@stacksjs/ts-cloud 0.11.7 → 0.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/aws/index.js +1 -1
- package/dist/bin/chunk-0rtn6q5x.js +3 -0
- package/dist/bin/chunk-258ehp9s.js +1 -0
- package/dist/bin/chunk-2yctv06c.js +1 -0
- package/dist/bin/chunk-3276rveh.js +37 -0
- package/dist/bin/chunk-3m665jwp.js +70 -0
- package/dist/bin/chunk-3s2p9vxj.js +1 -0
- package/dist/bin/chunk-4esma5m9.js +1 -0
- package/dist/bin/chunk-4n0j3n3b.js +2 -0
- package/dist/bin/chunk-54bqchag.js +92 -0
- package/dist/bin/{chunk-4q6tad44.js → chunk-5bhx3bsa.js} +121 -121
- package/dist/bin/chunk-5zagqd20.js +1 -0
- package/dist/bin/chunk-7hw2js5h.js +512 -0
- package/dist/bin/chunk-8h1qr6x4.js +50 -0
- package/dist/bin/{chunk-w32xv8n4.js → chunk-9vdc7adf.js} +6 -6
- package/dist/bin/chunk-a1dd6sby.js +1 -0
- package/dist/bin/chunk-a4dw35gs.js +1 -0
- package/dist/bin/chunk-a9d55ker.js +1 -0
- package/dist/bin/chunk-awa1qade.js +9 -0
- package/dist/bin/chunk-b6by94pk.js +2 -0
- package/dist/bin/chunk-c8sypnbe.js +2 -0
- package/dist/bin/chunk-cx4e3d4w.js +1 -0
- package/dist/bin/chunk-d5a3vheh.js +2 -0
- package/dist/bin/chunk-e1fym2bd.js +1 -0
- package/dist/bin/chunk-ej4h0q2y.js +1 -0
- package/dist/bin/chunk-ett305ym.js +4 -0
- package/dist/bin/chunk-f11xf3n6.js +2 -0
- package/dist/bin/chunk-fq7ktvgy.js +3 -0
- package/dist/bin/chunk-fyq4th2m.js +1 -0
- package/dist/bin/chunk-g67qr8yf.js +1 -0
- package/dist/bin/chunk-gc82cx4h.js +1 -0
- package/dist/bin/chunk-hchtvpr9.js +1 -0
- package/dist/bin/chunk-hpe4jjce.js +1 -0
- package/dist/bin/chunk-k5vprsef.js +6 -0
- package/dist/bin/chunk-m22krd4z.js +3 -0
- package/dist/bin/chunk-mkppcwz8.js +1 -0
- package/dist/bin/chunk-mpjg0kc7.js +2 -0
- package/dist/bin/chunk-mrm4m4dk.js +2 -0
- package/dist/bin/chunk-nff46rxd.js +1 -0
- package/dist/bin/chunk-np1z3bgt.js +1 -0
- package/dist/bin/chunk-nskxkk6r.js +1 -0
- package/dist/bin/chunk-pez932b1.js +111 -0
- package/dist/bin/chunk-qsdf5kzk.js +2 -0
- package/dist/bin/chunk-r61qmhv1.js +2 -0
- package/dist/bin/chunk-r6gdcz5c.js +1 -0
- package/dist/bin/chunk-satwnr42.js +2 -0
- package/dist/bin/{chunk-dz1ec589.js → chunk-scqmd4qv.js} +30 -30
- package/dist/bin/chunk-smbycpt5.js +44 -0
- package/dist/bin/chunk-sn7e0sn7.js +2 -0
- package/dist/bin/chunk-ss574pka.js +1 -0
- package/dist/bin/chunk-tj0xb2d8.js +585 -0
- package/dist/bin/chunk-v3rzf9d0.js +141 -0
- package/dist/bin/chunk-wnpma6t3.js +34 -0
- package/dist/bin/chunk-xan0e052.js +5 -0
- package/dist/bin/chunk-xbk2y43r.js +60 -0
- package/dist/bin/chunk-xjp3v95e.js +6 -0
- package/dist/bin/chunk-xyt490vp.js +6 -0
- package/dist/bin/chunk-yn9r02gy.js +1 -0
- package/dist/bin/chunk-zhkhn9cc.js +1 -0
- package/dist/bin/cli.js +445 -430
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/chunk-0zf72ngj.js +1 -0
- package/dist/chunk-2hpjte1d.js +704 -0
- package/dist/chunk-4m6gwhwr.js +5 -0
- package/dist/chunk-5m29dhke.js +34 -0
- package/dist/chunk-6fzeemcs.js +114 -0
- package/dist/{chunk-zz52xje8.js → chunk-6xcbfs2r.js} +111 -111
- package/dist/chunk-bpnhqb70.js +6 -0
- package/dist/chunk-ead1nkbr.js +60 -0
- package/dist/chunk-fea461tj.js +141 -0
- package/dist/chunk-fvjczc73.js +1 -0
- package/dist/chunk-gearw6rk.js +4 -0
- package/dist/chunk-j60hesb3.js +2 -0
- package/dist/chunk-pmgtmt3d.js +1 -0
- package/dist/chunk-prf2pkvq.js +5 -0
- package/dist/chunk-q0wffgw5.js +37 -0
- package/dist/chunk-qcemnt35.js +50 -0
- package/dist/chunk-qvbwsaay.js +1 -0
- package/dist/chunk-r2pbqcnz.js +2 -0
- package/dist/chunk-r6110zv2.js +1 -0
- package/dist/chunk-rr1yaj55.js +2 -0
- package/dist/chunk-wcrj06cg.js +44 -0
- package/dist/chunk-wte9mh18.js +92 -0
- package/dist/{chunk-aw0cgv5w.js → chunk-y1dh3znq.js} +52 -52
- package/dist/chunk-y6e86wjs.js +445 -0
- package/dist/chunk-y8b7ht4v.js +1 -0
- package/dist/chunk-yf487g6e.js +2 -0
- package/dist/chunk-zmmc9j5f.js +2 -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.d.ts +1 -0
- package/dist/index.js +91 -91
- package/dist/operations/drained-sites.d.ts +56 -0
- package/dist/operations/drained-sites.test.d.ts +1 -0
- package/dist/pages/cloudflare-pages.d.ts +240 -0
- package/dist/pages/cloudflare-pages.test.d.ts +1 -0
- package/dist/pages/index.d.ts +2 -0
- package/dist/protection/index.js +1 -1
- package/dist/push/index.js +1 -1
- package/dist/spend/index.js +1 -1
- package/dist/ui/404.html +1 -1
- package/dist/ui/accept-invitation.html +1 -1
- package/dist/ui/access-denied.html +1 -1
- package/dist/ui/account/automation.html +6 -6
- package/dist/ui/account/security.html +2 -2
- package/dist/ui/applications/compose.html +6 -6
- package/dist/ui/applications/new.html +2 -2
- package/dist/ui/data/backups.html +80 -80
- package/dist/ui/data/services.html +78 -78
- package/dist/ui/data/volumes.html +50 -50
- package/dist/ui/index.html +50 -50
- package/dist/ui/infrastructure/topology.html +118 -118
- package/dist/ui/integrations.html +2 -2
- package/dist/ui/operations/alerts.html +48 -48
- package/dist/ui/operations/configuration.html +6 -6
- package/dist/ui/operations/jobs.html +75 -75
- package/dist/ui/operations/maintenance.html +6 -6
- package/dist/ui/operations/observability.html +82 -82
- package/dist/ui/operations/previews.html +6 -6
- package/dist/ui/operations/queue.html +6 -6
- package/dist/ui/operations/regions.html +6 -6
- package/dist/ui/operations/releases.html +6 -6
- package/dist/ui/operations/spend.html +54 -54
- package/dist/ui/operations/workloads.html +104 -104
- package/dist/ui/security.html +2 -2
- package/dist/ui/server/actions.html +56 -56
- package/dist/ui/server/activity.html +2 -2
- package/dist/ui/server/capacity.html +6 -6
- package/dist/ui/server/database.html +105 -105
- package/dist/ui/server/deployments.html +50 -50
- package/dist/ui/server/diagnostics.html +2 -2
- package/dist/ui/server/firewall.html +76 -76
- package/dist/ui/server/fleet.html +34 -34
- package/dist/ui/server/logs.html +24 -24
- package/dist/ui/server/metrics.html +112 -112
- package/dist/ui/server/security.html +1 -1
- package/dist/ui/server/services.html +26 -26
- package/dist/ui/server/sites.html +120 -120
- package/dist/ui/server/ssh-keys.html +52 -52
- package/dist/ui/server/team.html +144 -144
- package/dist/ui/server/terminal.html +15 -15
- package/dist/ui/serverless/alarms.html +52 -52
- package/dist/ui/serverless/assets.html +27 -27
- package/dist/ui/serverless/cost.html +2 -2
- package/dist/ui/serverless/data.html +35 -35
- package/dist/ui/serverless/deployments.html +27 -27
- package/dist/ui/serverless/firewall.html +2 -2
- package/dist/ui/serverless/functions.html +40 -40
- package/dist/ui/serverless/logs.html +24 -24
- package/dist/ui/serverless/metrics.html +2 -2
- package/dist/ui/serverless/queues.html +48 -48
- package/dist/ui/serverless/secrets.html +52 -52
- package/dist/ui/serverless/traces.html +6 -6
- package/dist/ui/serverless.html +53 -53
- package/dist/ui-src/src/charts.ts +8721 -13558
- package/dist/ui-src/src/topology.ts +2 -2
- package/package.json +4 -3
- package/dist/bin/chunk-0zwknfwp.js +0 -1
- package/dist/bin/chunk-3aph4c1w.js +0 -2
- package/dist/bin/chunk-4xhj37nj.js +0 -37
- package/dist/bin/chunk-5nkqza92.js +0 -1
- package/dist/bin/chunk-5nsqz5n3.js +0 -585
- package/dist/bin/chunk-64vczwwt.js +0 -1
- package/dist/bin/chunk-6tfwm33r.js +0 -6
- package/dist/bin/chunk-7g2ahkse.js +0 -1
- package/dist/bin/chunk-7zhgmp1s.js +0 -3
- package/dist/bin/chunk-82mj52xr.js +0 -141
- package/dist/bin/chunk-8khgprf6.js +0 -44
- package/dist/bin/chunk-9a88fp00.js +0 -2
- package/dist/bin/chunk-a7w13qfm.js +0 -2
- package/dist/bin/chunk-b4wt9jcg.js +0 -60
- package/dist/bin/chunk-btsyjhk7.js +0 -92
- package/dist/bin/chunk-c0bdafbx.js +0 -2
- package/dist/bin/chunk-cbsys5v8.js +0 -111
- package/dist/bin/chunk-cd0ps58j.js +0 -1
- package/dist/bin/chunk-d7ke90zt.js +0 -2
- package/dist/bin/chunk-djg4zyqk.js +0 -1
- package/dist/bin/chunk-dkaz333b.js +0 -1
- package/dist/bin/chunk-dkf4qsp2.js +0 -1
- package/dist/bin/chunk-e2bybahr.js +0 -3
- package/dist/bin/chunk-e5ab5twy.js +0 -50
- package/dist/bin/chunk-edvvx3hg.js +0 -1
- package/dist/bin/chunk-ehc63fvs.js +0 -2
- package/dist/bin/chunk-f06c5np9.js +0 -1
- package/dist/bin/chunk-g0fm1xcs.js +0 -1
- package/dist/bin/chunk-gq8794k6.js +0 -1
- package/dist/bin/chunk-hq9x489e.js +0 -70
- package/dist/bin/chunk-j447p8t4.js +0 -512
- package/dist/bin/chunk-ja1vjdn1.js +0 -6
- package/dist/bin/chunk-k3120rx6.js +0 -1
- package/dist/bin/chunk-kg61p5hw.js +0 -3
- package/dist/bin/chunk-mcr0r4at.js +0 -2
- package/dist/bin/chunk-mfrf9q4b.js +0 -2
- package/dist/bin/chunk-my3ewh3a.js +0 -34
- package/dist/bin/chunk-nw3d4k52.js +0 -1
- package/dist/bin/chunk-p70bc9yr.js +0 -1
- package/dist/bin/chunk-r6b3pq31.js +0 -4
- package/dist/bin/chunk-s4yzes15.js +0 -2
- package/dist/bin/chunk-sj5csg49.js +0 -2
- package/dist/bin/chunk-tvz9c388.js +0 -1
- package/dist/bin/chunk-wkx799z2.js +0 -1
- package/dist/bin/chunk-x6f61g36.js +0 -9
- package/dist/bin/chunk-xhwqpgwq.js +0 -2
- package/dist/bin/chunk-xk08030d.js +0 -6
- package/dist/bin/chunk-y1h63vpm.js +0 -1
- package/dist/bin/chunk-yw6f160x.js +0 -1
- package/dist/bin/chunk-zdt2rjk6.js +0 -1
- package/dist/bin/chunk-zh2d4704.js +0 -1
- package/dist/bin/chunk-znnawt0k.js +0 -1
- package/dist/bin/chunk-zpe64t4r.js +0 -1
- package/dist/bin/chunk-zsf6pccz.js +0 -1
- package/dist/chunk-1qdne0bf.js +0 -1
- package/dist/chunk-5vt93kxx.js +0 -1
- package/dist/chunk-73ztr55z.js +0 -2
- package/dist/chunk-95e6aeqz.js +0 -1
- package/dist/chunk-aj025v2s.js +0 -4
- package/dist/chunk-aw0spg20.js +0 -445
- package/dist/chunk-by2bwzk6.js +0 -141
- package/dist/chunk-dr4pj8hp.js +0 -5
- package/dist/chunk-hn40z11p.js +0 -37
- package/dist/chunk-kasdm9tx.js +0 -34
- package/dist/chunk-mz0dk78z.js +0 -6
- package/dist/chunk-nk7sav4r.js +0 -92
- package/dist/chunk-p10xt3jb.js +0 -1
- package/dist/chunk-q0rc1ax9.js +0 -114
- package/dist/chunk-q9q6cmt0.js +0 -1
- package/dist/chunk-rd38qdnf.js +0 -1
- package/dist/chunk-tz9myq9a.js +0 -2
- package/dist/chunk-wavjkdb8.js +0 -2
- package/dist/chunk-x3hay61c.js +0 -44
- package/dist/chunk-xcj8zfmg.js +0 -2
- package/dist/chunk-y4xkj2f1.js +0 -50
- package/dist/chunk-ywjkyg8p.js +0 -704
- package/dist/chunk-z2qqwy7e.js +0 -2
- package/dist/chunk-zam6ecam.js +0 -60
package/dist/aws/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$d as
|
|
1
|
+
import{$d as da,$e as db,Ae as Ea,Be as Fa,Ce as Ga,De as Ha,Ee as Ia,Fe as Ja,Ge as Ka,He as La,Ie as Ma,Jd as k,Je as Na,Kd as l,Ke as Oa,Ld as m,Le as Pa,Md as n,Me as Qa,Nd as o,Ne as Ra,Od as p,Oe as Sa,Pd as q,Pe as Ta,Qd as r,Qe as Ua,Rd as t,Re as Va,Sd as w,Se as Wa,Td as V,Te as Xa,Ud as X,Ue as Ya,Vd as Y,Ve as Za,Wd as Z,We as _a,Xd as _,Xe as $a,Yd as $,Ye as ab,Zd as aa,Ze as bb,_d as ba,_e as cb,ae as ea,af as eb,be as fa,bf as fb,ce as ga,cf as gb,de as ha,df as hb,ee as ia,ef as ib,fe as ja,ff as jb,ge as ka,gf as kb,he as la,hf as lb,ie as ma,if as mb,je as na,jf as nb,ke as oa,kf as ob,le as pa,lf as pb,me as qa,mf as qb,ne as ra,nf as rb,oe as sa,pe as ta,qe as ua,re as va,se as wa,te as xa,ue as ya,ve as za,we as Aa,xe as Ba,ye as Ca,ze as Da}from"../chunk-6fzeemcs.js";import{of as e,pf as h,qf as i,rf as j}from"../chunk-5m29dhke.js";import{sf as v}from"../chunk-fea461tj.js";import{tf as U}from"../chunk-zmmc9j5f.js";import{uf as ca}from"../chunk-j60hesb3.js";import{Af as B,Bf as C,Cf as D,Df as E,Ef as F,Ff as G,Gf as H,Hf as I,If as J,Jf as K,Kf as L,Lf as M,Mf as N,Nf as O,Of as P,Pf as Q,Qf as R,Rf as S,Sf as T,vf as x,wf as y,xf as z,zf as A}from"../chunk-yf487g6e.js";import{Tf as f}from"../chunk-qcemnt35.js";import{Vh as u,Wh as W}from"../chunk-gearw6rk.js";import{Xh as s}from"../chunk-r2pbqcnz.js";import{Zh as g}from"../chunk-wte9mh18.js";import{$h as b,_h as a,ai as c,bi as d}from"../chunk-bpnhqb70.js";import"../chunk-rr1yaj55.js";export{J as verifyZoneParity,Ha as translateToMultiple,Ga as translate,Oa as trackEvent,Ca as textToSpeech,Za as startSmtpServer,Xa as startImapServer,ob as setupSmsInfrastructure,Qa as search,Ra as retrieveForRag,a as resolveS3Endpoint,q as resolveObjectStorage,D as resolveDeclaredRecords,ka as requestModelAccess,m as remapKey,E as reconcileDeclaredRecords,C as qualifyName,p as providerEndpoint,B as policyTag,H as planZoneMigration,db as normalizePhoneNumber,o as migrateObjectStorage,Da as listVoices,Ia as listLanguages,la as listClaudeModels,n as keyMatchesFilters,fb as isValidPhoneNumber,hb as isSamePhoneNumber,wa as isContentSafe,pb as getSmsInfrastructureStatus,Na as getSimilarItems,Ma as getRecommendations,gb as getCountryCode,na as generateEmbeddings,eb as formatPhoneNumber,ya as extractTextFromS3,Aa as extractTablesFromS3,za as extractFormsFromS3,qa as extractEntities,G as exportRoute53Zone,j as email,R as dnsProviders,ra as detectLanguage,ua as detectLabelsFromS3,P as detectDnsProvider,d as detectCredentialSource,jb as createVoicemailHandler,lb as createVoiceClient,qb as createSmsInfrastructure,$a as createSmsInboxHandler,bb as createSmsClient,ab as createScheduledSmsHandler,Ea as createSSML,N as createRoute53Validator,kb as createRecordingHandler,L as createPorkbunValidator,r as createObjectStorageClient,M as createGoDaddyValidator,O as createDnsProvider,cb as createDeliveryReceiptHandler,va as countFacesInS3Image,sa as containsPii,ma as completeWithClaude,c as buildQueryParams,I as applyZoneMigration,pa as analyzeSentiment,ib as VoiceClient,K as UnifiedDnsValidator,Fa as TranslateClient,fa as TranscribeClient,xa as TextractClient,nb as SupportTemplates,mb as SupportClient,Ya as SmtpServer,_a as SmsClient,X as SecretsManagerClient,Ua as SchedulerClient,k as STSClient,W as SSMClient,Z as SQSClient,Y as SNSClient,h as SESClient,g as S3Client,F as Route53Provider,w as Route53DomainsClient,f as Route53Client,ta as RekognitionClient,ca as RDSClient,y as PorkbunProvider,Ba as PollyClient,Ka as PersonalizeRuntimeClient,La as PersonalizeEventsClient,Ja as PersonalizeClient,x as PROXIABLE_RECORD_TYPES,ea as OpenSearchClient,_ as LambdaClient,Pa as KendraClient,Wa as ImapServer,e as IAMClient,z as GoDaddyProvider,Sa as EventBridgeClient,i as EmailClient,Ta as ElastiCacheClient,ba as ELBv2Client,rb as EFSClient,V as ECSClient,U as ECRClient,u as EC2Client,da as DynamoDBClient,Q as DnsProviderFactory,t as CostExplorerClient,aa as ConnectClient,oa as ComprehendClient,A as CloudflareProvider,$ as CloudWatchLogsClient,v as CloudFrontClient,s as CloudFormationClient,ga as BedrockRuntimeClient,ha as BedrockClient,ia as BedrockAgentRuntimeClient,ja as BedrockAgentClient,l as AwsBackupClient,Va as ApplicationAutoScalingClient,b as AWSClient,T as ACMDnsValidator,S as ACMClient};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{Ef as Z,Rf as F,Uf as H,Vf as w,dg as A,vf as $}from"./chunk-awa1qade.js";function C(z){return`'${z.split("'").join("'\\''")}'`}function q(z){let G=z.user||"root",K=z.script.join(`
|
|
2
|
+
`),M=G==="root"?'bash -l "$TS_CLOUD_RECIPE"':`runuser -l ${C(G)} -c "bash $TS_CLOUD_RECIPE"`;return["set -uo pipefail",`echo "__TS_CLOUD_RECIPE_BEGIN__ ${z.name} (user=${G})"`,"TS_CLOUD_RECIPE=$(mktemp)",`cat > "$TS_CLOUD_RECIPE" <<'TS_CLOUD_RECIPE_EOF'`,K,"TS_CLOUD_RECIPE_EOF",'chmod +r "$TS_CLOUD_RECIPE"',M,"TS_CLOUD_RC=$?",'rm -f "$TS_CLOUD_RECIPE"',`echo "__TS_CLOUD_RECIPE_END__ ${z.name} exit=$TS_CLOUD_RC"`,"exit $TS_CLOUD_RC"]}var j={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};async function X(z){return await z.driver.findComputeTargets({slug:z.slug,environment:z.environment,role:z.role||"app"})}async function B(z,G){let K=z.logger||j,M=await X(z);if(M.length===0)return{success:!1,error:`No '${z.role||"app"}' servers found for ${z.slug}/${z.environment}.`};let Q=$(z.slug,G.siteName),W=w(Q,G.to||"unused"),U=["set -uo pipefail",...A(W,{...G.to?{to:G.to}:{},unitBase:`${z.slug}-${G.siteName}`}),`(cd ${Z} && pantry restart php-fpm) 2>/dev/null || true`,`(cd ${W.current} && eval "$(cd ${Z} && pantry env 2>/dev/null)" && php artisan queue:restart) 2>/dev/null || true`];K.step(`Rolling back ${G.siteName}${G.to?` to ${G.to}`:" to the previous release"} on ${M.length} server(s)...`);let V=await z.driver.runRemoteDeploy({targets:M,commands:U,comment:`ts-cloud rollback ${z.slug}/${G.siteName}`,tags:{Project:z.slug,Environment:z.environment,Role:z.role||"app"}});if(!V.success)K.error(`Rollback failed: ${V.error||"unknown error"}`);else K.success(`Rolled back ${G.siteName}.`);return{success:V.success,error:V.error,perInstance:V.perInstance}}async function I(z,G){let K=await X(z);if(K.length===0)return{success:!1,error:`No '${z.role||"app"}' servers found for ${z.slug}/${z.environment}.`};let M=H($(z.slug,G.siteName)),Q=Math.max(1,G.limit??20),W=[`[ -f ${M} ] && tail -n ${Q} ${M} || echo "no deploy history for ${G.siteName}"`],U=await z.driver.runRemoteDeploy({targets:K,commands:W,comment:`ts-cloud deploy:history ${z.slug}/${G.siteName}`,tags:{Project:z.slug,Environment:z.environment,Role:z.role||"app"}});return{success:U.success,error:U.error,perInstance:U.perInstance}}async function L(z,G){let K=z.logger||j,M=await X(z);if(M.length===0)return{success:!1,error:`No '${z.role||"app"}' servers found for ${z.slug}/${z.environment}.`};K.step(`Running recipe '${G.name}' as ${G.user||"root"} on ${M.length} server(s)...`);let Q=await z.driver.runRemoteDeploy({targets:M,commands:q({name:G.name,script:G.script,user:G.user}),comment:`ts-cloud recipe ${G.name}`,tags:{Project:z.slug,Environment:z.environment,Role:z.role||"app"}});if(!Q.success)K.error(`Recipe '${G.name}' failed: ${Q.error||"unknown error"}`);else K.success(`Recipe '${G.name}' completed.`);return{success:Q.success,error:Q.error,perInstance:Q.perInstance}}async function S(z,G){let K=z.logger||j;if(!G.database?.name)return{success:!1,error:"No appDatabase configured to restore."};let M=await X(z);if(M.length===0)return{success:!1,error:`No '${z.role||"app"}' servers found for ${z.slug}/${z.environment}.`};K.step(`Restoring database '${G.database.name}'${G.from?` from ${G.from}`:" from the latest backup"} on ${M.length} server(s)...`);let Q=await z.driver.runRemoteDeploy({targets:M,commands:F(G.database,{from:G.from}),comment:`ts-cloud db:restore ${z.slug}/${G.database.name}`,tags:{Project:z.slug,Environment:z.environment,Role:z.role||"app"}});if(!Q.success)K.error(`Restore failed: ${Q.error||"unknown error"}`);else K.success(`Restored ${G.database.name}.`);return{success:Q.success,error:Q.error,perInstance:Q.perInstance}}
|
|
3
|
+
export{B as xd,I as yd,L as zd,S as Ad};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{rd as a,sd as b}from"./chunk-mpjg0kc7.js";import"./chunk-8h1qr6x4.js";import"./chunk-xyt490vp.js";import"./chunk-c8sypnbe.js";export{b as ACMDnsValidator,a as ACMClient};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{wd as a}from"./chunk-v3rzf9d0.js";import"./chunk-xyt490vp.js";import"./chunk-c8sypnbe.js";export{a as CloudFrontClient};
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
var Y={mode:"detection",paranoiaLevel:1,inboundThreshold:5,outboundThreshold:4,maxBodyBytes:13107200,rejectOversizedBody:!0,auditLogPath:"/var/log/ts-cloud/waf-audit.log",blockStatus:403},C={bypassBase:1e5,exclusionBase:101000,rateLimitBase:102000,customBase:109000};function X(q){return q.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/[\r\n]+/g," ")}function W(q){if(q.length>1000)return!1;if(/\([^)]*[+*]\)[+*]/.test(q))return!1;if(/\[[^\]]*\][+*]\{/.test(q))return!1;try{return new RegExp(q),!0}catch{return!1}}function R(q,V){let G=[],K=[],J=V;for(let H of q){if(H.enabled===!1)continue;if(H.key&&(H.key.source==="cookie"||H.key.source==="header")&&!H.key.name){K.push({ruleId:H.id,reason:"The rule keys on a header or cookie but names none."});continue}let $=H.path?_(H.path):".*";if(!W($)){K.push({ruleId:H.id,reason:"The path pattern compiles to an unsafe regular expression."});continue}let Z=[`SecRule REQUEST_URI "@rx ${X($)}"`];if(H.methods?.length)Z.push(` "chain,id:${J},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${X(H.id)}'"`);else Z.push(` "id:${J},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${X(H.id)}'"`);if(G.push(`# Marks requests governed by the ts-cloud rate limit "${X(H.id)}".`),G.push(Z.join(" \\\n")),H.methods?.length)G.push(` SecRule REQUEST_METHOD "@within ${X(H.methods.join(" ").toUpperCase())}" "t:none"`);G.push(""),J++}return{lines:G,unmapped:K}}function _(q){return`^${q.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*")}$`}function y(q={},V=[]){let G=q.mode??Y.mode,K=[],J=q.paranoiaLevel??Y.paranoiaLevel,H=q.inboundThreshold??Y.inboundThreshold,$=q.outboundThreshold??Y.outboundThreshold,Z=q.maxBodyBytes??Y.maxBodyBytes,j=q.rejectOversizedBody!==!1;if(G==="blocking"&&J>=3)K.push(`Paranoia level ${J} blocks legitimate traffic on most applications until it is tuned. Run it in detection mode first.`);if(G==="blocking")K.push("zig-waf is pre-alpha. Blocking mode makes it a failure path for every request.");if(!j)K.push("Oversized bodies are passed through uninspected, so padding a request bypasses every rule.");if(q.bypassPaths?.length)K.push(`${q.bypassPaths.length} path(s) bypass inspection entirely.`);let Q=["# Managed by ts-cloud. Edits are overwritten on the next deploy.",`# Mode: ${G}. Paranoia level: ${J}.`,""];if(G==="off")return Q.push("SecRuleEngine Off",""),{config:`${Q.join(`
|
|
2
|
+
`)}
|
|
3
|
+
`,unmappedRateLimits:[],warnings:K,mode:G};Q.push(`SecRuleEngine ${G==="blocking"?"On":"DetectionOnly"}`,"SecRequestBodyAccess On","SecResponseBodyAccess Off",`SecRequestBodyLimit ${Z}`,`SecRequestBodyNoFilesLimit ${Math.min(Z,131072)}`,`SecRequestBodyLimitAction ${j?"Reject":"ProcessPartial"}`,"SecRequestBodyInMemoryLimit 131072",`SecAuditEngine ${G==="blocking"?"RelevantOnly":"On"}`,"SecAuditLogParts ABIJDEFHZ",`SecAuditLog ${X(q.auditLogPath??Y.auditLogPath)}`,"SecAuditLogType Serial",`SecDefaultAction "phase:1,log,auditlog,${G==="blocking"?`deny,status:${q.blockStatus??Y.blockStatus}`:"pass"}"`,"","# CRS anomaly scoring setup.",`SecAction "id:900000,phase:1,pass,nolog,t:none,setvar:tx.paranoia_level=${J}"`,`SecAction "id:900001,phase:1,pass,nolog,t:none,setvar:tx.inbound_anomaly_score_threshold=${H}"`,`SecAction "id:900002,phase:1,pass,nolog,t:none,setvar:tx.outbound_anomaly_score_threshold=${$}"`,'SecAction "id:900003,phase:1,pass,nolog,t:none,setvar:tx.critical_anomaly_score=5,setvar:tx.error_anomaly_score=4,setvar:tx.warning_anomaly_score=3,setvar:tx.notice_anomaly_score=2"','SecAction "id:900004,phase:1,pass,nolog,t:none,setvar:tx.anomaly_score=0"',"");let z=C.bypassBase;for(let N of q.bypassPaths??[]){let k=_(N);if(!W(k)){K.push(`Bypass path "${N}" was dropped: it compiles to an unsafe regular expression.`);continue}Q.push(`# Inspection bypass for ${X(N)}. Every bypass is an unguarded route.`,`SecRule REQUEST_URI "@rx ${X(k)}" "id:${z},phase:1,pass,nolog,ctl:ruleEngine=Off"`,""),z++}let B=C.exclusionBase;for(let N of q.exclusions??[]){if(!Number.isInteger(N.ruleId)||N.ruleId<=0){K.push(`Exclusion with rule id "${N.ruleId}" was dropped: the id is not a positive integer.`);continue}if(Q.push(`# ${X(N.reason)}`),N.pathPattern){if(!W(N.pathPattern)){K.push(`Exclusion for rule ${N.ruleId} was dropped: its path pattern is unsafe.`);continue}Q.push(`SecRule REQUEST_URI "@rx ${X(N.pathPattern)}" "id:${B},phase:1,pass,nolog,ctl:ruleRemoveById=${N.ruleId}"`),B++}else Q.push(`SecRuleRemoveById ${N.ruleId}`);Q.push("")}let M=R(V,C.rateLimitBase);if(M.lines.length>0)Q.push("# Rate-limit route markers. SecLang has no counters, so the tag is set","# here and the counting stays in the ts-cloud limiter.",...M.lines);let O=C.customBase;for(let N of q.customRules??[])Q.push(`# Operator-supplied rule ${O}.`,N.trim(),""),O++;if(G==="blocking")Q.push("# Blocking decision: one rule, at the end, on the accumulated score.",`SecRule TX:ANOMALY_SCORE "@ge %{tx.inbound_anomaly_score_threshold}" "id:949110,phase:2,deny,status:${q.blockStatus??Y.blockStatus},log,msg:'Inbound anomaly score exceeded (total: %{tx.anomaly_score})'"`,"");return{config:`${Q.join(`
|
|
4
|
+
`)}
|
|
5
|
+
`,unmappedRateLimits:M.unmapped,warnings:K,mode:G}}function A(q={},V=[],G={}){let K=G.binary??"/usr/local/bin/zig-waf",J=G.configPath??"/etc/ts-cloud/waf.conf",H=y(q,V);return`#!/usr/bin/env bash
|
|
6
|
+
# Managed by ts-cloud. Installs the zig-waf ruleset.
|
|
7
|
+
set -euo pipefail
|
|
8
|
+
|
|
9
|
+
if [ ! -x "${K}" ]; then
|
|
10
|
+
echo "ts-cloud: ${K} is not installed; skipping WAF configuration" >&2
|
|
11
|
+
exit 0
|
|
12
|
+
fi
|
|
13
|
+
|
|
14
|
+
install -d -m 0755 "$(dirname "${J}")"
|
|
15
|
+
install -d -m 0750 /var/log/ts-cloud
|
|
16
|
+
|
|
17
|
+
cat > "${J}.new" <<'WAF_EOF'
|
|
18
|
+
${H.config}WAF_EOF
|
|
19
|
+
|
|
20
|
+
# Compile the config before it goes live. A config that does not validate
|
|
21
|
+
# would leave the engine with no rules while still reporting itself enabled.
|
|
22
|
+
if ! "${K}" validate "${J}.new"; then
|
|
23
|
+
echo "ts-cloud: generated WAF config failed validation, keeping the previous one" >&2
|
|
24
|
+
rm -f "${J}.new"
|
|
25
|
+
exit 1
|
|
26
|
+
fi
|
|
27
|
+
|
|
28
|
+
if [ -f "${J}" ] && cmp -s "${J}.new" "${J}"; then
|
|
29
|
+
rm -f "${J}.new"
|
|
30
|
+
echo "ts-cloud: WAF config unchanged"
|
|
31
|
+
exit 0
|
|
32
|
+
fi
|
|
33
|
+
|
|
34
|
+
mv "${J}.new" "${J}"
|
|
35
|
+
echo "ts-cloud: WAF config installed (mode: ${H.mode})"
|
|
36
|
+
`}function F(q,V){return q.map((G)=>({projectId:V.projectId,environmentId:V.environmentId,resourceId:V.resourceId,kind:"event",source:"zig-waf",name:G.action==="blocked"?"waf.blocked":"waf.matched",timestamp:G.timestamp,value:1,host:G.host,pathTemplate:G.path,method:G.method,attributes:{ruleId:G.ruleId??null,anomalyScore:G.anomalyScore,action:G.action,messages:G.messages.slice(0,5)}}))}
|
|
37
|
+
export{X as Ze,W as _e,_ as $e,y as af,A as bf,F as cf};
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import{Lh as T}from"./chunk-5bhx3bsa.js";import"./chunk-c8sypnbe.js";function _(q){let j=q.sites||{};for(let D of Object.values(j))if(D?.repository?.url)return{provider:D.repository.provider,branch:D.repository.branch};return}function x(q){let j=q.trim().toLowerCase();if(j.includes("github.com"))return"github";if(j.includes("gitlab.com"))return"gitlab";if(j.includes("bitbucket.org"))return"bitbucket";return}function Q(q){return`'${q.replace(/'/g,"'\\''")}'`}function $(q){return q.replace(/'/g,"''")}function k(q,j){let D=["bunx --bun @stacksjs/ts-cloud deploy","--env",Q(q)];if(j.site)D.push("--site",Q(j.site));if(j.skipDnsVerification)D.push("--skip-dns-verification");return D.push("--yes"),D.join(" ")}function I(q,j="production",D={}){let N=_(q),F=D.provider||N?.provider;if(F!=="github"&&F!=="gitlab"&&F!=="bitbucket")return null;let G=q.environments?.[j],H=G?.deployBranch||N?.branch||"main",L=k(j,D),M=JSON.stringify(H),V=JSON.stringify(j),O=G?.domain?G.domain.startsWith("http")?G.domain:`https://${G.domain}`:void 0,W=O?`
|
|
2
|
+
url: ${JSON.stringify(O)}`:"",X=D.setup==="pantry"?` - name: Setup Pantry
|
|
3
|
+
uses: home-lang/pantry/packages/action@main`:` - uses: oven-sh/setup-bun@v2
|
|
4
|
+
- run: bun install --frozen-lockfile`,Y=T(q)==="hetzner"&&!!q.infrastructure?.compute,J=D.sshPrivateKeySecret||"SSH_PRIVATE_KEY";if(!/^[A-Z_][A-Z0-9_]*$/i.test(J))throw Error(`Invalid SSH private key secret name '${J}'`);let Z=Y?`
|
|
5
|
+
- name: Configure deployment SSH key
|
|
6
|
+
env:
|
|
7
|
+
SSH_PRIVATE_KEY: \${{ secrets.${J} }}
|
|
8
|
+
run: |
|
|
9
|
+
if [ -z "$SSH_PRIVATE_KEY" ]; then
|
|
10
|
+
echo "::error::${J} is required for Hetzner compute deployments"
|
|
11
|
+
exit 1
|
|
12
|
+
fi
|
|
13
|
+
install -d -m 700 "$HOME/.ssh"
|
|
14
|
+
printf '%s\\n' "$SSH_PRIVATE_KEY" | tr -d '\\r' > "$HOME/.ssh/id_ed25519"
|
|
15
|
+
chmod 600 "$HOME/.ssh/id_ed25519"
|
|
16
|
+
ssh-keygen -y -f "$HOME/.ssh/id_ed25519" > "$HOME/.ssh/id_ed25519.pub"
|
|
17
|
+
`:"";if(F==="github")return{provider:F,branch:H,path:".github/workflows/deploy.yml",content:`name: Deploy ${j}
|
|
18
|
+
run-name: Deploy ${j} from \${{ github.ref_name }}
|
|
19
|
+
|
|
20
|
+
on:
|
|
21
|
+
push:
|
|
22
|
+
branches: [${M}]
|
|
23
|
+
workflow_dispatch:
|
|
24
|
+
|
|
25
|
+
permissions:
|
|
26
|
+
contents: read
|
|
27
|
+
|
|
28
|
+
concurrency:
|
|
29
|
+
group: ts-cloud-${j}
|
|
30
|
+
cancel-in-progress: false
|
|
31
|
+
|
|
32
|
+
jobs:
|
|
33
|
+
deploy:
|
|
34
|
+
if: github.ref_name == '${$(H)}'
|
|
35
|
+
runs-on: ubuntu-latest
|
|
36
|
+
environment:
|
|
37
|
+
name: ${V}${W}
|
|
38
|
+
steps:
|
|
39
|
+
- uses: actions/checkout@v6
|
|
40
|
+
${X}
|
|
41
|
+
${Z}
|
|
42
|
+
# Provide the provider credentials your config needs as repo secrets.
|
|
43
|
+
- run: ${L}
|
|
44
|
+
env:
|
|
45
|
+
HCLOUD_TOKEN: \${{ secrets.HCLOUD_TOKEN }}
|
|
46
|
+
HETZNER_API_TOKEN: \${{ secrets.HETZNER_API_TOKEN }}
|
|
47
|
+
AWS_ACCESS_KEY_ID: \${{ secrets.AWS_ACCESS_KEY_ID }}
|
|
48
|
+
AWS_SECRET_ACCESS_KEY: \${{ secrets.AWS_SECRET_ACCESS_KEY }}
|
|
49
|
+
TS_CLOUD_UI_DISABLE: '1'
|
|
50
|
+
`};if(F==="gitlab")return{provider:F,branch:H,path:".gitlab-ci.yml",content:`deploy:
|
|
51
|
+
image: oven/bun:latest
|
|
52
|
+
rules:
|
|
53
|
+
- if: '$CI_COMMIT_BRANCH == ${M}'
|
|
54
|
+
environment: ${j}
|
|
55
|
+
script:
|
|
56
|
+
- bun install --frozen-lockfile
|
|
57
|
+
- ${L}
|
|
58
|
+
# Set HCLOUD_TOKEN / HETZNER_API_TOKEN / AWS credentials as CI variables.
|
|
59
|
+
`};return{provider:F,branch:H,path:"bitbucket-pipelines.yml",content:`pipelines:
|
|
60
|
+
branches:
|
|
61
|
+
${M}:
|
|
62
|
+
- step:
|
|
63
|
+
name: Deploy ${j}
|
|
64
|
+
deployment: ${j}
|
|
65
|
+
image: oven/bun:latest
|
|
66
|
+
script:
|
|
67
|
+
- bun install --frozen-lockfile
|
|
68
|
+
- ${L}
|
|
69
|
+
# Set HCLOUD_TOKEN / HETZNER_API_TOKEN / AWS credentials as repo variables.
|
|
70
|
+
`}}export{x as inferQuickDeployProvider,I as buildQuickDeployCi};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as y,b as z,c as A,d as B,e as C,f as D,g as E,h as F,i as G,j as H,k as I,l as J,m as K,n as L,o as M}from"./chunk-yn9r02gy.js";import{$e as u,Ze as s,_e as t,af as v,bf as w,cf as x}from"./chunk-3276rveh.js";import{df as k,ef as l,ff as m,gf as n,hf as o,if as p,jf as q,kf as r}from"./chunk-smbycpt5.js";import{Ao as c,Bo as d,Co as e,Do as f,Eo as g,Fo as h,Go as i,Ho as j,yo as a,zo as b}from"./chunk-5bhx3bsa.js";import"./chunk-c8sypnbe.js";export{x as wafEventTelemetry,m as sysctlHardening,A as ruleMatches,w as renderWafInstallScript,v as renderWafConfig,n as renderSysctlFile,o as renderNftablesRuleset,p as renderDdosInstallScript,j as recursionBlockedResponse,B as rateLimitKey,D as rateLimitHeaders,i as propagationHeaders,q as planMitigation,f as parseChain,M as mergeControlsIntoConfig,l as isValidCidr,t as isSafePattern,g as inspectInvocation,u as globToRegex,z as globMatches,d as functionFingerprint,s as escapeSecLang,J as describePosture,E as defaultRateLimitRules,r as applyMitigationFactor,K as applyControlsToRateLimits,L as applyControlsToDdos,c as TRACE_HEADER,h as RecursionGuard,C as RateLimiter,y as RATE_LIMIT_KEY_SEPARATOR,I as ProtectionControlStore,F as PROTECTION_SETTING,G as MAX_CONTROL_HOURS,a as DEPTH_HEADER,e as DEFAULT_RECURSION_LIMITS,k as DEFAULT_DDOS_THRESHOLDS,H as DEFAULT_ATTACK_MODE_HOURS,b as CHAIN_HEADER};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{gd as a}from"./chunk-sn7e0sn7.js";import"./chunk-xyt490vp.js";import"./chunk-c8sypnbe.js";export{a as RDSClient};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var L=[{index:0,id:"clients",label:"Clients"},{index:1,id:"dns",label:"DNS & TLS"},{index:2,id:"edge",label:"Edge"},{index:3,id:"routing",label:"Routing"},{index:4,id:"apps",label:"Applications"},{index:5,id:"runtime",label:"Background runtime"},{index:6,id:"data",label:"Data services"},{index:7,id:"durability",label:"Durability"}],m=[{index:0,id:"clients",label:"Clients"},{index:1,id:"dns",label:"DNS & TLS"},{index:2,id:"edge",label:"Edge"},{index:3,id:"entry",label:"Entry points"},{index:4,id:"compute",label:"Compute"},{index:5,id:"messaging",label:"Messaging & pooling"},{index:6,id:"data",label:"Data services"},{index:7,id:"durability",label:"Durability"}],w=[{match:/^redis/,kind:"cache",label:"Redis"},{match:/^(?:mysql|mariadb)/,kind:"database",label:"MySQL"},{match:/^postgres/,kind:"database",label:"PostgreSQL"},{match:/^meilisearch/,kind:"database",label:"Meilisearch"},{match:/^vitess|^vtgate/,kind:"database",label:"Vitess"},{match:/^memcached/,kind:"cache",label:"Memcached"}],y=/^(?:rpx-gateway|nginx|caddy|traefik|haproxy)$/;function j(H,Z=""){let J=H==null?"":String(H).trim();return J&&J!=="-"&&J!=="—"?J:Z}function h(H){return Array.isArray(H)?H.length:0}function D(H){let Z=j(H).toLowerCase();if(!Z)return"unknown";if(["running","live","active","available","success","ok","healthy","enabled"].includes(Z))return"ok";if(["failed","stopped","unreachable","error","critical","disabled"].includes(Z))return"bad";if(["configured","creating","pending","degraded","shadowed","warn","unknown"].includes(Z))return"warn";return"warn"}function Q(H,Z,J){if(J.has(Z.source)&&J.has(Z.target))H.push(Z)}function v(H,Z={}){let J=[],M=[],E=[],P=H.server??{},$=Array.isArray(H.sites)?H.sites:[],O=Array.isArray(H.services)?H.services:[],Y=Array.isArray(H.workers)?H.workers:[],I=H.security??{},b=!!H._serverReachable&&!H.metricsUnavailable,_="box";if(!b)E.push("The compute box could not be probed, so live service state is missing; the shape comes from your cloud config.");J.push({id:"internet",label:"Internet",kind:"internet",layer:0,status:"ok",sub:"Public traffic",facts:[],external:!0});let W=[...new Set($.map((z)=>j(z.domain)||j(z.route).split("/")[0]).filter((z)=>z&&z!=="internal"&&z!=="loopback"))],q=Array.isArray(I.tlsCertificates)?I.tlsCertificates:[],X=q.filter((z)=>Number(z?.daysRemaining??999)<21).length;J.push({id:"dns",label:W.length===1?W[0]:"Public domains",kind:"dns",layer:1,status:X?"warn":W.length?"ok":"unknown",sub:W.length>1?`${W.length} domains`:"DNS & certificates",facts:[{label:"Domains",value:W.length?W.slice(0,6).join(", "):"none resolved"},{label:"Certificates",value:q.length?`${q.length} issued`:"none reported"},...X?[{label:"Expiring",value:`${X} within 21 days`}]:[]],href:"/server/security",external:!0});let T=I.firewall??{},A=Array.isArray(I.ports)?I.ports:[];J.push({id:"firewall",label:"Host firewall",kind:"firewall",layer:2,status:D(T.status),sub:j(T.summary,"Inbound filtering"),facts:[{label:"State",value:j(T.status,"unknown")},{label:"Open ports",value:A.length?A.map((z)=>j(z.listen)).join(", "):"not reported"}],href:"/server/firewall",group:"box"});let C=O.find((z)=>y.test(j(z.name)));J.push({id:"proxy",label:j(C?.name,"Reverse proxy"),kind:"proxy",layer:3,status:C?D(C.status):"unknown",sub:"TLS termination & routing",facts:[{label:"Service",value:j(C?.name,"not detected")},{label:"State",value:j(C?.status,b?"not running":"not probed")},{label:"Routes",value:`${$.length} site${$.length===1?"":"s"}`}],href:"/server/services",group:"box"});for(let z of $){let B=`site:${j(z.name)}`;if(!j(z.name))continue;J.push({id:B,label:j(z.name),kind:"site",layer:4,status:D(z.status),sub:j(z.runtime,"runtime"),facts:[{label:"Route",value:j(z.route,"internal")},{label:"Runtime",value:j(z.runtime,"unknown")},{label:"Delivery",value:j(z.deploy,"unknown")},{label:"TLS",value:j(z.tls,"unknown")},...z.responseMs!=null?[{label:"Response",value:`${Math.round(Number(z.responseMs))} ms`}]:[],...z.httpStatus!=null?[{label:"HTTP",value:String(z.httpStatus)}]:[]],href:"/server/sites",group:"box"})}for(let z of Y){let B=`worker:${j(z.name)}`;if(!j(z.name))continue;J.push({id:B,label:j(z.name),kind:"worker",layer:5,status:D(z.status),sub:`${Number(z.processes??1)} process${Number(z.processes??1)===1?"":"es"}`,facts:[{label:"Processes",value:String(z.processes??1)},{label:"State",value:j(z.status,"unknown")},...j(z.site)?[{label:"Site",value:j(z.site)}]:[]],href:"/operations/jobs",group:"box"})}let g=H.serverScheduler??{};if(g.enabled)J.push({id:"scheduler",label:"Scheduler",kind:"scheduler",layer:5,status:"ok",sub:"Cron dispatch",facts:[{label:"Last run",value:j(g.lastRun,"unknown")}],href:"/operations/jobs",group:"box"});let U=O.map((z)=>{let B=j(z.name),G=w.find((N)=>N.match.test(B));return G?{service:z,name:B,...G}:null}).filter((z)=>!!z);for(let z of U)J.push({id:`data:${z.name}`,label:z.label,kind:z.kind,layer:6,status:D(z.service.status),sub:z.name,facts:[{label:"Unit",value:z.name},{label:"State",value:j(z.service.status,"unknown")}],href:"/data/services",group:"box"});let V=H.backup??{};if(V.enabled)J.push({id:"backup",label:"Backups",kind:"backup",layer:7,status:"ok",sub:j(V.destination,"destination"),facts:[{label:"Destination",value:j(V.destination,"unknown")},{label:"Schedule",value:j(V.schedule,"unknown")},{label:"Retention",value:`${V.retention??0} copies`},{label:"Last run",value:j(V.last,"unknown")}],href:"/data/backups"});let K=new Set(J.map((z)=>z.id));Q(M,{source:"internet",target:"dns",flow:"request",label:"https"},K),Q(M,{source:"dns",target:"firewall",flow:"request",label:"443/80"},K),Q(M,{source:"firewall",target:"proxy",flow:"request"},K);for(let z of $){let B=`site:${j(z.name)}`;Q(M,{source:"proxy",target:B,flow:"request",label:j(z.path)||void 0,status:D(z.status)},K)}for(let z of Y){let B=`worker:${j(z.name)}`,G=`site:${j(z.site)}`;if(K.has(G))Q(M,{source:G,target:B,flow:"async",label:"queue"},K);else Q(M,{source:"proxy",target:B,flow:"async",label:"queue"},K)}for(let z of Y)Q(M,{source:"scheduler",target:`worker:${j(z.name)}`,flow:"async",label:"dispatch"},K);let S=[...$.map((z)=>`site:${j(z.name)}`),...Y.map((z)=>`worker:${j(z.name)}`)];for(let z of U)for(let B of S)Q(M,{source:B,target:`data:${z.name}`,flow:"data",label:"localhost"},K);if(U.length&&S.length)E.push("Data-service edges show co-location on the box: every process on it can reach localhost. They are not a declared per-site binding.");for(let z of U)Q(M,{source:`data:${z.name}`,target:"backup",flow:"backup",label:"snapshot"},K);for(let z of $)Q(M,{source:`site:${j(z.name)}`,target:"backup",flow:"backup"},K);return{mode:"server",project:j(Z.project)||j(H.project?.name)||j(P.name,"project"),environment:j(Z.environment)||j(H.environment,"production"),provider:j(P.provider,"unknown"),region:j(P.region,"unknown"),generatedAt:new Date().toISOString(),layers:L,groups:[{id:"box",label:j(P.name,"App server"),sub:[j(P.provider),j(P.region),j(P.ip)].filter(Boolean).join(" · ")}],nodes:J,links:M,notes:E}}function p(H,Z={}){let J=[],M=[],E=[],P=H.app??{},$=Array.isArray(H.functions)?H.functions:[],O=Array.isArray(H.queues)?H.queues:[],Y=H.metrics??{};if(!$.length)E.push("No Lambda functions were read for this environment, so the compute layer is empty rather than assumed.");J.push({id:"internet",label:"Internet",kind:"internet",layer:0,status:"ok",sub:"Public traffic",facts:[],external:!0});let I=j(P.url),b=I.replace(/^https?:\/\//,"").split("/")[0];J.push({id:"dns",label:b||"Application domain",kind:"dns",layer:1,status:b?"ok":"unknown",sub:"DNS & certificates",facts:[{label:"Endpoint",value:I||"not resolved"}],external:!0});let _=H.waf;if(_)J.push({id:"waf",label:"WAF",kind:"waf",layer:2,status:D(_.status??"active"),sub:j(_.scope,"Managed rules"),facts:[{label:"Web ACL",value:j(_.name,"unnamed")},..._.blocked!=null?[{label:"Blocked (24h)",value:String(_.blocked)}]:[],{label:"Rules",value:String(h(H.wafRules))}],href:"/serverless/firewall"});let W=H.assetsInfo;if(W)J.push({id:"cdn",label:"Asset CDN",kind:"cdn",layer:2,status:"ok",sub:j(W.cdn,"CloudFront"),facts:[{label:"Distribution",value:j(W.cdn,"unknown")},{label:"Custom domain",value:j(W.customDomain,"none")}],href:"/serverless/assets"}),J.push({id:"assets",label:"Asset bucket",kind:"storage",layer:6,status:"ok",sub:j(W.bucket,"S3"),facts:[{label:"Bucket",value:j(W.bucket,"unknown")},...W.files?[{label:"Objects",value:String(W.files)}]:[],...W.sizeMb?[{label:"Size",value:`${W.sizeMb} MB`}]:[]],href:"/serverless/assets"});let q=$.find((G)=>j(G.key).startsWith("http"));J.push({id:"gateway",label:"HTTP entry point",kind:"gateway",layer:3,status:q?"ok":"unknown",sub:"Function URL / API Gateway",facts:[{label:"Endpoint",value:I||"not resolved"},{label:"Invocations (24h)",value:String(Y.invocations??0)},...Y.errorRatePct!=null?[{label:"Error rate",value:`${Y.errorRatePct}%`}]:[]],href:"/serverless/metrics"});for(let G of $){let N=`fn:${j(G.name)}`;if(!j(G.name))continue;let F=Number(G.errors??0),R=Number(G.invocations??0);J.push({id:N,label:j(G.key,j(G.name)),kind:"function",layer:4,status:F>0?R&&F/R>0.02?"bad":"warn":R?"ok":"idle",sub:j(G.runtime,"lambda"),facts:[{label:"Function",value:j(G.name)},{label:"Memory",value:`${G.memory??0} MB`},{label:"Timeout",value:`${G.timeout??0}s`},{label:"Invocations (24h)",value:String(R)},{label:"Errors (24h)",value:String(F)},{label:"p95",value:`${G.p95??0} ms`},...G.provisioned?[{label:"Provisioned",value:j(G.provisioned)}]:[]],href:"/serverless/functions"})}for(let G of O){let N=`queue:${j(G.name)}`;if(!j(G.name))continue;let F=Number(G.dlq??0);J.push({id:N,label:j(G.name),kind:"queue",layer:5,status:F>0?"bad":Number(G.visible??0)>0?"warn":"ok",sub:"SQS",facts:[{label:"Visible",value:String(G.visible??0)},{label:"In flight",value:String(G.inFlight??0)},{label:"Processed (24h)",value:String(G.processed??0)},{label:"Dead letter",value:String(F)}],href:"/serverless/queues"})}let X=H.aurora;if(X)J.push({id:"database",label:"Aurora Serverless",kind:"database",layer:6,status:D(X.status),sub:j(X.engine,"aurora"),facts:[{label:"Cluster",value:j(X.id,"unknown")},{label:"Capacity",value:`${X.currentAcu??0} ACU (${X.minAcu??0}–${X.maxAcu??0})`},{label:"Connections",value:String(X.connections??0)}],href:"/serverless/data"});let T=H.proxy;if(T)J.push({id:"rds-proxy",label:"RDS Proxy",kind:"database",layer:5,status:D(T.status),sub:"Connection pooling",facts:[{label:"Proxy",value:j(T.name,"unknown")},{label:"Endpoint",value:j(T.endpoint,"unknown")},{label:"Pooled",value:String(T.pooledConns??0)}],href:"/serverless/data"});let A=H.redis;if(A)J.push({id:"cache",label:"ElastiCache",kind:"cache",layer:6,status:D(A.status),sub:j(A.node,"redis"),facts:[{label:"Group",value:j(A.id,"unknown")},{label:"Hit rate",value:`${A.hitRate??0}%`}],href:"/serverless/data"});let C=H.efs;if(C)J.push({id:"efs",label:"EFS",kind:"filesystem",layer:6,status:D(C.status),sub:j(C.mount,"/mnt/local"),facts:[{label:"File system",value:j(C.id,"unknown")},{label:"Mount",value:j(C.mount,"unknown")},{label:"Size",value:`${C.sizeMb??0} MB`}],href:"/data/volumes"});let g=H.scheduler??{};if(g.enabled)J.push({id:"scheduler",label:"Scheduler",kind:"scheduler",layer:3,status:"ok",sub:j(g.expression,"rate(1 minute)"),facts:[{label:"Expression",value:j(g.expression,"unknown")},{label:"Last run",value:j(g.lastRun,"unknown")}],href:"/operations/jobs"});let U=new Set(J.map((G)=>G.id)),V=U.has("waf")?"waf":"gateway";Q(M,{source:"internet",target:"dns",flow:"request",label:"https"},U),Q(M,{source:"dns",target:V,flow:"request"},U),Q(M,{source:"dns",target:"cdn",flow:"request",label:"assets"},U),Q(M,{source:"waf",target:"gateway",flow:"request",label:"allowed"},U),Q(M,{source:"cdn",target:"assets",flow:"data",label:"origin"},U);let K=$.filter((G)=>j(G.key).startsWith("http")),S=$.filter((G)=>j(G.key).startsWith("queue")),z=$.filter((G)=>j(G.key).startsWith("cli"));for(let G of K)Q(M,{source:"gateway",target:`fn:${j(G.name)}`,flow:"request",label:"invoke"},U);for(let G of z)Q(M,{source:"scheduler",target:`fn:${j(G.name)}`,flow:"async",label:"schedule"},U);for(let G of O){for(let N of K)Q(M,{source:`fn:${j(N.name)}`,target:`queue:${j(G.name)}`,flow:"async",label:"publish"},U);for(let N of S)Q(M,{source:`queue:${j(G.name)}`,target:`fn:${j(N.name)}`,flow:"async",label:"consume"},U)}let B=["rds-proxy","database","cache","efs","assets"];for(let G of $){let N=`fn:${j(G.name)}`;if(U.has("rds-proxy"))Q(M,{source:N,target:"rds-proxy",flow:"data",label:"pooled"},U);else Q(M,{source:N,target:"database",flow:"data",label:"sql"},U);for(let F of B.filter((R)=>R!=="rds-proxy"&&R!=="database"))Q(M,{source:N,target:F,flow:"data"},U)}return Q(M,{source:"rds-proxy",target:"database",flow:"data",label:"sql"},U),{mode:"serverless",project:j(Z.project)||j(P.name,"application"),environment:j(Z.environment)||j(P.env,"production"),provider:"aws",region:j(P.region,"unknown"),generatedAt:new Date().toISOString(),layers:m,groups:[],nodes:J,links:M,notes:E}}
|
|
2
|
+
export{v as hg,p as ig};
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import{ch as y,dh as b}from"./chunk-xyt490vp.js";import{pp as H}from"./chunk-c8sypnbe.js";import*as J from"node:crypto";import{readFileSync as m}from"node:fs";import{readdir as d}from"node:fs/promises";import{join as p}from"node:path";function f(_){if(_){let C=h(_);if(!C)throw Error(`AWS profile '${_}' not found in ~/.aws/credentials`);return C}let E=process.env.AWS_ACCESS_KEY_ID,W=process.env.AWS_SECRET_ACCESS_KEY;if(E&&W)return{accessKeyId:E,secretAccessKey:W,sessionToken:process.env.AWS_SESSION_TOKEN};return h(process.env.AWS_PROFILE||"default")??{accessKeyId:"",secretAccessKey:""}}function h(_){let{existsSync:E,readFileSync:W}=H("node:fs"),{homedir:C}=H("node:os"),{join:A}=H("node:path"),Y=process.env.AWS_SHARED_CREDENTIALS_FILE||A(C(),".aws","credentials");if(!E(Y))return null;let $=W(Y,"utf-8"),G=null,V,Z,Q;for(let N of $.split(`
|
|
2
|
+
`)){let L=N.trim();if(!L||L.startsWith("#")||L.startsWith(";"))continue;let w=L.match(/^\[([^\]]+)\]$/);if(w){if(G===_&&V&&Z)return{accessKeyId:V,secretAccessKey:Z,sessionToken:Q};G=w[1],V=void 0,Z=void 0,Q=void 0;continue}if(G===_){let[M,...U]=L.split("="),F=U.join("=").trim();switch(M.trim().toLowerCase()){case"aws_access_key_id":V=F;break;case"aws_secret_access_key":Z=F;break;case"aws_session_token":Q=F;break}}}if(G===_&&V&&Z)return{accessKeyId:V,secretAccessKey:Z,sessionToken:Q};return null}function g(_){let{buffer:E,byteOffset:W,byteLength:C}=_;if(E instanceof ArrayBuffer)return E.slice(W,W+C);let A=new ArrayBuffer(C);return new Uint8Array(A).set(new Uint8Array(_)),A}class l{client;region;explicitProfile;endpoint;endpointProtocol="https";forcePathStyle;explicitCredentials;constructor(_="us-east-1",E,W){let C=typeof _==="string"?W:_,A=typeof _==="string"?_:_.region??"us-east-1",Y=typeof _==="string"?E:_.profile,$=C?.endpoint?y({region:A,path:"/",endpoint:C.endpoint}):void 0;this.region=A,this.explicitProfile=Y,this.endpoint=$?.host,this.endpointProtocol=$?.protocol??"https",this.forcePathStyle=C?.forcePathStyle,this.explicitCredentials=C?.credentials,this.client=new b(C?.credentials,{profile:Y,endpoint:C?.endpoint,forcePathStyle:C?.forcePathStyle})}getCredentials(){if(this.explicitCredentials?.accessKeyId&&this.explicitCredentials.secretAccessKey)return this.explicitCredentials;let _=f(this.explicitProfile);if(_.accessKeyId&&_.secretAccessKey)return _;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(_){return this.forcePathStyle?this.s3BaseHost():`${_}.${this.s3BaseHost()}`}objectPath(_,E){return this.forcePathStyle?`/${_}/${E}`:`/${E}`}objectUrl(_,E){return`${this.endpointProtocol}://${this.s3VirtualHost(_)}${this.objectPath(_,E)}`}async listBuckets(){let _=await this.client.request({service:"s3",region:this.region,method:"GET",path:"/"}),E=[],C=(_?.ListAllMyBucketsResult??_)?.Buckets?.Bucket;if(C){let A=Array.isArray(C)?C:[C];for(let Y of A)E.push({Name:Y.Name,CreationDate:Y.CreationDate})}return{Buckets:E}}async createBucket(_,E){let W={};if(E?.acl)W["x-amz-acl"]=E.acl;let C;if(this.region!=="us-east-1"&&!this.endpoint)C=`<?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>`,W["Content-Type"]="application/xml";await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}`,headers:W,body:C})}async deleteBucket(_){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${_}`})}async emptyAndDeleteBucket(_){let E=!0;while(E){let W=await this.listAllObjects({bucket:_});if(W.length===0){E=!1;break}let C=W.map((A)=>A.Key);for(let A=0;A<C.length;A+=1000){let Y=C.slice(A,A+1000);await this.deleteObjects(_,Y)}}await this.deleteBucket(_)}async listAllObjects(_){let E=[],W;do{let C={"list-type":"2","max-keys":"1000"};if(_.prefix)C.prefix=_.prefix;if(W)C["continuation-token"]=W;let A=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_.bucket}`,queryParams:C}),Y=A?.ListBucketResult??A,$=Y?.Contents;if($){let V=Array.isArray($)?$:[$];for(let Z of V)E.push({Key:Z.Key,LastModified:Z.LastModified||"",Size:Number.parseInt(Z.Size||"0"),ETag:Z.ETag})}let G=Y?.IsTruncated;W=G==="true"||G===!0?Y?.NextContinuationToken:void 0}while(W);return E}async list(_){let E=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_.bucket}`}),W=[],A=(E?.ListBucketResult??E)?.Contents;if(A){let Y=Array.isArray(A)?A:[A];for(let $ of Y){if(_.prefix&&!$.Key?.startsWith(_.prefix))continue;if(W.push({Key:$.Key||"",LastModified:$.LastModified||"",Size:Number.parseInt($.Size||"0"),ETag:$.ETag}),_.maxKeys&&W.length>=_.maxKeys)break}}return W}async putObject(_){let E={};if(_.acl)E["x-amz-acl"]=_.acl;if(_.cacheControl)E["Cache-Control"]=_.cacheControl;if(_.contentType)E["Content-Type"]=_.contentType;if(_.metadata)for(let[A,Y]of Object.entries(_.metadata))E[`x-amz-meta-${A}`]=Y;let W=_.key.split("/").map((A)=>encodeURIComponent(A)).join("/"),C=_.body instanceof Uint8Array&&!Buffer.isBuffer(_.body)?Buffer.from(_.body):_.body;if(Buffer.isBuffer(C)||C instanceof Uint8Array){let A=Buffer.isBuffer(C)?C:Buffer.from(C),{accessKeyId:Y,secretAccessKey:$,sessionToken:G}=this.getCredentials(),V=this.s3VirtualHost(_.bucket),Z=this.objectPath(_.bucket,W),Q=this.objectUrl(_.bucket,W),N=new Date,L=N.toISOString().replace(/[:-]|\.\d{3}/g,""),w=N.toISOString().slice(0,10).replace(/-/g,""),M=J.createHash("sha256").update(A).digest("hex"),U={host:V,"x-amz-date":L,"x-amz-content-sha256":M,...E};if(G)U["x-amz-security-token"]=G;let F=Object.keys(U).sort().map((B)=>`${B.toLowerCase()}:${U[B].trim()}
|
|
6
|
+
`).join(""),x=Object.keys(U).sort().map((B)=>B.toLowerCase()).join(";"),I=["PUT",Z,"",F,x,M].join(`
|
|
7
|
+
`),z="AWS4-HMAC-SHA256",P=`${w}/${this.region}/s3/aws4_request`,K=[z,L,P,J.createHash("sha256").update(I).digest("hex")].join(`
|
|
8
|
+
`),v=J.createHmac("sha256",`AWS4${$}`).update(w).digest(),X=J.createHmac("sha256",v).update(this.region).digest(),O=J.createHmac("sha256",X).update("s3").digest(),j=J.createHmac("sha256",O).update("aws4_request").digest(),T=J.createHmac("sha256",j).update(K).digest("hex"),R=`${z} Credential=${Y}/${P}, SignedHeaders=${x}, Signature=${T}`,D=await fetch(Q,{method:"PUT",headers:{...U,Authorization:R},body:g(A)});if(!D.ok){let B=await D.text();throw Error(`S3 PUT failed: ${D.status} ${B}`)}return}await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${W}`,bucket:_.bucket,headers:E,body:_.body})}async getObject(_,E){let W=E.split("/").map((A)=>encodeURIComponent(A)).join("/");return await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${W}`,bucket:_,rawResponse:!0})}async getObjectBytes(_,E){let{accessKeyId:W,secretAccessKey:C,sessionToken:A}=this.getCredentials(),Y=this.s3VirtualHost(_),$=E.split("/").map((B)=>encodeURIComponent(B)).join("/"),G=this.objectPath(_,$),V=this.objectUrl(_,$),Z=new Date,Q=Z.toISOString().replace(/[:-]|\.\d{3}/g,""),N=Z.toISOString().slice(0,10).replace(/-/g,""),L=J.createHash("sha256").update("").digest("hex"),w={host:Y,"x-amz-date":Q,"x-amz-content-sha256":L};if(A)w["x-amz-security-token"]=A;let M=Object.keys(w).sort().map((B)=>`${B.toLowerCase()}:${w[B].trim()}
|
|
9
|
+
`).join(""),U=Object.keys(w).sort().map((B)=>B.toLowerCase()).join(";"),F=["GET",G,"",M,U,L].join(`
|
|
10
|
+
`),x="AWS4-HMAC-SHA256",I=`${N}/${this.region}/s3/aws4_request`,z=[x,Q,I,J.createHash("sha256").update(F).digest("hex")].join(`
|
|
11
|
+
`),P=J.createHmac("sha256",`AWS4${C}`).update(N).digest(),K=J.createHmac("sha256",P).update(this.region).digest(),v=J.createHmac("sha256",K).update("s3").digest(),X=J.createHmac("sha256",v).update("aws4_request").digest(),O=J.createHmac("sha256",X).update(z).digest("hex"),j=`${x} Credential=${W}/${I}, SignedHeaders=${U}, Signature=${O}`,T=await fetch(V,{method:"GET",headers:{...w,Authorization:j}});if(!T.ok){let B=await T.text();throw Error(`S3 GET failed: ${T.status} ${B}`)}let R=await T.arrayBuffer(),D=T.headers.get("content-length");return{body:new Uint8Array(R),contentType:T.headers.get("content-type")??void 0,contentLength:D?Number.parseInt(D,10):void 0}}async copyObject(_){let E={"x-amz-copy-source":`/${_.sourceBucket}/${_.sourceKey}`};if(_.metadataDirective)E["x-amz-metadata-directive"]=_.metadataDirective;if(_.contentType)E["Content-Type"]=_.contentType;if(_.metadata)for(let[W,C]of Object.entries(_.metadata))E[`x-amz-meta-${W}`]=C;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_.destinationBucket}/${_.destinationKey}`,headers:E})}async deleteObject(_,E){let W=E.split("/").map((C)=>encodeURIComponent(C)).join("/");await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${W}`,bucket:_})}async deleteObjects(_,E){let W=`<?xml version="1.0" encoding="UTF-8"?>
|
|
12
|
+
<Delete>
|
|
13
|
+
${E.map((A)=>`<Object><Key>${A}</Key></Object>`).join(`
|
|
14
|
+
`)}
|
|
15
|
+
</Delete>`,C=J.createHash("md5").update(W).digest("base64");await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${_}`,queryParams:{delete:""},body:W,headers:{"Content-Type":"application/xml","Content-MD5":C}})}async bucketExists(_){try{return await this.client.request({service:"s3",region:this.region,method:"HEAD",path:`/${_}`}),!0}catch{return!1}}async copy(_){let E=m(_.source);await this.putObject({bucket:_.bucket,key:_.key,body:E,acl:_.acl,cacheControl:_.cacheControl,contentType:_.contentType,metadata:_.metadata})}async sync(_){let E=await this.listFilesRecursive(_.source);for(let W of E){if(_.exclude&&_.exclude.some((Y)=>W.includes(Y)))continue;if(_.include&&!_.include.some((Y)=>W.includes(Y)))continue;let C=W.substring(_.source.length+1),A=_.prefix?`${_.prefix}/${C}`:C;if(!_.dryRun){let Y=m(W);await this.putObject({bucket:_.bucket,key:A,body:Y,acl:_.acl,cacheControl:_.cacheControl,contentType:_.contentType,metadata:_.metadata})}}}async delete(_,E){await this.deleteObject(_,E)}async deletePrefix(_,E){let C=(await this.list({bucket:_,prefix:E})).map((A)=>A.Key);if(C.length>0)await this.deleteObjects(_,C)}async getBucketSize(_,E){return(await this.list({bucket:_,prefix:E})).reduce((C,A)=>C+A.Size,0)}async listFilesRecursive(_){let E=[],W=await d(_,{withFileTypes:!0});for(let C of W){let A=p(_,C.name);if(C.isDirectory()){let Y=await this.listFilesRecursive(A);E.push(...Y)}else E.push(A)}return E}async putBucketPolicy(_,E){let{accessKeyId:W,secretAccessKey:C,sessionToken:A}=this.getCredentials(),Y=this.s3BaseHost(),$=typeof E==="string"?E:JSON.stringify(E),G=new Date,V=G.toISOString().replace(/[:-]|\.\d{3}/g,""),Z=G.toISOString().slice(0,10).replace(/-/g,""),Q=J.createHash("sha256").update($).digest("hex"),N="/"+_,L="policy=",w={host:Y,"x-amz-date":V,"x-amz-content-sha256":Q,"content-type":"application/json"};if(A)w["x-amz-security-token"]=A;let M=Object.keys(w).sort().map((D)=>`${D.toLowerCase()}:${w[D].trim()}
|
|
16
|
+
`).join(""),U=Object.keys(w).sort().map((D)=>D.toLowerCase()).join(";"),F=["PUT",N,"policy=",M,U,Q].join(`
|
|
17
|
+
`),x="AWS4-HMAC-SHA256",I=`${Z}/${this.region}/s3/aws4_request`,z=[x,V,I,J.createHash("sha256").update(F).digest("hex")].join(`
|
|
18
|
+
`),P=J.createHmac("sha256","AWS4"+C).update(Z).digest(),K=J.createHmac("sha256",P).update(this.region).digest(),v=J.createHmac("sha256",K).update("s3").digest(),X=J.createHmac("sha256",v).update("aws4_request").digest(),O=J.createHmac("sha256",X).update(z).digest("hex"),j=`${x} Credential=${W}/${I}, SignedHeaders=${U}, Signature=${O}`,T=`${this.endpointProtocol}://${Y}${N}?policy=`,R=await fetch(T,{method:"PUT",headers:{...w,Authorization:j},body:$});if(!R.ok){let D=await R.text();throw Error(`Failed to put bucket policy: ${R.status} ${D}`)}}async getBucketPolicy(_){let{accessKeyId:E,secretAccessKey:W,sessionToken:C}=this.getCredentials(),A=this.s3BaseHost(),Y=new Date,$=Y.toISOString().replace(/[:-]|\.\d{3}/g,""),G=Y.toISOString().slice(0,10).replace(/-/g,""),V=J.createHash("sha256").update("").digest("hex"),Z="/"+_,Q="policy=",N={host:A,"x-amz-date":$,"x-amz-content-sha256":V};if(C)N["x-amz-security-token"]=C;let L=Object.keys(N).sort().map((R)=>`${R.toLowerCase()}:${N[R].trim()}
|
|
19
|
+
`).join(""),w=Object.keys(N).sort().map((R)=>R.toLowerCase()).join(";"),M=["GET",Z,"policy=",L,w,V].join(`
|
|
20
|
+
`),U="AWS4-HMAC-SHA256",F=`${G}/${this.region}/s3/aws4_request`,x=[U,$,F,J.createHash("sha256").update(M).digest("hex")].join(`
|
|
21
|
+
`),I=J.createHmac("sha256","AWS4"+W).update(G).digest(),z=J.createHmac("sha256",I).update(this.region).digest(),P=J.createHmac("sha256",z).update("s3").digest(),K=J.createHmac("sha256",P).update("aws4_request").digest(),v=J.createHmac("sha256",K).update(x).digest("hex"),X=`${U} Credential=${E}/${F}, SignedHeaders=${w}, Signature=${v}`,O=`${this.endpointProtocol}://${A}${Z}?policy=`,j=await fetch(O,{method:"GET",headers:{...N,Authorization:X}});if(j.status===404)return null;if(!j.ok){let R=await j.text();throw Error(`Failed to get bucket policy: ${j.status} ${R}`)}let T=await j.text();return JSON.parse(T)}async deleteBucketPolicy(_){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${_}`,queryParams:{policy:""}})}async headBucket(_){try{return{exists:!0,region:(await this.client.request({service:"s3",region:this.region,method:"HEAD",path:`/${_}`,returnHeaders:!0}))?.headers?.["x-amz-bucket-region"]}}catch(E){if(E.statusCode===404)return{exists:!1};throw E}}async headObject(_,E){try{let W=await this.client.request({service:"s3",region:this.region,method:"HEAD",path:`/${_}/${E}`,returnHeaders:!0});return{ContentLength:W?.headers?.["content-length"]?parseInt(W.headers["content-length"]):void 0,ContentType:W?.headers?.["content-type"],ETag:W?.headers?.etag,LastModified:W?.headers?.["last-modified"]}}catch(W){if(W.statusCode===404)return null;throw W}}async getObjectBuffer(_,E){let W=await this.getObject(_,E);return Buffer.from(W)}async getObjectJson(_,E){let W=await this.getObject(_,E);return JSON.parse(W)}async putObjectJson(_,E,W,C){await this.putObject({bucket:_,key:E,body:JSON.stringify(W),contentType:"application/json",...C})}async getBucketVersioning(_){return{Status:(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}`,queryParams:{versioning:""}}))?.VersioningConfiguration?.Status}}async putBucketVersioning(_,E){let W=`<?xml version="1.0" encoding="UTF-8"?>
|
|
22
|
+
<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
23
|
+
<Status>${E}</Status>
|
|
24
|
+
</VersioningConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}`,queryParams:{versioning:""},headers:{"Content-Type":"application/xml"},body:W})}async getBucketLifecycleConfiguration(_){try{return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}`,queryParams:{lifecycle:""}}))?.LifecycleConfiguration}catch(E){if(E.statusCode===404)return null;throw E}}async putBucketLifecycleConfiguration(_,E){let C=`<?xml version="1.0" encoding="UTF-8"?>
|
|
25
|
+
<LifecycleConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
26
|
+
${E.map((A)=>{let Y=`<Rule><ID>${A.ID}</ID><Status>${A.Status}</Status>`;if(A.Filter)Y+=`<Filter><Prefix>${A.Filter.Prefix||""}</Prefix></Filter>`;else Y+="<Filter><Prefix></Prefix></Filter>";if(A.Expiration){if(A.Expiration.Days)Y+=`<Expiration><Days>${A.Expiration.Days}</Days></Expiration>`;else if(A.Expiration.Date)Y+=`<Expiration><Date>${A.Expiration.Date}</Date></Expiration>`}if(A.Transitions)for(let $ of A.Transitions)Y+=`<Transition><Days>${$.Days}</Days><StorageClass>${$.StorageClass}</StorageClass></Transition>`;if(A.NoncurrentVersionExpiration)Y+=`<NoncurrentVersionExpiration><NoncurrentDays>${A.NoncurrentVersionExpiration.NoncurrentDays}</NoncurrentDays></NoncurrentVersionExpiration>`;return Y+="</Rule>",Y}).join("")}
|
|
27
|
+
</LifecycleConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}`,queryParams:{lifecycle:""},headers:{"Content-Type":"application/xml"},body:C})}async deleteBucketLifecycleConfiguration(_){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${_}`,queryParams:{lifecycle:""}})}async getBucketCors(_){try{return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}`,queryParams:{cors:""}}))?.CORSConfiguration}catch(E){if(E.statusCode===404)return null;throw E}}async putBucketCors(_,E){let C=`<?xml version="1.0" encoding="UTF-8"?>
|
|
28
|
+
<CORSConfiguration>
|
|
29
|
+
${E.map((A)=>{let Y="<CORSRule>";for(let $ of A.AllowedOrigins)Y+=`<AllowedOrigin>${$}</AllowedOrigin>`;for(let $ of A.AllowedMethods)Y+=`<AllowedMethod>${$}</AllowedMethod>`;if(A.AllowedHeaders)for(let $ of A.AllowedHeaders)Y+=`<AllowedHeader>${$}</AllowedHeader>`;if(A.ExposeHeaders)for(let $ of A.ExposeHeaders)Y+=`<ExposeHeader>${$}</ExposeHeader>`;if(A.MaxAgeSeconds)Y+=`<MaxAgeSeconds>${A.MaxAgeSeconds}</MaxAgeSeconds>`;return Y+="</CORSRule>",Y}).join("")}
|
|
30
|
+
</CORSConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}`,queryParams:{cors:""},headers:{"Content-Type":"application/xml"},body:C})}async deleteBucketCors(_){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${_}`,queryParams:{cors:""}})}async getBucketEncryption(_){try{return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}`,queryParams:{encryption:""}}))?.ServerSideEncryptionConfiguration}catch(E){if(E.statusCode===404)return null;throw E}}async putBucketEncryption(_,E,W){let C=`<ApplyServerSideEncryptionByDefault><SSEAlgorithm>${E}</SSEAlgorithm>`;if(W)C+=`<KMSMasterKeyID>${W}</KMSMasterKeyID>`;C+="</ApplyServerSideEncryptionByDefault>";let A=`<?xml version="1.0" encoding="UTF-8"?>
|
|
31
|
+
<ServerSideEncryptionConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
32
|
+
<Rule>${C}</Rule>
|
|
33
|
+
</ServerSideEncryptionConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}`,queryParams:{encryption:""},headers:{"Content-Type":"application/xml"},body:A})}async deleteBucketEncryption(_){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${_}`,queryParams:{encryption:""}})}async getBucketTagging(_){try{let W=(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}`,queryParams:{tagging:""}}))?.Tagging?.TagSet?.Tag;if(!W)return[];return Array.isArray(W)?W:[W]}catch(E){if(E.statusCode===404)return[];throw E}}async putBucketTagging(_,E){let C=`<?xml version="1.0" encoding="UTF-8"?>
|
|
34
|
+
<Tagging>
|
|
35
|
+
<TagSet>${E.map((A)=>`<Tag><Key>${A.Key}</Key><Value>${A.Value}</Value></Tag>`).join("")}</TagSet>
|
|
36
|
+
</Tagging>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}`,queryParams:{tagging:""},headers:{"Content-Type":"application/xml"},body:C})}async deleteBucketTagging(_){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${_}`,queryParams:{tagging:""}})}async getObjectTagging(_,E){try{let C=(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}/${E}`,queryParams:{tagging:""}}))?.Tagging?.TagSet?.Tag;if(!C)return[];return Array.isArray(C)?C:[C]}catch(W){if(W.statusCode===404)return[];throw W}}async putObjectTagging(_,E,W){let A=`<?xml version="1.0" encoding="UTF-8"?>
|
|
37
|
+
<Tagging>
|
|
38
|
+
<TagSet>${W.map((Y)=>`<Tag><Key>${Y.Key}</Key><Value>${Y.Value}</Value></Tag>`).join("")}</TagSet>
|
|
39
|
+
</Tagging>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}/${E}`,queryParams:{tagging:""},headers:{"Content-Type":"application/xml"},body:A})}async deleteObjectTagging(_,E){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${_}/${E}`,queryParams:{tagging:""}})}async getBucketAcl(_){return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}`,queryParams:{acl:""}}))?.AccessControlPolicy}async putBucketAcl(_,E){await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}`,queryParams:{acl:""},headers:{"x-amz-acl":E}})}async getObjectAcl(_,E){return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}/${E}`,queryParams:{acl:""}}))?.AccessControlPolicy}async putObjectAcl(_,E,W){await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}/${E}`,queryParams:{acl:""},headers:{"x-amz-acl":W}})}async getBucketLocation(_){return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}`,queryParams:{location:""}}))?.LocationConstraint||"us-east-1"}async getBucketLogging(_){return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}`,queryParams:{logging:""}}))?.BucketLoggingStatus}async putBucketLogging(_,E,W){let C=`<?xml version="1.0" encoding="UTF-8"?>
|
|
40
|
+
<BucketLoggingStatus xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
41
|
+
<LoggingEnabled>
|
|
42
|
+
<TargetBucket>${E}</TargetBucket>
|
|
43
|
+
<TargetPrefix>${W}</TargetPrefix>
|
|
44
|
+
</LoggingEnabled>
|
|
45
|
+
</BucketLoggingStatus>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}`,queryParams:{logging:""},headers:{"Content-Type":"application/xml"},body:C})}async getBucketNotificationConfiguration(_){return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}`,queryParams:{notification:""}}))?.NotificationConfiguration}async putBucketNotificationConfiguration(_,E){let W="";if(E.LambdaFunctionConfigurations)for(let A of E.LambdaFunctionConfigurations){if(W+="<CloudFunctionConfiguration>",A.Id)W+=`<Id>${A.Id}</Id>`;W+=`<CloudFunction>${A.LambdaFunctionArn}</CloudFunction>`;for(let Y of A.Events)W+=`<Event>${Y}</Event>`;if(A.Filter?.Key?.FilterRules){W+="<Filter><S3Key>";for(let Y of A.Filter.Key.FilterRules)W+=`<FilterRule><Name>${Y.Name}</Name><Value>${Y.Value}</Value></FilterRule>`;W+="</S3Key></Filter>"}W+="</CloudFunctionConfiguration>"}if(E.TopicConfigurations)for(let A of E.TopicConfigurations){if(W+="<TopicConfiguration>",A.Id)W+=`<Id>${A.Id}</Id>`;W+=`<Topic>${A.TopicArn}</Topic>`;for(let Y of A.Events)W+=`<Event>${Y}</Event>`;W+="</TopicConfiguration>"}if(E.QueueConfigurations)for(let A of E.QueueConfigurations){if(W+="<QueueConfiguration>",A.Id)W+=`<Id>${A.Id}</Id>`;W+=`<Queue>${A.QueueArn}</Queue>`;for(let Y of A.Events)W+=`<Event>${Y}</Event>`;W+="</QueueConfiguration>"}let C=`<?xml version="1.0" encoding="UTF-8"?>
|
|
46
|
+
<NotificationConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
47
|
+
${W}
|
|
48
|
+
</NotificationConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}`,queryParams:{notification:""},headers:{"Content-Type":"application/xml"},body:C})}async getBucketWebsite(_){try{return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}`,queryParams:{website:""}}))?.WebsiteConfiguration}catch(E){if(E.statusCode===404)return null;throw E}}async putBucketWebsite(_,E){let W="";if(E.RedirectAllRequestsTo)W=`<RedirectAllRequestsTo>
|
|
49
|
+
<HostName>${E.RedirectAllRequestsTo.HostName}</HostName>
|
|
50
|
+
${E.RedirectAllRequestsTo.Protocol?`<Protocol>${E.RedirectAllRequestsTo.Protocol}</Protocol>`:""}
|
|
51
|
+
</RedirectAllRequestsTo>`;else if(W=`<IndexDocument><Suffix>${E.IndexDocument}</Suffix></IndexDocument>`,E.ErrorDocument)W+=`<ErrorDocument><Key>${E.ErrorDocument}</Key></ErrorDocument>`;let C=`<?xml version="1.0" encoding="UTF-8"?>
|
|
52
|
+
<WebsiteConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
53
|
+
${W}
|
|
54
|
+
</WebsiteConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}`,queryParams:{website:""},headers:{"Content-Type":"application/xml"},body:C})}async deleteBucketWebsite(_){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${_}`,queryParams:{website:""}})}async getBucketReplication(_){try{return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}`,queryParams:{replication:""}}))?.ReplicationConfiguration}catch(E){if(E.statusCode===404)return null;throw E}}async deleteBucketReplication(_){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${_}`,queryParams:{replication:""}})}async getPublicAccessBlock(_){try{return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}`,queryParams:{publicAccessBlock:""}}))?.PublicAccessBlockConfiguration}catch(E){if(E.statusCode===404)return null;throw E}}async putPublicAccessBlock(_,E){let W=`<?xml version="1.0" encoding="UTF-8"?>
|
|
55
|
+
<PublicAccessBlockConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
56
|
+
<BlockPublicAcls>${E.BlockPublicAcls??!0}</BlockPublicAcls>
|
|
57
|
+
<IgnorePublicAcls>${E.IgnorePublicAcls??!0}</IgnorePublicAcls>
|
|
58
|
+
<BlockPublicPolicy>${E.BlockPublicPolicy??!0}</BlockPublicPolicy>
|
|
59
|
+
<RestrictPublicBuckets>${E.RestrictPublicBuckets??!0}</RestrictPublicBuckets>
|
|
60
|
+
</PublicAccessBlockConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}`,queryParams:{publicAccessBlock:""},headers:{"Content-Type":"application/xml"},body:W})}async deletePublicAccessBlock(_){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${_}`,queryParams:{publicAccessBlock:""}})}generatePresignedGetUrl(_,E,W=3600){let{accessKeyId:C,secretAccessKey:A}=this.getCredentials(),Y=this.s3VirtualHost(_),$=new Date,G=$.toISOString().replace(/[:-]|\.\d{3}/g,""),V=$.toISOString().slice(0,10).replace(/-/g,""),Z=`${V}/${this.region}/s3/aws4_request`,Q=`${C}/${Z}`,N=E.split("/").map((P)=>encodeURIComponent(P)).join("/"),L=new URLSearchParams({"X-Amz-Algorithm":"AWS4-HMAC-SHA256","X-Amz-Credential":Q,"X-Amz-Date":G,"X-Amz-Expires":W.toString(),"X-Amz-SignedHeaders":"host"}),w=["GET",this.objectPath(_,N),L.toString(),`host:${Y}
|
|
61
|
+
`,"host","UNSIGNED-PAYLOAD"].join(`
|
|
62
|
+
`),M=["AWS4-HMAC-SHA256",G,Z,J.createHash("sha256").update(w).digest("hex")].join(`
|
|
63
|
+
`),U=J.createHmac("sha256",`AWS4${A}`).update(V).digest(),F=J.createHmac("sha256",U).update(this.region).digest(),x=J.createHmac("sha256",F).update("s3").digest(),I=J.createHmac("sha256",x).update("aws4_request").digest(),z=J.createHmac("sha256",I).update(M).digest("hex");return L.append("X-Amz-Signature",z),`${this.endpointProtocol}://${Y}${this.objectPath(_,N)}?${L.toString()}`}generatePresignedPutUrl(_,E,W,C=3600){let{accessKeyId:A,secretAccessKey:Y}=this.getCredentials(),$=this.s3VirtualHost(_),G=new Date,V=G.toISOString().replace(/[:-]|\.\d{3}/g,""),Z=G.toISOString().slice(0,10).replace(/-/g,""),Q=`${Z}/${this.region}/s3/aws4_request`,N=`${A}/${Q}`,L=E.split("/").map((K)=>encodeURIComponent(K)).join("/"),w=new URLSearchParams({"X-Amz-Algorithm":"AWS4-HMAC-SHA256","X-Amz-Credential":N,"X-Amz-Date":V,"X-Amz-Expires":C.toString(),"X-Amz-SignedHeaders":"content-type;host"}),M=["PUT",this.objectPath(_,L),w.toString(),`content-type:${W}
|
|
64
|
+
host:${$}
|
|
65
|
+
`,"content-type;host","UNSIGNED-PAYLOAD"].join(`
|
|
66
|
+
`),U=["AWS4-HMAC-SHA256",V,Q,J.createHash("sha256").update(M).digest("hex")].join(`
|
|
67
|
+
`),F=J.createHmac("sha256",`AWS4${Y}`).update(Z).digest(),x=J.createHmac("sha256",F).update(this.region).digest(),I=J.createHmac("sha256",x).update("s3").digest(),z=J.createHmac("sha256",I).update("aws4_request").digest(),P=J.createHmac("sha256",z).update(U).digest("hex");return w.append("X-Amz-Signature",P),`${this.endpointProtocol}://${$}${this.objectPath(_,L)}?${w.toString()}`}async createMultipartUpload(_,E,W){let C={};if(W?.contentType)C["Content-Type"]=W.contentType;if(W?.metadata)for(let[G,V]of Object.entries(W.metadata))C[`x-amz-meta-${G}`]=V;let A=E.split("/").map((G)=>encodeURIComponent(G)).join("/"),Y=await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${A}`,bucket:_,queryParams:{uploads:""},headers:C});return{UploadId:(Y?.InitiateMultipartUploadResult??Y)?.UploadId}}async uploadPart(_,E,W,C,A){let{accessKeyId:Y,secretAccessKey:$,sessionToken:G}=this.getCredentials(),V=this.s3VirtualHost(_),Z=E.split("/").map((q)=>encodeURIComponent(q)).join("/"),Q=this.objectPath(_,Z),N=`${this.objectUrl(_,Z)}?partNumber=${C}&uploadId=${encodeURIComponent(W)}`,L=new Date,w=L.toISOString().replace(/[:-]|\.\d{3}/g,""),M=L.toISOString().slice(0,10).replace(/-/g,""),U=J.createHash("sha256").update(A).digest("hex"),F={host:V,"x-amz-date":w,"x-amz-content-sha256":U};if(G)F["x-amz-security-token"]=G;let x=Object.keys(F).sort().map((q)=>`${q.toLowerCase()}:${F[q].trim()}
|
|
68
|
+
`).join(""),I=Object.keys(F).sort().map((q)=>q.toLowerCase()).join(";"),z=["PUT",Q,`partNumber=${C}&uploadId=${encodeURIComponent(W)}`,x,I,U].join(`
|
|
69
|
+
`),P="AWS4-HMAC-SHA256",K=`${M}/${this.region}/s3/aws4_request`,v=[P,w,K,J.createHash("sha256").update(z).digest("hex")].join(`
|
|
70
|
+
`),X=J.createHmac("sha256",`AWS4${$}`).update(M).digest(),O=J.createHmac("sha256",X).update(this.region).digest(),j=J.createHmac("sha256",O).update("s3").digest(),T=J.createHmac("sha256",j).update("aws4_request").digest(),R=J.createHmac("sha256",T).update(v).digest("hex"),D=`${P} Credential=${Y}/${K}, SignedHeaders=${I}, Signature=${R}`,B=await fetch(N,{method:"PUT",headers:{...F,Authorization:D},body:g(A)});if(!B.ok){let q=await B.text();throw Error(`Upload part failed: ${B.status} ${q}`)}return{ETag:B.headers.get("etag")||""}}async completeMultipartUpload(_,E,W,C){let A=E.split("/").map((G)=>encodeURIComponent(G)).join("/"),$=`<?xml version="1.0" encoding="UTF-8"?>
|
|
71
|
+
<CompleteMultipartUpload>${C.sort((G,V)=>G.PartNumber-V.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:`/${A}`,bucket:_,queryParams:{uploadId:W},headers:{"Content-Type":"application/xml"},body:$})}async abortMultipartUpload(_,E,W){let C=E.split("/").map((A)=>encodeURIComponent(A)).join("/");await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${C}`,bucket:_,queryParams:{uploadId:W}})}async listMultipartUploads(_){let E=await this.client.request({service:"s3",region:this.region,method:"GET",path:"/",bucket:_,queryParams:{uploads:""}}),W=(E?.ListMultipartUploadsResult??E)?.Upload;if(!W)return[];return(Array.isArray(W)?W:[W]).map((A)=>({Key:A.Key,UploadId:A.UploadId,Initiated:A.Initiated}))}async restoreObject(_,E,W,C="Standard"){let A=`<?xml version="1.0" encoding="UTF-8"?>
|
|
72
|
+
<RestoreRequest>
|
|
73
|
+
<Days>${W}</Days>
|
|
74
|
+
<GlacierJobParameters>
|
|
75
|
+
<Tier>${C}</Tier>
|
|
76
|
+
</GlacierJobParameters>
|
|
77
|
+
</RestoreRequest>`;await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${_}/${E}`,queryParams:{restore:""},headers:{"Content-Type":"application/xml"},body:A})}async selectObjectContent(_,E,W,C,A="JSON"){let Y="";if(C==="CSV")Y="<CSV><FileHeaderInfo>USE</FileHeaderInfo></CSV>";else if(C==="JSON")Y="<JSON><Type>DOCUMENT</Type></JSON>";else Y="<Parquet/>";let $="";if(A==="CSV")$="<CSV/>";else $="<JSON/>";let G=`<?xml version="1.0" encoding="UTF-8"?>
|
|
78
|
+
<SelectObjectContentRequest>
|
|
79
|
+
<Expression>${W}</Expression>
|
|
80
|
+
<ExpressionType>SQL</ExpressionType>
|
|
81
|
+
<InputSerialization>${Y}</InputSerialization>
|
|
82
|
+
<OutputSerialization>${$}</OutputSerialization>
|
|
83
|
+
</SelectObjectContentRequest>`;return await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${_}/${E}`,queryParams:{select:"","select-type":"2"},headers:{"Content-Type":"application/xml"},body:G,rawResponse:!0})}async getSignedUrl(_){let{bucket:E,key:W,expiresIn:C=3600,operation:A="getObject"}=_,{accessKeyId:Y,secretAccessKey:$,sessionToken:G}=this.getCredentials(),V=new Date,Z=V.toISOString().replace(/[:-]|\.\d{3}/g,""),Q=V.toISOString().slice(0,10).replace(/-/g,""),N=this.s3VirtualHost(E),L=A==="putObject"?"PUT":"GET",w="AWS4-HMAC-SHA256",M=`${Q}/${this.region}/s3/aws4_request`,F={"X-Amz-Algorithm":"AWS4-HMAC-SHA256","X-Amz-Credential":`${Y}/${M}`,"X-Amz-Date":Z,"X-Amz-Expires":C.toString(),"X-Amz-SignedHeaders":"host"};if(G)F["X-Amz-Security-Token"]=G;let I=Object.keys(F).sort().map((S)=>`${encodeURIComponent(S)}=${encodeURIComponent(F[S])}`).join("&"),z=W.split("/").map((S)=>encodeURIComponent(S)).join("/"),P=this.objectPath(E,z),K=`host:${N}
|
|
84
|
+
`,O=[L,P,I,K,"host","UNSIGNED-PAYLOAD"].join(`
|
|
85
|
+
`),j=["AWS4-HMAC-SHA256",Z,M,J.createHash("sha256").update(O).digest("hex")].join(`
|
|
86
|
+
`),T=J.createHmac("sha256",`AWS4${$}`).update(Q).digest(),R=J.createHmac("sha256",T).update(this.region).digest(),D=J.createHmac("sha256",R).update("s3").digest(),B=J.createHmac("sha256",D).update("aws4_request").digest(),q=J.createHmac("sha256",B).update(j).digest("hex");return`${this.endpointProtocol}://${N}${P}?${I}&X-Amz-Signature=${q}`}async listObjects(_){let{bucket:E,prefix:W,maxKeys:C=1000,continuationToken:A}=_,Y={"list-type":"2","max-keys":C.toString()};if(W)Y.prefix=W;if(A)Y["continuation-token"]=A;let $=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${E}`,queryParams:Y}),G=[],V=$?.ListBucketResult??$;if(V?.Contents){let Z=Array.isArray(V.Contents)?V.Contents:[V.Contents];for(let Q of Z)G.push({Key:Q.Key||"",LastModified:Q.LastModified||"",Size:Number.parseInt(Q.Size||"0"),ETag:Q.ETag})}return{objects:G,nextContinuationToken:V?.NextContinuationToken}}async emptyBucket(_){let E=0,W=await this.listAllObjects({bucket:_});if(W.length>0)for(let C=0;C<W.length;C+=1000){let Y=W.slice(C,C+1000).map(($)=>$.Key);await this.deleteObjects(_,Y),E+=Y.length}try{let C,A;do{let Y=await this.listObjectVersions({bucket:_,keyMarker:C,versionIdMarker:A,maxKeys:1000}),$=[];if(Y.versions)for(let G of Y.versions)$.push({Key:G.Key,VersionId:G.VersionId});if(Y.deleteMarkers)for(let G of Y.deleteMarkers)$.push({Key:G.Key,VersionId:G.VersionId});if($.length>0)await this.deleteObjectVersions(_,$),E+=$.length;C=Y.nextKeyMarker,A=Y.nextVersionIdMarker}while(C)}catch{}return{deletedCount:E}}async listObjectVersions(_){let{bucket:E,prefix:W,keyMarker:C,versionIdMarker:A,maxKeys:Y=1000}=_,$={versions:"","max-keys":Y.toString()};if(W)$.prefix=W;if(C)$["key-marker"]=C;if(A)$["version-id-marker"]=A;let G=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${E}`,queryParams:$}),V=[],Z=[];if(G.Version){let Q=Array.isArray(G.Version)?G.Version:[G.Version];for(let N of Q)V.push({Key:N.Key,VersionId:N.VersionId,IsLatest:N.IsLatest==="true"})}if(G.DeleteMarker){let Q=Array.isArray(G.DeleteMarker)?G.DeleteMarker:[G.DeleteMarker];for(let N of Q)Z.push({Key:N.Key,VersionId:N.VersionId,IsLatest:N.IsLatest==="true"})}return{versions:V,deleteMarkers:Z,nextKeyMarker:G.NextKeyMarker,nextVersionIdMarker:G.NextVersionIdMarker}}async deleteObjectVersions(_,E){let W=`<?xml version="1.0" encoding="UTF-8"?>
|
|
87
|
+
<Delete>
|
|
88
|
+
<Quiet>true</Quiet>
|
|
89
|
+
${E.map((A)=>`<Object><Key>${A.Key}</Key>${A.VersionId?`<VersionId>${A.VersionId}</VersionId>`:""}</Object>`).join(`
|
|
90
|
+
`)}
|
|
91
|
+
</Delete>`,C=J.createHash("md5").update(W).digest("base64");await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${_}`,queryParams:{delete:""},body:W,headers:{"Content-Type":"application/xml","Content-MD5":C}})}}
|
|
92
|
+
export{f as pg,l as qg};
|