@stacksjs/ts-cloud 0.16.51 → 0.16.52

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.
Files changed (65) hide show
  1. package/dist/bin/{chunk-gc199s7a.js → chunk-0e9yddgc.js} +1 -1
  2. package/dist/bin/{chunk-m5jvp6ph.js → chunk-k6g1c681.js} +1 -1
  3. package/dist/bin/{chunk-d24ztt54.js → chunk-nxvtya6v.js} +22 -22
  4. package/dist/bin/cli.js +4 -4
  5. package/dist/bin/dashboard-server.js +1 -1
  6. package/dist/{chunk-dw0cvqdr.js → chunk-ggtsfsxx.js} +7 -7
  7. package/dist/{chunk-53kyxata.js → chunk-rjaa4epz.js} +1 -1
  8. package/dist/deploy/index.js +1 -1
  9. package/dist/drivers/index.js +1 -1
  10. package/dist/index.js +1 -1
  11. package/dist/ui/404.html +1 -1
  12. package/dist/ui/accept-invitation.html +1 -1
  13. package/dist/ui/access-denied.html +1 -1
  14. package/dist/ui/account/automation.html +6 -6
  15. package/dist/ui/account/security.html +1 -1
  16. package/dist/ui/applications/compose.html +5 -5
  17. package/dist/ui/applications/new.html +2 -2
  18. package/dist/ui/data/backups.html +6 -6
  19. package/dist/ui/data/services.html +6 -6
  20. package/dist/ui/data/volumes.html +6 -6
  21. package/dist/ui/index.html +6 -6
  22. package/dist/ui/infrastructure/topology.html +5 -5
  23. package/dist/ui/integrations.html +2 -2
  24. package/dist/ui/operations/alerts.html +6 -6
  25. package/dist/ui/operations/configuration.html +6 -6
  26. package/dist/ui/operations/jobs.html +6 -6
  27. package/dist/ui/operations/maintenance.html +6 -6
  28. package/dist/ui/operations/observability.html +6 -6
  29. package/dist/ui/operations/previews.html +6 -6
  30. package/dist/ui/operations/queue.html +6 -6
  31. package/dist/ui/operations/regions.html +6 -6
  32. package/dist/ui/operations/releases.html +6 -6
  33. package/dist/ui/operations/spend.html +6 -6
  34. package/dist/ui/operations/workloads.html +5 -5
  35. package/dist/ui/security.html +2 -2
  36. package/dist/ui/server/actions.html +6 -6
  37. package/dist/ui/server/activity.html +1 -1
  38. package/dist/ui/server/capacity.html +6 -6
  39. package/dist/ui/server/database.html +5 -5
  40. package/dist/ui/server/deployments.html +6 -6
  41. package/dist/ui/server/diagnostics.html +2 -2
  42. package/dist/ui/server/firewall.html +6 -6
  43. package/dist/ui/server/fleet.html +6 -6
  44. package/dist/ui/server/logs.html +6 -6
  45. package/dist/ui/server/metrics.html +6 -6
  46. package/dist/ui/server/security.html +1 -1
  47. package/dist/ui/server/services.html +1 -1
  48. package/dist/ui/server/sites.html +5 -5
  49. package/dist/ui/server/ssh-keys.html +6 -6
  50. package/dist/ui/server/team.html +6 -6
  51. package/dist/ui/server/terminal.html +2 -2
  52. package/dist/ui/serverless/alarms.html +6 -6
  53. package/dist/ui/serverless/assets.html +2 -2
  54. package/dist/ui/serverless/cost.html +2 -2
  55. package/dist/ui/serverless/data.html +6 -6
  56. package/dist/ui/serverless/deployments.html +1 -1
  57. package/dist/ui/serverless/firewall.html +1 -1
  58. package/dist/ui/serverless/functions.html +6 -6
  59. package/dist/ui/serverless/logs.html +6 -6
  60. package/dist/ui/serverless/metrics.html +2 -2
  61. package/dist/ui/serverless/queues.html +6 -6
  62. package/dist/ui/serverless/secrets.html +6 -6
  63. package/dist/ui/serverless/traces.html +5 -5
  64. package/dist/ui/serverless.html +5 -5
  65. package/package.json +3 -3
@@ -9,7 +9,7 @@ ${ho(c)}`:u}),s=r.length-n.length,i=s>0?[`(+${s} more instance${s===1?"":"s"} fa
9
9
  `)}function So(e){let t=2166136261,r=16777619;for(let n=0;n<e.length;n++){let s=e.charCodeAt(n);t=Math.imul(t^s,16777619)>>>0,r=Math.imul(r+s,2246822507)>>>0}return`${t.toString(36)}${r.toString(36)}`.padEnd(12,"0").slice(0,12)}function Cg(e,t,r={}){let n=r.mode??"testing",s=r.maxAge??604800,i=r.mx?.length?r.mx:[e.hostname],a=`${["version: STSv1",`mode: ${n}`,...i.map((u)=>`mx: ${u}`),`max_age: ${s}`].join(`\r
10
10
  `)}\r
11
11
  `,c=So(a);return{host:`mta-sts.${t}`,body:a,id:c,txt:`v=STSv1; id=${c}`}}var Eg=8461;function Eh(e,t=Eg){return[`const policy = ${JSON.stringify(e.body)}`,"Bun.serve({",` port: ${t},`," hostname: '127.0.0.1',"," fetch(req) {"," const { pathname } = new URL(req.url)"," if (pathname !== '/.well-known/mta-sts.txt') return new Response('Not Found', { status: 404 })"," return new Response(policy, { headers: { 'content-type': 'text/plain; charset=utf-8' } })"," },","})"].join(`
12
- `)}var St={php:"php.net",nginx:"nginx.org",composer:"getcomposer.org",mysql:"mysql.com",mariadb:"mariadb.com/server",postgres:"postgresql.org",vitess:"vitess.io",etcd:"etcd.io",redis:"redis.io",memcached:"memcached.org",meilisearch:"meilisearch.com",mail:"github.com/mail-os/mail",git:"git-scm.com",certbot:"certbot.eff.org",bun:"bun.sh",node:"nodejs.org",deno:"deno.land"};var T="/opt/pantry";function Lt(e){return`'${e.split("'").join("'\\''")}'`}function Nr(e={}){return["export DEBIAN_FRONTEND=noninteractive","export PANTRY_SERVICE_SCOPE=system","export PANTRY_INSTALL_DIR=/usr/local/bin",e.version?`export PANTRY_VERSION=${Lt(e.version)}`:'export PANTRY_VERSION="${PANTRY_VERSION:-latest}"',"command -v curl >/dev/null 2>&1 || (apt-get update -y && apt-get install -y curl ca-certificates)","command -v unzip >/dev/null 2>&1 || (apt-get update -y && apt-get install -y unzip)",'OS=$(uname -s | tr \'[:upper:]\' \'[:lower:]\'); ARCH=$(uname -m); case "$ARCH" in x86_64|amd64) ARCH=x64 ;; arm64|aarch64) ARCH=arm64 ;; esac; ZIP="pantry-${OS}-${ARCH}.zip"; if [ "${PANTRY_VERSION:-latest}" = latest ]; then REL=\'latest/download\'; else REL="download/v${PANTRY_VERSION}"; fi; TMP=$(mktemp -d); curl -fsSL -o "${TMP}/${ZIP}" "https://github.com/pantry-pm/pantry/releases/${REL}/${ZIP}"; unzip -o "${TMP}/${ZIP}" -d /usr/local/bin; chmod +x /usr/local/bin/pantry; rm -rf "${TMP}"','export PATH="/usr/local/bin:$PATH"',"mkdir -p /opt/pantry"]}function ve(){return'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true'}function ge(e){if(e.length===0)return[];return[`(cd /opt/pantry && pantry install ${[...new Set(e)].map(Lt).join(" ")})`]}function Ut(e){return[...new Set(e)].flatMap((t)=>[`(cd /opt/pantry && pantry start ${Lt(t)})`,`(cd /opt/pantry && pantry enable ${Lt(t)})`])}var ne="/etc/mail",he="mail-server",Cr="mail",Er=`${T}/pantry/.bin`;function _e(e){return`'${String(e).split("'").join("'\\''")}'`}function Le(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function _o(e){return[e.version?`${St.mail}@${e.version}`:St.mail]}function Rr(e,t){return`${ne}/dkim/${t}.${e.dkim.selector}.pem`}function Un(e){return`${e.storagePath}/smtp.db`}function vo(e){let t=["# Generated by ts-cloud. Edits are overwritten on the next deploy —","# change `services.mail` in the cloud config instead.","","[server]",`host = ${Le(e.bindAddress)}`,`port = ${e.ports.smtp}`,`hostname = ${Le(e.hostname)}`];if(e.domains.length>0)t.push(`local_domains = ${Le(e.domains.join(", "))}`);if(e.mode==="catcher")t.push("catch_all = true");if(t.push(`max_message_size = ${e.maxMessageSize}`,"","[tls]",`enabled = ${e.tls.enabled}`),e.tls.certPath)t.push(`cert_path = ${Le(e.tls.certPath)}`);if(e.tls.keyPath)t.push(`key_path = ${Le(e.tls.keyPath)}`);if(t.push("","[auth]",`enabled = ${e.mode==="server"}`,"","[antispam]",`dnsbl = ${e.spam.dnsbl}`,`greylist = ${e.spam.greylist}`,`spam_filter = ${e.spam.enabled}`,`junk_score = ${e.spam.junkScore}`,`reject_score = ${e.spam.rejectScore}`,"","[dkim]",`rotation_enabled = ${e.dkim.enabled&&e.dkim.rotate}`,`rotation_interval_days = ${e.dkim.rotateIntervalDays}`,"","[acme]",`enabled = ${e.tls.acme}`),e.tls.acmeEmail)t.push(`email = ${Le(e.tls.acmeEmail)}`);if(t.push("","[webhook]",`enabled = ${!!e.webhookUrl}`),e.webhookUrl)t.push(`url = ${Le(e.webhookUrl)}`);return t.push(""),t.join(`
12
+ `)}var St={php:"php.net",nginx:"nginx.org",composer:"getcomposer.org",mysql:"mysql.com",mariadb:"mariadb.com/server",postgres:"postgresql.org",vitess:"vitess.io",etcd:"etcd.io",redis:"redis.io",memcached:"memcached.org",meilisearch:"meilisearch.com",mail:"github.com/mail-os/mail",git:"git-scm.com",certbot:"certbot.eff.org",bun:"bun.sh",node:"nodejs.org",deno:"deno.land"};var T="/opt/pantry";function Lt(e){return`'${e.split("'").join("'\\''")}'`}function Nr(e={}){return["export DEBIAN_FRONTEND=noninteractive","export PANTRY_SERVICE_SCOPE=system","export PANTRY_INSTALL_DIR=/usr/local/bin",e.version?`export PANTRY_VERSION=${Lt(e.version)}`:'export PANTRY_VERSION="${PANTRY_VERSION:-latest}"',"command -v curl >/dev/null 2>&1 || (apt-get update -y && apt-get install -y curl ca-certificates)","command -v unzip >/dev/null 2>&1 || (apt-get update -y && apt-get install -y unzip)",'OS=$(uname -s | tr \'[:upper:]\' \'[:lower:]\'); ARCH=$(uname -m); case "$ARCH" in x86_64|amd64) ARCH=x64 ;; arm64|aarch64) ARCH=arm64 ;; esac; ZIP="pantry-${OS}-${ARCH}.zip"; if [ "${PANTRY_VERSION:-latest}" = latest ]; then REL=\'latest/download\'; else REL="download/v${PANTRY_VERSION}"; fi; TMP=$(mktemp -d); curl -fsSL -o "${TMP}/${ZIP}" "https://github.com/pantry-pm/pantry/releases/${REL}/${ZIP}"; unzip -o "${TMP}/${ZIP}" -d /usr/local/bin; chmod +x /usr/local/bin/pantry; rm -rf "${TMP}"','export PATH="/usr/local/bin:$PATH"',"mkdir -p /opt/pantry"]}function ve(){return'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true'}function ge(e){if(e.length===0)return[];return[`(cd /opt/pantry && pantry install ${[...new Set(e)].map(Lt).join(" ")})`]}function Ut(e){return[...new Set(e)].flatMap((t)=>[`(cd /opt/pantry && pantry start ${Lt(t)})`,`(cd /opt/pantry && pantry enable ${Lt(t)})`])}var ne="/etc/mail",he="mail-server",Cr="mail",Er=`${T}/pantry/.bin`;function _e(e){return`'${String(e).split("'").join("'\\''")}'`}function Ue(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function _o(e){return[e.version?`${St.mail}@${e.version}`:St.mail]}function Rr(e,t){return`${ne}/dkim/${t}.${e.dkim.selector}.pem`}function Un(e){return`${e.storagePath}/smtp.db`}function vo(e){let t=["# Generated by ts-cloud. Edits are overwritten on the next deploy —","# change `services.mail` in the cloud config instead.","","[server]",`host = ${Ue(e.bindAddress)}`,`port = ${e.ports.smtp}`,`hostname = ${Ue(e.hostname)}`];if(e.domains.length>0)t.push(`local_domains = ${Ue(e.domains.join(", "))}`);if(e.mode==="catcher")t.push("catch_all = true");if(t.push(`max_message_size = ${e.maxMessageSize}`,"","[tls]",`enabled = ${e.tls.enabled}`),e.tls.certPath)t.push(`cert_path = ${Ue(e.tls.certPath)}`);if(e.tls.keyPath)t.push(`key_path = ${Ue(e.tls.keyPath)}`);if(t.push("","[auth]",`enabled = ${e.mode==="server"}`,"","[antispam]",`dnsbl = ${e.spam.dnsbl}`,`greylist = ${e.spam.greylist}`,`spam_filter = ${e.spam.enabled}`,`junk_score = ${e.spam.junkScore}`,`reject_score = ${e.spam.rejectScore}`,"","[dkim]",`rotation_enabled = ${e.dkim.enabled&&e.dkim.rotate}`,`rotation_interval_days = ${e.dkim.rotateIntervalDays}`,"","[acme]",`enabled = ${e.tls.acme}`),e.tls.acmeEmail)t.push(`email = ${Ue(e.tls.acmeEmail)}`);if(t.push("","[webhook]",`enabled = ${!!e.webhookUrl}`),e.webhookUrl)t.push(`url = ${Ue(e.webhookUrl)}`);return t.push(""),t.join(`
13
13
  `)}function yo(e){let t=["# Generated by ts-cloud. See /etc/mail/config.toml for the rest.",`SMTP_DB_PATH=${Un(e)}`,`SMTP_DELIVERY_METHOD=${e.delivery==="ses"?"ses":"direct"}`];if(e.delivery==="ses")t.push(`SMTP_SES_REGION=${e.sesRegion}`);if(e.ports.submission)t.push(`SUBMISSION_PORT=${e.ports.submission}`);if(e.ports.submissions)t.push(`SMTPS_PORT=${e.ports.submissions}`);if(e.ports.imap)t.push("IMAP_ENABLED=1",`IMAP_PORT=${e.ports.imap}`);if(e.webmail.enabled)t.push("SMTP_ENABLE_WEBMAIL=true",`SMTP_WEBMAIL_PORT=${e.webmail.port}`,`SMTP_WEBMAIL_TLS=${e.webmail.tls}`,`SMTP_WEBMAIL_SECURE_COOKIES=${e.webmail.secureCookies}`,`SMTP_WEBMAIL_ATTACHMENT_MAX_FILE=${e.webmail.attachmentMaxFileBytes}`,`SMTP_WEBMAIL_ATTACHMENT_MAX_TOTAL=${e.webmail.attachmentMaxTotalBytes}`,`SMTP_WEBMAIL_ATTACHMENT_MAX_COUNT=${e.webmail.attachmentMaxCount}`,`SMTP_WEBMAIL_UNDO_SEND_SECONDS=${e.webmail.undoSendSeconds}`);if(e.tls.requireForAuth)t.push("SMTP_REQUIRE_TLS_FOR_AUTH=true");if(e.dkim.enabled&&e.domains.length>0){let[r,...n]=e.domains;if(t.push(`DKIM_DOMAIN=${r}`,`DKIM_SELECTOR=${e.dkim.selector}`,`DKIM_PRIVATE_KEY_PATH=${Rr(e,r)}`),n.length>0){let s=n.map((i)=>`${i}:${e.dkim.selector}:${Rr(e,i)}`);t.push(`DKIM_EXTRA_KEYS=${s.join(",")}`)}}return t.push(""),t.join(`
14
14
  `)}function $o(e){let t=[e.ports.smtp,e.ports.submission,e.ports.submissions,e.ports.imap,e.ports.imaps].some((r)=>typeof r==="number"&&r<1024);return["[Unit]","Description=Mail server (SMTP/IMAP + webmail)","After=network-online.target","Wants=network-online.target","","[Service]","Type=simple",`User=${he}`,`Group=${he}`,`WorkingDirectory=${e.storagePath}`,`EnvironmentFile=${ne}/mail.env`,`Environment="PATH=${Er}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"`,`ExecStart=${Er}/mail serve --config ${ne}/config.toml`,"Restart=always","RestartSec=5","LimitNOFILE=65536",...t?["AmbientCapabilities=CAP_NET_BIND_SERVICE","CapabilityBoundingSet=CAP_NET_BIND_SERVICE"]:[],"NoNewPrivileges=true","PrivateTmp=true","ProtectSystem=strict","ProtectHome=true","ProtectKernelTunables=true","ProtectKernelModules=true","ProtectControlGroups=true",`ReadWritePaths=${e.storagePath} ${ne}`,"","[Install]","WantedBy=multi-user.target",""].join(`
15
15
  `)}function To(e){if(!e.dkim.enabled||e.domains.length===0)return[];let t=[`mkdir -p ${ne}/dkim`];for(let r of e.domains){let n=Rr(e,r);t.push(`if [ ! -f ${_e(n)} ]; then openssl genrsa -out ${_e(n)} 2048; fi`,`chmod 0600 ${_e(n)}`,`echo "DKIM ${e.dkim.selector}._domainkey.${r} IN TXT v=DKIM1; k=rsa; p=$(openssl rsa -in ${_e(n)} -pubout -outform PEM 2>/dev/null | grep -v '^-----' | tr -d '\\n')"`)}return t.push(`chown -R ${he}:${he} ${ne}/dkim`),t}function bo(e){if(e.accounts.length===0)return[];let t=(r)=>`runuser -u ${he} -- env SMTP_DB_PATH="$TS_CLOUD_MAIL_DB" ${Er}/mail user:local ${r}`;return e.accounts.flatMap((r)=>[t(`create ${_e(r.address)} ${_e(r.password)} ${_e(r.address)}`),...r.passwordPolicy==="managed"?[t(`change-password ${_e(r.address)} ${_e(r.password)}`)]:[]])}function Hn(e){if(!e.enabled)return[];return[...ge(_o(e)),`id -u ${he} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin ${he}`,`mkdir -p ${e.storagePath} ${ne}`,`chown -R ${he}:${he} ${e.storagePath}`,`TS_CLOUD_MAIL_DB="$(grep -sE '^SMTP_DB_PATH=' ${ne}/mail.env | head -1 | cut -d= -f2- || true)"`,`[ -n "$TS_CLOUD_MAIL_DB" ] || TS_CLOUD_MAIL_DB=${_e(Un(e))}`,`cat > ${ne}/config.toml <<'TS_CLOUD_MAIL_CONF_EOF'`,vo(e),"TS_CLOUD_MAIL_CONF_EOF",`cat > ${ne}/mail.env <<'TS_CLOUD_MAIL_ENV_EOF'`,yo(e),"TS_CLOUD_MAIL_ENV_EOF",`sed -i "s|^SMTP_DB_PATH=.*|SMTP_DB_PATH=$TS_CLOUD_MAIL_DB|" ${ne}/mail.env`,`chmod 0640 ${ne}/mail.env`,`chown root:${he} ${ne}/mail.env`,...To(e),`cat > /etc/systemd/system/${Cr}.service <<'TS_CLOUD_MAIL_UNIT_EOF'`,$o(e),"TS_CLOUD_MAIL_UNIT_EOF","systemctl daemon-reload",`systemctl enable ${Cr}`,`systemctl restart ${Cr}`,...bo(e)]}var le=`${T}/pantry/.bin`,Ar=15306,Dr=15991,Ht=15999,kn=16101,kt=2379,ye="/var/lib/vitess",Hr=100;function vt(e){return e===!0||typeof e==="object"&&e!==null}function wo(e){return typeof e==="object"&&e!==null?e:{}}function X(e){return`'${String(e).split("'").join("'\\''")}'`}function Co(e){let r=[e.version?`vitess.io@${e.version}`:"vitess.io"];if(e.mode!=="combo"&&!e.etcdEndpoint)r.push("etcd.io");return r.push("mysql.com@8.0.43"),r}var te="vitess",Po=`${le}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`,zn="/usr/local/lib/vitess",zr=new Map;function Ir(e){return`${zn}/${e}.sh`}function Je(e,t){return zr.set(e,Eo(t)),`/bin/sh ${Ir(e)}`}function Nn(){let e=[`mkdir -p ${zn}`];for(let[t,r]of zr)e.push(`cat > ${Ir(t)} <<'TS_CLOUD_VITESS_LAUNCHER_EOF'`,r,"TS_CLOUD_VITESS_LAUNCHER_EOF",`chmod 0755 ${Ir(t)}`);return e}function Eo(e){return["#!/bin/sh","set -e",`cd ${T}`,`PANTRY_ENV="$(pantry env 2>/dev/null | grep -E '^(export [A-Za-z_]|[A-Za-z_][A-Za-z0-9_]*=)' || true)"`,'if [ -n "$PANTRY_ENV" ]; then eval "$PANTRY_ENV"; fi',`VT_MYSQL_ROOT="$(dirname "$(dirname "$(readlink -f ${le}/mysqld 2>/dev/null)")")"`,`VTROOT="$(dirname "$(dirname "$(readlink -f ${le}/mysqlctld 2>/dev/null)")")"`,"export VT_MYSQL_ROOT VTROOT",'LD_LIBRARY_PATH="$VT_MYSQL_ROOT/lib:$VTROOT/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"',"export LD_LIBRARY_PATH",`exec ${e.join(" ")}`].join(`
@@ -24,7 +24,7 @@ EOF`,`DISK_PCT=$(df -P / | awk 'NR==2{gsub("%","",$5); print $5}')`,"UPTIME_SEC=
24
24
  `)}
