@stacksjs/ts-cloud 0.16.68 → 0.16.70
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/bin/chunk-04jkzt83.js +1 -0
- package/dist/bin/chunk-0pptjpck.js +1 -0
- package/dist/bin/chunk-0rb8hp47.js +1 -0
- package/dist/bin/{chunk-zz9nj5kn.js → chunk-1gypqjyd.js} +5 -5
- package/dist/bin/chunk-4c6bmvwq.js +1 -0
- package/dist/bin/{chunk-e4c7ba0g.js → chunk-4w6n5wht.js} +1 -1
- package/dist/bin/chunk-5bsgbfaa.js +1 -0
- package/dist/bin/chunk-6bnxvtvy.js +1 -0
- package/dist/bin/{chunk-d28q9ath.js → chunk-6d80tpq9.js} +2 -2
- package/dist/bin/chunk-6dwj78tg.js +1 -0
- package/dist/bin/{chunk-krt80e8w.js → chunk-6vryg8kw.js} +6 -6
- package/dist/bin/{chunk-v5js5pz6.js → chunk-6wz74ram.js} +79 -79
- package/dist/bin/chunk-7qkc4af5.js +1 -0
- package/dist/bin/chunk-7tvepzyw.js +1 -0
- package/dist/bin/chunk-87ycafdr.js +1 -0
- package/dist/bin/{chunk-w2eezm9z.js → chunk-8cw7a6c7.js} +2 -2
- package/dist/bin/chunk-8cxdvpzy.js +1 -0
- package/dist/bin/chunk-8vm3veyc.js +1 -0
- package/dist/bin/{chunk-b0r8a5h5.js → chunk-9cj1fm00.js} +5 -5
- package/dist/bin/{chunk-1cb0r1j3.js → chunk-9j6040sq.js} +2 -2
- package/dist/bin/{chunk-m92m9tx3.js → chunk-atsg4tw3.js} +115 -115
- package/dist/bin/chunk-axv264y9.js +1 -0
- package/dist/bin/{chunk-zs1cpqhv.js → chunk-b2gmbf1r.js} +2 -2
- package/dist/bin/chunk-b96qbfmt.js +1 -0
- package/dist/bin/{chunk-mjbd4pbz.js → chunk-bgjvxdds.js} +5 -5
- package/dist/bin/chunk-bgm9p3x6.js +1 -0
- package/dist/bin/{chunk-x40sd2m9.js → chunk-bn0c836y.js} +3 -3
- package/dist/bin/chunk-cmraxfxd.js +1 -0
- package/dist/bin/chunk-d5n4d3pj.js +1 -0
- package/dist/bin/{chunk-8escxm7h.js → chunk-dbmtygg1.js} +1 -1
- package/dist/bin/{chunk-jrxb5sg4.js → chunk-e0scvrf7.js} +3 -3
- package/dist/bin/{chunk-2247xk4n.js → chunk-ey3wcb9c.js} +1 -1
- package/dist/bin/{chunk-rgnmxfvp.js → chunk-fmz6qv0v.js} +3 -3
- package/dist/bin/{chunk-abk97qeq.js → chunk-gbbcp2bw.js} +2 -2
- package/dist/bin/{chunk-m60wwxz1.js → chunk-gcz6twdg.js} +4 -4
- package/dist/bin/{chunk-5t1ky9re.js → chunk-h5m9tan5.js} +1 -1
- package/dist/bin/chunk-hyrvmjq0.js +2 -0
- package/dist/bin/chunk-j77zj12s.js +1 -0
- package/dist/bin/chunk-jegvamsc.js +1 -0
- package/dist/bin/{chunk-pgbtdsj2.js → chunk-k61k237r.js} +3 -3
- package/dist/bin/chunk-mrnc8esz.js +1 -0
- package/dist/bin/{chunk-wjn2bpdb.js → chunk-mt8yss58.js} +2 -2
- package/dist/bin/chunk-nxkbvmz2.js +1 -0
- package/dist/bin/chunk-r58k9cj8.js +1 -0
- package/dist/bin/{chunk-gga18c4g.js → chunk-reexpdfk.js} +2 -2
- package/dist/bin/{chunk-5fde4d44.js → chunk-rg6r03q3.js} +1 -1
- package/dist/bin/{chunk-pr96tp0s.js → chunk-rhy7gbt1.js} +2 -2
- package/dist/bin/{chunk-fx9zesgx.js → chunk-rkcr1xth.js} +38 -38
- package/dist/bin/{chunk-5gf0je0v.js → chunk-rqwgs1fs.js} +13 -13
- package/dist/bin/{chunk-qjxd8f5m.js → chunk-rsqzyxmz.js} +5 -5
- package/dist/bin/chunk-s15gpps2.js +1 -0
- package/dist/bin/chunk-sb0v3vej.js +1 -0
- package/dist/bin/{chunk-7y56qyrj.js → chunk-swbb39hj.js} +1 -1
- package/dist/bin/{chunk-55j0x82p.js → chunk-tkj474c6.js} +3 -3
- package/dist/bin/{chunk-sv7n9ape.js → chunk-tx2mh4bw.js} +2 -2
- package/dist/bin/{chunk-qka0e661.js → chunk-vveaxany.js} +4 -4
- package/dist/bin/{chunk-nxsx69p4.js → chunk-w4e696gz.js} +4 -4
- package/dist/bin/{chunk-tdv5rwjv.js → chunk-whryzwb7.js} +1 -1
- package/dist/bin/{chunk-6tqzgm9z.js → chunk-xfr0nfdq.js} +5 -5
- package/dist/bin/{chunk-43a60zkj.js → chunk-xhe84hg1.js} +1 -1
- package/dist/bin/chunk-ywpkvdfg.js +1 -0
- package/dist/bin/{chunk-17ewx21n.js → chunk-zph18vv6.js} +1 -1
- package/dist/bin/cli.js +89 -89
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/bin/stacks-queue-worker.js +1 -1
- package/dist/bin/stacks-scheduler.js +1 -1
- package/dist/{chunk-spr6akra.js → chunk-3nrnbk63.js} +117 -117
- package/dist/{chunk-192rthtb.js → chunk-p9gqv8vt.js} +1 -1
- package/dist/deploy/index.js +1 -1
- package/dist/drivers/index.js +1 -1
- package/dist/drivers/shared/app-frameworks.d.ts +4 -0
- package/dist/drivers/shared/app-services.d.ts +8 -3
- package/dist/drivers/shared/background-bun.d.ts +3 -0
- package/dist/drivers/shared/deploy-script.d.ts +8 -0
- package/dist/index.js +1 -1
- package/dist/ui/404.html +1 -1
- package/dist/ui/accept-invitation.html +1 -1
- package/dist/ui/access-denied.html +1 -1
- package/dist/ui/account/automation.html +6 -6
- package/dist/ui/account/security.html +2 -2
- package/dist/ui/applications/compose.html +6 -6
- package/dist/ui/applications/new.html +1 -1
- package/dist/ui/data/backups.html +6 -6
- package/dist/ui/data/services.html +6 -6
- package/dist/ui/data/volumes.html +6 -6
- package/dist/ui/index.html +6 -6
- package/dist/ui/infrastructure/topology.html +5 -5
- package/dist/ui/integrations.html +2 -2
- package/dist/ui/operations/alerts.html +6 -6
- package/dist/ui/operations/configuration.html +5 -5
- package/dist/ui/operations/jobs.html +5 -5
- package/dist/ui/operations/maintenance.html +6 -6
- package/dist/ui/operations/observability.html +6 -6
- package/dist/ui/operations/previews.html +6 -6
- package/dist/ui/operations/queue.html +6 -6
- package/dist/ui/operations/regions.html +6 -6
- package/dist/ui/operations/releases.html +6 -6
- package/dist/ui/operations/spend.html +6 -6
- package/dist/ui/operations/workloads.html +6 -6
- package/dist/ui/security.html +1 -1
- package/dist/ui/server/actions.html +6 -6
- package/dist/ui/server/activity.html +2 -2
- package/dist/ui/server/capacity.html +6 -6
- package/dist/ui/server/database.html +6 -6
- package/dist/ui/server/deployments.html +6 -6
- package/dist/ui/server/diagnostics.html +2 -2
- package/dist/ui/server/firewall.html +6 -6
- package/dist/ui/server/fleet.html +6 -6
- package/dist/ui/server/logs.html +6 -6
- package/dist/ui/server/metrics.html +6 -6
- package/dist/ui/server/security.html +2 -2
- package/dist/ui/server/services.html +1 -1
- 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 +1 -1
- package/dist/ui/serverless/functions.html +6 -6
- package/dist/ui/serverless/logs.html +6 -6
- package/dist/ui/serverless/metrics.html +2 -2
- package/dist/ui/serverless/queues.html +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-19dhvnjh.js +0 -1
- package/dist/bin/chunk-1tk64amh.js +0 -1
- package/dist/bin/chunk-37xeqae4.js +0 -1
- package/dist/bin/chunk-4vz5erjz.js +0 -1
- package/dist/bin/chunk-6cyr6gcg.js +0 -1
- package/dist/bin/chunk-6rwewb7j.js +0 -1
- package/dist/bin/chunk-7d83f6sn.js +0 -1
- package/dist/bin/chunk-bkvxzenb.js +0 -1
- package/dist/bin/chunk-dmm1p4bs.js +0 -1
- package/dist/bin/chunk-dycx66c7.js +0 -1
- package/dist/bin/chunk-fjx816tt.js +0 -1
- package/dist/bin/chunk-gmy8p7nr.js +0 -1
- package/dist/bin/chunk-h5ccvped.js +0 -1
- package/dist/bin/chunk-h9h9dn0r.js +0 -1
- package/dist/bin/chunk-ht6s2cwm.js +0 -1
- package/dist/bin/chunk-ncr1dwdt.js +0 -1
- package/dist/bin/chunk-nzhpva7z.js +0 -1
- package/dist/bin/chunk-p40tvp17.js +0 -1
- package/dist/bin/chunk-qe8zh9kn.js +0 -1
- package/dist/bin/chunk-sn1zde06.js +0 -1
- package/dist/bin/chunk-t6zpvaqr.js +0 -1
- package/dist/bin/chunk-v4ncs6q2.js +0 -1
- package/dist/bin/chunk-vrn0akcn.js +0 -1
- package/dist/bin/chunk-x00efaxm.js +0 -1
- package/dist/bin/chunk-zred4827.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{mt}from"./chunk-ey3wcb9c.js";import"./chunk-9cj1fm00.js";export{mt as STSClient};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function
|
|
2
|
-
export{
|
|
1
|
+
function vs(n){let t=new RegExp("[\\u007F-\\uFFFF]","g");return JSON.stringify(n).replace(t,(o)=>`\\u${o.charCodeAt(0).toString(16).padStart(4,"0")}`)}
|
|
2
|
+
export{vs};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{vs}from"./chunk-b2gmbf1r.js";export{vs as encodeDashboardPayload};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var q;try{q=await import("node:crypto")}catch{}var v=new Map,Q=100,ee={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"};function
|
|
1
|
+
var q;try{q=await import("node:crypto")}catch{}var v=new Map,Q=100,ee={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"};function lc(e){let n=typeof e==="string"?new URL(e):e,{hostname:t,pathname:s}=n;if(t.endsWith(".on.aws")){let a=t.match(/^[^.]+\.lambda-url\.([^.]+)\.on\.aws$/);if(a)return{service:"lambda",region:a[1]};return{service:"",region:""}}if(t.endsWith(".r2.cloudflarestorage.com"))return{service:"s3",region:"auto"};if(t.endsWith(".backblazeb2.com")){let a=t.match(/^(?:[^.]+\.)?s3\.([^.]+)\.backblazeb2\.com$/);if(a)return{service:"s3",region:a[1]};return{service:"",region:""}}let c=t.replace("dualstack.","").match(/([^.]+)\.(?:([^.]+)\.)?amazonaws\.com(?:\.cn)?$/);if(!c)return{service:"",region:""};let r=c[1],i=c[2]||"";if(i==="us-gov")i="us-gov-west-1";else if(i==="s3"||i==="s3-accelerate")i="us-east-1",r="s3";else if(r==="iot")if(t.startsWith("iot."))r="execute-api";else if(t.startsWith("data.jobs.iot."))r="iot-jobs-data";else r=s==="/mqtt"?"iotdevicegateway":"iotdata";else if(r==="autoscaling");else if(!i&&r.startsWith("s3-"))i=r.slice(3).replace(/^fips-|^external-1/,""),r="s3";else if(r.endsWith("-fips"))r=r.slice(0,-5);else if(i&&/-\d$/.test(r)&&!/-\d$/.test(i))[r,i]=[i,r];return r=ee[r]||r,{service:r,region:i||"us-east-1"}}function Y(e){let{method:n,url:t,body:s="",accessKeyId:c,secretAccessKey:r,sessionToken:i,signQuery:a=!1,expiresIn:h=86400,datetime:m}=e,d=new URL(t),f=d.hostname,p=lc(d),u=e.service||p.service,g=e.region||p.region;if(!u)throw Error("Could not detect service from URL. Please provide service explicitly.");if(!g)throw Error("Could not detect region from URL. Please provide region explicitly.");let o=m||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),y=o.substring(0,8),S=[y,g,u,"aws4_request"].join("/"),b="AWS4-HMAC-SHA256";if(a)return te({urlObj:d,method:n,body:s,accessKeyId:c,secretAccessKey:r,sessionToken:i,service:u,region:g,timestamp:o,date:y,credentialScope:S,algorithm:b,expiresIn:h,cache:e.cache});let A=d.pathname||"/",x=I(d.searchParams),l={host:f,"x-amz-date":o,...e.headers};if(i)l["x-amz-security-token"]=i;let R=Object.keys(l).some((D)=>D.toLowerCase()==="content-type");if(s&&!R)l["content-type"]="application/x-amz-json-1.0";if(u==="s3"&&!l["x-amz-content-sha256"])l["x-amz-content-sha256"]=E(s);let P=_(l),w=N(l),U=l["x-amz-content-sha256"]||E(s),O=[n,j(A),x,P,w,U].join(`
|
|
2
2
|
`),M=E(O),K=[b,o,S,M].join(`
|
|
3
|
-
`),W=e.cache??v,L=J(r,y,g,u,K,W),X=[`${b} Credential=${c}/${S}`,`SignedHeaders=${w}`,`Signature=${L}`].join(", ");return l.authorization=X,{url:t,method:n,headers:l,body:s||void 0}}async function
|
|
3
|
+
`),W=e.cache??v,L=J(r,y,g,u,K,W),X=[`${b} Credential=${c}/${S}`,`SignedHeaders=${w}`,`Signature=${L}`].join(", ");return l.authorization=X,{url:t,method:n,headers:l,body:s||void 0}}async function dc(e){let{method:n,url:t,body:s="",accessKeyId:c,secretAccessKey:r,sessionToken:i,signQuery:a=!1,expiresIn:h=86400,datetime:m}=e,d=new URL(t),f=d.hostname,p=lc(d),u=e.service||p.service,g=e.region||p.region;if(!u)throw Error("Could not detect service from URL. Please provide service explicitly.");if(!g)throw Error("Could not detect region from URL. Please provide region explicitly.");let o=m||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),y=o.substring(0,8),S=[y,g,u,"aws4_request"].join("/"),b="AWS4-HMAC-SHA256";if(a)return ne({urlObj:d,method:n,body:s,accessKeyId:c,secretAccessKey:r,sessionToken:i,service:u,region:g,timestamp:o,date:y,credentialScope:S,algorithm:b,expiresIn:h,cache:e.cache});let A=d.pathname||"/",x=I(d.searchParams),l={host:f,"x-amz-date":o,...e.headers};if(i)l["x-amz-security-token"]=i;let R=Object.keys(l).some((F)=>F.toLowerCase()==="content-type");if(s&&!R)l["content-type"]="application/x-amz-json-1.0";let P=await k(s);if(u==="s3"&&!l["x-amz-content-sha256"])l["x-amz-content-sha256"]=P;let w=_(l),U=N(l),O=l["x-amz-content-sha256"]||P,M=[n,j(A),x,w,U,O].join(`
|
|
4
4
|
`),K=await k(M),W=[b,o,S,K].join(`
|
|
5
5
|
`),L=e.cache??v,X=await V(r,y,g,u,W,L),D=[`${b} Credential=${c}/${S}`,`SignedHeaders=${U}`,`Signature=${X}`].join(", ");return l.authorization=D,{url:t,method:n,headers:l,body:s||void 0}}function te(e){let{urlObj:n,method:t,body:s,accessKeyId:c,secretAccessKey:r,sessionToken:i,service:a,region:h,timestamp:m,date:d,credentialScope:f,algorithm:p,expiresIn:u,cache:g}=e,o=new URL(n.toString());o.searchParams.set("X-Amz-Algorithm",p),o.searchParams.set("X-Amz-Credential",`${c}/${f}`),o.searchParams.set("X-Amz-Date",m),o.searchParams.set("X-Amz-Expires",String(u));let y=a==="s3"?"UNSIGNED-PAYLOAD":E(s);if(a==="s3")o.searchParams.set("X-Amz-Content-Sha256",y);let S="host";if(o.searchParams.set("X-Amz-SignedHeaders",S),i)o.searchParams.set("X-Amz-Security-Token",i);let b=j(o.pathname||"/"),A=`host:${o.hostname}
|
|
6
6
|
`,x=I(o.searchParams),l=[t,b,x,A,S,y].join(`
|
|
@@ -8,7 +8,7 @@ var q;try{q=await import("node:crypto")}catch{}var v=new Map,Q=100,ee={appstream
|
|
|
8
8
|
`),w=J(r,d,h,a,R,g??v);return o.searchParams.set("X-Amz-Signature",w),{url:o.toString(),method:t,headers:{},body:s||void 0}}async function ne(e){let{urlObj:n,method:t,body:s,accessKeyId:c,secretAccessKey:r,sessionToken:i,service:a,region:h,timestamp:m,date:d,credentialScope:f,algorithm:p,expiresIn:u,cache:g}=e,o=new URL(n.toString());o.searchParams.set("X-Amz-Algorithm",p),o.searchParams.set("X-Amz-Credential",`${c}/${f}`),o.searchParams.set("X-Amz-Date",m),o.searchParams.set("X-Amz-Expires",String(u));let y=a==="s3"?"UNSIGNED-PAYLOAD":await k(s);if(a==="s3")o.searchParams.set("X-Amz-Content-Sha256",y);let S="host";if(o.searchParams.set("X-Amz-SignedHeaders",S),i)o.searchParams.set("X-Amz-Security-Token",i);let b=j(o.pathname||"/"),A=`host:${o.hostname}
|
|
9
9
|
`,x=I(o.searchParams),l=[t,b,x,A,S,y].join(`
|
|
10
10
|
`),R=[p,m,f,await k(l)].join(`
|
|
11
|
-
`),w=await V(r,d,h,a,R,g??v);return o.searchParams.set("X-Amz-Signature",w),{url:o.toString(),method:t,headers:{},body:s||void 0}}function
|
|
11
|
+
`),w=await V(r,d,h,a,R,g??v);return o.searchParams.set("X-Amz-Signature",w),{url:o.toString(),method:t,headers:{},body:s||void 0}}function cs(e){let{url:n,method:t="GET",expiresIn:s=3600,...c}=e,r=Math.min(s,604800);return Y({...c,url:n,method:t,signQuery:!0,expiresIn:r}).url}async function xp(e){let{url:n,method:t="GET",expiresIn:s=3600,...c}=e,r=Math.min(s,604800);return(await dc({...c,url:n,method:t,signQuery:!0,expiresIn:r})).url}function _(e){return Object.keys(e).sort().map((n)=>`${n.toLowerCase()}:${e[n].trim().replace(/\s+/g," ")}`).join(`
|
|
12
12
|
`)+`
|
|
13
|
-
`}function N(e){return Object.keys(e).sort().map((n)=>n.toLowerCase()).join(";")}function I(e){let n=[];return e.forEach((t,s)=>{n.push([B(s),B(t)])}),n.sort((t,s)=>{if(t[0]<s[0])return-1;if(t[0]>s[0])return 1;if(t[1]<s[1])return-1;if(t[1]>s[1])return 1;return 0}),n.map(([t,s])=>`${t}=${s}`).join("&")}function j(e){return e.split("/").map((n)=>B(n)).join("/")}function B(e){return encodeURIComponent(e).replace(/[!'()*]/g,(n)=>`%${n.charCodeAt(0).toString(16).toUpperCase()}`)}function E(e){if(!q)throw Error("Synchronous hash not available in browser. Use signRequestAsync() instead.");return q.createHash("sha256").update(e,"utf8").digest("hex")}function C(e,n){if(!q)throw Error("Synchronous hmac not available in browser. Use signRequestAsync() instead.");return q.createHmac("sha256",e).update(n,"utf8").digest()}async function k(e){let t=new TextEncoder().encode(e),s=await crypto.subtle.digest("SHA-256",t);return G(new Uint8Array(s))}async function z(e,n){let t=new TextEncoder,s=typeof e==="string"?t.encode(e):e,c=t.encode(n),r=await crypto.subtle.importKey("raw",s.buffer,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),i=await crypto.subtle.sign("HMAC",r,c.buffer);return new Uint8Array(i)}function G(e){return Array.from(e).map((n)=>n.toString(16).padStart(2,"0")).join("")}function J(e,n,t,s,c,r){let i=`${e}:${n}:${t}:${s}`,a=r.get(i);if(!a){let h=C(`AWS4${e}`,n),m=C(h,t),d=C(m,s);if(a=C(d,"aws4_request"),r.size>=Q){let f=r.keys().next().value;if(f)r.delete(f)}r.set(i,a)}return C(a,c).toString("hex")}async function V(e,n,t,s,c,r){let i=`${e}:${n}:${t}:${s}`,a=r.get(i);if(!a){let m=await z(`AWS4${e}`,n),d=await z(m,t),f=await z(d,s);if(a=await z(f,"aws4_request"),r.size>=Q){let p=r.keys().next().value;if(p)r.delete(p)}r.set(i,a)}let h=await z(a,c);return G(h)}function Z(e,n){return n.includes(e)}function T(e,n,t){let s=n*Math.pow(2,e),c=Math.random()*0.3*s;return Math.min(s+c,t)}function H(e){return new Promise((n)=>setTimeout(n,e))}async function _t(e,n){let{maxRetries:t=3,initialDelayMs:s=100,maxDelayMs:c=5000,retryableStatusCodes:r=[429,500,502,503,504],timeoutMs:i=30000}=n??{},a,h;for(let m=0;m<=t;m++){let d=Y(e),f={method:d.method,headers:d.headers};if(d.body)f.body=d.body;let p=new AbortController,u=setTimeout(()=>p.abort(),i);f.signal=p.signal;try{let g=await fetch(d.url,f);if(clearTimeout(u),h=g,g.ok)return g;if(m<t&&Z(g.status,r)){let y=T(m,s,c);await H(y);continue}let o=await g.text();throw Error(`AWS API request failed (${g.status}): ${o}`)}catch(g){if(clearTimeout(u),a=g,g instanceof Error&&g.name==="AbortError")a=Error(`Request timed out after ${i}ms`);if(m<t&&!(g instanceof Error&&g.message.includes("AWS API request failed"))){let o=T(m,s,c);await H(o);continue}throw a}}throw a??Error("Request failed after retries")}async function
|
|
14
|
-
export{
|
|
13
|
+
`}function N(e){return Object.keys(e).sort().map((n)=>n.toLowerCase()).join(";")}function I(e){let n=[];return e.forEach((t,s)=>{n.push([B(s),B(t)])}),n.sort((t,s)=>{if(t[0]<s[0])return-1;if(t[0]>s[0])return 1;if(t[1]<s[1])return-1;if(t[1]>s[1])return 1;return 0}),n.map(([t,s])=>`${t}=${s}`).join("&")}function j(e){return e.split("/").map((n)=>B(n)).join("/")}function B(e){return encodeURIComponent(e).replace(/[!'()*]/g,(n)=>`%${n.charCodeAt(0).toString(16).toUpperCase()}`)}function E(e){if(!q)throw Error("Synchronous hash not available in browser. Use signRequestAsync() instead.");return q.createHash("sha256").update(e,"utf8").digest("hex")}function C(e,n){if(!q)throw Error("Synchronous hmac not available in browser. Use signRequestAsync() instead.");return q.createHmac("sha256",e).update(n,"utf8").digest()}async function k(e){let t=new TextEncoder().encode(e),s=await crypto.subtle.digest("SHA-256",t);return G(new Uint8Array(s))}async function z(e,n){let t=new TextEncoder,s=typeof e==="string"?t.encode(e):e,c=t.encode(n),r=await crypto.subtle.importKey("raw",s.buffer,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),i=await crypto.subtle.sign("HMAC",r,c.buffer);return new Uint8Array(i)}function G(e){return Array.from(e).map((n)=>n.toString(16).padStart(2,"0")).join("")}function J(e,n,t,s,c,r){let i=`${e}:${n}:${t}:${s}`,a=r.get(i);if(!a){let h=C(`AWS4${e}`,n),m=C(h,t),d=C(m,s);if(a=C(d,"aws4_request"),r.size>=Q){let f=r.keys().next().value;if(f)r.delete(f)}r.set(i,a)}return C(a,c).toString("hex")}async function V(e,n,t,s,c,r){let i=`${e}:${n}:${t}:${s}`,a=r.get(i);if(!a){let m=await z(`AWS4${e}`,n),d=await z(m,t),f=await z(d,s);if(a=await z(f,"aws4_request"),r.size>=Q){let p=r.keys().next().value;if(p)r.delete(p)}r.set(i,a)}let h=await z(a,c);return G(h)}function Z(e,n){return n.includes(e)}function T(e,n,t){let s=n*Math.pow(2,e),c=Math.random()*0.3*s;return Math.min(s+c,t)}function H(e){return new Promise((n)=>setTimeout(n,e))}async function _t(e,n){let{maxRetries:t=3,initialDelayMs:s=100,maxDelayMs:c=5000,retryableStatusCodes:r=[429,500,502,503,504],timeoutMs:i=30000}=n??{},a,h;for(let m=0;m<=t;m++){let d=Y(e),f={method:d.method,headers:d.headers};if(d.body)f.body=d.body;let p=new AbortController,u=setTimeout(()=>p.abort(),i);f.signal=p.signal;try{let g=await fetch(d.url,f);if(clearTimeout(u),h=g,g.ok)return g;if(m<t&&Z(g.status,r)){let y=T(m,s,c);await H(y);continue}let o=await g.text();throw Error(`AWS API request failed (${g.status}): ${o}`)}catch(g){if(clearTimeout(u),a=g,g instanceof Error&&g.name==="AbortError")a=Error(`Request timed out after ${i}ms`);if(m<t&&!(g instanceof Error&&g.message.includes("AWS API request failed"))){let o=T(m,s,c);await H(o);continue}throw a}}throw a??Error("Request failed after retries")}async function _p(e){return _t(e,{maxRetries:0})}async function Op(e,n){let{maxRetries:t=3,initialDelayMs:s=100,maxDelayMs:c=5000,retryableStatusCodes:r=[429,500,502,503,504],timeoutMs:i=30000}=n??{},a;for(let h=0;h<=t;h++){let m=await dc(e),d={method:m.method,headers:m.headers};if(m.body)d.body=m.body;let f=new AbortController,p=setTimeout(()=>f.abort(),i);d.signal=f.signal;try{let u=await fetch(m.url,d);if(clearTimeout(p),u.ok)return u;if(h<t&&Z(u.status,r)){let o=T(h,s,c);await H(o);continue}let g=await u.text();throw Error(`AWS API request failed (${u.status}): ${g}`)}catch(u){if(clearTimeout(p),a=u,u instanceof Error&&u.name==="AbortError")a=Error(`Request timed out after ${i}ms`);if(h<t&&!(u instanceof Error&&u.message.includes("AWS API request failed"))){let g=T(h,s,c);await H(g);continue}throw a}}throw a??Error("Request failed after retries")}async function Nn(e){let n=await e.text(),t={},s=/<(\w+)>([^<]+)<\/\1>/g,c;while((c=s.exec(n))!==null){let[,r,i]=c;t[r]=i}return t}async function $p(e){return await e.json()}function Lp(){v.clear()}function Mp(){return v.size}function Up(){return q!==void 0}function Bp(){return typeof crypto<"u"&&typeof crypto.subtle<"u"}
|
|
14
|
+
export{lc,Y,dc,cs,xp,_t,_p,Op,Nn,$p,Lp,Mp,Up,Bp};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{v}from"./chunk-rg6r03q3.js";import"./chunk-9cj1fm00.js";export{v as CloudFormationClient};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{J,w,D,Oi,
|
|
2
|
-
`),s=r==="root"?'bash -l "$TS_CLOUD_RECIPE"':`runuser -l ${g(r)} -c "bash $TS_CLOUD_RECIPE"`;return["set -uo pipefail",`echo "__TS_CLOUD_RECIPE_BEGIN__ ${e.name} (user=${r})"`,"TS_CLOUD_RECIPE=$(mktemp)",`cat > "$TS_CLOUD_RECIPE" <<'TS_CLOUD_RECIPE_EOF'`,t,"TS_CLOUD_RECIPE_EOF",'chmod +r "$TS_CLOUD_RECIPE"',s,"TS_CLOUD_RC=$?",'rm -f "$TS_CLOUD_RECIPE"',`echo "__TS_CLOUD_RECIPE_END__ ${e.name} exit=$TS_CLOUD_RC"`,"exit $TS_CLOUD_RC"]}var c={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};async function u(e){return await e.driver.findComputeTargets({slug:e.slug,environment:e.environment,role:e.role||"app"})}async function
|
|
3
|
-
export{
|
|
1
|
+
import{J,w,D,Oi,Zs,Wt,Yc,Zc}from"./chunk-gcz6twdg.js";function g(e){return`'${e.split("'").join("'\\''")}'`}function p(e){let r=e.user||"root",t=e.script.join(`
|
|
2
|
+
`),s=r==="root"?'bash -l "$TS_CLOUD_RECIPE"':`runuser -l ${g(r)} -c "bash $TS_CLOUD_RECIPE"`;return["set -uo pipefail",`echo "__TS_CLOUD_RECIPE_BEGIN__ ${e.name} (user=${r})"`,"TS_CLOUD_RECIPE=$(mktemp)",`cat > "$TS_CLOUD_RECIPE" <<'TS_CLOUD_RECIPE_EOF'`,t,"TS_CLOUD_RECIPE_EOF",'chmod +r "$TS_CLOUD_RECIPE"',s,"TS_CLOUD_RC=$?",'rm -f "$TS_CLOUD_RECIPE"',`echo "__TS_CLOUD_RECIPE_END__ ${e.name} exit=$TS_CLOUD_RC"`,"exit $TS_CLOUD_RC"]}var c={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};async function u(e){return await e.driver.findComputeTargets({slug:e.slug,environment:e.environment,role:e.role||"app"})}async function Ks(e,r){let t=e.logger||c,s=await u(e);if(s.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};let n=J(e.slug,r.siteName),o=Wt(n,r.to||"unused"),a=r.onlyIfLive?f(o.current,r.siteName,r.onlyIfLive):[];if(r.dryRun){let l=await e.driver.runRemoteDeploy({targets:s,commands:["set -uo pipefail",...a,...Yc(o,r.to?{to:r.to}:{})],comment:`ts-cloud rollback plan ${e.slug}/${r.siteName}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});return{success:l.success,error:l.error,perInstance:l.perInstance}}let m=["set -euo pipefail",...a,...Zc(o,{...r.to?{to:r.to}:{},unitBase:`${e.slug}-${r.siteName}`})];if(r.site&&w(r.site)==="server-php")m.push(`(cd ${D} && pantry restart php-fpm)`,`if [ -f ${o.current}/artisan ]; then (cd ${o.current} && TS_CLOUD_RB_ENV=$(cd ${D} && pantry env) && eval "$TS_CLOUD_RB_ENV" && php artisan queue:restart); fi`);t.step(`Rolling back ${r.siteName}${r.to?` to ${r.to}`:" to the previous release"} on ${s.length} server(s)...`);let i=await e.driver.runRemoteDeploy({targets:s,commands:m,comment:`ts-cloud rollback ${e.slug}/${r.siteName}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});if(!i.success)t.error(`Rollback failed: ${i.error||"unknown error"}`);else t.success(`Rolled back ${r.siteName}.`);return{success:i.success,error:i.error,perInstance:i.perInstance}}function f(e,r,t){let s=t.replace(/[^0-9A-Za-z._-]/g,"");return[`TS_CLOUD_LIVE_ID=$(basename "$(readlink -f ${e} 2>/dev/null)" 2>/dev/null || true)`,`if [ -z "$TS_CLOUD_LIVE_ID" ] || [ "$TS_CLOUD_LIVE_ID" = "." ]; then echo "${r}: no live release here; left alone"; exit 0; fi`,`case "${s}" in "$TS_CLOUD_LIVE_ID"*) ;; *) echo "${r} serves $TS_CLOUD_LIVE_ID, not ${s}; left alone"; exit 0 ;; esac`]}async function bm(e,r){let t=await u(e);if(t.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};let s=Zs(J(e.slug,r.siteName)),n=Math.max(1,r.limit??20),o=[`[ -f ${s} ] && tail -n ${n} ${s} || echo "no deploy history for ${r.siteName}"`],a=await e.driver.runRemoteDeploy({targets:t,commands:o,comment:`ts-cloud deploy:history ${e.slug}/${r.siteName}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});return{success:a.success,error:a.error,perInstance:a.perInstance}}async function Sm(e,r){let t=e.logger||c,s=await u(e);if(s.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};t.step(`Running recipe '${r.name}' as ${r.user||"root"} on ${s.length} server(s)...`);let n=await e.driver.runRemoteDeploy({targets:s,commands:p({name:r.name,script:r.script,user:r.user}),comment:`ts-cloud recipe ${r.name}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});if(!n.success)t.error(`Recipe '${r.name}' failed: ${n.error||"unknown error"}`);else t.success(`Recipe '${r.name}' completed.`);return{success:n.success,error:n.error,perInstance:n.perInstance}}async function Js(e,r){let t=e.logger||c;if(!r.database?.name)return{success:!1,error:"No appDatabase configured to restore."};let s=await u(e);if(s.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};t.step(`Restoring database '${r.database.name}'${r.from?` from ${r.from}`:" from the latest backup"} on ${s.length} server(s)...`);let n=await e.driver.runRemoteDeploy({targets:s,commands:Oi(r.database,{from:r.from}),comment:`ts-cloud db:restore ${e.slug}/${r.database.name}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});if(!n.success)t.error(`Restore failed: ${n.error||"unknown error"}`);else t.success(`Restored ${r.database.name}.`);return{success:n.success,error:n.error,perInstance:n.perInstance}}
|
|
3
|
+
export{Ks,bm,Sm,Js};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Q}from"./chunk-whryzwb7.js";import"./chunk-9cj1fm00.js";export{Q as EC2Client};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{fe}from"./chunk-xhe84hg1.js";import"./chunk-9cj1fm00.js";export{fe as RDSClient};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{p}from"./chunk-
|
|
1
|
+
import{p}from"./chunk-9cj1fm00.js";class Ct{client;region;constructor(e="us-east-1",r){this.region=e,this.client=new p(void 0,{profile:r})}async createRepository(e){let r={repositoryName:e.repositoryName};if(e.imageTagMutability)r.imageTagMutability=e.imageTagMutability;if(e.imageScanningConfiguration)r.imageScanningConfiguration=e.imageScanningConfiguration;if(e.encryptionConfiguration)r.encryptionConfiguration=e.encryptionConfiguration;if(e.tags&&e.tags.length>0)r.tags=e.tags;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.CreateRepository","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{repository:t.repository?this.parseRepository(t.repository):void 0}}async describeRepositories(e){let r={};if(e?.repositoryNames&&e.repositoryNames.length>0)r.repositoryNames=e.repositoryNames;if(e?.registryId)r.registryId=e.registryId;if(e?.maxResults)r.maxResults=e.maxResults;if(e?.nextToken)r.nextToken=e.nextToken;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.DescribeRepositories","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{repositories:t.repositories?.map((i)=>this.parseRepository(i)),nextToken:t.nextToken}}async getAuthorizationToken(e){let r={};if(e&&e.length>0)r.registryIds=e;return{authorizationData:(await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.GetAuthorizationToken","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)})).authorizationData?.map((i)=>({authorizationToken:i.authorizationToken,expiresAt:i.expiresAt,proxyEndpoint:i.proxyEndpoint}))}}async deleteRepository(e){let r={repositoryName:e.repositoryName};if(e.registryId)r.registryId=e.registryId;if(e.force!==void 0)r.force=e.force;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.DeleteRepository","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{repository:t.repository?this.parseRepository(t.repository):void 0}}async describeImages(e){let r={repositoryName:e.repositoryName};if(e.registryId)r.registryId=e.registryId;if(e.imageIds&&e.imageIds.length>0)r.imageIds=e.imageIds;if(e.filter)r.filter=e.filter;if(e.maxResults)r.maxResults=e.maxResults;if(e.nextToken)r.nextToken=e.nextToken;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.DescribeImages","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{imageDetails:t.imageDetails?.map((i)=>this.parseImageDetail(i)),nextToken:t.nextToken}}async batchDeleteImage(e){let r={repositoryName:e.repositoryName,imageIds:e.imageIds};if(e.registryId)r.registryId=e.registryId;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.BatchDeleteImage","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{imageIds:t.imageIds,failures:t.failures}}async putLifecyclePolicy(e){let r={repositoryName:e.repositoryName,lifecyclePolicyText:e.lifecyclePolicyText};if(e.registryId)r.registryId=e.registryId;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.PutLifecyclePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{registryId:t.registryId,repositoryName:t.repositoryName,lifecyclePolicyText:t.lifecyclePolicyText}}async getLifecyclePolicy(e){let r={repositoryName:e.repositoryName};if(e.registryId)r.registryId=e.registryId;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.GetLifecyclePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{registryId:t.registryId,repositoryName:t.repositoryName,lifecyclePolicyText:t.lifecyclePolicyText,lastEvaluatedAt:t.lastEvaluatedAt}}async setRepositoryPolicy(e){let r={repositoryName:e.repositoryName,policyText:e.policyText};if(e.registryId)r.registryId=e.registryId;if(e.force!==void 0)r.force=e.force;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.SetRepositoryPolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{registryId:t.registryId,repositoryName:t.repositoryName,policyText:t.policyText}}async getRepositoryPolicy(e){let r={repositoryName:e.repositoryName};if(e.registryId)r.registryId=e.registryId;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.GetRepositoryPolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{registryId:t.registryId,repositoryName:t.repositoryName,policyText:t.policyText}}async tagResource(e){let r={resourceArn:e.resourceArn,tags:e.tags};await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.TagResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)})}async listTagsForResource(e){let r={resourceArn:e};return{tags:(await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.ListTagsForResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)})).tags}}createLifecyclePolicyText(e){return JSON.stringify({rules:e.map((r)=>({rulePriority:r.rulePriority,description:r.description,selection:r.selection,action:r.action}))})}async getDockerLoginCommand(){let e=await this.getAuthorizationToken();if(!e.authorizationData?.[0])throw Error("Failed to get authorization token");let r=e.authorizationData[0],t=r.authorizationToken||"",i=r.proxyEndpoint||"";return`echo "${Buffer.from(t,"base64").toString("utf8").split(":")[1]}" | docker login --username AWS --password-stdin ${i}`}getRegistryUri(e){return`${e}.dkr.ecr.${this.region}.amazonaws.com`}parseRepository(e){return{repositoryArn:e.repositoryArn,registryId:e.registryId,repositoryName:e.repositoryName,repositoryUri:e.repositoryUri,createdAt:e.createdAt,imageTagMutability:e.imageTagMutability,imageScanningConfiguration:e.imageScanningConfiguration,encryptionConfiguration:e.encryptionConfiguration}}parseImageDetail(e){return{registryId:e.registryId,repositoryName:e.repositoryName,imageDigest:e.imageDigest,imageTags:e.imageTags,imageSizeInBytes:e.imageSizeInBytes,imagePushedAt:e.imagePushedAt,imageScanStatus:e.imageScanStatus,imageScanFindingsSummary:e.imageScanFindingsSummary}}}
|
|
2
2
|
export{Ct};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{p}from"./chunk-b0r8a5h5.js";import{$e,ya,Ui,Ja,Dn,Wi,Xa,Qa,oc,sc}from"./chunk-v5js5pz6.js";import{n,r,a,e,u,i,Ee}from"./chunk-qka0e661.js";import{v}from"./chunk-5fde4d44.js";import{P}from"./chunk-e4c7ba0g.js";import{g}from"./chunk-17ewx21n.js";class K{client;region;constructor(t="us-east-1",s){this.region=t,this.client=new p(void 0,{profile:s})}async createSecret(t){let s={Name:t.Name};if(t.Description)s.Description=t.Description;if(t.KmsKeyId)s.KmsKeyId=t.KmsKeyId;if(t.SecretBinary)s.SecretBinary=t.SecretBinary;if(t.SecretString)s.SecretString=t.SecretString;if(t.Tags&&t.Tags.length>0)s.Tags=t.Tags;if(t.AddReplicaRegions&&t.AddReplicaRegions.length>0)s.AddReplicaRegions=t.AddReplicaRegions;if(t.ForceOverwriteReplicaSecret!==void 0)s.ForceOverwriteReplicaSecret=t.ForceOverwriteReplicaSecret;s.ClientRequestToken=t.ClientRequestToken||crypto.randomUUID();let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.CreateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId,ReplicationStatus:o.ReplicationStatus}}async updateSecret(t){let s={SecretId:t.SecretId,ClientRequestToken:t.ClientRequestToken||crypto.randomUUID()};if(t.Description)s.Description=t.Description;if(t.KmsKeyId)s.KmsKeyId=t.KmsKeyId;if(t.SecretBinary)s.SecretBinary=t.SecretBinary;if(t.SecretString)s.SecretString=t.SecretString;let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.UpdateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId}}async putSecretValue(t){let s={SecretId:t.SecretId};if(t.SecretBinary)s.SecretBinary=t.SecretBinary;if(t.SecretString)s.SecretString=t.SecretString;if(t.VersionStages&&t.VersionStages.length>0)s.VersionStages=t.VersionStages;s.ClientRequestToken=t.ClientRequestToken||crypto.randomUUID();let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.PutSecretValue","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId,VersionStages:o.VersionStages}}async getSecretValue(t){let s={SecretId:t.SecretId};if(t.VersionId)s.VersionId=t.VersionId;if(t.VersionStage)s.VersionStage=t.VersionStage;let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.GetSecretValue","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId,SecretBinary:o.SecretBinary,SecretString:o.SecretString,VersionStages:o.VersionStages,CreatedDate:o.CreatedDate}}async describeSecret(t){let s={SecretId:t},o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.DescribeSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return this.parseSecret(o)}async listSecrets(t){let s={};if(t?.MaxResults)s.MaxResults=t.MaxResults;if(t?.NextToken)s.NextToken=t.NextToken;if(t?.Filters&&t.Filters.length>0)s.Filters=t.Filters;if(t?.SortOrder)s.SortOrder=t.SortOrder;let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.ListSecrets","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{SecretList:o.SecretList?.map((c)=>this.parseSecret(c)),NextToken:o.NextToken}}async deleteSecret(t){let s={SecretId:t.SecretId};if(t.RecoveryWindowInDays!==void 0)s.RecoveryWindowInDays=t.RecoveryWindowInDays;if(t.ForceDeleteWithoutRecovery!==void 0)s.ForceDeleteWithoutRecovery=t.ForceDeleteWithoutRecovery;let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.DeleteSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,DeletionDate:o.DeletionDate}}async restoreSecret(t){let s={SecretId:t},o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.RestoreSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name}}async rotateSecret(t){let s={SecretId:t.SecretId};if(t.ClientRequestToken)s.ClientRequestToken=t.ClientRequestToken;if(t.RotationLambdaARN)s.RotationLambdaARN=t.RotationLambdaARN;if(t.RotationRules)s.RotationRules=t.RotationRules;if(t.RotateImmediately!==void 0)s.RotateImmediately=t.RotateImmediately;let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.RotateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId}}async cancelRotateSecret(t){let s={SecretId:t},o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.CancelRotateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name}}async getResourcePolicy(t){let s={SecretId:t},o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.GetResourcePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,ResourcePolicy:o.ResourcePolicy}}async putResourcePolicy(t){let s={SecretId:t.SecretId,ResourcePolicy:t.ResourcePolicy};if(t.BlockPublicPolicy!==void 0)s.BlockPublicPolicy=t.BlockPublicPolicy;let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.PutResourcePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name}}async deleteResourcePolicy(t){let s={SecretId:t},o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.DeleteResourcePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name}}async tagResource(t){let s={SecretId:t.SecretId,Tags:t.Tags};await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.TagResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)})}async untagResource(t){let s={SecretId:t.SecretId,TagKeys:t.TagKeys};await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.UntagResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)})}async setString(t,s,o){try{let c=await this.putSecretValue({SecretId:t,SecretString:s});return{ARN:c.ARN,VersionId:c.VersionId}}catch(c){if(c.code==="ResourceNotFoundException"){let l=await this.createSecret({Name:t,SecretString:s,Description:o?.description,KmsKeyId:o?.kmsKeyId,Tags:o?.tags});return{ARN:l.ARN,VersionId:l.VersionId}}throw c}}async setJson(t,s,o){return this.setString(t,JSON.stringify(s),o)}async getString(t){return(await this.getSecretValue({SecretId:t})).SecretString}async getJson(t){let s=await this.getString(t);if(s)return JSON.parse(s);return}async listAll(){let t=[],s;do{let o=await this.listSecrets({NextToken:s});if(o.SecretList)t.push(...o.SecretList);s=o.NextToken}while(s);return t}parseSecret(t){return{ARN:t.ARN,Name:t.Name,Description:t.Description,KmsKeyId:t.KmsKeyId,RotationEnabled:t.RotationEnabled,RotationLambdaARN:t.RotationLambdaARN,RotationRules:t.RotationRules,LastRotatedDate:t.LastRotatedDate,LastChangedDate:t.LastChangedDate,LastAccessedDate:t.LastAccessedDate,DeletedDate:t.DeletedDate,NextRotationDate:t.NextRotationDate,Tags:t.Tags,SecretVersionsToStages:t.SecretVersionsToStages,CreatedDate:t.CreatedDate,PrimaryRegion:t.PrimaryRegion}}}import{existsSync as de,readdirSync as me,readFileSync as pe,statSync as fe}from"node:fs";import{join as ne,relative as Se}from"node:path";function k(t,s){let o=t.environments?.[s]?.app;if(!o)throw Error(`No serverless app configured for environment '${s}'. Add environments.${s}.app to your config.`);let c=t.project.slug,l=t.environments?.[s]?.region||t.project.region||"us-east-1";return{app:o,slug:c,region:l,stackName:$e(t,s),artifactBucket:ya(c,s),assetsBucket:Ui(c,s)}}function Tt(t,s){let o=k(t,s),c=`${o.slug}-${s}`;return{region:o.region,slug:o.slug,stackName:o.stackName,functions:{http:`${c}-http`,queue:`${c}-queue`,cli:`${c}-cli`}}}async function q(t,s=8){let o;for(let c=0;c<s;c++)try{return await t()}catch(l){let d=l?.code||l?.name||"",m=String(l?.message||"");if(d==="ResourceConflictException"||/update is in progress|currently in the following state/i.test(m)){o=l,await new Promise((f)=>setTimeout(f,3000));continue}throw l}throw o}var ie=(t,s)=>`releases/${t}/${s}/current.json`;async function G(t,s,o,c){try{return await t.getObjectJson(s,ie(o,c))}catch{return null}}async function ae(t,s,o,c,l){await t.putObjectJson(s,ie(o,c),l)}async function ye(t,s){if(!t.secrets)return{};let o=new K(s),c={},l=Array.isArray(t.secrets)?t.secrets.map((d)=>({envName:d.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),secretId:d})):Object.entries(t.secrets).map(([d,m])=>({envName:d,secretId:m}));if(Array.isArray(t.secrets)){let d=new Map;for(let{envName:f,secretId:S}of l)d.set(f,[...d.get(f)??[],S]);let m=[...d.entries()].filter(([,f])=>f.length>1);if(m.length){let f=m.map(([S,R])=>`${S} ← ${R.join(", ")}`).join("; ");throw Error(`serverless secrets: multiple secrets map to the same env var (${f}). Use the map form { ENV_NAME: 'secret/id' } to disambiguate.`)}}for(let{envName:d,secretId:m}of l){let S=(await o.getSecretValue({SecretId:m})).SecretString??"";try{let R=JSON.parse(S);if(R&&typeof R==="object"&&!Array.isArray(R)){for(let[w,N]of Object.entries(R))c[w]=String(N);continue}}catch{}c[d]=S}return c}function Zd(t,s){let o={},c=s.DbProxyEndpoint||s.DbEndpoint;if(c)o.DB_CONNECTION="mysql",o.DB_HOST=c,o.DB_PORT="3306",o.DB_DATABASE=o.DB_DATABASE||"app";if(s.CacheEndpoint){if(o.REDIS_HOST=s.CacheEndpoint,o.REDIS_PORT="6379",t.cache?.driver==="elasticache")o.CACHE_STORE="redis",o.CACHE_DRIVER="redis",o.SESSION_DRIVER="redis"}return o}function Fs(t,s,o,c,l,d,m,f={}){let S=t.kind==="php"?oc({cacheDriver:t.cache?.driver==="elasticache"?"redis":"dynamodb"}):{};return{TSCLOUD_LAMBDA_MODE:c,TSCLOUD_ENV:o,MAINTENANCE_MODE:"0",...t.octane?{TSCLOUD_OCTANE:"1"}:{},...t.serveAssets?{TSCLOUD_SERVE_ASSETS:"1"}:{},...t.redirectRobotsTxt===!1?{TSCLOUD_REDIRECT_ROBOTS_TXT:"0"}:{},...S,...f,...s.app.cache?.driver!=="elasticache"?{TSCLOUD_CACHE_TABLE:`${s.slug}-${o}-cache`}:{},...m?{TSCLOUD_QUEUE:m,SQS_QUEUE:m}:{},...d?{ASSET_URL:d}:{},...t.env??{},...l}}function Re(t){let s=t.slice(t.lastIndexOf(".")).toLowerCase();return{".html":"text/html",".css":"text/css",".js":"text/javascript",".mjs":"text/javascript",".json":"application/json",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".txt":"text/plain",".map":"application/json"}[s]??"application/octet-stream"}function*oe(t){for(let s of me(t)){let o=ne(t,s);if(fe(o).isDirectory())yield*oe(o);else yield o}}async function he(t,s,o,c,l=!1){let d=0;for(let m of oe(o)){let f=Se(o,m).replace(/\\/g,"/");if(!l&&f.split("/").some((S)=>S.startsWith(".")))continue;await t.putObject({bucket:s,key:`${c}/${f}`,body:pe(m),contentType:Re(m),cacheControl:"public, max-age=31536000, immutable"}),d++}return d}function $o(t,s){let o=Object.entries(s).reduce((c,[l,d])=>c+Buffer.byteLength(`${l}=${d}`,"utf8"),0);if(o>4096){let c=Object.entries(s).map(([l,d])=>[l,Buffer.byteLength(`${l}=${d}`,"utf8")]).sort((l,d)=>d[1]-l[1]).slice(0,5).map(([l,d])=>`${l} (${d}B)`).join(", ");throw Error(`${t}: environment variables total ${o}B, over AWS's 4096B limit (${o-4096}B too large). Largest: ${c}. Move large/secret values out of env — store them in Secrets Manager and fetch at cold start.`)}}async function U(t,s,o,c){$o(s,o),await q(()=>t.updateFunctionConfiguration({FunctionName:s,Environment:{Variables:o}})),await t.waitForFunctionActive(s,120);let l=c.kind==="image"?{FunctionName:s,ImageUri:c.imageUri}:{FunctionName:s,S3Bucket:c.bucket,S3Key:c.key};await q(()=>t.updateFunctionCode(l)),await t.waitForFunctionActive(s,120)}async function X(t,s){let c=(await q(()=>t.publishVersion({FunctionName:s}))).Version;if(!c)throw Error(`publishVersion returned no version for ${s}`);return await q(()=>t.updateAlias({FunctionName:s,Name:"live",FunctionVersion:c})),c}async function um(t,s,o={}){let c=k(t,s),{app:l,slug:d,region:m,stackName:f,artifactBucket:S}=c,R=o.projectRoot??process.cwd();i(`Deploying serverless app: ${d} (${s})`),e(`Stack: ${f}`),e(`Region: ${m}`);let w=new g(m),N=new v(m),T=new P(m),D=l.kind==="php",O=l.packaging==="image",h=Wi(l),V,E,b,Y,M=[];if(O&&h.usesLayer&&h.layerKind!=="php")throw Error(`packaging: 'image' currently supports PHP and managed Node runtimes. ${h.kind}${h.kind==="node"?` ${h.version}`:""} uses a custom runtime — `+"use the default zip packaging (the runtime layer is built + attached automatically).");if(O){u("Building + pushing container image");let{buildAndPushServerlessImage:y}=await import("./chunk-p40tvp17.js"),C=await y({app:l,projectRoot:R,region:m,repository:`${d}-${s}`,skipBuild:o.skipBuild,onStep:(I)=>e(` ${I}`)});V=C.handlers,E={kind:"image",imageUri:C.imageUri},b=C.tag,M.push({ParameterKey:"ImageUri",ParameterValue:C.imageUri})}else{u("Packaging application");let y=D?sc({projectRoot:R,app:l,skipBuild:o.skipBuild,onStep:(x)=>e(` ${x}`)}):await Dn({projectRoot:R,app:l,skipBuild:o.skipBuild,onStep:(x)=>e(` ${x}`)}),C=Ja(d,s,y.sha256);if(e(`Artifact: ${y.sha256.slice(0,12)} (${(y.zip.length/1024).toFixed(0)} KB)`),V=y.handlers,b=y.sha256,h.usesLayer){let x=h.layerEnvVar?process.env[h.layerEnvVar]:void 0;if(Y=l.layers??(x?[x]:void 0),!Y?.length){let ge=h.layerKind==="php"?"serverless:build-php-layer":h.layerKind==="bun"?"serverless:build-bun-layer":"serverless:build-node-layer";throw Error(`${h.kind} apps on provided.al2023 need a runtime layer. Set environments.<env>.app.layers or the ${h.layerEnvVar} env var (build one with \`cloud ${ge}\`)${h.kind==="node"?", or use a managed Node version (18/20/22)":""}.`)}}if(!await w.bucketExists(S))u(`Creating artifact bucket ${S}`),await w.createBucket(S);if(await w.headObject(S,C).then((x)=>x!==null).catch(()=>!1))e("Artifact already uploaded — reusing");else u("Uploading artifact"),await w.putObject({bucket:S,key:C,body:y.zip,contentType:"application/zip"});E={kind:"zip",bucket:S,key:C},M.push({ParameterKey:"ArtifactBucket",ParameterValue:S},{ParameterKey:"ArtifactKey",ParameterValue:C})}let A=Qa({config:t,environment:s,app:l,handlers:V,runtimeLayers:Y}),te=JSON.stringify(A.template),re=["CAPABILITY_NAMED_IAM"],L=await N.describeStacks({stackName:f}).then((y)=>y.Stacks[0]?.StackStatus).catch(()=>{return}),J=L!==void 0;if(L&&/DELETE_IN_PROGRESS/.test(L))u("Waiting for an in-progress stack delete to finish"),await N.waitForStack(f,"stack-delete-complete").catch(()=>{}),J=!1;else if(L&&/(?:ROLLBACK_COMPLETE|REVIEW_IN_PROGRESS|CREATE_FAILED)/.test(L))u(`Deleting unusable stack (status ${L}) before recreate`),await N.deleteStack(f),await N.waitForStack(f,"stack-delete-complete").catch(()=>{}),J=!1;u(J?"Updating infrastructure stack":"Creating infrastructure stack");try{if(J)await N.updateStack({stackName:f,templateBody:te,parameters:M,capabilities:re}),await N.waitForStack(f,"stack-update-complete");else await N.createStack({stackName:f,templateBody:te,parameters:M,capabilities:re,onFailure:"DELETE"}),await N.waitForStack(f,"stack-create-complete")}catch(y){if(/No updates are to be performed/i.test(String(y?.message)))e("No infrastructure changes");else throw y}let Q=await N.getStackOutputs(f).catch(()=>({})),B;if(l.assets){let y=ne(R,l.assets);if(de(y)){let C=l.assetDomain||Q.AssetsCdnDomain;B=C?`https://${C}/${b}`:void 0,u(`Syncing assets from ${l.assets}`);let I=await he(w,c.assetsBucket,y,b,l.dotFilesAsAssets);e(`Uploaded ${I} asset(s)${B?` → ${B}`:""}`)}else a(`Assets directory not found: ${y}`)}u("Resolving secrets");let _=await ye(l,m);if(l.database?.connection==="aurora-serverless")try{let C=await new K(m).getSecretValue({SecretId:`${d}/${s}/db`}),I=JSON.parse(C.SecretString??"{}");if(I.username)_.DB_USERNAME=I.username;if(I.password)_.DB_PASSWORD=I.password}catch(y){a(`Could not resolve Aurora DB credentials: ${y.message}`)}if(!await w.bucketExists(S))await w.createBucket(S);let H=await G(w,S,d,s),F={},Z=A.queueNames[0],ee=Zd(l,Q);if(u("Activating functions"),F.http=Fs(l,c,s,"http",_,B,Z,ee),await U(T,A.functionNames.http,F.http,E),F.cli=Fs(l,c,s,"cli",_,B,Z,ee),await U(T,A.functionNames.cli,F.cli,E),A.queueNames.length)F.queue=Fs(l,c,s,"queue",_,B,Z,ee),await U(T,A.functionNames.queue,F.queue,E);let se=(l.provisionedConcurrency??0)>0,W={};if(se){if(u("Publishing versions + flipping live alias"),W.http=await X(T,A.functionNames.http),W.cli=await X(T,A.functionNames.cli),A.queueNames.length)W.queue=await X(T,A.functionNames.queue)}if(await ae(w,S,d,s,{sha:b,code:E,previousSha:H?.sha,previousCode:H?.code,previousFunctionEnv:H?.functionEnv,...se?{functionVersions:W,previousFunctionVersions:H?.functionVersions}:{},functionEnv:F,functionNames:{http:A.functionNames.http,cli:A.functionNames.cli,...A.queueNames.length?{queue:A.functionNames.queue}:{}},assetUrl:B,timestamp:new Date().toISOString()}),!o.skipDeployHooks&&l.deploy?.length){u("Running deploy hooks");for(let y of l.deploy){e(` deploy: ${y}`);let C=await T.invoke({FunctionName:A.functionNames.cli,InvocationType:"RequestResponse",Payload:{command:y},LogType:"Tail"});if(C.FunctionError)throw r("Deploy hook failed — the new build is ALREADY LIVE."),e(` Roll back with: cloud serverless:rollback --env ${s}`),Error(`Deploy hook failed (${y}): ${C.Payload}`)}}let j=Q.HttpApiEndpoint;if(!o.skipHealthCheck&&j){u("Health check");try{let y=await fetch(j,{method:"GET"});e(`GET ${j} → ${y.status}`)}catch(y){a(`Health check could not reach ${j}: ${y.message}`)}}Ee(["Serverless deploy complete","",j?`URL: ${j}`:"",`Stack: ${f}`,`Build: ${b.slice(0,12)}`].filter(Boolean).join(`
|
|
2
|
-
`),"green")}async function
|
|
3
|
-
export{K,Tt,
|
|
1
|
+
import{p}from"./chunk-9cj1fm00.js";import{$e,ba,Bi,Xa,Dn,Ki,Qa,Ya,sc,ac}from"./chunk-6wz74ram.js";import{n,r,a,e,u,i,Ee}from"./chunk-vveaxany.js";import{v}from"./chunk-rg6r03q3.js";import{P}from"./chunk-4w6n5wht.js";import{g}from"./chunk-zph18vv6.js";class K{client;region;constructor(t="us-east-1",s){this.region=t,this.client=new p(void 0,{profile:s})}async createSecret(t){let s={Name:t.Name};if(t.Description)s.Description=t.Description;if(t.KmsKeyId)s.KmsKeyId=t.KmsKeyId;if(t.SecretBinary)s.SecretBinary=t.SecretBinary;if(t.SecretString)s.SecretString=t.SecretString;if(t.Tags&&t.Tags.length>0)s.Tags=t.Tags;if(t.AddReplicaRegions&&t.AddReplicaRegions.length>0)s.AddReplicaRegions=t.AddReplicaRegions;if(t.ForceOverwriteReplicaSecret!==void 0)s.ForceOverwriteReplicaSecret=t.ForceOverwriteReplicaSecret;s.ClientRequestToken=t.ClientRequestToken||crypto.randomUUID();let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.CreateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId,ReplicationStatus:o.ReplicationStatus}}async updateSecret(t){let s={SecretId:t.SecretId,ClientRequestToken:t.ClientRequestToken||crypto.randomUUID()};if(t.Description)s.Description=t.Description;if(t.KmsKeyId)s.KmsKeyId=t.KmsKeyId;if(t.SecretBinary)s.SecretBinary=t.SecretBinary;if(t.SecretString)s.SecretString=t.SecretString;let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.UpdateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId}}async putSecretValue(t){let s={SecretId:t.SecretId};if(t.SecretBinary)s.SecretBinary=t.SecretBinary;if(t.SecretString)s.SecretString=t.SecretString;if(t.VersionStages&&t.VersionStages.length>0)s.VersionStages=t.VersionStages;s.ClientRequestToken=t.ClientRequestToken||crypto.randomUUID();let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.PutSecretValue","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId,VersionStages:o.VersionStages}}async getSecretValue(t){let s={SecretId:t.SecretId};if(t.VersionId)s.VersionId=t.VersionId;if(t.VersionStage)s.VersionStage=t.VersionStage;let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.GetSecretValue","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId,SecretBinary:o.SecretBinary,SecretString:o.SecretString,VersionStages:o.VersionStages,CreatedDate:o.CreatedDate}}async describeSecret(t){let s={SecretId:t},o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.DescribeSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return this.parseSecret(o)}async listSecrets(t){let s={};if(t?.MaxResults)s.MaxResults=t.MaxResults;if(t?.NextToken)s.NextToken=t.NextToken;if(t?.Filters&&t.Filters.length>0)s.Filters=t.Filters;if(t?.SortOrder)s.SortOrder=t.SortOrder;let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.ListSecrets","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{SecretList:o.SecretList?.map((c)=>this.parseSecret(c)),NextToken:o.NextToken}}async deleteSecret(t){let s={SecretId:t.SecretId};if(t.RecoveryWindowInDays!==void 0)s.RecoveryWindowInDays=t.RecoveryWindowInDays;if(t.ForceDeleteWithoutRecovery!==void 0)s.ForceDeleteWithoutRecovery=t.ForceDeleteWithoutRecovery;let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.DeleteSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,DeletionDate:o.DeletionDate}}async restoreSecret(t){let s={SecretId:t},o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.RestoreSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name}}async rotateSecret(t){let s={SecretId:t.SecretId};if(t.ClientRequestToken)s.ClientRequestToken=t.ClientRequestToken;if(t.RotationLambdaARN)s.RotationLambdaARN=t.RotationLambdaARN;if(t.RotationRules)s.RotationRules=t.RotationRules;if(t.RotateImmediately!==void 0)s.RotateImmediately=t.RotateImmediately;let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.RotateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId}}async cancelRotateSecret(t){let s={SecretId:t},o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.CancelRotateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name}}async getResourcePolicy(t){let s={SecretId:t},o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.GetResourcePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,ResourcePolicy:o.ResourcePolicy}}async putResourcePolicy(t){let s={SecretId:t.SecretId,ResourcePolicy:t.ResourcePolicy};if(t.BlockPublicPolicy!==void 0)s.BlockPublicPolicy=t.BlockPublicPolicy;let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.PutResourcePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name}}async deleteResourcePolicy(t){let s={SecretId:t},o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.DeleteResourcePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name}}async tagResource(t){let s={SecretId:t.SecretId,Tags:t.Tags};await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.TagResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)})}async untagResource(t){let s={SecretId:t.SecretId,TagKeys:t.TagKeys};await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.UntagResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)})}async setString(t,s,o){try{let c=await this.putSecretValue({SecretId:t,SecretString:s});return{ARN:c.ARN,VersionId:c.VersionId}}catch(c){if(c.code==="ResourceNotFoundException"){let l=await this.createSecret({Name:t,SecretString:s,Description:o?.description,KmsKeyId:o?.kmsKeyId,Tags:o?.tags});return{ARN:l.ARN,VersionId:l.VersionId}}throw c}}async setJson(t,s,o){return this.setString(t,JSON.stringify(s),o)}async getString(t){return(await this.getSecretValue({SecretId:t})).SecretString}async getJson(t){let s=await this.getString(t);if(s)return JSON.parse(s);return}async listAll(){let t=[],s;do{let o=await this.listSecrets({NextToken:s});if(o.SecretList)t.push(...o.SecretList);s=o.NextToken}while(s);return t}parseSecret(t){return{ARN:t.ARN,Name:t.Name,Description:t.Description,KmsKeyId:t.KmsKeyId,RotationEnabled:t.RotationEnabled,RotationLambdaARN:t.RotationLambdaARN,RotationRules:t.RotationRules,LastRotatedDate:t.LastRotatedDate,LastChangedDate:t.LastChangedDate,LastAccessedDate:t.LastAccessedDate,DeletedDate:t.DeletedDate,NextRotationDate:t.NextRotationDate,Tags:t.Tags,SecretVersionsToStages:t.SecretVersionsToStages,CreatedDate:t.CreatedDate,PrimaryRegion:t.PrimaryRegion}}}import{existsSync as de,readdirSync as me,readFileSync as pe,statSync as fe}from"node:fs";import{join as ne,relative as Se}from"node:path";function k(t,s){let o=t.environments?.[s]?.app;if(!o)throw Error(`No serverless app configured for environment '${s}'. Add environments.${s}.app to your config.`);let c=t.project.slug,l=t.environments?.[s]?.region||t.project.region||"us-east-1";return{app:o,slug:c,region:l,stackName:$e(t,s),artifactBucket:ba(c,s),assetsBucket:Bi(c,s)}}function Tt(t,s){let o=k(t,s),c=`${o.slug}-${s}`;return{region:o.region,slug:o.slug,stackName:o.stackName,functions:{http:`${c}-http`,queue:`${c}-queue`,cli:`${c}-cli`}}}async function q(t,s=8){let o;for(let c=0;c<s;c++)try{return await t()}catch(l){let d=l?.code||l?.name||"",m=String(l?.message||"");if(d==="ResourceConflictException"||/update is in progress|currently in the following state/i.test(m)){o=l,await new Promise((f)=>setTimeout(f,3000));continue}throw l}throw o}var ie=(t,s)=>`releases/${t}/${s}/current.json`;async function G(t,s,o,c){try{return await t.getObjectJson(s,ie(o,c))}catch{return null}}async function ae(t,s,o,c,l){await t.putObjectJson(s,ie(o,c),l)}async function ye(t,s){if(!t.secrets)return{};let o=new K(s),c={},l=Array.isArray(t.secrets)?t.secrets.map((d)=>({envName:d.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),secretId:d})):Object.entries(t.secrets).map(([d,m])=>({envName:d,secretId:m}));if(Array.isArray(t.secrets)){let d=new Map;for(let{envName:f,secretId:S}of l)d.set(f,[...d.get(f)??[],S]);let m=[...d.entries()].filter(([,f])=>f.length>1);if(m.length){let f=m.map(([S,R])=>`${S} ← ${R.join(", ")}`).join("; ");throw Error(`serverless secrets: multiple secrets map to the same env var (${f}). Use the map form { ENV_NAME: 'secret/id' } to disambiguate.`)}}for(let{envName:d,secretId:m}of l){let S=(await o.getSecretValue({SecretId:m})).SecretString??"";try{let R=JSON.parse(S);if(R&&typeof R==="object"&&!Array.isArray(R)){for(let[w,N]of Object.entries(R))c[w]=String(N);continue}}catch{}c[d]=S}return c}function tu(t,s){let o={},c=s.DbProxyEndpoint||s.DbEndpoint;if(c)o.DB_CONNECTION="mysql",o.DB_HOST=c,o.DB_PORT="3306",o.DB_DATABASE=o.DB_DATABASE||"app";if(s.CacheEndpoint){if(o.REDIS_HOST=s.CacheEndpoint,o.REDIS_PORT="6379",t.cache?.driver==="elasticache")o.CACHE_STORE="redis",o.CACHE_DRIVER="redis",o.SESSION_DRIVER="redis"}return o}function Fs(t,s,o,c,l,d,m,f={}){let S=t.kind==="php"?sc({cacheDriver:t.cache?.driver==="elasticache"?"redis":"dynamodb"}):{};return{TSCLOUD_LAMBDA_MODE:c,TSCLOUD_ENV:o,MAINTENANCE_MODE:"0",...t.octane?{TSCLOUD_OCTANE:"1"}:{},...t.serveAssets?{TSCLOUD_SERVE_ASSETS:"1"}:{},...t.redirectRobotsTxt===!1?{TSCLOUD_REDIRECT_ROBOTS_TXT:"0"}:{},...S,...f,...s.app.cache?.driver!=="elasticache"?{TSCLOUD_CACHE_TABLE:`${s.slug}-${o}-cache`}:{},...m?{TSCLOUD_QUEUE:m,SQS_QUEUE:m}:{},...d?{ASSET_URL:d}:{},...t.env??{},...l}}function Re(t){let s=t.slice(t.lastIndexOf(".")).toLowerCase();return{".html":"text/html",".css":"text/css",".js":"text/javascript",".mjs":"text/javascript",".json":"application/json",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".txt":"text/plain",".map":"application/json"}[s]??"application/octet-stream"}function*oe(t){for(let s of me(t)){let o=ne(t,s);if(fe(o).isDirectory())yield*oe(o);else yield o}}async function he(t,s,o,c,l=!1){let d=0;for(let m of oe(o)){let f=Se(o,m).replace(/\\/g,"/");if(!l&&f.split("/").some((S)=>S.startsWith(".")))continue;await t.putObject({bucket:s,key:`${c}/${f}`,body:pe(m),contentType:Re(m),cacheControl:"public, max-age=31536000, immutable"}),d++}return d}function Lo(t,s){let o=Object.entries(s).reduce((c,[l,d])=>c+Buffer.byteLength(`${l}=${d}`,"utf8"),0);if(o>4096){let c=Object.entries(s).map(([l,d])=>[l,Buffer.byteLength(`${l}=${d}`,"utf8")]).sort((l,d)=>d[1]-l[1]).slice(0,5).map(([l,d])=>`${l} (${d}B)`).join(", ");throw Error(`${t}: environment variables total ${o}B, over AWS's 4096B limit (${o-4096}B too large). Largest: ${c}. Move large/secret values out of env — store them in Secrets Manager and fetch at cold start.`)}}async function U(t,s,o,c){Lo(s,o),await q(()=>t.updateFunctionConfiguration({FunctionName:s,Environment:{Variables:o}})),await t.waitForFunctionActive(s,120);let l=c.kind==="image"?{FunctionName:s,ImageUri:c.imageUri}:{FunctionName:s,S3Bucket:c.bucket,S3Key:c.key};await q(()=>t.updateFunctionCode(l)),await t.waitForFunctionActive(s,120)}async function X(t,s){let c=(await q(()=>t.publishVersion({FunctionName:s}))).Version;if(!c)throw Error(`publishVersion returned no version for ${s}`);return await q(()=>t.updateAlias({FunctionName:s,Name:"live",FunctionVersion:c})),c}async function mm(t,s,o={}){let c=k(t,s),{app:l,slug:d,region:m,stackName:f,artifactBucket:S}=c,R=o.projectRoot??process.cwd();i(`Deploying serverless app: ${d} (${s})`),e(`Stack: ${f}`),e(`Region: ${m}`);let w=new g(m),N=new v(m),T=new P(m),D=l.kind==="php",O=l.packaging==="image",h=Ki(l),V,E,b,Y,M=[];if(O&&h.usesLayer&&h.layerKind!=="php")throw Error(`packaging: 'image' currently supports PHP and managed Node runtimes. ${h.kind}${h.kind==="node"?` ${h.version}`:""} uses a custom runtime — `+"use the default zip packaging (the runtime layer is built + attached automatically).");if(O){u("Building + pushing container image");let{buildAndPushServerlessImage:y}=await import("./chunk-7qkc4af5.js"),C=await y({app:l,projectRoot:R,region:m,repository:`${d}-${s}`,skipBuild:o.skipBuild,onStep:(I)=>e(` ${I}`)});V=C.handlers,E={kind:"image",imageUri:C.imageUri},b=C.tag,M.push({ParameterKey:"ImageUri",ParameterValue:C.imageUri})}else{u("Packaging application");let y=D?ac({projectRoot:R,app:l,skipBuild:o.skipBuild,onStep:(x)=>e(` ${x}`)}):await Dn({projectRoot:R,app:l,skipBuild:o.skipBuild,onStep:(x)=>e(` ${x}`)}),C=Xa(d,s,y.sha256);if(e(`Artifact: ${y.sha256.slice(0,12)} (${(y.zip.length/1024).toFixed(0)} KB)`),V=y.handlers,b=y.sha256,h.usesLayer){let x=h.layerEnvVar?process.env[h.layerEnvVar]:void 0;if(Y=l.layers??(x?[x]:void 0),!Y?.length){let ge=h.layerKind==="php"?"serverless:build-php-layer":h.layerKind==="bun"?"serverless:build-bun-layer":"serverless:build-node-layer";throw Error(`${h.kind} apps on provided.al2023 need a runtime layer. Set environments.<env>.app.layers or the ${h.layerEnvVar} env var (build one with \`cloud ${ge}\`)${h.kind==="node"?", or use a managed Node version (18/20/22)":""}.`)}}if(!await w.bucketExists(S))u(`Creating artifact bucket ${S}`),await w.createBucket(S);if(await w.headObject(S,C).then((x)=>x!==null).catch(()=>!1))e("Artifact already uploaded — reusing");else u("Uploading artifact"),await w.putObject({bucket:S,key:C,body:y.zip,contentType:"application/zip"});E={kind:"zip",bucket:S,key:C},M.push({ParameterKey:"ArtifactBucket",ParameterValue:S},{ParameterKey:"ArtifactKey",ParameterValue:C})}let A=Ya({config:t,environment:s,app:l,handlers:V,runtimeLayers:Y}),te=JSON.stringify(A.template),re=["CAPABILITY_NAMED_IAM"],L=await N.describeStacks({stackName:f}).then((y)=>y.Stacks[0]?.StackStatus).catch(()=>{return}),J=L!==void 0;if(L&&/DELETE_IN_PROGRESS/.test(L))u("Waiting for an in-progress stack delete to finish"),await N.waitForStack(f,"stack-delete-complete").catch(()=>{}),J=!1;else if(L&&/(?:ROLLBACK_COMPLETE|REVIEW_IN_PROGRESS|CREATE_FAILED)/.test(L))u(`Deleting unusable stack (status ${L}) before recreate`),await N.deleteStack(f),await N.waitForStack(f,"stack-delete-complete").catch(()=>{}),J=!1;u(J?"Updating infrastructure stack":"Creating infrastructure stack");try{if(J)await N.updateStack({stackName:f,templateBody:te,parameters:M,capabilities:re}),await N.waitForStack(f,"stack-update-complete");else await N.createStack({stackName:f,templateBody:te,parameters:M,capabilities:re,onFailure:"DELETE"}),await N.waitForStack(f,"stack-create-complete")}catch(y){if(/No updates are to be performed/i.test(String(y?.message)))e("No infrastructure changes");else throw y}let Q=await N.getStackOutputs(f).catch(()=>({})),B;if(l.assets){let y=ne(R,l.assets);if(de(y)){let C=l.assetDomain||Q.AssetsCdnDomain;B=C?`https://${C}/${b}`:void 0,u(`Syncing assets from ${l.assets}`);let I=await he(w,c.assetsBucket,y,b,l.dotFilesAsAssets);e(`Uploaded ${I} asset(s)${B?` → ${B}`:""}`)}else a(`Assets directory not found: ${y}`)}u("Resolving secrets");let _=await ye(l,m);if(l.database?.connection==="aurora-serverless")try{let C=await new K(m).getSecretValue({SecretId:`${d}/${s}/db`}),I=JSON.parse(C.SecretString??"{}");if(I.username)_.DB_USERNAME=I.username;if(I.password)_.DB_PASSWORD=I.password}catch(y){a(`Could not resolve Aurora DB credentials: ${y.message}`)}if(!await w.bucketExists(S))await w.createBucket(S);let H=await G(w,S,d,s),F={},Z=A.queueNames[0],ee=tu(l,Q);if(u("Activating functions"),F.http=Fs(l,c,s,"http",_,B,Z,ee),await U(T,A.functionNames.http,F.http,E),F.cli=Fs(l,c,s,"cli",_,B,Z,ee),await U(T,A.functionNames.cli,F.cli,E),A.queueNames.length)F.queue=Fs(l,c,s,"queue",_,B,Z,ee),await U(T,A.functionNames.queue,F.queue,E);let se=(l.provisionedConcurrency??0)>0,W={};if(se){if(u("Publishing versions + flipping live alias"),W.http=await X(T,A.functionNames.http),W.cli=await X(T,A.functionNames.cli),A.queueNames.length)W.queue=await X(T,A.functionNames.queue)}if(await ae(w,S,d,s,{sha:b,code:E,previousSha:H?.sha,previousCode:H?.code,previousFunctionEnv:H?.functionEnv,...se?{functionVersions:W,previousFunctionVersions:H?.functionVersions}:{},functionEnv:F,functionNames:{http:A.functionNames.http,cli:A.functionNames.cli,...A.queueNames.length?{queue:A.functionNames.queue}:{}},assetUrl:B,timestamp:new Date().toISOString()}),!o.skipDeployHooks&&l.deploy?.length){u("Running deploy hooks");for(let y of l.deploy){e(` deploy: ${y}`);let C=await T.invoke({FunctionName:A.functionNames.cli,InvocationType:"RequestResponse",Payload:{command:y},LogType:"Tail"});if(C.FunctionError)throw r("Deploy hook failed — the new build is ALREADY LIVE."),e(` Roll back with: cloud serverless:rollback --env ${s}`),Error(`Deploy hook failed (${y}): ${C.Payload}`)}}let j=Q.HttpApiEndpoint;if(!o.skipHealthCheck&&j){u("Health check");try{let y=await fetch(j,{method:"GET"});e(`GET ${j} → ${y.status}`)}catch(y){a(`Health check could not reach ${j}: ${y.message}`)}}Ee(["Serverless deploy complete","",j?`URL: ${j}`:"",`Stack: ${f}`,`Build: ${b.slice(0,12)}`].filter(Boolean).join(`
|
|
2
|
+
`),"green")}async function js(t,s){let o=k(t,s),c=new g(o.region),l=new P(o.region),d=await G(c,o.artifactBucket,o.slug,s);if(!d)throw Error("No previous release to redeploy. Run a full deploy first.");i(`Redeploying ${o.slug} (${s}) — build ${d.sha.slice(0,12)}`);for(let[m,f]of Object.entries(d.functionNames)){if(!f)continue;u(`Re-activating ${m} (${f})`),await U(l,f,d.functionEnv[m]??{},d.code);let S=d.functionVersions?.[m];if(S)await q(()=>l.updateAlias({FunctionName:f,Name:"live",FunctionVersion:S}))}n("Redeploy complete")}async function Vs(t,s){let o=k(t,s),c=new g(o.region),l=new P(o.region),d=await G(c,o.artifactBucket,o.slug,s);if(!d?.previousCode)throw Error("No previous release to roll back to.");i(`Rolling back ${o.slug} (${s}) → ${d.previousSha?.slice(0,12)}`);for(let[m,f]of Object.entries(d.functionNames)){if(!f)continue;u(`Restoring ${m} (${f})`);let S=d.previousFunctionEnv?.[m]??d.functionEnv[m]??{};await U(l,f,S,d.previousCode);let R=d.previousFunctionVersions?.[m];if(R)await q(()=>l.updateAlias({FunctionName:f,Name:"live",FunctionVersion:R}))}await ae(c,o.artifactBucket,o.slug,s,{...d,sha:d.previousSha??d.sha,code:d.previousCode,functionEnv:d.previousFunctionEnv??d.functionEnv,functionVersions:d.previousFunctionVersions??d.functionVersions,previousSha:void 0,previousCode:void 0,previousFunctionEnv:void 0,previousFunctionVersions:void 0,timestamp:new Date().toISOString()}),n("Rollback complete")}async function Mo(t,s,o,c){let l=k(t,s),d=new P(l.region),m=`${l.slug}-${s}-http`,S={...(await d.getFunction(m)).Configuration?.Environment?.Variables??{}};if(S.MAINTENANCE_MODE=o?"1":"0",o&&c)S.MAINTENANCE_BYPASS_SECRET=c;if(!o)delete S.MAINTENANCE_BYPASS_SECRET;if(await q(()=>d.updateFunctionConfiguration({FunctionName:m,Environment:{Variables:S}})),(l.app.provisionedConcurrency??0)>0)await d.waitForFunctionActive(m,120),await X(d,m);n(o?"Application is now in maintenance mode (503)":"Application is live")}async function Gt(t,s,o){let c=k(t,s),l=new P(c.region),d=`${c.slug}-${s}-cli`,m=await l.invoke({FunctionName:d,InvocationType:"RequestResponse",Payload:{command:o},LogType:"Tail"});if(m.FunctionError)throw Error(`Command failed: ${m.Payload}`);return m.Payload??""}var ce=(t,s)=>`commands/${t}/${s}/history.json`,ve=50;async function le(t,s,o,c){try{return(await t.getObjectJson(s,ce(o,c)))?.records??[]}catch{return[]}}async function gm(t,s,o){let c=k(t,s),l=new P(c.region),d=`${c.slug}-${s}-cli`,m=await l.invoke({FunctionName:d,InvocationType:"RequestResponse",Payload:{command:o},LogType:"Tail"}),f=m.Payload??"",S=m.FunctionError?"error":"ok",R=-1;try{let w=new g(c.region);if(await w.bucketExists(c.artifactBucket)){let N=await le(w,c.artifactBucket,c.slug,s);R=N.reduce((T,D)=>Math.max(T,D.id),0)+1,N.push({id:R,command:o,timestamp:new Date().toISOString(),status:S,output:f.slice(0,4000)}),await w.putObjectJson(c.artifactBucket,ce(c.slug,s),{records:N.slice(-ve)})}}catch{}if(m.FunctionError)throw Error(`Command failed${R>0?` (#${R})`:""}: ${f}`);return{id:R,status:S,output:f}}async function ru(t,s){let o=k(t,s),c=new g(o.region);return le(c,o.artifactBucket,o.slug,s)}async function fm(t,s,o){let c=await ru(t,s);if(!c.length)return;return o==null?c[c.length-1]:c.find((l)=>l.id===o)}async function hm(t,s,o){let c=Buffer.from(o,"utf-8").toString("base64");return Gt(t,s,`tscloud:db-query --sql-base64=${c}`)}async function z(t,s){let o=k(t,s),c=new v(o.region),l=new P(o.region),d=new g(o.region),m="not deployed",f={};try{let{Stacks:O}=await c.describeStacks({stackName:o.stackName});m=O?.[0]?.StackStatus??m;for(let h of O?.[0]?.Outputs??[])if(h.OutputKey)f[h.OutputKey]=h.OutputValue??""}catch{}let S=Qa(o.app,o.slug,s),R=o.app.provisionedConcurrency??0,w=["http","cli",...S.length?["queue"]:[]],N=`${o.slug}-${s}`,T=[];for(let O of w){let h=`${N}-${O}`,V={mode:O,name:h,version:"$LATEST"};if(R>0){let E=await l.getAlias(h,"live").catch(()=>null);if(E?.FunctionVersion){V.version=E.FunctionVersion;let b=await l.getProvisionedConcurrencyConfig(h,"live").catch(()=>null);if(b)V.provisioned={status:b.Status??"-",allocated:b.AllocatedProvisionedConcurrentExecutions??0,requested:b.RequestedProvisionedConcurrentExecutions??0}}}T.push(V)}let D=await G(d,o.artifactBucket,o.slug,s).catch(()=>null);return{slug:o.slug,environment:s,region:o.region,stackStatus:m,endpoint:f.HttpApiEndpoint,assetUrl:D?.assetUrl,scheduler:o.app.scheduler??"on",queues:S,provisionedConcurrency:R,functions:T,lastRelease:D?{sha:D.sha,timestamp:D.timestamp}:void 0}}function ue(t,s){return`${t}-${s}-db`}async function zs(t,s,o,c){let l=k(t,s);if(l.app.database?.connection!=="aurora-serverless")throw Error("No Aurora Serverless v2 database is configured for this environment.");let{RDSClient:d}=await import("./chunk-d5n4d3pj.js"),m=new d(l.region),f=ue(l.slug,s);u(`Scaling ${f} → ${o}–${c} ACUs`),await m.modifyDBCluster({DBClusterIdentifier:f,ServerlessV2ScalingConfiguration:{MinCapacity:o,MaxCapacity:c},ApplyImmediately:!0}),n(`Scaling applied to ${f} (takes effect shortly).`)}async function ym(t,s,o){let c=k(t,s);if(c.app.database?.connection!=="aurora-serverless")throw Error("No Aurora Serverless v2 database is configured for this environment.");if(!o.toTime&&!o.latest)throw Error("Specify a restore point: --to <ISO timestamp> or --latest.");let{RDSClient:l}=await import("./chunk-d5n4d3pj.js"),d=new l(c.region),m=ue(c.slug,s),f=o.latest?"latest":o.toTime.toISOString().replace(/[^0-9]/g,"").slice(0,14),S=o.target??`${m}-restore-${f}`;u(`Restoring ${m} → new cluster ${S} (${o.latest?"latest restorable time":o.toTime.toISOString()})`),await d.restoreDBClusterToPointInTime({DBClusterIdentifier:S,SourceDBClusterIdentifier:m,RestoreToTime:o.toTime,UseLatestRestorableTime:o.latest}),u("Waiting for the restored cluster to be ready");for(let R=0;R<120;R++){let{DBClusters:w}=await d.describeDBClusters({DBClusterIdentifier:S}),N=w?.[0]?.Status;if(N&&N!=="creating")break;await new Promise((T)=>setTimeout(T,15000))}return u("Adding a writer instance"),await d.createDBInstance({DBInstanceIdentifier:`${S}-1`,DBClusterIdentifier:S,Engine:"aurora-mysql",DBInstanceClass:"db.serverless"}),n(`Restore complete → cluster ${S} with writer ${S}-1. Point an env's database at it once available.`),S}
|
|
3
|
+
export{K,Tt,tu,Fs,Lo,mm,js,Vs,Mo,Gt,gm,ru,fm,hm,z,zs,ym};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{p}from"./chunk-
|
|
1
|
+
import{p}from"./chunk-9cj1fm00.js";class mt{client;region;constructor(t="us-east-1",e){this.region=t,this.client=new p(void 0,{profile:e})}async getCallerIdentity(){let t=await this.client.request({service:"sts",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetCallerIdentity&Version=2011-06-15"});if(typeof t==="string"){let n=t.match(/<Account>(\d+)<\/Account>/),r=t.match(/<UserId>([^<]+)<\/UserId>/),i=t.match(/<Arn>([^<]+)<\/Arn>/);return{Account:n?.[1],UserId:r?.[1],Arn:i?.[1]}}let e=t?.GetCallerIdentityResponse?.GetCallerIdentityResult||t?.GetCallerIdentityResult;if(e)return{Account:String(e.Account),UserId:e.UserId,Arn:e.Arn};if(t?.Account)return{Account:String(t.Account),UserId:t.UserId,Arn:t.Arn};return{Account:void 0,UserId:void 0,Arn:void 0}}}
|
|
2
2
|
export{mt};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Kt,p}from"./chunk-b0r8a5h5.js";import{g}from"./chunk-17ewx21n.js";import{F}from"./chunk-gga18c4g.js";import{L}from"./chunk-abk97qeq.js";import{Gr}from"./chunk-7v68hpgc.js";function R(e,t){let r=[`Action=${e}`,"Version=2010-05-08"];for(let[a,i]of Object.entries(t)){if(i===void 0||i===null)continue;if(Array.isArray(i))i.forEach((n,o)=>{if(typeof n==="object"&&n!==null)for(let[u,l]of Object.entries(n))r.push(`${a}.member.${o+1}.${u}=${encodeURIComponent(String(l))}`);else r.push(`${a}.member.${o+1}=${encodeURIComponent(String(n))}`)});else if(typeof i==="object"){for(let[n,o]of Object.entries(i))if(o!==void 0&&o!==null)r.push(`${a}.${n}=${encodeURIComponent(String(o))}`)}else r.push(`${a}=${encodeURIComponent(String(i))}`)}return r.join("&")}var f=new Kt({ignoreAttributes:!0,parseTagValue:!1,trimValues:!0});function S(e){if(typeof e!=="string"||!e.trim())return{};return f.parse(e)}function s(e,t){let r=[e];while(r.length>0){let a=[];for(let i of r){if(!i||typeof i!=="object")continue;if(Array.isArray(i)){a.push(...i);continue}if(t in i){let n=i[t];return typeof n==="string"?n:void 0}a.push(...Object.values(i))}r=a}return}function c(e,t,r){let a=[e];while(a.length>0){let i=[];for(let n of a){if(!n||typeof n!=="object")continue;if(Array.isArray(n)){i.push(...n);continue}if(t in n){let o=n[t]?.[r];return o===void 0||o===null?[]:Array.isArray(o)?o:[o]}i.push(...Object.values(n))}a=i}return[]}class te{client;region;constructor(e="us-east-1",t){this.client=new p(void 0,{profile:t}),this.region=e}async request(e,t={}){let r=R(e,t),a=await this.client.request({service:"iam",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r,rawResponse:!0});return S(a)}async createUser(e){let t=await this.request("CreateUser",e);return this.parseUser(t)}async getUser(e={}){let t=await this.request("GetUser",e);return this.parseUser(t)}async listUsers(e={}){let t=await this.request("ListUsers",e),r=this.parseUsers(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Users:r,IsTruncated:a,Marker:i}}async updateUser(e){await this.request("UpdateUser",e)}async deleteUser(e){await this.request("DeleteUser",e)}parseUser(e){return{UserName:s(e,"UserName")||"",UserId:s(e,"UserId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),CreateDate:s(e,"CreateDate"),PasswordLastUsed:s(e,"PasswordLastUsed")}}parseUsers(e){return c(e,"Users","member").map((r)=>({UserName:s(r,"UserName")||"",UserId:s(r,"UserId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),CreateDate:s(r,"CreateDate"),PasswordLastUsed:s(r,"PasswordLastUsed")}))}async createGroup(e){let t=await this.request("CreateGroup",e);return this.parseGroup(t)}async getGroup(e){let t=await this.request("GetGroup",e),r=this.parseGroup(t),a=this.parseUsers(t),i=s(t,"IsTruncated")==="true",n=s(t,"Marker");return{Group:r,Users:a,IsTruncated:i,Marker:n}}async listGroups(e={}){let t=await this.request("ListGroups",e),r=this.parseGroups(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Groups:r,IsTruncated:a,Marker:i}}async updateGroup(e){await this.request("UpdateGroup",e)}async deleteGroup(e){await this.request("DeleteGroup",e)}async addUserToGroup(e){await this.request("AddUserToGroup",e)}async removeUserFromGroup(e){await this.request("RemoveUserFromGroup",e)}async listGroupsForUser(e){let t=await this.request("ListGroupsForUser",e),r=this.parseGroups(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Groups:r,IsTruncated:a,Marker:i}}parseGroup(e){return{GroupName:s(e,"GroupName")||"",GroupId:s(e,"GroupId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),CreateDate:s(e,"CreateDate")}}parseGroups(e){return c(e,"Groups","member").map((r)=>({GroupName:s(r,"GroupName")||"",GroupId:s(r,"GroupId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),CreateDate:s(r,"CreateDate")}))}async createRole(e){let t=await this.request("CreateRole",e);return this.parseRole(t)}async getRole(e){let t=await this.request("GetRole",e);return this.parseRole(t)}async listRoles(e={}){let t=await this.request("ListRoles",e),r=this.parseRoles(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Roles:r,IsTruncated:a,Marker:i}}async updateRole(e){await this.request("UpdateRole",e)}async updateRoleDescription(e){let t=await this.request("UpdateRoleDescription",e);return this.parseRole(t)}async updateAssumeRolePolicy(e){await this.request("UpdateAssumeRolePolicy",e)}async deleteRole(e){await this.request("DeleteRole",e)}async tagRole(e){await this.request("TagRole",e)}async untagRole(e){await this.request("UntagRole",e)}async listRoleTags(e){let t=await this.request("ListRoleTags",e),r=this.parseTags(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Tags:r,IsTruncated:a,Marker:i}}parseRole(e){return{RoleName:s(e,"RoleName")||"",RoleId:s(e,"RoleId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),CreateDate:s(e,"CreateDate"),AssumeRolePolicyDocument:s(e,"AssumeRolePolicyDocument"),Description:s(e,"Description"),MaxSessionDuration:s(e,"MaxSessionDuration")?Number.parseInt(s(e,"MaxSessionDuration"),10):void 0}}parseRoles(e){return c(e,"Roles","member").map((r)=>({RoleName:s(r,"RoleName")||"",RoleId:s(r,"RoleId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),CreateDate:s(r,"CreateDate"),AssumeRolePolicyDocument:s(r,"AssumeRolePolicyDocument"),Description:s(r,"Description"),MaxSessionDuration:s(r,"MaxSessionDuration")?Number.parseInt(s(r,"MaxSessionDuration"),10):void 0}))}parseTags(e){return c(e,"Tags","member").map((r)=>({Key:s(r,"Key")||"",Value:s(r,"Value")||""}))}async createPolicy(e){let t=await this.request("CreatePolicy",e);return this.parsePolicy(t)}async getPolicy(e){let t=await this.request("GetPolicy",e);return this.parsePolicy(t)}async getPolicyVersion(e){let t=await this.request("GetPolicyVersion",e);return{VersionId:s(t,"VersionId")||"",IsDefaultVersion:s(t,"IsDefaultVersion")==="true",CreateDate:s(t,"CreateDate"),Document:s(t,"Document")}}async listPolicies(e={}){let t=await this.request("ListPolicies",e),r=this.parsePolicies(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Policies:r,IsTruncated:a,Marker:i}}async listPolicyVersions(e){let t=await this.request("ListPolicyVersions",e),r=this.parsePolicyVersions(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Versions:r,IsTruncated:a,Marker:i}}async createPolicyVersion(e){let t=await this.request("CreatePolicyVersion",e);return{VersionId:s(t,"VersionId")||"",IsDefaultVersion:s(t,"IsDefaultVersion")==="true",CreateDate:s(t,"CreateDate")}}async deletePolicyVersion(e){await this.request("DeletePolicyVersion",e)}async setDefaultPolicyVersion(e){await this.request("SetDefaultPolicyVersion",e)}async deletePolicy(e){await this.request("DeletePolicy",e)}async attachUserPolicy(e){await this.request("AttachUserPolicy",e)}async detachUserPolicy(e){await this.request("DetachUserPolicy",e)}async attachGroupPolicy(e){await this.request("AttachGroupPolicy",e)}async detachGroupPolicy(e){await this.request("DetachGroupPolicy",e)}async attachRolePolicy(e){await this.request("AttachRolePolicy",e)}async detachRolePolicy(e){await this.request("DetachRolePolicy",e)}async listAttachedUserPolicies(e){let t=await this.request("ListAttachedUserPolicies",e),r=this.parseAttachedPolicies(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{AttachedPolicies:r,IsTruncated:a,Marker:i}}async listAttachedGroupPolicies(e){let t=await this.request("ListAttachedGroupPolicies",e),r=this.parseAttachedPolicies(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{AttachedPolicies:r,IsTruncated:a,Marker:i}}async listAttachedRolePolicies(e){let t=await this.request("ListAttachedRolePolicies",e),r=this.parseAttachedPolicies(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{AttachedPolicies:r,IsTruncated:a,Marker:i}}parsePolicy(e){return{PolicyName:s(e,"PolicyName")||"",PolicyId:s(e,"PolicyId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),DefaultVersionId:s(e,"DefaultVersionId"),AttachmentCount:s(e,"AttachmentCount")?Number.parseInt(s(e,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:s(e,"PermissionsBoundaryUsageCount")?Number.parseInt(s(e,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:s(e,"IsAttachable")==="true",Description:s(e,"Description"),CreateDate:s(e,"CreateDate"),UpdateDate:s(e,"UpdateDate")}}parsePolicies(e){return c(e,"Policies","member").map((r)=>({PolicyName:s(r,"PolicyName")||"",PolicyId:s(r,"PolicyId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),DefaultVersionId:s(r,"DefaultVersionId"),AttachmentCount:s(r,"AttachmentCount")?Number.parseInt(s(r,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:s(r,"PermissionsBoundaryUsageCount")?Number.parseInt(s(r,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:s(r,"IsAttachable")==="true",Description:s(r,"Description"),CreateDate:s(r,"CreateDate"),UpdateDate:s(r,"UpdateDate")}))}parsePolicyVersions(e){return c(e,"Versions","member").map((r)=>({VersionId:s(r,"VersionId")||"",IsDefaultVersion:s(r,"IsDefaultVersion")==="true",CreateDate:s(r,"CreateDate")}))}parseAttachedPolicies(e){return c(e,"AttachedPolicies","member").map((r)=>({PolicyName:s(r,"PolicyName")||"",PolicyArn:s(r,"PolicyArn")||""}))}async putUserPolicy(e){await this.request("PutUserPolicy",e)}async getUserPolicy(e){let t=await this.request("GetUserPolicy",e);return{UserName:s(t,"UserName")||"",PolicyName:s(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(s(t,"PolicyDocument")||"")}}async deleteUserPolicy(e){await this.request("DeleteUserPolicy",e)}async listUserPolicies(e){let t=await this.request("ListUserPolicies",e),r=c(t,"PolicyNames","member"),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{PolicyNames:r,IsTruncated:a,Marker:i}}async putGroupPolicy(e){await this.request("PutGroupPolicy",e)}async getGroupPolicy(e){let t=await this.request("GetGroupPolicy",e);return{GroupName:s(t,"GroupName")||"",PolicyName:s(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(s(t,"PolicyDocument")||"")}}async deleteGroupPolicy(e){await this.request("DeleteGroupPolicy",e)}async listGroupPolicies(e){let t=await this.request("ListGroupPolicies",e),r=c(t,"PolicyNames","member"),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{PolicyNames:r,IsTruncated:a,Marker:i}}async putRolePolicy(e){await this.request("PutRolePolicy",e)}async getRolePolicy(e){let t=await this.request("GetRolePolicy",e);return{RoleName:s(t,"RoleName")||"",PolicyName:s(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(s(t,"PolicyDocument")||"")}}async deleteRolePolicy(e){await this.request("DeleteRolePolicy",e)}async listRolePolicies(e){let t=await this.request("ListRolePolicies",e),r=c(t,"PolicyNames","member"),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{PolicyNames:r,IsTruncated:a,Marker:i}}async createAccessKey(e={}){let t=await this.request("CreateAccessKey",e);if(typeof t==="object"){let r=t?.CreateAccessKeyResult?.AccessKey||t?.AccessKey;if(r)return{AccessKey:{UserName:r.UserName||"",AccessKeyId:r.AccessKeyId||"",Status:r.Status||"Active",SecretAccessKey:r.SecretAccessKey||"",CreateDate:r.CreateDate}}}return{AccessKey:{UserName:s(t,"UserName")||"",AccessKeyId:s(t,"AccessKeyId")||"",Status:s(t,"Status")||"Active",SecretAccessKey:s(t,"SecretAccessKey")||"",CreateDate:s(t,"CreateDate")}}}async listAccessKeys(e={}){let t=await this.request("ListAccessKeys",e),r=this.parseAccessKeys(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{AccessKeyMetadata:r,IsTruncated:a,Marker:i}}async updateAccessKey(e){await this.request("UpdateAccessKey",e)}async deleteAccessKey(e){await this.request("DeleteAccessKey",e)}async getAccessKeyLastUsed(e){let t=await this.request("GetAccessKeyLastUsed",e);return{UserName:s(t,"UserName")||"",AccessKeyLastUsed:{LastUsedDate:s(t,"LastUsedDate"),ServiceName:s(t,"ServiceName"),Region:s(t,"Region")}}}parseAccessKeys(e){return c(e,"AccessKeyMetadata","member").map((r)=>({UserName:s(r,"UserName"),AccessKeyId:s(r,"AccessKeyId")||"",Status:s(r,"Status")||"Active",CreateDate:s(r,"CreateDate")}))}async createInstanceProfile(e){let t=await this.request("CreateInstanceProfile",e);return this.parseInstanceProfile(t)}async getInstanceProfile(e){let t=await this.request("GetInstanceProfile",e);return this.parseInstanceProfile(t)}async listInstanceProfiles(e={}){let t=await this.request("ListInstanceProfiles",e),r=this.parseInstanceProfiles(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{InstanceProfiles:r,IsTruncated:a,Marker:i}}async listInstanceProfilesForRole(e){let t=await this.request("ListInstanceProfilesForRole",e),r=this.parseInstanceProfiles(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{InstanceProfiles:r,IsTruncated:a,Marker:i}}async addRoleToInstanceProfile(e){await this.request("AddRoleToInstanceProfile",e)}async removeRoleFromInstanceProfile(e){await this.request("RemoveRoleFromInstanceProfile",e)}async deleteInstanceProfile(e){await this.request("DeleteInstanceProfile",e)}parseInstanceProfile(e){return{InstanceProfileName:s(e,"InstanceProfileName")||"",InstanceProfileId:s(e,"InstanceProfileId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),CreateDate:s(e,"CreateDate")}}parseInstanceProfiles(e){return c(e,"InstanceProfiles","member").map((r)=>({InstanceProfileName:s(r,"InstanceProfileName")||"",InstanceProfileId:s(r,"InstanceProfileId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),CreateDate:s(r,"CreateDate")}))}async getAccountPasswordPolicy(){let e=await this.request("GetAccountPasswordPolicy");return{MinimumPasswordLength:s(e,"MinimumPasswordLength")?Number.parseInt(s(e,"MinimumPasswordLength"),10):void 0,RequireSymbols:s(e,"RequireSymbols")==="true",RequireNumbers:s(e,"RequireNumbers")==="true",RequireUppercaseCharacters:s(e,"RequireUppercaseCharacters")==="true",RequireLowercaseCharacters:s(e,"RequireLowercaseCharacters")==="true",AllowUsersToChangePassword:s(e,"AllowUsersToChangePassword")==="true",ExpirePasswords:s(e,"ExpirePasswords")==="true",MaxPasswordAge:s(e,"MaxPasswordAge")?Number.parseInt(s(e,"MaxPasswordAge"),10):void 0,PasswordReusePrevention:s(e,"PasswordReusePrevention")?Number.parseInt(s(e,"PasswordReusePrevention"),10):void 0,HardExpiry:s(e,"HardExpiry")==="true"}}async updateAccountPasswordPolicy(e){await this.request("UpdateAccountPasswordPolicy",e)}async deleteAccountPasswordPolicy(){await this.request("DeleteAccountPasswordPolicy")}async getAccountSummary(){let e=await this.request("GetAccountSummary"),t={},r=c(e,"SummaryMap","entry");for(let a of r){let i=s(a,"key"),n=s(a,"value");if(i&&n)t[i]=Number.parseInt(n,10)}return t}async listAccountAliases(){let e=await this.request("ListAccountAliases"),t=c(e,"AccountAliases","member"),r=s(e,"IsTruncated")==="true",a=s(e,"Marker");return{AccountAliases:t,IsTruncated:r,Marker:a}}async createAccountAlias(e){await this.request("CreateAccountAlias",e)}async deleteAccountAlias(e){await this.request("DeleteAccountAlias",e)}async simulatePrincipalPolicy(e){let t=await this.request("SimulatePrincipalPolicy",e);return this.parseSimulationResults(t)}parseSimulationResults(e){let r=c(e,"EvaluationResults","member").map((n)=>{let u=c(n,"MatchedStatements","member").map((l)=>({SourcePolicyId:s(l,"SourcePolicyId"),SourcePolicyType:s(l,"SourcePolicyType")}));return{EvalActionName:s(n,"EvalActionName")||"",EvalResourceName:s(n,"EvalResourceName"),EvalDecision:s(n,"EvalDecision")||"",MatchedStatements:u.length>0?u:void 0}}),a=s(e,"IsTruncated")==="true",i=s(e,"Marker");return{EvaluationResults:r,IsTruncated:a,Marker:i}}}class we{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new p(t)}async createEmailIdentity(e){return await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/identities",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async getEmailIdentity(e){let t=await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/identities/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}});return{IdentityType:t.IdentityType,IdentityName:e,SendingEnabled:t.VerifiedForSendingStatus,VerificationStatus:t.VerificationStatus,DkimAttributes:t.DkimAttributes,MailFromAttributes:t.MailFromAttributes}}async putEmailIdentityMailFromAttributes(e,t){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(e)}/mail-from`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async listEmailIdentities(e){let t="/v2/email/identities",r=[];if(e?.PageSize)r.push(`PageSize=${e.PageSize}`);if(e?.NextToken)r.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(r.length>0)t+=`?${r.join("&")}`;let a=await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}});return{EmailIdentities:a.EmailIdentities,NextToken:a.NextToken}}async deleteEmailIdentity(e){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/identities/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async putEmailIdentityDkimAttributes(e){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(e.EmailIdentity)}/dkim`,headers:{"Content-Type":"application/json"},body:JSON.stringify({SigningEnabled:e.SigningEnabled})})}async sendEmail(e){return{MessageId:(await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/outbound-emails",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).MessageId}}async sendBulkEmail(e){return{BulkEmailEntryResults:(await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/outbound-bulk-emails",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).BulkEmailEntryResults}}async createEmailTemplate(e){await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/templates",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async getEmailTemplate(e){return await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/templates/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async deleteEmailTemplate(e){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/templates/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async listEmailTemplates(e){let t="/v2/email/templates",r=[];if(e?.PageSize)r.push(`PageSize=${e.PageSize}`);if(e?.NextToken)r.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(r.length>0)t+=`?${r.join("&")}`;return await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}})}async getSendStatistics(){let e=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendStatistics&Version=2010-12-01"}),t=L(e,"GetSendStatistics")?.SendDataPoints?.member;return{SendDataPoints:t==null?[]:Array.isArray(t)?t:[t]}}async getSendQuota(){let e=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendQuota&Version=2010-12-01"}),t=L(e,"GetSendQuota"),r=(a)=>a==null||a===""?void 0:Number(a);return{Max24HourSend:r(t?.Max24HourSend),MaxSendRate:r(t?.MaxSendRate),SentLast24Hours:r(t?.SentLast24Hours)}}async verifyDomain(e){let t=await this.createEmailIdentity({EmailIdentity:e});return{dkimTokens:t.DkimAttributes?.Tokens,verificationStatus:t.DkimAttributes?.Status}}async sendSimpleEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],r=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0,a={};if(e.text)a.Text={Data:e.text};if(e.html)a.Html={Data:e.html};return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Simple:{Subject:{Data:e.subject},Body:a}},ReplyToAddresses:r})}async sendTemplatedEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],r=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0;return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Template:{TemplateName:e.templateName,TemplateData:JSON.stringify(e.templateData)}},ReplyToAddresses:r})}async getDkimRecords(e){let t=await this.getEmailIdentity(e);if(!t.DkimAttributes?.Tokens)return[];return t.DkimAttributes.Tokens.map((r)=>({name:`${r}._domainkey.${e}`,type:"CNAME",value:`${r}.dkim.amazonses.com`}))}async isDomainVerified(e){try{let t=await this.getEmailIdentity(e);return t.VerificationStatus==="SUCCESS"&&t.SendingEnabled===!0}catch{return!1}}async waitForDomainVerification(e,t=60,r=30000){for(let a=0;a<t;a++){if(await this.isDomainVerified(e))return!0;await new Promise((n)=>setTimeout(n,r))}return!1}buildFormBody(e){return Object.entries(e).filter(([,r])=>r!==void 0).map(([r,a])=>`${encodeURIComponent(r)}=${encodeURIComponent(a)}`).join("&")}async createReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"CreateReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async deleteReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async setActiveReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"SetActiveReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async listReceiptRuleSets(e){let t={Action:"ListReceiptRuleSets",Version:"2010-12-01"};if(e)t.NextToken=e;let r=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)}),a=r?.ListReceiptRuleSetsResponse?.ListReceiptRuleSetsResult||r?.ListReceiptRuleSetsResult,i=a?.RuleSets?.member;return{RuleSets:Array.isArray(i)?i:i?[i]:[],NextToken:a?.NextToken}}async describeReceiptRuleSet(e){let t=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DescribeReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})}),r=t?.DescribeReceiptRuleSetResponse?.DescribeReceiptRuleSetResult||t?.DescribeReceiptRuleSetResult,a=r?.Rules?.member;return{Metadata:r?.Metadata,Rules:Array.isArray(a)?a:a?[a]:[]}}async createReceiptRule(e){let t={Action:"CreateReceiptRule",Version:"2010-12-01",RuleSetName:e.RuleSetName,"Rule.Name":e.Rule.Name,"Rule.Enabled":e.Rule.Enabled!==!1?"true":"false"};if(e.Rule.TlsPolicy)t["Rule.TlsPolicy"]=e.Rule.TlsPolicy;if(e.Rule.ScanEnabled!==void 0)t["Rule.ScanEnabled"]=e.Rule.ScanEnabled?"true":"false";if(e.After)t.After=e.After;if(e.Rule.Recipients)e.Rule.Recipients.forEach((r,a)=>{t[`Rule.Recipients.member.${a+1}`]=r});e.Rule.Actions.forEach((r,a)=>{let i=a+1;if(r.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=r.S3Action.BucketName,r.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=r.S3Action.ObjectKeyPrefix;if(r.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=r.S3Action.KmsKeyArn}if(r.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=r.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=r.LambdaAction.InvocationType||"Event";if(r.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=r.SNSAction.TopicArn,r.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=r.SNSAction.Encoding}if(r.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=r.StopAction.Scope,r.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=r.StopAction.TopicArn}}),await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)})}async deleteReceiptRule(e,t){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteReceiptRule",Version:"2010-12-01",RuleSetName:e,RuleName:t})})}async receiptRuleSetExists(e){try{return await this.describeReceiptRuleSet(e),!0}catch(t){if(t.code==="RuleSetDoesNotExist"||t.statusCode===400)return!1;throw t}}async getActiveReceiptRuleSet(){let e=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DescribeActiveReceiptRuleSet",Version:"2010-12-01"})}),t=e?.DescribeActiveReceiptRuleSetResponse?.DescribeActiveReceiptRuleSetResult||e?.DescribeActiveReceiptRuleSetResult;if(!t?.Metadata)return null;let r=t?.Rules?.member;return{Metadata:t?.Metadata,Rules:Array.isArray(r)?r:r?[r]:[]}}async updateReceiptRule(e){let t={Action:"UpdateReceiptRule",Version:"2010-12-01",RuleSetName:e.RuleSetName,"Rule.Name":e.Rule.Name};if(e.Rule.Enabled!==void 0)t["Rule.Enabled"]=e.Rule.Enabled?"true":"false";if(e.Rule.TlsPolicy)t["Rule.TlsPolicy"]=e.Rule.TlsPolicy;if(e.Rule.ScanEnabled!==void 0)t["Rule.ScanEnabled"]=e.Rule.ScanEnabled?"true":"false";if(e.Rule.Recipients)e.Rule.Recipients.forEach((r,a)=>{t[`Rule.Recipients.member.${a+1}`]=r});e.Rule.Actions.forEach((r,a)=>{let i=a+1;if(r.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=r.S3Action.BucketName,r.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=r.S3Action.ObjectKeyPrefix;if(r.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=r.S3Action.KmsKeyArn}if(r.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=r.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=r.LambdaAction.InvocationType||"Event";if(r.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=r.SNSAction.TopicArn,r.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=r.SNSAction.Encoding}if(r.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=r.StopAction.Scope,r.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=r.StopAction.TopicArn}}),await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)})}async sendRawEmail(e){let t=Buffer.from(e.rawMessage).toString("base64"),r={Action:"SendRawEmail",Version:"2010-12-01",Source:e.source,"RawMessage.Data":t};e.destinations.forEach((n,o)=>{r[`Destinations.member.${o+1}`]=n});let a=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(r)});return{MessageId:(a?.SendRawEmailResponse?.SendRawEmailResult||a?.SendRawEmailResult)?.MessageId}}async getSuppressedDestination(e){try{return(await this.client.request({service:"ses",region:this.region,method:"GET",path:`/v2/email/suppression/addresses/${encodeURIComponent(e)}`}))?.SuppressedDestination||null}catch(t){if(t.message?.includes("404")||t.message?.includes("NotFoundException"))return null;throw t}}async deleteSuppressedDestination(e){await this.client.request({service:"ses",region:this.region,method:"DELETE",path:`/v2/email/suppression/addresses/${encodeURIComponent(e)}`})}}class Zc{ses;s3;iam;route53;region;domain;defaultFrom;constructor(e={}){this.region=e.region||"us-east-1",this.domain=e.domain,this.defaultFrom=e.defaultFrom,this.ses=new we(this.region),this.s3=new g(this.region),this.iam=new te(this.region),this.route53=new F(this.region)}async send(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required. Set defaultFrom in constructor or provide from in options.");let r=e.fromName?`${e.fromName} <${t}>`:t,a=Array.isArray(e.to)?e.to:[e.to];if(!e.attachments||e.attachments.length===0)return{messageId:(await this.ses.sendSimpleEmail({from:r,to:a,subject:e.subject,text:e.text,html:e.html,replyTo:e.replyTo})).MessageId||""};let i=this.buildRawEmail(e,r,a);return{messageId:(await this.ses.sendEmail({FromEmailAddress:r,Destination:{ToAddresses:a,CcAddresses:e.cc?Array.isArray(e.cc)?e.cc:[e.cc]:void 0,BccAddresses:e.bcc?Array.isArray(e.bcc)?e.bcc:[e.bcc]:void 0},Content:{Raw:{Data:Buffer.from(i).toString("base64")}}})).MessageId||""}}async sendTemplate(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required");let r=e.fromName?`${e.fromName} <${t}>`:t;return{messageId:(await this.ses.sendTemplatedEmail({from:r,to:e.to,templateName:e.templateName,templateData:e.templateData,replyTo:e.replyTo})).MessageId||""}}async sendBulk(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required");let r=e.recipients.map((i)=>({Destination:{ToAddresses:Array.isArray(i.to)?i.to:[i.to]},ReplacementEmailContent:i.templateData?{ReplacementTemplate:{ReplacementTemplateData:JSON.stringify(i.templateData)}}:void 0}));return{results:(await this.ses.sendBulkEmail({FromEmailAddress:t,BulkEmailEntries:r,DefaultContent:{Template:{TemplateName:e.templateName,TemplateData:JSON.stringify(e.defaultTemplateData)}}})).BulkEmailEntryResults?.map((i)=>({status:i.Status||"UNKNOWN",messageId:i.MessageId,error:i.Error}))||[]}}async setupDomain(e){let t;try{t=await this.ses.getEmailIdentity(e)}catch{let a=await this.ses.createEmailIdentity({EmailIdentity:e});t={VerificationStatus:a.DkimAttributes?.Status,DkimAttributes:a.DkimAttributes,SendingEnabled:a.VerifiedForSendingStatus}}try{await this.ses.putEmailIdentityDkimAttributes({EmailIdentity:e,SigningEnabled:!0})}catch{}try{await this.ses.putEmailIdentityMailFromAttributes(e,{MailFromDomain:`mail.${e}`,BehaviorOnMxFailure:"USE_DEFAULT_VALUE"})}catch{}let r=await this.ses.getDkimRecords(e);return{domainVerified:t.SendingEnabled===!0,dkimStatus:t.DkimAttributes?.Status||"UNKNOWN",dkimTokens:t.DkimAttributes?.Tokens,mailFromStatus:t.MailFromAttributes?.MailFromDomainStatus}}async getDnsRecords(e){let t=[],r=await this.ses.getDkimRecords(e);for(let a of r)t.push({type:a.type,name:a.name,value:a.value,ttl:1800});return t.push({type:"MX",name:e,value:`inbound-smtp.${this.region}.amazonaws.com`,priority:10,ttl:3600}),t.push({type:"MX",name:`mail.${e}`,value:`feedback-smtp.${this.region}.amazonses.com`,priority:10,ttl:3600}),t.push({type:"TXT",name:`mail.${e}`,value:"v=spf1 include:amazonses.com ~all",ttl:3600}),t.push({type:"TXT",name:`_dmarc.${e}`,value:`v=DMARC1;p=quarantine;pct=25;rua=mailto:dmarcreports@${e}`,ttl:3600}),t}async isDomainReady(e){try{let t=await this.ses.getEmailIdentity(e);return t.SendingEnabled===!0&&t.DkimAttributes?.Status==="SUCCESS"}catch{return!1}}async setupReceiving(e){let t={Version:"2012-10-17",Statement:[{Sid:"AllowSESPuts",Effect:"Allow",Principal:{Service:"ses.amazonaws.com"},Action:"s3:PutObject",Resource:`arn:aws:s3:::${e.bucketName}/*`,Condition:{StringEquals:{"AWS:SourceAccount":e.accountId}}}]};await this.s3.putBucketPolicy(e.bucketName,t);try{await this.ses.createReceiptRuleSet(e.ruleSetName)}catch(a){if(!a.message?.includes("already exists")&&a.code!=="AlreadyExists")throw a}let r=[{S3Action:{BucketName:e.bucketName,ObjectKeyPrefix:e.prefix||"inbox/"}}];if(e.lambdaArn)r.push({LambdaAction:{FunctionArn:e.lambdaArn,InvocationType:"Event"}});try{await this.ses.createReceiptRule({RuleSetName:e.ruleSetName,Rule:{Name:e.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:e.recipients||[e.domain],ScanEnabled:e.scanEnabled!==!1,Actions:r}})}catch(a){if(a.message?.includes("already exists"))await this.ses.deleteReceiptRule(e.ruleSetName,e.ruleName),await this.ses.createReceiptRule({RuleSetName:e.ruleSetName,Rule:{Name:e.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:e.recipients||[e.domain],ScanEnabled:e.scanEnabled!==!1,Actions:r}});else throw a}await this.ses.setActiveReceiptRuleSet(e.ruleSetName)}async getIncomingEmails(e){return(await this.s3.list({bucket:e.bucket,prefix:e.prefix||"incoming/",maxKeys:e.maxResults||100})).map((r)=>({key:r.Key||"",lastModified:r.LastModified||"",size:r.Size||0}))}async readEmail(e){return await this.s3.getObject(e.bucket,e.key)}async createSmtpCredentials(e){let t=`ses-smtp-${e.username.replace(/[^a-zA-Z0-9]/g,"-")}`,{AWSClient:r}=await import("./chunk-qe8zh9kn.js"),a=new r,i=(m,y)=>{let P={Action:m,Version:"2010-05-08",...y};return Object.entries(P).map(([A,h])=>`${encodeURIComponent(A)}=${encodeURIComponent(h)}`).join("&")};try{await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateUser",{UserName:t})})}catch(m){if(!m.message?.includes("EntityAlreadyExists"))throw m}let n={Version:"2012-10-17",Statement:[{Effect:"Allow",Action:"ses:SendRawEmail",Resource:"*",Condition:{StringLike:{"ses:FromAddress":`*@${e.domain}`}}}]},o=`ses-smtp-policy-${e.domain.replace(/\./g,"-")}`;try{await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("PutUserPolicy",{UserName:t,PolicyName:o,PolicyDocument:JSON.stringify(n)})})}catch{}let l=(await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateAccessKey",{UserName:t})}))?.CreateAccessKeyResult?.AccessKey;if(!l?.AccessKeyId||!l?.SecretAccessKey)throw Error("Failed to create access key");let d=this.deriveSmtpPassword(l.SecretAccessKey);return{username:l.AccessKeyId,password:d,server:`email-smtp.${this.region}.amazonaws.com`,port:587}}deriveSmtpPassword(e){let t=Gr("node:crypto"),r="SendRawEmail",a=Buffer.from([4]),i=t.createHmac("sha256",`AWS4${e}`).update("11111111").digest();return i=t.createHmac("sha256",i).update(this.region).digest(),i=t.createHmac("sha256",i).update("ses").digest(),i=t.createHmac("sha256",i).update("aws4_request").digest(),i=t.createHmac("sha256",i).update("SendRawEmail").digest(),Buffer.concat([a,i]).toString("base64")}async createTemplate(e){await this.ses.createEmailTemplate({TemplateName:e.name,TemplateContent:{Subject:e.subject,Text:e.text,Html:e.html}})}async getTemplate(e){try{let t=await this.ses.getEmailTemplate(e);return{name:t.TemplateName||e,subject:t.TemplateContent?.Subject,text:t.TemplateContent?.Text,html:t.TemplateContent?.Html}}catch{return null}}async deleteTemplate(e){await this.ses.deleteEmailTemplate(e)}async listTemplates(){return(await this.ses.listEmailTemplates()).TemplatesMetadata?.map((t)=>({name:t.TemplateName||"",createdAt:t.CreatedTimestamp}))||[]}async deploy(e){let t=`${e.appName}-${e.environment}-email-rules`,r=`${e.appName}-inbound-email`,a=e.storage?.bucketName||`${e.appName}-${e.environment}-email`,i=await this.setupDomain(e.domain);if(!(await this.s3.listBuckets()).Buckets?.some((l)=>l.Name===a))await this.s3.createBucket(a);await this.setupReceiving({domain:e.domain,ruleSetName:t,ruleName:r,bucketName:a,prefix:e.storage?.prefix||"inbox/",accountId:e.accountId,recipients:e.catchAll?[e.domain]:e.mailboxes,scanEnabled:!0});let u=await this.getDnsRecords(e.domain);return{success:!0,domainVerified:i.domainVerified,dkimStatus:i.dkimStatus,receiptRuleSet:t,storageBucket:a,dnsRecords:u}}async undeploy(e){let t=`${e.appName}-${e.environment}-email-rules`,r=`${e.appName}-inbound-email`,a=`${e.appName}-${e.environment}-email`;try{await this.ses.deleteReceiptRule(t,r)}catch{}try{await this.ses.deleteReceiptRuleSet(t)}catch{}if(e.deleteBucket)try{await this.s3.emptyAndDeleteBucket(a)}catch{}}async getSendingStats(){let e=await this.ses.getSendQuota();return{sentLast24Hours:e.SentLast24Hours||0,maxSendRate:e.MaxSendRate||0,max24HourSend:e.Max24HourSend||0}}buildRawEmail(e,t,r){let a=`----=_Part_${Date.now()}_${Math.random().toString(36).substring(2)}`,i="";if(i+=`From: ${t}\r
|
|
1
|
+
import{Kt,p}from"./chunk-9cj1fm00.js";import{g}from"./chunk-zph18vv6.js";import{B}from"./chunk-reexpdfk.js";import{L}from"./chunk-gbbcp2bw.js";import{Gr}from"./chunk-7v68hpgc.js";function R(e,t){let r=[`Action=${e}`,"Version=2010-05-08"];for(let[a,i]of Object.entries(t)){if(i===void 0||i===null)continue;if(Array.isArray(i))i.forEach((n,o)=>{if(typeof n==="object"&&n!==null)for(let[u,l]of Object.entries(n))r.push(`${a}.member.${o+1}.${u}=${encodeURIComponent(String(l))}`);else r.push(`${a}.member.${o+1}=${encodeURIComponent(String(n))}`)});else if(typeof i==="object"){for(let[n,o]of Object.entries(i))if(o!==void 0&&o!==null)r.push(`${a}.${n}=${encodeURIComponent(String(o))}`)}else r.push(`${a}=${encodeURIComponent(String(i))}`)}return r.join("&")}var f=new Kt({ignoreAttributes:!0,parseTagValue:!1,trimValues:!0});function S(e){if(typeof e!=="string"||!e.trim())return{};return f.parse(e)}function s(e,t){let r=[e];while(r.length>0){let a=[];for(let i of r){if(!i||typeof i!=="object")continue;if(Array.isArray(i)){a.push(...i);continue}if(t in i){let n=i[t];return typeof n==="string"?n:void 0}a.push(...Object.values(i))}r=a}return}function c(e,t,r){let a=[e];while(a.length>0){let i=[];for(let n of a){if(!n||typeof n!=="object")continue;if(Array.isArray(n)){i.push(...n);continue}if(t in n){let o=n[t]?.[r];return o===void 0||o===null?[]:Array.isArray(o)?o:[o]}i.push(...Object.values(n))}a=i}return[]}class te{client;region;constructor(e="us-east-1",t){this.client=new p(void 0,{profile:t}),this.region=e}async request(e,t={}){let r=R(e,t),a=await this.client.request({service:"iam",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r,rawResponse:!0});return S(a)}async createUser(e){let t=await this.request("CreateUser",e);return this.parseUser(t)}async getUser(e={}){let t=await this.request("GetUser",e);return this.parseUser(t)}async listUsers(e={}){let t=await this.request("ListUsers",e),r=this.parseUsers(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Users:r,IsTruncated:a,Marker:i}}async updateUser(e){await this.request("UpdateUser",e)}async deleteUser(e){await this.request("DeleteUser",e)}parseUser(e){return{UserName:s(e,"UserName")||"",UserId:s(e,"UserId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),CreateDate:s(e,"CreateDate"),PasswordLastUsed:s(e,"PasswordLastUsed")}}parseUsers(e){return c(e,"Users","member").map((r)=>({UserName:s(r,"UserName")||"",UserId:s(r,"UserId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),CreateDate:s(r,"CreateDate"),PasswordLastUsed:s(r,"PasswordLastUsed")}))}async createGroup(e){let t=await this.request("CreateGroup",e);return this.parseGroup(t)}async getGroup(e){let t=await this.request("GetGroup",e),r=this.parseGroup(t),a=this.parseUsers(t),i=s(t,"IsTruncated")==="true",n=s(t,"Marker");return{Group:r,Users:a,IsTruncated:i,Marker:n}}async listGroups(e={}){let t=await this.request("ListGroups",e),r=this.parseGroups(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Groups:r,IsTruncated:a,Marker:i}}async updateGroup(e){await this.request("UpdateGroup",e)}async deleteGroup(e){await this.request("DeleteGroup",e)}async addUserToGroup(e){await this.request("AddUserToGroup",e)}async removeUserFromGroup(e){await this.request("RemoveUserFromGroup",e)}async listGroupsForUser(e){let t=await this.request("ListGroupsForUser",e),r=this.parseGroups(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Groups:r,IsTruncated:a,Marker:i}}parseGroup(e){return{GroupName:s(e,"GroupName")||"",GroupId:s(e,"GroupId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),CreateDate:s(e,"CreateDate")}}parseGroups(e){return c(e,"Groups","member").map((r)=>({GroupName:s(r,"GroupName")||"",GroupId:s(r,"GroupId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),CreateDate:s(r,"CreateDate")}))}async createRole(e){let t=await this.request("CreateRole",e);return this.parseRole(t)}async getRole(e){let t=await this.request("GetRole",e);return this.parseRole(t)}async listRoles(e={}){let t=await this.request("ListRoles",e),r=this.parseRoles(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Roles:r,IsTruncated:a,Marker:i}}async updateRole(e){await this.request("UpdateRole",e)}async updateRoleDescription(e){let t=await this.request("UpdateRoleDescription",e);return this.parseRole(t)}async updateAssumeRolePolicy(e){await this.request("UpdateAssumeRolePolicy",e)}async deleteRole(e){await this.request("DeleteRole",e)}async tagRole(e){await this.request("TagRole",e)}async untagRole(e){await this.request("UntagRole",e)}async listRoleTags(e){let t=await this.request("ListRoleTags",e),r=this.parseTags(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Tags:r,IsTruncated:a,Marker:i}}parseRole(e){return{RoleName:s(e,"RoleName")||"",RoleId:s(e,"RoleId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),CreateDate:s(e,"CreateDate"),AssumeRolePolicyDocument:s(e,"AssumeRolePolicyDocument"),Description:s(e,"Description"),MaxSessionDuration:s(e,"MaxSessionDuration")?Number.parseInt(s(e,"MaxSessionDuration"),10):void 0}}parseRoles(e){return c(e,"Roles","member").map((r)=>({RoleName:s(r,"RoleName")||"",RoleId:s(r,"RoleId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),CreateDate:s(r,"CreateDate"),AssumeRolePolicyDocument:s(r,"AssumeRolePolicyDocument"),Description:s(r,"Description"),MaxSessionDuration:s(r,"MaxSessionDuration")?Number.parseInt(s(r,"MaxSessionDuration"),10):void 0}))}parseTags(e){return c(e,"Tags","member").map((r)=>({Key:s(r,"Key")||"",Value:s(r,"Value")||""}))}async createPolicy(e){let t=await this.request("CreatePolicy",e);return this.parsePolicy(t)}async getPolicy(e){let t=await this.request("GetPolicy",e);return this.parsePolicy(t)}async getPolicyVersion(e){let t=await this.request("GetPolicyVersion",e);return{VersionId:s(t,"VersionId")||"",IsDefaultVersion:s(t,"IsDefaultVersion")==="true",CreateDate:s(t,"CreateDate"),Document:s(t,"Document")}}async listPolicies(e={}){let t=await this.request("ListPolicies",e),r=this.parsePolicies(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Policies:r,IsTruncated:a,Marker:i}}async listPolicyVersions(e){let t=await this.request("ListPolicyVersions",e),r=this.parsePolicyVersions(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Versions:r,IsTruncated:a,Marker:i}}async createPolicyVersion(e){let t=await this.request("CreatePolicyVersion",e);return{VersionId:s(t,"VersionId")||"",IsDefaultVersion:s(t,"IsDefaultVersion")==="true",CreateDate:s(t,"CreateDate")}}async deletePolicyVersion(e){await this.request("DeletePolicyVersion",e)}async setDefaultPolicyVersion(e){await this.request("SetDefaultPolicyVersion",e)}async deletePolicy(e){await this.request("DeletePolicy",e)}async attachUserPolicy(e){await this.request("AttachUserPolicy",e)}async detachUserPolicy(e){await this.request("DetachUserPolicy",e)}async attachGroupPolicy(e){await this.request("AttachGroupPolicy",e)}async detachGroupPolicy(e){await this.request("DetachGroupPolicy",e)}async attachRolePolicy(e){await this.request("AttachRolePolicy",e)}async detachRolePolicy(e){await this.request("DetachRolePolicy",e)}async listAttachedUserPolicies(e){let t=await this.request("ListAttachedUserPolicies",e),r=this.parseAttachedPolicies(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{AttachedPolicies:r,IsTruncated:a,Marker:i}}async listAttachedGroupPolicies(e){let t=await this.request("ListAttachedGroupPolicies",e),r=this.parseAttachedPolicies(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{AttachedPolicies:r,IsTruncated:a,Marker:i}}async listAttachedRolePolicies(e){let t=await this.request("ListAttachedRolePolicies",e),r=this.parseAttachedPolicies(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{AttachedPolicies:r,IsTruncated:a,Marker:i}}parsePolicy(e){return{PolicyName:s(e,"PolicyName")||"",PolicyId:s(e,"PolicyId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),DefaultVersionId:s(e,"DefaultVersionId"),AttachmentCount:s(e,"AttachmentCount")?Number.parseInt(s(e,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:s(e,"PermissionsBoundaryUsageCount")?Number.parseInt(s(e,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:s(e,"IsAttachable")==="true",Description:s(e,"Description"),CreateDate:s(e,"CreateDate"),UpdateDate:s(e,"UpdateDate")}}parsePolicies(e){return c(e,"Policies","member").map((r)=>({PolicyName:s(r,"PolicyName")||"",PolicyId:s(r,"PolicyId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),DefaultVersionId:s(r,"DefaultVersionId"),AttachmentCount:s(r,"AttachmentCount")?Number.parseInt(s(r,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:s(r,"PermissionsBoundaryUsageCount")?Number.parseInt(s(r,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:s(r,"IsAttachable")==="true",Description:s(r,"Description"),CreateDate:s(r,"CreateDate"),UpdateDate:s(r,"UpdateDate")}))}parsePolicyVersions(e){return c(e,"Versions","member").map((r)=>({VersionId:s(r,"VersionId")||"",IsDefaultVersion:s(r,"IsDefaultVersion")==="true",CreateDate:s(r,"CreateDate")}))}parseAttachedPolicies(e){return c(e,"AttachedPolicies","member").map((r)=>({PolicyName:s(r,"PolicyName")||"",PolicyArn:s(r,"PolicyArn")||""}))}async putUserPolicy(e){await this.request("PutUserPolicy",e)}async getUserPolicy(e){let t=await this.request("GetUserPolicy",e);return{UserName:s(t,"UserName")||"",PolicyName:s(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(s(t,"PolicyDocument")||"")}}async deleteUserPolicy(e){await this.request("DeleteUserPolicy",e)}async listUserPolicies(e){let t=await this.request("ListUserPolicies",e),r=c(t,"PolicyNames","member"),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{PolicyNames:r,IsTruncated:a,Marker:i}}async putGroupPolicy(e){await this.request("PutGroupPolicy",e)}async getGroupPolicy(e){let t=await this.request("GetGroupPolicy",e);return{GroupName:s(t,"GroupName")||"",PolicyName:s(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(s(t,"PolicyDocument")||"")}}async deleteGroupPolicy(e){await this.request("DeleteGroupPolicy",e)}async listGroupPolicies(e){let t=await this.request("ListGroupPolicies",e),r=c(t,"PolicyNames","member"),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{PolicyNames:r,IsTruncated:a,Marker:i}}async putRolePolicy(e){await this.request("PutRolePolicy",e)}async getRolePolicy(e){let t=await this.request("GetRolePolicy",e);return{RoleName:s(t,"RoleName")||"",PolicyName:s(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(s(t,"PolicyDocument")||"")}}async deleteRolePolicy(e){await this.request("DeleteRolePolicy",e)}async listRolePolicies(e){let t=await this.request("ListRolePolicies",e),r=c(t,"PolicyNames","member"),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{PolicyNames:r,IsTruncated:a,Marker:i}}async createAccessKey(e={}){let t=await this.request("CreateAccessKey",e);if(typeof t==="object"){let r=t?.CreateAccessKeyResult?.AccessKey||t?.AccessKey;if(r)return{AccessKey:{UserName:r.UserName||"",AccessKeyId:r.AccessKeyId||"",Status:r.Status||"Active",SecretAccessKey:r.SecretAccessKey||"",CreateDate:r.CreateDate}}}return{AccessKey:{UserName:s(t,"UserName")||"",AccessKeyId:s(t,"AccessKeyId")||"",Status:s(t,"Status")||"Active",SecretAccessKey:s(t,"SecretAccessKey")||"",CreateDate:s(t,"CreateDate")}}}async listAccessKeys(e={}){let t=await this.request("ListAccessKeys",e),r=this.parseAccessKeys(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{AccessKeyMetadata:r,IsTruncated:a,Marker:i}}async updateAccessKey(e){await this.request("UpdateAccessKey",e)}async deleteAccessKey(e){await this.request("DeleteAccessKey",e)}async getAccessKeyLastUsed(e){let t=await this.request("GetAccessKeyLastUsed",e);return{UserName:s(t,"UserName")||"",AccessKeyLastUsed:{LastUsedDate:s(t,"LastUsedDate"),ServiceName:s(t,"ServiceName"),Region:s(t,"Region")}}}parseAccessKeys(e){return c(e,"AccessKeyMetadata","member").map((r)=>({UserName:s(r,"UserName"),AccessKeyId:s(r,"AccessKeyId")||"",Status:s(r,"Status")||"Active",CreateDate:s(r,"CreateDate")}))}async createInstanceProfile(e){let t=await this.request("CreateInstanceProfile",e);return this.parseInstanceProfile(t)}async getInstanceProfile(e){let t=await this.request("GetInstanceProfile",e);return this.parseInstanceProfile(t)}async listInstanceProfiles(e={}){let t=await this.request("ListInstanceProfiles",e),r=this.parseInstanceProfiles(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{InstanceProfiles:r,IsTruncated:a,Marker:i}}async listInstanceProfilesForRole(e){let t=await this.request("ListInstanceProfilesForRole",e),r=this.parseInstanceProfiles(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{InstanceProfiles:r,IsTruncated:a,Marker:i}}async addRoleToInstanceProfile(e){await this.request("AddRoleToInstanceProfile",e)}async removeRoleFromInstanceProfile(e){await this.request("RemoveRoleFromInstanceProfile",e)}async deleteInstanceProfile(e){await this.request("DeleteInstanceProfile",e)}parseInstanceProfile(e){return{InstanceProfileName:s(e,"InstanceProfileName")||"",InstanceProfileId:s(e,"InstanceProfileId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),CreateDate:s(e,"CreateDate")}}parseInstanceProfiles(e){return c(e,"InstanceProfiles","member").map((r)=>({InstanceProfileName:s(r,"InstanceProfileName")||"",InstanceProfileId:s(r,"InstanceProfileId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),CreateDate:s(r,"CreateDate")}))}async getAccountPasswordPolicy(){let e=await this.request("GetAccountPasswordPolicy");return{MinimumPasswordLength:s(e,"MinimumPasswordLength")?Number.parseInt(s(e,"MinimumPasswordLength"),10):void 0,RequireSymbols:s(e,"RequireSymbols")==="true",RequireNumbers:s(e,"RequireNumbers")==="true",RequireUppercaseCharacters:s(e,"RequireUppercaseCharacters")==="true",RequireLowercaseCharacters:s(e,"RequireLowercaseCharacters")==="true",AllowUsersToChangePassword:s(e,"AllowUsersToChangePassword")==="true",ExpirePasswords:s(e,"ExpirePasswords")==="true",MaxPasswordAge:s(e,"MaxPasswordAge")?Number.parseInt(s(e,"MaxPasswordAge"),10):void 0,PasswordReusePrevention:s(e,"PasswordReusePrevention")?Number.parseInt(s(e,"PasswordReusePrevention"),10):void 0,HardExpiry:s(e,"HardExpiry")==="true"}}async updateAccountPasswordPolicy(e){await this.request("UpdateAccountPasswordPolicy",e)}async deleteAccountPasswordPolicy(){await this.request("DeleteAccountPasswordPolicy")}async getAccountSummary(){let e=await this.request("GetAccountSummary"),t={},r=c(e,"SummaryMap","entry");for(let a of r){let i=s(a,"key"),n=s(a,"value");if(i&&n)t[i]=Number.parseInt(n,10)}return t}async listAccountAliases(){let e=await this.request("ListAccountAliases"),t=c(e,"AccountAliases","member"),r=s(e,"IsTruncated")==="true",a=s(e,"Marker");return{AccountAliases:t,IsTruncated:r,Marker:a}}async createAccountAlias(e){await this.request("CreateAccountAlias",e)}async deleteAccountAlias(e){await this.request("DeleteAccountAlias",e)}async simulatePrincipalPolicy(e){let t=await this.request("SimulatePrincipalPolicy",e);return this.parseSimulationResults(t)}parseSimulationResults(e){let r=c(e,"EvaluationResults","member").map((n)=>{let u=c(n,"MatchedStatements","member").map((l)=>({SourcePolicyId:s(l,"SourcePolicyId"),SourcePolicyType:s(l,"SourcePolicyType")}));return{EvalActionName:s(n,"EvalActionName")||"",EvalResourceName:s(n,"EvalResourceName"),EvalDecision:s(n,"EvalDecision")||"",MatchedStatements:u.length>0?u:void 0}}),a=s(e,"IsTruncated")==="true",i=s(e,"Marker");return{EvaluationResults:r,IsTruncated:a,Marker:i}}}class we{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new p(t)}async createEmailIdentity(e){return await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/identities",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async getEmailIdentity(e){let t=await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/identities/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}});return{IdentityType:t.IdentityType,IdentityName:e,SendingEnabled:t.VerifiedForSendingStatus,VerificationStatus:t.VerificationStatus,DkimAttributes:t.DkimAttributes,MailFromAttributes:t.MailFromAttributes}}async putEmailIdentityMailFromAttributes(e,t){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(e)}/mail-from`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async listEmailIdentities(e){let t="/v2/email/identities",r=[];if(e?.PageSize)r.push(`PageSize=${e.PageSize}`);if(e?.NextToken)r.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(r.length>0)t+=`?${r.join("&")}`;let a=await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}});return{EmailIdentities:a.EmailIdentities,NextToken:a.NextToken}}async deleteEmailIdentity(e){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/identities/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async putEmailIdentityDkimAttributes(e){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(e.EmailIdentity)}/dkim`,headers:{"Content-Type":"application/json"},body:JSON.stringify({SigningEnabled:e.SigningEnabled})})}async sendEmail(e){return{MessageId:(await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/outbound-emails",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).MessageId}}async sendBulkEmail(e){return{BulkEmailEntryResults:(await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/outbound-bulk-emails",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).BulkEmailEntryResults}}async createEmailTemplate(e){await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/templates",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async getEmailTemplate(e){return await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/templates/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async deleteEmailTemplate(e){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/templates/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async listEmailTemplates(e){let t="/v2/email/templates",r=[];if(e?.PageSize)r.push(`PageSize=${e.PageSize}`);if(e?.NextToken)r.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(r.length>0)t+=`?${r.join("&")}`;return await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}})}async getSendStatistics(){let e=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendStatistics&Version=2010-12-01"}),t=L(e,"GetSendStatistics")?.SendDataPoints?.member;return{SendDataPoints:t==null?[]:Array.isArray(t)?t:[t]}}async getSendQuota(){let e=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendQuota&Version=2010-12-01"}),t=L(e,"GetSendQuota"),r=(a)=>a==null||a===""?void 0:Number(a);return{Max24HourSend:r(t?.Max24HourSend),MaxSendRate:r(t?.MaxSendRate),SentLast24Hours:r(t?.SentLast24Hours)}}async verifyDomain(e){let t=await this.createEmailIdentity({EmailIdentity:e});return{dkimTokens:t.DkimAttributes?.Tokens,verificationStatus:t.DkimAttributes?.Status}}async sendSimpleEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],r=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0,a={};if(e.text)a.Text={Data:e.text};if(e.html)a.Html={Data:e.html};return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Simple:{Subject:{Data:e.subject},Body:a}},ReplyToAddresses:r})}async sendTemplatedEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],r=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0;return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Template:{TemplateName:e.templateName,TemplateData:JSON.stringify(e.templateData)}},ReplyToAddresses:r})}async getDkimRecords(e){let t=await this.getEmailIdentity(e);if(!t.DkimAttributes?.Tokens)return[];return t.DkimAttributes.Tokens.map((r)=>({name:`${r}._domainkey.${e}`,type:"CNAME",value:`${r}.dkim.amazonses.com`}))}async isDomainVerified(e){try{let t=await this.getEmailIdentity(e);return t.VerificationStatus==="SUCCESS"&&t.SendingEnabled===!0}catch{return!1}}async waitForDomainVerification(e,t=60,r=30000){for(let a=0;a<t;a++){if(await this.isDomainVerified(e))return!0;await new Promise((n)=>setTimeout(n,r))}return!1}buildFormBody(e){return Object.entries(e).filter(([,r])=>r!==void 0).map(([r,a])=>`${encodeURIComponent(r)}=${encodeURIComponent(a)}`).join("&")}async createReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"CreateReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async deleteReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async setActiveReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"SetActiveReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async listReceiptRuleSets(e){let t={Action:"ListReceiptRuleSets",Version:"2010-12-01"};if(e)t.NextToken=e;let r=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)}),a=r?.ListReceiptRuleSetsResponse?.ListReceiptRuleSetsResult||r?.ListReceiptRuleSetsResult,i=a?.RuleSets?.member;return{RuleSets:Array.isArray(i)?i:i?[i]:[],NextToken:a?.NextToken}}async describeReceiptRuleSet(e){let t=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DescribeReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})}),r=t?.DescribeReceiptRuleSetResponse?.DescribeReceiptRuleSetResult||t?.DescribeReceiptRuleSetResult,a=r?.Rules?.member;return{Metadata:r?.Metadata,Rules:Array.isArray(a)?a:a?[a]:[]}}async createReceiptRule(e){let t={Action:"CreateReceiptRule",Version:"2010-12-01",RuleSetName:e.RuleSetName,"Rule.Name":e.Rule.Name,"Rule.Enabled":e.Rule.Enabled!==!1?"true":"false"};if(e.Rule.TlsPolicy)t["Rule.TlsPolicy"]=e.Rule.TlsPolicy;if(e.Rule.ScanEnabled!==void 0)t["Rule.ScanEnabled"]=e.Rule.ScanEnabled?"true":"false";if(e.After)t.After=e.After;if(e.Rule.Recipients)e.Rule.Recipients.forEach((r,a)=>{t[`Rule.Recipients.member.${a+1}`]=r});e.Rule.Actions.forEach((r,a)=>{let i=a+1;if(r.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=r.S3Action.BucketName,r.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=r.S3Action.ObjectKeyPrefix;if(r.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=r.S3Action.KmsKeyArn}if(r.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=r.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=r.LambdaAction.InvocationType||"Event";if(r.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=r.SNSAction.TopicArn,r.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=r.SNSAction.Encoding}if(r.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=r.StopAction.Scope,r.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=r.StopAction.TopicArn}}),await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)})}async deleteReceiptRule(e,t){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteReceiptRule",Version:"2010-12-01",RuleSetName:e,RuleName:t})})}async receiptRuleSetExists(e){try{return await this.describeReceiptRuleSet(e),!0}catch(t){if(t.code==="RuleSetDoesNotExist"||t.statusCode===400)return!1;throw t}}async getActiveReceiptRuleSet(){let e=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DescribeActiveReceiptRuleSet",Version:"2010-12-01"})}),t=e?.DescribeActiveReceiptRuleSetResponse?.DescribeActiveReceiptRuleSetResult||e?.DescribeActiveReceiptRuleSetResult;if(!t?.Metadata)return null;let r=t?.Rules?.member;return{Metadata:t?.Metadata,Rules:Array.isArray(r)?r:r?[r]:[]}}async updateReceiptRule(e){let t={Action:"UpdateReceiptRule",Version:"2010-12-01",RuleSetName:e.RuleSetName,"Rule.Name":e.Rule.Name};if(e.Rule.Enabled!==void 0)t["Rule.Enabled"]=e.Rule.Enabled?"true":"false";if(e.Rule.TlsPolicy)t["Rule.TlsPolicy"]=e.Rule.TlsPolicy;if(e.Rule.ScanEnabled!==void 0)t["Rule.ScanEnabled"]=e.Rule.ScanEnabled?"true":"false";if(e.Rule.Recipients)e.Rule.Recipients.forEach((r,a)=>{t[`Rule.Recipients.member.${a+1}`]=r});e.Rule.Actions.forEach((r,a)=>{let i=a+1;if(r.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=r.S3Action.BucketName,r.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=r.S3Action.ObjectKeyPrefix;if(r.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=r.S3Action.KmsKeyArn}if(r.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=r.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=r.LambdaAction.InvocationType||"Event";if(r.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=r.SNSAction.TopicArn,r.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=r.SNSAction.Encoding}if(r.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=r.StopAction.Scope,r.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=r.StopAction.TopicArn}}),await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)})}async sendRawEmail(e){let t=Buffer.from(e.rawMessage).toString("base64"),r={Action:"SendRawEmail",Version:"2010-12-01",Source:e.source,"RawMessage.Data":t};e.destinations.forEach((n,o)=>{r[`Destinations.member.${o+1}`]=n});let a=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(r)});return{MessageId:(a?.SendRawEmailResponse?.SendRawEmailResult||a?.SendRawEmailResult)?.MessageId}}async getSuppressedDestination(e){try{return(await this.client.request({service:"ses",region:this.region,method:"GET",path:`/v2/email/suppression/addresses/${encodeURIComponent(e)}`}))?.SuppressedDestination||null}catch(t){if(t.message?.includes("404")||t.message?.includes("NotFoundException"))return null;throw t}}async deleteSuppressedDestination(e){await this.client.request({service:"ses",region:this.region,method:"DELETE",path:`/v2/email/suppression/addresses/${encodeURIComponent(e)}`})}}class tl{ses;s3;iam;route53;region;domain;defaultFrom;constructor(e={}){this.region=e.region||"us-east-1",this.domain=e.domain,this.defaultFrom=e.defaultFrom,this.ses=new we(this.region),this.s3=new g(this.region),this.iam=new te(this.region),this.route53=new B(this.region)}async send(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required. Set defaultFrom in constructor or provide from in options.");let r=e.fromName?`${e.fromName} <${t}>`:t,a=Array.isArray(e.to)?e.to:[e.to];if(!e.attachments||e.attachments.length===0)return{messageId:(await this.ses.sendSimpleEmail({from:r,to:a,subject:e.subject,text:e.text,html:e.html,replyTo:e.replyTo})).MessageId||""};let i=this.buildRawEmail(e,r,a);return{messageId:(await this.ses.sendEmail({FromEmailAddress:r,Destination:{ToAddresses:a,CcAddresses:e.cc?Array.isArray(e.cc)?e.cc:[e.cc]:void 0,BccAddresses:e.bcc?Array.isArray(e.bcc)?e.bcc:[e.bcc]:void 0},Content:{Raw:{Data:Buffer.from(i).toString("base64")}}})).MessageId||""}}async sendTemplate(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required");let r=e.fromName?`${e.fromName} <${t}>`:t;return{messageId:(await this.ses.sendTemplatedEmail({from:r,to:e.to,templateName:e.templateName,templateData:e.templateData,replyTo:e.replyTo})).MessageId||""}}async sendBulk(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required");let r=e.recipients.map((i)=>({Destination:{ToAddresses:Array.isArray(i.to)?i.to:[i.to]},ReplacementEmailContent:i.templateData?{ReplacementTemplate:{ReplacementTemplateData:JSON.stringify(i.templateData)}}:void 0}));return{results:(await this.ses.sendBulkEmail({FromEmailAddress:t,BulkEmailEntries:r,DefaultContent:{Template:{TemplateName:e.templateName,TemplateData:JSON.stringify(e.defaultTemplateData)}}})).BulkEmailEntryResults?.map((i)=>({status:i.Status||"UNKNOWN",messageId:i.MessageId,error:i.Error}))||[]}}async setupDomain(e){let t;try{t=await this.ses.getEmailIdentity(e)}catch{let a=await this.ses.createEmailIdentity({EmailIdentity:e});t={VerificationStatus:a.DkimAttributes?.Status,DkimAttributes:a.DkimAttributes,SendingEnabled:a.VerifiedForSendingStatus}}try{await this.ses.putEmailIdentityDkimAttributes({EmailIdentity:e,SigningEnabled:!0})}catch{}try{await this.ses.putEmailIdentityMailFromAttributes(e,{MailFromDomain:`mail.${e}`,BehaviorOnMxFailure:"USE_DEFAULT_VALUE"})}catch{}let r=await this.ses.getDkimRecords(e);return{domainVerified:t.SendingEnabled===!0,dkimStatus:t.DkimAttributes?.Status||"UNKNOWN",dkimTokens:t.DkimAttributes?.Tokens,mailFromStatus:t.MailFromAttributes?.MailFromDomainStatus}}async getDnsRecords(e){let t=[],r=await this.ses.getDkimRecords(e);for(let a of r)t.push({type:a.type,name:a.name,value:a.value,ttl:1800});return t.push({type:"MX",name:e,value:`inbound-smtp.${this.region}.amazonaws.com`,priority:10,ttl:3600}),t.push({type:"MX",name:`mail.${e}`,value:`feedback-smtp.${this.region}.amazonses.com`,priority:10,ttl:3600}),t.push({type:"TXT",name:`mail.${e}`,value:"v=spf1 include:amazonses.com ~all",ttl:3600}),t.push({type:"TXT",name:`_dmarc.${e}`,value:`v=DMARC1;p=quarantine;pct=25;rua=mailto:dmarcreports@${e}`,ttl:3600}),t}async isDomainReady(e){try{let t=await this.ses.getEmailIdentity(e);return t.SendingEnabled===!0&&t.DkimAttributes?.Status==="SUCCESS"}catch{return!1}}async setupReceiving(e){let t={Version:"2012-10-17",Statement:[{Sid:"AllowSESPuts",Effect:"Allow",Principal:{Service:"ses.amazonaws.com"},Action:"s3:PutObject",Resource:`arn:aws:s3:::${e.bucketName}/*`,Condition:{StringEquals:{"AWS:SourceAccount":e.accountId}}}]};await this.s3.putBucketPolicy(e.bucketName,t);try{await this.ses.createReceiptRuleSet(e.ruleSetName)}catch(a){if(!a.message?.includes("already exists")&&a.code!=="AlreadyExists")throw a}let r=[{S3Action:{BucketName:e.bucketName,ObjectKeyPrefix:e.prefix||"inbox/"}}];if(e.lambdaArn)r.push({LambdaAction:{FunctionArn:e.lambdaArn,InvocationType:"Event"}});try{await this.ses.createReceiptRule({RuleSetName:e.ruleSetName,Rule:{Name:e.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:e.recipients||[e.domain],ScanEnabled:e.scanEnabled!==!1,Actions:r}})}catch(a){if(a.message?.includes("already exists"))await this.ses.deleteReceiptRule(e.ruleSetName,e.ruleName),await this.ses.createReceiptRule({RuleSetName:e.ruleSetName,Rule:{Name:e.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:e.recipients||[e.domain],ScanEnabled:e.scanEnabled!==!1,Actions:r}});else throw a}await this.ses.setActiveReceiptRuleSet(e.ruleSetName)}async getIncomingEmails(e){return(await this.s3.list({bucket:e.bucket,prefix:e.prefix||"incoming/",maxKeys:e.maxResults||100})).map((r)=>({key:r.Key||"",lastModified:r.LastModified||"",size:r.Size||0}))}async readEmail(e){return await this.s3.getObject(e.bucket,e.key)}async createSmtpCredentials(e){let t=`ses-smtp-${e.username.replace(/[^a-zA-Z0-9]/g,"-")}`,{AWSClient:r}=await import("./chunk-6bnxvtvy.js"),a=new r,i=(m,y)=>{let P={Action:m,Version:"2010-05-08",...y};return Object.entries(P).map(([A,h])=>`${encodeURIComponent(A)}=${encodeURIComponent(h)}`).join("&")};try{await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateUser",{UserName:t})})}catch(m){if(!m.message?.includes("EntityAlreadyExists"))throw m}let n={Version:"2012-10-17",Statement:[{Effect:"Allow",Action:"ses:SendRawEmail",Resource:"*",Condition:{StringLike:{"ses:FromAddress":`*@${e.domain}`}}}]},o=`ses-smtp-policy-${e.domain.replace(/\./g,"-")}`;try{await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("PutUserPolicy",{UserName:t,PolicyName:o,PolicyDocument:JSON.stringify(n)})})}catch{}let l=(await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateAccessKey",{UserName:t})}))?.CreateAccessKeyResult?.AccessKey;if(!l?.AccessKeyId||!l?.SecretAccessKey)throw Error("Failed to create access key");let d=this.deriveSmtpPassword(l.SecretAccessKey);return{username:l.AccessKeyId,password:d,server:`email-smtp.${this.region}.amazonaws.com`,port:587}}deriveSmtpPassword(e){let t=Gr("node:crypto"),r="SendRawEmail",a=Buffer.from([4]),i=t.createHmac("sha256",`AWS4${e}`).update("11111111").digest();return i=t.createHmac("sha256",i).update(this.region).digest(),i=t.createHmac("sha256",i).update("ses").digest(),i=t.createHmac("sha256",i).update("aws4_request").digest(),i=t.createHmac("sha256",i).update("SendRawEmail").digest(),Buffer.concat([a,i]).toString("base64")}async createTemplate(e){await this.ses.createEmailTemplate({TemplateName:e.name,TemplateContent:{Subject:e.subject,Text:e.text,Html:e.html}})}async getTemplate(e){try{let t=await this.ses.getEmailTemplate(e);return{name:t.TemplateName||e,subject:t.TemplateContent?.Subject,text:t.TemplateContent?.Text,html:t.TemplateContent?.Html}}catch{return null}}async deleteTemplate(e){await this.ses.deleteEmailTemplate(e)}async listTemplates(){return(await this.ses.listEmailTemplates()).TemplatesMetadata?.map((t)=>({name:t.TemplateName||"",createdAt:t.CreatedTimestamp}))||[]}async deploy(e){let t=`${e.appName}-${e.environment}-email-rules`,r=`${e.appName}-inbound-email`,a=e.storage?.bucketName||`${e.appName}-${e.environment}-email`,i=await this.setupDomain(e.domain);if(!(await this.s3.listBuckets()).Buckets?.some((l)=>l.Name===a))await this.s3.createBucket(a);await this.setupReceiving({domain:e.domain,ruleSetName:t,ruleName:r,bucketName:a,prefix:e.storage?.prefix||"inbox/",accountId:e.accountId,recipients:e.catchAll?[e.domain]:e.mailboxes,scanEnabled:!0});let u=await this.getDnsRecords(e.domain);return{success:!0,domainVerified:i.domainVerified,dkimStatus:i.dkimStatus,receiptRuleSet:t,storageBucket:a,dnsRecords:u}}async undeploy(e){let t=`${e.appName}-${e.environment}-email-rules`,r=`${e.appName}-inbound-email`,a=`${e.appName}-${e.environment}-email`;try{await this.ses.deleteReceiptRule(t,r)}catch{}try{await this.ses.deleteReceiptRuleSet(t)}catch{}if(e.deleteBucket)try{await this.s3.emptyAndDeleteBucket(a)}catch{}}async getSendingStats(){let e=await this.ses.getSendQuota();return{sentLast24Hours:e.SentLast24Hours||0,maxSendRate:e.MaxSendRate||0,max24HourSend:e.Max24HourSend||0}}buildRawEmail(e,t,r){let a=`----=_Part_${Date.now()}_${Math.random().toString(36).substring(2)}`,i="";if(i+=`From: ${t}\r
|
|
2
2
|
`,i+=`To: ${r.join(", ")}\r
|
|
3
3
|
`,e.cc){let n=Array.isArray(e.cc)?e.cc:[e.cc];i+=`Cc: ${n.join(", ")}\r
|
|
4
4
|
`}if(i+=`Subject: ${e.subject}\r
|
|
@@ -30,5 +30,5 @@ import{Kt,p}from"./chunk-b0r8a5h5.js";import{g}from"./chunk-17ewx21n.js";import{
|
|
|
30
30
|
`,i+=`\r
|
|
31
31
|
`,i+=`${n.content}\r
|
|
32
32
|
`;return i+=`--${a}--\r
|
|
33
|
-
`,i}}var
|
|
34
|
-
export{te,we,
|
|
33
|
+
`,i}}var vm=new tl;
|
|
34
|
+
export{te,we,tl,vm};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function L(n,r){return(n?.[`${r}Response`]??n)?.[`${r}Result`]}function x(n){if(n===void 0||n===null||n==="")return[];return Array.isArray(n)?n:[n]}function
|
|
2
|
-
export{L,x,
|
|
1
|
+
function L(n,r){return(n?.[`${r}Response`]??n)?.[`${r}Result`]}function x(n){if(n===void 0||n===null||n==="")return[];return Array.isArray(n)?n:[n]}function aa(n){return n===!0||n==="true"}
|
|
2
|
+
export{L,x,aa};
|