@stacksjs/ts-cloud 0.16.25 → 0.16.26

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 (114) hide show
  1. package/dist/aws/cloudfront.d.ts +88 -49
  2. package/dist/aws/index.js +1 -1
  3. package/dist/bin/chunk-08hxbrmv.js +1 -0
  4. package/dist/bin/{chunk-y4g86dpe.js → chunk-0apv4e8e.js} +2 -2
  5. package/dist/bin/{chunk-fdsh3m2q.js → chunk-0hbrkdrc.js} +1 -1
  6. package/dist/bin/{chunk-h1618tyv.js → chunk-10dnawvx.js} +1 -1
  7. package/dist/bin/{chunk-9066j2kz.js → chunk-2857cbf1.js} +1 -1
  8. package/dist/bin/chunk-2qrr4ydb.js +1 -0
  9. package/dist/bin/{chunk-db9zx72q.js → chunk-3rzabz10.js} +1 -1
  10. package/dist/bin/{chunk-t5gkbppg.js → chunk-4a8qt6e8.js} +12 -12
  11. package/dist/bin/chunk-4jgespb7.js +1 -0
  12. package/dist/bin/{chunk-mdbzfvba.js → chunk-4xfwb21f.js} +1 -1
  13. package/dist/bin/{chunk-8wnpx6n2.js → chunk-5ky6qf18.js} +10 -10
  14. package/dist/bin/{chunk-21jwbrap.js → chunk-817q3s2p.js} +1 -1
  15. package/dist/bin/{chunk-9rya3733.js → chunk-85733wwc.js} +50 -50
  16. package/dist/bin/{chunk-g0gqwszk.js → chunk-8hnph1yy.js} +1 -1
  17. package/dist/bin/{chunk-n5zwm2z4.js → chunk-8k87zpnp.js} +1 -1
  18. package/dist/bin/{chunk-p1cv4n00.js → chunk-8tp6srfc.js} +1 -1
  19. package/dist/bin/{chunk-td8zgch7.js → chunk-92rhkvpx.js} +2 -2
  20. package/dist/bin/{chunk-tnzp96vn.js → chunk-ccykpema.js} +1 -1
  21. package/dist/bin/{chunk-nxyhheav.js → chunk-cgyqnbcm.js} +1 -1
  22. package/dist/bin/{chunk-0xxc6dy8.js → chunk-e3tjy3wg.js} +1 -1
  23. package/dist/bin/chunk-eshss5qy.js +2 -0
  24. package/dist/bin/{chunk-ntmnpteh.js → chunk-f4rp62j4.js} +8 -8
  25. package/dist/bin/chunk-ff888cnm.js +1 -0
  26. package/dist/bin/{chunk-n8ya6q6d.js → chunk-fjxsj9z9.js} +1 -1
  27. package/dist/bin/{chunk-3kvz4kyq.js → chunk-h3shxxh4.js} +1 -1
  28. package/dist/bin/{chunk-z96ssb7e.js → chunk-hvd87xj9.js} +1 -1
  29. package/dist/bin/chunk-jxyt009c.js +1 -0
  30. package/dist/bin/chunk-kxmq7r53.js +1 -0
  31. package/dist/bin/{chunk-v4e4726j.js → chunk-qsyna6ng.js} +1 -1
  32. package/dist/bin/{chunk-mfer1e5z.js → chunk-qxssaa4s.js} +1 -1
  33. package/dist/bin/{chunk-78tzgf65.js → chunk-r2ft7vek.js} +1 -1
  34. package/dist/bin/{chunk-82sbpydz.js → chunk-rfvx641h.js} +1 -1
  35. package/dist/bin/chunk-swnef46q.js +1 -0
  36. package/dist/bin/chunk-v95b2dy0.js +1 -0
  37. package/dist/bin/chunk-wjwxtz68.js +1 -0
  38. package/dist/bin/{chunk-gj530nqd.js → chunk-x2r1zm2r.js} +1 -1
  39. package/dist/bin/{chunk-5mk3sxpw.js → chunk-z3962as2.js} +1 -1
  40. package/dist/bin/{chunk-mrte8smv.js → chunk-zvt7as22.js} +1 -1
  41. package/dist/bin/cli.js +375 -375
  42. package/dist/bin/dashboard-server.js +1 -1
  43. package/dist/{chunk-826gp2kd.js → chunk-k75jv8s6.js} +1 -1
  44. package/dist/{chunk-jwx5t3vf.js → chunk-mdqnpbbc.js} +9 -9
  45. package/dist/{chunk-r1730x8g.js → chunk-mte9da2p.js} +2 -2
  46. package/dist/{chunk-kmwnzw91.js → chunk-nkd35khb.js} +1 -1
  47. package/dist/deploy/index.js +1 -1
  48. package/dist/index.d.ts +1 -1
  49. package/dist/index.js +1 -1
  50. package/dist/ui/404.html +1 -1
  51. package/dist/ui/accept-invitation.html +1 -1
  52. package/dist/ui/access-denied.html +1 -1
  53. package/dist/ui/account/automation.html +6 -6
  54. package/dist/ui/account/security.html +2 -2
  55. package/dist/ui/applications/compose.html +6 -6
  56. package/dist/ui/applications/new.html +2 -2
  57. package/dist/ui/data/backups.html +6 -6
  58. package/dist/ui/data/services.html +6 -6
  59. package/dist/ui/data/volumes.html +6 -6
  60. package/dist/ui/index.html +5 -5
  61. package/dist/ui/infrastructure/topology.html +6 -6
  62. package/dist/ui/integrations.html +2 -2
  63. package/dist/ui/operations/alerts.html +6 -6
  64. package/dist/ui/operations/configuration.html +6 -6
  65. package/dist/ui/operations/jobs.html +5 -5
  66. package/dist/ui/operations/maintenance.html +5 -5
  67. package/dist/ui/operations/observability.html +6 -6
  68. package/dist/ui/operations/previews.html +5 -5
  69. package/dist/ui/operations/queue.html +6 -6
  70. package/dist/ui/operations/regions.html +5 -5
  71. package/dist/ui/operations/releases.html +6 -6
  72. package/dist/ui/operations/spend.html +6 -6
  73. package/dist/ui/operations/workloads.html +6 -6
  74. package/dist/ui/security.html +1 -1
  75. package/dist/ui/server/actions.html +6 -6
  76. package/dist/ui/server/activity.html +1 -1
  77. package/dist/ui/server/capacity.html +6 -6
  78. package/dist/ui/server/database.html +6 -6
  79. package/dist/ui/server/deployments.html +6 -6
  80. package/dist/ui/server/diagnostics.html +2 -2
  81. package/dist/ui/server/firewall.html +6 -6
  82. package/dist/ui/server/fleet.html +6 -6
  83. package/dist/ui/server/logs.html +6 -6
  84. package/dist/ui/server/metrics.html +6 -6
  85. package/dist/ui/server/security.html +2 -2
  86. package/dist/ui/server/services.html +1 -1
  87. package/dist/ui/server/sites.html +6 -6
  88. package/dist/ui/server/ssh-keys.html +6 -6
  89. package/dist/ui/server/team.html +6 -6
  90. package/dist/ui/server/terminal.html +2 -2
  91. package/dist/ui/serverless/alarms.html +6 -6
  92. package/dist/ui/serverless/assets.html +2 -2
  93. package/dist/ui/serverless/cost.html +2 -2
  94. package/dist/ui/serverless/data.html +6 -6
  95. package/dist/ui/serverless/deployments.html +2 -2
  96. package/dist/ui/serverless/firewall.html +1 -1
  97. package/dist/ui/serverless/functions.html +5 -5
  98. package/dist/ui/serverless/logs.html +6 -6
  99. package/dist/ui/serverless/metrics.html +2 -2
  100. package/dist/ui/serverless/queues.html +6 -6
  101. package/dist/ui/serverless/secrets.html +6 -6
  102. package/dist/ui/serverless/traces.html +6 -6
  103. package/dist/ui/serverless.html +6 -6
  104. package/package.json +3 -3
  105. package/dist/bin/chunk-4261t3bq.js +0 -1
  106. package/dist/bin/chunk-4a98nszr.js +0 -1
  107. package/dist/bin/chunk-ajv4z454.js +0 -1
  108. package/dist/bin/chunk-cnmngqqg.js +0 -1
  109. package/dist/bin/chunk-dhj4786e.js +0 -1
  110. package/dist/bin/chunk-es4sdbrr.js +0 -1
  111. package/dist/bin/chunk-hje6rsxj.js +0 -2
  112. package/dist/bin/chunk-ksfr2ya8.js +0 -1
  113. package/dist/bin/chunk-s7axkfrs.js +0 -1
  114. package/dist/bin/chunk-yavtz60y.js +0 -1