25
25
  `}function qr(e){let t=`/etc/nginx/sites-available/${e.siteName}`,r=`/etc/nginx/sites-enabled/${e.siteName}`,n=sa(e),s=[...Wr()];if(e.auth){let i=Qn(e.siteName),a=(m)=>m.split("'").join("'\\''"),c=a(e.auth.password),u=a(e.auth.username);s.push(`TS_CLOUD_HTPASS=$(openssl passwd -apr1 '${c}')`,`printf '%s:%s\\n' '${u}' "$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",`${xe} -t`,"systemctl reload ts-cloud-nginx 2>/dev/null || systemctl restart ts-cloud-nginx 2>/dev/null || true"),s}var xe="/usr/local/bin/ts-cloud-nginx";function Wr(e="/opt/pantry"){return[...Nr(),...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 > ${xe} <<'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 ${xe}`,"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=${xe} -t`,`ExecStart=${xe} -g 'daemon off;'`,`ExecReload=${xe} -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 yt(e,t){return!e.events||e.events.includes(t)}async function Yr(e,t,r,n={}){if(!e)return[];let s=n.fetchImpl??globalThis.fetch,i=[],a=[],c=(u,m)=>s(u,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m)}).catch(()=>{return});if(e.slack?.webhookUrl&&yt(e,t))i.push("slack"),a.push(c(e.slack.webhookUrl,{text:r}));if(e.discord?.webhookUrl&&yt(e,t))i.push("discord"),a.push(c(e.discord.webhookUrl,{content:r}));if(e.telegram?.botToken&&e.telegram.chatId&&yt(e,t)){i.push("telegram");let u=`https://api.telegram.org/bot${e.telegram.botToken}/sendMessage`;a.push(c(u,{chat_id:e.telegram.chatId,text:r}))}if(e.webhook?.url&&yt(e,t))if(i.push("webhook"),(e.webhook.method||"POST")==="GET"){let u=e.webhook.url.includes("?")?"&":"?",m=`${e.webhook.url}${u}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&&yt(e,t))i.push("email"),a.push(ia(e.email,t,r));return await Promise.all(a),i}async function ia(e,t,r){try{let n=await import("./chunk-21mmcmm7.js");await n.email.send({to:e.to,from:e.from,subject:`[ts-cloud] ${t}`,text:r})}catch{}}function es(e,t){return t??e}function et(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"]}function tt(e=[],t={}){let r=t.path??"/root/.ssh/authorized_keys",s=[`mkdir -p ${r.replace(/\/[^/]*$/,"")}`,`touch ${r}`,`sed -i '/^${ts("# >>> ts-cloud managed keys >>>")}$/,/^${ts("# <<< ts-cloud managed keys <<<")}$/d' ${r}`];if(e.length>0){let i=["# >>> ts-cloud managed keys >>>",...e.map((a)=>`${a.publicKey.trim()} ${a.name}`),"# <<< ts-cloud managed keys <<<"].join(`
26
26
  `);s.push(`cat >> ${r} <<'TS_CLOUD_KEYS_EOF'`,i,"TS_CLOUD_KEYS_EOF",`chmod 600 ${r}`)}return s}function ts(e){return e.replace(/[.*[\]\\/^$]/g,"\\$&")}function ns(e,t){let r=`/tmp/ts-cloud-${e}.sh`,n=`TS_CLOUD_${e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}_EOF`;return[`cat > ${r} <<'${n}'`,t.replace(/\n$/,""),n,`chmod +x ${r}`,`bash ${r} || echo "ts-cloud: ${e} setup did not complete; continuing" >&2`,`rm -f ${r}`]}function ss(e,t){if(e===!1)return;if(e===!0||e===void 0)return t;return e}var rs={enabled:!0,ports:[80,443]},oa={mode:"detection",paranoiaLevel:1};function aa(e=!0,t=[]){let r=ss(e,rs);if(!r||r.enabled===!1)return[];let n=[...new Set([...r.ports??rs.ports??[],...t])].sort((s,i)=>s-i);return ns("ddos",Qi({...r,ports:n}))}function ca(e=!0){let t=ss(e,oa);if(!t||t.mode==="off")return[];return ns("waf",Ci(t))}function is(e={},t=[]){return[...aa(e.ddos,t),...ca(e.waf)]}function la(e){return`${e}-sftp`}function os(e){return e.port??2222}function ua(e){let t=e.sftp.storage;if(t?.type==="efs"&&t.path)return t.path;return`/var/sftp/${e.slug}`}function rt(e){return`'${e.split("'").join("'\\''")}'`}function as(e,t){if(t==="aws")return;let r=e.storage;if(r?.type==="s3"||!r&&!!e.bucket)throw Error(`sftp: bucket-backed storage is only available on the aws provider (Transfer Family). On ${t}, use storage: { type: 'efs' } to serve a directory on the server.`);for(let[s,i]of Object.entries(e.users))if(!i.sshPublicKeys?.length)throw Error(`sftp: user ${s} needs at least one SSH public key`)}function cs(e){let{slug:t,sftp:r}=e,n=la(t),s=ua(e),i=os(r),a="/etc/ts-sftp/host_key",c="/etc/ts-sftp/users",u=r.serviceUser??"ts-sftp",m=[`# --- ts-sftp (${n}) ---`,`id -u ${u} >/dev/null 2>&1 || useradd --system --home-dir ${rt(s)} --shell /usr/sbin/nologin ${u}`,'export HOME="${HOME:-/root}"','command -v bun >/dev/null 2>&1 || (curl -fsSL https://bun.sh/install | bash && ln -sf "$HOME/.bun/bin/bun" /usr/local/bin/bun)',`mkdir -p ${rt(s)} /etc/ts-sftp /etc/ts-sftp/users /opt/ts-sftp`,"chmod 750 /etc/ts-sftp",`cd /opt/ts-sftp && [ -f package.json ] || printf '{"name":"ts-sftp-host","private":true}' > package.json`,`cd /opt/ts-sftp && bun add ts-sftp@${r.version??"latest"} --no-save --production || bun add ts-sftp@${r.version??"latest"}`,`[ -f /etc/ts-sftp/host_key ] || bun /opt/ts-sftp/node_modules/ts-sftp/dist/bin/cli.js keygen --out /etc/ts-sftp/host_key --comment ${rt(`${t}-sftp`)}`,"chmod 600 /etc/ts-sftp/host_key",'BUN_REAL=$(readlink -f "$(command -v bun)")','case "$BUN_REAL" in /root/*) install -m 0755 "$BUN_REAL" /usr/local/bin/ts-sftp-bun; BUN_BIN=/usr/local/bin/ts-sftp-bun;; *) BUN_BIN="$BUN_REAL";; esac'],f=[];for(let[v,S]of Object.entries(r.users)){let _=(S.homeDirectory??v).replace(/^\/+|\/+$/g,"");if(!_||_.split("/").includes(".."))throw Error(`sftp: invalid homeDirectory for user ${v}`);let y=`/etc/ts-sftp/users/${v}.pub`;m.push(`mkdir -p ${rt(`${s}/${_}`)}`,`printf '%s\\n' ${rt(S.sshPublicKeys.join(`
27
- `))} > ${y}`,`chmod 644 ${y}`),f.push(`--user ${v}:${y}`)}return m.push(`chown -R ${u}:${u} ${rt(s)} /etc/ts-sftp`,`cat > /etc/systemd/system/${n}.service <<TSCLOUD_SFTP_UNIT`,"[Unit]","Description=ts-sftp file transfer server","After=network.target","","[Service]",`User=${u}`,`ExecStart=$BUN_BIN /opt/ts-sftp/node_modules/ts-sftp/dist/bin/cli.js serve --root ${s} --host-key /etc/ts-sftp/host_key --port ${i}${r.readOnly?" --read-only":""} ${f.join(" ")}`,"Restart=always","RestartSec=2","NoNewPrivileges=true","PrivateTmp=true","ProtectSystem=strict",`ReadWritePaths=${s}`,"","[Install]","WantedBy=multi-user.target","TSCLOUD_SFTP_UNIT","systemctl daemon-reload",`systemctl enable ${n}.service`,`systemctl restart ${n}.service`),m}function ls(e){return e?[os(e)]:[]}var pa=[80,443];function Bt(e={}){if(e.enabled===!1)return[];let t=[...new Set([...pa,...e.allowedPorts||[]])].filter((n)=>Number.isInteger(n)&&n>=1&&n<=65535).sort((n,s)=>n-s),r=["export DEBIAN_FRONTEND=noninteractive","command -v ufw >/dev/null 2>&1 || apt-get install -y ufw","ufw --force reset","ufw default deny incoming","ufw default allow outgoing","ufw allow OpenSSH"];for(let n of t)r.push(`ufw allow ${n}/tcp`);return r.push("ufw --force enable"),r}function Ue(e,t){let r=e.infrastructure?.compute??{},n=r.runtime==="php"||!!r.php,s=b(e,{environment:t?.environment}),i=n||!!r.managedServices,a=i?Nr():[],c=!j({...r,proxy:w(e,{environment:t?.environment})}),u=n?[...a,...Ft({versions:r.php?.versions,default:r.php?.default,extensions:r.php?.extensions,installNginx:c,optimizeForProduction:r.php?.optimizeForProduction,ini:r.php?.ini}),...c?Wr():[]]:void 0,m=[],f=g(e);if(!n&&i)m.push(...a);if(m.push(...et(e.notifications)),r.managedServices)m.push(...Nt(r.managedServices,{mail:s.enabled?s:void 0}),...Ze(f,r.managedServices));let v=e.infrastructure?.sftp;if(v)as(v,be(e)),m.push(...cs({slug:e.project.slug,sftp:v}));let S=r.firewall??(n?{enabled:!0}:{enabled:!1}),_=Xe(s);if(m.push(...Bt(_.length>0?{...S,allowedPorts:[...S.allowedPorts??[],..._]}:S)),m.push(...is({ddos:r.ddos,waf:r.waf},[...r.firewall?.allowedPorts??[],..._])),m.push(...Oe(r.autoUpdates??n)),m.push(...js(r.appUpdates)),m.push(...Re(r.monitoring??n)),m.push(...tt(r.sshKeys,{path:t?.authorizedKeysPath})),r.backups?.enabled)m.push(...Mt({database:f,backups:r.backups}));return{runtime:r.runtime||"bun",runtimeVersion:r.runtimeVersion||"latest",phpBox:n,phpProvision:u,servicesProvision:m.length>0?m:void 0}}function M(e={}){let{runtime:t="bun",runtimeVersion:r="latest",systemPackages:n=[],database:s,phpProvision:i,servicesProvision:a,caddyfile:c,rpxProvision:u,baked:m=!1,swapGb:f=2}=e,v=new Set(n);if(s==="sqlite")v.add("sqlite3");else if(s==="mysql")v.add("mysql-client");else if(s==="postgres")v.add("postgresql-client");let S=`#!/bin/bash
27
+ `))} > ${y}`,`chmod 644 ${y}`),f.push(`--user ${v}:${y}`)}return m.push(`chown -R ${u}:${u} ${rt(s)} /etc/ts-sftp`,`cat > /etc/systemd/system/${n}.service <<TSCLOUD_SFTP_UNIT`,"[Unit]","Description=ts-sftp file transfer server","After=network.target","","[Service]",`User=${u}`,`ExecStart=$BUN_BIN /opt/ts-sftp/node_modules/ts-sftp/dist/bin/cli.js serve --root ${s} --host-key /etc/ts-sftp/host_key --port ${i}${r.readOnly?" --read-only":""} ${f.join(" ")}`,"Restart=always","RestartSec=2","NoNewPrivileges=true","PrivateTmp=true","ProtectSystem=strict",`ReadWritePaths=${s}`,"","[Install]","WantedBy=multi-user.target","TSCLOUD_SFTP_UNIT","systemctl daemon-reload",`systemctl enable ${n}.service`,`systemctl restart ${n}.service`),m}function ls(e){return e?[os(e)]:[]}var pa=[80,443];function Bt(e={}){if(e.enabled===!1)return[];let t=[...new Set([...pa,...e.allowedPorts||[]])].filter((n)=>Number.isInteger(n)&&n>=1&&n<=65535).sort((n,s)=>n-s),r=["export DEBIAN_FRONTEND=noninteractive","command -v ufw >/dev/null 2>&1 || apt-get install -y ufw","ufw --force reset","ufw default deny incoming","ufw default allow outgoing","ufw allow OpenSSH"];for(let n of t)r.push(`ufw allow ${n}/tcp`);return r.push("ufw --force enable"),r}function He(e,t){let r=e.infrastructure?.compute??{},n=r.runtime==="php"||!!r.php,s=b(e,{environment:t?.environment}),i=n||!!r.managedServices,a=i?Nr():[],c=!j({...r,proxy:w(e,{environment:t?.environment})}),u=n?[...a,...Ft({versions:r.php?.versions,default:r.php?.default,extensions:r.php?.extensions,installNginx:c,optimizeForProduction:r.php?.optimizeForProduction,ini:r.php?.ini}),...c?Wr():[]]:void 0,m=[],f=g(e);if(!n&&i)m.push(...a);if(m.push(...et(e.notifications)),r.managedServices)m.push(...Nt(r.managedServices,{mail:s.enabled?s:void 0}),...Ze(f,r.managedServices));let v=e.infrastructure?.sftp;if(v)as(v,be(e)),m.push(...cs({slug:e.project.slug,sftp:v}));let S=r.firewall??(n?{enabled:!0}:{enabled:!1}),_=Xe(s);if(m.push(...Bt(_.length>0?{...S,allowedPorts:[...S.allowedPorts??[],..._]}:S)),m.push(...is({ddos:r.ddos,waf:r.waf},[...r.firewall?.allowedPorts??[],..._])),m.push(...Oe(r.autoUpdates??n)),m.push(...js(r.appUpdates)),m.push(...Re(r.monitoring??n)),m.push(...tt(r.sshKeys,{path:t?.authorizedKeysPath})),r.backups?.enabled)m.push(...Mt({database:f,backups:r.backups}));return{runtime:r.runtime||"bun",runtimeVersion:r.runtimeVersion||"latest",phpBox:n,phpProvision:u,servicesProvision:m.length>0?m:void 0}}function M(e={}){let{runtime:t="bun",runtimeVersion:r="latest",systemPackages:n=[],database:s,phpProvision:i,servicesProvision:a,caddyfile:c,rpxProvision:u,baked:m=!1,swapGb:f=2}=e,v=new Set(n);if(s==="sqlite")v.add("sqlite3");else if(s==="mysql")v.add("mysql-client");else if(s==="postgres")v.add("postgresql-client");let S=`#!/bin/bash
28
28
  set -euo pipefail
29
29
  `,_=Math.floor(f);if(_>0)S+=`
30
30
  # Swap: a swapless box under memory pressure lets the kernel OOM killer choose
@@ -134,10 +134,10 @@ ${y.join(`
134
134
  `)}
135
135
  `}return S+=`
136
136
  echo "ts-cloud bootstrap complete — instance is ready for site deploys"
