@stacksjs/ts-cloud 0.16.21 → 0.16.23
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/elasticache.d.ts +11 -9
- package/dist/aws/index.js +1 -1
- package/dist/aws/xml-result.d.ts +20 -0
- package/dist/bin/{chunk-k7wh1wr5.js → chunk-0d98bem8.js} +2 -2
- package/dist/bin/chunk-0r45d0s3.js +2 -0
- package/dist/{chunk-g6g33pt9.js → bin/chunk-21zhm1mk.js} +7 -7
- package/dist/bin/chunk-2g1j00yc.js +1 -0
- package/dist/bin/{chunk-6kx50dyc.js → chunk-2tk8egg8.js} +1 -1
- package/dist/bin/{chunk-90102shh.js → chunk-33e0t7e5.js} +2 -2
- package/dist/bin/{chunk-ngyqqy6d.js → chunk-34kwhmbt.js} +5 -5
- package/dist/bin/chunk-4xmhrvfa.js +1 -0
- package/dist/bin/{chunk-gfr2215x.js → chunk-65rndjtr.js} +63 -63
- package/dist/bin/{chunk-t10e32an.js → chunk-6cfpdb35.js} +7 -7
- package/dist/bin/chunk-6crapvp1.js +1 -0
- package/dist/bin/chunk-7b4gf64x.js +1 -0
- package/dist/bin/chunk-818tj49e.js +1 -0
- package/dist/bin/{chunk-9vmtm7nq.js → chunk-8vm7tpyv.js} +2 -2
- package/dist/bin/{chunk-e24bscb0.js → chunk-90kpnjdm.js} +16 -16
- package/dist/bin/chunk-92qsww97.js +1 -0
- package/dist/bin/chunk-9947rscj.js +1 -0
- package/dist/bin/{chunk-2mv692y4.js → chunk-9h7yjtz2.js} +5 -5
- package/dist/bin/{chunk-tq172j2x.js → chunk-btr6zq53.js} +3 -3
- package/dist/bin/chunk-cas0bp91.js +2 -0
- package/dist/bin/{chunk-6wqjk007.js → chunk-cpwk0pbg.js} +134 -134
- package/dist/bin/chunk-cyap08qg.js +1 -0
- package/dist/bin/chunk-dk92s260.js +1 -0
- package/dist/bin/chunk-ejxp74ks.js +1 -0
- package/dist/bin/{chunk-dyh0vndw.js → chunk-en7sf83z.js} +4 -4
- package/dist/bin/{chunk-djjj62c0.js → chunk-f2yhthd1.js} +2 -2
- package/dist/bin/{chunk-z1dtdw3j.js → chunk-f3sd1hpa.js} +5 -5
- package/dist/bin/chunk-gfwkmttt.js +1 -0
- package/dist/bin/chunk-gx98tkpf.js +1 -0
- package/dist/bin/{chunk-apnhhfkj.js → chunk-gzpwf3n4.js} +2 -2
- package/dist/bin/{chunk-dmdg23a5.js → chunk-h90azajz.js} +2 -2
- package/dist/bin/chunk-hcdbw9j1.js +1 -0
- package/dist/bin/chunk-hdsgfgnz.js +34 -0
- package/dist/bin/{chunk-1j8b1d58.js → chunk-hqmkfh4a.js} +2 -2
- package/dist/bin/{chunk-x63yz8xg.js → chunk-ht318ydv.js} +1 -1
- package/dist/bin/{chunk-h1rb8qvt.js → chunk-ht6tpmqw.js} +2 -2
- package/dist/bin/{chunk-e55fdn0r.js → chunk-j0zg3mbm.js} +3 -3
- package/dist/bin/{chunk-0f1qpmd6.js → chunk-jbpkwxht.js} +5 -5
- package/dist/bin/{chunk-5a7sxtwn.js → chunk-jtnv8nwz.js} +2 -2
- package/dist/bin/{chunk-ys5n5c84.js → chunk-k052rtd5.js} +5 -5
- package/dist/bin/{chunk-148x1zq8.js → chunk-k1eezsj1.js} +2 -2
- package/dist/bin/chunk-kay11qc7.js +1 -0
- package/dist/bin/chunk-n28a9a9c.js +1 -0
- package/dist/bin/chunk-n298azax.js +2 -0
- package/dist/bin/chunk-q8w7fa56.js +1 -0
- package/dist/bin/chunk-qdnx952p.js +1 -0
- package/dist/bin/chunk-t1jpqn4x.js +6 -0
- package/dist/bin/chunk-tr0pkm4p.js +1 -0
- package/dist/bin/{chunk-mxvekmdx.js → chunk-tyqxz92e.js} +114 -114
- package/dist/bin/chunk-tytvrehe.js +1 -0
- package/dist/bin/{chunk-3n733cgx.js → chunk-v002yxaf.js} +2 -2
- package/dist/bin/chunk-wpp0fa94.js +1 -0
- package/dist/bin/{chunk-0trtkv9g.js → chunk-wyanqf91.js} +7 -7
- package/dist/bin/{chunk-rbtt23vx.js → chunk-xs6afjat.js} +3 -3
- package/dist/bin/chunk-xzgxwnb7.js +1 -0
- package/dist/bin/chunk-y21yk6zv.js +1 -0
- package/dist/bin/chunk-yt1t5ct8.js +1 -0
- package/dist/bin/chunk-yxyvhqhr.js +2 -0
- package/dist/bin/{chunk-290bzm2m.js → chunk-zcabmq4p.js} +3 -3
- package/dist/bin/chunk-zs8ddeaz.js +1 -0
- package/dist/bin/cli.js +355 -355
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/{chunk-k53agv2m.js → chunk-01rbgche.js} +2 -2
- package/dist/{chunk-3m9ghthh.js → chunk-14zcywnp.js} +2 -2
- package/dist/chunk-2hy7ny4k.js +5 -0
- package/dist/{chunk-aw1tp3p3.js → chunk-4apkvhsc.js} +88 -88
- package/dist/chunk-4rb7stp5.js +92 -0
- package/dist/chunk-5vxpgw8q.js +6 -0
- package/dist/{chunk-bxrzsth8.js → chunk-60fn008g.js} +2 -2
- package/dist/{chunk-z3wynefj.js → chunk-92gn9ght.js} +19 -19
- package/dist/{chunk-hyeeqga9.js → chunk-b5xjjz3y.js} +6 -6
- package/dist/{chunk-e52me1c6.js → chunk-bz1hp7es.js} +1 -1
- package/dist/{chunk-kczzc599.js → chunk-c836kdrx.js} +38 -38
- package/dist/{chunk-srrscggm.js → chunk-ckwdjb5q.js} +5 -5
- package/dist/chunk-cpyrhh52.js +709 -0
- package/dist/chunk-cwgy9pvc.js +34 -0
- package/dist/{chunk-v2p7c7s4.js → chunk-ds2v2xpb.js} +134 -134
- package/dist/chunk-e4qh4c2n.js +1 -0
- package/dist/{chunk-vs0qrm09.js → chunk-g6aev693.js} +1 -1
- package/dist/chunk-gm0qysea.js +114 -0
- package/dist/chunk-hpq0rrve.js +2 -0
- package/dist/{chunk-5far81q7.js → chunk-j2w0cvnr.js} +2 -2
- package/dist/{chunk-31tvc877.js → chunk-nfkdgsgh.js} +18 -18
- package/dist/{chunk-qcaqc5b8.js → chunk-pdmfmsm9.js} +3 -3
- package/dist/chunk-pj9z4fjv.js +1 -0
- package/dist/{chunk-w9jhyy09.js → chunk-rq0wrpz6.js} +4 -4
- package/dist/{chunk-9wmer0zx.js → chunk-t7q4awss.js} +2 -2
- package/dist/chunk-twhbns31.js +1 -0
- package/dist/chunk-wkg22nj5.js +1 -0
- package/dist/{bin/chunk-8jbkphmg.js → chunk-xassxhvq.js} +7 -7
- package/dist/{chunk-e8e1h2h9.js → chunk-xkqx98bx.js} +2 -2
- package/dist/chunk-xtd0s5ep.js +1 -0
- package/dist/deploy/index.js +1 -1
- package/dist/dns/index.js +1 -1
- package/dist/drivers/index.js +1 -1
- package/dist/index.js +86 -86
- package/dist/operations/index.js +1 -1
- package/dist/protection/index.js +1 -1
- package/dist/spend/index.js +1 -1
- package/dist/ui/404.html +1 -1
- package/dist/ui/accept-invitation.html +1 -1
- package/dist/ui/access-denied.html +1 -1
- package/dist/ui/account/automation.html +5 -5
- package/dist/ui/account/security.html +2 -2
- package/dist/ui/applications/compose.html +6 -6
- package/dist/ui/applications/new.html +2 -2
- package/dist/ui/data/backups.html +5 -5
- package/dist/ui/data/services.html +6 -6
- package/dist/ui/data/volumes.html +6 -6
- package/dist/ui/index.html +6 -6
- package/dist/ui/infrastructure/topology.html +6 -6
- package/dist/ui/integrations.html +2 -2
- package/dist/ui/operations/alerts.html +6 -6
- package/dist/ui/operations/configuration.html +6 -6
- package/dist/ui/operations/jobs.html +6 -6
- package/dist/ui/operations/maintenance.html +5 -5
- package/dist/ui/operations/observability.html +6 -6
- package/dist/ui/operations/previews.html +6 -6
- package/dist/ui/operations/queue.html +6 -6
- package/dist/ui/operations/regions.html +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 +2 -2
- package/dist/ui/server/actions.html +6 -6
- package/dist/ui/server/activity.html +2 -2
- package/dist/ui/server/capacity.html +6 -6
- package/dist/ui/server/database.html +6 -6
- package/dist/ui/server/deployments.html +6 -6
- package/dist/ui/server/diagnostics.html +2 -2
- package/dist/ui/server/firewall.html +6 -6
- package/dist/ui/server/fleet.html +6 -6
- package/dist/ui/server/logs.html +6 -6
- package/dist/ui/server/metrics.html +6 -6
- package/dist/ui/server/security.html +2 -2
- package/dist/ui/server/services.html +2 -2
- package/dist/ui/server/sites.html +6 -6
- package/dist/ui/server/ssh-keys.html +5 -5
- package/dist/ui/server/team.html +6 -6
- package/dist/ui/server/terminal.html +2 -2
- package/dist/ui/serverless/alarms.html +6 -6
- package/dist/ui/serverless/assets.html +2 -2
- package/dist/ui/serverless/cost.html +2 -2
- package/dist/ui/serverless/data.html +6 -6
- package/dist/ui/serverless/deployments.html +2 -2
- package/dist/ui/serverless/firewall.html +1 -1
- package/dist/ui/serverless/functions.html +6 -6
- package/dist/ui/serverless/logs.html +6 -6
- package/dist/ui/serverless/metrics.html +2 -2
- package/dist/ui/serverless/queues.html +6 -6
- package/dist/ui/serverless/secrets.html +6 -6
- package/dist/ui/serverless/traces.html +6 -6
- package/dist/ui/serverless.html +6 -6
- package/package.json +3 -3
- package/dist/bin/chunk-0h6cggyt.js +0 -1
- package/dist/bin/chunk-2g2zrtjs.js +0 -2
- package/dist/bin/chunk-35rkh66r.js +0 -1
- package/dist/bin/chunk-4cs098d1.js +0 -1
- package/dist/bin/chunk-52fhq35h.js +0 -1
- package/dist/bin/chunk-6se7ygxa.js +0 -1
- package/dist/bin/chunk-72g1hr4z.js +0 -1
- package/dist/bin/chunk-840arz58.js +0 -34
- package/dist/bin/chunk-c7vxdwth.js +0 -1
- package/dist/bin/chunk-e0c3agf2.js +0 -1
- package/dist/bin/chunk-egn33pr9.js +0 -2
- package/dist/bin/chunk-gf7yavs5.js +0 -1
- package/dist/bin/chunk-gp5w7e4c.js +0 -1
- package/dist/bin/chunk-gt7g41js.js +0 -1
- package/dist/bin/chunk-hagakkgm.js +0 -1
- package/dist/bin/chunk-hr3vbg6y.js +0 -1
- package/dist/bin/chunk-hyb5v8wr.js +0 -1
- package/dist/bin/chunk-mx9ppkmn.js +0 -6
- package/dist/bin/chunk-nqb1faqj.js +0 -1
- package/dist/bin/chunk-p831sptd.js +0 -1
- package/dist/bin/chunk-qxx1a51w.js +0 -1
- package/dist/bin/chunk-sh248v2y.js +0 -1
- package/dist/bin/chunk-swfmx4f8.js +0 -1
- package/dist/bin/chunk-vjkyj3xy.js +0 -2
- package/dist/bin/chunk-w78chy9x.js +0 -1
- package/dist/bin/chunk-w8k1gyzr.js +0 -1
- package/dist/bin/chunk-wagzxm7z.js +0 -1
- package/dist/bin/chunk-xdxk6baf.js +0 -1
- package/dist/bin/chunk-ysv52qcc.js +0 -1
- package/dist/chunk-07rjctzz.js +0 -1
- package/dist/chunk-3rahpgb9.js +0 -709
- package/dist/chunk-49vvjfrd.js +0 -1
- package/dist/chunk-6kcmbymp.js +0 -1
- package/dist/chunk-7xnwa0s8.js +0 -5
- package/dist/chunk-89p8mshq.js +0 -114
- package/dist/chunk-9asn5fpt.js +0 -92
- package/dist/chunk-d46p0h6t.js +0 -34
- package/dist/chunk-dak9hfrd.js +0 -1
- package/dist/chunk-ptq9v346.js +0 -2
- package/dist/chunk-z4xzd43p.js +0 -1
- package/dist/chunk-zx8ecz8b.js +0 -6
package/dist/chunk-9asn5fpt.js
DELETED
|
@@ -1,92 +0,0 @@
|
|
|
1
|
-
import{br,n}from"./chunk-zx8ecz8b.js";import{Fe}from"./chunk-bxrzsth8.js";import*as l from"node:crypto";import{readFileSync as B}from"node:fs";import{readdir as L}from"node:fs/promises";import{join as z}from"node:path";function Bt(e){if(e){let r=D(e);if(!r)throw Error(`AWS profile '${e}' not found in ~/.aws/credentials`);return r}let t=process.env.AWS_ACCESS_KEY_ID,s=process.env.AWS_SECRET_ACCESS_KEY;if(t&&s)return{accessKeyId:t,secretAccessKey:s,sessionToken:process.env.AWS_SESSION_TOKEN};return D(process.env.AWS_PROFILE||"default")??{accessKeyId:"",secretAccessKey:""}}function D(e){let{existsSync:t,readFileSync:s}=Fe("node:fs"),{homedir:r}=Fe("node:os"),{join:i}=Fe("node:path"),a=process.env.AWS_SHARED_CREDENTIALS_FILE||i(r(),".aws","credentials");if(!t(a))return null;let c=s(a,"utf-8"),g=null,d,u,y;for(let h of c.split(`
|
|
2
|
-
`)){let m=h.trim();if(!m||m.startsWith("#")||m.startsWith(";"))continue;let p=m.match(/^\[([^\]]+)\]$/);if(p){if(g===e&&d&&u)return{accessKeyId:d,secretAccessKey:u,sessionToken:y};g=p[1],d=void 0,u=void 0,y=void 0;continue}if(g===e){let[b,...S]=m.split("="),f=S.join("=").trim();switch(b.trim().toLowerCase()){case"aws_access_key_id":d=f;break;case"aws_secret_access_key":u=f;break;case"aws_session_token":y=f;break}}}if(g===e&&d&&u)return{accessKeyId:d,secretAccessKey:u,sessionToken:y};return null}function U(e){let{buffer:t,byteOffset:s,byteLength:r}=e;if(t instanceof ArrayBuffer)return t.slice(s,s+r);let i=new ArrayBuffer(r);return new Uint8Array(i).set(new Uint8Array(e)),i}function j(e,t){let s=e?.[t]??e;if(s===null||typeof s!=="object"||Array.isArray(s))return s;let r={...s};return delete r["@_xmlns"],r}class o{client;region;explicitProfile;endpoint;endpointProtocol="https";forcePathStyle;explicitCredentials;constructor(e="us-east-1",t,s){let r=typeof e==="string"?s:e,i=typeof e==="string"?e:e.region??"us-east-1",a=typeof e==="string"?t:e.profile,c=r?.endpoint?br({region:i,path:"/",endpoint:r.endpoint}):void 0;this.region=i,this.explicitProfile=a,this.endpoint=c?.host,this.endpointProtocol=c?.protocol??"https",this.forcePathStyle=r?.forcePathStyle,this.explicitCredentials=r?.credentials,this.client=new n(r?.credentials,{profile:a,endpoint:r?.endpoint,forcePathStyle:r?.forcePathStyle})}getCredentials(){if(this.explicitCredentials?.accessKeyId&&this.explicitCredentials.secretAccessKey)return this.explicitCredentials;let e=Bt(this.explicitProfile);if(e.accessKeyId&&e.secretAccessKey)return e;throw Error("S3 credentials not found. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY (or pass explicit credentials/profile), or configure ~/.aws/credentials.")}s3BaseHost(){return this.endpoint||`s3.${this.region}.amazonaws.com`}s3VirtualHost(e){return this.forcePathStyle?this.s3BaseHost():`${e}.${this.s3BaseHost()}`}objectPath(e,t){return this.forcePathStyle?`/${e}/${t}`:`/${t}`}objectUrl(e,t){return`${this.endpointProtocol}://${this.s3VirtualHost(e)}${this.objectPath(e,t)}`}async listBuckets(){let e=await this.client.request({service:"s3",region:this.region,method:"GET",path:"/"}),t=[],r=(e?.ListAllMyBucketsResult??e)?.Buckets?.Bucket;if(r){let i=Array.isArray(r)?r:[r];for(let a of i)t.push({Name:a.Name,CreationDate:a.CreationDate})}return{Buckets:t}}async createBucket(e,t){let s={};if(t?.acl)s["x-amz-acl"]=t.acl;let r;if(this.region!=="us-east-1"&&!this.endpoint)r=`<?xml version="1.0" encoding="UTF-8"?>
|
|
3
|
-
<CreateBucketConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
4
|
-
<LocationConstraint>${this.region}</LocationConstraint>
|
|
5
|
-
</CreateBucketConfiguration>`,s["Content-Type"]="application/xml";await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,headers:s,body:r})}async deleteBucket(e){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${e}`})}async emptyAndDeleteBucket(e){let t=!0;while(t){let s=await this.listAllObjects({bucket:e});if(s.length===0){t=!1;break}let r=s.map((i)=>i.Key);for(let i=0;i<r.length;i+=1000){let a=r.slice(i,i+1000);await this.deleteObjects(e,a)}}await this.deleteBucket(e)}async listAllObjects(e){let t=[],s;do{let r={"list-type":"2","max-keys":"1000"};if(e.prefix)r.prefix=e.prefix;if(s)r["continuation-token"]=s;let i=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e.bucket}`,queryParams:r}),a=i?.ListBucketResult??i,c=a?.Contents;if(c){let d=Array.isArray(c)?c:[c];for(let u of d)t.push({Key:u.Key,LastModified:u.LastModified||"",Size:Number.parseInt(u.Size||"0"),ETag:u.ETag})}let g=a?.IsTruncated;s=g==="true"||g===!0?a?.NextContinuationToken:void 0}while(s);return t}async list(e){let t=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e.bucket}`}),s=[],i=(t?.ListBucketResult??t)?.Contents;if(i){let a=Array.isArray(i)?i:[i];for(let c of a){if(e.prefix&&!c.Key?.startsWith(e.prefix))continue;if(s.push({Key:c.Key||"",LastModified:c.LastModified||"",Size:Number.parseInt(c.Size||"0"),ETag:c.ETag}),e.maxKeys&&s.length>=e.maxKeys)break}}return s}async putObject(e){let t={};if(e.acl)t["x-amz-acl"]=e.acl;if(e.cacheControl)t["Cache-Control"]=e.cacheControl;if(e.contentType)t["Content-Type"]=e.contentType;if(e.metadata)for(let[i,a]of Object.entries(e.metadata))t[`x-amz-meta-${i}`]=a;let s=e.key.split("/").map((i)=>encodeURIComponent(i)).join("/"),r=e.body instanceof Uint8Array&&!Buffer.isBuffer(e.body)?Buffer.from(e.body):e.body;if(Buffer.isBuffer(r)||r instanceof Uint8Array){let i=Buffer.isBuffer(r)?r:Buffer.from(r),{accessKeyId:a,secretAccessKey:c,sessionToken:g}=this.getCredentials(),d=this.s3VirtualHost(e.bucket),u=this.objectPath(e.bucket,s),y=this.objectUrl(e.bucket,s),h=new Date,m=h.toISOString().replace(/[:-]|\.\d{3}/g,""),p=h.toISOString().slice(0,10).replace(/-/g,""),b=l.createHash("sha256").update(i).digest("hex"),S={host:d,"x-amz-date":m,"x-amz-content-sha256":b,...t};if(g)S["x-amz-security-token"]=g;let f=Object.keys(S).sort().map((P)=>`${P.toLowerCase()}:${S[P].trim()}
|
|
6
|
-
`).join(""),k=Object.keys(S).sort().map((P)=>P.toLowerCase()).join(";"),T=["PUT",u,"",f,k,b].join(`
|
|
7
|
-
`),w="AWS4-HMAC-SHA256",C=`${p}/${this.region}/s3/aws4_request`,q=[w,m,C,l.createHash("sha256").update(T).digest("hex")].join(`
|
|
8
|
-
`),I=l.createHmac("sha256",`AWS4${c}`).update(p).digest(),K=l.createHmac("sha256",I).update(this.region).digest(),H=l.createHmac("sha256",K).update("s3").digest(),E=l.createHmac("sha256",H).update("aws4_request").digest(),v=l.createHmac("sha256",E).update(q).digest("hex"),A=`${w} Credential=${a}/${C}, SignedHeaders=${k}, Signature=${v}`,x=await fetch(y,{method:"PUT",headers:{...S,Authorization:A},body:U(i)});if(!x.ok){let P=await x.text();throw Error(`S3 PUT failed: ${x.status} ${P}`)}return}await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${s}`,bucket:e.bucket,headers:t,body:e.body})}async getObject(e,t){let s=t.split("/").map((i)=>encodeURIComponent(i)).join("/");return await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${s}`,bucket:e,rawResponse:!0})}async getObjectBytes(e,t){let{accessKeyId:s,secretAccessKey:r,sessionToken:i}=this.getCredentials(),a=this.s3VirtualHost(e),c=t.split("/").map((P)=>encodeURIComponent(P)).join("/"),g=this.objectPath(e,c),d=this.objectUrl(e,c),u=new Date,y=u.toISOString().replace(/[:-]|\.\d{3}/g,""),h=u.toISOString().slice(0,10).replace(/-/g,""),m=l.createHash("sha256").update("").digest("hex"),p={host:a,"x-amz-date":y,"x-amz-content-sha256":m};if(i)p["x-amz-security-token"]=i;let b=Object.keys(p).sort().map((P)=>`${P.toLowerCase()}:${p[P].trim()}
|
|
9
|
-
`).join(""),S=Object.keys(p).sort().map((P)=>P.toLowerCase()).join(";"),f=["GET",g,"",b,S,m].join(`
|
|
10
|
-
`),k="AWS4-HMAC-SHA256",T=`${h}/${this.region}/s3/aws4_request`,w=[k,y,T,l.createHash("sha256").update(f).digest("hex")].join(`
|
|
11
|
-
`),C=l.createHmac("sha256",`AWS4${r}`).update(h).digest(),q=l.createHmac("sha256",C).update(this.region).digest(),I=l.createHmac("sha256",q).update("s3").digest(),K=l.createHmac("sha256",I).update("aws4_request").digest(),H=l.createHmac("sha256",K).update(w).digest("hex"),E=`${k} Credential=${s}/${T}, SignedHeaders=${S}, Signature=${H}`,v=await fetch(d,{method:"GET",headers:{...p,Authorization:E}});if(!v.ok){let P=await v.text();throw Error(`S3 GET failed: ${v.status} ${P}`)}let A=await v.arrayBuffer(),x=v.headers.get("content-length");return{body:new Uint8Array(A),contentType:v.headers.get("content-type")??void 0,contentLength:x?Number.parseInt(x,10):void 0}}async copyObject(e){let t=(r)=>r.split("/").map((i)=>encodeURIComponent(i)).join("/"),s={"x-amz-copy-source":`/${e.sourceBucket}/${t(e.sourceKey)}`};if(e.metadataDirective)s["x-amz-metadata-directive"]=e.metadataDirective;if(e.contentType)s["Content-Type"]=e.contentType;if(e.metadata)for(let[r,i]of Object.entries(e.metadata))s[`x-amz-meta-${r}`]=i;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e.destinationBucket}/${t(e.destinationKey)}`,headers:s})}async deleteObject(e,t){let s=t.split("/").map((r)=>encodeURIComponent(r)).join("/");await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${s}`,bucket:e})}async deleteObjects(e,t){let s=`<?xml version="1.0" encoding="UTF-8"?>
|
|
12
|
-
<Delete>
|
|
13
|
-
${t.map((i)=>`<Object><Key>${i}</Key></Object>`).join(`
|
|
14
|
-
`)}
|
|
15
|
-
</Delete>`,r=l.createHash("md5").update(s).digest("base64");await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${e}`,queryParams:{delete:""},body:s,headers:{"Content-Type":"application/xml","Content-MD5":r}})}async bucketExists(e){try{return await this.client.request({service:"s3",region:this.region,method:"HEAD",path:`/${e}`}),!0}catch{return!1}}async copy(e){let t=B(e.source);await this.putObject({bucket:e.bucket,key:e.key,body:t,acl:e.acl,cacheControl:e.cacheControl,contentType:e.contentType,metadata:e.metadata})}async sync(e){let t=await this.listFilesRecursive(e.source);for(let s of t){if(e.exclude&&e.exclude.some((a)=>s.includes(a)))continue;if(e.include&&!e.include.some((a)=>s.includes(a)))continue;let r=s.substring(e.source.length+1),i=e.prefix?`${e.prefix}/${r}`:r;if(!e.dryRun){let a=B(s);await this.putObject({bucket:e.bucket,key:i,body:a,acl:e.acl,cacheControl:e.cacheControl,contentType:e.contentType,metadata:e.metadata})}}}async delete(e,t){await this.deleteObject(e,t)}async deletePrefix(e,t){let r=(await this.list({bucket:e,prefix:t})).map((i)=>i.Key);if(r.length>0)await this.deleteObjects(e,r)}async getBucketSize(e,t){return(await this.list({bucket:e,prefix:t})).reduce((r,i)=>r+i.Size,0)}async listFilesRecursive(e){let t=[],s=await L(e,{withFileTypes:!0});for(let r of s){let i=z(e,r.name);if(r.isDirectory()){let a=await this.listFilesRecursive(i);t.push(...a)}else t.push(i)}return t}async putBucketPolicy(e,t){let{accessKeyId:s,secretAccessKey:r,sessionToken:i}=this.getCredentials(),a=this.s3BaseHost(),c=typeof t==="string"?t:JSON.stringify(t),g=new Date,d=g.toISOString().replace(/[:-]|\.\d{3}/g,""),u=g.toISOString().slice(0,10).replace(/-/g,""),y=l.createHash("sha256").update(c).digest("hex"),h="/"+e,m="policy=",p={host:a,"x-amz-date":d,"x-amz-content-sha256":y,"content-type":"application/json"};if(i)p["x-amz-security-token"]=i;let b=Object.keys(p).sort().map((x)=>`${x.toLowerCase()}:${p[x].trim()}
|
|
16
|
-
`).join(""),S=Object.keys(p).sort().map((x)=>x.toLowerCase()).join(";"),f=["PUT",h,"policy=",b,S,y].join(`
|
|
17
|
-
`),k="AWS4-HMAC-SHA256",T=`${u}/${this.region}/s3/aws4_request`,w=[k,d,T,l.createHash("sha256").update(f).digest("hex")].join(`
|
|
18
|
-
`),C=l.createHmac("sha256","AWS4"+r).update(u).digest(),q=l.createHmac("sha256",C).update(this.region).digest(),I=l.createHmac("sha256",q).update("s3").digest(),K=l.createHmac("sha256",I).update("aws4_request").digest(),H=l.createHmac("sha256",K).update(w).digest("hex"),E=`${k} Credential=${s}/${T}, SignedHeaders=${S}, Signature=${H}`,v=`${this.endpointProtocol}://${a}${h}?policy=`,A=await fetch(v,{method:"PUT",headers:{...p,Authorization:E},body:c});if(!A.ok){let x=await A.text();throw Error(`Failed to put bucket policy: ${A.status} ${x}`)}}async getBucketPolicy(e){let{accessKeyId:t,secretAccessKey:s,sessionToken:r}=this.getCredentials(),i=this.s3BaseHost(),a=new Date,c=a.toISOString().replace(/[:-]|\.\d{3}/g,""),g=a.toISOString().slice(0,10).replace(/-/g,""),d=l.createHash("sha256").update("").digest("hex"),u="/"+e,y="policy=",h={host:i,"x-amz-date":c,"x-amz-content-sha256":d};if(r)h["x-amz-security-token"]=r;let m=Object.keys(h).sort().map((A)=>`${A.toLowerCase()}:${h[A].trim()}
|
|
19
|
-
`).join(""),p=Object.keys(h).sort().map((A)=>A.toLowerCase()).join(";"),b=["GET",u,"policy=",m,p,d].join(`
|
|
20
|
-
`),S="AWS4-HMAC-SHA256",f=`${g}/${this.region}/s3/aws4_request`,k=[S,c,f,l.createHash("sha256").update(b).digest("hex")].join(`
|
|
21
|
-
`),T=l.createHmac("sha256","AWS4"+s).update(g).digest(),w=l.createHmac("sha256",T).update(this.region).digest(),C=l.createHmac("sha256",w).update("s3").digest(),q=l.createHmac("sha256",C).update("aws4_request").digest(),I=l.createHmac("sha256",q).update(k).digest("hex"),K=`${S} Credential=${t}/${f}, SignedHeaders=${p}, Signature=${I}`,H=`${this.endpointProtocol}://${i}${u}?policy=`,E=await fetch(H,{method:"GET",headers:{...h,Authorization:K}});if(E.status===404)return null;if(!E.ok){let A=await E.text();throw Error(`Failed to get bucket policy: ${E.status} ${A}`)}let v=await E.text();return JSON.parse(v)}async deleteBucketPolicy(e){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${e}`,queryParams:{policy:""}})}async headBucket(e){try{return{exists:!0,region:(await this.client.request({service:"s3",region:this.region,method:"HEAD",path:`/${e}`,returnHeaders:!0}))?.headers?.["x-amz-bucket-region"]}}catch(t){if(t.statusCode===404)return{exists:!1};throw t}}async headObject(e,t){try{let s=await this.client.request({service:"s3",region:this.region,method:"HEAD",path:`/${e}/${t}`,returnHeaders:!0});return{ContentLength:s?.headers?.["content-length"]?parseInt(s.headers["content-length"]):void 0,ContentType:s?.headers?.["content-type"],ETag:s?.headers?.etag,LastModified:s?.headers?.["last-modified"]}}catch(s){if(s.statusCode===404)return null;throw s}}async getObjectBuffer(e,t){let s=await this.getObject(e,t);return Buffer.from(s)}async getObjectJson(e,t){let s=await this.getObject(e,t);return JSON.parse(s)}async putObjectJson(e,t,s,r){await this.putObject({bucket:e,key:t,body:JSON.stringify(s),contentType:"application/json",...r})}async getBucketVersioning(e){let t=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}`,queryParams:{versioning:""}});return{Status:(t?.VersioningConfiguration??t)?.Status}}async putBucketVersioning(e,t){let s=`<?xml version="1.0" encoding="UTF-8"?>
|
|
22
|
-
<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
23
|
-
<Status>${t}</Status>
|
|
24
|
-
</VersioningConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,queryParams:{versioning:""},headers:{"Content-Type":"application/xml"},body:s})}async getBucketLifecycleConfiguration(e){try{let t=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}`,queryParams:{lifecycle:""}});return j(t,"LifecycleConfiguration")}catch(t){if(t.statusCode===404)return null;throw t}}async putBucketLifecycleConfiguration(e,t){let r=`<?xml version="1.0" encoding="UTF-8"?>
|
|
25
|
-
<LifecycleConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
26
|
-
${t.map((i)=>{let a=`<Rule><ID>${i.ID}</ID><Status>${i.Status}</Status>`;if(i.Filter)a+=`<Filter><Prefix>${i.Filter.Prefix||""}</Prefix></Filter>`;else a+="<Filter><Prefix></Prefix></Filter>";if(i.Expiration){if(i.Expiration.Days)a+=`<Expiration><Days>${i.Expiration.Days}</Days></Expiration>`;else if(i.Expiration.Date)a+=`<Expiration><Date>${i.Expiration.Date}</Date></Expiration>`}if(i.Transitions)for(let c of i.Transitions)a+=`<Transition><Days>${c.Days}</Days><StorageClass>${c.StorageClass}</StorageClass></Transition>`;if(i.NoncurrentVersionExpiration)a+=`<NoncurrentVersionExpiration><NoncurrentDays>${i.NoncurrentVersionExpiration.NoncurrentDays}</NoncurrentDays></NoncurrentVersionExpiration>`;return a+="</Rule>",a}).join("")}
|
|
27
|
-
</LifecycleConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,queryParams:{lifecycle:""},headers:{"Content-Type":"application/xml"},body:r})}async deleteBucketLifecycleConfiguration(e){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${e}`,queryParams:{lifecycle:""}})}async getBucketCors(e){try{let t=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}`,queryParams:{cors:""}});return j(t,"CORSConfiguration")}catch(t){if(t.statusCode===404)return null;throw t}}async putBucketCors(e,t){let r=`<?xml version="1.0" encoding="UTF-8"?>
|
|
28
|
-
<CORSConfiguration>
|
|
29
|
-
${t.map((i)=>{let a="<CORSRule>";for(let c of i.AllowedOrigins)a+=`<AllowedOrigin>${c}</AllowedOrigin>`;for(let c of i.AllowedMethods)a+=`<AllowedMethod>${c}</AllowedMethod>`;if(i.AllowedHeaders)for(let c of i.AllowedHeaders)a+=`<AllowedHeader>${c}</AllowedHeader>`;if(i.ExposeHeaders)for(let c of i.ExposeHeaders)a+=`<ExposeHeader>${c}</ExposeHeader>`;if(i.MaxAgeSeconds)a+=`<MaxAgeSeconds>${i.MaxAgeSeconds}</MaxAgeSeconds>`;return a+="</CORSRule>",a}).join("")}
|
|
30
|
-
</CORSConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,queryParams:{cors:""},headers:{"Content-Type":"application/xml"},body:r})}async deleteBucketCors(e){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${e}`,queryParams:{cors:""}})}async getBucketEncryption(e){try{let t=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}`,queryParams:{encryption:""}});return j(t,"ServerSideEncryptionConfiguration")}catch(t){if(t.statusCode===404)return null;throw t}}async putBucketEncryption(e,t,s){let r=`<ApplyServerSideEncryptionByDefault><SSEAlgorithm>${t}</SSEAlgorithm>`;if(s)r+=`<KMSMasterKeyID>${s}</KMSMasterKeyID>`;r+="</ApplyServerSideEncryptionByDefault>";let i=`<?xml version="1.0" encoding="UTF-8"?>
|
|
31
|
-
<ServerSideEncryptionConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
32
|
-
<Rule>${r}</Rule>
|
|
33
|
-
</ServerSideEncryptionConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,queryParams:{encryption:""},headers:{"Content-Type":"application/xml"},body:i})}async deleteBucketEncryption(e){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${e}`,queryParams:{encryption:""}})}async getBucketTagging(e){try{let s=(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}`,queryParams:{tagging:""}}))?.Tagging?.TagSet?.Tag;if(!s)return[];return Array.isArray(s)?s:[s]}catch(t){if(t.statusCode===404)return[];throw t}}async putBucketTagging(e,t){let r=`<?xml version="1.0" encoding="UTF-8"?>
|
|
34
|
-
<Tagging>
|
|
35
|
-
<TagSet>${t.map((i)=>`<Tag><Key>${i.Key}</Key><Value>${i.Value}</Value></Tag>`).join("")}</TagSet>
|
|
36
|
-
</Tagging>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,queryParams:{tagging:""},headers:{"Content-Type":"application/xml"},body:r})}async deleteBucketTagging(e){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${e}`,queryParams:{tagging:""}})}async getObjectTagging(e,t){try{let r=(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}/${t}`,queryParams:{tagging:""}}))?.Tagging?.TagSet?.Tag;if(!r)return[];return Array.isArray(r)?r:[r]}catch(s){if(s.statusCode===404)return[];throw s}}async putObjectTagging(e,t,s){let i=`<?xml version="1.0" encoding="UTF-8"?>
|
|
37
|
-
<Tagging>
|
|
38
|
-
<TagSet>${s.map((a)=>`<Tag><Key>${a.Key}</Key><Value>${a.Value}</Value></Tag>`).join("")}</TagSet>
|
|
39
|
-
</Tagging>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}/${t}`,queryParams:{tagging:""},headers:{"Content-Type":"application/xml"},body:i})}async deleteObjectTagging(e,t){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${e}/${t}`,queryParams:{tagging:""}})}async getBucketAcl(e){let t=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}`,queryParams:{acl:""}});return j(t,"AccessControlPolicy")}async putBucketAcl(e,t){await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,queryParams:{acl:""},headers:{"x-amz-acl":t}})}async getObjectAcl(e,t){let s=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}/${t}`,queryParams:{acl:""}});return j(s,"AccessControlPolicy")}async putObjectAcl(e,t,s){await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}/${t}`,queryParams:{acl:""},headers:{"x-amz-acl":s}})}async getBucketLocation(e){let t=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}`,queryParams:{location:""}}),s=j(t,"LocationConstraint");return(typeof s==="string"?s:s?.["#text"])||"us-east-1"}async getBucketLogging(e){let t=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}`,queryParams:{logging:""}});return j(t,"BucketLoggingStatus")}async putBucketLogging(e,t,s){let r=`<?xml version="1.0" encoding="UTF-8"?>
|
|
40
|
-
<BucketLoggingStatus xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
41
|
-
<LoggingEnabled>
|
|
42
|
-
<TargetBucket>${t}</TargetBucket>
|
|
43
|
-
<TargetPrefix>${s}</TargetPrefix>
|
|
44
|
-
</LoggingEnabled>
|
|
45
|
-
</BucketLoggingStatus>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,queryParams:{logging:""},headers:{"Content-Type":"application/xml"},body:r})}async getBucketNotificationConfiguration(e){let t=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}`,queryParams:{notification:""}});return j(t,"NotificationConfiguration")}async putBucketNotificationConfiguration(e,t){let s="";if(t.LambdaFunctionConfigurations)for(let i of t.LambdaFunctionConfigurations){if(s+="<CloudFunctionConfiguration>",i.Id)s+=`<Id>${i.Id}</Id>`;s+=`<CloudFunction>${i.LambdaFunctionArn}</CloudFunction>`;for(let a of i.Events)s+=`<Event>${a}</Event>`;if(i.Filter?.Key?.FilterRules){s+="<Filter><S3Key>";for(let a of i.Filter.Key.FilterRules)s+=`<FilterRule><Name>${a.Name}</Name><Value>${a.Value}</Value></FilterRule>`;s+="</S3Key></Filter>"}s+="</CloudFunctionConfiguration>"}if(t.TopicConfigurations)for(let i of t.TopicConfigurations){if(s+="<TopicConfiguration>",i.Id)s+=`<Id>${i.Id}</Id>`;s+=`<Topic>${i.TopicArn}</Topic>`;for(let a of i.Events)s+=`<Event>${a}</Event>`;s+="</TopicConfiguration>"}if(t.QueueConfigurations)for(let i of t.QueueConfigurations){if(s+="<QueueConfiguration>",i.Id)s+=`<Id>${i.Id}</Id>`;s+=`<Queue>${i.QueueArn}</Queue>`;for(let a of i.Events)s+=`<Event>${a}</Event>`;s+="</QueueConfiguration>"}let r=`<?xml version="1.0" encoding="UTF-8"?>
|
|
46
|
-
<NotificationConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
47
|
-
${s}
|
|
48
|
-
</NotificationConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,queryParams:{notification:""},headers:{"Content-Type":"application/xml"},body:r})}async getBucketWebsite(e){try{let t=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}`,queryParams:{website:""}});return j(t,"WebsiteConfiguration")}catch(t){if(t.statusCode===404)return null;throw t}}async putBucketWebsite(e,t){let s="";if(t.RedirectAllRequestsTo)s=`<RedirectAllRequestsTo>
|
|
49
|
-
<HostName>${t.RedirectAllRequestsTo.HostName}</HostName>
|
|
50
|
-
${t.RedirectAllRequestsTo.Protocol?`<Protocol>${t.RedirectAllRequestsTo.Protocol}</Protocol>`:""}
|
|
51
|
-
</RedirectAllRequestsTo>`;else if(s=`<IndexDocument><Suffix>${t.IndexDocument}</Suffix></IndexDocument>`,t.ErrorDocument)s+=`<ErrorDocument><Key>${t.ErrorDocument}</Key></ErrorDocument>`;let r=`<?xml version="1.0" encoding="UTF-8"?>
|
|
52
|
-
<WebsiteConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
53
|
-
${s}
|
|
54
|
-
</WebsiteConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,queryParams:{website:""},headers:{"Content-Type":"application/xml"},body:r})}async deleteBucketWebsite(e){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${e}`,queryParams:{website:""}})}async getBucketReplication(e){try{let t=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}`,queryParams:{replication:""}});return j(t,"ReplicationConfiguration")}catch(t){if(t.statusCode===404)return null;throw t}}async deleteBucketReplication(e){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${e}`,queryParams:{replication:""}})}async getPublicAccessBlock(e){try{let t=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e}`,queryParams:{publicAccessBlock:""}});return j(t,"PublicAccessBlockConfiguration")}catch(t){if(t.statusCode===404)return null;throw t}}async putPublicAccessBlock(e,t){let s=`<?xml version="1.0" encoding="UTF-8"?>
|
|
55
|
-
<PublicAccessBlockConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
56
|
-
<BlockPublicAcls>${t.BlockPublicAcls??!0}</BlockPublicAcls>
|
|
57
|
-
<IgnorePublicAcls>${t.IgnorePublicAcls??!0}</IgnorePublicAcls>
|
|
58
|
-
<BlockPublicPolicy>${t.BlockPublicPolicy??!0}</BlockPublicPolicy>
|
|
59
|
-
<RestrictPublicBuckets>${t.RestrictPublicBuckets??!0}</RestrictPublicBuckets>
|
|
60
|
-
</PublicAccessBlockConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,queryParams:{publicAccessBlock:""},headers:{"Content-Type":"application/xml"},body:s})}async deletePublicAccessBlock(e){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${e}`,queryParams:{publicAccessBlock:""}})}generatePresignedGetUrl(e,t,s=3600){let{accessKeyId:r,secretAccessKey:i}=this.getCredentials(),a=this.s3VirtualHost(e),c=new Date,g=c.toISOString().replace(/[:-]|\.\d{3}/g,""),d=c.toISOString().slice(0,10).replace(/-/g,""),u=`${d}/${this.region}/s3/aws4_request`,y=`${r}/${u}`,h=t.split("/").map((C)=>encodeURIComponent(C)).join("/"),m=new URLSearchParams({"X-Amz-Algorithm":"AWS4-HMAC-SHA256","X-Amz-Credential":y,"X-Amz-Date":g,"X-Amz-Expires":s.toString(),"X-Amz-SignedHeaders":"host"}),p=["GET",this.objectPath(e,h),m.toString(),`host:${a}
|
|
61
|
-
`,"host","UNSIGNED-PAYLOAD"].join(`
|
|
62
|
-
`),b=["AWS4-HMAC-SHA256",g,u,l.createHash("sha256").update(p).digest("hex")].join(`
|
|
63
|
-
`),S=l.createHmac("sha256",`AWS4${i}`).update(d).digest(),f=l.createHmac("sha256",S).update(this.region).digest(),k=l.createHmac("sha256",f).update("s3").digest(),T=l.createHmac("sha256",k).update("aws4_request").digest(),w=l.createHmac("sha256",T).update(b).digest("hex");return m.append("X-Amz-Signature",w),`${this.endpointProtocol}://${a}${this.objectPath(e,h)}?${m.toString()}`}generatePresignedPutUrl(e,t,s,r=3600){let{accessKeyId:i,secretAccessKey:a}=this.getCredentials(),c=this.s3VirtualHost(e),g=new Date,d=g.toISOString().replace(/[:-]|\.\d{3}/g,""),u=g.toISOString().slice(0,10).replace(/-/g,""),y=`${u}/${this.region}/s3/aws4_request`,h=`${i}/${y}`,m=t.split("/").map((q)=>encodeURIComponent(q)).join("/"),p=new URLSearchParams({"X-Amz-Algorithm":"AWS4-HMAC-SHA256","X-Amz-Credential":h,"X-Amz-Date":d,"X-Amz-Expires":r.toString(),"X-Amz-SignedHeaders":"content-type;host"}),b=["PUT",this.objectPath(e,m),p.toString(),`content-type:${s}
|
|
64
|
-
host:${c}
|
|
65
|
-
`,"content-type;host","UNSIGNED-PAYLOAD"].join(`
|
|
66
|
-
`),S=["AWS4-HMAC-SHA256",d,y,l.createHash("sha256").update(b).digest("hex")].join(`
|
|
67
|
-
`),f=l.createHmac("sha256",`AWS4${a}`).update(u).digest(),k=l.createHmac("sha256",f).update(this.region).digest(),T=l.createHmac("sha256",k).update("s3").digest(),w=l.createHmac("sha256",T).update("aws4_request").digest(),C=l.createHmac("sha256",w).update(S).digest("hex");return p.append("X-Amz-Signature",C),`${this.endpointProtocol}://${c}${this.objectPath(e,m)}?${p.toString()}`}async createMultipartUpload(e,t,s){let r={};if(s?.contentType)r["Content-Type"]=s.contentType;if(s?.metadata)for(let[g,d]of Object.entries(s.metadata))r[`x-amz-meta-${g}`]=d;let i=t.split("/").map((g)=>encodeURIComponent(g)).join("/"),a=await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${i}`,bucket:e,queryParams:{uploads:""},headers:r});return{UploadId:(a?.InitiateMultipartUploadResult??a)?.UploadId}}async uploadPart(e,t,s,r,i){let{accessKeyId:a,secretAccessKey:c,sessionToken:g}=this.getCredentials(),d=this.s3VirtualHost(e),u=t.split("/").map((O)=>encodeURIComponent(O)).join("/"),y=this.objectPath(e,u),h=`${this.objectUrl(e,u)}?partNumber=${r}&uploadId=${encodeURIComponent(s)}`,m=new Date,p=m.toISOString().replace(/[:-]|\.\d{3}/g,""),b=m.toISOString().slice(0,10).replace(/-/g,""),S=l.createHash("sha256").update(i).digest("hex"),f={host:d,"x-amz-date":p,"x-amz-content-sha256":S};if(g)f["x-amz-security-token"]=g;let k=Object.keys(f).sort().map((O)=>`${O.toLowerCase()}:${f[O].trim()}
|
|
68
|
-
`).join(""),T=Object.keys(f).sort().map((O)=>O.toLowerCase()).join(";"),w=["PUT",y,`partNumber=${r}&uploadId=${encodeURIComponent(s)}`,k,T,S].join(`
|
|
69
|
-
`),C="AWS4-HMAC-SHA256",q=`${b}/${this.region}/s3/aws4_request`,I=[C,p,q,l.createHash("sha256").update(w).digest("hex")].join(`
|
|
70
|
-
`),K=l.createHmac("sha256",`AWS4${c}`).update(b).digest(),H=l.createHmac("sha256",K).update(this.region).digest(),E=l.createHmac("sha256",H).update("s3").digest(),v=l.createHmac("sha256",E).update("aws4_request").digest(),A=l.createHmac("sha256",v).update(I).digest("hex"),x=`${C} Credential=${a}/${q}, SignedHeaders=${T}, Signature=${A}`,P=await fetch(h,{method:"PUT",headers:{...f,Authorization:x},body:U(i)});if(!P.ok){let O=await P.text();throw Error(`Upload part failed: ${P.status} ${O}`)}return{ETag:P.headers.get("etag")||""}}async completeMultipartUpload(e,t,s,r){let i=t.split("/").map((g)=>encodeURIComponent(g)).join("/"),c=`<?xml version="1.0" encoding="UTF-8"?>
|
|
71
|
-
<CompleteMultipartUpload>${r.sort((g,d)=>g.PartNumber-d.PartNumber).map((g)=>`<Part><PartNumber>${g.PartNumber}</PartNumber><ETag>${g.ETag}</ETag></Part>`).join("")}</CompleteMultipartUpload>`;await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${i}`,bucket:e,queryParams:{uploadId:s},headers:{"Content-Type":"application/xml"},body:c})}async abortMultipartUpload(e,t,s){let r=t.split("/").map((i)=>encodeURIComponent(i)).join("/");await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${r}`,bucket:e,queryParams:{uploadId:s}})}async listMultipartUploads(e){let t=await this.client.request({service:"s3",region:this.region,method:"GET",path:"/",bucket:e,queryParams:{uploads:""}}),s=(t?.ListMultipartUploadsResult??t)?.Upload;if(!s)return[];return(Array.isArray(s)?s:[s]).map((i)=>({Key:i.Key,UploadId:i.UploadId,Initiated:i.Initiated}))}async restoreObject(e,t,s,r="Standard"){let i=`<?xml version="1.0" encoding="UTF-8"?>
|
|
72
|
-
<RestoreRequest>
|
|
73
|
-
<Days>${s}</Days>
|
|
74
|
-
<GlacierJobParameters>
|
|
75
|
-
<Tier>${r}</Tier>
|
|
76
|
-
</GlacierJobParameters>
|
|
77
|
-
</RestoreRequest>`;await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${e}/${t}`,queryParams:{restore:""},headers:{"Content-Type":"application/xml"},body:i})}async selectObjectContent(e,t,s,r,i="JSON"){let a="";if(r==="CSV")a="<CSV><FileHeaderInfo>USE</FileHeaderInfo></CSV>";else if(r==="JSON")a="<JSON><Type>DOCUMENT</Type></JSON>";else a="<Parquet/>";let c="";if(i==="CSV")c="<CSV/>";else c="<JSON/>";let g=`<?xml version="1.0" encoding="UTF-8"?>
|
|
78
|
-
<SelectObjectContentRequest>
|
|
79
|
-
<Expression>${s}</Expression>
|
|
80
|
-
<ExpressionType>SQL</ExpressionType>
|
|
81
|
-
<InputSerialization>${a}</InputSerialization>
|
|
82
|
-
<OutputSerialization>${c}</OutputSerialization>
|
|
83
|
-
</SelectObjectContentRequest>`;return await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${e}/${t}`,queryParams:{select:"","select-type":"2"},headers:{"Content-Type":"application/xml"},body:g,rawResponse:!0})}async getSignedUrl(e){let{bucket:t,key:s,expiresIn:r=3600,operation:i="getObject"}=e,{accessKeyId:a,secretAccessKey:c,sessionToken:g}=this.getCredentials(),d=new Date,u=d.toISOString().replace(/[:-]|\.\d{3}/g,""),y=d.toISOString().slice(0,10).replace(/-/g,""),h=this.s3VirtualHost(t),m=i==="putObject"?"PUT":"GET",p="AWS4-HMAC-SHA256",b=`${y}/${this.region}/s3/aws4_request`,f={"X-Amz-Algorithm":"AWS4-HMAC-SHA256","X-Amz-Credential":`${a}/${b}`,"X-Amz-Date":u,"X-Amz-Expires":r.toString(),"X-Amz-SignedHeaders":"host"};if(g)f["X-Amz-Security-Token"]=g;let T=Object.keys(f).sort().map((R)=>`${encodeURIComponent(R)}=${encodeURIComponent(f[R])}`).join("&"),w=s.split("/").map((R)=>encodeURIComponent(R)).join("/"),C=this.objectPath(t,w),q=`host:${h}
|
|
84
|
-
`,H=[m,C,T,q,"host","UNSIGNED-PAYLOAD"].join(`
|
|
85
|
-
`),E=["AWS4-HMAC-SHA256",u,b,l.createHash("sha256").update(H).digest("hex")].join(`
|
|
86
|
-
`),v=l.createHmac("sha256",`AWS4${c}`).update(y).digest(),A=l.createHmac("sha256",v).update(this.region).digest(),x=l.createHmac("sha256",A).update("s3").digest(),P=l.createHmac("sha256",x).update("aws4_request").digest(),O=l.createHmac("sha256",P).update(E).digest("hex");return`${this.endpointProtocol}://${h}${C}?${T}&X-Amz-Signature=${O}`}async listObjects(e){let{bucket:t,prefix:s,maxKeys:r=1000,continuationToken:i}=e,a={"list-type":"2","max-keys":r.toString()};if(s)a.prefix=s;if(i)a["continuation-token"]=i;let c=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${t}`,queryParams:a}),g=[],d=c?.ListBucketResult??c;if(d?.Contents){let u=Array.isArray(d.Contents)?d.Contents:[d.Contents];for(let y of u)g.push({Key:y.Key||"",LastModified:y.LastModified||"",Size:Number.parseInt(y.Size||"0"),ETag:y.ETag})}return{objects:g,nextContinuationToken:d?.NextContinuationToken}}async emptyBucket(e){let t=0,s=await this.listAllObjects({bucket:e});if(s.length>0)for(let r=0;r<s.length;r+=1000){let a=s.slice(r,r+1000).map((c)=>c.Key);await this.deleteObjects(e,a),t+=a.length}try{let r,i;do{let a=await this.listObjectVersions({bucket:e,keyMarker:r,versionIdMarker:i,maxKeys:1000}),c=[];if(a.versions)for(let g of a.versions)c.push({Key:g.Key,VersionId:g.VersionId});if(a.deleteMarkers)for(let g of a.deleteMarkers)c.push({Key:g.Key,VersionId:g.VersionId});if(c.length>0)await this.deleteObjectVersions(e,c),t+=c.length;r=a.nextKeyMarker,i=a.nextVersionIdMarker}while(r)}catch{}return{deletedCount:t}}async listObjectVersions(e){let{bucket:t,prefix:s,keyMarker:r,versionIdMarker:i,maxKeys:a=1000}=e,c={versions:"","max-keys":a.toString()};if(s)c.prefix=s;if(r)c["key-marker"]=r;if(i)c["version-id-marker"]=i;let g=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${t}`,queryParams:c}),d=[],u=[];if(g.Version){let y=Array.isArray(g.Version)?g.Version:[g.Version];for(let h of y)d.push({Key:h.Key,VersionId:h.VersionId,IsLatest:h.IsLatest==="true"})}if(g.DeleteMarker){let y=Array.isArray(g.DeleteMarker)?g.DeleteMarker:[g.DeleteMarker];for(let h of y)u.push({Key:h.Key,VersionId:h.VersionId,IsLatest:h.IsLatest==="true"})}return{versions:d,deleteMarkers:u,nextKeyMarker:g.NextKeyMarker,nextVersionIdMarker:g.NextVersionIdMarker}}async deleteObjectVersions(e,t){let s=`<?xml version="1.0" encoding="UTF-8"?>
|
|
87
|
-
<Delete>
|
|
88
|
-
<Quiet>true</Quiet>
|
|
89
|
-
${t.map((i)=>`<Object><Key>${i.Key}</Key>${i.VersionId?`<VersionId>${i.VersionId}</VersionId>`:""}</Object>`).join(`
|
|
90
|
-
`)}
|
|
91
|
-
</Delete>`,r=l.createHash("md5").update(s).digest("base64");await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${e}`,queryParams:{delete:""},body:s,headers:{"Content-Type":"application/xml","Content-MD5":r}})}}
|
|
92
|
-
export{Bt,o};
|
package/dist/chunk-d46p0h6t.js
DELETED
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
import{n}from"./chunk-zx8ecz8b.js";import{o}from"./chunk-9asn5fpt.js";import{y}from"./chunk-9wmer0zx.js";import{Fe}from"./chunk-bxrzsth8.js";function f(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=f(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}}}function p(e,t){return(e?.[`${t}Response`]??e)?.[`${t}Result`]}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(){let e=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendStatistics&Version=2010-12-01"}),t=p(e,"GetSendStatistics")?.SendDataPoints?.member;return{SendDataPoints:t==null?[]:Array.isArray(t)?t:[t]}}async getSendQuota(){let e=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendQuota&Version=2010-12-01"}),t=p(e,"GetSendQuota"),s=(a)=>a==null||a===""?void 0:Number(a);return{Max24HourSend:s(t?.Max24HourSend),MaxSendRate:s(t?.MaxSendRate),SentLast24Hours:s(t?.SentLast24Hours)}}async verifyDomain(e){let t=await this.createEmailIdentity({EmailIdentity:e});return{dkimTokens:t.DkimAttributes?.Tokens,verificationStatus:t.DkimAttributes?.Status}}async sendSimpleEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],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,A)=>{let h={Action:g,Version:"2010-05-08",...A};return Object.entries(h).map(([R,S])=>`${encodeURIComponent(R)}=${encodeURIComponent(S)}`).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
|
-
`,i+=`To: ${s.join(", ")}\r
|
|
3
|
-
`,e.cc){let c=Array.isArray(e.cc)?e.cc:[e.cc];i+=`Cc: ${c.join(", ")}\r
|
|
4
|
-
`}if(i+=`Subject: ${e.subject}\r
|
|
5
|
-
`,i+=`MIME-Version: 1.0\r
|
|
6
|
-
`,i+=`Content-Type: multipart/mixed; boundary="${a}"\r
|
|
7
|
-
`,i+=`\r
|
|
8
|
-
`,e.text||e.html)if(i+=`--${a}\r
|
|
9
|
-
`,e.html&&e.text){let c=`----=_Alt_${Date.now()}`;i+=`Content-Type: multipart/alternative; boundary="${c}"\r
|
|
10
|
-
`,i+=`\r
|
|
11
|
-
`,i+=`--${c}\r
|
|
12
|
-
`,i+=`Content-Type: text/plain; charset="UTF-8"\r
|
|
13
|
-
`,i+=`\r
|
|
14
|
-
`,i+=`${e.text}\r
|
|
15
|
-
`,i+=`--${c}\r
|
|
16
|
-
`,i+=`Content-Type: text/html; charset="UTF-8"\r
|
|
17
|
-
`,i+=`\r
|
|
18
|
-
`,i+=`${e.html}\r
|
|
19
|
-
`,i+=`--${c}--\r
|
|
20
|
-
`}else if(e.html)i+=`Content-Type: text/html; charset="UTF-8"\r
|
|
21
|
-
`,i+=`\r
|
|
22
|
-
`,i+=`${e.html}\r
|
|
23
|
-
`;else i+=`Content-Type: text/plain; charset="UTF-8"\r
|
|
24
|
-
`,i+=`\r
|
|
25
|
-
`,i+=`${e.text}\r
|
|
26
|
-
`;if(e.attachments)for(let c of e.attachments)i+=`--${a}\r
|
|
27
|
-
`,i+=`Content-Type: ${c.contentType||"application/octet-stream"}; name="${c.filename}"\r
|
|
28
|
-
`,i+=`Content-Transfer-Encoding: base64\r
|
|
29
|
-
`,i+=`Content-Disposition: attachment; filename="${c.filename}"\r
|
|
30
|
-
`,i+=`\r
|
|
31
|
-
`,i+=`${c.content}\r
|
|
32
|
-
`;return i+=`--${a}--\r
|
|
33
|
-
`,i}}var Dh=new Sn;
|
|
34
|
-
export{fe,tt,Sn,Dh};
|
package/dist/chunk-dak9hfrd.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{j}from"./chunk-k53agv2m.js";import"./chunk-zx8ecz8b.js";export{j as RDSClient};
|
package/dist/chunk-ptq9v346.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{n}from"./chunk-zx8ecz8b.js";class h{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new n(void 0,{profile:t})}async createStack(e){let t={Action:"CreateStack",StackName:e.stackName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;else throw Error("Either templateBody or templateUrl must be provided");if(e.parameters)e.parameters.forEach((a,r)=>{t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.roleArn)t.RoleARN=e.roleArn;if(e.tags)e.tags.forEach((a,r)=>{t[`Tags.member.${r+1}.Key`]=a.Key,t[`Tags.member.${r+1}.Value`]=a.Value});if(e.timeoutInMinutes)t.TimeoutInMinutes=e.timeoutInMinutes;if(e.onFailure)t.OnFailure=e.onFailure;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackId:s.StackId||s.CreateStackResult?.StackId}}async updateStack(e){let t={Action:"UpdateStack",StackName:e.stackName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;if(e.parameters)e.parameters.forEach((a,r)=>{if(t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,a.UsePreviousValue)t[`Parameters.member.${r+1}.UsePreviousValue`]="true";else t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.roleArn)t.RoleARN=e.roleArn;if(e.tags)e.tags.forEach((a,r)=>{t[`Tags.member.${r+1}.Key`]=a.Key,t[`Tags.member.${r+1}.Value`]=a.Value});let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackId:s.StackId||s.UpdateStackResult?.StackId}}async deleteStack(e,t,s){let a={Action:"DeleteStack",StackName:e,Version:"2010-05-15"};if(t)a.RoleARN=t;if(s&&s.length>0)s.forEach((r,u)=>{a[`RetainResources.member.${u+1}`]=r});await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(a).toString()})}async describeStacks(e={}){let t={Action:"DescribeStacks",Version:"2010-05-15"};if(e.stackName)t.StackName=e.stackName;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{Stacks:this.parseStacksResponse(s)}}async describeStackEvents(e){let t={Action:"DescribeStackEvents",StackName:e,Version:"2010-05-15"},s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackEvents:this.parseStackEvents(s)}}async listStackResources(e){let t={Action:"ListStackResources",StackName:e,Version:"2010-05-15"},a=(await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}))?.ListStackResourcesResult?.StackResourceSummaries?.member,r=[];if(a)r=Array.isArray(a)?a:[a];return{StackResourceSummaries:r}}async waitForStack(e,t){let s={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},a=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],r=s[t],u=360,i=0;while(i<360)try{let c=await this.describeStacks({stackName:e});if(c.Stacks.length===0){if(t==="stack-delete-complete")return;if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Stack not visible yet`);await new Promise((m)=>setTimeout(m,2000)),i++;continue}let o=c.Stacks[0];if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Status = ${o.StackStatus}${o.StackStatusReason?` (${o.StackStatusReason})`:""}`);if(r.includes(o.StackStatus))return;if((t==="stack-create-complete"||t==="stack-update-complete")&&(o.StackStatus==="DELETE_IN_PROGRESS"||o.StackStatus==="DELETE_COMPLETE")){console.log("[waitForStack] Stack is being deleted (creation/update failed)");let m="";try{let S=await this.describeStackEvents(e);console.log("[waitForStack] Stack events (most recent first):");for(let k of S.StackEvents.slice(0,15))if(k.ResourceStatus.includes("FAILED")||k.ResourceStatusReason){if(console.log(` ${k.LogicalResourceId}: ${k.ResourceStatus} - ${k.ResourceStatusReason||"No reason provided"}`),k.ResourceStatus.includes("FAILED")&&k.ResourceStatusReason&&!m)m=k.ResourceStatusReason}}catch{}let l=m||o.StackStatusReason||"Check CloudFormation console for details.";throw Error(`Stack creation/update failed - stack is being deleted. Reason: ${l}`)}if(o.StackStatus==="DELETE_FAILED"&&t==="stack-delete-complete"){let m=Error("Stack deletion failed - may have resources that need to be retained");throw m.code="DELETE_FAILED",m.stackStatus=o.StackStatus,m.statusReason=o.StackStatusReason,m}if(a.includes(o.StackStatus))throw Error(`Stack reached failure status: ${o.StackStatus}`);await new Promise((m)=>setTimeout(m,5000)),i++}catch(c){if(t==="stack-delete-complete"&&c.message?.includes("does not exist"))return;if(t==="stack-create-complete"&&c.message?.includes("does not exist")){if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Stack does not exist (error), retrying...`);await new Promise((o)=>setTimeout(o,2000)),i++;continue}throw console.log(`[waitForStack] Unexpected error: ${c.message}`),c}throw console.log(`[waitForStack] Timeout after ${i} attempts`),Error(`Timeout waiting for stack to reach ${t}`)}async validateTemplate(e){let t={Action:"ValidateTemplate",TemplateBody:e,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()})}async listStacks(e){let t={Action:"ListStacks",Version:"2010-05-15"};if(e)e.forEach((c,o)=>{t[`StackStatusFilter.member.${o+1}`]=c});let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}),a=s.ListStacksResponse||s,r=a.ListStacksResult||a,u=r.StackSummaries?.member||r.StackSummaries||[];return{StackSummaries:(Array.isArray(u)?u:u?[u]:[]).map((c)=>({StackId:c.StackId||"",StackName:c.StackName||"",TemplateDescription:c.TemplateDescription,CreationTime:c.CreationTime||"",LastUpdatedTime:c.LastUpdatedTime,DeletionTime:c.DeletionTime,StackStatus:c.StackStatus||""}))}}async createChangeSet(e){let t={Action:"CreateChangeSet",StackName:e.stackName,ChangeSetName:e.changeSetName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;if(e.parameters)e.parameters.forEach((a,r)=>{t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.changeSetType)t.ChangeSetType=e.changeSetType;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{Id:s.Id,StackId:s.StackId}}async describeChangeSet(e,t){let s={Action:"DescribeChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async executeChangeSet(e,t){let s={Action:"ExecuteChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async deleteChangeSet(e,t){let s={Action:"DeleteChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async getStackOutputs(e){let t=await this.describeStacks({stackName:e});if(!t.Stacks||t.Stacks.length===0)throw Error(`Stack ${e} not found`);let s=t.Stacks[0],a={};if(s.Outputs)for(let r of s.Outputs)a[r.OutputKey]=r.OutputValue;return a}async getTemplate(e){let t={Action:"GetTemplate",StackName:e,Version:"2010-05-15"},s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{TemplateBody:s?.GetTemplateResult?.TemplateBody||s?.TemplateBody||""}}parseStacksResponse(e){let t=[],s=e?.DescribeStacksResult?.Stacks?.member||e?.Stacks?.member||e?.Stacks||e;if(s&&!Array.isArray(s))s=[s];if(Array.isArray(s)){for(let a of s)if(a.StackId||a.StackName){let r;if(a.Outputs?.member)r=(Array.isArray(a.Outputs.member)?a.Outputs.member:[a.Outputs.member]).map((i)=>({OutputKey:i.OutputKey,OutputValue:i.OutputValue,Description:i.Description,ExportName:i.ExportName}));t.push({StackId:a.StackId,StackName:a.StackName,StackStatus:a.StackStatus,CreationTime:a.CreationTime,LastUpdatedTime:a.LastUpdatedTime,StackStatusReason:a.StackStatusReason,Outputs:r})}}else if(e.StackId)t.push({StackId:e.StackId,StackName:e.StackName,StackStatus:e.StackStatus,CreationTime:e.CreationTime,LastUpdatedTime:e.LastUpdatedTime});return t}parseStackEvents(e){let t=[],s=e?.DescribeStackEventsResult?.StackEvents?.member||e?.StackEvents?.member||e?.StackEvents||[];if(s&&!Array.isArray(s))s=[s];for(let a of s)if(a.LogicalResourceId)t.push({Timestamp:a.Timestamp,ResourceType:a.ResourceType,LogicalResourceId:a.LogicalResourceId,ResourceStatus:a.ResourceStatus,ResourceStatusReason:a.ResourceStatusReason});return t}async waitForStackWithProgress(e,t,s){let a={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},r=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],u=a[t],i=360,c=0,o=new Set;while(c<360)try{if(s)try{let k=[...(await this.describeStackEvents(e)).StackEvents||[]].reverse();for(let d of k){let g=`${d.LogicalResourceId}-${d.ResourceStatus}-${d.Timestamp}`;if(!o.has(g))o.add(g),s({resourceId:d.LogicalResourceId,resourceType:d.ResourceType,status:d.ResourceStatus,reason:d.ResourceStatusReason,timestamp:d.Timestamp})}}catch{}let m=await this.describeStacks({stackName:e});if(m.Stacks.length===0){if(t==="stack-delete-complete")return;await new Promise((S)=>setTimeout(S,2000)),c++;continue}let l=m.Stacks[0];if(u.includes(l.StackStatus))return;if(l.StackStatus==="DELETE_FAILED"&&t==="stack-delete-complete"){let S=Error("Stack deletion failed - may have resources that need to be retained");throw S.code="DELETE_FAILED",S.stackStatus=l.StackStatus,S.statusReason=l.StackStatusReason,S}if(r.includes(l.StackStatus))throw Error(`Stack reached failure status: ${l.StackStatus}`);await new Promise((S)=>setTimeout(S,3000)),c++}catch(m){if(t==="stack-delete-complete"&&m.message?.includes("does not exist"))return;if(t==="stack-create-complete"&&m.message?.includes("does not exist")){await new Promise((l)=>setTimeout(l,2000)),c++;continue}throw m}throw Error(`Timeout waiting for stack to reach ${t}`)}async waitForStackComplete(e,t=120,s=5000){let a=["CREATE_COMPLETE","UPDATE_COMPLETE","DELETE_COMPLETE"],r=["CREATE_FAILED","UPDATE_FAILED","DELETE_FAILED","ROLLBACK_COMPLETE","ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED"];for(let u=0;u<t;u++)try{let i=await this.describeStacks({stackName:e});if(i.Stacks.length===0)return{success:!0,status:"DELETE_COMPLETE"};let c=i.Stacks[0],o=c.StackStatus;if(a.includes(o))return{success:!0,status:o};if(r.includes(o))return{success:!1,status:o,reason:c.StackStatusReason};await new Promise((m)=>setTimeout(m,s))}catch(i){if(i.message?.includes("does not exist"))return{success:!0,status:"DELETE_COMPLETE"};throw i}return{success:!1,status:"TIMEOUT",reason:"Timeout waiting for stack operation"}}}
|
|
2
|
-
export{h};
|
package/dist/chunk-z4xzd43p.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{xa}from"./chunk-7xnwa0s8.js";import"./chunk-5far81q7.js";import"./chunk-zx8ecz8b.js";import"./chunk-v2p7c7s4.js";export{xa as buildAndPushServerlessImage};
|
package/dist/chunk-zx8ecz8b.js
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import*as T from"node:crypto";import{existsSync as W,readFileSync as J}from"node:fs";import{homedir as B}from"node:os";import{join as K}from"node:path";var z={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"},H={nbsp:" ",copy:"©",reg:"®",trade:"™",euro:"€",pound:"£",yen:"¥",cent:"¢",deg:"°",micro:"µ",middot:"·",bull:"•",hellip:"…",prime:"′",Prime:"″",laquo:"«",raquo:"»",lsquo:"‘",rsquo:"’",ldquo:"“",rdquo:"”",ndash:"–",mdash:"—",iexcl:"¡",iquest:"¿",sect:"§",para:"¶",dagger:"†",Dagger:"‡",lsaquo:"‹",rsaquo:"›",oline:"‾",frasl:"⁄",ensp:" ",emsp:" ",thinsp:" ",zwnj:"",zwj:"",lrm:"",rlm:"",times:"×",divide:"÷",plusmn:"±",ne:"≠",le:"≤",ge:"≥",infin:"∞",fnof:"ƒ",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω",alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigmaf:"ς",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",thetasym:"ϑ",upsih:"ϒ",piv:"ϖ",larr:"←",uarr:"↑",rarr:"→",darr:"↓",harr:"↔",crarr:"↵",lArr:"⇐",uArr:"⇑",rArr:"⇒",dArr:"⇓",hArr:"⇔",forall:"∀",part:"∂",exist:"∃",empty:"∅",nabla:"∇",isin:"∈",notin:"∉",ni:"∋",prod:"∏",sum:"∑",minus:"−",lowast:"∗",radic:"√",prop:"∝",ang:"∠",and:"∧",or:"∨",cap:"∩",cup:"∪",int:"∫",there4:"∴",sim:"∼",cong:"≅",asymp:"≈",equiv:"≡",sub:"⊂",sup:"⊃",nsub:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"⋅",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",lang:"〈",rang:"〉",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦",Agrave:"À",Aacute:"Á",Acirc:"Â",Atilde:"Ã",Auml:"Ä",Aring:"Å",AElig:"Æ",Ccedil:"Ç",Egrave:"È",Eacute:"É",Ecirc:"Ê",Euml:"Ë",Igrave:"Ì",Iacute:"Í",Icirc:"Î",Iuml:"Ï",ETH:"Ð",Ntilde:"Ñ",Ograve:"Ò",Oacute:"Ó",Ocirc:"Ô",Otilde:"Õ",Ouml:"Ö",Oslash:"Ø",Ugrave:"Ù",Uacute:"Ú",Ucirc:"Û",Uuml:"Ü",Yacute:"Ý",THORN:"Þ",szlig:"ß",agrave:"à",aacute:"á",acirc:"â",atilde:"ã",auml:"ä",aring:"å",aelig:"æ",ccedil:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"í",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",circ:"ˆ",tilde:"˜"};class R{customEntities={};useHtmlEntities;constructor(t=!1){this.useHtmlEntities=t}addEntity(t,e){this.customEntities[t]=e}decodeEntities(t){let e=t.indexOf("&");if(e===-1)return t;let r=t.length,i="",s=0;while(e!==-1&&e<r){if(e>s)i+=t.substring(s,e);let a=t.indexOf(";",e+1);if(a===-1||a-e>32){i+="&",s=e+1,e=t.indexOf("&",s);continue}let o=t.substring(e+1,a);if(o.charCodeAt(0)===35){let c=o.length,h=0,A=!1;if(c>2&&(o.charCodeAt(1)===120||o.charCodeAt(1)===88)){A=!0;for(let m=2;m<c;m++){let f=o.charCodeAt(m);if(f>=48&&f<=57)h=h<<4|f-48;else if(f>=65&&f<=70)h=h<<4|f-55;else if(f>=97&&f<=102)h=h<<4|f-87;else{A=!1;break}}}else if(c>1){A=!0;for(let m=1;m<c;m++){let f=o.charCodeAt(m);if(f>=48&&f<=57)h=h*10+(f-48);else{A=!1;break}}}if(A)i+=String.fromCodePoint(h);else i+=t.substring(e,a+1)}else{let c=this.customEntities[o];if(c===void 0){let h=o.length;if(h>=2&&h<=4){let A=o.charCodeAt(0);if(A===108&&h===2&&o.charCodeAt(1)===116)c="<";else if(A===103&&h===2&&o.charCodeAt(1)===116)c=">";else if(A===97&&h===3&&o.charCodeAt(1)===109&&o.charCodeAt(2)===112)c="&";else if(A===113&&h===4)c=o==="quot"?'"':void 0;else if(A===97&&h===4)c=o==="apos"?"'":void 0}if(c===void 0)c=z[o]??(this.useHtmlEntities?H[o]:void 0)}if(c!==void 0)i+=c;else i+=t.substring(e,a+1)}s=a+1,e=t.indexOf("&",s)}if(s<r)i+=t.substring(s);return i}}var P=[];P[38]="&";P[60]="<";P[62]=">";P[34]=""";P[39]="'";var L={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,alwaysCreateTextNode:!1,trimValues:!0,parseTagValue:!0,parseAttributeValue:!1,processEntities:!0,htmlEntities:!1,commentPropName:!1,cdataPropName:!1,piPropName:!1,preserveOrder:!1,stopNodes:[],unpairedTags:[],isArray:void 0,tagValueProcessor:void 0,attributeValueProcessor:void 0,updateTag:void 0,numberParseOptions:{hex:!0,leadingZeros:!0,scientific:!0},ignorePiTags:!1,transformAttributeName:void 0,transformTagName:void 0,ignoreDeclaration:!1};function _(t){return t===32||t===9||t===10||t===13}function x(t){return t>=65&&t<=90||t>=97&&t<=122||t===95||t===58||t>=192&&t<=214||t>=216&&t<=246||t>=248&&t<=767||t>=880&&t<=893||t>=895&&t<=8191||t>=8204&&t<=8205||t>=8304&&t<=8591||t>=11264&&t<=12271||t>=12289&&t<=55295||t>=63744&&t<=64975||t>=65008&&t<=65533}function V(t){return x(t)||t===45||t===46||t>=48&&t<=57||t===183||t>=768&&t<=879||t>=8255&&t<=8256}var X=/^0x[\da-fA-F]+$/,M=/^[+-]?\d+(\.\d+)?[eE][+-]?\d+$/,G=/^[+-]?(\d+\.?\d*|\.\d+)$/;function D(t,e){return t.charCodeAt(e)===91&&t.charCodeAt(e+1)===67&&t.charCodeAt(e+2)===68&&t.charCodeAt(e+3)===65&&t.charCodeAt(e+4)===84&&t.charCodeAt(e+5)===65&&t.charCodeAt(e+6)===91}function k(t,e){let r=t.charCodeAt(e),i=t.charCodeAt(e+1),s=t.charCodeAt(e+2),a=t.charCodeAt(e+3),o=t.charCodeAt(e+4),c=t.charCodeAt(e+5),h=t.charCodeAt(e+6);return(r===68||r===100)&&(i===79||i===111)&&(s===67||s===99)&&(a===84||a===116)&&(o===89||o===121)&&(c===80||c===112)&&(h===69||h===101)}function Y(t,e,r){if(e>=r||!x(t.charCodeAt(e)))return e;e++;while(e<r&&V(t.charCodeAt(e)))e++;return e}class v{options;entityDecoder;unpairedSet;exactStopNodes;wildcardStopSuffixes;needsJPath;_ignoreAttributes=!0;_textNodeName="#text";_commentPropName=!1;_cdataPropName=!1;_piPropName=!1;_alwaysCreateTextNode=!1;_trimValues=!0;_processEntities=!0;_parseTagValue=!0;_parseAttributeValue=!1;_removeNSPrefix=!1;_attrPrefix="@_";_attrsGroupName=!1;_ignorePiTags=!1;_ignoreDeclaration=!1;constructor(t){this.options={...L,...t},this.entityDecoder=new R(this.options.htmlEntities),this.unpairedSet=new Set(this.options.unpairedTags),this.exactStopNodes=new Set,this.wildcardStopSuffixes=[];for(let e of this.options.stopNodes)if(e.startsWith("*."))this.wildcardStopSuffixes.push(e.substring(2));else this.exactStopNodes.add(e);this._ignoreAttributes=this.options.ignoreAttributes,this._textNodeName=this.options.textNodeName,this._commentPropName=this.options.commentPropName,this._cdataPropName=this.options.cdataPropName,this._piPropName=this.options.piPropName,this._alwaysCreateTextNode=this.options.alwaysCreateTextNode,this._trimValues=this.options.trimValues,this._processEntities=this.options.processEntities,this._parseTagValue=this.options.parseTagValue,this._parseAttributeValue=this.options.parseAttributeValue,this._removeNSPrefix=this.options.removeNSPrefix,this._attrPrefix=this.options.attributeNamePrefix,this._attrsGroupName=this.options.attributesGroupName,this._ignorePiTags=this.options.ignorePiTags,this._ignoreDeclaration=this.options.ignoreDeclaration,this.needsJPath=this.options.stopNodes.length>0||this.options.isArray!==void 0||this.options.updateTag!==void 0||this.options.tagValueProcessor!==void 0||this.options.attributeValueProcessor!==void 0}addEntity(t,e){this.entityDecoder.addEntity(t,e)}parse(t){if(t instanceof Uint8Array)t=new TextDecoder().decode(t);let e=t;if(this.options.preserveOrder)return this.parseOrdered(e);return this.parseUnordered(e)}parseUnordered(t){let e={},r=t.length,i=0;if(r>0&&t.charCodeAt(0)===65279)i=1;return i=this.parseChildren(t,i,r,e,"",[]),e}parseOrdered(t){let e=t.length,r=0;if(e>0&&t.charCodeAt(0)===65279)r=1;let i=[];return this.parseChildrenOrdered(t,r,e,i,""),i}readTagName(t,e,r){return Y(t,e,r)}extractTagName(t,e,r){let i=t.substring(e,r);if(this._removeNSPrefix){let s=i.indexOf(":");if(s!==-1)i=i.substring(s+1)}if(this.options.transformTagName)i=this.options.transformTagName(i);return i}parseAttributes(t,e,r,i,s){let a=0,o=this._removeNSPrefix,c=this.options.transformAttributeName,h=this._trimValues,A=this._processEntities,m=this.options.attributeValueProcessor;while(e<r){let f=t.charCodeAt(e);while(f===32||f===9||f===10||f===13){if(e++,e>=r)break;f=t.charCodeAt(e)}if(e>=r)break;if(f===62||f===47)break;let b=e;if(!x(f))break;e++;while(e<r&&V(t.charCodeAt(e)))e++;let p=t.substring(b,e);if(o){let C=p.indexOf(":");if(C!==-1)p=p.substring(C+1)}if(c)p=c(p);while(e<r&&_(t.charCodeAt(e)))e++;if(e<r&&t.charCodeAt(e)===61){e++;while(e<r&&_(t.charCodeAt(e)))e++;if(e>=r)break;let C=t.charCodeAt(e);if(C===34||C===39){e++;let E=e;while(e<r&&t.charCodeAt(e)!==C)e++;let d=t.substring(E,e);if(h&&d.length>0){let u=d.charCodeAt(0),g=d.charCodeAt(d.length-1);if(u<=32||g<=32)d=d.trim()}if(A)d=this.entityDecoder.decodeEntities(d);if(m)d=m(p,d,i)??d;if(s[p]=d,a++,e<r)e++}}else s[p]="true",a++}return a>0?-e-1:e}processTagValue(t,e,r,i,s){if(this._trimValues){let a=t.length;if(a>0){let o=t.charCodeAt(0),c=t.charCodeAt(a-1);if(o<=32||c<=32)t=t.trim()}}if(this._processEntities)t=this.entityDecoder.decodeEntities(t);if(this.options.tagValueProcessor){let a=this.options.tagValueProcessor(e,t,r,i,s);if(a!==void 0)t=a}if(!t)return t;if(this._parseTagValue)return this.parseValue(t);return t}parseValue(t){if(t==="true")return!0;if(t==="false")return!1;if(!t)return t;let e=t.charCodeAt(0);if(!(e>=48&&e<=57||e===43||e===45||e===46))return t;let i=this.options.numberParseOptions;if(i.skipLike?.test(t))return t;if(i.hex&&e===48&&X.test(t))return Number.parseInt(t,16);if(t.length>1&&e===48&&t.charCodeAt(1)!==46){if(i.leadingZeros)return t}if(i.scientific&&M.test(t)){let s=Number(t);if(!Number.isNaN(s))return s}if(G.test(t)){let s=Number(t);if(!Number.isNaN(s))return s}return t}parseAttributeValue(t){if(!this._parseAttributeValue)return t;return this.parseValue(t)}isStopNode(t){if(this.exactStopNodes.has(t))return!0;for(let e of this.wildcardStopSuffixes)if(t.endsWith(`.${e}`)||t===e)return!0;return!1}readStopNodeContent(t,e,r,i){let s=`</${i}`,a=t.indexOf(s,e);if(a===-1)return{content:t.substring(e),pos:r};let o=t.substring(e,a),c=a+s.length;while(c<r&&t.charCodeAt(c)!==62)c++;if(c<r)c++;return{content:o,pos:c}}addToObj(t,e,r,i,s,a){let o=t[e];if(o!==void 0)if(!Array.isArray(o))t[e]=[o,r];else o.push(r);else if(this.options.isArray?.(e,i,s,a))t[e]=[r];else t[e]=r}flushText(t,e,r,i){if(!t&&!e)return;let s=this._textNodeName;if(e){let a=t;if(a&&this._processEntities)a=this.entityDecoder.decodeEntities(a);let o=e+a;if(this._trimValues&&o.length>0){let c=o.charCodeAt(0),h=o.charCodeAt(o.length-1);if(c<=32||h<=32)o=o.trim()}if(this.options.tagValueProcessor){let c=this.options.tagValueProcessor(s,o,r,!1,!0);if(c!==void 0)o=c}if(o){let c=this._parseTagValue?this.parseValue(o):o;if(c!==void 0&&c!=="")this.addToObj(i,s,c,r,!0,!1)}}else{let a=this.processTagValue(t,s,r,!1,!0);if(a!==void 0&&a!=="")this.addToObj(i,s,a,r,!0,!1)}}parseChildren(t,e,r,i,s,a){let o="",c="",h=this.needsJPath;while(e<r){if(t.charCodeAt(e)!==60){let u=e;e++;while(e<r&&t.charCodeAt(e)!==60)e++;if(!o)o=t.substring(u,e);else o+=t.substring(u,e);continue}if(e+1>=r)break;let m=t.charCodeAt(e+1);if(m===33&&e+3<r&&t.charCodeAt(e+2)===45&&t.charCodeAt(e+3)===45){if(o||c)this.flushText(o,c,s,i),o="",c="";e+=4;let u=t.indexOf("-->",e);if(u===-1){e=r;break}if(this._commentPropName){let g=t.substring(e,u);this.addToObj(i,this._commentPropName,g,s,!0,!1)}e=u+3;continue}if(m===33&&e+8<r&&D(t,e+2)){e+=9;let u=t.indexOf("]]>",e);if(u===-1){e=r;break}let g=t.substring(e,u);if(this._cdataPropName)this.flushText(o,c,s,i),o="",c="",this.addToObj(i,this._cdataPropName,g,s,!0,!1);else{if(o){let y=o;if(this._processEntities)y=this.entityDecoder.decodeEntities(y);c+=y,o=""}c+=g}e=u+3;continue}if(m===33&&e+9<r&&k(t,e+2)){e+=9;let u=1;while(e<r&&u>0){let g=t.charCodeAt(e);if(g===60)u++;else if(g===62)u--;e++}continue}if(m===63){e+=2;let u=e;while(e<r&&!_(t.charCodeAt(e))&&t.charCodeAt(e)!==63)e++;let g=t.substring(u,e),y=t.indexOf("?>",e);if(y===-1){e=r;break}let N=t.substring(e,y).trim();if(g==="xml"){if(!this._ignoreDeclaration&&this._piPropName){let w=this.parsePiAttributes(N);this.addToObj(i,this._piPropName,{[g]:w},s,!0,!1)}}else if(!this._ignorePiTags&&this._piPropName)this.addToObj(i,this._piPropName,{[g]:N},s,!0,!1);e=y+2;continue}if(m===47){if(o||c)this.flushText(o,c,s,i),o="",c="";e+=2;let u=e,g=this.readTagName(t,e,r),y=this.extractTagName(t,u,g);e=g;while(e<r&&_(t.charCodeAt(e)))e++;if(e<r&&t.charCodeAt(e)===62)e++;if(a.length>0&&a[a.length-1]===y){a.pop();continue}return e}if(o||c)this.flushText(o,c,s,i),o="",c="";e++;let f=e,b=this.readTagName(t,e,r),p=this.extractTagName(t,f,b);if(!p){e=b+1;continue}e=b;let C=h?s?`${s}.${p}`:p:"",E={},d=!1;if(!this._ignoreAttributes){let u=this.parseAttributes(t,e,r,C,E);if(u<0)e=-u-1,d=!0;else e=u}else while(e<r){let u=t.charCodeAt(e);if(u===62||u===47)break;if(u===34||u===39){e++;while(e<r&&t.charCodeAt(e)!==u)e++}e++}if(this.options.updateTag){if(this.options.updateTag(p,C,E)===!1){while(e<r&&_(t.charCodeAt(e)))e++;if(e<r&&t.charCodeAt(e)===47)e+=2;else if(e<r&&t.charCodeAt(e)===62){e++;let g=`</${p}>`,y=t.indexOf(g,e);if(y!==-1)e=y+g.length}continue}}while(e<r&&_(t.charCodeAt(e)))e++;if(e<r&&t.charCodeAt(e)===47){if(e+=2,d||this._alwaysCreateTextNode){let u={};if(d)this.applyAttributes(u,E,C);if(this._alwaysCreateTextNode)u[this._textNodeName]="";this.addToObj(i,p,u,C,!0,!1)}else this.addToObj(i,p,"",C,!0,!1);continue}if(e<r&&t.charCodeAt(e)===62){if(e++,this.unpairedSet.has(p)){if(d){let N={};this.applyAttributes(N,E,C),this.addToObj(i,p,N,C,!0,!1)}else this.addToObj(i,p,"",C,!0,!1);a.push(p);continue}if(this.exactStopNodes.size>0||this.wildcardStopSuffixes.length>0){if(this.isStopNode(C)){let N=this.readStopNodeContent(t,e,r,p),w={};if(d)this.applyAttributes(w,E,C);if(N.content)w[this._textNodeName]=N.content;this.addToObj(i,p,w,C,!0,!1),e=N.pos;continue}}let u={};if(d)this.applyAttributes(u,E,C);e=this.parseChildren(t,e,r,u,C,a);let g=this._textNodeName,y=u[g];if(!d&&!this._alwaysCreateTextNode){let N=!0;for(let w in u)if(w!==g){N=!1;break}if(N){this.addToObj(i,p,y!==void 0?y:"",C,!0,!1);continue}}this.addToObj(i,p,u,C,!1,!1)}}if(o||c)this.flushText(o,c,s,i);return e}parseChildrenOrdered(t,e,r,i,s){let a="",o=this.needsJPath;while(e<r){if(t.charCodeAt(e)!==60){let d=e;e++;while(e<r&&t.charCodeAt(e)!==60)e++;if(!a)a=t.substring(d,e);else a+=t.substring(d,e);continue}if(e+1>=r)break;let h=t.charCodeAt(e+1);if(h===33&&e+3<r&&t.charCodeAt(e+2)===45&&t.charCodeAt(e+3)===45){if(a){let u=this.processTagValue(a,this._textNodeName,s,!1,!0);if(u!==void 0&&u!=="")i.push({[this._textNodeName]:u});a=""}e+=4;let d=t.indexOf("-->",e);if(d===-1){e=r;break}if(this._commentPropName)i.push({[this._commentPropName]:[{[this._textNodeName]:t.substring(e,d)}]});e=d+3;continue}if(h===33&&e+8<r&&D(t,e+2)){e+=9;let d=t.indexOf("]]>",e);if(d===-1){e=r;break}let u=t.substring(e,d);if(this._cdataPropName){if(a){let g=this.processTagValue(a,this._textNodeName,s,!1,!0);if(g!==void 0&&g!=="")i.push({[this._textNodeName]:g});a=""}i.push({[this._cdataPropName]:[{[this._textNodeName]:u}]})}else a+=u;e=d+3;continue}if(h===33&&e+9<r&&k(t,e+2)){e+=9;let d=1;while(e<r&&d>0){let u=t.charCodeAt(e);if(u===60)d++;else if(u===62)d--;e++}continue}if(h===63){e+=2;let d=t.indexOf("?>",e);if(d===-1){e=r;break}e=d+2;continue}if(h===47){if(a){let u=this.processTagValue(a,this._textNodeName,s,!1,!0);if(u!==void 0&&u!=="")i.push({[this._textNodeName]:u});a=""}e+=2,e=this.readTagName(t,e,r);while(e<r&&_(t.charCodeAt(e)))e++;if(e<r&&t.charCodeAt(e)===62)e++;return e}if(a){let d=this.processTagValue(a,this._textNodeName,s,!1,!0);if(d!==void 0&&d!=="")i.push({[this._textNodeName]:d});a=""}e++;let A=e,m=this.readTagName(t,e,r),f=this.extractTagName(t,A,m);if(!f){e=m+1;continue}e=m;let b=o?s?`${s}.${f}`:f:"",p={},C=!1;if(!this._ignoreAttributes){let d=this.parseAttributes(t,e,r,b,p);if(d<0)e=-d-1,C=!0;else e=d}else while(e<r){let d=t.charCodeAt(e);if(d===62||d===47)break;if(d===34||d===39){e++;while(e<r&&t.charCodeAt(e)!==d)e++}e++}while(e<r&&_(t.charCodeAt(e)))e++;let E={[f]:[]};if(C){E[":@"]={};for(let u in p)E[":@"][this._attrPrefix+u]=this.parseAttributeValue(p[u])}if(e<r&&t.charCodeAt(e)===47){e+=2,i.push(E);continue}if(e<r&&t.charCodeAt(e)===62)e++,e=this.parseChildrenOrdered(t,e,r,E[f],b),i.push(E)}if(a){let c=this.processTagValue(a,this._textNodeName,s,!1,!0);if(c!==void 0&&c!=="")i.push({[this._textNodeName]:c})}return e}applyAttributes(t,e,r){let i=this._attrPrefix;if(this._attrsGroupName){let s={};for(let a in e)s[i+a]=this.parseAttributeValue(e[a]);t[this._attrsGroupName]=s}else for(let s in e)t[i+s]=this.parseAttributeValue(e[s])}parsePiAttributes(t){let e={},r=0,i=t.length;while(r<i){while(r<i&&_(t.charCodeAt(r)))r++;if(r>=i)break;let s=r;while(r<i&&!_(t.charCodeAt(r))&&t.charCodeAt(r)!==61)r++;let a=t.substring(s,r);if(!a)break;while(r<i&&_(t.charCodeAt(r)))r++;if(r<i&&t.charCodeAt(r)===61){r++;while(r<i&&_(t.charCodeAt(r)))r++;if(r<i){let o=t.charCodeAt(r);if(o===34||o===39){r++;let c=r;while(r<i&&t.charCodeAt(r)!==o)r++;if(e[a]=t.substring(c,r),r<i)r++}}}}return e}}function br(t){let e=t.endpoint||`s3.${t.region}.amazonaws.com`,r=new URL(/^https?:\/\//i.test(e)?e:`https://${e}`);if(r.protocol!=="http:"&&r.protocol!=="https:"||r.pathname!=="/"&&r.pathname!==""||r.search||r.hash||r.username||r.password)throw Error("S3 endpoint must be an HTTP(S) origin without a path");let i=r.protocol.slice(0,-1),s=r.host;if(!t.bucket)return{protocol:i,host:s,path:t.path};if(t.forcePathStyle){let a=t.path==="/"?`/${t.bucket}`:`/${t.bucket}${t.path}`;return{protocol:i,host:s,path:a}}return{protocol:i,host:`${t.bucket}.${s}`,path:t.path}}class n{credentials;config;cache;xmlParser;constructor(t,e){this.config={maxRetries:3,retryDelay:1000,cacheEnabled:!0,defaultCacheTTL:60000,...e},this.credentials=t||this.loadCredentials(),this.cache=new Map,this.xmlParser=new v({ignoreAttributes:!1,attributeNamePrefix:"@_",textNodeName:"#text",parseAttributeValue:!0,trimValues:!0})}loadCredentials(){let t=process.env.AWS_ACCESS_KEY_ID,e=process.env.AWS_SECRET_ACCESS_KEY,r=process.env.AWS_SESSION_TOKEN;if(t&&e)return{accessKeyId:t,secretAccessKey:e,sessionToken:r};let i=this.loadCredentialsFromFile();if(i)return i;return{accessKeyId:"",secretAccessKey:""}}loadCredentialsFromFile(){let t=this.config?.profile||process.env.AWS_PROFILE||"default",e=process.env.AWS_SHARED_CREDENTIALS_FILE||K(B(),".aws","credentials");if(!W(e))return null;try{let r=J(e,"utf-8"),i=this.parseCredentialsFile(r,t);if(i.accessKeyId&&i.secretAccessKey)return i}catch{}return null}parseCredentialsFile(t,e){let r=t.split(`
|
|
2
|
-
`),i="",s="",a="",o;for(let c of r){let h=c.trim();if(!h||h.startsWith("#"))continue;let A=h.match(/^\[([^\]]+)\]$/);if(A){i=A[1];continue}if(i===e){let[m,...f]=h.split("="),b=f.join("=").trim();if(m.trim()==="aws_access_key_id")s=b;else if(m.trim()==="aws_secret_access_key")a=b;else if(m.trim()==="aws_session_token")o=b}}return{accessKeyId:s,secretAccessKey:a,sessionToken:o}}ec2CredentialsCache;async getCredentials(){let t=process.env.AWS_ACCESS_KEY_ID,e=process.env.AWS_SECRET_ACCESS_KEY;if(t&&e)return{accessKeyId:t,secretAccessKey:e,sessionToken:process.env.AWS_SESSION_TOKEN};let r=this.loadCredentialsFromFile();if(r)return r;if(this.ec2CredentialsCache){let i=Date.now();if(this.ec2CredentialsCache.expiration>i+300000)return this.ec2CredentialsCache.credentials}try{let s=await(await fetch("http://169.254.169.254/latest/api/token",{method:"PUT",headers:{"X-aws-ec2-metadata-token-ttl-seconds":"21600"}})).text(),o=await(await fetch("http://169.254.169.254/latest/meta-data/iam/security-credentials/",{headers:{"X-aws-ec2-metadata-token":s}})).text(),h=await(await fetch(`http://169.254.169.254/latest/meta-data/iam/security-credentials/${o}`,{headers:{"X-aws-ec2-metadata-token":s}})).json(),A={accessKeyId:h.AccessKeyId,secretAccessKey:h.SecretAccessKey,sessionToken:h.Token};return this.ec2CredentialsCache={credentials:A,expiration:new Date(h.Expiration).getTime()},A}catch(i){throw Error("AWS credentials not found. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables, or run on an EC2 instance with an IAM role.")}}async request(t){if(t.method==="GET"&&this.config.cacheEnabled&&t.cacheKey){let i=this.getFromCache(t.cacheKey);if(i!==null)return i}let e=t.retries??this.config.maxRetries??3,r=null;for(let i=0;i<=e;i++)try{let s=await this.makeRequest(t);if(t.method==="GET"&&this.config.cacheEnabled&&t.cacheKey)this.setInCache(t.cacheKey,s,t.cacheTTL??this.config.defaultCacheTTL??60000);return s}catch(s){if(r=s,!this.shouldRetry(s))throw s;if(i===e)throw s;let o=this.calculateRetryDelay(i);await this.sleep(o)}throw r||Error("Request failed after retries")}async makeRequest(t){let e=t.credentials||(this.credentials?.accessKeyId?this.credentials:await this.getCredentials());if(!e||!e.accessKeyId||!e.secretAccessKey)throw Error("AWS credentials not provided");let r=this.buildUrl(t),i=this.signRequest(t,e),s=await fetch(r,{method:t.method,headers:i,body:t.body}),a=await s.text();if(!s.ok)throw this.parseError(a,s.status,s.headers);if(!a||a.trim()===""){if(t.returnHeaders)return{body:null,headers:this.headersToObject(s.headers)};return null}if(t.rawResponse){if(t.returnHeaders)return{body:a,headers:this.headersToObject(s.headers)};return a}let o;if(a.startsWith("<"))o=this.parseXmlResponse(a);else try{o=JSON.parse(a)}catch{o=a}if(t.returnHeaders)return{body:o,headers:this.headersToObject(s.headers)};return o}headersToObject(t){let e={};return t.forEach((r,i)=>{e[i]=r}),e}buildUrl(t){let{service:e,region:r,queryParams:i}=t,{path:s}=t,a,o="https";if(e==="s3"){let h=br({region:r,path:s,bucket:t.bucket,endpoint:this.config.endpoint,forcePathStyle:this.config.forcePathStyle});o=h.protocol,a=h.host,s=h.path}else if(e==="cloudfront")a="cloudfront.amazonaws.com";else if(e==="iam")a="iam.amazonaws.com";else if(e==="route53")a="route53.amazonaws.com";else if(e==="route53domains")a="route53domains.us-east-1.amazonaws.com";else if(e==="ecr")a=`api.ecr.${r}.amazonaws.com`;else if(e==="ses")a=`email.${r}.amazonaws.com`;else a=`${e}.${r}.amazonaws.com`;let c=`${o}://${a}${s}`;if(i&&Object.keys(i).length>0){let h=Object.keys(i).map((A)=>`${this.uriEncode(A)}=${this.uriEncode(i[A])}`).join("&");c+=`?${h}`}return c}signRequest(t,e){let{service:r,region:i,method:s,queryParams:a,body:o}=t,{path:c}=t,h=new Date,A=this.getAmzDate(h),m=this.getDateStamp(h),f;if(r==="s3"){let S=br({region:i,path:c,bucket:t.bucket,endpoint:this.config.endpoint,forcePathStyle:this.config.forcePathStyle});f=S.host,c=S.path}else if(r==="cloudfront")f="cloudfront.amazonaws.com";else if(r==="iam")f="iam.amazonaws.com";else if(r==="route53")f="route53.amazonaws.com";else if(r==="route53domains")f="route53domains.us-east-1.amazonaws.com";else if(r==="ecr")f=`api.ecr.${i}.amazonaws.com`;else if(r==="ses")f=`email.${i}.amazonaws.com`;else f=`${r}.${i}.amazonaws.com`;let b={host:f,"x-amz-date":A,...t.headers||{}};if(e.sessionToken)b["x-amz-security-token"]=e.sessionToken;if(o){if(!Object.keys(b).some((O)=>O.toLowerCase()==="content-type"))b["content-type"]="application/x-www-form-urlencoded";b["content-length"]=Buffer.byteLength(o).toString()}let p=this.sha256(o||"");b["x-amz-content-sha256"]=p;let C=c,E=a?Object.keys(a).sort().map((S)=>`${this.uriEncode(S)}=${this.uriEncode(a[S])}`).join("&"):"",d=Object.keys(b).sort((S,O)=>S.toLowerCase().localeCompare(O.toLowerCase())),u=d.map((S)=>`${S.toLowerCase()}:${b[S].trim()}
|
|
3
|
-
`).join(""),g=d.map((S)=>S.toLowerCase()).join(";"),y=[s,C,E,u,g,p].join(`
|
|
4
|
-
`),N="AWS4-HMAC-SHA256",w=r;if(r==="email")w="ses";let I=`${m}/${i}/${w}/aws4_request`,F=[N,A,I,this.sha256(y)].join(`
|
|
5
|
-
`),q=this.getSignatureKey(e.secretAccessKey,m,i,w),U=this.hmac(q,F),j=`${N} Credential=${e.accessKeyId}/${I}, SignedHeaders=${g}, Signature=${U}`;return{...b,Authorization:j}}getAmzDate(t){return t.toISOString().replace(/[:-]|\.\d{3}/g,"")}getDateStamp(t){return t.toISOString().slice(0,10).replace(/-/g,"")}uriEncode(t){return encodeURIComponent(t).replace(/[!'()*]/g,(e)=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}sha256(t){return T.createHash("sha256").update(t,"utf8").digest("hex")}hmac(t,e){return T.createHmac("sha256",t).update(e,"utf8").digest("hex")}getSignatureKey(t,e,r,i){let s=T.createHmac("sha256",`AWS4${t}`).update(e).digest(),a=T.createHmac("sha256",s).update(r).digest(),o=T.createHmac("sha256",a).update(i).digest();return T.createHmac("sha256",o).update("aws4_request").digest()}parseXmlResponse(t){try{let e=this.xmlParser.parse(t);if(e.ErrorResponse)throw this.createErrorFromXml(e.ErrorResponse.Error);let r=Object.keys(e);if(r.length===1)return e[r[0]];return e}catch(e){if(e.code||e.statusCode)throw e;return{}}}parseError(t,e,r){let i=Error();if(i.statusCode=e,i.requestId=r.get("x-amzn-requestid")||r.get("x-amz-request-id")||void 0,t.startsWith("<"))try{let s=this.xmlParser.parse(t);if(s.ErrorResponse?.Error){let a=s.ErrorResponse.Error;return i.code=a.Code,i.message=`AWS Error [${a.Code}]: ${a.Message||"Unknown error"}`,i.type=a.Type,i}if(s.Error)return i.code=s.Error.Code,i.message=`AWS Error [${s.Error.Code}]: ${s.Error.Message||"Unknown error"}`,i}catch{}try{let s=JSON.parse(t);if(s.__type||s.code)return i.code=s.__type||s.code,i.message=`AWS Error [${i.code}]: ${s.message||s.Message||"Unknown error"}`,i}catch{}return i.message=`AWS API Error (${e}): ${t}`,i}createErrorFromXml(t){let e=Error();return e.code=t.Code,e.message=`AWS Error [${t.Code}]: ${t.Message||"Unknown error"}`,e.type=t.Type,e}isRetryableError(t){return["RequestTimeout","RequestTimeoutException","PriorRequestNotComplete","ConnectionError","ThrottlingException","Throttling","TooManyRequestsException","ProvisionedThroughputExceededException","RequestLimitExceeded","BandwidthLimitExceeded","SlowDown","ServiceUnavailable","ServiceUnavailableException","InternalError","InternalFailure","InternalServerError","InternalServiceException","TransientError","TransientFailure","IDPCommunicationErrorException","NetworkError","ConnectionRefusedException","EC2ThrottledException","503 Slow Down","500 InternalError"].includes(t)}isRetryableStatusCode(t){return t>=500||t===429}shouldRetry(t){if(t.name==="FetchError"||t.name==="TypeError"||t.code==="ECONNRESET")return!0;if(t.code&&this.isRetryableError(t.code))return!0;if(t.statusCode&&this.isRetryableStatusCode(t.statusCode))return!0;if(t.statusCode&&t.statusCode>=400&&t.statusCode<500&&t.statusCode!==429)return!1;if(t.statusCode)return!1;return!0}calculateRetryDelay(t){let e=this.config.retryDelay??1000,r=30000,i=Math.min(e*2**t,30000),s=Math.random()*0.3*i;return i+s}sleep(t){return new Promise((e)=>setTimeout(e,t))}getFromCache(t){let e=this.cache.get(t);if(!e)return null;if(Date.now()>e.expires)return this.cache.delete(t),null;return e.data}setInCache(t,e,r){this.cache.set(t,{data:e,expires:Date.now()+r})}clearCache(){this.cache.clear()}clearExpiredCache(){let t=Date.now();for(let[e,r]of this.cache.entries())if(t>r.expires)this.cache.delete(e)}}function l(t){let e={};for(let[r,i]of Object.entries(t)){if(i===void 0||i===null)continue;if(Array.isArray(i))i.forEach((s,a)=>{e[`${r}.${a+1}`]=String(s)});else if(typeof i==="object")for(let[s,a]of Object.entries(i))e[`${r}.${s}`]=String(a);else e[r]=String(i)}return e}function Wh(){let t=process.env.AWS_ACCESS_KEY_ID,e=process.env.AWS_SECRET_ACCESS_KEY,r=t==="",i=e==="";if(t&&e)return{source:"env",emptyEnvKey:r,emptyEnvSecret:i,description:"environment variables (AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY)"};let s=process.env.AWS_PROFILE||"default",a=process.env.AWS_SHARED_CREDENTIALS_FILE||K(B(),".aws","credentials");if(W(a))return{source:"file",profile:s,emptyEnvKey:r,emptyEnvSecret:i,description:`~/.aws/credentials (profile: ${s})`};return{source:"ec2",emptyEnvKey:r,emptyEnvSecret:i,description:"EC2 instance metadata service (IMDSv2)"}}
|
|
6
|
-
export{br,n,l,Wh};
|