@stacksjs/ts-cloud 0.16.88 → 0.16.89

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-9993sjym.js → chunk-a66hyvc3.js} +1 -1
  2. package/dist/bin/{chunk-awvhkc81.js → chunk-deptcjq9.js} +1 -1
  3. package/dist/bin/{chunk-4rgwcv9n.js → chunk-h6xne9s6.js} +26 -26
  4. package/dist/bin/cli.js +4 -4
  5. package/dist/bin/dashboard-server.js +1 -1
  6. package/dist/{chunk-vxx89c13.js → chunk-7xy7bsyx.js} +11 -11
  7. package/dist/{chunk-4p9kv2bz.js → chunk-bvywngfv.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 +2 -2
  16. package/dist/ui/applications/compose.html +6 -6
  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 +6 -6
  23. package/dist/ui/integrations.html +2 -2
  24. package/dist/ui/operations/alerts.html +5 -5
  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 +5 -5
  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 +5 -5
  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 +6 -6
  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 +5 -5
  39. package/dist/ui/server/database.html +6 -6
  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 +2 -2
  47. package/dist/ui/server/services.html +1 -1
  48. package/dist/ui/server/sites.html +6 -6
  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 +2 -2
  57. package/dist/ui/serverless/firewall.html +2 -2
  58. package/dist/ui/serverless/functions.html +5 -5
  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 +6 -6
  64. package/dist/ui/serverless.html +5 -5
  65. package/package.json +3 -3
@@ -9,7 +9,7 @@ ${ta(c)}`:f}),s=r.length-n.length,i=s>0?[`(+${s} more instance${s===1?"":"s"} fa
9
9
  `)}function ra(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 Og(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((f)=>`mx: ${f}`),`max_age: ${s}`].join(`\r
10
10
  `)}\r
11
11
  `,c=ra(a);return{host:`mta-sts.${t}`,body:a,id:c,txt:`v=STSv1; id=${c}`}}var _g=8461;function Fh(e,t=_g){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 Dt={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 u="/opt/pantry";function Ot(e){return`'${e.split("'").join("'\\''")}'`}function ht(e={}){let t=e.installDir??"/usr/local/bin",r=e.version?`export PANTRY_VERSION=${Ot(e.version)}`:'export PANTRY_VERSION="${PANTRY_VERSION:-latest}"';return["export DEBIAN_FRONTEND=noninteractive","export PANTRY_SERVICE_SCOPE=system",`export PANTRY_INSTALL_DIR=${t}`,r,"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}"; mkdir -p ${t}; unzip -o "\${TMP}/\${ZIP}" -d ${t}; chmod +x ${t}/pantry; rm -rf "\${TMP}"`,`export PATH="${t}:$PATH"`,"mkdir -p /opt/pantry"]}function Re(){return'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true'}function De(e){if(e.length===0)return[];let t=[...new Set(e)],r=new Set(["/opt/pantry","/opt/pantry/pantry"]);for(let s of t){let i="/opt/pantry/pantry";for(let a of s.split("@")[0].split("/")){if(!/^[a-zA-Z0-9._-]+$/.test(a))throw Error("Invalid pantry package domain");i+=`/${a}`,r.add(i)}}let n=[...r].map(Ot).join(" ");return[`(umask 022; mkdir -p ${n} && chmod 0755 ${n} && cd /opt/pantry && pantry install ${t.map(Ot).join(" ")})`]}function sr(e){return[...new Set(e)].flatMap((t)=>[`(cd /opt/pantry && pantry start ${Ot(t)})`,`(cd /opt/pantry && pantry enable ${Ot(t)})`])}var fe="/etc/mail",Oe="mail-server",rn="mail",nn=`${u}/pantry/.bin`;function xe(e){return`'${String(e).split("'").join("'\\''")}'`}function Xe(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function na(e){return[e.version?`${Dt.mail}@${e.version}`:Dt.mail]}function sn(e,t){return`${fe}/dkim/${t}.${e.dkim.selector}.pem`}function os(e){return`${e.storagePath}/smtp.db`}function sa(e){let t=["# Generated by ts-cloud. Edits are overwritten on the next deploy —","# change `services.mail` in the cloud config instead.","","[server]",`host = ${Xe(e.bindAddress)}`,`port = ${e.ports.smtp}`,`hostname = ${Xe(e.hostname)}`];if(e.domains.length>0)t.push(`local_domains = ${Xe(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 = ${Xe(e.tls.certPath)}`);if(e.tls.keyPath)t.push(`key_path = ${Xe(e.tls.keyPath)}`);if(t.push("","[auth]",`enabled = ${e.mode==="server"}`,"","[antispam]",`dnsbl = ${e.spam.dnsbl}`,`dnsbl_reject = ${e.spam.dnsblReject}`,`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 = ${Xe(e.tls.acmeEmail)}`);if(t.push("","[webhook]",`enabled = ${!!e.webhookUrl}`),e.webhookUrl)t.push(`url = ${Xe(e.webhookUrl)}`);return t.push(""),t.join(`
12
+ `)}var Dt={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 u="/opt/pantry";function Ot(e){return`'${e.split("'").join("'\\''")}'`}function ht(e={}){let t=e.installDir??"/usr/local/bin",r=e.version?`export PANTRY_VERSION=${Ot(e.version)}`:'export PANTRY_VERSION="${PANTRY_VERSION:-latest}"';return["export DEBIAN_FRONTEND=noninteractive","export PANTRY_SERVICE_SCOPE=system",`export PANTRY_INSTALL_DIR=${t}`,r,"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}"; mkdir -p ${t}; unzip -o "\${TMP}/\${ZIP}" -d ${t}; chmod +x ${t}/pantry; rm -rf "\${TMP}"`,`export PATH="${t}:$PATH"`,"mkdir -p /opt/pantry"]}function Re(){return'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true'}function De(e){if(e.length===0)return[];let t=[...new Set(e)],r=new Set(["/opt/pantry","/opt/pantry/pantry"]);for(let s of t){let i="/opt/pantry/pantry";for(let a of s.split("@")[0].split("/")){if(!/^[a-zA-Z0-9._-]+$/.test(a))throw Error("Invalid pantry package domain");i+=`/${a}`,r.add(i)}}let n=[...r].map(Ot).join(" ");return[`(umask 022; mkdir -p ${n} && chmod 0755 ${n} && cd /opt/pantry && pantry install ${t.map(Ot).join(" ")})`]}function sr(e){return[...new Set(e)].flatMap((t)=>[`(cd /opt/pantry && pantry start ${Ot(t)})`,`(cd /opt/pantry && pantry enable ${Ot(t)})`])}var fe="/etc/mail",Oe="mail-server",rn="mail",nn=`${u}/pantry/.bin`;function xe(e){return`'${String(e).split("'").join("'\\''")}'`}function Ye(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function na(e){return[e.version?`${Dt.mail}@${e.version}`:Dt.mail]}function sn(e,t){return`${fe}/dkim/${t}.${e.dkim.selector}.pem`}function os(e){return`${e.storagePath}/smtp.db`}function sa(e){let t=["# Generated by ts-cloud. Edits are overwritten on the next deploy —","# change `services.mail` in the cloud config instead.","","[server]",`host = ${Ye(e.bindAddress)}`,`port = ${e.ports.smtp}`,`hostname = ${Ye(e.hostname)}`];if(e.domains.length>0)t.push(`local_domains = ${Ye(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 = ${Ye(e.tls.certPath)}`);if(e.tls.keyPath)t.push(`key_path = ${Ye(e.tls.keyPath)}`);if(t.push("","[auth]",`enabled = ${e.mode==="server"}`,"","[antispam]",`dnsbl = ${e.spam.dnsbl}`,`dnsbl_reject = ${e.spam.dnsblReject}`,`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 = ${Ye(e.tls.acmeEmail)}`);if(t.push("","[webhook]",`enabled = ${!!e.webhookUrl}`),e.webhookUrl)t.push(`url = ${Ye(e.webhookUrl)}`);return t.push(""),t.join(`
13
13
  `)}function oa(e){let t=["# Generated by ts-cloud. See /etc/mail/config.toml for the rest.",`SMTP_HOSTNAME=${e.hostname}`,`SMTP_DB_PATH=${os(e)}`,`SMTP_DNSBL_REJECT=${e.spam.dnsblReject}`,`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=e.domains.find((s)=>s!==e.hostname)||e.hostname,n=e.domains.filter((s)=>s!==r);if(t.push(`DKIM_DOMAIN=${r}`,`DKIM_SELECTOR=${e.dkim.selector}`,`DKIM_PRIVATE_KEY_PATH=${sn(e,r)}`),n.length>0){let s=n.map((i)=>`${i}:${e.dkim.selector}:${sn(e,i)}`);t.push(`DKIM_EXTRA_KEYS=${s.join(",")}`)}}return t.push(""),t.join(`
14
14
  `)}function ia(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=${Oe}`,`Group=${Oe}`,`WorkingDirectory=${e.storagePath}`,`EnvironmentFile=${fe}/mail.env`,...e.tls.systemCredentials?[`LoadCredential=server.crt:${e.tls.systemCredentials.certPath}`,`LoadCredential=server.key:${e.tls.systemCredentials.keyPath}`]:[],`Environment="PATH=${nn}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"`,`ExecStart=${nn}/mail serve --config ${fe}/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} ${fe}`,"","[Install]","WantedBy=multi-user.target",""].join(`
15
15
  `)}function aa(e){if(!e.dkim.enabled||e.domains.length===0)return[];let t=[`mkdir -p ${fe}/dkim`];for(let r of e.domains){let n=sn(e,r);t.push(`if [ ! -f ${xe(n)} ]; then openssl genrsa -out ${xe(n)} 2048; fi`,`chmod 0600 ${xe(n)}`,`echo "DKIM ${e.dkim.selector}._domainkey.${r} IN TXT v=DKIM1; k=rsa; p=$(openssl rsa -in ${xe(n)} -pubout -outform PEM 2>/dev/null | grep -v '^-----' | tr -d '\\n')"`)}return t.push(`chown -R ${Oe}:${Oe} ${fe}/dkim`),t}function ca(e){if(e.accounts.length===0)return[];let t=(r)=>`runuser -u ${Oe} -- env SMTP_DB_PATH="$TS_CLOUD_MAIL_DB" ${nn}/mail user:local ${r}`;return e.accounts.flatMap((r)=>[t(`create ${xe(r.address)} ${xe(r.password)} ${xe(r.address)}`),...r.passwordPolicy==="managed"?[t(`change-password ${xe(r.address)} ${xe(r.password)}`)]:[]])}function or(e){if(!e.enabled)return[];return[...De(na(e)),`id -u ${Oe} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin ${Oe}`,`mkdir -p ${e.storagePath} ${fe}`,`chown root:${Oe} ${fe}`,`chmod 0750 ${fe}`,`chown -R ${Oe}:${Oe} ${e.storagePath}`,`TS_CLOUD_MAIL_DB="$(grep -sE '^SMTP_DB_PATH=' ${fe}/mail.env | head -1 | cut -d= -f2- || true)"`,`[ -n "$TS_CLOUD_MAIL_DB" ] || TS_CLOUD_MAIL_DB=${xe(os(e))}`,`cat > ${fe}/config.toml <<'TS_CLOUD_MAIL_CONF_EOF'`,sa(e),"TS_CLOUD_MAIL_CONF_EOF",`cat > ${fe}/mail.env <<'TS_CLOUD_MAIL_ENV_EOF'`,oa(e),"TS_CLOUD_MAIL_ENV_EOF",`sed -i "s|^SMTP_DB_PATH=.*|SMTP_DB_PATH=$TS_CLOUD_MAIL_DB|" ${fe}/mail.env`,`chmod 0640 ${fe}/mail.env ${fe}/config.toml`,`chown root:${Oe} ${fe}/mail.env ${fe}/config.toml`,...aa(e),`cat > /etc/systemd/system/${rn}.service <<'TS_CLOUD_MAIL_UNIT_EOF'`,ia(e),"TS_CLOUD_MAIL_UNIT_EOF",...e.tls.systemCredentials?["cat > /etc/systemd/system/ts-cloud-mail-tls.path <<'TS_CLOUD_MAIL_TLS_PATH'","[Unit]","Description=Refresh mail after gateway certificate renewal","[Path]",`PathChanged=${e.tls.systemCredentials.certPath}`,`PathChanged=${e.tls.systemCredentials.keyPath}`,"Unit=ts-cloud-mail-tls.service","[Install]","WantedBy=multi-user.target","TS_CLOUD_MAIL_TLS_PATH","cat > /etc/systemd/system/ts-cloud-mail-tls.service <<'TS_CLOUD_MAIL_TLS_UNIT'","[Unit]","Description=Load renewed mail TLS credentials","[Service]","Type=oneshot","ExecStart=/usr/bin/systemctl restart mail.service","TS_CLOUD_MAIL_TLS_UNIT"]:["systemctl disable --now ts-cloud-mail-tls.path 2>/dev/null || true"],"systemctl daemon-reload",...e.tls.systemCredentials?["systemctl enable --now ts-cloud-mail-tls.path"]:[],`systemctl enable ${rn}`,`systemctl restart ${rn}`,...ca(e)]}var we=`${u}/pantry/.bin`,cn=15306,on=15991,ir=15999,is=16101,ar=2379,Ae="/var/lib/vitess",ln=100;function Lt(e){return e===!0||typeof e==="object"&&e!==null}function la(e){return typeof e==="object"&&e!==null?e:{}}function pe(e){return`'${String(e).split("'").join("'\\''")}'`}function ua(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 ye="vitess",pa=`${we}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`,us="/usr/local/lib/vitess",pn=new Map;function an(e){return`${us}/${e}.sh`}function it(e,t){return pn.set(e,da(t)),`/bin/sh ${an(e)}`}function as(){let e=[`mkdir -p ${us}`];for(let[t,r]of pn)e.push(`cat > ${an(t)} <<'TS_CLOUD_VITESS_LAUNCHER_EOF'`,r,"TS_CLOUD_VITESS_LAUNCHER_EOF",`chmod 0755 ${an(t)}`);return e}function da(e){return["#!/bin/sh","set -e",`cd ${u}`,`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 ${we}/mysqld 2>/dev/null)")")"`,`VTROOT="$(dirname "$(dirname "$(readlink -f ${we}/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,9 +24,9 @@ EOF`,'DISK_PCT=0; DISK_ALERTS=""; ALERT_KEY=""',..._,"UPTIME_SEC=$(cut -d' ' -f1
24
24
  `)}
25
25
  `}return`${["server {"," listen 80;"," listen [::]:80;",` server_name ${r};`,...n,"}"].join(`
26
26
  `)}
27
- `}function hn(e){let t=`/etc/nginx/sites-available/${e.siteName}`,r=`/etc/nginx/sites-enabled/${e.siteName}`,n=Ba(e),s=[...gn()];if(e.auth){let i=gs(e.siteName),a=(h)=>h.split("'").join("'\\''"),c=a(e.auth.password),f=a(e.auth.username);s.push(`TS_CLOUD_HTPASS=$(openssl passwd -apr1 '${c}')`,`printf '%s:%s\\n' '${f}' "$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",`${Fe} -t`,"systemctl reload ts-cloud-nginx 2>/dev/null || systemctl restart ts-cloud-nginx 2>/dev/null || true"),s}var Fe="/usr/local/bin/ts-cloud-nginx";function gn(e="/opt/pantry"){return[...ht(),...De(["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 > ${Fe} <<'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 ${Fe}`,"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=${Fe} -t`,`ExecStart=${Fe} -g 'daemon off;'`,`ExecReload=${Fe} -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"]}import{readFileSync as Ka}from"node:fs";function ja(e){if(typeof e==="string")return e;if(!/^\/[\w./-]+$/.test(e.envFile)||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e.variable))throw Error("Invalid notification env-file reference");let r=Ka(e.envFile,"utf8").split(/\r?\n/).map((n)=>n.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/)).find((n)=>n?.[1]===e.variable)?.[2];if(!r)throw Error(`Notification variable ${e.variable} is missing`);return r.replace(/^(['"])(.*)\1$/,"$2")}function Ht(e,t){return!e.events||e.events.includes(t)}async function Sn(e,t,r,n={}){if(!e)return[];let s=n.fetchImpl??globalThis.fetch,i=[],a=[],c=async(f,h)=>{try{return await s(ja(f),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h)})}catch{return}};if(e.slack?.webhookUrl&&Ht(e,t))i.push("slack"),a.push(c(e.slack.webhookUrl,{text:r}));if(e.discord?.webhookUrl&&Ht(e,t))i.push("discord"),a.push(c(e.discord.webhookUrl,{content:r}));if(e.telegram?.botToken&&e.telegram.chatId&&Ht(e,t)){i.push("telegram");let f=`https://api.telegram.org/bot${e.telegram.botToken}/sendMessage`;a.push(c(f,{chat_id:e.telegram.chatId,text:r}))}if(e.webhook?.url&&Ht(e,t))if(i.push("webhook"),(e.webhook.method||"POST")==="GET"){let f=e.webhook.url.includes("?")?"&":"?",h=`${e.webhook.url}${f}event=${encodeURIComponent(t)}&message=${encodeURIComponent(r)}`;a.push(s(h,{method:"GET"}).catch(()=>{return}))}else a.push(c(e.webhook.url,{event:t,message:r}));if(e.email?.to&&Ht(e,t))i.push("email"),a.push(Ga(e.email,t,r));return await Promise.all(a),i}async function Ga(e,t,r){try{let n=await import("./chunk-ncet7ba7.js");await n.email.send({to:e.to,from:e.from,subject:`[ts-cloud] ${t}`,text:r})}catch{}}function Ss(e,t){return t??e}function Je(e){if(!e)return[];let t=(s)=>"'"+s.replaceAll("'",`'"'"'`)+"'",r=(s)=>{if(typeof s==="string")return t(s);if(!/^\/[\w./-]+$/.test(s.envFile)||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(s.variable))throw Error("Invalid notification env-file reference");return'"$(read_env '+t(s.envFile)+" "+t(s.variable)+')"'},n=[];for(let[s,i]of[["slack","text"],["discord","content"]]){let a=e[s]?.webhookUrl;if(a)n.push("URL="+r(a),'post "$URL" '+t(i))}if(e.telegram?.botToken&&e.telegram.chatId)n.push("curl -fsS --max-time 30 -X POST "+t("https://api.telegram.org/bot"+e.telegram.botToken+"/sendMessage")+" --data-urlencode "+t("chat_id="+e.telegram.chatId)+' --data-urlencode "text=$MSG" >/dev/null || FAILED=1');if(e.webhook?.url)if(e.webhook.method==="GET")n.push("curl -fsS --max-time 30 -G "+t(e.webhook.url)+' --data-urlencode "message=$MSG" >/dev/null || FAILED=1');else n.push("post "+t(e.webhook.url)+" message");if(!n.length)return[];return["cat > /usr/local/bin/ts-cloud-notify.new <<'TS_CLOUD_NOTIFY_EOF'","#!/bin/bash","set -uo pipefail",'MSG="${1:-}"; FAILED=0',String.raw`read_env(){ awk -v key="$2" '$0 ~ "^[[:space:]]*(export[[:space:]]+)?" key "[[:space:]]*=" { sub("^[^=]*=[[:space:]]*", ""); sub(/[\r[:space:]]+$/, ""); if (($0 ~ /^".*"$/) || ($0 ~ /^\047.*\047$/)) $0=substr($0,2,length($0)-2); print; exit }' "$1"; }`,String.raw`ESCAPED=$(printf %s "$MSG" | LC_ALL=C awk 'BEGIN{ORS=""; for(i=1;i<32;i++) esc[sprintf("%c",i)]=sprintf("\\u%04x",i)} {if(NR>1) printf "\\n"; for(i=1;i<=length($0);i++){ c=substr($0,i,1); if(c=="\\") printf "\\\\"; else if(c=="\"") printf "\\\""; else if(c in esc) printf "%s",esc[c]; else printf "%s",c }}')`,String.raw`post(){ if [ -z "$1" ]; then FAILED=1; return; fi; curl -fsS --max-time 30 -X POST -H 'Content-Type: application/json' --data "{\"$2\":\"$ESCAPED\"}" "$1" >/dev/null || FAILED=1; }`,...n,'exit "$FAILED"',"TS_CLOUD_NOTIFY_EOF","chmod 0700 /usr/local/bin/ts-cloud-notify.new","mv -f /usr/local/bin/ts-cloud-notify.new /usr/local/bin/ts-cloud-notify"]}function lt(e=[],t={}){let r=t.path??"/root/.ssh/authorized_keys",s=[`mkdir -p ${r.replace(/\/[^/]*$/,"")}`,`touch ${r}`,`sed -i '/^${_s("# >>> ts-cloud managed keys >>>")}$/,/^${_s("# <<< 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(`
27
+ `}function hn(e){let t=`/etc/nginx/sites-available/${e.siteName}`,r=`/etc/nginx/sites-enabled/${e.siteName}`,n=Ba(e),s=[...gn()];if(e.auth){let i=gs(e.siteName),a=(h)=>h.split("'").join("'\\''"),c=a(e.auth.password),f=a(e.auth.username);s.push(`TS_CLOUD_HTPASS=$(openssl passwd -apr1 '${c}')`,`printf '%s:%s\\n' '${f}' "$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",`${Fe} -t`,"systemctl reload ts-cloud-nginx 2>/dev/null || systemctl restart ts-cloud-nginx 2>/dev/null || true"),s}var Fe="/usr/local/bin/ts-cloud-nginx";function gn(e="/opt/pantry"){return[...ht(),...De(["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 > ${Fe} <<'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 ${Fe}`,"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=${Fe} -t`,`ExecStart=${Fe} -g 'daemon off;'`,`ExecReload=${Fe} -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"]}import{readFileSync as Ka}from"node:fs";function ja(e){if(typeof e==="string")return e;if(!/^\/[\w./-]+$/.test(e.envFile)||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e.variable))throw Error("Invalid notification env-file reference");let r=Ka(e.envFile,"utf8").split(/\r?\n/).map((n)=>n.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/)).find((n)=>n?.[1]===e.variable)?.[2];if(!r)throw Error(`Notification variable ${e.variable} is missing`);return r.replace(/^(['"])(.*)\1$/,"$2")}function Ht(e,t){return!e.events||e.events.includes(t)}async function Sn(e,t,r,n={}){if(!e)return[];let s=n.fetchImpl??globalThis.fetch,i=[],a=[],c=async(f,h)=>{try{return await s(ja(f),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h)})}catch{return}};if(e.slack?.webhookUrl&&Ht(e,t))i.push("slack"),a.push(c(e.slack.webhookUrl,{text:r}));if(e.discord?.webhookUrl&&Ht(e,t))i.push("discord"),a.push(c(e.discord.webhookUrl,{content:r}));if(e.telegram?.botToken&&e.telegram.chatId&&Ht(e,t)){i.push("telegram");let f=`https://api.telegram.org/bot${e.telegram.botToken}/sendMessage`;a.push(c(f,{chat_id:e.telegram.chatId,text:r}))}if(e.webhook?.url&&Ht(e,t))if(i.push("webhook"),(e.webhook.method||"POST")==="GET"){let f=e.webhook.url.includes("?")?"&":"?",h=`${e.webhook.url}${f}event=${encodeURIComponent(t)}&message=${encodeURIComponent(r)}`;a.push(s(h,{method:"GET"}).catch(()=>{return}))}else a.push(c(e.webhook.url,{event:t,message:r}));if(e.email?.to&&Ht(e,t))i.push("email"),a.push(Ga(e.email,t,r));return await Promise.all(a),i}async function Ga(e,t,r){try{let n=await import("./chunk-ncet7ba7.js");await n.email.send({to:e.to,from:e.from,subject:`[ts-cloud] ${t}`,text:r})}catch{}}function Ss(e,t){return t??e}function Xe(e){if(!e)return[];let t=(s)=>"'"+s.replaceAll("'",`'"'"'`)+"'",r=(s)=>{if(typeof s==="string")return t(s);if(!/^\/[\w./-]+$/.test(s.envFile)||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(s.variable))throw Error("Invalid notification env-file reference");return'"$(read_env '+t(s.envFile)+" "+t(s.variable)+')"'},n=[];for(let[s,i]of[["slack","text"],["discord","content"]]){let a=e[s]?.webhookUrl;if(a)n.push("URL="+r(a),'post "$URL" '+t(i))}if(e.telegram?.botToken&&e.telegram.chatId)n.push("curl -fsS --max-time 30 -X POST "+t("https://api.telegram.org/bot"+e.telegram.botToken+"/sendMessage")+" --data-urlencode "+t("chat_id="+e.telegram.chatId)+' --data-urlencode "text=$MSG" >/dev/null || FAILED=1');if(e.webhook?.url)if(e.webhook.method==="GET")n.push("curl -fsS --max-time 30 -G "+t(e.webhook.url)+' --data-urlencode "message=$MSG" >/dev/null || FAILED=1');else n.push("post "+t(e.webhook.url)+" message");if(!n.length)return[];return["cat > /usr/local/bin/ts-cloud-notify.new <<'TS_CLOUD_NOTIFY_EOF'","#!/bin/bash","set -uo pipefail",'MSG="${1:-}"; FAILED=0',String.raw`read_env(){ awk -v key="$2" '$0 ~ "^[[:space:]]*(export[[:space:]]+)?" key "[[:space:]]*=" { sub("^[^=]*=[[:space:]]*", ""); sub(/[\r[:space:]]+$/, ""); if (($0 ~ /^".*"$/) || ($0 ~ /^\047.*\047$/)) $0=substr($0,2,length($0)-2); print; exit }' "$1"; }`,String.raw`ESCAPED=$(printf %s "$MSG" | LC_ALL=C awk 'BEGIN{ORS=""; for(i=1;i<32;i++) esc[sprintf("%c",i)]=sprintf("\\u%04x",i)} {if(NR>1) printf "\\n"; for(i=1;i<=length($0);i++){ c=substr($0,i,1); if(c=="\\") printf "\\\\"; else if(c=="\"") printf "\\\""; else if(c in esc) printf "%s",esc[c]; else printf "%s",c }}')`,String.raw`post(){ if [ -z "$1" ]; then FAILED=1; return; fi; curl -fsS --max-time 30 -X POST -H 'Content-Type: application/json' --data "{\"$2\":\"$ESCAPED\"}" "$1" >/dev/null || FAILED=1; }`,...n,'exit "$FAILED"',"TS_CLOUD_NOTIFY_EOF","chmod 0700 /usr/local/bin/ts-cloud-notify.new","mv -f /usr/local/bin/ts-cloud-notify.new /usr/local/bin/ts-cloud-notify"]}function lt(e=[],t={}){let r=t.path??"/root/.ssh/authorized_keys",s=[`mkdir -p ${r.replace(/\/[^/]*$/,"")}`,`touch ${r}`,`sed -i '/^${_s("# >>> ts-cloud managed keys >>>")}$/,/^${_s("# <<< 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(`
28
28
  `);s.push(`cat >> ${r} <<'TS_CLOUD_KEYS_EOF'`,i,"TS_CLOUD_KEYS_EOF",`chmod 600 ${r}`)}return s}function _s(e){return e.replace(/[.*[\]\\/^$]/g,"\\$&")}function $s(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 ys(e,t){if(e===!1)return;if(e===!0||e===void 0)return t;return e}var vs={enabled:!0,ports:[80,443]},Va={mode:"detection",paranoiaLevel:1};function qa(e=!0,t=[]){let r=ys(e,vs);if(!r||r.enabled===!1)return[];let n=[...new Set([...r.ports??vs.ports??[],...t])].sort((s,i)=>s-i);return $s("ddos",Wi({...r,ports:n}))}function Wa(e=!0){let t=ys(e,Va);if(!t||t.mode==="off")return[];return $s("waf",ki(t))}function bs(e={},t=[]){return[...qa(e.ddos,t),...Wa(e.waf)]}function Ya(e){return`${e}-sftp`}function Ts(e){return e.port??2222}function Xa(e){let t=e.sftp.storage;if(t?.type==="efs"&&t.path)return t.path;return`/var/sftp/${e.slug}`}function ut(e){return`'${e.split("'").join("'\\''")}'`}function ws(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=Ya(t),s=Xa(e),i=Ts(r),a="/etc/ts-sftp/host_key",c="/etc/ts-sftp/users",f=r.serviceUser??"ts-sftp",h=[`# --- ts-sftp (${n}) ---`,`id -u ${f} >/dev/null 2>&1 || useradd --system --home-dir ${ut(s)} --shell /usr/sbin/nologin ${f}`,'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 ${ut(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 ${ut(`${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'],g=[];for(let[S,_]of Object.entries(r.users)){let v=(_.homeDirectory??S).replace(/^\/+|\/+$/g,"");if(!v||v.split("/").includes(".."))throw Error(`sftp: invalid homeDirectory for user ${S}`);let y=`/etc/ts-sftp/users/${S}.pub`;h.push(`mkdir -p ${ut(`${s}/${v}`)}`,`printf '%s\\n' ${ut(_.sshPublicKeys.join(`
29
- `))} > ${y}`,`chmod 644 ${y}`),g.push(`--user ${S}:${y}`)}return h.push(`chown -R ${f}:${f} ${ut(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=${f}`,`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":""} ${g.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`),h}function Ps(e){return e?[Ts(e)]:[]}var Ja=[80,443];function dr(e={}){if(e.enabled===!1)return[];let t=[...new Set([...Ja,...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 Qe(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?ht():[],c=!j({...r,proxy:w(e,{environment:t?.environment})}),f=n?[...a,...ur({versions:r.php?.versions,default:r.php?.default,extensions:r.php?.extensions,installNginx:c,optimizeForProduction:r.php?.optimizeForProduction,ini:r.php?.ini}),...c?gn():[]]:void 0,h=[],g=p(e);if(!n&&i)h.push(...a);if(h.push(...Je(e.notifications)),r.managedServices)h.push(...cr(r.managedServices,{mail:s.enabled?s:void 0}),...ct(g,r.managedServices));let S=e.infrastructure?.sftp;if(S)ws(S,de(e)),h.push(...Cs({slug:e.project.slug,sftp:S}));let _=r.firewall??(n?{enabled:!0}:{enabled:!1}),v=Ze(s);if(h.push(...dr(v.length>0?{..._,allowedPorts:[..._.allowedPorts??[],...v]}:_)),h.push(...bs({ddos:r.ddos,waf:r.waf},[...r.firewall?.allowedPorts??[],...v])),h.push(...Me(r.autoUpdates??n)),h.push(...eo(r.appUpdates)),h.push(...Le(r.monitoring??n)),h.push(...lt(r.sshKeys,{path:t?.authorizedKeysPath})),r.backups?.enabled)h.push(...Ut({database:g,backups:r.backups}));return{runtime:r.runtime||"bun",runtimeVersion:r.runtimeVersion||"latest",phpBox:n,phpProvision:f,servicesProvision:h.length>0?h:void 0}}function Es(e,t){if(e.cloud?.attachTo)return[];let r=e.infrastructure?.compute,n=b(e,{environment:t});return[...r?.backups?.enabled?Ut({database:p(e),backups:r.backups}):[],...n.enabled?or(n):[]]}function M(e={}){let{runtime:t="bun",runtimeVersion:r="latest",systemPackages:n=[],database:s,phpProvision:i,servicesProvision:a,caddyfile:c,rpxProvision:f,baked:h=!1,swapGb:g=2}=e,S=new Set(n);if(s==="sqlite")S.add("sqlite3");else if(s==="mysql")S.add("mysql-client");else if(s==="postgres")S.add("postgresql-client");let _=`#!/bin/bash
29
+ `))} > ${y}`,`chmod 644 ${y}`),g.push(`--user ${S}:${y}`)}return h.push(`chown -R ${f}:${f} ${ut(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=${f}`,`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":""} ${g.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`),h}function Ps(e){return e?[Ts(e)]:[]}var Ja=[80,443];function dr(e={}){if(e.enabled===!1)return[];let t=[...new Set([...Ja,...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 Je(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?ht():[],c=!j({...r,proxy:w(e,{environment:t?.environment})}),f=n?[...a,...ur({versions:r.php?.versions,default:r.php?.default,extensions:r.php?.extensions,installNginx:c,optimizeForProduction:r.php?.optimizeForProduction,ini:r.php?.ini}),...c?gn():[]]:void 0,h=[],g=p(e);if(!n&&i)h.push(...a);if(h.push(...Xe(e.notifications)),r.managedServices)h.push(...cr(r.managedServices,{mail:s.enabled?s:void 0}),...ct(g,r.managedServices));let S=e.infrastructure?.sftp;if(S)ws(S,de(e)),h.push(...Cs({slug:e.project.slug,sftp:S}));let _=r.firewall??(n?{enabled:!0}:{enabled:!1}),v=Ze(s);if(h.push(...dr(v.length>0?{..._,allowedPorts:[..._.allowedPorts??[],...v]}:_)),h.push(...bs({ddos:r.ddos,waf:r.waf},[...r.firewall?.allowedPorts??[],...v])),h.push(...Me(r.autoUpdates??n)),h.push(...eo(r.appUpdates)),h.push(...Le(r.monitoring??n)),h.push(...lt(r.sshKeys,{path:t?.authorizedKeysPath})),r.backups?.enabled)h.push(...Ut({database:g,backups:r.backups}));return{runtime:r.runtime||"bun",runtimeVersion:r.runtimeVersion||"latest",phpBox:n,phpProvision:f,servicesProvision:h.length>0?h:void 0}}function Es(e,t){if(e.cloud?.attachTo)return[];let r=e.infrastructure?.compute,n=b(e,{environment:t});return[...r?.backups?.enabled?Ut({database:p(e),backups:r.backups}):[],...n.enabled?or(n):[]]}function M(e={}){let{runtime:t="bun",runtimeVersion:r="latest",systemPackages:n=[],database:s,phpProvision:i,servicesProvision:a,caddyfile:c,rpxProvision:f,baked:h=!1,swapGb:g=2}=e,S=new Set(n);if(s==="sqlite")S.add("sqlite3");else if(s==="mysql")S.add("mysql-client");else if(s==="postgres")S.add("postgresql-client");let _=`#!/bin/bash
30
30
  set -euo pipefail
31
31
  `,v=Math.floor(g);if(v>0)_+=`
32
32
  # Swap: a swapless box under memory pressure lets the kernel OOM killer choose
@@ -138,7 +138,7 @@ ${y.join(`
138
138
  `)}
139
139
  `}return _+=`
140
140
  echo "ts-cloud bootstrap complete — instance is ready for site deploys"
141
- `,_}var Rs="/aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id";function Os(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 Ze(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=Qe(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 xs(e){return Buffer.from(e,"utf8").toString("base64")}function As(e){return e.infrastructure?.compute?.image??null}function fr(e,t){return`${e}-${t}-app-sg`}function _n(e,t,r="app"){return[{Key:"Project",Value:e},{Key:"Environment",Value:t},{Key:"Role",Value:r},{Key:"ManagedBy",Value:"ts-cloud"}]}function Za(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 Is(e,t){let r=fr(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 Za(n.Tags,t.slug,t.environment);return!!t.vpcId&&n.VpcId===t.vpcId})}function ec(e){try{let t=Ls(Qa(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 $r{name="aws";usesCloudFormation=!0;region;ec2Client;cfnClient;constructor(e={}){this.region=e.region||"us-east-1",this.ec2Client=e.ec2Client??((t)=>new qr(t)),this.cfnClient=e.cfnClient??((t)=>new A(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 W=c[0];return{appInstanceId:W.id,appPublicIp:W.publicIp,appPublicIpv6:W.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}let f=As(t);if(!f){if(f=(await new Be(n).getParameter({Name:Rs})).Parameter?.Value??null,!f)throw Error("Could not resolve the Ubuntu 24.04 AMI from SSM")}let h=await a.describeVpcs(),g=(h.Vpcs||[]).find((W)=>W.IsDefault)||(h.Vpcs||[])[0];if(!g?.VpcId)throw Error("No VPC found to launch the instance into");let S=(await a.describeSubnets({Filters:[{Name:"vpc-id",Values:[g.VpcId]}]})).Subnets||[],_=S.find((W)=>W.MapPublicIpOnLaunch)||S[0],v=_?.SubnetId;if(!_?.MapPublicIpOnLaunch)console.warn("ts-cloud: no public subnet found; the instance may not get a public IP (deploys/SSL need one).");let y=fr(s,r),x=(await a.describeSecurityGroups({Filters:[{Name:"group-name",Values:[y]},{Name:"vpc-id",Values:[g.VpcId]}]})).SecurityGroups?.[0]?.GroupId;if(!x)x=(await a.createSecurityGroup({GroupName:y,Description:`ts-cloud ${s}/${r} app`,VpcId:g.VpcId,TagSpecifications:[{ResourceType:"security-group",Tags:_n(s,r)}]})).GroupId;let q=Os(t,r);await a.authorizeSecurityGroupIngress({GroupId:x,IpPermissions:q.map((W)=>({IpProtocol:W.protocol,FromPort:W.port,ToPort:W.port,IpRanges:[{CidrIp:W.cidr}]}))}).catch((W)=>{if(!/InvalidPermission\.Duplicate/.test(W instanceof Error?W.message:""))throw W});let H=xs(Ds(t,r)),R=i.server?.instanceType||"t3.small",I=(await a.runInstances({ImageId:f,InstanceType:R,MinCount:1,MaxCount:1,SecurityGroupIds:x?[x]:void 0,SubnetId:v,UserData:H,IamInstanceProfile:i.server?.iamInstanceProfile?{Name:i.server.iamInstanceProfile}:void 0,TagSpecifications:[{ResourceType:"instance",Tags:[{Key:"Name",Value:`${s}-${r}-app`},..._n(s,r)]}]})).Instances?.[0]?.InstanceId;if(!I)throw Error("RunInstances did not return an instance id");let V=await a.waitForInstanceState(I,"running");if(!V)throw Error(`Instance ${I} did not reach 'running' before timeout`);return{appInstanceId:I,appPublicIp:V.PublicIpAddress,appPublicIpv6:se(V.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=[],f=(await this.findComputeTargets({slug:n,environment:r,role:"app",region:s})).map((y)=>y.id),h;if(f.length>0)h=(await i.describeInstances({InstanceIds:f}).catch(()=>({Reservations:[]}))).Reservations?.flatMap((C)=>C.Instances??[]).find((C)=>C.VpcId)?.VpcId;if(f.length>0)await i.terminateInstances(f),a.push(...f.map((y)=>`instance ${y}`)),await Promise.all(f.map((y)=>i.waitForInstanceState(y,"terminated").catch(()=>{return})));let g=fr(n,r),S=[{Name:"group-name",Values:[g]}];if(h)S.push({Name:"vpc-id",Values:[h]});let _=await i.describeSecurityGroups({Filters:S}).catch(()=>({SecurityGroups:[]})),v=Is(_.SecurityGroups??[],{slug:n,environment:r,vpcId:h});if(v?.GroupId)for(let y=0;y<10;y++)try{await i.deleteSecurityGroup(v.GroupId),a.push(`security group ${g}`);break}catch{await new Promise((C)=>setTimeout(C,3000))}return{destroyed:a}}async getComputeOutputs(e){let t=this.resolveRegion(e.config),r=m(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:Ls(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=ec(a);if(!c)try{c=(await this.cfnClient(t).getStackOutputs(a)).appInstanceId??null}catch{c=null}if(!c)return[];try{let f=await r.describeInstances({InstanceIds:[c],Filters:[{Name:"instance-state-name",Values:["running","pending"]}]});return this.reservationsToTargets(f.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:se(n.Ipv6Address),privateIp:n.PrivateIpAddress,status:n.State?.Name})}return t}bashWrap(e){return["bash <<'TS_CLOUD_BASH_EOF'",e.join(`
141
+ `,_}var Rs="/aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id";function Os(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 Ze(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=Je(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 xs(e){return Buffer.from(e,"utf8").toString("base64")}function As(e){return e.infrastructure?.compute?.image??null}function fr(e,t){return`${e}-${t}-app-sg`}function _n(e,t,r="app"){return[{Key:"Project",Value:e},{Key:"Environment",Value:t},{Key:"Role",Value:r},{Key:"ManagedBy",Value:"ts-cloud"}]}function Za(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 Is(e,t){let r=fr(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 Za(n.Tags,t.slug,t.environment);return!!t.vpcId&&n.VpcId===t.vpcId})}function ec(e){try{let t=Ls(Qa(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 $r{name="aws";usesCloudFormation=!0;region;ec2Client;cfnClient;constructor(e={}){this.region=e.region||"us-east-1",this.ec2Client=e.ec2Client??((t)=>new qr(t)),this.cfnClient=e.cfnClient??((t)=>new A(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 W=c[0];return{appInstanceId:W.id,appPublicIp:W.publicIp,appPublicIpv6:W.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}let f=As(t);if(!f){if(f=(await new Be(n).getParameter({Name:Rs})).Parameter?.Value??null,!f)throw Error("Could not resolve the Ubuntu 24.04 AMI from SSM")}let h=await a.describeVpcs(),g=(h.Vpcs||[]).find((W)=>W.IsDefault)||(h.Vpcs||[])[0];if(!g?.VpcId)throw Error("No VPC found to launch the instance into");let S=(await a.describeSubnets({Filters:[{Name:"vpc-id",Values:[g.VpcId]}]})).Subnets||[],_=S.find((W)=>W.MapPublicIpOnLaunch)||S[0],v=_?.SubnetId;if(!_?.MapPublicIpOnLaunch)console.warn("ts-cloud: no public subnet found; the instance may not get a public IP (deploys/SSL need one).");let y=fr(s,r),x=(await a.describeSecurityGroups({Filters:[{Name:"group-name",Values:[y]},{Name:"vpc-id",Values:[g.VpcId]}]})).SecurityGroups?.[0]?.GroupId;if(!x)x=(await a.createSecurityGroup({GroupName:y,Description:`ts-cloud ${s}/${r} app`,VpcId:g.VpcId,TagSpecifications:[{ResourceType:"security-group",Tags:_n(s,r)}]})).GroupId;let q=Os(t,r);await a.authorizeSecurityGroupIngress({GroupId:x,IpPermissions:q.map((W)=>({IpProtocol:W.protocol,FromPort:W.port,ToPort:W.port,IpRanges:[{CidrIp:W.cidr}]}))}).catch((W)=>{if(!/InvalidPermission\.Duplicate/.test(W instanceof Error?W.message:""))throw W});let H=xs(Ds(t,r)),R=i.server?.instanceType||"t3.small",I=(await a.runInstances({ImageId:f,InstanceType:R,MinCount:1,MaxCount:1,SecurityGroupIds:x?[x]:void 0,SubnetId:v,UserData:H,IamInstanceProfile:i.server?.iamInstanceProfile?{Name:i.server.iamInstanceProfile}:void 0,TagSpecifications:[{ResourceType:"instance",Tags:[{Key:"Name",Value:`${s}-${r}-app`},..._n(s,r)]}]})).Instances?.[0]?.InstanceId;if(!I)throw Error("RunInstances did not return an instance id");let V=await a.waitForInstanceState(I,"running");if(!V)throw Error(`Instance ${I} did not reach 'running' before timeout`);return{appInstanceId:I,appPublicIp:V.PublicIpAddress,appPublicIpv6:se(V.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=[],f=(await this.findComputeTargets({slug:n,environment:r,role:"app",region:s})).map((y)=>y.id),h;if(f.length>0)h=(await i.describeInstances({InstanceIds:f}).catch(()=>({Reservations:[]}))).Reservations?.flatMap((C)=>C.Instances??[]).find((C)=>C.VpcId)?.VpcId;if(f.length>0)await i.terminateInstances(f),a.push(...f.map((y)=>`instance ${y}`)),await Promise.all(f.map((y)=>i.waitForInstanceState(y,"terminated").catch(()=>{return})));let g=fr(n,r),S=[{Name:"group-name",Values:[g]}];if(h)S.push({Name:"vpc-id",Values:[h]});let _=await i.describeSecurityGroups({Filters:S}).catch(()=>({SecurityGroups:[]})),v=Is(_.SecurityGroups??[],{slug:n,environment:r,vpcId:h});if(v?.GroupId)for(let y=0;y<10;y++)try{await i.deleteSecurityGroup(v.GroupId),a.push(`security group ${g}`);break}catch{await new Promise((C)=>setTimeout(C,3000))}return{destroyed:a}}async getComputeOutputs(e){let t=this.resolveRegion(e.config),r=m(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:Ls(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=ec(a);if(!c)try{c=(await this.cfnClient(t).getStackOutputs(a)).appInstanceId??null}catch{c=null}if(!c)return[];try{let f=await r.describeInstances({InstanceIds:[c],Filters:[{Name:"instance-state-name",Values:["running","pending"]}]});return this.reservationsToTargets(f.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:se(n.Ipv6Address),privateIp:n.PrivateIpAddress,status:n.State?.Name})}return t}bashWrap(e){return["bash <<'TS_CLOUD_BASH_EOF'",e.join(`
142
142
  `),"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((g)=>setTimeout(g,3000));try{if(c=await e.listCommandInvocations({CommandId:t,Details:!0}),c.length>=r&&c.every((S)=>a.has(S.Status||"")))break}catch{}}let f=c.map((g)=>({instanceId:g.InstanceId,status:g.Status||"Unknown",output:g.StandardOutputContent,error:g.StandardErrorContent})),h=f.length>0&&f.every((g)=>g.status==="Success");return{success:h,instanceCount:f.length,perInstance:f,error:h?void 0:Yt(f,"One or more SSM command invocations failed")}}}import{execFileSync as cl,execSync as vo}from"node:child_process";import{createHash as ll,randomUUID as $o}from"node:crypto";import{createReadStream as ul,existsSync as pl,readFileSync as dl}from"node:fs";async function Us(e,t){let r=await import("node:fs"),n=await import("node:path"),s=await import("node:child_process"),i="/etc/ts-cloud/compute-storage.json",a="/var/lib/ts-cloud/compute-storage-state.json",c="/run/ts-cloud-root-web",f=t[0]??"status";if(!["plan","status","check","apply","ensure-site","reclaim"].includes(f))throw Error(`Unknown compute storage command: ${f}`);let h=(T,k)=>{try{return JSON.parse(r.readFileSync(T,"utf8"))}catch(P){if(P.code==="ENOENT")return k;throw P}},g=(T,k)=>{r.mkdirSync(n.dirname(T),{recursive:!0});let P=`${T}.${process.pid}.tmp`;r.writeFileSync(P,`${JSON.stringify(k,null,2)}
143
143
  `,{mode:420}),r.renameSync(P,T)},S=(T,k)=>s.execFileSync(T,k,{encoding:"utf8",maxBuffer:16777216}),_=(T,k)=>{let P=s.spawnSync(T,k,{encoding:"utf8"});return P.status===0?P.stdout.trim():""},v=(T)=>!!_("findmnt",["-n","--mountpoint",T]),y=(T,k)=>{try{let P=r.statSync(T),O=r.statSync(k);return P.dev===O.dev&&P.ino===O.ino}catch{return!1}},C=h("/var/lib/ts-cloud/compute-storage-state.json",{entries:[]}),x=e.deploymentStorage,q=e.volumes.find((T)=>T.key===x?.volume),H=(T,k)=>{if(!q)return[];let P=[];for(let O of r.readdirSync(e.webRoot,{withFileTypes:!0})){if(!O.isDirectory()||O.isSymbolicLink())continue;let D=n.join(e.webRoot,O.name);if(T&&D!==T&&D!==n.join(e.webRoot,`${k}-shared`))continue;for(let J of["releases",...x?.includeBackups===!1?[]:["backups"]]){let Y=n.join(D,J);if(!r.existsSync(Y)||!r.lstatSync(Y).isDirectory())continue;P.push({source:Y,destination:n.join(q.mountPath,J,O.name)})}}return P},R=(T)=>{try{return v(T.mountPath)&&r.statSync(T.mountPath).dev===r.statSync(T.device).rdev}catch{return!1}},L=(T)=>{let k=r.statfsSync(T),P=(k.blocks-k.bfree)*k.bsize,O=k.bavail*k.bsize;return{path:T,sizeBytes:k.blocks*k.bsize,usedBytes:P,availableBytes:O,usedPercent:Math.ceil(100*P/(P+O))}},I=()=>{let T=[],k=[L("/")];for(let O of e.volumes)if(!R(O))T.push(`missing or incorrect volume mount: ${O.mountPath}`);else k.push(L(O.mountPath));for(let O of C.entries)if(!v(O.source)||!y(O.source,O.destination))T.push(`missing deployment mount: ${O.source}`);let P=new Set(C.entries.map((O)=>O.source));for(let O of H())if(!P.has(O.source))T.push(`deployment needs volume placement: ${O.source}`);return{timestamp:new Date().toISOString(),volumes:e.volumes.map((O)=>({key:O.key,name:O.name,id:O.id,size:O.size,mountPath:O.mountPath})),disks:k,mounts:C.entries.length,problems:T}};if(f==="plan")return console.log(JSON.stringify({volumes:e.volumes,entries:H(),state:C},null,2));if(f==="status"||f==="check"){let T=I();if(f==="check"){g("/var/lib/ts-cloud/compute-storage-status.json",T);let k="/var/lib/ts-cloud/compute-storage-alert.json",P=h(k,{problems:[]});if(JSON.stringify(P.problems)!==JSON.stringify(T.problems)){let O=T.problems.join("; ")||"all configured mounts are healthy",D=`${T.problems.length?"Storage alert":"Storage recovered"} on ${_("hostname",[])}: ${O}`;S("/usr/local/bin/ts-cloud-notify",[D.length>1800?`${D.slice(0,1600)}... Full report: /var/lib/ts-cloud/compute-storage-status.json`:D])}g(k,{problems:T.problems,timestamp:T.timestamp})}if(console.log(JSON.stringify(T)),T.problems.length)process.exitCode=1;return T}if(process.getuid?.()!==0)throw Error("Compute storage changes require root");let V=()=>{let O=r.readFileSync("/etc/fstab","utf8");if(!r.existsSync("/etc/fstab.before-ts-cloud-storage"))r.copyFileSync("/etc/fstab","/etc/fstab.before-ts-cloud-storage");let D=[];for(let X of e.volumes){let ee=S("blkid",["-s","UUID","-o","value",X.device]).trim();if(!ee)throw Error(`Volume ${X.name} has no filesystem UUID`);D.push(`UUID=${ee} ${X.mountPath} ext4 defaults,noatime,nodev,nosuid,nofail,x-systemd.device-timeout=30s 0 2`)}for(let X of C.entries)D.push(`${X.destination} ${X.source} none bind,nofail,x-systemd.requires-mounts-for=${q.mountPath} 0 0`);let J=`# BEGIN ts-cloud compute storage
144
144
  ${D.join(`
@@ -155,13 +155,13 @@ RequiresMountsFor=${T.join(" ")}
155
155
  `).at(-1)?.split(/\s+/)[0],N=r.statfsSync(q.mountPath);if(Number(E)>N.bavail*N.bsize)throw Error("Insufficient free volume capacity for a verified deployment copy")}if(!r.existsSync("/run/ts-cloud-root-web"))r.mkdirSync("/run/ts-cloud-root-web");if(!v("/run/ts-cloud-root-web"))S("mount",["--bind",e.webRoot,"/run/ts-cloud-root-web"]);S("mount",["--make-private","/run/ts-cloud-root-web"]);let O=r.statSync(e.webRoot).dev;for(let E of C.entries){let N=n.join("/run/ts-cloud-root-web",n.relative(e.webRoot,E.source));if(r.existsSync(N)&&(r.statSync(N).dev!==O||y(N,E.destination)))throw Error(`Root recovery view contains a deployment mount: ${N}`)}for(let E=0;E<P.length;E++){if(v(P[E].source)&&y(P[E].source,P[E].destination))continue;console.log(`copy ${E+1}/${P.length}: ${P[E].source}`),await ne(P[E],!1)}if(f!=="reclaim")for(let E of T)ae(E);for(let E of r.readdirSync(e.webRoot,{withFileTypes:!0}).filter((N)=>N.isDirectory()).sort((N,_e)=>N.name.localeCompare(_e.name)))ae(n.join(e.webRoot,E.name,".ts-cloud/deploy.lock"));for(let E of f==="reclaim"?[]:H(f==="ensure-site"?t[1]:void 0,t[2]))if(!C.entries.some((N)=>N.source===E.source)&&!P.some((N)=>N.source===E.source))P.push(E);if(P.length)console.log("Checking application services and HTTPS routes before activation");let D=P.length?await me():void 0;if(D)g("/var/lib/ts-cloud/compute-storage-health-before.json",D);let J=ie().filter((E)=>E.write);if(J.length)throw Error(`Live writable files must be shared before migration: ${J.map((E)=>E.file).join(", ")}`);let Y={entries:[...C.entries],fstab:r.readFileSync("/etc/fstab","utf8")};if(P.length)S("sync",[]);let X=[];try{for(let E=0;E<P.length;E++){let N=P[E];if(v(N.source)){if(!y(N.source,N.destination))throw Error(`Unrecorded mount occupies ${N.source}`);C.entries.push(N),g("/var/lib/ts-cloud/compute-storage-state.json",C);continue}if(console.log(`verify and mount ${E+1}/${P.length}: ${N.source}`),await ne(N,!0),S("mount",["--bind",N.destination,N.source]),!y(N.source,N.destination))throw Error(`Bind verification failed: ${N.source}`);X.push(N),C.entries.push(N),g("/var/lib/ts-cloud/compute-storage-state.json",C),V()}if(V(),S("findmnt",["--verify"]),C.activatedAt=new Date().toISOString(),g("/var/lib/ts-cloud/compute-storage-state.json",C),Se(),D){console.log("Checking application services and HTTPS routes after activation");let E=await me();g("/var/lib/ts-cloud/compute-storage-health-after.json",E);let N=D.routes.filter((ce)=>ce.ok&&!E.routes.some(($e)=>$e.domain===ce.domain&&$e.path===ce.path&&$e.ok)),_e=Object.keys(D.services).filter((ce)=>!E.services[ce]);if(N.length||_e.length)throw Error(`Application verification failed: ${N.map((ce)=>ce.domain+ce.path).concat(_e).join(", ")}`);console.log(`Verified ${E.routes.length} routes and ${Object.keys(E.services).length} services`)}}catch(E){let N=[];for(let _e of X.reverse())try{S("umount",[_e.source])}catch{N.push(_e),console.error(`Rollback mount busy, original data retained: ${_e.source}`)}if(C.entries=[...Y.entries,...N],r.writeFileSync("/etc/fstab",Y.fstab),N.length)V();throw g("/var/lib/ts-cloud/compute-storage-state.json",C),S("systemctl",["daemon-reload"]),E}let ee=ie().filter((E)=>E.device===O).map((E)=>E.file);for(let E of C.entries){if(!v(E.source)||!y(E.source,E.destination))throw Error(`Lost deployment mount: ${E.source}`);let N=n.join("/run/ts-cloud-root-web",n.relative(e.webRoot,E.source));if(!r.existsSync(N))continue;if(r.statSync(N).dev!==O||y(N,E.destination))throw Error(`Refusing to clean a deployment volume through the root recovery view: ${N}`);let _e="";try{_e=n.basename(r.realpathSync(n.join(n.dirname(E.source),"current")))}catch{}for(let ce of r.readdirSync(N,{withFileTypes:!0})){let $e=n.join(N,ce.name);if(n.basename(E.source)==="backups"){if(ce.isFile()&&r.existsSync(n.join(E.destination,ce.name)))r.unlinkSync($e)}else if(ce.isDirectory()&&!ce.isSymbolicLink()&&ce.name!==_e&&!ee.some((Rt)=>Rt===n.join(E.source,ce.name)||Rt.startsWith(`${n.join(E.source,ce.name)}/`)))r.rmSync($e,{recursive:!0})}}S("sync",[]);let ue=I();return g("/var/lib/ts-cloud/compute-storage-status.json",ue),console.log(JSON.stringify(ue)),ue}finally{for(let T of re.reverse())Z.symbols.flock(T,8),r.closeSync(T);Z.close()}}var vn="/etc/ts-cloud/compute-storage.json",Ke="/usr/local/lib/ts-cloud/compute-storage.mjs";function ei(e,t){let r=Object.entries(e.infrastructure?.compute?.volumes??{}).map(([s,i])=>{if(!/^[a-z][a-z0-9-]*$/.test(s))throw Error(`Invalid compute volume key: ${s}`);if(!Number.isInteger(i.size)||i.size<10||i.size>10240)throw Error(`compute.volumes.${s}.size must be a whole number from 10 to 10240 GB`);if(!i.mountPath.startsWith("/")||!i.mountPath.slice(1).split("/").every((c)=>/^[\w-]+$/.test(c))||i.mountPath==="/var"||i.mountPath==="/var/lib"||["/etc","/usr","/var/www","/root","/boot","/dev","/proc","/sys","/run","/bin","/sbin","/lib"].some((c)=>i.mountPath===c||i.mountPath.startsWith(`${c}/`)))throw Error(`Unsafe compute volume mount path: ${i.mountPath}`);let a=i.name??`${e.project.slug}-${t}-${s}`;if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(a))throw Error(`Invalid compute volume name: ${a}`);return{...i,key:s,name:a,mountPath:i.mountPath.replace(/\/+$/,"")}});for(let s of r)if(r.some((i)=>i!==s&&(i.name===s.name||i.mountPath===s.mountPath||i.mountPath.startsWith(`${s.mountPath}/`))))throw Error("Compute volumes must have distinct names and non-overlapping mount paths");let n=e.infrastructure?.compute?.deploymentStorage;for(let s of n?.locks??[])if(!s.startsWith("/run/lock/")||!s.slice(10).split("/").every((i)=>/^[\w.-]+$/.test(i)&&i!=="."&&i!=="..")||s==="/run/lock/ts-cloud-compute-storage.lock")throw Error(`Invalid deployment storage lock: ${s}`);for(let s of n?.dependentUnits??[])if(!/^[\w@.-]+\.service$/.test(s))throw Error(`Invalid deployment storage dependent unit: ${s}`);if(n&&!r.some((s)=>s.key===n.volume))throw Error(`deploymentStorage.volume references an undeclared compute volume: ${n.volume}`);return r}function hr(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function ti(e){let t=`${vn}.candidate`,r=`#!/usr/bin/env bun
156
156
  await (${Us.toString()})(JSON.parse(await Bun.file(process.env.TS_CLOUD_STORAGE_POLICY || ${JSON.stringify(vn)}).text()), process.argv.slice(2));
157
157
  `;return['command -v bun >/dev/null 2>&1 || { echo "Configured compute storage requires Bun on the host" >&2; exit 1; }',"install -d -m 0755 /etc/ts-cloud /usr/local/lib/ts-cloud /var/lib/ts-cloud",`printf %s ${hr(Buffer.from(r).toString("base64"))} | base64 -d > ${Ke}.new`,`chmod 0755 ${Ke}.new && mv ${Ke}.new ${Ke}`,`printf %s ${hr(JSON.stringify(e))} > ${t}`,`chmod 0644 ${t}`,`TS_CLOUD_STORAGE_POLICY=${t} bun ${Ke} apply 2>&1 | tee /var/log/ts-cloud-compute-storage.log`,`rm -f ${t}`,"cat > /etc/systemd/system/ts-cloud-storage-check.service <<'TS_CLOUD_STORAGE_SERVICE'","[Unit]","Description=Check configured compute storage and deployment mounts","[Service]","Type=oneshot",`ExecStart=/usr/local/bin/bun ${Ke} check`,"TS_CLOUD_STORAGE_SERVICE","cat > /etc/systemd/system/ts-cloud-storage-check.timer <<'TS_CLOUD_STORAGE_TIMER'","[Unit]","Description=Check compute storage every minute","[Timer]","OnBootSec=2min","OnUnitActiveSec=1min","[Install]","WantedBy=timers.target","TS_CLOUD_STORAGE_TIMER","systemctl daemon-reload","systemctl enable --now ts-cloud-storage-check.timer","cat > /etc/systemd/system/ts-cloud-storage-reclaim.service <<'TS_CLOUD_RECLAIM_SERVICE'","[Unit]","Description=Reclaim inactive root copies of volume-backed deployments","[Service]","Type=oneshot",`ExecStart=/usr/local/bin/bun ${Ke} reclaim`,"Nice=19","IOSchedulingClass=idle","TS_CLOUD_RECLAIM_SERVICE","cat > /etc/systemd/system/ts-cloud-storage-reclaim.timer <<'TS_CLOUD_RECLAIM_TIMER'","[Unit]","Description=Reclaim retired deployment copies hourly","[Timer]","OnCalendar=hourly","RandomizedDelaySec=5min","Persistent=true","[Install]","WantedBy=timers.target","TS_CLOUD_RECLAIM_TIMER","systemctl daemon-reload","systemctl enable --now ts-cloud-storage-reclaim.timer"]}function Mr(e,t){return[`if [ -f ${vn} ]; then bun ${Ke} ensure-site ${hr(e)} ${hr(t)}; fi`]}import{createHash as tc}from"node:crypto";function rc(){return["if [ -x /usr/local/bin/bun ]; then",' TS_CLOUD_HOST_BUN="$(readlink -f /usr/local/bin/bun)"',' case "$TS_CLOUD_HOST_BUN" in /root/*|/home/*)'," install -d -m 755 /opt/ts-cloud /opt/ts-cloud/bun /opt/ts-cloud/bun/bin",' TS_CLOUD_BUN_STAGE="$(mktemp /opt/ts-cloud/bun/bin/.bun.XXXXXX)"',' install -m 755 "$TS_CLOUD_HOST_BUN" "$TS_CLOUD_BUN_STAGE"',' mv -f "$TS_CLOUD_BUN_STAGE" /opt/ts-cloud/bun/bin/bun'," ln -sfn /opt/ts-cloud/bun/bin/bun /usr/local/bin/bun"," ;; esac","fi"]}function pt(e){if(!/^[a-z0-9][a-z0-9-]*$/.test(e))throw Error("Runtime isolation requires a safe project slug");return`tsc-${e.length<=24?e:`${e.slice(0,15)}-${tc("sha256").update(e).digest("hex").slice(0,8)}`}`}function Mt(e,t,r){return[`User=${e}`,`Group=${e}`,"NoNewPrivileges=true","PrivateTmp=true","ProtectHome=true","ProtectProc=invisible","InaccessiblePaths=-/run/postgresql -/var/run/postgresql","TemporaryFileSystem=/var/www:ro",`BindPaths=${t} -/var/www/${r}-shared`,"UMask=0077",`Environment=HOME=/var/lib/ts-cloud/${e}`]}function ks(e,t,r){let n=pt(e);if(!t.startsWith(`/var/www/${e}-`)||t.slice(9).includes("/"))throw Error("Runtime isolation requires a project-namespaced application directory");let s=`/var/lib/ts-cloud/${n}`,i=`/var/www/${e}-shared`,a=[...new Set([t,...r])];for(let c of a)if(!/^\/[a-zA-Z0-9_./-]+$/.test(c)||c.split("/").includes("..")||!(c===t||c.startsWith(`${t}/`)||c===i||c.startsWith(`${i}/`)))throw Error(`Runtime isolation cannot take ownership outside project ${e}`);return[...rc(),`if ! id -u ${n} >/dev/null 2>&1; then useradd --system --user-group --create-home --home-dir ${s} --shell /usr/sbin/nologin ${n}; fi`,`[ "$(id -u ${n})" != 0 ] && [ "$(getent passwd ${n} | cut -d: -f6)" = ${s} ] || { echo 'Unexpected runtime isolation identity' >&2; exit 1; }`,`install -d -m 700 -o ${n} -g ${n} ${s}`,...a.map((c)=>`chown -hR ${n}:${n} ${c}`),`chmod 750 ${t}`]}function gr(e){return Object.entries(e).map(([t,r])=>`${t}=${nc(String(r))}`).join(`
158
- `)}function nc(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}var Sr=["storage",".env"],zt=4;function Ue(e){return`${e.replace(/\/+$/,"")}/.ts-cloud`}function sc(e){return`${Ue(e)}/deploy-history.log`}function oc(e,t){return`${Ue(e)}/deploys/${t}.log`}function Hs(e){return`${Ue(e)}/shared-paths`}function vr(e){return`${e.shared}/stx-images`}function Ft(e){return`${e.shared}/stx-bundles`}function Zt(e,t){let r=e.replace(/\/+$/,"");return{base:r,releases:`${r}/releases`,shared:`${r}/shared`,current:`${r}/current`,release:`${r}/releases/${t}`}}function Ns(e){let t=e.split("/").pop()||e;if(t===".env"||t.startsWith(".env."))return!0;return/\.[a-z0-9]+$/i.test(t)}function $n(e){return typeof e==="string"?e:e.path}function Ms(e){let t=new Map;for(let r of e)t.set($n(r),r);return[...t.values()]}function zs(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 ic(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=Sr){let r=[`mkdir -p ${e.releases} ${e.shared} ${vr(e)} ${Ft(e)}`,...ic(e)],n=t.map((i)=>zs(e,i));for(let{path:i,target:a,seed:c}of n){if(!c)continue;if(r.push(`ts_cloud_adopt_shared '${i}' '${a}'`),Ns(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=Hs(e.base);return r.push(`mkdir -p ${Ue(e.base)}`,`cat > ${s} <<'TS_CLOUD_SHARED_PATHS_EOF'`,...n.map((i)=>`${i.path} ${i.target}`),"TS_CLOUD_SHARED_PATHS_EOF"),r}function yn(e,t=900){let r=`${Ue(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 bn(e){let t=`${e.release}.incoming`;return[`rm -rf ${t}`,`mkdir -p ${t}`,...ac(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 Tn(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 ac(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 wn(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 cc(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 yr(e,t=Sr){let r=[];for(let n of t){let{path:s,target:i,seed:a}=zs(e,n),c=`${e.release}/${s}`,f=[`rm -rf ${c}`,`mkdir -p "$(dirname ${c})"`,`ln -sfn ${i} ${c}`];if(a){if(s!==".env"&&Ns(s))r.push(...cc(c,i));r.push(...f);continue}r.push(`if [ -e ${i} ]; then`,...f.map((h)=>` ${h}`),"fi")}return r}function lc(e,t){let r=Hs(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 dt(e){return[`ln -sfn ${e.release} ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`]}function Cn(e){return`${Ue(e)}/previous-release`}function Pn(e,t="TS_CLOUD_PREV_CURRENT"){let r=Cn(e.base);return[`if [ -n "\${${t}:-}" ] && [ -d "$${t}" ] && [ "$(readlink -f "$${t}")" != "$(readlink -f ${e.release})" ]; then mkdir -p ${Ue(e.base)}; basename "$${t}" > ${r}; fi`]}function Fs(e,t){let r=Cn(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 $g(e,t={}){return[...Fs(e,t.to),'echo "would roll back from $(basename "${TS_CLOUD_CURRENT:-none}") to $TS_CLOUD_RB_ID (dry run: nothing changed)"']}function Mg(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 ${Cn(e.base)}`,'echo "rolled back to $TS_CLOUD_RB_ID"'],i=[...Fs(e,t.to),...lc(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((f)=>` ${f}`),` 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((f)=>` ${f}`),` systemctl restart ${a}.service`,"else",...s.map((f)=>` ${f}`),"fi"]}function mt(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 uc(e){return`${Ue(e)}/owner`}function En(e,t){let r=uc(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 br(e,t){let r=Ue(e),n=oc(e,t.releaseId),s=sc(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 pc=new Set(["sqlite","sqlite3"]),dc=new Set([":memory:","memory"]);function mc(e){let t=e?.DB_CONNECTION?.trim().toLowerCase();return t!=null&&pc.has(t)}function fc(e){let t=e.trim().replace(/^\.\//,"");if(t===""||t.startsWith("/")||t.startsWith("~"))return;if(t.split("/").includes(".."))return;return t.replace(/\/+$/,"")}function Rn(e,t=[]){if(!mc(e))return{};let r=e?.DB_DATABASE_PATH?.trim()||e?.DB_DATABASE?.trim();if(r&&dc.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=fc(r);if(!n)return{};if(t.some((s)=>$n(s)===n))return{};return{path:n}}function Tr(e,t=[]){let{path:r}=Rn(e,t);return r?[r]:[]}var Fr="/var/ts-cloud/artifacts",Uh="/usr/local/bin/ts-cloud-host-cleanup.sh",Qh="ts-cloud-host-cleanup";var Fg=Object.freeze({stagingMaxAgeMinutes:60,artifactMaxAgeDays:2,artifactUploadMaxAgeMinutes:60,bunCacheMaxAgeDays:7,journalMaxAgeDays:14,journalMaxSizeMb:512,containerImageMaxAgeHours:168}),Ug=Object.freeze({artifactMaxAgeDays:0,bunCacheMaxAgeDays:1,journalMaxAgeDays:3,journalMaxSizeMb:256,containerImageMaxAgeHours:24}),Hh=50,Gh=85,Vh="daily";function Bs(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function et(e,t,r=0){if(!Number.isInteger(t)||t<r)throw Error(`hostCleanup: ${e} must be a whole number >= ${r} (got ${t})`)}function Ks(e,t){for(let[r,n]of Object.entries(t))et(`${e}.${r}`,n);et(`${e}.stagingMaxAgeMinutes`,t.stagingMaxAgeMinutes,15),et(`${e}.artifactUploadMaxAgeMinutes`,t.artifactUploadMaxAgeMinutes,15),et(`${e}.journalMaxSizeMb`,t.journalMaxSizeMb,1)}function hc(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(et(`${r}.maxAgeDays`,e.maxAgeDays),e.type!==void 0&&e.type!=="file"&&e.type!=="directory")throw Error(`${r}.type must be 'file' or 'directory'`)}function Ur(e){let t=typeof e==="object"&&e!==null?e:{},r=e!==!1,n={...Fg,...js(t.retention)};Ks("hostCleanup.retention",n);let s=null;if(t.pressure!==!1){let c=typeof t.pressure==="object"?t.pressure:{},f=c.lowWaterPercent??50,h=c.highWaterPercent??85;if(et("hostCleanup.pressure.lowWaterPercent",f),et("hostCleanup.pressure.highWaterPercent",h,1),h>100||f>=h)throw Error(`hostCleanup.pressure: need 0 <= lowWaterPercent < highWaterPercent <= 100 (got ${f} and ${h})`);let g={...Ug,...js(c.escalated)},S=Object.fromEntries(Object.keys(n).map((_)=>[_,Math.min(n[_],g[_]??n[_])]));Ks("hostCleanup.pressure.escalated",S),s={lowWaterPercent:f,highWaterPercent:h,escalated:S}}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(hc),{enabled:r,timer:r&&t.timer!==!1,schedule:i,retention:n,pressure:s,paths:a}}function js(e){return Object.fromEntries(Object.entries(e??{}).filter(([,t])=>t!==void 0))}var Kt={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 On(e){return Object.keys(Kt).map((t)=>`${Kt[t]}=${e[t]}`).join(" ")}var Ge=(e)=>`"$${Kt[e]}"`;function Gs(e){return[`find /var/ts-cloud/staging -xdev -maxdepth 1 -type f -mmin +${Ge("stagingMaxAgeMinutes")} -delete 2>/dev/null || true`,`find /tmp -xdev -maxdepth 1 -type f -name "*-release.tar.gz" -mmin +${Ge("stagingMaxAgeMinutes")} -delete 2>/dev/null || true`,`find /var/ts-cloud/artifacts -xdev -maxdepth 1 -type f -name "*.tar.gz" -mtime +${Ge("artifactMaxAgeDays")} -delete 2>/dev/null || true`,`find /var/ts-cloud/artifacts -xdev -maxdepth 1 -type f -name ".*.tmp" -mmin +${Ge("artifactUploadMaxAgeMinutes")} -delete 2>/dev/null || true`,...e.map(gc),`journalctl --vacuum-time=${Ge("journalMaxAgeDays")}d --vacuum-size=${Ge("journalMaxSizeMb")}M >/dev/null 2>&1 || true`]}function gc(e){let t=Bs(e.path.replace(/\/+$/,"")),r=Bs(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 Vs(){return[`find /root/.bun/install/cache -xdev -type f -mtime +${Ge("bunCacheMaxAgeDays")} -delete 2>/dev/null || true`,`find /root/.bun/install/cache -xdev -depth -type d -empty -mtime +${Ge("bunCacheMaxAgeDays")} -delete 2>/dev/null || true`,`if command -v docker >/dev/null 2>&1; then docker image prune --all --force --filter "until=\${${Kt.containerImageMaxAgeHours}}h" >/dev/null 2>&1 || true; fi`,`if command -v podman >/dev/null 2>&1; then podman image prune --all --force --filter "until=\${${Kt.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 qs(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 ri(e){let{retention:t,pressure:r,paths:n}=Ur(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)"',On(t),...Gs(n),...Vs(),'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"'];let{lowWaterPercent:a,highWaterPercent:c,escalated:f}=r;return['echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',...qs("TS_CLOUD_HC_BEFORE"),"TS_CLOUD_HC_TIER=normal",On(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",` ${On(f)}`,` echo "[ts-cloud] warning: / at \${TS_CLOUD_HC_BEFORE}% (at or above ${c}%), host cleanup is using shortened retention windows" >&2`,"fi",...Gs(n),'if [ "$TS_CLOUD_HC_TIER" != light ]; then',...Vs().map((h)=>` ${h}`),"fi",'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"',...qs("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 Qg(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",...ri(e),"exit 0"]}function Dn(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 to(e){let t=Ur(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=Dn("/usr/local/bin/ts-cloud-host-cleanup.sh",Qg(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",...Dn("/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"),...Dn("/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 ni(e){let t=to(e);if(!Ur(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']}function Js(e,t,r={}){if(!t.length)return[];let n=Object.entries(r).flatMap(([s,i])=>{if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(s))throw Error("Invalid pre-start environment variable name");if(["PORT","PORT_BACKEND","PORT_ADMIN","PORT_FRONTEND"].includes(s))return[];return[`export ${s}=${We(String(i))}`]});return[`cd ${e}`,`if [ -d ${u} ] && command -v pantry >/dev/null 2>&1; then`,` ${Re()}`,"fi",...n,...t]}var Sc=/\.(?:[cm]?[jt]sx?)$/;function ii(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&&!Sc.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 Ws(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.
158
+ `)}function nc(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}var Sr=["storage",".env"],zt=4;function Ue(e){return`${e.replace(/\/+$/,"")}/.ts-cloud`}function sc(e){return`${Ue(e)}/deploy-history.log`}function oc(e,t){return`${Ue(e)}/deploys/${t}.log`}function Hs(e){return`${Ue(e)}/shared-paths`}function vr(e){return`${e.shared}/stx-images`}function Ft(e){return`${e.shared}/stx-bundles`}function Zt(e,t){let r=e.replace(/\/+$/,"");return{base:r,releases:`${r}/releases`,shared:`${r}/shared`,current:`${r}/current`,release:`${r}/releases/${t}`}}function Ns(e){let t=e.split("/").pop()||e;if(t===".env"||t.startsWith(".env."))return!0;return/\.[a-z0-9]+$/i.test(t)}function $n(e){return typeof e==="string"?e:e.path}function Ms(e){let t=new Map;for(let r of e)t.set($n(r),r);return[...t.values()]}function zs(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 ic(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=Sr){let r=[`mkdir -p ${e.releases} ${e.shared} ${vr(e)} ${Ft(e)}`,...ic(e)],n=t.map((i)=>zs(e,i));for(let{path:i,target:a,seed:c}of n){if(!c)continue;if(r.push(`ts_cloud_adopt_shared '${i}' '${a}'`),Ns(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=Hs(e.base);return r.push(`mkdir -p ${Ue(e.base)}`,`cat > ${s} <<'TS_CLOUD_SHARED_PATHS_EOF'`,...n.map((i)=>`${i.path} ${i.target}`),"TS_CLOUD_SHARED_PATHS_EOF"),r}function yn(e,t=900){let r=`${Ue(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 bn(e){let t=`${e.release}.incoming`;return[`rm -rf ${t}`,`mkdir -p ${t}`,...ac(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 Tn(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 ac(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 wn(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 cc(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 yr(e,t=Sr){let r=[];for(let n of t){let{path:s,target:i,seed:a}=zs(e,n),c=`${e.release}/${s}`,f=[`rm -rf ${c}`,`mkdir -p "$(dirname ${c})"`,`ln -sfn ${i} ${c}`];if(a){if(s!==".env"&&Ns(s))r.push(...cc(c,i));r.push(...f);continue}r.push(`if [ -e ${i} ]; then`,...f.map((h)=>` ${h}`),"fi")}return r}function lc(e,t){let r=Hs(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 dt(e){return[`ln -sfn ${e.release} ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`]}function Cn(e){return`${Ue(e)}/previous-release`}function Pn(e,t="TS_CLOUD_PREV_CURRENT"){let r=Cn(e.base);return[`if [ -n "\${${t}:-}" ] && [ -d "$${t}" ] && [ "$(readlink -f "$${t}")" != "$(readlink -f ${e.release})" ]; then mkdir -p ${Ue(e.base)}; basename "$${t}" > ${r}; fi`]}function Fs(e,t){let r=Cn(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 $g(e,t={}){return[...Fs(e,t.to),'echo "would roll back from $(basename "${TS_CLOUD_CURRENT:-none}") to $TS_CLOUD_RB_ID (dry run: nothing changed)"']}function Mg(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 ${Cn(e.base)}`,'echo "rolled back to $TS_CLOUD_RB_ID"'],i=[...Fs(e,t.to),...lc(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((f)=>` ${f}`),` 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((f)=>` ${f}`),` systemctl restart ${a}.service`,"else",...s.map((f)=>` ${f}`),"fi"]}function mt(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 uc(e){return`${Ue(e)}/owner`}function En(e,t){let r=uc(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 br(e,t){let r=Ue(e),n=oc(e,t.releaseId),s=sc(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 pc=new Set(["sqlite","sqlite3"]),dc=new Set([":memory:","memory"]);function mc(e){let t=e?.DB_CONNECTION?.trim().toLowerCase();return t!=null&&pc.has(t)}function fc(e){let t=e.trim().replace(/^\.\//,"");if(t===""||t.startsWith("/")||t.startsWith("~"))return;if(t.split("/").includes(".."))return;return t.replace(/\/+$/,"")}function Rn(e,t=[]){if(!mc(e))return{};let r=e?.DB_DATABASE_PATH?.trim()||e?.DB_DATABASE?.trim();if(r&&dc.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=fc(r);if(!n)return{};if(t.some((s)=>$n(s)===n))return{};return{path:n}}function Tr(e,t=[]){let{path:r}=Rn(e,t);return r?[r]:[]}var Fr="/var/ts-cloud/artifacts",Uh="/usr/local/bin/ts-cloud-host-cleanup.sh",Qh="ts-cloud-host-cleanup";var Fg=Object.freeze({stagingMaxAgeMinutes:60,artifactMaxAgeDays:2,artifactUploadMaxAgeMinutes:60,bunCacheMaxAgeDays:7,journalMaxAgeDays:14,journalMaxSizeMb:512,containerImageMaxAgeHours:168}),Ug=Object.freeze({artifactMaxAgeDays:0,bunCacheMaxAgeDays:1,journalMaxAgeDays:3,journalMaxSizeMb:256,containerImageMaxAgeHours:24}),Hh=50,Gh=85,Vh="daily";function Bs(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function et(e,t,r=0){if(!Number.isInteger(t)||t<r)throw Error(`hostCleanup: ${e} must be a whole number >= ${r} (got ${t})`)}function Ks(e,t){for(let[r,n]of Object.entries(t))et(`${e}.${r}`,n);et(`${e}.stagingMaxAgeMinutes`,t.stagingMaxAgeMinutes,15),et(`${e}.artifactUploadMaxAgeMinutes`,t.artifactUploadMaxAgeMinutes,15),et(`${e}.journalMaxSizeMb`,t.journalMaxSizeMb,1)}function hc(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(et(`${r}.maxAgeDays`,e.maxAgeDays),e.type!==void 0&&e.type!=="file"&&e.type!=="directory")throw Error(`${r}.type must be 'file' or 'directory'`)}function Ur(e){let t=typeof e==="object"&&e!==null?e:{},r=e!==!1,n={...Fg,...js(t.retention)};Ks("hostCleanup.retention",n);let s=null;if(t.pressure!==!1){let c=typeof t.pressure==="object"?t.pressure:{},f=c.lowWaterPercent??50,h=c.highWaterPercent??85;if(et("hostCleanup.pressure.lowWaterPercent",f),et("hostCleanup.pressure.highWaterPercent",h,1),h>100||f>=h)throw Error(`hostCleanup.pressure: need 0 <= lowWaterPercent < highWaterPercent <= 100 (got ${f} and ${h})`);let g={...Ug,...js(c.escalated)},S=Object.fromEntries(Object.keys(n).map((_)=>[_,Math.min(n[_],g[_]??n[_])]));Ks("hostCleanup.pressure.escalated",S),s={lowWaterPercent:f,highWaterPercent:h,escalated:S}}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(hc),{enabled:r,timer:r&&t.timer!==!1,schedule:i,retention:n,pressure:s,paths:a}}function js(e){return Object.fromEntries(Object.entries(e??{}).filter(([,t])=>t!==void 0))}var Kt={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 On(e){return Object.keys(Kt).map((t)=>`${Kt[t]}=${e[t]}`).join(" ")}var Qe=(e)=>`"$${Kt[e]}"`;function Gs(e){return[`find /var/ts-cloud/staging -xdev -maxdepth 1 -type f -mmin +${Qe("stagingMaxAgeMinutes")} -delete 2>/dev/null || true`,`find /tmp -xdev -maxdepth 1 -type f -name "*-release.tar.gz" -mmin +${Qe("stagingMaxAgeMinutes")} -delete 2>/dev/null || true`,"TS_CLOUD_HC_ARTIFACT_MIN=$((TS_CLOUD_HC_ARTIFACT_DAYS * 1440))",'[ "$TS_CLOUD_HC_ARTIFACT_MIN" -gt 0 ] || TS_CLOUD_HC_ARTIFACT_MIN=1','find /var/ts-cloud/artifacts -xdev -maxdepth 1 -type f -name "*.tar.gz" -mmin +"$TS_CLOUD_HC_ARTIFACT_MIN" -delete 2>/dev/null || true',`find /var/ts-cloud/artifacts -xdev -maxdepth 1 -type f -name ".*.tmp" -mmin +${Qe("artifactUploadMaxAgeMinutes")} -delete 2>/dev/null || true`,...e.map(gc),`journalctl --vacuum-time=${Qe("journalMaxAgeDays")}d --vacuum-size=${Qe("journalMaxSizeMb")}M >/dev/null 2>&1 || true`]}function gc(e){let t=Bs(e.path.replace(/\/+$/,"")),r=Bs(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 Vs(){return[`find /root/.bun/install/cache -xdev -type f -mtime +${Qe("bunCacheMaxAgeDays")} -delete 2>/dev/null || true`,`find /root/.bun/install/cache -xdev -depth -type d -empty -mtime +${Qe("bunCacheMaxAgeDays")} -delete 2>/dev/null || true`,`if command -v docker >/dev/null 2>&1; then docker image prune --all --force --filter "until=\${${Kt.containerImageMaxAgeHours}}h" >/dev/null 2>&1 || true; fi`,`if command -v podman >/dev/null 2>&1; then podman image prune --all --force --filter "until=\${${Kt.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 qs(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 ri(e){let{retention:t,pressure:r,paths:n}=Ur(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)"',On(t),...Gs(n),...Vs(),'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"'];let{lowWaterPercent:a,highWaterPercent:c,escalated:f}=r;return['echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',...qs("TS_CLOUD_HC_BEFORE"),"TS_CLOUD_HC_TIER=normal",On(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",` ${On(f)}`,` echo "[ts-cloud] warning: / at \${TS_CLOUD_HC_BEFORE}% (at or above ${c}%), host cleanup is using shortened retention windows" >&2`,"fi",...Gs(n),'if [ "$TS_CLOUD_HC_TIER" != light ]; then',...Vs().map((h)=>` ${h}`),"fi",'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"',...qs("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 Qg(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",...ri(e),"exit 0"]}function Dn(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 to(e){let t=Ur(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=Dn("/usr/local/bin/ts-cloud-host-cleanup.sh",Qg(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",...Dn("/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"),...Dn("/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 ni(e){let t=to(e);if(!Ur(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']}function Js(e,t,r={}){if(!t.length)return[];let n=Object.entries(r).flatMap(([s,i])=>{if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(s))throw Error("Invalid pre-start environment variable name");if(["PORT","PORT_BACKEND","PORT_ADMIN","PORT_FRONTEND"].includes(s))return[];return[`export ${s}=${Ge(String(i))}`]});return[`cd ${e}`,`if [ -d ${u} ] && command -v pantry >/dev/null 2>&1; then`,` ${Re()}`,"fi",...n,...t]}var Sc=/\.(?:[cm]?[jt]sx?)$/;function ii(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&&!Sc.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 Ws(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.
159
159
  # An eighth of %sMB RAM. Set memoryHigh in config to override.
160
160
  [Service]
161
161
  MemoryAccounting=true
162
162
  MemoryHigh=%sM
163
- ' "$TS_CLOUD_MEM_MB" "$TS_CLOUD_HIGH_MB" > /etc/systemd/system/${e}.d/50-ts-cloud-memory.conf`,"systemctl daemon-reload",'echo "[ts-cloud] memoryHigh=auto resolved to ${TS_CLOUD_HIGH_MB}M (one eighth of ${TS_CLOUD_MEM_MB}M)"',...An()]}function wr(e,t={auto:!0}){let r=t.auto===!1?[]:[`/etc/systemd/system/${e}.d/50-ts-cloud-memory.conf`];for(let n of["/etc/systemd/system.control","/run/systemd/system.control"]){if(t.high)r.push(`${n}/${e}.d/50-MemoryHigh.conf`);if(t.max)r.push(`${n}/${e}.d/50-MemoryMax.conf`)}if(r.length===0)return[];return["TS_CLOUD_MEM_CLEARED=0",...r.map((n)=>`if [ -f ${n} ]; then rm -f ${n}; TS_CLOUD_MEM_CLEARED=1; echo "[ts-cloud] removed ${n}: memory limits now come from config"; fi`),'if [ "$TS_CLOUD_MEM_CLEARED" = 1 ]; then systemctl daemon-reload; fi']}function An(){return[`TS_CLOUD_COMMIT=$(for f in /sys/fs/cgroup/system.slice/*.service/memory.high /sys/fs/cgroup/system.slice/*.slice/*.service/memory.high; do [ -f "$f" ] || continue; v=$(cat "$f" 2>/dev/null); [ "$v" = "max" ] && continue; echo "$v"; done | awk '{s+=$1} END {print int(s/1048576)}')`,"TS_CLOUD_RAM=$(awk '/^MemTotal:/{print int($2/1024)}' /proc/meminfo)",'if [ -n "$TS_CLOUD_COMMIT" ] && [ "$TS_CLOUD_COMMIT" -gt 0 ] && [ "$TS_CLOUD_RAM" -gt 0 ]; then TS_CLOUD_PCT=$((TS_CLOUD_COMMIT * 100 / TS_CLOUD_RAM)); if [ "$TS_CLOUD_PCT" -gt 300 ]; then echo "[ts-cloud] WARNING: services on this box declare ${TS_CLOUD_COMMIT}M of MemoryHigh against ${TS_CLOUD_RAM}M of RAM (${TS_CLOUD_PCT}% committed). Soft ceilings, so this is not fatal - but no ceiling can protect the box once enough of them are drawn on at once."; else echo "[ts-cloud] memory commitment: ${TS_CLOUD_COMMIT}M declared against ${TS_CLOUD_RAM}M RAM (${TS_CLOUD_PCT}%)"; fi; fi']}function vc(e){return[`TS_CLOUD_SLICE=$(systemctl show ${e} -p Slice --value 2>/dev/null || true)`,'if [ -n "$TS_CLOUD_SLICE" ] && [ "$TS_CLOUD_SLICE" != "system.slice" ]; then systemctl set-property --runtime "$TS_CLOUD_SLICE" MemoryHigh=infinity MemoryMax=infinity 2>/dev/null || true; systemctl set-property "$TS_CLOUD_SLICE" MemoryHigh=infinity MemoryMax=infinity 2>/dev/null || true; fi']}var tt={path:"/",intervalSeconds:60,failuresBeforeRestart:3,timeoutSeconds:10,startupGraceSeconds:600,maxBackoffSeconds:3600,backoffBaseSeconds:300};function jt(e,t,r){return typeof e==="number"&&Number.isFinite(e)?Math.max(r,Math.floor(e)):t}function Ys(e){let{unitBase:t,unitPattern:r,port:n}=e,s=e.path&&e.path.startsWith("/")?e.path:tt.path,i=jt(e.intervalSeconds,tt.intervalSeconds,10),a=jt(e.failuresBeforeRestart,tt.failuresBeforeRestart,1),c=jt(e.timeoutSeconds,tt.timeoutSeconds,1),f=jt(e.startupGraceSeconds,tt.startupGraceSeconds,0),h=jt(e.maxBackoffSeconds,tt.maxBackoffSeconds,0),g=Math.min(tt.backoffBaseSeconds,h),S=`/usr/local/sbin/${t}-liveness`,_=`/run/${t}-liveness`,v=`${t}-liveness`,y=`127.0.0.1:${n}${s}`,x=r.includes("@*")?`TS_CLOUD_UNIT=$(systemctl list-units --plain --no-legend --type=service '${r}' 2>/dev/null | awk '{print $1}' | head -1)`:`TS_CLOUD_UNIT=${r}`;return[`cat > ${S} <<'TS_CLOUD_LIVENESS_EOF'`,"#!/bin/sh",`# Liveness check for ${t}, written by ts-cloud on every deploy.`,`# Settings: interval=${i}s timeout=${c}s failures=${a} startup-grace=${f}s max-backoff=${h}s`,"set -eu",`TS_CLOUD_STATE=${_}`,'exec 9>"$TS_CLOUD_STATE.lock"',"flock -n 9 || exit 0",x,'[ -n "$TS_CLOUD_UNIT" ] || exit 0','systemctl is-active --quiet "$TS_CLOUD_UNIT" || exit 0',"TS_CLOUD_RC=0",`curl -s -o /dev/null --max-time ${c} "http://${y}" || TS_CLOUD_RC=$?`,'if [ "$TS_CLOUD_RC" -eq 0 ]; then',' rm -f "$TS_CLOUD_STATE.fail"',' if [ -f "$TS_CLOUD_STATE.restarts" ]; then',` TS_CLOUD_LAST=$(awk '{print $2}' "$TS_CLOUD_STATE.restarts" 2>/dev/null || true)`,` case "$TS_CLOUD_LAST" in ''|*[!0-9]*) TS_CLOUD_LAST=0 ;; esac`,` [ $(($(date +%s) - TS_CLOUD_LAST)) -lt ${h} ] || rm -f "$TS_CLOUD_STATE.restarts"`," fi"," exit 0","fi",'case "$TS_CLOUD_RC" in'," 7) TS_CLOUD_WHY='connection refused' ;;",` 28) TS_CLOUD_WHY='no response within ${c}s' ;;`,' *) TS_CLOUD_WHY="curl exit $TS_CLOUD_RC" ;;',"esac",'TS_CLOUD_SINCE=$(systemctl show "$TS_CLOUD_UNIT" -p ActiveEnterTimestampMonotonic --value 2>/dev/null || true)',"TS_CLOUD_UPTIME=$(cut -d' ' -f1 /proc/uptime 2>/dev/null || true)",`TS_CLOUD_AGE=$(awk -v up="$TS_CLOUD_UPTIME" -v since="$TS_CLOUD_SINCE" 'BEGIN { if (since + 0 > 0 && up + 0 > 0) print int(up - since / 1000000); else print -1 }')`,`case "$TS_CLOUD_AGE" in ''|*[!0-9-]*) TS_CLOUD_AGE=-1 ;; esac`,'if [ "$TS_CLOUD_AGE" -lt 0 ]; then',' TS_CLOUD_PID=$(systemctl show "$TS_CLOUD_UNIT" -p MainPID --value 2>/dev/null || true)',` case "$TS_CLOUD_PID" in ''|0|*[!0-9]*) ;; *) TS_CLOUD_AGE=$(ps -o etimes= -p "$TS_CLOUD_PID" 2>/dev/null | tr -d ' ' || true) ;; esac`,` case "$TS_CLOUD_AGE" in ''|*[!0-9]*) TS_CLOUD_AGE=-1 ;; esac`,"fi",`if [ "$TS_CLOUD_AGE" -ge 0 ] && [ "$TS_CLOUD_AGE" -lt ${f} ]; then`,' rm -f "$TS_CLOUD_STATE.fail"',` logger -t ${v} "$TS_CLOUD_UNIT is \${TS_CLOUD_AGE}s old, inside its ${f}s startup grace; not counting this failed check on ${y} ($TS_CLOUD_WHY)"`," exit 0","fi",'TS_CLOUD_FAILS=$(cat "$TS_CLOUD_STATE.fail" 2>/dev/null || echo 0)',`case "$TS_CLOUD_FAILS" in ''|*[!0-9]*) TS_CLOUD_FAILS=0 ;; esac`,"TS_CLOUD_FAILS=$((TS_CLOUD_FAILS + 1))",'echo "$TS_CLOUD_FAILS" > "$TS_CLOUD_STATE.fail"',`if [ "$TS_CLOUD_FAILS" -lt ${a} ]; then`,` logger -t ${v} "check $TS_CLOUD_FAILS of ${a} failed on ${y} ($TS_CLOUD_WHY)"`," exit 0","fi","TS_CLOUD_NOW=$(date +%s)","TS_CLOUD_STREAK=0","TS_CLOUD_LAST=0",'[ ! -f "$TS_CLOUD_STATE.restarts" ] || read -r TS_CLOUD_STREAK TS_CLOUD_LAST < "$TS_CLOUD_STATE.restarts" || true',`case "$TS_CLOUD_STREAK" in ''|*[!0-9]*) TS_CLOUD_STREAK=0 ;; esac`,`case "$TS_CLOUD_LAST" in ''|*[!0-9]*) TS_CLOUD_LAST=0 ;; esac`,'if [ "$TS_CLOUD_STREAK" -gt 0 ]; then',` TS_CLOUD_WAIT=${g}`," TS_CLOUD_I=1",` while [ "$TS_CLOUD_I" -lt "$TS_CLOUD_STREAK" ] && [ "$TS_CLOUD_WAIT" -lt ${h} ]; do TS_CLOUD_WAIT=$((TS_CLOUD_WAIT * 2)); TS_CLOUD_I=$((TS_CLOUD_I + 1)); done`,` [ "$TS_CLOUD_WAIT" -le ${h} ] || TS_CLOUD_WAIT=${h}`," TS_CLOUD_ELAPSED=$((TS_CLOUD_NOW - TS_CLOUD_LAST))",' if [ "$TS_CLOUD_ELAPSED" -lt "$TS_CLOUD_WAIT" ]; then',` logger -t ${v} "holding off: $TS_CLOUD_STREAK liveness restart(s) in a row have not brought $TS_CLOUD_UNIT back; next restart allowed in $((TS_CLOUD_WAIT - TS_CLOUD_ELAPSED))s ($TS_CLOUD_WHY on ${y})"`," exit 0"," fi","fi","TS_CLOUD_STREAK=$((TS_CLOUD_STREAK + 1))",`logger -t ${v} "no HTTP response on ${y} after $TS_CLOUD_FAILS checks ($TS_CLOUD_WHY); restarting $TS_CLOUD_UNIT (liveness restart $TS_CLOUD_STREAK in a row)"`,'echo "$TS_CLOUD_STREAK $TS_CLOUD_NOW" > "$TS_CLOUD_STATE.restarts"','rm -f "$TS_CLOUD_STATE.fail"','systemctl restart "$TS_CLOUD_UNIT"',"TS_CLOUD_LIVENESS_EOF",`chmod +x ${S}`,`rm -f ${_}.fail ${_}.restarts`,`cat > /etc/systemd/system/${t}-liveness.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=Liveness check for ${t} (managed by ts-cloud)`,"","[Service]","Type=oneshot",`ExecStart=${S}`,"TS_CLOUD_UNIT_EOF",`cat > /etc/systemd/system/${t}-liveness.timer <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=Run the ${t} liveness check every ${i}s`,"","[Timer]",`OnUnitActiveSec=${i}s`,`OnBootSec=${i}s`,"Persistent=true","","[Install]","WantedBy=timers.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",`systemctl enable --now ${t}-liveness.timer >/dev/null 2>&1 || true`]}var Xs=20,xn=3,yc=5,bc=60;function Tc(e){let{paths:t,unitBase:r,releaseId:n,port:s}=e,i=`${r}@${n}.service`,a=`${r}.service`,c=Math.max(1,e.healthGateSeconds??5),f=e.healthCheckPath?e.healthCheckPath.startsWith("/")?e.healthCheckPath:`/${e.healthCheckPath}`:null,h=f?`curl -sf -o /dev/null --max-time ${yc} "http://127.0.0.1:${s}${f}"`:null,g=(S)=>`{ echo "[ts-cloud] release ${n} ${S}" >&2; ts_cloud_restore_previous; exit 1; }`;return[`TS_CLOUD_OLD_UNITS=$(systemctl list-units --plain --no-legend --type=service "${r}@*.service" 2>/dev/null | awk '{print $1}' | grep -v "^${i}$" || true)`,`TS_CLOUD_PREV_CURRENT="$(readlink ${t.current} 2>/dev/null || true)"`,"TS_CLOUD_LEGACY_STOPPED=0","ts_cloud_restore_previous() {",` journalctl -u ${i} -n 50 --no-pager >&2 || true`,` systemctl stop ${i} 2>/dev/null || true`,` systemctl disable ${i} 2>/dev/null || true`,` if [ -n "$TS_CLOUD_PREV_CURRENT" ] && [ -d "$TS_CLOUD_PREV_CURRENT" ]; then ln -sfn "$TS_CLOUD_PREV_CURRENT" ${t.current}.tmp && mv -Tf ${t.current}.tmp ${t.current}; fi`,' for TS_CLOUD_RU in ${TS_CLOUD_OLD_UNITS}; do systemctl enable "$TS_CLOUD_RU" 2>/dev/null || true; systemctl start "$TS_CLOUD_RU" 2>/dev/null || true; done',` if [ "$TS_CLOUD_LEGACY_STOPPED" -eq 1 ]; then systemctl start ${a} 2>/dev/null || true; fi`,' if [ -n "$TS_CLOUD_OLD_UNITS" ] || [ "$TS_CLOUD_LEGACY_STOPPED" -eq 1 ]; then echo "[ts-cloud] previous release restored and serving" >&2; else echo "[ts-cloud] there was no previous release to restore" >&2; fi',"}",`if [ -f /etc/systemd/system/${a} ] && systemctl is-active --quiet ${a}; then echo "[ts-cloud] retiring pre-zero-downtime unit ${a} (one-time restart cutover)"; systemctl stop ${a}; TS_CLOUD_LEGACY_STOPPED=1; fi`,'TS_CLOUD_STARTED_AT="@$(date +%s)"',`systemctl restart ${i}`,`TS_CLOUD_GATE_OK=1; for TS_CLOUD_I in $(seq 1 ${c}); do sleep 1; systemctl is-active --quiet ${i} || { TS_CLOUD_GATE_OK=0; break; }; done`,'if [ "$TS_CLOUD_GATE_OK" -ne 1 ]; then',` if journalctl -u ${i} --since "$TS_CLOUD_STARTED_AT" -o cat --no-pager 2>/dev/null | grep -iE 'EADDRINUSE|address already in use|port [0-9]+ (is )?in use|Failed to start server' >/dev/null; then`,` echo "[ts-cloud] release ${n} could not share :${s} with the previous release (no SO_REUSEPORT?) — retiring it and retrying" >&2`,' for TS_CLOUD_RU in ${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_RU" 2>/dev/null || true; done',` systemctl restart ${i}`,` for TS_CLOUD_I in $(seq 1 ${c}); do sleep 1; systemctl is-active --quiet ${i} || ${g("failed its health gate on the free port")}; done`," else",` ${g("crashed on start — the previous release was never stopped")}`," fi","fi",`if ss -ltnpH "sport = :${s}" >/dev/null 2>&1; then`," TS_CLOUD_BOUND=0",` for TS_CLOUD_I in $(seq 1 ${bc}); do`,` TS_CLOUD_NEW_PID="$(systemctl show -p MainPID --value ${i} 2>/dev/null || true)"`,` if [ -n "$TS_CLOUD_NEW_PID" ] && [ "$TS_CLOUD_NEW_PID" != "0" ] && ss -ltnpH "sport = :${s}" 2>/dev/null | grep "pid=$TS_CLOUD_NEW_PID," >/dev/null; then TS_CLOUD_BOUND=1; break; fi`,` systemctl is-active --quiet ${i} || break`,` sleep ${xn}`," done",` [ "$TS_CLOUD_BOUND" -eq 1 ] || ${g(`never took :${s}`)}`,"else",' echo "[ts-cloud] cannot read listener PIDs on this host — the response probes run without the bind check" >&2',"fi",...h?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${Xs}); do if ${h}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${xn}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${g(`never answered ${f}`)}`]:[],...dt(t),`systemctl enable ${i} 2>/dev/null || true`,'for TS_CLOUD_U in ${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done',`TS_CLOUD_LISTENING=0; for TS_CLOUD_I in $(seq 1 ${c}); do if ss -ltnH "sport = :${s}" 2>/dev/null | grep . >/dev/null; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done`,`if [ "$TS_CLOUD_LISTENING" -ne 1 ]; then echo "[ts-cloud] nothing is listening on ${s} after retiring the previous release — restarting ${i} on the now-free port" >&2; systemctl restart ${i}; for TS_CLOUD_I in $(seq 1 ${c}); do if ss -ltnH "sport = :${s}" 2>/dev/null | grep . >/dev/null; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done; fi`,`[ "$TS_CLOUD_LISTENING" -eq 1 ] || ${g(`is active but never bound :${s}`)}`,...h?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${Xs}); do if ${h}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${xn}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${g(`stopped answering ${f} once it served alone`)}`]:[],...Pn(t),`systemctl list-unit-files --plain --no-legend "${r}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v -e "^${i}$" -e "^${r}@\\.service$" || true; } | while read -r TS_CLOUD_U; do systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done`,`if [ -f /etc/systemd/system/${a} ]; then systemctl disable ${a} 2>/dev/null || true; rm -f /etc/systemd/system/${a}; systemctl daemon-reload; fi`]}function Qs(e,t){if(!t.length)return[];let r=We(e.release);return[`if [ -e ${r} ] || [ -L ${r} ]; then`,...t,"fi"]}function si(e){let{siteName:t,slug:r,artifactFetch:n,releaseId:s,execStart:i,envEntries:a,port:c,keepReleases:f=zt,preStartCommands:h=[],postActivateCommands:g=[],beforeResetCommands:S=[],healthCheckPath:_,healthGateSeconds:v=5,liveness:y,memoryHigh:C="auto",memoryMax:x,cpuWeight:q,ioWeight:H,tasksMax:R,stopTimeout:L}=e,I=[...q!=null?[`CPUWeight=${q}`]:[],...H!=null?[`IOWeight=${H}`]:[],...R!=null?[`TasksMax=${R}`]:[],...L?[`TimeoutStopSec=${L}`]:[]],V=e.zeroDowntime??c!=null,W=e.appDir??`/var/www/${t}`,K=Zt(W,s),te=`${r}-${t}`,Z=`${te}.service`,re=ai(r,t,s),ae=e.sharedPaths??[],ie=Ms([".env",...ae,...Tr(a,ae)]),ne=gr(a),me=Js(K.release,h,a),Se=["set -euo pipefail",...yn(K),...n,...Bt(K,ie),...Qs(K,S),Tn(K),...bn(K),`tar xzf ${re} -C "$TS_CLOUD_STAGED"`,`rm -f ${re}`,`cat > ${K.shared}/.env <<'TS_CLOUD_ENV_EOF'`,ne,"TS_CLOUD_ENV_EOF",`chmod 600 ${K.shared}/.env`,...wn(K),`find ${K.release} -maxdepth 1 \\( -type f -o -type l \\) -name '.env*' ! -name '.env.example' ! -name '*.example' -delete`,`sed -i -E '/^[[:space:]]*(PORT|PORT_BACKEND|PORT_ADMIN|PORT_FRONTEND)[[:space:]]*=/d' ${K.shared}/.env 2>/dev/null || true`,...yr(K,ie),...me,...e.isolation?ks(e.slug||t,K.base,ie.flatMap((T)=>typeof T==="string"||!T.target?[]:[T.target])):[]];if(V&&c!=null){let T=`${te}@${s}.service`,k=_?_.startsWith("/")?_:`/${_}`:null;return[...Se,`cat > /etc/systemd/system/${te}@.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} release %i (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",...e.isolation?Mt(pt(e.slug||t),K.base,e.slug||t):[],`WorkingDirectory=${K.releases}/%i`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...C&&C!=="auto"?[`MemoryHigh=${C}`]:[],...x?[`MemoryMax=${x}`]:[],...I,`EnvironmentFile=${K.releases}/%i/.env`,`Environment=PORT=${c}`,`Environment=STX_IMAGE_CACHE_DIR=${vr(K)}`,`Environment=STX_BUNDLE_CACHE_DIR=${Ft(K)}`,`Environment=STX_BUNDLE_CACHE_DIR=${Ft(K)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...C==="auto"?Ws(`${te}@.service`):[...wr(`${te}@.service`),...An()],...vc(T),...Tc({paths:K,unitBase:te,releaseId:s,port:c,healthCheckPath:k,healthGateSeconds:v}),...g,...mt(K,f),...y===!1?[]:Ys({...y,unitBase:te,unitPattern:`${te}@*.service`,port:c,path:y?.path??_})]}return[...Se,`cat > /etc/systemd/system/${Z} <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",...e.isolation?Mt(pt(e.slug||t),K.base,e.slug||t):[],`WorkingDirectory=${K.current}`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...C&&C!=="auto"?[`MemoryHigh=${C}`]:[],...x?[`MemoryMax=${x}`]:[],...I,`EnvironmentFile=${K.current}/.env`,...c?[`Environment=PORT=${c}`]:[],`Environment=STX_IMAGE_CACHE_DIR=${vr(K)}`,`Environment=STX_BUNDLE_CACHE_DIR=${Ft(K)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...wr(Z,{auto:C!=="auto",high:C!=="auto",max:Boolean(x)}),...C==="auto"?Ws(Z):An(),`systemctl enable ${Z}`,`TS_CLOUD_PREV_CURRENT="$(readlink ${K.current} 2>/dev/null || true)"`,...dt(K),`systemctl restart ${Z}`,`for TS_CLOUD_I in $(seq 1 ${Math.max(1,v)}); do sleep 1; systemctl is-active --quiet ${Z} || { echo "[ts-cloud] release ${s} of ${Z} did not stay up — restoring the previous release" >&2; journalctl -u ${Z} -n 50 --no-pager >&2 || true; if [ -n "$TS_CLOUD_PREV_CURRENT" ] && [ -d "$TS_CLOUD_PREV_CURRENT" ] && [ "$(readlink -f "$TS_CLOUD_PREV_CURRENT")" != "$(readlink -f ${K.release})" ]; then ln -sfn "$TS_CLOUD_PREV_CURRENT" ${K.current}.tmp && mv -Tf ${K.current}.tmp ${K.current}; systemctl restart ${Z} || true; fi; exit 1; }; done`,...Pn(K),...g,...mt(K,f),...y===!1||!c?[]:Ys({...y,unitBase:te,unitPattern:Z,port:c,path:y?.path??_})]}function oi(e){let{siteName:t,artifactFetch:r,releaseId:n,keepReleases:s=zt,preStartCommands:i=[],postActivateCommands:a=[],beforeResetCommands:c=[]}=e,f=e.appDir??`/var/www/${t}`,h=Zt(f,n),g=ai(e.slug,t,n),S=Js(h.release,i);return["set -euo pipefail",...yn(h),...r,...Bt(h,[]),...Qs(h,c),Tn(h),...bn(h),`tar xzf ${g} -C "$TS_CLOUD_STAGED"`,...wn(h),`rm -f ${g}`,...S,...dt(h),...a,...mt(h,s)]}function ai(e,t,r){return`/tmp/${[e,t,r].filter(Boolean).join("-")}-release.tar.gz`}function $c(e,t,r,n){return[`aws s3 cp "s3://${e}/${t}" ${n} --region ${r}`]}function Mc(e,t){return[`mv "${e}" ${t}`]}function We(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function Cr(e,t,r){return["set -euo pipefail",`chmod 600 ${We(e)}`,`mv -f -- ${We(e)} ${We(t)}`,`cp -- ${We(t)} ${We(r)}`].join(`
164
- `)}function Pr(e){return`rm -f -- ${We(e)} 2>/dev/null || true`}function In(e={}){let t=Math.max(1,e.appServers??e.instances??1),r=!!e.servicesServer||t>1,n=t>1||!!e.server?.loadBalancer;return{appServers:t,loadBalancer:n,dedicatedServices:r,servicesOnApp:!r}}function uo(e,t){let r={REDIS_HOST:e,MEILISEARCH_HOST:`http://${e}:7700`};if(t?.name){if(r.DB_CONNECTION=t.engine==="postgres"?"pgsql":"mysql",r.DB_HOST=e,r.DB_PORT=String(t.port??(t.engine==="postgres"?5432:3306)),r.DB_DATABASE=t.name,t.username)r.DB_USERNAME=t.username;if(t.password)r.DB_PASSWORD=t.password}return r}function Ln(e){let t=e.infrastructure?.compute??{},r=p(e);return[...cr(t.managedServices??{mysql:!0,redis:!0},{bindPrivate:!0}),...ct(r,t.managedServices??{mysql:!0}),...Me(!0),...Le(!0),...lt(t.sshKeys),...Je(e.notifications),...t.backups?.enabled?[...Ut({database:r,backups:t.backups})]:[]]}var Gt=["-S","ssh"];function ci(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 Qr(e,t,r={}){let n=Bun.spawn(["ssh",...ci(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 be(e,t,r={}){let n=await Qr(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 Fc(e,t,r,n={}){let s=Bun.spawn(["scp",...Gt,...ci(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 At(e,t={}){let r=t.timeoutMs??180000,n=t.pollIntervalMs??5000,s=Date.now();while(Date.now()-s<r){let i=await Qr(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 Uc(e,t={}){let r=t.timeoutMs??300000,n=t.pollIntervalMs??5000,s=Date.now();while(Date.now()-s<r){let i=await Qr(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 di(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(`
163
+ ' "$TS_CLOUD_MEM_MB" "$TS_CLOUD_HIGH_MB" > /etc/systemd/system/${e}.d/50-ts-cloud-memory.conf`,"systemctl daemon-reload",'echo "[ts-cloud] memoryHigh=auto resolved to ${TS_CLOUD_HIGH_MB}M (one eighth of ${TS_CLOUD_MEM_MB}M)"',...An()]}function wr(e,t={auto:!0}){let r=t.auto===!1?[]:[`/etc/systemd/system/${e}.d/50-ts-cloud-memory.conf`];for(let n of["/etc/systemd/system.control","/run/systemd/system.control"]){if(t.high)r.push(`${n}/${e}.d/50-MemoryHigh.conf`);if(t.max)r.push(`${n}/${e}.d/50-MemoryMax.conf`)}if(r.length===0)return[];return["TS_CLOUD_MEM_CLEARED=0",...r.map((n)=>`if [ -f ${n} ]; then rm -f ${n}; TS_CLOUD_MEM_CLEARED=1; echo "[ts-cloud] removed ${n}: memory limits now come from config"; fi`),'if [ "$TS_CLOUD_MEM_CLEARED" = 1 ]; then systemctl daemon-reload; fi']}function An(){return[`TS_CLOUD_COMMIT=$(for f in /sys/fs/cgroup/system.slice/*.service/memory.high /sys/fs/cgroup/system.slice/*.slice/*.service/memory.high; do [ -f "$f" ] || continue; v=$(cat "$f" 2>/dev/null); [ "$v" = "max" ] && continue; echo "$v"; done | awk '{s+=$1} END {print int(s/1048576)}')`,"TS_CLOUD_RAM=$(awk '/^MemTotal:/{print int($2/1024)}' /proc/meminfo)",'if [ -n "$TS_CLOUD_COMMIT" ] && [ "$TS_CLOUD_COMMIT" -gt 0 ] && [ "$TS_CLOUD_RAM" -gt 0 ]; then TS_CLOUD_PCT=$((TS_CLOUD_COMMIT * 100 / TS_CLOUD_RAM)); if [ "$TS_CLOUD_PCT" -gt 300 ]; then echo "[ts-cloud] WARNING: services on this box declare ${TS_CLOUD_COMMIT}M of MemoryHigh against ${TS_CLOUD_RAM}M of RAM (${TS_CLOUD_PCT}% committed). Soft ceilings, so this is not fatal - but no ceiling can protect the box once enough of them are drawn on at once."; else echo "[ts-cloud] memory commitment: ${TS_CLOUD_COMMIT}M declared against ${TS_CLOUD_RAM}M RAM (${TS_CLOUD_PCT}%)"; fi; fi']}function vc(e){return[`TS_CLOUD_SLICE=$(systemctl show ${e} -p Slice --value 2>/dev/null || true)`,'if [ -n "$TS_CLOUD_SLICE" ] && [ "$TS_CLOUD_SLICE" != "system.slice" ]; then systemctl set-property --runtime "$TS_CLOUD_SLICE" MemoryHigh=infinity MemoryMax=infinity 2>/dev/null || true; systemctl set-property "$TS_CLOUD_SLICE" MemoryHigh=infinity MemoryMax=infinity 2>/dev/null || true; fi']}var tt={path:"/",intervalSeconds:60,failuresBeforeRestart:3,timeoutSeconds:10,startupGraceSeconds:600,maxBackoffSeconds:3600,backoffBaseSeconds:300};function jt(e,t,r){return typeof e==="number"&&Number.isFinite(e)?Math.max(r,Math.floor(e)):t}function Ys(e){let{unitBase:t,unitPattern:r,port:n}=e,s=e.path&&e.path.startsWith("/")?e.path:tt.path,i=jt(e.intervalSeconds,tt.intervalSeconds,10),a=jt(e.failuresBeforeRestart,tt.failuresBeforeRestart,1),c=jt(e.timeoutSeconds,tt.timeoutSeconds,1),f=jt(e.startupGraceSeconds,tt.startupGraceSeconds,0),h=jt(e.maxBackoffSeconds,tt.maxBackoffSeconds,0),g=Math.min(tt.backoffBaseSeconds,h),S=`/usr/local/sbin/${t}-liveness`,_=`/run/${t}-liveness`,v=`${t}-liveness`,y=`127.0.0.1:${n}${s}`,x=r.includes("@*")?`TS_CLOUD_UNIT=$(systemctl list-units --plain --no-legend --type=service '${r}' 2>/dev/null | awk '{print $1}' | head -1)`:`TS_CLOUD_UNIT=${r}`;return[`cat > ${S} <<'TS_CLOUD_LIVENESS_EOF'`,"#!/bin/sh",`# Liveness check for ${t}, written by ts-cloud on every deploy.`,`# Settings: interval=${i}s timeout=${c}s failures=${a} startup-grace=${f}s max-backoff=${h}s`,"set -eu",`TS_CLOUD_STATE=${_}`,'exec 9>"$TS_CLOUD_STATE.lock"',"flock -n 9 || exit 0",x,'[ -n "$TS_CLOUD_UNIT" ] || exit 0','systemctl is-active --quiet "$TS_CLOUD_UNIT" || exit 0',"TS_CLOUD_RC=0",`curl -s -o /dev/null --max-time ${c} "http://${y}" || TS_CLOUD_RC=$?`,'if [ "$TS_CLOUD_RC" -eq 0 ]; then',' rm -f "$TS_CLOUD_STATE.fail"',' if [ -f "$TS_CLOUD_STATE.restarts" ]; then',` TS_CLOUD_LAST=$(awk '{print $2}' "$TS_CLOUD_STATE.restarts" 2>/dev/null || true)`,` case "$TS_CLOUD_LAST" in ''|*[!0-9]*) TS_CLOUD_LAST=0 ;; esac`,` [ $(($(date +%s) - TS_CLOUD_LAST)) -lt ${h} ] || rm -f "$TS_CLOUD_STATE.restarts"`," fi"," exit 0","fi",'case "$TS_CLOUD_RC" in'," 7) TS_CLOUD_WHY='connection refused' ;;",` 28) TS_CLOUD_WHY='no response within ${c}s' ;;`,' *) TS_CLOUD_WHY="curl exit $TS_CLOUD_RC" ;;',"esac",'TS_CLOUD_SINCE=$(systemctl show "$TS_CLOUD_UNIT" -p ActiveEnterTimestampMonotonic --value 2>/dev/null || true)',"TS_CLOUD_UPTIME=$(cut -d' ' -f1 /proc/uptime 2>/dev/null || true)",`TS_CLOUD_AGE=$(awk -v up="$TS_CLOUD_UPTIME" -v since="$TS_CLOUD_SINCE" 'BEGIN { if (since + 0 > 0 && up + 0 > 0) print int(up - since / 1000000); else print -1 }')`,`case "$TS_CLOUD_AGE" in ''|*[!0-9-]*) TS_CLOUD_AGE=-1 ;; esac`,'if [ "$TS_CLOUD_AGE" -lt 0 ]; then',' TS_CLOUD_PID=$(systemctl show "$TS_CLOUD_UNIT" -p MainPID --value 2>/dev/null || true)',` case "$TS_CLOUD_PID" in ''|0|*[!0-9]*) ;; *) TS_CLOUD_AGE=$(ps -o etimes= -p "$TS_CLOUD_PID" 2>/dev/null | tr -d ' ' || true) ;; esac`,` case "$TS_CLOUD_AGE" in ''|*[!0-9]*) TS_CLOUD_AGE=-1 ;; esac`,"fi",`if [ "$TS_CLOUD_AGE" -ge 0 ] && [ "$TS_CLOUD_AGE" -lt ${f} ]; then`,' rm -f "$TS_CLOUD_STATE.fail"',` logger -t ${v} "$TS_CLOUD_UNIT is \${TS_CLOUD_AGE}s old, inside its ${f}s startup grace; not counting this failed check on ${y} ($TS_CLOUD_WHY)"`," exit 0","fi",'TS_CLOUD_FAILS=$(cat "$TS_CLOUD_STATE.fail" 2>/dev/null || echo 0)',`case "$TS_CLOUD_FAILS" in ''|*[!0-9]*) TS_CLOUD_FAILS=0 ;; esac`,"TS_CLOUD_FAILS=$((TS_CLOUD_FAILS + 1))",'echo "$TS_CLOUD_FAILS" > "$TS_CLOUD_STATE.fail"',`if [ "$TS_CLOUD_FAILS" -lt ${a} ]; then`,` logger -t ${v} "check $TS_CLOUD_FAILS of ${a} failed on ${y} ($TS_CLOUD_WHY)"`," exit 0","fi","TS_CLOUD_NOW=$(date +%s)","TS_CLOUD_STREAK=0","TS_CLOUD_LAST=0",'[ ! -f "$TS_CLOUD_STATE.restarts" ] || read -r TS_CLOUD_STREAK TS_CLOUD_LAST < "$TS_CLOUD_STATE.restarts" || true',`case "$TS_CLOUD_STREAK" in ''|*[!0-9]*) TS_CLOUD_STREAK=0 ;; esac`,`case "$TS_CLOUD_LAST" in ''|*[!0-9]*) TS_CLOUD_LAST=0 ;; esac`,'if [ "$TS_CLOUD_STREAK" -gt 0 ]; then',` TS_CLOUD_WAIT=${g}`," TS_CLOUD_I=1",` while [ "$TS_CLOUD_I" -lt "$TS_CLOUD_STREAK" ] && [ "$TS_CLOUD_WAIT" -lt ${h} ]; do TS_CLOUD_WAIT=$((TS_CLOUD_WAIT * 2)); TS_CLOUD_I=$((TS_CLOUD_I + 1)); done`,` [ "$TS_CLOUD_WAIT" -le ${h} ] || TS_CLOUD_WAIT=${h}`," TS_CLOUD_ELAPSED=$((TS_CLOUD_NOW - TS_CLOUD_LAST))",' if [ "$TS_CLOUD_ELAPSED" -lt "$TS_CLOUD_WAIT" ]; then',` logger -t ${v} "holding off: $TS_CLOUD_STREAK liveness restart(s) in a row have not brought $TS_CLOUD_UNIT back; next restart allowed in $((TS_CLOUD_WAIT - TS_CLOUD_ELAPSED))s ($TS_CLOUD_WHY on ${y})"`," exit 0"," fi","fi","TS_CLOUD_STREAK=$((TS_CLOUD_STREAK + 1))",`logger -t ${v} "no HTTP response on ${y} after $TS_CLOUD_FAILS checks ($TS_CLOUD_WHY); restarting $TS_CLOUD_UNIT (liveness restart $TS_CLOUD_STREAK in a row)"`,'echo "$TS_CLOUD_STREAK $TS_CLOUD_NOW" > "$TS_CLOUD_STATE.restarts"','rm -f "$TS_CLOUD_STATE.fail"','systemctl restart "$TS_CLOUD_UNIT"',"TS_CLOUD_LIVENESS_EOF",`chmod +x ${S}`,`rm -f ${_}.fail ${_}.restarts`,`cat > /etc/systemd/system/${t}-liveness.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=Liveness check for ${t} (managed by ts-cloud)`,"","[Service]","Type=oneshot",`ExecStart=${S}`,"TS_CLOUD_UNIT_EOF",`cat > /etc/systemd/system/${t}-liveness.timer <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=Run the ${t} liveness check every ${i}s`,"","[Timer]",`OnUnitActiveSec=${i}s`,`OnBootSec=${i}s`,"Persistent=true","","[Install]","WantedBy=timers.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",`systemctl enable --now ${t}-liveness.timer >/dev/null 2>&1 || true`]}var Xs=20,xn=3,yc=5,bc=60;function Tc(e){let{paths:t,unitBase:r,releaseId:n,port:s}=e,i=`${r}@${n}.service`,a=`${r}.service`,c=Math.max(1,e.healthGateSeconds??5),f=e.healthCheckPath?e.healthCheckPath.startsWith("/")?e.healthCheckPath:`/${e.healthCheckPath}`:null,h=f?`curl -sf -o /dev/null --max-time ${yc} "http://127.0.0.1:${s}${f}"`:null,g=(S)=>`{ echo "[ts-cloud] release ${n} ${S}" >&2; ts_cloud_restore_previous; exit 1; }`;return[`TS_CLOUD_OLD_UNITS=$(systemctl list-units --plain --no-legend --type=service "${r}@*.service" 2>/dev/null | awk '{print $1}' | grep -v "^${i}$" || true)`,`TS_CLOUD_PREV_CURRENT="$(readlink ${t.current} 2>/dev/null || true)"`,"TS_CLOUD_LEGACY_STOPPED=0","ts_cloud_restore_previous() {",` journalctl -u ${i} -n 50 --no-pager >&2 || true`,` systemctl stop ${i} 2>/dev/null || true`,` systemctl disable ${i} 2>/dev/null || true`,` if [ -n "$TS_CLOUD_PREV_CURRENT" ] && [ -d "$TS_CLOUD_PREV_CURRENT" ]; then ln -sfn "$TS_CLOUD_PREV_CURRENT" ${t.current}.tmp && mv -Tf ${t.current}.tmp ${t.current}; fi`,' for TS_CLOUD_RU in ${TS_CLOUD_OLD_UNITS}; do systemctl enable "$TS_CLOUD_RU" 2>/dev/null || true; systemctl start "$TS_CLOUD_RU" 2>/dev/null || true; done',` if [ "$TS_CLOUD_LEGACY_STOPPED" -eq 1 ]; then systemctl start ${a} 2>/dev/null || true; fi`,' if [ -n "$TS_CLOUD_OLD_UNITS" ] || [ "$TS_CLOUD_LEGACY_STOPPED" -eq 1 ]; then echo "[ts-cloud] previous release restored and serving" >&2; else echo "[ts-cloud] there was no previous release to restore" >&2; fi',"}",`if [ -f /etc/systemd/system/${a} ] && systemctl is-active --quiet ${a}; then echo "[ts-cloud] retiring pre-zero-downtime unit ${a} (one-time restart cutover)"; systemctl stop ${a}; TS_CLOUD_LEGACY_STOPPED=1; fi`,'TS_CLOUD_STARTED_AT="@$(date +%s)"',`systemctl restart ${i}`,`TS_CLOUD_GATE_OK=1; for TS_CLOUD_I in $(seq 1 ${c}); do sleep 1; systemctl is-active --quiet ${i} || { TS_CLOUD_GATE_OK=0; break; }; done`,'if [ "$TS_CLOUD_GATE_OK" -ne 1 ]; then',` if journalctl -u ${i} --since "$TS_CLOUD_STARTED_AT" -o cat --no-pager 2>/dev/null | grep -iE 'EADDRINUSE|address already in use|port [0-9]+ (is )?in use|Failed to start server' >/dev/null; then`,` echo "[ts-cloud] release ${n} could not share :${s} with the previous release (no SO_REUSEPORT?) — retiring it and retrying" >&2`,' for TS_CLOUD_RU in ${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_RU" 2>/dev/null || true; done',` systemctl restart ${i}`,` for TS_CLOUD_I in $(seq 1 ${c}); do sleep 1; systemctl is-active --quiet ${i} || ${g("failed its health gate on the free port")}; done`," else",` ${g("crashed on start — the previous release was never stopped")}`," fi","fi",`if ss -ltnpH "sport = :${s}" >/dev/null 2>&1; then`," TS_CLOUD_BOUND=0",` for TS_CLOUD_I in $(seq 1 ${bc}); do`,` TS_CLOUD_NEW_PID="$(systemctl show -p MainPID --value ${i} 2>/dev/null || true)"`,` if [ -n "$TS_CLOUD_NEW_PID" ] && [ "$TS_CLOUD_NEW_PID" != "0" ] && ss -ltnpH "sport = :${s}" 2>/dev/null | grep "pid=$TS_CLOUD_NEW_PID," >/dev/null; then TS_CLOUD_BOUND=1; break; fi`,` systemctl is-active --quiet ${i} || break`,` sleep ${xn}`," done",` [ "$TS_CLOUD_BOUND" -eq 1 ] || ${g(`never took :${s}`)}`,"else",' echo "[ts-cloud] cannot read listener PIDs on this host — the response probes run without the bind check" >&2',"fi",...h?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${Xs}); do if ${h}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${xn}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${g(`never answered ${f}`)}`]:[],...dt(t),`systemctl enable ${i} 2>/dev/null || true`,'for TS_CLOUD_U in ${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done',`TS_CLOUD_LISTENING=0; for TS_CLOUD_I in $(seq 1 ${c}); do if ss -ltnH "sport = :${s}" 2>/dev/null | grep . >/dev/null; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done`,`if [ "$TS_CLOUD_LISTENING" -ne 1 ]; then echo "[ts-cloud] nothing is listening on ${s} after retiring the previous release — restarting ${i} on the now-free port" >&2; systemctl restart ${i}; for TS_CLOUD_I in $(seq 1 ${c}); do if ss -ltnH "sport = :${s}" 2>/dev/null | grep . >/dev/null; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done; fi`,`[ "$TS_CLOUD_LISTENING" -eq 1 ] || ${g(`is active but never bound :${s}`)}`,...h?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${Xs}); do if ${h}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${xn}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${g(`stopped answering ${f} once it served alone`)}`]:[],...Pn(t),`systemctl list-unit-files --plain --no-legend "${r}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v -e "^${i}$" -e "^${r}@\\.service$" || true; } | while read -r TS_CLOUD_U; do systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done`,`if [ -f /etc/systemd/system/${a} ]; then systemctl disable ${a} 2>/dev/null || true; rm -f /etc/systemd/system/${a}; systemctl daemon-reload; fi`]}function Qs(e,t){if(!t.length)return[];let r=Ge(e.release);return[`if [ -e ${r} ] || [ -L ${r} ]; then`,...t,"fi"]}function si(e){let{siteName:t,slug:r,artifactFetch:n,releaseId:s,execStart:i,envEntries:a,port:c,keepReleases:f=zt,preStartCommands:h=[],postActivateCommands:g=[],beforeResetCommands:S=[],healthCheckPath:_,healthGateSeconds:v=5,liveness:y,memoryHigh:C="auto",memoryMax:x,cpuWeight:q,ioWeight:H,tasksMax:R,stopTimeout:L}=e,I=[...q!=null?[`CPUWeight=${q}`]:[],...H!=null?[`IOWeight=${H}`]:[],...R!=null?[`TasksMax=${R}`]:[],...L?[`TimeoutStopSec=${L}`]:[]],V=e.zeroDowntime??c!=null,W=e.appDir??`/var/www/${t}`,K=Zt(W,s),te=`${r}-${t}`,Z=`${te}.service`,re=ai(r,t,s),ae=e.sharedPaths??[],ie=Ms([".env",...ae,...Tr(a,ae)]),ne=gr(a),me=Js(K.release,h,a),Se=["set -euo pipefail",...yn(K),...n,...Bt(K,ie),...Qs(K,S),Tn(K),...bn(K),`tar xzf ${re} -C "$TS_CLOUD_STAGED"`,`rm -f ${re}`,`cat > ${K.shared}/.env <<'TS_CLOUD_ENV_EOF'`,ne,"TS_CLOUD_ENV_EOF",`chmod 600 ${K.shared}/.env`,...wn(K),`find ${K.release} -maxdepth 1 \\( -type f -o -type l \\) -name '.env*' ! -name '.env.example' ! -name '*.example' -delete`,`sed -i -E '/^[[:space:]]*(PORT|PORT_BACKEND|PORT_ADMIN|PORT_FRONTEND)[[:space:]]*=/d' ${K.shared}/.env 2>/dev/null || true`,...yr(K,ie),...me,...e.isolation?ks(e.slug||t,K.base,ie.flatMap((T)=>typeof T==="string"||!T.target?[]:[T.target])):[]];if(V&&c!=null){let T=`${te}@${s}.service`,k=_?_.startsWith("/")?_:`/${_}`:null;return[...Se,`cat > /etc/systemd/system/${te}@.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} release %i (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",...e.isolation?Mt(pt(e.slug||t),K.base,e.slug||t):[],`WorkingDirectory=${K.releases}/%i`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...C&&C!=="auto"?[`MemoryHigh=${C}`]:[],...x?[`MemoryMax=${x}`]:[],...I,`EnvironmentFile=${K.releases}/%i/.env`,`Environment=PORT=${c}`,`Environment=STX_IMAGE_CACHE_DIR=${vr(K)}`,`Environment=STX_BUNDLE_CACHE_DIR=${Ft(K)}`,`Environment=STX_BUNDLE_CACHE_DIR=${Ft(K)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...C==="auto"?Ws(`${te}@.service`):[...wr(`${te}@.service`),...An()],...vc(T),...Tc({paths:K,unitBase:te,releaseId:s,port:c,healthCheckPath:k,healthGateSeconds:v}),...g,...mt(K,f),...y===!1?[]:Ys({...y,unitBase:te,unitPattern:`${te}@*.service`,port:c,path:y?.path??_})]}return[...Se,`cat > /etc/systemd/system/${Z} <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",...e.isolation?Mt(pt(e.slug||t),K.base,e.slug||t):[],`WorkingDirectory=${K.current}`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...C&&C!=="auto"?[`MemoryHigh=${C}`]:[],...x?[`MemoryMax=${x}`]:[],...I,`EnvironmentFile=${K.current}/.env`,...c?[`Environment=PORT=${c}`]:[],`Environment=STX_IMAGE_CACHE_DIR=${vr(K)}`,`Environment=STX_BUNDLE_CACHE_DIR=${Ft(K)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...wr(Z,{auto:C!=="auto",high:C!=="auto",max:Boolean(x)}),...C==="auto"?Ws(Z):An(),`systemctl enable ${Z}`,`TS_CLOUD_PREV_CURRENT="$(readlink ${K.current} 2>/dev/null || true)"`,...dt(K),`systemctl restart ${Z}`,`for TS_CLOUD_I in $(seq 1 ${Math.max(1,v)}); do sleep 1; systemctl is-active --quiet ${Z} || { echo "[ts-cloud] release ${s} of ${Z} did not stay up — restoring the previous release" >&2; journalctl -u ${Z} -n 50 --no-pager >&2 || true; if [ -n "$TS_CLOUD_PREV_CURRENT" ] && [ -d "$TS_CLOUD_PREV_CURRENT" ] && [ "$(readlink -f "$TS_CLOUD_PREV_CURRENT")" != "$(readlink -f ${K.release})" ]; then ln -sfn "$TS_CLOUD_PREV_CURRENT" ${K.current}.tmp && mv -Tf ${K.current}.tmp ${K.current}; systemctl restart ${Z} || true; fi; exit 1; }; done`,...Pn(K),...g,...mt(K,f),...y===!1||!c?[]:Ys({...y,unitBase:te,unitPattern:Z,port:c,path:y?.path??_})]}function oi(e){let{siteName:t,artifactFetch:r,releaseId:n,keepReleases:s=zt,preStartCommands:i=[],postActivateCommands:a=[],beforeResetCommands:c=[]}=e,f=e.appDir??`/var/www/${t}`,h=Zt(f,n),g=ai(e.slug,t,n),S=Js(h.release,i);return["set -euo pipefail",...yn(h),...r,...Bt(h,[]),...Qs(h,c),Tn(h),...bn(h),`tar xzf ${g} -C "$TS_CLOUD_STAGED"`,...wn(h),`rm -f ${g}`,...S,...dt(h),...a,...mt(h,s)]}function ai(e,t,r){return`/tmp/${[e,t,r].filter(Boolean).join("-")}-release.tar.gz`}function $c(e,t,r,n){return[`aws s3 cp "s3://${e}/${t}" ${n} --region ${r}`]}function Mc(e,t){return[`mv "${e}" ${t}`]}function Ge(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function Cr(e,t,r){return["set -euo pipefail",`chmod 600 ${Ge(e)}`,`mv -f -- ${Ge(e)} ${Ge(t)}`,`cp -- ${Ge(t)} ${Ge(r)}`].join(`
164
+ `)}function Pr(e){return`rm -f -- ${Ge(e)} 2>/dev/null || true`}function In(e={}){let t=Math.max(1,e.appServers??e.instances??1),r=!!e.servicesServer||t>1,n=t>1||!!e.server?.loadBalancer;return{appServers:t,loadBalancer:n,dedicatedServices:r,servicesOnApp:!r}}function uo(e,t){let r={REDIS_HOST:e,MEILISEARCH_HOST:`http://${e}:7700`};if(t?.name){if(r.DB_CONNECTION=t.engine==="postgres"?"pgsql":"mysql",r.DB_HOST=e,r.DB_PORT=String(t.port??(t.engine==="postgres"?5432:3306)),r.DB_DATABASE=t.name,t.username)r.DB_USERNAME=t.username;if(t.password)r.DB_PASSWORD=t.password}return r}function Ln(e){let t=e.infrastructure?.compute??{},r=p(e);return[...cr(t.managedServices??{mysql:!0,redis:!0},{bindPrivate:!0}),...ct(r,t.managedServices??{mysql:!0}),...Me(!0),...Le(!0),...lt(t.sshKeys),...Xe(e.notifications),...t.backups?.enabled?[...Ut({database:r,backups:t.backups})]:[]]}var Gt=["-S","ssh"];function ci(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 Qr(e,t,r={}){let n=Bun.spawn(["ssh",...ci(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 be(e,t,r={}){let n=await Qr(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 Fc(e,t,r,n={}){let s=Bun.spawn(["scp",...Gt,...ci(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 At(e,t={}){let r=t.timeoutMs??180000,n=t.pollIntervalMs??5000,s=Date.now();while(Date.now()-s<r){let i=await Qr(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 Uc(e,t={}){let r=t.timeoutMs??300000,n=t.pollIntervalMs??5000,s=Date.now();while(Date.now()-s<r){let i=await Qr(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 di(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(`
165
165
  `)}var Qc=di();import{homedir as wc}from"node:os";import{join as Cc}from"node:path";var Er={location:"fsn1",image:"ubuntu-24.04",sshUser:"root",sshPrivateKeyPath:"~/.ssh/id_ed25519"};function Rr(e){return e.startsWith("~/")?Cc(wc(),e.slice(2)):e}function ft(...e){for(let t of e){let r=process.env[t]?.trim();if(r)return r}return}function gt(...e){for(let t of e){let r=t?.trim();if(r)return r}return}function Vt(e,t){return gt(e,t?.hetzner?.apiToken,ft("HCLOUD_TOKEN","HETZNER_API_TOKEN"))}function Hc(e,t){return gt(t,e?.hetzner?.location,ft("HCLOUD_LOCATION","HETZNER_LOCATION"))??Er.location}function qt(e,t){let r=e?.infrastructure?.compute;return gt(t,r?.image,e?.hetzner?.image,ft("HCLOUD_IMAGE","HETZNER_IMAGE"))??Er.image}function Pc(e,t){return gt(t,e?.hetzner?.sshUser,ft("HCLOUD_SSH_USER","HETZNER_SSH_USER"))??Er.sshUser}function mo(e,t){return Rr(gt(t,e?.hetzner?.sshPrivateKeyPath,ft("HCLOUD_SSH_KEY","HETZNER_SSH_KEY"))??Er.sshPrivateKeyPath)}function Ec(e,t,r){let n=gt(t,e?.hetzner?.sshPublicKeyPath,ft("HCLOUD_SSH_PUBLIC_KEY","HETZNER_SSH_PUBLIC_KEY"));if(n)return Rr(n);return`${r??mo(e)}.pub`}function fo(e,t={}){let r=mo(e,t.sshPrivateKeyPath);return{apiToken:Vt(t.apiToken,e),location:Hc(e,t.location),image:qt(e,t.image),sshUser:Pc(e,t.sshUser),sshPrivateKeyPath:r,sshPublicKeyPath:Ec(e,t.sshPublicKeyPath,r)}}var Rc="https://api.hetzner.cloud/v1";class Dr extends Error{status;code;details;constructor(e,t,r,n){super(e);this.status=t;this.code=r;this.details=n;this.name="HetznerApiError"}}class xr extends Error{action;constructor(e,t){super(e);this.action=t;this.name="HetznerActionError"}}function ho(e){return e.map((t)=>({type:"server",server:{id:t.server}}))}class Hr{name="hetzner";apiToken;baseUrl;fetchImpl;constructor(e){this.apiToken=e.apiToken,this.baseUrl=e.baseUrl??Rc,this.fetchImpl=e.fetchImpl??fetch}async request(e,t,r){let n=await this.fetchImpl(`${this.baseUrl}${t}`,{method:e,headers:{Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},body:r===void 0?void 0:JSON.stringify(r)}),s=await n.text(),i;try{i=s?JSON.parse(s):{}}catch{if(!n.ok){let a=s.trim().slice(0,200)||n.statusText||"Hetzner API error";throw Error(`Hetzner API ${e} ${t} (${n.status}): ${a}`)}throw Error(`Hetzner API ${e} ${t}: unexpected non-JSON response`)}if(!n.ok){let a=i.error?.message||n.statusText||"Hetzner API error",c=i.error?.code?` [${i.error.code}]`:"";throw new Dr(`Hetzner API ${e} ${t} (${n.status})${c}: ${a}`,n.status,i.error?.code,i.error?.details)}return i}async requestAll(e,t){let r=[],n=1;for(;;){let s=e.includes("?")?"&":"?",i=await this.request("GET",`${e}${s}per_page=50&page=${n}`);r.push(...i[t]??[]);let a=i.meta?.pagination?.next_page;if(!a)return r;n=a}}async listServers(){return this.requestAll("/servers","servers")}async getLocation(e){let r=(await this.request("GET",`/locations?name=${encodeURIComponent(e)}`)).locations.find((n)=>n.name===e);if(!r)throw Error(`Hetzner location not found: ${e}`);return r}async getServer(e){return(await this.request("GET",`/servers/${e}`)).server}async changeServerReverseDns(e,t,r){return(await this.request("POST",`/servers/${e}/actions/change_dns_ptr`,{ip:t,dns_ptr:r})).action}async listVolumes(){return this.requestAll("/volumes","volumes")}async getVolume(e){return(await this.request("GET",`/volumes/${e}`)).volume}async createVolume(e){return this.request("POST","/volumes",{...e,automount:!1})}async attachVolume(e,t){return(await this.request("POST",`/volumes/${e}/actions/attach`,{server:t,automount:!1})).action}async resizeVolume(e,t){return(await this.request("POST",`/volumes/${e}/actions/resize`,{size:t})).action}async protectVolume(e,t){return(await this.request("POST",`/volumes/${e}/actions/change_protection`,{delete:t})).action}async getServerMetrics(e,t){let r=new URLSearchParams({type:t.types.join(","),start:t.start.toISOString(),end:t.end.toISOString(),step:String(Math.max(60,Math.floor(t.step??60)))});return(await this.request("GET",`/servers/${e}/metrics?${r}`)).metrics}async listServerTypes(e){let t=e?`?name=${encodeURIComponent(e)}`:"";return this.requestAll(`/server_types${t}`,"server_types")}async getServerType(e){return(await this.listServerTypes(e)).find((t)=>t.name===e)??null}async createServer(e){let t=await this.request("POST","/servers",{name:e.name,server_type:e.serverType,image:e.image,location:e.location,datacenter:e.datacenter,ssh_keys:e.sshKeys,user_data:e.userData,labels:e.labels,firewalls:e.firewalls,networks:e.networks,start_after_create:!0});return{server:t.server,action:t.action}}async listNetworks(){return this.requestAll("/networks","networks")}async createNetwork(e){let t=e.ipRange??"10.0.0.0/16";return(await this.request("POST","/networks",{name:e.name,ip_range:t,subnets:[{type:"cloud",ip_range:t,network_zone:"eu-central"}],labels:e.labels})).network}async deleteNetwork(e){await this.request("DELETE",`/networks/${e}`)}async listLoadBalancers(){return this.requestAll("/load_balancers","load_balancers")}async createLoadBalancer(e){return(await this.request("POST","/load_balancers",{name:e.name,load_balancer_type:e.type??"lb11",location:e.location,network_zone:e.network?void 0:e.networkZone??"eu-central",network:e.network,labels:e.labels,targets:[{type:"label_selector",label_selector:{selector:e.labelSelector},use_private_ip:!!e.network}],services:e.services.map((r)=>({protocol:r.protocol??"tcp",listen_port:r.listenPort,destination_port:r.destinationPort,health_check:{protocol:"http",port:80,interval:15,timeout:10,retries:3,http:{path:"/",status_codes:["2??","3??"]}}}))})).load_balancer}async deleteLoadBalancer(e){await this.request("DELETE",`/load_balancers/${e}`)}async deleteServer(e){return(await this.request("DELETE",`/servers/${e}`)).action}async listFirewalls(){return this.requestAll("/firewalls","firewalls")}async createFirewall(e){let t=await this.request("POST","/firewalls",{name:e.name,rules:e.rules,labels:e.labels,apply_to:e.applyTo?ho(e.applyTo):void 0});return{firewall:t.firewall,actions:t.actions}}async setFirewallRules(e,t){return(await this.request("POST",`/firewalls/${e}/actions/set_rules`,{rules:t})).actions??[]}async deleteFirewall(e){await this.request("DELETE",`/firewalls/${e}`)}async applyFirewallToResources(e,t){return(await this.request("POST",`/firewalls/${e}/actions/apply_to_resources`,{apply_to:ho(t)})).actions}async listSshKeys(){return this.requestAll("/ssh_keys","ssh_keys")}async createSshKey(e){return(await this.request("POST","/ssh_keys",{name:e.name,public_key:e.publicKey,labels:e.labels})).ssh_key}async deleteSshKey(e){await this.request("DELETE",`/ssh_keys/${e}`)}async getAction(e){return(await this.request("GET",`/actions/${e}`)).action}async shutdownServer(e){return(await this.request("POST",`/servers/${e}/actions/shutdown`,{})).action}async powerOnServer(e){return(await this.request("POST",`/servers/${e}/actions/poweron`,{})).action}async changeServerType(e,t,r){return(await this.request("POST",`/servers/${e}/actions/change_type`,{server_type:t,upgrade_disk:r})).action}async powerOffServer(e){return(await this.request("POST",`/servers/${e}/actions/poweroff`,{})).action}async stopServer(e,t){if((await this.getServer(e)).status==="off")return;await this.shutdownServer(e);let n=t?.gracefulWaitMs??120000,s=t?.pollIntervalMs??3000,i=Date.now();while(Date.now()-i<n){if((await this.getServer(e)).status==="off")return;await new Promise((c)=>setTimeout(c,s))}let a=await this.powerOffServer(e);await this.waitForAction(a.id),await this.waitForServerStatus(e,"off")}async renameServer(e,t){return(await this.request("PUT",`/servers/${e}`,{name:t})).server}async listImages(e){let t=e?.type?`?type=${encodeURIComponent(e.type)}`:"";return this.requestAll(`/images${t}`,"images")}async getImage(e){return(await this.request("GET",`/images/${e}`)).image}async createImage(e,t){return this.request("POST",`/servers/${e}/actions/create_image`,{description:t.description,type:t.type??"snapshot",labels:t.labels})}async deleteImage(e){await this.request("DELETE",`/images/${e}`)}async rebuildServer(e,t){return(await this.request("POST",`/servers/${e}/actions/rebuild`,{image:t})).action}async listPrimaryIps(){return this.requestAll("/primary_ips","primary_ips")}async unassignPrimaryIp(e){return(await this.request("POST",`/primary_ips/${e}/actions/unassign`,{})).action}async assignPrimaryIp(e,t){return(await this.request("POST",`/primary_ips/${e}/actions/assign`,{assignee_id:t,assignee_type:"server"})).action}async waitForAction(e,t){let r=t?.pollIntervalMs??2000,n=t?.maxWaitMs??300000,s=Date.now();while(Date.now()-s<n){let i=await this.getAction(e);if(i.status==="success")return i;if(i.status==="error")throw new xr(i.error?.message||"Hetzner action failed",i);await new Promise((a)=>setTimeout(a,r))}throw Error(`Timed out waiting for Hetzner action ${e}`)}async waitForServerRunning(e,t){let r=t?.pollIntervalMs??3000,n=t?.maxWaitMs??600000,s=Date.now();while(Date.now()-s<n){let i=await this.getServer(e);if(i.status==="running")return i;await new Promise((a)=>setTimeout(a,r))}throw Error(`Timed out waiting for server ${e} to reach running state`)}async waitForServerStatus(e,t,r){let n=r?.pollIntervalMs??3000,s=r?.maxWaitMs??600000,i=Date.now();while(Date.now()-i<s){let a=await this.getServer(e);if(a.status===t)return a;await new Promise((c)=>setTimeout(c,n))}throw Error(`Timed out waiting for server ${e} to reach ${t} state`)}}function Gc(e,t){let r=Vt(e,t);if(!r)throw Error("Hetzner API token required. Set hetzner.apiToken in cloud.config.ts or HCLOUD_TOKEN / HETZNER_API_TOKEN.");return r}function qe(e){let[t,r]=e.trim().split(/\s+/);return r?`${t} ${r}`:t}function go(e,t){if(!t)return[];if(t.length>253||!/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z0-9-]*$/i.test(t))throw Error("Reverse DNS requires a valid fully qualified hostname");let r=[],{ipv4:n,ipv6:s}=e.public_net;if(n?.ip&&n.dns_ptr!==t)r.push({ip:n.ip,hostname:t});let i=se(s?.ip);if(i&&!s?.dns_ptr?.some((a)=>a.ip===i&&a.dns_ptr===t))r.push({ip:i,hostname:t});return r}function So(e){if(!e)return"";return e.endsWith(`
166
166
  `)?e:`${e}
167
167
  `}function oe(e,t={}){let r=t.scriptPath??"/var/lib/cloud/ts-cloud-bootstrap.sh",n=t.permissions??"0755",s=e.split(`
@@ -175,7 +175,7 @@ ${So(t.before)}write_files:
175
175
  ${s}
176
176
  runcmd:
177
177
  - [ bash, ${r} ]
178
- ${So(t.after)}`}function Ar(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 Un={micro:"cpx11",small:"cx23",medium:"cx33",large:"cx43",xlarge:"cx53","2xlarge":"ccx33"};function Ye(e){if(!e)return Un.micro;if(e in Un)return Un[e];return e}var he="ts-cloud";function ge(e,t,r="app"){return{[`${he}/project`]:e,[`${he}/environment`]:t,[`${he}/role`]:r,[`${he}/managed-by`]:"ts-cloud"}}function Te(e,t,r,n="app"){return kn(e,t,r)&&e[`${he}/role`]===n}function kn(e,t,r){if(!e)return!1;return e[`${he}/project`]===t&&e[`${he}/environment`]===r}function Dc(e){return e.location?.name??e.datacenter?.location.name??"unknown"}function _t(e){return typeof e==="number"&&Number.isFinite(e)?e:0}function xc(e,t){if(e.architecture&&t.architecture&&e.architecture!==t.architecture)throw Error(`Cannot resize ${e.name} (${e.architecture}) to ${t.name} (${t.architecture}) in place.`);let r=[];if(_t(t.cores)<_t(e.cores))r.push("CPU");if(_t(t.memory)<_t(e.memory))r.push("memory");if(_t(t.disk)<_t(e.disk))r.push("disk");if(r.length>0)throw Error(`Refusing an in-place downgrade from ${e.name} to ${t.name}: ${r.join(", ")} would shrink.`)}async function er(e,t,r,n=!0){let[s,i]=await Promise.all([e.getServer(t),e.getServerType(r)]);if(!i)throw Error(`Hetzner server type ${r} was not found.`);let a=s.server_type,c=a.name===i.name;if(!c)xc(a,i);let f=Dc(s),h=i.locations?.find((g)=>g.name===f);return{serverId:t,serverName:s.name,location:f,currentType:a,targetType:i,capacityAvailable:h?.available!==!1,alreadyComplete:c,upgradeDisk:n}}function Hg(e){if(e instanceof Dr&&e.code==="resource_unavailable")return!0;if(e instanceof xr){if(e.action.error?.code==="resource_unavailable")return!0;if(/no fitting vhost|placement|free resources/i.test(e.action.error?.message??""))return!0}return/resource_unavailable|no fitting vhost|error during placement|free resources/i.test(e instanceof Error?e.message:String(e))}async function He(e,t,r){await e?.onPhase?.(t,r)}async function Hn(e,t,r){await e.waitForAction(t.id,{pollIntervalMs:r.actionPollIntervalMs,maxWaitMs:r.actionTimeoutMs})}var Ir=async({client:e,hooks:t,actionPollIntervalMs:r,actionTimeoutMs:n,serverPollIntervalMs:s,serverTimeoutMs:i},a,c,f)=>{let h=await e.getServer(a.serverId);if(h.status!=="running"){await He(t,f?"recovering":"powering-on",{serverId:a.serverId});let S=await e.powerOnServer(a.serverId);await Hn(e,S,{actionPollIntervalMs:r,actionTimeoutMs:n}),h=await e.waitForServerRunning(a.serverId,{pollIntervalMs:s,maxWaitMs:i})}await He(t,"verifying",{serverId:a.serverId,recovered:f});let g=await t?.afterBoot?.(h,a.targetType,c,{recovered:f});return{server:h,verification:g}};async function li(e){let{client:t,hooks:r}=e,n=e.upgradeDisk??!0;await He(r,"planning",{serverId:e.serverId,targetType:e.targetType});let s=await er(t,e.serverId,e.targetType,n),i=await t.getServer(s.serverId);if(s.alreadyComplete){let f=await Ir(e,s,e.manifest,!1);return await He(r,"complete",{alreadyComplete:!0}),{status:"already-complete",plan:s,verification:f.verification}}if(!s.capacityAvailable&&!e.attemptUnavailable)return await He(r,"waiting-capacity",{location:s.location,targetType:s.targetType.name}),{status:"waiting-capacity",plan:s};let a=e.manifest;if(i.status==="off"&&!e.resumeFromOff){let f=await Ir(e,s,void 0,!0);return{status:"recovered",plan:s,server:f.server,verification:f.verification,retryable:!0,error:"Server was already off without a resumable resize checkpoint; powered it back on."}}if(i.status==="running"){await He(r,"preflight",{serverId:s.serverId}),a=await r?.preflight?.(i,s.targetType),await He(r,"shutting-down",{serverId:s.serverId});let f=await t.shutdownServer(s.serverId);await Hn(t,f,e),i=await t.waitForServerStatus(s.serverId,"off",{pollIntervalMs:e.serverPollIntervalMs,maxWaitMs:e.serverTimeoutMs})}try{await He(r,"resizing",{serverId:s.serverId,from:s.currentType.name,to:s.targetType.name,upgradeDisk:n});let f=await t.changeServerType(s.serverId,s.targetType.name,n);await Hn(t,f,e)}catch(f){let h=await Ir(e,s,a,!0);return{status:"recovered",plan:s,server:h.server,manifest:a,verification:h.verification,retryable:Hg(f),error:f instanceof Error?f.message:String(f)}}let c=await Ir(e,s,a,!1);if(c.verification&&!c.verification.ok)throw Error(`Resize completed but verification failed: ${(c.verification.failures??[]).join("; ")}`);return await He(r,"complete",{serverId:s.serverId,targetType:s.targetType.name}),{status:"completed",plan:s,server:c.server,manifest:a,verification:c.verification}}var Ac=String.raw`
178
+ ${So(t.after)}`}function Ar(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 Un={micro:"cpx11",small:"cx23",medium:"cx33",large:"cx43",xlarge:"cx53","2xlarge":"ccx33"};function We(e){if(!e)return Un.micro;if(e in Un)return Un[e];return e}var he="ts-cloud";function ge(e,t,r="app"){return{[`${he}/project`]:e,[`${he}/environment`]:t,[`${he}/role`]:r,[`${he}/managed-by`]:"ts-cloud"}}function Te(e,t,r,n="app"){return kn(e,t,r)&&e[`${he}/role`]===n}function kn(e,t,r){if(!e)return!1;return e[`${he}/project`]===t&&e[`${he}/environment`]===r}function Dc(e){return e.location?.name??e.datacenter?.location.name??"unknown"}function _t(e){return typeof e==="number"&&Number.isFinite(e)?e:0}function xc(e,t){if(e.architecture&&t.architecture&&e.architecture!==t.architecture)throw Error(`Cannot resize ${e.name} (${e.architecture}) to ${t.name} (${t.architecture}) in place.`);let r=[];if(_t(t.cores)<_t(e.cores))r.push("CPU");if(_t(t.memory)<_t(e.memory))r.push("memory");if(_t(t.disk)<_t(e.disk))r.push("disk");if(r.length>0)throw Error(`Refusing an in-place downgrade from ${e.name} to ${t.name}: ${r.join(", ")} would shrink.`)}async function er(e,t,r,n=!0){let[s,i]=await Promise.all([e.getServer(t),e.getServerType(r)]);if(!i)throw Error(`Hetzner server type ${r} was not found.`);let a=s.server_type,c=a.name===i.name;if(!c)xc(a,i);let f=Dc(s),h=i.locations?.find((g)=>g.name===f);return{serverId:t,serverName:s.name,location:f,currentType:a,targetType:i,capacityAvailable:h?.available!==!1,alreadyComplete:c,upgradeDisk:n}}function Hg(e){if(e instanceof Dr&&e.code==="resource_unavailable")return!0;if(e instanceof xr){if(e.action.error?.code==="resource_unavailable")return!0;if(/no fitting vhost|placement|free resources/i.test(e.action.error?.message??""))return!0}return/resource_unavailable|no fitting vhost|error during placement|free resources/i.test(e instanceof Error?e.message:String(e))}async function He(e,t,r){await e?.onPhase?.(t,r)}async function Hn(e,t,r){await e.waitForAction(t.id,{pollIntervalMs:r.actionPollIntervalMs,maxWaitMs:r.actionTimeoutMs})}var Ir=async({client:e,hooks:t,actionPollIntervalMs:r,actionTimeoutMs:n,serverPollIntervalMs:s,serverTimeoutMs:i},a,c,f)=>{let h=await e.getServer(a.serverId);if(h.status!=="running"){await He(t,f?"recovering":"powering-on",{serverId:a.serverId});let S=await e.powerOnServer(a.serverId);await Hn(e,S,{actionPollIntervalMs:r,actionTimeoutMs:n}),h=await e.waitForServerRunning(a.serverId,{pollIntervalMs:s,maxWaitMs:i})}await He(t,"verifying",{serverId:a.serverId,recovered:f});let g=await t?.afterBoot?.(h,a.targetType,c,{recovered:f});return{server:h,verification:g}};async function li(e){let{client:t,hooks:r}=e,n=e.upgradeDisk??!0;await He(r,"planning",{serverId:e.serverId,targetType:e.targetType});let s=await er(t,e.serverId,e.targetType,n),i=await t.getServer(s.serverId);if(s.alreadyComplete){let f=await Ir(e,s,e.manifest,!1);return await He(r,"complete",{alreadyComplete:!0}),{status:"already-complete",plan:s,verification:f.verification}}if(!s.capacityAvailable&&!e.attemptUnavailable)return await He(r,"waiting-capacity",{location:s.location,targetType:s.targetType.name}),{status:"waiting-capacity",plan:s};let a=e.manifest;if(i.status==="off"&&!e.resumeFromOff){let f=await Ir(e,s,void 0,!0);return{status:"recovered",plan:s,server:f.server,verification:f.verification,retryable:!0,error:"Server was already off without a resumable resize checkpoint; powered it back on."}}if(i.status==="running"){await He(r,"preflight",{serverId:s.serverId}),a=await r?.preflight?.(i,s.targetType),await He(r,"shutting-down",{serverId:s.serverId});let f=await t.shutdownServer(s.serverId);await Hn(t,f,e),i=await t.waitForServerStatus(s.serverId,"off",{pollIntervalMs:e.serverPollIntervalMs,maxWaitMs:e.serverTimeoutMs})}try{await He(r,"resizing",{serverId:s.serverId,from:s.currentType.name,to:s.targetType.name,upgradeDisk:n});let f=await t.changeServerType(s.serverId,s.targetType.name,n);await Hn(t,f,e)}catch(f){let h=await Ir(e,s,a,!0);return{status:"recovered",plan:s,server:h.server,manifest:a,verification:h.verification,retryable:Hg(f),error:f instanceof Error?f.message:String(f)}}let c=await Ir(e,s,a,!1);if(c.verification&&!c.verification.ok)throw Error(`Resize completed but verification failed: ${(c.verification.failures??[]).join("; ")}`);return await He(r,"complete",{serverId:s.serverId,targetType:s.targetType.name}),{status:"completed",plan:s,server:c.server,manifest:a,verification:c.verification}}var Ac=String.raw`
179
179
  const { readdir, readFile, readlink, stat } = await import('node:fs/promises')
180
180
 
181
181
  const text = (command) => {
@@ -281,8 +281,8 @@ case "$root_fs" in
281
281
  *) echo "Unsupported root filesystem: $root_fs" >&2; exit 1 ;;
282
282
  esac`,e)}async function rl(e,t){let r=Buffer.from(t.join(`
283
283
  `)).toString("base64");await be(e.host,`printf %s ${r} | base64 -d | while read -r unit; do [ -z "$unit" ] || systemctl is-active --quiet "$unit" || systemctl start "$unit"; done`,e)}async function jc(e,t,r,n={recovered:!1}){if(await At(e.host,{...e,timeoutMs:e.sshTimeoutMs??600000}),!n.recovered)await tl(e);if(r)await rl(e,r.runningServices);let s=await Vc(e),i=[],a=r?vt(r.runningServices,s.runningServices):[],c=r?vt(r.releaseLinks,s.releaseLinks):[],f=r?vt(r.routeFragments,s.routeFragments):[],h=r?vt(r.routeIds,s.routeIds):[],g=r?.persistentData.map((L)=>L.split("=")[0])??[],S=s.persistentData.map((L)=>L.split("=")[0]),_=vt(g,S),v=r?vt(r.dataCatalog,s.dataCatalog):[],y=s.routeProbes.filter((L)=>!L.ok),C=n.recovered&&r?r.cpuCores:t.cores??0,x=n.recovered&&r?r.memoryBytes:el(t),q=s.cpuCores>=C,H=s.memoryBytes>=x*0.9,R=n.recovered||s.rootDiskBytes>=(t.disk??0)*1e9*0.95;if(s.failedUnits.length>0)i.push(`Failed services: ${s.failedUnits.join(", ")}`);if(a.length>0)i.push(`Services did not return: ${a.join(", ")}`);if(c.length>0)i.push(`Release links changed: ${c.join(", ")}`);if(f.length>0)i.push(`Route manifests changed: ${f.join(", ")}`);if(h.length>0)i.push(`Routes disappeared: ${h.join(", ")}`);if(_.length>0)i.push(`Persistent data paths disappeared: ${_.join(", ")}`);if(v.length>0)i.push(`Databases or volumes disappeared: ${v.join(", ")}`);if(y.length>0)i.push(`Unhealthy routes: ${y.map((L)=>L.domain).join(", ")}`);if(!q)i.push(`Expected at least ${C} CPU cores, found ${s.cpuCores}`);if(!H)i.push(`Expected at least ${x} bytes of RAM`);if(!R)i.push(`Expected approximately ${t.disk??0} GB root disk`);return{ok:i.length===0,checks:{cpuCores:s.cpuCores,memoryBytes:s.memoryBytes,rootDiskBytes:s.rootDiskBytes,rootFilesystemBytes:s.rootFilesystemBytes,runningServices:s.runningServices.length,releaseLinks:s.releaseLinks.length,routeFragments:s.routeFragments.length,routes:s.routeIds.length,healthyRoutes:s.routeProbes.filter((L)=>L.ok).length,persistentDataPaths:s.persistentData.length,databasesAndVolumes:s.dataCatalog.length,failedUnits:s.failedUnits.length},failures:i}}import{mkdir as nl,readFile as sl,rename as ol,writeFile as al}from"node:fs/promises";import{join as _o}from"node:path";var zc="storage/cloud/state";function yt(e=process.cwd()){return il()?l(e,"state"):_o(e,zc)}function je(e,t=process.cwd()){return _o(yt(t),`${e}.json`)}async function ze(e,t=process.cwd()){try{let r=await sl(je(e,t),"utf8");return JSON.parse(r)}catch{return null}}async function St(e,t,r=process.cwd()){let n=je(e,r);await nl(yt(r),{recursive:!0});let s=`${n}.${process.pid}.tmp`;await al(s,`${JSON.stringify(t,null,2)}
284
- `,"utf8"),await ol(s,n)}async function rt(e){return ze(e)}async function nt(e,t){await St(e,t)}async function ui(e,t,r){let n=r.length?await e.listVolumes():[];return r.map((s)=>{let i=n.filter((h)=>h.name===s.name);if(i.length>1)throw Error(`Ambiguous volume name: ${s.name}`);let a=i[0];if(a&&a.server!==null&&a.server!==t.id)throw Error(`Volume ${a.name} belongs to another server; refusing to detach live storage`);let c=t.location?.name??t.datacenter?.location.name;if(a&&a.location.name!==c)throw Error(`Volume ${a.name} is in ${a.location.name}, server is in ${c}`);if(a&&a.size>s.size)throw Error(`Refusing to shrink volume ${a.name}: ${a.size} GB to ${s.size} GB`);let f=[];if(!a)f.push("create");else{if(a.server===null)f.push("attach");if(a.size<s.size)f.push("grow")}if(!a||a.protection.delete!==(s.deleteProtection!==!1))f.push("protect");return f.push("mount"),{declaration:s,existing:a,actions:f}})}async function gi(e,t,r){let n=[];for(let s of r){let i=s.existing,a=!i;if(!i){let c=await e.createVolume({name:s.declaration.name,size:s.declaration.size,server:t.id,labels:{...t.labels,"ts-cloud/volume":s.declaration.key}});await e.waitForAction(c.action.id);for(let f of c.next_actions??[])await e.waitForAction(f.id);i=await e.getVolume(c.volume.id)}if(i.server===null)await e.waitForAction((await e.attachVolume(i.id,t.id)).id),i=await e.getVolume(i.id);if(i.server!==t.id||i.location.name!==(t.location?.name??t.datacenter?.location.name))throw Error(`Volume attachment verification failed: ${i.name}`);if(i.linux_device!==`/dev/disk/by-id/scsi-0HC_Volume_${i.id}`)throw Error(`Unexpected Hetzner volume device: ${i.name}`);if(i.size<s.declaration.size)await e.waitForAction((await e.resizeVolume(i.id,s.declaration.size)).id);if(i.protection.delete!==(s.declaration.deleteProtection!==!1))await e.waitForAction((await e.protectVolume(i.id,s.declaration.deleteProtection!==!1)).id);n.push({...s.declaration,id:i.id,device:i.linux_device,allowFormat:a})}return n}var Nn=268435456;function Wt(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function ml(e){let t=ll("sha256");for await(let r of ul(e))t.update(r);return t.digest("hex")}class Pe{name="hetzner";usesCloudFormation=!1;client;sshPrivateKeyPath;sshPublicKeyPath;sshUser;location;stateOnly;residency;waitForBoot;bootWait;async applyComputeChanges(e){let{config:t,environment:r}=e;if(t.cloud?.attachTo)throw Error("Only the compute owner may reconcile server size and volumes");let n=t.infrastructure?.compute;if(n?.resize&&!n.size)throw Error("compute.resize requires an explicit compute.size");let s=ei(t,r),i=In(n??{});if(i.appServers>1||i.dedicatedServices)throw Error("Managed compute volumes currently require a single app server");let a=await this.getComputeOutputs(e);if(!a.appInstanceId)throw Error("No existing compute server found; provision the server first");let c=await this.client.getServer(Number(a.appInstanceId)),f=await ui(this.client,c,s),h=n?.resize&&n.size?await er(this.client,c.id,Ye(n.size),n.resize.upgradeDisk!==!1):void 0,g={serverId:String(c.id),changes:f.flatMap((y)=>y.actions.map((C)=>({resource:y.declaration.name,action:C,detail:`${y.declaration.size} GB at ${y.declaration.mountPath}`})))};if(n?.deploymentStorage)g.changes.push({resource:n.deploymentStorage.volume,action:"place-deployments",detail:`Reconcile release directories${n.deploymentStorage.includeBackups!==!1?" and deployment backups":""} on the volume; ${n.deploymentStorage.migrateExisting?"verify and migrate existing files":"refuse nonempty directories"}`});if(h&&!h.alreadyComplete)if(!h.capacityAvailable){if(n?.resize?.whenUnavailable!=="keep-current")throw Error(`${h.targetType.name} is unavailable in ${h.location}`);g.waitingForCapacity=`${h.targetType.name} unavailable in ${h.location}; keeping ${c.server_type.name} running`}else g.changes.push({resource:c.name,action:"resize",detail:`${c.server_type.name} to ${h.targetType.name}`});if(e.dryRun)return g;if(g.waitingForCapacity)console.warn(`[ts-cloud] ${g.waitingForCapacity}`);let S=await gi(this.client,c,f),_=[{id:String(c.id),name:c.name,publicIp:c.public_net.ipv4?.ip}],v=[...Je(t.notifications),...n?.volumes||n?.deploymentStorage?ti({volumes:S,deploymentStorage:n?.deploymentStorage,webRoot:"/var/www"}):[],...n?.monitoring!==!1?Le(n?.monitoring):[]];if(v.length){let y=await this.runRemoteDeploy({targets:_,commands:v,timeoutSeconds:7200,comment:"ts-cloud apply configured compute storage"});if(!y.success)throw Error(y.error||y.perInstance.map((C)=>C.error||C.output).join(`
285
- `))}if(h?.capacityAvailable&&!h.alreadyComplete){let y={host:_[0].publicIp,user:this.sshUser,identityFile:this.sshPrivateKeyPath},C=await li({client:this.client,serverId:c.id,targetType:h.targetType.name,upgradeDisk:h.upgradeDisk,hooks:{preflight:()=>qc(y),afterBoot:(x,q,H,R)=>jc(y,q,H,R)}});if(C.status!=="completed"&&C.status!=="already-complete")throw Error(`Resize did not complete: ${C.status}`)}return g}constructor(e={}){this.residency=e.residency;let t=Vt(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 Hr({apiToken:t??""});let r=fo(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=m(t,r),a=`${n}-${r}-app`,c=s.runtime==="php"||!!s.php,f=In(s);if(s.reverseDns&&(f.dedicatedServices||f.appServers>1))throw Error("Reverse DNS currently requires a single owned app server");let h=t.cloud?.residency||this.residency,{assertComputeResidency:g}=await import("./chunk-nh7rcks9.js"),S=(T)=>{if(h)g(h,{country:T.location?.country||T.datacenter?.location?.country,location:T.location?.name||T.datacenter?.location?.name})};if(h){if(f.dedicatedServices||f.appServers>1)throw Error("Residency policy currently requires single-host compute");let T=await this.client.getLocation(t.hetzner?.location||this.location);g(h,{country:T.country,location:T.name})}if(f.dedicatedServices||f.appServers>1)return c?this.provisionFleet(e,f):this.provisionBunFleet(e,f);let _=ge(n,r,"app"),v=t.sites||{},y=j(s)?[]:this.collectUpstreamPorts(v),C=`${n}-${r}-app-fw`,{firewall:x}=await this.ensureFirewall(C,_,Ar({allowSsh:s.allowSsh!==!1,sitePorts:y,allowedPorts:[...s.firewall?.allowedPorts??[],...Ps(t.infrastructure?.sftp),...Ze(b(t,{environment:r}))]})),q=await this.ensureSshKey(n,r,_),H=await rt(i);if(H?.serverId){let T=await this.tryGetServer(H.serverId);if(T&&T.status!=="off"&&T.labels?.["ts-cloud/project"]===n&&T.labels?.["ts-cloud/environment"]===r){if(S(T),await this.reconcileReverseDns(e,T),s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.reconcileOwnedServices(e,T),this.outputsFromState(H,T)}}let R=await this.findExistingServer(n,r,a);if(R&&R.status!=="off"){S(R);let T={provider:"hetzner",stackName:i,serverId:R.id,serverName:R.name,publicIp:R.public_net.ipv4?.ip,publicIpv6:se(R.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};if(await nt(i,T),s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.reconcileOwnedServices(e,R),await this.reconcileReverseDns(e,R),this.outputsFromState(T,R)}let L=w(t,{environment:r}),I=L?.engine==="rpx"?G({proxy:L,config:B(v,{proxy:L,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,V=Qe(t,{environment:r}),W=s.bakedImage===!0,K=M({runtime:V.runtime,runtimeVersion:V.runtimeVersion,systemPackages:s.systemPackages,database:t.infrastructure?.database,phpProvision:V.phpProvision,servicesProvision:V.servicesProvision,rpxProvision:I,baked:W,swapGb:s.swapGb}),te=oe(K),Z=Ye(s.size),re=qt(t),{server:ae,action:ie}=await this.client.createServer({name:a,serverType:Z,image:re,location:t.hetzner?.location||this.location,userData:te,labels:_,sshKeys:q?[q]:void 0,firewalls:[{firewall:x.id}]});await this.client.waitForAction(ie.id);let ne=await this.client.waitForServerRunning(ae.id);S(ne),await this.reconcileReverseDns(e,ne);let me={provider:"hetzner",stackName:i,serverId:ne.id,serverName:ne.name,firewallId:x.id,publicIp:ne.public_net.ipv4?.ip,publicIpv6:se(ne.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};await nt(i,me);let Se=ne.public_net.ipv4?.ip;if(Se&&this.waitForBoot)await this.waitForSshReady(Se),await this.waitForCloudInit(Se);if(s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(me,ne)}async provisionFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,i=r.infrastructure.compute,a=m(r,n),c=Ye(i.size),f=qt(r),h=r.hetzner?.location||this.location,g=i.bakedImage===!0,S=await rt(a);if(S?.loadBalancerId){let O=(await this.client.listLoadBalancers().catch(()=>[])).find((D)=>D.id===S.loadBalancerId);if(O)return{appPublicIp:O.public_net?.ipv4?.ip,loadBalancerIp:O.public_net?.ipv4?.ip,servicesPrivateIp:S.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}let _=await this.ensureSshKey(s,n,ge(s,n,"app")),v=`${s}-${n}-net`,C=(await this.client.listNetworks().catch(()=>[])).find((P)=>P.name===v)??await this.client.createNetwork({name:v,labels:ge(s,n,"app")}),{firewall:x}=await this.ensureFirewall(`${s}-${n}-app-fw`,ge(s,n,"app"),Ar({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),{firewall:q}=await this.ensureFirewall(`${s}-${n}-services-fw`,ge(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:[C.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[C.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[C.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[C.ip_range]}]),H=Ln(r),R=oe(M({runtime:"php",servicesProvision:H,baked:g,swapGb:i.swapGb})),L=await this.client.listServers().catch(()=>[]),I=[],V=L.find((P)=>Te(P.labels,s,n,"services"));if(!V){let{server:P,action:O}=await this.client.createServer({name:`${s}-${n}-services`,serverType:Ye(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:f,location:h,userData:R,labels:ge(s,n,"services"),sshKeys:_?[_]:void 0,firewalls:[{firewall:q.id}],networks:[C.id]});await this.client.waitForAction(O.id),V=await this.client.waitForServerRunning(P.id),I.push(P.id)}let W=V.id,K=V.private_net?.[0]?.ip??(await this.client.getServer(W)).private_net?.[0]?.ip,te=[...Me(!0),...Le(!0),...lt(i.sshKeys),...Je(r.notifications)],Z=ur({versions:i.php?.versions,default:i.php?.default,extensions:i.php?.extensions,installNginx:!j(i),optimizeForProduction:i.php?.optimizeForProduction,ini:i.php?.ini}),re=oe(M({runtime:"php",phpProvision:Z,servicesProvision:te,baked:g,swapGb:i.swapGb})),ae=L.filter((P)=>Te(P.labels,s,n,"app")),ie=ae.map((P)=>P.id);if(ae.length>t.appServers)for(let P of ae.slice(t.appServers))await this.client.deleteServer(P.id).catch(()=>{}),ie.splice(ie.indexOf(P.id),1);for(let P=ae.length;P<t.appServers;P++){let{server:O,action:D}=await this.client.createServer({name:`${s}-${n}-app-${P+1}`,serverType:c,image:f,location:h,userData:re,labels:ge(s,n,"app"),sshKeys:_?[_]:void 0,firewalls:[{firewall:x.id}],networks:[C.id]});await this.client.waitForAction(D.id),ie.push(O.id),I.push(O.id)}if(this.waitForBoot&&I.length>0)await Promise.all(I.map(async(P)=>{let D=(await this.client.waitForServerRunning(P)).public_net.ipv4?.ip;if(D)await this.waitForSshReady(D),await this.waitForCloudInit(D)}));let ne=`${s}-${n}-lb`,me,Se;if(t.loadBalancer){let O=(await this.client.listLoadBalancers().catch(()=>[])).find((D)=>D.name===ne)??await this.client.createLoadBalancer({name:ne,location:h,network:C.id,labels:ge(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}]});Se=O.id,me=O.public_net?.ipv4?.ip}let T=me??(await this.client.getServer(ie[0]).catch(()=>{return}))?.public_net.ipv4?.ip,k={provider:"hetzner",stackName:a,networkId:C.id,loadBalancerId:Se,servicesServerId:W,servicesPrivateIp:K,publicIp:T,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await nt(a,k),{appPublicIp:T,loadBalancerIp:me,servicesPrivateIp:K,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=m(r,n),c=Ye(i.size),f=qt(r),h=r.hetzner?.location||this.location,g=i.bakedImage===!0,S=r.sites||{},_=await rt(a);if(_?.lbServerId){let D=await this.tryGetServer(_.lbServerId);if(D&&D.status!=="off"){let J=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"},Y=await this.findComputeTargets({slug:s,environment:n,role:"app",stackName:a});return this.refreshLbRoutes(D,S,Y.map((X)=>({privateIp:X.privateIp,publicIp:X.publicIp})),J,s),{appPublicIp:D.public_net.ipv4?.ip??_.publicIp,loadBalancerIp:D.public_net.ipv4?.ip??_.publicIp,servicesPrivateIp:_.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}}let v=await this.ensureSshKey(s,n,ge(s,n,"app")),y=`${s}-${n}-net`,x=(await this.client.listNetworks().catch(()=>[])).find((D)=>D.name===y)??await this.client.createNetwork({name:y,labels:ge(s,n,"app")}),q=this.collectUpstreamPorts(S),{firewall:H}=await this.ensureFirewall(`${s}-${n}-app-fw`,ge(s,n,"app"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},...q.map((D)=>({direction:"in",protocol:"tcp",port:String(D),source_ips:[x.ip_range],description:`ts-cloud port ${D} (private, LB-only)`}))]),{firewall:R}=await this.ensureFirewall(`${s}-${n}-lb-fw`,ge(s,n,"lb"),Ar({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),L=await this.client.listServers().catch(()=>[]),I=[],V,W,K=!!i.servicesServer||!!i.managedServices,te=t.dedicatedServices&&K;if(te){let{firewall:D}=await this.ensureFirewall(`${s}-${n}-services-fw`,ge(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]}]),J=Ln(r),Y=oe(M({runtime:"bun",servicesProvision:J,baked:g,swapGb:i.swapGb})),X=L.find((ee)=>Te(ee.labels,s,n,"services"));if(!X){let{server:ee,action:ue}=await this.client.createServer({name:`${s}-${n}-services`,serverType:Ye(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:f,location:h,userData:Y,labels:ge(s,n,"services"),sshKeys:v?[v]:void 0,firewalls:[{firewall:D.id}],networks:[x.id]});await this.client.waitForAction(ue.id),X=await this.client.waitForServerRunning(ee.id),I.push(ee.id)}V=X.id,W=X.private_net?.[0]?.ip??(await this.client.getServer(V)).private_net?.[0]?.ip}let Z=te?{...i,managedServices:void 0,backups:void 0}:i,re=Qe({...r,infrastructure:{...r.infrastructure,compute:Z}},{environment:n}),ae=oe(M({runtime:re.runtime,runtimeVersion:re.runtimeVersion,systemPackages:i.systemPackages,database:r.infrastructure?.database,servicesProvision:re.servicesProvision,baked:g,swapGb:i.swapGb})),ie=L.filter((D)=>Te(D.labels,s,n,"app")),ne=ie.map((D)=>D.id);if(ie.length>t.appServers)for(let D of ie.slice(t.appServers))await this.client.deleteServer(D.id).catch(()=>{}),ne.splice(ne.indexOf(D.id),1);for(let D=ie.length;D<t.appServers;D++){let{server:J,action:Y}=await this.client.createServer({name:`${s}-${n}-app-${D+1}`,serverType:c,image:f,location:h,userData:ae,labels:ge(s,n,"app"),sshKeys:v?[v]:void 0,firewalls:[{firewall:H.id}],networks:[x.id]});await this.client.waitForAction(Y.id),ne.push(J.id),I.push(J.id)}if(this.waitForBoot&&I.length>0)await Promise.all(I.map(async(D)=>{let Y=(await this.client.waitForServerRunning(D)).public_net.ipv4?.ip;if(Y)await this.waitForSshReady(Y),await this.waitForCloudInit(Y)}));let me=[];for(let D of ne){let J=L.find((Y)=>Y.id===D);if(!J||!J.private_net?.[0]?.ip)J=await this.client.getServer(D).catch(()=>J);me.push({privateIp:J?.private_net?.[0]?.ip,publicIp:J?.public_net.ipv4?.ip})}let Se=`${s}-${n}-lb`,T,k;if(t.loadBalancer){let D=L.find((Y)=>Te(Y.labels,s,n,"lb")),J=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"};if(!D){let Y=G({proxy:J,config:rr(S,me,{proxy:J,slug:s}),slug:s,bunBin:re.runtime==="node"||re.runtime==="deno"?void 0:"/usr/local/bin/bun"}),X=oe(M({runtime:"bun",rpxProvision:Y,baked:!1})),ee=typeof i.loadBalancer==="object"?i.loadBalancer.size:void 0,{server:ue,action:E}=await this.client.createServer({name:Se,serverType:Ye(ee??"micro"),image:f,location:h,userData:X,labels:ge(s,n,"lb"),sshKeys:v?[v]:void 0,firewalls:[{firewall:R.id}],networks:[x.id]});if(await this.client.waitForAction(E.id),D=await this.client.waitForServerRunning(ue.id),this.waitForBoot){let N=D.public_net.ipv4?.ip;if(N)await this.waitForSshReady(N),await this.waitForCloudInit(N)}}else this.refreshLbRoutes(D,S,me,J,s);T=D.id,k=D.public_net.ipv4?.ip}let P=k??(await this.client.getServer(ne[0]).catch(()=>{return}))?.public_net.ipv4?.ip,O={provider:"hetzner",stackName:a,networkId:x.id,lbServerId:T,appServerIds:ne,servicesServerId:V,servicesPrivateIp:W,publicIp:P,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await nt(a,O),{appPublicIp:P,loadBalancerIp:k,servicesPrivateIp:W,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async destroyCompute(e){let{config:t,environment:r}=e,n=t.project.slug,s=m(t,r),i=await rt(s),a=[],c=`${n}-${r}-lb`,h=(await this.client.listLoadBalancers().catch(()=>[])).find((H)=>H.name===c);if(h)try{await this.client.deleteLoadBalancer(h.id),a.push(`load balancer ${c}`)}catch{}let g=await this.client.listServers().catch(()=>[]),S=new Set;for(let H of g)if(Te(H.labels,n,r,"app")||Te(H.labels,n,r,"services")||Te(H.labels,n,r,"lb"))S.add(H.id);if(i?.serverId)S.add(i.serverId);if(i?.servicesServerId)S.add(i.servicesServerId);if(i?.lbServerId)S.add(i.lbServerId);for(let H of i?.appServerIds??[])S.add(H);for(let H of S)try{await this.client.deleteServer(H),a.push(`server ${H}`)}catch{}let _=await this.client.listFirewalls().catch(()=>[]);for(let H of[`${n}-${r}-app-fw`,`${n}-${r}-services-fw`,`${n}-${r}-lb-fw`]){let R=_.find((L)=>L.name===H);if(!R)continue;for(let L=0;L<12;L++)try{await this.client.deleteFirewall(R.id),a.push(`firewall ${H}`);break}catch{await this.sleep(3000)}}let v=`${n}-${r}-net`,C=(await this.client.listNetworks().catch(()=>[])).find((H)=>H.name===v);if(C)for(let H=0;H<12;H++)try{await this.client.deleteNetwork(C.id),a.push(`network ${v}`);break}catch{await this.sleep(3000)}let q=(await this.client.listSshKeys().catch(()=>[])).filter((H)=>kn(H.labels,n,r));for(let H of q)try{await this.client.deleteSshKey(H.id),a.push(`ssh key ${H.name}`)}catch{}return await nt(s,{provider:"hetzner",stackName:s}).catch(()=>{}),{destroyed:a}}async getComputeOutputs(e){let t=m(e.config,e.environment),r=await rt(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:m(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:m(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,"-")}-${$o()}.tar.gz`}`,i=await ml(e.localPath),a=Fr,c=`${a}/${i}.tar.gz`;for(let f of t){if(!f.publicIp)throw Error(`Target ${f.id} has no public IP for SCP upload`);let h=["set -euo pipefail",`mkdir -p ${Wt(a)} /var/ts-cloud/staging`,`test -s ${Wt(c)}`,`cp -- ${Wt(c)} ${Wt(s)}`].join(`
284
+ `,"utf8"),await ol(s,n)}async function rt(e){return ze(e)}async function nt(e,t){await St(e,t)}async function ui(e,t,r){let n=r.length?await e.listVolumes():[];return r.map((s)=>{let i=n.filter((h)=>h.name===s.name);if(i.length>1)throw Error(`Ambiguous volume name: ${s.name}`);let a=i[0];if(a&&a.server!==null&&a.server!==t.id)throw Error(`Volume ${a.name} belongs to another server; refusing to detach live storage`);let c=t.location?.name??t.datacenter?.location.name;if(a&&a.location.name!==c)throw Error(`Volume ${a.name} is in ${a.location.name}, server is in ${c}`);if(a&&a.size>s.size)throw Error(`Refusing to shrink volume ${a.name}: ${a.size} GB to ${s.size} GB`);let f=[];if(!a)f.push("create");else{if(a.server===null)f.push("attach");if(a.size<s.size)f.push("grow")}if(!a||a.protection.delete!==(s.deleteProtection!==!1))f.push("protect");return f.push("mount"),{declaration:s,existing:a,actions:f}})}async function gi(e,t,r){let n=[];for(let s of r){let i=s.existing,a=!i;if(!i){let c=await e.createVolume({name:s.declaration.name,size:s.declaration.size,server:t.id,labels:{...t.labels,"ts-cloud/volume":s.declaration.key}});await e.waitForAction(c.action.id);for(let f of c.next_actions??[])await e.waitForAction(f.id);i=await e.getVolume(c.volume.id)}if(i.server===null)await e.waitForAction((await e.attachVolume(i.id,t.id)).id),i=await e.getVolume(i.id);if(i.server!==t.id||i.location.name!==(t.location?.name??t.datacenter?.location.name))throw Error(`Volume attachment verification failed: ${i.name}`);if(i.linux_device!==`/dev/disk/by-id/scsi-0HC_Volume_${i.id}`)throw Error(`Unexpected Hetzner volume device: ${i.name}`);if(i.size<s.declaration.size)await e.waitForAction((await e.resizeVolume(i.id,s.declaration.size)).id);if(i.protection.delete!==(s.declaration.deleteProtection!==!1))await e.waitForAction((await e.protectVolume(i.id,s.declaration.deleteProtection!==!1)).id);n.push({...s.declaration,id:i.id,device:i.linux_device,allowFormat:a})}return n}var Nn=268435456;function Wt(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function ml(e){let t=ll("sha256");for await(let r of ul(e))t.update(r);return t.digest("hex")}class Pe{name="hetzner";usesCloudFormation=!1;client;sshPrivateKeyPath;sshPublicKeyPath;sshUser;location;stateOnly;residency;waitForBoot;bootWait;async applyComputeChanges(e){let{config:t,environment:r}=e;if(t.cloud?.attachTo)throw Error("Only the compute owner may reconcile server size and volumes");let n=t.infrastructure?.compute;if(n?.resize&&!n.size)throw Error("compute.resize requires an explicit compute.size");let s=ei(t,r),i=In(n??{});if(i.appServers>1||i.dedicatedServices)throw Error("Managed compute volumes currently require a single app server");let a=await this.getComputeOutputs(e);if(!a.appInstanceId)throw Error("No existing compute server found; provision the server first");let c=await this.client.getServer(Number(a.appInstanceId)),f=await ui(this.client,c,s),h=n?.resize&&n.size?await er(this.client,c.id,We(n.size),n.resize.upgradeDisk!==!1):void 0,g={serverId:String(c.id),changes:f.flatMap((y)=>y.actions.map((C)=>({resource:y.declaration.name,action:C,detail:`${y.declaration.size} GB at ${y.declaration.mountPath}`})))};if(n?.deploymentStorage)g.changes.push({resource:n.deploymentStorage.volume,action:"place-deployments",detail:`Reconcile release directories${n.deploymentStorage.includeBackups!==!1?" and deployment backups":""} on the volume; ${n.deploymentStorage.migrateExisting?"verify and migrate existing files":"refuse nonempty directories"}`});if(h&&!h.alreadyComplete)if(!h.capacityAvailable){if(n?.resize?.whenUnavailable!=="keep-current")throw Error(`${h.targetType.name} is unavailable in ${h.location}`);g.waitingForCapacity=`${h.targetType.name} unavailable in ${h.location}; keeping ${c.server_type.name} running`}else g.changes.push({resource:c.name,action:"resize",detail:`${c.server_type.name} to ${h.targetType.name}`});if(e.dryRun)return g;if(g.waitingForCapacity)console.warn(`[ts-cloud] ${g.waitingForCapacity}`);let S=await gi(this.client,c,f),_=[{id:String(c.id),name:c.name,publicIp:c.public_net.ipv4?.ip}],v=[...Xe(t.notifications),...n?.volumes||n?.deploymentStorage?ti({volumes:S,deploymentStorage:n?.deploymentStorage,webRoot:"/var/www"}):[],...n?.monitoring!==!1?Le(n?.monitoring):[]];if(v.length){let y=await this.runRemoteDeploy({targets:_,commands:v,timeoutSeconds:7200,comment:"ts-cloud apply configured compute storage"});if(!y.success)throw Error(y.error||y.perInstance.map((C)=>C.error||C.output).join(`
285
+ `))}if(h?.capacityAvailable&&!h.alreadyComplete){let y={host:_[0].publicIp,user:this.sshUser,identityFile:this.sshPrivateKeyPath},C=await li({client:this.client,serverId:c.id,targetType:h.targetType.name,upgradeDisk:h.upgradeDisk,hooks:{preflight:()=>qc(y),afterBoot:(x,q,H,R)=>jc(y,q,H,R)}});if(C.status!=="completed"&&C.status!=="already-complete")throw Error(`Resize did not complete: ${C.status}`)}return g}constructor(e={}){this.residency=e.residency;let t=Vt(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 Hr({apiToken:t??""});let r=fo(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=m(t,r),a=`${n}-${r}-app`,c=s.runtime==="php"||!!s.php,f=In(s);if(s.reverseDns&&(f.dedicatedServices||f.appServers>1))throw Error("Reverse DNS currently requires a single owned app server");let h=t.cloud?.residency||this.residency,{assertComputeResidency:g}=await import("./chunk-nh7rcks9.js"),S=(T)=>{if(h)g(h,{country:T.location?.country||T.datacenter?.location?.country,location:T.location?.name||T.datacenter?.location?.name})};if(h){if(f.dedicatedServices||f.appServers>1)throw Error("Residency policy currently requires single-host compute");let T=await this.client.getLocation(t.hetzner?.location||this.location);g(h,{country:T.country,location:T.name})}if(f.dedicatedServices||f.appServers>1)return c?this.provisionFleet(e,f):this.provisionBunFleet(e,f);let _=ge(n,r,"app"),v=t.sites||{},y=j(s)?[]:this.collectUpstreamPorts(v),C=`${n}-${r}-app-fw`,{firewall:x}=await this.ensureFirewall(C,_,Ar({allowSsh:s.allowSsh!==!1,sitePorts:y,allowedPorts:[...s.firewall?.allowedPorts??[],...Ps(t.infrastructure?.sftp),...Ze(b(t,{environment:r}))]})),q=await this.ensureSshKey(n,r,_),H=await rt(i);if(H?.serverId){let T=await this.tryGetServer(H.serverId);if(T&&T.status!=="off"&&T.labels?.["ts-cloud/project"]===n&&T.labels?.["ts-cloud/environment"]===r){if(S(T),await this.reconcileReverseDns(e,T),s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.reconcileOwnedServices(e,T),this.outputsFromState(H,T)}}let R=await this.findExistingServer(n,r,a);if(R&&R.status!=="off"){S(R);let T={provider:"hetzner",stackName:i,serverId:R.id,serverName:R.name,publicIp:R.public_net.ipv4?.ip,publicIpv6:se(R.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};if(await nt(i,T),s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.reconcileOwnedServices(e,R),await this.reconcileReverseDns(e,R),this.outputsFromState(T,R)}let L=w(t,{environment:r}),I=L?.engine==="rpx"?G({proxy:L,config:B(v,{proxy:L,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,V=Je(t,{environment:r}),W=s.bakedImage===!0,K=M({runtime:V.runtime,runtimeVersion:V.runtimeVersion,systemPackages:s.systemPackages,database:t.infrastructure?.database,phpProvision:V.phpProvision,servicesProvision:V.servicesProvision,rpxProvision:I,baked:W,swapGb:s.swapGb}),te=oe(K),Z=We(s.size),re=qt(t),{server:ae,action:ie}=await this.client.createServer({name:a,serverType:Z,image:re,location:t.hetzner?.location||this.location,userData:te,labels:_,sshKeys:q?[q]:void 0,firewalls:[{firewall:x.id}]});await this.client.waitForAction(ie.id);let ne=await this.client.waitForServerRunning(ae.id);S(ne),await this.reconcileReverseDns(e,ne);let me={provider:"hetzner",stackName:i,serverId:ne.id,serverName:ne.name,firewallId:x.id,publicIp:ne.public_net.ipv4?.ip,publicIpv6:se(ne.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};await nt(i,me);let Se=ne.public_net.ipv4?.ip;if(Se&&this.waitForBoot)await this.waitForSshReady(Se),await this.waitForCloudInit(Se);if(s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(me,ne)}async provisionFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,i=r.infrastructure.compute,a=m(r,n),c=We(i.size),f=qt(r),h=r.hetzner?.location||this.location,g=i.bakedImage===!0,S=await rt(a);if(S?.loadBalancerId){let O=(await this.client.listLoadBalancers().catch(()=>[])).find((D)=>D.id===S.loadBalancerId);if(O)return{appPublicIp:O.public_net?.ipv4?.ip,loadBalancerIp:O.public_net?.ipv4?.ip,servicesPrivateIp:S.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}let _=await this.ensureSshKey(s,n,ge(s,n,"app")),v=`${s}-${n}-net`,C=(await this.client.listNetworks().catch(()=>[])).find((P)=>P.name===v)??await this.client.createNetwork({name:v,labels:ge(s,n,"app")}),{firewall:x}=await this.ensureFirewall(`${s}-${n}-app-fw`,ge(s,n,"app"),Ar({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),{firewall:q}=await this.ensureFirewall(`${s}-${n}-services-fw`,ge(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:[C.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[C.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[C.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[C.ip_range]}]),H=Ln(r),R=oe(M({runtime:"php",servicesProvision:H,baked:g,swapGb:i.swapGb})),L=await this.client.listServers().catch(()=>[]),I=[],V=L.find((P)=>Te(P.labels,s,n,"services"));if(!V){let{server:P,action:O}=await this.client.createServer({name:`${s}-${n}-services`,serverType:We(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:f,location:h,userData:R,labels:ge(s,n,"services"),sshKeys:_?[_]:void 0,firewalls:[{firewall:q.id}],networks:[C.id]});await this.client.waitForAction(O.id),V=await this.client.waitForServerRunning(P.id),I.push(P.id)}let W=V.id,K=V.private_net?.[0]?.ip??(await this.client.getServer(W)).private_net?.[0]?.ip,te=[...Me(!0),...Le(!0),...lt(i.sshKeys),...Xe(r.notifications)],Z=ur({versions:i.php?.versions,default:i.php?.default,extensions:i.php?.extensions,installNginx:!j(i),optimizeForProduction:i.php?.optimizeForProduction,ini:i.php?.ini}),re=oe(M({runtime:"php",phpProvision:Z,servicesProvision:te,baked:g,swapGb:i.swapGb})),ae=L.filter((P)=>Te(P.labels,s,n,"app")),ie=ae.map((P)=>P.id);if(ae.length>t.appServers)for(let P of ae.slice(t.appServers))await this.client.deleteServer(P.id).catch(()=>{}),ie.splice(ie.indexOf(P.id),1);for(let P=ae.length;P<t.appServers;P++){let{server:O,action:D}=await this.client.createServer({name:`${s}-${n}-app-${P+1}`,serverType:c,image:f,location:h,userData:re,labels:ge(s,n,"app"),sshKeys:_?[_]:void 0,firewalls:[{firewall:x.id}],networks:[C.id]});await this.client.waitForAction(D.id),ie.push(O.id),I.push(O.id)}if(this.waitForBoot&&I.length>0)await Promise.all(I.map(async(P)=>{let D=(await this.client.waitForServerRunning(P)).public_net.ipv4?.ip;if(D)await this.waitForSshReady(D),await this.waitForCloudInit(D)}));let ne=`${s}-${n}-lb`,me,Se;if(t.loadBalancer){let O=(await this.client.listLoadBalancers().catch(()=>[])).find((D)=>D.name===ne)??await this.client.createLoadBalancer({name:ne,location:h,network:C.id,labels:ge(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}]});Se=O.id,me=O.public_net?.ipv4?.ip}let T=me??(await this.client.getServer(ie[0]).catch(()=>{return}))?.public_net.ipv4?.ip,k={provider:"hetzner",stackName:a,networkId:C.id,loadBalancerId:Se,servicesServerId:W,servicesPrivateIp:K,publicIp:T,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await nt(a,k),{appPublicIp:T,loadBalancerIp:me,servicesPrivateIp:K,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=m(r,n),c=We(i.size),f=qt(r),h=r.hetzner?.location||this.location,g=i.bakedImage===!0,S=r.sites||{},_=await rt(a);if(_?.lbServerId){let D=await this.tryGetServer(_.lbServerId);if(D&&D.status!=="off"){let J=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"},Y=await this.findComputeTargets({slug:s,environment:n,role:"app",stackName:a});return this.refreshLbRoutes(D,S,Y.map((X)=>({privateIp:X.privateIp,publicIp:X.publicIp})),J,s),{appPublicIp:D.public_net.ipv4?.ip??_.publicIp,loadBalancerIp:D.public_net.ipv4?.ip??_.publicIp,servicesPrivateIp:_.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}}let v=await this.ensureSshKey(s,n,ge(s,n,"app")),y=`${s}-${n}-net`,x=(await this.client.listNetworks().catch(()=>[])).find((D)=>D.name===y)??await this.client.createNetwork({name:y,labels:ge(s,n,"app")}),q=this.collectUpstreamPorts(S),{firewall:H}=await this.ensureFirewall(`${s}-${n}-app-fw`,ge(s,n,"app"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},...q.map((D)=>({direction:"in",protocol:"tcp",port:String(D),source_ips:[x.ip_range],description:`ts-cloud port ${D} (private, LB-only)`}))]),{firewall:R}=await this.ensureFirewall(`${s}-${n}-lb-fw`,ge(s,n,"lb"),Ar({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),L=await this.client.listServers().catch(()=>[]),I=[],V,W,K=!!i.servicesServer||!!i.managedServices,te=t.dedicatedServices&&K;if(te){let{firewall:D}=await this.ensureFirewall(`${s}-${n}-services-fw`,ge(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]}]),J=Ln(r),Y=oe(M({runtime:"bun",servicesProvision:J,baked:g,swapGb:i.swapGb})),X=L.find((ee)=>Te(ee.labels,s,n,"services"));if(!X){let{server:ee,action:ue}=await this.client.createServer({name:`${s}-${n}-services`,serverType:We(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:f,location:h,userData:Y,labels:ge(s,n,"services"),sshKeys:v?[v]:void 0,firewalls:[{firewall:D.id}],networks:[x.id]});await this.client.waitForAction(ue.id),X=await this.client.waitForServerRunning(ee.id),I.push(ee.id)}V=X.id,W=X.private_net?.[0]?.ip??(await this.client.getServer(V)).private_net?.[0]?.ip}let Z=te?{...i,managedServices:void 0,backups:void 0}:i,re=Je({...r,infrastructure:{...r.infrastructure,compute:Z}},{environment:n}),ae=oe(M({runtime:re.runtime,runtimeVersion:re.runtimeVersion,systemPackages:i.systemPackages,database:r.infrastructure?.database,servicesProvision:re.servicesProvision,baked:g,swapGb:i.swapGb})),ie=L.filter((D)=>Te(D.labels,s,n,"app")),ne=ie.map((D)=>D.id);if(ie.length>t.appServers)for(let D of ie.slice(t.appServers))await this.client.deleteServer(D.id).catch(()=>{}),ne.splice(ne.indexOf(D.id),1);for(let D=ie.length;D<t.appServers;D++){let{server:J,action:Y}=await this.client.createServer({name:`${s}-${n}-app-${D+1}`,serverType:c,image:f,location:h,userData:ae,labels:ge(s,n,"app"),sshKeys:v?[v]:void 0,firewalls:[{firewall:H.id}],networks:[x.id]});await this.client.waitForAction(Y.id),ne.push(J.id),I.push(J.id)}if(this.waitForBoot&&I.length>0)await Promise.all(I.map(async(D)=>{let Y=(await this.client.waitForServerRunning(D)).public_net.ipv4?.ip;if(Y)await this.waitForSshReady(Y),await this.waitForCloudInit(Y)}));let me=[];for(let D of ne){let J=L.find((Y)=>Y.id===D);if(!J||!J.private_net?.[0]?.ip)J=await this.client.getServer(D).catch(()=>J);me.push({privateIp:J?.private_net?.[0]?.ip,publicIp:J?.public_net.ipv4?.ip})}let Se=`${s}-${n}-lb`,T,k;if(t.loadBalancer){let D=L.find((Y)=>Te(Y.labels,s,n,"lb")),J=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"};if(!D){let Y=G({proxy:J,config:rr(S,me,{proxy:J,slug:s}),slug:s,bunBin:re.runtime==="node"||re.runtime==="deno"?void 0:"/usr/local/bin/bun"}),X=oe(M({runtime:"bun",rpxProvision:Y,baked:!1})),ee=typeof i.loadBalancer==="object"?i.loadBalancer.size:void 0,{server:ue,action:E}=await this.client.createServer({name:Se,serverType:We(ee??"micro"),image:f,location:h,userData:X,labels:ge(s,n,"lb"),sshKeys:v?[v]:void 0,firewalls:[{firewall:R.id}],networks:[x.id]});if(await this.client.waitForAction(E.id),D=await this.client.waitForServerRunning(ue.id),this.waitForBoot){let N=D.public_net.ipv4?.ip;if(N)await this.waitForSshReady(N),await this.waitForCloudInit(N)}}else this.refreshLbRoutes(D,S,me,J,s);T=D.id,k=D.public_net.ipv4?.ip}let P=k??(await this.client.getServer(ne[0]).catch(()=>{return}))?.public_net.ipv4?.ip,O={provider:"hetzner",stackName:a,networkId:x.id,lbServerId:T,appServerIds:ne,servicesServerId:V,servicesPrivateIp:W,publicIp:P,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await nt(a,O),{appPublicIp:P,loadBalancerIp:k,servicesPrivateIp:W,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async destroyCompute(e){let{config:t,environment:r}=e,n=t.project.slug,s=m(t,r),i=await rt(s),a=[],c=`${n}-${r}-lb`,h=(await this.client.listLoadBalancers().catch(()=>[])).find((H)=>H.name===c);if(h)try{await this.client.deleteLoadBalancer(h.id),a.push(`load balancer ${c}`)}catch{}let g=await this.client.listServers().catch(()=>[]),S=new Set;for(let H of g)if(Te(H.labels,n,r,"app")||Te(H.labels,n,r,"services")||Te(H.labels,n,r,"lb"))S.add(H.id);if(i?.serverId)S.add(i.serverId);if(i?.servicesServerId)S.add(i.servicesServerId);if(i?.lbServerId)S.add(i.lbServerId);for(let H of i?.appServerIds??[])S.add(H);for(let H of S)try{await this.client.deleteServer(H),a.push(`server ${H}`)}catch{}let _=await this.client.listFirewalls().catch(()=>[]);for(let H of[`${n}-${r}-app-fw`,`${n}-${r}-services-fw`,`${n}-${r}-lb-fw`]){let R=_.find((L)=>L.name===H);if(!R)continue;for(let L=0;L<12;L++)try{await this.client.deleteFirewall(R.id),a.push(`firewall ${H}`);break}catch{await this.sleep(3000)}}let v=`${n}-${r}-net`,C=(await this.client.listNetworks().catch(()=>[])).find((H)=>H.name===v);if(C)for(let H=0;H<12;H++)try{await this.client.deleteNetwork(C.id),a.push(`network ${v}`);break}catch{await this.sleep(3000)}let q=(await this.client.listSshKeys().catch(()=>[])).filter((H)=>kn(H.labels,n,r));for(let H of q)try{await this.client.deleteSshKey(H.id),a.push(`ssh key ${H.name}`)}catch{}return await nt(s,{provider:"hetzner",stackName:s}).catch(()=>{}),{destroyed:a}}async getComputeOutputs(e){let t=m(e.config,e.environment),r=await rt(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:m(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:m(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,"-")}-${$o()}.tar.gz`}`,i=await ml(e.localPath),a=Fr,c=`${a}/${i}.tar.gz`;for(let f of t){if(!f.publicIp)throw Error(`Target ${f.id} has no public IP for SCP upload`);let h=["set -euo pipefail",`mkdir -p ${Wt(a)} /var/ts-cloud/staging`,`test -s ${Wt(c)}`,`cp -- ${Wt(c)} ${Wt(s)}`].join(`
286
286
  `);try{this.sshExec(f.publicIp,h);continue}catch{}let g=`${a}/.${i}-${$o()}.tmp`;try{this.scpToHost(f.publicIp,e.localPath,g),this.sshExec(f.publicIp,Cr(g,c,s))}catch(S){try{this.sshExec(f.publicIp,Pr(g))}catch{}throw S}}return{artifactRef:s}}async findComputeTargets(e){let{assertComputeResidency:t}=await import("./chunk-nh7rcks9.js"),r=e.role||"app",n=(a)=>{if(this.residency)t(this.residency,{country:a.location?.country||a.datacenter?.location?.country,location:a.location?.name||a.datacenter?.location?.name});return{id:String(a.id),name:a.name,publicIp:a.public_net.ipv4?.ip,publicIpv6:se(a.public_net.ipv6?.ip),privateIp:a.private_net?.[0]?.ip,status:a.status}};if(r==="app"||r==="lb"||r==="services"){let a=await rt(e.stackName??`${e.slug}-${e.environment}`),c=[...new Set(r==="app"?[a?.serverId,...a?.appServerIds??[]]:r==="lb"?[a?.lbServerId]:[a?.servicesServerId])].filter((g)=>typeof g==="number");if(this.stateOnly){if(this.residency)throw Error("Residency requires fresh provider evidence; a local state pin alone is insufficient");if(c.length>0&&a?.publicIp)return c.map((g)=>({id:String(g),name:g===a.serverId?a.serverName:void 0,publicIp:a.publicIp,publicIpv6:a.publicIpv6,status:"running"}));if(r!=="app")return[];throw Error(`Hetzner API token required because '${e.stackName??`${e.slug}-${e.environment}`}' has no complete local compute state pin.`)}let f=await this.client.listServers();if(c.length>0){let g=[];for(let S of c){let _=f.find((v)=>v.id===S)??await this.tryGetServer(S);if(S===a?.serverId&&a.serverName&&_?.name!==a.serverName)continue;if(_&&_.status!=="off")g.push(_)}if(g.length>0)return g.map(n)}let h=f.filter((g)=>Te(g.labels,e.slug,e.environment,r));if(h.length>0)return h.map(n);if(r==="app"){let g=f.filter((S)=>S.status!=="off"&&S.labels?.[`${he}/managed-by`]==="ts-cloud"&&S.labels?.[`${he}/environment`]===e.environment&&S.labels?.[`${he}/role`]==="app");if(g.length===1)return g.map(n)}return[]}if(this.stateOnly)throw Error(`Hetzner API token required to discover '${r}' compute targets.`);let i=(await this.client.listServers()).filter((a)=>Te(a.labels,e.slug,e.environment,r));if(i.length>0)return i.map(n);return[]}async attachToComputeInfrastructure(e,t,r){let n=await this.client.listServers(),s=(_)=>n.filter((v)=>v.status!=="off"&&Te(v.labels,e,r,_)),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],f=i[0],h=a??f,g=m(t,r),S={provider:"hetzner",stackName:g,serverId:f.id,serverName:f.name,appServerIds:i.map((_)=>_.id),lbServerId:a?.id,servicesServerId:c?.id,servicesPrivateIp:c?.private_net?.[0]?.ip,publicIp:h.public_net.ipv4?.ip,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await nt(g,S),this.outputsFromState(S)}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(`
287
287
  `),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);Or(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:Yt(r,"One or more SSH deploy commands failed")}}async ensureSshKey(e,t,r){if(!pl(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=dl(this.sshPublicKeyPath,"utf8").trim(),s=qe(n),a=(await this.client.listSshKeys()).find((f)=>qe(f.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((f)=>f.privateIp||f.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=rr(t,a,{proxy:n,slug:s});this.sshExec(i,Ne({config:c,slug:s}).join(`
288
288
  `))}async findExistingServer(e,t,r){let n=await this.client.listServers(),s=n.find((a)=>Te(a.labels,e,t,"app")||a.name===r);if(s)return s;let i=n.filter((a)=>a.status!=="off"&&a.labels?.[`${he}/managed-by`]==="ts-cloud"&&a.labels?.[`${he}/environment`]===t&&a.labels?.[`${he}/role`]==="app");if(i.length===1){let a=i[0],c=a.labels?.[`${he}/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{vo(`ssh ${this.sshBaseArgs(e,["-o","ConnectTimeout=5"]).map(Wt).join(" ")} true`,{stdio:"pipe",maxBuffer:Nn});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}:
@@ -322,7 +322,7 @@ systemctl restart systemd-journald
322
322
  # The deploy user uploads releases as itself (scp), while the scripts run as
323
323
  # root through sudo. setgid group-writable directories let both write.
324
324
  install -d -m 2775 -g "$(id -gn ${st(e)})" /var/ts-cloud/artifacts /var/ts-cloud/staging
325
- `}function Pl(e){let t=st(e),r=`/home/${e}`;return[`chown -R ${t}:"$(id -gn ${t})" ${st(`${r}/.ssh`)}`,`chmod 700 ${st(`${r}/.ssh`)}`]}function mi(e){let{config:t,environment:r,profile:n,sudoUser:s}=e;io(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,f=e.lan?{...e.lan.hostname?{hostname:e.lan.hostname}:{},tls:e.lan.tls??"local-ca",...Co(e)?{ip:Co(e)}:{}}:void 0,h=i.proxy?.engine==="rpx"?B(a,{proxy:i.proxy,slug:c,lan:f,mail:b(t,{environment:e.environment,environmentType:e.environment})}):void 0,g=i.proxy?.engine==="rpx"&&h?G({proxy:i.proxy,config:h,slug:c,profile:n,bunBin:i.runtime==="node"||i.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,S=i.proxy?.engine==="rpx"&&h?Ne({config:h,slug:c}):void 0,_=s?`/home/${s}/.ssh/authorized_keys`:void 0,v=Qe(t,{environment:r,authorizedKeysPath:_}),y=s?[...v.servicesProvision??[],...Pl(s)]:v.servicesProvision,C=[...new Set([...i.systemPackages??[],"psmisc","ca-certificates"])],x=i.swapGb??(n==="raspberry-pi"?Wg:void 0),q=M({runtime:v.runtime,runtimeVersion:v.runtimeVersion,systemPackages:C,database:t.infrastructure?.database,phpProvision:v.phpProvision,servicesProvision:y,rpxProvision:g,swapGb:x}).replace(/^#!\/bin\/bash\nset -euo pipefail\n/,""),H=Kg(),R=h?.localCa?` lan=${h.localCa.hosts.join(",")} tls=local-ca`:f?` lan=${f.hostname??`${c}.local`} tls=${f.tls??"local-ca"}`:"",L=`#!/bin/bash
325
+ `}function Pl(e){let t=st(e),r=`/home/${e}`;return[`chown -R ${t}:"$(id -gn ${t})" ${st(`${r}/.ssh`)}`,`chmod 700 ${st(`${r}/.ssh`)}`]}function mi(e){let{config:t,environment:r,profile:n,sudoUser:s}=e;io(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,f=e.lan?{...e.lan.hostname?{hostname:e.lan.hostname}:{},tls:e.lan.tls??"local-ca",...Co(e)?{ip:Co(e)}:{}}:void 0,h=i.proxy?.engine==="rpx"?B(a,{proxy:i.proxy,slug:c,lan:f,mail:b(t,{environment:e.environment,environmentType:e.environment})}):void 0,g=i.proxy?.engine==="rpx"&&h?G({proxy:i.proxy,config:h,slug:c,profile:n,bunBin:i.runtime==="node"||i.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,S=i.proxy?.engine==="rpx"&&h?Ne({config:h,slug:c}):void 0,_=s?`/home/${s}/.ssh/authorized_keys`:void 0,v=Je(t,{environment:r,authorizedKeysPath:_}),y=s?[...v.servicesProvision??[],...Pl(s)]:v.servicesProvision,C=[...new Set([...i.systemPackages??[],"psmisc","ca-certificates"])],x=i.swapGb??(n==="raspberry-pi"?Wg:void 0),q=M({runtime:v.runtime,runtimeVersion:v.runtimeVersion,systemPackages:C,database:t.infrastructure?.database,phpProvision:v.phpProvision,servicesProvision:y,rpxProvision:g,swapGb:x}).replace(/^#!\/bin\/bash\nset -euo pipefail\n/,""),H=Kg(),R=h?.localCa?` lan=${h.localCa.hosts.join(",")} tls=local-ca`:f?` lan=${f.hostname??`${c}.local`} tls=${f.tls??"local-ca"}`:"",L=`#!/bin/bash
326
326
  set -euo pipefail
327
327
  # ts-cloud ssh bootstrap v${ke} profile=${n}${R}
328
328