@@ -1,4 +1,4 @@
1
- import{Gs,A,C,hi,Js,Xs,F,E,qt,Pr}from"./chunk-t5gkbppg.js";import{u}from"./chunk-q3xwh0r8.js";import{v}from"./chunk-v4e4726j.js";import{Q}from"./chunk-w23en85y.js";import{g}from"./chunk-2q27v6vz.js";import{J,ai,_s,P,U,br,St,Ze,fo,ci,yo,bt,lc,So,bo,ui,vo,Bt,Ls,dc,pi,Ms,Us,Bs,Fs,To,tn,rn,js,Eo}from"./chunk-0xxc6dy8.js";import{co,lo,Ts}from"./chunk-9066j2kz.js";import{Wr}from"./chunk-xss6yj73.js";import{Ss}from"./chunk-9464wvf2.js";import{yr}from"./chunk-wsedynyb.js";import{existsSync as Bl,readFileSync as Kl}from"node:fs";import{readFileSync as rs}from"node:fs";import{join as Ea}from"node:path";function qo(e={}){let t=new Set;for(let r of Object.values(e)){if(!r.domain)continue;if(r.redirect||r.deploy==="server"||r.start)t.add(r.domain)}return t}function er(e){return e.replace(/\.$/,"").toLowerCase()}function Ro(e,t,r){let n=er(e.name),s=er(t),i=er(r),o=i===s?"@":i.endsWith(`.${s}`)?i.slice(0,-(s.length+1)):i;return n===i||n===o||o==="@"&&(n===""||n===s)}async function Oo(e,t,r,n,s="A"){let i=await e.listRecords(t);if(!i.success)return[`could not list ${s} records: ${i.message||"unknown provider error"}`];let o=i.records.filter((l)=>l.type===s&&Ro(l,t,r)),a=o.findIndex((l)=>l.content===n);if(o.length<=1||a===-1)return[];let c=[];for(let[l,p]of o.entries()){if(l===a)continue;let d=await e.deleteRecord(t,p);if(!d.success)c.push(`could not remove stale ${p.name} ${s} ${p.content}: ${d.message||"unknown provider error"}`)}return c}function ue(e){if(!e)return;let t=e.trim();if(!t)return;if(!t.includes("/"))return t;let[r]=t.split("/");if(!r.endsWith("::"))return r||void 0;return`${r}1`}var Do=new Set(["mail","smtp","imap","mx"]);function ki(e){return!Do.has(e.split(".")[0]??"")}async function Wn(e){let{provider:t,zone:r,fqdn:n,ipv4:s,ipv6:i,ttl:o=600}=e,a={published:[],warnings:[]},c=[{type:"A",content:s}];if(i&&ki(n))c.push({type:"AAAA",content:i});for(let{type:l,content:p}of c){let d=await t.upsertRecord(r,{name:n,type:l,content:p,ttl:o});if(d?.success===!1){a.warnings.push(`${n} → ${p} failed: ${d.error||d.message||"unknown error"}`);continue}if(a.warnings.push(...(await Oo(t,r,n,p,l)).map((m)=>`${n} cleanup: ${m}`)),await _i(t,r,n,p,l))a.published.push({fqdn:n,type:l,content:p});else a.warnings.push(`${n} → ${p} reported success at ${t.name} but no matching ${l} record exists — create it manually: ${l} ${n} → ${p}`)}return a}async function _i(e,t,r,n,s){try{if(typeof e?.listRecords!=="function")return!0;let i=await e.listRecords(t);if(!i?.success||!Array.isArray(i.records))return!0;return i.records.some((o)=>{let a=typeof o?.name==="string"?o.name.replace(/\.$/,""):"";return o?.type===s&&a===r&&o?.content===n})}catch{return!0}}function tr(e){return(Buffer.isBuffer(e)?e.toString("utf8"):typeof e==="string"?e:"").replace(/(^|\n)(\s*(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*=).*$/gm,"$1$2[redacted]").replace(/encrypted:[A-Za-z0-9+/=]+/g,"encrypted:[redacted]").trim().slice(-8000)}function st(e,t){let r=tr(e?.stderr),n=/line (\d+): syntax error/.exec(r);if(!n)return"";let s=Number(n[1]),i=t.split(`
1
+ import{Gs,A,C,hi,Js,Xs,F,E,qt,Pr}from"./chunk-4a8qt6e8.js";import{u}from"./chunk-q3xwh0r8.js";import{v}from"./chunk-qsyna6ng.js";import{Q}from"./chunk-w23en85y.js";import{g}from"./chunk-2q27v6vz.js";import{J,ai,_s,P,U,br,St,Ze,fo,ci,yo,bt,lc,So,bo,ui,vo,Bt,Ls,dc,pi,Ms,Us,Bs,Fs,To,tn,rn,js,Eo}from"./chunk-e3tjy3wg.js";import{co,lo,Ts}from"./chunk-2857cbf1.js";import{Wr}from"./chunk-xss6yj73.js";import{Ss}from"./chunk-9464wvf2.js";import{yr}from"./chunk-wsedynyb.js";import{existsSync as Bl,readFileSync as Kl}from"node:fs";import{readFileSync as rs}from"node:fs";import{join as Ea}from"node:path";function qo(e={}){let t=new Set;for(let r of Object.values(e)){if(!r.domain)continue;if(r.redirect||r.deploy==="server"||r.start)t.add(r.domain)}return t}function er(e){return e.replace(/\.$/,"").toLowerCase()}function Ro(e,t,r){let n=er(e.name),s=er(t),i=er(r),o=i===s?"@":i.endsWith(`.${s}`)?i.slice(0,-(s.length+1)):i;return n===i||n===o||o==="@"&&(n===""||n===s)}async function Oo(e,t,r,n,s="A"){let i=await e.listRecords(t);if(!i.success)return[`could not list ${s} records: ${i.message||"unknown provider error"}`];let o=i.records.filter((l)=>l.type===s&&Ro(l,t,r)),a=o.findIndex((l)=>l.content===n);if(o.length<=1||a===-1)return[];let c=[];for(let[l,p]of o.entries()){if(l===a)continue;let d=await e.deleteRecord(t,p);if(!d.success)c.push(`could not remove stale ${p.name} ${s} ${p.content}: ${d.message||"unknown provider error"}`)}return c}function ue(e){if(!e)return;let t=e.trim();if(!t)return;if(!t.includes("/"))return t;let[r]=t.split("/");if(!r.endsWith("::"))return r||void 0;return`${r}1`}var Do=new Set(["mail","smtp","imap","mx"]);function ki(e){return!Do.has(e.split(".")[0]??"")}async function Wn(e){let{provider:t,zone:r,fqdn:n,ipv4:s,ipv6:i,ttl:o=600}=e,a={published:[],warnings:[]},c=[{type:"A",content:s}];if(i&&ki(n))c.push({type:"AAAA",content:i});for(let{type:l,content:p}of c){let d=await t.upsertRecord(r,{name:n,type:l,content:p,ttl:o});if(d?.success===!1){a.warnings.push(`${n} → ${p} failed: ${d.error||d.message||"unknown error"}`);continue}if(a.warnings.push(...(await Oo(t,r,n,p,l)).map((m)=>`${n} cleanup: ${m}`)),await _i(t,r,n,p,l))a.published.push({fqdn:n,type:l,content:p});else a.warnings.push(`${n} → ${p} reported success at ${t.name} but no matching ${l} record exists — create it manually: ${l} ${n} → ${p}`)}return a}async function _i(e,t,r,n,s){try{if(typeof e?.listRecords!=="function")return!0;let i=await e.listRecords(t);if(!i?.success||!Array.isArray(i.records))return!0;return i.records.some((o)=>{let a=typeof o?.name==="string"?o.name.replace(/\.$/,""):"";return o?.type===s&&a===r&&o?.content===n})}catch{return!0}}function tr(e){return(Buffer.isBuffer(e)?e.toString("utf8"):typeof e==="string"?e:"").replace(/(^|\n)(\s*(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*=).*$/gm,"$1$2[redacted]").replace(/encrypted:[A-Za-z0-9+/=]+/g,"encrypted:[redacted]").trim().slice(-8000)}function st(e,t){let r=tr(e?.stderr),n=/line (\d+): syntax error/.exec(r);if(!n)return"";let s=Number(n[1]),i=t.split(`
2
2
  `),o=Math.max(1,s-12),a=Math.min(i.length,s+2),c=i.slice(o-1,a).map((l,p)=>{let d=o+p,m=/^[A-Z_][A-Z0-9_]*=/.test(l)?l.replace(/=.*/,"=<redacted>"):l;return` ${String(d).padStart(4)}${d===s?" >":" "} ${m}`});return["",`The deploy script bash rejected is ${i.length} lines; it stopped at ${s}.`,...c].join(`
3
3
  `)}function Pe(e){let t=e,r=typeof t?.status==="number"?` (exit ${t.status})`:"",n=t?.signal?` (signal ${t.signal})`:"",s=[tr(t?.stderr),tr(t?.stdout)].filter(Boolean).join(`
4
4
  `);return`Remote SSH command failed${r}${n}${s?`
@@ -12,7 +12,7 @@ EOF`,`DISK_PCT=$(df -P / | awk 'NR==2{gsub("%","",$5); print $5}')`,"UPTIME_SEC=
12
12
  `)}
13
13
  `}return`${["server {"," listen 80;"," listen [::]:80;",` server_name ${r};`,...n,"}"].join(`
14
14
  `)}
15
- `}function nr(e){let t=`/etc/nginx/sites-available/${e.siteName}`,r=`/etc/nginx/sites-enabled/${e.siteName}`,n=sa(e),s=[...ir()];if(e.auth){let i=En(e.siteName),o=(l)=>l.split("'").join("'\\''"),a=o(e.auth.password),c=o(e.auth.username);s.push(`TS_CLOUD_HTPASS=$(openssl passwd -apr1 '${a}')`,`printf '%s:%s\\n' '${c}' "$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",`${be} -t`,"systemctl reload ts-cloud-nginx 2>/dev/null || systemctl restart ts-cloud-nginx 2>/dev/null || true"),s}var be="/usr/local/bin/ts-cloud-nginx";function ir(e="/opt/pantry"){return[...br(),...Ze(["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 > ${be} <<'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 ${be}`,"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=${be} -t`,`ExecStart=${be} -g 'daemon off;'`,`ExecReload=${be} -s reload`,"Restart=always","RestartSec=3","","[Install]","WantedBy=multi-user.target","TS_CLOUD_NGINXUNIT_EOF","systemctl daemon-reload","systemctl enable ts-cloud-nginx","ls /etc/nginx/sites-enabled/* >/dev/null 2>&1 && systemctl restart ts-cloud-nginx || true"]}function it(e,t){return!e.events||e.events.includes(t)}async function pr(e,t,r,n={}){if(!e)return[];let s=n.fetchImpl??globalThis.fetch,i=[],o=[],a=(c,l)=>s(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)}).catch(()=>{return});if(e.slack?.webhookUrl&&it(e,t))i.push("slack"),o.push(a(e.slack.webhookUrl,{text:r}));if(e.discord?.webhookUrl&&it(e,t))i.push("discord"),o.push(a(e.discord.webhookUrl,{content:r}));if(e.telegram?.botToken&&e.telegram.chatId&&it(e,t)){i.push("telegram");let c=`https://api.telegram.org/bot${e.telegram.botToken}/sendMessage`;o.push(a(c,{chat_id:e.telegram.chatId,text:r}))}if(e.webhook?.url&&it(e,t))if(i.push("webhook"),(e.webhook.method||"POST")==="GET"){let c=e.webhook.url.includes("?")?"&":"?",l=`${e.webhook.url}${c}event=${encodeURIComponent(t)}&message=${encodeURIComponent(r)}`;o.push(s(l,{method:"GET"}).catch(()=>{return}))}else o.push(a(e.webhook.url,{event:t,message:r}));if(e.email?.to&&it(e,t))i.push("email"),o.push(ia(e.email,t,r));return await Promise.all(o),i}async function ia(e,t,r){try{let n=await import("./chunk-g0gqwszk.js");await n.email.send({to:e.to,from:e.from,subject:`[ts-cloud] ${t}`,text:r})}catch{}}function On(e,t){return t??e}function ke(e){if(!e)return[];let t=[];if(e.slack?.webhookUrl)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"text\\":\\"$MSG\\"}" ${e.slack.webhookUrl} || true`);if(e.discord?.webhookUrl)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"content\\":\\"$MSG\\"}" ${e.discord.webhookUrl} || true`);if(e.telegram?.botToken&&e.telegram.chatId)t.push(`curl -fsS -X POST "https://api.telegram.org/bot${e.telegram.botToken}/sendMessage" --data-urlencode "chat_id=${e.telegram.chatId}" --data-urlencode "text=$MSG" || true`);if(e.webhook?.url)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"message\\":\\"$MSG\\"}" ${e.webhook.url} || true`);if(t.length===0)return[];return["cat > /usr/local/bin/ts-cloud-notify <<'TS_CLOUD_NOTIFY_EOF'","#!/bin/bash",'MSG="$1"',...t,"TS_CLOUD_NOTIFY_EOF","chmod +x /usr/local/bin/ts-cloud-notify"]}import{isIP as In}from"node:net";var Fr="/etc/rpx/certs",An="/etc/rpx/local-ca",oa="rpx-root-ca.crt";function Ct(e=An){return`${e.replace(/\/+$/,"")}/${oa}`}function hr(e){if(e.toLowerCase().endsWith(".local"))return!1;return e.split(".").length===2}function $i(e,t={}){let r=new Set;for(let n of Object.values(e)){if(!n?.domain)continue;if(P(n)==="bucket")continue;r.add(n.domain)}if(t.autoWww!==!1)for(let n of[...r]){if(!hr(n))continue;r.add(`www.${n}`)}return[...r]}var aa=["1.1.1.1","8.8.8.8"],ca="/var/www/acme-challenge";function la(e){if(typeof e==="string")return{to:e};let t={to:e.to};if(e.status!=null)t.status=e.status;if(e.preservePath!=null)t.preservePath=e.preservePath;return t}function ua(e){let t=e.auth;if(!t||t.enabled===!1||!t.password)return;return{username:t.username||"admin",password:t.password,...t.realm?{realm:t.realm}:{}}}function Sr(e){if(!e)return;return e.tls??"local-ca"}function Oi(e,t){if(e.cloud?.provider!=="ssh")return;let r=e.ssh?.lan;if(!r)return;return{...r.hostname?{hostname:r.hostname}:{},tls:r.tls??"local-ca",...t?{ip:t}:{}}}function Ln(e){if(e.cloud?.provider!=="ssh")return;return e.ssh?.profile}function pa(e){let t=e.trim().toLowerCase();if(!t||t.startsWith("*")||t.includes(":")||t.includes("/")||t.includes(" "))return!1;if(In(t)!==0)return!1;return t.endsWith(".local")||!t.includes(".")}function da(e,t,r){let n=[],s=new Set,i=(l,p)=>{let d=l.trim().toLowerCase();if(!d||s.has(d))return;s.add(d),n.push({host:d,source:p})},o=t.hostname?.trim(),a=(o||`${r}.local`).toLowerCase();if(i(a,o?"ssh.lan.hostname":`the ssh provider's default LAN name for project "${r}"`),Object.entries(e).some(([l,p])=>!!p&&Pr(l)))i(`dashboard.${a}`,"the management dashboard site");for(let[l,p]of Object.entries(e)){if(!p?.domain)continue;if(P(p)==="bucket")continue;if(!pa(p.domain))continue;i(p.domain,`site "${l}"`)}return n}function ma(e,t){if(!t?.length)return;return t.find((r)=>{let n=(r.startsWith(".")?r.slice(1):r).toLowerCase();return e===n||e.endsWith(`.${n}`)})}function fa(e,t){if(!t?.enabled)return;for(let{host:r,source:n}of e){let s=ma(r,t.allowedSuffixes);if(!s)continue;throw Error(`The LAN certificate authority and public on-demand TLS both claim "${r}". LAN source: ${n}. Public source: the on-demand TLS allowed suffix "${s}", which is derived from the site domains. A host is either LAN-only, with a certificate signed by the box's own CA, or public, with one issued by Let's Encrypt, never both. Give the LAN a name no site domain covers (ssh.lan.hostname), or take that domain out of the sites this deploy routes.`)}}function Hn(e){if(!e||e==="/")return;let t=`/${e}`.replace(/\/+/g,"/").replace(/\/+$/,"");if(!t.startsWith("/"))t=`/${t}`;return t===""||t==="/"?void 0:t}function mr(e,t){let n=(t?`${e}${t}`:e).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return n.length>0?n:"rpx"}function ga(e,t){if(!t||t.length===0)return`localhost:${e}`;return t.map((r)=>`${r.privateIp??r.publicIp}:${e}`)}function Nn(e,t,r){let n=(t.wwwRoot??"/var/www").replace(/\/+$/,""),s=t.slug??"app",i=t.proxy.certsDir??Fr,o=t.proxy.loadBalancer,a=[],c=new Set;for(let[m,f]of Object.entries(e)){if(!f||!f.domain)continue;let h=P(f);if(h==="bucket")continue;let _=Hn(f.path),w=mr(f.domain,_),b=ua(f);if(h==="redirect"){a.push({to:f.domain,path:_,redirect:la(f.redirect),id:w,...b?{auth:b}:{}}),c.add(f.domain);continue}if(h==="proxy"){let S=_s(f);if(S.length===0)continue;let T=S.length===1?S[0]:S;a.push({to:f.domain,path:_,from:T,id:w,...b?{auth:b}:{},...Array.isArray(T)&&o?{loadBalancer:o}:{}}),c.add(f.domain);continue}if(h==="server-app"){if(typeof f.port!=="number")continue;let S=ga(f.port,r);a.push({to:f.domain,path:_,from:S,id:w,...b?{auth:b}:{},...Array.isArray(S)&&o?{loadBalancer:o}:{}})}else a.push({to:f.domain,path:_,static:{dir:`${n}/${s}-${m}/current`,spa:f.spa??!1,pathRewriteStyle:f.pathRewriteStyle??"directory"},cleanUrls:f.pathRewriteStyle!=="flat",...b?{auth:b}:{},id:w});c.add(f.domain)}if(t.proxy.autoWww!==!1)for(let m of[...c]){if(!hr(m))continue;let f=`www.${m}`;if(c.has(f))continue;a.push({to:f,redirect:{to:`https://${m}`},id:mr(f)}),c.add(f)}a.sort((m,f)=>{if(m.to!==f.to)return m.to.localeCompare(f.to);return(f.path?.length??0)-(m.path?.length??0)});let l={proxies:a,productionCerts:{certsDir:i,certsDirServerNames:[...c]},https:!0,hostsManagement:!1,cleanup:{hosts:!1,certs:!1}};if(t.proxy.onDemandTls&&c.size>0)l.onDemandTls={enabled:!0,allowedSuffixes:[...c],email:t.proxy.onDemandTlsEmail,certsDir:i,staging:t.proxy.onDemandTlsStaging??!1};if(t.proxy.onDemandTls)l.acmeChallengeWebroot=t.proxy.acmeWebroot??ca;let p=t.proxy.cdn,d=p?.frontedHosts?.length?p.frontedHosts:[...c];if(p?.secret&&d.length>0)l.originGuard={header:p.secretHeader??"X-Origin-Verify",value:p.secret,hosts:d};if(t.lan)if(Sr(t.lan)==="off")l.https=!1;else{let m=da(e,t.lan,s);fa(m,l.onDemandTls);let f=t.lan.ip&&In(t.lan.ip)!==0?[t.lan.ip]:[];l.localCa={dir:An,hosts:m.map((h)=>h.host),...f.length>0?{ips:f}:{},installTrust:!0}}return l}function ye(e,t){return Nn(e,t)}function Fe(e,t,r){return Nn(e,r,t)}function Y(e){return e?.webServer==="rpx"||e?.proxy?.engine==="rpx"}var ot="/etc/rpx",V="/opt/rpx-gateway",fr="/etc/rpx/gateway.ts",Ue="/etc/rpx/gateway",le="rpx-gateway.service",ee="/etc/rpx/sites.d";function ha(e=ee,t=Fr){return`// Generated by ts-cloud — rpx gateway assembler.
15
+ `}function nr(e){let t=`/etc/nginx/sites-available/${e.siteName}`,r=`/etc/nginx/sites-enabled/${e.siteName}`,n=sa(e),s=[...ir()];if(e.auth){let i=En(e.siteName),o=(l)=>l.split("'").join("'\\''"),a=o(e.auth.password),c=o(e.auth.username);s.push(`TS_CLOUD_HTPASS=$(openssl passwd -apr1 '${a}')`,`printf '%s:%s\\n' '${c}' "$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",`${be} -t`,"systemctl reload ts-cloud-nginx 2>/dev/null || systemctl restart ts-cloud-nginx 2>/dev/null || true"),s}var be="/usr/local/bin/ts-cloud-nginx";function ir(e="/opt/pantry"){return[...br(),...Ze(["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 > ${be} <<'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 ${be}`,"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=${be} -t`,`ExecStart=${be} -g 'daemon off;'`,`ExecReload=${be} -s reload`,"Restart=always","RestartSec=3","","[Install]","WantedBy=multi-user.target","TS_CLOUD_NGINXUNIT_EOF","systemctl daemon-reload","systemctl enable ts-cloud-nginx","ls /etc/nginx/sites-enabled/* >/dev/null 2>&1 && systemctl restart ts-cloud-nginx || true"]}function it(e,t){return!e.events||e.events.includes(t)}async function pr(e,t,r,n={}){if(!e)return[];let s=n.fetchImpl??globalThis.fetch,i=[],o=[],a=(c,l)=>s(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)}).catch(()=>{return});if(e.slack?.webhookUrl&&it(e,t))i.push("slack"),o.push(a(e.slack.webhookUrl,{text:r}));if(e.discord?.webhookUrl&&it(e,t))i.push("discord"),o.push(a(e.discord.webhookUrl,{content:r}));if(e.telegram?.botToken&&e.telegram.chatId&&it(e,t)){i.push("telegram");let c=`https://api.telegram.org/bot${e.telegram.botToken}/sendMessage`;o.push(a(c,{chat_id:e.telegram.chatId,text:r}))}if(e.webhook?.url&&it(e,t))if(i.push("webhook"),(e.webhook.method||"POST")==="GET"){let c=e.webhook.url.includes("?")?"&":"?",l=`${e.webhook.url}${c}event=${encodeURIComponent(t)}&message=${encodeURIComponent(r)}`;o.push(s(l,{method:"GET"}).catch(()=>{return}))}else o.push(a(e.webhook.url,{event:t,message:r}));if(e.email?.to&&it(e,t))i.push("email"),o.push(ia(e.email,t,r));return await Promise.all(o),i}async function ia(e,t,r){try{let n=await import("./chunk-8hnph1yy.js");await n.email.send({to:e.to,from:e.from,subject:`[ts-cloud] ${t}`,text:r})}catch{}}function On(e,t){return t??e}function ke(e){if(!e)return[];let t=[];if(e.slack?.webhookUrl)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"text\\":\\"$MSG\\"}" ${e.slack.webhookUrl} || true`);if(e.discord?.webhookUrl)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"content\\":\\"$MSG\\"}" ${e.discord.webhookUrl} || true`);if(e.telegram?.botToken&&e.telegram.chatId)t.push(`curl -fsS -X POST "https://api.telegram.org/bot${e.telegram.botToken}/sendMessage" --data-urlencode "chat_id=${e.telegram.chatId}" --data-urlencode "text=$MSG" || true`);if(e.webhook?.url)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"message\\":\\"$MSG\\"}" ${e.webhook.url} || true`);if(t.length===0)return[];return["cat > /usr/local/bin/ts-cloud-notify <<'TS_CLOUD_NOTIFY_EOF'","#!/bin/bash",'MSG="$1"',...t,"TS_CLOUD_NOTIFY_EOF","chmod +x /usr/local/bin/ts-cloud-notify"]}import{isIP as In}from"node:net";var Fr="/etc/rpx/certs",An="/etc/rpx/local-ca",oa="rpx-root-ca.crt";function Ct(e=An){return`${e.replace(/\/+$/,"")}/${oa}`}function hr(e){if(e.toLowerCase().endsWith(".local"))return!1;return e.split(".").length===2}function $i(e,t={}){let r=new Set;for(let n of Object.values(e)){if(!n?.domain)continue;if(P(n)==="bucket")continue;r.add(n.domain)}if(t.autoWww!==!1)for(let n of[...r]){if(!hr(n))continue;r.add(`www.${n}`)}return[...r]}var aa=["1.1.1.1","8.8.8.8"],ca="/var/www/acme-challenge";function la(e){if(typeof e==="string")return{to:e};let t={to:e.to};if(e.status!=null)t.status=e.status;if(e.preservePath!=null)t.preservePath=e.preservePath;return t}function ua(e){let t=e.auth;if(!t||t.enabled===!1||!t.password)return;return{username:t.username||"admin",password:t.password,...t.realm?{realm:t.realm}:{}}}function Sr(e){if(!e)return;return e.tls??"local-ca"}function Oi(e,t){if(e.cloud?.provider!=="ssh")return;let r=e.ssh?.lan;if(!r)return;return{...r.hostname?{hostname:r.hostname}:{},tls:r.tls??"local-ca",...t?{ip:t}:{}}}function Ln(e){if(e.cloud?.provider!=="ssh")return;return e.ssh?.profile}function pa(e){let t=e.trim().toLowerCase();if(!t||t.startsWith("*")||t.includes(":")||t.includes("/")||t.includes(" "))return!1;if(In(t)!==0)return!1;return t.endsWith(".local")||!t.includes(".")}function da(e,t,r){let n=[],s=new Set,i=(l,p)=>{let d=l.trim().toLowerCase();if(!d||s.has(d))return;s.add(d),n.push({host:d,source:p})},o=t.hostname?.trim(),a=(o||`${r}.local`).toLowerCase();if(i(a,o?"ssh.lan.hostname":`the ssh provider's default LAN name for project "${r}"`),Object.entries(e).some(([l,p])=>!!p&&Pr(l)))i(`dashboard.${a}`,"the management dashboard site");for(let[l,p]of Object.entries(e)){if(!p?.domain)continue;if(P(p)==="bucket")continue;if(!pa(p.domain))continue;i(p.domain,`site "${l}"`)}return n}function ma(e,t){if(!t?.length)return;return t.find((r)=>{let n=(r.startsWith(".")?r.slice(1):r).toLowerCase();return e===n||e.endsWith(`.${n}`)})}function fa(e,t){if(!t?.enabled)return;for(let{host:r,source:n}of e){let s=ma(r,t.allowedSuffixes);if(!s)continue;throw Error(`The LAN certificate authority and public on-demand TLS both claim "${r}". LAN source: ${n}. Public source: the on-demand TLS allowed suffix "${s}", which is derived from the site domains. A host is either LAN-only, with a certificate signed by the box's own CA, or public, with one issued by Let's Encrypt, never both. Give the LAN a name no site domain covers (ssh.lan.hostname), or take that domain out of the sites this deploy routes.`)}}function Hn(e){if(!e||e==="/")return;let t=`/${e}`.replace(/\/+/g,"/").replace(/\/+$/,"");if(!t.startsWith("/"))t=`/${t}`;return t===""||t==="/"?void 0:t}function mr(e,t){let n=(t?`${e}${t}`:e).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return n.length>0?n:"rpx"}function ga(e,t){if(!t||t.length===0)return`localhost:${e}`;return t.map((r)=>`${r.privateIp??r.publicIp}:${e}`)}function Nn(e,t,r){let n=(t.wwwRoot??"/var/www").replace(/\/+$/,""),s=t.slug??"app",i=t.proxy.certsDir??Fr,o=t.proxy.loadBalancer,a=[],c=new Set;for(let[m,f]of Object.entries(e)){if(!f||!f.domain)continue;let h=P(f);if(h==="bucket")continue;let _=Hn(f.path),w=mr(f.domain,_),b=ua(f);if(h==="redirect"){a.push({to:f.domain,path:_,redirect:la(f.redirect),id:w,...b?{auth:b}:{}}),c.add(f.domain);continue}if(h==="proxy"){let S=_s(f);if(S.length===0)continue;let T=S.length===1?S[0]:S;a.push({to:f.domain,path:_,from:T,id:w,...b?{auth:b}:{},...Array.isArray(T)&&o?{loadBalancer:o}:{}}),c.add(f.domain);continue}if(h==="server-app"){if(typeof f.port!=="number")continue;let S=ga(f.port,r);a.push({to:f.domain,path:_,from:S,id:w,...b?{auth:b}:{},...Array.isArray(S)&&o?{loadBalancer:o}:{}})}else a.push({to:f.domain,path:_,static:{dir:`${n}/${s}-${m}/current`,spa:f.spa??!1,pathRewriteStyle:f.pathRewriteStyle??"directory"},cleanUrls:f.pathRewriteStyle!=="flat",...b?{auth:b}:{},id:w});c.add(f.domain)}if(t.proxy.autoWww!==!1)for(let m of[...c]){if(!hr(m))continue;let f=`www.${m}`;if(c.has(f))continue;a.push({to:f,redirect:{to:`https://${m}`},id:mr(f)}),c.add(f)}a.sort((m,f)=>{if(m.to!==f.to)return m.to.localeCompare(f.to);return(f.path?.length??0)-(m.path?.length??0)});let l={proxies:a,productionCerts:{certsDir:i,certsDirServerNames:[...c]},https:!0,hostsManagement:!1,cleanup:{hosts:!1,certs:!1}};if(t.proxy.onDemandTls&&c.size>0)l.onDemandTls={enabled:!0,allowedSuffixes:[...c],email:t.proxy.onDemandTlsEmail,certsDir:i,staging:t.proxy.onDemandTlsStaging??!1};if(t.proxy.onDemandTls)l.acmeChallengeWebroot=t.proxy.acmeWebroot??ca;let p=t.proxy.cdn,d=p?.frontedHosts?.length?p.frontedHosts:[...c];if(p?.secret&&d.length>0)l.originGuard={header:p.secretHeader??"X-Origin-Verify",value:p.secret,hosts:d};if(t.lan)if(Sr(t.lan)==="off")l.https=!1;else{let m=da(e,t.lan,s);fa(m,l.onDemandTls);let f=t.lan.ip&&In(t.lan.ip)!==0?[t.lan.ip]:[];l.localCa={dir:An,hosts:m.map((h)=>h.host),...f.length>0?{ips:f}:{},installTrust:!0}}return l}function ye(e,t){return Nn(e,t)}function Fe(e,t,r){return Nn(e,r,t)}function Y(e){return e?.webServer==="rpx"||e?.proxy?.engine==="rpx"}var ot="/etc/rpx",V="/opt/rpx-gateway",fr="/etc/rpx/gateway.ts",Ue="/etc/rpx/gateway",le="rpx-gateway.service",ee="/etc/rpx/sites.d";function ha(e=ee,t=Fr){return`// Generated by ts-cloud — rpx gateway assembler.
16
16
  // Merges every app's fragment in ${e} so independent deploys compose
17
17
  // without clobbering each other. Each deploy writes only its own <slug>.json.
18
18
  import { startProxies } from '@stacksjs/rpx'
@@ -251,7 +251,7 @@ ${h.join(`
251
251
  `)}
252
252
  `}return m+=`
253
253
  echo "ts-cloud bootstrap complete — instance is ready for site deploys"
254
- `,m}var Xn="/aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id";function Yn(e){let t=[{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"}],r=new Set;for(let n of Object.values(e.sites||{}))if(n&&typeof n.port==="number"&&![22,80,443].includes(n.port))r.add(n.port);for(let n of r)t.push({port:n,protocol:"tcp",cidr:"0.0.0.0/0"});return t}function Qn(e){let t=e.infrastructure?.compute??{},r=Re(e),n=t.proxy?.engine==="rpx"?de({proxy:t.proxy,config:ye(e.sites??{},{proxy:t.proxy,slug:e.project.slug}),slug:e.project.slug,bunBin:t.runtime==="node"||t.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0;return te({runtime:r.runtime,runtimeVersion:r.runtimeVersion,systemPackages:t.systemPackages,database:e.infrastructure?.database,phpProvision:r.phpProvision,servicesProvision:r.servicesProvision,rpxProvision:n,baked:t.bakedImage===!0,swapGb:t.swapGb})}function Zn(e){return Buffer.from(e,"utf8").toString("base64")}function es(e){return e.infrastructure?.compute?.image??null}function xt(e,t){return`${e}-${t}-app-sg`}function _r(e,t,r="app"){return[{Key:"Project",Value:e},{Key:"Environment",Value:t},{Key:"Role",Value:r},{Key:"ManagedBy",Value:"ts-cloud"}]}function Ra(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 ts(e,t){let r=xt(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 Ra(n.Tags,t.slug,t.environment);return!!t.vpcId&&n.VpcId===t.vpcId})}function Oa(e){try{let t=rs(Ea(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 Rt{name="aws";usesCloudFormation=!0;region;ec2Client;cfnClient;constructor(e={}){this.region=e.region||"us-east-1",this.ec2Client=e.ec2Client??((t)=>new Q(t)),this.cfnClient=e.cfnClient??((t)=>new v(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 o=this.ec2Client(n),a=await this.findComputeTargets({slug:s,environment:r,role:"app",region:n});if(a.length>0){let O=a[0];return{appInstanceId:O.id,appPublicIp:O.publicIp,appPublicIpv6:O.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}let c=es(t);if(!c){if(c=(await new ze(n).getParameter({Name:Xn})).Parameter?.Value??null,!c)throw Error("Could not resolve the Ubuntu 24.04 AMI from SSM")}let l=await o.describeVpcs(),p=(l.Vpcs||[]).find((O)=>O.IsDefault)||(l.Vpcs||[])[0];if(!p?.VpcId)throw Error("No VPC found to launch the instance into");let d=(await o.describeSubnets({Filters:[{Name:"vpc-id",Values:[p.VpcId]}]})).Subnets||[],m=d.find((O)=>O.MapPublicIpOnLaunch)||d[0],f=m?.SubnetId;if(!m?.MapPublicIpOnLaunch)console.warn("ts-cloud: no public subnet found; the instance may not get a public IP (deploys/SSL need one).");let h=xt(s,r),w=(await o.describeSecurityGroups({Filters:[{Name:"group-name",Values:[h]},{Name:"vpc-id",Values:[p.VpcId]}]})).SecurityGroups?.[0]?.GroupId;if(!w)w=(await o.createSecurityGroup({GroupName:h,Description:`ts-cloud ${s}/${r} app`,VpcId:p.VpcId,TagSpecifications:[{ResourceType:"security-group",Tags:_r(s,r)}]})).GroupId;let b=Yn(t);await o.authorizeSecurityGroupIngress({GroupId:w,IpPermissions:b.map((O)=>({IpProtocol:O.protocol,FromPort:O.port,ToPort:O.port,IpRanges:[{CidrIp:O.cidr}]}))}).catch((O)=>{if(!/InvalidPermission\.Duplicate/.test(O instanceof Error?O.message:""))throw O});let S=Zn(Qn(t)),T=i.server?.instanceType||"t3.small",I=(await o.runInstances({ImageId:c,InstanceType:T,MinCount:1,MaxCount:1,SecurityGroupIds:w?[w]:void 0,SubnetId:f,UserData:S,IamInstanceProfile:i.server?.iamInstanceProfile?{Name:i.server.iamInstanceProfile}:void 0,TagSpecifications:[{ResourceType:"instance",Tags:[{Key:"Name",Value:`${s}-${r}-app`},..._r(s,r)]}]})).Instances?.[0]?.InstanceId;if(!I)throw Error("RunInstances did not return an instance id");let R=await o.waitForInstanceState(I,"running");if(!R)throw Error(`Instance ${I} did not reach 'running' before timeout`);return{appInstanceId:I,appPublicIp:R.PublicIpAddress,appPublicIpv6:ue(R.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),o=[],c=(await this.findComputeTargets({slug:n,environment:r,role:"app",region:s})).map((h)=>h.id),l;if(c.length>0)l=(await i.describeInstances({InstanceIds:c}).catch(()=>({Reservations:[]}))).Reservations?.flatMap((_)=>_.Instances??[]).find((_)=>_.VpcId)?.VpcId;if(c.length>0)await i.terminateInstances(c),o.push(...c.map((h)=>`instance ${h}`)),await Promise.all(c.map((h)=>i.waitForInstanceState(h,"terminated").catch(()=>{return})));let p=xt(n,r),d=[{Name:"group-name",Values:[p]}];if(l)d.push({Name:"vpc-id",Values:[l]});let m=await i.describeSecurityGroups({Filters:d}).catch(()=>({SecurityGroups:[]})),f=ts(m.SecurityGroups??[],{slug:n,environment:r,vpcId:l});if(f?.GroupId)for(let h=0;h<10;h++)try{await i.deleteSecurityGroup(f.GroupId),o.push(`security group ${p}`);break}catch{await new Promise((_)=>setTimeout(_,3000))}return{destroyed:o}}async getComputeOutputs(e){let t=this.resolveRegion(e.config),r=E(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 o=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",region:t}))[0];return{appInstanceId:o?.id,appPublicIp:o?.publicIp,appPublicIpv6:o?.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 g(t).putObject({bucket:n,key:e.remoteKey,body:rs(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 o=e.stackName??`${e.slug}-${e.environment}`,a=Oa(o);if(!a)try{a=(await this.cfnClient(t).getStackOutputs(o)).appInstanceId??null}catch{a=null}if(!a)return[];try{let c=await r.describeInstances({InstanceIds:[a],Filters:[{Name:"instance-state-name",Values:["running","pending"]}]});return this.reservationsToTargets(c.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:ue(n.Ipv6Address),privateIp:n.PrivateIpAddress,status:n.State?.Name})}return t}bashWrap(e){return["bash <<'TS_CLOUD_BASH_EOF'",e.join(`
254
+ `,m}var Xn="/aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id";function Yn(e){let t=[{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"}],r=new Set;for(let n of Object.values(e.sites||{}))if(n&&typeof n.port==="number"&&![22,80,443].includes(n.port))r.add(n.port);for(let n of r)t.push({port:n,protocol:"tcp",cidr:"0.0.0.0/0"});return t}function Qn(e){let t=e.infrastructure?.compute??{},r=Re(e),n=t.proxy?.engine==="rpx"?de({proxy:t.proxy,config:ye(e.sites??{},{proxy:t.proxy,slug:e.project.slug}),slug:e.project.slug,bunBin:t.runtime==="node"||t.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0;return te({runtime:r.runtime,runtimeVersion:r.runtimeVersion,systemPackages:t.systemPackages,database:e.infrastructure?.database,phpProvision:r.phpProvision,servicesProvision:r.servicesProvision,rpxProvision:n,baked:t.bakedImage===!0,swapGb:t.swapGb})}function Zn(e){return Buffer.from(e,"utf8").toString("base64")}function es(e){return e.infrastructure?.compute?.image??null}function xt(e,t){return`${e}-${t}-app-sg`}function _r(e,t,r="app"){return[{Key:"Project",Value:e},{Key:"Environment",Value:t},{Key:"Role",Value:r},{Key:"ManagedBy",Value:"ts-cloud"}]}function Ra(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 ts(e,t){let r=xt(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 Ra(n.Tags,t.slug,t.environment);return!!t.vpcId&&n.VpcId===t.vpcId})}function Oa(e){try{let t=rs(Ea(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 Rt{name="aws";usesCloudFormation=!0;region;ec2Client;cfnClient;constructor(e={}){this.region=e.region||"us-east-1",this.ec2Client=e.ec2Client??((t)=>new Q(t)),this.cfnClient=e.cfnClient??((t)=>new v(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 o=this.ec2Client(n),a=await this.findComputeTargets({slug:s,environment:r,role:"app",region:n});if(a.length>0){let R=a[0];return{appInstanceId:R.id,appPublicIp:R.publicIp,appPublicIpv6:R.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}let c=es(t);if(!c){if(c=(await new ze(n).getParameter({Name:Xn})).Parameter?.Value??null,!c)throw Error("Could not resolve the Ubuntu 24.04 AMI from SSM")}let l=await o.describeVpcs(),p=(l.Vpcs||[]).find((R)=>R.IsDefault)||(l.Vpcs||[])[0];if(!p?.VpcId)throw Error("No VPC found to launch the instance into");let d=(await o.describeSubnets({Filters:[{Name:"vpc-id",Values:[p.VpcId]}]})).Subnets||[],m=d.find((R)=>R.MapPublicIpOnLaunch)||d[0],f=m?.SubnetId;if(!m?.MapPublicIpOnLaunch)console.warn("ts-cloud: no public subnet found; the instance may not get a public IP (deploys/SSL need one).");let h=xt(s,r),w=(await o.describeSecurityGroups({Filters:[{Name:"group-name",Values:[h]},{Name:"vpc-id",Values:[p.VpcId]}]})).SecurityGroups?.[0]?.GroupId;if(!w)w=(await o.createSecurityGroup({GroupName:h,Description:`ts-cloud ${s}/${r} app`,VpcId:p.VpcId,TagSpecifications:[{ResourceType:"security-group",Tags:_r(s,r)}]})).GroupId;let b=Yn(t);await o.authorizeSecurityGroupIngress({GroupId:w,IpPermissions:b.map((R)=>({IpProtocol:R.protocol,FromPort:R.port,ToPort:R.port,IpRanges:[{CidrIp:R.cidr}]}))}).catch((R)=>{if(!/InvalidPermission\.Duplicate/.test(R instanceof Error?R.message:""))throw R});let S=Zn(Qn(t)),T=i.server?.instanceType||"t3.small",I=(await o.runInstances({ImageId:c,InstanceType:T,MinCount:1,MaxCount:1,SecurityGroupIds:w?[w]:void 0,SubnetId:f,UserData:S,IamInstanceProfile:i.server?.iamInstanceProfile?{Name:i.server.iamInstanceProfile}:void 0,TagSpecifications:[{ResourceType:"instance",Tags:[{Key:"Name",Value:`${s}-${r}-app`},..._r(s,r)]}]})).Instances?.[0]?.InstanceId;if(!I)throw Error("RunInstances did not return an instance id");let x=await o.waitForInstanceState(I,"running");if(!x)throw Error(`Instance ${I} did not reach 'running' before timeout`);return{appInstanceId:I,appPublicIp:x.PublicIpAddress,appPublicIpv6:ue(x.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),o=[],c=(await this.findComputeTargets({slug:n,environment:r,role:"app",region:s})).map((h)=>h.id),l;if(c.length>0)l=(await i.describeInstances({InstanceIds:c}).catch(()=>({Reservations:[]}))).Reservations?.flatMap((_)=>_.Instances??[]).find((_)=>_.VpcId)?.VpcId;if(c.length>0)await i.terminateInstances(c),o.push(...c.map((h)=>`instance ${h}`)),await Promise.all(c.map((h)=>i.waitForInstanceState(h,"terminated").catch(()=>{return})));let p=xt(n,r),d=[{Name:"group-name",Values:[p]}];if(l)d.push({Name:"vpc-id",Values:[l]});let m=await i.describeSecurityGroups({Filters:d}).catch(()=>({SecurityGroups:[]})),f=ts(m.SecurityGroups??[],{slug:n,environment:r,vpcId:l});if(f?.GroupId)for(let h=0;h<10;h++)try{await i.deleteSecurityGroup(f.GroupId),o.push(`security group ${p}`);break}catch{await new Promise((_)=>setTimeout(_,3000))}return{destroyed:o}}async getComputeOutputs(e){let t=this.resolveRegion(e.config),r=E(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 o=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",region:t}))[0];return{appInstanceId:o?.id,appPublicIp:o?.publicIp,appPublicIpv6:o?.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 g(t).putObject({bucket:n,key:e.remoteKey,body:rs(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 o=e.stackName??`${e.slug}-${e.environment}`,a=Oa(o);if(!a)try{a=(await this.cfnClient(t).getStackOutputs(o)).appInstanceId??null}catch{a=null}if(!a)return[];try{let c=await r.describeInstances({InstanceIds:[a],Filters:[{Name:"instance-state-name",Values:["running","pending"]}]});return this.reservationsToTargets(c.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:ue(n.Ipv6Address),privateIp:n.PrivateIpAddress,status:n.State?.Name})}return t}bashWrap(e){return["bash <<'TS_CLOUD_BASH_EOF'",e.join(`
255
255
  `),"TS_CLOUD_BASH_EOF"]}async runRemoteDeploy(e){let t=this.region,r=new ze(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(),o=new Set(["Success","Failed","Cancelled","TimedOut"]),a=[];while(Date.now()-i<n){await new Promise((p)=>setTimeout(p,3000));try{if(a=await e.listCommandInvocations({CommandId:t,Details:!0}),a.length>=r&&a.every((d)=>o.has(d.Status||"")))break}catch{}}let c=a.map((p)=>({instanceId:p.InstanceId,status:p.Status||"Unknown",output:p.StandardOutputContent,error:p.StandardErrorContent})),l=c.length>0&&c.every((p)=>p.status==="Success");return{success:l,instanceCount:c.length,perInstance:c,error:l?void 0:xe(c,"One or more SSM command invocations failed")}}}function ns(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 Tr(e,t,r={}){let n=Bun.spawn(["ssh",...ns(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 Ne(e,t,r={}){let n=await Tr(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 $r(e,t={}){let r=t.timeoutMs??180000,n=t.pollIntervalMs??5000,s=Date.now();while(Date.now()-s<r){let i=await Tr(e,"echo ready",t);if(i.code===0&&i.stdout.includes("ready"))return;await new Promise((o)=>setTimeout(o,n))}throw Error(`SSH not ready on ${e} after ${r}ms`)}function at(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(`
256
256
  `)}var Cr=at();import{execFileSync as Za,execSync as Cs}from"node:child_process";import{createHash as ec,randomUUID as Ps}from"node:crypto";import{createReadStream as tc,existsSync as rc,readFileSync as nc}from"node:fs";function Et(e){return Object.entries(e).map(([t,r])=>`${t}=${Da(String(r))}`).join(`
257
257
  `)}function Da(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}var Ia=new Set(["sqlite","sqlite3"]),Aa=new Set([":memory:","memory"]);function La(e){let t=e?.DB_CONNECTION?.trim().toLowerCase();return t!=null&&Ia.has(t)}function Ha(e){let t=e.trim().replace(/^\.\//,"");if(t===""||t.startsWith("/")||t.startsWith("~"))return;if(t.split("/").includes(".."))return;return t.replace(/\/+$/,"")}function xr(e,t=[]){if(!La(e))return{};let r=e?.DB_DATABASE_PATH?.trim()||e?.DB_DATABASE?.trim();if(r&&Aa.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=Ha(r);if(!n)return{};if(t.some((s)=>Ls(s)===n))return{};return{path:n}}function Ot(e,t=[]){let{path:r}=xr(e,t);return r?[r]:[]}var je="/var/ts-cloud/artifacts";var us=Object.freeze({stagingMaxAgeMinutes:60,artifactMaxAgeDays:2,artifactUploadMaxAgeMinutes:60,bunCacheMaxAgeDays:7,journalMaxAgeDays:14,journalMaxSizeMb:512,containerImageMaxAgeHours:168}),ps=Object.freeze({artifactMaxAgeDays:0,bunCacheMaxAgeDays:1,journalMaxAgeDays:3,journalMaxSizeMb:256,containerImageMaxAgeHours:24});function ss(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function Oe(e,t,r=0){if(!Number.isInteger(t)||t<r)throw Error(`hostCleanup: ${e} must be a whole number >= ${r} (got ${t})`)}function is(e,t){for(let[r,n]of Object.entries(t))Oe(`${e}.${r}`,n);Oe(`${e}.stagingMaxAgeMinutes`,t.stagingMaxAgeMinutes,15),Oe(`${e}.artifactUploadMaxAgeMinutes`,t.artifactUploadMaxAgeMinutes,15),Oe(`${e}.journalMaxSizeMb`,t.journalMaxSizeMb,1)}function Na(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(Oe(`${r}.maxAgeDays`,e.maxAgeDays),e.type!==void 0&&e.type!=="file"&&e.type!=="directory")throw Error(`${r}.type must be 'file' or 'directory'`)}function It(e){let t=typeof e==="object"&&e!==null?e:{},r=e!==!1,n={...us,...os(t.retention)};is("hostCleanup.retention",n);let s=null;if(t.pressure!==!1){let a=typeof t.pressure==="object"?t.pressure:{},c=a.lowWaterPercent??50,l=a.highWaterPercent??85;if(Oe("hostCleanup.pressure.lowWaterPercent",c),Oe("hostCleanup.pressure.highWaterPercent",l,1),l>100||c>=l)throw Error(`hostCleanup.pressure: need 0 <= lowWaterPercent < highWaterPercent <= 100 (got ${c} and ${l})`);let p={...ps,...os(a.escalated)},d=Object.fromEntries(Object.keys(n).map((m)=>[m,Math.min(n[m],p[m]??n[m])]));is("hostCleanup.pressure.escalated",d),s={lowWaterPercent:c,highWaterPercent:l,escalated:d}}let i=t.schedule??"daily";if(!/^[\w*:,./~ -]+$/.test(i))throw Error(`hostCleanup.schedule must be a systemd OnCalendar expression (got ${JSON.stringify(i)})`);let o=t.paths??[];return o.forEach(Na),{enabled:r,timer:r&&t.timer!==!1,schedule:i,retention:n,pressure:s,paths:o}}function os(e){return Object.fromEntries(Object.entries(e??{}).filter(([,t])=>t!==void 0))}var ct={stagingMaxAgeMinutes:"TS_CLOUD_HC_STAGING_MIN",artifactMaxAgeDays:"TS_CLOUD_HC_ARTIFACT_DAYS",artifactUploadMaxAgeMinutes:"TS_CLOUD_HC_UPLOAD_MIN",bunCacheMaxAgeDays:"TS_CLOUD_HC_BUN_DAYS",journalMaxAgeDays:"TS_CLOUD_HC_JOURNAL_DAYS",journalMaxSizeMb:"TS_CLOUD_HC_JOURNAL_MB",containerImageMaxAgeHours:"TS_CLOUD_HC_IMAGE_HOURS"};function Rr(e){return Object.keys(ct).map((t)=>`${ct[t]}=${e[t]}`).join(" ")}var Ee=(e)=>`"$${ct[e]}"`;function as(e){return[`find /var/ts-cloud/staging -xdev -maxdepth 1 -type f -mmin +${Ee("stagingMaxAgeMinutes")} -delete 2>/dev/null || true`,`find /tmp -xdev -maxdepth 1 -type f -name "*-release.tar.gz" -mmin +${Ee("stagingMaxAgeMinutes")} -delete 2>/dev/null || true`,`find /var/ts-cloud/artifacts -xdev -maxdepth 1 -type f -name "*.tar.gz" -mtime +${Ee("artifactMaxAgeDays")} -delete 2>/dev/null || true`,`find /var/ts-cloud/artifacts -xdev -maxdepth 1 -type f -name ".*.tmp" -mmin +${Ee("artifactUploadMaxAgeMinutes")} -delete 2>/dev/null || true`,...e.map(Ua),`journalctl --vacuum-time=${Ee("journalMaxAgeDays")}d --vacuum-size=${Ee("journalMaxSizeMb")}M >/dev/null 2>&1 || true`]}function Ua(e){let t=ss(e.path.replace(/\/+$/,"")),r=ss(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 cs(){return[`find /root/.bun/install/cache -xdev -type f -mtime +${Ee("bunCacheMaxAgeDays")} -delete 2>/dev/null || true`,"find /root/.bun/install/cache -xdev -depth -type d -empty -delete 2>/dev/null || true",`if command -v docker >/dev/null 2>&1; then docker image prune --all --force --filter "until=\${${ct.containerImageMaxAgeHours}}h" >/dev/null 2>&1 || true; fi`,`if command -v podman >/dev/null 2>&1; then podman image prune --all --force --filter "until=\${${ct.containerImageMaxAgeHours}}h" >/dev/null 2>&1 || true; fi`,"if command -v apt-get >/dev/null 2>&1; then apt-get clean >/dev/null 2>&1 || true; fi"]}function ls(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 Or(e){let{retention:t,pressure:r,paths:n}=It(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)"',Rr(t),...as(n),...cs(),'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"'];let{lowWaterPercent:o,highWaterPercent:a,escalated:c}=r;return['echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',...ls("TS_CLOUD_HC_BEFORE"),"TS_CLOUD_HC_TIER=normal",Rr(t),`if [ "$TS_CLOUD_HC_BEFORE" -ge 0 ] && [ "$TS_CLOUD_HC_BEFORE" -lt ${o} ]; then`," TS_CLOUD_HC_TIER=light",` echo "[ts-cloud] host cleanup: / at \${TS_CLOUD_HC_BEFORE}% (under ${o}%), skipping cache and image pruning"`,`elif [ "$TS_CLOUD_HC_BEFORE" -ge ${a} ]; then`," TS_CLOUD_HC_TIER=pressure",` ${Rr(c)}`,` echo "[ts-cloud] warning: / at \${TS_CLOUD_HC_BEFORE}% (at or above ${a}%), host cleanup is using shortened retention windows" >&2`,"fi",...as(n),'if [ "$TS_CLOUD_HC_TIER" != light ]; then',...cs().map((l)=>` ${l}`),"fi",'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"',...ls("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\\":${o},\\"highWaterPercent\\":${a}}"`,"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 ${a} ]; then`,` echo "[ts-cloud] warning: / still at \${TS_CLOUD_HC_AFTER}% after host cleanup (high-water ${a}%); 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 ${a}%)" >/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 ${a}% 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 ds(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",...Or(e),"exit 0"]}function Er(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 ms(e){let t=It(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=Er("/usr/local/bin/ts-cloud-host-cleanup.sh",ds(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",...Er("/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"),...Er("/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 Dr(e){let t=ms(e);if(!It(e).enabled)return t;return[...t,'if [ -x /usr/local/bin/ts-cloud-host-cleanup.sh ]; then /usr/local/bin/ts-cloud-host-cleanup.sh < /dev/null || echo "[ts-cloud] warning: host cleanup exited $?" >&2; fi']}var Ma=/\.(?:[cm]?[jt]sx?)$/;function Ar(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="",...o]=s.split(/\s+/);if(i&&!Ma.test(i)){let a=i.startsWith("/")?i:r&&i.startsWith("./")?`${r.replace(/\/+$/,"")}/${i.replace(/^\.\//,"")}`:void 0;if(a)return[a,...o].join(" ")}return`${n} ${s}`}function fs(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.
@@ -259,7 +259,7 @@ echo "ts-cloud bootstrap complete — instance is ready for site deploys"
259
259
  [Service]
260
260
  MemoryAccounting=true
261
261
  MemoryHigh=%sM
262
- ' "$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)"',...Ir()]}function Ir(){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 Fa(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 De={path:"/",intervalSeconds:60,failuresBeforeRestart:3,timeoutSeconds:10,startupGraceSeconds:600,maxBackoffSeconds:3600,backoffBaseSeconds:300};function pt(e,t,r){return typeof e==="number"&&Number.isFinite(e)?Math.max(r,Math.floor(e)):t}function gs(e){let{unitBase:t,unitPattern:r,port:n}=e,s=e.path&&e.path.startsWith("/")?e.path:De.path,i=pt(e.intervalSeconds,De.intervalSeconds,10),o=pt(e.failuresBeforeRestart,De.failuresBeforeRestart,1),a=pt(e.timeoutSeconds,De.timeoutSeconds,1),c=pt(e.startupGraceSeconds,De.startupGraceSeconds,0),l=pt(e.maxBackoffSeconds,De.maxBackoffSeconds,0),p=Math.min(De.backoffBaseSeconds,l),d=`/usr/local/sbin/${t}-liveness`,m=`/run/${t}-liveness`,f=`${t}-liveness`,h=`127.0.0.1:${n}${s}`,w=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 > ${d} <<'TS_CLOUD_LIVENESS_EOF'`,"#!/bin/sh",`# Liveness check for ${t}, written by ts-cloud on every deploy.`,`# Settings: interval=${i}s timeout=${a}s failures=${o} startup-grace=${c}s max-backoff=${l}s`,"set -eu",`TS_CLOUD_STATE=${m}`,'exec 9>"$TS_CLOUD_STATE.lock"',"flock -n 9 || exit 0",w,'[ -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 ${a} "http://${h}" || 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 ${l} ] || 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 ${a}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 ${c} ]; then`,' rm -f "$TS_CLOUD_STATE.fail"',` logger -t ${f} "$TS_CLOUD_UNIT is \${TS_CLOUD_AGE}s old, inside its ${c}s startup grace; not counting this failed check on ${h} ($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 ${o} ]; then`,` logger -t ${f} "check $TS_CLOUD_FAILS of ${o} failed on ${h} ($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=${p}`," TS_CLOUD_I=1",` while [ "$TS_CLOUD_I" -lt "$TS_CLOUD_STREAK" ] && [ "$TS_CLOUD_WAIT" -lt ${l} ]; do TS_CLOUD_WAIT=$((TS_CLOUD_WAIT * 2)); TS_CLOUD_I=$((TS_CLOUD_I + 1)); done`,` [ "$TS_CLOUD_WAIT" -le ${l} ] || TS_CLOUD_WAIT=${l}`," TS_CLOUD_ELAPSED=$((TS_CLOUD_NOW - TS_CLOUD_LAST))",' if [ "$TS_CLOUD_ELAPSED" -lt "$TS_CLOUD_WAIT" ]; then',` logger -t ${f} "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 ${h})"`," exit 0"," fi","fi","TS_CLOUD_STREAK=$((TS_CLOUD_STREAK + 1))",`logger -t ${f} "no HTTP response on ${h} 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 ${d}`,`rm -f ${m}.fail ${m}.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=${d}`,"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 za=20,hs=3,Ba=5,Ka=60;function Lr(e){let{siteName:t,slug:r,artifactFetch:n,releaseId:s,execStart:i,envEntries:o,port:a,keepReleases:c=ui,preStartCommands:l=[],healthCheckPath:p,healthGateSeconds:d=5,liveness:m,memoryHigh:f="auto",memoryMax:h,cpuWeight:_,ioWeight:w,tasksMax:b,stopTimeout:S}=e,T=[..._!=null?[`CPUWeight=${_}`]:[],...w!=null?[`IOWeight=${w}`]:[],...b!=null?[`TasksMax=${b}`]:[],...S?[`TimeoutStopSec=${S}`]:[]],y=e.zeroDowntime??a!=null,I=e.appDir??`/var/www/${t}`,R=Bt(I,s),O=`${r}-${t}`,N=`${O}.service`,ne=mt(r,t,s),G=e.sharedPaths??[],k=dc([".env",...G,...Ot(o,G)]),X=Et(o),M=l.length>0?[`cd ${R.release}`,...l]:[],Z=["set -euo pipefail",...Ms(R),Bs(R),...n,...pi(R,k),...Us(R),`tar xzf ${ne} -C "$TS_CLOUD_STAGED"`,`rm -f ${ne}`,`cat > ${R.shared}/.env <<'TS_CLOUD_ENV_EOF'`,X,"TS_CLOUD_ENV_EOF",`chmod 600 ${R.shared}/.env`,...Fs(R),`find ${R.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' ${R.shared}/.env 2>/dev/null || true`,...To(R,k),...M];if(y&&a!=null){let H=`${O}@${s}.service`,fe=p?p.startsWith("/")?p:`/${p}`:null,ae=`{ echo "[ts-cloud] release ${s} failed its health gate — previous release keeps serving" >&2; journalctl -u ${H} -n 50 --no-pager >&2 || true; systemctl stop ${H} 2>/dev/null || true; exit 1; }`;return[...Z,`cat > /etc/systemd/system/${O}@.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} release %i (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${R.releases}/%i`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...f&&f!=="auto"?[`MemoryHigh=${f}`]:[],...h?[`MemoryMax=${h}`]:[],...T,`EnvironmentFile=${R.releases}/%i/.env`,`Environment=PORT=${a}`,`Environment=STX_IMAGE_CACHE_DIR=${vo(R)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...f==="auto"?fs(`${O}@.service`):Ir(),...Fa(H),`TS_CLOUD_OLD_UNITS=$(systemctl list-units --plain --no-legend --type=service "${O}@*.service" 2>/dev/null | awk '{print $1}' | grep -v "^${H}$" || true)`,`if [ -f /etc/systemd/system/${N} ] && systemctl is-active --quiet ${N}; then echo "[ts-cloud] retiring pre-zero-downtime unit ${N} (one-time restart cutover)"; systemctl stop ${N}; fi`,`systemctl restart ${H}`,`TS_CLOUD_GATE_OK=1; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do sleep 1; systemctl is-active --quiet ${H} || { TS_CLOUD_GATE_OK=0; break; }; done`,`if [ "$TS_CLOUD_GATE_OK" -ne 1 ]; then echo "[ts-cloud] release ${s} could not overlap the previous release (no SO_REUSEPORT?) — retiring old instances 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 ${H}; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do sleep 1; systemctl is-active --quiet ${H} || ${ae}; done; fi`,`if ss -ltnpH "sport = :${a}" >/dev/null 2>&1; then`," TS_CLOUD_BOUND=0",` for TS_CLOUD_I in $(seq 1 ${Ka}); do`,` TS_CLOUD_NEW_PID="$(systemctl show -p MainPID --value ${H} 2>/dev/null || true)"`,` if [ -n "$TS_CLOUD_NEW_PID" ] && [ "$TS_CLOUD_NEW_PID" != "0" ] && ss -ltnpH "sport = :${a}" 2>/dev/null | grep -q "pid=$TS_CLOUD_NEW_PID,"; then TS_CLOUD_BOUND=1; break; fi`,` sleep ${hs}`," done",` if [ "$TS_CLOUD_BOUND" -ne 1 ]; then echo "[ts-cloud] release ${s} never joined ${a} alongside the previous release" >&2; ${ae}; fi`,"else",' echo "[ts-cloud] cannot read listener PIDs on this host — the response gate runs without the bind check" >&2',"fi",...fe?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${za}); do if curl -sf -o /dev/null --max-time ${Ba} "http://127.0.0.1:${a}${fe}"; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${hs}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${ae}`]:[],...tn(R),`systemctl enable ${H} 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 ${Math.max(1,d)}); do if ss -ltnH "sport = :${a}" 2>/dev/null | grep -q .; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done`,`if [ "$TS_CLOUD_LISTENING" -ne 1 ]; then echo "[ts-cloud] nothing is listening on ${a} after retiring the previous release — restarting ${H} on the now-free port" >&2; systemctl restart ${H}; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do if ss -ltnH "sport = :${a}" 2>/dev/null | grep -q .; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done; fi`,`if [ "$TS_CLOUD_LISTENING" -ne 1 ]; then echo "[ts-cloud] ${H} is active but never bound ${a}" >&2; journalctl -u ${H} -n 50 --no-pager >&2 || true; exit 1; fi`,`systemctl list-unit-files --plain --no-legend "${O}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v -e "^${H}$" -e "^${O}@\\.service$" || true; } | while read -r TS_CLOUD_U; do systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done`,`if [ -f /etc/systemd/system/${N} ]; then systemctl disable ${N} 2>/dev/null || true; rm -f /etc/systemd/system/${N}; systemctl daemon-reload; fi`,...rn(R,c),...m===!1?[]:gs({...m,unitBase:O,unitPattern:`${O}@*.service`,port:a,path:m?.path??p})]}return[...Z,`cat > /etc/systemd/system/${N} <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${R.current}`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...f&&f!=="auto"?[`MemoryHigh=${f}`]:[],...h?[`MemoryMax=${h}`]:[],...T,`EnvironmentFile=${R.current}/.env`,...a?[`Environment=PORT=${a}`]:[],`Environment=STX_IMAGE_CACHE_DIR=${vo(R)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...f==="auto"?fs(N):Ir(),`systemctl enable ${N}`,...tn(R),`systemctl restart ${N}`,`systemctl is-active ${N}`,...rn(R,c),...m===!1||!a?[]:gs({...m,unitBase:O,unitPattern:N,port:a,path:m?.path??p})]}function Nr(e){let{siteName:t,artifactFetch:r,releaseId:n,keepReleases:s=ui,preStartCommands:i=[]}=e,o=e.appDir??`/var/www/${t}`,a=Bt(o,n),c=mt(e.slug,t,n),l=i.length>0?[`cd ${a.release}`,...i]:[];return["set -euo pipefail",...Ms(a),Bs(a),...r,...pi(a,[]),...Us(a),`tar xzf ${c} -C "$TS_CLOUD_STAGED"`,...Fs(a),`rm -f ${c}`,...l,...tn(a),...rn(a,s)]}function mt(e,t,r){return`/tmp/${[e,t,r].filter(Boolean).join("-")}-release.tar.gz`}function kr(e,t,r,n){return[`aws s3 cp "s3://${e}/${t}" ${n} --region ${r}`]}function Ur(e,t){return[`mv "${e}" ${t}`]}function We(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function At(e,t,r){return["set -euo pipefail",`chmod 600 ${We(e)}`,`mv -f -- ${We(e)} ${We(t)}`,`cp -- ${We(t)} ${We(r)}`].join(`
262
+ ' "$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)"',...Ir()]}function Ir(){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 Fa(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 De={path:"/",intervalSeconds:60,failuresBeforeRestart:3,timeoutSeconds:10,startupGraceSeconds:600,maxBackoffSeconds:3600,backoffBaseSeconds:300};function pt(e,t,r){return typeof e==="number"&&Number.isFinite(e)?Math.max(r,Math.floor(e)):t}function gs(e){let{unitBase:t,unitPattern:r,port:n}=e,s=e.path&&e.path.startsWith("/")?e.path:De.path,i=pt(e.intervalSeconds,De.intervalSeconds,10),o=pt(e.failuresBeforeRestart,De.failuresBeforeRestart,1),a=pt(e.timeoutSeconds,De.timeoutSeconds,1),c=pt(e.startupGraceSeconds,De.startupGraceSeconds,0),l=pt(e.maxBackoffSeconds,De.maxBackoffSeconds,0),p=Math.min(De.backoffBaseSeconds,l),d=`/usr/local/sbin/${t}-liveness`,m=`/run/${t}-liveness`,f=`${t}-liveness`,h=`127.0.0.1:${n}${s}`,w=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 > ${d} <<'TS_CLOUD_LIVENESS_EOF'`,"#!/bin/sh",`# Liveness check for ${t}, written by ts-cloud on every deploy.`,`# Settings: interval=${i}s timeout=${a}s failures=${o} startup-grace=${c}s max-backoff=${l}s`,"set -eu",`TS_CLOUD_STATE=${m}`,'exec 9>"$TS_CLOUD_STATE.lock"',"flock -n 9 || exit 0",w,'[ -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 ${a} "http://${h}" || 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 ${l} ] || 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 ${a}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 ${c} ]; then`,' rm -f "$TS_CLOUD_STATE.fail"',` logger -t ${f} "$TS_CLOUD_UNIT is \${TS_CLOUD_AGE}s old, inside its ${c}s startup grace; not counting this failed check on ${h} ($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 ${o} ]; then`,` logger -t ${f} "check $TS_CLOUD_FAILS of ${o} failed on ${h} ($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=${p}`," TS_CLOUD_I=1",` while [ "$TS_CLOUD_I" -lt "$TS_CLOUD_STREAK" ] && [ "$TS_CLOUD_WAIT" -lt ${l} ]; do TS_CLOUD_WAIT=$((TS_CLOUD_WAIT * 2)); TS_CLOUD_I=$((TS_CLOUD_I + 1)); done`,` [ "$TS_CLOUD_WAIT" -le ${l} ] || TS_CLOUD_WAIT=${l}`," TS_CLOUD_ELAPSED=$((TS_CLOUD_NOW - TS_CLOUD_LAST))",' if [ "$TS_CLOUD_ELAPSED" -lt "$TS_CLOUD_WAIT" ]; then',` logger -t ${f} "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 ${h})"`," exit 0"," fi","fi","TS_CLOUD_STREAK=$((TS_CLOUD_STREAK + 1))",`logger -t ${f} "no HTTP response on ${h} 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 ${d}`,`rm -f ${m}.fail ${m}.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=${d}`,"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 za=20,hs=3,Ba=5,Ka=60;function Lr(e){let{siteName:t,slug:r,artifactFetch:n,releaseId:s,execStart:i,envEntries:o,port:a,keepReleases:c=ui,preStartCommands:l=[],healthCheckPath:p,healthGateSeconds:d=5,liveness:m,memoryHigh:f="auto",memoryMax:h,cpuWeight:_,ioWeight:w,tasksMax:b,stopTimeout:S}=e,T=[..._!=null?[`CPUWeight=${_}`]:[],...w!=null?[`IOWeight=${w}`]:[],...b!=null?[`TasksMax=${b}`]:[],...S?[`TimeoutStopSec=${S}`]:[]],y=e.zeroDowntime??a!=null,I=e.appDir??`/var/www/${t}`,x=Bt(I,s),R=`${r}-${t}`,N=`${R}.service`,ne=mt(r,t,s),G=e.sharedPaths??[],k=dc([".env",...G,...Ot(o,G)]),X=Et(o),M=l.length>0?[`cd ${x.release}`,...l]:[],Z=["set -euo pipefail",...Ms(x),Bs(x),...n,...pi(x,k),...Us(x),`tar xzf ${ne} -C "$TS_CLOUD_STAGED"`,`rm -f ${ne}`,`cat > ${x.shared}/.env <<'TS_CLOUD_ENV_EOF'`,X,"TS_CLOUD_ENV_EOF",`chmod 600 ${x.shared}/.env`,...Fs(x),`find ${x.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' ${x.shared}/.env 2>/dev/null || true`,...To(x,k),...M];if(y&&a!=null){let H=`${R}@${s}.service`,fe=p?p.startsWith("/")?p:`/${p}`:null,ae=`{ echo "[ts-cloud] release ${s} failed its health gate — previous release keeps serving" >&2; journalctl -u ${H} -n 50 --no-pager >&2 || true; systemctl stop ${H} 2>/dev/null || true; exit 1; }`;return[...Z,`cat > /etc/systemd/system/${R}@.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} release %i (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${x.releases}/%i`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...f&&f!=="auto"?[`MemoryHigh=${f}`]:[],...h?[`MemoryMax=${h}`]:[],...T,`EnvironmentFile=${x.releases}/%i/.env`,`Environment=PORT=${a}`,`Environment=STX_IMAGE_CACHE_DIR=${vo(x)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...f==="auto"?fs(`${R}@.service`):Ir(),...Fa(H),`TS_CLOUD_OLD_UNITS=$(systemctl list-units --plain --no-legend --type=service "${R}@*.service" 2>/dev/null | awk '{print $1}' | grep -v "^${H}$" || true)`,`if [ -f /etc/systemd/system/${N} ] && systemctl is-active --quiet ${N}; then echo "[ts-cloud] retiring pre-zero-downtime unit ${N} (one-time restart cutover)"; systemctl stop ${N}; fi`,`systemctl restart ${H}`,`TS_CLOUD_GATE_OK=1; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do sleep 1; systemctl is-active --quiet ${H} || { TS_CLOUD_GATE_OK=0; break; }; done`,`if [ "$TS_CLOUD_GATE_OK" -ne 1 ]; then echo "[ts-cloud] release ${s} could not overlap the previous release (no SO_REUSEPORT?) — retiring old instances 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 ${H}; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do sleep 1; systemctl is-active --quiet ${H} || ${ae}; done; fi`,`if ss -ltnpH "sport = :${a}" >/dev/null 2>&1; then`," TS_CLOUD_BOUND=0",` for TS_CLOUD_I in $(seq 1 ${Ka}); do`,` TS_CLOUD_NEW_PID="$(systemctl show -p MainPID --value ${H} 2>/dev/null || true)"`,` if [ -n "$TS_CLOUD_NEW_PID" ] && [ "$TS_CLOUD_NEW_PID" != "0" ] && ss -ltnpH "sport = :${a}" 2>/dev/null | grep -q "pid=$TS_CLOUD_NEW_PID,"; then TS_CLOUD_BOUND=1; break; fi`,` sleep ${hs}`," done",` if [ "$TS_CLOUD_BOUND" -ne 1 ]; then echo "[ts-cloud] release ${s} never joined ${a} alongside the previous release" >&2; ${ae}; fi`,"else",' echo "[ts-cloud] cannot read listener PIDs on this host — the response gate runs without the bind check" >&2',"fi",...fe?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${za}); do if curl -sf -o /dev/null --max-time ${Ba} "http://127.0.0.1:${a}${fe}"; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${hs}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${ae}`]:[],...tn(x),`systemctl enable ${H} 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 ${Math.max(1,d)}); do if ss -ltnH "sport = :${a}" 2>/dev/null | grep -q .; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done`,`if [ "$TS_CLOUD_LISTENING" -ne 1 ]; then echo "[ts-cloud] nothing is listening on ${a} after retiring the previous release — restarting ${H} on the now-free port" >&2; systemctl restart ${H}; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do if ss -ltnH "sport = :${a}" 2>/dev/null | grep -q .; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done; fi`,`if [ "$TS_CLOUD_LISTENING" -ne 1 ]; then echo "[ts-cloud] ${H} is active but never bound ${a}" >&2; journalctl -u ${H} -n 50 --no-pager >&2 || true; exit 1; fi`,`systemctl list-unit-files --plain --no-legend "${R}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v -e "^${H}$" -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/${N} ]; then systemctl disable ${N} 2>/dev/null || true; rm -f /etc/systemd/system/${N}; systemctl daemon-reload; fi`,...rn(x,c),...m===!1?[]:gs({...m,unitBase:R,unitPattern:`${R}@*.service`,port:a,path:m?.path??p})]}return[...Z,`cat > /etc/systemd/system/${N} <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${x.current}`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...f&&f!=="auto"?[`MemoryHigh=${f}`]:[],...h?[`MemoryMax=${h}`]:[],...T,`EnvironmentFile=${x.current}/.env`,...a?[`Environment=PORT=${a}`]:[],`Environment=STX_IMAGE_CACHE_DIR=${vo(x)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...f==="auto"?fs(N):Ir(),`systemctl enable ${N}`,...tn(x),`systemctl restart ${N}`,`systemctl is-active ${N}`,...rn(x,c),...m===!1||!a?[]:gs({...m,unitBase:R,unitPattern:N,port:a,path:m?.path??p})]}function Nr(e){let{siteName:t,artifactFetch:r,releaseId:n,keepReleases:s=ui,preStartCommands:i=[]}=e,o=e.appDir??`/var/www/${t}`,a=Bt(o,n),c=mt(e.slug,t,n),l=i.length>0?[`cd ${a.release}`,...i]:[];return["set -euo pipefail",...Ms(a),Bs(a),...r,...pi(a,[]),...Us(a),`tar xzf ${c} -C "$TS_CLOUD_STAGED"`,...Fs(a),`rm -f ${c}`,...l,...tn(a),...rn(a,s)]}function mt(e,t,r){return`/tmp/${[e,t,r].filter(Boolean).join("-")}-release.tar.gz`}function kr(e,t,r,n){return[`aws s3 cp "s3://${e}/${t}" ${n} --region ${r}`]}function Ur(e,t){return[`mv "${e}" ${t}`]}function We(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function At(e,t,r){return["set -euo pipefail",`chmod 600 ${We(e)}`,`mv -f -- ${We(e)} ${We(t)}`,`cp -- ${We(t)} ${We(r)}`].join(`
263
263
  `)}function Lt(e){return`rm -f -- ${We(e)} 2>/dev/null || true`}function ys(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 vs(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 Mr(e){let t=e.infrastructure?.compute??{},r=C(e);return[...yo(t.managedServices??{mysql:!0,redis:!0},{bindPrivate:!0}),...bt(r,t.managedServices??{mysql:!0}),...Se(!0),...ve(!0),...Be(t.sshKeys),...ke(e.notifications),...t.backups?.enabled?[...So({database:r,backups:t.backups})]:[]]}import{homedir as ja}from"node:os";import{join as Wa}from"node:path";var Ht={location:"fsn1",image:"ubuntu-24.04",sshUser:"root",sshPrivateKeyPath:"~/.ssh/id_ed25519"};function jr(e){return e.startsWith("~/")?Wa(ja(),e.slice(2)):e}function Ge(...e){for(let t of e){let r=process.env[t]?.trim();if(r)return r}return}function Ve(...e){for(let t of e){let r=t?.trim();if(r)return r}return}function ft(e,t){return Ve(e,t?.hetzner?.apiToken,Ge("HCLOUD_TOKEN","HETZNER_API_TOKEN"))}function Br(e,t){return Ve(t,e?.hetzner?.location,Ge("HCLOUD_LOCATION","HETZNER_LOCATION"))??Ht.location}function gt(e,t){let r=e?.infrastructure?.compute;return Ve(t,r?.image,e?.hetzner?.image,Ge("HCLOUD_IMAGE","HETZNER_IMAGE"))??Ht.image}function Ga(e,t){return Ve(t,e?.hetzner?.sshUser,Ge("HCLOUD_SSH_USER","HETZNER_SSH_USER"))??Ht.sshUser}function bs(e,t){return jr(Ve(t,e?.hetzner?.sshPrivateKeyPath,Ge("HCLOUD_SSH_KEY","HETZNER_SSH_KEY"))??Ht.sshPrivateKeyPath)}function Va(e,t,r){let n=Ve(t,e?.hetzner?.sshPublicKeyPath,Ge("HCLOUD_SSH_PUBLIC_KEY","HETZNER_SSH_PUBLIC_KEY"));if(n)return jr(n);return`${r??bs(e)}.pub`}function or(e,t={}){let r=bs(e,t.sshPrivateKeyPath);return{apiToken:ft(t.apiToken,e),location:Br(e,t.location),image:gt(e,t.image),sshUser:Ga(e,t.sshUser),sshPrivateKeyPath:r,sshPublicKeyPath:Va(e,t.sshPublicKeyPath,r)}}var qa="https://api.hetzner.cloud/v1";class Nt 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 kt extends Error{action;constructor(e,t){super(e);this.action=t;this.name="HetznerActionError"}}class qe{name="hetzner";apiToken;baseUrl;fetchImpl;constructor(e){this.apiToken=e.apiToken,this.baseUrl=e.baseUrl??qa,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 o=s.trim().slice(0,200)||n.statusText||"Hetzner API error";throw Error(`Hetzner API ${e} ${t} (${n.status}): ${o}`)}throw Error(`Hetzner API ${e} ${t}: unexpected non-JSON response`)}if(!n.ok){let o=i.error?.message||n.statusText||"Hetzner API error",a=i.error?.code?` [${i.error.code}]`:"";throw new Nt(`Hetzner API ${e} ${t} (${n.status})${a}: ${o}`,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 o=i.meta?.pagination?.next_page;if(!o)return r;n=o}}async listServers(){return this.requestAll("/servers","servers")}async getServer(e){return(await this.request("GET",`/servers/${e}`)).server}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});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: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((a)=>setTimeout(a,s))}let o=await this.powerOffServer(e);await this.waitForAction(o.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 kt(i.error?.message||"Hetzner action failed",i);await new Promise((o)=>setTimeout(o,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((o)=>setTimeout(o,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 o=await this.getServer(e);if(o.status===t)return o;await new Promise((a)=>setTimeout(a,n))}throw Error(`Timed out waiting for server ${e} to reach ${t} state`)}}function sr(e,t){let r=ft(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 ht(e){let[t,r]=e.trim().split(/\s+/);return r?`${t} ${r}`:t}function ws(e){if(!e)return"";return e.endsWith(`
264
264
  `)?e:`${e}
265
265
  `}function me(e,t={}){let r=t.scriptPath??"/var/lib/cloud/ts-cloud-bootstrap.sh",n=t.permissions??"0755",s=e.split(`
@@ -274,7 +274,7 @@ ${s}
274
274
  runcmd:
275
275
  - [ bash, ${r} ]
276
276
  ${ws(t.after)}`}function Vr(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 Kr={micro:"cpx11",small:"cx23",medium:"cx33",large:"cx43",xlarge:"cx53","2xlarge":"ccx33"};function lt(e){if(!e)return Kr.micro;if(e in Kr)return Kr[e];return e}var j="ts-cloud";function W(e,t,r="app"){return{[`${j}/project`]:e,[`${j}/environment`]:t,[`${j}/role`]:r,[`${j}/managed-by`]:"ts-cloud"}}function re(e,t,r,n="app"){return Gr(e,t,r)&&e[`${j}/role`]===n}function Gr(e,t,r){if(!e)return!1;return e[`${j}/project`]===t&&e[`${j}/environment`]===r}import{mkdir as Xa,readFile as Ya,rename as Ja,writeFile as Qa}from"node:fs/promises";import{join as $s}from"node:path";var Xr="storage/cloud/state";function we(e=process.cwd()){return Gs()?A(e,"state"):$s(e,Xr)}function Xe(e,t=process.cwd()){return $s(we(t),`${e}.json`)}async function Ie(e,t=process.cwd()){try{let r=await Ya(Xe(e,t),"utf8");return JSON.parse(r)}catch{return null}}async function Ye(e,t,r=process.cwd()){let n=Xe(e,r);await Xa(we(r),{recursive:!0});let s=`${n}.${process.pid}.tmp`;await Qa(s,`${JSON.stringify(t,null,2)}
277
- `,"utf8"),await Ja(s,n)}async function pe(e){return Ie(e)}async function dt(e,t){await Ye(e,t)}var Yr=268435456;function yt(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function sc(e){let t=ec("sha256");for await(let r of tc(e))t.update(r);return t.digest("hex")}class _e{name="hetzner";usesCloudFormation=!1;client;sshPrivateKeyPath;sshPublicKeyPath;sshUser;location;stateOnly;waitForBoot;bootWait;constructor(e={}){let t=ft(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 qe({apiToken:t??""});let r=or(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=E(t,r),o=`${n}-${r}-app`,a=s.runtime==="php"||!!s.php,c=ys(s);if(c.dedicatedServices||c.appServers>1)return a?this.provisionFleet(e,c):this.provisionBunFleet(e,c);let l=W(n,r,"app"),p=t.sites||{},d=Y(s)?[]:this.collectUpstreamPorts(p),m=`${n}-${r}-app-fw`,{firewall:f}=await this.ensureFirewall(m,l,Vr({allowSsh:s.allowSsh!==!1,sitePorts:d,allowedPorts:[...s.firewall?.allowedPorts??[],...qn(t.infrastructure?.sftp)]})),h=await this.ensureSshKey(n,r,l),_=await pe(i);if(_?.serverId){let M=await this.tryGetServer(_.serverId);if(M&&M.status!=="off")return this.outputsFromState(_,M)}let w=await this.findExistingServer(n,r,o);if(w&&w.status!=="off"){let M={provider:"hetzner",stackName:i,serverId:w.id,serverName:w.name,publicIp:w.public_net.ipv4?.ip,publicIpv6:ue(w.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await dt(i,M),this.outputsFromState(M,w)}let b=s.proxy?.engine==="rpx"?de({proxy:s.proxy,config:ye(p,{proxy:s.proxy,slug:t.project.slug}),slug:t.project.slug,bunBin:s.runtime==="node"||s.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,S=Re(t,{environment:r}),T=s.bakedImage===!0,y=te({runtime:S.runtime,runtimeVersion:S.runtimeVersion,systemPackages:s.systemPackages,database:t.infrastructure?.database,phpProvision:S.phpProvision,servicesProvision:S.servicesProvision,rpxProvision:b,baked:T,swapGb:s.swapGb}),I=me(y),R=lt(s.size),O=gt(t),{server:N,action:ne}=await this.client.createServer({name:o,serverType:R,image:O,location:t.hetzner?.location||this.location,userData:I,labels:l,sshKeys:h?[h]:void 0,firewalls:[{firewall:f.id}]});await this.client.waitForAction(ne.id);let G=await this.client.waitForServerRunning(N.id),k={provider:"hetzner",stackName:i,serverId:G.id,serverName:G.name,firewallId:f.id,publicIp:G.public_net.ipv4?.ip,publicIpv6:ue(G.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};await dt(i,k);let X=G.public_net.ipv4?.ip;if(X&&this.waitForBoot)await this.waitForSshReady(X),await this.waitForCloudInit(X);return this.outputsFromState(k,G)}async provisionFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,i=r.infrastructure.compute,o=E(r,n),a=lt(i.size),c=gt(r),l=r.hetzner?.location||this.location,p=i.bakedImage===!0,d=await pe(o);if(d?.loadBalancerId){let z=(await this.client.listLoadBalancers().catch(()=>[])).find((D)=>D.id===d.loadBalancerId);if(z)return{appPublicIp:z.public_net?.ipv4?.ip,loadBalancerIp:z.public_net?.ipv4?.ip,servicesPrivateIp:d.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}let m=await this.ensureSshKey(s,n,W(s,n,"app")),f=`${s}-${n}-net`,_=(await this.client.listNetworks().catch(()=>[])).find((L)=>L.name===f)??await this.client.createNetwork({name:f,labels:W(s,n,"app")}),{firewall:w}=await this.ensureFirewall(`${s}-${n}-app-fw`,W(s,n,"app"),Vr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),{firewall:b}=await this.ensureFirewall(`${s}-${n}-services-fw`,W(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:[_.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[_.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[_.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[_.ip_range]}]),S=Mr(r),T=me(te({runtime:"php",servicesProvision:S,baked:p,swapGb:i.swapGb})),y=await this.client.listServers().catch(()=>[]),I=[],R=y.find((L)=>re(L.labels,s,n,"services"));if(!R){let{server:L,action:z}=await this.client.createServer({name:`${s}-${n}-services`,serverType:lt(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:c,location:l,userData:T,labels:W(s,n,"services"),sshKeys:m?[m]:void 0,firewalls:[{firewall:b.id}],networks:[_.id]});await this.client.waitForAction(z.id),R=await this.client.waitForServerRunning(L.id),I.push(L.id)}let O=R.id,N=R.private_net?.[0]?.ip??(await this.client.getServer(O)).private_net?.[0]?.ip,ne=[...Se(!0),...ve(!0),...Be(i.sshKeys),...ke(r.notifications)],G=$t({versions:i.php?.versions,default:i.php?.default,extensions:i.php?.extensions,installNginx:!Y(i),optimizeForProduction:i.php?.optimizeForProduction,ini:i.php?.ini}),k=me(te({runtime:"php",phpProvision:G,servicesProvision:ne,baked:p,swapGb:i.swapGb})),X=y.filter((L)=>re(L.labels,s,n,"app")),M=X.map((L)=>L.id);if(X.length>t.appServers)for(let L of X.slice(t.appServers))await this.client.deleteServer(L.id).catch(()=>{}),M.splice(M.indexOf(L.id),1);for(let L=X.length;L<t.appServers;L++){let{server:z,action:D}=await this.client.createServer({name:`${s}-${n}-app-${L+1}`,serverType:a,image:c,location:l,userData:k,labels:W(s,n,"app"),sshKeys:m?[m]:void 0,firewalls:[{firewall:w.id}],networks:[_.id]});await this.client.waitForAction(D.id),M.push(z.id),I.push(z.id)}if(this.waitForBoot&&I.length>0)await Promise.all(I.map(async(L)=>{let D=(await this.client.waitForServerRunning(L)).public_net.ipv4?.ip;if(D)await this.waitForSshReady(D),await this.waitForCloudInit(D)}));let Z=`${s}-${n}-lb`,H,fe;if(t.loadBalancer){let z=(await this.client.listLoadBalancers().catch(()=>[])).find((D)=>D.name===Z)??await this.client.createLoadBalancer({name:Z,location:l,network:_.id,labels:W(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}]});fe=z.id,H=z.public_net?.ipv4?.ip}let ae=H??(await this.client.getServer(M[0]).catch(()=>{return}))?.public_net.ipv4?.ip,se={provider:"hetzner",stackName:o,networkId:_.id,loadBalancerId:fe,servicesServerId:O,servicesPrivateIp:N,publicIp:ae,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await dt(o,se),{appPublicIp:ae,loadBalancerIp:H,servicesPrivateIp:N,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async provisionBunFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,i=r.infrastructure.compute,o=E(r,n),a=lt(i.size),c=gt(r),l=r.hetzner?.location||this.location,p=i.bakedImage===!0,d=r.sites||{},m=await pe(o);if(m?.lbServerId){let D=await this.tryGetServer(m.lbServerId);if(D&&D.status!=="off"){let B=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"},K=await this.findComputeTargets({slug:s,environment:n,role:"app",stackName:o});return this.refreshLbRoutes(D,d,K.map((ce)=>({privateIp:ce.privateIp,publicIp:ce.publicIp})),B,s),{appPublicIp:D.public_net.ipv4?.ip??m.publicIp,loadBalancerIp:D.public_net.ipv4?.ip??m.publicIp,servicesPrivateIp:m.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}}let f=await this.ensureSshKey(s,n,W(s,n,"app")),h=`${s}-${n}-net`,w=(await this.client.listNetworks().catch(()=>[])).find((D)=>D.name===h)??await this.client.createNetwork({name:h,labels:W(s,n,"app")}),b=this.collectUpstreamPorts(d),{firewall:S}=await this.ensureFirewall(`${s}-${n}-app-fw`,W(s,n,"app"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},...b.map((D)=>({direction:"in",protocol:"tcp",port:String(D),source_ips:[w.ip_range],description:`ts-cloud port ${D} (private, LB-only)`}))]),{firewall:T}=await this.ensureFirewall(`${s}-${n}-lb-fw`,W(s,n,"lb"),Vr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),y=await this.client.listServers().catch(()=>[]),I=[],R,O,N=!!i.servicesServer||!!i.managedServices,ne=t.dedicatedServices&&N;if(ne){let{firewall:D}=await this.ensureFirewall(`${s}-${n}-services-fw`,W(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:[w.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[w.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[w.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[w.ip_range]}]),B=Mr(r),K=me(te({runtime:"bun",servicesProvision:B,baked:p,swapGb:i.swapGb})),ce=y.find((he)=>re(he.labels,s,n,"services"));if(!ce){let{server:he,action:rt}=await this.client.createServer({name:`${s}-${n}-services`,serverType:lt(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:c,location:l,userData:K,labels:W(s,n,"services"),sshKeys:f?[f]:void 0,firewalls:[{firewall:D.id}],networks:[w.id]});await this.client.waitForAction(rt.id),ce=await this.client.waitForServerRunning(he.id),I.push(he.id)}R=ce.id,O=ce.private_net?.[0]?.ip??(await this.client.getServer(R)).private_net?.[0]?.ip}let G=ne?{...i,managedServices:void 0,backups:void 0}:i,k=Re({...r,infrastructure:{...r.infrastructure,compute:G}},{environment:n}),X=me(te({runtime:k.runtime,runtimeVersion:k.runtimeVersion,systemPackages:i.systemPackages,database:r.infrastructure?.database,servicesProvision:k.servicesProvision,baked:p,swapGb:i.swapGb})),M=y.filter((D)=>re(D.labels,s,n,"app")),Z=M.map((D)=>D.id);if(M.length>t.appServers)for(let D of M.slice(t.appServers))await this.client.deleteServer(D.id).catch(()=>{}),Z.splice(Z.indexOf(D.id),1);for(let D=M.length;D<t.appServers;D++){let{server:B,action:K}=await this.client.createServer({name:`${s}-${n}-app-${D+1}`,serverType:a,image:c,location:l,userData:X,labels:W(s,n,"app"),sshKeys:f?[f]:void 0,firewalls:[{firewall:S.id}],networks:[w.id]});await this.client.waitForAction(K.id),Z.push(B.id),I.push(B.id)}if(this.waitForBoot&&I.length>0)await Promise.all(I.map(async(D)=>{let K=(await this.client.waitForServerRunning(D)).public_net.ipv4?.ip;if(K)await this.waitForSshReady(K),await this.waitForCloudInit(K)}));let H=[];for(let D of Z){let B=y.find((K)=>K.id===D);if(!B||!B.private_net?.[0]?.ip)B=await this.client.getServer(D).catch(()=>B);H.push({privateIp:B?.private_net?.[0]?.ip,publicIp:B?.public_net.ipv4?.ip})}let fe=`${s}-${n}-lb`,ae,se;if(t.loadBalancer){let D=y.find((K)=>re(K.labels,s,n,"lb")),B=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"};if(!D){let K=de({proxy:B,config:Fe(d,H,{proxy:B,slug:s}),slug:s,bunBin:k.runtime==="node"||k.runtime==="deno"?void 0:"/usr/local/bin/bun"}),ce=me(te({runtime:"bun",rpxProvision:K,baked:!1})),he=typeof i.loadBalancer==="object"?i.loadBalancer.size:void 0,{server:rt,action:Zt}=await this.client.createServer({name:fe,serverType:lt(he??"micro"),image:c,location:l,userData:ce,labels:W(s,n,"lb"),sshKeys:f?[f]:void 0,firewalls:[{firewall:T.id}],networks:[w.id]});if(await this.client.waitForAction(Zt.id),D=await this.client.waitForServerRunning(rt.id),this.waitForBoot){let nt=D.public_net.ipv4?.ip;if(nt)await this.waitForSshReady(nt),await this.waitForCloudInit(nt)}}else this.refreshLbRoutes(D,d,H,B,s);ae=D.id,se=D.public_net.ipv4?.ip}let L=se??(await this.client.getServer(Z[0]).catch(()=>{return}))?.public_net.ipv4?.ip,z={provider:"hetzner",stackName:o,networkId:w.id,lbServerId:ae,appServerIds:Z,servicesServerId:R,servicesPrivateIp:O,publicIp:L,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await dt(o,z),{appPublicIp:L,loadBalancerIp:se,servicesPrivateIp:O,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async destroyCompute(e){let{config:t,environment:r}=e,n=t.project.slug,s=E(t,r),i=await pe(s),o=[],a=`${n}-${r}-lb`,l=(await this.client.listLoadBalancers().catch(()=>[])).find((S)=>S.name===a);if(l)try{await this.client.deleteLoadBalancer(l.id),o.push(`load balancer ${a}`)}catch{}let p=await this.client.listServers().catch(()=>[]),d=new Set;for(let S of p)if(re(S.labels,n,r,"app")||re(S.labels,n,r,"services")||re(S.labels,n,r,"lb"))d.add(S.id);if(i?.serverId)d.add(i.serverId);if(i?.servicesServerId)d.add(i.servicesServerId);if(i?.lbServerId)d.add(i.lbServerId);for(let S of i?.appServerIds??[])d.add(S);for(let S of d)try{await this.client.deleteServer(S),o.push(`server ${S}`)}catch{}let m=await this.client.listFirewalls().catch(()=>[]);for(let S of[`${n}-${r}-app-fw`,`${n}-${r}-services-fw`,`${n}-${r}-lb-fw`]){let T=m.find((y)=>y.name===S);if(!T)continue;for(let y=0;y<12;y++)try{await this.client.deleteFirewall(T.id),o.push(`firewall ${S}`);break}catch{await this.sleep(3000)}}let f=`${n}-${r}-net`,_=(await this.client.listNetworks().catch(()=>[])).find((S)=>S.name===f);if(_)for(let S=0;S<12;S++)try{await this.client.deleteNetwork(_.id),o.push(`network ${f}`);break}catch{await this.sleep(3000)}let b=(await this.client.listSshKeys().catch(()=>[])).filter((S)=>Gr(S.labels,n,r));for(let S of b)try{await this.client.deleteSshKey(S.id),o.push(`ssh key ${S.name}`)}catch{}return await dt(s,{provider:"hetzner",stackName:s}).catch(()=>{}),{destroyed:o}}async getComputeOutputs(e){let t=E(e.config,e.environment),r=await pe(t);if(r?.serverId){let i=await this.tryGetServer(r.serverId);if(i)return this.outputsFromState(r,i)}if(r?.lbServerId){let o=(await this.tryGetServer(r.lbServerId))?.public_net.ipv4?.ip??r.publicIp;return{...this.outputsFromState(r),appPublicIp:o,loadBalancerIp:o}}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:E(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:E(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,"-")}-${Ps()}.tar.gz`}`,i=await sc(e.localPath),o=je,a=`${o}/${i}.tar.gz`;for(let c of t){if(!c.publicIp)throw Error(`Target ${c.id} has no public IP for SCP upload`);let l=["set -euo pipefail",`mkdir -p ${yt(o)} /var/ts-cloud/staging`,`test -s ${yt(a)}`,`cp -- ${yt(a)} ${yt(s)}`].join(`
277
+ `,"utf8"),await Ja(s,n)}async function pe(e){return Ie(e)}async function dt(e,t){await Ye(e,t)}var Yr=268435456;function yt(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function sc(e){let t=ec("sha256");for await(let r of tc(e))t.update(r);return t.digest("hex")}class _e{name="hetzner";usesCloudFormation=!1;client;sshPrivateKeyPath;sshPublicKeyPath;sshUser;location;stateOnly;waitForBoot;bootWait;constructor(e={}){let t=ft(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 qe({apiToken:t??""});let r=or(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=E(t,r),o=`${n}-${r}-app`,a=s.runtime==="php"||!!s.php,c=ys(s);if(c.dedicatedServices||c.appServers>1)return a?this.provisionFleet(e,c):this.provisionBunFleet(e,c);let l=W(n,r,"app"),p=t.sites||{},d=Y(s)?[]:this.collectUpstreamPorts(p),m=`${n}-${r}-app-fw`,{firewall:f}=await this.ensureFirewall(m,l,Vr({allowSsh:s.allowSsh!==!1,sitePorts:d,allowedPorts:[...s.firewall?.allowedPorts??[],...qn(t.infrastructure?.sftp)]})),h=await this.ensureSshKey(n,r,l),_=await pe(i);if(_?.serverId){let M=await this.tryGetServer(_.serverId);if(M&&M.status!=="off")return this.outputsFromState(_,M)}let w=await this.findExistingServer(n,r,o);if(w&&w.status!=="off"){let M={provider:"hetzner",stackName:i,serverId:w.id,serverName:w.name,publicIp:w.public_net.ipv4?.ip,publicIpv6:ue(w.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await dt(i,M),this.outputsFromState(M,w)}let b=s.proxy?.engine==="rpx"?de({proxy:s.proxy,config:ye(p,{proxy:s.proxy,slug:t.project.slug}),slug:t.project.slug,bunBin:s.runtime==="node"||s.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,S=Re(t,{environment:r}),T=s.bakedImage===!0,y=te({runtime:S.runtime,runtimeVersion:S.runtimeVersion,systemPackages:s.systemPackages,database:t.infrastructure?.database,phpProvision:S.phpProvision,servicesProvision:S.servicesProvision,rpxProvision:b,baked:T,swapGb:s.swapGb}),I=me(y),x=lt(s.size),R=gt(t),{server:N,action:ne}=await this.client.createServer({name:o,serverType:x,image:R,location:t.hetzner?.location||this.location,userData:I,labels:l,sshKeys:h?[h]:void 0,firewalls:[{firewall:f.id}]});await this.client.waitForAction(ne.id);let G=await this.client.waitForServerRunning(N.id),k={provider:"hetzner",stackName:i,serverId:G.id,serverName:G.name,firewallId:f.id,publicIp:G.public_net.ipv4?.ip,publicIpv6:ue(G.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};await dt(i,k);let X=G.public_net.ipv4?.ip;if(X&&this.waitForBoot)await this.waitForSshReady(X),await this.waitForCloudInit(X);return this.outputsFromState(k,G)}async provisionFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,i=r.infrastructure.compute,o=E(r,n),a=lt(i.size),c=gt(r),l=r.hetzner?.location||this.location,p=i.bakedImage===!0,d=await pe(o);if(d?.loadBalancerId){let z=(await this.client.listLoadBalancers().catch(()=>[])).find((D)=>D.id===d.loadBalancerId);if(z)return{appPublicIp:z.public_net?.ipv4?.ip,loadBalancerIp:z.public_net?.ipv4?.ip,servicesPrivateIp:d.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}let m=await this.ensureSshKey(s,n,W(s,n,"app")),f=`${s}-${n}-net`,_=(await this.client.listNetworks().catch(()=>[])).find((L)=>L.name===f)??await this.client.createNetwork({name:f,labels:W(s,n,"app")}),{firewall:w}=await this.ensureFirewall(`${s}-${n}-app-fw`,W(s,n,"app"),Vr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),{firewall:b}=await this.ensureFirewall(`${s}-${n}-services-fw`,W(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:[_.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[_.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[_.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[_.ip_range]}]),S=Mr(r),T=me(te({runtime:"php",servicesProvision:S,baked:p,swapGb:i.swapGb})),y=await this.client.listServers().catch(()=>[]),I=[],x=y.find((L)=>re(L.labels,s,n,"services"));if(!x){let{server:L,action:z}=await this.client.createServer({name:`${s}-${n}-services`,serverType:lt(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:c,location:l,userData:T,labels:W(s,n,"services"),sshKeys:m?[m]:void 0,firewalls:[{firewall:b.id}],networks:[_.id]});await this.client.waitForAction(z.id),x=await this.client.waitForServerRunning(L.id),I.push(L.id)}let R=x.id,N=x.private_net?.[0]?.ip??(await this.client.getServer(R)).private_net?.[0]?.ip,ne=[...Se(!0),...ve(!0),...Be(i.sshKeys),...ke(r.notifications)],G=$t({versions:i.php?.versions,default:i.php?.default,extensions:i.php?.extensions,installNginx:!Y(i),optimizeForProduction:i.php?.optimizeForProduction,ini:i.php?.ini}),k=me(te({runtime:"php",phpProvision:G,servicesProvision:ne,baked:p,swapGb:i.swapGb})),X=y.filter((L)=>re(L.labels,s,n,"app")),M=X.map((L)=>L.id);if(X.length>t.appServers)for(let L of X.slice(t.appServers))await this.client.deleteServer(L.id).catch(()=>{}),M.splice(M.indexOf(L.id),1);for(let L=X.length;L<t.appServers;L++){let{server:z,action:D}=await this.client.createServer({name:`${s}-${n}-app-${L+1}`,serverType:a,image:c,location:l,userData:k,labels:W(s,n,"app"),sshKeys:m?[m]:void 0,firewalls:[{firewall:w.id}],networks:[_.id]});await this.client.waitForAction(D.id),M.push(z.id),I.push(z.id)}if(this.waitForBoot&&I.length>0)await Promise.all(I.map(async(L)=>{let D=(await this.client.waitForServerRunning(L)).public_net.ipv4?.ip;if(D)await this.waitForSshReady(D),await this.waitForCloudInit(D)}));let Z=`${s}-${n}-lb`,H,fe;if(t.loadBalancer){let z=(await this.client.listLoadBalancers().catch(()=>[])).find((D)=>D.name===Z)??await this.client.createLoadBalancer({name:Z,location:l,network:_.id,labels:W(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}]});fe=z.id,H=z.public_net?.ipv4?.ip}let ae=H??(await this.client.getServer(M[0]).catch(()=>{return}))?.public_net.ipv4?.ip,se={provider:"hetzner",stackName:o,networkId:_.id,loadBalancerId:fe,servicesServerId:R,servicesPrivateIp:N,publicIp:ae,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await dt(o,se),{appPublicIp:ae,loadBalancerIp:H,servicesPrivateIp:N,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async provisionBunFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,i=r.infrastructure.compute,o=E(r,n),a=lt(i.size),c=gt(r),l=r.hetzner?.location||this.location,p=i.bakedImage===!0,d=r.sites||{},m=await pe(o);if(m?.lbServerId){let D=await this.tryGetServer(m.lbServerId);if(D&&D.status!=="off"){let B=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"},K=await this.findComputeTargets({slug:s,environment:n,role:"app",stackName:o});return this.refreshLbRoutes(D,d,K.map((ce)=>({privateIp:ce.privateIp,publicIp:ce.publicIp})),B,s),{appPublicIp:D.public_net.ipv4?.ip??m.publicIp,loadBalancerIp:D.public_net.ipv4?.ip??m.publicIp,servicesPrivateIp:m.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}}let f=await this.ensureSshKey(s,n,W(s,n,"app")),h=`${s}-${n}-net`,w=(await this.client.listNetworks().catch(()=>[])).find((D)=>D.name===h)??await this.client.createNetwork({name:h,labels:W(s,n,"app")}),b=this.collectUpstreamPorts(d),{firewall:S}=await this.ensureFirewall(`${s}-${n}-app-fw`,W(s,n,"app"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},...b.map((D)=>({direction:"in",protocol:"tcp",port:String(D),source_ips:[w.ip_range],description:`ts-cloud port ${D} (private, LB-only)`}))]),{firewall:T}=await this.ensureFirewall(`${s}-${n}-lb-fw`,W(s,n,"lb"),Vr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),y=await this.client.listServers().catch(()=>[]),I=[],x,R,N=!!i.servicesServer||!!i.managedServices,ne=t.dedicatedServices&&N;if(ne){let{firewall:D}=await this.ensureFirewall(`${s}-${n}-services-fw`,W(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:[w.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[w.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[w.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[w.ip_range]}]),B=Mr(r),K=me(te({runtime:"bun",servicesProvision:B,baked:p,swapGb:i.swapGb})),ce=y.find((he)=>re(he.labels,s,n,"services"));if(!ce){let{server:he,action:rt}=await this.client.createServer({name:`${s}-${n}-services`,serverType:lt(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:c,location:l,userData:K,labels:W(s,n,"services"),sshKeys:f?[f]:void 0,firewalls:[{firewall:D.id}],networks:[w.id]});await this.client.waitForAction(rt.id),ce=await this.client.waitForServerRunning(he.id),I.push(he.id)}x=ce.id,R=ce.private_net?.[0]?.ip??(await this.client.getServer(x)).private_net?.[0]?.ip}let G=ne?{...i,managedServices:void 0,backups:void 0}:i,k=Re({...r,infrastructure:{...r.infrastructure,compute:G}},{environment:n}),X=me(te({runtime:k.runtime,runtimeVersion:k.runtimeVersion,systemPackages:i.systemPackages,database:r.infrastructure?.database,servicesProvision:k.servicesProvision,baked:p,swapGb:i.swapGb})),M=y.filter((D)=>re(D.labels,s,n,"app")),Z=M.map((D)=>D.id);if(M.length>t.appServers)for(let D of M.slice(t.appServers))await this.client.deleteServer(D.id).catch(()=>{}),Z.splice(Z.indexOf(D.id),1);for(let D=M.length;D<t.appServers;D++){let{server:B,action:K}=await this.client.createServer({name:`${s}-${n}-app-${D+1}`,serverType:a,image:c,location:l,userData:X,labels:W(s,n,"app"),sshKeys:f?[f]:void 0,firewalls:[{firewall:S.id}],networks:[w.id]});await this.client.waitForAction(K.id),Z.push(B.id),I.push(B.id)}if(this.waitForBoot&&I.length>0)await Promise.all(I.map(async(D)=>{let K=(await this.client.waitForServerRunning(D)).public_net.ipv4?.ip;if(K)await this.waitForSshReady(K),await this.waitForCloudInit(K)}));let H=[];for(let D of Z){let B=y.find((K)=>K.id===D);if(!B||!B.private_net?.[0]?.ip)B=await this.client.getServer(D).catch(()=>B);H.push({privateIp:B?.private_net?.[0]?.ip,publicIp:B?.public_net.ipv4?.ip})}let fe=`${s}-${n}-lb`,ae,se;if(t.loadBalancer){let D=y.find((K)=>re(K.labels,s,n,"lb")),B=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"};if(!D){let K=de({proxy:B,config:Fe(d,H,{proxy:B,slug:s}),slug:s,bunBin:k.runtime==="node"||k.runtime==="deno"?void 0:"/usr/local/bin/bun"}),ce=me(te({runtime:"bun",rpxProvision:K,baked:!1})),he=typeof i.loadBalancer==="object"?i.loadBalancer.size:void 0,{server:rt,action:Zt}=await this.client.createServer({name:fe,serverType:lt(he??"micro"),image:c,location:l,userData:ce,labels:W(s,n,"lb"),sshKeys:f?[f]:void 0,firewalls:[{firewall:T.id}],networks:[w.id]});if(await this.client.waitForAction(Zt.id),D=await this.client.waitForServerRunning(rt.id),this.waitForBoot){let nt=D.public_net.ipv4?.ip;if(nt)await this.waitForSshReady(nt),await this.waitForCloudInit(nt)}}else this.refreshLbRoutes(D,d,H,B,s);ae=D.id,se=D.public_net.ipv4?.ip}let L=se??(await this.client.getServer(Z[0]).catch(()=>{return}))?.public_net.ipv4?.ip,z={provider:"hetzner",stackName:o,networkId:w.id,lbServerId:ae,appServerIds:Z,servicesServerId:x,servicesPrivateIp:R,publicIp:L,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await dt(o,z),{appPublicIp:L,loadBalancerIp:se,servicesPrivateIp:R,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async destroyCompute(e){let{config:t,environment:r}=e,n=t.project.slug,s=E(t,r),i=await pe(s),o=[],a=`${n}-${r}-lb`,l=(await this.client.listLoadBalancers().catch(()=>[])).find((S)=>S.name===a);if(l)try{await this.client.deleteLoadBalancer(l.id),o.push(`load balancer ${a}`)}catch{}let p=await this.client.listServers().catch(()=>[]),d=new Set;for(let S of p)if(re(S.labels,n,r,"app")||re(S.labels,n,r,"services")||re(S.labels,n,r,"lb"))d.add(S.id);if(i?.serverId)d.add(i.serverId);if(i?.servicesServerId)d.add(i.servicesServerId);if(i?.lbServerId)d.add(i.lbServerId);for(let S of i?.appServerIds??[])d.add(S);for(let S of d)try{await this.client.deleteServer(S),o.push(`server ${S}`)}catch{}let m=await this.client.listFirewalls().catch(()=>[]);for(let S of[`${n}-${r}-app-fw`,`${n}-${r}-services-fw`,`${n}-${r}-lb-fw`]){let T=m.find((y)=>y.name===S);if(!T)continue;for(let y=0;y<12;y++)try{await this.client.deleteFirewall(T.id),o.push(`firewall ${S}`);break}catch{await this.sleep(3000)}}let f=`${n}-${r}-net`,_=(await this.client.listNetworks().catch(()=>[])).find((S)=>S.name===f);if(_)for(let S=0;S<12;S++)try{await this.client.deleteNetwork(_.id),o.push(`network ${f}`);break}catch{await this.sleep(3000)}let b=(await this.client.listSshKeys().catch(()=>[])).filter((S)=>Gr(S.labels,n,r));for(let S of b)try{await this.client.deleteSshKey(S.id),o.push(`ssh key ${S.name}`)}catch{}return await dt(s,{provider:"hetzner",stackName:s}).catch(()=>{}),{destroyed:o}}async getComputeOutputs(e){let t=E(e.config,e.environment),r=await pe(t);if(r?.serverId){let i=await this.tryGetServer(r.serverId);if(i)return this.outputsFromState(r,i)}if(r?.lbServerId){let o=(await this.tryGetServer(r.lbServerId))?.public_net.ipv4?.ip??r.publicIp;return{...this.outputsFromState(r),appPublicIp:o,loadBalancerIp:o}}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:E(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:E(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,"-")}-${Ps()}.tar.gz`}`,i=await sc(e.localPath),o=je,a=`${o}/${i}.tar.gz`;for(let c of t){if(!c.publicIp)throw Error(`Target ${c.id} has no public IP for SCP upload`);let l=["set -euo pipefail",`mkdir -p ${yt(o)} /var/ts-cloud/staging`,`test -s ${yt(a)}`,`cp -- ${yt(a)} ${yt(s)}`].join(`
278
278
  `);try{this.sshExec(c.publicIp,l);continue}catch{}let p=`${o}/.${i}-${Ps()}.tmp`;try{this.scpToHost(c.publicIp,e.localPath,p),this.sshExec(c.publicIp,At(p,a,s))}catch(d){try{this.sshExec(c.publicIp,Lt(p))}catch{}throw d}}return{artifactRef:s}}async findComputeTargets(e){let t=e.role||"app",r=(i)=>({id:String(i.id),name:i.name,publicIp:i.public_net.ipv4?.ip,publicIpv6:ue(i.public_net.ipv6?.ip),privateIp:i.private_net?.[0]?.ip,status:i.status});if(t==="app"||t==="lb"||t==="services"){let i=await pe(e.stackName??`${e.slug}-${e.environment}`),o=[...new Set(t==="app"?[i?.serverId,...i?.appServerIds??[]]:t==="lb"?[i?.lbServerId]:[i?.servicesServerId])].filter((l)=>typeof l==="number");if(this.stateOnly){if(o.length>0&&i?.publicIp)return o.map((l)=>({id:String(l),name:l===i.serverId?i.serverName:void 0,publicIp:i.publicIp,publicIpv6:i.publicIpv6,status:"running"}));if(t!=="app")return[];throw Error(`Hetzner API token required because '${e.stackName??`${e.slug}-${e.environment}`}' has no complete local compute state pin.`)}let a=await this.client.listServers();if(o.length>0){let l=[];for(let p of o){let d=a.find((m)=>m.id===p)??await this.tryGetServer(p);if(p===i?.serverId&&i.serverName&&d?.name!==i.serverName)continue;if(d&&d.status!=="off")l.push(d)}if(l.length>0)return l.map(r)}let c=a.filter((l)=>re(l.labels,e.slug,e.environment,t));if(c.length>0)return c.map(r);if(t==="app"){let l=a.filter((p)=>p.status!=="off"&&p.labels?.[`${j}/managed-by`]==="ts-cloud"&&p.labels?.[`${j}/environment`]===e.environment&&p.labels?.[`${j}/role`]==="app");if(l.length===1)return l.map(r)}return[]}if(this.stateOnly)throw Error(`Hetzner API token required to discover '${t}' compute targets.`);let s=(await this.client.listServers()).filter((i)=>re(i.labels,e.slug,e.environment,t));if(s.length>0)return s.map(r);return[]}async attachToComputeInfrastructure(e,t,r){let n=await this.client.listServers(),s=(m)=>n.filter((f)=>f.status!=="off"&&re(f.labels,e,r,m)),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 o=s("lb")[0],a=s("services")[0],c=i[0],l=o??c,p=E(t,r),d={provider:"hetzner",stackName:p,serverId:c.id,serverName:c.name,appServerIds:i.map((m)=>m.id),lbServerId:o?.id,servicesServerId:a?.id,servicesPrivateIp:a?.private_net?.[0]?.ip,publicIp:l.public_net.ipv4?.ip,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await dt(p,d),this.outputsFromState(d)}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(`
279
279
  `),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);Le(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:xe(r,"One or more SSH deploy commands failed")}}async ensureSshKey(e,t,r){if(!rc(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=nc(this.sshPublicKeyPath,"utf8").trim(),s=ht(n),o=(await this.client.listSshKeys()).find((c)=>ht(c.public_key)===s);if(o)return o.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 o=r.filter((c)=>c.privateIp||c.publicIp);if(o.length===0){console.warn(`[ts-cloud] No routable app boxes found for LB '${e.name}' — leaving its current rpx routes untouched.`);return}let a=Fe(t,o,{proxy:n,slug:s});this.sshExec(i,He({config:a,slug:s}).join(`
280
280
  `))}async findExistingServer(e,t,r){let n=await this.client.listServers(),s=n.find((o)=>re(o.labels,e,t,"app")||o.name===r);if(s)return s;let i=n.filter((o)=>o.status!=="off"&&o.labels?.[`${j}/managed-by`]==="ts-cloud"&&o.labels?.[`${j}/environment`]===t&&o.labels?.[`${j}/role`]==="app");if(i.length===1){let o=i[0],a=o.labels?.[`${j}/project`]??"unknown";return console.warn(`[ts-cloud] No server named '${r}' found; adopting existing ts-cloud app server '${o.name}' (project label '${a}') for project '${e}' — `+"updating it in place instead of provisioning a new server."),o}return}async ensureFirewall(e,t,r){let s=(await this.client.listFirewalls()).find((o)=>o.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{Cs(`ssh ${this.sshBaseArgs(e,["-o","ConnectTimeout=5"]).map(yt).join(" ")} true`,{stdio:"pipe",maxBuffer:Yr});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}:
@@ -373,7 +373,7 @@ ${" ".repeat(t+10)}${r.remediation}`:n}).join(`
373
373
  `);try{await this.exec(a.publicIp,c);continue}catch{}let l=`${cn}/.${i}-${ii()}.tmp`;try{await this.transport.scp(a.publicIp,e.localPath,l),await this.exec(a.publicIp,At(l,o,s))}catch(p){throw await this.exec(a.publicIp,Lt(l)).catch(()=>{}),p}}return{artifactRef:s}}async runRemoteDeploy(e){if(e.targets.length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets provided"};let t=e.commands.join(`
374
374
  `),r=[];for(let s of e.targets){if(!s.publicIp){r.push({instanceId:s.id,status:"Failed",error:"Missing address"});continue}try{let i=await this.exec(s.publicIp,t);Le(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:xe(r,"One or more SSH deploy commands failed")}}targetHost(){return this.host.host}ensureHostKey(e=this.host.host){return this.transport.ensureHostKey(e)}async preflight(e=this.host.host){let t=await this.transport.exec(e,sn,{sudo:!1}),r=on(t);return{facts:r,findings:an(r,{user:this.host.user,profile:this.settings.profile})}}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e;for(let h of li(t,this.settings))console.warn(`[ts-cloud] ${h}`);let n=this.host,s=E(t,r),i=await Ie(s,this.cwd),o=process.env[oi]==="1"&&i?.provider==="ssh"&&i.host===n.host&&i.bootstrapVersion===Te,a=await this.ensureHostKey(n.host);if(a.pinnedNow)console.warn(`[ts-cloud] pinned ${n.host} host key ${a.fingerprint}`);await this.waitForSshReady(n.host);let{facts:c,findings:l}=await this.preflight(n.host);if(dr(l))throw Error(`Preflight failed for ${n.host}; refusing to bootstrap it.
375
375
  ${zr(l)}`);for(let h of l)console.warn(`[ts-cloud] ${h.severity}: ${h.message}`);if(c.cloudInitPresent&&/running/i.test(c.cloudInitStatus??""))await this.waitForCloudInit(n.host);let p=c.lanIp?.trim()||(Tc(n.host)!==0?n.host:void 0),d=i?.provider==="ssh"?i.bootstrappedAt:void 0;if(!o){let h=cr({config:t,environment:r,profile:this.settings.profile,facts:c,sudoUser:n.user!=="root"?n.user:void 0,lan:this.settings.lan,lanIp:p});Le(await this.exec(n.host,h)),d=new Date().toISOString()}let m={provider:"ssh",stackName:s,host:n.host,sshUser:n.user,sshPort:n.port,hostKeyFingerprint:a.fingerprint||void 0,publicIp:this.settings.publicIp==="auto"?void 0:this.settings.publicIp,lanIp:c.lanIp||void 0,deployStoragePath:_t,profile:this.settings.profile,bootstrapVersion:Te,bootstrappedAt:d};await Ye(s,m,this.cwd);let f=await this.getComputeOutputs();if(Y(t.infrastructure?.compute)&&Sr(this.settings.lan)==="local-ca")f.lanCaCertPath=Ct(),console.warn(`[ts-cloud] LAN certificate authority on ${n.host} at ${f.lanCaCertPath}. Fetch it with: scp ${n.user}@${n.host}:${f.lanCaCertPath} ./rpx-root-ca.crt`);return f}async destroyCompute(e){let t=E(e.config,e.environment),r=this.host;return console.warn(`[ts-cloud] forgot ${r.host} for ${t}; nothing was removed on the host (stop the systemd units and remove /var/ts-cloud and /etc/rpx by hand if you want it clean).`),await Ye(t,{provider:"ssh",stackName:t,host:r.host,sshUser:r.user,sshPort:r.port},this.cwd).catch(()=>{}),{destroyed:[`local state for ${t}`]}}async sleep(e){await new Promise((t)=>setTimeout(t,e))}async waitForSshReady(e){let{sshIntervalMs:t,sshTimeoutMs:r}=this.bootWait,n=Date.now();do{if(await this.transport.probe(e))return;await this.sleep(t)}while(Date.now()-n<r);throw Error(`Timed out waiting for SSH on ${e} after ${r}ms`)}async waitForCloudInit(e){let{cloudInitIntervalMs:t,cloudInitTimeoutMs:r}=this.bootWait,n=Date.now();while(Date.now()-n<r){try{let s=await this.transport.exec(e,"if command -v cloud-init >/dev/null 2>&1; then cloud-init status --long 2>/dev/null || true; else echo 'status: done'; fi",{sudo:!1});if(/status:\s*error/.test(s))throw Error(`cloud-init reported an error on ${e}:
376
- ${s}`);if(/status:\s*(?:done|degraded)/.test(s))return}catch(s){if(s instanceof Error&&/cloud-init reported an error/.test(s.message))throw s}await this.sleep(t)}throw Error(`Timed out waiting for cloud-init to finish on ${e} after ${r}ms`)}}function x(e){if(Jr())return new Ut;switch(e.provider??F(e.config)){case"aws":return new Rt({region:e.config.project.region});case"hetzner":return new _e({apiToken:e.config.hetzner?.apiToken,allowStateOnly:Boolean(e.config.cloud?.attachTo),sshPrivateKeyPath:e.config.hetzner?.sshPrivateKeyPath,sshPublicKeyPath:e.config.hetzner?.sshPublicKeyPath,sshUser:e.config.hetzner?.sshUser,location:e.config.hetzner?.location});case"ssh":return new ur({hosts:e.config.ssh?.hosts,hostKey:e.config.ssh?.hostKey,sudo:e.config.ssh?.sudo,profile:e.config.ssh?.profile,publicIp:e.config.ssh?.publicIp,lan:e.config.ssh?.lan});default:throw Error(`Unknown cloud provider: ${e.provider??F(e.config)}`)}}class di{drivers=new Map;getDriver(e,t){let r=t??F(e),n=`${r}:${e.project.slug}:${e.project.region||"default"}`,s=this.drivers.get(n);if(s)return s;let i=x({config:e,provider:r});return this.drivers.set(n,i),i}}var rm=new di;var mi="/var/lib/ts-cloud/bootstrap.sh",Mi={"raspberry-pi-os":"bootfs",ubuntu:"system-boot"},Pc=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,xc=/^[a-z_][a-z0-9_-]{0,31}$/,Rc=/^[A-Z]{2}$/;function ie(e){return JSON.stringify(e)}function Ec(e){if(!Pc.test(e.hostname))throw Error(`Invalid hostname '${e.hostname}': use lowercase letters, digits and hyphens.`);if(!xc.test(e.user))throw Error(`Invalid user '${e.user}': use a lowercase Unix user name.`);let t=e.publicKey.trim();if(!t||t.includes(`
376
+ ${s}`);if(/status:\s*(?:done|degraded)/.test(s))return}catch(s){if(s instanceof Error&&/cloud-init reported an error/.test(s.message))throw s}await this.sleep(t)}throw Error(`Timed out waiting for cloud-init to finish on ${e} after ${r}ms`)}}function O(e){if(Jr())return new Ut;switch(e.provider??F(e.config)){case"aws":return new Rt({region:e.config.project.region});case"hetzner":return new _e({apiToken:e.config.hetzner?.apiToken,allowStateOnly:Boolean(e.config.cloud?.attachTo),sshPrivateKeyPath:e.config.hetzner?.sshPrivateKeyPath,sshPublicKeyPath:e.config.hetzner?.sshPublicKeyPath,sshUser:e.config.hetzner?.sshUser,location:e.config.hetzner?.location});case"ssh":return new ur({hosts:e.config.ssh?.hosts,hostKey:e.config.ssh?.hostKey,sudo:e.config.ssh?.sudo,profile:e.config.ssh?.profile,publicIp:e.config.ssh?.publicIp,lan:e.config.ssh?.lan});default:throw Error(`Unknown cloud provider: ${e.provider??F(e.config)}`)}}class di{drivers=new Map;getDriver(e,t){let r=t??F(e),n=`${r}:${e.project.slug}:${e.project.region||"default"}`,s=this.drivers.get(n);if(s)return s;let i=O({config:e,provider:r});return this.drivers.set(n,i),i}}var rm=new di;var mi="/var/lib/ts-cloud/bootstrap.sh",Mi={"raspberry-pi-os":"bootfs",ubuntu:"system-boot"},Pc=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,xc=/^[a-z_][a-z0-9_-]{0,31}$/,Rc=/^[A-Z]{2}$/;function ie(e){return JSON.stringify(e)}function Ec(e){if(!Pc.test(e.hostname))throw Error(`Invalid hostname '${e.hostname}': use lowercase letters, digits and hyphens.`);if(!xc.test(e.user))throw Error(`Invalid user '${e.user}': use a lowercase Unix user name.`);let t=e.publicKey.trim();if(!t||t.includes(`
377
377
  `)||!/^(?:ssh|ecdsa|sk)-/.test(t))throw Error("publicKey must be one public key line, e.g. the contents of ~/.ssh/id_ed25519.pub.");if(e.wifi){if(!e.wifi.ssid)throw Error("wifi.ssid is required.");if(!e.wifi.passphrase)throw Error("wifi.passphrase is required.");if(!Rc.test(e.wifi.country))throw Error(`wifi.country must be a two-letter regulatory domain such as DE or US, not '${e.wifi.country}'.`)}}function Oc(e,t){let r=[`hostname: ${ie(e.hostname)}`,"manage_etc_hosts: true","users:",` - name: ${ie(e.user)}`," ssh_authorized_keys:",` - ${ie(e.publicKey.trim())}`,` sudo: ${ie("ALL=(ALL) NOPASSWD:ALL")}`," shell: /bin/bash"," lock_passwd: true","ssh_pwauth: false"];if(e.timezone)r.push(`timezone: ${ie(e.timezone)}`);if(e.locale)r.push(`locale: ${ie(e.locale)}`);if(r.push("package_update: true"),t==="raspberry-pi-os")r.push("rpi:"," enable_ssh: true"," interfaces:"," spi: false"," i2c: false"," onewire: false"," remote_gpio: false"," serial:"," console: false"," hardware: false");return`${r.join(`
378
378
  `)}
379
379
  `}function Dc(e){let t=["version: 2","ethernets:"," eth0:"," match:",` name: ${ie("e*")}`," dhcp4: true"," dhcp6: true"," optional: true"];if(e.wifi)t.push("wifis:"," wlan0:"," dhcp4: true"," dhcp6: true"," optional: true",` regulatory-domain: ${ie(e.wifi.country)}`," access-points:",` ${ie(e.wifi.ssid)}:`,` password: ${ie(e.wifi.passphrase)}`);return`${t.join(`
@@ -526,7 +526,7 @@ console.log(JSON.stringify({
526
526
  `.replace(/%/g,"\\%");c.push(`cat > ${w} <<'TS_CLOUD_CRON_EOF'`,T.replace(/\n$/,""),"TS_CLOUD_CRON_EOF",`chmod 644 ${w}`)}else c.push(`rm -f ${w}`);return c}function gn(e){return!!(e.queues?.length||e.daemons?.length||e.scheduler)}function hn(e){if(e.ssl?.provider)return e.ssl.provider;return e.domain?"letsencrypt":"none"}var Hi={cloudflare:{pkg:"python3-certbot-dns-cloudflare",plugin:"dns-cloudflare"},route53:{pkg:"python3-certbot-dns-route53",plugin:"dns-route53"},digitalocean:{pkg:"python3-certbot-dns-digitalocean",plugin:"dns-digitalocean"},google:{pkg:"python3-certbot-dns-google",plugin:"dns-google"}};function Ni(e){return`/etc/letsencrypt/ts-cloud-${e}.ini`}function dl(e){let t=e?Hi[e.provider]:void 0,r=["certbot","python3-certbot-nginx",...t?[t.pkg]:[]].join(" ");return["export DEBIAN_FRONTEND=noninteractive",t?`apt-get update -y && apt-get install -y ${r}`:`command -v certbot >/dev/null 2>&1 || { apt-get update -y && apt-get install -y ${r}; }`,"mkdir -p /etc/letsencrypt/renewal-hooks/deploy","cat > /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh <<'TS_CLOUD_HOOK_EOF'","#!/bin/sh","systemctl reload ts-cloud-nginx 2>/dev/null || systemctl reload nginx 2>/dev/null || true","TS_CLOUD_HOOK_EOF","chmod +x /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh","systemctl enable certbot.timer 2>/dev/null || true","systemctl start certbot.timer 2>/dev/null || true"]}function ml(e){if(!e.credentials||Object.keys(e.credentials).length===0)return[];let t=Ni(e.provider),r=Object.entries(e.credentials).map(([n,s])=>`${n} = ${s}`).join(`
527
527
  `);return[`cat > ${t} <<'TS_CLOUD_DNSCREDS_EOF'`,r,"TS_CLOUD_DNSCREDS_EOF",`chmod 600 ${t}`]}function fl(e){let t=e.dns,r=e.wildcard?[`*.${e.domain}`,e.domain]:[e.domain,...e.aliases||[]].filter(Boolean),n=["certbot","--non-interactive","--agree-tos","--keep-until-expiring"];if(t){let s=Hi[t.provider].plugin;if(n.push(`--${s}`),t.provider!=="route53"&&t.credentials)n.push(`--${s}-credentials ${Ni(t.provider)}`);if(typeof t.propagationSeconds==="number"&&t.provider!=="route53")n.push(`--${s}-propagation-seconds ${t.propagationSeconds}`);n.push("certonly")}else n.push("--nginx",`--nginx-ctl ${be}`,e.redirect===!1?"--no-redirect":"--redirect");if(e.email)n.push(`-m ${e.email}`);else n.push("--register-unsafely-without-email");for(let s of r)n.push(`-d ${s}`);return[n.join(" ")]}function Sn(e){if(hn(e)!=="letsencrypt"||!e.domain)return[];let t=e.ssl,r=t?.dns,n=t?.wildcard===!0;if(n&&!r)return[];return[...dl(r),...r?ml(r):[],...fl({domain:e.domain,aliases:e.aliases,email:t?.email,wildcard:n,dns:r})]}function zi(e){let{repository:t,releaseDir:r,commit:n}=e,s=t.branch||"main",i=t.url,o=[`rm -rf ${r}`,`mkdir -p ${r}`];if(t.strategy==="tag")if(t.tag)o.push(`git clone -q --depth 1 --branch ${oe(t.tag)} ${oe(i)} ${r}`),o.push(`printf '%s' ${oe(t.tag)} > ${r}/.ts-cloud-tag`);else{let a=t.tagPattern||"v*";o.push(`TS_CLOUD_TAG="$(git ls-remote --tags --refs --sort=-v:refname ${oe(i)} ${oe(`refs/tags/${a}`)} | head -n1 | sed 's#.*refs/tags/##')"`,`test -n "$TS_CLOUD_TAG" || { echo "no tags matching" ${oe(a)} "found in" ${oe(i)} >&2; exit 1; }`,`git clone -q --depth 1 --branch "$TS_CLOUD_TAG" ${oe(i)} ${r}`,`printf '%s' "$TS_CLOUD_TAG" > ${r}/.ts-cloud-tag`)}else if(n)o.push(`git -C ${r} init -q`,`git -C ${r} remote add origin ${oe(i)}`,`git -C ${r} fetch -q --depth 1 origin ${oe(n)}`,`git -C ${r} checkout -q FETCH_HEAD`);else o.push(`git clone -q --depth 1 --branch ${oe(s)} ${oe(i)} ${r}`);return o.push(`git -C ${r} rev-parse HEAD > ${r}/.ts-cloud-sha`),o}function oe(e){return`'${e.split("'").join("'\\''")}'`}var Gt="$CREATE_RELEASE",Vt="$ACTIVATE_RELEASE",Gi="$RESTART_QUEUES",Ki="composer install --no-interaction --prefer-dist --optimize-autoloader --no-dev",gl=["php artisan migrate --force","php artisan config:cache","php artisan route:cache","php artisan view:cache","php artisan event:cache","php artisan storage:link"];function hl(e){switch(e){case"laravel":case"statamic":return[Gt,Ki,...gl,Vt,Gi];case"php":case"wordpress":return[Gt,`${Ki} || true`,Vt];case"static":case"spa":return[Gt,Vt]}}function Sl(e,t){return e.replace(/^php\s+/,`${t} `).replace(/(\s)php\s+artisan\s+/g,`$1${t} artisan `)}function yl(e,t){let r=Et(t);return[`cat > ${e} <<'TS_CLOUD_ENV_EOF'`,r,"TS_CLOUD_ENV_EOF",`chmod 600 ${e}`]}function Wi(e,t,r){return[`cat > ${e} <<'${r}'`,t.replace(/\n$/,""),r,`chmod 600 ${e}`]}function vl(e,t){if(!t)return[];let r=[];if(t.composerAuth){let n=typeof t.composerAuth==="string"?t.composerAuth:JSON.stringify(t.composerAuth,null,2);r.push(...Wi(`${e}/auth.json`,n,"TS_CLOUD_AUTHJSON_EOF"))}if(t.npmrc)r.push(...Wi(`${e}/.npmrc`,t.npmrc,"TS_CLOUD_NPMRC_EOF"));return r}function Vi(e){let t=e.healthCheck?.path;if(!t||!e.domain)return[];let n=`http://127.0.0.1${t.startsWith("/")?t:`/${t}`}`;return[`echo "[ts-cloud] health check ${n} (Host: ${e.domain})"`,"TS_CLOUD_HC_OK=0",`for i in $(seq 1 10); do TS_CLOUD_HC=$(curl -s -o /dev/null -w "%{http_code}" -H "Host: ${e.domain}" -m 10 "${n}" 2>/dev/null || echo 000); case "$TS_CLOUD_HC" in 2*|3*) TS_CLOUD_HC_OK=1; break ;; esac; sleep 3; done`,'[ "$TS_CLOUD_HC_OK" = 1 ] && echo "health check passed ($TS_CLOUD_HC)" || { echo "health check FAILED (last=$TS_CLOUD_HC)" >&2; exit 1; }']}function qi(e){let{siteName:t,site:r,releaseId:n,commit:s}=e;if(!r.repository?.url)throw Error(`Site '${t}' is a PHP/git site but has no repository.url to clone`);let i=e.appBase??`/var/www/${t}`,o="php",a=Bt(i,n),c=r.sharedPaths??bo,l=[...c,...Ot(r.env,c)],p=r.keepReleases??ui,d=r.deployScript?.length?r.deployScript:hl(r.type??"laravel"),m=["set -euo pipefail",'export HOME="${HOME:-/root}"','export COMPOSER_HOME="${COMPOSER_HOME:-/root/.composer}"',"export COMPOSER_ALLOW_SUPERUSER=1",St()];if(m.push(...Eo(i,{releaseId:n,commit:s,branch:r.repository.branch,keepLogs:p})),m.push(...pi(a,l)),r.env&&Object.keys(r.env).length>0)m.push(...yl(`${a.shared}/.env`,r.env));for(let f of d){let h=f.trim();if(h===Gt)m.push(...zi({repository:r.repository,releaseDir:a.release,commit:s})),m.push(...To(a,l)),m.push(`cd ${a.release}`),m.push(...vl(a.release,r.credentials)),m.push(`chown -R www-data:www-data ${a.shared}/storage 2>/dev/null || true`,`[ -d ${a.release}/bootstrap/cache ] && chown -R www-data:www-data ${a.release}/bootstrap/cache 2>/dev/null || true`,`chmod -R ug+rwX ${a.shared}/storage 2>/dev/null || true`);else if(h===Vt)m.push(...tn(a)),m.push(...rn(a,p)),m.push(`(cd ${U} && pantry restart php-fpm) 2>/dev/null || true`);else if(h===Gi)m.push(`${o} artisan queue:restart || true`);else m.push(Sl(f,o))}return m}var Xt={mysql:{port:3306,binaries:["mysqld","mysql"]},mariadb:{port:3306,binaries:["mariadbd","mariadb","mysqld"]},postgres:{port:5432,binaries:["postgres","psql"]},redis:{port:6379,binaries:["redis-server","redis-cli"]},memcached:{port:11211,binaries:["memcached"]},meilisearch:{port:7700,binaries:["meilisearch"]},vitess:{port:15306,binaries:["vtgate"]}},Tt="ts-cloud-service:";function bl(e){return e===!0||typeof e==="object"&&e!=null}function Xi(e){if(!e)return[];return Object.keys(Xt).filter((t)=>bl(e[t]))}function Yi(e){if(e.length===0)return[];return[St(),"ts_cloud_port_open() {",' if command -v ss >/dev/null 2>&1; then ss -ltn 2>/dev/null | grep -qE "[:.]$1[[:space:]]" && return 0; fi',' if command -v netstat >/dev/null 2>&1; then netstat -ltn 2>/dev/null | grep -qE "[:.]$1[[:space:]]" && return 0; fi'," (exec 3<>/dev/tcp/127.0.0.1/$1) 2>/dev/null && { exec 3<&- 3>&-; return 0; }"," return 1","}","ts_cloud_probe() {",' TS_CLOUD_SVC="$1"; TS_CLOUD_PORT="$2"; shift 2',' for TS_CLOUD_BIN in "$@"; do',` if command -v "$TS_CLOUD_BIN" >/dev/null 2>&1; then echo "${Tt}$TS_CLOUD_SVC:present"; return 0; fi`," done",` if ts_cloud_port_open "$TS_CLOUD_PORT"; then echo "${Tt}$TS_CLOUD_SVC:present"; return 0; fi`,` echo "${Tt}$TS_CLOUD_SVC:missing"`," return 0","}",...e.filter((t)=>Xt[t]).map((t)=>`ts_cloud_probe ${t} ${Xt[t].port} ${Xt[t].binaries.join(" ")}`),"exit 0"]}function Ji(e,t){if(!e)return[];let r=new Map;for(let n of e.split(`
528
528
  `)){let s=n.indexOf(Tt);if(s===-1)continue;let[i,o]=n.slice(s+Tt.length).trim().split(":");if(i)r.set(i,o)}return t.filter((n)=>r.get(n)==="missing")}function Qi(e,t,r){let n=r?` on ${r}`:"",s=e.map((o)=>`managedServices.${o}`).join(", "),i=e.length===1?`no ${e[0]}`:`none of ${e.join(", ")}`;return`This project declares ${s}, but '${t}' has ${i}${n}. Attach mode does not provision services on the owner's box, so nothing will install ${e.length===1?"it":"them"}. Point the app at an external service, or ask the owner of '${t}' to add ${e.length===1?"it":"them"} to their own config and re-provision.`}var Zi="/var/lib/pantry/php-fpm/pool.d",wl=9100,_l=400;function Yt(e){return(e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"site").slice(0,28)}function eo(e){return`web_${Yt(e)}`}function Tl(e){let t=Yt(e),r=0;for(let n=0;n<t.length;n++)r=r*31+t.charCodeAt(n)>>>0;return wl+r%_l}function yn(e){return`127.0.0.1:${Tl(e)}`}function $l(e){let t=Yt(e.siteName),r=eo(e.siteName),n=e.maxChildren??10;return[`; ts-cloud-managed pool for ${e.siteName} (site isolation)`,`[${t}]`,`user = ${r}`,`group = ${r}`,`listen = ${yn(e.siteName)}`,"pm = dynamic",`pm.max_children = ${n}`,"pm.start_servers = 2","pm.min_spare_servers = 1","pm.max_spare_servers = 3","pm.max_requests = 500","catch_workers_output = yes",`php_admin_value[open_basedir] = ${e.appBase}:/tmp`,""].join(`
529
- `)}function to(e){let t=eo(e.siteName),r=Yt(e.siteName),n=`${Zi}/${r}.conf`;return[`getent group ${t} >/dev/null || groupadd --system ${t}`,`id -u ${t} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin -g ${t} ${t}`,`usermod -aG ${t} www-data 2>/dev/null || true`,`chown -R ${t}:${t} ${e.appBase} || true`,`chmod -R g+rX ${e.appBase} || true`,`chmod 600 ${e.appBase}/shared/.env 2>/dev/null || true`,`mkdir -p ${Zi}`,`cat > ${n} <<'TS_CLOUD_FPMPOOL_EOF'`,$l(e).replace(/\n$/,""),"TS_CLOUD_FPMPOOL_EOF",`(cd ${U} && pantry restart php-fpm) 2>/dev/null || true`]}var Qt={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};function Rl(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function no(e,t,r=Qt){let{config:n,environment:s,siteName:i,site:o,slug:a,sha:c,runtime:l,localTarballPath:p}=t,d=`releases/${i}/${c}.tar.gz`,m=E(n,s),f=await e.getComputeOutputs({config:n,environment:s}),h=await e.findComputeTargets({slug:a,environment:s,role:"app",stackName:m});if(h.length===0)return{success:!1,error:e.name==="aws"?`Stack '${m}' has no EC2 instances tagged Project=${a} Environment=${s} Role=app, and storage/cloud/state/${m}.json pins no live instance. For a shared box, record its instanceId there.`:`No Hetzner servers labeled ts-cloud/project=${a} ts-cloud/environment=${s} ts-cloud/role=app, and storage/cloud/state/${m}.json pins no live server. For a shared box, record its serverId there.`};let _=f.servicesPrivateIp?vs(f.servicesPrivateIp,C(n)):lc(C(n)),w=Xs(hi(n,{environment:s})),b=n.infrastructure?.compute,S=Dr(b?.hostCleanup),T=Y(b)?{HOST:"127.0.0.1"}:{},y=s==="production"?{APP_ENV:"production",NODE_ENV:"production"}:{},I={..._,...w,...T,...o.env||{},...y},R=xr(I,o.sharedPaths??[]);if(R.warning)r.warn(`Site '${i}': ${R.warning}`);else if(R.path)r.info(`Site '${i}': sharing '${R.path}' so the SQLite database survives deploys.`);if(ai(o)){let L=o.phpVersion??b?.php?.default??b?.php?.versions?.[0],z=J(a,i),D=Object.keys(_).length>0?{...o,env:I}:o,B=qi({siteName:i,site:D,releaseId:c,appBase:z,defaultPhpVersion:L}),K=!Y(b),he=hn(o)==="custom"&&o.ssl?.certPath&&o.ssl?.keyPath?{certPath:o.ssl.certPath,keyPath:o.ssl.keyPath}:void 0,rt=o.isolation?to({siteName:i,appBase:z}):[],Zt=K?nr({siteName:i,domain:o.domain||i,aliases:o.aliases,type:o.type,appDir:`${z}/current`,webDirectory:o.webDirectory,phpVersion:L,fastcgiPass:o.isolation?yn(i):void 0,redirects:o.redirects,ssl:he,auth:o.auth&&o.auth.enabled!==!1&&o.auth.password?{username:o.auth.username||"admin",password:o.auth.password,realm:o.auth.realm}:void 0,serverSnippet:rr(o.nginx,b?.nginxTemplates),clientMaxBodySize:o.nginx?.clientMaxBodySize,hsts:o.ssl?.hsts,tlsProtocols:o.ssl?.tlsProtocols,security:o.security}):[],nt=K?Sn(o):[],Co=gn(o)?fn({slug:a,siteName:i,site:o,phpVersion:L,appBase:z}):[],Po=K?Vi(o):[];r.step(`Deploying PHP site '${i}' to ${h.length} target(s)...`);let Ce=await e.runRemoteDeploy({targets:h,commands:[...js(z,a),...B,...rt,...Zt,...nt,...Co,...Po,...S],comment:`ts-cloud deploy ${a}/${i}@${c}`,tags:{Project:a,Environment:s,Role:"app"}}),Cn=On(n.notifications,o.notifications);if(!Ce.success)return await ro(e,h,S,r),await pr(Cn,"deploy-failed",`❌ Deploy of ${a}/${i}@${c} failed: ${Ce.error||"unknown error"}`),{success:!1,error:Ce.error||"Remote PHP deploy failed",instanceCount:Ce.instanceCount,perInstance:Ce.perInstance};let xo=o.domain?` → https://${o.domain}`:"";return await pr(Cn,"deploy",`✅ Deployed ${a}/${i}@${c}${xo}`),{success:!0,instanceCount:Ce.instanceCount,perInstance:Ce.perInstance}}if(!p)return{success:!1,error:`Site '${i}' requires a release tarball but none was provided`};let O=await e.uploadRelease({config:n,environment:s,localPath:p,remoteKey:d,targets:h}),N=mt(a,i,c),ne=e.name==="aws"?kr(f.deployBucketName,d,n.project.region||"us-east-1",N):Ur(O.artifactRef,N),G=P(o),k=J(a,i),X=G==="server-static"?Nr({siteName:i,slug:a,appDir:k,artifactFetch:ne,releaseId:c,preStartCommands:o.preStart}):Lr({siteName:i,slug:a,appDir:k,artifactFetch:ne,releaseId:c,execStart:Ar(o.start,l,`${k.replace(/\/+$/,"")}/releases/%i`),envEntries:I,port:o.port,preStartCommands:o.preStart,sharedPaths:o.sharedPaths,zeroDowntime:o.zeroDowntime!==!1,healthCheckPath:o.healthCheck?.path,liveness:o.liveness,memoryHigh:o.memoryHigh,memoryMax:o.memoryMax,cpuWeight:o.cpuWeight,ioWeight:o.ioWeight,tasksMax:o.tasksMax,stopTimeout:o.stopTimeout}),M=G==="server-static"&&!Y(b)&&!!o.domain,Z=M?nr({siteName:i,domain:o.domain,aliases:o.aliases,type:o.type==="spa"?"spa":"static",appDir:`${k}/current`,webDirectory:"",redirects:o.redirects,auth:o.auth&&o.auth.enabled!==!1&&o.auth.password?{username:o.auth.username||"admin",password:o.auth.password,realm:o.auth.realm}:void 0,serverSnippet:rr(o.nginx,b?.nginxTemplates),clientMaxBodySize:o.nginx?.clientMaxBodySize,hsts:o.ssl?.hsts,tlsProtocols:o.ssl?.tlsProtocols,security:o.security}):[],H=M?Sn(o):[],fe=gn(o)?fn({slug:a,siteName:i,site:o,appBase:k}):[],ae=[...Eo(k,{releaseId:c,commit:c,branch:o.repository?.branch??"main"}),...js(k,a),...X,...Z,...H,...fe,...S];r.step(`Deploying to ${h.length} target(s)...`);let se=await e.runRemoteDeploy({targets:h,commands:ae,comment:`ts-cloud deploy ${a}/${i}@${c}`,tags:{Project:a,Environment:s,Role:"app"}});if(!se.success)return await ro(e,h,S,r),{success:!1,error:se.error||"Remote deploy failed",instanceCount:se.instanceCount,perInstance:se.perInstance};return{success:!0,instanceCount:se.instanceCount,perInstance:se.perInstance}}async function ro(e,t,r,n){if(r.length===0)return;try{let s=await e.runRemoteDeploy({targets:t,commands:r,comment:"ts-cloud host cleanup after failed deploy"});if(!s.success)n.warn(`Host cleanup after the failed deploy did not complete: ${s.error||"unknown error"}`)}catch(s){n.warn(`Host cleanup after the failed deploy did not run: ${s.message}`)}}function Jt(e){return`'${e.replaceAll("'","'\\''")}'`}function El(e,t,r=!1,n=[]){let s=`${e}-dashboard-`,i=t.map((a)=>`${e}-${a}.service`),o=r?[`export TS_CLOUD_DASHBOARD_KEEP_DOMAINS=${Jt(JSON.stringify(n))}`,"rm -f /run/ts-cloud-dashboard-routes-changed",`/usr/local/bin/bun --bun -e ${Jt(`
529
+ `)}function to(e){let t=eo(e.siteName),r=Yt(e.siteName),n=`${Zi}/${r}.conf`;return[`getent group ${t} >/dev/null || groupadd --system ${t}`,`id -u ${t} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin -g ${t} ${t}`,`usermod -aG ${t} www-data 2>/dev/null || true`,`chown -R ${t}:${t} ${e.appBase} || true`,`chmod -R g+rX ${e.appBase} || true`,`chmod 600 ${e.appBase}/shared/.env 2>/dev/null || true`,`mkdir -p ${Zi}`,`cat > ${n} <<'TS_CLOUD_FPMPOOL_EOF'`,$l(e).replace(/\n$/,""),"TS_CLOUD_FPMPOOL_EOF",`(cd ${U} && pantry restart php-fpm) 2>/dev/null || true`]}var Qt={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};function Rl(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function no(e,t,r=Qt){let{config:n,environment:s,siteName:i,site:o,slug:a,sha:c,runtime:l,localTarballPath:p}=t,d=`releases/${i}/${c}.tar.gz`,m=E(n,s),f=await e.getComputeOutputs({config:n,environment:s}),h=await e.findComputeTargets({slug:a,environment:s,role:"app",stackName:m});if(h.length===0)return{success:!1,error:e.name==="aws"?`Stack '${m}' has no EC2 instances tagged Project=${a} Environment=${s} Role=app, and storage/cloud/state/${m}.json pins no live instance. For a shared box, record its instanceId there.`:`No Hetzner servers labeled ts-cloud/project=${a} ts-cloud/environment=${s} ts-cloud/role=app, and storage/cloud/state/${m}.json pins no live server. For a shared box, record its serverId there.`};let _=f.servicesPrivateIp?vs(f.servicesPrivateIp,C(n)):lc(C(n)),w=Xs(hi(n,{environment:s})),b=n.infrastructure?.compute,S=Dr(b?.hostCleanup),T=Y(b)?{HOST:"127.0.0.1"}:{},y=s==="production"?{APP_ENV:"production",NODE_ENV:"production"}:{},I={..._,...w,...T,...o.env||{},...y},x=xr(I,o.sharedPaths??[]);if(x.warning)r.warn(`Site '${i}': ${x.warning}`);else if(x.path)r.info(`Site '${i}': sharing '${x.path}' so the SQLite database survives deploys.`);if(ai(o)){let L=o.phpVersion??b?.php?.default??b?.php?.versions?.[0],z=J(a,i),D=Object.keys(_).length>0?{...o,env:I}:o,B=qi({siteName:i,site:D,releaseId:c,appBase:z,defaultPhpVersion:L}),K=!Y(b),he=hn(o)==="custom"&&o.ssl?.certPath&&o.ssl?.keyPath?{certPath:o.ssl.certPath,keyPath:o.ssl.keyPath}:void 0,rt=o.isolation?to({siteName:i,appBase:z}):[],Zt=K?nr({siteName:i,domain:o.domain||i,aliases:o.aliases,type:o.type,appDir:`${z}/current`,webDirectory:o.webDirectory,phpVersion:L,fastcgiPass:o.isolation?yn(i):void 0,redirects:o.redirects,ssl:he,auth:o.auth&&o.auth.enabled!==!1&&o.auth.password?{username:o.auth.username||"admin",password:o.auth.password,realm:o.auth.realm}:void 0,serverSnippet:rr(o.nginx,b?.nginxTemplates),clientMaxBodySize:o.nginx?.clientMaxBodySize,hsts:o.ssl?.hsts,tlsProtocols:o.ssl?.tlsProtocols,security:o.security}):[],nt=K?Sn(o):[],Co=gn(o)?fn({slug:a,siteName:i,site:o,phpVersion:L,appBase:z}):[],Po=K?Vi(o):[];r.step(`Deploying PHP site '${i}' to ${h.length} target(s)...`);let Ce=await e.runRemoteDeploy({targets:h,commands:[...js(z,a),...B,...rt,...Zt,...nt,...Co,...Po,...S],comment:`ts-cloud deploy ${a}/${i}@${c}`,tags:{Project:a,Environment:s,Role:"app"}}),Cn=On(n.notifications,o.notifications);if(!Ce.success)return await ro(e,h,S,r),await pr(Cn,"deploy-failed",`❌ Deploy of ${a}/${i}@${c} failed: ${Ce.error||"unknown error"}`),{success:!1,error:Ce.error||"Remote PHP deploy failed",instanceCount:Ce.instanceCount,perInstance:Ce.perInstance};let xo=o.domain?` → https://${o.domain}`:"";return await pr(Cn,"deploy",`✅ Deployed ${a}/${i}@${c}${xo}`),{success:!0,instanceCount:Ce.instanceCount,perInstance:Ce.perInstance}}if(!p)return{success:!1,error:`Site '${i}' requires a release tarball but none was provided`};let R=await e.uploadRelease({config:n,environment:s,localPath:p,remoteKey:d,targets:h}),N=mt(a,i,c),ne=e.name==="aws"?kr(f.deployBucketName,d,n.project.region||"us-east-1",N):Ur(R.artifactRef,N),G=P(o),k=J(a,i),X=G==="server-static"?Nr({siteName:i,slug:a,appDir:k,artifactFetch:ne,releaseId:c,preStartCommands:o.preStart}):Lr({siteName:i,slug:a,appDir:k,artifactFetch:ne,releaseId:c,execStart:Ar(o.start,l,`${k.replace(/\/+$/,"")}/releases/%i`),envEntries:I,port:o.port,preStartCommands:o.preStart,sharedPaths:o.sharedPaths,zeroDowntime:o.zeroDowntime!==!1,healthCheckPath:o.healthCheck?.path,liveness:o.liveness,memoryHigh:o.memoryHigh,memoryMax:o.memoryMax,cpuWeight:o.cpuWeight,ioWeight:o.ioWeight,tasksMax:o.tasksMax,stopTimeout:o.stopTimeout}),M=G==="server-static"&&!Y(b)&&!!o.domain,Z=M?nr({siteName:i,domain:o.domain,aliases:o.aliases,type:o.type==="spa"?"spa":"static",appDir:`${k}/current`,webDirectory:"",redirects:o.redirects,auth:o.auth&&o.auth.enabled!==!1&&o.auth.password?{username:o.auth.username||"admin",password:o.auth.password,realm:o.auth.realm}:void 0,serverSnippet:rr(o.nginx,b?.nginxTemplates),clientMaxBodySize:o.nginx?.clientMaxBodySize,hsts:o.ssl?.hsts,tlsProtocols:o.ssl?.tlsProtocols,security:o.security}):[],H=M?Sn(o):[],fe=gn(o)?fn({slug:a,siteName:i,site:o,appBase:k}):[],ae=[...Eo(k,{releaseId:c,commit:c,branch:o.repository?.branch??"main"}),...js(k,a),...X,...Z,...H,...fe,...S];r.step(`Deploying to ${h.length} target(s)...`);let se=await e.runRemoteDeploy({targets:h,commands:ae,comment:`ts-cloud deploy ${a}/${i}@${c}`,tags:{Project:a,Environment:s,Role:"app"}});if(!se.success)return await ro(e,h,S,r),{success:!1,error:se.error||"Remote deploy failed",instanceCount:se.instanceCount,perInstance:se.perInstance};return{success:!0,instanceCount:se.instanceCount,perInstance:se.perInstance}}async function ro(e,t,r,n){if(r.length===0)return;try{let s=await e.runRemoteDeploy({targets:t,commands:r,comment:"ts-cloud host cleanup after failed deploy"});if(!s.success)n.warn(`Host cleanup after the failed deploy did not complete: ${s.error||"unknown error"}`)}catch(s){n.warn(`Host cleanup after the failed deploy did not run: ${s.message}`)}}function Jt(e){return`'${e.replaceAll("'","'\\''")}'`}function El(e,t,r=!1,n=[]){let s=`${e}-dashboard-`,i=t.map((a)=>`${e}-${a}.service`),o=r?[`export TS_CLOUD_DASHBOARD_KEEP_DOMAINS=${Jt(JSON.stringify(n))}`,"rm -f /run/ts-cloud-dashboard-routes-changed",`/usr/local/bin/bun --bun -e ${Jt(`
530
530
  const { chmodSync, existsSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } = require('node:fs')
531
531
  const { basename, join } = require('node:path')
532
532
  const root = '/etc/rpx/sites.d'
@@ -554,7 +554,7 @@ console.log(JSON.stringify({
554
554
  changed = true
555
555
  }
556
556
  if (changed) writeFileSync('/run/ts-cloud-dashboard-routes-changed', '')
557
- `)}`,"if [ -e /run/ts-cloud-dashboard-routes-changed ]; then"," systemctl restart rpx-gateway.service"," rm -f /run/ts-cloud-dashboard-routes-changed","fi"]:[];return["set -euo pipefail",`TS_CLOUD_DASHBOARD_PREFIX=${Jt(s)}`,`TS_CLOUD_DASHBOARD_SERVER_OWNER=${r?"1":"0"}`,`TS_CLOUD_DASHBOARD_DESIRED=${Jt(` ${i.join(" ")} `)}`,"for TS_CLOUD_UNIT_FILE in /etc/systemd/system/*.service; do",' [ -e "$TS_CLOUD_UNIT_FILE" ] || continue',' TS_CLOUD_UNIT=$(basename "$TS_CLOUD_UNIT_FILE")',' case "$TS_CLOUD_UNIT" in'," *-dashboard-*.service)",' if [ "$TS_CLOUD_DASHBOARD_SERVER_OWNER" != 1 ]; then',' case "$TS_CLOUD_UNIT" in "$TS_CLOUD_DASHBOARD_PREFIX"*.service) ;; *) continue ;; esac'," fi",' case "$TS_CLOUD_DASHBOARD_DESIRED" in',' *" $TS_CLOUD_UNIT "*) ;;'," *)",' systemctl disable --now "$TS_CLOUD_UNIT" 2>/dev/null || true',' rm -f "$TS_CLOUD_UNIT_FILE"'," ;;"," esac"," ;;"," esac","done","systemctl daemon-reload","systemctl reset-failed",...o]}async function Ol(e,t,r,n){let{config:s,environment:i}=t,o=s.project.slug,a=E(s,i),c=await e.findComputeTargets({slug:o,environment:i,role:"app",stackName:a});if(c.length===0)return!0;let l=await e.runRemoteDeploy({targets:c,commands:El(o,r,!s.cloud?.attachTo,r.map((p)=>s.sites?.[p]?.domain).filter((p)=>typeof p==="string")),comment:`ts-cloud reconcile management dashboard ${o}`,tags:{Project:o,Environment:i,Role:"app"}});if(!l.success)return n.error(`Management dashboard reconciliation failed: ${l.error||"unknown error"}`),!1;return!0}async function Dl(e,t,r){let{config:n}=t,s=n.cloud?.attachTo;if(!s||!e.listReachableResources)return;let i;try{i=await e.listReachableResources()}catch(c){r.warn(`Could not determine this credential's reach: ${c instanceof Error?c.message:String(c)}`);return}let o=Ti(i,{ownerSlug:s,selfSlug:n.project.slug}),a=pn(o)>0;for(let c of Ci(o,{ownerSlug:s,selfSlug:n.project.slug}))if(a)r.warn(c);else r.info(c)}async function Il(e,t,r){let{config:n,environment:s}=t,i=n.cloud?.attachTo;if(!i)return!0;let o=Xi(n.infrastructure?.compute?.managedServices);if(o.length===0)return!0;let a=n.project.slug,c=E(n,s),l=await e.findComputeTargets({slug:a,environment:s,role:"app",stackName:c});if(l.length===0)return!0;let p=await e.runRemoteDeploy({targets:l,commands:Yi(o),comment:`ts-cloud preflight managed services ${a}`,tags:{Project:a,Environment:s,Role:"app"}});if(!p.success)return r.warn(`Could not check '${i}' for the declared services: ${p.error||"unknown error"}`),!0;let d=new Set;for(let m of p.perInstance)for(let f of Ji(m.output,o))d.add(f);if(d.size===0)return!0;return r.error(Qi([...d],i,l[0]?.publicIp)),!1}async function Al(e,t,r){let{config:n,environment:s}=t;if(!n.cloud?.attachTo)return!0;let i=n.infrastructure?.compute,o=C(n),a=bt(o,i?.managedServices??{});if(a.length===0)return!0;let c=n.project.slug,l=E(n,s),p=await e.findComputeTargets({slug:c,environment:s,role:"app",stackName:l});if(p.length===0)return!0;r.step(`Ensuring database '${o?.name}' + role exist on the shared box...`);let d=await e.runRemoteDeploy({targets:p,commands:a,comment:`ts-cloud ensure database ${c}/${o?.name}`,tags:{Project:c,Environment:s,Role:"app"}});if(!d.success)return r.error(`Ensuring database '${o?.name}' failed: ${d.error||"unknown error"}`),!1;return r.success(`Database '${o?.name}' is ready on ${d.instanceCount} target(s)`),!0}async function Fi(e){let{config:t,environment:r,driver:n,sha:s,runtime:i,tarballForSite:o,logger:a=Qt}=e,c=t.project.slug,l=e.cwd??process.cwd(),p=e.managementDashboard!==!1,d=qt(t);if(p)co(t,{cwd:l,logger:{info:a.info,warn:a.warn}});let m=!p||d?[]:lo(t);if(p&&e.rpxConfig&&e.rpxConfig!==t&&!qt(e.rpxConfig))co(e.rpxConfig,{cwd:l,logger:{info:()=>{},warn:()=>{}}});if(p&&!await Ol(n,e,lo(t),a))return!1;let f=null,h=new Map;if(m.length>0)if(f=Ts(t.sites?.[m[0]],{cwd:l,slug:c,sha:s,siteName:m[0],logger:{info:a.info,warn:a.warn}}),!f){a.warn("Management dashboard: no artifact available — skipping dashboard site(s) for this deploy.");for(let T of m)if(t.sites)delete t.sites[T]}else for(let T of m){if(T===m[0]){h.set(T,f);continue}try{let y=xl(Pl(),`${c}-${T}-${s}.tar.gz`);Cl(f,y),h.set(T,y)}catch{h.set(T,f)}}let _=t.sites||{},w=Object.entries(_).filter(([T,y])=>{if(!y)return!1;let I=P(y);if(I==="bucket")return a.warn(`Site '${T}' targets a bucket — skipping (handled by the static-site path, not compute).`),!1;if(I==="redirect")return!1;if(I==="proxy")return!1;return!0});if(w.length===0)return vn(e);if(await Dl(n,e,a),!await Il(n,e,a))return!1;if(!await Al(n,e,a))return!1;let b=(T)=>h.get(T)??o(T);for(let[T,y]of w){a.step(`Deploying site: ${T}`);let I=ai(y)?void 0:b(T),R=await no(n,{config:t,environment:r,siteName:T,site:y,slug:c,sha:s,runtime:i,localTarballPath:I},a);if(!R.success){if(a.error(`Deploy of '${T}' failed: ${R.error||"unknown error"}`),R.perInstance)for(let O of R.perInstance)a.error(` ${O.instanceId}: ${O.status}${O.error?` — ${O.error}`:""}`);return!1}if(a.success(`Deployed ${c}/${T}@${s} to ${R.instanceCount} target(s)`),R.perInstance)for(let O of R.perInstance)a.info(` ✓ ${O.instanceId}: ${O.status}`)}if(!await vn(e))return!1;return!0}async function Ll(e,t,r){let n=Oi(e);if(!n||n.tls==="off")return n;let s=await Ie(t,r),i=s?.provider==="ssh"?s.lanIp:void 0;return i?{...n,ip:i}:n}async function vn(e){let{config:t,environment:r,driver:n,logger:s=Qt}=e,i=e.rpxConfig??t,o=i.infrastructure?.compute?.proxy??t.infrastructure?.compute?.proxy;if(o?.engine!=="rpx")return!0;let a=i.sites||{},c=t.project.slug,l=E(t,r),p=await n.findComputeTargets({slug:c,environment:r,role:"lb",stackName:l});if(p.length>0){let S=(await n.findComputeTargets({slug:c,environment:r,role:"app",stackName:l})).map((I)=>({privateIp:I.privateIp,publicIp:I.publicIp})),T=Fe(a,S,{proxy:o,slug:c});if(T.proxies.length===0)return s.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;s.step(`Reloading the load balancer's rpx gateway with ${T.proxies.length} route(s)...`);let y=await n.runRemoteDeploy({targets:p,commands:He({config:T,slug:c,preserveManagementDashboardRoutes:e.managementDashboard===!1}),comment:`ts-cloud rpx gateway reload ${c}`,tags:{Project:c,Environment:r,Role:"lb"}});if(!y.success)return s.error(`rpx gateway reload failed: ${y.error||"unknown error"}`),!1;return s.success(`rpx gateway reloaded on ${y.instanceCount} load balancer(s)`),!0}let d=await Ll(t,l,e.cwd),m=ye(a,{proxy:o,slug:c,lan:d});if(m.proxies.length===0)return s.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;let f=await n.findComputeTargets({slug:c,environment:r,role:"app",stackName:l});if(f.length===0)return s.warn("rpx gateway: no compute targets found — skipping gateway reload."),!0;let h=Boolean(t.cloud?.attachTo);if(h&&(o.version||o.tlsxVersion))s.warn(`rpx gateway: ignoring proxy.version/tlsxVersion — this project attaches to '${t.cloud?.attachTo}' and the gateway belongs to that box's owner.`);s.step(`Reloading rpx gateway with ${m.proxies.length} route(s)...`);let _=de({proxy:o,config:m,slug:c,tenant:h,profile:Ln(t),preserveManagementDashboardRoutes:e.managementDashboard===!1}),w=await n.runRemoteDeploy({targets:f,commands:_,comment:`ts-cloud rpx gateway reload ${c}`,tags:{Project:c,Environment:r,Role:"app"}});if(!w.success)return s.error(`rpx gateway reload failed: ${w.error||"unknown error"}`),!1;return s.success(`rpx gateway reloaded on ${w.instanceCount} target(s)`),!0}async function ji(e){let{config:t,environment:r,driver:n,logger:s=Qt}=e,i=e.rpxConfig??t,o=i.infrastructure?.compute?.proxy??t.infrastructure?.compute?.proxy;if(o?.engine!=="rpx"||!o.onDemandTls)return!0;let a=ye(i.sites||{},{proxy:o,slug:t.project.slug});if(a.proxies.length===0)return!0;let c=wr(a);if(c.length===0)return!0;let l=t.project.slug,p=E(t,r),d="lb",m=await n.findComputeTargets({slug:l,environment:r,role:d,stackName:p});if(m.length===0)d="app",m=await n.findComputeTargets({slug:l,environment:r,role:d,stackName:p});if(m.length===0)return s.warn("rpx TLS: no gateway targets found - skipping certificate issuance."),!0;s.step("Issuing rpx TLS certificates after DNS reconciliation...");let f=c.map((_)=>`test -s ${Rl(`${a.productionCerts.certsDir}/${_}.crt`)}`).join(" && "),h=await n.runRemoteDeploy({targets:m,commands:[`systemctl start ${vr(l)}`,f],comment:`ts-cloud rpx TLS issuance ${l}`,tags:{Project:l,Environment:r,Role:d}});if(!h.success)return s.error(`rpx TLS issuance failed: ${h.error||"unknown error"}`),!1;return s.success(`rpx TLS certificates reconciled on ${h.instanceCount} gateway target(s)`),!0}import{createHash as Hl}from"node:crypto";function _a(e){let t=bn(e.name),r=wn(e.publicKey),n=kl([...e.existingKeys??[],{name:t,publicKey:r}]);return io(e.configText,n)}function xa(e){let t=bn(e.name),r=(e.existingKeys??[]).filter((n)=>n.name!==t);if((e.existingKeys??[]).length===r.length)throw Error(`SSH key '${t}' does not exist in compute.sshKeys`);return io(e.configText,r)}function Dt(e=[]){return e.map((t)=>({name:t.name,publicKey:t.publicKey,type:Ul(t.publicKey),fingerprint:Ml(t.publicKey),added:"configured"}))}function io(e,t){let r=Fl(e,"compute"),n=Nl(t),s=zl(e,r.start,r.end,"sshKeys");if(s){let c=s.propertyStart;while(c>0&&e[c-1]!==`
557
+ `)}`,"if [ -e /run/ts-cloud-dashboard-routes-changed ]; then"," systemctl restart rpx-gateway.service"," rm -f /run/ts-cloud-dashboard-routes-changed","fi"]:[];return["set -euo pipefail",`TS_CLOUD_DASHBOARD_PREFIX=${Jt(s)}`,`TS_CLOUD_DASHBOARD_SERVER_OWNER=${r?"1":"0"}`,`TS_CLOUD_DASHBOARD_DESIRED=${Jt(` ${i.join(" ")} `)}`,"for TS_CLOUD_UNIT_FILE in /etc/systemd/system/*.service; do",' [ -e "$TS_CLOUD_UNIT_FILE" ] || continue',' TS_CLOUD_UNIT=$(basename "$TS_CLOUD_UNIT_FILE")',' case "$TS_CLOUD_UNIT" in'," *-dashboard-*.service)",' if [ "$TS_CLOUD_DASHBOARD_SERVER_OWNER" != 1 ]; then',' case "$TS_CLOUD_UNIT" in "$TS_CLOUD_DASHBOARD_PREFIX"*.service) ;; *) continue ;; esac'," fi",' case "$TS_CLOUD_DASHBOARD_DESIRED" in',' *" $TS_CLOUD_UNIT "*) ;;'," *)",' systemctl disable --now "$TS_CLOUD_UNIT" 2>/dev/null || true',' rm -f "$TS_CLOUD_UNIT_FILE"'," ;;"," esac"," ;;"," esac","done","systemctl daemon-reload","systemctl reset-failed",...o]}async function Ol(e,t,r,n){let{config:s,environment:i}=t,o=s.project.slug,a=E(s,i),c=await e.findComputeTargets({slug:o,environment:i,role:"app",stackName:a});if(c.length===0)return!0;let l=await e.runRemoteDeploy({targets:c,commands:El(o,r,!s.cloud?.attachTo,r.map((p)=>s.sites?.[p]?.domain).filter((p)=>typeof p==="string")),comment:`ts-cloud reconcile management dashboard ${o}`,tags:{Project:o,Environment:i,Role:"app"}});if(!l.success)return n.error(`Management dashboard reconciliation failed: ${l.error||"unknown error"}`),!1;return!0}async function Dl(e,t,r){let{config:n}=t,s=n.cloud?.attachTo;if(!s||!e.listReachableResources)return;let i;try{i=await e.listReachableResources()}catch(c){r.warn(`Could not determine this credential's reach: ${c instanceof Error?c.message:String(c)}`);return}let o=Ti(i,{ownerSlug:s,selfSlug:n.project.slug}),a=pn(o)>0;for(let c of Ci(o,{ownerSlug:s,selfSlug:n.project.slug}))if(a)r.warn(c);else r.info(c)}async function Il(e,t,r){let{config:n,environment:s}=t,i=n.cloud?.attachTo;if(!i)return!0;let o=Xi(n.infrastructure?.compute?.managedServices);if(o.length===0)return!0;let a=n.project.slug,c=E(n,s),l=await e.findComputeTargets({slug:a,environment:s,role:"app",stackName:c});if(l.length===0)return!0;let p=await e.runRemoteDeploy({targets:l,commands:Yi(o),comment:`ts-cloud preflight managed services ${a}`,tags:{Project:a,Environment:s,Role:"app"}});if(!p.success)return r.warn(`Could not check '${i}' for the declared services: ${p.error||"unknown error"}`),!0;let d=new Set;for(let m of p.perInstance)for(let f of Ji(m.output,o))d.add(f);if(d.size===0)return!0;return r.error(Qi([...d],i,l[0]?.publicIp)),!1}async function Al(e,t,r){let{config:n,environment:s}=t;if(!n.cloud?.attachTo)return!0;let i=n.infrastructure?.compute,o=C(n),a=bt(o,i?.managedServices??{});if(a.length===0)return!0;let c=n.project.slug,l=E(n,s),p=await e.findComputeTargets({slug:c,environment:s,role:"app",stackName:l});if(p.length===0)return!0;r.step(`Ensuring database '${o?.name}' + role exist on the shared box...`);let d=await e.runRemoteDeploy({targets:p,commands:a,comment:`ts-cloud ensure database ${c}/${o?.name}`,tags:{Project:c,Environment:s,Role:"app"}});if(!d.success)return r.error(`Ensuring database '${o?.name}' failed: ${d.error||"unknown error"}`),!1;return r.success(`Database '${o?.name}' is ready on ${d.instanceCount} target(s)`),!0}async function Fi(e){let{config:t,environment:r,driver:n,sha:s,runtime:i,tarballForSite:o,logger:a=Qt}=e,c=t.project.slug,l=e.cwd??process.cwd(),p=e.managementDashboard!==!1,d=qt(t);if(p)co(t,{cwd:l,logger:{info:a.info,warn:a.warn}});let m=!p||d?[]:lo(t);if(p&&e.rpxConfig&&e.rpxConfig!==t&&!qt(e.rpxConfig))co(e.rpxConfig,{cwd:l,logger:{info:()=>{},warn:()=>{}}});if(p&&!await Ol(n,e,lo(t),a))return!1;let f=null,h=new Map;if(m.length>0)if(f=Ts(t.sites?.[m[0]],{cwd:l,slug:c,sha:s,siteName:m[0],logger:{info:a.info,warn:a.warn}}),!f){a.warn("Management dashboard: no artifact available — skipping dashboard site(s) for this deploy.");for(let T of m)if(t.sites)delete t.sites[T]}else for(let T of m){if(T===m[0]){h.set(T,f);continue}try{let y=xl(Pl(),`${c}-${T}-${s}.tar.gz`);Cl(f,y),h.set(T,y)}catch{h.set(T,f)}}let _=t.sites||{},w=Object.entries(_).filter(([T,y])=>{if(!y)return!1;let I=P(y);if(I==="bucket")return a.warn(`Site '${T}' targets a bucket — skipping (handled by the static-site path, not compute).`),!1;if(I==="redirect")return!1;if(I==="proxy")return!1;return!0});if(w.length===0)return vn(e);if(await Dl(n,e,a),!await Il(n,e,a))return!1;if(!await Al(n,e,a))return!1;let b=(T)=>h.get(T)??o(T);for(let[T,y]of w){a.step(`Deploying site: ${T}`);let I=ai(y)?void 0:b(T),x=await no(n,{config:t,environment:r,siteName:T,site:y,slug:c,sha:s,runtime:i,localTarballPath:I},a);if(!x.success){if(a.error(`Deploy of '${T}' failed: ${x.error||"unknown error"}`),x.perInstance)for(let R of x.perInstance)a.error(` ${R.instanceId}: ${R.status}${R.error?` — ${R.error}`:""}`);return!1}if(a.success(`Deployed ${c}/${T}@${s} to ${x.instanceCount} target(s)`),x.perInstance)for(let R of x.perInstance)a.info(` ✓ ${R.instanceId}: ${R.status}`)}if(!await vn(e))return!1;return!0}async function Ll(e,t,r){let n=Oi(e);if(!n||n.tls==="off")return n;let s=await Ie(t,r),i=s?.provider==="ssh"?s.lanIp:void 0;return i?{...n,ip:i}:n}async function vn(e){let{config:t,environment:r,driver:n,logger:s=Qt}=e,i=e.rpxConfig??t,o=i.infrastructure?.compute?.proxy??t.infrastructure?.compute?.proxy;if(o?.engine!=="rpx")return!0;let a=i.sites||{},c=t.project.slug,l=E(t,r),p=await n.findComputeTargets({slug:c,environment:r,role:"lb",stackName:l});if(p.length>0){let S=(await n.findComputeTargets({slug:c,environment:r,role:"app",stackName:l})).map((I)=>({privateIp:I.privateIp,publicIp:I.publicIp})),T=Fe(a,S,{proxy:o,slug:c});if(T.proxies.length===0)return s.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;s.step(`Reloading the load balancer's rpx gateway with ${T.proxies.length} route(s)...`);let y=await n.runRemoteDeploy({targets:p,commands:He({config:T,slug:c,preserveManagementDashboardRoutes:e.managementDashboard===!1}),comment:`ts-cloud rpx gateway reload ${c}`,tags:{Project:c,Environment:r,Role:"lb"}});if(!y.success)return s.error(`rpx gateway reload failed: ${y.error||"unknown error"}`),!1;return s.success(`rpx gateway reloaded on ${y.instanceCount} load balancer(s)`),!0}let d=await Ll(t,l,e.cwd),m=ye(a,{proxy:o,slug:c,lan:d});if(m.proxies.length===0)return s.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;let f=await n.findComputeTargets({slug:c,environment:r,role:"app",stackName:l});if(f.length===0)return s.warn("rpx gateway: no compute targets found — skipping gateway reload."),!0;let h=Boolean(t.cloud?.attachTo);if(h&&(o.version||o.tlsxVersion))s.warn(`rpx gateway: ignoring proxy.version/tlsxVersion — this project attaches to '${t.cloud?.attachTo}' and the gateway belongs to that box's owner.`);s.step(`Reloading rpx gateway with ${m.proxies.length} route(s)...`);let _=de({proxy:o,config:m,slug:c,tenant:h,profile:Ln(t),preserveManagementDashboardRoutes:e.managementDashboard===!1}),w=await n.runRemoteDeploy({targets:f,commands:_,comment:`ts-cloud rpx gateway reload ${c}`,tags:{Project:c,Environment:r,Role:"app"}});if(!w.success)return s.error(`rpx gateway reload failed: ${w.error||"unknown error"}`),!1;return s.success(`rpx gateway reloaded on ${w.instanceCount} target(s)`),!0}async function ji(e){let{config:t,environment:r,driver:n,logger:s=Qt}=e,i=e.rpxConfig??t,o=i.infrastructure?.compute?.proxy??t.infrastructure?.compute?.proxy;if(o?.engine!=="rpx"||!o.onDemandTls)return!0;let a=ye(i.sites||{},{proxy:o,slug:t.project.slug});if(a.proxies.length===0)return!0;let c=wr(a);if(c.length===0)return!0;let l=t.project.slug,p=E(t,r),d="lb",m=await n.findComputeTargets({slug:l,environment:r,role:d,stackName:p});if(m.length===0)d="app",m=await n.findComputeTargets({slug:l,environment:r,role:d,stackName:p});if(m.length===0)return s.warn("rpx TLS: no gateway targets found - skipping certificate issuance."),!0;s.step("Issuing rpx TLS certificates after DNS reconciliation...");let f=c.map((_)=>`test -s ${Rl(`${a.productionCerts.certsDir}/${_}.crt`)}`).join(" && "),h=await n.runRemoteDeploy({targets:m,commands:[`systemctl start ${vr(l)}`,f],comment:`ts-cloud rpx TLS issuance ${l}`,tags:{Project:l,Environment:r,Role:d}});if(!h.success)return s.error(`rpx TLS issuance failed: ${h.error||"unknown error"}`),!1;return s.success(`rpx TLS certificates reconciled on ${h.instanceCount} gateway target(s)`),!0}import{createHash as Hl}from"node:crypto";function _a(e){let t=bn(e.name),r=wn(e.publicKey),n=kl([...e.existingKeys??[],{name:t,publicKey:r}]);return io(e.configText,n)}function xa(e){let t=bn(e.name),r=(e.existingKeys??[]).filter((n)=>n.name!==t);if((e.existingKeys??[]).length===r.length)throw Error(`SSH key '${t}' does not exist in compute.sshKeys`);return io(e.configText,r)}function Dt(e=[]){return e.map((t)=>({name:t.name,publicKey:t.publicKey,type:Ul(t.publicKey),fingerprint:Ml(t.publicKey),added:"configured"}))}function io(e,t){let r=Fl(e,"compute"),n=Nl(t),s=zl(e,r.start,r.end,"sshKeys");if(s){let c=s.propertyStart;while(c>0&&e[c-1]!==`
558
558
  `&&/\s/.test(e[c-1]))c--;return`${e.slice(0,c)}${n}${e.slice(s.end+1)}`}let i=e.slice(0,r.end).trimEnd(),o=e.slice(r.end),a=i.endsWith(",")||i.endsWith("{")?"":",";return`${i}${a}
559
559
  ${n},
560
560
  ${o}`}function Nl(e){if(e.length===0)return" sshKeys: []";return` sshKeys: [
@@ -720,5 +720,5 @@ EOF`,'echo "DISKPCT=${DISKPCT:-0}"','echo "DISKUSEDG=${DISKUSEDG:-0}"','echo "DI
720
720
  `)){let n=r.trim();if(n.startsWith("DISCOVERED_SITE="))try{let s=JSON.parse(Buffer.from(n.slice(16),"base64").toString("utf8"));if(s?.domain&&s?.route)t.discoveredSites.push(s)}catch{}else if(n.startsWith("SVC=")){let[,s,i,o,a,c]=/^SVC=([^=]+)=([^=]+)(?:=([^=]*)(?:=([^=]*)(?:=(.*))?)?)?$/.exec(n)??[];if(s)t.services.push({name:s,status:i,memBytes:Number(o||0),enabled:a||q,since:c||q})}else{let s=n.indexOf("=");if(s>0)t[n.slice(0,s)]=n.slice(s+1)}}return t}function ao(e){let t=e.infrastructure?.compute,r=[];if(t?.webServer==="rpx"||t?.proxy?.engine==="rpx")r.push({name:"rpx-gateway",status:"configured"});else if(t?.webServer==="nginx"||t?.webServer==null)r.push({name:"ts-cloud-nginx",status:"configured"});let n=t?.php?.versions??(t?.runtime==="php"?["8.3"]:[]);for(let o of n)r.push({name:`php${o}-fpm`,status:"configured"});let s=t?.managedServices??{},i=[["mysql","mysql"],["mariadb","mariadb"],["postgres","postgresql"],["redis","redis"],["memcached","memcached"],["meilisearch","meilisearch"]];for(let[o,a]of i)if(s[o])r.push({name:a,status:"configured"});return r}function ql(e){let t=e.infrastructure?.compute?.backups,r=!!t?.enabled,n=t?.schedule??"0 2 * * *";return{enabled:r,schedule:n,destination:r?t?.bucket??"local":"off",retention:r?t?.retentionCount??5:0,last:r?"pending first run":"not configured",size:r?q:"0 MB"}}function uo(e){return e.infrastructure?.compute?.provider??e.cloud?.provider??e.provider??"aws"}function Xl(e){if(uo(e)==="hetzner")return Br(e);return e.project.region??"us-east-1"}function Yl(e){let t=e.infrastructure?.compute?.monitoring,r=Number(typeof t==="object"?t?.alerts?.bandwidthTb??0:0);return Number.isFinite(r)&&r>0?Math.round(r*1000000000000):0}function Jl(e,t){let r=Xe(E(e,t));if(!Bl(r))return null;try{return JSON.parse(Kl(r,"utf8"))}catch{return null}}function Ql(e){let t=e.sites??{},r=[];for(let[n,s]of Object.entries(t)){let i=s.queues??s.workers;if(Array.isArray(i)){for(let o of i)if(typeof o==="string")r.push({name:`${n}:${o}`,site:n,processes:1,status:"configured"});else if(o?.name)r.push({name:`${n}:${o.name}`,site:n,processes:o.processes??1,status:"configured"})}}return r}function po(e){if(!e||e==="")return"/";return e.startsWith("/")?e:`/${e}`}function Zl(e){let t=po(e.path);if(!e.domain)return{route:"internal"};return{route:t==="/"?e.domain:`${e.domain}${t}`,href:`https://${e.domain}${t==="/"?"":t}`}}function oo(e,t){let r=P(t);if(r==="redirect")return"redirect";if(r==="proxy")return"proxy";let n=String(t.build??"").toLowerCase(),s=String(t.start??"").toLowerCase();if(e==="main"||s.includes("buddy/src/cli.ts serve"))return"stacks";if(e==="api"||s.includes("/serve/api"))return"api";if(n.includes("buildblog"))return"bunpress blog";if(n.includes("bunpress"))return"bunpress";if(n.includes("site:build")||n.includes("stx"))return"stx static";if(r==="server-static")return t.spa?"spa":"static";if(r==="server-app")return"app";if(r==="server-php")return t.type??"php";return"bucket"}function eu(e){let t=P(e);if(t==="redirect"||t==="proxy")return"—";let r=`${e.start??""} ${e.build??""}`.toLowerCase();if(t==="server-static")return r.includes("bunpress")||r.includes("bun ")||r.includes("bunx ")?"static/bun":"static";if(t==="server-app")return r.includes("bun")?"bun":"node";if(t==="server-php")return`php ${e.php??e.phpVersion??"8.3"}`;return"static"}function tu(e){let t=P(e);if(t==="redirect")return"redirect";if(t==="proxy")return"proxy";if(t==="server-app")return"service";if(t==="server-static")return"server static";if(t==="server-php")return"php release";return"bucket"}function ru(e){let t=new Map;return Object.entries(e.sites??{}).map(([r,n])=>{let s=po(n.path),{route:i,href:o}=Zl(n),a=n.domain?`${n.domain}${s}`:"",c=a?t.get(a):void 0;if(a&&!c)t.set(a,r);return{name:r,route:i,href:o,domain:n.domain??"internal",path:s,kind:oo(r,n),type:oo(r,n),runtime:eu(n),deploy:tu(n),tls:n.domain?n.ssl===!1?"http":"https":"loopback",ssl:n.domain?n.ssl!==!1:!1,status:c?"shadowed":"live",shadowedBy:c,lastDeploy:q}})}function nu(e,t,r){let n=new Map(e.map((s)=>[String(s.route),{...s,project:r,managedBy:"owner"}]));for(let s of t){let i=n.get(s.route),o=i?.name??`${s.project}:${s.name}`;n.set(s.route,{...i,...s,name:o,kind:i?.kind??s.kind,type:i?.type??s.kind,runtime:i?.runtime??s.runtime,deploy:i?.deploy??s.deploy,root:i?.root??s.root,branch:i?.branch??s.branch,managedBy:s.project===r?"owner":"attached"})}return[...n.values()].sort((s,i)=>{if(s.managedBy!==i.managedBy)return s.managedBy==="owner"?-1:1;return String(s.route).localeCompare(String(i.route))})}function _n(e){return`'${e.replaceAll("'","'\\''")}'`}function mo(e){return e.replace(/[\\&/]/g,"\\$&")}function su(e,t){if(e.length===0)return["true"];return["set +e",...e.map((r)=>{let n=_n(`${J(t,r)}/.ts-cloud/deploy-history.log`),s=mo(r);return`TS_CLOUD_HISTORY=${n}; { [ -f "$TS_CLOUD_HISTORY" ] && tail -n 24 "$TS_CLOUD_HISTORY" | sed "s/^/DEPLOY=${s}\\t/"; } || true`}),"true"]}function go(e){return[...new Set(Object.values(e.sites??{}).map((t)=>t.domain).filter((t)=>typeof t==="string"&&t.length>0))]}function iu(e){return["set +e",'if command -v ss >/dev/null 2>&1; then ss -H -lntup 2>/dev/null | while read -r proto _state _recv _send local _peer rest; do [ -n "$proto" ] && [ -n "$local" ] && printf "PORT=%s\\t%s\\t%s\\n" "$proto" "$local" "$rest"; done; fi','if command -v ufw >/dev/null 2>&1; then ufw status numbered 2>/dev/null | sed "s/^/FIREWALL=/"; else echo "FIREWALL=ufw unavailable"; fi','journalctl _COMM=sshd --no-pager -n 30 -o short-iso 2>/dev/null | sed "s/^/AUTH=/" || true',...go(e).map((r)=>`TS_CLOUD_DOMAIN=${_n(r)}; TS_CLOUD_EXPIRY=$(echo | timeout 8 openssl s_client -servername "$TS_CLOUD_DOMAIN" -connect "$TS_CLOUD_DOMAIN:443" 2>/dev/null | openssl x509 -noout -enddate 2>/dev/null | cut -d= -f2-); [ -n "$TS_CLOUD_EXPIRY" ] && printf "CERT=%s\\t%s\\n" "$TS_CLOUD_DOMAIN" "$TS_CLOUD_EXPIRY" || printf "CERT=%s\\tunavailable\\n" "$TS_CLOUD_DOMAIN"`),"true"]}function ou(e){let t=new Map,r=(i,o)=>{if(i&&o&&!t.has(o))t.set(o,{pattern:i,label:o})},n=e.infrastructure?.compute,s=e.project.slug;if(n?.webServer==="rpx"||n?.proxy?.engine==="rpx")r("rpx-gateway","rpx-gateway");else r("nginx","nginx");for(let i of ao(e))r(i.name,i.name);for(let[i,o]of Object.entries(e.sites??{})){if(P(o)!=="server-app")continue;if(r(`${s}-${i}`,`${s}-${i}`),Array.isArray(o.queues??o.workers)&&(o.queues??o.workers).length)r(`${s}-${i}-queue-*`,`${s}-${i}-queues`);if(Array.isArray(o.daemons)&&o.daemons.length)r(`${s}-${i}-daemon-*`,`${s}-${i}-daemons`)}return[...t.values()]}function au(e){let t=ou(e);if(t.length===0)return["true"];return["set +e",...t.map((r)=>{let n=_n(r.pattern),s=mo(r.label);return`journalctl -u ${n} --no-pager -n 150 -o short-iso 2>/dev/null | sed "s/^/LOG=${s}\\t/" || true`}),'[ -f /var/log/ts-cloud-backup.log ] && tail -n 60 /var/log/ts-cloud-backup.log 2>/dev/null | sed "s/^/LOG=backups\\t/" || true',"true"]}function Tn(e){let t=new Date(e);if(Number.isNaN(t.getTime()))return e||q;let r=Math.max(0,Math.round((Date.now()-t.getTime())/1000));if(r<60)return`${r}s ago`;let n=Math.round(r/60);if(n<60)return`${n}m ago`;let s=Math.round(n/60);if(s<48)return`${s}h ago`;return`${Math.round(s/24)}d ago`}function ho(e){if(/(?:error|failed|panic|fatal|exception|denied|unhealthy)/i.test(e))return"error";if(/(?:warn|warning|retry|restart|deprecated|timeout)/i.test(e))return"warn";return"info"}function cu(e){let t=[];for(let r of e.split(`
721
721
  `)){let n=r.trim();if(!n.startsWith("LOG="))continue;let s=n.indexOf("\t");if(s<0)continue;let i=n.slice(4,s),o=n.slice(s+1),a=/^(\d{4}-\d{2}-\d{2}T[^\s]+)\s+(\S+)\s+(.*)$/.exec(o),c=a?.[1]??"",l=a?.[2]??"",p=(a?.[3]??o).trim();if(!p)continue;t.push({source:i,timestamp:c,when:c?Tn(c):q,host:l,message:p,level:ho(p)})}return t.sort((r,n)=>String(n.timestamp).localeCompare(String(r.timestamp))).slice(0,600)}function wo(e){if(/^(?:127\.|localhost:|\[?::1\]?)/.test(e))return"loopback";if(/^(?:10\.|192\.168\.|172\.(?:1[6-9]|2\d|3[01])\.|169\.254\.|\[?f[cd][0-9a-f:])/i.test(e))return"private";return"public"}function lu(e){if(wo(e)!=="public")return"ok";if(/:(?:22|80|443)$/.test(e)||/^\*:(?:22|80|443)$/.test(e))return"ok";return"warn"}function uu(e){if(e==null)return"warn";if(e<8)return"bad";if(e<30)return"warn";return"ok"}function pu(e){let t=[],r=[],n=[],s=[];for(let a of e.split(`
722
722
  `)){let c=a.trim();if(c.startsWith("PORT=")){let[l="",p="",d=""]=c.slice(5).split("\t");if(l&&p)t.push({proto:l,listen:p,processName:d||q,exposure:wo(p),tone:lu(p)})}else if(c.startsWith("FIREWALL=")){let l=c.slice(9).trim();if(l)r.push(l)}else if(c.startsWith("AUTH=")){let l=c.slice(5),p=/^(\d{4}-\d{2}-\d{2}T[^\s]+)\s+(\S+)\s+(.*)$/.exec(l),d=(p?.[3]??l).trim();if(d)n.push({timestamp:p?.[1]??"",when:p?.[1]?Tn(p[1]):q,host:p?.[2]??"",message:d,level:ho(d)})}else if(c.startsWith("CERT=")){let[l="",p=""]=c.slice(5).split("\t");if(!l)continue;let d=new Date(p),m=Number.isNaN(d.getTime())?null:Math.ceil((d.getTime()-Date.now())/86400000);s.push({domain:l,expires:Number.isNaN(d.getTime())?p||q:d.toISOString().slice(0,10),daysRemaining:m,status:uu(m)})}}let i=r.some((a)=>/Status:\s*active/i.test(a)),o=r.some((a)=>/unavailable/i.test(a));return{ports:t.slice(0,80),firewall:{status:i?"active":o?"unavailable":"inactive",summary:i?"ufw active":o?"ufw unavailable":"ufw inactive or not configured",rules:r.filter((a)=>a&&!/^Status:/i.test(a)).slice(0,60)},tlsCertificates:s,authEvents:n.sort((a,c)=>String(c.timestamp).localeCompare(String(a.timestamp))).slice(0,30)}}function $n(e){let r=e.infrastructure?.compute?.firewall??{},n=[...new Set([22,80,443,...r.allowedPorts??[]])],s=go(e);return{ports:n.map((i)=>({proto:"tcp",listen:`0.0.0.0:${i}`,processName:"configured firewall",exposure:"public",tone:[22,80,443].includes(Number(i))?"ok":"warn"})),firewall:{status:r.enabled===!1?"disabled":"configured",summary:r.enabled===!1?"host firewall disabled in config":"host firewall configured declaratively",rules:n.map((i)=>`ALLOW ${i}/tcp`)},tlsCertificates:s.map((i)=>({domain:i,expires:q,daysRemaining:null,status:"warn"})),authEvents:[]}}function _o(e,t){let r=t.security??$n(e),n=!!t._serverReachable&&!t.metricsUnavailable,s=t.sites??[],i=s.filter((l)=>l.status==="shadowed"),o=(t.services??[]).filter((l)=>["failed","stopped"].includes(l.status)),a=(r.tlsCertificates??[]).filter((l)=>l.status!=="ok"),c=t.sshKeys??[];return[{name:"Live server probe",status:n?"pass":"warn",detail:n?"Metrics and remote checks are coming from the compute box.":"The dashboard is rendering config/state data until the box probe succeeds."},{name:"Managed services",status:o.length?"fail":"pass",detail:o.length?`${o.length} service(s) need attention.`:`${(t.services??[]).length} service(s) reported healthy or configured.`},{name:"Route conflicts",status:i.length?"warn":"pass",detail:i.length?`${i.map((l)=>l.name).join(", ")} is shadowed by an earlier route.`:`${s.length} site route(s) are unshadowed.`},{name:"SSH access",status:c.length?"pass":"warn",detail:c.length?`${c.length} declarative authorized key(s) configured.`:"No declarative SSH keys are configured."},{name:"Firewall",status:["active","configured"].includes(r.firewall?.status)?"pass":"warn",detail:r.firewall?.summary??"Firewall status unavailable."},{name:"TLS certificates",status:a.length?"warn":"pass",detail:a.length?`${a.length} certificate(s) need renewal visibility.`:`${(r.tlsCertificates??[]).length} certificate(s) look healthy.`}]}function $o(e){let t=[];for(let r of e.serverDeploymentsDetail??e.serverDeployments??[])t.push({type:"deploy",tone:r.status==="failed"?"bad":"ok",title:`${r.site} deployed ${r.sha}`,detail:`${r.branch} · ${r.status}`,when:r.when,timestamp:r.timestamp});for(let r of e.serverLogs??[])if(r.level==="error"||r.level==="warn")t.push({type:"log",tone:r.level==="error"?"bad":"warn",title:`${r.source} ${r.level}`,detail:r.message,when:r.when,timestamp:r.timestamp});for(let r of e.sshKeys??[])t.push({type:"ssh",tone:"ok",title:`${r.name} authorized`,detail:r.fingerprint,when:r.added??q,timestamp:""});return t.sort((r,n)=>String(n.timestamp).localeCompare(String(r.timestamp))).slice(0,80)}function du(e,t={}){let r=[];for(let n of e.split(`
723
- `)){let s=n.trim();if(!s.startsWith("DEPLOY="))continue;let i=s.split("\t"),o=i[0]?.replace(/^DEPLOY=/,"")??"",[a,c,l,p,d]=i.slice(1);if(!o||!a||!c)continue;let m=t[o]??{},f=P(m),h=(l||c).slice(0,7);r.push({sha:h,release:c,commit:l||c,site:o,branch:m.branch??(f==="server-static"?"build artifact":"main"),status:p||"unknown",when:Tn(a),timestamp:a,took:"-",by:"ts-cloud",rc:d?.replace(/^rc=/,"")??"",steps:f==="server-static"?["upload artifact","publish static files"]:["upload artifact","restart service"]})}return r.sort((n,s)=>String(s.timestamp).localeCompare(String(n.timestamp)))}function mu(e,t){let r=Jl(e,t),n=ao(e),s=ru(e),i=Math.max(1,Number(e.infrastructure?.compute?.disk?.size??1)),o={server:{name:r?.serverName??`${e.project.slug}-${t}-app`,provider:r?.provider??uo(e),region:Xl(e),ip:r?.publicIp??q,os:"Linux",uptime:q,probeStatus:"unavailable"},systemMetrics:{load:0,load5:0,load15:0,cpuUsedPct:0,cpus:Math.max(1,Number(e.infrastructure?.compute?.instances??1)),memUsedMb:0,memTotalMb:0,memAvailableMb:0,memCacheMb:0,swapUsedMb:0,swapTotalMb:0,diskUsedPct:0,diskUsedGb:0,diskTotalGb:i,inodeUsedPct:0,networkRxBytes:0,networkTxBytes:0,networkRxBytesPerSec:0,networkTxBytesPerSec:0,networkRxBytesToday:0,networkTxBytesToday:0,networkRxBytesMonth:0,networkTxBytesMonth:0,networkMonthKey:"",processes:0,uptimeSeconds:0},metricsUnavailable:!0,bandwidthBudgetBytes:Yl(e),services:n,servicesDetail:n.map((a)=>({...a,since:q,memMb:0,auto:!0})),backup:ql(e),backupHistory:[],workers:Ql(e),serverScheduler:{enabled:!1,lastRun:"not configured"},serverDeployments:[],serverDeploymentsDetail:[],deploymentsEmptyReason:"No deployment history has been recorded yet. Future server deploys will write /var/www/<site>/.ts-cloud/deploy-history.log.",serverLogs:[],serverLogsEmptyReason:"Live server logs are unavailable until the dashboard can reach the compute box.",security:$n(e),securityEmptyReason:"Live security checks are unavailable until the dashboard can reach the compute box.",sites:s,sitesDetail:s.map((a)=>{let c=e.sites?.[a.name]??{},l=P(c);return{...a,root:l==="server-static"?J(e.project.slug,a.name):`${J(e.project.slug,a.name)}/current`,branch:l==="server-static"?"build artifact":"main",build:c.build,php:c.php??c.phpVersion,aliases:Array.isArray(c.aliases)?c.aliases:[],redirects:c.redirects&&typeof c.redirects==="object"?c.redirects:{},envKeys:Object.keys(c.env??c.environment??{})}}),siteHealth:[],sshKeys:Dt(e.infrastructure?.compute?.sshKeys??[]),_serverReachable:!1,_metricsStatus:"unavailable"};return o.diagnostics=_o(e,o),o.activity=$o(o),o.topology=Wr(o,{project:e.project.name,environment:t}),o}async function Jn(e,t,r={}){if(!e.infrastructure?.compute)return null;let n=null;try{n=x({config:e})}catch{n=null}let s=null,i=0,o=[];if(n)try{if(o=await n.findComputeTargets({slug:e.project.slug,environment:t,role:"app"}),i=o.length,o.length){let d=(await n.runRemoteDeploy({targets:[o[0]],commands:Gl({includeServices:!r.telemetryOnly,includeSites:r.includeSiteHealth!==!1,projectFilter:e.cloud?.attachTo?e.project.slug:void 0}),comment:`ts-cloud dashboard:build ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output;if(d)s=Vl(d)}}catch{}let a=mu(e,t),c=(p,d=0)=>{let m=Number(p);return Number.isFinite(m)?m:d};if(a.server.os=s?.OS||a.server.os,a.server.uptime=s?.UPTIME||a.server.uptime,s){if(a.server.probeStatus="live",a.metricsUnavailable=!1,a._metricsStatus="live",a.systemMetrics={load:c(s.LOAD),load5:c(s.LOAD5),load15:c(s.LOAD15),cpuUsedPct:c(s.CPUUSED),cpus:c(s.CPUS,1),memUsedMb:c(s.MEMUSED),memTotalMb:c(s.MEMTOTAL,1),memAvailableMb:c(s.MEMAVAILABLE),memCacheMb:c(s.MEMCACHE),swapUsedMb:c(s.SWAPUSED),swapTotalMb:c(s.SWAPTOTAL),diskUsedPct:c(s.DISKPCT),diskUsedGb:c(s.DISKUSEDG),diskTotalGb:c(s.DISKTOTG,1),inodeUsedPct:c(s.INODEPCT),networkRxBytes:c(s.NETRX),networkTxBytes:c(s.NETTX),networkRxBytesPerSec:c(s.NETRXRATE),networkTxBytesPerSec:c(s.NETTXRATE),networkRxBytesToday:c(s.NETRXTODAY),networkTxBytesToday:c(s.NETTXTODAY),networkRxBytesMonth:c(s.NETRXMONTH),networkTxBytesMonth:c(s.NETTXMONTH),networkMonthKey:s.NETMONTHKEY||"",processes:c(s.PROCESSES),uptimeSeconds:c(s.UPTIME_SECONDS)},s.services.length){let p=[...new Map(s.services.map((d)=>[d.name,d])).values()];a.services=p.map((d)=>({name:d.name,status:d.status==="active"?"running":d.status})),a.servicesDetail=p.map((d)=>({name:d.name,status:d.status==="active"?"running":d.status,since:d.since&&d.since!==q?d.since:a.server.uptime,memMb:Math.max(0,Math.round(Number(d.memBytes??0)/1024/1024)),auto:d.enabled?!["disabled","static","masked"].includes(d.enabled):!0}))}if(s.discoveredSites.length)a.sitesDetail=nu(a.sitesDetail,s.discoveredSites,e.project.slug),a.sites=a.sitesDetail.map((p)=>({name:p.name,project:p.project,managedBy:p.managedBy,route:p.route,href:p.href,domain:p.domain,path:p.path,kind:p.kind,type:p.type,runtime:p.runtime,deploy:p.deploy,tls:p.tls,status:p.status,httpStatus:p.httpStatus,responseMs:p.responseMs,tlsDaysRemaining:p.tlsDaysRemaining,checkedAt:p.checkedAt})),a.siteHealth=a.sitesDetail.map((p)=>({name:p.name,project:p.project,route:p.route,status:p.status,httpStatus:p.httpStatus,responseMs:p.responseMs,tlsDaysRemaining:p.tlsDaysRemaining,checkedAt:p.checkedAt}))}if(n&&o.length&&!r.telemetryOnly)await Promise.all([(async()=>{try{let p=Object.keys(e.sites??{}),m=(await n.runRemoteDeploy({targets:[o[0]],commands:su(p,e.project.slug),comment:`ts-cloud dashboard:deploy-history ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",f=du(m,e.sites);a.serverDeployments=f.slice(0,5),a.serverDeploymentsDetail=f.slice(0,50),a.deploymentsEmptyReason=f.length?void 0:"No deployment history was found on the server yet. Deploy again to populate this timeline."}catch{a.deploymentsEmptyReason="Deployment history could not be read from the server."}})(),(async()=>{try{let d=(await n.runRemoteDeploy({targets:[o[0]],commands:au(e),comment:`ts-cloud dashboard:server-logs ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",m=cu(d);a.serverLogs=m,a.serverLogsEmptyReason=m.length?void 0:"No recent journal entries were found for the managed server units."}catch{a.serverLogsEmptyReason="Server logs could not be read from the box."}})(),(async()=>{try{let d=(await n.runRemoteDeploy({targets:[o[0]],commands:iu(e),comment:`ts-cloud dashboard:security ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",m=pu(d),f=$n(e);if(!m.ports.length)m.ports=f.ports;if(!m.tlsCertificates.length)m.tlsCertificates=f.tlsCertificates;a.security=m,a.securityEmptyReason=void 0}catch{a.securityEmptyReason="Server security checks could not be read from the box."}})()]);else if(n&&i===0)a.deploymentsEmptyReason="No app server target was found for this environment.";let l=e.infrastructure?.compute?.sshKeys??e.infrastructure?.ssh?.keys??e.infrastructure?.sshKeys;if(Array.isArray(l)&&l.length)a.sshKeys=Dt(l);return a._serverReachable=i>0&&!!s,a.diagnostics=_o(e,a),a.activity=$o(a),a.topology=Wr(a,{project:e.project.name,environment:t}),a}
724
- export{ze,qo,ue,ki,Wn,_i,xi,Fr,$i,Oi,ye,Y,He,Ne,jr,or,qe,sr,Vr,lt,pe,dt,ar,Li,cr,lr,dr,zr,ur,x,Mi,Ui,Gn,Wo,Hr,Go,Ko,ka,Bi,Jo,Xo,Qo,Yo,ut,Zo,qr,Fi,ji,_a,xa,Dt,Kn,Jn};
723
+ `)){let s=n.trim();if(!s.startsWith("DEPLOY="))continue;let i=s.split("\t"),o=i[0]?.replace(/^DEPLOY=/,"")??"",[a,c,l,p,d]=i.slice(1);if(!o||!a||!c)continue;let m=t[o]??{},f=P(m),h=(l||c).slice(0,7);r.push({sha:h,release:c,commit:l||c,site:o,branch:m.branch??(f==="server-static"?"build artifact":"main"),status:p||"unknown",when:Tn(a),timestamp:a,took:"-",by:"ts-cloud",rc:d?.replace(/^rc=/,"")??"",steps:f==="server-static"?["upload artifact","publish static files"]:["upload artifact","restart service"]})}return r.sort((n,s)=>String(s.timestamp).localeCompare(String(n.timestamp)))}function mu(e,t){let r=Jl(e,t),n=ao(e),s=ru(e),i=Math.max(1,Number(e.infrastructure?.compute?.disk?.size??1)),o={server:{name:r?.serverName??`${e.project.slug}-${t}-app`,provider:r?.provider??uo(e),region:Xl(e),ip:r?.publicIp??q,os:"Linux",uptime:q,probeStatus:"unavailable"},systemMetrics:{load:0,load5:0,load15:0,cpuUsedPct:0,cpus:Math.max(1,Number(e.infrastructure?.compute?.instances??1)),memUsedMb:0,memTotalMb:0,memAvailableMb:0,memCacheMb:0,swapUsedMb:0,swapTotalMb:0,diskUsedPct:0,diskUsedGb:0,diskTotalGb:i,inodeUsedPct:0,networkRxBytes:0,networkTxBytes:0,networkRxBytesPerSec:0,networkTxBytesPerSec:0,networkRxBytesToday:0,networkTxBytesToday:0,networkRxBytesMonth:0,networkTxBytesMonth:0,networkMonthKey:"",processes:0,uptimeSeconds:0},metricsUnavailable:!0,bandwidthBudgetBytes:Yl(e),services:n,servicesDetail:n.map((a)=>({...a,since:q,memMb:0,auto:!0})),backup:ql(e),backupHistory:[],workers:Ql(e),serverScheduler:{enabled:!1,lastRun:"not configured"},serverDeployments:[],serverDeploymentsDetail:[],deploymentsEmptyReason:"No deployment history has been recorded yet. Future server deploys will write /var/www/<site>/.ts-cloud/deploy-history.log.",serverLogs:[],serverLogsEmptyReason:"Live server logs are unavailable until the dashboard can reach the compute box.",security:$n(e),securityEmptyReason:"Live security checks are unavailable until the dashboard can reach the compute box.",sites:s,sitesDetail:s.map((a)=>{let c=e.sites?.[a.name]??{},l=P(c);return{...a,root:l==="server-static"?J(e.project.slug,a.name):`${J(e.project.slug,a.name)}/current`,branch:l==="server-static"?"build artifact":"main",build:c.build,php:c.php??c.phpVersion,aliases:Array.isArray(c.aliases)?c.aliases:[],redirects:c.redirects&&typeof c.redirects==="object"?c.redirects:{},envKeys:Object.keys(c.env??c.environment??{})}}),siteHealth:[],sshKeys:Dt(e.infrastructure?.compute?.sshKeys??[]),_serverReachable:!1,_metricsStatus:"unavailable"};return o.diagnostics=_o(e,o),o.activity=$o(o),o.topology=Wr(o,{project:e.project.name,environment:t}),o}async function Jn(e,t,r={}){if(!e.infrastructure?.compute)return null;let n=null;try{n=O({config:e})}catch{n=null}let s=null,i=0,o=[];if(n)try{if(o=await n.findComputeTargets({slug:e.project.slug,environment:t,role:"app"}),i=o.length,o.length){let d=(await n.runRemoteDeploy({targets:[o[0]],commands:Gl({includeServices:!r.telemetryOnly,includeSites:r.includeSiteHealth!==!1,projectFilter:e.cloud?.attachTo?e.project.slug:void 0}),comment:`ts-cloud dashboard:build ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output;if(d)s=Vl(d)}}catch{}let a=mu(e,t),c=(p,d=0)=>{let m=Number(p);return Number.isFinite(m)?m:d};if(a.server.os=s?.OS||a.server.os,a.server.uptime=s?.UPTIME||a.server.uptime,s){if(a.server.probeStatus="live",a.metricsUnavailable=!1,a._metricsStatus="live",a.systemMetrics={load:c(s.LOAD),load5:c(s.LOAD5),load15:c(s.LOAD15),cpuUsedPct:c(s.CPUUSED),cpus:c(s.CPUS,1),memUsedMb:c(s.MEMUSED),memTotalMb:c(s.MEMTOTAL,1),memAvailableMb:c(s.MEMAVAILABLE),memCacheMb:c(s.MEMCACHE),swapUsedMb:c(s.SWAPUSED),swapTotalMb:c(s.SWAPTOTAL),diskUsedPct:c(s.DISKPCT),diskUsedGb:c(s.DISKUSEDG),diskTotalGb:c(s.DISKTOTG,1),inodeUsedPct:c(s.INODEPCT),networkRxBytes:c(s.NETRX),networkTxBytes:c(s.NETTX),networkRxBytesPerSec:c(s.NETRXRATE),networkTxBytesPerSec:c(s.NETTXRATE),networkRxBytesToday:c(s.NETRXTODAY),networkTxBytesToday:c(s.NETTXTODAY),networkRxBytesMonth:c(s.NETRXMONTH),networkTxBytesMonth:c(s.NETTXMONTH),networkMonthKey:s.NETMONTHKEY||"",processes:c(s.PROCESSES),uptimeSeconds:c(s.UPTIME_SECONDS)},s.services.length){let p=[...new Map(s.services.map((d)=>[d.name,d])).values()];a.services=p.map((d)=>({name:d.name,status:d.status==="active"?"running":d.status})),a.servicesDetail=p.map((d)=>({name:d.name,status:d.status==="active"?"running":d.status,since:d.since&&d.since!==q?d.since:a.server.uptime,memMb:Math.max(0,Math.round(Number(d.memBytes??0)/1024/1024)),auto:d.enabled?!["disabled","static","masked"].includes(d.enabled):!0}))}if(s.discoveredSites.length)a.sitesDetail=nu(a.sitesDetail,s.discoveredSites,e.project.slug),a.sites=a.sitesDetail.map((p)=>({name:p.name,project:p.project,managedBy:p.managedBy,route:p.route,href:p.href,domain:p.domain,path:p.path,kind:p.kind,type:p.type,runtime:p.runtime,deploy:p.deploy,tls:p.tls,status:p.status,httpStatus:p.httpStatus,responseMs:p.responseMs,tlsDaysRemaining:p.tlsDaysRemaining,checkedAt:p.checkedAt})),a.siteHealth=a.sitesDetail.map((p)=>({name:p.name,project:p.project,route:p.route,status:p.status,httpStatus:p.httpStatus,responseMs:p.responseMs,tlsDaysRemaining:p.tlsDaysRemaining,checkedAt:p.checkedAt}))}if(n&&o.length&&!r.telemetryOnly)await Promise.all([(async()=>{try{let p=Object.keys(e.sites??{}),m=(await n.runRemoteDeploy({targets:[o[0]],commands:su(p,e.project.slug),comment:`ts-cloud dashboard:deploy-history ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",f=du(m,e.sites);a.serverDeployments=f.slice(0,5),a.serverDeploymentsDetail=f.slice(0,50),a.deploymentsEmptyReason=f.length?void 0:"No deployment history was found on the server yet. Deploy again to populate this timeline."}catch{a.deploymentsEmptyReason="Deployment history could not be read from the server."}})(),(async()=>{try{let d=(await n.runRemoteDeploy({targets:[o[0]],commands:au(e),comment:`ts-cloud dashboard:server-logs ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",m=cu(d);a.serverLogs=m,a.serverLogsEmptyReason=m.length?void 0:"No recent journal entries were found for the managed server units."}catch{a.serverLogsEmptyReason="Server logs could not be read from the box."}})(),(async()=>{try{let d=(await n.runRemoteDeploy({targets:[o[0]],commands:iu(e),comment:`ts-cloud dashboard:security ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",m=pu(d),f=$n(e);if(!m.ports.length)m.ports=f.ports;if(!m.tlsCertificates.length)m.tlsCertificates=f.tlsCertificates;a.security=m,a.securityEmptyReason=void 0}catch{a.securityEmptyReason="Server security checks could not be read from the box."}})()]);else if(n&&i===0)a.deploymentsEmptyReason="No app server target was found for this environment.";let l=e.infrastructure?.compute?.sshKeys??e.infrastructure?.ssh?.keys??e.infrastructure?.sshKeys;if(Array.isArray(l)&&l.length)a.sshKeys=Dt(l);return a._serverReachable=i>0&&!!s,a.diagnostics=_o(e,a),a.activity=$o(a),a.topology=Wr(a,{project:e.project.name,environment:t}),a}
724
+ export{ze,qo,ue,ki,Wn,_i,xi,Fr,$i,Oi,ye,Y,He,Ne,jr,or,qe,sr,Vr,lt,pe,dt,ar,Li,cr,lr,dr,zr,ur,O,Mi,Ui,Gn,Wo,Hr,Go,Ko,ka,Bi,Jo,Xo,Qo,Yo,ut,Zo,qr,Fi,ji,_a,xa,Dt,Kn,Jn};