@stacksjs/ts-cloud 0.16.59 → 0.16.62
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/aws/index.js +1 -1
- package/dist/bin/{chunk-x8gqdr3m.js → chunk-0ejp168p.js} +1 -1
- package/dist/bin/chunk-0v5tsfx5.js +1 -0
- package/dist/bin/{chunk-qt6rjw6v.js → chunk-2avtspqd.js} +5 -5
- package/dist/bin/{chunk-hs2r1nsg.js → chunk-38qy0dj2.js} +3 -3
- package/dist/bin/chunk-3x52axr2.js +1 -0
- package/dist/bin/{chunk-bss9yv52.js → chunk-5ad4b744.js} +2 -2
- package/dist/bin/chunk-67mww6gq.js +1 -0
- package/dist/bin/{chunk-0dmf1a2q.js → chunk-6da5c33e.js} +2 -2
- package/dist/bin/chunk-6r04kx46.js +2 -0
- package/dist/bin/{chunk-p6qa21fr.js → chunk-71b4t3d8.js} +2 -2
- package/dist/bin/chunk-7khzyn7k.js +1 -0
- package/dist/bin/{chunk-rq0wxfyp.js → chunk-8bgfn8ek.js} +3 -3
- package/dist/bin/{chunk-9t78j764.js → chunk-90ds3vw7.js} +1 -1
- package/dist/bin/chunk-97494wnx.js +1 -0
- package/dist/bin/{chunk-jvbe549p.js → chunk-9pj5r0x0.js} +1 -1
- package/dist/bin/{chunk-sy4zws71.js → chunk-aekwpste.js} +1 -1
- package/dist/bin/chunk-agmznzms.js +1 -0
- package/dist/bin/chunk-ambf5hpg.js +1 -0
- package/dist/bin/chunk-b39h9as6.js +1 -0
- package/dist/bin/{chunk-27rh6te6.js → chunk-cf2eyje1.js} +7 -7
- package/dist/bin/{chunk-z6xnegpe.js → chunk-d0q93ecd.js} +5 -5
- package/dist/bin/{chunk-yydj05nb.js → chunk-d38cyam8.js} +5 -5
- package/dist/bin/chunk-dfgzav9j.js +1 -0
- package/dist/bin/{chunk-3mhzd931.js → chunk-e51cd46z.js} +2 -2
- package/dist/bin/chunk-ekwfpppj.js +1 -0
- package/dist/bin/{chunk-acn2c3ep.js → chunk-favx96qj.js} +5 -5
- package/dist/bin/chunk-g0w0jec3.js +1 -0
- package/dist/bin/{chunk-nn1w8fvd.js → chunk-g2kjjb1a.js} +95 -95
- package/dist/bin/chunk-g514nb80.js +1 -0
- package/dist/bin/chunk-hknz7fsr.js +1 -0
- package/dist/bin/chunk-j9yq3b4d.js +2 -0
- package/dist/bin/chunk-k8qrjnyg.js +1 -0
- package/dist/bin/{chunk-dwq5vgdc.js → chunk-kmxkwznm.js} +5 -5
- package/dist/bin/chunk-kqstefmv.js +1 -0
- package/dist/bin/chunk-mk2h37pm.js +1 -0
- package/dist/bin/{chunk-8z2436dv.js → chunk-mver6psb.js} +2 -2
- package/dist/bin/{chunk-0rvg0ma7.js → chunk-n667tnf3.js} +3 -3
- package/dist/bin/{chunk-p23wfy3r.js → chunk-nn8k84cd.js} +1 -1
- package/dist/bin/chunk-nrtjmzzn.js +1 -0
- package/dist/bin/{chunk-1mb679gj.js → chunk-pe18g092.js} +3 -3
- package/dist/bin/chunk-q3rch5hc.js +1 -0
- package/dist/bin/{chunk-0xfy78nc.js → chunk-qpvydcfm.js} +5 -5
- package/dist/bin/chunk-qqb6h33k.js +1 -0
- package/dist/bin/chunk-r1p3k2tn.js +1 -0
- package/dist/bin/{chunk-c1dwwtkq.js → chunk-rgddxcrr.js} +112 -97
- package/dist/bin/{chunk-cvps1wjq.js → chunk-sbjzewvk.js} +6 -6
- package/dist/bin/chunk-t8xq3v3j.js +1 -0
- package/dist/bin/{chunk-mdcv2vw1.js → chunk-tcn6qcc4.js} +2 -2
- package/dist/bin/{chunk-gr1ra9nj.js → chunk-tg3vzzc4.js} +2 -2
- package/dist/bin/{chunk-551brgyd.js → chunk-tpttr74v.js} +5 -5
- package/dist/bin/{chunk-0f8jky3x.js → chunk-tw6z2mvh.js} +15 -15
- package/dist/bin/{chunk-hc9tnwqs.js → chunk-v3j9wgmn.js} +200 -200
- package/dist/bin/{chunk-r99jcm9t.js → chunk-v5x06h8w.js} +5 -5
- package/dist/bin/{chunk-9hb2wkkt.js → chunk-v6jm8dsa.js} +1 -1
- package/dist/bin/{chunk-06rjt80a.js → chunk-vbq4ten8.js} +3 -3
- package/dist/bin/chunk-xb48vxmk.js +1 -0
- package/dist/bin/{chunk-e19dabas.js → chunk-ya1413jw.js} +2 -2
- package/dist/bin/chunk-yehb738r.js +1 -0
- package/dist/bin/chunk-ythfx8pv.js +1 -0
- package/dist/bin/{chunk-95djv2ja.js → chunk-zesb85ra.js} +1 -1
- package/dist/bin/{chunk-rbyrd9we.js → chunk-zs0q8sh5.js} +1 -1
- package/dist/bin/chunk-zynfzzjk.js +1 -0
- package/dist/bin/cli.js +292 -292
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/{chunk-b1v1301e.js → chunk-2phe49y7.js} +25 -25
- package/dist/chunk-3b08b1zx.js +1 -0
- package/dist/{chunk-pqyv47m4.js → chunk-7mw4x3ay.js} +1 -1
- package/dist/{chunk-j2bpd2v9.js → chunk-7s7w8kzc.js} +5 -5
- package/dist/{chunk-c87bg8wk.js → chunk-8jqv6wh7.js} +2 -2
- package/dist/{chunk-2pqjw8pq.js → chunk-8z3jfyk8.js} +7 -7
- package/dist/chunk-9sdkhmav.js +1 -0
- package/dist/{chunk-y9q6sv2q.js → chunk-b0s2605f.js} +6 -6
- package/dist/{chunk-tj3egckk.js → chunk-betvtvy7.js} +3 -3
- package/dist/{chunk-qb8cf1ss.js → chunk-bn3jfrg5.js} +2 -2
- package/dist/{chunk-mkvqcd3x.js → chunk-bydj8p3h.js} +2 -2
- package/dist/{chunk-95qrgpjk.js → chunk-e97qhzfe.js} +8 -8
- package/dist/{chunk-1a7ms51t.js → chunk-et77ydjb.js} +4 -4
- package/dist/{chunk-yece1kc4.js → chunk-f512g4fq.js} +5 -5
- package/dist/chunk-fc9n4dpq.js +1 -0
- package/dist/{chunk-x8fg8zg8.js → chunk-g0bh9atv.js} +2 -2
- package/dist/{chunk-6ky22rmg.js → chunk-gj4hj95p.js} +1 -1
- package/dist/{chunk-7bzyjfb1.js → chunk-h5j27a4h.js} +106 -101
- package/dist/{chunk-rxh9dkpd.js → chunk-k2bb62em.js} +4 -4
- package/dist/chunk-kfcct0jz.js +1 -0
- package/dist/{chunk-nq6cqjfv.js → chunk-mqbsnpsv.js} +1 -1
- package/dist/{chunk-dp0hvmd0.js → chunk-n0xw26th.js} +1 -1
- package/dist/{chunk-w174jbbm.js → chunk-n3sydv3m.js} +1 -1
- package/dist/{chunk-za23j2mq.js → chunk-p921pam0.js} +118 -118
- package/dist/{chunk-jg2m713e.js → chunk-pjdp30dn.js} +2 -2
- package/dist/{chunk-qdaj5yyh.js → chunk-r41cawtf.js} +5 -5
- package/dist/{chunk-z5as1fa7.js → chunk-r9ydamw0.js} +102 -102
- package/dist/{chunk-ryce2n62.js → chunk-rs8v7c67.js} +3 -3
- package/dist/{chunk-cwqqv7dx.js → chunk-sqtzajrx.js} +4 -4
- package/dist/{chunk-7md90ny0.js → chunk-t3ssg8p0.js} +2 -2
- package/dist/{chunk-3h5vgz4z.js → chunk-tt3pn05f.js} +1 -1
- package/dist/chunk-v34tdcwv.js +1 -0
- package/dist/{chunk-x6a2e5sx.js → chunk-v90w8kbz.js} +3 -3
- package/dist/chunk-xq7xs8bh.js +1 -0
- package/dist/deploy/index.js +1 -1
- package/dist/dns/index.js +1 -1
- package/dist/drivers/index.js +1 -1
- package/dist/drivers/shared/box-converge.d.ts +46 -1
- package/dist/index.js +45 -45
- package/dist/mail/index.js +2 -2
- package/dist/operations/index.js +1 -1
- package/dist/protection/index.js +1 -1
- package/dist/spend/index.js +1 -1
- package/dist/ui/404.html +1 -1
- package/dist/ui/accept-invitation.html +1 -1
- package/dist/ui/access-denied.html +1 -1
- package/dist/ui/account/automation.html +6 -6
- package/dist/ui/account/security.html +2 -2
- package/dist/ui/applications/compose.html +6 -6
- package/dist/ui/applications/new.html +2 -2
- package/dist/ui/data/backups.html +5 -5
- package/dist/ui/data/services.html +6 -6
- package/dist/ui/data/volumes.html +6 -6
- package/dist/ui/index.html +6 -6
- package/dist/ui/infrastructure/topology.html +5 -5
- package/dist/ui/integrations.html +1 -1
- package/dist/ui/operations/alerts.html +6 -6
- package/dist/ui/operations/configuration.html +6 -6
- package/dist/ui/operations/jobs.html +5 -5
- package/dist/ui/operations/maintenance.html +6 -6
- package/dist/ui/operations/observability.html +5 -5
- package/dist/ui/operations/previews.html +5 -5
- package/dist/ui/operations/queue.html +5 -5
- package/dist/ui/operations/regions.html +6 -6
- package/dist/ui/operations/releases.html +5 -5
- package/dist/ui/operations/spend.html +5 -5
- package/dist/ui/operations/workloads.html +5 -5
- 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 +5 -5
- package/dist/ui/server/database.html +5 -5
- package/dist/ui/server/deployments.html +5 -5
- package/dist/ui/server/diagnostics.html +1 -1
- package/dist/ui/server/firewall.html +5 -5
- package/dist/ui/server/fleet.html +5 -5
- package/dist/ui/server/logs.html +5 -5
- package/dist/ui/server/metrics.html +5 -5
- package/dist/ui/server/security.html +1 -1
- package/dist/ui/server/services.html +2 -2
- package/dist/ui/server/sites.html +6 -6
- package/dist/ui/server/ssh-keys.html +6 -6
- package/dist/ui/server/team.html +6 -6
- package/dist/ui/server/terminal.html +2 -2
- package/dist/ui/serverless/alarms.html +6 -6
- package/dist/ui/serverless/assets.html +1 -1
- package/dist/ui/serverless/cost.html +2 -2
- package/dist/ui/serverless/data.html +6 -6
- package/dist/ui/serverless/deployments.html +2 -2
- package/dist/ui/serverless/firewall.html +1 -1
- package/dist/ui/serverless/functions.html +6 -6
- package/dist/ui/serverless/logs.html +6 -6
- package/dist/ui/serverless/metrics.html +2 -2
- package/dist/ui/serverless/queues.html +6 -6
- package/dist/ui/serverless/secrets.html +6 -6
- package/dist/ui/serverless/traces.html +6 -6
- package/dist/ui/serverless.html +5 -5
- package/package.json +3 -3
- package/dist/bin/chunk-1z4hxpwe.js +0 -2
- package/dist/bin/chunk-37gemrn2.js +0 -1
- package/dist/bin/chunk-40963a0r.js +0 -1
- package/dist/bin/chunk-4zsp269q.js +0 -1
- package/dist/bin/chunk-57sers7y.js +0 -1
- package/dist/bin/chunk-5cmj2m13.js +0 -1
- package/dist/bin/chunk-8vmy8yhf.js +0 -1
- package/dist/bin/chunk-apqyj6gr.js +0 -1
- package/dist/bin/chunk-at4x6wf2.js +0 -1
- package/dist/bin/chunk-bd4ppf6w.js +0 -1
- package/dist/bin/chunk-bzbah8jm.js +0 -1
- package/dist/bin/chunk-bzpeqh5z.js +0 -1
- package/dist/bin/chunk-cmkvxf6c.js +0 -1
- package/dist/bin/chunk-d2fq60kd.js +0 -1
- package/dist/bin/chunk-e0d34gcp.js +0 -1
- package/dist/bin/chunk-ed4vh6b4.js +0 -1
- package/dist/bin/chunk-fqvqqtg6.js +0 -1
- package/dist/bin/chunk-hrg9ygbz.js +0 -1
- package/dist/bin/chunk-hzc049ns.js +0 -1
- package/dist/bin/chunk-kj0eewaq.js +0 -1
- package/dist/bin/chunk-kqd186ky.js +0 -2
- package/dist/bin/chunk-mt70pxs8.js +0 -1
- package/dist/bin/chunk-n6hngvvb.js +0 -1
- package/dist/bin/chunk-n9aeark7.js +0 -1
- package/dist/bin/chunk-pntcdh4x.js +0 -1
- package/dist/bin/chunk-sfwm3wzx.js +0 -1
- package/dist/bin/chunk-zgasmfgt.js +0 -1
- package/dist/chunk-3855mx54.js +0 -1
- package/dist/chunk-92yhw6da.js +0 -1
- package/dist/chunk-9tbx7g94.js +0 -1
- package/dist/chunk-qkycmppw.js +0 -1
- package/dist/chunk-wtp36fj6.js +0 -1
- package/dist/chunk-zwckda2e.js +0 -1
|
@@ -1,38 +1,38 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`),a=Math.max(1,s-12),c=Math.min(i.length,s+2),u=i.slice(a-1,c).map((
|
|
3
|
-
`)}function
|
|
1
|
+
import{il,Q,l,g,C,Xe,Ji,w,be,m,ce,ln,Dt,Pt,gr,pr,Zi}from"./chunk-r9ydamw0.js";import{o}from"./chunk-betvtvy7.js";import{U,jr,d}from"./chunk-8jqv6wh7.js";import{go,dd,Ip,bp,B,tr,j,z,ud,gd,G,Ne}from"./chunk-b0s2605f.js";import{ki}from"./chunk-k2bb62em.js";import{Gr,Be}from"./chunk-bydj8p3h.js";import{A}from"./chunk-tt3pn05f.js";import{Wi}from"./chunk-8z3jfyk8.js";import{readFileSync as Es}from"node:fs";import{join as Ua}from"node:path";function kg(e={}){let t=new Set;for(let r of Object.values(e)){if(!r.domain)continue;if(!(r.redirect||r.deploy==="server"||r.start))continue;t.add(r.domain);for(let n of r.aliases??[]){let s=String(n).trim().toLowerCase();if(s)t.add(s)}}return t}function Kr(e){return e.replace(/\.$/,"").toLowerCase()}function qn(e,t,r){let n=Kr(e.name),s=Kr(t),i=Kr(r),a=i===s?"@":i.endsWith(`.${s}`)?i.slice(0,-(s.length+1)):i;return n===i||n===a||a==="@"&&(n===""||n===s)}async function xc(e,t,r,n,s="A"){let i=await e.listRecords(t);if(!i.success)return[`could not list ${s} records: ${i.message||"unknown provider error"}`];let a=i.records.filter((f)=>f.type===s&&qn(f,t,r)),c=a.findIndex((f)=>f.content===n);if(a.length<=1||c===-1)return[];let u=[];for(let[f,h]of a.entries()){if(f===c)continue;let _=await e.deleteRecord(t,h);if(!_.success)u.push(`could not remove stale ${h.name} ${s} ${h.content}: ${_.message||"unknown provider error"}`)}return u}async function Ng(e,t,r){let n=await e.listRecords(t);if(!n.success)return{removed:[],warnings:[`could not list records for ${t}: ${n.message||"unknown provider error"}`]};let s=[],i=[];for(let a of n.records){if(a.type!=="A"&&a.type!=="AAAA"||!qn(a,t,r))continue;let c=await e.deleteRecord(t,a);if(c.success)s.push(a);else i.push(`could not remove ${a.type} ${r} ${a.content}: ${c.message||"unknown provider error"}`)}return{removed:s,warnings:i}}function De(e){if(!e)return;let t=e.trim();if(!t)return;if(!t.includes("/"))return t;let[r]=t.split("/");if(!r.endsWith("::"))return r||void 0;return`${r}1`}var Oc=new Set(["mail","smtp","imap","mx"]);function Xn(e){return!Oc.has(e.split(".")[0]??"")}async function Bg(e){let{provider:t,zone:r,fqdn:n,ipv4:s,ipv6:i,ttl:a=600}=e,c={published:[],warnings:[]},u=[{type:"A",content:s}];if(i&&Xn(n))u.push({type:"AAAA",content:i});for(let{type:f,content:h}of u){let _=await t.upsertRecord(r,{name:n,type:f,content:h,ttl:a});if(_?.success===!1){c.warnings.push(`${n} → ${h} failed: ${_.error||_.message||"unknown error"}`);continue}if(c.warnings.push(...(await xc(t,r,n,h,f)).map((S)=>`${n} cleanup: ${S}`)),await _c(t,r,n,h,f))c.published.push({fqdn:n,type:f,content:h});else c.warnings.push(`${n} → ${h} reported success at ${t.name} but no matching ${f} record exists — create it manually: ${f} ${n} → ${h}`)}return c}async function _c(e,t,r,n,s){try{if(typeof e?.listRecords!=="function")return!0;let i=await e.listRecords(t);if(!i?.success||!Array.isArray(i.records))return!0;return i.records.some((a)=>{let c=typeof a?.name==="string"?a.name.replace(/\.$/,""):"";return a?.type===s&&c===r&&a?.content===n})}catch{return!0}}function Vr(e){return(Buffer.isBuffer(e)?e.toString("utf8"):typeof e==="string"?e:"").replace(/(^|\n)(\s*(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*=).*$/gm,"$1$2[redacted]").replace(/encrypted:[A-Za-z0-9+/=]+/g,"encrypted:[redacted]").trim().slice(-8000)}function Yn(e,t){let r=Vr(e?.stderr),n=/line (\d+): syntax error/.exec(r);if(!n)return"";let s=Number(n[1]),i=t.split(`
|
|
2
|
+
`),a=Math.max(1,s-12),c=Math.min(i.length,s+2),u=i.slice(a-1,c).map((f,h)=>{let _=a+h,S=/^[A-Z_][A-Z0-9_]*=/.test(f)?f.replace(/=.*/,"=<redacted>"):f;return` ${String(_).padStart(4)}${_===s?" >":" "} ${S}`});return["",`The deploy script bash rejected is ${i.length} lines; it stopped at ${s}.`,...u].join(`
|
|
3
|
+
`)}function Wt(e){let t=e,r=typeof t?.status==="number"?` (exit ${t.status})`:"",n=t?.signal?` (signal ${t.signal})`:"",s=[Vr(t?.stderr),Vr(t?.stdout)].filter(Boolean).join(`
|
|
4
4
|
`);return`Remote SSH command failed${r}${n}${s?`
|
|
5
|
-
${s}`:""}`}function
|
|
6
|
-
`)){let r=t.trim();if(!r.startsWith("[ts-cloud]"))continue;console.warn(r)}}var
|
|
7
|
-
${e.slice(-
|
|
8
|
-
${
|
|
9
|
-
`)}function
|
|
5
|
+
${s}`:""}`}function xr(e){for(let t of e.split(`
|
|
6
|
+
`)){let r=t.trim();if(!r.startsWith("[ts-cloud]"))continue;console.warn(r)}}var Wn=4000,Pi=3;function Oi(e){return e.length>Wn?`…
|
|
7
|
+
${e.slice(-Wn)}`:e}function Jt(e,t){let r=e.filter((a)=>a.status!=="Success");if(r.length===0)return t;let n=r.slice(0,Pi).map((a)=>{let c=(a.error||a.output||"").trim(),u=`${a.instanceId}: ${a.status}`;return c?`${u}
|
|
8
|
+
${Oi(c)}`:u}),s=r.length-n.length,i=s>0?[`(+${s} more instance${s===1?"":"s"} failed)`]:[];return[t,...n,...i].join(`
|
|
9
|
+
`)}function xi(e){let t=2166136261,r=16777619;for(let n=0;n<e.length;n++){let s=e.charCodeAt(n);t=Math.imul(t^s,16777619)>>>0,r=Math.imul(r+s,2246822507)>>>0}return`${t.toString(36)}${r.toString(36)}`.padEnd(12,"0").slice(0,12)}function xg(e,t,r={}){let n=r.mode??"testing",s=r.maxAge??604800,i=r.mx?.length?r.mx:[e.hostname],a=`${["version: STSv1",`mode: ${n}`,...i.map((u)=>`mx: ${u}`),`max_age: ${s}`].join(`\r
|
|
10
10
|
`)}\r
|
|
11
|
-
`,c=
|
|
12
|
-
`)}var
|
|
13
|
-
`)}function
|
|
14
|
-
`)}function
|
|
15
|
-
`)}function
|
|
16
|
-
`)}function st(e){let t=["[Unit]",`Description=${e.description}`,`After=network.target${e.after?.length?` ${e.after.join(" ")}`:""}`];if(e.requires?.length)t.push(`Requires=${e.requires.join(" ")}`);return t.push("","[Service]","Type=simple",`User=${fe}`,`Group=${fe}`,`Environment="PATH=${
|
|
17
|
-
`)}function ts(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_VITESS_UNIT_EOF'`,t,"TS_CLOUD_VITESS_UNIT_EOF"]}function ji(e){let t=e.cell??"zone1",r=e.vtgatePort??Wr,s=`${((e.keyspaces?.length)?e.keyspaces:[{name:"app"}]).map((i)=>{let a=(i.sharded?["-80","80-"]:["0"]).map((c)=>`shards:{name:"${c}"}`).join(" ");return`keyspaces:{name:"${i.name}" ${a}}`}).join(" ")} cells:"${t}"`;return st({description:"Vitess (vtcombo, single-process development stack)",execStart:nt("vtcombo",[`${ve}/vtcombo`,`--cell ${t}`,`--proto-topo ${oe(s)}`,`--mysql-server-port ${r}`,"--mysql-server-bind-address 127.0.0.1","--mysql-auth-server-impl none","--start-mysql",`--port ${Vr}`,`--grpc-port ${jt}`])})}function Vi(){return st({description:"etcd (Vitess topology store)",execStart:nt("etcd",[`${ve}/etcd`,`--data-dir ${Re}/etcd`,`--listen-client-urls http://127.0.0.1:${Vt}`,`--advertise-client-urls http://127.0.0.1:${Vt}`]),execStartPre:[`+/bin/mkdir -p ${Re}/etcd`,`+/bin/chown ${fe}:${fe} ${Re}/etcd`]})}function Jr(e){return["--topo-implementation etcd2",`--topo-global-server-address ${e.etcdEndpoint??`http://127.0.0.1:${Vt}`}`,"--topo-global-root /vitess/global"]}function Gi(e){let t=!e.etcdEndpoint;return st({description:"Vitess vtctld (control plane)",after:t?["vitess-etcd.service"]:[],requires:t?["vitess-etcd.service"]:[],execStart:nt("vtctld",[`${ve}/vtctld`,...Jr(e),`--cell ${e.cell??"zone1"}`,"--service-map grpc-vtctl,grpc-vtctld",`--grpc-port ${jt}`,`--port ${jt+1}`])})}function qi(e,t,r){let n=e.cell??"zone1";return st({description:`Vitess vttablet (${t}/${r})`,after:["vitess-vtctld.service","vitess-mysqlctld.service"],requires:["vitess-mysqlctld.service"],execStart:nt("vttablet",[`${ve}/vttablet`,...Jr(e),`--tablet-path ${n}-${String(Yr).padStart(10,"0")}`,`--init-keyspace ${t}`,`--init-shard ${r}`,"--init-tablet-type replica",`--service-map ${oe("grpc-queryservice,grpc-tabletmanager,grpc-updatestream")}`,`--port ${Qn}`,`--grpc-port ${Qn+1}`,`--db-port ${e.mysqlPort??3306}`,`--mycnf-mysql-port ${e.mysqlPort??3306}`])})}function Wi(e){return st({description:"Vitess mysqlctld (managed mysqld)",execStart:nt("mysqlctld",[`${ve}/mysqlctld`,`--tablet-uid ${Yr}`,`--mysql-port ${e.mysqlPort??3306}`,'--init-db-sql-file "$VTROOT/config/init_db.sql"',"--wait-time 2m"]),execStartPre:[`+/bin/mkdir -p ${Re}`,`+/bin/chown ${fe}:${fe} ${Re}`]})}var ss="/etc/vitess/auth.json",Tt="/var/lib/vitess/vtgate-auth.sha256";function Yi(e){let t=e.username??"vitess",r=e.password??"";return["mkdir -p /etc/vitess",'VTESS_AUTH_TMP="$(mktemp)"',`cat > "$VTESS_AUTH_TMP" <<'TS_CLOUD_VITESS_AUTH_EOF'`,JSON.stringify({[t]:[{Password:r,UserData:t}]}),"TS_CLOUD_VITESS_AUTH_EOF",`VTESS_VTGATE_AUTH_SHA="$(sha256sum "$VTESS_AUTH_TMP" | awk '{print $1}')"`,"VTESS_VTGATE_AUTH_CHANGED=1",`if [ -f ${Tt} ] && [ "$(cat ${Tt})" = "$VTESS_VTGATE_AUTH_SHA" ]; then VTESS_VTGATE_AUTH_CHANGED=0; fi`,`install -o ${fe} -g ${fe} -m 0600 "$VTESS_AUTH_TMP" ${ss}`,'rm -f "$VTESS_AUTH_TMP"']}function Ji(e){let t=e.cell??"zone1";return st({description:"Vitess vtgate (query router)",after:["vitess-vtctld.service"],execStart:nt("vtgate",[`${ve}/vtgate`,...Jr(e),`--cell ${t}`,`--cells-to-watch ${t}`,"--tablet-types-to-wait PRIMARY,REPLICA",`--service-map ${oe("grpc-vtgateservice")}`,`--mysql-server-port ${e.vtgatePort??Wr}`,`--mysql-server-bind-address ${e.bindAddress??"127.0.0.1"}`,"--mysql-auth-server-impl static",`--mysql-auth-server-static-file ${ss}`,`--port ${Vr}`,`--grpc-port ${Vr+1}`])})}function Zi(e){let t=e.cell??"zone1",r=e.etcdEndpoint??`http://127.0.0.1:${Vt}`,n=`${ve}/vtctldclient --server 127.0.0.1:${jt}`,s=[`for i in $(seq 1 30); do ${n} GetCellInfoNames >/dev/null 2>&1 && break; sleep 2; done`,`if ! ${n} GetCellInfoNames 2>/dev/null | grep -qx ${oe(t)}; then`,` ${n} AddCellInfo --root ${oe(`/vitess/${t}`)} --server-address ${oe(r)} ${oe(t)}`,"fi"];for(let i of e.keyspaces??[]){let a=i.sharded?" --sharded":"";s.push(`if ! ${n} GetKeyspace ${oe(i.name)} >/dev/null 2>&1; then`,` ${n} CreateKeyspace${a} ${oe(i.name)}`,"fi");let c=`${t}-${String(Yr).padStart(10,"0")}`;for(let u of i.sharded?["-80","80-"]:["0"]){let m=`${i.name}/${u}`;s.push("for i in $(seq 1 90); do",` if ${n} GetShard ${oe(m)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then break; fi`,` ${n} PlannedReparentShard ${oe(m)} --new-primary ${oe(c)} >/dev/null 2>&1 && break`,` ${n} InitShardPrimary --force ${oe(m)} ${oe(c)} >/dev/null 2>&1 && break`," sleep 2","done",`if ! ${n} GetShard ${oe(m)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then`,` echo "no primary could be elected for ${m}" >&2; exit 1`,"fi")}s.push(`${n} RebuildKeyspaceGraph ${oe(i.name)} >/dev/null`)}return s}function rs(e){let t=e.vtgatePort??Wr;return["for i in $(seq 1 60); do",` if (cd ${f} && eval "$(pantry env 2>/dev/null)"; MYSQL_PWD=${oe(e.password??"")} ${ve}/mysql -h 127.0.0.1 -P ${t} -u ${oe(e.username??"vitess")} --connect-timeout=2 -e 'SHOW KEYSPACES') >/dev/null 2>&1; then`,` echo "vtgate is serving on ${t}"; exit 0`," fi"," sleep 2","done",`echo "vtgate did not become ready on port ${t}" >&2`,"exit 1"]}function Xs(e){if(!wt(e))return[];let t=Ni(e),r=t.mode==="combo";Xr.clear();let n=['if [ "$(uname -m)" != "x86_64" ]; then',' echo "vitess: Vitess publishes only x86_64 release tarballs; this box is $(uname -m). Drop managedServices.vitess or use an x86_64 host." >&2'," exit 1","fi",...Te(Mi(t)),`VT_MYSQL_LIB="$(dirname "$(dirname "$(readlink -f ${ve}/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 ${fe} >/dev/null 2>&1 || useradd --system --home-dir ${Re} --shell /usr/sbin/nologin ${fe}`,`mkdir -p ${Re}`,`chown -R ${fe}:${fe} ${Re}`];if(r)return n.push(...ts("vitess-vtcombo",ji(t)),...es(),"systemctl daemon-reload","systemctl enable --now vitess-vtcombo.service",...rs(t)),n;n.push(...Yi(t));let s=[];if(!t.etcdEndpoint)s.push(["vitess-etcd",Vi()]);s.push(["vitess-vtctld",Gi(t)],["vitess-mysqlctld",Wi(t)],["vitess-vtgate",Ji(t)]);for(let i of t.keyspaces??[])for(let a of i.sharded?["-80","80-"]:["0"])s.push([`vitess-vttablet-${i.name}-${a.replace(/-/g,"x")}`,qi(t,i.name,a)]);for(let[i,a]of s)n.push(...ts(i,a));n.push(...es()),n.push("systemctl daemon-reload");for(let[i]of s)n.push(`systemctl enable --now ${i}.service`);return n.push(`if [ "$VTESS_VTGATE_AUTH_CHANGED" = 1 ]; then systemctl restart vitess-vtgate.service; printf '%s\\n' "$VTESS_VTGATE_AUTH_SHA" > ${Tt}; chown ${fe}:${fe} ${Tt}; chmod 0600 ${Tt}; fi`,...Zi(t),...rs(t)),n}var Qi=new Set(["singlestore","vitess"]);function Yn(e){if(e?.engine&&Qi.has(e.engine))return!1;return!e?.host||e.host==="127.0.0.1"||e.host==="localhost"}function Jt(e,t="psql"){let r=e?.port??5432;if(Yn(e))return`${t} -p ${r} -U postgres`;let n=e?.username||"postgres";return`${e?.password?`PGPASSWORD='${e.password.replace(/'/g,"'\\''")}' `:""}${t} -h ${e.host} -p ${r} -U ${n} -w`}function Oe(e){return e===!0||typeof e==="object"&&e!=null}function ea(e){let t=[],r=[];if(Oe(e.mysql))t.push(typeof e.mysql==="object"&&e.mysql.version?`mysql.com@${e.mysql.version}`:"mysql.com@8.0.43"),r.push("mysql");else if(Oe(e.mariadb))t.push(bt.mariadb),r.push("mariadb");if(Oe(e.postgres))t.push("postgresql.org"),r.push("postgres");if(Oe(e.redis))t.push("redis.io"),r.push("redis");if(Oe(e.memcached))t.push("memcached.org"),r.push("memcached");if(Oe(e.meilisearch))t.push("meilisearch.com"),r.push("meilisearch");return{packages:t,services:r}}function Gt(e={},t={}){let r=ea(e),n=Xs(e.vitess),s=t.mail?Wn(t.mail):[];if(r.packages.length===0)return[...n,...s];return[...Te(r.packages),...Bt(r.services),...n,...s]}function ot(e,t={}){if(!e?.name)return[];if(!Yn(e))return[];let r=e.name,n=e.username||r,s=e.password||"",i=Oe(t.postgres)||e.engine==="postgres",a=Oe(t.mariadb)||e.engine==="mariadb",c=Oe(t.mysql)||e.engine==="mysql";if(i&&!c&&!a){let _=(R)=>`"${R.replace(/"/g,'""')}"`,y=(R)=>`'${R.replace(/'/g,"''")}'`,b=(R,x)=>["DO $$ BEGIN",` IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${y(R)}) THEN`,` CREATE ROLE ${_(R)} LOGIN PASSWORD ${y(x)};`," ELSE",` ALTER ROLE ${_(R)} LOGIN PASSWORD ${y(x)};`," END IF;","END $$;"],I=(R)=>{let x=R.databases&&R.databases.length>0?R.databases:[r],W=[];for(let k of x)if(R.access==="readonly")W.push(`GRANT CONNECT ON DATABASE ${_(k)} TO ${_(R.username)};`,`\\connect ${_(k)}`,`GRANT USAGE ON SCHEMA public TO ${_(R.username)};`,`GRANT SELECT ON ALL TABLES IN SCHEMA public TO ${_(R.username)};`,`ALTER DEFAULT PRIVILEGES FOR ROLE ${_(n)} IN SCHEMA public GRANT SELECT ON TABLES TO ${_(R.username)};`,"\\connect postgres");else W.push(`GRANT ALL PRIVILEGES ON DATABASE ${_(k)} TO ${_(R.username)};`);return W},D=e.users||[],H=e.port??5432;return[Ee(),`for i in $(seq 1 30); do pg_isready -p ${H} -q && break; sleep 2; done`,`${Jt(e)} <<'TS_CLOUD_PG_EOF'`,...b(n,s),`SELECT 'CREATE DATABASE ${_(r)} OWNER ${_(n)}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = ${y(r)})\\gexec`,...D.flatMap((R)=>[...b(R.username,R.password),...I(R)]),"TS_CLOUD_PG_EOF",...ta(e)]}let u=a?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock",m=(_)=>_.replace(/`/g,"``"),h=(_)=>_.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),S=(_)=>{let y=_.databases&&_.databases.length>0?_.databases:[r],b=_.access==="readonly"?"SELECT":"ALL PRIVILEGES",I=[`CREATE USER IF NOT EXISTS '${h(_.username)}'@'%' IDENTIFIED BY '${h(_.password)}';`,`CREATE USER IF NOT EXISTS '${h(_.username)}'@'localhost' IDENTIFIED BY '${h(_.password)}';`,`ALTER USER '${h(_.username)}'@'%' IDENTIFIED BY '${h(_.password)}';`,`ALTER USER '${h(_.username)}'@'localhost' IDENTIFIED BY '${h(_.password)}';`];for(let D of y)I.push(`GRANT ${b} ON \`${m(D)}\`.* TO '${h(_.username)}'@'%';`,`GRANT ${b} ON \`${m(D)}\`.* TO '${h(_.username)}'@'localhost';`);return I},v=e.users||[];return[Ee(),`for i in $(seq 1 30); do mysqladmin --socket=${u} -u root ping 2>/dev/null | grep -q alive && break; sleep 2; done`,`mysql --socket=${u} -u root <<'TS_CLOUD_SQL_EOF'`,`CREATE DATABASE IF NOT EXISTS \`${m(r)}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`,...S({username:n,password:s}),...v.flatMap(S),"FLUSH PRIVILEGES;","TS_CLOUD_SQL_EOF"]}function ta(e){return[`${Jt(e)} -tA <<'TS_CLOUD_PG_CAP_EOF' || true`,"\\set QUIET on","SELECT CASE WHEN used::float / NULLIF(cap, 0) >= 0.8"," THEN '[ts-cloud] postgres is at ' || used || '/' || cap || ' connections on this server.'"," || ' Raise max_connections (ALTER SYSTEM SET max_connections = ...; then restart) or'"," || ' set idle_session_timeout so abandoned pools are reclaimed.'"," ELSE NULL END","FROM (SELECT (SELECT count(*) FROM pg_stat_activity) AS used,"," (SELECT setting::int FROM pg_settings WHERE name = 'max_connections') AS cap) c","WHERE CASE WHEN used::float / NULLIF(cap, 0) >= 0.8 THEN true ELSE false END;","SELECT '[ts-cloud] ' || coalesce(datname, '(background)') || ': ' || count(*) || ' connection(s), oldest idle ' ||"," coalesce(round(extract(epoch from max(now() - state_change)) / 60)::text || 'm', 'n/a')","FROM pg_stat_activity","WHERE (SELECT count(*)::float / NULLIF((SELECT setting::int FROM pg_settings WHERE name = 'max_connections'), 0) FROM pg_stat_activity) >= 0.8","GROUP BY datname ORDER BY count(*) DESC;","TS_CLOUD_PG_CAP_EOF"]}function os(e){if(!e?.name)return{};let t=e.engine==="singlestore",r=e.engine==="vitess",n=e.engine==="postgres"?"pgsql":t?"singlestore":r?"vitess":"mysql",s=e.port??(e.engine==="postgres"?5432:r?15306:3306),i={DB_CONNECTION:n,DB_HOST:e.host||"127.0.0.1",DB_PORT:String(s),DB_DATABASE:e.name};if(e.username)i.DB_USERNAME=e.username;if(e.password)i.DB_PASSWORD=e.password;if((t||r)&&e.ssl!==!1)i.DB_SSL="true";return i}var Zr="/var/backups/ts-cloud",ra="/etc/ts-cloud/backups.config.ts",is="/etc/cron.d/ts-cloud-backups",xr="/usr/local/bin/ts-cloud-backup.sh";function na(e){if(!e.name)return null;let t=e.host||"127.0.0.1",r=e.engine==="postgres",n=r?"postgresql":"mysql",s=e.port??(r?5432:3306),i=(a)=>a.replace(/\\/g,"\\\\").replace(/'/g,"\\'");return[" {",` type: '${n}',`,` name: '${i(e.name)}',`," connection: {",` hostname: '${i(t)}',`,` port: ${s},`,` database: '${i(e.name)}',`,` username: '${i(e.username||e.name)}',`,` password: '${i(e.password||"")}',`," ssl: false,"," },"," includeSchema: true,"," includeData: true,"," },"].join(`
|
|
18
|
-
`)}function
|
|
19
|
-
`)}function
|
|
11
|
+
`,c=xi(a);return{host:`mta-sts.${t}`,body:a,id:c,txt:`v=STSv1; id=${c}`}}var Og=8461;function $h(e,t=Og){return[`const policy = ${JSON.stringify(e.body)}`,"Bun.serve({",` port: ${t},`," hostname: '127.0.0.1',"," fetch(req) {"," const { pathname } = new URL(req.url)"," if (pathname !== '/.well-known/mta-sts.txt') return new Response('Not Found', { status: 404 })"," return new Response(policy, { headers: { 'content-type': 'text/plain; charset=utf-8' } })"," },","})"].join(`
|
|
12
|
+
`)}var Tt={php:"php.net",nginx:"nginx.org",composer:"getcomposer.org",mysql:"mysql.com",mariadb:"mariadb.com/server",postgres:"postgresql.org",vitess:"vitess.io",etcd:"etcd.io",redis:"redis.io",memcached:"memcached.org",meilisearch:"meilisearch.com",mail:"github.com/mail-os/mail",git:"git-scm.com",certbot:"certbot.eff.org",bun:"bun.sh",node:"nodejs.org",deno:"deno.land"};var p="/opt/pantry";function jt(e){return`'${e.split("'").join("'\\''")}'`}function mt(e={}){let t=e.installDir??"/usr/local/bin",r=e.version?`export PANTRY_VERSION=${jt(e.version)}`:'export PANTRY_VERSION="${PANTRY_VERSION:-latest}"';return["export DEBIAN_FRONTEND=noninteractive","export PANTRY_SERVICE_SCOPE=system",`export PANTRY_INSTALL_DIR=${t}`,r,"command -v curl >/dev/null 2>&1 || (apt-get update -y && apt-get install -y curl ca-certificates)","command -v unzip >/dev/null 2>&1 || (apt-get update -y && apt-get install -y unzip)",`OS=$(uname -s | tr '[:upper:]' '[:lower:]'); ARCH=$(uname -m); case "$ARCH" in x86_64|amd64) ARCH=x64 ;; arm64|aarch64) ARCH=arm64 ;; esac; ZIP="pantry-\${OS}-\${ARCH}.zip"; if [ "\${PANTRY_VERSION:-latest}" = latest ]; then REL='latest/download'; else REL="download/v\${PANTRY_VERSION}"; fi; TMP=$(mktemp -d); curl -fsSL -o "\${TMP}/\${ZIP}" "https://github.com/pantry-pm/pantry/releases/\${REL}/\${ZIP}"; mkdir -p ${t}; unzip -o "\${TMP}/\${ZIP}" -d ${t}; chmod +x ${t}/pantry; rm -rf "\${TMP}"`,`export PATH="${t}:$PATH"`,"mkdir -p /opt/pantry"]}function Ee(){return'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true'}function Te(e){if(e.length===0)return[];return[`(cd /opt/pantry && pantry install ${[...new Set(e)].map(jt).join(" ")})`]}function Vt(e){return[...new Set(e)].flatMap((t)=>[`(cd /opt/pantry && pantry start ${jt(t)})`,`(cd /opt/pantry && pantry enable ${jt(t)})`])}var he="/etc/mail",we="mail-server",qr="mail",Wr=`${p}/pantry/.bin`;function Ce(e){return`'${String(e).split("'").join("'\\''")}'`}function Ge(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function Li(e){return[e.version?`${Tt.mail}@${e.version}`:Tt.mail]}function Yr(e,t){return`${he}/dkim/${t}.${e.dkim.selector}.pem`}function Jn(e){return`${e.storagePath}/smtp.db`}function Ui(e){let t=["# Generated by ts-cloud. Edits are overwritten on the next deploy —","# change `services.mail` in the cloud config instead.","","[server]",`host = ${Ge(e.bindAddress)}`,`port = ${e.ports.smtp}`,`hostname = ${Ge(e.hostname)}`];if(e.domains.length>0)t.push(`local_domains = ${Ge(e.domains.join(", "))}`);if(e.mode==="catcher")t.push("catch_all = true");if(t.push(`max_message_size = ${e.maxMessageSize}`,"","[tls]",`enabled = ${e.tls.enabled}`),e.tls.certPath)t.push(`cert_path = ${Ge(e.tls.certPath)}`);if(e.tls.keyPath)t.push(`key_path = ${Ge(e.tls.keyPath)}`);if(t.push("","[auth]",`enabled = ${e.mode==="server"}`,"","[antispam]",`dnsbl = ${e.spam.dnsbl}`,`greylist = ${e.spam.greylist}`,`spam_filter = ${e.spam.enabled}`,`junk_score = ${e.spam.junkScore}`,`reject_score = ${e.spam.rejectScore}`,"","[dkim]",`rotation_enabled = ${e.dkim.enabled&&e.dkim.rotate}`,`rotation_interval_days = ${e.dkim.rotateIntervalDays}`,"","[acme]",`enabled = ${e.tls.acme}`),e.tls.acmeEmail)t.push(`email = ${Ge(e.tls.acmeEmail)}`);if(t.push("","[webhook]",`enabled = ${!!e.webhookUrl}`),e.webhookUrl)t.push(`url = ${Ge(e.webhookUrl)}`);return t.push(""),t.join(`
|
|
13
|
+
`)}function Hi(e){let t=["# Generated by ts-cloud. See /etc/mail/config.toml for the rest.",`SMTP_DB_PATH=${Jn(e)}`,`SMTP_DELIVERY_METHOD=${e.delivery==="ses"?"ses":"direct"}`];if(e.delivery==="ses")t.push(`SMTP_SES_REGION=${e.sesRegion}`);if(e.ports.submission)t.push(`SUBMISSION_PORT=${e.ports.submission}`);if(e.ports.submissions)t.push(`SMTPS_PORT=${e.ports.submissions}`);if(e.ports.imap)t.push("IMAP_ENABLED=1",`IMAP_PORT=${e.ports.imap}`);if(e.webmail.enabled)t.push("SMTP_ENABLE_WEBMAIL=true",`SMTP_WEBMAIL_PORT=${e.webmail.port}`,`SMTP_WEBMAIL_TLS=${e.webmail.tls}`,`SMTP_WEBMAIL_SECURE_COOKIES=${e.webmail.secureCookies}`,`SMTP_WEBMAIL_ATTACHMENT_MAX_FILE=${e.webmail.attachmentMaxFileBytes}`,`SMTP_WEBMAIL_ATTACHMENT_MAX_TOTAL=${e.webmail.attachmentMaxTotalBytes}`,`SMTP_WEBMAIL_ATTACHMENT_MAX_COUNT=${e.webmail.attachmentMaxCount}`,`SMTP_WEBMAIL_UNDO_SEND_SECONDS=${e.webmail.undoSendSeconds}`);if(e.tls.requireForAuth)t.push("SMTP_REQUIRE_TLS_FOR_AUTH=true");if(e.dkim.enabled&&e.domains.length>0){let[r,...n]=e.domains;if(t.push(`DKIM_DOMAIN=${r}`,`DKIM_SELECTOR=${e.dkim.selector}`,`DKIM_PRIVATE_KEY_PATH=${Yr(e,r)}`),n.length>0){let s=n.map((i)=>`${i}:${e.dkim.selector}:${Yr(e,i)}`);t.push(`DKIM_EXTRA_KEYS=${s.join(",")}`)}}return t.push(""),t.join(`
|
|
14
|
+
`)}function Ni(e){let t=[e.ports.smtp,e.ports.submission,e.ports.submissions,e.ports.imap,e.ports.imaps].some((r)=>typeof r==="number"&&r<1024);return["[Unit]","Description=Mail server (SMTP/IMAP + webmail)","After=network-online.target","Wants=network-online.target","","[Service]","Type=simple",`User=${we}`,`Group=${we}`,`WorkingDirectory=${e.storagePath}`,`EnvironmentFile=${he}/mail.env`,`Environment="PATH=${Wr}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"`,`ExecStart=${Wr}/mail serve --config ${he}/config.toml`,"Restart=always","RestartSec=5","LimitNOFILE=65536",...t?["AmbientCapabilities=CAP_NET_BIND_SERVICE","CapabilityBoundingSet=CAP_NET_BIND_SERVICE"]:[],"NoNewPrivileges=true","PrivateTmp=true","ProtectSystem=strict","ProtectHome=true","ProtectKernelTunables=true","ProtectKernelModules=true","ProtectControlGroups=true",`ReadWritePaths=${e.storagePath} ${he}`,"","[Install]","WantedBy=multi-user.target",""].join(`
|
|
15
|
+
`)}function Mi(e){if(!e.dkim.enabled||e.domains.length===0)return[];let t=[`mkdir -p ${he}/dkim`];for(let r of e.domains){let n=Yr(e,r);t.push(`if [ ! -f ${Ce(n)} ]; then openssl genrsa -out ${Ce(n)} 2048; fi`,`chmod 0600 ${Ce(n)}`,`echo "DKIM ${e.dkim.selector}._domainkey.${r} IN TXT v=DKIM1; k=rsa; p=$(openssl rsa -in ${Ce(n)} -pubout -outform PEM 2>/dev/null | grep -v '^-----' | tr -d '\\n')"`)}return t.push(`chown -R ${we}:${we} ${he}/dkim`),t}function Fi(e){if(e.accounts.length===0)return[];let t=(r)=>`runuser -u ${we} -- env SMTP_DB_PATH="$TS_CLOUD_MAIL_DB" ${Wr}/mail user:local ${r}`;return e.accounts.flatMap((r)=>[t(`create ${Ce(r.address)} ${Ce(r.password)} ${Ce(r.address)}`),...r.passwordPolicy==="managed"?[t(`change-password ${Ce(r.address)} ${Ce(r.password)}`)]:[]])}function Qn(e){if(!e.enabled)return[];return[...Te(Li(e)),`id -u ${we} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin ${we}`,`mkdir -p ${e.storagePath} ${he}`,`chown -R ${we}:${we} ${e.storagePath}`,`TS_CLOUD_MAIL_DB="$(grep -sE '^SMTP_DB_PATH=' ${he}/mail.env | head -1 | cut -d= -f2- || true)"`,`[ -n "$TS_CLOUD_MAIL_DB" ] || TS_CLOUD_MAIL_DB=${Ce(Jn(e))}`,`cat > ${he}/config.toml <<'TS_CLOUD_MAIL_CONF_EOF'`,Ui(e),"TS_CLOUD_MAIL_CONF_EOF",`cat > ${he}/mail.env <<'TS_CLOUD_MAIL_ENV_EOF'`,Hi(e),"TS_CLOUD_MAIL_ENV_EOF",`sed -i "s|^SMTP_DB_PATH=.*|SMTP_DB_PATH=$TS_CLOUD_MAIL_DB|" ${he}/mail.env`,`chmod 0640 ${he}/mail.env`,`chown root:${we} ${he}/mail.env`,...Mi(e),`cat > /etc/systemd/system/${qr}.service <<'TS_CLOUD_MAIL_UNIT_EOF'`,Ni(e),"TS_CLOUD_MAIL_UNIT_EOF","systemctl daemon-reload",`systemctl enable ${qr}`,`systemctl restart ${qr}`,...Fi(e)]}var _e=`${p}/pantry/.bin`,Zr=15306,Xr=15991,Gt=15999,es=16101,qt=2379,Re="/var/lib/vitess",en=100;function Ct(e){return e===!0||typeof e==="object"&&e!==null}function zi(e){return typeof e==="object"&&e!==null?e:{}}function oe(e){return`'${String(e).split("'").join("'\\''")}'`}function Bi(e){let r=[e.version?`vitess.io@${e.version}`:"vitess.io"];if(e.mode!=="combo"&&!e.etcdEndpoint)r.push("etcd.io");return r.push("mysql.com@8.0.43"),r}var fe="vitess",Ki=`${_e}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`,ss="/usr/local/lib/vitess",tn=new Map;function Jr(e){return`${ss}/${e}.sh`}function nt(e,t){return tn.set(e,ji(t)),`/bin/sh ${Jr(e)}`}function ts(){let e=[`mkdir -p ${ss}`];for(let[t,r]of tn)e.push(`cat > ${Jr(t)} <<'TS_CLOUD_VITESS_LAUNCHER_EOF'`,r,"TS_CLOUD_VITESS_LAUNCHER_EOF",`chmod 0755 ${Jr(t)}`);return e}function ji(e){return["#!/bin/sh","set -e",`cd ${p}`,`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 ${_e}/mysqld 2>/dev/null)")")"`,`VTROOT="$(dirname "$(dirname "$(readlink -f ${_e}/mysqlctld 2>/dev/null)")")"`,"export VT_MYSQL_ROOT VTROOT",'LD_LIBRARY_PATH="$VT_MYSQL_ROOT/lib:$VTROOT/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"',"export LD_LIBRARY_PATH",`exec ${e.join(" ")}`].join(`
|
|
16
|
+
`)}function st(e){let t=["[Unit]",`Description=${e.description}`,`After=network.target${e.after?.length?` ${e.after.join(" ")}`:""}`];if(e.requires?.length)t.push(`Requires=${e.requires.join(" ")}`);return t.push("","[Service]","Type=simple",`User=${fe}`,`Group=${fe}`,`Environment="PATH=${Ki}"`,`Environment="VTDATAROOT=${Re}"`,...Object.entries(e.environment??{}).map(([r,n])=>`Environment="${r}=${n}"`),...(e.execStartPre??[]).map((r)=>`ExecStartPre=${r}`),`ExecStart=${e.execStart}`,"Restart=always","RestartSec=5","LimitNOFILE=65535","","[Install]","WantedBy=multi-user.target"),t.join(`
|
|
17
|
+
`)}function rs(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_VITESS_UNIT_EOF'`,t,"TS_CLOUD_VITESS_UNIT_EOF"]}function Vi(e){let t=e.cell??"zone1",r=e.vtgatePort??Zr,s=`${((e.keyspaces?.length)?e.keyspaces:[{name:"app"}]).map((i)=>{let a=(i.sharded?["-80","80-"]:["0"]).map((c)=>`shards:{name:"${c}"}`).join(" ");return`keyspaces:{name:"${i.name}" ${a}}`}).join(" ")} cells:"${t}"`;return st({description:"Vitess (vtcombo, single-process development stack)",execStart:nt("vtcombo",[`${_e}/vtcombo`,`--cell ${t}`,`--proto-topo ${oe(s)}`,`--mysql-server-port ${r}`,"--mysql-server-bind-address 127.0.0.1","--mysql-auth-server-impl none","--start-mysql",`--port ${Xr}`,`--grpc-port ${Gt}`])})}function Gi(){return st({description:"etcd (Vitess topology store)",execStart:nt("etcd",[`${_e}/etcd`,`--data-dir ${Re}/etcd`,`--listen-client-urls http://127.0.0.1:${qt}`,`--advertise-client-urls http://127.0.0.1:${qt}`]),execStartPre:[`+/bin/mkdir -p ${Re}/etcd`,`+/bin/chown ${fe}:${fe} ${Re}/etcd`]})}function rn(e){return["--topo-implementation etcd2",`--topo-global-server-address ${e.etcdEndpoint??`http://127.0.0.1:${qt}`}`,"--topo-global-root /vitess/global"]}function qi(e){let t=!e.etcdEndpoint;return st({description:"Vitess vtctld (control plane)",after:t?["vitess-etcd.service"]:[],requires:t?["vitess-etcd.service"]:[],execStart:nt("vtctld",[`${_e}/vtctld`,...rn(e),`--cell ${e.cell??"zone1"}`,"--service-map grpc-vtctl,grpc-vtctld",`--grpc-port ${Gt}`,`--port ${Gt+1}`])})}function Yi(e,t,r){let n=e.cell??"zone1";return st({description:`Vitess vttablet (${t}/${r})`,after:["vitess-vtctld.service","vitess-mysqlctld.service"],requires:["vitess-mysqlctld.service"],execStart:nt("vttablet",[`${_e}/vttablet`,...rn(e),`--tablet-path ${n}-${String(en).padStart(10,"0")}`,`--init-keyspace ${t}`,`--init-shard ${r}`,"--init-tablet-type replica",`--service-map ${oe("grpc-queryservice,grpc-tabletmanager,grpc-updatestream")}`,`--port ${es}`,`--grpc-port ${es+1}`,`--db-port ${e.mysqlPort??3306}`,`--mycnf-mysql-port ${e.mysqlPort??3306}`])})}function Xi(e){return st({description:"Vitess mysqlctld (managed mysqld)",execStart:nt("mysqlctld",[`${_e}/mysqlctld`,`--tablet-uid ${en}`,`--mysql-port ${e.mysqlPort??3306}`,'--init-db-sql-file "$VTROOT/config/init_db.sql"',"--wait-time 2m"]),execStartPre:[`+/bin/mkdir -p ${Re}`,`+/bin/chown ${fe}:${fe} ${Re}`]})}var os="/etc/vitess/auth.json",wt="/var/lib/vitess/vtgate-auth.sha256";function Qi(e){let t=e.username??"vitess",r=e.password??"";return["mkdir -p /etc/vitess",'VTESS_AUTH_TMP="$(mktemp)"',`cat > "$VTESS_AUTH_TMP" <<'TS_CLOUD_VITESS_AUTH_EOF'`,JSON.stringify({[t]:[{Password:r,UserData:t}]}),"TS_CLOUD_VITESS_AUTH_EOF",`VTESS_VTGATE_AUTH_SHA="$(sha256sum "$VTESS_AUTH_TMP" | awk '{print $1}')"`,"VTESS_VTGATE_AUTH_CHANGED=1",`if [ -f ${wt} ] && [ "$(cat ${wt})" = "$VTESS_VTGATE_AUTH_SHA" ]; then VTESS_VTGATE_AUTH_CHANGED=0; fi`,`install -o ${fe} -g ${fe} -m 0600 "$VTESS_AUTH_TMP" ${os}`,'rm -f "$VTESS_AUTH_TMP"']}function ea(e){let t=e.cell??"zone1";return st({description:"Vitess vtgate (query router)",after:["vitess-vtctld.service"],execStart:nt("vtgate",[`${_e}/vtgate`,...rn(e),`--cell ${t}`,`--cells-to-watch ${t}`,"--tablet-types-to-wait PRIMARY,REPLICA",`--service-map ${oe("grpc-vtgateservice")}`,`--mysql-server-port ${e.vtgatePort??Zr}`,`--mysql-server-bind-address ${e.bindAddress??"127.0.0.1"}`,"--mysql-auth-server-impl static",`--mysql-auth-server-static-file ${os}`,`--port ${Xr}`,`--grpc-port ${Xr+1}`])})}function ta(e){let t=e.cell??"zone1",r=e.etcdEndpoint??`http://127.0.0.1:${qt}`,n=`${_e}/vtctldclient --server 127.0.0.1:${Gt}`,s=[`for i in $(seq 1 30); do ${n} GetCellInfoNames >/dev/null 2>&1 && break; sleep 2; done`,`if ! ${n} GetCellInfoNames 2>/dev/null | grep -qx ${oe(t)}; then`,` ${n} AddCellInfo --root ${oe(`/vitess/${t}`)} --server-address ${oe(r)} ${oe(t)}`,"fi"];for(let i of e.keyspaces??[]){let a=i.sharded?" --sharded":"";s.push(`if ! ${n} GetKeyspace ${oe(i.name)} >/dev/null 2>&1; then`,` ${n} CreateKeyspace${a} ${oe(i.name)}`,"fi");let c=`${t}-${String(en).padStart(10,"0")}`;for(let u of i.sharded?["-80","80-"]:["0"]){let f=`${i.name}/${u}`;s.push("for i in $(seq 1 90); do",` if ${n} GetShard ${oe(f)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then break; fi`,` ${n} PlannedReparentShard ${oe(f)} --new-primary ${oe(c)} >/dev/null 2>&1 && break`,` ${n} InitShardPrimary --force ${oe(f)} ${oe(c)} >/dev/null 2>&1 && break`," sleep 2","done",`if ! ${n} GetShard ${oe(f)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then`,` echo "no primary could be elected for ${f}" >&2; exit 1`,"fi")}s.push(`${n} RebuildKeyspaceGraph ${oe(i.name)} >/dev/null`)}return s}function ns(e){let t=e.vtgatePort??Zr;return["for i in $(seq 1 60); do",` if (cd ${p} && eval "$(pantry env 2>/dev/null)"; MYSQL_PWD=${oe(e.password??"")} ${_e}/mysql -h 127.0.0.1 -P ${t} -u ${oe(e.username??"vitess")} --connect-timeout=2 -e 'SHOW KEYSPACES') >/dev/null 2>&1; then`,` echo "vtgate is serving on ${t}"; exit 0`," fi"," sleep 2","done",`echo "vtgate did not become ready on port ${t}" >&2`,"exit 1"]}function Zs(e){if(!Ct(e))return[];let t=zi(e),r=t.mode==="combo";tn.clear();let n=['if [ "$(uname -m)" != "x86_64" ]; then',' echo "vitess: Vitess publishes only x86_64 release tarballs; this box is $(uname -m). Drop managedServices.vitess or use an x86_64 host." >&2'," exit 1","fi",...Te(Bi(t)),`VT_MYSQL_LIB="$(dirname "$(dirname "$(readlink -f ${_e}/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 ${fe} >/dev/null 2>&1 || useradd --system --home-dir ${Re} --shell /usr/sbin/nologin ${fe}`,`mkdir -p ${Re}`,`chown -R ${fe}:${fe} ${Re}`];if(r)return n.push(...rs("vitess-vtcombo",Vi(t)),...ts(),"systemctl daemon-reload","systemctl enable --now vitess-vtcombo.service",...ns(t)),n;n.push(...Qi(t));let s=[];if(!t.etcdEndpoint)s.push(["vitess-etcd",Gi()]);s.push(["vitess-vtctld",qi(t)],["vitess-mysqlctld",Xi(t)],["vitess-vtgate",ea(t)]);for(let i of t.keyspaces??[])for(let a of i.sharded?["-80","80-"]:["0"])s.push([`vitess-vttablet-${i.name}-${a.replace(/-/g,"x")}`,Yi(t,i.name,a)]);for(let[i,a]of s)n.push(...rs(i,a));n.push(...ts()),n.push("systemctl daemon-reload");for(let[i]of s)n.push(`systemctl enable --now ${i}.service`);return n.push(`if [ "$VTESS_VTGATE_AUTH_CHANGED" = 1 ]; then systemctl restart vitess-vtgate.service; printf '%s\\n' "$VTESS_VTGATE_AUTH_SHA" > ${wt}; chown ${fe}:${fe} ${wt}; chmod 0600 ${wt}; fi`,...ta(t),...ns(t)),n}var ra=new Set(["singlestore","vitess"]);function Zn(e){if(e?.engine&&ra.has(e.engine))return!1;return!e?.host||e.host==="127.0.0.1"||e.host==="localhost"}function Xt(e,t="psql"){let r=e?.port??5432;if(Zn(e))return`${t} -p ${r} -U postgres`;let n=e?.username||"postgres";return`${e?.password?`PGPASSWORD='${e.password.replace(/'/g,"'\\''")}' `:""}${t} -h ${e.host} -p ${r} -U ${n} -w`}function Oe(e){return e===!0||typeof e==="object"&&e!=null}function na(e){let t=[],r=[];if(Oe(e.mysql))t.push(typeof e.mysql==="object"&&e.mysql.version?`mysql.com@${e.mysql.version}`:"mysql.com@8.0.43"),r.push("mysql");else if(Oe(e.mariadb))t.push(Tt.mariadb),r.push("mariadb");if(Oe(e.postgres))t.push("postgresql.org"),r.push("postgres");if(Oe(e.redis))t.push("redis.io"),r.push("redis");if(Oe(e.memcached))t.push("memcached.org"),r.push("memcached");if(Oe(e.meilisearch))t.push("meilisearch.com"),r.push("meilisearch");return{packages:t,services:r}}function Qt(e={},t={}){let r=na(e),n=Zs(e.vitess),s=t.mail?Qn(t.mail):[];if(r.packages.length===0)return[...n,...s];return[...Te(r.packages),...Vt(r.services),...n,...s]}function ot(e,t={}){if(!e?.name)return[];if(!Zn(e))return[];let r=e.name,n=e.username||r,s=e.password||"",i=Oe(t.postgres)||e.engine==="postgres",a=Oe(t.mariadb)||e.engine==="mariadb",c=Oe(t.mysql)||e.engine==="mysql";if(i&&!c&&!a){let v=(R)=>`"${R.replace(/"/g,'""')}"`,y=(R)=>`'${R.replace(/'/g,"''")}'`,b=(R,x)=>["DO $$ BEGIN",` IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${y(R)}) THEN`,` CREATE ROLE ${v(R)} LOGIN PASSWORD ${y(x)};`," ELSE",` ALTER ROLE ${v(R)} LOGIN PASSWORD ${y(x)};`," END IF;","END $$;"],I=(R)=>{let x=R.databases&&R.databases.length>0?R.databases:[r],W=[];for(let k of x)if(R.access==="readonly")W.push(`GRANT CONNECT ON DATABASE ${v(k)} TO ${v(R.username)};`,`\\connect ${v(k)}`,`GRANT USAGE ON SCHEMA public TO ${v(R.username)};`,`GRANT SELECT ON ALL TABLES IN SCHEMA public TO ${v(R.username)};`,`ALTER DEFAULT PRIVILEGES FOR ROLE ${v(n)} IN SCHEMA public GRANT SELECT ON TABLES TO ${v(R.username)};`,"\\connect postgres");else W.push(`GRANT ALL PRIVILEGES ON DATABASE ${v(k)} TO ${v(R.username)};`);return W},D=e.users||[],H=e.port??5432;return[Ee(),`for i in $(seq 1 30); do pg_isready -p ${H} -q && break; sleep 2; done`,`${Xt(e)} <<'TS_CLOUD_PG_EOF'`,...b(n,s),`SELECT 'CREATE DATABASE ${v(r)} OWNER ${v(n)}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = ${y(r)})\\gexec`,...D.flatMap((R)=>[...b(R.username,R.password),...I(R)]),"TS_CLOUD_PG_EOF",...sa(e)]}let u=a?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock",f=(v)=>v.replace(/`/g,"``"),h=(v)=>v.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),_=(v)=>{let y=v.databases&&v.databases.length>0?v.databases:[r],b=v.access==="readonly"?"SELECT":"ALL PRIVILEGES",I=[`CREATE USER IF NOT EXISTS '${h(v.username)}'@'%' IDENTIFIED BY '${h(v.password)}';`,`CREATE USER IF NOT EXISTS '${h(v.username)}'@'localhost' IDENTIFIED BY '${h(v.password)}';`,`ALTER USER '${h(v.username)}'@'%' IDENTIFIED BY '${h(v.password)}';`,`ALTER USER '${h(v.username)}'@'localhost' IDENTIFIED BY '${h(v.password)}';`];for(let D of y)I.push(`GRANT ${b} ON \`${f(D)}\`.* TO '${h(v.username)}'@'%';`,`GRANT ${b} ON \`${f(D)}\`.* TO '${h(v.username)}'@'localhost';`);return I},S=e.users||[];return[Ee(),`for i in $(seq 1 30); do mysqladmin --socket=${u} -u root ping 2>/dev/null | grep -q alive && break; sleep 2; done`,`mysql --socket=${u} -u root <<'TS_CLOUD_SQL_EOF'`,`CREATE DATABASE IF NOT EXISTS \`${f(r)}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`,..._({username:n,password:s}),...S.flatMap(_),"FLUSH PRIVILEGES;","TS_CLOUD_SQL_EOF"]}function sa(e){return[`${Xt(e)} -tA <<'TS_CLOUD_PG_CAP_EOF' || true`,"\\set QUIET on","SELECT CASE WHEN used::float / NULLIF(cap, 0) >= 0.8"," THEN '[ts-cloud] postgres is at ' || used || '/' || cap || ' connections on this server.'"," || ' Raise max_connections (ALTER SYSTEM SET max_connections = ...; then restart) or'"," || ' set idle_session_timeout so abandoned pools are reclaimed.'"," ELSE NULL END","FROM (SELECT (SELECT count(*) FROM pg_stat_activity) AS used,"," (SELECT setting::int FROM pg_settings WHERE name = 'max_connections') AS cap) c","WHERE CASE WHEN used::float / NULLIF(cap, 0) >= 0.8 THEN true ELSE false END;","SELECT '[ts-cloud] ' || coalesce(datname, '(background)') || ': ' || count(*) || ' connection(s), oldest idle ' ||"," coalesce(round(extract(epoch from max(now() - state_change)) / 60)::text || 'm', 'n/a')","FROM pg_stat_activity","WHERE (SELECT count(*)::float / NULLIF((SELECT setting::int FROM pg_settings WHERE name = 'max_connections'), 0) FROM pg_stat_activity) >= 0.8","GROUP BY datname ORDER BY count(*) DESC;","TS_CLOUD_PG_CAP_EOF"]}function is(e){if(!e?.name)return{};let t=e.engine==="singlestore",r=e.engine==="vitess",n=e.engine==="postgres"?"pgsql":t?"singlestore":r?"vitess":"mysql",s=e.port??(e.engine==="postgres"?5432:r?15306:3306),i={DB_CONNECTION:n,DB_HOST:e.host||"127.0.0.1",DB_PORT:String(s),DB_DATABASE:e.name};if(e.username)i.DB_USERNAME=e.username;if(e.password)i.DB_PASSWORD=e.password;if((t||r)&&e.ssl!==!1)i.DB_SSL="true";return i}var nn="/var/backups/ts-cloud",oa="/etc/ts-cloud/backups.config.ts",as="/etc/cron.d/ts-cloud-backups",Or="/usr/local/bin/ts-cloud-backup.sh";function ia(e){if(!e.name)return null;let t=e.host||"127.0.0.1",r=e.engine==="postgres",n=r?"postgresql":"mysql",s=e.port??(r?5432:3306),i=(a)=>a.replace(/\\/g,"\\\\").replace(/'/g,"\\'");return[" {",` type: '${n}',`,` name: '${i(e.name)}',`," connection: {",` hostname: '${i(t)}',`,` port: ${s},`,` database: '${i(e.name)}',`,` username: '${i(e.username||e.name)}',`,` password: '${i(e.password||"")}',`," ssl: false,"," },"," includeSchema: true,"," includeData: true,"," },"].join(`
|
|
18
|
+
`)}function aa(e,t){let r=e?ia(e):null,n=t.bucket?[" destinations: ["," {"," type: 's3',",` bucket: '${t.bucket}',`," prefix: 'db-backups',",...t.endpoint?[` endpoint: '${t.endpoint}',`]:[]," optional: false,"," },"," ],"]:[];return["import type { BackupConfig } from 'ts-backups'","","const config: BackupConfig = {"," verbose: true,",` outputPath: '${nn}',`," retention: {",` count: ${t.retentionCount??5},`,` maxAge: ${t.retentionDays??30},`," },"," databases: [",...r?[r]:[]," ],",...n,"}","","export default config",""].join(`
|
|
19
|
+
`)}function rr(e){let{database:t,backups:r}=e;if(!r.enabled)return[];let n=r.schedule||"0 2 * * *",s=aa(t,r);return["export DEBIAN_FRONTEND=noninteractive",`mkdir -p /etc/ts-cloud ${nn}`,"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 > ${oa} <<'TS_CLOUD_BACKUP_CFG_EOF'`,s.replace(/\n$/,""),"TS_CLOUD_BACKUP_CFG_EOF",`cat > ${Or} <<'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 start --config /etc/ts-cloud/backups.config.ts; then notify "❌ ts-cloud backup failed"; exit 1; fi',"TS_CLOUD_BACKUP_RUN_EOF",`chmod +x ${Or}`,`cat > ${as} <<'TS_CLOUD_BACKUP_CRON_EOF'`,`${n} root ${Or} >> /var/log/ts-cloud-backup.log 2>&1`,"TS_CLOUD_BACKUP_CRON_EOF",`chmod 644 ${as}`]}function ca(e){return e==="mariadb"?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock"}function _g(e,t={}){if(!e?.name)return[];let r=e.name,n=e.engine==="postgres",s=t.from?`TS_CLOUD_DUMP="${t.from}"`:`TS_CLOUD_DUMP="$(find ${nn} -type f -name '*${r}*.sql' -o -type f -name '*${r}*.sql.gz' 2>/dev/null | xargs -r ls -1t 2>/dev/null | head -1)"`,i=n?`${Xt(e)} -d "${r}"`:`mysql --socket=${ca(e.engine)} -u root "${r}"`;return["set -uo pipefail",'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true',s,'[ -n "$TS_CLOUD_DUMP" ] && [ -f "$TS_CLOUD_DUMP" ] || { echo "no backup dump found to restore" >&2; exit 1; }','echo "[ts-cloud] restoring '+r+' from $TS_CLOUD_DUMP"',`case "$TS_CLOUD_DUMP" in *.gz) gunzip -c "$TS_CLOUD_DUMP" ;; *) cat "$TS_CLOUD_DUMP" ;; esac | ${i}`,'echo "restore complete"']}function la(e){return`/etc/ts-cloud/${e}-upgrade.env`}function ua(e){return`${e}-upgrade`}function eo(e){if(!e||e.length===0)return[];let t=["mkdir -p /etc/ts-cloud"],r=[];for(let n of e){if(n.enabled===!1)continue;if(!n.service||!n.binary)continue;let{service:s,binary:i,command:a="upgrade",channel:c="stable",schedule:u="daily",randomizedDelay:f="4h",args:h=[]}=n,_=ua(s),S=la(s),v=[`--path ${i}`,`--service ${s}`,...c==="canary"?["--canary"]:[],...h].join(" ");t.push(`if [ ! -f ${S} ]; then`,` cat > ${S} <<'TS_CLOUD_APPUPD_ENV_EOF'`,"# Set to false to pause automatic updates without disabling the timer.","ENABLED=true","# Extra flags appended to the update command.","ARGS=","TS_CLOUD_APPUPD_ENV_EOF","fi",`chmod 644 ${S}`,`cat > /etc/systemd/system/${_}.service <<'TS_CLOUD_APPUPD_SVC_EOF'`,"[Unit]",`Description=Check for and install ${s} updates`,"After=network-online.target","Wants=network-online.target","","[Service]","Type=oneshot",`EnvironmentFile=-${S}`,`ExecStart=/bin/sh -c 'if [ "\${ENABLED:-true}" != "true" ]; then echo "auto-update disabled via ${S}"; exit 0; fi; exec ${i} ${a} ${v} $ARGS'`,"TS_CLOUD_APPUPD_SVC_EOF",`cat > /etc/systemd/system/${_}.timer <<'TS_CLOUD_APPUPD_TMR_EOF'`,"[Unit]",`Description=Scheduled ${s} update check`,"","[Timer]",`OnCalendar=${u}`,`RandomizedDelaySec=${f}`,"Persistent=true","","[Install]","WantedBy=timers.target","TS_CLOUD_APPUPD_TMR_EOF"),r.push(`systemctl enable --now ${_}.timer`)}if(r.length===0)return[];return[...t,"systemctl daemon-reload",...r]}function Ue(e=!0){if(!e)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 cs=[["nginx",80],["https",443],["phpFpm",9074],["mysql",3306],["postgres",5432],["redis",6379],["meilisearch",7700],["typesense",8108],["smtp",25]];function pa(e=!0){let t=typeof e==="object"?e:{},r=typeof e==="boolean"?e:e.enabled!==!1,n=Number(t.alerts?.bandwidthTb??0);return{enabled:r,cpuLoadPerCore:t.alerts?.cpuLoadPerCore??2,memPercent:t.alerts?.memPercent??90,diskPercent:t.alerts?.diskPercent??90,bandwidthTb:Number.isFinite(n)&&n>0?n:0,bandwidthPercent:t.alerts?.bandwidthPercent??80}}function xe(e=!0){let{enabled:t,cpuLoadPerCore:r,memPercent:n,diskPercent:s,bandwidthTb:i,bandwidthPercent:a}=pa(e);if(!t)return[];let c=Math.round(i*1000000000000),u=cs.map(([y,b])=>`SVC_${y.toUpperCase()}=$(probe ${b})`),f=cs.map(([y])=>`"${y}":"$SVC_${y.toUpperCase()}"`).join(","),h=(typeof e==="object"?e.filesystems:void 0)??["/"];if(!h.length)throw Error("monitoring.filesystems must include at least one path");let _=h.map((y)=>typeof y==="string"?{path:y,requiredMount:!1}:y);for(let y of _)if(y.path!=="/"&&(!y.path.startsWith("/")||!y.path.slice(1).split("/").every((b)=>/^[\w-]+$/.test(b))))throw Error(`Invalid monitoring filesystem path: ${y.path}`);let S=_.flatMap((y,b)=>[`DISK_${b}_MOUNTED=true; DISK_${b}_PCT=null`,...y.requiredMount?[`if ! mountpoint -q '${y.path}'; then DISK_${b}_MOUNTED=false; DISK_ALERTS="$DISK_ALERTS missing-mount=${y.path}"; ALERT_KEY="$ALERT_KEY mount:${y.path}"; fi`]:[],`if [ "$DISK_${b}_MOUNTED" = true ]; then`,` DISK_${b}_PCT=$(df -Pk '${y.path}' 2>/dev/null | awk 'NR==2{gsub("%","",$5);print $5}')`,` if [[ "$DISK_${b}_PCT" =~ ^[0-9]+$ ]]; then`,` [ "$DISK_${b}_PCT" -le "$DISK_PCT" ] || DISK_PCT=$DISK_${b}_PCT`,` if [ "$DISK_${b}_PCT" -ge ${s} ]; then DISK_ALERTS="$DISK_ALERTS disk=${y.path}:$DISK_${b}_PCT%"; ALERT_KEY="$ALERT_KEY disk:${y.path}"; fi`,` else DISK_${b}_PCT=null; DISK_ALERTS="$DISK_ALERTS unreadable-disk=${y.path}"; ALERT_KEY="$ALERT_KEY unreadable:${y.path}"; fi`,"fi"]),v=_.map((y,b)=>`{"path":"${y.path}","usedPercent":$DISK_${b}_PCT,"mounted":$DISK_${b}_MOUNTED}`).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
|
|
20
20
|
$(free -m | awk '/^Mem:/{total=$2; used=$3} /^Swap:/{print total, used, $2, $3}')
|
|
21
|
-
EOF`,'DISK_PCT=0; DISK_ALERTS=""; ALERT_KEY=""',...v,"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; }",...u,"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,"disks":[${_}],"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":${c}},"services":{`+m+"}}","JSON","mv -f /var/lib/ts-cloud/metrics.json.tmp /var/lib/ts-cloud/metrics.json",'ALERTS="$DISK_ALERTS"',`if awk -v l="$LOAD" -v c="$CPUS" -v t=${r} 'BEGIN{exit !(c>0 && l/c > t)}'; then ALERTS="$ALERTS load=$LOAD/${r}xCPU"; ALERT_KEY="$ALERT_KEY cpu"; fi`,`if [ "\${MEM_PCT:-0}" -ge ${n} ]; then ALERTS="$ALERTS mem=\${MEM_PCT}%"; ALERT_KEY="$ALERT_KEY memory"; fi`,"PREV=$(cat /var/lib/ts-cloud/alert-state 2>/dev/null || echo ok)",'if [ -n "$ALERTS" ]; then',` if [ "$PREV" != "$ALERT_KEY" ] && [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "⚠️ $(hostname): resource alert:$ALERTS"; then printf '%s\\n' "$ALERT_KEY" > ${"/var/lib/ts-cloud/alert-state"}; fi`,"else",` if [ "$PREV" != ok ] && [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "✅ $(hostname): resource usage back to normal"; then echo ok > ${"/var/lib/ts-cloud/alert-state"}; fi`,"fi",...c>0?["BW_TOTAL=$(( MONTH_RX + MONTH_TX ))",`BW_PCT=$(( BW_TOTAL * 100 / ${c} ))`,"BW_PREV=$(cat /var/lib/ts-cloud/bandwidth-alert-state 2>/dev/null || echo ok)",`if [ "$BW_PCT" -ge ${a} ]; then`,` if [ "$BW_PREV" != alert ] && [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "⚠️ $(hostname): bandwidth at \${BW_PCT}% of the ${i} TB monthly allowance ($MONTH_KEY)"; then echo alert > ${"/var/lib/ts-cloud/bandwidth-alert-state"}; fi`,"else",` if [ "$BW_PREV" = alert ] && [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "✅ $(hostname): bandwidth back under the monthly allowance (\${BW_PCT}%)"; then echo ok > ${"/var/lib/ts-cloud/bandwidth-alert-state"}; fi`,"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 la={"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"},ua="127.0.0.1:9074";function cs(e){return ua}function pa(e={}){let t=e.versions?.length?e.versions:["8.3"];return e.default&&t.includes(e.default)?e.default:t[0]}function da(e={}){return{...e.optimizeForProduction===!1?{}:{...la},...e.ini||{}}}function ma(e={}){let t=da(e),r=Object.keys(t);if(r.length===0)return[];let n=r.map((i)=>`${i}=${t[i]}`),s="ts-cloud-managed";return[Ee(),"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'`,`; ${s} — production PHP tuning`,...n,"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 '/; ${s} BEGIN/,/; ${s} END/d' "$TS_CLOUD_LOADED_INI"`,` cat >> "$TS_CLOUD_LOADED_INI" <<'TS_CLOUD_PHPINI_EOF'`,`; ${s} BEGIN`,...n,`; ${s} END`,"TS_CLOUD_PHPINI_EOF","fi",`(cd ${f} && pantry restart php-fpm) 2>/dev/null || true`]}function Qt(e={}){let t=pa(e),r=e.installNginx!==!1,n=e.installComposer!==!1,s=[`php.net@${t}`];if(n)s.push("getcomposer.org");if(r)s.push("nginx.org");return[...Te(s),...Bt(["php-fpm"]),...ma(e)]}function en(e,t){if(!e)return[];let r=[];if(e.template&&t?.[e.template])r.push(...t[e.template]);if(e.serverSnippet)r.push(...e.serverSnippet);return r}function fa(e){if(!e)return"";let t=typeof e==="object"?e:{},n=[`max-age=${t.maxAge??31536000}`];if(t.includeSubDomains??!0)n.push("includeSubDomains");if(t.preload)n.push("preload");return` add_header Strict-Transport-Security "${n.join("; ")}" always;`}function ga(e){if(!e||!e.allow?.length&&!e.deny?.length)return[];let t=[];for(let r of e.deny||[])t.push(` deny ${r};`);if(e.allow?.length){for(let r of e.allow)t.push(` allow ${r};`);t.push(" deny all;")}return t}function ls(e){return`/etc/nginx/.htpasswd-${e}`}var ha=new Set(["laravel","php","statamic","wordpress"]);function Sa(e){return ha.has(e)}function _a(e){return e==="laravel"||e==="statamic"?"public":""}function va(e,t){let r=e.replace(/\/+$/,""),n=t.replace(/^\/+|\/+$/g,"");return n?`${r}/${n}`:r}function ya(e){let t=e.type??"laravel",r=e.webDirectory??_a(t),n=va(e.appDir,r),s=Sa(t),i=e.phpVersion??"8.3",a=[` root ${n};`,"",' add_header X-Frame-Options "SAMEORIGIN";',' add_header X-Content-Type-Options "nosniff";'],c=fa(e.hsts);if(c)a.push(c);for(let u of ga(e.security))a.push(u);if(a.push("",` index ${s?"index.php index.html":"index.html index.htm"};`,""," charset utf-8;",""),e.clientMaxBodySize)a.push(` client_max_body_size ${e.clientMaxBodySize};`,"");if(e.auth)a.push(` auth_basic "${e.auth.realm||"Restricted"}";`,` auth_basic_user_file ${ls(e.siteName)};`,"");for(let[u,m]of Object.entries(e.redirects||{}))a.push(` location = ${u} { return 301 ${m}; }`);if(Object.keys(e.redirects||{}).length>0)a.push("");if(s){if(a.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 ${e.fastcgiPass??cs(i)};`," fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;"," include fastcgi_params;"," }",""," location ~ /\\.(?!well-known).* {"," deny all;"," }"),t==="wordpress")a.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(t==="spa")a.push(" location / {"," try_files $uri $uri/ /index.html;"," }");else a.push(" location / {"," try_files $uri $uri/ =404;"," }");if(e.serverSnippet&&e.serverSnippet.length>0){a.push("");for(let u of e.serverSnippet)a.push(u?` ${u}`:"")}return a}function $a(e){let t=[e.domain,...e.aliases||[]].filter(Boolean);for(let i of t)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(i.trim()))throw Error(`Refusing to build a vhost: '${i}' is not a valid hostname.`);if(!t.length)throw Error("Refusing to build a vhost: no server_name (domain) was given.");let r=t.join(" "),n=ya(e);if(e.ssl){let i=["server {"," listen 80;"," listen [::]:80;",` server_name ${r};`," return 301 https://$host$request_uri;","}"],a=["server {"," listen 443 ssl;"," listen [::]:443 ssl;",` server_name ${r};`,` ssl_certificate ${e.ssl.certPath};`,` ssl_certificate_key ${e.ssl.keyPath};`,...e.tlsProtocols?.length?[` ssl_protocols ${e.tlsProtocols.join(" ")};`]:[],"",...n,"}"];return`${[...i,"",...a].join(`
|
|
21
|
+
EOF`,'DISK_PCT=0; DISK_ALERTS=""; ALERT_KEY=""',...S,"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; }",...u,"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,"disks":[${v}],"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":${c}},"services":{`+f+"}}","JSON","mv -f /var/lib/ts-cloud/metrics.json.tmp /var/lib/ts-cloud/metrics.json",'ALERTS="$DISK_ALERTS"',`if awk -v l="$LOAD" -v c="$CPUS" -v t=${r} 'BEGIN{exit !(c>0 && l/c > t)}'; then ALERTS="$ALERTS load=$LOAD/${r}xCPU"; ALERT_KEY="$ALERT_KEY cpu"; fi`,`if [ "\${MEM_PCT:-0}" -ge ${n} ]; then ALERTS="$ALERTS mem=\${MEM_PCT}%"; ALERT_KEY="$ALERT_KEY memory"; fi`,"PREV=$(cat /var/lib/ts-cloud/alert-state 2>/dev/null || echo ok)",'if [ -n "$ALERTS" ]; then',` if [ "$PREV" != "$ALERT_KEY" ] && [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "⚠️ $(hostname): resource alert:$ALERTS"; then printf '%s\\n' "$ALERT_KEY" > ${"/var/lib/ts-cloud/alert-state"}; fi`,"else",` if [ "$PREV" != ok ] && [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "✅ $(hostname): resource usage back to normal"; then echo ok > ${"/var/lib/ts-cloud/alert-state"}; fi`,"fi",...c>0?["BW_TOTAL=$(( MONTH_RX + MONTH_TX ))",`BW_PCT=$(( BW_TOTAL * 100 / ${c} ))`,"BW_PREV=$(cat /var/lib/ts-cloud/bandwidth-alert-state 2>/dev/null || echo ok)",`if [ "$BW_PCT" -ge ${a} ]; then`,` if [ "$BW_PREV" != alert ] && [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "⚠️ $(hostname): bandwidth at \${BW_PCT}% of the ${i} TB monthly allowance ($MONTH_KEY)"; then echo alert > ${"/var/lib/ts-cloud/bandwidth-alert-state"}; fi`,"else",` if [ "$BW_PREV" = alert ] && [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "✅ $(hostname): bandwidth back under the monthly allowance (\${BW_PCT}%)"; then echo ok > ${"/var/lib/ts-cloud/bandwidth-alert-state"}; fi`,"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 da={"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"},ma="127.0.0.1:9074";function ls(e){return ma}function fa(e={}){let t=e.versions?.length?e.versions:["8.3"];return e.default&&t.includes(e.default)?e.default:t[0]}function ga(e={}){return{...e.optimizeForProduction===!1?{}:{...da},...e.ini||{}}}function ha(e={}){let t=ga(e),r=Object.keys(t);if(r.length===0)return[];let n=r.map((i)=>`${i}=${t[i]}`),s="ts-cloud-managed";return[Ee(),"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'`,`; ${s} — production PHP tuning`,...n,"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 '/; ${s} BEGIN/,/; ${s} END/d' "$TS_CLOUD_LOADED_INI"`,` cat >> "$TS_CLOUD_LOADED_INI" <<'TS_CLOUD_PHPINI_EOF'`,`; ${s} BEGIN`,...n,`; ${s} END`,"TS_CLOUD_PHPINI_EOF","fi",`(cd ${p} && pantry restart php-fpm) 2>/dev/null || true`]}function nr(e={}){let t=fa(e),r=e.installNginx!==!1,n=e.installComposer!==!1,s=[`php.net@${t}`];if(n)s.push("getcomposer.org");if(r)s.push("nginx.org");return[...Te(s),...Vt(["php-fpm"]),...ha(e)]}function sn(e,t){if(!e)return[];let r=[];if(e.template&&t?.[e.template])r.push(...t[e.template]);if(e.serverSnippet)r.push(...e.serverSnippet);return r}function Sa(e){if(!e)return"";let t=typeof e==="object"?e:{},n=[`max-age=${t.maxAge??31536000}`];if(t.includeSubDomains??!0)n.push("includeSubDomains");if(t.preload)n.push("preload");return` add_header Strict-Transport-Security "${n.join("; ")}" always;`}function va(e){if(!e||!e.allow?.length&&!e.deny?.length)return[];let t=[];for(let r of e.deny||[])t.push(` deny ${r};`);if(e.allow?.length){for(let r of e.allow)t.push(` allow ${r};`);t.push(" deny all;")}return t}function us(e){return`/etc/nginx/.htpasswd-${e}`}var _a=new Set(["laravel","php","statamic","wordpress"]);function ya(e){return _a.has(e)}function $a(e){return e==="laravel"||e==="statamic"?"public":""}function ba(e,t){let r=e.replace(/\/+$/,""),n=t.replace(/^\/+|\/+$/g,"");return n?`${r}/${n}`:r}function Ta(e){let t=e.type??"laravel",r=e.webDirectory??$a(t),n=ba(e.appDir,r),s=ya(t),i=e.phpVersion??"8.3",a=[` root ${n};`,"",' add_header X-Frame-Options "SAMEORIGIN";',' add_header X-Content-Type-Options "nosniff";'],c=Sa(e.hsts);if(c)a.push(c);for(let u of va(e.security))a.push(u);if(a.push("",` index ${s?"index.php index.html":"index.html index.htm"};`,""," charset utf-8;",""),e.clientMaxBodySize)a.push(` client_max_body_size ${e.clientMaxBodySize};`,"");if(e.auth)a.push(` auth_basic "${e.auth.realm||"Restricted"}";`,` auth_basic_user_file ${us(e.siteName)};`,"");for(let[u,f]of Object.entries(e.redirects||{}))a.push(` location = ${u} { return 301 ${f}; }`);if(Object.keys(e.redirects||{}).length>0)a.push("");if(s){if(a.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 ${e.fastcgiPass??ls(i)};`," fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;"," include fastcgi_params;"," }",""," location ~ /\\.(?!well-known).* {"," deny all;"," }"),t==="wordpress")a.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(t==="spa")a.push(" location / {"," try_files $uri $uri/ /index.html;"," }");else a.push(" location / {"," try_files $uri $uri/ =404;"," }");if(e.serverSnippet&&e.serverSnippet.length>0){a.push("");for(let u of e.serverSnippet)a.push(u?` ${u}`:"")}return a}function wa(e){let t=[e.domain,...e.aliases||[]].filter(Boolean);for(let i of t)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(i.trim()))throw Error(`Refusing to build a vhost: '${i}' is not a valid hostname.`);if(!t.length)throw Error("Refusing to build a vhost: no server_name (domain) was given.");let r=t.join(" "),n=Ta(e);if(e.ssl){let i=["server {"," listen 80;"," listen [::]:80;",` server_name ${r};`," return 301 https://$host$request_uri;","}"],a=["server {"," listen 443 ssl;"," listen [::]:443 ssl;",` server_name ${r};`,` ssl_certificate ${e.ssl.certPath};`,` ssl_certificate_key ${e.ssl.keyPath};`,...e.tlsProtocols?.length?[` ssl_protocols ${e.tlsProtocols.join(" ")};`]:[],"",...n,"}"];return`${[...i,"",...a].join(`
|
|
22
22
|
`)}
|
|
23
23
|
`}return`${["server {"," listen 80;"," listen [::]:80;",` server_name ${r};`,...n,"}"].join(`
|
|
24
24
|
`)}
|
|
25
|
-
`}function
|
|
26
|
-
`);s.push(`cat >> ${r} <<'TS_CLOUD_KEYS_EOF'`,i,"TS_CLOUD_KEYS_EOF",`chmod 600 ${r}`)}return s}function
|
|
27
|
-
`))} > ${y}`,`chmod 644 ${y}`),h.push(`--user ${
|
|
25
|
+
`}function on(e){let t=`/etc/nginx/sites-available/${e.siteName}`,r=`/etc/nginx/sites-enabled/${e.siteName}`,n=wa(e),s=[...an()];if(e.auth){let i=us(e.siteName),a=(f)=>f.split("'").join("'\\''"),c=a(e.auth.password),u=a(e.auth.username);s.push(`TS_CLOUD_HTPASS=$(openssl passwd -apr1 '${c}')`,`printf '%s:%s\\n' '${u}' "$TS_CLOUD_HTPASS" > ${i}`,`chmod 640 ${i}`,`chown root:www-data ${i} 2>/dev/null || true`)}return s.push(`cat > ${t} <<'TS_CLOUD_NGINX_EOF'`,n.replace(/\n$/,""),"TS_CLOUD_NGINX_EOF",`ln -sf ${t} ${r}`,"rm -f /etc/nginx/sites-enabled/default",`${He} -t`,"systemctl reload ts-cloud-nginx 2>/dev/null || systemctl restart ts-cloud-nginx 2>/dev/null || true"),s}var He="/usr/local/bin/ts-cloud-nginx";function an(e="/opt/pantry"){return[...mt(),...Te(["nginx.org"]),"mkdir -p /etc/nginx/sites-available /etc/nginx/sites-enabled /var/log/nginx /var/lib/nginx/body /var/lib/nginx/proxy /var/lib/nginx/fastcgi /var/lib/nginx/uwsgi /var/lib/nginx/scgi","getent passwd www-data >/dev/null || useradd --system --no-create-home --shell /usr/sbin/nologin www-data","chown -R www-data:www-data /var/lib/nginx /var/log/nginx",`cat > ${He} <<'TS_CLOUD_NGINXBIN_EOF'`,"#!/bin/sh",`eval "$(cd ${e} && pantry env 2>/dev/null)"`,"NGINX_BIN=/opt/pantry/pantry/.bin/nginx",'if [ ! -x "$NGINX_BIN" ]; then NGINX_BIN=$(command -v nginx || true); fi','if [ -z "$NGINX_BIN" ]; then echo "nginx binary not found; run pantry install nginx.org or install nginx explicitly" >&2; exit 1; fi','exec "$NGINX_BIN" -c /etc/nginx/nginx.conf "$@"',"TS_CLOUD_NGINXBIN_EOF",`chmod +x ${He}`,"cat > /etc/nginx/fastcgi_params <<'TS_CLOUD_FCGI_EOF'","fastcgi_param QUERY_STRING $query_string;","fastcgi_param REQUEST_METHOD $request_method;","fastcgi_param CONTENT_TYPE $content_type;","fastcgi_param CONTENT_LENGTH $content_length;","fastcgi_param SCRIPT_NAME $fastcgi_script_name;","fastcgi_param REQUEST_URI $request_uri;","fastcgi_param DOCUMENT_URI $document_uri;","fastcgi_param DOCUMENT_ROOT $document_root;","fastcgi_param SERVER_PROTOCOL $server_protocol;","fastcgi_param REQUEST_SCHEME $scheme;","fastcgi_param HTTPS $https if_not_empty;","fastcgi_param GATEWAY_INTERFACE CGI/1.1;","fastcgi_param SERVER_SOFTWARE nginx/$nginx_version;","fastcgi_param REMOTE_ADDR $remote_addr;","fastcgi_param REMOTE_PORT $remote_port;","fastcgi_param SERVER_ADDR $server_addr;","fastcgi_param SERVER_PORT $server_port;","fastcgi_param SERVER_NAME $server_name;","fastcgi_param REDIRECT_STATUS 200;","TS_CLOUD_FCGI_EOF","cat > /etc/nginx/nginx.conf <<'TS_CLOUD_NGINXCONF_EOF'","user www-data;","worker_processes auto;","pid /run/nginx.pid;","error_log /var/log/nginx/error.log;","events { worker_connections 1024; }","http {"," default_type application/octet-stream;"," types {"," text/html html htm;"," text/css css;"," application/javascript js;"," application/json json;"," image/svg+xml svg;"," image/png png;"," image/jpeg jpg jpeg;"," image/gif gif;"," image/x-icon ico;"," image/webp webp;"," font/woff2 woff2;"," font/woff woff;"," text/plain txt;"," }"," access_log /var/log/nginx/access.log;"," sendfile on;"," tcp_nopush on;"," keepalive_timeout 65;"," server_tokens off;"," client_max_body_size 100m;"," client_body_temp_path /var/lib/nginx/body;"," proxy_temp_path /var/lib/nginx/proxy;"," fastcgi_temp_path /var/lib/nginx/fastcgi;"," uwsgi_temp_path /var/lib/nginx/uwsgi;"," scgi_temp_path /var/lib/nginx/scgi;"," server {"," listen 80 default_server;"," listen [::]:80 default_server;"," server_name _;"," return 444;"," }"," include /etc/nginx/sites-enabled/*;","}","TS_CLOUD_NGINXCONF_EOF","cat > /etc/systemd/system/ts-cloud-nginx.service <<'TS_CLOUD_NGINXUNIT_EOF'","[Unit]","Description=ts-cloud nginx (pantry)","After=network.target","","[Service]","Type=simple",`ExecStartPre=${He} -t`,`ExecStart=${He} -g 'daemon off;'`,`ExecReload=${He} -s reload`,"Restart=always","RestartSec=3","","[Install]","WantedBy=multi-user.target","TS_CLOUD_NGINXUNIT_EOF","systemctl daemon-reload","systemctl enable ts-cloud-nginx","ls /etc/nginx/sites-enabled/* >/dev/null 2>&1 && systemctl restart ts-cloud-nginx || true"]}import{readFileSync as Ca}from"node:fs";function Pa(e){if(typeof e==="string")return e;if(!/^\/[\w./-]+$/.test(e.envFile)||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e.variable))throw Error("Invalid notification env-file reference");let r=Ca(e.envFile,"utf8").split(/\r?\n/).map((n)=>n.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/)).find((n)=>n?.[1]===e.variable)?.[2];if(!r)throw Error(`Notification variable ${e.variable} is missing`);return r.replace(/^(['"])(.*)\1$/,"$2")}function Et(e,t){return!e.events||e.events.includes(t)}async function cn(e,t,r,n={}){if(!e)return[];let s=n.fetchImpl??globalThis.fetch,i=[],a=[],c=async(u,f)=>{try{return await s(Pa(u),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f)})}catch{return}};if(e.slack?.webhookUrl&&Et(e,t))i.push("slack"),a.push(c(e.slack.webhookUrl,{text:r}));if(e.discord?.webhookUrl&&Et(e,t))i.push("discord"),a.push(c(e.discord.webhookUrl,{content:r}));if(e.telegram?.botToken&&e.telegram.chatId&&Et(e,t)){i.push("telegram");let u=`https://api.telegram.org/bot${e.telegram.botToken}/sendMessage`;a.push(c(u,{chat_id:e.telegram.chatId,text:r}))}if(e.webhook?.url&&Et(e,t))if(i.push("webhook"),(e.webhook.method||"POST")==="GET"){let u=e.webhook.url.includes("?")?"&":"?",f=`${e.webhook.url}${u}event=${encodeURIComponent(t)}&message=${encodeURIComponent(r)}`;a.push(s(f,{method:"GET"}).catch(()=>{return}))}else a.push(c(e.webhook.url,{event:t,message:r}));if(e.email?.to&&Et(e,t))i.push("email"),a.push(Ea(e.email,t,r));return await Promise.all(a),i}async function Ea(e,t,r){try{let n=await import("./chunk-v34tdcwv.js");await n.email.send({to:e.to,from:e.from,subject:`[ts-cloud] ${t}`,text:r})}catch{}}function ps(e,t){return t??e}function We(e){if(!e)return[];let t=(s)=>"'"+s.replaceAll("'",`'"'"'`)+"'",r=(s)=>{if(typeof s==="string")return t(s);if(!/^\/[\w./-]+$/.test(s.envFile)||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(s.variable))throw Error("Invalid notification env-file reference");return'"$(read_env '+t(s.envFile)+" "+t(s.variable)+')"'},n=[];for(let[s,i]of[["slack","text"],["discord","content"]]){let a=e[s]?.webhookUrl;if(a)n.push("URL="+r(a),'post "$URL" '+t(i))}if(e.telegram?.botToken&&e.telegram.chatId)n.push("curl -fsS --max-time 30 -X POST "+t("https://api.telegram.org/bot"+e.telegram.botToken+"/sendMessage")+" --data-urlencode "+t("chat_id="+e.telegram.chatId)+' --data-urlencode "text=$MSG" >/dev/null || FAILED=1');if(e.webhook?.url)if(e.webhook.method==="GET")n.push("curl -fsS --max-time 30 -G "+t(e.webhook.url)+' --data-urlencode "message=$MSG" >/dev/null || FAILED=1');else n.push("post "+t(e.webhook.url)+" message");if(!n.length)return[];return["cat > /usr/local/bin/ts-cloud-notify.new <<'TS_CLOUD_NOTIFY_EOF'","#!/bin/bash","set -uo pipefail",'MSG="${1:-}"; FAILED=0',String.raw`read_env(){ awk -v key="$2" '$0 ~ "^[[:space:]]*(export[[:space:]]+)?" key "[[:space:]]*=" { sub("^[^=]*=[[:space:]]*", ""); sub(/[\r[:space:]]+$/, ""); if (($0 ~ /^".*"$/) || ($0 ~ /^\047.*\047$/)) $0=substr($0,2,length($0)-2); print; exit }' "$1"; }`,String.raw`ESCAPED=$(printf %s "$MSG" | LC_ALL=C awk 'BEGIN{ORS=""; for(i=1;i<32;i++) esc[sprintf("%c",i)]=sprintf("\\u%04x",i)} {if(NR>1) printf "\\n"; for(i=1;i<=length($0);i++){ c=substr($0,i,1); if(c=="\\") printf "\\\\"; else if(c=="\"") printf "\\\""; else if(c in esc) printf "%s",esc[c]; else printf "%s",c }}')`,String.raw`post(){ if [ -z "$1" ]; then FAILED=1; return; fi; curl -fsS --max-time 30 -X POST -H 'Content-Type: application/json' --data "{\"$2\":\"$ESCAPED\"}" "$1" >/dev/null || FAILED=1; }`,...n,'exit "$FAILED"',"TS_CLOUD_NOTIFY_EOF","chmod 0700 /usr/local/bin/ts-cloud-notify.new","mv -f /usr/local/bin/ts-cloud-notify.new /usr/local/bin/ts-cloud-notify"]}function it(e=[],t={}){let r=t.path??"/root/.ssh/authorized_keys",s=[`mkdir -p ${r.replace(/\/[^/]*$/,"")}`,`touch ${r}`,`sed -i '/^${ds("# >>> ts-cloud managed keys >>>")}$/,/^${ds("# <<< ts-cloud managed keys <<<")}$/d' ${r}`];if(e.length>0){let i=["# >>> ts-cloud managed keys >>>",...e.map((a)=>`${a.publicKey.trim()} ${a.name}`),"# <<< ts-cloud managed keys <<<"].join(`
|
|
26
|
+
`);s.push(`cat >> ${r} <<'TS_CLOUD_KEYS_EOF'`,i,"TS_CLOUD_KEYS_EOF",`chmod 600 ${r}`)}return s}function ds(e){return e.replace(/[.*[\]\\/^$]/g,"\\$&")}function fs(e,t){let r=`/tmp/ts-cloud-${e}.sh`,n=`TS_CLOUD_${e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}_EOF`;return[`cat > ${r} <<'${n}'`,t.replace(/\n$/,""),n,`chmod +x ${r}`,`bash ${r} || echo "ts-cloud: ${e} setup did not complete; continuing" >&2`,`rm -f ${r}`]}function gs(e,t){if(e===!1)return;if(e===!0||e===void 0)return t;return e}var ms={enabled:!0,ports:[80,443]},Ra={mode:"detection",paranoiaLevel:1};function Oa(e=!0,t=[]){let r=gs(e,ms);if(!r||r.enabled===!1)return[];let n=[...new Set([...r.ports??ms.ports??[],...t])].sort((s,i)=>s-i);return fs("ddos",Wi({...r,ports:n}))}function Da(e=!0){let t=gs(e,Ra);if(!t||t.mode==="off")return[];return fs("waf",ki(t))}function hs(e={},t=[]){return[...Oa(e.ddos,t),...Da(e.waf)]}function xa(e){return`${e}-sftp`}function Ss(e){return e.port??2222}function Ia(e){let t=e.sftp.storage;if(t?.type==="efs"&&t.path)return t.path;return`/var/sftp/${e.slug}`}function at(e){return`'${e.split("'").join("'\\''")}'`}function vs(e,t){if(t==="aws")return;let r=e.storage;if(r?.type==="s3"||!r&&!!e.bucket)throw Error(`sftp: bucket-backed storage is only available on the aws provider (Transfer Family). On ${t}, use storage: { type: 'efs' } to serve a directory on the server.`);for(let[s,i]of Object.entries(e.users))if(!i.sshPublicKeys?.length)throw Error(`sftp: user ${s} needs at least one SSH public key`)}function _s(e){let{slug:t,sftp:r}=e,n=xa(t),s=Ia(e),i=Ss(r),a="/etc/ts-sftp/host_key",c="/etc/ts-sftp/users",u=r.serviceUser??"ts-sftp",f=[`# --- ts-sftp (${n}) ---`,`id -u ${u} >/dev/null 2>&1 || useradd --system --home-dir ${at(s)} --shell /usr/sbin/nologin ${u}`,'export HOME="${HOME:-/root}"','command -v bun >/dev/null 2>&1 || (curl -fsSL https://bun.sh/install | bash && ln -sf "$HOME/.bun/bin/bun" /usr/local/bin/bun)',`mkdir -p ${at(s)} /etc/ts-sftp /etc/ts-sftp/users /opt/ts-sftp`,"chmod 750 /etc/ts-sftp",`cd /opt/ts-sftp && [ -f package.json ] || printf '{"name":"ts-sftp-host","private":true}' > package.json`,`cd /opt/ts-sftp && bun add ts-sftp@${r.version??"latest"} --no-save --production || bun add ts-sftp@${r.version??"latest"}`,`[ -f /etc/ts-sftp/host_key ] || bun /opt/ts-sftp/node_modules/ts-sftp/dist/bin/cli.js keygen --out /etc/ts-sftp/host_key --comment ${at(`${t}-sftp`)}`,"chmod 600 /etc/ts-sftp/host_key",'BUN_REAL=$(readlink -f "$(command -v bun)")','case "$BUN_REAL" in /root/*) install -m 0755 "$BUN_REAL" /usr/local/bin/ts-sftp-bun; BUN_BIN=/usr/local/bin/ts-sftp-bun;; *) BUN_BIN="$BUN_REAL";; esac'],h=[];for(let[_,S]of Object.entries(r.users)){let v=(S.homeDirectory??_).replace(/^\/+|\/+$/g,"");if(!v||v.split("/").includes(".."))throw Error(`sftp: invalid homeDirectory for user ${_}`);let y=`/etc/ts-sftp/users/${_}.pub`;f.push(`mkdir -p ${at(`${s}/${v}`)}`,`printf '%s\\n' ${at(S.sshPublicKeys.join(`
|
|
27
|
+
`))} > ${y}`,`chmod 644 ${y}`),h.push(`--user ${_}:${y}`)}return f.push(`chown -R ${u}:${u} ${at(s)} /etc/ts-sftp`,`cat > /etc/systemd/system/${n}.service <<TSCLOUD_SFTP_UNIT`,"[Unit]","Description=ts-sftp file transfer server","After=network.target","","[Service]",`User=${u}`,`ExecStart=$BUN_BIN /opt/ts-sftp/node_modules/ts-sftp/dist/bin/cli.js serve --root ${s} --host-key /etc/ts-sftp/host_key --port ${i}${r.readOnly?" --read-only":""} ${h.join(" ")}`,"Restart=always","RestartSec=2","NoNewPrivileges=true","PrivateTmp=true","ProtectSystem=strict",`ReadWritePaths=${s}`,"","[Install]","WantedBy=multi-user.target","TSCLOUD_SFTP_UNIT","systemctl daemon-reload",`systemctl enable ${n}.service`,`systemctl restart ${n}.service`),f}function ys(e){return e?[Ss(e)]:[]}var Aa=[80,443];function sr(e={}){if(e.enabled===!1)return[];let t=[...new Set([...Aa,...e.allowedPorts||[]])].filter((n)=>Number.isInteger(n)&&n>=1&&n<=65535).sort((n,s)=>n-s),r=["export DEBIAN_FRONTEND=noninteractive","command -v ufw >/dev/null 2>&1 || apt-get install -y ufw","ufw --force reset","ufw default deny incoming","ufw default allow outgoing","ufw allow OpenSSH"];for(let n of t)r.push(`ufw allow ${n}/tcp`);return r.push("ufw --force enable"),r}function Ye(e,t){let r=e.infrastructure?.compute??{},n=r.runtime==="php"||!!r.php,s=C(e,{environment:t?.environment}),i=n||!!r.managedServices,a=i?mt():[],c=!j({...r,proxy:w(e,{environment:t?.environment})}),u=n?[...a,...nr({versions:r.php?.versions,default:r.php?.default,extensions:r.php?.extensions,installNginx:c,optimizeForProduction:r.php?.optimizeForProduction,ini:r.php?.ini}),...c?an():[]]:void 0,f=[],h=g(e);if(!n&&i)f.push(...a);if(f.push(...We(e.notifications)),r.managedServices)f.push(...Qt(r.managedServices,{mail:s.enabled?s:void 0}),...ot(h,r.managedServices));let _=e.infrastructure?.sftp;if(_)vs(_,be(e)),f.push(..._s({slug:e.project.slug,sftp:_}));let S=r.firewall??(n?{enabled:!0}:{enabled:!1}),v=Xe(s);if(f.push(...sr(v.length>0?{...S,allowedPorts:[...S.allowedPorts??[],...v]}:S)),f.push(...hs({ddos:r.ddos,waf:r.waf},[...r.firewall?.allowedPorts??[],...v])),f.push(...Ue(r.autoUpdates??n)),f.push(...eo(r.appUpdates)),f.push(...xe(r.monitoring??n)),f.push(...it(r.sshKeys,{path:t?.authorizedKeysPath})),r.backups?.enabled)f.push(...rr({database:h,backups:r.backups}));return{runtime:r.runtime||"bun",runtimeVersion:r.runtimeVersion||"latest",phpBox:n,phpProvision:u,servicesProvision:f.length>0?f:void 0}}function M(e={}){let{runtime:t="bun",runtimeVersion:r="latest",systemPackages:n=[],database:s,phpProvision:i,servicesProvision:a,caddyfile:c,rpxProvision:u,baked:f=!1,swapGb:h=2}=e,_=new Set(n);if(s==="sqlite")_.add("sqlite3");else if(s==="mysql")_.add("mysql-client");else if(s==="postgres")_.add("postgresql-client");let S=`#!/bin/bash
|
|
28
28
|
set -euo pipefail
|
|
29
|
-
`,
|
|
29
|
+
`,v=Math.floor(h);if(v>0)S+=`
|
|
30
30
|
# Swap: a swapless box under memory pressure lets the kernel OOM killer choose
|
|
31
31
|
# victims box-wide (the gateway, a tenant app, postgres). A modest swapfile
|
|
32
32
|
# with low swappiness gives the kernel headroom without hurting responsiveness.
|
|
33
33
|
if ! swapon --show=NAME --noheadings 2>/dev/null | grep -qx '/swapfile'; then
|
|
34
34
|
if [ ! -f /swapfile ]; then
|
|
35
|
-
fallocate -l ${
|
|
35
|
+
fallocate -l ${v}G /swapfile || dd if=/dev/zero of=/swapfile bs=1M count=${v*1024} status=none
|
|
36
36
|
chmod 600 /swapfile
|
|
37
37
|
mkswap /swapfile >/dev/null
|
|
38
38
|
fi
|
|
@@ -41,20 +41,20 @@ fi
|
|
|
41
41
|
grep -qE '^/swapfile\\s' /etc/fstab || echo '/swapfile none swap sw 0 0' >> /etc/fstab
|
|
42
42
|
echo 'vm.swappiness=10' > /etc/sysctl.d/99-ts-cloud-swap.conf
|
|
43
43
|
sysctl -w vm.swappiness=10 >/dev/null
|
|
44
|
-
`;if(!
|
|
44
|
+
`;if(!f){if(S+=`
|
|
45
45
|
export DEBIAN_FRONTEND=noninteractive
|
|
46
46
|
apt-get update -y
|
|
47
47
|
apt-get upgrade -y
|
|
48
48
|
apt-get install -y curl tar gzip unzip git ca-certificates
|
|
49
|
-
`,
|
|
50
|
-
apt-get install -y ${[...
|
|
51
|
-
`;if(i&&i.length>0)
|
|
49
|
+
`,_.size>0)S+=`
|
|
50
|
+
apt-get install -y ${[..._].join(" ")}
|
|
51
|
+
`;if(i&&i.length>0)S+=`
|
|
52
52
|
${i.join(`
|
|
53
53
|
`)}
|
|
54
|
-
`;if(a&&a.length>0)
|
|
54
|
+
`;if(a&&a.length>0)S+=`
|
|
55
55
|
${a.join(`
|
|
56
56
|
`)}
|
|
57
|
-
`;if(t==="bun")
|
|
57
|
+
`;if(t==="bun")S+=`
|
|
58
58
|
# cloud-init runs this with \`set -u\` and NO $HOME set. bun's install.sh
|
|
59
59
|
# dereferences $HOME even when BUN_INSTALL is set, so without this the install
|
|
60
60
|
# aborts with "HOME: unbound variable" and /usr/local/bin/bun never appears —
|
|
@@ -76,17 +76,17 @@ curl -fsSL https://bun.sh/install | bash${r==="latest"?"":` -s "bun-v${r}"`}
|
|
|
76
76
|
ln -sf /root/.bun/bin/bun /usr/local/bin/bun
|
|
77
77
|
echo 'export BUN_INSTALL="/root/.bun"' > /etc/profile.d/bun.sh
|
|
78
78
|
echo 'export PATH="$BUN_INSTALL/bin:$PATH"' >> /etc/profile.d/bun.sh
|
|
79
|
-
`;else if(t==="node"){let y=r==="latest"||!r?"20":r.split(".")[0];
|
|
79
|
+
`;else if(t==="node"){let y=r==="latest"||!r?"20":r.split(".")[0];S+=`
|
|
80
80
|
curl -fsSL https://deb.nodesource.com/setup_${y}.x | bash -
|
|
81
81
|
apt-get install -y nodejs
|
|
82
82
|
ln -sf /usr/bin/node /usr/local/bin/node
|
|
83
83
|
ln -sf /usr/bin/npm /usr/local/bin/npm
|
|
84
|
-
`}else if(t==="deno")
|
|
84
|
+
`}else if(t==="deno")S+=`
|
|
85
85
|
curl -fsSL https://deno.land/install.sh | sh
|
|
86
86
|
ln -sf /root/.deno/bin/deno /usr/local/bin/deno
|
|
87
|
-
`}if(
|
|
87
|
+
`}if(S+=`
|
|
88
88
|
mkdir -p /var/www /var/ts-cloud/staging /var/ts-cloud/releases
|
|
89
|
-
`,c)
|
|
89
|
+
`,c)S+=`
|
|
90
90
|
ARCH=$(uname -m | sed 's/x86_64/amd64/;s/aarch64/arm64/')
|
|
91
91
|
curl -fsSL "https://caddyserver.com/api/download?os=linux&arch=\${ARCH}" -o /usr/local/bin/caddy
|
|
92
92
|
chmod +x /usr/local/bin/caddy
|
|
@@ -129,41 +129,41 @@ CADDY_CONFIG_EOF
|
|
|
129
129
|
systemctl daemon-reload
|
|
130
130
|
systemctl enable caddy
|
|
131
131
|
systemctl start caddy
|
|
132
|
-
`;if(u&&u.length>0){let y=u[0]==="set -euo pipefail"?u.slice(1):u;
|
|
132
|
+
`;if(u&&u.length>0){let y=u[0]==="set -euo pipefail"?u.slice(1):u;S+=`
|
|
133
133
|
${y.join(`
|
|
134
134
|
`)}
|
|
135
|
-
`}return
|
|
135
|
+
`}return S+=`
|
|
136
136
|
echo "ts-cloud bootstrap complete — instance is ready for site deploys"
|
|
137
|
-
`,
|
|
138
|
-
`),"TS_CLOUD_BASH_EOF"]}async runRemoteDeploy(e){let t=this.region,r=new Be(t);if(e.targets.length>0){let s=await r.sendCommand({InstanceIds:e.targets.map((i)=>i.id),DocumentName:"AWS-RunShellScript",Parameters:{commands:this.bashWrap(e.commands)},TimeoutSeconds:e.timeoutSeconds||600,Comment:e.comment});if(!s.CommandId)return{success:!1,instanceCount:0,perInstance:[],error:"Failed to send SSM command"};return this.pollSsmCommand(r,s.CommandId,e.targets.length,((e.timeoutSeconds||600)+30)*1000)}if(!e.tags||Object.keys(e.tags).length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets or tags provided for AWS deploy"};let n=await r.sendCommandByTags({tags:e.tags,commands:this.bashWrap(e.commands),timeoutSeconds:e.timeoutSeconds||600,comment:e.comment});return{success:n.success,instanceCount:n.instanceCount,perInstance:n.perInstance.map((s)=>({instanceId:s.instanceId,status:s.status,output:s.output,error:s.error})),error:n.error}}async pollSsmCommand(e,t,r,n=600000){let i=Date.now(),a=new Set(["Success","Failed","Cancelled","TimedOut"]),c=[];while(Date.now()-i<n){await new Promise((h)=>setTimeout(h,3000));try{if(c=await e.listCommandInvocations({CommandId:t,Details:!0}),c.length>=r&&c.every((
|
|
139
|
-
`,{mode:420}),r.renameSync(K,T)},
|
|
137
|
+
`,S}var $s="/aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id";function bs(e,t){let r=[{port:22,protocol:"tcp",cidr:"0.0.0.0/0"},{port:80,protocol:"tcp",cidr:"0.0.0.0/0"},{port:443,protocol:"tcp",cidr:"0.0.0.0/0"}],n=new Set;for(let s of Object.values(e.sites||{}))if(s&&typeof s.port==="number"&&![22,80,443].includes(s.port))n.add(s.port);for(let s of Xe(C(e,{environment:t})))n.add(s);for(let s of n)r.push({port:s,protocol:"tcp",cidr:"0.0.0.0/0"});return r}function Ts(e,t){let r={...e.infrastructure?.compute,proxy:w(e,{environment:t})},n=Ye(e,{environment:t}),s=r.proxy?.engine==="rpx"?G({proxy:r.proxy,config:B(e.sites??{},{proxy:r.proxy,slug:e.project.slug,mail:C(e,{environment:t})}),slug:e.project.slug,bunBin:r.runtime==="node"||r.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0;return M({runtime:n.runtime,runtimeVersion:n.runtimeVersion,systemPackages:r.systemPackages,database:e.infrastructure?.database,phpProvision:n.phpProvision,servicesProvision:n.servicesProvision,rpxProvision:s,baked:r.bakedImage===!0,swapGb:r.swapGb})}function ws(e){return Buffer.from(e,"utf8").toString("base64")}function Cs(e){return e.infrastructure?.compute?.image??null}function or(e,t){return`${e}-${t}-app-sg`}function un(e,t,r="app"){return[{Key:"Project",Value:e},{Key:"Environment",Value:t},{Key:"Role",Value:r},{Key:"ManagedBy",Value:"ts-cloud"}]}function La(e,t,r){if(!e?.length)return!1;let n=(s)=>e.find((i)=>i.Key===s)?.Value;return n("Project")===t&&n("Environment")===r}function Ps(e,t){let r=or(t.slug,t.environment);return e.find((n)=>{if(n.GroupName!==r)return!1;if(t.vpcId&&n.VpcId&&n.VpcId!==t.vpcId)return!1;if(!!n.Tags?.some((i)=>i.Key==="Project"))return La(n.Tags,t.slug,t.environment);return!!t.vpcId&&n.VpcId===t.vpcId})}function Ha(e){try{let t=Es(Ua(process.cwd(),"storage/cloud/state",`${e}.json`),"utf8"),r=JSON.parse(t);return typeof r.instanceId==="string"&&r.instanceId.length>0?r.instanceId:null}catch{return null}}class _r{name="aws";usesCloudFormation=!0;region;ec2Client;cfnClient;constructor(e={}){this.region=e.region||"us-east-1",this.ec2Client=e.ec2Client??((t)=>new Gr(t)),this.cfnClient=e.cfnClient??((t)=>new A(t))}resolveRegion(e){return e.project.region||this.region}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e,n=this.resolveRegion(t),s=t.project.slug,i=t.infrastructure?.compute;if(!i)throw Error("infrastructure.compute is required to provision AWS compute");let a=this.ec2Client(n),c=await this.findComputeTargets({slug:s,environment:r,role:"app",region:n});if(c.length>0){let V=c[0];return{appInstanceId:V.id,appPublicIp:V.publicIp,appPublicIpv6:V.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}let u=Cs(t);if(!u){if(u=(await new Be(n).getParameter({Name:$s})).Parameter?.Value??null,!u)throw Error("Could not resolve the Ubuntu 24.04 AMI from SSM")}let f=await a.describeVpcs(),h=(f.Vpcs||[]).find((V)=>V.IsDefault)||(f.Vpcs||[])[0];if(!h?.VpcId)throw Error("No VPC found to launch the instance into");let _=(await a.describeSubnets({Filters:[{Name:"vpc-id",Values:[h.VpcId]}]})).Subnets||[],S=_.find((V)=>V.MapPublicIpOnLaunch)||_[0],v=S?.SubnetId;if(!S?.MapPublicIpOnLaunch)console.warn("ts-cloud: no public subnet found; the instance may not get a public IP (deploys/SSL need one).");let y=or(s,r),I=(await a.describeSecurityGroups({Filters:[{Name:"group-name",Values:[y]},{Name:"vpc-id",Values:[h.VpcId]}]})).SecurityGroups?.[0]?.GroupId;if(!I)I=(await a.createSecurityGroup({GroupName:y,Description:`ts-cloud ${s}/${r} app`,VpcId:h.VpcId,TagSpecifications:[{ResourceType:"security-group",Tags:un(s,r)}]})).GroupId;let D=bs(t,r);await a.authorizeSecurityGroupIngress({GroupId:I,IpPermissions:D.map((V)=>({IpProtocol:V.protocol,FromPort:V.port,ToPort:V.port,IpRanges:[{CidrIp:V.cidr}]}))}).catch((V)=>{if(!/InvalidPermission\.Duplicate/.test(V instanceof Error?V.message:""))throw V});let H=ws(Ts(t,r)),R=i.server?.instanceType||"t3.small",W=(await a.runInstances({ImageId:u,InstanceType:R,MinCount:1,MaxCount:1,SecurityGroupIds:I?[I]:void 0,SubnetId:v,UserData:H,IamInstanceProfile:i.server?.iamInstanceProfile?{Name:i.server.iamInstanceProfile}:void 0,TagSpecifications:[{ResourceType:"instance",Tags:[{Key:"Name",Value:`${s}-${r}-app`},...un(s,r)]}]})).Instances?.[0]?.InstanceId;if(!W)throw Error("RunInstances did not return an instance id");let k=await a.waitForInstanceState(W,"running");if(!k)throw Error(`Instance ${W} did not reach 'running' before timeout`);return{appInstanceId:W,appPublicIp:k.PublicIpAddress,appPublicIpv6:De(k.Ipv6Address),sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}async destroyCompute(e){let{config:t,environment:r}=e,n=t.project.slug,s=this.resolveRegion(t),i=this.ec2Client(s),a=[],u=(await this.findComputeTargets({slug:n,environment:r,role:"app",region:s})).map((y)=>y.id),f;if(u.length>0)f=(await i.describeInstances({InstanceIds:u}).catch(()=>({Reservations:[]}))).Reservations?.flatMap((b)=>b.Instances??[]).find((b)=>b.VpcId)?.VpcId;if(u.length>0)await i.terminateInstances(u),a.push(...u.map((y)=>`instance ${y}`)),await Promise.all(u.map((y)=>i.waitForInstanceState(y,"terminated").catch(()=>{return})));let h=or(n,r),_=[{Name:"group-name",Values:[h]}];if(f)_.push({Name:"vpc-id",Values:[f]});let S=await i.describeSecurityGroups({Filters:_}).catch(()=>({SecurityGroups:[]})),v=Ps(S.SecurityGroups??[],{slug:n,environment:r,vpcId:f});if(v?.GroupId)for(let y=0;y<10;y++)try{await i.deleteSecurityGroup(v.GroupId),a.push(`security group ${h}`);break}catch{await new Promise((b)=>setTimeout(b,3000))}return{destroyed:a}}async getComputeOutputs(e){let t=this.resolveRegion(e.config),r=m(e.config,e.environment),n=this.cfnClient(t);try{let s=await n.getStackOutputs(r);return{deployBucketName:s.deployBucketName,appInstanceId:s.appInstanceId,appPublicIp:s.appPublicIp,sshUser:"ec2-user"}}catch(s){if(!/does not exist|ValidationError/i.test(s instanceof Error?s.message:""))throw s;let a=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",region:t}))[0];return{appInstanceId:a?.id,appPublicIp:a?.publicIp,appPublicIpv6:a?.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}}async uploadRelease(e){let t=this.resolveRegion(e.config),n=(await this.getComputeOutputs({config:e.config,environment:e.environment})).deployBucketName;if(!n)throw Error("No deployBucketName in stack outputs. Re-deploy infrastructure to add the staging bucket.");return await new o(t).putObject({bucket:n,key:e.remoteKey,body:Es(e.localPath),contentType:"application/gzip"}),{artifactRef:`s3://${n}/${e.remoteKey}`}}async findComputeTargets(e){let t=e.region??this.region,r=this.ec2Client(t),n=[{Name:"tag:Project",Values:[e.slug]},{Name:"tag:Environment",Values:[e.environment]},{Name:"tag:Role",Values:[e.role||"app"]},{Name:"instance-state-name",Values:["running","pending"]}],s=await r.describeInstances({Filters:n}),i=this.reservationsToTargets(s.Reservations);if(i.length>0||(e.role||"app")!=="app")return i;let a=e.stackName??`${e.slug}-${e.environment}`,c=Ha(a);if(!c)try{c=(await this.cfnClient(t).getStackOutputs(a)).appInstanceId??null}catch{c=null}if(!c)return[];try{let u=await r.describeInstances({InstanceIds:[c],Filters:[{Name:"instance-state-name",Values:["running","pending"]}]});return this.reservationsToTargets(u.Reservations)}catch{return[]}}reservationsToTargets(e){let t=[];for(let r of e||[])for(let n of r.Instances||[]){if(!n.InstanceId)continue;let s=n.Tags?.find((i)=>i.Key==="Name")?.Value;t.push({id:n.InstanceId,name:s,publicIp:n.PublicIpAddress,publicIpv6:De(n.Ipv6Address),privateIp:n.PrivateIpAddress,status:n.State?.Name})}return t}bashWrap(e){return["bash <<'TS_CLOUD_BASH_EOF'",e.join(`
|
|
138
|
+
`),"TS_CLOUD_BASH_EOF"]}async runRemoteDeploy(e){let t=this.region,r=new Be(t);if(e.targets.length>0){let s=await r.sendCommand({InstanceIds:e.targets.map((i)=>i.id),DocumentName:"AWS-RunShellScript",Parameters:{commands:this.bashWrap(e.commands)},TimeoutSeconds:e.timeoutSeconds||600,Comment:e.comment});if(!s.CommandId)return{success:!1,instanceCount:0,perInstance:[],error:"Failed to send SSM command"};return this.pollSsmCommand(r,s.CommandId,e.targets.length,((e.timeoutSeconds||600)+30)*1000)}if(!e.tags||Object.keys(e.tags).length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets or tags provided for AWS deploy"};let n=await r.sendCommandByTags({tags:e.tags,commands:this.bashWrap(e.commands),timeoutSeconds:e.timeoutSeconds||600,comment:e.comment});return{success:n.success,instanceCount:n.instanceCount,perInstance:n.perInstance.map((s)=>({instanceId:s.instanceId,status:s.status,output:s.output,error:s.error})),error:n.error}}async pollSsmCommand(e,t,r,n=600000){let i=Date.now(),a=new Set(["Success","Failed","Cancelled","TimedOut"]),c=[];while(Date.now()-i<n){await new Promise((h)=>setTimeout(h,3000));try{if(c=await e.listCommandInvocations({CommandId:t,Details:!0}),c.length>=r&&c.every((_)=>a.has(_.Status||"")))break}catch{}}let u=c.map((h)=>({instanceId:h.InstanceId,status:h.Status||"Unknown",output:h.StandardOutputContent,error:h.StandardErrorContent})),f=u.length>0&&u.every((h)=>h.status==="Success");return{success:f,instanceCount:u.length,perInstance:u,error:f?void 0:Jt(u,"One or more SSM command invocations failed")}}}import{execFileSync as Tc,execSync as Ws}from"node:child_process";import{createHash as wc,randomUUID as Ys}from"node:crypto";import{createReadStream as Cc,existsSync as Pc,readFileSync as Ec}from"node:fs";async function Rs(e,t){let r=await import("node:fs"),n=await import("node:path"),s=await import("node:child_process"),i="/etc/ts-cloud/compute-storage.json",a="/var/lib/ts-cloud/compute-storage-state.json",c="/run/ts-cloud-root-web",u=t[0]??"status";if(!["plan","status","check","apply","ensure-site","reclaim"].includes(u))throw Error(`Unknown compute storage command: ${u}`);let f=(T,O)=>{try{return JSON.parse(r.readFileSync(T,"utf8"))}catch(K){if(K.code==="ENOENT")return O;throw K}},h=(T,O)=>{r.mkdirSync(n.dirname(T),{recursive:!0});let K=`${T}.${process.pid}.tmp`;r.writeFileSync(K,`${JSON.stringify(O,null,2)}
|
|
139
|
+
`,{mode:420}),r.renameSync(K,T)},_=(T,O)=>s.execFileSync(T,O,{encoding:"utf8",maxBuffer:16777216}),S=(T,O)=>{let K=s.spawnSync(T,O,{encoding:"utf8"});return K.status===0?K.stdout.trim():""},v=(T)=>!!S("findmnt",["-n","--mountpoint",T]),y=(T,O)=>{try{let K=r.statSync(T),E=r.statSync(O);return K.dev===E.dev&&K.ino===E.ino}catch{return!1}},b=f("/var/lib/ts-cloud/compute-storage-state.json",{entries:[]}),I=e.deploymentStorage,D=e.volumes.find((T)=>T.key===I?.volume),H=(T,O)=>{if(!D)return[];let K=[];for(let E of r.readdirSync(e.webRoot,{withFileTypes:!0})){if(!E.isDirectory()||E.isSymbolicLink())continue;let q=n.join(e.webRoot,E.name);if(T&&q!==T&&q!==n.join(e.webRoot,`${O}-shared`))continue;for(let N of["releases",...I?.includeBackups===!1?[]:["backups"]]){let Y=n.join(q,N);if(!r.existsSync(Y)||!r.lstatSync(Y).isDirectory())continue;K.push({source:Y,destination:n.join(D.mountPath,N,E.name)})}}return K},R=(T)=>{try{return v(T.mountPath)&&r.statSync(T.mountPath).dev===r.statSync(T.device).rdev}catch{return!1}},x=(T)=>{let O=r.statfsSync(T),K=(O.blocks-O.bfree)*O.bsize,E=O.bavail*O.bsize;return{path:T,sizeBytes:O.blocks*O.bsize,usedBytes:K,availableBytes:E,usedPercent:Math.ceil(100*K/(K+E))}},W=()=>{let T=[],O=[x("/")];for(let E of e.volumes)if(!R(E))T.push(`missing or incorrect volume mount: ${E.mountPath}`);else O.push(x(E.mountPath));for(let E of b.entries)if(!v(E.source)||!y(E.source,E.destination))T.push(`missing deployment mount: ${E.source}`);let K=new Set(b.entries.map((E)=>E.source));for(let E of H())if(!K.has(E.source))T.push(`deployment needs volume placement: ${E.source}`);return{timestamp:new Date().toISOString(),volumes:e.volumes.map((E)=>({key:E.key,name:E.name,id:E.id,size:E.size,mountPath:E.mountPath})),disks:O,mounts:b.entries.length,problems:T}};if(u==="plan")return console.log(JSON.stringify({volumes:e.volumes,entries:H(),state:b},null,2));if(u==="status"||u==="check"){let T=W();if(u==="check"){h("/var/lib/ts-cloud/compute-storage-status.json",T);let O="/var/lib/ts-cloud/compute-storage-alert.json",K=f(O,{problems:[]});if(JSON.stringify(K.problems)!==JSON.stringify(T.problems)){let E=T.problems.join("; ")||"all configured mounts are healthy",q=`${T.problems.length?"Storage alert":"Storage recovered"} on ${S("hostname",[])}: ${E}`;_("/usr/local/bin/ts-cloud-notify",[q.length>1800?`${q.slice(0,1600)}... Full report: /var/lib/ts-cloud/compute-storage-status.json`:q])}h(O,{problems:T.problems,timestamp:T.timestamp})}if(console.log(JSON.stringify(T)),T.problems.length)process.exitCode=1;return T}if(process.getuid?.()!==0)throw Error("Compute storage changes require root");let k=()=>{let E=r.readFileSync("/etc/fstab","utf8");if(!r.existsSync("/etc/fstab.before-ts-cloud-storage"))r.copyFileSync("/etc/fstab","/etc/fstab.before-ts-cloud-storage");let q=[];for(let X of e.volumes){let J=_("blkid",["-s","UUID","-o","value",X.device]).trim();if(!J)throw Error(`Volume ${X.name} has no filesystem UUID`);q.push(`UUID=${J} ${X.mountPath} ext4 defaults,noatime,nodev,nosuid,nofail,x-systemd.device-timeout=30s 0 2`)}for(let X of b.entries)q.push(`${X.destination} ${X.source} none bind,nofail,x-systemd.requires-mounts-for=${D.mountPath} 0 0`);let N=`# BEGIN ts-cloud compute storage
|
|
140
140
|
${q.join(`
|
|
141
141
|
`)}
|
|
142
142
|
# END ts-cloud compute storage`,Y;if(E.includes("# BEGIN ts-cloud compute storage")){let X=E.indexOf("# BEGIN ts-cloud compute storage"),J=E.indexOf("# END ts-cloud compute storage",X);if(J<0)throw Error("Incomplete managed storage block in fstab");Y=E.slice(0,X)+N+E.slice(J+30)}else Y=`${E.trimEnd()}
|
|
143
143
|
${N}
|
|
144
|
-
`;r.writeFileSync("/etc/fstab.ts-cloud-new",Y),r.renameSync("/etc/fstab.ts-cloud-new","/etc/fstab")},V=()=>{for(let T of e.volumes){if(!r.existsSync(T.device)||!r.statSync(T.device).isBlockDevice())throw Error(`Volume device missing: ${T.device}`);let O=
|
|
145
|
-
`).map((Y)=>Y.trim().split(/\s+/)[0]).filter(Boolean),O={};if(T.length){let Y=
|
|
144
|
+
`;r.writeFileSync("/etc/fstab.ts-cloud-new",Y),r.renameSync("/etc/fstab.ts-cloud-new","/etc/fstab")},V=()=>{for(let T of e.volumes){if(!r.existsSync(T.device)||!r.statSync(T.device).isBlockDevice())throw Error(`Volume device missing: ${T.device}`);let O=S("blkid",["-s","TYPE","-o","value",T.device]);if(!O){if(!T.allowFormat)throw Error(`Refusing to format adopted volume ${T.name}; no recognized filesystem`);_("mkfs.ext4",["-m","1",T.device]),O="ext4"}if(O!=="ext4")throw Error(`Refusing to replace ${O} filesystem on ${T.name}`);if(r.mkdirSync(T.mountPath,{recursive:!0}),v(T.mountPath)&&!R(T))throw Error(`Another filesystem occupies ${T.mountPath}`);if(!v(T.mountPath)&&r.readdirSync(T.mountPath).length)throw Error(`Refusing to hide existing files beneath ${T.mountPath}`);if(!v(T.mountPath))_("mount",["-o","noatime,nodev,nosuid",T.device,T.mountPath]);if(!R(T))throw Error(`Volume identity verification failed: ${T.name}`);_("resize2fs",[T.device]),T.allowFormat=!1}h("/etc/ts-cloud/compute-storage.json",e),k(),_("systemctl",["daemon-reload"])},{dlopen:te}=await import("bun:ffi"),ue=te("libc.so.6",{flock:{args:["i32","i32"],returns:"i32"}}),me=[],Z=(T)=>{r.mkdirSync(n.dirname(T),{recursive:!0});let O=r.openSync(T,r.constants.O_CREAT|r.constants.O_RDWR|r.constants.O_NOFOLLOW,384);if(ue.symbols.flock(O,2)!==0)throw r.closeSync(O),Error(`Could not acquire lock: ${T}`);me.push(O)},pe=()=>{let T=[];for(let O of r.readdirSync("/proc").filter((K)=>/^\d+$/.test(K))){let K=[];try{K=r.readdirSync(`/proc/${O}/fd`)}catch{continue}for(let E of["cwd","exe",...K.map((q)=>`fd/${q}`)]){let q=`/proc/${O}/${E}`;try{let N=r.readlinkSync(q);if(!N.startsWith(`${e.webRoot}/`)||!N.includes("/releases/"))continue;let Y=!1;if(E.startsWith("fd/")){let X=r.readFileSync(`/proc/${O}/fdinfo/${E.slice(3)}`,"utf8").match(/^flags:\s+(\d+)/m);Y=!!X&&(Number.parseInt(X[1],8)&3)!==0&&r.statSync(q).isFile()}T.push({file:N,write:Y,device:r.statSync(q).dev})}catch{}}}return T},ne=async(T,O)=>{r.mkdirSync(T.destination,{recursive:!0});let K=["rsync","-aHAXx","--numeric-ids","--delete",...O?["--checksum"]:[],`${T.source}/`,`${T.destination}/`],q=await Bun.spawn(K,{stdout:"inherit",stderr:"inherit"}).exited;if(q!==0&&!(q===24&&!O))throw Error(`rsync failed (${q}): ${T.source}`)},ee=async()=>{let T=_("systemctl",["list-units","--type=service","--state=running","--no-legend","--plain"]).split(`
|
|
145
|
+
`).map((Y)=>Y.trim().split(/\s+/)[0]).filter(Boolean),O={};if(T.length){let Y=_("systemctl",["show",...T,"-p","Id","-p","MainPID","-p","WorkingDirectory"]);for(let X of Y.split(`
|
|
146
146
|
|
|
147
147
|
`)){let J=Object.fromEntries(X.split(`
|
|
148
148
|
`).filter(Boolean).map((P)=>{let L=P.indexOf("=");return[P.slice(0,L),P.slice(L+1)]}));if(J.WorkingDirectory?.startsWith(`${e.webRoot}/`)||/^(?:mail|rpx-gateway|postgresql|mysql|redis)[@.]/.test(J.Id??""))O[J.Id]=Number(J.MainPID)}}let K=new Map;if(r.existsSync("/etc/rpx/sites.d"))for(let Y of r.readdirSync("/etc/rpx/sites.d").filter((X)=>X.endsWith(".json"))){let X=JSON.parse(r.readFileSync(n.join("/etc/rpx/sites.d",Y),"utf8"));for(let J of X.proxies??[]){if(typeof J.to!=="string"||!/^[a-zA-Z0-9.-]+$/.test(J.to))continue;let P=typeof J.path==="string"&&J.path.startsWith("/")?J.path:"/";K.set(`${J.to}${P}`,{domain:J.to,path:P})}}let E=[...K.values()],q=[],N=0;return await Promise.all(Array.from({length:Math.min(8,E.length)},async()=>{while(N<E.length){let Y=E[N++],X=Bun.spawn(["curl","-sS","--max-time","12","--output","/dev/null","--write-out","%{http_code}","--resolve",`${Y.domain}:443:127.0.0.1`,`https://${Y.domain}${Y.path}`],{stdout:"pipe",stderr:"pipe"}),[J,,P]=await Promise.all([new Response(X.stdout).text(),new Response(X.stderr).text(),X.exited]),L=Number(J);q.push({...Y,status:L,ok:P===0&&L>=200&&L<500})}})),{routes:q.sort((Y,X)=>`${Y.domain}${Y.path}`.localeCompare(`${X.domain}${X.path}`)),services:O}},ge=()=>{let T=[D.mountPath,...b.entries.map((K)=>K.source)],O=new Set(["rpx-gateway.service",...I?.dependentUnits??[]]);for(let K of r.readdirSync("/etc/systemd/system")){if(!K.endsWith(".service"))continue;try{if(r.readFileSync(`/etc/systemd/system/${K}`,"utf8").includes(e.webRoot))O.add(K)}catch{}}for(let K of O){let E=`/etc/systemd/system/${K}.d`;r.mkdirSync(E,{recursive:!0}),r.writeFileSync(`${E}/ts-cloud-storage.conf`,`[Unit]
|
|
149
149
|
RequiresMountsFor=${T.join(" ")}
|
|
150
|
-
`)}
|
|
151
|
-
`).at(-1)?.split(/\s+/)[0],L=r.statfsSync(D.mountPath);if(Number(P)>L.bavail*L.bsize)throw Error("Insufficient free volume capacity for a verified deployment copy")}if(!r.existsSync("/run/ts-cloud-root-web"))r.mkdirSync("/run/ts-cloud-root-web");if(!
|
|
152
|
-
await (${
|
|
153
|
-
`;return['command -v bun >/dev/null 2>&1 || { echo "Configured compute storage requires Bun on the host" >&2; exit 1; }',"install -d -m 0755 /etc/ts-cloud /usr/local/lib/ts-cloud /var/lib/ts-cloud",`printf %s ${
|
|
154
|
-
`)}function La(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}var or=["storage",".env"],Pt=4;function Ie(e){return`${e.replace(/\/+$/,"")}/.ts-cloud`}function Ua(e){return`${Ie(e)}/deploy-history.log`}function Ha(e,t){return`${Ie(e)}/deploys/${t}.log`}function Rs(e){return`${Ie(e)}/shared-paths`}function ir(e){return`${e.shared}/stx-images`}function Xt(e,t){let r=e.replace(/\/+$/,"");return{base:r,releases:`${r}/releases`,shared:`${r}/shared`,current:`${r}/current`,release:`${r}/releases/${t}`}}function Os(e){let t=e.split("/").pop()||e;if(t===".env"||t.startsWith(".env."))return!0;return/\.[a-z0-9]+$/i.test(t)}function an(e){return typeof e==="string"?e:e.path}function Ds(e){let t=new Map;for(let r of e)t.set(an(r),r);return[...t.values()]}function xs(e,t){if(typeof t==="string")return{path:t,target:`${e.shared}/${t}`,seed:!0};return{path:t.path,target:t.target??`${e.shared}/${t.path}`,seed:t.seed!==!1}}function ka(e){return["ts_cloud_adopt_shared() {",' TS_CLOUD_SP="$1"',' TS_CLOUD_DST="$2"',` TS_CLOUD_SRC="${e.current}/$TS_CLOUD_SP"`,' if [ -e "$TS_CLOUD_DST" ]; then return 0; fi',' if [ -L "$TS_CLOUD_SRC" ] || [ ! -e "$TS_CLOUD_SRC" ]; then return 0; fi',' mkdir -p "$(dirname "$TS_CLOUD_DST")"',' cp -a "$TS_CLOUD_SRC" "$TS_CLOUD_DST"'," for TS_CLOUD_SIDECAR in -wal -shm; do",' if [ -f "$TS_CLOUD_SRC$TS_CLOUD_SIDECAR" ]; then cp -a "$TS_CLOUD_SRC$TS_CLOUD_SIDECAR" "$TS_CLOUD_DST$TS_CLOUD_SIDECAR"; fi'," done",' echo "[ts-cloud] adopted $TS_CLOUD_SP from the live release into shared/ — it now survives deploys"'," return 0","}"]}function Et(e,t=or){let r=[`mkdir -p ${e.releases} ${e.shared} ${ir(e)}`,...ka(e)],n=t.map((i)=>xs(e,i));for(let{path:i,target:a,seed:c}of n){if(!c)continue;if(r.push(`ts_cloud_adopt_shared '${i}' '${a}'`),Os(i))r.push(`mkdir -p "$(dirname ${a})"`,`touch ${a}`);else if(i==="storage")r.push(`mkdir -p ${a}/app/public`,`mkdir -p ${a}/framework/cache/data`,`mkdir -p ${a}/framework/sessions`,`mkdir -p ${a}/framework/testing`,`mkdir -p ${a}/framework/views`,`mkdir -p ${a}/logs`);else r.push(`mkdir -p ${a}`)}let s=Rs(e.base);return r.push(`mkdir -p ${Ie(e.base)}`,`cat > ${s} <<'TS_CLOUD_SHARED_PATHS_EOF'`,...n.map((i)=>`${i.path} ${i.target}`),"TS_CLOUD_SHARED_PATHS_EOF"),r}function cn(e,t=900){let r=`${Ie(e.base)}/deploy.lock`;return[`mkdir -p "$(dirname ${r})"`,`exec 9>${r}`,`flock -w ${t} 9 || { echo "[ts-cloud] another deploy of this site has held the lock for ${t}s — refusing to race it" >&2; exit 1; }`]}function ln(e){let t=`${e.release}.incoming`;return[`rm -rf ${t}`,`mkdir -p ${t}`,...Na(e),'if [ "$TS_CLOUD_IS_LIVE" = "yes" ]; then',` TS_CLOUD_STAGED=${t}`,"else",` rm -rf ${e.release}`,` mkdir -p ${e.release}`,` rmdir ${t}`,` TS_CLOUD_STAGED=${e.release}`,"fi"]}function un(e){let t=`TS_CLOUD_TRAP_LIVE="$(readlink -f ${e.current} 2>/dev/null || true)"`,r=`TS_CLOUD_TRAP_TARGET="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`;return`trap '${`if [ $? -ne 0 ]; then ${t}; ${r}; [ "$TS_CLOUD_TRAP_LIVE" = "$TS_CLOUD_TRAP_TARGET" ] || rm -rf ${e.release}; fi`}' EXIT`}function Na(e){return[`TS_CLOUD_LIVE_PATH="$(readlink -f ${e.current} 2>/dev/null || true)"`,`TS_CLOUD_RELEASE_PATH="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`,'if [ -n "$TS_CLOUD_LIVE_PATH" ] && [ "$TS_CLOUD_LIVE_PATH" = "$TS_CLOUD_RELEASE_PATH" ]; then TS_CLOUD_IS_LIVE=yes; else TS_CLOUD_IS_LIVE=no; fi']}function pn(e){let t=`${e.release}.incoming`;return[`if [ "$TS_CLOUD_STAGED" = "${t}" ]; then`,` rm -rf ${e.release}.previous`,` mv ${e.release} ${e.release}.previous`,` mv ${t} ${e.release}`,` rm -rf ${e.release}.previous`,"fi"]}function Ma(e,t){return[`if [ -f ${e} ] && [ ! -L ${e} ] && [ -s ${e} ] && [ ! -s ${t} ]; then`,` cp -a ${e} ${t}`,` echo "[ts-cloud] seeded shared/ from the release's own copy of the file"`,"fi"]}function ar(e,t=or){let r=[];for(let n of t){let{path:s,target:i,seed:a}=xs(e,n),c=`${e.release}/${s}`,u=[`rm -rf ${c}`,`mkdir -p "$(dirname ${c})"`,`ln -sfn ${i} ${c}`];if(a){if(s!==".env"&&Os(s))r.push(...Ma(c,i));r.push(...u);continue}r.push(`if [ -e ${i} ]; then`,...u.map((m)=>` ${m}`),"fi")}return r}function Fa(e,t){let r=Rs(e.base);return[`if [ -f ${r} ]; then`,' while IFS="\t" read -r TS_CLOUD_SP TS_CLOUD_TGT; do',' [ -n "$TS_CLOUD_SP" ] || continue',` [ -n "$TS_CLOUD_TGT" ] || TS_CLOUD_TGT="${e.shared}/$TS_CLOUD_SP"`,' [ -e "$TS_CLOUD_TGT" ] || continue',` rm -rf ${t}/"$TS_CLOUD_SP"`,` mkdir -p "$(dirname ${t}/"$TS_CLOUD_SP")"`,` ln -sfn "$TS_CLOUD_TGT" ${t}/"$TS_CLOUD_SP"`,` done < ${r}`,"fi"]}function ct(e){return[`ln -sfn ${e.release} ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`]}function mn(e){return`${Ie(e)}/previous-release`}function fn(e,t="TS_CLOUD_PREV_CURRENT"){let r=mn(e.base);return[`if [ -n "\${${t}:-}" ] && [ -d "$${t}" ] && [ "$(readlink -f "$${t}")" != "$(readlink -f ${e.release})" ]; then mkdir -p ${Ie(e.base)}; basename "$${t}" > ${r}; fi`]}function Is(e,t){let r=mn(e.base);return[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,...t?[`TS_CLOUD_RB_TARGET=${e.releases}/${t}`]:["TS_CLOUD_RB_TARGET=",`if [ -f ${r} ]; then TS_CLOUD_REC="${e.releases}/$(cat ${r})"; if [ -d "$TS_CLOUD_REC" ] && [ "$(readlink -f "$TS_CLOUD_REC")" != "$TS_CLOUD_CURRENT" ]; then TS_CLOUD_RB_TARGET="$TS_CLOUD_REC"; fi; fi`,`[ -n "$TS_CLOUD_RB_TARGET" ] || TS_CLOUD_RB_TARGET=$(ls -1dt ${e.releases}/*/ 2>/dev/null | sed 's#/$##' | while read -r r; do [ "$(readlink -f "$r")" != "$TS_CLOUD_CURRENT" ] && { echo "$r"; break; }; done)`],'[ -n "$TS_CLOUD_RB_TARGET" ] && [ -d "$TS_CLOUD_RB_TARGET" ] || { echo "no release to roll back to (looked for ${TS_CLOUD_RB_TARGET:-a previous release})" >&2; exit 1; }','[ "$(readlink -f "$TS_CLOUD_RB_TARGET")" != "$TS_CLOUD_CURRENT" ] || { echo "$(basename "$TS_CLOUD_RB_TARGET") is already the live release" >&2; exit 1; }','TS_CLOUD_RB_ID=$(basename "$TS_CLOUD_RB_TARGET")']}function _g(e,t={}){return[...Is(e,t.to),'echo "would roll back from $(basename "${TS_CLOUD_CURRENT:-none}") to $TS_CLOUD_RB_ID (dry run: nothing changed)"']}function Lg(e,t={}){let r=Math.max(1,t.gateSeconds??5),n=t.systemdDir??"/etc/systemd/system",s=[`ln -sfn "$TS_CLOUD_RB_TARGET" ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`,`rm -f ${mn(e.base)}`,'echo "rolled back to $TS_CLOUD_RB_ID"'],i=[...Is(e,t.to),...Fa(e,'"$TS_CLOUD_RB_TARGET"')];if(!t.unitBase)return[...i,...s];let a=t.unitBase,c=`${a}@\${TS_CLOUD_RB_ID}.service`;return[...i,`if [ -f ${n}/${a}@.service ]; then`,` systemctl start "${c}"`,` for TS_CLOUD_I in $(seq 1 ${r}); do sleep 1; systemctl is-active --quiet "${c}" || { echo "the release rolled back to, $TS_CLOUD_RB_ID, did not stay up; the current release keeps serving" >&2; journalctl -u "${c}" -n 30 --no-pager >&2 || true; systemctl stop "${c}" 2>/dev/null || true; exit 1; }; done`,...s.map((u)=>` ${u}`),` systemctl enable "${c}" 2>/dev/null || true`,` systemctl list-units --plain --no-legend --type=service "${a}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v "^${a}@\${TS_CLOUD_RB_ID}.service$" || true; } | while read -r TS_CLOUD_U; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done`,`elif [ -f ${n}/${a}.service ]; then`,...s.map((u)=>` ${u}`),` systemctl restart ${a}.service`,"else",...s.map((u)=>` ${u}`),"fi"]}function lt(e,t=4){let r=Math.max(1,t);return[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,`ls -1dt ${e.releases}/*/ 2>/dev/null | sed 's#/$##' | tail -n +${r+1} | while read -r TS_CLOUD_OLD; do`,' [ "$(readlink -f "$TS_CLOUD_OLD")" = "$TS_CLOUD_CURRENT" ] || rm -rf "$TS_CLOUD_OLD"',"done"]}function za(e){return`${Ie(e)}/owner`}function gn(e,t){let r=za(e);return[`if [ -f "${r}" ]; then`,` TS_CLOUD_OWNER=$(cat "${r}")`,` if [ "$TS_CLOUD_OWNER" != "${t}" ]; then`,` echo "[ts-cloud] REFUSING deploy: ${e} belongs to project '$TS_CLOUD_OWNER', not '${t}'. Another project on this box derives the same site key — give one of them a distinct site name/domain, or remove ${r} to transfer ownership." >&2`," exit 1"," fi","else",` mkdir -p "$(dirname "${r}")"`,` printf '%s\\n' "${t}" > "${r}"`,"fi"]}function cr(e,t){let r=Ie(e),n=Ha(e,t.releaseId),s=Ua(e),i=Math.max(1,t.keepLogs??20),a=t.commit||"",c=t.branch||"";return[`mkdir -p ${r}/deploys`,`exec > >(tee -a ${n}) 2>&1`,`echo "[ts-cloud] deploy ${t.releaseId} commit=${a} branch=${c} starting $(date -u +%Y-%m-%dT%H:%M:%SZ)"`,"ts_cloud_record_deploy() {"," TS_CLOUD_RC=$?",' if [ "$TS_CLOUD_RC" -eq 0 ]; then TS_CLOUD_ST=success; else TS_CLOUD_ST=failed; fi',` printf '%s\\t%s\\t%s\\t%s\\trc=%s\\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "${t.releaseId}" "${a}" "$TS_CLOUD_ST" "$TS_CLOUD_RC" >> ${s}`,"}","trap ts_cloud_record_deploy EXIT",`ls -1t ${r}/deploys/*.log 2>/dev/null | tail -n +${i+1} | while read -r TS_CLOUD_OLDLOG; do rm -f "$TS_CLOUD_OLDLOG"; done`]}var Ba=new Set(["sqlite","sqlite3"]),Ka=new Set([":memory:","memory"]);function ja(e){let t=e?.DB_CONNECTION?.trim().toLowerCase();return t!=null&&Ba.has(t)}function Va(e){let t=e.trim().replace(/^\.\//,"");if(t===""||t.startsWith("/")||t.startsWith("~"))return;if(t.split("/").includes(".."))return;return t.replace(/\/+$/,"")}function hn(e,t=[]){if(!ja(e))return{};let r=e?.DB_DATABASE_PATH?.trim()||e?.DB_DATABASE?.trim();if(r&&Ka.has(r.toLowerCase()))return{};if(!r)return{warning:"DB_CONNECTION is sqlite but neither DB_DATABASE_PATH nor DB_DATABASE names a file, so ts-cloud cannot tell where the database lives. If it is written inside the release directory, the next deploy discards it. Set DB_DATABASE_PATH, or list the file in the site's `sharedPaths`."};let n=Va(r);if(!n)return{};if(t.some((s)=>an(s)===n))return{};return{path:n}}function lr(e,t=[]){let{path:r}=hn(e,t);return r?[r]:[]}var Lr="/var/ts-cloud/artifacts",Mh="/usr/local/bin/ts-cloud-host-cleanup.sh",Fh="ts-cloud-host-cleanup";var $g=Object.freeze({stagingMaxAgeMinutes:60,artifactMaxAgeDays:2,artifactUploadMaxAgeMinutes:60,bunCacheMaxAgeDays:7,journalMaxAgeDays:14,journalMaxSizeMb:512,containerImageMaxAgeHours:168}),Mg=Object.freeze({artifactMaxAgeDays:0,bunCacheMaxAgeDays:1,journalMaxAgeDays:3,journalMaxSizeMb:256,containerImageMaxAgeHours:24}),Uh=50,Qh=85,Hh="daily";function As(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function Je(e,t,r=0){if(!Number.isInteger(t)||t<r)throw Error(`hostCleanup: ${e} must be a whole number >= ${r} (got ${t})`)}function Ls(e,t){for(let[r,n]of Object.entries(t))Je(`${e}.${r}`,n);Je(`${e}.stagingMaxAgeMinutes`,t.stagingMaxAgeMinutes,15),Je(`${e}.artifactUploadMaxAgeMinutes`,t.artifactUploadMaxAgeMinutes,15),Je(`${e}.journalMaxSizeMb`,t.journalMaxSizeMb,1)}function Ga(e,t){let r=`hostCleanup.paths[${t}]`,n=e.path?.replace(/\/+$/,"")??"";if(!n.startsWith("/")||n===""||/[\s'"`$\\]/.test(n)||n.split("/").includes(".."))throw Error(`${r}.path must be an absolute directory with no spaces, quotes or '..' (got ${JSON.stringify(e.path)})`);if(n==="/var/www"||n.startsWith("/var/www/"))throw Error(`${r}.path must not be under /var/www: releases are pruned by keepReleases`);if(!e.pattern||/^[*?]+$/.test(e.pattern)||e.pattern.includes("/")||/[\n'"`]/.test(e.pattern))throw Error(`${r}.pattern must be a file-name glob naming something, not a bare wildcard (got ${JSON.stringify(e.pattern)})`);if(Je(`${r}.maxAgeDays`,e.maxAgeDays),e.type!==void 0&&e.type!=="file"&&e.type!=="directory")throw Error(`${r}.type must be 'file' or 'directory'`)}function $r(e){let t=typeof e==="object"&&e!==null?e:{},r=e!==!1,n={...$g,...Us(t.retention)};Ls("hostCleanup.retention",n);let s=null;if(t.pressure!==!1){let c=typeof t.pressure==="object"?t.pressure:{},u=c.lowWaterPercent??50,m=c.highWaterPercent??85;if(Je("hostCleanup.pressure.lowWaterPercent",u),Je("hostCleanup.pressure.highWaterPercent",m,1),m>100||u>=m)throw Error(`hostCleanup.pressure: need 0 <= lowWaterPercent < highWaterPercent <= 100 (got ${u} and ${m})`);let h={...Mg,...Us(c.escalated)},S=Object.fromEntries(Object.keys(n).map((v)=>[v,Math.min(n[v],h[v]??n[v])]));Ls("hostCleanup.pressure.escalated",S),s={lowWaterPercent:u,highWaterPercent:m,escalated:S}}let i=t.schedule??"daily";if(!/^[\w*:,./~ -]+$/.test(i))throw Error(`hostCleanup.schedule must be a systemd OnCalendar expression (got ${JSON.stringify(i)})`);let a=t.paths??[];return a.forEach(Ga),{enabled:r,timer:r&&t.timer!==!1,schedule:i,retention:n,pressure:s,paths:a}}function Us(e){return Object.fromEntries(Object.entries(e??{}).filter(([,t])=>t!==void 0))}var Ot={stagingMaxAgeMinutes:"TS_CLOUD_HC_STAGING_MIN",artifactMaxAgeDays:"TS_CLOUD_HC_ARTIFACT_DAYS",artifactUploadMaxAgeMinutes:"TS_CLOUD_HC_UPLOAD_MIN",bunCacheMaxAgeDays:"TS_CLOUD_HC_BUN_DAYS",journalMaxAgeDays:"TS_CLOUD_HC_JOURNAL_DAYS",journalMaxSizeMb:"TS_CLOUD_HC_JOURNAL_MB",containerImageMaxAgeHours:"TS_CLOUD_HC_IMAGE_HOURS"};function Sn(e){return Object.keys(Ot).map((t)=>`${Ot[t]}=${e[t]}`).join(" ")}var Fe=(e)=>`"$${Ot[e]}"`;function Hs(e){return[`find /var/ts-cloud/staging -xdev -maxdepth 1 -type f -mmin +${Fe("stagingMaxAgeMinutes")} -delete 2>/dev/null || true`,`find /tmp -xdev -maxdepth 1 -type f -name "*-release.tar.gz" -mmin +${Fe("stagingMaxAgeMinutes")} -delete 2>/dev/null || true`,`find /var/ts-cloud/artifacts -xdev -maxdepth 1 -type f -name "*.tar.gz" -mtime +${Fe("artifactMaxAgeDays")} -delete 2>/dev/null || true`,`find /var/ts-cloud/artifacts -xdev -maxdepth 1 -type f -name ".*.tmp" -mmin +${Fe("artifactUploadMaxAgeMinutes")} -delete 2>/dev/null || true`,...e.map(qa),`journalctl --vacuum-time=${Fe("journalMaxAgeDays")}d --vacuum-size=${Fe("journalMaxSizeMb")}M >/dev/null 2>&1 || true`]}function qa(e){let t=As(e.path.replace(/\/+$/,"")),r=As(e.pattern);return e.type==="directory"?`find ${t} -xdev -mindepth 1 -maxdepth 1 -type d -name ${r} -mtime +${e.maxAgeDays} -exec rm -rf -- {} + 2>/dev/null || true`:`find ${t} -xdev -mindepth 1 -maxdepth 1 -type f -name ${r} -mtime +${e.maxAgeDays} -delete 2>/dev/null || true`}function ks(){return[`find /root/.bun/install/cache -xdev -type f -mtime +${Fe("bunCacheMaxAgeDays")} -delete 2>/dev/null || true`,`find /root/.bun/install/cache -xdev -depth -type d -empty -mtime +${Fe("bunCacheMaxAgeDays")} -delete 2>/dev/null || true`,`if command -v docker >/dev/null 2>&1; then docker image prune --all --force --filter "until=\${${Ot.containerImageMaxAgeHours}}h" >/dev/null 2>&1 || true; fi`,`if command -v podman >/dev/null 2>&1; then podman image prune --all --force --filter "until=\${${Ot.containerImageMaxAgeHours}}h" >/dev/null 2>&1 || true; fi`,"if command -v apt-get >/dev/null 2>&1; then apt-get clean >/dev/null 2>&1 || true; fi"]}function Ns(e){return[`${e}="$(df -P / 2>/dev/null | awk 'NR==2 {sub(/%/, "", $5); print $5}' || true)"`,`case "$${e}" in ''|*[!0-9]*) ${e}=-1 ;; esac`]}function ti(e){let{retention:t,pressure:r,paths:n}=$r(e),s='echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',i='echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"';if(!r)return['echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',Sn(t),...Hs(n),...ks(),'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"'];let{lowWaterPercent:a,highWaterPercent:c,escalated:u}=r;return['echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',...Ns("TS_CLOUD_HC_BEFORE"),"TS_CLOUD_HC_TIER=normal",Sn(t),`if [ "$TS_CLOUD_HC_BEFORE" -ge 0 ] && [ "$TS_CLOUD_HC_BEFORE" -lt ${a} ]; then`," TS_CLOUD_HC_TIER=light",` echo "[ts-cloud] host cleanup: / at \${TS_CLOUD_HC_BEFORE}% (under ${a}%), skipping cache and image pruning"`,`elif [ "$TS_CLOUD_HC_BEFORE" -ge ${c} ]; then`," TS_CLOUD_HC_TIER=pressure",` ${Sn(u)}`,` echo "[ts-cloud] warning: / at \${TS_CLOUD_HC_BEFORE}% (at or above ${c}%), host cleanup is using shortened retention windows" >&2`,"fi",...Hs(n),'if [ "$TS_CLOUD_HC_TIER" != light ]; then',...ks().map((m)=>` ${m}`),"fi",'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"',...Ns("TS_CLOUD_HC_AFTER"),`echo "[ts-cloud] host-cleanup {\\"event\\":\\"host-cleanup\\",\\"tier\\":\\"$TS_CLOUD_HC_TIER\\",\\"diskBeforePercent\\":$TS_CLOUD_HC_BEFORE,\\"diskAfterPercent\\":$TS_CLOUD_HC_AFTER,\\"lowWaterPercent\\":${a},\\"highWaterPercent\\":${c}}"`,"mkdir -p /var/lib/ts-cloud 2>/dev/null || true",'TS_CLOUD_HC_PREV="$(cat /var/lib/ts-cloud/host-cleanup.alert 2>/dev/null || echo ok)"',`if [ "$TS_CLOUD_HC_AFTER" -ge ${c} ]; then`,` echo "[ts-cloud] warning: / still at \${TS_CLOUD_HC_AFTER}% after host cleanup (high-water ${c}%); something outside ts-cloud's retention rules is filling the disk" >&2`,` if [ "$TS_CLOUD_HC_PREV" != alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "⚠️ $(hostname): / at \${TS_CLOUD_HC_AFTER}% after host cleanup (high-water ${c}%)" >/dev/null 2>&1 || true; fi`," echo alert > /var/lib/ts-cloud/host-cleanup.alert 2>/dev/null || true","else",` if [ "$TS_CLOUD_HC_PREV" = alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "✅ $(hostname): / back under ${c}% after host cleanup (\${TS_CLOUD_HC_AFTER}%)" >/dev/null 2>&1 || true; fi`," echo ok > /var/lib/ts-cloud/host-cleanup.alert 2>/dev/null || true","fi"]}function Fg(e){return["#!/usr/bin/env bash","# Managed by ts-cloud: rewritten on every deploy. Configure compute.hostCleanup instead of editing.","set -uo pipefail","TS_CLOUD_HC_LOCK=/run/lock/ts-cloud-host-cleanup.lock","[ -d /run/lock ] || TS_CLOUD_HC_LOCK=/tmp/ts-cloud-host-cleanup.lock",'if command -v flock >/dev/null 2>&1 && exec 9>"$TS_CLOUD_HC_LOCK"; then',' if ! flock -n 9; then echo "[ts-cloud] host cleanup already running; skipping"; exit 0; fi',"fi",...ti(e),"exit 0"]}function _n(e,t,r,n,s){return[`cat > ${e}.ts-cloud-new <<'${r}' || true`,...t,r,`if [ -s ${e}.ts-cloud-new ] && ! cmp -s ${e}.ts-cloud-new ${e}; then chmod ${n} ${e}.ts-cloud-new && mv -f ${e}.ts-cloud-new ${e}${s?` && ${s}=1`:""} || true; else rm -f ${e}.ts-cloud-new; fi`]}function Zs(e){let t=$r(e),r="/etc/systemd/system/ts-cloud-host-cleanup",n=["if [ -f /etc/systemd/system/ts-cloud-host-cleanup.timer ]; then"," systemctl disable --now ts-cloud-host-cleanup.timer >/dev/null 2>&1 || true"," rm -f /etc/systemd/system/ts-cloud-host-cleanup.timer /etc/systemd/system/ts-cloud-host-cleanup.service"," systemctl daemon-reload >/dev/null 2>&1 || true","fi"];if(!t.enabled)return[...n,"rm -f /usr/local/bin/ts-cloud-host-cleanup.sh"];let s=_n("/usr/local/bin/ts-cloud-host-cleanup.sh",Fg(e),"TS_CLOUD_HOST_CLEANUP_EOF","755");if(!t.timer)return[...s,...n];return[...s,"TS_CLOUD_HC_UNITS_CHANGED=0","if command -v systemctl >/dev/null 2>&1 && [ -d /etc/systemd/system ]; then",..._n("/etc/systemd/system/ts-cloud-host-cleanup.service",["[Unit]","Description=ts-cloud host cleanup (bounded disk retention)","After=local-fs.target","","[Service]","Type=oneshot","ExecStart=/usr/local/bin/ts-cloud-host-cleanup.sh","Nice=19","IOSchedulingClass=idle"],"TS_CLOUD_HOST_CLEANUP_SVC_EOF","644","TS_CLOUD_HC_UNITS_CHANGED"),..._n("/etc/systemd/system/ts-cloud-host-cleanup.timer",["[Unit]","Description=Run ts-cloud host cleanup on a schedule, independent of deploys","","[Timer]",`OnCalendar=${t.schedule}`,"RandomizedDelaySec=1h","Persistent=true","","[Install]","WantedBy=timers.target"],"TS_CLOUD_HOST_CLEANUP_TMR_EOF","644","TS_CLOUD_HC_UNITS_CHANGED"),' if [ "$TS_CLOUD_HC_UNITS_CHANGED" -eq 1 ]; then systemctl daemon-reload >/dev/null 2>&1 || true; fi'," systemctl enable --now ts-cloud-host-cleanup.timer >/dev/null 2>&1 || true","fi"]}function ri(e){let t=Zs(e);if(!$r(e).enabled)return t;return[...t,'if [ -x /usr/local/bin/ts-cloud-host-cleanup.sh ]; then /usr/local/bin/ts-cloud-host-cleanup.sh < /dev/null || echo "[ts-cloud] warning: host cleanup exited $?" >&2; fi']}var Wa=/\.(?:[cm]?[jt]sx?)$/;function ni(e,t,r){let n=t==="bun"?"/usr/local/bin/bun":t==="deno"?"/usr/local/bin/deno":"/usr/local/bin/node",s=e.trim();if(/^(?:bun|node|deno)\s+/.test(s))return`${n} ${s.replace(/^(?:bun|node|deno)\s+/,"")}`;let[i="",...a]=s.split(/\s+/);if(i&&!Wa.test(i)){let c=i.startsWith("/")?i:r&&i.startsWith("./")?`${r.replace(/\/+$/,"")}/${i.replace(/^\.\//,"")}`:void 0;if(c)return[c,...a].join(" ")}return`${n} ${s}`}function Ms(e){return["TS_CLOUD_MEM_MB=$(awk '/^MemTotal:/{print int($2/1024)}' /proc/meminfo)","TS_CLOUD_HIGH_MB=$((TS_CLOUD_MEM_MB / 8))",'[ "$TS_CLOUD_HIGH_MB" -lt 512 ] && TS_CLOUD_HIGH_MB=512','[ "$TS_CLOUD_HIGH_MB" -gt 4096 ] && TS_CLOUD_HIGH_MB=4096',`mkdir -p /etc/systemd/system/${e}.d`,`printf '# Written by ts-cloud: memoryHigh resolved from this box.
|
|
150
|
+
`)}_("systemctl",["daemon-reload"])};try{Z("/run/lock/ts-cloud-compute-storage.lock"),b=f("/var/lib/ts-cloud/compute-storage-state.json",{entries:[]});let T=f("/etc/ts-cloud/compute-storage.json",null);if(T){for(let P of T.volumes)if(!e.volumes.some((L)=>L.id===P.id&&L.key===P.key&&L.mountPath===P.mountPath))throw Error(`Refusing to remove or relocate managed volume ${P.name}; migrate its data explicitly first`);if(b.entries.length&&(T.deploymentStorage?.volume!==I?.volume||T.deploymentStorage?.includeBackups!==!1!==(I?.includeBackups!==!1)))throw Error("Refusing to change an active deployment-storage policy; migrate its data explicitly first")}if(u==="apply")V();for(let P of e.volumes)if(!R(P))throw Error(`Required volume is not mounted: ${P.name}`);if(!I||!D)return{volumes:e.volumes};if(u==="ensure-site"){let[P,L]=t.slice(1);if(!P?.startsWith(`${e.webRoot}/`)||!/^[\w-]+$/.test(n.basename(P))||P.includes("..")||!/^[\w-]+$/.test(L??""))throw Error("Invalid deployment site path or project slug");if(r.mkdirSync(n.join(P,"releases"),{recursive:!0}),I.includeBackups!==!1)r.mkdirSync(n.join(e.webRoot,`${L}-shared`,"backups"),{recursive:!0})}let O=(u==="reclaim"?[]:H(u==="ensure-site"?t[1]:void 0,t[2])).filter((P)=>!b.entries.some((L)=>L.source===P.source));for(let P of b.entries)if(!v(P.source)||!y(P.source,P.destination))throw Error(`Recorded deployment mount is missing: ${P.source}`);if(!O.length&&u==="ensure-site")return{inherited:!0,volume:D.name};if(!I.migrateExisting&&O.some((P)=>r.readdirSync(P.source).length>0))throw Error("Existing deployments require deploymentStorage.migrateExisting: true");if(O.length){let P=_("du",["-scx","--block-size=1",...O.map((ie)=>ie.source)]).trim().split(`
|
|
151
|
+
`).at(-1)?.split(/\s+/)[0],L=r.statfsSync(D.mountPath);if(Number(P)>L.bavail*L.bsize)throw Error("Insufficient free volume capacity for a verified deployment copy")}if(!r.existsSync("/run/ts-cloud-root-web"))r.mkdirSync("/run/ts-cloud-root-web");if(!v("/run/ts-cloud-root-web"))_("mount",["--bind",e.webRoot,"/run/ts-cloud-root-web"]);_("mount",["--make-private","/run/ts-cloud-root-web"]);let K=r.statSync(e.webRoot).dev;for(let P of b.entries){let L=n.join("/run/ts-cloud-root-web",n.relative(e.webRoot,P.source));if(r.existsSync(L)&&(r.statSync(L).dev!==K||y(L,P.destination)))throw Error(`Root recovery view contains a deployment mount: ${L}`)}for(let P=0;P<O.length;P++){if(v(O[P].source)&&y(O[P].source,O[P].destination))continue;console.log(`copy ${P+1}/${O.length}: ${O[P].source}`),await ne(O[P],!1)}for(let P of new Set([...I.locks??[],"/run/lock/ts-cloud-host-cleanup.lock"]))Z(P);for(let P of r.readdirSync(e.webRoot,{withFileTypes:!0}).filter((L)=>L.isDirectory()).sort((L,ie)=>L.name.localeCompare(ie.name)))Z(n.join(e.webRoot,P.name,".ts-cloud/deploy.lock"));for(let P of u==="reclaim"?[]:H(u==="ensure-site"?t[1]:void 0,t[2]))if(!b.entries.some((L)=>L.source===P.source)&&!O.some((L)=>L.source===P.source))O.push(P);if(O.length)console.log("Checking application services and HTTPS routes before activation");let E=O.length?await ee():void 0;if(E)h("/var/lib/ts-cloud/compute-storage-health-before.json",E);let q=pe().filter((P)=>P.write);if(q.length)throw Error(`Live writable files must be shared before migration: ${q.map((P)=>P.file).join(", ")}`);let N={entries:[...b.entries],fstab:r.readFileSync("/etc/fstab","utf8")};if(O.length)_("sync",[]);let Y=[];try{for(let P=0;P<O.length;P++){let L=O[P];if(v(L.source)){if(!y(L.source,L.destination))throw Error(`Unrecorded mount occupies ${L.source}`);b.entries.push(L),h("/var/lib/ts-cloud/compute-storage-state.json",b);continue}if(console.log(`verify and mount ${P+1}/${O.length}: ${L.source}`),await ne(L,!0),_("mount",["--bind",L.destination,L.source]),!y(L.source,L.destination))throw Error(`Bind verification failed: ${L.source}`);Y.push(L),b.entries.push(L),h("/var/lib/ts-cloud/compute-storage-state.json",b),k()}if(k(),_("findmnt",["--verify"]),b.activatedAt=new Date().toISOString(),h("/var/lib/ts-cloud/compute-storage-state.json",b),ge(),E){console.log("Checking application services and HTTPS routes after activation");let P=await ee();h("/var/lib/ts-cloud/compute-storage-health-after.json",P);let L=E.routes.filter((re)=>re.ok&&!P.routes.some((Le)=>Le.domain===re.domain&&Le.path===re.path&&Le.ok)),ie=Object.keys(E.services).filter((re)=>!P.services[re]);if(L.length||ie.length)throw Error(`Application verification failed: ${L.map((re)=>re.domain+re.path).concat(ie).join(", ")}`);console.log(`Verified ${P.routes.length} routes and ${Object.keys(P.services).length} services`)}}catch(P){let L=[];for(let ie of Y.reverse())try{_("umount",[ie.source])}catch{L.push(ie),console.error(`Rollback mount busy, original data retained: ${ie.source}`)}if(b.entries=[...N.entries,...L],r.writeFileSync("/etc/fstab",N.fstab),L.length)k();throw h("/var/lib/ts-cloud/compute-storage-state.json",b),_("systemctl",["daemon-reload"]),P}let X=pe().filter((P)=>P.device===K).map((P)=>P.file);for(let P of b.entries){if(!v(P.source)||!y(P.source,P.destination))throw Error(`Lost deployment mount: ${P.source}`);let L=n.join("/run/ts-cloud-root-web",n.relative(e.webRoot,P.source));if(!r.existsSync(L))continue;if(r.statSync(L).dev!==K||y(L,P.destination))throw Error(`Refusing to clean a deployment volume through the root recovery view: ${L}`);let ie="";try{ie=n.basename(r.realpathSync(n.join(n.dirname(P.source),"current")))}catch{}for(let re of r.readdirSync(L,{withFileTypes:!0})){let Le=n.join(L,re.name);if(n.basename(P.source)==="backups"){if(re.isFile()&&r.existsSync(n.join(P.destination,re.name)))r.unlinkSync(Le)}else if(re.isDirectory()&&!re.isSymbolicLink()&&re.name!==ie&&!X.some((Kt)=>Kt===n.join(P.source,re.name)||Kt.startsWith(`${n.join(P.source,re.name)}/`)))r.rmSync(Le,{recursive:!0})}}_("sync",[]);let J=W();return h("/var/lib/ts-cloud/compute-storage-status.json",J),console.log(JSON.stringify(J)),J}finally{for(let T of me.reverse())ue.symbols.flock(T,8),r.closeSync(T);ue.close()}}var pn="/etc/ts-cloud/compute-storage.json",Me="/usr/local/lib/ts-cloud/compute-storage.mjs";function ei(e,t){let r=Object.entries(e.infrastructure?.compute?.volumes??{}).map(([s,i])=>{if(!/^[a-z][a-z0-9-]*$/.test(s))throw Error(`Invalid compute volume key: ${s}`);if(!Number.isInteger(i.size)||i.size<10||i.size>10240)throw Error(`compute.volumes.${s}.size must be a whole number from 10 to 10240 GB`);if(!i.mountPath.startsWith("/")||!i.mountPath.slice(1).split("/").every((c)=>/^[\w-]+$/.test(c))||i.mountPath==="/var"||i.mountPath==="/var/lib"||["/etc","/usr","/var/www","/root","/boot","/dev","/proc","/sys","/run","/bin","/sbin","/lib"].some((c)=>i.mountPath===c||i.mountPath.startsWith(`${c}/`)))throw Error(`Unsafe compute volume mount path: ${i.mountPath}`);let a=i.name??`${e.project.slug}-${t}-${s}`;if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(a))throw Error(`Invalid compute volume name: ${a}`);return{...i,key:s,name:a,mountPath:i.mountPath.replace(/\/+$/,"")}});for(let s of r)if(r.some((i)=>i!==s&&(i.name===s.name||i.mountPath===s.mountPath||i.mountPath.startsWith(`${s.mountPath}/`))))throw Error("Compute volumes must have distinct names and non-overlapping mount paths");let n=e.infrastructure?.compute?.deploymentStorage;for(let s of n?.locks??[])if(!s.startsWith("/run/lock/")||!s.slice(10).split("/").every((i)=>/^[\w.-]+$/.test(i)&&i!=="."&&i!=="..")||s==="/run/lock/ts-cloud-compute-storage.lock")throw Error(`Invalid deployment storage lock: ${s}`);for(let s of n?.dependentUnits??[])if(!/^[\w@.-]+\.service$/.test(s))throw Error(`Invalid deployment storage dependent unit: ${s}`);if(n&&!r.some((s)=>s.key===n.volume))throw Error(`deploymentStorage.volume references an undeclared compute volume: ${n.volume}`);return r}function ir(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function ti(e){let t=`${pn}.candidate`,r=`#!/usr/bin/env bun
|
|
152
|
+
await (${Rs.toString()})(JSON.parse(await Bun.file(process.env.TS_CLOUD_STORAGE_POLICY || ${JSON.stringify(pn)}).text()), process.argv.slice(2));
|
|
153
|
+
`;return['command -v bun >/dev/null 2>&1 || { echo "Configured compute storage requires Bun on the host" >&2; exit 1; }',"install -d -m 0755 /etc/ts-cloud /usr/local/lib/ts-cloud /var/lib/ts-cloud",`printf %s ${ir(Buffer.from(r).toString("base64"))} | base64 -d > ${Me}.new`,`chmod 0755 ${Me}.new && mv ${Me}.new ${Me}`,`printf %s ${ir(JSON.stringify(e))} > ${t}`,`chmod 0644 ${t}`,`TS_CLOUD_STORAGE_POLICY=${t} bun ${Me} apply 2>&1 | tee /var/log/ts-cloud-compute-storage.log`,`rm -f ${t}`,"cat > /etc/systemd/system/ts-cloud-storage-check.service <<'TS_CLOUD_STORAGE_SERVICE'","[Unit]","Description=Check configured compute storage and deployment mounts","[Service]","Type=oneshot",`ExecStart=/usr/local/bin/bun ${Me} check`,"TS_CLOUD_STORAGE_SERVICE","cat > /etc/systemd/system/ts-cloud-storage-check.timer <<'TS_CLOUD_STORAGE_TIMER'","[Unit]","Description=Check compute storage every minute","[Timer]","OnBootSec=2min","OnUnitActiveSec=1min","[Install]","WantedBy=timers.target","TS_CLOUD_STORAGE_TIMER","systemctl daemon-reload","systemctl enable --now ts-cloud-storage-check.timer","cat > /etc/systemd/system/ts-cloud-storage-reclaim.service <<'TS_CLOUD_RECLAIM_SERVICE'","[Unit]","Description=Reclaim inactive root copies of volume-backed deployments","[Service]","Type=oneshot",`ExecStart=/usr/local/bin/bun ${Me} reclaim`,"Nice=19","IOSchedulingClass=idle","TS_CLOUD_RECLAIM_SERVICE","cat > /etc/systemd/system/ts-cloud-storage-reclaim.timer <<'TS_CLOUD_RECLAIM_TIMER'","[Unit]","Description=Reclaim retired deployment copies hourly","[Timer]","OnCalendar=hourly","RandomizedDelaySec=5min","Persistent=true","[Install]","WantedBy=timers.target","TS_CLOUD_RECLAIM_TIMER","systemctl daemon-reload","systemctl enable --now ts-cloud-storage-reclaim.timer"]}function Lr(e,t){return[`if [ -f ${pn} ]; then bun ${Me} ensure-site ${ir(e)} ${ir(t)}; fi`]}function ar(e){return Object.entries(e).map(([t,r])=>`${t}=${ka(String(r))}`).join(`
|
|
154
|
+
`)}function ka(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}var cr=["storage",".env"],Rt=4;function Ie(e){return`${e.replace(/\/+$/,"")}/.ts-cloud`}function Na(e){return`${Ie(e)}/deploy-history.log`}function Ma(e,t){return`${Ie(e)}/deploys/${t}.log`}function Os(e){return`${Ie(e)}/shared-paths`}function lr(e){return`${e.shared}/stx-images`}function Yt(e,t){let r=e.replace(/\/+$/,"");return{base:r,releases:`${r}/releases`,shared:`${r}/shared`,current:`${r}/current`,release:`${r}/releases/${t}`}}function Ds(e){let t=e.split("/").pop()||e;if(t===".env"||t.startsWith(".env."))return!0;return/\.[a-z0-9]+$/i.test(t)}function dn(e){return typeof e==="string"?e:e.path}function xs(e){let t=new Map;for(let r of e)t.set(dn(r),r);return[...t.values()]}function Is(e,t){if(typeof t==="string")return{path:t,target:`${e.shared}/${t}`,seed:!0};return{path:t.path,target:t.target??`${e.shared}/${t.path}`,seed:t.seed!==!1}}function Fa(e){return["ts_cloud_adopt_shared() {",' TS_CLOUD_SP="$1"',' TS_CLOUD_DST="$2"',` TS_CLOUD_SRC="${e.current}/$TS_CLOUD_SP"`,' if [ -e "$TS_CLOUD_DST" ]; then return 0; fi',' if [ -L "$TS_CLOUD_SRC" ] || [ ! -e "$TS_CLOUD_SRC" ]; then return 0; fi',' mkdir -p "$(dirname "$TS_CLOUD_DST")"',' cp -a "$TS_CLOUD_SRC" "$TS_CLOUD_DST"'," for TS_CLOUD_SIDECAR in -wal -shm; do",' if [ -f "$TS_CLOUD_SRC$TS_CLOUD_SIDECAR" ]; then cp -a "$TS_CLOUD_SRC$TS_CLOUD_SIDECAR" "$TS_CLOUD_DST$TS_CLOUD_SIDECAR"; fi'," done",' echo "[ts-cloud] adopted $TS_CLOUD_SP from the live release into shared/ — it now survives deploys"'," return 0","}"]}function Ot(e,t=cr){let r=[`mkdir -p ${e.releases} ${e.shared} ${lr(e)}`,...Fa(e)],n=t.map((i)=>Is(e,i));for(let{path:i,target:a,seed:c}of n){if(!c)continue;if(r.push(`ts_cloud_adopt_shared '${i}' '${a}'`),Ds(i))r.push(`mkdir -p "$(dirname ${a})"`,`touch ${a}`);else if(i==="storage")r.push(`mkdir -p ${a}/app/public`,`mkdir -p ${a}/framework/cache/data`,`mkdir -p ${a}/framework/sessions`,`mkdir -p ${a}/framework/testing`,`mkdir -p ${a}/framework/views`,`mkdir -p ${a}/logs`);else r.push(`mkdir -p ${a}`)}let s=Os(e.base);return r.push(`mkdir -p ${Ie(e.base)}`,`cat > ${s} <<'TS_CLOUD_SHARED_PATHS_EOF'`,...n.map((i)=>`${i.path} ${i.target}`),"TS_CLOUD_SHARED_PATHS_EOF"),r}function mn(e,t=900){let r=`${Ie(e.base)}/deploy.lock`;return[`mkdir -p "$(dirname ${r})"`,`exec 9>${r}`,`flock -w ${t} 9 || { echo "[ts-cloud] another deploy of this site has held the lock for ${t}s — refusing to race it" >&2; exit 1; }`]}function fn(e){let t=`${e.release}.incoming`;return[`rm -rf ${t}`,`mkdir -p ${t}`,...za(e),'if [ "$TS_CLOUD_IS_LIVE" = "yes" ]; then',` TS_CLOUD_STAGED=${t}`,"else",` rm -rf ${e.release}`,` mkdir -p ${e.release}`,` rmdir ${t}`,` TS_CLOUD_STAGED=${e.release}`,"fi"]}function gn(e){let t=`TS_CLOUD_TRAP_LIVE="$(readlink -f ${e.current} 2>/dev/null || true)"`,r=`TS_CLOUD_TRAP_TARGET="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`;return`trap '${`if [ $? -ne 0 ]; then ${t}; ${r}; [ "$TS_CLOUD_TRAP_LIVE" = "$TS_CLOUD_TRAP_TARGET" ] || rm -rf ${e.release}; fi`}' EXIT`}function za(e){return[`TS_CLOUD_LIVE_PATH="$(readlink -f ${e.current} 2>/dev/null || true)"`,`TS_CLOUD_RELEASE_PATH="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`,'if [ -n "$TS_CLOUD_LIVE_PATH" ] && [ "$TS_CLOUD_LIVE_PATH" = "$TS_CLOUD_RELEASE_PATH" ]; then TS_CLOUD_IS_LIVE=yes; else TS_CLOUD_IS_LIVE=no; fi']}function hn(e){let t=`${e.release}.incoming`;return[`if [ "$TS_CLOUD_STAGED" = "${t}" ]; then`,` rm -rf ${e.release}.previous`,` mv ${e.release} ${e.release}.previous`,` mv ${t} ${e.release}`,` rm -rf ${e.release}.previous`,"fi"]}function Ba(e,t){return[`if [ -f ${e} ] && [ ! -L ${e} ] && [ -s ${e} ] && [ ! -s ${t} ]; then`,` cp -a ${e} ${t}`,` echo "[ts-cloud] seeded shared/ from the release's own copy of the file"`,"fi"]}function ur(e,t=cr){let r=[];for(let n of t){let{path:s,target:i,seed:a}=Is(e,n),c=`${e.release}/${s}`,u=[`rm -rf ${c}`,`mkdir -p "$(dirname ${c})"`,`ln -sfn ${i} ${c}`];if(a){if(s!==".env"&&Ds(s))r.push(...Ba(c,i));r.push(...u);continue}r.push(`if [ -e ${i} ]; then`,...u.map((f)=>` ${f}`),"fi")}return r}function Ka(e,t){let r=Os(e.base);return[`if [ -f ${r} ]; then`,' while IFS="\t" read -r TS_CLOUD_SP TS_CLOUD_TGT; do',' [ -n "$TS_CLOUD_SP" ] || continue',` [ -n "$TS_CLOUD_TGT" ] || TS_CLOUD_TGT="${e.shared}/$TS_CLOUD_SP"`,' [ -e "$TS_CLOUD_TGT" ] || continue',` rm -rf ${t}/"$TS_CLOUD_SP"`,` mkdir -p "$(dirname ${t}/"$TS_CLOUD_SP")"`,` ln -sfn "$TS_CLOUD_TGT" ${t}/"$TS_CLOUD_SP"`,` done < ${r}`,"fi"]}function ct(e){return[`ln -sfn ${e.release} ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`]}function Sn(e){return`${Ie(e)}/previous-release`}function vn(e,t="TS_CLOUD_PREV_CURRENT"){let r=Sn(e.base);return[`if [ -n "\${${t}:-}" ] && [ -d "$${t}" ] && [ "$(readlink -f "$${t}")" != "$(readlink -f ${e.release})" ]; then mkdir -p ${Ie(e.base)}; basename "$${t}" > ${r}; fi`]}function As(e,t){let r=Sn(e.base);return[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,...t?[`TS_CLOUD_RB_TARGET=${e.releases}/${t}`]:["TS_CLOUD_RB_TARGET=",`if [ -f ${r} ]; then TS_CLOUD_REC="${e.releases}/$(cat ${r})"; if [ -d "$TS_CLOUD_REC" ] && [ "$(readlink -f "$TS_CLOUD_REC")" != "$TS_CLOUD_CURRENT" ]; then TS_CLOUD_RB_TARGET="$TS_CLOUD_REC"; fi; fi`,`[ -n "$TS_CLOUD_RB_TARGET" ] || TS_CLOUD_RB_TARGET=$(ls -1dt ${e.releases}/*/ 2>/dev/null | sed 's#/$##' | while read -r r; do [ "$(readlink -f "$r")" != "$TS_CLOUD_CURRENT" ] && { echo "$r"; break; }; done)`],'[ -n "$TS_CLOUD_RB_TARGET" ] && [ -d "$TS_CLOUD_RB_TARGET" ] || { echo "no release to roll back to (looked for ${TS_CLOUD_RB_TARGET:-a previous release})" >&2; exit 1; }','[ "$(readlink -f "$TS_CLOUD_RB_TARGET")" != "$TS_CLOUD_CURRENT" ] || { echo "$(basename "$TS_CLOUD_RB_TARGET") is already the live release" >&2; exit 1; }','TS_CLOUD_RB_ID=$(basename "$TS_CLOUD_RB_TARGET")']}function Lg(e,t={}){return[...As(e,t.to),'echo "would roll back from $(basename "${TS_CLOUD_CURRENT:-none}") to $TS_CLOUD_RB_ID (dry run: nothing changed)"']}function $g(e,t={}){let r=Math.max(1,t.gateSeconds??5),n=t.systemdDir??"/etc/systemd/system",s=[`ln -sfn "$TS_CLOUD_RB_TARGET" ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`,`rm -f ${Sn(e.base)}`,'echo "rolled back to $TS_CLOUD_RB_ID"'],i=[...As(e,t.to),...Ka(e,'"$TS_CLOUD_RB_TARGET"')];if(!t.unitBase)return[...i,...s];let a=t.unitBase,c=`${a}@\${TS_CLOUD_RB_ID}.service`;return[...i,`if [ -f ${n}/${a}@.service ]; then`,` systemctl start "${c}"`,` for TS_CLOUD_I in $(seq 1 ${r}); do sleep 1; systemctl is-active --quiet "${c}" || { echo "the release rolled back to, $TS_CLOUD_RB_ID, did not stay up; the current release keeps serving" >&2; journalctl -u "${c}" -n 30 --no-pager >&2 || true; systemctl stop "${c}" 2>/dev/null || true; exit 1; }; done`,...s.map((u)=>` ${u}`),` systemctl enable "${c}" 2>/dev/null || true`,` systemctl list-units --plain --no-legend --type=service "${a}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v "^${a}@\${TS_CLOUD_RB_ID}.service$" || true; } | while read -r TS_CLOUD_U; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done`,`elif [ -f ${n}/${a}.service ]; then`,...s.map((u)=>` ${u}`),` systemctl restart ${a}.service`,"else",...s.map((u)=>` ${u}`),"fi"]}function lt(e,t=4){let r=Math.max(1,t);return[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,`ls -1dt ${e.releases}/*/ 2>/dev/null | sed 's#/$##' | tail -n +${r+1} | while read -r TS_CLOUD_OLD; do`,' [ "$(readlink -f "$TS_CLOUD_OLD")" = "$TS_CLOUD_CURRENT" ] || rm -rf "$TS_CLOUD_OLD"',"done"]}function ja(e){return`${Ie(e)}/owner`}function _n(e,t){let r=ja(e);return[`if [ -f "${r}" ]; then`,` TS_CLOUD_OWNER=$(cat "${r}")`,` if [ "$TS_CLOUD_OWNER" != "${t}" ]; then`,` echo "[ts-cloud] REFUSING deploy: ${e} belongs to project '$TS_CLOUD_OWNER', not '${t}'. Another project on this box derives the same site key — give one of them a distinct site name/domain, or remove ${r} to transfer ownership." >&2`," exit 1"," fi","else",` mkdir -p "$(dirname "${r}")"`,` printf '%s\\n' "${t}" > "${r}"`,"fi"]}function dr(e,t){let r=Ie(e),n=Ma(e,t.releaseId),s=Na(e),i=Math.max(1,t.keepLogs??20),a=t.commit||"",c=t.branch||"";return[`mkdir -p ${r}/deploys`,`exec > >(tee -a ${n}) 2>&1`,`echo "[ts-cloud] deploy ${t.releaseId} commit=${a} branch=${c} starting $(date -u +%Y-%m-%dT%H:%M:%SZ)"`,"ts_cloud_record_deploy() {"," TS_CLOUD_RC=$?",' if [ "$TS_CLOUD_RC" -eq 0 ]; then TS_CLOUD_ST=success; else TS_CLOUD_ST=failed; fi',` printf '%s\\t%s\\t%s\\t%s\\trc=%s\\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "${t.releaseId}" "${a}" "$TS_CLOUD_ST" "$TS_CLOUD_RC" >> ${s}`,"}","trap ts_cloud_record_deploy EXIT",`ls -1t ${r}/deploys/*.log 2>/dev/null | tail -n +${i+1} | while read -r TS_CLOUD_OLDLOG; do rm -f "$TS_CLOUD_OLDLOG"; done`]}var Va=new Set(["sqlite","sqlite3"]),Ga=new Set([":memory:","memory"]);function qa(e){let t=e?.DB_CONNECTION?.trim().toLowerCase();return t!=null&&Va.has(t)}function Wa(e){let t=e.trim().replace(/^\.\//,"");if(t===""||t.startsWith("/")||t.startsWith("~"))return;if(t.split("/").includes(".."))return;return t.replace(/\/+$/,"")}function yn(e,t=[]){if(!qa(e))return{};let r=e?.DB_DATABASE_PATH?.trim()||e?.DB_DATABASE?.trim();if(r&&Ga.has(r.toLowerCase()))return{};if(!r)return{warning:"DB_CONNECTION is sqlite but neither DB_DATABASE_PATH nor DB_DATABASE names a file, so ts-cloud cannot tell where the database lives. If it is written inside the release directory, the next deploy discards it. Set DB_DATABASE_PATH, or list the file in the site's `sharedPaths`."};let n=Wa(r);if(!n)return{};if(t.some((s)=>dn(s)===n))return{};return{path:n}}function mr(e,t=[]){let{path:r}=yn(e,t);return r?[r]:[]}var $r="/var/ts-cloud/artifacts",Mh="/usr/local/bin/ts-cloud-host-cleanup.sh",Fh="ts-cloud-host-cleanup";var Mg=Object.freeze({stagingMaxAgeMinutes:60,artifactMaxAgeDays:2,artifactUploadMaxAgeMinutes:60,bunCacheMaxAgeDays:7,journalMaxAgeDays:14,journalMaxSizeMb:512,containerImageMaxAgeHours:168}),Fg=Object.freeze({artifactMaxAgeDays:0,bunCacheMaxAgeDays:1,journalMaxAgeDays:3,journalMaxSizeMb:256,containerImageMaxAgeHours:24}),Uh=50,Qh=85,Hh="daily";function Ls(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function Je(e,t,r=0){if(!Number.isInteger(t)||t<r)throw Error(`hostCleanup: ${e} must be a whole number >= ${r} (got ${t})`)}function Us(e,t){for(let[r,n]of Object.entries(t))Je(`${e}.${r}`,n);Je(`${e}.stagingMaxAgeMinutes`,t.stagingMaxAgeMinutes,15),Je(`${e}.artifactUploadMaxAgeMinutes`,t.artifactUploadMaxAgeMinutes,15),Je(`${e}.journalMaxSizeMb`,t.journalMaxSizeMb,1)}function Ya(e,t){let r=`hostCleanup.paths[${t}]`,n=e.path?.replace(/\/+$/,"")??"";if(!n.startsWith("/")||n===""||/[\s'"`$\\]/.test(n)||n.split("/").includes(".."))throw Error(`${r}.path must be an absolute directory with no spaces, quotes or '..' (got ${JSON.stringify(e.path)})`);if(n==="/var/www"||n.startsWith("/var/www/"))throw Error(`${r}.path must not be under /var/www: releases are pruned by keepReleases`);if(!e.pattern||/^[*?]+$/.test(e.pattern)||e.pattern.includes("/")||/[\n'"`]/.test(e.pattern))throw Error(`${r}.pattern must be a file-name glob naming something, not a bare wildcard (got ${JSON.stringify(e.pattern)})`);if(Je(`${r}.maxAgeDays`,e.maxAgeDays),e.type!==void 0&&e.type!=="file"&&e.type!=="directory")throw Error(`${r}.type must be 'file' or 'directory'`)}function Mr(e){let t=typeof e==="object"&&e!==null?e:{},r=e!==!1,n={...Mg,...Hs(t.retention)};Us("hostCleanup.retention",n);let s=null;if(t.pressure!==!1){let c=typeof t.pressure==="object"?t.pressure:{},u=c.lowWaterPercent??50,f=c.highWaterPercent??85;if(Je("hostCleanup.pressure.lowWaterPercent",u),Je("hostCleanup.pressure.highWaterPercent",f,1),f>100||u>=f)throw Error(`hostCleanup.pressure: need 0 <= lowWaterPercent < highWaterPercent <= 100 (got ${u} and ${f})`);let h={...Fg,...Hs(c.escalated)},_=Object.fromEntries(Object.keys(n).map((S)=>[S,Math.min(n[S],h[S]??n[S])]));Us("hostCleanup.pressure.escalated",_),s={lowWaterPercent:u,highWaterPercent:f,escalated:_}}let i=t.schedule??"daily";if(!/^[\w*:,./~ -]+$/.test(i))throw Error(`hostCleanup.schedule must be a systemd OnCalendar expression (got ${JSON.stringify(i)})`);let a=t.paths??[];return a.forEach(Ya),{enabled:r,timer:r&&t.timer!==!1,schedule:i,retention:n,pressure:s,paths:a}}function Hs(e){return Object.fromEntries(Object.entries(e??{}).filter(([,t])=>t!==void 0))}var xt={stagingMaxAgeMinutes:"TS_CLOUD_HC_STAGING_MIN",artifactMaxAgeDays:"TS_CLOUD_HC_ARTIFACT_DAYS",artifactUploadMaxAgeMinutes:"TS_CLOUD_HC_UPLOAD_MIN",bunCacheMaxAgeDays:"TS_CLOUD_HC_BUN_DAYS",journalMaxAgeDays:"TS_CLOUD_HC_JOURNAL_DAYS",journalMaxSizeMb:"TS_CLOUD_HC_JOURNAL_MB",containerImageMaxAgeHours:"TS_CLOUD_HC_IMAGE_HOURS"};function $n(e){return Object.keys(xt).map((t)=>`${xt[t]}=${e[t]}`).join(" ")}var Fe=(e)=>`"$${xt[e]}"`;function ks(e){return[`find /var/ts-cloud/staging -xdev -maxdepth 1 -type f -mmin +${Fe("stagingMaxAgeMinutes")} -delete 2>/dev/null || true`,`find /tmp -xdev -maxdepth 1 -type f -name "*-release.tar.gz" -mmin +${Fe("stagingMaxAgeMinutes")} -delete 2>/dev/null || true`,`find /var/ts-cloud/artifacts -xdev -maxdepth 1 -type f -name "*.tar.gz" -mtime +${Fe("artifactMaxAgeDays")} -delete 2>/dev/null || true`,`find /var/ts-cloud/artifacts -xdev -maxdepth 1 -type f -name ".*.tmp" -mmin +${Fe("artifactUploadMaxAgeMinutes")} -delete 2>/dev/null || true`,...e.map(Xa),`journalctl --vacuum-time=${Fe("journalMaxAgeDays")}d --vacuum-size=${Fe("journalMaxSizeMb")}M >/dev/null 2>&1 || true`]}function Xa(e){let t=Ls(e.path.replace(/\/+$/,"")),r=Ls(e.pattern);return e.type==="directory"?`find ${t} -xdev -mindepth 1 -maxdepth 1 -type d -name ${r} -mtime +${e.maxAgeDays} -exec rm -rf -- {} + 2>/dev/null || true`:`find ${t} -xdev -mindepth 1 -maxdepth 1 -type f -name ${r} -mtime +${e.maxAgeDays} -delete 2>/dev/null || true`}function Ns(){return[`find /root/.bun/install/cache -xdev -type f -mtime +${Fe("bunCacheMaxAgeDays")} -delete 2>/dev/null || true`,`find /root/.bun/install/cache -xdev -depth -type d -empty -mtime +${Fe("bunCacheMaxAgeDays")} -delete 2>/dev/null || true`,`if command -v docker >/dev/null 2>&1; then docker image prune --all --force --filter "until=\${${xt.containerImageMaxAgeHours}}h" >/dev/null 2>&1 || true; fi`,`if command -v podman >/dev/null 2>&1; then podman image prune --all --force --filter "until=\${${xt.containerImageMaxAgeHours}}h" >/dev/null 2>&1 || true; fi`,"if command -v apt-get >/dev/null 2>&1; then apt-get clean >/dev/null 2>&1 || true; fi"]}function Ms(e){return[`${e}="$(df -P / 2>/dev/null | awk 'NR==2 {sub(/%/, "", $5); print $5}' || true)"`,`case "$${e}" in ''|*[!0-9]*) ${e}=-1 ;; esac`]}function ri(e){let{retention:t,pressure:r,paths:n}=Mr(e),s='echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',i='echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"';if(!r)return['echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',$n(t),...ks(n),...Ns(),'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"'];let{lowWaterPercent:a,highWaterPercent:c,escalated:u}=r;return['echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',...Ms("TS_CLOUD_HC_BEFORE"),"TS_CLOUD_HC_TIER=normal",$n(t),`if [ "$TS_CLOUD_HC_BEFORE" -ge 0 ] && [ "$TS_CLOUD_HC_BEFORE" -lt ${a} ]; then`," TS_CLOUD_HC_TIER=light",` echo "[ts-cloud] host cleanup: / at \${TS_CLOUD_HC_BEFORE}% (under ${a}%), skipping cache and image pruning"`,`elif [ "$TS_CLOUD_HC_BEFORE" -ge ${c} ]; then`," TS_CLOUD_HC_TIER=pressure",` ${$n(u)}`,` echo "[ts-cloud] warning: / at \${TS_CLOUD_HC_BEFORE}% (at or above ${c}%), host cleanup is using shortened retention windows" >&2`,"fi",...ks(n),'if [ "$TS_CLOUD_HC_TIER" != light ]; then',...Ns().map((f)=>` ${f}`),"fi",'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"',...Ms("TS_CLOUD_HC_AFTER"),`echo "[ts-cloud] host-cleanup {\\"event\\":\\"host-cleanup\\",\\"tier\\":\\"$TS_CLOUD_HC_TIER\\",\\"diskBeforePercent\\":$TS_CLOUD_HC_BEFORE,\\"diskAfterPercent\\":$TS_CLOUD_HC_AFTER,\\"lowWaterPercent\\":${a},\\"highWaterPercent\\":${c}}"`,"mkdir -p /var/lib/ts-cloud 2>/dev/null || true",'TS_CLOUD_HC_PREV="$(cat /var/lib/ts-cloud/host-cleanup.alert 2>/dev/null || echo ok)"',`if [ "$TS_CLOUD_HC_AFTER" -ge ${c} ]; then`,` echo "[ts-cloud] warning: / still at \${TS_CLOUD_HC_AFTER}% after host cleanup (high-water ${c}%); something outside ts-cloud's retention rules is filling the disk" >&2`,` if [ "$TS_CLOUD_HC_PREV" != alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "⚠️ $(hostname): / at \${TS_CLOUD_HC_AFTER}% after host cleanup (high-water ${c}%)" >/dev/null 2>&1 || true; fi`," echo alert > /var/lib/ts-cloud/host-cleanup.alert 2>/dev/null || true","else",` if [ "$TS_CLOUD_HC_PREV" = alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "✅ $(hostname): / back under ${c}% after host cleanup (\${TS_CLOUD_HC_AFTER}%)" >/dev/null 2>&1 || true; fi`," echo ok > /var/lib/ts-cloud/host-cleanup.alert 2>/dev/null || true","fi"]}function Ug(e){return["#!/usr/bin/env bash","# Managed by ts-cloud: rewritten on every deploy. Configure compute.hostCleanup instead of editing.","set -uo pipefail","TS_CLOUD_HC_LOCK=/run/lock/ts-cloud-host-cleanup.lock","[ -d /run/lock ] || TS_CLOUD_HC_LOCK=/tmp/ts-cloud-host-cleanup.lock",'if command -v flock >/dev/null 2>&1 && exec 9>"$TS_CLOUD_HC_LOCK"; then',' if ! flock -n 9; then echo "[ts-cloud] host cleanup already running; skipping"; exit 0; fi',"fi",...ri(e),"exit 0"]}function bn(e,t,r,n,s){return[`cat > ${e}.ts-cloud-new <<'${r}' || true`,...t,r,`if [ -s ${e}.ts-cloud-new ] && ! cmp -s ${e}.ts-cloud-new ${e}; then chmod ${n} ${e}.ts-cloud-new && mv -f ${e}.ts-cloud-new ${e}${s?` && ${s}=1`:""} || true; else rm -f ${e}.ts-cloud-new; fi`]}function to(e){let t=Mr(e),r="/etc/systemd/system/ts-cloud-host-cleanup",n=["if [ -f /etc/systemd/system/ts-cloud-host-cleanup.timer ]; then"," systemctl disable --now ts-cloud-host-cleanup.timer >/dev/null 2>&1 || true"," rm -f /etc/systemd/system/ts-cloud-host-cleanup.timer /etc/systemd/system/ts-cloud-host-cleanup.service"," systemctl daemon-reload >/dev/null 2>&1 || true","fi"];if(!t.enabled)return[...n,"rm -f /usr/local/bin/ts-cloud-host-cleanup.sh"];let s=bn("/usr/local/bin/ts-cloud-host-cleanup.sh",Ug(e),"TS_CLOUD_HOST_CLEANUP_EOF","755");if(!t.timer)return[...s,...n];return[...s,"TS_CLOUD_HC_UNITS_CHANGED=0","if command -v systemctl >/dev/null 2>&1 && [ -d /etc/systemd/system ]; then",...bn("/etc/systemd/system/ts-cloud-host-cleanup.service",["[Unit]","Description=ts-cloud host cleanup (bounded disk retention)","After=local-fs.target","","[Service]","Type=oneshot","ExecStart=/usr/local/bin/ts-cloud-host-cleanup.sh","Nice=19","IOSchedulingClass=idle"],"TS_CLOUD_HOST_CLEANUP_SVC_EOF","644","TS_CLOUD_HC_UNITS_CHANGED"),...bn("/etc/systemd/system/ts-cloud-host-cleanup.timer",["[Unit]","Description=Run ts-cloud host cleanup on a schedule, independent of deploys","","[Timer]",`OnCalendar=${t.schedule}`,"RandomizedDelaySec=1h","Persistent=true","","[Install]","WantedBy=timers.target"],"TS_CLOUD_HOST_CLEANUP_TMR_EOF","644","TS_CLOUD_HC_UNITS_CHANGED"),' if [ "$TS_CLOUD_HC_UNITS_CHANGED" -eq 1 ]; then systemctl daemon-reload >/dev/null 2>&1 || true; fi'," systemctl enable --now ts-cloud-host-cleanup.timer >/dev/null 2>&1 || true","fi"]}function ni(e){let t=to(e);if(!Mr(e).enabled)return t;return[...t,'if [ -x /usr/local/bin/ts-cloud-host-cleanup.sh ]; then /usr/local/bin/ts-cloud-host-cleanup.sh < /dev/null || echo "[ts-cloud] warning: host cleanup exited $?" >&2; fi']}var Ja=/\.(?:[cm]?[jt]sx?)$/;function ii(e,t,r){let n=t==="bun"?"/usr/local/bin/bun":t==="deno"?"/usr/local/bin/deno":"/usr/local/bin/node",s=e.trim();if(/^(?:bun|node|deno)\s+/.test(s))return`${n} ${s.replace(/^(?:bun|node|deno)\s+/,"")}`;let[i="",...a]=s.split(/\s+/);if(i&&!Ja.test(i)){let c=i.startsWith("/")?i:r&&i.startsWith("./")?`${r.replace(/\/+$/,"")}/${i.replace(/^\.\//,"")}`:void 0;if(c)return[c,...a].join(" ")}return`${n} ${s}`}function Fs(e){return["TS_CLOUD_MEM_MB=$(awk '/^MemTotal:/{print int($2/1024)}' /proc/meminfo)","TS_CLOUD_HIGH_MB=$((TS_CLOUD_MEM_MB / 8))",'[ "$TS_CLOUD_HIGH_MB" -lt 512 ] && TS_CLOUD_HIGH_MB=512','[ "$TS_CLOUD_HIGH_MB" -gt 4096 ] && TS_CLOUD_HIGH_MB=4096',`mkdir -p /etc/systemd/system/${e}.d`,`printf '# Written by ts-cloud: memoryHigh resolved from this box.
|
|
155
155
|
# An eighth of %sMB RAM. Set memoryHigh in config to override.
|
|
156
156
|
[Service]
|
|
157
157
|
MemoryAccounting=true
|
|
158
158
|
MemoryHigh=%sM
|
|
159
|
-
' "$TS_CLOUD_MEM_MB" "$TS_CLOUD_HIGH_MB" > /etc/systemd/system/${e}.d/50-ts-cloud-memory.conf`,"systemctl daemon-reload",'echo "[ts-cloud] memoryHigh=auto resolved to ${TS_CLOUD_HIGH_MB}M (one eighth of ${TS_CLOUD_MEM_MB}M)"',...yn()]}function pr(e,t={auto:!0}){let r=t.auto===!1?[]:[`/etc/systemd/system/${e}.d/50-ts-cloud-memory.conf`];for(let n of["/etc/systemd/system.control","/run/systemd/system.control"]){if(t.high)r.push(`${n}/${e}.d/50-MemoryHigh.conf`);if(t.max)r.push(`${n}/${e}.d/50-MemoryMax.conf`)}if(r.length===0)return[];return["TS_CLOUD_MEM_CLEARED=0",...r.map((n)=>`if [ -f ${n} ]; then rm -f ${n}; TS_CLOUD_MEM_CLEARED=1; echo "[ts-cloud] removed ${n}: memory limits now come from config"; fi`),'if [ "$TS_CLOUD_MEM_CLEARED" = 1 ]; then systemctl daemon-reload; fi']}function yn(){return[`TS_CLOUD_COMMIT=$(for f in /sys/fs/cgroup/system.slice/*.service/memory.high /sys/fs/cgroup/system.slice/*.slice/*.service/memory.high; do [ -f "$f" ] || continue; v=$(cat "$f" 2>/dev/null); [ "$v" = "max" ] && continue; echo "$v"; done | awk '{s+=$1} END {print int(s/1048576)}')`,"TS_CLOUD_RAM=$(awk '/^MemTotal:/{print int($2/1024)}' /proc/meminfo)",'if [ -n "$TS_CLOUD_COMMIT" ] && [ "$TS_CLOUD_COMMIT" -gt 0 ] && [ "$TS_CLOUD_RAM" -gt 0 ]; then TS_CLOUD_PCT=$((TS_CLOUD_COMMIT * 100 / TS_CLOUD_RAM)); if [ "$TS_CLOUD_PCT" -gt 300 ]; then echo "[ts-cloud] WARNING: services on this box declare ${TS_CLOUD_COMMIT}M of MemoryHigh against ${TS_CLOUD_RAM}M of RAM (${TS_CLOUD_PCT}% committed). Soft ceilings, so this is not fatal - but no ceiling can protect the box once enough of them are drawn on at once."; else echo "[ts-cloud] memory commitment: ${TS_CLOUD_COMMIT}M declared against ${TS_CLOUD_RAM}M RAM (${TS_CLOUD_PCT}%)"; fi; fi']}function Ya(e){return[`TS_CLOUD_SLICE=$(systemctl show ${e} -p Slice --value 2>/dev/null || true)`,'if [ -n "$TS_CLOUD_SLICE" ] && [ "$TS_CLOUD_SLICE" != "system.slice" ]; then systemctl set-property --runtime "$TS_CLOUD_SLICE" MemoryHigh=infinity MemoryMax=infinity 2>/dev/null || true; systemctl set-property "$TS_CLOUD_SLICE" MemoryHigh=infinity MemoryMax=infinity 2>/dev/null || true; fi']}var Ze={path:"/",intervalSeconds:60,failuresBeforeRestart:3,timeoutSeconds:10,startupGraceSeconds:600,maxBackoffSeconds:3600,backoffBaseSeconds:300};function xt(e,t,r){return typeof e==="number"&&Number.isFinite(e)?Math.max(r,Math.floor(e)):t}function Fs(e){let{unitBase:t,unitPattern:r,port:n}=e,s=e.path&&e.path.startsWith("/")?e.path:Ze.path,i=xt(e.intervalSeconds,Ze.intervalSeconds,10),a=xt(e.failuresBeforeRestart,Ze.failuresBeforeRestart,1),c=xt(e.timeoutSeconds,Ze.timeoutSeconds,1),u=xt(e.startupGraceSeconds,Ze.startupGraceSeconds,0),m=xt(e.maxBackoffSeconds,Ze.maxBackoffSeconds,0),h=Math.min(Ze.backoffBaseSeconds,m),S=`/usr/local/sbin/${t}-liveness`,v=`/run/${t}-liveness`,_=`${t}-liveness`,y=`127.0.0.1:${n}${s}`,I=r.includes("@*")?`TS_CLOUD_UNIT=$(systemctl list-units --plain --no-legend --type=service '${r}' 2>/dev/null | awk '{print $1}' | head -1)`:`TS_CLOUD_UNIT=${r}`;return[`cat > ${S} <<'TS_CLOUD_LIVENESS_EOF'`,"#!/bin/sh",`# Liveness check for ${t}, written by ts-cloud on every deploy.`,`# Settings: interval=${i}s timeout=${c}s failures=${a} startup-grace=${u}s max-backoff=${m}s`,"set -eu",`TS_CLOUD_STATE=${v}`,'exec 9>"$TS_CLOUD_STATE.lock"',"flock -n 9 || exit 0",I,'[ -n "$TS_CLOUD_UNIT" ] || exit 0','systemctl is-active --quiet "$TS_CLOUD_UNIT" || exit 0',"TS_CLOUD_RC=0",`curl -s -o /dev/null --max-time ${c} "http://${y}" || TS_CLOUD_RC=$?`,'if [ "$TS_CLOUD_RC" -eq 0 ]; then',' rm -f "$TS_CLOUD_STATE.fail"',' if [ -f "$TS_CLOUD_STATE.restarts" ]; then',` TS_CLOUD_LAST=$(awk '{print $2}' "$TS_CLOUD_STATE.restarts" 2>/dev/null || true)`,` case "$TS_CLOUD_LAST" in ''|*[!0-9]*) TS_CLOUD_LAST=0 ;; esac`,` [ $(($(date +%s) - TS_CLOUD_LAST)) -lt ${m} ] || rm -f "$TS_CLOUD_STATE.restarts"`," fi"," exit 0","fi",'case "$TS_CLOUD_RC" in'," 7) TS_CLOUD_WHY='connection refused' ;;",` 28) TS_CLOUD_WHY='no response within ${c}s' ;;`,' *) TS_CLOUD_WHY="curl exit $TS_CLOUD_RC" ;;',"esac",'TS_CLOUD_SINCE=$(systemctl show "$TS_CLOUD_UNIT" -p ActiveEnterTimestampMonotonic --value 2>/dev/null || true)',"TS_CLOUD_UPTIME=$(cut -d' ' -f1 /proc/uptime 2>/dev/null || true)",`TS_CLOUD_AGE=$(awk -v up="$TS_CLOUD_UPTIME" -v since="$TS_CLOUD_SINCE" 'BEGIN { if (since + 0 > 0 && up + 0 > 0) print int(up - since / 1000000); else print -1 }')`,`case "$TS_CLOUD_AGE" in ''|*[!0-9-]*) TS_CLOUD_AGE=-1 ;; esac`,'if [ "$TS_CLOUD_AGE" -lt 0 ]; then',' TS_CLOUD_PID=$(systemctl show "$TS_CLOUD_UNIT" -p MainPID --value 2>/dev/null || true)',` case "$TS_CLOUD_PID" in ''|0|*[!0-9]*) ;; *) TS_CLOUD_AGE=$(ps -o etimes= -p "$TS_CLOUD_PID" 2>/dev/null | tr -d ' ' || true) ;; esac`,` case "$TS_CLOUD_AGE" in ''|*[!0-9]*) TS_CLOUD_AGE=-1 ;; esac`,"fi",`if [ "$TS_CLOUD_AGE" -ge 0 ] && [ "$TS_CLOUD_AGE" -lt ${u} ]; then`,' rm -f "$TS_CLOUD_STATE.fail"',` logger -t ${_} "$TS_CLOUD_UNIT is \${TS_CLOUD_AGE}s old, inside its ${u}s startup grace; not counting this failed check on ${y} ($TS_CLOUD_WHY)"`," exit 0","fi",'TS_CLOUD_FAILS=$(cat "$TS_CLOUD_STATE.fail" 2>/dev/null || echo 0)',`case "$TS_CLOUD_FAILS" in ''|*[!0-9]*) TS_CLOUD_FAILS=0 ;; esac`,"TS_CLOUD_FAILS=$((TS_CLOUD_FAILS + 1))",'echo "$TS_CLOUD_FAILS" > "$TS_CLOUD_STATE.fail"',`if [ "$TS_CLOUD_FAILS" -lt ${a} ]; then`,` logger -t ${_} "check $TS_CLOUD_FAILS of ${a} failed on ${y} ($TS_CLOUD_WHY)"`," exit 0","fi","TS_CLOUD_NOW=$(date +%s)","TS_CLOUD_STREAK=0","TS_CLOUD_LAST=0",'[ ! -f "$TS_CLOUD_STATE.restarts" ] || read -r TS_CLOUD_STREAK TS_CLOUD_LAST < "$TS_CLOUD_STATE.restarts" || true',`case "$TS_CLOUD_STREAK" in ''|*[!0-9]*) TS_CLOUD_STREAK=0 ;; esac`,`case "$TS_CLOUD_LAST" in ''|*[!0-9]*) TS_CLOUD_LAST=0 ;; esac`,'if [ "$TS_CLOUD_STREAK" -gt 0 ]; then',` TS_CLOUD_WAIT=${h}`," TS_CLOUD_I=1",` while [ "$TS_CLOUD_I" -lt "$TS_CLOUD_STREAK" ] && [ "$TS_CLOUD_WAIT" -lt ${m} ]; do TS_CLOUD_WAIT=$((TS_CLOUD_WAIT * 2)); TS_CLOUD_I=$((TS_CLOUD_I + 1)); done`,` [ "$TS_CLOUD_WAIT" -le ${m} ] || TS_CLOUD_WAIT=${m}`," TS_CLOUD_ELAPSED=$((TS_CLOUD_NOW - TS_CLOUD_LAST))",' if [ "$TS_CLOUD_ELAPSED" -lt "$TS_CLOUD_WAIT" ]; then',` logger -t ${_} "holding off: $TS_CLOUD_STREAK liveness restart(s) in a row have not brought $TS_CLOUD_UNIT back; next restart allowed in $((TS_CLOUD_WAIT - TS_CLOUD_ELAPSED))s ($TS_CLOUD_WHY on ${y})"`," exit 0"," fi","fi","TS_CLOUD_STREAK=$((TS_CLOUD_STREAK + 1))",`logger -t ${_} "no HTTP response on ${y} after $TS_CLOUD_FAILS checks ($TS_CLOUD_WHY); restarting $TS_CLOUD_UNIT (liveness restart $TS_CLOUD_STREAK in a row)"`,'echo "$TS_CLOUD_STREAK $TS_CLOUD_NOW" > "$TS_CLOUD_STATE.restarts"','rm -f "$TS_CLOUD_STATE.fail"','systemctl restart "$TS_CLOUD_UNIT"',"TS_CLOUD_LIVENESS_EOF",`chmod +x ${S}`,`rm -f ${v}.fail ${v}.restarts`,`cat > /etc/systemd/system/${t}-liveness.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=Liveness check for ${t} (managed by ts-cloud)`,"","[Service]","Type=oneshot",`ExecStart=${S}`,"TS_CLOUD_UNIT_EOF",`cat > /etc/systemd/system/${t}-liveness.timer <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=Run the ${t} liveness check every ${i}s`,"","[Timer]",`OnUnitActiveSec=${i}s`,`OnBootSec=${i}s`,"Persistent=true","","[Install]","WantedBy=timers.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",`systemctl enable --now ${t}-liveness.timer >/dev/null 2>&1 || true`]}var zs=20,vn=3,Xa=5,Ja=60;function Za(e){let{paths:t,unitBase:r,releaseId:n,port:s}=e,i=`${r}@${n}.service`,a=`${r}.service`,c=Math.max(1,e.healthGateSeconds??5),u=e.healthCheckPath?e.healthCheckPath.startsWith("/")?e.healthCheckPath:`/${e.healthCheckPath}`:null,m=u?`curl -sf -o /dev/null --max-time ${Xa} "http://127.0.0.1:${s}${u}"`:null,h=(S)=>`{ echo "[ts-cloud] release ${n} ${S}" >&2; ts_cloud_restore_previous; exit 1; }`;return[`TS_CLOUD_OLD_UNITS=$(systemctl list-units --plain --no-legend --type=service "${r}@*.service" 2>/dev/null | awk '{print $1}' | grep -v "^${i}$" || true)`,`TS_CLOUD_PREV_CURRENT="$(readlink ${t.current} 2>/dev/null || true)"`,"TS_CLOUD_LEGACY_STOPPED=0","ts_cloud_restore_previous() {",` journalctl -u ${i} -n 50 --no-pager >&2 || true`,` systemctl stop ${i} 2>/dev/null || true`,` systemctl disable ${i} 2>/dev/null || true`,` if [ -n "$TS_CLOUD_PREV_CURRENT" ] && [ -d "$TS_CLOUD_PREV_CURRENT" ]; then ln -sfn "$TS_CLOUD_PREV_CURRENT" ${t.current}.tmp && mv -Tf ${t.current}.tmp ${t.current}; fi`,' for TS_CLOUD_RU in ${TS_CLOUD_OLD_UNITS}; do systemctl enable "$TS_CLOUD_RU" 2>/dev/null || true; systemctl start "$TS_CLOUD_RU" 2>/dev/null || true; done',` if [ "$TS_CLOUD_LEGACY_STOPPED" -eq 1 ]; then systemctl start ${a} 2>/dev/null || true; fi`,' if [ -n "$TS_CLOUD_OLD_UNITS" ] || [ "$TS_CLOUD_LEGACY_STOPPED" -eq 1 ]; then echo "[ts-cloud] previous release restored and serving" >&2; else echo "[ts-cloud] there was no previous release to restore" >&2; fi',"}",`if [ -f /etc/systemd/system/${a} ] && systemctl is-active --quiet ${a}; then echo "[ts-cloud] retiring pre-zero-downtime unit ${a} (one-time restart cutover)"; systemctl stop ${a}; TS_CLOUD_LEGACY_STOPPED=1; fi`,'TS_CLOUD_STARTED_AT="@$(date +%s)"',`systemctl restart ${i}`,`TS_CLOUD_GATE_OK=1; for TS_CLOUD_I in $(seq 1 ${c}); do sleep 1; systemctl is-active --quiet ${i} || { TS_CLOUD_GATE_OK=0; break; }; done`,'if [ "$TS_CLOUD_GATE_OK" -ne 1 ]; then',` if journalctl -u ${i} --since "$TS_CLOUD_STARTED_AT" -o cat --no-pager 2>/dev/null | grep -iE 'EADDRINUSE|address already in use|port [0-9]+ (is )?in use|Failed to start server' >/dev/null; then`,` echo "[ts-cloud] release ${n} could not share :${s} with the previous release (no SO_REUSEPORT?) — retiring it and retrying" >&2`,' for TS_CLOUD_RU in ${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_RU" 2>/dev/null || true; done',` systemctl restart ${i}`,` for TS_CLOUD_I in $(seq 1 ${c}); do sleep 1; systemctl is-active --quiet ${i} || ${h("failed its health gate on the free port")}; done`," else",` ${h("crashed on start — the previous release was never stopped")}`," fi","fi",`if ss -ltnpH "sport = :${s}" >/dev/null 2>&1; then`," TS_CLOUD_BOUND=0",` for TS_CLOUD_I in $(seq 1 ${Ja}); do`,` TS_CLOUD_NEW_PID="$(systemctl show -p MainPID --value ${i} 2>/dev/null || true)"`,` if [ -n "$TS_CLOUD_NEW_PID" ] && [ "$TS_CLOUD_NEW_PID" != "0" ] && ss -ltnpH "sport = :${s}" 2>/dev/null | grep "pid=$TS_CLOUD_NEW_PID," >/dev/null; then TS_CLOUD_BOUND=1; break; fi`,` systemctl is-active --quiet ${i} || break`,` sleep ${vn}`," done",` [ "$TS_CLOUD_BOUND" -eq 1 ] || ${h(`never took :${s}`)}`,"else",' echo "[ts-cloud] cannot read listener PIDs on this host — the response probes run without the bind check" >&2',"fi",...m?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${zs}); do if ${m}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${vn}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${h(`never answered ${u}`)}`]:[],...ct(t),`systemctl enable ${i} 2>/dev/null || true`,'for TS_CLOUD_U in ${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done',`TS_CLOUD_LISTENING=0; for TS_CLOUD_I in $(seq 1 ${c}); do if ss -ltnH "sport = :${s}" 2>/dev/null | grep . >/dev/null; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done`,`if [ "$TS_CLOUD_LISTENING" -ne 1 ]; then echo "[ts-cloud] nothing is listening on ${s} after retiring the previous release — restarting ${i} on the now-free port" >&2; systemctl restart ${i}; for TS_CLOUD_I in $(seq 1 ${c}); do if ss -ltnH "sport = :${s}" 2>/dev/null | grep . >/dev/null; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done; fi`,`[ "$TS_CLOUD_LISTENING" -eq 1 ] || ${h(`is active but never bound :${s}`)}`,...m?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${zs}); do if ${m}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${vn}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${h(`stopped answering ${u} once it served alone`)}`]:[],...fn(t),`systemctl list-unit-files --plain --no-legend "${r}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v -e "^${i}$" -e "^${r}@\\.service$" || true; } | while read -r TS_CLOUD_U; do systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done`,`if [ -f /etc/systemd/system/${a} ]; then systemctl disable ${a} 2>/dev/null || true; rm -f /etc/systemd/system/${a}; systemctl daemon-reload; fi`]}function ii(e){let{siteName:t,slug:r,artifactFetch:n,releaseId:s,execStart:i,envEntries:a,port:c,keepReleases:u=Pt,preStartCommands:m=[],healthCheckPath:h,healthGateSeconds:S=5,liveness:v,memoryHigh:_="auto",memoryMax:y,cpuWeight:b,ioWeight:I,tasksMax:D,stopTimeout:H}=e,R=[...b!=null?[`CPUWeight=${b}`]:[],...I!=null?[`IOWeight=${I}`]:[],...D!=null?[`TasksMax=${D}`]:[],...H?[`TimeoutStopSec=${H}`]:[]],x=e.zeroDowntime??c!=null,W=e.appDir??`/var/www/${t}`,k=Xt(W,s),V=`${r}-${t}`,te=`${V}.service`,ue=oi(r,t,s),me=e.sharedPaths??[],Z=Ds([".env",...me,...lr(a,me)]),pe=sr(a),ne=m.length>0?[`cd ${k.release}`,...m]:[],ee=["set -euo pipefail",...cn(k),un(k),...n,...Et(k,Z),...ln(k),`tar xzf ${ue} -C "$TS_CLOUD_STAGED"`,`rm -f ${ue}`,`cat > ${k.shared}/.env <<'TS_CLOUD_ENV_EOF'`,pe,"TS_CLOUD_ENV_EOF",`chmod 600 ${k.shared}/.env`,...pn(k),`find ${k.release} -maxdepth 1 \\( -type f -o -type l \\) -name '.env*' ! -name '.env.example' ! -name '*.example' -delete`,`sed -i -E '/^[[:space:]]*(PORT|PORT_BACKEND|PORT_ADMIN|PORT_FRONTEND)[[:space:]]*=/d' ${k.shared}/.env 2>/dev/null || true`,...ar(k,Z),...ne];if(x&&c!=null){let ge=`${V}@${s}.service`,T=h?h.startsWith("/")?h:`/${h}`:null;return[...ee,`cat > /etc/systemd/system/${V}@.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} release %i (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${k.releases}/%i`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",..._&&_!=="auto"?[`MemoryHigh=${_}`]:[],...y?[`MemoryMax=${y}`]:[],...R,`EnvironmentFile=${k.releases}/%i/.env`,`Environment=PORT=${c}`,`Environment=STX_IMAGE_CACHE_DIR=${ir(k)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",..._==="auto"?Ms(`${V}@.service`):[...pr(`${V}@.service`),...yn()],...Ya(ge),...Za({paths:k,unitBase:V,releaseId:s,port:c,healthCheckPath:T,healthGateSeconds:S}),...lt(k,u),...v===!1?[]:Fs({...v,unitBase:V,unitPattern:`${V}@*.service`,port:c,path:v?.path??h})]}return[...ee,`cat > /etc/systemd/system/${te} <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${k.current}`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",..._&&_!=="auto"?[`MemoryHigh=${_}`]:[],...y?[`MemoryMax=${y}`]:[],...R,`EnvironmentFile=${k.current}/.env`,...c?[`Environment=PORT=${c}`]:[],`Environment=STX_IMAGE_CACHE_DIR=${ir(k)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...pr(te,{auto:_!=="auto",high:_!=="auto",max:Boolean(y)}),..._==="auto"?Ms(te):yn(),`systemctl enable ${te}`,`TS_CLOUD_PREV_CURRENT="$(readlink ${k.current} 2>/dev/null || true)"`,...ct(k),`systemctl restart ${te}`,`for TS_CLOUD_I in $(seq 1 ${Math.max(1,S)}); do sleep 1; systemctl is-active --quiet ${te} || { echo "[ts-cloud] release ${s} of ${te} did not stay up — restoring the previous release" >&2; journalctl -u ${te} -n 50 --no-pager >&2 || true; if [ -n "$TS_CLOUD_PREV_CURRENT" ] && [ -d "$TS_CLOUD_PREV_CURRENT" ] && [ "$(readlink -f "$TS_CLOUD_PREV_CURRENT")" != "$(readlink -f ${k.release})" ]; then ln -sfn "$TS_CLOUD_PREV_CURRENT" ${k.current}.tmp && mv -Tf ${k.current}.tmp ${k.current}; systemctl restart ${te} || true; fi; exit 1; }; done`,...fn(k),...lt(k,u),...v===!1||!c?[]:Fs({...v,unitBase:V,unitPattern:te,port:c,path:v?.path??h})]}function si(e){let{siteName:t,artifactFetch:r,releaseId:n,keepReleases:s=Pt,preStartCommands:i=[]}=e,a=e.appDir??`/var/www/${t}`,c=Xt(a,n),u=oi(e.slug,t,n),m=i.length>0?[`cd ${c.release}`,...i]:[];return["set -euo pipefail",...cn(c),un(c),...r,...Et(c,[]),...ln(c),`tar xzf ${u} -C "$TS_CLOUD_STAGED"`,...pn(c),`rm -f ${u}`,...m,...ct(c),...lt(c,s)]}function oi(e,t,r){return`/tmp/${[e,t,r].filter(Boolean).join("-")}-release.tar.gz`}function _c(e,t,r,n){return[`aws s3 cp "s3://${e}/${t}" ${n} --region ${r}`]}function Lc(e,t){return[`mv "${e}" ${t}`]}function ut(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function dr(e,t,r){return["set -euo pipefail",`chmod 600 ${ut(e)}`,`mv -f -- ${ut(e)} ${ut(t)}`,`cp -- ${ut(t)} ${ut(r)}`].join(`
|
|
160
|
-
`)}function
|
|
161
|
-
`)}var
|
|
159
|
+
' "$TS_CLOUD_MEM_MB" "$TS_CLOUD_HIGH_MB" > /etc/systemd/system/${e}.d/50-ts-cloud-memory.conf`,"systemctl daemon-reload",'echo "[ts-cloud] memoryHigh=auto resolved to ${TS_CLOUD_HIGH_MB}M (one eighth of ${TS_CLOUD_MEM_MB}M)"',...wn()]}function fr(e,t={auto:!0}){let r=t.auto===!1?[]:[`/etc/systemd/system/${e}.d/50-ts-cloud-memory.conf`];for(let n of["/etc/systemd/system.control","/run/systemd/system.control"]){if(t.high)r.push(`${n}/${e}.d/50-MemoryHigh.conf`);if(t.max)r.push(`${n}/${e}.d/50-MemoryMax.conf`)}if(r.length===0)return[];return["TS_CLOUD_MEM_CLEARED=0",...r.map((n)=>`if [ -f ${n} ]; then rm -f ${n}; TS_CLOUD_MEM_CLEARED=1; echo "[ts-cloud] removed ${n}: memory limits now come from config"; fi`),'if [ "$TS_CLOUD_MEM_CLEARED" = 1 ]; then systemctl daemon-reload; fi']}function wn(){return[`TS_CLOUD_COMMIT=$(for f in /sys/fs/cgroup/system.slice/*.service/memory.high /sys/fs/cgroup/system.slice/*.slice/*.service/memory.high; do [ -f "$f" ] || continue; v=$(cat "$f" 2>/dev/null); [ "$v" = "max" ] && continue; echo "$v"; done | awk '{s+=$1} END {print int(s/1048576)}')`,"TS_CLOUD_RAM=$(awk '/^MemTotal:/{print int($2/1024)}' /proc/meminfo)",'if [ -n "$TS_CLOUD_COMMIT" ] && [ "$TS_CLOUD_COMMIT" -gt 0 ] && [ "$TS_CLOUD_RAM" -gt 0 ]; then TS_CLOUD_PCT=$((TS_CLOUD_COMMIT * 100 / TS_CLOUD_RAM)); if [ "$TS_CLOUD_PCT" -gt 300 ]; then echo "[ts-cloud] WARNING: services on this box declare ${TS_CLOUD_COMMIT}M of MemoryHigh against ${TS_CLOUD_RAM}M of RAM (${TS_CLOUD_PCT}% committed). Soft ceilings, so this is not fatal - but no ceiling can protect the box once enough of them are drawn on at once."; else echo "[ts-cloud] memory commitment: ${TS_CLOUD_COMMIT}M declared against ${TS_CLOUD_RAM}M RAM (${TS_CLOUD_PCT}%)"; fi; fi']}function Za(e){return[`TS_CLOUD_SLICE=$(systemctl show ${e} -p Slice --value 2>/dev/null || true)`,'if [ -n "$TS_CLOUD_SLICE" ] && [ "$TS_CLOUD_SLICE" != "system.slice" ]; then systemctl set-property --runtime "$TS_CLOUD_SLICE" MemoryHigh=infinity MemoryMax=infinity 2>/dev/null || true; systemctl set-property "$TS_CLOUD_SLICE" MemoryHigh=infinity MemoryMax=infinity 2>/dev/null || true; fi']}var Ze={path:"/",intervalSeconds:60,failuresBeforeRestart:3,timeoutSeconds:10,startupGraceSeconds:600,maxBackoffSeconds:3600,backoffBaseSeconds:300};function Lt(e,t,r){return typeof e==="number"&&Number.isFinite(e)?Math.max(r,Math.floor(e)):t}function zs(e){let{unitBase:t,unitPattern:r,port:n}=e,s=e.path&&e.path.startsWith("/")?e.path:Ze.path,i=Lt(e.intervalSeconds,Ze.intervalSeconds,10),a=Lt(e.failuresBeforeRestart,Ze.failuresBeforeRestart,1),c=Lt(e.timeoutSeconds,Ze.timeoutSeconds,1),u=Lt(e.startupGraceSeconds,Ze.startupGraceSeconds,0),f=Lt(e.maxBackoffSeconds,Ze.maxBackoffSeconds,0),h=Math.min(Ze.backoffBaseSeconds,f),_=`/usr/local/sbin/${t}-liveness`,S=`/run/${t}-liveness`,v=`${t}-liveness`,y=`127.0.0.1:${n}${s}`,I=r.includes("@*")?`TS_CLOUD_UNIT=$(systemctl list-units --plain --no-legend --type=service '${r}' 2>/dev/null | awk '{print $1}' | head -1)`:`TS_CLOUD_UNIT=${r}`;return[`cat > ${_} <<'TS_CLOUD_LIVENESS_EOF'`,"#!/bin/sh",`# Liveness check for ${t}, written by ts-cloud on every deploy.`,`# Settings: interval=${i}s timeout=${c}s failures=${a} startup-grace=${u}s max-backoff=${f}s`,"set -eu",`TS_CLOUD_STATE=${S}`,'exec 9>"$TS_CLOUD_STATE.lock"',"flock -n 9 || exit 0",I,'[ -n "$TS_CLOUD_UNIT" ] || exit 0','systemctl is-active --quiet "$TS_CLOUD_UNIT" || exit 0',"TS_CLOUD_RC=0",`curl -s -o /dev/null --max-time ${c} "http://${y}" || TS_CLOUD_RC=$?`,'if [ "$TS_CLOUD_RC" -eq 0 ]; then',' rm -f "$TS_CLOUD_STATE.fail"',' if [ -f "$TS_CLOUD_STATE.restarts" ]; then',` TS_CLOUD_LAST=$(awk '{print $2}' "$TS_CLOUD_STATE.restarts" 2>/dev/null || true)`,` case "$TS_CLOUD_LAST" in ''|*[!0-9]*) TS_CLOUD_LAST=0 ;; esac`,` [ $(($(date +%s) - TS_CLOUD_LAST)) -lt ${f} ] || rm -f "$TS_CLOUD_STATE.restarts"`," fi"," exit 0","fi",'case "$TS_CLOUD_RC" in'," 7) TS_CLOUD_WHY='connection refused' ;;",` 28) TS_CLOUD_WHY='no response within ${c}s' ;;`,' *) TS_CLOUD_WHY="curl exit $TS_CLOUD_RC" ;;',"esac",'TS_CLOUD_SINCE=$(systemctl show "$TS_CLOUD_UNIT" -p ActiveEnterTimestampMonotonic --value 2>/dev/null || true)',"TS_CLOUD_UPTIME=$(cut -d' ' -f1 /proc/uptime 2>/dev/null || true)",`TS_CLOUD_AGE=$(awk -v up="$TS_CLOUD_UPTIME" -v since="$TS_CLOUD_SINCE" 'BEGIN { if (since + 0 > 0 && up + 0 > 0) print int(up - since / 1000000); else print -1 }')`,`case "$TS_CLOUD_AGE" in ''|*[!0-9-]*) TS_CLOUD_AGE=-1 ;; esac`,'if [ "$TS_CLOUD_AGE" -lt 0 ]; then',' TS_CLOUD_PID=$(systemctl show "$TS_CLOUD_UNIT" -p MainPID --value 2>/dev/null || true)',` case "$TS_CLOUD_PID" in ''|0|*[!0-9]*) ;; *) TS_CLOUD_AGE=$(ps -o etimes= -p "$TS_CLOUD_PID" 2>/dev/null | tr -d ' ' || true) ;; esac`,` case "$TS_CLOUD_AGE" in ''|*[!0-9]*) TS_CLOUD_AGE=-1 ;; esac`,"fi",`if [ "$TS_CLOUD_AGE" -ge 0 ] && [ "$TS_CLOUD_AGE" -lt ${u} ]; then`,' rm -f "$TS_CLOUD_STATE.fail"',` logger -t ${v} "$TS_CLOUD_UNIT is \${TS_CLOUD_AGE}s old, inside its ${u}s startup grace; not counting this failed check on ${y} ($TS_CLOUD_WHY)"`," exit 0","fi",'TS_CLOUD_FAILS=$(cat "$TS_CLOUD_STATE.fail" 2>/dev/null || echo 0)',`case "$TS_CLOUD_FAILS" in ''|*[!0-9]*) TS_CLOUD_FAILS=0 ;; esac`,"TS_CLOUD_FAILS=$((TS_CLOUD_FAILS + 1))",'echo "$TS_CLOUD_FAILS" > "$TS_CLOUD_STATE.fail"',`if [ "$TS_CLOUD_FAILS" -lt ${a} ]; then`,` logger -t ${v} "check $TS_CLOUD_FAILS of ${a} failed on ${y} ($TS_CLOUD_WHY)"`," exit 0","fi","TS_CLOUD_NOW=$(date +%s)","TS_CLOUD_STREAK=0","TS_CLOUD_LAST=0",'[ ! -f "$TS_CLOUD_STATE.restarts" ] || read -r TS_CLOUD_STREAK TS_CLOUD_LAST < "$TS_CLOUD_STATE.restarts" || true',`case "$TS_CLOUD_STREAK" in ''|*[!0-9]*) TS_CLOUD_STREAK=0 ;; esac`,`case "$TS_CLOUD_LAST" in ''|*[!0-9]*) TS_CLOUD_LAST=0 ;; esac`,'if [ "$TS_CLOUD_STREAK" -gt 0 ]; then',` TS_CLOUD_WAIT=${h}`," TS_CLOUD_I=1",` while [ "$TS_CLOUD_I" -lt "$TS_CLOUD_STREAK" ] && [ "$TS_CLOUD_WAIT" -lt ${f} ]; do TS_CLOUD_WAIT=$((TS_CLOUD_WAIT * 2)); TS_CLOUD_I=$((TS_CLOUD_I + 1)); done`,` [ "$TS_CLOUD_WAIT" -le ${f} ] || TS_CLOUD_WAIT=${f}`," TS_CLOUD_ELAPSED=$((TS_CLOUD_NOW - TS_CLOUD_LAST))",' if [ "$TS_CLOUD_ELAPSED" -lt "$TS_CLOUD_WAIT" ]; then',` logger -t ${v} "holding off: $TS_CLOUD_STREAK liveness restart(s) in a row have not brought $TS_CLOUD_UNIT back; next restart allowed in $((TS_CLOUD_WAIT - TS_CLOUD_ELAPSED))s ($TS_CLOUD_WHY on ${y})"`," exit 0"," fi","fi","TS_CLOUD_STREAK=$((TS_CLOUD_STREAK + 1))",`logger -t ${v} "no HTTP response on ${y} after $TS_CLOUD_FAILS checks ($TS_CLOUD_WHY); restarting $TS_CLOUD_UNIT (liveness restart $TS_CLOUD_STREAK in a row)"`,'echo "$TS_CLOUD_STREAK $TS_CLOUD_NOW" > "$TS_CLOUD_STATE.restarts"','rm -f "$TS_CLOUD_STATE.fail"','systemctl restart "$TS_CLOUD_UNIT"',"TS_CLOUD_LIVENESS_EOF",`chmod +x ${_}`,`rm -f ${S}.fail ${S}.restarts`,`cat > /etc/systemd/system/${t}-liveness.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=Liveness check for ${t} (managed by ts-cloud)`,"","[Service]","Type=oneshot",`ExecStart=${_}`,"TS_CLOUD_UNIT_EOF",`cat > /etc/systemd/system/${t}-liveness.timer <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=Run the ${t} liveness check every ${i}s`,"","[Timer]",`OnUnitActiveSec=${i}s`,`OnBootSec=${i}s`,"Persistent=true","","[Install]","WantedBy=timers.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",`systemctl enable --now ${t}-liveness.timer >/dev/null 2>&1 || true`]}var Bs=20,Tn=3,Qa=5,ec=60;function tc(e){let{paths:t,unitBase:r,releaseId:n,port:s}=e,i=`${r}@${n}.service`,a=`${r}.service`,c=Math.max(1,e.healthGateSeconds??5),u=e.healthCheckPath?e.healthCheckPath.startsWith("/")?e.healthCheckPath:`/${e.healthCheckPath}`:null,f=u?`curl -sf -o /dev/null --max-time ${Qa} "http://127.0.0.1:${s}${u}"`:null,h=(_)=>`{ echo "[ts-cloud] release ${n} ${_}" >&2; ts_cloud_restore_previous; exit 1; }`;return[`TS_CLOUD_OLD_UNITS=$(systemctl list-units --plain --no-legend --type=service "${r}@*.service" 2>/dev/null | awk '{print $1}' | grep -v "^${i}$" || true)`,`TS_CLOUD_PREV_CURRENT="$(readlink ${t.current} 2>/dev/null || true)"`,"TS_CLOUD_LEGACY_STOPPED=0","ts_cloud_restore_previous() {",` journalctl -u ${i} -n 50 --no-pager >&2 || true`,` systemctl stop ${i} 2>/dev/null || true`,` systemctl disable ${i} 2>/dev/null || true`,` if [ -n "$TS_CLOUD_PREV_CURRENT" ] && [ -d "$TS_CLOUD_PREV_CURRENT" ]; then ln -sfn "$TS_CLOUD_PREV_CURRENT" ${t.current}.tmp && mv -Tf ${t.current}.tmp ${t.current}; fi`,' for TS_CLOUD_RU in ${TS_CLOUD_OLD_UNITS}; do systemctl enable "$TS_CLOUD_RU" 2>/dev/null || true; systemctl start "$TS_CLOUD_RU" 2>/dev/null || true; done',` if [ "$TS_CLOUD_LEGACY_STOPPED" -eq 1 ]; then systemctl start ${a} 2>/dev/null || true; fi`,' if [ -n "$TS_CLOUD_OLD_UNITS" ] || [ "$TS_CLOUD_LEGACY_STOPPED" -eq 1 ]; then echo "[ts-cloud] previous release restored and serving" >&2; else echo "[ts-cloud] there was no previous release to restore" >&2; fi',"}",`if [ -f /etc/systemd/system/${a} ] && systemctl is-active --quiet ${a}; then echo "[ts-cloud] retiring pre-zero-downtime unit ${a} (one-time restart cutover)"; systemctl stop ${a}; TS_CLOUD_LEGACY_STOPPED=1; fi`,'TS_CLOUD_STARTED_AT="@$(date +%s)"',`systemctl restart ${i}`,`TS_CLOUD_GATE_OK=1; for TS_CLOUD_I in $(seq 1 ${c}); do sleep 1; systemctl is-active --quiet ${i} || { TS_CLOUD_GATE_OK=0; break; }; done`,'if [ "$TS_CLOUD_GATE_OK" -ne 1 ]; then',` if journalctl -u ${i} --since "$TS_CLOUD_STARTED_AT" -o cat --no-pager 2>/dev/null | grep -iE 'EADDRINUSE|address already in use|port [0-9]+ (is )?in use|Failed to start server' >/dev/null; then`,` echo "[ts-cloud] release ${n} could not share :${s} with the previous release (no SO_REUSEPORT?) — retiring it and retrying" >&2`,' for TS_CLOUD_RU in ${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_RU" 2>/dev/null || true; done',` systemctl restart ${i}`,` for TS_CLOUD_I in $(seq 1 ${c}); do sleep 1; systemctl is-active --quiet ${i} || ${h("failed its health gate on the free port")}; done`," else",` ${h("crashed on start — the previous release was never stopped")}`," fi","fi",`if ss -ltnpH "sport = :${s}" >/dev/null 2>&1; then`," TS_CLOUD_BOUND=0",` for TS_CLOUD_I in $(seq 1 ${ec}); do`,` TS_CLOUD_NEW_PID="$(systemctl show -p MainPID --value ${i} 2>/dev/null || true)"`,` if [ -n "$TS_CLOUD_NEW_PID" ] && [ "$TS_CLOUD_NEW_PID" != "0" ] && ss -ltnpH "sport = :${s}" 2>/dev/null | grep "pid=$TS_CLOUD_NEW_PID," >/dev/null; then TS_CLOUD_BOUND=1; break; fi`,` systemctl is-active --quiet ${i} || break`,` sleep ${Tn}`," done",` [ "$TS_CLOUD_BOUND" -eq 1 ] || ${h(`never took :${s}`)}`,"else",' echo "[ts-cloud] cannot read listener PIDs on this host — the response probes run without the bind check" >&2',"fi",...f?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${Bs}); do if ${f}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${Tn}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${h(`never answered ${u}`)}`]:[],...ct(t),`systemctl enable ${i} 2>/dev/null || true`,'for TS_CLOUD_U in ${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done',`TS_CLOUD_LISTENING=0; for TS_CLOUD_I in $(seq 1 ${c}); do if ss -ltnH "sport = :${s}" 2>/dev/null | grep . >/dev/null; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done`,`if [ "$TS_CLOUD_LISTENING" -ne 1 ]; then echo "[ts-cloud] nothing is listening on ${s} after retiring the previous release — restarting ${i} on the now-free port" >&2; systemctl restart ${i}; for TS_CLOUD_I in $(seq 1 ${c}); do if ss -ltnH "sport = :${s}" 2>/dev/null | grep . >/dev/null; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done; fi`,`[ "$TS_CLOUD_LISTENING" -eq 1 ] || ${h(`is active but never bound :${s}`)}`,...f?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${Bs}); do if ${f}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${Tn}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${h(`stopped answering ${u} once it served alone`)}`]:[],...vn(t),`systemctl list-unit-files --plain --no-legend "${r}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v -e "^${i}$" -e "^${r}@\\.service$" || true; } | while read -r TS_CLOUD_U; do systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done`,`if [ -f /etc/systemd/system/${a} ]; then systemctl disable ${a} 2>/dev/null || true; rm -f /etc/systemd/system/${a}; systemctl daemon-reload; fi`]}function si(e){let{siteName:t,slug:r,artifactFetch:n,releaseId:s,execStart:i,envEntries:a,port:c,keepReleases:u=Rt,preStartCommands:f=[],healthCheckPath:h,healthGateSeconds:_=5,liveness:S,memoryHigh:v="auto",memoryMax:y,cpuWeight:b,ioWeight:I,tasksMax:D,stopTimeout:H}=e,R=[...b!=null?[`CPUWeight=${b}`]:[],...I!=null?[`IOWeight=${I}`]:[],...D!=null?[`TasksMax=${D}`]:[],...H?[`TimeoutStopSec=${H}`]:[]],x=e.zeroDowntime??c!=null,W=e.appDir??`/var/www/${t}`,k=Yt(W,s),V=`${r}-${t}`,te=`${V}.service`,ue=ai(r,t,s),me=e.sharedPaths??[],Z=xs([".env",...me,...mr(a,me)]),pe=ar(a),ne=f.length>0?[`cd ${k.release}`,...f]:[],ee=["set -euo pipefail",...mn(k),gn(k),...n,...Ot(k,Z),...fn(k),`tar xzf ${ue} -C "$TS_CLOUD_STAGED"`,`rm -f ${ue}`,`cat > ${k.shared}/.env <<'TS_CLOUD_ENV_EOF'`,pe,"TS_CLOUD_ENV_EOF",`chmod 600 ${k.shared}/.env`,...hn(k),`find ${k.release} -maxdepth 1 \\( -type f -o -type l \\) -name '.env*' ! -name '.env.example' ! -name '*.example' -delete`,`sed -i -E '/^[[:space:]]*(PORT|PORT_BACKEND|PORT_ADMIN|PORT_FRONTEND)[[:space:]]*=/d' ${k.shared}/.env 2>/dev/null || true`,...ur(k,Z),...ne];if(x&&c!=null){let ge=`${V}@${s}.service`,T=h?h.startsWith("/")?h:`/${h}`:null;return[...ee,`cat > /etc/systemd/system/${V}@.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} release %i (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${k.releases}/%i`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...v&&v!=="auto"?[`MemoryHigh=${v}`]:[],...y?[`MemoryMax=${y}`]:[],...R,`EnvironmentFile=${k.releases}/%i/.env`,`Environment=PORT=${c}`,`Environment=STX_IMAGE_CACHE_DIR=${lr(k)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...v==="auto"?Fs(`${V}@.service`):[...fr(`${V}@.service`),...wn()],...Za(ge),...tc({paths:k,unitBase:V,releaseId:s,port:c,healthCheckPath:T,healthGateSeconds:_}),...lt(k,u),...S===!1?[]:zs({...S,unitBase:V,unitPattern:`${V}@*.service`,port:c,path:S?.path??h})]}return[...ee,`cat > /etc/systemd/system/${te} <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${k.current}`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...v&&v!=="auto"?[`MemoryHigh=${v}`]:[],...y?[`MemoryMax=${y}`]:[],...R,`EnvironmentFile=${k.current}/.env`,...c?[`Environment=PORT=${c}`]:[],`Environment=STX_IMAGE_CACHE_DIR=${lr(k)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...fr(te,{auto:v!=="auto",high:v!=="auto",max:Boolean(y)}),...v==="auto"?Fs(te):wn(),`systemctl enable ${te}`,`TS_CLOUD_PREV_CURRENT="$(readlink ${k.current} 2>/dev/null || true)"`,...ct(k),`systemctl restart ${te}`,`for TS_CLOUD_I in $(seq 1 ${Math.max(1,_)}); do sleep 1; systemctl is-active --quiet ${te} || { echo "[ts-cloud] release ${s} of ${te} did not stay up — restoring the previous release" >&2; journalctl -u ${te} -n 50 --no-pager >&2 || true; if [ -n "$TS_CLOUD_PREV_CURRENT" ] && [ -d "$TS_CLOUD_PREV_CURRENT" ] && [ "$(readlink -f "$TS_CLOUD_PREV_CURRENT")" != "$(readlink -f ${k.release})" ]; then ln -sfn "$TS_CLOUD_PREV_CURRENT" ${k.current}.tmp && mv -Tf ${k.current}.tmp ${k.current}; systemctl restart ${te} || true; fi; exit 1; }; done`,...vn(k),...lt(k,u),...S===!1||!c?[]:zs({...S,unitBase:V,unitPattern:te,port:c,path:S?.path??h})]}function oi(e){let{siteName:t,artifactFetch:r,releaseId:n,keepReleases:s=Rt,preStartCommands:i=[]}=e,a=e.appDir??`/var/www/${t}`,c=Yt(a,n),u=ai(e.slug,t,n),f=i.length>0?[`cd ${c.release}`,...i]:[];return["set -euo pipefail",...mn(c),gn(c),...r,...Ot(c,[]),...fn(c),`tar xzf ${u} -C "$TS_CLOUD_STAGED"`,...hn(c),`rm -f ${u}`,...f,...ct(c),...lt(c,s)]}function ai(e,t,r){return`/tmp/${[e,t,r].filter(Boolean).join("-")}-release.tar.gz`}function Lc(e,t,r,n){return[`aws s3 cp "s3://${e}/${t}" ${n} --region ${r}`]}function $c(e,t){return[`mv "${e}" ${t}`]}function ut(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function hr(e,t,r){return["set -euo pipefail",`chmod 600 ${ut(e)}`,`mv -f -- ${ut(e)} ${ut(t)}`,`cp -- ${ut(t)} ${ut(r)}`].join(`
|
|
160
|
+
`)}function Sr(e){return`rm -f -- ${ut(e)} 2>/dev/null || true`}function Cn(e={}){let t=Math.max(1,e.appServers??e.instances??1),r=!!e.servicesServer||t>1,n=t>1||!!e.server?.loadBalancer;return{appServers:t,loadBalancer:n,dedicatedServices:r,servicesOnApp:!r}}function Ks(e,t){let r={REDIS_HOST:e,MEILISEARCH_HOST:`http://${e}:7700`};if(t?.name){if(r.DB_CONNECTION=t.engine==="postgres"?"pgsql":"mysql",r.DB_HOST=e,r.DB_PORT=String(t.port??(t.engine==="postgres"?5432:3306)),r.DB_DATABASE=t.name,t.username)r.DB_USERNAME=t.username;if(t.password)r.DB_PASSWORD=t.password}return r}function Pn(e){let t=e.infrastructure?.compute??{},r=g(e);return[...Qt(t.managedServices??{mysql:!0,redis:!0},{bindPrivate:!0}),...ot(r,t.managedServices??{mysql:!0}),...Ue(!0),...xe(!0),...it(t.sshKeys),...We(e.notifications),...t.backups?.enabled?[...rr({database:r,backups:t.backups})]:[]]}var Ut=["-S","ssh"];function ci(e={},t="ssh"){let r=[];if(e.identityFile)r.push("-i",e.identityFile);if(e.port)r.push(t==="scp"?"-P":"-p",String(e.port));return r.push("-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR","-o",`ConnectTimeout=${e.connectTimeoutSec??10}`),r}async function Fr(e,t,r={}){let n=Bun.spawn(["ssh",...ci(r),`${r.user??"root"}@${e}`,t],{stdout:"pipe",stderr:"pipe"}),[s,i]=await Promise.all([new Response(n.stdout).text(),new Response(n.stderr).text()]);return{code:await n.exited,stdout:s,stderr:i}}async function Se(e,t,r={}){let n=await Fr(e,t,r);if(n.code!==0)throw Error(`ssh \`${t}\` on ${e} failed (${n.code}): ${n.stderr.trim()||n.stdout.trim()}`);return n.stdout}async function Mc(e,t,r,n={}){let s=Bun.spawn(["scp",...Ut,...ci(n,"scp"),...t,`${n.user??"root"}@${e}:${r}`],{stdout:"pipe",stderr:"pipe"}),i=await s.exited;if(i!==0){let a=await new Response(s.stderr).text();throw Error(`scp to ${e}:${r} failed (${i}): ${a.trim()}`)}}async function ft(e,t={}){let r=t.timeoutMs??180000,n=t.pollIntervalMs??5000,s=Date.now();while(Date.now()-s<r){let i=await Fr(e,"echo ready",t);if(i.code===0&&i.stdout.includes("ready"))return;await new Promise((a)=>setTimeout(a,n))}throw Error(`SSH not ready on ${e} after ${r}ms`)}async function Fc(e,t={}){let r=t.timeoutMs??300000,n=t.pollIntervalMs??5000,s=Date.now();while(Date.now()-s<r){let i=await Fr(e,"cloud-init status 2>/dev/null || echo unknown",t);if(i.stdout.includes("status: done"))return;if(i.stdout.includes("status: error"))throw Error(`cloud-init reported an error on ${e}; check /var/log/cloud-init-output.log`);await new Promise((a)=>setTimeout(a,n))}throw Error(`cloud-init did not finish on ${e} after ${r}ms`)}function di(e={}){return["set -e","ts_cloud_script=$(mktemp /tmp/ts-cloud-deploy.XXXXXXXX)",`trap 'rm -f "$ts_cloud_script"' EXIT`,'cat > "$ts_cloud_script"',e.sudo?'sudo -n -H bash "$ts_cloud_script" < /dev/null':'bash "$ts_cloud_script" < /dev/null'].join(`
|
|
161
|
+
`)}var Uc=di();import{homedir as rc}from"node:os";import{join as nc}from"node:path";var vr={location:"fsn1",image:"ubuntu-24.04",sshUser:"root",sshPrivateKeyPath:"~/.ssh/id_ed25519"};function yr(e){return e.startsWith("~/")?nc(rc(),e.slice(2)):e}function pt(...e){for(let t of e){let r=process.env[t]?.trim();if(r)return r}return}function dt(...e){for(let t of e){let r=t?.trim();if(r)return r}return}function Ht(e,t){return dt(e,t?.hetzner?.apiToken,pt("HCLOUD_TOKEN","HETZNER_API_TOKEN"))}function Qc(e,t){return dt(t,e?.hetzner?.location,pt("HCLOUD_LOCATION","HETZNER_LOCATION"))??vr.location}function kt(e,t){let r=e?.infrastructure?.compute;return dt(t,r?.image,e?.hetzner?.image,pt("HCLOUD_IMAGE","HETZNER_IMAGE"))??vr.image}function sc(e,t){return dt(t,e?.hetzner?.sshUser,pt("HCLOUD_SSH_USER","HETZNER_SSH_USER"))??vr.sshUser}function js(e,t){return yr(dt(t,e?.hetzner?.sshPrivateKeyPath,pt("HCLOUD_SSH_KEY","HETZNER_SSH_KEY"))??vr.sshPrivateKeyPath)}function oc(e,t,r){let n=dt(t,e?.hetzner?.sshPublicKeyPath,pt("HCLOUD_SSH_PUBLIC_KEY","HETZNER_SSH_PUBLIC_KEY"));if(n)return yr(n);return`${r??js(e)}.pub`}function Vs(e,t={}){let r=js(e,t.sshPrivateKeyPath);return{apiToken:Ht(t.apiToken,e),location:Qc(e,t.location),image:kt(e,t.image),sshUser:sc(e,t.sshUser),sshPrivateKeyPath:r,sshPublicKeyPath:oc(e,t.sshPublicKeyPath,r)}}var ic="https://api.hetzner.cloud/v1";class br extends Error{status;code;details;constructor(e,t,r,n){super(e);this.status=t;this.code=r;this.details=n;this.name="HetznerApiError"}}class Tr extends Error{action;constructor(e,t){super(e);this.action=t;this.name="HetznerActionError"}}class Ur{name="hetzner";apiToken;baseUrl;fetchImpl;constructor(e){this.apiToken=e.apiToken,this.baseUrl=e.baseUrl??ic,this.fetchImpl=e.fetchImpl??fetch}async request(e,t,r){let n=await this.fetchImpl(`${this.baseUrl}${t}`,{method:e,headers:{Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},body:r===void 0?void 0:JSON.stringify(r)}),s=await n.text(),i;try{i=s?JSON.parse(s):{}}catch{if(!n.ok){let a=s.trim().slice(0,200)||n.statusText||"Hetzner API error";throw Error(`Hetzner API ${e} ${t} (${n.status}): ${a}`)}throw Error(`Hetzner API ${e} ${t}: unexpected non-JSON response`)}if(!n.ok){let a=i.error?.message||n.statusText||"Hetzner API error",c=i.error?.code?` [${i.error.code}]`:"";throw new br(`Hetzner API ${e} ${t} (${n.status})${c}: ${a}`,n.status,i.error?.code,i.error?.details)}return i}async requestAll(e,t){let r=[],n=1;for(;;){let s=e.includes("?")?"&":"?",i=await this.request("GET",`${e}${s}per_page=50&page=${n}`);r.push(...i[t]??[]);let a=i.meta?.pagination?.next_page;if(!a)return r;n=a}}async listServers(){return this.requestAll("/servers","servers")}async getServer(e){return(await this.request("GET",`/servers/${e}`)).server}async listVolumes(){return this.requestAll("/volumes","volumes")}async getVolume(e){return(await this.request("GET",`/volumes/${e}`)).volume}async createVolume(e){return this.request("POST","/volumes",{...e,automount:!1})}async attachVolume(e,t){return(await this.request("POST",`/volumes/${e}/actions/attach`,{server:t,automount:!1})).action}async resizeVolume(e,t){return(await this.request("POST",`/volumes/${e}/actions/resize`,{size:t})).action}async protectVolume(e,t){return(await this.request("POST",`/volumes/${e}/actions/change_protection`,{delete:t})).action}async getServerMetrics(e,t){let r=new URLSearchParams({type:t.types.join(","),start:t.start.toISOString(),end:t.end.toISOString(),step:String(Math.max(60,Math.floor(t.step??60)))});return(await this.request("GET",`/servers/${e}/metrics?${r}`)).metrics}async listServerTypes(e){let t=e?`?name=${encodeURIComponent(e)}`:"";return this.requestAll(`/server_types${t}`,"server_types")}async getServerType(e){return(await this.listServerTypes(e)).find((t)=>t.name===e)??null}async createServer(e){let t=await this.request("POST","/servers",{name:e.name,server_type:e.serverType,image:e.image,location:e.location,datacenter:e.datacenter,ssh_keys:e.sshKeys,user_data:e.userData,labels:e.labels,firewalls:e.firewalls,networks:e.networks,start_after_create:!0});return{server:t.server,action:t.action}}async listNetworks(){return this.requestAll("/networks","networks")}async createNetwork(e){let t=e.ipRange??"10.0.0.0/16";return(await this.request("POST","/networks",{name:e.name,ip_range:t,subnets:[{type:"cloud",ip_range:t,network_zone:"eu-central"}],labels:e.labels})).network}async deleteNetwork(e){await this.request("DELETE",`/networks/${e}`)}async listLoadBalancers(){return this.requestAll("/load_balancers","load_balancers")}async createLoadBalancer(e){return(await this.request("POST","/load_balancers",{name:e.name,load_balancer_type:e.type??"lb11",location:e.location,network_zone:e.network?void 0:e.networkZone??"eu-central",network:e.network,labels:e.labels,targets:[{type:"label_selector",label_selector:{selector:e.labelSelector},use_private_ip:!!e.network}],services:e.services.map((r)=>({protocol:r.protocol??"tcp",listen_port:r.listenPort,destination_port:r.destinationPort,health_check:{protocol:"http",port:80,interval:15,timeout:10,retries:3,http:{path:"/",status_codes:["2??","3??"]}}}))})).load_balancer}async deleteLoadBalancer(e){await this.request("DELETE",`/load_balancers/${e}`)}async deleteServer(e){return(await this.request("DELETE",`/servers/${e}`)).action}async listFirewalls(){return this.requestAll("/firewalls","firewalls")}async createFirewall(e){let t=await this.request("POST","/firewalls",{name:e.name,rules:e.rules,labels:e.labels,apply_to:e.applyTo});return{firewall:t.firewall,actions:t.actions}}async setFirewallRules(e,t){return(await this.request("POST",`/firewalls/${e}/actions/set_rules`,{rules:t})).actions??[]}async deleteFirewall(e){await this.request("DELETE",`/firewalls/${e}`)}async applyFirewallToResources(e,t){return(await this.request("POST",`/firewalls/${e}/actions/apply_to_resources`,{apply_to:t})).actions}async listSshKeys(){return this.requestAll("/ssh_keys","ssh_keys")}async createSshKey(e){return(await this.request("POST","/ssh_keys",{name:e.name,public_key:e.publicKey,labels:e.labels})).ssh_key}async deleteSshKey(e){await this.request("DELETE",`/ssh_keys/${e}`)}async getAction(e){return(await this.request("GET",`/actions/${e}`)).action}async shutdownServer(e){return(await this.request("POST",`/servers/${e}/actions/shutdown`,{})).action}async powerOnServer(e){return(await this.request("POST",`/servers/${e}/actions/poweron`,{})).action}async changeServerType(e,t,r){return(await this.request("POST",`/servers/${e}/actions/change_type`,{server_type:t,upgrade_disk:r})).action}async powerOffServer(e){return(await this.request("POST",`/servers/${e}/actions/poweroff`,{})).action}async stopServer(e,t){if((await this.getServer(e)).status==="off")return;await this.shutdownServer(e);let n=t?.gracefulWaitMs??120000,s=t?.pollIntervalMs??3000,i=Date.now();while(Date.now()-i<n){if((await this.getServer(e)).status==="off")return;await new Promise((c)=>setTimeout(c,s))}let a=await this.powerOffServer(e);await this.waitForAction(a.id),await this.waitForServerStatus(e,"off")}async renameServer(e,t){return(await this.request("PUT",`/servers/${e}`,{name:t})).server}async listImages(e){let t=e?.type?`?type=${encodeURIComponent(e.type)}`:"";return this.requestAll(`/images${t}`,"images")}async getImage(e){return(await this.request("GET",`/images/${e}`)).image}async createImage(e,t){return this.request("POST",`/servers/${e}/actions/create_image`,{description:t.description,type:t.type??"snapshot",labels:t.labels})}async deleteImage(e){await this.request("DELETE",`/images/${e}`)}async rebuildServer(e,t){return(await this.request("POST",`/servers/${e}/actions/rebuild`,{image:t})).action}async listPrimaryIps(){return this.requestAll("/primary_ips","primary_ips")}async unassignPrimaryIp(e){return(await this.request("POST",`/primary_ips/${e}/actions/unassign`,{})).action}async assignPrimaryIp(e,t){return(await this.request("POST",`/primary_ips/${e}/actions/assign`,{assignee_id:t,assignee_type:"server"})).action}async waitForAction(e,t){let r=t?.pollIntervalMs??2000,n=t?.maxWaitMs??300000,s=Date.now();while(Date.now()-s<n){let i=await this.getAction(e);if(i.status==="success")return i;if(i.status==="error")throw new Tr(i.error?.message||"Hetzner action failed",i);await new Promise((a)=>setTimeout(a,r))}throw Error(`Timed out waiting for Hetzner action ${e}`)}async waitForServerRunning(e,t){let r=t?.pollIntervalMs??3000,n=t?.maxWaitMs??600000,s=Date.now();while(Date.now()-s<n){let i=await this.getServer(e);if(i.status==="running")return i;await new Promise((a)=>setTimeout(a,r))}throw Error(`Timed out waiting for server ${e} to reach running state`)}async waitForServerStatus(e,t,r){let n=r?.pollIntervalMs??3000,s=r?.maxWaitMs??600000,i=Date.now();while(Date.now()-i<s){let a=await this.getServer(e);if(a.status===t)return a;await new Promise((c)=>setTimeout(c,n))}throw Error(`Timed out waiting for server ${e} to reach ${t} state`)}}function Hc(e,t){let r=Ht(e,t);if(!r)throw Error("Hetzner API token required. Set hetzner.apiToken in cloud.config.ts or HCLOUD_TOKEN / HETZNER_API_TOKEN.");return r}function Ve(e){let[t,r]=e.trim().split(/\s+/);return r?`${t} ${r}`:t}function Gs(e){if(!e)return"";return e.endsWith(`
|
|
162
162
|
`)?e:`${e}
|
|
163
163
|
`}function se(e,t={}){let r=t.scriptPath??"/var/lib/cloud/ts-cloud-bootstrap.sh",n=t.permissions??"0755",s=e.split(`
|
|
164
164
|
`).map((i)=>` ${i}`).join(`
|
|
165
165
|
`);return`#cloud-config
|
|
166
|
-
${
|
|
166
|
+
${Gs(t.before)}write_files:
|
|
167
167
|
- path: ${r}
|
|
168
168
|
permissions: '${n}'
|
|
169
169
|
owner: root:root
|
|
@@ -171,7 +171,7 @@ ${Vs(t.before)}write_files:
|
|
|
171
171
|
${s}
|
|
172
172
|
runcmd:
|
|
173
173
|
- [ bash, ${r} ]
|
|
174
|
-
${
|
|
174
|
+
${Gs(t.after)}`}function wr(e){let t=new Set([80,443,...e.sitePorts,...e.allowedPorts??[]]);if(e.allowSsh)t.add(22);return[...t].map((r)=>({direction:"in",protocol:"tcp",port:String(r),source_ips:["0.0.0.0/0","::/0"],description:`ts-cloud port ${r}`}))}var En={micro:"cpx11",small:"cx23",medium:"cx33",large:"cx43",xlarge:"cx53","2xlarge":"ccx33"};function ze(e){if(!e)return En.micro;if(e in En)return En[e];return e}var ae="ts-cloud";function le(e,t,r="app"){return{[`${ae}/project`]:e,[`${ae}/environment`]:t,[`${ae}/role`]:r,[`${ae}/managed-by`]:"ts-cloud"}}function ve(e,t,r,n="app"){return Rn(e,t,r)&&e[`${ae}/role`]===n}function Rn(e,t,r){if(!e)return!1;return e[`${ae}/project`]===t&&e[`${ae}/environment`]===r}function ac(e){return e.location?.name??e.datacenter?.location.name??"unknown"}function gt(e){return typeof e==="number"&&Number.isFinite(e)?e:0}function cc(e,t){if(e.architecture&&t.architecture&&e.architecture!==t.architecture)throw Error(`Cannot resize ${e.name} (${e.architecture}) to ${t.name} (${t.architecture}) in place.`);let r=[];if(gt(t.cores)<gt(e.cores))r.push("CPU");if(gt(t.memory)<gt(e.memory))r.push("memory");if(gt(t.disk)<gt(e.disk))r.push("disk");if(r.length>0)throw Error(`Refusing an in-place downgrade from ${e.name} to ${t.name}: ${r.join(", ")} would shrink.`)}async function Zt(e,t,r,n=!0){let[s,i]=await Promise.all([e.getServer(t),e.getServerType(r)]);if(!i)throw Error(`Hetzner server type ${r} was not found.`);let a=s.server_type,c=a.name===i.name;if(!c)cc(a,i);let u=ac(s),f=i.locations?.find((h)=>h.name===u);return{serverId:t,serverName:s.name,location:u,currentType:a,targetType:i,capacityAvailable:f?.available!==!1,alreadyComplete:c,upgradeDisk:n}}function Qg(e){if(e instanceof br&&e.code==="resource_unavailable")return!0;if(e instanceof Tr){if(e.action.error?.code==="resource_unavailable")return!0;if(/no fitting vhost|placement|free resources/i.test(e.action.error?.message??""))return!0}return/resource_unavailable|no fitting vhost|error during placement|free resources/i.test(e instanceof Error?e.message:String(e))}async function Ae(e,t,r){await e?.onPhase?.(t,r)}async function On(e,t,r){await e.waitForAction(t.id,{pollIntervalMs:r.actionPollIntervalMs,maxWaitMs:r.actionTimeoutMs})}var Cr=async({client:e,hooks:t,actionPollIntervalMs:r,actionTimeoutMs:n,serverPollIntervalMs:s,serverTimeoutMs:i},a,c,u)=>{let f=await e.getServer(a.serverId);if(f.status!=="running"){await Ae(t,u?"recovering":"powering-on",{serverId:a.serverId});let _=await e.powerOnServer(a.serverId);await On(e,_,{actionPollIntervalMs:r,actionTimeoutMs:n}),f=await e.waitForServerRunning(a.serverId,{pollIntervalMs:s,maxWaitMs:i})}await Ae(t,"verifying",{serverId:a.serverId,recovered:u});let h=await t?.afterBoot?.(f,a.targetType,c,{recovered:u});return{server:f,verification:h}};async function li(e){let{client:t,hooks:r}=e,n=e.upgradeDisk??!0;await Ae(r,"planning",{serverId:e.serverId,targetType:e.targetType});let s=await Zt(t,e.serverId,e.targetType,n),i=await t.getServer(s.serverId);if(s.alreadyComplete){let u=await Cr(e,s,e.manifest,!1);return await Ae(r,"complete",{alreadyComplete:!0}),{status:"already-complete",plan:s,verification:u.verification}}if(!s.capacityAvailable&&!e.attemptUnavailable)return await Ae(r,"waiting-capacity",{location:s.location,targetType:s.targetType.name}),{status:"waiting-capacity",plan:s};let a=e.manifest;if(i.status==="off"&&!e.resumeFromOff){let u=await Cr(e,s,void 0,!0);return{status:"recovered",plan:s,server:u.server,verification:u.verification,retryable:!0,error:"Server was already off without a resumable resize checkpoint; powered it back on."}}if(i.status==="running"){await Ae(r,"preflight",{serverId:s.serverId}),a=await r?.preflight?.(i,s.targetType),await Ae(r,"shutting-down",{serverId:s.serverId});let u=await t.shutdownServer(s.serverId);await On(t,u,e),i=await t.waitForServerStatus(s.serverId,"off",{pollIntervalMs:e.serverPollIntervalMs,maxWaitMs:e.serverTimeoutMs})}try{await Ae(r,"resizing",{serverId:s.serverId,from:s.currentType.name,to:s.targetType.name,upgradeDisk:n});let u=await t.changeServerType(s.serverId,s.targetType.name,n);await On(t,u,e)}catch(u){let f=await Cr(e,s,a,!0);return{status:"recovered",plan:s,server:f.server,manifest:a,verification:f.verification,retryable:Qg(u),error:u instanceof Error?u.message:String(u)}}let c=await Cr(e,s,a,!1);if(c.verification&&!c.verification.ok)throw Error(`Resize completed but verification failed: ${(c.verification.failures??[]).join("; ")}`);return await Ae(r,"complete",{serverId:s.serverId,targetType:s.targetType.name}),{status:"completed",plan:s,server:c.server,manifest:a,verification:c.verification}}var lc=String.raw`
|
|
175
175
|
const { readdir, readFile, readlink, stat } = await import('node:fs/promises')
|
|
176
176
|
|
|
177
177
|
const text = (command) => {
|
|
@@ -263,7 +263,7 @@ console.log(JSON.stringify({
|
|
|
263
263
|
persistentData: persistentData.sort(),
|
|
264
264
|
dataCatalog: dataCatalog.sort(),
|
|
265
265
|
}))
|
|
266
|
-
`;function
|
|
266
|
+
`;function uc(e){return`printf %s ${Buffer.from(e).toString("base64")} | base64 -d | bun -`}async function pc(e){let t=await Se(e.host,uc(lc),e);return JSON.parse(t)}async function dc(e,t){let r="";for(let n=1;n<=3;n++){let s=Bun.spawn(["curl","--location","--silent","--show-error","--output","/dev/null","--max-time",String(Math.max(1,Math.ceil(t/1000))),"--write-out","%{http_code}",`https://${e}/`],{stdout:"pipe",stderr:"pipe"}),[i,a,c]=await Promise.all([new Response(s.stdout).text(),new Response(s.stderr).text(),s.exited]),u=Number.parseInt(i.trim(),10);if(c===0&&u>0)return{domain:e,ok:u<500,status:u};if(r=a.trim()||`curl exited ${c}`,n<3)await Bun.sleep(500*n)}return{domain:e,ok:!1,error:r}}async function mc(e,t){let r=[],n=0,s=Array.from({length:Math.min(4,e.length)},async()=>{for(;;){let i=n++,a=e[i];if(!a)return;r[i]=await dc(a,t)}});return await Promise.all(s),r}async function Gc(e){let t=await pc(e),r=await mc(t.routeDomains,e.routeTimeoutMs??15000);return{...t,routeProbes:r}}async function Vc(e){let t=await Gc(e),r=t.routeProbes.filter((n)=>!n.ok);if(t.failedUnits.length>0)throw Error(`Preflight found failed services: ${t.failedUnits.join(", ")}`);if(r.length>0)throw Error(`Preflight found unhealthy routes: ${r.map((n)=>n.domain).join(", ")}`);return await Se(e.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`,e),t}function vt(e,t){let r=new Set(t);return e.filter((n)=>!r.has(n))}function fc(e){return Math.floor((e.memory??0)*1024*1024*1024)}async function gc(e){await Se(e.host,String.raw`set -e
|
|
267
267
|
root_source="$(findmnt -n -o SOURCE /)"
|
|
268
268
|
root_fs="$(findmnt -n -o FSTYPE /)"
|
|
269
269
|
parent="$(lsblk -n -o PKNAME "$root_source" | head -1)"
|
|
@@ -275,18 +275,18 @@ case "$root_fs" in
|
|
|
275
275
|
ext2|ext3|ext4) resize2fs "$root_source" ;;
|
|
276
276
|
xfs) xfs_growfs / ;;
|
|
277
277
|
*) echo "Unsupported root filesystem: $root_fs" >&2; exit 1 ;;
|
|
278
|
-
esac`,e)}async function
|
|
279
|
-
`)).toString("base64");await Se(e.host,`printf %s ${r} | base64 -d | while read -r unit; do [ -z "$unit" ] || systemctl is-active --quiet "$unit" || systemctl start "$unit"; done`,e)}async function qc(e,t,r,n={recovered:!1}){if(await
|
|
280
|
-
`,"utf8"),await
|
|
281
|
-
`))}if(m?.capacityAvailable&&!m.alreadyComplete){let y={host:v[0].publicIp,user:this.sshUser,identityFile:this.sshPrivateKeyPath},b=await Hc({client:this.client,serverId:c.id,targetType:m.targetType.name,upgradeDisk:m.upgradeDisk,hooks:{preflight:()=>Vc(y),afterBoot:(I,D,H,R)=>qc(y,D,H,R)}});if(b.status!=="completed"&&b.status!=="already-complete")throw Error(`Resize did not complete: ${b.status}`)}return h}constructor(e={}){let t=Lt(e.apiToken);if(this.stateOnly=!e.client&&!t&&e.allowStateOnly===!0,!e.client&&!t&&!this.stateOnly)throw Error("Hetzner API token required. Set hetzner.apiToken in cloud.config.ts or HCLOUD_TOKEN / HETZNER_API_TOKEN.");this.client=e.client??new Fr({apiToken:t??""});let r=js(void 0,{sshPrivateKeyPath:e.sshPrivateKeyPath,sshPublicKeyPath:e.sshPublicKeyPath,sshUser:e.sshUser,location:e.location});this.sshPrivateKeyPath=r.sshPrivateKeyPath,this.sshPublicKeyPath=r.sshPublicKeyPath,this.sshUser=r.sshUser,this.location=r.location,this.waitForBoot=e.waitForBoot??!0,this.bootWait={sshIntervalMs:e.bootWait?.sshIntervalMs??5000,sshTimeoutMs:e.bootWait?.sshTimeoutMs??300000,cloudInitIntervalMs:e.bootWait?.cloudInitIntervalMs??5000,cloudInitTimeoutMs:e.bootWait?.cloudInitTimeoutMs??600000}}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e,n=t.project.slug,s=t.infrastructure?.compute;if(!s)throw Error("infrastructure.compute is required to provision Hetzner compute");if(t.cloud?.attachTo)return this.attachToComputeInfrastructure(t.cloud.attachTo,t,r);let i=p(t,r),a=`${n}-${r}-app`,c=s.runtime==="php"||!!s.php,u=$n(s);if(u.dedicatedServices||u.appServers>1)return c?this.provisionFleet(e,u):this.provisionBunFleet(e,u);let m=le(n,r,"app"),h=t.sites||{},S=j(s)?[]:this.collectUpstreamPorts(h),v=`${n}-${r}-app-fw`,{firewall:_}=await this.ensureFirewall(v,m,yr({allowSsh:s.allowSsh!==!1,sitePorts:S,allowedPorts:[...s.firewall?.allowedPorts??[],...vs(t.infrastructure?.sftp),...Xe(C(t,{environment:r}))]})),y=await this.ensureSshKey(n,r,m),b=await Qe(i);if(b?.serverId){let ee=await this.tryGetServer(b.serverId);if(ee&&ee.status!=="off"){if(s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(b,ee)}}let I=await this.findExistingServer(n,r,a);if(I&&I.status!=="off"){let ee={provider:"hetzner",stackName:i,serverId:I.id,serverName:I.name,publicIp:I.public_net.ipv4?.ip,publicIpv6:De(I.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};if(await et(i,ee),s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(ee,I)}let D=w(t,{environment:r}),H=D?.engine==="rpx"?G({proxy:D,config:B(h,{proxy:D,slug:t.project.slug,mail:C(t,{environment:r})}),slug:t.project.slug,bunBin:s.runtime==="node"||s.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,R=Ye(t,{environment:r}),x=s.bakedImage===!0,W=M({runtime:R.runtime,runtimeVersion:R.runtimeVersion,systemPackages:s.systemPackages,database:t.infrastructure?.database,phpProvision:R.phpProvision,servicesProvision:R.servicesProvision,rpxProvision:H,baked:x,swapGb:s.swapGb}),k=se(W),V=ze(s.size),te=Ut(t),{server:ue,action:me}=await this.client.createServer({name:a,serverType:V,image:te,location:t.hetzner?.location||this.location,userData:k,labels:m,sshKeys:y?[y]:void 0,firewalls:[{firewall:_.id}]});await this.client.waitForAction(me.id);let Z=await this.client.waitForServerRunning(ue.id),pe={provider:"hetzner",stackName:i,serverId:Z.id,serverName:Z.name,firewallId:_.id,publicIp:Z.public_net.ipv4?.ip,publicIpv6:De(Z.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};await et(i,pe);let ne=Z.public_net.ipv4?.ip;if(ne&&this.waitForBoot)await this.waitForSshReady(ne),await this.waitForCloudInit(ne);if(s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(pe,Z)}async provisionFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,i=r.infrastructure.compute,a=p(r,n),c=ze(i.size),u=Ut(r),m=r.hetzner?.location||this.location,h=i.bakedImage===!0,S=await Qe(a);if(S?.loadBalancerId){let q=(await this.client.listLoadBalancers().catch(()=>[])).find((N)=>N.id===S.loadBalancerId);if(q)return{appPublicIp:q.public_net?.ipv4?.ip,loadBalancerIp:q.public_net?.ipv4?.ip,servicesPrivateIp:S.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}let v=await this.ensureSshKey(s,n,le(s,n,"app")),_=`${s}-${n}-net`,b=(await this.client.listNetworks().catch(()=>[])).find((E)=>E.name===_)??await this.client.createNetwork({name:_,labels:le(s,n,"app")}),{firewall:I}=await this.ensureFirewall(`${s}-${n}-app-fw`,le(s,n,"app"),yr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),{firewall:D}=await this.ensureFirewall(`${s}-${n}-services-fw`,le(s,n,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[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]}]),H=bn(r),R=se(M({runtime:"php",servicesProvision:H,baked:h,swapGb:i.swapGb})),x=await this.client.listServers().catch(()=>[]),W=[],k=x.find((E)=>_e(E.labels,s,n,"services"));if(!k){let{server:E,action:q}=await this.client.createServer({name:`${s}-${n}-services`,serverType:ze(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:u,location:m,userData:R,labels:le(s,n,"services"),sshKeys:v?[v]:void 0,firewalls:[{firewall:D.id}],networks:[b.id]});await this.client.waitForAction(q.id),k=await this.client.waitForServerRunning(E.id),W.push(E.id)}let V=k.id,te=k.private_net?.[0]?.ip??(await this.client.getServer(V)).private_net?.[0]?.ip,ue=[...Ue(!0),...xe(!0),...it(i.sshKeys),...We(r.notifications)],me=Qt({versions:i.php?.versions,default:i.php?.default,extensions:i.php?.extensions,installNginx:!j(i),optimizeForProduction:i.php?.optimizeForProduction,ini:i.php?.ini}),Z=se(M({runtime:"php",phpProvision:me,servicesProvision:ue,baked:h,swapGb:i.swapGb})),pe=x.filter((E)=>_e(E.labels,s,n,"app")),ne=pe.map((E)=>E.id);if(pe.length>t.appServers)for(let E of pe.slice(t.appServers))await this.client.deleteServer(E.id).catch(()=>{}),ne.splice(ne.indexOf(E.id),1);for(let E=pe.length;E<t.appServers;E++){let{server:q,action:N}=await this.client.createServer({name:`${s}-${n}-app-${E+1}`,serverType:c,image:u,location:m,userData:Z,labels:le(s,n,"app"),sshKeys:v?[v]:void 0,firewalls:[{firewall:I.id}],networks:[b.id]});await this.client.waitForAction(N.id),ne.push(q.id),W.push(q.id)}if(this.waitForBoot&&W.length>0)await Promise.all(W.map(async(E)=>{let N=(await this.client.waitForServerRunning(E)).public_net.ipv4?.ip;if(N)await this.waitForSshReady(N),await this.waitForCloudInit(N)}));let ee=`${s}-${n}-lb`,ge,T;if(t.loadBalancer){let q=(await this.client.listLoadBalancers().catch(()=>[])).find((N)=>N.name===ee)??await this.client.createLoadBalancer({name:ee,location:m,network:b.id,labels:le(s,n,"lb"),labelSelector:`ts-cloud/project=${s},ts-cloud/environment=${n},ts-cloud/role=app`,services:[{listenPort:80,destinationPort:80},{listenPort:443,destinationPort:443}]});T=q.id,ge=q.public_net?.ipv4?.ip}let O=ge??(await this.client.getServer(ne[0]).catch(()=>{return}))?.public_net.ipv4?.ip,K={provider:"hetzner",stackName:a,networkId:b.id,loadBalancerId:T,servicesServerId:V,servicesPrivateIp:te,publicIp:O,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await et(a,K),{appPublicIp:O,loadBalancerIp:ge,servicesPrivateIp:te,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async provisionBunFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,i=r.infrastructure.compute,a=p(r,n),c=ze(i.size),u=Ut(r),m=r.hetzner?.location||this.location,h=i.bakedImage===!0,S=r.sites||{},v=await Qe(a);if(v?.lbServerId){let N=await this.tryGetServer(v.lbServerId);if(N&&N.status!=="off"){let Y=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"},X=await this.findComputeTargets({slug:s,environment:n,role:"app",stackName:a});return this.refreshLbRoutes(N,S,X.map((J)=>({privateIp:J.privateIp,publicIp:J.publicIp})),Y,s),{appPublicIp:N.public_net.ipv4?.ip??v.publicIp,loadBalancerIp:N.public_net.ipv4?.ip??v.publicIp,servicesPrivateIp:v.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}}let _=await this.ensureSshKey(s,n,le(s,n,"app")),y=`${s}-${n}-net`,I=(await this.client.listNetworks().catch(()=>[])).find((N)=>N.name===y)??await this.client.createNetwork({name:y,labels:le(s,n,"app")}),D=this.collectUpstreamPorts(S),{firewall:H}=await this.ensureFirewall(`${s}-${n}-app-fw`,le(s,n,"app"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},...D.map((N)=>({direction:"in",protocol:"tcp",port:String(N),source_ips:[I.ip_range],description:`ts-cloud port ${N} (private, LB-only)`}))]),{firewall:R}=await this.ensureFirewall(`${s}-${n}-lb-fw`,le(s,n,"lb"),yr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),x=await this.client.listServers().catch(()=>[]),W=[],k,V,te=!!i.servicesServer||!!i.managedServices,ue=t.dedicatedServices&&te;if(ue){let{firewall:N}=await this.ensureFirewall(`${s}-${n}-services-fw`,le(s,n,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[I.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[I.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[I.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[I.ip_range]}]),Y=bn(r),X=se(M({runtime:"bun",servicesProvision:Y,baked:h,swapGb:i.swapGb})),J=x.find((P)=>_e(P.labels,s,n,"services"));if(!J){let{server:P,action:L}=await this.client.createServer({name:`${s}-${n}-services`,serverType:ze(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:u,location:m,userData:X,labels:le(s,n,"services"),sshKeys:_?[_]:void 0,firewalls:[{firewall:N.id}],networks:[I.id]});await this.client.waitForAction(L.id),J=await this.client.waitForServerRunning(P.id),W.push(P.id)}k=J.id,V=J.private_net?.[0]?.ip??(await this.client.getServer(k)).private_net?.[0]?.ip}let me=ue?{...i,managedServices:void 0,backups:void 0}:i,Z=Ye({...r,infrastructure:{...r.infrastructure,compute:me}},{environment:n}),pe=se(M({runtime:Z.runtime,runtimeVersion:Z.runtimeVersion,systemPackages:i.systemPackages,database:r.infrastructure?.database,servicesProvision:Z.servicesProvision,baked:h,swapGb:i.swapGb})),ne=x.filter((N)=>_e(N.labels,s,n,"app")),ee=ne.map((N)=>N.id);if(ne.length>t.appServers)for(let N of ne.slice(t.appServers))await this.client.deleteServer(N.id).catch(()=>{}),ee.splice(ee.indexOf(N.id),1);for(let N=ne.length;N<t.appServers;N++){let{server:Y,action:X}=await this.client.createServer({name:`${s}-${n}-app-${N+1}`,serverType:c,image:u,location:m,userData:pe,labels:le(s,n,"app"),sshKeys:_?[_]:void 0,firewalls:[{firewall:H.id}],networks:[I.id]});await this.client.waitForAction(X.id),ee.push(Y.id),W.push(Y.id)}if(this.waitForBoot&&W.length>0)await Promise.all(W.map(async(N)=>{let X=(await this.client.waitForServerRunning(N)).public_net.ipv4?.ip;if(X)await this.waitForSshReady(X),await this.waitForCloudInit(X)}));let ge=[];for(let N of ee){let Y=x.find((X)=>X.id===N);if(!Y||!Y.private_net?.[0]?.ip)Y=await this.client.getServer(N).catch(()=>Y);ge.push({privateIp:Y?.private_net?.[0]?.ip,publicIp:Y?.public_net.ipv4?.ip})}let T=`${s}-${n}-lb`,O,K;if(t.loadBalancer){let N=x.find((X)=>_e(X.labels,s,n,"lb")),Y=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"};if(!N){let X=G({proxy:Y,config:er(S,ge,{proxy:Y,slug:s}),slug:s,bunBin:Z.runtime==="node"||Z.runtime==="deno"?void 0:"/usr/local/bin/bun"}),J=se(M({runtime:"bun",rpxProvision:X,baked:!1})),P=typeof i.loadBalancer==="object"?i.loadBalancer.size:void 0,{server:L,action:ie}=await this.client.createServer({name:T,serverType:ze(P??"micro"),image:u,location:m,userData:J,labels:le(s,n,"lb"),sshKeys:_?[_]:void 0,firewalls:[{firewall:R.id}],networks:[I.id]});if(await this.client.waitForAction(ie.id),N=await this.client.waitForServerRunning(L.id),this.waitForBoot){let re=N.public_net.ipv4?.ip;if(re)await this.waitForSshReady(re),await this.waitForCloudInit(re)}}else this.refreshLbRoutes(N,S,ge,Y,s);O=N.id,K=N.public_net.ipv4?.ip}let E=K??(await this.client.getServer(ee[0]).catch(()=>{return}))?.public_net.ipv4?.ip,q={provider:"hetzner",stackName:a,networkId:I.id,lbServerId:O,appServerIds:ee,servicesServerId:k,servicesPrivateIp:V,publicIp:E,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await et(a,q),{appPublicIp:E,loadBalancerIp:K,servicesPrivateIp:V,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async destroyCompute(e){let{config:t,environment:r}=e,n=t.project.slug,s=p(t,r),i=await Qe(s),a=[],c=`${n}-${r}-lb`,m=(await this.client.listLoadBalancers().catch(()=>[])).find((H)=>H.name===c);if(m)try{await this.client.deleteLoadBalancer(m.id),a.push(`load balancer ${c}`)}catch{}let h=await this.client.listServers().catch(()=>[]),S=new Set;for(let H of h)if(_e(H.labels,n,r,"app")||_e(H.labels,n,r,"services")||_e(H.labels,n,r,"lb"))S.add(H.id);if(i?.serverId)S.add(i.serverId);if(i?.servicesServerId)S.add(i.servicesServerId);if(i?.lbServerId)S.add(i.lbServerId);for(let H of i?.appServerIds??[])S.add(H);for(let H of S)try{await this.client.deleteServer(H),a.push(`server ${H}`)}catch{}let v=await this.client.listFirewalls().catch(()=>[]);for(let H of[`${n}-${r}-app-fw`,`${n}-${r}-services-fw`,`${n}-${r}-lb-fw`]){let R=v.find((x)=>x.name===H);if(!R)continue;for(let x=0;x<12;x++)try{await this.client.deleteFirewall(R.id),a.push(`firewall ${H}`);break}catch{await this.sleep(3000)}}let _=`${n}-${r}-net`,b=(await this.client.listNetworks().catch(()=>[])).find((H)=>H.name===_);if(b)for(let H=0;H<12;H++)try{await this.client.deleteNetwork(b.id),a.push(`network ${_}`);break}catch{await this.sleep(3000)}let D=(await this.client.listSshKeys().catch(()=>[])).filter((H)=>wn(H.labels,n,r));for(let H of D)try{await this.client.deleteSshKey(H.id),a.push(`ssh key ${H.name}`)}catch{}return await et(s,{provider:"hetzner",stackName:s}).catch(()=>{}),{destroyed:a}}async getComputeOutputs(e){let t=p(e.config,e.environment),r=await Qe(t);if(r?.serverId){let i=await this.tryGetServer(r.serverId);if(i)return this.outputsFromState(r,i)}if(r?.lbServerId){let a=(await this.tryGetServer(r.lbServerId))?.public_net.ipv4?.ip??r.publicIp;return{...this.outputsFromState(r),appPublicIp:a,loadBalancerIp:a}}if(r?.loadBalancerId||r?.servicesPrivateIp)return this.outputsFromState(r);let s=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:p(e.config,e.environment)}))[0];return{deployStoragePath:"/var/ts-cloud/staging",appInstanceId:s?.id,appPublicIp:s?.publicIp,sshUser:this.sshUser}}async uploadRelease(e){let t=e.targets?.length?e.targets:await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:p(e.config,e.environment)});if(t.length===0)throw Error("No Hetzner compute targets found for release upload");let s=`/var/ts-cloud/staging/${`${e.remoteKey.replace(/^releases\//,"").replace(/\.tar\.gz$/,"").replace(/\//g,"-")}-${Ws()}.tar.gz`}`,i=await Cc(e.localPath),a=Lr,c=`${a}/${i}.tar.gz`;for(let u of t){if(!u.publicIp)throw Error(`Target ${u.id} has no public IP for SCP upload`);let m=["set -euo pipefail",`mkdir -p ${Ht(a)} /var/ts-cloud/staging`,`test -s ${Ht(c)}`,`cp -- ${Ht(c)} ${Ht(s)}`].join(`
|
|
282
|
-
`);try{this.sshExec(u.publicIp,
|
|
283
|
-
`),r=[];for(let s of e.targets){if(!s.publicIp){r.push({instanceId:s.id,status:"Failed",error:"Missing public IP"});continue}try{let i=this.sshExec(s.publicIp,t);
|
|
284
|
-
`))}async findExistingServer(e,t,r){let n=await this.client.listServers(),s=n.find((a)=>
|
|
285
|
-
${s}`);if(/status:\s*(?:done|degraded)/.test(s))return}catch(s){if(s instanceof Error&&/cloud-init reported an error/.test(s.message))throw s}await this.sleep(t)}throw Error(`Timed out waiting for cloud-init to finish on ${e} after ${r}ms`)}outputsFromState(e,t){return{deployStoragePath:e.deployStoragePath||"/var/ts-cloud/staging",appInstanceId:e.serverId?String(e.serverId):void 0,appPublicIp:t?.public_net.ipv4?.ip||e.publicIp,appPublicIpv6:De(t?.public_net.ipv6?.ip)||e.publicIpv6,sshUser:e.sshUser||this.sshUser,servicesPrivateIp:e.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(e,t=[]){return["-i",this.sshPrivateKeyPath,...Pe.SSH_HOST_KEY_OPTS,...Pe.SSH_KEEPALIVE_OPTS,"-o","BatchMode=yes",...t,`${this.sshUser}@${e}`]}scpToHost(e,t,r){let n=["scp",...
|
|
286
|
-
`);try{let r=Bun.spawn(["bash","-c",t],{stdout:"pipe",stderr:"pipe",env:process.env}),[n,s,i]=await Promise.all([new Response(r.stdout).text(),new Response(r.stderr).text(),r.exited]);return{success:i===0,instanceCount:1,perInstance:[{instanceId:"localhost",status:i===0?"Success":"Failed",output:n,error:s}]}}catch(r){return{success:!1,instanceCount:1,perInstance:[{instanceId:"localhost",status:"Failed",error:r?.message??String(r)}],error:r?.message??String(r)}}}}function zc(){let e=process.env.TS_CLOUD_DASHBOARD_BOX;return e!=null&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}import{createHash as
|
|
287
|
-
`).find((i)=>i&&!i.startsWith("#"))?.trim().split(/\s+/);if(n.code!==0||!s?.[1]||!s[2])throw Error(`SSH host-key scan failed: ${n.stderr.trim()||"no key returned"}`);return{algorithm:s[1],key:s[2]}}function Wc(e,t=22){return t===22?e:`[${e}]:${t}`}function
|
|
288
|
-
`)){let i=s.trim();if(!i||i.startsWith("#")||i.startsWith("@"))continue;let[a,c,u]=i.split(/\s+/);if(!a||!c||!u)continue;if(a.split(",").includes(n))return{algorithm:c,key:u}}return null}function Jc(e=process.cwd()){return l(e,"ssh","known_hosts")}async function
|
|
289
|
-
`,{mode:384})}class
|
|
278
|
+
esac`,e)}async function hc(e,t){let r=Buffer.from(t.join(`
|
|
279
|
+
`)).toString("base64");await Se(e.host,`printf %s ${r} | base64 -d | while read -r unit; do [ -z "$unit" ] || systemctl is-active --quiet "$unit" || systemctl start "$unit"; done`,e)}async function qc(e,t,r,n={recovered:!1}){if(await ft(e.host,{...e,timeoutMs:e.sshTimeoutMs??600000}),!n.recovered)await gc(e);if(r)await hc(e,r.runningServices);let s=await Gc(e),i=[],a=r?vt(r.runningServices,s.runningServices):[],c=r?vt(r.releaseLinks,s.releaseLinks):[],u=r?vt(r.routeFragments,s.routeFragments):[],f=r?vt(r.routeIds,s.routeIds):[],h=r?.persistentData.map((x)=>x.split("=")[0])??[],_=s.persistentData.map((x)=>x.split("=")[0]),S=vt(h,_),v=r?vt(r.dataCatalog,s.dataCatalog):[],y=s.routeProbes.filter((x)=>!x.ok),b=n.recovered&&r?r.cpuCores:t.cores??0,I=n.recovered&&r?r.memoryBytes:fc(t),D=s.cpuCores>=b,H=s.memoryBytes>=I*0.9,R=n.recovered||s.rootDiskBytes>=(t.disk??0)*1e9*0.95;if(s.failedUnits.length>0)i.push(`Failed services: ${s.failedUnits.join(", ")}`);if(a.length>0)i.push(`Services did not return: ${a.join(", ")}`);if(c.length>0)i.push(`Release links changed: ${c.join(", ")}`);if(u.length>0)i.push(`Route manifests changed: ${u.join(", ")}`);if(f.length>0)i.push(`Routes disappeared: ${f.join(", ")}`);if(S.length>0)i.push(`Persistent data paths disappeared: ${S.join(", ")}`);if(v.length>0)i.push(`Databases or volumes disappeared: ${v.join(", ")}`);if(y.length>0)i.push(`Unhealthy routes: ${y.map((x)=>x.domain).join(", ")}`);if(!D)i.push(`Expected at least ${b} CPU cores, found ${s.cpuCores}`);if(!H)i.push(`Expected at least ${I} bytes of RAM`);if(!R)i.push(`Expected approximately ${t.disk??0} GB root disk`);return{ok:i.length===0,checks:{cpuCores:s.cpuCores,memoryBytes:s.memoryBytes,rootDiskBytes:s.rootDiskBytes,rootFilesystemBytes:s.rootFilesystemBytes,runningServices:s.runningServices.length,releaseLinks:s.releaseLinks.length,routeFragments:s.routeFragments.length,routes:s.routeIds.length,healthyRoutes:s.routeProbes.filter((x)=>x.ok).length,persistentDataPaths:s.persistentData.length,databasesAndVolumes:s.dataCatalog.length,failedUnits:s.failedUnits.length},failures:i}}import{mkdir as Sc,readFile as vc,rename as yc,writeFile as bc}from"node:fs/promises";import{join as qs}from"node:path";var jc="storage/cloud/state";function ht(e=process.cwd()){return il()?l(e,"state"):qs(e,jc)}function qe(e,t=process.cwd()){return qs(ht(t),`${e}.json`)}async function je(e,t=process.cwd()){try{let r=await vc(qe(e,t),"utf8");return JSON.parse(r)}catch{return null}}async function At(e,t,r=process.cwd()){let n=qe(e,r);await Sc(ht(r),{recursive:!0});let s=`${n}.${process.pid}.tmp`;await bc(s,`${JSON.stringify(t,null,2)}
|
|
280
|
+
`,"utf8"),await yc(s,n)}async function Qe(e){return je(e)}async function et(e,t){await At(e,t)}async function ui(e,t,r){let n=r.length?await e.listVolumes():[];return r.map((s)=>{let i=n.filter((f)=>f.name===s.name);if(i.length>1)throw Error(`Ambiguous volume name: ${s.name}`);let a=i[0];if(a&&a.server!==null&&a.server!==t.id)throw Error(`Volume ${a.name} belongs to another server; refusing to detach live storage`);let c=t.location?.name??t.datacenter?.location.name;if(a&&a.location.name!==c)throw Error(`Volume ${a.name} is in ${a.location.name}, server is in ${c}`);if(a&&a.size>s.size)throw Error(`Refusing to shrink volume ${a.name}: ${a.size} GB to ${s.size} GB`);let u=[];if(!a)u.push("create");else{if(a.server===null)u.push("attach");if(a.size<s.size)u.push("grow")}if(!a||a.protection.delete!==(s.deleteProtection!==!1))u.push("protect");return u.push("mount"),{declaration:s,existing:a,actions:u}})}async function gi(e,t,r){let n=[];for(let s of r){let i=s.existing,a=!i;if(!i){let c=await e.createVolume({name:s.declaration.name,size:s.declaration.size,server:t.id,labels:{...t.labels,"ts-cloud/volume":s.declaration.key}});await e.waitForAction(c.action.id);for(let u of c.next_actions??[])await e.waitForAction(u.id);i=await e.getVolume(c.volume.id)}if(i.server===null)await e.waitForAction((await e.attachVolume(i.id,t.id)).id),i=await e.getVolume(i.id);if(i.server!==t.id||i.location.name!==(t.location?.name??t.datacenter?.location.name))throw Error(`Volume attachment verification failed: ${i.name}`);if(i.linux_device!==`/dev/disk/by-id/scsi-0HC_Volume_${i.id}`)throw Error(`Unexpected Hetzner volume device: ${i.name}`);if(i.size<s.declaration.size)await e.waitForAction((await e.resizeVolume(i.id,s.declaration.size)).id);if(i.protection.delete!==(s.declaration.deleteProtection!==!1))await e.waitForAction((await e.protectVolume(i.id,s.declaration.deleteProtection!==!1)).id);n.push({...s.declaration,id:i.id,device:i.linux_device,allowFormat:a})}return n}var Dn=268435456;function Nt(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function Rc(e){let t=wc("sha256");for await(let r of Cc(e))t.update(r);return t.digest("hex")}class Pe{name="hetzner";usesCloudFormation=!1;client;sshPrivateKeyPath;sshPublicKeyPath;sshUser;location;stateOnly;waitForBoot;bootWait;async applyComputeChanges(e){let{config:t,environment:r}=e;if(t.cloud?.attachTo)throw Error("Only the compute owner may reconcile server size and volumes");let n=t.infrastructure?.compute;if(n?.resize&&!n.size)throw Error("compute.resize requires an explicit compute.size");let s=ei(t,r),i=Cn(n??{});if(i.appServers>1||i.dedicatedServices)throw Error("Managed compute volumes currently require a single app server");let a=await this.getComputeOutputs(e);if(!a.appInstanceId)throw Error("No existing compute server found; provision the server first");let c=await this.client.getServer(Number(a.appInstanceId)),u=await ui(this.client,c,s),f=n?.resize&&n.size?await Zt(this.client,c.id,ze(n.size),n.resize.upgradeDisk!==!1):void 0,h={serverId:String(c.id),changes:u.flatMap((y)=>y.actions.map((b)=>({resource:y.declaration.name,action:b,detail:`${y.declaration.size} GB at ${y.declaration.mountPath}`})))};if(n?.deploymentStorage)h.changes.push({resource:n.deploymentStorage.volume,action:"place-deployments",detail:`Reconcile release directories${n.deploymentStorage.includeBackups!==!1?" and deployment backups":""} on the volume; ${n.deploymentStorage.migrateExisting?"verify and migrate existing files":"refuse nonempty directories"}`});if(f&&!f.alreadyComplete)if(!f.capacityAvailable){if(n?.resize?.whenUnavailable!=="keep-current")throw Error(`${f.targetType.name} is unavailable in ${f.location}`);h.waitingForCapacity=`${f.targetType.name} unavailable in ${f.location}; keeping ${c.server_type.name} running`}else h.changes.push({resource:c.name,action:"resize",detail:`${c.server_type.name} to ${f.targetType.name}`});if(e.dryRun)return h;if(h.waitingForCapacity)console.warn(`[ts-cloud] ${h.waitingForCapacity}`);let _=await gi(this.client,c,u),S=[{id:String(c.id),name:c.name,publicIp:c.public_net.ipv4?.ip}],v=[...We(t.notifications),...n?.volumes||n?.deploymentStorage?ti({volumes:_,deploymentStorage:n?.deploymentStorage,webRoot:"/var/www"}):[],...n?.monitoring!==!1?xe(n?.monitoring):[]];if(v.length){let y=await this.runRemoteDeploy({targets:S,commands:v,timeoutSeconds:7200,comment:"ts-cloud apply configured compute storage"});if(!y.success)throw Error(y.error||y.perInstance.map((b)=>b.error||b.output).join(`
|
|
281
|
+
`))}if(f?.capacityAvailable&&!f.alreadyComplete){let y={host:S[0].publicIp,user:this.sshUser,identityFile:this.sshPrivateKeyPath},b=await li({client:this.client,serverId:c.id,targetType:f.targetType.name,upgradeDisk:f.upgradeDisk,hooks:{preflight:()=>Vc(y),afterBoot:(I,D,H,R)=>qc(y,D,H,R)}});if(b.status!=="completed"&&b.status!=="already-complete")throw Error(`Resize did not complete: ${b.status}`)}return h}constructor(e={}){let t=Ht(e.apiToken);if(this.stateOnly=!e.client&&!t&&e.allowStateOnly===!0,!e.client&&!t&&!this.stateOnly)throw Error("Hetzner API token required. Set hetzner.apiToken in cloud.config.ts or HCLOUD_TOKEN / HETZNER_API_TOKEN.");this.client=e.client??new Ur({apiToken:t??""});let r=Vs(void 0,{sshPrivateKeyPath:e.sshPrivateKeyPath,sshPublicKeyPath:e.sshPublicKeyPath,sshUser:e.sshUser,location:e.location});this.sshPrivateKeyPath=r.sshPrivateKeyPath,this.sshPublicKeyPath=r.sshPublicKeyPath,this.sshUser=r.sshUser,this.location=r.location,this.waitForBoot=e.waitForBoot??!0,this.bootWait={sshIntervalMs:e.bootWait?.sshIntervalMs??5000,sshTimeoutMs:e.bootWait?.sshTimeoutMs??300000,cloudInitIntervalMs:e.bootWait?.cloudInitIntervalMs??5000,cloudInitTimeoutMs:e.bootWait?.cloudInitTimeoutMs??600000}}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e,n=t.project.slug,s=t.infrastructure?.compute;if(!s)throw Error("infrastructure.compute is required to provision Hetzner compute");if(t.cloud?.attachTo)return this.attachToComputeInfrastructure(t.cloud.attachTo,t,r);let i=m(t,r),a=`${n}-${r}-app`,c=s.runtime==="php"||!!s.php,u=Cn(s);if(u.dedicatedServices||u.appServers>1)return c?this.provisionFleet(e,u):this.provisionBunFleet(e,u);let f=le(n,r,"app"),h=t.sites||{},_=j(s)?[]:this.collectUpstreamPorts(h),S=`${n}-${r}-app-fw`,{firewall:v}=await this.ensureFirewall(S,f,wr({allowSsh:s.allowSsh!==!1,sitePorts:_,allowedPorts:[...s.firewall?.allowedPorts??[],...ys(t.infrastructure?.sftp),...Xe(C(t,{environment:r}))]})),y=await this.ensureSshKey(n,r,f),b=await Qe(i);if(b?.serverId){let ee=await this.tryGetServer(b.serverId);if(ee&&ee.status!=="off"){if(s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(b,ee)}}let I=await this.findExistingServer(n,r,a);if(I&&I.status!=="off"){let ee={provider:"hetzner",stackName:i,serverId:I.id,serverName:I.name,publicIp:I.public_net.ipv4?.ip,publicIpv6:De(I.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};if(await et(i,ee),s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(ee,I)}let D=w(t,{environment:r}),H=D?.engine==="rpx"?G({proxy:D,config:B(h,{proxy:D,slug:t.project.slug,mail:C(t,{environment:r})}),slug:t.project.slug,bunBin:s.runtime==="node"||s.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,R=Ye(t,{environment:r}),x=s.bakedImage===!0,W=M({runtime:R.runtime,runtimeVersion:R.runtimeVersion,systemPackages:s.systemPackages,database:t.infrastructure?.database,phpProvision:R.phpProvision,servicesProvision:R.servicesProvision,rpxProvision:H,baked:x,swapGb:s.swapGb}),k=se(W),V=ze(s.size),te=kt(t),{server:ue,action:me}=await this.client.createServer({name:a,serverType:V,image:te,location:t.hetzner?.location||this.location,userData:k,labels:f,sshKeys:y?[y]:void 0,firewalls:[{firewall:v.id}]});await this.client.waitForAction(me.id);let Z=await this.client.waitForServerRunning(ue.id),pe={provider:"hetzner",stackName:i,serverId:Z.id,serverName:Z.name,firewallId:v.id,publicIp:Z.public_net.ipv4?.ip,publicIpv6:De(Z.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};await et(i,pe);let ne=Z.public_net.ipv4?.ip;if(ne&&this.waitForBoot)await this.waitForSshReady(ne),await this.waitForCloudInit(ne);if(s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(pe,Z)}async provisionFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,i=r.infrastructure.compute,a=m(r,n),c=ze(i.size),u=kt(r),f=r.hetzner?.location||this.location,h=i.bakedImage===!0,_=await Qe(a);if(_?.loadBalancerId){let q=(await this.client.listLoadBalancers().catch(()=>[])).find((N)=>N.id===_.loadBalancerId);if(q)return{appPublicIp:q.public_net?.ipv4?.ip,loadBalancerIp:q.public_net?.ipv4?.ip,servicesPrivateIp:_.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}let S=await this.ensureSshKey(s,n,le(s,n,"app")),v=`${s}-${n}-net`,b=(await this.client.listNetworks().catch(()=>[])).find((E)=>E.name===v)??await this.client.createNetwork({name:v,labels:le(s,n,"app")}),{firewall:I}=await this.ensureFirewall(`${s}-${n}-app-fw`,le(s,n,"app"),wr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),{firewall:D}=await this.ensureFirewall(`${s}-${n}-services-fw`,le(s,n,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[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]}]),H=Pn(r),R=se(M({runtime:"php",servicesProvision:H,baked:h,swapGb:i.swapGb})),x=await this.client.listServers().catch(()=>[]),W=[],k=x.find((E)=>ve(E.labels,s,n,"services"));if(!k){let{server:E,action:q}=await this.client.createServer({name:`${s}-${n}-services`,serverType:ze(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:u,location:f,userData:R,labels:le(s,n,"services"),sshKeys:S?[S]:void 0,firewalls:[{firewall:D.id}],networks:[b.id]});await this.client.waitForAction(q.id),k=await this.client.waitForServerRunning(E.id),W.push(E.id)}let V=k.id,te=k.private_net?.[0]?.ip??(await this.client.getServer(V)).private_net?.[0]?.ip,ue=[...Ue(!0),...xe(!0),...it(i.sshKeys),...We(r.notifications)],me=nr({versions:i.php?.versions,default:i.php?.default,extensions:i.php?.extensions,installNginx:!j(i),optimizeForProduction:i.php?.optimizeForProduction,ini:i.php?.ini}),Z=se(M({runtime:"php",phpProvision:me,servicesProvision:ue,baked:h,swapGb:i.swapGb})),pe=x.filter((E)=>ve(E.labels,s,n,"app")),ne=pe.map((E)=>E.id);if(pe.length>t.appServers)for(let E of pe.slice(t.appServers))await this.client.deleteServer(E.id).catch(()=>{}),ne.splice(ne.indexOf(E.id),1);for(let E=pe.length;E<t.appServers;E++){let{server:q,action:N}=await this.client.createServer({name:`${s}-${n}-app-${E+1}`,serverType:c,image:u,location:f,userData:Z,labels:le(s,n,"app"),sshKeys:S?[S]:void 0,firewalls:[{firewall:I.id}],networks:[b.id]});await this.client.waitForAction(N.id),ne.push(q.id),W.push(q.id)}if(this.waitForBoot&&W.length>0)await Promise.all(W.map(async(E)=>{let N=(await this.client.waitForServerRunning(E)).public_net.ipv4?.ip;if(N)await this.waitForSshReady(N),await this.waitForCloudInit(N)}));let ee=`${s}-${n}-lb`,ge,T;if(t.loadBalancer){let q=(await this.client.listLoadBalancers().catch(()=>[])).find((N)=>N.name===ee)??await this.client.createLoadBalancer({name:ee,location:f,network:b.id,labels:le(s,n,"lb"),labelSelector:`ts-cloud/project=${s},ts-cloud/environment=${n},ts-cloud/role=app`,services:[{listenPort:80,destinationPort:80},{listenPort:443,destinationPort:443}]});T=q.id,ge=q.public_net?.ipv4?.ip}let O=ge??(await this.client.getServer(ne[0]).catch(()=>{return}))?.public_net.ipv4?.ip,K={provider:"hetzner",stackName:a,networkId:b.id,loadBalancerId:T,servicesServerId:V,servicesPrivateIp:te,publicIp:O,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await et(a,K),{appPublicIp:O,loadBalancerIp:ge,servicesPrivateIp:te,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async provisionBunFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,i=r.infrastructure.compute,a=m(r,n),c=ze(i.size),u=kt(r),f=r.hetzner?.location||this.location,h=i.bakedImage===!0,_=r.sites||{},S=await Qe(a);if(S?.lbServerId){let N=await this.tryGetServer(S.lbServerId);if(N&&N.status!=="off"){let Y=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"},X=await this.findComputeTargets({slug:s,environment:n,role:"app",stackName:a});return this.refreshLbRoutes(N,_,X.map((J)=>({privateIp:J.privateIp,publicIp:J.publicIp})),Y,s),{appPublicIp:N.public_net.ipv4?.ip??S.publicIp,loadBalancerIp:N.public_net.ipv4?.ip??S.publicIp,servicesPrivateIp:S.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}}let v=await this.ensureSshKey(s,n,le(s,n,"app")),y=`${s}-${n}-net`,I=(await this.client.listNetworks().catch(()=>[])).find((N)=>N.name===y)??await this.client.createNetwork({name:y,labels:le(s,n,"app")}),D=this.collectUpstreamPorts(_),{firewall:H}=await this.ensureFirewall(`${s}-${n}-app-fw`,le(s,n,"app"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},...D.map((N)=>({direction:"in",protocol:"tcp",port:String(N),source_ips:[I.ip_range],description:`ts-cloud port ${N} (private, LB-only)`}))]),{firewall:R}=await this.ensureFirewall(`${s}-${n}-lb-fw`,le(s,n,"lb"),wr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),x=await this.client.listServers().catch(()=>[]),W=[],k,V,te=!!i.servicesServer||!!i.managedServices,ue=t.dedicatedServices&&te;if(ue){let{firewall:N}=await this.ensureFirewall(`${s}-${n}-services-fw`,le(s,n,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[I.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[I.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[I.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[I.ip_range]}]),Y=Pn(r),X=se(M({runtime:"bun",servicesProvision:Y,baked:h,swapGb:i.swapGb})),J=x.find((P)=>ve(P.labels,s,n,"services"));if(!J){let{server:P,action:L}=await this.client.createServer({name:`${s}-${n}-services`,serverType:ze(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:u,location:f,userData:X,labels:le(s,n,"services"),sshKeys:v?[v]:void 0,firewalls:[{firewall:N.id}],networks:[I.id]});await this.client.waitForAction(L.id),J=await this.client.waitForServerRunning(P.id),W.push(P.id)}k=J.id,V=J.private_net?.[0]?.ip??(await this.client.getServer(k)).private_net?.[0]?.ip}let me=ue?{...i,managedServices:void 0,backups:void 0}:i,Z=Ye({...r,infrastructure:{...r.infrastructure,compute:me}},{environment:n}),pe=se(M({runtime:Z.runtime,runtimeVersion:Z.runtimeVersion,systemPackages:i.systemPackages,database:r.infrastructure?.database,servicesProvision:Z.servicesProvision,baked:h,swapGb:i.swapGb})),ne=x.filter((N)=>ve(N.labels,s,n,"app")),ee=ne.map((N)=>N.id);if(ne.length>t.appServers)for(let N of ne.slice(t.appServers))await this.client.deleteServer(N.id).catch(()=>{}),ee.splice(ee.indexOf(N.id),1);for(let N=ne.length;N<t.appServers;N++){let{server:Y,action:X}=await this.client.createServer({name:`${s}-${n}-app-${N+1}`,serverType:c,image:u,location:f,userData:pe,labels:le(s,n,"app"),sshKeys:v?[v]:void 0,firewalls:[{firewall:H.id}],networks:[I.id]});await this.client.waitForAction(X.id),ee.push(Y.id),W.push(Y.id)}if(this.waitForBoot&&W.length>0)await Promise.all(W.map(async(N)=>{let X=(await this.client.waitForServerRunning(N)).public_net.ipv4?.ip;if(X)await this.waitForSshReady(X),await this.waitForCloudInit(X)}));let ge=[];for(let N of ee){let Y=x.find((X)=>X.id===N);if(!Y||!Y.private_net?.[0]?.ip)Y=await this.client.getServer(N).catch(()=>Y);ge.push({privateIp:Y?.private_net?.[0]?.ip,publicIp:Y?.public_net.ipv4?.ip})}let T=`${s}-${n}-lb`,O,K;if(t.loadBalancer){let N=x.find((X)=>ve(X.labels,s,n,"lb")),Y=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"};if(!N){let X=G({proxy:Y,config:tr(_,ge,{proxy:Y,slug:s}),slug:s,bunBin:Z.runtime==="node"||Z.runtime==="deno"?void 0:"/usr/local/bin/bun"}),J=se(M({runtime:"bun",rpxProvision:X,baked:!1})),P=typeof i.loadBalancer==="object"?i.loadBalancer.size:void 0,{server:L,action:ie}=await this.client.createServer({name:T,serverType:ze(P??"micro"),image:u,location:f,userData:J,labels:le(s,n,"lb"),sshKeys:v?[v]:void 0,firewalls:[{firewall:R.id}],networks:[I.id]});if(await this.client.waitForAction(ie.id),N=await this.client.waitForServerRunning(L.id),this.waitForBoot){let re=N.public_net.ipv4?.ip;if(re)await this.waitForSshReady(re),await this.waitForCloudInit(re)}}else this.refreshLbRoutes(N,_,ge,Y,s);O=N.id,K=N.public_net.ipv4?.ip}let E=K??(await this.client.getServer(ee[0]).catch(()=>{return}))?.public_net.ipv4?.ip,q={provider:"hetzner",stackName:a,networkId:I.id,lbServerId:O,appServerIds:ee,servicesServerId:k,servicesPrivateIp:V,publicIp:E,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await et(a,q),{appPublicIp:E,loadBalancerIp:K,servicesPrivateIp:V,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async destroyCompute(e){let{config:t,environment:r}=e,n=t.project.slug,s=m(t,r),i=await Qe(s),a=[],c=`${n}-${r}-lb`,f=(await this.client.listLoadBalancers().catch(()=>[])).find((H)=>H.name===c);if(f)try{await this.client.deleteLoadBalancer(f.id),a.push(`load balancer ${c}`)}catch{}let h=await this.client.listServers().catch(()=>[]),_=new Set;for(let H of h)if(ve(H.labels,n,r,"app")||ve(H.labels,n,r,"services")||ve(H.labels,n,r,"lb"))_.add(H.id);if(i?.serverId)_.add(i.serverId);if(i?.servicesServerId)_.add(i.servicesServerId);if(i?.lbServerId)_.add(i.lbServerId);for(let H of i?.appServerIds??[])_.add(H);for(let H of _)try{await this.client.deleteServer(H),a.push(`server ${H}`)}catch{}let S=await this.client.listFirewalls().catch(()=>[]);for(let H of[`${n}-${r}-app-fw`,`${n}-${r}-services-fw`,`${n}-${r}-lb-fw`]){let R=S.find((x)=>x.name===H);if(!R)continue;for(let x=0;x<12;x++)try{await this.client.deleteFirewall(R.id),a.push(`firewall ${H}`);break}catch{await this.sleep(3000)}}let v=`${n}-${r}-net`,b=(await this.client.listNetworks().catch(()=>[])).find((H)=>H.name===v);if(b)for(let H=0;H<12;H++)try{await this.client.deleteNetwork(b.id),a.push(`network ${v}`);break}catch{await this.sleep(3000)}let D=(await this.client.listSshKeys().catch(()=>[])).filter((H)=>Rn(H.labels,n,r));for(let H of D)try{await this.client.deleteSshKey(H.id),a.push(`ssh key ${H.name}`)}catch{}return await et(s,{provider:"hetzner",stackName:s}).catch(()=>{}),{destroyed:a}}async getComputeOutputs(e){let t=m(e.config,e.environment),r=await Qe(t);if(r?.serverId){let i=await this.tryGetServer(r.serverId);if(i)return this.outputsFromState(r,i)}if(r?.lbServerId){let a=(await this.tryGetServer(r.lbServerId))?.public_net.ipv4?.ip??r.publicIp;return{...this.outputsFromState(r),appPublicIp:a,loadBalancerIp:a}}if(r?.loadBalancerId||r?.servicesPrivateIp)return this.outputsFromState(r);let s=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:m(e.config,e.environment)}))[0];return{deployStoragePath:"/var/ts-cloud/staging",appInstanceId:s?.id,appPublicIp:s?.publicIp,sshUser:this.sshUser}}async uploadRelease(e){let t=e.targets?.length?e.targets:await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:m(e.config,e.environment)});if(t.length===0)throw Error("No Hetzner compute targets found for release upload");let s=`/var/ts-cloud/staging/${`${e.remoteKey.replace(/^releases\//,"").replace(/\.tar\.gz$/,"").replace(/\//g,"-")}-${Ys()}.tar.gz`}`,i=await Rc(e.localPath),a=$r,c=`${a}/${i}.tar.gz`;for(let u of t){if(!u.publicIp)throw Error(`Target ${u.id} has no public IP for SCP upload`);let f=["set -euo pipefail",`mkdir -p ${Nt(a)} /var/ts-cloud/staging`,`test -s ${Nt(c)}`,`cp -- ${Nt(c)} ${Nt(s)}`].join(`
|
|
282
|
+
`);try{this.sshExec(u.publicIp,f);continue}catch{}let h=`${a}/.${i}-${Ys()}.tmp`;try{this.scpToHost(u.publicIp,e.localPath,h),this.sshExec(u.publicIp,hr(h,c,s))}catch(_){try{this.sshExec(u.publicIp,Sr(h))}catch{}throw _}}return{artifactRef:s}}async findComputeTargets(e){let t=e.role||"app",r=(i)=>({id:String(i.id),name:i.name,publicIp:i.public_net.ipv4?.ip,publicIpv6:De(i.public_net.ipv6?.ip),privateIp:i.private_net?.[0]?.ip,status:i.status});if(t==="app"||t==="lb"||t==="services"){let i=await Qe(e.stackName??`${e.slug}-${e.environment}`),a=[...new Set(t==="app"?[i?.serverId,...i?.appServerIds??[]]:t==="lb"?[i?.lbServerId]:[i?.servicesServerId])].filter((f)=>typeof f==="number");if(this.stateOnly){if(a.length>0&&i?.publicIp)return a.map((f)=>({id:String(f),name:f===i.serverId?i.serverName:void 0,publicIp:i.publicIp,publicIpv6:i.publicIpv6,status:"running"}));if(t!=="app")return[];throw Error(`Hetzner API token required because '${e.stackName??`${e.slug}-${e.environment}`}' has no complete local compute state pin.`)}let c=await this.client.listServers();if(a.length>0){let f=[];for(let h of a){let _=c.find((S)=>S.id===h)??await this.tryGetServer(h);if(h===i?.serverId&&i.serverName&&_?.name!==i.serverName)continue;if(_&&_.status!=="off")f.push(_)}if(f.length>0)return f.map(r)}let u=c.filter((f)=>ve(f.labels,e.slug,e.environment,t));if(u.length>0)return u.map(r);if(t==="app"){let f=c.filter((h)=>h.status!=="off"&&h.labels?.[`${ae}/managed-by`]==="ts-cloud"&&h.labels?.[`${ae}/environment`]===e.environment&&h.labels?.[`${ae}/role`]==="app");if(f.length===1)return f.map(r)}return[]}if(this.stateOnly)throw Error(`Hetzner API token required to discover '${t}' compute targets.`);let s=(await this.client.listServers()).filter((i)=>ve(i.labels,e.slug,e.environment,t));if(s.length>0)return s.map(r);return[]}async attachToComputeInfrastructure(e,t,r){let n=await this.client.listServers(),s=(S)=>n.filter((v)=>v.status!=="off"&&ve(v.labels,e,r,S)),i=s("app");if(i.length===0)throw Error(`Cannot attach '${t.project.slug}' to '${e}': no running Hetzner app server is labeled for ${e}/${r}. Deploy the owner project first.`);let a=s("lb")[0],c=s("services")[0],u=i[0],f=a??u,h=m(t,r),_={provider:"hetzner",stackName:h,serverId:u.id,serverName:u.name,appServerIds:i.map((S)=>S.id),lbServerId:a?.id,servicesServerId:c?.id,servicesPrivateIp:c?.private_net?.[0]?.ip,publicIp:f.public_net.ipv4?.ip,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await et(h,_),this.outputsFromState(_)}async listReachableResources(){return(await this.client.listServers()).map((t)=>({name:t.name,labels:t.labels}))}async runRemoteDeploy(e){if(e.targets.length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets provided"};let t=e.commands.join(`
|
|
283
|
+
`),r=[];for(let s of e.targets){if(!s.publicIp){r.push({instanceId:s.id,status:"Failed",error:"Missing public IP"});continue}try{let i=this.sshExec(s.publicIp,t);xr(i),r.push({instanceId:s.id,status:"Success",output:i})}catch(i){r.push({instanceId:s.id,status:"Failed",error:i.message})}}let n=r.every((s)=>s.status==="Success");return{success:n,instanceCount:e.targets.length,perInstance:r,error:n?void 0:Jt(r,"One or more SSH deploy commands failed")}}async ensureSshKey(e,t,r){if(!Pc(this.sshPublicKeyPath))throw Error(`SSH public key not found at ${this.sshPublicKeyPath}. ts-cloud deploys to Hetzner over SSH and needs a public key to authorize on the server. Generate one (\`ssh-keygen -t ed25519\`) or set hetzner.sshPrivateKeyPath / HCLOUD_SSH_PUBLIC_KEY.`);let n=Ec(this.sshPublicKeyPath,"utf8").trim(),s=Ve(n),a=(await this.client.listSshKeys()).find((u)=>Ve(u.public_key)===s);if(a)return a.id;return(await this.client.createSshKey({name:`${e}-${t}-deploy`,publicKey:n,labels:r})).id}async tryGetServer(e){try{return await this.client.getServer(e)}catch{return null}}refreshLbRoutes(e,t,r,n,s){let i=e.public_net.ipv4?.ip;if(!i){console.warn(`[ts-cloud] LB server '${e.name}' has no public IP — skipping the rpx route refresh; its routes may be stale.`);return}let a=r.filter((u)=>u.privateIp||u.publicIp);if(a.length===0){console.warn(`[ts-cloud] No routable app boxes found for LB '${e.name}' — leaving its current rpx routes untouched.`);return}let c=tr(t,a,{proxy:n,slug:s});this.sshExec(i,Ne({config:c,slug:s}).join(`
|
|
284
|
+
`))}async findExistingServer(e,t,r){let n=await this.client.listServers(),s=n.find((a)=>ve(a.labels,e,t,"app")||a.name===r);if(s)return s;let i=n.filter((a)=>a.status!=="off"&&a.labels?.[`${ae}/managed-by`]==="ts-cloud"&&a.labels?.[`${ae}/environment`]===t&&a.labels?.[`${ae}/role`]==="app");if(i.length===1){let a=i[0],c=a.labels?.[`${ae}/project`]??"unknown";return console.warn(`[ts-cloud] No server named '${r}' found; adopting existing ts-cloud app server '${a.name}' (project label '${c}') for project '${e}' — `+"updating it in place instead of provisioning a new server."),a}return}async ensureFirewall(e,t,r){let s=(await this.client.listFirewalls()).find((a)=>a.name===e);if(s)return await this.client.setFirewallRules(s.id,r),{firewall:s};let{firewall:i}=await this.client.createFirewall({name:e,labels:t,rules:r});return{firewall:i}}collectUpstreamPorts(e){let t=new Set;for(let r of Object.values(e))if(typeof r.port==="number")t.add(r.port);return[...t].filter((r)=>![80,443].includes(r))}async sleep(e){await new Promise((t)=>setTimeout(t,e))}async waitForSshReady(e){let{sshIntervalMs:t,sshTimeoutMs:r}=this.bootWait,n=Date.now(),s;while(Date.now()-n<r)try{Ws(`ssh ${this.sshBaseArgs(e,["-o","ConnectTimeout=5"]).map(Nt).join(" ")} true`,{stdio:"pipe",maxBuffer:Dn});return}catch(i){s=i,await this.sleep(t)}throw Error(`Timed out waiting for SSH on ${e} after ${r}ms: ${s?.message??"unknown error"}`)}async waitForCloudInit(e){let{cloudInitIntervalMs:t,cloudInitTimeoutMs:r}=this.bootWait,n=Date.now();while(Date.now()-n<r){try{let s=this.sshExec(e,"if command -v cloud-init >/dev/null 2>&1; then cloud-init status --long 2>/dev/null || true; else echo 'status: done'; fi");if(/status:\s*error/.test(s))throw Error(`cloud-init reported an error on ${e}:
|
|
285
|
+
${s}`);if(/status:\s*(?:done|degraded)/.test(s))return}catch(s){if(s instanceof Error&&/cloud-init reported an error/.test(s.message))throw s}await this.sleep(t)}throw Error(`Timed out waiting for cloud-init to finish on ${e} after ${r}ms`)}outputsFromState(e,t){return{deployStoragePath:e.deployStoragePath||"/var/ts-cloud/staging",appInstanceId:e.serverId?String(e.serverId):void 0,appPublicIp:t?.public_net.ipv4?.ip||e.publicIp,appPublicIpv6:De(t?.public_net.ipv6?.ip)||e.publicIpv6,sshUser:e.sshUser||this.sshUser,servicesPrivateIp:e.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(e,t=[]){return["-i",this.sshPrivateKeyPath,...Pe.SSH_HOST_KEY_OPTS,...Pe.SSH_KEEPALIVE_OPTS,"-o","BatchMode=yes",...t,`${this.sshUser}@${e}`]}scpToHost(e,t,r){let n=["scp",...Ut,"-i",this.sshPrivateKeyPath,...Pe.SSH_HOST_KEY_OPTS,...Pe.SSH_KEEPALIVE_OPTS,"-o","BatchMode=yes",t,`${this.sshUser}@${e}:${r}`].map((i)=>`"${i.replace(/"/g,"\\\"")}"`).join(" "),s=3;for(let i=1;i<=3;i++)try{Ws(n,{stdio:"pipe",maxBuffer:Dn});return}catch(a){if(i===3)throw Error(Wt(a))}}sshExec(e,t){try{return Tc("ssh",[...this.sshBaseArgs(e),Uc],{encoding:"utf8",input:t,stdio:["pipe","pipe","pipe"],maxBuffer:Dn})}catch(r){throw Error(`${Wt(r)}${Yn(r,t)}`)}}}class ro{name="ssh";usesCloudFormation=!1;async getComputeOutputs(){return{appPublicIp:"127.0.0.1",sshUser:"root"}}async uploadRelease(e){return{artifactRef:e.localPath}}async findComputeTargets(e){if((e.role||"app")!=="app")return[];return[{id:"localhost",name:"localhost",publicIp:"127.0.0.1",status:"running"}]}async runRemoteDeploy(e){let t=e.commands.join(`
|
|
286
|
+
`);try{let r=Bun.spawn(["bash","-c",t],{stdout:"pipe",stderr:"pipe",env:process.env}),[n,s,i]=await Promise.all([new Response(r.stdout).text(),new Response(r.stderr).text(),r.exited]);return{success:i===0,instanceCount:1,perInstance:[{instanceId:"localhost",status:i===0?"Success":"Failed",output:n,error:s}]}}catch(r){return{success:!1,instanceCount:1,perInstance:[{instanceId:"localhost",status:"Failed",error:r?.message??String(r)}],error:r?.message??String(r)}}}}function zc(){let e=process.env.TS_CLOUD_DASHBOARD_BOX;return e!=null&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}import{createHash as ll,randomUUID as fo}from"node:crypto";import{createReadStream as ul}from"node:fs";import{isIP as pl}from"node:net";import{createHash as Dc}from"node:crypto";import{appendFile as Ic,mkdir as Ac,readFile as kc}from"node:fs/promises";import{dirname as Nc}from"node:path";var Xs=268435456,Js=async(e,t)=>{let r=Bun.spawn(e,{stdin:t===void 0?"ignore":Buffer.from(t),stdout:"pipe",stderr:"pipe"}),[n,s,i]=await Promise.all([r.exited,new Response(r.stdout).text(),new Response(r.stderr).text()]);return{code:n,signal:r.signalCode,stdout:s.slice(-Xs),stderr:i.slice(-Xs)}},Hg=["-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR"],Gg=["-o","ConnectTimeout=30","-o","ServerAliveInterval=15","-o","ServerAliveCountMax=4"];function Qs(e){if(e.hostKey==="insecure")return[...Hg];return["-o",`StrictHostKeyChecking=${e.hostKey.policy==="pin"?"yes":"accept-new"}`,"-o",`UserKnownHostsFile=${e.hostKey.knownHostsFile}`,"-o","LogLevel=ERROR"]}function lo(e){let t=[...Gg];if(e.connectTimeoutSec!==void 0)t[1]=`ConnectTimeout=${e.connectTimeoutSec}`;return t}function Kc(e,t,r=[]){return["-i",e.identityFile,"-p",String(e.port??22),...Qs(e),...lo(e),"-o","BatchMode=yes",...r,`${e.user}@${t}`]}function Vg(e,t,r,n){return["-i",e.identityFile,"-P",String(e.port??22),...Qs(e),...lo(e),"-o","BatchMode=yes",r,`${e.user}@${t}:${n}`]}function yt(e){return`SHA256:${Dc("sha256").update(Buffer.from(e,"base64")).digest("base64").replace(/=+$/,"")}`}async function pi(e,t=22,r=Js){let n=await r(["ssh-keyscan","-T","10","-p",String(t),"-t","ed25519",e]),s=n.stdout.split(`
|
|
287
|
+
`).find((i)=>i&&!i.startsWith("#"))?.trim().split(/\s+/);if(n.code!==0||!s?.[1]||!s[2])throw Error(`SSH host-key scan failed: ${n.stderr.trim()||"no key returned"}`);return{algorithm:s[1],key:s[2]}}function Wc(e,t=22){return t===22?e:`[${e}]:${t}`}function qg(e,t,r){return`${Wc(e,t)} ${r.algorithm} ${r.key}`}function jg(e,t,r=22){let n=Wc(t,r);for(let s of e.split(`
|
|
288
|
+
`)){let i=s.trim();if(!i||i.startsWith("#")||i.startsWith("@"))continue;let[a,c,u]=i.split(/\s+/);if(!a||!c||!u)continue;if(a.split(",").includes(n))return{algorithm:c,key:u}}return null}function Jc(e=process.cwd()){return l(e,"ssh","known_hosts")}async function Bc(e){try{return await kc(e,"utf8")}catch{return""}}async function el(e,t){await Ac(Nc(e),{recursive:!0}),await Ic(e,`${t}
|
|
289
|
+
`,{mode:384})}class St{options;run;scan;readKnownHosts;appendKnownHosts;constructor(e,t={}){this.options=e;this.run=t.run??Js,this.scan=t.scan??pi,this.readKnownHosts=t.readKnownHosts??Bc,this.appendKnownHosts=t.appendKnownHosts??el}runnerFor(e={}){if(e.sudo!==void 0)return di({sudo:e.sudo});return this.options.runner??di()}async exec(e,t,r={}){let n=await this.run(["ssh",...Kc(this.options,e),this.runnerFor(r)],t);if(n.code!==0){let s={status:n.code,signal:n.signal,stdout:n.stdout,stderr:n.stderr};throw Error(`${Wt(s)}${Yn(s,t)}`)}return n.stdout}async scp(e,t,r){let n=["scp",...Ut,...Vg(this.options,e,t,r)],s=3;for(let i=1;i<=3;i++){let a=await this.run(n);if(a.code===0)return;if(i===3)throw Error(Wt({status:a.code,signal:a.signal,stdout:a.stdout,stderr:a.stderr}))}}async probe(e){return(await this.run(["ssh",...Kc(this.options,e,["-o","ConnectTimeout=5"]),"true"])).code===0}async ensureHostKey(e){let t=this.options.port??22;if(this.options.hostKey==="insecure")try{return{fingerprint:yt((await this.scan(e,t,this.run)).key),pinnedNow:!1}}catch{return{fingerprint:"",pinnedNow:!1}}let{policy:r,knownHostsFile:n}=this.options.hostKey,s=jg(await this.readKnownHosts(n),e,t);if(s)return{fingerprint:yt(s.key),pinnedNow:!1};let i=await this.scan(e,t,this.run);if(r==="pin")return await this.appendKnownHosts(n,qg(e,t,i)),{fingerprint:yt(i.key),pinnedNow:!0};return{fingerprint:yt(i.key),pinnedNow:!1}}}import{isIP as tl}from"node:net";var ke=1,Xc="/var/lib/ts-cloud";function zg(e=ke){return`${Xc}/bootstrap.v${e}`}var Kg=1;function rl(e){return e==="aarch64"||e==="arm64"}function uo(e){let t=e.lanIp?.trim()||e.facts?.lanIp?.trim();return t&&tl(t)!==0?t:void 0}function no(e,t,r){if(!Ct(e.infrastructure?.compute?.managedServices?.vitess))return;if(t==="raspberry-pi"||rl(r))throw Error(`managedServices.vitess is enabled, but Vitess publishes only x86_64 release tarballs and this host is ${r??"a Raspberry Pi (arm64)"}. Drop managedServices.vitess or deploy it to an x86_64 host.`)}function tt(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function nl(){return`
|
|
290
290
|
# A Pi 5 has no battery-backed RTC and boots in 1970 until NTP answers. apt
|
|
291
291
|
# rejects Release files "from the future" and ACME rejects a skewed clock, so
|
|
292
292
|
# wait (bounded) for systemd-timesyncd before anything touches the network
|
|
@@ -302,7 +302,7 @@ if command -v timedatectl >/dev/null 2>&1; then
|
|
|
302
302
|
systemctl start systemd-time-wait-sync >/dev/null 2>&1 || true
|
|
303
303
|
fi
|
|
304
304
|
fi
|
|
305
|
-
`}function
|
|
305
|
+
`}function sl(){return`
|
|
306
306
|
# SD cards wear; a journal allowed to grow to the default 10% of the disk is
|
|
307
307
|
# the single biggest writer on an idle Pi. Bound it.
|
|
308
308
|
install -d -m 0755 /etc/systemd/journald.conf.d
|
|
@@ -313,11 +313,11 @@ MaxRetentionSec=7day
|
|
|
313
313
|
Compress=yes
|
|
314
314
|
TS_CLOUD_JOURNAL_EOF
|
|
315
315
|
systemctl restart systemd-journald
|
|
316
|
-
`}function
|
|
316
|
+
`}function ol(e){return`
|
|
317
317
|
# The deploy user uploads releases as itself (scp), while the scripts run as
|
|
318
318
|
# root through sudo. setgid group-writable directories let both write.
|
|
319
319
|
install -d -m 2775 -g "$(id -gn ${tt(e)})" /var/ts-cloud/artifacts /var/ts-cloud/staging
|
|
320
|
-
`}function
|
|
320
|
+
`}function al(e){let t=tt(e),r=`/home/${e}`;return[`chown -R ${t}:"$(id -gn ${t})" ${tt(`${r}/.ssh`)}`,`chmod 700 ${tt(`${r}/.ssh`)}`]}function mi(e){let{config:t,environment:r,profile:n,sudoUser:s}=e;no(t,n,e.facts?.arch);let i={...t.infrastructure?.compute,proxy:w(t,{environment:e.environment,environmentType:e.environment})},a=t.sites??{},c=t.project.slug,u=e.lan?{...e.lan.hostname?{hostname:e.lan.hostname}:{},tls:e.lan.tls??"local-ca",...uo(e)?{ip:uo(e)}:{}}:void 0,f=i.proxy?.engine==="rpx"?B(a,{proxy:i.proxy,slug:c,lan:u,mail:C(t,{environment:e.environment,environmentType:e.environment})}):void 0,h=i.proxy?.engine==="rpx"&&f?G({proxy:i.proxy,config:f,slug:c,profile:n,bunBin:i.runtime==="node"||i.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,_=i.proxy?.engine==="rpx"&&f?Ne({config:f,slug:c}):void 0,S=s?`/home/${s}/.ssh/authorized_keys`:void 0,v=Ye(t,{environment:r,authorizedKeysPath:S}),y=s?[...v.servicesProvision??[],...al(s)]:v.servicesProvision,b=[...new Set([...i.systemPackages??[],"psmisc","ca-certificates"])],I=i.swapGb??(n==="raspberry-pi"?Kg:void 0),D=M({runtime:v.runtime,runtimeVersion:v.runtimeVersion,systemPackages:b,database:t.infrastructure?.database,phpProvision:v.phpProvision,servicesProvision:y,rpxProvision:h,swapGb:I}).replace(/^#!\/bin\/bash\nset -euo pipefail\n/,""),H=zg(),R=f?.localCa?` lan=${f.localCa.hosts.join(",")} tls=local-ca`:u?` lan=${u.hostname??`${c}.local`} tls=${u.tls??"local-ca"}`:"",x=`#!/bin/bash
|
|
321
321
|
set -euo pipefail
|
|
322
322
|
# ts-cloud ssh bootstrap v${ke} profile=${n}${R}
|
|
323
323
|
|
|
@@ -327,17 +327,17 @@ set -euo pipefail
|
|
|
327
327
|
# re-create swap on every boot.
|
|
328
328
|
if [ -e ${tt(H)} ]; then
|
|
329
329
|
echo "[ts-cloud] bootstrap v${ke} already applied; refreshing the gateway fragment only"
|
|
330
|
-
`;if(
|
|
330
|
+
`;if(_){let W=_[0]==="set -euo pipefail"?_.slice(1):_;x+=`${W.join(`
|
|
331
331
|
`)}
|
|
332
332
|
`}if(x+=` exit 0
|
|
333
333
|
fi
|
|
334
|
-
`,x+=
|
|
334
|
+
`,x+=nl(),n==="raspberry-pi")x+=sl();if(s)x+=ol(s);if(x+=`
|
|
335
335
|
${D}`,x+=`
|
|
336
336
|
install -d -m 0755 ${tt(Xc)}
|
|
337
337
|
date -u +%Y-%m-%dT%H:%M:%SZ > ${tt(H)}
|
|
338
338
|
echo "[ts-cloud] bootstrap v${ke} applied (${n}); gateway fragment at ${z}/${c}.json"
|
|
339
|
-
`,
|
|
340
|
-
`;return x}var
|
|
339
|
+
`,f?.localCa)x+=`echo "[ts-cloud] LAN certificate authority for ${f.localCa.hosts.join(", ")} at ${go(f.localCa.dir)} (copy it to a client to trust this box)"
|
|
340
|
+
`;return x}var It={user:"root",port:22,privateKeyPath:"~/.ssh/id_ed25519",hostKey:"pin",profile:"generic",publicIp:"auto"},po=["pin","accept-new","insecure"],mo=["raspberry-pi","generic"];function _t(...e){for(let t of e){let r=process.env[t]?.trim();if(r)return r}return}function Mt(...e){for(let t of e){let r=t?.trim();if(r)return r}return}function Wg(e,t){if(t?.length)return t;if(e?.ssh?.hosts?.length)return e.ssh.hosts;let r=_t("TS_CLOUD_SSH_HOST");if(r)return[{host:r}];throw Error("No ssh host configured. Set ssh.hosts in cloud.config.ts or TS_CLOUD_SSH_HOST.")}function Jg(e,t){return Mt(t,e?.user,_t("TS_CLOUD_SSH_USER"))??It.user}function Xg(e,t){let r=[{source:"the explicit port",value:t},{source:`ssh.hosts[].port for ${e?.host??"the host"}`,value:e?.port},{source:"TS_CLOUD_SSH_PORT",value:_t("TS_CLOUD_SSH_PORT")}];for(let{source:n,value:s}of r){if(s===void 0||s==="")continue;let i=typeof s==="number"?s:Number(s);if(!Number.isInteger(i)||i<1||i>65535)throw Error(`Invalid SSH port from ${n}: ${String(s)}`);return i}return It.port}function Yg(e,t){return yr(Mt(t,e?.privateKeyPath,_t("TS_CLOUD_SSH_KEY"))??It.privateKeyPath)}function Zg(e,t){let r=Mt(t,e?.ssh?.hostKey,_t("TS_CLOUD_SSH_HOST_KEY"))??It.hostKey;if(!po.includes(r))throw Error(`Invalid ssh.hostKey '${r}'. Use one of: ${po.join(", ")}.`);return r}function ep(e,t=It.user,r){return r??e?.ssh?.sudo??t!=="root"}function tp(e,t){let r=Mt(t,e?.ssh?.profile,_t("TS_CLOUD_SSH_PROFILE"))??It.profile;if(!mo.includes(r))throw Error(`Invalid ssh.profile '${r}'. Use one of: ${mo.join(", ")}.`);return r}function rp(e,t){return Mt(t,e?.ssh?.publicIp)??It.publicIp}function np(e,t){return t??e?.ssh?.lan}function fi(e,t={}){let r=Wg(e,t.hosts).map((n)=>({host:n.host,user:Jg(n,t.user),port:Xg(n,t.port),privateKeyPath:Yg(n,t.privateKeyPath),role:n.role??"app"}));return{hosts:r,hostKey:Zg(e,t.hostKey),sudo:ep(e,r[0]?.user,t.sudo),profile:tp(e,t.profile),publicIp:rp(e,t.publicIp),lan:np(e,t.lan)}}var hi=`set -u
|
|
341
341
|
. /etc/os-release 2>/dev/null || true
|
|
342
342
|
# Strings are stripped of quotes, backslashes and newlines rather than escaped:
|
|
343
343
|
# nothing reported here legitimately contains them, and a probe that cannot
|
|
@@ -369,23 +369,23 @@ printf '"lanIp":"%s",' "$(json_str "$(hostname -I 2>/dev/null | awk '{print $1}'
|
|
|
369
369
|
printf '"tools":{"curl":%s,"tar":%s},' "$(bool command -v curl)" "$(bool command -v tar)"
|
|
370
370
|
printf '"privilege":"%s"' "$(sudo -n true >/dev/null 2>&1 && printf sudo || printf user)"
|
|
371
371
|
printf '}\\n'
|
|
372
|
-
`;function
|
|
372
|
+
`;function Ai(e){let t=e.split(`
|
|
373
373
|
`).map((r)=>r.trim()).filter(Boolean).at(-1);if(!t||!t.startsWith("{"))throw Error(`Preflight returned no facts:
|
|
374
|
-
${e.trim().slice(-2000)}`);try{return JSON.parse(t)}catch(r){throw Error(`Preflight returned malformed facts: ${r.message}`)}}var $t=1073741824;function
|
|
374
|
+
${e.trim().slice(-2000)}`);try{return JSON.parse(t)}catch(r){throw Error(`Preflight returned malformed facts: ${r.message}`)}}var $t=1073741824;function cl(e){return e==="aarch64"||e==="arm64"}function yi(e,t){let r=[],n=e.arch??"";if(!cl(n)&&!(n==="x86_64"&&t.profile==="generic"))r.push({code:"arch.not-aarch64",severity:"error",message:t.profile==="raspberry-pi"?`The raspberry-pi profile expects a 64-bit ARM OS; this host reports ${n||"an unknown architecture"}.`:`Unsupported architecture ${n||"(unknown)"}.`,remediation:t.profile==="raspberry-pi"?"Flash the 64-bit Raspberry Pi OS or Ubuntu Server arm64 image.":"Use an x86_64 or arm64 Linux host."});let s=`${e.osId??""} ${e.osIdLike??""}`.toLowerCase();if(!/\b(?:debian|ubuntu|raspbian)\b/.test(s))r.push({code:"os.unsupported",severity:"error",message:`The bootstrap targets Debian and Ubuntu (apt); this host reports ${e.os||"an unknown OS"}.`,remediation:"Install Raspberry Pi OS, Debian or Ubuntu Server."});let i=e.memoryBytes??0;if(i<$t)r.push({code:"memory.low",severity:"error",message:`${(i/$t).toFixed(2)} GiB of memory; the runtime plus a gateway needs at least 1 GiB.`,remediation:"Use a host with 2 GiB or more."});else if(i<2*$t)r.push({code:"memory.low",severity:"warning",message:`${(i/$t).toFixed(2)} GiB of memory; on-box builds and managed services will be tight.`,remediation:"Build releases in CI rather than on the host, and keep managedServices small."});if((e.diskFreeBytes??0)<4*$t)r.push({code:"disk.low",severity:"error",message:`${((e.diskFreeBytes??0)/$t).toFixed(1)} GiB free on /; releases, the artifact cache and swap need at least 4 GiB.`,remediation:"Free space or use a larger card or disk."});if(t.user!=="root"&&!e.sudoOk)r.push({code:"sudo.missing",severity:"error",message:`${t.user} cannot run sudo without a password, and the bootstrap needs root.`,remediation:`Add '${t.user} ALL=(ALL) NOPASSWD:ALL' to /etc/sudoers.d/ts-cloud, or deploy as root.`});if(!e.timeSynced)r.push({code:"time.unsynced",severity:"warning",message:"The clock is not NTP-synchronised yet; the bootstrap waits for it before running apt.",remediation:"Nothing to do unless it never syncs: then check the network and systemd-timesyncd."});if(!e.httpsOk)r.push({code:"https.blocked",severity:"error",message:"The host cannot reach https://github.com, so it cannot download the runtime or packages.",remediation:"Check DNS, the default route and any egress firewall from the host."});if(e.cloudInitPresent&&/running/i.test(e.cloudInitStatus??""))r.push({code:"cloud-init.running",severity:"info",message:"cloud-init is still running its first boot; the adopt waits for it to finish."});if(e.piModel)r.push({code:"pi.model",severity:"info",message:e.piModel});if(e.kernelBits===32)r.push({code:"bits.32",severity:"error",message:"This is a 32-bit userland; bun ships no 32-bit build.",remediation:"Flash a 64-bit OS image."});return r}function Si(e){return e.some((t)=>t.severity==="error")}function Ii(e){if(e.length===0)return"No findings.";let t=Math.max(...e.map((r)=>r.code.length));return e.map((r)=>{let n=`${r.severity.padEnd(7)} ${r.code.padEnd(t)} ${r.message}`;return r.remediation?`${n}
|
|
375
375
|
${" ".repeat(t+10)}${r.remediation}`:n}).join(`
|
|
376
|
-
`)}var
|
|
377
|
-
`);try{await this.exec(c.publicIp,u);continue}catch{}let
|
|
378
|
-
`),r=[];for(let s of e.targets){if(!s.publicIp){r.push({instanceId:s.id,status:"Failed",error:"Missing address"});continue}try{let i=await this.exec(s.publicIp,t);
|
|
379
|
-
${
|
|
380
|
-
${s}`);if(/status:\s*(?:done|degraded)/.test(s))return}catch(s){if(s instanceof Error&&/cloud-init reported an error/.test(s.message))throw s}await this.sleep(t)}throw Error(`Timed out waiting for cloud-init to finish on ${e} after ${r}ms`)}}function F(e){if(zc())return new
|
|
381
|
-
`)||!/^(?:ssh|ecdsa|sk)-/.test(t))throw Error("publicKey must be one public key line, e.g. the contents of ~/.ssh/id_ed25519.pub.");if(e.wifi){if(!e.wifi.ssid)throw Error("wifi.ssid is required.");if(!e.wifi.passphrase)throw Error("wifi.passphrase is required.");if(!
|
|
376
|
+
`)}var bi="/var/ts-cloud/staging",xn=$r,ip="TS_CLOUD_SSH_SKIP_BOOTSTRAP",dl=["size","instances","appServers","servicesServer","loadBalancer","fleet","image","bakedImage","allowSsh"];function Ft(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function ml(e){let t=ll("sha256");for await(let r of ul(e))t.update(r);return t.digest("hex")}function sp(e,t){if(e.cloud?.attachTo)throw Error("cloud.attachTo is not supported by the ssh provider: it deploys to the hosts in ssh.hosts and nothing else.");if(t.hosts.length>1)throw Error(`ssh.hosts lists ${t.hosts.length} hosts; multi-host ssh fleets are not supported yet.`);if(Ct(e.infrastructure?.compute?.managedServices?.vitess))no(e,t.profile);let r=e.infrastructure?.compute??{};return dl.filter((n)=>r[n]!==void 0).map((n)=>`infrastructure.compute.${n} has no effect with the ssh provider; the host is what it is.`)}class Qr{name="ssh";usesCloudFormation=!1;settings;cwd;bootWait;transportInstance;constructor(e={}){this.settings=fi(void 0,{hosts:e.hosts,user:e.user,port:e.port,privateKeyPath:e.privateKeyPath,hostKey:e.hostKey,sudo:e.sudo,profile:e.profile,publicIp:e.publicIp,lan:e.lan}),this.cwd=e.cwd??process.cwd(),this.transportInstance=e.transport,this.bootWait={sshIntervalMs:e.bootWait?.sshIntervalMs??5000,sshTimeoutMs:e.bootWait?.sshTimeoutMs??300000,cloudInitIntervalMs:e.bootWait?.cloudInitIntervalMs??5000,cloudInitTimeoutMs:e.bootWait?.cloudInitTimeoutMs??600000}}get host(){if(this.settings.hosts.length>1)throw Error(`ssh.hosts lists ${this.settings.hosts.length} hosts; multi-host ssh fleets are not supported yet.`);return this.settings.hosts[0]}get transport(){if(!this.transportInstance){let e=this.host;this.transportInstance=new St({user:e.user,port:e.port,identityFile:e.privateKeyPath,hostKey:this.settings.hostKey==="insecure"?"insecure":{policy:this.settings.hostKey,knownHostsFile:Jc(this.cwd)}})}return this.transportInstance}exec(e,t){return this.transport.exec(e,t,{sudo:this.settings.sudo})}async findComputeTargets(e){if((e.role||"app")!=="app")return[];let{host:t}=this.host;return[{id:t,name:t,publicIp:t,status:"running"}]}async getComputeOutputs(){let{host:e,user:t}=this.host;return{appInstanceId:e,appPublicIp:e,sshUser:t,deployStoragePath:bi}}async uploadRelease(e){let t=e.targets?.length?e.targets:await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:m(e.config,e.environment)});if(t.length===0)throw Error("No ssh compute targets found for release upload");let n=`${e.remoteKey.replace(/^releases\//,"").replace(/\.tar\.gz$/,"").replace(/\//g,"-")}-${fo()}.tar.gz`,s=`${bi}/${n}`,i=await ml(e.localPath),a=`${xn}/${i}.tar.gz`;for(let c of t){if(!c.publicIp)throw Error(`Target ${c.id} has no address for SCP upload`);let u=["set -euo pipefail",`mkdir -p ${Ft(xn)} ${Ft(bi)}`,`test -s ${Ft(a)}`,`cp -- ${Ft(a)} ${Ft(s)}`].join(`
|
|
377
|
+
`);try{await this.exec(c.publicIp,u);continue}catch{}let f=`${xn}/.${i}-${fo()}.tmp`;try{await this.transport.scp(c.publicIp,e.localPath,f),await this.exec(c.publicIp,hr(f,a,s))}catch(h){throw await this.exec(c.publicIp,Sr(f)).catch(()=>{}),h}}return{artifactRef:s}}async runRemoteDeploy(e){if(e.targets.length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets provided"};let t=e.commands.join(`
|
|
378
|
+
`),r=[];for(let s of e.targets){if(!s.publicIp){r.push({instanceId:s.id,status:"Failed",error:"Missing address"});continue}try{let i=await this.exec(s.publicIp,t);xr(i),r.push({instanceId:s.id,status:"Success",output:i})}catch(i){r.push({instanceId:s.id,status:"Failed",error:i.message})}}let n=r.every((s)=>s.status==="Success");return{success:n,instanceCount:e.targets.length,perInstance:r,error:n?void 0:Jt(r,"One or more SSH deploy commands failed")}}targetHost(){return this.host.host}ensureHostKey(e=this.host.host){return this.transport.ensureHostKey(e)}async preflight(e=this.host.host){let t=await this.transport.exec(e,hi,{sudo:!1}),r=Ai(t);return{facts:r,findings:yi(r,{user:this.host.user,profile:this.settings.profile})}}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e;for(let y of sp(t,this.settings))console.warn(`[ts-cloud] ${y}`);let n=this.host,s=m(t,r),i=await je(s,this.cwd),a=process.env[ip]==="1"&&i?.provider==="ssh"&&i.host===n.host&&i.bootstrapVersion===ke,c=await this.ensureHostKey(n.host);if(c.pinnedNow)console.warn(`[ts-cloud] pinned ${n.host} host key ${c.fingerprint}`);await this.waitForSshReady(n.host);let{facts:u,findings:f}=await this.preflight(n.host);if(Si(f))throw Error(`Preflight failed for ${n.host}; refusing to bootstrap it.
|
|
379
|
+
${Ii(f)}`);for(let y of f)console.warn(`[ts-cloud] ${y.severity}: ${y.message}`);if(u.cloudInitPresent&&/running/i.test(u.cloudInitStatus??""))await this.waitForCloudInit(n.host);let h=u.lanIp?.trim()||(pl(n.host)!==0?n.host:void 0),_=i?.provider==="ssh"?i.bootstrappedAt:void 0;if(!a){let y=mi({config:t,environment:r,profile:this.settings.profile,facts:u,sudoUser:n.user!=="root"?n.user:void 0,lan:this.settings.lan,lanIp:h});xr(await this.exec(n.host,y)),_=new Date().toISOString()}let S={provider:"ssh",stackName:s,host:n.host,sshUser:n.user,sshPort:n.port,hostKeyFingerprint:c.fingerprint||void 0,publicIp:this.settings.publicIp==="auto"?void 0:this.settings.publicIp,lanIp:u.lanIp||void 0,deployStoragePath:bi,profile:this.settings.profile,bootstrapVersion:ke,bootstrappedAt:_};await At(s,S,this.cwd);let v=await this.getComputeOutputs();if(j(t.infrastructure?.compute)&&dd(this.settings.lan)==="local-ca")v.lanCaCertPath=go(),console.warn(`[ts-cloud] LAN certificate authority on ${n.host} at ${v.lanCaCertPath}. Fetch it with: scp ${n.user}@${n.host}:${v.lanCaCertPath} ./rpx-root-ca.crt`);return v}async destroyCompute(e){let t=m(e.config,e.environment),r=this.host;return console.warn(`[ts-cloud] forgot ${r.host} for ${t}; nothing was removed on the host (stop the systemd units and remove /var/ts-cloud and /etc/rpx by hand if you want it clean).`),await At(t,{provider:"ssh",stackName:t,host:r.host,sshUser:r.user,sshPort:r.port},this.cwd).catch(()=>{}),{destroyed:[`local state for ${t}`]}}async sleep(e){await new Promise((t)=>setTimeout(t,e))}async waitForSshReady(e){let{sshIntervalMs:t,sshTimeoutMs:r}=this.bootWait,n=Date.now();do{if(await this.transport.probe(e))return;await this.sleep(t)}while(Date.now()-n<r);throw Error(`Timed out waiting for SSH on ${e} after ${r}ms`)}async waitForCloudInit(e){let{cloudInitIntervalMs:t,cloudInitTimeoutMs:r}=this.bootWait,n=Date.now();while(Date.now()-n<r){try{let s=await this.transport.exec(e,"if command -v cloud-init >/dev/null 2>&1; then cloud-init status --long 2>/dev/null || true; else echo 'status: done'; fi",{sudo:!1});if(/status:\s*error/.test(s))throw Error(`cloud-init reported an error on ${e}:
|
|
380
|
+
${s}`);if(/status:\s*(?:done|degraded)/.test(s))return}catch(s){if(s instanceof Error&&/cloud-init reported an error/.test(s.message))throw s}await this.sleep(t)}throw Error(`Timed out waiting for cloud-init to finish on ${e} after ${r}ms`)}}function F(e){if(zc())return new ro;switch(e.provider??be(e.config)){case"aws":return new _r({region:e.config.project.region});case"hetzner":return new Pe({apiToken:e.config.hetzner?.apiToken,allowStateOnly:Boolean(e.config.cloud?.attachTo),sshPrivateKeyPath:e.config.hetzner?.sshPrivateKeyPath,sshPublicKeyPath:e.config.hetzner?.sshPublicKeyPath,sshUser:e.config.hetzner?.sshUser,location:e.config.hetzner?.location});case"ssh":return new Qr({hosts:e.config.ssh?.hosts,hostKey:e.config.ssh?.hostKey,sudo:e.config.ssh?.sudo,profile:e.config.ssh?.profile,publicIp:e.config.ssh?.publicIp,lan:e.config.ssh?.lan});case"fly":throw Error("Fly.io has no box to provision or reach over SSH: deploy it with deployToFly() from @stacksjs/ts-cloud.");default:throw Error(`Unknown cloud provider: ${e.provider??be(e.config)}`)}}class io{drivers=new Map;getDriver(e,t){let r=t??be(e),n=`${r}:${e.project.slug}:${e.project.region||"default"}`,s=this.drivers.get(n);if(s)return s;let i=F({config:e,provider:r});return this.drivers.set(n,i),i}}var op=new io;var ap="/var/lib/ts-cloud/bootstrap.sh",cp={"raspberry-pi-os":"bootfs",ubuntu:"system-boot"},fl=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,gl=/^[a-z_][a-z0-9_-]{0,31}$/,hl=/^[A-Z]{2}$/;function ye(e){return JSON.stringify(e)}function Sl(e){if(!fl.test(e.hostname))throw Error(`Invalid hostname '${e.hostname}': use lowercase letters, digits and hyphens.`);if(!gl.test(e.user))throw Error(`Invalid user '${e.user}': use a lowercase Unix user name.`);let t=e.publicKey.trim();if(!t||t.includes(`
|
|
381
|
+
`)||!/^(?:ssh|ecdsa|sk)-/.test(t))throw Error("publicKey must be one public key line, e.g. the contents of ~/.ssh/id_ed25519.pub.");if(e.wifi){if(!e.wifi.ssid)throw Error("wifi.ssid is required.");if(!e.wifi.passphrase)throw Error("wifi.passphrase is required.");if(!hl.test(e.wifi.country))throw Error(`wifi.country must be a two-letter regulatory domain such as DE or US, not '${e.wifi.country}'.`)}}function vl(e,t){let r=[`hostname: ${ye(e.hostname)}`,"manage_etc_hosts: true","users:",` - name: ${ye(e.user)}`," ssh_authorized_keys:",` - ${ye(e.publicKey.trim())}`,` sudo: ${ye("ALL=(ALL) NOPASSWD:ALL")}`," shell: /bin/bash"," lock_passwd: true","ssh_pwauth: false"];if(e.timezone)r.push(`timezone: ${ye(e.timezone)}`);if(e.locale)r.push(`locale: ${ye(e.locale)}`);if(r.push("package_update: true"),t==="raspberry-pi-os")r.push("rpi:"," enable_ssh: true"," interfaces:"," spi: false"," i2c: false"," onewire: false"," remote_gpio: false"," serial:"," console: false"," hardware: false");return`${r.join(`
|
|
382
382
|
`)}
|
|
383
|
-
`}function
|
|
383
|
+
`}function _l(e){let t=["version: 2","ethernets:"," eth0:"," match:",` name: ${ye("e*")}`," dhcp4: true"," dhcp6: true"," optional: true"];if(e.wifi)t.push("wifis:"," wlan0:"," dhcp4: true"," dhcp6: true"," optional: true",` regulatory-domain: ${ye(e.wifi.country)}`," access-points:",` ${ye(e.wifi.ssid)}:`,` password: ${ye(e.wifi.passphrase)}`);return`${t.join(`
|
|
384
384
|
`)}
|
|
385
|
-
`}function
|
|
385
|
+
`}function yl(e){return[`instance-id: ${ye(`ts-cloud-${e.hostname}`)}`,`local-hostname: ${ye(e.hostname)}`].join(`
|
|
386
386
|
`)+`
|
|
387
|
-
`}function
|
|
388
|
-
`)}function Yc(e,t,r){
|
|
387
|
+
`}function $l(e,t){return[`Copy user-data, network-config and meta-data onto the boot partition of the flashed card (the volume named '${cp[t]}'), replacing the files already there.`,"Eject the card, put it in the board and power it on.","The first boot takes a few minutes: cloud-init creates the user, waits for the clock to sync, then runs the ts-cloud bootstrap (packages, runtime, gateway).",`Then, from this machine: cloud ssh:preflight ${e.hostname}.local --user ${e.user}`,"When the preflight is clean, cloud deploy adopts the host and ships the sites."].join(`
|
|
388
|
+
`)}function Yc(e,t,r){Sl(e);let n={scriptPath:ap,permissions:"0700",before:vl(e,r.os)};return{files:{"user-data":se(t,n),"network-config":_l(e),"meta-data":yl(e)},instructions:$l(e,r.os)}}function ho(e){return e.infrastructure?.compute??{}}function dp(e){let t=ho(e),r=t.monitoring;return{firewallPorts:[...new Set([22,80,443,...t.firewall?.allowedPorts??[]])].filter((s)=>Number.isInteger(s)&&s>=1&&s<=65535).sort((s,i)=>s-i),monitoring:r!==!1&&(typeof r!=="object"||r.enabled!==!1),autoUpdates:t.autoUpdates!==!1,swapGb:Math.max(0,Math.floor(t.swapGb??2)),sshPasswordAuthentication:!1,sshMaxStartups:"100:30:200",journalMaxUse:"256M",journalRetention:"14day"}}function bl(e){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",`MaxStartups ${e.sshMaxStartups}`,"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=${e.journalMaxUse}`,`MaxRetentionSec=${e.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 Tl(e){if(e===0)return[];return["if ! swapon --show=NAME --noheadings 2>/dev/null | grep -qx '/swapfile'; then",` if [ ! -f /swapfile ]; then fallocate -l ${e}G /swapfile || dd if=/dev/zero of=/swapfile bs=1M count=${e*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 lp(e){let t=ho(e),r=dp(e),n=t.monitoring??!0,s=t.firewall??{enabled:!0};return["set -euo pipefail",...j(t)?["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"]:[],...Tl(r.swapGb),...Ue(r.autoUpdates),...xe(n),...bl(r),...sr(s),"systemctl daemon-reload","systemctl reset-failed"]}var wl=String.raw`
|
|
389
389
|
const text = (command) => {
|
|
390
390
|
const result = Bun.spawnSync(['bash', '-lc', command], { stdout: 'pipe', stderr: 'pipe' })
|
|
391
391
|
return result.stdout.toString().trim()
|
|
@@ -416,30 +416,35 @@ console.log(JSON.stringify({
|
|
|
416
416
|
failedUnits: lines("systemctl --failed --type=service --no-legend --plain | awk '{print $1}'"),
|
|
417
417
|
publicTcpPorts: [...new Set(publicTcpPorts)].sort((a, b) => a - b),
|
|
418
418
|
}))
|
|
419
|
-
`;function
|
|
420
|
-
`),n=`printf %s ${Buffer.from(r).toString("base64")} | base64 -d | bash`;await Se(t.host,n,t)}async function Vh(e){let t=await Se(e.host,
|
|
421
|
-
`,"utf8"),await So(r,t)}async function Kh(e,t=1800000){let r=
|
|
422
|
-
`,"utf8"),async()=>{await
|
|
419
|
+
`;function Cl(e){return`printf %s ${Buffer.from(e).toString("base64")} | base64 -d | bun -`}async function Gh(e,t){let r=lp(e).join(`
|
|
420
|
+
`),n=`printf %s ${Buffer.from(r).toString("base64")} | base64 -d | bash`;await Se(t.host,n,t)}async function Vh(e){let t=await Se(e.host,Cl(wl),e);return JSON.parse(t)}function qh(e,t){let r=[],n=new Set(t.firewallPorts),s=e.firewallPorts.filter((a)=>!n.has(a)),i=t.firewallPorts.filter((a)=>!e.firewallPorts.includes(a));if(!t.firewallActive)r.push("UFW is not active");if(s.length>0)r.push(`UFW is missing ports: ${s.join(", ")}`);if(i.length>0)r.push(`UFW has unexpected ports: ${i.join(", ")}`);if(t.passwordAuthentication)r.push("SSH password authentication remains enabled");if(t.rootPasswordLogin)r.push("SSH root password login remains enabled");if(!t.fail2banActive)r.push("fail2ban is not active");if(e.autoUpdates&&!t.unattendedUpgradesActive)r.push("unattended upgrades are not active");if(e.monitoring&&!t.metricsTimerActive)r.push("metrics timer is not active");if(e.monitoring&&!t.metricsSnapshotFresh)r.push("metrics snapshot is stale");if(e.swapGb>0&&t.swapBytes<e.swapGb*1073741824*0.9)r.push("configured swap is missing");if(t.failedUnits.length>0)r.push(`failed services: ${t.failedUnits.join(", ")}`);return r}import{mkdir as Pr,readFile as Pl,rename as So,rmdir as El,stat as Rl,unlink as Ol,writeFile as vo}from"node:fs/promises";import{join as Er}from"node:path";function Zc(e){return Er(ht(),`${e}-resize.json`)}function up(e){return Er(ht(),`${e}-resize.lock`)}async function jh(e){try{return JSON.parse(await Pl(Zc(e),"utf8"))}catch{return null}}async function zh(e){let t=Zc(e.stackName);await Pr(ht(),{recursive:!0});let r=`${t}.${process.pid}.tmp`;await vo(r,`${JSON.stringify(e,null,2)}
|
|
421
|
+
`,"utf8"),await So(r,t)}async function Kh(e,t=1800000){let r=up(e);await Pr(ht(),{recursive:!0});try{await Pr(r)}catch(n){if(Date.now()-(await Rl(r)).mtimeMs<=t)throw Error(`Another resize process holds ${r}.`);await So(r,`${r}.stale-${Date.now()}`),await Pr(r)}return await vo(Er(r,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
|
|
422
|
+
`,"utf8"),async()=>{await Ol(Er(r,"owner.json")).catch(()=>{}),await El(r).catch(()=>{})}}async function Ci(e,t){let r=Ve(t.publicKey),n=(await e.listSshKeys()).find((i)=>Ve(i.public_key)===r);if(n)return{id:n.id,name:n.name,created:!1};let s=await e.createSshKey({name:t.name,publicKey:t.publicKey.trim(),labels:t.labels});return{id:s.id,name:s.name,created:!0}}async function Ei(e,t){let r=(await e.listFirewalls()).find((s)=>s.name===t.name);if(r)return await e.setFirewallRules(r.id,t.rules),{id:r.id,name:r.name,created:!1};let{firewall:n}=await e.createFirewall({name:t.name,rules:t.rules,labels:t.labels});return{id:n.id,name:n.name,created:!0}}async function vi(e,t){let{waitForRunning:r=!0,...n}=t,s=(await e.listServers()).find((a)=>a.name===t.name),i=!s;if(!s)s=(await e.createServer(n)).server;if(r)s=await e.waitForServerRunning(s.id);return{server:s,created:i}}function Ti(e){let t=e.public_net.ipv4?.ip;if(!t)throw Error(`Hetzner server "${e.name}" (#${e.id}) has no public IPv4`);return t}var ed="/aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id";function td(e){let t=e.sshPublicKey.trim(),r=["#cloud-config","disable_root: false","ssh_authorized_keys:",` - ${t}`];if(e.bootstrapScript){let s=e.bootstrapScript.split(`
|
|
423
423
|
`).map((i)=>` ${i}`).join(`
|
|
424
424
|
`);r.push("write_files:"," - path: /var/lib/cloud/box-bootstrap.sh"," permissions: '0755'"," owner: root:root"," content: |",s)}if(r.push("runcmd:",` - mkdir -p /root/.ssh && grep -qF "${t}" /root/.ssh/authorized_keys 2>/dev/null || echo "${t}" >> /root/.ssh/authorized_keys`),e.bootstrapScript)r.push(" - [ bash, /var/lib/cloud/box-bootstrap.sh ]");return`${r.join(`
|
|
425
425
|
`)}
|
|
426
|
-
`}function
|
|
426
|
+
`}function Dl(e=[]){let t=[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"],description:"SSH"}];for(let r of e)t.push({direction:"in",protocol:r.protocol,...r.protocol==="icmp"?{}:{port:String(r.port)},source_ips:["0.0.0.0/0","::/0"]});return t}class wi{client;provider="hetzner";constructor(e){this.client=e}async ensureBox(e){let t=await Ci(this.client,{name:`${e.name}-key`,publicKey:e.sshPublicKey}),r=await Ei(this.client,{name:`${e.name}-fw`,rules:Dl(e.ports)}),{server:n,created:s}=await vi(this.client,{name:e.name,serverType:e.size,image:e.image??"ubuntu-24.04",location:e.location,sshKeys:[t.id],firewalls:[{firewall:r.id}],userData:td(e),labels:e.labels});if(!s){if(!((await this.client.listFirewalls()).find((c)=>c.id===r.id)?.applied_to??[]).some((c)=>c.type==="server"&&c.server?.id===n.id)){let c=await this.client.applyFirewallToResources(r.id,[{type:"server",server:n.id}]);for(let u of c)await this.client.waitForAction(u.id).catch(()=>{})}}return{provider:"hetzner",id:String(n.id),name:n.name,publicIp:Ti(n),created:s}}async destroyBox(e){let t=[],r=(await this.client.listServers()).find((s)=>s.name===e);if(r){let s=await this.client.deleteServer(r.id);await this.client.waitForAction(s.id).catch(()=>{}),t.push(`server ${e} (#${r.id})`)}let n=(await this.client.listFirewalls()).find((s)=>s.name===`${e}-fw`);if(n)for(let s=0;s<10;s++)try{await this.client.deleteFirewall(n.id),t.push(`firewall ${e}-fw (#${n.id})`);break}catch{if(s===9)break;await new Promise((i)=>setTimeout(i,3000))}return{destroyed:t}}}function xl(e=[]){let t=[{IpProtocol:"tcp",FromPort:22,ToPort:22,IpRanges:[{CidrIp:"0.0.0.0/0",Description:"SSH"}]}];for(let r of e)t.push(r.protocol==="icmp"?{IpProtocol:"icmp",FromPort:-1,ToPort:-1,IpRanges:[{CidrIp:"0.0.0.0/0"}]}:{IpProtocol:r.protocol,FromPort:r.port,ToPort:r.port,IpRanges:[{CidrIp:"0.0.0.0/0"}]});return t}class rd{provider="aws";ec2;ssm;constructor(e){this.ec2=e.ec2,this.ssm=e.ssm}async findInstance(e,t){return(await this.ec2.describeInstances({Filters:[{Name:"tag:Name",Values:[e]},{Name:"instance-state-name",Values:t}]})).Reservations?.flatMap((n)=>n.Instances??[])[0]}async waitForPublicIp(e,t=300000){let r=Date.now();while(Date.now()-r<t){let n=await this.ec2.getInstance(e);if(n?.State?.Name==="running"&&n.PublicIpAddress)return n;await new Promise((s)=>setTimeout(s,5000))}throw Error(`EC2 instance ${e} did not reach running with a public IP within ${t}ms`)}async ensureSecurityGroup(e){let t=`${e.name}-sg`,n=(await this.ec2.describeSecurityGroups({Filters:[{Name:"group-name",Values:[t]}]})).SecurityGroups?.[0]?.GroupId;if(n)return n;let s=await this.ec2.createSecurityGroup({GroupName:t,Description:`box ${e.name} (managed by ts-cloud box-provision)`});if(!s.GroupId)throw Error(`could not create security group ${t}`);return await this.ec2.authorizeSecurityGroupIngress({GroupId:s.GroupId,IpPermissions:xl(e.ports)}),s.GroupId}async resolveImage(e){if(e.image?.startsWith("ami-"))return e.image;let r=(await this.ssm.getParameter({Name:ed})).Parameter?.Value;if(!r)throw Error(`could not resolve the Ubuntu 24.04 AMI via SSM (${ed})`);return r}async ensureBox(e){let t=await this.findInstance(e.name,["pending","running"]);if(t?.InstanceId){let u=await this.waitForPublicIp(t.InstanceId);return{provider:"aws",id:u.InstanceId,name:e.name,publicIp:u.PublicIpAddress,created:!1}}let[r,n]=await Promise.all([this.ensureSecurityGroup(e),this.resolveImage(e)]),s=[{Key:"Name",Value:e.name},...Object.entries(e.labels??{}).map(([u,f])=>({Key:u,Value:f}))],a=(await this.ec2.runInstances({ImageId:n,InstanceType:e.size,MinCount:1,MaxCount:1,SecurityGroupIds:[r],UserData:Buffer.from(td(e),"utf8").toString("base64"),TagSpecifications:[{ResourceType:"instance",Tags:s}]})).Instances?.[0]?.InstanceId;if(!a)throw Error(`RunInstances returned no instance for box ${e.name}`);let c=await this.waitForPublicIp(a);return{provider:"aws",id:a,name:e.name,publicIp:c.PublicIpAddress,created:!0}}async destroyBox(e){let t=[],r=await this.findInstance(e,["pending","running","stopping","stopped"]);if(r?.InstanceId){await this.ec2.terminateInstances([r.InstanceId]),t.push(`instance ${e} (${r.InstanceId})`);let i=Date.now();while(Date.now()-i<300000){let a=await this.ec2.getInstance(r.InstanceId);if(!a||a.State?.Name==="terminated")break;await new Promise((c)=>setTimeout(c,5000))}}let s=(await this.ec2.describeSecurityGroups({Filters:[{Name:"group-name",Values:[`${e}-sg`]}]})).SecurityGroups?.[0]?.GroupId;if(s)for(let i=0;i<10;i++)try{await this.ec2.deleteSecurityGroup(s),t.push(`security group ${e}-sg (${s})`);break}catch{if(i===9)break;await new Promise((a)=>setTimeout(a,3000))}return{destroyed:t}}}function Wh(e){if(e.provider==="hetzner"){if(!e.hetzner)throw Error('createBoxProvisioner: options.hetzner (a HetznerClient) is required for provider "hetzner"');return new wi(e.hetzner)}if(!e.aws)throw Error('createBoxProvisioner: options.aws ({ ec2, ssm }) is required for provider "aws"');return new rd(e.aws)}var so="/opt/pantry/cli",gp=`${p}/pantry/.bin`,Il={"google.com/chrome":{profile:"ts-cloud-pantry-chrome",binary:`${p}/pantry/google.com/chrome/*/lib/chrome-for-testing/chrome`}};function Al(e,t){return["# Written by ts-cloud: lets this pantry package create user namespaces for its","# sandbox, like Ubuntu's own profile for /opt/google/chrome/chrome.","abi <abi/4.0>,","include <tunables/global>","",`profile ${e} ${t} flags=(unconfined) {`," userns,","",` include if exists <local/${e}>`,"}",""].join(`
|
|
427
|
+
`)}var Dr="ts-cloud:",Ll=["/usr/local/bin","/usr/bin","/bin"];function bt(e){return`'${e.split("'").join("'\\''")}'`}function Rr(e){return Buffer.from(e,"utf8").toString("base64")}function zt(e,t){if(!/^[a-z_][a-z0-9_.-]*$/i.test(t))throw Error(`Box ${e} "${t}" may only contain letters, digits, '.', '_' and '-'`)}function pp(e){return Object.entries(e).map(([t,r])=>{if(!/^[A-Z_][A-Z0-9_]*$/i.test(t))throw Error(`Environment variable name "${t}" is not valid`);let n=String(r).replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n");return`${t}="${n}"`}).join(`
|
|
427
428
|
`).concat(`
|
|
428
|
-
`)}function
|
|
429
|
-
`)}function
|
|
429
|
+
`)}function mp(e,t,r){let n=r.userUnit?"%h":"/root",s=["# Written by ts-cloud from the box declaration; edits here are overwritten.","[Unit]",`Description=${t.description??e}`,"After=network-online.target","","[Service]","Type=simple",`WorkingDirectory=${t.workingDirectory??n}`];if(t.environmentFile)s.push(`EnvironmentFile=${t.environmentFile}`);if(t.environment&&Object.keys(t.environment).length>0)s.push(`EnvironmentFile=${n}/.config/ts-cloud/${e}.env`);return s.push(`Environment=PATH=${[...t.path??[],...r.pantryOnPath===!1?[]:[gp],...Ll].join(":")}`),s.push(`ExecStart=${t.exec}`),s.push(`Restart=${t.restart??"always"}`),s.push(`RestartSec=${t.restartSec??10}`),s.push("","[Install]",`WantedBy=${r.userUnit?"default.target":"multi-user.target"}`,""),s.join(`
|
|
430
|
+
`)}function fp(e){let t=e.user?.name;if(t)zt("user",t);for(let u of e.user?.groups??[])zt("group",u);let r=Object.entries(e.services??{});for(let[u]of r)zt("service",u);let n=e.pantryVersion,s=["set -euo pipefail","export DEBIAN_FRONTEND=noninteractive",`say() { echo "${Dr} $*"; }`,"write_if_changed() {",' local path="$1" mode="$2" owner="$3" tmp'," tmp=$(mktemp)",' printf %s "$4" | base64 -d > "$tmp"',' if [ -f "$path" ] && cmp -s "$tmp" "$path"; then rm -f "$tmp"; return 1; fi',' install -D -m "$mode" -o "${owner%%:*}" -g "${owner##*:}" "$tmp" "$path"',' rm -f "$tmp"',"}",`PANTRY="${so}/pantry"`,n?`if [ ! -x "$PANTRY" ] || ! "$PANTRY" --version 2>/dev/null | grep -q "pantry ${n.replace(/[^0-9A-Za-z.+-]/g,"")}\\b"; then`:'if [ ! -x "$PANTRY" ]; then'," (",...mt({version:n,installDir:so}).map((u)=>` ${u}`)," )",' say "pantry $("$PANTRY" --version 2>/dev/null | head -1)"',"fi",`mkdir -p ${p}`],i=[...new Set(e.packages??[])];if(i.length>0){let u=Math.round((e.minFreeDiskGb??10)*1024*1024),f=`${p}/pantry/.ts-cloud-packages`,h=`${[...i].sort().join(`
|
|
430
431
|
`)}
|
|
431
|
-
`}
|
|
432
|
-
`).filter((t)=>t.startsWith(On)).map((t)=>t.slice(On.length).trim())}async function Jh(e){let{box:t}=e,r=await new vi(e.client).ensureBox({name:t.name,size:t.size,image:t.image,location:t.location,ports:t.ports,sshPublicKey:e.sshPublicKey,labels:{"ts-cloud/role":"box","ts-cloud/managed-by":"ts-cloud",...t.labels}});await Yt(r.publicIp,{identityFile:e.identityFile});let s=await new yt({user:"root",identityFile:e.identityFile,hostKey:{policy:"pin",knownHostsFile:e.knownHostsFile}}).exec(r.publicIp,mp(t));return{box:r,report:fp(s)}}import{copyFileSync as du}from"node:fs";import{tmpdir as mu}from"node:os";import{join as fu}from"node:path";var xl=`${ae}/project`;function yo(e,t){let r=t.ownerSlug.trim(),n=t.selfSlug?.trim(),s={total:e.length,owner:[],self:[],others:new Map,unmanaged:[]};for(let i of e){let a=i.labels?.[xl]?.trim();if(!a){s.unmanaged.push(i.name);continue}if(a===r){s.owner.push(i.name);continue}if(n&&a===n){s.self.push(i.name);continue}let c=s.others.get(a);if(c)c.push(i.name);else s.others.set(a,[i.name])}return s}function Dn(e){let t=e.unmanaged.length;for(let r of e.others.values())t+=r.length;return t}function $o(e,t){let r=Dn(e),n=[];if(n.push(`Attaching to '${t.ownerSlug}' shares one provider project, so this deploy's credential can write to all ${e.total} server(s) it can see.`),r===0)return n.push("Nothing outside the two projects being joined is reachable with it."),n;n.push(`${r} of them belong to neither project:`);for(let s of[...e.others.keys()].sort())n.push(` ${s}: ${[...e.others.get(s)].sort().join(", ")}`);if(e.unmanaged.length>0)n.push(` not managed by ts-cloud: ${[...e.unmanaged].sort().join(", ")}`);return n.push("A compromised CI run or a mistargeted teardown in this project now reaches those. Keep the app in its own provider project instead if that is not acceptable, which rules out attaching."),n}import{execSync as To}from"node:child_process";import{randomBytes as Al}from"node:crypto";import{chmodSync as Ll,copyFileSync as Ul,existsSync as rt,mkdirSync as wo,readFileSync as Co,statSync as Hl,writeFileSync as In}from"node:fs";import{tmpdir as kl}from"node:os";import{basename as Nl,dirname as Ln,isAbsolute as Po,join as de,resolve as Ml}from"node:path";import{fileURLToPath as Eo}from"node:url";function xn(e){if(!e||typeof e!=="object")return e;return Object.fromEntries(Object.keys(e).map((t)=>[t,""]))}function Il(e){let t=JSON.parse(JSON.stringify(e??{}));if(t.hetzner)delete t.hetzner.apiToken;delete t.aws,delete t.stateDir;for(let r of Object.values(t.sites??{})){if(r?.env)r.env=xn(r.env);if(r?.environment)r.environment=xn(r.environment)}for(let r of Object.values(t.environments??{}))if(r?.variables)r.variables=xn(r.variables);for(let r of Object.values(t.infrastructure?.databases??{}))if(r?.password)r.password="";if(t.infrastructure?.appDatabase?.password)t.infrastructure.appDatabase.password="";if(t.infrastructure?.compute?.database?.password)t.infrastructure.compute.database.password="";if(t.infrastructure?.compute?.managedServices?.vitess?.password)t.infrastructure.compute.managedServices.vitess.password="";return t}function bo(e){let t=Il(e);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(t,null,2)}`,""].join(`
|
|
433
|
-
`)}var nd="dashboard";function so(){return Q("dashboard-credentials.json")}function Fl(){return Al(24).toString("base64url")}function id(e,t,r){let n=process.env.TS_CLOUD_UI_PASSWORD?.trim();if(n)return{password:n,source:"env"};if(An(process.env.TS_CLOUD_UI_PUBLIC))return{password:void 0,source:"public"};let s=so(),i=l(e,"dashboard-credentials.json");try{if(rt(i)){let c=JSON.parse(Co(i,"utf8"));if(c?.password)return{password:c.password,source:"generated"}}}catch{}let a=Fl();try{wo(Ln(i),{recursive:!0}),In(i,`${JSON.stringify({username:t,password:a,generatedAt:new Date().toISOString()},null,2)}
|
|
434
|
-
`),Ll(i,384),r.info(`Management dashboard: generated a password for '${t}' and saved it to ${s} (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(c){r.warn(`Management dashboard: could not persist the generated password (${c?.message??c}). Using it for this deploy only — pass: ${a}
|
|
435
|
-
This password is now in your deploy log. Set TS_CLOUD_UI_PASSWORD to a value of your own and redeploy once ${s} is writable.`)}return{password:a,source:"generated"}}var Ro={info:()=>{},warn:()=>{}};function An(e){return e!=null&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function zl(){return Q("dashboard-release")}function Oo(){let e=Ln(Eo(import.meta.url));for(let t of[de(e,"..","..","package.json"),de(e,"..","package.json")])try{let r=JSON.parse(Co(t,"utf8"));if(r.name==="@stacksjs/ts-cloud"&&r.version)return`^${r.version}`}catch{}return"latest"}function Bl(){return process.env.TS_CLOUD_UI_VERSION?.trim()||Oo()}function Kl(e,t,r){if(!e?.project?.slug)return r.warn("Management dashboard: the cloud config has no project slug — skipping the live dashboard."),null;let n=l(t,"dashboard-release");try{wo(n,{recursive:!0}),In(de(n,"cloud.config.ts"),bo(e));let s=Bl();if(s.startsWith("file:")){let a=s.slice(5),c=Po(a)?a:Ml(t,a);if(!rt(c)||!Hl(c).isFile())s=Oo(),r.warn(`Management dashboard: TS_CLOUD_UI_VERSION points to a missing package file (${c}); using the deploying ts-cloud version ${s} instead.`);else{let u=Nl(c),m=de(n,u);if(c!==m)Ul(c,m);s=`file:./${u}`}}let i={name:"ts-cloud-dashboard",private:!0,type:"module",dependencies:{"@stacksjs/ts-cloud":s}};return In(de(n,"package.json"),`${JSON.stringify(i,null,2)}
|
|
436
|
-
`),zl()}catch(s){return r.warn(`Management dashboard: could not stage the live release (${s?.message??s}) — skipping.`),null}}function Zt(e){if(rt(de(e,"packages","ui","pages"))||rt(de(e,"packages","ui","package.json")))return{uiRoot:"packages/ui/dist",build:"cd packages/ui && bun install && bun run build"};let t=Ln(Eo(import.meta.url)),r=[de(t,"ui"),de(t,"..","ui"),de(t,"..","..","ui"),de(t,"..","dist","ui")];for(let n of r)if(rt(de(n,"index.html"))||rt(de(n,"serverless.html")))return{uiRoot:n,build:!1};return null}function Ti(e,t={}){let r=t.logger??Ro,n=t.cwd??process.cwd();if(An(process.env.TS_CLOUD_UI_DISABLE))return r.info("Management dashboard: skipped (TS_CLOUD_UI_DISABLE set)."),e;if(e.cloud?.attachTo)return r.info(`Management dashboard: ${e.project.slug} is attached to ${e.cloud.attachTo}; the server owner's dashboard monitors every attached project.`),e;if(ur(e))return e;let s=e.environments&&Object.keys(e.environments)[0],i=process.env.TS_CLOUD_UI_DOMAIN?.trim()||void 0,a=Number(process.env.TS_CLOUD_UI_PORT)||void 0,c={...e.sites??{}};if(!An(process.env.TS_CLOUD_UI_STATIC)){let _=Kl(e,n,r);if(!_)return e;let y=Xi(e,s??"production",{uiRoot:_,build:!1,domain:i,port:a,live:!0});if(y.length===0)return r.info("Management dashboard: no domain resolved (set TS_CLOUD_UI_DOMAIN or configure a site domain) — skipping."),e;for(let{name:b,site:I}of y)c[b]=I,r.info(`Management dashboard → https://${I.domain} (sign in with your ts-cloud account; the first deploy prints an admin password once)`);return e.sites=c,e}let u=Zt(n);if(!u)return r.info("Management dashboard: UI not found (no local ui/ or packaged dist/ui) — skipping auto-deploy."),e;let m=process.env.TS_CLOUD_UI_USERNAME?.trim()||"admin",h=id(n,m,r),S=Xi(e,s??"production",{uiRoot:u.uiRoot,build:u.build,domain:i,username:m,password:h.password,realm:process.env.TS_CLOUD_UI_REALM?.trim()||void 0,live:!1,port:a});if(S.length===0)return r.info("Management dashboard: no domain resolved (set TS_CLOUD_UI_DOMAIN or configure a site domain) — skipping."),e;let v=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 ${so()})`;r.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:_,site:y}of S)c[_]=y,r.info(`Management dashboard → https://${y.domain} (${v})`);return e.sites=c,e}function Un(e){return Object.keys(e.sites??{}).filter(gr)}function oo(e,t){if(!e?.root)return null;let r=t.cwd??process.cwd(),n=t.logger??Ro;try{if(typeof e.build==="string"&&e.build.trim())n.info(`Management dashboard: building UI (${e.build})`),To(e.build,{cwd:r,stdio:"inherit"});let s=Po(e.root)?e.root:de(r,e.root);if(!rt(s))return n.warn(`Management dashboard: build output not found at ${s} — skipping dashboard artifact.`),null;let i=de(kl(),`${t.slug}-${t.siteName??nd}-${t.sha}.tar.gz`);return To(`tar czf "${i}" -C "${s}" .`,{stdio:"inherit"}),i}catch(s){return n.warn(`Management dashboard: failed to build artifact — ${s?.message??s}. Skipping dashboard deploy.`),null}}var jl=new Set(["laravel","php","statamic","wordpress"]);function Qr(e){if(e.framework)return e.framework;if(e.type&&jl.has(e.type))return"laravel";return"stacks"}var Do=`eval "$(cd ${f} && pantry env 2>/dev/null)"`,xo="/usr/local/bin/bun",Vl="node_modules/@stacksjs/ts-cloud/dist/bin/stacks-scheduler.js",Gl="node_modules/@stacksjs/ts-cloud/dist/bin/stacks-queue-worker.js",Io={id:"stacks",wrapExec:(e)=>e,execEnv:{PATH:"/usr/local/bin:/usr/bin:/bin",BUN_INSTALL:"/root/.bun",APP_ENV:"production",NODE_ENV:"production"},schedulerMode:"daemon",schedulerCommand:()=>`${xo} ${Vl}`,queueWorkerCommand:(e,{current:t})=>{let r=[`--queue=${e.queue||"default"}`,`--sleep=${e.sleep??3}`,`--tries=${e.tries??3}`,`--timeout=${e.timeout??60}`];return`${xo} ${t}/${Gl} ${r.join(" ")}`}},ql={id:"laravel",wrapExec:(e)=>`/bin/sh -lc '${Do}; exec ${e}'`,schedulerMode:"cron",schedulerCommand:({current:e})=>`cd ${e} && ${Do} && php artisan schedule:run`,queueWorkerCommand:(e,{current:t})=>{let r=`${t}/artisan`;if(e.horizon)return`php ${r} horizon`;let n=[e.connection||"default",`--queue=${e.queue||"default"}`,`--sleep=${e.sleep??3}`,`--tries=${e.tries??3}`,`--timeout=${e.timeout??60}`,`--memory=${e.memory??128}`];if(e.maxJobs)n.push(`--max-jobs=${e.maxJobs}`);if(e.maxTime)n.push(`--max-time=${e.maxTime}`);return`php ${r} queue:work ${n.join(" ")}`}},Wl={stacks:Io,laravel:ql};function Ao(e){return Wl[e]??Io}function Lo(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Yl(e){return`'${e.split("'").join("'\\''")}'`}function Uo(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"unnamed"}function Xl(e,t,r){return`${e}-${t}-queue-${r}`}function Jl(e,t,r,n){return`${e}-${t}-daemon-${r.name?Uo(r.name):Uo(r.command).slice(0,32)||String(n)}`}function Hn(e){let t=["[Unit]",`Description=${e.description}`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${e.workingDir}`,...Object.entries(e.environment??{}).map(([r,n])=>`Environment="${r}=${n}"`),`ExecStart=${e.execStart}`,`Restart=${e.restart||"always"}`,"RestartSec=5","MemoryAccounting=true",`MemoryHigh=${e.memoryHigh??"2G"}`,...e.memoryMax?[`MemoryMax=${e.memoryMax}`]:[]];if(e.user)t.push(`User=${e.user}`);if(typeof e.stopWaitSecs==="number")t.push(`TimeoutStopSec=${e.stopWaitSecs}`);return t.push("","[Install]","WantedBy=multi-user.target"),`${t.join(`
|
|
432
|
+
`;s.push(`WANTED_PACKAGES=${bt(Rr(h))}`,`if [ -f ${f} ] && [ "$(base64 -w0 < ${f})" = "$WANTED_PACKAGES" ]; then MISSING=0; else MISSING=1; fi`),s.push('if [ "$MISSING" = 1 ]; then'," FREE_KB=$(df -Pk / | awk 'NR==2 {print $4}')",` if [ "$FREE_KB" -lt ${u} ]; then`,` say "not installing packages: $((FREE_KB / 1048576)) GB free, the box declares at least ${e.minFreeDiskGb??10} GB"`," exit 3"," fi",` PANTRY_SERVICE_SCOPE=system PATH="${so}:$PATH" sh -c ${bt(`cd ${p} && pantry install ${i.map(bt).join(" ")}`)}`,` chmod -R a+rX ${p}/pantry 2>/dev/null || true`,` printf %s "$WANTED_PACKAGES" | base64 -d > ${f}`,` say "packages ${i.join(" ")}"`,"fi");let _=Object.entries(Il).filter(([S])=>i.some((v)=>v===S||v.startsWith(`${S}@`)));if(_.length>0){s.push("if command -v apparmor_parser >/dev/null 2>&1 && [ -d /etc/apparmor.d ]; then");for(let[,{profile:S,binary:v}]of _)s.push(` if write_if_changed /etc/apparmor.d/${S} 644 root:root ${bt(Rr(Al(S,v)))}; then`,` apparmor_parser -r /etc/apparmor.d/${S}`,` say "apparmor profile ${S} (user namespaces for its sandbox)"`," fi");s.push("fi")}}if(t)s.push(`if ! id -u ${t} >/dev/null 2>&1; then useradd --create-home --shell /bin/bash ${t}; say "created user ${t}"; fi`,...(e.user?.groups??[]).map((u)=>`if getent group ${u} >/dev/null && ! id -nG ${t} | tr ' ' '\\n' | grep -qx ${u}; then usermod -aG ${u} ${t}; say "added ${t} to ${u}"; fi`),`if [ "$(loginctl show-user ${t} -p Linger --value 2>/dev/null)" != yes ]; then loginctl enable-linger ${t}; say "enabled linger for ${t}"; fi`);s.push(..._o(e));let a=t?`${t}:${t}`:"root:root",c=t?"$SVC_HOME/.config/systemd/user":"/etc/systemd/system";if(r.length>0)s.push("RELOAD=0");for(let[u,f]of r){let h=mp(u,f,{userUnit:Boolean(t),pantryOnPath:i.length>0});s.push(`CHANGED_${u.replace(/[^A-Za-z0-9_]/g,"_")}=0`);let _=`CHANGED_${u.replace(/[^A-Za-z0-9_]/g,"_")}`;if(f.environment&&Object.keys(f.environment).length>0)s.push(`if write_if_changed "$SVC_HOME/.config/ts-cloud/${u}.env" 600 ${a} ${bt(Rr(pp(f.environment)))}; then ${_}=1; fi`);s.push(`if write_if_changed "${c}/${u}.service" 644 ${a} ${bt(Rr(h))}; then ${_}=1; RELOAD=1; fi`)}if(r.length>0)s.push('if [ "$RELOAD" = 1 ]; then svc daemon-reload; fi');for(let[u,f]of r){let h=`CHANGED_${u.replace(/[^A-Za-z0-9_]/g,"_")}`;s.push(`svc enable ${u}.service >/dev/null 2>&1 || svc enable ${u}.service`,`if ! svc is-active --quiet ${u}.service; then svc start ${u}.service; say "started ${u}"`,f.restartOnChange?`elif [ "$${h}" = 1 ]; then svc restart ${u}.service; say "restarted ${u}"`:`elif [ "$${h}" = 1 ]; then say "changed ${u}; restart it to apply"`,"fi")}return s.push('say "converged"'),`${s.join(`
|
|
437
433
|
`)}
|
|
438
|
-
`}function
|
|
439
|
-
|
|
440
|
-
`
|
|
441
|
-
`))
|
|
442
|
-
`)}function
|
|
434
|
+
`}function _o(e){let t=e.user?.name;if(!t)return["SVC_HOME=/root",'svc() { systemctl "$@"; }'];return[`SVC_UID=$(id -u ${t})`,`SVC_HOME=$(getent passwd ${t} | cut -d: -f6)`,`svc() { sudo -u ${t} XDG_RUNTIME_DIR="/run/user/$SVC_UID" systemctl --user "$@"; }`,'for _ in $(seq 1 30); do [ -S "/run/user/$SVC_UID/bus" ] && break; sleep 1; done']}function Ul(e){if(e.user?.name)zt("user",e.user.name);let t=Object.entries(e.services??{}).filter(([,n])=>n.drainSignal),r=["set -euo pipefail",`say() { echo "${Dr} $*"; }`,..._o(e)];for(let[n,s]of t){zt("service",n);let i=String(s.drainSignal).replace(/^SIG/i,"").toUpperCase();if(!/^[A-Z0-9]+$/.test(i))throw Error(`Box service "${n}" has an invalid drainSignal`);let a=s.drainTimeoutSec??3600;r.push(`if svc is-active --quiet ${n}.service; then`,` PID=$(svc show -p MainPID --value ${n}.service)`,` svc kill -s SIG${i} ${n}.service`,` say "draining ${n} (SIG${i})"`," WAITED=0",' while [ "$PID" != 0 ] && kill -0 "$PID" 2>/dev/null; do',` if [ "$WAITED" -ge ${a} ]; then say "${n} still busy after ${a}s; not powering off"; exit 4; fi`," sleep 5; WAITED=$((WAITED + 5))"," done",` svc stop ${n}.service`,` say "drained ${n} after \${WAITED}s"`,"fi")}return r.push('say "drained"'),`${r.join(`
|
|
435
|
+
`)}
|
|
436
|
+
`}function yo(e,t){if(!e.resize||t.alreadyComplete)return"none";if(t.capacityAvailable||e.resize.attemptUnavailable)return"resize";if(e.resize.whenUnavailable==="keep-current")return"unavailable";throw Error(`${t.targetType.name} is out of stock in ${t.location}; set resize.attemptUnavailable to ask anyway, or whenUnavailable: 'keep-current' to wait`)}function nd(e){return e.split(`
|
|
437
|
+
`).filter((t)=>t.startsWith(Dr)).map((t)=>t.slice(Dr.length).trim())}async function Jh(e){let{box:t}=e;if(e.dryRun)return Hl(e);let r=await new wi(e.client).ensureBox({name:t.name,size:t.size,image:t.image,location:t.location,ports:t.ports,sshPublicKey:e.sshPublicKey,labels:{"ts-cloud/role":"box","ts-cloud/managed-by":"ts-cloud",...t.labels}});await ft(r.publicIp,{identityFile:e.identityFile});let n=new St({user:"root",identityFile:e.identityFile,hostKey:{policy:"pin",knownHostsFile:e.knownHostsFile}}),s=[];if(t.resize&&!r.created){let a=await Zt(e.client,Number(r.id),t.size,t.resize.upgradeDisk!==!1),c=yo(t,a);if(c==="unavailable")s.push(`${a.targetType.name} is out of stock in ${a.location}; keeping ${a.currentType.name}`);if(c==="resize"){let u=await li({client:e.client,serverId:Number(r.id),targetType:a.targetType.name,upgradeDisk:a.upgradeDisk,attemptUnavailable:t.resize.attemptUnavailable,hooks:{preflight:async()=>{s.push(...nd(await n.exec(r.publicIp,Ul(t))))},onPhase:(f)=>e.onPhase?.(f)}});if(u.status==="completed")s.push(`resized ${a.currentType.name} to ${a.targetType.name}`);else if(u.status==="recovered")s.push(`could not resize to ${a.targetType.name} (${u.error}); back on ${a.currentType.name}`);else if(u.status==="waiting-capacity")s.push(`${a.targetType.name} is out of stock in ${a.location}; keeping ${a.currentType.name}`);await ft(r.publicIp,{identityFile:e.identityFile})}}let i=await n.exec(r.publicIp,fp(t));return{box:r,report:[...s,...nd(i)]}}async function Hl(e){let{box:t}=e,r=(await e.client.listServers()).find((i)=>i.name===t.name);if(!r)return{box:{provider:"hetzner",id:"",name:t.name,publicIp:"",created:!1},report:[`would create ${t.name} (${t.size})`,"would converge"]};let n={provider:"hetzner",id:String(r.id),name:r.name,publicIp:r.public_net?.ipv4?.ip??"",created:!1},s=[];if(t.resize){let i=await Zt(e.client,r.id,t.size,t.resize.upgradeDisk!==!1),a=yo(t,i);if(a==="resize")s.push(`would resize ${i.currentType.name} to ${i.targetType.name}${i.capacityAvailable?"":" (out of stock; asking placement anyway)"}, draining ${Object.entries(t.services??{}).filter(([,c])=>c.drainSignal).map(([c])=>c).join(", ")||"nothing"} first`);else if(a==="unavailable")s.push(`${i.targetType.name} is out of stock in ${i.location}; would keep ${i.currentType.name}`)}else if(r.server_type.name!==t.size)s.push(`runs ${r.server_type.name}, declared ${t.size}; set resize to change it`);return s.push("would converge"),{box:n,report:s}}import{copyFileSync as vu}from"node:fs";import{tmpdir as _u}from"node:os";import{join as yu}from"node:path";var kl=`${ae}/project`;function $o(e,t){let r=t.ownerSlug.trim(),n=t.selfSlug?.trim(),s={total:e.length,owner:[],self:[],others:new Map,unmanaged:[]};for(let i of e){let a=i.labels?.[kl]?.trim();if(!a){s.unmanaged.push(i.name);continue}if(a===r){s.owner.push(i.name);continue}if(n&&a===n){s.self.push(i.name);continue}let c=s.others.get(a);if(c)c.push(i.name);else s.others.set(a,[i.name])}return s}function In(e){let t=e.unmanaged.length;for(let r of e.others.values())t+=r.length;return t}function bo(e,t){let r=In(e),n=[];if(n.push(`Attaching to '${t.ownerSlug}' shares one provider project, so this deploy's credential can write to all ${e.total} server(s) it can see.`),r===0)return n.push("Nothing outside the two projects being joined is reachable with it."),n;n.push(`${r} of them belong to neither project:`);for(let s of[...e.others.keys()].sort())n.push(` ${s}: ${[...e.others.get(s)].sort().join(", ")}`);if(e.unmanaged.length>0)n.push(` not managed by ts-cloud: ${[...e.unmanaged].sort().join(", ")}`);return n.push("A compromised CI run or a mistargeted teardown in this project now reaches those. Keep the app in its own provider project instead if that is not acceptable, which rules out attaching."),n}import{execSync as wo}from"node:child_process";import{randomBytes as Ml}from"node:crypto";import{chmodSync as Fl,copyFileSync as zl,existsSync as rt,mkdirSync as Co,readFileSync as Po,statSync as Bl,writeFileSync as Ln}from"node:fs";import{tmpdir as Kl}from"node:os";import{basename as jl,dirname as Hn,isAbsolute as Eo,join as de,resolve as Vl}from"node:path";import{fileURLToPath as Ro}from"node:url";function An(e){if(!e||typeof e!=="object")return e;return Object.fromEntries(Object.keys(e).map((t)=>[t,""]))}function Nl(e){let t=JSON.parse(JSON.stringify(e??{}));if(t.hetzner)delete t.hetzner.apiToken;delete t.aws,delete t.stateDir;for(let r of Object.values(t.sites??{})){if(r?.env)r.env=An(r.env);if(r?.environment)r.environment=An(r.environment)}for(let r of Object.values(t.environments??{}))if(r?.variables)r.variables=An(r.variables);for(let r of Object.values(t.infrastructure?.databases??{}))if(r?.password)r.password="";if(t.infrastructure?.appDatabase?.password)t.infrastructure.appDatabase.password="";if(t.infrastructure?.compute?.database?.password)t.infrastructure.compute.database.password="";if(t.infrastructure?.compute?.managedServices?.vitess?.password)t.infrastructure.compute.managedServices.vitess.password="";return t}function To(e){let t=Nl(e);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(t,null,2)}`,""].join(`
|
|
438
|
+
`)}var id="dashboard";function oo(){return Q("dashboard-credentials.json")}function Gl(){return Ml(24).toString("base64url")}function sd(e,t,r){let n=process.env.TS_CLOUD_UI_PASSWORD?.trim();if(n)return{password:n,source:"env"};if(Un(process.env.TS_CLOUD_UI_PUBLIC))return{password:void 0,source:"public"};let s=oo(),i=l(e,"dashboard-credentials.json");try{if(rt(i)){let c=JSON.parse(Po(i,"utf8"));if(c?.password)return{password:c.password,source:"generated"}}}catch{}let a=Gl();try{Co(Hn(i),{recursive:!0}),Ln(i,`${JSON.stringify({username:t,password:a,generatedAt:new Date().toISOString()},null,2)}
|
|
439
|
+
`),Fl(i,384),r.info(`Management dashboard: generated a password for '${t}' and saved it to ${s} (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(c){r.warn(`Management dashboard: could not persist the generated password (${c?.message??c}). Using it for this deploy only — pass: ${a}
|
|
440
|
+
This password is now in your deploy log. Set TS_CLOUD_UI_PASSWORD to a value of your own and redeploy once ${s} is writable.`)}return{password:a,source:"generated"}}var Oo={info:()=>{},warn:()=>{}};function Un(e){return e!=null&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function ql(){return Q("dashboard-release")}function Do(){let e=Hn(Ro(import.meta.url));for(let t of[de(e,"..","..","package.json"),de(e,"..","package.json")])try{let r=JSON.parse(Po(t,"utf8"));if(r.name==="@stacksjs/ts-cloud"&&r.version)return`^${r.version}`}catch{}return"latest"}function Wl(){return process.env.TS_CLOUD_UI_VERSION?.trim()||Do()}function Yl(e,t,r){if(!e?.project?.slug)return r.warn("Management dashboard: the cloud config has no project slug — skipping the live dashboard."),null;let n=l(t,"dashboard-release");try{Co(n,{recursive:!0}),Ln(de(n,"cloud.config.ts"),To(e));let s=Wl();if(s.startsWith("file:")){let a=s.slice(5),c=Eo(a)?a:Vl(t,a);if(!rt(c)||!Bl(c).isFile())s=Do(),r.warn(`Management dashboard: TS_CLOUD_UI_VERSION points to a missing package file (${c}); using the deploying ts-cloud version ${s} instead.`);else{let u=jl(c),f=de(n,u);if(c!==f)zl(c,f);s=`file:./${u}`}}let i={name:"ts-cloud-dashboard",private:!0,type:"module",dependencies:{"@stacksjs/ts-cloud":s}};return Ln(de(n,"package.json"),`${JSON.stringify(i,null,2)}
|
|
441
|
+
`),ql()}catch(s){return r.warn(`Management dashboard: could not stage the live release (${s?.message??s}) — skipping.`),null}}function er(e){if(rt(de(e,"packages","ui","pages"))||rt(de(e,"packages","ui","package.json")))return{uiRoot:"packages/ui/dist",build:"cd packages/ui && bun install && bun run build"};let t=Hn(Ro(import.meta.url)),r=[de(t,"ui"),de(t,"..","ui"),de(t,"..","..","ui"),de(t,"..","dist","ui")];for(let n of r)if(rt(de(n,"index.html"))||rt(de(n,"serverless.html")))return{uiRoot:n,build:!1};return null}function Ri(e,t={}){let r=t.logger??Oo,n=t.cwd??process.cwd();if(Un(process.env.TS_CLOUD_UI_DISABLE))return r.info("Management dashboard: skipped (TS_CLOUD_UI_DISABLE set)."),e;if(e.cloud?.attachTo)return r.info(`Management dashboard: ${e.project.slug} is attached to ${e.cloud.attachTo}; the server owner's dashboard monitors every attached project.`),e;if(gr(e))return e;let s=e.environments&&Object.keys(e.environments)[0],i=process.env.TS_CLOUD_UI_DOMAIN?.trim()||void 0,a=Number(process.env.TS_CLOUD_UI_PORT)||void 0,c={...e.sites??{}};if(!Un(process.env.TS_CLOUD_UI_STATIC)){let v=Yl(e,n,r);if(!v)return e;let y=Zi(e,s??"production",{uiRoot:v,build:!1,domain:i,port:a,live:!0});if(y.length===0)return r.info("Management dashboard: no domain resolved (set TS_CLOUD_UI_DOMAIN or configure a site domain) — skipping."),e;for(let{name:b,site:I}of y)c[b]=I,r.info(`Management dashboard → https://${I.domain} (sign in with your ts-cloud account; the first deploy prints an admin password once)`);return e.sites=c,e}let u=er(n);if(!u)return r.info("Management dashboard: UI not found (no local ui/ or packaged dist/ui) — skipping auto-deploy."),e;let f=process.env.TS_CLOUD_UI_USERNAME?.trim()||"admin",h=sd(n,f,r),_=Zi(e,s??"production",{uiRoot:u.uiRoot,build:u.build,domain:i,username:f,password:h.password,realm:process.env.TS_CLOUD_UI_REALM?.trim()||void 0,live:!1,port:a});if(_.length===0)return r.info("Management dashboard: no domain resolved (set TS_CLOUD_UI_DOMAIN or configure a site domain) — skipping."),e;let S=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 ${oo()})`;r.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:v,site:y}of _)c[v]=y,r.info(`Management dashboard → https://${y.domain} (${S})`);return e.sites=c,e}function kn(e){return Object.keys(e.sites??{}).filter(pr)}function ao(e,t){if(!e?.root)return null;let r=t.cwd??process.cwd(),n=t.logger??Oo;try{if(typeof e.build==="string"&&e.build.trim())n.info(`Management dashboard: building UI (${e.build})`),wo(e.build,{cwd:r,stdio:"inherit"});let s=Eo(e.root)?e.root:de(r,e.root);if(!rt(s))return n.warn(`Management dashboard: build output not found at ${s} — skipping dashboard artifact.`),null;let i=de(Kl(),`${t.slug}-${t.siteName??id}-${t.sha}.tar.gz`);return wo(`tar czf "${i}" -C "${s}" .`,{stdio:"inherit"}),i}catch(s){return n.warn(`Management dashboard: failed to build artifact — ${s?.message??s}. Skipping dashboard deploy.`),null}}var Xl=new Set(["laravel","php","statamic","wordpress"]);function Hr(e){if(e.framework)return e.framework;if(e.type&&Xl.has(e.type))return"laravel";return"stacks"}var xo=`eval "$(cd ${p} && pantry env 2>/dev/null)"`,Io="/usr/local/bin/bun",Jl="node_modules/@stacksjs/ts-cloud/dist/bin/stacks-scheduler.js",Zl="node_modules/@stacksjs/ts-cloud/dist/bin/stacks-queue-worker.js",Ao={id:"stacks",wrapExec:(e)=>e,execEnv:{PATH:"/usr/local/bin:/usr/bin:/bin",BUN_INSTALL:"/root/.bun",APP_ENV:"production",NODE_ENV:"production"},schedulerMode:"daemon",schedulerCommand:()=>`${Io} ${Jl}`,queueWorkerCommand:(e,{current:t})=>{let r=[`--queue=${e.queue||"default"}`,`--sleep=${e.sleep??3}`,`--tries=${e.tries??3}`,`--timeout=${e.timeout??60}`];return`${Io} ${t}/${Zl} ${r.join(" ")}`}},Ql={id:"laravel",wrapExec:(e)=>`/bin/sh -lc '${xo}; exec ${e}'`,schedulerMode:"cron",schedulerCommand:({current:e})=>`cd ${e} && ${xo} && php artisan schedule:run`,queueWorkerCommand:(e,{current:t})=>{let r=`${t}/artisan`;if(e.horizon)return`php ${r} horizon`;let n=[e.connection||"default",`--queue=${e.queue||"default"}`,`--sleep=${e.sleep??3}`,`--tries=${e.tries??3}`,`--timeout=${e.timeout??60}`,`--memory=${e.memory??128}`];if(e.maxJobs)n.push(`--max-jobs=${e.maxJobs}`);if(e.maxTime)n.push(`--max-time=${e.maxTime}`);return`php ${r} queue:work ${n.join(" ")}`}},eu={stacks:Ao,laravel:Ql};function Lo(e){return eu[e]??Ao}function Uo(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function tu(e){return`'${e.split("'").join("'\\''")}'`}function Ho(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"unnamed"}function ru(e,t,r){return`${e}-${t}-queue-${r}`}function nu(e,t,r,n){return`${e}-${t}-daemon-${r.name?Ho(r.name):Ho(r.command).slice(0,32)||String(n)}`}function Nn(e){let t=["[Unit]",`Description=${e.description}`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${e.workingDir}`,...Object.entries(e.environment??{}).map(([r,n])=>`Environment="${r}=${n}"`),`ExecStart=${e.execStart}`,`Restart=${e.restart||"always"}`,"RestartSec=5","MemoryAccounting=true",`MemoryHigh=${e.memoryHigh??"2G"}`,...e.memoryMax?[`MemoryMax=${e.memoryMax}`]:[]];if(e.user)t.push(`User=${e.user}`);if(typeof e.stopWaitSecs==="number")t.push(`TimeoutStopSec=${e.stopWaitSecs}`);return t.push("","[Install]","WantedBy=multi-user.target"),`${t.join(`
|
|
442
|
+
`)}
|
|
443
|
+
`}function Mn(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_UNIT_EOF'`,t.replace(/\n$/,""),"TS_CLOUD_UNIT_EOF"]}function su(e,t){return`/etc/cron.d/${e}-${t}-scheduler`}function Fn(e){let{slug:t,siteName:r,site:n}=e,i=`${e.appBase??`/var/www/${r}`}/current`,a=Lo(Hr(n)),c={current:i},u=[],f=[];(n.queues||[]).forEach((D,H)=>{let R=Math.max(1,D.processes??1);for(let x=0;x<R;x++){let W=ru(t,r,f.length);f.push(W),u.push(...Mn(W,Nn({description:`${r} queue worker ${H}.${x} (managed by ts-cloud)`,workingDir:i,execStart:a.wrapExec(a.queueWorkerCommand(D,c)),environment:a.execEnv,stopWaitSecs:D.stopWaitSecs??90})))}}),(n.daemons||[]).forEach((D,H)=>{let R=Math.max(1,D.processes??1);for(let x=0;x<R;x++){let W=`${nu(t,r,D,H)}-${x}`;f.push(W),u.push(...Mn(W,Nn({description:`${r} daemon ${D.name||D.command} (managed by ts-cloud)`,workingDir:D.directory||i,execStart:a.wrapExec(D.command),environment:a.execEnv,restart:D.restart,user:D.user})))}});let S=n.scheduler,v=S===!0||typeof S==="object"&&S!==null,y=`${t}-${r}-scheduler`;if(v&&a.schedulerMode==="daemon"){f.push(y);let D=typeof S==="object"&&S!==null?S:{};u.push(...Mn(y,Nn({description:`${r} scheduler (managed by ts-cloud)`,workingDir:i,execStart:a.wrapExec(a.schedulerCommand(c)),environment:a.execEnv,memoryHigh:D.memoryHigh,memoryMax:D.memoryMax})),...fr(`${y}.service`,{auto:!1,high:Boolean(D.memoryHigh),max:Boolean(D.memoryMax)}))}let b=f.map((D)=>`${D}.service`).join(" ");u.push("systemctl daemon-reload",`TS_CLOUD_DESIRED="${b}"`,`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E '^${Uo(t)}-${Uo(r)}-((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 D of f)u.push(`systemctl enable ${D}.service`,`systemctl restart ${D}.service`);let I=su(t,r);if(v&&a.schedulerMode==="cron"){let D=typeof S==="object"&&S!==null?S:void 0,H=`${a.schedulerCommand(c)} >> /dev/null 2>&1`;if(D?.heartbeatUrl){let x=D.heartbeatMethod||"GET",W=x==="GET"?"":`-X ${x} `;H+=` && curl -fsS -m 10 ${W}${tu(D.heartbeatUrl)} >/dev/null 2>&1`}let R=`* * * * * root ${H}
|
|
444
|
+
`.replace(/%/g,"\\%");u.push(`cat > ${I} <<'TS_CLOUD_CRON_EOF'`,R.replace(/\n$/,""),"TS_CLOUD_CRON_EOF",`chmod 644 ${I}`)}else u.push(`rm -f ${I}`);return u}function zn(e){return!!(e.queues?.length||e.daemons?.length||e.scheduler)}function Bn(e){if(e.ssl?.provider)return e.ssl.provider;return e.domain?"letsencrypt":"none"}var ko={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 No(e){return`/etc/letsencrypt/ts-cloud-${e}.ini`}function ou(e){let t=e?ko[e.provider]:void 0,r=["certbot","python3-certbot-nginx",...t?[t.pkg]:[]].join(" ");return["export DEBIAN_FRONTEND=noninteractive",t?`apt-get update -y && apt-get install -y ${r}`:`command -v certbot >/dev/null 2>&1 || { apt-get update -y && apt-get install -y ${r}; }`,"mkdir -p /etc/letsencrypt/renewal-hooks/deploy","cat > /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh <<'TS_CLOUD_HOOK_EOF'","#!/bin/sh","systemctl reload ts-cloud-nginx 2>/dev/null || systemctl reload nginx 2>/dev/null || true","TS_CLOUD_HOOK_EOF","chmod +x /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh","systemctl enable certbot.timer 2>/dev/null || true","systemctl start certbot.timer 2>/dev/null || true"]}function iu(e){if(!e.credentials||Object.keys(e.credentials).length===0)return[];let t=No(e.provider),r=Object.entries(e.credentials).map(([n,s])=>`${n} = ${s}`).join(`
|
|
445
|
+
`);return[`cat > ${t} <<'TS_CLOUD_DNSCREDS_EOF'`,r,"TS_CLOUD_DNSCREDS_EOF",`chmod 600 ${t}`]}function au(e){let t=e.dns,r=e.wildcard?[`*.${e.domain}`,e.domain]:[e.domain,...e.aliases||[]].filter(Boolean),n=["certbot","--non-interactive","--agree-tos","--keep-until-expiring"];if(t){let s=ko[t.provider].plugin;if(n.push(`--${s}`),t.provider!=="route53"&&t.credentials)n.push(`--${s}-credentials ${No(t.provider)}`);if(typeof t.propagationSeconds==="number"&&t.provider!=="route53")n.push(`--${s}-propagation-seconds ${t.propagationSeconds}`);n.push("certonly")}else n.push("--nginx",`--nginx-ctl ${He}`,e.redirect===!1?"--no-redirect":"--redirect");if(e.email)n.push(`-m ${e.email}`);else n.push("--register-unsafely-without-email");for(let s of r)n.push(`-d ${s}`);return[n.join(" ")]}function Kn(e){if(Bn(e)!=="letsencrypt"||!e.domain)return[];let t=e.ssl,r=t?.dns,n=t?.wildcard===!0;if(n&&!r)return[];return[...ou(r),...r?iu(r):[],...au({domain:e.domain,aliases:e.aliases,email:t?.email,wildcard:n,dns:r})]}function Mo(e){let{repository:t,releaseDir:r,commit:n}=e,s=t.branch||"main",i=t.url,a=[`rm -rf ${r}`,`mkdir -p ${r}`];if(t.strategy==="tag")if(t.tag)a.push(`git clone -q --depth 1 --branch ${$e(t.tag)} ${$e(i)} ${r}`),a.push(`printf '%s' ${$e(t.tag)} > ${r}/.ts-cloud-tag`);else{let c=t.tagPattern||"v*";a.push(`TS_CLOUD_TAG="$(git ls-remote --tags --refs --sort=-v:refname ${$e(i)} ${$e(`refs/tags/${c}`)} | head -n1 | sed 's#.*refs/tags/##')"`,`test -n "$TS_CLOUD_TAG" || { echo "no tags matching" ${$e(c)} "found in" ${$e(i)} >&2; exit 1; }`,`git clone -q --depth 1 --branch "$TS_CLOUD_TAG" ${$e(i)} ${r}`,`printf '%s' "$TS_CLOUD_TAG" > ${r}/.ts-cloud-tag`)}else if(n)a.push(`git -C ${r} init -q`,`git -C ${r} remote add origin ${$e(i)}`,`git -C ${r} fetch -q --depth 1 origin ${$e(n)}`,`git -C ${r} checkout -q FETCH_HEAD`);else a.push(`git clone -q --depth 1 --branch ${$e(s)} ${$e(i)} ${r}`);return a.push(`git -C ${r} rev-parse HEAD > ${r}/.ts-cloud-sha`),a}function $e(e){return`'${e.split("'").join("'\\''")}'`}var Ir="$CREATE_RELEASE",Ar="$ACTIVATE_RELEASE",Bo="$RESTART_QUEUES",Fo="composer install --no-interaction --prefer-dist --optimize-autoloader --no-dev",cu=["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 lu(e){switch(e){case"laravel":case"statamic":return[Ir,Fo,...cu,Ar,Bo];case"php":case"wordpress":return[Ir,`${Fo} || true`,Ar];case"static":case"spa":return[Ir,Ar]}}function uu(e,t){return e.replace(/^php\s+/,`${t} `).replace(/(\s)php\s+artisan\s+/g,`$1${t} artisan `)}function pu(e,t){let r=ar(t);return[`cat > ${e} <<'TS_CLOUD_ENV_EOF'`,r,"TS_CLOUD_ENV_EOF",`chmod 600 ${e}`]}function zo(e,t,r){return[`cat > ${e} <<'${r}'`,t.replace(/\n$/,""),r,`chmod 600 ${e}`]}function du(e,t){if(!t)return[];let r=[];if(t.composerAuth){let n=typeof t.composerAuth==="string"?t.composerAuth:JSON.stringify(t.composerAuth,null,2);r.push(...zo(`${e}/auth.json`,n,"TS_CLOUD_AUTHJSON_EOF"))}if(t.npmrc)r.push(...zo(`${e}/.npmrc`,t.npmrc,"TS_CLOUD_NPMRC_EOF"));return r}function Ko(e){let t=e.healthCheck?.path;if(!t||!e.domain)return[];let n=`http://127.0.0.1${t.startsWith("/")?t:`/${t}`}`;return[`echo "[ts-cloud] health check ${n} (Host: ${e.domain})"`,"TS_CLOUD_HC_OK=0",`for i in $(seq 1 10); do TS_CLOUD_HC=$(curl -s -o /dev/null -w "%{http_code}" -H "Host: ${e.domain}" -m 10 "${n}" 2>/dev/null || echo 000); case "$TS_CLOUD_HC" in 2*|3*) TS_CLOUD_HC_OK=1; break ;; esac; sleep 3; done`,'[ "$TS_CLOUD_HC_OK" = 1 ] && echo "health check passed ($TS_CLOUD_HC)" || { echo "health check FAILED (last=$TS_CLOUD_HC)" >&2; exit 1; }']}function jo(e){let{siteName:t,site:r,releaseId:n,commit:s}=e;if(!r.repository?.url)throw Error(`Site '${t}' is a PHP/git site but has no repository.url to clone`);let i=e.appBase??`/var/www/${t}`,a="php",c=Yt(i,n),u=r.sharedPaths??cr,f=[...u,...mr(r.env,u)],h=r.keepReleases??Rt,_=r.deployScript?.length?r.deployScript:lu(r.type??"laravel"),S=["set -euo pipefail",'export HOME="${HOME:-/root}"','export COMPOSER_HOME="${COMPOSER_HOME:-/root/.composer}"',"export COMPOSER_ALLOW_SUPERUSER=1",Ee()];if(S.push(...dr(i,{releaseId:n,commit:s,branch:r.repository.branch,keepLogs:h})),S.push(...Ot(c,f)),r.env&&Object.keys(r.env).length>0)S.push(...pu(`${c.shared}/.env`,r.env));for(let v of _){let y=v.trim();if(y===Ir)S.push(...Mo({repository:r.repository,releaseDir:c.release,commit:s})),S.push(...ur(c,f)),S.push(`cd ${c.release}`),S.push(...du(c.release,r.credentials)),S.push(`chown -R www-data:www-data ${c.shared}/storage 2>/dev/null || true`,`[ -d ${c.release}/bootstrap/cache ] && chown -R www-data:www-data ${c.release}/bootstrap/cache 2>/dev/null || true`,`chmod -R ug+rwX ${c.shared}/storage 2>/dev/null || true`);else if(y===Ar)S.push(...ct(c)),S.push(...lt(c,h)),S.push(`(cd ${p} && pantry restart php-fpm) 2>/dev/null || true`);else if(y===Bo)S.push(`${a} artisan queue:restart || true`);else S.push(uu(v,a))}return S}var kr={mysql:{port:3306,binaries:["mysqld","mysql"]},mariadb:{port:3306,binaries:["mariadbd","mariadb","mysqld"]},postgres:{port:5432,binaries:["postgres","psql"]},redis:{port:6379,binaries:["redis-server","redis-cli"]},memcached:{port:11211,binaries:["memcached"]},meilisearch:{port:7700,binaries:["meilisearch"]},vitess:{port:15306,binaries:["vtgate"]}},Bt="ts-cloud-service:";function mu(e){return e===!0||typeof e==="object"&&e!=null}function Vo(e){if(!e)return[];return Object.keys(kr).filter((t)=>mu(e[t]))}function Go(e){if(e.length===0)return[];return[Ee(),"ts_cloud_port_open() {",' if command -v ss >/dev/null 2>&1; then ss -ltn 2>/dev/null | grep -qE "[:.]$1[[:space:]]" && return 0; fi',' if command -v netstat >/dev/null 2>&1; then netstat -ltn 2>/dev/null | grep -qE "[:.]$1[[:space:]]" && return 0; fi'," (exec 3<>/dev/tcp/127.0.0.1/$1) 2>/dev/null && { exec 3<&- 3>&-; return 0; }"," return 1","}","ts_cloud_probe() {",' TS_CLOUD_SVC="$1"; TS_CLOUD_PORT="$2"; shift 2',' for TS_CLOUD_BIN in "$@"; do',` if command -v "$TS_CLOUD_BIN" >/dev/null 2>&1; then echo "${Bt}$TS_CLOUD_SVC:present"; return 0; fi`," done",` if ts_cloud_port_open "$TS_CLOUD_PORT"; then echo "${Bt}$TS_CLOUD_SVC:present"; return 0; fi`,` echo "${Bt}$TS_CLOUD_SVC:missing"`," return 0","}",...e.filter((t)=>kr[t]).map((t)=>`ts_cloud_probe ${t} ${kr[t].port} ${kr[t].binaries.join(" ")}`),"exit 0"]}function qo(e,t){if(!e)return[];let r=new Map;for(let n of e.split(`
|
|
446
|
+
`)){let s=n.indexOf(Bt);if(s===-1)continue;let[i,a]=n.slice(s+Bt.length).trim().split(":");if(i)r.set(i,a)}return t.filter((n)=>r.get(n)==="missing")}function Wo(e,t,r){let n=r?` on ${r}`:"",s=e.map((a)=>`managedServices.${a}`).join(", "),i=e.length===1?`no ${e[0]}`:`none of ${e.join(", ")}`;return`This project declares ${s}, but '${t}' has ${i}${n}. Attach mode does not provision services on the owner's box, so nothing will install ${e.length===1?"it":"them"}. Point the app at an external service, or ask the owner of '${t}' to add ${e.length===1?"it":"them"} to their own config and re-provision.`}var Yo="/var/lib/pantry/php-fpm/pool.d",fu=9100,gu=400;function Nr(e){return(e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"site").slice(0,28)}function Xo(e){return`web_${Nr(e)}`}function hu(e){let t=Nr(e),r=0;for(let n=0;n<t.length;n++)r=r*31+t.charCodeAt(n)>>>0;return fu+r%gu}function jn(e){return`127.0.0.1:${hu(e)}`}function Su(e){let t=Nr(e.siteName),r=Xo(e.siteName),n=e.maxChildren??10;return[`; ts-cloud-managed pool for ${e.siteName} (site isolation)`,`[${t}]`,`user = ${r}`,`group = ${r}`,`listen = ${jn(e.siteName)}`,"pm = dynamic",`pm.max_children = ${n}`,"pm.start_servers = 2","pm.min_spare_servers = 1","pm.max_spare_servers = 3","pm.max_requests = 500","catch_workers_output = yes",`php_admin_value[open_basedir] = ${e.appBase}:/tmp`,""].join(`
|
|
447
|
+
`)}function Jo(e){let t=Xo(e.siteName),r=Nr(e.siteName),n=`${Yo}/${r}.conf`;return[`getent group ${t} >/dev/null || groupadd --system ${t}`,`id -u ${t} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin -g ${t} ${t}`,`usermod -aG ${t} www-data 2>/dev/null || true`,`chown -R ${t}:${t} ${e.appBase} || true`,`chmod -R g+rX ${e.appBase} || true`,`chmod 600 ${e.appBase}/shared/.env 2>/dev/null || true`,`mkdir -p ${Yo}`,`cat > ${n} <<'TS_CLOUD_FPMPOOL_EOF'`,Su(e).replace(/\n$/,""),"TS_CLOUD_FPMPOOL_EOF",`(cd ${p} && pantry restart php-fpm) 2>/dev/null || true`]}var Br={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};function $u(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function co(e,t,r=Br){let{config:n,environment:s,siteName:i,site:a,slug:c,sha:u,runtime:f,localTarballPath:h}=t,_=`releases/${i}/${u}.tar.gz`,S=m(n,s),v=await e.getComputeOutputs({config:n,environment:s}),y=await e.findComputeTargets({slug:c,environment:s,role:"app",stackName:S});if(y.length===0)return{success:!1,error:e.name==="aws"?`Stack '${S}' has no EC2 instances tagged Project=${c} Environment=${s} Role=app, and storage/cloud/state/${S}.json pins no live instance. For a shared box, record its instanceId there.`:`No Hetzner servers labeled ts-cloud/project=${c} ts-cloud/environment=${s} ts-cloud/role=app, and storage/cloud/state/${S}.json pins no live server. For a shared box, record its serverId there.`};let b=v.servicesPrivateIp?Ks(v.servicesPrivateIp,g(n)):is(g(n)),I=Ji(C(n,{environment:s})),D=n.infrastructure?.compute,H=ni(D?.hostCleanup),R=j({...D,proxy:w(n,{environment:s})})?{HOST:"127.0.0.1"}:{},x=s==="production"?{APP_ENV:"production",NODE_ENV:"production"}:{},W={...b,...I,...R,...a.env||{},...x},k=yn(W,a.sharedPaths??[]);if(k.warning)r.warn(`Site '${i}': ${k.warning}`);else if(k.path)r.info(`Site '${i}': sharing '${k.path}' so the SQLite database survives deploys.`);if(jr(a)){let E=a.phpVersion??D?.php?.default??D?.php?.versions?.[0],q=U(c,i),N=Object.keys(b).length>0?{...a,env:W}:a,Y=jo({siteName:i,site:N,releaseId:u,appBase:q,defaultPhpVersion:E}),X=!j(D),P=Bn(a)==="custom"&&a.ssl?.certPath&&a.ssl?.keyPath?{certPath:a.ssl.certPath,keyPath:a.ssl.keyPath}:void 0,L=a.isolation?Jo({siteName:i,appBase:q}):[],ie=X?on({siteName:i,domain:a.domain||i,aliases:a.aliases,type:a.type,appDir:`${q}/current`,webDirectory:a.webDirectory,phpVersion:E,fastcgiPass:a.isolation?jn(i):void 0,redirects:a.redirects,ssl:P,auth:a.auth&&a.auth.enabled!==!1&&a.auth.password?{username:a.auth.username||"admin",password:a.auth.password,realm:a.auth.realm}:void 0,serverSnippet:sn(a.nginx,D?.nginxTemplates),clientMaxBodySize:a.nginx?.clientMaxBodySize,hsts:a.ssl?.hsts,tlsProtocols:a.ssl?.tlsProtocols,security:a.security}):[],re=X?Kn(a):[],Le=zn(a)?Fn({slug:c,siteName:i,site:a,phpVersion:E,appBase:q}):[],Kt=X?Ko(a):[];r.step(`Deploying PHP site '${i}' to ${y.length} target(s)...`);let Ke=await e.runRemoteDeploy({targets:y,commands:[..._n(q,c),...Lr(q,c),...Y,...L,...ie,...re,...Le,...Kt,...H],comment:`ts-cloud deploy ${c}/${i}@${u}`,tags:{Project:c,Environment:s,Role:"app"}}),Gn=ps(n.notifications,a.notifications);if(!Ke.success)return await Zo(e,y,H,r),await cn(Gn,"deploy-failed",`❌ Deploy of ${c}/${i}@${u} failed: ${Ke.error||"unknown error"}`),{success:!1,error:Ke.error||"Remote PHP deploy failed",instanceCount:Ke.instanceCount,perInstance:Ke.perInstance};let $i=a.domain?` → https://${a.domain}`:"";return await cn(Gn,"deploy",`✅ Deployed ${c}/${i}@${u}${$i}`),{success:!0,instanceCount:Ke.instanceCount,perInstance:Ke.perInstance}}if(!h)return{success:!1,error:`Site '${i}' requires a release tarball but none was provided`};let V=await e.uploadRelease({config:n,environment:s,localPath:h,remoteKey:_,targets:y}),te=ai(c,i,u),ue=e.name==="aws"?Lc(v.deployBucketName,_,n.project.region||"us-east-1",te):$c(V.artifactRef,te),me=d(a),Z=U(c,i),pe=me==="server-static"?oi({siteName:i,slug:c,appDir:Z,artifactFetch:ue,releaseId:u,preStartCommands:a.preStart}):si({siteName:i,slug:c,appDir:Z,artifactFetch:ue,releaseId:u,execStart:ii(a.start,f,`${Z.replace(/\/+$/,"")}/releases/%i`),envEntries:W,port:a.port,preStartCommands:a.preStart,sharedPaths:a.sharedPaths,zeroDowntime:a.zeroDowntime!==!1,healthCheckPath:a.healthCheck?.path,liveness:a.liveness,memoryHigh:a.memoryHigh,memoryMax:a.memoryMax,cpuWeight:a.cpuWeight,ioWeight:a.ioWeight,tasksMax:a.tasksMax,stopTimeout:a.stopTimeout}),ne=me==="server-static"&&!j(D)&&!!a.domain,ee=ne?on({siteName:i,domain:a.domain,aliases:a.aliases,type:a.type==="spa"?"spa":"static",appDir:`${Z}/current`,webDirectory:"",redirects:a.redirects,auth:a.auth&&a.auth.enabled!==!1&&a.auth.password?{username:a.auth.username||"admin",password:a.auth.password,realm:a.auth.realm}:void 0,serverSnippet:sn(a.nginx,D?.nginxTemplates),clientMaxBodySize:a.nginx?.clientMaxBodySize,hsts:a.ssl?.hsts,tlsProtocols:a.ssl?.tlsProtocols,security:a.security}):[],ge=ne?Kn(a):[],T=zn(a)?Fn({slug:c,siteName:i,site:a,appBase:Z}):[],O=[...dr(Z,{releaseId:u,commit:u,branch:a.repository?.branch??"main"}),..._n(Z,c),...Lr(Z,c),...pe,...ee,...ge,...T,...H];r.step(`Deploying to ${y.length} target(s)...`);let K=await e.runRemoteDeploy({targets:y,commands:O,comment:`ts-cloud deploy ${c}/${i}@${u}`,tags:{Project:c,Environment:s,Role:"app"}});if(!K.success)return await Zo(e,y,H,r),{success:!1,error:K.error||"Remote deploy failed",instanceCount:K.instanceCount,perInstance:K.perInstance};return{success:!0,instanceCount:K.instanceCount,perInstance:K.perInstance}}async function Zo(e,t,r,n){if(r.length===0)return;try{let s=await e.runRemoteDeploy({targets:t,commands:r,comment:"ts-cloud host cleanup after failed deploy"});if(!s.success)n.warn(`Host cleanup after the failed deploy did not complete: ${s.error||"unknown error"}`)}catch(s){n.warn(`Host cleanup after the failed deploy did not run: ${s.message}`)}}function zr(e){return`'${e.replaceAll("'","'\\''")}'`}function bu(e,t,r=!1,n=[]){let s=`${e}-dashboard-`,i=t.map((c)=>`${e}-${c}.service`),a=r?[`export TS_CLOUD_DASHBOARD_KEEP_DOMAINS=${zr(JSON.stringify(n))}`,"rm -f /run/ts-cloud-dashboard-routes-changed",`/usr/local/bin/bun --bun -e ${zr(`
|
|
443
448
|
const { chmodSync, existsSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } = require('node:fs')
|
|
444
449
|
const { basename, join } = require('node:path')
|
|
445
450
|
const root = '/etc/rpx/sites.d'
|
|
@@ -467,4 +472,4 @@ This password is now in your deploy log. Set TS_CLOUD_UI_PASSWORD to a value of
|
|
|
467
472
|
changed = true
|
|
468
473
|
}
|
|
469
474
|
if (changed) writeFileSync('/run/ts-cloud-dashboard-routes-changed', '')
|
|
470
|
-
`)}`,"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=${Ir(s)}`,`TS_CLOUD_DASHBOARD_SERVER_OWNER=${r?"1":"0"}`,`TS_CLOUD_DASHBOARD_DESIRED=${Ir(` ${i.join(" ")} `)}`,"for TS_CLOUD_UNIT_FILE in /etc/systemd/system/*.service; do",' [ -e "$TS_CLOUD_UNIT_FILE" ] || continue',' TS_CLOUD_UNIT=$(basename "$TS_CLOUD_UNIT_FILE")',' case "$TS_CLOUD_UNIT" in'," *-dashboard-*.service)",' if [ "$TS_CLOUD_DASHBOARD_SERVER_OWNER" != 1 ]; then',' case "$TS_CLOUD_UNIT" in "$TS_CLOUD_DASHBOARD_PREFIX"*.service) ;; *) continue ;; esac'," fi",' case "$TS_CLOUD_DASHBOARD_DESIRED" in',' *" $TS_CLOUD_UNIT "*) ;;'," *)",' systemctl disable --now "$TS_CLOUD_UNIT" 2>/dev/null || true',' rm -f "$TS_CLOUD_UNIT_FILE"'," ;;"," esac"," ;;"," esac","done","systemctl daemon-reload","systemctl reset-failed",...a]}async function Su(e,t,r,n){let{config:s,environment:i}=t,a=s.project.slug,c=p(s,i),u=await e.findComputeTargets({slug:a,environment:i,role:"app",stackName:c});if(u.length===0)return!0;let m=await e.runRemoteDeploy({targets:u,commands:hu(a,r,!s.cloud?.attachTo,r.map((h)=>s.sites?.[h]?.domain).filter((h)=>typeof h==="string")),comment:`ts-cloud reconcile management dashboard ${a}`,tags:{Project:a,Environment:i,Role:"app"}});if(!m.success)return n.error(`Management dashboard reconciliation failed: ${m.error||"unknown error"}`),!1;return!0}async function _u(e,t,r){let{config:n}=t,s=n.cloud?.attachTo;if(!s||!e.listReachableResources)return;let i;try{i=await e.listReachableResources()}catch(u){r.warn(`Could not determine this credential's reach: ${u instanceof Error?u.message:String(u)}`);return}let a=yo(i,{ownerSlug:s,selfSlug:n.project.slug}),c=Dn(a)>0;for(let u of $o(a,{ownerSlug:s,selfSlug:n.project.slug}))if(c)r.warn(u);else r.info(u)}async function vu(e,t,r){let{config:n,environment:s}=t,i=n.cloud?.attachTo;if(!i)return!0;let a=jo(n.infrastructure?.compute?.managedServices);if(a.length===0)return!0;let c=n.project.slug,u=p(n,s),m=await e.findComputeTargets({slug:c,environment:s,role:"app",stackName:u});if(m.length===0)return!0;let h=await e.runRemoteDeploy({targets:m,commands:Vo(a),comment:`ts-cloud preflight managed services ${c}`,tags:{Project:c,Environment:s,Role:"app"}});if(!h.success)return r.warn(`Could not check '${i}' for the declared services: ${h.error||"unknown error"}`),!0;let S=new Set;for(let v of h.perInstance)for(let _ of Go(v.output,a))S.add(_);if(S.size===0)return!0;return r.error(qo([...S],i,m[0]?.publicIp)),!1}async function yu(e,t,r){let{config:n,environment:s}=t;if(!n.cloud?.attachTo)return!0;let i=n.infrastructure?.compute,a=g(n),c=ot(a,i?.managedServices??{});if(c.length===0)return!0;let u=n.project.slug,m=p(n,s),h=await e.findComputeTargets({slug:u,environment:s,role:"app",stackName:m});if(h.length===0)return!0;r.step(`Ensuring database '${a?.name}' + role exist on the shared box...`);let S=await e.runRemoteDeploy({targets:h,commands:c,comment:`ts-cloud ensure database ${u}/${a?.name}`,tags:{Project:u,Environment:s,Role:"app"}});if(!S.success)return r.error(`Ensuring database '${a?.name}' failed: ${S.error||"unknown error"}`),!1;return r.success(`Database '${a?.name}' is ready on ${S.instanceCount} target(s)`),!0}async function sd(e){let{config:t,environment:r,driver:n,sha:s,runtime:i,tarballForSite:a,logger:c=Ar}=e,u=t.project.slug,m=e.cwd??process.cwd(),h=e.managementDashboard!==!1,S=ur(t);if(h)Ti(t,{cwd:m,logger:{info:c.info,warn:c.warn}});let v=!h||S?[]:Un(t);if(h&&e.rpxConfig&&e.rpxConfig!==t&&!ur(e.rpxConfig))Ti(e.rpxConfig,{cwd:m,logger:{info:()=>{},warn:()=>{}}});if(h&&!await Su(n,e,Un(t),c))return!1;let _=null,y=new Map;if(v.length>0)if(_=oo(t.sites?.[v[0]],{cwd:m,slug:u,sha:s,siteName:v[0],logger:{info:c.info,warn:c.warn}}),!_){c.warn("Management dashboard: no artifact available — skipping dashboard site(s) for this deploy.");for(let R of v)if(t.sites)delete t.sites[R]}else for(let R of v){if(R===v[0]){y.set(R,_);continue}try{let x=fu(mu(),`${u}-${R}-${s}.tar.gz`);du(_,x),y.set(R,x)}catch{y.set(R,_)}}let b=t.sites||{},I=Object.entries(b).filter(([R,x])=>{if(!x)return!1;let W=d(x);if(W==="bucket")return c.warn(`Site '${R}' targets a bucket — skipping (handled by the static-site path, not compute).`),!1;if(W==="redirect")return!1;if(W==="proxy")return!1;return!0});if(I.length===0)return wi(e);if(await _u(n,e,c),!await vu(n,e,c))return!1;if(!await yu(n,e,c))return!1;let D=(R)=>y.get(R)??a(R);for(let[R,x]of I){c.step(`Deploying site: ${R}`);let W=qr(x)?void 0:D(R),k=await ao(n,{config:t,environment:r,siteName:R,site:x,slug:u,sha:s,runtime:i,localTarballPath:W},c);if(!k.success){if(c.error(`Deploy of '${R}' failed: ${k.error||"unknown error"}`),k.perInstance)for(let V of k.perInstance)c.error(` ${V.instanceId}: ${V.status}${V.error?` — ${V.error}`:""}`);return!1}if(c.success(`Deployed ${u}/${R}@${s} to ${k.instanceCount} target(s)`),k.perInstance)for(let V of k.perInstance)c.info(` ✓ ${V.instanceId}: ${V.status}`)}if(!await wi(e))return!1;return!0}async function $u(e,t,r){let n=Ip(e);if(!n||n.tls==="off")return n;let s=await je(t,r),i=s?.provider==="ssh"?s.lanIp:void 0;return i?{...n,ip:i}:n}async function wi(e){let{config:t,environment:r,driver:n,logger:s=Ar}=e,i=e.rpxConfig??t,a=w(i,{environment:r})??w(t,{environment:r});if(a?.engine!=="rpx")return!0;let c=i.sites||{},u=t.project.slug,m=p(t,r),h=await n.findComputeTargets({slug:u,environment:r,role:"lb",stackName:m});if(h.length>0){let H=(await n.findComputeTargets({slug:u,environment:r,role:"app",stackName:m})).map((W)=>({privateIp:W.privateIp,publicIp:W.publicIp})),R=er(c,H,{proxy:a,slug:u});if(R.proxies.length===0)return s.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;s.step(`Reloading the load balancer's rpx gateway with ${R.proxies.length} route(s)...`);let x=await n.runRemoteDeploy({targets:h,commands:Ne({config:R,slug:u,preserveManagementDashboardRoutes:e.managementDashboard===!1}),comment:`ts-cloud rpx gateway reload ${u}`,tags:{Project:u,Environment:r,Role:"lb"}});if(!x.success)return s.error(`rpx gateway reload failed: ${x.error||"unknown error"}`),!1;return s.success(`rpx gateway reloaded on ${x.instanceCount} load balancer(s)`),!0}let S=await $u(t,m,e.cwd),v=B(c,{proxy:a,slug:u,lan:S,mail:C(t,{environment:r})});if(v.proxies.length===0)return s.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;let _=await n.findComputeTargets({slug:u,environment:r,role:"app",stackName:m});if(_.length===0)return s.warn("rpx gateway: no compute targets found — skipping gateway reload."),!0;let y=Boolean(t.cloud?.attachTo);if(y&&(a.version||a.tlsxVersion))s.warn(`rpx gateway: ignoring proxy.version/tlsxVersion — this project attaches to '${t.cloud?.attachTo}' and the gateway belongs to that box's owner.`);s.step(`Reloading rpx gateway with ${v.proxies.length} route(s)...`);let b=G({proxy:a,config:v,slug:u,tenant:y,profile:bp(t),preserveManagementDashboardRoutes:e.managementDashboard===!1}),I=await n.runRemoteDeploy({targets:_,commands:b,comment:`ts-cloud rpx gateway reload ${u}`,tags:{Project:u,Environment:r,Role:"app"}});if(!I.success)return s.error(`rpx gateway reload failed: ${I.error||"unknown error"}`),!1;return s.success(`rpx gateway reloaded on ${I.instanceCount} target(s)`),!0}async function od(e){let{config:t,environment:r,driver:n,logger:s=Ar}=e,i=e.rpxConfig??t,a=w(i,{environment:r})??w(t,{environment:r});if(a?.engine!=="rpx"||!a.onDemandTls)return!0;let c=B(i.sites||{},{proxy:a,slug:t.project.slug,mail:C(t,{environment:r})});if(c.proxies.length===0)return!0;let u=ud(c);if(u.length===0)return!0;let m=t.project.slug,h=p(t,r),S="lb",v=await n.findComputeTargets({slug:m,environment:r,role:S,stackName:h});if(v.length===0)S="app",v=await n.findComputeTargets({slug:m,environment:r,role:S,stackName:h});if(v.length===0)return s.warn("rpx TLS: no gateway targets found - skipping certificate issuance."),!0;s.step("Issuing rpx TLS certificates after DNS reconciliation...");let _=u.map((b)=>`test -s ${gu(`${c.productionCerts.certsDir}/${b}.crt`)}`).join(" && "),y=await n.runRemoteDeploy({targets:v,commands:[`systemctl start ${ld(m)}`,_],comment:`ts-cloud rpx TLS issuance ${m}`,tags:{Project:m,Environment:r,Role:S}});if(!y.success)return s.error(`rpx TLS issuance failed: ${y.error||"unknown error"}`),!1;return s.success(`rpx TLS certificates reconciled on ${y.instanceCount} gateway target(s)`),!0}var hp="658327ea-f89d-4fab-a63d-7e88639e58f6",Ap="4135ea2d-6df8-44a3-9df3-4b5a84be39ad",yp="216adef6-5c7f-47e4-b989-5492eafa07d3",Kn="origin",Zo="origin-failover";function Qo(e,t){let r={TargetOriginId:Kn,ViewerProtocolPolicy:"redirect-to-https",Compress:!0,CachePolicyId:t==="dynamic"?Ap:hp,OriginRequestPolicyId:yp,SmoothStreaming:!1,FieldLevelEncryptionId:"",TrustedSigners:{Enabled:!1,Quantity:0},TrustedKeyGroups:{Enabled:!1,Quantity:0},LambdaFunctionAssociations:{Quantity:0},FunctionAssociations:{Quantity:0},AllowedMethods:t==="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(e!==null)r.PathPattern=e;return r}function Xh(e){let t=e.aliases;if(t.length===0)throw Error("buildCloudFrontOriginConfig: at least one alias is required");if(t.includes(e.originDomain))throw Error(`buildCloudFrontOriginConfig: originDomain ${e.originDomain} must not be one of the aliases (it would loop)`);if(e.originShield&&!e.originShieldRegion)throw Error("buildCloudFrontOriginConfig: originShieldRegion is required when originShield is enabled");let r=e.failoverOriginDomain;if(r!==void 0){if(t.includes(r))throw Error(`buildCloudFrontOriginConfig: failoverOriginDomain ${r} must not be one of the aliases (it would loop)`);if(r===e.originDomain)throw Error("buildCloudFrontOriginConfig: failoverOriginDomain must differ from originDomain")}else if(e.failoverStatusCodes)throw Error("buildCloudFrontOriginConfig: failoverStatusCodes needs failoverOriginDomain to fail over to");let n=e.originSecretHeader??"X-Origin-Verify",s=e.originSecret?{Quantity:1,Items:[{HeaderName:n,HeaderValue:e.originSecret}]}:{Quantity:0},i=[...e.behaviors??[]].sort((v,_)=>_.pathPattern.length-v.pathPattern.length),a=ce(e,"buildCloudFrontOriginConfig"),c=(v,_,y,b={})=>({Id:v,DomainName:_,OriginPath:"",CustomHeaders:s,CustomOriginConfig:{HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only",OriginSslProtocols:{Quantity:1,Items:["TLSv1.2"]},OriginReadTimeout:30,OriginKeepaliveTimeout:5},ConnectionAttempts:b.ConnectionAttempts??3,ConnectionTimeout:b.ConnectionTimeout??10,OriginShield:y,OriginAccessControlId:""}),u=[c(Kn,e.originDomain,e.originShield?{Enabled:!0,OriginShieldRegion:e.originShieldRegion}:{Enabled:!1},a)],m={Quantity:0},h=Qo(null,"static");if(r!==void 0)u.push(c(Zo,r,{Enabled:!1})),m=dn({primaryOriginId:Kn,secondaryOriginId:Zo,statusCodes:e.failoverStatusCodes}),Rt(h.AllowedMethods,"the default cache behavior"),h.TargetOriginId=m.Items[0].Id;let S={CallerReference:e.callerReference??e.originDomain,Comment:e.comment??`Origin-fronted distribution for ${t[0]} → ${e.originDomain}`,Enabled:!0,Aliases:{Quantity:t.length,Items:t},DefaultRootObject:"",Origins:{Quantity:u.length,Items:u},OriginGroups:m,DefaultCacheBehavior:h,CacheBehaviors:{Quantity:i.length,Items:i.map((v)=>Qo(v.pathPattern,v.kind))},ViewerCertificate:{CloudFrontDefaultCertificate:!1,ACMCertificateArn:e.viewerCertificateArn,Certificate:e.viewerCertificateArn,CertificateSource:"acm",SSLSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"},PriceClass:e.priceClass??"PriceClass_All",HttpVersion:"http2and3",IsIPV6Enabled:!0,Restrictions:{GeoRestriction:{RestrictionType:"none",Quantity:0}},Logging:{Enabled:!1,IncludeCookies:!1,Bucket:"",Prefix:""},WebACLId:"",CustomErrorResponses:{Quantity:0}};return Dt(S,"buildCloudFrontOriginConfig"),S}export{Pg,Bc,kg,De,xc,Jn,Ng,Oc,Xn,Kt,Br,Wt,Bg,xg,$h,f,mt,Xs,Yn,Jt,xr,Og,Ys,M,Or,Zn,ei,_r,Xt,_g,Lg,Lr,Mh,Fh,$g,Mg,Uh,Qh,Hh,$r,ti,Fg,Zs,ri,ni,ii,si,oi,_c,Lc,ai,Mr,Se,$c,Yt,Mc,ci,Fc,Uc,Fr,Qc,Ve,se,eo,Ug,Hc,Gc,Vc,qc,jc,ft,qe,je,ht,di,li,Pe,to,zc,Qg,Hg,Kc,Gg,At,ui,Wc,Vg,qg,Jc,yt,ke,Xc,jg,zg,ro,gi,St,Kg,Wg,Jg,Xg,Yg,Zg,ep,tp,rp,pi,mi,fi,hi,Ai,yi,Si,np,ip,Ur,F,no,sp,op,ap,Yc,cp,dp,Gh,Vh,qh,Zc,lp,jh,zh,Kh,Ii,bi,Ci,Ei,ed,td,vi,rd,Wh,io,up,gp,pp,mp,fp,Jh,nd,so,id,Zt,Ti,oo,Qr,ao,sd,wi,od,hp,Ap,yp,Xh};
|
|
475
|
+
`)}`,"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=${zr(s)}`,`TS_CLOUD_DASHBOARD_SERVER_OWNER=${r?"1":"0"}`,`TS_CLOUD_DASHBOARD_DESIRED=${zr(` ${i.join(" ")} `)}`,"for TS_CLOUD_UNIT_FILE in /etc/systemd/system/*.service; do",' [ -e "$TS_CLOUD_UNIT_FILE" ] || continue',' TS_CLOUD_UNIT=$(basename "$TS_CLOUD_UNIT_FILE")',' case "$TS_CLOUD_UNIT" in'," *-dashboard-*.service)",' if [ "$TS_CLOUD_DASHBOARD_SERVER_OWNER" != 1 ]; then',' case "$TS_CLOUD_UNIT" in "$TS_CLOUD_DASHBOARD_PREFIX"*.service) ;; *) continue ;; esac'," fi",' case "$TS_CLOUD_DASHBOARD_DESIRED" in',' *" $TS_CLOUD_UNIT "*) ;;'," *)",' systemctl disable --now "$TS_CLOUD_UNIT" 2>/dev/null || true',' rm -f "$TS_CLOUD_UNIT_FILE"'," ;;"," esac"," ;;"," esac","done","systemctl daemon-reload","systemctl reset-failed",...a]}async function Tu(e,t,r,n){let{config:s,environment:i}=t,a=s.project.slug,c=m(s,i),u=await e.findComputeTargets({slug:a,environment:i,role:"app",stackName:c});if(u.length===0)return!0;let f=await e.runRemoteDeploy({targets:u,commands:bu(a,r,!s.cloud?.attachTo,r.map((h)=>s.sites?.[h]?.domain).filter((h)=>typeof h==="string")),comment:`ts-cloud reconcile management dashboard ${a}`,tags:{Project:a,Environment:i,Role:"app"}});if(!f.success)return n.error(`Management dashboard reconciliation failed: ${f.error||"unknown error"}`),!1;return!0}async function wu(e,t,r){let{config:n}=t,s=n.cloud?.attachTo;if(!s||!e.listReachableResources)return;let i;try{i=await e.listReachableResources()}catch(u){r.warn(`Could not determine this credential's reach: ${u instanceof Error?u.message:String(u)}`);return}let a=$o(i,{ownerSlug:s,selfSlug:n.project.slug}),c=In(a)>0;for(let u of bo(a,{ownerSlug:s,selfSlug:n.project.slug}))if(c)r.warn(u);else r.info(u)}async function Cu(e,t,r){let{config:n,environment:s}=t,i=n.cloud?.attachTo;if(!i)return!0;let a=Vo(n.infrastructure?.compute?.managedServices);if(a.length===0)return!0;let c=n.project.slug,u=m(n,s),f=await e.findComputeTargets({slug:c,environment:s,role:"app",stackName:u});if(f.length===0)return!0;let h=await e.runRemoteDeploy({targets:f,commands:Go(a),comment:`ts-cloud preflight managed services ${c}`,tags:{Project:c,Environment:s,Role:"app"}});if(!h.success)return r.warn(`Could not check '${i}' for the declared services: ${h.error||"unknown error"}`),!0;let _=new Set;for(let S of h.perInstance)for(let v of qo(S.output,a))_.add(v);if(_.size===0)return!0;return r.error(Wo([..._],i,f[0]?.publicIp)),!1}async function Pu(e,t,r){let{config:n,environment:s}=t;if(!n.cloud?.attachTo)return!0;let i=n.infrastructure?.compute,a=g(n),c=ot(a,i?.managedServices??{});if(c.length===0)return!0;let u=n.project.slug,f=m(n,s),h=await e.findComputeTargets({slug:u,environment:s,role:"app",stackName:f});if(h.length===0)return!0;r.step(`Ensuring database '${a?.name}' + role exist on the shared box...`);let _=await e.runRemoteDeploy({targets:h,commands:c,comment:`ts-cloud ensure database ${u}/${a?.name}`,tags:{Project:u,Environment:s,Role:"app"}});if(!_.success)return r.error(`Ensuring database '${a?.name}' failed: ${_.error||"unknown error"}`),!1;return r.success(`Database '${a?.name}' is ready on ${_.instanceCount} target(s)`),!0}async function od(e){let{config:t,environment:r,driver:n,sha:s,runtime:i,tarballForSite:a,logger:c=Br}=e,u=t.project.slug,f=e.cwd??process.cwd(),h=e.managementDashboard!==!1,_=gr(t);if(h)Ri(t,{cwd:f,logger:{info:c.info,warn:c.warn}});let S=!h||_?[]:kn(t);if(h&&e.rpxConfig&&e.rpxConfig!==t&&!gr(e.rpxConfig))Ri(e.rpxConfig,{cwd:f,logger:{info:()=>{},warn:()=>{}}});if(h&&!await Tu(n,e,kn(t),c))return!1;let v=null,y=new Map;if(S.length>0)if(v=ao(t.sites?.[S[0]],{cwd:f,slug:u,sha:s,siteName:S[0],logger:{info:c.info,warn:c.warn}}),!v){c.warn("Management dashboard: no artifact available — skipping dashboard site(s) for this deploy.");for(let R of S)if(t.sites)delete t.sites[R]}else for(let R of S){if(R===S[0]){y.set(R,v);continue}try{let x=yu(_u(),`${u}-${R}-${s}.tar.gz`);vu(v,x),y.set(R,x)}catch{y.set(R,v)}}let b=t.sites||{},I=Object.entries(b).filter(([R,x])=>{if(!x)return!1;let W=d(x);if(W==="bucket")return c.warn(`Site '${R}' targets a bucket — skipping (handled by the static-site path, not compute).`),!1;if(W==="redirect")return!1;if(W==="proxy")return!1;return!0});if(I.length===0)return Di(e);if(await wu(n,e,c),!await Cu(n,e,c))return!1;if(!await Pu(n,e,c))return!1;let D=(R)=>y.get(R)??a(R);for(let[R,x]of I){c.step(`Deploying site: ${R}`);let W=jr(x)?void 0:D(R),k=await co(n,{config:t,environment:r,siteName:R,site:x,slug:u,sha:s,runtime:i,localTarballPath:W},c);if(!k.success){if(c.error(`Deploy of '${R}' failed: ${k.error||"unknown error"}`),k.perInstance)for(let V of k.perInstance)c.error(` ${V.instanceId}: ${V.status}${V.error?` — ${V.error}`:""}`);return!1}if(c.success(`Deployed ${u}/${R}@${s} to ${k.instanceCount} target(s)`),k.perInstance)for(let V of k.perInstance)c.info(` ✓ ${V.instanceId}: ${V.status}`)}if(!await Di(e))return!1;return!0}async function Eu(e,t,r){let n=Ip(e);if(!n||n.tls==="off")return n;let s=await je(t,r),i=s?.provider==="ssh"?s.lanIp:void 0;return i?{...n,ip:i}:n}async function Di(e){let{config:t,environment:r,driver:n,logger:s=Br}=e,i=e.rpxConfig??t,a=w(i,{environment:r})??w(t,{environment:r});if(a?.engine!=="rpx")return!0;let c=i.sites||{},u=t.project.slug,f=m(t,r),h=await n.findComputeTargets({slug:u,environment:r,role:"lb",stackName:f});if(h.length>0){let H=(await n.findComputeTargets({slug:u,environment:r,role:"app",stackName:f})).map((W)=>({privateIp:W.privateIp,publicIp:W.publicIp})),R=tr(c,H,{proxy:a,slug:u});if(R.proxies.length===0)return s.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;s.step(`Reloading the load balancer's rpx gateway with ${R.proxies.length} route(s)...`);let x=await n.runRemoteDeploy({targets:h,commands:Ne({config:R,slug:u,preserveManagementDashboardRoutes:e.managementDashboard===!1}),comment:`ts-cloud rpx gateway reload ${u}`,tags:{Project:u,Environment:r,Role:"lb"}});if(!x.success)return s.error(`rpx gateway reload failed: ${x.error||"unknown error"}`),!1;return s.success(`rpx gateway reloaded on ${x.instanceCount} load balancer(s)`),!0}let _=await Eu(t,f,e.cwd),S=B(c,{proxy:a,slug:u,lan:_,mail:C(t,{environment:r})});if(S.proxies.length===0)return s.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;let v=await n.findComputeTargets({slug:u,environment:r,role:"app",stackName:f});if(v.length===0)return s.warn("rpx gateway: no compute targets found — skipping gateway reload."),!0;let y=Boolean(t.cloud?.attachTo);if(y&&(a.version||a.tlsxVersion))s.warn(`rpx gateway: ignoring proxy.version/tlsxVersion — this project attaches to '${t.cloud?.attachTo}' and the gateway belongs to that box's owner.`);s.step(`Reloading rpx gateway with ${S.proxies.length} route(s)...`);let b=G({proxy:a,config:S,slug:u,tenant:y,profile:bp(t),preserveManagementDashboardRoutes:e.managementDashboard===!1}),I=await n.runRemoteDeploy({targets:v,commands:b,comment:`ts-cloud rpx gateway reload ${u}`,tags:{Project:u,Environment:r,Role:"app"}});if(!I.success)return s.error(`rpx gateway reload failed: ${I.error||"unknown error"}`),!1;return s.success(`rpx gateway reloaded on ${I.instanceCount} target(s)`),!0}async function ad(e){let{config:t,environment:r,driver:n,logger:s=Br}=e,i=e.rpxConfig??t,a=w(i,{environment:r})??w(t,{environment:r});if(a?.engine!=="rpx"||!a.onDemandTls)return!0;let c=B(i.sites||{},{proxy:a,slug:t.project.slug,mail:C(t,{environment:r})});if(c.proxies.length===0)return!0;let u=gd(c);if(u.length===0)return!0;let f=t.project.slug,h=m(t,r),_="lb",S=await n.findComputeTargets({slug:f,environment:r,role:_,stackName:h});if(S.length===0)_="app",S=await n.findComputeTargets({slug:f,environment:r,role:_,stackName:h});if(S.length===0)return s.warn("rpx TLS: no gateway targets found - skipping certificate issuance."),!0;s.step("Issuing rpx TLS certificates after DNS reconciliation...");let v=u.map((b)=>`test -s ${$u(`${c.productionCerts.certsDir}/${b}.crt`)}`).join(" && "),y=await n.runRemoteDeploy({targets:S,commands:[`systemctl start ${ud(f)}`,v],comment:`ts-cloud rpx TLS issuance ${f}`,tags:{Project:f,Environment:r,Role:_}});if(!y.success)return s.error(`rpx TLS issuance failed: ${y.error||"unknown error"}`),!1;return s.success(`rpx TLS certificates reconciled on ${y.instanceCount} gateway target(s)`),!0}var hp="658327ea-f89d-4fab-a63d-7e88639e58f6",Ap="4135ea2d-6df8-44a3-9df3-4b5a84be39ad",yp="216adef6-5c7f-47e4-b989-5492eafa07d3",Vn="origin",Qo="origin-failover";function _i(e,t){let r={TargetOriginId:Vn,ViewerProtocolPolicy:"redirect-to-https",Compress:!0,CachePolicyId:t==="dynamic"?Ap:hp,OriginRequestPolicyId:yp,SmoothStreaming:!1,FieldLevelEncryptionId:"",TrustedSigners:{Enabled:!1,Quantity:0},TrustedKeyGroups:{Enabled:!1,Quantity:0},LambdaFunctionAssociations:{Quantity:0},FunctionAssociations:{Quantity:0},AllowedMethods:t==="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(e!==null)r.PathPattern=e;return r}function Xh(e){let t=e.aliases;if(t.length===0)throw Error("buildCloudFrontOriginConfig: at least one alias is required");if(t.includes(e.originDomain))throw Error(`buildCloudFrontOriginConfig: originDomain ${e.originDomain} must not be one of the aliases (it would loop)`);if(e.originShield&&!e.originShieldRegion)throw Error("buildCloudFrontOriginConfig: originShieldRegion is required when originShield is enabled");let r=e.failoverOriginDomain;if(r!==void 0){if(t.includes(r))throw Error(`buildCloudFrontOriginConfig: failoverOriginDomain ${r} must not be one of the aliases (it would loop)`);if(r===e.originDomain)throw Error("buildCloudFrontOriginConfig: failoverOriginDomain must differ from originDomain")}else if(e.failoverStatusCodes)throw Error("buildCloudFrontOriginConfig: failoverStatusCodes needs failoverOriginDomain to fail over to");let n=e.originSecretHeader??"X-Origin-Verify",s=e.originSecret?{Quantity:1,Items:[{HeaderName:n,HeaderValue:e.originSecret}]}:{Quantity:0},i=[...e.behaviors??[]].sort((S,v)=>v.pathPattern.length-S.pathPattern.length),a=ce(e,"buildCloudFrontOriginConfig"),c=(S,v,y,b={})=>({Id:S,DomainName:v,OriginPath:"",CustomHeaders:s,CustomOriginConfig:{HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only",OriginSslProtocols:{Quantity:1,Items:["TLSv1.2"]},OriginReadTimeout:30,OriginKeepaliveTimeout:5},ConnectionAttempts:b.ConnectionAttempts??3,ConnectionTimeout:b.ConnectionTimeout??10,OriginShield:y,OriginAccessControlId:""}),u=[c(Vn,e.originDomain,e.originShield?{Enabled:!0,OriginShieldRegion:e.originShieldRegion}:{Enabled:!1},a)],f={Quantity:0},h=_i(null,"static");if(r!==void 0)u.push(c(Qo,r,{Enabled:!1})),f=ln({primaryOriginId:Vn,secondaryOriginId:Qo,statusCodes:e.failoverStatusCodes}),Dt(h.AllowedMethods,"the default cache behavior"),h.TargetOriginId=f.Items[0].Id;let _={CallerReference:e.callerReference??e.originDomain,Comment:e.comment??`Origin-fronted distribution for ${t[0]} → ${e.originDomain}`,Enabled:!0,Aliases:{Quantity:t.length,Items:t},DefaultRootObject:"",Origins:{Quantity:u.length,Items:u},OriginGroups:f,DefaultCacheBehavior:h,CacheBehaviors:{Quantity:i.length,Items:i.map((S)=>_i(S.pathPattern,S.kind))},ViewerCertificate:{CloudFrontDefaultCertificate:!1,ACMCertificateArn:e.viewerCertificateArn,Certificate:e.viewerCertificateArn,CertificateSource:"acm",SSLSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"},PriceClass:e.priceClass??"PriceClass_All",HttpVersion:"http2and3",IsIPV6Enabled:!0,Restrictions:{GeoRestriction:{RestrictionType:"none",Quantity:0}},Logging:{Enabled:!1,IncludeCookies:!1,Bucket:"",Prefix:""},WebACLId:"",CustomErrorResponses:{Quantity:0}};return Pt(_,"buildCloudFrontOriginConfig"),_}export{kg,xc,Ng,De,Oc,Xn,Bg,_c,Yn,Wt,xr,Jt,xg,Og,$h,p,mt,Zs,Zn,Xt,Or,_g,eo,M,_r,ei,ti,Lr,Yt,Lg,$g,$r,Mh,Fh,Mg,Fg,Uh,Qh,Hh,Mr,ri,Ug,to,ni,ii,si,oi,ai,Lc,$c,ci,Fr,Se,Mc,ft,Fc,di,Uc,Qc,Ur,Hc,Ve,se,Zt,Qg,li,Gc,Vc,qc,jc,ht,qe,je,At,ui,gi,Pe,ro,zc,Hg,Gg,Kc,Vg,yt,pi,Wc,qg,jg,Jc,St,ke,Xc,zg,Kg,no,mi,It,Wg,Jg,Xg,Yg,Zg,ep,tp,rp,np,fi,hi,Ai,yi,Si,Ii,bi,ip,sp,Qr,F,io,op,ap,cp,Yc,dp,lp,Gh,Vh,qh,Zc,up,jh,zh,Kh,Ci,Ei,vi,Ti,ed,td,wi,rd,Wh,so,gp,pp,mp,fp,nd,Jh,id,oo,sd,er,Ri,ao,Hr,co,od,Di,ad,hp,Ap,yp,Xh};
|