@stacksjs/ts-cloud 0.16.16 → 0.16.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/aws/index.js +1 -1
- package/dist/bin/chunk-0h6cggyt.js +1 -0
- package/dist/bin/{chunk-tfasfg4a.js → chunk-0trtkv9g.js} +4 -4
- package/dist/bin/{chunk-2v91xnqx.js → chunk-148x1zq8.js} +2 -2
- package/dist/bin/{chunk-xxf1vhfr.js → chunk-1j8b1d58.js} +1 -1
- package/dist/bin/chunk-2g2zrtjs.js +2 -0
- package/dist/bin/{chunk-3qfd0vnc.js → chunk-2mv692y4.js} +5 -5
- package/dist/bin/{chunk-grs2cwm7.js → chunk-3n733cgx.js} +2 -2
- package/dist/bin/chunk-4cs098d1.js +1 -0
- package/dist/bin/chunk-52fhq35h.js +1 -0
- package/dist/bin/{chunk-j0wfftk1.js → chunk-5a7sxtwn.js} +1 -1
- package/dist/bin/{chunk-yk4p2k8w.js → chunk-6kx50dyc.js} +2 -2
- package/dist/bin/chunk-6se7ygxa.js +1 -0
- package/dist/bin/chunk-72g1hr4z.js +1 -0
- package/dist/bin/chunk-75ak501k.js +3 -0
- package/dist/{chunk-fdn4wnd8.js → bin/chunk-8jbkphmg.js} +7 -7
- package/dist/bin/{chunk-edfh9ts2.js → chunk-90102shh.js} +1 -1
- package/dist/bin/{chunk-pd8tk3z5.js → chunk-9vmtm7nq.js} +1 -1
- package/dist/bin/chunk-a7kmjq4y.js +1 -0
- package/dist/bin/{chunk-whww424p.js → chunk-acqj5mfq.js} +108 -108
- package/dist/bin/chunk-c7vxdwth.js +1 -0
- package/dist/bin/chunk-ckk70zc9.js +1 -0
- package/dist/bin/{chunk-90c3rkd8.js → chunk-cnbvm43k.js} +5 -5
- package/dist/bin/chunk-d9yzg97w.js +1 -0
- package/dist/bin/{chunk-zacbzz1w.js → chunk-djjj62c0.js} +2 -2
- package/dist/bin/chunk-dk9f6h0m.js +1 -0
- package/dist/bin/{chunk-1baj8p0r.js → chunk-dmdg23a5.js} +1 -1
- package/dist/bin/{chunk-y4c26gaf.js → chunk-dyh0vndw.js} +1 -1
- package/dist/bin/chunk-e0c3agf2.js +1 -0
- package/dist/bin/{chunk-khta83xb.js → chunk-e24bscb0.js} +15 -15
- package/dist/bin/{chunk-bhay1f8a.js → chunk-egn33pr9.js} +1 -1
- package/dist/bin/{chunk-3x4p2s2r.js → chunk-eyvxsaaz.js} +3 -3
- package/dist/bin/{chunk-b3yp7bak.js → chunk-ezhbcpw1.js} +3 -3
- package/dist/bin/{chunk-2943bszc.js → chunk-gfnw9nhq.js} +30 -30
- package/dist/bin/{chunk-gv9deppc.js → chunk-h1rb8qvt.js} +2 -2
- package/dist/bin/chunk-hagakkgm.js +1 -0
- package/dist/bin/chunk-hr3vbg6y.js +1 -0
- package/dist/bin/chunk-hyb5v8wr.js +1 -0
- package/dist/bin/{chunk-fjz07v7g.js → chunk-k7wh1wr5.js} +1 -1
- package/dist/bin/{chunk-cs6a98r1.js → chunk-mx9ppkmn.js} +4 -4
- package/dist/bin/{chunk-zzmk290g.js → chunk-mxvekmdx.js} +126 -126
- package/dist/bin/chunk-nagvc7e4.js +1 -0
- package/dist/bin/{chunk-0znhykt9.js → chunk-ngyqqy6d.js} +5 -5
- package/dist/bin/chunk-nqb1faqj.js +1 -0
- package/dist/bin/chunk-nrrprf04.js +724 -0
- package/dist/bin/chunk-p831sptd.js +1 -0
- package/dist/bin/chunk-padk76ac.js +1 -0
- package/dist/bin/chunk-qxwkg8yg.js +2 -0
- package/dist/bin/chunk-qxx1a51w.js +1 -0
- package/dist/bin/{chunk-80295akq.js → chunk-rbtt23vx.js} +3 -3
- package/dist/bin/chunk-swfmx4f8.js +1 -0
- package/dist/bin/{chunk-dczw0nxw.js → chunk-t10e32an.js} +7 -7
- package/dist/bin/{chunk-vx9qk1g1.js → chunk-vjkyj3xy.js} +1 -1
- package/dist/bin/chunk-w8k1gyzr.js +1 -0
- package/dist/bin/chunk-wagzxm7z.js +1 -0
- package/dist/bin/{chunk-n02421y9.js → chunk-x63yz8xg.js} +1 -1
- package/dist/bin/chunk-xdxk6baf.js +1 -0
- package/dist/bin/{chunk-tvv6vdx6.js → chunk-ys5n5c84.js} +4 -4
- package/dist/bin/{chunk-tc24txss.js → chunk-z1dtdw3j.js} +5 -5
- package/dist/bin/chunk-zww0xfdp.js +1 -0
- package/dist/bin/cli.js +281 -281
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/{chunk-wdrqt329.js → chunk-2p71e3x7.js} +162 -162
- package/dist/{chunk-yxn6tpbg.js → chunk-31tvc877.js} +1 -1
- package/dist/{chunk-gstz8w2d.js → chunk-3m9ghthh.js} +2 -2
- package/dist/{chunk-4xta1s4z.js → chunk-5far81q7.js} +2 -2
- package/dist/{chunk-a6aw2jtz.js → chunk-60nr1ehk.js} +14 -14
- package/dist/chunk-6kcmbymp.js +1 -0
- package/dist/{chunk-0bbrbzf9.js → chunk-7xnwa0s8.js} +4 -4
- package/dist/{chunk-whwg2nzb.js → chunk-9syc8s7r.js} +5 -5
- package/dist/{chunk-emx1j2yt.js → chunk-9wmer0zx.js} +1 -1
- package/dist/{chunk-4twnkjyq.js → chunk-bxrzsth8.js} +2 -2
- package/dist/{chunk-a21phhyj.js → chunk-c3f89ryr.js} +7 -7
- package/dist/chunk-dak9hfrd.js +1 -0
- package/dist/{chunk-jgv0x24e.js → chunk-e52me1c6.js} +1 -1
- package/dist/{chunk-v9t92ak2.js → chunk-e8e1h2h9.js} +2 -2
- package/dist/{bin/chunk-dp2fsnpe.js → chunk-g6g33pt9.js} +7 -7
- package/dist/chunk-hjgjbkhk.js +1 -0
- package/dist/{chunk-6eq5xfcx.js → chunk-k53agv2m.js} +1 -1
- package/dist/{chunk-rmn71xjb.js → chunk-kczzc599.js} +25 -25
- package/dist/{chunk-g0yyw5k8.js → chunk-ptq9v346.js} +1 -1
- package/dist/{chunk-fz70vxrk.js → chunk-qcaqc5b8.js} +2 -2
- package/dist/chunk-rtn4gj6y.js +1 -0
- package/dist/chunk-s2ve9zxn.js +584 -0
- package/dist/{chunk-pekptc1b.js → chunk-srrscggm.js} +5 -5
- package/dist/{chunk-jncbm332.js → chunk-v2p7c7s4.js} +325 -325
- package/dist/{chunk-gn42mekr.js → chunk-vs0qrm09.js} +1 -1
- package/dist/{chunk-rgw06xbk.js → chunk-w9jhyy09.js} +4 -4
- package/dist/{chunk-z87dekhm.js → chunk-yd40pg8g.js} +21 -21
- package/dist/{chunk-sm5rn3db.js → chunk-z3wynefj.js} +19 -19
- package/dist/chunk-z4xzd43p.js +1 -0
- package/dist/{chunk-ss4q8kge.js → chunk-zx8ecz8b.js} +4 -4
- package/dist/deploy/index.d.ts +1 -0
- package/dist/deploy/index.js +1 -1
- package/dist/deploy/storage-failover.d.ts +54 -0
- package/dist/dns/index.js +1 -1
- package/dist/drivers/index.d.ts +2 -0
- package/dist/drivers/index.js +1 -1
- package/dist/drivers/shared/cloudfront-origin.d.ts +9 -2
- package/dist/drivers/shared/deploy-script.d.ts +7 -5
- package/dist/drivers/shared/host-cleanup.d.ts +90 -0
- package/dist/generators/infrastructure.d.ts +9 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +49 -49
- package/dist/operations/index.js +1 -1
- package/dist/protection/index.js +1 -1
- package/dist/spend/index.js +1 -1
- package/dist/ui/404.html +1 -1
- package/dist/ui/accept-invitation.html +1 -1
- package/dist/ui/access-denied.html +1 -1
- package/dist/ui/account/automation.html +6 -6
- package/dist/ui/account/security.html +2 -2
- package/dist/ui/applications/compose.html +6 -6
- package/dist/ui/applications/new.html +2 -2
- package/dist/ui/data/backups.html +6 -6
- package/dist/ui/data/services.html +6 -6
- package/dist/ui/data/volumes.html +6 -6
- package/dist/ui/index.html +6 -6
- package/dist/ui/infrastructure/topology.html +6 -6
- package/dist/ui/integrations.html +1 -1
- package/dist/ui/operations/alerts.html +6 -6
- package/dist/ui/operations/configuration.html +5 -5
- package/dist/ui/operations/jobs.html +6 -6
- package/dist/ui/operations/maintenance.html +5 -5
- package/dist/ui/operations/observability.html +5 -5
- package/dist/ui/operations/previews.html +6 -6
- package/dist/ui/operations/queue.html +5 -5
- package/dist/ui/operations/regions.html +5 -5
- 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 +1 -1
- package/dist/ui/server/capacity.html +5 -5
- package/dist/ui/server/database.html +6 -6
- package/dist/ui/server/deployments.html +5 -5
- package/dist/ui/server/diagnostics.html +2 -2
- package/dist/ui/server/firewall.html +6 -6
- package/dist/ui/server/fleet.html +6 -6
- package/dist/ui/server/logs.html +6 -6
- package/dist/ui/server/metrics.html +5 -5
- package/dist/ui/server/security.html +2 -2
- package/dist/ui/server/services.html +2 -2
- package/dist/ui/server/sites.html +6 -6
- package/dist/ui/server/ssh-keys.html +6 -6
- package/dist/ui/server/team.html +6 -6
- package/dist/ui/server/terminal.html +2 -2
- package/dist/ui/serverless/alarms.html +6 -6
- package/dist/ui/serverless/assets.html +2 -2
- package/dist/ui/serverless/cost.html +2 -2
- package/dist/ui/serverless/data.html +6 -6
- package/dist/ui/serverless/deployments.html +2 -2
- package/dist/ui/serverless/firewall.html +2 -2
- package/dist/ui/serverless/functions.html +6 -6
- package/dist/ui/serverless/logs.html +6 -6
- package/dist/ui/serverless/metrics.html +2 -2
- package/dist/ui/serverless/queues.html +6 -6
- package/dist/ui/serverless/secrets.html +6 -6
- package/dist/ui/serverless/traces.html +6 -6
- package/dist/ui/serverless.html +5 -5
- package/package.json +3 -3
- package/dist/bin/chunk-2tn43y0d.js +0 -1
- package/dist/bin/chunk-2w591cvg.js +0 -1
- package/dist/bin/chunk-4v6f496n.js +0 -1
- package/dist/bin/chunk-64cdtvar.js +0 -1
- package/dist/bin/chunk-66egshmp.js +0 -1
- package/dist/bin/chunk-7raskz63.js +0 -1
- package/dist/bin/chunk-9bxyy4th.js +0 -1
- package/dist/bin/chunk-bbt0vyzj.js +0 -1
- package/dist/bin/chunk-cpcae7e2.js +0 -1
- package/dist/bin/chunk-dsc7ef1w.js +0 -1
- package/dist/bin/chunk-f2wn46nw.js +0 -1
- package/dist/bin/chunk-fddwwac7.js +0 -1
- package/dist/bin/chunk-ffcyj2jj.js +0 -1
- package/dist/bin/chunk-gbejgj71.js +0 -1
- package/dist/bin/chunk-j76935z3.js +0 -3
- package/dist/bin/chunk-kjbkwzxd.js +0 -1
- package/dist/bin/chunk-knthwdhz.js +0 -1
- package/dist/bin/chunk-m2kr333s.js +0 -2
- package/dist/bin/chunk-m5wc1ent.js +0 -1
- package/dist/bin/chunk-nm000jpj.js +0 -725
- package/dist/bin/chunk-pjgbnk3q.js +0 -1
- package/dist/bin/chunk-rn0pgnt4.js +0 -1
- package/dist/bin/chunk-v93xyx1p.js +0 -1
- package/dist/bin/chunk-vx9mmpaz.js +0 -1
- package/dist/bin/chunk-xtzy90zh.js +0 -1
- package/dist/bin/chunk-z6mnhd0j.js +0 -1
- package/dist/chunk-051jwkd2.js +0 -1
- package/dist/chunk-1gne7rkf.js +0 -1
- package/dist/chunk-38c310s1.js +0 -1
- package/dist/chunk-acpxtkfy.js +0 -585
- package/dist/chunk-dk3t3hgq.js +0 -1
- package/dist/chunk-qc2v4h2q.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{br,n,l,Wh}from"./chunk-zx8ecz8b.js";export{n as AWSClient,l as buildQueryParams,Wh as detectCredentialSource,br as resolveS3Endpoint};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{mo,qr,$d,Pi,So,Co}from"./chunk-v2p7c7s4.js";import{_e}from"./chunk-5far81q7.js";import{execFileSync as C}from"node:child_process";import{mkdirSync as S,mkdtempSync as U,rmSync as L,writeFileSync as d}from"node:fs";import{tmpdir as O}from"node:os";import{dirname as j,join as s}from"node:path";var r={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m"};function I(t,e){return`${r[e]}${t}${r.reset}`}function pn(t){console.log(`${r.green}✓${r.reset} ${t}`)}function hu(t){console.error(`${r.red}✗${r.reset} ${t}`)}function ns(t){console.warn(`${r.yellow}⚠${r.reset} ${t}`)}function P(t){console.log(`${r.blue}ℹ${r.reset} ${t}`)}function v(t){console.log(`${r.cyan}→${r.reset} ${t}`)}function is(t){console.log(`
|
|
2
2
|
${r.bright}${r.cyan}${t}${r.reset}
|
|
3
|
-
`)}var F=!!(process.env.CI||process.env.GITHUB_ACTIONS||process.env.BUILDKITE||process.env.CIRCLECI||process.env.GITLAB_CI);function
|
|
4
|
-
`),i=Math.max(...n.map((l)=>l.length)),a="─".repeat(i+2);console.log(I(`┌${a}┐`,e)),n.forEach((l)=>{console.log(I(`│ ${l.padEnd(i)} │`,e))}),console.log(I(`└${a}┘`,e))}function A(t,e){for(let n of e){let i=s(t,n.name);S(j(i),{recursive:!0}),d(i,n.data,n.mode?{mode:n.mode}:void 0)}}async function
|
|
5
|
-
export{
|
|
3
|
+
`)}var F=!!(process.env.CI||process.env.GITHUB_ACTIONS||process.env.BUILDKITE||process.env.CIRCLECI||process.env.GITLAB_CI);function fu(t,e="cyan"){let n=t.split(`
|
|
4
|
+
`),i=Math.max(...n.map((l)=>l.length)),a="─".repeat(i+2);console.log(I(`┌${a}┐`,e)),n.forEach((l)=>{console.log(I(`│ ${l.padEnd(i)} │`,e))}),console.log(I(`└${a}┘`,e))}function A(t,e){for(let n of e){let i=s(t,n.name);S(j(i),{recursive:!0}),d(i,n.data,n.mode?{mode:n.mode}:void 0)}}async function xa(t){let{app:e,projectRoot:n,region:i,repository:a}=t,l=e.architecture??"x86_64",R=l==="arm64"?"linux/arm64":"linux/amd64",E=e.kind==="php",c=t.onStep??(()=>{}),p=U(s(O(),"tscloud-img-"));try{let f=s(p,"app");S(f,{recursive:!0});let y,w;if(E){So({projectRoot:n,app:e,skipBuild:t.skipBuild,onStep:c}),c("staging application tree");let o=Co(n);A(f,o),A(s(p,"runtime"),Pi().map((g)=>({name:g.path,data:g.contents,mode:g.mode})));let b=e.handlers?.http??"public/index.php";y={http:b,queue:e.handlers?.queue??b,cli:e.handlers?.cli??b},w=mo(o.map((g)=>`${g.name}:${g.data.length}`).join("|"))}else{c("bundling application");let o=await qr({projectRoot:n,app:e,skipBuild:t.skipBuild,onStep:c});d(s(f,"index.mjs"),o.bundle),y=o.handlers,w=o.sha256}let k=w.slice(0,16);d(s(p,"Dockerfile"),$d({kind:e.kind??"node",phpVersion:e.phpVersion,architecture:l}));let x=new _e(i),u;try{u=(await x.describeRepositories({repositoryNames:[a]})).repositories?.[0]?.repositoryUri??""}catch{u=""}if(!u)c(`creating ECR repository ${a}`),u=(await x.createRepository({repositoryName:a,imageScanningConfiguration:{scanOnPush:!0}})).repository?.repositoryUri??"";if(!u)throw Error(`could not resolve ECR repository URI for ${a}`);let m=`${u}:${k}`;c("docker build"),C("docker",["build","--platform",R,"--provenance=false","--sbom=false","-t",m,p],{stdio:"inherit"}),c("ecr auth + push");let h=(await x.getAuthorizationToken()).authorizationData?.[0];if(!h?.authorizationToken||!h.proxyEndpoint)throw Error("failed to get an ECR authorization token");let T=h.proxyEndpoint.replace(/^https?:\/\//,""),B=s(p,".docker");return S(B,{recursive:!0}),d(s(B,"config.json"),JSON.stringify({auths:{[T]:{auth:h.authorizationToken}}})),C("docker",["push",m],{stdio:"inherit",env:{...process.env,DOCKER_CONFIG:B}}),P(`Image: ${m}`),{imageUri:m,tag:k,handlers:y}}finally{L(p,{recursive:!0,force:!0})}}
|
|
5
|
+
export{pn,hu,ns,P,v,is,fu,xa};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{z,oe,T,ae,
|
|
1
|
+
import{z,oe,T,ae,dr}from"./chunk-e8e1h2h9.js";import{o}from"./chunk-yd40pg8g.js";import{A}from"./chunk-31tvc877.js";import{y}from"./chunk-9wmer0zx.js";import{h}from"./chunk-ptq9v346.js";function Ba(t){let{bucketName:s,domain:u,aliases:e,certificateArn:p,defaultRootObject:i="index.html",errorDocument:a="404.html",passthroughUrls:c=!1,singlePageApp:g=!1,dynamicApp:C=!1,computeOriginDomain:w,computeOriginPort:x=3008,computeOriginId:E="app-compute",retainOnStackDelete:M=!1}=t,S=M?{DeletionPolicy:"Retain",UpdateReplacePolicy:"Retain"}:{},N=C&&!!w,j=N?["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"]:["GET","HEAD"],v=N?["GET","HEAD"]:["GET","HEAD"],O={},B={};O.S3Bucket={Type:"AWS::S3::Bucket",...S,Properties:{BucketName:s,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:i,ErrorDocument:a}}},B.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},B.BucketArn={Description:"S3 Bucket ARN",Value:{"Fn::GetAtt":["S3Bucket","Arn"]}},O.CloudFrontOAC={Type:"AWS::CloudFront::OriginAccessControl",...S,Properties:{OriginAccessControlConfig:{Name:`OAC-${s}`,Description:`OAC for ${s}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}};let I;if(c&&N)I="InstallRootRedirectFunction",O[I]={Type:"AWS::CloudFront::Function",Properties:{Name:{"Fn::Sub":"${AWS::StackName}-install-root-redirect"},AutoPublish:!0,FunctionConfig:{Comment:"Redirect curl pantry.dev | bash (GET /) to /install.sh on S3",Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) {
|
|
2
2
|
var request = event.request;
|
|
3
3
|
if (request.uri === '/' || request.uri === '') {
|
|
4
4
|
return {
|
|
@@ -24,7 +24,7 @@ import{z,oe,T,ae,or}from"./chunk-v9t92ak2.js";import{a}from"./chunk-z87dekhm.js"
|
|
|
24
24
|
}
|
|
25
25
|
|
|
26
26
|
return request;
|
|
27
|
-
}`}};let R={Id:`S3-${s}`,DomainName:{"Fn::GetAtt":["S3Bucket","RegionalDomainName"]},S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{"Fn::GetAtt":["CloudFrontOAC","Id"]}},d=N?{Id:E,DomainName:w,CustomOriginConfig:{HTTPPort:x,HTTPSPort:443,OriginProtocolPolicy:"http-only",OriginSSLProtocols:["TLSv1.2"]}}:null,k=N?E:`S3-${s}`,b={Enabled:!0,DefaultRootObject:i,HttpVersion:"http2and3",IPV6Enabled:!0,PriceClass:"PriceClass_100",Origins:d?[d,R]:[R],DefaultCacheBehavior:{TargetOriginId:k,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:j,CachedMethods:v,Compress:!0,...N?{CachePolicyId:"4135ea2d-6df8-44a3-9df3-4b5a84be39ad",OriginRequestPolicyId:"b689b0a8-53d0-40ab-baf2-68738e2966ac",...c&&I?{FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":[I,"FunctionARN"]}}]}:{}}:{CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",...!c&&{FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":["UrlRewriteFunction","FunctionARN"]}}]}}},...N&&c?{CacheBehaviors:[{PathPattern:"/install.sh",TargetOriginId:`S3-${s}`,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6"}]}:{},CustomErrorResponses:g?[{ErrorCode:403,ResponseCode:200,ResponsePagePath:`/${i}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:200,ResponsePagePath:`/${i}`,ErrorCachingMinTTL:300}]:[{ErrorCode:403,ResponseCode:404,ResponsePagePath:`/${
|
|
27
|
+
}`}};let R={Id:`S3-${s}`,DomainName:{"Fn::GetAtt":["S3Bucket","RegionalDomainName"]},S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{"Fn::GetAtt":["CloudFrontOAC","Id"]}},d=N?{Id:E,DomainName:w,CustomOriginConfig:{HTTPPort:x,HTTPSPort:443,OriginProtocolPolicy:"http-only",OriginSSLProtocols:["TLSv1.2"]}}:null,k=N?E:`S3-${s}`,b={Enabled:!0,DefaultRootObject:i,HttpVersion:"http2and3",IPV6Enabled:!0,PriceClass:"PriceClass_100",Origins:d?[d,R]:[R],DefaultCacheBehavior:{TargetOriginId:k,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:j,CachedMethods:v,Compress:!0,...N?{CachePolicyId:"4135ea2d-6df8-44a3-9df3-4b5a84be39ad",OriginRequestPolicyId:"b689b0a8-53d0-40ab-baf2-68738e2966ac",...c&&I?{FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":[I,"FunctionARN"]}}]}:{}}:{CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",...!c&&{FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":["UrlRewriteFunction","FunctionARN"]}}]}}},...N&&c?{CacheBehaviors:[{PathPattern:"/install.sh",TargetOriginId:`S3-${s}`,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6"}]}:{},CustomErrorResponses:g?[{ErrorCode:403,ResponseCode:200,ResponsePagePath:`/${i}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:200,ResponsePagePath:`/${i}`,ErrorCachingMinTTL:300}]:[{ErrorCode:403,ResponseCode:404,ResponsePagePath:`/${a}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:404,ResponsePagePath:`/${a}`,ErrorCachingMinTTL:300}]};if(u&&p)b.Aliases=e&&e.length>0?e:[u],b.ViewerCertificate={AcmCertificateArn:p,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};else b.ViewerCertificate={CloudFrontDefaultCertificate:!0};return O.CloudFrontDistribution={Type:"AWS::CloudFront::Distribution",...S,DependsOn:["S3Bucket","CloudFrontOAC",...c&&N&&I?[I]:[],...!c?["UrlRewriteFunction"]:[]],Properties:{DistributionConfig:b}},B.DistributionId={Description:"CloudFront Distribution ID",Value:{Ref:"CloudFrontDistribution"}},B.DistributionDomain={Description:"CloudFront Distribution Domain",Value:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]}},O.S3BucketPolicy={Type:"AWS::S3::BucketPolicy",...S,DependsOn:["S3Bucket","CloudFrontDistribution"],Properties:{Bucket:{Ref:"S3Bucket"},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":"arn:aws:s3:::${S3Bucket}/*"},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":"arn:aws:cloudfront::${AWS::AccountId}:distribution/${CloudFrontDistribution}"}}}}]}}},B.SiteUrl={Description:"Site URL",Value:u?`https://${u}`:{"Fn::Sub":"https://${CloudFrontDistribution.DomainName}"}},{AWSTemplateFormatVersion:"2010-09-09",Description:`Static site infrastructure for ${u||s} (External DNS)`,Resources:O,Outputs:B}}async function ln(t){let s=t.region||"us-east-1",u="us-east-1",e=t.domain,p=t.bucket||e.replace(/\./g,"-"),i=t.stackName||`${t.siteName}-static-site`,a=new h("us-east-1"),c=new ae("us-east-1"),g=null;if(!t.skipDnsVerification){g=T(t.dnsProvider),console.log(`Verifying DNS provider can manage ${e}...`);let n=await g.listRecords(e);if(!n.success){let r=n.message||"unknown error — check API credentials and domain ownership";return{success:!1,stackName:i,bucket:p,message:`DNS provider '${g.name}' cannot manage domain ${e}: ${r}`}}console.log(`DNS provider '${g.name}' verified for ${e}`)}else console.log(`Skipping DNS verification for ${e}`);let C=t.certificateArn,E=e.split(".").length===2?`www.${e}`:void 0;if(!C){console.log(`Checking for existing SSL certificate for ${e}...`);let n=await c.findCertificateByDomain(e),r=!1;if(n&&n.Status==="ISSUED"){if(E&&n.SubjectAlternativeNames)r=n.SubjectAlternativeNames.includes(E)||n.SubjectAlternativeNames.some((m)=>m===`*.${e}`);else r=!0;if(r)C=n.CertificateArn,console.log(`Found existing certificate with www coverage: ${C}`);else console.log(`Existing certificate doesn't cover ${E}, requesting new one...`)}if(!C){if(!g)return{success:!1,stackName:i,bucket:p,message:`No DNS provider available to validate SSL certificate for ${e}. Provide a certificateArn or enable DNS verification.`};console.log(`Requesting new SSL certificate for ${e}${E?` (including ${E})`:""}...`);let f=await new oe(g,"us-east-1").findOrCreateCertificate({domainName:e,subjectAlternativeNames:E?[E]:void 0,waitForValidation:!0,maxWaitMinutes:10});if(f.status!=="issued")return{success:!1,stackName:i,bucket:p,message:`SSL certificate validation failed. Status: ${f.status}`};C=f.certificateArn,console.log(`Certificate issued: ${C}`)}}let M=!1,S;try{let n=await a.describeStacks({stackName:i});if(n.Stacks.length>0){let r=n.Stacks[0],m=r.StackStatus;if(m==="DELETE_IN_PROGRESS")console.log("Previous stack is still being deleted, waiting..."),await a.waitForStack(i,"stack-delete-complete"),M=!1;else if(m==="DELETE_COMPLETE")M=!1;else M=!0,S=(r.Outputs||[]).find((l)=>l.OutputKey==="BucketName")?.OutputValue}}catch(n){if(n.message?.includes("does not exist")||n.code==="ValidationError")M=!1;else throw n}let N=S||p;if(!M){let n=new o(s),r=new A,m=!1;if(e)try{console.log(`Checking for existing CloudFront distributions with alias ${e}...`);let f=await r.listDistributions();for(let l of f){let D=[];if(l.Aliases?.Items){if(Array.isArray(l.Aliases.Items))D=l.Aliases.Items;else if(typeof l.Aliases.Items==="object"){let F=l.Aliases.Items.CNAME;if(typeof F==="string")D=[F];else if(Array.isArray(F))D=F}}if(D.includes(e)){m=!0,console.log(`Found existing CloudFront distribution ${l.Id} with alias ${e}`),console.log("Reusing existing infrastructure for updates...");let P=(await r.getDistributionConfig(l.Id)).DistributionConfig?.Origins?.Items,V;if(P){let U=[];if(Array.isArray(P))U=P;else if(P.Origin)U=Array.isArray(P.Origin)?P.Origin:[P.Origin];else U=[P];for(let L of U){let W=(L.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(W){V=W[1];break}}}if(V)return console.log(`Using existing S3 bucket: ${V}`),{success:!0,stackName:`existing-${l.Id}`,bucket:V,distributionId:l.Id,distributionDomain:l.DomainName,domain:e,certificateArn:C,message:"Using existing CloudFront distribution",_existingInfrastructure:!0}}}}catch{}if(!m)try{if((await n.headBucket(p)).exists){console.log(`Found orphaned S3 bucket ${p}, cleaning up...`);try{let l=n.emptyBucket(p).then(()=>n.deleteBucket(p)),D=new Promise((F,P)=>setTimeout(()=>P(Error("Bucket cleanup timeout")),30000));await Promise.race([l,D]),console.log(`Deleted orphaned S3 bucket ${p}`)}catch(l){console.log(`Note: Could not clean up S3 bucket: ${l.message}`);let D=Date.now().toString(36);N=`${p}-${D}`,console.log(`Using alternative bucket name: ${N}`)}}}catch{}}let v=Ba({bucketName:N,domain:e,aliases:E?[e,E]:[e],certificateArn:C,defaultRootObject:t.defaultRootObject,errorDocument:t.errorDocument,passthroughUrls:t.passthroughUrls,singlePageApp:t.singlePageApp,dynamicApp:t.dynamicApp,computeOriginDomain:t.computeOriginDomain,computeOriginPort:t.computeOriginPort,computeOriginId:t.computeOriginId}),O=Object.entries(t.tags||{}).map(([n,r])=>({Key:n,Value:r}));if(O.push({Key:"ManagedBy",Value:"ts-cloud"}),O.push({Key:"Application",Value:t.siteName}),g)O.push({Key:"DnsProvider",Value:g.name});let B,I=!1;if(M){I=!0,console.log(`Updating CloudFormation stack: ${i}`);try{B=(await a.updateStack({stackName:i,templateBody:JSON.stringify(v),capabilities:["CAPABILITY_IAM"],tags:O})).StackId,console.log(`Update initiated, stack ID: ${B}`)}catch(n){if(n.message?.includes("No updates are to be performed")){let r=await a.describeStacks({stackName:i});B=r.Stacks[0].StackId;let m=r.Stacks[0]?.Outputs||[],f=(D)=>m.find((F)=>F.OutputKey===D)?.OutputValue,l=f("DistributionDomain");if(l)await H(g,e,l);return{success:!0,stackId:B,stackName:i,bucket:f("BucketName")||N,distributionId:f("DistributionId"),distributionDomain:l,domain:e,certificateArn:C,message:"Static site infrastructure is already up to date"}}else throw n}}else console.log(`Creating CloudFormation stack: ${i}`),console.log(`Bucket name: ${N}`),console.log(`Domain: ${e}`),console.log(`Certificate ARN: ${C}`),B=(await a.createStack({stackName:i,templateBody:JSON.stringify(v),capabilities:["CAPABILITY_IAM"],tags:O,onFailure:"DELETE"})).StackId,console.log(`Create initiated, stack ID: ${B}`);console.log(`Waiting for stack to reach ${I?"stack-update-complete":"stack-create-complete"}...`);try{await a.waitForStack(i,I?"stack-update-complete":"stack-create-complete"),console.log("Stack operation completed successfully!")}catch(n){if(n.message?.includes("must be verified")||n.message?.includes("Access denied for operation")){console.log("CloudFront account verification required - checking for existing infrastructure...");try{let m=new A,f=await m.listDistributions();for(let l of f){let D=[];if(l.Aliases?.Items){if(Array.isArray(l.Aliases.Items))D=l.Aliases.Items;else if(typeof l.Aliases.Items==="object"){let F=l.Aliases.Items.CNAME;if(typeof F==="string")D=[F];else if(Array.isArray(F))D=F}}if(D.includes(e)){console.log(`Found existing CloudFront distribution ${l.Id} with alias ${e}`),console.log("Using existing infrastructure despite account verification requirement...");let P=(await m.getDistributionConfig(l.Id)).DistributionConfig?.Origins?.Items,V;if(P){let U=[];if(Array.isArray(P))U=P;else if(P.Origin)U=Array.isArray(P.Origin)?P.Origin:[P.Origin];else U=[P];for(let L of U){let W=(L.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(W){V=W[1];break}}}if(V){console.log(`Using existing S3 bucket: ${V}`);let U=l.DomainName;if(U)await H(g,e,U);return{success:!0,stackName:`existing-${l.Id}`,bucket:V,distributionId:l.Id,distributionDomain:l.DomainName,domain:e,certificateArn:C,message:"Using existing CloudFront distribution (account verification pending for new distributions)"}}}}}catch{}return console.log(`
|
|
28
28
|
┌─────────────────────────────────────────────────────────────────────────────┐
|
|
29
29
|
│ AWS ACCOUNT VERIFICATION REQUIRED │
|
|
30
30
|
├─────────────────────────────────────────────────────────────────────────────┤
|
|
@@ -42,7 +42,7 @@ import{z,oe,T,ae,or}from"./chunk-v9t92ak2.js";import{a}from"./chunk-z87dekhm.js"
|
|
|
42
42
|
│ │
|
|
43
43
|
│ Verification typically takes 1-2 business days. │
|
|
44
44
|
│ After verification, re-run: bunx bunpress deploy │
|
|
45
|
-
└─────────────────────────────────────────────────────────────────────────────┘`),{success:!1,stackId:B,stackName:i,bucket:N,message:"CloudFront account verification required. Please contact AWS Support."}}return{success:!1,stackId:B,stackName:i,bucket:N,message:`Stack deployment failed: ${
|
|
45
|
+
└─────────────────────────────────────────────────────────────────────────────┘`),{success:!1,stackId:B,stackName:i,bucket:N,message:"CloudFront account verification required. Please contact AWS Support."}}return{success:!1,stackId:B,stackName:i,bucket:N,message:`Stack deployment failed: ${n.message}`}}let d=(await a.describeStacks({stackName:i})).Stacks[0]?.Outputs||[],k=(n)=>d.find((r)=>r.OutputKey===n)?.OutputValue,b=k("DistributionDomain");if(b&&g)console.log(`Creating DNS records via ${g.name}...`),await H(g,e,b);else if(b&&!g)console.log("Skipping DNS record creation (DNS verification was skipped)");return{success:!0,stackId:B,stackName:i,bucket:k("BucketName")||N,distributionId:k("DistributionId"),distributionDomain:b,domain:e,certificateArn:C,message:"Static site infrastructure deployed successfully with external DNS"}}async function H(t,s,u){if(!t){console.log("Skipping DNS record creation (DNS verification was skipped)");return}if(s.split(".").length===2)if(t instanceof z){console.log(`Creating Route53 alias record for apex domain ${s} -> ${u}`);let i=await t.createCloudFrontAlias({domain:s,name:s,cloudFrontDomainName:u});if(!i.success)console.warn(`Warning: Could not create Route53 alias record: ${i.message}`),console.warn("Please manually create an A-record alias in Route53:"),console.warn(` ${s} -> ${u}`);else console.log(`Created Route53 alias record: ${s} -> ${u}`);let a=`www.${s}`;console.log(`Creating Route53 alias record for ${a} -> ${u}`);let c=await t.createCloudFrontAlias({domain:s,name:a,cloudFrontDomainName:u});if(!c.success)console.warn(`Warning: Could not create www Route53 alias: ${c.message}`),console.warn("Please manually create an A-record alias in Route53:"),console.warn(` ${a} -> ${u}`);else console.log(`Created Route53 alias record: ${a} -> ${u}`)}else{try{let g=await t.listRecords(s,"A");if(g.success)for(let C of g.records){let w=C.name.replace(/\.$/,"");if(w===s||w==="")console.log(`Removing existing root A record (${C.content}) to make room for ALIAS...`),await t.deleteRecord(s,{name:s,type:"A",content:C.content})}}catch(g){console.log(`Note: Could not check for conflicting A records: ${g instanceof Error?g.message:g}`)}console.log(`Creating ALIAS record for apex domain ${s} -> ${u}`);let i=await t.upsertRecord(s,{name:s,type:"ALIAS",content:u,ttl:600});if(!i.success)console.warn(`Warning: Could not create ALIAS record: ${i.message}`),console.warn("Please manually create an ALIAS record in your DNS provider:"),console.warn(` ${s} -> ${u}`);else console.log(`Created ALIAS record: ${s} -> ${u}`);let a=`www.${s}`;console.log(`Creating CNAME record for ${a} -> ${u}`);let c=await t.upsertRecord(s,{name:a,type:"CNAME",content:u,ttl:600});if(!c.success)console.warn(`Warning: Could not create www DNS record: ${c.message}`),console.warn("Please manually create a CNAME record:"),console.warn(` ${a} -> ${u}`);else console.log(`Created CNAME record: ${a} -> ${u}`)}else{console.log(`Creating CNAME record for ${s} -> ${u}`);let i=await t.upsertRecord(s,{name:s,type:"CNAME",content:u,ttl:600});if(!i.success)console.warn(`Warning: Could not create DNS record: ${i.message}`),console.warn("Please manually create a CNAME record:"),console.warn(` ${s} -> ${u}`);else console.log(`Created CNAME record: ${s} -> ${u}`)}}async function un(t){let{sourceDir:s,cleanBucket:u=!1,onProgress:e,...p}=t;e?.("infrastructure","Deploying CloudFormation stack...");let i=await ln(p);if(!i.success)return i;if(u){e?.("clean","Cleaning old files from S3...");try{await new o(p.region||"us-east-1").emptyBucket(i.bucket)}catch(C){console.log(`Note: Could not clean bucket: ${C.message}`)}}e?.("upload","Uploading files to S3...");let{uploadStaticFiles:a}=await import("./chunk-rtn4gj6y.js"),c=await a({sourceDir:s,bucket:i.bucket,region:p.region||"us-east-1",cacheControl:p.cacheControl,onProgress:(C,w,x)=>{e?.("upload",`${C}/${w}: ${x}`)}});if(c.errors.length>0)return{...i,success:!1,message:`Upload errors: ${c.errors.join(", ")}`,filesUploaded:c.uploaded};if(i.distributionId&&c.uploaded>0){e?.("invalidate","Invalidating CloudFront cache...");let{invalidateCache:C}=await import("./chunk-rtn4gj6y.js");await C(i.distributionId)}e?.("complete","Deployment complete!");let g=c.skipped>0?`Deployed ${c.uploaded} files (${c.skipped} unchanged) with external DNS`:`Deployed ${c.uploaded} files successfully with external DNS`;return{...i,filesUploaded:c.uploaded,filesSkipped:c.skipped,message:g}}function Zi(t){let{bucketName:s,domain:u,certificateArn:e,hostedZoneId:p,defaultRootObject:i="index.html",errorDocument:a="404.html"}=t,c={},g={};c.S3Bucket={Type:"AWS::S3::Bucket",Properties:{BucketName:s,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:i,ErrorDocument:a}}},g.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},g.BucketArn={Description:"S3 Bucket ARN",Value:{"Fn::GetAtt":["S3Bucket","Arn"]}},c.CloudFrontOAC={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`OAC-${s}`,Description:`OAC for ${s}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},c.UrlRewriteFunction={Type:"AWS::CloudFront::Function",Properties:{Name:{"Fn::Sub":"${AWS::StackName}-url-rewrite"},AutoPublish:!0,FunctionConfig:{Comment:"Append .html extension to URLs without extensions",Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) {
|
|
46
46
|
const request = event.request;
|
|
47
47
|
var uri = request.uri;
|
|
48
48
|
|
|
@@ -56,5 +56,5 @@ import{z,oe,T,ae,or}from"./chunk-v9t92ak2.js";import{a}from"./chunk-z87dekhm.js"
|
|
|
56
56
|
}
|
|
57
57
|
|
|
58
58
|
return request;
|
|
59
|
-
}`}};let C={Enabled:!0,DefaultRootObject:i,HttpVersion:"http2and3",IPV6Enabled:!0,PriceClass:"PriceClass_100",Origins:[{Id:`S3-${s}`,DomainName:{"Fn::GetAtt":["S3Bucket","RegionalDomainName"]},S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{"Fn::GetAtt":["CloudFrontOAC","Id"]}}],DefaultCacheBehavior:{TargetOriginId:`S3-${s}`,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD"],CachedMethods:["GET","HEAD"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":["UrlRewriteFunction","FunctionARN"]}}]},CustomErrorResponses:[{ErrorCode:403,ResponseCode:200,ResponsePagePath:`/${i}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:404,ResponsePagePath:`/${r}`,ErrorCachingMinTTL:300}]};if(u&&e)C.Aliases=[u],C.ViewerCertificate={AcmCertificateArn:e,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};else C.ViewerCertificate={CloudFrontDefaultCertificate:!0};if(c.CloudFrontDistribution={Type:"AWS::CloudFront::Distribution",DependsOn:["S3Bucket","CloudFrontOAC","UrlRewriteFunction"],Properties:{DistributionConfig:C}},g.DistributionId={Description:"CloudFront Distribution ID",Value:{Ref:"CloudFrontDistribution"}},g.DistributionDomain={Description:"CloudFront Distribution Domain",Value:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]}},c.S3BucketPolicy={Type:"AWS::S3::BucketPolicy",DependsOn:["S3Bucket","CloudFrontDistribution"],Properties:{Bucket:{Ref:"S3Bucket"},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":"arn:aws:s3:::${S3Bucket}/*"},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":"arn:aws:cloudfront::${AWS::AccountId}:distribution/${CloudFrontDistribution}"}}}}]}}},u&&p)c.DNSRecord={Type:"AWS::Route53::RecordSet",DependsOn:"CloudFrontDistribution",Properties:{HostedZoneId:p,Name:u,Type:"A",AliasTarget:{DNSName:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}},c.DNSRecordIPv6={Type:"AWS::Route53::RecordSet",DependsOn:"CloudFrontDistribution",Properties:{HostedZoneId:p,Name:u,Type:"AAAA",AliasTarget:{DNSName:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}},g.SiteUrl={Description:"Site URL",Value:{"Fn::Sub":"https://${DNSRecord}"}};return{AWSTemplateFormatVersion:"2010-09-09",Description:`Static site infrastructure for ${u||s}`,Resources:c,Outputs:g}}async function Wi(t){if(t.dnsProvider&&t.dnsProvider.provider!=="route53"){let d=t.domain||(t.subdomain&&t.baseDomain?`${t.subdomain}.${t.baseDomain}`:void 0);if(!d)return{success:!1,stackName:t.stackName||`${t.siteName}-static-site`,bucket:t.bucket||`${t.siteName}-${Date.now()}`,message:"Domain is required when using external DNS provider"};return sn({siteName:t.siteName,region:t.region,domain:d,bucket:t.bucket,certificateArn:t.certificateArn,stackName:t.stackName,defaultRootObject:t.defaultRootObject,errorDocument:t.errorDocument,cacheControl:t.cacheControl,tags:t.tags,dnsProvider:t.dnsProvider})}let s=t.region||"us-east-1",u="us-east-1",e;if(t.domain)e=t.domain;else if(t.subdomain&&t.baseDomain)e=`${t.subdomain}.${t.baseDomain}`;let p=t.bucket||(e?e.replace(/\./g,"-"):`${t.siteName}-${Date.now()}`),i=t.stackName||`${t.siteName}-static-site`,r=new h(u),c=new y,g=new ae("us-east-1"),C=new or("us-east-1"),{hostedZoneId:w,certificateArn:x}=t;if(e&&!w){let d=await c.findHostedZoneForDomain(e);if(d)w=d.Id.replace("/hostedzone/","");else return{success:!1,stackName:i,bucket:p,message:`No Route53 hosted zone found for ${t.baseDomain||e}. Please create one first.`}}if(e&&!x&&w){let d=await g.findCertificateByDomain(e);if(d&&d.Status==="ISSUED")x=d.CertificateArn;else x=(await C.requestAndValidate({domainName:e,hostedZoneId:w,waitForValidation:!0,maxWaitMinutes:10})).certificateArn}let E=!1,M;try{let d=await r.describeStacks({stackName:i});if(d.Stacks.length>0){let k=d.Stacks[0],b=k.StackStatus;if(b==="DELETE_IN_PROGRESS")console.log("Previous stack is still being deleted, waiting..."),await r.waitForStack(i,"stack-delete-complete"),E=!1;else if(b==="DELETE_COMPLETE")E=!1;else E=!0,M=(k.Outputs||[]).find((n)=>n.OutputKey==="BucketName")?.OutputValue}}catch(d){if(d.message?.includes("does not exist")||d.code==="ValidationError")E=!1;else throw d}let S=M||p;if(!E){let d=new a(s),k=new A,b=!1;if(e){try{console.log(`Checking for existing CloudFront distribution for ${e}...`);let o=await k.listDistributions();for(let n of o){let m=[];if(n.Aliases?.Items){if(Array.isArray(n.Aliases.Items))m=n.Aliases.Items;else if(typeof n.Aliases.Items==="object"){let f=n.Aliases.Items.CNAME;if(typeof f==="string")m=[f];else if(Array.isArray(f))m=f}}if(m.includes(e)){b=!0,console.log(`Found existing CloudFront distribution ${n.Id} for ${e}`);let l=(await k.getDistributionConfig(n.Id)).DistributionConfig?.Origins?.Items,D;if(l){let F=[];if(Array.isArray(l))F=l;else if(l.Origin)F=Array.isArray(l.Origin)?l.Origin:[l.Origin];else F=[l];for(let P of F){let U=(P.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(U){D=U[1];break}}}if(D){let F=e.replace(/\./g,"-");if(!D.startsWith(F)&&!D.includes(t.siteName)){console.log(`Warning: Found distribution with mismatched bucket ${D}, skipping...`);continue}if(console.log(`Using existing S3 bucket: ${D}`),w&&n.DomainName)try{console.log(`Ensuring Route53 records exist for ${e}...`),await c.createAliasRecord({HostedZoneId:w,Name:e,Type:"A",TargetHostedZoneId:y.CloudFrontHostedZoneId,TargetDNSName:n.DomainName,EvaluateTargetHealth:!1}),await c.createAliasRecord({HostedZoneId:w,Name:e,Type:"AAAA",TargetHostedZoneId:y.CloudFrontHostedZoneId,TargetDNSName:n.DomainName,EvaluateTargetHealth:!1}),console.log(`Route53 records ensured for ${e}`)}catch(P){console.log(`Note: Could not update Route53 records: ${P.message}`)}return{success:!0,stackName:`existing-${n.Id}`,bucket:D,distributionId:n.Id,distributionDomain:n.DomainName,domain:e,certificateArn:x,message:"Using existing CloudFront distribution"}}}}}catch{}if(w)try{let n=(await c.listResourceRecordSets({HostedZoneId:w})).ResourceRecordSets||[];for(let m of n)if(m.Name===`${e}.`&&(m.Type==="A"||m.Type==="AAAA")){if(m.AliasTarget){console.log(`Found orphaned Route53 ${m.Type} record for ${e}, cleaning up...`);try{await c.deleteRecord({HostedZoneId:w,RecordSet:m}),console.log(`Deleted orphaned Route53 ${m.Type} record for ${e}`)}catch(f){console.log(`Note: Could not delete Route53 record: ${f.message}`)}}}}catch{}}if(!b)try{if((await d.headBucket(p)).exists){console.log(`Found orphaned S3 bucket ${p}, cleaning up...`);try{let n=d.emptyBucket(p).then(()=>d.deleteBucket(p)),m=new Promise((f,l)=>setTimeout(()=>l(Error("Bucket cleanup timeout")),30000));await Promise.race([n,m]),console.log(`Deleted orphaned S3 bucket ${p}`)}catch(n){console.log(`Note: Could not clean up S3 bucket: ${n.message}`);let m=Date.now().toString(36);S=`${p}-${m}`,console.log(`Using alternative bucket name: ${S}`)}}}catch{}}let N=Ki({bucketName:S,domain:e,certificateArn:x,hostedZoneId:w,defaultRootObject:t.defaultRootObject,errorDocument:t.errorDocument}),j=Object.entries(t.tags||{}).map(([d,k])=>({Key:d,Value:k}));j.push({Key:"ManagedBy",Value:"ts-cloud"}),j.push({Key:"Application",Value:t.siteName});let v,O=!1;if(E){O=!0,console.log(`Updating CloudFormation stack: ${i}`),console.log(`Using existing bucket: ${S}`),console.log(`Domain: ${e||"not specified"}`),console.log(`Certificate ARN: ${x||"not specified"}`);try{v=(await r.updateStack({stackName:i,templateBody:JSON.stringify(N),capabilities:["CAPABILITY_IAM"],tags:j})).StackId,console.log(`Update initiated, stack ID: ${v}`)}catch(d){if(d.message?.includes("No updates are to be performed")){let k=await r.describeStacks({stackName:i});v=k.Stacks[0].StackId;let b=k.Stacks[0]?.Outputs||[],o=(n)=>b.find((m)=>m.OutputKey===n)?.OutputValue;return{success:!0,stackId:v,stackName:i,bucket:o("BucketName")||S,distributionId:o("DistributionId"),distributionDomain:o("DistributionDomain"),domain:e,certificateArn:x,message:"Static site infrastructure is already up to date"}}else throw d}}else console.log(`Creating CloudFormation stack: ${i}`),console.log(`Bucket name: ${S}`),console.log(`Domain: ${e||"not specified"}`),console.log(`Certificate ARN: ${x||"not specified"}`),console.log("Stack does not exist, creating..."),v=(await r.createStack({stackName:i,templateBody:JSON.stringify(N),capabilities:["CAPABILITY_IAM"],tags:j,onFailure:"DELETE"})).StackId,console.log(`Create initiated, stack ID: ${v}`);console.log(`Waiting for stack to reach ${O?"stack-update-complete":"stack-create-complete"}...`);try{await r.waitForStack(i,O?"stack-update-complete":"stack-create-complete"),console.log("Stack operation completed successfully!")}catch(d){if(d.message?.includes("must be verified")||d.message?.includes("Access denied for operation")||d.message?.includes("failed")){console.log("CloudFormation deployment failed, trying direct API creation...");let k=new A;if(e)try{let b=await k.listDistributions();for(let o of b){let n=[];if(o.Aliases?.Items){if(Array.isArray(o.Aliases.Items))n=o.Aliases.Items;else if(typeof o.Aliases.Items==="object"){let m=o.Aliases.Items.CNAME;if(typeof m==="string")n=[m];else if(Array.isArray(m))n=m}}if(n.includes(e)){console.log(`Found existing CloudFront distribution ${o.Id} with alias ${e}`);let f=(await k.getDistributionConfig(o.Id)).DistributionConfig?.Origins?.Items,l;if(f){let D=[];if(Array.isArray(f))D=f;else if(f.Origin)D=Array.isArray(f.Origin)?f.Origin:[f.Origin];else D=[f];for(let F of D){let V=(F.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(V){l=V[1];break}}}if(l)return console.log(`Using existing S3 bucket: ${l}`),{success:!0,stackName:`existing-${o.Id}`,bucket:l,distributionId:o.Id,distributionDomain:o.DomainName,domain:e,certificateArn:x,message:"Using existing CloudFront distribution (account verification pending for new distributions)"}}}}catch{}console.log("No existing infrastructure found, creating via direct API calls...");try{let b=new a(s);if((await b.headBucket(S)).exists)console.log(`Using existing S3 bucket: ${S}`);else console.log(`Creating S3 bucket: ${S}...`),await b.createBucket(S);await b.putBucketWebsite(S,{IndexDocument:t.defaultRootObject||"index.html",ErrorDocument:t.errorDocument||"404.html"}),await b.putPublicAccessBlock(S,{BlockPublicAcls:!0,IgnorePublicAcls:!0,BlockPublicPolicy:!1,RestrictPublicBuckets:!1}),console.log(`S3 bucket ${S} configured`);let n=`OAC-${S}`;console.log(`Creating Origin Access Control: ${n}...`);let m=await k.findOrCreateOriginAccessControl(n);console.log(`Origin Access Control ${m.Id} ready`),console.log("Creating CloudFront distribution...");let f=await k.createDistributionForS3({bucketName:S,bucketRegion:s,originAccessControlId:m.Id,aliases:e?[e]:[],certificateArn:x,defaultRootObject:t.defaultRootObject||"index.html",comment:`Distribution for ${e||S}`});console.log(`CloudFront distribution ${f.Id} created`),console.log("Updating S3 bucket policy...");let l=A.getS3BucketPolicyForCloudFront(S,f.ARN);if(await b.putBucketPolicy(S,l),console.log("S3 bucket policy updated"),e&&w){console.log(`Creating Route53 records for ${e}...`);try{await c.createAliasRecord({HostedZoneId:w,Name:e,Type:"A",TargetHostedZoneId:y.CloudFrontHostedZoneId,TargetDNSName:f.DomainName,EvaluateTargetHealth:!1}),await c.createAliasRecord({HostedZoneId:w,Name:e,Type:"AAAA",TargetHostedZoneId:y.CloudFrontHostedZoneId,TargetDNSName:f.DomainName,EvaluateTargetHealth:!1}),console.log(`Route53 records created for ${e}`)}catch(D){console.log(`Note: Could not create Route53 records: ${D.message}`)}}return{success:!0,stackName:`direct-${f.Id}`,bucket:S,distributionId:f.Id,distributionDomain:f.DomainName,domain:e,certificateArn:x,message:"Static site infrastructure created via direct API calls"}}catch(b){return console.log(`Direct API creation failed: ${b.message}`),{success:!1,stackId:v,stackName:i,bucket:S,message:`Deployment failed: ${b.message}`}}}return{success:!1,stackId:v,stackName:i,bucket:S,message:`Stack deployment failed: ${d.message}`}}let I=(await r.describeStacks({stackName:i})).Stacks[0]?.Outputs||[],R=(d)=>I.find((k)=>k.OutputKey===d)?.OutputValue;return{success:!0,stackId:v,stackName:i,bucket:R("BucketName")||S,distributionId:R("DistributionId"),distributionDomain:R("DistributionDomain"),domain:e,certificateArn:x,message:"Static site infrastructure deployed successfully"}}async function Ji(t){let{sourceDir:s,bucket:u,region:e,cacheControl:p="max-age=31536000, public",onProgress:i}=t,r=new a(e),{readdir:c}=await import("node:fs/promises"),{join:g,relative:C}=await import("node:path"),{createHash:w}=await import("node:crypto");async function x(I){let R=[],d=await c(I,{withFileTypes:!0});for(let k of d){let b=g(I,k.name);if(k.isDirectory())R.push(...await x(b));else R.push(b)}return R}function E(I){let R=I.split(".").pop()?.toLowerCase();return{html:"text/html; charset=utf-8",css:"text/css; charset=utf-8",js:"application/javascript; charset=utf-8",json:"application/json; charset=utf-8",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",ico:"image/x-icon",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",xml:"application/xml",txt:"text/plain; charset=utf-8",sh:"text/plain; charset=utf-8",bash:"text/plain; charset=utf-8",ps1:"text/plain; charset=utf-8"}[R||""]||"application/octet-stream"}function M(I){return w("md5").update(I).digest("hex")}async function S(){let I=new Map,R;do{let d=await r.listObjects({bucket:u,maxKeys:1000,continuationToken:R});for(let k of d.objects){let b=k.ETag?.replace(/"/g,"")||"";I.set(k.Key,b)}R=d.nextContinuationToken}while(R);return I}let N=await x(s),j=[],v=0,O=0,B=await S();for(let I of N){let R=C(s,I),d=E(I),k=I.endsWith(".html")?"max-age=3600, public":p;try{let b=Buffer.from(await Bun.file(I).arrayBuffer()),o=M(b),n=B.get(R);if(n&&n===o){O++,i?.(v+O,N.length,R);continue}await r.putObject({bucket:u,key:R,body:b,contentType:d,cacheControl:k}),v++,i?.(v+O,N.length,R)}catch(b){j.push(`Failed to upload ${R}: ${b.message}`)}}return{uploaded:v,skipped:O,errors:j}}async function Xi(t){return{invalidationId:(await new A().invalidateAll(t)).Id}}async function wa(t,s="us-east-1"){let u=new h(s);try{let r=((await u.describeStacks({stackName:t})).Stacks[0]?.Outputs||[]).find((c)=>c.OutputKey==="BucketName")?.OutputValue;if(r)await new a(s).emptyBucket(r)}catch{}await u.deleteStack(t);let e=await u.waitForStackComplete(t,60,1e4);return{success:e.success||e.status==="DELETE_COMPLETE",message:e.success?"Static site deleted successfully":`Deletion failed: ${e.status}`}}async function Ra(t){let{sourceDir:s,cleanBucket:u=!1,onProgress:e,...p}=t;e?.("infrastructure","Deploying CloudFormation stack...");let i=await Wi(p);if(!i.success)return i;if(u){e?.("clean","Cleaning old files from S3...");try{await new a(p.region||"us-east-1").emptyBucket(i.bucket)}catch(g){console.log(`Note: Could not clean bucket: ${g.message}`)}}e?.("upload","Uploading files to S3...");let r=await Ji({sourceDir:s,bucket:i.bucket,region:p.region||"us-east-1",cacheControl:p.cacheControl,onProgress:(g,C,w)=>{e?.("upload",`${g}/${C}: ${w}`)}});if(r.errors.length>0)return{...i,success:!1,message:`Upload errors: ${r.errors.join(", ")}`,filesUploaded:r.uploaded};if(i.distributionId&&r.uploaded>0)e?.("invalidate","Invalidating CloudFront cache..."),await Xi(i.distributionId);e?.("complete","Deployment complete!");let c=r.skipped>0?`Deployed ${r.uploaded} files (${r.skipped} unchanged)`:`Deployed ${r.uploaded} files successfully`;return{...i,filesUploaded:r.uploaded,filesSkipped:r.skipped,message:c}}
|
|
60
|
-
export{
|
|
59
|
+
}`}};let C={Enabled:!0,DefaultRootObject:i,HttpVersion:"http2and3",IPV6Enabled:!0,PriceClass:"PriceClass_100",Origins:[{Id:`S3-${s}`,DomainName:{"Fn::GetAtt":["S3Bucket","RegionalDomainName"]},S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{"Fn::GetAtt":["CloudFrontOAC","Id"]}}],DefaultCacheBehavior:{TargetOriginId:`S3-${s}`,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD"],CachedMethods:["GET","HEAD"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":["UrlRewriteFunction","FunctionARN"]}}]},CustomErrorResponses:[{ErrorCode:403,ResponseCode:200,ResponsePagePath:`/${i}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:404,ResponsePagePath:`/${a}`,ErrorCachingMinTTL:300}]};if(u&&e)C.Aliases=[u],C.ViewerCertificate={AcmCertificateArn:e,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};else C.ViewerCertificate={CloudFrontDefaultCertificate:!0};if(c.CloudFrontDistribution={Type:"AWS::CloudFront::Distribution",DependsOn:["S3Bucket","CloudFrontOAC","UrlRewriteFunction"],Properties:{DistributionConfig:C}},g.DistributionId={Description:"CloudFront Distribution ID",Value:{Ref:"CloudFrontDistribution"}},g.DistributionDomain={Description:"CloudFront Distribution Domain",Value:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]}},c.S3BucketPolicy={Type:"AWS::S3::BucketPolicy",DependsOn:["S3Bucket","CloudFrontDistribution"],Properties:{Bucket:{Ref:"S3Bucket"},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":"arn:aws:s3:::${S3Bucket}/*"},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":"arn:aws:cloudfront::${AWS::AccountId}:distribution/${CloudFrontDistribution}"}}}}]}}},u&&p)c.DNSRecord={Type:"AWS::Route53::RecordSet",DependsOn:"CloudFrontDistribution",Properties:{HostedZoneId:p,Name:u,Type:"A",AliasTarget:{DNSName:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}},c.DNSRecordIPv6={Type:"AWS::Route53::RecordSet",DependsOn:"CloudFrontDistribution",Properties:{HostedZoneId:p,Name:u,Type:"AAAA",AliasTarget:{DNSName:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}},g.SiteUrl={Description:"Site URL",Value:{"Fn::Sub":"https://${DNSRecord}"}};return{AWSTemplateFormatVersion:"2010-09-09",Description:`Static site infrastructure for ${u||s}`,Resources:c,Outputs:g}}async function es(t){if(t.dnsProvider&&t.dnsProvider.provider!=="route53"){let d=t.domain||(t.subdomain&&t.baseDomain?`${t.subdomain}.${t.baseDomain}`:void 0);if(!d)return{success:!1,stackName:t.stackName||`${t.siteName}-static-site`,bucket:t.bucket||`${t.siteName}-${Date.now()}`,message:"Domain is required when using external DNS provider"};return ln({siteName:t.siteName,region:t.region,domain:d,bucket:t.bucket,certificateArn:t.certificateArn,stackName:t.stackName,defaultRootObject:t.defaultRootObject,errorDocument:t.errorDocument,cacheControl:t.cacheControl,tags:t.tags,dnsProvider:t.dnsProvider})}let s=t.region||"us-east-1",u="us-east-1",e;if(t.domain)e=t.domain;else if(t.subdomain&&t.baseDomain)e=`${t.subdomain}.${t.baseDomain}`;let p=t.bucket||(e?e.replace(/\./g,"-"):`${t.siteName}-${Date.now()}`),i=t.stackName||`${t.siteName}-static-site`,a=new h(u),c=new y,g=new ae("us-east-1"),C=new dr("us-east-1"),{hostedZoneId:w,certificateArn:x}=t;if(e&&!w){let d=await c.findHostedZoneForDomain(e);if(d)w=d.Id.replace("/hostedzone/","");else return{success:!1,stackName:i,bucket:p,message:`No Route53 hosted zone found for ${t.baseDomain||e}. Please create one first.`}}if(e&&!x&&w){let d=await g.findCertificateByDomain(e);if(d&&d.Status==="ISSUED")x=d.CertificateArn;else x=(await C.requestAndValidate({domainName:e,hostedZoneId:w,waitForValidation:!0,maxWaitMinutes:10})).certificateArn}let E=!1,M;try{let d=await a.describeStacks({stackName:i});if(d.Stacks.length>0){let k=d.Stacks[0],b=k.StackStatus;if(b==="DELETE_IN_PROGRESS")console.log("Previous stack is still being deleted, waiting..."),await a.waitForStack(i,"stack-delete-complete"),E=!1;else if(b==="DELETE_COMPLETE")E=!1;else E=!0,M=(k.Outputs||[]).find((r)=>r.OutputKey==="BucketName")?.OutputValue}}catch(d){if(d.message?.includes("does not exist")||d.code==="ValidationError")E=!1;else throw d}let S=M||p;if(!E){let d=new o(s),k=new A,b=!1;if(e){try{console.log(`Checking for existing CloudFront distribution for ${e}...`);let n=await k.listDistributions();for(let r of n){let m=[];if(r.Aliases?.Items){if(Array.isArray(r.Aliases.Items))m=r.Aliases.Items;else if(typeof r.Aliases.Items==="object"){let f=r.Aliases.Items.CNAME;if(typeof f==="string")m=[f];else if(Array.isArray(f))m=f}}if(m.includes(e)){b=!0,console.log(`Found existing CloudFront distribution ${r.Id} for ${e}`);let l=(await k.getDistributionConfig(r.Id)).DistributionConfig?.Origins?.Items,D;if(l){let F=[];if(Array.isArray(l))F=l;else if(l.Origin)F=Array.isArray(l.Origin)?l.Origin:[l.Origin];else F=[l];for(let P of F){let U=(P.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(U){D=U[1];break}}}if(D){let F=e.replace(/\./g,"-");if(!D.startsWith(F)&&!D.includes(t.siteName)){console.log(`Warning: Found distribution with mismatched bucket ${D}, skipping...`);continue}if(console.log(`Using existing S3 bucket: ${D}`),w&&r.DomainName)try{console.log(`Ensuring Route53 records exist for ${e}...`),await c.createAliasRecord({HostedZoneId:w,Name:e,Type:"A",TargetHostedZoneId:y.CloudFrontHostedZoneId,TargetDNSName:r.DomainName,EvaluateTargetHealth:!1}),await c.createAliasRecord({HostedZoneId:w,Name:e,Type:"AAAA",TargetHostedZoneId:y.CloudFrontHostedZoneId,TargetDNSName:r.DomainName,EvaluateTargetHealth:!1}),console.log(`Route53 records ensured for ${e}`)}catch(P){console.log(`Note: Could not update Route53 records: ${P.message}`)}return{success:!0,stackName:`existing-${r.Id}`,bucket:D,distributionId:r.Id,distributionDomain:r.DomainName,domain:e,certificateArn:x,message:"Using existing CloudFront distribution"}}}}}catch{}if(w)try{let r=(await c.listResourceRecordSets({HostedZoneId:w})).ResourceRecordSets||[];for(let m of r)if(m.Name===`${e}.`&&(m.Type==="A"||m.Type==="AAAA")){if(m.AliasTarget){console.log(`Found orphaned Route53 ${m.Type} record for ${e}, cleaning up...`);try{await c.deleteRecord({HostedZoneId:w,RecordSet:m}),console.log(`Deleted orphaned Route53 ${m.Type} record for ${e}`)}catch(f){console.log(`Note: Could not delete Route53 record: ${f.message}`)}}}}catch{}}if(!b)try{if((await d.headBucket(p)).exists){console.log(`Found orphaned S3 bucket ${p}, cleaning up...`);try{let r=d.emptyBucket(p).then(()=>d.deleteBucket(p)),m=new Promise((f,l)=>setTimeout(()=>l(Error("Bucket cleanup timeout")),30000));await Promise.race([r,m]),console.log(`Deleted orphaned S3 bucket ${p}`)}catch(r){console.log(`Note: Could not clean up S3 bucket: ${r.message}`);let m=Date.now().toString(36);S=`${p}-${m}`,console.log(`Using alternative bucket name: ${S}`)}}}catch{}}let N=Zi({bucketName:S,domain:e,certificateArn:x,hostedZoneId:w,defaultRootObject:t.defaultRootObject,errorDocument:t.errorDocument}),j=Object.entries(t.tags||{}).map(([d,k])=>({Key:d,Value:k}));j.push({Key:"ManagedBy",Value:"ts-cloud"}),j.push({Key:"Application",Value:t.siteName});let v,O=!1;if(E){O=!0,console.log(`Updating CloudFormation stack: ${i}`),console.log(`Using existing bucket: ${S}`),console.log(`Domain: ${e||"not specified"}`),console.log(`Certificate ARN: ${x||"not specified"}`);try{v=(await a.updateStack({stackName:i,templateBody:JSON.stringify(N),capabilities:["CAPABILITY_IAM"],tags:j})).StackId,console.log(`Update initiated, stack ID: ${v}`)}catch(d){if(d.message?.includes("No updates are to be performed")){let k=await a.describeStacks({stackName:i});v=k.Stacks[0].StackId;let b=k.Stacks[0]?.Outputs||[],n=(r)=>b.find((m)=>m.OutputKey===r)?.OutputValue;return{success:!0,stackId:v,stackName:i,bucket:n("BucketName")||S,distributionId:n("DistributionId"),distributionDomain:n("DistributionDomain"),domain:e,certificateArn:x,message:"Static site infrastructure is already up to date"}}else throw d}}else console.log(`Creating CloudFormation stack: ${i}`),console.log(`Bucket name: ${S}`),console.log(`Domain: ${e||"not specified"}`),console.log(`Certificate ARN: ${x||"not specified"}`),console.log("Stack does not exist, creating..."),v=(await a.createStack({stackName:i,templateBody:JSON.stringify(N),capabilities:["CAPABILITY_IAM"],tags:j,onFailure:"DELETE"})).StackId,console.log(`Create initiated, stack ID: ${v}`);console.log(`Waiting for stack to reach ${O?"stack-update-complete":"stack-create-complete"}...`);try{await a.waitForStack(i,O?"stack-update-complete":"stack-create-complete"),console.log("Stack operation completed successfully!")}catch(d){if(d.message?.includes("must be verified")||d.message?.includes("Access denied for operation")||d.message?.includes("failed")){console.log("CloudFormation deployment failed, trying direct API creation...");let k=new A;if(e)try{let b=await k.listDistributions();for(let n of b){let r=[];if(n.Aliases?.Items){if(Array.isArray(n.Aliases.Items))r=n.Aliases.Items;else if(typeof n.Aliases.Items==="object"){let m=n.Aliases.Items.CNAME;if(typeof m==="string")r=[m];else if(Array.isArray(m))r=m}}if(r.includes(e)){console.log(`Found existing CloudFront distribution ${n.Id} with alias ${e}`);let f=(await k.getDistributionConfig(n.Id)).DistributionConfig?.Origins?.Items,l;if(f){let D=[];if(Array.isArray(f))D=f;else if(f.Origin)D=Array.isArray(f.Origin)?f.Origin:[f.Origin];else D=[f];for(let F of D){let V=(F.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(V){l=V[1];break}}}if(l)return console.log(`Using existing S3 bucket: ${l}`),{success:!0,stackName:`existing-${n.Id}`,bucket:l,distributionId:n.Id,distributionDomain:n.DomainName,domain:e,certificateArn:x,message:"Using existing CloudFront distribution (account verification pending for new distributions)"}}}}catch{}console.log("No existing infrastructure found, creating via direct API calls...");try{let b=new o(s);if((await b.headBucket(S)).exists)console.log(`Using existing S3 bucket: ${S}`);else console.log(`Creating S3 bucket: ${S}...`),await b.createBucket(S);await b.putBucketWebsite(S,{IndexDocument:t.defaultRootObject||"index.html",ErrorDocument:t.errorDocument||"404.html"}),await b.putPublicAccessBlock(S,{BlockPublicAcls:!0,IgnorePublicAcls:!0,BlockPublicPolicy:!1,RestrictPublicBuckets:!1}),console.log(`S3 bucket ${S} configured`);let r=`OAC-${S}`;console.log(`Creating Origin Access Control: ${r}...`);let m=await k.findOrCreateOriginAccessControl(r);console.log(`Origin Access Control ${m.Id} ready`),console.log("Creating CloudFront distribution...");let f=await k.createDistributionForS3({bucketName:S,bucketRegion:s,originAccessControlId:m.Id,aliases:e?[e]:[],certificateArn:x,defaultRootObject:t.defaultRootObject||"index.html",comment:`Distribution for ${e||S}`});console.log(`CloudFront distribution ${f.Id} created`),console.log("Updating S3 bucket policy...");let l=A.getS3BucketPolicyForCloudFront(S,f.ARN);if(await b.putBucketPolicy(S,l),console.log("S3 bucket policy updated"),e&&w){console.log(`Creating Route53 records for ${e}...`);try{await c.createAliasRecord({HostedZoneId:w,Name:e,Type:"A",TargetHostedZoneId:y.CloudFrontHostedZoneId,TargetDNSName:f.DomainName,EvaluateTargetHealth:!1}),await c.createAliasRecord({HostedZoneId:w,Name:e,Type:"AAAA",TargetHostedZoneId:y.CloudFrontHostedZoneId,TargetDNSName:f.DomainName,EvaluateTargetHealth:!1}),console.log(`Route53 records created for ${e}`)}catch(D){console.log(`Note: Could not create Route53 records: ${D.message}`)}}return{success:!0,stackName:`direct-${f.Id}`,bucket:S,distributionId:f.Id,distributionDomain:f.DomainName,domain:e,certificateArn:x,message:"Static site infrastructure created via direct API calls"}}catch(b){return console.log(`Direct API creation failed: ${b.message}`),{success:!1,stackId:v,stackName:i,bucket:S,message:`Deployment failed: ${b.message}`}}}return{success:!1,stackId:v,stackName:i,bucket:S,message:`Stack deployment failed: ${d.message}`}}let I=(await a.describeStacks({stackName:i})).Stacks[0]?.Outputs||[],R=(d)=>I.find((k)=>k.OutputKey===d)?.OutputValue;return{success:!0,stackId:v,stackName:i,bucket:R("BucketName")||S,distributionId:R("DistributionId"),distributionDomain:R("DistributionDomain"),domain:e,certificateArn:x,message:"Static site infrastructure deployed successfully"}}async function ts(t){let{sourceDir:s,bucket:u,region:e,cacheControl:p="max-age=31536000, public",onProgress:i}=t,a=new o(e),{readdir:c}=await import("node:fs/promises"),{join:g,relative:C}=await import("node:path"),{createHash:w}=await import("node:crypto");async function x(I){let R=[],d=await c(I,{withFileTypes:!0});for(let k of d){let b=g(I,k.name);if(k.isDirectory())R.push(...await x(b));else R.push(b)}return R}function E(I){let R=I.split(".").pop()?.toLowerCase();return{html:"text/html; charset=utf-8",css:"text/css; charset=utf-8",js:"application/javascript; charset=utf-8",json:"application/json; charset=utf-8",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",ico:"image/x-icon",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",xml:"application/xml",txt:"text/plain; charset=utf-8",sh:"text/plain; charset=utf-8",bash:"text/plain; charset=utf-8",ps1:"text/plain; charset=utf-8"}[R||""]||"application/octet-stream"}function M(I){return w("md5").update(I).digest("hex")}async function S(){let I=new Map,R;do{let d=await a.listObjects({bucket:u,maxKeys:1000,continuationToken:R});for(let k of d.objects){let b=k.ETag?.replace(/"/g,"")||"";I.set(k.Key,b)}R=d.nextContinuationToken}while(R);return I}let N=await x(s),j=[],v=0,O=0,B=await S();for(let I of N){let R=C(s,I),d=E(I),k=I.endsWith(".html")?"max-age=3600, public":p;try{let b=Buffer.from(await Bun.file(I).arrayBuffer()),n=M(b),r=B.get(R);if(r&&r===n){O++,i?.(v+O,N.length,R);continue}await a.putObject({bucket:u,key:R,body:b,contentType:d,cacheControl:k}),v++,i?.(v+O,N.length,R)}catch(b){j.push(`Failed to upload ${R}: ${b.message}`)}}return{uploaded:v,skipped:O,errors:j}}async function rs(t){return{invalidationId:(await new A().invalidateAll(t)).Id}}async function _a(t,s="us-east-1"){let u=new h(s);try{let a=((await u.describeStacks({stackName:t})).Stacks[0]?.Outputs||[]).find((c)=>c.OutputKey==="BucketName")?.OutputValue;if(a)await new o(s).emptyBucket(a)}catch{}await u.deleteStack(t);let e=await u.waitForStackComplete(t,60,1e4);return{success:e.success||e.status==="DELETE_COMPLETE",message:e.success?"Static site deleted successfully":`Deletion failed: ${e.status}`}}async function Oa(t){let{sourceDir:s,cleanBucket:u=!1,onProgress:e,...p}=t;e?.("infrastructure","Deploying CloudFormation stack...");let i=await es(p);if(!i.success)return i;if(u){e?.("clean","Cleaning old files from S3...");try{await new o(p.region||"us-east-1").emptyBucket(i.bucket)}catch(g){console.log(`Note: Could not clean bucket: ${g.message}`)}}e?.("upload","Uploading files to S3...");let a=await ts({sourceDir:s,bucket:i.bucket,region:p.region||"us-east-1",cacheControl:p.cacheControl,onProgress:(g,C,w)=>{e?.("upload",`${g}/${C}: ${w}`)}});if(a.errors.length>0)return{...i,success:!1,message:`Upload errors: ${a.errors.join(", ")}`,filesUploaded:a.uploaded};if(i.distributionId&&a.uploaded>0)e?.("invalidate","Invalidating CloudFront cache..."),await rs(i.distributionId);e?.("complete","Deployment complete!");let c=a.skipped>0?`Deployed ${a.uploaded} files (${a.skipped} unchanged)`:`Deployed ${a.uploaded} files successfully`;return{...i,filesUploaded:a.uploaded,filesSkipped:a.skipped,message:c}}
|
|
60
|
+
export{Ba,ln,un,Zi,es,ts,rs,_a,Oa};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{n}from"./chunk-
|
|
1
|
+
import{n}from"./chunk-zx8ecz8b.js";class y{client;region;constructor(e="us-east-1"){this.region=e,this.client=new n}async createHostedZone(e){let t=e.CallerReference||`${Date.now()}-${Math.random().toString(36).slice(2)}`,o=`<?xml version="1.0" encoding="UTF-8"?>
|
|
2
2
|
<CreateHostedZoneRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
|
|
3
3
|
<Name>${e.Name}</Name>
|
|
4
4
|
<CallerReference>${t}</CallerReference>`;if(e.HostedZoneConfig){if(o+=`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as q}from"node:module";var k=Object.create;var{getPrototypeOf:l,defineProperty:i,getOwnPropertyNames:m}=Object;var j=Object.prototype.hasOwnProperty;function n(a){return this[a]}var o,p,
|
|
2
|
-
export{
|
|
1
|
+
import{createRequire as q}from"node:module";var k=Object.create;var{getPrototypeOf:l,defineProperty:i,getOwnPropertyNames:m}=Object;var j=Object.prototype.hasOwnProperty;function n(a){return this[a]}var o,p,zh=(a,b,d)=>{var f=a!=null&&typeof a==="object";if(f){var g=b?o??=new WeakMap:p??=new WeakMap,h=g.get(a);if(h)return h}d=a!=null?k(l(a)):{};let c=b||!a||!a.__esModule||!j.call(a,"default")?i(d,"default",{value:a,enumerable:!0}):d;if(a&&typeof a==="object"||typeof a==="function"){for(let e of m(a))if(!j.call(c,e))i(c,e,{get:n.bind(a,e),enumerable:!0})}if(f)g.set(a,c);return c};var Kh=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var Fe=q(import.meta.url);
|
|
2
|
+
export{zh,Kh,Fe};
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import{n}from"./chunk-ss4q8kge.js";import{a}from"./chunk-z87dekhm.js";import{y}from"./chunk-emx1j2yt.js";import{Me}from"./chunk-4twnkjyq.js";function S(e,t){let s=[`Action=${e}`,"Version=2010-05-08"];for(let[o,i]of Object.entries(t)){if(i===void 0||i===null)continue;if(Array.isArray(i))i.forEach((c,u)=>{if(typeof c==="object"&&c!==null)for(let[d,m]of Object.entries(c))s.push(`${o}.member.${u+1}.${d}=${encodeURIComponent(String(m))}`);else s.push(`${o}.member.${u+1}=${encodeURIComponent(String(c))}`)});else if(typeof i==="object"){for(let[c,u]of Object.entries(i))if(u!==void 0&&u!==null)s.push(`${o}.${c}=${encodeURIComponent(String(u))}`)}else s.push(`${o}=${encodeURIComponent(String(i))}`)}return s.join("&")}function r(e,t){let s=new RegExp(`<${t}>([^<]*)</${t}>`),o=e.match(s);return o?o[1]:void 0}function l(e,t,s){let o=new RegExp(`<${t}>([\\s\\S]*?)</${t}>`),i=e.match(o);if(!i)return[];let c=[],u=new RegExp(`<${s}>([\\s\\S]*?)</${s}>`,"g"),d;while((d=u.exec(i[1]))!==null)c.push(d[1]);return c}class fe{client;region;constructor(e="us-east-1",t){this.client=new n(void 0,{profile:t}),this.region=e}async request(e,t={}){let s=S(e,t);return await this.client.request({service:"iam",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s})}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),s=this.parseUsers(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Users:s,IsTruncated:o,Marker:i}}async updateUser(e){await this.request("UpdateUser",e)}async deleteUser(e){await this.request("DeleteUser",e)}parseUser(e){return{UserName:r(e,"UserName")||"",UserId:r(e,"UserId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate"),PasswordLastUsed:r(e,"PasswordLastUsed")}}parseUsers(e){return l(e,"Users","member").map((s)=>({UserName:r(s,"UserName")||"",UserId:r(s,"UserId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate"),PasswordLastUsed:r(s,"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),s=this.parseGroup(t),o=this.parseUsers(t),i=r(t,"IsTruncated")==="true",c=r(t,"Marker");return{Group:s,Users:o,IsTruncated:i,Marker:c}}async listGroups(e={}){let t=await this.request("ListGroups",e),s=this.parseGroups(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Groups:s,IsTruncated:o,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),s=this.parseGroups(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Groups:s,IsTruncated:o,Marker:i}}parseGroup(e){return{GroupName:r(e,"GroupName")||"",GroupId:r(e,"GroupId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate")}}parseGroups(e){return l(e,"Groups","member").map((s)=>({GroupName:r(s,"GroupName")||"",GroupId:r(s,"GroupId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"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),s=this.parseRoles(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Roles:s,IsTruncated:o,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),s=this.parseTags(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Tags:s,IsTruncated:o,Marker:i}}parseRole(e){return{RoleName:r(e,"RoleName")||"",RoleId:r(e,"RoleId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate"),AssumeRolePolicyDocument:r(e,"AssumeRolePolicyDocument"),Description:r(e,"Description"),MaxSessionDuration:r(e,"MaxSessionDuration")?Number.parseInt(r(e,"MaxSessionDuration"),10):void 0}}parseRoles(e){return l(e,"Roles","member").map((s)=>({RoleName:r(s,"RoleName")||"",RoleId:r(s,"RoleId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate"),AssumeRolePolicyDocument:r(s,"AssumeRolePolicyDocument"),Description:r(s,"Description"),MaxSessionDuration:r(s,"MaxSessionDuration")?Number.parseInt(r(s,"MaxSessionDuration"),10):void 0}))}parseTags(e){return l(e,"Tags","member").map((s)=>({Key:r(s,"Key")||"",Value:r(s,"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:r(t,"VersionId")||"",IsDefaultVersion:r(t,"IsDefaultVersion")==="true",CreateDate:r(t,"CreateDate"),Document:r(t,"Document")}}async listPolicies(e={}){let t=await this.request("ListPolicies",e),s=this.parsePolicies(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Policies:s,IsTruncated:o,Marker:i}}async listPolicyVersions(e){let t=await this.request("ListPolicyVersions",e),s=this.parsePolicyVersions(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Versions:s,IsTruncated:o,Marker:i}}async createPolicyVersion(e){let t=await this.request("CreatePolicyVersion",e);return{VersionId:r(t,"VersionId")||"",IsDefaultVersion:r(t,"IsDefaultVersion")==="true",CreateDate:r(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),s=this.parseAttachedPolicies(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:o,Marker:i}}async listAttachedGroupPolicies(e){let t=await this.request("ListAttachedGroupPolicies",e),s=this.parseAttachedPolicies(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:o,Marker:i}}async listAttachedRolePolicies(e){let t=await this.request("ListAttachedRolePolicies",e),s=this.parseAttachedPolicies(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:o,Marker:i}}parsePolicy(e){return{PolicyName:r(e,"PolicyName")||"",PolicyId:r(e,"PolicyId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),DefaultVersionId:r(e,"DefaultVersionId"),AttachmentCount:r(e,"AttachmentCount")?Number.parseInt(r(e,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:r(e,"PermissionsBoundaryUsageCount")?Number.parseInt(r(e,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:r(e,"IsAttachable")==="true",Description:r(e,"Description"),CreateDate:r(e,"CreateDate"),UpdateDate:r(e,"UpdateDate")}}parsePolicies(e){return l(e,"Policies","member").map((s)=>({PolicyName:r(s,"PolicyName")||"",PolicyId:r(s,"PolicyId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),DefaultVersionId:r(s,"DefaultVersionId"),AttachmentCount:r(s,"AttachmentCount")?Number.parseInt(r(s,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:r(s,"PermissionsBoundaryUsageCount")?Number.parseInt(r(s,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:r(s,"IsAttachable")==="true",Description:r(s,"Description"),CreateDate:r(s,"CreateDate"),UpdateDate:r(s,"UpdateDate")}))}parsePolicyVersions(e){return l(e,"Versions","member").map((s)=>({VersionId:r(s,"VersionId")||"",IsDefaultVersion:r(s,"IsDefaultVersion")==="true",CreateDate:r(s,"CreateDate")}))}parseAttachedPolicies(e){return l(e,"AttachedPolicies","member").map((s)=>({PolicyName:r(s,"PolicyName")||"",PolicyArn:r(s,"PolicyArn")||""}))}async putUserPolicy(e){await this.request("PutUserPolicy",e)}async getUserPolicy(e){let t=await this.request("GetUserPolicy",e);return{UserName:r(t,"UserName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteUserPolicy(e){await this.request("DeleteUserPolicy",e)}async listUserPolicies(e){let t=await this.request("ListUserPolicies",e),s=l(t,"PolicyNames","member"),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:o,Marker:i}}async putGroupPolicy(e){await this.request("PutGroupPolicy",e)}async getGroupPolicy(e){let t=await this.request("GetGroupPolicy",e);return{GroupName:r(t,"GroupName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteGroupPolicy(e){await this.request("DeleteGroupPolicy",e)}async listGroupPolicies(e){let t=await this.request("ListGroupPolicies",e),s=l(t,"PolicyNames","member"),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:o,Marker:i}}async putRolePolicy(e){await this.request("PutRolePolicy",e)}async getRolePolicy(e){let t=await this.request("GetRolePolicy",e);return{RoleName:r(t,"RoleName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteRolePolicy(e){await this.request("DeleteRolePolicy",e)}async listRolePolicies(e){let t=await this.request("ListRolePolicies",e),s=l(t,"PolicyNames","member"),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:o,Marker:i}}async createAccessKey(e={}){let t=await this.request("CreateAccessKey",e);if(typeof t==="object"){let s=t?.CreateAccessKeyResult?.AccessKey||t?.AccessKey;if(s)return{AccessKey:{UserName:s.UserName||"",AccessKeyId:s.AccessKeyId||"",Status:s.Status||"Active",SecretAccessKey:s.SecretAccessKey||"",CreateDate:s.CreateDate}}}return{AccessKey:{UserName:r(t,"UserName")||"",AccessKeyId:r(t,"AccessKeyId")||"",Status:r(t,"Status")||"Active",SecretAccessKey:r(t,"SecretAccessKey")||"",CreateDate:r(t,"CreateDate")}}}async listAccessKeys(e={}){let t=await this.request("ListAccessKeys",e),s=this.parseAccessKeys(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AccessKeyMetadata:s,IsTruncated:o,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:r(t,"UserName")||"",AccessKeyLastUsed:{LastUsedDate:r(t,"LastUsedDate"),ServiceName:r(t,"ServiceName"),Region:r(t,"Region")}}}parseAccessKeys(e){return l(e,"AccessKeyMetadata","member").map((s)=>({UserName:r(s,"UserName"),AccessKeyId:r(s,"AccessKeyId")||"",Status:r(s,"Status")||"Active",CreateDate:r(s,"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),s=this.parseInstanceProfiles(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{InstanceProfiles:s,IsTruncated:o,Marker:i}}async listInstanceProfilesForRole(e){let t=await this.request("ListInstanceProfilesForRole",e),s=this.parseInstanceProfiles(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{InstanceProfiles:s,IsTruncated:o,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:r(e,"InstanceProfileName")||"",InstanceProfileId:r(e,"InstanceProfileId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate")}}parseInstanceProfiles(e){return l(e,"InstanceProfiles","member").map((s)=>({InstanceProfileName:r(s,"InstanceProfileName")||"",InstanceProfileId:r(s,"InstanceProfileId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate")}))}async getAccountPasswordPolicy(){let e=await this.request("GetAccountPasswordPolicy");return{MinimumPasswordLength:r(e,"MinimumPasswordLength")?Number.parseInt(r(e,"MinimumPasswordLength"),10):void 0,RequireSymbols:r(e,"RequireSymbols")==="true",RequireNumbers:r(e,"RequireNumbers")==="true",RequireUppercaseCharacters:r(e,"RequireUppercaseCharacters")==="true",RequireLowercaseCharacters:r(e,"RequireLowercaseCharacters")==="true",AllowUsersToChangePassword:r(e,"AllowUsersToChangePassword")==="true",ExpirePasswords:r(e,"ExpirePasswords")==="true",MaxPasswordAge:r(e,"MaxPasswordAge")?Number.parseInt(r(e,"MaxPasswordAge"),10):void 0,PasswordReusePrevention:r(e,"PasswordReusePrevention")?Number.parseInt(r(e,"PasswordReusePrevention"),10):void 0,HardExpiry:r(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={},s=l(e,"SummaryMap","entry");for(let o of s){let i=r(o,"key"),c=r(o,"value");if(i&&c)t[i]=Number.parseInt(c,10)}return t}async listAccountAliases(){let e=await this.request("ListAccountAliases"),t=l(e,"AccountAliases","member"),s=r(e,"IsTruncated")==="true",o=r(e,"Marker");return{AccountAliases:t,IsTruncated:s,Marker:o}}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 s=l(e,"EvaluationResults","member").map((c)=>{let d=l(c,"MatchedStatements","member").map((m)=>({SourcePolicyId:r(m,"SourcePolicyId"),SourcePolicyType:r(m,"SourcePolicyType")}));return{EvalActionName:r(c,"EvalActionName")||"",EvalResourceName:r(c,"EvalResourceName"),EvalDecision:r(c,"EvalDecision")||"",MatchedStatements:d.length>0?d:void 0}}),o=r(e,"IsTruncated")==="true",i=r(e,"Marker");return{EvaluationResults:s,IsTruncated:o,Marker:i}}}class et{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new n(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",s=[];if(e?.PageSize)s.push(`PageSize=${e.PageSize}`);if(e?.NextToken)s.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(s.length>0)t+=`?${s.join("&")}`;let o=await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}});return{EmailIdentities:o.EmailIdentities,NextToken:o.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",s=[];if(e?.PageSize)s.push(`PageSize=${e.PageSize}`);if(e?.NextToken)s.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(s.length>0)t+=`?${s.join("&")}`;return await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}})}async getSendStatistics(){return{SendDataPoints:(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"})).GetSendStatisticsResponse?.GetSendStatisticsResult?.SendDataPoints?.member}}async getSendQuota(){let t=(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"})).GetSendQuotaResponse?.GetSendQuotaResult;return{Max24HourSend:t?.Max24HourSend?Number(t.Max24HourSend):void 0,MaxSendRate:t?.MaxSendRate?Number(t.MaxSendRate):void 0,SentLast24Hours:t?.SentLast24Hours?Number(t.SentLast24Hours):void 0}}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],s=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0,o={};if(e.text)o.Text={Data:e.text};if(e.html)o.Html={Data:e.html};return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Simple:{Subject:{Data:e.subject},Body:o}},ReplyToAddresses:s})}async sendTemplatedEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],s=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:s})}async getDkimRecords(e){let t=await this.getEmailIdentity(e);if(!t.DkimAttributes?.Tokens)return[];return t.DkimAttributes.Tokens.map((s)=>({name:`${s}._domainkey.${e}`,type:"CNAME",value:`${s}.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,s=30000){for(let o=0;o<t;o++){if(await this.isDomainVerified(e))return!0;await new Promise((c)=>setTimeout(c,s))}return!1}buildFormBody(e){return Object.entries(e).filter(([,s])=>s!==void 0).map(([s,o])=>`${encodeURIComponent(s)}=${encodeURIComponent(o)}`).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 s=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)}),o=s?.ListReceiptRuleSetsResponse?.ListReceiptRuleSetsResult||s?.ListReceiptRuleSetsResult,i=o?.RuleSets?.member;return{RuleSets:Array.isArray(i)?i:i?[i]:[],NextToken:o?.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})}),s=t?.DescribeReceiptRuleSetResponse?.DescribeReceiptRuleSetResult||t?.DescribeReceiptRuleSetResult,o=s?.Rules?.member;return{Metadata:s?.Metadata,Rules:Array.isArray(o)?o:o?[o]:[]}}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((s,o)=>{t[`Rule.Recipients.member.${o+1}`]=s});e.Rule.Actions.forEach((s,o)=>{let i=o+1;if(s.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=s.S3Action.BucketName,s.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=s.S3Action.ObjectKeyPrefix;if(s.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=s.S3Action.KmsKeyArn}if(s.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=s.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=s.LambdaAction.InvocationType||"Event";if(s.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=s.SNSAction.TopicArn,s.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=s.SNSAction.Encoding}if(s.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=s.StopAction.Scope,s.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=s.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 s=t?.Rules?.member;return{Metadata:t?.Metadata,Rules:Array.isArray(s)?s:s?[s]:[]}}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((s,o)=>{t[`Rule.Recipients.member.${o+1}`]=s});e.Rule.Actions.forEach((s,o)=>{let i=o+1;if(s.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=s.S3Action.BucketName,s.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=s.S3Action.ObjectKeyPrefix;if(s.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=s.S3Action.KmsKeyArn}if(s.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=s.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=s.LambdaAction.InvocationType||"Event";if(s.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=s.SNSAction.TopicArn,s.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=s.SNSAction.Encoding}if(s.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=s.StopAction.Scope,s.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=s.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"),s={Action:"SendRawEmail",Version:"2010-12-01",Source:e.source,"RawMessage.Data":t};e.destinations.forEach((c,u)=>{s[`Destinations.member.${u+1}`]=c});let o=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(s)});return{MessageId:(o?.SendRawEmailResponse?.SendRawEmailResult||o?.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 hn{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 et(this.region),this.s3=new a(this.region),this.iam=new fe(this.region),this.route53=new y(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 s=e.fromName?`${e.fromName} <${t}>`:t,o=Array.isArray(e.to)?e.to:[e.to];if(!e.attachments||e.attachments.length===0)return{messageId:(await this.ses.sendSimpleEmail({from:s,to:o,subject:e.subject,text:e.text,html:e.html,replyTo:e.replyTo})).MessageId||""};let i=this.buildRawEmail(e,s,o);return{messageId:(await this.ses.sendEmail({FromEmailAddress:s,Destination:{ToAddresses:o,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 s=e.fromName?`${e.fromName} <${t}>`:t;return{messageId:(await this.ses.sendTemplatedEmail({from:s,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 s=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:s,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 o=await this.ses.createEmailIdentity({EmailIdentity:e});t={VerificationStatus:o.DkimAttributes?.Status,DkimAttributes:o.DkimAttributes,SendingEnabled:o.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 s=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=[],s=await this.ses.getDkimRecords(e);for(let o of s)t.push({type:o.type,name:o.name,value:o.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(o){if(!o.message?.includes("already exists")&&o.code!=="AlreadyExists")throw o}let s=[{S3Action:{BucketName:e.bucketName,ObjectKeyPrefix:e.prefix||"inbox/"}}];if(e.lambdaArn)s.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:s}})}catch(o){if(o.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:s}});else throw o}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((s)=>({key:s.Key||"",lastModified:s.LastModified||"",size:s.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:s}=await import("./chunk-dk3t3hgq.js"),o=new s,i=(g,P)=>{let A={Action:g,Version:"2010-05-08",...P};return Object.entries(A).map(([h,R])=>`${encodeURIComponent(h)}=${encodeURIComponent(R)}`).join("&")};try{await o.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateUser",{UserName:t})})}catch(g){if(!g.message?.includes("EntityAlreadyExists"))throw g}let c={Version:"2012-10-17",Statement:[{Effect:"Allow",Action:"ses:SendRawEmail",Resource:"*",Condition:{StringLike:{"ses:FromAddress":`*@${e.domain}`}}}]},u=`ses-smtp-policy-${e.domain.replace(/\./g,"-")}`;try{await o.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("PutUserPolicy",{UserName:t,PolicyName:u,PolicyDocument:JSON.stringify(c)})})}catch{}let m=(await o.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(!m?.AccessKeyId||!m?.SecretAccessKey)throw Error("Failed to create access key");let p=this.deriveSmtpPassword(m.SecretAccessKey);return{username:m.AccessKeyId,password:p,server:`email-smtp.${this.region}.amazonaws.com`,port:587}}deriveSmtpPassword(e){let t=Me("node:crypto"),s="SendRawEmail",o=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([o,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`,s=`${e.appName}-inbound-email`,o=e.storage?.bucketName||`${e.appName}-${e.environment}-email`,i=await this.setupDomain(e.domain);if(!(await this.s3.listBuckets()).Buckets?.some((m)=>m.Name===o))await this.s3.createBucket(o);await this.setupReceiving({domain:e.domain,ruleSetName:t,ruleName:s,bucketName:o,prefix:e.storage?.prefix||"inbox/",accountId:e.accountId,recipients:e.catchAll?[e.domain]:e.mailboxes,scanEnabled:!0});let d=await this.getDnsRecords(e.domain);return{success:!0,domainVerified:i.domainVerified,dkimStatus:i.dkimStatus,receiptRuleSet:t,storageBucket:o,dnsRecords:d}}async undeploy(e){let t=`${e.appName}-${e.environment}-email-rules`,s=`${e.appName}-inbound-email`,o=`${e.appName}-${e.environment}-email`;try{await this.ses.deleteReceiptRule(t,s)}catch{}try{await this.ses.deleteReceiptRuleSet(t)}catch{}if(e.deleteBucket)try{await this.s3.emptyAndDeleteBucket(o)}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,s){let o=`----=_Part_${Date.now()}_${Math.random().toString(36).substring(2)}`,i="";if(i+=`From: ${t}\r
|
|
1
|
+
import{n}from"./chunk-zx8ecz8b.js";import{o}from"./chunk-yd40pg8g.js";import{y}from"./chunk-9wmer0zx.js";import{Fe}from"./chunk-bxrzsth8.js";function S(e,t){let s=[`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((c,u)=>{if(typeof c==="object"&&c!==null)for(let[d,m]of Object.entries(c))s.push(`${a}.member.${u+1}.${d}=${encodeURIComponent(String(m))}`);else s.push(`${a}.member.${u+1}=${encodeURIComponent(String(c))}`)});else if(typeof i==="object"){for(let[c,u]of Object.entries(i))if(u!==void 0&&u!==null)s.push(`${a}.${c}=${encodeURIComponent(String(u))}`)}else s.push(`${a}=${encodeURIComponent(String(i))}`)}return s.join("&")}function r(e,t){let s=new RegExp(`<${t}>([^<]*)</${t}>`),a=e.match(s);return a?a[1]:void 0}function l(e,t,s){let a=new RegExp(`<${t}>([\\s\\S]*?)</${t}>`),i=e.match(a);if(!i)return[];let c=[],u=new RegExp(`<${s}>([\\s\\S]*?)</${s}>`,"g"),d;while((d=u.exec(i[1]))!==null)c.push(d[1]);return c}class fe{client;region;constructor(e="us-east-1",t){this.client=new n(void 0,{profile:t}),this.region=e}async request(e,t={}){let s=S(e,t);return await this.client.request({service:"iam",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s})}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),s=this.parseUsers(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Users:s,IsTruncated:a,Marker:i}}async updateUser(e){await this.request("UpdateUser",e)}async deleteUser(e){await this.request("DeleteUser",e)}parseUser(e){return{UserName:r(e,"UserName")||"",UserId:r(e,"UserId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate"),PasswordLastUsed:r(e,"PasswordLastUsed")}}parseUsers(e){return l(e,"Users","member").map((s)=>({UserName:r(s,"UserName")||"",UserId:r(s,"UserId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate"),PasswordLastUsed:r(s,"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),s=this.parseGroup(t),a=this.parseUsers(t),i=r(t,"IsTruncated")==="true",c=r(t,"Marker");return{Group:s,Users:a,IsTruncated:i,Marker:c}}async listGroups(e={}){let t=await this.request("ListGroups",e),s=this.parseGroups(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Groups:s,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),s=this.parseGroups(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Groups:s,IsTruncated:a,Marker:i}}parseGroup(e){return{GroupName:r(e,"GroupName")||"",GroupId:r(e,"GroupId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate")}}parseGroups(e){return l(e,"Groups","member").map((s)=>({GroupName:r(s,"GroupName")||"",GroupId:r(s,"GroupId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"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),s=this.parseRoles(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Roles:s,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),s=this.parseTags(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Tags:s,IsTruncated:a,Marker:i}}parseRole(e){return{RoleName:r(e,"RoleName")||"",RoleId:r(e,"RoleId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate"),AssumeRolePolicyDocument:r(e,"AssumeRolePolicyDocument"),Description:r(e,"Description"),MaxSessionDuration:r(e,"MaxSessionDuration")?Number.parseInt(r(e,"MaxSessionDuration"),10):void 0}}parseRoles(e){return l(e,"Roles","member").map((s)=>({RoleName:r(s,"RoleName")||"",RoleId:r(s,"RoleId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate"),AssumeRolePolicyDocument:r(s,"AssumeRolePolicyDocument"),Description:r(s,"Description"),MaxSessionDuration:r(s,"MaxSessionDuration")?Number.parseInt(r(s,"MaxSessionDuration"),10):void 0}))}parseTags(e){return l(e,"Tags","member").map((s)=>({Key:r(s,"Key")||"",Value:r(s,"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:r(t,"VersionId")||"",IsDefaultVersion:r(t,"IsDefaultVersion")==="true",CreateDate:r(t,"CreateDate"),Document:r(t,"Document")}}async listPolicies(e={}){let t=await this.request("ListPolicies",e),s=this.parsePolicies(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Policies:s,IsTruncated:a,Marker:i}}async listPolicyVersions(e){let t=await this.request("ListPolicyVersions",e),s=this.parsePolicyVersions(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Versions:s,IsTruncated:a,Marker:i}}async createPolicyVersion(e){let t=await this.request("CreatePolicyVersion",e);return{VersionId:r(t,"VersionId")||"",IsDefaultVersion:r(t,"IsDefaultVersion")==="true",CreateDate:r(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),s=this.parseAttachedPolicies(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:a,Marker:i}}async listAttachedGroupPolicies(e){let t=await this.request("ListAttachedGroupPolicies",e),s=this.parseAttachedPolicies(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:a,Marker:i}}async listAttachedRolePolicies(e){let t=await this.request("ListAttachedRolePolicies",e),s=this.parseAttachedPolicies(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:a,Marker:i}}parsePolicy(e){return{PolicyName:r(e,"PolicyName")||"",PolicyId:r(e,"PolicyId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),DefaultVersionId:r(e,"DefaultVersionId"),AttachmentCount:r(e,"AttachmentCount")?Number.parseInt(r(e,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:r(e,"PermissionsBoundaryUsageCount")?Number.parseInt(r(e,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:r(e,"IsAttachable")==="true",Description:r(e,"Description"),CreateDate:r(e,"CreateDate"),UpdateDate:r(e,"UpdateDate")}}parsePolicies(e){return l(e,"Policies","member").map((s)=>({PolicyName:r(s,"PolicyName")||"",PolicyId:r(s,"PolicyId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),DefaultVersionId:r(s,"DefaultVersionId"),AttachmentCount:r(s,"AttachmentCount")?Number.parseInt(r(s,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:r(s,"PermissionsBoundaryUsageCount")?Number.parseInt(r(s,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:r(s,"IsAttachable")==="true",Description:r(s,"Description"),CreateDate:r(s,"CreateDate"),UpdateDate:r(s,"UpdateDate")}))}parsePolicyVersions(e){return l(e,"Versions","member").map((s)=>({VersionId:r(s,"VersionId")||"",IsDefaultVersion:r(s,"IsDefaultVersion")==="true",CreateDate:r(s,"CreateDate")}))}parseAttachedPolicies(e){return l(e,"AttachedPolicies","member").map((s)=>({PolicyName:r(s,"PolicyName")||"",PolicyArn:r(s,"PolicyArn")||""}))}async putUserPolicy(e){await this.request("PutUserPolicy",e)}async getUserPolicy(e){let t=await this.request("GetUserPolicy",e);return{UserName:r(t,"UserName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteUserPolicy(e){await this.request("DeleteUserPolicy",e)}async listUserPolicies(e){let t=await this.request("ListUserPolicies",e),s=l(t,"PolicyNames","member"),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:a,Marker:i}}async putGroupPolicy(e){await this.request("PutGroupPolicy",e)}async getGroupPolicy(e){let t=await this.request("GetGroupPolicy",e);return{GroupName:r(t,"GroupName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteGroupPolicy(e){await this.request("DeleteGroupPolicy",e)}async listGroupPolicies(e){let t=await this.request("ListGroupPolicies",e),s=l(t,"PolicyNames","member"),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:a,Marker:i}}async putRolePolicy(e){await this.request("PutRolePolicy",e)}async getRolePolicy(e){let t=await this.request("GetRolePolicy",e);return{RoleName:r(t,"RoleName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteRolePolicy(e){await this.request("DeleteRolePolicy",e)}async listRolePolicies(e){let t=await this.request("ListRolePolicies",e),s=l(t,"PolicyNames","member"),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:a,Marker:i}}async createAccessKey(e={}){let t=await this.request("CreateAccessKey",e);if(typeof t==="object"){let s=t?.CreateAccessKeyResult?.AccessKey||t?.AccessKey;if(s)return{AccessKey:{UserName:s.UserName||"",AccessKeyId:s.AccessKeyId||"",Status:s.Status||"Active",SecretAccessKey:s.SecretAccessKey||"",CreateDate:s.CreateDate}}}return{AccessKey:{UserName:r(t,"UserName")||"",AccessKeyId:r(t,"AccessKeyId")||"",Status:r(t,"Status")||"Active",SecretAccessKey:r(t,"SecretAccessKey")||"",CreateDate:r(t,"CreateDate")}}}async listAccessKeys(e={}){let t=await this.request("ListAccessKeys",e),s=this.parseAccessKeys(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AccessKeyMetadata:s,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:r(t,"UserName")||"",AccessKeyLastUsed:{LastUsedDate:r(t,"LastUsedDate"),ServiceName:r(t,"ServiceName"),Region:r(t,"Region")}}}parseAccessKeys(e){return l(e,"AccessKeyMetadata","member").map((s)=>({UserName:r(s,"UserName"),AccessKeyId:r(s,"AccessKeyId")||"",Status:r(s,"Status")||"Active",CreateDate:r(s,"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),s=this.parseInstanceProfiles(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{InstanceProfiles:s,IsTruncated:a,Marker:i}}async listInstanceProfilesForRole(e){let t=await this.request("ListInstanceProfilesForRole",e),s=this.parseInstanceProfiles(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{InstanceProfiles:s,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:r(e,"InstanceProfileName")||"",InstanceProfileId:r(e,"InstanceProfileId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate")}}parseInstanceProfiles(e){return l(e,"InstanceProfiles","member").map((s)=>({InstanceProfileName:r(s,"InstanceProfileName")||"",InstanceProfileId:r(s,"InstanceProfileId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate")}))}async getAccountPasswordPolicy(){let e=await this.request("GetAccountPasswordPolicy");return{MinimumPasswordLength:r(e,"MinimumPasswordLength")?Number.parseInt(r(e,"MinimumPasswordLength"),10):void 0,RequireSymbols:r(e,"RequireSymbols")==="true",RequireNumbers:r(e,"RequireNumbers")==="true",RequireUppercaseCharacters:r(e,"RequireUppercaseCharacters")==="true",RequireLowercaseCharacters:r(e,"RequireLowercaseCharacters")==="true",AllowUsersToChangePassword:r(e,"AllowUsersToChangePassword")==="true",ExpirePasswords:r(e,"ExpirePasswords")==="true",MaxPasswordAge:r(e,"MaxPasswordAge")?Number.parseInt(r(e,"MaxPasswordAge"),10):void 0,PasswordReusePrevention:r(e,"PasswordReusePrevention")?Number.parseInt(r(e,"PasswordReusePrevention"),10):void 0,HardExpiry:r(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={},s=l(e,"SummaryMap","entry");for(let a of s){let i=r(a,"key"),c=r(a,"value");if(i&&c)t[i]=Number.parseInt(c,10)}return t}async listAccountAliases(){let e=await this.request("ListAccountAliases"),t=l(e,"AccountAliases","member"),s=r(e,"IsTruncated")==="true",a=r(e,"Marker");return{AccountAliases:t,IsTruncated:s,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 s=l(e,"EvaluationResults","member").map((c)=>{let d=l(c,"MatchedStatements","member").map((m)=>({SourcePolicyId:r(m,"SourcePolicyId"),SourcePolicyType:r(m,"SourcePolicyType")}));return{EvalActionName:r(c,"EvalActionName")||"",EvalResourceName:r(c,"EvalResourceName"),EvalDecision:r(c,"EvalDecision")||"",MatchedStatements:d.length>0?d:void 0}}),a=r(e,"IsTruncated")==="true",i=r(e,"Marker");return{EvaluationResults:s,IsTruncated:a,Marker:i}}}class tt{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new n(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",s=[];if(e?.PageSize)s.push(`PageSize=${e.PageSize}`);if(e?.NextToken)s.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(s.length>0)t+=`?${s.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",s=[];if(e?.PageSize)s.push(`PageSize=${e.PageSize}`);if(e?.NextToken)s.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(s.length>0)t+=`?${s.join("&")}`;return await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}})}async getSendStatistics(){return{SendDataPoints:(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"})).GetSendStatisticsResponse?.GetSendStatisticsResult?.SendDataPoints?.member}}async getSendQuota(){let t=(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"})).GetSendQuotaResponse?.GetSendQuotaResult;return{Max24HourSend:t?.Max24HourSend?Number(t.Max24HourSend):void 0,MaxSendRate:t?.MaxSendRate?Number(t.MaxSendRate):void 0,SentLast24Hours:t?.SentLast24Hours?Number(t.SentLast24Hours):void 0}}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],s=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:s})}async sendTemplatedEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],s=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:s})}async getDkimRecords(e){let t=await this.getEmailIdentity(e);if(!t.DkimAttributes?.Tokens)return[];return t.DkimAttributes.Tokens.map((s)=>({name:`${s}._domainkey.${e}`,type:"CNAME",value:`${s}.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,s=30000){for(let a=0;a<t;a++){if(await this.isDomainVerified(e))return!0;await new Promise((c)=>setTimeout(c,s))}return!1}buildFormBody(e){return Object.entries(e).filter(([,s])=>s!==void 0).map(([s,a])=>`${encodeURIComponent(s)}=${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 s=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=s?.ListReceiptRuleSetsResponse?.ListReceiptRuleSetsResult||s?.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})}),s=t?.DescribeReceiptRuleSetResponse?.DescribeReceiptRuleSetResult||t?.DescribeReceiptRuleSetResult,a=s?.Rules?.member;return{Metadata:s?.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((s,a)=>{t[`Rule.Recipients.member.${a+1}`]=s});e.Rule.Actions.forEach((s,a)=>{let i=a+1;if(s.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=s.S3Action.BucketName,s.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=s.S3Action.ObjectKeyPrefix;if(s.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=s.S3Action.KmsKeyArn}if(s.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=s.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=s.LambdaAction.InvocationType||"Event";if(s.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=s.SNSAction.TopicArn,s.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=s.SNSAction.Encoding}if(s.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=s.StopAction.Scope,s.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=s.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 s=t?.Rules?.member;return{Metadata:t?.Metadata,Rules:Array.isArray(s)?s:s?[s]:[]}}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((s,a)=>{t[`Rule.Recipients.member.${a+1}`]=s});e.Rule.Actions.forEach((s,a)=>{let i=a+1;if(s.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=s.S3Action.BucketName,s.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=s.S3Action.ObjectKeyPrefix;if(s.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=s.S3Action.KmsKeyArn}if(s.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=s.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=s.LambdaAction.InvocationType||"Event";if(s.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=s.SNSAction.TopicArn,s.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=s.SNSAction.Encoding}if(s.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=s.StopAction.Scope,s.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=s.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"),s={Action:"SendRawEmail",Version:"2010-12-01",Source:e.source,"RawMessage.Data":t};e.destinations.forEach((c,u)=>{s[`Destinations.member.${u+1}`]=c});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(s)});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 Sn{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 tt(this.region),this.s3=new o(this.region),this.iam=new fe(this.region),this.route53=new y(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 s=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:s,to:a,subject:e.subject,text:e.text,html:e.html,replyTo:e.replyTo})).MessageId||""};let i=this.buildRawEmail(e,s,a);return{messageId:(await this.ses.sendEmail({FromEmailAddress:s,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 s=e.fromName?`${e.fromName} <${t}>`:t;return{messageId:(await this.ses.sendTemplatedEmail({from:s,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 s=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:s,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 s=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=[],s=await this.ses.getDkimRecords(e);for(let a of s)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 s=[{S3Action:{BucketName:e.bucketName,ObjectKeyPrefix:e.prefix||"inbox/"}}];if(e.lambdaArn)s.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:s}})}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:s}});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((s)=>({key:s.Key||"",lastModified:s.LastModified||"",size:s.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:s}=await import("./chunk-6kcmbymp.js"),a=new s,i=(g,P)=>{let A={Action:g,Version:"2010-05-08",...P};return Object.entries(A).map(([h,R])=>`${encodeURIComponent(h)}=${encodeURIComponent(R)}`).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(g){if(!g.message?.includes("EntityAlreadyExists"))throw g}let c={Version:"2012-10-17",Statement:[{Effect:"Allow",Action:"ses:SendRawEmail",Resource:"*",Condition:{StringLike:{"ses:FromAddress":`*@${e.domain}`}}}]},u=`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:u,PolicyDocument:JSON.stringify(c)})})}catch{}let m=(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(!m?.AccessKeyId||!m?.SecretAccessKey)throw Error("Failed to create access key");let p=this.deriveSmtpPassword(m.SecretAccessKey);return{username:m.AccessKeyId,password:p,server:`email-smtp.${this.region}.amazonaws.com`,port:587}}deriveSmtpPassword(e){let t=Fe("node:crypto"),s="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`,s=`${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((m)=>m.Name===a))await this.s3.createBucket(a);await this.setupReceiving({domain:e.domain,ruleSetName:t,ruleName:s,bucketName:a,prefix:e.storage?.prefix||"inbox/",accountId:e.accountId,recipients:e.catchAll?[e.domain]:e.mailboxes,scanEnabled:!0});let d=await this.getDnsRecords(e.domain);return{success:!0,domainVerified:i.domainVerified,dkimStatus:i.dkimStatus,receiptRuleSet:t,storageBucket:a,dnsRecords:d}}async undeploy(e){let t=`${e.appName}-${e.environment}-email-rules`,s=`${e.appName}-inbound-email`,a=`${e.appName}-${e.environment}-email`;try{await this.ses.deleteReceiptRule(t,s)}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,s){let a=`----=_Part_${Date.now()}_${Math.random().toString(36).substring(2)}`,i="";if(i+=`From: ${t}\r
|
|
2
2
|
`,i+=`To: ${s.join(", ")}\r
|
|
3
3
|
`,e.cc){let c=Array.isArray(e.cc)?e.cc:[e.cc];i+=`Cc: ${c.join(", ")}\r
|
|
4
4
|
`}if(i+=`Subject: ${e.subject}\r
|
|
5
5
|
`,i+=`MIME-Version: 1.0\r
|
|
6
|
-
`,i+=`Content-Type: multipart/mixed; boundary="${
|
|
6
|
+
`,i+=`Content-Type: multipart/mixed; boundary="${a}"\r
|
|
7
7
|
`,i+=`\r
|
|
8
|
-
`,e.text||e.html)if(i+=`--${
|
|
8
|
+
`,e.text||e.html)if(i+=`--${a}\r
|
|
9
9
|
`,e.html&&e.text){let c=`----=_Alt_${Date.now()}`;i+=`Content-Type: multipart/alternative; boundary="${c}"\r
|
|
10
10
|
`,i+=`\r
|
|
11
11
|
`,i+=`--${c}\r
|
|
@@ -23,12 +23,12 @@ import{n}from"./chunk-ss4q8kge.js";import{a}from"./chunk-z87dekhm.js";import{y}f
|
|
|
23
23
|
`;else i+=`Content-Type: text/plain; charset="UTF-8"\r
|
|
24
24
|
`,i+=`\r
|
|
25
25
|
`,i+=`${e.text}\r
|
|
26
|
-
`;if(e.attachments)for(let c of e.attachments)i+=`--${
|
|
26
|
+
`;if(e.attachments)for(let c of e.attachments)i+=`--${a}\r
|
|
27
27
|
`,i+=`Content-Type: ${c.contentType||"application/octet-stream"}; name="${c.filename}"\r
|
|
28
28
|
`,i+=`Content-Transfer-Encoding: base64\r
|
|
29
29
|
`,i+=`Content-Disposition: attachment; filename="${c.filename}"\r
|
|
30
30
|
`,i+=`\r
|
|
31
31
|
`,i+=`${c.content}\r
|
|
32
|
-
`;return i+=`--${
|
|
33
|
-
`,i}}var
|
|
34
|
-
export{fe,
|
|
32
|
+
`;return i+=`--${a}--\r
|
|
33
|
+
`,i}}var Dh=new Sn;
|
|
34
|
+
export{fe,tt,Sn,Dh};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{j}from"./chunk-k53agv2m.js";import"./chunk-zx8ecz8b.js";export{j as RDSClient};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{$r}from"./chunk-g6g33pt9.js";var Vd="\x00";function Eo(t,i){if(t==="*"||t==="**")return!0;let e=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*");return new RegExp(`^${e}$`).test(i)}function f(t,i){if(t.startsWith("*.")){let e=t.slice(1);return i.endsWith(e)&&i.length>e.length}return t===i}function Ni(t,i){if(t.enabled===!1)return!1;if(t.methods?.length&&!t.methods.some((e)=>e.toUpperCase()===i.method.toUpperCase()))return!1;if(t.path&&!Eo(t.path,i.path))return!1;if(t.host&&!f(t.host,i.host??""))return!1;return!0}function ki(t,i){let e=t.key??{source:"ip"},o=e.fallbackToIp!==!1,r;if(e.source==="ip")r=i.ip;else if(e.source==="global")r="global";else if(e.source==="host")r=i.host??"";else if(e.source==="path")r=i.path;else if(e.source==="header")r=e.name?i.headers?.[e.name.toLowerCase()]:void 0;else if(e.source==="cookie")r=e.name?i.cookies?.[e.name]:void 0;if(!r&&e.source!=="global")r=o?i.ip:"__missing__";return`${t.id}\x00${r}`}class bo{clock;maxTrackedKeys;buckets=new Map;windows=new Map;rules;constructor(t,i=()=>Date.now(),e=1e5){this.clock=i;this.maxTrackedKeys=e;this.rules=[...t].sort((o,r)=>(o.priority??0)-(r.priority??0))}check(t){let i=this.clock(),e=this.rules.filter((n)=>Ni(n,t)),o;for(let n of e){let s=this.test(n,t,i);if(s.allowed)continue;if(!o||d(s.action)>d(o.action))o=s}if(o)return o;let r={action:"allow",allowed:!0};for(let n of e){let s=this.consume(n,t,i);if(s.remaining!=null&&(r.remaining??1/0)>s.remaining)r=s}return r}test(t,i,e){let o=ki(t,i);if((t.algorithm??"token_bucket")==="token_bucket"){let n=t.burst??t.limit,s=this.buckets.get(o),a=s?Math.min(n,s.tokens+this.refill(t,e-s.updatedAt)):n;if(a>=1)return{action:"allow",allowed:!0};return this.blocked(t,o,0,this.msPerToken(t)*(1-a),e)}let r=(this.windows.get(o)?.hits??[]).filter((n)=>n>e-t.windowMs);if(r.length<t.limit)return{action:"allow",allowed:!0};return this.blocked(t,o,0,r[0]+t.windowMs-e,e)}peek(t){let i=this.clock();for(let e of this.rules){if(!Ni(e,t))continue;let o=this.test(e,t,i);if(!o.allowed)return o}return{action:"allow",allowed:!0}}msPerToken(t){return t.windowMs/Math.max(1,t.limit)}refill(t,i){return Math.max(0,i)/this.msPerToken(t)}blocked(t,i,e,o,r){let n=t.action??"deny";return{action:n,allowed:n==="allow"||n==="log",ruleId:t.id,limit:t.limit,remaining:e,retryAfterMs:Math.max(0,Math.ceil(o)),resetAt:r+Math.max(0,o),key:i}}consume(t,i,e){let o=ki(t,i);if((t.algorithm??"token_bucket")==="token_bucket"){let l=t.burst??t.limit,u=this.buckets.get(o)??{tokens:l,updatedAt:e},c=Math.min(l,u.tokens+this.refill(t,e-u.updatedAt));if(c<1)return this.buckets.set(o,{tokens:c,updatedAt:e}),this.blocked(t,o,0,this.msPerToken(t)*(1-c),e);return this.evictIfNeeded(this.buckets),this.buckets.set(o,{tokens:c-1,updatedAt:e}),{action:"allow",allowed:!0,ruleId:t.id,limit:l,remaining:Math.floor(c-1),resetAt:e+this.msPerToken(t)*(l-(c-1)),key:o}}let n=this.windows.get(o)??{hits:[]},s=e-t.windowMs,a=n.hits.filter((l)=>l>s);if(a.length>=t.limit)return this.windows.set(o,{hits:a}),this.blocked(t,o,0,a[0]+t.windowMs-e,e);return a.push(e),this.evictIfNeeded(this.windows),this.windows.set(o,{hits:a}),{action:"allow",allowed:!0,ruleId:t.id,limit:t.limit,remaining:t.limit-a.length,resetAt:a[0]+t.windowMs,key:o}}evictIfNeeded(t){if(t.size<this.maxTrackedKeys)return;let i=t.size-this.maxTrackedKeys+1,e=0;for(let o of t.keys())if(t.delete(o),++e>=i)break}sweep(){let t=this.clock(),i=0;for(let[e,o]of this.windows){let r=e.split("\x00")[0],n=this.rules.find((s)=>s.id===r);if(!n){this.windows.delete(e),i++;continue}if(o.hits.every((s)=>s<=t-n.windowMs))this.windows.delete(e),i++}for(let[e,o]of this.buckets){let r=e.split("\x00")[0],n=this.rules.find((s)=>s.id===r);if(!n||t-o.updatedAt>n.windowMs*2)this.buckets.delete(e),i++}return i}get trackedKeys(){return this.buckets.size+this.windows.size}}function d(t){return{allow:0,log:1,throttle:2,challenge:3,deny:4}[t]}function jd(t){let i={};if(t.limit!=null)i["ratelimit-limit"]=String(t.limit);if(t.remaining!=null)i["ratelimit-remaining"]=String(t.remaining);if(t.resetAt!=null)i["ratelimit-reset"]=String(Math.max(0,Math.ceil((t.resetAt-Date.now())/1000)));if(!t.allowed&&t.retryAfterMs!=null)i["retry-after"]=String(Math.max(1,Math.ceil(t.retryAfterMs/1000)));return i}function zd(){return[{id:"global-ip",limit:600,windowMs:60000,burst:100,key:{source:"ip"},action:"deny",priority:100},{id:"api-ip",limit:120,windowMs:60000,burst:30,path:"/api/**",key:{source:"ip"},action:"deny",priority:50},{id:"auth-ip",limit:10,windowMs:60000,algorithm:"sliding_window",path:"/auth/**",methods:["POST"],key:{source:"ip"},action:"challenge",priority:10}]}var Kd="protection.controls",Bi=24,vo=4,g={ipRules:{allow:[],block:[]}};function m(t,i){if(!t?.enabled)return;return new Date(t.expiresAt).getTime()>i.getTime()?t:void 0}function p(t,i){let e=Number.isFinite(t)?Number(t):i;return Math.min(Bi,Math.max(0.25,e))}var h=500;class To{controlPlane;options;constructor(t,i={}){this.controlPlane=t;this.options=i}now(){return this.options.now?.()??new Date}read(){let t=this.controlPlane.getSetting(Kd);if(!t||typeof t!=="object"||Array.isArray(t))return{...g,ipRules:{allow:[],block:[]}};let i=t;return{attackMode:i.attackMode,mitigationPause:i.mitigationPause,ipRules:{allow:Array.isArray(i.ipRules?.allow)?i.ipRules.allow:[],block:Array.isArray(i.ipRules?.block)?i.ipRules.block:[]},updatedAt:i.updatedAt}}write(t){let i={...t,updatedAt:this.now().toISOString()};return this.controlPlane.setSetting(Kd,i),i}raw(){return this.read()}current(){let t=this.now(),i=this.read();return{attackMode:m(i.attackMode,t),mitigationPause:m(i.mitigationPause,t),ipRules:i.ipRules}}enableAttackMode(t){let i=this.now(),e={enabled:!0,startedAt:i.toISOString(),expiresAt:new Date(i.getTime()+p(t.hours,vo)*3600000).toISOString(),reason:t.reason.trim()||"Attack mode enabled by an operator.",actorId:t.actorId};return this.write({...this.read(),attackMode:e}),e}disableAttackMode(){let t=this.read();if(!t.attackMode?.enabled)return!1;return this.write({...t,attackMode:{...t.attackMode,enabled:!1}}),!0}pauseMitigations(t){let i=t.reason.trim();if(!i)throw Error("Pausing mitigations requires a reason: you are liable for the traffic it admits.");let e=this.now(),o={enabled:!0,startedAt:e.toISOString(),expiresAt:new Date(e.getTime()+p(t.hours,Bi)*3600000).toISOString(),reason:i,actorId:t.actorId};return this.write({...this.read(),mitigationPause:o}),o}resumeMitigations(){let t=this.read();if(!t.mitigationPause?.enabled)return!1;return this.write({...t,mitigationPause:{...t.mitigationPause,enabled:!1}}),!0}addIpRule(t,i){let e=i.trim();if(!$r(e))throw Error(`Not a valid IP or CIDR: ${i}`);let o=this.read(),r={...o.ipRules,[t]:[...new Set([...o.ipRules[t],e])]};if(r[t].length>h)throw Error(`At most ${h} ${t} rules are supported.`);let n=t==="allow"?"block":"allow";return r[n]=r[n].filter((s)=>s!==e),this.write({...o,ipRules:r}),r}removeIpRule(t,i){let e=this.read(),o={...e.ipRules,[t]:e.ipRules[t].filter((r)=>r!==i.trim())};return this.write({...e,ipRules:o}),o}}function Wd(t){if(t.mitigationPause)return{attackMode:!!t.attackMode,mitigationPaused:!0,summary:`Automatic mitigation is paused until ${t.mitigationPause.expiresAt}. All traffic is being served and billed.`,expiresAt:t.mitigationPause.expiresAt};if(t.attackMode)return{attackMode:!0,mitigationPaused:!1,summary:`Attack mode is on until ${t.attackMode.expiresAt}. Every visitor is being challenged.`,expiresAt:t.attackMode.expiresAt};return{attackMode:!1,mitigationPaused:!1,summary:"Protection is in its normal posture."}}function Jd(t,i){if(i.mitigationPause)return t.map((e)=>({...e,enabled:!1}));if(!i.attackMode)return[...t];return t.map((e)=>({...e,action:e.action==="deny"?"deny":"challenge",burst:Math.max(1,Math.min(e.burst??e.limit,5))}))}function wo(t,i){let e=[...new Set([...t.allowlist??[],...i.ipRules.allow])],o=[...new Set([...t.blocklist??[],...i.ipRules.block])];if(i.mitigationPause)return{...t,allowlist:e,blocklist:o,monitorOnly:!0};if(!i.attackMode)return{...t,allowlist:e,blocklist:o};let r=t.thresholds??{};return{...t,allowlist:e,blocklist:o,thresholds:{...r,newConnectionsPerSecond:Math.max(1,Math.floor((r.newConnectionsPerSecond??50)/5)),concurrentPerSource:Math.max(1,Math.floor((r.concurrentPerSource??100)/5))}}}function oy(t,i){let e=t?.infrastructure?.compute;if(!e||e.ddos===!1)return t;let o=typeof e.ddos==="object"&&e.ddos!==null?e.ddos:{};return{...t,infrastructure:{...t.infrastructure,compute:{...e,ddos:wo(o,i)}}}}export{Vd,Eo,Ni,ki,bo,jd,zd,Kd,Bi,vo,To,Wd,Jd,wo,oy};
|