@stacksjs/ts-cloud 0.16.16 → 0.16.17
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-m5wc1ent.js → chunk-1aqrfqbz.js} +1 -1
- package/dist/bin/{chunk-2943bszc.js → chunk-1k1dyh5k.js} +1 -1
- package/dist/bin/{chunk-2v91xnqx.js → chunk-30jk87p4.js} +2 -2
- package/dist/bin/{chunk-n02421y9.js → chunk-36aywmsq.js} +1 -1
- package/dist/bin/{chunk-80295akq.js → chunk-6wc8a9cs.js} +2 -2
- package/dist/bin/chunk-71rdf1sw.js +1 -0
- package/dist/bin/{chunk-vx9mmpaz.js → chunk-75kmf1ke.js} +1 -1
- package/dist/bin/chunk-7q37vt87.js +1 -0
- package/dist/bin/{chunk-gv9deppc.js → chunk-850n63e0.js} +2 -2
- package/dist/bin/{chunk-tfasfg4a.js → chunk-8af2sky9.js} +1 -1
- package/dist/bin/chunk-8r0gvent.js +1 -0
- package/dist/bin/{chunk-v93xyx1p.js → chunk-925xkkf9.js} +1 -1
- package/dist/bin/{chunk-tc24txss.js → chunk-94pvxv17.js} +1 -1
- package/dist/bin/{chunk-zzmk290g.js → chunk-98m9rbpk.js} +28 -28
- package/dist/bin/{chunk-cs6a98r1.js → chunk-afzrsjmc.js} +2 -2
- package/dist/bin/chunk-am4recks.js +1 -0
- package/dist/bin/chunk-az3emrhh.js +1 -0
- package/dist/bin/chunk-btfh77e4.js +1 -0
- package/dist/bin/{chunk-khta83xb.js → chunk-bxfnhnqd.js} +13 -13
- package/dist/bin/chunk-bxy657va.js +1 -0
- package/dist/bin/{chunk-2w591cvg.js → chunk-d5sd5xtt.js} +1 -1
- package/dist/bin/{chunk-pd8tk3z5.js → chunk-dg918k6w.js} +1 -1
- package/dist/bin/{chunk-xxf1vhfr.js → chunk-e7kqxsqh.js} +1 -1
- package/dist/bin/{chunk-y4c26gaf.js → chunk-etvcw9we.js} +1 -1
- package/dist/bin/{chunk-dczw0nxw.js → chunk-evtcxme1.js} +4 -4
- package/dist/bin/chunk-fbhf8kh5.js +1 -0
- package/dist/bin/{chunk-bhay1f8a.js → chunk-frbwzrx4.js} +1 -1
- package/dist/bin/{chunk-j0wfftk1.js → chunk-fren71ry.js} +1 -1
- package/dist/bin/{chunk-fddwwac7.js → chunk-g0z3a0wx.js} +1 -1
- package/dist/bin/{chunk-b3yp7bak.js → chunk-g8yaztb1.js} +1 -1
- package/dist/bin/{chunk-edfh9ts2.js → chunk-g954ew3x.js} +1 -1
- package/dist/bin/{chunk-tvv6vdx6.js → chunk-gn745j0p.js} +1 -1
- package/dist/bin/{chunk-j76935z3.js → chunk-hn961k5f.js} +3 -3
- package/dist/bin/{chunk-vx9qk1g1.js → chunk-jq36fh46.js} +1 -1
- package/dist/bin/{chunk-zacbzz1w.js → chunk-kymrvq47.js} +1 -1
- package/dist/bin/chunk-mtbav1sg.js +1 -0
- package/dist/bin/chunk-pk2xwzke.js +1 -0
- package/dist/bin/{chunk-whww424p.js → chunk-q6cayjpr.js} +75 -75
- package/dist/bin/{chunk-90c3rkd8.js → chunk-r2vrq2gr.js} +4 -4
- package/dist/bin/{chunk-yk4p2k8w.js → chunk-rt51mrj9.js} +1 -1
- package/dist/bin/chunk-s5br13d9.js +724 -0
- package/dist/bin/chunk-sbhbne4d.js +1 -0
- package/dist/bin/chunk-sd0twb8d.js +1 -0
- package/dist/bin/chunk-va8pr0ch.js +1 -0
- package/dist/bin/{chunk-fjz07v7g.js → chunk-va9y882b.js} +1 -1
- package/dist/bin/chunk-vwa96q94.js +1 -0
- package/dist/bin/{chunk-3qfd0vnc.js → chunk-xenj3py3.js} +3 -3
- package/dist/bin/chunk-y6vnwk4e.js +1 -0
- package/dist/bin/chunk-y7w98fc1.js +1 -0
- package/dist/bin/chunk-yw65b70x.js +1 -0
- package/dist/bin/{chunk-3x4p2s2r.js → chunk-z4rx32w4.js} +1 -1
- package/dist/bin/chunk-z65rp2mn.js +1 -0
- package/dist/bin/{chunk-1baj8p0r.js → chunk-znfh0mx7.js} +1 -1
- package/dist/bin/cli.js +118 -118
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/{chunk-a6aw2jtz.js → chunk-1ayadqry.js} +6 -6
- package/dist/{chunk-jgv0x24e.js → chunk-2ht2ve4t.js} +1 -1
- package/dist/{chunk-emx1j2yt.js → chunk-2vr8rqg8.js} +1 -1
- package/dist/chunk-3jrvr0pv.js +1 -0
- package/dist/{chunk-6eq5xfcx.js → chunk-3rh4m6ag.js} +1 -1
- package/dist/chunk-4bcf62qk.js +584 -0
- package/dist/{chunk-ss4q8kge.js → chunk-590gwv9d.js} +4 -4
- package/dist/{chunk-0bbrbzf9.js → chunk-6jzg0gtw.js} +4 -4
- package/dist/{chunk-jncbm332.js → chunk-6m18fz5f.js} +85 -85
- package/dist/{chunk-a21phhyj.js → chunk-81yetzg2.js} +3 -3
- package/dist/{chunk-fdn4wnd8.js → chunk-84w9n41b.js} +7 -7
- package/dist/{chunk-gn42mekr.js → chunk-a9pqpqrh.js} +1 -1
- package/dist/chunk-ajwt2hzh.js +1 -0
- package/dist/{chunk-4twnkjyq.js → chunk-enhddb1a.js} +2 -2
- package/dist/{chunk-g0yyw5k8.js → chunk-f3hhmec2.js} +1 -1
- package/dist/{chunk-z87dekhm.js → chunk-fw9hk0xt.js} +2 -2
- package/dist/{chunk-gstz8w2d.js → chunk-hasa64d4.js} +2 -2
- package/dist/{chunk-whwg2nzb.js → chunk-m1x32x81.js} +5 -5
- package/dist/chunk-mcxmdch0.js +1 -0
- package/dist/{chunk-4xta1s4z.js → chunk-mytcpvg5.js} +1 -1
- package/dist/{chunk-rmn71xjb.js → chunk-nca98yaf.js} +20 -20
- package/dist/{chunk-yxn6tpbg.js → chunk-nz3ygqjb.js} +1 -1
- package/dist/{chunk-pekptc1b.js → chunk-pn8bczhy.js} +5 -5
- package/dist/{chunk-sm5rn3db.js → chunk-r2v44ba2.js} +19 -19
- package/dist/chunk-wqhhvh3k.js +1 -0
- package/dist/{chunk-rgw06xbk.js → chunk-x3xs6qvx.js} +4 -4
- package/dist/chunk-xhn2v84m.js +1 -0
- package/dist/{chunk-fz70vxrk.js → chunk-ygrxsjcz.js} +2 -2
- package/dist/{chunk-wdrqt329.js → chunk-ynjfj2rt.js} +112 -112
- package/dist/{chunk-v9t92ak2.js → chunk-z13hksc9.js} +2 -2
- package/dist/deploy/index.js +1 -1
- package/dist/dns/index.js +1 -1
- package/dist/drivers/index.d.ts +2 -0
- package/dist/drivers/index.js +1 -1
- package/dist/drivers/shared/deploy-script.d.ts +7 -5
- package/dist/drivers/shared/host-cleanup.d.ts +90 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +21 -21
- package/dist/operations/index.js +1 -1
- package/dist/protection/index.js +1 -1
- package/dist/spend/index.js +1 -1
- package/dist/ui/404.html +1 -1
- package/dist/ui/accept-invitation.html +1 -1
- package/dist/ui/access-denied.html +1 -1
- package/dist/ui/account/automation.html +5 -5
- package/dist/ui/account/security.html +2 -2
- package/dist/ui/applications/compose.html +6 -6
- package/dist/ui/applications/new.html +2 -2
- package/dist/ui/data/backups.html +6 -6
- package/dist/ui/data/services.html +6 -6
- package/dist/ui/data/volumes.html +6 -6
- package/dist/ui/index.html +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 +6 -6
- package/dist/ui/operations/jobs.html +6 -6
- package/dist/ui/operations/maintenance.html +6 -6
- package/dist/ui/operations/observability.html +6 -6
- package/dist/ui/operations/previews.html +6 -6
- package/dist/ui/operations/queue.html +6 -6
- package/dist/ui/operations/regions.html +6 -6
- package/dist/ui/operations/releases.html +6 -6
- package/dist/ui/operations/spend.html +6 -6
- package/dist/ui/operations/workloads.html +6 -6
- package/dist/ui/security.html +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 +5 -5
- package/dist/ui/server/deployments.html +5 -5
- package/dist/ui/server/diagnostics.html +2 -2
- package/dist/ui/server/firewall.html +6 -6
- package/dist/ui/server/fleet.html +5 -5
- package/dist/ui/server/logs.html +6 -6
- package/dist/ui/server/metrics.html +5 -5
- package/dist/ui/server/security.html +2 -2
- package/dist/ui/server/services.html +2 -2
- package/dist/ui/server/sites.html +5 -5
- package/dist/ui/server/ssh-keys.html +6 -6
- package/dist/ui/server/team.html +6 -6
- package/dist/ui/server/terminal.html +2 -2
- package/dist/ui/serverless/alarms.html +6 -6
- package/dist/ui/serverless/assets.html +2 -2
- package/dist/ui/serverless/cost.html +2 -2
- package/dist/ui/serverless/data.html +6 -6
- package/dist/ui/serverless/deployments.html +2 -2
- package/dist/ui/serverless/firewall.html +2 -2
- package/dist/ui/serverless/functions.html +6 -6
- package/dist/ui/serverless/logs.html +6 -6
- package/dist/ui/serverless/metrics.html +2 -2
- package/dist/ui/serverless/queues.html +6 -6
- package/dist/ui/serverless/secrets.html +6 -6
- package/dist/ui/serverless/traces.html +6 -6
- package/dist/ui/serverless.html +6 -6
- package/package.json +3 -3
- package/dist/bin/chunk-2tn43y0d.js +0 -1
- package/dist/bin/chunk-4v6f496n.js +0 -1
- package/dist/bin/chunk-64cdtvar.js +0 -1
- package/dist/bin/chunk-66egshmp.js +0 -1
- package/dist/bin/chunk-7raskz63.js +0 -1
- package/dist/bin/chunk-9bxyy4th.js +0 -1
- package/dist/bin/chunk-bbt0vyzj.js +0 -1
- package/dist/bin/chunk-cpcae7e2.js +0 -1
- package/dist/bin/chunk-dsc7ef1w.js +0 -1
- package/dist/bin/chunk-f2wn46nw.js +0 -1
- package/dist/bin/chunk-ffcyj2jj.js +0 -1
- package/dist/bin/chunk-gbejgj71.js +0 -1
- package/dist/bin/chunk-kjbkwzxd.js +0 -1
- package/dist/bin/chunk-knthwdhz.js +0 -1
- package/dist/bin/chunk-nm000jpj.js +0 -725
- package/dist/bin/chunk-pjgbnk3q.js +0 -1
- package/dist/bin/chunk-rn0pgnt4.js +0 -1
- package/dist/bin/chunk-xtzy90zh.js +0 -1
- package/dist/bin/chunk-z6mnhd0j.js +0 -1
- package/dist/chunk-051jwkd2.js +0 -1
- package/dist/chunk-1gne7rkf.js +0 -1
- package/dist/chunk-38c310s1.js +0 -1
- package/dist/chunk-acpxtkfy.js +0 -585
- package/dist/chunk-dk3t3hgq.js +0 -1
- package/dist/chunk-qc2v4h2q.js +0 -1
|
@@ -1,26 +1,26 @@
|
|
|
1
|
-
import{createRequire as ar}from"node:module";import{isAbsolute as $t,join as ut,relative as ur}from"node:path";import{existsSync as Ge,readdirSync as Rr}from"node:fs";import{join as ce}from"node:path";import{createHash as Gr}from"node:crypto";import{copyFileSync as Fr,existsSync as Ct,readdirSync as Ur,readFileSync as tt,statSync as Vr,writeFileSync as at}from"node:fs";import{basename as jr,dirname as pa,extname as ga,join as Fe}from"node:path";import{existsSync as Oa,readFileSync as Gt}from"node:fs";import{homedir as Ba}from"node:os";import{join as _a}from"node:path";import{createHash as Wa}from"node:crypto";import{existsSync as nt,mkdirSync as qn,readdirSync as Sa,readFileSync as ba,unlinkSync as Ve,writeFileSync as Hn}from"node:fs";import{join as It}from"node:path";import{createHash as Kt}from"node:crypto";import{createReadStream as zn,readdirSync as Qn,statSync as dt}from"node:fs";import{join as Jn,relative as Yn}from"node:path";import{deflateRawSync as oi}from"node:zlib";import{execSync as Ci}from"node:child_process";import{createHash as Ti}from"node:crypto";import{cpSync as vi,mkdtempSync as wi,rmSync as Ei,writeFileSync as Pi}from"node:fs";import{tmpdir as Ii}from"node:os";import{dirname as Ri,isAbsolute as Ni,join as Ie,resolve as Di}from"node:path";import{fileURLToPath as ki}from"node:url";import{execFileSync as ht}from"node:child_process";import{mkdtempSync as Ua,readFileSync as yt,rmSync as Va}from"node:fs";import{tmpdir as ja}from"node:os";import{dirname as xi,join as ue}from"node:path";import{fileURLToPath as Oi}from"node:url";import{AsyncLocalStorage as _i}from"node:async_hooks";import{createHash as Wi}from"node:crypto";import{readFileSync as Ki}from"node:fs";import{dirname as qi,join as Qa}from"node:path";import{fileURLToPath as Hi}from"node:url";import{execFileSync as it}from"node:child_process";import{existsSync as Qi,mkdirSync as Ji,mkdtempSync as Yi,readdirSync as Zi,readFileSync as Xi,rmSync as es,statSync as Ja,writeFileSync as ts}from"node:fs";import{tmpdir as as}from"node:os";import{join as Re,relative as rs}from"node:path";import{execSync as ns}from"node:child_process";import{createHash as is}from"node:crypto";import{readdirSync as ss,readFileSync as os,statSync as Xa}from"node:fs";import{join as cs,relative as er,resolve as ma}from"node:path";var rr=Object.defineProperty,nr=(e)=>e;function ir(e,a){this[e]=nr.bind(null,a)}var xe=(e,a)=>{for(var r in a)rr(e,r,{get:a[r],enumerable:!0,configurable:!0,set:ir.bind(a,r)})},sr=(e,a,r)=>()=>{if(e)try{a=e(e=0)}catch(n){r=[n]}if(r)throw r[0];return a},or=ar(import.meta.url);function Za(e){let a=typeof e==="string"?new URL(e):e,{hostname:r,pathname:n}=a;if(r.endsWith(".on.aws")){let u=r.match(/^[^.]+\.lambda-url\.([^.]+)\.on\.aws$/);if(u)return{service:"lambda",region:u[1]};return{service:"",region:""}}if(r.endsWith(".r2.cloudflarestorage.com"))return{service:"s3",region:"auto"};if(r.endsWith(".backblazeb2.com")){let u=r.match(/^(?:[^.]+\.)?s3\.([^.]+)\.backblazeb2\.com$/);if(u)return{service:"s3",region:u[1]};return{service:"",region:""}}let i=r.replace("dualstack.","").match(/([^.]+)\.(?:([^.]+)\.)?amazonaws\.com(?:\.cn)?$/);if(!i)return{service:"",region:""};let o=i[1],c=i[2]||"";if(c==="us-gov")c="us-gov-west-1";else if(c==="s3"||c==="s3-accelerate")c="us-east-1",o="s3";else if(o==="iot")if(r.startsWith("iot."))o="execute-api";else if(r.startsWith("data.jobs.iot."))o="iot-jobs-data";else o=n==="/mqtt"?"iotdevicegateway":"iotdata";else if(o==="autoscaling");else if(!c&&o.startsWith("s3-"))c=o.slice(3).replace(/^fips-|^external-1/,""),o="s3";else if(o.endsWith("-fips"))o=o.slice(0,-5);else if(c&&/-\d$/.test(o)&&!/-\d$/.test(c))[o,c]=[c,o];return o=Na[o]||o,{service:o,region:c||"us-east-1"}}function oe(e){let{method:a,url:r,body:n="",accessKeyId:i,secretAccessKey:o,sessionToken:c,signQuery:u=!1,expiresIn:d=86400,datetime:m}=e,p=new URL(r),g=p.hostname,h=Za(p),y=e.service||h.service,f=e.region||h.region;if(!y)throw Error("Could not detect service from URL. Please provide service explicitly.");if(!f)throw Error("Could not detect region from URL. Please provide region explicitly.");let b=m||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),v=b.substring(0,8),w=[v,f,y,"aws4_request"].join("/"),R="AWS4-HMAC-SHA256";if(u)return cr({urlObj:p,method:a,body:n,accessKeyId:i,secretAccessKey:o,sessionToken:c,service:y,region:f,timestamp:b,date:v,credentialScope:w,algorithm:R,expiresIn:d,cache:e.cache});let T=p.pathname||"/",N=pt(p.searchParams),I={host:g,"x-amz-date":b,...e.headers};if(c)I["x-amz-security-token"]=c;let k=Object.keys(I).some((de)=>de.toLowerCase()==="content-type");if(n&&!k)I["content-type"]="application/x-amz-json-1.0";if(y==="s3"&&!I["x-amz-content-sha256"])I["x-amz-content-sha256"]=Ke(n);let
|
|
1
|
+
import{createRequire as ar}from"node:module";import{isAbsolute as $t,join as ut,relative as ur}from"node:path";import{existsSync as Ge,readdirSync as Rr}from"node:fs";import{join as ce}from"node:path";import{createHash as Gr}from"node:crypto";import{copyFileSync as Fr,existsSync as Ct,readdirSync as Ur,readFileSync as tt,statSync as Vr,writeFileSync as at}from"node:fs";import{basename as jr,dirname as pa,extname as ga,join as Fe}from"node:path";import{existsSync as Oa,readFileSync as Gt}from"node:fs";import{homedir as Ba}from"node:os";import{join as _a}from"node:path";import{createHash as Wa}from"node:crypto";import{existsSync as nt,mkdirSync as qn,readdirSync as Sa,readFileSync as ba,unlinkSync as Ve,writeFileSync as Hn}from"node:fs";import{join as It}from"node:path";import{createHash as Kt}from"node:crypto";import{createReadStream as zn,readdirSync as Qn,statSync as dt}from"node:fs";import{join as Jn,relative as Yn}from"node:path";import{deflateRawSync as oi}from"node:zlib";import{execSync as Ci}from"node:child_process";import{createHash as Ti}from"node:crypto";import{cpSync as vi,mkdtempSync as wi,rmSync as Ei,writeFileSync as Pi}from"node:fs";import{tmpdir as Ii}from"node:os";import{dirname as Ri,isAbsolute as Ni,join as Ie,resolve as Di}from"node:path";import{fileURLToPath as ki}from"node:url";import{execFileSync as ht}from"node:child_process";import{mkdtempSync as Ua,readFileSync as yt,rmSync as Va}from"node:fs";import{tmpdir as ja}from"node:os";import{dirname as xi,join as ue}from"node:path";import{fileURLToPath as Oi}from"node:url";import{AsyncLocalStorage as _i}from"node:async_hooks";import{createHash as Wi}from"node:crypto";import{readFileSync as Ki}from"node:fs";import{dirname as qi,join as Qa}from"node:path";import{fileURLToPath as Hi}from"node:url";import{execFileSync as it}from"node:child_process";import{existsSync as Qi,mkdirSync as Ji,mkdtempSync as Yi,readdirSync as Zi,readFileSync as Xi,rmSync as es,statSync as Ja,writeFileSync as ts}from"node:fs";import{tmpdir as as}from"node:os";import{join as Re,relative as rs}from"node:path";import{execSync as ns}from"node:child_process";import{createHash as is}from"node:crypto";import{readdirSync as ss,readFileSync as os,statSync as Xa}from"node:fs";import{join as cs,relative as er,resolve as ma}from"node:path";var rr=Object.defineProperty,nr=(e)=>e;function ir(e,a){this[e]=nr.bind(null,a)}var xe=(e,a)=>{for(var r in a)rr(e,r,{get:a[r],enumerable:!0,configurable:!0,set:ir.bind(a,r)})},sr=(e,a,r)=>()=>{if(e)try{a=e(e=0)}catch(n){r=[n]}if(r)throw r[0];return a},or=ar(import.meta.url);function Za(e){let a=typeof e==="string"?new URL(e):e,{hostname:r,pathname:n}=a;if(r.endsWith(".on.aws")){let u=r.match(/^[^.]+\.lambda-url\.([^.]+)\.on\.aws$/);if(u)return{service:"lambda",region:u[1]};return{service:"",region:""}}if(r.endsWith(".r2.cloudflarestorage.com"))return{service:"s3",region:"auto"};if(r.endsWith(".backblazeb2.com")){let u=r.match(/^(?:[^.]+\.)?s3\.([^.]+)\.backblazeb2\.com$/);if(u)return{service:"s3",region:u[1]};return{service:"",region:""}}let i=r.replace("dualstack.","").match(/([^.]+)\.(?:([^.]+)\.)?amazonaws\.com(?:\.cn)?$/);if(!i)return{service:"",region:""};let o=i[1],c=i[2]||"";if(c==="us-gov")c="us-gov-west-1";else if(c==="s3"||c==="s3-accelerate")c="us-east-1",o="s3";else if(o==="iot")if(r.startsWith("iot."))o="execute-api";else if(r.startsWith("data.jobs.iot."))o="iot-jobs-data";else o=n==="/mqtt"?"iotdevicegateway":"iotdata";else if(o==="autoscaling");else if(!c&&o.startsWith("s3-"))c=o.slice(3).replace(/^fips-|^external-1/,""),o="s3";else if(o.endsWith("-fips"))o=o.slice(0,-5);else if(c&&/-\d$/.test(o)&&!/-\d$/.test(c))[o,c]=[c,o];return o=Na[o]||o,{service:o,region:c||"us-east-1"}}function oe(e){let{method:a,url:r,body:n="",accessKeyId:i,secretAccessKey:o,sessionToken:c,signQuery:u=!1,expiresIn:d=86400,datetime:m}=e,p=new URL(r),g=p.hostname,h=Za(p),y=e.service||h.service,f=e.region||h.region;if(!y)throw Error("Could not detect service from URL. Please provide service explicitly.");if(!f)throw Error("Could not detect region from URL. Please provide region explicitly.");let b=m||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),v=b.substring(0,8),w=[v,f,y,"aws4_request"].join("/"),R="AWS4-HMAC-SHA256";if(u)return cr({urlObj:p,method:a,body:n,accessKeyId:i,secretAccessKey:o,sessionToken:c,service:y,region:f,timestamp:b,date:v,credentialScope:w,algorithm:R,expiresIn:d,cache:e.cache});let T=p.pathname||"/",N=pt(p.searchParams),I={host:g,"x-amz-date":b,...e.headers};if(c)I["x-amz-security-token"]=c;let k=Object.keys(I).some((de)=>de.toLowerCase()==="content-type");if(n&&!k)I["content-type"]="application/x-amz-json-1.0";if(y==="s3"&&!I["x-amz-content-sha256"])I["x-amz-content-sha256"]=Ke(n);let O=Ta(I),L=va(I),_=I["x-amz-content-sha256"]||Ke(n),W=[a,gt(T),N,O,L,_].join(`
|
|
2
2
|
`),K=Ke(W),Z=[R,b,w,K].join(`
|
|
3
|
-
`),z=e.cache??ye,J=Ea(o,v,f,y,Z,z),q=[`${R} Credential=${i}/${w}`,`SignedHeaders=${L}`,`Signature=${J}`].join(", ");return I.authorization=q,{url:r,method:a,headers:I,body:n||void 0}}async function ec(e){let{method:a,url:r,body:n="",accessKeyId:i,secretAccessKey:o,sessionToken:c,signQuery:u=!1,expiresIn:d=86400,datetime:m}=e,p=new URL(r),g=p.hostname,h=Za(p),y=e.service||h.service,f=e.region||h.region;if(!y)throw Error("Could not detect service from URL. Please provide service explicitly.");if(!f)throw Error("Could not detect region from URL. Please provide region explicitly.");let b=m||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),v=b.substring(0,8),w=[v,f,y,"aws4_request"].join("/"),R="AWS4-HMAC-SHA256";if(u)return lr({urlObj:p,method:a,body:n,accessKeyId:i,secretAccessKey:o,sessionToken:c,service:y,region:f,timestamp:b,date:v,credentialScope:w,algorithm:R,expiresIn:d,cache:e.cache});let T=p.pathname||"/",N=pt(p.searchParams),I={host:g,"x-amz-date":b,...e.headers};if(c)I["x-amz-security-token"]=c;let k=Object.keys(I).some((Oe)=>Oe.toLowerCase()==="content-type");if(n&&!k)I["content-type"]="application/x-amz-json-1.0";let
|
|
3
|
+
`),z=e.cache??ye,J=Ea(o,v,f,y,Z,z),q=[`${R} Credential=${i}/${w}`,`SignedHeaders=${L}`,`Signature=${J}`].join(", ");return I.authorization=q,{url:r,method:a,headers:I,body:n||void 0}}async function ec(e){let{method:a,url:r,body:n="",accessKeyId:i,secretAccessKey:o,sessionToken:c,signQuery:u=!1,expiresIn:d=86400,datetime:m}=e,p=new URL(r),g=p.hostname,h=Za(p),y=e.service||h.service,f=e.region||h.region;if(!y)throw Error("Could not detect service from URL. Please provide service explicitly.");if(!f)throw Error("Could not detect region from URL. Please provide region explicitly.");let b=m||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),v=b.substring(0,8),w=[v,f,y,"aws4_request"].join("/"),R="AWS4-HMAC-SHA256";if(u)return lr({urlObj:p,method:a,body:n,accessKeyId:i,secretAccessKey:o,sessionToken:c,service:y,region:f,timestamp:b,date:v,credentialScope:w,algorithm:R,expiresIn:d,cache:e.cache});let T=p.pathname||"/",N=pt(p.searchParams),I={host:g,"x-amz-date":b,...e.headers};if(c)I["x-amz-security-token"]=c;let k=Object.keys(I).some((Oe)=>Oe.toLowerCase()==="content-type");if(n&&!k)I["content-type"]="application/x-amz-json-1.0";let O=await ot(n);if(y==="s3"&&!I["x-amz-content-sha256"])I["x-amz-content-sha256"]=O;let L=Ta(I),_=va(I),W=I["x-amz-content-sha256"]||O,K=[a,gt(T),N,L,_,W].join(`
|
|
4
4
|
`),Z=await ot(K),z=[R,b,w,Z].join(`
|
|
5
|
-
`),J=e.cache??ye,q=await Pa(o,v,f,y,z,J),de=[`${R} Credential=${i}/${w}`,`SignedHeaders=${
|
|
5
|
+
`),J=e.cache??ye,q=await Pa(o,v,f,y,z,J),de=[`${R} Credential=${i}/${w}`,`SignedHeaders=${_}`,`Signature=${q}`].join(", ");return I.authorization=de,{url:r,method:a,headers:I,body:n||void 0}}function cr(e){let{urlObj:a,method:r,body:n,accessKeyId:i,secretAccessKey:o,sessionToken:c,service:u,region:d,timestamp:m,date:p,credentialScope:g,algorithm:h,expiresIn:y,cache:f}=e,b=new URL(a.toString());b.searchParams.set("X-Amz-Algorithm",h),b.searchParams.set("X-Amz-Credential",`${i}/${g}`),b.searchParams.set("X-Amz-Date",m),b.searchParams.set("X-Amz-Expires",String(y));let v=u==="s3"?"UNSIGNED-PAYLOAD":Ke(n);if(u==="s3")b.searchParams.set("X-Amz-Content-Sha256",v);let w="host";if(b.searchParams.set("X-Amz-SignedHeaders",w),c)b.searchParams.set("X-Amz-Security-Token",c);let R=gt(b.pathname||"/"),T=`host:${b.hostname}
|
|
6
6
|
`,N=pt(b.searchParams),I=[r,R,N,T,w,v].join(`
|
|
7
7
|
`),k=[h,m,g,Ke(I)].join(`
|
|
8
|
-
`),
|
|
8
|
+
`),O=Ea(o,p,d,u,k,f??ye);return b.searchParams.set("X-Amz-Signature",O),{url:b.toString(),method:r,headers:{},body:n||void 0}}async function lr(e){let{urlObj:a,method:r,body:n,accessKeyId:i,secretAccessKey:o,sessionToken:c,service:u,region:d,timestamp:m,date:p,credentialScope:g,algorithm:h,expiresIn:y,cache:f}=e,b=new URL(a.toString());b.searchParams.set("X-Amz-Algorithm",h),b.searchParams.set("X-Amz-Credential",`${i}/${g}`),b.searchParams.set("X-Amz-Date",m),b.searchParams.set("X-Amz-Expires",String(y));let v=u==="s3"?"UNSIGNED-PAYLOAD":await ot(n);if(u==="s3")b.searchParams.set("X-Amz-Content-Sha256",v);let w="host";if(b.searchParams.set("X-Amz-SignedHeaders",w),c)b.searchParams.set("X-Amz-Security-Token",c);let R=gt(b.pathname||"/"),T=`host:${b.hostname}
|
|
9
9
|
`,N=pt(b.searchParams),I=[r,R,N,T,w,v].join(`
|
|
10
10
|
`),k=[h,m,g,await ot(I)].join(`
|
|
11
|
-
`),
|
|
11
|
+
`),O=await Pa(o,p,d,u,k,f??ye);return b.searchParams.set("X-Amz-Signature",O),{url:b.toString(),method:r,headers:{},body:n||void 0}}function cd(e){let{url:a,method:r="GET",expiresIn:n=3600,...i}=e,o=Math.min(n,604800);return oe({...i,url:a,method:r,signQuery:!0,expiresIn:o}).url}async function Ku(e){let{url:a,method:r="GET",expiresIn:n=3600,...i}=e,o=Math.min(n,604800);return(await ec({...i,url:a,method:r,signQuery:!0,expiresIn:o})).url}function Ta(e){return Object.keys(e).sort().map((a)=>`${a.toLowerCase()}:${e[a].trim().replace(/\s+/g," ")}`).join(`
|
|
12
12
|
`)+`
|
|
13
|
-
`}function va(e){return Object.keys(e).sort().map((a)=>a.toLowerCase()).join(";")}function pt(e){let a=[];return e.forEach((r,n)=>{a.push([kt(n),kt(r)])}),a.sort((r,n)=>{if(r[0]<n[0])return-1;if(r[0]>n[0])return 1;if(r[1]<n[1])return-1;if(r[1]>n[1])return 1;return 0}),a.map(([r,n])=>`${r}=${n}`).join("&")}function gt(e){return e.split("/").map((a)=>kt(a)).join("/")}function kt(e){return encodeURIComponent(e).replace(/[!'()*]/g,(a)=>`%${a.charCodeAt(0).toString(16).toUpperCase()}`)}function Ke(e){if(!$e)throw Error("Synchronous hash not available in browser. Use signRequestAsync() instead.");return $e.createHash("sha256").update(e,"utf8").digest("hex")}function _e(e,a){if(!$e)throw Error("Synchronous hmac not available in browser. Use signRequestAsync() instead.");return $e.createHmac("sha256",e).update(a,"utf8").digest()}async function ot(e){let a=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",a);return wa(new Uint8Array(r))}async function We(e,a){let r=new TextEncoder,n=typeof e==="string"?r.encode(e):e,i=r.encode(a),o=await crypto.subtle.importKey("raw",n.buffer,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),c=await crypto.subtle.sign("HMAC",o,i.buffer);return new Uint8Array(c)}function wa(e){return Array.from(e).map((a)=>a.toString(16).padStart(2,"0")).join("")}function Ea(e,a,r,n,i,o){let c=`${e}:${a}:${r}:${n}`,u=o.get(c);if(!u){let d=_e(`AWS4${e}`,a),m=_e(d,r),p=_e(m,n);if(u=_e(p,"aws4_request"),o.size>=Ra){let g=o.keys().next().value;if(g)o.delete(g)}o.set(c,u)}return _e(u,i).toString("hex")}async function Pa(e,a,r,n,i,o){let c=`${e}:${a}:${r}:${n}`,u=o.get(c);if(!u){let m=await We(`AWS4${e}`,a),p=await We(m,r),g=await We(p,n);if(u=await We(g,"aws4_request"),o.size>=Ra){let h=o.keys().next().value;if(h)o.delete(h)}o.set(c,u)}let d=await We(u,i);return wa(d)}function Ia(e,a){return a.includes(e)}function ct(e,a,r){let n=a*Math.pow(2,e),i=Math.random()*0.3*n;return Math.min(n+i,r)}function lt(e){return new Promise((a)=>setTimeout(a,e))}async function ui(e,a){let{maxRetries:r=3,initialDelayMs:n=100,maxDelayMs:i=5000,retryableStatusCodes:o=[429,500,502,503,504],timeoutMs:c=30000}=a??{},u,d;for(let m=0;m<=r;m++){let p=oe(e),g={method:p.method,headers:p.headers};if(p.body)g.body=p.body;let h=new AbortController,y=setTimeout(()=>h.abort(),c);g.signal=h.signal;try{let f=await fetch(p.url,g);if(clearTimeout(y),d=f,f.ok)return f;if(m<r&&Ia(f.status,o)){let v=ct(m,n,i);await lt(v);continue}let b=await f.text();throw Error(`AWS API request failed (${f.status}): ${b}`)}catch(f){if(clearTimeout(y),u=f,f instanceof Error&&f.name==="AbortError")u=Error(`Request timed out after ${c}ms`);if(m<r&&!(f instanceof Error&&f.message.includes("AWS API request failed"))){let b=ct(m,n,i);await lt(b);continue}throw u}}throw u??Error("Request failed after retries")}async function Ju(e){return ui(e,{maxRetries:0})}async function Xu(e,a){let{maxRetries:r=3,initialDelayMs:n=100,maxDelayMs:i=5000,retryableStatusCodes:o=[429,500,502,503,504],timeoutMs:c=30000}=a??{},u;for(let d=0;d<=r;d++){let m=await ec(e),p={method:m.method,headers:m.headers};if(m.body)p.body=m.body;let g=new AbortController,h=setTimeout(()=>g.abort(),c);p.signal=g.signal;try{let y=await fetch(m.url,p);if(clearTimeout(h),y.ok)return y;if(d<r&&Ia(y.status,o)){let b=ct(d,n,i);await lt(b);continue}let f=await y.text();throw Error(`AWS API request failed (${y.status}): ${f}`)}catch(y){if(clearTimeout(h),u=y,y instanceof Error&&y.name==="AbortError")u=Error(`Request timed out after ${c}ms`);if(d<r&&!(y instanceof Error&&y.message.includes("AWS API request failed"))){let f=ct(d,n,i);await lt(f);continue}throw u}}throw u??Error("Request failed after retries")}async function Os(e){let a=await e.text(),r={},n=/<(\w+)>([^<]+)<\/\1>/g,i;while((i=n.exec(a))!==null){let[,o,c]=i;r[o]=c}return r}async function Qu(e){return await e.json()}function Yu(){ye.clear()}function Zu(){return ye.size}function ep(){return $e!==void 0}function tp(){return typeof crypto<"u"&&typeof crypto.subtle<"u"}var $e,ye,Ra=100,Na,Qe=sr(async()=>{try{$e=await import("node:crypto")}catch{}ye=new Map,Na={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"}}),rp={backgroundJobs:{visibilityTimeout:120,messageRetentionPeriod:604800,deadLetterQueue:!0,maxReceiveCount:3,encrypted:!0},fifo:{fifo:!0,contentBasedDeduplication:!0,visibilityTimeout:30,encrypted:!0},highThroughput:{visibilityTimeout:30,receiveMessageWaitTime:20,encrypted:!0},delayed:{delaySeconds:60,visibilityTimeout:60,encrypted:!0},longRunning:{visibilityTimeout:900,messageRetentionPeriod:1209600,deadLetterQueue:!0,maxReceiveCount:2,encrypted:!0},monitored:{visibilityTimeout:60,messageRetentionPeriod:604800,deadLetterQueue:!0,maxReceiveCount:3,encrypted:!0,alarms:{enabled:!0,queueDepthThreshold:1000,messageAgeThreshold:3600,dlqAlarm:!0}},lambdaOptimized:{visibilityTimeout:360,receiveMessageWaitTime:20,deadLetterQueue:!0,maxReceiveCount:3,encrypted:!0},fanOut:{visibilityTimeout:30,receiveMessageWaitTime:20,encrypted:!0}},np={serverless:{development:{enabled:!0,mode:"serverless",channels:{public:!0,private:!0,presence:!0},storage:{type:"dynamodb",dynamodb:{billingMode:"PAY_PER_REQUEST"}},scaling:{maxConnections:1000,handlerMemory:128}},production:{enabled:!0,mode:"serverless",channels:{public:!0,private:!0,presence:{enabled:!0,maxMembers:100,heartbeatInterval:30,inactivityTimeout:60}},storage:{type:"dynamodb",dynamodb:{billingMode:"PAY_PER_REQUEST",pointInTimeRecovery:!0,connectionTTL:86400}},scaling:{maxConnections:50000,messagesPerSecond:5000,handlerMemory:256,handlerTimeout:30},monitoring:{enabled:!0,connectionThreshold:40000,errorThreshold:100,latencyThreshold:500},keepAlive:!0,keepAliveInterval:30,idleTimeout:600},notifications:{enabled:!0,mode:"serverless",channels:{public:!1,private:!0,presence:!1},storage:{type:"dynamodb",dynamodb:{billingMode:"PAY_PER_REQUEST"}},scaling:{maxConnections:50000,messagesPerSecond:2000,handlerMemory:128},keepAlive:!0,keepAliveInterval:60,idleTimeout:1800}},server:{development:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"ws",driver:"bun",idleTimeout:120,perMessageDeflate:!1,metrics:!1}},production:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:120,maxPayloadLength:16777216,backpressureLimit:1048576,sendPings:!0,perMessageDeflate:!0,instances:2,redis:{enabled:!0,keyPrefix:"broadcasting:"},rateLimit:{enabled:!0,max:100,window:60000,perChannel:!0,perUser:!0},loadManagement:{enabled:!0,maxConnections:1e4,maxSubscriptionsPerConnection:100,shedLoadThreshold:0.8},metrics:!0,autoScaling:{min:2,max:10,targetCPU:70}},monitoring:{enabled:!0,connectionThreshold:8000,errorThreshold:100}},highPerformance:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:60,maxPayloadLength:8388608,backpressureLimit:2097152,closeOnBackpressureLimit:!0,sendPings:!0,perMessageDeflate:!0,instances:4,redis:{enabled:!0,useElastiCache:!0,keyPrefix:"rt:"},rateLimit:{enabled:!0,max:200,window:60000,perChannel:!0},loadManagement:{enabled:!0,maxConnections:25000,maxSubscriptionsPerConnection:50,shedLoadThreshold:0.7},metrics:{enabled:!0,path:"/metrics"},autoScaling:{min:4,max:20,targetCPU:60,targetConnections:20000}},monitoring:{enabled:!0,connectionThreshold:80000,errorThreshold:50,latencyThreshold:50}},chat:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:{enabled:!0,maxMembers:200,heartbeatInterval:20,inactivityTimeout:60}},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:300,maxPayloadLength:1048576,sendPings:!0,perMessageDeflate:!0,instances:2,redis:{enabled:!0,keyPrefix:"chat:"},rateLimit:{enabled:!0,max:60,window:60000,perChannel:!0},loadManagement:{enabled:!0,maxConnections:15000,maxSubscriptionsPerConnection:20},metrics:!0},keepAlive:!0,keepAliveInterval:25,idleTimeout:900},gaming:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:{enabled:!0,maxMembers:100,heartbeatInterval:10,inactivityTimeout:30}},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:30,maxPayloadLength:65536,backpressureLimit:524288,closeOnBackpressureLimit:!0,sendPings:!0,perMessageDeflate:!1,instances:4,redis:{enabled:!0,useElastiCache:!0},rateLimit:{enabled:!0,max:120,window:60000},loadManagement:{enabled:!0,maxConnections:5000,maxSubscriptionsPerConnection:10,shedLoadThreshold:0.6},metrics:!0,autoScaling:{min:4,max:16,targetCPU:50}},keepAlive:!0,keepAliveInterval:10,idleTimeout:60},single:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:120,sendPings:!0,perMessageDeflate:!0,instances:1,rateLimit:{enabled:!0,max:100,window:60000},loadManagement:{enabled:!0,maxConnections:1e4},metrics:!0}}}},tc=".ts-cloud",rc="TS_CLOUD_STATE_DIR",Ot=null;function Ls(e){Ot=e?.trim()||null}function Ms(){return Boolean(process.env[rc]?.trim()||Ot)}function yo(){return process.env[rc]?.trim()||Ot||tc}function Ye(...e){return ut(yo(),...e)}function A(e,...a){let r=yo();return $t(r)?ut(r,...a):ut(e,r,...a)}function Us(e,a=process.cwd()){let r=(i,o)=>{let c=ur(i,o);return c===""||!c.startsWith("..")&&!$t(c)},n=$t(e)?e:ut(a,e);return r(A(a),n)}function nc(e){let a=e.infrastructure?.compute!=null,r=Object.values(e.environments??{}).some((n)=>n?.app!=null);return{server:a,serverless:r}}function V(e){if(e.mode==="server"||e.mode==="serverless")return e.mode;let{serverless:a}=nc(e);return a?"serverless":"server"}function wr(e){let{server:a,serverless:r}=nc(e);if(a&&r)return"A project cannot be both a server and a serverless deployment. Found `infrastructure.compute` (server) AND `environments.<env>.app` (serverless Lambda). Keep one: remove `infrastructure.compute` for a serverless app, or remove `environments.<env>.app` for a server.";if(e.mode==="server"&&r&&!a)return"Config sets `mode: 'server'` but declares a serverless app (`environments.<env>.app`). Remove the app or change the mode.";if(e.mode==="serverless"&&a&&!r)return"Config sets `mode: 'serverless'` but declares a server (`infrastructure.compute`). Remove the compute block or change the mode.";return null}function C(e){return e.infrastructure?.appDatabase??e.infrastructure?.compute?.database}function dr(e){return typeof e==="object"&&e!==null?e:{}}function ld(e){return e===!0||typeof e==="object"&&e!==null}function mr(e,a){let r=a?e.environments?.[a]:void 0;if(r?.domain)return r.domain;let n=Object.values(e.sites??{}),i=e.sites?.main?.domain??n.find((o)=>o.domain)?.domain;if(i)return i;return`${e.project?.slug??"app"}.local`}function pr(e){let a=e.indexOf(".");return a>0?e.slice(a+1):void 0}function pi(e,a={}){let r=e.infrastructure?.compute?.managedServices?.mail,n=dr(r),i=a.environmentType??(a.environment?e.environments?.[a.environment]?.type:void 0),o=n.mode??(i==="production"?"server":"catcher"),c=o==="server",u=mr(e,a.environment),d=n.hostname??(c?`mail.${u}`:"localhost"),m=n.ports??{},p=c?{smtp:m.smtp??25,submission:m.submission??587,submissions:m.submissions??465,imap:m.imap??143,imaps:m.imaps??993,webmail:m.webmail??8080,managesieve:m.managesieve}:{smtp:m.smtp??1025,submission:m.submission,submissions:m.submissions,imap:m.imap,imaps:m.imaps,webmail:m.webmail??8025,managesieve:m.managesieve},g=n.tls??{},h=g.enabled??c,y=!!(g.certPath&&g.keyPath),f=(n.accounts??[]).map((L)=>({address:L.address,password:L.password})),b=typeof n.dkim==="object"&&n.dkim!==null?n.dkim:{},v=n.dkim===!1?!1:n.dkim===!0||c,w=typeof n.webmail==="object"&&n.webmail!==null?n.webmail:{},R=n.webmail===!1?!1:w.enabled??!0,T=n.spam??{},N=n.delivery??(c?"direct":"none"),I=n.expose??c,k=pr(d),x=[...new Set([d,...k?[k]:[],...n.domains??[]])];return{enabled:ld(r),mode:o,version:n.version,hostname:d,domains:x,ports:p,tls:{enabled:h,acme:h&&!y&&(g.acme??!0),certPath:g.certPath,keyPath:g.keyPath,requireForAuth:g.requireForAuth??(h&&c),acmeEmail:g.acmeEmail??f[0]?.address},dkim:{enabled:v,selector:b.selector??"default",rotate:b.rotate??!1,rotateIntervalDays:b.rotateIntervalDays??90},webmail:{enabled:R,port:w.port??p.webmail,domain:w.domain},delivery:N,sesRegion:n.sesRegion??"us-east-1",accounts:f,storagePath:n.storagePath??"/var/lib/mail",maxMessageSize:n.maxMessageSize??26214400,spam:{enabled:T.enabled??c,enforce:T.enforce??!1,junkScore:T.junkScore??5,rejectScore:T.rejectScore??12,dnsbl:T.dnsbl??c,greylist:T.greylist??!1},webhookUrl:n.webhookUrl,expose:I,bindAddress:I?"0.0.0.0":"127.0.0.1"}}function Bs(e){if(!e.enabled||!e.expose)return[];let a=[e.ports.smtp,e.ports.submission,e.ports.submissions,e.ports.imap,e.ports.imaps,e.ports.managesieve].filter((r)=>typeof r==="number");if(e.webmail.enabled&&!e.webmail.domain)a.push(e.webmail.port);return[...new Set(a)].sort((r,n)=>r-n)}function Fs(e){if(!e.enabled)return{};let a=e.ports.submission??e.ports.smtp,r={MAIL_MAILER:"smtp",MAIL_HOST:"127.0.0.1",MAIL_PORT:String(a)};if(e.mode==="server"){r.MAIL_ENCRYPTION=e.tls.enabled?"tls":"null";let n=e.accounts[0];if(n)r.MAIL_USERNAME=n.address,r.MAIL_PASSWORD=n.password}else r.MAIL_ENCRYPTION="null",r.MAIL_USERNAME="null",r.MAIL_PASSWORD="null";return r}function U(e){if(e.cloud?.provider)return e.cloud.provider;if(e.ssh?.hosts?.length)return"ssh";if(e.hetzner?.apiToken)return"hetzner";return"aws"}class So{template;constructor(e){this.template={AWSTemplateFormatVersion:"2010-09-09",Description:e,Resources:{}}}addResource(e,a){return this.template.Resources[e]=a,this}addResources(e){return Object.assign(this.template.Resources,e),this}addParameter(e,a){if(!this.template.Parameters)this.template.Parameters={};return this.template.Parameters[e]=a,this}addOutput(e,a){if(!this.template.Outputs)this.template.Outputs={};return this.template.Outputs[e]=a,this}hasResource(e){return e in this.template.Resources}getResources(){return this.template.Resources}build(){return this.template}toJSON(e=!0){return JSON.stringify(this.template,null,e?2:0)}toYAML(){return this.convertToYAML(this.template)}convertToYAML(e,a=0){let r=" ".repeat(a),n="";for(let[i,o]of Object.entries(e)){if(o===null||o===void 0)continue;if(typeof o==="object"&&!Array.isArray(o))n+=`${r}${i}:
|
|
13
|
+
`}function va(e){return Object.keys(e).sort().map((a)=>a.toLowerCase()).join(";")}function pt(e){let a=[];return e.forEach((r,n)=>{a.push([kt(n),kt(r)])}),a.sort((r,n)=>{if(r[0]<n[0])return-1;if(r[0]>n[0])return 1;if(r[1]<n[1])return-1;if(r[1]>n[1])return 1;return 0}),a.map(([r,n])=>`${r}=${n}`).join("&")}function gt(e){return e.split("/").map((a)=>kt(a)).join("/")}function kt(e){return encodeURIComponent(e).replace(/[!'()*]/g,(a)=>`%${a.charCodeAt(0).toString(16).toUpperCase()}`)}function Ke(e){if(!$e)throw Error("Synchronous hash not available in browser. Use signRequestAsync() instead.");return $e.createHash("sha256").update(e,"utf8").digest("hex")}function _e(e,a){if(!$e)throw Error("Synchronous hmac not available in browser. Use signRequestAsync() instead.");return $e.createHmac("sha256",e).update(a,"utf8").digest()}async function ot(e){let a=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",a);return wa(new Uint8Array(r))}async function We(e,a){let r=new TextEncoder,n=typeof e==="string"?r.encode(e):e,i=r.encode(a),o=await crypto.subtle.importKey("raw",n.buffer,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),c=await crypto.subtle.sign("HMAC",o,i.buffer);return new Uint8Array(c)}function wa(e){return Array.from(e).map((a)=>a.toString(16).padStart(2,"0")).join("")}function Ea(e,a,r,n,i,o){let c=`${e}:${a}:${r}:${n}`,u=o.get(c);if(!u){let d=_e(`AWS4${e}`,a),m=_e(d,r),p=_e(m,n);if(u=_e(p,"aws4_request"),o.size>=Ra){let g=o.keys().next().value;if(g)o.delete(g)}o.set(c,u)}return _e(u,i).toString("hex")}async function Pa(e,a,r,n,i,o){let c=`${e}:${a}:${r}:${n}`,u=o.get(c);if(!u){let m=await We(`AWS4${e}`,a),p=await We(m,r),g=await We(p,n);if(u=await We(g,"aws4_request"),o.size>=Ra){let h=o.keys().next().value;if(h)o.delete(h)}o.set(c,u)}let d=await We(u,i);return wa(d)}function Ia(e,a){return a.includes(e)}function ct(e,a,r){let n=a*Math.pow(2,e),i=Math.random()*0.3*n;return Math.min(n+i,r)}function lt(e){return new Promise((a)=>setTimeout(a,e))}async function ui(e,a){let{maxRetries:r=3,initialDelayMs:n=100,maxDelayMs:i=5000,retryableStatusCodes:o=[429,500,502,503,504],timeoutMs:c=30000}=a??{},u,d;for(let m=0;m<=r;m++){let p=oe(e),g={method:p.method,headers:p.headers};if(p.body)g.body=p.body;let h=new AbortController,y=setTimeout(()=>h.abort(),c);g.signal=h.signal;try{let f=await fetch(p.url,g);if(clearTimeout(y),d=f,f.ok)return f;if(m<r&&Ia(f.status,o)){let v=ct(m,n,i);await lt(v);continue}let b=await f.text();throw Error(`AWS API request failed (${f.status}): ${b}`)}catch(f){if(clearTimeout(y),u=f,f instanceof Error&&f.name==="AbortError")u=Error(`Request timed out after ${c}ms`);if(m<r&&!(f instanceof Error&&f.message.includes("AWS API request failed"))){let b=ct(m,n,i);await lt(b);continue}throw u}}throw u??Error("Request failed after retries")}async function Ju(e){return ui(e,{maxRetries:0})}async function Xu(e,a){let{maxRetries:r=3,initialDelayMs:n=100,maxDelayMs:i=5000,retryableStatusCodes:o=[429,500,502,503,504],timeoutMs:c=30000}=a??{},u;for(let d=0;d<=r;d++){let m=await ec(e),p={method:m.method,headers:m.headers};if(m.body)p.body=m.body;let g=new AbortController,h=setTimeout(()=>g.abort(),c);p.signal=g.signal;try{let y=await fetch(m.url,p);if(clearTimeout(h),y.ok)return y;if(d<r&&Ia(y.status,o)){let b=ct(d,n,i);await lt(b);continue}let f=await y.text();throw Error(`AWS API request failed (${y.status}): ${f}`)}catch(y){if(clearTimeout(h),u=y,y instanceof Error&&y.name==="AbortError")u=Error(`Request timed out after ${c}ms`);if(d<r&&!(y instanceof Error&&y.message.includes("AWS API request failed"))){let f=ct(d,n,i);await lt(f);continue}throw u}}throw u??Error("Request failed after retries")}async function Os(e){let a=await e.text(),r={},n=/<(\w+)>([^<]+)<\/\1>/g,i;while((i=n.exec(a))!==null){let[,o,c]=i;r[o]=c}return r}async function Qu(e){return await e.json()}function Yu(){ye.clear()}function Zu(){return ye.size}function ep(){return $e!==void 0}function tp(){return typeof crypto<"u"&&typeof crypto.subtle<"u"}var $e,ye,Ra=100,Na,Qe=sr(async()=>{try{$e=await import("node:crypto")}catch{}ye=new Map,Na={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"}}),rp={backgroundJobs:{visibilityTimeout:120,messageRetentionPeriod:604800,deadLetterQueue:!0,maxReceiveCount:3,encrypted:!0},fifo:{fifo:!0,contentBasedDeduplication:!0,visibilityTimeout:30,encrypted:!0},highThroughput:{visibilityTimeout:30,receiveMessageWaitTime:20,encrypted:!0},delayed:{delaySeconds:60,visibilityTimeout:60,encrypted:!0},longRunning:{visibilityTimeout:900,messageRetentionPeriod:1209600,deadLetterQueue:!0,maxReceiveCount:2,encrypted:!0},monitored:{visibilityTimeout:60,messageRetentionPeriod:604800,deadLetterQueue:!0,maxReceiveCount:3,encrypted:!0,alarms:{enabled:!0,queueDepthThreshold:1000,messageAgeThreshold:3600,dlqAlarm:!0}},lambdaOptimized:{visibilityTimeout:360,receiveMessageWaitTime:20,deadLetterQueue:!0,maxReceiveCount:3,encrypted:!0},fanOut:{visibilityTimeout:30,receiveMessageWaitTime:20,encrypted:!0}},np={serverless:{development:{enabled:!0,mode:"serverless",channels:{public:!0,private:!0,presence:!0},storage:{type:"dynamodb",dynamodb:{billingMode:"PAY_PER_REQUEST"}},scaling:{maxConnections:1000,handlerMemory:128}},production:{enabled:!0,mode:"serverless",channels:{public:!0,private:!0,presence:{enabled:!0,maxMembers:100,heartbeatInterval:30,inactivityTimeout:60}},storage:{type:"dynamodb",dynamodb:{billingMode:"PAY_PER_REQUEST",pointInTimeRecovery:!0,connectionTTL:86400}},scaling:{maxConnections:50000,messagesPerSecond:5000,handlerMemory:256,handlerTimeout:30},monitoring:{enabled:!0,connectionThreshold:40000,errorThreshold:100,latencyThreshold:500},keepAlive:!0,keepAliveInterval:30,idleTimeout:600},notifications:{enabled:!0,mode:"serverless",channels:{public:!1,private:!0,presence:!1},storage:{type:"dynamodb",dynamodb:{billingMode:"PAY_PER_REQUEST"}},scaling:{maxConnections:50000,messagesPerSecond:2000,handlerMemory:128},keepAlive:!0,keepAliveInterval:60,idleTimeout:1800}},server:{development:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"ws",driver:"bun",idleTimeout:120,perMessageDeflate:!1,metrics:!1}},production:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:120,maxPayloadLength:16777216,backpressureLimit:1048576,sendPings:!0,perMessageDeflate:!0,instances:2,redis:{enabled:!0,keyPrefix:"broadcasting:"},rateLimit:{enabled:!0,max:100,window:60000,perChannel:!0,perUser:!0},loadManagement:{enabled:!0,maxConnections:1e4,maxSubscriptionsPerConnection:100,shedLoadThreshold:0.8},metrics:!0,autoScaling:{min:2,max:10,targetCPU:70}},monitoring:{enabled:!0,connectionThreshold:8000,errorThreshold:100}},highPerformance:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:60,maxPayloadLength:8388608,backpressureLimit:2097152,closeOnBackpressureLimit:!0,sendPings:!0,perMessageDeflate:!0,instances:4,redis:{enabled:!0,useElastiCache:!0,keyPrefix:"rt:"},rateLimit:{enabled:!0,max:200,window:60000,perChannel:!0},loadManagement:{enabled:!0,maxConnections:25000,maxSubscriptionsPerConnection:50,shedLoadThreshold:0.7},metrics:{enabled:!0,path:"/metrics"},autoScaling:{min:4,max:20,targetCPU:60,targetConnections:20000}},monitoring:{enabled:!0,connectionThreshold:80000,errorThreshold:50,latencyThreshold:50}},chat:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:{enabled:!0,maxMembers:200,heartbeatInterval:20,inactivityTimeout:60}},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:300,maxPayloadLength:1048576,sendPings:!0,perMessageDeflate:!0,instances:2,redis:{enabled:!0,keyPrefix:"chat:"},rateLimit:{enabled:!0,max:60,window:60000,perChannel:!0},loadManagement:{enabled:!0,maxConnections:15000,maxSubscriptionsPerConnection:20},metrics:!0},keepAlive:!0,keepAliveInterval:25,idleTimeout:900},gaming:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:{enabled:!0,maxMembers:100,heartbeatInterval:10,inactivityTimeout:30}},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:30,maxPayloadLength:65536,backpressureLimit:524288,closeOnBackpressureLimit:!0,sendPings:!0,perMessageDeflate:!1,instances:4,redis:{enabled:!0,useElastiCache:!0},rateLimit:{enabled:!0,max:120,window:60000},loadManagement:{enabled:!0,maxConnections:5000,maxSubscriptionsPerConnection:10,shedLoadThreshold:0.6},metrics:!0,autoScaling:{min:4,max:16,targetCPU:50}},keepAlive:!0,keepAliveInterval:10,idleTimeout:60},single:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:120,sendPings:!0,perMessageDeflate:!0,instances:1,rateLimit:{enabled:!0,max:100,window:60000},loadManagement:{enabled:!0,maxConnections:1e4},metrics:!0}}}},tc=".ts-cloud",rc="TS_CLOUD_STATE_DIR",Ot=null;function Ls(e){Ot=e?.trim()||null}function Ms(){return Boolean(process.env[rc]?.trim()||Ot)}function yo(){return process.env[rc]?.trim()||Ot||tc}function Ye(...e){return ut(yo(),...e)}function A(e,...a){let r=yo();return $t(r)?ut(r,...a):ut(e,r,...a)}function Us(e,a=process.cwd()){let r=(i,o)=>{let c=ur(i,o);return c===""||!c.startsWith("..")&&!$t(c)},n=$t(e)?e:ut(a,e);return r(A(a),n)}function nc(e){let a=e.infrastructure?.compute!=null,r=Object.values(e.environments??{}).some((n)=>n?.app!=null);return{server:a,serverless:r}}function V(e){if(e.mode==="server"||e.mode==="serverless")return e.mode;let{serverless:a}=nc(e);return a?"serverless":"server"}function wr(e){let{server:a,serverless:r}=nc(e);if(a&&r)return"A project cannot be both a server and a serverless deployment. Found `infrastructure.compute` (server) AND `environments.<env>.app` (serverless Lambda). Keep one: remove `infrastructure.compute` for a serverless app, or remove `environments.<env>.app` for a server.";if(e.mode==="server"&&r&&!a)return"Config sets `mode: 'server'` but declares a serverless app (`environments.<env>.app`). Remove the app or change the mode.";if(e.mode==="serverless"&&a&&!r)return"Config sets `mode: 'serverless'` but declares a server (`infrastructure.compute`). Remove the compute block or change the mode.";return null}function C(e){return e.infrastructure?.appDatabase??e.infrastructure?.compute?.database}function dr(e){return typeof e==="object"&&e!==null?e:{}}function ld(e){return e===!0||typeof e==="object"&&e!==null}function mr(e,a){let r=a?e.environments?.[a]:void 0;if(r?.domain)return r.domain;let n=Object.values(e.sites??{}),i=e.sites?.main?.domain??n.find((o)=>o.domain)?.domain;if(i)return i;return`${e.project?.slug??"app"}.local`}function pr(e){let a=e.indexOf(".");return a>0?e.slice(a+1):void 0}function pi(e,a={}){let r=e.infrastructure?.compute?.managedServices?.mail,n=dr(r),i=a.environmentType??(a.environment?e.environments?.[a.environment]?.type:void 0),o=n.mode??(i==="production"?"server":"catcher"),c=o==="server",u=mr(e,a.environment),d=n.hostname??(c?`mail.${u}`:"localhost"),m=n.ports??{},p=c?{smtp:m.smtp??25,submission:m.submission??587,submissions:m.submissions??465,imap:m.imap??143,imaps:m.imaps??993,webmail:m.webmail??8080,managesieve:m.managesieve}:{smtp:m.smtp??1025,submission:m.submission,submissions:m.submissions,imap:m.imap,imaps:m.imaps,webmail:m.webmail??8025,managesieve:m.managesieve},g=n.tls??{},h=g.enabled??c,y=!!(g.certPath&&g.keyPath),f=(n.accounts??[]).map((L)=>({address:L.address,password:L.password})),b=typeof n.dkim==="object"&&n.dkim!==null?n.dkim:{},v=n.dkim===!1?!1:n.dkim===!0||c,w=typeof n.webmail==="object"&&n.webmail!==null?n.webmail:{},R=n.webmail===!1?!1:w.enabled??!0,T=n.spam??{},N=n.delivery??(c?"direct":"none"),I=n.expose??c,k=pr(d),O=[...new Set([d,...k?[k]:[],...n.domains??[]])];return{enabled:ld(r),mode:o,version:n.version,hostname:d,domains:O,ports:p,tls:{enabled:h,acme:h&&!y&&(g.acme??!0),certPath:g.certPath,keyPath:g.keyPath,requireForAuth:g.requireForAuth??(h&&c),acmeEmail:g.acmeEmail??f[0]?.address},dkim:{enabled:v,selector:b.selector??"default",rotate:b.rotate??!1,rotateIntervalDays:b.rotateIntervalDays??90},webmail:{enabled:R,port:w.port??p.webmail,domain:w.domain},delivery:N,sesRegion:n.sesRegion??"us-east-1",accounts:f,storagePath:n.storagePath??"/var/lib/mail",maxMessageSize:n.maxMessageSize??26214400,spam:{enabled:T.enabled??c,enforce:T.enforce??!1,junkScore:T.junkScore??5,rejectScore:T.rejectScore??12,dnsbl:T.dnsbl??c,greylist:T.greylist??!1},webhookUrl:n.webhookUrl,expose:I,bindAddress:I?"0.0.0.0":"127.0.0.1"}}function Bs(e){if(!e.enabled||!e.expose)return[];let a=[e.ports.smtp,e.ports.submission,e.ports.submissions,e.ports.imap,e.ports.imaps,e.ports.managesieve].filter((r)=>typeof r==="number");if(e.webmail.enabled&&!e.webmail.domain)a.push(e.webmail.port);return[...new Set(a)].sort((r,n)=>r-n)}function Fs(e){if(!e.enabled)return{};let a=e.ports.submission??e.ports.smtp,r={MAIL_MAILER:"smtp",MAIL_HOST:"127.0.0.1",MAIL_PORT:String(a)};if(e.mode==="server"){r.MAIL_ENCRYPTION=e.tls.enabled?"tls":"null";let n=e.accounts[0];if(n)r.MAIL_USERNAME=n.address,r.MAIL_PASSWORD=n.password}else r.MAIL_ENCRYPTION="null",r.MAIL_USERNAME="null",r.MAIL_PASSWORD="null";return r}function U(e){if(e.cloud?.provider)return e.cloud.provider;if(e.ssh?.hosts?.length)return"ssh";if(e.hetzner?.apiToken)return"hetzner";return"aws"}class So{template;constructor(e){this.template={AWSTemplateFormatVersion:"2010-09-09",Description:e,Resources:{}}}addResource(e,a){return this.template.Resources[e]=a,this}addResources(e){return Object.assign(this.template.Resources,e),this}addParameter(e,a){if(!this.template.Parameters)this.template.Parameters={};return this.template.Parameters[e]=a,this}addOutput(e,a){if(!this.template.Outputs)this.template.Outputs={};return this.template.Outputs[e]=a,this}hasResource(e){return e in this.template.Resources}getResources(){return this.template.Resources}build(){return this.template}toJSON(e=!0){return JSON.stringify(this.template,null,e?2:0)}toYAML(){return this.convertToYAML(this.template)}convertToYAML(e,a=0){let r=" ".repeat(a),n="";for(let[i,o]of Object.entries(e)){if(o===null||o===void 0)continue;if(typeof o==="object"&&!Array.isArray(o))n+=`${r}${i}:
|
|
14
14
|
${this.convertToYAML(o,a+1)}`;else if(Array.isArray(o)){n+=`${r}${i}:
|
|
15
15
|
`;for(let c of o)if(typeof c==="object")n+=`${r} -
|
|
16
16
|
${this.convertToYAML(c,a+2)}`;else n+=`${r} - ${c}
|
|
17
17
|
`}else n+=`${r}${i}: ${o}
|
|
18
|
-
`}return n}}function ip(e){let a=[],r=[],n=[];if(gr(e,a),e.Resources)hr(e.Resources,a,r);else a.push({path:"Resources",message:"Template must contain at least one resource",severity:"error"});if(e.Parameters)yr(e.Parameters,a,r);if(e.Outputs)fr(e.Outputs,a);Sr(e,a);let i=br(e);if(i.length>0)for(let o of i)a.push({path:"Resources",message:`Circular dependency detected: ${o.join(" → ")}`,severity:"error"});return vr(e,r,n),{valid:a.length===0,errors:a,warnings:r,info:n}}function gr(e,a){if(!e.AWSTemplateFormatVersion)a.push({path:"AWSTemplateFormatVersion",message:"Template should specify AWSTemplateFormatVersion",severity:"error"});else if(e.AWSTemplateFormatVersion!=="2010-09-09")a.push({path:"AWSTemplateFormatVersion",message:'AWSTemplateFormatVersion must be "2010-09-09"',severity:"error"})}function hr(e,a,r){let n=Object.keys(e);if(n.length===0){a.push({path:"Resources",message:"Template must contain at least one resource",severity:"error"});return}if(n.length>500)r.push({path:"Resources",message:`Template contains ${n.length} resources (limit is 500)`,severity:"warning"});for(let i of n){let o=e[i];if(!/^[a-zA-Z0-9]+$/.test(i))a.push({path:`Resources.${i}`,message:"Logical ID must contain only alphanumeric characters",severity:"error"});if(!o.Type)a.push({path:`Resources.${i}.Type`,message:"Resource Type is required",severity:"error"});else if(!o.Type.startsWith("AWS::")&&!o.Type.startsWith("Custom::"))a.push({path:`Resources.${i}.Type`,message:'Resource Type must start with "AWS::" or "Custom::"',severity:"error"});if(o.DeletionPolicy&&!["Delete","Retain","Snapshot"].includes(o.DeletionPolicy))a.push({path:`Resources.${i}.DeletionPolicy`,message:'DeletionPolicy must be "Delete", "Retain", or "Snapshot"',severity:"error"});if(!o.DeletionPolicy&&Da(o.Type))r.push({path:`Resources.${i}.DeletionPolicy`,message:`${o.Type} should specify DeletionPolicy to prevent accidental data loss`,severity:"warning"})}}function yr(e,a,r){let n=Object.keys(e);if(n.length>200)r.push({path:"Parameters",message:`Template contains ${n.length} parameters (limit is 200)`,severity:"warning"});for(let i of n){let o=e[i];if(!o.Type)a.push({path:`Parameters.${i}.Type`,message:"Parameter Type is required",severity:"error"});let c=["String","Number","List<Number>","CommaDelimitedList","AWS::EC2::AvailabilityZone::Name","AWS::EC2::Image::Id","AWS::EC2::Instance::Id","AWS::EC2::KeyPair::KeyName","AWS::EC2::SecurityGroup::GroupName","AWS::EC2::SecurityGroup::Id","AWS::EC2::Subnet::Id","AWS::EC2::Volume::Id","AWS::EC2::VPC::Id","AWS::Route53::HostedZone::Id","List<AWS::EC2::AvailabilityZone::Name>","List<AWS::EC2::Image::Id>","List<AWS::EC2::Instance::Id>","List<AWS::EC2::SecurityGroup::GroupName>","List<AWS::EC2::SecurityGroup::Id>","List<AWS::EC2::Subnet::Id>","List<AWS::EC2::Volume::Id>","List<AWS::EC2::VPC::Id>","List<AWS::Route53::HostedZone::Id>","AWS::SSM::Parameter::Name","AWS::SSM::Parameter::Value<String>","AWS::SSM::Parameter::Value<List<String>>","AWS::SSM::Parameter::Value<CommaDelimitedList>"];if(o.Type&&!c.includes(o.Type))a.push({path:`Parameters.${i}.Type`,message:`Invalid parameter type: ${o.Type}`,severity:"error"})}}function fr(e,a){let r=Object.keys(e);for(let n of r)if(!e[n].Value)a.push({path:`Outputs.${n}.Value`,message:"Output Value is required",severity:"error"})}function Sr(e,a){let r=e.Resources||{},n=e.Parameters||{},i=new Set(Object.keys(r)),o=new Set(Object.keys(n));function c(u,d){if(typeof u!=="object"||u===null)return;if(u.Ref){let m=u.Ref;if(!i.has(m)&&!o.has(m)&&m!=="AWS::Region"&&m!=="AWS::AccountId"&&m!=="AWS::StackName"&&m!=="AWS::StackId"&&m!=="AWS::URLSuffix"&&m!=="AWS::Partition"&&m!=="AWS::NoValue")a.push({path:d,message:`Reference to non-existent resource or parameter: ${m}`,severity:"error"})}if(u["Fn::GetAtt"]){let m=u["Fn::GetAtt"];if(Array.isArray(m)&&m.length>=1){let p=m[0];if(!i.has(p))a.push({path:d,message:`GetAtt references non-existent resource: ${p}`,severity:"error"})}}for(let m in u)c(u[m],`${d}.${m}`)}for(let u in r)c(r[u],`Resources.${u}`);if(e.Outputs)for(let u in e.Outputs)c(e.Outputs[u],`Outputs.${u}`)}function br(e){let a=e.Resources||{},r=new Map;for(let u in a){let d=new Set,m=a[u];if(m.DependsOn)if(Array.isArray(m.DependsOn))m.DependsOn.forEach((p)=>d.add(p));else d.add(m.DependsOn);Tr(m).forEach((p)=>d.add(p)),r.set(u,d)}let n=[],i=new Set,o=new Set;function c(u,d){i.add(u),o.add(u),d.push(u);let m=r.get(u)||new Set;for(let p of m)if(!i.has(p))c(p,[...d]);else if(o.has(p)){let g=d.indexOf(p),h=[...d.slice(g),p];n.push(h)}o.delete(u)}for(let u of r.keys())if(!i.has(u))c(u,[]);return n}function Tr(e){let a=new Set;function r(n){if(typeof n!=="object"||n===null)return;if(n.Ref&&typeof n.Ref==="string"){if(!n.Ref.startsWith("AWS::"))a.add(n.Ref)}if(n["Fn::GetAtt"]&&Array.isArray(n["Fn::GetAtt"]))a.add(n["Fn::GetAtt"][0]);for(let i in n)r(n[i])}return r(e),a}function Da(e){return["AWS::S3::Bucket","AWS::DynamoDB::Table","AWS::RDS::DBInstance","AWS::RDS::DBCluster","AWS::ElastiCache::CacheCluster","AWS::ElastiCache::ReplicationGroup","AWS::EFS::FileSystem","AWS::OpenSearchService::Domain"].includes(e)}function vr(e,a,r){let n=e.Resources||{};if(!e.Description)r.push({path:"Description",message:"Consider adding a Description to the template",severity:"info"});for(let i in n){let o=n[i],c=o.Properties;if(c&&!c.Tags&&Er(o.Type))r.push({path:`Resources.${i}`,message:`Consider adding Tags to ${o.Type}`,severity:"info"});if(Da(o.Type)){if(o.Type==="AWS::S3::Bucket"&&!c?.BucketEncryption)a.push({path:`Resources.${i}`,message:"S3 bucket should enable encryption",severity:"warning"});if(o.Type==="AWS::RDS::DBInstance"&&!c?.StorageEncrypted)a.push({path:`Resources.${i}`,message:"RDS instance should enable storage encryption",severity:"warning"})}}}function Er(e){return!["AWS::CloudFormation::Stack","AWS::CloudFormation::WaitCondition","AWS::CloudFormation::WaitConditionHandle"].includes(e)}function op(e){let a=[],r=[],n=[],i=Buffer.byteLength(e,"utf8"),o=i/1024,c=51200,u=460800;if(i>460800)a.push({path:"Template",message:`Template size (${o.toFixed(2)} KB) exceeds maximum size of 450 KB`,severity:"error"});else if(i>51200)r.push({path:"Template",message:`Template size (${o.toFixed(2)} KB) exceeds 50 KB. Must use S3 for deployment.`,severity:"warning"});return{valid:a.length===0,errors:a,warnings:r,info:n}}function sp(e){let a=[],r=[],n=[],i=e.Resources||{},o=e.Parameters||{},c=e.Outputs||{};if(Object.keys(i).length>500)a.push({path:"Resources",message:`Template has ${Object.keys(i).length} resources (limit is 500)`,severity:"error"});if(Object.keys(o).length>200)a.push({path:"Parameters",message:`Template has ${Object.keys(o).length} parameters (limit is 200)`,severity:"error"});if(Object.keys(c).length>200)a.push({path:"Outputs",message:`Template has ${Object.keys(c).length} outputs (limit is 200)`,severity:"error"});return{valid:a.length===0,errors:a,warnings:r,info:n}}var P={Ref:(e)=>({Ref:e}),GetAtt:(e,a)=>({"Fn::GetAtt":[e,a]}),Sub:(e,a)=>{if(a)return{"Fn::Sub":[e,a]};return{"Fn::Sub":e}},Join:(e,a)=>({"Fn::Join":[e,a]}),Select:(e,a)=>({"Fn::Select":[e,a]}),Split:(e,a)=>({"Fn::Split":[e,a]}),GetAZs:(e="")=>({"Fn::GetAZs":e}),ImportValue:(e)=>({"Fn::ImportValue":e}),If:(e,a,r)=>({"Fn::If":[e,a,r]}),Equals:(e,a)=>({"Fn::Equals":[e,a]}),And:(...e)=>({"Fn::And":e}),Or:(...e)=>({"Fn::Or":e}),Not:(e)=>({"Fn::Not":[e]}),Base64:(e)=>({"Fn::Base64":e})},ap={AccountId:{Ref:"AWS::AccountId"},Region:{Ref:"AWS::Region"},StackId:{Ref:"AWS::StackId"},StackName:{Ref:"AWS::StackName"},NotificationARNs:{Ref:"AWS::NotificationARNs"},Partition:{Ref:"AWS::Partition"},URLSuffix:{Ref:"AWS::URLSuffix"},NoValue:{Ref:"AWS::NoValue"}};function l(e){let{slug:a,environment:r,resourceType:n,timestamp:i,suffix:o}=e,c=[a,r,n];if(i)c.push(i);if(o)c.push(o);return c.join("-")}function s(e){return e.split("-").map((a)=>a.charAt(0).toUpperCase()+a.slice(1)).join("")}function cp(){return Date.now().toString()}function lp(e){return e.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/^-+|-+$/g,"").replace(/-+/g,"-")}function E(e,a){return e.project.stackName??`${e.project.slug}-${a}`}function js(e,a,r,n){return r.stackName??`${e.project.slug}-${n}-${a}-site`}function Vs(e,a){return`${e.project.slug}-${a}`}function zs(e,a,r,n){if(n)return n;if(r==="main")return`${e}-${a}-site`;return`${e}-${a}-${r}`}function dp(e,a,r,n){return n??`${e}-${a}-${r}`}function up(e,a){return`${e}-${a}-deploy`}function Pe(e,a){return`${e.project.slug}-${a}-app`}function qs(e,a){return`${e}-${a}-deployments`}function bo(e,a){return`${e}-${a}-assets`}class dd{nodes=new Map;addResource(e,a){let r=this.extractDependencies(a);this.nodes.set(e,{logicalId:e,resource:a,dependencies:r})}extractDependencies(e){let a=new Set;if(e.DependsOn)if(Array.isArray(e.DependsOn))e.DependsOn.forEach((r)=>a.add(r));else a.add(e.DependsOn);return this.findReferences(e.Properties||{},a),a}findReferences(e,a){if(!e||typeof e!=="object")return;if("Ref"in e&&typeof e.Ref==="string"){if(!e.Ref.startsWith("AWS::"))a.add(e.Ref)}if("Fn::GetAtt"in e&&Array.isArray(e["Fn::GetAtt"]))a.add(e["Fn::GetAtt"][0]);for(let r of Object.values(e))if(typeof r==="object")this.findReferences(r,a)}topologicalSort(){let e=[],a=new Set,r=new Set,n=(i)=>{if(a.has(i))return;if(r.has(i))throw Error(`Circular dependency detected: ${i}`);r.add(i);let o=this.nodes.get(i);if(o)for(let c of o.dependencies)n(c);r.delete(i),a.add(i),e.push(i)};for(let i of this.nodes.keys())n(i);return e}validate(){for(let[e,a]of this.nodes.entries())for(let r of a.dependencies)if(!this.nodes.has(r))throw Error(`Resource "${e}" depends on "${r}" which does not exist`)}getDependents(e){let a=[];for(let[r,n]of this.nodes.entries())if(n.dependencies.has(e))a.push(r);return a}}function pp(e,a){let r=[],n=[],i=[],o=[],c=[],u=e.Resources||{},d=a.Resources||{},m=new Set([...Object.keys(u),...Object.keys(d)]);for(let g of m){let h=u[g],y=d[g];if(!h&&y)r.push({logicalId:g,action:"add",resourceType:y.Type});else if(h&&!y)n.push({logicalId:g,action:"remove",resourceType:h.Type});else if(h&&y)if(h.Type!==y.Type)o.push({logicalId:g,action:"replace",resourceType:y.Type,reason:`Type changed from ${h.Type} to ${y.Type}`});else{let f=ka(h.Properties||{},y.Properties||{});if(f.length>0)if(Pr(h.Type,f))o.push({logicalId:g,action:"replace",resourceType:y.Type,changes:f,reason:"Property changes require replacement"});else i.push({logicalId:g,action:"update",resourceType:y.Type,changes:f});else c.push(g)}}let p=Ir([...n,...o,...i]);return{added:r,removed:n,updated:i,replaced:o,unchanged:c,summary:{totalChanges:r.length+n.length+i.length+o.length,requiresReplacement:o.length>0,dangerousChanges:p}}}function ka(e,a,r=""){let n=[],i=new Set([...Object.keys(e),...Object.keys(a)]);for(let o of i){let c=r?`${r}.${o}`:o,u=e[o],d=a[o];if(u===void 0&&d!==void 0)n.push({path:c,oldValue:void 0,newValue:d});else if(u!==void 0&&d===void 0)n.push({path:c,oldValue:u,newValue:void 0});else if(typeof u!==typeof d)n.push({path:c,oldValue:u,newValue:d});else if(typeof u==="object"&&u!==null)if(Array.isArray(u)&&Array.isArray(d)){if(JSON.stringify(u)!==JSON.stringify(d))n.push({path:c,oldValue:u,newValue:d})}else if(!Array.isArray(u)&&!Array.isArray(d)){let m=ka(u,d,c);n.push(...m)}else n.push({path:c,oldValue:u,newValue:d});else if(u!==d)n.push({path:c,oldValue:u,newValue:d})}return n}function Pr(e,a){let r={"AWS::S3::Bucket":new Set(["BucketName"]),"AWS::DynamoDB::Table":new Set(["TableName","KeySchema"]),"AWS::RDS::DBInstance":new Set(["DBInstanceIdentifier","DBName","Engine"]),"AWS::Lambda::Function":new Set(["FunctionName"]),"AWS::EC2::Instance":new Set(["ImageId","InstanceType","KeyName"]),"AWS::ECS::TaskDefinition":new Set(["Family","ContainerDefinitions"]),"AWS::ElastiCache::CacheCluster":new Set(["CacheNodeType","Engine"]),"AWS::CloudFront::Distribution":new Set([]),"AWS::Route53::HostedZone":new Set(["Name"]),"AWS::IAM::Role":new Set(["RoleName","Path"]),"AWS::KMS::Key":new Set(["KeyPolicy"]),"AWS::Cognito::UserPool":new Set(["UserPoolName"]),"AWS::OpenSearchService::Domain":new Set(["DomainName"])}[e];if(!r)return!1;for(let n of a){let i=n.path.split(".")[0];if(r.has(i))return!0}return!1}function Ir(e){let a=[];for(let r of e){if(r.action==="remove"&&(r.resourceType==="AWS::RDS::DBInstance"||r.resourceType==="AWS::DynamoDB::Table"||r.resourceType==="AWS::ElastiCache::CacheCluster"))a.push(`Removing ${r.resourceType} ${r.logicalId} - data loss risk!`);if(r.action==="replace"&&(r.resourceType==="AWS::RDS::DBInstance"||r.resourceType==="AWS::DynamoDB::Table"))a.push(`Replacing ${r.resourceType} ${r.logicalId} - data loss risk!`);if((r.action==="remove"||r.action==="replace")&&r.resourceType==="AWS::S3::Bucket")a.push(`${r.action==="remove"?"Removing":"Replacing"} S3 bucket ${r.logicalId} - data loss risk!`);if(r.action==="replace"&&r.resourceType==="AWS::EC2::Instance")a.push(`Replacing EC2 instance ${r.logicalId} - downtime expected`);if(r.action==="update"&&r.resourceType==="AWS::EC2::SecurityGroup")a.push(`Updating security group ${r.logicalId} - may affect connectivity`);if((r.action==="update"||r.action==="replace")&&(r.resourceType==="AWS::IAM::Role"||r.resourceType==="AWS::IAM::Policy"))a.push(`Modifying IAM ${r.resourceType.split("::")[2]} ${r.logicalId} - may affect permissions`)}return a}function mp(e){let a=[];if(a.push(`=== Stack Update Analysis ===
|
|
18
|
+
`}return n}}function ip(e){let a=[],r=[],n=[];if(gr(e,a),e.Resources)hr(e.Resources,a,r);else a.push({path:"Resources",message:"Template must contain at least one resource",severity:"error"});if(e.Parameters)yr(e.Parameters,a,r);if(e.Outputs)fr(e.Outputs,a);Sr(e,a);let i=br(e);if(i.length>0)for(let o of i)a.push({path:"Resources",message:`Circular dependency detected: ${o.join(" → ")}`,severity:"error"});return vr(e,r,n),{valid:a.length===0,errors:a,warnings:r,info:n}}function gr(e,a){if(!e.AWSTemplateFormatVersion)a.push({path:"AWSTemplateFormatVersion",message:"Template should specify AWSTemplateFormatVersion",severity:"error"});else if(e.AWSTemplateFormatVersion!=="2010-09-09")a.push({path:"AWSTemplateFormatVersion",message:'AWSTemplateFormatVersion must be "2010-09-09"',severity:"error"})}function hr(e,a,r){let n=Object.keys(e);if(n.length===0){a.push({path:"Resources",message:"Template must contain at least one resource",severity:"error"});return}if(n.length>500)r.push({path:"Resources",message:`Template contains ${n.length} resources (limit is 500)`,severity:"warning"});for(let i of n){let o=e[i];if(!/^[a-zA-Z0-9]+$/.test(i))a.push({path:`Resources.${i}`,message:"Logical ID must contain only alphanumeric characters",severity:"error"});if(!o.Type)a.push({path:`Resources.${i}.Type`,message:"Resource Type is required",severity:"error"});else if(!o.Type.startsWith("AWS::")&&!o.Type.startsWith("Custom::"))a.push({path:`Resources.${i}.Type`,message:'Resource Type must start with "AWS::" or "Custom::"',severity:"error"});if(o.DeletionPolicy&&!["Delete","Retain","Snapshot"].includes(o.DeletionPolicy))a.push({path:`Resources.${i}.DeletionPolicy`,message:'DeletionPolicy must be "Delete", "Retain", or "Snapshot"',severity:"error"});if(!o.DeletionPolicy&&Da(o.Type))r.push({path:`Resources.${i}.DeletionPolicy`,message:`${o.Type} should specify DeletionPolicy to prevent accidental data loss`,severity:"warning"})}}function yr(e,a,r){let n=Object.keys(e);if(n.length>200)r.push({path:"Parameters",message:`Template contains ${n.length} parameters (limit is 200)`,severity:"warning"});for(let i of n){let o=e[i];if(!o.Type)a.push({path:`Parameters.${i}.Type`,message:"Parameter Type is required",severity:"error"});let c=["String","Number","List<Number>","CommaDelimitedList","AWS::EC2::AvailabilityZone::Name","AWS::EC2::Image::Id","AWS::EC2::Instance::Id","AWS::EC2::KeyPair::KeyName","AWS::EC2::SecurityGroup::GroupName","AWS::EC2::SecurityGroup::Id","AWS::EC2::Subnet::Id","AWS::EC2::Volume::Id","AWS::EC2::VPC::Id","AWS::Route53::HostedZone::Id","List<AWS::EC2::AvailabilityZone::Name>","List<AWS::EC2::Image::Id>","List<AWS::EC2::Instance::Id>","List<AWS::EC2::SecurityGroup::GroupName>","List<AWS::EC2::SecurityGroup::Id>","List<AWS::EC2::Subnet::Id>","List<AWS::EC2::Volume::Id>","List<AWS::EC2::VPC::Id>","List<AWS::Route53::HostedZone::Id>","AWS::SSM::Parameter::Name","AWS::SSM::Parameter::Value<String>","AWS::SSM::Parameter::Value<List<String>>","AWS::SSM::Parameter::Value<CommaDelimitedList>"];if(o.Type&&!c.includes(o.Type))a.push({path:`Parameters.${i}.Type`,message:`Invalid parameter type: ${o.Type}`,severity:"error"})}}function fr(e,a){let r=Object.keys(e);for(let n of r)if(!e[n].Value)a.push({path:`Outputs.${n}.Value`,message:"Output Value is required",severity:"error"})}function Sr(e,a){let r=e.Resources||{},n=e.Parameters||{},i=new Set(Object.keys(r)),o=new Set(Object.keys(n));function c(u,d){if(typeof u!=="object"||u===null)return;if(u.Ref){let m=u.Ref;if(!i.has(m)&&!o.has(m)&&m!=="AWS::Region"&&m!=="AWS::AccountId"&&m!=="AWS::StackName"&&m!=="AWS::StackId"&&m!=="AWS::URLSuffix"&&m!=="AWS::Partition"&&m!=="AWS::NoValue")a.push({path:d,message:`Reference to non-existent resource or parameter: ${m}`,severity:"error"})}if(u["Fn::GetAtt"]){let m=u["Fn::GetAtt"];if(Array.isArray(m)&&m.length>=1){let p=m[0];if(!i.has(p))a.push({path:d,message:`GetAtt references non-existent resource: ${p}`,severity:"error"})}}for(let m in u)c(u[m],`${d}.${m}`)}for(let u in r)c(r[u],`Resources.${u}`);if(e.Outputs)for(let u in e.Outputs)c(e.Outputs[u],`Outputs.${u}`)}function br(e){let a=e.Resources||{},r=new Map;for(let u in a){let d=new Set,m=a[u];if(m.DependsOn)if(Array.isArray(m.DependsOn))m.DependsOn.forEach((p)=>d.add(p));else d.add(m.DependsOn);Tr(m).forEach((p)=>d.add(p)),r.set(u,d)}let n=[],i=new Set,o=new Set;function c(u,d){i.add(u),o.add(u),d.push(u);let m=r.get(u)||new Set;for(let p of m)if(!i.has(p))c(p,[...d]);else if(o.has(p)){let g=d.indexOf(p),h=[...d.slice(g),p];n.push(h)}o.delete(u)}for(let u of r.keys())if(!i.has(u))c(u,[]);return n}function Tr(e){let a=new Set;function r(n){if(typeof n!=="object"||n===null)return;if(n.Ref&&typeof n.Ref==="string"){if(!n.Ref.startsWith("AWS::"))a.add(n.Ref)}if(n["Fn::GetAtt"]&&Array.isArray(n["Fn::GetAtt"]))a.add(n["Fn::GetAtt"][0]);for(let i in n)r(n[i])}return r(e),a}function Da(e){return["AWS::S3::Bucket","AWS::DynamoDB::Table","AWS::RDS::DBInstance","AWS::RDS::DBCluster","AWS::ElastiCache::CacheCluster","AWS::ElastiCache::ReplicationGroup","AWS::EFS::FileSystem","AWS::OpenSearchService::Domain"].includes(e)}function vr(e,a,r){let n=e.Resources||{};if(!e.Description)r.push({path:"Description",message:"Consider adding a Description to the template",severity:"info"});for(let i in n){let o=n[i],c=o.Properties;if(c&&!c.Tags&&Er(o.Type))r.push({path:`Resources.${i}`,message:`Consider adding Tags to ${o.Type}`,severity:"info"});if(Da(o.Type)){if(o.Type==="AWS::S3::Bucket"&&!c?.BucketEncryption)a.push({path:`Resources.${i}`,message:"S3 bucket should enable encryption",severity:"warning"});if(o.Type==="AWS::RDS::DBInstance"&&!c?.StorageEncrypted)a.push({path:`Resources.${i}`,message:"RDS instance should enable storage encryption",severity:"warning"})}}}function Er(e){return!["AWS::CloudFormation::Stack","AWS::CloudFormation::WaitCondition","AWS::CloudFormation::WaitConditionHandle"].includes(e)}function op(e){let a=[],r=[],n=[],i=Buffer.byteLength(e,"utf8"),o=i/1024,c=51200,u=460800;if(i>460800)a.push({path:"Template",message:`Template size (${o.toFixed(2)} KB) exceeds maximum size of 450 KB`,severity:"error"});else if(i>51200)r.push({path:"Template",message:`Template size (${o.toFixed(2)} KB) exceeds 50 KB. Must use S3 for deployment.`,severity:"warning"});return{valid:a.length===0,errors:a,warnings:r,info:n}}function sp(e){let a=[],r=[],n=[],i=e.Resources||{},o=e.Parameters||{},c=e.Outputs||{};if(Object.keys(i).length>500)a.push({path:"Resources",message:`Template has ${Object.keys(i).length} resources (limit is 500)`,severity:"error"});if(Object.keys(o).length>200)a.push({path:"Parameters",message:`Template has ${Object.keys(o).length} parameters (limit is 200)`,severity:"error"});if(Object.keys(c).length>200)a.push({path:"Outputs",message:`Template has ${Object.keys(c).length} outputs (limit is 200)`,severity:"error"});return{valid:a.length===0,errors:a,warnings:r,info:n}}var P={Ref:(e)=>({Ref:e}),GetAtt:(e,a)=>({"Fn::GetAtt":[e,a]}),Sub:(e,a)=>{if(a)return{"Fn::Sub":[e,a]};return{"Fn::Sub":e}},Join:(e,a)=>({"Fn::Join":[e,a]}),Select:(e,a)=>({"Fn::Select":[e,a]}),Split:(e,a)=>({"Fn::Split":[e,a]}),GetAZs:(e="")=>({"Fn::GetAZs":e}),ImportValue:(e)=>({"Fn::ImportValue":e}),If:(e,a,r)=>({"Fn::If":[e,a,r]}),Equals:(e,a)=>({"Fn::Equals":[e,a]}),And:(...e)=>({"Fn::And":e}),Or:(...e)=>({"Fn::Or":e}),Not:(e)=>({"Fn::Not":[e]}),Base64:(e)=>({"Fn::Base64":e})},ap={AccountId:{Ref:"AWS::AccountId"},Region:{Ref:"AWS::Region"},StackId:{Ref:"AWS::StackId"},StackName:{Ref:"AWS::StackName"},NotificationARNs:{Ref:"AWS::NotificationARNs"},Partition:{Ref:"AWS::Partition"},URLSuffix:{Ref:"AWS::URLSuffix"},NoValue:{Ref:"AWS::NoValue"}};function l(e){let{slug:a,environment:r,resourceType:n,timestamp:i,suffix:o}=e,c=[a,r,n];if(i)c.push(i);if(o)c.push(o);return c.join("-")}function s(e){return e.split("-").map((a)=>a.charAt(0).toUpperCase()+a.slice(1)).join("")}function cp(){return Date.now().toString()}function lp(e){return e.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/^-+|-+$/g,"").replace(/-+/g,"-")}function E(e,a){return e.project.stackName??`${e.project.slug}-${a}`}function js(e,a,r,n){return r.stackName??`${e.project.slug}-${n}-${a}-site`}function Vs(e,a){return`${e.project.slug}-${a}`}function zs(e,a,r,n){if(n)return n;if(r==="main")return`${e}-${a}-site`;return`${e}-${a}-${r}`}function dp(e,a,r,n){return n??`${e}-${a}-${r}`}function up(e,a){return`${e}-${a}-deploy`}function Pe(e,a){return`${e.project.slug}-${a}-app`}function Hs(e,a){return`${e}-${a}-deployments`}function bo(e,a){return`${e}-${a}-assets`}class dd{nodes=new Map;addResource(e,a){let r=this.extractDependencies(a);this.nodes.set(e,{logicalId:e,resource:a,dependencies:r})}extractDependencies(e){let a=new Set;if(e.DependsOn)if(Array.isArray(e.DependsOn))e.DependsOn.forEach((r)=>a.add(r));else a.add(e.DependsOn);return this.findReferences(e.Properties||{},a),a}findReferences(e,a){if(!e||typeof e!=="object")return;if("Ref"in e&&typeof e.Ref==="string"){if(!e.Ref.startsWith("AWS::"))a.add(e.Ref)}if("Fn::GetAtt"in e&&Array.isArray(e["Fn::GetAtt"]))a.add(e["Fn::GetAtt"][0]);for(let r of Object.values(e))if(typeof r==="object")this.findReferences(r,a)}topologicalSort(){let e=[],a=new Set,r=new Set,n=(i)=>{if(a.has(i))return;if(r.has(i))throw Error(`Circular dependency detected: ${i}`);r.add(i);let o=this.nodes.get(i);if(o)for(let c of o.dependencies)n(c);r.delete(i),a.add(i),e.push(i)};for(let i of this.nodes.keys())n(i);return e}validate(){for(let[e,a]of this.nodes.entries())for(let r of a.dependencies)if(!this.nodes.has(r))throw Error(`Resource "${e}" depends on "${r}" which does not exist`)}getDependents(e){let a=[];for(let[r,n]of this.nodes.entries())if(n.dependencies.has(e))a.push(r);return a}}function pp(e,a){let r=[],n=[],i=[],o=[],c=[],u=e.Resources||{},d=a.Resources||{},m=new Set([...Object.keys(u),...Object.keys(d)]);for(let g of m){let h=u[g],y=d[g];if(!h&&y)r.push({logicalId:g,action:"add",resourceType:y.Type});else if(h&&!y)n.push({logicalId:g,action:"remove",resourceType:h.Type});else if(h&&y)if(h.Type!==y.Type)o.push({logicalId:g,action:"replace",resourceType:y.Type,reason:`Type changed from ${h.Type} to ${y.Type}`});else{let f=ka(h.Properties||{},y.Properties||{});if(f.length>0)if(Pr(h.Type,f))o.push({logicalId:g,action:"replace",resourceType:y.Type,changes:f,reason:"Property changes require replacement"});else i.push({logicalId:g,action:"update",resourceType:y.Type,changes:f});else c.push(g)}}let p=Ir([...n,...o,...i]);return{added:r,removed:n,updated:i,replaced:o,unchanged:c,summary:{totalChanges:r.length+n.length+i.length+o.length,requiresReplacement:o.length>0,dangerousChanges:p}}}function ka(e,a,r=""){let n=[],i=new Set([...Object.keys(e),...Object.keys(a)]);for(let o of i){let c=r?`${r}.${o}`:o,u=e[o],d=a[o];if(u===void 0&&d!==void 0)n.push({path:c,oldValue:void 0,newValue:d});else if(u!==void 0&&d===void 0)n.push({path:c,oldValue:u,newValue:void 0});else if(typeof u!==typeof d)n.push({path:c,oldValue:u,newValue:d});else if(typeof u==="object"&&u!==null)if(Array.isArray(u)&&Array.isArray(d)){if(JSON.stringify(u)!==JSON.stringify(d))n.push({path:c,oldValue:u,newValue:d})}else if(!Array.isArray(u)&&!Array.isArray(d)){let m=ka(u,d,c);n.push(...m)}else n.push({path:c,oldValue:u,newValue:d});else if(u!==d)n.push({path:c,oldValue:u,newValue:d})}return n}function Pr(e,a){let r={"AWS::S3::Bucket":new Set(["BucketName"]),"AWS::DynamoDB::Table":new Set(["TableName","KeySchema"]),"AWS::RDS::DBInstance":new Set(["DBInstanceIdentifier","DBName","Engine"]),"AWS::Lambda::Function":new Set(["FunctionName"]),"AWS::EC2::Instance":new Set(["ImageId","InstanceType","KeyName"]),"AWS::ECS::TaskDefinition":new Set(["Family","ContainerDefinitions"]),"AWS::ElastiCache::CacheCluster":new Set(["CacheNodeType","Engine"]),"AWS::CloudFront::Distribution":new Set([]),"AWS::Route53::HostedZone":new Set(["Name"]),"AWS::IAM::Role":new Set(["RoleName","Path"]),"AWS::KMS::Key":new Set(["KeyPolicy"]),"AWS::Cognito::UserPool":new Set(["UserPoolName"]),"AWS::OpenSearchService::Domain":new Set(["DomainName"])}[e];if(!r)return!1;for(let n of a){let i=n.path.split(".")[0];if(r.has(i))return!0}return!1}function Ir(e){let a=[];for(let r of e){if(r.action==="remove"&&(r.resourceType==="AWS::RDS::DBInstance"||r.resourceType==="AWS::DynamoDB::Table"||r.resourceType==="AWS::ElastiCache::CacheCluster"))a.push(`Removing ${r.resourceType} ${r.logicalId} - data loss risk!`);if(r.action==="replace"&&(r.resourceType==="AWS::RDS::DBInstance"||r.resourceType==="AWS::DynamoDB::Table"))a.push(`Replacing ${r.resourceType} ${r.logicalId} - data loss risk!`);if((r.action==="remove"||r.action==="replace")&&r.resourceType==="AWS::S3::Bucket")a.push(`${r.action==="remove"?"Removing":"Replacing"} S3 bucket ${r.logicalId} - data loss risk!`);if(r.action==="replace"&&r.resourceType==="AWS::EC2::Instance")a.push(`Replacing EC2 instance ${r.logicalId} - downtime expected`);if(r.action==="update"&&r.resourceType==="AWS::EC2::SecurityGroup")a.push(`Updating security group ${r.logicalId} - may affect connectivity`);if((r.action==="update"||r.action==="replace")&&(r.resourceType==="AWS::IAM::Role"||r.resourceType==="AWS::IAM::Policy"))a.push(`Modifying IAM ${r.resourceType.split("::")[2]} ${r.logicalId} - may affect permissions`)}return a}function mp(e){let a=[];if(a.push(`=== Stack Update Analysis ===
|
|
19
19
|
`),e.summary.totalChanges===0)return a.push(`No changes detected.
|
|
20
20
|
`),a.join(`
|
|
21
21
|
`);if(a.push(`Total changes: ${e.summary.totalChanges}`),a.push(`Requires replacement: ${e.summary.requiresReplacement?"Yes":"No"}
|
|
22
22
|
`),e.summary.dangerousChanges.length>0){a.push("⚠️ DANGEROUS CHANGES DETECTED:");for(let r of e.summary.dangerousChanges)a.push(` • ${r}`);a.push("")}if(e.added.length>0){a.push(`✅ Resources to Add (${e.added.length}):`);for(let r of e.added)a.push(` + ${r.logicalId} (${r.resourceType})`);a.push("")}if(e.removed.length>0){a.push(`❌ Resources to Remove (${e.removed.length}):`);for(let r of e.removed)a.push(` - ${r.logicalId} (${r.resourceType})`);a.push("")}if(e.replaced.length>0){a.push(`\uD83D\uDD04 Resources to Replace (${e.replaced.length}):`);for(let r of e.replaced){if(a.push(` ~ ${r.logicalId} (${r.resourceType})`),r.reason)a.push(` Reason: ${r.reason}`);if(r.changes){for(let n of r.changes.slice(0,3))a.push(` • ${n.path}: ${JSON.stringify(n.oldValue)} → ${JSON.stringify(n.newValue)}`);if(r.changes.length>3)a.push(` ... and ${r.changes.length-3} more changes`)}}a.push("")}if(e.updated.length>0){a.push(`\uD83D\uDCDD Resources to Update (${e.updated.length}):`);for(let r of e.updated)if(a.push(` ~ ${r.logicalId} (${r.resourceType})`),r.changes){for(let n of r.changes.slice(0,3))a.push(` • ${n.path}: ${JSON.stringify(n.oldValue)} → ${JSON.stringify(n.newValue)}`);if(r.changes.length>3)a.push(` ... and ${r.changes.length-3} more changes`)}a.push("")}if(e.unchanged.length>0)a.push(`⚪ Unchanged Resources (${e.unchanged.length})`);return a.join(`
|
|
23
|
-
`)}class Le{static createBucket(e){let{name:a,bucketName:r,slug:n,environment:i,public:o=!1,versioning:c=!1,website:u=!1,encryption:d=!0,intelligentTiering:m=!1,cors:p,lifecycleRules:g}=e,h=r??l({slug:n,environment:i,resourceType:"s3",suffix:a}),y=s(h),f={Type:"AWS::S3::Bucket",Properties:{BucketName:h}};if(d)f.Properties.BucketEncryption={ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]};if(c)f.Properties.VersioningConfiguration={Status:"Enabled"};if(u)f.Properties.WebsiteConfiguration={IndexDocument:"index.html",ErrorDocument:"error.html"};if(!o)f.Properties.PublicAccessBlockConfiguration={BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0};if(p&&p.length>0)f.Properties.CorsConfiguration={CorsRules:p.map((v)=>({AllowedOrigins:v.allowedOrigins,AllowedMethods:v.allowedMethods,AllowedHeaders:v.allowedHeaders,MaxAge:v.maxAge}))};if(g&&g.length>0)f.Properties.LifecycleConfiguration={Rules:g.map((v)=>({Id:v.id,Status:v.enabled?"Enabled":"Disabled",ExpirationInDays:v.expirationDays,Transitions:v.transitions?.map((w)=>({TransitionInDays:w.days,StorageClass:w.storageClass}))}))};if(m&&g){let v={id:"IntelligentTieringRule",enabled:!0,transitions:[{days:0,storageClass:"INTELLIGENT_TIERING"}]};if(!f.Properties.LifecycleConfiguration)f.Properties.LifecycleConfiguration={Rules:[]};f.Properties.LifecycleConfiguration.Rules.push({Id:v.id,Status:"Enabled",Transitions:v.transitions?.map((w)=>({TransitionInDays:w.days,StorageClass:w.storageClass}))})}let b;if(o)b={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:P.Ref(y),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadGetObject",Effect:"Allow",Principal:"*",Action:["s3:GetObject"],Resource:[P.Join("",[P.GetAtt(y,"Arn"),"/*"])]}]}}};return{bucket:f,bucketPolicy:b,logicalId:y}}static enableVersioning(e){if(!e.Properties)e.Properties={};return e.Properties.VersioningConfiguration={Status:"Enabled"},e}static enableWebsiteHosting(e,a="index.html",r="error.html"){if(!e.Properties)e.Properties={};return e.Properties.WebsiteConfiguration={IndexDocument:a,ErrorDocument:r},e}static setLifecycleRules(e,a){if(!e.Properties)e.Properties={};return e.Properties.LifecycleConfiguration={Rules:a.map((r)=>({Id:r.id,Status:r.enabled?"Enabled":"Disabled",ExpirationInDays:r.expirationDays,Transitions:r.transitions?.map((n)=>({TransitionInDays:n.days,StorageClass:n.storageClass}))}))},e}static enableIntelligentTiering(e){if(!e.Properties)e.Properties={};if(!e.Properties.LifecycleConfiguration)e.Properties.LifecycleConfiguration={Rules:[]};return e.Properties.LifecycleConfiguration.Rules.push({Id:"IntelligentTieringRule",Status:"Enabled",Transitions:[{TransitionInDays:0,StorageClass:"INTELLIGENT_TIERING"}]}),e}static addLambdaNotification(e,a){if(!e.Properties)e.Properties={};if(!e.Properties.NotificationConfiguration)e.Properties.NotificationConfiguration={};if(!e.Properties.NotificationConfiguration.LambdaConfigurations)e.Properties.NotificationConfiguration.LambdaConfigurations=[];let r={Event:a.events[0],Function:a.functionArn};if(a.filter)r.Filter={S3Key:{Rules:[...a.filter.prefix?[{Name:"prefix",Value:a.filter.prefix}]:[],...a.filter.suffix?[{Name:"suffix",Value:a.filter.suffix}]:[]]}};for(let n of a.events){let i={...r,Event:n};e.Properties.NotificationConfiguration.LambdaConfigurations.push(i)}return e}static Notifications={onObjectCreated:(e)=>({functionArn:e,events:["s3:ObjectCreated:*"]}),onObjectRemoved:(e)=>({functionArn:e,events:["s3:ObjectRemoved:*"]}),onImageUpload:(e,a)=>({functionArn:e,events:["s3:ObjectCreated:*"],filter:{prefix:a,suffix:".jpg"}}),onFileType:(e,a,r)=>({functionArn:e,events:["s3:ObjectCreated:*"],filter:{prefix:r,suffix:a}}),onFolderUpload:(e,a)=>({functionArn:e,events:["s3:ObjectCreated:*"],filter:{prefix:a.endsWith("/")?a:`${a}/`}})};static createBackupPlan(e){let{name:a,slug:r,environment:n,bucketLogicalIds:i,retentionDays:o,schedule:c="cron(0 5 * * ? *)",vaultName:u,enableContinuousBackup:d=!1,moveToColdStorageAfterDays:m}=e,p=u||l({slug:r,environment:n,resourceType:"backup-vault",suffix:a}),g=s(p),h={Type:"AWS::Backup::BackupVault",Properties:{BackupVaultName:p}},y=l({slug:r,environment:n,resourceType:"backup-role",suffix:a}),f=s(y),b={Type:"AWS::IAM::Role",Properties:{RoleName:y,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"backup.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSBackupServiceRolePolicyForBackup","arn:aws:iam::aws:policy/service-role/AWSBackupServiceRolePolicyForRestores"]}},v=l({slug:r,environment:n,resourceType:"backup-plan",suffix:a}),w=s(v),R={DeleteAfterDays:o};if(m&&m<o)R.MoveToColdStorageAfterDays=m;let T={Type:"AWS::Backup::BackupPlan",Properties:{BackupPlan:{BackupPlanName:v,BackupPlanRule:[{RuleName:`${a}-daily-backup`,TargetBackupVault:P.Ref(g),ScheduleExpression:c,StartWindowMinutes:60,CompletionWindowMinutes:120,Lifecycle:R,EnableContinuousBackup:d}]}}},N=l({slug:r,environment:n,resourceType:"backup-selection",suffix:a}),I=s(N),k=i.map((L)=>P.GetAtt(L,"Arn")),x={Type:"AWS::Backup::BackupSelection",Properties:{BackupPlanId:P.Ref(w),BackupSelection:{SelectionName:N,IamRoleArn:P.GetAtt(f,"Arn"),Resources:k}}};return{vault:h,plan:T,selection:x,role:b,vaultLogicalId:g,planLogicalId:w,selectionLogicalId:I,roleLogicalId:f}}static BackupSchedules={HOURLY:"cron(0 * * * ? *)",DAILY_5AM:"cron(0 5 * * ? *)",DAILY_MIDNIGHT:"cron(0 0 * * ? *)",WEEKLY_SUNDAY:"cron(0 5 ? * SUN *)",WEEKLY_SATURDAY:"cron(0 5 ? * SAT *)",MONTHLY_FIRST:"cron(0 5 1 * ? *)",EVERY_12_HOURS:"cron(0 */12 * * ? *)",EVERY_6_HOURS:"cron(0 */6 * * ? *)"};static BackupRetention={ONE_DAY:1,ONE_WEEK:7,TWO_WEEKS:14,ONE_MONTH:30,THREE_MONTHS:90,SIX_MONTHS:180,ONE_YEAR:365,TWO_YEARS:730,FIVE_YEARS:1825,SEVEN_YEARS:2555};static createWwwRedirectBucket(e){let{slug:a,environment:r,sourceDomain:n,targetDomain:i,protocol:o="https"}=e,c=l({slug:a,environment:r,resourceType:"s3",suffix:"www-redirect"}),u=s(c),d={Type:"AWS::S3::Bucket",Properties:{BucketName:n,WebsiteConfiguration:{RedirectAllRequestsTo:{HostName:i,Protocol:o}},PublicAccessBlockConfiguration:{BlockPublicAcls:!1,BlockPublicPolicy:!1,IgnorePublicAcls:!1,RestrictPublicBuckets:!1}}},m={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:P.Ref(u),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadForRedirect",Effect:"Allow",Principal:"*",Action:["s3:GetObject"],Resource:[P.Join("",[P.GetAtt(u,"Arn"),"/*"])]}]}}};return{bucket:d,bucketPolicy:m,logicalId:u}}static createDocsBucket(e){let{slug:a,environment:r,domain:n}=e,i=n||l({slug:a,environment:r,resourceType:"s3",suffix:"docs"}),o=s(i);return{bucket:{Type:"AWS::S3::Bucket",Properties:{BucketName:i,BucketEncryption:{ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]},PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},Tags:[{Key:"backup",Value:"weekly"}]}},logicalId:o}}static createEmailBucket(e){let{slug:a,environment:r}=e,n=l({slug:a,environment:r,resourceType:"s3",suffix:"email"}),i=s(n),o={Type:"AWS::S3::Bucket",Properties:{BucketName:n,BucketEncryption:{ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]},PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},LifecycleConfiguration:{Rules:[{Id:"EmailRetention",Status:"Enabled",ExpirationInDays:90,Transitions:[{TransitionInDays:30,StorageClass:"STANDARD_IA"}]}]}}},c={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:P.Ref(i),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowSESPuts",Effect:"Allow",Principal:{Service:"ses.amazonaws.com"},Action:"s3:PutObject",Resource:P.Join("",[P.GetAtt(i,"Arn"),"/*"]),Condition:{StringEquals:{"AWS:SourceAccount":P.Ref("AWS::AccountId")}}}]}}};return{bucket:o,bucketPolicy:c,logicalId:i}}static docsExist(e={}){let{projectRoot:a=process.cwd(),docsPaths:r=["docs","documentation","doc"]}=e;for(let n of r){let i=ce(a,n);if(Ge(i)){let o=["dist","build",".bunpress/dist","_site","out","public"];for(let c of o){let u=ce(i,c);if(Ge(u))try{if(Rr(u).length>0)return{exists:!0,path:i,hasDistFolder:!0,distPath:u}}catch{}}return{exists:!0,path:i,hasDistFolder:!1,distPath:null}}}return{exists:!1,path:null,hasDistFolder:!1,distPath:null}}static createDocsBucketIfExists(e){let a=Le.docsExist({projectRoot:e.projectRoot,docsPaths:e.docsPaths});if(!a.exists)return{bucket:null,logicalId:null,docsInfo:a};let r=Le.createDocsBucket({slug:e.slug,environment:e.environment,domain:e.domain});return{bucket:r.bucket,bucketPolicy:r.bucketPolicy,logicalId:r.logicalId,docsInfo:a}}static createPrivateBucket(e){let{slug:a,environment:r,enableVersioning:n=!0,retentionDays:i,encryptionKeyArn:o}=e,c=l({slug:a,environment:r,resourceType:"s3",suffix:"private"}),u=s(c);return{bucket:{Type:"AWS::S3::Bucket",Properties:{BucketName:c,BucketEncryption:{ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:o?{SSEAlgorithm:"aws:kms",KMSMasterKeyID:o}:{SSEAlgorithm:"AES256"}}]},PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},VersioningConfiguration:n?{Status:"Enabled"}:void 0,LifecycleConfiguration:i?{Rules:[{Id:"RetentionPolicy",Status:"Enabled",ExpirationInDays:i}]}:void 0,Tags:[{Key:"backup",Value:"daily"}]}},logicalId:u}}static checkSourcePaths(e={}){let{projectRoot:a=process.cwd(),paths:r={}}=e,n=r.web||"views/web/dist",i=r.docs||"docs/dist",o=r.private||"private";return{web:{exists:Ge(ce(a,n)),path:ce(a,n)},docs:{exists:Ge(ce(a,i)),path:ce(a,i)},private:{exists:Ge(ce(a,o)),path:ce(a,o)}}}static createDeploymentBuckets(e){let{slug:a,environment:r,domain:n,projectRoot:i,paths:o}=e,c=Le.checkSourcePaths({projectRoot:i,paths:o}),u={},d={web:!1,docs:!1,private:!1},m=Le.createBucket({name:"web",slug:a,environment:r,public:!1,versioning:!1,encryption:!0});if(u[m.logicalId]=m.bucket,d.web=!0,c.docs.exists){let p=Le.createDocsBucket({slug:a,environment:r,domain:n?`docs.${n}`:void 0});if(u[p.logicalId]=p.bucket,p.bucketPolicy)u[`${p.logicalId}Policy`]=p.bucketPolicy;d.docs=!0}if(c.private.exists){let p=Le.createPrivateBucket({slug:a,environment:r,enableVersioning:!0});u[p.logicalId]=p.bucket,d.private=!0}return{resources:u,created:d,sourcePaths:c}}}class vt{static createRepository(e){let{name:a,slug:r,environment:n,scanOnPush:i=!0,imageMutability:o="MUTABLE",encryption:c="AES256",kmsKey:u,lifecyclePolicy:d,tags:m}=e,p=l({slug:r,environment:n,resourceType:"ecr",suffix:a}),g=s(p),h={Type:"AWS::ECR::Repository",Properties:{RepositoryName:p,ImageTagMutability:o,ImageScanningConfiguration:{ScanOnPush:i},EncryptionConfiguration:{EncryptionType:c,...u&&c==="KMS"?{KmsKey:u}:{}}}};if(d)h.Properties.LifecyclePolicy={LifecyclePolicyText:JSON.stringify(vt.generateLifecyclePolicy(d))};if(m)h.Properties.Tags=Object.entries(m).map(([y,f])=>({Key:y,Value:f}));return{repository:h,logicalId:g}}static generateLifecyclePolicy(e){let a=[];if(e.untaggedImageExpireDays!==void 0)a.push({rulePriority:1,description:"Delete untagged images",selection:{tagStatus:"untagged",countType:"sinceImagePushed",countNumber:e.untaggedImageExpireDays,countUnit:"days"},action:{type:"expire"}});if(e.maxImageCount!==void 0)a.push({rulePriority:a.length+1,description:"Keep only most recent images",selection:{tagStatus:"any",countType:"imageCountMoreThan",countNumber:e.maxImageCount},action:{type:"expire"}});if(e.maxImageAgeDays!==void 0)a.push({rulePriority:a.length+1,description:"Delete images older than specified days",selection:{tagStatus:"any",countType:"sinceImagePushed",countNumber:e.maxImageAgeDays,countUnit:"days"},action:{type:"expire"}});return{rules:a}}static LifecyclePolicies={production:{maxImageCount:10,untaggedImageExpireDays:7},development:{maxImageCount:5,untaggedImageExpireDays:3},minimal:{maxImageCount:3,untaggedImageExpireDays:1},archive:{maxImageCount:50,untaggedImageExpireDays:30}};static enableImmutableTags(e){if(!e.Properties)e.Properties={};return e.Properties.ImageTagMutability="IMMUTABLE",e}static enableScanOnPush(e){if(!e.Properties)e.Properties={};return e.Properties.ImageScanningConfiguration={ScanOnPush:!0},e}static setLifecyclePolicy(e,a){if(!e.Properties)e.Properties={};return e.Properties.LifecyclePolicy={LifecyclePolicyText:JSON.stringify(vt.generateLifecyclePolicy(a))},e}static addCrossAccountAccess(e,a){if(!e.Properties)e.Properties={};return e.Properties.RepositoryPolicyText={Version:"2012-10-17",Statement:[{Sid:"CrossAccountPull",Effect:"Allow",Principal:{AWS:a.map((r)=>`arn:aws:iam::${r}:root`)},Action:["ecr:GetDownloadUrlForLayer","ecr:BatchGetImage","ecr:BatchCheckLayerAvailability"]}]},e}static addLambdaAccess(e){if(!e.Properties)e.Properties={};return e.Properties.RepositoryPolicyText={Version:"2012-10-17",Statement:[{Sid:"LambdaECRImageRetrievalPolicy",Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:["ecr:GetDownloadUrlForLayer","ecr:BatchGetImage"]}]},e}static generateBunDockerfile(e){let{baseImage:a="oven/bun:1-debian",serverPath:r,port:n=3000,additionalDirs:i=[],healthCheckEndpoint:o="/health",nodeCompatible:c=!1,envVars:u={},buildCommands:d=[],runCommand:m}=e,p=["app","config",...i],g=m||`bun run ${r}`,h=`# Multi-stage build for Bun application
|
|
23
|
+
`)}class Le{static createBucket(e){let{name:a,bucketName:r,slug:n,environment:i,public:o=!1,versioning:c=!1,website:u=!1,encryption:d=!0,intelligentTiering:m=!1,cors:p,lifecycleRules:g}=e,h=r??l({slug:n,environment:i,resourceType:"s3",suffix:a}),y=s(h),f={Type:"AWS::S3::Bucket",Properties:{BucketName:h}};if(d)f.Properties.BucketEncryption={ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]};if(c)f.Properties.VersioningConfiguration={Status:"Enabled"};if(u)f.Properties.WebsiteConfiguration={IndexDocument:"index.html",ErrorDocument:"error.html"};if(!o)f.Properties.PublicAccessBlockConfiguration={BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0};if(p&&p.length>0)f.Properties.CorsConfiguration={CorsRules:p.map((v)=>({AllowedOrigins:v.allowedOrigins,AllowedMethods:v.allowedMethods,AllowedHeaders:v.allowedHeaders,MaxAge:v.maxAge}))};if(g&&g.length>0)f.Properties.LifecycleConfiguration={Rules:g.map((v)=>({Id:v.id,Status:v.enabled?"Enabled":"Disabled",ExpirationInDays:v.expirationDays,Transitions:v.transitions?.map((w)=>({TransitionInDays:w.days,StorageClass:w.storageClass}))}))};if(m&&g){let v={id:"IntelligentTieringRule",enabled:!0,transitions:[{days:0,storageClass:"INTELLIGENT_TIERING"}]};if(!f.Properties.LifecycleConfiguration)f.Properties.LifecycleConfiguration={Rules:[]};f.Properties.LifecycleConfiguration.Rules.push({Id:v.id,Status:"Enabled",Transitions:v.transitions?.map((w)=>({TransitionInDays:w.days,StorageClass:w.storageClass}))})}let b;if(o)b={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:P.Ref(y),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadGetObject",Effect:"Allow",Principal:"*",Action:["s3:GetObject"],Resource:[P.Join("",[P.GetAtt(y,"Arn"),"/*"])]}]}}};return{bucket:f,bucketPolicy:b,logicalId:y}}static enableVersioning(e){if(!e.Properties)e.Properties={};return e.Properties.VersioningConfiguration={Status:"Enabled"},e}static enableWebsiteHosting(e,a="index.html",r="error.html"){if(!e.Properties)e.Properties={};return e.Properties.WebsiteConfiguration={IndexDocument:a,ErrorDocument:r},e}static setLifecycleRules(e,a){if(!e.Properties)e.Properties={};return e.Properties.LifecycleConfiguration={Rules:a.map((r)=>({Id:r.id,Status:r.enabled?"Enabled":"Disabled",ExpirationInDays:r.expirationDays,Transitions:r.transitions?.map((n)=>({TransitionInDays:n.days,StorageClass:n.storageClass}))}))},e}static enableIntelligentTiering(e){if(!e.Properties)e.Properties={};if(!e.Properties.LifecycleConfiguration)e.Properties.LifecycleConfiguration={Rules:[]};return e.Properties.LifecycleConfiguration.Rules.push({Id:"IntelligentTieringRule",Status:"Enabled",Transitions:[{TransitionInDays:0,StorageClass:"INTELLIGENT_TIERING"}]}),e}static addLambdaNotification(e,a){if(!e.Properties)e.Properties={};if(!e.Properties.NotificationConfiguration)e.Properties.NotificationConfiguration={};if(!e.Properties.NotificationConfiguration.LambdaConfigurations)e.Properties.NotificationConfiguration.LambdaConfigurations=[];let r={Event:a.events[0],Function:a.functionArn};if(a.filter)r.Filter={S3Key:{Rules:[...a.filter.prefix?[{Name:"prefix",Value:a.filter.prefix}]:[],...a.filter.suffix?[{Name:"suffix",Value:a.filter.suffix}]:[]]}};for(let n of a.events){let i={...r,Event:n};e.Properties.NotificationConfiguration.LambdaConfigurations.push(i)}return e}static Notifications={onObjectCreated:(e)=>({functionArn:e,events:["s3:ObjectCreated:*"]}),onObjectRemoved:(e)=>({functionArn:e,events:["s3:ObjectRemoved:*"]}),onImageUpload:(e,a)=>({functionArn:e,events:["s3:ObjectCreated:*"],filter:{prefix:a,suffix:".jpg"}}),onFileType:(e,a,r)=>({functionArn:e,events:["s3:ObjectCreated:*"],filter:{prefix:r,suffix:a}}),onFolderUpload:(e,a)=>({functionArn:e,events:["s3:ObjectCreated:*"],filter:{prefix:a.endsWith("/")?a:`${a}/`}})};static createBackupPlan(e){let{name:a,slug:r,environment:n,bucketLogicalIds:i,retentionDays:o,schedule:c="cron(0 5 * * ? *)",vaultName:u,enableContinuousBackup:d=!1,moveToColdStorageAfterDays:m}=e,p=u||l({slug:r,environment:n,resourceType:"backup-vault",suffix:a}),g=s(p),h={Type:"AWS::Backup::BackupVault",Properties:{BackupVaultName:p}},y=l({slug:r,environment:n,resourceType:"backup-role",suffix:a}),f=s(y),b={Type:"AWS::IAM::Role",Properties:{RoleName:y,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"backup.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSBackupServiceRolePolicyForBackup","arn:aws:iam::aws:policy/service-role/AWSBackupServiceRolePolicyForRestores"]}},v=l({slug:r,environment:n,resourceType:"backup-plan",suffix:a}),w=s(v),R={DeleteAfterDays:o};if(m&&m<o)R.MoveToColdStorageAfterDays=m;let T={Type:"AWS::Backup::BackupPlan",Properties:{BackupPlan:{BackupPlanName:v,BackupPlanRule:[{RuleName:`${a}-daily-backup`,TargetBackupVault:P.Ref(g),ScheduleExpression:c,StartWindowMinutes:60,CompletionWindowMinutes:120,Lifecycle:R,EnableContinuousBackup:d}]}}},N=l({slug:r,environment:n,resourceType:"backup-selection",suffix:a}),I=s(N),k=i.map((L)=>P.GetAtt(L,"Arn")),O={Type:"AWS::Backup::BackupSelection",Properties:{BackupPlanId:P.Ref(w),BackupSelection:{SelectionName:N,IamRoleArn:P.GetAtt(f,"Arn"),Resources:k}}};return{vault:h,plan:T,selection:O,role:b,vaultLogicalId:g,planLogicalId:w,selectionLogicalId:I,roleLogicalId:f}}static BackupSchedules={HOURLY:"cron(0 * * * ? *)",DAILY_5AM:"cron(0 5 * * ? *)",DAILY_MIDNIGHT:"cron(0 0 * * ? *)",WEEKLY_SUNDAY:"cron(0 5 ? * SUN *)",WEEKLY_SATURDAY:"cron(0 5 ? * SAT *)",MONTHLY_FIRST:"cron(0 5 1 * ? *)",EVERY_12_HOURS:"cron(0 */12 * * ? *)",EVERY_6_HOURS:"cron(0 */6 * * ? *)"};static BackupRetention={ONE_DAY:1,ONE_WEEK:7,TWO_WEEKS:14,ONE_MONTH:30,THREE_MONTHS:90,SIX_MONTHS:180,ONE_YEAR:365,TWO_YEARS:730,FIVE_YEARS:1825,SEVEN_YEARS:2555};static createWwwRedirectBucket(e){let{slug:a,environment:r,sourceDomain:n,targetDomain:i,protocol:o="https"}=e,c=l({slug:a,environment:r,resourceType:"s3",suffix:"www-redirect"}),u=s(c),d={Type:"AWS::S3::Bucket",Properties:{BucketName:n,WebsiteConfiguration:{RedirectAllRequestsTo:{HostName:i,Protocol:o}},PublicAccessBlockConfiguration:{BlockPublicAcls:!1,BlockPublicPolicy:!1,IgnorePublicAcls:!1,RestrictPublicBuckets:!1}}},m={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:P.Ref(u),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadForRedirect",Effect:"Allow",Principal:"*",Action:["s3:GetObject"],Resource:[P.Join("",[P.GetAtt(u,"Arn"),"/*"])]}]}}};return{bucket:d,bucketPolicy:m,logicalId:u}}static createDocsBucket(e){let{slug:a,environment:r,domain:n}=e,i=n||l({slug:a,environment:r,resourceType:"s3",suffix:"docs"}),o=s(i);return{bucket:{Type:"AWS::S3::Bucket",Properties:{BucketName:i,BucketEncryption:{ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]},PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},Tags:[{Key:"backup",Value:"weekly"}]}},logicalId:o}}static createEmailBucket(e){let{slug:a,environment:r}=e,n=l({slug:a,environment:r,resourceType:"s3",suffix:"email"}),i=s(n),o={Type:"AWS::S3::Bucket",Properties:{BucketName:n,BucketEncryption:{ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]},PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},LifecycleConfiguration:{Rules:[{Id:"EmailRetention",Status:"Enabled",ExpirationInDays:90,Transitions:[{TransitionInDays:30,StorageClass:"STANDARD_IA"}]}]}}},c={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:P.Ref(i),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowSESPuts",Effect:"Allow",Principal:{Service:"ses.amazonaws.com"},Action:"s3:PutObject",Resource:P.Join("",[P.GetAtt(i,"Arn"),"/*"]),Condition:{StringEquals:{"AWS:SourceAccount":P.Ref("AWS::AccountId")}}}]}}};return{bucket:o,bucketPolicy:c,logicalId:i}}static docsExist(e={}){let{projectRoot:a=process.cwd(),docsPaths:r=["docs","documentation","doc"]}=e;for(let n of r){let i=ce(a,n);if(Ge(i)){let o=["dist","build",".bunpress/dist","_site","out","public"];for(let c of o){let u=ce(i,c);if(Ge(u))try{if(Rr(u).length>0)return{exists:!0,path:i,hasDistFolder:!0,distPath:u}}catch{}}return{exists:!0,path:i,hasDistFolder:!1,distPath:null}}}return{exists:!1,path:null,hasDistFolder:!1,distPath:null}}static createDocsBucketIfExists(e){let a=Le.docsExist({projectRoot:e.projectRoot,docsPaths:e.docsPaths});if(!a.exists)return{bucket:null,logicalId:null,docsInfo:a};let r=Le.createDocsBucket({slug:e.slug,environment:e.environment,domain:e.domain});return{bucket:r.bucket,bucketPolicy:r.bucketPolicy,logicalId:r.logicalId,docsInfo:a}}static createPrivateBucket(e){let{slug:a,environment:r,enableVersioning:n=!0,retentionDays:i,encryptionKeyArn:o}=e,c=l({slug:a,environment:r,resourceType:"s3",suffix:"private"}),u=s(c);return{bucket:{Type:"AWS::S3::Bucket",Properties:{BucketName:c,BucketEncryption:{ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:o?{SSEAlgorithm:"aws:kms",KMSMasterKeyID:o}:{SSEAlgorithm:"AES256"}}]},PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},VersioningConfiguration:n?{Status:"Enabled"}:void 0,LifecycleConfiguration:i?{Rules:[{Id:"RetentionPolicy",Status:"Enabled",ExpirationInDays:i}]}:void 0,Tags:[{Key:"backup",Value:"daily"}]}},logicalId:u}}static checkSourcePaths(e={}){let{projectRoot:a=process.cwd(),paths:r={}}=e,n=r.web||"views/web/dist",i=r.docs||"docs/dist",o=r.private||"private";return{web:{exists:Ge(ce(a,n)),path:ce(a,n)},docs:{exists:Ge(ce(a,i)),path:ce(a,i)},private:{exists:Ge(ce(a,o)),path:ce(a,o)}}}static createDeploymentBuckets(e){let{slug:a,environment:r,domain:n,projectRoot:i,paths:o}=e,c=Le.checkSourcePaths({projectRoot:i,paths:o}),u={},d={web:!1,docs:!1,private:!1},m=Le.createBucket({name:"web",slug:a,environment:r,public:!1,versioning:!1,encryption:!0});if(u[m.logicalId]=m.bucket,d.web=!0,c.docs.exists){let p=Le.createDocsBucket({slug:a,environment:r,domain:n?`docs.${n}`:void 0});if(u[p.logicalId]=p.bucket,p.bucketPolicy)u[`${p.logicalId}Policy`]=p.bucketPolicy;d.docs=!0}if(c.private.exists){let p=Le.createPrivateBucket({slug:a,environment:r,enableVersioning:!0});u[p.logicalId]=p.bucket,d.private=!0}return{resources:u,created:d,sourcePaths:c}}}class vt{static createRepository(e){let{name:a,slug:r,environment:n,scanOnPush:i=!0,imageMutability:o="MUTABLE",encryption:c="AES256",kmsKey:u,lifecyclePolicy:d,tags:m}=e,p=l({slug:r,environment:n,resourceType:"ecr",suffix:a}),g=s(p),h={Type:"AWS::ECR::Repository",Properties:{RepositoryName:p,ImageTagMutability:o,ImageScanningConfiguration:{ScanOnPush:i},EncryptionConfiguration:{EncryptionType:c,...u&&c==="KMS"?{KmsKey:u}:{}}}};if(d)h.Properties.LifecyclePolicy={LifecyclePolicyText:JSON.stringify(vt.generateLifecyclePolicy(d))};if(m)h.Properties.Tags=Object.entries(m).map(([y,f])=>({Key:y,Value:f}));return{repository:h,logicalId:g}}static generateLifecyclePolicy(e){let a=[];if(e.untaggedImageExpireDays!==void 0)a.push({rulePriority:1,description:"Delete untagged images",selection:{tagStatus:"untagged",countType:"sinceImagePushed",countNumber:e.untaggedImageExpireDays,countUnit:"days"},action:{type:"expire"}});if(e.maxImageCount!==void 0)a.push({rulePriority:a.length+1,description:"Keep only most recent images",selection:{tagStatus:"any",countType:"imageCountMoreThan",countNumber:e.maxImageCount},action:{type:"expire"}});if(e.maxImageAgeDays!==void 0)a.push({rulePriority:a.length+1,description:"Delete images older than specified days",selection:{tagStatus:"any",countType:"sinceImagePushed",countNumber:e.maxImageAgeDays,countUnit:"days"},action:{type:"expire"}});return{rules:a}}static LifecyclePolicies={production:{maxImageCount:10,untaggedImageExpireDays:7},development:{maxImageCount:5,untaggedImageExpireDays:3},minimal:{maxImageCount:3,untaggedImageExpireDays:1},archive:{maxImageCount:50,untaggedImageExpireDays:30}};static enableImmutableTags(e){if(!e.Properties)e.Properties={};return e.Properties.ImageTagMutability="IMMUTABLE",e}static enableScanOnPush(e){if(!e.Properties)e.Properties={};return e.Properties.ImageScanningConfiguration={ScanOnPush:!0},e}static setLifecyclePolicy(e,a){if(!e.Properties)e.Properties={};return e.Properties.LifecyclePolicy={LifecyclePolicyText:JSON.stringify(vt.generateLifecyclePolicy(a))},e}static addCrossAccountAccess(e,a){if(!e.Properties)e.Properties={};return e.Properties.RepositoryPolicyText={Version:"2012-10-17",Statement:[{Sid:"CrossAccountPull",Effect:"Allow",Principal:{AWS:a.map((r)=>`arn:aws:iam::${r}:root`)},Action:["ecr:GetDownloadUrlForLayer","ecr:BatchGetImage","ecr:BatchCheckLayerAvailability"]}]},e}static addLambdaAccess(e){if(!e.Properties)e.Properties={};return e.Properties.RepositoryPolicyText={Version:"2012-10-17",Statement:[{Sid:"LambdaECRImageRetrievalPolicy",Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:["ecr:GetDownloadUrlForLayer","ecr:BatchGetImage"]}]},e}static generateBunDockerfile(e){let{baseImage:a="oven/bun:1-debian",serverPath:r,port:n=3000,additionalDirs:i=[],healthCheckEndpoint:o="/health",nodeCompatible:c=!1,envVars:u={},buildCommands:d=[],runCommand:m}=e,p=["app","config",...i],g=m||`bun run ${r}`,h=`# Multi-stage build for Bun application
|
|
24
24
|
# Generated by ts-cloud
|
|
25
25
|
|
|
26
26
|
# Builder stage
|
|
@@ -103,7 +103,7 @@ echo "Image: $IMAGE_URI:${n}"
|
|
|
103
103
|
docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG
|
|
104
104
|
docker push $ECR_REGISTRY/$ECR_REPOSITORY:latest`},...e.ecsCluster&&e.ecsService?[{name:"Deploy to ECS",run:`aws ecs update-service --cluster ${e.ecsCluster} --service ${e.ecsService} --force-new-deployment`}]:[]]}}};return`# Generated by ts-cloud
|
|
105
105
|
${JSON.stringify(a,null,2).replace(/"/g,"").replace(/,\n/g,`
|
|
106
|
-
`)}`}};static DockerfileTemplates={bunServer:(e,a=3000)=>vt.generateBunDockerfile({serverPath:e,port:a}),bunWithBuild:(e,a,r=3000)=>vt.generateBunDockerfile({serverPath:e,port:r,buildCommands:[a]}),bunFullStack:(e,a=3000)=>vt.generateBunDockerfile({serverPath:e,port:a,additionalDirs:["public","views","dist"],buildCommands:["bun run build"]}),bunApi:(e,a=3000)=>vt.generateBunDockerfile({serverPath:e,port:a,healthCheckEndpoint:"/api/health"})}}var
|
|
106
|
+
`)}`}};static DockerfileTemplates={bunServer:(e,a=3000)=>vt.generateBunDockerfile({serverPath:e,port:a}),bunWithBuild:(e,a,r=3000)=>vt.generateBunDockerfile({serverPath:e,port:r,buildCommands:[a]}),bunFullStack:(e,a=3000)=>vt.generateBunDockerfile({serverPath:e,port:a,additionalDirs:["public","views","dist"],buildCommands:["bun run build"]}),bunApi:(e,a=3000)=>vt.generateBunDockerfile({serverPath:e,port:a,healthCheckEndpoint:"/api/health"})}}var qs=[400,403,404,416,429,500,502,503,504],ic=[500,502,503,504],oc=["GET","HEAD","OPTIONS"],gp="-failover-group";function ud(e){if(e===void 0)return[...ic];if(e.length===0)throw Error(`CloudFront origin failover: statusCodes must list at least one code (allowed: ${qs.join(", ")}). Omit it to use the default ${ic.join(", ")}.`);let a=e.filter((r)=>!qs.includes(r));if(a.length>0)throw Error(`CloudFront origin failover: ${a.join(", ")} ${a.length===1?"is not a status code":"are not status codes"} CloudFront can fail over on. Allowed: ${qs.join(", ")}.`);return[...new Set(e)].sort((r,n)=>r-n)}function sc(e){let{primaryOriginId:a,secondaryOriginId:r}=e;if(!a||!r)throw Error("CloudFront origin failover: both a primary and a secondary origin id are required");if(a===r)throw Error(`CloudFront origin failover: the secondary origin must differ from the primary (both are "${a}")`);let n=ud(e.statusCodes);return{Id:e.groupId??`${a}-failover-group`,FailoverCriteria:{StatusCodes:{Quantity:n.length,Items:n}},Members:{Quantity:2,Items:[{OriginId:a},{OriginId:r}]}}}function Ws(e){return{Quantity:1,Items:[sc(e)]}}function vo(e,a="the cache behavior"){let r=(Array.isArray(e)?e:e?.Items??[]).filter((n)=>!oc.includes(n.toUpperCase()));if(r.length>0)throw Error(`CloudFront origin failover: ${a} allows ${r.join(", ")}, but a cache behavior that targets an origin group may only allow ${oc.join(", ")}. CloudFront never fails over a write, so point the write paths at a single origin in their own cache behavior.`)}function To(e){return/\.s3[.-](?:[a-z0-9-]+\.)?amazonaws\.com(?:\.cn)?$/i.test(e)&&!/s3-website/i.test(e)}class Me{static createDistribution(e){let{slug:a,environment:r,origin:n,customDomain:i,certificateArn:o,errorPages:c,cachePolicy:u,edgeFunctions:d,http3:m=!1,comment:p,failoverOrigin:g}=e,h=l({slug:a,environment:r,resourceType:"cdn"}),y=s(h),f={Id:"DefaultOrigin",DomainName:n.domainName,OriginPath:n.originPath||""},b;if(n.type==="s3"){let w=`${y}OAC`;b={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`${h}-oac`,Description:`Origin Access Control for ${h}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},f.OriginAccessControlId=P.Ref(w)}else if(n.type==="alb"||n.type==="custom")f.CustomOriginConfig={HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only"};let v={Type:"AWS::CloudFront::Distribution",Properties:{DistributionConfig:{Enabled:!0,Comment:p||`CDN for ${h}`,DefaultRootObject:"index.html",Origins:[f],DefaultCacheBehavior:{TargetOriginId:"DefaultOrigin",ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0},PriceClass:"PriceClass_100",HttpVersion:m?"http2and3":"http2"}}};if(i&&o)v.Properties.DistributionConfig.Aliases=[i],v.Properties.DistributionConfig.ViewerCertificate={AcmCertificateArn:o,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};if(c&&c.length>0)v.Properties.DistributionConfig.CustomErrorResponses=c.map((w)=>({ErrorCode:w.errorCode,ResponseCode:w.responseCode,ResponsePagePath:w.responsePagePath}));if(d&&d.length>0)v.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations=d.map((w)=>({EventType:w.event,LambdaFunctionARN:w.functionArn}));if(g)Me.addOriginFailover(v,g);return{distribution:v,originAccessControl:b,logicalId:y}}static addOriginFailover(e,a){let r=e.Properties.DistributionConfig,n=r.DefaultCacheBehavior,i=n.TargetOriginId,o=a.id??"FailoverOrigin";if(r.OriginGroups&&r.OriginGroups.Quantity>0)throw Error("CloudFront origin failover: this distribution already has an origin group");if(vo(n.AllowedMethods??["GET","HEAD"],"the default cache behavior"),r.Origins.some((m)=>m.Id===o))throw Error(`CloudFront origin failover: an origin with id "${o}" already exists`);let c=sc({primaryOriginId:i,secondaryOriginId:o,statusCodes:a.statusCodes}),u=a.type??(To(a.domainName)?"s3":"custom"),d={Id:o,DomainName:a.domainName,OriginPath:a.originPath||""};if(u==="s3"){let m=r.Origins.find((p)=>p.Id===i);if(d.S3OriginConfig={OriginAccessIdentity:""},m?.OriginAccessControlId)d.OriginAccessControlId=m.OriginAccessControlId}else d.CustomOriginConfig={HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only"};return r.Origins.push(d),r.OriginGroups={Quantity:1,Items:[c]},n.TargetOriginId=c.Id,e}static setCustomDomain(e,a,r){return e.Properties.DistributionConfig.Aliases=[a],e.Properties.DistributionConfig.ViewerCertificate={AcmCertificateArn:r,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"},e}static setErrorPages(e,a){return e.Properties.DistributionConfig.CustomErrorResponses=a.map((r)=>({ErrorCode:r.errorCode,ResponseCode:r.responseCode,ResponsePagePath:r.responsePagePath})),e}static enableHttp3(e){return e.Properties.DistributionConfig.HttpVersion="http2and3",e}static addEdgeFunction(e,a,r){if(!e.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations)e.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations=[];return e.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations.push({EventType:a,LambdaFunctionARN:r}),e}static setCachePolicy(e,a){return e.Properties.DistributionConfig.Comment=`${e.Properties.DistributionConfig.Comment||""} (TTL: ${a.default||86400}s)`,e}static createSpaDistribution(e){return Me.createDistribution({...e,errorPages:[{errorCode:404,responseCode:200,responsePagePath:"/index.html"},{errorCode:403,responseCode:200,responsePagePath:"/index.html"}]})}static createDocsOriginRequestFunction(e){let{slug:a,environment:r}=e,n=l({slug:a,environment:r,resourceType:"edge-docs"}),i=s(n),o=s(`${n}-role`),c=s(`${n}-version`),u={Type:"AWS::IAM::Role",Properties:{RoleName:`${n}-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:["lambda.amazonaws.com","edgelambda.amazonaws.com"]},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"]}},d=`
|
|
107
107
|
'use strict';
|
|
108
108
|
|
|
109
109
|
exports.handler = async (event) => {
|
|
@@ -209,7 +209,7 @@ exports.handler = async (event) => {
|
|
|
209
209
|
|
|
210
210
|
return request;
|
|
211
211
|
};
|
|
212
|
-
`.trim()};static Config={ttl:(e)=>{let{min:a=0,max:r=86400,default:n=86400}=e;return{MinTTL:a,MaxTTL:r,DefaultTTL:n}},cookies:(e,a)=>{let r={Forward:e==="allowList"?"whitelist":e};if(e==="allowList"&&a)r.WhitelistedNames=a;return r},allowedMethods:(e)=>{let a={ALL:["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"],GET_HEAD:["GET","HEAD"],GET_HEAD_OPTIONS:["GET","HEAD","OPTIONS"]};return a[e]||a.GET_HEAD},cachedMethods:(e)=>{let a={GET_HEAD:["GET","HEAD"],GET_HEAD_OPTIONS:["GET","HEAD","OPTIONS"]};return a[e]||a.GET_HEAD},ttlPresets:{static:{min:0,max:31536000,default:31536000},dynamic:{min:0,max:0,default:0},api:{min:0,max:3600,default:60},html:{min:0,max:86400,default:86400},images:{min:0,max:604800,default:604800}},cacheBehavior:(e)=>{let{ttl:a={min:0,max:86400,default:86400},cookies:r="none",allowedCookies:n,allowedMethods:i="GET_HEAD",cachedMethods:o="GET_HEAD",compress:c=!0,forwardQueryString:u=!0,forwardHeaders:d=[]}=e;return{MinTTL:a.min,MaxTTL:a.max,DefaultTTL:a.default,Compress:c,AllowedMethods:Me.Config.allowedMethods(i),CachedMethods:Me.Config.cachedMethods(o),ForwardedValues:{QueryString:u,Headers:d,Cookies:Me.Config.cookies(r,n)}}}};static applyConfig(e,a){let r=e.Properties.DistributionConfig.DefaultCacheBehavior;if(a.ttl)r.MinTTL=a.ttl.min,r.MaxTTL=a.ttl.max,r.DefaultTTL=a.ttl.default;if(a.compress!==void 0)r.Compress=a.compress;if(a.allowedMethods)r.AllowedMethods=Me.Config.allowedMethods(a.allowedMethods);if(a.cachedMethods)r.CachedMethods=Me.Config.cachedMethods(a.cachedMethods);if(a.cookies){if(!r.ForwardedValues)r.ForwardedValues={QueryString:!0};r.ForwardedValues.Cookies=Me.Config.cookies(a.cookies,a.allowedCookies)}return e}}class Se{static createHostedZone(e){let{domain:a,slug:r,environment:n,comment:i}=e,o=l({slug:r,environment:n,resourceType:"hostedzone"}),c=s(`${o}-${a.replace(/\./g,"")}`);return{zone:{Type:"AWS::Route53::HostedZone",Properties:{Name:a,HostedZoneConfig:{Comment:i||`Hosted zone for ${a}`}}},logicalId:c}}static createRecord(e){let{hostedZoneId:a,hostedZoneName:r,name:n,type:i,ttl:o,values:c,aliasTarget:u}=e,d=s(`record-${n.replace(/\./g,"")}-${i}`),m={Type:"AWS::Route53::RecordSet",Properties:{Name:n,Type:i}};if(a)m.Properties.HostedZoneId=a;else if(r)m.Properties.HostedZoneName=r;if(u)m.Properties.AliasTarget={DNSName:u.dnsName,HostedZoneId:u.hostedZoneId,EvaluateTargetHealth:u.evaluateTargetHealth??!1};else m.Properties.TTL=o||300,m.Properties.ResourceRecords=c||[];return{record:m,logicalId:d}}static createCloudFrontAlias(e,a,r){return Se.createRecord({hostedZoneId:r,name:e,type:"A",aliasTarget:{dnsName:a,hostedZoneId:"Z2FDTNDATAQYW2",evaluateTargetHealth:!1}})}static createAlbAlias(e,a,r,n){return Se.createRecord({hostedZoneId:n,name:e,type:"A",aliasTarget:{dnsName:a,hostedZoneId:r,evaluateTargetHealth:!0}})}static createCname(e,a,r,n=300){return Se.createRecord({hostedZoneId:r,name:e,type:"CNAME",ttl:n,values:[a]})}static createWwwRedirect(e,a){return Se.createRecord({hostedZoneId:a,name:`www.${e}`,type:"CNAME",ttl:300,values:[e]})}static createMxRecords(e,a,r,n=300){return Se.createRecord({hostedZoneId:r,name:e,type:"MX",ttl:n,values:a.map((i)=>`${i.priority} ${i.server}`)})}static createTxtRecord(e,a,r,n=300){return Se.createRecord({hostedZoneId:r,name:e,type:"TXT",ttl:n,values:[`"${a}"`]})}static createSpfRecord(e,a,r){return Se.createTxtRecord(e,a,r)}static createDmarcRecord(e,a,r,n){let i=`v=DMARC1; p=${a}; rua=mailto:${r}`;return Se.createTxtRecord(`_dmarc.${e}`,i,n)}static createS3WebsiteAlias(e,a,r,n){return Se.createRecord({hostedZoneId:n,name:e,type:"A",aliasTarget:{dnsName:a,hostedZoneId:r,evaluateTargetHealth:!1}})}static S3WebsiteHostedZoneIds={"us-east-1":"Z3AQBSTGFYJSTF","us-east-2":"Z2O1EMRO9K5GLX","us-west-1":"Z2F56UZL2M1ACD","us-west-2":"Z3BJ6K6RIION7M","af-south-1":"Z83WF9RJE8B12","ap-east-1":"ZNB98KWMFR0R6","ap-south-1":"Z11RGJOFQNVJUP","ap-south-2":"Z02976202B4EZMXIPMXF7","ap-northeast-1":"Z2M4EHUR26P7ZW","ap-northeast-2":"Z3W03O7B5YMIYP","ap-northeast-3":"Z2YQB5RD63NC85","ap-southeast-1":"Z3O0J2DXBE1FTB","ap-southeast-2":"Z1WCIBER6CPFUU","ap-southeast-3":"Z01613992JD795ZI93075","ca-central-1":"Z1QDHH18159H29","eu-central-1":"Z21DNDUVLTQW6Q","eu-central-2":"Z030506016YDQGETNASS","eu-west-1":"Z1BKCTXD74EZPE","eu-west-2":"Z3GKZC51ZF0DB4","eu-west-3":"Z3R1K369G5AVDG","eu-north-1":"Z3BAZG2TWCNX0D","eu-south-1":"Z30OZKI7KPW7MI","eu-south-2":"Z0081959F7139GRJC19J","me-south-1":"Z1MPMWCPA7YB62","me-central-1":"Z06143092I8HRBER9VXCO","sa-east-1":"Z7KQH4QJS55SO"};static getS3WebsiteEndpoint(e,a){return`${e}.s3-website-${a}.amazonaws.com`}static createStoreRecord(e,a,r){return Se.createCname(`store.${e}`,a,r)}static createApiRecord(e,a,r){return Se.createCname(`api.${e}`,a,r)}static createDocsRecord(e,a,r){return Se.createCname(`docs.${e}`,a,r)}static CloudFrontHostedZoneId="Z2FDTNDATAQYW2"}class B{static createCertificate(e){let{domain:a,subdomains:r=[],slug:n,environment:i,validationMethod:o="DNS",hostedZoneId:c}=e,u=l({slug:n,environment:i,resourceType:"acm"}),d=s(`${u}-${a.replace(/\./g,"")}`),m=[a];for(let g of r)if(g==="*")m.push(`*.${a}`);else m.push(`${g}.${a}`);let p={Type:"AWS::CertificateManager::Certificate",Properties:{DomainName:a,SubjectAlternativeNames:m,ValidationMethod:o}};if(o==="DNS"&&c)p.Properties.DomainValidationOptions=m.map((g)=>({DomainName:g,HostedZoneId:c}));return{certificate:p,logicalId:d}}static createKmsKey(e){let{description:a,slug:r,environment:n,enableRotation:i=!0,multiRegion:o=!1}=e,c=l({slug:r,environment:n,resourceType:"kms"}),u=s(c),d={Version:"2012-10-17",Statement:[{Sid:"Enable IAM User Permissions",Effect:"Allow",Principal:{AWS:P.Sub("arn:aws:iam::${AWS::AccountId}:root")},Action:"kms:*",Resource:"*"},{Sid:"Allow services to use the key",Effect:"Allow",Principal:{Service:["s3.amazonaws.com","cloudfront.amazonaws.com","logs.amazonaws.com","secretsmanager.amazonaws.com"]},Action:["kms:Decrypt","kms:GenerateDataKey"],Resource:"*"}]},m={Type:"AWS::KMS::Key",Properties:{Description:a,Enabled:!0,EnableKeyRotation:i,KeyPolicy:d,KeySpec:"SYMMETRIC_DEFAULT",KeyUsage:"ENCRYPT_DECRYPT",MultiRegion:o}},p=s(`${c}-alias`),g={Type:"AWS::KMS::Alias",Properties:{AliasName:`alias/${r}-${n}`,TargetKeyId:P.Ref(u)}};return{key:m,alias:g,logicalId:u,aliasId:p}}static createFirewall(e){let{slug:a,environment:r,scope:n="CLOUDFRONT",defaultAction:i="allow"}=e,o=l({slug:a,environment:r,resourceType:"waf"}),c=s(o);return{webAcl:{Type:"AWS::WAFv2::WebACL",Properties:{Name:o,Scope:n,DefaultAction:i==="allow"?{Allow:{}}:{Block:{}},Description:`WAF for ${a} ${r}`,Rules:[],VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${o}-metric`}}},logicalId:c}}static setRateLimit(e,a){if(!e.Properties.Rules)e.Properties.Rules=[];return e.Properties.Rules.push({Name:a.name,Priority:a.priority,Statement:{RateBasedStatement:{Limit:a.requestsPerWindow,AggregateKeyType:a.aggregateKeyType||"IP"}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${a.name}-metric`}}),e}static blockCountries(e,a){if(!e.Properties.Rules)e.Properties.Rules=[];return e.Properties.Rules.push({Name:a.name,Priority:a.priority,Statement:{GeoMatchStatement:{CountryCodes:a.countryCodes}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${a.name}-metric`}}),e}static blockIpAddresses(e,a,r,n){let i=l({slug:r,environment:n,resourceType:"ipset"}),o=s(`${i}-${a.name}`),c={Type:"AWS::WAFv2::IPSet",Properties:{Name:`${i}-${a.name}`,Scope:e.Properties.Scope,IPAddressVersion:a.ipVersion||"IPV4",Addresses:a.ipAddresses,Description:`Blocked IPs for ${a.name}`}};if(!e.Properties.Rules)e.Properties.Rules=[];return e.Properties.Rules.push({Name:a.name,Priority:a.priority,Statement:{IPSetReferenceStatement:{Arn:P.GetAtt(o,"Arn")}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${a.name}-metric`}}),{webAcl:e,ipSet:c,ipSetLogicalId:o}}static addManagedRules(e,a){if(!e.Properties.Rules)e.Properties.Rules=[];let r={ManagedRuleGroupStatement:{VendorName:a.vendorName,Name:a.ruleName}};if(a.excludedRules&&a.excludedRules.length>0)r.ManagedRuleGroupStatement.ExcludedRules=a.excludedRules.map((n)=>({Name:n}));return e.Properties.Rules.push({Name:a.name,Priority:a.priority,Statement:r,VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${a.name}-metric`}}),e}static ManagedRuleGroups={CoreRuleSet:{vendorName:"AWS",ruleName:"AWSManagedRulesCommonRuleSet"},KnownBadInputs:{vendorName:"AWS",ruleName:"AWSManagedRulesKnownBadInputsRuleSet"},SqlDatabase:{vendorName:"AWS",ruleName:"AWSManagedRulesSQLiRuleSet"},LinuxOS:{vendorName:"AWS",ruleName:"AWSManagedRulesLinuxRuleSet"},PosixOS:{vendorName:"AWS",ruleName:"AWSManagedRulesUnixRuleSet"},AmazonIpReputation:{vendorName:"AWS",ruleName:"AWSManagedRulesAmazonIpReputationList"},AnonymousIpList:{vendorName:"AWS",ruleName:"AWSManagedRulesAnonymousIpList"},BotControl:{vendorName:"AWS",ruleName:"AWSManagedRulesBotControlRuleSet"}};static setPathRateLimit(e,a){if(!e.Properties.Rules)e.Properties.Rules=[];let r=a.paths.map((n)=>({SearchString:n,FieldToMatch:{UriPath:{}},TextTransformation:[{Priority:0,Type:"LOWERCASE"}],PositionalConstraint:"STARTS_WITH"}));return e.Properties.Rules.push({Name:a.name,Priority:a.priority,Statement:{RateBasedStatement:{Limit:a.requestsPerWindow,AggregateKeyType:a.aggregateKeyType||"IP",ScopeDownStatement:{OrStatement:{Statements:r.map((n)=>({ByteMatchStatement:n}))}}}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${a.name}-metric`}}),e}static setHeaderRateLimit(e,a){if(!e.Properties.Rules)e.Properties.Rules=[];let r={RateBasedStatement:{Limit:a.requestsPerWindow,AggregateKeyType:"CUSTOM_KEYS",CustomKeys:[{Header:{Name:a.headerName,TextTransformations:[{Priority:0,Type:"NONE"}]}}]}};if(a.headerValue)r.RateBasedStatement.ScopeDownStatement={ByteMatchStatement:{SearchString:a.headerValue,FieldToMatch:{SingleHeader:{Name:a.headerName}},TextTransformation:[{Priority:0,Type:"NONE"}],PositionalConstraint:"EXACTLY"}};return e.Properties.Rules.push({Name:a.name,Priority:a.priority,Statement:r,Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${a.name}-metric`}}),e}static protectLoginEndpoint(e,a){let{loginPaths:r,priority:n,requestsPerMinute:i=10}=a;return B.setPathRateLimit(e,{name:"LoginRateLimit",priority:n,requestsPerWindow:i*5,paths:r}),e}static protectApiEndpoints(e,a){let{apiPaths:r,priority:n,requestsPerMinute:i=100}=a;return B.setPathRateLimit(e,{name:"ApiRateLimit",priority:n,requestsPerWindow:i*5,paths:r}),e}static createProtectedFirewall(e){let{slug:a,environment:r,scope:n="CLOUDFRONT",enableBotControl:i=!1,enableRateLimiting:o=!0,rateLimitPerMinute:c=2000}=e,{webAcl:u,logicalId:d}=B.createFirewall({slug:a,environment:r,scope:n,defaultAction:"allow"}),m=0;if(u=B.addManagedRules(u,{name:"AWSIPReputationList",priority:m++,...B.ManagedRuleGroups.AmazonIpReputation}),u=B.addManagedRules(u,{name:"AWSAnonymousIPList",priority:m++,...B.ManagedRuleGroups.AnonymousIpList}),u=B.addManagedRules(u,{name:"AWSCoreRuleSet",priority:m++,...B.ManagedRuleGroups.CoreRuleSet}),u=B.addManagedRules(u,{name:"AWSKnownBadInputs",priority:m++,...B.ManagedRuleGroups.KnownBadInputs}),u=B.addManagedRules(u,{name:"AWSSQLi",priority:m++,...B.ManagedRuleGroups.SqlDatabase}),i)u=B.addManagedRules(u,{name:"AWSBotControl",priority:m++,...B.ManagedRuleGroups.BotControl});if(o)u=B.setRateLimit(u,{name:"GlobalRateLimit",priority:m++,requestsPerWindow:c*5});return{webAcl:u,logicalId:d}}static RateLimitPresets={STANDARD:2000,HIGH_TRAFFIC:1e4,STRICT:100,LOGIN:10,API:100}}class S{static createServer(e){let{slug:a,environment:r,instanceType:n="t3.micro",imageId:i="ami-0f3caa1cf4417e51b",keyName:o,securityGroupIds:c,subnetId:u,userData:d,volumeSize:m=20,volumeType:p="gp3",encrypted:g=!0}=e,h=l({slug:a,environment:r,resourceType:"ec2"}),y=s(h),f={Type:"AWS::EC2::Instance",Properties:{ImageId:i,InstanceType:n,Tags:[{Key:"Name",Value:h},{Key:"Environment",Value:r}]}};if(o)f.Properties.KeyName=o;if(c)f.Properties.SecurityGroupIds=c;if(u)f.Properties.SubnetId=u;if(d)f.Properties.UserData=P.Base64(d);return f.Properties.BlockDeviceMappings=[{DeviceName:"/dev/xvda",Ebs:{VolumeSize:m,VolumeType:p,Encrypted:g,DeleteOnTermination:!0}}],{instance:f,logicalId:y}}static createSecurityGroup(e){let{slug:a,environment:r,vpcId:n,description:i,ingress:o=[],egress:c=[]}=e,u=l({slug:a,environment:r,resourceType:"sg"}),d=s(u),m={Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:i||`Security group for ${a} ${r}`,Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:r}]}};if(n)m.Properties.VpcId=n;if(o.length>0)m.Properties.SecurityGroupIngress=o.map((p)=>({IpProtocol:p.protocol,FromPort:p.fromPort,ToPort:p.toPort,CidrIp:p.cidr,SourceSecurityGroupId:p.sourceSecurityGroupId}));if(c.length>0)m.Properties.SecurityGroupEgress=c.map((p)=>({IpProtocol:p.protocol,FromPort:p.fromPort,ToPort:p.toPort,CidrIp:p.cidr,DestinationSecurityGroupId:p.sourceSecurityGroupId}));return{securityGroup:m,logicalId:d}}static createWebServerSecurityGroup(e,a,r){return S.createSecurityGroup({slug:e,environment:a,vpcId:r,description:"Security group for web servers - HTTP, HTTPS, SSH",ingress:[{protocol:"tcp",fromPort:80,toPort:80,cidr:"0.0.0.0/0"},{protocol:"tcp",fromPort:443,toPort:443,cidr:"0.0.0.0/0"},{protocol:"tcp",fromPort:22,toPort:22,cidr:"0.0.0.0/0"}],egress:[{protocol:"-1",fromPort:0,toPort:0,cidr:"0.0.0.0/0"}]})}static createLoadBalancer(e){let{slug:a,environment:r,scheme:n="internet-facing",subnets:i,securityGroups:o,type:c="application"}=e,u=l({slug:a,environment:r,resourceType:"alb"}),d=s(u),m={Type:"AWS::ElasticLoadBalancingV2::LoadBalancer",Properties:{Name:u,Scheme:n,Type:c,Subnets:i,Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:r}]}};if(o)m.Properties.SecurityGroups=o;return{loadBalancer:m,logicalId:d}}static createTargetGroup(e){let{slug:a,environment:r,port:n,protocol:i="HTTP",vpcId:o,targetType:c="ip",healthCheckPath:u="/",healthCheckInterval:d=30,healthCheckTimeout:m=5,healthyThreshold:p=2,unhealthyThreshold:g=3}=e,h=l({slug:a,environment:r,resourceType:"tg"}),y=s(h);return{targetGroup:{Type:"AWS::ElasticLoadBalancingV2::TargetGroup",Properties:{Name:h,Port:n,Protocol:i,VpcId:o,TargetType:c,HealthCheckEnabled:!0,HealthCheckProtocol:i,HealthCheckPath:u,HealthCheckIntervalSeconds:d,HealthCheckTimeoutSeconds:m,HealthyThresholdCount:p,UnhealthyThresholdCount:g,Tags:[{Key:"Name",Value:h},{Key:"Environment",Value:r}]}},logicalId:y}}static createListener(e,a){let{port:r,protocol:n="HTTP",certificateArn:i,defaultTargetGroupArn:o}=a,c=s(`listener-${e}-${r}`),u={Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:P.Ref(e),Port:r,Protocol:n,DefaultActions:[{Type:"forward",TargetGroupArn:o}]}};if(n==="HTTPS"&&i)u.Properties.Certificates=[{CertificateArn:i}],u.Properties.SslPolicy="ELBSecurityPolicy-TLS13-1-2-2021-06";return{listener:u,logicalId:c}}static createEcsCluster(e,a){let r=l({slug:e,environment:a,resourceType:"ecs-cluster"}),n=s(r);return{cluster:{Type:"AWS::ECS::Cluster",Properties:{ClusterName:r,Tags:[{Key:"Name",Value:r},{Key:"Environment",Value:a}]}},logicalId:n}}static createFargateService(e){let{slug:a,environment:r,image:n,cpu:i="256",memory:o="512",desiredCount:c=1,containerPort:u=8080,environmentVariables:d={},secrets:m=[],healthCheck:p,logGroup:g,subnets:h,securityGroups:y,targetGroupArn:f}=e,{cluster:b,logicalId:v}=S.createEcsCluster(a,r),w=l({slug:a,environment:r,resourceType:"fargate"}),R=s(`${w}-execution-role`),T={Type:"AWS::IAM::Role",Properties:{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"]}},N=s(`${w}-task-role`),I={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ecs-tasks.amazonaws.com"},Action:"sts:AssumeRole"}]}}},k=s(`${w}-task`),x={Type:"AWS::ECS::TaskDefinition",Properties:{Family:w,TaskRoleArn:P.GetAtt(N,"Arn"),ExecutionRoleArn:P.GetAtt(R,"Arn"),NetworkMode:"awsvpc",RequiresCompatibilities:["FARGATE"],Cpu:i,Memory:o,ContainerDefinitions:[{Name:a,Image:n,Essential:!0,PortMappings:[{ContainerPort:u,Protocol:"tcp"}],Environment:Object.entries(d).map(([W,K])=>({Name:W,Value:K})),Secrets:m.map((W)=>({Name:W.name,ValueFrom:W.valueFrom}))}],Tags:[{Key:"Name",Value:w},{Key:"Environment",Value:r}]}};if(p)x.Properties.ContainerDefinitions[0].HealthCheck={Command:p.command,Interval:p.interval||30,Timeout:p.timeout||5,Retries:p.retries||3,StartPeriod:60};if(g)x.Properties.ContainerDefinitions[0].LogConfiguration={LogDriver:"awslogs",Options:{"awslogs-group":g,"awslogs-region":P.Ref("AWS::Region"),"awslogs-stream-prefix":a}};let L=s(`${w}-service`),O={Type:"AWS::ECS::Service",Properties:{ServiceName:w,Cluster:P.Ref(v),TaskDefinition:P.Ref(k),DesiredCount:c,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{Subnets:h,SecurityGroups:y,AssignPublicIp:"ENABLED"}},Tags:[{Key:"Name",Value:w},{Key:"Environment",Value:r}]}};if(f)O.Properties.LoadBalancers=[{TargetGroupArn:f,ContainerName:a,ContainerPort:u}];return{cluster:b,taskDefinition:x,service:O,taskRole:I,executionRole:T,clusterLogicalId:v,taskDefinitionLogicalId:k,serviceLogicalId:L,taskRoleLogicalId:N,executionRoleLogicalId:R}}static createLambdaFunction(e){let{slug:a,environment:r,runtime:n,handler:i,code:o,timeout:c=30,memorySize:u=128,environmentVariables:d={},vpcConfig:m}=e,p=l({slug:a,environment:r,resourceType:"lambda"}),g=s(p),h=s(`${p}-role`),y={Type:"AWS::IAM::Role",Properties:{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"]}};if(m)y.Properties.ManagedPolicyArns.push("arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole");let f={Type:"AWS::Lambda::Function",Properties:{FunctionName:p,Runtime:n,Role:P.GetAtt(h,"Arn"),Handler:i,Code:{...o.s3Bucket&&{S3Bucket:o.s3Bucket},...o.s3Key&&{S3Key:o.s3Key},...o.zipFile&&{ZipFile:o.zipFile}},Timeout:c,MemorySize:u,Tags:[{Key:"Name",Value:p},{Key:"Environment",Value:r}]}};if(Object.keys(d).length>0)f.Properties.Environment={Variables:d};if(m)f.Properties.VpcConfig={SecurityGroupIds:m.securityGroupIds,SubnetIds:m.subnetIds};return{lambdaFunction:f,role:y,logicalId:g,roleLogicalId:h}}static generateNodeServerUserData(e={}){let{nodeVersion:a="20",appRepo:r,environment:n={}}=e,i=Object.entries(n).map(([o,c])=>`echo "export ${o}='${c}'" >> /etc/environment`).join(`
|
|
212
|
+
`.trim()};static Config={ttl:(e)=>{let{min:a=0,max:r=86400,default:n=86400}=e;return{MinTTL:a,MaxTTL:r,DefaultTTL:n}},cookies:(e,a)=>{let r={Forward:e==="allowList"?"whitelist":e};if(e==="allowList"&&a)r.WhitelistedNames=a;return r},allowedMethods:(e)=>{let a={ALL:["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"],GET_HEAD:["GET","HEAD"],GET_HEAD_OPTIONS:["GET","HEAD","OPTIONS"]};return a[e]||a.GET_HEAD},cachedMethods:(e)=>{let a={GET_HEAD:["GET","HEAD"],GET_HEAD_OPTIONS:["GET","HEAD","OPTIONS"]};return a[e]||a.GET_HEAD},ttlPresets:{static:{min:0,max:31536000,default:31536000},dynamic:{min:0,max:0,default:0},api:{min:0,max:3600,default:60},html:{min:0,max:86400,default:86400},images:{min:0,max:604800,default:604800}},cacheBehavior:(e)=>{let{ttl:a={min:0,max:86400,default:86400},cookies:r="none",allowedCookies:n,allowedMethods:i="GET_HEAD",cachedMethods:o="GET_HEAD",compress:c=!0,forwardQueryString:u=!0,forwardHeaders:d=[]}=e;return{MinTTL:a.min,MaxTTL:a.max,DefaultTTL:a.default,Compress:c,AllowedMethods:Me.Config.allowedMethods(i),CachedMethods:Me.Config.cachedMethods(o),ForwardedValues:{QueryString:u,Headers:d,Cookies:Me.Config.cookies(r,n)}}}};static applyConfig(e,a){let r=e.Properties.DistributionConfig.DefaultCacheBehavior;if(a.ttl)r.MinTTL=a.ttl.min,r.MaxTTL=a.ttl.max,r.DefaultTTL=a.ttl.default;if(a.compress!==void 0)r.Compress=a.compress;if(a.allowedMethods)r.AllowedMethods=Me.Config.allowedMethods(a.allowedMethods);if(a.cachedMethods)r.CachedMethods=Me.Config.cachedMethods(a.cachedMethods);if(a.cookies){if(!r.ForwardedValues)r.ForwardedValues={QueryString:!0};r.ForwardedValues.Cookies=Me.Config.cookies(a.cookies,a.allowedCookies)}return e}}class Se{static createHostedZone(e){let{domain:a,slug:r,environment:n,comment:i}=e,o=l({slug:r,environment:n,resourceType:"hostedzone"}),c=s(`${o}-${a.replace(/\./g,"")}`);return{zone:{Type:"AWS::Route53::HostedZone",Properties:{Name:a,HostedZoneConfig:{Comment:i||`Hosted zone for ${a}`}}},logicalId:c}}static createRecord(e){let{hostedZoneId:a,hostedZoneName:r,name:n,type:i,ttl:o,values:c,aliasTarget:u}=e,d=s(`record-${n.replace(/\./g,"")}-${i}`),m={Type:"AWS::Route53::RecordSet",Properties:{Name:n,Type:i}};if(a)m.Properties.HostedZoneId=a;else if(r)m.Properties.HostedZoneName=r;if(u)m.Properties.AliasTarget={DNSName:u.dnsName,HostedZoneId:u.hostedZoneId,EvaluateTargetHealth:u.evaluateTargetHealth??!1};else m.Properties.TTL=o||300,m.Properties.ResourceRecords=c||[];return{record:m,logicalId:d}}static createCloudFrontAlias(e,a,r){return Se.createRecord({hostedZoneId:r,name:e,type:"A",aliasTarget:{dnsName:a,hostedZoneId:"Z2FDTNDATAQYW2",evaluateTargetHealth:!1}})}static createAlbAlias(e,a,r,n){return Se.createRecord({hostedZoneId:n,name:e,type:"A",aliasTarget:{dnsName:a,hostedZoneId:r,evaluateTargetHealth:!0}})}static createCname(e,a,r,n=300){return Se.createRecord({hostedZoneId:r,name:e,type:"CNAME",ttl:n,values:[a]})}static createWwwRedirect(e,a){return Se.createRecord({hostedZoneId:a,name:`www.${e}`,type:"CNAME",ttl:300,values:[e]})}static createMxRecords(e,a,r,n=300){return Se.createRecord({hostedZoneId:r,name:e,type:"MX",ttl:n,values:a.map((i)=>`${i.priority} ${i.server}`)})}static createTxtRecord(e,a,r,n=300){return Se.createRecord({hostedZoneId:r,name:e,type:"TXT",ttl:n,values:[`"${a}"`]})}static createSpfRecord(e,a,r){return Se.createTxtRecord(e,a,r)}static createDmarcRecord(e,a,r,n){let i=`v=DMARC1; p=${a}; rua=mailto:${r}`;return Se.createTxtRecord(`_dmarc.${e}`,i,n)}static createS3WebsiteAlias(e,a,r,n){return Se.createRecord({hostedZoneId:n,name:e,type:"A",aliasTarget:{dnsName:a,hostedZoneId:r,evaluateTargetHealth:!1}})}static S3WebsiteHostedZoneIds={"us-east-1":"Z3AQBSTGFYJSTF","us-east-2":"Z2O1EMRO9K5GLX","us-west-1":"Z2F56UZL2M1ACD","us-west-2":"Z3BJ6K6RIION7M","af-south-1":"Z83WF9RJE8B12","ap-east-1":"ZNB98KWMFR0R6","ap-south-1":"Z11RGJOFQNVJUP","ap-south-2":"Z02976202B4EZMXIPMXF7","ap-northeast-1":"Z2M4EHUR26P7ZW","ap-northeast-2":"Z3W03O7B5YMIYP","ap-northeast-3":"Z2YQB5RD63NC85","ap-southeast-1":"Z3O0J2DXBE1FTB","ap-southeast-2":"Z1WCIBER6CPFUU","ap-southeast-3":"Z01613992JD795ZI93075","ca-central-1":"Z1QDHH18159H29","eu-central-1":"Z21DNDUVLTQW6Q","eu-central-2":"Z030506016YDQGETNASS","eu-west-1":"Z1BKCTXD74EZPE","eu-west-2":"Z3GKZC51ZF0DB4","eu-west-3":"Z3R1K369G5AVDG","eu-north-1":"Z3BAZG2TWCNX0D","eu-south-1":"Z30OZKI7KPW7MI","eu-south-2":"Z0081959F7139GRJC19J","me-south-1":"Z1MPMWCPA7YB62","me-central-1":"Z06143092I8HRBER9VXCO","sa-east-1":"Z7KQH4QJS55SO"};static getS3WebsiteEndpoint(e,a){return`${e}.s3-website-${a}.amazonaws.com`}static createStoreRecord(e,a,r){return Se.createCname(`store.${e}`,a,r)}static createApiRecord(e,a,r){return Se.createCname(`api.${e}`,a,r)}static createDocsRecord(e,a,r){return Se.createCname(`docs.${e}`,a,r)}static CloudFrontHostedZoneId="Z2FDTNDATAQYW2"}class B{static createCertificate(e){let{domain:a,subdomains:r=[],slug:n,environment:i,validationMethod:o="DNS",hostedZoneId:c}=e,u=l({slug:n,environment:i,resourceType:"acm"}),d=s(`${u}-${a.replace(/\./g,"")}`),m=[a];for(let g of r)if(g==="*")m.push(`*.${a}`);else m.push(`${g}.${a}`);let p={Type:"AWS::CertificateManager::Certificate",Properties:{DomainName:a,SubjectAlternativeNames:m,ValidationMethod:o}};if(o==="DNS"&&c)p.Properties.DomainValidationOptions=m.map((g)=>({DomainName:g,HostedZoneId:c}));return{certificate:p,logicalId:d}}static createKmsKey(e){let{description:a,slug:r,environment:n,enableRotation:i=!0,multiRegion:o=!1}=e,c=l({slug:r,environment:n,resourceType:"kms"}),u=s(c),d={Version:"2012-10-17",Statement:[{Sid:"Enable IAM User Permissions",Effect:"Allow",Principal:{AWS:P.Sub("arn:aws:iam::${AWS::AccountId}:root")},Action:"kms:*",Resource:"*"},{Sid:"Allow services to use the key",Effect:"Allow",Principal:{Service:["s3.amazonaws.com","cloudfront.amazonaws.com","logs.amazonaws.com","secretsmanager.amazonaws.com"]},Action:["kms:Decrypt","kms:GenerateDataKey"],Resource:"*"}]},m={Type:"AWS::KMS::Key",Properties:{Description:a,Enabled:!0,EnableKeyRotation:i,KeyPolicy:d,KeySpec:"SYMMETRIC_DEFAULT",KeyUsage:"ENCRYPT_DECRYPT",MultiRegion:o}},p=s(`${c}-alias`),g={Type:"AWS::KMS::Alias",Properties:{AliasName:`alias/${r}-${n}`,TargetKeyId:P.Ref(u)}};return{key:m,alias:g,logicalId:u,aliasId:p}}static createFirewall(e){let{slug:a,environment:r,scope:n="CLOUDFRONT",defaultAction:i="allow"}=e,o=l({slug:a,environment:r,resourceType:"waf"}),c=s(o);return{webAcl:{Type:"AWS::WAFv2::WebACL",Properties:{Name:o,Scope:n,DefaultAction:i==="allow"?{Allow:{}}:{Block:{}},Description:`WAF for ${a} ${r}`,Rules:[],VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${o}-metric`}}},logicalId:c}}static setRateLimit(e,a){if(!e.Properties.Rules)e.Properties.Rules=[];return e.Properties.Rules.push({Name:a.name,Priority:a.priority,Statement:{RateBasedStatement:{Limit:a.requestsPerWindow,AggregateKeyType:a.aggregateKeyType||"IP"}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${a.name}-metric`}}),e}static blockCountries(e,a){if(!e.Properties.Rules)e.Properties.Rules=[];return e.Properties.Rules.push({Name:a.name,Priority:a.priority,Statement:{GeoMatchStatement:{CountryCodes:a.countryCodes}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${a.name}-metric`}}),e}static blockIpAddresses(e,a,r,n){let i=l({slug:r,environment:n,resourceType:"ipset"}),o=s(`${i}-${a.name}`),c={Type:"AWS::WAFv2::IPSet",Properties:{Name:`${i}-${a.name}`,Scope:e.Properties.Scope,IPAddressVersion:a.ipVersion||"IPV4",Addresses:a.ipAddresses,Description:`Blocked IPs for ${a.name}`}};if(!e.Properties.Rules)e.Properties.Rules=[];return e.Properties.Rules.push({Name:a.name,Priority:a.priority,Statement:{IPSetReferenceStatement:{Arn:P.GetAtt(o,"Arn")}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${a.name}-metric`}}),{webAcl:e,ipSet:c,ipSetLogicalId:o}}static addManagedRules(e,a){if(!e.Properties.Rules)e.Properties.Rules=[];let r={ManagedRuleGroupStatement:{VendorName:a.vendorName,Name:a.ruleName}};if(a.excludedRules&&a.excludedRules.length>0)r.ManagedRuleGroupStatement.ExcludedRules=a.excludedRules.map((n)=>({Name:n}));return e.Properties.Rules.push({Name:a.name,Priority:a.priority,Statement:r,VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${a.name}-metric`}}),e}static ManagedRuleGroups={CoreRuleSet:{vendorName:"AWS",ruleName:"AWSManagedRulesCommonRuleSet"},KnownBadInputs:{vendorName:"AWS",ruleName:"AWSManagedRulesKnownBadInputsRuleSet"},SqlDatabase:{vendorName:"AWS",ruleName:"AWSManagedRulesSQLiRuleSet"},LinuxOS:{vendorName:"AWS",ruleName:"AWSManagedRulesLinuxRuleSet"},PosixOS:{vendorName:"AWS",ruleName:"AWSManagedRulesUnixRuleSet"},AmazonIpReputation:{vendorName:"AWS",ruleName:"AWSManagedRulesAmazonIpReputationList"},AnonymousIpList:{vendorName:"AWS",ruleName:"AWSManagedRulesAnonymousIpList"},BotControl:{vendorName:"AWS",ruleName:"AWSManagedRulesBotControlRuleSet"}};static setPathRateLimit(e,a){if(!e.Properties.Rules)e.Properties.Rules=[];let r=a.paths.map((n)=>({SearchString:n,FieldToMatch:{UriPath:{}},TextTransformation:[{Priority:0,Type:"LOWERCASE"}],PositionalConstraint:"STARTS_WITH"}));return e.Properties.Rules.push({Name:a.name,Priority:a.priority,Statement:{RateBasedStatement:{Limit:a.requestsPerWindow,AggregateKeyType:a.aggregateKeyType||"IP",ScopeDownStatement:{OrStatement:{Statements:r.map((n)=>({ByteMatchStatement:n}))}}}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${a.name}-metric`}}),e}static setHeaderRateLimit(e,a){if(!e.Properties.Rules)e.Properties.Rules=[];let r={RateBasedStatement:{Limit:a.requestsPerWindow,AggregateKeyType:"CUSTOM_KEYS",CustomKeys:[{Header:{Name:a.headerName,TextTransformations:[{Priority:0,Type:"NONE"}]}}]}};if(a.headerValue)r.RateBasedStatement.ScopeDownStatement={ByteMatchStatement:{SearchString:a.headerValue,FieldToMatch:{SingleHeader:{Name:a.headerName}},TextTransformation:[{Priority:0,Type:"NONE"}],PositionalConstraint:"EXACTLY"}};return e.Properties.Rules.push({Name:a.name,Priority:a.priority,Statement:r,Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${a.name}-metric`}}),e}static protectLoginEndpoint(e,a){let{loginPaths:r,priority:n,requestsPerMinute:i=10}=a;return B.setPathRateLimit(e,{name:"LoginRateLimit",priority:n,requestsPerWindow:i*5,paths:r}),e}static protectApiEndpoints(e,a){let{apiPaths:r,priority:n,requestsPerMinute:i=100}=a;return B.setPathRateLimit(e,{name:"ApiRateLimit",priority:n,requestsPerWindow:i*5,paths:r}),e}static createProtectedFirewall(e){let{slug:a,environment:r,scope:n="CLOUDFRONT",enableBotControl:i=!1,enableRateLimiting:o=!0,rateLimitPerMinute:c=2000}=e,{webAcl:u,logicalId:d}=B.createFirewall({slug:a,environment:r,scope:n,defaultAction:"allow"}),m=0;if(u=B.addManagedRules(u,{name:"AWSIPReputationList",priority:m++,...B.ManagedRuleGroups.AmazonIpReputation}),u=B.addManagedRules(u,{name:"AWSAnonymousIPList",priority:m++,...B.ManagedRuleGroups.AnonymousIpList}),u=B.addManagedRules(u,{name:"AWSCoreRuleSet",priority:m++,...B.ManagedRuleGroups.CoreRuleSet}),u=B.addManagedRules(u,{name:"AWSKnownBadInputs",priority:m++,...B.ManagedRuleGroups.KnownBadInputs}),u=B.addManagedRules(u,{name:"AWSSQLi",priority:m++,...B.ManagedRuleGroups.SqlDatabase}),i)u=B.addManagedRules(u,{name:"AWSBotControl",priority:m++,...B.ManagedRuleGroups.BotControl});if(o)u=B.setRateLimit(u,{name:"GlobalRateLimit",priority:m++,requestsPerWindow:c*5});return{webAcl:u,logicalId:d}}static RateLimitPresets={STANDARD:2000,HIGH_TRAFFIC:1e4,STRICT:100,LOGIN:10,API:100}}class S{static createServer(e){let{slug:a,environment:r,instanceType:n="t3.micro",imageId:i="ami-0f3caa1cf4417e51b",keyName:o,securityGroupIds:c,subnetId:u,userData:d,volumeSize:m=20,volumeType:p="gp3",encrypted:g=!0}=e,h=l({slug:a,environment:r,resourceType:"ec2"}),y=s(h),f={Type:"AWS::EC2::Instance",Properties:{ImageId:i,InstanceType:n,Tags:[{Key:"Name",Value:h},{Key:"Environment",Value:r}]}};if(o)f.Properties.KeyName=o;if(c)f.Properties.SecurityGroupIds=c;if(u)f.Properties.SubnetId=u;if(d)f.Properties.UserData=P.Base64(d);return f.Properties.BlockDeviceMappings=[{DeviceName:"/dev/xvda",Ebs:{VolumeSize:m,VolumeType:p,Encrypted:g,DeleteOnTermination:!0}}],{instance:f,logicalId:y}}static createSecurityGroup(e){let{slug:a,environment:r,vpcId:n,description:i,ingress:o=[],egress:c=[]}=e,u=l({slug:a,environment:r,resourceType:"sg"}),d=s(u),m={Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:i||`Security group for ${a} ${r}`,Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:r}]}};if(n)m.Properties.VpcId=n;if(o.length>0)m.Properties.SecurityGroupIngress=o.map((p)=>({IpProtocol:p.protocol,FromPort:p.fromPort,ToPort:p.toPort,CidrIp:p.cidr,SourceSecurityGroupId:p.sourceSecurityGroupId}));if(c.length>0)m.Properties.SecurityGroupEgress=c.map((p)=>({IpProtocol:p.protocol,FromPort:p.fromPort,ToPort:p.toPort,CidrIp:p.cidr,DestinationSecurityGroupId:p.sourceSecurityGroupId}));return{securityGroup:m,logicalId:d}}static createWebServerSecurityGroup(e,a,r){return S.createSecurityGroup({slug:e,environment:a,vpcId:r,description:"Security group for web servers - HTTP, HTTPS, SSH",ingress:[{protocol:"tcp",fromPort:80,toPort:80,cidr:"0.0.0.0/0"},{protocol:"tcp",fromPort:443,toPort:443,cidr:"0.0.0.0/0"},{protocol:"tcp",fromPort:22,toPort:22,cidr:"0.0.0.0/0"}],egress:[{protocol:"-1",fromPort:0,toPort:0,cidr:"0.0.0.0/0"}]})}static createLoadBalancer(e){let{slug:a,environment:r,scheme:n="internet-facing",subnets:i,securityGroups:o,type:c="application"}=e,u=l({slug:a,environment:r,resourceType:"alb"}),d=s(u),m={Type:"AWS::ElasticLoadBalancingV2::LoadBalancer",Properties:{Name:u,Scheme:n,Type:c,Subnets:i,Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:r}]}};if(o)m.Properties.SecurityGroups=o;return{loadBalancer:m,logicalId:d}}static createTargetGroup(e){let{slug:a,environment:r,port:n,protocol:i="HTTP",vpcId:o,targetType:c="ip",healthCheckPath:u="/",healthCheckInterval:d=30,healthCheckTimeout:m=5,healthyThreshold:p=2,unhealthyThreshold:g=3}=e,h=l({slug:a,environment:r,resourceType:"tg"}),y=s(h);return{targetGroup:{Type:"AWS::ElasticLoadBalancingV2::TargetGroup",Properties:{Name:h,Port:n,Protocol:i,VpcId:o,TargetType:c,HealthCheckEnabled:!0,HealthCheckProtocol:i,HealthCheckPath:u,HealthCheckIntervalSeconds:d,HealthCheckTimeoutSeconds:m,HealthyThresholdCount:p,UnhealthyThresholdCount:g,Tags:[{Key:"Name",Value:h},{Key:"Environment",Value:r}]}},logicalId:y}}static createListener(e,a){let{port:r,protocol:n="HTTP",certificateArn:i,defaultTargetGroupArn:o}=a,c=s(`listener-${e}-${r}`),u={Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:P.Ref(e),Port:r,Protocol:n,DefaultActions:[{Type:"forward",TargetGroupArn:o}]}};if(n==="HTTPS"&&i)u.Properties.Certificates=[{CertificateArn:i}],u.Properties.SslPolicy="ELBSecurityPolicy-TLS13-1-2-2021-06";return{listener:u,logicalId:c}}static createEcsCluster(e,a){let r=l({slug:e,environment:a,resourceType:"ecs-cluster"}),n=s(r);return{cluster:{Type:"AWS::ECS::Cluster",Properties:{ClusterName:r,Tags:[{Key:"Name",Value:r},{Key:"Environment",Value:a}]}},logicalId:n}}static createFargateService(e){let{slug:a,environment:r,image:n,cpu:i="256",memory:o="512",desiredCount:c=1,containerPort:u=8080,environmentVariables:d={},secrets:m=[],healthCheck:p,logGroup:g,subnets:h,securityGroups:y,targetGroupArn:f}=e,{cluster:b,logicalId:v}=S.createEcsCluster(a,r),w=l({slug:a,environment:r,resourceType:"fargate"}),R=s(`${w}-execution-role`),T={Type:"AWS::IAM::Role",Properties:{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"]}},N=s(`${w}-task-role`),I={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ecs-tasks.amazonaws.com"},Action:"sts:AssumeRole"}]}}},k=s(`${w}-task`),O={Type:"AWS::ECS::TaskDefinition",Properties:{Family:w,TaskRoleArn:P.GetAtt(N,"Arn"),ExecutionRoleArn:P.GetAtt(R,"Arn"),NetworkMode:"awsvpc",RequiresCompatibilities:["FARGATE"],Cpu:i,Memory:o,ContainerDefinitions:[{Name:a,Image:n,Essential:!0,PortMappings:[{ContainerPort:u,Protocol:"tcp"}],Environment:Object.entries(d).map(([W,K])=>({Name:W,Value:K})),Secrets:m.map((W)=>({Name:W.name,ValueFrom:W.valueFrom}))}],Tags:[{Key:"Name",Value:w},{Key:"Environment",Value:r}]}};if(p)O.Properties.ContainerDefinitions[0].HealthCheck={Command:p.command,Interval:p.interval||30,Timeout:p.timeout||5,Retries:p.retries||3,StartPeriod:60};if(g)O.Properties.ContainerDefinitions[0].LogConfiguration={LogDriver:"awslogs",Options:{"awslogs-group":g,"awslogs-region":P.Ref("AWS::Region"),"awslogs-stream-prefix":a}};let L=s(`${w}-service`),_={Type:"AWS::ECS::Service",Properties:{ServiceName:w,Cluster:P.Ref(v),TaskDefinition:P.Ref(k),DesiredCount:c,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{Subnets:h,SecurityGroups:y,AssignPublicIp:"ENABLED"}},Tags:[{Key:"Name",Value:w},{Key:"Environment",Value:r}]}};if(f)_.Properties.LoadBalancers=[{TargetGroupArn:f,ContainerName:a,ContainerPort:u}];return{cluster:b,taskDefinition:O,service:_,taskRole:I,executionRole:T,clusterLogicalId:v,taskDefinitionLogicalId:k,serviceLogicalId:L,taskRoleLogicalId:N,executionRoleLogicalId:R}}static createLambdaFunction(e){let{slug:a,environment:r,runtime:n,handler:i,code:o,timeout:c=30,memorySize:u=128,environmentVariables:d={},vpcConfig:m}=e,p=l({slug:a,environment:r,resourceType:"lambda"}),g=s(p),h=s(`${p}-role`),y={Type:"AWS::IAM::Role",Properties:{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"]}};if(m)y.Properties.ManagedPolicyArns.push("arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole");let f={Type:"AWS::Lambda::Function",Properties:{FunctionName:p,Runtime:n,Role:P.GetAtt(h,"Arn"),Handler:i,Code:{...o.s3Bucket&&{S3Bucket:o.s3Bucket},...o.s3Key&&{S3Key:o.s3Key},...o.zipFile&&{ZipFile:o.zipFile}},Timeout:c,MemorySize:u,Tags:[{Key:"Name",Value:p},{Key:"Environment",Value:r}]}};if(Object.keys(d).length>0)f.Properties.Environment={Variables:d};if(m)f.Properties.VpcConfig={SecurityGroupIds:m.securityGroupIds,SubnetIds:m.subnetIds};return{lambdaFunction:f,role:y,logicalId:g,roleLogicalId:h}}static generateNodeServerUserData(e={}){let{nodeVersion:a="20",appRepo:r,environment:n={}}=e,i=Object.entries(n).map(([o,c])=>`echo "export ${o}='${c}'" >> /etc/environment`).join(`
|
|
213
213
|
`);return`#!/bin/bash
|
|
214
214
|
# Update system
|
|
215
215
|
yum update -y
|
|
@@ -604,7 +604,7 @@ ufw default allow outgoing
|
|
|
604
604
|
${e.map((a)=>`ufw allow ${a}`).join(`
|
|
605
605
|
`)}
|
|
606
606
|
ufw --force enable
|
|
607
|
-
`},Presets:{bunWithNginx:(e,a=3000)=>S.UserData.generateAppServerScript({runtime:"bun",webServer:"nginx",processManager:"systemd",domain:e,appPort:a,enableSsl:!0}),bunWithCaddy:(e,a=3000)=>S.UserData.generateAppServerScript({runtime:"bun",webServer:"caddy",processManager:"systemd",domain:e,appPort:a,enableSsl:!1}),nodeWithPm2:(e,a=3000)=>S.UserData.generateAppServerScript({runtime:"node",webServer:"nginx",processManager:"pm2",domain:e,appPort:a,enableSsl:!0}),worker:(e="bun")=>S.UserData.generateAppServerScript({runtime:e,webServer:"none",processManager:"systemd",enableSsl:!1})}};static createElasticIp(e){let{slug:a,environment:r,domain:n,instanceLogicalId:i}=e,o=l({slug:a,environment:r,resourceType:"eip"}),c=s(o),u={Type:"AWS::EC2::EIP",Properties:{Domain:"vpc",Tags:[{Key:"Name",Value:o},{Key:"Environment",Value:r},...n?[{Key:"Domain",Value:n}]:[]]}},d={[c]:u},m,p;if(i)p=s(`${o}-assoc`),m={Type:"AWS::EC2::EIPAssociation",Properties:{AllocationId:P.GetAtt(c,"AllocationId"),InstanceId:P.Ref(i)}},d[p]=m;return{eip:u,eipAssociation:m,eipLogicalId:c,associationLogicalId:p,resources:d}}static createServerModeStack(e){let{slug:a,environment:r,vpcId:n,subnetId:i,instanceType:o="t3.small",imageId:c="ami-0f3caa1cf4417e51b",keyName:u,domain:d,userData:m,allowedPorts:p=[22,80,443],volumeSize:g=20,volumeType:h="gp3"}=e,y={},f=l({slug:a,environment:r,resourceType:"server-sg"}),b=s(f),v={Type:"AWS::EC2::SecurityGroup",Properties:{GroupName:f,GroupDescription:`Security group for ${a} server`,VpcId:n,SecurityGroupIngress:p.map((q)=>({IpProtocol:"tcp",FromPort:q,ToPort:q,CidrIp:"0.0.0.0/0",Description:`Port ${q}`})),SecurityGroupEgress:[{IpProtocol:"-1",CidrIp:"0.0.0.0/0",Description:"Allow all outbound"}],Tags:[{Key:"Name",Value:f},{Key:"Environment",Value:r}]}};y[b]=v;let w=l({slug:a,environment:r,resourceType:"server-role"}),R=s(w),T={Type:"AWS::IAM::Role",Properties:{RoleName:w,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ec2.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore","arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy"],Policies:[{PolicyName:"StacksServerPermissions",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["ses:SendEmail","ses:SendRawEmail","ses:SendBulkEmail","ses:VerifyDomainIdentity","ses:VerifyDomainDkim","ses:GetIdentityDkimAttributes","ses:GetIdentityVerificationAttributes"],Resource:"*"},{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:ListBucket"],Resource:"*"},{Effect:"Allow",Action:["route53:ChangeResourceRecordSets","route53:ListResourceRecordSets","route53:GetHostedZone"],Resource:"*"},{Effect:"Allow",Action:["ssm:GetParameter","ssm:GetParameters"],Resource:"*"}]}}]}};y[R]=T;let N=l({slug:a,environment:r,resourceType:"server-profile"}),I=s(N),k={Type:"AWS::IAM::InstanceProfile",Properties:{InstanceProfileName:N,Roles:[P.Ref(R)]}};y[I]=k;let
|
|
607
|
+
`},Presets:{bunWithNginx:(e,a=3000)=>S.UserData.generateAppServerScript({runtime:"bun",webServer:"nginx",processManager:"systemd",domain:e,appPort:a,enableSsl:!0}),bunWithCaddy:(e,a=3000)=>S.UserData.generateAppServerScript({runtime:"bun",webServer:"caddy",processManager:"systemd",domain:e,appPort:a,enableSsl:!1}),nodeWithPm2:(e,a=3000)=>S.UserData.generateAppServerScript({runtime:"node",webServer:"nginx",processManager:"pm2",domain:e,appPort:a,enableSsl:!0}),worker:(e="bun")=>S.UserData.generateAppServerScript({runtime:e,webServer:"none",processManager:"systemd",enableSsl:!1})}};static createElasticIp(e){let{slug:a,environment:r,domain:n,instanceLogicalId:i}=e,o=l({slug:a,environment:r,resourceType:"eip"}),c=s(o),u={Type:"AWS::EC2::EIP",Properties:{Domain:"vpc",Tags:[{Key:"Name",Value:o},{Key:"Environment",Value:r},...n?[{Key:"Domain",Value:n}]:[]]}},d={[c]:u},m,p;if(i)p=s(`${o}-assoc`),m={Type:"AWS::EC2::EIPAssociation",Properties:{AllocationId:P.GetAtt(c,"AllocationId"),InstanceId:P.Ref(i)}},d[p]=m;return{eip:u,eipAssociation:m,eipLogicalId:c,associationLogicalId:p,resources:d}}static createServerModeStack(e){let{slug:a,environment:r,vpcId:n,subnetId:i,instanceType:o="t3.small",imageId:c="ami-0f3caa1cf4417e51b",keyName:u,domain:d,userData:m,allowedPorts:p=[22,80,443],volumeSize:g=20,volumeType:h="gp3"}=e,y={},f=l({slug:a,environment:r,resourceType:"server-sg"}),b=s(f),v={Type:"AWS::EC2::SecurityGroup",Properties:{GroupName:f,GroupDescription:`Security group for ${a} server`,VpcId:n,SecurityGroupIngress:p.map((q)=>({IpProtocol:"tcp",FromPort:q,ToPort:q,CidrIp:"0.0.0.0/0",Description:`Port ${q}`})),SecurityGroupEgress:[{IpProtocol:"-1",CidrIp:"0.0.0.0/0",Description:"Allow all outbound"}],Tags:[{Key:"Name",Value:f},{Key:"Environment",Value:r}]}};y[b]=v;let w=l({slug:a,environment:r,resourceType:"server-role"}),R=s(w),T={Type:"AWS::IAM::Role",Properties:{RoleName:w,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ec2.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore","arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy"],Policies:[{PolicyName:"StacksServerPermissions",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["ses:SendEmail","ses:SendRawEmail","ses:SendBulkEmail","ses:VerifyDomainIdentity","ses:VerifyDomainDkim","ses:GetIdentityDkimAttributes","ses:GetIdentityVerificationAttributes"],Resource:"*"},{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:ListBucket"],Resource:"*"},{Effect:"Allow",Action:["route53:ChangeResourceRecordSets","route53:ListResourceRecordSets","route53:GetHostedZone"],Resource:"*"},{Effect:"Allow",Action:["ssm:GetParameter","ssm:GetParameters"],Resource:"*"}]}}]}};y[R]=T;let N=l({slug:a,environment:r,resourceType:"server-profile"}),I=s(N),k={Type:"AWS::IAM::InstanceProfile",Properties:{InstanceProfileName:N,Roles:[P.Ref(R)]}};y[I]=k;let O=l({slug:a,environment:r,resourceType:"server"}),L=s(O),_={Type:"AWS::EC2::Instance",DependsOn:[I],Properties:{ImageId:c,InstanceType:o,KeyName:u,SubnetId:i,SecurityGroupIds:[P.Ref(b)],IamInstanceProfile:P.Ref(I),BlockDeviceMappings:[{DeviceName:"/dev/xvda",Ebs:{VolumeSize:g,VolumeType:h,Encrypted:!0,DeleteOnTermination:!0}}],Tags:[{Key:"Name",Value:O},{Key:"Environment",Value:r},...d?[{Key:"Domain",Value:d}]:[]]}};if(m)_.Properties.UserData=P.Base64(m);y[L]=_;let{eip:W,eipAssociation:K,eipLogicalId:Z,associationLogicalId:z,resources:J}=S.createElasticIp({slug:a,environment:r,domain:d,instanceLogicalId:L});return Object.assign(y,J),{instance:_,securityGroup:v,eip:W,eipAssociation:K,instanceRole:T,instanceProfile:k,resources:y,outputs:{instanceLogicalId:L,securityGroupLogicalId:b,eipLogicalId:Z,associationLogicalId:z,roleLogicalId:R,profileLogicalId:I}}}static ServerMode={webServer:(e)=>{let a=S.UserData.generateAppServerScript({runtime:e.runtime||"bun",webServer:e.webServer||"nginx",domain:e.domain,enableSsl:!0});return S.createServerModeStack({...e,userData:a,instanceType:"t3.small",allowedPorts:[22,80,443]})},workerServer:(e)=>{let a=S.UserData.generateAppServerScript({runtime:e.runtime||"bun",webServer:"none",installRedis:e.installRedis});return S.createServerModeStack({...e,userData:a,instanceType:"t3.medium",allowedPorts:[22]})},cacheServer:(e)=>S.createServerModeStack({...e,userData:`#!/bin/bash
|
|
608
608
|
set -e
|
|
609
609
|
apt-get update && apt-get upgrade -y
|
|
610
610
|
apt-get install -y redis-server
|
|
@@ -612,7 +612,7 @@ sed -i 's/bind 127.0.0.1/bind 0.0.0.0/' /etc/redis/redis.conf
|
|
|
612
612
|
systemctl enable redis-server
|
|
613
613
|
systemctl restart redis-server
|
|
614
614
|
echo "Redis server setup complete!"
|
|
615
|
-
`,instanceType:"t3.medium",allowedPorts:[22,6379]})}}class
|
|
615
|
+
`,instanceType:"t3.medium",allowedPorts:[22,6379]})}}class x{static createVpc(e){let{slug:a,environment:r,cidr:n="10.0.0.0/16",enableDnsHostnames:i=!0,enableDnsSupport:o=!0}=e,c=l({slug:a,environment:r,resourceType:"vpc"}),u=s(c);return{vpc:{Type:"AWS::EC2::VPC",Properties:{CidrBlock:n,EnableDnsHostnames:i,EnableDnsSupport:o,Tags:[{Key:"Name",Value:c},{Key:"Environment",Value:r}]}},logicalId:u}}static createSubnet(e){let{slug:a,environment:r,vpcId:n,type:i,cidr:o,availabilityZone:c,mapPublicIp:u=i==="public"}=e,d=l({slug:a,environment:r,resourceType:`subnet-${i}`}),m=s(`${d}-${c}`);return{subnet:{Type:"AWS::EC2::Subnet",Properties:{VpcId:n,CidrBlock:o,AvailabilityZone:c,MapPublicIpOnLaunch:u,Tags:[{Key:"Name",Value:`${d}-${c}`},{Key:"Environment",Value:r},{Key:"Type",Value:i}]}},logicalId:m}}static createInternetGateway(e,a){let r=l({slug:e,environment:a,resourceType:"igw"}),n=s(r);return{internetGateway:{Type:"AWS::EC2::InternetGateway",Properties:{Tags:[{Key:"Name",Value:r},{Key:"Environment",Value:a}]}},logicalId:n}}static attachInternetGateway(e,a){let r=s(`${e}-igw-attachment`);return{attachment:{Type:"AWS::EC2::VPCGatewayAttachment",Properties:{VpcId:P.Ref(e),InternetGatewayId:P.Ref(a)}},logicalId:r}}static createEip(e,a){let r=l({slug:e,environment:a,resourceType:"eip"}),n=s(r);return{eip:{Type:"AWS::EC2::EIP",Properties:{Domain:"vpc",Tags:[{Key:"Name",Value:r},{Key:"Environment",Value:a}]}},logicalId:n}}static createNatGateway(e,a){let{slug:r,environment:n,subnetId:i}=e,o=l({slug:r,environment:n,resourceType:"nat"}),c=s(o);return{natGateway:{Type:"AWS::EC2::NatGateway",Properties:{AllocationId:P.GetAtt(a,"AllocationId"),SubnetId:i,Tags:[{Key:"Name",Value:o},{Key:"Environment",Value:n},{Key:"Warning",Value:"NAT Gateway incurs hourly charges"}]}},logicalId:c}}static createRouteTable(e,a,r,n){let i=l({slug:e,environment:a,resourceType:`rt-${n}`}),o=s(i);return{routeTable:{Type:"AWS::EC2::RouteTable",Properties:{VpcId:P.Ref(r),Tags:[{Key:"Name",Value:i},{Key:"Environment",Value:a},{Key:"Type",Value:n}]}},logicalId:o}}static createRoute(e,a,r){let n=s(`${e}-route-${r.type}`),i={Type:"AWS::EC2::Route",Properties:{RouteTableId:P.Ref(e),DestinationCidrBlock:a}};if(r.type==="igw")i.Properties.GatewayId=P.Ref(r.logicalId);else if(r.type==="nat")i.Properties.NatGatewayId=P.Ref(r.logicalId);else if(r.type==="instance")i.Properties.InstanceId=P.Ref(r.logicalId);return{route:i,logicalId:n}}static associateSubnetWithRouteTable(e,a){let r=s(`${e}-rt-assoc`);return{association:{Type:"AWS::EC2::SubnetRouteTableAssociation",Properties:{SubnetId:P.Ref(e),RouteTableId:P.Ref(a)}},logicalId:r}}static enableFlowLogs(e){let{slug:a,environment:r,resourceId:n,resourceType:i,trafficType:o="ALL",logGroupName:c}=e,u=l({slug:a,environment:r,resourceType:"flowlog"}),d=s(u);return{flowLog:{Type:"AWS::EC2::FlowLog",Properties:{ResourceType:i,ResourceIds:[n],TrafficType:o,LogDestinationType:"cloud-watch-logs",LogGroupName:c||`/aws/vpc/${a}-${r}`,Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:r}]}},logicalId:d}}static calculateSubnetCidrs(e,a,r=3){let[n,i]=e.split("/"),o=Number.parseInt(i,10),c=Math.ceil(Math.log2(a*r)),u=o+c;if(u>28)throw Error("VPC CIDR is too small to accommodate requested subnets");let[d,m,p,g]=n.split(".").map(Number),h=(d<<24)+(m<<16)+(p<<8)+g,y=2**(32-u),f=[];for(let b=0;b<a*r;b++){let v=h+b*y,w=[v>>>24&255,v>>>16&255,v>>>8&255,v&255].join(".");f.push(`${w}/${u}`)}return f}static getAvailabilityZones(e,a){return["a","b","c","d","e","f"].slice(0,a).map((r)=>`${e}${r}`)}static createMultiAzNetwork(e){let{slug:a,environment:r,region:n,cidr:i="10.0.0.0/16",zones:o=3,enableNatGateway:c=!1,singleNatGateway:u=!1,enableFlowLogs:d=!1}=e,m={},p=[],g=[],h=[],{vpc:y,logicalId:f}=x.createVpc({slug:a,environment:r,cidr:i});m[f]=y;let{internetGateway:b,logicalId:v}=x.createInternetGateway(a,r);m[v]=b;let{attachment:w,logicalId:R}=x.attachInternetGateway(f,v);m[R]=w;let{routeTable:T,logicalId:N}=x.createRouteTable(a,r,f,"public");m[N]=T;let{route:I,logicalId:k}=x.createRoute(N,"0.0.0.0/0",{type:"igw",logicalId:v});I.DependsOn=R,m[k]=I;let O=x.calculateSubnetCidrs(i,o,2),L=x.getAvailabilityZones(n,o),_=[];for(let W=0;W<o;W++){let K=L[W],Z=O[W*2],z=O[W*2+1],{subnet:J,logicalId:q}=x.createSubnet({slug:a,environment:r,vpcId:P.Ref(f),type:"public",cidr:Z,availabilityZone:K});m[q]=J,p.push(q);let{association:de,logicalId:Oe}=x.associateSubnetWithRouteTable(q,N);m[Oe]=de;let{subnet:ft,logicalId:X}=x.createSubnet({slug:a,environment:r,vpcId:P.Ref(f),type:"private",cidr:z,availabilityZone:K});if(m[X]=ft,g.push(X),c&&(!u||W===0)){let{eip:Y,logicalId:te}=x.createEip(`${a}-${K}`,r);m[te]=Y;let{natGateway:me,logicalId:ae}=x.createNatGateway({slug:`${a}-${K}`,environment:r,subnetId:P.Ref(q)},te);me.DependsOn=R,m[ae]=me,h.push(ae);let{routeTable:ie,logicalId:fe}=x.createRouteTable(`${a}-${K}`,r,f,"private");m[fe]=ie,_.push(fe);let{route:Be,logicalId:M}=x.createRoute(fe,"0.0.0.0/0",{type:"nat",logicalId:ae});m[M]=Be;let{association:j,logicalId:F}=x.associateSubnetWithRouteTable(X,fe);m[F]=j}else if(c&&u&&W>0){let{association:Y,logicalId:te}=x.associateSubnetWithRouteTable(X,_[0]);m[te]=Y}else{let{routeTable:Y,logicalId:te}=x.createRouteTable(`${a}-${K}-isolated`,r,f,"private");m[te]=Y;let{association:me,logicalId:ae}=x.associateSubnetWithRouteTable(X,te);m[ae]=me}}if(d){let{flowLog:W,logicalId:K}=x.enableFlowLogs({slug:a,environment:r,resourceId:P.Ref(f),resourceType:"VPC"});m[K]=W}return{resources:m,outputs:{vpcId:f,publicSubnetIds:p,privateSubnetIds:g,natGatewayIds:h.length>0?h:void 0}}}static NatGatewayCostWarning=`
|
|
616
616
|
⚠️ NAT Gateway Cost Warning:
|
|
617
617
|
- Each NAT Gateway costs approximately $32-45/month (hourly charges)
|
|
618
618
|
- Data processing charges: $0.045/GB processed
|
|
@@ -2306,14 +2306,14 @@ function resolveTemplate(template, data) {
|
|
|
2306
2306
|
}
|
|
2307
2307
|
return result;
|
|
2308
2308
|
}
|
|
2309
|
-
`;class be{static LambdaCode={send:La,receive:Lr,deliveryStatus:$r};static createPinpointApp(e){return{[`${e.slug}PinpointApp`]:{Type:"AWS::Pinpoint::App",Properties:{Name:e.name||`${e.slug}-sms`}}}}static createSmsChannel(e){let a={ApplicationId:e.applicationId,Enabled:e.enabled!==!1};if(e.senderId)a.SenderId=e.senderId;if(e.shortCode)a.ShortCode=e.shortCode;return{[`${e.slug}SmsChannel`]:{Type:"AWS::Pinpoint::SMSChannel",Properties:a}}}static createSmsLambdaRole(e){return{[`${e.slug}SmsLambdaRole`]:{Type:"AWS::IAM::Role",Properties:{RoleName:`${e.slug}-sms-lambda-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:"SmsLambdaPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["mobiletargeting:SendMessages","mobiletargeting:GetSmsChannel"],Resource:"*"},{Effect:"Allow",Action:["sns:Publish"],Resource:"*"},{Effect:"Allow",Action:["dynamodb:PutItem","dynamodb:UpdateItem","dynamodb:GetItem","dynamodb:DeleteItem"],Resource:"*"}]}}]}}}}static createSendLambda(e){return{[`${e.slug}SmsSendLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${e.slug}-sms-send`,Runtime:"nodejs20.x",Handler:"index.handler",Role:e.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:be.LambdaCode.send},Environment:{Variables:{PINPOINT_APP_ID:e.pinpointAppId,MESSAGE_LOG_TABLE:e.messageLogTable||"",SMS_SENDER_ID:e.senderId||"",SMS_ORIGINATION_NUMBER:e.originationNumber||""}}}}}}static createReceiveLambda(e){return{[`${e.slug}SmsReceiveLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${e.slug}-sms-receive`,Runtime:"nodejs20.x",Handler:"index.handler",Role:e.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:be.LambdaCode.receive},Environment:{Variables:{OPT_OUT_TABLE:e.optOutTable||"",MESSAGE_LOG_TABLE:e.messageLogTable||"",NOTIFICATION_TOPIC_ARN:e.notificationTopicArn||"",WEBHOOK_URL:e.webhookUrl||""}}}}}}static createDeliveryStatusLambda(e){return{[`${e.slug}SmsDeliveryStatusLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${e.slug}-sms-delivery-status`,Runtime:"nodejs20.x",Handler:"index.handler",Role:e.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:be.LambdaCode.deliveryStatus},Environment:{Variables:{MESSAGE_LOG_TABLE:e.messageLogTable||"",NOTIFICATION_TOPIC_ARN:e.notificationTopicArn||"",WEBHOOK_URL:e.webhookUrl||""}}}}}}static createMessageLogTable(e){return{[`${e.slug}SmsMessageLogTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${e.slug}-sms-messages`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"messageId",AttributeType:"S"}],KeySchema:[{AttributeName:"messageId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createOptOutTable(e){return{[`${e.slug}SmsOptOutTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${e.slug}-sms-optouts`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"phoneNumber",AttributeType:"S"}],KeySchema:[{AttributeName:"phoneNumber",KeyType:"HASH"}]}}}}static createNotificationTopic(e){return{[`${e.slug}SmsNotificationTopic`]:{Type:"AWS::SNS::Topic",Properties:{TopicName:`${e.slug}-sms-notifications`}}}}static createCompleteSetup(e){let a={},r={};Object.assign(a,be.createPinpointApp({slug:e.slug})),Object.assign(a,be.createSmsChannel({slug:e.slug,applicationId:{Ref:`${e.slug}PinpointApp`},senderId:e.senderId})),Object.assign(a,be.createSmsLambdaRole({slug:e.slug})),Object.assign(a,be.createMessageLogTable({slug:e.slug})),Object.assign(a,be.createOptOutTable({slug:e.slug})),Object.assign(a,be.createNotificationTopic({slug:e.slug}));let n={"Fn::GetAtt":[`${e.slug}SmsLambdaRole`,"Arn"]},i={Ref:`${e.slug}PinpointApp`},o={Ref:`${e.slug}SmsMessageLogTable`},c={Ref:`${e.slug}SmsOptOutTable`},u={Ref:`${e.slug}SmsNotificationTopic`};if(Object.assign(a,be.createSendLambda({slug:e.slug,roleArn:n,pinpointAppId:i,messageLogTable:o,senderId:e.senderId,originationNumber:e.originationNumber})),e.twoWayEnabled)Object.assign(a,be.createReceiveLambda({slug:e.slug,roleArn:n,optOutTable:c,messageLogTable:o,notificationTopicArn:u,webhookUrl:e.webhookUrl}));return Object.assign(a,be.createDeliveryStatusLambda({slug:e.slug,roleArn:n,messageLogTable:o,notificationTopicArn:u,webhookUrl:e.webhookUrl})),r[`${e.slug}PinpointAppId`]={Description:"Pinpoint application ID",Value:{Ref:`${e.slug}PinpointApp`}},r[`${e.slug}SmsSendLambdaArn`]={Description:"SMS send Lambda ARN",Value:{"Fn::GetAtt":[`${e.slug}SmsSendLambda`,"Arn"]}},r[`${e.slug}SmsNotificationTopicArn`]={Description:"SMS notification topic ARN",Value:{Ref:`${e.slug}SmsNotificationTopic`}},r[`${e.slug}SmsMessageLogTableName`]={Description:"SMS message log table name",Value:{Ref:`${e.slug}SmsMessageLogTable`}},{resources:a,outputs:r}}}function At(e){return e.replace(/[^a-zA-Z0-9]/g," ").trim().split(/\s+/).map((a)=>a.charAt(0).toUpperCase()+a.slice(1)).join("")||"User"}function xr(e,a){let r=(e||a).replace(/^\/+|\/+$/g,"");if(!r||r.split("/").includes(".."))throw Error(`sftp: invalid homeDirectory for user ${a}`);return r}function Or(e){let a=e.storage;if(a?.type==="efs"){let n="fileSystemId"in a?a.fileSystemId:void 0;if(!n||typeof n==="string"&&!n.trim())throw Error("sftp: EFS storage requires fileSystemId, or a fileSystem name defined in infrastructure.fileSystem");return{type:"efs",fileSystemId:n,posixProfile:a.posixProfile}}let r=(a?.type==="s3"?a.bucket??e.bucket:e.bucket)?.trim();if(!r)throw Error("sftp: S3 storage requires bucket, or a storageBucket name defined in infrastructure.storage");return{type:"s3",bucket:r}}function Br(e,a,r){let n=a.posixProfile??r;if(!n)throw Error(`sftp: user ${e} requires a posixProfile (uid/gid) on an EFS-backed server`);for(let i of[n.uid,n.gid,...n.secondaryGids??[]])if(!Number.isInteger(i)||i<0||i>4294967295)throw Error(`sftp: user ${e} has an invalid posixProfile id ${i}`);return{Uid:n.uid,Gid:n.gid,...n.secondaryGids?.length?{SecondaryGids:n.secondaryGids}:{}}}function _r(e,a){return typeof e==="string"?`/${e}/${a}`:{"Fn::Sub":[`/\${FileSystemId}/${a}`,{FileSystemId:e}]}}function Wr(e){return typeof e==="string"?{"Fn::Sub":"arn:aws:elasticfilesystem:${AWS::Region}:${AWS::AccountId}:file-system/${FileSystemId}".replace("${FileSystemId}",e)}:{"Fn::Sub":["arn:aws:elasticfilesystem:${AWS::Region}:${AWS::AccountId}:file-system/${FileSystemId}",{FileSystemId:e}]}}class Eo{static create(e){let a=Or(e),r=a.type==="efs"?"EFS":"S3",n=e.endpointType??"PUBLIC";if(n==="VPC"&&(!e.endpointDetails?.vpcId||!e.endpointDetails.subnetIds.length))throw Error("sftp: VPC endpoints require endpointDetails.vpcId and at least one subnet");let i=`${At(e.slug)}${At(e.environment)}Sftp`,o=`${i}Server`,c={},u;if(e.logging!==!1){let d=`${i}LoggingRole`;c[d]={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"transfer.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"TransferLogging",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["logs:CreateLogGroup","logs:CreateLogStream","logs:DescribeLogStreams","logs:PutLogEvents"],Resource:"arn:aws:logs:*:*:log-group:/aws/transfer/*"}]}}]}},u={"Fn::GetAtt":[d,"Arn"]}}c[o]={Type:"AWS::Transfer::Server",Properties:{Domain:r,EndpointType:n,IdentityProviderType:"SERVICE_MANAGED",Protocols:["SFTP"],...n==="VPC"?{EndpointDetails:{VpcId:e.endpointDetails.vpcId,SubnetIds:e.endpointDetails.subnetIds,...e.endpointDetails.securityGroupIds?.length?{SecurityGroupIds:e.endpointDetails.securityGroupIds}:{},...e.endpointDetails.addressAllocationIds?.length?{AddressAllocationIds:e.endpointDetails.addressAllocationIds}:{}}}:{},...e.securityPolicyName?{SecurityPolicyName:e.securityPolicyName}:{},...u?{LoggingRole:u}:{},Tags:[{Key:"Project",Value:e.slug},{Key:"Environment",Value:e.environment},{Key:"ManagedBy",Value:"ts-cloud"}]}};for(let[d,m]of Object.entries(e.users)){if(!/^[a-zA-Z0-9_.@-]{3,100}$/.test(d))throw Error(`sftp: invalid username ${d}`);if(!m.sshPublicKeys.length)throw Error(`sftp: user ${d} requires at least one SSH public key`);let p=At(d),g=xr(m.homeDirectory,d),h=`${i}${p}User`,y=m.roleArn;if(!y){let f=`${i}${p}Role`,b;if(a.type==="efs")b=[{Effect:"Allow",Action:["elasticfilesystem:ClientMount","elasticfilesystem:ClientWrite","elasticfilesystem:DescribeMountTargets"],Resource:Wr(a.fileSystemId)}];else{let v=`arn:aws:s3:::${a.bucket}`;b=[{Effect:"Allow",Action:["s3:ListBucket","s3:GetBucketLocation"],Resource:v,Condition:{StringLike:{"s3:prefix":[g,`${g}/*`]}}},{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:GetObjectVersion"],Resource:`${v}/${g}/*`}]}c[f]={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"transfer.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"SftpHomeDirectory",PolicyDocument:{Version:"2012-10-17",Statement:b}}]}},y={"Fn::GetAtt":[f,"Arn"]}}c[h]={Type:"AWS::Transfer::User",DependsOn:[o],Properties:{ServerId:{Ref:o},UserName:d,Role:y,HomeDirectoryType:"PATH",HomeDirectory:a.type==="efs"?_r(a.fileSystemId,g):`/${a.bucket}/${g}`,...a.type==="efs"?{PosixProfile:Br(d,m,a.posixProfile)}:{},SshPublicKeys:m.sshPublicKeys}}}return{resources:c,serverLogicalId:o,domain:r}}}class Ue{static createBedrockRole(e,a){let{slug:r,environment:n,name:i,models:o=["*"],allowStreaming:c=!0}=a,u=i||l({slug:r,environment:n,resourceType:"bedrock-role"}),d=s(u),m=["bedrock:InvokeModel"];if(c)m.push("bedrock:InvokeModelWithResponseStream");let p=o.map((g)=>g==="*"?"arn:aws:bedrock:*::foundation-model/*":`arn:aws:bedrock:*::foundation-model/${g}`);return{role:{Type:"AWS::IAM::Role",Properties:{RoleName:u,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:e},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:`${u}-policy`,PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:m,Resource:p}]}}],Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:n}]}},logicalId:d}}static createBedrockPolicy(e){let{slug:a,environment:r,name:n,models:i=["*"],allowInvoke:o=!0,allowStreaming:c=!0,allowAsync:u=!1}=e,d=n||l({slug:a,environment:r,resourceType:"bedrock-policy"}),m=s(d),p=[];if(o)p.push("bedrock:InvokeModel");if(c)p.push("bedrock:InvokeModelWithResponseStream");if(u)p.push("bedrock:InvokeModelAsync");let g=i.map((h)=>h==="*"?"arn:aws:bedrock:*::foundation-model/*":`arn:aws:bedrock:*::foundation-model/${h}`);return{policy:{Type:"AWS::IAM::ManagedPolicy",Properties:{ManagedPolicyName:d,PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"BedrockModelInvocation",Effect:"Allow",Action:p,Resource:g}]}}},logicalId:m}}static enableBedrockForLambda(e){return Ue.createBedrockRole("lambda.amazonaws.com",e)}static enableBedrockForEcs(e){return Ue.createBedrockRole("ecs-tasks.amazonaws.com",e)}static enableBedrockForEc2(e){return Ue.createBedrockRole("ec2.amazonaws.com",e)}static addBedrockPermissions(e,a=["*"],r=!0){let n=["bedrock:InvokeModel"];if(r)n.push("bedrock:InvokeModelWithResponseStream");let i=a.map((o)=>o==="*"?"arn:aws:bedrock:*::foundation-model/*":`arn:aws:bedrock:*::foundation-model/${o}`);if(!e.Properties.Policies)e.Properties.Policies=[];return e.Properties.Policies.push({PolicyName:"bedrock-permissions",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:n,Resource:i}]}}),e}static Models={Claude3_5_Sonnet:"anthropic.claude-3-5-sonnet-20241022-v2:0",Claude3_5_Haiku:"anthropic.claude-3-5-haiku-20241022-v1:0",Claude3_Opus:"anthropic.claude-3-opus-20240229-v1:0",Claude3_Sonnet:"anthropic.claude-3-sonnet-20240229-v1:0",Claude3_Haiku:"anthropic.claude-3-haiku-20240307-v1:0",TitanTextG1Express:"amazon.titan-text-express-v1",TitanTextG1Lite:"amazon.titan-text-lite-v1",TitanEmbedG1Text:"amazon.titan-embed-text-v1",TitanImageG1:"amazon.titan-image-generator-v1",JurassicUltra:"ai21.j2-ultra-v1",JurassicMid:"ai21.j2-mid-v1",CommandText:"cohere.command-text-v14",CommandLight:"cohere.command-light-text-v14",EmbedEnglish:"cohere.embed-english-v3",EmbedMultilingual:"cohere.embed-multilingual-v3",Llama3_2_1B:"meta.llama3-2-1b-instruct-v1:0",Llama3_2_3B:"meta.llama3-2-3b-instruct-v1:0",Llama3_2_11B:"meta.llama3-2-11b-instruct-v1:0",Llama3_2_90B:"meta.llama3-2-90b-instruct-v1:0",Llama3_1_8B:"meta.llama3-1-8b-instruct-v1:0",Llama3_1_70B:"meta.llama3-1-70b-instruct-v1:0",Llama3_1_405B:"meta.llama3-1-405b-instruct-v1:0",Mistral7B:"mistral.mistral-7b-instruct-v0:2",Mixtral8x7B:"mistral.mixtral-8x7b-instruct-v0:1",MistralLarge:"mistral.mistral-large-2402-v1:0",StableDiffusionXL:"stability.stable-diffusion-xl-v1"};static ModelGroups={AllClaude:["anthropic.claude-3-5-sonnet-20241022-v2:0","anthropic.claude-3-5-haiku-20241022-v1:0","anthropic.claude-3-opus-20240229-v1:0","anthropic.claude-3-sonnet-20240229-v1:0","anthropic.claude-3-haiku-20240307-v1:0"],AllTitan:["amazon.titan-text-express-v1","amazon.titan-text-lite-v1","amazon.titan-embed-text-v1","amazon.titan-image-generator-v1"],AllLlama:["meta.llama3-2-1b-instruct-v1:0","meta.llama3-2-3b-instruct-v1:0","meta.llama3-2-11b-instruct-v1:0","meta.llama3-2-90b-instruct-v1:0","meta.llama3-1-8b-instruct-v1:0","meta.llama3-1-70b-instruct-v1:0","meta.llama3-1-405b-instruct-v1:0"],TextModels:["anthropic.claude-3-5-sonnet-20241022-v2:0","anthropic.claude-3-5-haiku-20241022-v1:0","amazon.titan-text-express-v1","meta.llama3-2-11b-instruct-v1:0","mistral.mistral-7b-instruct-v0:2"],EmbeddingModels:["amazon.titan-embed-text-v1","cohere.embed-english-v3","cohere.embed-multilingual-v3"],ImageModels:["amazon.titan-image-generator-v1","stability.stable-diffusion-xl-v1"]}}class Bt{static createPostgres(e){return Bt.createRDSInstance("postgres","16.2",e)}static createMysql(e){return Bt.createRDSInstance("mysql","8.0.35",e)}static createRDSInstance(e,a,r){let{slug:n,environment:i,instanceClass:o="db.t3.micro",allocatedStorage:c=20,storageType:u="gp3",masterUsername:d="admin",masterPassword:m,databaseName:p,subnetIds:g,securityGroupIds:h,encrypted:y=!0,kmsKeyId:f,multiAz:b=!1,backupRetentionDays:v=7,publiclyAccessible:w=!1,enableCloudwatchLogs:R=!0,deletionProtection:T=!0}=r,N=l({slug:n,environment:i,resourceType:`${e}-db`}),I=s(N),k,x;if(g&&g.length>0){let O=l({slug:n,environment:i,resourceType:"db-subnet-group"});x=s(O),k={Type:"AWS::RDS::DBSubnetGroup",Properties:{DBSubnetGroupName:O,DBSubnetGroupDescription:`Subnet group for ${N}`,SubnetIds:g,Tags:[{Key:"Name",Value:O},{Key:"Environment",Value:i}]}}}let L={Type:"AWS::RDS::DBInstance",Properties:{DBInstanceIdentifier:N,DBInstanceClass:o,Engine:e,EngineVersion:a,MasterUsername:d,MasterUserPassword:m,AllocatedStorage:c,StorageType:u,StorageEncrypted:y,MultiAZ:b,BackupRetentionPeriod:v,PubliclyAccessible:w,DeletionProtection:T,Tags:[{Key:"Name",Value:N},{Key:"Environment",Value:i}]}};if(p)L.Properties.DBName=p;if(f)L.Properties.KmsKeyId=f;if(x)L.Properties.DBSubnetGroupName=P.Ref(x);if(h&&h.length>0)L.Properties.VPCSecurityGroups=h;if(R)L.Properties.EnableCloudwatchLogsExports=e==="postgres"?["postgresql"]:["error","general","slowquery"];return{dbInstance:L,subnetGroup:k,logicalId:I,subnetGroupId:x}}static createReadReplica(e,a){let{slug:r,environment:n,instanceClass:i="db.t3.micro",securityGroupIds:o,publiclyAccessible:c=!1}=a,u=l({slug:r,environment:n,resourceType:"db-replica"}),d=s(u),m={Type:"AWS::RDS::DBInstance",Properties:{DBInstanceIdentifier:u,DBInstanceClass:i,SourceDBInstanceIdentifier:P.Ref(e),PubliclyAccessible:c,Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:n},{Key:"Type",Value:"ReadReplica"}]}};if(o&&o.length>0)m.Properties.VPCSecurityGroups=o;return{replica:m,logicalId:d}}static createParameterGroup(e,a,r){let{slug:n,environment:i,parameters:o={}}=r,c=l({slug:n,environment:i,resourceType:"db-params"}),u=s(c),d=e==="postgres"?`postgres${a.split(".")[0]}`:`mysql${a.split(".")[0]}.${a.split(".")[1]}`;return{parameterGroup:{Type:"AWS::RDS::DBParameterGroup",Properties:{DBParameterGroupName:c,Description:`Parameter group for ${c}`,Family:d,Parameters:o,Tags:[{Key:"Name",Value:c},{Key:"Environment",Value:i}]}},logicalId:u}}static enableBackup(e,a=7){return e.Properties.BackupRetentionPeriod=a,e}static createTable(e){let{slug:a,environment:r,tableName:n,partitionKey:i,sortKey:o,billingMode:c="PAY_PER_REQUEST",readCapacity:u=5,writeCapacity:d=5,streamEnabled:m=!1,streamViewType:p="NEW_AND_OLD_IMAGES",encrypted:g=!0,kmsKeyId:h,pointInTimeRecovery:y=!0,ttlAttribute:f}=e,b=n||l({slug:a,environment:r,resourceType:"table"}),v=s(b),w=[{AttributeName:i.name,AttributeType:i.type}];if(o)w.push({AttributeName:o.name,AttributeType:o.type});let R=[{AttributeName:i.name,KeyType:"HASH"}];if(o)R.push({AttributeName:o.name,KeyType:"RANGE"});let T={Type:"AWS::DynamoDB::Table",Properties:{TableName:b,BillingMode:c,AttributeDefinitions:w,KeySchema:R,Tags:[{Key:"Name",Value:b},{Key:"Environment",Value:r}]}};if(c==="PROVISIONED")T.Properties.ProvisionedThroughput={ReadCapacityUnits:u,WriteCapacityUnits:d};if(m)T.Properties.StreamSpecification={StreamViewType:p};if(g)T.Properties.SSESpecification={SSEEnabled:!0,SSEType:h?"KMS":"AES256",KMSMasterKeyId:h};if(y)T.Properties.PointInTimeRecoverySpecification={PointInTimeRecoveryEnabled:!0};if(f)T.Properties.TimeToLiveSpecification={AttributeName:f,Enabled:!0};return{table:T,logicalId:v}}static addGlobalSecondaryIndex(e,a){let{indexName:r,partitionKey:n,sortKey:i,projectionType:o="ALL",nonKeyAttributes:c,readCapacity:u=5,writeCapacity:d=5}=a;if(!e.Properties.AttributeDefinitions.some((g)=>g.AttributeName===n.name))e.Properties.AttributeDefinitions.push({AttributeName:n.name,AttributeType:n.type});if(i&&!e.Properties.AttributeDefinitions.some((g)=>g.AttributeName===i.name))e.Properties.AttributeDefinitions.push({AttributeName:i.name,AttributeType:i.type});let m=[{AttributeName:n.name,KeyType:"HASH"}];if(i)m.push({AttributeName:i.name,KeyType:"RANGE"});let p={IndexName:r,KeySchema:m,Projection:{ProjectionType:o,NonKeyAttributes:o==="INCLUDE"?c:void 0},ProvisionedThroughput:void 0};if(e.Properties.BillingMode==="PROVISIONED")p.ProvisionedThroughput={ReadCapacityUnits:u,WriteCapacityUnits:d};if(!e.Properties.GlobalSecondaryIndexes)e.Properties.GlobalSecondaryIndexes=[];return e.Properties.GlobalSecondaryIndexes.push(p),e}static enableStreams(e,a="NEW_AND_OLD_IMAGES"){return e.Properties.StreamSpecification={StreamViewType:a},e}static InstanceClasses={T3_Micro:"db.t3.micro",T3_Small:"db.t3.small",T3_Medium:"db.t3.medium",T3_Large:"db.t3.large",T4g_Micro:"db.t4g.micro",T4g_Small:"db.t4g.small",T4g_Medium:"db.t4g.medium",M5_Large:"db.m5.large",M5_XLarge:"db.m5.xlarge",M5_2XLarge:"db.m5.2xlarge",R5_Large:"db.r5.large",R5_XLarge:"db.r5.xlarge",R5_2XLarge:"db.r5.2xlarge"}}class mi{static createRedis(e){let{slug:a,environment:r,nodeType:n="cache.t3.micro",engineVersion:i="7.1",port:o=6379,subnetIds:c,securityGroupIds:u,numCacheClusters:d=2,automaticFailover:m=!0,multiAz:p=!0,clusterMode:g=!1,numNodeGroups:h=1,replicasPerNodeGroup:y=1,atRestEncryption:f=!0,transitEncryption:b=!0,authToken:v,kmsKeyId:w,snapshotRetentionDays:R=7,snapshotWindow:T,maintenanceWindow:N}=e,I=l({slug:a,environment:r,resourceType:"redis"}),k=s(I),x,L;if(c&&c.length>0){let W=l({slug:a,environment:r,resourceType:"cache-subnet-group"});L=s(W),x={Type:"AWS::ElastiCache::SubnetGroup",Properties:{CacheSubnetGroupName:W,Description:`Subnet group for ${I}`,SubnetIds:c,Tags:[{Key:"Name",Value:W},{Key:"Environment",Value:r}]}}}let O={Type:"AWS::ElastiCache::ReplicationGroup",Properties:{ReplicationGroupId:I,ReplicationGroupDescription:`Redis cluster for ${a} ${r}`,Engine:"redis",EngineVersion:i,CacheNodeType:n,Port:o,AutomaticFailoverEnabled:m,MultiAZEnabled:p,AtRestEncryptionEnabled:f,TransitEncryptionEnabled:b,SnapshotRetentionLimit:R,AutoMinorVersionUpgrade:!0,Tags:[{Key:"Name",Value:I},{Key:"Environment",Value:r}]}};if(g)O.Properties.NumNodeGroups=h,O.Properties.ReplicasPerNodeGroup=y;else O.Properties.NumCacheClusters=d;if(v)O.Properties.AuthToken=v;if(w)O.Properties.KmsKeyId=w;if(L)O.Properties.CacheSubnetGroupName=P.Ref(L);if(u&&u.length>0)O.Properties.SecurityGroupIds=u;if(T)O.Properties.SnapshotWindow=T;if(N)O.Properties.PreferredMaintenanceWindow=N;return{replicationGroup:O,subnetGroup:x,logicalId:k,subnetGroupId:L}}static createMemcached(e){let{slug:a,environment:r,nodeType:n="cache.t3.micro",engineVersion:i="1.6.22",port:o=11211,numCacheNodes:c=2,subnetIds:u,securityGroupIds:d,azMode:m="cross-az",preferredAzs:p,maintenanceWindow:g}=e,h=l({slug:a,environment:r,resourceType:"memcached"}),y=s(h),f,b;if(u&&u.length>0){let w=l({slug:a,environment:r,resourceType:"cache-subnet-group"});b=s(w),f={Type:"AWS::ElastiCache::SubnetGroup",Properties:{CacheSubnetGroupName:w,Description:`Subnet group for ${h}`,SubnetIds:u,Tags:[{Key:"Name",Value:w},{Key:"Environment",Value:r}]}}}let v={Type:"AWS::ElastiCache::CacheCluster",Properties:{ClusterName:h,CacheNodeType:n,Engine:"memcached",EngineVersion:i,NumCacheNodes:c,Port:o,AZMode:m,AutoMinorVersionUpgrade:!0,Tags:[{Key:"Name",Value:h},{Key:"Environment",Value:r}]}};if(b)v.Properties.CacheSubnetGroupName=P.Ref(b);if(d&&d.length>0)v.Properties.VpcSecurityGroupIds=d;if(p&&p.length>0)v.Properties.PreferredAvailabilityZones=p;if(g)v.Properties.PreferredMaintenanceWindow=g;return{cluster:v,subnetGroup:f,logicalId:y,subnetGroupId:b}}static enableClusterMode(e,a=3,r=2){return delete e.Properties.NumCacheClusters,e.Properties.NumNodeGroups=a,e.Properties.ReplicasPerNodeGroup=r,e}static createRedisParameterGroup(e,a){let{slug:r,environment:n,parameters:i={}}=a,o=l({slug:r,environment:n,resourceType:"redis-params"}),c=s(o);return{parameterGroup:{Type:"AWS::ElastiCache::ParameterGroup",Properties:{CacheParameterGroupFamily:`redis${e.split(".")[0]}.x`,Description:`Parameter group for ${o}`,Properties:i,Tags:[{Key:"Name",Value:o},{Key:"Environment",Value:n}]}},logicalId:c}}static createMemcachedParameterGroup(e,a){let{slug:r,environment:n,parameters:i={}}=a,o=l({slug:r,environment:n,resourceType:"memcached-params"}),c=s(o);return{parameterGroup:{Type:"AWS::ElastiCache::ParameterGroup",Properties:{CacheParameterGroupFamily:`memcached${e.split(".")[0]}.${e.split(".")[1]}`,Description:`Parameter group for ${o}`,Properties:i,Tags:[{Key:"Name",Value:o},{Key:"Environment",Value:n}]}},logicalId:c}}static NodeTypes={T3_Micro:"cache.t3.micro",T3_Small:"cache.t3.small",T3_Medium:"cache.t3.medium",T4g_Micro:"cache.t4g.micro",T4g_Small:"cache.t4g.small",T4g_Medium:"cache.t4g.medium",M5_Large:"cache.m5.large",M5_XLarge:"cache.m5.xlarge",M5_2XLarge:"cache.m5.2xlarge",R5_Large:"cache.r5.large",R5_XLarge:"cache.r5.xlarge",R5_2XLarge:"cache.r5.2xlarge",R5_4XLarge:"cache.r5.4xlarge",R6g_Large:"cache.r6g.large",R6g_XLarge:"cache.r6g.xlarge",R6g_2XLarge:"cache.r6g.2xlarge"}}class ve{static createUser(e){let{slug:a,environment:r,userName:n,groups:i,managedPolicyArns:o}=e,c=n||l({slug:a,environment:r,resourceType:"user"}),u=s(c),d={Type:"AWS::IAM::User",Properties:{UserName:c,Tags:[{Key:"Name",Value:c},{Key:"Environment",Value:r}]}};if(i&&i.length>0)d.Properties.Groups=i;if(o&&o.length>0)d.Properties.ManagedPolicyArns=o;return{user:d,logicalId:u}}static createRole(e){let{slug:a,environment:r,roleName:n,servicePrincipal:i,awsPrincipal:o,managedPolicyArns:c}=e,u=n||l({slug:a,environment:r,resourceType:"role"}),d=s(u),m={};if(i)m.Service=i;if(o)m.AWS=o;let p={Type:"AWS::IAM::Role",Properties:{RoleName:u,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:m,Action:"sts:AssumeRole"}]},Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:r}]}};if(c&&c.length>0)p.Properties.ManagedPolicyArns=c;return{role:p,logicalId:d}}static createGroup(e){let{slug:a,environment:r,groupName:n,managedPolicyArns:i}=e,o=n||l({slug:a,environment:r,resourceType:"group"}),c=s(o),u={Type:"AWS::IAM::Group",Properties:{GroupName:o}};if(i&&i.length>0)u.Properties.ManagedPolicyArns=i;return{group:u,logicalId:c}}static createPolicy(e){let{slug:a,environment:r,policyName:n,description:i,statements:o}=e,c=n||l({slug:a,environment:r,resourceType:"policy"}),u=s(c),d=o.map((m)=>({Sid:m.sid,Effect:m.effect||"Allow",Action:m.actions,Resource:m.resources,Condition:m.conditions}));return{policy:{Type:"AWS::IAM::ManagedPolicy",Properties:{ManagedPolicyName:c,Description:i||`Managed policy for ${c}`,PolicyDocument:{Version:"2012-10-17",Statement:d}}},logicalId:u}}static attachPolicyToRole(e,a){if(!e.Properties.ManagedPolicyArns)e.Properties.ManagedPolicyArns=[];if(!e.Properties.ManagedPolicyArns.includes(a))e.Properties.ManagedPolicyArns.push(a);return e}static attachPolicyToUser(e,a){if(!e.Properties.ManagedPolicyArns)e.Properties.ManagedPolicyArns=[];if(!e.Properties.ManagedPolicyArns.includes(a))e.Properties.ManagedPolicyArns.push(a);return e}static attachPolicyToGroup(e,a){if(!e.Properties.ManagedPolicyArns)e.Properties.ManagedPolicyArns=[];if(!e.Properties.ManagedPolicyArns.includes(a))e.Properties.ManagedPolicyArns.push(a);return e}static addInlinePolicyToRole(e,a,r){if(!e.Properties.Policies)e.Properties.Policies=[];let n=r.map((i)=>({Effect:i.effect||"Allow",Action:i.actions,Resource:i.resources}));return e.Properties.Policies.push({PolicyName:a,PolicyDocument:{Version:"2012-10-17",Statement:n}}),e}static addInlinePolicyToUser(e,a,r){if(!e.Properties.Policies)e.Properties.Policies=[];let n=r.map((i)=>({Effect:i.effect||"Allow",Action:i.actions,Resource:i.resources}));return e.Properties.Policies.push({PolicyName:a,PolicyDocument:{Version:"2012-10-17",Statement:n}}),e}static createAccessKey(e,a){let{slug:r,environment:n,status:i="Active"}=a,o=l({slug:r,environment:n,resourceType:"access-key"}),c=s(o);return{accessKey:{Type:"AWS::IAM::AccessKey",Properties:{UserName:P.Ref(e),Status:i}},logicalId:c}}static createInstanceProfile(e,a){let{slug:r,environment:n,profileName:i}=a,o=i||l({slug:r,environment:n,resourceType:"instance-profile"}),c=s(o);return{instanceProfile:{Type:"AWS::IAM::InstanceProfile",Properties:{InstanceProfileName:o,Roles:[P.Ref(e)]}},logicalId:c}}static ManagedPolicies={AdministratorAccess:"arn:aws:iam::aws:policy/AdministratorAccess",PowerUserAccess:"arn:aws:iam::aws:policy/PowerUserAccess",ReadOnlyAccess:"arn:aws:iam::aws:policy/ReadOnlyAccess",S3FullAccess:"arn:aws:iam::aws:policy/AmazonS3FullAccess",S3ReadOnlyAccess:"arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess",DynamoDBFullAccess:"arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess",DynamoDBReadOnlyAccess:"arn:aws:iam::aws:policy/AmazonDynamoDBReadOnlyAccess",RDSFullAccess:"arn:aws:iam::aws:policy/AmazonRDSFullAccess",RDSReadOnlyAccess:"arn:aws:iam::aws:policy/AmazonRDSReadOnlyAccess",LambdaFullAccess:"arn:aws:iam::aws:policy/AWSLambda_FullAccess",LambdaReadOnlyAccess:"arn:aws:iam::aws:policy/AWSLambda_ReadOnlyAccess",LambdaBasicExecutionRole:"arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole",LambdaVPCAccessExecutionRole:"arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole",EC2FullAccess:"arn:aws:iam::aws:policy/AmazonEC2FullAccess",EC2ReadOnlyAccess:"arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess",EC2ContainerRegistryReadOnly:"arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly",EC2ContainerRegistryPowerUser:"arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryPowerUser",ECSTaskExecutionRole:"arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy",ECSFullAccess:"arn:aws:iam::aws:policy/AmazonECS_FullAccess",CloudWatchFullAccess:"arn:aws:iam::aws:policy/CloudWatchFullAccess",CloudWatchLogsFullAccess:"arn:aws:iam::aws:policy/CloudWatchLogsFullAccess",SESFullAccess:"arn:aws:iam::aws:policy/AmazonSESFullAccess",SNSFullAccess:"arn:aws:iam::aws:policy/AmazonSNSFullAccess",SQSFullAccess:"arn:aws:iam::aws:policy/AmazonSQSFullAccess",SecretsManagerReadWrite:"arn:aws:iam::aws:policy/SecretsManagerReadWrite"};static ServicePrincipals={Lambda:"lambda.amazonaws.com",EC2:"ec2.amazonaws.com",ECS:"ecs.amazonaws.com",ECSTaskExecution:"ecs-tasks.amazonaws.com",APIGateway:"apigateway.amazonaws.com",Events:"events.amazonaws.com",States:"states.amazonaws.com",CodeBuild:"codebuild.amazonaws.com",CodeDeploy:"codedeploy.amazonaws.com",CloudFormation:"cloudformation.amazonaws.com"};static createCiCdUser(e){let{slug:a,environment:r,permissions:n,createAccessKey:i=!0}=e,o={},c=[];if(n.s3Buckets&&n.s3Buckets.length>0)c.push({sid:"S3Access",actions:["s3:GetBucketLocation","s3:ListBucket","s3:GetObject","s3:PutObject","s3:DeleteObject","s3:ListBucketMultipartUploads","s3:AbortMultipartUpload"],resources:[...n.s3Buckets,...n.s3Buckets.map((y)=>`${y}/*`)]});if(n.cloudFrontDistributions&&n.cloudFrontDistributions.length>0)c.push({sid:"CloudFrontAccess",actions:["cloudfront:CreateInvalidation","cloudfront:GetInvalidation","cloudfront:ListInvalidations","cloudfront:GetDistribution"],resources:n.cloudFrontDistributions});if(n.ecrRepositories&&n.ecrRepositories.length>0)c.push({sid:"ECRAccess",actions:["ecr:GetAuthorizationToken","ecr:BatchCheckLayerAvailability","ecr:GetDownloadUrlForLayer","ecr:GetRepositoryPolicy","ecr:DescribeRepositories","ecr:ListImages","ecr:DescribeImages","ecr:BatchGetImage","ecr:InitiateLayerUpload","ecr:UploadLayerPart","ecr:CompleteLayerUpload","ecr:PutImage"],resources:n.ecrRepositories}),c.push({sid:"ECRLogin",actions:["ecr:GetAuthorizationToken"],resources:"*"});if(n.ecsServices&&n.ecsServices.length>0)c.push({sid:"ECSAccess",actions:["ecs:DescribeServices","ecs:DescribeTaskDefinition","ecs:DescribeTasks","ecs:ListTasks","ecs:RegisterTaskDefinition","ecs:UpdateService","ecs:RunTask","ecs:StopTask"],resources:n.ecsServices}),c.push({sid:"ECSTaskDefinitions",actions:["ecs:RegisterTaskDefinition","ecs:DeregisterTaskDefinition"],resources:"*"}),c.push({sid:"ECSPassRole",actions:["iam:PassRole"],resources:"*",conditions:{StringLike:{"iam:PassedToService":"ecs-tasks.amazonaws.com"}}});if(n.cloudFormationStacks&&n.cloudFormationStacks.length>0)c.push({sid:"CloudFormationAccess",actions:["cloudformation:CreateStack","cloudformation:UpdateStack","cloudformation:DeleteStack","cloudformation:DescribeStacks","cloudformation:DescribeStackEvents","cloudformation:DescribeStackResources","cloudformation:GetTemplate","cloudformation:ListStackResources","cloudformation:ValidateTemplate"],resources:n.cloudFormationStacks});if(n.lambdaFunctions&&n.lambdaFunctions.length>0)c.push({sid:"LambdaAccess",actions:["lambda:GetFunction","lambda:UpdateFunctionCode","lambda:UpdateFunctionConfiguration","lambda:PublishVersion","lambda:UpdateAlias","lambda:CreateAlias"],resources:n.lambdaFunctions});if(n.secretsManagerSecrets&&n.secretsManagerSecrets.length>0)c.push({sid:"SecretsManagerAccess",actions:["secretsmanager:GetSecretValue","secretsmanager:DescribeSecret"],resources:n.secretsManagerSecrets});let{policy:u,logicalId:d}=ve.createPolicy({slug:a,environment:r,policyName:l({slug:a,environment:r,resourceType:"cicd-policy"}),description:`CI/CD deployment policy for ${a} (${r})`,statements:c});o[d]=u;let{user:m,logicalId:p}=ve.createUser({slug:a,environment:r,userName:l({slug:a,environment:r,resourceType:"cicd-user"}),managedPolicyArns:[P.Ref(d)]});o[p]=m;let g,h;if(i){let y=ve.createAccessKey(p,{slug:a,environment:r});g=y.accessKey,h=y.logicalId,o[h]=g}return{user:m,accessKey:g,policy:u,userLogicalId:p,accessKeyLogicalId:h,policyLogicalId:d,resources:o}}static createCrossAccountRole(e){let{slug:a,environment:r,trustedAccountIds:n,externalId:i,permissions:o,maxSessionDuration:c=3600}=e,u={},{policy:d,logicalId:m}=ve.createPolicy({slug:a,environment:r,policyName:l({slug:a,environment:r,resourceType:"cross-account-policy"}),description:`Cross-account access policy for ${a} (${r})`,statements:o});u[m]=d;let p=l({slug:a,environment:r,resourceType:"cross-account-role"}),g=s(p),h={};if(i)h.StringEquals={"sts:ExternalId":i};let y={Type:"AWS::IAM::Role",Properties:{RoleName:p,MaxSessionDuration:c,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:n.map((f)=>`arn:aws:iam::${f}:root`)},Action:"sts:AssumeRole",...Object.keys(h).length>0?{Condition:h}:{}}]},ManagedPolicyArns:[P.Ref(m)],Tags:[{Key:"Name",Value:p},{Key:"Environment",Value:r},{Key:"Purpose",Value:"Cross-Account Access"}]}};return u[g]=y,{role:y,policy:d,roleLogicalId:g,policyLogicalId:m,resources:u}}static createCliUser(e){let{slug:a,environment:r,permissions:n="readonly"}=e,i={},o=[],c=[];switch(n){case"readonly":c=[ve.ManagedPolicies.ReadOnlyAccess];break;case"deploy":o=[{sid:"S3Deploy",actions:["s3:*"],resources:"*"},{sid:"CloudFrontDeploy",actions:["cloudfront:*"],resources:"*"},{sid:"ECSDeploy",actions:["ecs:*"],resources:"*"},{sid:"ECRDeploy",actions:["ecr:*"],resources:"*"},{sid:"LambdaDeploy",actions:["lambda:*"],resources:"*"},{sid:"CloudFormationDeploy",actions:["cloudformation:*"],resources:"*"},{sid:"IAMPassRole",actions:["iam:PassRole"],resources:"*"}];break;case"admin":c=[ve.ManagedPolicies.AdministratorAccess];break}let u,d;if(o.length>0){let y=ve.createPolicy({slug:a,environment:r,policyName:l({slug:a,environment:r,resourceType:"cli-policy"}),description:`CLI access policy for ${a} (${r})`,statements:o});u=y.policy,d=y.logicalId,i[d]=u,c=[P.Ref(d)]}let{user:m,logicalId:p}=ve.createUser({slug:a,environment:r,userName:l({slug:a,environment:r,resourceType:"cli-user"}),managedPolicyArns:c});i[p]=m;let{accessKey:g,logicalId:h}=ve.createAccessKey(p,{slug:a,environment:r});return i[h]=g,{user:m,accessKey:g,policy:u,userLogicalId:p,accessKeyLogicalId:h,policyLogicalId:d,resources:i}}static CiCdPolicies={s3Deployment:(e)=>[{sid:"S3ListBuckets",actions:["s3:ListBucket","s3:GetBucketLocation"],resources:e},{sid:"S3Objects",actions:["s3:GetObject","s3:PutObject","s3:DeleteObject"],resources:e.map((a)=>`${a}/*`)}],cloudFrontInvalidation:(e)=>[{sid:"CloudFrontInvalidation",actions:["cloudfront:CreateInvalidation","cloudfront:GetInvalidation","cloudfront:ListInvalidations"],resources:e}],ecsDeployment:()=>[{sid:"ECSServices",actions:["ecs:DescribeServices","ecs:UpdateService","ecs:DescribeTaskDefinition","ecs:RegisterTaskDefinition"],resources:"*"},{sid:"ECSPassRole",actions:["iam:PassRole"],resources:"*",conditions:{StringLike:{"iam:PassedToService":"ecs-tasks.amazonaws.com"}}}],ecrPush:(e)=>[{sid:"ECRAuth",actions:["ecr:GetAuthorizationToken"],resources:"*"},{sid:"ECRPush",actions:["ecr:BatchCheckLayerAvailability","ecr:GetDownloadUrlForLayer","ecr:BatchGetImage","ecr:InitiateLayerUpload","ecr:UploadLayerPart","ecr:CompleteLayerUpload","ecr:PutImage"],resources:e}],lambdaDeployment:(e)=>[{sid:"LambdaDeploy",actions:["lambda:GetFunction","lambda:UpdateFunctionCode","lambda:UpdateFunctionConfiguration","lambda:PublishVersion"],resources:e}],cloudFormationDeployment:(e)=>[{sid:"CloudFormationDeploy",actions:["cloudformation:CreateStack","cloudformation:UpdateStack","cloudformation:DescribeStacks","cloudformation:DescribeStackEvents","cloudformation:GetTemplate"],resources:e}]}}class wo{static createRestApi(e){let{slug:a,environment:r,name:n,description:i,endpointType:o="REGIONAL",binaryMediaTypes:c,compressionSize:u}=e,d=n||l({slug:a,environment:r,resourceType:"rest-api"}),m=s(d),p={Type:"AWS::ApiGateway::RestApi",Properties:{Name:d,Description:i||`REST API for ${a} ${r}`,EndpointConfiguration:{Types:[o]},Tags:[{Key:"Name",Value:d},{Key:"Environment",Value:r}]}};if(c&&c.length>0)p.Properties.BinaryMediaTypes=c;if(u!==void 0)p.Properties.MinimumCompressionSize=u;return{restApi:p,logicalId:m}}static createHttpApi(e){let{slug:a,environment:r,name:n,description:i,corsEnabled:o=!0,corsOrigins:c=["*"],corsMethods:u=["GET","POST","PUT","PATCH","DELETE","OPTIONS"],corsHeaders:d=["*"],corsMaxAge:m=86400,corsAllowCredentials:p=!1}=e,g=n||l({slug:a,environment:r,resourceType:"http-api"}),h=s(g),y={Type:"AWS::ApiGatewayV2::Api",Properties:{Name:g,Description:i||`HTTP API for ${a} ${r}`,ProtocolType:"HTTP",Tags:{Name:g,Environment:r}}};if(o)y.Properties.CorsConfiguration={AllowOrigins:c,AllowMethods:u,AllowHeaders:d,MaxAge:m,AllowCredentials:p};return{httpApi:y,logicalId:h}}static createWebSocketApi(e){let{slug:a,environment:r,name:n,description:i}=e,o=n||l({slug:a,environment:r,resourceType:"ws-api"}),c=s(o);return{webSocketApi:{Type:"AWS::ApiGatewayV2::Api",Properties:{Name:o,Description:i||`WebSocket API for ${a} ${r}`,ProtocolType:"WEBSOCKET",Tags:{Name:o,Environment:r}}},logicalId:c}}static createDeployment(e,a){let{slug:r,environment:n,description:i}=a,o=l({slug:r,environment:n,resourceType:"api-deployment"}),c=s(o);return{deployment:{Type:"AWS::ApiGateway::Deployment",Properties:{RestApiId:P.Ref(e),Description:i||`Deployment for ${o}`}},logicalId:c}}static createStage(e,a,r){let{slug:n,environment:i,stageName:o,description:c,cacheEnabled:u=!1,cacheSize:d="0.5",variables:m,throttling:p}=r,g=l({slug:n,environment:i,resourceType:"api-stage"}),h=s(g),y={Type:"AWS::ApiGateway::Stage",Properties:{StageName:o||i,RestApiId:P.Ref(e),DeploymentId:P.Ref(a),Description:c,CacheClusterEnabled:u,Tags:[{Key:"Name",Value:g},{Key:"Environment",Value:i}]}};if(u)y.Properties.CacheClusterSize=d;if(m)y.Properties.Variables=m;if(p)y.Properties.MethodSettings=[{HttpMethod:"*",ResourcePath:"/*",ThrottlingBurstLimit:p.burstLimit,ThrottlingRateLimit:p.rateLimit}];return{stage:y,logicalId:h}}static createAuthorizer(e,a){let{slug:r,environment:n,name:i,type:o,functionArn:c,identitySource:u,userPoolArns:d,ttl:m=300}=a,p=i||l({slug:r,environment:n,resourceType:"api-authorizer"}),g=s(p),h={Type:"AWS::ApiGateway::Authorizer",Properties:{Name:p,Type:o,RestApiId:P.Ref(e),AuthorizerResultTtlInSeconds:m}};if(o==="TOKEN"||o==="REQUEST"){if(!c)throw Error("Lambda authorizer requires functionArn");h.Properties.AuthorizerUri=c,h.Properties.IdentitySource=u||"method.request.header.Authorization"}if(o==="COGNITO_USER_POOLS"){if(!d||d.length===0)throw Error("Cognito authorizer requires userPoolArns");h.Properties.ProviderARNs=d,h.Properties.IdentitySource=u||"method.request.header.Authorization"}return{authorizer:h,logicalId:g}}static setCors(e,a={}){let{origins:r=["*"],methods:n=["GET","POST","PUT","PATCH","DELETE","OPTIONS"],headers:i=["*"],maxAge:o=86400,allowCredentials:c=!1}=a;return e.Properties.CorsConfiguration={AllowOrigins:r,AllowMethods:n,AllowHeaders:i,MaxAge:o,AllowCredentials:c},e}static addThrottling(e,a=5000,r=1e4){if(!e.Properties.MethodSettings)e.Properties.MethodSettings=[];return e.Properties.MethodSettings.push({HttpMethod:"*",ResourcePath:"/*",ThrottlingBurstLimit:a,ThrottlingRateLimit:r}),e}static enableCaching(e,a="0.5",r=300){if(e.Properties.CacheClusterEnabled=!0,e.Properties.CacheClusterSize=a,!e.Properties.MethodSettings)e.Properties.MethodSettings=[];return e.Properties.MethodSettings.push({HttpMethod:"*",ResourcePath:"/*",CachingEnabled:!0,CacheTtlInSeconds:r}),e}static CacheSizes={Small:"0.5",Medium:"1.6",Large:"6.1",XLarge:"13.5",XXLarge:"28.4",XXXLarge:"58.2",Huge:"118",Massive:"237"};static ThrottlingPresets={Light:{burstLimit:100,rateLimit:50},Medium:{burstLimit:500,rateLimit:250},Heavy:{burstLimit:2000,rateLimit:1000},Default:{burstLimit:5000,rateLimit:1e4}}}class Ne{static createTopic(e){let{slug:a,environment:r,topicName:n,displayName:i,encrypted:o=!1,kmsKeyId:c}=e,u=n||l({slug:a,environment:r,resourceType:"topic"}),d=s(u),m={Type:"AWS::SNS::Topic",Properties:{TopicName:u,DisplayName:i||u,Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:r}]}};if(o&&c)m.Properties.KmsMasterKeyId=c;return{topic:m,logicalId:d}}static subscribe(e,a){let{slug:r,environment:n,protocol:i,endpoint:o,filterPolicy:c,rawMessageDelivery:u=!1}=a,d=l({slug:r,environment:n,resourceType:"subscription"}),m=o.replace(/[^a-zA-Z0-9]/g,""),p=m.length>12?m.slice(-12):m,g=s(`${d}-${i}-${p}`),h={Type:"AWS::SNS::Subscription",Properties:{TopicArn:P.Ref(e),Protocol:i,Endpoint:o,RawMessageDelivery:u}};if(c)h.Properties.FilterPolicy=c;return{subscription:h,logicalId:g}}static subscribeEmail(e,a,r){return Ne.subscribe(e,{...r,protocol:"email",endpoint:a})}static subscribeLambda(e,a,r){return Ne.subscribe(e,{...r,protocol:"lambda",endpoint:a,rawMessageDelivery:!0})}static subscribeSqs(e,a,r){return Ne.subscribe(e,{...r,protocol:"sqs",endpoint:a})}static subscribeHttp(e,a,r){let n=a.startsWith("https://")?"https":"http";return Ne.subscribe(e,{...r,protocol:n,endpoint:a})}static subscribeSms(e,a,r){return Ne.subscribe(e,{...r,protocol:"sms",endpoint:a})}static setTopicPolicy(e,a){let{slug:r,environment:n,allowedPrincipals:i,allowedServices:o,actions:c="SNS:Publish"}=a,u=l({slug:r,environment:n,resourceType:"topic-policy"}),d=s(u),m={};if(i)m.AWS=i;if(o)m.Service=o;return{policy:{Type:"AWS::SNS::TopicPolicy",Properties:{Topics:[P.Ref(e)],PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:m,Action:c,Resource:P.Ref(e)}]}}},logicalId:d}}static allowCloudWatchAlarms(e,a){return Ne.setTopicPolicy(e,{...a,allowedServices:"cloudwatch.amazonaws.com",actions:"SNS:Publish"})}static allowEventBridge(e,a){return Ne.setTopicPolicy(e,{...a,allowedServices:"events.amazonaws.com",actions:"SNS:Publish"})}static allowS3(e,a){return Ne.setTopicPolicy(e,{...a,allowedServices:"s3.amazonaws.com",actions:"SNS:Publish"})}static enableEncryption(e,a){if(!e.Properties)e.Properties={};return e.Properties.KmsMasterKeyId=a,e}static addInlineSubscription(e,a,r){if(!e.Properties)e.Properties={};if(!e.Properties.Subscription)e.Properties.Subscription=[];return e.Properties.Subscription.push({Protocol:a,Endpoint:r}),e}static FilterPolicies={eventType:(e)=>({eventType:e}),status:(e)=>({status:e}),numericRange:(e,a,r)=>({[e]:[{numeric:[">=",a,"<=",r]}]}),prefix:(e,a)=>({[e]:[{prefix:a}]}),and:(...e)=>Object.assign({},...e),exists:(e,a)=>({[e]:[{exists:a}]})};static UseCases={createAlertTopic:(e)=>Ne.createTopic({...e,topicName:e.topicName||`${e.slug}-${e.environment}-alerts`,displayName:e.displayName||"Alert Notifications"}),createEventFanout:(e)=>Ne.createTopic({...e,topicName:e.topicName||`${e.slug}-${e.environment}-events`,displayName:e.displayName||"Event Fanout"}),createNotificationTopic:(e)=>Ne.createTopic({...e,topicName:e.topicName||`${e.slug}-${e.environment}-notifications`,displayName:e.displayName||"User Notifications"})}}class gd{static createStateMachine(e){let{slug:a,environment:r,stateMachineName:n,type:i="STANDARD",definition:o,roleArn:c,loggingConfiguration:u,tracingConfiguration:d}=e,m=n||l({slug:a,environment:r,resourceType:"state-machine"}),p=s(m),g,h,y;if(c)y=c;else{let b=l({slug:a,environment:r,resourceType:"state-machine-role"});h=s(b),g={Type:"AWS::IAM::Role",Properties:{RoleName:b,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"states.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/CloudWatchLogsFullAccess"],Tags:[{Key:"Name",Value:b},{Key:"Environment",Value:r}]}},y=P.GetAtt(h,"Arn")}let f={Type:"AWS::StepFunctions::StateMachine",Properties:{StateMachineName:m,StateMachineType:i,DefinitionString:JSON.stringify(o),RoleArn:y,Tags:[{Key:"Name",Value:m},{Key:"Environment",Value:r}]}};if(u)f.Properties.LoggingConfiguration={Level:u.level,IncludeExecutionData:u.includeExecutionData,Destinations:u.destinations?.map((b)=>({CloudWatchLogsLogGroup:{LogGroupArn:b}}))};if(d)f.Properties.TracingConfiguration={Enabled:d.enabled};return{stateMachine:f,logicalId:p,role:g,roleLogicalId:h}}static createLambdaTask(e,a){return{Type:"Task",Resource:"arn:aws:states:::lambda:invoke",Parameters:{FunctionName:e,Payload:a?.parameters||{"Input.$":"$"}},ResultPath:a?.resultPath,Retry:a?.retry,Catch:a?.catch,Next:a?.next,End:a?.end}}static createDynamoDBTask(e,a,r,n){return{Type:"Task",Resource:{GetItem:"arn:aws:states:::dynamodb:getItem",PutItem:"arn:aws:states:::dynamodb:putItem",UpdateItem:"arn:aws:states:::dynamodb:updateItem",DeleteItem:"arn:aws:states:::dynamodb:deleteItem"}[e],Parameters:{TableName:a,...r},ResultPath:n?.resultPath,Retry:n?.retry,Catch:n?.catch,Next:n?.next,End:n?.end}}static createSNSPublishTask(e,a,r){return{Type:"Task",Resource:"arn:aws:states:::sns:publish",Parameters:{TopicArn:e,Message:a},ResultPath:r?.resultPath,Retry:r?.retry,Catch:r?.catch,Next:r?.next,End:r?.end}}static createSQSSendMessageTask(e,a,r){return{Type:"Task",Resource:"arn:aws:states:::sqs:sendMessage",Parameters:{QueueUrl:e,MessageBody:a},ResultPath:r?.resultPath,Retry:r?.retry,Catch:r?.catch,Next:r?.next,End:r?.end}}static createPassState(e){return{Type:"Pass",Result:e?.result,ResultPath:e?.resultPath,Parameters:e?.parameters,Next:e?.next,End:e?.end}}static createWaitState(e){return{Type:"Wait",Seconds:e.seconds,Timestamp:e.timestamp,SecondsPath:e.secondsPath,TimestampPath:e.timestampPath,Next:e.next,End:e.end}}static createChoiceState(e,a){return{Type:"Choice",Choices:e,Default:a}}static createParallelState(e,a){return{Type:"Parallel",Branches:e,ResultPath:a?.resultPath,Retry:a?.retry,Catch:a?.catch,Next:a?.next,End:a?.end}}static createMapState(e,a){return{Type:"Map",ItemsPath:a?.itemsPath||"$.items",Iterator:e,MaxConcurrency:a?.maxConcurrency,ResultPath:a?.resultPath,Retry:a?.retry,Catch:a?.catch,Next:a?.next,End:a?.end}}static createSucceedState(){return{Type:"Succeed"}}static createFailState(e,a){return{Type:"Fail",Error:e,Cause:a}}static RetryPolicies={standard:()=>({ErrorEquals:["States.ALL"],IntervalSeconds:2,MaxAttempts:3,BackoffRate:2}),aggressive:()=>({ErrorEquals:["States.TaskFailed","States.Timeout"],IntervalSeconds:1,MaxAttempts:5,BackoffRate:1.5}),custom:(e,a,r,n)=>({ErrorEquals:e,IntervalSeconds:a,MaxAttempts:r,BackoffRate:n})};static CatchPolicies={all:(e,a)=>({ErrorEquals:["States.ALL"],Next:e,ResultPath:a||"$.error"}),specific:(e,a,r)=>({ErrorEquals:e,Next:a,ResultPath:r||"$.error"})};static Patterns={sequential:(e,a,r)=>{let n={};return r.forEach((i,o)=>{let c=o===r.length-1;n[i.name]={...i.state,Next:c?void 0:r[o+1].name,End:c}}),{Comment:"Sequential workflow",StartAt:r[0].name,States:n}},fanout:(e,a,r)=>({Comment:"Fan-out workflow",StartAt:"Parallel",States:{Parallel:{Type:"Parallel",Branches:r.map((n)=>n.definition),End:!0}}}),map:(e,a,r,n)=>({Comment:"Map workflow",StartAt:"Map",States:{Map:{Type:"Map",ItemsPath:"$.items",Iterator:r,MaxConcurrency:n,End:!0}}}),withErrorHandling:(e,a,r,n)=>({Comment:"Workflow with error handling",StartAt:"Main",States:{Main:{...r,Catch:[{ErrorEquals:["States.ALL"],Next:"ErrorHandler"}],Next:"Success"},ErrorHandler:n,Success:{Type:"Succeed"}}})}}class gi{static createAlarm(e){let{slug:a,environment:r,alarmName:n,metricName:i,namespace:o,statistic:c="Average",period:u=300,evaluationPeriods:d=1,threshold:m,comparisonOperator:p,treatMissingData:g="notBreaching",actionsEnabled:h=!0,alarmActions:y,okActions:f,insufficientDataActions:b,dimensions:v,unit:w,datapointsToAlarm:R}=e,T=n||l({slug:a,environment:r,resourceType:"alarm"}),N=s(T),I={Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:T,MetricName:i,Namespace:o,Statistic:c,Period:u,EvaluationPeriods:d,Threshold:m,ComparisonOperator:p,TreatMissingData:g,ActionsEnabled:h}};if(y&&y.length>0)I.Properties.AlarmActions=y;if(f&&f.length>0)I.Properties.OKActions=f;if(b&&b.length>0)I.Properties.InsufficientDataActions=b;if(v)I.Properties.Dimensions=Object.entries(v).map(([k,x])=>({Name:k,Value:x}));if(w)I.Properties.Unit=w;if(R!==void 0)I.Properties.DatapointsToAlarm=R;return{alarm:I,logicalId:N}}static createCompositeAlarm(e){let{slug:a,environment:r,alarmName:n,alarmRule:i,actionsEnabled:o=!0,alarmActions:c,okActions:u,insufficientDataActions:d}=e,m=n||l({slug:a,environment:r,resourceType:"composite-alarm"}),p=s(m),g={Type:"AWS::CloudWatch::CompositeAlarm",Properties:{AlarmName:m,AlarmRule:i,ActionsEnabled:o}};if(c&&c.length>0)g.Properties.AlarmActions=c;if(u&&u.length>0)g.Properties.OKActions=u;if(d&&d.length>0)g.Properties.InsufficientDataActions=d;return{alarm:g,logicalId:p}}static createDashboard(e){let{slug:a,environment:r,dashboardName:n,widgets:i}=e,o=n||l({slug:a,environment:r,resourceType:"dashboard"}),c=s(o),u={widgets:i.map((d)=>({type:d.type,x:d.x,y:d.y,width:d.width,height:d.height,properties:d.properties}))};return{dashboard:{Type:"AWS::CloudWatch::Dashboard",Properties:{DashboardName:o,DashboardBody:JSON.stringify(u)}},logicalId:c}}static createLogGroup(e){let{slug:a,environment:r,logGroupName:n,retentionInDays:i,kmsKeyId:o}=e,c=n||l({slug:a,environment:r,resourceType:"log-group"}),u=s(c),d={Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:c}};if(i!==void 0)d.Properties.RetentionInDays=i;if(o)d.Properties.KmsKeyId=o;return{logGroup:d,logicalId:u}}static createLogStream(e,a){let{slug:r,environment:n,logStreamName:i}=a,o=i||l({slug:r,environment:n,resourceType:"log-stream"}),c=s(o);return{logStream:{Type:"AWS::Logs::LogStream",Properties:{LogGroupName:P.Ref(e),LogStreamName:o}},logicalId:c}}static createMetricFilter(e,a){let{slug:r,environment:n,filterName:i,filterPattern:o,metricTransformations:c}=a,u=i||l({slug:r,environment:n,resourceType:"metric-filter"}),d=s(u);return{metricFilter:{Type:"AWS::Logs::MetricFilter",Properties:{LogGroupName:P.Ref(e),FilterPattern:o,MetricTransformations:c.map((m)=>({MetricName:m.metricName,MetricNamespace:m.metricNamespace,MetricValue:m.metricValue,DefaultValue:m.defaultValue,Unit:m.unit}))}},logicalId:d}}static AlarmTypes={highCpu:(e,a,r,n=80,i)=>({slug:e,environment:a,alarmName:`${e}-${a}-high-cpu`,metricName:"CPUUtilization",namespace:"AWS/EC2",statistic:"Average",period:300,evaluationPeriods:2,threshold:n,comparisonOperator:"GreaterThanThreshold",dimensions:{InstanceId:r},alarmActions:i?[i]:void 0}),highMemory:(e,a,r,n=80,i)=>({slug:e,environment:a,alarmName:`${e}-${a}-high-memory`,metricName:"MemoryUtilization",namespace:"System/Linux",statistic:"Average",period:300,evaluationPeriods:2,threshold:n,comparisonOperator:"GreaterThanThreshold",dimensions:{InstanceId:r},alarmActions:i?[i]:void 0}),highDisk:(e,a,r,n=80,i)=>({slug:e,environment:a,alarmName:`${e}-${a}-high-disk`,metricName:"DiskSpaceUtilization",namespace:"System/Linux",statistic:"Average",period:300,evaluationPeriods:2,threshold:n,comparisonOperator:"GreaterThanThreshold",dimensions:{InstanceId:r,Filesystem:"/dev/xvda1",MountPath:"/"},alarmActions:i?[i]:void 0}),lambdaErrors:(e,a,r,n=5,i)=>({slug:e,environment:a,alarmName:`${e}-${a}-lambda-errors`,metricName:"Errors",namespace:"AWS/Lambda",statistic:"Sum",period:300,evaluationPeriods:1,threshold:n,comparisonOperator:"GreaterThanThreshold",dimensions:{FunctionName:r},alarmActions:i?[i]:void 0}),lambdaThrottles:(e,a,r,n=10,i)=>({slug:e,environment:a,alarmName:`${e}-${a}-lambda-throttles`,metricName:"Throttles",namespace:"AWS/Lambda",statistic:"Sum",period:300,evaluationPeriods:1,threshold:n,comparisonOperator:"GreaterThanThreshold",dimensions:{FunctionName:r},alarmActions:i?[i]:void 0}),apiGateway5xxErrors:(e,a,r,n=10,i)=>({slug:e,environment:a,alarmName:`${e}-${a}-api-5xx-errors`,metricName:"5XXError",namespace:"AWS/ApiGateway",statistic:"Sum",period:300,evaluationPeriods:1,threshold:n,comparisonOperator:"GreaterThanThreshold",dimensions:{ApiName:r},alarmActions:i?[i]:void 0}),apiGateway4xxErrors:(e,a,r,n=50,i)=>({slug:e,environment:a,alarmName:`${e}-${a}-api-4xx-errors`,metricName:"4XXError",namespace:"AWS/ApiGateway",statistic:"Sum",period:300,evaluationPeriods:2,threshold:n,comparisonOperator:"GreaterThanThreshold",dimensions:{ApiName:r},alarmActions:i?[i]:void 0}),dynamoDBThrottles:(e,a,r,n=5,i)=>({slug:e,environment:a,alarmName:`${e}-${a}-dynamodb-throttles`,metricName:"UserErrors",namespace:"AWS/DynamoDB",statistic:"Sum",period:300,evaluationPeriods:1,threshold:n,comparisonOperator:"GreaterThanThreshold",dimensions:{TableName:r},alarmActions:i?[i]:void 0}),rdsCpu:(e,a,r,n=80,i)=>({slug:e,environment:a,alarmName:`${e}-${a}-rds-cpu`,metricName:"CPUUtilization",namespace:"AWS/RDS",statistic:"Average",period:300,evaluationPeriods:2,threshold:n,comparisonOperator:"GreaterThanThreshold",dimensions:{DBInstanceIdentifier:r},alarmActions:i?[i]:void 0}),rdsFreeStorage:(e,a,r,n=5368709120,i)=>({slug:e,environment:a,alarmName:`${e}-${a}-rds-storage`,metricName:"FreeStorageSpace",namespace:"AWS/RDS",statistic:"Average",period:300,evaluationPeriods:1,threshold:n,comparisonOperator:"LessThanThreshold",dimensions:{DBInstanceIdentifier:r},alarmActions:i?[i]:void 0,unit:"Bytes"}),sqsQueueDepth:(e,a,r,n=100,i)=>({slug:e,environment:a,alarmName:`${e}-${a}-sqs-depth`,metricName:"ApproximateNumberOfMessagesVisible",namespace:"AWS/SQS",statistic:"Average",period:300,evaluationPeriods:2,threshold:n,comparisonOperator:"GreaterThanThreshold",dimensions:{QueueName:r},alarmActions:i?[i]:void 0}),albUnhealthyTargets:(e,a,r,n,i=1,o)=>({slug:e,environment:a,alarmName:`${e}-${a}-alb-unhealthy`,metricName:"UnHealthyHostCount",namespace:"AWS/ApplicationELB",statistic:"Average",period:300,evaluationPeriods:2,threshold:i,comparisonOperator:"GreaterThanThreshold",dimensions:{LoadBalancer:r,TargetGroup:n},alarmActions:o?[o]:void 0}),sesBounceRate:(e,a,r=5,n)=>({slug:e,environment:a,alarmName:`${e}-${a}-ses-bounce-rate`,metricName:"Reputation.BounceRate",namespace:"AWS/SES",statistic:"Average",period:3600,evaluationPeriods:1,threshold:r/100,comparisonOperator:"GreaterThanThreshold",alarmActions:n?[n]:void 0}),sesComplaintRate:(e,a,r=0.1,n)=>({slug:e,environment:a,alarmName:`${e}-${a}-ses-complaint-rate`,metricName:"Reputation.ComplaintRate",namespace:"AWS/SES",statistic:"Average",period:3600,evaluationPeriods:1,threshold:r/100,comparisonOperator:"GreaterThanThreshold",alarmActions:n?[n]:void 0}),smsDeliveryFailure:(e,a,r,n=10,i)=>({slug:e,environment:a,alarmName:`${e}-${a}-sms-delivery-failure`,metricName:"DirectSendMessagePermanentFailure",namespace:"AWS/Pinpoint",statistic:"Sum",period:300,evaluationPeriods:1,threshold:n,comparisonOperator:"GreaterThanThreshold",dimensions:{ApplicationId:r},alarmActions:i?[i]:void 0}),smsSpendLimit:(e,a,r=100,n)=>({slug:e,environment:a,alarmName:`${e}-${a}-sms-spend-limit`,metricName:"DirectSendMessageSpend",namespace:"AWS/Pinpoint",statistic:"Sum",period:86400,evaluationPeriods:1,threshold:r,comparisonOperator:"GreaterThanThreshold",alarmActions:n?[n]:void 0}),connectMissedCalls:(e,a,r,n=5,i)=>({slug:e,environment:a,alarmName:`${e}-${a}-connect-missed-calls`,metricName:"MissedCalls",namespace:"AWS/Connect",statistic:"Sum",period:3600,evaluationPeriods:1,threshold:n,comparisonOperator:"GreaterThanThreshold",dimensions:{InstanceId:r},alarmActions:i?[i]:void 0})};static DashboardWidgets={metric:(e,a,r,n,i,o)=>({type:"metric",x:e,y:a,width:r,height:n,properties:{metrics:i,title:o||"Metrics",region:"us-east-1",period:300}}),text:(e,a,r,n,i)=>({type:"text",x:e,y:a,width:r,height:n,properties:{markdown:i}}),log:(e,a,r,n,i,o)=>({type:"log",x:e,y:a,width:r,height:n,properties:{query:`SOURCE '${i.join("' | SOURCE '")}'
|
|
2309
|
+
`;class be{static LambdaCode={send:La,receive:Lr,deliveryStatus:$r};static createPinpointApp(e){return{[`${e.slug}PinpointApp`]:{Type:"AWS::Pinpoint::App",Properties:{Name:e.name||`${e.slug}-sms`}}}}static createSmsChannel(e){let a={ApplicationId:e.applicationId,Enabled:e.enabled!==!1};if(e.senderId)a.SenderId=e.senderId;if(e.shortCode)a.ShortCode=e.shortCode;return{[`${e.slug}SmsChannel`]:{Type:"AWS::Pinpoint::SMSChannel",Properties:a}}}static createSmsLambdaRole(e){return{[`${e.slug}SmsLambdaRole`]:{Type:"AWS::IAM::Role",Properties:{RoleName:`${e.slug}-sms-lambda-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:"SmsLambdaPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["mobiletargeting:SendMessages","mobiletargeting:GetSmsChannel"],Resource:"*"},{Effect:"Allow",Action:["sns:Publish"],Resource:"*"},{Effect:"Allow",Action:["dynamodb:PutItem","dynamodb:UpdateItem","dynamodb:GetItem","dynamodb:DeleteItem"],Resource:"*"}]}}]}}}}static createSendLambda(e){return{[`${e.slug}SmsSendLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${e.slug}-sms-send`,Runtime:"nodejs20.x",Handler:"index.handler",Role:e.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:be.LambdaCode.send},Environment:{Variables:{PINPOINT_APP_ID:e.pinpointAppId,MESSAGE_LOG_TABLE:e.messageLogTable||"",SMS_SENDER_ID:e.senderId||"",SMS_ORIGINATION_NUMBER:e.originationNumber||""}}}}}}static createReceiveLambda(e){return{[`${e.slug}SmsReceiveLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${e.slug}-sms-receive`,Runtime:"nodejs20.x",Handler:"index.handler",Role:e.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:be.LambdaCode.receive},Environment:{Variables:{OPT_OUT_TABLE:e.optOutTable||"",MESSAGE_LOG_TABLE:e.messageLogTable||"",NOTIFICATION_TOPIC_ARN:e.notificationTopicArn||"",WEBHOOK_URL:e.webhookUrl||""}}}}}}static createDeliveryStatusLambda(e){return{[`${e.slug}SmsDeliveryStatusLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${e.slug}-sms-delivery-status`,Runtime:"nodejs20.x",Handler:"index.handler",Role:e.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:be.LambdaCode.deliveryStatus},Environment:{Variables:{MESSAGE_LOG_TABLE:e.messageLogTable||"",NOTIFICATION_TOPIC_ARN:e.notificationTopicArn||"",WEBHOOK_URL:e.webhookUrl||""}}}}}}static createMessageLogTable(e){return{[`${e.slug}SmsMessageLogTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${e.slug}-sms-messages`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"messageId",AttributeType:"S"}],KeySchema:[{AttributeName:"messageId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createOptOutTable(e){return{[`${e.slug}SmsOptOutTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${e.slug}-sms-optouts`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"phoneNumber",AttributeType:"S"}],KeySchema:[{AttributeName:"phoneNumber",KeyType:"HASH"}]}}}}static createNotificationTopic(e){return{[`${e.slug}SmsNotificationTopic`]:{Type:"AWS::SNS::Topic",Properties:{TopicName:`${e.slug}-sms-notifications`}}}}static createCompleteSetup(e){let a={},r={};Object.assign(a,be.createPinpointApp({slug:e.slug})),Object.assign(a,be.createSmsChannel({slug:e.slug,applicationId:{Ref:`${e.slug}PinpointApp`},senderId:e.senderId})),Object.assign(a,be.createSmsLambdaRole({slug:e.slug})),Object.assign(a,be.createMessageLogTable({slug:e.slug})),Object.assign(a,be.createOptOutTable({slug:e.slug})),Object.assign(a,be.createNotificationTopic({slug:e.slug}));let n={"Fn::GetAtt":[`${e.slug}SmsLambdaRole`,"Arn"]},i={Ref:`${e.slug}PinpointApp`},o={Ref:`${e.slug}SmsMessageLogTable`},c={Ref:`${e.slug}SmsOptOutTable`},u={Ref:`${e.slug}SmsNotificationTopic`};if(Object.assign(a,be.createSendLambda({slug:e.slug,roleArn:n,pinpointAppId:i,messageLogTable:o,senderId:e.senderId,originationNumber:e.originationNumber})),e.twoWayEnabled)Object.assign(a,be.createReceiveLambda({slug:e.slug,roleArn:n,optOutTable:c,messageLogTable:o,notificationTopicArn:u,webhookUrl:e.webhookUrl}));return Object.assign(a,be.createDeliveryStatusLambda({slug:e.slug,roleArn:n,messageLogTable:o,notificationTopicArn:u,webhookUrl:e.webhookUrl})),r[`${e.slug}PinpointAppId`]={Description:"Pinpoint application ID",Value:{Ref:`${e.slug}PinpointApp`}},r[`${e.slug}SmsSendLambdaArn`]={Description:"SMS send Lambda ARN",Value:{"Fn::GetAtt":[`${e.slug}SmsSendLambda`,"Arn"]}},r[`${e.slug}SmsNotificationTopicArn`]={Description:"SMS notification topic ARN",Value:{Ref:`${e.slug}SmsNotificationTopic`}},r[`${e.slug}SmsMessageLogTableName`]={Description:"SMS message log table name",Value:{Ref:`${e.slug}SmsMessageLogTable`}},{resources:a,outputs:r}}}function At(e){return e.replace(/[^a-zA-Z0-9]/g," ").trim().split(/\s+/).map((a)=>a.charAt(0).toUpperCase()+a.slice(1)).join("")||"User"}function xr(e,a){let r=(e||a).replace(/^\/+|\/+$/g,"");if(!r||r.split("/").includes(".."))throw Error(`sftp: invalid homeDirectory for user ${a}`);return r}function Or(e){let a=e.storage;if(a?.type==="efs"){let n="fileSystemId"in a?a.fileSystemId:void 0;if(!n||typeof n==="string"&&!n.trim())throw Error("sftp: EFS storage requires fileSystemId, or a fileSystem name defined in infrastructure.fileSystem");return{type:"efs",fileSystemId:n,posixProfile:a.posixProfile}}let r=(a?.type==="s3"?a.bucket??e.bucket:e.bucket)?.trim();if(!r)throw Error("sftp: S3 storage requires bucket, or a storageBucket name defined in infrastructure.storage");return{type:"s3",bucket:r}}function Br(e,a,r){let n=a.posixProfile??r;if(!n)throw Error(`sftp: user ${e} requires a posixProfile (uid/gid) on an EFS-backed server`);for(let i of[n.uid,n.gid,...n.secondaryGids??[]])if(!Number.isInteger(i)||i<0||i>4294967295)throw Error(`sftp: user ${e} has an invalid posixProfile id ${i}`);return{Uid:n.uid,Gid:n.gid,...n.secondaryGids?.length?{SecondaryGids:n.secondaryGids}:{}}}function _r(e,a){return typeof e==="string"?`/${e}/${a}`:{"Fn::Sub":[`/\${FileSystemId}/${a}`,{FileSystemId:e}]}}function Wr(e){return typeof e==="string"?{"Fn::Sub":"arn:aws:elasticfilesystem:${AWS::Region}:${AWS::AccountId}:file-system/${FileSystemId}".replace("${FileSystemId}",e)}:{"Fn::Sub":["arn:aws:elasticfilesystem:${AWS::Region}:${AWS::AccountId}:file-system/${FileSystemId}",{FileSystemId:e}]}}class Eo{static create(e){let a=Or(e),r=a.type==="efs"?"EFS":"S3",n=e.endpointType??"PUBLIC";if(n==="VPC"&&(!e.endpointDetails?.vpcId||!e.endpointDetails.subnetIds.length))throw Error("sftp: VPC endpoints require endpointDetails.vpcId and at least one subnet");let i=`${At(e.slug)}${At(e.environment)}Sftp`,o=`${i}Server`,c={},u;if(e.logging!==!1){let d=`${i}LoggingRole`;c[d]={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"transfer.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"TransferLogging",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["logs:CreateLogGroup","logs:CreateLogStream","logs:DescribeLogStreams","logs:PutLogEvents"],Resource:"arn:aws:logs:*:*:log-group:/aws/transfer/*"}]}}]}},u={"Fn::GetAtt":[d,"Arn"]}}c[o]={Type:"AWS::Transfer::Server",Properties:{Domain:r,EndpointType:n,IdentityProviderType:"SERVICE_MANAGED",Protocols:["SFTP"],...n==="VPC"?{EndpointDetails:{VpcId:e.endpointDetails.vpcId,SubnetIds:e.endpointDetails.subnetIds,...e.endpointDetails.securityGroupIds?.length?{SecurityGroupIds:e.endpointDetails.securityGroupIds}:{},...e.endpointDetails.addressAllocationIds?.length?{AddressAllocationIds:e.endpointDetails.addressAllocationIds}:{}}}:{},...e.securityPolicyName?{SecurityPolicyName:e.securityPolicyName}:{},...u?{LoggingRole:u}:{},Tags:[{Key:"Project",Value:e.slug},{Key:"Environment",Value:e.environment},{Key:"ManagedBy",Value:"ts-cloud"}]}};for(let[d,m]of Object.entries(e.users)){if(!/^[a-zA-Z0-9_.@-]{3,100}$/.test(d))throw Error(`sftp: invalid username ${d}`);if(!m.sshPublicKeys.length)throw Error(`sftp: user ${d} requires at least one SSH public key`);let p=At(d),g=xr(m.homeDirectory,d),h=`${i}${p}User`,y=m.roleArn;if(!y){let f=`${i}${p}Role`,b;if(a.type==="efs")b=[{Effect:"Allow",Action:["elasticfilesystem:ClientMount","elasticfilesystem:ClientWrite","elasticfilesystem:DescribeMountTargets"],Resource:Wr(a.fileSystemId)}];else{let v=`arn:aws:s3:::${a.bucket}`;b=[{Effect:"Allow",Action:["s3:ListBucket","s3:GetBucketLocation"],Resource:v,Condition:{StringLike:{"s3:prefix":[g,`${g}/*`]}}},{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:GetObjectVersion"],Resource:`${v}/${g}/*`}]}c[f]={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"transfer.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"SftpHomeDirectory",PolicyDocument:{Version:"2012-10-17",Statement:b}}]}},y={"Fn::GetAtt":[f,"Arn"]}}c[h]={Type:"AWS::Transfer::User",DependsOn:[o],Properties:{ServerId:{Ref:o},UserName:d,Role:y,HomeDirectoryType:"PATH",HomeDirectory:a.type==="efs"?_r(a.fileSystemId,g):`/${a.bucket}/${g}`,...a.type==="efs"?{PosixProfile:Br(d,m,a.posixProfile)}:{},SshPublicKeys:m.sshPublicKeys}}}return{resources:c,serverLogicalId:o,domain:r}}}class Ue{static createBedrockRole(e,a){let{slug:r,environment:n,name:i,models:o=["*"],allowStreaming:c=!0}=a,u=i||l({slug:r,environment:n,resourceType:"bedrock-role"}),d=s(u),m=["bedrock:InvokeModel"];if(c)m.push("bedrock:InvokeModelWithResponseStream");let p=o.map((g)=>g==="*"?"arn:aws:bedrock:*::foundation-model/*":`arn:aws:bedrock:*::foundation-model/${g}`);return{role:{Type:"AWS::IAM::Role",Properties:{RoleName:u,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:e},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:`${u}-policy`,PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:m,Resource:p}]}}],Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:n}]}},logicalId:d}}static createBedrockPolicy(e){let{slug:a,environment:r,name:n,models:i=["*"],allowInvoke:o=!0,allowStreaming:c=!0,allowAsync:u=!1}=e,d=n||l({slug:a,environment:r,resourceType:"bedrock-policy"}),m=s(d),p=[];if(o)p.push("bedrock:InvokeModel");if(c)p.push("bedrock:InvokeModelWithResponseStream");if(u)p.push("bedrock:InvokeModelAsync");let g=i.map((h)=>h==="*"?"arn:aws:bedrock:*::foundation-model/*":`arn:aws:bedrock:*::foundation-model/${h}`);return{policy:{Type:"AWS::IAM::ManagedPolicy",Properties:{ManagedPolicyName:d,PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"BedrockModelInvocation",Effect:"Allow",Action:p,Resource:g}]}}},logicalId:m}}static enableBedrockForLambda(e){return Ue.createBedrockRole("lambda.amazonaws.com",e)}static enableBedrockForEcs(e){return Ue.createBedrockRole("ecs-tasks.amazonaws.com",e)}static enableBedrockForEc2(e){return Ue.createBedrockRole("ec2.amazonaws.com",e)}static addBedrockPermissions(e,a=["*"],r=!0){let n=["bedrock:InvokeModel"];if(r)n.push("bedrock:InvokeModelWithResponseStream");let i=a.map((o)=>o==="*"?"arn:aws:bedrock:*::foundation-model/*":`arn:aws:bedrock:*::foundation-model/${o}`);if(!e.Properties.Policies)e.Properties.Policies=[];return e.Properties.Policies.push({PolicyName:"bedrock-permissions",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:n,Resource:i}]}}),e}static Models={Claude3_5_Sonnet:"anthropic.claude-3-5-sonnet-20241022-v2:0",Claude3_5_Haiku:"anthropic.claude-3-5-haiku-20241022-v1:0",Claude3_Opus:"anthropic.claude-3-opus-20240229-v1:0",Claude3_Sonnet:"anthropic.claude-3-sonnet-20240229-v1:0",Claude3_Haiku:"anthropic.claude-3-haiku-20240307-v1:0",TitanTextG1Express:"amazon.titan-text-express-v1",TitanTextG1Lite:"amazon.titan-text-lite-v1",TitanEmbedG1Text:"amazon.titan-embed-text-v1",TitanImageG1:"amazon.titan-image-generator-v1",JurassicUltra:"ai21.j2-ultra-v1",JurassicMid:"ai21.j2-mid-v1",CommandText:"cohere.command-text-v14",CommandLight:"cohere.command-light-text-v14",EmbedEnglish:"cohere.embed-english-v3",EmbedMultilingual:"cohere.embed-multilingual-v3",Llama3_2_1B:"meta.llama3-2-1b-instruct-v1:0",Llama3_2_3B:"meta.llama3-2-3b-instruct-v1:0",Llama3_2_11B:"meta.llama3-2-11b-instruct-v1:0",Llama3_2_90B:"meta.llama3-2-90b-instruct-v1:0",Llama3_1_8B:"meta.llama3-1-8b-instruct-v1:0",Llama3_1_70B:"meta.llama3-1-70b-instruct-v1:0",Llama3_1_405B:"meta.llama3-1-405b-instruct-v1:0",Mistral7B:"mistral.mistral-7b-instruct-v0:2",Mixtral8x7B:"mistral.mixtral-8x7b-instruct-v0:1",MistralLarge:"mistral.mistral-large-2402-v1:0",StableDiffusionXL:"stability.stable-diffusion-xl-v1"};static ModelGroups={AllClaude:["anthropic.claude-3-5-sonnet-20241022-v2:0","anthropic.claude-3-5-haiku-20241022-v1:0","anthropic.claude-3-opus-20240229-v1:0","anthropic.claude-3-sonnet-20240229-v1:0","anthropic.claude-3-haiku-20240307-v1:0"],AllTitan:["amazon.titan-text-express-v1","amazon.titan-text-lite-v1","amazon.titan-embed-text-v1","amazon.titan-image-generator-v1"],AllLlama:["meta.llama3-2-1b-instruct-v1:0","meta.llama3-2-3b-instruct-v1:0","meta.llama3-2-11b-instruct-v1:0","meta.llama3-2-90b-instruct-v1:0","meta.llama3-1-8b-instruct-v1:0","meta.llama3-1-70b-instruct-v1:0","meta.llama3-1-405b-instruct-v1:0"],TextModels:["anthropic.claude-3-5-sonnet-20241022-v2:0","anthropic.claude-3-5-haiku-20241022-v1:0","amazon.titan-text-express-v1","meta.llama3-2-11b-instruct-v1:0","mistral.mistral-7b-instruct-v0:2"],EmbeddingModels:["amazon.titan-embed-text-v1","cohere.embed-english-v3","cohere.embed-multilingual-v3"],ImageModels:["amazon.titan-image-generator-v1","stability.stable-diffusion-xl-v1"]}}class Bt{static createPostgres(e){return Bt.createRDSInstance("postgres","16.2",e)}static createMysql(e){return Bt.createRDSInstance("mysql","8.0.35",e)}static createRDSInstance(e,a,r){let{slug:n,environment:i,instanceClass:o="db.t3.micro",allocatedStorage:c=20,storageType:u="gp3",masterUsername:d="admin",masterPassword:m,databaseName:p,subnetIds:g,securityGroupIds:h,encrypted:y=!0,kmsKeyId:f,multiAz:b=!1,backupRetentionDays:v=7,publiclyAccessible:w=!1,enableCloudwatchLogs:R=!0,deletionProtection:T=!0}=r,N=l({slug:n,environment:i,resourceType:`${e}-db`}),I=s(N),k,O;if(g&&g.length>0){let _=l({slug:n,environment:i,resourceType:"db-subnet-group"});O=s(_),k={Type:"AWS::RDS::DBSubnetGroup",Properties:{DBSubnetGroupName:_,DBSubnetGroupDescription:`Subnet group for ${N}`,SubnetIds:g,Tags:[{Key:"Name",Value:_},{Key:"Environment",Value:i}]}}}let L={Type:"AWS::RDS::DBInstance",Properties:{DBInstanceIdentifier:N,DBInstanceClass:o,Engine:e,EngineVersion:a,MasterUsername:d,MasterUserPassword:m,AllocatedStorage:c,StorageType:u,StorageEncrypted:y,MultiAZ:b,BackupRetentionPeriod:v,PubliclyAccessible:w,DeletionProtection:T,Tags:[{Key:"Name",Value:N},{Key:"Environment",Value:i}]}};if(p)L.Properties.DBName=p;if(f)L.Properties.KmsKeyId=f;if(O)L.Properties.DBSubnetGroupName=P.Ref(O);if(h&&h.length>0)L.Properties.VPCSecurityGroups=h;if(R)L.Properties.EnableCloudwatchLogsExports=e==="postgres"?["postgresql"]:["error","general","slowquery"];return{dbInstance:L,subnetGroup:k,logicalId:I,subnetGroupId:O}}static createReadReplica(e,a){let{slug:r,environment:n,instanceClass:i="db.t3.micro",securityGroupIds:o,publiclyAccessible:c=!1}=a,u=l({slug:r,environment:n,resourceType:"db-replica"}),d=s(u),m={Type:"AWS::RDS::DBInstance",Properties:{DBInstanceIdentifier:u,DBInstanceClass:i,SourceDBInstanceIdentifier:P.Ref(e),PubliclyAccessible:c,Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:n},{Key:"Type",Value:"ReadReplica"}]}};if(o&&o.length>0)m.Properties.VPCSecurityGroups=o;return{replica:m,logicalId:d}}static createParameterGroup(e,a,r){let{slug:n,environment:i,parameters:o={}}=r,c=l({slug:n,environment:i,resourceType:"db-params"}),u=s(c),d=e==="postgres"?`postgres${a.split(".")[0]}`:`mysql${a.split(".")[0]}.${a.split(".")[1]}`;return{parameterGroup:{Type:"AWS::RDS::DBParameterGroup",Properties:{DBParameterGroupName:c,Description:`Parameter group for ${c}`,Family:d,Parameters:o,Tags:[{Key:"Name",Value:c},{Key:"Environment",Value:i}]}},logicalId:u}}static enableBackup(e,a=7){return e.Properties.BackupRetentionPeriod=a,e}static createTable(e){let{slug:a,environment:r,tableName:n,partitionKey:i,sortKey:o,billingMode:c="PAY_PER_REQUEST",readCapacity:u=5,writeCapacity:d=5,streamEnabled:m=!1,streamViewType:p="NEW_AND_OLD_IMAGES",encrypted:g=!0,kmsKeyId:h,pointInTimeRecovery:y=!0,ttlAttribute:f}=e,b=n||l({slug:a,environment:r,resourceType:"table"}),v=s(b),w=[{AttributeName:i.name,AttributeType:i.type}];if(o)w.push({AttributeName:o.name,AttributeType:o.type});let R=[{AttributeName:i.name,KeyType:"HASH"}];if(o)R.push({AttributeName:o.name,KeyType:"RANGE"});let T={Type:"AWS::DynamoDB::Table",Properties:{TableName:b,BillingMode:c,AttributeDefinitions:w,KeySchema:R,Tags:[{Key:"Name",Value:b},{Key:"Environment",Value:r}]}};if(c==="PROVISIONED")T.Properties.ProvisionedThroughput={ReadCapacityUnits:u,WriteCapacityUnits:d};if(m)T.Properties.StreamSpecification={StreamViewType:p};if(g)T.Properties.SSESpecification={SSEEnabled:!0,SSEType:h?"KMS":"AES256",KMSMasterKeyId:h};if(y)T.Properties.PointInTimeRecoverySpecification={PointInTimeRecoveryEnabled:!0};if(f)T.Properties.TimeToLiveSpecification={AttributeName:f,Enabled:!0};return{table:T,logicalId:v}}static addGlobalSecondaryIndex(e,a){let{indexName:r,partitionKey:n,sortKey:i,projectionType:o="ALL",nonKeyAttributes:c,readCapacity:u=5,writeCapacity:d=5}=a;if(!e.Properties.AttributeDefinitions.some((g)=>g.AttributeName===n.name))e.Properties.AttributeDefinitions.push({AttributeName:n.name,AttributeType:n.type});if(i&&!e.Properties.AttributeDefinitions.some((g)=>g.AttributeName===i.name))e.Properties.AttributeDefinitions.push({AttributeName:i.name,AttributeType:i.type});let m=[{AttributeName:n.name,KeyType:"HASH"}];if(i)m.push({AttributeName:i.name,KeyType:"RANGE"});let p={IndexName:r,KeySchema:m,Projection:{ProjectionType:o,NonKeyAttributes:o==="INCLUDE"?c:void 0},ProvisionedThroughput:void 0};if(e.Properties.BillingMode==="PROVISIONED")p.ProvisionedThroughput={ReadCapacityUnits:u,WriteCapacityUnits:d};if(!e.Properties.GlobalSecondaryIndexes)e.Properties.GlobalSecondaryIndexes=[];return e.Properties.GlobalSecondaryIndexes.push(p),e}static enableStreams(e,a="NEW_AND_OLD_IMAGES"){return e.Properties.StreamSpecification={StreamViewType:a},e}static InstanceClasses={T3_Micro:"db.t3.micro",T3_Small:"db.t3.small",T3_Medium:"db.t3.medium",T3_Large:"db.t3.large",T4g_Micro:"db.t4g.micro",T4g_Small:"db.t4g.small",T4g_Medium:"db.t4g.medium",M5_Large:"db.m5.large",M5_XLarge:"db.m5.xlarge",M5_2XLarge:"db.m5.2xlarge",R5_Large:"db.r5.large",R5_XLarge:"db.r5.xlarge",R5_2XLarge:"db.r5.2xlarge"}}class mi{static createRedis(e){let{slug:a,environment:r,nodeType:n="cache.t3.micro",engineVersion:i="7.1",port:o=6379,subnetIds:c,securityGroupIds:u,numCacheClusters:d=2,automaticFailover:m=!0,multiAz:p=!0,clusterMode:g=!1,numNodeGroups:h=1,replicasPerNodeGroup:y=1,atRestEncryption:f=!0,transitEncryption:b=!0,authToken:v,kmsKeyId:w,snapshotRetentionDays:R=7,snapshotWindow:T,maintenanceWindow:N}=e,I=l({slug:a,environment:r,resourceType:"redis"}),k=s(I),O,L;if(c&&c.length>0){let W=l({slug:a,environment:r,resourceType:"cache-subnet-group"});L=s(W),O={Type:"AWS::ElastiCache::SubnetGroup",Properties:{CacheSubnetGroupName:W,Description:`Subnet group for ${I}`,SubnetIds:c,Tags:[{Key:"Name",Value:W},{Key:"Environment",Value:r}]}}}let _={Type:"AWS::ElastiCache::ReplicationGroup",Properties:{ReplicationGroupId:I,ReplicationGroupDescription:`Redis cluster for ${a} ${r}`,Engine:"redis",EngineVersion:i,CacheNodeType:n,Port:o,AutomaticFailoverEnabled:m,MultiAZEnabled:p,AtRestEncryptionEnabled:f,TransitEncryptionEnabled:b,SnapshotRetentionLimit:R,AutoMinorVersionUpgrade:!0,Tags:[{Key:"Name",Value:I},{Key:"Environment",Value:r}]}};if(g)_.Properties.NumNodeGroups=h,_.Properties.ReplicasPerNodeGroup=y;else _.Properties.NumCacheClusters=d;if(v)_.Properties.AuthToken=v;if(w)_.Properties.KmsKeyId=w;if(L)_.Properties.CacheSubnetGroupName=P.Ref(L);if(u&&u.length>0)_.Properties.SecurityGroupIds=u;if(T)_.Properties.SnapshotWindow=T;if(N)_.Properties.PreferredMaintenanceWindow=N;return{replicationGroup:_,subnetGroup:O,logicalId:k,subnetGroupId:L}}static createMemcached(e){let{slug:a,environment:r,nodeType:n="cache.t3.micro",engineVersion:i="1.6.22",port:o=11211,numCacheNodes:c=2,subnetIds:u,securityGroupIds:d,azMode:m="cross-az",preferredAzs:p,maintenanceWindow:g}=e,h=l({slug:a,environment:r,resourceType:"memcached"}),y=s(h),f,b;if(u&&u.length>0){let w=l({slug:a,environment:r,resourceType:"cache-subnet-group"});b=s(w),f={Type:"AWS::ElastiCache::SubnetGroup",Properties:{CacheSubnetGroupName:w,Description:`Subnet group for ${h}`,SubnetIds:u,Tags:[{Key:"Name",Value:w},{Key:"Environment",Value:r}]}}}let v={Type:"AWS::ElastiCache::CacheCluster",Properties:{ClusterName:h,CacheNodeType:n,Engine:"memcached",EngineVersion:i,NumCacheNodes:c,Port:o,AZMode:m,AutoMinorVersionUpgrade:!0,Tags:[{Key:"Name",Value:h},{Key:"Environment",Value:r}]}};if(b)v.Properties.CacheSubnetGroupName=P.Ref(b);if(d&&d.length>0)v.Properties.VpcSecurityGroupIds=d;if(p&&p.length>0)v.Properties.PreferredAvailabilityZones=p;if(g)v.Properties.PreferredMaintenanceWindow=g;return{cluster:v,subnetGroup:f,logicalId:y,subnetGroupId:b}}static enableClusterMode(e,a=3,r=2){return delete e.Properties.NumCacheClusters,e.Properties.NumNodeGroups=a,e.Properties.ReplicasPerNodeGroup=r,e}static createRedisParameterGroup(e,a){let{slug:r,environment:n,parameters:i={}}=a,o=l({slug:r,environment:n,resourceType:"redis-params"}),c=s(o);return{parameterGroup:{Type:"AWS::ElastiCache::ParameterGroup",Properties:{CacheParameterGroupFamily:`redis${e.split(".")[0]}.x`,Description:`Parameter group for ${o}`,Properties:i,Tags:[{Key:"Name",Value:o},{Key:"Environment",Value:n}]}},logicalId:c}}static createMemcachedParameterGroup(e,a){let{slug:r,environment:n,parameters:i={}}=a,o=l({slug:r,environment:n,resourceType:"memcached-params"}),c=s(o);return{parameterGroup:{Type:"AWS::ElastiCache::ParameterGroup",Properties:{CacheParameterGroupFamily:`memcached${e.split(".")[0]}.${e.split(".")[1]}`,Description:`Parameter group for ${o}`,Properties:i,Tags:[{Key:"Name",Value:o},{Key:"Environment",Value:n}]}},logicalId:c}}static NodeTypes={T3_Micro:"cache.t3.micro",T3_Small:"cache.t3.small",T3_Medium:"cache.t3.medium",T4g_Micro:"cache.t4g.micro",T4g_Small:"cache.t4g.small",T4g_Medium:"cache.t4g.medium",M5_Large:"cache.m5.large",M5_XLarge:"cache.m5.xlarge",M5_2XLarge:"cache.m5.2xlarge",R5_Large:"cache.r5.large",R5_XLarge:"cache.r5.xlarge",R5_2XLarge:"cache.r5.2xlarge",R5_4XLarge:"cache.r5.4xlarge",R6g_Large:"cache.r6g.large",R6g_XLarge:"cache.r6g.xlarge",R6g_2XLarge:"cache.r6g.2xlarge"}}class ve{static createUser(e){let{slug:a,environment:r,userName:n,groups:i,managedPolicyArns:o}=e,c=n||l({slug:a,environment:r,resourceType:"user"}),u=s(c),d={Type:"AWS::IAM::User",Properties:{UserName:c,Tags:[{Key:"Name",Value:c},{Key:"Environment",Value:r}]}};if(i&&i.length>0)d.Properties.Groups=i;if(o&&o.length>0)d.Properties.ManagedPolicyArns=o;return{user:d,logicalId:u}}static createRole(e){let{slug:a,environment:r,roleName:n,servicePrincipal:i,awsPrincipal:o,managedPolicyArns:c}=e,u=n||l({slug:a,environment:r,resourceType:"role"}),d=s(u),m={};if(i)m.Service=i;if(o)m.AWS=o;let p={Type:"AWS::IAM::Role",Properties:{RoleName:u,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:m,Action:"sts:AssumeRole"}]},Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:r}]}};if(c&&c.length>0)p.Properties.ManagedPolicyArns=c;return{role:p,logicalId:d}}static createGroup(e){let{slug:a,environment:r,groupName:n,managedPolicyArns:i}=e,o=n||l({slug:a,environment:r,resourceType:"group"}),c=s(o),u={Type:"AWS::IAM::Group",Properties:{GroupName:o}};if(i&&i.length>0)u.Properties.ManagedPolicyArns=i;return{group:u,logicalId:c}}static createPolicy(e){let{slug:a,environment:r,policyName:n,description:i,statements:o}=e,c=n||l({slug:a,environment:r,resourceType:"policy"}),u=s(c),d=o.map((m)=>({Sid:m.sid,Effect:m.effect||"Allow",Action:m.actions,Resource:m.resources,Condition:m.conditions}));return{policy:{Type:"AWS::IAM::ManagedPolicy",Properties:{ManagedPolicyName:c,Description:i||`Managed policy for ${c}`,PolicyDocument:{Version:"2012-10-17",Statement:d}}},logicalId:u}}static attachPolicyToRole(e,a){if(!e.Properties.ManagedPolicyArns)e.Properties.ManagedPolicyArns=[];if(!e.Properties.ManagedPolicyArns.includes(a))e.Properties.ManagedPolicyArns.push(a);return e}static attachPolicyToUser(e,a){if(!e.Properties.ManagedPolicyArns)e.Properties.ManagedPolicyArns=[];if(!e.Properties.ManagedPolicyArns.includes(a))e.Properties.ManagedPolicyArns.push(a);return e}static attachPolicyToGroup(e,a){if(!e.Properties.ManagedPolicyArns)e.Properties.ManagedPolicyArns=[];if(!e.Properties.ManagedPolicyArns.includes(a))e.Properties.ManagedPolicyArns.push(a);return e}static addInlinePolicyToRole(e,a,r){if(!e.Properties.Policies)e.Properties.Policies=[];let n=r.map((i)=>({Effect:i.effect||"Allow",Action:i.actions,Resource:i.resources}));return e.Properties.Policies.push({PolicyName:a,PolicyDocument:{Version:"2012-10-17",Statement:n}}),e}static addInlinePolicyToUser(e,a,r){if(!e.Properties.Policies)e.Properties.Policies=[];let n=r.map((i)=>({Effect:i.effect||"Allow",Action:i.actions,Resource:i.resources}));return e.Properties.Policies.push({PolicyName:a,PolicyDocument:{Version:"2012-10-17",Statement:n}}),e}static createAccessKey(e,a){let{slug:r,environment:n,status:i="Active"}=a,o=l({slug:r,environment:n,resourceType:"access-key"}),c=s(o);return{accessKey:{Type:"AWS::IAM::AccessKey",Properties:{UserName:P.Ref(e),Status:i}},logicalId:c}}static createInstanceProfile(e,a){let{slug:r,environment:n,profileName:i}=a,o=i||l({slug:r,environment:n,resourceType:"instance-profile"}),c=s(o);return{instanceProfile:{Type:"AWS::IAM::InstanceProfile",Properties:{InstanceProfileName:o,Roles:[P.Ref(e)]}},logicalId:c}}static ManagedPolicies={AdministratorAccess:"arn:aws:iam::aws:policy/AdministratorAccess",PowerUserAccess:"arn:aws:iam::aws:policy/PowerUserAccess",ReadOnlyAccess:"arn:aws:iam::aws:policy/ReadOnlyAccess",S3FullAccess:"arn:aws:iam::aws:policy/AmazonS3FullAccess",S3ReadOnlyAccess:"arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess",DynamoDBFullAccess:"arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess",DynamoDBReadOnlyAccess:"arn:aws:iam::aws:policy/AmazonDynamoDBReadOnlyAccess",RDSFullAccess:"arn:aws:iam::aws:policy/AmazonRDSFullAccess",RDSReadOnlyAccess:"arn:aws:iam::aws:policy/AmazonRDSReadOnlyAccess",LambdaFullAccess:"arn:aws:iam::aws:policy/AWSLambda_FullAccess",LambdaReadOnlyAccess:"arn:aws:iam::aws:policy/AWSLambda_ReadOnlyAccess",LambdaBasicExecutionRole:"arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole",LambdaVPCAccessExecutionRole:"arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole",EC2FullAccess:"arn:aws:iam::aws:policy/AmazonEC2FullAccess",EC2ReadOnlyAccess:"arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess",EC2ContainerRegistryReadOnly:"arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly",EC2ContainerRegistryPowerUser:"arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryPowerUser",ECSTaskExecutionRole:"arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy",ECSFullAccess:"arn:aws:iam::aws:policy/AmazonECS_FullAccess",CloudWatchFullAccess:"arn:aws:iam::aws:policy/CloudWatchFullAccess",CloudWatchLogsFullAccess:"arn:aws:iam::aws:policy/CloudWatchLogsFullAccess",SESFullAccess:"arn:aws:iam::aws:policy/AmazonSESFullAccess",SNSFullAccess:"arn:aws:iam::aws:policy/AmazonSNSFullAccess",SQSFullAccess:"arn:aws:iam::aws:policy/AmazonSQSFullAccess",SecretsManagerReadWrite:"arn:aws:iam::aws:policy/SecretsManagerReadWrite"};static ServicePrincipals={Lambda:"lambda.amazonaws.com",EC2:"ec2.amazonaws.com",ECS:"ecs.amazonaws.com",ECSTaskExecution:"ecs-tasks.amazonaws.com",APIGateway:"apigateway.amazonaws.com",Events:"events.amazonaws.com",States:"states.amazonaws.com",CodeBuild:"codebuild.amazonaws.com",CodeDeploy:"codedeploy.amazonaws.com",CloudFormation:"cloudformation.amazonaws.com"};static createCiCdUser(e){let{slug:a,environment:r,permissions:n,createAccessKey:i=!0}=e,o={},c=[];if(n.s3Buckets&&n.s3Buckets.length>0)c.push({sid:"S3Access",actions:["s3:GetBucketLocation","s3:ListBucket","s3:GetObject","s3:PutObject","s3:DeleteObject","s3:ListBucketMultipartUploads","s3:AbortMultipartUpload"],resources:[...n.s3Buckets,...n.s3Buckets.map((y)=>`${y}/*`)]});if(n.cloudFrontDistributions&&n.cloudFrontDistributions.length>0)c.push({sid:"CloudFrontAccess",actions:["cloudfront:CreateInvalidation","cloudfront:GetInvalidation","cloudfront:ListInvalidations","cloudfront:GetDistribution"],resources:n.cloudFrontDistributions});if(n.ecrRepositories&&n.ecrRepositories.length>0)c.push({sid:"ECRAccess",actions:["ecr:GetAuthorizationToken","ecr:BatchCheckLayerAvailability","ecr:GetDownloadUrlForLayer","ecr:GetRepositoryPolicy","ecr:DescribeRepositories","ecr:ListImages","ecr:DescribeImages","ecr:BatchGetImage","ecr:InitiateLayerUpload","ecr:UploadLayerPart","ecr:CompleteLayerUpload","ecr:PutImage"],resources:n.ecrRepositories}),c.push({sid:"ECRLogin",actions:["ecr:GetAuthorizationToken"],resources:"*"});if(n.ecsServices&&n.ecsServices.length>0)c.push({sid:"ECSAccess",actions:["ecs:DescribeServices","ecs:DescribeTaskDefinition","ecs:DescribeTasks","ecs:ListTasks","ecs:RegisterTaskDefinition","ecs:UpdateService","ecs:RunTask","ecs:StopTask"],resources:n.ecsServices}),c.push({sid:"ECSTaskDefinitions",actions:["ecs:RegisterTaskDefinition","ecs:DeregisterTaskDefinition"],resources:"*"}),c.push({sid:"ECSPassRole",actions:["iam:PassRole"],resources:"*",conditions:{StringLike:{"iam:PassedToService":"ecs-tasks.amazonaws.com"}}});if(n.cloudFormationStacks&&n.cloudFormationStacks.length>0)c.push({sid:"CloudFormationAccess",actions:["cloudformation:CreateStack","cloudformation:UpdateStack","cloudformation:DeleteStack","cloudformation:DescribeStacks","cloudformation:DescribeStackEvents","cloudformation:DescribeStackResources","cloudformation:GetTemplate","cloudformation:ListStackResources","cloudformation:ValidateTemplate"],resources:n.cloudFormationStacks});if(n.lambdaFunctions&&n.lambdaFunctions.length>0)c.push({sid:"LambdaAccess",actions:["lambda:GetFunction","lambda:UpdateFunctionCode","lambda:UpdateFunctionConfiguration","lambda:PublishVersion","lambda:UpdateAlias","lambda:CreateAlias"],resources:n.lambdaFunctions});if(n.secretsManagerSecrets&&n.secretsManagerSecrets.length>0)c.push({sid:"SecretsManagerAccess",actions:["secretsmanager:GetSecretValue","secretsmanager:DescribeSecret"],resources:n.secretsManagerSecrets});let{policy:u,logicalId:d}=ve.createPolicy({slug:a,environment:r,policyName:l({slug:a,environment:r,resourceType:"cicd-policy"}),description:`CI/CD deployment policy for ${a} (${r})`,statements:c});o[d]=u;let{user:m,logicalId:p}=ve.createUser({slug:a,environment:r,userName:l({slug:a,environment:r,resourceType:"cicd-user"}),managedPolicyArns:[P.Ref(d)]});o[p]=m;let g,h;if(i){let y=ve.createAccessKey(p,{slug:a,environment:r});g=y.accessKey,h=y.logicalId,o[h]=g}return{user:m,accessKey:g,policy:u,userLogicalId:p,accessKeyLogicalId:h,policyLogicalId:d,resources:o}}static createCrossAccountRole(e){let{slug:a,environment:r,trustedAccountIds:n,externalId:i,permissions:o,maxSessionDuration:c=3600}=e,u={},{policy:d,logicalId:m}=ve.createPolicy({slug:a,environment:r,policyName:l({slug:a,environment:r,resourceType:"cross-account-policy"}),description:`Cross-account access policy for ${a} (${r})`,statements:o});u[m]=d;let p=l({slug:a,environment:r,resourceType:"cross-account-role"}),g=s(p),h={};if(i)h.StringEquals={"sts:ExternalId":i};let y={Type:"AWS::IAM::Role",Properties:{RoleName:p,MaxSessionDuration:c,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:n.map((f)=>`arn:aws:iam::${f}:root`)},Action:"sts:AssumeRole",...Object.keys(h).length>0?{Condition:h}:{}}]},ManagedPolicyArns:[P.Ref(m)],Tags:[{Key:"Name",Value:p},{Key:"Environment",Value:r},{Key:"Purpose",Value:"Cross-Account Access"}]}};return u[g]=y,{role:y,policy:d,roleLogicalId:g,policyLogicalId:m,resources:u}}static createCliUser(e){let{slug:a,environment:r,permissions:n="readonly"}=e,i={},o=[],c=[];switch(n){case"readonly":c=[ve.ManagedPolicies.ReadOnlyAccess];break;case"deploy":o=[{sid:"S3Deploy",actions:["s3:*"],resources:"*"},{sid:"CloudFrontDeploy",actions:["cloudfront:*"],resources:"*"},{sid:"ECSDeploy",actions:["ecs:*"],resources:"*"},{sid:"ECRDeploy",actions:["ecr:*"],resources:"*"},{sid:"LambdaDeploy",actions:["lambda:*"],resources:"*"},{sid:"CloudFormationDeploy",actions:["cloudformation:*"],resources:"*"},{sid:"IAMPassRole",actions:["iam:PassRole"],resources:"*"}];break;case"admin":c=[ve.ManagedPolicies.AdministratorAccess];break}let u,d;if(o.length>0){let y=ve.createPolicy({slug:a,environment:r,policyName:l({slug:a,environment:r,resourceType:"cli-policy"}),description:`CLI access policy for ${a} (${r})`,statements:o});u=y.policy,d=y.logicalId,i[d]=u,c=[P.Ref(d)]}let{user:m,logicalId:p}=ve.createUser({slug:a,environment:r,userName:l({slug:a,environment:r,resourceType:"cli-user"}),managedPolicyArns:c});i[p]=m;let{accessKey:g,logicalId:h}=ve.createAccessKey(p,{slug:a,environment:r});return i[h]=g,{user:m,accessKey:g,policy:u,userLogicalId:p,accessKeyLogicalId:h,policyLogicalId:d,resources:i}}static CiCdPolicies={s3Deployment:(e)=>[{sid:"S3ListBuckets",actions:["s3:ListBucket","s3:GetBucketLocation"],resources:e},{sid:"S3Objects",actions:["s3:GetObject","s3:PutObject","s3:DeleteObject"],resources:e.map((a)=>`${a}/*`)}],cloudFrontInvalidation:(e)=>[{sid:"CloudFrontInvalidation",actions:["cloudfront:CreateInvalidation","cloudfront:GetInvalidation","cloudfront:ListInvalidations"],resources:e}],ecsDeployment:()=>[{sid:"ECSServices",actions:["ecs:DescribeServices","ecs:UpdateService","ecs:DescribeTaskDefinition","ecs:RegisterTaskDefinition"],resources:"*"},{sid:"ECSPassRole",actions:["iam:PassRole"],resources:"*",conditions:{StringLike:{"iam:PassedToService":"ecs-tasks.amazonaws.com"}}}],ecrPush:(e)=>[{sid:"ECRAuth",actions:["ecr:GetAuthorizationToken"],resources:"*"},{sid:"ECRPush",actions:["ecr:BatchCheckLayerAvailability","ecr:GetDownloadUrlForLayer","ecr:BatchGetImage","ecr:InitiateLayerUpload","ecr:UploadLayerPart","ecr:CompleteLayerUpload","ecr:PutImage"],resources:e}],lambdaDeployment:(e)=>[{sid:"LambdaDeploy",actions:["lambda:GetFunction","lambda:UpdateFunctionCode","lambda:UpdateFunctionConfiguration","lambda:PublishVersion"],resources:e}],cloudFormationDeployment:(e)=>[{sid:"CloudFormationDeploy",actions:["cloudformation:CreateStack","cloudformation:UpdateStack","cloudformation:DescribeStacks","cloudformation:DescribeStackEvents","cloudformation:GetTemplate"],resources:e}]}}class wo{static createRestApi(e){let{slug:a,environment:r,name:n,description:i,endpointType:o="REGIONAL",binaryMediaTypes:c,compressionSize:u}=e,d=n||l({slug:a,environment:r,resourceType:"rest-api"}),m=s(d),p={Type:"AWS::ApiGateway::RestApi",Properties:{Name:d,Description:i||`REST API for ${a} ${r}`,EndpointConfiguration:{Types:[o]},Tags:[{Key:"Name",Value:d},{Key:"Environment",Value:r}]}};if(c&&c.length>0)p.Properties.BinaryMediaTypes=c;if(u!==void 0)p.Properties.MinimumCompressionSize=u;return{restApi:p,logicalId:m}}static createHttpApi(e){let{slug:a,environment:r,name:n,description:i,corsEnabled:o=!0,corsOrigins:c=["*"],corsMethods:u=["GET","POST","PUT","PATCH","DELETE","OPTIONS"],corsHeaders:d=["*"],corsMaxAge:m=86400,corsAllowCredentials:p=!1}=e,g=n||l({slug:a,environment:r,resourceType:"http-api"}),h=s(g),y={Type:"AWS::ApiGatewayV2::Api",Properties:{Name:g,Description:i||`HTTP API for ${a} ${r}`,ProtocolType:"HTTP",Tags:{Name:g,Environment:r}}};if(o)y.Properties.CorsConfiguration={AllowOrigins:c,AllowMethods:u,AllowHeaders:d,MaxAge:m,AllowCredentials:p};return{httpApi:y,logicalId:h}}static createWebSocketApi(e){let{slug:a,environment:r,name:n,description:i}=e,o=n||l({slug:a,environment:r,resourceType:"ws-api"}),c=s(o);return{webSocketApi:{Type:"AWS::ApiGatewayV2::Api",Properties:{Name:o,Description:i||`WebSocket API for ${a} ${r}`,ProtocolType:"WEBSOCKET",Tags:{Name:o,Environment:r}}},logicalId:c}}static createDeployment(e,a){let{slug:r,environment:n,description:i}=a,o=l({slug:r,environment:n,resourceType:"api-deployment"}),c=s(o);return{deployment:{Type:"AWS::ApiGateway::Deployment",Properties:{RestApiId:P.Ref(e),Description:i||`Deployment for ${o}`}},logicalId:c}}static createStage(e,a,r){let{slug:n,environment:i,stageName:o,description:c,cacheEnabled:u=!1,cacheSize:d="0.5",variables:m,throttling:p}=r,g=l({slug:n,environment:i,resourceType:"api-stage"}),h=s(g),y={Type:"AWS::ApiGateway::Stage",Properties:{StageName:o||i,RestApiId:P.Ref(e),DeploymentId:P.Ref(a),Description:c,CacheClusterEnabled:u,Tags:[{Key:"Name",Value:g},{Key:"Environment",Value:i}]}};if(u)y.Properties.CacheClusterSize=d;if(m)y.Properties.Variables=m;if(p)y.Properties.MethodSettings=[{HttpMethod:"*",ResourcePath:"/*",ThrottlingBurstLimit:p.burstLimit,ThrottlingRateLimit:p.rateLimit}];return{stage:y,logicalId:h}}static createAuthorizer(e,a){let{slug:r,environment:n,name:i,type:o,functionArn:c,identitySource:u,userPoolArns:d,ttl:m=300}=a,p=i||l({slug:r,environment:n,resourceType:"api-authorizer"}),g=s(p),h={Type:"AWS::ApiGateway::Authorizer",Properties:{Name:p,Type:o,RestApiId:P.Ref(e),AuthorizerResultTtlInSeconds:m}};if(o==="TOKEN"||o==="REQUEST"){if(!c)throw Error("Lambda authorizer requires functionArn");h.Properties.AuthorizerUri=c,h.Properties.IdentitySource=u||"method.request.header.Authorization"}if(o==="COGNITO_USER_POOLS"){if(!d||d.length===0)throw Error("Cognito authorizer requires userPoolArns");h.Properties.ProviderARNs=d,h.Properties.IdentitySource=u||"method.request.header.Authorization"}return{authorizer:h,logicalId:g}}static setCors(e,a={}){let{origins:r=["*"],methods:n=["GET","POST","PUT","PATCH","DELETE","OPTIONS"],headers:i=["*"],maxAge:o=86400,allowCredentials:c=!1}=a;return e.Properties.CorsConfiguration={AllowOrigins:r,AllowMethods:n,AllowHeaders:i,MaxAge:o,AllowCredentials:c},e}static addThrottling(e,a=5000,r=1e4){if(!e.Properties.MethodSettings)e.Properties.MethodSettings=[];return e.Properties.MethodSettings.push({HttpMethod:"*",ResourcePath:"/*",ThrottlingBurstLimit:a,ThrottlingRateLimit:r}),e}static enableCaching(e,a="0.5",r=300){if(e.Properties.CacheClusterEnabled=!0,e.Properties.CacheClusterSize=a,!e.Properties.MethodSettings)e.Properties.MethodSettings=[];return e.Properties.MethodSettings.push({HttpMethod:"*",ResourcePath:"/*",CachingEnabled:!0,CacheTtlInSeconds:r}),e}static CacheSizes={Small:"0.5",Medium:"1.6",Large:"6.1",XLarge:"13.5",XXLarge:"28.4",XXXLarge:"58.2",Huge:"118",Massive:"237"};static ThrottlingPresets={Light:{burstLimit:100,rateLimit:50},Medium:{burstLimit:500,rateLimit:250},Heavy:{burstLimit:2000,rateLimit:1000},Default:{burstLimit:5000,rateLimit:1e4}}}class Ne{static createTopic(e){let{slug:a,environment:r,topicName:n,displayName:i,encrypted:o=!1,kmsKeyId:c}=e,u=n||l({slug:a,environment:r,resourceType:"topic"}),d=s(u),m={Type:"AWS::SNS::Topic",Properties:{TopicName:u,DisplayName:i||u,Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:r}]}};if(o&&c)m.Properties.KmsMasterKeyId=c;return{topic:m,logicalId:d}}static subscribe(e,a){let{slug:r,environment:n,protocol:i,endpoint:o,filterPolicy:c,rawMessageDelivery:u=!1}=a,d=l({slug:r,environment:n,resourceType:"subscription"}),m=o.replace(/[^a-zA-Z0-9]/g,""),p=m.length>12?m.slice(-12):m,g=s(`${d}-${i}-${p}`),h={Type:"AWS::SNS::Subscription",Properties:{TopicArn:P.Ref(e),Protocol:i,Endpoint:o,RawMessageDelivery:u}};if(c)h.Properties.FilterPolicy=c;return{subscription:h,logicalId:g}}static subscribeEmail(e,a,r){return Ne.subscribe(e,{...r,protocol:"email",endpoint:a})}static subscribeLambda(e,a,r){return Ne.subscribe(e,{...r,protocol:"lambda",endpoint:a,rawMessageDelivery:!0})}static subscribeSqs(e,a,r){return Ne.subscribe(e,{...r,protocol:"sqs",endpoint:a})}static subscribeHttp(e,a,r){let n=a.startsWith("https://")?"https":"http";return Ne.subscribe(e,{...r,protocol:n,endpoint:a})}static subscribeSms(e,a,r){return Ne.subscribe(e,{...r,protocol:"sms",endpoint:a})}static setTopicPolicy(e,a){let{slug:r,environment:n,allowedPrincipals:i,allowedServices:o,actions:c="SNS:Publish"}=a,u=l({slug:r,environment:n,resourceType:"topic-policy"}),d=s(u),m={};if(i)m.AWS=i;if(o)m.Service=o;return{policy:{Type:"AWS::SNS::TopicPolicy",Properties:{Topics:[P.Ref(e)],PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:m,Action:c,Resource:P.Ref(e)}]}}},logicalId:d}}static allowCloudWatchAlarms(e,a){return Ne.setTopicPolicy(e,{...a,allowedServices:"cloudwatch.amazonaws.com",actions:"SNS:Publish"})}static allowEventBridge(e,a){return Ne.setTopicPolicy(e,{...a,allowedServices:"events.amazonaws.com",actions:"SNS:Publish"})}static allowS3(e,a){return Ne.setTopicPolicy(e,{...a,allowedServices:"s3.amazonaws.com",actions:"SNS:Publish"})}static enableEncryption(e,a){if(!e.Properties)e.Properties={};return e.Properties.KmsMasterKeyId=a,e}static addInlineSubscription(e,a,r){if(!e.Properties)e.Properties={};if(!e.Properties.Subscription)e.Properties.Subscription=[];return e.Properties.Subscription.push({Protocol:a,Endpoint:r}),e}static FilterPolicies={eventType:(e)=>({eventType:e}),status:(e)=>({status:e}),numericRange:(e,a,r)=>({[e]:[{numeric:[">=",a,"<=",r]}]}),prefix:(e,a)=>({[e]:[{prefix:a}]}),and:(...e)=>Object.assign({},...e),exists:(e,a)=>({[e]:[{exists:a}]})};static UseCases={createAlertTopic:(e)=>Ne.createTopic({...e,topicName:e.topicName||`${e.slug}-${e.environment}-alerts`,displayName:e.displayName||"Alert Notifications"}),createEventFanout:(e)=>Ne.createTopic({...e,topicName:e.topicName||`${e.slug}-${e.environment}-events`,displayName:e.displayName||"Event Fanout"}),createNotificationTopic:(e)=>Ne.createTopic({...e,topicName:e.topicName||`${e.slug}-${e.environment}-notifications`,displayName:e.displayName||"User Notifications"})}}class gd{static createStateMachine(e){let{slug:a,environment:r,stateMachineName:n,type:i="STANDARD",definition:o,roleArn:c,loggingConfiguration:u,tracingConfiguration:d}=e,m=n||l({slug:a,environment:r,resourceType:"state-machine"}),p=s(m),g,h,y;if(c)y=c;else{let b=l({slug:a,environment:r,resourceType:"state-machine-role"});h=s(b),g={Type:"AWS::IAM::Role",Properties:{RoleName:b,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"states.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/CloudWatchLogsFullAccess"],Tags:[{Key:"Name",Value:b},{Key:"Environment",Value:r}]}},y=P.GetAtt(h,"Arn")}let f={Type:"AWS::StepFunctions::StateMachine",Properties:{StateMachineName:m,StateMachineType:i,DefinitionString:JSON.stringify(o),RoleArn:y,Tags:[{Key:"Name",Value:m},{Key:"Environment",Value:r}]}};if(u)f.Properties.LoggingConfiguration={Level:u.level,IncludeExecutionData:u.includeExecutionData,Destinations:u.destinations?.map((b)=>({CloudWatchLogsLogGroup:{LogGroupArn:b}}))};if(d)f.Properties.TracingConfiguration={Enabled:d.enabled};return{stateMachine:f,logicalId:p,role:g,roleLogicalId:h}}static createLambdaTask(e,a){return{Type:"Task",Resource:"arn:aws:states:::lambda:invoke",Parameters:{FunctionName:e,Payload:a?.parameters||{"Input.$":"$"}},ResultPath:a?.resultPath,Retry:a?.retry,Catch:a?.catch,Next:a?.next,End:a?.end}}static createDynamoDBTask(e,a,r,n){return{Type:"Task",Resource:{GetItem:"arn:aws:states:::dynamodb:getItem",PutItem:"arn:aws:states:::dynamodb:putItem",UpdateItem:"arn:aws:states:::dynamodb:updateItem",DeleteItem:"arn:aws:states:::dynamodb:deleteItem"}[e],Parameters:{TableName:a,...r},ResultPath:n?.resultPath,Retry:n?.retry,Catch:n?.catch,Next:n?.next,End:n?.end}}static createSNSPublishTask(e,a,r){return{Type:"Task",Resource:"arn:aws:states:::sns:publish",Parameters:{TopicArn:e,Message:a},ResultPath:r?.resultPath,Retry:r?.retry,Catch:r?.catch,Next:r?.next,End:r?.end}}static createSQSSendMessageTask(e,a,r){return{Type:"Task",Resource:"arn:aws:states:::sqs:sendMessage",Parameters:{QueueUrl:e,MessageBody:a},ResultPath:r?.resultPath,Retry:r?.retry,Catch:r?.catch,Next:r?.next,End:r?.end}}static createPassState(e){return{Type:"Pass",Result:e?.result,ResultPath:e?.resultPath,Parameters:e?.parameters,Next:e?.next,End:e?.end}}static createWaitState(e){return{Type:"Wait",Seconds:e.seconds,Timestamp:e.timestamp,SecondsPath:e.secondsPath,TimestampPath:e.timestampPath,Next:e.next,End:e.end}}static createChoiceState(e,a){return{Type:"Choice",Choices:e,Default:a}}static createParallelState(e,a){return{Type:"Parallel",Branches:e,ResultPath:a?.resultPath,Retry:a?.retry,Catch:a?.catch,Next:a?.next,End:a?.end}}static createMapState(e,a){return{Type:"Map",ItemsPath:a?.itemsPath||"$.items",Iterator:e,MaxConcurrency:a?.maxConcurrency,ResultPath:a?.resultPath,Retry:a?.retry,Catch:a?.catch,Next:a?.next,End:a?.end}}static createSucceedState(){return{Type:"Succeed"}}static createFailState(e,a){return{Type:"Fail",Error:e,Cause:a}}static RetryPolicies={standard:()=>({ErrorEquals:["States.ALL"],IntervalSeconds:2,MaxAttempts:3,BackoffRate:2}),aggressive:()=>({ErrorEquals:["States.TaskFailed","States.Timeout"],IntervalSeconds:1,MaxAttempts:5,BackoffRate:1.5}),custom:(e,a,r,n)=>({ErrorEquals:e,IntervalSeconds:a,MaxAttempts:r,BackoffRate:n})};static CatchPolicies={all:(e,a)=>({ErrorEquals:["States.ALL"],Next:e,ResultPath:a||"$.error"}),specific:(e,a,r)=>({ErrorEquals:e,Next:a,ResultPath:r||"$.error"})};static Patterns={sequential:(e,a,r)=>{let n={};return r.forEach((i,o)=>{let c=o===r.length-1;n[i.name]={...i.state,Next:c?void 0:r[o+1].name,End:c}}),{Comment:"Sequential workflow",StartAt:r[0].name,States:n}},fanout:(e,a,r)=>({Comment:"Fan-out workflow",StartAt:"Parallel",States:{Parallel:{Type:"Parallel",Branches:r.map((n)=>n.definition),End:!0}}}),map:(e,a,r,n)=>({Comment:"Map workflow",StartAt:"Map",States:{Map:{Type:"Map",ItemsPath:"$.items",Iterator:r,MaxConcurrency:n,End:!0}}}),withErrorHandling:(e,a,r,n)=>({Comment:"Workflow with error handling",StartAt:"Main",States:{Main:{...r,Catch:[{ErrorEquals:["States.ALL"],Next:"ErrorHandler"}],Next:"Success"},ErrorHandler:n,Success:{Type:"Succeed"}}})}}class gi{static createAlarm(e){let{slug:a,environment:r,alarmName:n,metricName:i,namespace:o,statistic:c="Average",period:u=300,evaluationPeriods:d=1,threshold:m,comparisonOperator:p,treatMissingData:g="notBreaching",actionsEnabled:h=!0,alarmActions:y,okActions:f,insufficientDataActions:b,dimensions:v,unit:w,datapointsToAlarm:R}=e,T=n||l({slug:a,environment:r,resourceType:"alarm"}),N=s(T),I={Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:T,MetricName:i,Namespace:o,Statistic:c,Period:u,EvaluationPeriods:d,Threshold:m,ComparisonOperator:p,TreatMissingData:g,ActionsEnabled:h}};if(y&&y.length>0)I.Properties.AlarmActions=y;if(f&&f.length>0)I.Properties.OKActions=f;if(b&&b.length>0)I.Properties.InsufficientDataActions=b;if(v)I.Properties.Dimensions=Object.entries(v).map(([k,O])=>({Name:k,Value:O}));if(w)I.Properties.Unit=w;if(R!==void 0)I.Properties.DatapointsToAlarm=R;return{alarm:I,logicalId:N}}static createCompositeAlarm(e){let{slug:a,environment:r,alarmName:n,alarmRule:i,actionsEnabled:o=!0,alarmActions:c,okActions:u,insufficientDataActions:d}=e,m=n||l({slug:a,environment:r,resourceType:"composite-alarm"}),p=s(m),g={Type:"AWS::CloudWatch::CompositeAlarm",Properties:{AlarmName:m,AlarmRule:i,ActionsEnabled:o}};if(c&&c.length>0)g.Properties.AlarmActions=c;if(u&&u.length>0)g.Properties.OKActions=u;if(d&&d.length>0)g.Properties.InsufficientDataActions=d;return{alarm:g,logicalId:p}}static createDashboard(e){let{slug:a,environment:r,dashboardName:n,widgets:i}=e,o=n||l({slug:a,environment:r,resourceType:"dashboard"}),c=s(o),u={widgets:i.map((d)=>({type:d.type,x:d.x,y:d.y,width:d.width,height:d.height,properties:d.properties}))};return{dashboard:{Type:"AWS::CloudWatch::Dashboard",Properties:{DashboardName:o,DashboardBody:JSON.stringify(u)}},logicalId:c}}static createLogGroup(e){let{slug:a,environment:r,logGroupName:n,retentionInDays:i,kmsKeyId:o}=e,c=n||l({slug:a,environment:r,resourceType:"log-group"}),u=s(c),d={Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:c}};if(i!==void 0)d.Properties.RetentionInDays=i;if(o)d.Properties.KmsKeyId=o;return{logGroup:d,logicalId:u}}static createLogStream(e,a){let{slug:r,environment:n,logStreamName:i}=a,o=i||l({slug:r,environment:n,resourceType:"log-stream"}),c=s(o);return{logStream:{Type:"AWS::Logs::LogStream",Properties:{LogGroupName:P.Ref(e),LogStreamName:o}},logicalId:c}}static createMetricFilter(e,a){let{slug:r,environment:n,filterName:i,filterPattern:o,metricTransformations:c}=a,u=i||l({slug:r,environment:n,resourceType:"metric-filter"}),d=s(u);return{metricFilter:{Type:"AWS::Logs::MetricFilter",Properties:{LogGroupName:P.Ref(e),FilterPattern:o,MetricTransformations:c.map((m)=>({MetricName:m.metricName,MetricNamespace:m.metricNamespace,MetricValue:m.metricValue,DefaultValue:m.defaultValue,Unit:m.unit}))}},logicalId:d}}static AlarmTypes={highCpu:(e,a,r,n=80,i)=>({slug:e,environment:a,alarmName:`${e}-${a}-high-cpu`,metricName:"CPUUtilization",namespace:"AWS/EC2",statistic:"Average",period:300,evaluationPeriods:2,threshold:n,comparisonOperator:"GreaterThanThreshold",dimensions:{InstanceId:r},alarmActions:i?[i]:void 0}),highMemory:(e,a,r,n=80,i)=>({slug:e,environment:a,alarmName:`${e}-${a}-high-memory`,metricName:"MemoryUtilization",namespace:"System/Linux",statistic:"Average",period:300,evaluationPeriods:2,threshold:n,comparisonOperator:"GreaterThanThreshold",dimensions:{InstanceId:r},alarmActions:i?[i]:void 0}),highDisk:(e,a,r,n=80,i)=>({slug:e,environment:a,alarmName:`${e}-${a}-high-disk`,metricName:"DiskSpaceUtilization",namespace:"System/Linux",statistic:"Average",period:300,evaluationPeriods:2,threshold:n,comparisonOperator:"GreaterThanThreshold",dimensions:{InstanceId:r,Filesystem:"/dev/xvda1",MountPath:"/"},alarmActions:i?[i]:void 0}),lambdaErrors:(e,a,r,n=5,i)=>({slug:e,environment:a,alarmName:`${e}-${a}-lambda-errors`,metricName:"Errors",namespace:"AWS/Lambda",statistic:"Sum",period:300,evaluationPeriods:1,threshold:n,comparisonOperator:"GreaterThanThreshold",dimensions:{FunctionName:r},alarmActions:i?[i]:void 0}),lambdaThrottles:(e,a,r,n=10,i)=>({slug:e,environment:a,alarmName:`${e}-${a}-lambda-throttles`,metricName:"Throttles",namespace:"AWS/Lambda",statistic:"Sum",period:300,evaluationPeriods:1,threshold:n,comparisonOperator:"GreaterThanThreshold",dimensions:{FunctionName:r},alarmActions:i?[i]:void 0}),apiGateway5xxErrors:(e,a,r,n=10,i)=>({slug:e,environment:a,alarmName:`${e}-${a}-api-5xx-errors`,metricName:"5XXError",namespace:"AWS/ApiGateway",statistic:"Sum",period:300,evaluationPeriods:1,threshold:n,comparisonOperator:"GreaterThanThreshold",dimensions:{ApiName:r},alarmActions:i?[i]:void 0}),apiGateway4xxErrors:(e,a,r,n=50,i)=>({slug:e,environment:a,alarmName:`${e}-${a}-api-4xx-errors`,metricName:"4XXError",namespace:"AWS/ApiGateway",statistic:"Sum",period:300,evaluationPeriods:2,threshold:n,comparisonOperator:"GreaterThanThreshold",dimensions:{ApiName:r},alarmActions:i?[i]:void 0}),dynamoDBThrottles:(e,a,r,n=5,i)=>({slug:e,environment:a,alarmName:`${e}-${a}-dynamodb-throttles`,metricName:"UserErrors",namespace:"AWS/DynamoDB",statistic:"Sum",period:300,evaluationPeriods:1,threshold:n,comparisonOperator:"GreaterThanThreshold",dimensions:{TableName:r},alarmActions:i?[i]:void 0}),rdsCpu:(e,a,r,n=80,i)=>({slug:e,environment:a,alarmName:`${e}-${a}-rds-cpu`,metricName:"CPUUtilization",namespace:"AWS/RDS",statistic:"Average",period:300,evaluationPeriods:2,threshold:n,comparisonOperator:"GreaterThanThreshold",dimensions:{DBInstanceIdentifier:r},alarmActions:i?[i]:void 0}),rdsFreeStorage:(e,a,r,n=5368709120,i)=>({slug:e,environment:a,alarmName:`${e}-${a}-rds-storage`,metricName:"FreeStorageSpace",namespace:"AWS/RDS",statistic:"Average",period:300,evaluationPeriods:1,threshold:n,comparisonOperator:"LessThanThreshold",dimensions:{DBInstanceIdentifier:r},alarmActions:i?[i]:void 0,unit:"Bytes"}),sqsQueueDepth:(e,a,r,n=100,i)=>({slug:e,environment:a,alarmName:`${e}-${a}-sqs-depth`,metricName:"ApproximateNumberOfMessagesVisible",namespace:"AWS/SQS",statistic:"Average",period:300,evaluationPeriods:2,threshold:n,comparisonOperator:"GreaterThanThreshold",dimensions:{QueueName:r},alarmActions:i?[i]:void 0}),albUnhealthyTargets:(e,a,r,n,i=1,o)=>({slug:e,environment:a,alarmName:`${e}-${a}-alb-unhealthy`,metricName:"UnHealthyHostCount",namespace:"AWS/ApplicationELB",statistic:"Average",period:300,evaluationPeriods:2,threshold:i,comparisonOperator:"GreaterThanThreshold",dimensions:{LoadBalancer:r,TargetGroup:n},alarmActions:o?[o]:void 0}),sesBounceRate:(e,a,r=5,n)=>({slug:e,environment:a,alarmName:`${e}-${a}-ses-bounce-rate`,metricName:"Reputation.BounceRate",namespace:"AWS/SES",statistic:"Average",period:3600,evaluationPeriods:1,threshold:r/100,comparisonOperator:"GreaterThanThreshold",alarmActions:n?[n]:void 0}),sesComplaintRate:(e,a,r=0.1,n)=>({slug:e,environment:a,alarmName:`${e}-${a}-ses-complaint-rate`,metricName:"Reputation.ComplaintRate",namespace:"AWS/SES",statistic:"Average",period:3600,evaluationPeriods:1,threshold:r/100,comparisonOperator:"GreaterThanThreshold",alarmActions:n?[n]:void 0}),smsDeliveryFailure:(e,a,r,n=10,i)=>({slug:e,environment:a,alarmName:`${e}-${a}-sms-delivery-failure`,metricName:"DirectSendMessagePermanentFailure",namespace:"AWS/Pinpoint",statistic:"Sum",period:300,evaluationPeriods:1,threshold:n,comparisonOperator:"GreaterThanThreshold",dimensions:{ApplicationId:r},alarmActions:i?[i]:void 0}),smsSpendLimit:(e,a,r=100,n)=>({slug:e,environment:a,alarmName:`${e}-${a}-sms-spend-limit`,metricName:"DirectSendMessageSpend",namespace:"AWS/Pinpoint",statistic:"Sum",period:86400,evaluationPeriods:1,threshold:r,comparisonOperator:"GreaterThanThreshold",alarmActions:n?[n]:void 0}),connectMissedCalls:(e,a,r,n=5,i)=>({slug:e,environment:a,alarmName:`${e}-${a}-connect-missed-calls`,metricName:"MissedCalls",namespace:"AWS/Connect",statistic:"Sum",period:3600,evaluationPeriods:1,threshold:n,comparisonOperator:"GreaterThanThreshold",dimensions:{InstanceId:r},alarmActions:i?[i]:void 0})};static DashboardWidgets={metric:(e,a,r,n,i,o)=>({type:"metric",x:e,y:a,width:r,height:n,properties:{metrics:i,title:o||"Metrics",region:"us-east-1",period:300}}),text:(e,a,r,n,i)=>({type:"text",x:e,y:a,width:r,height:n,properties:{markdown:i}}),log:(e,a,r,n,i,o)=>({type:"log",x:e,y:a,width:r,height:n,properties:{query:`SOURCE '${i.join("' | SOURCE '")}'
|
|
2310
2310
|
| fields @timestamp, @message
|
|
2311
2311
|
| sort @timestamp desc
|
|
2312
2312
|
| limit 20`,region:"us-east-1",title:o||"Logs"}})};static RetentionPeriods={ONE_DAY:1,THREE_DAYS:3,FIVE_DAYS:5,ONE_WEEK:7,TWO_WEEKS:14,ONE_MONTH:30,TWO_MONTHS:60,THREE_MONTHS:90,FOUR_MONTHS:120,FIVE_MONTHS:150,SIX_MONTHS:180,ONE_YEAR:365,THIRTEEN_MONTHS:400,EIGHTEEN_MONTHS:545,TWO_YEARS:731,FIVE_YEARS:1827,TEN_YEARS:3653,NEVER_EXPIRE:void 0};static FilterPatterns={errors:"[time, request_id, event_type = ERROR*, ...]",all:"",jsonField:(e,a)=>`{ $.${e} = "${a}" }`,httpStatus:(e)=>`[..., status_code = ${e}, ...]`,http4xx:"[..., status_code = 4*, ...]",http5xx:"[..., status_code = 5*, ...]"};static createApplicationDashboard(e){let{slug:a,environment:r,region:n="us-east-1",components:i={}}=e,o=[],c=0;if(o.push({type:"text",x:0,y:c,width:24,height:1,properties:{markdown:`# ${a.toUpperCase()} Dashboard (${r})`}}),c+=1,i.ec2InstanceIds&&i.ec2InstanceIds.length>0)o.push({type:"text",x:0,y:c,width:24,height:1,properties:{markdown:"## EC2 Instances"}}),c+=1,o.push({type:"metric",x:0,y:c,width:8,height:6,properties:{title:"CPU Utilization",region:n,metrics:i.ec2InstanceIds.map((u)=>["AWS/EC2","CPUUtilization","InstanceId",u]),period:300,stat:"Average"}}),o.push({type:"metric",x:8,y:c,width:8,height:6,properties:{title:"Network Traffic",region:n,metrics:[...i.ec2InstanceIds.flatMap((u)=>[["AWS/EC2","NetworkIn","InstanceId",u,{label:`${u} In`}],["AWS/EC2","NetworkOut","InstanceId",u,{label:`${u} Out`}]])],period:300,stat:"Sum"}}),o.push({type:"metric",x:16,y:c,width:8,height:6,properties:{title:"Status Checks",region:n,metrics:i.ec2InstanceIds.map((u)=>["AWS/EC2","StatusCheckFailed","InstanceId",u]),period:60,stat:"Maximum"}}),c+=6;if(i.lambdaFunctionNames&&i.lambdaFunctionNames.length>0)o.push({type:"text",x:0,y:c,width:24,height:1,properties:{markdown:"## Lambda Functions"}}),c+=1,o.push({type:"metric",x:0,y:c,width:8,height:6,properties:{title:"Invocations",region:n,metrics:i.lambdaFunctionNames.map((u)=>["AWS/Lambda","Invocations","FunctionName",u]),period:300,stat:"Sum"}}),o.push({type:"metric",x:8,y:c,width:8,height:6,properties:{title:"Duration",region:n,metrics:i.lambdaFunctionNames.map((u)=>["AWS/Lambda","Duration","FunctionName",u]),period:300,stat:"Average"}}),o.push({type:"metric",x:16,y:c,width:8,height:6,properties:{title:"Errors",region:n,metrics:i.lambdaFunctionNames.map((u)=>["AWS/Lambda","Errors","FunctionName",u]),period:300,stat:"Sum"}}),c+=6;if(i.ecsClusterName&&i.ecsServiceName)o.push({type:"text",x:0,y:c,width:24,height:1,properties:{markdown:"## ECS Service"}}),c+=1,o.push({type:"metric",x:0,y:c,width:8,height:6,properties:{title:"CPU Utilization",region:n,metrics:[["AWS/ECS","CPUUtilization","ClusterName",i.ecsClusterName,"ServiceName",i.ecsServiceName]],period:300,stat:"Average"}}),o.push({type:"metric",x:8,y:c,width:8,height:6,properties:{title:"Memory Utilization",region:n,metrics:[["AWS/ECS","MemoryUtilization","ClusterName",i.ecsClusterName,"ServiceName",i.ecsServiceName]],period:300,stat:"Average"}}),o.push({type:"metric",x:16,y:c,width:8,height:6,properties:{title:"Running Tasks",region:n,metrics:[["ECS/ContainerInsights","RunningTaskCount","ClusterName",i.ecsClusterName,"ServiceName",i.ecsServiceName]],period:60,stat:"Average"}}),c+=6;if(i.albName)o.push({type:"text",x:0,y:c,width:24,height:1,properties:{markdown:"## Application Load Balancer"}}),c+=1,o.push({type:"metric",x:0,y:c,width:8,height:6,properties:{title:"Request Count",region:n,metrics:[["AWS/ApplicationELB","RequestCount","LoadBalancer",i.albName]],period:60,stat:"Sum"}}),o.push({type:"metric",x:8,y:c,width:8,height:6,properties:{title:"Response Time",region:n,metrics:[["AWS/ApplicationELB","TargetResponseTime","LoadBalancer",i.albName]],period:60,stat:"Average"}}),o.push({type:"metric",x:16,y:c,width:8,height:6,properties:{title:"HTTP Errors",region:n,metrics:[["AWS/ApplicationELB","HTTPCode_Target_4XX_Count","LoadBalancer",i.albName,{label:"4XX"}],["AWS/ApplicationELB","HTTPCode_Target_5XX_Count","LoadBalancer",i.albName,{label:"5XX"}]],period:60,stat:"Sum"}}),c+=6;if(i.rdsInstanceId)o.push({type:"text",x:0,y:c,width:24,height:1,properties:{markdown:"## RDS Database"}}),c+=1,o.push({type:"metric",x:0,y:c,width:8,height:6,properties:{title:"CPU Utilization",region:n,metrics:[["AWS/RDS","CPUUtilization","DBInstanceIdentifier",i.rdsInstanceId]],period:300,stat:"Average"}}),o.push({type:"metric",x:8,y:c,width:8,height:6,properties:{title:"Database Connections",region:n,metrics:[["AWS/RDS","DatabaseConnections","DBInstanceIdentifier",i.rdsInstanceId]],period:60,stat:"Sum"}}),o.push({type:"metric",x:16,y:c,width:8,height:6,properties:{title:"Free Storage Space",region:n,metrics:[["AWS/RDS","FreeStorageSpace","DBInstanceIdentifier",i.rdsInstanceId]],period:300,stat:"Average"}}),c+=6;if(i.sqsQueueNames&&i.sqsQueueNames.length>0)o.push({type:"text",x:0,y:c,width:24,height:1,properties:{markdown:"## SQS Queues"}}),c+=1,o.push({type:"metric",x:0,y:c,width:12,height:6,properties:{title:"Messages Visible",region:n,metrics:i.sqsQueueNames.map((u)=>["AWS/SQS","ApproximateNumberOfMessagesVisible","QueueName",u]),period:60,stat:"Sum"}}),o.push({type:"metric",x:12,y:c,width:12,height:6,properties:{title:"Message Age",region:n,metrics:i.sqsQueueNames.map((u)=>["AWS/SQS","ApproximateAgeOfOldestMessage","QueueName",u]),period:60,stat:"Maximum"}}),c+=6;if(i.logGroupNames&&i.logGroupNames.length>0)o.push({type:"text",x:0,y:c,width:24,height:1,properties:{markdown:"## Application Logs"}}),c+=1,o.push({type:"log",x:0,y:c,width:24,height:6,properties:{query:`SOURCE '${i.logGroupNames.join("' | SOURCE '")}'
|
|
2313
2313
|
| fields @timestamp, @message
|
|
2314
2314
|
| filter @message like /ERROR|WARN|Exception/
|
|
2315
2315
|
| sort @timestamp desc
|
|
2316
|
-
| limit 50`,region:n,title:"Recent Errors and Warnings"}}),c+=6;return gi.createDashboard({slug:a,environment:r,widgets:o})}static DashboardTemplates={staticWebsite:(e)=>({slug:e.slug,environment:e.environment,widgets:[{type:"text",x:0,y:0,width:24,height:1,properties:{markdown:`# ${e.slug.toUpperCase()} Static Website Dashboard`}},{type:"metric",x:0,y:1,width:8,height:6,properties:{title:"CloudFront Requests",region:"us-east-1",metrics:[["AWS/CloudFront","Requests","DistributionId",e.cloudFrontDistributionId,"Region","Global"]],period:300,stat:"Sum"}},{type:"metric",x:8,y:1,width:8,height:6,properties:{title:"Error Rate",region:"us-east-1",metrics:[["AWS/CloudFront","4xxErrorRate","DistributionId",e.cloudFrontDistributionId,"Region","Global",{label:"4XX"}],["AWS/CloudFront","5xxErrorRate","DistributionId",e.cloudFrontDistributionId,"Region","Global",{label:"5XX"}]],period:300,stat:"Average"}},{type:"metric",x:16,y:1,width:8,height:6,properties:{title:"Bytes Downloaded",region:"us-east-1",metrics:[["AWS/CloudFront","BytesDownloaded","DistributionId",e.cloudFrontDistributionId,"Region","Global"]],period:300,stat:"Sum"}},{type:"metric",x:0,y:7,width:12,height:6,properties:{title:"S3 Bucket Size",region:e.region||"us-east-1",metrics:[["AWS/S3","BucketSizeBytes","BucketName",e.s3BucketName,"StorageType","StandardStorage"]],period:86400,stat:"Average"}},{type:"metric",x:12,y:7,width:12,height:6,properties:{title:"S3 Number of Objects",region:e.region||"us-east-1",metrics:[["AWS/S3","NumberOfObjects","BucketName",e.s3BucketName,"StorageType","AllStorageTypes"]],period:86400,stat:"Average"}}]}),serverlessApi:(e)=>({slug:e.slug,environment:e.environment,widgets:[{type:"text",x:0,y:0,width:24,height:1,properties:{markdown:`# ${e.slug.toUpperCase()} Serverless API Dashboard`}},{type:"metric",x:0,y:1,width:8,height:6,properties:{title:"API Requests",region:e.region||"us-east-1",metrics:[["AWS/ApiGateway","Count","ApiName",e.apiGatewayName]],period:60,stat:"Sum"}},{type:"metric",x:8,y:1,width:8,height:6,properties:{title:"API Latency",region:e.region||"us-east-1",metrics:[["AWS/ApiGateway","Latency","ApiName",e.apiGatewayName]],period:60,stat:"Average"}},{type:"metric",x:16,y:1,width:8,height:6,properties:{title:"API Errors",region:e.region||"us-east-1",metrics:[["AWS/ApiGateway","4XXError","ApiName",e.apiGatewayName,{label:"4XX"}],["AWS/ApiGateway","5XXError","ApiName",e.apiGatewayName,{label:"5XX"}]],period:60,stat:"Sum"}},...e.lambdaFunctionNames.map((a,r)=>({type:"metric",x:r%3*8,y:7+Math.floor(r/3)*6,width:8,height:6,properties:{title:`${a} Metrics`,region:e.region||"us-east-1",metrics:[["AWS/Lambda","Invocations","FunctionName",a],["AWS/Lambda","Duration","FunctionName",a],["AWS/Lambda","Errors","FunctionName",a]],period:300,stat:"Sum"}}))]}),containerService:(e)=>({slug:e.slug,environment:e.environment,widgets:[{type:"text",x:0,y:0,width:24,height:1,properties:{markdown:`# ${e.slug.toUpperCase()} Container Service Dashboard`}},{type:"metric",x:0,y:1,width:8,height:6,properties:{title:"ECS CPU",region:e.region||"us-east-1",metrics:[["AWS/ECS","CPUUtilization","ClusterName",e.ecsClusterName,"ServiceName",e.ecsServiceName]],period:60,stat:"Average"}},{type:"metric",x:8,y:1,width:8,height:6,properties:{title:"ECS Memory",region:e.region||"us-east-1",metrics:[["AWS/ECS","MemoryUtilization","ClusterName",e.ecsClusterName,"ServiceName",e.ecsServiceName]],period:60,stat:"Average"}},{type:"metric",x:16,y:1,width:8,height:6,properties:{title:"Running Tasks",region:e.region||"us-east-1",metrics:[["ECS/ContainerInsights","RunningTaskCount","ClusterName",e.ecsClusterName,"ServiceName",e.ecsServiceName]],period:60,stat:"Average"}},{type:"metric",x:0,y:7,width:8,height:6,properties:{title:"ALB Requests",region:e.region||"us-east-1",metrics:[["AWS/ApplicationELB","RequestCount","LoadBalancer",e.albName]],period:60,stat:"Sum"}},{type:"metric",x:8,y:7,width:8,height:6,properties:{title:"Response Time",region:e.region||"us-east-1",metrics:[["AWS/ApplicationELB","TargetResponseTime","LoadBalancer",e.albName]],period:60,stat:"Average"}},{type:"metric",x:16,y:7,width:8,height:6,properties:{title:"Healthy Hosts",region:e.region||"us-east-1",metrics:[["AWS/ApplicationELB","HealthyHostCount","LoadBalancer",e.albName]],period:60,stat:"Average"}},...e.rdsInstanceId?[{type:"metric",x:0,y:13,width:12,height:6,properties:{title:"RDS CPU",region:e.region||"us-east-1",metrics:[["AWS/RDS","CPUUtilization","DBInstanceIdentifier",e.rdsInstanceId]],period:300,stat:"Average"}},{type:"metric",x:12,y:13,width:12,height:6,properties:{title:"RDS Connections",region:e.region||"us-east-1",metrics:[["AWS/RDS","DatabaseConnections","DBInstanceIdentifier",e.rdsInstanceId]],period:60,stat:"Sum"}}]:[]]})};static Config={createAlarmConfig:(e)=>{let{metricName:a,namespace:r,threshold:n,comparisonOperator:i="GreaterThanThreshold",evaluationPeriods:o=1,period:c=300,statistic:u="Average",treatMissingData:d="missing"}=e;return{MetricName:a,Namespace:r,Threshold:n,ComparisonOperator:i,EvaluationPeriods:o,Period:c,Statistic:u,TreatMissingData:d}},namespaces:{ec2:"AWS/EC2",ecs:"AWS/ECS",lambda:"AWS/Lambda",rds:"AWS/RDS",sqs:"AWS/SQS",sns:"AWS/SNS",s3:"AWS/S3",cloudfront:"AWS/CloudFront",alb:"AWS/ApplicationELB",nlb:"AWS/NetworkELB",apiGateway:"AWS/ApiGateway",dynamodb:"AWS/DynamoDB",elasticache:"AWS/ElastiCache"},comparisonOperators:{greaterThan:"GreaterThanThreshold",greaterOrEqual:"GreaterThanOrEqualToThreshold",lessThan:"LessThanThreshold",lessOrEqual:"LessThanOrEqualToThreshold"},metrics:{ec2:{cpu:{metricName:"CPUUtilization",namespace:"AWS/EC2"},networkIn:{metricName:"NetworkIn",namespace:"AWS/EC2"},networkOut:{metricName:"NetworkOut",namespace:"AWS/EC2"},statusCheck:{metricName:"StatusCheckFailed",namespace:"AWS/EC2"}},ecs:{cpu:{metricName:"CPUUtilization",namespace:"AWS/ECS"},memory:{metricName:"MemoryUtilization",namespace:"AWS/ECS"}},lambda:{invocations:{metricName:"Invocations",namespace:"AWS/Lambda"},errors:{metricName:"Errors",namespace:"AWS/Lambda"},duration:{metricName:"Duration",namespace:"AWS/Lambda"},throttles:{metricName:"Throttles",namespace:"AWS/Lambda"},concurrentExecutions:{metricName:"ConcurrentExecutions",namespace:"AWS/Lambda"}},rds:{cpu:{metricName:"CPUUtilization",namespace:"AWS/RDS"},connections:{metricName:"DatabaseConnections",namespace:"AWS/RDS"},freeStorage:{metricName:"FreeStorageSpace",namespace:"AWS/RDS"},readLatency:{metricName:"ReadLatency",namespace:"AWS/RDS"},writeLatency:{metricName:"WriteLatency",namespace:"AWS/RDS"}},alb:{requestCount:{metricName:"RequestCount",namespace:"AWS/ApplicationELB"},responseTime:{metricName:"TargetResponseTime",namespace:"AWS/ApplicationELB"},httpCode4xx:{metricName:"HTTPCode_Target_4XX_Count",namespace:"AWS/ApplicationELB"},httpCode5xx:{metricName:"HTTPCode_Target_5XX_Count",namespace:"AWS/ApplicationELB"},healthyHosts:{metricName:"HealthyHostCount",namespace:"AWS/ApplicationELB"}},sqs:{messagesVisible:{metricName:"ApproximateNumberOfMessagesVisible",namespace:"AWS/SQS"},messagesDelayed:{metricName:"ApproximateNumberOfMessagesDelayed",namespace:"AWS/SQS"},messageAge:{metricName:"ApproximateAgeOfOldestMessage",namespace:"AWS/SQS"}}},presets:{highCpu:(e=80)=>({metricName:"CPUUtilization",threshold:e,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),highMemory:(e=80)=>({metricName:"MemoryUtilization",threshold:e,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),highErrors:(e=10)=>({metricName:"Errors",threshold:e,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:1,period:60,statistic:"Sum"}),highLatency:(e=5000)=>({metricName:"Duration",threshold:e,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),lowHealthyHosts:(e=1)=>({metricName:"HealthyHostCount",namespace:"AWS/ApplicationELB",threshold:e,comparisonOperator:"LessThanThreshold",evaluationPeriods:2,period:60,statistic:"Minimum"}),queueDepth:(e=1000)=>({metricName:"ApproximateNumberOfMessagesVisible",namespace:"AWS/SQS",threshold:e,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),lowStorage:(e=10737418240)=>({metricName:"FreeStorageSpace",namespace:"AWS/RDS",threshold:e,comparisonOperator:"LessThanThreshold",evaluationPeriods:1,period:300,statistic:"Average"})}}}class Te{static createUserPool(e){let{slug:a,environment:r,userPoolName:n,aliasAttributes:i,autoVerifiedAttributes:o,passwordPolicy:c,mfaConfiguration:u,emailConfiguration:d,smsConfiguration:m,lambdaTriggers:p,userPoolAddOns:g,accountRecoverySetting:h}=e,y=n||l({slug:a,environment:r,resourceType:"user-pool"}),f=s(y),b={Type:"AWS::Cognito::UserPool",Properties:{UserPoolName:y,Policies:c?{PasswordPolicy:{MinimumLength:c.minimumLength,RequireLowercase:c.requireLowercase,RequireUppercase:c.requireUppercase,RequireNumbers:c.requireNumbers,RequireSymbols:c.requireSymbols,TemporaryPasswordValidityDays:c.temporaryPasswordValidityDays}}:void 0,MfaConfiguration:u,Schema:[{Name:"email",AttributeDataType:"String",Required:!0,Mutable:!1}]}};if(i&&i.length>0)b.Properties.UsernameAttributes=i;if(o&&o.length>0)b.Properties.AutoVerifiedAttributes=o;if(d)b.Properties.EmailConfiguration={EmailSendingAccount:d.emailSendingAccount,From:d.from,ReplyToEmailAddress:d.replyToEmailAddress,SourceArn:d.sourceArn,ConfigurationSet:d.configurationSet};if(m)b.Properties.SmsConfiguration={ExternalId:m.externalId,SnsCallerArn:m.snsCallerArn};if(p)b.Properties.LambdaConfig={PreSignUp:p.preSignUp,PostConfirmation:p.postConfirmation,PreAuthentication:p.preAuthentication,PostAuthentication:p.postAuthentication,CustomMessage:p.customMessage,DefineAuthChallenge:p.defineAuthChallenge,CreateAuthChallenge:p.createAuthChallenge,VerifyAuthChallengeResponse:p.verifyAuthChallengeResponse,PreTokenGeneration:p.preTokenGeneration,UserMigration:p.userMigration};if(g)b.Properties.UserPoolAddOns={AdvancedSecurityMode:g.advancedSecurityMode};if(h)b.Properties.AccountRecoverySetting={RecoveryMechanisms:h.recoveryMechanisms};return{userPool:b,logicalId:f}}static createUserPoolClient(e,a){let{slug:r,environment:n,clientName:i,generateSecret:o=!1,refreshTokenValidity:c,accessTokenValidity:u,idTokenValidity:d,tokenValidityUnits:m,readAttributes:p,writeAttributes:g,explicitAuthFlows:h,preventUserExistenceErrors:y,enableTokenRevocation:f,callbackURLs:b,logoutURLs:v,allowedOAuthFlows:w,allowedOAuthScopes:R,allowedOAuthFlowsUserPoolClient:T,supportedIdentityProviders:N}=a,I=i||l({slug:r,environment:n,resourceType:"user-pool-client"}),k=s(I);return{client:{Type:"AWS::Cognito::UserPoolClient",Properties:{ClientName:I,UserPoolId:P.Ref(e),GenerateSecret:o,RefreshTokenValidity:c,AccessTokenValidity:u,IdTokenValidity:d,TokenValidityUnits:m,ReadAttributes:p,WriteAttributes:g,ExplicitAuthFlows:h,PreventUserExistenceErrors:y,EnableTokenRevocation:f,CallbackURLs:b,LogoutURLs:v,AllowedOAuthFlows:w,AllowedOAuthScopes:R,AllowedOAuthFlowsUserPoolClient:T,SupportedIdentityProviders:N}},logicalId:k}}static createUserPoolDomain(e,a){let{slug:r,environment:n,domain:i,customDomainConfig:o}=a,c=l({slug:r,environment:n,resourceType:"user-pool-domain"}),u=s(c);return{domain:{Type:"AWS::Cognito::UserPoolDomain",Properties:{Domain:i,UserPoolId:P.Ref(e),CustomDomainConfig:o}},logicalId:u}}static createIdentityPool(e){let{slug:a,environment:r,identityPoolName:n,allowUnauthenticatedIdentities:i=!1,cognitoIdentityProviders:o,supportedLoginProviders:c,samlProviderARNs:u,openIdConnectProviderARNs:d}=e,m=n||l({slug:a,environment:r,resourceType:"identity-pool"}),p=s(m);return{identityPool:{Type:"AWS::Cognito::IdentityPool",Properties:{IdentityPoolName:m,AllowUnauthenticatedIdentities:i,CognitoIdentityProviders:o,SupportedLoginProviders:c,SamlProviderARNs:u,OpenIdConnectProviderARNs:d}},logicalId:p}}static createIdentityPoolRoleAttachment(e,a){let{slug:r,environment:n,authenticatedRole:i,unauthenticatedRole:o,roleMappings:c}=a,u=l({slug:r,environment:n,resourceType:"identity-pool-role-attachment"}),d=s(u),m={authenticated:i};if(o)m.unauthenticated=o;return{attachment:{Type:"AWS::Cognito::IdentityPoolRoleAttachment",Properties:{IdentityPoolId:P.Ref(e),Roles:m,RoleMappings:c}},logicalId:d}}static createAuthenticatedRole(e){let{slug:a,environment:r,identityPoolLogicalId:n}=e,i=l({slug:a,environment:r,resourceType:"cognito-authenticated-role"}),o=s(i);return{role:{Type:"AWS::IAM::Role",Properties:{RoleName:i,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Federated:"cognito-identity.amazonaws.com"},Action:"sts:AssumeRoleWithWebIdentity",Condition:{StringEquals:{"cognito-identity.amazonaws.com:aud":P.Ref(n)},"ForAnyValue:StringLike":{"cognito-identity.amazonaws.com:amr":"authenticated"}}}]},Policies:[{PolicyName:"CognitoAuthenticatedPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["cognito-sync:*","cognito-identity:*"],Resource:"*"}]}}],Tags:[{Key:"Name",Value:i},{Key:"Environment",Value:r}]}},logicalId:o}}static createUnauthenticatedRole(e){let{slug:a,environment:r,identityPoolLogicalId:n}=e,i=l({slug:a,environment:r,resourceType:"cognito-unauthenticated-role"}),o=s(i);return{role:{Type:"AWS::IAM::Role",Properties:{RoleName:i,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Federated:"cognito-identity.amazonaws.com"},Action:"sts:AssumeRoleWithWebIdentity",Condition:{StringEquals:{"cognito-identity.amazonaws.com:aud":P.Ref(n)},"ForAnyValue:StringLike":{"cognito-identity.amazonaws.com:amr":"unauthenticated"}}}]},Policies:[{PolicyName:"CognitoUnauthenticatedPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["cognito-sync:*"],Resource:"*"}]}}],Tags:[{Key:"Name",Value:i},{Key:"Environment",Value:r}]}},logicalId:o}}static PasswordPolicies={relaxed:()=>({minimumLength:8,requireLowercase:!1,requireUppercase:!1,requireNumbers:!1,requireSymbols:!1,temporaryPasswordValidityDays:7}),standard:()=>({minimumLength:8,requireLowercase:!0,requireUppercase:!0,requireNumbers:!0,requireSymbols:!1,temporaryPasswordValidityDays:3}),strict:()=>({minimumLength:12,requireLowercase:!0,requireUppercase:!0,requireNumbers:!0,requireSymbols:!0,temporaryPasswordValidityDays:1})};static AuthFlows={standard:["ALLOW_USER_SRP_AUTH","ALLOW_REFRESH_TOKEN_AUTH"],admin:["ALLOW_ADMIN_USER_PASSWORD_AUTH","ALLOW_REFRESH_TOKEN_AUTH"],custom:["ALLOW_CUSTOM_AUTH","ALLOW_REFRESH_TOKEN_AUTH"],all:["ALLOW_USER_SRP_AUTH","ALLOW_USER_PASSWORD_AUTH","ALLOW_ADMIN_USER_PASSWORD_AUTH","ALLOW_CUSTOM_AUTH","ALLOW_REFRESH_TOKEN_AUTH"]};static OAuthScopes={basic:["openid","email","profile"],all:["openid","email","profile","phone","aws.cognito.signin.user.admin"]};static UseCases={webApp:(e,a,r)=>{let{userPool:n,logicalId:i}=Te.createUserPool({slug:e,environment:a,aliasAttributes:["email"],autoVerifiedAttributes:["email"],passwordPolicy:Te.PasswordPolicies.standard(),mfaConfiguration:"OPTIONAL"}),{client:o,logicalId:c}=Te.createUserPoolClient(i,{slug:e,environment:a,explicitAuthFlows:[...Te.AuthFlows.standard],callbackURLs:[r],allowedOAuthFlows:["code"],allowedOAuthScopes:[...Te.OAuthScopes.basic],allowedOAuthFlowsUserPoolClient:!0});return{userPool:n,poolId:i,client:o,clientId:c}},mobileApp:(e,a)=>{let{userPool:r,logicalId:n}=Te.createUserPool({slug:e,environment:a,aliasAttributes:["email"],autoVerifiedAttributes:["email"],passwordPolicy:Te.PasswordPolicies.standard(),mfaConfiguration:"OPTIONAL"}),{client:i,logicalId:o}=Te.createUserPoolClient(n,{slug:e,environment:a,explicitAuthFlows:[...Te.AuthFlows.standard]}),{identityPool:c,logicalId:u}=Te.createIdentityPool({slug:e,environment:a,allowUnauthenticatedIdentities:!1,cognitoIdentityProviders:[{ClientId:P.Ref(o),ProviderName:P.GetAtt(n,"ProviderName")}]}),{role:d,logicalId:m}=Te.createAuthenticatedRole({slug:e,environment:a,identityPoolLogicalId:u}),{attachment:p,logicalId:g}=Te.createIdentityPoolRoleAttachment(u,{slug:e,environment:a,authenticatedRole:P.GetAtt(m,"Arn")});return{userPool:r,poolId:n,client:i,clientId:o,identityPool:c,identityPoolId:u,authRole:d,authRoleId:m,attachment:p,attachmentId:g}}}}class Ee{static createApplication(e){let{slug:a,environment:r,applicationName:n,computePlatform:i}=e,o=n||l({slug:a,environment:r,resourceType:"deploy-app"}),c=s(o);return{application:{Type:"AWS::CodeDeploy::Application",Properties:{ApplicationName:o,ComputePlatform:i,Tags:[{Key:"Name",Value:o},{Key:"Environment",Value:r}]}},logicalId:c}}static createDeploymentGroup(e,a){let{slug:r,environment:n,deploymentGroupName:i,serviceRoleArn:o,autoScalingGroups:c,ec2TagFilters:u,deploymentConfigName:d,autoRollbackConfiguration:m,alarmConfiguration:p,loadBalancerInfo:g,blueGreenDeploymentConfiguration:h}=a,y=i||l({slug:r,environment:n,resourceType:"deploy-group"}),f=s(y);return{deploymentGroup:{Type:"AWS::CodeDeploy::DeploymentGroup",Properties:{ApplicationName:P.Ref(e),DeploymentGroupName:y,ServiceRoleArn:o,AutoScalingGroups:c,Ec2TagFilters:u?.map((b)=>({Key:b.key,Value:b.value,Type:b.type})),DeploymentConfigName:d,AutoRollbackConfiguration:m?{Enabled:m.enabled,Events:m.events}:void 0,AlarmConfiguration:p?{Enabled:p.enabled,Alarms:p.alarms?.map((b)=>({Name:b.name})),IgnorePollAlarmFailure:p.ignorePollAlarmFailure}:void 0,LoadBalancerInfo:g?{TargetGroupInfoList:g.targetGroupInfoList?.map((b)=>({Name:b.name})),ElbInfoList:g.elbInfoList?.map((b)=>({Name:b.name}))}:void 0,BlueGreenDeploymentConfiguration:h?{TerminateBlueInstancesOnDeploymentSuccess:h.terminateBlueInstancesOnDeploymentSuccess?{Action:h.terminateBlueInstancesOnDeploymentSuccess.action,TerminationWaitTimeInMinutes:h.terminateBlueInstancesOnDeploymentSuccess.terminationWaitTimeInMinutes}:void 0,DeploymentReadyOption:h.deploymentReadyOption?{ActionOnTimeout:h.deploymentReadyOption.actionOnTimeout,WaitTimeInMinutes:h.deploymentReadyOption.waitTimeInMinutes}:void 0,GreenFleetProvisioningOption:h.greenFleetProvisioningOption?{Action:h.greenFleetProvisioningOption.action}:void 0}:void 0,Tags:[{Key:"Name",Value:y},{Key:"Environment",Value:n}]}},logicalId:f}}static createDeploymentConfig(e){let{slug:a,environment:r,deploymentConfigName:n,minimumHealthyHosts:i,trafficRoutingConfig:o}=e,c=n||l({slug:a,environment:r,resourceType:"deploy-config"}),u=s(c);return{deploymentConfig:{Type:"AWS::CodeDeploy::DeploymentConfig",Properties:{DeploymentConfigName:c,MinimumHealthyHosts:i?{Type:i.type,Value:i.value}:void 0,TrafficRoutingConfig:o?{Type:o.type,TimeBasedCanary:o.timeBasedCanary?{CanaryPercentage:o.timeBasedCanary.canaryPercentage,CanaryInterval:o.timeBasedCanary.canaryInterval}:void 0,TimeBasedLinear:o.timeBasedLinear?{LinearPercentage:o.timeBasedLinear.linearPercentage,LinearInterval:o.timeBasedLinear.linearInterval}:void 0}:void 0}},logicalId:u}}static DeploymentConfigs={allAtOnce:()=>({type:"FLEET_PERCENT",value:0}),halfAtATime:()=>({type:"FLEET_PERCENT",value:50}),oneAtATime:()=>({type:"HOST_COUNT",value:1}),custom:(e,a)=>({type:e,value:a})};static TrafficRouting={allAtOnce:()=>({type:"AllAtOnce"}),canary:(e,a)=>({type:"TimeBasedCanary",timeBasedCanary:{canaryPercentage:e,canaryInterval:a}}),linear:(e,a)=>({type:"TimeBasedLinear",timeBasedLinear:{linearPercentage:e,linearInterval:a}})};static RollbackConfigs={onFailure:()=>({enabled:!0,events:["DEPLOYMENT_FAILURE"]}),onAlarmOrFailure:()=>({enabled:!0,events:["DEPLOYMENT_FAILURE","DEPLOYMENT_STOP_ON_ALARM"]}),onAllEvents:()=>({enabled:!0,events:["DEPLOYMENT_FAILURE","DEPLOYMENT_STOP_ON_ALARM","DEPLOYMENT_STOP_ON_REQUEST"]}),disabled:()=>({enabled:!1})};static BlueGreenConfigs={standard:()=>({terminateBlueInstancesOnDeploymentSuccess:{action:"TERMINATE",terminationWaitTimeInMinutes:5},deploymentReadyOption:{actionOnTimeout:"CONTINUE_DEPLOYMENT",waitTimeInMinutes:0},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}}),withDelay:(e)=>({terminateBlueInstancesOnDeploymentSuccess:{action:"TERMINATE",terminationWaitTimeInMinutes:e},deploymentReadyOption:{actionOnTimeout:"CONTINUE_DEPLOYMENT",waitTimeInMinutes:0},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}}),withManualApproval:(e)=>({terminateBlueInstancesOnDeploymentSuccess:{action:"TERMINATE",terminationWaitTimeInMinutes:5},deploymentReadyOption:{actionOnTimeout:"STOP_DEPLOYMENT",waitTimeInMinutes:e},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}}),keepBlue:()=>({terminateBlueInstancesOnDeploymentSuccess:{action:"KEEP_ALIVE"},deploymentReadyOption:{actionOnTimeout:"CONTINUE_DEPLOYMENT",waitTimeInMinutes:0},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}})};static UseCases={ec2Deployment:(e,a,r,n)=>{let{application:i,logicalId:o}=Ee.createApplication({slug:e,environment:a,computePlatform:"Server"}),{deploymentGroup:c,logicalId:u}=Ee.createDeploymentGroup(o,{slug:e,environment:a,serviceRoleArn:r,autoScalingGroups:n,deploymentConfigName:"CodeDeployDefault.OneAtATime",autoRollbackConfiguration:Ee.RollbackConfigs.onFailure()});return{application:i,appId:o,deploymentGroup:c,groupId:u}},lambdaCanaryDeployment:(e,a,r,n=10,i=5)=>{let{application:o,logicalId:c}=Ee.createApplication({slug:e,environment:a,computePlatform:"Lambda"}),{deploymentConfig:u,logicalId:d}=Ee.createDeploymentConfig({slug:e,environment:a,trafficRoutingConfig:Ee.TrafficRouting.canary(n,i)}),{deploymentGroup:m,logicalId:p}=Ee.createDeploymentGroup(c,{slug:e,environment:a,serviceRoleArn:r,deploymentConfigName:P.Ref(d),autoRollbackConfiguration:Ee.RollbackConfigs.onAlarmOrFailure()});return{application:o,appId:c,deploymentConfig:u,configId:d,deploymentGroup:m,groupId:p}},ecsBlueGreenDeployment:(e,a,r,n)=>{let{application:i,logicalId:o}=Ee.createApplication({slug:e,environment:a,computePlatform:"ECS"}),{deploymentGroup:c,logicalId:u}=Ee.createDeploymentGroup(o,{slug:e,environment:a,serviceRoleArn:r,loadBalancerInfo:{targetGroupInfoList:[{name:n}]},blueGreenDeploymentConfiguration:Ee.BlueGreenConfigs.standard(),autoRollbackConfiguration:Ee.RollbackConfigs.onFailure()});return{application:i,appId:o,deploymentGroup:c,groupId:u}}};static Strategies={rolling:(e=25)=>({type:"rolling",batchPercentage:e}),blueGreen:()=>({type:"blue-green"}),canary:(e=10,a=5)=>({type:"canary",canaryPercentage:e,canaryInterval:a}),allAtOnce:()=>({type:"all-at-once"})}}class ee{static ContentTypes={".html":"text/html",".htm":"text/html",".css":"text/css",".js":"application/javascript",".mjs":"application/javascript",".json":"application/json",".xml":"application/xml",".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",".eot":"application/vnd.ms-fontobject",".pdf":"application/pdf",".txt":"text/plain",".md":"text/markdown",".map":"application/json"};static NoHashPatterns=[/^index\.html$/,/^favicon\.ico$/,/^robots\.txt$/,/^sitemap\.xml$/,/^manifest\.json$/,/^\.well-known\//,/^_redirects$/,/^_headers$/];static computeFileHash(e,a="md5"){let r=tt(e);return Gr(a).update(r).digest("hex")}static computeShortHash(e){return ee.computeFileHash(e).slice(0,8)}static getContentType(e){let a=ga(e).toLowerCase();return ee.ContentTypes[a]||"application/octet-stream"}static shouldHashFile(e,a){return![...ee.NoHashPatterns,...a||[]].some((r)=>r.test(e))}static generateHashedFilename(e,a){let r=ga(e),n=jr(e,r),i=pa(e);if(i===".")return`${n}.${a}${r}`;return Fe(i,`${n}.${a}${r}`)}static collectFiles(e,a){let r=[],n=a||e;if(!Ct(e))return r;let i=Ur(e,{withFileTypes:!0});for(let o of i){let c=Fe(e,o.name);if(o.isDirectory())r.push(...ee.collectFiles(c,n));else if(o.isFile())r.push(c)}return r}static hashDirectory(e){let{sourceDir:a,outputDir:r,excludePatterns:n=[],hashAlgorithm:i="md5",copyUnhashed:o=!0}=e,c=ee.collectFiles(a),u=[],d={};for(let p of c){let g=p.replace(a,"").replace(/^[/\\]/,""),h=ee.shouldHashFile(g,n),y=Vr(p),f=h?ee.computeFileHash(p,i).slice(0,8):"",b=h?ee.generateHashedFilename(g,f):g,v={originalPath:g,hashedPath:b,hash:f,size:y.size,contentType:ee.getContentType(p)};if(u.push(v),d[g]=b,r){let w=Fe(r,b),R=pa(w);if(!Ct(R)){let{mkdirSync:T}=or("node:fs");T(R,{recursive:!0})}if(h||o)Fr(p,w)}}let m={version:"1.0",timestamp:new Date().toISOString(),assets:u,hashMap:d};if(r){let p=Fe(r,"asset-manifest.json");at(p,JSON.stringify(m,null,2))}return m}static getInvalidationPaths(e,a){let r=[];if(!e)return["/*"];let n=e.hashMap,i=a.hashMap;for(let[o,c]of Object.entries(i)){let u=n[o];if(!u||u!==c){if(r.push(`/${o}`),u&&u!==c)r.push(`/${u}`)}}for(let[o,c]of Object.entries(n))if(!i[o])r.push(`/${o}`),r.push(`/${c}`);if(r.length>100)return["/*"];return[...new Set(r)]}static updateHtmlReferences(e){let{htmlDir:a,manifest:r,basePath:n=""}=e,i=ee.collectFiles(a).filter((o)=>o.endsWith(".html")||o.endsWith(".htm"));for(let o of i){let c=tt(o,"utf-8");for(let[u,d]of Object.entries(r.hashMap)){if(u===d)continue;let m=[new RegExp(`(src|href)=["']${n}/?${ee.escapeRegExp(u)}["']`,"g"),new RegExp(`url\\(["']?${n}/?${ee.escapeRegExp(u)}["']?\\)`,"g")];for(let p of m)c=c.replace(p,(g)=>g.replace(u,d))}at(o,c)}}static updateCssReferences(e){let{cssDir:a,manifest:r,basePath:n=""}=e,i=ee.collectFiles(a).filter((o)=>o.endsWith(".css"));for(let o of i){let c=tt(o,"utf-8");for(let[u,d]of Object.entries(r.hashMap)){if(u===d)continue;let m=new RegExp(`url\\(["']?${n}/?${ee.escapeRegExp(u)}["']?\\)`,"g");c=c.replace(m,`url(${n}/${d})`)}at(o,c)}}static escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}static generateS3DeploymentManifest(e){let{sourceDir:a,keyPrefix:r="",excludePatterns:n=[],cacheControl:i={hashed:"public, max-age=31536000, immutable",unhashed:"public, max-age=3600",html:"public, max-age=0, must-revalidate"}}=e;return ee.hashDirectory({sourceDir:a,excludePatterns:n}).assets.map((o)=>{let c=o.hash!=="",u=o.contentType==="text/html",d=i.unhashed||"public, max-age=3600";if(u)d=i.html||"public, max-age=0, must-revalidate";else if(c)d=i.hashed||"public, max-age=31536000, immutable";return{localPath:Fe(a,o.originalPath),s3Key:r?`${r}/${o.hashedPath}`:o.hashedPath,contentType:o.contentType,cacheControl:d,hash:o.hash}})}static compareManifests(e,a){let r={added:[],removed:[],changed:[],unchanged:[]},n=new Set(Object.keys(e.hashMap)),i=new Set(Object.keys(a.hashMap));for(let o of i)if(!n.has(o))r.added.push(o);for(let o of n)if(!i.has(o))r.removed.push(o);for(let o of i)if(n.has(o))if(e.hashMap[o]!==a.hashMap[o])r.changed.push(o);else r.unchanged.push(o);return r}static loadManifest(e){if(!Ct(e))return null;try{let a=tt(e,"utf-8");return JSON.parse(a)}catch{return null}}static saveManifest(e,a){at(a,JSON.stringify(e,null,2))}}class fi{static createSecret(e){let{slug:a,environment:r,secretName:n,description:i,secretString:o,kmsKeyId:c,tags:u}=e,d=n||l({slug:a,environment:r,resourceType:"secret"}),m=s(d),p={Type:"AWS::SecretsManager::Secret",Properties:{Name:d,Description:i,SecretString:o,Tags:[{Key:"Name",Value:d},{Key:"Environment",Value:r},...u?Object.entries(u).map(([g,h])=>({Key:g,Value:h})):[]]}};if(c)p.Properties.KmsKeyId=c;return{secret:p,logicalId:m}}static createGeneratedSecret(e){let{slug:a,environment:r,secretName:n,description:i,excludeCharacters:o,excludeLowercase:c,excludeNumbers:u,excludePunctuation:d,excludeUppercase:m,passwordLength:p,requireEachIncludedType:g,kmsKeyId:h,tags:y}=e,f=n||l({slug:a,environment:r,resourceType:"secret"}),b=s(f),v={Type:"AWS::SecretsManager::Secret",Properties:{Name:f,Description:i,GenerateSecretString:{ExcludeCharacters:o,ExcludeLowercase:c,ExcludeNumbers:u,ExcludePunctuation:d,ExcludeUppercase:m,PasswordLength:p||32,RequireEachIncludedType:g!==!1},Tags:[{Key:"Name",Value:f},{Key:"Environment",Value:r},...y?Object.entries(y).map(([w,R])=>({Key:w,Value:R})):[]]}};if(h)v.Properties.KmsKeyId=h;return{secret:v,logicalId:b}}static createDatabaseSecret(e){let{slug:a,environment:r,secretName:n,username:i,dbname:o,engine:c,host:u,port:d,kmsKeyId:m}=e,p=n||l({slug:a,environment:r,resourceType:"db-secret"}),g=s(p),h={username:i};if(o)h.dbname=o;if(c)h.engine=c;if(u)h.host=u;if(d)h.port=d;let y={Type:"AWS::SecretsManager::Secret",Properties:{Name:p,Description:`Database credentials for ${i}`,GenerateSecretString:{SecretStringTemplate:JSON.stringify(h),GenerateStringKey:"password",PasswordLength:32,ExcludeCharacters:'"@/\\',RequireEachIncludedType:!0},Tags:[{Key:"Name",Value:p},{Key:"Environment",Value:r},{Key:"Type",Value:"database"}]}};if(m)y.Properties.KmsKeyId=m;return{secret:y,logicalId:g}}static attachToDatabase(e){let{slug:a,environment:r,secretId:n,targetId:i,targetType:o}=e,c=l({slug:a,environment:r,resourceType:"secret-attachment"}),u=s(c);return{attachment:{Type:"AWS::SecretsManager::SecretTargetAttachment",Properties:{SecretId:n,TargetId:i,TargetType:o}},logicalId:u}}static enableRotation(e){let{slug:a,environment:r,secretId:n,rotationLambdaArn:i,automaticallyAfterDays:o,rotationType:c,kmsKeyArn:u,vpcSecurityGroupIds:d,vpcSubnetIds:m}=e,p=l({slug:a,environment:r,resourceType:"secret-rotation"}),g=s(p),h={Type:"AWS::SecretsManager::RotationSchedule",Properties:{SecretId:n,RotationRules:{AutomaticallyAfterDays:o||30}}};if(i)h.Properties.RotationLambdaARN=i;else if(c)h.Properties.HostedRotationLambda={RotationType:c,KmsKeyArn:u,VpcSecurityGroupIds:d,VpcSubnetIds:m};return{rotation:h,logicalId:g}}static SecretTypes={apiKey:(e,a,r)=>fi.createGeneratedSecret({slug:e,environment:a,secretName:`${e}-${a}-${r}-api-key`,description:`API key for ${r}`,passwordLength:32,excludePunctuation:!0,excludeLowercase:!1,excludeUppercase:!1,excludeNumbers:!1}),oauthClientSecret:(e,a,r)=>fi.createGeneratedSecret({slug:e,environment:a,secretName:`${e}-${a}-${r}-oauth-secret`,description:`OAuth client secret for ${r}`,passwordLength:64,excludeCharacters:"\"'`\\/@",requireEachIncludedType:!0}),jwtSecret:(e,a)=>fi.createGeneratedSecret({slug:e,environment:a,secretName:`${e}-${a}-jwt-secret`,description:"JWT signing secret",passwordLength:64,excludePunctuation:!0}),encryptionKey:(e,a)=>fi.createGeneratedSecret({slug:e,environment:a,secretName:`${e}-${a}-encryption-key`,description:"Data encryption key",passwordLength:64,excludeCharacters:"+/=",excludePunctuation:!0})};static RotationTypes={MySQLSingleUser:"MySQLSingleUser",MySQLMultiUser:"MySQLMultiUser",PostgreSQLSingleUser:"PostgreSQLSingleUser",PostgreSQLMultiUser:"PostgreSQLMultiUser",OracleSingleUser:"OracleSingleUser",OracleMultiUser:"OracleMultiUser",MariaDBSingleUser:"MariaDBSingleUser",MariaDBMultiUser:"MariaDBMultiUser",SQLServerSingleUser:"SQLServerSingleUser",SQLServerMultiUser:"SQLServerMultiUser",RedshiftSingleUser:"RedshiftSingleUser",RedshiftMultiUser:"RedshiftMultiUser",MongoDBSingleUser:"MongoDBSingleUser",MongoDBMultiUser:"MongoDBMultiUser"}}class G{static createParameter(e){let{slug:a,environment:r,parameterName:n,value:i,type:o="String",description:c,tier:u="Standard",tags:d}=e,m=n||l({slug:a,environment:r,resourceType:"parameter"}),p=s(m);return{parameter:{Type:"AWS::SSM::Parameter",Properties:{Name:`/${a}/${r}/${m}`,Type:o,Value:i,Description:c,Tier:u,Tags:{Name:m,Environment:r,...d}}},logicalId:p}}static createString(e,a,r,n,i){return G.createParameter({slug:e,environment:a,parameterName:r,value:n,type:"String",description:i})}static createSecureString(e,a,r,n,i){return G.createParameter({slug:e,environment:a,parameterName:r,value:n,type:"SecureString",description:i})}static createStringList(e,a,r,n,i){return G.createParameter({slug:e,environment:a,parameterName:r,value:n.join(","),type:"StringList",description:i})}static Parameters={databaseUrl:(e,a,r)=>G.createSecureString(e,a,"database-url",r,"Database connection URL"),apiEndpoint:(e,a,r)=>G.createString(e,a,"api-endpoint",r,"API endpoint URL"),appVersion:(e,a,r)=>G.createString(e,a,"app-version",r,"Application version"),featureFlags:(e,a,r)=>G.createStringList(e,a,"feature-flags",r,"Enabled feature flags"),apiKey:(e,a,r,n)=>G.createSecureString(e,a,`${r}-api-key`,n,`API key for ${r}`),oauthCredentials:(e,a,r,n)=>{let i=G.createString(e,a,"oauth-client-id",r,"OAuth client ID"),o=G.createSecureString(e,a,"oauth-client-secret",n,"OAuth client secret");return{clientId:i,clientSecret:o}},smtpCredentials:(e,a,r,n,i,o)=>{let c=G.createString(e,a,"smtp-username",r,"SMTP username"),u=G.createSecureString(e,a,"smtp-password",n,"SMTP password"),d=G.createString(e,a,"smtp-host",i,"SMTP host"),m=G.createString(e,a,"smtp-port",o.toString(),"SMTP port");return{username:c,password:u,host:d,port:m}},redisUrl:(e,a,r)=>G.createSecureString(e,a,"redis-url",r,"Redis connection URL"),s3Bucket:(e,a,r)=>G.createString(e,a,"s3-bucket",r,"S3 bucket name"),cloudFrontDistribution:(e,a,r)=>G.createString(e,a,"cloudfront-distribution-id",r,"CloudFront distribution ID")}}class Ft{static createDomain(e){let{slug:a,environment:r,domainName:n,engineVersion:i="OpenSearch_2.11",instanceType:o="t3.small.search",instanceCount:c=1,volumeSize:u=10,volumeType:d="gp3",dedicatedMaster:m=!1,dedicatedMasterType:p,dedicatedMasterCount:g=3,multiAz:h=!1,availabilityZoneCount:y=2,vpc:f,encryption:b,enforceHttps:v=!0,tlsSecurityPolicy:w="Policy-Min-TLS-1-2-2019-07",advancedSecurity:R,autoSnapshotHour:T=0,autoTune:N=!0,tags:I={}}=e,k=n||l({slug:a,environment:r,resourceType:"search"}),x=s(k);return{domain:{Type:"AWS::OpenSearchService::Domain",Properties:{DomainName:k,EngineVersion:i,ClusterConfig:{InstanceType:o,InstanceCount:c,DedicatedMasterEnabled:m,...m&&{DedicatedMasterType:p||o,DedicatedMasterCount:g},ZoneAwarenessEnabled:h,...h&&{ZoneAwarenessConfig:{AvailabilityZoneCount:y}}},EBSOptions:{EBSEnabled:!0,VolumeType:d,VolumeSize:u},DomainEndpointOptions:{EnforceHTTPS:v,TLSSecurityPolicy:w},SnapshotOptions:{AutomatedSnapshotStartHour:T},...f&&{VPCOptions:{SubnetIds:f.subnetIds,SecurityGroupIds:f.securityGroupIds}},...b&&{EncryptionAtRestOptions:{Enabled:b.atRest??!0,...b.kmsKeyId&&{KmsKeyId:b.kmsKeyId}},NodeToNodeEncryptionOptions:{Enabled:b.nodeToNode??!0}},...R&&{AdvancedSecurityOptions:{Enabled:R.enabled,InternalUserDatabaseEnabled:R.internalUserDatabase??!0,...R.masterUserName&&R.masterUserPassword&&{MasterUserOptions:{MasterUserName:R.masterUserName,MasterUserPassword:R.masterUserPassword}},...R.masterUserArn&&{MasterUserOptions:{MasterUserARN:R.masterUserArn}}}},...N&&{AutoTuneOptions:{DesiredState:"ENABLED"}},Tags:[{Key:"Name",Value:k},{Key:"Environment",Value:r},...Object.entries(I).map(([L,O])=>({Key:L,Value:O}))]}},logicalId:x}}static createAccessPolicy(e,a){let{ipAddresses:r,iamPrincipalArns:n,allowAll:i,vpcEndpoint:o}=a;if(i)return{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:"*"},Action:"es:*",Resource:e}]};let c=[];if(n&&n.length>0)c.push({Effect:"Allow",Principal:{AWS:n},Action:"es:*",Resource:e});if(r&&r.length>0)c.push({Effect:"Allow",Principal:{AWS:"*"},Action:"es:*",Resource:e,Condition:{IpAddress:{"aws:SourceIp":r}}});if(o)return{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:"*"},Action:"es:*",Resource:e}]};return{Version:"2012-10-17",Statement:c}}static DomainPresets={development:(e,a)=>Ft.createDomain({slug:e,environment:a,instanceType:"t3.small.search",instanceCount:1,volumeSize:10,multiAz:!1,dedicatedMaster:!1,encryption:{atRest:!0,nodeToNode:!0},autoTune:!1}),production:(e,a,r)=>Ft.createDomain({slug:e,environment:a,instanceType:"m6g.large.search",instanceCount:3,volumeSize:100,volumeType:"gp3",multiAz:!0,availabilityZoneCount:3,dedicatedMaster:!0,dedicatedMasterType:"m6g.large.search",dedicatedMasterCount:3,vpc:r,encryption:{atRest:!0,nodeToNode:!0},advancedSecurity:{enabled:!0,internalUserDatabase:!0},autoTune:!0}),costOptimized:(e,a)=>Ft.createDomain({slug:e,environment:a,instanceType:"t3.medium.search",instanceCount:2,volumeSize:20,volumeType:"gp3",multiAz:!0,dedicatedMaster:!1,encryption:{atRest:!0,nodeToNode:!0},autoTune:!0}),highPerformance:(e,a,r)=>Ft.createDomain({slug:e,environment:a,instanceType:"r6g.2xlarge.search",instanceCount:6,volumeSize:500,volumeType:"gp3",multiAz:!0,availabilityZoneCount:3,dedicatedMaster:!0,dedicatedMasterType:"c6g.xlarge.search",dedicatedMasterCount:3,vpc:r,encryption:{atRest:!0,nodeToNode:!0},advancedSecurity:{enabled:!0,internalUserDatabase:!1},autoTune:!0})};static InstanceTypes={"t3.small.search":"t3.small.search","t3.medium.search":"t3.medium.search","m6g.large.search":"m6g.large.search","m6g.xlarge.search":"m6g.xlarge.search","m6g.2xlarge.search":"m6g.2xlarge.search","r6g.large.search":"r6g.large.search","r6g.xlarge.search":"r6g.xlarge.search","r6g.2xlarge.search":"r6g.2xlarge.search","r6g.4xlarge.search":"r6g.4xlarge.search","c6g.large.search":"c6g.large.search","c6g.xlarge.search":"c6g.xlarge.search","c6g.2xlarge.search":"c6g.2xlarge.search"};static EngineVersions={"OpenSearch_2.11":"OpenSearch_2.11","OpenSearch_2.9":"OpenSearch_2.9","OpenSearch_2.7":"OpenSearch_2.7","OpenSearch_1.3":"OpenSearch_1.3","Elasticsearch_7.10":"Elasticsearch_7.10"}}class Et{static createDomainRedirectBucket(e){let{slug:a,environment:r,sourceDomain:n,targetDomain:i,protocol:o="https"}=e,c=l({slug:a,environment:r,resourceType:"s3",suffix:"redirect"}),u=s(c),d=s(`${c}-policy`),m={Type:"AWS::S3::Bucket",Properties:{BucketName:n,WebsiteConfiguration:{RedirectAllRequestsTo:{HostName:i,Protocol:o}},PublicAccessBlockConfiguration:{BlockPublicAcls:!1,BlockPublicPolicy:!1,IgnorePublicAcls:!1,RestrictPublicBuckets:!1},Tags:[{Key:"Name",Value:c},{Key:"Environment",Value:r},{Key:"Purpose",Value:"Domain Redirect"}]}},p={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:P.Ref(u),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadForRedirect",Effect:"Allow",Principal:"*",Action:["s3:GetObject"],Resource:[P.Join("",[P.GetAtt(u,"Arn"),"/*"])]}]}}};return{bucket:m,bucketPolicy:p,logicalId:u,policyLogicalId:d}}static createPathRedirectFunction(e){let{slug:a,environment:r,rules:n}=e,i=l({slug:a,environment:r,resourceType:"cf-redirect"}),o=s(i),c=Et.generateRedirectFunctionCode(n);return{function:{Type:"AWS::CloudFront::Function",Properties:{Name:i,AutoPublish:!0,FunctionConfig:{Comment:`Path redirect function for ${a} (${r})`,Runtime:"cloudfront-js-2.0"},FunctionCode:c}},logicalId:o,functionCode:c}}static generateRedirectFunctionCode(e){return`function handler(event) {
|
|
2316
|
+
| limit 50`,region:n,title:"Recent Errors and Warnings"}}),c+=6;return gi.createDashboard({slug:a,environment:r,widgets:o})}static DashboardTemplates={staticWebsite:(e)=>({slug:e.slug,environment:e.environment,widgets:[{type:"text",x:0,y:0,width:24,height:1,properties:{markdown:`# ${e.slug.toUpperCase()} Static Website Dashboard`}},{type:"metric",x:0,y:1,width:8,height:6,properties:{title:"CloudFront Requests",region:"us-east-1",metrics:[["AWS/CloudFront","Requests","DistributionId",e.cloudFrontDistributionId,"Region","Global"]],period:300,stat:"Sum"}},{type:"metric",x:8,y:1,width:8,height:6,properties:{title:"Error Rate",region:"us-east-1",metrics:[["AWS/CloudFront","4xxErrorRate","DistributionId",e.cloudFrontDistributionId,"Region","Global",{label:"4XX"}],["AWS/CloudFront","5xxErrorRate","DistributionId",e.cloudFrontDistributionId,"Region","Global",{label:"5XX"}]],period:300,stat:"Average"}},{type:"metric",x:16,y:1,width:8,height:6,properties:{title:"Bytes Downloaded",region:"us-east-1",metrics:[["AWS/CloudFront","BytesDownloaded","DistributionId",e.cloudFrontDistributionId,"Region","Global"]],period:300,stat:"Sum"}},{type:"metric",x:0,y:7,width:12,height:6,properties:{title:"S3 Bucket Size",region:e.region||"us-east-1",metrics:[["AWS/S3","BucketSizeBytes","BucketName",e.s3BucketName,"StorageType","StandardStorage"]],period:86400,stat:"Average"}},{type:"metric",x:12,y:7,width:12,height:6,properties:{title:"S3 Number of Objects",region:e.region||"us-east-1",metrics:[["AWS/S3","NumberOfObjects","BucketName",e.s3BucketName,"StorageType","AllStorageTypes"]],period:86400,stat:"Average"}}]}),serverlessApi:(e)=>({slug:e.slug,environment:e.environment,widgets:[{type:"text",x:0,y:0,width:24,height:1,properties:{markdown:`# ${e.slug.toUpperCase()} Serverless API Dashboard`}},{type:"metric",x:0,y:1,width:8,height:6,properties:{title:"API Requests",region:e.region||"us-east-1",metrics:[["AWS/ApiGateway","Count","ApiName",e.apiGatewayName]],period:60,stat:"Sum"}},{type:"metric",x:8,y:1,width:8,height:6,properties:{title:"API Latency",region:e.region||"us-east-1",metrics:[["AWS/ApiGateway","Latency","ApiName",e.apiGatewayName]],period:60,stat:"Average"}},{type:"metric",x:16,y:1,width:8,height:6,properties:{title:"API Errors",region:e.region||"us-east-1",metrics:[["AWS/ApiGateway","4XXError","ApiName",e.apiGatewayName,{label:"4XX"}],["AWS/ApiGateway","5XXError","ApiName",e.apiGatewayName,{label:"5XX"}]],period:60,stat:"Sum"}},...e.lambdaFunctionNames.map((a,r)=>({type:"metric",x:r%3*8,y:7+Math.floor(r/3)*6,width:8,height:6,properties:{title:`${a} Metrics`,region:e.region||"us-east-1",metrics:[["AWS/Lambda","Invocations","FunctionName",a],["AWS/Lambda","Duration","FunctionName",a],["AWS/Lambda","Errors","FunctionName",a]],period:300,stat:"Sum"}}))]}),containerService:(e)=>({slug:e.slug,environment:e.environment,widgets:[{type:"text",x:0,y:0,width:24,height:1,properties:{markdown:`# ${e.slug.toUpperCase()} Container Service Dashboard`}},{type:"metric",x:0,y:1,width:8,height:6,properties:{title:"ECS CPU",region:e.region||"us-east-1",metrics:[["AWS/ECS","CPUUtilization","ClusterName",e.ecsClusterName,"ServiceName",e.ecsServiceName]],period:60,stat:"Average"}},{type:"metric",x:8,y:1,width:8,height:6,properties:{title:"ECS Memory",region:e.region||"us-east-1",metrics:[["AWS/ECS","MemoryUtilization","ClusterName",e.ecsClusterName,"ServiceName",e.ecsServiceName]],period:60,stat:"Average"}},{type:"metric",x:16,y:1,width:8,height:6,properties:{title:"Running Tasks",region:e.region||"us-east-1",metrics:[["ECS/ContainerInsights","RunningTaskCount","ClusterName",e.ecsClusterName,"ServiceName",e.ecsServiceName]],period:60,stat:"Average"}},{type:"metric",x:0,y:7,width:8,height:6,properties:{title:"ALB Requests",region:e.region||"us-east-1",metrics:[["AWS/ApplicationELB","RequestCount","LoadBalancer",e.albName]],period:60,stat:"Sum"}},{type:"metric",x:8,y:7,width:8,height:6,properties:{title:"Response Time",region:e.region||"us-east-1",metrics:[["AWS/ApplicationELB","TargetResponseTime","LoadBalancer",e.albName]],period:60,stat:"Average"}},{type:"metric",x:16,y:7,width:8,height:6,properties:{title:"Healthy Hosts",region:e.region||"us-east-1",metrics:[["AWS/ApplicationELB","HealthyHostCount","LoadBalancer",e.albName]],period:60,stat:"Average"}},...e.rdsInstanceId?[{type:"metric",x:0,y:13,width:12,height:6,properties:{title:"RDS CPU",region:e.region||"us-east-1",metrics:[["AWS/RDS","CPUUtilization","DBInstanceIdentifier",e.rdsInstanceId]],period:300,stat:"Average"}},{type:"metric",x:12,y:13,width:12,height:6,properties:{title:"RDS Connections",region:e.region||"us-east-1",metrics:[["AWS/RDS","DatabaseConnections","DBInstanceIdentifier",e.rdsInstanceId]],period:60,stat:"Sum"}}]:[]]})};static Config={createAlarmConfig:(e)=>{let{metricName:a,namespace:r,threshold:n,comparisonOperator:i="GreaterThanThreshold",evaluationPeriods:o=1,period:c=300,statistic:u="Average",treatMissingData:d="missing"}=e;return{MetricName:a,Namespace:r,Threshold:n,ComparisonOperator:i,EvaluationPeriods:o,Period:c,Statistic:u,TreatMissingData:d}},namespaces:{ec2:"AWS/EC2",ecs:"AWS/ECS",lambda:"AWS/Lambda",rds:"AWS/RDS",sqs:"AWS/SQS",sns:"AWS/SNS",s3:"AWS/S3",cloudfront:"AWS/CloudFront",alb:"AWS/ApplicationELB",nlb:"AWS/NetworkELB",apiGateway:"AWS/ApiGateway",dynamodb:"AWS/DynamoDB",elasticache:"AWS/ElastiCache"},comparisonOperators:{greaterThan:"GreaterThanThreshold",greaterOrEqual:"GreaterThanOrEqualToThreshold",lessThan:"LessThanThreshold",lessOrEqual:"LessThanOrEqualToThreshold"},metrics:{ec2:{cpu:{metricName:"CPUUtilization",namespace:"AWS/EC2"},networkIn:{metricName:"NetworkIn",namespace:"AWS/EC2"},networkOut:{metricName:"NetworkOut",namespace:"AWS/EC2"},statusCheck:{metricName:"StatusCheckFailed",namespace:"AWS/EC2"}},ecs:{cpu:{metricName:"CPUUtilization",namespace:"AWS/ECS"},memory:{metricName:"MemoryUtilization",namespace:"AWS/ECS"}},lambda:{invocations:{metricName:"Invocations",namespace:"AWS/Lambda"},errors:{metricName:"Errors",namespace:"AWS/Lambda"},duration:{metricName:"Duration",namespace:"AWS/Lambda"},throttles:{metricName:"Throttles",namespace:"AWS/Lambda"},concurrentExecutions:{metricName:"ConcurrentExecutions",namespace:"AWS/Lambda"}},rds:{cpu:{metricName:"CPUUtilization",namespace:"AWS/RDS"},connections:{metricName:"DatabaseConnections",namespace:"AWS/RDS"},freeStorage:{metricName:"FreeStorageSpace",namespace:"AWS/RDS"},readLatency:{metricName:"ReadLatency",namespace:"AWS/RDS"},writeLatency:{metricName:"WriteLatency",namespace:"AWS/RDS"}},alb:{requestCount:{metricName:"RequestCount",namespace:"AWS/ApplicationELB"},responseTime:{metricName:"TargetResponseTime",namespace:"AWS/ApplicationELB"},httpCode4xx:{metricName:"HTTPCode_Target_4XX_Count",namespace:"AWS/ApplicationELB"},httpCode5xx:{metricName:"HTTPCode_Target_5XX_Count",namespace:"AWS/ApplicationELB"},healthyHosts:{metricName:"HealthyHostCount",namespace:"AWS/ApplicationELB"}},sqs:{messagesVisible:{metricName:"ApproximateNumberOfMessagesVisible",namespace:"AWS/SQS"},messagesDelayed:{metricName:"ApproximateNumberOfMessagesDelayed",namespace:"AWS/SQS"},messageAge:{metricName:"ApproximateAgeOfOldestMessage",namespace:"AWS/SQS"}}},presets:{highCpu:(e=80)=>({metricName:"CPUUtilization",threshold:e,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),highMemory:(e=80)=>({metricName:"MemoryUtilization",threshold:e,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),highErrors:(e=10)=>({metricName:"Errors",threshold:e,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:1,period:60,statistic:"Sum"}),highLatency:(e=5000)=>({metricName:"Duration",threshold:e,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),lowHealthyHosts:(e=1)=>({metricName:"HealthyHostCount",namespace:"AWS/ApplicationELB",threshold:e,comparisonOperator:"LessThanThreshold",evaluationPeriods:2,period:60,statistic:"Minimum"}),queueDepth:(e=1000)=>({metricName:"ApproximateNumberOfMessagesVisible",namespace:"AWS/SQS",threshold:e,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),lowStorage:(e=10737418240)=>({metricName:"FreeStorageSpace",namespace:"AWS/RDS",threshold:e,comparisonOperator:"LessThanThreshold",evaluationPeriods:1,period:300,statistic:"Average"})}}}class Te{static createUserPool(e){let{slug:a,environment:r,userPoolName:n,aliasAttributes:i,autoVerifiedAttributes:o,passwordPolicy:c,mfaConfiguration:u,emailConfiguration:d,smsConfiguration:m,lambdaTriggers:p,userPoolAddOns:g,accountRecoverySetting:h}=e,y=n||l({slug:a,environment:r,resourceType:"user-pool"}),f=s(y),b={Type:"AWS::Cognito::UserPool",Properties:{UserPoolName:y,Policies:c?{PasswordPolicy:{MinimumLength:c.minimumLength,RequireLowercase:c.requireLowercase,RequireUppercase:c.requireUppercase,RequireNumbers:c.requireNumbers,RequireSymbols:c.requireSymbols,TemporaryPasswordValidityDays:c.temporaryPasswordValidityDays}}:void 0,MfaConfiguration:u,Schema:[{Name:"email",AttributeDataType:"String",Required:!0,Mutable:!1}]}};if(i&&i.length>0)b.Properties.UsernameAttributes=i;if(o&&o.length>0)b.Properties.AutoVerifiedAttributes=o;if(d)b.Properties.EmailConfiguration={EmailSendingAccount:d.emailSendingAccount,From:d.from,ReplyToEmailAddress:d.replyToEmailAddress,SourceArn:d.sourceArn,ConfigurationSet:d.configurationSet};if(m)b.Properties.SmsConfiguration={ExternalId:m.externalId,SnsCallerArn:m.snsCallerArn};if(p)b.Properties.LambdaConfig={PreSignUp:p.preSignUp,PostConfirmation:p.postConfirmation,PreAuthentication:p.preAuthentication,PostAuthentication:p.postAuthentication,CustomMessage:p.customMessage,DefineAuthChallenge:p.defineAuthChallenge,CreateAuthChallenge:p.createAuthChallenge,VerifyAuthChallengeResponse:p.verifyAuthChallengeResponse,PreTokenGeneration:p.preTokenGeneration,UserMigration:p.userMigration};if(g)b.Properties.UserPoolAddOns={AdvancedSecurityMode:g.advancedSecurityMode};if(h)b.Properties.AccountRecoverySetting={RecoveryMechanisms:h.recoveryMechanisms};return{userPool:b,logicalId:f}}static createUserPoolClient(e,a){let{slug:r,environment:n,clientName:i,generateSecret:o=!1,refreshTokenValidity:c,accessTokenValidity:u,idTokenValidity:d,tokenValidityUnits:m,readAttributes:p,writeAttributes:g,explicitAuthFlows:h,preventUserExistenceErrors:y,enableTokenRevocation:f,callbackURLs:b,logoutURLs:v,allowedOAuthFlows:w,allowedOAuthScopes:R,allowedOAuthFlowsUserPoolClient:T,supportedIdentityProviders:N}=a,I=i||l({slug:r,environment:n,resourceType:"user-pool-client"}),k=s(I);return{client:{Type:"AWS::Cognito::UserPoolClient",Properties:{ClientName:I,UserPoolId:P.Ref(e),GenerateSecret:o,RefreshTokenValidity:c,AccessTokenValidity:u,IdTokenValidity:d,TokenValidityUnits:m,ReadAttributes:p,WriteAttributes:g,ExplicitAuthFlows:h,PreventUserExistenceErrors:y,EnableTokenRevocation:f,CallbackURLs:b,LogoutURLs:v,AllowedOAuthFlows:w,AllowedOAuthScopes:R,AllowedOAuthFlowsUserPoolClient:T,SupportedIdentityProviders:N}},logicalId:k}}static createUserPoolDomain(e,a){let{slug:r,environment:n,domain:i,customDomainConfig:o}=a,c=l({slug:r,environment:n,resourceType:"user-pool-domain"}),u=s(c);return{domain:{Type:"AWS::Cognito::UserPoolDomain",Properties:{Domain:i,UserPoolId:P.Ref(e),CustomDomainConfig:o}},logicalId:u}}static createIdentityPool(e){let{slug:a,environment:r,identityPoolName:n,allowUnauthenticatedIdentities:i=!1,cognitoIdentityProviders:o,supportedLoginProviders:c,samlProviderARNs:u,openIdConnectProviderARNs:d}=e,m=n||l({slug:a,environment:r,resourceType:"identity-pool"}),p=s(m);return{identityPool:{Type:"AWS::Cognito::IdentityPool",Properties:{IdentityPoolName:m,AllowUnauthenticatedIdentities:i,CognitoIdentityProviders:o,SupportedLoginProviders:c,SamlProviderARNs:u,OpenIdConnectProviderARNs:d}},logicalId:p}}static createIdentityPoolRoleAttachment(e,a){let{slug:r,environment:n,authenticatedRole:i,unauthenticatedRole:o,roleMappings:c}=a,u=l({slug:r,environment:n,resourceType:"identity-pool-role-attachment"}),d=s(u),m={authenticated:i};if(o)m.unauthenticated=o;return{attachment:{Type:"AWS::Cognito::IdentityPoolRoleAttachment",Properties:{IdentityPoolId:P.Ref(e),Roles:m,RoleMappings:c}},logicalId:d}}static createAuthenticatedRole(e){let{slug:a,environment:r,identityPoolLogicalId:n}=e,i=l({slug:a,environment:r,resourceType:"cognito-authenticated-role"}),o=s(i);return{role:{Type:"AWS::IAM::Role",Properties:{RoleName:i,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Federated:"cognito-identity.amazonaws.com"},Action:"sts:AssumeRoleWithWebIdentity",Condition:{StringEquals:{"cognito-identity.amazonaws.com:aud":P.Ref(n)},"ForAnyValue:StringLike":{"cognito-identity.amazonaws.com:amr":"authenticated"}}}]},Policies:[{PolicyName:"CognitoAuthenticatedPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["cognito-sync:*","cognito-identity:*"],Resource:"*"}]}}],Tags:[{Key:"Name",Value:i},{Key:"Environment",Value:r}]}},logicalId:o}}static createUnauthenticatedRole(e){let{slug:a,environment:r,identityPoolLogicalId:n}=e,i=l({slug:a,environment:r,resourceType:"cognito-unauthenticated-role"}),o=s(i);return{role:{Type:"AWS::IAM::Role",Properties:{RoleName:i,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Federated:"cognito-identity.amazonaws.com"},Action:"sts:AssumeRoleWithWebIdentity",Condition:{StringEquals:{"cognito-identity.amazonaws.com:aud":P.Ref(n)},"ForAnyValue:StringLike":{"cognito-identity.amazonaws.com:amr":"unauthenticated"}}}]},Policies:[{PolicyName:"CognitoUnauthenticatedPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["cognito-sync:*"],Resource:"*"}]}}],Tags:[{Key:"Name",Value:i},{Key:"Environment",Value:r}]}},logicalId:o}}static PasswordPolicies={relaxed:()=>({minimumLength:8,requireLowercase:!1,requireUppercase:!1,requireNumbers:!1,requireSymbols:!1,temporaryPasswordValidityDays:7}),standard:()=>({minimumLength:8,requireLowercase:!0,requireUppercase:!0,requireNumbers:!0,requireSymbols:!1,temporaryPasswordValidityDays:3}),strict:()=>({minimumLength:12,requireLowercase:!0,requireUppercase:!0,requireNumbers:!0,requireSymbols:!0,temporaryPasswordValidityDays:1})};static AuthFlows={standard:["ALLOW_USER_SRP_AUTH","ALLOW_REFRESH_TOKEN_AUTH"],admin:["ALLOW_ADMIN_USER_PASSWORD_AUTH","ALLOW_REFRESH_TOKEN_AUTH"],custom:["ALLOW_CUSTOM_AUTH","ALLOW_REFRESH_TOKEN_AUTH"],all:["ALLOW_USER_SRP_AUTH","ALLOW_USER_PASSWORD_AUTH","ALLOW_ADMIN_USER_PASSWORD_AUTH","ALLOW_CUSTOM_AUTH","ALLOW_REFRESH_TOKEN_AUTH"]};static OAuthScopes={basic:["openid","email","profile"],all:["openid","email","profile","phone","aws.cognito.signin.user.admin"]};static UseCases={webApp:(e,a,r)=>{let{userPool:n,logicalId:i}=Te.createUserPool({slug:e,environment:a,aliasAttributes:["email"],autoVerifiedAttributes:["email"],passwordPolicy:Te.PasswordPolicies.standard(),mfaConfiguration:"OPTIONAL"}),{client:o,logicalId:c}=Te.createUserPoolClient(i,{slug:e,environment:a,explicitAuthFlows:[...Te.AuthFlows.standard],callbackURLs:[r],allowedOAuthFlows:["code"],allowedOAuthScopes:[...Te.OAuthScopes.basic],allowedOAuthFlowsUserPoolClient:!0});return{userPool:n,poolId:i,client:o,clientId:c}},mobileApp:(e,a)=>{let{userPool:r,logicalId:n}=Te.createUserPool({slug:e,environment:a,aliasAttributes:["email"],autoVerifiedAttributes:["email"],passwordPolicy:Te.PasswordPolicies.standard(),mfaConfiguration:"OPTIONAL"}),{client:i,logicalId:o}=Te.createUserPoolClient(n,{slug:e,environment:a,explicitAuthFlows:[...Te.AuthFlows.standard]}),{identityPool:c,logicalId:u}=Te.createIdentityPool({slug:e,environment:a,allowUnauthenticatedIdentities:!1,cognitoIdentityProviders:[{ClientId:P.Ref(o),ProviderName:P.GetAtt(n,"ProviderName")}]}),{role:d,logicalId:m}=Te.createAuthenticatedRole({slug:e,environment:a,identityPoolLogicalId:u}),{attachment:p,logicalId:g}=Te.createIdentityPoolRoleAttachment(u,{slug:e,environment:a,authenticatedRole:P.GetAtt(m,"Arn")});return{userPool:r,poolId:n,client:i,clientId:o,identityPool:c,identityPoolId:u,authRole:d,authRoleId:m,attachment:p,attachmentId:g}}}}class Ee{static createApplication(e){let{slug:a,environment:r,applicationName:n,computePlatform:i}=e,o=n||l({slug:a,environment:r,resourceType:"deploy-app"}),c=s(o);return{application:{Type:"AWS::CodeDeploy::Application",Properties:{ApplicationName:o,ComputePlatform:i,Tags:[{Key:"Name",Value:o},{Key:"Environment",Value:r}]}},logicalId:c}}static createDeploymentGroup(e,a){let{slug:r,environment:n,deploymentGroupName:i,serviceRoleArn:o,autoScalingGroups:c,ec2TagFilters:u,deploymentConfigName:d,autoRollbackConfiguration:m,alarmConfiguration:p,loadBalancerInfo:g,blueGreenDeploymentConfiguration:h}=a,y=i||l({slug:r,environment:n,resourceType:"deploy-group"}),f=s(y);return{deploymentGroup:{Type:"AWS::CodeDeploy::DeploymentGroup",Properties:{ApplicationName:P.Ref(e),DeploymentGroupName:y,ServiceRoleArn:o,AutoScalingGroups:c,Ec2TagFilters:u?.map((b)=>({Key:b.key,Value:b.value,Type:b.type})),DeploymentConfigName:d,AutoRollbackConfiguration:m?{Enabled:m.enabled,Events:m.events}:void 0,AlarmConfiguration:p?{Enabled:p.enabled,Alarms:p.alarms?.map((b)=>({Name:b.name})),IgnorePollAlarmFailure:p.ignorePollAlarmFailure}:void 0,LoadBalancerInfo:g?{TargetGroupInfoList:g.targetGroupInfoList?.map((b)=>({Name:b.name})),ElbInfoList:g.elbInfoList?.map((b)=>({Name:b.name}))}:void 0,BlueGreenDeploymentConfiguration:h?{TerminateBlueInstancesOnDeploymentSuccess:h.terminateBlueInstancesOnDeploymentSuccess?{Action:h.terminateBlueInstancesOnDeploymentSuccess.action,TerminationWaitTimeInMinutes:h.terminateBlueInstancesOnDeploymentSuccess.terminationWaitTimeInMinutes}:void 0,DeploymentReadyOption:h.deploymentReadyOption?{ActionOnTimeout:h.deploymentReadyOption.actionOnTimeout,WaitTimeInMinutes:h.deploymentReadyOption.waitTimeInMinutes}:void 0,GreenFleetProvisioningOption:h.greenFleetProvisioningOption?{Action:h.greenFleetProvisioningOption.action}:void 0}:void 0,Tags:[{Key:"Name",Value:y},{Key:"Environment",Value:n}]}},logicalId:f}}static createDeploymentConfig(e){let{slug:a,environment:r,deploymentConfigName:n,minimumHealthyHosts:i,trafficRoutingConfig:o}=e,c=n||l({slug:a,environment:r,resourceType:"deploy-config"}),u=s(c);return{deploymentConfig:{Type:"AWS::CodeDeploy::DeploymentConfig",Properties:{DeploymentConfigName:c,MinimumHealthyHosts:i?{Type:i.type,Value:i.value}:void 0,TrafficRoutingConfig:o?{Type:o.type,TimeBasedCanary:o.timeBasedCanary?{CanaryPercentage:o.timeBasedCanary.canaryPercentage,CanaryInterval:o.timeBasedCanary.canaryInterval}:void 0,TimeBasedLinear:o.timeBasedLinear?{LinearPercentage:o.timeBasedLinear.linearPercentage,LinearInterval:o.timeBasedLinear.linearInterval}:void 0}:void 0}},logicalId:u}}static DeploymentConfigs={allAtOnce:()=>({type:"FLEET_PERCENT",value:0}),halfAtATime:()=>({type:"FLEET_PERCENT",value:50}),oneAtATime:()=>({type:"HOST_COUNT",value:1}),custom:(e,a)=>({type:e,value:a})};static TrafficRouting={allAtOnce:()=>({type:"AllAtOnce"}),canary:(e,a)=>({type:"TimeBasedCanary",timeBasedCanary:{canaryPercentage:e,canaryInterval:a}}),linear:(e,a)=>({type:"TimeBasedLinear",timeBasedLinear:{linearPercentage:e,linearInterval:a}})};static RollbackConfigs={onFailure:()=>({enabled:!0,events:["DEPLOYMENT_FAILURE"]}),onAlarmOrFailure:()=>({enabled:!0,events:["DEPLOYMENT_FAILURE","DEPLOYMENT_STOP_ON_ALARM"]}),onAllEvents:()=>({enabled:!0,events:["DEPLOYMENT_FAILURE","DEPLOYMENT_STOP_ON_ALARM","DEPLOYMENT_STOP_ON_REQUEST"]}),disabled:()=>({enabled:!1})};static BlueGreenConfigs={standard:()=>({terminateBlueInstancesOnDeploymentSuccess:{action:"TERMINATE",terminationWaitTimeInMinutes:5},deploymentReadyOption:{actionOnTimeout:"CONTINUE_DEPLOYMENT",waitTimeInMinutes:0},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}}),withDelay:(e)=>({terminateBlueInstancesOnDeploymentSuccess:{action:"TERMINATE",terminationWaitTimeInMinutes:e},deploymentReadyOption:{actionOnTimeout:"CONTINUE_DEPLOYMENT",waitTimeInMinutes:0},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}}),withManualApproval:(e)=>({terminateBlueInstancesOnDeploymentSuccess:{action:"TERMINATE",terminationWaitTimeInMinutes:5},deploymentReadyOption:{actionOnTimeout:"STOP_DEPLOYMENT",waitTimeInMinutes:e},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}}),keepBlue:()=>({terminateBlueInstancesOnDeploymentSuccess:{action:"KEEP_ALIVE"},deploymentReadyOption:{actionOnTimeout:"CONTINUE_DEPLOYMENT",waitTimeInMinutes:0},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}})};static UseCases={ec2Deployment:(e,a,r,n)=>{let{application:i,logicalId:o}=Ee.createApplication({slug:e,environment:a,computePlatform:"Server"}),{deploymentGroup:c,logicalId:u}=Ee.createDeploymentGroup(o,{slug:e,environment:a,serviceRoleArn:r,autoScalingGroups:n,deploymentConfigName:"CodeDeployDefault.OneAtATime",autoRollbackConfiguration:Ee.RollbackConfigs.onFailure()});return{application:i,appId:o,deploymentGroup:c,groupId:u}},lambdaCanaryDeployment:(e,a,r,n=10,i=5)=>{let{application:o,logicalId:c}=Ee.createApplication({slug:e,environment:a,computePlatform:"Lambda"}),{deploymentConfig:u,logicalId:d}=Ee.createDeploymentConfig({slug:e,environment:a,trafficRoutingConfig:Ee.TrafficRouting.canary(n,i)}),{deploymentGroup:m,logicalId:p}=Ee.createDeploymentGroup(c,{slug:e,environment:a,serviceRoleArn:r,deploymentConfigName:P.Ref(d),autoRollbackConfiguration:Ee.RollbackConfigs.onAlarmOrFailure()});return{application:o,appId:c,deploymentConfig:u,configId:d,deploymentGroup:m,groupId:p}},ecsBlueGreenDeployment:(e,a,r,n)=>{let{application:i,logicalId:o}=Ee.createApplication({slug:e,environment:a,computePlatform:"ECS"}),{deploymentGroup:c,logicalId:u}=Ee.createDeploymentGroup(o,{slug:e,environment:a,serviceRoleArn:r,loadBalancerInfo:{targetGroupInfoList:[{name:n}]},blueGreenDeploymentConfiguration:Ee.BlueGreenConfigs.standard(),autoRollbackConfiguration:Ee.RollbackConfigs.onFailure()});return{application:i,appId:o,deploymentGroup:c,groupId:u}}};static Strategies={rolling:(e=25)=>({type:"rolling",batchPercentage:e}),blueGreen:()=>({type:"blue-green"}),canary:(e=10,a=5)=>({type:"canary",canaryPercentage:e,canaryInterval:a}),allAtOnce:()=>({type:"all-at-once"})}}class ee{static ContentTypes={".html":"text/html",".htm":"text/html",".css":"text/css",".js":"application/javascript",".mjs":"application/javascript",".json":"application/json",".xml":"application/xml",".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",".eot":"application/vnd.ms-fontobject",".pdf":"application/pdf",".txt":"text/plain",".md":"text/markdown",".map":"application/json"};static NoHashPatterns=[/^index\.html$/,/^favicon\.ico$/,/^robots\.txt$/,/^sitemap\.xml$/,/^manifest\.json$/,/^\.well-known\//,/^_redirects$/,/^_headers$/];static computeFileHash(e,a="md5"){let r=tt(e);return Gr(a).update(r).digest("hex")}static computeShortHash(e){return ee.computeFileHash(e).slice(0,8)}static getContentType(e){let a=ga(e).toLowerCase();return ee.ContentTypes[a]||"application/octet-stream"}static shouldHashFile(e,a){return![...ee.NoHashPatterns,...a||[]].some((r)=>r.test(e))}static generateHashedFilename(e,a){let r=ga(e),n=jr(e,r),i=pa(e);if(i===".")return`${n}.${a}${r}`;return Fe(i,`${n}.${a}${r}`)}static collectFiles(e,a){let r=[],n=a||e;if(!Ct(e))return r;let i=Ur(e,{withFileTypes:!0});for(let o of i){let c=Fe(e,o.name);if(o.isDirectory())r.push(...ee.collectFiles(c,n));else if(o.isFile())r.push(c)}return r}static hashDirectory(e){let{sourceDir:a,outputDir:r,excludePatterns:n=[],hashAlgorithm:i="md5",copyUnhashed:o=!0}=e,c=ee.collectFiles(a),u=[],d={};for(let p of c){let g=p.replace(a,"").replace(/^[/\\]/,""),h=ee.shouldHashFile(g,n),y=Vr(p),f=h?ee.computeFileHash(p,i).slice(0,8):"",b=h?ee.generateHashedFilename(g,f):g,v={originalPath:g,hashedPath:b,hash:f,size:y.size,contentType:ee.getContentType(p)};if(u.push(v),d[g]=b,r){let w=Fe(r,b),R=pa(w);if(!Ct(R)){let{mkdirSync:T}=or("node:fs");T(R,{recursive:!0})}if(h||o)Fr(p,w)}}let m={version:"1.0",timestamp:new Date().toISOString(),assets:u,hashMap:d};if(r){let p=Fe(r,"asset-manifest.json");at(p,JSON.stringify(m,null,2))}return m}static getInvalidationPaths(e,a){let r=[];if(!e)return["/*"];let n=e.hashMap,i=a.hashMap;for(let[o,c]of Object.entries(i)){let u=n[o];if(!u||u!==c){if(r.push(`/${o}`),u&&u!==c)r.push(`/${u}`)}}for(let[o,c]of Object.entries(n))if(!i[o])r.push(`/${o}`),r.push(`/${c}`);if(r.length>100)return["/*"];return[...new Set(r)]}static updateHtmlReferences(e){let{htmlDir:a,manifest:r,basePath:n=""}=e,i=ee.collectFiles(a).filter((o)=>o.endsWith(".html")||o.endsWith(".htm"));for(let o of i){let c=tt(o,"utf-8");for(let[u,d]of Object.entries(r.hashMap)){if(u===d)continue;let m=[new RegExp(`(src|href)=["']${n}/?${ee.escapeRegExp(u)}["']`,"g"),new RegExp(`url\\(["']?${n}/?${ee.escapeRegExp(u)}["']?\\)`,"g")];for(let p of m)c=c.replace(p,(g)=>g.replace(u,d))}at(o,c)}}static updateCssReferences(e){let{cssDir:a,manifest:r,basePath:n=""}=e,i=ee.collectFiles(a).filter((o)=>o.endsWith(".css"));for(let o of i){let c=tt(o,"utf-8");for(let[u,d]of Object.entries(r.hashMap)){if(u===d)continue;let m=new RegExp(`url\\(["']?${n}/?${ee.escapeRegExp(u)}["']?\\)`,"g");c=c.replace(m,`url(${n}/${d})`)}at(o,c)}}static escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}static generateS3DeploymentManifest(e){let{sourceDir:a,keyPrefix:r="",excludePatterns:n=[],cacheControl:i={hashed:"public, max-age=31536000, immutable",unhashed:"public, max-age=3600",html:"public, max-age=0, must-revalidate"}}=e;return ee.hashDirectory({sourceDir:a,excludePatterns:n}).assets.map((o)=>{let c=o.hash!=="",u=o.contentType==="text/html",d=i.unhashed||"public, max-age=3600";if(u)d=i.html||"public, max-age=0, must-revalidate";else if(c)d=i.hashed||"public, max-age=31536000, immutable";return{localPath:Fe(a,o.originalPath),s3Key:r?`${r}/${o.hashedPath}`:o.hashedPath,contentType:o.contentType,cacheControl:d,hash:o.hash}})}static compareManifests(e,a){let r={added:[],removed:[],changed:[],unchanged:[]},n=new Set(Object.keys(e.hashMap)),i=new Set(Object.keys(a.hashMap));for(let o of i)if(!n.has(o))r.added.push(o);for(let o of n)if(!i.has(o))r.removed.push(o);for(let o of i)if(n.has(o))if(e.hashMap[o]!==a.hashMap[o])r.changed.push(o);else r.unchanged.push(o);return r}static loadManifest(e){if(!Ct(e))return null;try{let a=tt(e,"utf-8");return JSON.parse(a)}catch{return null}}static saveManifest(e,a){at(a,JSON.stringify(e,null,2))}}class fi{static createSecret(e){let{slug:a,environment:r,secretName:n,description:i,secretString:o,kmsKeyId:c,tags:u}=e,d=n||l({slug:a,environment:r,resourceType:"secret"}),m=s(d),p={Type:"AWS::SecretsManager::Secret",Properties:{Name:d,Description:i,SecretString:o,Tags:[{Key:"Name",Value:d},{Key:"Environment",Value:r},...u?Object.entries(u).map(([g,h])=>({Key:g,Value:h})):[]]}};if(c)p.Properties.KmsKeyId=c;return{secret:p,logicalId:m}}static createGeneratedSecret(e){let{slug:a,environment:r,secretName:n,description:i,excludeCharacters:o,excludeLowercase:c,excludeNumbers:u,excludePunctuation:d,excludeUppercase:m,passwordLength:p,requireEachIncludedType:g,kmsKeyId:h,tags:y}=e,f=n||l({slug:a,environment:r,resourceType:"secret"}),b=s(f),v={Type:"AWS::SecretsManager::Secret",Properties:{Name:f,Description:i,GenerateSecretString:{ExcludeCharacters:o,ExcludeLowercase:c,ExcludeNumbers:u,ExcludePunctuation:d,ExcludeUppercase:m,PasswordLength:p||32,RequireEachIncludedType:g!==!1},Tags:[{Key:"Name",Value:f},{Key:"Environment",Value:r},...y?Object.entries(y).map(([w,R])=>({Key:w,Value:R})):[]]}};if(h)v.Properties.KmsKeyId=h;return{secret:v,logicalId:b}}static createDatabaseSecret(e){let{slug:a,environment:r,secretName:n,username:i,dbname:o,engine:c,host:u,port:d,kmsKeyId:m}=e,p=n||l({slug:a,environment:r,resourceType:"db-secret"}),g=s(p),h={username:i};if(o)h.dbname=o;if(c)h.engine=c;if(u)h.host=u;if(d)h.port=d;let y={Type:"AWS::SecretsManager::Secret",Properties:{Name:p,Description:`Database credentials for ${i}`,GenerateSecretString:{SecretStringTemplate:JSON.stringify(h),GenerateStringKey:"password",PasswordLength:32,ExcludeCharacters:'"@/\\',RequireEachIncludedType:!0},Tags:[{Key:"Name",Value:p},{Key:"Environment",Value:r},{Key:"Type",Value:"database"}]}};if(m)y.Properties.KmsKeyId=m;return{secret:y,logicalId:g}}static attachToDatabase(e){let{slug:a,environment:r,secretId:n,targetId:i,targetType:o}=e,c=l({slug:a,environment:r,resourceType:"secret-attachment"}),u=s(c);return{attachment:{Type:"AWS::SecretsManager::SecretTargetAttachment",Properties:{SecretId:n,TargetId:i,TargetType:o}},logicalId:u}}static enableRotation(e){let{slug:a,environment:r,secretId:n,rotationLambdaArn:i,automaticallyAfterDays:o,rotationType:c,kmsKeyArn:u,vpcSecurityGroupIds:d,vpcSubnetIds:m}=e,p=l({slug:a,environment:r,resourceType:"secret-rotation"}),g=s(p),h={Type:"AWS::SecretsManager::RotationSchedule",Properties:{SecretId:n,RotationRules:{AutomaticallyAfterDays:o||30}}};if(i)h.Properties.RotationLambdaARN=i;else if(c)h.Properties.HostedRotationLambda={RotationType:c,KmsKeyArn:u,VpcSecurityGroupIds:d,VpcSubnetIds:m};return{rotation:h,logicalId:g}}static SecretTypes={apiKey:(e,a,r)=>fi.createGeneratedSecret({slug:e,environment:a,secretName:`${e}-${a}-${r}-api-key`,description:`API key for ${r}`,passwordLength:32,excludePunctuation:!0,excludeLowercase:!1,excludeUppercase:!1,excludeNumbers:!1}),oauthClientSecret:(e,a,r)=>fi.createGeneratedSecret({slug:e,environment:a,secretName:`${e}-${a}-${r}-oauth-secret`,description:`OAuth client secret for ${r}`,passwordLength:64,excludeCharacters:"\"'`\\/@",requireEachIncludedType:!0}),jwtSecret:(e,a)=>fi.createGeneratedSecret({slug:e,environment:a,secretName:`${e}-${a}-jwt-secret`,description:"JWT signing secret",passwordLength:64,excludePunctuation:!0}),encryptionKey:(e,a)=>fi.createGeneratedSecret({slug:e,environment:a,secretName:`${e}-${a}-encryption-key`,description:"Data encryption key",passwordLength:64,excludeCharacters:"+/=",excludePunctuation:!0})};static RotationTypes={MySQLSingleUser:"MySQLSingleUser",MySQLMultiUser:"MySQLMultiUser",PostgreSQLSingleUser:"PostgreSQLSingleUser",PostgreSQLMultiUser:"PostgreSQLMultiUser",OracleSingleUser:"OracleSingleUser",OracleMultiUser:"OracleMultiUser",MariaDBSingleUser:"MariaDBSingleUser",MariaDBMultiUser:"MariaDBMultiUser",SQLServerSingleUser:"SQLServerSingleUser",SQLServerMultiUser:"SQLServerMultiUser",RedshiftSingleUser:"RedshiftSingleUser",RedshiftMultiUser:"RedshiftMultiUser",MongoDBSingleUser:"MongoDBSingleUser",MongoDBMultiUser:"MongoDBMultiUser"}}class G{static createParameter(e){let{slug:a,environment:r,parameterName:n,value:i,type:o="String",description:c,tier:u="Standard",tags:d}=e,m=n||l({slug:a,environment:r,resourceType:"parameter"}),p=s(m);return{parameter:{Type:"AWS::SSM::Parameter",Properties:{Name:`/${a}/${r}/${m}`,Type:o,Value:i,Description:c,Tier:u,Tags:{Name:m,Environment:r,...d}}},logicalId:p}}static createString(e,a,r,n,i){return G.createParameter({slug:e,environment:a,parameterName:r,value:n,type:"String",description:i})}static createSecureString(e,a,r,n,i){return G.createParameter({slug:e,environment:a,parameterName:r,value:n,type:"SecureString",description:i})}static createStringList(e,a,r,n,i){return G.createParameter({slug:e,environment:a,parameterName:r,value:n.join(","),type:"StringList",description:i})}static Parameters={databaseUrl:(e,a,r)=>G.createSecureString(e,a,"database-url",r,"Database connection URL"),apiEndpoint:(e,a,r)=>G.createString(e,a,"api-endpoint",r,"API endpoint URL"),appVersion:(e,a,r)=>G.createString(e,a,"app-version",r,"Application version"),featureFlags:(e,a,r)=>G.createStringList(e,a,"feature-flags",r,"Enabled feature flags"),apiKey:(e,a,r,n)=>G.createSecureString(e,a,`${r}-api-key`,n,`API key for ${r}`),oauthCredentials:(e,a,r,n)=>{let i=G.createString(e,a,"oauth-client-id",r,"OAuth client ID"),o=G.createSecureString(e,a,"oauth-client-secret",n,"OAuth client secret");return{clientId:i,clientSecret:o}},smtpCredentials:(e,a,r,n,i,o)=>{let c=G.createString(e,a,"smtp-username",r,"SMTP username"),u=G.createSecureString(e,a,"smtp-password",n,"SMTP password"),d=G.createString(e,a,"smtp-host",i,"SMTP host"),m=G.createString(e,a,"smtp-port",o.toString(),"SMTP port");return{username:c,password:u,host:d,port:m}},redisUrl:(e,a,r)=>G.createSecureString(e,a,"redis-url",r,"Redis connection URL"),s3Bucket:(e,a,r)=>G.createString(e,a,"s3-bucket",r,"S3 bucket name"),cloudFrontDistribution:(e,a,r)=>G.createString(e,a,"cloudfront-distribution-id",r,"CloudFront distribution ID")}}class Ft{static createDomain(e){let{slug:a,environment:r,domainName:n,engineVersion:i="OpenSearch_2.11",instanceType:o="t3.small.search",instanceCount:c=1,volumeSize:u=10,volumeType:d="gp3",dedicatedMaster:m=!1,dedicatedMasterType:p,dedicatedMasterCount:g=3,multiAz:h=!1,availabilityZoneCount:y=2,vpc:f,encryption:b,enforceHttps:v=!0,tlsSecurityPolicy:w="Policy-Min-TLS-1-2-2019-07",advancedSecurity:R,autoSnapshotHour:T=0,autoTune:N=!0,tags:I={}}=e,k=n||l({slug:a,environment:r,resourceType:"search"}),O=s(k);return{domain:{Type:"AWS::OpenSearchService::Domain",Properties:{DomainName:k,EngineVersion:i,ClusterConfig:{InstanceType:o,InstanceCount:c,DedicatedMasterEnabled:m,...m&&{DedicatedMasterType:p||o,DedicatedMasterCount:g},ZoneAwarenessEnabled:h,...h&&{ZoneAwarenessConfig:{AvailabilityZoneCount:y}}},EBSOptions:{EBSEnabled:!0,VolumeType:d,VolumeSize:u},DomainEndpointOptions:{EnforceHTTPS:v,TLSSecurityPolicy:w},SnapshotOptions:{AutomatedSnapshotStartHour:T},...f&&{VPCOptions:{SubnetIds:f.subnetIds,SecurityGroupIds:f.securityGroupIds}},...b&&{EncryptionAtRestOptions:{Enabled:b.atRest??!0,...b.kmsKeyId&&{KmsKeyId:b.kmsKeyId}},NodeToNodeEncryptionOptions:{Enabled:b.nodeToNode??!0}},...R&&{AdvancedSecurityOptions:{Enabled:R.enabled,InternalUserDatabaseEnabled:R.internalUserDatabase??!0,...R.masterUserName&&R.masterUserPassword&&{MasterUserOptions:{MasterUserName:R.masterUserName,MasterUserPassword:R.masterUserPassword}},...R.masterUserArn&&{MasterUserOptions:{MasterUserARN:R.masterUserArn}}}},...N&&{AutoTuneOptions:{DesiredState:"ENABLED"}},Tags:[{Key:"Name",Value:k},{Key:"Environment",Value:r},...Object.entries(I).map(([L,_])=>({Key:L,Value:_}))]}},logicalId:O}}static createAccessPolicy(e,a){let{ipAddresses:r,iamPrincipalArns:n,allowAll:i,vpcEndpoint:o}=a;if(i)return{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:"*"},Action:"es:*",Resource:e}]};let c=[];if(n&&n.length>0)c.push({Effect:"Allow",Principal:{AWS:n},Action:"es:*",Resource:e});if(r&&r.length>0)c.push({Effect:"Allow",Principal:{AWS:"*"},Action:"es:*",Resource:e,Condition:{IpAddress:{"aws:SourceIp":r}}});if(o)return{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:"*"},Action:"es:*",Resource:e}]};return{Version:"2012-10-17",Statement:c}}static DomainPresets={development:(e,a)=>Ft.createDomain({slug:e,environment:a,instanceType:"t3.small.search",instanceCount:1,volumeSize:10,multiAz:!1,dedicatedMaster:!1,encryption:{atRest:!0,nodeToNode:!0},autoTune:!1}),production:(e,a,r)=>Ft.createDomain({slug:e,environment:a,instanceType:"m6g.large.search",instanceCount:3,volumeSize:100,volumeType:"gp3",multiAz:!0,availabilityZoneCount:3,dedicatedMaster:!0,dedicatedMasterType:"m6g.large.search",dedicatedMasterCount:3,vpc:r,encryption:{atRest:!0,nodeToNode:!0},advancedSecurity:{enabled:!0,internalUserDatabase:!0},autoTune:!0}),costOptimized:(e,a)=>Ft.createDomain({slug:e,environment:a,instanceType:"t3.medium.search",instanceCount:2,volumeSize:20,volumeType:"gp3",multiAz:!0,dedicatedMaster:!1,encryption:{atRest:!0,nodeToNode:!0},autoTune:!0}),highPerformance:(e,a,r)=>Ft.createDomain({slug:e,environment:a,instanceType:"r6g.2xlarge.search",instanceCount:6,volumeSize:500,volumeType:"gp3",multiAz:!0,availabilityZoneCount:3,dedicatedMaster:!0,dedicatedMasterType:"c6g.xlarge.search",dedicatedMasterCount:3,vpc:r,encryption:{atRest:!0,nodeToNode:!0},advancedSecurity:{enabled:!0,internalUserDatabase:!1},autoTune:!0})};static InstanceTypes={"t3.small.search":"t3.small.search","t3.medium.search":"t3.medium.search","m6g.large.search":"m6g.large.search","m6g.xlarge.search":"m6g.xlarge.search","m6g.2xlarge.search":"m6g.2xlarge.search","r6g.large.search":"r6g.large.search","r6g.xlarge.search":"r6g.xlarge.search","r6g.2xlarge.search":"r6g.2xlarge.search","r6g.4xlarge.search":"r6g.4xlarge.search","c6g.large.search":"c6g.large.search","c6g.xlarge.search":"c6g.xlarge.search","c6g.2xlarge.search":"c6g.2xlarge.search"};static EngineVersions={"OpenSearch_2.11":"OpenSearch_2.11","OpenSearch_2.9":"OpenSearch_2.9","OpenSearch_2.7":"OpenSearch_2.7","OpenSearch_1.3":"OpenSearch_1.3","Elasticsearch_7.10":"Elasticsearch_7.10"}}class Et{static createDomainRedirectBucket(e){let{slug:a,environment:r,sourceDomain:n,targetDomain:i,protocol:o="https"}=e,c=l({slug:a,environment:r,resourceType:"s3",suffix:"redirect"}),u=s(c),d=s(`${c}-policy`),m={Type:"AWS::S3::Bucket",Properties:{BucketName:n,WebsiteConfiguration:{RedirectAllRequestsTo:{HostName:i,Protocol:o}},PublicAccessBlockConfiguration:{BlockPublicAcls:!1,BlockPublicPolicy:!1,IgnorePublicAcls:!1,RestrictPublicBuckets:!1},Tags:[{Key:"Name",Value:c},{Key:"Environment",Value:r},{Key:"Purpose",Value:"Domain Redirect"}]}},p={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:P.Ref(u),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadForRedirect",Effect:"Allow",Principal:"*",Action:["s3:GetObject"],Resource:[P.Join("",[P.GetAtt(u,"Arn"),"/*"])]}]}}};return{bucket:m,bucketPolicy:p,logicalId:u,policyLogicalId:d}}static createPathRedirectFunction(e){let{slug:a,environment:r,rules:n}=e,i=l({slug:a,environment:r,resourceType:"cf-redirect"}),o=s(i),c=Et.generateRedirectFunctionCode(n);return{function:{Type:"AWS::CloudFront::Function",Properties:{Name:i,AutoPublish:!0,FunctionConfig:{Comment:`Path redirect function for ${a} (${r})`,Runtime:"cloudfront-js-2.0"},FunctionCode:c}},logicalId:o,functionCode:c}}static generateRedirectFunctionCode(e){return`function handler(event) {
|
|
2317
2317
|
const request = event.request;
|
|
2318
2318
|
const uri = request.uri;
|
|
2319
2319
|
const querystring = request.querystring;
|
|
@@ -2490,10 +2490,10 @@ rpm -U ./amazon-cloudwatch-agent.rpm || true
|
|
|
2490
2490
|
# Install Node.js or PHP/Python based on app needs
|
|
2491
2491
|
# Configure application server (PM2, Nginx, Apache)
|
|
2492
2492
|
# Mount EFS for shared file storage
|
|
2493
|
-
`}},storage:{uploads:{type:"efs",performanceMode:"generalPurpose",throughputMode:"bursting",encrypted:!0,lifecyclePolicy:{transitionToIA:30}},backups:{public:!1,versioning:!0,encryption:!0,lifecycleRules:[{id:"ArchiveOldBackups",enabled:!0,transitions:[{days:90,storageClass:"GLACIER"}]}]},static:{public:!0,versioning:!1,encryption:!1,cors:[{allowedOrigins:[n||"*"],allowedMethods:["GET","HEAD"]}]}},cdn:{enabled:!0,origins:[{originId:"static-assets",domainName:`${r}-static.s3.amazonaws.com`,pathPattern:"/static/*"}],customDomain:n?{domain:n,certificateArn:"TO_BE_GENERATED"}:void 0,cachePolicy:{minTTL:0,defaultTTL:86400,maxTTL:31536000},compress:!0,http3:!0},databases:u==="mysql"?{mysql:{engine:"mysql",version:"8.0",instanceClass:"db.t3.medium",allocatedStorage:100,maxAllocatedStorage:500,multiAZ:!0,backupRetentionDays:14,preferredBackupWindow:"03:00-04:00",preferredMaintenanceWindow:"sun:04:00-sun:05:00",enablePerformanceInsights:!0,performanceInsightsRetention:7,deletionProtection:!0,parameters:{max_connections:"500",innodb_buffer_pool_size:"{DBInstanceClassMemory*3/4}",slow_query_log:"1",long_query_time:"2"}}}:{postgres:{engine:"postgres",version:"15",instanceClass:"db.t3.medium",allocatedStorage:100,maxAllocatedStorage:500,multiAZ:!0,backupRetentionDays:14,preferredBackupWindow:"03:00-04:00",preferredMaintenanceWindow:"sun:04:00-sun:05:00",enablePerformanceInsights:!0,performanceInsightsRetention:7,deletionProtection:!0,parameters:{max_connections:"500",shared_buffers:"{DBInstanceClassMemory/4}",log_min_duration_statement:"2000"}}},cache:d==="redis"?{redis:{nodeType:"cache.t3.medium",numCacheNodes:2,engine:"redis",engineVersion:"7.0",port:6379,parameterGroup:{maxmemoryPolicy:"allkeys-lru",timeout:"300"},snapshotRetentionLimit:5,snapshotWindow:"03:00-05:00",automaticFailoverEnabled:!0}}:void 0,queues:{jobs:{fifo:!1,visibilityTimeout:900,messageRetentionPeriod:345600,receiveMessageWaitTime:20,deadLetterQueue:!0,maxReceiveCount:3},emails:{fifo:!1,visibilityTimeout:300,messageRetentionPeriod:86400,deadLetterQueue:!0}},functions:{"job-worker":{runtime:"nodejs20.x",handler:"dist/workers/jobs.handler",memory:2048,timeout:900,events:[{type:"sqs",queueName:`${r}-jobs`,batchSize:10}]},"email-sender":{runtime:"nodejs20.x",handler:"dist/workers/email.handler",memory:512,timeout:60,events:[{type:"sqs",queueName:`${r}-emails`,batchSize:10}]},cleanup:{runtime:"nodejs20.x",handler:"dist/tasks/cleanup.handler",memory:512,timeout:300,events:[{type:"schedule",expression:"cron(0 2 * * ? *)"}]}},monitoring:{dashboard:{name:`${r}-web-app`,widgets:[{type:"metric",metrics:["EC2CPUUtilization","ALBRequestCount","ALBTargetResponseTime","RDSCPUUtilization","RDSDatabaseConnections","RDSReadLatency","RDSWriteLatency"]}]},alarms:[{metric:"EC2CPUUtilization",threshold:80,evaluationPeriods:2},{metric:"RDSCPUUtilization",threshold:80,evaluationPeriods:2},{metric:"RDSDatabaseConnections",threshold:400,evaluationPeriods:1},{metric:"ALBTargetResponseTime",threshold:2000,evaluationPeriods:2},{metric:"ALBUnhealthyHostCount",threshold:1,evaluationPeriods:1}],logs:{retention:14,groups:[`${r}-app`,`${r}-nginx`,`${r}-workers`]}},security:{certificate:n?{domain:n,validationMethod:"DNS"}:void 0,waf:{enabled:!0,rules:["rateLimit","sqlInjection","xss","knownBadInputs"]},securityGroups:{alb:{ingress:[{port:80,protocol:"tcp",cidr:"0.0.0.0/0"},{port:443,protocol:"tcp",cidr:"0.0.0.0/0"}]},app:{ingress:[{port:3000,protocol:"tcp",source:"alb-sg"}]},database:{ingress:[{port:u==="mysql"?3306:5432,protocol:"tcp",source:"app-sg"}]},...d==="redis"&&{cache:{ingress:[{port:6379,protocol:"tcp",source:"app-sg"}]}}}}}}}function Dp(e){let{name:a,slug:r,domain:n,repository:i,phpVersion:o="8.3",size:c="small",database:u=r.replace(/-/g,"_"),databasePassword:d,sslEmail:m,deployStrategy:p="push",provider:g="hetzner"}=e;return{project:{name:a,slug:r,region:"us-east-1"},mode:"server",cloud:{provider:g},environments:{production:{type:"production",domain:n}},infrastructure:{compute:{mode:"server",size:c,runtime:"php",webServer:"nginx",php:{versions:[o],default:o},managedServices:{mysql:!0,redis:!0},firewall:{enabled:!0},autoUpdates:!0,monitoring:!0,backups:{enabled:!0,schedule:"0 2 * * *",retentionCount:7}},appDatabase:{engine:"mysql",name:u,username:u,password:d}},sites:{main:{root:".",type:"laravel",domain:n,phpVersion:o,repository:{...i,strategy:p},scheduler:!0,queues:[{connection:"redis",queue:"default",processes:1}],ssl:{provider:"letsencrypt",email:m}}}}}function kp(e){let{name:a,slug:r,domain:n,layers:i,phpVersion:o="8.3",architecture:c="x86_64",memory:u=1024,build:d,deploy:m=["migrate --force"],cache:p="dynamodb",scheduler:g="on",region:h="us-east-1"}=e;return{project:{name:a,slug:r,region:h},mode:"serverless",environments:{production:{type:"production",domain:n,app:{kind:"php",runtime:"provided.al2023",phpVersion:o,architecture:c,layers:i,memory:u,build:d,deploy:m,assets:"public",queues:!0,scheduler:g,cache:{driver:p},domain:n}}}}}function
|
|
2493
|
+
`}},storage:{uploads:{type:"efs",performanceMode:"generalPurpose",throughputMode:"bursting",encrypted:!0,lifecyclePolicy:{transitionToIA:30}},backups:{public:!1,versioning:!0,encryption:!0,lifecycleRules:[{id:"ArchiveOldBackups",enabled:!0,transitions:[{days:90,storageClass:"GLACIER"}]}]},static:{public:!0,versioning:!1,encryption:!1,cors:[{allowedOrigins:[n||"*"],allowedMethods:["GET","HEAD"]}]}},cdn:{enabled:!0,origins:[{originId:"static-assets",domainName:`${r}-static.s3.amazonaws.com`,pathPattern:"/static/*"}],customDomain:n?{domain:n,certificateArn:"TO_BE_GENERATED"}:void 0,cachePolicy:{minTTL:0,defaultTTL:86400,maxTTL:31536000},compress:!0,http3:!0},databases:u==="mysql"?{mysql:{engine:"mysql",version:"8.0",instanceClass:"db.t3.medium",allocatedStorage:100,maxAllocatedStorage:500,multiAZ:!0,backupRetentionDays:14,preferredBackupWindow:"03:00-04:00",preferredMaintenanceWindow:"sun:04:00-sun:05:00",enablePerformanceInsights:!0,performanceInsightsRetention:7,deletionProtection:!0,parameters:{max_connections:"500",innodb_buffer_pool_size:"{DBInstanceClassMemory*3/4}",slow_query_log:"1",long_query_time:"2"}}}:{postgres:{engine:"postgres",version:"15",instanceClass:"db.t3.medium",allocatedStorage:100,maxAllocatedStorage:500,multiAZ:!0,backupRetentionDays:14,preferredBackupWindow:"03:00-04:00",preferredMaintenanceWindow:"sun:04:00-sun:05:00",enablePerformanceInsights:!0,performanceInsightsRetention:7,deletionProtection:!0,parameters:{max_connections:"500",shared_buffers:"{DBInstanceClassMemory/4}",log_min_duration_statement:"2000"}}},cache:d==="redis"?{redis:{nodeType:"cache.t3.medium",numCacheNodes:2,engine:"redis",engineVersion:"7.0",port:6379,parameterGroup:{maxmemoryPolicy:"allkeys-lru",timeout:"300"},snapshotRetentionLimit:5,snapshotWindow:"03:00-05:00",automaticFailoverEnabled:!0}}:void 0,queues:{jobs:{fifo:!1,visibilityTimeout:900,messageRetentionPeriod:345600,receiveMessageWaitTime:20,deadLetterQueue:!0,maxReceiveCount:3},emails:{fifo:!1,visibilityTimeout:300,messageRetentionPeriod:86400,deadLetterQueue:!0}},functions:{"job-worker":{runtime:"nodejs20.x",handler:"dist/workers/jobs.handler",memory:2048,timeout:900,events:[{type:"sqs",queueName:`${r}-jobs`,batchSize:10}]},"email-sender":{runtime:"nodejs20.x",handler:"dist/workers/email.handler",memory:512,timeout:60,events:[{type:"sqs",queueName:`${r}-emails`,batchSize:10}]},cleanup:{runtime:"nodejs20.x",handler:"dist/tasks/cleanup.handler",memory:512,timeout:300,events:[{type:"schedule",expression:"cron(0 2 * * ? *)"}]}},monitoring:{dashboard:{name:`${r}-web-app`,widgets:[{type:"metric",metrics:["EC2CPUUtilization","ALBRequestCount","ALBTargetResponseTime","RDSCPUUtilization","RDSDatabaseConnections","RDSReadLatency","RDSWriteLatency"]}]},alarms:[{metric:"EC2CPUUtilization",threshold:80,evaluationPeriods:2},{metric:"RDSCPUUtilization",threshold:80,evaluationPeriods:2},{metric:"RDSDatabaseConnections",threshold:400,evaluationPeriods:1},{metric:"ALBTargetResponseTime",threshold:2000,evaluationPeriods:2},{metric:"ALBUnhealthyHostCount",threshold:1,evaluationPeriods:1}],logs:{retention:14,groups:[`${r}-app`,`${r}-nginx`,`${r}-workers`]}},security:{certificate:n?{domain:n,validationMethod:"DNS"}:void 0,waf:{enabled:!0,rules:["rateLimit","sqlInjection","xss","knownBadInputs"]},securityGroups:{alb:{ingress:[{port:80,protocol:"tcp",cidr:"0.0.0.0/0"},{port:443,protocol:"tcp",cidr:"0.0.0.0/0"}]},app:{ingress:[{port:3000,protocol:"tcp",source:"alb-sg"}]},database:{ingress:[{port:u==="mysql"?3306:5432,protocol:"tcp",source:"app-sg"}]},...d==="redis"&&{cache:{ingress:[{port:6379,protocol:"tcp",source:"app-sg"}]}}}}}}}function Dp(e){let{name:a,slug:r,domain:n,repository:i,phpVersion:o="8.3",size:c="small",database:u=r.replace(/-/g,"_"),databasePassword:d,sslEmail:m,deployStrategy:p="push",provider:g="hetzner"}=e;return{project:{name:a,slug:r,region:"us-east-1"},mode:"server",cloud:{provider:g},environments:{production:{type:"production",domain:n}},infrastructure:{compute:{mode:"server",size:c,runtime:"php",webServer:"nginx",php:{versions:[o],default:o},managedServices:{mysql:!0,redis:!0},firewall:{enabled:!0},autoUpdates:!0,monitoring:!0,backups:{enabled:!0,schedule:"0 2 * * *",retentionCount:7}},appDatabase:{engine:"mysql",name:u,username:u,password:d}},sites:{main:{root:".",type:"laravel",domain:n,phpVersion:o,repository:{...i,strategy:p},scheduler:!0,queues:[{connection:"redis",queue:"default",processes:1}],ssl:{provider:"letsencrypt",email:m}}}}}function kp(e){let{name:a,slug:r,domain:n,layers:i,phpVersion:o="8.3",architecture:c="x86_64",memory:u=1024,build:d,deploy:m=["migrate --force"],cache:p="dynamodb",scheduler:g="on",region:h="us-east-1"}=e;return{project:{name:a,slug:r,region:h},mode:"serverless",environments:{production:{type:"production",domain:n,app:{kind:"php",runtime:"provided.al2023",phpVersion:o,architecture:c,layers:i,memory:u,build:d,deploy:m,assets:"public",queues:!0,scheduler:g,cache:{driver:p},domain:n}}}}}function _p(e){return{root:e.root??"packages/ui/dist",deploy:"server",type:"static",domain:e.domain,build:e.build??"cd packages/ui && bun install && bun run build",ssl:{provider:"letsencrypt"},auth:{username:e.username??"admin",password:e.password}}}var fd=tc,hd="./node_modules/@stacksjs/ts-cloud/dist/bin/dashboard-server.js";function Mn(e){let a=e.split(".").filter(Boolean);return a.length<=2?e:a.slice(-2).join(".")}function xn(e){let a=2166136261;for(let r=0;r<e.length;r++)a^=e.charCodeAt(r),a=Math.imul(a,16777619);return a>>>0}var yd=20000,Sd=12000;function bd(e){return yd+xn(e)%Sd}function Ma(e,a){let r=Mn(e);if(r===e)return`dashboard.${r}`;for(let n of a)if(n===r)return`dashboard.${r}`;return`dashboard.${e}`}function xa(e,a){let r=[],n=e.infrastructure?.dns?.domain;if(n&&!e.cloud?.attachTo)r.push(n);if(a&&e.environments?.[a]?.domain)r.push(e.environments[a].domain);for(let i of Object.values(e.sites??{})){let o=i;if(!o||o.redirect)continue;let c=o.domain;if(typeof c==="string")r.push(c);else if(Array.isArray(c))r.push(...c.filter((u)=>typeof u==="string"))}return r.filter((i)=>i&&!i.startsWith("dashboard."))}function vd(e,a,r){if(r)return r;let n=xa(e,a),i=n[0];if(!i)return null;return Ma(i,n)}function Td(e,a,r){if(r)return[r];let n=xa(e,a),i=[];for(let o of n){let c=Ma(o,n);if(!i.includes(c))i.push(c)}return i}function jt(e){return Object.entries(e.sites??{}).some(([a,r])=>{if(!r)return!1;let n=r.root??"";return Cr(a)||n==="ui/dist"||n.endsWith("/ui/dist")||n.endsWith("/dist/ui")})}var cc="dashboard-";function lc(e){return cc+e.replace(/^dashboard\./,"").replace(/\./g,"-")}function Cr(e){return e==="dashboard"||e.startsWith(cc)}function hi(e,a,r){if(jt(e))return[];if(e.cloud?.attachTo)return[];let n=r.password?{auth:{username:r.username||"admin",password:r.password,realm:r.realm}}:{},i=r.build===!1||r.build===void 0?{}:{build:r.build};if(r.live!==!1){let o=vd(e,a,r.domain);if(!o)return[];let c=r.port??bd(o),u=e.infrastructure?.appDatabase??e.infrastructure?.compute?.database,d={root:r.uiRoot,deploy:"server",domain:o,preStart:["bun install --production --no-save"],start:`bun ${hd} --box --host 127.0.0.1 --port ${c}`,port:c,cpuWeight:10,ioWeight:10,tasksMax:128,env:{APP_ENV:"production",NODE_ENV:"production",TS_CLOUD_DASHBOARD_TELEMETRY:"1",...u?.password?{TS_CLOUD_DASHBOARD_DB_PASSWORD:u.password}:{}},zeroDowntime:!1,sharedPaths:[fd],healthCheck:{path:"/login"},ssl:{provider:"letsencrypt"}};return[{name:lc(o),site:d}]}return Td(e,a,r.domain).map((o)=>({name:lc(o),site:{root:r.uiRoot,deploy:"server",type:"static",domain:o,ssl:{provider:"letsencrypt"},...i,...n}}))}function xp(e,a,r){return hi(e,a,r)[0]??null}function Wt(e,a){let r={...e};for(let n in a){let i=a[n],o=r[n];if(i===void 0)continue;if(Array.isArray(i)&&Array.isArray(o))r[n]=[...o,...i];else if(typeof i==="object"&&i!==null&&!Array.isArray(i)&&typeof o==="object"&&o!==null&&!Array.isArray(o))r[n]=Wt(o,i);else r[n]=i}return r}function dc(e,a){return Wt(e,a)}function $p(...e){return e.reduce((a,r)=>Wt(a,r),{})}function Op(e,a){return(r)=>{let n=e(r);if(typeof a==="function")return dc(n,a(n,r));return dc(n,a)}}function rn(e){return{infrastructure:e}}function Lp(e){return rn({monitoring:e})}function Mp(e){return rn({security:e})}function Up(e){return rn({databases:e})}function Bp(e){return rn({cache:e})}function Fp(e){return rn({cdn:e})}function jp(e){return rn({queues:e})}Qe();function Ed(){let e=process.env.AWS_ACCESS_KEY_ID,a=process.env.AWS_SECRET_ACCESS_KEY;if(!e||!a)return null;return{accessKeyId:e,secretAccessKey:a,sessionToken:process.env.AWS_SESSION_TOKEN}}function wd(e){let a=e?.profile||process.env.AWS_PROFILE||"default",r=e?.credentialsFile||_a(Ba(),".aws","credentials");if(!Oa(r))return null;try{let n=Gt(r,"utf-8");return On(n,a)}catch{return null}}function On(e,a){let r=e.split(`
|
|
2494
2494
|
`),n=null,i,o,c;for(let u of r){let d=u.trim();if(!d||d.startsWith("#")||d.startsWith(";"))continue;let m=d.match(/^\[([^\]]+)\]$/);if(m){if(n===a&&i&&o)return{accessKeyId:i,secretAccessKey:o,sessionToken:c};n=m[1],i=void 0,o=void 0,c=void 0;continue}if(n===a){let[p,...g]=d.split("="),h=g.join("=").trim();switch(p.trim().toLowerCase()){case"aws_access_key_id":i=h;break;case"aws_secret_access_key":o=h;break;case"aws_session_token":c=h;break}}}if(n===a&&i&&o)return{accessKeyId:i,secretAccessKey:o,sessionToken:c};return null}async function Cd(e){let a=e?.timeout??1000,r="http://169.254.169.254";try{let n=await qe("http://169.254.169.254/latest/api/token",{method:"PUT",headers:{"X-aws-ec2-metadata-token-ttl-seconds":"21600"}},a);if(!n.ok)return null;let i=await n.text(),o=await qe("http://169.254.169.254/latest/meta-data/iam/security-credentials/",{headers:{"X-aws-ec2-metadata-token":i}},a);if(!o.ok)return null;let c=(await o.text()).trim(),u=await qe(`http://169.254.169.254/latest/meta-data/iam/security-credentials/${c}`,{headers:{"X-aws-ec2-metadata-token":i}},a);if(!u.ok)return null;let d=await u.json();return{accessKeyId:d.AccessKeyId,secretAccessKey:d.SecretAccessKey,sessionToken:d.Token,expiration:new Date(d.Expiration)}}catch{return null}}async function Ad(e){let a=e?.timeout??1000,r=process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI,n=process.env.AWS_CONTAINER_CREDENTIALS_FULL_URI,i=null;if(r)i=`http://169.254.170.2${r}`;else if(n)i=n;if(!i)return null;try{let o={},c=process.env.AWS_CONTAINER_AUTHORIZATION_TOKEN;if(c)o.Authorization=c;let u=await qe(i,{headers:o},a);if(!u.ok)return null;let d=await u.json();return{accessKeyId:d.AccessKeyId,secretAccessKey:d.SecretAccessKey,sessionToken:d.Token,expiration:new Date(d.Expiration)}}catch{return null}}async function Id(e){let a=e?.timeout??5000,r=process.env.AWS_WEB_IDENTITY_TOKEN_FILE,n=process.env.AWS_ROLE_ARN,i=process.env.AWS_ROLE_SESSION_NAME||"ts-cloud-session";if(!r||!n)return null;try{let o=Gt(r,"utf-8").trim(),c=process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||"us-east-1",u=c.startsWith("us-gov")?`https://sts.${c}.amazonaws.com`:c==="us-east-1"?"https://sts.amazonaws.com":`https://sts.${c}.amazonaws.com`,d=new URLSearchParams({Action:"AssumeRoleWithWebIdentity",Version:"2011-06-15",RoleArn:n,RoleSessionName:i,WebIdentityToken:o}),m=await qe(`${u}/?${d.toString()}`,{method:"POST"},a);if(!m.ok)return null;let p=await m.text(),g=je(p,"AccessKeyId"),h=je(p,"SecretAccessKey"),y=je(p,"SessionToken"),f=je(p,"Expiration");if(!g||!h)return null;return{accessKeyId:g,secretAccessKey:h,sessionToken:y??void 0,expiration:f?new Date(f):void 0}}catch{return null}}async function Ao(e){let a=Ed();if(a)return a;let r=wd(e);if(r)return r;let n=await Id(e);if(n)return n;let i=await Ad(e);if(i)return i;let o=await Cd(e);if(o)return o;throw Error("Could not find AWS credentials. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables, or configure ~/.aws/credentials, or run on an EC2 instance with an IAM role.")}function Vp(e){let a=null,r=null;return async()=>{if(a){if(!a.expiration)return a;let n=300000;if(a.expiration.getTime()-Date.now()>n)return a}if(r)return r;return r=Ao(e).then((n)=>(a=n,r=null,n)).catch((n)=>{throw r=null,n}),r}}async function qe(e,a,r){let n=new AbortController,i=setTimeout(()=>n.abort(),r);try{let o=await fetch(e,{...a,signal:n.signal});return clearTimeout(i),o}catch(o){throw clearTimeout(i),o}}function je(e,a){let r=new RegExp(`<${a}>([^<]+)</${a}>`),n=e.match(r);return n?n[1]:null}async function Js(e){return Ao({profile:e})}function Rd(e){let a=process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION;if(a)return a;let r=_a(Ba(),".aws","config");if(Oa(r))try{let n=Gt(r,"utf-8"),i=e||process.env.AWS_PROFILE||"default",o=i==="default"?"[default]":`[profile ${i}]`,c=n.split(`
|
|
2495
2495
|
`),u=!1;for(let d of c){let m=d.trim();if(m.startsWith("[")){u=m===o;continue}if(u&&m.startsWith("region")){let[,p]=m.split("=");if(p)return p.trim()}}}catch{}return"us-east-1"}async function Pd(e){let a=e||await Ao(),r=Rd();await Qe();let n=r.startsWith("us-gov")?`https://sts.${r}.amazonaws.com`:r==="us-east-1"?"https://sts.amazonaws.com":`https://sts.${r}.amazonaws.com`,i="Action=GetCallerIdentity&Version=2011-06-15",o=oe({method:"POST",url:n,body:"Action=GetCallerIdentity&Version=2011-06-15",headers:{"Content-Type":"application/x-www-form-urlencoded"},...a,service:"sts",region:r}),c=await fetch(o.url,{method:o.method,headers:o.headers,body:o.body});if(!c.ok)throw Error(`Failed to get account ID: ${await c.text()}`);let u=await c.text(),d=je(u,"Account");if(!d)throw Error("Failed to parse account ID from response");return d}await Qe();class Nd{profile;credentials=null;region;constructor(e="us-east-1",a="default"){this.profile=a,this.region=e}async init(){if(this.credentials=await Js(this.profile),this.credentials.region)this.region=this.credentials.region}async ensureCredentials(){if(!this.credentials)await this.init();return this.credentials}async request(e,a){let r=await this.ensureCredentials(),n={Action:e,Version:"2010-05-15",...Mt(a)},i=new URLSearchParams(n).toString(),o=await(await ui({method:"POST",url:`https://cloudformation.${this.region}.amazonaws.com/`,service:"cloudformation",region:this.region,headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i,accessKeyId:r.accessKeyId,secretAccessKey:r.secretAccessKey,sessionToken:r.sessionToken})).text();return Bn(o)}async createStack(e){let a={StackName:e.stackName};if(e.templateBody)a.TemplateBody=e.templateBody;else if(e.templateURL)a.TemplateURL=e.templateURL;else throw Error("Either templateBody or templateURL must be provided");if(e.parameters)for(let[n,[i,o]]of Object.entries(e.parameters).entries())a[`Parameters.member.${n+1}.ParameterKey`]=i,a[`Parameters.member.${n+1}.ParameterValue`]=o;if(e.capabilities)for(let[n,i]of e.capabilities.entries())a[`Capabilities.member.${n+1}`]=i;if(e.tags)for(let[n,[i,o]]of Object.entries(e.tags).entries())a[`Tags.member.${n+1}.Key`]=i,a[`Tags.member.${n+1}.Value`]=o;if(e.timeoutInMinutes)a.TimeoutInMinutes=e.timeoutInMinutes;if(e.onFailure)a.OnFailure=e.onFailure;let r=await this.request("CreateStack",a);return(r?.CreateStackResult||r?.CreateStackResponse?.CreateStackResult||r)?.StackId}async updateStack(e){let a={StackName:e.stackName};if(e.templateBody)a.TemplateBody=e.templateBody;else if(e.templateURL)a.TemplateURL=e.templateURL;if(e.parameters)for(let[n,[i,o]]of Object.entries(e.parameters).entries())a[`Parameters.member.${n+1}.ParameterKey`]=i,a[`Parameters.member.${n+1}.ParameterValue`]=o;if(e.capabilities)for(let[n,i]of e.capabilities.entries())a[`Capabilities.member.${n+1}`]=i;if(e.tags)for(let[n,[i,o]]of Object.entries(e.tags).entries())a[`Tags.member.${n+1}.Key`]=i,a[`Tags.member.${n+1}.Value`]=o;let r=await this.request("UpdateStack",a);return(r?.UpdateStackResult||r?.UpdateStackResponse?.UpdateStackResult||r)?.StackId}async deleteStack(e){await this.request("DeleteStack",{StackName:e})}async describeStack(e){let a=await this.request("DescribeStacks",{StackName:e}),r=(a?.DescribeStacksResult||a?.DescribeStacksResponse?.DescribeStacksResult||a)?.Stacks?.member,n=Array.isArray(r)?r[0]:r;if(!n)throw Error(`Stack ${e} not found`);return _n(n)}async listStacks(e){let a={};if(e)for(let[n,i]of e.entries())a[`StackStatusFilter.member.${n+1}`]=i;let r=await this.request("ListStacks",a);return Wn(r)}async describeStackEvents(e){let a=await this.request("DescribeStackEvents",{StackName:e});return Gn(a)}async waitForStack(e,a,r){let n=0,i=null;while(n<360){n++;let o=await this.describeStack(e);if(r)try{let c=await this.describeStackEvents(e),u=[];if(i){for(let d of c){if(d.EventId===i)break;u.push(d)}u.reverse()}else if(c.length>0)u=[c[0]];for(let d of u)r(d);if(c.length>0)i=c[0].EventId}catch{}if(o.StackStatus&&a.includes(o.StackStatus))return o;if(o.StackStatus?.includes("FAILED")||o.StackStatus?.includes("ROLLBACK"))throw Error(`Stack reached failed state: ${o.StackStatus}
|
|
2496
|
-
Reason: ${o.StackStatusReason||"Unknown"}`);await new Promise((c)=>setTimeout(c,5000))}throw Error(`Timeout waiting for stack ${e} to complete`)}async waitForStackWithProgress(e,a,r){let n={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]}[a];if(!n)throw Error(`Unknown waiter: ${a}`);return this.waitForStack(e,n,r)}async createChangeSet(e){let a={StackName:e.stackName,ChangeSetName:e.changeSetName,ChangeSetType:"UPDATE"};if(e.templateBody)a.TemplateBody=e.templateBody;else if(e.templateURL)a.TemplateURL=e.templateURL;if(e.parameters)for(let[r,[n,i]]of Object.entries(e.parameters).entries())a[`Parameters.member.${r+1}.ParameterKey`]=n,a[`Parameters.member.${r+1}.ParameterValue`]=i;if(e.capabilities)for(let[r,n]of e.capabilities.entries())a[`Capabilities.member.${r+1}`]=n;return(await this.request("CreateChangeSet",a)).ChangeSetId}async executeChangeSet(e,a){await this.request("ExecuteChangeSet",{ChangeSetName:e,StackName:a})}async describeStacks(e){let a=typeof e==="string"?e:e.stackName;try{return{Stacks:[await this.describeStack(a)]}}catch{return{Stacks:[]}}}async getStackOutputs(e){let a=await this.request("DescribeStacks",{StackName:e}),r=(a?.DescribeStacksResult||a?.DescribeStacksResponse?.DescribeStacksResult||a)?.Stacks?.member,n=Array.isArray(r)?r[0]:r;if(!n)return{};let i={},o=n.Outputs?.member;if(o){let c=Array.isArray(o)?o:[o];for(let u of c)if(u.OutputKey&&u.OutputValue)i[u.OutputKey]=u.OutputValue}return i}}function Mt(e,a=""){let r={};for(let[n,i]of Object.entries(e)){let o=a?`${a}.${n}`:n;if(Array.isArray(i))i.forEach((c,u)=>{if(typeof c==="object")Object.assign(r,Mt(c,`${o}.${u+1}`));else r[`${o}.${u+1}`]=String(c)});else if(typeof i==="object"&&i!==null)Object.assign(r,Mt(i,o));else if(i!==void 0&&i!==null)r[o]=String(i)}return r}function Bn(e){e=e.replace(/<\?xml[^?]*\?>\s*/,"").trim();function a(n,i,o){let c=1,u=o,d=`<${i}`,m=`</${i}>`;while(u<n.length&&c>0){let p=n.indexOf(d,u),g=n.indexOf(m,u);if(g===-1)return-1;if(p!==-1&&p<g){let h=n[p+d.length];if(h===">"||h===" "||h==="/"){let y=n.indexOf(">",p);if(y!==-1&&n[y-1]==="/")u=y+1;else c++,u=y+1}else u=p+d.length}else{if(c--,c===0)return g;u=g+m.length}}return-1}function r(n,i){while(i<n.length&&/\s/.test(n[i]))i++;if(i>=n.length||n[i]!=="<"){let y=n.indexOf("<",i);if(y===-1)return{value:n.slice(i).trim(),end:n.length};return{value:n.slice(i,y).trim(),end:y}}if(n[i+1]==="/")return{value:void 0,end:i};let o=n.slice(i).match(/^<(\w+)([^>]*?)\/?>/);if(!o)return{value:void 0,end:i+1};let c=o[1];if(o[0].endsWith("/>"))return{value:"",end:i+o[0].length};let u=i+o[0].length,d=`</${c}>`,m=a(n,c,u);if(m===-1)return{value:void 0,end:i+o[0].length};let p=n.slice(u,m).trim();if(!p.includes("<"))return{value:p,end:m+d.length};let g={},h=u;while(h<m){while(h<m&&/\s/.test(n[h]))h++;if(h>=m)break;if(n[h]!=="<"||n[h+1]==="/")break;let y=n.slice(h).match(/^<(\w+)/);if(!y)break;let f=y[1],b=r(n,h);if(b.value===void 0){h++;continue}if(f==="member"||g[f]!==void 0){if(!Array.isArray(g[f]))g[f]=g[f]!==void 0?[g[f]]:[];g[f].push(b.value)}else g[f]=b.value;h=b.end}return{value:g,end:m+d.length}}return r(e,0).value||{}}function _n(e){return{StackName:e.StackName||"",StackId:e.StackId,StackStatus:e.StackStatus,CreationTime:e.CreationTime,LastUpdatedTime:e.LastUpdatedTime,StackStatusReason:e.StackStatusReason,Description:e.Description}}function Wn(e){let a=(e?.ListStacksResult||e?.ListStacksResponse?.ListStacksResult||e)?.StackSummaries?.member;if(!a)return[];return(Array.isArray(a)?a:[a]).map((r)=>({StackName:r.StackName||"",StackId:r.StackId,StackStatus:r.StackStatus,CreationTime:r.CreationTime,LastUpdatedTime:r.LastUpdatedTime,StackStatusReason:r.StackStatusReason,Description:r.Description}))}function Gn(e){let a=(e?.DescribeStackEventsResult||e?.DescribeStackEventsResponse?.DescribeStackEventsResult||e)?.StackEvents?.member;if(!a)return[];return(Array.isArray(a)?a:[a]).map((r)=>({StackId:r.StackId||"",EventId:r.EventId||"",StackName:r.StackName||"",LogicalResourceId:r.LogicalResourceId||"",PhysicalResourceId:r.PhysicalResourceId,ResourceType:r.ResourceType||"",Timestamp:r.Timestamp||"",ResourceStatus:r.ResourceStatus||"",ResourceStatusReason:r.ResourceStatusReason}))}await Qe();var Fn=5242880,Pt=5242880,Un=5242880;class uc{region;endpoint;forcePathStyle;credentials;credentialOptions;retryOptions;constructor(e={}){this.region=e.region||process.env.AWS_REGION||"us-east-1",this.endpoint=e.endpoint||`https://s3.${this.region}.amazonaws.com`,this.forcePathStyle=e.forcePathStyle||!1,this.credentials=e.credentials,this.credentialOptions=e.credentialOptions,this.retryOptions=e.retryOptions||{}}async getCredentials(){if(this.credentials)return this.credentials;return Ao(this.credentialOptions)}buildUrl(e,a){let r=a?encodeURIComponent(a).replace(/%2F/g,"/"):"";if(this.forcePathStyle)return a?`${this.endpoint}/${e}/${r}`:`${this.endpoint}/${e}`;let n=new URL(this.endpoint);return n.hostname=`${e}.${n.hostname}`,a?`${n.origin}/${r}`:n.origin}async get(e,a,r={}){let n=await this.getCredentials(),i=this.buildUrl(e,a),o={};if(r.range)o.Range=r.range;if(r.ifModifiedSince)o["If-Modified-Since"]=r.ifModifiedSince.toUTCString();if(r.ifMatch)o["If-Match"]=r.ifMatch;if(r.ifNoneMatch)o["If-None-Match"]=r.ifNoneMatch;let c=new URL(i);if(r.responseContentType)c.searchParams.set("response-content-type",r.responseContentType);if(r.responseContentDisposition)c.searchParams.set("response-content-disposition",r.responseContentDisposition);let u=oe({method:"GET",url:c.toString(),headers:o,...n,service:"s3",region:this.region}),d=await fetch(u.url,{method:u.method,headers:u.headers});if(!d.ok&&d.status!==304){let m=await d.text();throw new Ce(`Failed to get object: ${m}`,d.status,e,a)}return d}async getText(e,a,r={}){return(await this.get(e,a,r)).text()}async getJSON(e,a,r={}){return(await this.get(e,a,r)).json()}async getBuffer(e,a,r={}){return(await this.get(e,a,r)).arrayBuffer()}async put(e,a,r,n={}){let i,o;if(typeof r==="string")i=new TextEncoder().encode(r).length,o=r;else if(r instanceof ArrayBuffer)i=r.byteLength,o=r;else if(r instanceof Uint8Array)i=r.byteLength,o=r;else if(r instanceof Blob)i=r.size,o=r;else return this.uploadMultipart(e,a,r,{...n,partSize:Pt});if(i>Un){let c=Kn(o).stream();return this.uploadMultipart(e,a,c,{...n,partSize:Pt})}return this.putSimple(e,a,o,i,n)}async putSimple(e,a,r,n,i){let o=await this.getCredentials(),c=this.buildUrl(e,a),u={"Content-Length":String(n),"Content-Type":i.contentType||fa(a)};if(i.contentEncoding)u["Content-Encoding"]=i.contentEncoding;if(i.cacheControl)u["Cache-Control"]=i.cacheControl;if(i.contentDisposition)u["Content-Disposition"]=i.contentDisposition;if(i.storageClass)u["x-amz-storage-class"]=i.storageClass;if(i.serverSideEncryption)u["x-amz-server-side-encryption"]=i.serverSideEncryption;if(i.acl)u["x-amz-acl"]=i.acl;if(i.tagging)u["x-amz-tagging"]=i.tagging;if(i.metadata)for(let[g,h]of Object.entries(i.metadata))u[`x-amz-meta-${g.toLowerCase()}`]=h;let d;if(typeof r==="string")d=r;else if(r instanceof Blob)d=await r.text();else d=new TextDecoder().decode(r instanceof ArrayBuffer?new Uint8Array(r):r);let m=oe({method:"PUT",url:c,headers:u,body:d,...o,service:"s3",region:this.region}),p=await fetch(m.url,{method:m.method,headers:m.headers,body:r});if(!p.ok){let g=await p.text();throw new Ce(`Failed to put object: ${g}`,p.status,e,a)}return{etag:(p.headers.get("ETag")||"").replace(/"/g,"")}}async delete(e,a){let r=await this.getCredentials(),n=this.buildUrl(e,a),i=oe({method:"DELETE",url:n,...r,service:"s3",region:this.region}),o=await fetch(i.url,{method:i.method,headers:i.headers});if(!o.ok&&o.status!==204){let c=await o.text();throw new Ce(`Failed to delete object: ${c}`,o.status,e,a)}}async deleteMany(e,a){let r=await this.getCredentials(),n=`${this.buildUrl(e)}?delete`,i=`<?xml version="1.0" encoding="UTF-8"?><Delete><Quiet>false</Quiet>${a.map((y)=>`<Object><Key>${jn(y)}</Key></Object>`).join("")}</Delete>`,o=oe({method:"POST",url:n,headers:{"Content-Type":"application/xml"},body:i,...r,service:"s3",region:this.region}),c=await fetch(o.url,{method:o.method,headers:o.headers,body:i});if(!c.ok){let y=await c.text();throw new Ce(`Failed to delete objects: ${y}`,c.status,e)}let u=await c.text(),d=[],m=[],p=/<Deleted><Key>([^<]+)<\/Key>/g,g;while((g=p.exec(u))!==null)d.push(g[1]);let h=/<Error><Key>([^<]+)<\/Key><Code>([^<]+)<\/Code><Message>([^<]+)<\/Message>/g;while((g=h.exec(u))!==null)m.push({key:g[1],error:`${g[2]}: ${g[3]}`});return{deleted:d,errors:m}}async list(e,a={}){let r=await this.getCredentials(),n=new URL(this.buildUrl(e));if(n.searchParams.set("list-type","2"),a.prefix)n.searchParams.set("prefix",a.prefix);if(a.delimiter)n.searchParams.set("delimiter",a.delimiter);if(a.maxKeys)n.searchParams.set("max-keys",String(a.maxKeys));if(a.continuationToken)n.searchParams.set("continuation-token",a.continuationToken);if(a.startAfter)n.searchParams.set("start-after",a.startAfter);let i=oe({method:"GET",url:n.toString(),...r,service:"s3",region:this.region}),o=await fetch(i.url,{method:i.method,headers:i.headers});if(!o.ok){let u=await o.text();throw new Ce(`Failed to list objects: ${u}`,o.status,e)}let c=await o.text();return Vn(c)}async*listAll(e,a={}){let r;do{let n=await this.list(e,{...a,continuationToken:r});for(let i of n.contents)yield i;r=n.nextContinuationToken}while(r)}async head(e,a){let r=await this.getCredentials(),n=this.buildUrl(e,a),i=oe({method:"HEAD",url:n,...r,service:"s3",region:this.region}),o=await fetch(i.url,{method:i.method,headers:i.headers});if(o.status===404)return null;if(!o.ok){let u=await o.text();throw new Ce(`Failed to head object: ${u}`,o.status,e,a)}let c={};return o.headers.forEach((u,d)=>{if(d.toLowerCase().startsWith("x-amz-meta-"))c[d.slice(11)]=u}),{contentLength:Number(o.headers.get("Content-Length")||0),contentType:o.headers.get("Content-Type")||"application/octet-stream",etag:(o.headers.get("ETag")||"").replace(/"/g,""),lastModified:new Date(o.headers.get("Last-Modified")||0),metadata:c,storageClass:o.headers.get("x-amz-storage-class")||void 0,serverSideEncryption:o.headers.get("x-amz-server-side-encryption")||void 0}}async exists(e,a){return await this.head(e,a)!==null}async copy(e,a,r,n,i={}){let o=await this.getCredentials(),c=this.buildUrl(r,n),u={"x-amz-copy-source":`/${e}/${encodeURIComponent(a)}`};if(i.metadataDirective)u["x-amz-metadata-directive"]=i.metadataDirective;if(i.contentType)u["Content-Type"]=i.contentType;if(i.storageClass)u["x-amz-storage-class"]=i.storageClass;if(i.acl)u["x-amz-acl"]=i.acl;if(i.metadata)for(let[g,h]of Object.entries(i.metadata))u[`x-amz-meta-${g.toLowerCase()}`]=h;let d=oe({method:"PUT",url:c,headers:u,...o,service:"s3",region:this.region}),m=await fetch(d.url,{method:d.method,headers:d.headers});if(!m.ok){let g=await m.text();throw new Ce(`Failed to copy object: ${g}`,m.status,r,n)}let p=(await m.text()).match(/<ETag>"?([^"<]+)"?<\/ETag>/);return{etag:p?p[1]:""}}async getPresignedUrl(e,a,r={}){let n=await this.getCredentials(),i=this.buildUrl(e,a);return cd({url:i,method:r.method||"GET",expiresIn:r.expiresIn||3600,...n,service:"s3",region:this.region})}async uploadMultipart(e,a,r,n={}){let i=await this.getCredentials(),o=Math.max(n.partSize||Pt,Fn),c,u;if(r instanceof ReadableStream)c=r;else if(r instanceof Blob)c=r.stream(),u=r.size;else{let p=new Blob([r]);c=p.stream(),u=p.size}let{uploadId:d,baseUrl:m}=await this.initiateMultipartUpload(e,a,n);try{let p=await this.uploadParts(e,a,m,d,c,o,i,u,n.concurrency||4,n.onProgress);return await this.completeMultipartUpload(e,a,m,d,p)}catch(p){throw await this.abortMultipartUpload(e,a,d,m).catch(()=>{}),p}}async initiateMultipartUpload(e,a,r){let n=await this.getCredentials(),i=this.buildUrl(e,a),o=`${i}?uploads`,c={"Content-Type":r.contentType||fa(a)};if(r.storageClass)c["x-amz-storage-class"]=r.storageClass;if(r.serverSideEncryption)c["x-amz-server-side-encryption"]=r.serverSideEncryption;if(r.acl)c["x-amz-acl"]=r.acl;if(r.metadata)for(let[g,h]of Object.entries(r.metadata))c[`x-amz-meta-${g.toLowerCase()}`]=h;let u=oe({method:"POST",url:o,headers:c,...n,service:"s3",region:this.region}),d=await fetch(u.url,{method:u.method,headers:u.headers});if(!d.ok){let g=await d.text();throw new Ce(`Failed to initiate multipart upload: ${g}`,d.status,e,a)}let m=(await d.text()).match(/<UploadId>([^<]+)<\/UploadId>/);if(!m)throw new Ce("Failed to parse upload ID from response",0,e,a);let p=i;if(d.url)try{let g=new URL(d.url);g.search="",p=g.toString()}catch{}return{uploadId:m[1],baseUrl:p}}async uploadParts(e,a,r,n,i,o,c,u,d,m){let p=[],g=i.getReader(),h=1,y=new Uint8Array(0),f=0,b=u?Math.ceil(u/o):void 0,v=new Map,w=async(T,N)=>{let I=`${r}?partNumber=${N}&uploadId=${encodeURIComponent(n)}`,k={"Content-Length":String(T.byteLength),"x-amz-content-sha256":"UNSIGNED-PAYLOAD"},x=oe({method:"PUT",url:I,headers:k,...c,service:"s3",region:this.region}),L=await fetch(x.url,{method:x.method,headers:x.headers,body:T,redirect:"error"});if(!L.ok){let W=await L.text();throw new Ce(`Failed to upload part ${N}: ${W}`,L.status,e,a)}let O=(L.headers.get("ETag")||"").replace(/"/g,"");if(!O)throw new Ce(`Missing ETag for part ${N}`,L.status,e,a);return{partNumber:N,etag:O}},R=async()=>{let T=await Promise.race(v.values());v.delete(T.partNumber),p.push(T)};while(!0){let{done:T,value:N}=await g.read();if(N){let I=new Uint8Array(y.length+N.length);I.set(y),I.set(N,y.length),y=I}while(y.length>=o||T&&y.length>0){let I=y.slice(0,o);y=y.slice(o);let k=h++;if(v.size>=d)await R();if(v.set(k,w(I,k)),f+=I.byteLength,m)m({loaded:f,total:u||f,part:k,totalParts:b||k})}if(T)break}while(v.size>0)await R();return p.sort((T,N)=>T.partNumber-N.partNumber),p}async completeMultipartUpload(e,a,r,n,i){let o=await this.getCredentials(),c=`${r}?uploadId=${encodeURIComponent(n)}`,u=`<?xml version="1.0" encoding="UTF-8"?><CompleteMultipartUpload>${i.map((g)=>`<Part><PartNumber>${g.partNumber}</PartNumber><ETag>"${g.etag}"</ETag></Part>`).join("")}</CompleteMultipartUpload>`,d=oe({method:"POST",url:c,headers:{"Content-Type":"application/xml"},body:u,...o,service:"s3",region:this.region}),m=await fetch(d.url,{method:d.method,headers:d.headers,body:u});if(!m.ok){let g=await m.text();throw new Ce(`Failed to complete multipart upload: ${g}`,m.status,e,a)}let p=(await m.text()).match(/<ETag>"?([^"<]+)"?<\/ETag>/);return{etag:p?p[1]:""}}async abortMultipartUpload(e,a,r,n){let i=await this.getCredentials(),o=`${n??this.buildUrl(e,a)}?uploadId=${encodeURIComponent(r)}`,c=oe({method:"DELETE",url:o,...i,service:"s3",region:this.region});await fetch(c.url,{method:c.method,headers:c.headers})}async emptyAndDeleteBucket(e){let a=[];for await(let o of this.listAll(e,{}))if(a.push(o.key),a.length>=1000)await this.deleteMany(e,a),a=[];if(a.length>0)await this.deleteMany(e,a);let r=await this.getCredentials(),n=this.buildUrl(e),i=oe({method:"DELETE",url:n,...r,service:"s3",region:this.region});await fetch(i.url,{method:i.method,headers:i.headers})}}class Ce extends Error{statusCode;bucket;key;constructor(e,a,r,n){super(e);this.statusCode=a,this.bucket=r,this.key=n,this.name="S3Error"}}function Vn(e){let a=[],r=[],n=/<Contents>([\s\S]*?)<\/Contents>/g,i;while((i=n.exec(e))!==null){let c=i[1];a.push({key:Q(c,"Key")||"",lastModified:new Date(Q(c,"LastModified")||0),etag:(Q(c,"ETag")||"").replace(/"/g,""),size:Number(Q(c,"Size")||0),storageClass:Q(c,"StorageClass")||"STANDARD"})}let o=/<CommonPrefixes><Prefix>([^<]+)<\/Prefix><\/CommonPrefixes>/g;while((i=o.exec(e))!==null)r.push(i[1]);return{contents:a,commonPrefixes:r,isTruncated:Q(e,"IsTruncated")==="true",continuationToken:Q(e,"ContinuationToken")||void 0,nextContinuationToken:Q(e,"NextContinuationToken")||void 0,keyCount:Number(Q(e,"KeyCount")||0),maxKeys:Number(Q(e,"MaxKeys")||1000),prefix:Q(e,"Prefix")||void 0,delimiter:Q(e,"Delimiter")||void 0}}function Q(e,a){let r=new RegExp(`<${a}>([^<]*)</${a}>`),n=e.match(r);return n?n[1]:null}function jn(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function fa(e){let a=e.split(".").pop()?.toLowerCase();return{html:"text/html",htm:"text/html",css:"text/css",js:"application/javascript",mjs:"application/javascript",json:"application/json",xml:"application/xml",txt:"text/plain",md:"text/markdown",csv:"text/csv",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",ico:"image/x-icon",avif:"image/avif",mp4:"video/mp4",webm:"video/webm",mov:"video/quicktime",avi:"video/x-msvideo",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",zip:"application/zip",gz:"application/gzip",tar:"application/x-tar",rar:"application/vnd.rar","7z":"application/x-7z-compressed",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",otf:"font/otf",eot:"application/vnd.ms-fontobject",wasm:"application/wasm"}[a||""]||"application/octet-stream"}function Kn(e){if(e instanceof Blob)return e;if(typeof e==="string")return new Blob([e],{type:"text/plain"});return new Blob([e])}function zp(e){return new uc(e)}await Qe();class Dd{profile;credentials=null;constructor(e="default"){this.profile=e}async init(){this.credentials=await Js(this.profile)}async ensureCredentials(){if(!this.credentials)await this.init();return this.credentials}async createInvalidation(e){let a=await this.ensureCredentials(),r=e.callerReference||`invalidation-${Date.now()}`,n=`<?xml version="1.0" encoding="UTF-8"?>
|
|
2496
|
+
Reason: ${o.StackStatusReason||"Unknown"}`);await new Promise((c)=>setTimeout(c,5000))}throw Error(`Timeout waiting for stack ${e} to complete`)}async waitForStackWithProgress(e,a,r){let n={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]}[a];if(!n)throw Error(`Unknown waiter: ${a}`);return this.waitForStack(e,n,r)}async createChangeSet(e){let a={StackName:e.stackName,ChangeSetName:e.changeSetName,ChangeSetType:"UPDATE"};if(e.templateBody)a.TemplateBody=e.templateBody;else if(e.templateURL)a.TemplateURL=e.templateURL;if(e.parameters)for(let[r,[n,i]]of Object.entries(e.parameters).entries())a[`Parameters.member.${r+1}.ParameterKey`]=n,a[`Parameters.member.${r+1}.ParameterValue`]=i;if(e.capabilities)for(let[r,n]of e.capabilities.entries())a[`Capabilities.member.${r+1}`]=n;return(await this.request("CreateChangeSet",a)).ChangeSetId}async executeChangeSet(e,a){await this.request("ExecuteChangeSet",{ChangeSetName:e,StackName:a})}async describeStacks(e){let a=typeof e==="string"?e:e.stackName;try{return{Stacks:[await this.describeStack(a)]}}catch{return{Stacks:[]}}}async getStackOutputs(e){let a=await this.request("DescribeStacks",{StackName:e}),r=(a?.DescribeStacksResult||a?.DescribeStacksResponse?.DescribeStacksResult||a)?.Stacks?.member,n=Array.isArray(r)?r[0]:r;if(!n)return{};let i={},o=n.Outputs?.member;if(o){let c=Array.isArray(o)?o:[o];for(let u of c)if(u.OutputKey&&u.OutputValue)i[u.OutputKey]=u.OutputValue}return i}}function Mt(e,a=""){let r={};for(let[n,i]of Object.entries(e)){let o=a?`${a}.${n}`:n;if(Array.isArray(i))i.forEach((c,u)=>{if(typeof c==="object")Object.assign(r,Mt(c,`${o}.${u+1}`));else r[`${o}.${u+1}`]=String(c)});else if(typeof i==="object"&&i!==null)Object.assign(r,Mt(i,o));else if(i!==void 0&&i!==null)r[o]=String(i)}return r}function Bn(e){e=e.replace(/<\?xml[^?]*\?>\s*/,"").trim();function a(n,i,o){let c=1,u=o,d=`<${i}`,m=`</${i}>`;while(u<n.length&&c>0){let p=n.indexOf(d,u),g=n.indexOf(m,u);if(g===-1)return-1;if(p!==-1&&p<g){let h=n[p+d.length];if(h===">"||h===" "||h==="/"){let y=n.indexOf(">",p);if(y!==-1&&n[y-1]==="/")u=y+1;else c++,u=y+1}else u=p+d.length}else{if(c--,c===0)return g;u=g+m.length}}return-1}function r(n,i){while(i<n.length&&/\s/.test(n[i]))i++;if(i>=n.length||n[i]!=="<"){let y=n.indexOf("<",i);if(y===-1)return{value:n.slice(i).trim(),end:n.length};return{value:n.slice(i,y).trim(),end:y}}if(n[i+1]==="/")return{value:void 0,end:i};let o=n.slice(i).match(/^<(\w+)([^>]*?)\/?>/);if(!o)return{value:void 0,end:i+1};let c=o[1];if(o[0].endsWith("/>"))return{value:"",end:i+o[0].length};let u=i+o[0].length,d=`</${c}>`,m=a(n,c,u);if(m===-1)return{value:void 0,end:i+o[0].length};let p=n.slice(u,m).trim();if(!p.includes("<"))return{value:p,end:m+d.length};let g={},h=u;while(h<m){while(h<m&&/\s/.test(n[h]))h++;if(h>=m)break;if(n[h]!=="<"||n[h+1]==="/")break;let y=n.slice(h).match(/^<(\w+)/);if(!y)break;let f=y[1],b=r(n,h);if(b.value===void 0){h++;continue}if(f==="member"||g[f]!==void 0){if(!Array.isArray(g[f]))g[f]=g[f]!==void 0?[g[f]]:[];g[f].push(b.value)}else g[f]=b.value;h=b.end}return{value:g,end:m+d.length}}return r(e,0).value||{}}function _n(e){return{StackName:e.StackName||"",StackId:e.StackId,StackStatus:e.StackStatus,CreationTime:e.CreationTime,LastUpdatedTime:e.LastUpdatedTime,StackStatusReason:e.StackStatusReason,Description:e.Description}}function Wn(e){let a=(e?.ListStacksResult||e?.ListStacksResponse?.ListStacksResult||e)?.StackSummaries?.member;if(!a)return[];return(Array.isArray(a)?a:[a]).map((r)=>({StackName:r.StackName||"",StackId:r.StackId,StackStatus:r.StackStatus,CreationTime:r.CreationTime,LastUpdatedTime:r.LastUpdatedTime,StackStatusReason:r.StackStatusReason,Description:r.Description}))}function Gn(e){let a=(e?.DescribeStackEventsResult||e?.DescribeStackEventsResponse?.DescribeStackEventsResult||e)?.StackEvents?.member;if(!a)return[];return(Array.isArray(a)?a:[a]).map((r)=>({StackId:r.StackId||"",EventId:r.EventId||"",StackName:r.StackName||"",LogicalResourceId:r.LogicalResourceId||"",PhysicalResourceId:r.PhysicalResourceId,ResourceType:r.ResourceType||"",Timestamp:r.Timestamp||"",ResourceStatus:r.ResourceStatus||"",ResourceStatusReason:r.ResourceStatusReason}))}await Qe();var Fn=5242880,Pt=5242880,Un=5242880;class uc{region;endpoint;forcePathStyle;credentials;credentialOptions;retryOptions;constructor(e={}){this.region=e.region||process.env.AWS_REGION||"us-east-1",this.endpoint=e.endpoint||`https://s3.${this.region}.amazonaws.com`,this.forcePathStyle=e.forcePathStyle||!1,this.credentials=e.credentials,this.credentialOptions=e.credentialOptions,this.retryOptions=e.retryOptions||{}}async getCredentials(){if(this.credentials)return this.credentials;return Ao(this.credentialOptions)}buildUrl(e,a){let r=a?encodeURIComponent(a).replace(/%2F/g,"/"):"";if(this.forcePathStyle)return a?`${this.endpoint}/${e}/${r}`:`${this.endpoint}/${e}`;let n=new URL(this.endpoint);return n.hostname=`${e}.${n.hostname}`,a?`${n.origin}/${r}`:n.origin}async get(e,a,r={}){let n=await this.getCredentials(),i=this.buildUrl(e,a),o={};if(r.range)o.Range=r.range;if(r.ifModifiedSince)o["If-Modified-Since"]=r.ifModifiedSince.toUTCString();if(r.ifMatch)o["If-Match"]=r.ifMatch;if(r.ifNoneMatch)o["If-None-Match"]=r.ifNoneMatch;let c=new URL(i);if(r.responseContentType)c.searchParams.set("response-content-type",r.responseContentType);if(r.responseContentDisposition)c.searchParams.set("response-content-disposition",r.responseContentDisposition);let u=oe({method:"GET",url:c.toString(),headers:o,...n,service:"s3",region:this.region}),d=await fetch(u.url,{method:u.method,headers:u.headers});if(!d.ok&&d.status!==304){let m=await d.text();throw new Ce(`Failed to get object: ${m}`,d.status,e,a)}return d}async getText(e,a,r={}){return(await this.get(e,a,r)).text()}async getJSON(e,a,r={}){return(await this.get(e,a,r)).json()}async getBuffer(e,a,r={}){return(await this.get(e,a,r)).arrayBuffer()}async put(e,a,r,n={}){let i,o;if(typeof r==="string")i=new TextEncoder().encode(r).length,o=r;else if(r instanceof ArrayBuffer)i=r.byteLength,o=r;else if(r instanceof Uint8Array)i=r.byteLength,o=r;else if(r instanceof Blob)i=r.size,o=r;else return this.uploadMultipart(e,a,r,{...n,partSize:Pt});if(i>Un){let c=Kn(o).stream();return this.uploadMultipart(e,a,c,{...n,partSize:Pt})}return this.putSimple(e,a,o,i,n)}async putSimple(e,a,r,n,i){let o=await this.getCredentials(),c=this.buildUrl(e,a),u={"Content-Length":String(n),"Content-Type":i.contentType||fa(a)};if(i.contentEncoding)u["Content-Encoding"]=i.contentEncoding;if(i.cacheControl)u["Cache-Control"]=i.cacheControl;if(i.contentDisposition)u["Content-Disposition"]=i.contentDisposition;if(i.storageClass)u["x-amz-storage-class"]=i.storageClass;if(i.serverSideEncryption)u["x-amz-server-side-encryption"]=i.serverSideEncryption;if(i.acl)u["x-amz-acl"]=i.acl;if(i.tagging)u["x-amz-tagging"]=i.tagging;if(i.metadata)for(let[g,h]of Object.entries(i.metadata))u[`x-amz-meta-${g.toLowerCase()}`]=h;let d;if(typeof r==="string")d=r;else if(r instanceof Blob)d=await r.text();else d=new TextDecoder().decode(r instanceof ArrayBuffer?new Uint8Array(r):r);let m=oe({method:"PUT",url:c,headers:u,body:d,...o,service:"s3",region:this.region}),p=await fetch(m.url,{method:m.method,headers:m.headers,body:r});if(!p.ok){let g=await p.text();throw new Ce(`Failed to put object: ${g}`,p.status,e,a)}return{etag:(p.headers.get("ETag")||"").replace(/"/g,"")}}async delete(e,a){let r=await this.getCredentials(),n=this.buildUrl(e,a),i=oe({method:"DELETE",url:n,...r,service:"s3",region:this.region}),o=await fetch(i.url,{method:i.method,headers:i.headers});if(!o.ok&&o.status!==204){let c=await o.text();throw new Ce(`Failed to delete object: ${c}`,o.status,e,a)}}async deleteMany(e,a){let r=await this.getCredentials(),n=`${this.buildUrl(e)}?delete`,i=`<?xml version="1.0" encoding="UTF-8"?><Delete><Quiet>false</Quiet>${a.map((y)=>`<Object><Key>${jn(y)}</Key></Object>`).join("")}</Delete>`,o=oe({method:"POST",url:n,headers:{"Content-Type":"application/xml"},body:i,...r,service:"s3",region:this.region}),c=await fetch(o.url,{method:o.method,headers:o.headers,body:i});if(!c.ok){let y=await c.text();throw new Ce(`Failed to delete objects: ${y}`,c.status,e)}let u=await c.text(),d=[],m=[],p=/<Deleted><Key>([^<]+)<\/Key>/g,g;while((g=p.exec(u))!==null)d.push(g[1]);let h=/<Error><Key>([^<]+)<\/Key><Code>([^<]+)<\/Code><Message>([^<]+)<\/Message>/g;while((g=h.exec(u))!==null)m.push({key:g[1],error:`${g[2]}: ${g[3]}`});return{deleted:d,errors:m}}async list(e,a={}){let r=await this.getCredentials(),n=new URL(this.buildUrl(e));if(n.searchParams.set("list-type","2"),a.prefix)n.searchParams.set("prefix",a.prefix);if(a.delimiter)n.searchParams.set("delimiter",a.delimiter);if(a.maxKeys)n.searchParams.set("max-keys",String(a.maxKeys));if(a.continuationToken)n.searchParams.set("continuation-token",a.continuationToken);if(a.startAfter)n.searchParams.set("start-after",a.startAfter);let i=oe({method:"GET",url:n.toString(),...r,service:"s3",region:this.region}),o=await fetch(i.url,{method:i.method,headers:i.headers});if(!o.ok){let u=await o.text();throw new Ce(`Failed to list objects: ${u}`,o.status,e)}let c=await o.text();return Vn(c)}async*listAll(e,a={}){let r;do{let n=await this.list(e,{...a,continuationToken:r});for(let i of n.contents)yield i;r=n.nextContinuationToken}while(r)}async head(e,a){let r=await this.getCredentials(),n=this.buildUrl(e,a),i=oe({method:"HEAD",url:n,...r,service:"s3",region:this.region}),o=await fetch(i.url,{method:i.method,headers:i.headers});if(o.status===404)return null;if(!o.ok){let u=await o.text();throw new Ce(`Failed to head object: ${u}`,o.status,e,a)}let c={};return o.headers.forEach((u,d)=>{if(d.toLowerCase().startsWith("x-amz-meta-"))c[d.slice(11)]=u}),{contentLength:Number(o.headers.get("Content-Length")||0),contentType:o.headers.get("Content-Type")||"application/octet-stream",etag:(o.headers.get("ETag")||"").replace(/"/g,""),lastModified:new Date(o.headers.get("Last-Modified")||0),metadata:c,storageClass:o.headers.get("x-amz-storage-class")||void 0,serverSideEncryption:o.headers.get("x-amz-server-side-encryption")||void 0}}async exists(e,a){return await this.head(e,a)!==null}async copy(e,a,r,n,i={}){let o=await this.getCredentials(),c=this.buildUrl(r,n),u={"x-amz-copy-source":`/${e}/${encodeURIComponent(a)}`};if(i.metadataDirective)u["x-amz-metadata-directive"]=i.metadataDirective;if(i.contentType)u["Content-Type"]=i.contentType;if(i.storageClass)u["x-amz-storage-class"]=i.storageClass;if(i.acl)u["x-amz-acl"]=i.acl;if(i.metadata)for(let[g,h]of Object.entries(i.metadata))u[`x-amz-meta-${g.toLowerCase()}`]=h;let d=oe({method:"PUT",url:c,headers:u,...o,service:"s3",region:this.region}),m=await fetch(d.url,{method:d.method,headers:d.headers});if(!m.ok){let g=await m.text();throw new Ce(`Failed to copy object: ${g}`,m.status,r,n)}let p=(await m.text()).match(/<ETag>"?([^"<]+)"?<\/ETag>/);return{etag:p?p[1]:""}}async getPresignedUrl(e,a,r={}){let n=await this.getCredentials(),i=this.buildUrl(e,a);return cd({url:i,method:r.method||"GET",expiresIn:r.expiresIn||3600,...n,service:"s3",region:this.region})}async uploadMultipart(e,a,r,n={}){let i=await this.getCredentials(),o=Math.max(n.partSize||Pt,Fn),c,u;if(r instanceof ReadableStream)c=r;else if(r instanceof Blob)c=r.stream(),u=r.size;else{let p=new Blob([r]);c=p.stream(),u=p.size}let{uploadId:d,baseUrl:m}=await this.initiateMultipartUpload(e,a,n);try{let p=await this.uploadParts(e,a,m,d,c,o,i,u,n.concurrency||4,n.onProgress);return await this.completeMultipartUpload(e,a,m,d,p)}catch(p){throw await this.abortMultipartUpload(e,a,d,m).catch(()=>{}),p}}async initiateMultipartUpload(e,a,r){let n=await this.getCredentials(),i=this.buildUrl(e,a),o=`${i}?uploads`,c={"Content-Type":r.contentType||fa(a)};if(r.storageClass)c["x-amz-storage-class"]=r.storageClass;if(r.serverSideEncryption)c["x-amz-server-side-encryption"]=r.serverSideEncryption;if(r.acl)c["x-amz-acl"]=r.acl;if(r.metadata)for(let[g,h]of Object.entries(r.metadata))c[`x-amz-meta-${g.toLowerCase()}`]=h;let u=oe({method:"POST",url:o,headers:c,...n,service:"s3",region:this.region}),d=await fetch(u.url,{method:u.method,headers:u.headers});if(!d.ok){let g=await d.text();throw new Ce(`Failed to initiate multipart upload: ${g}`,d.status,e,a)}let m=(await d.text()).match(/<UploadId>([^<]+)<\/UploadId>/);if(!m)throw new Ce("Failed to parse upload ID from response",0,e,a);let p=i;if(d.url)try{let g=new URL(d.url);g.search="",p=g.toString()}catch{}return{uploadId:m[1],baseUrl:p}}async uploadParts(e,a,r,n,i,o,c,u,d,m){let p=[],g=i.getReader(),h=1,y=new Uint8Array(0),f=0,b=u?Math.ceil(u/o):void 0,v=new Map,w=async(T,N)=>{let I=`${r}?partNumber=${N}&uploadId=${encodeURIComponent(n)}`,k={"Content-Length":String(T.byteLength),"x-amz-content-sha256":"UNSIGNED-PAYLOAD"},O=oe({method:"PUT",url:I,headers:k,...c,service:"s3",region:this.region}),L=await fetch(O.url,{method:O.method,headers:O.headers,body:T,redirect:"error"});if(!L.ok){let W=await L.text();throw new Ce(`Failed to upload part ${N}: ${W}`,L.status,e,a)}let _=(L.headers.get("ETag")||"").replace(/"/g,"");if(!_)throw new Ce(`Missing ETag for part ${N}`,L.status,e,a);return{partNumber:N,etag:_}},R=async()=>{let T=await Promise.race(v.values());v.delete(T.partNumber),p.push(T)};while(!0){let{done:T,value:N}=await g.read();if(N){let I=new Uint8Array(y.length+N.length);I.set(y),I.set(N,y.length),y=I}while(y.length>=o||T&&y.length>0){let I=y.slice(0,o);y=y.slice(o);let k=h++;if(v.size>=d)await R();if(v.set(k,w(I,k)),f+=I.byteLength,m)m({loaded:f,total:u||f,part:k,totalParts:b||k})}if(T)break}while(v.size>0)await R();return p.sort((T,N)=>T.partNumber-N.partNumber),p}async completeMultipartUpload(e,a,r,n,i){let o=await this.getCredentials(),c=`${r}?uploadId=${encodeURIComponent(n)}`,u=`<?xml version="1.0" encoding="UTF-8"?><CompleteMultipartUpload>${i.map((g)=>`<Part><PartNumber>${g.partNumber}</PartNumber><ETag>"${g.etag}"</ETag></Part>`).join("")}</CompleteMultipartUpload>`,d=oe({method:"POST",url:c,headers:{"Content-Type":"application/xml"},body:u,...o,service:"s3",region:this.region}),m=await fetch(d.url,{method:d.method,headers:d.headers,body:u});if(!m.ok){let g=await m.text();throw new Ce(`Failed to complete multipart upload: ${g}`,m.status,e,a)}let p=(await m.text()).match(/<ETag>"?([^"<]+)"?<\/ETag>/);return{etag:p?p[1]:""}}async abortMultipartUpload(e,a,r,n){let i=await this.getCredentials(),o=`${n??this.buildUrl(e,a)}?uploadId=${encodeURIComponent(r)}`,c=oe({method:"DELETE",url:o,...i,service:"s3",region:this.region});await fetch(c.url,{method:c.method,headers:c.headers})}async emptyAndDeleteBucket(e){let a=[];for await(let o of this.listAll(e,{}))if(a.push(o.key),a.length>=1000)await this.deleteMany(e,a),a=[];if(a.length>0)await this.deleteMany(e,a);let r=await this.getCredentials(),n=this.buildUrl(e),i=oe({method:"DELETE",url:n,...r,service:"s3",region:this.region});await fetch(i.url,{method:i.method,headers:i.headers})}}class Ce extends Error{statusCode;bucket;key;constructor(e,a,r,n){super(e);this.statusCode=a,this.bucket=r,this.key=n,this.name="S3Error"}}function Vn(e){let a=[],r=[],n=/<Contents>([\s\S]*?)<\/Contents>/g,i;while((i=n.exec(e))!==null){let c=i[1];a.push({key:Q(c,"Key")||"",lastModified:new Date(Q(c,"LastModified")||0),etag:(Q(c,"ETag")||"").replace(/"/g,""),size:Number(Q(c,"Size")||0),storageClass:Q(c,"StorageClass")||"STANDARD"})}let o=/<CommonPrefixes><Prefix>([^<]+)<\/Prefix><\/CommonPrefixes>/g;while((i=o.exec(e))!==null)r.push(i[1]);return{contents:a,commonPrefixes:r,isTruncated:Q(e,"IsTruncated")==="true",continuationToken:Q(e,"ContinuationToken")||void 0,nextContinuationToken:Q(e,"NextContinuationToken")||void 0,keyCount:Number(Q(e,"KeyCount")||0),maxKeys:Number(Q(e,"MaxKeys")||1000),prefix:Q(e,"Prefix")||void 0,delimiter:Q(e,"Delimiter")||void 0}}function Q(e,a){let r=new RegExp(`<${a}>([^<]*)</${a}>`),n=e.match(r);return n?n[1]:null}function jn(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function fa(e){let a=e.split(".").pop()?.toLowerCase();return{html:"text/html",htm:"text/html",css:"text/css",js:"application/javascript",mjs:"application/javascript",json:"application/json",xml:"application/xml",txt:"text/plain",md:"text/markdown",csv:"text/csv",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",ico:"image/x-icon",avif:"image/avif",mp4:"video/mp4",webm:"video/webm",mov:"video/quicktime",avi:"video/x-msvideo",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",zip:"application/zip",gz:"application/gzip",tar:"application/x-tar",rar:"application/vnd.rar","7z":"application/x-7z-compressed",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",otf:"font/otf",eot:"application/vnd.ms-fontobject",wasm:"application/wasm"}[a||""]||"application/octet-stream"}function Kn(e){if(e instanceof Blob)return e;if(typeof e==="string")return new Blob([e],{type:"text/plain"});return new Blob([e])}function zp(e){return new uc(e)}await Qe();class Dd{profile;credentials=null;constructor(e="default"){this.profile=e}async init(){this.credentials=await Js(this.profile)}async ensureCredentials(){if(!this.credentials)await this.init();return this.credentials}async createInvalidation(e){let a=await this.ensureCredentials(),r=e.callerReference||`invalidation-${Date.now()}`,n=`<?xml version="1.0" encoding="UTF-8"?>
|
|
2497
2497
|
<InvalidationBatch>
|
|
2498
2498
|
<Paths>
|
|
2499
2499
|
<Quantity>${e.paths.length}</Quantity>
|
|
@@ -2507,12 +2507,12 @@ Reason: ${o.StackStatusReason||"Unknown"}`);await new Promise((c)=>setTimeout(c,
|
|
|
2507
2507
|
\uD83D\uDCA1 Solution: ${this.solution}`;if(this.details&&Object.keys(this.details).length>0){e+=`
|
|
2508
2508
|
|
|
2509
2509
|
Details:`;for(let[a,r]of Object.entries(this.details))e+=`
|
|
2510
|
-
${a}: ${JSON.stringify(r)}`}return e}}class Io extends wt{constructor(e,a,r){super(e,"CONFIG_ERROR",a,r);this.name="ConfigurationError"}}class Ar extends wt{constructor(e,a,r){super(e,"CREDENTIAL_ERROR",a,r);this.name="CredentialError"}}class kd extends wt{constructor(e,a,r){super(e,"DEPLOYMENT_ERROR",a,r);this.name="DeploymentError"}}class pc extends wt{constructor(e,a,r){super(e,"VALIDATION_ERROR",a,r);this.name="ValidationError"}}class
|
|
2510
|
+
${a}: ${JSON.stringify(r)}`}return e}}class Io extends wt{constructor(e,a,r){super(e,"CONFIG_ERROR",a,r);this.name="ConfigurationError"}}class Ar extends wt{constructor(e,a,r){super(e,"CREDENTIAL_ERROR",a,r);this.name="CredentialError"}}class kd extends wt{constructor(e,a,r){super(e,"DEPLOYMENT_ERROR",a,r);this.name="DeploymentError"}}class pc extends wt{constructor(e,a,r){super(e,"VALIDATION_ERROR",a,r);this.name="ValidationError"}}class _d extends wt{statusCode;constructor(e,a,r,n){super(e,"AWS_API_ERROR",r,n);this.statusCode=a,this.name="AWSAPIError"}}var xd={NO_CREDENTIALS:{message:"AWS credentials not found",solution:`Configure AWS credentials using one of these methods:
|
|
2511
2511
|
1. Set environment variables: AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY
|
|
2512
2512
|
2. Create ~/.aws/credentials file with your credentials
|
|
2513
2513
|
3. Use an IAM role (for EC2 instances)
|
|
2514
|
-
4. Run 'aws configure' if you have AWS CLI installed`},INVALID_CREDENTIALS:{message:"AWS credentials are invalid",solution:"Verify your AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are correct. Run: aws sts get-caller-identity"},EXPIRED_CREDENTIALS:{message:"AWS credentials have expired",solution:"Refresh your AWS credentials. If using temporary credentials, generate new ones."},MISSING_CONFIG:{message:"Configuration file not found",solution:"Create a cloud.config.ts file in your project root. Use: cloud init"},INVALID_CONFIG:{message:"Configuration is invalid",solution:"Check your cloud.config.ts file for syntax errors. Use: cloud config:validate"},MISSING_REQUIRED_FIELD:{message:"Required configuration field is missing",solution:"Add the missing field to your cloud.config.ts file"},INVALID_REGION:{message:"AWS region is invalid",solution:"Use a valid AWS region like us-east-1, us-west-2, eu-west-1, etc."},STACK_ALREADY_EXISTS:{message:"CloudFormation stack already exists",solution:"Use: cloud deploy --update to update the existing stack, or cloud destroy to delete it first"},STACK_IN_PROGRESS:{message:"Stack operation already in progress",solution:"Wait for the current operation to complete, or cancel it in the AWS Console"},INSUFFICIENT_PERMISSIONS:{message:"Insufficient IAM permissions",solution:"Ensure your IAM user/role has the necessary permissions for CloudFormation and the resources you're deploying"},RESOURCE_LIMIT_EXCEEDED:{message:"AWS service limit exceeded",solution:"Request a service limit increase in the AWS Console, or clean up unused resources"},ROLLBACK_COMPLETE:{message:"Stack creation failed and rolled back",solution:"Check the CloudFormation events to see which resource failed. Fix the issue and try again."},CIRCULAR_DEPENDENCY:{message:"Circular dependency detected in resources",solution:"Review your resource dependencies and remove the circular reference"},INVALID_RESOURCE_NAME:{message:"Resource name contains invalid characters",solution:"Use only alphanumeric characters and hyphens in resource names"},DUPLICATE_RESOURCE:{message:"Duplicate resource name detected",solution:"Ensure all resource names are unique in your configuration"},VPC_CIDR_CONFLICT:{message:"VPC CIDR block conflicts with existing VPC",solution:"Use a different CIDR block that doesn't overlap with existing VPCs"},SUBNET_CIDR_INVALID:{message:"Subnet CIDR block is invalid or outside VPC range",solution:"Ensure subnet CIDR is within the VPC CIDR range and properly sized"},DB_INSTANCE_LIMIT:{message:"RDS instance limit reached",solution:"Delete unused RDS instances or request a limit increase"},INVALID_DB_NAME:{message:"Database name contains invalid characters",solution:"Use only alphanumeric characters and underscores, starting with a letter"},BUCKET_ALREADY_EXISTS:{message:"S3 bucket name already exists globally",solution:"S3 bucket names must be globally unique. Try a different name with your organization prefix"},INVALID_BUCKET_NAME:{message:"S3 bucket name is invalid",solution:"Use lowercase letters, numbers, and hyphens. Must start/end with letter/number. 3-63 characters."},TEMPLATE_TOO_LARGE:{message:"CloudFormation template exceeds size limit",solution:"Split your infrastructure into multiple stacks or use nested stacks"},INVALID_TEMPLATE:{message:"CloudFormation template is invalid",solution:"Validate your template with: cloud config:validate"},PARAMETER_NOT_FOUND:{message:"CloudFormation parameter not found",solution:"Check that all referenced parameters are defined in your template"}};function $d(e){return
|
|
2515
|
-
Stack trace:`),console.error(a.stack)}}static success(e){console.log(`✔ ${e}`)}}function
|
|
2514
|
+
4. Run 'aws configure' if you have AWS CLI installed`},INVALID_CREDENTIALS:{message:"AWS credentials are invalid",solution:"Verify your AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are correct. Run: aws sts get-caller-identity"},EXPIRED_CREDENTIALS:{message:"AWS credentials have expired",solution:"Refresh your AWS credentials. If using temporary credentials, generate new ones."},MISSING_CONFIG:{message:"Configuration file not found",solution:"Create a cloud.config.ts file in your project root. Use: cloud init"},INVALID_CONFIG:{message:"Configuration is invalid",solution:"Check your cloud.config.ts file for syntax errors. Use: cloud config:validate"},MISSING_REQUIRED_FIELD:{message:"Required configuration field is missing",solution:"Add the missing field to your cloud.config.ts file"},INVALID_REGION:{message:"AWS region is invalid",solution:"Use a valid AWS region like us-east-1, us-west-2, eu-west-1, etc."},STACK_ALREADY_EXISTS:{message:"CloudFormation stack already exists",solution:"Use: cloud deploy --update to update the existing stack, or cloud destroy to delete it first"},STACK_IN_PROGRESS:{message:"Stack operation already in progress",solution:"Wait for the current operation to complete, or cancel it in the AWS Console"},INSUFFICIENT_PERMISSIONS:{message:"Insufficient IAM permissions",solution:"Ensure your IAM user/role has the necessary permissions for CloudFormation and the resources you're deploying"},RESOURCE_LIMIT_EXCEEDED:{message:"AWS service limit exceeded",solution:"Request a service limit increase in the AWS Console, or clean up unused resources"},ROLLBACK_COMPLETE:{message:"Stack creation failed and rolled back",solution:"Check the CloudFormation events to see which resource failed. Fix the issue and try again."},CIRCULAR_DEPENDENCY:{message:"Circular dependency detected in resources",solution:"Review your resource dependencies and remove the circular reference"},INVALID_RESOURCE_NAME:{message:"Resource name contains invalid characters",solution:"Use only alphanumeric characters and hyphens in resource names"},DUPLICATE_RESOURCE:{message:"Duplicate resource name detected",solution:"Ensure all resource names are unique in your configuration"},VPC_CIDR_CONFLICT:{message:"VPC CIDR block conflicts with existing VPC",solution:"Use a different CIDR block that doesn't overlap with existing VPCs"},SUBNET_CIDR_INVALID:{message:"Subnet CIDR block is invalid or outside VPC range",solution:"Ensure subnet CIDR is within the VPC CIDR range and properly sized"},DB_INSTANCE_LIMIT:{message:"RDS instance limit reached",solution:"Delete unused RDS instances or request a limit increase"},INVALID_DB_NAME:{message:"Database name contains invalid characters",solution:"Use only alphanumeric characters and underscores, starting with a letter"},BUCKET_ALREADY_EXISTS:{message:"S3 bucket name already exists globally",solution:"S3 bucket names must be globally unique. Try a different name with your organization prefix"},INVALID_BUCKET_NAME:{message:"S3 bucket name is invalid",solution:"Use lowercase letters, numbers, and hyphens. Must start/end with letter/number. 3-63 characters."},TEMPLATE_TOO_LARGE:{message:"CloudFormation template exceeds size limit",solution:"Split your infrastructure into multiple stacks or use nested stacks"},INVALID_TEMPLATE:{message:"CloudFormation template is invalid",solution:"Validate your template with: cloud config:validate"},PARAMETER_NOT_FOUND:{message:"CloudFormation parameter not found",solution:"Check that all referenced parameters are defined in your template"}};function $d(e){return xd[e]}function mc(e,a){let r=$d(e);return new wt(r.message,e,r.solution,a)}class De{static verboseMode=!1;static debugMode=!1;static setVerbose(e){this.verboseMode=e}static setDebug(e){this.debugMode=e}static verbose(e,...a){if(this.verboseMode)console.log(`[VERBOSE] ${e}`,...a)}static debug(e,...a){if(this.debugMode)console.log(`[DEBUG] ${e}`,...a)}static info(e,...a){console.log(`ℹ ${e}`,...a)}static warn(e,...a){console.warn(`⚠ ${e}`,...a)}static error(e,a){if(console.error(`✖ ${e}`),a){if(a instanceof wt)console.error(a.toString());else console.error(a.message);if(this.debugMode&&a.stack)console.error(`
|
|
2515
|
+
Stack trace:`),console.error(a.stack)}}static success(e){console.log(`✔ ${e}`)}}function Hp(e){if(!e)throw mc("MISSING_CONFIG");if(!e.project)throw new Io("Missing required field: project","Add a project configuration with name, slug, and region",{field:"project"});if(!e.project.name)throw new Io("Missing required field: project.name","Add a project name to your configuration",{field:"project.name"});if(!e.project.slug)throw new Io("Missing required field: project.slug","Add a project slug (lowercase, alphanumeric with hyphens)",{field:"project.slug"});if(!/^[a-z0-9-]+$/.test(e.project.slug))throw new pc("Invalid project slug format","Use only lowercase letters, numbers, and hyphens",{slug:e.project.slug});if(e.project.region){if(!["us-east-1","us-east-2","us-west-1","us-west-2","eu-west-1","eu-west-2","eu-west-3","eu-central-1","ap-southeast-1","ap-southeast-2","ap-northeast-1","ap-northeast-2","sa-east-1","ca-central-1"].includes(e.project.region))throw mc("INVALID_REGION",{region:e.project.region})}De.success("Configuration validation passed")}function qp(e){let a=[];if(e.environments?.production&&e.infrastructure?.database){let r=e.infrastructure.database;if((r.postgres||r.mysql)&&!r.postgres?.multiAZ&&!r.mysql?.multiAZ)a.push("Production database should use Multi-AZ for high availability")}if(e.infrastructure?.storage){for(let[r,n]of Object.entries(e.infrastructure.storage))if(n.encryption===!1)a.push(`Storage "${r}" is not encrypted - consider enabling encryption for security`)}if(e.infrastructure?.storage){for(let[r,n]of Object.entries(e.infrastructure.storage))if(n.public===!0)a.push(`Storage "${r}" is publicly accessible - ensure this is intentional`)}if(e.infrastructure?.database){let r=e.infrastructure.database;if(r.postgres||r.mysql){let n=r.postgres?.backupRetentionDays||r.mysql?.backupRetentionDays;if(!n||n<7)a.push("Database backup retention is less than 7 days - consider increasing for production")}}if(!e.infrastructure?.monitoring)a.push("No monitoring configured - consider adding CloudWatch alarms");return a}async function Wp(e="default"){try{De.verbose("Resolving AWS credentials...");let a=await Js(e);if(!a.accessKeyId||!a.secretAccessKey)throw new Ar("AWS credentials are incomplete","Ensure both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are set");De.verbose("Credentials resolved successfully"),De.debug("Access Key ID:",a.accessKeyId.substring(0,8)+"..."),De.verbose("Testing credentials with GetCallerIdentity...");let r;try{r=await Pd(a),De.verbose("Credentials are valid"),De.debug("Account ID:",r)}catch(n){if(n instanceof Error)if(n.message.includes("InvalidClientTokenId"))throw new Ar("Invalid AWS access key ID","Check that your AWS_ACCESS_KEY_ID is correct");else if(n.message.includes("SignatureDoesNotMatch"))throw new Ar("Invalid AWS secret access key","Check that your AWS_SECRET_ACCESS_KEY is correct");else if(n.message.includes("ExpiredToken"))throw new Ar("AWS credentials have expired","Refresh your temporary credentials or use long-term credentials");else throw new Ar(`Failed to validate credentials: ${n.message}`,"Verify your AWS credentials are correct and have the necessary permissions");throw n}return{valid:!0,accountId:r,region:a.region}}catch(a){if(a instanceof Ar)throw a;return{valid:!1,error:a instanceof Error?a.message:"Unknown error"}}}async function Gp(e,a){return{allowed:a,denied:[]}}function Od(e){let a=new Set(["cloudformation:CreateStack","cloudformation:UpdateStack","cloudformation:DeleteStack","cloudformation:DescribeStacks","cloudformation:DescribeStackEvents","cloudformation:GetTemplate","cloudformation:ListStacks"]);if(e.infrastructure){if(e.infrastructure.storage)a.add("s3:CreateBucket"),a.add("s3:DeleteBucket"),a.add("s3:PutBucketPolicy"),a.add("s3:PutBucketVersioning"),a.add("s3:PutBucketEncryption"),a.add("s3:PutObject"),a.add("s3:GetObject");if(e.infrastructure.compute){if(e.infrastructure.compute.server)a.add("ec2:RunInstances"),a.add("ec2:TerminateInstances"),a.add("ec2:DescribeInstances"),a.add("autoscaling:CreateAutoScalingGroup"),a.add("autoscaling:UpdateAutoScalingGroup"),a.add("autoscaling:DeleteAutoScalingGroup"),a.add("elasticloadbalancing:CreateLoadBalancer"),a.add("elasticloadbalancing:DeleteLoadBalancer");if(e.infrastructure.compute.fargate)a.add("ecs:CreateCluster"),a.add("ecs:DeleteCluster"),a.add("ecs:CreateService"),a.add("ecs:UpdateService"),a.add("ecs:DeleteService"),a.add("ecs:RegisterTaskDefinition")}if(e.infrastructure.database){if(e.infrastructure.database.postgres||e.infrastructure.database.mysql)a.add("rds:CreateDBInstance"),a.add("rds:DeleteDBInstance"),a.add("rds:ModifyDBInstance"),a.add("rds:DescribeDBInstances");if(e.infrastructure.database.dynamodb)a.add("dynamodb:CreateTable"),a.add("dynamodb:DeleteTable"),a.add("dynamodb:UpdateTable"),a.add("dynamodb:DescribeTable")}if(e.infrastructure.functions)a.add("lambda:CreateFunction"),a.add("lambda:DeleteFunction"),a.add("lambda:UpdateFunctionCode"),a.add("lambda:UpdateFunctionConfiguration"),a.add("lambda:AddPermission");if(e.infrastructure.cdn)a.add("cloudfront:CreateDistribution"),a.add("cloudfront:UpdateDistribution"),a.add("cloudfront:DeleteDistribution"),a.add("cloudfront:GetDistribution");if(e.infrastructure.network)a.add("ec2:CreateVpc"),a.add("ec2:DeleteVpc"),a.add("ec2:CreateSubnet"),a.add("ec2:DeleteSubnet"),a.add("ec2:CreateInternetGateway"),a.add("ec2:DeleteInternetGateway"),a.add("ec2:CreateNatGateway"),a.add("ec2:DeleteNatGateway"),a.add("ec2:CreateRouteTable"),a.add("ec2:DeleteRouteTable"),a.add("ec2:CreateSecurityGroup"),a.add("ec2:DeleteSecurityGroup")}return a.add("iam:CreateRole"),a.add("iam:DeleteRole"),a.add("iam:AttachRolePolicy"),a.add("iam:DetachRolePolicy"),a.add("iam:PutRolePolicy"),a.add("iam:GetRole"),a.add("iam:PassRole"),Array.from(a).sort()}function Kp(e){let a=Od(e);return JSON.stringify({Version:"2012-10-17",Statement:[{Effect:"Allow",Action:a,Resource:"*"}]},null,2)}var Ae={ec2:{"Running On-Demand Instances":20,"Elastic IPs":5,VPCs:5,"Internet Gateways":5,"NAT Gateways":5,"Security Groups":500},rds:{"DB Instances":40,"DB Snapshots":100,"DB Parameter Groups":50},lambda:{"Concurrent Executions":1000,"Function Storage":80530636800},s3:{Buckets:100},cloudformation:{Stacks:200,StackSets:100},elasticache:{Nodes:100,Clusters:100},dynamodb:{Tables:256},ecs:{Clusters:1e4,"Services per Cluster":2000}};async function Jp(e){let a=[];if(De.verbose("Checking AWS service quotas..."),e.infrastructure?.compute?.server){let n=e.infrastructure.compute.server.autoScaling?.max||1;a.push({service:"EC2",quotaName:"Running On-Demand Instances",currentValue:n,limit:Ae.ec2["Running On-Demand Instances"],percentage:n/Ae.ec2["Running On-Demand Instances"]*100,warning:n>Ae.ec2["Running On-Demand Instances"]*0.8})}if(e.infrastructure?.network?.vpc)a.push({service:"EC2",quotaName:"VPCs",currentValue:1,limit:Ae.ec2.VPCs,percentage:1/Ae.ec2.VPCs*100,warning:!1});if(e.infrastructure?.database?.postgres||e.infrastructure?.database?.mysql)a.push({service:"RDS",quotaName:"DB Instances",currentValue:1,limit:Ae.rds["DB Instances"],percentage:1/Ae.rds["DB Instances"]*100,warning:!1});if(e.infrastructure?.storage){let n=Object.keys(e.infrastructure.storage).length;a.push({service:"S3",quotaName:"Buckets",currentValue:n,limit:Ae.s3.Buckets,percentage:n/Ae.s3.Buckets*100,warning:n>Ae.s3.Buckets*0.8})}if(e.infrastructure?.functions){let n=0;for(let i of Object.values(e.infrastructure.functions))if(Array.isArray(i))n+=i.length;a.push({service:"Lambda",quotaName:"Functions (estimated)",currentValue:n,limit:1000,percentage:n/1000*100,warning:n>800})}if(e.infrastructure?.database?.dynamodb){let n=e.infrastructure.database.dynamodb.tables?.length||0;a.push({service:"DynamoDB",quotaName:"Tables",currentValue:n,limit:Ae.dynamodb.Tables,percentage:n/Ae.dynamodb.Tables*100,warning:n>Ae.dynamodb.Tables*0.8})}let r=a.filter((n)=>n.warning);if(r.length>0){De.warn("Service quota warnings detected:");for(let n of r)De.warn(` ${n.service} - ${n.quotaName}: ${n.currentValue}/${n.limit} (${n.percentage.toFixed(1)}%)`)}else De.verbose("All service quotas are within limits");return a}function Xp(e){if(e.length===0)return"No quotas to check";let a=`Service Quota Usage:
|
|
2516
2516
|
|
|
2517
2517
|
`,r=e.reduce((n,i)=>{if(!n[i.service])n[i.service]=[];return n[i.service].push(i),n},{});for(let[n,i]of Object.entries(r)){a+=`${n}:
|
|
2518
2518
|
`;for(let o of i){let c=o.warning?"⚠":"✓";a+=` ${c} ${o.quotaName}: ${o.currentValue}/${o.limit} (${o.percentage.toFixed(1)}%)
|
|
@@ -2749,7 +2749,7 @@ jobs:
|
|
|
2749
2749
|
$SLACK_WEBHOOK_URL`:'run: |\n echo "${{ steps.cost.outputs.cost_json }}"'}
|
|
2750
2750
|
`}class wc{channels=[];addChannel(e){this.channels.push(e)}removeChannel(e){this.channels=this.channels.filter((a)=>a.type!==e)}async notify(e){let a=this.channels.map((r)=>this.sendToChannel(r,e));await Promise.allSettled(a)}async sendToChannel(e,a){switch(e.type){case"slack":await this.sendToSlack(e.config,a);break;case"discord":await this.sendToDiscord(e.config,a);break;case"email":await this.sendToEmail(e.config,a);break;case"webhook":await this.sendToWebhook(e.config,a);break}}async sendToSlack(e,a){let r=this.formatSlackMessage(a,e),n=await fetch(e.webhookUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!n.ok)throw Error(`Failed to send Slack notification: ${n.statusText}`)}formatSlackMessage(e,a){let{environment:r,type:n}=e,i={created:":rocket:",updated:":arrows_counterclockwise:",destroyed:":wastebasket:",failed:":x:",expired:":hourglass_flowing_sand:"}[n],o={created:"#36a64f",updated:"#2196F3",destroyed:"#808080",failed:"#f44336",expired:"#ff9800"}[n],c={created:"Preview Environment Created",updated:"Preview Environment Updated",destroyed:"Preview Environment Destroyed",failed:"Preview Environment Failed",expired:"Preview Environment Expired"}[n];return{username:a.username||"ts-cloud",icon_emoji:a.iconEmoji||":cloud:",channel:a.channel,attachments:[{color:o,title:`${i} ${c}`,fields:[{title:"Environment",value:r.name,short:!0},{title:"Branch",value:r.branch,short:!0},...r.pr?[{title:"PR",value:`#${r.pr}`,short:!0}]:[],{title:"Commit",value:r.commitSha.substring(0,7),short:!0},...r.url?[{title:"URL",value:r.url,short:!1}]:[],...n==="created"?[{title:"Expires",value:r.expiresAt.toLocaleString(),short:!0}]:[]],footer:"ts-cloud Preview Environments",ts:Math.floor(e.timestamp.getTime()/1000)}]}}async sendToDiscord(e,a){let r=this.formatDiscordMessage(a,e),n=await fetch(e.webhookUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!n.ok)throw Error(`Failed to send Discord notification: ${n.statusText}`)}formatDiscordMessage(e,a){let{environment:r,type:n}=e,i={created:":rocket:",updated:":arrows_counterclockwise:",destroyed:":wastebasket:",failed:":x:",expired:":hourglass:"}[n],o={created:3581519,updated:2201331,destroyed:8421504,failed:16007990,expired:16750592}[n],c={created:"Preview Environment Created",updated:"Preview Environment Updated",destroyed:"Preview Environment Destroyed",failed:"Preview Environment Failed",expired:"Preview Environment Expired"}[n];return{username:a.username||"ts-cloud",avatar_url:a.avatarUrl,embeds:[{title:`${i} ${c}`,color:o,fields:[{name:"Environment",value:r.name,inline:!0},{name:"Branch",value:r.branch,inline:!0},...r.pr?[{name:"PR",value:`#${r.pr}`,inline:!0}]:[],{name:"Commit",value:`\`${r.commitSha.substring(0,7)}\``,inline:!0},...r.url?[{name:"URL",value:r.url,inline:!1}]:[]],timestamp:e.timestamp.toISOString(),footer:{text:"ts-cloud Preview Environments"}}]}}async sendToEmail(e,a){console.log(`Email notification would be sent to ${e.to.join(", ")}`)}async sendToWebhook(e,a){let r=await fetch(e.url,{method:e.method||"POST",headers:{"Content-Type":"application/json",...e.headers},body:JSON.stringify({event:a.type,environment:a.environment,timestamp:a.timestamp.toISOString(),metadata:a.metadata})});if(!r.ok)throw Error(`Failed to send webhook notification: ${r.statusText}`)}}var Rm=new wc;function Pm(e){let{columns:a,data:r,border:n=!0,header:i=!0,compact:o=!1,maxWidth:c}=e;if(r.length===0)return"No data to display";let u=a.map((m)=>{let p=m.label.length,g=Math.max(...r.map((y)=>(m.formatter?m.formatter(y[m.key]):String(y[m.key]||"")).length)),h=m.width||Math.max(p,g);if(c&&h>c)h=c;return h}),d=[];if(n)d.push(Nt(u,"top",o));if(i){if(d.push(Aa(a.map((m)=>m.label),u,a.map((m)=>m.align||"left"),n)),n)d.push(Nt(u,"middle",o))}for(let m of r){let p=a.map((g)=>{let h=g.formatter?g.formatter(m[g.key]):String(m[g.key]||"");return ei(h,u[a.indexOf(g)])});d.push(Aa(p,u,a.map((g)=>g.align||"left"),n))}if(n)d.push(Nt(u,"bottom",o));return d.join(`
|
|
2751
2751
|
`)}function Aa(e,a,r,n){let i=e.map((o,c)=>{let u=a[c],d=r[c];return Xn(o,u,d)});if(n)return`│ ${i.join(" │ ")} │`;return i.join(" ")}function Nt(e,a,r){let n=a==="top"?"┌":a==="middle"?"├":"└",i=a==="top"?"┐":a==="middle"?"┤":"┘",o=a==="top"?"┬":a==="middle"?"┼":"┴",c="─";if(r)return n+e.map((u)=>"─".repeat(u+2)).join(o)+i;return n+e.map((u)=>"─".repeat(u+2)).join(o)+i}function Xn(e,a,r){let n=Fa(e).length;if(n>=a)return e;let i=a-n;switch(r){case"right":return" ".repeat(i)+e;case"center":{let o=Math.floor(i/2),c=i-o;return" ".repeat(o)+e+" ".repeat(c)}default:return e+" ".repeat(i)}}function ei(e,a){if(Fa(e).length<=a)return e;return e.substring(0,a-1)+"…"}function Fa(e){return e.replace(/\x1B\[[0-9;]*m/g,"")}function Nm(e,a={}){let{indent:r=" ",showMetadata:n=!1}=a,i=[];function o(c,u,d){let m=u+(d?"└─ ":"├─ ")+c.label;if(i.push(m),n&&c.metadata){let p=u+(d?" ":"│ ");for(let[g,h]of Object.entries(c.metadata))i.push(`${p}${g}: ${h}`)}if(c.children&&c.children.length>0){let p=u+(d?" ":"│ ");c.children.forEach((g,h)=>{o(g,p,h===c.children.length-1)})}}return e.forEach((c,u)=>{o(c,"",u===e.length-1)}),i.join(`
|
|
2752
|
-
`)}function Dm(e){let{total:a,current:r,width:n=40,format:i=":bar :percent :current/:total",complete:o="█",incomplete:c="░"}=e,u=Math.min(100,Math.max(0,r/a*100)),d=Math.floor(n*r/a),m=n-d,p=o.repeat(d)+c.repeat(m);return i.replace(":bar",p).replace(":percent",`${u.toFixed(0)}%`).replace(":current",String(r)).replace(":total",String(a))}function km(e,a=2){if(e===0)return"0 Bytes";let r=1024,n=a<0?0:a,i=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],o=Math.floor(Math.log(e)/Math.log(r));return`${Number.parseFloat((e/Math.pow(r,o)).toFixed(n))} ${i[o]}`}function
|
|
2752
|
+
`)}function Dm(e){let{total:a,current:r,width:n=40,format:i=":bar :percent :current/:total",complete:o="█",incomplete:c="░"}=e,u=Math.min(100,Math.max(0,r/a*100)),d=Math.floor(n*r/a),m=n-d,p=o.repeat(d)+c.repeat(m);return i.replace(":bar",p).replace(":percent",`${u.toFixed(0)}%`).replace(":current",String(r)).replace(":total",String(a))}function km(e,a=2){if(e===0)return"0 Bytes";let r=1024,n=a<0?0:a,i=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],o=Math.floor(Math.log(e)/Math.log(r));return`${Number.parseFloat((e/Math.pow(r,o)).toFixed(n))} ${i[o]}`}function _m(e){if(e<1000)return`${e}ms`;let a=Math.floor(e/1000);if(a<60)return`${a}s`;let r=Math.floor(a/60),n=a%60;if(r<60)return n>0?`${r}m ${n}s`:`${r}m`;let i=Math.floor(r/60),o=r%60;if(i<24)return o>0?`${i}h ${o}m`:`${i}h`;let c=Math.floor(i/24),u=i%24;return u>0?`${c}d ${u}h`:`${c}d`}function xm(e,a="•"){return e.map((r)=>`${a} ${r}`).join(`
|
|
2753
2753
|
`)}function $m(e,a={}){let{indent:r="",separator:n=": "}=a,i=Math.max(...Object.keys(e).map((o)=>o.length));return Object.entries(e).map(([o,c])=>{let u=o.padEnd(i);return`${r}${u}${n}${c}`}).join(`
|
|
2754
2754
|
`)}class Bd{total;current=0;width;format;message;showETA;showPercentage;showCounter;startTime=Date.now();lastUpdate=0;constructor(e){this.total=e.total,this.current=e.current||0,this.width=e.width||40,this.format=e.format||":message :bar :percent :eta",this.message=e.message||"Progress",this.showETA=e.showETA!==!1,this.showPercentage=e.showPercentage!==!1,this.showCounter=e.showCounter!==!1}tick(e=1){this.current=Math.min(this.total,this.current+e),this.lastUpdate=Date.now()}update(e){this.current=Math.min(this.total,Math.max(0,e)),this.lastUpdate=Date.now()}setMessage(e){this.message=e}getPercentage(){return Math.min(100,this.current/this.total*100)}getETA(){if(this.current===0)return 0;let e=Date.now()-this.startTime,a=this.current/e,r=this.total-this.current;return Math.round(r/a)}getETAFormatted(){if(this.current===0)return"calculating...";if(this.current===this.total)return"complete";let e=this.getETA();if(e<1000)return"< 1s";if(e<60000)return`${Math.round(e/1000)}s`;let a=Math.floor(e/60000);if(a<60)return`${a}m`;let r=Math.floor(a/60),n=a%60;if(r<24)return n>0?`${r}h ${n}m`:`${r}h`;let i=Math.floor(r/24),o=r%24;return o>0?`${i}d ${o}h`:`${i}d`}render(){let e=this.getPercentage(),a=Math.floor(this.width*this.current/this.total),r=this.width-a,n="█".repeat(a)+"░".repeat(r),i=`${e.toFixed(1)}%`,o=`${this.current}/${this.total}`,c=this.showETA?`ETA: ${this.getETAFormatted()}`:"",u=this.format.replace(":message",this.message).replace(":bar",n).replace(":percent",this.showPercentage?i:"").replace(":counter",this.showCounter?o:"").replace(":eta",c).replace(":current",String(this.current)).replace(":total",String(this.total));return u=u.replace(/\s+/g," ").trim(),u}isComplete(){return this.current>=this.total}}class Fd{steps;currentStepIndex=0;constructor(e){this.steps=e.map((a)=>({name:a,status:"pending"}))}startStep(e,a){if(e>=0&&e<this.steps.length)this.steps[e].status="active",this.steps[e].message=a,this.currentStepIndex=e}completeStep(e){if(this.currentStepIndex>=0&&this.currentStepIndex<this.steps.length)this.steps[this.currentStepIndex].status="completed",this.steps[this.currentStepIndex].message=e,this.currentStepIndex++}failStep(e){if(this.currentStepIndex>=0&&this.currentStepIndex<this.steps.length)this.steps[this.currentStepIndex].status="failed",this.steps[this.currentStepIndex].error=e}skipStep(e){if(this.currentStepIndex>=0&&this.currentStepIndex<this.steps.length)this.steps[this.currentStepIndex].status="skipped",this.steps[this.currentStepIndex].message=e,this.currentStepIndex++}getStep(e){return this.steps[e]}getSteps(){return this.steps}render(){let e=[];for(let a of this.steps){let r=`${this.getStatusIcon(a.status)} ${a.name}`;if(a.message)r+=` - ${a.message}`;if(a.error)r+=`
|
|
2755
2755
|
Error: ${a.error}`;e.push(r)}return e.join(`
|
|
@@ -2768,9 +2768,9 @@ ${a.map((r)=>` • ${r}`).join(`
|
|
|
2768
2768
|
`)}function Vm(e){let a=[];if(a.push(`Usage: ts-cloud ${e.name}`),a.push(""),a.push(e.description),e.aliases&&e.aliases.length>0)a.push(""),a.push(`Aliases: ${e.aliases.join(", ")}`);if(e.examples&&e.examples.length>0){a.push(""),a.push("Examples:");for(let r of e.examples)a.push(` ${r}`)}return a.join(`
|
|
2769
2769
|
`)}function zm(e,a,r=[]){let n={valid:!0,errors:[],warnings:[],suggestions:[]},[i,...o]=e.split(" ");if(!a.includes(i)){n.valid=!1,n.errors.push(`Unknown command: ${i}`);let c=Cc(i,a);if(c.length>0)n.suggestions.push(...c)}for(let c of r)if(!o.some((u)=>u===`--${c}`||u.startsWith(`--${c}=`)))n.valid=!1,n.errors.push(`Missing required flag: --${c}`);return n}class zd{options;running=!1;history={commands:[],maxSize:1000};historyIndex=-1;constructor(e){this.options={prompt:e.prompt||"> ",welcome:e.welcome||'Welcome to ts-cloud interactive mode. Type "help" for available commands.',...e}}async start(){if(this.running=!0,this.options.welcome)console.log(this.options.welcome),console.log("");if(this.options.historyFile)await this.loadHistory();while(this.running)try{let e=await this.readInput();if(!e.trim())continue;this.addToHistory(e),await this.executeCommand(e)}catch(e){if(e instanceof Error)console.error(`Error: ${e.message}`)}if(this.options.historyFile)await this.saveHistory()}stop(){this.running=!1}async readInput(){return new Promise((e)=>{process.stdout.write(this.options.prompt||"> "),e("")})}async executeCommand(e){let[a,...r]=this.parseCommand(e);if(a==="exit"||a==="quit"){this.stop();return}if(a==="help"){this.showHelp();return}if(a==="history"){this.showHistory();return}if(a==="clear"){console.clear();return}let n=this.findCommand(a);if(!n){console.error(`Unknown command: ${a}`),console.log('Type "help" to see available commands.');return}try{await n.handler(r)}catch(i){if(i instanceof Error)console.error(`Command failed: ${i.message}`)}}parseCommand(e){return e.trim().split(/\s+/)}findCommand(e){for(let[a,r]of this.options.commands)if(r.name===e||r.aliases?.includes(e))return r;return}showHelp(){console.log("Available commands:"),console.log("");let e=Array.from(this.options.commands.values());console.log(" help Show this help message"),console.log(" history Show command history"),console.log(" clear Clear screen"),console.log(" exit, quit Exit interactive mode"),console.log("");for(let a of e){let r=` ${a.name.padEnd(20)} ${a.description}`;if(a.aliases&&a.aliases.length>0)r+=` (aliases: ${a.aliases.join(", ")})`;console.log(r)}}showHistory(){if(this.history.commands.length===0){console.log("No command history");return}console.log("Command history:"),this.history.commands.forEach((e,a)=>{console.log(` ${(a+1).toString().padStart(4)} ${e}`)})}addToHistory(e){if(this.history.commands[this.history.commands.length-1]===e)return;if(this.history.commands.push(e),this.history.commands.length>this.history.maxSize)this.history.commands=this.history.commands.slice(-this.history.maxSize);this.historyIndex=this.history.commands.length}historyBack(){if(this.historyIndex>0)return this.historyIndex--,this.history.commands[this.historyIndex];return}historyForward(){if(this.historyIndex<this.history.commands.length-1)return this.historyIndex++,this.history.commands[this.historyIndex];return this.historyIndex=this.history.commands.length,""}autocomplete(e){let a=[],r=["help","history","clear","exit","quit"];for(let n of r)if(n.startsWith(e))a.push(n);for(let[n,i]of this.options.commands){if(i.name.startsWith(e))a.push(i.name);if(i.aliases){for(let o of i.aliases)if(o.startsWith(e))a.push(o)}}return a}async loadHistory(){if(!this.options.historyFile)return;try{let e=await import("node:fs/promises"),a=await e.readFile(this.options.historyFile,"utf-8");this.history.commands=a.split(`
|
|
2770
2770
|
`).filter((r)=>r.trim()),this.historyIndex=this.history.commands.length}catch{}}async saveHistory(){if(!this.options.historyFile)return;try{let e=await import("node:fs/promises");await e.writeFile(this.options.historyFile,this.history.commands.join(`
|
|
2771
|
-
`))}catch(e){console.error(`Failed to save history: ${e}`)}}searchHistory(e){return this.history.commands.filter((a)=>a.includes(e))}clearHistory(){this.history.commands=[],this.historyIndex=0}}class
|
|
2772
|
-
`)}importJSON(e){let a=JSON.parse(e).map((r)=>({...r,timestamp:new Date(r.timestamp)}));if(this.entries.push(...a),this.entries.length>this.maxSize)this.entries=this.entries.slice(-this.maxSize)}groupByDate(){let e=new Map;for(let a of this.entries){let r=a.timestamp.toISOString().split("T")[0];if(!e.has(r))e.set(r,[]);e.get(r).push(a)}return e}groupByCommand(){let e=new Map;for(let a of this.entries){let r=a.command.split(" ")[0];if(!e.has(r))e.set(r,[]);e.get(r).push(a)}return e}replay(e){return this.getByIndex(e)?.command}getSuggestions(e,a=5){let r=e.toLowerCase(),n=this.entries.filter((i)=>i.command.toLowerCase().startsWith(r)).map((i)=>i.command);return[...new Set(n)].slice(0,a)}analyzePatterns(){let e=new Map,a=new Map;for(let n of this.entries){let i=n.timestamp.getHours(),o=n.timestamp.getDay();e.set(i,(e.get(i)||0)+1),a.set(o,(a.get(o)||0)+1)}let r=this.entries.length>0?this.getSuccessful().length/this.entries.length:0;return{timeOfDay:e,dayOfWeek:a,successRate:r}}}function
|
|
2773
|
-
`)}function
|
|
2771
|
+
`))}catch(e){console.error(`Failed to save history: ${e}`)}}searchHistory(e){return this.history.commands.filter((a)=>a.includes(e))}clearHistory(){this.history.commands=[],this.historyIndex=0}}class Hd{variables=new Map;workingDirectory=process.cwd();set(e,a){this.variables.set(e,a)}get(e){return this.variables.get(e)}has(e){return this.variables.has(e)}delete(e){this.variables.delete(e)}getAll(){return Object.fromEntries(this.variables)}clear(){this.variables.clear()}setWorkingDirectory(e){this.workingDirectory=e}getWorkingDirectory(){return this.workingDirectory}}class qd{command={};name(e){return this.command.name=e,this}description(e){return this.command.description=e,this}aliases(...e){return this.command.aliases=e,this}handler(e){return this.command.handler=e,this}autocomplete(e){return this.command.autocomplete=e,this}build(){if(!this.command.name||!this.command.description||!this.command.handler)throw Error("Command must have name, description, and handler");return this.command}}class Wd{entries=[];maxSize;persistFile;trackOutput;constructor(e={}){this.maxSize=e.maxSize||1000,this.persistFile=e.persistFile,this.trackOutput=e.trackOutput||!1}add(e){if(this.entries.push({...e,timestamp:new Date}),this.entries.length>this.maxSize)this.entries=this.entries.slice(-this.maxSize)}getAll(){return[...this.entries]}getRecent(e=10){return this.entries.slice(-e)}search(e){let a=e.toLowerCase();return this.entries.filter((r)=>r.command.toLowerCase().includes(a))}searchByDate(e,a){return this.entries.filter((r)=>r.timestamp>=e&&r.timestamp<=a)}getSuccessful(){return this.entries.filter((e)=>e.success)}getFailed(){return this.entries.filter((e)=>!e.success)}getMostUsed(e=10){let a=new Map;for(let r of this.entries){let n=r.command.split(" ")[0];a.set(n,(a.get(n)||0)+1)}return Array.from(a.entries()).map(([r,n])=>({command:r,count:n})).sort((r,n)=>n.count-r.count).slice(0,e)}getStats(){let e=this.entries.length,a=this.entries.filter((u)=>u.success).length,r=this.entries.filter((u)=>!u.success).length,n=this.entries.filter((u)=>u.duration!==void 0),i=n.length>0?n.reduce((u,d)=>u+(d.duration||0),0)/n.length:0,o=this.getMostUsed(1),c=o.length>0?o[0].command:"N/A";return{total:e,successful:a,failed:r,averageDuration:i,mostUsed:c}}clear(){this.entries=[]}getByIndex(e){if(e<0||e>=this.entries.length)return;return this.entries[e]}removeByIndex(e){if(e>=0&&e<this.entries.length)this.entries.splice(e,1)}async save(){if(!this.persistFile)return;try{let e=await import("node:fs/promises"),a=JSON.stringify(this.entries,null,2);await e.writeFile(this.persistFile,a,"utf-8")}catch(e){throw Error(`Failed to save history: ${e}`)}}async load(){if(!this.persistFile)return;try{let e=await import("node:fs/promises"),a=await e.readFile(this.persistFile,"utf-8"),r=JSON.parse(a);this.entries=r.map((n)=>({...n,timestamp:new Date(n.timestamp)}))}catch{this.entries=[]}}exportJSON(){return JSON.stringify(this.entries,null,2)}exportCSV(){return["Timestamp,Command,Success,Duration",...this.entries.map((e)=>[e.timestamp.toISOString(),`"${e.command.replace(/"/g,'""')}"`,e.success,e.duration||""].join(","))].join(`
|
|
2772
|
+
`)}importJSON(e){let a=JSON.parse(e).map((r)=>({...r,timestamp:new Date(r.timestamp)}));if(this.entries.push(...a),this.entries.length>this.maxSize)this.entries=this.entries.slice(-this.maxSize)}groupByDate(){let e=new Map;for(let a of this.entries){let r=a.timestamp.toISOString().split("T")[0];if(!e.has(r))e.set(r,[]);e.get(r).push(a)}return e}groupByCommand(){let e=new Map;for(let a of this.entries){let r=a.command.split(" ")[0];if(!e.has(r))e.set(r,[]);e.get(r).push(a)}return e}replay(e){return this.getByIndex(e)?.command}getSuggestions(e,a=5){let r=e.toLowerCase(),n=this.entries.filter((i)=>i.command.toLowerCase().startsWith(r)).map((i)=>i.command);return[...new Set(n)].slice(0,a)}analyzePatterns(){let e=new Map,a=new Map;for(let n of this.entries){let i=n.timestamp.getHours(),o=n.timestamp.getDay();e.set(i,(e.get(i)||0)+1),a.set(o,(a.get(o)||0)+1)}let r=this.entries.length>0?this.getSuccessful().length/this.entries.length:0;return{timeOfDay:e,dayOfWeek:a,successRate:r}}}function Hm(e,a={}){let{maxWidth:r=100}=a;if(e.length===0)return"No command history";let n=[];for(let i=0;i<e.length;i++){let o=e[i],c=(i+1).toString().padStart(4),u=o.timestamp.toLocaleString(),d=o.success?"✓":"✗",m=o.command;if(m.length>r-30)m=m.substring(0,r-33)+"...";let p=`${c} ${u} ${d} ${m}`;if(o.duration)p+=` (${o.duration}ms)`;n.push(p)}return n.join(`
|
|
2773
|
+
`)}function qm(e){let a=[];return a.push("Command History Statistics"),a.push("─".repeat(30)),a.push(`Total commands: ${e.total}`),a.push(`Successful: ${e.successful}`),a.push(`Failed: ${e.failed}`),a.push(`Success rate: ${(e.successful/e.total*100).toFixed(1)}%`),a.push(`Average duration: ${e.averageDuration.toFixed(0)}ms`),a.push(`Most used: ${e.mostUsed}`),a.join(`
|
|
2774
2774
|
`)}class Ac{deployments=new Map;async deploy(e,a){let r=this.generateDeploymentId(),n={id:r,regions:a.regions.map((i)=>({region:i.code,stackName:this.getStackName(e,i.code),status:"pending"})),status:"deploying",startTime:new Date};this.deployments.set(r,n);try{let i=a.regions.find((c)=>c.isPrimary)||a.regions[0];await this.deployToRegion(e,i,n);let o=a.regions.filter((c)=>c.code!==i.code);if(await Promise.all(o.map((c)=>this.deployToRegion(e,c,n))),a.globalResources)await this.deployGlobalResources(n,a);if(a.replication)await this.setupReplication(n,a);if(a.failover?.enabled)await this.setupFailover(n,a);return n.status="deployed",n.endTime=new Date,n}catch(i){throw n.status="failed",n.endTime=new Date,i}}async deployToRegion(e,a,r){let n=r.regions.find((i)=>i.region===a.code);if(!n)throw Error(`Region deployment not found: ${a.code}`);n.status="deploying",n.startTime=new Date;try{let i=this.createRegionConfig(e,a);await this.deployStack(n.stackName,i,a.code),n.status="deployed",n.endTime=new Date,n.outputs={stackId:`arn:aws:cloudformation:${a.code}:123456789012:stack/${n.stackName}/guid`,endpoint:`https://${n.stackName}.${a.code}.example.com`}}catch(i){throw n.status="failed",n.endTime=new Date,n.error=i instanceof Error?i.message:String(i),i}}async deployGlobalResources(e,a){let r={};if(a.globalResources?.route53)r.route53=await this.deployRoute53(e,a);if(a.globalResources?.cloudfront)r.cloudfront=await this.deployCloudFront(e,a);if(a.globalResources?.waf)r.waf=await this.deployWAF(e);e.globalResources=r}async deployRoute53(e,a){let r=[],n=[];for(let i of e.regions){if(i.status!=="deployed")continue;let o={id:`health-${i.region}`,endpoint:i.outputs?.endpoint,path:a.failover?.healthCheckPath||"/health",region:i.region};r.push(o);let c={name:"example.com",type:"A",region:i.region,setIdentifier:i.region,healthCheckId:o.id,resourceRecords:[i.outputs?.endpoint]};n.push(c)}return{healthChecks:r,recordSets:n,hostedZoneId:"Z1234567890ABC"}}async deployCloudFront(e,a){return{distributionId:"E1234567890ABC",domainName:"d1234567890abc.cloudfront.net",origins:e.regions.filter((r)=>r.status==="deployed").map((r,n)=>{let i=a.regions[n];return{id:`origin-${r.region}`,domainName:r.outputs?.endpoint,weight:i?.weight||100}}),status:"Deployed"}}async deployWAF(e){return{webAclId:"arn:aws:wafv2:us-east-1:123456789012:global/webacl/test/a1234567-b890-c123-d456-e789012345f6",webAclArn:"arn:aws:wafv2:us-east-1:123456789012:global/webacl/test/a1234567-b890-c123-d456-e789012345f6"}}async setupReplication(e,a){if(a.replication?.s3)await this.setupS3Replication(e);if(a.replication?.dynamodb)await this.setupDynamoDBReplication(e);if(a.replication?.secrets)await this.setupSecretsReplication(e)}async setupS3Replication(e){let a=e.regions.filter((r)=>r.status==="deployed");for(let r=0;r<a.length-1;r++){let n=a[r],i=a[r+1];console.log(`Setting up S3 replication: ${n.region} -> ${i.region}`)}}async setupDynamoDBReplication(e){let a=e.regions.filter((r)=>r.status==="deployed").map((r)=>r.region);console.log(`Setting up DynamoDB global table in regions: ${a.join(", ")}`)}async setupSecretsReplication(e){let a=e.regions.filter((r)=>r.status==="deployed").map((r)=>r.region);console.log(`Setting up Secrets Manager replication in regions: ${a.join(", ")}`)}async setupFailover(e,a){let r=e.regions.find((i,o)=>a.regions[o]?.isPrimary)||e.regions[0],n=e.regions.filter((i)=>i.region!==r.region);console.log(`Setting up failover: primary=${r.region}, secondary=${n.map((i)=>i.region).join(", ")}`)}async destroy(e){let a=this.deployments.get(e);if(!a)throw Error(`Deployment not found: ${e}`);a.status="rolling-back";try{if(a.globalResources)await this.destroyGlobalResources(a.globalResources);await Promise.all(a.regions.map((r)=>this.destroyRegionStack(r))),this.deployments.delete(e)}catch(r){throw a.status="failed",r}}async destroyGlobalResources(e){if(e.waf)console.log("Destroying WAF resources");if(e.cloudfront)console.log("Destroying CloudFront distribution");if(e.route53)console.log("Destroying Route53 resources")}async destroyRegionStack(e){if(e.status!=="deployed")return;e.status="rolling-back";try{console.log(`Destroying stack ${e.stackName} in ${e.region}`),e.status="pending"}catch(a){throw e.status="failed",e.error=a instanceof Error?a.message:String(a),a}}getDeployment(e){return this.deployments.get(e)}listDeployments(){return Array.from(this.deployments.values())}getStackName(e,a){return`${e.project.slug}-${a}`}createRegionConfig(e,a){return{...e,infrastructure:{...e.infrastructure}}}async deployStack(e,a,r){console.log(`Deploying stack ${e} to ${r}`)}generateDeploymentId(){return`deploy-${Date.now()}-${Math.random().toString(36).substring(7)}`}}var Wm=new Ac;class Ic{references=[];exports=new Map;addExport(e){let a=`${e.region}:${e.exportName}`;if(!this.exports.has(e.region))this.exports.set(e.region,[]);this.exports.get(e.region).push(e)}getExport(e,a){let r=this.exports.get(e);if(!r)return;return r.find((n)=>n.exportName===a)?.value}createReference(e,a,r,n){let i=`/cross-region/${e}/${r}/${n}`;return this.references.push({sourceRegion:e,targetRegion:a,resourceType:r,resourceId:n,value:i}),i}async resolveReference(e,a){let r=this.references.find((n)=>n.targetRegion===e&&n.value===a);if(!r)throw Error(`Reference not found: ${a}`);return`arn:aws:resource:${r.sourceRegion}:123456789012:${r.resourceType}/${r.resourceId}`}getReferencesForRegion(e){return this.references.filter((a)=>a.sourceRegion===e||a.targetRegion===e)}clear(){this.references=[],this.exports.clear()}}class Rc{resources=new Map;register(e){this.resources.set(e.id,e)}get(e){return this.resources.get(e)}getByType(e){return Array.from(this.resources.values()).filter((a)=>a.type===e)}getCloudFrontDistributions(){return this.getByType("cloudfront")}getRoute53HostedZones(){return this.getByType("route53")}getWAFWebACLs(){return this.getByType("waf")}remove(e){this.resources.delete(e)}clear(){this.resources.clear()}}class Pc{pairs=[];addPair(e){this.pairs.push(e)}getPairedRegion(e){let a=this.pairs.find((r)=>r.primary===e||r.secondary===e);if(!a)return;return a.primary===e?a.secondary:a.primary}getAllPairs(){return[...this.pairs]}getReplicatedPairs(){return this.pairs.filter((e)=>e.replicationConfig)}getFailoverPairs(){return this.pairs.filter((e)=>e.failoverConfig?.automatic)}arePaired(e,a){return this.pairs.some((r)=>r.primary===e&&r.secondary===a||r.primary===a&&r.secondary===e)}clear(){this.pairs=[]}}class Nc{dependencies=[];addDependency(e){this.dependencies.push(e)}getDependencies(e,a){return this.dependencies.filter((r)=>r.dependentStack===e&&r.dependentRegion===a)}getDependents(e,a){return this.dependencies.filter((r)=>r.dependsOnStack===e&&r.dependsOnRegion===a)}hasDependencies(e,a){return this.getDependencies(e,a).length>0}getDeploymentOrder(e){let a=new Set,r=[],n=(i)=>{let o=`${i.name}:${i.region}`;if(a.has(o))return;a.add(o);let c=this.getDependencies(i.name,i.region);for(let u of c)n({name:u.dependsOnStack,region:u.dependsOnRegion});r.push(i)};for(let i of e)n(i);return r}detectCircularDependencies(){let e=new Set,a=new Set,r=(n,i)=>{let o=`${n}:${i}`;if(a.has(o))return!0;if(e.has(o))return!1;e.add(o),a.add(o);let c=this.getDependencies(n,i);for(let u of c)if(r(u.dependsOnStack,u.dependsOnRegion))return!0;return a.delete(o),!1};for(let n of this.dependencies)if(r(n.dependentStack,n.dependentRegion))return!0;return!1}clear(){this.dependencies=[]}}var Gm=new Ic,Km=new Rc,Jm=new Pc,Xm=new Nc,et=[{code:"us-east-1",name:"US East (N. Virginia)",location:"Virginia, USA",launchYear:2006,availabilityZones:6,localZones:16,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"standard",multiplier:1},compliance:["PCI-DSS","HIPAA","SOC","ISO","FedRAMP"]},{code:"us-east-2",name:"US East (Ohio)",location:"Ohio, USA",launchYear:2016,availabilityZones:3,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"standard",multiplier:1},compliance:["PCI-DSS","HIPAA","SOC","ISO"]},{code:"us-west-1",name:"US West (N. California)",location:"California, USA",launchYear:2009,availabilityZones:3,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"premium",multiplier:1.1},compliance:["PCI-DSS","HIPAA","SOC","ISO"]},{code:"us-west-2",name:"US West (Oregon)",location:"Oregon, USA",launchYear:2011,availabilityZones:4,localZones:2,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"standard",multiplier:1},compliance:["PCI-DSS","HIPAA","SOC","ISO"]},{code:"eu-west-1",name:"Europe (Ireland)",location:"Dublin, Ireland",launchYear:2007,availabilityZones:3,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"standard",multiplier:1.05},compliance:["PCI-DSS","GDPR","SOC","ISO"]},{code:"eu-central-1",name:"Europe (Frankfurt)",location:"Frankfurt, Germany",launchYear:2014,availabilityZones:3,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"premium",multiplier:1.1},compliance:["PCI-DSS","GDPR","SOC","ISO"]},{code:"ap-southeast-1",name:"Asia Pacific (Singapore)",location:"Singapore",launchYear:2010,availabilityZones:3,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"premium",multiplier:1.12},compliance:["PCI-DSS","SOC","ISO","MTCS"]},{code:"ap-northeast-1",name:"Asia Pacific (Tokyo)",location:"Tokyo, Japan",launchYear:2011,availabilityZones:4,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"premium",multiplier:1.15},compliance:["PCI-DSS","SOC","ISO"]}];function yi(e){return et.find((a)=>a.code===e)}function Qm(){return et}function Ym(e){let a=e.toLowerCase();return et.filter((r)=>r.location.toLowerCase().includes(a))}function Zm(e){return et.filter((a)=>a.compliance.includes(e))}function eg(e){return et.filter((a)=>a.pricing.tier===e)}function tg(e){return et.some((a)=>a.code===e)}function rg(e){if(e.continent==="North America")return yi("us-east-1");if(e.continent==="Europe")return yi("eu-west-1");if(e.continent==="Asia")return yi("ap-southeast-1");return yi("us-east-1")}function ng(e){let a=[...et];if(e.compliance)a=a.filter((r)=>e.compliance.every((n)=>r.compliance.includes(n)));if(e.requiredServices)a=a.filter((r)=>e.requiredServices.every((n)=>r.services[n]));if(e.pricingSensitive)a.sort((r,n)=>r.pricing.multiplier-n.pricing.multiplier);return a.slice(0,5)}function ig(e){let a=yi(e);if(!a)throw Error(`Invalid region: ${e}`);let r=[];for(let n of et){if(n.code===e)continue;let i=ri(a,n),o=ni(a,n);r.push({primary:a,secondary:n,distance:i,sameContinent:o})}return r.sort((n,i)=>{if(n.sameContinent!==i.sameContinent)return n.sameContinent?1:-1;return n.distance-i.distance}),r.slice(0,3)}function ri(e,a){let r={"North America":0,"South America":1,Europe:2,Asia:3,Africa:4,Oceania:5},n=ze(e.location),i=ze(a.location);return Math.abs((r[n]||0)-(r[i]||0))}function ni(e,a){return ze(e.location)===ze(a.location)}function ze(e){if(e.includes("USA")||e.includes("Canada"))return"North America";if(e.includes("Europe")||e.includes("Ireland")||e.includes("Germany"))return"Europe";if(e.includes("Asia")||e.includes("Singapore")||e.includes("Japan"))return"Asia";if(e.includes("Brazil"))return"South America";if(e.includes("Australia"))return"Oceania";return"Unknown"}function Gd(e){return`${e.name} (${e.code})`}function og(e){return e.map((a)=>Gd(a)).join(`
|
|
2775
2775
|
`)}function sg(){let e={total:et.length,byContinent:{},byPricingTier:{}};for(let a of et){let r=ze(a.location);e.byContinent[r]=(e.byContinent[r]||0)+1,e.byPricingTier[a.pricing.tier]=(e.byPricingTier[a.pricing.tier]||0)+1}return e}class Dc{accounts=new Map;crossAccountRoles=[];accountMappings=[];registerAccount(e){this.accounts.set(e.id,e)}getAccount(e){return this.accounts.get(e)}getAccountByAlias(e){return Array.from(this.accounts.values()).find((a)=>a.alias===e)}listAccounts(){return Array.from(this.accounts.values())}getAccountsByRole(e){return Array.from(this.accounts.values()).filter((a)=>a.role===e)}createCrossAccountRole(e,a,r,n,i){let o={roleArn:`arn:aws:iam::${a}:role/${r}`,roleName:r,sourceAccountId:e,targetAccountId:a,permissions:n,externalId:i?.externalId,sessionDuration:i?.sessionDuration||3600};return this.crossAccountRoles.push(o),o}getAssumeRolePolicyDocument(e,a){let r={Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:`arn:aws:iam::${e}:root`},Action:"sts:AssumeRole"}]};if(a)r.Statement[0].Condition={StringEquals:{"sts:ExternalId":a}};return r}generateCrossAccountPolicy(e){return{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:e,Resource:"*"}]}}mapEnvironmentToAccount(e,a,r){this.accountMappings.push({environment:e,accountId:a,region:r})}getAccountForEnvironment(e){return this.accountMappings.find((a)=>a.environment===e)}async assumeRole(e,a,r){return console.log(`Assuming role: ${e} with session: ${a}`),{accessKeyId:"AKIAIOSFODNN7EXAMPLE",secretAccessKey:"wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",sessionToken:"token",expiration:new Date(Date.now()+3600000)}}async getCredentialsForAccount(e){let a=this.accounts.get(e);if(!a)throw Error(`Account not found: ${e}`);if(a.assumeRoleArn){let r=await this.assumeRole(a.assumeRoleArn,`ts-cloud-${Date.now()}`);return{accessKeyId:r.accessKeyId,secretAccessKey:r.secretAccessKey,sessionToken:r.sessionToken}}throw Error("No credentials available for account")}listCrossAccountRoles(){return[...this.crossAccountRoles]}getCrossAccountRolesForAccount(e){return this.crossAccountRoles.filter((a)=>a.sourceAccountId===e||a.targetAccountId===e)}async validateAccountAccess(e){try{let a=await this.getCredentialsForAccount(e);return console.log(`Validating access to account: ${e}`),!0}catch{return!1}}async getConsolidatedBilling(){let e={};for(let a of this.accounts.values())e[a.id]=Math.random()*1000;return{totalCost:Object.values(e).reduce((a,r)=>a+r,0),byAccount:e}}clear(){this.accounts.clear(),this.crossAccountRoles=[],this.accountMappings=[]}}class kc{organizationId;organizationalUnits=new Map;getOrganizationId(){return this.organizationId}setOrganizationId(e){this.organizationId=e}createOrganizationalUnit(e,a){let r={id:`ou-${Date.now()}`,name:e,parentId:a,accounts:[]};return this.organizationalUnits.set(r.id,r),r}getOrganizationalUnit(e){return this.organizationalUnits.get(e)}listOrganizationalUnits(){return Array.from(this.organizationalUnits.values())}addAccountToOU(e,a){let r=this.organizationalUnits.get(e);if(!r)throw Error(`Organizational unit not found: ${e}`);if(!r.accounts.includes(a))r.accounts.push(a)}removeAccountFromOU(e,a){let r=this.organizationalUnits.get(e);if(!r)throw Error(`Organizational unit not found: ${e}`);r.accounts=r.accounts.filter((n)=>n!==a)}getAccountsInOU(e){let a=this.organizationalUnits.get(e);if(!a)return[];return[...a.accounts]}applyServiceControlPolicy(e,a){return{id:`scp-${Date.now()}`,name:"Custom SCP",targetId:e,policyDocument:a}}clear(){this.organizationId=void 0,this.organizationalUnits.clear()}}var ag=new Dc,cg=new kc,Kd={basic:{name:"Basic (3 Accounts)",description:"Simple structure for small teams",accounts:[{alias:"management",email:"aws+management@example.com",role:"management",ou:"root",description:"Management account for AWS Organizations"},{alias:"production",email:"aws+production@example.com",role:"production",ou:"workloads",description:"Production workloads"},{alias:"development",email:"aws+development@example.com",role:"development",ou:"workloads",description:"Development and testing"}],organizationalUnits:[{name:"root"},{name:"workloads",parent:"root"}]},standard:{name:"Standard (5 Accounts)",description:"Recommended for most organizations",accounts:[{alias:"management",email:"aws+management@example.com",role:"management",ou:"root",description:"Management account"},{alias:"security",email:"aws+security@example.com",role:"security",ou:"security",description:"Security tooling and audit logs"},{alias:"shared-services",email:"aws+shared@example.com",role:"shared-services",ou:"infrastructure",description:"Shared services (CI/CD, monitoring)"},{alias:"production",email:"aws+production@example.com",role:"production",ou:"workloads",description:"Production environment"},{alias:"staging",email:"aws+staging@example.com",role:"staging",ou:"workloads",description:"Staging environment"},{alias:"development",email:"aws+development@example.com",role:"development",ou:"workloads",description:"Development environment"}],organizationalUnits:[{name:"root"},{name:"security",parent:"root"},{name:"infrastructure",parent:"root"},{name:"workloads",parent:"root"}]},enterprise:{name:"Enterprise (7+ Accounts)",description:"For large organizations with strict compliance requirements",accounts:[{alias:"management",email:"aws+management@example.com",role:"management",ou:"root",description:"Management account"},{alias:"audit",email:"aws+audit@example.com",role:"security",ou:"security",description:"Audit and compliance"},{alias:"log-archive",email:"aws+logs@example.com",role:"security",ou:"security",description:"Centralized log storage"},{alias:"shared-services",email:"aws+shared@example.com",role:"shared-services",ou:"infrastructure",description:"Shared infrastructure"},{alias:"network",email:"aws+network@example.com",role:"shared-services",ou:"infrastructure",description:"Network infrastructure (Transit Gateway)"},{alias:"production",email:"aws+production@example.com",role:"production",ou:"production-ou",description:"Production workloads"},{alias:"staging",email:"aws+staging@example.com",role:"staging",ou:"non-production-ou",description:"Staging environment"},{alias:"development",email:"aws+development@example.com",role:"development",ou:"non-production-ou",description:"Development environment"}],organizationalUnits:[{name:"root"},{name:"security",parent:"root",policies:["deny-root-access"]},{name:"infrastructure",parent:"root"},{name:"production-ou",parent:"root",policies:["require-mfa"]},{name:"non-production-ou",parent:"root"}]}},lg={denyRootAccess:{name:"Deny Root User Access",description:"Prevent root user from performing any actions",policyDocument:{Version:"2012-10-17",Statement:[{Sid:"DenyRootUser",Effect:"Deny",Action:"*",Resource:"*",Condition:{StringLike:{"aws:PrincipalArn":"arn:aws:iam::*:root"}}}]}},requireMFA:{name:"Require MFA for All Actions",description:"Require MFA for console and API access",policyDocument:{Version:"2012-10-17",Statement:[{Sid:"RequireMFA",Effect:"Deny",Action:"*",Resource:"*",Condition:{BoolIfExists:{"aws:MultiFactorAuthPresent":"false"}}}]}},denyRegions:{name:"Deny Access to Non-Approved Regions",description:"Restrict operations to specific regions",policyDocument:{Version:"2012-10-17",Statement:[{Sid:"DenyNonApprovedRegions",Effect:"Deny",NotAction:["iam:*","organizations:*","route53:*","cloudfront:*","support:*","s3:*"],Resource:"*",Condition:{StringNotEquals:{"aws:RequestedRegion":["us-east-1","us-west-2"]}}}]}},preventLeaving:{name:"Prevent Leaving Organization",description:"Prevent accounts from leaving the organization",policyDocument:{Version:"2012-10-17",Statement:[{Sid:"PreventLeaving",Effect:"Deny",Action:"organizations:LeaveOrganization",Resource:"*"}]}},denyS3Unencrypted:{name:"Deny Unencrypted S3 Uploads",description:"Require encryption for all S3 uploads",policyDocument:{Version:"2012-10-17",Statement:[{Sid:"DenyUnencryptedS3Uploads",Effect:"Deny",Action:"s3:PutObject",Resource:"*",Condition:{StringNotEquals:{"s3:x-amz-server-side-encryption":["AES256","aws:kms"]}}}]}}},dg={deploymentRole:{name:"CrossAccountDeploymentRole",description:"Role for deploying infrastructure from CI/CD",permissions:["cloudformation:*","s3:*","ec2:*","ecs:*","lambda:*","iam:GetRole","iam:PassRole","logs:*","events:*"]},readOnlyRole:{name:"CrossAccountReadOnlyRole",description:"Read-only access for monitoring and auditing",permissions:["cloudformation:Describe*","cloudformation:List*","ec2:Describe*","ecs:Describe*","lambda:Get*","lambda:List*","s3:Get*","s3:List*","logs:Get*","logs:Describe*"]},securityAuditRole:{name:"CrossAccountSecurityAuditRole",description:"Security audit and compliance checks",permissions:["iam:Get*","iam:List*","iam:Generate*","access-analyzer:*","guardduty:Get*","guardduty:List*","securityhub:Get*","securityhub:List*","config:Describe*","config:Get*","config:List*"]},breakGlassRole:{name:"CrossAccountBreakGlassRole",description:"Emergency access role (use with caution)",permissions:["*"]}};function ug(e){return Kd[e]}function pg(e,a){return{Type:"AWS::IAM::Role",Properties:{RoleName:e.roleName,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:`arn:aws:iam::${e.sourceAccountId}:root`},Action:"sts:AssumeRole",...e.externalId&&{Condition:{StringEquals:{"sts:ExternalId":e.externalId}}}}]},Policies:[{PolicyName:`${e.roleName}Policy`,PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:e.permissions,Resource:"*"}]}}],...a&&{ManagedPolicyArns:a},MaxSessionDuration:e.sessionDuration||3600,Tags:[{Key:"ManagedBy",Value:"TS-Cloud"},{Key:"SourceAccount",Value:e.sourceAccountId}]}}}function mg(e){let a=[],r=[],n=e.accounts.filter((d)=>d.role==="management");if(n.length===0)a.push("No management account defined");if(n.length>1)a.push("Multiple management accounts defined");let i=e.accounts.map((d)=>d.email),o=i.filter((d,m)=>i.indexOf(d)!==m);if(o.length>0)a.push(`Duplicate email addresses: ${o.join(", ")}`);let c=e.accounts.map((d)=>d.alias),u=c.filter((d,m)=>c.indexOf(d)!==m);if(u.length>0)a.push(`Duplicate aliases: ${u.join(", ")}`);if(!e.accounts.some((d)=>d.role==="security"))r.push("No dedicated security account - consider adding one for audit logs");if(e.accounts.length<3)r.push("Less than 3 accounts - consider separating environments");if(!e.accounts.some((d)=>d.role==="production"))r.push("No production account defined");return{valid:a.length===0,errors:a,warnings:r}}function gg(e){let a=[];if(a.push(`${e.name}`),a.push("─".repeat(e.name.length)),a.push(e.description),a.push(""),e.organizationalUnits){a.push("Organizational Units:");for(let r of e.organizationalUnits){let n=r.parent?" └─ ":" ";a.push(`${n}${r.name}`)}a.push("")}a.push("Accounts:");for(let r of e.accounts)a.push(` ${r.alias.padEnd(20)} ${r.role.padEnd(15)} ${r.email}`),a.push(` ${"".padEnd(20)} ${r.description}`),a.push("");return a.join(`
|
|
2776
2776
|
`)}function fg(e={}){let{workflowName:a="Deploy",trigger:r="push",branches:n=["main"],environments:i=["production"],awsRegion:o="us-east-1",awsRole:c,bunVersion:u="latest",deployCommand:d="bun run cloud deploy",testCommand:m="bun test",buildCommand:p="bun run build"}=e,g=!!c;return`name: ${a}
|
|
@@ -3607,7 +3607,7 @@ workflows:
|
|
|
3607
3607
|
requires:
|
|
3608
3608
|
- test
|
|
3609
3609
|
${i}
|
|
3610
|
-
`}class xc{backupPlans=new Map;backupVaults=new Map;restoreJobs=new Map;continuousBackups=new Map;planCounter=0;restoreCounter=0;continuousBackupCounter=0;createVault(e){this.backupVaults.set(e.name,e)}getVault(e){return this.backupVaults.get(e)}createBackupPlan(e){let a=`backup-plan-${Date.now()}-${this.planCounter++}`,r={id:a,...e};return this.backupPlans.set(a,r),r}getBackupPlan(e){return this.backupPlans.get(e)}listBackupPlans(){return Array.from(this.backupPlans.values())}createRDSBackupPlan(e){let{dbInstanceArn:a,schedule:r="0 2 * * *",retentionDays:n=7,vaultName:i="default-vault"}=e;return this.createBackupPlan({name:"RDS Daily Backup",schedule:r,retentionDays:n,vaultName:i,resources:[{resourceArn:a,resourceType:"rds",region:"us-east-1"}],lifecycle:{moveTocoldStorageAfterDays:30,deleteAfterDays:n}})}createDynamoDBBackupPlan(e){let{tableArn:a,schedule:r="0 3 * * *",retentionDays:n=35,crossRegionCopy:i}=e;return this.createBackupPlan({name:"DynamoDB Daily Backup",schedule:r,retentionDays:n,vaultName:"dynamodb-vault",resources:[{resourceArn:a,resourceType:"dynamodb",region:"us-east-1"}],lifecycle:{deleteAfterDays:n},tags:i?{CrossRegionCopy:i.join(",")}:void 0})}createEFSBackupPlan(e){let{fileSystemArn:a,schedule:r="0 1 * * *",retentionDays:n=30}=e;return this.createBackupPlan({name:"EFS Daily Backup",schedule:r,retentionDays:n,vaultName:"efs-vault",resources:[{resourceArn:a,resourceType:"efs",region:"us-east-1"}],lifecycle:{deleteAfterDays:n}})}enableContinuousBackup(e,a=35){let r=`continuous-backup-${Date.now()}-${this.continuousBackupCounter++}`,n={id:r,resourceId:e,enabled:!0,retentionDays:a};return this.continuousBackups.set(r,n),n}getContinuousBackup(e){return this.continuousBackups.get(e)}enablePointInTimeRecovery(e,a){return{enabled:!0,earliestRestorableTime:new Date(Date.now()-604800000),latestRestorableTime:new Date}}async restoreFromBackup(e){let{backupId:a,resourceType:r,targetRegion:n}=e,i={id:`restore-${Date.now()}-${this.restoreCounter++}`,backupId:a,resourceType:r,status:"pending",startTime:new Date,targetRegion:n};return this.restoreJobs.set(i.id,i),setTimeout(()=>{i.status="running"},100),setTimeout(()=>{i.status="completed",i.endTime=new Date},1000),i}async restoreToPointInTime(e){let{sourceResourceArn:a,targetResourceName:r,restoreTime:n,resourceType:i}=e,o={id:`pitr-${Date.now()}-${this.restoreCounter++}`,backupId:`pitr-${n.getTime()}`,resourceType:i,status:"pending",startTime:new Date};return this.restoreJobs.set(o.id,o),console.log(`Restoring ${i} from ${a} to ${r} at ${n.toISOString()}`),setTimeout(()=>{o.status="completed",o.endTime=new Date},2000),o}getRestoreJob(e){return this.restoreJobs.get(e)}listRestoreJobs(){return Array.from(this.restoreJobs.values())}setupCrossRegionReplication(e){let{sourceVault:a,sourceRegion:r,targetRegions:n}=e;console.log("Setting up cross-region replication:"),console.log(` Source: ${a} in ${r}`),console.log(` Targets: ${n.join(", ")}`)}generateBackupVaultCF(e){return{Type:"AWS::Backup::BackupVault",Properties:{BackupVaultName:e.name,...e.encryptionKeyArn&&{EncryptionKeyArn:e.encryptionKeyArn},...e.accessPolicy&&{AccessPolicy:e.accessPolicy}}}}generateBackupPlanCF(e){return{Type:"AWS::Backup::BackupPlan",Properties:{BackupPlan:{BackupPlanName:e.name,BackupPlanRule:[{RuleName:"DailyBackup",TargetBackupVault:e.vaultName,ScheduleExpression:`cron(${e.schedule})`,StartWindowMinutes:60,CompletionWindowMinutes:120,Lifecycle:e.lifecycle?{...e.lifecycle.moveTocoldStorageAfterDays&&{MoveToColdStorageAfterDays:e.lifecycle.moveTocoldStorageAfterDays},...e.lifecycle.deleteAfterDays&&{DeleteAfterDays:e.lifecycle.deleteAfterDays}}:void 0}]},...e.tags&&{BackupPlanTags:e.tags}}}}generateBackupSelectionCF(e){return{Type:"AWS::Backup::BackupSelection",Properties:{BackupPlanId:{Ref:`BackupPlan${e.id}`},BackupSelection:{SelectionName:`${e.name}Selection`,IamRoleArn:"arn:aws:iam::123456789012:role/service-role/AWSBackupDefaultServiceRole",Resources:e.resources.map((a)=>a.resourceArn)}}}}clear(){this.backupPlans.clear(),this.backupVaults.clear(),this.restoreJobs.clear(),this.continuousBackups.clear(),this.planCounter=0,this.restoreCounter=0,this.continuousBackupCounter=0}}var Dg=new xc;class _c{drPlans=new Map;failoverTests=new Map;planCounter=0;testCounter=0;createDRPlan(e){let a=`dr-plan-${Date.now()}-${this.planCounter++}`,r={id:a,...e};return this.drPlans.set(a,r),r}createRDSDRPlan(e){let{primaryDbArn:a,secondaryDbArn:r,primaryRegion:n,secondaryRegion:i,rto:o=60,rpo:c=5}=e;return this.createDRPlan({name:"RDS Multi-Region DR",primaryRegion:n,secondaryRegion:i,rto:o,rpo:c,resources:[{resourceId:"primary-db",resourceType:"rds",primaryArn:a,secondaryArn:r,replicationEnabled:!0}],runbook:this.generateRDSRunbook(n,i),testSchedule:"0 0 1 * *"})}createDynamoDBDRPlan(e){let{tableArn:a,regions:r,rto:n=15,rpo:i=1}=e;return this.createDRPlan({name:"DynamoDB Global Tables DR",primaryRegion:r[0],secondaryRegion:r[1],rto:n,rpo:i,resources:[{resourceId:"dynamodb-table",resourceType:"dynamodb",primaryArn:a,replicationEnabled:!0}],runbook:this.generateDynamoDBRunbook(r)})}generateRDSRunbook(e,a){return{estimatedDuration:60,requiredApprovals:["cto","engineering-lead"],steps:[{order:1,name:"Verify Primary Database Failure",description:"Confirm that the primary database is truly unavailable and not experiencing temporary issues",action:"aws rds describe-db-instances --region "+e,automatable:!0,estimatedDuration:2,rollbackable:!1},{order:2,name:"Check Replication Lag",description:"Verify that the read replica is up to date",action:"Check ReplicaLag metric in CloudWatch",automatable:!0,estimatedDuration:1,rollbackable:!1},{order:3,name:"Promote Read Replica",description:"Promote the read replica in the secondary region to be the new primary",action:"aws rds promote-read-replica --db-instance-identifier replica --region "+a,automatable:!0,estimatedDuration:10,rollbackable:!1},{order:4,name:"Update DNS Records",description:"Update Route53 records to point to the new primary database",action:"Update Route53 failover record set",automatable:!0,estimatedDuration:5,rollbackable:!0},{order:5,name:"Update Application Configuration",description:"Update application connection strings if needed",action:"Deploy configuration update to ECS/Lambda",automatable:!0,estimatedDuration:10,rollbackable:!0},{order:6,name:"Verify Application Connectivity",description:"Test that applications can connect to the new primary",action:"Run smoke tests",automatable:!0,estimatedDuration:5,rollbackable:!1},{order:7,name:"Monitor for Issues",description:"Monitor CloudWatch metrics and application logs",action:"Monitor for 30 minutes",automatable:!1,estimatedDuration:30,rollbackable:!1}]}}generateDynamoDBRunbook(e){return{estimatedDuration:15,steps:[{order:1,name:"Verify Primary Region Failure",description:"Confirm that the primary region is experiencing an outage",action:"Check AWS Health Dashboard",automatable:!0,estimatedDuration:2,rollbackable:!1},{order:2,name:"Update Route53 Failover",description:"Update Route53 to direct traffic to secondary region",action:"Update Route53 health check and failover records",automatable:!0,estimatedDuration:5,rollbackable:!0},{order:3,name:"Update Application Endpoints",description:"Update Lambda/ECS to use secondary region DynamoDB endpoint",action:"Deploy configuration update",automatable:!0,estimatedDuration:5,rollbackable:!0},{order:4,name:"Verify Data Consistency",description:"Verify that data is consistent in secondary region",action:"Run data validation queries",automatable:!0,estimatedDuration:3,rollbackable:!1}]}}async executeFailover(e,a=!1){let r=this.drPlans.get(e);if(!r)throw Error(`DR plan not found: ${e}`);let n=Date.now(),i=0;console.log(`${a?"[DRY RUN] ":""}Executing failover for plan: ${r.name}`),console.log(`Primary: ${r.primaryRegion} -> Secondary: ${r.secondaryRegion}`),console.log(`RTO: ${r.rto} minutes, RPO: ${r.rpo} minutes`),console.log("");for(let o of r.runbook.steps){if(console.log(`Step ${o.order}: ${o.name}`),console.log(` ${o.description}`),console.log(` Action: ${o.action}`),console.log(` Estimated: ${o.estimatedDuration} minutes`),a)console.log(" [SKIPPED - DRY RUN]");else if(o.automatable)console.log(" [AUTOMATED]");else console.log(" [MANUAL - WAITING]");i++,console.log("")}return{success:!0,duration:(Date.now()-n)/1000/60,completedSteps:i}}scheduleFailoverTest(e,a){let r={id:`failover-test-${Date.now()}-${this.testCounter++}`,planId:e,status:"scheduled",startTime:a};return this.failoverTests.set(r.id,r),r}async runFailoverTest(e){let a=this.drPlans.get(e);if(!a)throw Error(`DR plan not found: ${e}`);let r={id:`failover-test-${Date.now()}-${this.testCounter++}`,planId:e,status:"running",startTime:new Date,results:[]};this.failoverTests.set(r.id,r),console.log(`Running failover test for plan: ${a.name}`),console.log("This is a non-destructive test using test resources"),console.log("");for(let n of a.runbook.steps){let i=Date.now();console.log(`Testing step ${n.order}: ${n.name}`);let o={step:n.name,status:"success",duration:(Date.now()-i)/1000,message:`Successfully validated step ${n.order}`};r.results.push(o)}return r.status="completed",r.endTime=new Date,r}getDRPlan(e){return this.drPlans.get(e)}listDRPlans(){return Array.from(this.drPlans.values())}getFailoverTest(e){return this.failoverTests.get(e)}listFailoverTests(){return Array.from(this.failoverTests.values())}validateDRPlan(e){let a=[],r=[];if(e.rto<e.rpo)r.push("RTO cannot be less than RPO");if(e.rto>240)a.push("RTO exceeds 4 hours - consider improving recovery time");if(e.rpo>60)a.push("RPO exceeds 1 hour - consider more frequent backups");if(e.resources.length===0)r.push("No resources defined in DR plan");for(let o of e.resources){if(!o.replicationEnabled)a.push(`Resource ${o.resourceId} does not have replication enabled`);if(!o.secondaryArn&&o.resourceType!=="dynamodb")a.push(`Resource ${o.resourceId} does not have secondary resource defined`)}if(e.runbook.steps.length===0)r.push("No recovery steps defined in runbook");let n=e.runbook.steps.reduce((o,c)=>o+c.estimatedDuration,0);if(n>e.rto)a.push(`Estimated recovery duration (${n}m) exceeds RTO (${e.rto}m)`);let i=e.runbook.steps.filter((o)=>!o.automatable);if(i.length>0)a.push(`${i.length} manual steps in runbook - consider automation`);return{valid:r.length===0,warnings:a,errors:r}}clear(){this.drPlans.clear(),this.failoverTests.clear(),this.planCounter=0,this.testCounter=0}}var kg=new _c;class $c{configRules=new Map;configRecorders=new Map;deliveryChannels=new Map;ruleCounter=0;createConfigRecorder(e){return this.configRecorders.set(e.name,e),e}createDeliveryChannel(e){return this.deliveryChannels.set(e.name,e),e}createConfigRule(e){let a=`config-rule-${Date.now()}-${this.ruleCounter++}`,r={id:a,...e};return this.configRules.set(a,r),r}createS3EncryptionRule(){return this.createConfigRule({name:"s3-bucket-server-side-encryption-enabled",description:"Checks that S3 buckets have server-side encryption enabled",source:"AWS_MANAGED",identifier:"S3_BUCKET_SERVER_SIDE_ENCRYPTION_ENABLED",scope:{complianceResourceTypes:["AWS::S3::Bucket"]}})}createS3PublicAccessBlockRule(){return this.createConfigRule({name:"s3-bucket-public-read-prohibited",description:"Checks that S3 buckets do not allow public read access",source:"AWS_MANAGED",identifier:"S3_BUCKET_PUBLIC_READ_PROHIBITED",scope:{complianceResourceTypes:["AWS::S3::Bucket"]}})}createS3VersioningRule(){return this.createConfigRule({name:"s3-bucket-versioning-enabled",description:"Checks whether versioning is enabled for S3 buckets",source:"AWS_MANAGED",identifier:"S3_BUCKET_VERSIONING_ENABLED",scope:{complianceResourceTypes:["AWS::S3::Bucket"]}})}createRdsEncryptionRule(){return this.createConfigRule({name:"rds-storage-encrypted",description:"Checks whether storage encryption is enabled for RDS DB instances",source:"AWS_MANAGED",identifier:"RDS_STORAGE_ENCRYPTED",scope:{complianceResourceTypes:["AWS::RDS::DBInstance"]}})}createRdsSnapshotEncryptionRule(){return this.createConfigRule({name:"rds-snapshots-public-prohibited",description:"Checks if RDS snapshots are public",source:"AWS_MANAGED",identifier:"RDS_SNAPSHOTS_PUBLIC_PROHIBITED",scope:{complianceResourceTypes:["AWS::RDS::DBSnapshot","AWS::RDS::DBClusterSnapshot"]}})}createRdsBackupRule(e=7){return this.createConfigRule({name:"db-backup-enabled",description:"Checks whether RDS DB instances have backups enabled",source:"AWS_MANAGED",identifier:"DB_BACKUP_ENABLED",inputParameters:{backupRetentionPeriod:e},scope:{complianceResourceTypes:["AWS::RDS::DBInstance"]}})}createEc2InstanceProfileRule(){return this.createConfigRule({name:"ec2-instance-managed-by-systems-manager",description:"Checks if EC2 instances are managed by Systems Manager",source:"AWS_MANAGED",identifier:"EC2_INSTANCE_MANAGED_BY_SSM",scope:{complianceResourceTypes:["AWS::EC2::Instance"]}})}createEbsEncryptionRule(){return this.createConfigRule({name:"encrypted-volumes",description:"Checks whether EBS volumes are encrypted",source:"AWS_MANAGED",identifier:"ENCRYPTED_VOLUMES",scope:{complianceResourceTypes:["AWS::EC2::Volume"]}})}createIamPasswordPolicyRule(){return this.createConfigRule({name:"iam-password-policy",description:"Checks whether the IAM password policy meets specified requirements",source:"AWS_MANAGED",identifier:"IAM_PASSWORD_POLICY",inputParameters:{RequireUppercaseCharacters:!0,RequireLowercaseCharacters:!0,RequireSymbols:!0,RequireNumbers:!0,MinimumPasswordLength:14,PasswordReusePrevention:24,MaxPasswordAge:90}})}createIamMfaRule(){return this.createConfigRule({name:"iam-user-mfa-enabled",description:"Checks whether IAM users have MFA enabled",source:"AWS_MANAGED",identifier:"IAM_USER_MFA_ENABLED"})}createRootAccountMfaRule(){return this.createConfigRule({name:"root-account-mfa-enabled",description:"Checks whether the root account has MFA enabled",source:"AWS_MANAGED",identifier:"ROOT_ACCOUNT_MFA_ENABLED"})}createVpcFlowLogsRule(){return this.createConfigRule({name:"vpc-flow-logs-enabled",description:"Checks whether VPC Flow Logs is enabled",source:"AWS_MANAGED",identifier:"VPC_FLOW_LOGS_ENABLED",scope:{complianceResourceTypes:["AWS::EC2::VPC"]}})}createCloudTrailEnabledRule(){return this.createConfigRule({name:"cloudtrail-enabled",description:"Checks whether CloudTrail is enabled",source:"AWS_MANAGED",identifier:"CLOUD_TRAIL_ENABLED",maxExecutionFrequency:"TwentyFour_Hours"})}createCloudWatchAlarmRule(){return this.createConfigRule({name:"cloudwatch-alarm-action-check",description:"Checks whether CloudWatch alarms have actions configured",source:"AWS_MANAGED",identifier:"CLOUDWATCH_ALARM_ACTION_CHECK",inputParameters:{alarmActionRequired:!0,insufficientDataActionRequired:!1,okActionRequired:!1},scope:{complianceResourceTypes:["AWS::CloudWatch::Alarm"]}})}createCustomLambdaRule(e){return this.createConfigRule({name:e.name,description:e.description,source:"CUSTOM_LAMBDA",lambdaFunctionArn:e.lambdaFunctionArn,scope:e.resourceTypes?{complianceResourceTypes:e.resourceTypes}:void 0,maxExecutionFrequency:e.maxExecutionFrequency,inputParameters:e.inputParameters})}createCompliancePreset(e){let a=[];switch(e){case"hipaa":a.push(this.createS3EncryptionRule(),this.createRdsEncryptionRule(),this.createEbsEncryptionRule(),this.createCloudTrailEnabledRule(),this.createIamPasswordPolicyRule(),this.createRdsBackupRule(7),this.createVpcFlowLogsRule());break;case"pci-dss":a.push(this.createS3EncryptionRule(),this.createS3PublicAccessBlockRule(),this.createRdsEncryptionRule(),this.createEbsEncryptionRule(),this.createCloudTrailEnabledRule(),this.createIamPasswordPolicyRule(),this.createIamMfaRule(),this.createRootAccountMfaRule(),this.createVpcFlowLogsRule());break;case"sox":a.push(this.createS3VersioningRule(),this.createCloudTrailEnabledRule(),this.createRdsBackupRule(30),this.createIamPasswordPolicyRule());break;case"gdpr":a.push(this.createS3EncryptionRule(),this.createRdsEncryptionRule(),this.createEbsEncryptionRule(),this.createCloudTrailEnabledRule(),this.createRdsSnapshotEncryptionRule());break;case"basic":a.push(this.createS3EncryptionRule(),this.createS3PublicAccessBlockRule(),this.createRdsEncryptionRule(),this.createCloudTrailEnabledRule(),this.createIamMfaRule(),this.createRootAccountMfaRule());break}return a}getConfigRule(e){return this.configRules.get(e)}listConfigRules(){return Array.from(this.configRules.values())}getConfigRecorder(e){return this.configRecorders.get(e)}listConfigRecorders(){return Array.from(this.configRecorders.values())}getDeliveryChannel(e){return this.deliveryChannels.get(e)}listDeliveryChannels(){return Array.from(this.deliveryChannels.values())}generateConfigRuleCF(e){let a={Type:"AWS::Config::ConfigRule",Properties:{ConfigRuleName:e.name,Description:e.description,Source:{Owner:e.source==="AWS_MANAGED"?"AWS":"CUSTOM_LAMBDA"}}};if(e.source==="AWS_MANAGED"&&e.identifier)a.Properties.Source.SourceIdentifier=e.identifier;if(e.source==="CUSTOM_LAMBDA"&&e.lambdaFunctionArn)a.Properties.Source.SourceIdentifier=e.lambdaFunctionArn,a.Properties.Source.SourceDetails=[{EventSource:"aws.config",MessageType:"ConfigurationItemChangeNotification"}];if(e.inputParameters)a.Properties.InputParameters=JSON.stringify(e.inputParameters);if(e.scope){if(a.Properties.Scope={},e.scope.complianceResourceTypes)a.Properties.Scope.ComplianceResourceTypes=e.scope.complianceResourceTypes;if(e.scope.tagKey)a.Properties.Scope.TagKey=e.scope.tagKey;if(e.scope.tagValue)a.Properties.Scope.TagValue=e.scope.tagValue}if(e.maxExecutionFrequency)a.Properties.MaximumExecutionFrequency=e.maxExecutionFrequency;return a}generateConfigRecorderCF(e){return{Type:"AWS::Config::ConfigurationRecorder",Properties:{Name:e.name,RoleArn:e.roleArn,RecordingGroup:e.recordingGroup||{AllSupported:!0,IncludeGlobalResourceTypes:!0}}}}generateDeliveryChannelCF(e){return{Type:"AWS::Config::DeliveryChannel",Properties:{Name:e.name,S3BucketName:e.s3BucketName,...e.s3KeyPrefix&&{S3KeyPrefix:e.s3KeyPrefix},...e.snsTopicArn&&{SnsTopicARN:e.snsTopicArn},...e.configSnapshotDeliveryProperties&&{ConfigSnapshotDeliveryProperties:e.configSnapshotDeliveryProperties}}}}clear(){this.configRules.clear(),this.configRecorders.clear(),this.deliveryChannels.clear(),this.ruleCounter=0}}var xg=new $c;class Oc{trails=new Map;trailCounter=0;createTrail(e){let a=`trail-${Date.now()}-${this.trailCounter++}`,r={id:a,...e};return this.trails.set(a,r),r}createOrganizationTrail(e){return this.createTrail({name:e.name,s3BucketName:e.s3BucketName,s3KeyPrefix:"organization-trail",includeGlobalServiceEvents:!0,isMultiRegionTrail:!0,enableLogFileValidation:!0,kmsKeyId:e.kmsKeyId,cloudWatchLogsLogGroupArn:e.cloudWatchLogsLogGroupArn,cloudWatchLogsRoleArn:e.cloudWatchLogsRoleArn})}createSecurityAuditTrail(e){return this.createTrail({name:e.name,s3BucketName:e.s3BucketName,s3KeyPrefix:"security-audit",includeGlobalServiceEvents:!0,isMultiRegionTrail:!0,enableLogFileValidation:!0,kmsKeyId:e.kmsKeyId,cloudWatchLogsLogGroupArn:e.cloudWatchLogsLogGroupArn,cloudWatchLogsRoleArn:e.cloudWatchLogsRoleArn,eventSelectors:[{readWriteType:"All",includeManagementEvents:!0,excludeManagementEventSources:[]}],insightSelectors:[{insightType:"ApiCallRateInsight"},{insightType:"ApiErrorRateInsight"}]})}createDataEventsTrail(e){let a=[];if(e.s3DataBuckets&&e.s3DataBuckets.length>0)a.push({type:"AWS::S3::Object",values:e.s3DataBuckets.map((r)=>`arn:aws:s3:::${r}/*`)});if(e.lambdaFunctions&&e.lambdaFunctions.length>0)a.push({type:"AWS::Lambda::Function",values:e.lambdaFunctions});return this.createTrail({name:e.name,s3BucketName:e.s3BucketName,s3KeyPrefix:"data-events",includeGlobalServiceEvents:!0,isMultiRegionTrail:!0,enableLogFileValidation:!0,eventSelectors:[{readWriteType:"All",includeManagementEvents:!1,dataResources:a}]})}createAdvancedTrail(e){return this.createTrail({name:e.name,s3BucketName:e.s3BucketName,includeGlobalServiceEvents:!0,isMultiRegionTrail:!0,enableLogFileValidation:!0,advancedEventSelectors:e.selectors})}createReadOnlyTrail(e){return this.createTrail({name:e.name,s3BucketName:e.s3BucketName,includeGlobalServiceEvents:!0,isMultiRegionTrail:!0,enableLogFileValidation:!0,eventSelectors:[{readWriteType:"ReadOnly",includeManagementEvents:!0}]})}createWriteOnlyTrail(e){return this.createTrail({name:e.name,s3BucketName:e.s3BucketName,includeGlobalServiceEvents:!0,isMultiRegionTrail:!0,enableLogFileValidation:!0,eventSelectors:[{readWriteType:"WriteOnly",includeManagementEvents:!0}]})}getTrail(e){return this.trails.get(e)}listTrails(){return Array.from(this.trails.values())}generateTrailCF(e){let a={Type:"AWS::CloudTrail::Trail",Properties:{TrailName:e.name,S3BucketName:e.s3BucketName,IsLogging:!0,IncludeGlobalServiceEvents:e.includeGlobalServiceEvents??!0,IsMultiRegionTrail:e.isMultiRegionTrail??!0,EnableLogFileValidation:e.enableLogFileValidation??!0}};if(e.s3KeyPrefix)a.Properties.S3KeyPrefix=e.s3KeyPrefix;if(e.cloudWatchLogsLogGroupArn)a.Properties.CloudWatchLogsLogGroupArn=e.cloudWatchLogsLogGroupArn;if(e.cloudWatchLogsRoleArn)a.Properties.CloudWatchLogsRoleArn=e.cloudWatchLogsRoleArn;if(e.snsTopicName)a.Properties.SnsTopicName=e.snsTopicName;if(e.kmsKeyId)a.Properties.KMSKeyId=e.kmsKeyId;if(e.eventSelectors)a.Properties.EventSelectors=e.eventSelectors.map((r)=>({ReadWriteType:r.readWriteType,IncludeManagementEvents:r.includeManagementEvents??!0,...r.dataResources&&{DataResources:r.dataResources.map((n)=>({Type:n.type,Values:n.values}))},...r.excludeManagementEventSources&&{ExcludeManagementEventSources:r.excludeManagementEventSources}}));if(e.insightSelectors)a.Properties.InsightSelectors=e.insightSelectors.map((r)=>({InsightType:r.insightType}));if(e.advancedEventSelectors)a.Properties.AdvancedEventSelectors=e.advancedEventSelectors.map((r)=>({Name:r.name,FieldSelectors:r.fieldSelectors.map((n)=>({Field:n.field,...n.equals&&{Equals:n.equals},...n.startsWith&&{StartsWith:n.startsWith},...n.endsWith&&{EndsWith:n.endsWith},...n.notEquals&&{NotEquals:n.notEquals},...n.notStartsWith&&{NotStartsWith:n.notStartsWith},...n.notEndsWith&&{NotEndsWith:n.notEndsWith}}))}));return a}generateBucketPolicy(e,a){return{Version:"2012-10-17",Statement:[{Sid:"AWSCloudTrailAclCheck",Effect:"Allow",Principal:{Service:"cloudtrail.amazonaws.com"},Action:"s3:GetBucketAcl",Resource:`arn:aws:s3:::${e}`},{Sid:"AWSCloudTrailWrite",Effect:"Allow",Principal:{Service:"cloudtrail.amazonaws.com"},Action:"s3:PutObject",Resource:a.map((r)=>`arn:aws:s3:::${e}/AWSLogs/${r}/*`),Condition:{StringEquals:{"s3:x-amz-acl":"bucket-owner-full-control"}}}]}}clear(){this.trails.clear(),this.trailCounter=0}}var _g=new Oc;class Lc{detectors=new Map;threatIntelSets=new Map;ipSets=new Map;filters=new Map;detectorCounter=0;threatIntelCounter=0;ipSetCounter=0;filterCounter=0;createDetector(e){let a=`detector-${Date.now()}-${this.detectorCounter++}`,r={id:a,...e};return this.detectors.set(a,r),r}createComprehensiveDetector(){return this.createDetector({enable:!0,findingPublishingFrequency:"FIFTEEN_MINUTES",dataSources:{s3Logs:{enable:!0},kubernetes:{auditLogs:{enable:!0}},malwareProtection:{scanEc2InstanceWithFindings:{ebsVolumes:{enable:!0}}}},features:[{name:"S3_DATA_EVENTS",status:"ENABLED"},{name:"EKS_AUDIT_LOGS",status:"ENABLED"},{name:"EBS_MALWARE_PROTECTION",status:"ENABLED"},{name:"RDS_LOGIN_EVENTS",status:"ENABLED"},{name:"LAMBDA_NETWORK_LOGS",status:"ENABLED"}]})}createBasicDetector(){return this.createDetector({enable:!0,findingPublishingFrequency:"SIX_HOURS"})}createThreatIntelSet(e){let a=`threat-intel-${Date.now()}-${this.threatIntelCounter++}`,r={id:a,...e};return this.threatIntelSets.set(a,r),r}createIPSet(e){let a=`ip-set-${Date.now()}-${this.ipSetCounter++}`,r={id:a,...e};return this.ipSets.set(a,r),r}createFindingFilter(e){let a=`filter-${Date.now()}-${this.filterCounter++}`,r={id:a,...e};return this.filters.set(a,r),r}createLowSeverityArchiveFilter(e){return this.createFindingFilter({detectorId:e,name:"archive-low-severity",description:"Automatically archive low severity findings",action:"ARCHIVE",rank:1,findingCriteria:{criterion:{severity:{lt:4}}}})}createFindingTypeFilter(e,a,r){return this.createFindingFilter({detectorId:e,name:`filter-finding-types-${r.toLowerCase()}`,description:`${r==="ARCHIVE"?"Archive":"Keep"} specific finding types`,action:r,rank:2,findingCriteria:{criterion:{type:{eq:a}}}})}createTrustedIPFilter(e,a){return this.createFindingFilter({detectorId:e,name:"trusted-ip-addresses",description:"Archive findings from trusted IP addresses",action:"ARCHIVE",rank:3,findingCriteria:{criterion:{"resource.instanceDetails.networkInterfaces.privateIpAddress":{eq:a}}}})}getDetector(e){return this.detectors.get(e)}listDetectors(){return Array.from(this.detectors.values())}getThreatIntelSet(e){return this.threatIntelSets.get(e)}listThreatIntelSets(){return Array.from(this.threatIntelSets.values())}getIPSet(e){return this.ipSets.get(e)}listIPSets(){return Array.from(this.ipSets.values())}getFindingFilter(e){return this.filters.get(e)}listFindingFilters(){return Array.from(this.filters.values())}generateDetectorCF(e){let a={Type:"AWS::GuardDuty::Detector",Properties:{Enable:e.enable}};if(e.findingPublishingFrequency)a.Properties.FindingPublishingFrequency=e.findingPublishingFrequency;if(e.dataSources){if(a.Properties.DataSources={},e.dataSources.s3Logs)a.Properties.DataSources.S3Logs={Enable:e.dataSources.s3Logs.enable};if(e.dataSources.kubernetes)a.Properties.DataSources.Kubernetes={AuditLogs:{Enable:e.dataSources.kubernetes.auditLogs.enable}};if(e.dataSources.malwareProtection)a.Properties.DataSources.MalwareProtection={ScanEc2InstanceWithFindings:{EbsVolumes:{Enable:e.dataSources.malwareProtection.scanEc2InstanceWithFindings.ebsVolumes.enable}}}}if(e.features)a.Properties.Features=e.features.map((r)=>({Name:r.name,Status:r.status,...r.additionalConfiguration&&{AdditionalConfiguration:r.additionalConfiguration}}));return a}generateThreatIntelSetCF(e){return{Type:"AWS::GuardDuty::ThreatIntelSet",Properties:{DetectorId:e.detectorId,Name:e.name,Format:e.format,Location:e.location,Activate:e.activate}}}generateIPSetCF(e){return{Type:"AWS::GuardDuty::IPSet",Properties:{DetectorId:e.detectorId,Name:e.name,Format:e.format,Location:e.location,Activate:e.activate}}}generateFilterCF(e){return{Type:"AWS::GuardDuty::Filter",Properties:{DetectorId:e.detectorId,Name:e.name,Description:e.description,Action:e.action,Rank:e.rank,FindingCriteria:{Criterion:e.findingCriteria.criterion}}}}clear(){this.detectors.clear(),this.threatIntelSets.clear(),this.ipSets.clear(),this.filters.clear(),this.detectorCounter=0,this.threatIntelCounter=0,this.ipSetCounter=0,this.filterCounter=0}}var $g=new Lc;class nn{hubs=new Map;hubCounter=0;ruleCounter=0;static Standards={AWS_FOUNDATIONAL_SECURITY:{arn:"arn:aws:securityhub:::ruleset/aws-foundational-security-best-practices/v/1.0.0",name:"AWS Foundational Security Best Practices",description:"AWS recommended security best practices"},CIS_AWS_FOUNDATIONS_1_2:{arn:"arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.2.0",name:"CIS AWS Foundations Benchmark v1.2.0",description:"CIS AWS Foundations Benchmark v1.2.0"},CIS_AWS_FOUNDATIONS_1_4:{arn:"arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.4.0",name:"CIS AWS Foundations Benchmark v1.4.0",description:"CIS AWS Foundations Benchmark v1.4.0"},PCI_DSS:{arn:"arn:aws:securityhub:us-east-1::standards/pci-dss/v/3.2.1",name:"PCI DSS v3.2.1",description:"Payment Card Industry Data Security Standard"},NIST_800_53:{arn:"arn:aws:securityhub:us-east-1::standards/nist-800-53/v/5.0.0",name:"NIST SP 800-53 Rev. 5",description:"NIST Special Publication 800-53 Revision 5"}};createHub(e){let a=`hub-${Date.now()}-${this.hubCounter++}`,r={id:a,...e};return this.hubs.set(a,r),r}createComprehensiveHub(){return this.createHub({enable:!0,controlFindingGenerator:"SECURITY_CONTROL",enableDefaultStandards:!0,standards:[{id:"aws-foundational",...nn.Standards.AWS_FOUNDATIONAL_SECURITY,enabled:!0},{id:"cis-1-4",...nn.Standards.CIS_AWS_FOUNDATIONS_1_4,enabled:!0},{id:"pci-dss",...nn.Standards.PCI_DSS,enabled:!0}]})}createBasicHub(){return this.createHub({enable:!0,controlFindingGenerator:"STANDARD_CONTROL",enableDefaultStandards:!0,standards:[{id:"aws-foundational",...nn.Standards.AWS_FOUNDATIONAL_SECURITY,enabled:!0}]})}createLowSeveritySuppressionRule(){return{id:`rule-${Date.now()}-${this.ruleCounter++}`,ruleName:"Suppress Low Severity Informational Findings",description:"Automatically suppress informational findings",actions:[{type:"FINDING_FIELDS_UPDATE",findingFieldsUpdate:{workflow:{status:"SUPPRESSED"},note:{text:"Automatically suppressed low severity finding",updatedBy:"SecurityHub Automation"}}}],criteria:{severityLabel:[{value:"INFORMATIONAL",comparison:"EQUALS"}],recordState:[{value:"ACTIVE",comparison:"EQUALS"}]},ruleStatus:"ENABLED",ruleOrder:1}}createResourceTypeNotificationRule(e){return{id:`rule-${Date.now()}-${this.ruleCounter++}`,ruleName:"Notify on Critical Resource Findings",description:"Set findings for critical resources to NOTIFIED status",actions:[{type:"FINDING_FIELDS_UPDATE",findingFieldsUpdate:{workflow:{status:"NOTIFIED"},note:{text:"Critical resource finding requires attention",updatedBy:"SecurityHub Automation"}}}],criteria:{resourceType:e.map((a)=>({value:a,comparison:"EQUALS"})),severityLabel:[{value:"HIGH",comparison:"EQUALS"},{value:"CRITICAL",comparison:"EQUALS"}],workflowStatus:[{value:"NEW",comparison:"EQUALS"}]},ruleStatus:"ENABLED",ruleOrder:2}}createComplianceFailureRule(){return{id:`rule-${Date.now()}-${this.ruleCounter++}`,ruleName:"Flag Compliance Failures",description:"Increase severity for compliance failures",actions:[{type:"FINDING_FIELDS_UPDATE",findingFieldsUpdate:{severity:{label:"HIGH"},workflow:{status:"NOTIFIED"},note:{text:"Compliance failure detected - requires immediate attention",updatedBy:"SecurityHub Automation"}}}],criteria:{complianceStatus:[{value:"FAILED",comparison:"EQUALS"}],recordState:[{value:"ACTIVE",comparison:"EQUALS"}]},ruleStatus:"ENABLED",ruleOrder:3}}createFalsePositiveSuppressionRule(e,a){return{id:`rule-${Date.now()}-${this.ruleCounter++}`,ruleName:`Suppress False Positives - ${e}`,description:`Automatically suppress known false positives from ${e}`,actions:[{type:"FINDING_FIELDS_UPDATE",findingFieldsUpdate:{workflow:{status:"SUPPRESSED"},note:{text:"Known false positive - automatically suppressed",updatedBy:"SecurityHub Automation"}}}],criteria:{productName:[{value:e,comparison:"EQUALS"}],title:a.map((r)=>({value:r,comparison:"PREFIX"}))},ruleStatus:"ENABLED",ruleOrder:10}}getHub(e){return this.hubs.get(e)}listHubs(){return Array.from(this.hubs.values())}generateHubCF(e){let a={Type:"AWS::SecurityHub::Hub",Properties:{}};if(e.controlFindingGenerator)a.Properties.ControlFindingGenerator=e.controlFindingGenerator;if(e.enableDefaultStandards!==void 0)a.Properties.EnableDefaultStandards=e.enableDefaultStandards;return a}generateStandardCF(e){let a={Type:"AWS::SecurityHub::Standard",Properties:{StandardsArn:e.arn}};if(e.disabledControls&&e.disabledControls.length>0)a.Properties.DisabledStandardsControls=e.disabledControls.map((r)=>({StandardsControlArn:r,Reason:"Disabled by configuration"}));return a}generateAutomationRuleCF(e){return{Type:"AWS::SecurityHub::AutomationRule",Properties:{RuleName:e.ruleName,Description:e.description,Actions:e.actions.map((a)=>({Type:a.type,FindingFieldsUpdate:a.findingFieldsUpdate})),Criteria:e.criteria,RuleStatus:e.ruleStatus,RuleOrder:e.ruleOrder}}}clear(){this.hubs.clear(),this.hubCounter=0,this.ruleCounter=0}}var Og=new nn;class Mc{deployments=new Map;deploymentHistory=new Map;deploymentCounter=0;resultCounter=0;createDeployment(e){let a=`bg-deployment-${Date.now()}-${this.deploymentCounter++}`,r={id:a,...e};return this.deployments.set(a,r),r}createALBDeployment(e){return this.createDeployment({name:e.name,blueEnvironment:{name:"blue",targetGroupArn:e.blueTargetGroupArn,weight:100},greenEnvironment:{name:"green",targetGroupArn:e.greenTargetGroupArn,weight:0},activeEnvironment:"blue",routingConfig:{type:"alb",listenerArn:e.listenerArn,switchoverTimeSeconds:0},autoPromote:e.autoPromote,healthCheckConfig:e.healthCheckConfig})}createRoute53Deployment(e){return this.createDeployment({name:e.name,blueEnvironment:{name:"blue",targetGroupArn:e.blueTargetGroupArn,weight:100},greenEnvironment:{name:"green",targetGroupArn:e.greenTargetGroupArn,weight:0},activeEnvironment:"blue",routingConfig:{type:"route53",hostedZoneId:e.hostedZoneId,switchoverTimeSeconds:e.switchoverTimeSeconds||60}})}createECSDeployment(e){return this.createDeployment({name:e.name,blueEnvironment:{name:"blue",targetGroupArn:e.blueTargetGroupArn,taskDefinitionArn:e.blueTaskDefinitionArn,weight:100},greenEnvironment:{name:"green",targetGroupArn:e.greenTargetGroupArn,taskDefinitionArn:e.greenTaskDefinitionArn,weight:0},activeEnvironment:"blue",routingConfig:{type:"alb",listenerArn:e.listenerArn},autoRollback:e.autoRollback??!0})}async executeDeployment(e,a=!1){let r=this.deployments.get(e);if(!r)throw Error(`Deployment not found: ${e}`);let n={success:!1,deploymentId:`result-${Date.now()}-${this.resultCounter++}`,startTime:new Date,healthChecksPassed:!1,errors:[]};console.log(`${a?"[DRY RUN] ":""}Starting blue/green deployment: ${r.name}`),console.log(` Active environment: ${r.activeEnvironment}`),console.log(` Routing type: ${r.routingConfig.type}`);let i=r.activeEnvironment==="blue"?"green":"blue";if(console.log(` Switching to: ${i}`),console.log(`\\n1. Deploying to ${i} environment`),!a)await new Promise((o)=>setTimeout(o,100));if(console.log(`\\n2. Running health checks on ${i} environment`),r.healthCheckConfig){let o=await this.runHealthChecks(r,i,a);if(n.healthChecksPassed=o,!o){if(n.errors?.push("Health checks failed"),n.endTime=new Date,r.autoRollback)console.log(" Auto-rollback enabled - keeping current environment active"),n.rolledBackAt=new Date;return this.recordDeployment(e,n),n}}else n.healthChecksPassed=!0;if(console.log(`\\n3. Switching traffic to ${i} environment`),!a)r.activeEnvironment=i,n.switchedAt=new Date;if(console.log(`\\n4. Monitoring ${i} environment`),!a)await new Promise((o)=>setTimeout(o,100));return n.success=!0,n.endTime=new Date,console.log("\\n✓ Deployment completed successfully"),this.recordDeployment(e,n),n}async rollback(e){let a=this.deployments.get(e);if(!a)throw Error(`Deployment not found: ${e}`);let r={success:!1,deploymentId:`result-${Date.now()}-${this.resultCounter++}`,startTime:new Date,healthChecksPassed:!0,errors:[]};console.log(`Rolling back deployment: ${a.name}`);let n=a.activeEnvironment==="blue"?"green":"blue";return a.activeEnvironment=n,r.success=!0,r.rolledBackAt=new Date,r.endTime=new Date,console.log(` Switched back to: ${n}`),this.recordDeployment(e,r),r}async runHealthChecks(e,a,r){let n=e.healthCheckConfig;if(console.log(` Health check path: ${n.path||"/"}`),console.log(` Healthy threshold: ${n.healthyThreshold}`),console.log(` Interval: ${n.interval}s`),r)return console.log(" [SKIPPED - DRY RUN]"),!0;let i=0,o=n.healthyThreshold+2;for(let c=0;c<o;c++)if(await new Promise((u)=>setTimeout(u,50)),Math.random()>0.1){if(i++,console.log(` Check ${c+1}: ✓ Healthy (${i}/${n.healthyThreshold})`),i>=n.healthyThreshold)return!0}else i=0,console.log(` Check ${c+1}: ✗ Unhealthy`);return!1}recordDeployment(e,a){if(!this.deploymentHistory.has(e))this.deploymentHistory.set(e,[]);this.deploymentHistory.get(e).push(a)}getDeployment(e){return this.deployments.get(e)}listDeployments(){return Array.from(this.deployments.values())}getDeploymentHistory(e){return this.deploymentHistory.get(e)||[]}generateALBListenerCF(e){let a=e.activeEnvironment==="blue"?e.blueEnvironment:e.greenEnvironment;return{Type:"AWS::ElasticLoadBalancingV2::ListenerRule",Properties:{ListenerArn:e.routingConfig.listenerArn,Priority:1,Conditions:[{Field:"path-pattern",Values:["/*"]}],Actions:[{Type:"forward",TargetGroupArn:a.targetGroupArn}]}}}generateRoute53RecordSetCF(e,a){return[{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:e.routingConfig.hostedZoneId,Name:a,Type:"A",SetIdentifier:"blue",Weight:e.activeEnvironment==="blue"?100:0,AliasTarget:{HostedZoneId:e.routingConfig.hostedZoneId,DNSName:e.blueEnvironment.targetGroupArn,EvaluateTargetHealth:!0}}},{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:e.routingConfig.hostedZoneId,Name:a,Type:"A",SetIdentifier:"green",Weight:e.activeEnvironment==="green"?100:0,AliasTarget:{HostedZoneId:e.routingConfig.hostedZoneId,DNSName:e.greenEnvironment.targetGroupArn,EvaluateTargetHealth:!0}}}]}clear(){this.deployments.clear(),this.deploymentHistory.clear(),this.deploymentCounter=0,this.resultCounter=0}}var Lg=new Mc;class Ro{deployments=new Map;deploymentHistory=new Map;deploymentCounter=0;resultCounter=0;static Strategies={CONSERVATIVE:[{name:"Initial Canary",trafficPercentage:10,durationMinutes:10},{name:"Quarter Traffic",trafficPercentage:25,durationMinutes:10},{name:"Half Traffic",trafficPercentage:50,durationMinutes:15},{name:"Full Traffic",trafficPercentage:100,durationMinutes:5}],BALANCED:[{name:"Initial Canary",trafficPercentage:20,durationMinutes:5},{name:"Half Traffic",trafficPercentage:50,durationMinutes:10},{name:"Full Traffic",trafficPercentage:100,durationMinutes:5}],AGGRESSIVE:[{name:"Half Traffic",trafficPercentage:50,durationMinutes:5},{name:"Full Traffic",trafficPercentage:100,durationMinutes:5}],LINEAR_10:[{name:"Canary 10%",trafficPercentage:10,durationMinutes:5},{name:"Canary 20%",trafficPercentage:20,durationMinutes:5},{name:"Canary 30%",trafficPercentage:30,durationMinutes:5},{name:"Canary 40%",trafficPercentage:40,durationMinutes:5},{name:"Canary 50%",trafficPercentage:50,durationMinutes:5},{name:"Canary 60%",trafficPercentage:60,durationMinutes:5},{name:"Canary 70%",trafficPercentage:70,durationMinutes:5},{name:"Canary 80%",trafficPercentage:80,durationMinutes:5},{name:"Canary 90%",trafficPercentage:90,durationMinutes:5},{name:"Full Traffic",trafficPercentage:100,durationMinutes:5}]};createDeployment(e){let a=`canary-${Date.now()}-${this.deploymentCounter++}`,r={id:a,...e};return this.deployments.set(a,r),r}createLambdaCanaryDeployment(e){let a=e.strategy||"BALANCED",r=Ro.Strategies[a].map((n)=>({...n,alarmThresholds:{errorRate:e.errorRateThreshold||1,latencyP99:e.latencyThreshold||1000}}));return this.createDeployment({name:e.name,baselineVersion:{version:"baseline",functionVersionArn:e.baselineVersionArn,weight:100},canaryVersion:{version:"canary",functionVersionArn:e.canaryVersionArn,weight:0},stages:r,currentStage:0,status:"pending",autoPromote:e.autoPromote??!0,autoRollback:!0})}createECSCanaryDeployment(e){let a=e.strategy||"CONSERVATIVE",r=Ro.Strategies[a];return this.createDeployment({name:e.name,baselineVersion:{version:"baseline",taskDefinitionArn:e.baselineTaskDefinitionArn,targetGroupArn:e.baselineTargetGroupArn,weight:100},canaryVersion:{version:"canary",taskDefinitionArn:e.canaryTaskDefinitionArn,targetGroupArn:e.canaryTargetGroupArn,weight:0},stages:r,currentStage:0,status:"pending",autoRollback:!0})}async executeDeployment(e,a=!1){let r=this.deployments.get(e);if(!r)throw Error(`Deployment not found: ${e}`);let n={success:!1,deploymentId:`result-${Date.now()}-${this.resultCounter++}`,startTime:new Date,completedStages:0,rolledBack:!1};console.log(`${a?"[DRY RUN] ":""}Starting canary deployment: ${r.name}`),console.log(` Strategy: ${r.stages.length} stages`),console.log(` Auto-promote: ${r.autoPromote}`),console.log(` Auto-rollback: ${r.autoRollback}`),console.log(""),r.status="in_progress";for(let i=0;i<r.stages.length;i++){let o=r.stages[i];if(r.currentStage=i,console.log(`Stage ${i+1}/${r.stages.length}: ${o.name}`),console.log(` Traffic: ${o.trafficPercentage}% canary, ${100-o.trafficPercentage}% baseline`),console.log(` Duration: ${o.durationMinutes} minutes`),!a)r.baselineVersion.weight=100-o.trafficPercentage,r.canaryVersion.weight=o.trafficPercentage;if(!await this.monitorStage(r,o,a)){if(console.log(" ✗ Stage failed - metrics exceeded thresholds"),r.autoRollback)console.log("\\n Rolling back deployment..."),await this.rollback(e,a),n.rolledBack=!0,n.reason="Metrics exceeded thresholds";return n.endTime=new Date,r.status="rolled_back",this.recordDeployment(e,n),n}console.log(" ✓ Stage completed successfully"),n.completedStages++,console.log("")}return r.status="completed",n.success=!0,n.endTime=new Date,console.log("✓ Canary deployment completed successfully"),this.recordDeployment(e,n),n}async monitorStage(e,a,r){if(console.log(" Monitoring metrics..."),r)return console.log(" [SKIPPED - DRY RUN]"),!0;await new Promise((i)=>setTimeout(i,100));let n={baselineErrorRate:Math.random()*0.5,canaryErrorRate:Math.random()*0.8,baselineLatencyP99:200+Math.random()*100,canaryLatencyP99:180+Math.random()*150,baselineRequestCount:Math.floor(Math.random()*1000)+500,canaryRequestCount:Math.floor((Math.random()*1000+500)*a.trafficPercentage/100)};if(e.metrics=n,console.log(` Baseline: ${n.baselineErrorRate.toFixed(2)}% errors, ${n.baselineLatencyP99.toFixed(0)}ms P99`),console.log(` Canary: ${n.canaryErrorRate.toFixed(2)}% errors, ${n.canaryLatencyP99.toFixed(0)}ms P99`),a.alarmThresholds){let{errorRate:i,latencyP99:o}=a.alarmThresholds;if(i&&n.canaryErrorRate>i)return console.log(` ⚠ Error rate exceeded threshold: ${n.canaryErrorRate.toFixed(2)}% > ${i}%`),!1;if(o&&n.canaryLatencyP99>o)return console.log(` ⚠ Latency P99 exceeded threshold: ${n.canaryLatencyP99.toFixed(0)}ms > ${o}ms`),!1}return!0}async rollback(e,a=!1){let r=this.deployments.get(e);if(!r)throw Error(`Deployment not found: ${e}`);if(console.log(`${a?"[DRY RUN] ":""}Rolling back canary deployment: ${r.name}`),!a)r.baselineVersion.weight=100,r.canaryVersion.weight=0,r.status="rolled_back";console.log(" Traffic restored to baseline: 100%")}promoteCanary(e){let a=this.deployments.get(e);if(!a)throw Error(`Deployment not found: ${e}`);console.log(`Promoting canary to baseline: ${a.name}`);let r=a.baselineVersion;a.baselineVersion=a.canaryVersion,a.canaryVersion=r,a.baselineVersion.weight=100,a.canaryVersion.weight=0,a.status="completed",console.log(" Canary promoted successfully")}recordDeployment(e,a){if(!this.deploymentHistory.has(e))this.deploymentHistory.set(e,[]);this.deploymentHistory.get(e).push(a)}getDeployment(e){return this.deployments.get(e)}listDeployments(){return Array.from(this.deployments.values())}getDeploymentHistory(e){return this.deploymentHistory.get(e)||[]}generateLambdaAliasCF(e,a){return{Type:"AWS::Lambda::Alias",Properties:{FunctionName:{Ref:"LambdaFunction"},Name:a,FunctionVersion:e.canaryVersion.version,RoutingConfig:{AdditionalVersionWeights:[{FunctionVersion:e.baselineVersion.version,FunctionWeight:e.baselineVersion.weight/100}]}}}}generateALBListenerRuleCF(e){return{Type:"AWS::ElasticLoadBalancingV2::ListenerRule",Properties:{ListenerArn:{Ref:"LoadBalancerListener"},Priority:1,Conditions:[{Field:"path-pattern",Values:["/*"]}],Actions:[{Type:"forward",ForwardConfig:{TargetGroups:[{TargetGroupArn:e.baselineVersion.targetGroupArn,Weight:e.baselineVersion.weight},{TargetGroupArn:e.canaryVersion.targetGroupArn,Weight:e.canaryVersion.weight}],TargetGroupStickinessConfig:{Enabled:!1}}}]}}}clear(){this.deployments.clear(),this.deploymentHistory.clear(),this.deploymentCounter=0,this.resultCounter=0}}var Mg=new Ro;class Uc{tests=new Map;testCounter=0;createTest(e){let a=`abtest-${Date.now()}-${this.testCounter++}`,r={id:a,...e};return this.tests.set(a,r),r}createSimpleABTest(e){let a=e.variantTrafficPercentage||50;return this.createTest({name:e.name,description:e.description,variants:[{id:"control",name:"Control",description:"Original version",trafficPercentage:100-a,targetGroupArn:e.controlTargetGroupArn,weight:100-a},{id:"variant-a",name:"Variant A",description:"Test version",trafficPercentage:a,targetGroupArn:e.variantTargetGroupArn,weight:a}],routingStrategy:{type:e.stickySession?"cookie":"random",cookieName:e.stickySession?"ab_variant":void 0,stickySession:e.stickySession??!1,sessionDuration:1440},startTime:new Date,status:"draft"})}createMultivariateTest(e){let a=e.variants.reduce((r,n)=>r+n.trafficPercentage,0);if(a!==100)throw Error(`Traffic percentages must sum to 100, got ${a}`);return this.createTest({name:e.name,description:e.description,variants:e.variants.map((r,n)=>({id:`variant-${n}`,name:r.name,description:r.description,trafficPercentage:r.trafficPercentage,targetGroupArn:r.targetGroupArn,weight:r.trafficPercentage})),routingStrategy:e.routingStrategy||{type:"random",stickySession:!1},startTime:new Date,status:"draft"})}createHeaderBasedTest(e){return this.createTest({name:e.name,description:`Route based on ${e.headerName} header`,variants:[{id:"control",name:"Control",trafficPercentage:50,targetGroupArn:e.controlTargetGroupArn,weight:50},{id:"variant-a",name:"Variant A",trafficPercentage:50,targetGroupArn:e.variantTargetGroupArn,weight:50}],routingStrategy:{type:"header",headerName:e.headerName,stickySession:!1},startTime:new Date,status:"draft"})}createGeoBasedTest(e){return this.createTest({name:e.name,description:"Route based on geographic location",variants:[{id:"control",name:"Control (Rest of World)",trafficPercentage:50,targetGroupArn:e.controlTargetGroupArn,weight:50},{id:"variant-a",name:`Variant A (${e.regions.join(", ")})`,trafficPercentage:50,targetGroupArn:e.variantTargetGroupArn,weight:50}],routingStrategy:{type:"geo",stickySession:!0,sessionDuration:1440},startTime:new Date,status:"draft"})}startTest(e){let a=this.tests.get(e);if(!a)throw Error(`Test not found: ${e}`);if(a.status!=="draft"&&a.status!=="paused")throw Error(`Cannot start test in ${a.status} status`);a.status="active",a.startTime=new Date,console.log(`Started A/B test: ${a.name}`),console.log(` Variants: ${a.variants.length}`),a.variants.forEach((r)=>{console.log(` - ${r.name}: ${r.trafficPercentage}%`)})}pauseTest(e){let a=this.tests.get(e);if(!a)throw Error(`Test not found: ${e}`);a.status="paused",console.log(`Paused A/B test: ${a.name}`)}updateTrafficSplit(e,a,r){let n=this.tests.get(e);if(!n)throw Error(`Test not found: ${e}`);let i=n.variants.find((c)=>c.id===a);if(!i)throw Error(`Variant not found: ${a}`);let o=i.trafficPercentage;i.trafficPercentage=r,i.weight=r,console.log(`Updated ${i.name} traffic: ${o}% → ${r}%`)}analyzeResults(e){let a=this.tests.get(e);if(!a)throw Error(`Test not found: ${e}`);if(!a.metrics)a.metrics=this.collectMetrics(a);let r=a.variants[0],n=0;for(let m of a.variants){let p=a.metrics.variants[m.id];if(p&&p.conversionRate>n)n=p.conversionRate,r=m}let i=a.metrics.variants.control||a.metrics.variants[a.variants[0].id],o=a.metrics.variants[r.id],c=(o.conversionRate-i.conversionRate)/i.conversionRate*100,u=100,d=o.requests>u&&i.requests>u&&Math.abs(c)>10;return{testId:e,winningVariant:r.name,confidence:d?95:75,improvement:c,statisticalSignificance:d,metrics:a.metrics,recommendation:this.generateRecommendation(c,d,r.name)}}declareWinner(e,a){let r=this.tests.get(e);if(!r)throw Error(`Test not found: ${e}`);let n=r.variants.find((i)=>i.id===a);if(!n)throw Error(`Variant not found: ${a}`);r.variants.forEach((i)=>{if(i.id===a)i.trafficPercentage=100,i.weight=100;else i.trafficPercentage=0,i.weight=0}),r.status="completed",r.endTime=new Date,r.winner=a,console.log(`Declared winner: ${n.name}`),console.log(` All traffic now routed to ${n.name}`)}collectMetrics(e){let a={},r=0;for(let n of e.variants){let i=Math.floor(Math.random()*1000)+500,o=Math.floor(i*(Math.random()*0.1+0.05)),c=o/i*100;a[n.id]={requests:i,conversions:o,conversionRate:c,averageLatency:150+Math.random()*100,errorRate:Math.random()*0.5,revenue:o*(Math.random()*50+100)},r+=i}return{variants:a,totalRequests:r,startTime:e.startTime,lastUpdated:new Date}}generateRecommendation(e,a,r){if(!a)return"Continue test - sample size too small or no significant difference detected";if(e>20)return`Strong winner detected - ${r} shows ${e.toFixed(1)}% improvement. Recommend deploying to all traffic.`;if(e>10)return`Moderate improvement - ${r} shows ${e.toFixed(1)}% improvement. Consider deploying.`;if(e>0)return`Minor improvement - ${r} shows ${e.toFixed(1)}% improvement. May not be worth the complexity.`;return"No improvement detected - consider reverting to control variant"}getTest(e){return this.tests.get(e)}listTests(){return Array.from(this.tests.values())}generateALBListenerRuleCF(e){return{Type:"AWS::ElasticLoadBalancingV2::ListenerRule",Properties:{ListenerArn:{Ref:"LoadBalancerListener"},Priority:1,Conditions:[{Field:"path-pattern",Values:["/*"]}],Actions:[{Type:"forward",ForwardConfig:{TargetGroups:e.variants.map((a)=>({TargetGroupArn:a.targetGroupArn,Weight:a.weight})),TargetGroupStickinessConfig:{Enabled:e.routingStrategy.stickySession||!1,DurationSeconds:e.routingStrategy.sessionDuration?e.routingStrategy.sessionDuration*60:void 0}}}]}}}generateLambdaEdgeFunction(e){return`'use strict';
|
|
3610
|
+
`}class _c{backupPlans=new Map;backupVaults=new Map;restoreJobs=new Map;continuousBackups=new Map;planCounter=0;restoreCounter=0;continuousBackupCounter=0;createVault(e){this.backupVaults.set(e.name,e)}getVault(e){return this.backupVaults.get(e)}createBackupPlan(e){let a=`backup-plan-${Date.now()}-${this.planCounter++}`,r={id:a,...e};return this.backupPlans.set(a,r),r}getBackupPlan(e){return this.backupPlans.get(e)}listBackupPlans(){return Array.from(this.backupPlans.values())}createRDSBackupPlan(e){let{dbInstanceArn:a,schedule:r="0 2 * * *",retentionDays:n=7,vaultName:i="default-vault"}=e;return this.createBackupPlan({name:"RDS Daily Backup",schedule:r,retentionDays:n,vaultName:i,resources:[{resourceArn:a,resourceType:"rds",region:"us-east-1"}],lifecycle:{moveTocoldStorageAfterDays:30,deleteAfterDays:n}})}createDynamoDBBackupPlan(e){let{tableArn:a,schedule:r="0 3 * * *",retentionDays:n=35,crossRegionCopy:i}=e;return this.createBackupPlan({name:"DynamoDB Daily Backup",schedule:r,retentionDays:n,vaultName:"dynamodb-vault",resources:[{resourceArn:a,resourceType:"dynamodb",region:"us-east-1"}],lifecycle:{deleteAfterDays:n},tags:i?{CrossRegionCopy:i.join(",")}:void 0})}createEFSBackupPlan(e){let{fileSystemArn:a,schedule:r="0 1 * * *",retentionDays:n=30}=e;return this.createBackupPlan({name:"EFS Daily Backup",schedule:r,retentionDays:n,vaultName:"efs-vault",resources:[{resourceArn:a,resourceType:"efs",region:"us-east-1"}],lifecycle:{deleteAfterDays:n}})}enableContinuousBackup(e,a=35){let r=`continuous-backup-${Date.now()}-${this.continuousBackupCounter++}`,n={id:r,resourceId:e,enabled:!0,retentionDays:a};return this.continuousBackups.set(r,n),n}getContinuousBackup(e){return this.continuousBackups.get(e)}enablePointInTimeRecovery(e,a){return{enabled:!0,earliestRestorableTime:new Date(Date.now()-604800000),latestRestorableTime:new Date}}async restoreFromBackup(e){let{backupId:a,resourceType:r,targetRegion:n}=e,i={id:`restore-${Date.now()}-${this.restoreCounter++}`,backupId:a,resourceType:r,status:"pending",startTime:new Date,targetRegion:n};return this.restoreJobs.set(i.id,i),setTimeout(()=>{i.status="running"},100),setTimeout(()=>{i.status="completed",i.endTime=new Date},1000),i}async restoreToPointInTime(e){let{sourceResourceArn:a,targetResourceName:r,restoreTime:n,resourceType:i}=e,o={id:`pitr-${Date.now()}-${this.restoreCounter++}`,backupId:`pitr-${n.getTime()}`,resourceType:i,status:"pending",startTime:new Date};return this.restoreJobs.set(o.id,o),console.log(`Restoring ${i} from ${a} to ${r} at ${n.toISOString()}`),setTimeout(()=>{o.status="completed",o.endTime=new Date},2000),o}getRestoreJob(e){return this.restoreJobs.get(e)}listRestoreJobs(){return Array.from(this.restoreJobs.values())}setupCrossRegionReplication(e){let{sourceVault:a,sourceRegion:r,targetRegions:n}=e;console.log("Setting up cross-region replication:"),console.log(` Source: ${a} in ${r}`),console.log(` Targets: ${n.join(", ")}`)}generateBackupVaultCF(e){return{Type:"AWS::Backup::BackupVault",Properties:{BackupVaultName:e.name,...e.encryptionKeyArn&&{EncryptionKeyArn:e.encryptionKeyArn},...e.accessPolicy&&{AccessPolicy:e.accessPolicy}}}}generateBackupPlanCF(e){return{Type:"AWS::Backup::BackupPlan",Properties:{BackupPlan:{BackupPlanName:e.name,BackupPlanRule:[{RuleName:"DailyBackup",TargetBackupVault:e.vaultName,ScheduleExpression:`cron(${e.schedule})`,StartWindowMinutes:60,CompletionWindowMinutes:120,Lifecycle:e.lifecycle?{...e.lifecycle.moveTocoldStorageAfterDays&&{MoveToColdStorageAfterDays:e.lifecycle.moveTocoldStorageAfterDays},...e.lifecycle.deleteAfterDays&&{DeleteAfterDays:e.lifecycle.deleteAfterDays}}:void 0}]},...e.tags&&{BackupPlanTags:e.tags}}}}generateBackupSelectionCF(e){return{Type:"AWS::Backup::BackupSelection",Properties:{BackupPlanId:{Ref:`BackupPlan${e.id}`},BackupSelection:{SelectionName:`${e.name}Selection`,IamRoleArn:"arn:aws:iam::123456789012:role/service-role/AWSBackupDefaultServiceRole",Resources:e.resources.map((a)=>a.resourceArn)}}}}clear(){this.backupPlans.clear(),this.backupVaults.clear(),this.restoreJobs.clear(),this.continuousBackups.clear(),this.planCounter=0,this.restoreCounter=0,this.continuousBackupCounter=0}}var Dg=new _c;class xc{drPlans=new Map;failoverTests=new Map;planCounter=0;testCounter=0;createDRPlan(e){let a=`dr-plan-${Date.now()}-${this.planCounter++}`,r={id:a,...e};return this.drPlans.set(a,r),r}createRDSDRPlan(e){let{primaryDbArn:a,secondaryDbArn:r,primaryRegion:n,secondaryRegion:i,rto:o=60,rpo:c=5}=e;return this.createDRPlan({name:"RDS Multi-Region DR",primaryRegion:n,secondaryRegion:i,rto:o,rpo:c,resources:[{resourceId:"primary-db",resourceType:"rds",primaryArn:a,secondaryArn:r,replicationEnabled:!0}],runbook:this.generateRDSRunbook(n,i),testSchedule:"0 0 1 * *"})}createDynamoDBDRPlan(e){let{tableArn:a,regions:r,rto:n=15,rpo:i=1}=e;return this.createDRPlan({name:"DynamoDB Global Tables DR",primaryRegion:r[0],secondaryRegion:r[1],rto:n,rpo:i,resources:[{resourceId:"dynamodb-table",resourceType:"dynamodb",primaryArn:a,replicationEnabled:!0}],runbook:this.generateDynamoDBRunbook(r)})}generateRDSRunbook(e,a){return{estimatedDuration:60,requiredApprovals:["cto","engineering-lead"],steps:[{order:1,name:"Verify Primary Database Failure",description:"Confirm that the primary database is truly unavailable and not experiencing temporary issues",action:"aws rds describe-db-instances --region "+e,automatable:!0,estimatedDuration:2,rollbackable:!1},{order:2,name:"Check Replication Lag",description:"Verify that the read replica is up to date",action:"Check ReplicaLag metric in CloudWatch",automatable:!0,estimatedDuration:1,rollbackable:!1},{order:3,name:"Promote Read Replica",description:"Promote the read replica in the secondary region to be the new primary",action:"aws rds promote-read-replica --db-instance-identifier replica --region "+a,automatable:!0,estimatedDuration:10,rollbackable:!1},{order:4,name:"Update DNS Records",description:"Update Route53 records to point to the new primary database",action:"Update Route53 failover record set",automatable:!0,estimatedDuration:5,rollbackable:!0},{order:5,name:"Update Application Configuration",description:"Update application connection strings if needed",action:"Deploy configuration update to ECS/Lambda",automatable:!0,estimatedDuration:10,rollbackable:!0},{order:6,name:"Verify Application Connectivity",description:"Test that applications can connect to the new primary",action:"Run smoke tests",automatable:!0,estimatedDuration:5,rollbackable:!1},{order:7,name:"Monitor for Issues",description:"Monitor CloudWatch metrics and application logs",action:"Monitor for 30 minutes",automatable:!1,estimatedDuration:30,rollbackable:!1}]}}generateDynamoDBRunbook(e){return{estimatedDuration:15,steps:[{order:1,name:"Verify Primary Region Failure",description:"Confirm that the primary region is experiencing an outage",action:"Check AWS Health Dashboard",automatable:!0,estimatedDuration:2,rollbackable:!1},{order:2,name:"Update Route53 Failover",description:"Update Route53 to direct traffic to secondary region",action:"Update Route53 health check and failover records",automatable:!0,estimatedDuration:5,rollbackable:!0},{order:3,name:"Update Application Endpoints",description:"Update Lambda/ECS to use secondary region DynamoDB endpoint",action:"Deploy configuration update",automatable:!0,estimatedDuration:5,rollbackable:!0},{order:4,name:"Verify Data Consistency",description:"Verify that data is consistent in secondary region",action:"Run data validation queries",automatable:!0,estimatedDuration:3,rollbackable:!1}]}}async executeFailover(e,a=!1){let r=this.drPlans.get(e);if(!r)throw Error(`DR plan not found: ${e}`);let n=Date.now(),i=0;console.log(`${a?"[DRY RUN] ":""}Executing failover for plan: ${r.name}`),console.log(`Primary: ${r.primaryRegion} -> Secondary: ${r.secondaryRegion}`),console.log(`RTO: ${r.rto} minutes, RPO: ${r.rpo} minutes`),console.log("");for(let o of r.runbook.steps){if(console.log(`Step ${o.order}: ${o.name}`),console.log(` ${o.description}`),console.log(` Action: ${o.action}`),console.log(` Estimated: ${o.estimatedDuration} minutes`),a)console.log(" [SKIPPED - DRY RUN]");else if(o.automatable)console.log(" [AUTOMATED]");else console.log(" [MANUAL - WAITING]");i++,console.log("")}return{success:!0,duration:(Date.now()-n)/1000/60,completedSteps:i}}scheduleFailoverTest(e,a){let r={id:`failover-test-${Date.now()}-${this.testCounter++}`,planId:e,status:"scheduled",startTime:a};return this.failoverTests.set(r.id,r),r}async runFailoverTest(e){let a=this.drPlans.get(e);if(!a)throw Error(`DR plan not found: ${e}`);let r={id:`failover-test-${Date.now()}-${this.testCounter++}`,planId:e,status:"running",startTime:new Date,results:[]};this.failoverTests.set(r.id,r),console.log(`Running failover test for plan: ${a.name}`),console.log("This is a non-destructive test using test resources"),console.log("");for(let n of a.runbook.steps){let i=Date.now();console.log(`Testing step ${n.order}: ${n.name}`);let o={step:n.name,status:"success",duration:(Date.now()-i)/1000,message:`Successfully validated step ${n.order}`};r.results.push(o)}return r.status="completed",r.endTime=new Date,r}getDRPlan(e){return this.drPlans.get(e)}listDRPlans(){return Array.from(this.drPlans.values())}getFailoverTest(e){return this.failoverTests.get(e)}listFailoverTests(){return Array.from(this.failoverTests.values())}validateDRPlan(e){let a=[],r=[];if(e.rto<e.rpo)r.push("RTO cannot be less than RPO");if(e.rto>240)a.push("RTO exceeds 4 hours - consider improving recovery time");if(e.rpo>60)a.push("RPO exceeds 1 hour - consider more frequent backups");if(e.resources.length===0)r.push("No resources defined in DR plan");for(let o of e.resources){if(!o.replicationEnabled)a.push(`Resource ${o.resourceId} does not have replication enabled`);if(!o.secondaryArn&&o.resourceType!=="dynamodb")a.push(`Resource ${o.resourceId} does not have secondary resource defined`)}if(e.runbook.steps.length===0)r.push("No recovery steps defined in runbook");let n=e.runbook.steps.reduce((o,c)=>o+c.estimatedDuration,0);if(n>e.rto)a.push(`Estimated recovery duration (${n}m) exceeds RTO (${e.rto}m)`);let i=e.runbook.steps.filter((o)=>!o.automatable);if(i.length>0)a.push(`${i.length} manual steps in runbook - consider automation`);return{valid:r.length===0,warnings:a,errors:r}}clear(){this.drPlans.clear(),this.failoverTests.clear(),this.planCounter=0,this.testCounter=0}}var kg=new xc;class $c{configRules=new Map;configRecorders=new Map;deliveryChannels=new Map;ruleCounter=0;createConfigRecorder(e){return this.configRecorders.set(e.name,e),e}createDeliveryChannel(e){return this.deliveryChannels.set(e.name,e),e}createConfigRule(e){let a=`config-rule-${Date.now()}-${this.ruleCounter++}`,r={id:a,...e};return this.configRules.set(a,r),r}createS3EncryptionRule(){return this.createConfigRule({name:"s3-bucket-server-side-encryption-enabled",description:"Checks that S3 buckets have server-side encryption enabled",source:"AWS_MANAGED",identifier:"S3_BUCKET_SERVER_SIDE_ENCRYPTION_ENABLED",scope:{complianceResourceTypes:["AWS::S3::Bucket"]}})}createS3PublicAccessBlockRule(){return this.createConfigRule({name:"s3-bucket-public-read-prohibited",description:"Checks that S3 buckets do not allow public read access",source:"AWS_MANAGED",identifier:"S3_BUCKET_PUBLIC_READ_PROHIBITED",scope:{complianceResourceTypes:["AWS::S3::Bucket"]}})}createS3VersioningRule(){return this.createConfigRule({name:"s3-bucket-versioning-enabled",description:"Checks whether versioning is enabled for S3 buckets",source:"AWS_MANAGED",identifier:"S3_BUCKET_VERSIONING_ENABLED",scope:{complianceResourceTypes:["AWS::S3::Bucket"]}})}createRdsEncryptionRule(){return this.createConfigRule({name:"rds-storage-encrypted",description:"Checks whether storage encryption is enabled for RDS DB instances",source:"AWS_MANAGED",identifier:"RDS_STORAGE_ENCRYPTED",scope:{complianceResourceTypes:["AWS::RDS::DBInstance"]}})}createRdsSnapshotEncryptionRule(){return this.createConfigRule({name:"rds-snapshots-public-prohibited",description:"Checks if RDS snapshots are public",source:"AWS_MANAGED",identifier:"RDS_SNAPSHOTS_PUBLIC_PROHIBITED",scope:{complianceResourceTypes:["AWS::RDS::DBSnapshot","AWS::RDS::DBClusterSnapshot"]}})}createRdsBackupRule(e=7){return this.createConfigRule({name:"db-backup-enabled",description:"Checks whether RDS DB instances have backups enabled",source:"AWS_MANAGED",identifier:"DB_BACKUP_ENABLED",inputParameters:{backupRetentionPeriod:e},scope:{complianceResourceTypes:["AWS::RDS::DBInstance"]}})}createEc2InstanceProfileRule(){return this.createConfigRule({name:"ec2-instance-managed-by-systems-manager",description:"Checks if EC2 instances are managed by Systems Manager",source:"AWS_MANAGED",identifier:"EC2_INSTANCE_MANAGED_BY_SSM",scope:{complianceResourceTypes:["AWS::EC2::Instance"]}})}createEbsEncryptionRule(){return this.createConfigRule({name:"encrypted-volumes",description:"Checks whether EBS volumes are encrypted",source:"AWS_MANAGED",identifier:"ENCRYPTED_VOLUMES",scope:{complianceResourceTypes:["AWS::EC2::Volume"]}})}createIamPasswordPolicyRule(){return this.createConfigRule({name:"iam-password-policy",description:"Checks whether the IAM password policy meets specified requirements",source:"AWS_MANAGED",identifier:"IAM_PASSWORD_POLICY",inputParameters:{RequireUppercaseCharacters:!0,RequireLowercaseCharacters:!0,RequireSymbols:!0,RequireNumbers:!0,MinimumPasswordLength:14,PasswordReusePrevention:24,MaxPasswordAge:90}})}createIamMfaRule(){return this.createConfigRule({name:"iam-user-mfa-enabled",description:"Checks whether IAM users have MFA enabled",source:"AWS_MANAGED",identifier:"IAM_USER_MFA_ENABLED"})}createRootAccountMfaRule(){return this.createConfigRule({name:"root-account-mfa-enabled",description:"Checks whether the root account has MFA enabled",source:"AWS_MANAGED",identifier:"ROOT_ACCOUNT_MFA_ENABLED"})}createVpcFlowLogsRule(){return this.createConfigRule({name:"vpc-flow-logs-enabled",description:"Checks whether VPC Flow Logs is enabled",source:"AWS_MANAGED",identifier:"VPC_FLOW_LOGS_ENABLED",scope:{complianceResourceTypes:["AWS::EC2::VPC"]}})}createCloudTrailEnabledRule(){return this.createConfigRule({name:"cloudtrail-enabled",description:"Checks whether CloudTrail is enabled",source:"AWS_MANAGED",identifier:"CLOUD_TRAIL_ENABLED",maxExecutionFrequency:"TwentyFour_Hours"})}createCloudWatchAlarmRule(){return this.createConfigRule({name:"cloudwatch-alarm-action-check",description:"Checks whether CloudWatch alarms have actions configured",source:"AWS_MANAGED",identifier:"CLOUDWATCH_ALARM_ACTION_CHECK",inputParameters:{alarmActionRequired:!0,insufficientDataActionRequired:!1,okActionRequired:!1},scope:{complianceResourceTypes:["AWS::CloudWatch::Alarm"]}})}createCustomLambdaRule(e){return this.createConfigRule({name:e.name,description:e.description,source:"CUSTOM_LAMBDA",lambdaFunctionArn:e.lambdaFunctionArn,scope:e.resourceTypes?{complianceResourceTypes:e.resourceTypes}:void 0,maxExecutionFrequency:e.maxExecutionFrequency,inputParameters:e.inputParameters})}createCompliancePreset(e){let a=[];switch(e){case"hipaa":a.push(this.createS3EncryptionRule(),this.createRdsEncryptionRule(),this.createEbsEncryptionRule(),this.createCloudTrailEnabledRule(),this.createIamPasswordPolicyRule(),this.createRdsBackupRule(7),this.createVpcFlowLogsRule());break;case"pci-dss":a.push(this.createS3EncryptionRule(),this.createS3PublicAccessBlockRule(),this.createRdsEncryptionRule(),this.createEbsEncryptionRule(),this.createCloudTrailEnabledRule(),this.createIamPasswordPolicyRule(),this.createIamMfaRule(),this.createRootAccountMfaRule(),this.createVpcFlowLogsRule());break;case"sox":a.push(this.createS3VersioningRule(),this.createCloudTrailEnabledRule(),this.createRdsBackupRule(30),this.createIamPasswordPolicyRule());break;case"gdpr":a.push(this.createS3EncryptionRule(),this.createRdsEncryptionRule(),this.createEbsEncryptionRule(),this.createCloudTrailEnabledRule(),this.createRdsSnapshotEncryptionRule());break;case"basic":a.push(this.createS3EncryptionRule(),this.createS3PublicAccessBlockRule(),this.createRdsEncryptionRule(),this.createCloudTrailEnabledRule(),this.createIamMfaRule(),this.createRootAccountMfaRule());break}return a}getConfigRule(e){return this.configRules.get(e)}listConfigRules(){return Array.from(this.configRules.values())}getConfigRecorder(e){return this.configRecorders.get(e)}listConfigRecorders(){return Array.from(this.configRecorders.values())}getDeliveryChannel(e){return this.deliveryChannels.get(e)}listDeliveryChannels(){return Array.from(this.deliveryChannels.values())}generateConfigRuleCF(e){let a={Type:"AWS::Config::ConfigRule",Properties:{ConfigRuleName:e.name,Description:e.description,Source:{Owner:e.source==="AWS_MANAGED"?"AWS":"CUSTOM_LAMBDA"}}};if(e.source==="AWS_MANAGED"&&e.identifier)a.Properties.Source.SourceIdentifier=e.identifier;if(e.source==="CUSTOM_LAMBDA"&&e.lambdaFunctionArn)a.Properties.Source.SourceIdentifier=e.lambdaFunctionArn,a.Properties.Source.SourceDetails=[{EventSource:"aws.config",MessageType:"ConfigurationItemChangeNotification"}];if(e.inputParameters)a.Properties.InputParameters=JSON.stringify(e.inputParameters);if(e.scope){if(a.Properties.Scope={},e.scope.complianceResourceTypes)a.Properties.Scope.ComplianceResourceTypes=e.scope.complianceResourceTypes;if(e.scope.tagKey)a.Properties.Scope.TagKey=e.scope.tagKey;if(e.scope.tagValue)a.Properties.Scope.TagValue=e.scope.tagValue}if(e.maxExecutionFrequency)a.Properties.MaximumExecutionFrequency=e.maxExecutionFrequency;return a}generateConfigRecorderCF(e){return{Type:"AWS::Config::ConfigurationRecorder",Properties:{Name:e.name,RoleArn:e.roleArn,RecordingGroup:e.recordingGroup||{AllSupported:!0,IncludeGlobalResourceTypes:!0}}}}generateDeliveryChannelCF(e){return{Type:"AWS::Config::DeliveryChannel",Properties:{Name:e.name,S3BucketName:e.s3BucketName,...e.s3KeyPrefix&&{S3KeyPrefix:e.s3KeyPrefix},...e.snsTopicArn&&{SnsTopicARN:e.snsTopicArn},...e.configSnapshotDeliveryProperties&&{ConfigSnapshotDeliveryProperties:e.configSnapshotDeliveryProperties}}}}clear(){this.configRules.clear(),this.configRecorders.clear(),this.deliveryChannels.clear(),this.ruleCounter=0}}var _g=new $c;class Oc{trails=new Map;trailCounter=0;createTrail(e){let a=`trail-${Date.now()}-${this.trailCounter++}`,r={id:a,...e};return this.trails.set(a,r),r}createOrganizationTrail(e){return this.createTrail({name:e.name,s3BucketName:e.s3BucketName,s3KeyPrefix:"organization-trail",includeGlobalServiceEvents:!0,isMultiRegionTrail:!0,enableLogFileValidation:!0,kmsKeyId:e.kmsKeyId,cloudWatchLogsLogGroupArn:e.cloudWatchLogsLogGroupArn,cloudWatchLogsRoleArn:e.cloudWatchLogsRoleArn})}createSecurityAuditTrail(e){return this.createTrail({name:e.name,s3BucketName:e.s3BucketName,s3KeyPrefix:"security-audit",includeGlobalServiceEvents:!0,isMultiRegionTrail:!0,enableLogFileValidation:!0,kmsKeyId:e.kmsKeyId,cloudWatchLogsLogGroupArn:e.cloudWatchLogsLogGroupArn,cloudWatchLogsRoleArn:e.cloudWatchLogsRoleArn,eventSelectors:[{readWriteType:"All",includeManagementEvents:!0,excludeManagementEventSources:[]}],insightSelectors:[{insightType:"ApiCallRateInsight"},{insightType:"ApiErrorRateInsight"}]})}createDataEventsTrail(e){let a=[];if(e.s3DataBuckets&&e.s3DataBuckets.length>0)a.push({type:"AWS::S3::Object",values:e.s3DataBuckets.map((r)=>`arn:aws:s3:::${r}/*`)});if(e.lambdaFunctions&&e.lambdaFunctions.length>0)a.push({type:"AWS::Lambda::Function",values:e.lambdaFunctions});return this.createTrail({name:e.name,s3BucketName:e.s3BucketName,s3KeyPrefix:"data-events",includeGlobalServiceEvents:!0,isMultiRegionTrail:!0,enableLogFileValidation:!0,eventSelectors:[{readWriteType:"All",includeManagementEvents:!1,dataResources:a}]})}createAdvancedTrail(e){return this.createTrail({name:e.name,s3BucketName:e.s3BucketName,includeGlobalServiceEvents:!0,isMultiRegionTrail:!0,enableLogFileValidation:!0,advancedEventSelectors:e.selectors})}createReadOnlyTrail(e){return this.createTrail({name:e.name,s3BucketName:e.s3BucketName,includeGlobalServiceEvents:!0,isMultiRegionTrail:!0,enableLogFileValidation:!0,eventSelectors:[{readWriteType:"ReadOnly",includeManagementEvents:!0}]})}createWriteOnlyTrail(e){return this.createTrail({name:e.name,s3BucketName:e.s3BucketName,includeGlobalServiceEvents:!0,isMultiRegionTrail:!0,enableLogFileValidation:!0,eventSelectors:[{readWriteType:"WriteOnly",includeManagementEvents:!0}]})}getTrail(e){return this.trails.get(e)}listTrails(){return Array.from(this.trails.values())}generateTrailCF(e){let a={Type:"AWS::CloudTrail::Trail",Properties:{TrailName:e.name,S3BucketName:e.s3BucketName,IsLogging:!0,IncludeGlobalServiceEvents:e.includeGlobalServiceEvents??!0,IsMultiRegionTrail:e.isMultiRegionTrail??!0,EnableLogFileValidation:e.enableLogFileValidation??!0}};if(e.s3KeyPrefix)a.Properties.S3KeyPrefix=e.s3KeyPrefix;if(e.cloudWatchLogsLogGroupArn)a.Properties.CloudWatchLogsLogGroupArn=e.cloudWatchLogsLogGroupArn;if(e.cloudWatchLogsRoleArn)a.Properties.CloudWatchLogsRoleArn=e.cloudWatchLogsRoleArn;if(e.snsTopicName)a.Properties.SnsTopicName=e.snsTopicName;if(e.kmsKeyId)a.Properties.KMSKeyId=e.kmsKeyId;if(e.eventSelectors)a.Properties.EventSelectors=e.eventSelectors.map((r)=>({ReadWriteType:r.readWriteType,IncludeManagementEvents:r.includeManagementEvents??!0,...r.dataResources&&{DataResources:r.dataResources.map((n)=>({Type:n.type,Values:n.values}))},...r.excludeManagementEventSources&&{ExcludeManagementEventSources:r.excludeManagementEventSources}}));if(e.insightSelectors)a.Properties.InsightSelectors=e.insightSelectors.map((r)=>({InsightType:r.insightType}));if(e.advancedEventSelectors)a.Properties.AdvancedEventSelectors=e.advancedEventSelectors.map((r)=>({Name:r.name,FieldSelectors:r.fieldSelectors.map((n)=>({Field:n.field,...n.equals&&{Equals:n.equals},...n.startsWith&&{StartsWith:n.startsWith},...n.endsWith&&{EndsWith:n.endsWith},...n.notEquals&&{NotEquals:n.notEquals},...n.notStartsWith&&{NotStartsWith:n.notStartsWith},...n.notEndsWith&&{NotEndsWith:n.notEndsWith}}))}));return a}generateBucketPolicy(e,a){return{Version:"2012-10-17",Statement:[{Sid:"AWSCloudTrailAclCheck",Effect:"Allow",Principal:{Service:"cloudtrail.amazonaws.com"},Action:"s3:GetBucketAcl",Resource:`arn:aws:s3:::${e}`},{Sid:"AWSCloudTrailWrite",Effect:"Allow",Principal:{Service:"cloudtrail.amazonaws.com"},Action:"s3:PutObject",Resource:a.map((r)=>`arn:aws:s3:::${e}/AWSLogs/${r}/*`),Condition:{StringEquals:{"s3:x-amz-acl":"bucket-owner-full-control"}}}]}}clear(){this.trails.clear(),this.trailCounter=0}}var xg=new Oc;class Lc{detectors=new Map;threatIntelSets=new Map;ipSets=new Map;filters=new Map;detectorCounter=0;threatIntelCounter=0;ipSetCounter=0;filterCounter=0;createDetector(e){let a=`detector-${Date.now()}-${this.detectorCounter++}`,r={id:a,...e};return this.detectors.set(a,r),r}createComprehensiveDetector(){return this.createDetector({enable:!0,findingPublishingFrequency:"FIFTEEN_MINUTES",dataSources:{s3Logs:{enable:!0},kubernetes:{auditLogs:{enable:!0}},malwareProtection:{scanEc2InstanceWithFindings:{ebsVolumes:{enable:!0}}}},features:[{name:"S3_DATA_EVENTS",status:"ENABLED"},{name:"EKS_AUDIT_LOGS",status:"ENABLED"},{name:"EBS_MALWARE_PROTECTION",status:"ENABLED"},{name:"RDS_LOGIN_EVENTS",status:"ENABLED"},{name:"LAMBDA_NETWORK_LOGS",status:"ENABLED"}]})}createBasicDetector(){return this.createDetector({enable:!0,findingPublishingFrequency:"SIX_HOURS"})}createThreatIntelSet(e){let a=`threat-intel-${Date.now()}-${this.threatIntelCounter++}`,r={id:a,...e};return this.threatIntelSets.set(a,r),r}createIPSet(e){let a=`ip-set-${Date.now()}-${this.ipSetCounter++}`,r={id:a,...e};return this.ipSets.set(a,r),r}createFindingFilter(e){let a=`filter-${Date.now()}-${this.filterCounter++}`,r={id:a,...e};return this.filters.set(a,r),r}createLowSeverityArchiveFilter(e){return this.createFindingFilter({detectorId:e,name:"archive-low-severity",description:"Automatically archive low severity findings",action:"ARCHIVE",rank:1,findingCriteria:{criterion:{severity:{lt:4}}}})}createFindingTypeFilter(e,a,r){return this.createFindingFilter({detectorId:e,name:`filter-finding-types-${r.toLowerCase()}`,description:`${r==="ARCHIVE"?"Archive":"Keep"} specific finding types`,action:r,rank:2,findingCriteria:{criterion:{type:{eq:a}}}})}createTrustedIPFilter(e,a){return this.createFindingFilter({detectorId:e,name:"trusted-ip-addresses",description:"Archive findings from trusted IP addresses",action:"ARCHIVE",rank:3,findingCriteria:{criterion:{"resource.instanceDetails.networkInterfaces.privateIpAddress":{eq:a}}}})}getDetector(e){return this.detectors.get(e)}listDetectors(){return Array.from(this.detectors.values())}getThreatIntelSet(e){return this.threatIntelSets.get(e)}listThreatIntelSets(){return Array.from(this.threatIntelSets.values())}getIPSet(e){return this.ipSets.get(e)}listIPSets(){return Array.from(this.ipSets.values())}getFindingFilter(e){return this.filters.get(e)}listFindingFilters(){return Array.from(this.filters.values())}generateDetectorCF(e){let a={Type:"AWS::GuardDuty::Detector",Properties:{Enable:e.enable}};if(e.findingPublishingFrequency)a.Properties.FindingPublishingFrequency=e.findingPublishingFrequency;if(e.dataSources){if(a.Properties.DataSources={},e.dataSources.s3Logs)a.Properties.DataSources.S3Logs={Enable:e.dataSources.s3Logs.enable};if(e.dataSources.kubernetes)a.Properties.DataSources.Kubernetes={AuditLogs:{Enable:e.dataSources.kubernetes.auditLogs.enable}};if(e.dataSources.malwareProtection)a.Properties.DataSources.MalwareProtection={ScanEc2InstanceWithFindings:{EbsVolumes:{Enable:e.dataSources.malwareProtection.scanEc2InstanceWithFindings.ebsVolumes.enable}}}}if(e.features)a.Properties.Features=e.features.map((r)=>({Name:r.name,Status:r.status,...r.additionalConfiguration&&{AdditionalConfiguration:r.additionalConfiguration}}));return a}generateThreatIntelSetCF(e){return{Type:"AWS::GuardDuty::ThreatIntelSet",Properties:{DetectorId:e.detectorId,Name:e.name,Format:e.format,Location:e.location,Activate:e.activate}}}generateIPSetCF(e){return{Type:"AWS::GuardDuty::IPSet",Properties:{DetectorId:e.detectorId,Name:e.name,Format:e.format,Location:e.location,Activate:e.activate}}}generateFilterCF(e){return{Type:"AWS::GuardDuty::Filter",Properties:{DetectorId:e.detectorId,Name:e.name,Description:e.description,Action:e.action,Rank:e.rank,FindingCriteria:{Criterion:e.findingCriteria.criterion}}}}clear(){this.detectors.clear(),this.threatIntelSets.clear(),this.ipSets.clear(),this.filters.clear(),this.detectorCounter=0,this.threatIntelCounter=0,this.ipSetCounter=0,this.filterCounter=0}}var $g=new Lc;class nn{hubs=new Map;hubCounter=0;ruleCounter=0;static Standards={AWS_FOUNDATIONAL_SECURITY:{arn:"arn:aws:securityhub:::ruleset/aws-foundational-security-best-practices/v/1.0.0",name:"AWS Foundational Security Best Practices",description:"AWS recommended security best practices"},CIS_AWS_FOUNDATIONS_1_2:{arn:"arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.2.0",name:"CIS AWS Foundations Benchmark v1.2.0",description:"CIS AWS Foundations Benchmark v1.2.0"},CIS_AWS_FOUNDATIONS_1_4:{arn:"arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.4.0",name:"CIS AWS Foundations Benchmark v1.4.0",description:"CIS AWS Foundations Benchmark v1.4.0"},PCI_DSS:{arn:"arn:aws:securityhub:us-east-1::standards/pci-dss/v/3.2.1",name:"PCI DSS v3.2.1",description:"Payment Card Industry Data Security Standard"},NIST_800_53:{arn:"arn:aws:securityhub:us-east-1::standards/nist-800-53/v/5.0.0",name:"NIST SP 800-53 Rev. 5",description:"NIST Special Publication 800-53 Revision 5"}};createHub(e){let a=`hub-${Date.now()}-${this.hubCounter++}`,r={id:a,...e};return this.hubs.set(a,r),r}createComprehensiveHub(){return this.createHub({enable:!0,controlFindingGenerator:"SECURITY_CONTROL",enableDefaultStandards:!0,standards:[{id:"aws-foundational",...nn.Standards.AWS_FOUNDATIONAL_SECURITY,enabled:!0},{id:"cis-1-4",...nn.Standards.CIS_AWS_FOUNDATIONS_1_4,enabled:!0},{id:"pci-dss",...nn.Standards.PCI_DSS,enabled:!0}]})}createBasicHub(){return this.createHub({enable:!0,controlFindingGenerator:"STANDARD_CONTROL",enableDefaultStandards:!0,standards:[{id:"aws-foundational",...nn.Standards.AWS_FOUNDATIONAL_SECURITY,enabled:!0}]})}createLowSeveritySuppressionRule(){return{id:`rule-${Date.now()}-${this.ruleCounter++}`,ruleName:"Suppress Low Severity Informational Findings",description:"Automatically suppress informational findings",actions:[{type:"FINDING_FIELDS_UPDATE",findingFieldsUpdate:{workflow:{status:"SUPPRESSED"},note:{text:"Automatically suppressed low severity finding",updatedBy:"SecurityHub Automation"}}}],criteria:{severityLabel:[{value:"INFORMATIONAL",comparison:"EQUALS"}],recordState:[{value:"ACTIVE",comparison:"EQUALS"}]},ruleStatus:"ENABLED",ruleOrder:1}}createResourceTypeNotificationRule(e){return{id:`rule-${Date.now()}-${this.ruleCounter++}`,ruleName:"Notify on Critical Resource Findings",description:"Set findings for critical resources to NOTIFIED status",actions:[{type:"FINDING_FIELDS_UPDATE",findingFieldsUpdate:{workflow:{status:"NOTIFIED"},note:{text:"Critical resource finding requires attention",updatedBy:"SecurityHub Automation"}}}],criteria:{resourceType:e.map((a)=>({value:a,comparison:"EQUALS"})),severityLabel:[{value:"HIGH",comparison:"EQUALS"},{value:"CRITICAL",comparison:"EQUALS"}],workflowStatus:[{value:"NEW",comparison:"EQUALS"}]},ruleStatus:"ENABLED",ruleOrder:2}}createComplianceFailureRule(){return{id:`rule-${Date.now()}-${this.ruleCounter++}`,ruleName:"Flag Compliance Failures",description:"Increase severity for compliance failures",actions:[{type:"FINDING_FIELDS_UPDATE",findingFieldsUpdate:{severity:{label:"HIGH"},workflow:{status:"NOTIFIED"},note:{text:"Compliance failure detected - requires immediate attention",updatedBy:"SecurityHub Automation"}}}],criteria:{complianceStatus:[{value:"FAILED",comparison:"EQUALS"}],recordState:[{value:"ACTIVE",comparison:"EQUALS"}]},ruleStatus:"ENABLED",ruleOrder:3}}createFalsePositiveSuppressionRule(e,a){return{id:`rule-${Date.now()}-${this.ruleCounter++}`,ruleName:`Suppress False Positives - ${e}`,description:`Automatically suppress known false positives from ${e}`,actions:[{type:"FINDING_FIELDS_UPDATE",findingFieldsUpdate:{workflow:{status:"SUPPRESSED"},note:{text:"Known false positive - automatically suppressed",updatedBy:"SecurityHub Automation"}}}],criteria:{productName:[{value:e,comparison:"EQUALS"}],title:a.map((r)=>({value:r,comparison:"PREFIX"}))},ruleStatus:"ENABLED",ruleOrder:10}}getHub(e){return this.hubs.get(e)}listHubs(){return Array.from(this.hubs.values())}generateHubCF(e){let a={Type:"AWS::SecurityHub::Hub",Properties:{}};if(e.controlFindingGenerator)a.Properties.ControlFindingGenerator=e.controlFindingGenerator;if(e.enableDefaultStandards!==void 0)a.Properties.EnableDefaultStandards=e.enableDefaultStandards;return a}generateStandardCF(e){let a={Type:"AWS::SecurityHub::Standard",Properties:{StandardsArn:e.arn}};if(e.disabledControls&&e.disabledControls.length>0)a.Properties.DisabledStandardsControls=e.disabledControls.map((r)=>({StandardsControlArn:r,Reason:"Disabled by configuration"}));return a}generateAutomationRuleCF(e){return{Type:"AWS::SecurityHub::AutomationRule",Properties:{RuleName:e.ruleName,Description:e.description,Actions:e.actions.map((a)=>({Type:a.type,FindingFieldsUpdate:a.findingFieldsUpdate})),Criteria:e.criteria,RuleStatus:e.ruleStatus,RuleOrder:e.ruleOrder}}}clear(){this.hubs.clear(),this.hubCounter=0,this.ruleCounter=0}}var Og=new nn;class Mc{deployments=new Map;deploymentHistory=new Map;deploymentCounter=0;resultCounter=0;createDeployment(e){let a=`bg-deployment-${Date.now()}-${this.deploymentCounter++}`,r={id:a,...e};return this.deployments.set(a,r),r}createALBDeployment(e){return this.createDeployment({name:e.name,blueEnvironment:{name:"blue",targetGroupArn:e.blueTargetGroupArn,weight:100},greenEnvironment:{name:"green",targetGroupArn:e.greenTargetGroupArn,weight:0},activeEnvironment:"blue",routingConfig:{type:"alb",listenerArn:e.listenerArn,switchoverTimeSeconds:0},autoPromote:e.autoPromote,healthCheckConfig:e.healthCheckConfig})}createRoute53Deployment(e){return this.createDeployment({name:e.name,blueEnvironment:{name:"blue",targetGroupArn:e.blueTargetGroupArn,weight:100},greenEnvironment:{name:"green",targetGroupArn:e.greenTargetGroupArn,weight:0},activeEnvironment:"blue",routingConfig:{type:"route53",hostedZoneId:e.hostedZoneId,switchoverTimeSeconds:e.switchoverTimeSeconds||60}})}createECSDeployment(e){return this.createDeployment({name:e.name,blueEnvironment:{name:"blue",targetGroupArn:e.blueTargetGroupArn,taskDefinitionArn:e.blueTaskDefinitionArn,weight:100},greenEnvironment:{name:"green",targetGroupArn:e.greenTargetGroupArn,taskDefinitionArn:e.greenTaskDefinitionArn,weight:0},activeEnvironment:"blue",routingConfig:{type:"alb",listenerArn:e.listenerArn},autoRollback:e.autoRollback??!0})}async executeDeployment(e,a=!1){let r=this.deployments.get(e);if(!r)throw Error(`Deployment not found: ${e}`);let n={success:!1,deploymentId:`result-${Date.now()}-${this.resultCounter++}`,startTime:new Date,healthChecksPassed:!1,errors:[]};console.log(`${a?"[DRY RUN] ":""}Starting blue/green deployment: ${r.name}`),console.log(` Active environment: ${r.activeEnvironment}`),console.log(` Routing type: ${r.routingConfig.type}`);let i=r.activeEnvironment==="blue"?"green":"blue";if(console.log(` Switching to: ${i}`),console.log(`\\n1. Deploying to ${i} environment`),!a)await new Promise((o)=>setTimeout(o,100));if(console.log(`\\n2. Running health checks on ${i} environment`),r.healthCheckConfig){let o=await this.runHealthChecks(r,i,a);if(n.healthChecksPassed=o,!o){if(n.errors?.push("Health checks failed"),n.endTime=new Date,r.autoRollback)console.log(" Auto-rollback enabled - keeping current environment active"),n.rolledBackAt=new Date;return this.recordDeployment(e,n),n}}else n.healthChecksPassed=!0;if(console.log(`\\n3. Switching traffic to ${i} environment`),!a)r.activeEnvironment=i,n.switchedAt=new Date;if(console.log(`\\n4. Monitoring ${i} environment`),!a)await new Promise((o)=>setTimeout(o,100));return n.success=!0,n.endTime=new Date,console.log("\\n✓ Deployment completed successfully"),this.recordDeployment(e,n),n}async rollback(e){let a=this.deployments.get(e);if(!a)throw Error(`Deployment not found: ${e}`);let r={success:!1,deploymentId:`result-${Date.now()}-${this.resultCounter++}`,startTime:new Date,healthChecksPassed:!0,errors:[]};console.log(`Rolling back deployment: ${a.name}`);let n=a.activeEnvironment==="blue"?"green":"blue";return a.activeEnvironment=n,r.success=!0,r.rolledBackAt=new Date,r.endTime=new Date,console.log(` Switched back to: ${n}`),this.recordDeployment(e,r),r}async runHealthChecks(e,a,r){let n=e.healthCheckConfig;if(console.log(` Health check path: ${n.path||"/"}`),console.log(` Healthy threshold: ${n.healthyThreshold}`),console.log(` Interval: ${n.interval}s`),r)return console.log(" [SKIPPED - DRY RUN]"),!0;let i=0,o=n.healthyThreshold+2;for(let c=0;c<o;c++)if(await new Promise((u)=>setTimeout(u,50)),Math.random()>0.1){if(i++,console.log(` Check ${c+1}: ✓ Healthy (${i}/${n.healthyThreshold})`),i>=n.healthyThreshold)return!0}else i=0,console.log(` Check ${c+1}: ✗ Unhealthy`);return!1}recordDeployment(e,a){if(!this.deploymentHistory.has(e))this.deploymentHistory.set(e,[]);this.deploymentHistory.get(e).push(a)}getDeployment(e){return this.deployments.get(e)}listDeployments(){return Array.from(this.deployments.values())}getDeploymentHistory(e){return this.deploymentHistory.get(e)||[]}generateALBListenerCF(e){let a=e.activeEnvironment==="blue"?e.blueEnvironment:e.greenEnvironment;return{Type:"AWS::ElasticLoadBalancingV2::ListenerRule",Properties:{ListenerArn:e.routingConfig.listenerArn,Priority:1,Conditions:[{Field:"path-pattern",Values:["/*"]}],Actions:[{Type:"forward",TargetGroupArn:a.targetGroupArn}]}}}generateRoute53RecordSetCF(e,a){return[{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:e.routingConfig.hostedZoneId,Name:a,Type:"A",SetIdentifier:"blue",Weight:e.activeEnvironment==="blue"?100:0,AliasTarget:{HostedZoneId:e.routingConfig.hostedZoneId,DNSName:e.blueEnvironment.targetGroupArn,EvaluateTargetHealth:!0}}},{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:e.routingConfig.hostedZoneId,Name:a,Type:"A",SetIdentifier:"green",Weight:e.activeEnvironment==="green"?100:0,AliasTarget:{HostedZoneId:e.routingConfig.hostedZoneId,DNSName:e.greenEnvironment.targetGroupArn,EvaluateTargetHealth:!0}}}]}clear(){this.deployments.clear(),this.deploymentHistory.clear(),this.deploymentCounter=0,this.resultCounter=0}}var Lg=new Mc;class Ro{deployments=new Map;deploymentHistory=new Map;deploymentCounter=0;resultCounter=0;static Strategies={CONSERVATIVE:[{name:"Initial Canary",trafficPercentage:10,durationMinutes:10},{name:"Quarter Traffic",trafficPercentage:25,durationMinutes:10},{name:"Half Traffic",trafficPercentage:50,durationMinutes:15},{name:"Full Traffic",trafficPercentage:100,durationMinutes:5}],BALANCED:[{name:"Initial Canary",trafficPercentage:20,durationMinutes:5},{name:"Half Traffic",trafficPercentage:50,durationMinutes:10},{name:"Full Traffic",trafficPercentage:100,durationMinutes:5}],AGGRESSIVE:[{name:"Half Traffic",trafficPercentage:50,durationMinutes:5},{name:"Full Traffic",trafficPercentage:100,durationMinutes:5}],LINEAR_10:[{name:"Canary 10%",trafficPercentage:10,durationMinutes:5},{name:"Canary 20%",trafficPercentage:20,durationMinutes:5},{name:"Canary 30%",trafficPercentage:30,durationMinutes:5},{name:"Canary 40%",trafficPercentage:40,durationMinutes:5},{name:"Canary 50%",trafficPercentage:50,durationMinutes:5},{name:"Canary 60%",trafficPercentage:60,durationMinutes:5},{name:"Canary 70%",trafficPercentage:70,durationMinutes:5},{name:"Canary 80%",trafficPercentage:80,durationMinutes:5},{name:"Canary 90%",trafficPercentage:90,durationMinutes:5},{name:"Full Traffic",trafficPercentage:100,durationMinutes:5}]};createDeployment(e){let a=`canary-${Date.now()}-${this.deploymentCounter++}`,r={id:a,...e};return this.deployments.set(a,r),r}createLambdaCanaryDeployment(e){let a=e.strategy||"BALANCED",r=Ro.Strategies[a].map((n)=>({...n,alarmThresholds:{errorRate:e.errorRateThreshold||1,latencyP99:e.latencyThreshold||1000}}));return this.createDeployment({name:e.name,baselineVersion:{version:"baseline",functionVersionArn:e.baselineVersionArn,weight:100},canaryVersion:{version:"canary",functionVersionArn:e.canaryVersionArn,weight:0},stages:r,currentStage:0,status:"pending",autoPromote:e.autoPromote??!0,autoRollback:!0})}createECSCanaryDeployment(e){let a=e.strategy||"CONSERVATIVE",r=Ro.Strategies[a];return this.createDeployment({name:e.name,baselineVersion:{version:"baseline",taskDefinitionArn:e.baselineTaskDefinitionArn,targetGroupArn:e.baselineTargetGroupArn,weight:100},canaryVersion:{version:"canary",taskDefinitionArn:e.canaryTaskDefinitionArn,targetGroupArn:e.canaryTargetGroupArn,weight:0},stages:r,currentStage:0,status:"pending",autoRollback:!0})}async executeDeployment(e,a=!1){let r=this.deployments.get(e);if(!r)throw Error(`Deployment not found: ${e}`);let n={success:!1,deploymentId:`result-${Date.now()}-${this.resultCounter++}`,startTime:new Date,completedStages:0,rolledBack:!1};console.log(`${a?"[DRY RUN] ":""}Starting canary deployment: ${r.name}`),console.log(` Strategy: ${r.stages.length} stages`),console.log(` Auto-promote: ${r.autoPromote}`),console.log(` Auto-rollback: ${r.autoRollback}`),console.log(""),r.status="in_progress";for(let i=0;i<r.stages.length;i++){let o=r.stages[i];if(r.currentStage=i,console.log(`Stage ${i+1}/${r.stages.length}: ${o.name}`),console.log(` Traffic: ${o.trafficPercentage}% canary, ${100-o.trafficPercentage}% baseline`),console.log(` Duration: ${o.durationMinutes} minutes`),!a)r.baselineVersion.weight=100-o.trafficPercentage,r.canaryVersion.weight=o.trafficPercentage;if(!await this.monitorStage(r,o,a)){if(console.log(" ✗ Stage failed - metrics exceeded thresholds"),r.autoRollback)console.log("\\n Rolling back deployment..."),await this.rollback(e,a),n.rolledBack=!0,n.reason="Metrics exceeded thresholds";return n.endTime=new Date,r.status="rolled_back",this.recordDeployment(e,n),n}console.log(" ✓ Stage completed successfully"),n.completedStages++,console.log("")}return r.status="completed",n.success=!0,n.endTime=new Date,console.log("✓ Canary deployment completed successfully"),this.recordDeployment(e,n),n}async monitorStage(e,a,r){if(console.log(" Monitoring metrics..."),r)return console.log(" [SKIPPED - DRY RUN]"),!0;await new Promise((i)=>setTimeout(i,100));let n={baselineErrorRate:Math.random()*0.5,canaryErrorRate:Math.random()*0.8,baselineLatencyP99:200+Math.random()*100,canaryLatencyP99:180+Math.random()*150,baselineRequestCount:Math.floor(Math.random()*1000)+500,canaryRequestCount:Math.floor((Math.random()*1000+500)*a.trafficPercentage/100)};if(e.metrics=n,console.log(` Baseline: ${n.baselineErrorRate.toFixed(2)}% errors, ${n.baselineLatencyP99.toFixed(0)}ms P99`),console.log(` Canary: ${n.canaryErrorRate.toFixed(2)}% errors, ${n.canaryLatencyP99.toFixed(0)}ms P99`),a.alarmThresholds){let{errorRate:i,latencyP99:o}=a.alarmThresholds;if(i&&n.canaryErrorRate>i)return console.log(` ⚠ Error rate exceeded threshold: ${n.canaryErrorRate.toFixed(2)}% > ${i}%`),!1;if(o&&n.canaryLatencyP99>o)return console.log(` ⚠ Latency P99 exceeded threshold: ${n.canaryLatencyP99.toFixed(0)}ms > ${o}ms`),!1}return!0}async rollback(e,a=!1){let r=this.deployments.get(e);if(!r)throw Error(`Deployment not found: ${e}`);if(console.log(`${a?"[DRY RUN] ":""}Rolling back canary deployment: ${r.name}`),!a)r.baselineVersion.weight=100,r.canaryVersion.weight=0,r.status="rolled_back";console.log(" Traffic restored to baseline: 100%")}promoteCanary(e){let a=this.deployments.get(e);if(!a)throw Error(`Deployment not found: ${e}`);console.log(`Promoting canary to baseline: ${a.name}`);let r=a.baselineVersion;a.baselineVersion=a.canaryVersion,a.canaryVersion=r,a.baselineVersion.weight=100,a.canaryVersion.weight=0,a.status="completed",console.log(" Canary promoted successfully")}recordDeployment(e,a){if(!this.deploymentHistory.has(e))this.deploymentHistory.set(e,[]);this.deploymentHistory.get(e).push(a)}getDeployment(e){return this.deployments.get(e)}listDeployments(){return Array.from(this.deployments.values())}getDeploymentHistory(e){return this.deploymentHistory.get(e)||[]}generateLambdaAliasCF(e,a){return{Type:"AWS::Lambda::Alias",Properties:{FunctionName:{Ref:"LambdaFunction"},Name:a,FunctionVersion:e.canaryVersion.version,RoutingConfig:{AdditionalVersionWeights:[{FunctionVersion:e.baselineVersion.version,FunctionWeight:e.baselineVersion.weight/100}]}}}}generateALBListenerRuleCF(e){return{Type:"AWS::ElasticLoadBalancingV2::ListenerRule",Properties:{ListenerArn:{Ref:"LoadBalancerListener"},Priority:1,Conditions:[{Field:"path-pattern",Values:["/*"]}],Actions:[{Type:"forward",ForwardConfig:{TargetGroups:[{TargetGroupArn:e.baselineVersion.targetGroupArn,Weight:e.baselineVersion.weight},{TargetGroupArn:e.canaryVersion.targetGroupArn,Weight:e.canaryVersion.weight}],TargetGroupStickinessConfig:{Enabled:!1}}}]}}}clear(){this.deployments.clear(),this.deploymentHistory.clear(),this.deploymentCounter=0,this.resultCounter=0}}var Mg=new Ro;class Uc{tests=new Map;testCounter=0;createTest(e){let a=`abtest-${Date.now()}-${this.testCounter++}`,r={id:a,...e};return this.tests.set(a,r),r}createSimpleABTest(e){let a=e.variantTrafficPercentage||50;return this.createTest({name:e.name,description:e.description,variants:[{id:"control",name:"Control",description:"Original version",trafficPercentage:100-a,targetGroupArn:e.controlTargetGroupArn,weight:100-a},{id:"variant-a",name:"Variant A",description:"Test version",trafficPercentage:a,targetGroupArn:e.variantTargetGroupArn,weight:a}],routingStrategy:{type:e.stickySession?"cookie":"random",cookieName:e.stickySession?"ab_variant":void 0,stickySession:e.stickySession??!1,sessionDuration:1440},startTime:new Date,status:"draft"})}createMultivariateTest(e){let a=e.variants.reduce((r,n)=>r+n.trafficPercentage,0);if(a!==100)throw Error(`Traffic percentages must sum to 100, got ${a}`);return this.createTest({name:e.name,description:e.description,variants:e.variants.map((r,n)=>({id:`variant-${n}`,name:r.name,description:r.description,trafficPercentage:r.trafficPercentage,targetGroupArn:r.targetGroupArn,weight:r.trafficPercentage})),routingStrategy:e.routingStrategy||{type:"random",stickySession:!1},startTime:new Date,status:"draft"})}createHeaderBasedTest(e){return this.createTest({name:e.name,description:`Route based on ${e.headerName} header`,variants:[{id:"control",name:"Control",trafficPercentage:50,targetGroupArn:e.controlTargetGroupArn,weight:50},{id:"variant-a",name:"Variant A",trafficPercentage:50,targetGroupArn:e.variantTargetGroupArn,weight:50}],routingStrategy:{type:"header",headerName:e.headerName,stickySession:!1},startTime:new Date,status:"draft"})}createGeoBasedTest(e){return this.createTest({name:e.name,description:"Route based on geographic location",variants:[{id:"control",name:"Control (Rest of World)",trafficPercentage:50,targetGroupArn:e.controlTargetGroupArn,weight:50},{id:"variant-a",name:`Variant A (${e.regions.join(", ")})`,trafficPercentage:50,targetGroupArn:e.variantTargetGroupArn,weight:50}],routingStrategy:{type:"geo",stickySession:!0,sessionDuration:1440},startTime:new Date,status:"draft"})}startTest(e){let a=this.tests.get(e);if(!a)throw Error(`Test not found: ${e}`);if(a.status!=="draft"&&a.status!=="paused")throw Error(`Cannot start test in ${a.status} status`);a.status="active",a.startTime=new Date,console.log(`Started A/B test: ${a.name}`),console.log(` Variants: ${a.variants.length}`),a.variants.forEach((r)=>{console.log(` - ${r.name}: ${r.trafficPercentage}%`)})}pauseTest(e){let a=this.tests.get(e);if(!a)throw Error(`Test not found: ${e}`);a.status="paused",console.log(`Paused A/B test: ${a.name}`)}updateTrafficSplit(e,a,r){let n=this.tests.get(e);if(!n)throw Error(`Test not found: ${e}`);let i=n.variants.find((c)=>c.id===a);if(!i)throw Error(`Variant not found: ${a}`);let o=i.trafficPercentage;i.trafficPercentage=r,i.weight=r,console.log(`Updated ${i.name} traffic: ${o}% → ${r}%`)}analyzeResults(e){let a=this.tests.get(e);if(!a)throw Error(`Test not found: ${e}`);if(!a.metrics)a.metrics=this.collectMetrics(a);let r=a.variants[0],n=0;for(let m of a.variants){let p=a.metrics.variants[m.id];if(p&&p.conversionRate>n)n=p.conversionRate,r=m}let i=a.metrics.variants.control||a.metrics.variants[a.variants[0].id],o=a.metrics.variants[r.id],c=(o.conversionRate-i.conversionRate)/i.conversionRate*100,u=100,d=o.requests>u&&i.requests>u&&Math.abs(c)>10;return{testId:e,winningVariant:r.name,confidence:d?95:75,improvement:c,statisticalSignificance:d,metrics:a.metrics,recommendation:this.generateRecommendation(c,d,r.name)}}declareWinner(e,a){let r=this.tests.get(e);if(!r)throw Error(`Test not found: ${e}`);let n=r.variants.find((i)=>i.id===a);if(!n)throw Error(`Variant not found: ${a}`);r.variants.forEach((i)=>{if(i.id===a)i.trafficPercentage=100,i.weight=100;else i.trafficPercentage=0,i.weight=0}),r.status="completed",r.endTime=new Date,r.winner=a,console.log(`Declared winner: ${n.name}`),console.log(` All traffic now routed to ${n.name}`)}collectMetrics(e){let a={},r=0;for(let n of e.variants){let i=Math.floor(Math.random()*1000)+500,o=Math.floor(i*(Math.random()*0.1+0.05)),c=o/i*100;a[n.id]={requests:i,conversions:o,conversionRate:c,averageLatency:150+Math.random()*100,errorRate:Math.random()*0.5,revenue:o*(Math.random()*50+100)},r+=i}return{variants:a,totalRequests:r,startTime:e.startTime,lastUpdated:new Date}}generateRecommendation(e,a,r){if(!a)return"Continue test - sample size too small or no significant difference detected";if(e>20)return`Strong winner detected - ${r} shows ${e.toFixed(1)}% improvement. Recommend deploying to all traffic.`;if(e>10)return`Moderate improvement - ${r} shows ${e.toFixed(1)}% improvement. Consider deploying.`;if(e>0)return`Minor improvement - ${r} shows ${e.toFixed(1)}% improvement. May not be worth the complexity.`;return"No improvement detected - consider reverting to control variant"}getTest(e){return this.tests.get(e)}listTests(){return Array.from(this.tests.values())}generateALBListenerRuleCF(e){return{Type:"AWS::ElasticLoadBalancingV2::ListenerRule",Properties:{ListenerArn:{Ref:"LoadBalancerListener"},Priority:1,Conditions:[{Field:"path-pattern",Values:["/*"]}],Actions:[{Type:"forward",ForwardConfig:{TargetGroups:e.variants.map((a)=>({TargetGroupArn:a.targetGroupArn,Weight:a.weight})),TargetGroupStickinessConfig:{Enabled:e.routingStrategy.stickySession||!1,DurationSeconds:e.routingStrategy.sessionDuration?e.routingStrategy.sessionDuration*60:void 0}}}]}}}generateLambdaEdgeFunction(e){return`'use strict';
|
|
3611
3611
|
|
|
3612
3612
|
exports.handler = (event, _context, _callback) => {
|
|
3613
3613
|
const request = event.Records[0].cf.request;
|
|
@@ -3762,12 +3762,12 @@ exports.handler = async () => {
|
|
|
3762
3762
|
`),o.push(u.version),!a)return console.log("Rolling back previously applied migrations..."),await this.rollbackMigrations(i.reverse(),r),{success:!1,version:u.version,appliedMigrations:[],failedMigrations:o,executionTimeMs:Date.now()-n,error:d instanceof Error?d.message:String(d),rollbackPerformed:!0}}let c=Date.now()-n;return console.log(`${a?"[DRY RUN] ":""}Migration plan completed successfully`),console.log(`Total time: ${c}ms`),{success:!0,version:r.migrations[r.migrations.length-1]?.version||"unknown",appliedMigrations:i,failedMigrations:o,executionTimeMs:c}}async rollbackMigrations(e,a){for(let r of e){let n=a.migrations.find((i)=>i.version===r);if(n)console.log(`Rolling back: ${n.version} - ${n.name}`),n.rolledBackAt=new Date,console.log(`✓ Rolled back
|
|
3763
3763
|
`)}}getMigrationStatus(e){let a=this.plans.get(e);if(!a)throw Error(`Migration plan not found: ${e}`);let r=a.migrations.filter((i)=>i.appliedAt&&!i.rolledBackAt),n=a.migrations.filter((i)=>!i.appliedAt);return{currentVersion:r[r.length-1]?.version||"0.0.0",pendingMigrations:n,appliedMigrations:r,lastMigration:r[r.length-1]}}generateSchemaSQL(e,a,r="postgres"){let n=[],i=[];for(let o of e)switch(o.type){case"add_column":n.push(`ALTER TABLE ${a} ADD COLUMN ${o.columnName} ${o.columnType}${o.nullable===!1?" NOT NULL":""}${o.defaultValue?` DEFAULT ${o.defaultValue}`:""}; `),i.push(`ALTER TABLE ${a} DROP COLUMN ${o.columnName};`);break;case"drop_column":n.push(`ALTER TABLE ${a} DROP COLUMN ${o.columnName};`),i.push(`-- Cannot restore dropped column ${o.columnName}`);break;case"modify_column":if(r==="postgres")n.push(`ALTER TABLE ${a} ALTER COLUMN ${o.columnName} TYPE ${o.newType};`);else n.push(`ALTER TABLE ${a} MODIFY COLUMN ${o.columnName} ${o.newType};`);i.push(`-- Reverting ${o.columnName} type change requires manual intervention`);break;case"add_index":n.push(`CREATE INDEX ${o.indexName} ON ${a} (${(o.columns??[]).join(", ")});`),i.push(`DROP INDEX ${o.indexName};`);break;case"drop_index":n.push(`DROP INDEX ${o.indexName};`),i.push(`-- Cannot restore index ${o.indexName} without schema details`);break}return{up:n.join(`
|
|
3764
3764
|
`),down:i.reverse().join(`
|
|
3765
|
-
`)}}generateChecksum(e){let a=0;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);a=(a<<5)-a+n,a=a&a}return a.toString(16)}validatePlan(e){let a=this.plans.get(e);if(!a)return{valid:!1,errors:["Migration plan not found"]};let r=[],n=new Set;for(let i of a.migrations){if(n.has(i.version))r.push(`Duplicate migration version: ${i.version}`);n.add(i.version)}for(let i of a.migrations)if(!i.down||i.down.trim()==="")r.push(`Migration ${i.version} is missing rollback SQL`);for(let i of a.migrations)if(this.generateChecksum(i.up+i.down)!==i.checksum)r.push(`Migration ${i.version} has invalid checksum`);return{valid:r.length===0,errors:r}}getPlan(e){return this.plans.get(e)}listPlans(){return Array.from(this.plans.values())}getMigration(e){return this.migrations.get(e)}listMigrations(){return Array.from(this.migrations.values())}clear(){this.plans.clear(),this.migrations.clear(),this.planCounter=0,this.migrationCounter=0}}var
|
|
3765
|
+
`)}}generateChecksum(e){let a=0;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);a=(a<<5)-a+n,a=a&a}return a.toString(16)}validatePlan(e){let a=this.plans.get(e);if(!a)return{valid:!1,errors:["Migration plan not found"]};let r=[],n=new Set;for(let i of a.migrations){if(n.has(i.version))r.push(`Duplicate migration version: ${i.version}`);n.add(i.version)}for(let i of a.migrations)if(!i.down||i.down.trim()==="")r.push(`Migration ${i.version} is missing rollback SQL`);for(let i of a.migrations)if(this.generateChecksum(i.up+i.down)!==i.checksum)r.push(`Migration ${i.version} has invalid checksum`);return{valid:r.length===0,errors:r}}getPlan(e){return this.plans.get(e)}listPlans(){return Array.from(this.plans.values())}getMigration(e){return this.migrations.get(e)}listMigrations(){return Array.from(this.migrations.values())}clear(){this.plans.clear(),this.migrations.clear(),this.planCounter=0,this.migrationCounter=0}}var Hg=new zc;class Hc{replicas=new Map;replicationGroups=new Map;proxies=new Map;proxyTargets=new Map;replicaCounter=0;groupCounter=0;proxyCounter=0;targetCounter=0;createReplica(e){let a=`replica-${Date.now()}-${this.replicaCounter++}`,r={id:a,status:"creating",...e};return this.replicas.set(a,r),r}createRDSReplica(e){return this.createReplica({name:e.name,sourceDatabase:e.sourceDatabase,region:e.region||"us-east-1",instanceClass:e.instanceClass||"db.t3.medium",multiAZ:e.multiAZ||!1,autoMinorVersionUpgrade:!0,backupRetentionPeriod:7})}createCrossRegionReplica(e){return this.createReplica({name:e.name,sourceDatabase:e.sourceDatabase,region:e.targetRegion,instanceClass:e.instanceClass||"db.t3.medium",multiAZ:!0,autoMinorVersionUpgrade:!0,backupRetentionPeriod:7})}createReplicationGroup(e){let a=`replication-group-${Date.now()}-${this.groupCounter++}`,r={id:a,...e};return this.replicationGroups.set(a,r),r}createAutoScalingReplicationGroup(e){return this.createReplicationGroup({name:e.name,primaryDatabase:e.primaryDatabase,replicas:[],loadBalancing:e.loadBalancing||{type:"round-robin"},failoverEnabled:!0,autoScaling:{enabled:!0,minReplicas:e.minReplicas,maxReplicas:e.maxReplicas,targetCPU:e.targetCPU||70,scaleUpCooldown:300,scaleDownCooldown:600}})}addReplicaToGroup(e,a){let r=this.replicationGroups.get(e);if(!r)throw Error(`Replication group not found: ${e}`);r.replicas.push(a)}createProxy(e){let a=`rds-proxy-${Date.now()}-${this.proxyCounter++}`,r={id:a,...e};return this.proxies.set(a,r),r}createConnectionPoolProxy(e){return this.createProxy({name:e.name,engineFamily:e.engineFamily,targetDatabase:e.targetDatabase,maxConnectionsPercent:e.maxConnections||100,maxIdleConnectionsPercent:50,connectionBorrowTimeout:120,sessionPinningFilters:["EXCLUDE_VARIABLE_SETS"],requireTLS:!0,idleClientTimeout:1800,vpcSubnetIds:e.vpcSubnetIds,securityGroupIds:e.securityGroupIds,secretArn:e.secretArn})}createServerlessProxy(e){return this.createProxy({name:e.name,engineFamily:e.engineFamily,targetDatabase:e.targetDatabase,maxConnectionsPercent:100,maxIdleConnectionsPercent:10,connectionBorrowTimeout:60,sessionPinningFilters:["EXCLUDE_VARIABLE_SETS"],requireTLS:!0,idleClientTimeout:300,vpcSubnetIds:e.vpcSubnetIds,securityGroupIds:e.securityGroupIds,secretArn:e.secretArn})}addProxyTarget(e){let a=`proxy-target-${Date.now()}-${this.targetCounter++}`,r={id:a,...e};return this.proxyTargets.set(a,r),r}promoteReplica(e){let a=this.replicas.get(e);if(!a)return{success:!1,message:"Replica not found"};if(console.log(`Promoting replica to primary: ${a.name}`),console.log(`Region: ${a.region}`),console.log(`
|
|
3766
3766
|
1. Checking replication lag...`),a.replicationLag&&a.replicationLag>5000)return{success:!1,message:`Replication lag too high: ${a.replicationLag}ms`};return console.log(` Replication lag: ${a.replicationLag||0}ms (acceptable)`),console.log(`
|
|
3767
3767
|
2. Promoting replica to standalone instance...`),console.log(`
|
|
3768
3768
|
3. Updating DNS records...`),console.log(`
|
|
3769
3769
|
4. Updating application configuration...`),console.log(`
|
|
3770
|
-
✓ Promotion completed successfully`),a.status="available",{success:!0,message:"Replica promoted successfully"}}getReplicationLag(e){if(!this.replicas.get(e))throw Error(`Replica not found: ${e}`);return Math.floor(Math.random()*1000)}getReplica(e){return this.replicas.get(e)}listReplicas(){return Array.from(this.replicas.values())}getReplicationGroup(e){return this.replicationGroups.get(e)}listReplicationGroups(){return Array.from(this.replicationGroups.values())}getProxy(e){return this.proxies.get(e)}listProxies(){return Array.from(this.proxies.values())}generateReplicaCF(e){return{Type:"AWS::RDS::DBInstance",Properties:{SourceDBInstanceIdentifier:e.sourceDatabase,DBInstanceIdentifier:e.name,DBInstanceClass:e.instanceClass,MultiAZ:e.multiAZ||!1,AutoMinorVersionUpgrade:e.autoMinorVersionUpgrade??!0,...e.backupRetentionPeriod&&{BackupRetentionPeriod:e.backupRetentionPeriod},...e.preferredBackupWindow&&{PreferredBackupWindow:e.preferredBackupWindow},...e.preferredMaintenanceWindow&&{PreferredMaintenanceWindow:e.preferredMaintenanceWindow}}}}generateProxyCF(e){return{Type:"AWS::RDS::DBProxy",Properties:{DBProxyName:e.name,EngineFamily:e.engineFamily,Auth:[{AuthScheme:"SECRETS",SecretArn:e.secretArn,IAMAuth:"DISABLED"}],RoleArn:{"Fn::GetAtt":["RDSProxyRole","Arn"]},VpcSubnetIds:e.vpcSubnetIds,VpcSecurityGroupIds:e.securityGroupIds,RequireTLS:e.requireTLS??!0,IdleClientTimeout:e.idleClientTimeout||1800,...e.maxConnectionsPercent&&{MaxConnectionsPercent:e.maxConnectionsPercent},...e.maxIdleConnectionsPercent&&{MaxIdleConnectionsPercent:e.maxIdleConnectionsPercent},...e.connectionBorrowTimeout&&{ConnectionBorrowTimeout:e.connectionBorrowTimeout}}}}generateProxyTargetCF(e,a){return{Type:"AWS::RDS::DBProxyTargetGroup",Properties:{DBProxyName:a.name,TargetGroupName:"default",DBInstanceIdentifiers:[e.targetArn],ConnectionPoolConfig:{MaxConnectionsPercent:100,MaxIdleConnectionsPercent:50,ConnectionBorrowTimeout:120}}}}generateProxyRoleCF(){return{Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"rds.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"RDSProxySecretsPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["secretsmanager:GetSecretValue","secretsmanager:DescribeSecret"],Resource:"arn:aws:secretsmanager:*:*:secret:*"},{Effect:"Allow",Action:["kms:Decrypt"],Resource:"arn:aws:kms:*:*:key/*",Condition:{StringEquals:{"kms:ViaService":"secretsmanager.*.amazonaws.com"}}}]}}]}}}clear(){this.replicas.clear(),this.replicationGroups.clear(),this.proxies.clear(),this.proxyTargets.clear(),this.replicaCounter=0,this.groupCounter=0,this.proxyCounter=0,this.targetCounter=0}}var Hg=new qc;class Hc{insights=new Map;slowQueryLogs=new Map;queryMetrics=new Map;reports=new Map;indexRecommendations=new Map;insightsCounter=0;logCounter=0;metricCounter=0;reportCounter=0;recommendationCounter=0;enablePerformanceInsights(e){let a=`pi-${Date.now()}-${this.insightsCounter++}`,r={id:a,name:e.name,databaseIdentifier:e.databaseIdentifier,enabled:!0,retentionPeriod:e.retentionPeriod||7,kmsKeyId:e.kmsKeyId};return this.insights.set(a,r),r}enableSlowQueryLog(e){let a=`slow-query-${Date.now()}-${this.logCounter++}`,r={id:a,name:e.name,databaseIdentifier:e.databaseIdentifier,enabled:!0,logDestination:e.logDestination,cloudwatchLogGroup:e.cloudwatchLogGroup,s3Bucket:e.s3Bucket,s3Prefix:e.s3Bucket?"slow-queries/":void 0,minExecutionTime:e.minExecutionTime||1000};return this.slowQueryLogs.set(a,r),r}recordQueryMetric(e){let a=`metric-${Date.now()}-${this.metricCounter++}`,r={id:a,timestamp:new Date,...e};return this.queryMetrics.set(a,r),r}generatePerformanceReport(e){let a=`report-${Date.now()}-${this.reportCounter++}`,r={avgCPU:Math.random()*60+20,maxCPU:Math.random()*30+70,avgConnections:Math.floor(Math.random()*50+10),maxConnections:Math.floor(Math.random()*50+100),avgReadIOPS:Math.floor(Math.random()*1000+500),avgWriteIOPS:Math.floor(Math.random()*500+200),avgReadThroughput:Math.random()*50+10,avgWriteThroughput:Math.random()*20+5,avgReadLatency:Math.random()*5+1,avgWriteLatency:Math.random()*8+2,cacheHitRatio:Math.random()*10+90,deadlocks:Math.floor(Math.random()*5),longRunningTransactions:Math.floor(Math.random()*10)},n=Array.from(this.queryMetrics.values()),i=n.sort((d,m)=>m.executionCount-d.executionCount).slice(0,10),o=n.filter((d)=>d.avgExecutionTime>1000).sort((d,m)=>m.avgExecutionTime-d.avgExecutionTime).slice(0,10),c=this.generateRecommendations(r,o),u={id:a,name:e.name,databaseIdentifier:e.databaseIdentifier,reportType:e.reportType,metrics:r,topQueries:i,slowQueries:o,recommendations:c,generatedAt:new Date};return this.reports.set(a,u),u}generateRecommendations(e,a){let r=[];if(e.avgCPU>70)r.push({type:"scaling",severity:"high",title:"High CPU Usage",description:`Average CPU usage is ${e.avgCPU.toFixed(1)}%, which is above the recommended threshold of 70%.`,impact:"Performance degradation, increased latency, potential timeouts",effort:"medium"});if(e.cacheHitRatio<95)r.push({type:"configuration",severity:"medium",title:"Low Cache Hit Ratio",description:`Cache hit ratio is ${e.cacheHitRatio.toFixed(1)}%. Consider increasing buffer pool size.`,impact:"Increased disk I/O, slower query performance",effort:"low"});if(e.deadlocks>0)r.push({type:"query",severity:"medium",title:"Deadlocks Detected",description:`${e.deadlocks} deadlock(s) detected. Review transaction isolation levels and query patterns.`,impact:"Transaction failures, application errors",effort:"high"});if(a.length>0)r.push({type:"index",severity:"high",title:"Slow Queries Detected",description:`${a.length} slow queries detected. Consider adding indexes or optimizing queries.`,impact:"High latency, poor user experience",effort:"medium"});if(e.avgReadLatency>10||e.avgWriteLatency>10)r.push({type:"scaling",severity:"high",title:"High I/O Latency",description:"Read or write latency is high. Consider upgrading to Provisioned IOPS or moving to a larger instance.",impact:"Slow query execution, application timeouts",effort:"medium"});return r}analyzeQuery(e){let a=`analysis-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,r=[{id:1,operation:"Seq Scan",table:"users",rows:1e4,cost:850.5,children:[]}],n=[];if(e.toLowerCase().includes("select *"))n.push({type:"full_table_scan",severity:"warning",description:"Query selects all columns. Consider selecting only required columns."});if(!e.toLowerCase().includes("where")&&e.toLowerCase().includes("select"))n.push({type:"full_table_scan",severity:"critical",description:"Query has no WHERE clause and may scan entire table."});return{id:a,queryId:a,sql:e,executionPlan:r,bottlenecks:n,recommendations:["Add appropriate indexes on WHERE clause columns","Consider using EXPLAIN ANALYZE to get actual execution statistics","Review and optimize JOIN conditions"],estimatedCost:r[0].cost}}recommendIndex(e){let a=`index-rec-${Date.now()}-${this.recommendationCounter++}`,r=`idx_${e.tableName}_${e.columns.join("_")}`,n={id:a,tableName:e.tableName,columns:e.columns,reason:e.reason,estimatedImprovement:e.estimatedImprovement||50,estimatedSize:e.columns.length*10,createSQL:`CREATE INDEX ${r} ON ${e.tableName} (${e.columns.join(", ")});`};return this.indexRecommendations.set(a,n),n}getInsights(e){return this.insights.get(e)}listInsights(){return Array.from(this.insights.values())}getSlowQueryLog(e){return this.slowQueryLogs.get(e)}listSlowQueryLogs(){return Array.from(this.slowQueryLogs.values())}getReport(e){return this.reports.get(e)}listReports(){return Array.from(this.reports.values())}listIndexRecommendations(){return Array.from(this.indexRecommendations.values())}generatePerformanceInsightsCF(e){return{EnablePerformanceInsights:e.enabled,PerformanceInsightsRetentionPeriod:e.retentionPeriod,...e.kmsKeyId&&{PerformanceInsightsKMSKeyId:e.kmsKeyId}}}generateSlowQueryAlarmCF(e){return{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:e.alarmName,AlarmDescription:"Alert when slow queries exceed threshold",MetricName:"SlowQueryCount",Namespace:"AWS/RDS",Statistic:"Sum",Period:300,EvaluationPeriods:1,Threshold:e.threshold,ComparisonOperator:"GreaterThanThreshold",...e.snsTopicArn&&{AlarmActions:[e.snsTopicArn]}}}}clear(){this.insights.clear(),this.slowQueryLogs.clear(),this.queryMetrics.clear(),this.reports.clear(),this.indexRecommendations.clear(),this.insightsCounter=0,this.logCounter=0,this.metricCounter=0,this.reportCounter=0,this.recommendationCounter=0}}var Wg=new Hc;class Wc{users=new Map;roles=new Map;audits=new Map;userCounter=0;roleCounter=0;auditCounter=0;createUser(e){let a=`db-user-${Date.now()}-${this.userCounter++}`,r={id:a,createdAt:new Date,...e};return this.users.set(a,r),r}createReadOnlyUser(e){let a=e.tables?e.tables.map((r)=>({database:e.database,table:r,privileges:["SELECT"]})):[{database:e.database,privileges:["SELECT"]}];return this.createUser({username:e.username,database:e.database,privileges:a,passwordSecretArn:e.passwordSecretArn,rotationEnabled:!0,rotationDays:90})}createReadWriteUser(e){let a=e.tables?e.tables.map((r)=>({database:e.database,table:r,privileges:["SELECT","INSERT","UPDATE","DELETE"]})):[{database:e.database,privileges:["SELECT","INSERT","UPDATE","DELETE"]}];return this.createUser({username:e.username,database:e.database,privileges:a,passwordSecretArn:e.passwordSecretArn,rotationEnabled:!0,rotationDays:60})}createAdminUser(e){return this.createUser({username:e.username,database:e.database,privileges:[{database:e.database,privileges:["ALL"]}],passwordSecretArn:e.passwordSecretArn,rotationEnabled:!0,rotationDays:30})}createApplicationUser(e){let a=e.tables.map((r)=>({database:e.database,table:r.name,privileges:r.privileges}));return this.createUser({username:e.username,database:e.database,privileges:a,passwordSecretArn:e.passwordSecretArn,rotationEnabled:!0,rotationDays:90})}createRole(e){let a=`role-${Date.now()}-${this.roleCounter++}`,r={id:a,users:[],...e};return this.roles.set(a,r),r}assignUserToRole(e,a){let r=this.users.get(e),n=this.roles.get(a);if(!r)throw Error(`User not found: ${e}`);if(!n)throw Error(`Role not found: ${a}`);n.users.push(e);for(let i of n.privileges){let o=r.privileges.find((c)=>c.database===i.database&&c.table===i.table);if(o)o.privileges=Array.from(new Set([...o.privileges,...i.privileges]));else r.privileges.push({...i})}}grantPrivileges(e,a){let r=this.users.get(e);if(!r)return{success:!1,message:"User not found"};for(let n of a){let i=r.privileges.find((o)=>o.database===n.database&&o.table===n.table);if(i)i.privileges=Array.from(new Set([...i.privileges,...n.privileges]));else r.privileges.push(n)}return this.auditAccess({username:r.username,action:"GRANT",database:a[0]?.database,table:a[0]?.table,success:!0}),{success:!0,message:"Privileges granted successfully"}}revokePrivileges(e,a){let r=this.users.get(e);if(!r)return{success:!1,message:"User not found"};for(let n of a){let i=r.privileges.findIndex((o)=>o.database===n.database&&o.table===n.table);if(i!==-1){let o=r.privileges[i];if(o.privileges=o.privileges.filter((c)=>!n.privileges.includes(c)),o.privileges.length===0)r.privileges.splice(i,1)}}return this.auditAccess({username:r.username,action:"REVOKE",database:a[0]?.database,table:a[0]?.table,success:!0}),{success:!0,message:"Privileges revoked successfully"}}rotatePassword(e){let a=this.users.get(e);if(!a)return{success:!1};let r=`arn:aws:secretsmanager:us-east-1:123456789012:secret:db-${a.username}-${Date.now()}`;return a.passwordSecretArn=r,a.lastRotated=new Date,console.log(`Password rotated for user: ${a.username}`),{success:!0,newSecretArn:r}}needsPasswordRotation(e){let a=this.users.get(e);if(!a||!a.rotationEnabled||!a.lastRotated||!a.rotationDays)return!1;return(Date.now()-a.lastRotated.getTime())/86400000>=a.rotationDays}auditAccess(e){let a=`audit-${Date.now()}-${this.auditCounter++}`,r={id:a,timestamp:new Date,...e};return this.audits.set(a,r),r}getUserAccessHistory(e,a=100){return Array.from(this.audits.values()).filter((r)=>r.username===e).sort((r,n)=>n.timestamp.getTime()-r.timestamp.getTime()).slice(0,a)}getFailedLoginAttempts(e,a=24){let r=Date.now()-a*60*60*1000;return Array.from(this.audits.values()).filter((n)=>n.username===e&&n.action==="LOGIN"&&!n.success&&n.timestamp.getTime()>r)}generateCreateUserSQL(e,a="postgres"){let r=[];if(a==="postgres"){r.push(`CREATE USER ${e.username} WITH PASSWORD '${e.passwordSecretArn}';`);for(let n of e.privileges)if(n.privileges.includes("ALL"))r.push(`GRANT ALL PRIVILEGES ON DATABASE ${n.database} TO ${e.username};`);else{let i=n.privileges.join(", ");if(n.table)r.push(`GRANT ${i} ON ${n.database}.${n.table} TO ${e.username};`);else r.push(`GRANT ${i} ON DATABASE ${n.database} TO ${e.username};`)}}else{r.push(`CREATE USER '${e.username}'@'%' IDENTIFIED BY '${e.passwordSecretArn}';`);for(let n of e.privileges){let i=n.privileges.includes("ALL")?"ALL PRIVILEGES":n.privileges.join(", "),o=n.table?`${n.database}.${n.table}`:`${n.database}.*`;r.push(`GRANT ${i} ON ${o} TO '${e.username}'@'%';`)}r.push("FLUSH PRIVILEGES;")}return r.join(`
|
|
3770
|
+
✓ Promotion completed successfully`),a.status="available",{success:!0,message:"Replica promoted successfully"}}getReplicationLag(e){if(!this.replicas.get(e))throw Error(`Replica not found: ${e}`);return Math.floor(Math.random()*1000)}getReplica(e){return this.replicas.get(e)}listReplicas(){return Array.from(this.replicas.values())}getReplicationGroup(e){return this.replicationGroups.get(e)}listReplicationGroups(){return Array.from(this.replicationGroups.values())}getProxy(e){return this.proxies.get(e)}listProxies(){return Array.from(this.proxies.values())}generateReplicaCF(e){return{Type:"AWS::RDS::DBInstance",Properties:{SourceDBInstanceIdentifier:e.sourceDatabase,DBInstanceIdentifier:e.name,DBInstanceClass:e.instanceClass,MultiAZ:e.multiAZ||!1,AutoMinorVersionUpgrade:e.autoMinorVersionUpgrade??!0,...e.backupRetentionPeriod&&{BackupRetentionPeriod:e.backupRetentionPeriod},...e.preferredBackupWindow&&{PreferredBackupWindow:e.preferredBackupWindow},...e.preferredMaintenanceWindow&&{PreferredMaintenanceWindow:e.preferredMaintenanceWindow}}}}generateProxyCF(e){return{Type:"AWS::RDS::DBProxy",Properties:{DBProxyName:e.name,EngineFamily:e.engineFamily,Auth:[{AuthScheme:"SECRETS",SecretArn:e.secretArn,IAMAuth:"DISABLED"}],RoleArn:{"Fn::GetAtt":["RDSProxyRole","Arn"]},VpcSubnetIds:e.vpcSubnetIds,VpcSecurityGroupIds:e.securityGroupIds,RequireTLS:e.requireTLS??!0,IdleClientTimeout:e.idleClientTimeout||1800,...e.maxConnectionsPercent&&{MaxConnectionsPercent:e.maxConnectionsPercent},...e.maxIdleConnectionsPercent&&{MaxIdleConnectionsPercent:e.maxIdleConnectionsPercent},...e.connectionBorrowTimeout&&{ConnectionBorrowTimeout:e.connectionBorrowTimeout}}}}generateProxyTargetCF(e,a){return{Type:"AWS::RDS::DBProxyTargetGroup",Properties:{DBProxyName:a.name,TargetGroupName:"default",DBInstanceIdentifiers:[e.targetArn],ConnectionPoolConfig:{MaxConnectionsPercent:100,MaxIdleConnectionsPercent:50,ConnectionBorrowTimeout:120}}}}generateProxyRoleCF(){return{Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"rds.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"RDSProxySecretsPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["secretsmanager:GetSecretValue","secretsmanager:DescribeSecret"],Resource:"arn:aws:secretsmanager:*:*:secret:*"},{Effect:"Allow",Action:["kms:Decrypt"],Resource:"arn:aws:kms:*:*:key/*",Condition:{StringEquals:{"kms:ViaService":"secretsmanager.*.amazonaws.com"}}}]}}]}}}clear(){this.replicas.clear(),this.replicationGroups.clear(),this.proxies.clear(),this.proxyTargets.clear(),this.replicaCounter=0,this.groupCounter=0,this.proxyCounter=0,this.targetCounter=0}}var qg=new Hc;class qc{insights=new Map;slowQueryLogs=new Map;queryMetrics=new Map;reports=new Map;indexRecommendations=new Map;insightsCounter=0;logCounter=0;metricCounter=0;reportCounter=0;recommendationCounter=0;enablePerformanceInsights(e){let a=`pi-${Date.now()}-${this.insightsCounter++}`,r={id:a,name:e.name,databaseIdentifier:e.databaseIdentifier,enabled:!0,retentionPeriod:e.retentionPeriod||7,kmsKeyId:e.kmsKeyId};return this.insights.set(a,r),r}enableSlowQueryLog(e){let a=`slow-query-${Date.now()}-${this.logCounter++}`,r={id:a,name:e.name,databaseIdentifier:e.databaseIdentifier,enabled:!0,logDestination:e.logDestination,cloudwatchLogGroup:e.cloudwatchLogGroup,s3Bucket:e.s3Bucket,s3Prefix:e.s3Bucket?"slow-queries/":void 0,minExecutionTime:e.minExecutionTime||1000};return this.slowQueryLogs.set(a,r),r}recordQueryMetric(e){let a=`metric-${Date.now()}-${this.metricCounter++}`,r={id:a,timestamp:new Date,...e};return this.queryMetrics.set(a,r),r}generatePerformanceReport(e){let a=`report-${Date.now()}-${this.reportCounter++}`,r={avgCPU:Math.random()*60+20,maxCPU:Math.random()*30+70,avgConnections:Math.floor(Math.random()*50+10),maxConnections:Math.floor(Math.random()*50+100),avgReadIOPS:Math.floor(Math.random()*1000+500),avgWriteIOPS:Math.floor(Math.random()*500+200),avgReadThroughput:Math.random()*50+10,avgWriteThroughput:Math.random()*20+5,avgReadLatency:Math.random()*5+1,avgWriteLatency:Math.random()*8+2,cacheHitRatio:Math.random()*10+90,deadlocks:Math.floor(Math.random()*5),longRunningTransactions:Math.floor(Math.random()*10)},n=Array.from(this.queryMetrics.values()),i=n.sort((d,m)=>m.executionCount-d.executionCount).slice(0,10),o=n.filter((d)=>d.avgExecutionTime>1000).sort((d,m)=>m.avgExecutionTime-d.avgExecutionTime).slice(0,10),c=this.generateRecommendations(r,o),u={id:a,name:e.name,databaseIdentifier:e.databaseIdentifier,reportType:e.reportType,metrics:r,topQueries:i,slowQueries:o,recommendations:c,generatedAt:new Date};return this.reports.set(a,u),u}generateRecommendations(e,a){let r=[];if(e.avgCPU>70)r.push({type:"scaling",severity:"high",title:"High CPU Usage",description:`Average CPU usage is ${e.avgCPU.toFixed(1)}%, which is above the recommended threshold of 70%.`,impact:"Performance degradation, increased latency, potential timeouts",effort:"medium"});if(e.cacheHitRatio<95)r.push({type:"configuration",severity:"medium",title:"Low Cache Hit Ratio",description:`Cache hit ratio is ${e.cacheHitRatio.toFixed(1)}%. Consider increasing buffer pool size.`,impact:"Increased disk I/O, slower query performance",effort:"low"});if(e.deadlocks>0)r.push({type:"query",severity:"medium",title:"Deadlocks Detected",description:`${e.deadlocks} deadlock(s) detected. Review transaction isolation levels and query patterns.`,impact:"Transaction failures, application errors",effort:"high"});if(a.length>0)r.push({type:"index",severity:"high",title:"Slow Queries Detected",description:`${a.length} slow queries detected. Consider adding indexes or optimizing queries.`,impact:"High latency, poor user experience",effort:"medium"});if(e.avgReadLatency>10||e.avgWriteLatency>10)r.push({type:"scaling",severity:"high",title:"High I/O Latency",description:"Read or write latency is high. Consider upgrading to Provisioned IOPS or moving to a larger instance.",impact:"Slow query execution, application timeouts",effort:"medium"});return r}analyzeQuery(e){let a=`analysis-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,r=[{id:1,operation:"Seq Scan",table:"users",rows:1e4,cost:850.5,children:[]}],n=[];if(e.toLowerCase().includes("select *"))n.push({type:"full_table_scan",severity:"warning",description:"Query selects all columns. Consider selecting only required columns."});if(!e.toLowerCase().includes("where")&&e.toLowerCase().includes("select"))n.push({type:"full_table_scan",severity:"critical",description:"Query has no WHERE clause and may scan entire table."});return{id:a,queryId:a,sql:e,executionPlan:r,bottlenecks:n,recommendations:["Add appropriate indexes on WHERE clause columns","Consider using EXPLAIN ANALYZE to get actual execution statistics","Review and optimize JOIN conditions"],estimatedCost:r[0].cost}}recommendIndex(e){let a=`index-rec-${Date.now()}-${this.recommendationCounter++}`,r=`idx_${e.tableName}_${e.columns.join("_")}`,n={id:a,tableName:e.tableName,columns:e.columns,reason:e.reason,estimatedImprovement:e.estimatedImprovement||50,estimatedSize:e.columns.length*10,createSQL:`CREATE INDEX ${r} ON ${e.tableName} (${e.columns.join(", ")});`};return this.indexRecommendations.set(a,n),n}getInsights(e){return this.insights.get(e)}listInsights(){return Array.from(this.insights.values())}getSlowQueryLog(e){return this.slowQueryLogs.get(e)}listSlowQueryLogs(){return Array.from(this.slowQueryLogs.values())}getReport(e){return this.reports.get(e)}listReports(){return Array.from(this.reports.values())}listIndexRecommendations(){return Array.from(this.indexRecommendations.values())}generatePerformanceInsightsCF(e){return{EnablePerformanceInsights:e.enabled,PerformanceInsightsRetentionPeriod:e.retentionPeriod,...e.kmsKeyId&&{PerformanceInsightsKMSKeyId:e.kmsKeyId}}}generateSlowQueryAlarmCF(e){return{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:e.alarmName,AlarmDescription:"Alert when slow queries exceed threshold",MetricName:"SlowQueryCount",Namespace:"AWS/RDS",Statistic:"Sum",Period:300,EvaluationPeriods:1,Threshold:e.threshold,ComparisonOperator:"GreaterThanThreshold",...e.snsTopicArn&&{AlarmActions:[e.snsTopicArn]}}}}clear(){this.insights.clear(),this.slowQueryLogs.clear(),this.queryMetrics.clear(),this.reports.clear(),this.indexRecommendations.clear(),this.insightsCounter=0,this.logCounter=0,this.metricCounter=0,this.reportCounter=0,this.recommendationCounter=0}}var Wg=new qc;class Wc{users=new Map;roles=new Map;audits=new Map;userCounter=0;roleCounter=0;auditCounter=0;createUser(e){let a=`db-user-${Date.now()}-${this.userCounter++}`,r={id:a,createdAt:new Date,...e};return this.users.set(a,r),r}createReadOnlyUser(e){let a=e.tables?e.tables.map((r)=>({database:e.database,table:r,privileges:["SELECT"]})):[{database:e.database,privileges:["SELECT"]}];return this.createUser({username:e.username,database:e.database,privileges:a,passwordSecretArn:e.passwordSecretArn,rotationEnabled:!0,rotationDays:90})}createReadWriteUser(e){let a=e.tables?e.tables.map((r)=>({database:e.database,table:r,privileges:["SELECT","INSERT","UPDATE","DELETE"]})):[{database:e.database,privileges:["SELECT","INSERT","UPDATE","DELETE"]}];return this.createUser({username:e.username,database:e.database,privileges:a,passwordSecretArn:e.passwordSecretArn,rotationEnabled:!0,rotationDays:60})}createAdminUser(e){return this.createUser({username:e.username,database:e.database,privileges:[{database:e.database,privileges:["ALL"]}],passwordSecretArn:e.passwordSecretArn,rotationEnabled:!0,rotationDays:30})}createApplicationUser(e){let a=e.tables.map((r)=>({database:e.database,table:r.name,privileges:r.privileges}));return this.createUser({username:e.username,database:e.database,privileges:a,passwordSecretArn:e.passwordSecretArn,rotationEnabled:!0,rotationDays:90})}createRole(e){let a=`role-${Date.now()}-${this.roleCounter++}`,r={id:a,users:[],...e};return this.roles.set(a,r),r}assignUserToRole(e,a){let r=this.users.get(e),n=this.roles.get(a);if(!r)throw Error(`User not found: ${e}`);if(!n)throw Error(`Role not found: ${a}`);n.users.push(e);for(let i of n.privileges){let o=r.privileges.find((c)=>c.database===i.database&&c.table===i.table);if(o)o.privileges=Array.from(new Set([...o.privileges,...i.privileges]));else r.privileges.push({...i})}}grantPrivileges(e,a){let r=this.users.get(e);if(!r)return{success:!1,message:"User not found"};for(let n of a){let i=r.privileges.find((o)=>o.database===n.database&&o.table===n.table);if(i)i.privileges=Array.from(new Set([...i.privileges,...n.privileges]));else r.privileges.push(n)}return this.auditAccess({username:r.username,action:"GRANT",database:a[0]?.database,table:a[0]?.table,success:!0}),{success:!0,message:"Privileges granted successfully"}}revokePrivileges(e,a){let r=this.users.get(e);if(!r)return{success:!1,message:"User not found"};for(let n of a){let i=r.privileges.findIndex((o)=>o.database===n.database&&o.table===n.table);if(i!==-1){let o=r.privileges[i];if(o.privileges=o.privileges.filter((c)=>!n.privileges.includes(c)),o.privileges.length===0)r.privileges.splice(i,1)}}return this.auditAccess({username:r.username,action:"REVOKE",database:a[0]?.database,table:a[0]?.table,success:!0}),{success:!0,message:"Privileges revoked successfully"}}rotatePassword(e){let a=this.users.get(e);if(!a)return{success:!1};let r=`arn:aws:secretsmanager:us-east-1:123456789012:secret:db-${a.username}-${Date.now()}`;return a.passwordSecretArn=r,a.lastRotated=new Date,console.log(`Password rotated for user: ${a.username}`),{success:!0,newSecretArn:r}}needsPasswordRotation(e){let a=this.users.get(e);if(!a||!a.rotationEnabled||!a.lastRotated||!a.rotationDays)return!1;return(Date.now()-a.lastRotated.getTime())/86400000>=a.rotationDays}auditAccess(e){let a=`audit-${Date.now()}-${this.auditCounter++}`,r={id:a,timestamp:new Date,...e};return this.audits.set(a,r),r}getUserAccessHistory(e,a=100){return Array.from(this.audits.values()).filter((r)=>r.username===e).sort((r,n)=>n.timestamp.getTime()-r.timestamp.getTime()).slice(0,a)}getFailedLoginAttempts(e,a=24){let r=Date.now()-a*60*60*1000;return Array.from(this.audits.values()).filter((n)=>n.username===e&&n.action==="LOGIN"&&!n.success&&n.timestamp.getTime()>r)}generateCreateUserSQL(e,a="postgres"){let r=[];if(a==="postgres"){r.push(`CREATE USER ${e.username} WITH PASSWORD '${e.passwordSecretArn}';`);for(let n of e.privileges)if(n.privileges.includes("ALL"))r.push(`GRANT ALL PRIVILEGES ON DATABASE ${n.database} TO ${e.username};`);else{let i=n.privileges.join(", ");if(n.table)r.push(`GRANT ${i} ON ${n.database}.${n.table} TO ${e.username};`);else r.push(`GRANT ${i} ON DATABASE ${n.database} TO ${e.username};`)}}else{r.push(`CREATE USER '${e.username}'@'%' IDENTIFIED BY '${e.passwordSecretArn}';`);for(let n of e.privileges){let i=n.privileges.includes("ALL")?"ALL PRIVILEGES":n.privileges.join(", "),o=n.table?`${n.database}.${n.table}`:`${n.database}.*`;r.push(`GRANT ${i} ON ${o} TO '${e.username}'@'%';`)}r.push("FLUSH PRIVILEGES;")}return r.join(`
|
|
3771
3771
|
`)}getUser(e){return this.users.get(e)}listUsers(){return Array.from(this.users.values())}getRole(e){return this.roles.get(e)}listRoles(){return Array.from(this.roles.values())}clear(){this.users.clear(),this.roles.clear(),this.audits.clear(),this.userCounter=0,this.roleCounter=0,this.auditCounter=0}}var Gg=new Wc;class Gc{rotations=new Map;schedules=new Map;rotationCounter=0;scheduleCounter=0;createRotation(e){let a=`rotation-${Date.now()}-${this.rotationCounter++}`,r={id:a,...e};return this.rotations.set(a,r),r}enableRDSRotation(e){let a=this.createRotation({secretId:e.secretId,secretType:"rds_credentials",rotationEnabled:!0,rotationDays:e.rotationDays||30,rotationLambdaArn:this.generateRDSRotationLambdaArn(e.engine)});return a.nextRotation=new Date(Date.now()+a.rotationDays*24*60*60*1000),a}enableAPIKeyRotation(e){return this.createRotation({secretId:e.secretId,secretType:"api_key",rotationEnabled:!0,rotationDays:e.rotationDays||90,rotationLambdaArn:e.rotationLambdaArn})}enableOAuthRotation(e){return this.createRotation({secretId:e.secretId,secretType:"oauth_token",rotationEnabled:!0,rotationDays:e.rotationDays||60,rotationLambdaArn:e.rotationLambdaArn})}enableSSHKeyRotation(e){return this.createRotation({secretId:e.secretId,secretType:"ssh_key",rotationEnabled:!0,rotationDays:e.rotationDays||180,rotationLambdaArn:e.rotationLambdaArn})}createSchedule(e){let a=`schedule-${Date.now()}-${this.scheduleCounter++}`,r={id:a,...e};return this.schedules.set(a,r),r}async executeRotation(e){let a=this.rotations.get(e);if(!a)throw Error(`Rotation not found: ${e}`);console.log(`
|
|
3772
3772
|
Executing rotation for secret: ${a.secretId}`),console.log(`Secret type: ${a.secretType}`),console.log(`Rotation interval: ${a.rotationDays} days`);try{console.log(`
|
|
3773
3773
|
Rotation steps:`),console.log("1. Creating new secret version...");let r=`v${Date.now()}`;console.log("2. Testing new credentials..."),console.log("3. Updating application references..."),console.log("4. Marking previous version as deprecated...");let n=a.versionStages?.[0]||"v1";return console.log("5. Finalizing rotation..."),a.lastRotated=new Date,a.nextRotation=new Date(Date.now()+a.rotationDays*24*60*60*1000),console.log(`
|
|
@@ -7283,7 +7283,7 @@ export const queue = __handlers.queue
|
|
|
7283
7283
|
export const cli = __handlers.cli
|
|
7284
7284
|
`}var $i=["adapter.ts","recursion.ts","auto-recursion.ts"];function Li(){return Ie(Ri(ki(import.meta.url)),"runtime")}function eu(e,a,r){for(let n of e??[])r?.(`build: ${n}`),Ci(n,{stdio:"inherit",cwd:a})}function Po(e){return Ti("sha256").update(e).digest("hex")}function Ys(e,a,r){return`deployments/${e}/${a}/${r}.zip`}async function sn(e){let a=Di(e.projectRoot??process.cwd()),{app:r}=e;if(!e.skipBuild)eu(r.build,a,e.onStep);let n=r.entry;if(!n)throw Error("serverless app: `entry` is required to package a Node/Bun application");let i=Ni(n)?n:Ie(a,n),o=wi(Ie(Ii(),"tscloud-pkg-"));try{for(let h of $i)vi(Ie(Li(),h),Ie(o,h));let c=Ie(o,"bootstrap.ts");Pi(c,Zd({entryImport:i,adapterImport:"./adapter"})),e.onStep?.("bundling application");let u=await Bun.build({entrypoints:[c],target:r.kind==="bun"?"bun":"node",format:"esm",minify:!1,sourcemap:"none"});if(!u.success){let h=u.logs.map((y)=>String(y)).join(`
|
|
7285
7285
|
`);throw Error(`serverless app bundle failed:
|
|
7286
|
-
${h}`)}let d=u.outputs[0],m=Buffer.from(await d.arrayBuffer()),p="index",g=Si([{name:`${p}.mjs`,data:m}]);return{zip:g,bundle:m,sha256:Po(g),handlerFile:p,handlers:{http:r.handlers?.http??`${p}.http`,queue:r.handlers?.queue??`${p}.queue`,cli:r.handlers?.cli??`${p}.cli`},bundleBytes:m.length}}finally{Ei(o,{recursive:!0,force:!0})}}var tu=["18","20","22"];function Mi(e){if(!e)return"22";let a=String(e).match(/(\d+)/);return a?a[1]:"22"}function No(e){let a=e.kind??"node";if(a==="php")return{lambdaRuntime:"provided.al2023",kind:"php",version:e.phpVersion??"8.3",usesLayer:!0,layerKind:"php",layerEnvVar:"TSCLOUD_PHP_LAYER_ARN"};if(a==="bun")return{lambdaRuntime:"provided.al2023",kind:"bun",version:e.runtimeVersion??"latest",usesLayer:!0,layerKind:"bun",layerEnvVar:"TSCLOUD_BUN_LAYER_ARN"};let r=Mi(e.runtimeVersion);if(e.runtime!=="provided.al2023"&&tu.includes(r))return{lambdaRuntime:e.runtime&&e.runtime.startsWith("nodejs")?e.runtime:`nodejs${r}.x`,kind:"node",version:r,usesLayer:!1};return{lambdaRuntime:"provided.al2023",kind:"node",version:r,usesLayer:!0,layerKind:"node",layerEnvVar:"TSCLOUD_NODE_LAYER_ARN"}}function Vt(e,a,r){if(e.queues===!1)return[];if(e.queues===void 0||e.queues===!0)return[{name:`${a}-${r}-default`}];return e.queues.map((n)=>{if(typeof n==="string")return{name:`${a}-${r}-${n}`};let[i,o]=Object.entries(n)[0];return{name:`${a}-${r}-${i}`,concurrency:o}})}function Zs(e,a,r){return Vt(e,a,r).map((n)=>n.name)}function ea(e){let{app:a,environment:r,handlers:n}=e,i=e.config.project.slug,o=No(a).lambdaRuntime,c=a.architecture??"x86_64",u=e.config.project.region,d={http:`${i}-${r}-http`,queue:`${i}-${r}-queue`,cli:`${i}-${r}-cli`};if(a.gatewayVersion===1)throw Error("serverless app: `gatewayVersion: 1` (REST API) is not supported — ts-cloud uses API Gateway HTTP API (v2). Remove `gatewayVersion` or set it to 2.");let m=Vt(a,i,r),p=m.map((M)=>M.name),g=p.length>0,h=a.logRetention??14,y=a.packaging==="image";if(y&&a.lambdaInsights)throw Error("serverless app: `lambdaInsights` layer attachment is only supported for zip packaging. Container images must install the Lambda Insights extension in the image.");let f=(a.scheduler??"on")!=="off",b=(a.cache?.driver??"dynamodb")==="dynamodb",v=Boolean(a.assets),w=bo(i,r),R=a.tmpStorage??512,T={},N={},I=[{PolicyName:"tscloud-serverless-app",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["logs:CreateLogGroup","logs:CreateLogStream","logs:PutLogEvents"],Resource:t.sub("arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/*")},{Effect:"Allow",Action:["lambda:InvokeFunction"],Resource:t.sub(`arn:aws:lambda:\${AWS::Region}:\${AWS::AccountId}:function:${i}-${r}-*`)},{Effect:"Allow",Action:["secretsmanager:GetSecretValue","ssm:GetParameter","ssm:GetParameters","ssm:GetParametersByPath"],Resource:[t.sub(`arn:aws:secretsmanager:\${AWS::Region}:\${AWS::AccountId}:secret:${i}/${r}/*`),t.sub(`arn:aws:ssm:\${AWS::Region}:\${AWS::AccountId}:parameter/${i}/${r}/*`)]},{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:ListBucket"],Resource:[t.sub(`arn:aws:s3:::${w}`),t.sub(`arn:aws:s3:::${w}/*`),...a.storage?.bucket?[t.sub(`arn:aws:s3:::${a.storage.bucket}`),t.sub(`arn:aws:s3:::${a.storage.bucket}/*`)]:[]]}]}}];if(g)I[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["sqs:SendMessage","sqs:ReceiveMessage","sqs:DeleteMessage","sqs:GetQueueAttributes","sqs:GetQueueUrl"],Resource:t.sub(`arn:aws:sqs:\${AWS::Region}:\${AWS::AccountId}:${i}-${r}-*`)});if(b)I[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["dynamodb:GetItem","dynamodb:PutItem","dynamodb:UpdateItem","dynamodb:DeleteItem","dynamodb:Query","dynamodb:Scan","dynamodb:BatchGetItem","dynamodb:BatchWriteItem"],Resource:t.sub(`arn:aws:dynamodb:\${AWS::Region}:\${AWS::AccountId}:table/${i}-${r}-cache*`)});let k=["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"];if(a.vpc?.subnets?.length)k.push("arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole");if(a.lambdaInsights)k.push("arn:aws:iam::aws:policy/CloudWatchLambdaInsightsExecutionRolePolicy");T.AppRole={Type:"AWS::IAM::Role",Properties:{RoleName:`${i}-${r}-app-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:k,Policies:I}};let x=(M)=>({TSCLOUD_LAMBDA_MODE:M,TSCLOUD_ENV:r,...a.octane?{TSCLOUD_OCTANE:"1"}:{},...a.scheduler==="sub-minute"?{TSCLOUD_SCHEDULER:"sub-minute"}:{},...b?{TSCLOUD_CACHE_TABLE:`${i}-${r}-cache`}:{},...g?{TSCLOUD_QUEUE:p[0]}:{},...a.env??{}}),L=Boolean(a.efs),O=typeof a.efs==="object"?a.efs:{},W=O.mountPath??"/mnt/local",K=L&&!O.accessPointArn,Z=O.accessPointArn??(K?t.getAtt("EfsAccessPoint","Arn"):void 0),z=a.vpc?.subnets??[],J=z.length>0,q=a.cache?.driver==="elasticache"||a.database?.connection==="aurora-serverless"||Boolean(a.rdsProxy)||L;if(q&&!J)throw Error("serverless app: elasticache / aurora-serverless / rdsProxy / efs require app.vpc.subnets (private subnets) to be set.");let de=J?{VpcConfig:{SubnetIds:z,SecurityGroupIds:[...a.vpc?.securityGroups??[],...q?[t.getAtt("DataSecurityGroup","GroupId")]:[]]}}:{},Oe=K?z.map((M,j)=>`EfsMountTarget${j}`):[],ft=L?{FileSystemConfigs:[{Arn:Z,LocalMountPath:W}]}:{};if(L)I[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["elasticfilesystem:ClientMount","elasticfilesystem:ClientWrite","elasticfilesystem:ClientRootAccess","elasticfilesystem:DescribeMountTargets"],Resource:"*"});function X(M,j,F,H,re,Je,se,Xe=R){T[`${M}LogGroup`]={Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:`/aws/lambda/${j}`,RetentionInDays:h}};let St=[...e.runtimeLayers??[],...a.lambdaInsights?[a.lambdaInsights.layerArn]:[]],bt=y?{PackageType:"Image",Code:{ImageUri:t.ref("ImageUri")},...a.kind==="php"?{}:{ImageConfig:{Command:[F]}}}:{Runtime:o,Handler:F,Code:{S3Bucket:t.ref("ArtifactBucket"),S3Key:t.ref("ArtifactKey")},...St.length?{Layers:[...new Set(St)]}:{}};T[M]={Type:"AWS::Lambda::Function",DependsOn:[`${M}LogGroup`,...Oe],Properties:{FunctionName:j,Architectures:[c],MemorySize:re,Timeout:Je,Role:t.getAtt("AppRole","Arn"),Environment:{Variables:x(H)},EphemeralStorage:{Size:Xe},...bt,...se!==void 0?{ReservedConcurrentExecutions:se}:{},...de,...ft}}}if(X("HttpFunction",d.http,n.http,"http",a.memory??1024,a.timeout??28,a.concurrency,R),X("CliFunction",d.cli,n.cli,"cli",a.cliMemory??1024,a.cliTimeout??900,void 0,a.cliTmpStorage??R),g)X("QueueFunction",d.queue,n.queue,"queue",a.queueMemory??1024,a.queueTimeout??120,void 0,a.queueTmpStorage??R);let Y=(a.provisionedConcurrency??0)>0?a.provisionedConcurrency:0,te=["HttpFunction","CliFunction",...g?["QueueFunction"]:[]];if(Y)for(let M of te)T[`${M}Version`]={Type:"AWS::Lambda::Version",DeletionPolicy:"Retain",Properties:{FunctionName:t.ref(M)}},T[`${M}Alias`]={Type:"AWS::Lambda::Alias",Properties:{FunctionName:t.ref(M),Name:"live",FunctionVersion:t.getAtt(`${M}Version`,"Version"),ProvisionedConcurrencyConfig:{ProvisionedConcurrentExecutions:Y}}};let me=(M)=>Y?t.ref(`${M}Alias`):t.getAtt(M,"Arn"),ae=(M)=>Y?t.ref(`${M}Alias`):t.ref(M);T.HttpApi={Type:"AWS::ApiGatewayV2::Api",Properties:{Name:`${i}-${r}`,ProtocolType:"HTTP"}},T.HttpIntegration={Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:t.ref("HttpApi"),IntegrationType:"AWS_PROXY",IntegrationUri:me("HttpFunction"),PayloadFormatVersion:"2.0"}},T.HttpRoute={Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:t.ref("HttpApi"),RouteKey:"$default",Target:t.join("/",["integrations",t.ref("HttpIntegration")])}},T.HttpStage={Type:"AWS::ApiGatewayV2::Stage",Properties:{ApiId:t.ref("HttpApi"),StageName:"$default",AutoDeploy:!0}},T.HttpPermission={Type:"AWS::Lambda::Permission",Properties:{FunctionName:ae("HttpFunction"),Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:t.sub("arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${HttpApi}/*/*")}},N.HttpApiEndpoint={Description:"HTTP API endpoint",Value:t.getAtt("HttpApi","ApiEndpoint")},N.HttpApiId={Description:"HTTP API id",Value:t.ref("HttpApi")};let ie=(Array.isArray(a.domain)?a.domain:a.domain?[a.domain]:[]).filter(Boolean);if(ie.length){if(!a.certificateArn&&!a.hostedZoneId)throw Error("serverless app: a custom `domain` needs either `certificateArn` (pre-issued, regional) or `hostedZoneId` (to auto-issue + validate an ACM cert).");let M=a.certificateArn;if(!M)T.HttpCertificate={Type:"AWS::CertificateManager::Certificate",Properties:{DomainName:ie[0],...ie.length>1?{SubjectAlternativeNames:ie.slice(1)}:{},ValidationMethod:"DNS",DomainValidationOptions:ie.map((j)=>({DomainName:j,HostedZoneId:a.hostedZoneId}))}},M=t.ref("HttpCertificate");ie.forEach((j,F)=>{let H=`HttpDomain${F}`;if(T[H]={Type:"AWS::ApiGatewayV2::DomainName",Properties:{DomainName:j,DomainNameConfigurations:[{CertificateArn:M,EndpointType:"REGIONAL"}]}},T[`HttpApiMapping${F}`]={Type:"AWS::ApiGatewayV2::ApiMapping",DependsOn:["HttpStage"],Properties:{ApiId:t.ref("HttpApi"),DomainName:t.ref(H),Stage:"$default"}},a.hostedZoneId)T[`HttpDomainRecord${F}`]={Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:a.hostedZoneId,Name:j,Type:"A",AliasTarget:{DNSName:t.getAtt(H,"RegionalDomainName"),HostedZoneId:t.getAtt(H,"RegionalHostedZoneId")}}};N[`CustomDomain${F}`]={Description:`Custom domain ${j}`,Value:j},N[`CustomDomainTarget${F}`]={Description:`Point ${j} (CNAME/alias) at this APIGW regional domain`,Value:t.getAtt(H,"RegionalDomainName")}})}if(g)T.AppQueueDlq={Type:"AWS::SQS::Queue",Properties:{QueueName:`${i}-${r}-dlq`,MessageRetentionPeriod:1209600}},m.forEach((M,j)=>{let F=`AppQueue${j}`,H=a.queueTimeout??120;T[F]={Type:"AWS::SQS::Queue",Properties:{QueueName:M.name,VisibilityTimeout:Math.min(43200,H*6),RedrivePolicy:{deadLetterTargetArn:t.getAtt("AppQueueDlq","Arn"),maxReceiveCount:a.queueTries??3}}};let re=M.concurrency??a.queueConcurrency;T[`${F}Mapping`]={Type:"AWS::Lambda::EventSourceMapping",Properties:{EventSourceArn:t.getAtt(F,"Arn"),FunctionName:ae("QueueFunction"),BatchSize:1,FunctionResponseTypes:["ReportBatchItemFailures"],...re?{ScalingConfig:{MaximumConcurrency:Math.max(2,re)}}:{}}},N[`QueueUrl${j}`]={Description:`Queue URL: ${M.name}`,Value:t.ref(F)}});if(f)T.SchedulerRule={Type:"AWS::Events::Rule",Properties:{Name:`${i}-${r}-scheduler`,ScheduleExpression:"rate(1 minute)",State:"ENABLED",Targets:[{Id:"cli",Arn:me("CliFunction"),Input:JSON.stringify({command:"schedule:run"})}]}},T.SchedulerPermission={Type:"AWS::Lambda::Permission",Properties:{FunctionName:ae("CliFunction"),Action:"lambda:InvokeFunction",Principal:"events.amazonaws.com",SourceArn:t.getAtt("SchedulerRule","Arn")}};if(a.warm&&a.warm>0){let M={http:"HttpFunction",queue:"QueueFunction",cli:"CliFunction"},j=(a.warmFunctions??["http"]).filter((F)=>F!=="queue"||g);for(let F of j){let H=F.charAt(0).toUpperCase()+F.slice(1),re=Math.ceil(a.warm/5),Je=0;for(let se=0;se<re;se++){let Xe=Math.min(5,a.warm-Je);T[`Warmer${H}Rule${se}`]={Type:"AWS::Events::Rule",Properties:{Name:`${i}-${r}-warmer-${F}-${se}`,ScheduleExpression:"rate(5 minutes)",State:"ENABLED",Targets:Array.from({length:Xe},(St,bt)=>({Id:`warm-${F}-${se}-${bt}`,Arn:t.getAtt(M[F],"Arn"),Input:JSON.stringify({warmer:!0})}))}},Je+=Xe}T[`Warmer${H}Permission`]={Type:"AWS::Lambda::Permission",Properties:{FunctionName:t.ref(M[F]),Action:"lambda:InvokeFunction",Principal:"events.amazonaws.com",SourceArn:t.sub(`arn:aws:events:\${AWS::Region}:\${AWS::AccountId}:rule/${i}-${r}-warmer-${F}-*`)}}}}if(b)T.CacheTable={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${i}-${r}-cache`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"key",AttributeType:"S"}],KeySchema:[{AttributeName:"key",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"expires_at",Enabled:!0}}},N.CacheTableName={Description:"DynamoDB cache table",Value:t.ref("CacheTable")};if(v){if(T.AssetsBucket={Type:"AWS::S3::Bucket",Properties:{BucketName:w,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0}}},T.AssetsOAC={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`${i}-${r}-assets-oac`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},T.AssetsDistribution={Type:"AWS::CloudFront::Distribution",Properties:{DistributionConfig:{Enabled:!0,DefaultCacheBehavior:{TargetOriginId:"assets",ViewerProtocolPolicy:"redirect-to-https",Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6"},Origins:[{Id:"assets",DomainName:t.getAtt("AssetsBucket","RegionalDomainName"),OriginAccessControlId:t.ref("AssetsOAC"),S3OriginConfig:{OriginAccessIdentity:""}}],...a.assetDomain?{Aliases:[a.assetDomain],ViewerCertificate:{AcmCertificateArn:a.assetCertificateArn??t.ref("AssetsCertificate"),SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}}:{}}}},a.assetDomain){if(!a.assetCertificateArn){if(!a.hostedZoneId)throw Error("serverless app: `assetDomain` requires either `assetCertificateArn` (a us-east-1 ACM cert) or `hostedZoneId` (to auto-issue + validate one). CloudFront only accepts certs from us-east-1.");if(u!=="us-east-1")throw Error(`serverless app: auto-issuing an asset-domain cert needs a us-east-1 app (CloudFront certs must be us-east-1); this app is in ${u}. Supply a pre-issued us-east-1 \`assetCertificateArn\` instead.`);T.AssetsCertificate={Type:"AWS::CertificateManager::Certificate",Properties:{DomainName:a.assetDomain,ValidationMethod:"DNS",DomainValidationOptions:[{DomainName:a.assetDomain,HostedZoneId:a.hostedZoneId}]}}}if(a.hostedZoneId)T.AssetsDomainRecord={Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:a.hostedZoneId,Name:a.assetDomain,Type:"A",AliasTarget:{DNSName:t.getAtt("AssetsDistribution","DomainName"),HostedZoneId:"Z2FDTNDATAQYW2"}}};N.AssetDomain={Description:"Custom asset CDN host",Value:a.assetDomain}}T.AssetsBucketPolicy={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:t.ref("AssetsBucket"),PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:t.sub(`arn:aws:s3:::${w}/*`),Condition:{StringEquals:{"AWS:SourceArn":t.sub("arn:aws:cloudfront::${AWS::AccountId}:distribution/${AssetsDistribution}")}}}]}}},N.AssetsBucketName={Description:"Assets bucket",Value:t.ref("AssetsBucket")},N.AssetsCdnDomain={Description:"Assets CloudFront domain",Value:t.getAtt("AssetsDistribution","DomainName")}}if(a.firewall?.enabled){let M=[],j=0;if(a.firewall.rateLimit)M.push({Name:"rate-limit",Priority:j++,Action:{Block:{}},Statement:{RateBasedStatement:{Limit:a.firewall.rateLimit,AggregateKeyType:"IP"}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${i}-${r}-rate`}});let F={sqlInjection:"AWSManagedRulesSQLiRuleSet",xss:"AWSManagedRulesCommonRuleSet",common:"AWSManagedRulesCommonRuleSet",botControl:"AWSManagedRulesBotControlRuleSet",ipReputation:"AWSManagedRulesAmazonIpReputationList"};for(let H of a.firewall.rules??[]){let re=F[H];if(!re)continue;M.push({Name:`managed-${H}`,Priority:j++,OverrideAction:{None:{}},Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:re}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${i}-${r}-${H}`}})}T.WebAcl={Type:"AWS::WAFv2::WebACL",Properties:{Name:`${i}-${r}-waf`,Scope:"REGIONAL",DefaultAction:{Allow:{}},Rules:M,VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${i}-${r}-waf`}}},N.WafAclArn={Description:"WAF web ACL ARN. Attach to a CloudFront distribution fronting the API to enforce (HTTP API v2 stages do not support direct WAF association).",Value:t.getAtt("WebAcl","Arn")}}if(J&&q){if(!a.vpc?.id)throw Error("serverless app: data services (elasticache / aurora-serverless / rdsProxy / efs) need app.vpc.id (the VPC id) so the managed security group is created in the right VPC.");T.DataSecurityGroup={Type:"AWS::EC2::SecurityGroup",Properties:{VpcId:a.vpc.id,GroupDescription:`${i}-${r} serverless data access`,SecurityGroupIngress:[{IpProtocol:"-1",CidrIp:"10.0.0.0/8"}]}}}if(K)T.EfsFileSystem={Type:"AWS::EFS::FileSystem",Properties:{Encrypted:!0,FileSystemTags:[{Key:"Name",Value:`${i}-${r}-efs`}]}},z.forEach((M,j)=>{T[`EfsMountTarget${j}`]={Type:"AWS::EFS::MountTarget",Properties:{FileSystemId:t.ref("EfsFileSystem"),SubnetId:M,SecurityGroups:[t.getAtt("DataSecurityGroup","GroupId")]}}}),T.EfsAccessPoint={Type:"AWS::EFS::AccessPoint",Properties:{FileSystemId:t.ref("EfsFileSystem"),PosixUser:{Uid:1001,Gid:1001},RootDirectory:{Path:"/lambda",CreationInfo:{OwnerUid:1001,OwnerGid:1001,Permissions:"0755"}}}},N.EfsFileSystemId={Description:"EFS file system id",Value:t.ref("EfsFileSystem")};if(a.cache?.driver==="elasticache")T.CacheSubnetGroup={Type:"AWS::ElastiCache::SubnetGroup",Properties:{Description:`${i}-${r} cache subnets`,SubnetIds:z}},T.CacheCluster={Type:"AWS::ElastiCache::ReplicationGroup",Properties:{ReplicationGroupId:`${i}-${r}-cache`,ReplicationGroupDescription:`${i}-${r} redis`,Engine:"redis",CacheNodeType:"cache.t4g.micro",NumCacheClusters:1,AutomaticFailoverEnabled:!1,CacheSubnetGroupName:t.ref("CacheSubnetGroup"),SecurityGroupIds:[t.getAtt("DataSecurityGroup","GroupId")],TransitEncryptionEnabled:!1}},N.CacheEndpoint={Description:"Redis primary endpoint",Value:t.getAtt("CacheCluster","PrimaryEndPoint.Address")};if(a.database?.connection==="aurora-serverless")T.DbSubnetGroup={Type:"AWS::RDS::DBSubnetGroup",Properties:{DBSubnetGroupDescription:`${i}-${r} db subnets`,SubnetIds:z}},T.DbSecret={Type:"AWS::SecretsManager::Secret",Properties:{Name:`${i}/${r}/db`,GenerateSecretString:{SecretStringTemplate:JSON.stringify({username:"app"}),GenerateStringKey:"password",PasswordLength:32,ExcludePunctuation:!0}}},T.DbCluster={Type:"AWS::RDS::DBCluster",Properties:{Engine:"aurora-mysql",EngineMode:"provisioned",DBClusterIdentifier:`${i}-${r}-db`,DatabaseName:"app",MasterUsername:t.sub("{{resolve:secretsmanager:${DbSecret}:SecretString:username}}"),MasterUserPassword:t.sub("{{resolve:secretsmanager:${DbSecret}:SecretString:password}}"),ServerlessV2ScalingConfiguration:{MinCapacity:a.database?.minCapacity??0.5,MaxCapacity:a.database?.maxCapacity??4},DBSubnetGroupName:t.ref("DbSubnetGroup"),VpcSecurityGroupIds:[t.getAtt("DataSecurityGroup","GroupId")]}},T.DbInstance={Type:"AWS::RDS::DBInstance",Properties:{Engine:"aurora-mysql",DBInstanceClass:"db.serverless",DBClusterIdentifier:t.ref("DbCluster")}},N.DbEndpoint={Description:"Aurora cluster endpoint",Value:t.getAtt("DbCluster","Endpoint.Address")};if(a.rdsProxy&&a.database?.connection==="aurora-serverless")T.DbProxyRole={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"rds.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"read-db-secret",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["secretsmanager:GetSecretValue"],Resource:t.ref("DbSecret")}]}}]}},T.DbProxy={Type:"AWS::RDS::DBProxy",Properties:{DBProxyName:typeof a.rdsProxy==="object"&&a.rdsProxy.name?a.rdsProxy.name:`${i}-${r}-proxy`,EngineFamily:"MYSQL",RoleArn:t.getAtt("DbProxyRole","Arn"),Auth:[{AuthScheme:"SECRETS",SecretArn:t.ref("DbSecret"),IAMAuth:"DISABLED"}],VpcSubnetIds:z,VpcSecurityGroupIds:[t.getAtt("DataSecurityGroup","GroupId")],RequireTLS:!1}},T.DbProxyTargetGroup={Type:"AWS::RDS::DBProxyTargetGroup",DependsOn:["DbInstance"],Properties:{DBProxyName:t.ref("DbProxy"),TargetGroupName:"default",DBClusterIdentifiers:[t.ref("DbCluster")]}},N.DbProxyEndpoint={Description:"RDS Proxy endpoint",Value:t.getAtt("DbProxy","Endpoint")};if(N.HttpFunctionName={Description:"HTTP function name",Value:t.ref("HttpFunction")},N.CliFunctionName={Description:"CLI function name",Value:t.ref("CliFunction")},g)N.QueueFunctionName={Description:"Queue function name",Value:t.ref("QueueFunction")};let fe={AWSTemplateFormatVersion:"2010-09-09",Description:`Serverless application for ${e.config.project.name} (${i}-${r})`,Parameters:y?{ImageUri:{Type:"String",Description:"ECR image URI of the deployment artifact"}}:{ArtifactBucket:{Type:"String",Description:"S3 bucket holding the deployment artifact"},ArtifactKey:{Type:"String",Description:"S3 key of the deployment artifact (zip)"}},Resources:T,Outputs:N},Be={};for(let M of Object.values(T))Be[M.Type]=(Be[M.Type]??0)+1;return{template:fe,functionNames:d,queueNames:p,resourceSummary:Be}}var ru=["cli","fpm","curl","mbstring","xml","pdo","mysqlnd","gd","bcmath","intl","opcache","sodium","process","pecl-redis6","pecl-apcu","pgsql"];function nu(e){let a=`php${e.replace(".","")}`;return ru.map((r)=>`${a}-php-${r}`)}function Sl(e,a){let r=`php${e.replace(".","")}`,n=nu(e).join(" \\\n "),i=`/opt/remi/${r}/root`,o=`/etc/opt/remi/${r}`;return`${a?`FROM almalinux:9 AS ${a}`:"FROM almalinux:9"}
|
|
7286
|
+
${h}`)}let d=u.outputs[0],m=Buffer.from(await d.arrayBuffer()),p="index",g=Si([{name:`${p}.mjs`,data:m}]);return{zip:g,bundle:m,sha256:Po(g),handlerFile:p,handlers:{http:r.handlers?.http??`${p}.http`,queue:r.handlers?.queue??`${p}.queue`,cli:r.handlers?.cli??`${p}.cli`},bundleBytes:m.length}}finally{Ei(o,{recursive:!0,force:!0})}}var tu=["18","20","22"];function Mi(e){if(!e)return"22";let a=String(e).match(/(\d+)/);return a?a[1]:"22"}function No(e){let a=e.kind??"node";if(a==="php")return{lambdaRuntime:"provided.al2023",kind:"php",version:e.phpVersion??"8.3",usesLayer:!0,layerKind:"php",layerEnvVar:"TSCLOUD_PHP_LAYER_ARN"};if(a==="bun")return{lambdaRuntime:"provided.al2023",kind:"bun",version:e.runtimeVersion??"latest",usesLayer:!0,layerKind:"bun",layerEnvVar:"TSCLOUD_BUN_LAYER_ARN"};let r=Mi(e.runtimeVersion);if(e.runtime!=="provided.al2023"&&tu.includes(r))return{lambdaRuntime:e.runtime&&e.runtime.startsWith("nodejs")?e.runtime:`nodejs${r}.x`,kind:"node",version:r,usesLayer:!1};return{lambdaRuntime:"provided.al2023",kind:"node",version:r,usesLayer:!0,layerKind:"node",layerEnvVar:"TSCLOUD_NODE_LAYER_ARN"}}function Vt(e,a,r){if(e.queues===!1)return[];if(e.queues===void 0||e.queues===!0)return[{name:`${a}-${r}-default`}];return e.queues.map((n)=>{if(typeof n==="string")return{name:`${a}-${r}-${n}`};let[i,o]=Object.entries(n)[0];return{name:`${a}-${r}-${i}`,concurrency:o}})}function Zs(e,a,r){return Vt(e,a,r).map((n)=>n.name)}function ea(e){let{app:a,environment:r,handlers:n}=e,i=e.config.project.slug,o=No(a).lambdaRuntime,c=a.architecture??"x86_64",u=e.config.project.region,d={http:`${i}-${r}-http`,queue:`${i}-${r}-queue`,cli:`${i}-${r}-cli`};if(a.gatewayVersion===1)throw Error("serverless app: `gatewayVersion: 1` (REST API) is not supported — ts-cloud uses API Gateway HTTP API (v2). Remove `gatewayVersion` or set it to 2.");let m=Vt(a,i,r),p=m.map((M)=>M.name),g=p.length>0,h=a.logRetention??14,y=a.packaging==="image";if(y&&a.lambdaInsights)throw Error("serverless app: `lambdaInsights` layer attachment is only supported for zip packaging. Container images must install the Lambda Insights extension in the image.");let f=(a.scheduler??"on")!=="off",b=(a.cache?.driver??"dynamodb")==="dynamodb",v=Boolean(a.assets),w=bo(i,r),R=a.tmpStorage??512,T={},N={},I=[{PolicyName:"tscloud-serverless-app",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["logs:CreateLogGroup","logs:CreateLogStream","logs:PutLogEvents"],Resource:t.sub("arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/*")},{Effect:"Allow",Action:["lambda:InvokeFunction"],Resource:t.sub(`arn:aws:lambda:\${AWS::Region}:\${AWS::AccountId}:function:${i}-${r}-*`)},{Effect:"Allow",Action:["secretsmanager:GetSecretValue","ssm:GetParameter","ssm:GetParameters","ssm:GetParametersByPath"],Resource:[t.sub(`arn:aws:secretsmanager:\${AWS::Region}:\${AWS::AccountId}:secret:${i}/${r}/*`),t.sub(`arn:aws:ssm:\${AWS::Region}:\${AWS::AccountId}:parameter/${i}/${r}/*`)]},{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:ListBucket"],Resource:[t.sub(`arn:aws:s3:::${w}`),t.sub(`arn:aws:s3:::${w}/*`),...a.storage?.bucket?[t.sub(`arn:aws:s3:::${a.storage.bucket}`),t.sub(`arn:aws:s3:::${a.storage.bucket}/*`)]:[]]}]}}];if(g)I[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["sqs:SendMessage","sqs:ReceiveMessage","sqs:DeleteMessage","sqs:GetQueueAttributes","sqs:GetQueueUrl"],Resource:t.sub(`arn:aws:sqs:\${AWS::Region}:\${AWS::AccountId}:${i}-${r}-*`)});if(b)I[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["dynamodb:GetItem","dynamodb:PutItem","dynamodb:UpdateItem","dynamodb:DeleteItem","dynamodb:Query","dynamodb:Scan","dynamodb:BatchGetItem","dynamodb:BatchWriteItem"],Resource:t.sub(`arn:aws:dynamodb:\${AWS::Region}:\${AWS::AccountId}:table/${i}-${r}-cache*`)});let k=["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"];if(a.vpc?.subnets?.length)k.push("arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole");if(a.lambdaInsights)k.push("arn:aws:iam::aws:policy/CloudWatchLambdaInsightsExecutionRolePolicy");T.AppRole={Type:"AWS::IAM::Role",Properties:{RoleName:`${i}-${r}-app-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:k,Policies:I}};let O=(M)=>({TSCLOUD_LAMBDA_MODE:M,TSCLOUD_ENV:r,...a.octane?{TSCLOUD_OCTANE:"1"}:{},...a.scheduler==="sub-minute"?{TSCLOUD_SCHEDULER:"sub-minute"}:{},...b?{TSCLOUD_CACHE_TABLE:`${i}-${r}-cache`}:{},...g?{TSCLOUD_QUEUE:p[0]}:{},...a.env??{}}),L=Boolean(a.efs),_=typeof a.efs==="object"?a.efs:{},W=_.mountPath??"/mnt/local",K=L&&!_.accessPointArn,Z=_.accessPointArn??(K?t.getAtt("EfsAccessPoint","Arn"):void 0),z=a.vpc?.subnets??[],J=z.length>0,q=a.cache?.driver==="elasticache"||a.database?.connection==="aurora-serverless"||Boolean(a.rdsProxy)||L;if(q&&!J)throw Error("serverless app: elasticache / aurora-serverless / rdsProxy / efs require app.vpc.subnets (private subnets) to be set.");let de=J?{VpcConfig:{SubnetIds:z,SecurityGroupIds:[...a.vpc?.securityGroups??[],...q?[t.getAtt("DataSecurityGroup","GroupId")]:[]]}}:{},Oe=K?z.map((M,j)=>`EfsMountTarget${j}`):[],ft=L?{FileSystemConfigs:[{Arn:Z,LocalMountPath:W}]}:{};if(L)I[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["elasticfilesystem:ClientMount","elasticfilesystem:ClientWrite","elasticfilesystem:ClientRootAccess","elasticfilesystem:DescribeMountTargets"],Resource:"*"});function X(M,j,F,H,re,Je,se,Xe=R){T[`${M}LogGroup`]={Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:`/aws/lambda/${j}`,RetentionInDays:h}};let St=[...e.runtimeLayers??[],...a.lambdaInsights?[a.lambdaInsights.layerArn]:[]],bt=y?{PackageType:"Image",Code:{ImageUri:t.ref("ImageUri")},...a.kind==="php"?{}:{ImageConfig:{Command:[F]}}}:{Runtime:o,Handler:F,Code:{S3Bucket:t.ref("ArtifactBucket"),S3Key:t.ref("ArtifactKey")},...St.length?{Layers:[...new Set(St)]}:{}};T[M]={Type:"AWS::Lambda::Function",DependsOn:[`${M}LogGroup`,...Oe],Properties:{FunctionName:j,Architectures:[c],MemorySize:re,Timeout:Je,Role:t.getAtt("AppRole","Arn"),Environment:{Variables:O(H)},EphemeralStorage:{Size:Xe},...bt,...se!==void 0?{ReservedConcurrentExecutions:se}:{},...de,...ft}}}if(X("HttpFunction",d.http,n.http,"http",a.memory??1024,a.timeout??28,a.concurrency,R),X("CliFunction",d.cli,n.cli,"cli",a.cliMemory??1024,a.cliTimeout??900,void 0,a.cliTmpStorage??R),g)X("QueueFunction",d.queue,n.queue,"queue",a.queueMemory??1024,a.queueTimeout??120,void 0,a.queueTmpStorage??R);let Y=(a.provisionedConcurrency??0)>0?a.provisionedConcurrency:0,te=["HttpFunction","CliFunction",...g?["QueueFunction"]:[]];if(Y)for(let M of te)T[`${M}Version`]={Type:"AWS::Lambda::Version",DeletionPolicy:"Retain",Properties:{FunctionName:t.ref(M)}},T[`${M}Alias`]={Type:"AWS::Lambda::Alias",Properties:{FunctionName:t.ref(M),Name:"live",FunctionVersion:t.getAtt(`${M}Version`,"Version"),ProvisionedConcurrencyConfig:{ProvisionedConcurrentExecutions:Y}}};let me=(M)=>Y?t.ref(`${M}Alias`):t.getAtt(M,"Arn"),ae=(M)=>Y?t.ref(`${M}Alias`):t.ref(M);T.HttpApi={Type:"AWS::ApiGatewayV2::Api",Properties:{Name:`${i}-${r}`,ProtocolType:"HTTP"}},T.HttpIntegration={Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:t.ref("HttpApi"),IntegrationType:"AWS_PROXY",IntegrationUri:me("HttpFunction"),PayloadFormatVersion:"2.0"}},T.HttpRoute={Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:t.ref("HttpApi"),RouteKey:"$default",Target:t.join("/",["integrations",t.ref("HttpIntegration")])}},T.HttpStage={Type:"AWS::ApiGatewayV2::Stage",Properties:{ApiId:t.ref("HttpApi"),StageName:"$default",AutoDeploy:!0}},T.HttpPermission={Type:"AWS::Lambda::Permission",Properties:{FunctionName:ae("HttpFunction"),Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:t.sub("arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${HttpApi}/*/*")}},N.HttpApiEndpoint={Description:"HTTP API endpoint",Value:t.getAtt("HttpApi","ApiEndpoint")},N.HttpApiId={Description:"HTTP API id",Value:t.ref("HttpApi")};let ie=(Array.isArray(a.domain)?a.domain:a.domain?[a.domain]:[]).filter(Boolean);if(ie.length){if(!a.certificateArn&&!a.hostedZoneId)throw Error("serverless app: a custom `domain` needs either `certificateArn` (pre-issued, regional) or `hostedZoneId` (to auto-issue + validate an ACM cert).");let M=a.certificateArn;if(!M)T.HttpCertificate={Type:"AWS::CertificateManager::Certificate",Properties:{DomainName:ie[0],...ie.length>1?{SubjectAlternativeNames:ie.slice(1)}:{},ValidationMethod:"DNS",DomainValidationOptions:ie.map((j)=>({DomainName:j,HostedZoneId:a.hostedZoneId}))}},M=t.ref("HttpCertificate");ie.forEach((j,F)=>{let H=`HttpDomain${F}`;if(T[H]={Type:"AWS::ApiGatewayV2::DomainName",Properties:{DomainName:j,DomainNameConfigurations:[{CertificateArn:M,EndpointType:"REGIONAL"}]}},T[`HttpApiMapping${F}`]={Type:"AWS::ApiGatewayV2::ApiMapping",DependsOn:["HttpStage"],Properties:{ApiId:t.ref("HttpApi"),DomainName:t.ref(H),Stage:"$default"}},a.hostedZoneId)T[`HttpDomainRecord${F}`]={Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:a.hostedZoneId,Name:j,Type:"A",AliasTarget:{DNSName:t.getAtt(H,"RegionalDomainName"),HostedZoneId:t.getAtt(H,"RegionalHostedZoneId")}}};N[`CustomDomain${F}`]={Description:`Custom domain ${j}`,Value:j},N[`CustomDomainTarget${F}`]={Description:`Point ${j} (CNAME/alias) at this APIGW regional domain`,Value:t.getAtt(H,"RegionalDomainName")}})}if(g)T.AppQueueDlq={Type:"AWS::SQS::Queue",Properties:{QueueName:`${i}-${r}-dlq`,MessageRetentionPeriod:1209600}},m.forEach((M,j)=>{let F=`AppQueue${j}`,H=a.queueTimeout??120;T[F]={Type:"AWS::SQS::Queue",Properties:{QueueName:M.name,VisibilityTimeout:Math.min(43200,H*6),RedrivePolicy:{deadLetterTargetArn:t.getAtt("AppQueueDlq","Arn"),maxReceiveCount:a.queueTries??3}}};let re=M.concurrency??a.queueConcurrency;T[`${F}Mapping`]={Type:"AWS::Lambda::EventSourceMapping",Properties:{EventSourceArn:t.getAtt(F,"Arn"),FunctionName:ae("QueueFunction"),BatchSize:1,FunctionResponseTypes:["ReportBatchItemFailures"],...re?{ScalingConfig:{MaximumConcurrency:Math.max(2,re)}}:{}}},N[`QueueUrl${j}`]={Description:`Queue URL: ${M.name}`,Value:t.ref(F)}});if(f)T.SchedulerRule={Type:"AWS::Events::Rule",Properties:{Name:`${i}-${r}-scheduler`,ScheduleExpression:"rate(1 minute)",State:"ENABLED",Targets:[{Id:"cli",Arn:me("CliFunction"),Input:JSON.stringify({command:"schedule:run"})}]}},T.SchedulerPermission={Type:"AWS::Lambda::Permission",Properties:{FunctionName:ae("CliFunction"),Action:"lambda:InvokeFunction",Principal:"events.amazonaws.com",SourceArn:t.getAtt("SchedulerRule","Arn")}};if(a.warm&&a.warm>0){let M={http:"HttpFunction",queue:"QueueFunction",cli:"CliFunction"},j=(a.warmFunctions??["http"]).filter((F)=>F!=="queue"||g);for(let F of j){let H=F.charAt(0).toUpperCase()+F.slice(1),re=Math.ceil(a.warm/5),Je=0;for(let se=0;se<re;se++){let Xe=Math.min(5,a.warm-Je);T[`Warmer${H}Rule${se}`]={Type:"AWS::Events::Rule",Properties:{Name:`${i}-${r}-warmer-${F}-${se}`,ScheduleExpression:"rate(5 minutes)",State:"ENABLED",Targets:Array.from({length:Xe},(St,bt)=>({Id:`warm-${F}-${se}-${bt}`,Arn:t.getAtt(M[F],"Arn"),Input:JSON.stringify({warmer:!0})}))}},Je+=Xe}T[`Warmer${H}Permission`]={Type:"AWS::Lambda::Permission",Properties:{FunctionName:t.ref(M[F]),Action:"lambda:InvokeFunction",Principal:"events.amazonaws.com",SourceArn:t.sub(`arn:aws:events:\${AWS::Region}:\${AWS::AccountId}:rule/${i}-${r}-warmer-${F}-*`)}}}}if(b)T.CacheTable={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${i}-${r}-cache`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"key",AttributeType:"S"}],KeySchema:[{AttributeName:"key",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"expires_at",Enabled:!0}}},N.CacheTableName={Description:"DynamoDB cache table",Value:t.ref("CacheTable")};if(v){if(T.AssetsBucket={Type:"AWS::S3::Bucket",Properties:{BucketName:w,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0}}},T.AssetsOAC={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`${i}-${r}-assets-oac`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},T.AssetsDistribution={Type:"AWS::CloudFront::Distribution",Properties:{DistributionConfig:{Enabled:!0,DefaultCacheBehavior:{TargetOriginId:"assets",ViewerProtocolPolicy:"redirect-to-https",Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6"},Origins:[{Id:"assets",DomainName:t.getAtt("AssetsBucket","RegionalDomainName"),OriginAccessControlId:t.ref("AssetsOAC"),S3OriginConfig:{OriginAccessIdentity:""}}],...a.assetDomain?{Aliases:[a.assetDomain],ViewerCertificate:{AcmCertificateArn:a.assetCertificateArn??t.ref("AssetsCertificate"),SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}}:{}}}},a.assetDomain){if(!a.assetCertificateArn){if(!a.hostedZoneId)throw Error("serverless app: `assetDomain` requires either `assetCertificateArn` (a us-east-1 ACM cert) or `hostedZoneId` (to auto-issue + validate one). CloudFront only accepts certs from us-east-1.");if(u!=="us-east-1")throw Error(`serverless app: auto-issuing an asset-domain cert needs a us-east-1 app (CloudFront certs must be us-east-1); this app is in ${u}. Supply a pre-issued us-east-1 \`assetCertificateArn\` instead.`);T.AssetsCertificate={Type:"AWS::CertificateManager::Certificate",Properties:{DomainName:a.assetDomain,ValidationMethod:"DNS",DomainValidationOptions:[{DomainName:a.assetDomain,HostedZoneId:a.hostedZoneId}]}}}if(a.hostedZoneId)T.AssetsDomainRecord={Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:a.hostedZoneId,Name:a.assetDomain,Type:"A",AliasTarget:{DNSName:t.getAtt("AssetsDistribution","DomainName"),HostedZoneId:"Z2FDTNDATAQYW2"}}};N.AssetDomain={Description:"Custom asset CDN host",Value:a.assetDomain}}T.AssetsBucketPolicy={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:t.ref("AssetsBucket"),PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:t.sub(`arn:aws:s3:::${w}/*`),Condition:{StringEquals:{"AWS:SourceArn":t.sub("arn:aws:cloudfront::${AWS::AccountId}:distribution/${AssetsDistribution}")}}}]}}},N.AssetsBucketName={Description:"Assets bucket",Value:t.ref("AssetsBucket")},N.AssetsCdnDomain={Description:"Assets CloudFront domain",Value:t.getAtt("AssetsDistribution","DomainName")}}if(a.firewall?.enabled){let M=[],j=0;if(a.firewall.rateLimit)M.push({Name:"rate-limit",Priority:j++,Action:{Block:{}},Statement:{RateBasedStatement:{Limit:a.firewall.rateLimit,AggregateKeyType:"IP"}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${i}-${r}-rate`}});let F={sqlInjection:"AWSManagedRulesSQLiRuleSet",xss:"AWSManagedRulesCommonRuleSet",common:"AWSManagedRulesCommonRuleSet",botControl:"AWSManagedRulesBotControlRuleSet",ipReputation:"AWSManagedRulesAmazonIpReputationList"};for(let H of a.firewall.rules??[]){let re=F[H];if(!re)continue;M.push({Name:`managed-${H}`,Priority:j++,OverrideAction:{None:{}},Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:re}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${i}-${r}-${H}`}})}T.WebAcl={Type:"AWS::WAFv2::WebACL",Properties:{Name:`${i}-${r}-waf`,Scope:"REGIONAL",DefaultAction:{Allow:{}},Rules:M,VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${i}-${r}-waf`}}},N.WafAclArn={Description:"WAF web ACL ARN. Attach to a CloudFront distribution fronting the API to enforce (HTTP API v2 stages do not support direct WAF association).",Value:t.getAtt("WebAcl","Arn")}}if(J&&q){if(!a.vpc?.id)throw Error("serverless app: data services (elasticache / aurora-serverless / rdsProxy / efs) need app.vpc.id (the VPC id) so the managed security group is created in the right VPC.");T.DataSecurityGroup={Type:"AWS::EC2::SecurityGroup",Properties:{VpcId:a.vpc.id,GroupDescription:`${i}-${r} serverless data access`,SecurityGroupIngress:[{IpProtocol:"-1",CidrIp:"10.0.0.0/8"}]}}}if(K)T.EfsFileSystem={Type:"AWS::EFS::FileSystem",Properties:{Encrypted:!0,FileSystemTags:[{Key:"Name",Value:`${i}-${r}-efs`}]}},z.forEach((M,j)=>{T[`EfsMountTarget${j}`]={Type:"AWS::EFS::MountTarget",Properties:{FileSystemId:t.ref("EfsFileSystem"),SubnetId:M,SecurityGroups:[t.getAtt("DataSecurityGroup","GroupId")]}}}),T.EfsAccessPoint={Type:"AWS::EFS::AccessPoint",Properties:{FileSystemId:t.ref("EfsFileSystem"),PosixUser:{Uid:1001,Gid:1001},RootDirectory:{Path:"/lambda",CreationInfo:{OwnerUid:1001,OwnerGid:1001,Permissions:"0755"}}}},N.EfsFileSystemId={Description:"EFS file system id",Value:t.ref("EfsFileSystem")};if(a.cache?.driver==="elasticache")T.CacheSubnetGroup={Type:"AWS::ElastiCache::SubnetGroup",Properties:{Description:`${i}-${r} cache subnets`,SubnetIds:z}},T.CacheCluster={Type:"AWS::ElastiCache::ReplicationGroup",Properties:{ReplicationGroupId:`${i}-${r}-cache`,ReplicationGroupDescription:`${i}-${r} redis`,Engine:"redis",CacheNodeType:"cache.t4g.micro",NumCacheClusters:1,AutomaticFailoverEnabled:!1,CacheSubnetGroupName:t.ref("CacheSubnetGroup"),SecurityGroupIds:[t.getAtt("DataSecurityGroup","GroupId")],TransitEncryptionEnabled:!1}},N.CacheEndpoint={Description:"Redis primary endpoint",Value:t.getAtt("CacheCluster","PrimaryEndPoint.Address")};if(a.database?.connection==="aurora-serverless")T.DbSubnetGroup={Type:"AWS::RDS::DBSubnetGroup",Properties:{DBSubnetGroupDescription:`${i}-${r} db subnets`,SubnetIds:z}},T.DbSecret={Type:"AWS::SecretsManager::Secret",Properties:{Name:`${i}/${r}/db`,GenerateSecretString:{SecretStringTemplate:JSON.stringify({username:"app"}),GenerateStringKey:"password",PasswordLength:32,ExcludePunctuation:!0}}},T.DbCluster={Type:"AWS::RDS::DBCluster",Properties:{Engine:"aurora-mysql",EngineMode:"provisioned",DBClusterIdentifier:`${i}-${r}-db`,DatabaseName:"app",MasterUsername:t.sub("{{resolve:secretsmanager:${DbSecret}:SecretString:username}}"),MasterUserPassword:t.sub("{{resolve:secretsmanager:${DbSecret}:SecretString:password}}"),ServerlessV2ScalingConfiguration:{MinCapacity:a.database?.minCapacity??0.5,MaxCapacity:a.database?.maxCapacity??4},DBSubnetGroupName:t.ref("DbSubnetGroup"),VpcSecurityGroupIds:[t.getAtt("DataSecurityGroup","GroupId")]}},T.DbInstance={Type:"AWS::RDS::DBInstance",Properties:{Engine:"aurora-mysql",DBInstanceClass:"db.serverless",DBClusterIdentifier:t.ref("DbCluster")}},N.DbEndpoint={Description:"Aurora cluster endpoint",Value:t.getAtt("DbCluster","Endpoint.Address")};if(a.rdsProxy&&a.database?.connection==="aurora-serverless")T.DbProxyRole={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"rds.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"read-db-secret",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["secretsmanager:GetSecretValue"],Resource:t.ref("DbSecret")}]}}]}},T.DbProxy={Type:"AWS::RDS::DBProxy",Properties:{DBProxyName:typeof a.rdsProxy==="object"&&a.rdsProxy.name?a.rdsProxy.name:`${i}-${r}-proxy`,EngineFamily:"MYSQL",RoleArn:t.getAtt("DbProxyRole","Arn"),Auth:[{AuthScheme:"SECRETS",SecretArn:t.ref("DbSecret"),IAMAuth:"DISABLED"}],VpcSubnetIds:z,VpcSecurityGroupIds:[t.getAtt("DataSecurityGroup","GroupId")],RequireTLS:!1}},T.DbProxyTargetGroup={Type:"AWS::RDS::DBProxyTargetGroup",DependsOn:["DbInstance"],Properties:{DBProxyName:t.ref("DbProxy"),TargetGroupName:"default",DBClusterIdentifiers:[t.ref("DbCluster")]}},N.DbProxyEndpoint={Description:"RDS Proxy endpoint",Value:t.getAtt("DbProxy","Endpoint")};if(N.HttpFunctionName={Description:"HTTP function name",Value:t.ref("HttpFunction")},N.CliFunctionName={Description:"CLI function name",Value:t.ref("CliFunction")},g)N.QueueFunctionName={Description:"Queue function name",Value:t.ref("QueueFunction")};let fe={AWSTemplateFormatVersion:"2010-09-09",Description:`Serverless application for ${e.config.project.name} (${i}-${r})`,Parameters:y?{ImageUri:{Type:"String",Description:"ECR image URI of the deployment artifact"}}:{ArtifactBucket:{Type:"String",Description:"S3 bucket holding the deployment artifact"},ArtifactKey:{Type:"String",Description:"S3 key of the deployment artifact (zip)"}},Resources:T,Outputs:N},Be={};for(let M of Object.values(T))Be[M.Type]=(Be[M.Type]??0)+1;return{template:fe,functionNames:d,queueNames:p,resourceSummary:Be}}var ru=["cli","fpm","curl","mbstring","xml","pdo","mysqlnd","gd","bcmath","intl","opcache","sodium","process","pecl-redis6","pecl-apcu","pgsql"];function nu(e){let a=`php${e.replace(".","")}`;return ru.map((r)=>`${a}-php-${r}`)}function Sl(e,a){let r=`php${e.replace(".","")}`,n=nu(e).join(" \\\n "),i=`/opt/remi/${r}/root`,o=`/etc/opt/remi/${r}`;return`${a?`FROM almalinux:9 AS ${a}`:"FROM almalinux:9"}
|
|
7287
7287
|
|
|
7288
7288
|
# Build PHP on AlmaLinux 9 (where Remi's version-isolated SCL packages install
|
|
7289
7289
|
# cleanly — Remi's release RPM rejects Amazon Linux 2023). AlmaLinux 9 shares
|
|
@@ -7361,4 +7361,4 @@ decorate_workers_output = no
|
|
|
7361
7361
|
php_admin_value[error_log] = /dev/stderr
|
|
7362
7362
|
php_admin_flag[log_errors] = on
|
|
7363
7363
|
clear_env = no
|
|
7364
|
-
`}function zi(){return Qa(qi(Hi(import.meta.url)),"runtime-assets")}function bi(){let e=zi(),a=(r)=>Ki(Qa(e,r),"utf-8");return[{path:"bootstrap",contents:a("bootstrap"),mode:493},{path:"tscloud/runtime.php",contents:a("runtime.php"),mode:420},{path:"tscloud/octane-runtime.php",contents:a("octane-runtime.php"),mode:420},{path:"tscloud/cli-runtime.php",contents:a("cli-runtime.php"),mode:420},{path:"tscloud/fastcgi-client.php",contents:a("fastcgi-client.php"),mode:420},{path:"tscloud/php-fpm.conf",contents:gu(),mode:420}]}function sa(e={}){let a=e.cacheDriver??"dynamodb";return{APP_ENV:"production",LOG_CHANNEL:"stderr",CACHE_STORE:a,CACHE_DRIVER:a,SESSION_DRIVER:a,QUEUE_CONNECTION:"sqs",FILESYSTEM_DISK:"s3",VIEW_COMPILED_PATH:"/tmp/storage/framework/views",APP_SERVICES_CACHE:"/tmp/bootstrap/cache/services.php",APP_PACKAGES_CACHE:"/tmp/bootstrap/cache/packages.php",APP_CONFIG_CACHE:"/tmp/bootstrap/cache/config.php",APP_ROUTES_CACHE:"/tmp/bootstrap/cache/routes.php",APP_EVENTS_CACHE:"/tmp/bootstrap/cache/events.php"}}var fu=["composer install --no-dev --optimize-autoloader --no-interaction","php artisan config:cache","php artisan route:cache","php artisan event:cache","php artisan view:cache"];function*Ya(e){for(let a of Zi(e)){let r=Re(e,a);if(Ja(r).isDirectory())yield*Ya(r);else yield r}}function Af(e={}){let a=e.architecture??"x86_64",r=e.platform??(a==="arm64"?"linux/arm64":"linux/amd64"),n=e.onStep??(()=>{}),i=Yi(Re(as(),"tscloud-php-layer-")),o="tscloud-php-layer:build";try{ts(Re(i,"Dockerfile"),iu(e)),n("Building PHP runtime image (docker)"),it("docker",["build","--platform",r,"-t","tscloud-php-layer:build",i],{stdio:"inherit"}),n("Extracting /opt/php from image");let c=it("docker",["create","--platform",r,"tscloud-php-layer:build"],{encoding:"utf-8"}).trim(),u=Re(i,"opt");Ji(u,{recursive:!0});try{it("docker",["cp",`${c}:/opt/php`,Re(u,"php")],{stdio:"inherit"})}finally{it("docker",["rm",c],{stdio:"ignore"})}if(!Qi(Re(u,"php","bin","php")))throw Error("layer build produced no /opt/php/bin/php");let d=[];for(let g of Ya(u)){let h=rs(u,g).replace(/\\/g,"/"),y=Ja(g).mode&73?493:420;d.push({name:h,data:Xi(g),mode:y})}n("Injecting runtime assets");let m=new Set(bi().map((g)=>g.path)),p=d.filter((g)=>!m.has(g.name));for(let g of bi())p.push({name:g.path,data:g.contents,mode:g.mode});return n("Packaging layer ZIP"),{zip:Si(p),architecture:a,fileCount:p.length}}finally{es(i,{recursive:!0,force:!0})}}var hu=[".git",".github","node_modules","tests","storage/logs","storage/framework/cache","storage/framework/sessions","storage/framework/views",".env",".env.local",".vapor",".ts-cloud","dist-lambda"];function ls(e,a){return a.some((r)=>e===r||e.startsWith(`${r}/`))}function*tr(e,a,r){for(let n of ss(e)){let i=cs(e,n),o=er(a,i).replace(/\\/g,"/");if(ls(o,r))continue;if(Xa(i).isDirectory())yield*tr(i,a,r);else yield i}}function ko(e){if(e.skipBuild)return;let a=ma(e.projectRoot??process.cwd()),r=e.app.build??fu;for(let n of r)e.onStep?.(`build: ${n}`),ns(n,{stdio:"inherit",cwd:a})}function xo(e,a=[]){let r=ma(e),n=[...hu,yo(),...a],i=[];for(let o of tr(r,r,n)){let c=er(r,o).replace(/\\/g,"/"),u=(Xa(o).mode&73)!==0;i.push({name:c,data:os(o),mode:u?493:420})}return i}function aa(e){let a=ma(e.projectRoot??process.cwd());ko(e),e.onStep?.("packaging application tree");let r=xo(a,e.exclude);if(!r.length)throw Error(`No files to package under ${a}`);let n=Si(r),i=e.app.handlers?.http??"public/index.php";return{zip:n,sha256:is("sha256").update(n).digest("hex"),handlers:{http:i,queue:e.app.handlers?.queue??i,cli:e.app.handlers?.cli??i},fileCount:r.length}}class Rl{optimizations=new Map;imageConfigs=new Map;ssgConfigs=new Map;prerenderConfigs=new Map;counter=0;createAssetOptimization(e){let a=`asset-opt-${Date.now()}-${this.counter++}`,r={id:a,...e};return this.optimizations.set(a,r),r}createImageOptimization(e){let a=`image-opt-${Date.now()}-${this.counter++}`,r={id:a,...e};return this.imageConfigs.set(a,r),r}createSSGConfig(e){let a=`ssg-${Date.now()}-${this.counter++}`,r={id:a,...e};return this.ssgConfigs.set(a,r),r}createPrerenderConfig(e){let a=`prerender-${Date.now()}-${this.counter++}`,r={id:a,...e};return this.prerenderConfigs.set(a,r),r}listOptimizations(){return Array.from(this.optimizations.values())}listImageConfigs(){return Array.from(this.imageConfigs.values())}clear(){this.optimizations.clear(),this.imageConfigs.clear(),this.ssgConfigs.clear(),this.prerenderConfigs.clear()}}var If=new Rl;class Pl{policies=new Map;versioningConfigs=new Map;replicationRules=new Map;tieringConfigs=new Map;objectLocks=new Map;transferAcceleration=new Map;accessPoints=new Map;glacierConfigs=new Map;inventories=new Map;batchOps=new Map;eventNotifications=new Map;counter=0;createLifecyclePolicy(e,a){let r=`lifecycle-${Date.now()}-${this.counter++}`,n={id:r,transitions:e,expiration:a};return this.policies.set(r,n),n}enableVersioning(e=!1){let a=`versioning-${Date.now()}-${this.counter++}`,r={id:a,enabled:!0,mfaDelete:e};return this.versioningConfigs.set(a,r),r}createReplicationRule(e,a,r){let n=`replication-${Date.now()}-${this.counter++}`,i={id:n,sourceRegion:e,destRegion:a,destBucket:r};return this.replicationRules.set(n,i),i}createIntelligentTiering(e,a){let r=`tiering-${Date.now()}-${this.counter++}`,n={id:r,archiveDays:e,deepArchiveDays:a};return this.tieringConfigs.set(r,n),n}enableObjectLock(e){let a=`object-lock-${Date.now()}-${this.counter++}`,r={id:a,bucketName:e.bucketName,mode:e.mode||"COMPLIANCE",retentionDays:e.retentionDays,retentionYears:e.retentionYears,legalHoldEnabled:e.legalHoldEnabled||!1};return this.objectLocks.set(a,r),r}enableTransferAcceleration(e){let a=`transfer-accel-${Date.now()}-${this.counter++}`,r={id:a,bucketName:e,enabled:!0,endpoint:`${e}.s3-accelerate.amazonaws.com`};return this.transferAcceleration.set(a,r),r}createAccessPoint(e){let a=`access-point-${Date.now()}-${this.counter++}`,r={id:a,name:e.name,bucketName:e.bucketName,vpcId:e.vpcId,publicAccessBlock:e.publicAccessBlock!==!1,policy:e.policy};return this.accessPoints.set(a,r),r}createGlacierArchive(e){let a=`glacier-${Date.now()}-${this.counter++}`,r={id:a,bucketName:e.bucketName,archiveType:e.archiveType,transitionDays:e.transitionDays,restoreConfig:e.restoreTier?{tier:e.restoreTier,days:e.restoreDays||7}:void 0};return this.glacierConfigs.set(a,r),r}createInventory(e){let a=`inventory-${Date.now()}-${this.counter++}`,r={id:a,sourceBucket:e.sourceBucket,destinationBucket:e.destinationBucket,schedule:e.schedule||"Daily",format:e.format||"CSV",includedFields:e.includedFields||["Size","LastModifiedDate","StorageClass","ETag"],prefix:e.prefix};return this.inventories.set(a,r),r}createBatchOperation(e){let a=`batch-op-${Date.now()}-${this.counter++}`,r={id:a,operation:e.operation,manifestBucket:e.manifestBucket,manifestKey:e.manifestKey,priority:e.priority||10,status:"pending"};return this.batchOps.set(a,r),r}executeBatchOperation(e){let a=this.batchOps.get(e);if(!a)throw Error(`Batch operation not found: ${e}`);return a.status="in_progress",a.totalObjects=1000,a.processedObjects=0,a}getBatchOperationStatus(e){return this.batchOps.get(e)}createLambdaNotification(e){let a=`event-${Date.now()}-${this.counter++}`,r={id:a,bucketName:e.bucketName,events:e.events,destination:{type:"Lambda",arn:e.lambdaArn},filter:e.prefix||e.suffix?{prefix:e.prefix,suffix:e.suffix}:void 0};return this.eventNotifications.set(a,r),r}createSQSNotification(e){let a=`event-${Date.now()}-${this.counter++}`,r={id:a,bucketName:e.bucketName,events:e.events,destination:{type:"SQS",arn:e.queueArn},filter:e.prefix||e.suffix?{prefix:e.prefix,suffix:e.suffix}:void 0};return this.eventNotifications.set(a,r),r}createSNSNotification(e){let a=`event-${Date.now()}-${this.counter++}`,r={id:a,bucketName:e.bucketName,events:e.events,destination:{type:"SNS",arn:e.topicArn},filter:e.prefix||e.suffix?{prefix:e.prefix,suffix:e.suffix}:void 0};return this.eventNotifications.set(a,r),r}generateObjectLockCF(e){let a={ObjectLockEnabled:"Enabled",ObjectLockConfiguration:{ObjectLockEnabled:"Enabled",Rule:{DefaultRetention:{Mode:e.mode}}}};if(e.retentionDays)a.ObjectLockConfiguration.Rule.DefaultRetention.Days=e.retentionDays;if(e.retentionYears)a.ObjectLockConfiguration.Rule.DefaultRetention.Years=e.retentionYears;return a}generateTransferAccelerationCF(e){return{AccelerateConfiguration:{AccelerationStatus:e.enabled?"Enabled":"Suspended"}}}generateAccessPointCF(e){return{Type:"AWS::S3::AccessPoint",Properties:{Name:e.name,Bucket:e.bucketName,...e.vpcId&&{VpcConfiguration:{VpcId:e.vpcId}},PublicAccessBlockConfiguration:e.publicAccessBlock?{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0}:void 0,...e.policy&&{Policy:e.policy}}}}generateInventoryCF(e){return{Type:"AWS::S3::Bucket",Properties:{InventoryConfigurations:[{Id:e.id,Destination:{BucketArn:`arn:aws:s3:::${e.destinationBucket}`,Format:e.format},Enabled:!0,IncludedObjectVersions:"Current",OptionalFields:e.includedFields,ScheduleFrequency:e.schedule,...e.prefix&&{Prefix:e.prefix}}]}}}generateEventNotificationCF(e){let a=e.destination.type==="Lambda"?"LambdaConfigurations":e.destination.type==="SQS"?"QueueConfigurations":"TopicConfigurations",r=e.destination.type==="Lambda"?"Function":e.destination.type==="SQS"?"Queue":"Topic",n={Event:e.events[0],[r]:e.destination.arn};if(e.filter)n.Filter={S3Key:{Rules:[...e.filter.prefix?[{Name:"prefix",Value:e.filter.prefix}]:[],...e.filter.suffix?[{Name:"suffix",Value:e.filter.suffix}]:[]]}};return{NotificationConfiguration:{[a]:[n]}}}clear(){this.policies.clear(),this.versioningConfigs.clear(),this.replicationRules.clear(),this.tieringConfigs.clear(),this.objectLocks.clear(),this.transferAcceleration.clear(),this.accessPoints.clear(),this.glacierConfigs.clear(),this.inventories.clear(),this.batchOps.clear(),this.eventNotifications.clear()}}var Rf=new Pl;class Nl{checks=new Map;synthetics=new Map;uptimeTrackers=new Map;counter=0;createHealthCheck(e,a=30,r=10){let n=`health-${Date.now()}-${this.counter++}`,i={id:n,url:e,interval:a,timeout:r,status:"healthy"};return this.checks.set(n,i),i}createSyntheticMonitor(e,a,r,n){let i=`synthetic-${Date.now()}-${this.counter++}`,o={id:i,name:e,script:a,frequency:r,locations:n};return this.synthetics.set(i,o),o}trackUptime(e,a,r){let n=`uptime-${Date.now()}-${this.counter++}`,i=a/(a+r)*100,o={id:n,resource:e,uptime:a,downtime:r,availability:i};return this.uptimeTrackers.set(n,o),o}clear(){this.checks.clear(),this.synthetics.clear(),this.uptimeTrackers.clear()}}var Pf=new Nl;class Dl{wafRules=new Map;shieldProtections=new Map;securityGroups=new Map;nacls=new Map;counter=0;createWAFRule(e,a,r,n){let i=`waf-${Date.now()}-${this.counter++}`,o={id:i,name:e,priority:a,action:r,conditions:n};return this.wafRules.set(i,o),o}enableShield(e,a="standard"){let r=`shield-${Date.now()}-${this.counter++}`,n={id:r,resourceArn:e,protectionType:a};return this.shieldProtections.set(r,n),n}createSecurityGroup(e,a,r){let n=`sg-${Date.now()}-${this.counter++}`,i={id:n,name:e,vpcId:a,rules:r};return this.securityGroups.set(n,i),i}createNACL(e,a){let r=`nacl-${Date.now()}-${this.counter++}`,n={id:r,vpcId:e,rules:a};return this.nacls.set(r,n),n}clear(){this.wafRules.clear(),this.shieldProtections.clear(),this.securityGroups.clear(),this.nacls.clear()}}var Nf=new Dl;class kl{strategies=new Map;allocations=new Map;groups=new Map;counter=0;createTaggingStrategy(e,a){let r=`tagging-${Date.now()}-${this.counter++}`,n={id:r,tags:e,resources:a};return this.strategies.set(r,n),n}createCostAllocation(e,a){let r=`cost-${Date.now()}-${this.counter++}`,n={id:r,tagKey:e,allocations:a};return this.allocations.set(r,n),n}createResourceGroup(e,a,r){let n=`group-${Date.now()}-${this.counter++}`,i={id:n,name:e,query:{resourceTypeFilters:a,tagFilters:r}};return this.groups.set(n,i),i}clear(){this.strategies.clear(),this.allocations.clear(),this.groups.clear()}}var Df=new kl;export{Za,oe,ec,cd,Ku,ui,Ju,Xu,Os,Qu,Yu,Zu,ep,tp,rp,np,tc,rc,Ls,Ms,yo,Ye,A,Us,nc,V,wr,C,ld,pi,Bs,Fs,U,So,ip,op,sp,ap,l,s,cp,lp,E,js,Vs,zs,dp,up,Pe,qs,bo,dd,pp,mp,Le,vt,Hs,ic,oc,gp,ud,sc,Ws,vo,To,Me,Se,B,S,_,Ze,D,pd,Tt,pe,Ut,fp,md,be,Eo,Ue,Bt,mi,ve,wo,Ne,gd,gi,Te,Ee,ee,fi,G,Ft,Et,we,t,Co,hp,ac,Gs,yp,Sp,bp,vp,Ks,Tp,Ep,wp,Cp,Ap,Ip,Rp,Pp,Np,Dp,kp,xp,fd,hd,yd,Sd,bd,vd,Td,jt,cc,lc,Cr,hi,_p,dc,$p,Op,rn,Lp,Mp,Up,Bp,Fp,jp,Ed,wd,Cd,Ad,Id,Ao,Vp,Js,Rd,Pd,Nd,uc,Ce,zp,Dd,wt,Io,Ar,kd,pc,xd,_d,$d,mc,De,qp,Hp,Wp,Gp,Od,Kp,Ae,Jp,Xp,Qp,gc,fc,Yp,hc,yc,Zp,em,tm,rm,nm,Ld,Xs,im,om,sm,am,cm,Md,Ud,lm,dm,um,pm,mm,gm,fm,hm,ym,Sc,Qs,Sm,bm,vm,Tm,bc,vc,Tc,Em,Ec,wm,Cm,Am,Im,wc,Rm,Pm,Nm,Dm,km,xm,_m,$m,Bd,Fd,jd,Vd,Cc,Om,Lm,Mm,Um,Bm,Fm,jm,Vm,zm,zd,qd,Hd,Wd,qm,Hm,Ac,Wm,Ic,Rc,Pc,Nc,Gm,Km,Jm,Xm,et,yi,Qm,Ym,Zm,eg,tg,rg,ng,ig,Gd,og,sg,Dc,kc,ag,cg,Kd,lg,dg,ug,pg,mg,gg,fg,hg,yg,Sg,bg,vg,Tg,Eg,wg,Cg,Ag,Ig,Rg,Pg,Ng,xc,Dg,_c,kg,$c,xg,Oc,_g,Lc,$g,nn,Og,Mc,Lg,Ro,Mg,Uc,Ug,Bc,Bg,Fc,Fg,jc,jg,Vc,Vg,on,zg,zc,qg,qc,Hg,Hc,Wg,Wc,Gg,Gc,Kg,Kc,Jg,Jc,Xg,Xc,Qg,Qc,Yg,Yc,Zg,Zc,ef,el,tf,tl,rf,rl,nf,nl,of,il,sf,ol,af,sl,cf,al,lf,cl,df,ll,uf,dl,pf,ul,mf,pl,gf,ml,ff,Jd,Xd,Qd,Yd,gl,hf,fl,yf,hl,Sf,yl,bf,Si,Zd,eu,Po,Ys,sn,tu,No,Vt,Zs,ea,ru,nu,Sl,iu,ta,bl,vf,Tf,ra,na,ia,vl,Do,Tl,El,oa,wl,Cl,Al,ou,su,au,Ef,cu,lu,wf,du,Il,uu,pu,mu,Cf,gu,bi,sa,fu,Af,hu,ko,xo,aa,Rl,If,Pl,Rf,Nl,Pf,Dl,Nf,kl,Df};
|
|
7364
|
+
`}function zi(){return Qa(qi(Hi(import.meta.url)),"runtime-assets")}function bi(){let e=zi(),a=(r)=>Ki(Qa(e,r),"utf-8");return[{path:"bootstrap",contents:a("bootstrap"),mode:493},{path:"tscloud/runtime.php",contents:a("runtime.php"),mode:420},{path:"tscloud/octane-runtime.php",contents:a("octane-runtime.php"),mode:420},{path:"tscloud/cli-runtime.php",contents:a("cli-runtime.php"),mode:420},{path:"tscloud/fastcgi-client.php",contents:a("fastcgi-client.php"),mode:420},{path:"tscloud/php-fpm.conf",contents:gu(),mode:420}]}function sa(e={}){let a=e.cacheDriver??"dynamodb";return{APP_ENV:"production",LOG_CHANNEL:"stderr",CACHE_STORE:a,CACHE_DRIVER:a,SESSION_DRIVER:a,QUEUE_CONNECTION:"sqs",FILESYSTEM_DISK:"s3",VIEW_COMPILED_PATH:"/tmp/storage/framework/views",APP_SERVICES_CACHE:"/tmp/bootstrap/cache/services.php",APP_PACKAGES_CACHE:"/tmp/bootstrap/cache/packages.php",APP_CONFIG_CACHE:"/tmp/bootstrap/cache/config.php",APP_ROUTES_CACHE:"/tmp/bootstrap/cache/routes.php",APP_EVENTS_CACHE:"/tmp/bootstrap/cache/events.php"}}var fu=["composer install --no-dev --optimize-autoloader --no-interaction","php artisan config:cache","php artisan route:cache","php artisan event:cache","php artisan view:cache"];function*Ya(e){for(let a of Zi(e)){let r=Re(e,a);if(Ja(r).isDirectory())yield*Ya(r);else yield r}}function Af(e={}){let a=e.architecture??"x86_64",r=e.platform??(a==="arm64"?"linux/arm64":"linux/amd64"),n=e.onStep??(()=>{}),i=Yi(Re(as(),"tscloud-php-layer-")),o="tscloud-php-layer:build";try{ts(Re(i,"Dockerfile"),iu(e)),n("Building PHP runtime image (docker)"),it("docker",["build","--platform",r,"-t","tscloud-php-layer:build",i],{stdio:"inherit"}),n("Extracting /opt/php from image");let c=it("docker",["create","--platform",r,"tscloud-php-layer:build"],{encoding:"utf-8"}).trim(),u=Re(i,"opt");Ji(u,{recursive:!0});try{it("docker",["cp",`${c}:/opt/php`,Re(u,"php")],{stdio:"inherit"})}finally{it("docker",["rm",c],{stdio:"ignore"})}if(!Qi(Re(u,"php","bin","php")))throw Error("layer build produced no /opt/php/bin/php");let d=[];for(let g of Ya(u)){let h=rs(u,g).replace(/\\/g,"/"),y=Ja(g).mode&73?493:420;d.push({name:h,data:Xi(g),mode:y})}n("Injecting runtime assets");let m=new Set(bi().map((g)=>g.path)),p=d.filter((g)=>!m.has(g.name));for(let g of bi())p.push({name:g.path,data:g.contents,mode:g.mode});return n("Packaging layer ZIP"),{zip:Si(p),architecture:a,fileCount:p.length}}finally{es(i,{recursive:!0,force:!0})}}var hu=[".git",".github","node_modules","tests","storage/logs","storage/framework/cache","storage/framework/sessions","storage/framework/views",".env",".env.local",".vapor",".ts-cloud","dist-lambda"];function ls(e,a){return a.some((r)=>e===r||e.startsWith(`${r}/`))}function*tr(e,a,r){for(let n of ss(e)){let i=cs(e,n),o=er(a,i).replace(/\\/g,"/");if(ls(o,r))continue;if(Xa(i).isDirectory())yield*tr(i,a,r);else yield i}}function ko(e){if(e.skipBuild)return;let a=ma(e.projectRoot??process.cwd()),r=e.app.build??fu;for(let n of r)e.onStep?.(`build: ${n}`),ns(n,{stdio:"inherit",cwd:a})}function _o(e,a=[]){let r=ma(e),n=[...hu,yo(),...a],i=[];for(let o of tr(r,r,n)){let c=er(r,o).replace(/\\/g,"/"),u=(Xa(o).mode&73)!==0;i.push({name:c,data:os(o),mode:u?493:420})}return i}function aa(e){let a=ma(e.projectRoot??process.cwd());ko(e),e.onStep?.("packaging application tree");let r=_o(a,e.exclude);if(!r.length)throw Error(`No files to package under ${a}`);let n=Si(r),i=e.app.handlers?.http??"public/index.php";return{zip:n,sha256:is("sha256").update(n).digest("hex"),handlers:{http:i,queue:e.app.handlers?.queue??i,cli:e.app.handlers?.cli??i},fileCount:r.length}}class Rl{optimizations=new Map;imageConfigs=new Map;ssgConfigs=new Map;prerenderConfigs=new Map;counter=0;createAssetOptimization(e){let a=`asset-opt-${Date.now()}-${this.counter++}`,r={id:a,...e};return this.optimizations.set(a,r),r}createImageOptimization(e){let a=`image-opt-${Date.now()}-${this.counter++}`,r={id:a,...e};return this.imageConfigs.set(a,r),r}createSSGConfig(e){let a=`ssg-${Date.now()}-${this.counter++}`,r={id:a,...e};return this.ssgConfigs.set(a,r),r}createPrerenderConfig(e){let a=`prerender-${Date.now()}-${this.counter++}`,r={id:a,...e};return this.prerenderConfigs.set(a,r),r}listOptimizations(){return Array.from(this.optimizations.values())}listImageConfigs(){return Array.from(this.imageConfigs.values())}clear(){this.optimizations.clear(),this.imageConfigs.clear(),this.ssgConfigs.clear(),this.prerenderConfigs.clear()}}var If=new Rl;class Pl{policies=new Map;versioningConfigs=new Map;replicationRules=new Map;tieringConfigs=new Map;objectLocks=new Map;transferAcceleration=new Map;accessPoints=new Map;glacierConfigs=new Map;inventories=new Map;batchOps=new Map;eventNotifications=new Map;counter=0;createLifecyclePolicy(e,a){let r=`lifecycle-${Date.now()}-${this.counter++}`,n={id:r,transitions:e,expiration:a};return this.policies.set(r,n),n}enableVersioning(e=!1){let a=`versioning-${Date.now()}-${this.counter++}`,r={id:a,enabled:!0,mfaDelete:e};return this.versioningConfigs.set(a,r),r}createReplicationRule(e,a,r){let n=`replication-${Date.now()}-${this.counter++}`,i={id:n,sourceRegion:e,destRegion:a,destBucket:r};return this.replicationRules.set(n,i),i}createIntelligentTiering(e,a){let r=`tiering-${Date.now()}-${this.counter++}`,n={id:r,archiveDays:e,deepArchiveDays:a};return this.tieringConfigs.set(r,n),n}enableObjectLock(e){let a=`object-lock-${Date.now()}-${this.counter++}`,r={id:a,bucketName:e.bucketName,mode:e.mode||"COMPLIANCE",retentionDays:e.retentionDays,retentionYears:e.retentionYears,legalHoldEnabled:e.legalHoldEnabled||!1};return this.objectLocks.set(a,r),r}enableTransferAcceleration(e){let a=`transfer-accel-${Date.now()}-${this.counter++}`,r={id:a,bucketName:e,enabled:!0,endpoint:`${e}.s3-accelerate.amazonaws.com`};return this.transferAcceleration.set(a,r),r}createAccessPoint(e){let a=`access-point-${Date.now()}-${this.counter++}`,r={id:a,name:e.name,bucketName:e.bucketName,vpcId:e.vpcId,publicAccessBlock:e.publicAccessBlock!==!1,policy:e.policy};return this.accessPoints.set(a,r),r}createGlacierArchive(e){let a=`glacier-${Date.now()}-${this.counter++}`,r={id:a,bucketName:e.bucketName,archiveType:e.archiveType,transitionDays:e.transitionDays,restoreConfig:e.restoreTier?{tier:e.restoreTier,days:e.restoreDays||7}:void 0};return this.glacierConfigs.set(a,r),r}createInventory(e){let a=`inventory-${Date.now()}-${this.counter++}`,r={id:a,sourceBucket:e.sourceBucket,destinationBucket:e.destinationBucket,schedule:e.schedule||"Daily",format:e.format||"CSV",includedFields:e.includedFields||["Size","LastModifiedDate","StorageClass","ETag"],prefix:e.prefix};return this.inventories.set(a,r),r}createBatchOperation(e){let a=`batch-op-${Date.now()}-${this.counter++}`,r={id:a,operation:e.operation,manifestBucket:e.manifestBucket,manifestKey:e.manifestKey,priority:e.priority||10,status:"pending"};return this.batchOps.set(a,r),r}executeBatchOperation(e){let a=this.batchOps.get(e);if(!a)throw Error(`Batch operation not found: ${e}`);return a.status="in_progress",a.totalObjects=1000,a.processedObjects=0,a}getBatchOperationStatus(e){return this.batchOps.get(e)}createLambdaNotification(e){let a=`event-${Date.now()}-${this.counter++}`,r={id:a,bucketName:e.bucketName,events:e.events,destination:{type:"Lambda",arn:e.lambdaArn},filter:e.prefix||e.suffix?{prefix:e.prefix,suffix:e.suffix}:void 0};return this.eventNotifications.set(a,r),r}createSQSNotification(e){let a=`event-${Date.now()}-${this.counter++}`,r={id:a,bucketName:e.bucketName,events:e.events,destination:{type:"SQS",arn:e.queueArn},filter:e.prefix||e.suffix?{prefix:e.prefix,suffix:e.suffix}:void 0};return this.eventNotifications.set(a,r),r}createSNSNotification(e){let a=`event-${Date.now()}-${this.counter++}`,r={id:a,bucketName:e.bucketName,events:e.events,destination:{type:"SNS",arn:e.topicArn},filter:e.prefix||e.suffix?{prefix:e.prefix,suffix:e.suffix}:void 0};return this.eventNotifications.set(a,r),r}generateObjectLockCF(e){let a={ObjectLockEnabled:"Enabled",ObjectLockConfiguration:{ObjectLockEnabled:"Enabled",Rule:{DefaultRetention:{Mode:e.mode}}}};if(e.retentionDays)a.ObjectLockConfiguration.Rule.DefaultRetention.Days=e.retentionDays;if(e.retentionYears)a.ObjectLockConfiguration.Rule.DefaultRetention.Years=e.retentionYears;return a}generateTransferAccelerationCF(e){return{AccelerateConfiguration:{AccelerationStatus:e.enabled?"Enabled":"Suspended"}}}generateAccessPointCF(e){return{Type:"AWS::S3::AccessPoint",Properties:{Name:e.name,Bucket:e.bucketName,...e.vpcId&&{VpcConfiguration:{VpcId:e.vpcId}},PublicAccessBlockConfiguration:e.publicAccessBlock?{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0}:void 0,...e.policy&&{Policy:e.policy}}}}generateInventoryCF(e){return{Type:"AWS::S3::Bucket",Properties:{InventoryConfigurations:[{Id:e.id,Destination:{BucketArn:`arn:aws:s3:::${e.destinationBucket}`,Format:e.format},Enabled:!0,IncludedObjectVersions:"Current",OptionalFields:e.includedFields,ScheduleFrequency:e.schedule,...e.prefix&&{Prefix:e.prefix}}]}}}generateEventNotificationCF(e){let a=e.destination.type==="Lambda"?"LambdaConfigurations":e.destination.type==="SQS"?"QueueConfigurations":"TopicConfigurations",r=e.destination.type==="Lambda"?"Function":e.destination.type==="SQS"?"Queue":"Topic",n={Event:e.events[0],[r]:e.destination.arn};if(e.filter)n.Filter={S3Key:{Rules:[...e.filter.prefix?[{Name:"prefix",Value:e.filter.prefix}]:[],...e.filter.suffix?[{Name:"suffix",Value:e.filter.suffix}]:[]]}};return{NotificationConfiguration:{[a]:[n]}}}clear(){this.policies.clear(),this.versioningConfigs.clear(),this.replicationRules.clear(),this.tieringConfigs.clear(),this.objectLocks.clear(),this.transferAcceleration.clear(),this.accessPoints.clear(),this.glacierConfigs.clear(),this.inventories.clear(),this.batchOps.clear(),this.eventNotifications.clear()}}var Rf=new Pl;class Nl{checks=new Map;synthetics=new Map;uptimeTrackers=new Map;counter=0;createHealthCheck(e,a=30,r=10){let n=`health-${Date.now()}-${this.counter++}`,i={id:n,url:e,interval:a,timeout:r,status:"healthy"};return this.checks.set(n,i),i}createSyntheticMonitor(e,a,r,n){let i=`synthetic-${Date.now()}-${this.counter++}`,o={id:i,name:e,script:a,frequency:r,locations:n};return this.synthetics.set(i,o),o}trackUptime(e,a,r){let n=`uptime-${Date.now()}-${this.counter++}`,i=a/(a+r)*100,o={id:n,resource:e,uptime:a,downtime:r,availability:i};return this.uptimeTrackers.set(n,o),o}clear(){this.checks.clear(),this.synthetics.clear(),this.uptimeTrackers.clear()}}var Pf=new Nl;class Dl{wafRules=new Map;shieldProtections=new Map;securityGroups=new Map;nacls=new Map;counter=0;createWAFRule(e,a,r,n){let i=`waf-${Date.now()}-${this.counter++}`,o={id:i,name:e,priority:a,action:r,conditions:n};return this.wafRules.set(i,o),o}enableShield(e,a="standard"){let r=`shield-${Date.now()}-${this.counter++}`,n={id:r,resourceArn:e,protectionType:a};return this.shieldProtections.set(r,n),n}createSecurityGroup(e,a,r){let n=`sg-${Date.now()}-${this.counter++}`,i={id:n,name:e,vpcId:a,rules:r};return this.securityGroups.set(n,i),i}createNACL(e,a){let r=`nacl-${Date.now()}-${this.counter++}`,n={id:r,vpcId:e,rules:a};return this.nacls.set(r,n),n}clear(){this.wafRules.clear(),this.shieldProtections.clear(),this.securityGroups.clear(),this.nacls.clear()}}var Nf=new Dl;class kl{strategies=new Map;allocations=new Map;groups=new Map;counter=0;createTaggingStrategy(e,a){let r=`tagging-${Date.now()}-${this.counter++}`,n={id:r,tags:e,resources:a};return this.strategies.set(r,n),n}createCostAllocation(e,a){let r=`cost-${Date.now()}-${this.counter++}`,n={id:r,tagKey:e,allocations:a};return this.allocations.set(r,n),n}createResourceGroup(e,a,r){let n=`group-${Date.now()}-${this.counter++}`,i={id:n,name:e,query:{resourceTypeFilters:a,tagFilters:r}};return this.groups.set(n,i),i}clear(){this.strategies.clear(),this.allocations.clear(),this.groups.clear()}}var Df=new kl;export{Za,oe,ec,cd,Ku,ui,Ju,Xu,Os,Qu,Yu,Zu,ep,tp,rp,np,tc,rc,Ls,Ms,yo,Ye,A,Us,nc,V,wr,C,ld,pi,Bs,Fs,U,So,ip,op,sp,ap,l,s,cp,lp,E,js,Vs,zs,dp,up,Pe,Hs,bo,dd,pp,mp,Le,vt,qs,ic,oc,gp,ud,sc,Ws,vo,To,Me,Se,B,S,x,Ze,D,pd,Tt,pe,Ut,fp,md,be,Eo,Ue,Bt,mi,ve,wo,Ne,gd,gi,Te,Ee,ee,fi,G,Ft,Et,we,t,Co,hp,ac,Gs,yp,Sp,bp,vp,Ks,Tp,Ep,wp,Cp,Ap,Ip,Rp,Pp,Np,Dp,kp,_p,fd,hd,yd,Sd,bd,vd,Td,jt,cc,lc,Cr,hi,xp,dc,$p,Op,rn,Lp,Mp,Up,Bp,Fp,jp,Ed,wd,Cd,Ad,Id,Ao,Vp,Js,Rd,Pd,Nd,uc,Ce,zp,Dd,wt,Io,Ar,kd,pc,_d,xd,$d,mc,De,Hp,qp,Wp,Gp,Od,Kp,Ae,Jp,Xp,Qp,gc,fc,Yp,hc,yc,Zp,em,tm,rm,nm,Ld,Xs,im,om,sm,am,cm,Md,Ud,lm,dm,um,pm,mm,gm,fm,hm,ym,Sc,Qs,Sm,bm,vm,Tm,bc,vc,Tc,Em,Ec,wm,Cm,Am,Im,wc,Rm,Pm,Nm,Dm,km,_m,xm,$m,Bd,Fd,jd,Vd,Cc,Om,Lm,Mm,Um,Bm,Fm,jm,Vm,zm,zd,Hd,qd,Wd,Hm,qm,Ac,Wm,Ic,Rc,Pc,Nc,Gm,Km,Jm,Xm,et,yi,Qm,Ym,Zm,eg,tg,rg,ng,ig,Gd,og,sg,Dc,kc,ag,cg,Kd,lg,dg,ug,pg,mg,gg,fg,hg,yg,Sg,bg,vg,Tg,Eg,wg,Cg,Ag,Ig,Rg,Pg,Ng,_c,Dg,xc,kg,$c,_g,Oc,xg,Lc,$g,nn,Og,Mc,Lg,Ro,Mg,Uc,Ug,Bc,Bg,Fc,Fg,jc,jg,Vc,Vg,on,zg,zc,Hg,Hc,qg,qc,Wg,Wc,Gg,Gc,Kg,Kc,Jg,Jc,Xg,Xc,Qg,Qc,Yg,Yc,Zg,Zc,ef,el,tf,tl,rf,rl,nf,nl,of,il,sf,ol,af,sl,cf,al,lf,cl,df,ll,uf,dl,pf,ul,mf,pl,gf,ml,ff,Jd,Xd,Qd,Yd,gl,hf,fl,yf,hl,Sf,yl,bf,Si,Zd,eu,Po,Ys,sn,tu,No,Vt,Zs,ea,ru,nu,Sl,iu,ta,bl,vf,Tf,ra,na,ia,vl,Do,Tl,El,oa,wl,Cl,Al,ou,su,au,Ef,cu,lu,wf,du,Il,uu,pu,mu,Cf,gu,bi,sa,fu,Af,hu,ko,_o,aa,Rl,If,Pl,Rf,Nl,Pf,Dl,Nf,kl,Df};
|