@stacksjs/ts-cloud 0.9.3 → 0.9.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/aws/index.js +1 -269
- package/dist/bin/chunk-00kg80qg.js +1 -0
- package/dist/bin/{chunk-hzqw8xm5.js → chunk-1k5kszjp.js} +1 -1
- package/dist/bin/{chunk-9v39615t.js → chunk-21e0mavm.js} +1 -1
- package/dist/bin/{chunk-waayf9ay.js → chunk-2empps47.js} +1 -1
- package/dist/bin/{chunk-14cwr6eh.js → chunk-3vqfexc4.js} +1 -1
- package/dist/bin/chunk-5ectjq0b.js +1 -0
- package/dist/bin/{chunk-b5gd39s8.js → chunk-5erkxpt7.js} +4 -4
- package/dist/bin/{chunk-41x17hw1.js → chunk-5mrtzemj.js} +1 -1
- package/dist/bin/{chunk-p8q9bq9g.js → chunk-5n9fmabb.js} +1 -1
- package/dist/bin/{chunk-gqf6jsmy.js → chunk-9knpg30y.js} +1 -1
- package/dist/bin/{chunk-r3kv0vm9.js → chunk-ddk4rt4j.js} +1 -1
- package/dist/bin/{chunk-avm7tnwe.js → chunk-e0rkrq70.js} +1 -1
- package/dist/bin/{chunk-ry030a6b.js → chunk-etrb03mt.js} +1 -1
- package/dist/bin/{chunk-8v7ddyvf.js → chunk-k9t9wvms.js} +1 -1
- package/dist/bin/{chunk-92mea34a.js → chunk-m7dgskt1.js} +1 -1
- package/dist/bin/{chunk-3r4fb59r.js → chunk-mz0wbbsj.js} +1 -1
- package/dist/bin/{chunk-b9qbp8j1.js → chunk-qk9qgepa.js} +1 -1
- package/dist/bin/chunk-rxcvf10f.js +7364 -0
- package/dist/bin/{chunk-r9hjwcj9.js → chunk-tga3hhwk.js} +1 -1
- package/dist/bin/{chunk-ynjvbphf.js → chunk-tx0tqq2k.js} +1 -1
- package/dist/bin/{chunk-57y1zxbf.js → chunk-vm3q5gf2.js} +1 -1
- package/dist/bin/{chunk-bz828v8q.js → chunk-y7s5r8y6.js} +1 -1
- package/dist/bin/{chunk-sgyffpgm.js → chunk-zmegvjp8.js} +1 -1
- package/dist/bin/cli.js +14 -14
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/chunk-0ccta6z6.js +6 -0
- package/dist/chunk-0k1cs6pp.js +1 -0
- package/dist/chunk-1egjn203.js +704 -0
- package/dist/chunk-2wx29qga.js +5 -0
- package/dist/chunk-5m5rqmv7.js +1 -0
- package/dist/chunk-8ea5022g.js +114 -0
- package/dist/chunk-8xqn3c0w.js +2 -0
- package/dist/chunk-b4esxhmw.js +2 -0
- package/dist/chunk-b8e5wzwn.js +44 -0
- package/dist/chunk-bggt4n6e.js +2 -0
- package/dist/chunk-cwkg37rs.js +37 -0
- package/dist/chunk-dskvqt67.js +7355 -0
- package/dist/chunk-gahsdmxf.js +1617 -0
- package/dist/chunk-gnv3r2jg.js +1 -0
- package/dist/chunk-hg3c48cp.js +34 -0
- package/dist/chunk-m5azeva3.js +2 -0
- package/dist/chunk-r3qf56b3.js +92 -0
- package/dist/chunk-sdqa9ghv.js +141 -0
- package/dist/chunk-svrvvcm7.js +1 -0
- package/dist/chunk-v0p3hpc3.js +60 -0
- package/dist/chunk-wdzjbecg.js +50 -0
- package/dist/chunk-ww8k3g7j.js +1 -0
- package/dist/chunk-xmqfc62w.js +1 -0
- package/dist/chunk-xrebj679.js +435 -0
- package/dist/chunk-xt3s24vr.js +2 -0
- package/dist/chunk-y21zk0pn.js +4 -0
- package/dist/deploy/index.js +1 -168
- package/dist/dns/index.js +1 -41
- package/dist/drivers/index.js +1 -154
- package/dist/index.js +100 -6129
- package/dist/protection/index.js +1 -89
- package/dist/push/index.js +1 -509
- package/dist/spend/index.js +1 -173
- package/dist/ui/404.html +1 -1
- package/dist/ui/accept-invitation.html +1 -1
- package/dist/ui/access-denied.html +1 -1
- package/dist/ui/account/automation.html +6 -6
- package/dist/ui/account/security.html +2 -2
- package/dist/ui/applications/compose.html +6 -6
- package/dist/ui/applications/new.html +2 -2
- package/dist/ui/data/backups.html +5 -5
- package/dist/ui/data/services.html +5 -5
- package/dist/ui/data/volumes.html +6 -6
- package/dist/ui/index.html +6 -6
- package/dist/ui/infrastructure/topology.html +5 -5
- package/dist/ui/integrations.html +1 -1
- package/dist/ui/operations/alerts.html +5 -5
- package/dist/ui/operations/configuration.html +5 -5
- package/dist/ui/operations/jobs.html +5 -5
- package/dist/ui/operations/maintenance.html +5 -5
- package/dist/ui/operations/observability.html +6 -6
- package/dist/ui/operations/previews.html +6 -6
- package/dist/ui/operations/queue.html +6 -6
- package/dist/ui/operations/regions.html +6 -6
- package/dist/ui/operations/releases.html +6 -6
- package/dist/ui/operations/spend.html +6 -6
- package/dist/ui/operations/workloads.html +6 -6
- package/dist/ui/security.html +1 -1
- package/dist/ui/server/actions.html +5 -5
- package/dist/ui/server/activity.html +1 -1
- package/dist/ui/server/capacity.html +6 -6
- package/dist/ui/server/database.html +6 -6
- package/dist/ui/server/deployments.html +6 -6
- package/dist/ui/server/diagnostics.html +2 -2
- package/dist/ui/server/firewall.html +6 -6
- package/dist/ui/server/fleet.html +6 -6
- package/dist/ui/server/logs.html +6 -6
- package/dist/ui/server/metrics.html +6 -6
- package/dist/ui/server/security.html +2 -2
- package/dist/ui/server/services.html +1 -1
- package/dist/ui/server/sites.html +6 -6
- package/dist/ui/server/ssh-keys.html +6 -6
- package/dist/ui/server/team.html +6 -6
- package/dist/ui/server/terminal.html +1 -1
- package/dist/ui/serverless/alarms.html +5 -5
- package/dist/ui/serverless/assets.html +2 -2
- package/dist/ui/serverless/cost.html +1 -1
- package/dist/ui/serverless/data.html +6 -6
- package/dist/ui/serverless/deployments.html +2 -2
- package/dist/ui/serverless/firewall.html +1 -1
- package/dist/ui/serverless/functions.html +6 -6
- package/dist/ui/serverless/logs.html +6 -6
- package/dist/ui/serverless/metrics.html +2 -2
- package/dist/ui/serverless/queues.html +6 -6
- package/dist/ui/serverless/secrets.html +6 -6
- package/dist/ui/serverless/traces.html +6 -6
- package/dist/ui/serverless.html +5 -5
- package/package.json +3 -3
- package/dist/bin/chunk-jpjamjey.js +0 -6935
- package/dist/bin/chunk-m2zwtapr.js +0 -1
- package/dist/bin/chunk-rtczra13.js +0 -1
- package/dist/chunk-01d86gt1.js +0 -1324
- package/dist/chunk-050r7ycy.js +0 -46516
- package/dist/chunk-1c8dbv57.js +0 -7278
- package/dist/chunk-29rse4p1.js +0 -12203
- package/dist/chunk-32e7ya18.js +0 -642
- package/dist/chunk-4cjrg98a.js +0 -597
- package/dist/chunk-50jpda9q.js +0 -371
- package/dist/chunk-6a1t7fnq.js +0 -12121
- package/dist/chunk-728jvrr0.js +0 -1701
- package/dist/chunk-7m60qnc8.js +0 -1762
- package/dist/chunk-aa2dkn7b.js +0 -205
- package/dist/chunk-d48vtdj4.js +0 -433
- package/dist/chunk-f55nkpvb.js +0 -8
- package/dist/chunk-fgk8cqew.js +0 -152
- package/dist/chunk-he9a874b.js +0 -769
- package/dist/chunk-k2yyatfw.js +0 -10
- package/dist/chunk-k4px0bnv.js +0 -23
- package/dist/chunk-nsgqsmrh.js +0 -1779
- package/dist/chunk-q0st3se8.js +0 -42033
- package/dist/chunk-qr803fye.js +0 -2122
- package/dist/chunk-rds0sy87.js +0 -1771
- package/dist/chunk-ttz2ra5j.js +0 -12
- package/dist/chunk-v0bahtg2.js +0 -4
- package/dist/chunk-va2yd85b.js +0 -200
- package/dist/chunk-x9s0cqfx.js +0 -13
- package/dist/chunk-zqtpg06c.js +0 -1752
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
import{Nh as m1,Oh as Qz}from"./chunk-y21zk0pn.js";import{Ph as h1}from"./chunk-b4esxhmw.js";import{Rh as b1}from"./chunk-r3qf56b3.js";import{jl as D1}from"./chunk-cwkg37rs.js";import{ql as x1}from"./chunk-b8e5wzwn.js";import{$l as I,Nl as mz,Ol as vz,Rl as M1,Sl as O1,Tl as V0,Ul as b0,tn as Q$,wn as X2,xn as fz}from"./chunk-dskvqt67.js";import{qt as N4}from"./chunk-xt3s24vr.js";import{readFileSync as v1}from"node:fs";import{join as n4}from"node:path";function t8($={}){let z=new Set;for(let J of Object.values($)){if(!J.domain)continue;if(J.redirect||J.deploy==="server"||J.start)z.add(J.domain)}return z}function f$($){return $.replace(/\.$/,"").toLowerCase()}function d2($,z,J){let Z=f$($.name),Q=f$(z),q=f$(J),Y=q===Q?"@":q.endsWith(`.${Q}`)?q.slice(0,-(Q.length+1)):q;return Z===q||Z===Y||Y==="@"&&(Z===""||Z===Q)}async function c2($,z,J,Z,Q="A"){let q=await $.listRecords(z);if(!q.success)return[`could not list ${Q} records: ${q.message||"unknown provider error"}`];let Y=q.records.filter((G)=>G.type===Q&&d2(G,z,J)),W=Y.findIndex((G)=>G.content===Z);if(Y.length<=1||W===-1)return[];let j=[];for(let[G,H]of Y.entries()){if(G===W)continue;let M=await $.deleteRecord(z,H);if(!M.success)j.push(`could not remove stale ${H.name} ${Q} ${H.content}: ${M.message||"unknown provider error"}`)}return j}function W0($){if(!$)return;let z=$.trim();if(!z)return;if(!z.includes("/"))return z;let[J]=z.split("/");if(!J.endsWith("::"))return J||void 0;return`${J}1`}var l2=new Set(["mail","smtp","imap","mx"]);function p2($){return!l2.has($.split(".")[0]??"")}async function o8($){let{provider:z,zone:J,fqdn:Z,ipv4:Q,ipv6:q,ttl:Y=600}=$,W={published:[],warnings:[]},j=[{type:"A",content:Q}];if(q&&p2(Z))j.push({type:"AAAA",content:q});for(let{type:G,content:H}of j){let M=await z.upsertRecord(J,{name:Z,type:G,content:H,ttl:Y});if(M?.success===!1){W.warnings.push(`${Z} → ${H} failed: ${M.error||M.message||"unknown error"}`);continue}if(W.warnings.push(...(await c2(z,J,Z,H,G)).map((X)=>`${Z} cleanup: ${X}`)),await a2(z,J,Z,H,G))W.published.push({fqdn:Z,type:G,content:H});else W.warnings.push(`${Z} → ${H} reported success at ${z.name} but no matching ${G} record exists — create it manually: ${G} ${Z} → ${H}`)}return W}async function a2($,z,J,Z,Q){try{if(typeof $?.listRecords!=="function")return!0;let q=await $.listRecords(z);if(!q?.success||!Array.isArray(q.records))return!0;return q.records.some((Y)=>{let W=typeof Y?.name==="string"?Y.name.replace(/\.$/,""):"";return Y?.type===Q&&W===J&&Y?.content===Z})}catch{return!0}}var sz={php:"php.net",nginx:"nginx.org",composer:"getcomposer.org",mysql:"mysql.com",mariadb:"mariadb.com/server",postgres:"postgresql.org",vitess:"vitess.io",etcd:"etcd.io",redis:"redis.io",memcached:"memcached.org",meilisearch:"meilisearch.com",git:"git-scm.com",certbot:"certbot.eff.org",bun:"bun.sh",node:"nodejs.org",deno:"deno.land"};var l="/opt/pantry";function q$($){return`'${$.split("'").join("'\\''")}'`}function Y$($={}){return["export DEBIAN_FRONTEND=noninteractive","export PANTRY_SERVICE_SCOPE=system","export PANTRY_INSTALL_DIR=/usr/local/bin",$.version?`export PANTRY_VERSION=${q$($.version)}`:'export PANTRY_VERSION="${PANTRY_VERSION:-latest}"',"command -v curl >/dev/null 2>&1 || (apt-get update -y && apt-get install -y curl ca-certificates)","command -v unzip >/dev/null 2>&1 || (apt-get update -y && apt-get install -y unzip)",'OS=$(uname -s | tr \'[:upper:]\' \'[:lower:]\'); ARCH=$(uname -m); case "$ARCH" in x86_64|amd64) ARCH=x64 ;; arm64|aarch64) ARCH=arm64 ;; esac; ZIP="pantry-${OS}-${ARCH}.zip"; if [ "${PANTRY_VERSION:-latest}" = latest ]; then REL=\'latest/download\'; else REL="download/v${PANTRY_VERSION}"; fi; TMP=$(mktemp -d); curl -fsSL -o "${TMP}/${ZIP}" "https://github.com/pantry-pm/pantry/releases/${REL}/${ZIP}"; unzip -o "${TMP}/${ZIP}" -d /usr/local/bin; chmod +x /usr/local/bin/pantry; rm -rf "${TMP}"','export PATH="/usr/local/bin:$PATH"',"mkdir -p /opt/pantry"]}function C0(){return'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true'}function j0($){if($.length===0)return[];return[`(cd /opt/pantry && pantry install ${[...new Set($)].map(q$).join(" ")})`]}function W$($){return[...new Set($)].flatMap((z)=>[`(cd /opt/pantry && pantry start ${q$(z)})`,`(cd /opt/pantry && pantry enable ${q$(z)})`])}var p=`${l}/pantry/.bin`,m$=15306,b$=15991,j$=15999,ez=16101,G$=2379,J0="/var/lib/vitess",v$=100;function r2($){return $===!0||typeof $==="object"&&$!==null}function n2($){return typeof $==="object"&&$!==null?$:{}}function k($){return`'${String($).split("'").join("'\\''")}'`}function i2($){let J=[$.version?`vitess.io@${$.version}`:"vitess.io"];if($.mode!=="combo"&&!$.etcdEndpoint)J.push("etcd.io");return J.push("mysql.com@8.0.43"),J}var g="vitess",t2=`${p}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`,Z1="/usr/local/lib/vitess",u$=new Map;function h$($){return`${Z1}/${$}.sh`}function _0($,z){return u$.set($,o2(z)),`/bin/sh ${h$($)}`}function $1(){let $=[`mkdir -p ${Z1}`];for(let[z,J]of u$)$.push(`cat > ${h$(z)} <<'TS_CLOUD_VITESS_LAUNCHER_EOF'`,J,"TS_CLOUD_VITESS_LAUNCHER_EOF",`chmod 0755 ${h$(z)}`);return $}function o2($){return["#!/bin/sh","set -e",`cd ${l}`,`PANTRY_ENV="$(pantry env 2>/dev/null | grep -E '^(export [A-Za-z_]|[A-Za-z_][A-Za-z0-9_]*=)' || true)"`,'if [ -n "$PANTRY_ENV" ]; then eval "$PANTRY_ENV"; fi',`VT_MYSQL_ROOT="$(dirname "$(dirname "$(readlink -f ${p}/mysqld 2>/dev/null)")")"`,`VTROOT="$(dirname "$(dirname "$(readlink -f ${p}/mysqlctld 2>/dev/null)")")"`,"export VT_MYSQL_ROOT VTROOT",'LD_LIBRARY_PATH="$VT_MYSQL_ROOT/lib:$VTROOT/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"',"export LD_LIBRARY_PATH",`exec ${$.join(" ")}`].join(`
|
|
2
|
+
`)}function k0($){let z=["[Unit]",`Description=${$.description}`,`After=network.target${$.after?.length?` ${$.after.join(" ")}`:""}`];if($.requires?.length)z.push(`Requires=${$.requires.join(" ")}`);return z.push("","[Service]","Type=simple",`User=${g}`,`Group=${g}`,`Environment="PATH=${t2}"`,`Environment="VTDATAROOT=${J0}"`,...Object.entries($.environment??{}).map(([J,Z])=>`Environment="${J}=${Z}"`),...($.execStartPre??[]).map((J)=>`ExecStartPre=${J}`),`ExecStart=${$.execStart}`,"Restart=always","RestartSec=5","LimitNOFILE=65535","","[Install]","WantedBy=multi-user.target"),z.join(`
|
|
3
|
+
`)}function z1($,z){return[`cat > /etc/systemd/system/${$}.service <<'TS_CLOUD_VITESS_UNIT_EOF'`,z,"TS_CLOUD_VITESS_UNIT_EOF"]}function s2($){let z=$.cell??"zone1",J=$.vtgatePort??m$,Q=`${(($.keyspaces?.length)?$.keyspaces:[{name:"app"}]).map((q)=>{let Y=(q.sharded?["-80","80-"]:["0"]).map((W)=>`shards:{name:"${W}"}`).join(" ");return`keyspaces:{name:"${q.name}" ${Y}}`}).join(" ")} cells:"${z}"`;return k0({description:"Vitess (vtcombo, single-process development stack)",execStart:_0("vtcombo",[`${p}/vtcombo`,`--cell ${z}`,`--proto-topo ${k(Q)}`,`--mysql-server-port ${J}`,"--mysql-server-bind-address 127.0.0.1","--mysql-auth-server-impl none","--start-mysql",`--port ${b$}`,`--grpc-port ${j$}`])})}function e2(){return k0({description:"etcd (Vitess topology store)",execStart:_0("etcd",[`${p}/etcd`,`--data-dir ${J0}/etcd`,`--listen-client-urls http://127.0.0.1:${G$}`,`--advertise-client-urls http://127.0.0.1:${G$}`]),execStartPre:[`+/bin/mkdir -p ${J0}/etcd`,`+/bin/chown ${g}:${g} ${J0}/etcd`]})}function g$($){return["--topo-implementation etcd2",`--topo-global-server-address ${$.etcdEndpoint??`http://127.0.0.1:${G$}`}`,"--topo-global-root /vitess/global"]}function $4($){let z=!$.etcdEndpoint;return k0({description:"Vitess vtctld (control plane)",after:z?["vitess-etcd.service"]:[],requires:z?["vitess-etcd.service"]:[],execStart:_0("vtctld",[`${p}/vtctld`,...g$($),`--cell ${$.cell??"zone1"}`,"--service-map grpc-vtctl,grpc-vtctld",`--grpc-port ${j$}`,`--port ${j$+1}`])})}function z4($,z,J){let Z=$.cell??"zone1";return k0({description:`Vitess vttablet (${z}/${J})`,after:["vitess-vtctld.service","vitess-mysqlctld.service"],requires:["vitess-mysqlctld.service"],execStart:_0("vttablet",[`${p}/vttablet`,...g$($),`--tablet-path ${Z}-${String(v$).padStart(10,"0")}`,`--init-keyspace ${z}`,`--init-shard ${J}`,"--init-tablet-type replica",`--service-map ${k("grpc-queryservice,grpc-tabletmanager,grpc-updatestream")}`,`--port ${ez}`,`--grpc-port ${ez+1}`,`--db-port ${$.mysqlPort??3306}`,`--mycnf-mysql-port ${$.mysqlPort??3306}`])})}function J4($){return k0({description:"Vitess mysqlctld (managed mysqld)",execStart:_0("mysqlctld",[`${p}/mysqlctld`,`--tablet-uid ${v$}`,`--mysql-port ${$.mysqlPort??3306}`,'--init-db-sql-file "$VTROOT/config/init_db.sql"',"--wait-time 2m"]),execStartPre:[`+/bin/mkdir -p ${J0}`,`+/bin/chown ${g}:${g} ${J0}`]})}var Q1="/etc/vitess/auth.json",p0="/var/lib/vitess/vtgate-auth.sha256";function Z4($){let z=$.username??"vitess",J=$.password??"";return["mkdir -p /etc/vitess",'VTESS_AUTH_TMP="$(mktemp)"',`cat > "$VTESS_AUTH_TMP" <<'TS_CLOUD_VITESS_AUTH_EOF'`,JSON.stringify({[z]:[{Password:J,UserData:z}]}),"TS_CLOUD_VITESS_AUTH_EOF",`VTESS_VTGATE_AUTH_SHA="$(sha256sum "$VTESS_AUTH_TMP" | awk '{print $1}')"`,"VTESS_VTGATE_AUTH_CHANGED=1",`if [ -f ${p0} ] && [ "$(cat ${p0})" = "$VTESS_VTGATE_AUTH_SHA" ]; then VTESS_VTGATE_AUTH_CHANGED=0; fi`,`install -o ${g} -g ${g} -m 0600 "$VTESS_AUTH_TMP" ${Q1}`,'rm -f "$VTESS_AUTH_TMP"']}function Q4($){let z=$.cell??"zone1";return k0({description:"Vitess vtgate (query router)",after:["vitess-vtctld.service"],execStart:_0("vtgate",[`${p}/vtgate`,...g$($),`--cell ${z}`,`--cells-to-watch ${z}`,"--tablet-types-to-wait PRIMARY,REPLICA",`--service-map ${k("grpc-vtgateservice")}`,`--mysql-server-port ${$.vtgatePort??m$}`,`--mysql-server-bind-address ${$.bindAddress??"127.0.0.1"}`,"--mysql-auth-server-impl static",`--mysql-auth-server-static-file ${Q1}`,`--port ${b$}`,`--grpc-port ${b$+1}`])})}function q4($){let z=$.cell??"zone1",J=$.etcdEndpoint??`http://127.0.0.1:${G$}`,Z=`${p}/vtctldclient --server 127.0.0.1:${j$}`,Q=[`for i in $(seq 1 30); do ${Z} GetCellInfoNames >/dev/null 2>&1 && break; sleep 2; done`,`if ! ${Z} GetCellInfoNames 2>/dev/null | grep -qx ${k(z)}; then`,` ${Z} AddCellInfo --root ${k(`/vitess/${z}`)} --server-address ${k(J)} ${k(z)}`,"fi"];for(let q of $.keyspaces??[]){let Y=q.sharded?" --sharded":"";Q.push(`if ! ${Z} GetKeyspace ${k(q.name)} >/dev/null 2>&1; then`,` ${Z} CreateKeyspace${Y} ${k(q.name)}`,"fi");let W=`${z}-${String(v$).padStart(10,"0")}`;for(let j of q.sharded?["-80","80-"]:["0"]){let G=`${q.name}/${j}`;Q.push("for i in $(seq 1 90); do",` if ${Z} GetShard ${k(G)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then break; fi`,` ${Z} PlannedReparentShard ${k(G)} --new-primary ${k(W)} >/dev/null 2>&1 && break`,` ${Z} InitShardPrimary --force ${k(G)} ${k(W)} >/dev/null 2>&1 && break`," sleep 2","done",`if ! ${Z} GetShard ${k(G)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then`,` echo "no primary could be elected for ${G}" >&2; exit 1`,"fi")}Q.push(`${Z} RebuildKeyspaceGraph ${k(q.name)} >/dev/null`)}return Q}function J1($){let z=$.vtgatePort??m$;return["for i in $(seq 1 60); do",` if (cd ${l} && eval "$(pantry env 2>/dev/null)"; MYSQL_PWD=${k($.password??"")} ${p}/mysql -h 127.0.0.1 -P ${z} -u ${k($.username??"vitess")} --connect-timeout=2 -e 'SHOW KEYSPACES') >/dev/null 2>&1; then`,` echo "vtgate is serving on ${z}"; exit 0`," fi"," sleep 2","done",`echo "vtgate did not become ready on port ${z}" >&2`,"exit 1"]}function q1($){if(!r2($))return[];let z=n2($),J=z.mode==="combo";u$.clear();let Z=[...j0(i2(z)),`VT_MYSQL_LIB="$(dirname "$(dirname "$(readlink -f ${p}/mysqld)")")/lib"`,'if [ -d "$VT_MYSQL_LIB" ]; then',` printf '%s\\n' "$VT_MYSQL_LIB" > /etc/ld.so.conf.d/vitess-mysql.conf`," ldconfig","else",' echo "mysqld library directory not found under $VT_MYSQL_LIB" >&2; exit 1',"fi",`id -u ${g} >/dev/null 2>&1 || useradd --system --home-dir ${J0} --shell /usr/sbin/nologin ${g}`,`mkdir -p ${J0}`,`chown -R ${g}:${g} ${J0}`];if(J)return Z.push(...z1("vitess-vtcombo",s2(z)),...$1(),"systemctl daemon-reload","systemctl enable --now vitess-vtcombo.service",...J1(z)),Z;Z.push(...Z4(z));let Q=[];if(!z.etcdEndpoint)Q.push(["vitess-etcd",e2()]);Q.push(["vitess-vtctld",$4(z)],["vitess-mysqlctld",J4(z)],["vitess-vtgate",Q4(z)]);for(let q of z.keyspaces??[])for(let Y of q.sharded?["-80","80-"]:["0"])Q.push([`vitess-vttablet-${q.name}-${Y.replace(/-/g,"x")}`,z4(z,q.name,Y)]);for(let[q,Y]of Q)Z.push(...z1(q,Y));Z.push(...$1()),Z.push("systemctl daemon-reload");for(let[q]of Q)Z.push(`systemctl enable --now ${q}.service`);return Z.push(`if [ "$VTESS_VTGATE_AUTH_CHANGED" = 1 ]; then systemctl restart vitess-vtgate.service; printf '%s\\n' "$VTESS_VTGATE_AUTH_SHA" > ${p0}; chown ${g}:${g} ${p0}; chmod 0600 ${p0}; fi`,...q4(z),...J1(z)),Z}var Y4=new Set(["singlestore","vitess"]);function Y1($){if($?.engine&&Y4.has($.engine))return!1;return!$?.host||$.host==="127.0.0.1"||$.host==="localhost"}function d$($,z="psql"){let J=$?.port??5432;if(Y1($))return`${z} -p ${J} -U postgres`;let Z=$?.username||"postgres";return`${$?.password?`PGPASSWORD='${$.password.replace(/'/g,"'\\''")}' `:""}${z} -h ${$.host} -p ${J} -U ${Z} -w`}function Z0($){return $===!0||typeof $==="object"&&$!=null}function W4($){let z=[],J=[];if(Z0($.mysql))z.push(typeof $.mysql==="object"&&$.mysql.version?`mysql.com@${$.mysql.version}`:"mysql.com@8.0.43"),J.push("mysql");else if(Z0($.mariadb))z.push(sz.mariadb),J.push("mariadb");if(Z0($.postgres))z.push("postgresql.org"),J.push("postgres");if(Z0($.redis))z.push("redis.io"),J.push("redis");if(Z0($.memcached))z.push("memcached.org"),J.push("memcached");if(Z0($.meilisearch))z.push("meilisearch.com"),J.push("meilisearch");return{packages:z,services:J}}function K$($={},z={}){let J=W4($),Z=q1($.vitess);if(J.packages.length===0)return Z;return[...j0(J.packages),...W$(J.services),...Z]}function T0($,z={}){if(!$?.name)return[];if(!Y1($))return[];let J=$.name,Z=$.username||J,Q=$.password||"",q=Z0(z.postgres)||$.engine==="postgres",Y=Z0(z.mariadb)||$.engine==="mariadb",W=Z0(z.mysql)||$.engine==="mysql";if(q&&!W&&!Y){let K=(V)=>`"${V.replace(/"/g,'""')}"`,O=(V)=>`'${V.replace(/'/g,"''")}'`,L=(V,x)=>["DO $$ BEGIN",` IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${O(V)}) THEN`,` CREATE ROLE ${K(V)} LOGIN PASSWORD ${O(x)};`," ELSE",` ALTER ROLE ${K(V)} LOGIN PASSWORD ${O(x)};`," END IF;","END $$;"],B=(V)=>{let x=V.databases&&V.databases.length>0?V.databases:[J],C=[];for(let A of x)if(V.access==="readonly")C.push(`GRANT CONNECT ON DATABASE ${K(A)} TO ${K(V.username)};`,`\\connect ${K(A)}`,`GRANT USAGE ON SCHEMA public TO ${K(V.username)};`,`GRANT SELECT ON ALL TABLES IN SCHEMA public TO ${K(V.username)};`,`ALTER DEFAULT PRIVILEGES FOR ROLE ${K(Z)} IN SCHEMA public GRANT SELECT ON TABLES TO ${K(V.username)};`,"\\connect postgres");else C.push(`GRANT ALL PRIVILEGES ON DATABASE ${K(A)} TO ${K(V.username)};`);return C},U=$.users||[],F=$.port??5432;return[C0(),`for i in $(seq 1 30); do pg_isready -p ${F} -q && break; sleep 2; done`,`${d$($)} <<'TS_CLOUD_PG_EOF'`,...L(Z,Q),`SELECT 'CREATE DATABASE ${K(J)} OWNER ${K(Z)}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = ${O(J)})\\gexec`,...U.flatMap((V)=>[...L(V.username,V.password),...B(V)]),"TS_CLOUD_PG_EOF"]}let j=Y?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock",G=(K)=>K.replace(/`/g,"``"),H=(K)=>K.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),M=(K)=>{let O=K.databases&&K.databases.length>0?K.databases:[J],L=K.access==="readonly"?"SELECT":"ALL PRIVILEGES",B=[`CREATE USER IF NOT EXISTS '${H(K.username)}'@'%' IDENTIFIED BY '${H(K.password)}';`,`CREATE USER IF NOT EXISTS '${H(K.username)}'@'localhost' IDENTIFIED BY '${H(K.password)}';`,`ALTER USER '${H(K.username)}'@'%' IDENTIFIED BY '${H(K.password)}';`,`ALTER USER '${H(K.username)}'@'localhost' IDENTIFIED BY '${H(K.password)}';`];for(let U of O)B.push(`GRANT ${L} ON \`${G(U)}\`.* TO '${H(K.username)}'@'%';`,`GRANT ${L} ON \`${G(U)}\`.* TO '${H(K.username)}'@'localhost';`);return B},X=$.users||[];return[C0(),`for i in $(seq 1 30); do mysqladmin --socket=${j} -u root ping 2>/dev/null | grep -q alive && break; sleep 2; done`,`mysql --socket=${j} -u root <<'TS_CLOUD_SQL_EOF'`,`CREATE DATABASE IF NOT EXISTS \`${G(J)}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`,...M({username:Z,password:Q}),...X.flatMap(M),"FLUSH PRIVILEGES;","TS_CLOUD_SQL_EOF"]}function W1($){if(!$?.name)return{};let z=$.engine==="singlestore",J=$.engine==="vitess",Z=$.engine==="postgres"?"pgsql":z?"singlestore":J?"vitess":"mysql",Q=$.port??($.engine==="postgres"?5432:J?15306:3306),q={DB_CONNECTION:Z,DB_HOST:$.host||"127.0.0.1",DB_PORT:String(Q),DB_DATABASE:$.name};if($.username)q.DB_USERNAME=$.username;if($.password)q.DB_PASSWORD=$.password;if((z||J)&&$.ssl!==!1)q.DB_SSL="true";return q}var l$="/var/backups/ts-cloud",j4="/etc/ts-cloud/backups.config.ts",j1="/etc/cron.d/ts-cloud-backups",c$="/usr/local/bin/ts-cloud-backup.sh";function G4($){if(!$.name)return null;let z=$.host||"127.0.0.1",J=$.engine==="postgres",Z=J?"postgresql":"mysql",Q=$.port??(J?5432:3306),q=(Y)=>Y.replace(/\\/g,"\\\\").replace(/'/g,"\\'");return[" {",` type: '${Z}',`,` name: '${q($.name)}',`," connection: {",` hostname: '${q(z)}',`,` port: ${Q},`,` database: '${q($.name)}',`,` username: '${q($.username||$.name)}',`,` password: '${q($.password||"")}',`," ssl: false,"," },"," includeSchema: true,"," includeData: true,"," },"].join(`
|
|
4
|
+
`)}function K4($,z){let J=$?G4($):null,Z=z.bucket?[" destinations: ["," {"," type: 's3',",` bucket: '${z.bucket}',`," prefix: 'db-backups',",...z.endpoint?[` endpoint: '${z.endpoint}',`]:[]," optional: false,"," },"," ],"]:[];return["import type { BackupConfig } from 'ts-backups'","","const config: BackupConfig = {"," verbose: true,",` outputPath: '${l$}',`," retention: {",` count: ${z.retentionCount??5},`,` maxAge: ${z.retentionDays??30},`," },"," databases: [",...J?[J]:[]," ],",...Z,"}","","export default config",""].join(`
|
|
5
|
+
`)}function H$($){let{database:z,backups:J}=$;if(!J.enabled)return[];let Z=J.schedule||"0 2 * * *",Q=K4(z,J);return["export DEBIAN_FRONTEND=noninteractive",`mkdir -p /etc/ts-cloud ${l$}`,"command -v bun >/dev/null 2>&1 || (curl -fsSL https://bun.sh/install | bash && ln -sf /root/.bun/bin/bun /usr/local/bin/bun)","bun add -g ts-backups || true",`cat > ${j4} <<'TS_CLOUD_BACKUP_CFG_EOF'`,Q.replace(/\n$/,""),"TS_CLOUD_BACKUP_CFG_EOF",`cat > ${c$} <<'TS_CLOUD_BACKUP_RUN_EOF'`,"#!/bin/bash","set -uo pipefail",'export PATH="/root/.bun/bin:/usr/local/bin:$PATH"','notify() { [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "$1" || true; }',"cd /etc/ts-cloud",'if ! ts-backups backup --config /etc/ts-cloud/backups.config.ts; then notify "❌ ts-cloud backup failed"; exit 1; fi',"TS_CLOUD_BACKUP_RUN_EOF",`chmod +x ${c$}`,`cat > ${j1} <<'TS_CLOUD_BACKUP_CRON_EOF'`,`${Z} root ${c$} >> /var/log/ts-cloud-backup.log 2>&1`,"TS_CLOUD_BACKUP_CRON_EOF",`chmod 644 ${j1}`]}function H4($){return $==="mariadb"?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock"}function Y9($,z={}){if(!$?.name)return[];let J=$.name,Z=$.engine==="postgres",Q=z.from?`TS_CLOUD_DUMP="${z.from}"`:`TS_CLOUD_DUMP="$(find ${l$} -type f -name '*${J}*.sql' -o -type f -name '*${J}*.sql.gz' 2>/dev/null | xargs -r ls -1t 2>/dev/null | head -1)"`,q=Z?`${d$($)} -d "${J}"`:`mysql --socket=${H4($.engine)} -u root "${J}"`;return["set -uo pipefail",'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true',Q,'[ -n "$TS_CLOUD_DUMP" ] && [ -f "$TS_CLOUD_DUMP" ] || { echo "no backup dump found to restore" >&2; exit 1; }','echo "[ts-cloud] restoring '+J+' from $TS_CLOUD_DUMP"',`case "$TS_CLOUD_DUMP" in *.gz) gunzip -c "$TS_CLOUD_DUMP" ;; *) cat "$TS_CLOUD_DUMP" ;; esac | ${q}`,'echo "restore complete"']}function G0($=!0){if(!$)return[];return["export DEBIAN_FRONTEND=noninteractive","dpkg-query -W -f='${Status}' unattended-upgrades 2>/dev/null | grep -q 'ok installed' || apt-get install -y unattended-upgrades","cat > /etc/apt/apt.conf.d/20auto-upgrades <<'TS_CLOUD_AUTOUPD_EOF'",'APT::Periodic::Update-Package-Lists "1";','APT::Periodic::Unattended-Upgrade "1";','APT::Periodic::Download-Upgradeable-Packages "1";','APT::Periodic::AutocleanInterval "7";',"TS_CLOUD_AUTOUPD_EOF","systemctl enable --now unattended-upgrades 2>/dev/null || true"]}var G1=[["nginx",80],["https",443],["phpFpm",9074],["mysql",3306],["postgres",5432],["redis",6379],["meilisearch",7700],["typesense",8108],["smtp",25]];function X4($=!0){let z=typeof $==="object"?$:{},J=typeof $==="boolean"?$:$.enabled!==!1,Z=Number(z.alerts?.bandwidthTb??0);return{enabled:J,cpuLoadPerCore:z.alerts?.cpuLoadPerCore??2,memPercent:z.alerts?.memPercent??90,diskPercent:z.alerts?.diskPercent??90,bandwidthTb:Number.isFinite(Z)&&Z>0?Z:0,bandwidthPercent:z.alerts?.bandwidthPercent??80}}function K0($=!0){let{enabled:z,cpuLoadPerCore:J,memPercent:Z,diskPercent:Q,bandwidthTb:q,bandwidthPercent:Y}=X4($);if(!z)return[];let W=Math.round(q*1000000000000),j=G1.map(([H,M])=>`SVC_${H.toUpperCase()}=$(probe ${M})`),G=G1.map(([H])=>`"${H}":"$SVC_${H.toUpperCase()}"`).join(",");return["if ! command -v sadf >/dev/null 2>&1; then export DEBIAN_FRONTEND=noninteractive; apt-get update -qq; apt-get install -y -qq sysstat; fi","systemctl enable --now sysstat.service 2>/dev/null || true","mkdir -p /var/lib/ts-cloud","cat > /usr/local/bin/ts-cloud-metrics.sh <<'TS_CLOUD_METRICS_EOF'","#!/bin/bash","set -uo pipefail","LOAD=$(cut -d' ' -f1 /proc/loadavg)","CPUS=$(nproc)",`read MEM_TOTAL MEM_USED SWAP_TOTAL SWAP_USED <<EOF
|
|
6
|
+
$(free -m | awk '/^Mem:/{total=$2; used=$3} /^Swap:/{print total, used, $2, $3}')
|
|
7
|
+
EOF`,`DISK_PCT=$(df -P / | awk 'NR==2{gsub("%","",$5); print $5}')`,"UPTIME_SEC=$(cut -d' ' -f1 /proc/uptime | cut -d. -f1)",`RX_BYTES=$(awk -F'[: ]+' 'NR>2 && $2!="lo"{rx+=$3} END{print rx+0}' /proc/net/dev)`,`TX_BYTES=$(awk -F'[: ]+' 'NR>2 && $2!="lo"{tx+=$11} END{print tx+0}' /proc/net/dev)`,"NOW_EPOCH=$(date -u +%s); TODAY=$(date -u +%Y-%m-%d); MONTH=$(date -u +%Y-%m)","if [ -r /var/lib/ts-cloud/bandwidth-state ]; then . /var/lib/ts-cloud/bandwidth-state; fi","PREV_EPOCH=${PREV_EPOCH:-0}; PREV_RX=${PREV_RX:-0}; PREV_TX=${PREV_TX:-0}","DAY_KEY=${DAY_KEY:-$TODAY}; MONTH_KEY=${MONTH_KEY:-$MONTH}","DAY_RX=${DAY_RX:-0}; DAY_TX=${DAY_TX:-0}; MONTH_RX=${MONTH_RX:-0}; MONTH_TX=${MONTH_TX:-0}","ELAPSED=$(( NOW_EPOCH - PREV_EPOCH ))",'if [ "$PREV_EPOCH" -le 0 ] || [ "$ELAPSED" -le 0 ] || [ "$RX_BYTES" -lt "$PREV_RX" ] || [ "$TX_BYTES" -lt "$PREV_TX" ]; then'," DELTA_RX=0; DELTA_TX=0; ELAPSED=0","else"," DELTA_RX=$(( RX_BYTES - PREV_RX )); DELTA_TX=$(( TX_BYTES - PREV_TX ))","fi",'if [ "$DAY_KEY" != "$TODAY" ]; then DAY_KEY=$TODAY; DAY_RX=0; DAY_TX=0; fi','if [ "$MONTH_KEY" != "$MONTH" ]; then MONTH_KEY=$MONTH; MONTH_RX=0; MONTH_TX=0; fi',"DAY_RX=$(( DAY_RX + DELTA_RX )); DAY_TX=$(( DAY_TX + DELTA_TX ))","MONTH_RX=$(( MONTH_RX + DELTA_RX )); MONTH_TX=$(( MONTH_TX + DELTA_TX ))",'if [ "$ELAPSED" -gt 0 ]; then RX_RATE=$(( DELTA_RX / ELAPSED )); TX_RATE=$(( DELTA_TX / ELAPSED )); else RX_RATE=0; TX_RATE=0; fi',"cat > /var/lib/ts-cloud/bandwidth-state.tmp <<BWSTATE","PREV_EPOCH=$NOW_EPOCH","PREV_RX=$RX_BYTES","PREV_TX=$TX_BYTES","RX_RATE=$RX_RATE","TX_RATE=$TX_RATE","DAY_KEY=$DAY_KEY","DAY_RX=$DAY_RX","DAY_TX=$DAY_TX","MONTH_KEY=$MONTH_KEY","MONTH_RX=$MONTH_RX","MONTH_TX=$MONTH_TX","BWSTATE","mv -f /var/lib/ts-cloud/bandwidth-state.tmp /var/lib/ts-cloud/bandwidth-state","probe(){ (exec 3<>/dev/tcp/127.0.0.1/$1) 2>/dev/null && echo up || echo down; }",...j,"LOAD=${LOAD:-0}; CPUS=${CPUS:-1}; MEM_TOTAL=${MEM_TOTAL:-0}; MEM_USED=${MEM_USED:-0}","SWAP_TOTAL=${SWAP_TOTAL:-0}; SWAP_USED=${SWAP_USED:-0}; DISK_PCT=${DISK_PCT:-0}","UPTIME_SEC=${UPTIME_SEC:-0}; RX_BYTES=${RX_BYTES:-0}; TX_BYTES=${TX_BYTES:-0}","MEM_PCT=$(( MEM_TOTAL > 0 ? MEM_USED * 100 / MEM_TOTAL : 0 ))","cat > /var/lib/ts-cloud/metrics.json.tmp <<JSON",`{"load":$LOAD,"cpus":$CPUS,"memTotalMb":$MEM_TOTAL,"memUsedMb":$MEM_USED,"memUsedPct":$MEM_PCT,"swapTotalMb":$SWAP_TOTAL,"swapUsedMb":$SWAP_USED,"diskUsedPct":$DISK_PCT,"uptimeSec":$UPTIME_SEC,"network":{"rxBytes":$RX_BYTES,"txBytes":$TX_BYTES,"rxBytesPerSec":$RX_RATE,"txBytesPerSec":$TX_RATE,"dayKey":"$DAY_KEY","rxBytesToday":$DAY_RX,"txBytesToday":$DAY_TX,"monthKey":"$MONTH_KEY","rxBytesMonth":$MONTH_RX,"txBytesMonth":$MONTH_TX,"budgetBytes":${W}},"services":{`+G+"}}","JSON","mv -f /var/lib/ts-cloud/metrics.json.tmp /var/lib/ts-cloud/metrics.json",'ALERTS=""',`if awk -v l="$LOAD" -v c="$CPUS" -v t=${J} 'BEGIN{exit !(c>0 && l/c > t)}'; then ALERTS="$ALERTS load=$LOAD/${J}xCPU"; fi`,`if [ "\${MEM_PCT:-0}" -ge ${Z} ]; then ALERTS="$ALERTS mem=\${MEM_PCT}%"; fi`,`if [ "\${DISK_PCT:-0}" -ge ${Q} ]; then ALERTS="$ALERTS disk=\${DISK_PCT}%"; fi`,"PREV=$(cat /var/lib/ts-cloud/alert-state 2>/dev/null || echo ok)",'if [ -n "$ALERTS" ]; then',' if [ "$PREV" != alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "⚠️ $(hostname): resource alert —$ALERTS" || true; fi'," echo alert > /var/lib/ts-cloud/alert-state","else",' if [ "$PREV" = alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "✅ $(hostname): resource usage back to normal" || true; fi'," echo ok > /var/lib/ts-cloud/alert-state","fi",...W>0?["BW_TOTAL=$(( MONTH_RX + MONTH_TX ))",`BW_PCT=$(( BW_TOTAL * 100 / ${W} ))`,"BW_PREV=$(cat /var/lib/ts-cloud/bandwidth-alert-state 2>/dev/null || echo ok)",`if [ "$BW_PCT" -ge ${Y} ]; then`,` if [ "$BW_PREV" != alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "⚠️ $(hostname): bandwidth at \${BW_PCT}% of the ${q} TB monthly allowance ($MONTH_KEY)" || true; fi`," echo alert > /var/lib/ts-cloud/bandwidth-alert-state","else",' if [ "$BW_PREV" = alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "✅ $(hostname): bandwidth back under the monthly allowance (${BW_PCT}%)" || true; fi'," echo ok > /var/lib/ts-cloud/bandwidth-alert-state","fi"]:[],"TS_CLOUD_METRICS_EOF","chmod +x /usr/local/bin/ts-cloud-metrics.sh","cat > /etc/systemd/system/ts-cloud-metrics.service <<'TS_CLOUD_METRICS_SVC_EOF'","[Unit]","Description=ts-cloud metrics collector","","[Service]","Type=oneshot","ExecStart=/usr/local/bin/ts-cloud-metrics.sh","TS_CLOUD_METRICS_SVC_EOF","cat > /etc/systemd/system/ts-cloud-metrics.timer <<'TS_CLOUD_METRICS_TMR_EOF'","[Unit]","Description=Run ts-cloud metrics collector every minute","","[Timer]","OnCalendar=*-*-* *:*:00","AccuracySec=1s","RandomizedDelaySec=5s","Persistent=true","","[Install]","WantedBy=timers.target","TS_CLOUD_METRICS_TMR_EOF","systemctl daemon-reload","systemctl enable --now ts-cloud-metrics.timer","systemctl start ts-cloud-metrics.service"]}var M4={"opcache.enable":"1","opcache.enable_cli":"1","opcache.memory_consumption":"256","opcache.interned_strings_buffer":"16","opcache.max_accelerated_files":"20000","opcache.validate_timestamps":"0","opcache.revalidate_freq":"0","opcache.save_comments":"1","opcache.fast_shutdown":"1",realpath_cache_size:"4096K",realpath_cache_ttl:"600"},O4="127.0.0.1:9074";function K1($){return O4}function V4($={}){let z=$.versions?.length?$.versions:["8.3"];return $.default&&z.includes($.default)?$.default:z[0]}function F4($={}){return{...$.optimizeForProduction===!1?{}:{...M4},...$.ini||{}}}function B4($={}){let z=F4($),J=Object.keys(z);if(J.length===0)return[];let Z=J.map((q)=>`${q}=${z[q]}`),Q="ts-cloud-managed";return[C0(),"TS_CLOUD_SCAN_DIR=$(php -i 2>/dev/null | awk -F' => ' '/^Scan this dir for additional .ini files/{print $2}' | head -1)",`TS_CLOUD_LOADED_INI=$(php -r 'echo php_ini_loaded_file() ?: "";' 2>/dev/null)`,'if [ -n "$TS_CLOUD_SCAN_DIR" ] && [ "$TS_CLOUD_SCAN_DIR" != "(none)" ]; then',' mkdir -p "$TS_CLOUD_SCAN_DIR"',' TS_CLOUD_PHP_INI="$TS_CLOUD_SCAN_DIR/zz-ts-cloud.ini"',` cat > "$TS_CLOUD_PHP_INI" <<'TS_CLOUD_PHPINI_EOF'`,`; ${Q} — production PHP tuning`,...Z,"TS_CLOUD_PHPINI_EOF","else",' if [ -z "$TS_CLOUD_LOADED_INI" ]; then'," TS_CLOUD_INI_DIR=$(php -i 2>/dev/null | awk -F' => ' '/^Configuration File \\(php.ini\\) Path/{print $2}' | head -1)",' TS_CLOUD_LOADED_INI="$TS_CLOUD_INI_DIR/php.ini"',' mkdir -p "$TS_CLOUD_INI_DIR"',' touch "$TS_CLOUD_LOADED_INI"'," fi",` sed -i '/; ${Q} BEGIN/,/; ${Q} END/d' "$TS_CLOUD_LOADED_INI"`,` cat >> "$TS_CLOUD_LOADED_INI" <<'TS_CLOUD_PHPINI_EOF'`,`; ${Q} BEGIN`,...Z,`; ${Q} END`,"TS_CLOUD_PHPINI_EOF","fi",`(cd ${l} && pantry restart php-fpm) 2>/dev/null || true`]}function X$($={}){let z=V4($),J=$.installNginx!==!1,Z=$.installComposer!==!1,Q=[`php.net@${z}`];if(Z)Q.push("getcomposer.org");if(J)Q.push("nginx.org");return[...j0(Q),...W$(["php-fpm"]),...B4($)]}function p$($,z){if(!$)return[];let J=[];if($.template&&z?.[$.template])J.push(...z[$.template]);if($.serverSnippet)J.push(...$.serverSnippet);return J}function U4($){if(!$)return"";let z=typeof $==="object"?$:{},Z=[`max-age=${z.maxAge??31536000}`];if(z.includeSubDomains??!0)Z.push("includeSubDomains");if(z.preload)Z.push("preload");return` add_header Strict-Transport-Security "${Z.join("; ")}" always;`}function C4($){if(!$||!$.allow?.length&&!$.deny?.length)return[];let z=[];for(let J of $.deny||[])z.push(` deny ${J};`);if($.allow?.length){for(let J of $.allow)z.push(` allow ${J};`);z.push(" deny all;")}return z}function H1($){return`/etc/nginx/.htpasswd-${$}`}var L4=new Set(["laravel","php","statamic","wordpress"]);function x4($){return L4.has($)}function D4($){return $==="laravel"||$==="statamic"?"public":""}function w4($,z){let J=$.replace(/\/+$/,""),Z=z.replace(/^\/+|\/+$/g,"");return Z?`${J}/${Z}`:J}function A4($){let z=$.type??"laravel",J=$.webDirectory??D4(z),Z=w4($.appDir,J),Q=x4(z),q=$.phpVersion??"8.3",Y=[` root ${Z};`,"",' add_header X-Frame-Options "SAMEORIGIN";',' add_header X-Content-Type-Options "nosniff";'],W=U4($.hsts);if(W)Y.push(W);for(let j of C4($.security))Y.push(j);if(Y.push("",` index ${Q?"index.php index.html":"index.html index.htm"};`,""," charset utf-8;",""),$.clientMaxBodySize)Y.push(` client_max_body_size ${$.clientMaxBodySize};`,"");if($.auth)Y.push(` auth_basic "${$.auth.realm||"Restricted"}";`,` auth_basic_user_file ${H1($.siteName)};`,"");for(let[j,G]of Object.entries($.redirects||{}))Y.push(` location = ${j} { return 301 ${G}; }`);if(Object.keys($.redirects||{}).length>0)Y.push("");if(Q){if(Y.push(" location / {"," try_files $uri $uri/ /index.php?$query_string;"," }",""," location = /favicon.ico { access_log off; log_not_found off; }"," location = /robots.txt { access_log off; log_not_found off; }",""," error_page 404 /index.php;",""," location ~ \\.php$ {",` fastcgi_pass ${$.fastcgiPass??K1(q)};`," fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;"," include fastcgi_params;"," }",""," location ~ /\\.(?!well-known).* {"," deny all;"," }"),z==="wordpress")Y.push(""," location = /xmlrpc.php { deny all; }"," location ~* /(?:wp-config\\.php|readme\\.html|license\\.txt)$ { deny all; }"," location ~* /wp-content/uploads/.*\\.php$ { deny all; }")}else if(z==="spa")Y.push(" location / {"," try_files $uri $uri/ /index.html;"," }");else Y.push(" location / {"," try_files $uri $uri/ =404;"," }");if($.serverSnippet&&$.serverSnippet.length>0){Y.push("");for(let j of $.serverSnippet)Y.push(j?` ${j}`:"")}return Y}function R4($){let z=[$.domain,...$.aliases||[]].filter(Boolean);for(let q of z)if(!/^(?=.{1,253}$)(?:\*\.)?[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i.test(q.trim()))throw Error(`Refusing to build a vhost: '${q}' is not a valid hostname.`);if(!z.length)throw Error("Refusing to build a vhost: no server_name (domain) was given.");let J=z.join(" "),Z=A4($);if($.ssl){let q=["server {"," listen 80;"," listen [::]:80;",` server_name ${J};`," return 301 https://$host$request_uri;","}"],Y=["server {"," listen 443 ssl;"," listen [::]:443 ssl;",` server_name ${J};`,` ssl_certificate ${$.ssl.certPath};`,` ssl_certificate_key ${$.ssl.keyPath};`,...$.tlsProtocols?.length?[` ssl_protocols ${$.tlsProtocols.join(" ")};`]:[],"",...Z,"}"];return`${[...q,"",...Y].join(`
|
|
8
|
+
`)}
|
|
9
|
+
`}return`${["server {"," listen 80;"," listen [::]:80;",` server_name ${J};`,...Z,"}"].join(`
|
|
10
|
+
`)}
|
|
11
|
+
`}function a$($){let z=`/etc/nginx/sites-available/${$.siteName}`,J=`/etc/nginx/sites-enabled/${$.siteName}`,Z=R4($),Q=[...r$()];if($.auth){let q=H1($.siteName),Y=(G)=>G.split("'").join("'\\''"),W=Y($.auth.password),j=Y($.auth.username);Q.push(`TS_CLOUD_HTPASS=$(openssl passwd -apr1 '${W}')`,`printf '%s:%s\\n' '${j}' "$TS_CLOUD_HTPASS" > ${q}`,`chmod 640 ${q}`,`chown root:www-data ${q} 2>/dev/null || true`)}return Q.push(`cat > ${z} <<'TS_CLOUD_NGINX_EOF'`,Z.replace(/\n$/,""),"TS_CLOUD_NGINX_EOF",`ln -sf ${z} ${J}`,"rm -f /etc/nginx/sites-enabled/default",`${H0} -t`,"systemctl reload ts-cloud-nginx 2>/dev/null || systemctl restart ts-cloud-nginx 2>/dev/null || true"),Q}var H0="/usr/local/bin/ts-cloud-nginx";function r$($="/opt/pantry"){return[...Y$(),...j0(["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 > ${H0} <<'TS_CLOUD_NGINXBIN_EOF'`,"#!/bin/sh",`eval "$(cd ${$} && 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 ${H0}`,"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=${H0} -t`,`ExecStart=${H0} -g 'daemon off;'`,`ExecReload=${H0} -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 a0($,z){return!$.events||$.events.includes(z)}async function n$($,z,J,Z={}){if(!$)return[];let Q=Z.fetchImpl??globalThis.fetch,q=[],Y=[],W=(j,G)=>Q(j,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(G)}).catch(()=>{return});if($.slack?.webhookUrl&&a0($,z))q.push("slack"),Y.push(W($.slack.webhookUrl,{text:J}));if($.discord?.webhookUrl&&a0($,z))q.push("discord"),Y.push(W($.discord.webhookUrl,{content:J}));if($.telegram?.botToken&&$.telegram.chatId&&a0($,z)){q.push("telegram");let j=`https://api.telegram.org/bot${$.telegram.botToken}/sendMessage`;Y.push(W(j,{chat_id:$.telegram.chatId,text:J}))}if($.webhook?.url&&a0($,z))if(q.push("webhook"),($.webhook.method||"POST")==="GET"){let j=$.webhook.url.includes("?")?"&":"?",G=`${$.webhook.url}${j}event=${encodeURIComponent(z)}&message=${encodeURIComponent(J)}`;Y.push(Q(G,{method:"GET"}).catch(()=>{return}))}else Y.push(W($.webhook.url,{event:z,message:J}));if($.email?.to&&a0($,z))q.push("email"),Y.push(E4($.email,z,J));return await Promise.all(Y),q}async function E4($,z,J){try{await(await import("./chunk-0k1cs6pp.js")).email.send({to:$.to,from:$.from,subject:`[ts-cloud] ${z}`,text:J})}catch{}}function X1($,z){return z??$}function y0($){if(!$)return[];let z=[];if($.slack?.webhookUrl)z.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"text\\":\\"$MSG\\"}" ${$.slack.webhookUrl} || true`);if($.discord?.webhookUrl)z.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"content\\":\\"$MSG\\"}" ${$.discord.webhookUrl} || true`);if($.telegram?.botToken&&$.telegram.chatId)z.push(`curl -fsS -X POST "https://api.telegram.org/bot${$.telegram.botToken}/sendMessage" --data-urlencode "chat_id=${$.telegram.chatId}" --data-urlencode "text=$MSG" || true`);if($.webhook?.url)z.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"message\\":\\"$MSG\\"}" ${$.webhook.url} || true`);if(z.length===0)return[];return["cat > /usr/local/bin/ts-cloud-notify <<'TS_CLOUD_NOTIFY_EOF'","#!/bin/bash",'MSG="$1"',...z,"TS_CLOUD_NOTIFY_EOF","chmod +x /usr/local/bin/ts-cloud-notify"]}function i$($,z){return`/var/www/${$}-${z}`}var _4=new Set(["laravel","php","statamic","wordpress"]);function r0($){return $.type!=null&&_4.has($.type)}function t$($){let z=$.proxyTo;if(z==null)return[];return(Array.isArray(z)?z:[z]).map((Z)=>String(Z).trim()).filter((Z)=>Z.length>0)}function k4($){return t$($).length>0}function V1($){if($.deploy)return $.deploy;if(r0($))return"server";if($.start)return"server";return"bucket"}function $0($){if($.redirect)return"redirect";if(k4($))return"proxy";if(r0($))return"server-php";if(V1($)==="bucket")return"bucket";return $.start?"server-app":"server-static"}function T4($){return $.infrastructure?.compute!=null||Boolean($.cloud?.attachTo?.trim())}function B9($,z={}){let J=[],Z=[],Q=$.sites||{},q=T4($),Y=O1($);if(Y)J.push(Y);let W=new Map;for(let[j,G]of Object.entries(Q)){if(!G)continue;let H=V1(G),M=$0(G);if(M==="redirect"){if(!G.domain)J.push(`Site '${j}' is a redirect site but has no \`domain\` to redirect from.`);if(!(typeof G.redirect==="string"?G.redirect:G.redirect?.to))J.push(`Site '${j}' is a redirect site but has no redirect target (\`redirect\` / \`redirect.to\`).`);if(!q)J.push(`Site '${j}' is a redirect site but no \`infrastructure.compute\` is configured to host the gateway that serves the redirect.`);let K=[];if(G.start)K.push("start");if(G.root)K.push("root");if(G.proxyTo)K.push("proxyTo");if(K.length>0)Z.push(`Site '${j}' is a redirect site but also sets ${K.join(", ")}. These are ignored.`);continue}if(M==="proxy"){if(!G.domain)J.push(`Site '${j}' is a proxy site but has no \`domain\` to route from.`);if(!q)J.push(`Site '${j}' is a proxy site but no \`infrastructure.compute\` is configured to host the gateway that forwards it.`);let X=[];if(G.start)X.push("start");if(G.root)X.push("root");if(typeof G.port==="number")X.push("port");if(G.build)X.push("build");if(G.preStart&&G.preStart.length>0)X.push("preStart");if(X.length>0)Z.push(`Site '${j}' sets \`proxyTo\`, so ts-cloud ships and supervises nothing for it. ${X.join(", ")} ${X.length===1?"is":"are"} ignored — remove ${X.length===1?"it":"them"}, or drop \`proxyTo\` to let ts-cloud own the service.`);continue}if(H==="server"&&!G.start&&!G.root){J.push(`Site '${j}' sets deploy:'server' but declares neither \`start\` (dynamic app) nor \`root\` (static site to serve). Add one.`);continue}if(M==="server-php"){if(!q)J.push(`Site '${j}' is a PHP site (type:'${G.type}') but no \`infrastructure.compute\` is configured. Add a server (infrastructure.compute) with PHP provisioning.`);if(!G.repository?.url)J.push(`Site '${j}' is a PHP site (type:'${G.type}') but has no \`repository.url\` to clone. PHP sites deploy via git.`)}else if(M==="server-app"){if(!q)J.push(`Site '${j}' deploys to a server (deploy:'server'${G.deploy?"":" inferred from `start`"}) but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`);if(typeof G.port==="number"){let X=z.occupiedPorts?.get(G.port);if(X)J.push(`Site '${j}' wants port ${G.port}, which project '${X}' already serves on this box. Attached projects share one port namespace. Give '${j}' a free port, or let the attach allocate one.`);let K=W.get(G.port);if(K)J.push(`Sites '${K}' and '${j}' both use port ${G.port}. Server apps sharing a box must use distinct ports.`);else W.set(G.port,j)}}else if(M==="server-static"){if(!G.root)J.push(`Site '${j}' is a server static site (deploy:'server', no \`start\`) but has no \`root\` directory to serve.`);if(!q)J.push(`Site '${j}' deploys to a server (deploy:'server') but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`)}else{if(!G.root)J.push(`Site '${j}' deploys to a bucket but has no \`root\` directory to upload.`);let X=[];if(G.start)X.push("start");if(typeof G.port==="number")X.push("port");if(G.preStart&&G.preStart.length>0)X.push("preStart");if(X.length>0)Z.push(`Site '${j}' deploys to a bucket but sets server-only field(s): ${X.join(", ")}. These are ignored. Set deploy:'server' to use them.`)}}return{errors:J,warnings:Z}}function U9($){let z=$0($);return z!=="bucket"&&z!=="redirect"&&z!=="proxy"}function C9($){return $0($)==="bucket"}function L9($,z){if(M1($)==="serverless")return!0;let J=Object.entries($.sites??{}).filter(([,Q])=>Q!=null),Z=z?J.filter(([Q])=>Q===z):J;if(Z.length===0)return!0;return!Z.every(([,Q])=>{let q=$0(Q);return q==="redirect"||q==="proxy"})}var e$="/etc/rpx/certs";function $z($){return $.split(".").length===2}function y4($,z={}){let J=new Set;for(let Z of Object.values($)){if(!Z?.domain)continue;if($0(Z)==="bucket")continue;J.add(Z.domain)}if(z.autoWww!==!1)for(let Z of[...J]){if(!$z(Z))continue;J.add(`www.${Z}`)}return[...J]}var P4=["1.1.1.1","8.8.8.8"],I4="/var/www/acme-challenge";function S4($){if(typeof $==="string")return{to:$};let z={to:$.to};if($.status!=null)z.status=$.status;if($.preservePath!=null)z.preservePath=$.preservePath;return z}function f4($){let z=$.auth;if(!z||z.enabled===!1||!z.password)return;return{username:z.username||"admin",password:z.password,...z.realm?{realm:z.realm}:{}}}function F1($){if(!$||$==="/")return;let z=`/${$}`.replace(/\/+/g,"/").replace(/\/+$/,"");if(!z.startsWith("/"))z=`/${z}`;return z===""||z==="/"?void 0:z}function o$($,z){let Z=(z?`${$}${z}`:$).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return Z.length>0?Z:"rpx"}function b4($,z){if(!z||z.length===0)return`localhost:${$}`;return z.map((J)=>`${J.privateIp??J.publicIp}:${$}`)}function B1($,z,J){let Z=(z.wwwRoot??"/var/www").replace(/\/+$/,""),Q=z.slug??"app",q=z.proxy.certsDir??e$,Y=z.proxy.loadBalancer,W=[],j=new Set;for(let[X,K]of Object.entries($)){if(!K||!K.domain)continue;let O=$0(K);if(O==="bucket")continue;let L=F1(K.path),B=o$(K.domain,L),U=f4(K);if(O==="redirect"){W.push({to:K.domain,path:L,redirect:S4(K.redirect),id:B,...U?{auth:U}:{}}),j.add(K.domain);continue}if(O==="proxy"){let F=t$(K);if(F.length===0)continue;let V=F.length===1?F[0]:F;W.push({to:K.domain,path:L,from:V,id:B,...U?{auth:U}:{},...Array.isArray(V)&&Y?{loadBalancer:Y}:{}}),j.add(K.domain);continue}if(O==="server-app"){if(typeof K.port!=="number")continue;let F=b4(K.port,J);W.push({to:K.domain,path:L,from:F,id:B,...U?{auth:U}:{},...Array.isArray(F)&&Y?{loadBalancer:Y}:{}})}else W.push({to:K.domain,path:L,static:{dir:`${Z}/${Q}-${X}/current`,spa:K.spa??!1,pathRewriteStyle:K.pathRewriteStyle??"directory"},cleanUrls:K.pathRewriteStyle!=="flat",...U?{auth:U}:{},id:B});j.add(K.domain)}if(z.proxy.autoWww!==!1)for(let X of[...j]){if(!$z(X))continue;let K=`www.${X}`;if(j.has(K))continue;W.push({to:K,redirect:{to:`https://${X}`},id:o$(K)}),j.add(K)}W.sort((X,K)=>{if(X.to!==K.to)return X.to.localeCompare(K.to);return(K.path?.length??0)-(X.path?.length??0)});let G={proxies:W,productionCerts:{certsDir:q,certsDirServerNames:[...j]},https:!0,hostsManagement:!1,cleanup:{hosts:!1,certs:!1}};if(z.proxy.onDemandTls&&j.size>0)G.onDemandTls={enabled:!0,allowedSuffixes:[...j],email:z.proxy.onDemandTlsEmail,certsDir:q,staging:z.proxy.onDemandTlsStaging??!1};if(z.proxy.onDemandTls)G.acmeChallengeWebroot=z.proxy.acmeWebroot??I4;let H=z.proxy.cdn,M=H?.frontedHosts?.length?H.frontedHosts:[...j];if(H?.secret&&M.length>0)G.originGuard={header:H.secretHeader??"X-Origin-Verify",value:H.secret,hosts:M};return G}function M0($,z){return B1($,z)}function I0($,z,J){return B1($,J,z)}function h4($){return`// Generated by ts-cloud — rpx reverse-proxy gateway.
|
|
12
|
+
// Routes are derived from the \`sites\` model on every \`buddy deploy\`.
|
|
13
|
+
import { startProxies } from '@stacksjs/rpx'
|
|
14
|
+
|
|
15
|
+
const config = ${JSON.stringify($,null,2)} as const
|
|
16
|
+
|
|
17
|
+
// Verbose is the hard default for ts-cloud-installed gateways (RPX_VERBOSE=false
|
|
18
|
+
// opts out) — without it rpx's TLS/routing diagnostics never reach the journal.
|
|
19
|
+
await startProxies({ verbose: process.env.RPX_VERBOSE !== 'false', ...config } as any)
|
|
20
|
+
`}function o($){return $?.webServer==="rpx"||$?.proxy?.engine==="rpx"}var i0="/etc/rpx",d="/opt/rpx-gateway",s$="/etc/rpx/gateway.ts",n0="/etc/rpx/gateway",X0="rpx-gateway.service",L0="/etc/rpx/sites.d";function m4($=L0,z=e$){return`// Generated by ts-cloud — rpx gateway assembler.
|
|
21
|
+
// Merges every app's fragment in ${$} so independent deploys compose
|
|
22
|
+
// without clobbering each other. Each deploy writes only its own <slug>.json.
|
|
23
|
+
import { startProxies } from '@stacksjs/rpx'
|
|
24
|
+
import { readdirSync, readFileSync } from 'node:fs'
|
|
25
|
+
|
|
26
|
+
const dir = ${JSON.stringify($)}
|
|
27
|
+
const proxies = []
|
|
28
|
+
const seen = new Set()
|
|
29
|
+
const owners = new Map()
|
|
30
|
+
const suffixes = new Set()
|
|
31
|
+
const guardHosts = new Set()
|
|
32
|
+
let email
|
|
33
|
+
let certsDir = ${JSON.stringify(z)}
|
|
34
|
+
let acmeChallengeWebroot
|
|
35
|
+
let guard
|
|
36
|
+
let anyProduction = false
|
|
37
|
+
let files = []
|
|
38
|
+
try { files = readdirSync(dir).filter(n => n.endsWith('.json')).sort() } catch {}
|
|
39
|
+
for (const f of files) {
|
|
40
|
+
let frag
|
|
41
|
+
// Fragments are written atomically (temp + rename by ts-cloud), so a parse
|
|
42
|
+
// failure here means a genuinely corrupt fragment, not a mid-write read. Log
|
|
43
|
+
// it LOUD — a silent skip drops that app's whole host from the routing table,
|
|
44
|
+
// which then answers 404 until someone notices. We still continue so one bad
|
|
45
|
+
// fragment can't take every other app down, but the drop is now visible.
|
|
46
|
+
try { frag = JSON.parse(readFileSync(dir + '/' + f, 'utf8')) }
|
|
47
|
+
catch (err) { console.error('[rpx-assembler] SKIPPING malformed fragment ' + f + ' — its host(s) will 404 until fixed: ' + err); continue }
|
|
48
|
+
for (const p of frag.proxies ?? []) {
|
|
49
|
+
const key = p.id || (p.to + (p.path ?? ''))
|
|
50
|
+
if (seen.has(key)) {
|
|
51
|
+
console.warn('[rpx-assembler] duplicate route ' + key + ' in ' + f + ' ignored; first declared by ' + owners.get(key))
|
|
52
|
+
continue
|
|
53
|
+
}
|
|
54
|
+
seen.add(key)
|
|
55
|
+
owners.set(key, f)
|
|
56
|
+
proxies.push(p)
|
|
57
|
+
}
|
|
58
|
+
for (const s of frag.onDemandTls?.allowedSuffixes ?? []) suffixes.add(s)
|
|
59
|
+
email ??= frag.onDemandTls?.email
|
|
60
|
+
// One gateway, one ACME directory: production wins any disagreement between
|
|
61
|
+
// co-tenants, and a fragment predating the flag counts as production. A
|
|
62
|
+
// staging cert chains to an untrusted root, so defaulting the other way
|
|
63
|
+
// breaks every client of every tenant that wanted a real cert.
|
|
64
|
+
if (frag.onDemandTls && frag.onDemandTls.staging !== true) anyProduction = true
|
|
65
|
+
if (frag.productionCerts?.certsDir) certsDir = frag.productionCerts.certsDir
|
|
66
|
+
acmeChallengeWebroot ??= frag.acmeChallengeWebroot
|
|
67
|
+
if (frag.originGuard) {
|
|
68
|
+
// One gateway means one origin-guard secret (rpx takes a single
|
|
69
|
+
// header/value). A tenant whose secret disagrees with the adopted one must
|
|
70
|
+
// NOT have its hosts guarded: its CDN would send a different value, the
|
|
71
|
+
// gateway would reject every request, and a working host would go dark.
|
|
72
|
+
// Unguarded is weaker but serving, and the mismatch is logged.
|
|
73
|
+
guard ??= { header: frag.originGuard.header, value: frag.originGuard.value }
|
|
74
|
+
if (frag.originGuard.header === guard.header && frag.originGuard.value === guard.value) {
|
|
75
|
+
for (const h of frag.originGuard.hosts ?? []) guardHosts.add(h)
|
|
76
|
+
}
|
|
77
|
+
else {
|
|
78
|
+
console.warn('[rpx-assembler] origin-guard secret in ' + f + ' differs from the one already in force; its hosts stay unguarded rather than rejecting all traffic')
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
const config = {
|
|
83
|
+
proxies,
|
|
84
|
+
productionCerts: {
|
|
85
|
+
certsDir,
|
|
86
|
+
// A shared host's cert directory also contains mail and retired-site PEMs.
|
|
87
|
+
// Keep those files on disk for their owners, but do not turn them into live
|
|
88
|
+
// OpenSSL SNI contexts when no current route can select them.
|
|
89
|
+
certsDirServerNames: [...new Set(proxies.map(p => p.to).filter(Boolean))],
|
|
90
|
+
},
|
|
91
|
+
https: true,
|
|
92
|
+
hostsManagement: false,
|
|
93
|
+
cleanup: { hosts: false, certs: false },
|
|
94
|
+
// Verbose is the hard default for ts-cloud-installed gateways: without it,
|
|
95
|
+
// rpx's TLS/routing diagnostics (tlsx on-demand 'refused issuance',
|
|
96
|
+
// 'issuance failed', 'adopted existing on-disk cert') never reach the systemd
|
|
97
|
+
// journal and a production TLS failure looks like "nothing happens". Silence
|
|
98
|
+
// it by setting RPX_VERBOSE=false on the systemd unit.
|
|
99
|
+
verbose: process.env.RPX_VERBOSE !== 'false',
|
|
100
|
+
...(suffixes.size > 0 ? { onDemandTls: { enabled: true, allowedSuffixes: [...suffixes], email, certsDir, staging: !anyProduction } } : {}),
|
|
101
|
+
...(acmeChallengeWebroot ? { acmeChallengeWebroot } : {}),
|
|
102
|
+
...(guard ? { originGuard: { header: guard.header, value: guard.value, hosts: [...guardHosts] } } : {}),
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
await startProxies(config)
|
|
106
|
+
`}function P0($,z,J,Z="0644"){return[`__tsc_tmp="$(mktemp "${$}.XXXXXX")"`,`cat > "$__tsc_tmp" <<'${J}'`,z,J,`mv -f "$__tsc_tmp" ${$}`,`chmod ${Z} ${$}`]}function v4($){return`'${$.replaceAll("'","'\\''")}'`}function U1($,z,J,Z){if(!Z.preserveManagementDashboardRoutes)return P0($,z,J,"0600");let Q=`
|
|
107
|
+
const { readFileSync, writeFileSync } = require('node:fs')
|
|
108
|
+
const currentPath = process.env.TS_CLOUD_RPX_CURRENT_FRAGMENT
|
|
109
|
+
const candidatePath = process.env.TS_CLOUD_RPX_CANDIDATE_FRAGMENT
|
|
110
|
+
const isDashboard = route => /^(?:dashboard|cloud)\\./i.test(String(route?.to || ''))
|
|
111
|
+
const current = JSON.parse(readFileSync(currentPath, 'utf8'))
|
|
112
|
+
const candidate = JSON.parse(readFileSync(candidatePath, 'utf8'))
|
|
113
|
+
const retained = Array.isArray(current.proxies) ? current.proxies.filter(isDashboard) : []
|
|
114
|
+
const next = Array.isArray(candidate.proxies) ? candidate.proxies.filter(route => !isDashboard(route)) : []
|
|
115
|
+
candidate.proxies = [...next, ...retained]
|
|
116
|
+
writeFileSync(candidatePath, JSON.stringify(candidate, null, 2) + '\\n', { mode: 0o600 })
|
|
117
|
+
`.trim();return[`__tsc_fragment_candidate="$(mktemp "${$}.candidate.XXXXXX")"`,`cat > "$__tsc_fragment_candidate" <<'${J}'`,z,J,'chmod 0600 "$__tsc_fragment_candidate"',`if [ -f ${$} ]; then TS_CLOUD_RPX_CURRENT_FRAGMENT=${$} TS_CLOUD_RPX_CANDIDATE_FRAGMENT="$__tsc_fragment_candidate" ${Z.bunBin} -e ${v4(Q)}; fi`,`mv -f "$__tsc_fragment_candidate" ${$}`,`chmod 0600 ${$}`]}function zz($){return`rpx-cert-renew-${($||"app").replace(/[^a-z0-9._-]+/gi,"-")}.service`}function Jz($){let z=new Set;for(let J of $.proxies){let Z=J.to;if(!Z||Z.startsWith("*")||Z.includes(":")||!Z.includes("."))continue;z.add(Z)}return[...z]}function u4($){let{config:z,proxy:J}=$,Z=z.acmeChallengeWebroot,Q=Jz(z);if(!J.onDemandTls||!Z||Q.length===0)return[];let q=$.bunBin??"/usr/local/bin/bun",Y=J.version??"latest",W=z.productionCerts.certsDir,j=J.onDemandTlsEmail??`webmaster@${Q[0]}`,G=`${q} ${d}/node_modules/@stacksjs/tlsx/dist/bin/cli.js`,H=Q.join(","),M=Q.join(" "),X=($.slug||"app").replace(/[^a-z0-9._-]+/gi,"-"),K=`${i0}/renew-certs-${X}.sh`,O=zz(X),L=`rpx-cert-renew-${X}.timer`,B=["#!/bin/sh","# Generated by ts-cloud — issue/renew rpx gateway TLS certs via tlsx http-01.","# The running gateway serves the challenge from $WEBROOT on :80, so this needs","# no downtime and no DNS credentials. Reloads the gateway only if a cert changed.","set -u",`CERTS='${W}'`,`WEBROOT='${Z}'`,`EMAIL='${j}'`,`TLSX="${G}"`,`BUN='${q}'`,`DOMAINS='${H}'`,"DNS_ATTEMPTS='24'","DNS_DELAY_SECONDS='5'",`DNS_RESOLVERS='${P4.join(" ")}'`,"dns_resolves() {",' d="$1"'," for ns in $DNS_RESOLVERS; do",` if $BUN --eval "const{Resolver}=require('node:dns');const r=new Resolver();r.setServers([process.argv[1]]);r.resolve4(process.argv[2],e=>process.exit(e?1:0))" "$ns" "$d" >/dev/null 2>&1; then`," return 0"," fi"," done",' getent ahosts "$d" >/dev/null 2>&1',"}","wait_for_dns() {",' d="$1"'," attempt=1",' while ! dns_resolves "$d"; do',' if [ "$attempt" -ge "$DNS_ATTEMPTS" ]; then',' echo "DNS for $d did not become resolvable after $DNS_ATTEMPTS attempts" >&2'," return 1"," fi",' echo "Waiting for public DNS before ACME: $d (attempt $attempt/$DNS_ATTEMPTS)"',' sleep "$DNS_DELAY_SECONDS"'," attempt=$((attempt + 1))"," done","}",'before=$(cat "$CERTS"/*.crt 2>/dev/null | sha256sum)',`for d in ${M}; do`,' if [ ! -s "$CERTS/$d.crt" ]; then',' if wait_for_dns "$d"; then',' $TLSX acme:issue -d "$d" --method http-01 --webroot "$WEBROOT" --dir "$CERTS" --prod --email "$EMAIL" || echo "issue $d failed (non-fatal)"'," else",' echo "issue $d skipped until DNS resolves (non-fatal)"'," fi"," # rpx reloads its SNI set when a PEM appears. Complete that reload"," # before the next hostname starts http-01, or :80 can disappear in"," # the middle of the following challenge on a multi-domain deploy.",` [ -s "$CERTS/$d.crt" ] && systemctl restart ${X0}`," fi","done",'$TLSX acme:renew --domains "$DOMAINS" --method http-01 --webroot "$WEBROOT" --dir "$CERTS" --days 30 --prod --email "$EMAIL" || echo "renew: some domains failed (non-fatal)"','rm -f "$CERTS"/*.chain.crt','after=$(cat "$CERTS"/*.crt 2>/dev/null | sha256sum)',`[ "$before" = "$after" ] || systemctl restart ${X0}`].join(`
|
|
118
|
+
`),U=["[Unit]",`Description=Issue/renew rpx gateway TLS certs for ${X} (tlsx http-01)`,`After=network-online.target ${X0}`,"Wants=network-online.target","","[Service]","Type=oneshot",`ExecStart=${K}`].join(`
|
|
119
|
+
`),F=["[Unit]",`Description=Daily rpx gateway TLS cert issuance/renewal for ${X}`,"","[Timer]","OnCalendar=*-*-* 03:30:00","RandomizedDelaySec=1h","Persistent=true","","[Install]","WantedBy=timers.target"].join(`
|
|
120
|
+
`);return[`mkdir -p ${Z}`,`(cd ${d} && ${q} add @stacksjs/tlsx@${Y}) || true`,...P0(K,B,"TS_CLOUD_RENEW_EOF"),`chmod +x ${K}`,...P0(`/etc/systemd/system/${O}`,U,"TS_CLOUD_RENEW_SVC_EOF"),...P0(`/etc/systemd/system/${L}`,F,"TS_CLOUD_RENEW_TIMER_EOF"),"systemctl daemon-reload",`systemctl enable --now ${L} || true`,`${K} || true`]}function O0($){let{config:z,proxy:J}=$,Z=$.bunBin??"/usr/local/bin/bun",Q=J.version??"latest",q=z.productionCerts.certsDir,Y=($.slug||"app").replace(/[^a-z0-9._-]+/gi,"-"),W=JSON.stringify({slug:Y,...z},null,2),j=m4(L0,q),H=[`Environment=RPX_UPSTREAM_TIMEOUT=${J.upstreamTimeout??60}`];if(typeof J.maxUpstreamConns==="number")H.push(`Environment=RPX_MAX_UPSTREAM_CONNS=${J.maxUpstreamConns}`);let M=J.memoryHigh??"512M",X=J.memoryMax??"768M";return["set -euo pipefail",`mkdir -p ${i0} ${L0} ${q} ${d}`,`rm -rf ${d}.next ${d}.prev`,`mkdir -p ${d}.next`,`(cd ${d}.next && ${Z} add @stacksjs/rpx@${Q})`,`mv ${d} ${d}.prev`,`mv ${d}.next ${d}`,`rm -rf ${d}.prev`,`ln -sfn ${d}/node_modules ${i0}/node_modules`,...U1(`${L0}/${Y}.json`,W,"TS_CLOUD_RPX_FRAGMENT_EOF",{bunBin:Z,preserveManagementDashboardRoutes:$.preserveManagementDashboardRoutes}),...P0(s$,j,"TS_CLOUD_RPX_EOF"),`${Z} build --production --compile --outfile ${n0}.next ${s$}`,`chmod 0755 ${n0}.next`,`mv -f ${n0}.next ${n0}`,...P0(`/etc/systemd/system/${X0}`,["[Unit]","Description=rpx reverse-proxy gateway (managed by ts-cloud)","After=network.target network-online.target","Wants=network-online.target","","[Service]","Type=simple",`ExecStart=${n0}`,`WorkingDirectory=${d}`,"Environment=BUN_INSTALL=/root/.bun","Environment=APP_ENV=production","Environment=NODE_ENV=production",...H,"MemoryAccounting=true",`MemoryHigh=${M}`,`MemoryMax=${X}`,"CPUWeight=500","IOWeight=500","OOMPolicy=stop","Restart=always","RestartSec=5","StartLimitIntervalSec=120","StartLimitBurst=5",`ExecStartPre=/bin/sh -c 'for p in 80 443; do fuser -k -n tcp "$p" 2>/dev/null || true; done; sleep 1'`,"LimitNOFILE=1048576","AmbientCapabilities=CAP_NET_BIND_SERVICE","","[Install]","WantedBy=multi-user.target"].join(`
|
|
121
|
+
`),"TS_CLOUD_RPX_UNIT_EOF"),"systemctl daemon-reload","systemctl disable --now bun-gateway.service 2>/dev/null || true","systemctl disable --now bun-gateway-renew.timer bun-gateway-renew.service 2>/dev/null || true","rm -f /etc/systemd/system/bun-gateway-renew.timer /etc/systemd/system/bun-gateway-renew.service","systemctl disable --now ts-cloud-nginx.service 2>/dev/null || true",`for timer in /etc/systemd/system/rpx-cert-renew-*.timer; do [ -e "$timer" ] || continue; unit="$(basename "$timer")"; tenant="\${unit#rpx-cert-renew-}"; tenant="\${tenant%.timer}"; [ -f "${L0}/$tenant.json" ] && continue; systemctl disable --now "$unit" 2>/dev/null || true; rm -f "$timer" "/etc/systemd/system/rpx-cert-renew-$tenant.service" "${i0}/renew-certs-$tenant.sh"; done`,`systemctl enable ${X0}`,`systemctl restart ${X0}`,...u4($)]}function t0($){let z=($.slug||"app").replace(/[^a-z0-9._-]+/gi,"-"),J=JSON.stringify({slug:z,...$.config},null,2);return["set -euo pipefail",`mkdir -p ${L0}`,...U1(`${L0}/${z}.json`,J,"TS_CLOUD_RPX_FRAGMENT_EOF",{bunBin:"/usr/local/bin/bun",preserveManagementDashboardRoutes:$.preserveManagementDashboardRoutes}),`systemctl restart ${X0}`]}function S0($=[],z={}){let J=z.path??"/root/.ssh/authorized_keys",Q=[`mkdir -p ${J.replace(/\/[^/]*$/,"")}`,`touch ${J}`,`sed -i '/^${C1("# >>> ts-cloud managed keys >>>")}$/,/^${C1("# <<< ts-cloud managed keys <<<")}$/d' ${J}`];if($.length>0){let q=["# >>> ts-cloud managed keys >>>",...$.map((Y)=>`${Y.publicKey.trim()} ${Y.name}`),"# <<< ts-cloud managed keys <<<"].join(`
|
|
122
|
+
`);Q.push(`cat >> ${J} <<'TS_CLOUD_KEYS_EOF'`,q,"TS_CLOUD_KEYS_EOF",`chmod 600 ${J}`)}return Q}function C1($){return $.replace(/[.*[\]\\/^$]/g,"\\$&")}function w1($,z){let J=`/tmp/ts-cloud-${$}.sh`,Z=`TS_CLOUD_${$.toUpperCase().replace(/[^A-Z0-9]/g,"_")}_EOF`;return[`cat > ${J} <<'${Z}'`,z.replace(/\n$/,""),Z,`chmod +x ${J}`,`bash ${J} || echo "ts-cloud: ${$} setup did not complete; continuing" >&2`,`rm -f ${J}`]}function A1($,z){if($===!1)return;if($===!0||$===void 0)return z;return $}var L1={enabled:!0,ports:[80,443]},g4={mode:"detection",paranoiaLevel:1};function d4($=!0,z=[]){let J=A1($,L1);if(!J||J.enabled===!1)return[];let Z=[...new Set([...J.ports??L1.ports??[],...z])].sort((Q,q)=>Q-q);return w1("ddos",x1({...J,ports:Z}))}function c4($=!0){let z=A1($,g4);if(!z||z.mode==="off")return[];return w1("waf",D1(z))}function R1($={},z=[]){return[...d4($.ddos,z),...c4($.waf)]}function l4($){return`${$}-sftp`}function N1($){return $.port??2222}function p4($){let z=$.sftp.storage;if(z?.type==="efs"&&z.path)return z.path;return`/var/sftp/${$.slug}`}function f0($){return`'${$.split("'").join("'\\''")}'`}function E1($,z){if(z==="aws")return;let J=$.storage;if(J?.type==="s3"||!J&&!!$.bucket)throw Error(`sftp: bucket-backed storage is only available on the aws provider (Transfer Family). On ${z}, use storage: { type: 'efs' } to serve a directory on the server.`);for(let[Q,q]of Object.entries($.users))if(!q.sshPublicKeys?.length)throw Error(`sftp: user ${Q} needs at least one SSH public key`)}function _1($){let{slug:z,sftp:J}=$,Z=l4(z),Q=p4($),q=N1(J),Y="/etc/ts-sftp/host_key",W="/etc/ts-sftp/users",j=J.serviceUser??"ts-sftp",G=[`# --- ts-sftp (${Z}) ---`,`id -u ${j} >/dev/null 2>&1 || useradd --system --home-dir ${f0(Q)} --shell /usr/sbin/nologin ${j}`,'export HOME="${HOME:-/root}"','command -v bun >/dev/null 2>&1 || (curl -fsSL https://bun.sh/install | bash && ln -sf "$HOME/.bun/bin/bun" /usr/local/bin/bun)',`mkdir -p ${f0(Q)} /etc/ts-sftp /etc/ts-sftp/users /opt/ts-sftp`,"chmod 750 /etc/ts-sftp",`cd /opt/ts-sftp && [ -f package.json ] || printf '{"name":"ts-sftp-host","private":true}' > package.json`,`cd /opt/ts-sftp && bun add ts-sftp@${J.version??"latest"} --no-save --production || bun add ts-sftp@${J.version??"latest"}`,`[ -f /etc/ts-sftp/host_key ] || bun /opt/ts-sftp/node_modules/ts-sftp/dist/bin/cli.js keygen --out /etc/ts-sftp/host_key --comment ${f0(`${z}-sftp`)}`,"chmod 600 /etc/ts-sftp/host_key",'BUN_REAL=$(readlink -f "$(command -v bun)")','case "$BUN_REAL" in /root/*) install -m 0755 "$BUN_REAL" /usr/local/bin/ts-sftp-bun; BUN_BIN=/usr/local/bin/ts-sftp-bun;; *) BUN_BIN="$BUN_REAL";; esac'],H=[];for(let[M,X]of Object.entries(J.users)){let K=(X.homeDirectory??M).replace(/^\/+|\/+$/g,"");if(!K||K.split("/").includes(".."))throw Error(`sftp: invalid homeDirectory for user ${M}`);let O=`/etc/ts-sftp/users/${M}.pub`;G.push(`mkdir -p ${f0(`${Q}/${K}`)}`,`printf '%s\\n' ${f0(X.sshPublicKeys.join(`
|
|
123
|
+
`))} > ${O}`,`chmod 644 ${O}`),H.push(`--user ${M}:${O}`)}return G.push(`chown -R ${j}:${j} ${f0(Q)} /etc/ts-sftp`,`cat > /etc/systemd/system/${Z}.service <<TSCLOUD_SFTP_UNIT`,"[Unit]","Description=ts-sftp file transfer server","After=network.target","","[Service]",`User=${j}`,`ExecStart=$BUN_BIN /opt/ts-sftp/node_modules/ts-sftp/dist/bin/cli.js serve --root ${Q} --host-key /etc/ts-sftp/host_key --port ${q}${J.readOnly?" --read-only":""} ${H.join(" ")}`,"Restart=always","RestartSec=2","NoNewPrivileges=true","PrivateTmp=true","ProtectSystem=strict",`ReadWritePaths=${Q}`,"","[Install]","WantedBy=multi-user.target","TSCLOUD_SFTP_UNIT","systemctl daemon-reload",`systemctl enable ${Z}.service`,`systemctl restart ${Z}.service`),G}function k1($){return $?[N1($)]:[]}var a4=[80,443];function M$($={}){if($.enabled===!1)return[];let z=[...new Set([...a4,...$.allowedPorts||[]])].filter((Z)=>Number.isInteger(Z)&&Z>=1&&Z<=65535).sort((Z,Q)=>Z-Q),J=["export DEBIAN_FRONTEND=noninteractive","command -v ufw >/dev/null 2>&1 || apt-get install -y ufw","ufw --force reset","ufw default deny incoming","ufw default allow outgoing","ufw allow OpenSSH"];for(let Z of z)J.push(`ufw allow ${Z}/tcp`);return J.push("ufw --force enable"),J}function o0($){let z=$.infrastructure?.compute??{},J=z.runtime==="php"||!!z.php,Z=J||!!z.managedServices,Q=Z?Y$():[],q=!o(z),Y=J?[...Q,...X$({versions:z.php?.versions,default:z.php?.default,extensions:z.php?.extensions,installNginx:q,optimizeForProduction:z.php?.optimizeForProduction,ini:z.php?.ini}),...q?r$():[]]:void 0,W=[],j=V0($);if(!J&&Z)W.push(...Q);if(W.push(...y0($.notifications)),z.managedServices)W.push(...K$(z.managedServices),...T0(j,z.managedServices));let G=$.infrastructure?.sftp;if(G)E1(G,b0($)),W.push(..._1({slug:$.project.slug,sftp:G}));if(W.push(...M$(z.firewall??(J?{enabled:!0}:{enabled:!1}))),W.push(...R1({ddos:z.ddos,waf:z.waf},z.firewall?.allowedPorts??[])),W.push(...G0(z.autoUpdates??J)),W.push(...K0(z.monitoring??J)),W.push(...S0(z.sshKeys)),z.backups?.enabled)W.push(...H$({database:j,backups:z.backups}));return{runtime:z.runtime||"bun",runtimeVersion:z.runtimeVersion||"latest",phpBox:J,phpProvision:Y,servicesProvision:W.length>0?W:void 0}}function s($={}){let{runtime:z="bun",runtimeVersion:J="latest",systemPackages:Z=[],database:Q,phpProvision:q,servicesProvision:Y,caddyfile:W,rpxProvision:j,baked:G=!1,swapGb:H=2}=$,M=new Set(Z);if(Q==="sqlite")M.add("sqlite3");else if(Q==="mysql")M.add("mysql-client");else if(Q==="postgres")M.add("postgresql-client");let X=`#!/bin/bash
|
|
124
|
+
set -euo pipefail
|
|
125
|
+
`,K=Math.floor(H);if(K>0)X+=`
|
|
126
|
+
# Swap: a swapless box under memory pressure lets the kernel OOM killer choose
|
|
127
|
+
# victims box-wide (the gateway, a tenant app, postgres). A modest swapfile
|
|
128
|
+
# with low swappiness gives the kernel headroom without hurting responsiveness.
|
|
129
|
+
if ! swapon --show=NAME --noheadings 2>/dev/null | grep -qx '/swapfile'; then
|
|
130
|
+
if [ ! -f /swapfile ]; then
|
|
131
|
+
fallocate -l ${K}G /swapfile || dd if=/dev/zero of=/swapfile bs=1M count=${K*1024} status=none
|
|
132
|
+
chmod 600 /swapfile
|
|
133
|
+
mkswap /swapfile >/dev/null
|
|
134
|
+
fi
|
|
135
|
+
swapon /swapfile
|
|
136
|
+
fi
|
|
137
|
+
grep -qE '^/swapfile\\s' /etc/fstab || echo '/swapfile none swap sw 0 0' >> /etc/fstab
|
|
138
|
+
echo 'vm.swappiness=10' > /etc/sysctl.d/99-ts-cloud-swap.conf
|
|
139
|
+
sysctl -w vm.swappiness=10 >/dev/null
|
|
140
|
+
`;if(!G){if(X+=`
|
|
141
|
+
export DEBIAN_FRONTEND=noninteractive
|
|
142
|
+
apt-get update -y
|
|
143
|
+
apt-get upgrade -y
|
|
144
|
+
apt-get install -y curl tar gzip unzip git ca-certificates
|
|
145
|
+
`,M.size>0)X+=`
|
|
146
|
+
apt-get install -y ${[...M].join(" ")}
|
|
147
|
+
`;if(q&&q.length>0)X+=`
|
|
148
|
+
${q.join(`
|
|
149
|
+
`)}
|
|
150
|
+
`;if(Y&&Y.length>0)X+=`
|
|
151
|
+
${Y.join(`
|
|
152
|
+
`)}
|
|
153
|
+
`;if(z==="bun")X+=`
|
|
154
|
+
# cloud-init runs this with \`set -u\` and NO $HOME set. bun's install.sh
|
|
155
|
+
# dereferences $HOME even when BUN_INSTALL is set, so without this the install
|
|
156
|
+
# aborts with "HOME: unbound variable" and /usr/local/bin/bun never appears —
|
|
157
|
+
# breaking a from-scratch provision (adopting an existing box masked it).
|
|
158
|
+
export HOME="\${HOME:-/root}"
|
|
159
|
+
export BUN_INSTALL="/root/.bun"
|
|
160
|
+
# bun.sh's installer references $HOME internally and runs under this
|
|
161
|
+
# script's \`set -u\` (inherited by the piped bash) — cloud-init's runcmd
|
|
162
|
+
# environment doesn't export HOME by default, so without this the
|
|
163
|
+
# installer dies with "HOME: unbound variable" partway through (after
|
|
164
|
+
# the binary is already downloaded, so it looks like a partial success)
|
|
165
|
+
# and \`set -e\` aborts everything after it: the bun symlink, /var/www +
|
|
166
|
+
# /var/ts-cloud dirs, and the whole rpx gateway install/systemd setup
|
|
167
|
+
# never run. Confirmed against a real Hetzner box (stacksjs/status#1
|
|
168
|
+
# Phase 9 e2e deploy) — cloud-init reported success with none of that
|
|
169
|
+
# actually done.
|
|
170
|
+
export HOME="\${HOME:-/root}"
|
|
171
|
+
curl -fsSL https://bun.sh/install | bash${J==="latest"?"":` -s "bun-v${J}"`}
|
|
172
|
+
ln -sf /root/.bun/bin/bun /usr/local/bin/bun
|
|
173
|
+
echo 'export BUN_INSTALL="/root/.bun"' > /etc/profile.d/bun.sh
|
|
174
|
+
echo 'export PATH="$BUN_INSTALL/bin:$PATH"' >> /etc/profile.d/bun.sh
|
|
175
|
+
`;else if(z==="node"){let O=J==="latest"||!J?"20":J.split(".")[0];X+=`
|
|
176
|
+
curl -fsSL https://deb.nodesource.com/setup_${O}.x | bash -
|
|
177
|
+
apt-get install -y nodejs
|
|
178
|
+
ln -sf /usr/bin/node /usr/local/bin/node
|
|
179
|
+
ln -sf /usr/bin/npm /usr/local/bin/npm
|
|
180
|
+
`}else if(z==="deno")X+=`
|
|
181
|
+
curl -fsSL https://deno.land/install.sh | sh
|
|
182
|
+
ln -sf /root/.deno/bin/deno /usr/local/bin/deno
|
|
183
|
+
`}if(X+=`
|
|
184
|
+
mkdir -p /var/www /var/ts-cloud/staging /var/ts-cloud/releases
|
|
185
|
+
`,W)X+=`
|
|
186
|
+
ARCH=$(uname -m | sed 's/x86_64/amd64/;s/aarch64/arm64/')
|
|
187
|
+
curl -fsSL "https://caddyserver.com/api/download?os=linux&arch=\${ARCH}" -o /usr/local/bin/caddy
|
|
188
|
+
chmod +x /usr/local/bin/caddy
|
|
189
|
+
|
|
190
|
+
getent group caddy >/dev/null || groupadd --system caddy
|
|
191
|
+
getent passwd caddy >/dev/null || useradd --system --gid caddy \\
|
|
192
|
+
--create-home --home-dir /var/lib/caddy \\
|
|
193
|
+
--shell /usr/sbin/nologin --comment "Caddy web server" caddy
|
|
194
|
+
|
|
195
|
+
mkdir -p /etc/caddy /var/lib/caddy /var/log/caddy
|
|
196
|
+
chown -R caddy:caddy /var/lib/caddy /var/log/caddy
|
|
197
|
+
|
|
198
|
+
cat > /etc/systemd/system/caddy.service <<'CADDY_UNIT_EOF'
|
|
199
|
+
[Unit]
|
|
200
|
+
Description=Caddy
|
|
201
|
+
Documentation=https://caddyserver.com/docs/
|
|
202
|
+
After=network.target network-online.target
|
|
203
|
+
Requires=network-online.target
|
|
204
|
+
|
|
205
|
+
[Service]
|
|
206
|
+
Type=notify
|
|
207
|
+
User=caddy
|
|
208
|
+
Group=caddy
|
|
209
|
+
ExecStart=/usr/local/bin/caddy run --environ --config /etc/caddy/Caddyfile
|
|
210
|
+
ExecReload=/usr/local/bin/caddy reload --config /etc/caddy/Caddyfile --force
|
|
211
|
+
TimeoutStopSec=5s
|
|
212
|
+
LimitNOFILE=1048576
|
|
213
|
+
PrivateTmp=true
|
|
214
|
+
ProtectSystem=full
|
|
215
|
+
AmbientCapabilities=CAP_NET_BIND_SERVICE
|
|
216
|
+
|
|
217
|
+
[Install]
|
|
218
|
+
WantedBy=multi-user.target
|
|
219
|
+
CADDY_UNIT_EOF
|
|
220
|
+
|
|
221
|
+
cat > /etc/caddy/Caddyfile <<'CADDY_CONFIG_EOF'
|
|
222
|
+
${W}
|
|
223
|
+
CADDY_CONFIG_EOF
|
|
224
|
+
|
|
225
|
+
systemctl daemon-reload
|
|
226
|
+
systemctl enable caddy
|
|
227
|
+
systemctl start caddy
|
|
228
|
+
`;if(j&&j.length>0){let O=j[0]==="set -euo pipefail"?j.slice(1):j;X+=`
|
|
229
|
+
${O.join(`
|
|
230
|
+
`)}
|
|
231
|
+
`}return X+=`
|
|
232
|
+
echo "ts-cloud bootstrap complete — instance is ready for site deploys"
|
|
233
|
+
`,X}var T1="/aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id";function y1($){let z=[{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"}],J=new Set;for(let Z of Object.values($.sites||{}))if(Z&&typeof Z.port==="number"&&![22,80,443].includes(Z.port))J.add(Z.port);for(let Z of J)z.push({port:Z,protocol:"tcp",cidr:"0.0.0.0/0"});return z}function P1($){let z=$.infrastructure?.compute??{},J=o0($),Z=z.proxy?.engine==="rpx"?O0({proxy:z.proxy,config:M0($.sites??{},{proxy:z.proxy,slug:$.project.slug}),slug:$.project.slug,bunBin:z.runtime==="node"||z.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0;return s({runtime:J.runtime,runtimeVersion:J.runtimeVersion,systemPackages:z.systemPackages,database:$.infrastructure?.database,phpProvision:J.phpProvision,servicesProvision:J.servicesProvision,rpxProvision:Z,baked:z.bakedImage===!0,swapGb:z.swapGb})}function I1($){return Buffer.from($,"utf8").toString("base64")}function S1($){return $.infrastructure?.compute?.image??null}function O$($,z){return`${$}-${z}-app-sg`}function Zz($,z,J="app"){return[{Key:"Project",Value:$},{Key:"Environment",Value:z},{Key:"Role",Value:J},{Key:"ManagedBy",Value:"ts-cloud"}]}function r4($,z,J){if(!$?.length)return!1;let Z=(Q)=>$.find((q)=>q.Key===Q)?.Value;return Z("Project")===z&&Z("Environment")===J}function f1($,z){let J=O$(z.slug,z.environment);return $.find((Z)=>{if(Z.GroupName!==J)return!1;if(z.vpcId&&Z.VpcId&&Z.VpcId!==z.vpcId)return!1;if(!!Z.Tags?.some((q)=>q.Key==="Project"))return r4(Z.Tags,z.slug,z.environment);return!!z.vpcId&&Z.VpcId===z.vpcId})}function i4($){try{let z=v1(n4(process.cwd(),"storage/cloud/state",`${$}.json`),"utf8"),J=JSON.parse(z);return typeof J.instanceId==="string"&&J.instanceId.length>0?J.instanceId:null}catch{return null}}class V${name="aws";usesCloudFormation=!0;region;ec2Client;cfnClient;constructor($={}){this.region=$.region||"us-east-1",this.ec2Client=$.ec2Client??((z)=>new m1(z)),this.cfnClient=$.cfnClient??((z)=>new h1(z))}resolveRegion($){return $.project.region||this.region}async provisionComputeInfrastructure($){let{config:z,environment:J}=$,Z=this.resolveRegion(z),Q=z.project.slug,q=z.infrastructure?.compute;if(!q)throw Error("infrastructure.compute is required to provision AWS compute");let Y=this.ec2Client(Z),W=await this.findComputeTargets({slug:Q,environment:J,role:"app",region:Z});if(W.length>0){let D=W[0];return{appInstanceId:D.id,appPublicIp:D.publicIp,appPublicIpv6:D.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}let j=S1(z);if(!j){if(j=(await new Qz(Z).getParameter({Name:T1})).Parameter?.Value??null,!j)throw Error("Could not resolve the Ubuntu 24.04 AMI from SSM")}let G=await Y.describeVpcs(),H=(G.Vpcs||[]).find((D)=>D.IsDefault)||(G.Vpcs||[])[0];if(!H?.VpcId)throw Error("No VPC found to launch the instance into");let M=(await Y.describeSubnets({Filters:[{Name:"vpc-id",Values:[H.VpcId]}]})).Subnets||[],X=M.find((D)=>D.MapPublicIpOnLaunch)||M[0],K=X?.SubnetId;if(!X?.MapPublicIpOnLaunch)console.warn("ts-cloud: no public subnet found; the instance may not get a public IP (deploys/SSL need one).");let O=O$(Q,J),B=(await Y.describeSecurityGroups({Filters:[{Name:"group-name",Values:[O]},{Name:"vpc-id",Values:[H.VpcId]}]})).SecurityGroups?.[0]?.GroupId;if(!B)B=(await Y.createSecurityGroup({GroupName:O,Description:`ts-cloud ${Q}/${J} app`,VpcId:H.VpcId,TagSpecifications:[{ResourceType:"security-group",Tags:Zz(Q,J)}]})).GroupId;let U=y1(z);await Y.authorizeSecurityGroupIngress({GroupId:B,IpPermissions:U.map((D)=>({IpProtocol:D.protocol,FromPort:D.port,ToPort:D.port,IpRanges:[{CidrIp:D.cidr}]}))}).catch((D)=>{if(!/InvalidPermission\.Duplicate/.test(D instanceof Error?D.message:""))throw D});let F=I1(P1(z)),V=q.server?.instanceType||"t3.small",C=(await Y.runInstances({ImageId:j,InstanceType:V,MinCount:1,MaxCount:1,SecurityGroupIds:B?[B]:void 0,SubnetId:K,UserData:F,IamInstanceProfile:q.server?.iamInstanceProfile?{Name:q.server.iamInstanceProfile}:void 0,TagSpecifications:[{ResourceType:"instance",Tags:[{Key:"Name",Value:`${Q}-${J}-app`},...Zz(Q,J)]}]})).Instances?.[0]?.InstanceId;if(!C)throw Error("RunInstances did not return an instance id");let A=await Y.waitForInstanceState(C,"running");if(!A)throw Error(`Instance ${C} did not reach 'running' before timeout`);return{appInstanceId:C,appPublicIp:A.PublicIpAddress,appPublicIpv6:W0(A.Ipv6Address),sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}async destroyCompute($){let{config:z,environment:J}=$,Z=z.project.slug,Q=this.resolveRegion(z),q=this.ec2Client(Q),Y=[],j=(await this.findComputeTargets({slug:Z,environment:J,role:"app",region:Q})).map((O)=>O.id),G;if(j.length>0)G=(await q.describeInstances({InstanceIds:j}).catch(()=>({Reservations:[]}))).Reservations?.flatMap((L)=>L.Instances??[]).find((L)=>L.VpcId)?.VpcId;if(j.length>0)await q.terminateInstances(j),Y.push(...j.map((O)=>`instance ${O}`)),await Promise.all(j.map((O)=>q.waitForInstanceState(O,"terminated").catch(()=>{return})));let H=O$(Z,J),M=[{Name:"group-name",Values:[H]}];if(G)M.push({Name:"vpc-id",Values:[G]});let X=await q.describeSecurityGroups({Filters:M}).catch(()=>({SecurityGroups:[]})),K=f1(X.SecurityGroups??[],{slug:Z,environment:J,vpcId:G});if(K?.GroupId)for(let O=0;O<10;O++)try{await q.deleteSecurityGroup(K.GroupId),Y.push(`security group ${H}`);break}catch{await new Promise((L)=>setTimeout(L,3000))}return{destroyed:Y}}async getComputeOutputs($){let z=this.resolveRegion($.config),J=I($.config,$.environment),Z=this.cfnClient(z);try{let Q=await Z.getStackOutputs(J);return{deployBucketName:Q.deployBucketName,appInstanceId:Q.appInstanceId,appPublicIp:Q.appPublicIp,sshUser:"ec2-user"}}catch(Q){if(!/does not exist|ValidationError/i.test(Q instanceof Error?Q.message:""))throw Q;let Y=(await this.findComputeTargets({slug:$.config.project.slug,environment:$.environment,role:"app",region:z}))[0];return{appInstanceId:Y?.id,appPublicIp:Y?.publicIp,appPublicIpv6:Y?.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}}async uploadRelease($){let z=this.resolveRegion($.config),Z=(await this.getComputeOutputs({config:$.config,environment:$.environment})).deployBucketName;if(!Z)throw Error("No deployBucketName in stack outputs. Re-deploy infrastructure to add the staging bucket.");return await new b1(z).putObject({bucket:Z,key:$.remoteKey,body:v1($.localPath),contentType:"application/gzip"}),{artifactRef:`s3://${Z}/${$.remoteKey}`}}async findComputeTargets($){let z=$.region??this.region,J=this.ec2Client(z),Z=[{Name:"tag:Project",Values:[$.slug]},{Name:"tag:Environment",Values:[$.environment]},{Name:"tag:Role",Values:[$.role||"app"]},{Name:"instance-state-name",Values:["running","pending"]}],Q=await J.describeInstances({Filters:Z}),q=this.reservationsToTargets(Q.Reservations);if(q.length>0||($.role||"app")!=="app")return q;let Y=$.stackName??`${$.slug}-${$.environment}`,W=i4(Y);if(!W)try{W=(await this.cfnClient(z).getStackOutputs(Y)).appInstanceId??null}catch{W=null}if(!W)return[];try{let j=await J.describeInstances({InstanceIds:[W],Filters:[{Name:"instance-state-name",Values:["running","pending"]}]});return this.reservationsToTargets(j.Reservations)}catch{return[]}}reservationsToTargets($){let z=[];for(let J of $||[])for(let Z of J.Instances||[]){if(!Z.InstanceId)continue;let Q=Z.Tags?.find((q)=>q.Key==="Name")?.Value;z.push({id:Z.InstanceId,name:Q,publicIp:Z.PublicIpAddress,publicIpv6:W0(Z.Ipv6Address),privateIp:Z.PrivateIpAddress,status:Z.State?.Name})}return z}bashWrap($){return["bash <<'TS_CLOUD_BASH_EOF'",$.join(`
|
|
234
|
+
`),"TS_CLOUD_BASH_EOF"]}async runRemoteDeploy($){let z=this.region,J=new Qz(z);if($.targets.length>0){let Q=await J.sendCommand({InstanceIds:$.targets.map((q)=>q.id),DocumentName:"AWS-RunShellScript",Parameters:{commands:this.bashWrap($.commands)},TimeoutSeconds:$.timeoutSeconds||600,Comment:$.comment});if(!Q.CommandId)return{success:!1,instanceCount:0,perInstance:[],error:"Failed to send SSM command"};return this.pollSsmCommand(J,Q.CommandId,$.targets.length,(($.timeoutSeconds||600)+30)*1000)}if(!$.tags||Object.keys($.tags).length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets or tags provided for AWS deploy"};let Z=await J.sendCommandByTags({tags:$.tags,commands:this.bashWrap($.commands),timeoutSeconds:$.timeoutSeconds||600,comment:$.comment});return{success:Z.success,instanceCount:Z.instanceCount,perInstance:Z.perInstance.map((Q)=>({instanceId:Q.instanceId,status:Q.status,output:Q.output,error:Q.error})),error:Z.error}}async pollSsmCommand($,z,J,Z=600000){let q=Date.now(),Y=new Set(["Success","Failed","Cancelled","TimedOut"]),W=[];while(Date.now()-q<Z){await new Promise((H)=>setTimeout(H,3000));try{if(W=await $.listCommandInvocations({CommandId:z,Details:!0}),W.length>=J&&W.every((M)=>Y.has(M.Status||"")))break}catch{}}let j=W.map((H)=>({instanceId:H.InstanceId,status:H.Status||"Unknown",output:H.StandardOutputContent,error:H.StandardErrorContent})),G=j.length>0&&j.every((H)=>H.status==="Success");return{success:G,instanceCount:j.length,perInstance:j,error:G?void 0:"One or more SSM command invocations failed"}}}import{execFileSync as W6,execSync as r1}from"node:child_process";import{createHash as j6,randomUUID as n1}from"node:crypto";import{createReadStream as G6,existsSync as K6,readFileSync as H6}from"node:fs";function u1($={}){let z=Math.max(1,$.appServers??$.instances??1),J=!!$.servicesServer||z>1,Z=z>1||!!$.server?.loadBalancer;return{appServers:z,loadBalancer:Z,dedicatedServices:J,servicesOnApp:!J}}function g1($,z){let J={REDIS_HOST:$,MEILISEARCH_HOST:`http://${$}:7700`};if(z?.name){if(J.DB_CONNECTION=z.engine==="postgres"?"pgsql":"mysql",J.DB_HOST=$,J.DB_PORT=String(z.port??(z.engine==="postgres"?5432:3306)),J.DB_DATABASE=z.name,z.username)J.DB_USERNAME=z.username;if(z.password)J.DB_PASSWORD=z.password}return J}function qz($){let z=$.infrastructure?.compute??{},J=V0($);return[...K$(z.managedServices??{mysql:!0,redis:!0},{bindPrivate:!0}),...T0(J,z.managedServices??{mysql:!0}),...G0(!0),...K0(!0),...S0(z.sshKeys),...y0($.notifications),...z.backups?.enabled?[...H$({database:J,backups:z.backups})]:[]]}import{homedir as t4}from"node:os";import{join as o4}from"node:path";var F$={location:"fsn1",image:"ubuntu-24.04",sshUser:"root",sshPrivateKeyPath:"~/.ssh/id_ed25519"};function d1($){return $.startsWith("~/")?o4(t4(),$.slice(2)):$}function h0(...$){for(let z of $){let J=process.env[z]?.trim();if(J)return J}return}function m0(...$){for(let z of $){let J=z?.trim();if(J)return J}return}function s0($,z){return m0($,z?.hetzner?.apiToken,h0("HCLOUD_TOKEN","HETZNER_API_TOKEN"))}function s4($,z){return m0(z,$?.hetzner?.location,h0("HCLOUD_LOCATION","HETZNER_LOCATION"))??F$.location}function e0($,z){let J=$?.infrastructure?.compute;return m0(z,J?.image,$?.hetzner?.image,h0("HCLOUD_IMAGE","HETZNER_IMAGE"))??F$.image}function e4($,z){return m0(z,$?.hetzner?.sshUser,h0("HCLOUD_SSH_USER","HETZNER_SSH_USER"))??F$.sshUser}function c1($,z){return d1(m0(z,$?.hetzner?.sshPrivateKeyPath,h0("HCLOUD_SSH_KEY","HETZNER_SSH_KEY"))??F$.sshPrivateKeyPath)}function $6($,z,J){let Z=m0(z,$?.hetzner?.sshPublicKeyPath,h0("HCLOUD_SSH_PUBLIC_KEY","HETZNER_SSH_PUBLIC_KEY"));if(Z)return d1(Z);return`${J??c1($)}.pub`}function l1($,z={}){let J=c1($,z.sshPrivateKeyPath);return{apiToken:s0(z.apiToken,$),location:s4($,z.location),image:e0($,z.image),sshUser:e4($,z.sshUser),sshPrivateKeyPath:J,sshPublicKeyPath:$6($,z.sshPublicKeyPath,J)}}var z6="https://api.hetzner.cloud/v1";class B$ extends Error{status;code;details;constructor($,z,J,Z){super($);this.status=z;this.code=J;this.details=Z;this.name="HetznerApiError"}}class U$ extends Error{action;constructor($,z){super($);this.action=z;this.name="HetznerActionError"}}class C${name="hetzner";apiToken;baseUrl;fetchImpl;constructor($){this.apiToken=$.apiToken,this.baseUrl=$.baseUrl??z6,this.fetchImpl=$.fetchImpl??fetch}async request($,z,J){let Z=await this.fetchImpl(`${this.baseUrl}${z}`,{method:$,headers:{Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},body:J===void 0?void 0:JSON.stringify(J)}),Q=await Z.text(),q;try{q=Q?JSON.parse(Q):{}}catch{if(!Z.ok){let Y=Q.trim().slice(0,200)||Z.statusText||"Hetzner API error";throw Error(`Hetzner API ${$} ${z} (${Z.status}): ${Y}`)}throw Error(`Hetzner API ${$} ${z}: unexpected non-JSON response`)}if(!Z.ok){let Y=q.error?.message||Z.statusText||"Hetzner API error",W=q.error?.code?` [${q.error.code}]`:"";throw new B$(`Hetzner API ${$} ${z} (${Z.status})${W}: ${Y}`,Z.status,q.error?.code,q.error?.details)}return q}async requestAll($,z){let J=[],Z=1;for(;;){let Q=$.includes("?")?"&":"?",q=await this.request("GET",`${$}${Q}per_page=50&page=${Z}`);J.push(...q[z]??[]);let Y=q.meta?.pagination?.next_page;if(!Y)return J;Z=Y}}async listServers(){return this.requestAll("/servers","servers")}async getServer($){return(await this.request("GET",`/servers/${$}`)).server}async getServerMetrics($,z){let J=new URLSearchParams({type:z.types.join(","),start:z.start.toISOString(),end:z.end.toISOString(),step:String(Math.max(60,Math.floor(z.step??60)))});return(await this.request("GET",`/servers/${$}/metrics?${J}`)).metrics}async listServerTypes($){let z=$?`?name=${encodeURIComponent($)}`:"";return this.requestAll(`/server_types${z}`,"server_types")}async getServerType($){return(await this.listServerTypes($)).find((z)=>z.name===$)??null}async createServer($){let z=await this.request("POST","/servers",{name:$.name,server_type:$.serverType,image:$.image,location:$.location,datacenter:$.datacenter,ssh_keys:$.sshKeys,user_data:$.userData,labels:$.labels,firewalls:$.firewalls,networks:$.networks,start_after_create:!0});return{server:z.server,action:z.action}}async listNetworks(){return this.requestAll("/networks","networks")}async createNetwork($){let z=$.ipRange??"10.0.0.0/16";return(await this.request("POST","/networks",{name:$.name,ip_range:z,subnets:[{type:"cloud",ip_range:z,network_zone:"eu-central"}],labels:$.labels})).network}async deleteNetwork($){await this.request("DELETE",`/networks/${$}`)}async listLoadBalancers(){return this.requestAll("/load_balancers","load_balancers")}async createLoadBalancer($){return(await this.request("POST","/load_balancers",{name:$.name,load_balancer_type:$.type??"lb11",location:$.location,network_zone:$.network?void 0:$.networkZone??"eu-central",network:$.network,labels:$.labels,targets:[{type:"label_selector",label_selector:{selector:$.labelSelector},use_private_ip:!!$.network}],services:$.services.map((J)=>({protocol:J.protocol??"tcp",listen_port:J.listenPort,destination_port:J.destinationPort,health_check:{protocol:"http",port:80,interval:15,timeout:10,retries:3,http:{path:"/",status_codes:["2??","3??"]}}}))})).load_balancer}async deleteLoadBalancer($){await this.request("DELETE",`/load_balancers/${$}`)}async deleteServer($){return(await this.request("DELETE",`/servers/${$}`)).action}async listFirewalls(){return this.requestAll("/firewalls","firewalls")}async createFirewall($){let z=await this.request("POST","/firewalls",{name:$.name,rules:$.rules,labels:$.labels,apply_to:$.applyTo});return{firewall:z.firewall,actions:z.actions}}async setFirewallRules($,z){return(await this.request("POST",`/firewalls/${$}/actions/set_rules`,{rules:z})).actions??[]}async deleteFirewall($){await this.request("DELETE",`/firewalls/${$}`)}async applyFirewallToResources($,z){return(await this.request("POST",`/firewalls/${$}/actions/apply_to_resources`,{apply_to:z})).actions}async listSshKeys(){return this.requestAll("/ssh_keys","ssh_keys")}async createSshKey($){return(await this.request("POST","/ssh_keys",{name:$.name,public_key:$.publicKey,labels:$.labels})).ssh_key}async deleteSshKey($){await this.request("DELETE",`/ssh_keys/${$}`)}async getAction($){return(await this.request("GET",`/actions/${$}`)).action}async shutdownServer($){return(await this.request("POST",`/servers/${$}/actions/shutdown`,{})).action}async powerOnServer($){return(await this.request("POST",`/servers/${$}/actions/poweron`,{})).action}async changeServerType($,z,J){return(await this.request("POST",`/servers/${$}/actions/change_type`,{server_type:z,upgrade_disk:J})).action}async powerOffServer($){return(await this.request("POST",`/servers/${$}/actions/poweroff`,{})).action}async stopServer($,z){if((await this.getServer($)).status==="off")return;await this.shutdownServer($);let Z=z?.gracefulWaitMs??120000,Q=z?.pollIntervalMs??3000,q=Date.now();while(Date.now()-q<Z){if((await this.getServer($)).status==="off")return;await new Promise((W)=>setTimeout(W,Q))}let Y=await this.powerOffServer($);await this.waitForAction(Y.id),await this.waitForServerStatus($,"off")}async renameServer($,z){return(await this.request("PUT",`/servers/${$}`,{name:z})).server}async listImages($){let z=$?.type?`?type=${encodeURIComponent($.type)}`:"";return this.requestAll(`/images${z}`,"images")}async getImage($){return(await this.request("GET",`/images/${$}`)).image}async createImage($,z){return this.request("POST",`/servers/${$}/actions/create_image`,{description:z.description,type:z.type??"snapshot",labels:z.labels})}async deleteImage($){await this.request("DELETE",`/images/${$}`)}async rebuildServer($,z){return(await this.request("POST",`/servers/${$}/actions/rebuild`,{image:z})).action}async listPrimaryIps(){return this.requestAll("/primary_ips","primary_ips")}async unassignPrimaryIp($){return(await this.request("POST",`/primary_ips/${$}/actions/unassign`,{})).action}async assignPrimaryIp($,z){return(await this.request("POST",`/primary_ips/${$}/actions/assign`,{assignee_id:z,assignee_type:"server"})).action}async waitForAction($,z){let J=z?.pollIntervalMs??2000,Z=z?.maxWaitMs??300000,Q=Date.now();while(Date.now()-Q<Z){let q=await this.getAction($);if(q.status==="success")return q;if(q.status==="error")throw new U$(q.error?.message||"Hetzner action failed",q);await new Promise((Y)=>setTimeout(Y,J))}throw Error(`Timed out waiting for Hetzner action ${$}`)}async waitForServerRunning($,z){let J=z?.pollIntervalMs??3000,Z=z?.maxWaitMs??600000,Q=Date.now();while(Date.now()-Q<Z){let q=await this.getServer($);if(q.status==="running")return q;await new Promise((Y)=>setTimeout(Y,J))}throw Error(`Timed out waiting for server ${$} to reach running state`)}async waitForServerStatus($,z,J){let Z=J?.pollIntervalMs??3000,Q=J?.maxWaitMs??600000,q=Date.now();while(Date.now()-q<Q){let Y=await this.getServer($);if(Y.status===z)return Y;await new Promise((W)=>setTimeout(W,Z))}throw Error(`Timed out waiting for server ${$} to reach ${z} state`)}}function J6($,z){let J=s0($,z);if(!J)throw Error("Hetzner API token required. Set hetzner.apiToken in cloud.config.ts or HCLOUD_TOKEN / HETZNER_API_TOKEN.");return J}function x0($){let[z,J]=$.trim().split(/\s+/);return J?`${z} ${J}`:z}function F0($){return`#cloud-config
|
|
235
|
+
write_files:
|
|
236
|
+
- path: /var/lib/cloud/ts-cloud-bootstrap.sh
|
|
237
|
+
permissions: '0755'
|
|
238
|
+
owner: root:root
|
|
239
|
+
content: |
|
|
240
|
+
${$.split(`
|
|
241
|
+
`).map((Z)=>` ${Z}`).join(`
|
|
242
|
+
`)}
|
|
243
|
+
runcmd:
|
|
244
|
+
- [ bash, /var/lib/cloud/ts-cloud-bootstrap.sh ]
|
|
245
|
+
`}function L$($){let z=new Set([80,443,...$.sitePorts,...$.allowedPorts??[]]);if($.allowSsh)z.add(22);return[...z].map((J)=>{return{direction:"in",protocol:"tcp",port:String(J),source_ips:["0.0.0.0/0","::/0"],description:`ts-cloud port ${J}`}})}var Yz={micro:"cpx11",small:"cx23",medium:"cx33",large:"cx43",xlarge:"cx53","2xlarge":"ccx33"};function D0($){if(!$)return Yz.micro;if($ in Yz)return Yz[$];return $}var h="ts-cloud";function S($,z,J="app"){return{[`${h}/project`]:$,[`${h}/environment`]:z,[`${h}/role`]:J,[`${h}/managed-by`]:"ts-cloud"}}function c($,z,J,Z="app"){return Wz($,z,J)&&$[`${h}/role`]===Z}function Wz($,z,J){if(!$)return!1;return $[`${h}/project`]===z&&$[`${h}/environment`]===J}import{mkdir as Z6,readFile as Q6,rename as q6,writeFile as Y6}from"node:fs/promises";import{join as p1}from"node:path";var w0="storage/cloud/state";function a1($){return p1(process.cwd(),w0,`${$}.json`)}async function A0($){try{let z=await Q6(a1($),"utf8");return JSON.parse(z)}catch{return null}}async function R0($,z){let J=a1($);await Z6(p1(process.cwd(),w0),{recursive:!0});let Z=`${J}.${process.pid}.tmp`;await Y6(Z,`${JSON.stringify(z,null,2)}
|
|
246
|
+
`,"utf8"),await q6(Z,J)}var jz=268435456,X6=8000;function e($){return`'${$.replace(/'/g,`'"'"'`)}'`}async function M6($){let z=j6("sha256");for await(let J of G6($))z.update(J);return z.digest("hex")}function i1($){return(Buffer.isBuffer($)?$.toString("utf8"):typeof $==="string"?$:"").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(-X6)}function t1($){let z=$,J=typeof z?.status==="number"?` (exit ${z.status})`:"",Z=z?.signal?` (signal ${z.signal})`:"",Q=[i1(z?.stderr),i1(z?.stdout)].filter(Boolean).join(`
|
|
247
|
+
`);return`Remote SSH command failed${J}${Z}${Q?`
|
|
248
|
+
${Q}`:""}`}class B0{name="hetzner";usesCloudFormation=!1;client;sshPrivateKeyPath;sshPublicKeyPath;sshUser;location;stateOnly;waitForBoot;bootWait;constructor($={}){let z=s0($.apiToken);if(this.stateOnly=!$.client&&!z&&$.allowStateOnly===!0,!$.client&&!z&&!this.stateOnly)throw Error("Hetzner API token required. Set hetzner.apiToken in cloud.config.ts or HCLOUD_TOKEN / HETZNER_API_TOKEN.");this.client=$.client??new C$({apiToken:z??""});let J=l1(void 0,{sshPrivateKeyPath:$.sshPrivateKeyPath,sshPublicKeyPath:$.sshPublicKeyPath,sshUser:$.sshUser,location:$.location});this.sshPrivateKeyPath=J.sshPrivateKeyPath,this.sshPublicKeyPath=J.sshPublicKeyPath,this.sshUser=J.sshUser,this.location=J.location,this.waitForBoot=$.waitForBoot??!0,this.bootWait={sshIntervalMs:$.bootWait?.sshIntervalMs??5000,sshTimeoutMs:$.bootWait?.sshTimeoutMs??300000,cloudInitIntervalMs:$.bootWait?.cloudInitIntervalMs??5000,cloudInitTimeoutMs:$.bootWait?.cloudInitTimeoutMs??600000}}async provisionComputeInfrastructure($){let{config:z,environment:J}=$,Z=z.project.slug,Q=z.infrastructure?.compute;if(!Q)throw Error("infrastructure.compute is required to provision Hetzner compute");if(z.cloud?.attachTo)return this.attachToComputeInfrastructure(z.cloud.attachTo,z,J);let q=I(z,J),Y=`${Z}-${J}-app`,W=Q.runtime==="php"||!!Q.php,j=u1(Q);if(j.dedicatedServices||j.appServers>1)return W?this.provisionFleet($,j):this.provisionBunFleet($,j);let G=S(Z,J,"app"),H=z.sites||{},M=o(Q)?[]:this.collectUpstreamPorts(H),X=`${Z}-${J}-app-fw`,{firewall:K}=await this.ensureFirewall(X,G,L$({allowSsh:Q.allowSsh!==!1,sitePorts:M,allowedPorts:[...Q.firewall?.allowedPorts??[],...k1(z.infrastructure?.sftp)]})),O=await this.ensureSshKey(Z,J,G),L=await A0(q);if(L?.serverId){let R=await this.tryGetServer(L.serverId);if(R&&R.status!=="off")return this.outputsFromState(L,R)}let B=await this.findExistingServer(Z,J,Y);if(B&&B.status!=="off"){let R={provider:"hetzner",stackName:q,serverId:B.id,serverName:B.name,publicIp:B.public_net.ipv4?.ip,publicIpv6:W0(B.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await R0(q,R),this.outputsFromState(R,B)}let U=Q.proxy?.engine==="rpx"?O0({proxy:Q.proxy,config:M0(H,{proxy:Q.proxy,slug:z.project.slug}),slug:z.project.slug,bunBin:Q.runtime==="node"||Q.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,F=o0(z),V=Q.bakedImage===!0,x=s({runtime:F.runtime,runtimeVersion:F.runtimeVersion,systemPackages:Q.systemPackages,database:z.infrastructure?.database,phpProvision:F.phpProvision,servicesProvision:F.servicesProvision,rpxProvision:U,baked:V,swapGb:Q.swapGb}),C=F0(x),A=D0(Q.size),D=e0(z),{server:T,action:r}=await this.client.createServer({name:Y,serverType:A,image:D,location:z.hetzner?.location||this.location,userData:C,labels:G,sshKeys:O?[O]:void 0,firewalls:[{firewall:K.id}]});await this.client.waitForAction(r.id);let f=await this.client.waitForServerRunning(T.id),v={provider:"hetzner",stackName:q,serverId:f.id,serverName:f.name,firewallId:K.id,publicIp:f.public_net.ipv4?.ip,publicIpv6:W0(f.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};await R0(q,v);let b=f.public_net.ipv4?.ip;if(b&&this.waitForBoot)await this.waitForSshReady(b),await this.waitForCloudInit(b);return this.outputsFromState(v,f)}async provisionFleet($,z){let{config:J,environment:Z}=$,Q=J.project.slug,q=J.infrastructure.compute,Y=I(J,Z),W=D0(q.size),j=e0(J),G=J.hetzner?.location||this.location,H=q.bakedImage===!0,M=await A0(Y);if(M?.loadBalancerId){let _=(await this.client.listLoadBalancers().catch(()=>[])).find((w)=>w.id===M.loadBalancerId);if(_)return{appPublicIp:_.public_net?.ipv4?.ip,loadBalancerIp:_.public_net?.ipv4?.ip,servicesPrivateIp:M.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}let X=await this.ensureSshKey(Q,Z,S(Q,Z,"app")),K=`${Q}-${Z}-net`,L=(await this.client.listNetworks().catch(()=>[])).find((N)=>N.name===K)??await this.client.createNetwork({name:K,labels:S(Q,Z,"app")}),{firewall:B}=await this.ensureFirewall(`${Q}-${Z}-app-fw`,S(Q,Z,"app"),L$({allowSsh:!0,sitePorts:[],allowedPorts:q.firewall?.allowedPorts})),{firewall:U}=await this.ensureFirewall(`${Q}-${Z}-services-fw`,S(Q,Z,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[L.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[L.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[L.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[L.ip_range]}]),F=qz(J),V=F0(s({runtime:"php",servicesProvision:F,baked:H,swapGb:q.swapGb})),x=await this.client.listServers().catch(()=>[]),C=[],A=x.find((N)=>c(N.labels,Q,Z,"services"));if(!A){let{server:N,action:_}=await this.client.createServer({name:`${Q}-${Z}-services`,serverType:D0(typeof q.servicesServer==="object"?q.servicesServer.size:q.size),image:j,location:G,userData:V,labels:S(Q,Z,"services"),sshKeys:X?[X]:void 0,firewalls:[{firewall:U.id}],networks:[L.id]});await this.client.waitForAction(_.id),A=await this.client.waitForServerRunning(N.id),C.push(N.id)}let D=A.id,T=A.private_net?.[0]?.ip??(await this.client.getServer(D)).private_net?.[0]?.ip,r=[...G0(!0),...K0(!0),...S0(q.sshKeys),...y0(J.notifications)],f=X$({versions:q.php?.versions,default:q.php?.default,extensions:q.php?.extensions,installNginx:!o(q),optimizeForProduction:q.php?.optimizeForProduction,ini:q.php?.ini}),v=F0(s({runtime:"php",phpProvision:f,servicesProvision:r,baked:H,swapGb:q.swapGb})),b=x.filter((N)=>c(N.labels,Q,Z,"app")),R=b.map((N)=>N.id);if(b.length>z.appServers)for(let N of b.slice(z.appServers))await this.client.deleteServer(N.id).catch(()=>{}),R.splice(R.indexOf(N.id),1);for(let N=b.length;N<z.appServers;N++){let{server:_,action:w}=await this.client.createServer({name:`${Q}-${Z}-app-${N+1}`,serverType:W,image:j,location:G,userData:v,labels:S(Q,Z,"app"),sshKeys:X?[X]:void 0,firewalls:[{firewall:B.id}],networks:[L.id]});await this.client.waitForAction(w.id),R.push(_.id),C.push(_.id)}if(this.waitForBoot&&C.length>0)await Promise.all(C.map(async(N)=>{let w=(await this.client.waitForServerRunning(N)).public_net.ipv4?.ip;if(w)await this.waitForSshReady(w),await this.waitForCloudInit(w)}));let u=`${Q}-${Z}-lb`,y,z0;if(z.loadBalancer){let _=(await this.client.listLoadBalancers().catch(()=>[])).find((w)=>w.name===u)??await this.client.createLoadBalancer({name:u,location:G,network:L.id,labels:S(Q,Z,"lb"),labelSelector:`ts-cloud/project=${Q},ts-cloud/environment=${Z},ts-cloud/role=app`,services:[{listenPort:80,destinationPort:80},{listenPort:443,destinationPort:443}]});z0=_.id,y=_.public_net?.ipv4?.ip}let n=y??(await this.client.getServer(R[0]).catch(()=>{return}))?.public_net.ipv4?.ip,U0={provider:"hetzner",stackName:Y,networkId:L.id,loadBalancerId:z0,servicesServerId:D,servicesPrivateIp:T,publicIp:n,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await R0(Y,U0),{appPublicIp:n,loadBalancerIp:y,servicesPrivateIp:T,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async provisionBunFleet($,z){let{config:J,environment:Z}=$,Q=J.project.slug,q=J.infrastructure.compute,Y=I(J,Z),W=D0(q.size),j=e0(J),G=J.hetzner?.location||this.location,H=q.bakedImage===!0,M=J.sites||{},X=await A0(Y);if(X?.lbServerId){let w=await this.tryGetServer(X.lbServerId);if(w&&w.status!=="off"){let E=q.proxy?.engine==="rpx"?q.proxy:{engine:"rpx"},P=await this.findComputeTargets({slug:Q,environment:Z,role:"app",stackName:Y});return this.refreshLbRoutes(w,M,P.map((i)=>({privateIp:i.privateIp,publicIp:i.publicIp})),E,Q),{appPublicIp:w.public_net.ipv4?.ip??X.publicIp,loadBalancerIp:w.public_net.ipv4?.ip??X.publicIp,servicesPrivateIp:X.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}}let K=await this.ensureSshKey(Q,Z,S(Q,Z,"app")),O=`${Q}-${Z}-net`,B=(await this.client.listNetworks().catch(()=>[])).find((w)=>w.name===O)??await this.client.createNetwork({name:O,labels:S(Q,Z,"app")}),U=this.collectUpstreamPorts(M),{firewall:F}=await this.ensureFirewall(`${Q}-${Z}-app-fw`,S(Q,Z,"app"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},...U.map((w)=>({direction:"in",protocol:"tcp",port:String(w),source_ips:[B.ip_range],description:`ts-cloud port ${w} (private, LB-only)`}))]),{firewall:V}=await this.ensureFirewall(`${Q}-${Z}-lb-fw`,S(Q,Z,"lb"),L$({allowSsh:!0,sitePorts:[],allowedPorts:q.firewall?.allowedPorts})),x=await this.client.listServers().catch(()=>[]),C=[],A,D,T=!!q.servicesServer||!!q.managedServices,r=z.dedicatedServices&&T;if(r){let{firewall:w}=await this.ensureFirewall(`${Q}-${Z}-services-fw`,S(Q,Z,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[B.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[B.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[B.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[B.ip_range]}]),E=qz(J),P=F0(s({runtime:"bun",servicesProvision:E,baked:H,swapGb:q.swapGb})),i=x.find((Y0)=>c(Y0.labels,Q,Z,"services"));if(!i){let{server:Y0,action:l0}=await this.client.createServer({name:`${Q}-${Z}-services`,serverType:D0(typeof q.servicesServer==="object"?q.servicesServer.size:q.size),image:j,location:G,userData:P,labels:S(Q,Z,"services"),sshKeys:K?[K]:void 0,firewalls:[{firewall:w.id}],networks:[B.id]});await this.client.waitForAction(l0.id),i=await this.client.waitForServerRunning(Y0.id),C.push(Y0.id)}A=i.id,D=i.private_net?.[0]?.ip??(await this.client.getServer(A)).private_net?.[0]?.ip}let f=r?{...q,managedServices:void 0,backups:void 0}:q,v=o0({...J,infrastructure:{...J.infrastructure,compute:f}}),b=F0(s({runtime:v.runtime,runtimeVersion:v.runtimeVersion,systemPackages:q.systemPackages,database:J.infrastructure?.database,servicesProvision:v.servicesProvision,baked:H,swapGb:q.swapGb})),R=x.filter((w)=>c(w.labels,Q,Z,"app")),u=R.map((w)=>w.id);if(R.length>z.appServers)for(let w of R.slice(z.appServers))await this.client.deleteServer(w.id).catch(()=>{}),u.splice(u.indexOf(w.id),1);for(let w=R.length;w<z.appServers;w++){let{server:E,action:P}=await this.client.createServer({name:`${Q}-${Z}-app-${w+1}`,serverType:W,image:j,location:G,userData:b,labels:S(Q,Z,"app"),sshKeys:K?[K]:void 0,firewalls:[{firewall:F.id}],networks:[B.id]});await this.client.waitForAction(P.id),u.push(E.id),C.push(E.id)}if(this.waitForBoot&&C.length>0)await Promise.all(C.map(async(w)=>{let P=(await this.client.waitForServerRunning(w)).public_net.ipv4?.ip;if(P)await this.waitForSshReady(P),await this.waitForCloudInit(P)}));let y=[];for(let w of u){let E=x.find((P)=>P.id===w);if(!E||!E.private_net?.[0]?.ip)E=await this.client.getServer(w).catch(()=>E);y.push({privateIp:E?.private_net?.[0]?.ip,publicIp:E?.public_net.ipv4?.ip})}let z0=`${Q}-${Z}-lb`,n,U0;if(z.loadBalancer){let w=x.find((P)=>c(P.labels,Q,Z,"lb")),E=q.proxy?.engine==="rpx"?q.proxy:{engine:"rpx"};if(!w){let P=O0({proxy:E,config:I0(M,y,{proxy:E,slug:Q}),slug:Q,bunBin:v.runtime==="node"||v.runtime==="deno"?void 0:"/usr/local/bin/bun"}),i=F0(s({runtime:"bun",rpxProvision:P,baked:!1})),Y0=typeof q.loadBalancer==="object"?q.loadBalancer.size:void 0,{server:l0,action:S$}=await this.client.createServer({name:z0,serverType:D0(Y0??"micro"),image:j,location:G,userData:i,labels:S(Q,Z,"lb"),sshKeys:K?[K]:void 0,firewalls:[{firewall:V.id}],networks:[B.id]});if(await this.client.waitForAction(S$.id),w=await this.client.waitForServerRunning(l0.id),this.waitForBoot){let t=w.public_net.ipv4?.ip;if(t)await this.waitForSshReady(t),await this.waitForCloudInit(t)}}else this.refreshLbRoutes(w,M,y,E,Q);n=w.id,U0=w.public_net.ipv4?.ip}let N=U0??(await this.client.getServer(u[0]).catch(()=>{return}))?.public_net.ipv4?.ip,_={provider:"hetzner",stackName:Y,networkId:B.id,lbServerId:n,appServerIds:u,servicesServerId:A,servicesPrivateIp:D,publicIp:N,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await R0(Y,_),{appPublicIp:N,loadBalancerIp:U0,servicesPrivateIp:D,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async destroyCompute($){let{config:z,environment:J}=$,Z=z.project.slug,Q=I(z,J),q=await A0(Q),Y=[],W=`${Z}-${J}-lb`,G=(await this.client.listLoadBalancers().catch(()=>[])).find((F)=>F.name===W);if(G)try{await this.client.deleteLoadBalancer(G.id),Y.push(`load balancer ${W}`)}catch{}let H=await this.client.listServers().catch(()=>[]),M=new Set;for(let F of H)if(c(F.labels,Z,J,"app")||c(F.labels,Z,J,"services")||c(F.labels,Z,J,"lb"))M.add(F.id);if(q?.serverId)M.add(q.serverId);if(q?.servicesServerId)M.add(q.servicesServerId);if(q?.lbServerId)M.add(q.lbServerId);for(let F of q?.appServerIds??[])M.add(F);for(let F of M)try{await this.client.deleteServer(F),Y.push(`server ${F}`)}catch{}let X=await this.client.listFirewalls().catch(()=>[]);for(let F of[`${Z}-${J}-app-fw`,`${Z}-${J}-services-fw`,`${Z}-${J}-lb-fw`]){let V=X.find((x)=>x.name===F);if(!V)continue;for(let x=0;x<12;x++)try{await this.client.deleteFirewall(V.id),Y.push(`firewall ${F}`);break}catch{await this.sleep(3000)}}let K=`${Z}-${J}-net`,L=(await this.client.listNetworks().catch(()=>[])).find((F)=>F.name===K);if(L)for(let F=0;F<12;F++)try{await this.client.deleteNetwork(L.id),Y.push(`network ${K}`);break}catch{await this.sleep(3000)}let U=(await this.client.listSshKeys().catch(()=>[])).filter((F)=>Wz(F.labels,Z,J));for(let F of U)try{await this.client.deleteSshKey(F.id),Y.push(`ssh key ${F.name}`)}catch{}return await R0(Q,{provider:"hetzner",stackName:Q}).catch(()=>{}),{destroyed:Y}}async getComputeOutputs($){let z=I($.config,$.environment),J=await A0(z);if(J?.serverId){let q=await this.tryGetServer(J.serverId);if(q)return this.outputsFromState(J,q)}if(J?.lbServerId){let Y=(await this.tryGetServer(J.lbServerId))?.public_net.ipv4?.ip??J.publicIp;return{...this.outputsFromState(J),appPublicIp:Y,loadBalancerIp:Y}}if(J?.loadBalancerId||J?.servicesPrivateIp)return this.outputsFromState(J);let Q=(await this.findComputeTargets({slug:$.config.project.slug,environment:$.environment,role:"app",stackName:I($.config,$.environment)}))[0];return{deployStoragePath:"/var/ts-cloud/staging",appInstanceId:Q?.id,appPublicIp:Q?.publicIp,sshUser:this.sshUser}}async uploadRelease($){let z=$.targets?.length?$.targets:await this.findComputeTargets({slug:$.config.project.slug,environment:$.environment,role:"app",stackName:I($.config,$.environment)});if(z.length===0)throw Error("No Hetzner compute targets found for release upload");let Q=`/var/ts-cloud/staging/${`${$.remoteKey.replace(/^releases\//,"").replace(/\.tar\.gz$/,"").replace(/\//g,"-")}-${n1()}.tar.gz`}`,q=await M6($.localPath),Y="/var/ts-cloud/artifacts",W=`${Y}/${q}.tar.gz`;for(let j of z){if(!j.publicIp)throw Error(`Target ${j.id} has no public IP for SCP upload`);let G=["set -euo pipefail",`mkdir -p ${e(Y)} /var/ts-cloud/staging`,`test -s ${e(W)}`,`cp -- ${e(W)} ${e(Q)}`].join(`
|
|
249
|
+
`);try{this.sshExec(j.publicIp,G);continue}catch{}let H=`${Y}/.${q}-${n1()}.tmp`;this.scpToHost(j.publicIp,$.localPath,H),this.sshExec(j.publicIp,["set -euo pipefail",`chmod 600 ${e(H)}`,`mv -f -- ${e(H)} ${e(W)}`,`cp -- ${e(W)} ${e(Q)}`,`find ${e(Y)} -type f -name '*.tar.gz' -mtime +7 -delete 2>/dev/null || true`].join(`
|
|
250
|
+
`))}return{artifactRef:Q}}async findComputeTargets($){let z=$.role||"app",J=(q)=>({id:String(q.id),name:q.name,publicIp:q.public_net.ipv4?.ip,publicIpv6:W0(q.public_net.ipv6?.ip),privateIp:q.private_net?.[0]?.ip,status:q.status});if(z==="app"||z==="lb"||z==="services"){let q=await A0($.stackName??`${$.slug}-${$.environment}`),Y=[...new Set(z==="app"?[q?.serverId,...q?.appServerIds??[]]:z==="lb"?[q?.lbServerId]:[q?.servicesServerId])].filter((G)=>typeof G==="number");if(this.stateOnly){if(Y.length>0&&q?.publicIp)return Y.map((G)=>({id:String(G),name:G===q.serverId?q.serverName:void 0,publicIp:q.publicIp,publicIpv6:q.publicIpv6,status:"running"}));if(z!=="app")return[];throw Error(`Hetzner API token required because '${$.stackName??`${$.slug}-${$.environment}`}' has no complete local compute state pin.`)}let W=await this.client.listServers();if(Y.length>0){let G=[];for(let H of Y){let M=W.find((X)=>X.id===H)??await this.tryGetServer(H);if(H===q?.serverId&&q.serverName&&M?.name!==q.serverName)continue;if(M&&M.status!=="off")G.push(M)}if(G.length>0)return G.map(J)}let j=W.filter((G)=>c(G.labels,$.slug,$.environment,z));if(j.length>0)return j.map(J);if(z==="app"){let G=W.filter((H)=>H.status!=="off"&&H.labels?.[`${h}/managed-by`]==="ts-cloud"&&H.labels?.[`${h}/environment`]===$.environment&&H.labels?.[`${h}/role`]==="app");if(G.length===1)return G.map(J)}return[]}if(this.stateOnly)throw Error(`Hetzner API token required to discover '${z}' compute targets.`);let Q=(await this.client.listServers()).filter((q)=>c(q.labels,$.slug,$.environment,z));if(Q.length>0)return Q.map(J);return[]}async attachToComputeInfrastructure($,z,J){let Z=await this.client.listServers(),Q=(X)=>Z.filter((K)=>K.status!=="off"&&c(K.labels,$,J,X)),q=Q("app");if(q.length===0)throw Error(`Cannot attach '${z.project.slug}' to '${$}': no running Hetzner app server is labeled for ${$}/${J}. Deploy the owner project first.`);let Y=Q("lb")[0],W=Q("services")[0],j=q[0],G=Y??j,H=I(z,J),M={provider:"hetzner",stackName:H,serverId:j.id,serverName:j.name,appServerIds:q.map((X)=>X.id),lbServerId:Y?.id,servicesServerId:W?.id,servicesPrivateIp:W?.private_net?.[0]?.ip,publicIp:G.public_net.ipv4?.ip,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await R0(H,M),this.outputsFromState(M)}async runRemoteDeploy($){if($.targets.length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets provided"};let z=$.commands.join(`
|
|
251
|
+
`),J=[];for(let Q of $.targets){if(!Q.publicIp){J.push({instanceId:Q.id,status:"Failed",error:"Missing public IP"});continue}try{let q=this.sshExec(Q.publicIp,z);J.push({instanceId:Q.id,status:"Success",output:q})}catch(q){J.push({instanceId:Q.id,status:"Failed",error:q.message})}}let Z=J.every((Q)=>Q.status==="Success");return{success:Z,instanceCount:$.targets.length,perInstance:J,error:Z?void 0:"One or more SSH deploy commands failed"}}async ensureSshKey($,z,J){if(!K6(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 Z=H6(this.sshPublicKeyPath,"utf8").trim(),Q=x0(Z),Y=(await this.client.listSshKeys()).find((j)=>x0(j.public_key)===Q);if(Y)return Y.id;return(await this.client.createSshKey({name:`${$}-${z}-deploy`,publicKey:Z,labels:J})).id}async tryGetServer($){try{return await this.client.getServer($)}catch{return null}}refreshLbRoutes($,z,J,Z,Q){let q=$.public_net.ipv4?.ip;if(!q){console.warn(`[ts-cloud] LB server '${$.name}' has no public IP — skipping the rpx route refresh; its routes may be stale.`);return}let Y=J.filter((j)=>j.privateIp||j.publicIp);if(Y.length===0){console.warn(`[ts-cloud] No routable app boxes found for LB '${$.name}' — leaving its current rpx routes untouched.`);return}let W=I0(z,Y,{proxy:Z,slug:Q});this.sshExec(q,t0({config:W,slug:Q}).join(`
|
|
252
|
+
`))}async findExistingServer($,z,J){let Z=await this.client.listServers(),Q=Z.find((Y)=>c(Y.labels,$,z,"app")||Y.name===J);if(Q)return Q;let q=Z.filter((Y)=>Y.status!=="off"&&Y.labels?.[`${h}/managed-by`]==="ts-cloud"&&Y.labels?.[`${h}/environment`]===z&&Y.labels?.[`${h}/role`]==="app");if(q.length===1){let Y=q[0],W=Y.labels?.[`${h}/project`]??"unknown";return console.warn(`[ts-cloud] No server named '${J}' found; adopting existing ts-cloud app server '${Y.name}' (project label '${W}') for project '${$}' — `+"updating it in place instead of provisioning a new server."),Y}return}async ensureFirewall($,z,J){let Q=(await this.client.listFirewalls()).find((Y)=>Y.name===$);if(Q)return await this.client.setFirewallRules(Q.id,J),{firewall:Q};let{firewall:q}=await this.client.createFirewall({name:$,labels:z,rules:J});return{firewall:q}}collectUpstreamPorts($){let z=new Set;for(let J of Object.values($))if(typeof J.port==="number")z.add(J.port);return[...z].filter((J)=>![80,443].includes(J))}async sleep($){await new Promise((z)=>setTimeout(z,$))}async waitForSshReady($){let{sshIntervalMs:z,sshTimeoutMs:J}=this.bootWait,Z=Date.now(),Q;while(Date.now()-Z<J)try{r1(`ssh ${this.sshBaseArgs($,["-o","ConnectTimeout=5"]).map(e).join(" ")} true`,{stdio:"pipe",maxBuffer:jz});return}catch(q){Q=q,await this.sleep(z)}throw Error(`Timed out waiting for SSH on ${$} after ${J}ms: ${Q?.message??"unknown error"}`)}async waitForCloudInit($){let{cloudInitIntervalMs:z,cloudInitTimeoutMs:J}=this.bootWait,Z=Date.now();while(Date.now()-Z<J){try{let Q=this.sshExec($,"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(Q))throw Error(`cloud-init reported an error on ${$}:
|
|
253
|
+
${Q}`);if(/status:\s*(?:done|degraded)/.test(Q))return}catch(Q){if(Q instanceof Error&&/cloud-init reported an error/.test(Q.message))throw Q}await this.sleep(z)}throw Error(`Timed out waiting for cloud-init to finish on ${$} after ${J}ms`)}outputsFromState($,z){return{deployStoragePath:$.deployStoragePath||"/var/ts-cloud/staging",appInstanceId:$.serverId?String($.serverId):void 0,appPublicIp:z?.public_net.ipv4?.ip||$.publicIp,appPublicIpv6:W0(z?.public_net.ipv6?.ip)||$.publicIpv6,sshUser:$.sshUser||this.sshUser,servicesPrivateIp:$.servicesPrivateIp}}static SSH_HOST_KEY_OPTS=["-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR"];static SSH_KEEPALIVE_OPTS=["-o","ConnectTimeout=30","-o","ServerAliveInterval=15","-o","ServerAliveCountMax=4"];sshBaseArgs($,z=[]){return["-i",this.sshPrivateKeyPath,...B0.SSH_HOST_KEY_OPTS,...B0.SSH_KEEPALIVE_OPTS,"-o","BatchMode=yes",...z,`${this.sshUser}@${$}`]}scpToHost($,z,J){let Z=["scp","-i",this.sshPrivateKeyPath,...B0.SSH_HOST_KEY_OPTS,...B0.SSH_KEEPALIVE_OPTS,"-o","BatchMode=yes",z,`${this.sshUser}@${$}:${J}`].map((q)=>`"${q.replace(/"/g,"\\\"")}"`).join(" "),Q=3;for(let q=1;q<=3;q++)try{r1(Z,{stdio:"pipe",maxBuffer:jz});return}catch(Y){if(q===3)throw Error(t1(Y))}}sshExec($,z){try{return W6("ssh",[...this.sshBaseArgs($),"bash -s"],{encoding:"utf8",input:z,stdio:["pipe","pipe","pipe"],maxBuffer:jz})}catch(J){throw Error(t1(J))}}}class x${name="hetzner";usesCloudFormation=!1;async getComputeOutputs(){return{appPublicIp:"127.0.0.1",sshUser:"root"}}async uploadRelease($){return{artifactRef:$.localPath}}async findComputeTargets($){if(($.role||"app")!=="app")return[];return[{id:"localhost",name:"localhost",publicIp:"127.0.0.1",status:"running"}]}async runRemoteDeploy($){let z=$.commands.join(`
|
|
254
|
+
`);try{let J=Bun.spawn(["bash","-c",z],{stdout:"pipe",stderr:"pipe",env:process.env}),[Z,Q,q]=await Promise.all([new Response(J.stdout).text(),new Response(J.stderr).text(),J.exited]);return{success:q===0,instanceCount:1,perInstance:[{instanceId:"localhost",status:q===0?"Success":"Failed",output:Z,error:Q}]}}catch(J){return{success:!1,instanceCount:1,perInstance:[{instanceId:"localhost",status:"Failed",error:J?.message??String(J)}],error:J?.message??String(J)}}}}function Gz(){let $=process.env.TS_CLOUD_DASHBOARD_BOX;return $!=null&&$!==""&&$!=="0"&&$.toLowerCase()!=="false"}function O6($){if(Gz())return new x$;switch($.provider??b0($.config)){case"aws":return new V$({region:$.config.project.region});case"hetzner":return new B0({apiToken:$.config.hetzner?.apiToken,allowStateOnly:Boolean($.config.cloud?.attachTo),sshPrivateKeyPath:$.config.hetzner?.sshPrivateKeyPath,sshPublicKeyPath:$.config.hetzner?.sshPublicKeyPath,sshUser:$.config.hetzner?.sshUser,location:$.config.hetzner?.location});default:throw Error(`Unknown cloud provider: ${$.provider??b0($.config)}`)}}class o1{drivers=new Map;getDriver($,z){let J=z??b0($),Z=`${J}:${$.project.slug}:${$.project.region||"default"}`,Q=this.drivers.get(Z);if(Q)return Q;let q=O6({config:$,provider:J});return this.drivers.set(Z,q),q}}var e5=new o1;function V6($){return $.location?.name??$.datacenter?.location.name??"unknown"}function v0($){return typeof $==="number"&&Number.isFinite($)?$:0}function F6($,z){if($.architecture&&z.architecture&&$.architecture!==z.architecture)throw Error(`Cannot resize ${$.name} (${$.architecture}) to ${z.name} (${z.architecture}) in place.`);let J=[];if(v0(z.cores)<v0($.cores))J.push("CPU");if(v0(z.memory)<v0($.memory))J.push("memory");if(v0(z.disk)<v0($.disk))J.push("disk");if(J.length>0)throw Error(`Refusing an in-place downgrade from ${$.name} to ${z.name}: ${J.join(", ")} would shrink.`)}async function s1($,z,J,Z=!0){let[Q,q]=await Promise.all([$.getServer(z),$.getServerType(J)]);if(!q)throw Error(`Hetzner server type ${J} was not found.`);let Y=Q.server_type,W=Y.name===q.name;if(!W)F6(Y,q);let j=V6(Q),G=q.locations?.find((H)=>H.name===j);return{serverId:z,serverName:Q.name,location:j,currentType:Y,targetType:q,capacityAvailable:G?.available!==!1,alreadyComplete:W,upgradeDisk:Z}}function e1($){if($ instanceof B$&&$.code==="resource_unavailable")return!0;if($ instanceof U$){if($.action.error?.code==="resource_unavailable")return!0;if(/no fitting vhost|placement|free resources/i.test($.action.error?.message??""))return!0}return/resource_unavailable|no fitting vhost|error during placement|free resources/i.test($ instanceof Error?$.message:String($))}async function Q0($,z,J){await $?.onPhase?.(z,J)}async function Kz($,z,J){await $.waitForAction(z.id,{pollIntervalMs:J.actionPollIntervalMs,maxWaitMs:J.actionTimeoutMs})}var D$=async({client:$,hooks:z,actionPollIntervalMs:J,actionTimeoutMs:Z,serverPollIntervalMs:Q,serverTimeoutMs:q},Y,W,j)=>{let G=await $.getServer(Y.serverId);if(G.status!=="running"){await Q0(z,j?"recovering":"powering-on",{serverId:Y.serverId});let M=await $.powerOnServer(Y.serverId);await Kz($,M,{actionPollIntervalMs:J,actionTimeoutMs:Z}),G=await $.waitForServerRunning(Y.serverId,{pollIntervalMs:Q,maxWaitMs:q})}await Q0(z,"verifying",{serverId:Y.serverId,recovered:j});let H=await z?.afterBoot?.(G,Y.targetType,W,{recovered:j});return{server:G,verification:H}};async function B6($){let{client:z,hooks:J}=$,Z=$.upgradeDisk??!0;await Q0(J,"planning",{serverId:$.serverId,targetType:$.targetType});let Q=await s1(z,$.serverId,$.targetType,Z),q=await z.getServer(Q.serverId);if(Q.alreadyComplete){let j=await D$($,Q,$.manifest,!1);return await Q0(J,"complete",{alreadyComplete:!0}),{status:"already-complete",plan:Q,verification:j.verification}}if(!Q.capacityAvailable&&!$.attemptUnavailable)return await Q0(J,"waiting-capacity",{location:Q.location,targetType:Q.targetType.name}),{status:"waiting-capacity",plan:Q};let Y=$.manifest;if(q.status==="off"&&!$.resumeFromOff){let j=await D$($,Q,void 0,!0);return{status:"recovered",plan:Q,server:j.server,verification:j.verification,retryable:!0,error:"Server was already off without a resumable resize checkpoint; powered it back on."}}if(q.status==="running"){await Q0(J,"preflight",{serverId:Q.serverId}),Y=await J?.preflight?.(q,Q.targetType),await Q0(J,"shutting-down",{serverId:Q.serverId});let j=await z.shutdownServer(Q.serverId);await Kz(z,j,$),q=await z.waitForServerStatus(Q.serverId,"off",{pollIntervalMs:$.serverPollIntervalMs,maxWaitMs:$.serverTimeoutMs})}try{await Q0(J,"resizing",{serverId:Q.serverId,from:Q.currentType.name,to:Q.targetType.name,upgradeDisk:Z});let j=await z.changeServerType(Q.serverId,Q.targetType.name,Z);await Kz(z,j,$)}catch(j){let G=await D$($,Q,Y,!0);return{status:"recovered",plan:Q,server:G.server,manifest:Y,verification:G.verification,retryable:e1(j),error:j instanceof Error?j.message:String(j)}}let W=await D$($,Q,Y,!1);if(W.verification&&!W.verification.ok)throw Error(`Resize completed but verification failed: ${(W.verification.failures??[]).join("; ")}`);return await Q0(J,"complete",{serverId:Q.serverId,targetType:Q.targetType.name}),{status:"completed",plan:Q,server:W.server,manifest:Y,verification:W.verification}}function Hz($={}){let z=[];if($.identityFile)z.push("-i",$.identityFile);return z.push("-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR","-o",`ConnectTimeout=${$.connectTimeoutSec??10}`),z}async function w$($,z,J={}){let Z=Bun.spawn(["ssh",...Hz(J),`${J.user??"root"}@${$}`,z],{stdout:"pipe",stderr:"pipe"}),[Q,q]=await Promise.all([new Response(Z.stdout).text(),new Response(Z.stderr).text()]);return{code:await Z.exited,stdout:Q,stderr:q}}async function q0($,z,J={}){let Z=await w$($,z,J);if(Z.code!==0)throw Error(`ssh \`${z}\` on ${$} failed (${Z.code}): ${Z.stderr.trim()||Z.stdout.trim()}`);return Z.stdout}async function U6($,z,J,Z={}){let Q=Bun.spawn(["scp",...Hz(Z),...z,`${Z.user??"root"}@${$}:${J}`],{stdout:"pipe",stderr:"pipe"}),q=await Q.exited;if(q!==0){let Y=await new Response(Q.stderr).text();throw Error(`scp to ${$}:${J} failed (${q}): ${Y.trim()}`)}}async function Xz($,z={}){let J=z.timeoutMs??180000,Z=z.pollIntervalMs??5000,Q=Date.now();while(Date.now()-Q<J){let q=await w$($,"echo ready",z);if(q.code===0&&q.stdout.includes("ready"))return;await new Promise((Y)=>setTimeout(Y,Z))}throw Error(`SSH not ready on ${$} after ${J}ms`)}async function C6($,z={}){let J=z.timeoutMs??300000,Z=z.pollIntervalMs??5000,Q=Date.now();while(Date.now()-Q<J){let q=await w$($,"cloud-init status 2>/dev/null || echo unknown",z);if(q.stdout.includes("status: done"))return;if(q.stdout.includes("status: error"))throw Error(`cloud-init reported an error on ${$}; check /var/log/cloud-init-output.log`);await new Promise((Y)=>setTimeout(Y,Z))}throw Error(`cloud-init did not finish on ${$} after ${J}ms`)}var L6=String.raw`
|
|
255
|
+
const { readdir, readFile, readlink, stat } = await import('node:fs/promises')
|
|
256
|
+
|
|
257
|
+
const text = (command) => {
|
|
258
|
+
const result = Bun.spawnSync(['bash', '-lc', command], { stdout: 'pipe', stderr: 'pipe' })
|
|
259
|
+
return result.exitCode === 0 ? result.stdout.toString().trim() : ''
|
|
260
|
+
}
|
|
261
|
+
const lines = (command) => text(command).split('\n').map(value => value.trim()).filter(Boolean).sort()
|
|
262
|
+
const number = (value) => Number.parseInt(value || '0', 10) || 0
|
|
263
|
+
|
|
264
|
+
const root = text('findmnt -n -o SOURCE,FSTYPE /').split(/\s+/)
|
|
265
|
+
const rootSource = root[0] || ''
|
|
266
|
+
const rootFsType = root[1] || ''
|
|
267
|
+
const rootParent = text('lsblk -n -o PKNAME ' + rootSource + ' | head -1')
|
|
268
|
+
const rootDiskBytes = number(text('lsblk -b -n -o SIZE /dev/' + rootParent + ' | head -1'))
|
|
269
|
+
const rootFilesystemBytes = number(text("df -B1 --output=size / | tail -1"))
|
|
270
|
+
const memoryBytes = number(text("awk '/MemTotal/{print $2 * 1024}' /proc/meminfo"))
|
|
271
|
+
const allRunningServices = lines("systemctl list-units --type=service --state=running --no-legend --plain | awk '{print $1}'")
|
|
272
|
+
const runningServices = allRunningServices.filter((unit) => {
|
|
273
|
+
if (/^(containerd|docker|localtunnel|mail|mysql|mariadb|meilisearch|postgresql|redis|rpx-gateway)\b/.test(unit)) return true
|
|
274
|
+
const source = text('systemctl cat ' + unit + ' 2>/dev/null')
|
|
275
|
+
return /\/var\/www|\/usr\/local\/bin\/rpx|\/opt\/ts-cloud/.test(source)
|
|
276
|
+
})
|
|
277
|
+
const failedUnits = lines("systemctl --failed --type=service --no-legend --plain | awk '{print $1}'")
|
|
278
|
+
const releaseLinks = []
|
|
279
|
+
for (const path of lines("find /var/www -mindepth 2 -maxdepth 2 -type l -name current -print 2>/dev/null")) {
|
|
280
|
+
try {
|
|
281
|
+
releaseLinks.push(path + '=' + await readlink(path))
|
|
282
|
+
} catch {}
|
|
283
|
+
}
|
|
284
|
+
releaseLinks.sort()
|
|
285
|
+
|
|
286
|
+
const routeFragments = []
|
|
287
|
+
const routeIds = []
|
|
288
|
+
const routeDomains = new Set()
|
|
289
|
+
for (const path of lines("find /etc/rpx/sites.d -maxdepth 1 -type f -name '*.json' -print 2>/dev/null")) {
|
|
290
|
+
try {
|
|
291
|
+
const source = await readFile(path, 'utf8')
|
|
292
|
+
const digest = new Bun.CryptoHasher('sha256').update(source).digest('hex')
|
|
293
|
+
routeFragments.push(path + '=' + digest)
|
|
294
|
+
const value = JSON.parse(source)
|
|
295
|
+
for (const route of value.proxies || []) {
|
|
296
|
+
if (typeof route.to === 'string' && route.to) {
|
|
297
|
+
routeDomains.add(route.to)
|
|
298
|
+
routeIds.push(path + ':' + (route.id || route.to) + ':' + (route.path || '/'))
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
} catch {}
|
|
302
|
+
}
|
|
303
|
+
routeFragments.sort()
|
|
304
|
+
routeIds.sort()
|
|
305
|
+
|
|
306
|
+
const persistentData = []
|
|
307
|
+
for (const path of ['/var/lib/postgresql', '/var/lib/mysql', '/var/lib/redis', '/var/lib/docker', '/var/mail', '/var/vmail']) {
|
|
308
|
+
try {
|
|
309
|
+
const value = await stat(path)
|
|
310
|
+
if (value.isDirectory()) {
|
|
311
|
+
const bytes = number(text('du -sx --block-size=1 ' + path + " 2>/dev/null | awk '{print $1}'"))
|
|
312
|
+
persistentData.push(path + '=' + bytes)
|
|
313
|
+
}
|
|
314
|
+
} catch {}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
const dataCatalog = []
|
|
318
|
+
for (const database of lines("command -v psql >/dev/null && sudo -u postgres psql -Atqc 'select datname from pg_database where datistemplate = false order by datname' 2>/dev/null || true")) {
|
|
319
|
+
dataCatalog.push('postgres:' + database)
|
|
320
|
+
}
|
|
321
|
+
for (const database of lines("command -v mysql >/dev/null && mysql -NBe 'show databases' 2>/dev/null || true")) {
|
|
322
|
+
dataCatalog.push('mysql:' + database)
|
|
323
|
+
}
|
|
324
|
+
for (const volume of lines("command -v docker >/dev/null && docker volume ls --format '{{.Name}}' 2>/dev/null || true")) {
|
|
325
|
+
dataCatalog.push('docker-volume:' + volume)
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
console.log(JSON.stringify({
|
|
329
|
+
capturedAt: new Date().toISOString(),
|
|
330
|
+
hostname: text('hostname'),
|
|
331
|
+
cpuCores: number(text('nproc')),
|
|
332
|
+
memoryBytes,
|
|
333
|
+
rootSource,
|
|
334
|
+
rootFsType,
|
|
335
|
+
rootDiskBytes,
|
|
336
|
+
rootFilesystemBytes,
|
|
337
|
+
failedUnits,
|
|
338
|
+
runningServices,
|
|
339
|
+
releaseLinks,
|
|
340
|
+
routeFragments,
|
|
341
|
+
routeIds,
|
|
342
|
+
routeDomains: [...routeDomains].sort(),
|
|
343
|
+
persistentData: persistentData.sort(),
|
|
344
|
+
dataCatalog: dataCatalog.sort(),
|
|
345
|
+
}))
|
|
346
|
+
`;function x6($){return`printf %s ${Buffer.from($).toString("base64")} | base64 -d | bun -`}async function D6($){let z=await q0($.host,x6(L6),$);return JSON.parse(z)}async function w6($,z){let J="";for(let Z=1;Z<=3;Z++){let Q=Bun.spawn(["curl","--location","--silent","--show-error","--output","/dev/null","--max-time",String(Math.max(1,Math.ceil(z/1000))),"--write-out","%{http_code}",`https://${$}/`],{stdout:"pipe",stderr:"pipe"}),[q,Y,W]=await Promise.all([new Response(Q.stdout).text(),new Response(Q.stderr).text(),Q.exited]),j=Number.parseInt(q.trim(),10);if(W===0&&j>0)return{domain:$,ok:j<500,status:j};if(J=Y.trim()||`curl exited ${W}`,Z<3)await Bun.sleep(500*Z)}return{domain:$,ok:!1,error:J}}async function A6($,z){let J=[],Z=0,Q=Array.from({length:Math.min(4,$.length)},async()=>{for(;;){let q=Z++,Y=$[q];if(!Y)return;J[q]=await w6(Y,z)}});return await Promise.all(Q),J}async function Mz($){let z=await D6($),J=await A6(z.routeDomains,$.routeTimeoutMs??15000);return{...z,routeProbes:J}}async function R6($){let z=await Mz($),J=z.routeProbes.filter((Z)=>!Z.ok);if(z.failedUnits.length>0)throw Error(`Preflight found failed services: ${z.failedUnits.join(", ")}`);if(J.length>0)throw Error(`Preflight found unhealthy routes: ${J.map((Z)=>Z.domain).join(", ")}`);return await q0($.host,String.raw`systemctl list-units --type=service --state=running --no-legend --plain | awk '{print $1}' | while read -r unit; do if systemctl cat "$unit" 2>/dev/null | grep -Eq '/var/www|/usr/local/bin/rpx|/opt/ts-cloud'; then systemctl enable "$unit" >/dev/null 2>&1 || true; fi; done; systemctl daemon-reload; sync`,$),z}function u0($,z){let J=new Set(z);return $.filter((Z)=>!J.has(Z))}function N6($){return Math.floor(($.memory??0)*1024*1024*1024)}async function E6($){await q0($.host,String.raw`set -e
|
|
347
|
+
root_source="$(findmnt -n -o SOURCE /)"
|
|
348
|
+
root_fs="$(findmnt -n -o FSTYPE /)"
|
|
349
|
+
parent="$(lsblk -n -o PKNAME "$root_source" | head -1)"
|
|
350
|
+
partition="$(lsblk -n -o PARTN "$root_source" | head -1)"
|
|
351
|
+
if [ -n "$parent" ] && [ -n "$partition" ]; then
|
|
352
|
+
growpart "/dev/$parent" "$partition" || true
|
|
353
|
+
fi
|
|
354
|
+
case "$root_fs" in
|
|
355
|
+
ext2|ext3|ext4) resize2fs "$root_source" ;;
|
|
356
|
+
xfs) xfs_growfs / ;;
|
|
357
|
+
*) echo "Unsupported root filesystem: $root_fs" >&2; exit 1 ;;
|
|
358
|
+
esac`,$)}async function _6($,z){let J=Buffer.from(z.join(`
|
|
359
|
+
`)).toString("base64");await q0($.host,`printf %s ${J} | base64 -d | while read -r unit; do [ -z "$unit" ] || systemctl is-active --quiet "$unit" || systemctl start "$unit"; done`,$)}async function k6($,z,J,Z={recovered:!1}){if(await Xz($.host,{...$,timeoutMs:$.sshTimeoutMs??600000}),!Z.recovered)await E6($);if(J)await _6($,J.runningServices);let Q=await Mz($),q=[],Y=J?u0(J.runningServices,Q.runningServices):[],W=J?u0(J.releaseLinks,Q.releaseLinks):[],j=J?u0(J.routeFragments,Q.routeFragments):[],G=J?u0(J.routeIds,Q.routeIds):[],H=J?.persistentData.map((x)=>x.split("=")[0])??[],M=Q.persistentData.map((x)=>x.split("=")[0]),X=u0(H,M),K=J?u0(J.dataCatalog,Q.dataCatalog):[],O=Q.routeProbes.filter((x)=>!x.ok),L=Z.recovered&&J?J.cpuCores:z.cores??0,B=Z.recovered&&J?J.memoryBytes:N6(z),U=Q.cpuCores>=L,F=Q.memoryBytes>=B*0.9,V=Z.recovered||Q.rootDiskBytes>=(z.disk??0)*1e9*0.95;if(Q.failedUnits.length>0)q.push(`Failed services: ${Q.failedUnits.join(", ")}`);if(Y.length>0)q.push(`Services did not return: ${Y.join(", ")}`);if(W.length>0)q.push(`Release links changed: ${W.join(", ")}`);if(j.length>0)q.push(`Route manifests changed: ${j.join(", ")}`);if(G.length>0)q.push(`Routes disappeared: ${G.join(", ")}`);if(X.length>0)q.push(`Persistent data paths disappeared: ${X.join(", ")}`);if(K.length>0)q.push(`Databases or volumes disappeared: ${K.join(", ")}`);if(O.length>0)q.push(`Unhealthy routes: ${O.map((x)=>x.domain).join(", ")}`);if(!U)q.push(`Expected at least ${L} CPU cores, found ${Q.cpuCores}`);if(!F)q.push(`Expected at least ${B} bytes of RAM`);if(!V)q.push(`Expected approximately ${z.disk??0} GB root disk`);return{ok:q.length===0,checks:{cpuCores:Q.cpuCores,memoryBytes:Q.memoryBytes,rootDiskBytes:Q.rootDiskBytes,rootFilesystemBytes:Q.rootFilesystemBytes,runningServices:Q.runningServices.length,releaseLinks:Q.releaseLinks.length,routeFragments:Q.routeFragments.length,routes:Q.routeIds.length,healthyRoutes:Q.routeProbes.filter((x)=>x.ok).length,persistentDataPaths:Q.persistentData.length,databasesAndVolumes:Q.dataCatalog.length,failedUnits:Q.failedUnits.length},failures:q}}function $2($){return $.infrastructure?.compute??{}}function z2($){let z=$2($),J=z.monitoring;return{firewallPorts:[...new Set([22,80,443,...z.firewall?.allowedPorts??[]])].filter((Q)=>Number.isInteger(Q)&&Q>=1&&Q<=65535).sort((Q,q)=>Q-q),monitoring:J!==!1&&(typeof J!=="object"||J.enabled!==!1),autoUpdates:z.autoUpdates!==!1,swapGb:Math.max(0,Math.floor(z.swapGb??2)),sshPasswordAuthentication:!1,journalMaxUse:"256M",journalRetention:"14day"}}function T6($){return["install -d -m 0755 /etc/ssh/sshd_config.d /etc/systemd/journald.conf.d /etc/sysctl.d /etc/fail2ban/jail.d","cat > /etc/ssh/sshd_config.d/99-ts-cloud-hardening.conf <<'TS_CLOUD_SSH_EOF'","# Managed by ts-cloud host optimization.","PasswordAuthentication no","KbdInteractiveAuthentication no","PermitRootLogin prohibit-password","MaxAuthTries 4","LoginGraceTime 30","TS_CLOUD_SSH_EOF","sshd -t","systemctl reload ssh","cat > /etc/systemd/journald.conf.d/99-ts-cloud-retention.conf <<'TS_CLOUD_JOURNAL_EOF'","[Journal]",`SystemMaxUse=${$.journalMaxUse}`,`MaxRetentionSec=${$.journalRetention}`,"Compress=yes","TS_CLOUD_JOURNAL_EOF","systemctl restart systemd-journald","journalctl --vacuum-size=256M --vacuum-time=14d >/dev/null","cat > /etc/sysctl.d/99-ts-cloud-production.conf <<'TS_CLOUD_SYSCTL_EOF'","# Managed by ts-cloud host optimization.","vm.swappiness=10","vm.dirty_background_ratio=5","vm.dirty_ratio=15","net.core.somaxconn=4096","net.ipv4.tcp_max_syn_backlog=4096","net.ipv4.tcp_fin_timeout=30","net.ipv4.tcp_keepalive_time=300","net.ipv4.tcp_keepalive_intvl=30","net.ipv4.tcp_keepalive_probes=5","fs.inotify.max_user_watches=524288","TS_CLOUD_SYSCTL_EOF","sysctl --system >/dev/null","export DEBIAN_FRONTEND=noninteractive","command -v fail2ban-client >/dev/null 2>&1 || apt-get install -y fail2ban","cat > /etc/fail2ban/jail.d/99-ts-cloud-sshd.conf <<'TS_CLOUD_FAIL2BAN_EOF'","[sshd]","enabled = true","backend = systemd","bantime = 1h","findtime = 10m","maxretry = 5","TS_CLOUD_FAIL2BAN_EOF","systemctl enable --now fail2ban","systemctl restart fail2ban"]}function y6($){if($===0)return[];return["if ! swapon --show=NAME --noheadings 2>/dev/null | grep -qx '/swapfile'; then",` if [ ! -f /swapfile ]; then fallocate -l ${$}G /swapfile || dd if=/dev/zero of=/swapfile bs=1M count=${$*1024} status=none; fi`," chmod 600 /swapfile"," mkswap /swapfile >/dev/null"," swapon /swapfile","fi","grep -qE '^/swapfile\\s' /etc/fstab || echo '/swapfile none swap sw 0 0' >> /etc/fstab"]}function J2($){let z=$2($),J=z2($),Z=z.monitoring??!0,Q=z.firewall??{enabled:!0};return["set -euo pipefail",...o(z)?["systemctl disable --now nginx.service bun-gateway.service ts-cloud-nginx.service 2>/dev/null || true","systemctl reset-failed nginx.service bun-gateway.service ts-cloud-nginx.service 2>/dev/null || true"]:[],...y6(J.swapGb),...G0(J.autoUpdates),...K0(Z),...T6(J),...M$(Q),"systemctl daemon-reload","systemctl reset-failed"]}var P6=String.raw`
|
|
360
|
+
const text = (command) => {
|
|
361
|
+
const result = Bun.spawnSync(['bash', '-lc', command], { stdout: 'pipe', stderr: 'pipe' })
|
|
362
|
+
return result.stdout.toString().trim()
|
|
363
|
+
}
|
|
364
|
+
const lines = command => text(command).split('\n').map(value => value.trim()).filter(Boolean)
|
|
365
|
+
const number = value => Number.parseInt(value || '0', 10) || 0
|
|
366
|
+
const ssh = Object.fromEntries(lines("sshd -T 2>/dev/null | grep -E '^(passwordauthentication|permitrootlogin) '").map(line => line.split(/\s+/, 2)))
|
|
367
|
+
const firewallPorts = lines("ufw status 2>/dev/null | awk '/ALLOW/{print $1}'")
|
|
368
|
+
.flatMap(value => value.startsWith('OpenSSH') ? [22] : (value.match(/^\d+/) ? [number(value)] : []))
|
|
369
|
+
const publicTcpPorts = lines("ss -lntH | awk '{print $4}'")
|
|
370
|
+
.filter(address => !address.startsWith('127.') && !address.startsWith('[::1]'))
|
|
371
|
+
.flatMap(address => {
|
|
372
|
+
const match = address.match(/:(\d+)$/)
|
|
373
|
+
return match ? [number(match[1])] : []
|
|
374
|
+
})
|
|
375
|
+
const metricsMtime = number(text("stat -c %Y /var/lib/ts-cloud/metrics.json 2>/dev/null"))
|
|
376
|
+
console.log(JSON.stringify({
|
|
377
|
+
firewallActive: text("ufw status 2>/dev/null | head -1").includes('active'),
|
|
378
|
+
firewallPorts: [...new Set(firewallPorts)].sort((a, b) => a - b),
|
|
379
|
+
passwordAuthentication: ssh.passwordauthentication !== 'no',
|
|
380
|
+
rootPasswordLogin: ssh.permitrootlogin === 'yes',
|
|
381
|
+
fail2banActive: text('systemctl is-active fail2ban 2>/dev/null') === 'active',
|
|
382
|
+
unattendedUpgradesActive: text('systemctl is-active unattended-upgrades 2>/dev/null') === 'active',
|
|
383
|
+
metricsTimerActive: text('systemctl is-active ts-cloud-metrics.timer 2>/dev/null') === 'active',
|
|
384
|
+
metricsSnapshotFresh: metricsMtime > 0 && Math.floor(Date.now() / 1000) - metricsMtime < 180,
|
|
385
|
+
swapBytes: number(text("free -b | awk '/^Swap:/{print $2}'")),
|
|
386
|
+
journalBytes: number(text("journalctl --disk-usage 2>/dev/null | grep -Eo '[0-9.]+[KMG]' | tail -1 | numfmt --from=iec 2>/dev/null")),
|
|
387
|
+
failedUnits: lines("systemctl --failed --type=service --no-legend --plain | awk '{print $1}'"),
|
|
388
|
+
publicTcpPorts: [...new Set(publicTcpPorts)].sort((a, b) => a - b),
|
|
389
|
+
}))
|
|
390
|
+
`;function I6($){return`printf %s ${Buffer.from($).toString("base64")} | base64 -d | bun -`}async function S6($,z){let J=J2($).join(`
|
|
391
|
+
`),Z=`printf %s ${Buffer.from(J).toString("base64")} | base64 -d | bash`;await q0(z.host,Z,z)}async function f6($){let z=await q0($.host,I6(P6),$);return JSON.parse(z)}function b6($,z){let J=[],Z=new Set(z.firewallPorts),Q=$.firewallPorts.filter((Y)=>!Z.has(Y)),q=z.firewallPorts.filter((Y)=>!$.firewallPorts.includes(Y));if(!z.firewallActive)J.push("UFW is not active");if(Q.length>0)J.push(`UFW is missing ports: ${Q.join(", ")}`);if(q.length>0)J.push(`UFW has unexpected ports: ${q.join(", ")}`);if(z.passwordAuthentication)J.push("SSH password authentication remains enabled");if(z.rootPasswordLogin)J.push("SSH root password login remains enabled");if(!z.fail2banActive)J.push("fail2ban is not active");if($.autoUpdates&&!z.unattendedUpgradesActive)J.push("unattended upgrades are not active");if($.monitoring&&!z.metricsTimerActive)J.push("metrics timer is not active");if($.monitoring&&!z.metricsSnapshotFresh)J.push("metrics snapshot is stale");if($.swapGb>0&&z.swapBytes<$.swapGb*1073741824*0.9)J.push("configured swap is missing");if(z.failedUnits.length>0)J.push(`failed services: ${z.failedUnits.join(", ")}`);return J}import{mkdir as A$,readFile as h6,rename as Z2,rmdir as m6,stat as v6,unlink as u6,writeFile as Q2}from"node:fs/promises";import{join as g0}from"node:path";function Oz($){return g0(process.cwd(),w0,`${$}-resize.json`)}function q2($){return g0(process.cwd(),w0,`${$}-resize.lock`)}async function g6($){try{return JSON.parse(await h6(Oz($),"utf8"))}catch{return null}}async function d6($){let z=Oz($.stackName);await A$(g0(process.cwd(),w0),{recursive:!0});let J=`${z}.${process.pid}.tmp`;await Q2(J,`${JSON.stringify($,null,2)}
|
|
392
|
+
`,"utf8"),await Z2(J,z)}async function c6($,z=1800000){let J=q2($);await A$(g0(process.cwd(),w0),{recursive:!0});try{await A$(J)}catch(Z){if(Date.now()-(await v6(J)).mtimeMs<=z)throw Error(`Another resize process holds ${J}.`);await Z2(J,`${J}.stale-${Date.now()}`),await A$(J)}return await Q2(g0(J,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
|
|
393
|
+
`,"utf8"),async()=>{await u6(g0(J,"owner.json")).catch(()=>{}),await m6(J).catch(()=>{})}}async function Vz($,z){let J=x0(z.publicKey),Z=(await $.listSshKeys()).find((q)=>x0(q.public_key)===J);if(Z)return{id:Z.id,name:Z.name,created:!1};let Q=await $.createSshKey({name:z.name,publicKey:z.publicKey.trim(),labels:z.labels});return{id:Q.id,name:Q.name,created:!0}}async function Fz($,z){let J=(await $.listFirewalls()).find((Q)=>Q.name===z.name);if(J)return await $.setFirewallRules(J.id,z.rules),{id:J.id,name:J.name,created:!1};let{firewall:Z}=await $.createFirewall({name:z.name,rules:z.rules,labels:z.labels});return{id:Z.id,name:Z.name,created:!0}}async function Bz($,z){let{waitForRunning:J=!0,...Z}=z,Q=(await $.listServers()).find((Y)=>Y.name===z.name),q=!Q;if(!Q)Q=(await $.createServer(Z)).server;if(J)Q=await $.waitForServerRunning(Q.id);return{server:Q,created:q}}function Uz($){let z=$.public_net.ipv4?.ip;if(!z)throw Error(`Hetzner server "${$.name}" (#${$.id}) has no public IPv4`);return z}var Cz="/aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id";function Lz($){let z=$.sshPublicKey.trim(),J=["#cloud-config","disable_root: false","ssh_authorized_keys:",` - ${z}`];if($.bootstrapScript){let Q=$.bootstrapScript.split(`
|
|
394
|
+
`).map((q)=>` ${q}`).join(`
|
|
395
|
+
`);J.push("write_files:"," - path: /var/lib/cloud/box-bootstrap.sh"," permissions: '0755'"," owner: root:root"," content: |",Q)}if(J.push("runcmd:",` - mkdir -p /root/.ssh && grep -qF "${z}" /root/.ssh/authorized_keys 2>/dev/null || echo "${z}" >> /root/.ssh/authorized_keys`),$.bootstrapScript)J.push(" - [ bash, /var/lib/cloud/box-bootstrap.sh ]");return`${J.join(`
|
|
396
|
+
`)}
|
|
397
|
+
`}function l6($=[]){let z=[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"],description:"SSH"}];for(let J of $)z.push({direction:"in",protocol:J.protocol,...J.protocol==="icmp"?{}:{port:String(J.port)},source_ips:["0.0.0.0/0","::/0"]});return z}class xz{client;provider="hetzner";constructor($){this.client=$}async ensureBox($){let z=await Vz(this.client,{name:`${$.name}-key`,publicKey:$.sshPublicKey}),J=await Fz(this.client,{name:`${$.name}-fw`,rules:l6($.ports)}),{server:Z,created:Q}=await Bz(this.client,{name:$.name,serverType:$.size,image:$.image??"ubuntu-24.04",location:$.location,sshKeys:[z.id],firewalls:[{firewall:J.id}],userData:Lz($),labels:$.labels});return{provider:"hetzner",id:String(Z.id),name:Z.name,publicIp:Uz(Z),created:Q}}async destroyBox($){let z=[],J=(await this.client.listServers()).find((Q)=>Q.name===$);if(J){let Q=await this.client.deleteServer(J.id);await this.client.waitForAction(Q.id).catch(()=>{}),z.push(`server ${$} (#${J.id})`)}let Z=(await this.client.listFirewalls()).find((Q)=>Q.name===`${$}-fw`);if(Z)for(let Q=0;Q<10;Q++)try{await this.client.deleteFirewall(Z.id),z.push(`firewall ${$}-fw (#${Z.id})`);break}catch{if(Q===9)break;await new Promise((q)=>setTimeout(q,3000))}return{destroyed:z}}}function p6($=[]){let z=[{IpProtocol:"tcp",FromPort:22,ToPort:22,IpRanges:[{CidrIp:"0.0.0.0/0",Description:"SSH"}]}];for(let J of $)z.push(J.protocol==="icmp"?{IpProtocol:"icmp",FromPort:-1,ToPort:-1,IpRanges:[{CidrIp:"0.0.0.0/0"}]}:{IpProtocol:J.protocol,FromPort:J.port,ToPort:J.port,IpRanges:[{CidrIp:"0.0.0.0/0"}]});return z}class Dz{provider="aws";ec2;ssm;constructor($){this.ec2=$.ec2,this.ssm=$.ssm}async findInstance($,z){return(await this.ec2.describeInstances({Filters:[{Name:"tag:Name",Values:[$]},{Name:"instance-state-name",Values:z}]})).Reservations?.flatMap((Z)=>Z.Instances??[])[0]}async waitForPublicIp($,z=300000){let J=Date.now();while(Date.now()-J<z){let Z=await this.ec2.getInstance($);if(Z?.State?.Name==="running"&&Z.PublicIpAddress)return Z;await new Promise((Q)=>setTimeout(Q,5000))}throw Error(`EC2 instance ${$} did not reach running with a public IP within ${z}ms`)}async ensureSecurityGroup($){let z=`${$.name}-sg`,Z=(await this.ec2.describeSecurityGroups({Filters:[{Name:"group-name",Values:[z]}]})).SecurityGroups?.[0]?.GroupId;if(Z)return Z;let Q=await this.ec2.createSecurityGroup({GroupName:z,Description:`box ${$.name} (managed by ts-cloud box-provision)`});if(!Q.GroupId)throw Error(`could not create security group ${z}`);return await this.ec2.authorizeSecurityGroupIngress({GroupId:Q.GroupId,IpPermissions:p6($.ports)}),Q.GroupId}async resolveImage($){if($.image?.startsWith("ami-"))return $.image;let J=(await this.ssm.getParameter({Name:Cz})).Parameter?.Value;if(!J)throw Error(`could not resolve the Ubuntu 24.04 AMI via SSM (${Cz})`);return J}async ensureBox($){let z=await this.findInstance($.name,["pending","running"]);if(z?.InstanceId){let j=await this.waitForPublicIp(z.InstanceId);return{provider:"aws",id:j.InstanceId,name:$.name,publicIp:j.PublicIpAddress,created:!1}}let[J,Z]=await Promise.all([this.ensureSecurityGroup($),this.resolveImage($)]),Q=[{Key:"Name",Value:$.name},...Object.entries($.labels??{}).map(([j,G])=>({Key:j,Value:G}))],Y=(await this.ec2.runInstances({ImageId:Z,InstanceType:$.size,MinCount:1,MaxCount:1,SecurityGroupIds:[J],UserData:Buffer.from(Lz($),"utf8").toString("base64"),TagSpecifications:[{ResourceType:"instance",Tags:Q}]})).Instances?.[0]?.InstanceId;if(!Y)throw Error(`RunInstances returned no instance for box ${$.name}`);let W=await this.waitForPublicIp(Y);return{provider:"aws",id:Y,name:$.name,publicIp:W.PublicIpAddress,created:!0}}async destroyBox($){let z=[],J=await this.findInstance($,["pending","running","stopping","stopped"]);if(J?.InstanceId){await this.ec2.terminateInstances([J.InstanceId]),z.push(`instance ${$} (${J.InstanceId})`);let q=Date.now();while(Date.now()-q<300000){let Y=await this.ec2.getInstance(J.InstanceId);if(!Y||Y.State?.Name==="terminated")break;await new Promise((W)=>setTimeout(W,5000))}}let Q=(await this.ec2.describeSecurityGroups({Filters:[{Name:"group-name",Values:[`${$}-sg`]}]})).SecurityGroups?.[0]?.GroupId;if(Q)for(let q=0;q<10;q++)try{await this.ec2.deleteSecurityGroup(Q),z.push(`security group ${$}-sg (${Q})`);break}catch{if(q===9)break;await new Promise((Y)=>setTimeout(Y,3000))}return{destroyed:z}}}function a6($){if($.provider==="hetzner"){if(!$.hetzner)throw Error('createBoxProvisioner: options.hetzner (a HetznerClient) is required for provider "hetzner"');return new xz($.hetzner)}if(!$.aws)throw Error('createBoxProvisioner: options.aws ({ ec2, ssm }) is required for provider "aws"');return new Dz($.aws)}function R$($){return Object.entries($).map(([z,J])=>`${z}=${r6(String(J))}`).join(`
|
|
398
|
+
`)}function r6($){return`"${$.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}var N$=["storage",".env"],$$=4;function N0($){return`${$.replace(/\/+$/,"")}/.ts-cloud`}function n6($){return`${N0($)}/deploy-history.log`}function i6($,z){return`${N0($)}/deploys/${z}.log`}function W2($){return`${N0($)}/shared-paths`}function z$($,z){let J=$.replace(/\/+$/,"");return{base:J,releases:`${J}/releases`,shared:`${J}/shared`,current:`${J}/current`,release:`${J}/releases/${z}`}}function t6($){let z=$.split("/").pop()||$;if(z===".env"||z.startsWith(".env."))return!0;return/\.[a-z0-9]+$/i.test(z)}function o6($){return typeof $==="string"?$:$.path}function j2($){let z=new Map;for(let J of $)z.set(o6(J),J);return[...z.values()]}function G2($,z){if(typeof z==="string")return{path:z,target:`${$.shared}/${z}`,seed:!0};return{path:z.path,target:z.target??`${$.shared}/${z.path}`,seed:z.seed!==!1}}function s6($){return["ts_cloud_adopt_shared() {",' TS_CLOUD_SP="$1"',' TS_CLOUD_DST="$2"',` TS_CLOUD_SRC="${$.current}/$TS_CLOUD_SP"`,' if [ -e "$TS_CLOUD_DST" ]; then return 0; fi',' if [ -L "$TS_CLOUD_SRC" ] || [ ! -e "$TS_CLOUD_SRC" ]; then return 0; fi',' mkdir -p "$(dirname "$TS_CLOUD_DST")"',' cp -a "$TS_CLOUD_SRC" "$TS_CLOUD_DST"'," for TS_CLOUD_SIDECAR in -wal -shm; do",' if [ -f "$TS_CLOUD_SRC$TS_CLOUD_SIDECAR" ]; then cp -a "$TS_CLOUD_SRC$TS_CLOUD_SIDECAR" "$TS_CLOUD_DST$TS_CLOUD_SIDECAR"; fi'," done",' echo "[ts-cloud] adopted $TS_CLOUD_SP from the live release into shared/ — it now survives deploys"'," return 0","}"]}function J$($,z=N$){let J=[`mkdir -p ${$.releases} ${$.shared}`,...s6($)],Z=z.map((q)=>G2($,q));for(let{path:q,target:Y,seed:W}of Z){if(!W)continue;if(J.push(`ts_cloud_adopt_shared '${q}' '${Y}'`),t6(q))J.push(`mkdir -p "$(dirname ${Y})"`,`touch ${Y}`);else if(q==="storage")J.push(`mkdir -p ${Y}/app/public`,`mkdir -p ${Y}/framework/cache/data`,`mkdir -p ${Y}/framework/sessions`,`mkdir -p ${Y}/framework/testing`,`mkdir -p ${Y}/framework/views`,`mkdir -p ${Y}/logs`);else J.push(`mkdir -p ${Y}`)}let Q=W2($.base);return J.push(`mkdir -p ${N0($.base)}`,`cat > ${Q} <<'TS_CLOUD_SHARED_PATHS_EOF'`,...Z.map((q)=>`${q.path} ${q.target}`),"TS_CLOUD_SHARED_PATHS_EOF"),J}function wz($,z=900){let J=`${N0($.base)}/deploy.lock`;return[`mkdir -p "$(dirname ${J})"`,`exec 9>${J}`,`flock -w ${z} 9 || { echo "[ts-cloud] another deploy of this site has held the lock for ${z}s — refusing to race it" >&2; exit 1; }`]}function Az($){let z=`${$.release}.incoming`;return[`rm -rf ${z}`,`mkdir -p ${z}`,...e6($),'if [ "$TS_CLOUD_IS_LIVE" = "yes" ]; then',` TS_CLOUD_STAGED=${z}`,"else",` rm -rf ${$.release}`,` mkdir -p ${$.release}`,` rmdir ${z}`,` TS_CLOUD_STAGED=${$.release}`,"fi"]}function Rz($){let z=`TS_CLOUD_TRAP_LIVE="$(readlink -f ${$.current} 2>/dev/null || true)"`,J=`TS_CLOUD_TRAP_TARGET="$(readlink -f ${$.release} 2>/dev/null || echo ${$.release})"`;return`trap '${`if [ $? -ne 0 ]; then ${z}; ${J}; [ "$TS_CLOUD_TRAP_LIVE" = "$TS_CLOUD_TRAP_TARGET" ] || rm -rf ${$.release}; fi`}' EXIT`}function e6($){return[`TS_CLOUD_LIVE_PATH="$(readlink -f ${$.current} 2>/dev/null || true)"`,`TS_CLOUD_RELEASE_PATH="$(readlink -f ${$.release} 2>/dev/null || echo ${$.release})"`,'if [ -n "$TS_CLOUD_LIVE_PATH" ] && [ "$TS_CLOUD_LIVE_PATH" = "$TS_CLOUD_RELEASE_PATH" ]; then TS_CLOUD_IS_LIVE=yes; else TS_CLOUD_IS_LIVE=no; fi']}function Nz($){let z=`${$.release}.incoming`;return[`if [ "$TS_CLOUD_STAGED" = "${z}" ]; then`,` rm -rf ${$.release}.previous`,` mv ${$.release} ${$.release}.previous`,` mv ${z} ${$.release}`,` rm -rf ${$.release}.previous`,"fi"]}function E$($,z=N$){let J=[];for(let Z of z){let{path:Q,target:q,seed:Y}=G2($,Z),W=`${$.release}/${Q}`,j=[`rm -rf ${W}`,`mkdir -p "$(dirname ${W})"`,`ln -sfn ${q} ${W}`];if(Y){J.push(...j);continue}J.push(`if [ -e ${q} ]; then`,...j.map((G)=>` ${G}`),"fi")}return J}function Y2($,z){let J=W2($.base);return[`if [ -f ${J} ]; then`,' while IFS="\t" read -r TS_CLOUD_SP TS_CLOUD_TGT; do',' [ -n "$TS_CLOUD_SP" ] || continue',` [ -n "$TS_CLOUD_TGT" ] || TS_CLOUD_TGT="${$.shared}/$TS_CLOUD_SP"`,' [ -e "$TS_CLOUD_TGT" ] || continue',` rm -rf ${z}/"$TS_CLOUD_SP"`,` mkdir -p "$(dirname ${z}/"$TS_CLOUD_SP")"`,` ln -sfn "$TS_CLOUD_TGT" ${z}/"$TS_CLOUD_SP"`,` done < ${J}`,"fi"]}function d0($){return[`ln -sfn ${$.release} ${$.current}.tmp`,`mv -Tf ${$.current}.tmp ${$.current}`]}function xJ($,z={}){let J=z.to?[`[ -d ${$.releases}/${z.to} ] || { echo "rollback target ${$.releases}/${z.to} not found" >&2; exit 1; }`,...Y2($,`${$.releases}/${z.to}`),`ln -sfn ${$.releases}/${z.to} ${$.current}.tmp`,`mv -Tf ${$.current}.tmp ${$.current}`]:[`TS_CLOUD_CURRENT=$(readlink -f ${$.current} 2>/dev/null || true)`,`TS_CLOUD_PREV=$(ls -1dt ${$.releases}/*/ 2>/dev/null | sed 's#/$##' | while read -r r; do [ "$(readlink -f "$r")" != "$TS_CLOUD_CURRENT" ] && { echo "$r"; break; }; done)`,'[ -n "$TS_CLOUD_PREV" ] || { echo "no previous release to roll back to" >&2; exit 1; }',...Y2($,'"$TS_CLOUD_PREV"'),`ln -sfn "$TS_CLOUD_PREV" ${$.current}.tmp`,`mv -Tf ${$.current}.tmp ${$.current}`,'echo "rolled back to $TS_CLOUD_PREV"'];if(!z.unitBase)return J;let Z=z.unitBase;return[...J,`TS_CLOUD_RB_ID=$(basename "$(readlink -f ${$.current})")`,`if [ -f /etc/systemd/system/${Z}@.service ]; then systemctl start "${Z}@\${TS_CLOUD_RB_ID}.service"; sleep 2; systemctl is-active --quiet "${Z}@\${TS_CLOUD_RB_ID}.service" || { echo "rolled-back release failed to start" >&2; exit 1; }; systemctl enable "${Z}@\${TS_CLOUD_RB_ID}.service" 2>/dev/null || true; systemctl list-units --plain --no-legend --type=service "${Z}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v "^${Z}@\${TS_CLOUD_RB_ID}.service$" || true; } | while read -r TS_CLOUD_U; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done; elif [ -f /etc/systemd/system/${Z}.service ]; then systemctl restart ${Z}.service; fi`]}function c0($,z=4){let J=Math.max(1,z);return[`TS_CLOUD_CURRENT=$(readlink -f ${$.current} 2>/dev/null || true)`,`ls -1dt ${$.releases}/*/ 2>/dev/null | sed 's#/$##' | tail -n +${J+1} | while read -r TS_CLOUD_OLD; do`,' [ "$(readlink -f "$TS_CLOUD_OLD")" = "$TS_CLOUD_CURRENT" ] || rm -rf "$TS_CLOUD_OLD"',"done"]}function $8($){return`${N0($)}/owner`}function Ez($,z){let J=$8($);return[`if [ -f "${J}" ]; then`,` TS_CLOUD_OWNER=$(cat "${J}")`,` if [ "$TS_CLOUD_OWNER" != "${z}" ]; then`,` echo "[ts-cloud] REFUSING deploy: ${$} belongs to project '$TS_CLOUD_OWNER', not '${z}'. Another project on this box derives the same site key — give one of them a distinct site name/domain, or remove ${J} to transfer ownership." >&2`," exit 1"," fi","else",` mkdir -p "$(dirname "${J}")"`,` printf '%s\\n' "${z}" > "${J}"`,"fi"]}function _$($,z){let J=N0($),Z=i6($,z.releaseId),Q=n6($),q=Math.max(1,z.keepLogs??20),Y=z.commit||"",W=z.branch||"";return[`mkdir -p ${J}/deploys`,`exec > >(tee -a ${Z}) 2>&1`,`echo "[ts-cloud] deploy ${z.releaseId} commit=${Y} branch=${W} starting $(date -u +%Y-%m-%dT%H:%M:%SZ)"`,"ts_cloud_record_deploy() {"," TS_CLOUD_RC=$?",' if [ "$TS_CLOUD_RC" -eq 0 ]; then TS_CLOUD_ST=success; else TS_CLOUD_ST=failed; fi',` printf '%s\\t%s\\t%s\\t%s\\trc=%s\\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "${z.releaseId}" "${Y}" "$TS_CLOUD_ST" "$TS_CLOUD_RC" >> ${Q}`,"}","trap ts_cloud_record_deploy EXIT",`ls -1t ${J}/deploys/*.log 2>/dev/null | tail -n +${q+1} | while read -r TS_CLOUD_OLDLOG; do rm -f "$TS_CLOUD_OLDLOG"; done`]}function _z($,z){let J=z==="bun"?"/usr/local/bin/bun":z==="deno"?"/usr/local/bin/deno":"/usr/local/bin/node",Z=$.replace(/^(bun|node|deno)\s+/,"");return`${J} ${Z}`}function kz($){let{siteName:z,slug:J,artifactFetch:Z,releaseId:Q,execStart:q,envEntries:Y,port:W,keepReleases:j=$$,preStartCommands:G=[],healthCheckPath:H,healthGateSeconds:M=5,memoryHigh:X="2G",memoryMax:K,cpuWeight:O,ioWeight:L,tasksMax:B,stopTimeout:U}=$,F=[...O!=null?[`CPUWeight=${O}`]:[],...L!=null?[`IOWeight=${L}`]:[],...B!=null?[`TasksMax=${B}`]:[],...U?[`TimeoutStopSec=${U}`]:[]],V=$.zeroDowntime??W!=null,x=$.appDir??`/var/www/${z}`,C=z$(x,Q),A=`${J}-${z}`,D=`${A}.service`,T=Z$(J,z,Q),r=j2([".env",...$.sharedPaths??[]]),f=R$(Y),v=G.length>0?[`cd ${C.release}`,...G]:[],b=["set -euo pipefail",...wz(C),Rz(C),...Z,...J$(C,r),...Az(C),`tar xzf ${T} -C "$TS_CLOUD_STAGED"`,`rm -f ${T}`,`cat > ${C.shared}/.env <<'TS_CLOUD_ENV_EOF'`,f,"TS_CLOUD_ENV_EOF",`chmod 600 ${C.shared}/.env`,...Nz(C),`find ${C.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' ${C.shared}/.env 2>/dev/null || true`,...E$(C,r),...v];if(V&&W!=null){let R=`${A}@${Q}.service`,u=H?H.startsWith("/")?H:`/${H}`:null,y=`{ echo "[ts-cloud] release ${Q} failed its health gate — previous release keeps serving" >&2; journalctl -u ${R} -n 50 --no-pager >&2 || true; systemctl stop ${R} 2>/dev/null || true; exit 1; }`;return[...b,`cat > /etc/systemd/system/${A}@.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${z} release %i (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${C.releases}/%i`,`ExecStart=${q}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...X?[`MemoryHigh=${X}`]:[],...K?[`MemoryMax=${K}`]:[],...F,`EnvironmentFile=${C.releases}/%i/.env`,`Environment=PORT=${W}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",`TS_CLOUD_OLD_UNITS=$(systemctl list-units --plain --no-legend --type=service "${A}@*.service" 2>/dev/null | awk '{print $1}' | grep -v "^${R}$" || true)`,`if [ -f /etc/systemd/system/${D} ] && systemctl is-active --quiet ${D}; then echo "[ts-cloud] retiring pre-zero-downtime unit ${D} (one-time restart cutover)"; systemctl stop ${D}; fi`,`systemctl restart ${R}`,`TS_CLOUD_GATE_OK=1; for TS_CLOUD_I in $(seq 1 ${Math.max(1,M)}); do sleep 1; systemctl is-active --quiet ${R} || { TS_CLOUD_GATE_OK=0; break; }; done`,`if [ "$TS_CLOUD_GATE_OK" -ne 1 ]; then echo "[ts-cloud] release ${Q} 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 ${R}; for TS_CLOUD_I in $(seq 1 ${Math.max(1,M)}); do sleep 1; systemctl is-active --quiet ${R} || ${y}; done; fi`,...u?[`curl -sf -o /dev/null --max-time 10 "http://127.0.0.1:${W}${u}" || ${y}`]:[],...d0(C),`systemctl enable ${R} 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,M)}); do if ss -ltnH "sport = :${W}" 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 ${W} after retiring the previous release — restarting ${R} on the now-free port" >&2; systemctl restart ${R}; for TS_CLOUD_I in $(seq 1 ${Math.max(1,M)}); do if ss -ltnH "sport = :${W}" 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] ${R} is active but never bound ${W}" >&2; journalctl -u ${R} -n 50 --no-pager >&2 || true; exit 1; fi`,`systemctl list-unit-files --plain --no-legend "${A}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v -e "^${R}$" -e "^${A}@\\.service$" || true; } | while read -r TS_CLOUD_U; do systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done`,`if [ -f /etc/systemd/system/${D} ]; then systemctl disable ${D} 2>/dev/null || true; rm -f /etc/systemd/system/${D}; systemctl daemon-reload; fi`,...c0(C,j)]}return[...b,`cat > /etc/systemd/system/${D} <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${z} (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${C.current}`,`ExecStart=${q}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...X?[`MemoryHigh=${X}`]:[],...K?[`MemoryMax=${K}`]:[],...F,`EnvironmentFile=${C.current}/.env`,...W?[`Environment=PORT=${W}`]:[],"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",`systemctl enable ${D}`,...d0(C),`systemctl restart ${D}`,`systemctl is-active ${D}`,...c0(C,j)]}function Tz($){let{siteName:z,artifactFetch:J,releaseId:Z,keepReleases:Q=$$,preStartCommands:q=[]}=$,Y=$.appDir??`/var/www/${z}`,W=z$(Y,Z),j=Z$($.slug,z,Z),G=q.length>0?[`cd ${W.release}`,...q]:[];return["set -euo pipefail",...wz(W),Rz(W),...J,...J$(W,[]),...Az(W),`tar xzf ${j} -C "$TS_CLOUD_STAGED"`,...Nz(W),`rm -f ${j}`,...G,...d0(W),...c0(W,Q)]}function Z$($,z,J){return`/tmp/${[$,z,J].filter(Boolean).join("-")}-release.tar.gz`}function yz($,z,J,Z){return[`aws s3 cp "s3://${$}/${z}" ${Z} --region ${J}`]}function Pz($,z){return[`mv "${$}" ${z}`]}function Iz(){return['echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',"find /var/ts-cloud/staging -xdev -maxdepth 1 -type f -mmin +60 -delete 2>/dev/null || true",'find /tmp -xdev -maxdepth 1 -type f -name "*-release.tar.gz" -mmin +60 -delete 2>/dev/null || true',"find /root/.bun/install/cache -xdev -type f -mtime +7 -delete 2>/dev/null || true","find /root/.bun/install/cache -xdev -depth -type d -empty -delete 2>/dev/null || true","journalctl --vacuum-time=14d --vacuum-size=512M >/dev/null 2>&1 || true",'if command -v docker >/dev/null 2>&1; then docker image prune --all --force --filter "until=168h" >/dev/null 2>&1 || true; fi','if command -v podman >/dev/null 2>&1; then podman image prune --all --force --filter "until=168h" >/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",'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"']}import{copyFileSync as h8}from"node:fs";import{tmpdir as m8}from"node:os";import{join as v8}from"node:path";import{execSync as H2}from"node:child_process";import{randomBytes as J8}from"node:crypto";import{chmodSync as Z8,copyFileSync as Q8,existsSync as E0,mkdirSync as M2,readFileSync as O2,statSync as q8,writeFileSync as bz}from"node:fs";import{tmpdir as Y8}from"node:os";import{basename as W8,dirname as uz,isAbsolute as V2,join as m,resolve as j8}from"node:path";import{fileURLToPath as F2}from"node:url";function Sz($){if(!$||typeof $!=="object")return $;return Object.fromEntries(Object.keys($).map((z)=>[z,""]))}function z8($){let z=JSON.parse(JSON.stringify($??{}));if(z.hetzner)delete z.hetzner.apiToken;delete z.aws,delete z.stateDir;for(let J of Object.values(z.sites??{})){if(J?.env)J.env=Sz(J.env);if(J?.environment)J.environment=Sz(J.environment)}for(let J of Object.values(z.environments??{}))if(J?.variables)J.variables=Sz(J.variables);for(let J of Object.values(z.infrastructure?.databases??{}))if(J?.password)J.password="";if(z.infrastructure?.appDatabase?.password)z.infrastructure.appDatabase.password="";if(z.infrastructure?.compute?.database?.password)z.infrastructure.compute.database.password="";if(z.infrastructure?.compute?.managedServices?.vitess?.password)z.infrastructure.compute.managedServices.vitess.password="";return z}function K2($){let z=z8($);return["// Generated by ts-cloud for the management dashboard — do not edit.","//","// This is the project's resolved cloud config, inlined so it needs no","// imports on the box. Credentials are deliberately absent.",`export default ${JSON.stringify(z,null,2)}`,""].join(`
|
|
399
|
+
`)}var G8="dashboard";function B2(){return mz("dashboard-credentials.json")}function K8(){return J8(24).toString("base64url")}function H8($,z,J){let Z=process.env.TS_CLOUD_UI_PASSWORD?.trim();if(Z)return{password:Z,source:"env"};if(hz(process.env.TS_CLOUD_UI_PUBLIC))return{password:void 0,source:"public"};let Q=B2(),q=vz($,"dashboard-credentials.json");try{if(E0(q)){let W=JSON.parse(O2(q,"utf8"));if(W?.password)return{password:W.password,source:"generated"}}}catch{}let Y=K8();try{M2(uz(q),{recursive:!0}),bz(q,`${JSON.stringify({username:z,password:Y,generatedAt:new Date().toISOString()},null,2)}
|
|
400
|
+
`),Z8(q,384),J.info(`Management dashboard: generated a password for '${z}' and saved it to ${Q} (read it there — it is not printed). Set TS_CLOUD_UI_PASSWORD to pin your own, or TS_CLOUD_UI_PUBLIC=1 to serve without auth.`)}catch(W){J.warn(`Management dashboard: could not persist the generated password (${W?.message??W}). Using it for this deploy only — pass: ${Y}
|
|
401
|
+
This password is now in your deploy log. Set TS_CLOUD_UI_PASSWORD to a value of your own and redeploy once ${Q} is writable.`)}return{password:Y,source:"generated"}}var U2={info:()=>{},warn:()=>{}};function hz($){return $!=null&&$!==""&&$!=="0"&&$.toLowerCase()!=="false"}function X8(){return mz("dashboard-release")}function C2(){let $=uz(F2(import.meta.url));for(let z of[m($,"..","..","package.json"),m($,"..","package.json")])try{let J=JSON.parse(O2(z,"utf8"));if(J.name==="@stacksjs/ts-cloud"&&J.version)return`^${J.version}`}catch{}return"latest"}function M8(){return process.env.TS_CLOUD_UI_VERSION?.trim()||C2()}function O8($,z,J){if(!$?.project?.slug)return J.warn("Management dashboard: the cloud config has no project slug — skipping the live dashboard."),null;let Z=vz(z,"dashboard-release");try{M2(Z,{recursive:!0}),bz(m(Z,"cloud.config.ts"),K2($));let Q=M8();if(Q.startsWith("file:")){let Y=Q.slice(5),W=V2(Y)?Y:j8(z,Y);if(!E0(W)||!q8(W).isFile())Q=C2(),J.warn(`Management dashboard: TS_CLOUD_UI_VERSION points to a missing package file (${W}); using the deploying ts-cloud version ${Q} instead.`);else{let j=W8(W),G=m(Z,j);if(W!==G)Q8(W,G);Q=`file:./${j}`}}let q={name:"ts-cloud-dashboard",private:!0,type:"module",dependencies:{"@stacksjs/ts-cloud":Q}};return bz(m(Z,"package.json"),`${JSON.stringify(q,null,2)}
|
|
402
|
+
`),X8()}catch(Q){return J.warn(`Management dashboard: could not stage the live release (${Q?.message??Q}) — skipping.`),null}}function V8($){if(E0(m($,"packages","ui","pages"))||E0(m($,"packages","ui","package.json")))return{uiRoot:"packages/ui/dist",build:"cd packages/ui && bun install && bun run build"};let z=uz(F2(import.meta.url)),J=[m(z,"ui"),m(z,"..","ui"),m(z,"..","..","ui"),m(z,"..","dist","ui")];for(let Z of J)if(E0(m(Z,"index.html"))||E0(m(Z,"serverless.html")))return{uiRoot:Z,build:!1};return null}function gz($,z={}){let J=z.logger??U2,Z=z.cwd??process.cwd();if(hz(process.env.TS_CLOUD_UI_DISABLE))return J.info("Management dashboard: skipped (TS_CLOUD_UI_DISABLE set)."),$;if($.cloud?.attachTo)return J.info(`Management dashboard: ${$.project.slug} is attached to ${$.cloud.attachTo}; the server owner's dashboard monitors every attached project.`),$;if(Q$($))return $;let Q=$.environments&&Object.keys($.environments)[0],q=process.env.TS_CLOUD_UI_DOMAIN?.trim()||void 0,Y=Number(process.env.TS_CLOUD_UI_PORT)||void 0,W={...$.sites??{}};if(!hz(process.env.TS_CLOUD_UI_STATIC)){let K=O8($,Z,J);if(!K)return $;let O=fz($,Q??"production",{uiRoot:K,build:!1,domain:q,port:Y,live:!0});if(O.length===0)return J.info("Management dashboard: no domain resolved (set TS_CLOUD_UI_DOMAIN or configure a site domain) — skipping."),$;for(let{name:L,site:B}of O)W[L]=B,J.info(`Management dashboard → https://${B.domain} (sign in with your ts-cloud account; the first deploy prints an admin password once)`);return $.sites=W,$}let j=V8(Z);if(!j)return J.info("Management dashboard: UI not found (no local ui/ or packaged dist/ui) — skipping auto-deploy."),$;let G=process.env.TS_CLOUD_UI_USERNAME?.trim()||"admin",H=H8(Z,G,J),M=fz($,Q??"production",{uiRoot:j.uiRoot,build:j.build,domain:q,username:G,password:H.password,realm:process.env.TS_CLOUD_UI_REALM?.trim()||void 0,live:!1,port:Y});if(M.length===0)return J.info("Management dashboard: no domain resolved (set TS_CLOUD_UI_DOMAIN or configure a site domain) — skipping."),$;let X=H.source==="public"?"NO AUTH — TS_CLOUD_UI_PUBLIC is set (dashboard is publicly reachable)":H.source==="env"?"htpasswd-protected (TS_CLOUD_UI_PASSWORD)":`htpasswd-protected (auto-generated — see ${B2()})`;J.warn("Management dashboard: static mode — one shared password, and no per-site collaborators. Unset TS_CLOUD_UI_STATIC for the live dashboard.");for(let{name:K,site:O}of M)W[K]=O,J.info(`Management dashboard → https://${O.domain} (${X})`);return $.sites=W,$}function dz($){return Object.keys($.sites??{}).filter(X2)}function L2($,z){if(!$?.root)return null;let J=z.cwd??process.cwd(),Z=z.logger??U2;try{if(typeof $.build==="string"&&$.build.trim())Z.info(`Management dashboard: building UI (${$.build})`),H2($.build,{cwd:J,stdio:"inherit"});let Q=V2($.root)?$.root:m(J,$.root);if(!E0(Q))return Z.warn(`Management dashboard: build output not found at ${Q} — skipping dashboard artifact.`),null;let q=m(Y8(),`${z.slug}-${z.siteName??G8}-${z.sha}.tar.gz`);return H2(`tar czf "${q}" -C "${Q}" .`,{stdio:"inherit"}),q}catch(Q){return Z.warn(`Management dashboard: failed to build artifact — ${Q?.message??Q}. Skipping dashboard deploy.`),null}}var F8=new Set(["laravel","php","statamic","wordpress"]);function w2($){if($.framework)return $.framework;if($.type&&F8.has($.type))return"laravel";return"stacks"}var x2=`eval "$(cd ${l} && pantry env 2>/dev/null)"`,D2="/usr/local/bin/bun",B8="storage/framework/core/buddy/src/cli.ts",U8="node_modules/@stacksjs/ts-cloud/dist/bin/stacks-scheduler.js",A2={id:"stacks",wrapExec:($)=>$,execEnv:{PATH:"/usr/local/bin:/usr/bin:/bin",BUN_INSTALL:"/root/.bun",APP_ENV:"production",NODE_ENV:"production"},schedulerMode:"daemon",schedulerCommand:()=>`${D2} ${U8}`,queueWorkerCommand:($,{current:z})=>{let J=[`--queue=${$.queue||"default"}`,`--sleep=${$.sleep??3}`,`--tries=${$.tries??3}`,`--timeout=${$.timeout??60}`];return`${D2} ${z}/${B8} queue:work ${J.join(" ")}`}},C8={id:"laravel",wrapExec:($)=>`/bin/sh -lc '${x2}; exec ${$}'`,schedulerMode:"cron",schedulerCommand:({current:$})=>`cd ${$} && ${x2} && php artisan schedule:run`,queueWorkerCommand:($,{current:z})=>{let J=`${z}/artisan`;if($.horizon)return`php ${J} horizon`;let Z=[$.connection||"default",`--queue=${$.queue||"default"}`,`--sleep=${$.sleep??3}`,`--tries=${$.tries??3}`,`--timeout=${$.timeout??60}`,`--memory=${$.memory??128}`];if($.maxJobs)Z.push(`--max-jobs=${$.maxJobs}`);if($.maxTime)Z.push(`--max-time=${$.maxTime}`);return`php ${J} queue:work ${Z.join(" ")}`}},L8={stacks:A2,laravel:C8};function R2($){return L8[$]??A2}function N2($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function x8($){return`'${$.split("'").join("'\\''")}'`}function E2($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"unnamed"}function D8($,z,J){return`${$}-${z}-queue-${J}`}function w8($,z,J,Z){return`${$}-${z}-daemon-${J.name?E2(J.name):E2(J.command).slice(0,32)||String(Z)}`}function cz($){let z=["[Unit]",`Description=${$.description}`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${$.workingDir}`,...Object.entries($.environment??{}).map(([J,Z])=>`Environment="${J}=${Z}"`),`ExecStart=${$.execStart}`,`Restart=${$.restart||"always"}`,"RestartSec=5","MemoryAccounting=true",`MemoryHigh=${$.memoryHigh??"2G"}`,...$.memoryMax?[`MemoryMax=${$.memoryMax}`]:[]];if($.user)z.push(`User=${$.user}`);if(typeof $.stopWaitSecs==="number")z.push(`TimeoutStopSec=${$.stopWaitSecs}`);return z.push("","[Install]","WantedBy=multi-user.target"),`${z.join(`
|
|
403
|
+
`)}
|
|
404
|
+
`}function lz($,z){return[`cat > /etc/systemd/system/${$}.service <<'TS_CLOUD_UNIT_EOF'`,z.replace(/\n$/,""),"TS_CLOUD_UNIT_EOF"]}function A8($,z){return`/etc/cron.d/${$}-${z}-scheduler`}function pz($){let{slug:z,siteName:J,site:Z}=$,q=`${$.appBase??`/var/www/${J}`}/current`,Y=R2(w2(Z)),W={current:q},j=[],G=[];(Z.queues||[]).forEach((U,F)=>{let V=Math.max(1,U.processes??1);for(let x=0;x<V;x++){let C=D8(z,J,G.length);G.push(C),j.push(...lz(C,cz({description:`${J} queue worker ${F}.${x} (managed by ts-cloud)`,workingDir:q,execStart:Y.wrapExec(Y.queueWorkerCommand(U,W)),environment:Y.execEnv,stopWaitSecs:U.stopWaitSecs??90})))}}),(Z.daemons||[]).forEach((U,F)=>{let V=Math.max(1,U.processes??1);for(let x=0;x<V;x++){let C=`${w8(z,J,U,F)}-${x}`;G.push(C),j.push(...lz(C,cz({description:`${J} daemon ${U.name||U.command} (managed by ts-cloud)`,workingDir:U.directory||q,execStart:Y.wrapExec(U.command),environment:Y.execEnv,restart:U.restart,user:U.user})))}});let X=Z.scheduler,K=X===!0||typeof X==="object"&&X!==null,O=`${z}-${J}-scheduler`;if(K&&Y.schedulerMode==="daemon")G.push(O),j.push(...lz(O,cz({description:`${J} scheduler (managed by ts-cloud)`,workingDir:q,execStart:Y.wrapExec(Y.schedulerCommand(W)),environment:Y.execEnv})));let L=G.map((U)=>`${U}.service`).join(" ");j.push("systemctl daemon-reload",`TS_CLOUD_DESIRED="${L}"`,`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E '^${N2(z)}-${N2(J)}-((queue|daemon)-.*|scheduler)\\.service$' || true); do`,' case " $TS_CLOUD_DESIRED " in',' *" $unit "*) ;;',' *) systemctl stop "$unit" 2>/dev/null || true; systemctl disable "$unit" 2>/dev/null || true; rm -f "/etc/systemd/system/$unit" ;;'," esac","done","systemctl daemon-reload");for(let U of G)j.push(`systemctl enable ${U}.service`,`systemctl restart ${U}.service`);let B=A8(z,J);if(K&&Y.schedulerMode==="cron"){let U=typeof X==="object"&&X!==null?X:void 0,F=`${Y.schedulerCommand(W)} >> /dev/null 2>&1`;if(U?.heartbeatUrl){let x=U.heartbeatMethod||"GET",C=x==="GET"?"":`-X ${x} `;F+=` && curl -fsS -m 10 ${C}${x8(U.heartbeatUrl)} >/dev/null 2>&1`}let V=`* * * * * root ${F}
|
|
405
|
+
`.replace(/%/g,"\\%");j.push(`cat > ${B} <<'TS_CLOUD_CRON_EOF'`,V.replace(/\n$/,""),"TS_CLOUD_CRON_EOF",`chmod 644 ${B}`)}else j.push(`rm -f ${B}`);return j}function az($){return!!($.queues?.length||$.daemons?.length||$.scheduler)}function rz($){if($.ssl?.provider)return $.ssl.provider;return $.domain?"letsencrypt":"none"}var _2={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 k2($){return`/etc/letsencrypt/ts-cloud-${$}.ini`}function R8($){let z=$?_2[$.provider]:void 0,J=["certbot","python3-certbot-nginx",...z?[z.pkg]:[]].join(" ");return["export DEBIAN_FRONTEND=noninteractive",z?`apt-get update -y && apt-get install -y ${J}`:`command -v certbot >/dev/null 2>&1 || { apt-get update -y && apt-get install -y ${J}; }`,"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 N8($){if(!$.credentials||Object.keys($.credentials).length===0)return[];let z=k2($.provider),J=Object.entries($.credentials).map(([Z,Q])=>`${Z} = ${Q}`).join(`
|
|
406
|
+
`);return[`cat > ${z} <<'TS_CLOUD_DNSCREDS_EOF'`,J,"TS_CLOUD_DNSCREDS_EOF",`chmod 600 ${z}`]}function E8($){let z=$.dns,J=$.wildcard?[`*.${$.domain}`,$.domain]:[$.domain,...$.aliases||[]].filter(Boolean),Z=["certbot","--non-interactive","--agree-tos","--keep-until-expiring"];if(z){let Q=_2[z.provider].plugin;if(Z.push(`--${Q}`),z.provider!=="route53"&&z.credentials)Z.push(`--${Q}-credentials ${k2(z.provider)}`);if(typeof z.propagationSeconds==="number"&&z.provider!=="route53")Z.push(`--${Q}-propagation-seconds ${z.propagationSeconds}`);Z.push("certonly")}else Z.push("--nginx",`--nginx-ctl ${H0}`,$.redirect===!1?"--no-redirect":"--redirect");if($.email)Z.push(`-m ${$.email}`);else Z.push("--register-unsafely-without-email");for(let Q of J)Z.push(`-d ${Q}`);return[Z.join(" ")]}function nz($){if(rz($)!=="letsencrypt"||!$.domain)return[];let z=$.ssl,J=z?.dns,Z=z?.wildcard===!0;if(Z&&!J)return[];return[...R8(J),...J?N8(J):[],...E8({domain:$.domain,aliases:$.aliases,email:z?.email,wildcard:Z,dns:J})]}function T2($){let{repository:z,releaseDir:J,commit:Z}=$,Q=z.branch||"main",q=z.url,Y=[`rm -rf ${J}`,`mkdir -p ${J}`];if(z.strategy==="tag")if(z.tag)Y.push(`git clone -q --depth 1 --branch ${a(z.tag)} ${a(q)} ${J}`),Y.push(`printf '%s' ${a(z.tag)} > ${J}/.ts-cloud-tag`);else{let W=z.tagPattern||"v*";Y.push(`TS_CLOUD_TAG="$(git ls-remote --tags --refs --sort=-v:refname ${a(q)} ${a(`refs/tags/${W}`)} | head -n1 | sed 's#.*refs/tags/##')"`,`test -n "$TS_CLOUD_TAG" || { echo "no tags matching" ${a(W)} "found in" ${a(q)} >&2; exit 1; }`,`git clone -q --depth 1 --branch "$TS_CLOUD_TAG" ${a(q)} ${J}`,`printf '%s' "$TS_CLOUD_TAG" > ${J}/.ts-cloud-tag`)}else if(Z)Y.push(`git -C ${J} init -q`,`git -C ${J} remote add origin ${a(q)}`,`git -C ${J} fetch -q --depth 1 origin ${a(Z)}`,`git -C ${J} checkout -q FETCH_HEAD`);else Y.push(`git clone -q --depth 1 --branch ${a(Q)} ${a(q)} ${J}`);return Y.push(`git -C ${J} rev-parse HEAD > ${J}/.ts-cloud-sha`),Y}function a($){return`'${$.split("'").join("'\\''")}'`}var k$="$CREATE_RELEASE",T$="$ACTIVATE_RELEASE",I2="$RESTART_QUEUES",y2="composer install --no-interaction --prefer-dist --optimize-autoloader --no-dev",_8=["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 k8($){switch($){case"laravel":case"statamic":return[k$,y2,..._8,T$,I2];case"php":case"wordpress":return[k$,`${y2} || true`,T$];case"static":case"spa":return[k$,T$]}}function T8($,z){return $.replace(/^php\s+/,`${z} `).replace(/(\s)php\s+artisan\s+/g,`$1${z} artisan `)}function y8($,z){let J=R$(z);return[`cat > ${$} <<'TS_CLOUD_ENV_EOF'`,J,"TS_CLOUD_ENV_EOF",`chmod 600 ${$}`]}function P2($,z,J){return[`cat > ${$} <<'${J}'`,z.replace(/\n$/,""),J,`chmod 600 ${$}`]}function P8($,z){if(!z)return[];let J=[];if(z.composerAuth){let Z=typeof z.composerAuth==="string"?z.composerAuth:JSON.stringify(z.composerAuth,null,2);J.push(...P2(`${$}/auth.json`,Z,"TS_CLOUD_AUTHJSON_EOF"))}if(z.npmrc)J.push(...P2(`${$}/.npmrc`,z.npmrc,"TS_CLOUD_NPMRC_EOF"));return J}function S2($){let z=$.healthCheck?.path;if(!z||!$.domain)return[];let Z=`http://127.0.0.1${z.startsWith("/")?z:`/${z}`}`;return[`echo "[ts-cloud] health check ${Z} (Host: ${$.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: ${$.domain}" -m 10 "${Z}" 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 f2($){let{siteName:z,site:J,releaseId:Z,commit:Q}=$;if(!J.repository?.url)throw Error(`Site '${z}' is a PHP/git site but has no repository.url to clone`);let q=$.appBase??`/var/www/${z}`,Y="php",W=z$(q,Z),j=J.sharedPaths??N$,G=J.keepReleases??$$,H=J.deployScript?.length?J.deployScript:k8(J.type??"laravel"),M=["set -euo pipefail",'export HOME="${HOME:-/root}"','export COMPOSER_HOME="${COMPOSER_HOME:-/root/.composer}"',"export COMPOSER_ALLOW_SUPERUSER=1",C0()];if(M.push(..._$(q,{releaseId:Z,commit:Q,branch:J.repository.branch,keepLogs:G})),M.push(...J$(W,j)),J.env&&Object.keys(J.env).length>0)M.push(...y8(`${W.shared}/.env`,J.env));for(let X of H){let K=X.trim();if(K===k$)M.push(...T2({repository:J.repository,releaseDir:W.release,commit:Q})),M.push(...E$(W,j)),M.push(`cd ${W.release}`),M.push(...P8(W.release,J.credentials)),M.push(`chown -R www-data:www-data ${W.shared}/storage 2>/dev/null || true`,`[ -d ${W.release}/bootstrap/cache ] && chown -R www-data:www-data ${W.release}/bootstrap/cache 2>/dev/null || true`,`chmod -R ug+rwX ${W.shared}/storage 2>/dev/null || true`);else if(K===T$)M.push(...d0(W)),M.push(...c0(W,G)),M.push(`(cd ${l} && pantry restart php-fpm) 2>/dev/null || true`);else if(K===I2)M.push(`${Y} artisan queue:restart || true`);else M.push(T8(X,Y))}return M}var b2="/var/lib/pantry/php-fpm/pool.d",I8=9100,S8=400;function y$($){return($.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"site").slice(0,28)}function h2($){return`web_${y$($)}`}function f8($){let z=y$($),J=0;for(let Z=0;Z<z.length;Z++)J=J*31+z.charCodeAt(Z)>>>0;return I8+J%S8}function iz($){return`127.0.0.1:${f8($)}`}function b8($){let z=y$($.siteName),J=h2($.siteName),Z=$.maxChildren??10;return[`; ts-cloud-managed pool for ${$.siteName} (site isolation)`,`[${z}]`,`user = ${J}`,`group = ${J}`,`listen = ${iz($.siteName)}`,"pm = dynamic",`pm.max_children = ${Z}`,"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] = ${$.appBase}:/tmp`,""].join(`
|
|
407
|
+
`)}function m2($){let z=h2($.siteName),J=y$($.siteName),Z=`${b2}/${J}.conf`;return[`getent group ${z} >/dev/null || groupadd --system ${z}`,`id -u ${z} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin -g ${z} ${z}`,`usermod -aG ${z} www-data 2>/dev/null || true`,`chown -R ${z}:${z} ${$.appBase} || true`,`chmod -R g+rX ${$.appBase} || true`,`chmod 600 ${$.appBase}/shared/.env 2>/dev/null || true`,`mkdir -p ${b2}`,`cat > ${Z} <<'TS_CLOUD_FPMPOOL_EOF'`,b8($).replace(/\n$/,""),"TS_CLOUD_FPMPOOL_EOF",`(cd ${l} && pantry restart php-fpm) 2>/dev/null || true`]}var I$={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};function u8($){return`'${$.replace(/'/g,`'"'"'`)}'`}async function v2($,z,J=I$){let{config:Z,environment:Q,siteName:q,site:Y,slug:W,sha:j,runtime:G,localTarballPath:H}=z,M=`releases/${q}/${j}.tar.gz`,X=I(Z,Q),K=await $.getComputeOutputs({config:Z,environment:Q}),O=await $.findComputeTargets({slug:W,environment:Q,role:"app",stackName:X});if(O.length===0)return{success:!1,error:$.name==="aws"?`Stack '${X}' has no EC2 instances tagged Project=${W} Environment=${Q} Role=app, and storage/cloud/state/${X}.json pins no live instance. For a shared box, record its instanceId there.`:`No Hetzner servers labeled ts-cloud/project=${W} ts-cloud/environment=${Q} ts-cloud/role=app, and storage/cloud/state/${X}.json pins no live server. For a shared box, record its serverId there.`};let L=K.servicesPrivateIp?g1(K.servicesPrivateIp,V0(Z)):W1(V0(Z)),B=Z.infrastructure?.compute,U=o(B)?{HOST:"127.0.0.1"}:{},F=Q==="production"?{APP_ENV:"production",NODE_ENV:"production"}:{},V={...L,...U,...Y.env||{},...F};if(r0(Y)){let z0=Y.phpVersion??B?.php?.default??B?.php?.versions?.[0],n=i$(W,q),U0=Object.keys(L).length>0?{...Y,env:V}:Y,N=f2({siteName:q,site:U0,releaseId:j,appBase:n,defaultPhpVersion:z0}),_=!o(B),E=rz(Y)==="custom"&&Y.ssl?.certPath&&Y.ssl?.keyPath?{certPath:Y.ssl.certPath,keyPath:Y.ssl.keyPath}:void 0,P=Y.isolation?m2({siteName:q,appBase:n}):[],i=_?a$({siteName:q,domain:Y.domain||q,aliases:Y.aliases,type:Y.type,appDir:`${n}/current`,webDirectory:Y.webDirectory,phpVersion:z0,fastcgiPass:Y.isolation?iz(q):void 0,redirects:Y.redirects,ssl:E,auth:Y.auth&&Y.auth.enabled!==!1&&Y.auth.password?{username:Y.auth.username||"admin",password:Y.auth.password,realm:Y.auth.realm}:void 0,serverSnippet:p$(Y.nginx,B?.nginxTemplates),clientMaxBodySize:Y.nginx?.clientMaxBodySize,hsts:Y.ssl?.hsts,tlsProtocols:Y.ssl?.tlsProtocols,security:Y.security}):[],Y0=_?nz(Y):[],l0=az(Y)?pz({slug:W,siteName:q,site:Y,phpVersion:z0,appBase:n}):[],S$=_?S2(Y):[];J.step(`Deploying PHP site '${q}' to ${O.length} target(s)...`);let t=await $.runRemoteDeploy({targets:O,commands:[...Ez(n,W),...N,...P,...i,...Y0,...l0,...S$],comment:`ts-cloud deploy ${W}/${q}@${j}`,tags:{Project:W,Environment:Q,Role:"app"}}),oz=X1(Z.notifications,Y.notifications);if(!t.success)return await n$(oz,"deploy-failed",`❌ Deploy of ${W}/${q}@${j} failed: ${t.error||"unknown error"}`),{success:!1,error:t.error||"Remote PHP deploy failed",instanceCount:t.instanceCount,perInstance:t.perInstance};let g2=Y.domain?` → https://${Y.domain}`:"";return await n$(oz,"deploy",`✅ Deployed ${W}/${q}@${j}${g2}`),{success:!0,instanceCount:t.instanceCount,perInstance:t.perInstance}}if(!H)return{success:!1,error:`Site '${q}' requires a release tarball but none was provided`};let x=await $.uploadRelease({config:Z,environment:Q,localPath:H,remoteKey:M,targets:O}),C=Z$(W,q,j),A=$.name==="aws"?yz(K.deployBucketName,M,Z.project.region||"us-east-1",C):Pz(x.artifactRef,C),D=$0(Y),T=i$(W,q),r=D==="server-static"?Tz({siteName:q,slug:W,appDir:T,artifactFetch:A,releaseId:j,preStartCommands:Y.preStart}):kz({siteName:q,slug:W,appDir:T,artifactFetch:A,releaseId:j,execStart:_z(Y.start,G),envEntries:V,port:Y.port,preStartCommands:Y.preStart,sharedPaths:Y.sharedPaths,zeroDowntime:Y.zeroDowntime!==!1,healthCheckPath:Y.healthCheck?.path,memoryHigh:Y.memoryHigh,memoryMax:Y.memoryMax,cpuWeight:Y.cpuWeight,ioWeight:Y.ioWeight,tasksMax:Y.tasksMax,stopTimeout:Y.stopTimeout}),f=D==="server-static"&&!o(B)&&!!Y.domain,v=f?a$({siteName:q,domain:Y.domain,aliases:Y.aliases,type:Y.type==="spa"?"spa":"static",appDir:`${T}/current`,webDirectory:"",redirects:Y.redirects,auth:Y.auth&&Y.auth.enabled!==!1&&Y.auth.password?{username:Y.auth.username||"admin",password:Y.auth.password,realm:Y.auth.realm}:void 0,serverSnippet:p$(Y.nginx,B?.nginxTemplates),clientMaxBodySize:Y.nginx?.clientMaxBodySize,hsts:Y.ssl?.hsts,tlsProtocols:Y.ssl?.tlsProtocols,security:Y.security}):[],b=f?nz(Y):[],R=az(Y)?pz({slug:W,siteName:q,site:Y,appBase:T}):[],u=[..._$(T,{releaseId:j,commit:j,branch:Y.repository?.branch??"main"}),...Ez(T,W),...r,...v,...b,...R,...Iz()];J.step(`Deploying to ${O.length} target(s)...`);let y=await $.runRemoteDeploy({targets:O,commands:u,comment:`ts-cloud deploy ${W}/${q}@${j}`,tags:{Project:W,Environment:Q,Role:"app"}});if(!y.success)return{success:!1,error:y.error||"Remote deploy failed",instanceCount:y.instanceCount,perInstance:y.perInstance};return{success:!0,instanceCount:y.instanceCount,perInstance:y.perInstance}}function P$($){return`'${$.replaceAll("'","'\\''")}'`}function g8($,z,J=!1,Z=[]){let Q=`${$}-dashboard-`,q=z.map((W)=>`${$}-${W}.service`),Y=J?[`export TS_CLOUD_DASHBOARD_KEEP_DOMAINS=${P$(JSON.stringify(Z))}`,"rm -f /run/ts-cloud-dashboard-routes-changed",`/usr/local/bin/bun --bun -e ${P$(`
|
|
408
|
+
const { chmodSync, existsSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } = require('node:fs')
|
|
409
|
+
const { basename, join } = require('node:path')
|
|
410
|
+
const root = '/etc/rpx/sites.d'
|
|
411
|
+
const keep = new Set(JSON.parse(process.env.TS_CLOUD_DASHBOARD_KEEP_DOMAINS || '[]'))
|
|
412
|
+
let changed = false
|
|
413
|
+
for (const name of existsSync(root) ? readdirSync(root) : []) {
|
|
414
|
+
if (!name.endsWith('.json')) continue
|
|
415
|
+
const file = join(root, name)
|
|
416
|
+
let config
|
|
417
|
+
try { config = JSON.parse(readFileSync(file, 'utf8')) } catch { continue }
|
|
418
|
+
if (!Array.isArray(config.proxies)) continue
|
|
419
|
+
const project = basename(name, '.json')
|
|
420
|
+
const proxies = config.proxies.filter((route) => {
|
|
421
|
+
const domain = typeof route?.to === 'string' ? route.to.toLowerCase() : ''
|
|
422
|
+
if (!/^(?:dashboard|cloud)\\./.test(domain) || keep.has(domain)) return true
|
|
423
|
+
const siteName = domain.replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')
|
|
424
|
+
return !existsSync('/var/www/' + project + '-' + siteName)
|
|
425
|
+
})
|
|
426
|
+
if (proxies.length === config.proxies.length) continue
|
|
427
|
+
const temporary = file + '.tmp-' + process.pid
|
|
428
|
+
const mode = statSync(file).mode & 0o777
|
|
429
|
+
writeFileSync(temporary, JSON.stringify({ ...config, proxies }, null, 2) + '\\n', { mode })
|
|
430
|
+
chmodSync(temporary, mode)
|
|
431
|
+
renameSync(temporary, file)
|
|
432
|
+
changed = true
|
|
433
|
+
}
|
|
434
|
+
if (changed) writeFileSync('/run/ts-cloud-dashboard-routes-changed', '')
|
|
435
|
+
`)}`,"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=${P$(Q)}`,`TS_CLOUD_DASHBOARD_SERVER_OWNER=${J?"1":"0"}`,`TS_CLOUD_DASHBOARD_DESIRED=${P$(` ${q.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",...Y]}async function d8($,z,J,Z){let{config:Q,environment:q}=z,Y=Q.project.slug,W=I(Q,q),j=await $.findComputeTargets({slug:Y,environment:q,role:"app",stackName:W});if(j.length===0)return!0;let G=await $.runRemoteDeploy({targets:j,commands:g8(Y,J,!Q.cloud?.attachTo,J.map((H)=>Q.sites?.[H]?.domain).filter((H)=>typeof H==="string")),comment:`ts-cloud reconcile management dashboard ${Y}`,tags:{Project:Y,Environment:q,Role:"app"}});if(!G.success)return Z.error(`Management dashboard reconciliation failed: ${G.error||"unknown error"}`),!1;return!0}async function c8($,z,J){let{config:Z,environment:Q}=z;if(!Z.cloud?.attachTo)return!0;let q=Z.infrastructure?.compute,Y=V0(Z),W=T0(Y,q?.managedServices??{});if(W.length===0)return!0;let j=Z.project.slug,G=I(Z,Q),H=await $.findComputeTargets({slug:j,environment:Q,role:"app",stackName:G});if(H.length===0)return!0;J.step(`Ensuring database '${Y?.name}' + role exist on the shared box...`);let M=await $.runRemoteDeploy({targets:H,commands:W,comment:`ts-cloud ensure database ${j}/${Y?.name}`,tags:{Project:j,Environment:Q,Role:"app"}});if(!M.success)return J.error(`Ensuring database '${Y?.name}' failed: ${M.error||"unknown error"}`),!1;return J.success(`Database '${Y?.name}' is ready on ${M.instanceCount} target(s)`),!0}async function l8($){let{config:z,environment:J,driver:Z,sha:Q,runtime:q,tarballForSite:Y,logger:W=I$}=$,j=z.project.slug,G=$.cwd??process.cwd(),H=$.managementDashboard!==!1,M=Q$(z);if(H)gz(z,{cwd:G,logger:{info:W.info,warn:W.warn}});let X=!H||M?[]:dz(z);if(H&&$.rpxConfig&&$.rpxConfig!==z&&!Q$($.rpxConfig))gz($.rpxConfig,{cwd:G,logger:{info:()=>{},warn:()=>{}}});if(H&&!await d8(Z,$,dz(z),W))return!1;let K=null,O=new Map;if(X.length>0)if(K=L2(z.sites?.[X[0]],{cwd:G,slug:j,sha:Q,siteName:X[0],logger:{info:W.info,warn:W.warn}}),!K){W.warn("Management dashboard: no artifact available — skipping dashboard site(s) for this deploy.");for(let V of X)if(z.sites)delete z.sites[V]}else for(let V of X){if(V===X[0]){O.set(V,K);continue}try{let x=v8(m8(),`${j}-${V}-${Q}.tar.gz`);h8(K,x),O.set(V,x)}catch{O.set(V,K)}}let L=z.sites||{},B=Object.entries(L).filter(([V,x])=>{if(!x)return!1;let C=$0(x);if(C==="bucket")return W.warn(`Site '${V}' targets a bucket — skipping (handled by the static-site path, not compute).`),!1;if(C==="redirect")return!1;if(C==="proxy")return!1;return!0});if(B.length===0)return tz($);if(!await c8(Z,$,W))return!1;let U=(V)=>O.get(V)??Y(V);for(let[V,x]of B){W.step(`Deploying site: ${V}`);let C=r0(x)?void 0:U(V),A=await v2(Z,{config:z,environment:J,siteName:V,site:x,slug:j,sha:Q,runtime:q,localTarballPath:C},W);if(!A.success){if(W.error(`Deploy of '${V}' failed: ${A.error||"unknown error"}`),A.perInstance)for(let D of A.perInstance)W.error(` ${D.instanceId}: ${D.status}${D.error?` — ${D.error}`:""}`);return!1}if(W.success(`Deployed ${j}/${V}@${Q} to ${A.instanceCount} target(s)`),A.perInstance)for(let D of A.perInstance)W.info(` ✓ ${D.instanceId}: ${D.status}`)}if(!await tz($))return!1;return!0}async function tz($){let{config:z,environment:J,driver:Z,logger:Q=I$}=$,q=$.rpxConfig??z,Y=q.infrastructure?.compute?.proxy??z.infrastructure?.compute?.proxy;if(Y?.engine!=="rpx")return!0;let W=q.sites||{},j=z.project.slug,G=I(z,J),H=await Z.findComputeTargets({slug:j,environment:J,role:"lb",stackName:G});if(H.length>0){let B=(await Z.findComputeTargets({slug:j,environment:J,role:"app",stackName:G})).map((V)=>({privateIp:V.privateIp,publicIp:V.publicIp})),U=I0(W,B,{proxy:Y,slug:j});if(U.proxies.length===0)return Q.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;Q.step(`Reloading the load balancer's rpx gateway with ${U.proxies.length} route(s)...`);let F=await Z.runRemoteDeploy({targets:H,commands:t0({config:U,slug:j,preserveManagementDashboardRoutes:$.managementDashboard===!1}),comment:`ts-cloud rpx gateway reload ${j}`,tags:{Project:j,Environment:J,Role:"lb"}});if(!F.success)return Q.error(`rpx gateway reload failed: ${F.error||"unknown error"}`),!1;return Q.success(`rpx gateway reloaded on ${F.instanceCount} load balancer(s)`),!0}let M=M0(W,{proxy:Y,slug:j});if(M.proxies.length===0)return Q.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;let X=await Z.findComputeTargets({slug:j,environment:J,role:"app",stackName:G});if(X.length===0)return Q.warn("rpx gateway: no compute targets found — skipping gateway reload."),!0;Q.step(`Reloading rpx gateway with ${M.proxies.length} route(s)...`);let K=O0({proxy:Y,config:M,slug:j,preserveManagementDashboardRoutes:$.managementDashboard===!1}),O=await Z.runRemoteDeploy({targets:X,commands:K,comment:`ts-cloud rpx gateway reload ${j}`,tags:{Project:j,Environment:J,Role:"app"}});if(!O.success)return Q.error(`rpx gateway reload failed: ${O.error||"unknown error"}`),!1;return Q.success(`rpx gateway reloaded on ${O.instanceCount} target(s)`),!0}async function p8($){let{config:z,environment:J,driver:Z,logger:Q=I$}=$,q=$.rpxConfig??z,Y=q.infrastructure?.compute?.proxy??z.infrastructure?.compute?.proxy;if(Y?.engine!=="rpx"||!Y.onDemandTls)return!0;let W=M0(q.sites||{},{proxy:Y,slug:z.project.slug});if(W.proxies.length===0)return!0;let j=Jz(W);if(j.length===0)return!0;let G=z.project.slug,H=I(z,J),M="lb",X=await Z.findComputeTargets({slug:G,environment:J,role:M,stackName:H});if(X.length===0)M="app",X=await Z.findComputeTargets({slug:G,environment:J,role:M,stackName:H});if(X.length===0)return Q.warn("rpx TLS: no gateway targets found - skipping certificate issuance."),!0;Q.step("Issuing rpx TLS certificates after DNS reconciliation...");let K=j.map((L)=>`test -s ${u8(`${W.productionCerts.certsDir}/${L}.crt`)}`).join(" && "),O=await Z.runRemoteDeploy({targets:X,commands:[`systemctl start ${zz(G)}`,K],comment:`ts-cloud rpx TLS issuance ${G}`,tags:{Project:G,Environment:J,Role:M}});if(!O.success)return Q.error(`rpx TLS issuance failed: ${O.error||"unknown error"}`),!1;return Q.success(`rpx TLS certificates reconciled on ${O.instanceCount} gateway target(s)`),!0}var a8="658327ea-f89d-4fab-a63d-7e88639e58f6",r8="4135ea2d-6df8-44a3-9df3-4b5a84be39ad",n8="216adef6-5c7f-47e4-b989-5492eafa07d3";function u2($,z){let J={TargetOriginId:"origin",ViewerProtocolPolicy:"redirect-to-https",Compress:!0,CachePolicyId:z==="dynamic"?"4135ea2d-6df8-44a3-9df3-4b5a84be39ad":"658327ea-f89d-4fab-a63d-7e88639e58f6",OriginRequestPolicyId:"216adef6-5c7f-47e4-b989-5492eafa07d3",SmoothStreaming:!1,FieldLevelEncryptionId:"",TrustedSigners:{Enabled:!1,Quantity:0},TrustedKeyGroups:{Enabled:!1,Quantity:0},LambdaFunctionAssociations:{Quantity:0},FunctionAssociations:{Quantity:0},AllowedMethods:z==="dynamic"?{Quantity:7,Items:["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"],CachedMethods:{Quantity:2,Items:["GET","HEAD"]}}:{Quantity:3,Items:["GET","HEAD","OPTIONS"],CachedMethods:{Quantity:2,Items:["GET","HEAD"]}}};if($!==null)J.PathPattern=$;return J}function i8($){let z=$.aliases;if(z.length===0)throw Error("buildCloudFrontOriginConfig: at least one alias is required");if(z.includes($.originDomain))throw Error(`buildCloudFrontOriginConfig: originDomain ${$.originDomain} must not be one of the aliases (it would loop)`);if($.originShield&&!$.originShieldRegion)throw Error("buildCloudFrontOriginConfig: originShieldRegion is required when originShield is enabled");let J=$.originSecretHeader??"X-Origin-Verify",Z=$.originSecret?{Quantity:1,Items:[{HeaderName:J,HeaderValue:$.originSecret}]}:{Quantity:0},Q=[...$.behaviors??[]].sort((q,Y)=>Y.pathPattern.length-q.pathPattern.length);return{CallerReference:$.callerReference??$.originDomain,Comment:$.comment??`Origin-fronted distribution for ${z[0]} → ${$.originDomain}`,Enabled:!0,Aliases:{Quantity:z.length,Items:z},DefaultRootObject:"",Origins:{Quantity:1,Items:[{Id:"origin",DomainName:$.originDomain,OriginPath:"",CustomHeaders:Z,CustomOriginConfig:{HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only",OriginSslProtocols:{Quantity:1,Items:["TLSv1.2"]},OriginReadTimeout:30,OriginKeepaliveTimeout:5},ConnectionAttempts:3,ConnectionTimeout:10,OriginShield:$.originShield?{Enabled:!0,OriginShieldRegion:$.originShieldRegion}:{Enabled:!1},OriginAccessControlId:""}]},OriginGroups:{Quantity:0},DefaultCacheBehavior:u2(null,"static"),CacheBehaviors:{Quantity:Q.length,Items:Q.map((q)=>u2(q.pathPattern,q.kind))},ViewerCertificate:{CloudFrontDefaultCertificate:!1,ACMCertificateArn:$.viewerCertificateArn,Certificate:$.viewerCertificateArn,CertificateSource:"acm",SSLSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"},PriceClass:$.priceClass??"PriceClass_All",HttpVersion:"http2and3",IsIPV6Enabled:!0,Restrictions:{GeoRestriction:{RestrictionType:"none",Quantity:0}},Logging:{Enabled:!1,IncludeCookies:!1,Bucket:"",Prefix:""},WebACLId:"",CustomErrorResponses:{Quantity:0}}}export{t8 as Qf,c2 as Rf,W0 as Sf,l2 as Tf,p2 as Uf,o8 as Vf,a2 as Wf,l as Xf,Y$ as Yf,q1 as Zf,d$ as _f,c$ as $f,Y9 as ag,i$ as bg,r0 as cg,t$ as dg,k4 as eg,V1 as fg,$0 as gg,T4 as hg,B9 as ig,U9 as jg,C9 as kg,L9 as lg,e$ as mg,$z as ng,y4 as og,F1 as pg,o$ as qg,M0 as rg,I0 as sg,h4 as tg,i0 as ug,s$ as vg,X0 as wg,O0 as xg,t0 as yg,s as zg,V$ as Ag,s4 as Bg,C$ as Cg,J6 as Dg,x0 as Eg,F0 as Fg,B0 as Gg,x$ as Hg,Gz as Ig,O6 as Jg,o1 as Kg,e5 as Lg,s1 as Mg,e1 as Ng,B6 as Og,Hz as Pg,w$ as Qg,q0 as Rg,U6 as Sg,Xz as Tg,C6 as Ug,Mz as Vg,R6 as Wg,k6 as Xg,z2 as Yg,J2 as Zg,S6 as _g,f6 as $g,b6 as ah,Oz as bh,q2 as ch,g6 as dh,d6 as eh,c6 as fh,Vz as gh,Fz as hh,Bz as ih,Uz as jh,Cz as kh,Lz as lh,xz as mh,Dz as nh,a6 as oh,z$ as ph,xJ as qh,_z as rh,kz as sh,Tz as th,Z$ as uh,yz as vh,Pz as wh,Iz as xh,G8 as yh,B2 as zh,H8 as Ah,V8 as Bh,gz as Ch,L2 as Dh,w2 as Eh,v2 as Fh,l8 as Gh,tz as Hh,p8 as Ih,a8 as Jh,r8 as Kh,n8 as Lh,i8 as Mh};
|