@stacksjs/ts-cloud 0.16.18 → 0.16.19
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-cnbvm43k.js → chunk-0f1qpmd6.js} +2 -2
- package/dist/bin/{chunk-dk9f6h0m.js → chunk-28ztnqjk.js} +1 -1
- package/dist/bin/chunk-3ay4kfaw.js +1 -0
- package/dist/bin/{chunk-eyvxsaaz.js → chunk-48x0wc2g.js} +1 -1
- package/dist/bin/{chunk-nrrprf04.js → chunk-4sa22raw.js} +2 -2
- package/dist/bin/{chunk-ezhbcpw1.js → chunk-6d8chxyr.js} +1 -1
- package/dist/bin/{chunk-nagvc7e4.js → chunk-7thhxyzy.js} +1 -1
- package/dist/bin/{chunk-qxwkg8yg.js → chunk-apnhhfkj.js} +1 -1
- package/dist/bin/{chunk-gfnw9nhq.js → chunk-e55fdn0r.js} +35 -35
- package/dist/bin/{chunk-acqj5mfq.js → chunk-ehb9mpt8.js} +3 -3
- package/dist/bin/{chunk-d9yzg97w.js → chunk-gf7yavs5.js} +1 -1
- package/dist/bin/chunk-gp5w7e4c.js +1 -0
- package/dist/bin/{chunk-75ak501k.js → chunk-ndddd2ft.js} +1 -1
- package/dist/bin/{chunk-padk76ac.js → chunk-sh248v2y.js} +1 -1
- package/dist/bin/chunk-y286zhty.js +1 -0
- package/dist/bin/cli.js +15 -15
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/{chunk-rtn4gj6y.js → chunk-07rjctzz.js} +1 -1
- package/dist/{chunk-60nr1ehk.js → chunk-2m262b2n.js} +1 -1
- package/dist/chunk-4j8ef0pe.js +1 -0
- package/dist/{chunk-s2ve9zxn.js → chunk-5255nr93.js} +2 -2
- package/dist/{chunk-yd40pg8g.js → chunk-9asn5fpt.js} +36 -36
- package/dist/{chunk-2p71e3x7.js → chunk-bcy9z4ks.js} +3 -3
- package/dist/{chunk-9syc8s7r.js → chunk-hyeeqga9.js} +2 -2
- package/dist/{chunk-c3f89ryr.js → chunk-r1wpwfff.js} +1 -1
- package/dist/deploy/index.js +1 -1
- package/dist/drivers/index.js +1 -1
- package/dist/index.js +1 -1
- package/dist/ui/404.html +1 -1
- package/dist/ui/accept-invitation.html +1 -1
- package/dist/ui/access-denied.html +1 -1
- package/dist/ui/account/automation.html +6 -6
- package/dist/ui/account/security.html +2 -2
- package/dist/ui/applications/compose.html +6 -6
- package/dist/ui/applications/new.html +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 +1 -1
- 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 +5 -5
- 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 +5 -5
- 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 +6 -6
- package/dist/ui/server/team.html +6 -6
- package/dist/ui/server/terminal.html +1 -1
- 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-a7kmjq4y.js +0 -1
- package/dist/bin/chunk-ckk70zc9.js +0 -1
- package/dist/bin/chunk-zww0xfdp.js +0 -1
- package/dist/chunk-hjgjbkhk.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{fd,O,d,p,bi,Id,Sd,le,g,Te,Fr,Qt,Ht,Vt,Ur,Ti}from"./chunk-v2p7c7s4.js";import{o}from"./chunk-
|
|
1
|
+
import{fd,O,d,p,bi,Id,Sd,le,g,Te,Fr,Qt,Ht,Vt,Ur,Ti}from"./chunk-v2p7c7s4.js";import{o}from"./chunk-9asn5fpt.js";import{B,vr,Tr,u}from"./chunk-3m9ghthh.js";import{ii}from"./chunk-srrscggm.js";import{Er,be}from"./chunk-qcaqc5b8.js";import{h}from"./chunk-ptq9v346.js";import{Ei}from"./chunk-g6g33pt9.js";import{readFileSync as to}from"node:fs";import{join as Ma}from"node:path";function vu(e={}){let t=new Set;for(let r of Object.values(e)){if(!r.domain)continue;if(r.redirect||r.deploy==="server"||r.start)t.add(r.domain)}return t}function Hr(e){return e.replace(/\.$/,"").toLowerCase()}function Ci(e,t,r){let n=Hr(e.name),s=Hr(t),i=Hr(r),a=i===s?"@":i.endsWith(`.${s}`)?i.slice(0,-(s.length+1)):i;return n===i||n===a||a==="@"&&(n===""||n===s)}async function Xa(e,t,r,n,s="A"){let i=await e.listRecords(t);if(!i.success)return[`could not list ${s} records: ${i.message||"unknown provider error"}`];let a=i.records.filter((m)=>m.type===s&&Ci(m,t,r)),c=a.findIndex((m)=>m.content===n);if(a.length<=1||c===-1)return[];let l=[];for(let[m,S]of a.entries()){if(m===c)continue;let v=await e.deleteRecord(t,S);if(!v.success)l.push(`could not remove stale ${S.name} ${s} ${S.content}: ${v.message||"unknown provider error"}`)}return l}function ye(e){if(!e)return;let t=e.trim();if(!t)return;if(!t.includes("/"))return t;let[r]=t.split("/");if(!r.endsWith("::"))return r||void 0;return`${r}1`}var Ya=new Set(["mail","smtp","imap","mx"]);function Tn(e){return!Ya.has(e.split(".")[0]??"")}async function Tu(e){let{provider:t,zone:r,fqdn:n,ipv4:s,ipv6:i,ttl:a=600}=e,c={published:[],warnings:[]},l=[{type:"A",content:s}];if(i&&Tn(n))l.push({type:"AAAA",content:i});for(let{type:m,content:S}of l){let v=await t.upsertRecord(r,{name:n,type:m,content:S,ttl:a});if(v?.success===!1){c.warnings.push(`${n} → ${S} failed: ${v.error||v.message||"unknown error"}`);continue}if(c.warnings.push(...(await Xa(t,r,n,S,m)).map((_)=>`${n} cleanup: ${_}`)),await Za(t,r,n,S,m))c.published.push({fqdn:n,type:m,content:S});else c.warnings.push(`${n} → ${S} reported success at ${t.name} but no matching ${m} record exists — create it manually: ${m} ${n} → ${S}`)}return c}async function Za(e,t,r,n,s){try{if(typeof e?.listRecords!=="function")return!0;let i=await e.listRecords(t);if(!i?.success||!Array.isArray(i.records))return!0;return i.records.some((a)=>{let c=typeof a?.name==="string"?a.name.replace(/\.$/,""):"";return a?.type===s&&c===r&&a?.content===n})}catch{return!0}}function Nr(e){return(Buffer.isBuffer(e)?e.toString("utf8"):typeof e==="string"?e:"").replace(/(^|\n)(\s*(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*=).*$/gm,"$1$2[redacted]").replace(/encrypted:[A-Za-z0-9+/=]+/g,"encrypted:[redacted]").trim().slice(-8000)}function wn(e,t){let r=Nr(e?.stderr),n=/line (\d+): syntax error/.exec(r);if(!n)return"";let s=Number(n[1]),i=t.split(`
|
|
2
2
|
`),a=Math.max(1,s-12),c=Math.min(i.length,s+2),l=i.slice(a-1,c).map((m,S)=>{let v=a+S,_=/^[A-Z_][A-Z0-9_]*=/.test(m)?m.replace(/=.*/,"=<redacted>"):m;return` ${String(v).padStart(4)}${v===s?" >":" "} ${_}`});return["",`The deploy script bash rejected is ${i.length} lines; it stopped at ${s}.`,...l].join(`
|
|
3
3
|
`)}function Rt(e){let t=e,r=typeof t?.status==="number"?` (exit ${t.status})`:"",n=t?.signal?` (signal ${t.signal})`:"",s=[Nr(t?.stderr),Nr(t?.stdout)].filter(Boolean).join(`
|
|
4
4
|
`);return`Remote SSH command failed${r}${n}${s?`
|
|
@@ -22,7 +22,7 @@ EOF`,`DISK_PCT=$(df -P / | awk 'NR==2{gsub("%","",$5); print $5}')`,"UPTIME_SEC=
|
|
|
22
22
|
`)}
|
|
23
23
|
`}return`${["server {"," listen 80;"," listen [::]:80;",` server_name ${r};`,...n,"}"].join(`
|
|
24
24
|
`)}
|
|
25
|
-
`}function Xr(e){let t=`/etc/nginx/sites-available/${e.siteName}`,r=`/etc/nginx/sites-enabled/${e.siteName}`,n=ha(e),s=[...Jr()];if(e.auth){let i=xs(e.siteName),a=(m)=>m.split("'").join("'\\''"),c=a(e.auth.password),l=a(e.auth.username);s.push(`TS_CLOUD_HTPASS=$(openssl passwd -apr1 '${c}')`,`printf '%s:%s\\n' '${l}' "$TS_CLOUD_HTPASS" > ${i}`,`chmod 640 ${i}`,`chown root:www-data ${i} 2>/dev/null || true`)}return s.push(`cat > ${t} <<'TS_CLOUD_NGINX_EOF'`,n.replace(/\n$/,""),"TS_CLOUD_NGINX_EOF",`ln -sf ${t} ${r}`,"rm -f /etc/nginx/sites-enabled/default",`${He} -t`,"systemctl reload ts-cloud-nginx 2>/dev/null || systemctl restart ts-cloud-nginx 2>/dev/null || true"),s}var He="/usr/local/bin/ts-cloud-nginx";function Jr(e="/opt/pantry"){return[...ur(),...ge(["nginx.org"]),"mkdir -p /etc/nginx/sites-available /etc/nginx/sites-enabled /var/log/nginx /var/lib/nginx/body /var/lib/nginx/proxy /var/lib/nginx/fastcgi /var/lib/nginx/uwsgi /var/lib/nginx/scgi","getent passwd www-data >/dev/null || useradd --system --no-create-home --shell /usr/sbin/nologin www-data","chown -R www-data:www-data /var/lib/nginx /var/log/nginx",`cat > ${He} <<'TS_CLOUD_NGINXBIN_EOF'`,"#!/bin/sh",`eval "$(cd ${e} && pantry env 2>/dev/null)"`,"NGINX_BIN=/opt/pantry/pantry/.bin/nginx",'if [ ! -x "$NGINX_BIN" ]; then NGINX_BIN=$(command -v nginx || true); fi','if [ -z "$NGINX_BIN" ]; then echo "nginx binary not found; run pantry install nginx.org or install nginx explicitly" >&2; exit 1; fi','exec "$NGINX_BIN" -c /etc/nginx/nginx.conf "$@"',"TS_CLOUD_NGINXBIN_EOF",`chmod +x ${He}`,"cat > /etc/nginx/fastcgi_params <<'TS_CLOUD_FCGI_EOF'","fastcgi_param QUERY_STRING $query_string;","fastcgi_param REQUEST_METHOD $request_method;","fastcgi_param CONTENT_TYPE $content_type;","fastcgi_param CONTENT_LENGTH $content_length;","fastcgi_param SCRIPT_NAME $fastcgi_script_name;","fastcgi_param REQUEST_URI $request_uri;","fastcgi_param DOCUMENT_URI $document_uri;","fastcgi_param DOCUMENT_ROOT $document_root;","fastcgi_param SERVER_PROTOCOL $server_protocol;","fastcgi_param REQUEST_SCHEME $scheme;","fastcgi_param HTTPS $https if_not_empty;","fastcgi_param GATEWAY_INTERFACE CGI/1.1;","fastcgi_param SERVER_SOFTWARE nginx/$nginx_version;","fastcgi_param REMOTE_ADDR $remote_addr;","fastcgi_param REMOTE_PORT $remote_port;","fastcgi_param SERVER_ADDR $server_addr;","fastcgi_param SERVER_PORT $server_port;","fastcgi_param SERVER_NAME $server_name;","fastcgi_param REDIRECT_STATUS 200;","TS_CLOUD_FCGI_EOF","cat > /etc/nginx/nginx.conf <<'TS_CLOUD_NGINXCONF_EOF'","user www-data;","worker_processes auto;","pid /run/nginx.pid;","error_log /var/log/nginx/error.log;","events { worker_connections 1024; }","http {"," default_type application/octet-stream;"," types {"," text/html html htm;"," text/css css;"," application/javascript js;"," application/json json;"," image/svg+xml svg;"," image/png png;"," image/jpeg jpg jpeg;"," image/gif gif;"," image/x-icon ico;"," image/webp webp;"," font/woff2 woff2;"," font/woff woff;"," text/plain txt;"," }"," access_log /var/log/nginx/access.log;"," sendfile on;"," tcp_nopush on;"," keepalive_timeout 65;"," server_tokens off;"," client_max_body_size 100m;"," client_body_temp_path /var/lib/nginx/body;"," proxy_temp_path /var/lib/nginx/proxy;"," fastcgi_temp_path /var/lib/nginx/fastcgi;"," uwsgi_temp_path /var/lib/nginx/uwsgi;"," scgi_temp_path /var/lib/nginx/scgi;"," server {"," listen 80 default_server;"," listen [::]:80 default_server;"," server_name _;"," return 444;"," }"," include /etc/nginx/sites-enabled/*;","}","TS_CLOUD_NGINXCONF_EOF","cat > /etc/systemd/system/ts-cloud-nginx.service <<'TS_CLOUD_NGINXUNIT_EOF'","[Unit]","Description=ts-cloud nginx (pantry)","After=network.target","","[Service]","Type=simple",`ExecStartPre=${He} -t`,`ExecStart=${He} -g 'daemon off;'`,`ExecReload=${He} -s reload`,"Restart=always","RestartSec=3","","[Install]","WantedBy=multi-user.target","TS_CLOUD_NGINXUNIT_EOF","systemctl daemon-reload","systemctl enable ts-cloud-nginx","ls /etc/nginx/sites-enabled/* >/dev/null 2>&1 && systemctl restart ts-cloud-nginx || true"]}function bt(e,t){return!e.events||e.events.includes(t)}async function Qr(e,t,r,n={}){if(!e)return[];let s=n.fetchImpl??globalThis.fetch,i=[],a=[],c=(l,m)=>s(l,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m)}).catch(()=>{return});if(e.slack?.webhookUrl&&bt(e,t))i.push("slack"),a.push(c(e.slack.webhookUrl,{text:r}));if(e.discord?.webhookUrl&&bt(e,t))i.push("discord"),a.push(c(e.discord.webhookUrl,{content:r}));if(e.telegram?.botToken&&e.telegram.chatId&&bt(e,t)){i.push("telegram");let l=`https://api.telegram.org/bot${e.telegram.botToken}/sendMessage`;a.push(c(l,{chat_id:e.telegram.chatId,text:r}))}if(e.webhook?.url&&bt(e,t))if(i.push("webhook"),(e.webhook.method||"POST")==="GET"){let l=e.webhook.url.includes("?")?"&":"?",m=`${e.webhook.url}${l}event=${encodeURIComponent(t)}&message=${encodeURIComponent(r)}`;a.push(s(m,{method:"GET"}).catch(()=>{return}))}else a.push(c(e.webhook.url,{event:t,message:r}));if(e.email?.to&&bt(e,t))i.push("email"),a.push(Sa(e.email,t,r));return await Promise.all(a),i}async function Sa(e,t,r){try{let n=await import("./chunk-hjgjbkhk.js");await n.email.send({to:e.to,from:e.from,subject:`[ts-cloud] ${t}`,text:r})}catch{}}function Os(e,t){return t??e}function Ze(e){if(!e)return[];let t=[];if(e.slack?.webhookUrl)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"text\\":\\"$MSG\\"}" ${e.slack.webhookUrl} || true`);if(e.discord?.webhookUrl)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"content\\":\\"$MSG\\"}" ${e.discord.webhookUrl} || true`);if(e.telegram?.botToken&&e.telegram.chatId)t.push(`curl -fsS -X POST "https://api.telegram.org/bot${e.telegram.botToken}/sendMessage" --data-urlencode "chat_id=${e.telegram.chatId}" --data-urlencode "text=$MSG" || true`);if(e.webhook?.url)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"message\\":\\"$MSG\\"}" ${e.webhook.url} || true`);if(t.length===0)return[];return["cat > /usr/local/bin/ts-cloud-notify <<'TS_CLOUD_NOTIFY_EOF'","#!/bin/bash",'MSG="$1"',...t,"TS_CLOUD_NOTIFY_EOF","chmod +x /usr/local/bin/ts-cloud-notify"]}import{isIP as As}from"node:net";var Dn="/etc/rpx/certs",Ls="/etc/rpx/local-ca",_a="rpx-root-ca.crt";function Wt(e=Ls){return`${e.replace(/\/+$/,"")}/${_a}`}function Pn(e){if(e.toLowerCase().endsWith(".local"))return!1;return e.split(".").length===2}function Nn(e,t={}){let r=new Set;for(let n of Object.values(e)){if(!n?.domain)continue;if(u(n)==="bucket")continue;r.add(n.domain)}if(t.autoWww!==!1)for(let n of[...r]){if(!Pn(n))continue;r.add(`www.${n}`)}return[...r]}var va=["1.1.1.1","8.8.8.8"],ya="/var/www/acme-challenge";function $a(e){if(typeof e==="string")return{to:e};let t={to:e.to};if(e.status!=null)t.status=e.status;if(e.preservePath!=null)t.preservePath=e.preservePath;return t}function ba(e){let t=e.auth;if(!t||t.enabled===!1||!t.password)return;return{username:t.username||"admin",password:t.password,...t.realm?{realm:t.realm}:{}}}function en(e){if(!e)return;return e.tls??"local-ca"}function Us(e,t){if(e.cloud?.provider!=="ssh")return;let r=e.ssh?.lan;if(!r)return;return{...r.hostname?{hostname:r.hostname}:{},tls:r.tls??"local-ca",...t?{ip:t}:{}}}function Hs(e){if(e.cloud?.provider!=="ssh")return;return e.ssh?.profile}function Ta(e){let t=e.trim().toLowerCase();if(!t||t.startsWith("*")||t.includes(":")||t.includes("/")||t.includes(" "))return!1;if(As(t)!==0)return!1;return t.endsWith(".local")||!t.includes(".")}function wa(e,t,r){let n=[],s=new Set,i=(m,S)=>{let v=m.trim().toLowerCase();if(!v||s.has(v))return;s.add(v),n.push({host:v,source:S})},a=t.hostname?.trim(),c=(a||`${r}.local`).toLowerCase();if(i(c,a?"ssh.lan.hostname":`the ssh provider's default LAN name for project "${r}"`),Object.entries(e).some(([m,S])=>!!S&&Ur(m)))i(`dashboard.${c}`,"the management dashboard site");for(let[m,S]of Object.entries(e)){if(!S?.domain)continue;if(u(S)==="bucket")continue;if(!Ta(S.domain))continue;i(S.domain,`site "${m}"`)}return n}function Ca(e,t){if(!t?.length)return;return t.find((r)=>{let n=(r.startsWith(".")?r.slice(1):r).toLowerCase();return e===n||e.endsWith(`.${n}`)})}function Pa(e,t){if(!t?.enabled)return;for(let{host:r,source:n}of e){let s=Ca(r,t.allowedSuffixes);if(!s)continue;throw Error(`The LAN certificate authority and public on-demand TLS both claim "${r}". LAN source: ${n}. Public source: the on-demand TLS allowed suffix "${s}", which is derived from the site domains. A host is either LAN-only, with a certificate signed by the box's own CA, or public, with one issued by Let's Encrypt, never both. Give the LAN a name no site domain covers (ssh.lan.hostname), or take that domain out of the sites this deploy routes.`)}}function Pu(e){if(!e||e==="/")return;let t=`/${e}`.replace(/\/+/g,"/").replace(/\/+$/,"");if(!t.startsWith("/"))t=`/${t}`;return t===""||t==="/"?void 0:t}function ec(e,t){let n=(t?`${e}${t}`:e).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return n.length>0?n:"rpx"}function Ea(e,t){if(!t||t.length===0)return`localhost:${e}`;return t.map((r)=>`${r.privateIp??r.publicIp}:${e}`)}function Ms(e,t,r){let n=(t.wwwRoot??"/var/www").replace(/\/+$/,""),s=t.slug??"app",i=t.proxy.certsDir??Dn,a=t.proxy.loadBalancer,c=[],l=new Set;for(let[_,f]of Object.entries(e)){if(!f||!f.domain)continue;let y=u(f);if(y==="bucket")continue;let x=Pu(f.path),P=ec(f.domain,x),C=ba(f);if(y==="redirect"){c.push({to:f.domain,path:x,redirect:$a(f.redirect),id:P,...C?{auth:C}:{}}),l.add(f.domain);continue}if(y==="proxy"){let T=Tr(f);if(T.length===0)continue;let b=T.length===1?T[0]:T;c.push({to:f.domain,path:x,from:b,id:P,...C?{auth:C}:{},...Array.isArray(b)&&a?{loadBalancer:a}:{}}),l.add(f.domain);continue}if(y==="server-app"){if(typeof f.port!=="number")continue;let T=Ea(f.port,r);c.push({to:f.domain,path:x,from:T,id:P,...C?{auth:C}:{},...Array.isArray(T)&&a?{loadBalancer:a}:{}})}else c.push({to:f.domain,path:x,static:{dir:`${n}/${s}-${_}/current`,spa:f.spa??!1,pathRewriteStyle:f.pathRewriteStyle??"directory"},cleanUrls:f.pathRewriteStyle!=="flat",...C?{auth:C}:{},id:P});l.add(f.domain)}if(t.proxy.autoWww!==!1)for(let _ of[...l]){if(!Pn(_))continue;let f=`www.${_}`;if(l.has(f))continue;c.push({to:f,redirect:{to:`https://${_}`},id:ec(f)}),l.add(f)}c.sort((_,f)=>{if(_.to!==f.to)return _.to.localeCompare(f.to);return(f.path?.length??0)-(_.path?.length??0)});let m={proxies:c,productionCerts:{certsDir:i,certsDirServerNames:[...l]},https:!0,hostsManagement:!1,cleanup:{hosts:!1,certs:!1}};if(t.proxy.onDemandTls&&l.size>0)m.onDemandTls={enabled:!0,allowedSuffixes:[...l],email:t.proxy.onDemandTlsEmail,certsDir:i,staging:t.proxy.onDemandTlsStaging??!1};if(t.proxy.onDemandTls)m.acmeChallengeWebroot=t.proxy.acmeWebroot??ya;let S=t.proxy.cdn,v=S?.frontedHosts?.length?S.frontedHosts:[...l];if(S?.secret&&v.length>0)m.originGuard={header:S.secretHeader??"X-Origin-Verify",value:S.secret,hosts:v};if(t.lan)if(en(t.lan)==="off")m.https=!1;else{let _=wa(e,t.lan,s);Pa(_,m.onDemandTls);let f=t.lan.ip&&As(t.lan.ip)!==0?[t.lan.ip]:[];m.localCa={dir:Ls,hosts:_.map((y)=>y.host),...f.length>0?{ips:f}:{},installTrust:!0}}return m}function K(e,t){return Ms(e,t)}function gr(e,t,r){return Ms(e,r,t)}function Nh(e){return`// Generated by ts-cloud — rpx reverse-proxy gateway.
|
|
25
|
+
`}function Xr(e){let t=`/etc/nginx/sites-available/${e.siteName}`,r=`/etc/nginx/sites-enabled/${e.siteName}`,n=ha(e),s=[...Jr()];if(e.auth){let i=xs(e.siteName),a=(m)=>m.split("'").join("'\\''"),c=a(e.auth.password),l=a(e.auth.username);s.push(`TS_CLOUD_HTPASS=$(openssl passwd -apr1 '${c}')`,`printf '%s:%s\\n' '${l}' "$TS_CLOUD_HTPASS" > ${i}`,`chmod 640 ${i}`,`chown root:www-data ${i} 2>/dev/null || true`)}return s.push(`cat > ${t} <<'TS_CLOUD_NGINX_EOF'`,n.replace(/\n$/,""),"TS_CLOUD_NGINX_EOF",`ln -sf ${t} ${r}`,"rm -f /etc/nginx/sites-enabled/default",`${He} -t`,"systemctl reload ts-cloud-nginx 2>/dev/null || systemctl restart ts-cloud-nginx 2>/dev/null || true"),s}var He="/usr/local/bin/ts-cloud-nginx";function Jr(e="/opt/pantry"){return[...ur(),...ge(["nginx.org"]),"mkdir -p /etc/nginx/sites-available /etc/nginx/sites-enabled /var/log/nginx /var/lib/nginx/body /var/lib/nginx/proxy /var/lib/nginx/fastcgi /var/lib/nginx/uwsgi /var/lib/nginx/scgi","getent passwd www-data >/dev/null || useradd --system --no-create-home --shell /usr/sbin/nologin www-data","chown -R www-data:www-data /var/lib/nginx /var/log/nginx",`cat > ${He} <<'TS_CLOUD_NGINXBIN_EOF'`,"#!/bin/sh",`eval "$(cd ${e} && pantry env 2>/dev/null)"`,"NGINX_BIN=/opt/pantry/pantry/.bin/nginx",'if [ ! -x "$NGINX_BIN" ]; then NGINX_BIN=$(command -v nginx || true); fi','if [ -z "$NGINX_BIN" ]; then echo "nginx binary not found; run pantry install nginx.org or install nginx explicitly" >&2; exit 1; fi','exec "$NGINX_BIN" -c /etc/nginx/nginx.conf "$@"',"TS_CLOUD_NGINXBIN_EOF",`chmod +x ${He}`,"cat > /etc/nginx/fastcgi_params <<'TS_CLOUD_FCGI_EOF'","fastcgi_param QUERY_STRING $query_string;","fastcgi_param REQUEST_METHOD $request_method;","fastcgi_param CONTENT_TYPE $content_type;","fastcgi_param CONTENT_LENGTH $content_length;","fastcgi_param SCRIPT_NAME $fastcgi_script_name;","fastcgi_param REQUEST_URI $request_uri;","fastcgi_param DOCUMENT_URI $document_uri;","fastcgi_param DOCUMENT_ROOT $document_root;","fastcgi_param SERVER_PROTOCOL $server_protocol;","fastcgi_param REQUEST_SCHEME $scheme;","fastcgi_param HTTPS $https if_not_empty;","fastcgi_param GATEWAY_INTERFACE CGI/1.1;","fastcgi_param SERVER_SOFTWARE nginx/$nginx_version;","fastcgi_param REMOTE_ADDR $remote_addr;","fastcgi_param REMOTE_PORT $remote_port;","fastcgi_param SERVER_ADDR $server_addr;","fastcgi_param SERVER_PORT $server_port;","fastcgi_param SERVER_NAME $server_name;","fastcgi_param REDIRECT_STATUS 200;","TS_CLOUD_FCGI_EOF","cat > /etc/nginx/nginx.conf <<'TS_CLOUD_NGINXCONF_EOF'","user www-data;","worker_processes auto;","pid /run/nginx.pid;","error_log /var/log/nginx/error.log;","events { worker_connections 1024; }","http {"," default_type application/octet-stream;"," types {"," text/html html htm;"," text/css css;"," application/javascript js;"," application/json json;"," image/svg+xml svg;"," image/png png;"," image/jpeg jpg jpeg;"," image/gif gif;"," image/x-icon ico;"," image/webp webp;"," font/woff2 woff2;"," font/woff woff;"," text/plain txt;"," }"," access_log /var/log/nginx/access.log;"," sendfile on;"," tcp_nopush on;"," keepalive_timeout 65;"," server_tokens off;"," client_max_body_size 100m;"," client_body_temp_path /var/lib/nginx/body;"," proxy_temp_path /var/lib/nginx/proxy;"," fastcgi_temp_path /var/lib/nginx/fastcgi;"," uwsgi_temp_path /var/lib/nginx/uwsgi;"," scgi_temp_path /var/lib/nginx/scgi;"," server {"," listen 80 default_server;"," listen [::]:80 default_server;"," server_name _;"," return 444;"," }"," include /etc/nginx/sites-enabled/*;","}","TS_CLOUD_NGINXCONF_EOF","cat > /etc/systemd/system/ts-cloud-nginx.service <<'TS_CLOUD_NGINXUNIT_EOF'","[Unit]","Description=ts-cloud nginx (pantry)","After=network.target","","[Service]","Type=simple",`ExecStartPre=${He} -t`,`ExecStart=${He} -g 'daemon off;'`,`ExecReload=${He} -s reload`,"Restart=always","RestartSec=3","","[Install]","WantedBy=multi-user.target","TS_CLOUD_NGINXUNIT_EOF","systemctl daemon-reload","systemctl enable ts-cloud-nginx","ls /etc/nginx/sites-enabled/* >/dev/null 2>&1 && systemctl restart ts-cloud-nginx || true"]}function bt(e,t){return!e.events||e.events.includes(t)}async function Qr(e,t,r,n={}){if(!e)return[];let s=n.fetchImpl??globalThis.fetch,i=[],a=[],c=(l,m)=>s(l,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m)}).catch(()=>{return});if(e.slack?.webhookUrl&&bt(e,t))i.push("slack"),a.push(c(e.slack.webhookUrl,{text:r}));if(e.discord?.webhookUrl&&bt(e,t))i.push("discord"),a.push(c(e.discord.webhookUrl,{content:r}));if(e.telegram?.botToken&&e.telegram.chatId&&bt(e,t)){i.push("telegram");let l=`https://api.telegram.org/bot${e.telegram.botToken}/sendMessage`;a.push(c(l,{chat_id:e.telegram.chatId,text:r}))}if(e.webhook?.url&&bt(e,t))if(i.push("webhook"),(e.webhook.method||"POST")==="GET"){let l=e.webhook.url.includes("?")?"&":"?",m=`${e.webhook.url}${l}event=${encodeURIComponent(t)}&message=${encodeURIComponent(r)}`;a.push(s(m,{method:"GET"}).catch(()=>{return}))}else a.push(c(e.webhook.url,{event:t,message:r}));if(e.email?.to&&bt(e,t))i.push("email"),a.push(Sa(e.email,t,r));return await Promise.all(a),i}async function Sa(e,t,r){try{let n=await import("./chunk-4j8ef0pe.js");await n.email.send({to:e.to,from:e.from,subject:`[ts-cloud] ${t}`,text:r})}catch{}}function Os(e,t){return t??e}function Ze(e){if(!e)return[];let t=[];if(e.slack?.webhookUrl)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"text\\":\\"$MSG\\"}" ${e.slack.webhookUrl} || true`);if(e.discord?.webhookUrl)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"content\\":\\"$MSG\\"}" ${e.discord.webhookUrl} || true`);if(e.telegram?.botToken&&e.telegram.chatId)t.push(`curl -fsS -X POST "https://api.telegram.org/bot${e.telegram.botToken}/sendMessage" --data-urlencode "chat_id=${e.telegram.chatId}" --data-urlencode "text=$MSG" || true`);if(e.webhook?.url)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"message\\":\\"$MSG\\"}" ${e.webhook.url} || true`);if(t.length===0)return[];return["cat > /usr/local/bin/ts-cloud-notify <<'TS_CLOUD_NOTIFY_EOF'","#!/bin/bash",'MSG="$1"',...t,"TS_CLOUD_NOTIFY_EOF","chmod +x /usr/local/bin/ts-cloud-notify"]}import{isIP as As}from"node:net";var Dn="/etc/rpx/certs",Ls="/etc/rpx/local-ca",_a="rpx-root-ca.crt";function Wt(e=Ls){return`${e.replace(/\/+$/,"")}/${_a}`}function Pn(e){if(e.toLowerCase().endsWith(".local"))return!1;return e.split(".").length===2}function Nn(e,t={}){let r=new Set;for(let n of Object.values(e)){if(!n?.domain)continue;if(u(n)==="bucket")continue;r.add(n.domain)}if(t.autoWww!==!1)for(let n of[...r]){if(!Pn(n))continue;r.add(`www.${n}`)}return[...r]}var va=["1.1.1.1","8.8.8.8"],ya="/var/www/acme-challenge";function $a(e){if(typeof e==="string")return{to:e};let t={to:e.to};if(e.status!=null)t.status=e.status;if(e.preservePath!=null)t.preservePath=e.preservePath;return t}function ba(e){let t=e.auth;if(!t||t.enabled===!1||!t.password)return;return{username:t.username||"admin",password:t.password,...t.realm?{realm:t.realm}:{}}}function en(e){if(!e)return;return e.tls??"local-ca"}function Us(e,t){if(e.cloud?.provider!=="ssh")return;let r=e.ssh?.lan;if(!r)return;return{...r.hostname?{hostname:r.hostname}:{},tls:r.tls??"local-ca",...t?{ip:t}:{}}}function Hs(e){if(e.cloud?.provider!=="ssh")return;return e.ssh?.profile}function Ta(e){let t=e.trim().toLowerCase();if(!t||t.startsWith("*")||t.includes(":")||t.includes("/")||t.includes(" "))return!1;if(As(t)!==0)return!1;return t.endsWith(".local")||!t.includes(".")}function wa(e,t,r){let n=[],s=new Set,i=(m,S)=>{let v=m.trim().toLowerCase();if(!v||s.has(v))return;s.add(v),n.push({host:v,source:S})},a=t.hostname?.trim(),c=(a||`${r}.local`).toLowerCase();if(i(c,a?"ssh.lan.hostname":`the ssh provider's default LAN name for project "${r}"`),Object.entries(e).some(([m,S])=>!!S&&Ur(m)))i(`dashboard.${c}`,"the management dashboard site");for(let[m,S]of Object.entries(e)){if(!S?.domain)continue;if(u(S)==="bucket")continue;if(!Ta(S.domain))continue;i(S.domain,`site "${m}"`)}return n}function Ca(e,t){if(!t?.length)return;return t.find((r)=>{let n=(r.startsWith(".")?r.slice(1):r).toLowerCase();return e===n||e.endsWith(`.${n}`)})}function Pa(e,t){if(!t?.enabled)return;for(let{host:r,source:n}of e){let s=Ca(r,t.allowedSuffixes);if(!s)continue;throw Error(`The LAN certificate authority and public on-demand TLS both claim "${r}". LAN source: ${n}. Public source: the on-demand TLS allowed suffix "${s}", which is derived from the site domains. A host is either LAN-only, with a certificate signed by the box's own CA, or public, with one issued by Let's Encrypt, never both. Give the LAN a name no site domain covers (ssh.lan.hostname), or take that domain out of the sites this deploy routes.`)}}function Pu(e){if(!e||e==="/")return;let t=`/${e}`.replace(/\/+/g,"/").replace(/\/+$/,"");if(!t.startsWith("/"))t=`/${t}`;return t===""||t==="/"?void 0:t}function ec(e,t){let n=(t?`${e}${t}`:e).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return n.length>0?n:"rpx"}function Ea(e,t){if(!t||t.length===0)return`localhost:${e}`;return t.map((r)=>`${r.privateIp??r.publicIp}:${e}`)}function Ms(e,t,r){let n=(t.wwwRoot??"/var/www").replace(/\/+$/,""),s=t.slug??"app",i=t.proxy.certsDir??Dn,a=t.proxy.loadBalancer,c=[],l=new Set;for(let[_,f]of Object.entries(e)){if(!f||!f.domain)continue;let y=u(f);if(y==="bucket")continue;let x=Pu(f.path),P=ec(f.domain,x),C=ba(f);if(y==="redirect"){c.push({to:f.domain,path:x,redirect:$a(f.redirect),id:P,...C?{auth:C}:{}}),l.add(f.domain);continue}if(y==="proxy"){let T=Tr(f);if(T.length===0)continue;let b=T.length===1?T[0]:T;c.push({to:f.domain,path:x,from:b,id:P,...C?{auth:C}:{},...Array.isArray(b)&&a?{loadBalancer:a}:{}}),l.add(f.domain);continue}if(y==="server-app"){if(typeof f.port!=="number")continue;let T=Ea(f.port,r);c.push({to:f.domain,path:x,from:T,id:P,...C?{auth:C}:{},...Array.isArray(T)&&a?{loadBalancer:a}:{}})}else c.push({to:f.domain,path:x,static:{dir:`${n}/${s}-${_}/current`,spa:f.spa??!1,pathRewriteStyle:f.pathRewriteStyle??"directory"},cleanUrls:f.pathRewriteStyle!=="flat",...C?{auth:C}:{},id:P});l.add(f.domain)}if(t.proxy.autoWww!==!1)for(let _ of[...l]){if(!Pn(_))continue;let f=`www.${_}`;if(l.has(f))continue;c.push({to:f,redirect:{to:`https://${_}`},id:ec(f)}),l.add(f)}c.sort((_,f)=>{if(_.to!==f.to)return _.to.localeCompare(f.to);return(f.path?.length??0)-(_.path?.length??0)});let m={proxies:c,productionCerts:{certsDir:i,certsDirServerNames:[...l]},https:!0,hostsManagement:!1,cleanup:{hosts:!1,certs:!1}};if(t.proxy.onDemandTls&&l.size>0)m.onDemandTls={enabled:!0,allowedSuffixes:[...l],email:t.proxy.onDemandTlsEmail,certsDir:i,staging:t.proxy.onDemandTlsStaging??!1};if(t.proxy.onDemandTls)m.acmeChallengeWebroot=t.proxy.acmeWebroot??ya;let S=t.proxy.cdn,v=S?.frontedHosts?.length?S.frontedHosts:[...l];if(S?.secret&&v.length>0)m.originGuard={header:S.secretHeader??"X-Origin-Verify",value:S.secret,hosts:v};if(t.lan)if(en(t.lan)==="off")m.https=!1;else{let _=wa(e,t.lan,s);Pa(_,m.onDemandTls);let f=t.lan.ip&&As(t.lan.ip)!==0?[t.lan.ip]:[];m.localCa={dir:Ls,hosts:_.map((y)=>y.host),...f.length>0?{ips:f}:{},installTrust:!0}}return m}function K(e,t){return Ms(e,t)}function gr(e,t,r){return Ms(e,r,t)}function Nh(e){return`// Generated by ts-cloud — rpx reverse-proxy gateway.
|
|
26
26
|
// Routes are derived from the \`sites\` model on every \`buddy deploy\`.
|
|
27
27
|
import { startProxies } from '@stacksjs/rpx'
|
|
28
28
|
|
|
@@ -1,92 +1,92 @@
|
|
|
1
|
-
import{br,n}from"./chunk-zx8ecz8b.js";import{Fe}from"./chunk-bxrzsth8.js";import*as l from"node:crypto";import{readFileSync as
|
|
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
|
|
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
3
|
<CreateBucketConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
4
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:
|
|
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
6
|
`).join(""),k=Object.keys(S).sort().map((P)=>P.toLowerCase()).join(";"),T=["PUT",u,"",f,k,b].join(`
|
|
7
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
|
-
`),
|
|
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
9
|
`).join(""),S=Object.keys(p).sort().map((P)=>P.toLowerCase()).join(";"),f=["GET",g,"",b,S,m].join(`
|
|
10
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${
|
|
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
12
|
<Delete>
|
|
13
|
-
${t.map((
|
|
13
|
+
${t.map((i)=>`<Object><Key>${i}</Key></Object>`).join(`
|
|
14
14
|
`)}
|
|
15
|
-
</Delete>`,
|
|
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
16
|
`).join(""),S=Object.keys(p).sort().map((x)=>x.toLowerCase()).join(";"),f=["PUT",h,"policy=",b,S,y].join(`
|
|
17
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"+
|
|
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
19
|
`).join(""),p=Object.keys(h).sort().map((A)=>A.toLowerCase()).join(";"),b=["GET",u,"policy=",m,p,d].join(`
|
|
20
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(),
|
|
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
22
|
<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
23
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{
|
|
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
25
|
<LifecycleConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
26
|
-
${t.map((
|
|
27
|
-
</LifecycleConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,queryParams:{lifecycle:""},headers:{"Content-Type":"application/xml"},body:
|
|
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
28
|
<CORSConfiguration>
|
|
29
|
-
${t.map((
|
|
30
|
-
</CORSConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,queryParams:{cors:""},headers:{"Content-Type":"application/xml"},body:
|
|
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
31
|
<ServerSideEncryptionConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
32
|
-
<Rule>${
|
|
33
|
-
</ServerSideEncryptionConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,queryParams:{encryption:""},headers:{"Content-Type":"application/xml"},body:
|
|
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
34
|
<Tagging>
|
|
35
|
-
<TagSet>${t.map((
|
|
36
|
-
</Tagging>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,queryParams:{tagging:""},headers:{"Content-Type":"application/xml"},body:
|
|
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
37
|
<Tagging>
|
|
38
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:
|
|
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
40
|
<BucketLoggingStatus xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
41
41
|
<LoggingEnabled>
|
|
42
42
|
<TargetBucket>${t}</TargetBucket>
|
|
43
43
|
<TargetPrefix>${s}</TargetPrefix>
|
|
44
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:
|
|
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
46
|
<NotificationConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
47
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:
|
|
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
49
|
<HostName>${t.RedirectAllRequestsTo.HostName}</HostName>
|
|
50
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
|
|
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
52
|
<WebsiteConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
53
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:
|
|
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
55
|
<PublicAccessBlockConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
56
56
|
<BlockPublicAcls>${t.BlockPublicAcls??!0}</BlockPublicAcls>
|
|
57
57
|
<IgnorePublicAcls>${t.IgnorePublicAcls??!0}</IgnorePublicAcls>
|
|
58
58
|
<BlockPublicPolicy>${t.BlockPublicPolicy??!0}</BlockPublicPolicy>
|
|
59
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:
|
|
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
61
|
`,"host","UNSIGNED-PAYLOAD"].join(`
|
|
62
62
|
`),b=["AWS4-HMAC-SHA256",g,u,l.createHash("sha256").update(p).digest("hex")].join(`
|
|
63
|
-
`),S=l.createHmac("sha256",`AWS4${
|
|
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
64
|
host:${c}
|
|
65
65
|
`,"content-type;host","UNSIGNED-PAYLOAD"].join(`
|
|
66
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
|
|
68
|
-
`).join(""),T=Object.keys(f).sort().map((
|
|
69
|
-
`),C="AWS4-HMAC-SHA256",q=`${b}/${this.region}/s3/aws4_request`,
|
|
70
|
-
`),
|
|
71
|
-
<CompleteMultipartUpload>${
|
|
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
72
|
<RestoreRequest>
|
|
73
73
|
<Days>${s}</Days>
|
|
74
74
|
<GlacierJobParameters>
|
|
75
|
-
<Tier>${
|
|
75
|
+
<Tier>${r}</Tier>
|
|
76
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:
|
|
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
78
|
<SelectObjectContentRequest>
|
|
79
79
|
<Expression>${s}</Expression>
|
|
80
80
|
<ExpressionType>SQL</ExpressionType>
|
|
81
81
|
<InputSerialization>${a}</InputSerialization>
|
|
82
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:
|
|
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
84
|
`,H=[m,C,T,q,"host","UNSIGNED-PAYLOAD"].join(`
|
|
85
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(),
|
|
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
87
|
<Delete>
|
|
88
88
|
<Quiet>true</Quiet>
|
|
89
|
-
${t.map((
|
|
89
|
+
${t.map((i)=>`<Object><Key>${i.Key}</Key>${i.VersionId?`<VersionId>${i.VersionId}</VersionId>`:""}</Object>`).join(`
|
|
90
90
|
`)}
|
|
91
|
-
</Delete>`,
|
|
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
92
|
export{Bt,o};
|