137
- `,S}var us="/aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id";function ps(e,t){let r=[{port:22,protocol:"tcp",cidr:"0.0.0.0/0"},{port:80,protocol:"tcp",cidr:"0.0.0.0/0"},{port:443,protocol:"tcp",cidr:"0.0.0.0/0"}],n=new Set;for(let s of Object.values(e.sites||{}))if(s&&typeof s.port==="number"&&![22,80,443].includes(s.port))n.add(s.port);for(let s of Xe(b(e,{environment:t})))n.add(s);for(let s of n)r.push({port:s,protocol:"tcp",cidr:"0.0.0.0/0"});return r}function ds(e,t){let r={...e.infrastructure?.compute,proxy:w(e,{environment:t})},n=Ue(e,{environment:t}),s=r.proxy?.engine==="rpx"?G({proxy:r.proxy,config:B(e.sites??{},{proxy:r.proxy,slug:e.project.slug,mail:b(e,{environment:t})}),slug:e.project.slug,bunBin:r.runtime==="node"||r.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0;return M({runtime:n.runtime,runtimeVersion:n.runtimeVersion,systemPackages:r.systemPackages,database:e.infrastructure?.database,phpProvision:n.phpProvision,servicesProvision:n.servicesProvision,rpxProvision:s,baked:r.bakedImage===!0,swapGb:r.swapGb})}function ms(e){return Buffer.from(e,"utf8").toString("base64")}function fs(e){return e.infrastructure?.compute?.image??null}function Gt(e,t){return`${e}-${t}-app-sg`}function Xr(e,t,r="app"){return[{Key:"Project",Value:e},{Key:"Environment",Value:t},{Key:"Role",Value:r},{Key:"ManagedBy",Value:"ts-cloud"}]}function da(e,t,r){if(!e?.length)return!1;let n=(s)=>e.find((i)=>i.Key===s)?.Value;return n("Project")===t&&n("Environment")===r}function gs(e,t){let r=Gt(t.slug,t.environment);return e.find((n)=>{if(n.GroupName!==r)return!1;if(t.vpcId&&n.VpcId&&n.VpcId!==t.vpcId)return!1;if(!!n.Tags?.some((i)=>i.Key==="Project"))return da(n.Tags,t.slug,t.environment);return!!t.vpcId&&n.VpcId===t.vpcId})}function fa(e){try{let t=hs(ma(process.cwd(),"storage/cloud/state",`${e}.json`),"utf8"),r=JSON.parse(t);return typeof r.instanceId==="string"&&r.instanceId.length>0?r.instanceId:null}catch{return null}}class Br{name="aws";usesCloudFormation=!0;region;ec2Client;cfnClient;constructor(e={}){this.region=e.region||"us-east-1",this.ec2Client=e.ec2Client??((t)=>new Ur(t)),this.cfnClient=e.cfnClient??((t)=>new h(t))}resolveRegion(e){return e.project.region||this.region}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e,n=this.resolveRegion(t),s=t.project.slug,i=t.infrastructure?.compute;if(!i)throw Error("infrastructure.compute is required to provision AWS compute");let a=this.ec2Client(n),c=await this.findComputeTargets({slug:s,environment:r,role:"app",region:n});if(c.length>0){let I=c[0];return{appInstanceId:I.id,appPublicIp:I.publicIp,appPublicIpv6:I.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}let u=fs(t);if(!u){if(u=(await new Be(n).getParameter({Name:us})).Parameter?.Value??null,!u)throw Error("Could not resolve the Ubuntu 24.04 AMI from SSM")}let m=await a.describeVpcs(),f=(m.Vpcs||[]).find((I)=>I.IsDefault)||(m.Vpcs||[])[0];if(!f?.VpcId)throw Error("No VPC found to launch the instance into");let v=(await a.describeSubnets({Filters:[{Name:"vpc-id",Values:[f.VpcId]}]})).Subnets||[],S=v.find((I)=>I.MapPublicIpOnLaunch)||v[0],_=S?.SubnetId;if(!S?.MapPublicIpOnLaunch)console.warn("ts-cloud: no public subnet found; the instance may not get a public IP (deploys/SSL need one).");let y=Gt(s,r),R=(await a.describeSecurityGroups({Filters:[{Name:"group-name",Values:[y]},{Name:"vpc-id",Values:[f.VpcId]}]})).SecurityGroups?.[0]?.GroupId;if(!R)R=(await a.createSecurityGroup({GroupName:y,Description:`ts-cloud ${s}/${r} app`,VpcId:f.VpcId,TagSpecifications:[{ResourceType:"security-group",Tags:Xr(s,r)}]})).GroupId;let E=ps(t,r);await a.authorizeSecurityGroupIngress({GroupId:R,IpPermissions:E.map((I)=>({IpProtocol:I.protocol,FromPort:I.port,ToPort:I.port,IpRanges:[{CidrIp:I.cidr}]}))}).catch((I)=>{if(!/InvalidPermission\.Duplicate/.test(I instanceof Error?I.message:""))throw I});let D=ms(ds(t,r)),C=i.server?.instanceType||"t3.small",L=(await a.runInstances({ImageId:u,InstanceType:C,MinCount:1,MaxCount:1,SecurityGroupIds:R?[R]:void 0,SubnetId:_,UserData:D,IamInstanceProfile:i.server?.iamInstanceProfile?{Name:i.server.iamInstanceProfile}:void 0,TagSpecifications:[{ResourceType:"instance",Tags:[{Key:"Name",Value:`${s}-${r}-app`},...Xr(s,r)]}]})).Instances?.[0]?.InstanceId;if(!L)throw Error("RunInstances did not return an instance id");let O=await a.waitForInstanceState(L,"running");if(!O)throw Error(`Instance ${L} did not reach 'running' before timeout`);return{appInstanceId:L,appPublicIp:O.PublicIpAddress,appPublicIpv6:De(O.Ipv6Address),sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}async destroyCompute(e){let{config:t,environment:r}=e,n=t.project.slug,s=this.resolveRegion(t),i=this.ec2Client(s),a=[],u=(await this.findComputeTargets({slug:n,environment:r,role:"app",region:s})).map((y)=>y.id),m;if(u.length>0)m=(await i.describeInstances({InstanceIds:u}).catch(()=>({Reservations:[]}))).Reservations?.flatMap((x)=>x.Instances??[]).find((x)=>x.VpcId)?.VpcId;if(u.length>0)await i.terminateInstances(u),a.push(...u.map((y)=>`instance ${y}`)),await Promise.all(u.map((y)=>i.waitForInstanceState(y,"terminated").catch(()=>{return})));let f=Gt(n,r),v=[{Name:"group-name",Values:[f]}];if(m)v.push({Name:"vpc-id",Values:[m]});let S=await i.describeSecurityGroups({Filters:v}).catch(()=>({SecurityGroups:[]})),_=gs(S.SecurityGroups??[],{slug:n,environment:r,vpcId:m});if(_?.GroupId)for(let y=0;y<10;y++)try{await i.deleteSecurityGroup(_.GroupId),a.push(`security group ${f}`);break}catch{await new Promise((x)=>setTimeout(x,3000))}return{destroyed:a}}async getComputeOutputs(e){let t=this.resolveRegion(e.config),r=p(e.config,e.environment),n=this.cfnClient(t);try{let s=await n.getStackOutputs(r);return{deployBucketName:s.deployBucketName,appInstanceId:s.appInstanceId,appPublicIp:s.appPublicIp,sshUser:"ec2-user"}}catch(s){if(!/does not exist|ValidationError/i.test(s instanceof Error?s.message:""))throw s;let a=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",region:t}))[0];return{appInstanceId:a?.id,appPublicIp:a?.publicIp,appPublicIpv6:a?.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}}async uploadRelease(e){let t=this.resolveRegion(e.config),n=(await this.getComputeOutputs({config:e.config,environment:e.environment})).deployBucketName;if(!n)throw Error("No deployBucketName in stack outputs. Re-deploy infrastructure to add the staging bucket.");return await new o(t).putObject({bucket:n,key:e.remoteKey,body:hs(e.localPath),contentType:"application/gzip"}),{artifactRef:`s3://${n}/${e.remoteKey}`}}async findComputeTargets(e){let t=e.region??this.region,r=this.ec2Client(t),n=[{Name:"tag:Project",Values:[e.slug]},{Name:"tag:Environment",Values:[e.environment]},{Name:"tag:Role",Values:[e.role||"app"]},{Name:"instance-state-name",Values:["running","pending"]}],s=await r.describeInstances({Filters:n}),i=this.reservationsToTargets(s.Reservations);if(i.length>0||(e.role||"app")!=="app")return i;let a=e.stackName??`${e.slug}-${e.environment}`,c=fa(a);if(!c)try{c=(await this.cfnClient(t).getStackOutputs(a)).appInstanceId??null}catch{c=null}if(!c)return[];try{let u=await r.describeInstances({InstanceIds:[c],Filters:[{Name:"instance-state-name",Values:["running","pending"]}]});return this.reservationsToTargets(u.Reservations)}catch{return[]}}reservationsToTargets(e){let t=[];for(let r of e||[])for(let n of r.Instances||[]){if(!n.InstanceId)continue;let s=n.Tags?.find((i)=>i.Key==="Name")?.Value;t.push({id:n.InstanceId,name:s,publicIp:n.PublicIpAddress,publicIpv6:De(n.Ipv6Address),privateIp:n.PrivateIpAddress,status:n.State?.Name})}return t}bashWrap(e){return["bash <<'TS_CLOUD_BASH_EOF'",e.join(`
137
+ `,S}var us="/aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id";function ps(e,t){let r=[{port:22,protocol:"tcp",cidr:"0.0.0.0/0"},{port:80,protocol:"tcp",cidr:"0.0.0.0/0"},{port:443,protocol:"tcp",cidr:"0.0.0.0/0"}],n=new Set;for(let s of Object.values(e.sites||{}))if(s&&typeof s.port==="number"&&![22,80,443].includes(s.port))n.add(s.port);for(let s of Xe(b(e,{environment:t})))n.add(s);for(let s of n)r.push({port:s,protocol:"tcp",cidr:"0.0.0.0/0"});return r}function ds(e,t){let r={...e.infrastructure?.compute,proxy:w(e,{environment:t})},n=He(e,{environment:t}),s=r.proxy?.engine==="rpx"?G({proxy:r.proxy,config:B(e.sites??{},{proxy:r.proxy,slug:e.project.slug,mail:b(e,{environment:t})}),slug:e.project.slug,bunBin:r.runtime==="node"||r.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0;return M({runtime:n.runtime,runtimeVersion:n.runtimeVersion,systemPackages:r.systemPackages,database:e.infrastructure?.database,phpProvision:n.phpProvision,servicesProvision:n.servicesProvision,rpxProvision:s,baked:r.bakedImage===!0,swapGb:r.swapGb})}function ms(e){return Buffer.from(e,"utf8").toString("base64")}function fs(e){return e.infrastructure?.compute?.image??null}function Gt(e,t){return`${e}-${t}-app-sg`}function Xr(e,t,r="app"){return[{Key:"Project",Value:e},{Key:"Environment",Value:t},{Key:"Role",Value:r},{Key:"ManagedBy",Value:"ts-cloud"}]}function da(e,t,r){if(!e?.length)return!1;let n=(s)=>e.find((i)=>i.Key===s)?.Value;return n("Project")===t&&n("Environment")===r}function gs(e,t){let r=Gt(t.slug,t.environment);return e.find((n)=>{if(n.GroupName!==r)return!1;if(t.vpcId&&n.VpcId&&n.VpcId!==t.vpcId)return!1;if(!!n.Tags?.some((i)=>i.Key==="Project"))return da(n.Tags,t.slug,t.environment);return!!t.vpcId&&n.VpcId===t.vpcId})}function fa(e){try{let t=hs(ma(process.cwd(),"storage/cloud/state",`${e}.json`),"utf8"),r=JSON.parse(t);return typeof r.instanceId==="string"&&r.instanceId.length>0?r.instanceId:null}catch{return null}}class Br{name="aws";usesCloudFormation=!0;region;ec2Client;cfnClient;constructor(e={}){this.region=e.region||"us-east-1",this.ec2Client=e.ec2Client??((t)=>new Ur(t)),this.cfnClient=e.cfnClient??((t)=>new h(t))}resolveRegion(e){return e.project.region||this.region}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e,n=this.resolveRegion(t),s=t.project.slug,i=t.infrastructure?.compute;if(!i)throw Error("infrastructure.compute is required to provision AWS compute");let a=this.ec2Client(n),c=await this.findComputeTargets({slug:s,environment:r,role:"app",region:n});if(c.length>0){let I=c[0];return{appInstanceId:I.id,appPublicIp:I.publicIp,appPublicIpv6:I.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}let u=fs(t);if(!u){if(u=(await new Be(n).getParameter({Name:us})).Parameter?.Value??null,!u)throw Error("Could not resolve the Ubuntu 24.04 AMI from SSM")}let m=await a.describeVpcs(),f=(m.Vpcs||[]).find((I)=>I.IsDefault)||(m.Vpcs||[])[0];if(!f?.VpcId)throw Error("No VPC found to launch the instance into");let v=(await a.describeSubnets({Filters:[{Name:"vpc-id",Values:[f.VpcId]}]})).Subnets||[],S=v.find((I)=>I.MapPublicIpOnLaunch)||v[0],_=S?.SubnetId;if(!S?.MapPublicIpOnLaunch)console.warn("ts-cloud: no public subnet found; the instance may not get a public IP (deploys/SSL need one).");let y=Gt(s,r),R=(await a.describeSecurityGroups({Filters:[{Name:"group-name",Values:[y]},{Name:"vpc-id",Values:[f.VpcId]}]})).SecurityGroups?.[0]?.GroupId;if(!R)R=(await a.createSecurityGroup({GroupName:y,Description:`ts-cloud ${s}/${r} app`,VpcId:f.VpcId,TagSpecifications:[{ResourceType:"security-group",Tags:Xr(s,r)}]})).GroupId;let E=ps(t,r);await a.authorizeSecurityGroupIngress({GroupId:R,IpPermissions:E.map((I)=>({IpProtocol:I.protocol,FromPort:I.port,ToPort:I.port,IpRanges:[{CidrIp:I.cidr}]}))}).catch((I)=>{if(!/InvalidPermission\.Duplicate/.test(I instanceof Error?I.message:""))throw I});let D=ms(ds(t,r)),C=i.server?.instanceType||"t3.small",L=(await a.runInstances({ImageId:u,InstanceType:C,MinCount:1,MaxCount:1,SecurityGroupIds:R?[R]:void 0,SubnetId:_,UserData:D,IamInstanceProfile:i.server?.iamInstanceProfile?{Name:i.server.iamInstanceProfile}:void 0,TagSpecifications:[{ResourceType:"instance",Tags:[{Key:"Name",Value:`${s}-${r}-app`},...Xr(s,r)]}]})).Instances?.[0]?.InstanceId;if(!L)throw Error("RunInstances did not return an instance id");let O=await a.waitForInstanceState(L,"running");if(!O)throw Error(`Instance ${L} did not reach 'running' before timeout`);return{appInstanceId:L,appPublicIp:O.PublicIpAddress,appPublicIpv6:De(O.Ipv6Address),sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}async destroyCompute(e){let{config:t,environment:r}=e,n=t.project.slug,s=this.resolveRegion(t),i=this.ec2Client(s),a=[],u=(await this.findComputeTargets({slug:n,environment:r,role:"app",region:s})).map((y)=>y.id),m;if(u.length>0)m=(await i.describeInstances({InstanceIds:u}).catch(()=>({Reservations:[]}))).Reservations?.flatMap((x)=>x.Instances??[]).find((x)=>x.VpcId)?.VpcId;if(u.length>0)await i.terminateInstances(u),a.push(...u.map((y)=>`instance ${y}`)),await Promise.all(u.map((y)=>i.waitForInstanceState(y,"terminated").catch(()=>{return})));let f=Gt(n,r),v=[{Name:"group-name",Values:[f]}];if(m)v.push({Name:"vpc-id",Values:[m]});let S=await i.describeSecurityGroups({Filters:v}).catch(()=>({SecurityGroups:[]})),_=gs(S.SecurityGroups??[],{slug:n,environment:r,vpcId:m});if(_?.GroupId)for(let y=0;y<10;y++)try{await i.deleteSecurityGroup(_.GroupId),a.push(`security group ${f}`);break}catch{await new Promise((x)=>setTimeout(x,3000))}return{destroyed:a}}async getComputeOutputs(e){let t=this.resolveRegion(e.config),r=p(e.config,e.environment),n=this.cfnClient(t);try{let s=await n.getStackOutputs(r);return{deployBucketName:s.deployBucketName,appInstanceId:s.appInstanceId,appPublicIp:s.appPublicIp,sshUser:"ec2-user"}}catch(s){if(!/does not exist|ValidationError/i.test(s instanceof Error?s.message:""))throw s;let a=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",region:t}))[0];return{appInstanceId:a?.id,appPublicIp:a?.publicIp,appPublicIpv6:a?.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}}async uploadRelease(e){let t=this.resolveRegion(e.config),n=(await this.getComputeOutputs({config:e.config,environment:e.environment})).deployBucketName;if(!n)throw Error("No deployBucketName in stack outputs. Re-deploy infrastructure to add the staging bucket.");return await new o(t).putObject({bucket:n,key:e.remoteKey,body:hs(e.localPath),contentType:"application/gzip"}),{artifactRef:`s3://${n}/${e.remoteKey}`}}async findComputeTargets(e){let t=e.region??this.region,r=this.ec2Client(t),n=[{Name:"tag:Project",Values:[e.slug]},{Name:"tag:Environment",Values:[e.environment]},{Name:"tag:Role",Values:[e.role||"app"]},{Name:"instance-state-name",Values:["running","pending"]}],s=await r.describeInstances({Filters:n}),i=this.reservationsToTargets(s.Reservations);if(i.length>0||(e.role||"app")!=="app")return i;let a=e.stackName??`${e.slug}-${e.environment}`,c=fa(a);if(!c)try{c=(await this.cfnClient(t).getStackOutputs(a)).appInstanceId??null}catch{c=null}if(!c)return[];try{let u=await r.describeInstances({InstanceIds:[c],Filters:[{Name:"instance-state-name",Values:["running","pending"]}]});return this.reservationsToTargets(u.Reservations)}catch{return[]}}reservationsToTargets(e){let t=[];for(let r of e||[])for(let n of r.Instances||[]){if(!n.InstanceId)continue;let s=n.Tags?.find((i)=>i.Key==="Name")?.Value;t.push({id:n.InstanceId,name:s,publicIp:n.PublicIpAddress,publicIpv6:De(n.Ipv6Address),privateIp:n.PrivateIpAddress,status:n.State?.Name})}return t}bashWrap(e){return["bash <<'TS_CLOUD_BASH_EOF'",e.join(`
138
138
  `),"TS_CLOUD_BASH_EOF"]}async runRemoteDeploy(e){let t=this.region,r=new Be(t);if(e.targets.length>0){let s=await r.sendCommand({InstanceIds:e.targets.map((i)=>i.id),DocumentName:"AWS-RunShellScript",Parameters:{commands:this.bashWrap(e.commands)},TimeoutSeconds:e.timeoutSeconds||600,Comment:e.comment});if(!s.CommandId)return{success:!1,instanceCount:0,perInstance:[],error:"Failed to send SSM command"};return this.pollSsmCommand(r,s.CommandId,e.targets.length,((e.timeoutSeconds||600)+30)*1000)}if(!e.tags||Object.keys(e.tags).length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets or tags provided for AWS deploy"};let n=await r.sendCommandByTags({tags:e.tags,commands:this.bashWrap(e.commands),timeoutSeconds:e.timeoutSeconds||600,comment:e.comment});return{success:n.success,instanceCount:n.instanceCount,perInstance:n.perInstance.map((s)=>({instanceId:s.instanceId,status:s.status,output:s.output,error:s.error})),error:n.error}}async pollSsmCommand(e,t,r,n=600000){let i=Date.now(),a=new Set(["Success","Failed","Cancelled","TimedOut"]),c=[];while(Date.now()-i<n){await new Promise((f)=>setTimeout(f,3000));try{if(c=await e.listCommandInvocations({CommandId:t,Details:!0}),c.length>=r&&c.every((v)=>a.has(v.Status||"")))break}catch{}}let u=c.map((f)=>({instanceId:f.InstanceId,status:f.Status||"Unknown",output:f.StandardOutputContent,error:f.StandardErrorContent})),m=u.length>0&&u.every((f)=>f.status==="Success");return{success:m,instanceCount:u.length,perInstance:u,error:m?void 0:zt(u,"One or more SSM command invocations failed")}}}function Xn(e={},t="ssh"){let r=[];if(e.identityFile)r.push("-i",e.identityFile);if(e.port)r.push(t==="scp"?"-P":"-p",String(e.port));return r.push("-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR","-o",`ConnectTimeout=${e.connectTimeoutSec??10}`),r}async function xr(e,t,r={}){let n=Bun.spawn(["ssh",...Xn(r),`${r.user??"root"}@${e}`,t],{stdout:"pipe",stderr:"pipe"}),[s,i]=await Promise.all([new Response(n.stdout).text(),new Response(n.stderr).text()]);return{code:await n.exited,stdout:s,stderr:i}}async function Se(e,t,r={}){let n=await xr(e,t,r);if(n.code!==0)throw Error(`ssh \`${t}\` on ${e} failed (${n.code}): ${n.stderr.trim()||n.stdout.trim()}`);return n.stdout}async function Rc(e,t,r,n={}){let s=Bun.spawn(["scp",...Xn(n,"scp"),...t,`${n.user??"root"}@${e}:${r}`],{stdout:"pipe",stderr:"pipe"}),i=await s.exited;if(i!==0){let a=await new Response(s.stderr).text();throw Error(`scp to ${e}:${r} failed (${i}): ${a.trim()}`)}}async function Yn(e,t={}){let r=t.timeoutMs??180000,n=t.pollIntervalMs??5000,s=Date.now();while(Date.now()-s<r){let i=await xr(e,"echo ready",t);if(i.code===0&&i.stdout.includes("ready"))return;await new Promise((a)=>setTimeout(a,n))}throw Error(`SSH not ready on ${e} after ${r}ms`)}async function Dc(e,t={}){let r=t.timeoutMs??300000,n=t.pollIntervalMs??5000,s=Date.now();while(Date.now()-s<r){let i=await xr(e,"cloud-init status 2>/dev/null || echo unknown",t);if(i.stdout.includes("status: done"))return;if(i.stdout.includes("status: error"))throw Error(`cloud-init reported an error on ${e}; check /var/log/cloud-init-output.log`);await new Promise((a)=>setTimeout(a,n))}throw Error(`cloud-init did not finish on ${e} after ${r}ms`)}function Zn(e={}){return["set -e","ts_cloud_script=$(mktemp /tmp/ts-cloud-deploy.XXXXXXXX)",`trap 'rm -f "$ts_cloud_script"' EXIT`,'cat > "$ts_cloud_script"',e.sudo?'sudo -n -H bash "$ts_cloud_script" < /dev/null':'bash "$ts_cloud_script" < /dev/null'].join(`
139
139
  `)}var Pc=Zn();import{execFileSync as Ka,execSync as ks}from"node:child_process";import{createHash as ja,randomUUID as Ns}from"node:crypto";import{createReadStream as Ga,existsSync as Va,readFileSync as qa}from"node:fs";function Vt(e){return Object.entries(e).map(([t,r])=>`${t}=${ga(String(r))}`).join(`
140
- `)}function ga(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}var qt=["storage",".env"],$t=4;function Te(e){return`${e.replace(/\/+$/,"")}/.ts-cloud`}function ha(e){return`${Te(e)}/deploy-history.log`}function Sa(e,t){return`${Te(e)}/deploys/${t}.log`}function Ss(e){return`${Te(e)}/shared-paths`}function Yt(e){return`${e.shared}/stx-images`}function Wt(e,t){let r=e.replace(/\/+$/,"");return{base:r,releases:`${r}/releases`,shared:`${r}/shared`,current:`${r}/current`,release:`${r}/releases/${t}`}}function _s(e){let t=e.split("/").pop()||e;if(t===".env"||t.startsWith(".env."))return!0;return/\.[a-z0-9]+$/i.test(t)}function Jr(e){return typeof e==="string"?e:e.path}function vs(e){let t=new Map;for(let r of e)t.set(Jr(r),r);return[...t.values()]}function ys(e,t){if(typeof t==="string")return{path:t,target:`${e.shared}/${t}`,seed:!0};return{path:t.path,target:t.target??`${e.shared}/${t.path}`,seed:t.seed!==!1}}function _a(e){return["ts_cloud_adopt_shared() {",' TS_CLOUD_SP="$1"',' TS_CLOUD_DST="$2"',` TS_CLOUD_SRC="${e.current}/$TS_CLOUD_SP"`,' if [ -e "$TS_CLOUD_DST" ]; then return 0; fi',' if [ -L "$TS_CLOUD_SRC" ] || [ ! -e "$TS_CLOUD_SRC" ]; then return 0; fi',' mkdir -p "$(dirname "$TS_CLOUD_DST")"',' cp -a "$TS_CLOUD_SRC" "$TS_CLOUD_DST"'," for TS_CLOUD_SIDECAR in -wal -shm; do",' if [ -f "$TS_CLOUD_SRC$TS_CLOUD_SIDECAR" ]; then cp -a "$TS_CLOUD_SRC$TS_CLOUD_SIDECAR" "$TS_CLOUD_DST$TS_CLOUD_SIDECAR"; fi'," done",' echo "[ts-cloud] adopted $TS_CLOUD_SP from the live release into shared/ — it now survives deploys"'," return 0","}"]}function bt(e,t=qt){let r=[`mkdir -p ${e.releases} ${e.shared} ${Yt(e)}`,..._a(e)],n=t.map((i)=>ys(e,i));for(let{path:i,target:a,seed:c}of n){if(!c)continue;if(r.push(`ts_cloud_adopt_shared '${i}' '${a}'`),_s(i))r.push(`mkdir -p "$(dirname ${a})"`,`touch ${a}`);else if(i==="storage")r.push(`mkdir -p ${a}/app/public`,`mkdir -p ${a}/framework/cache/data`,`mkdir -p ${a}/framework/sessions`,`mkdir -p ${a}/framework/testing`,`mkdir -p ${a}/framework/views`,`mkdir -p ${a}/logs`);else r.push(`mkdir -p ${a}`)}let s=Ss(e.base);return r.push(`mkdir -p ${Te(e.base)}`,`cat > ${s} <<'TS_CLOUD_SHARED_PATHS_EOF'`,...n.map((i)=>`${i.path} ${i.target}`),"TS_CLOUD_SHARED_PATHS_EOF"),r}function Qr(e,t=900){let r=`${Te(e.base)}/deploy.lock`;return[`mkdir -p "$(dirname ${r})"`,`exec 9>${r}`,`flock -w ${t} 9 || { echo "[ts-cloud] another deploy of this site has held the lock for ${t}s — refusing to race it" >&2; exit 1; }`]}function Zr(e){let t=`${e.release}.incoming`;return[`rm -rf ${t}`,`mkdir -p ${t}`,...va(e),'if [ "$TS_CLOUD_IS_LIVE" = "yes" ]; then',` TS_CLOUD_STAGED=${t}`,"else",` rm -rf ${e.release}`,` mkdir -p ${e.release}`,` rmdir ${t}`,` TS_CLOUD_STAGED=${e.release}`,"fi"]}function en(e){let t=`TS_CLOUD_TRAP_LIVE="$(readlink -f ${e.current} 2>/dev/null || true)"`,r=`TS_CLOUD_TRAP_TARGET="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`;return`trap '${`if [ $? -ne 0 ]; then ${t}; ${r}; [ "$TS_CLOUD_TRAP_LIVE" = "$TS_CLOUD_TRAP_TARGET" ] || rm -rf ${e.release}; fi`}' EXIT`}function va(e){return[`TS_CLOUD_LIVE_PATH="$(readlink -f ${e.current} 2>/dev/null || true)"`,`TS_CLOUD_RELEASE_PATH="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`,'if [ -n "$TS_CLOUD_LIVE_PATH" ] && [ "$TS_CLOUD_LIVE_PATH" = "$TS_CLOUD_RELEASE_PATH" ]; then TS_CLOUD_IS_LIVE=yes; else TS_CLOUD_IS_LIVE=no; fi']}function tn(e){let t=`${e.release}.incoming`;return[`if [ "$TS_CLOUD_STAGED" = "${t}" ]; then`,` rm -rf ${e.release}.previous`,` mv ${e.release} ${e.release}.previous`,` mv ${t} ${e.release}`,` rm -rf ${e.release}.previous`,"fi"]}function ya(e,t){return[`if [ -f ${e} ] && [ ! -L ${e} ] && [ -s ${e} ] && [ ! -s ${t} ]; then`,` cp -a ${e} ${t}`,` echo "[ts-cloud] seeded shared/ from the release's own copy of the file"`,"fi"]}function Qt(e,t=qt){let r=[];for(let n of t){let{path:s,target:i,seed:a}=ys(e,n),c=`${e.release}/${s}`,u=[`rm -rf ${c}`,`mkdir -p "$(dirname ${c})"`,`ln -sfn ${i} ${c}`];if(a){if(s!==".env"&&_s(s))r.push(...ya(c,i));r.push(...u);continue}r.push(`if [ -e ${i} ]; then`,...u.map((m)=>` ${m}`),"fi")}return r}function $a(e,t){let r=Ss(e.base);return[`if [ -f ${r} ]; then`,' while IFS="\t" read -r TS_CLOUD_SP TS_CLOUD_TGT; do',' [ -n "$TS_CLOUD_SP" ] || continue',` [ -n "$TS_CLOUD_TGT" ] || TS_CLOUD_TGT="${e.shared}/$TS_CLOUD_SP"`,' [ -e "$TS_CLOUD_TGT" ] || continue',` rm -rf ${t}/"$TS_CLOUD_SP"`,` mkdir -p "$(dirname ${t}/"$TS_CLOUD_SP")"`,` ln -sfn "$TS_CLOUD_TGT" ${t}/"$TS_CLOUD_SP"`,` done < ${r}`,"fi"]}function nt(e){return[`ln -sfn ${e.release} ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`]}function rn(e){return`${Te(e)}/previous-release`}function nn(e,t="TS_CLOUD_PREV_CURRENT"){let r=rn(e.base);return[`if [ -n "\${${t}:-}" ] && [ -d "$${t}" ] && [ "$(readlink -f "$${t}")" != "$(readlink -f ${e.release})" ]; then mkdir -p ${Te(e.base)}; basename "$${t}" > ${r}; fi`]}function $s(e,t){let r=rn(e.base);return[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,...t?[`TS_CLOUD_RB_TARGET=${e.releases}/${t}`]:["TS_CLOUD_RB_TARGET=",`if [ -f ${r} ]; then TS_CLOUD_REC="${e.releases}/$(cat ${r})"; if [ -d "$TS_CLOUD_REC" ] && [ "$(readlink -f "$TS_CLOUD_REC")" != "$TS_CLOUD_CURRENT" ]; then TS_CLOUD_RB_TARGET="$TS_CLOUD_REC"; fi; fi`,`[ -n "$TS_CLOUD_RB_TARGET" ] || TS_CLOUD_RB_TARGET=$(ls -1dt ${e.releases}/*/ 2>/dev/null | sed 's#/$##' | while read -r r; do [ "$(readlink -f "$r")" != "$TS_CLOUD_CURRENT" ] && { echo "$r"; break; }; done)`],'[ -n "$TS_CLOUD_RB_TARGET" ] && [ -d "$TS_CLOUD_RB_TARGET" ] || { echo "no release to roll back to (looked for ${TS_CLOUD_RB_TARGET:-a previous release})" >&2; exit 1; }','[ "$(readlink -f "$TS_CLOUD_RB_TARGET")" != "$TS_CLOUD_CURRENT" ] || { echo "$(basename "$TS_CLOUD_RB_TARGET") is already the live release" >&2; exit 1; }','TS_CLOUD_RB_ID=$(basename "$TS_CLOUD_RB_TARGET")']}function Tg(e,t={}){return[...$s(e,t.to),'echo "would roll back from $(basename "${TS_CLOUD_CURRENT:-none}") to $TS_CLOUD_RB_ID (dry run: nothing changed)"']}function wg(e,t={}){let r=Math.max(1,t.gateSeconds??5),n=t.systemdDir??"/etc/systemd/system",s=[`ln -sfn "$TS_CLOUD_RB_TARGET" ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`,`rm -f ${rn(e.base)}`,'echo "rolled back to $TS_CLOUD_RB_ID"'],i=[...$s(e,t.to),...$a(e,'"$TS_CLOUD_RB_TARGET"')];if(!t.unitBase)return[...i,...s];let a=t.unitBase,c=`${a}@\${TS_CLOUD_RB_ID}.service`;return[...i,`if [ -f ${n}/${a}@.service ]; then`,` systemctl start "${c}"`,` for TS_CLOUD_I in $(seq 1 ${r}); do sleep 1; systemctl is-active --quiet "${c}" || { echo "the release rolled back to, $TS_CLOUD_RB_ID, did not stay up; the current release keeps serving" >&2; journalctl -u "${c}" -n 30 --no-pager >&2 || true; systemctl stop "${c}" 2>/dev/null || true; exit 1; }; done`,...s.map((u)=>` ${u}`),` systemctl enable "${c}" 2>/dev/null || true`,` systemctl list-units --plain --no-legend --type=service "${a}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v "^${a}@\${TS_CLOUD_RB_ID}.service$" || true; } | while read -r TS_CLOUD_U; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done`,`elif [ -f ${n}/${a}.service ]; then`,...s.map((u)=>` ${u}`),` systemctl restart ${a}.service`,"else",...s.map((u)=>` ${u}`),"fi"]}function st(e,t=4){let r=Math.max(1,t);return[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,`ls -1dt ${e.releases}/*/ 2>/dev/null | sed 's#/$##' | tail -n +${r+1} | while read -r TS_CLOUD_OLD; do`,' [ "$(readlink -f "$TS_CLOUD_OLD")" = "$TS_CLOUD_CURRENT" ] || rm -rf "$TS_CLOUD_OLD"',"done"]}function Ta(e){return`${Te(e)}/owner`}function sn(e,t){let r=Ta(e);return[`if [ -f "${r}" ]; then`,` TS_CLOUD_OWNER=$(cat "${r}")`,` if [ "$TS_CLOUD_OWNER" != "${t}" ]; then`,` echo "[ts-cloud] REFUSING deploy: ${e} belongs to project '$TS_CLOUD_OWNER', not '${t}'. Another project on this box derives the same site key — give one of them a distinct site name/domain, or remove ${r} to transfer ownership." >&2`," exit 1"," fi","else",` mkdir -p "$(dirname "${r}")"`,` printf '%s\\n' "${t}" > "${r}"`,"fi"]}function Zt(e,t){let r=Te(e),n=Sa(e,t.releaseId),s=ha(e),i=Math.max(1,t.keepLogs??20),a=t.commit||"",c=t.branch||"";return[`mkdir -p ${r}/deploys`,`exec > >(tee -a ${n}) 2>&1`,`echo "[ts-cloud] deploy ${t.releaseId} commit=${a} branch=${c} starting $(date -u +%Y-%m-%dT%H:%M:%SZ)"`,"ts_cloud_record_deploy() {"," TS_CLOUD_RC=$?",' if [ "$TS_CLOUD_RC" -eq 0 ]; then TS_CLOUD_ST=success; else TS_CLOUD_ST=failed; fi',` printf '%s\\t%s\\t%s\\t%s\\trc=%s\\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "${t.releaseId}" "${a}" "$TS_CLOUD_ST" "$TS_CLOUD_RC" >> ${s}`,"}","trap ts_cloud_record_deploy EXIT",`ls -1t ${r}/deploys/*.log 2>/dev/null | tail -n +${i+1} | while read -r TS_CLOUD_OLDLOG; do rm -f "$TS_CLOUD_OLDLOG"; done`]}var ba=new Set(["sqlite","sqlite3"]),wa=new Set([":memory:","memory"]);function Ca(e){let t=e?.DB_CONNECTION?.trim().toLowerCase();return t!=null&&ba.has(t)}function Pa(e){let t=e.trim().replace(/^\.\//,"");if(t===""||t.startsWith("/")||t.startsWith("~"))return;if(t.split("/").includes(".."))return;return t.replace(/\/+$/,"")}function on(e,t=[]){if(!Ca(e))return{};let r=e?.DB_DATABASE_PATH?.trim()||e?.DB_DATABASE?.trim();if(r&&wa.has(r.toLowerCase()))return{};if(!r)return{warning:"DB_CONNECTION is sqlite but neither DB_DATABASE_PATH nor DB_DATABASE names a file, so ts-cloud cannot tell where the database lives. If it is written inside the release directory, the next deploy discards it. Set DB_DATABASE_PATH, or list the file in the site's `sharedPaths`."};let n=Pa(r);if(!n)return{};if(t.some((s)=>Jr(s)===n))return{};return{path:n}}function er(e,t=[]){let{path:r}=on(e,t);return r?[r]:[]}var Or="/var/ts-cloud/artifacts",vh="/usr/local/bin/ts-cloud-host-cleanup.sh",Th="ts-cloud-host-cleanup";var Rg=Object.freeze({stagingMaxAgeMinutes:60,artifactMaxAgeDays:2,artifactUploadMaxAgeMinutes:60,bunCacheMaxAgeDays:7,journalMaxAgeDays:14,journalMaxSizeMb:512,containerImageMaxAgeHours:168}),Dg=Object.freeze({artifactMaxAgeDays:0,bunCacheMaxAgeDays:1,journalMaxAgeDays:3,journalMaxSizeMb:256,containerImageMaxAgeHours:24}),wh=50,Rh=85,Dh="daily";function Ts(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function Me(e,t,r=0){if(!Number.isInteger(t)||t<r)throw Error(`hostCleanup: ${e} must be a whole number >= ${r} (got ${t})`)}function bs(e,t){for(let[r,n]of Object.entries(t))Me(`${e}.${r}`,n);Me(`${e}.stagingMaxAgeMinutes`,t.stagingMaxAgeMinutes,15),Me(`${e}.artifactUploadMaxAgeMinutes`,t.artifactUploadMaxAgeMinutes,15),Me(`${e}.journalMaxSizeMb`,t.journalMaxSizeMb,1)}function Ea(e,t){let r=`hostCleanup.paths[${t}]`,n=e.path?.replace(/\/+$/,"")??"";if(!n.startsWith("/")||n===""||/[\s'"`$\\]/.test(n)||n.split("/").includes(".."))throw Error(`${r}.path must be an absolute directory with no spaces, quotes or '..' (got ${JSON.stringify(e.path)})`);if(n==="/var/www"||n.startsWith("/var/www/"))throw Error(`${r}.path must not be under /var/www: releases are pruned by keepReleases`);if(!e.pattern||/^[*?]+$/.test(e.pattern)||e.pattern.includes("/")||/[\n'"`]/.test(e.pattern))throw Error(`${r}.pattern must be a file-name glob naming something, not a bare wildcard (got ${JSON.stringify(e.pattern)})`);if(Me(`${r}.maxAgeDays`,e.maxAgeDays),e.type!==void 0&&e.type!=="file"&&e.type!=="directory")throw Error(`${r}.type must be 'file' or 'directory'`)}function _r(e){let t=typeof e==="object"&&e!==null?e:{},r=e!==!1,n={...Rg,...ws(t.retention)};bs("hostCleanup.retention",n);let s=null;if(t.pressure!==!1){let c=typeof t.pressure==="object"?t.pressure:{},u=c.lowWaterPercent??50,m=c.highWaterPercent??85;if(Me("hostCleanup.pressure.lowWaterPercent",u),Me("hostCleanup.pressure.highWaterPercent",m,1),m>100||u>=m)throw Error(`hostCleanup.pressure: need 0 <= lowWaterPercent < highWaterPercent <= 100 (got ${u} and ${m})`);let f={...Dg,...ws(c.escalated)},v=Object.fromEntries(Object.keys(n).map((S)=>[S,Math.min(n[S],f[S]??n[S])]));bs("hostCleanup.pressure.escalated",v),s={lowWaterPercent:u,highWaterPercent:m,escalated:v}}let i=t.schedule??"daily";if(!/^[\w*:,./~ -]+$/.test(i))throw Error(`hostCleanup.schedule must be a systemd OnCalendar expression (got ${JSON.stringify(i)})`);let a=t.paths??[];return a.forEach(Ea),{enabled:r,timer:r&&t.timer!==!1,schedule:i,retention:n,pressure:s,paths:a}}function ws(e){return Object.fromEntries(Object.entries(e??{}).filter(([,t])=>t!==void 0))}var Ct={stagingMaxAgeMinutes:"TS_CLOUD_HC_STAGING_MIN",artifactMaxAgeDays:"TS_CLOUD_HC_ARTIFACT_DAYS",artifactUploadMaxAgeMinutes:"TS_CLOUD_HC_UPLOAD_MIN",bunCacheMaxAgeDays:"TS_CLOUD_HC_BUN_DAYS",journalMaxAgeDays:"TS_CLOUD_HC_JOURNAL_DAYS",journalMaxSizeMb:"TS_CLOUD_HC_JOURNAL_MB",containerImageMaxAgeHours:"TS_CLOUD_HC_IMAGE_HOURS"};function cn(e){return Object.keys(Ct).map((t)=>`${Ct[t]}=${e[t]}`).join(" ")}var He=(e)=>`"$${Ct[e]}"`;function Cs(e){return[`find /var/ts-cloud/staging -xdev -maxdepth 1 -type f -mmin +${He("stagingMaxAgeMinutes")} -delete 2>/dev/null || true`,`find /tmp -xdev -maxdepth 1 -type f -name "*-release.tar.gz" -mmin +${He("stagingMaxAgeMinutes")} -delete 2>/dev/null || true`,`find /var/ts-cloud/artifacts -xdev -maxdepth 1 -type f -name "*.tar.gz" -mtime +${He("artifactMaxAgeDays")} -delete 2>/dev/null || true`,`find /var/ts-cloud/artifacts -xdev -maxdepth 1 -type f -name ".*.tmp" -mmin +${He("artifactUploadMaxAgeMinutes")} -delete 2>/dev/null || true`,...e.map(Oa),`journalctl --vacuum-time=${He("journalMaxAgeDays")}d --vacuum-size=${He("journalMaxSizeMb")}M >/dev/null 2>&1 || true`]}function Oa(e){let t=Ts(e.path.replace(/\/+$/,"")),r=Ts(e.pattern);return e.type==="directory"?`find ${t} -xdev -mindepth 1 -maxdepth 1 -type d -name ${r} -mtime +${e.maxAgeDays} -exec rm -rf -- {} + 2>/dev/null || true`:`find ${t} -xdev -mindepth 1 -maxdepth 1 -type f -name ${r} -mtime +${e.maxAgeDays} -delete 2>/dev/null || true`}function Ps(){return[`find /root/.bun/install/cache -xdev -type f -mtime +${He("bunCacheMaxAgeDays")} -delete 2>/dev/null || true`,"find /root/.bun/install/cache -xdev -depth -type d -empty -delete 2>/dev/null || true",`if command -v docker >/dev/null 2>&1; then docker image prune --all --force --filter "until=\${${Ct.containerImageMaxAgeHours}}h" >/dev/null 2>&1 || true; fi`,`if command -v podman >/dev/null 2>&1; then podman image prune --all --force --filter "until=\${${Ct.containerImageMaxAgeHours}}h" >/dev/null 2>&1 || true; fi`,"if command -v apt-get >/dev/null 2>&1; then apt-get clean >/dev/null 2>&1 || true; fi"]}function Es(e){return[`${e}="$(df -P / 2>/dev/null | awk 'NR==2 {sub(/%/, "", $5); print $5}' || true)"`,`case "$${e}" in ''|*[!0-9]*) ${e}=-1 ;; esac`]}function ei(e){let{retention:t,pressure:r,paths:n}=_r(e),s='echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',i='echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"';if(!r)return['echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',cn(t),...Cs(n),...Ps(),'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"'];let{lowWaterPercent:a,highWaterPercent:c,escalated:u}=r;return['echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',...Es("TS_CLOUD_HC_BEFORE"),"TS_CLOUD_HC_TIER=normal",cn(t),`if [ "$TS_CLOUD_HC_BEFORE" -ge 0 ] && [ "$TS_CLOUD_HC_BEFORE" -lt ${a} ]; then`," TS_CLOUD_HC_TIER=light",` echo "[ts-cloud] host cleanup: / at \${TS_CLOUD_HC_BEFORE}% (under ${a}%), skipping cache and image pruning"`,`elif [ "$TS_CLOUD_HC_BEFORE" -ge ${c} ]; then`," TS_CLOUD_HC_TIER=pressure",` ${cn(u)}`,` echo "[ts-cloud] warning: / at \${TS_CLOUD_HC_BEFORE}% (at or above ${c}%), host cleanup is using shortened retention windows" >&2`,"fi",...Cs(n),'if [ "$TS_CLOUD_HC_TIER" != light ]; then',...Ps().map((m)=>` ${m}`),"fi",'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"',...Es("TS_CLOUD_HC_AFTER"),`echo "[ts-cloud] host-cleanup {\\"event\\":\\"host-cleanup\\",\\"tier\\":\\"$TS_CLOUD_HC_TIER\\",\\"diskBeforePercent\\":$TS_CLOUD_HC_BEFORE,\\"diskAfterPercent\\":$TS_CLOUD_HC_AFTER,\\"lowWaterPercent\\":${a},\\"highWaterPercent\\":${c}}"`,"mkdir -p /var/lib/ts-cloud 2>/dev/null || true",'TS_CLOUD_HC_PREV="$(cat /var/lib/ts-cloud/host-cleanup.alert 2>/dev/null || echo ok)"',`if [ "$TS_CLOUD_HC_AFTER" -ge ${c} ]; then`,` echo "[ts-cloud] warning: / still at \${TS_CLOUD_HC_AFTER}% after host cleanup (high-water ${c}%); something outside ts-cloud's retention rules is filling the disk" >&2`,` if [ "$TS_CLOUD_HC_PREV" != alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "⚠️ $(hostname): / at \${TS_CLOUD_HC_AFTER}% after host cleanup (high-water ${c}%)" >/dev/null 2>&1 || true; fi`," echo alert > /var/lib/ts-cloud/host-cleanup.alert 2>/dev/null || true","else",` if [ "$TS_CLOUD_HC_PREV" = alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "✅ $(hostname): / back under ${c}% after host cleanup (\${TS_CLOUD_HC_AFTER}%)" >/dev/null 2>&1 || true; fi`," echo ok > /var/lib/ts-cloud/host-cleanup.alert 2>/dev/null || true","fi"]}function Pg(e){return["#!/usr/bin/env bash","# Managed by ts-cloud: rewritten on every deploy. Configure compute.hostCleanup instead of editing.","set -uo pipefail","TS_CLOUD_HC_LOCK=/run/lock/ts-cloud-host-cleanup.lock","[ -d /run/lock ] || TS_CLOUD_HC_LOCK=/tmp/ts-cloud-host-cleanup.lock",'if command -v flock >/dev/null 2>&1 && exec 9>"$TS_CLOUD_HC_LOCK"; then',' if ! flock -n 9; then echo "[ts-cloud] host cleanup already running; skipping"; exit 0; fi',"fi",...ei(e),"exit 0"]}function ln(e,t,r,n,s){return[`cat > ${e}.ts-cloud-new <<'${r}' || true`,...t,r,`if [ -s ${e}.ts-cloud-new ] && ! cmp -s ${e}.ts-cloud-new ${e}; then chmod ${n} ${e}.ts-cloud-new && mv -f ${e}.ts-cloud-new ${e}${s?` && ${s}=1`:""} || true; else rm -f ${e}.ts-cloud-new; fi`]}function zs(e){let t=_r(e),r="/etc/systemd/system/ts-cloud-host-cleanup",n=["if [ -f /etc/systemd/system/ts-cloud-host-cleanup.timer ]; then"," systemctl disable --now ts-cloud-host-cleanup.timer >/dev/null 2>&1 || true"," rm -f /etc/systemd/system/ts-cloud-host-cleanup.timer /etc/systemd/system/ts-cloud-host-cleanup.service"," systemctl daemon-reload >/dev/null 2>&1 || true","fi"];if(!t.enabled)return[...n,"rm -f /usr/local/bin/ts-cloud-host-cleanup.sh"];let s=ln("/usr/local/bin/ts-cloud-host-cleanup.sh",Pg(e),"TS_CLOUD_HOST_CLEANUP_EOF","755");if(!t.timer)return[...s,...n];return[...s,"TS_CLOUD_HC_UNITS_CHANGED=0","if command -v systemctl >/dev/null 2>&1 && [ -d /etc/systemd/system ]; then",...ln("/etc/systemd/system/ts-cloud-host-cleanup.service",["[Unit]","Description=ts-cloud host cleanup (bounded disk retention)","After=local-fs.target","","[Service]","Type=oneshot","ExecStart=/usr/local/bin/ts-cloud-host-cleanup.sh","Nice=19","IOSchedulingClass=idle"],"TS_CLOUD_HOST_CLEANUP_SVC_EOF","644","TS_CLOUD_HC_UNITS_CHANGED"),...ln("/etc/systemd/system/ts-cloud-host-cleanup.timer",["[Unit]","Description=Run ts-cloud host cleanup on a schedule, independent of deploys","","[Timer]",`OnCalendar=${t.schedule}`,"RandomizedDelaySec=1h","Persistent=true","","[Install]","WantedBy=timers.target"],"TS_CLOUD_HOST_CLEANUP_TMR_EOF","644","TS_CLOUD_HC_UNITS_CHANGED"),' if [ "$TS_CLOUD_HC_UNITS_CHANGED" -eq 1 ]; then systemctl daemon-reload >/dev/null 2>&1 || true; fi'," systemctl enable --now ts-cloud-host-cleanup.timer >/dev/null 2>&1 || true","fi"]}function ti(e){let t=zs(e);if(!_r(e).enabled)return t;return[...t,'if [ -x /usr/local/bin/ts-cloud-host-cleanup.sh ]; then /usr/local/bin/ts-cloud-host-cleanup.sh < /dev/null || echo "[ts-cloud] warning: host cleanup exited $?" >&2; fi']}var Ra=/\.(?:[cm]?[jt]sx?)$/;function ri(e,t,r){let n=t==="bun"?"/usr/local/bin/bun":t==="deno"?"/usr/local/bin/deno":"/usr/local/bin/node",s=e.trim();if(/^(?:bun|node|deno)\s+/.test(s))return`${n} ${s.replace(/^(?:bun|node|deno)\s+/,"")}`;let[i="",...a]=s.split(/\s+/);if(i&&!Ra.test(i)){let c=i.startsWith("/")?i:r&&i.startsWith("./")?`${r.replace(/\/+$/,"")}/${i.replace(/^\.\//,"")}`:void 0;if(c)return[c,...a].join(" ")}return`${n} ${s}`}function Os(e){return["TS_CLOUD_MEM_MB=$(awk '/^MemTotal:/{print int($2/1024)}' /proc/meminfo)","TS_CLOUD_HIGH_MB=$((TS_CLOUD_MEM_MB / 8))",'[ "$TS_CLOUD_HIGH_MB" -lt 512 ] && TS_CLOUD_HIGH_MB=512','[ "$TS_CLOUD_HIGH_MB" -gt 4096 ] && TS_CLOUD_HIGH_MB=4096',`mkdir -p /etc/systemd/system/${e}.d`,`printf '# Written by ts-cloud: memoryHigh resolved from this box.
140
+ `)}function ga(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}var qt=["storage",".env"],$t=4;function Te(e){return`${e.replace(/\/+$/,"")}/.ts-cloud`}function ha(e){return`${Te(e)}/deploy-history.log`}function Sa(e,t){return`${Te(e)}/deploys/${t}.log`}function Ss(e){return`${Te(e)}/shared-paths`}function Yt(e){return`${e.shared}/stx-images`}function Wt(e,t){let r=e.replace(/\/+$/,"");return{base:r,releases:`${r}/releases`,shared:`${r}/shared`,current:`${r}/current`,release:`${r}/releases/${t}`}}function _s(e){let t=e.split("/").pop()||e;if(t===".env"||t.startsWith(".env."))return!0;return/\.[a-z0-9]+$/i.test(t)}function Jr(e){return typeof e==="string"?e:e.path}function vs(e){let t=new Map;for(let r of e)t.set(Jr(r),r);return[...t.values()]}function ys(e,t){if(typeof t==="string")return{path:t,target:`${e.shared}/${t}`,seed:!0};return{path:t.path,target:t.target??`${e.shared}/${t.path}`,seed:t.seed!==!1}}function _a(e){return["ts_cloud_adopt_shared() {",' TS_CLOUD_SP="$1"',' TS_CLOUD_DST="$2"',` TS_CLOUD_SRC="${e.current}/$TS_CLOUD_SP"`,' if [ -e "$TS_CLOUD_DST" ]; then return 0; fi',' if [ -L "$TS_CLOUD_SRC" ] || [ ! -e "$TS_CLOUD_SRC" ]; then return 0; fi',' mkdir -p "$(dirname "$TS_CLOUD_DST")"',' cp -a "$TS_CLOUD_SRC" "$TS_CLOUD_DST"'," for TS_CLOUD_SIDECAR in -wal -shm; do",' if [ -f "$TS_CLOUD_SRC$TS_CLOUD_SIDECAR" ]; then cp -a "$TS_CLOUD_SRC$TS_CLOUD_SIDECAR" "$TS_CLOUD_DST$TS_CLOUD_SIDECAR"; fi'," done",' echo "[ts-cloud] adopted $TS_CLOUD_SP from the live release into shared/ — it now survives deploys"'," return 0","}"]}function bt(e,t=qt){let r=[`mkdir -p ${e.releases} ${e.shared} ${Yt(e)}`,..._a(e)],n=t.map((i)=>ys(e,i));for(let{path:i,target:a,seed:c}of n){if(!c)continue;if(r.push(`ts_cloud_adopt_shared '${i}' '${a}'`),_s(i))r.push(`mkdir -p "$(dirname ${a})"`,`touch ${a}`);else if(i==="storage")r.push(`mkdir -p ${a}/app/public`,`mkdir -p ${a}/framework/cache/data`,`mkdir -p ${a}/framework/sessions`,`mkdir -p ${a}/framework/testing`,`mkdir -p ${a}/framework/views`,`mkdir -p ${a}/logs`);else r.push(`mkdir -p ${a}`)}let s=Ss(e.base);return r.push(`mkdir -p ${Te(e.base)}`,`cat > ${s} <<'TS_CLOUD_SHARED_PATHS_EOF'`,...n.map((i)=>`${i.path} ${i.target}`),"TS_CLOUD_SHARED_PATHS_EOF"),r}function Qr(e,t=900){let r=`${Te(e.base)}/deploy.lock`;return[`mkdir -p "$(dirname ${r})"`,`exec 9>${r}`,`flock -w ${t} 9 || { echo "[ts-cloud] another deploy of this site has held the lock for ${t}s — refusing to race it" >&2; exit 1; }`]}function Zr(e){let t=`${e.release}.incoming`;return[`rm -rf ${t}`,`mkdir -p ${t}`,...va(e),'if [ "$TS_CLOUD_IS_LIVE" = "yes" ]; then',` TS_CLOUD_STAGED=${t}`,"else",` rm -rf ${e.release}`,` mkdir -p ${e.release}`,` rmdir ${t}`,` TS_CLOUD_STAGED=${e.release}`,"fi"]}function en(e){let t=`TS_CLOUD_TRAP_LIVE="$(readlink -f ${e.current} 2>/dev/null || true)"`,r=`TS_CLOUD_TRAP_TARGET="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`;return`trap '${`if [ $? -ne 0 ]; then ${t}; ${r}; [ "$TS_CLOUD_TRAP_LIVE" = "$TS_CLOUD_TRAP_TARGET" ] || rm -rf ${e.release}; fi`}' EXIT`}function va(e){return[`TS_CLOUD_LIVE_PATH="$(readlink -f ${e.current} 2>/dev/null || true)"`,`TS_CLOUD_RELEASE_PATH="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`,'if [ -n "$TS_CLOUD_LIVE_PATH" ] && [ "$TS_CLOUD_LIVE_PATH" = "$TS_CLOUD_RELEASE_PATH" ]; then TS_CLOUD_IS_LIVE=yes; else TS_CLOUD_IS_LIVE=no; fi']}function tn(e){let t=`${e.release}.incoming`;return[`if [ "$TS_CLOUD_STAGED" = "${t}" ]; then`,` rm -rf ${e.release}.previous`,` mv ${e.release} ${e.release}.previous`,` mv ${t} ${e.release}`,` rm -rf ${e.release}.previous`,"fi"]}function ya(e,t){return[`if [ -f ${e} ] && [ ! -L ${e} ] && [ -s ${e} ] && [ ! -s ${t} ]; then`,` cp -a ${e} ${t}`,` echo "[ts-cloud] seeded shared/ from the release's own copy of the file"`,"fi"]}function Qt(e,t=qt){let r=[];for(let n of t){let{path:s,target:i,seed:a}=ys(e,n),c=`${e.release}/${s}`,u=[`rm -rf ${c}`,`mkdir -p "$(dirname ${c})"`,`ln -sfn ${i} ${c}`];if(a){if(s!==".env"&&_s(s))r.push(...ya(c,i));r.push(...u);continue}r.push(`if [ -e ${i} ]; then`,...u.map((m)=>` ${m}`),"fi")}return r}function $a(e,t){let r=Ss(e.base);return[`if [ -f ${r} ]; then`,' while IFS="\t" read -r TS_CLOUD_SP TS_CLOUD_TGT; do',' [ -n "$TS_CLOUD_SP" ] || continue',` [ -n "$TS_CLOUD_TGT" ] || TS_CLOUD_TGT="${e.shared}/$TS_CLOUD_SP"`,' [ -e "$TS_CLOUD_TGT" ] || continue',` rm -rf ${t}/"$TS_CLOUD_SP"`,` mkdir -p "$(dirname ${t}/"$TS_CLOUD_SP")"`,` ln -sfn "$TS_CLOUD_TGT" ${t}/"$TS_CLOUD_SP"`,` done < ${r}`,"fi"]}function nt(e){return[`ln -sfn ${e.release} ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`]}function rn(e){return`${Te(e)}/previous-release`}function nn(e,t="TS_CLOUD_PREV_CURRENT"){let r=rn(e.base);return[`if [ -n "\${${t}:-}" ] && [ -d "$${t}" ] && [ "$(readlink -f "$${t}")" != "$(readlink -f ${e.release})" ]; then mkdir -p ${Te(e.base)}; basename "$${t}" > ${r}; fi`]}function $s(e,t){let r=rn(e.base);return[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,...t?[`TS_CLOUD_RB_TARGET=${e.releases}/${t}`]:["TS_CLOUD_RB_TARGET=",`if [ -f ${r} ]; then TS_CLOUD_REC="${e.releases}/$(cat ${r})"; if [ -d "$TS_CLOUD_REC" ] && [ "$(readlink -f "$TS_CLOUD_REC")" != "$TS_CLOUD_CURRENT" ]; then TS_CLOUD_RB_TARGET="$TS_CLOUD_REC"; fi; fi`,`[ -n "$TS_CLOUD_RB_TARGET" ] || TS_CLOUD_RB_TARGET=$(ls -1dt ${e.releases}/*/ 2>/dev/null | sed 's#/$##' | while read -r r; do [ "$(readlink -f "$r")" != "$TS_CLOUD_CURRENT" ] && { echo "$r"; break; }; done)`],'[ -n "$TS_CLOUD_RB_TARGET" ] && [ -d "$TS_CLOUD_RB_TARGET" ] || { echo "no release to roll back to (looked for ${TS_CLOUD_RB_TARGET:-a previous release})" >&2; exit 1; }','[ "$(readlink -f "$TS_CLOUD_RB_TARGET")" != "$TS_CLOUD_CURRENT" ] || { echo "$(basename "$TS_CLOUD_RB_TARGET") is already the live release" >&2; exit 1; }','TS_CLOUD_RB_ID=$(basename "$TS_CLOUD_RB_TARGET")']}function Tg(e,t={}){return[...$s(e,t.to),'echo "would roll back from $(basename "${TS_CLOUD_CURRENT:-none}") to $TS_CLOUD_RB_ID (dry run: nothing changed)"']}function wg(e,t={}){let r=Math.max(1,t.gateSeconds??5),n=t.systemdDir??"/etc/systemd/system",s=[`ln -sfn "$TS_CLOUD_RB_TARGET" ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`,`rm -f ${rn(e.base)}`,'echo "rolled back to $TS_CLOUD_RB_ID"'],i=[...$s(e,t.to),...$a(e,'"$TS_CLOUD_RB_TARGET"')];if(!t.unitBase)return[...i,...s];let a=t.unitBase,c=`${a}@\${TS_CLOUD_RB_ID}.service`;return[...i,`if [ -f ${n}/${a}@.service ]; then`,` systemctl start "${c}"`,` for TS_CLOUD_I in $(seq 1 ${r}); do sleep 1; systemctl is-active --quiet "${c}" || { echo "the release rolled back to, $TS_CLOUD_RB_ID, did not stay up; the current release keeps serving" >&2; journalctl -u "${c}" -n 30 --no-pager >&2 || true; systemctl stop "${c}" 2>/dev/null || true; exit 1; }; done`,...s.map((u)=>` ${u}`),` systemctl enable "${c}" 2>/dev/null || true`,` systemctl list-units --plain --no-legend --type=service "${a}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v "^${a}@\${TS_CLOUD_RB_ID}.service$" || true; } | while read -r TS_CLOUD_U; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done`,`elif [ -f ${n}/${a}.service ]; then`,...s.map((u)=>` ${u}`),` systemctl restart ${a}.service`,"else",...s.map((u)=>` ${u}`),"fi"]}function st(e,t=4){let r=Math.max(1,t);return[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,`ls -1dt ${e.releases}/*/ 2>/dev/null | sed 's#/$##' | tail -n +${r+1} | while read -r TS_CLOUD_OLD; do`,' [ "$(readlink -f "$TS_CLOUD_OLD")" = "$TS_CLOUD_CURRENT" ] || rm -rf "$TS_CLOUD_OLD"',"done"]}function Ta(e){return`${Te(e)}/owner`}function sn(e,t){let r=Ta(e);return[`if [ -f "${r}" ]; then`,` TS_CLOUD_OWNER=$(cat "${r}")`,` if [ "$TS_CLOUD_OWNER" != "${t}" ]; then`,` echo "[ts-cloud] REFUSING deploy: ${e} belongs to project '$TS_CLOUD_OWNER', not '${t}'. Another project on this box derives the same site key — give one of them a distinct site name/domain, or remove ${r} to transfer ownership." >&2`," exit 1"," fi","else",` mkdir -p "$(dirname "${r}")"`,` printf '%s\\n' "${t}" > "${r}"`,"fi"]}function Zt(e,t){let r=Te(e),n=Sa(e,t.releaseId),s=ha(e),i=Math.max(1,t.keepLogs??20),a=t.commit||"",c=t.branch||"";return[`mkdir -p ${r}/deploys`,`exec > >(tee -a ${n}) 2>&1`,`echo "[ts-cloud] deploy ${t.releaseId} commit=${a} branch=${c} starting $(date -u +%Y-%m-%dT%H:%M:%SZ)"`,"ts_cloud_record_deploy() {"," TS_CLOUD_RC=$?",' if [ "$TS_CLOUD_RC" -eq 0 ]; then TS_CLOUD_ST=success; else TS_CLOUD_ST=failed; fi',` printf '%s\\t%s\\t%s\\t%s\\trc=%s\\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "${t.releaseId}" "${a}" "$TS_CLOUD_ST" "$TS_CLOUD_RC" >> ${s}`,"}","trap ts_cloud_record_deploy EXIT",`ls -1t ${r}/deploys/*.log 2>/dev/null | tail -n +${i+1} | while read -r TS_CLOUD_OLDLOG; do rm -f "$TS_CLOUD_OLDLOG"; done`]}var ba=new Set(["sqlite","sqlite3"]),wa=new Set([":memory:","memory"]);function Ca(e){let t=e?.DB_CONNECTION?.trim().toLowerCase();return t!=null&&ba.has(t)}function Pa(e){let t=e.trim().replace(/^\.\//,"");if(t===""||t.startsWith("/")||t.startsWith("~"))return;if(t.split("/").includes(".."))return;return t.replace(/\/+$/,"")}function on(e,t=[]){if(!Ca(e))return{};let r=e?.DB_DATABASE_PATH?.trim()||e?.DB_DATABASE?.trim();if(r&&wa.has(r.toLowerCase()))return{};if(!r)return{warning:"DB_CONNECTION is sqlite but neither DB_DATABASE_PATH nor DB_DATABASE names a file, so ts-cloud cannot tell where the database lives. If it is written inside the release directory, the next deploy discards it. Set DB_DATABASE_PATH, or list the file in the site's `sharedPaths`."};let n=Pa(r);if(!n)return{};if(t.some((s)=>Jr(s)===n))return{};return{path:n}}function er(e,t=[]){let{path:r}=on(e,t);return r?[r]:[]}var Or="/var/ts-cloud/artifacts",vh="/usr/local/bin/ts-cloud-host-cleanup.sh",Th="ts-cloud-host-cleanup";var Rg=Object.freeze({stagingMaxAgeMinutes:60,artifactMaxAgeDays:2,artifactUploadMaxAgeMinutes:60,bunCacheMaxAgeDays:7,journalMaxAgeDays:14,journalMaxSizeMb:512,containerImageMaxAgeHours:168}),Dg=Object.freeze({artifactMaxAgeDays:0,bunCacheMaxAgeDays:1,journalMaxAgeDays:3,journalMaxSizeMb:256,containerImageMaxAgeHours:24}),wh=50,Rh=85,Dh="daily";function Ts(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function Me(e,t,r=0){if(!Number.isInteger(t)||t<r)throw Error(`hostCleanup: ${e} must be a whole number >= ${r} (got ${t})`)}function bs(e,t){for(let[r,n]of Object.entries(t))Me(`${e}.${r}`,n);Me(`${e}.stagingMaxAgeMinutes`,t.stagingMaxAgeMinutes,15),Me(`${e}.artifactUploadMaxAgeMinutes`,t.artifactUploadMaxAgeMinutes,15),Me(`${e}.journalMaxSizeMb`,t.journalMaxSizeMb,1)}function Ea(e,t){let r=`hostCleanup.paths[${t}]`,n=e.path?.replace(/\/+$/,"")??"";if(!n.startsWith("/")||n===""||/[\s'"`$\\]/.test(n)||n.split("/").includes(".."))throw Error(`${r}.path must be an absolute directory with no spaces, quotes or '..' (got ${JSON.stringify(e.path)})`);if(n==="/var/www"||n.startsWith("/var/www/"))throw Error(`${r}.path must not be under /var/www: releases are pruned by keepReleases`);if(!e.pattern||/^[*?]+$/.test(e.pattern)||e.pattern.includes("/")||/[\n'"`]/.test(e.pattern))throw Error(`${r}.pattern must be a file-name glob naming something, not a bare wildcard (got ${JSON.stringify(e.pattern)})`);if(Me(`${r}.maxAgeDays`,e.maxAgeDays),e.type!==void 0&&e.type!=="file"&&e.type!=="directory")throw Error(`${r}.type must be 'file' or 'directory'`)}function _r(e){let t=typeof e==="object"&&e!==null?e:{},r=e!==!1,n={...Rg,...ws(t.retention)};bs("hostCleanup.retention",n);let s=null;if(t.pressure!==!1){let c=typeof t.pressure==="object"?t.pressure:{},u=c.lowWaterPercent??50,m=c.highWaterPercent??85;if(Me("hostCleanup.pressure.lowWaterPercent",u),Me("hostCleanup.pressure.highWaterPercent",m,1),m>100||u>=m)throw Error(`hostCleanup.pressure: need 0 <= lowWaterPercent < highWaterPercent <= 100 (got ${u} and ${m})`);let f={...Dg,...ws(c.escalated)},v=Object.fromEntries(Object.keys(n).map((S)=>[S,Math.min(n[S],f[S]??n[S])]));bs("hostCleanup.pressure.escalated",v),s={lowWaterPercent:u,highWaterPercent:m,escalated:v}}let i=t.schedule??"daily";if(!/^[\w*:,./~ -]+$/.test(i))throw Error(`hostCleanup.schedule must be a systemd OnCalendar expression (got ${JSON.stringify(i)})`);let a=t.paths??[];return a.forEach(Ea),{enabled:r,timer:r&&t.timer!==!1,schedule:i,retention:n,pressure:s,paths:a}}function ws(e){return Object.fromEntries(Object.entries(e??{}).filter(([,t])=>t!==void 0))}var Ct={stagingMaxAgeMinutes:"TS_CLOUD_HC_STAGING_MIN",artifactMaxAgeDays:"TS_CLOUD_HC_ARTIFACT_DAYS",artifactUploadMaxAgeMinutes:"TS_CLOUD_HC_UPLOAD_MIN",bunCacheMaxAgeDays:"TS_CLOUD_HC_BUN_DAYS",journalMaxAgeDays:"TS_CLOUD_HC_JOURNAL_DAYS",journalMaxSizeMb:"TS_CLOUD_HC_JOURNAL_MB",containerImageMaxAgeHours:"TS_CLOUD_HC_IMAGE_HOURS"};function cn(e){return Object.keys(Ct).map((t)=>`${Ct[t]}=${e[t]}`).join(" ")}var Ie=(e)=>`"$${Ct[e]}"`;function Cs(e){return[`find /var/ts-cloud/staging -xdev -maxdepth 1 -type f -mmin +${Ie("stagingMaxAgeMinutes")} -delete 2>/dev/null || true`,`find /tmp -xdev -maxdepth 1 -type f -name "*-release.tar.gz" -mmin +${Ie("stagingMaxAgeMinutes")} -delete 2>/dev/null || true`,`find /var/ts-cloud/artifacts -xdev -maxdepth 1 -type f -name "*.tar.gz" -mtime +${Ie("artifactMaxAgeDays")} -delete 2>/dev/null || true`,`find /var/ts-cloud/artifacts -xdev -maxdepth 1 -type f -name ".*.tmp" -mmin +${Ie("artifactUploadMaxAgeMinutes")} -delete 2>/dev/null || true`,...e.map(Oa),`journalctl --vacuum-time=${Ie("journalMaxAgeDays")}d --vacuum-size=${Ie("journalMaxSizeMb")}M >/dev/null 2>&1 || true`]}function Oa(e){let t=Ts(e.path.replace(/\/+$/,"")),r=Ts(e.pattern);return e.type==="directory"?`find ${t} -xdev -mindepth 1 -maxdepth 1 -type d -name ${r} -mtime +${e.maxAgeDays} -exec rm -rf -- {} + 2>/dev/null || true`:`find ${t} -xdev -mindepth 1 -maxdepth 1 -type f -name ${r} -mtime +${e.maxAgeDays} -delete 2>/dev/null || true`}function Ps(){return[`find /root/.bun/install/cache -xdev -type f -mtime +${Ie("bunCacheMaxAgeDays")} -delete 2>/dev/null || true`,`find /root/.bun/install/cache -xdev -depth -type d -empty -mtime +${Ie("bunCacheMaxAgeDays")} -delete 2>/dev/null || true`,`if command -v docker >/dev/null 2>&1; then docker image prune --all --force --filter "until=\${${Ct.containerImageMaxAgeHours}}h" >/dev/null 2>&1 || true; fi`,`if command -v podman >/dev/null 2>&1; then podman image prune --all --force --filter "until=\${${Ct.containerImageMaxAgeHours}}h" >/dev/null 2>&1 || true; fi`,"if command -v apt-get >/dev/null 2>&1; then apt-get clean >/dev/null 2>&1 || true; fi"]}function Es(e){return[`${e}="$(df -P / 2>/dev/null | awk 'NR==2 {sub(/%/, "", $5); print $5}' || true)"`,`case "$${e}" in ''|*[!0-9]*) ${e}=-1 ;; esac`]}function ei(e){let{retention:t,pressure:r,paths:n}=_r(e),s='echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',i='echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"';if(!r)return['echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',cn(t),...Cs(n),...Ps(),'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"'];let{lowWaterPercent:a,highWaterPercent:c,escalated:u}=r;return['echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',...Es("TS_CLOUD_HC_BEFORE"),"TS_CLOUD_HC_TIER=normal",cn(t),`if [ "$TS_CLOUD_HC_BEFORE" -ge 0 ] && [ "$TS_CLOUD_HC_BEFORE" -lt ${a} ]; then`," TS_CLOUD_HC_TIER=light",` echo "[ts-cloud] host cleanup: / at \${TS_CLOUD_HC_BEFORE}% (under ${a}%), skipping cache and image pruning"`,`elif [ "$TS_CLOUD_HC_BEFORE" -ge ${c} ]; then`," TS_CLOUD_HC_TIER=pressure",` ${cn(u)}`,` echo "[ts-cloud] warning: / at \${TS_CLOUD_HC_BEFORE}% (at or above ${c}%), host cleanup is using shortened retention windows" >&2`,"fi",...Cs(n),'if [ "$TS_CLOUD_HC_TIER" != light ]; then',...Ps().map((m)=>` ${m}`),"fi",'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"',...Es("TS_CLOUD_HC_AFTER"),`echo "[ts-cloud] host-cleanup {\\"event\\":\\"host-cleanup\\",\\"tier\\":\\"$TS_CLOUD_HC_TIER\\",\\"diskBeforePercent\\":$TS_CLOUD_HC_BEFORE,\\"diskAfterPercent\\":$TS_CLOUD_HC_AFTER,\\"lowWaterPercent\\":${a},\\"highWaterPercent\\":${c}}"`,"mkdir -p /var/lib/ts-cloud 2>/dev/null || true",'TS_CLOUD_HC_PREV="$(cat /var/lib/ts-cloud/host-cleanup.alert 2>/dev/null || echo ok)"',`if [ "$TS_CLOUD_HC_AFTER" -ge ${c} ]; then`,` echo "[ts-cloud] warning: / still at \${TS_CLOUD_HC_AFTER}% after host cleanup (high-water ${c}%); something outside ts-cloud's retention rules is filling the disk" >&2`,` if [ "$TS_CLOUD_HC_PREV" != alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "⚠️ $(hostname): / at \${TS_CLOUD_HC_AFTER}% after host cleanup (high-water ${c}%)" >/dev/null 2>&1 || true; fi`," echo alert > /var/lib/ts-cloud/host-cleanup.alert 2>/dev/null || true","else",` if [ "$TS_CLOUD_HC_PREV" = alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "✅ $(hostname): / back under ${c}% after host cleanup (\${TS_CLOUD_HC_AFTER}%)" >/dev/null 2>&1 || true; fi`," echo ok > /var/lib/ts-cloud/host-cleanup.alert 2>/dev/null || true","fi"]}function Pg(e){return["#!/usr/bin/env bash","# Managed by ts-cloud: rewritten on every deploy. Configure compute.hostCleanup instead of editing.","set -uo pipefail","TS_CLOUD_HC_LOCK=/run/lock/ts-cloud-host-cleanup.lock","[ -d /run/lock ] || TS_CLOUD_HC_LOCK=/tmp/ts-cloud-host-cleanup.lock",'if command -v flock >/dev/null 2>&1 && exec 9>"$TS_CLOUD_HC_LOCK"; then',' if ! flock -n 9; then echo "[ts-cloud] host cleanup already running; skipping"; exit 0; fi',"fi",...ei(e),"exit 0"]}function ln(e,t,r,n,s){return[`cat > ${e}.ts-cloud-new <<'${r}' || true`,...t,r,`if [ -s ${e}.ts-cloud-new ] && ! cmp -s ${e}.ts-cloud-new ${e}; then chmod ${n} ${e}.ts-cloud-new && mv -f ${e}.ts-cloud-new ${e}${s?` && ${s}=1`:""} || true; else rm -f ${e}.ts-cloud-new; fi`]}function zs(e){let t=_r(e),r="/etc/systemd/system/ts-cloud-host-cleanup",n=["if [ -f /etc/systemd/system/ts-cloud-host-cleanup.timer ]; then"," systemctl disable --now ts-cloud-host-cleanup.timer >/dev/null 2>&1 || true"," rm -f /etc/systemd/system/ts-cloud-host-cleanup.timer /etc/systemd/system/ts-cloud-host-cleanup.service"," systemctl daemon-reload >/dev/null 2>&1 || true","fi"];if(!t.enabled)return[...n,"rm -f /usr/local/bin/ts-cloud-host-cleanup.sh"];let s=ln("/usr/local/bin/ts-cloud-host-cleanup.sh",Pg(e),"TS_CLOUD_HOST_CLEANUP_EOF","755");if(!t.timer)return[...s,...n];return[...s,"TS_CLOUD_HC_UNITS_CHANGED=0","if command -v systemctl >/dev/null 2>&1 && [ -d /etc/systemd/system ]; then",...ln("/etc/systemd/system/ts-cloud-host-cleanup.service",["[Unit]","Description=ts-cloud host cleanup (bounded disk retention)","After=local-fs.target","","[Service]","Type=oneshot","ExecStart=/usr/local/bin/ts-cloud-host-cleanup.sh","Nice=19","IOSchedulingClass=idle"],"TS_CLOUD_HOST_CLEANUP_SVC_EOF","644","TS_CLOUD_HC_UNITS_CHANGED"),...ln("/etc/systemd/system/ts-cloud-host-cleanup.timer",["[Unit]","Description=Run ts-cloud host cleanup on a schedule, independent of deploys","","[Timer]",`OnCalendar=${t.schedule}`,"RandomizedDelaySec=1h","Persistent=true","","[Install]","WantedBy=timers.target"],"TS_CLOUD_HOST_CLEANUP_TMR_EOF","644","TS_CLOUD_HC_UNITS_CHANGED"),' if [ "$TS_CLOUD_HC_UNITS_CHANGED" -eq 1 ]; then systemctl daemon-reload >/dev/null 2>&1 || true; fi'," systemctl enable --now ts-cloud-host-cleanup.timer >/dev/null 2>&1 || true","fi"]}function ti(e){let t=zs(e);if(!_r(e).enabled)return t;return[...t,'if [ -x /usr/local/bin/ts-cloud-host-cleanup.sh ]; then /usr/local/bin/ts-cloud-host-cleanup.sh < /dev/null || echo "[ts-cloud] warning: host cleanup exited $?" >&2; fi']}var Ra=/\.(?:[cm]?[jt]sx?)$/;function ri(e,t,r){let n=t==="bun"?"/usr/local/bin/bun":t==="deno"?"/usr/local/bin/deno":"/usr/local/bin/node",s=e.trim();if(/^(?:bun|node|deno)\s+/.test(s))return`${n} ${s.replace(/^(?:bun|node|deno)\s+/,"")}`;let[i="",...a]=s.split(/\s+/);if(i&&!Ra.test(i)){let c=i.startsWith("/")?i:r&&i.startsWith("./")?`${r.replace(/\/+$/,"")}/${i.replace(/^\.\//,"")}`:void 0;if(c)return[c,...a].join(" ")}return`${n} ${s}`}function Os(e){return["TS_CLOUD_MEM_MB=$(awk '/^MemTotal:/{print int($2/1024)}' /proc/meminfo)","TS_CLOUD_HIGH_MB=$((TS_CLOUD_MEM_MB / 8))",'[ "$TS_CLOUD_HIGH_MB" -lt 512 ] && TS_CLOUD_HIGH_MB=512','[ "$TS_CLOUD_HIGH_MB" -gt 4096 ] && TS_CLOUD_HIGH_MB=4096',`mkdir -p /etc/systemd/system/${e}.d`,`printf '# Written by ts-cloud: memoryHigh resolved from this box.
141
141
  # An eighth of %sMB RAM. Set memoryHigh in config to override.
142
142
  [Service]
143
143
  MemoryAccounting=true
@@ -157,7 +157,7 @@ ${s}
157
157
  runcmd:
158
158
  - [ bash, ${r} ]
159
159
  ${Us(t.after)}`}function lr(e){let t=new Set([80,443,...e.sitePorts,...e.allowedPorts??[]]);if(e.allowSsh)t.add(22);return[...t].map((r)=>({direction:"in",protocol:"tcp",port:String(r),source_ips:["0.0.0.0/0","::/0"],description:`ts-cloud port ${r}`}))}var mn={micro:"cpx11",small:"cx23",medium:"cx33",large:"cx43",xlarge:"cx53","2xlarge":"ccx33"};function ze(e){if(!e)return mn.micro;if(e in mn)return mn[e];return e}var J="ts-cloud";function Z(e,t,r="app"){return{[`${J}/project`]:e,[`${J}/environment`]:t,[`${J}/role`]:r,[`${J}/managed-by`]:"ts-cloud"}}function ie(e,t,r,n="app"){return fn(e,t,r)&&e[`${J}/role`]===n}function fn(e,t,r){if(!e)return!1;return e[`${J}/project`]===t&&e[`${J}/environment`]===r}import{mkdir as Ma,readFile as Fa,rename as za,writeFile as Ba}from"node:fs/promises";import{join as Hs}from"node:path";var Oc="storage/cloud/state";function mt(e=process.cwd()){return zd()?l(e,"state"):Hs(e,Oc)}function qe(e,t=process.cwd()){return Hs(mt(t),`${e}.json`)}async function je(e,t=process.cwd()){try{let r=await Fa(qe(e,t),"utf8");return JSON.parse(r)}catch{return null}}async function ft(e,t,r=process.cwd()){let n=qe(e,r);await Ma(mt(r),{recursive:!0});let s=`${n}.${process.pid}.tmp`;await Ba(s,`${JSON.stringify(t,null,2)}
160
- `,"utf8"),await za(s,n)}async function Ke(e){return je(e)}async function Ge(e,t){await ft(e,t)}var gn=268435456;function Rt(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function Wa(e){let t=ja("sha256");for await(let r of Ga(e))t.update(r);return t.digest("hex")}class Pe{name="hetzner";usesCloudFormation=!1;client;sshPrivateKeyPath;sshPublicKeyPath;sshUser;location;stateOnly;waitForBoot;bootWait;constructor(e={}){let t=Et(e.apiToken);if(this.stateOnly=!e.client&&!t&&e.allowStateOnly===!0,!e.client&&!t&&!this.stateOnly)throw Error("Hetzner API token required. Set hetzner.apiToken in cloud.config.ts or HCLOUD_TOKEN / HETZNER_API_TOKEN.");this.client=e.client??new Lr({apiToken:t??""});let r=Ls(void 0,{sshPrivateKeyPath:e.sshPrivateKeyPath,sshPublicKeyPath:e.sshPublicKeyPath,sshUser:e.sshUser,location:e.location});this.sshPrivateKeyPath=r.sshPrivateKeyPath,this.sshPublicKeyPath=r.sshPublicKeyPath,this.sshUser=r.sshUser,this.location=r.location,this.waitForBoot=e.waitForBoot??!0,this.bootWait={sshIntervalMs:e.bootWait?.sshIntervalMs??5000,sshTimeoutMs:e.bootWait?.sshTimeoutMs??300000,cloudInitIntervalMs:e.bootWait?.cloudInitIntervalMs??5000,cloudInitTimeoutMs:e.bootWait?.cloudInitTimeoutMs??600000}}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e,n=t.project.slug,s=t.infrastructure?.compute;if(!s)throw Error("infrastructure.compute is required to provision Hetzner compute");if(t.cloud?.attachTo)return this.attachToComputeInfrastructure(t.cloud.attachTo,t,r);let i=p(t,r),a=`${n}-${r}-app`,c=s.runtime==="php"||!!s.php,u=xs(s);if(u.dedicatedServices||u.appServers>1)return c?this.provisionFleet(e,u):this.provisionBunFleet(e,u);let m=Z(n,r,"app"),f=t.sites||{},v=j(s)?[]:this.collectUpstreamPorts(f),S=`${n}-${r}-app-fw`,{firewall:_}=await this.ensureFirewall(S,m,lr({allowSsh:s.allowSsh!==!1,sitePorts:v,allowedPorts:[...s.firewall?.allowedPorts??[],...ls(t.infrastructure?.sftp),...Xe(b(t,{environment:r}))]})),y=await this.ensureSshKey(n,r,m),x=await Ke(i);if(x?.serverId){let K=await this.tryGetServer(x.serverId);if(K&&K.status!=="off")return this.outputsFromState(x,K)}let R=await this.findExistingServer(n,r,a);if(R&&R.status!=="off"){let K={provider:"hetzner",stackName:i,serverId:R.id,serverName:R.name,publicIp:R.public_net.ipv4?.ip,publicIpv6:De(R.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await Ge(i,K),this.outputsFromState(K,R)}let E=w(t,{environment:r}),D=E?.engine==="rpx"?G({proxy:E,config:B(f,{proxy:E,slug:t.project.slug,mail:b(t,{environment:r})}),slug:t.project.slug,bunBin:s.runtime==="node"||s.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,C=Ue(t,{environment:r}),P=s.bakedImage===!0,L=M({runtime:C.runtime,runtimeVersion:C.runtimeVersion,systemPackages:s.systemPackages,database:t.infrastructure?.database,phpProvision:C.phpProvision,servicesProvision:C.servicesProvision,rpxProvision:D,baked:P,swapGb:s.swapGb}),O=se(L),I=ze(s.size),N=Ot(t),{server:oe,action:de}=await this.client.createServer({name:a,serverType:I,image:N,location:t.hetzner?.location||this.location,userData:O,labels:m,sshKeys:y?[y]:void 0,firewalls:[{firewall:_.id}]});await this.client.waitForAction(de.id);let k=await this.client.waitForServerRunning(oe.id),re={provider:"hetzner",stackName:i,serverId:k.id,serverName:k.name,firewallId:_.id,publicIp:k.public_net.ipv4?.ip,publicIpv6:De(k.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};await Ge(i,re);let Y=k.public_net.ipv4?.ip;if(Y&&this.waitForBoot)await this.waitForSshReady(Y),await this.waitForCloudInit(Y);return this.outputsFromState(re,k)}async provisionFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,i=r.infrastructure.compute,a=p(r,n),c=ze(i.size),u=Ot(r),m=r.hetzner?.location||this.location,f=i.bakedImage===!0,v=await Ke(a);if(v?.loadBalancerId){let V=(await this.client.listLoadBalancers().catch(()=>[])).find((A)=>A.id===v.loadBalancerId);if(V)return{appPublicIp:V.public_net?.ipv4?.ip,loadBalancerIp:V.public_net?.ipv4?.ip,servicesPrivateIp:v.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}let S=await this.ensureSshKey(s,n,Z(s,n,"app")),_=`${s}-${n}-net`,x=(await this.client.listNetworks().catch(()=>[])).find((H)=>H.name===_)??await this.client.createNetwork({name:_,labels:Z(s,n,"app")}),{firewall:R}=await this.ensureFirewall(`${s}-${n}-app-fw`,Z(s,n,"app"),lr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),{firewall:E}=await this.ensureFirewall(`${s}-${n}-services-fw`,Z(s,n,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[x.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[x.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[x.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[x.ip_range]}]),D=dn(r),C=se(M({runtime:"php",servicesProvision:D,baked:f,swapGb:i.swapGb})),P=await this.client.listServers().catch(()=>[]),L=[],O=P.find((H)=>ie(H.labels,s,n,"services"));if(!O){let{server:H,action:V}=await this.client.createServer({name:`${s}-${n}-services`,serverType:ze(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:u,location:m,userData:C,labels:Z(s,n,"services"),sshKeys:S?[S]:void 0,firewalls:[{firewall:E.id}],networks:[x.id]});await this.client.waitForAction(V.id),O=await this.client.waitForServerRunning(H.id),L.push(H.id)}let I=O.id,N=O.private_net?.[0]?.ip??(await this.client.getServer(I)).private_net?.[0]?.ip,oe=[...Oe(!0),...Re(!0),...tt(i.sshKeys),...et(r.notifications)],de=Ft({versions:i.php?.versions,default:i.php?.default,extensions:i.php?.extensions,installNginx:!j(i),optimizeForProduction:i.php?.optimizeForProduction,ini:i.php?.ini}),k=se(M({runtime:"php",phpProvision:de,servicesProvision:oe,baked:f,swapGb:i.swapGb})),re=P.filter((H)=>ie(H.labels,s,n,"app")),Y=re.map((H)=>H.id);if(re.length>t.appServers)for(let H of re.slice(t.appServers))await this.client.deleteServer(H.id).catch(()=>{}),Y.splice(Y.indexOf(H.id),1);for(let H=re.length;H<t.appServers;H++){let{server:V,action:A}=await this.client.createServer({name:`${s}-${n}-app-${H+1}`,serverType:c,image:u,location:m,userData:k,labels:Z(s,n,"app"),sshKeys:S?[S]:void 0,firewalls:[{firewall:R.id}],networks:[x.id]});await this.client.waitForAction(A.id),Y.push(V.id),L.push(V.id)}if(this.waitForBoot&&L.length>0)await Promise.all(L.map(async(H)=>{let A=(await this.client.waitForServerRunning(H)).public_net.ipv4?.ip;if(A)await this.waitForSshReady(A),await this.waitForCloudInit(A)}));let K=`${s}-${n}-lb`,me,Ce;if(t.loadBalancer){let V=(await this.client.listLoadBalancers().catch(()=>[])).find((A)=>A.name===K)??await this.client.createLoadBalancer({name:K,location:m,network:x.id,labels:Z(s,n,"lb"),labelSelector:`ts-cloud/project=${s},ts-cloud/environment=${n},ts-cloud/role=app`,services:[{listenPort:80,destinationPort:80},{listenPort:443,destinationPort:443}]});Ce=V.id,me=V.public_net?.ipv4?.ip}let Ie=me??(await this.client.getServer(Y[0]).catch(()=>{return}))?.public_net.ipv4?.ip,ae={provider:"hetzner",stackName:a,networkId:x.id,loadBalancerId:Ce,servicesServerId:I,servicesPrivateIp:N,publicIp:Ie,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await Ge(a,ae),{appPublicIp:Ie,loadBalancerIp:me,servicesPrivateIp:N,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async provisionBunFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,i=r.infrastructure.compute,a=p(r,n),c=ze(i.size),u=Ot(r),m=r.hetzner?.location||this.location,f=i.bakedImage===!0,v=r.sites||{},S=await Ke(a);if(S?.lbServerId){let A=await this.tryGetServer(S.lbServerId);if(A&&A.status!=="off"){let q=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"},W=await this.findComputeTargets({slug:s,environment:n,role:"app",stackName:a});return this.refreshLbRoutes(A,v,W.map((fe)=>({privateIp:fe.privateIp,publicIp:fe.publicIp})),q,s),{appPublicIp:A.public_net.ipv4?.ip??S.publicIp,loadBalancerIp:A.public_net.ipv4?.ip??S.publicIp,servicesPrivateIp:S.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}}let _=await this.ensureSshKey(s,n,Z(s,n,"app")),y=`${s}-${n}-net`,R=(await this.client.listNetworks().catch(()=>[])).find((A)=>A.name===y)??await this.client.createNetwork({name:y,labels:Z(s,n,"app")}),E=this.collectUpstreamPorts(v),{firewall:D}=await this.ensureFirewall(`${s}-${n}-app-fw`,Z(s,n,"app"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},...E.map((A)=>({direction:"in",protocol:"tcp",port:String(A),source_ips:[R.ip_range],description:`ts-cloud port ${A} (private, LB-only)`}))]),{firewall:C}=await this.ensureFirewall(`${s}-${n}-lb-fw`,Z(s,n,"lb"),lr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),P=await this.client.listServers().catch(()=>[]),L=[],O,I,N=!!i.servicesServer||!!i.managedServices,oe=t.dedicatedServices&&N;if(oe){let{firewall:A}=await this.ensureFirewall(`${s}-${n}-services-fw`,Z(s,n,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[R.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[R.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[R.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[R.ip_range]}]),q=dn(r),W=se(M({runtime:"bun",servicesProvision:q,baked:f,swapGb:i.swapGb})),fe=P.find((Ee)=>ie(Ee.labels,s,n,"services"));if(!fe){let{server:Ee,action:dt}=await this.client.createServer({name:`${s}-${n}-services`,serverType:ze(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:u,location:m,userData:W,labels:Z(s,n,"services"),sshKeys:_?[_]:void 0,firewalls:[{firewall:A.id}],networks:[R.id]});await this.client.waitForAction(dt.id),fe=await this.client.waitForServerRunning(Ee.id),L.push(Ee.id)}O=fe.id,I=fe.private_net?.[0]?.ip??(await this.client.getServer(O)).private_net?.[0]?.ip}let de=oe?{...i,managedServices:void 0,backups:void 0}:i,k=Ue({...r,infrastructure:{...r.infrastructure,compute:de}},{environment:n}),re=se(M({runtime:k.runtime,runtimeVersion:k.runtimeVersion,systemPackages:i.systemPackages,database:r.infrastructure?.database,servicesProvision:k.servicesProvision,baked:f,swapGb:i.swapGb})),Y=P.filter((A)=>ie(A.labels,s,n,"app")),K=Y.map((A)=>A.id);if(Y.length>t.appServers)for(let A of Y.slice(t.appServers))await this.client.deleteServer(A.id).catch(()=>{}),K.splice(K.indexOf(A.id),1);for(let A=Y.length;A<t.appServers;A++){let{server:q,action:W}=await this.client.createServer({name:`${s}-${n}-app-${A+1}`,serverType:c,image:u,location:m,userData:re,labels:Z(s,n,"app"),sshKeys:_?[_]:void 0,firewalls:[{firewall:D.id}],networks:[R.id]});await this.client.waitForAction(W.id),K.push(q.id),L.push(q.id)}if(this.waitForBoot&&L.length>0)await Promise.all(L.map(async(A)=>{let W=(await this.client.waitForServerRunning(A)).public_net.ipv4?.ip;if(W)await this.waitForSshReady(W),await this.waitForCloudInit(W)}));let me=[];for(let A of K){let q=P.find((W)=>W.id===A);if(!q||!q.private_net?.[0]?.ip)q=await this.client.getServer(A).catch(()=>q);me.push({privateIp:q?.private_net?.[0]?.ip,publicIp:q?.public_net.ipv4?.ip})}let Ce=`${s}-${n}-lb`,Ie,ae;if(t.loadBalancer){let A=P.find((W)=>ie(W.labels,s,n,"lb")),q=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"};if(!A){let W=G({proxy:q,config:Xt(v,me,{proxy:q,slug:s}),slug:s,bunBin:k.runtime==="node"||k.runtime==="deno"?void 0:"/usr/local/bin/bun"}),fe=se(M({runtime:"bun",rpxProvision:W,baked:!1})),Ee=typeof i.loadBalancer==="object"?i.loadBalancer.size:void 0,{server:dt,action:Tr}=await this.client.createServer({name:Ce,serverType:ze(Ee??"micro"),image:u,location:m,userData:fe,labels:Z(s,n,"lb"),sshKeys:_?[_]:void 0,firewalls:[{firewall:C.id}],networks:[R.id]});if(await this.client.waitForAction(Tr.id),A=await this.client.waitForServerRunning(dt.id),this.waitForBoot){let gt=A.public_net.ipv4?.ip;if(gt)await this.waitForSshReady(gt),await this.waitForCloudInit(gt)}}else this.refreshLbRoutes(A,v,me,q,s);Ie=A.id,ae=A.public_net.ipv4?.ip}let H=ae??(await this.client.getServer(K[0]).catch(()=>{return}))?.public_net.ipv4?.ip,V={provider:"hetzner",stackName:a,networkId:R.id,lbServerId:Ie,appServerIds:K,servicesServerId:O,servicesPrivateIp:I,publicIp:H,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await Ge(a,V),{appPublicIp:H,loadBalancerIp:ae,servicesPrivateIp:I,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async destroyCompute(e){let{config:t,environment:r}=e,n=t.project.slug,s=p(t,r),i=await Ke(s),a=[],c=`${n}-${r}-lb`,m=(await this.client.listLoadBalancers().catch(()=>[])).find((D)=>D.name===c);if(m)try{await this.client.deleteLoadBalancer(m.id),a.push(`load balancer ${c}`)}catch{}let f=await this.client.listServers().catch(()=>[]),v=new Set;for(let D of f)if(ie(D.labels,n,r,"app")||ie(D.labels,n,r,"services")||ie(D.labels,n,r,"lb"))v.add(D.id);if(i?.serverId)v.add(i.serverId);if(i?.servicesServerId)v.add(i.servicesServerId);if(i?.lbServerId)v.add(i.lbServerId);for(let D of i?.appServerIds??[])v.add(D);for(let D of v)try{await this.client.deleteServer(D),a.push(`server ${D}`)}catch{}let S=await this.client.listFirewalls().catch(()=>[]);for(let D of[`${n}-${r}-app-fw`,`${n}-${r}-services-fw`,`${n}-${r}-lb-fw`]){let C=S.find((P)=>P.name===D);if(!C)continue;for(let P=0;P<12;P++)try{await this.client.deleteFirewall(C.id),a.push(`firewall ${D}`);break}catch{await this.sleep(3000)}}let _=`${n}-${r}-net`,x=(await this.client.listNetworks().catch(()=>[])).find((D)=>D.name===_);if(x)for(let D=0;D<12;D++)try{await this.client.deleteNetwork(x.id),a.push(`network ${_}`);break}catch{await this.sleep(3000)}let E=(await this.client.listSshKeys().catch(()=>[])).filter((D)=>fn(D.labels,n,r));for(let D of E)try{await this.client.deleteSshKey(D.id),a.push(`ssh key ${D.name}`)}catch{}return await Ge(s,{provider:"hetzner",stackName:s}).catch(()=>{}),{destroyed:a}}async getComputeOutputs(e){let t=p(e.config,e.environment),r=await Ke(t);if(r?.serverId){let i=await this.tryGetServer(r.serverId);if(i)return this.outputsFromState(r,i)}if(r?.lbServerId){let a=(await this.tryGetServer(r.lbServerId))?.public_net.ipv4?.ip??r.publicIp;return{...this.outputsFromState(r),appPublicIp:a,loadBalancerIp:a}}if(r?.loadBalancerId||r?.servicesPrivateIp)return this.outputsFromState(r);let s=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:p(e.config,e.environment)}))[0];return{deployStoragePath:"/var/ts-cloud/staging",appInstanceId:s?.id,appPublicIp:s?.publicIp,sshUser:this.sshUser}}async uploadRelease(e){let t=e.targets?.length?e.targets:await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:p(e.config,e.environment)});if(t.length===0)throw Error("No Hetzner compute targets found for release upload");let s=`/var/ts-cloud/staging/${`${e.remoteKey.replace(/^releases\//,"").replace(/\.tar\.gz$/,"").replace(/\//g,"-")}-${Ns()}.tar.gz`}`,i=await Wa(e.localPath),a=Or,c=`${a}/${i}.tar.gz`;for(let u of t){if(!u.publicIp)throw Error(`Target ${u.id} has no public IP for SCP upload`);let m=["set -euo pipefail",`mkdir -p ${Rt(a)} /var/ts-cloud/staging`,`test -s ${Rt(c)}`,`cp -- ${Rt(c)} ${Rt(s)}`].join(`
160
+ `,"utf8"),await za(s,n)}async function Ke(e){return je(e)}async function Ge(e,t){await ft(e,t)}var gn=268435456;function Rt(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function Wa(e){let t=ja("sha256");for await(let r of Ga(e))t.update(r);return t.digest("hex")}class Pe{name="hetzner";usesCloudFormation=!1;client;sshPrivateKeyPath;sshPublicKeyPath;sshUser;location;stateOnly;waitForBoot;bootWait;constructor(e={}){let t=Et(e.apiToken);if(this.stateOnly=!e.client&&!t&&e.allowStateOnly===!0,!e.client&&!t&&!this.stateOnly)throw Error("Hetzner API token required. Set hetzner.apiToken in cloud.config.ts or HCLOUD_TOKEN / HETZNER_API_TOKEN.");this.client=e.client??new Lr({apiToken:t??""});let r=Ls(void 0,{sshPrivateKeyPath:e.sshPrivateKeyPath,sshPublicKeyPath:e.sshPublicKeyPath,sshUser:e.sshUser,location:e.location});this.sshPrivateKeyPath=r.sshPrivateKeyPath,this.sshPublicKeyPath=r.sshPublicKeyPath,this.sshUser=r.sshUser,this.location=r.location,this.waitForBoot=e.waitForBoot??!0,this.bootWait={sshIntervalMs:e.bootWait?.sshIntervalMs??5000,sshTimeoutMs:e.bootWait?.sshTimeoutMs??300000,cloudInitIntervalMs:e.bootWait?.cloudInitIntervalMs??5000,cloudInitTimeoutMs:e.bootWait?.cloudInitTimeoutMs??600000}}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e,n=t.project.slug,s=t.infrastructure?.compute;if(!s)throw Error("infrastructure.compute is required to provision Hetzner compute");if(t.cloud?.attachTo)return this.attachToComputeInfrastructure(t.cloud.attachTo,t,r);let i=p(t,r),a=`${n}-${r}-app`,c=s.runtime==="php"||!!s.php,u=xs(s);if(u.dedicatedServices||u.appServers>1)return c?this.provisionFleet(e,u):this.provisionBunFleet(e,u);let m=Z(n,r,"app"),f=t.sites||{},v=j(s)?[]:this.collectUpstreamPorts(f),S=`${n}-${r}-app-fw`,{firewall:_}=await this.ensureFirewall(S,m,lr({allowSsh:s.allowSsh!==!1,sitePorts:v,allowedPorts:[...s.firewall?.allowedPorts??[],...ls(t.infrastructure?.sftp),...Xe(b(t,{environment:r}))]})),y=await this.ensureSshKey(n,r,m),x=await Ke(i);if(x?.serverId){let K=await this.tryGetServer(x.serverId);if(K&&K.status!=="off")return this.outputsFromState(x,K)}let R=await this.findExistingServer(n,r,a);if(R&&R.status!=="off"){let K={provider:"hetzner",stackName:i,serverId:R.id,serverName:R.name,publicIp:R.public_net.ipv4?.ip,publicIpv6:De(R.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await Ge(i,K),this.outputsFromState(K,R)}let E=w(t,{environment:r}),D=E?.engine==="rpx"?G({proxy:E,config:B(f,{proxy:E,slug:t.project.slug,mail:b(t,{environment:r})}),slug:t.project.slug,bunBin:s.runtime==="node"||s.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,C=He(t,{environment:r}),P=s.bakedImage===!0,L=M({runtime:C.runtime,runtimeVersion:C.runtimeVersion,systemPackages:s.systemPackages,database:t.infrastructure?.database,phpProvision:C.phpProvision,servicesProvision:C.servicesProvision,rpxProvision:D,baked:P,swapGb:s.swapGb}),O=se(L),I=ze(s.size),N=Ot(t),{server:oe,action:de}=await this.client.createServer({name:a,serverType:I,image:N,location:t.hetzner?.location||this.location,userData:O,labels:m,sshKeys:y?[y]:void 0,firewalls:[{firewall:_.id}]});await this.client.waitForAction(de.id);let k=await this.client.waitForServerRunning(oe.id),re={provider:"hetzner",stackName:i,serverId:k.id,serverName:k.name,firewallId:_.id,publicIp:k.public_net.ipv4?.ip,publicIpv6:De(k.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};await Ge(i,re);let Y=k.public_net.ipv4?.ip;if(Y&&this.waitForBoot)await this.waitForSshReady(Y),await this.waitForCloudInit(Y);return this.outputsFromState(re,k)}async provisionFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,i=r.infrastructure.compute,a=p(r,n),c=ze(i.size),u=Ot(r),m=r.hetzner?.location||this.location,f=i.bakedImage===!0,v=await Ke(a);if(v?.loadBalancerId){let V=(await this.client.listLoadBalancers().catch(()=>[])).find((A)=>A.id===v.loadBalancerId);if(V)return{appPublicIp:V.public_net?.ipv4?.ip,loadBalancerIp:V.public_net?.ipv4?.ip,servicesPrivateIp:v.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}let S=await this.ensureSshKey(s,n,Z(s,n,"app")),_=`${s}-${n}-net`,x=(await this.client.listNetworks().catch(()=>[])).find((H)=>H.name===_)??await this.client.createNetwork({name:_,labels:Z(s,n,"app")}),{firewall:R}=await this.ensureFirewall(`${s}-${n}-app-fw`,Z(s,n,"app"),lr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),{firewall:E}=await this.ensureFirewall(`${s}-${n}-services-fw`,Z(s,n,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[x.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[x.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[x.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[x.ip_range]}]),D=dn(r),C=se(M({runtime:"php",servicesProvision:D,baked:f,swapGb:i.swapGb})),P=await this.client.listServers().catch(()=>[]),L=[],O=P.find((H)=>ie(H.labels,s,n,"services"));if(!O){let{server:H,action:V}=await this.client.createServer({name:`${s}-${n}-services`,serverType:ze(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:u,location:m,userData:C,labels:Z(s,n,"services"),sshKeys:S?[S]:void 0,firewalls:[{firewall:E.id}],networks:[x.id]});await this.client.waitForAction(V.id),O=await this.client.waitForServerRunning(H.id),L.push(H.id)}let I=O.id,N=O.private_net?.[0]?.ip??(await this.client.getServer(I)).private_net?.[0]?.ip,oe=[...Oe(!0),...Re(!0),...tt(i.sshKeys),...et(r.notifications)],de=Ft({versions:i.php?.versions,default:i.php?.default,extensions:i.php?.extensions,installNginx:!j(i),optimizeForProduction:i.php?.optimizeForProduction,ini:i.php?.ini}),k=se(M({runtime:"php",phpProvision:de,servicesProvision:oe,baked:f,swapGb:i.swapGb})),re=P.filter((H)=>ie(H.labels,s,n,"app")),Y=re.map((H)=>H.id);if(re.length>t.appServers)for(let H of re.slice(t.appServers))await this.client.deleteServer(H.id).catch(()=>{}),Y.splice(Y.indexOf(H.id),1);for(let H=re.length;H<t.appServers;H++){let{server:V,action:A}=await this.client.createServer({name:`${s}-${n}-app-${H+1}`,serverType:c,image:u,location:m,userData:k,labels:Z(s,n,"app"),sshKeys:S?[S]:void 0,firewalls:[{firewall:R.id}],networks:[x.id]});await this.client.waitForAction(A.id),Y.push(V.id),L.push(V.id)}if(this.waitForBoot&&L.length>0)await Promise.all(L.map(async(H)=>{let A=(await this.client.waitForServerRunning(H)).public_net.ipv4?.ip;if(A)await this.waitForSshReady(A),await this.waitForCloudInit(A)}));let K=`${s}-${n}-lb`,me,Ce;if(t.loadBalancer){let V=(await this.client.listLoadBalancers().catch(()=>[])).find((A)=>A.name===K)??await this.client.createLoadBalancer({name:K,location:m,network:x.id,labels:Z(s,n,"lb"),labelSelector:`ts-cloud/project=${s},ts-cloud/environment=${n},ts-cloud/role=app`,services:[{listenPort:80,destinationPort:80},{listenPort:443,destinationPort:443}]});Ce=V.id,me=V.public_net?.ipv4?.ip}let Ae=me??(await this.client.getServer(Y[0]).catch(()=>{return}))?.public_net.ipv4?.ip,ae={provider:"hetzner",stackName:a,networkId:x.id,loadBalancerId:Ce,servicesServerId:I,servicesPrivateIp:N,publicIp:Ae,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await Ge(a,ae),{appPublicIp:Ae,loadBalancerIp:me,servicesPrivateIp:N,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async provisionBunFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,i=r.infrastructure.compute,a=p(r,n),c=ze(i.size),u=Ot(r),m=r.hetzner?.location||this.location,f=i.bakedImage===!0,v=r.sites||{},S=await Ke(a);if(S?.lbServerId){let A=await this.tryGetServer(S.lbServerId);if(A&&A.status!=="off"){let q=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"},W=await this.findComputeTargets({slug:s,environment:n,role:"app",stackName:a});return this.refreshLbRoutes(A,v,W.map((fe)=>({privateIp:fe.privateIp,publicIp:fe.publicIp})),q,s),{appPublicIp:A.public_net.ipv4?.ip??S.publicIp,loadBalancerIp:A.public_net.ipv4?.ip??S.publicIp,servicesPrivateIp:S.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}}let _=await this.ensureSshKey(s,n,Z(s,n,"app")),y=`${s}-${n}-net`,R=(await this.client.listNetworks().catch(()=>[])).find((A)=>A.name===y)??await this.client.createNetwork({name:y,labels:Z(s,n,"app")}),E=this.collectUpstreamPorts(v),{firewall:D}=await this.ensureFirewall(`${s}-${n}-app-fw`,Z(s,n,"app"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},...E.map((A)=>({direction:"in",protocol:"tcp",port:String(A),source_ips:[R.ip_range],description:`ts-cloud port ${A} (private, LB-only)`}))]),{firewall:C}=await this.ensureFirewall(`${s}-${n}-lb-fw`,Z(s,n,"lb"),lr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),P=await this.client.listServers().catch(()=>[]),L=[],O,I,N=!!i.servicesServer||!!i.managedServices,oe=t.dedicatedServices&&N;if(oe){let{firewall:A}=await this.ensureFirewall(`${s}-${n}-services-fw`,Z(s,n,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[R.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[R.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[R.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[R.ip_range]}]),q=dn(r),W=se(M({runtime:"bun",servicesProvision:q,baked:f,swapGb:i.swapGb})),fe=P.find((Ee)=>ie(Ee.labels,s,n,"services"));if(!fe){let{server:Ee,action:dt}=await this.client.createServer({name:`${s}-${n}-services`,serverType:ze(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:u,location:m,userData:W,labels:Z(s,n,"services"),sshKeys:_?[_]:void 0,firewalls:[{firewall:A.id}],networks:[R.id]});await this.client.waitForAction(dt.id),fe=await this.client.waitForServerRunning(Ee.id),L.push(Ee.id)}O=fe.id,I=fe.private_net?.[0]?.ip??(await this.client.getServer(O)).private_net?.[0]?.ip}let de=oe?{...i,managedServices:void 0,backups:void 0}:i,k=He({...r,infrastructure:{...r.infrastructure,compute:de}},{environment:n}),re=se(M({runtime:k.runtime,runtimeVersion:k.runtimeVersion,systemPackages:i.systemPackages,database:r.infrastructure?.database,servicesProvision:k.servicesProvision,baked:f,swapGb:i.swapGb})),Y=P.filter((A)=>ie(A.labels,s,n,"app")),K=Y.map((A)=>A.id);if(Y.length>t.appServers)for(let A of Y.slice(t.appServers))await this.client.deleteServer(A.id).catch(()=>{}),K.splice(K.indexOf(A.id),1);for(let A=Y.length;A<t.appServers;A++){let{server:q,action:W}=await this.client.createServer({name:`${s}-${n}-app-${A+1}`,serverType:c,image:u,location:m,userData:re,labels:Z(s,n,"app"),sshKeys:_?[_]:void 0,firewalls:[{firewall:D.id}],networks:[R.id]});await this.client.waitForAction(W.id),K.push(q.id),L.push(q.id)}if(this.waitForBoot&&L.length>0)await Promise.all(L.map(async(A)=>{let W=(await this.client.waitForServerRunning(A)).public_net.ipv4?.ip;if(W)await this.waitForSshReady(W),await this.waitForCloudInit(W)}));let me=[];for(let A of K){let q=P.find((W)=>W.id===A);if(!q||!q.private_net?.[0]?.ip)q=await this.client.getServer(A).catch(()=>q);me.push({privateIp:q?.private_net?.[0]?.ip,publicIp:q?.public_net.ipv4?.ip})}let Ce=`${s}-${n}-lb`,Ae,ae;if(t.loadBalancer){let A=P.find((W)=>ie(W.labels,s,n,"lb")),q=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"};if(!A){let W=G({proxy:q,config:Xt(v,me,{proxy:q,slug:s}),slug:s,bunBin:k.runtime==="node"||k.runtime==="deno"?void 0:"/usr/local/bin/bun"}),fe=se(M({runtime:"bun",rpxProvision:W,baked:!1})),Ee=typeof i.loadBalancer==="object"?i.loadBalancer.size:void 0,{server:dt,action:Tr}=await this.client.createServer({name:Ce,serverType:ze(Ee??"micro"),image:u,location:m,userData:fe,labels:Z(s,n,"lb"),sshKeys:_?[_]:void 0,firewalls:[{firewall:C.id}],networks:[R.id]});if(await this.client.waitForAction(Tr.id),A=await this.client.waitForServerRunning(dt.id),this.waitForBoot){let gt=A.public_net.ipv4?.ip;if(gt)await this.waitForSshReady(gt),await this.waitForCloudInit(gt)}}else this.refreshLbRoutes(A,v,me,q,s);Ae=A.id,ae=A.public_net.ipv4?.ip}let H=ae??(await this.client.getServer(K[0]).catch(()=>{return}))?.public_net.ipv4?.ip,V={provider:"hetzner",stackName:a,networkId:R.id,lbServerId:Ae,appServerIds:K,servicesServerId:O,servicesPrivateIp:I,publicIp:H,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await Ge(a,V),{appPublicIp:H,loadBalancerIp:ae,servicesPrivateIp:I,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async destroyCompute(e){let{config:t,environment:r}=e,n=t.project.slug,s=p(t,r),i=await Ke(s),a=[],c=`${n}-${r}-lb`,m=(await this.client.listLoadBalancers().catch(()=>[])).find((D)=>D.name===c);if(m)try{await this.client.deleteLoadBalancer(m.id),a.push(`load balancer ${c}`)}catch{}let f=await this.client.listServers().catch(()=>[]),v=new Set;for(let D of f)if(ie(D.labels,n,r,"app")||ie(D.labels,n,r,"services")||ie(D.labels,n,r,"lb"))v.add(D.id);if(i?.serverId)v.add(i.serverId);if(i?.servicesServerId)v.add(i.servicesServerId);if(i?.lbServerId)v.add(i.lbServerId);for(let D of i?.appServerIds??[])v.add(D);for(let D of v)try{await this.client.deleteServer(D),a.push(`server ${D}`)}catch{}let S=await this.client.listFirewalls().catch(()=>[]);for(let D of[`${n}-${r}-app-fw`,`${n}-${r}-services-fw`,`${n}-${r}-lb-fw`]){let C=S.find((P)=>P.name===D);if(!C)continue;for(let P=0;P<12;P++)try{await this.client.deleteFirewall(C.id),a.push(`firewall ${D}`);break}catch{await this.sleep(3000)}}let _=`${n}-${r}-net`,x=(await this.client.listNetworks().catch(()=>[])).find((D)=>D.name===_);if(x)for(let D=0;D<12;D++)try{await this.client.deleteNetwork(x.id),a.push(`network ${_}`);break}catch{await this.sleep(3000)}let E=(await this.client.listSshKeys().catch(()=>[])).filter((D)=>fn(D.labels,n,r));for(let D of E)try{await this.client.deleteSshKey(D.id),a.push(`ssh key ${D.name}`)}catch{}return await Ge(s,{provider:"hetzner",stackName:s}).catch(()=>{}),{destroyed:a}}async getComputeOutputs(e){let t=p(e.config,e.environment),r=await Ke(t);if(r?.serverId){let i=await this.tryGetServer(r.serverId);if(i)return this.outputsFromState(r,i)}if(r?.lbServerId){let a=(await this.tryGetServer(r.lbServerId))?.public_net.ipv4?.ip??r.publicIp;return{...this.outputsFromState(r),appPublicIp:a,loadBalancerIp:a}}if(r?.loadBalancerId||r?.servicesPrivateIp)return this.outputsFromState(r);let s=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:p(e.config,e.environment)}))[0];return{deployStoragePath:"/var/ts-cloud/staging",appInstanceId:s?.id,appPublicIp:s?.publicIp,sshUser:this.sshUser}}async uploadRelease(e){let t=e.targets?.length?e.targets:await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:p(e.config,e.environment)});if(t.length===0)throw Error("No Hetzner compute targets found for release upload");let s=`/var/ts-cloud/staging/${`${e.remoteKey.replace(/^releases\//,"").replace(/\.tar\.gz$/,"").replace(/\//g,"-")}-${Ns()}.tar.gz`}`,i=await Wa(e.localPath),a=Or,c=`${a}/${i}.tar.gz`;for(let u of t){if(!u.publicIp)throw Error(`Target ${u.id} has no public IP for SCP upload`);let m=["set -euo pipefail",`mkdir -p ${Rt(a)} /var/ts-cloud/staging`,`test -s ${Rt(c)}`,`cp -- ${Rt(c)} ${Rt(s)}`].join(`
161
161
  `);try{this.sshExec(u.publicIp,m);continue}catch{}let f=`${a}/.${i}-${Ns()}.tmp`;try{this.scpToHost(u.publicIp,e.localPath,f),this.sshExec(u.publicIp,rr(f,c,s))}catch(v){try{this.sshExec(u.publicIp,nr(f))}catch{}throw v}}return{artifactRef:s}}async findComputeTargets(e){let t=e.role||"app",r=(i)=>({id:String(i.id),name:i.name,publicIp:i.public_net.ipv4?.ip,publicIpv6:De(i.public_net.ipv6?.ip),privateIp:i.private_net?.[0]?.ip,status:i.status});if(t==="app"||t==="lb"||t==="services"){let i=await Ke(e.stackName??`${e.slug}-${e.environment}`),a=[...new Set(t==="app"?[i?.serverId,...i?.appServerIds??[]]:t==="lb"?[i?.lbServerId]:[i?.servicesServerId])].filter((m)=>typeof m==="number");if(this.stateOnly){if(a.length>0&&i?.publicIp)return a.map((m)=>({id:String(m),name:m===i.serverId?i.serverName:void 0,publicIp:i.publicIp,publicIpv6:i.publicIpv6,status:"running"}));if(t!=="app")return[];throw Error(`Hetzner API token required because '${e.stackName??`${e.slug}-${e.environment}`}' has no complete local compute state pin.`)}let c=await this.client.listServers();if(a.length>0){let m=[];for(let f of a){let v=c.find((S)=>S.id===f)??await this.tryGetServer(f);if(f===i?.serverId&&i.serverName&&v?.name!==i.serverName)continue;if(v&&v.status!=="off")m.push(v)}if(m.length>0)return m.map(r)}let u=c.filter((m)=>ie(m.labels,e.slug,e.environment,t));if(u.length>0)return u.map(r);if(t==="app"){let m=c.filter((f)=>f.status!=="off"&&f.labels?.[`${J}/managed-by`]==="ts-cloud"&&f.labels?.[`${J}/environment`]===e.environment&&f.labels?.[`${J}/role`]==="app");if(m.length===1)return m.map(r)}return[]}if(this.stateOnly)throw Error(`Hetzner API token required to discover '${t}' compute targets.`);let s=(await this.client.listServers()).filter((i)=>ie(i.labels,e.slug,e.environment,t));if(s.length>0)return s.map(r);return[]}async attachToComputeInfrastructure(e,t,r){let n=await this.client.listServers(),s=(S)=>n.filter((_)=>_.status!=="off"&&ie(_.labels,e,r,S)),i=s("app");if(i.length===0)throw Error(`Cannot attach '${t.project.slug}' to '${e}': no running Hetzner app server is labeled for ${e}/${r}. Deploy the owner project first.`);let a=s("lb")[0],c=s("services")[0],u=i[0],m=a??u,f=p(t,r),v={provider:"hetzner",stackName:f,serverId:u.id,serverName:u.name,appServerIds:i.map((S)=>S.id),lbServerId:a?.id,servicesServerId:c?.id,servicesPrivateIp:c?.private_net?.[0]?.ip,publicIp:m.public_net.ipv4?.ip,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await Ge(f,v),this.outputsFromState(v)}async listReachableResources(){return(await this.client.listServers()).map((t)=>({name:t.name,labels:t.labels}))}async runRemoteDeploy(e){if(e.targets.length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets provided"};let t=e.commands.join(`
162
162
  `),r=[];for(let s of e.targets){if(!s.publicIp){r.push({instanceId:s.id,status:"Failed",error:"Missing public IP"});continue}try{let i=this.sshExec(s.publicIp,t);Pr(i),r.push({instanceId:s.id,status:"Success",output:i})}catch(i){r.push({instanceId:s.id,status:"Failed",error:i.message})}}let n=r.every((s)=>s.status==="Success");return{success:n,instanceCount:e.targets.length,perInstance:r,error:n?void 0:zt(r,"One or more SSH deploy commands failed")}}async ensureSshKey(e,t,r){if(!Va(this.sshPublicKeyPath))throw Error(`SSH public key not found at ${this.sshPublicKeyPath}. ts-cloud deploys to Hetzner over SSH and needs a public key to authorize on the server. Generate one (\`ssh-keygen -t ed25519\`) or set hetzner.sshPrivateKeyPath / HCLOUD_SSH_PUBLIC_KEY.`);let n=qa(this.sshPublicKeyPath,"utf8").trim(),s=Ve(n),a=(await this.client.listSshKeys()).find((u)=>Ve(u.public_key)===s);if(a)return a.id;return(await this.client.createSshKey({name:`${e}-${t}-deploy`,publicKey:n,labels:r})).id}async tryGetServer(e){try{return await this.client.getServer(e)}catch{return null}}refreshLbRoutes(e,t,r,n,s){let i=e.public_net.ipv4?.ip;if(!i){console.warn(`[ts-cloud] LB server '${e.name}' has no public IP — skipping the rpx route refresh; its routes may be stale.`);return}let a=r.filter((u)=>u.privateIp||u.publicIp);if(a.length===0){console.warn(`[ts-cloud] No routable app boxes found for LB '${e.name}' — leaving its current rpx routes untouched.`);return}let c=Xt(t,a,{proxy:n,slug:s});this.sshExec(i,ke({config:c,slug:s}).join(`
163
163
  `))}async findExistingServer(e,t,r){let n=await this.client.listServers(),s=n.find((a)=>ie(a.labels,e,t,"app")||a.name===r);if(s)return s;let i=n.filter((a)=>a.status!=="off"&&a.labels?.[`${J}/managed-by`]==="ts-cloud"&&a.labels?.[`${J}/environment`]===t&&a.labels?.[`${J}/role`]==="app");if(i.length===1){let a=i[0],c=a.labels?.[`${J}/project`]??"unknown";return console.warn(`[ts-cloud] No server named '${r}' found; adopting existing ts-cloud app server '${a.name}' (project label '${c}') for project '${e}' — `+"updating it in place instead of provisioning a new server."),a}return}async ensureFirewall(e,t,r){let s=(await this.client.listFirewalls()).find((a)=>a.name===e);if(s)return await this.client.setFirewallRules(s.id,r),{firewall:s};let{firewall:i}=await this.client.createFirewall({name:e,labels:t,rules:r});return{firewall:i}}collectUpstreamPorts(e){let t=new Set;for(let r of Object.values(e))if(typeof r.port==="number")t.add(r.port);return[...t].filter((r)=>![80,443].includes(r))}async sleep(e){await new Promise((t)=>setTimeout(t,e))}async waitForSshReady(e){let{sshIntervalMs:t,sshTimeoutMs:r}=this.bootWait,n=Date.now(),s;while(Date.now()-n<r)try{ks(`ssh ${this.sshBaseArgs(e,["-o","ConnectTimeout=5"]).map(Rt).join(" ")} true`,{stdio:"pipe",maxBuffer:gn});return}catch(i){s=i,await this.sleep(t)}throw Error(`Timed out waiting for SSH on ${e} after ${r}ms: ${s?.message??"unknown error"}`)}async waitForCloudInit(e){let{cloudInitIntervalMs:t,cloudInitTimeoutMs:r}=this.bootWait,n=Date.now();while(Date.now()-n<r){try{let s=this.sshExec(e,"if command -v cloud-init >/dev/null 2>&1; then cloud-init status --long 2>/dev/null || true; else echo 'status: done'; fi");if(/status:\s*error/.test(s))throw Error(`cloud-init reported an error on ${e}:
@@ -196,7 +196,7 @@ systemctl restart systemd-journald
196
196
  # The deploy user uploads releases as itself (scp), while the scripts run as
197
197
  # root through sudo. setgid group-writable directories let both write.
198
198
  install -d -m 2775 -g "$(id -gn ${We(e)})" /var/ts-cloud/artifacts /var/ts-cloud/staging
199
- `}function ac(e){let t=We(e),r=`/home/${e}`;return[`chown -R ${t}:"$(id -gn ${t})" ${We(`${r}/.ssh`)}`,`chmod 700 ${We(`${r}/.ssh`)}`]}function ai(e){let{config:t,environment:r,profile:n,sudoUser:s}=e;Ws(t,n,e.facts?.arch);let i={...t.infrastructure?.compute,proxy:w(t,{environment:e.environment,environmentType:e.environment})},a=t.sites??{},c=t.project.slug,u=e.lan?{...e.lan.hostname?{hostname:e.lan.hostname}:{},tls:e.lan.tls??"local-ca",...Vs(e)?{ip:Vs(e)}:{}}:void 0,m=i.proxy?.engine==="rpx"?B(a,{proxy:i.proxy,slug:c,lan:u,mail:b(t,{environment:e.environment,environmentType:e.environment})}):void 0,f=i.proxy?.engine==="rpx"&&m?G({proxy:i.proxy,config:m,slug:c,profile:n,bunBin:i.runtime==="node"||i.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,v=i.proxy?.engine==="rpx"&&m?ke({config:m,slug:c}):void 0,S=s?`/home/${s}/.ssh/authorized_keys`:void 0,_=Ue(t,{environment:r,authorizedKeysPath:S}),y=s?[..._.servicesProvision??[],...ac(s)]:_.servicesProvision,x=[...new Set([...i.systemPackages??[],"psmisc","ca-certificates"])],R=i.swapGb??(n==="raspberry-pi"?Lg:void 0),E=M({runtime:_.runtime,runtimeVersion:_.runtimeVersion,systemPackages:x,database:t.infrastructure?.database,phpProvision:_.phpProvision,servicesProvision:y,rpxProvision:f,swapGb:R}).replace(/^#!\/bin\/bash\nset -euo pipefail\n/,""),D=_g(),C=m?.localCa?` lan=${m.localCa.hosts.join(",")} tls=local-ca`:u?` lan=${u.hostname??`${c}.local`} tls=${u.tls??"local-ca"}`:"",P=`#!/bin/bash
199
+ `}function ac(e){let t=We(e),r=`/home/${e}`;return[`chown -R ${t}:"$(id -gn ${t})" ${We(`${r}/.ssh`)}`,`chmod 700 ${We(`${r}/.ssh`)}`]}function ai(e){let{config:t,environment:r,profile:n,sudoUser:s}=e;Ws(t,n,e.facts?.arch);let i={...t.infrastructure?.compute,proxy:w(t,{environment:e.environment,environmentType:e.environment})},a=t.sites??{},c=t.project.slug,u=e.lan?{...e.lan.hostname?{hostname:e.lan.hostname}:{},tls:e.lan.tls??"local-ca",...Vs(e)?{ip:Vs(e)}:{}}:void 0,m=i.proxy?.engine==="rpx"?B(a,{proxy:i.proxy,slug:c,lan:u,mail:b(t,{environment:e.environment,environmentType:e.environment})}):void 0,f=i.proxy?.engine==="rpx"&&m?G({proxy:i.proxy,config:m,slug:c,profile:n,bunBin:i.runtime==="node"||i.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,v=i.proxy?.engine==="rpx"&&m?ke({config:m,slug:c}):void 0,S=s?`/home/${s}/.ssh/authorized_keys`:void 0,_=He(t,{environment:r,authorizedKeysPath:S}),y=s?[..._.servicesProvision??[],...ac(s)]:_.servicesProvision,x=[...new Set([...i.systemPackages??[],"psmisc","ca-certificates"])],R=i.swapGb??(n==="raspberry-pi"?Lg:void 0),E=M({runtime:_.runtime,runtimeVersion:_.runtimeVersion,systemPackages:x,database:t.infrastructure?.database,phpProvision:_.phpProvision,servicesProvision:y,rpxProvision:f,swapGb:R}).replace(/^#!\/bin\/bash\nset -euo pipefail\n/,""),D=_g(),C=m?.localCa?` lan=${m.localCa.hosts.join(",")} tls=local-ca`:u?` lan=${u.hostname??`${c}.local`} tls=${u.tls??"local-ca"}`:"",P=`#!/bin/bash
200
200
  set -euo pipefail
201
201
  # ts-cloud ssh bootstrap v${Ne} profile=${n}${C}
202
202
 
@@ -417,7 +417,7 @@ This password is now in your deploy log. Set TS_CLOUD_UI_PASSWORD to a value of
417
417
  `.replace(/%/g,"\\%");u.push(`cat > ${R} <<'TS_CLOUD_CRON_EOF'`,C.replace(/\n$/,""),"TS_CLOUD_CRON_EOF",`chmod 644 ${R}`)}else u.push(`rm -f ${R}`);return u}function En(e){return!!(e.queues?.length||e.daemons?.length||e.scheduler)}function On(e){if(e.ssl?.provider)return e.ssl.provider;return e.domain?"letsencrypt":"none"}var ji={cloudflare:{pkg:"python3-certbot-dns-cloudflare",plugin:"dns-cloudflare"},route53:{pkg:"python3-certbot-dns-route53",plugin:"dns-route53"},digitalocean:{pkg:"python3-certbot-dns-digitalocean",plugin:"dns-digitalocean"},google:{pkg:"python3-certbot-dns-google",plugin:"dns-google"}};function Gi(e){return`/etc/letsencrypt/ts-cloud-${e}.ini`}function Nl(e){let t=e?ji[e.provider]:void 0,r=["certbot","python3-certbot-nginx",...t?[t.pkg]:[]].join(" ");return["export DEBIAN_FRONTEND=noninteractive",t?`apt-get update -y && apt-get install -y ${r}`:`command -v certbot >/dev/null 2>&1 || { apt-get update -y && apt-get install -y ${r}; }`,"mkdir -p /etc/letsencrypt/renewal-hooks/deploy","cat > /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh <<'TS_CLOUD_HOOK_EOF'","#!/bin/sh","systemctl reload ts-cloud-nginx 2>/dev/null || systemctl reload nginx 2>/dev/null || true","TS_CLOUD_HOOK_EOF","chmod +x /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh","systemctl enable certbot.timer 2>/dev/null || true","systemctl start certbot.timer 2>/dev/null || true"]}function Ml(e){if(!e.credentials||Object.keys(e.credentials).length===0)return[];let t=Gi(e.provider),r=Object.entries(e.credentials).map(([n,s])=>`${n} = ${s}`).join(`
418
418
  `);return[`cat > ${t} <<'TS_CLOUD_DNSCREDS_EOF'`,r,"TS_CLOUD_DNSCREDS_EOF",`chmod 600 ${t}`]}function Fl(e){let t=e.dns,r=e.wildcard?[`*.${e.domain}`,e.domain]:[e.domain,...e.aliases||[]].filter(Boolean),n=["certbot","--non-interactive","--agree-tos","--keep-until-expiring"];if(t){let s=ji[t.provider].plugin;if(n.push(`--${s}`),t.provider!=="route53"&&t.credentials)n.push(`--${s}-credentials ${Gi(t.provider)}`);if(typeof t.propagationSeconds==="number"&&t.provider!=="route53")n.push(`--${s}-propagation-seconds ${t.propagationSeconds}`);n.push("certonly")}else n.push("--nginx",`--nginx-ctl ${xe}`,e.redirect===!1?"--no-redirect":"--redirect");if(e.email)n.push(`-m ${e.email}`);else n.push("--register-unsafely-without-email");for(let s of r)n.push(`-d ${s}`);return[n.join(" ")]}function Rn(e){if(On(e)!=="letsencrypt"||!e.domain)return[];let t=e.ssl,r=t?.dns,n=t?.wildcard===!0;if(n&&!r)return[];return[...Nl(r),...r?Ml(r):[],...Fl({domain:e.domain,aliases:e.aliases,email:t?.email,wildcard:n,dns:r})]}function Vi(e){let{repository:t,releaseDir:r,commit:n}=e,s=t.branch||"main",i=t.url,a=[`rm -rf ${r}`,`mkdir -p ${r}`];if(t.strategy==="tag")if(t.tag)a.push(`git clone -q --depth 1 --branch ${pe(t.tag)} ${pe(i)} ${r}`),a.push(`printf '%s' ${pe(t.tag)} > ${r}/.ts-cloud-tag`);else{let c=t.tagPattern||"v*";a.push(`TS_CLOUD_TAG="$(git ls-remote --tags --refs --sort=-v:refname ${pe(i)} ${pe(`refs/tags/${c}`)} | head -n1 | sed 's#.*refs/tags/##')"`,`test -n "$TS_CLOUD_TAG" || { echo "no tags matching" ${pe(c)} "found in" ${pe(i)} >&2; exit 1; }`,`git clone -q --depth 1 --branch "$TS_CLOUD_TAG" ${pe(i)} ${r}`,`printf '%s' "$TS_CLOUD_TAG" > ${r}/.ts-cloud-tag`)}else if(n)a.push(`git -C ${r} init -q`,`git -C ${r} remote add origin ${pe(i)}`,`git -C ${r} fetch -q --depth 1 origin ${pe(n)}`,`git -C ${r} checkout -q FETCH_HEAD`);else a.push(`git clone -q --depth 1 --branch ${pe(s)} ${pe(i)} ${r}`);return a.push(`git -C ${r} rev-parse HEAD > ${r}/.ts-cloud-sha`),a}function pe(e){return`'${e.split("'").join("'\\''")}'`}var fr="$CREATE_RELEASE",gr="$ACTIVATE_RELEASE",Xi="$RESTART_QUEUES",Wi="composer install --no-interaction --prefer-dist --optimize-autoloader --no-dev",zl=["php artisan migrate --force","php artisan config:cache","php artisan route:cache","php artisan view:cache","php artisan event:cache","php artisan storage:link"];function Bl(e){switch(e){case"laravel":case"statamic":return[fr,Wi,...zl,gr,Xi];case"php":case"wordpress":return[fr,`${Wi} || true`,gr];case"static":case"spa":return[fr,gr]}}function Kl(e,t){return e.replace(/^php\s+/,`${t} `).replace(/(\s)php\s+artisan\s+/g,`$1${t} artisan `)}function jl(e,t){let r=Vt(t);return[`cat > ${e} <<'TS_CLOUD_ENV_EOF'`,r,"TS_CLOUD_ENV_EOF",`chmod 600 ${e}`]}function Yi(e,t,r){return[`cat > ${e} <<'${r}'`,t.replace(/\n$/,""),r,`chmod 600 ${e}`]}function Gl(e,t){if(!t)return[];let r=[];if(t.composerAuth){let n=typeof t.composerAuth==="string"?t.composerAuth:JSON.stringify(t.composerAuth,null,2);r.push(...Yi(`${e}/auth.json`,n,"TS_CLOUD_AUTHJSON_EOF"))}if(t.npmrc)r.push(...Yi(`${e}/.npmrc`,t.npmrc,"TS_CLOUD_NPMRC_EOF"));return r}function Ji(e){let t=e.healthCheck?.path;if(!t||!e.domain)return[];let n=`http://127.0.0.1${t.startsWith("/")?t:`/${t}`}`;return[`echo "[ts-cloud] health check ${n} (Host: ${e.domain})"`,"TS_CLOUD_HC_OK=0",`for i in $(seq 1 10); do TS_CLOUD_HC=$(curl -s -o /dev/null -w "%{http_code}" -H "Host: ${e.domain}" -m 10 "${n}" 2>/dev/null || echo 000); case "$TS_CLOUD_HC" in 2*|3*) TS_CLOUD_HC_OK=1; break ;; esac; sleep 3; done`,'[ "$TS_CLOUD_HC_OK" = 1 ] && echo "health check passed ($TS_CLOUD_HC)" || { echo "health check FAILED (last=$TS_CLOUD_HC)" >&2; exit 1; }']}function Zi(e){let{siteName:t,site:r,releaseId:n,commit:s}=e;if(!r.repository?.url)throw Error(`Site '${t}' is a PHP/git site but has no repository.url to clone`);let i=e.appBase??`/var/www/${t}`,a="php",c=Wt(i,n),u=r.sharedPaths??qt,m=[...u,...er(r.env,u)],f=r.keepReleases??$t,v=r.deployScript?.length?r.deployScript:Bl(r.type??"laravel"),S=["set -euo pipefail",'export HOME="${HOME:-/root}"','export COMPOSER_HOME="${COMPOSER_HOME:-/root/.composer}"',"export COMPOSER_ALLOW_SUPERUSER=1",ve()];if(S.push(...Zt(i,{releaseId:n,commit:s,branch:r.repository.branch,keepLogs:f})),S.push(...bt(c,m)),r.env&&Object.keys(r.env).length>0)S.push(...jl(`${c.shared}/.env`,r.env));for(let _ of v){let y=_.trim();if(y===fr)S.push(...Vi({repository:r.repository,releaseDir:c.release,commit:s})),S.push(...Qt(c,m)),S.push(`cd ${c.release}`),S.push(...Gl(c.release,r.credentials)),S.push(`chown -R www-data:www-data ${c.shared}/storage 2>/dev/null || true`,`[ -d ${c.release}/bootstrap/cache ] && chown -R www-data:www-data ${c.release}/bootstrap/cache 2>/dev/null || true`,`chmod -R ug+rwX ${c.shared}/storage 2>/dev/null || true`);else if(y===gr)S.push(...nt(c)),S.push(...st(c,f)),S.push(`(cd ${T} && pantry restart php-fpm) 2>/dev/null || true`);else if(y===Xi)S.push(`${a} artisan queue:restart || true`);else S.push(Kl(_,a))}return S}var hr={mysql:{port:3306,binaries:["mysqld","mysql"]},mariadb:{port:3306,binaries:["mariadbd","mariadb","mysqld"]},postgres:{port:5432,binaries:["postgres","psql"]},redis:{port:6379,binaries:["redis-server","redis-cli"]},memcached:{port:11211,binaries:["memcached"]},meilisearch:{port:7700,binaries:["meilisearch"]},vitess:{port:15306,binaries:["vtgate"]}},It="ts-cloud-service:";function Vl(e){return e===!0||typeof e==="object"&&e!=null}function eo(e){if(!e)return[];return Object.keys(hr).filter((t)=>Vl(e[t]))}function to(e){if(e.length===0)return[];return[ve(),"ts_cloud_port_open() {",' if command -v ss >/dev/null 2>&1; then ss -ltn 2>/dev/null | grep -qE "[:.]$1[[:space:]]" && return 0; fi',' if command -v netstat >/dev/null 2>&1; then netstat -ltn 2>/dev/null | grep -qE "[:.]$1[[:space:]]" && return 0; fi'," (exec 3<>/dev/tcp/127.0.0.1/$1) 2>/dev/null && { exec 3<&- 3>&-; return 0; }"," return 1","}","ts_cloud_probe() {",' TS_CLOUD_SVC="$1"; TS_CLOUD_PORT="$2"; shift 2',' for TS_CLOUD_BIN in "$@"; do',` if command -v "$TS_CLOUD_BIN" >/dev/null 2>&1; then echo "${It}$TS_CLOUD_SVC:present"; return 0; fi`," done",` if ts_cloud_port_open "$TS_CLOUD_PORT"; then echo "${It}$TS_CLOUD_SVC:present"; return 0; fi`,` echo "${It}$TS_CLOUD_SVC:missing"`," return 0","}",...e.filter((t)=>hr[t]).map((t)=>`ts_cloud_probe ${t} ${hr[t].port} ${hr[t].binaries.join(" ")}`),"exit 0"]}function no(e,t){if(!e)return[];let r=new Map;for(let n of e.split(`
419
419
  `)){let s=n.indexOf(It);if(s===-1)continue;let[i,a]=n.slice(s+It.length).trim().split(":");if(i)r.set(i,a)}return t.filter((n)=>r.get(n)==="missing")}function so(e,t,r){let n=r?` on ${r}`:"",s=e.map((a)=>`managedServices.${a}`).join(", "),i=e.length===1?`no ${e[0]}`:`none of ${e.join(", ")}`;return`This project declares ${s}, but '${t}' has ${i}${n}. Attach mode does not provision services on the owner's box, so nothing will install ${e.length===1?"it":"them"}. Point the app at an external service, or ask the owner of '${t}' to add ${e.length===1?"it":"them"} to their own config and re-provision.`}var io="/var/lib/pantry/php-fpm/pool.d",ql=9100,Wl=400;function Sr(e){return(e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"site").slice(0,28)}function oo(e){return`web_${Sr(e)}`}function Yl(e){let t=Sr(e),r=0;for(let n=0;n<t.length;n++)r=r*31+t.charCodeAt(n)>>>0;return ql+r%Wl}function Dn(e){return`127.0.0.1:${Yl(e)}`}function Xl(e){let t=Sr(e.siteName),r=oo(e.siteName),n=e.maxChildren??10;return[`; ts-cloud-managed pool for ${e.siteName} (site isolation)`,`[${t}]`,`user = ${r}`,`group = ${r}`,`listen = ${Dn(e.siteName)}`,"pm = dynamic",`pm.max_children = ${n}`,"pm.start_servers = 2","pm.min_spare_servers = 1","pm.max_spare_servers = 3","pm.max_requests = 500","catch_workers_output = yes",`php_admin_value[open_basedir] = ${e.appBase}:/tmp`,""].join(`
420
- `)}function ao(e){let t=oo(e.siteName),r=Sr(e.siteName),n=`${io}/${r}.conf`;return[`getent group ${t} >/dev/null || groupadd --system ${t}`,`id -u ${t} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin -g ${t} ${t}`,`usermod -aG ${t} www-data 2>/dev/null || true`,`chown -R ${t}:${t} ${e.appBase} || true`,`chmod -R g+rX ${e.appBase} || true`,`chmod 600 ${e.appBase}/shared/.env 2>/dev/null || true`,`mkdir -p ${io}`,`cat > ${n} <<'TS_CLOUD_FPMPOOL_EOF'`,Xl(e).replace(/\n$/,""),"TS_CLOUD_FPMPOOL_EOF",`(cd ${T} && pantry restart php-fpm) 2>/dev/null || true`]}var yr={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};function eu(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function Zs(e,t,r=yr){let{config:n,environment:s,siteName:i,site:a,slug:c,sha:u,runtime:m,localTarballPath:f}=t,v=`releases/${i}/${u}.tar.gz`,S=p(n,s),_=await e.getComputeOutputs({config:n,environment:s}),y=await e.findComputeTargets({slug:c,environment:s,role:"app",stackName:S});if(y.length===0)return{success:!1,error:e.name==="aws"?`Stack '${S}' has no EC2 instances tagged Project=${c} Environment=${s} Role=app, and storage/cloud/state/${S}.json pins no live instance. For a shared box, record its instanceId there.`:`No Hetzner servers labeled ts-cloud/project=${c} ts-cloud/environment=${s} ts-cloud/role=app, and storage/cloud/state/${S}.json pins no live server. For a shared box, record its serverId there.`};let x=_.servicesPrivateIp?Is(_.servicesPrivateIp,g(n)):jn(g(n)),R=Hi(b(n,{environment:s})),E=n.infrastructure?.compute,D=ti(E?.hostCleanup),C=j({...E,proxy:w(n,{environment:s})})?{HOST:"127.0.0.1"}:{},P=s==="production"?{APP_ENV:"production",NODE_ENV:"production"}:{},L={...x,...R,...C,...a.env||{},...P},O=on(L,a.sharedPaths??[]);if(O.warning)r.warn(`Site '${i}': ${O.warning}`);else if(O.path)r.info(`Site '${i}': sharing '${O.path}' so the SQLite database survives deploys.`);if(Gr(a)){let H=a.phpVersion??E?.php?.default??E?.php?.versions?.[0],V=U(c,i),A=Object.keys(x).length>0?{...a,env:L}:a,q=Zi({siteName:i,site:A,releaseId:u,appBase:V,defaultPhpVersion:H}),W=!j(E),Ee=On(a)==="custom"&&a.ssl?.certPath&&a.ssl?.keyPath?{certPath:a.ssl.certPath,keyPath:a.ssl.keyPath}:void 0,dt=a.isolation?ao({siteName:i,appBase:V}):[],Tr=W?qr({siteName:i,domain:a.domain||i,aliases:a.aliases,type:a.type,appDir:`${V}/current`,webDirectory:a.webDirectory,phpVersion:H,fastcgiPass:a.isolation?Dn(i):void 0,redirects:a.redirects,ssl:Ee,auth:a.auth&&a.auth.enabled!==!1&&a.auth.password?{username:a.auth.username||"admin",password:a.auth.password,realm:a.auth.realm}:void 0,serverSnippet:Vr(a.nginx,E?.nginxTemplates),clientMaxBodySize:a.nginx?.clientMaxBodySize,hsts:a.ssl?.hsts,tlsProtocols:a.ssl?.tlsProtocols,security:a.security}):[],gt=W?Rn(a):[],po=En(a)?Pn({slug:c,siteName:i,site:a,phpVersion:H,appBase:V}):[],mo=W?Ji(a):[];r.step(`Deploying PHP site '${i}' to ${y.length} target(s)...`);let Ae=await e.runRemoteDeploy({targets:y,commands:[...sn(V,c),...q,...dt,...Tr,...gt,...po,...mo,...D],comment:`ts-cloud deploy ${c}/${i}@${u}`,tags:{Project:c,Environment:s,Role:"app"}}),In=es(n.notifications,a.notifications);if(!Ae.success)return await co(e,y,D,r),await Yr(In,"deploy-failed",`❌ Deploy of ${c}/${i}@${u} failed: ${Ae.error||"unknown error"}`),{success:!1,error:Ae.error||"Remote PHP deploy failed",instanceCount:Ae.instanceCount,perInstance:Ae.perInstance};let fo=a.domain?` → https://${a.domain}`:"";return await Yr(In,"deploy",`✅ Deployed ${c}/${i}@${u}${fo}`),{success:!0,instanceCount:Ae.instanceCount,perInstance:Ae.perInstance}}if(!f)return{success:!1,error:`Site '${i}' requires a release tarball but none was provided`};let I=await e.uploadRelease({config:n,environment:s,localPath:f,remoteKey:v,targets:y}),N=si(c,i,u),oe=e.name==="aws"?Nc(_.deployBucketName,v,n.project.region||"us-east-1",N):kc(I.artifactRef,N),de=d(a),k=U(c,i),re=de==="server-static"?ii({siteName:i,slug:c,appDir:k,artifactFetch:oe,releaseId:u,preStartCommands:a.preStart}):ni({siteName:i,slug:c,appDir:k,artifactFetch:oe,releaseId:u,execStart:ri(a.start,m,`${k.replace(/\/+$/,"")}/releases/%i`),envEntries:L,port:a.port,preStartCommands:a.preStart,sharedPaths:a.sharedPaths,zeroDowntime:a.zeroDowntime!==!1,healthCheckPath:a.healthCheck?.path,liveness:a.liveness,memoryHigh:a.memoryHigh,memoryMax:a.memoryMax,cpuWeight:a.cpuWeight,ioWeight:a.ioWeight,tasksMax:a.tasksMax,stopTimeout:a.stopTimeout}),Y=de==="server-static"&&!j(E)&&!!a.domain,K=Y?qr({siteName:i,domain:a.domain,aliases:a.aliases,type:a.type==="spa"?"spa":"static",appDir:`${k}/current`,webDirectory:"",redirects:a.redirects,auth:a.auth&&a.auth.enabled!==!1&&a.auth.password?{username:a.auth.username||"admin",password:a.auth.password,realm:a.auth.realm}:void 0,serverSnippet:Vr(a.nginx,E?.nginxTemplates),clientMaxBodySize:a.nginx?.clientMaxBodySize,hsts:a.ssl?.hsts,tlsProtocols:a.ssl?.tlsProtocols,security:a.security}):[],me=Y?Rn(a):[],Ce=En(a)?Pn({slug:c,siteName:i,site:a,appBase:k}):[],Ie=[...Zt(k,{releaseId:u,commit:u,branch:a.repository?.branch??"main"}),...sn(k,c),...re,...K,...me,...Ce,...D];r.step(`Deploying to ${y.length} target(s)...`);let ae=await e.runRemoteDeploy({targets:y,commands:Ie,comment:`ts-cloud deploy ${c}/${i}@${u}`,tags:{Project:c,Environment:s,Role:"app"}});if(!ae.success)return await co(e,y,D,r),{success:!1,error:ae.error||"Remote deploy failed",instanceCount:ae.instanceCount,perInstance:ae.perInstance};return{success:!0,instanceCount:ae.instanceCount,perInstance:ae.perInstance}}async function co(e,t,r,n){if(r.length===0)return;try{let s=await e.runRemoteDeploy({targets:t,commands:r,comment:"ts-cloud host cleanup after failed deploy"});if(!s.success)n.warn(`Host cleanup after the failed deploy did not complete: ${s.error||"unknown error"}`)}catch(s){n.warn(`Host cleanup after the failed deploy did not run: ${s.message}`)}}function vr(e){return`'${e.replaceAll("'","'\\''")}'`}function tu(e,t,r=!1,n=[]){let s=`${e}-dashboard-`,i=t.map((c)=>`${e}-${c}.service`),a=r?[`export TS_CLOUD_DASHBOARD_KEEP_DOMAINS=${vr(JSON.stringify(n))}`,"rm -f /run/ts-cloud-dashboard-routes-changed",`/usr/local/bin/bun --bun -e ${vr(`
420
+ `)}function ao(e){let t=oo(e.siteName),r=Sr(e.siteName),n=`${io}/${r}.conf`;return[`getent group ${t} >/dev/null || groupadd --system ${t}`,`id -u ${t} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin -g ${t} ${t}`,`usermod -aG ${t} www-data 2>/dev/null || true`,`chown -R ${t}:${t} ${e.appBase} || true`,`chmod -R g+rX ${e.appBase} || true`,`chmod 600 ${e.appBase}/shared/.env 2>/dev/null || true`,`mkdir -p ${io}`,`cat > ${n} <<'TS_CLOUD_FPMPOOL_EOF'`,Xl(e).replace(/\n$/,""),"TS_CLOUD_FPMPOOL_EOF",`(cd ${T} && pantry restart php-fpm) 2>/dev/null || true`]}var yr={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};function eu(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function Zs(e,t,r=yr){let{config:n,environment:s,siteName:i,site:a,slug:c,sha:u,runtime:m,localTarballPath:f}=t,v=`releases/${i}/${u}.tar.gz`,S=p(n,s),_=await e.getComputeOutputs({config:n,environment:s}),y=await e.findComputeTargets({slug:c,environment:s,role:"app",stackName:S});if(y.length===0)return{success:!1,error:e.name==="aws"?`Stack '${S}' has no EC2 instances tagged Project=${c} Environment=${s} Role=app, and storage/cloud/state/${S}.json pins no live instance. For a shared box, record its instanceId there.`:`No Hetzner servers labeled ts-cloud/project=${c} ts-cloud/environment=${s} ts-cloud/role=app, and storage/cloud/state/${S}.json pins no live server. For a shared box, record its serverId there.`};let x=_.servicesPrivateIp?Is(_.servicesPrivateIp,g(n)):jn(g(n)),R=Hi(b(n,{environment:s})),E=n.infrastructure?.compute,D=ti(E?.hostCleanup),C=j({...E,proxy:w(n,{environment:s})})?{HOST:"127.0.0.1"}:{},P=s==="production"?{APP_ENV:"production",NODE_ENV:"production"}:{},L={...x,...R,...C,...a.env||{},...P},O=on(L,a.sharedPaths??[]);if(O.warning)r.warn(`Site '${i}': ${O.warning}`);else if(O.path)r.info(`Site '${i}': sharing '${O.path}' so the SQLite database survives deploys.`);if(Gr(a)){let H=a.phpVersion??E?.php?.default??E?.php?.versions?.[0],V=U(c,i),A=Object.keys(x).length>0?{...a,env:L}:a,q=Zi({siteName:i,site:A,releaseId:u,appBase:V,defaultPhpVersion:H}),W=!j(E),Ee=On(a)==="custom"&&a.ssl?.certPath&&a.ssl?.keyPath?{certPath:a.ssl.certPath,keyPath:a.ssl.keyPath}:void 0,dt=a.isolation?ao({siteName:i,appBase:V}):[],Tr=W?qr({siteName:i,domain:a.domain||i,aliases:a.aliases,type:a.type,appDir:`${V}/current`,webDirectory:a.webDirectory,phpVersion:H,fastcgiPass:a.isolation?Dn(i):void 0,redirects:a.redirects,ssl:Ee,auth:a.auth&&a.auth.enabled!==!1&&a.auth.password?{username:a.auth.username||"admin",password:a.auth.password,realm:a.auth.realm}:void 0,serverSnippet:Vr(a.nginx,E?.nginxTemplates),clientMaxBodySize:a.nginx?.clientMaxBodySize,hsts:a.ssl?.hsts,tlsProtocols:a.ssl?.tlsProtocols,security:a.security}):[],gt=W?Rn(a):[],po=En(a)?Pn({slug:c,siteName:i,site:a,phpVersion:H,appBase:V}):[],mo=W?Ji(a):[];r.step(`Deploying PHP site '${i}' to ${y.length} target(s)...`);let Le=await e.runRemoteDeploy({targets:y,commands:[...sn(V,c),...q,...dt,...Tr,...gt,...po,...mo,...D],comment:`ts-cloud deploy ${c}/${i}@${u}`,tags:{Project:c,Environment:s,Role:"app"}}),In=es(n.notifications,a.notifications);if(!Le.success)return await co(e,y,D,r),await Yr(In,"deploy-failed",`❌ Deploy of ${c}/${i}@${u} failed: ${Le.error||"unknown error"}`),{success:!1,error:Le.error||"Remote PHP deploy failed",instanceCount:Le.instanceCount,perInstance:Le.perInstance};let fo=a.domain?` → https://${a.domain}`:"";return await Yr(In,"deploy",`✅ Deployed ${c}/${i}@${u}${fo}`),{success:!0,instanceCount:Le.instanceCount,perInstance:Le.perInstance}}if(!f)return{success:!1,error:`Site '${i}' requires a release tarball but none was provided`};let I=await e.uploadRelease({config:n,environment:s,localPath:f,remoteKey:v,targets:y}),N=si(c,i,u),oe=e.name==="aws"?Nc(_.deployBucketName,v,n.project.region||"us-east-1",N):kc(I.artifactRef,N),de=d(a),k=U(c,i),re=de==="server-static"?ii({siteName:i,slug:c,appDir:k,artifactFetch:oe,releaseId:u,preStartCommands:a.preStart}):ni({siteName:i,slug:c,appDir:k,artifactFetch:oe,releaseId:u,execStart:ri(a.start,m,`${k.replace(/\/+$/,"")}/releases/%i`),envEntries:L,port:a.port,preStartCommands:a.preStart,sharedPaths:a.sharedPaths,zeroDowntime:a.zeroDowntime!==!1,healthCheckPath:a.healthCheck?.path,liveness:a.liveness,memoryHigh:a.memoryHigh,memoryMax:a.memoryMax,cpuWeight:a.cpuWeight,ioWeight:a.ioWeight,tasksMax:a.tasksMax,stopTimeout:a.stopTimeout}),Y=de==="server-static"&&!j(E)&&!!a.domain,K=Y?qr({siteName:i,domain:a.domain,aliases:a.aliases,type:a.type==="spa"?"spa":"static",appDir:`${k}/current`,webDirectory:"",redirects:a.redirects,auth:a.auth&&a.auth.enabled!==!1&&a.auth.password?{username:a.auth.username||"admin",password:a.auth.password,realm:a.auth.realm}:void 0,serverSnippet:Vr(a.nginx,E?.nginxTemplates),clientMaxBodySize:a.nginx?.clientMaxBodySize,hsts:a.ssl?.hsts,tlsProtocols:a.ssl?.tlsProtocols,security:a.security}):[],me=Y?Rn(a):[],Ce=En(a)?Pn({slug:c,siteName:i,site:a,appBase:k}):[],Ae=[...Zt(k,{releaseId:u,commit:u,branch:a.repository?.branch??"main"}),...sn(k,c),...re,...K,...me,...Ce,...D];r.step(`Deploying to ${y.length} target(s)...`);let ae=await e.runRemoteDeploy({targets:y,commands:Ae,comment:`ts-cloud deploy ${c}/${i}@${u}`,tags:{Project:c,Environment:s,Role:"app"}});if(!ae.success)return await co(e,y,D,r),{success:!1,error:ae.error||"Remote deploy failed",instanceCount:ae.instanceCount,perInstance:ae.perInstance};return{success:!0,instanceCount:ae.instanceCount,perInstance:ae.perInstance}}async function co(e,t,r,n){if(r.length===0)return;try{let s=await e.runRemoteDeploy({targets:t,commands:r,comment:"ts-cloud host cleanup after failed deploy"});if(!s.success)n.warn(`Host cleanup after the failed deploy did not complete: ${s.error||"unknown error"}`)}catch(s){n.warn(`Host cleanup after the failed deploy did not run: ${s.message}`)}}function vr(e){return`'${e.replaceAll("'","'\\''")}'`}function tu(e,t,r=!1,n=[]){let s=`${e}-dashboard-`,i=t.map((c)=>`${e}-${c}.service`),a=r?[`export TS_CLOUD_DASHBOARD_KEEP_DOMAINS=${vr(JSON.stringify(n))}`,"rm -f /run/ts-cloud-dashboard-routes-changed",`/usr/local/bin/bun --bun -e ${vr(`
421
421
  const { chmodSync, existsSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } = require('node:fs')
422
422
  const { basename, join } = require('node:path')
423
423
  const root = '/etc/rpx/sites.d'