@stacksjs/ts-cloud 0.12.11 → 0.12.12
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/bin/{chunk-vsd7670h.js → chunk-0b49jjgr.js} +1 -1
- package/dist/bin/chunk-0xnnkeb1.js +1 -0
- package/dist/bin/{chunk-hwdfky19.js → chunk-227jmf2b.js} +2 -2
- package/dist/bin/chunk-2nyyg44g.js +1 -0
- package/dist/bin/{chunk-f42gqn6c.js → chunk-2ztr119n.js} +1 -1
- package/dist/bin/chunk-43xj5cny.js +1 -0
- package/dist/bin/chunk-5w6y9pmz.js +1 -0
- package/dist/bin/{chunk-j2cb8we4.js → chunk-5x4rdx8k.js} +1 -1
- package/dist/bin/{chunk-yq9vetf8.js → chunk-6zc6a6t3.js} +127 -100
- package/dist/bin/chunk-7aagqqr9.js +1 -0
- package/dist/bin/{chunk-5gx38418.js → chunk-85qrgshq.js} +1 -1
- package/dist/bin/{chunk-tfmx17he.js → chunk-8zk8msx0.js} +1 -1
- package/dist/bin/chunk-9j83q0r4.js +1 -0
- package/dist/bin/{chunk-ewxf62t8.js → chunk-9nhqbes6.js} +2 -2
- package/dist/bin/chunk-a4js49mx.js +1 -0
- package/dist/bin/{chunk-b0xtsv8k.js → chunk-a9e0hvwe.js} +3 -3
- package/dist/bin/{chunk-vrc7eemq.js → chunk-a9tgxf2h.js} +1 -1
- package/dist/bin/chunk-aahrv359.js +1 -0
- package/dist/bin/{chunk-zrgd65r8.js → chunk-bfx23be3.js} +1 -1
- package/dist/bin/{chunk-0x8szp53.js → chunk-bpps61am.js} +1 -1
- package/dist/bin/{chunk-mhrtx0p1.js → chunk-bzth6d1s.js} +1 -1
- package/dist/bin/{chunk-2tsg6e8j.js → chunk-ca3taw2m.js} +1 -1
- package/dist/bin/{chunk-da49my09.js → chunk-cgzp0328.js} +1 -1
- package/dist/bin/{chunk-akwfvn5k.js → chunk-d2aaef9v.js} +1 -1
- package/dist/bin/{chunk-ncrnbcsa.js → chunk-e0z2t4mf.js} +2 -2
- package/dist/bin/{chunk-bj4ft4qc.js → chunk-e2dnxp8d.js} +2 -2
- package/dist/bin/{chunk-fc6r1ack.js → chunk-empfsmdk.js} +1 -1
- package/dist/bin/chunk-er3mww4m.js +1 -0
- package/dist/bin/{chunk-qr0xck72.js → chunk-fmp5bv0j.js} +1 -1
- package/dist/bin/{chunk-vxbnjz78.js → chunk-g3kp5ddx.js} +1 -1
- package/dist/bin/{chunk-qa06sft7.js → chunk-grepda40.js} +1 -1
- package/dist/bin/{chunk-3f27aa5r.js → chunk-h6xqtypj.js} +2 -2
- package/dist/bin/{chunk-9edyzdm0.js → chunk-hwk9ahms.js} +1 -1
- package/dist/bin/{chunk-3g80gjw6.js → chunk-jxd3j00s.js} +2 -2
- package/dist/bin/{chunk-5rhvcgzt.js → chunk-k1xw3zbm.js} +2 -2
- package/dist/bin/{chunk-re15e6p4.js → chunk-m07s5esk.js} +1 -1
- package/dist/bin/{chunk-hv3w2qy1.js → chunk-m9r5jype.js} +2 -2
- package/dist/bin/{chunk-84703zpq.js → chunk-n20kbxwb.js} +2 -2
- package/dist/bin/{chunk-vwqn3yx6.js → chunk-n2fnav53.js} +2 -2
- package/dist/bin/{chunk-nc9pp87y.js → chunk-nv211m42.js} +2 -2
- package/dist/bin/chunk-psgjy3z4.js +1 -0
- package/dist/bin/chunk-qmnr82da.js +1 -0
- package/dist/bin/{chunk-8223r1xn.js → chunk-qqpb82ty.js} +2 -2
- package/dist/bin/{chunk-9xbsmz1f.js → chunk-rqc8btkj.js} +1 -1
- package/dist/bin/chunk-rs85xvt7.js +1 -0
- package/dist/bin/{chunk-dep2n31v.js → chunk-t5ngva49.js} +1 -1
- package/dist/bin/{chunk-48eb4z0c.js → chunk-t7rcfwqc.js} +1 -1
- package/dist/bin/{chunk-ftcjjf76.js → chunk-tjgy10zm.js} +2 -2
- package/dist/bin/chunk-v0beqdna.js +1 -0
- package/dist/bin/chunk-vf2s3tba.js +1 -0
- package/dist/bin/{chunk-kyr5rasx.js → chunk-vzkfjrx2.js} +5 -5
- package/dist/bin/{chunk-2pevjm25.js → chunk-wcem4cqb.js} +2 -2
- package/dist/bin/chunk-wsh5ervz.js +1 -0
- package/dist/bin/chunk-xenhbdmr.js +1 -0
- package/dist/bin/chunk-xrdpxwbf.js +1 -0
- package/dist/bin/{chunk-a8t3c4qe.js → chunk-y68m9bx7.js} +1 -1
- package/dist/bin/cli.js +83 -83
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/{chunk-0a4tqwm9.js → chunk-ea7tn8nn.js} +1 -1
- package/dist/{chunk-fvpkxznh.js → chunk-t8hzekmk.js} +129 -102
- package/dist/deploy/index.js +1 -1
- package/dist/drivers/index.js +1 -1
- package/dist/drivers/shared/compute-deploy.d.ts +0 -12
- package/dist/drivers/shared/rpx-gateway.d.ts +124 -4
- package/dist/drivers/ssh/bootstrap.d.ts +13 -3
- package/dist/drivers/ssh/config.d.ts +11 -3
- package/dist/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 +2 -2
- package/dist/ui/account/automation.html +5 -5
- package/dist/ui/account/security.html +2 -2
- package/dist/ui/applications/compose.html +5 -5
- package/dist/ui/applications/new.html +2 -2
- package/dist/ui/data/backups.html +6 -6
- 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 +6 -6
- package/dist/ui/integrations.html +2 -2
- package/dist/ui/operations/alerts.html +6 -6
- package/dist/ui/operations/configuration.html +6 -6
- package/dist/ui/operations/jobs.html +6 -6
- package/dist/ui/operations/maintenance.html +5 -5
- package/dist/ui/operations/observability.html +6 -6
- package/dist/ui/operations/previews.html +6 -6
- package/dist/ui/operations/queue.html +6 -6
- package/dist/ui/operations/regions.html +5 -5
- package/dist/ui/operations/releases.html +6 -6
- package/dist/ui/operations/spend.html +6 -6
- package/dist/ui/operations/workloads.html +6 -6
- package/dist/ui/security.html +2 -2
- package/dist/ui/server/actions.html +6 -6
- package/dist/ui/server/activity.html +1 -1
- package/dist/ui/server/capacity.html +6 -6
- package/dist/ui/server/database.html +6 -6
- package/dist/ui/server/deployments.html +5 -5
- package/dist/ui/server/diagnostics.html +2 -2
- package/dist/ui/server/firewall.html +5 -5
- package/dist/ui/server/fleet.html +6 -6
- package/dist/ui/server/logs.html +6 -6
- package/dist/ui/server/metrics.html +5 -5
- package/dist/ui/server/security.html +2 -2
- package/dist/ui/server/services.html +1 -1
- package/dist/ui/server/sites.html +6 -6
- package/dist/ui/server/ssh-keys.html +6 -6
- package/dist/ui/server/team.html +6 -6
- package/dist/ui/server/terminal.html +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 +2 -2
- 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 +6 -6
- package/package.json +3 -3
- package/dist/bin/chunk-1hggd7yz.js +0 -1
- package/dist/bin/chunk-40j9hgzc.js +0 -1
- package/dist/bin/chunk-4gqfdr7t.js +0 -1
- package/dist/bin/chunk-5jv4cpky.js +0 -1
- package/dist/bin/chunk-5kxm5mx7.js +0 -1
- package/dist/bin/chunk-aghy01we.js +0 -1
- package/dist/bin/chunk-asvz121j.js +0 -1
- package/dist/bin/chunk-bcpdj01b.js +0 -1
- package/dist/bin/chunk-g76sry03.js +0 -1
- package/dist/bin/chunk-j02d6qmn.js +0 -1
- package/dist/bin/chunk-kmz8vb77.js +0 -1
- package/dist/bin/chunk-py1hyeb2.js +0 -1
- package/dist/bin/chunk-r85ahkwq.js +0 -1
- package/dist/bin/chunk-t6y3pkm8.js +0 -1
- package/dist/bin/chunk-vfcchrby.js +0 -1
- package/dist/bin/chunk-vmdh41kp.js +0 -1
- package/dist/bin/chunk-w8s8vgdj.js +0 -1
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`),o=Math.max(1,n-12),a=Math.min(i.length,n+2),c=i.slice(o-1,a).map((l,u)=>{let
|
|
3
|
-
`)}function be(e){let t=e,r=typeof t?.status==="number"?` (exit ${t.status})`:"",s=t?.signal?` (signal ${t.signal})`:"",n=[
|
|
1
|
+
import{hf as en}from"./chunk-wcem4cqb.js";import{mf as Ls}from"./chunk-5x4rdx8k.js";import{tf as Hs}from"./chunk-85qrgshq.js";import{Df as is,Ef as os,Ff as Ei}from"./chunk-e0z2t4mf.js";import{Gf as Ee,Hf as cs,If as xs,Jf as K,Pf as pe,Qf as ht,Rf as Oe,Sf as ft,Tf as ws,Uf as At,Yf as bt,Zf as Me,_f as Ri,ag as wt,cg as hi,dg as ct,fg as lt,gg as Qn,hg as ti,ig as ut,jg as Ur,kg as zr,lg as Fr,mg as Br,ng as Kt,og as Ve,qg as Xe,rg as ns,sg as Wt}from"./chunk-tjgy10zm.js";import{tg as ds}from"./chunk-rqc8btkj.js";import{vg as Zs}from"./chunk-h6xqtypj.js";import{Cg as Qs}from"./chunk-e2dnxp8d.js";import{ph as Ss}from"./chunk-bzth6d1s.js";import{Aj as ss,Dj as Ps,Lh as ln,Oh as It,Th as fe,Vh as vt,Wh as Gs,Xh as Ci,Yh as Le,gi as E}from"./chunk-n20kbxwb.js";import{Bp as ho}from"./chunk-m07s5esk.js";import{existsSync as nl,readFileSync as il}from"node:fs";import{readFileSync as tn}from"node:fs";import{join as Fo}from"node:path";function Il(e={}){let t=new Set;for(let r of Object.values(e)){if(!r.domain)continue;if(r.redirect||r.deploy==="server"||r.start)t.add(r.domain)}return t}function Qt(e){return e.replace(/\.$/,"").toLowerCase()}function Wi(e,t,r){let s=Qt(e.name),n=Qt(t),i=Qt(r),o=i===n?"@":i.endsWith(`.${n}`)?i.slice(0,-(n.length+1)):i;return s===i||s===o||o==="@"&&(s===""||s===n)}async function Vi(e,t,r,s,n="A"){let i=await e.listRecords(t);if(!i.success)return[`could not list ${n} records: ${i.message||"unknown provider error"}`];let o=i.records.filter((l)=>l.type===n&&Wi(l,t,r)),a=o.findIndex((l)=>l.content===s);if(o.length<=1||a===-1)return[];let c=[];for(let[l,u]of o.entries()){if(l===a)continue;let p=await e.deleteRecord(t,u);if(!p.success)c.push(`could not remove stale ${u.name} ${n} ${u.content}: ${p.message||"unknown provider error"}`)}return c}function ce(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 Xi=new Set(["mail","smtp","imap","mx"]);function qi(e){return!Xi.has(e.split(".")[0]??"")}async function Ol(e){let{provider:t,zone:r,fqdn:s,ipv4:n,ipv6:i,ttl:o=600}=e,a={published:[],warnings:[]},c=[{type:"A",content:n}];if(i&&qi(s))c.push({type:"AAAA",content:i});for(let{type:l,content:u}of c){let p=await t.upsertRecord(r,{name:s,type:l,content:u,ttl:o});if(p?.success===!1){a.warnings.push(`${s} → ${u} failed: ${p.error||p.message||"unknown error"}`);continue}if(a.warnings.push(...(await Vi(t,r,s,u,l)).map((d)=>`${s} cleanup: ${d}`)),await Yi(t,r,s,u,l))a.published.push({fqdn:s,type:l,content:u});else a.warnings.push(`${s} → ${u} reported success at ${t.name} but no matching ${l} record exists — create it manually: ${l} ${s} → ${u}`)}return a}async function Yi(e,t,r,s,n){try{if(typeof e?.listRecords!=="function")return!0;let i=await e.listRecords(t);if(!i?.success||!Array.isArray(i.records))return!0;return i.records.some((o)=>{let a=typeof o?.name==="string"?o.name.replace(/\.$/,""):"";return o?.type===n&&a===r&&o?.content===s})}catch{return!0}}function Zt(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 Je(e,t){let r=Zt(e?.stderr),s=/line (\d+): syntax error/.exec(r);if(!s)return"";let n=Number(s[1]),i=t.split(`
|
|
2
|
+
`),o=Math.max(1,n-12),a=Math.min(i.length,n+2),c=i.slice(o-1,a).map((l,u)=>{let p=o+u,d=/^[A-Z_][A-Z0-9_]*=/.test(l)?l.replace(/=.*/,"=<redacted>"):l;return` ${String(p).padStart(4)}${p===n?" >":" "} ${d}`});return["",`The deploy script bash rejected is ${i.length} lines; it stopped at ${n}.`,...c].join(`
|
|
3
|
+
`)}function be(e){let t=e,r=typeof t?.status==="number"?` (exit ${t.status})`:"",s=t?.signal?` (signal ${t.signal})`:"",n=[Zt(t?.stderr),Zt(t?.stdout)].filter(Boolean).join(`
|
|
4
4
|
`);return`Remote SSH command failed${r}${s}${n?`
|
|
5
|
-
${n}`:""}`}function
|
|
6
|
-
`)){let r=t.trim();if(!r.startsWith("[ts-cloud]"))continue;console.warn(r)}}var
|
|
7
|
-
${e.slice(-
|
|
8
|
-
${
|
|
9
|
-
`)}class mt{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new hs}async putParameter(e){let t={Name:e.Name,Value:e.Value};if(e.Type)t.Type=e.Type;if(e.Description)t.Description=e.Description;if(e.KeyId)t.KeyId=e.KeyId;if(e.Overwrite!==void 0)t.Overwrite=e.Overwrite;if(e.AllowedPattern)t.AllowedPattern=e.AllowedPattern;if(e.Tags&&e.Tags.length>0)t.Tags=e.Tags;if(e.Tier)t.Tier=e.Tier;if(e.DataType)t.DataType=e.DataType;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.PutParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Version:r.Version,Tier:r.Tier}}async getParameter(e){let t={Name:e.Name};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameter:r.Parameter?this.parseParameter(r.Parameter):void 0}}async getParameters(e){let t={Names:e.Names};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:r.Parameters?.map((s)=>this.parseParameter(s)),InvalidParameters:r.InvalidParameters}}async getParametersByPath(e){let t={Path:e.Path};if(e.Recursive!==void 0)t.Recursive=e.Recursive;if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;if(e.MaxResults)t.MaxResults=e.MaxResults;if(e.NextToken)t.NextToken=e.NextToken;if(e.ParameterFilters&&e.ParameterFilters.length>0)t.ParameterFilters=e.ParameterFilters;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParametersByPath","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:r.Parameters?.map((s)=>this.parseParameter(s)),NextToken:r.NextToken}}async deleteParameter(e){let t={Name:e.Name};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DeleteParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async deleteParameters(e){let t={Names:e},r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DeleteParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{DeletedParameters:r.DeletedParameters,InvalidParameters:r.InvalidParameters}}async describeParameters(e){let t={};if(e?.Filters&&e.Filters.length>0)t.Filters=e.Filters;if(e?.ParameterFilters&&e.ParameterFilters.length>0)t.ParameterFilters=e.ParameterFilters;if(e?.MaxResults)t.MaxResults=e.MaxResults;if(e?.NextToken)t.NextToken=e.NextToken;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DescribeParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:r.Parameters?.map((s)=>this.parseParameter(s)),NextToken:r.NextToken}}async getParameterHistory(e){let t={Name:e.Name};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;if(e.MaxResults)t.MaxResults=e.MaxResults;if(e.NextToken)t.NextToken=e.NextToken;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameterHistory","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:r.Parameters?.map((s)=>({Name:s.Name,Type:s.Type,KeyId:s.KeyId,LastModifiedDate:s.LastModifiedDate,LastModifiedUser:s.LastModifiedUser,Description:s.Description,Value:s.Value,Version:s.Version,Labels:s.Labels,Tier:s.Tier})),NextToken:r.NextToken}}async labelParameterVersion(e){let t={Name:e.Name,Labels:e.Labels};if(e.ParameterVersion!==void 0)t.ParameterVersion=e.ParameterVersion;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.LabelParameterVersion","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{InvalidLabels:r.InvalidLabels,ParameterVersion:r.ParameterVersion}}async addTagsToResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId,Tags:e.Tags};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.AddTagsToResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async removeTagsFromResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId,TagKeys:e.TagKeys};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.RemoveTagsFromResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async listTagsForResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId};return{TagList:(await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.ListTagsForResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})).TagList}}async setString(e,t,r){return this.putParameter({Name:e,Value:t,Type:"String",Description:r?.description,Overwrite:r?.overwrite??!0,Tags:r?.tags})}async setSecureString(e,t,r){return this.putParameter({Name:e,Value:t,Type:"SecureString",Description:r?.description,Overwrite:r?.overwrite??!0,KeyId:r?.kmsKeyId,Tags:r?.tags})}async getValue(e){return(await this.getParameter({Name:e,WithDecryption:!0})).Parameter?.Value}async getAllByPath(e,t=!0){let r=[],s;do{let n=await this.getParametersByPath({Path:e,Recursive:t,WithDecryption:!0,NextToken:s});if(n.Parameters)r.push(...n.Parameters);s=n.NextToken}while(s);return r}parseParameter(e){return{Name:e.Name,Type:e.Type,Value:e.Value,Version:e.Version,LastModifiedDate:e.LastModifiedDate,ARN:e.ARN,DataType:e.DataType,Description:e.Description,AllowedPattern:e.AllowedPattern,KeyId:e.KeyId,Tier:e.Tier}}async sendCommand(e){if(!e.InstanceIds&&!e.Targets)throw Error("SendCommand requires either InstanceIds or Targets");let t={DocumentName:e.DocumentName};if(e.InstanceIds)t.InstanceIds=e.InstanceIds;if(e.Targets)t.Targets=e.Targets;if(e.Parameters)t.Parameters=e.Parameters;if(e.TimeoutSeconds)t.TimeoutSeconds=e.TimeoutSeconds;if(e.Comment)t.Comment=e.Comment;if(e.OutputS3BucketName)t.OutputS3BucketName=e.OutputS3BucketName;if(e.OutputS3KeyPrefix)t.OutputS3KeyPrefix=e.OutputS3KeyPrefix;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.SendCommand","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{CommandId:r.Command?.CommandId,Status:r.Command?.Status,StatusDetails:r.Command?.StatusDetails}}async getCommandInvocation(e){let t={CommandId:e.CommandId,InstanceId:e.InstanceId},r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetCommandInvocation","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Status:r.Status,StatusDetails:r.StatusDetails,StandardOutputContent:r.StandardOutputContent,StandardErrorContent:r.StandardErrorContent,ResponseCode:r.ResponseCode}}async runShellCommand(e,t,r){let s=await this.sendCommand({InstanceIds:[e],DocumentName:"AWS-RunShellScript",Parameters:{commands:t},TimeoutSeconds:r?.timeoutSeconds||600});if(!s.CommandId)return{success:!1,error:"Failed to send command"};if(r?.waitForCompletion===!1)return{success:!0,status:"Pending"};let n=r?.pollIntervalMs||2000,i=r?.maxWaitMs||300000,o=Date.now();while(Date.now()-o<i){await new Promise((a)=>setTimeout(a,n));try{let a=await this.getCommandInvocation({CommandId:s.CommandId,InstanceId:e});if(a.Status==="Success")return{success:!0,output:a.StandardOutputContent,error:a.StandardErrorContent,status:a.Status};if(a.Status==="Failed"||a.Status==="Cancelled"||a.Status==="TimedOut")return{success:!1,output:a.StandardOutputContent,error:a.StandardErrorContent||a.StatusDetails,status:a.Status}}catch(a){if(!a.message?.includes("InvocationDoesNotExist"))return{success:!1,error:a.message}}}return{success:!1,error:"Command timed out waiting for completion"}}async listCommandInvocations(e){let t={CommandId:e.CommandId};if(e.Details)t.Details=!0;return((await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.ListCommandInvocations","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})).CommandInvocations||[]).map((n)=>({InstanceId:n.InstanceId,Status:n.Status,StatusDetails:n.StatusDetails,StandardOutputContent:n.CommandPlugins?.[0]?.Output,StandardErrorContent:n.CommandPlugins?.[0]?.StandardErrorUrl}))}async sendCommandByTags(e){let t=Object.entries(e.tags).map(([c,l])=>({Key:`tag:${c}`,Values:[l]})),r=await this.sendCommand({Targets:t,DocumentName:"AWS-RunShellScript",Parameters:{commands:e.commands},TimeoutSeconds:e.timeoutSeconds||600,Comment:e.comment});if(!r.CommandId)return{success:!1,instanceCount:0,perInstance:[],error:"Failed to send command"};let s=e.pollIntervalMs||3000,n=e.maxWaitMs||600000,i=Date.now(),o=new Set(["Success","Failed","Cancelled","TimedOut"]),a=[];while(Date.now()-i<n){await new Promise((c)=>setTimeout(c,s));try{if(a=await this.listCommandInvocations({CommandId:r.CommandId,Details:!0}),a.length===0)continue;if(a.every((l)=>o.has(l.Status||""))){let l=a.map((d)=>({instanceId:d.InstanceId,status:d.Status||"Unknown",output:d.StandardOutputContent,error:d.StandardErrorContent||d.StatusDetails})),u=a.every((d)=>d.Status==="Success");return{success:u,instanceCount:a.length,perInstance:l,error:u?void 0:"One or more instances reported a non-success status"}}}catch(c){if(!c.message?.includes("InvocationDoesNotExist"))return{success:!1,instanceCount:0,perInstance:[],error:c.message}}}return{success:!1,instanceCount:a.length,perInstance:a.map((c)=>({instanceId:c.InstanceId,status:c.Status||"Unknown"})),error:"Command timed out waiting for all instances to complete"}}}function Gi(e){return`/etc/ts-cloud/${e}-upgrade.env`}function Wi(e){return`${e}-upgrade`}function ys(e){if(!e||e.length===0)return[];let t=["mkdir -p /etc/ts-cloud"],r=[];for(let s of e){if(s.enabled===!1)continue;if(!s.service||!s.binary)continue;let{service:n,binary:i,command:o="upgrade",channel:a="stable",schedule:c="daily",randomizedDelay:l="4h",args:u=[]}=s,d=Wi(n),p=Gi(n),m=[`--path ${i}`,`--service ${n}`,...a==="canary"?["--canary"]:[],...u].join(" ");t.push(`if [ ! -f ${p} ]; then`,` cat > ${p} <<'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 ${p}`,`cat > /etc/systemd/system/${d}.service <<'TS_CLOUD_APPUPD_SVC_EOF'`,"[Unit]",`Description=Check for and install ${n} updates`,"After=network-online.target","Wants=network-online.target","","[Service]","Type=oneshot",`EnvironmentFile=-${p}`,`ExecStart=/bin/sh -c 'if [ "\${ENABLED:-true}" != "true" ]; then echo "auto-update disabled via ${p}"; exit 0; fi; exec ${i} ${o} ${m} $ARGS'`,"TS_CLOUD_APPUPD_SVC_EOF",`cat > /etc/systemd/system/${d}.timer <<'TS_CLOUD_APPUPD_TMR_EOF'`,"[Unit]",`Description=Scheduled ${n} update check`,"","[Timer]",`OnCalendar=${c}`,`RandomizedDelaySec=${l}`,"Persistent=true","","[Install]","WantedBy=timers.target","TS_CLOUD_APPUPD_TMR_EOF"),r.push(`systemctl enable --now ${d}.timer`)}if(r.length===0)return[];return[...t,"systemctl daemon-reload",...r]}function le(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 Ss=[["nginx",80],["https",443],["phpFpm",9074],["mysql",3306],["postgres",5432],["redis",6379],["meilisearch",7700],["typesense",8108],["smtp",25]];function Vi(e=!0){let t=typeof e==="object"?e:{},r=typeof e==="boolean"?e:e.enabled!==!1,s=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(s)&&s>0?s:0,bandwidthPercent:t.alerts?.bandwidthPercent??80}}function ue(e=!0){let{enabled:t,cpuLoadPerCore:r,memPercent:s,diskPercent:n,bandwidthTb:i,bandwidthPercent:o}=Vi(e);if(!t)return[];let a=Math.round(i*1000000000000),c=Ss.map(([u,d])=>`SVC_${u.toUpperCase()}=$(probe ${d})`),l=Ss.map(([u])=>`"${u}":"$SVC_${u.toUpperCase()}"`).join(",");return["if ! command -v sadf >/dev/null 2>&1; then export DEBIAN_FRONTEND=noninteractive; apt-get update -qq; apt-get install -y -qq sysstat; fi","systemctl enable --now sysstat.service 2>/dev/null || true","mkdir -p /var/lib/ts-cloud","cat > /usr/local/bin/ts-cloud-metrics.sh <<'TS_CLOUD_METRICS_EOF'","#!/bin/bash","set -uo pipefail","LOAD=$(cut -d' ' -f1 /proc/loadavg)","CPUS=$(nproc)",`read MEM_TOTAL MEM_USED SWAP_TOTAL SWAP_USED <<EOF
|
|
5
|
+
${n}`:""}`}function Ie(e){for(let t of e.split(`
|
|
6
|
+
`)){let r=t.trim();if(!r.startsWith("[ts-cloud]"))continue;console.warn(r)}}var ys=4000,Ji=3;function Qi(e){return e.length>ys?`…
|
|
7
|
+
${e.slice(-ys)}`:e}function we(e,t){let r=e.filter((o)=>o.status!=="Success");if(r.length===0)return t;let s=r.slice(0,Ji).map((o)=>{let a=(o.error||o.output||"").trim(),c=`${o.instanceId}: ${o.status}`;return a?`${c}
|
|
8
|
+
${Qi(a)}`:c}),n=r.length-s.length,i=n>0?[`(+${n} more instance${n===1?"":"s"} failed)`]:[];return[t,...s,...i].join(`
|
|
9
|
+
`)}class mt{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new Ss}async putParameter(e){let t={Name:e.Name,Value:e.Value};if(e.Type)t.Type=e.Type;if(e.Description)t.Description=e.Description;if(e.KeyId)t.KeyId=e.KeyId;if(e.Overwrite!==void 0)t.Overwrite=e.Overwrite;if(e.AllowedPattern)t.AllowedPattern=e.AllowedPattern;if(e.Tags&&e.Tags.length>0)t.Tags=e.Tags;if(e.Tier)t.Tier=e.Tier;if(e.DataType)t.DataType=e.DataType;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.PutParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Version:r.Version,Tier:r.Tier}}async getParameter(e){let t={Name:e.Name};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameter:r.Parameter?this.parseParameter(r.Parameter):void 0}}async getParameters(e){let t={Names:e.Names};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:r.Parameters?.map((s)=>this.parseParameter(s)),InvalidParameters:r.InvalidParameters}}async getParametersByPath(e){let t={Path:e.Path};if(e.Recursive!==void 0)t.Recursive=e.Recursive;if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;if(e.MaxResults)t.MaxResults=e.MaxResults;if(e.NextToken)t.NextToken=e.NextToken;if(e.ParameterFilters&&e.ParameterFilters.length>0)t.ParameterFilters=e.ParameterFilters;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParametersByPath","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:r.Parameters?.map((s)=>this.parseParameter(s)),NextToken:r.NextToken}}async deleteParameter(e){let t={Name:e.Name};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DeleteParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async deleteParameters(e){let t={Names:e},r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DeleteParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{DeletedParameters:r.DeletedParameters,InvalidParameters:r.InvalidParameters}}async describeParameters(e){let t={};if(e?.Filters&&e.Filters.length>0)t.Filters=e.Filters;if(e?.ParameterFilters&&e.ParameterFilters.length>0)t.ParameterFilters=e.ParameterFilters;if(e?.MaxResults)t.MaxResults=e.MaxResults;if(e?.NextToken)t.NextToken=e.NextToken;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DescribeParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:r.Parameters?.map((s)=>this.parseParameter(s)),NextToken:r.NextToken}}async getParameterHistory(e){let t={Name:e.Name};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;if(e.MaxResults)t.MaxResults=e.MaxResults;if(e.NextToken)t.NextToken=e.NextToken;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameterHistory","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:r.Parameters?.map((s)=>({Name:s.Name,Type:s.Type,KeyId:s.KeyId,LastModifiedDate:s.LastModifiedDate,LastModifiedUser:s.LastModifiedUser,Description:s.Description,Value:s.Value,Version:s.Version,Labels:s.Labels,Tier:s.Tier})),NextToken:r.NextToken}}async labelParameterVersion(e){let t={Name:e.Name,Labels:e.Labels};if(e.ParameterVersion!==void 0)t.ParameterVersion=e.ParameterVersion;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.LabelParameterVersion","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{InvalidLabels:r.InvalidLabels,ParameterVersion:r.ParameterVersion}}async addTagsToResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId,Tags:e.Tags};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.AddTagsToResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async removeTagsFromResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId,TagKeys:e.TagKeys};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.RemoveTagsFromResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async listTagsForResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId};return{TagList:(await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.ListTagsForResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})).TagList}}async setString(e,t,r){return this.putParameter({Name:e,Value:t,Type:"String",Description:r?.description,Overwrite:r?.overwrite??!0,Tags:r?.tags})}async setSecureString(e,t,r){return this.putParameter({Name:e,Value:t,Type:"SecureString",Description:r?.description,Overwrite:r?.overwrite??!0,KeyId:r?.kmsKeyId,Tags:r?.tags})}async getValue(e){return(await this.getParameter({Name:e,WithDecryption:!0})).Parameter?.Value}async getAllByPath(e,t=!0){let r=[],s;do{let n=await this.getParametersByPath({Path:e,Recursive:t,WithDecryption:!0,NextToken:s});if(n.Parameters)r.push(...n.Parameters);s=n.NextToken}while(s);return r}parseParameter(e){return{Name:e.Name,Type:e.Type,Value:e.Value,Version:e.Version,LastModifiedDate:e.LastModifiedDate,ARN:e.ARN,DataType:e.DataType,Description:e.Description,AllowedPattern:e.AllowedPattern,KeyId:e.KeyId,Tier:e.Tier}}async sendCommand(e){if(!e.InstanceIds&&!e.Targets)throw Error("SendCommand requires either InstanceIds or Targets");let t={DocumentName:e.DocumentName};if(e.InstanceIds)t.InstanceIds=e.InstanceIds;if(e.Targets)t.Targets=e.Targets;if(e.Parameters)t.Parameters=e.Parameters;if(e.TimeoutSeconds)t.TimeoutSeconds=e.TimeoutSeconds;if(e.Comment)t.Comment=e.Comment;if(e.OutputS3BucketName)t.OutputS3BucketName=e.OutputS3BucketName;if(e.OutputS3KeyPrefix)t.OutputS3KeyPrefix=e.OutputS3KeyPrefix;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.SendCommand","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{CommandId:r.Command?.CommandId,Status:r.Command?.Status,StatusDetails:r.Command?.StatusDetails}}async getCommandInvocation(e){let t={CommandId:e.CommandId,InstanceId:e.InstanceId},r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetCommandInvocation","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Status:r.Status,StatusDetails:r.StatusDetails,StandardOutputContent:r.StandardOutputContent,StandardErrorContent:r.StandardErrorContent,ResponseCode:r.ResponseCode}}async runShellCommand(e,t,r){let s=await this.sendCommand({InstanceIds:[e],DocumentName:"AWS-RunShellScript",Parameters:{commands:t},TimeoutSeconds:r?.timeoutSeconds||600});if(!s.CommandId)return{success:!1,error:"Failed to send command"};if(r?.waitForCompletion===!1)return{success:!0,status:"Pending"};let n=r?.pollIntervalMs||2000,i=r?.maxWaitMs||300000,o=Date.now();while(Date.now()-o<i){await new Promise((a)=>setTimeout(a,n));try{let a=await this.getCommandInvocation({CommandId:s.CommandId,InstanceId:e});if(a.Status==="Success")return{success:!0,output:a.StandardOutputContent,error:a.StandardErrorContent,status:a.Status};if(a.Status==="Failed"||a.Status==="Cancelled"||a.Status==="TimedOut")return{success:!1,output:a.StandardOutputContent,error:a.StandardErrorContent||a.StatusDetails,status:a.Status}}catch(a){if(!a.message?.includes("InvocationDoesNotExist"))return{success:!1,error:a.message}}}return{success:!1,error:"Command timed out waiting for completion"}}async listCommandInvocations(e){let t={CommandId:e.CommandId};if(e.Details)t.Details=!0;return((await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.ListCommandInvocations","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})).CommandInvocations||[]).map((n)=>({InstanceId:n.InstanceId,Status:n.Status,StatusDetails:n.StatusDetails,StandardOutputContent:n.CommandPlugins?.[0]?.Output,StandardErrorContent:n.CommandPlugins?.[0]?.StandardErrorUrl}))}async sendCommandByTags(e){let t=Object.entries(e.tags).map(([c,l])=>({Key:`tag:${c}`,Values:[l]})),r=await this.sendCommand({Targets:t,DocumentName:"AWS-RunShellScript",Parameters:{commands:e.commands},TimeoutSeconds:e.timeoutSeconds||600,Comment:e.comment});if(!r.CommandId)return{success:!1,instanceCount:0,perInstance:[],error:"Failed to send command"};let s=e.pollIntervalMs||3000,n=e.maxWaitMs||600000,i=Date.now(),o=new Set(["Success","Failed","Cancelled","TimedOut"]),a=[];while(Date.now()-i<n){await new Promise((c)=>setTimeout(c,s));try{if(a=await this.listCommandInvocations({CommandId:r.CommandId,Details:!0}),a.length===0)continue;if(a.every((l)=>o.has(l.Status||""))){let l=a.map((p)=>({instanceId:p.InstanceId,status:p.Status||"Unknown",output:p.StandardOutputContent,error:p.StandardErrorContent||p.StatusDetails})),u=a.every((p)=>p.Status==="Success");return{success:u,instanceCount:a.length,perInstance:l,error:u?void 0:"One or more instances reported a non-success status"}}}catch(c){if(!c.message?.includes("InvocationDoesNotExist"))return{success:!1,instanceCount:0,perInstance:[],error:c.message}}}return{success:!1,instanceCount:a.length,perInstance:a.map((c)=>({instanceId:c.InstanceId,status:c.Status||"Unknown"})),error:"Command timed out waiting for all instances to complete"}}}function Zi(e){return`/etc/ts-cloud/${e}-upgrade.env`}function eo(e){return`${e}-upgrade`}function vs(e){if(!e||e.length===0)return[];let t=["mkdir -p /etc/ts-cloud"],r=[];for(let s of e){if(s.enabled===!1)continue;if(!s.service||!s.binary)continue;let{service:n,binary:i,command:o="upgrade",channel:a="stable",schedule:c="daily",randomizedDelay:l="4h",args:u=[]}=s,p=eo(n),d=Zi(n),m=[`--path ${i}`,`--service ${n}`,...a==="canary"?["--canary"]:[],...u].join(" ");t.push(`if [ ! -f ${d} ]; then`,` cat > ${d} <<'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 ${d}`,`cat > /etc/systemd/system/${p}.service <<'TS_CLOUD_APPUPD_SVC_EOF'`,"[Unit]",`Description=Check for and install ${n} updates`,"After=network-online.target","Wants=network-online.target","","[Service]","Type=oneshot",`EnvironmentFile=-${d}`,`ExecStart=/bin/sh -c 'if [ "\${ENABLED:-true}" != "true" ]; then echo "auto-update disabled via ${d}"; exit 0; fi; exec ${i} ${o} ${m} $ARGS'`,"TS_CLOUD_APPUPD_SVC_EOF",`cat > /etc/systemd/system/${p}.timer <<'TS_CLOUD_APPUPD_TMR_EOF'`,"[Unit]",`Description=Scheduled ${n} update check`,"","[Timer]",`OnCalendar=${c}`,`RandomizedDelaySec=${l}`,"Persistent=true","","[Install]","WantedBy=timers.target","TS_CLOUD_APPUPD_TMR_EOF"),r.push(`systemctl enable --now ${p}.timer`)}if(r.length===0)return[];return[...t,"systemctl daemon-reload",...r]}function le(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 bs=[["nginx",80],["https",443],["phpFpm",9074],["mysql",3306],["postgres",5432],["redis",6379],["meilisearch",7700],["typesense",8108],["smtp",25]];function to(e=!0){let t=typeof e==="object"?e:{},r=typeof e==="boolean"?e:e.enabled!==!1,s=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(s)&&s>0?s:0,bandwidthPercent:t.alerts?.bandwidthPercent??80}}function ue(e=!0){let{enabled:t,cpuLoadPerCore:r,memPercent:s,diskPercent:n,bandwidthTb:i,bandwidthPercent:o}=to(e);if(!t)return[];let a=Math.round(i*1000000000000),c=bs.map(([u,p])=>`SVC_${u.toUpperCase()}=$(probe ${p})`),l=bs.map(([u])=>`"${u}":"$SVC_${u.toUpperCase()}"`).join(",");return["if ! command -v sadf >/dev/null 2>&1; then export DEBIAN_FRONTEND=noninteractive; apt-get update -qq; apt-get install -y -qq sysstat; fi","systemctl enable --now sysstat.service 2>/dev/null || true","mkdir -p /var/lib/ts-cloud","cat > /usr/local/bin/ts-cloud-metrics.sh <<'TS_CLOUD_METRICS_EOF'","#!/bin/bash","set -uo pipefail","LOAD=$(cut -d' ' -f1 /proc/loadavg)","CPUS=$(nproc)",`read MEM_TOTAL MEM_USED SWAP_TOTAL SWAP_USED <<EOF
|
|
10
10
|
$(free -m | awk '/^Mem:/{total=$2; used=$3} /^Swap:/{print total, used, $2, $3}')
|
|
11
|
-
EOF`,`DISK_PCT=$(df -P / | awk 'NR==2{gsub("%","",$5); print $5}')`,"UPTIME_SEC=$(cut -d' ' -f1 /proc/uptime | cut -d. -f1)",`RX_BYTES=$(awk -F'[: ]+' 'NR>2 && $2!="lo"{rx+=$3} END{print rx+0}' /proc/net/dev)`,`TX_BYTES=$(awk -F'[: ]+' 'NR>2 && $2!="lo"{tx+=$11} END{print tx+0}' /proc/net/dev)`,"NOW_EPOCH=$(date -u +%s); TODAY=$(date -u +%Y-%m-%d); MONTH=$(date -u +%Y-%m)","if [ -r /var/lib/ts-cloud/bandwidth-state ]; then . /var/lib/ts-cloud/bandwidth-state; fi","PREV_EPOCH=${PREV_EPOCH:-0}; PREV_RX=${PREV_RX:-0}; PREV_TX=${PREV_TX:-0}","DAY_KEY=${DAY_KEY:-$TODAY}; MONTH_KEY=${MONTH_KEY:-$MONTH}","DAY_RX=${DAY_RX:-0}; DAY_TX=${DAY_TX:-0}; MONTH_RX=${MONTH_RX:-0}; MONTH_TX=${MONTH_TX:-0}","ELAPSED=$(( NOW_EPOCH - PREV_EPOCH ))",'if [ "$PREV_EPOCH" -le 0 ] || [ "$ELAPSED" -le 0 ] || [ "$RX_BYTES" -lt "$PREV_RX" ] || [ "$TX_BYTES" -lt "$PREV_TX" ]; then'," DELTA_RX=0; DELTA_TX=0; ELAPSED=0","else"," DELTA_RX=$(( RX_BYTES - PREV_RX )); DELTA_TX=$(( TX_BYTES - PREV_TX ))","fi",'if [ "$DAY_KEY" != "$TODAY" ]; then DAY_KEY=$TODAY; DAY_RX=0; DAY_TX=0; fi','if [ "$MONTH_KEY" != "$MONTH" ]; then MONTH_KEY=$MONTH; MONTH_RX=0; MONTH_TX=0; fi',"DAY_RX=$(( DAY_RX + DELTA_RX )); DAY_TX=$(( DAY_TX + DELTA_TX ))","MONTH_RX=$(( MONTH_RX + DELTA_RX )); MONTH_TX=$(( MONTH_TX + DELTA_TX ))",'if [ "$ELAPSED" -gt 0 ]; then RX_RATE=$(( DELTA_RX / ELAPSED )); TX_RATE=$(( DELTA_TX / ELAPSED )); else RX_RATE=0; TX_RATE=0; fi',"cat > /var/lib/ts-cloud/bandwidth-state.tmp <<BWSTATE","PREV_EPOCH=$NOW_EPOCH","PREV_RX=$RX_BYTES","PREV_TX=$TX_BYTES","RX_RATE=$RX_RATE","TX_RATE=$TX_RATE","DAY_KEY=$DAY_KEY","DAY_RX=$DAY_RX","DAY_TX=$DAY_TX","MONTH_KEY=$MONTH_KEY","MONTH_RX=$MONTH_RX","MONTH_TX=$MONTH_TX","BWSTATE","mv -f /var/lib/ts-cloud/bandwidth-state.tmp /var/lib/ts-cloud/bandwidth-state","probe(){ (exec 3<>/dev/tcp/127.0.0.1/$1) 2>/dev/null && echo up || echo down; }",...c,"LOAD=${LOAD:-0}; CPUS=${CPUS:-1}; MEM_TOTAL=${MEM_TOTAL:-0}; MEM_USED=${MEM_USED:-0}","SWAP_TOTAL=${SWAP_TOTAL:-0}; SWAP_USED=${SWAP_USED:-0}; DISK_PCT=${DISK_PCT:-0}","UPTIME_SEC=${UPTIME_SEC:-0}; RX_BYTES=${RX_BYTES:-0}; TX_BYTES=${TX_BYTES:-0}","MEM_PCT=$(( MEM_TOTAL > 0 ? MEM_USED * 100 / MEM_TOTAL : 0 ))","cat > /var/lib/ts-cloud/metrics.json.tmp <<JSON",`{"load":$LOAD,"cpus":$CPUS,"memTotalMb":$MEM_TOTAL,"memUsedMb":$MEM_USED,"memUsedPct":$MEM_PCT,"swapTotalMb":$SWAP_TOTAL,"swapUsedMb":$SWAP_USED,"diskUsedPct":$DISK_PCT,"uptimeSec":$UPTIME_SEC,"network":{"rxBytes":$RX_BYTES,"txBytes":$TX_BYTES,"rxBytesPerSec":$RX_RATE,"txBytesPerSec":$TX_RATE,"dayKey":"$DAY_KEY","rxBytesToday":$DAY_RX,"txBytesToday":$DAY_TX,"monthKey":"$MONTH_KEY","rxBytesMonth":$MONTH_RX,"txBytesMonth":$MONTH_TX,"budgetBytes":${a}},"services":{`+l+"}}","JSON","mv -f /var/lib/ts-cloud/metrics.json.tmp /var/lib/ts-cloud/metrics.json",'ALERTS=""',`if awk -v l="$LOAD" -v c="$CPUS" -v t=${r} 'BEGIN{exit !(c>0 && l/c > t)}'; then ALERTS="$ALERTS load=$LOAD/${r}xCPU"; fi`,`if [ "\${MEM_PCT:-0}" -ge ${s} ]; then ALERTS="$ALERTS mem=\${MEM_PCT}%"; fi`,`if [ "\${DISK_PCT:-0}" -ge ${n} ]; then ALERTS="$ALERTS disk=\${DISK_PCT}%"; fi`,"PREV=$(cat /var/lib/ts-cloud/alert-state 2>/dev/null || echo ok)",'if [ -n "$ALERTS" ]; then',' if [ "$PREV" != alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "⚠️ $(hostname): resource alert —$ALERTS" || true; fi'," echo alert > /var/lib/ts-cloud/alert-state","else",' if [ "$PREV" = alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "✅ $(hostname): resource usage back to normal" || true; fi'," echo ok > /var/lib/ts-cloud/alert-state","fi",...a>0?["BW_TOTAL=$(( MONTH_RX + MONTH_TX ))",`BW_PCT=$(( BW_TOTAL * 100 / ${a} ))`,"BW_PREV=$(cat /var/lib/ts-cloud/bandwidth-alert-state 2>/dev/null || echo ok)",`if [ "$BW_PCT" -ge ${o} ]; then`,` if [ "$BW_PREV" != alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "⚠️ $(hostname): bandwidth at \${BW_PCT}% of the ${i} TB monthly allowance ($MONTH_KEY)" || true; fi`," echo alert > /var/lib/ts-cloud/bandwidth-alert-state","else",' if [ "$BW_PREV" = alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "✅ $(hostname): bandwidth back under the monthly allowance (${BW_PCT}%)" || true; fi'," echo ok > /var/lib/ts-cloud/bandwidth-alert-state","fi"]:[],"TS_CLOUD_METRICS_EOF","chmod +x /usr/local/bin/ts-cloud-metrics.sh","cat > /etc/systemd/system/ts-cloud-metrics.service <<'TS_CLOUD_METRICS_SVC_EOF'","[Unit]","Description=ts-cloud metrics collector","","[Service]","Type=oneshot","ExecStart=/usr/local/bin/ts-cloud-metrics.sh","TS_CLOUD_METRICS_SVC_EOF","cat > /etc/systemd/system/ts-cloud-metrics.timer <<'TS_CLOUD_METRICS_TMR_EOF'","[Unit]","Description=Run ts-cloud metrics collector every minute","","[Timer]","OnCalendar=*-*-* *:*:00","AccuracySec=1s","RandomizedDelaySec=5s","Persistent=true","","[Install]","WantedBy=timers.target","TS_CLOUD_METRICS_TMR_EOF","systemctl daemon-reload","systemctl enable --now ts-cloud-metrics.timer","systemctl start ts-cloud-metrics.service"]}var qi={"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"},Xi="127.0.0.1:9074";function bs(e){return Xi}function Yi(e={}){let t=e.versions?.length?e.versions:["8.3"];return e.default&&t.includes(e.default)?e.default:t[0]}function Ji(e={}){return{...e.optimizeForProduction===!1?{}:{...qi},...e.ini||{}}}function Qi(e={}){let t=Ji(e),r=Object.keys(t);if(r.length===0)return[];let s=r.map((i)=>`${i}=${t[i]}`),n="ts-cloud-managed";return[Ie(),"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'`,`; ${n} — production PHP tuning`,...s,"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 '/; ${n} BEGIN/,/; ${n} END/d' "$TS_CLOUD_LOADED_INI"`,` cat >> "$TS_CLOUD_LOADED_INI" <<'TS_CLOUD_PHPINI_EOF'`,`; ${n} BEGIN`,...s,`; ${n} END`,"TS_CLOUD_PHPINI_EOF","fi",`(cd ${pe} && pantry restart php-fpm) 2>/dev/null || true`]}function ft(e={}){let t=Yi(e),r=e.installNginx!==!1,s=e.installComposer!==!1,n=[`php.net@${t}`];if(s)n.push("getcomposer.org");if(r)n.push("nginx.org");return[...gt(n),...vs(["php-fpm"]),...Qi(e)]}function Zt(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 Zi(e){if(!e)return"";let t=typeof e==="object"?e:{},s=[`max-age=${t.maxAge??31536000}`];if(t.includeSubDomains??!0)s.push("includeSubDomains");if(t.preload)s.push("preload");return` add_header Strict-Transport-Security "${s.join("; ")}" always;`}function eo(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 ws(e){return`/etc/nginx/.htpasswd-${e}`}var to=new Set(["laravel","php","statamic","wordpress"]);function ro(e){return to.has(e)}function so(e){return e==="laravel"||e==="statamic"?"public":""}function no(e,t){let r=e.replace(/\/+$/,""),s=t.replace(/^\/+|\/+$/g,"");return s?`${r}/${s}`:r}function io(e){let t=e.type??"laravel",r=e.webDirectory??so(t),s=no(e.appDir,r),n=ro(t),i=e.phpVersion??"8.3",o=[` root ${s};`,"",' add_header X-Frame-Options "SAMEORIGIN";',' add_header X-Content-Type-Options "nosniff";'],a=Zi(e.hsts);if(a)o.push(a);for(let c of eo(e.security))o.push(c);if(o.push("",` index ${n?"index.php index.html":"index.html index.htm"};`,""," charset utf-8;",""),e.clientMaxBodySize)o.push(` client_max_body_size ${e.clientMaxBodySize};`,"");if(e.auth)o.push(` auth_basic "${e.auth.realm||"Restricted"}";`,` auth_basic_user_file ${ws(e.siteName)};`,"");for(let[c,l]of Object.entries(e.redirects||{}))o.push(` location = ${c} { return 301 ${l}; }`);if(Object.keys(e.redirects||{}).length>0)o.push("");if(n){if(o.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??bs(i)};`," fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;"," include fastcgi_params;"," }",""," location ~ /\\.(?!well-known).* {"," deny all;"," }"),t==="wordpress")o.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")o.push(" location / {"," try_files $uri $uri/ /index.html;"," }");else o.push(" location / {"," try_files $uri $uri/ =404;"," }");if(e.serverSnippet&&e.serverSnippet.length>0){o.push("");for(let c of e.serverSnippet)o.push(c?` ${c}`:"")}return o}function oo(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(" "),s=io(e);if(e.ssl){let i=["server {"," listen 80;"," listen [::]:80;",` server_name ${r};`," return 301 https://$host$request_uri;","}"],o=["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(" ")};`]:[],"",...s,"}"];return`${[...i,"",...o].join(`
|
|
11
|
+
EOF`,`DISK_PCT=$(df -P / | awk 'NR==2{gsub("%","",$5); print $5}')`,"UPTIME_SEC=$(cut -d' ' -f1 /proc/uptime | cut -d. -f1)",`RX_BYTES=$(awk -F'[: ]+' 'NR>2 && $2!="lo"{rx+=$3} END{print rx+0}' /proc/net/dev)`,`TX_BYTES=$(awk -F'[: ]+' 'NR>2 && $2!="lo"{tx+=$11} END{print tx+0}' /proc/net/dev)`,"NOW_EPOCH=$(date -u +%s); TODAY=$(date -u +%Y-%m-%d); MONTH=$(date -u +%Y-%m)","if [ -r /var/lib/ts-cloud/bandwidth-state ]; then . /var/lib/ts-cloud/bandwidth-state; fi","PREV_EPOCH=${PREV_EPOCH:-0}; PREV_RX=${PREV_RX:-0}; PREV_TX=${PREV_TX:-0}","DAY_KEY=${DAY_KEY:-$TODAY}; MONTH_KEY=${MONTH_KEY:-$MONTH}","DAY_RX=${DAY_RX:-0}; DAY_TX=${DAY_TX:-0}; MONTH_RX=${MONTH_RX:-0}; MONTH_TX=${MONTH_TX:-0}","ELAPSED=$(( NOW_EPOCH - PREV_EPOCH ))",'if [ "$PREV_EPOCH" -le 0 ] || [ "$ELAPSED" -le 0 ] || [ "$RX_BYTES" -lt "$PREV_RX" ] || [ "$TX_BYTES" -lt "$PREV_TX" ]; then'," DELTA_RX=0; DELTA_TX=0; ELAPSED=0","else"," DELTA_RX=$(( RX_BYTES - PREV_RX )); DELTA_TX=$(( TX_BYTES - PREV_TX ))","fi",'if [ "$DAY_KEY" != "$TODAY" ]; then DAY_KEY=$TODAY; DAY_RX=0; DAY_TX=0; fi','if [ "$MONTH_KEY" != "$MONTH" ]; then MONTH_KEY=$MONTH; MONTH_RX=0; MONTH_TX=0; fi',"DAY_RX=$(( DAY_RX + DELTA_RX )); DAY_TX=$(( DAY_TX + DELTA_TX ))","MONTH_RX=$(( MONTH_RX + DELTA_RX )); MONTH_TX=$(( MONTH_TX + DELTA_TX ))",'if [ "$ELAPSED" -gt 0 ]; then RX_RATE=$(( DELTA_RX / ELAPSED )); TX_RATE=$(( DELTA_TX / ELAPSED )); else RX_RATE=0; TX_RATE=0; fi',"cat > /var/lib/ts-cloud/bandwidth-state.tmp <<BWSTATE","PREV_EPOCH=$NOW_EPOCH","PREV_RX=$RX_BYTES","PREV_TX=$TX_BYTES","RX_RATE=$RX_RATE","TX_RATE=$TX_RATE","DAY_KEY=$DAY_KEY","DAY_RX=$DAY_RX","DAY_TX=$DAY_TX","MONTH_KEY=$MONTH_KEY","MONTH_RX=$MONTH_RX","MONTH_TX=$MONTH_TX","BWSTATE","mv -f /var/lib/ts-cloud/bandwidth-state.tmp /var/lib/ts-cloud/bandwidth-state","probe(){ (exec 3<>/dev/tcp/127.0.0.1/$1) 2>/dev/null && echo up || echo down; }",...c,"LOAD=${LOAD:-0}; CPUS=${CPUS:-1}; MEM_TOTAL=${MEM_TOTAL:-0}; MEM_USED=${MEM_USED:-0}","SWAP_TOTAL=${SWAP_TOTAL:-0}; SWAP_USED=${SWAP_USED:-0}; DISK_PCT=${DISK_PCT:-0}","UPTIME_SEC=${UPTIME_SEC:-0}; RX_BYTES=${RX_BYTES:-0}; TX_BYTES=${TX_BYTES:-0}","MEM_PCT=$(( MEM_TOTAL > 0 ? MEM_USED * 100 / MEM_TOTAL : 0 ))","cat > /var/lib/ts-cloud/metrics.json.tmp <<JSON",`{"load":$LOAD,"cpus":$CPUS,"memTotalMb":$MEM_TOTAL,"memUsedMb":$MEM_USED,"memUsedPct":$MEM_PCT,"swapTotalMb":$SWAP_TOTAL,"swapUsedMb":$SWAP_USED,"diskUsedPct":$DISK_PCT,"uptimeSec":$UPTIME_SEC,"network":{"rxBytes":$RX_BYTES,"txBytes":$TX_BYTES,"rxBytesPerSec":$RX_RATE,"txBytesPerSec":$TX_RATE,"dayKey":"$DAY_KEY","rxBytesToday":$DAY_RX,"txBytesToday":$DAY_TX,"monthKey":"$MONTH_KEY","rxBytesMonth":$MONTH_RX,"txBytesMonth":$MONTH_TX,"budgetBytes":${a}},"services":{`+l+"}}","JSON","mv -f /var/lib/ts-cloud/metrics.json.tmp /var/lib/ts-cloud/metrics.json",'ALERTS=""',`if awk -v l="$LOAD" -v c="$CPUS" -v t=${r} 'BEGIN{exit !(c>0 && l/c > t)}'; then ALERTS="$ALERTS load=$LOAD/${r}xCPU"; fi`,`if [ "\${MEM_PCT:-0}" -ge ${s} ]; then ALERTS="$ALERTS mem=\${MEM_PCT}%"; fi`,`if [ "\${DISK_PCT:-0}" -ge ${n} ]; then ALERTS="$ALERTS disk=\${DISK_PCT}%"; fi`,"PREV=$(cat /var/lib/ts-cloud/alert-state 2>/dev/null || echo ok)",'if [ -n "$ALERTS" ]; then',' if [ "$PREV" != alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "⚠️ $(hostname): resource alert —$ALERTS" || true; fi'," echo alert > /var/lib/ts-cloud/alert-state","else",' if [ "$PREV" = alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "✅ $(hostname): resource usage back to normal" || true; fi'," echo ok > /var/lib/ts-cloud/alert-state","fi",...a>0?["BW_TOTAL=$(( MONTH_RX + MONTH_TX ))",`BW_PCT=$(( BW_TOTAL * 100 / ${a} ))`,"BW_PREV=$(cat /var/lib/ts-cloud/bandwidth-alert-state 2>/dev/null || echo ok)",`if [ "$BW_PCT" -ge ${o} ]; then`,` if [ "$BW_PREV" != alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "⚠️ $(hostname): bandwidth at \${BW_PCT}% of the ${i} TB monthly allowance ($MONTH_KEY)" || true; fi`," echo alert > /var/lib/ts-cloud/bandwidth-alert-state","else",' if [ "$BW_PREV" = alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "✅ $(hostname): bandwidth back under the monthly allowance (${BW_PCT}%)" || true; fi'," echo ok > /var/lib/ts-cloud/bandwidth-alert-state","fi"]:[],"TS_CLOUD_METRICS_EOF","chmod +x /usr/local/bin/ts-cloud-metrics.sh","cat > /etc/systemd/system/ts-cloud-metrics.service <<'TS_CLOUD_METRICS_SVC_EOF'","[Unit]","Description=ts-cloud metrics collector","","[Service]","Type=oneshot","ExecStart=/usr/local/bin/ts-cloud-metrics.sh","TS_CLOUD_METRICS_SVC_EOF","cat > /etc/systemd/system/ts-cloud-metrics.timer <<'TS_CLOUD_METRICS_TMR_EOF'","[Unit]","Description=Run ts-cloud metrics collector every minute","","[Timer]","OnCalendar=*-*-* *:*:00","AccuracySec=1s","RandomizedDelaySec=5s","Persistent=true","","[Install]","WantedBy=timers.target","TS_CLOUD_METRICS_TMR_EOF","systemctl daemon-reload","systemctl enable --now ts-cloud-metrics.timer","systemctl start ts-cloud-metrics.service"]}var ro={"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"},so="127.0.0.1:9074";function $s(e){return so}function no(e={}){let t=e.versions?.length?e.versions:["8.3"];return e.default&&t.includes(e.default)?e.default:t[0]}function io(e={}){return{...e.optimizeForProduction===!1?{}:{...ro},...e.ini||{}}}function oo(e={}){let t=io(e),r=Object.keys(t);if(r.length===0)return[];let s=r.map((i)=>`${i}=${t[i]}`),n="ts-cloud-managed";return[Oe(),"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'`,`; ${n} — production PHP tuning`,...s,"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 '/; ${n} BEGIN/,/; ${n} END/d' "$TS_CLOUD_LOADED_INI"`,` cat >> "$TS_CLOUD_LOADED_INI" <<'TS_CLOUD_PHPINI_EOF'`,`; ${n} BEGIN`,...s,`; ${n} END`,"TS_CLOUD_PHPINI_EOF","fi",`(cd ${pe} && pantry restart php-fpm) 2>/dev/null || true`]}function gt(e={}){let t=no(e),r=e.installNginx!==!1,s=e.installComposer!==!1,n=[`php.net@${t}`];if(s)n.push("getcomposer.org");if(r)n.push("nginx.org");return[...ft(n),...ws(["php-fpm"]),...oo(e)]}function er(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 ao(e){if(!e)return"";let t=typeof e==="object"?e:{},s=[`max-age=${t.maxAge??31536000}`];if(t.includeSubDomains??!0)s.push("includeSubDomains");if(t.preload)s.push("preload");return` add_header Strict-Transport-Security "${s.join("; ")}" always;`}function co(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 _s(e){return`/etc/nginx/.htpasswd-${e}`}var lo=new Set(["laravel","php","statamic","wordpress"]);function uo(e){return lo.has(e)}function po(e){return e==="laravel"||e==="statamic"?"public":""}function mo(e,t){let r=e.replace(/\/+$/,""),s=t.replace(/^\/+|\/+$/g,"");return s?`${r}/${s}`:r}function fo(e){let t=e.type??"laravel",r=e.webDirectory??po(t),s=mo(e.appDir,r),n=uo(t),i=e.phpVersion??"8.3",o=[` root ${s};`,"",' add_header X-Frame-Options "SAMEORIGIN";',' add_header X-Content-Type-Options "nosniff";'],a=ao(e.hsts);if(a)o.push(a);for(let c of co(e.security))o.push(c);if(o.push("",` index ${n?"index.php index.html":"index.html index.htm"};`,""," charset utf-8;",""),e.clientMaxBodySize)o.push(` client_max_body_size ${e.clientMaxBodySize};`,"");if(e.auth)o.push(` auth_basic "${e.auth.realm||"Restricted"}";`,` auth_basic_user_file ${_s(e.siteName)};`,"");for(let[c,l]of Object.entries(e.redirects||{}))o.push(` location = ${c} { return 301 ${l}; }`);if(Object.keys(e.redirects||{}).length>0)o.push("");if(n){if(o.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??$s(i)};`," fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;"," include fastcgi_params;"," }",""," location ~ /\\.(?!well-known).* {"," deny all;"," }"),t==="wordpress")o.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")o.push(" location / {"," try_files $uri $uri/ /index.html;"," }");else o.push(" location / {"," try_files $uri $uri/ =404;"," }");if(e.serverSnippet&&e.serverSnippet.length>0){o.push("");for(let c of e.serverSnippet)o.push(c?` ${c}`:"")}return o}function go(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(" "),s=fo(e);if(e.ssl){let i=["server {"," listen 80;"," listen [::]:80;",` server_name ${r};`," return 301 https://$host$request_uri;","}"],o=["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(" ")};`]:[],"",...s,"}"];return`${[...i,"",...o].join(`
|
|
12
12
|
`)}
|
|
13
13
|
`}return`${["server {"," listen 80;"," listen [::]:80;",` server_name ${r};`,...s,"}"].join(`
|
|
14
14
|
`)}
|
|
15
|
-
`}function er(e){let t=`/etc/nginx/sites-available/${e.siteName}`,r=`/etc/nginx/sites-enabled/${e.siteName}`,s=oo(e),n=[...tr()];if(e.auth){let i=ws(e.siteName),o=(l)=>l.split("'").join("'\\''"),a=o(e.auth.password),c=o(e.auth.username);n.push(`TS_CLOUD_HTPASS=$(openssl passwd -apr1 '${a}')`,`printf '%s:%s\\n' '${c}' "$TS_CLOUD_HTPASS" > ${i}`,`chmod 640 ${i}`,`chown root:www-data ${i} 2>/dev/null || true`)}return n.push(`cat > ${t} <<'TS_CLOUD_NGINX_EOF'`,s.replace(/\n$/,""),"TS_CLOUD_NGINX_EOF",`ln -sf ${t} ${r}`,"rm -f /etc/nginx/sites-enabled/default",`${de} -t`,"systemctl reload ts-cloud-nginx 2>/dev/null || systemctl restart ts-cloud-nginx 2>/dev/null || true"),n}var de="/usr/local/bin/ts-cloud-nginx";function tr(e="/opt/pantry"){return[...ht(),...gt(["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 > ${de} <<'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 ${de}`,"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=${de} -t`,`ExecStart=${de} -g 'daemon off;'`,`ExecReload=${de} -s reload`,"Restart=always","RestartSec=3","","[Install]","WantedBy=multi-user.target","TS_CLOUD_NGINXUNIT_EOF","systemctl daemon-reload","systemctl enable ts-cloud-nginx","ls /etc/nginx/sites-enabled/* >/dev/null 2>&1 && systemctl restart ts-cloud-nginx || true"]}function Je(e,t){return!e.events||e.events.includes(t)}async function rr(e,t,r,s={}){if(!e)return[];let n=s.fetchImpl??globalThis.fetch,i=[],o=[],a=(c,l)=>n(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)}).catch(()=>{return});if(e.slack?.webhookUrl&&Je(e,t))i.push("slack"),o.push(a(e.slack.webhookUrl,{text:r}));if(e.discord?.webhookUrl&&Je(e,t))i.push("discord"),o.push(a(e.discord.webhookUrl,{content:r}));if(e.telegram?.botToken&&e.telegram.chatId&&Je(e,t)){i.push("telegram");let c=`https://api.telegram.org/bot${e.telegram.botToken}/sendMessage`;o.push(a(c,{chat_id:e.telegram.chatId,text:r}))}if(e.webhook?.url&&Je(e,t))if(i.push("webhook"),(e.webhook.method||"POST")==="GET"){let c=e.webhook.url.includes("?")?"&":"?",l=`${e.webhook.url}${c}event=${encodeURIComponent(t)}&message=${encodeURIComponent(r)}`;o.push(n(l,{method:"GET"}).catch(()=>{return}))}else o.push(a(e.webhook.url,{event:t,message:r}));if(e.email?.to&&Je(e,t))i.push("email"),o.push(co(e.email,t,r));return await Promise.all(o),i}async function co(e,t,r){try{await(await import("./chunk-1hggd7yz.js")).email.send({to:e.to,from:e.from,subject:`[ts-cloud] ${t}`,text:r})}catch{}}function $s(e,t){return t??e}function Oe(e){if(!e)return[];let t=[];if(e.slack?.webhookUrl)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"text\\":\\"$MSG\\"}" ${e.slack.webhookUrl} || true`);if(e.discord?.webhookUrl)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"content\\":\\"$MSG\\"}" ${e.discord.webhookUrl} || true`);if(e.telegram?.botToken&&e.telegram.chatId)t.push(`curl -fsS -X POST "https://api.telegram.org/bot${e.telegram.botToken}/sendMessage" --data-urlencode "chat_id=${e.telegram.chatId}" --data-urlencode "text=$MSG" || true`);if(e.webhook?.url)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"message\\":\\"$MSG\\"}" ${e.webhook.url} || true`);if(t.length===0)return[];return["cat > /usr/local/bin/ts-cloud-notify <<'TS_CLOUD_NOTIFY_EOF'","#!/bin/bash",'MSG="$1"',...t,"TS_CLOUD_NOTIFY_EOF","chmod +x /usr/local/bin/ts-cloud-notify"]}var ir="/etc/rpx/certs";function or(e){return e.split(".").length===2}function lo(e,t={}){let r=new Set;for(let s of Object.values(e)){if(!s?.domain)continue;if(K(s)==="bucket")continue;r.add(s.domain)}if(t.autoWww!==!1)for(let s of[...r]){if(!or(s))continue;r.add(`www.${s}`)}return[...r]}var uo=["1.1.1.1","8.8.8.8"],po="/var/www/acme-challenge";function mo(e){if(typeof e==="string")return{to:e};let t={to:e.to};if(e.status!=null)t.status=e.status;if(e.preservePath!=null)t.preservePath=e.preservePath;return t}function go(e){let t=e.auth;if(!t||t.enabled===!1||!t.password)return;return{username:t.username||"admin",password:t.password,...t.realm?{realm:t.realm}:{}}}function Ts(e){if(!e||e==="/")return;let t=`/${e}`.replace(/\/+/g,"/").replace(/\/+$/,"");if(!t.startsWith("/"))t=`/${t}`;return t===""||t==="/"?void 0:t}function sr(e,t){let s=(t?`${e}${t}`:e).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return s.length>0?s:"rpx"}function fo(e,t){if(!t||t.length===0)return`localhost:${e}`;return t.map((r)=>`${r.privateIp??r.publicIp}:${e}`)}function Ps(e,t,r){let s=(t.wwwRoot??"/var/www").replace(/\/+$/,""),n=t.slug??"app",i=t.proxy.certsDir??ir,o=t.proxy.loadBalancer,a=[],c=new Set;for(let[p,m]of Object.entries(e)){if(!m||!m.domain)continue;let g=K(m);if(g==="bucket")continue;let b=Ts(m.path),v=sr(m.domain,b),h=go(m);if(g==="redirect"){a.push({to:m.domain,path:b,redirect:mo(m.redirect),id:v,...h?{auth:h}:{}}),c.add(m.domain);continue}if(g==="proxy"){let f=_s(m);if(f.length===0)continue;let y=f.length===1?f[0]:f;a.push({to:m.domain,path:b,from:y,id:v,...h?{auth:h}:{},...Array.isArray(y)&&o?{loadBalancer:o}:{}}),c.add(m.domain);continue}if(g==="server-app"){if(typeof m.port!=="number")continue;let f=fo(m.port,r);a.push({to:m.domain,path:b,from:f,id:v,...h?{auth:h}:{},...Array.isArray(f)&&o?{loadBalancer:o}:{}})}else a.push({to:m.domain,path:b,static:{dir:`${s}/${n}-${p}/current`,spa:m.spa??!1,pathRewriteStyle:m.pathRewriteStyle??"directory"},cleanUrls:m.pathRewriteStyle!=="flat",...h?{auth:h}:{},id:v});c.add(m.domain)}if(t.proxy.autoWww!==!1)for(let p of[...c]){if(!or(p))continue;let m=`www.${p}`;if(c.has(m))continue;a.push({to:m,redirect:{to:`https://${p}`},id:sr(m)}),c.add(m)}a.sort((p,m)=>{if(p.to!==m.to)return p.to.localeCompare(m.to);return(m.path?.length??0)-(p.path?.length??0)});let l={proxies:a,productionCerts:{certsDir:i,certsDirServerNames:[...c]},https:!0,hostsManagement:!1,cleanup:{hosts:!1,certs:!1}};if(t.proxy.onDemandTls&&c.size>0)l.onDemandTls={enabled:!0,allowedSuffixes:[...c],email:t.proxy.onDemandTlsEmail,certsDir:i,staging:t.proxy.onDemandTlsStaging??!1};if(t.proxy.onDemandTls)l.acmeChallengeWebroot=t.proxy.acmeWebroot??po;let u=t.proxy.cdn,d=u?.frontedHosts?.length?u.frontedHosts:[...c];if(u?.secret&&d.length>0)l.originGuard={header:u.secretHeader??"X-Origin-Verify",value:u.secret,hosts:d};return l}function ee(e,t){return Ps(e,t)}function Ae(e,t,r){return Ps(e,r,t)}function Y(e){return e?.webServer==="rpx"||e?.proxy?.engine==="rpx"}var Ze="/etc/rpx",B="/opt/rpx-gateway",nr="/etc/rpx/gateway.ts",Qe="/etc/rpx/gateway",me="rpx-gateway.service",ne="/etc/rpx/sites.d";function ho(e=ne,t=ir){return`// Generated by ts-cloud — rpx gateway assembler.
|
|
15
|
+
`}function tr(e){let t=`/etc/nginx/sites-available/${e.siteName}`,r=`/etc/nginx/sites-enabled/${e.siteName}`,s=go(e),n=[...rr()];if(e.auth){let i=_s(e.siteName),o=(l)=>l.split("'").join("'\\''"),a=o(e.auth.password),c=o(e.auth.username);n.push(`TS_CLOUD_HTPASS=$(openssl passwd -apr1 '${a}')`,`printf '%s:%s\\n' '${c}' "$TS_CLOUD_HTPASS" > ${i}`,`chmod 640 ${i}`,`chown root:www-data ${i} 2>/dev/null || true`)}return n.push(`cat > ${t} <<'TS_CLOUD_NGINX_EOF'`,s.replace(/\n$/,""),"TS_CLOUD_NGINX_EOF",`ln -sf ${t} ${r}`,"rm -f /etc/nginx/sites-enabled/default",`${de} -t`,"systemctl reload ts-cloud-nginx 2>/dev/null || systemctl restart ts-cloud-nginx 2>/dev/null || true"),n}var de="/usr/local/bin/ts-cloud-nginx";function rr(e="/opt/pantry"){return[...ht(),...ft(["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 > ${de} <<'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 ${de}`,"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=${de} -t`,`ExecStart=${de} -g 'daemon off;'`,`ExecReload=${de} -s reload`,"Restart=always","RestartSec=3","","[Install]","WantedBy=multi-user.target","TS_CLOUD_NGINXUNIT_EOF","systemctl daemon-reload","systemctl enable ts-cloud-nginx","ls /etc/nginx/sites-enabled/* >/dev/null 2>&1 && systemctl restart ts-cloud-nginx || true"]}function Qe(e,t){return!e.events||e.events.includes(t)}async function sr(e,t,r,s={}){if(!e)return[];let n=s.fetchImpl??globalThis.fetch,i=[],o=[],a=(c,l)=>n(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)}).catch(()=>{return});if(e.slack?.webhookUrl&&Qe(e,t))i.push("slack"),o.push(a(e.slack.webhookUrl,{text:r}));if(e.discord?.webhookUrl&&Qe(e,t))i.push("discord"),o.push(a(e.discord.webhookUrl,{content:r}));if(e.telegram?.botToken&&e.telegram.chatId&&Qe(e,t)){i.push("telegram");let c=`https://api.telegram.org/bot${e.telegram.botToken}/sendMessage`;o.push(a(c,{chat_id:e.telegram.chatId,text:r}))}if(e.webhook?.url&&Qe(e,t))if(i.push("webhook"),(e.webhook.method||"POST")==="GET"){let c=e.webhook.url.includes("?")?"&":"?",l=`${e.webhook.url}${c}event=${encodeURIComponent(t)}&message=${encodeURIComponent(r)}`;o.push(n(l,{method:"GET"}).catch(()=>{return}))}else o.push(a(e.webhook.url,{event:t,message:r}));if(e.email?.to&&Qe(e,t))i.push("email"),o.push(yo(e.email,t,r));return await Promise.all(o),i}async function yo(e,t,r){try{await(await import("./chunk-43xj5cny.js")).email.send({to:e.to,from:e.from,subject:`[ts-cloud] ${t}`,text:r})}catch{}}function Ts(e,t){return t??e}function De(e){if(!e)return[];let t=[];if(e.slack?.webhookUrl)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"text\\":\\"$MSG\\"}" ${e.slack.webhookUrl} || true`);if(e.discord?.webhookUrl)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"content\\":\\"$MSG\\"}" ${e.discord.webhookUrl} || true`);if(e.telegram?.botToken&&e.telegram.chatId)t.push(`curl -fsS -X POST "https://api.telegram.org/bot${e.telegram.botToken}/sendMessage" --data-urlencode "chat_id=${e.telegram.chatId}" --data-urlencode "text=$MSG" || true`);if(e.webhook?.url)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"message\\":\\"$MSG\\"}" ${e.webhook.url} || true`);if(t.length===0)return[];return["cat > /usr/local/bin/ts-cloud-notify <<'TS_CLOUD_NOTIFY_EOF'","#!/bin/bash",'MSG="$1"',...t,"TS_CLOUD_NOTIFY_EOF","chmod +x /usr/local/bin/ts-cloud-notify"]}import{isIP as Cs}from"node:net";var or="/etc/rpx/certs",Rs="/etc/rpx/local-ca",So="rpx-root-ca.crt";function yt(e=Rs){return`${e.replace(/\/+$/,"")}/${So}`}function ar(e){if(e.toLowerCase().endsWith(".local"))return!1;return e.split(".").length===2}function vo(e,t={}){let r=new Set;for(let s of Object.values(e)){if(!s?.domain)continue;if(K(s)==="bucket")continue;r.add(s.domain)}if(t.autoWww!==!1)for(let s of[...r]){if(!ar(s))continue;r.add(`www.${s}`)}return[...r]}var bo=["1.1.1.1","8.8.8.8"],wo="/var/www/acme-challenge";function $o(e){if(typeof e==="string")return{to:e};let t={to:e.to};if(e.status!=null)t.status=e.status;if(e.preservePath!=null)t.preservePath=e.preservePath;return t}function _o(e){let t=e.auth;if(!t||t.enabled===!1||!t.password)return;return{username:t.username||"admin",password:t.password,...t.realm?{realm:t.realm}:{}}}function cr(e){if(!e)return;return e.tls??"local-ca"}function Es(e,t){if(e.cloud?.provider!=="ssh")return;let r=e.ssh?.lan;if(!r)return;return{...r.hostname?{hostname:r.hostname}:{},tls:r.tls??"local-ca",...t?{ip:t}:{}}}function Is(e){if(e.cloud?.provider!=="ssh")return;return e.ssh?.profile}function To(e){let t=e.trim().toLowerCase();if(!t||t.startsWith("*")||t.includes(":")||t.includes("/")||t.includes(" "))return!1;if(Cs(t)!==0)return!1;return t.endsWith(".local")||!t.includes(".")}function Po(e,t,r){let s=[],n=new Set,i=(l,u)=>{let p=l.trim().toLowerCase();if(!p||n.has(p))return;n.add(p),s.push({host:p,source:u})},o=t.hostname?.trim(),a=(o||`${r}.local`).toLowerCase();if(i(a,o?"ssh.lan.hostname":`the ssh provider's default LAN name for project "${r}"`),Object.entries(e).some(([l,u])=>!!u&&Ps(l)))i(`dashboard.${a}`,"the management dashboard site");for(let[l,u]of Object.entries(e)){if(!u?.domain)continue;if(K(u)==="bucket")continue;if(!To(u.domain))continue;i(u.domain,`site "${l}"`)}return s}function xo(e,t){if(!t?.length)return;return t.find((r)=>{let s=(r.startsWith(".")?r.slice(1):r).toLowerCase();return e===s||e.endsWith(`.${s}`)})}function Co(e,t){if(!t?.enabled)return;for(let{host:r,source:s}of e){let n=xo(r,t.allowedSuffixes);if(!n)continue;throw Error(`The LAN certificate authority and public on-demand TLS both claim "${r}". LAN source: ${s}. Public source: the on-demand TLS allowed suffix "${n}", which is derived from the site domains. A host is either LAN-only, with a certificate signed by the box's own CA, or public, with one issued by Let's Encrypt, never both. Give the LAN a name no site domain covers (ssh.lan.hostname), or take that domain out of the sites this deploy routes.`)}}function Os(e){if(!e||e==="/")return;let t=`/${e}`.replace(/\/+/g,"/").replace(/\/+$/,"");if(!t.startsWith("/"))t=`/${t}`;return t===""||t==="/"?void 0:t}function nr(e,t){let s=(t?`${e}${t}`:e).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return s.length>0?s:"rpx"}function Ro(e,t){if(!t||t.length===0)return`localhost:${e}`;return t.map((r)=>`${r.privateIp??r.publicIp}:${e}`)}function Ds(e,t,r){let s=(t.wwwRoot??"/var/www").replace(/\/+$/,""),n=t.slug??"app",i=t.proxy.certsDir??or,o=t.proxy.loadBalancer,a=[],c=new Set;for(let[d,m]of Object.entries(e)){if(!m||!m.domain)continue;let f=K(m);if(f==="bucket")continue;let S=Os(m.path),v=nr(m.domain,S),y=_o(m);if(f==="redirect"){a.push({to:m.domain,path:S,redirect:$o(m.redirect),id:v,...y?{auth:y}:{}}),c.add(m.domain);continue}if(f==="proxy"){let g=xs(m);if(g.length===0)continue;let b=g.length===1?g[0]:g;a.push({to:m.domain,path:S,from:b,id:v,...y?{auth:y}:{},...Array.isArray(b)&&o?{loadBalancer:o}:{}}),c.add(m.domain);continue}if(f==="server-app"){if(typeof m.port!=="number")continue;let g=Ro(m.port,r);a.push({to:m.domain,path:S,from:g,id:v,...y?{auth:y}:{},...Array.isArray(g)&&o?{loadBalancer:o}:{}})}else a.push({to:m.domain,path:S,static:{dir:`${s}/${n}-${d}/current`,spa:m.spa??!1,pathRewriteStyle:m.pathRewriteStyle??"directory"},cleanUrls:m.pathRewriteStyle!=="flat",...y?{auth:y}:{},id:v});c.add(m.domain)}if(t.proxy.autoWww!==!1)for(let d of[...c]){if(!ar(d))continue;let m=`www.${d}`;if(c.has(m))continue;a.push({to:m,redirect:{to:`https://${d}`},id:nr(m)}),c.add(m)}a.sort((d,m)=>{if(d.to!==m.to)return d.to.localeCompare(m.to);return(m.path?.length??0)-(d.path?.length??0)});let l={proxies:a,productionCerts:{certsDir:i,certsDirServerNames:[...c]},https:!0,hostsManagement:!1,cleanup:{hosts:!1,certs:!1}};if(t.proxy.onDemandTls&&c.size>0)l.onDemandTls={enabled:!0,allowedSuffixes:[...c],email:t.proxy.onDemandTlsEmail,certsDir:i,staging:t.proxy.onDemandTlsStaging??!1};if(t.proxy.onDemandTls)l.acmeChallengeWebroot=t.proxy.acmeWebroot??wo;let u=t.proxy.cdn,p=u?.frontedHosts?.length?u.frontedHosts:[...c];if(u?.secret&&p.length>0)l.originGuard={header:u.secretHeader??"X-Origin-Verify",value:u.secret,hosts:p};if(t.lan)if(cr(t.lan)==="off")l.https=!1;else{let d=Po(e,t.lan,n);Co(d,l.onDemandTls);let m=t.lan.ip&&Cs(t.lan.ip)!==0?[t.lan.ip]:[];l.localCa={dir:Rs,hosts:d.map((f)=>f.host),...m.length>0?{ips:m}:{},installTrust:!0}}return l}function ee(e,t){return Ds(e,t)}function Ne(e,t,r){return Ds(e,r,t)}function j(e){return e?.webServer==="rpx"||e?.proxy?.engine==="rpx"}var et="/etc/rpx",B="/opt/rpx-gateway",ir="/etc/rpx/gateway.ts",Ze="/etc/rpx/gateway",me="rpx-gateway.service",ne="/etc/rpx/sites.d";function Eo(e=ne,t=or){return`// Generated by ts-cloud — rpx gateway assembler.
|
|
16
16
|
// Merges every app's fragment in ${e} so independent deploys compose
|
|
17
17
|
// without clobbering each other. Each deploy writes only its own <slug>.json.
|
|
18
18
|
import { startProxies } from '@stacksjs/rpx'
|
|
@@ -29,6 +29,16 @@ let certsDir = ${JSON.stringify(t)}
|
|
|
29
29
|
let acmeChallengeWebroot
|
|
30
30
|
let guard
|
|
31
31
|
let anyProduction = false
|
|
32
|
+
// LAN certificate authority, unioned across fragments. It is gateway-wide, but
|
|
33
|
+
// it is carried per fragment because THIS file is rewritten wholesale by every
|
|
34
|
+
// deploy on the box: a co-tenant's deploy would erase a CA baked in here, while
|
|
35
|
+
// a fragment belongs to the project that configured it.
|
|
36
|
+
let localCa
|
|
37
|
+
const localCaHosts = new Set()
|
|
38
|
+
const localCaIps = new Set()
|
|
39
|
+
// TLS stays on unless every fragment asks for plain HTTP.
|
|
40
|
+
let fragmentCount = 0
|
|
41
|
+
let anyTls = false
|
|
32
42
|
let files = []
|
|
33
43
|
try { files = readdirSync(dir).filter(n => n.endsWith('.json')).sort() } catch {}
|
|
34
44
|
for (const f of files) {
|
|
@@ -40,6 +50,17 @@ for (const f of files) {
|
|
|
40
50
|
// fragment can't take every other app down, but the drop is now visible.
|
|
41
51
|
try { frag = JSON.parse(readFileSync(dir + '/' + f, 'utf8')) }
|
|
42
52
|
catch (err) { console.error('[rpx-assembler] SKIPPING malformed fragment ' + f + ' — its host(s) will 404 until fixed: ' + err); continue }
|
|
53
|
+
fragmentCount++
|
|
54
|
+
if (frag.https !== false) anyTls = true
|
|
55
|
+
if (frag.localCa) {
|
|
56
|
+
if (!localCa) localCa = { dir: frag.localCa.dir }
|
|
57
|
+
else if (frag.localCa.dir !== localCa.dir) console.warn('[rpx-assembler] ' + f + ' asks for a local CA in ' + frag.localCa.dir + '; the box already uses ' + localCa.dir + ', so its hosts join that CA instead')
|
|
58
|
+
for (const h of frag.localCa.hosts ?? []) localCaHosts.add(h)
|
|
59
|
+
for (const ip of frag.localCa.ips ?? []) localCaIps.add(ip)
|
|
60
|
+
if (frag.localCa.installTrust) localCa.installTrust = true
|
|
61
|
+
if (localCa.validityDays === undefined) localCa.validityDays = frag.localCa.validityDays
|
|
62
|
+
if (localCa.renewBeforeDays === undefined) localCa.renewBeforeDays = frag.localCa.renewBeforeDays
|
|
63
|
+
}
|
|
43
64
|
for (const p of frag.proxies ?? []) {
|
|
44
65
|
const key = p.id || (p.to + (p.path ?? ''))
|
|
45
66
|
if (seen.has(key)) {
|
|
@@ -74,6 +95,10 @@ for (const f of files) {
|
|
|
74
95
|
}
|
|
75
96
|
}
|
|
76
97
|
}
|
|
98
|
+
if (localCa) {
|
|
99
|
+
localCa.hosts = [...localCaHosts]
|
|
100
|
+
if (localCaIps.size > 0) localCa.ips = [...localCaIps]
|
|
101
|
+
}
|
|
77
102
|
const config = {
|
|
78
103
|
proxies,
|
|
79
104
|
productionCerts: {
|
|
@@ -83,7 +108,7 @@ const config = {
|
|
|
83
108
|
// OpenSSL SNI contexts when no current route can select them.
|
|
84
109
|
certsDirServerNames: [...new Set(proxies.map(p => p.to).filter(Boolean))],
|
|
85
110
|
},
|
|
86
|
-
https: true,
|
|
111
|
+
https: fragmentCount === 0 ? true : anyTls,
|
|
87
112
|
hostsManagement: false,
|
|
88
113
|
cleanup: { hosts: false, certs: false },
|
|
89
114
|
// Verbose is the hard default for ts-cloud-installed gateways: without it,
|
|
@@ -95,10 +120,11 @@ const config = {
|
|
|
95
120
|
...(suffixes.size > 0 ? { onDemandTls: { enabled: true, allowedSuffixes: [...suffixes], email, certsDir, staging: !anyProduction } } : {}),
|
|
96
121
|
...(acmeChallengeWebroot ? { acmeChallengeWebroot } : {}),
|
|
97
122
|
...(guard ? { originGuard: { header: guard.header, value: guard.value, hosts: [...guardHosts] } } : {}),
|
|
123
|
+
...(localCa && localCa.hosts.length > 0 ? { localCa } : {}),
|
|
98
124
|
}
|
|
99
125
|
|
|
100
126
|
await startProxies(config)
|
|
101
|
-
`}function
|
|
127
|
+
`}function Ae(e,t,r,s="0644"){return[`__tsc_tmp="$(mktemp "${e}.XXXXXX")"`,`cat > "$__tsc_tmp" <<'${r}'`,t,r,`mv -f "$__tsc_tmp" ${e}`,`chmod ${s} ${e}`]}function Io(e){return`'${e.replaceAll("'","'\\''")}'`}function As(e,t,r,s){if(!s.preserveManagementDashboardRoutes)return Ae(e,t,r,"0600");let n=`
|
|
102
128
|
const { readFileSync, writeFileSync } = require('node:fs')
|
|
103
129
|
const currentPath = process.env.TS_CLOUD_RPX_CURRENT_FRAGMENT
|
|
104
130
|
const candidatePath = process.env.TS_CLOUD_RPX_CANDIDATE_FRAGMENT
|
|
@@ -109,15 +135,15 @@ const retained = Array.isArray(current.proxies) ? current.proxies.filter(isDashb
|
|
|
109
135
|
const next = Array.isArray(candidate.proxies) ? candidate.proxies.filter(route => !isDashboard(route)) : []
|
|
110
136
|
candidate.proxies = [...next, ...retained]
|
|
111
137
|
writeFileSync(candidatePath, JSON.stringify(candidate, null, 2) + '\\n', { mode: 0o600 })
|
|
112
|
-
`.trim();return[`__tsc_fragment_candidate="$(mktemp "${e}.candidate.XXXXXX")"`,`cat > "$__tsc_fragment_candidate" <<'${r}'`,t,r,'chmod 0600 "$__tsc_fragment_candidate"',`if [ -f ${e} ]; then TS_CLOUD_RPX_CURRENT_FRAGMENT=${e} TS_CLOUD_RPX_CANDIDATE_FRAGMENT="$__tsc_fragment_candidate" ${s.bunBin} -e ${
|
|
113
|
-
`),
|
|
114
|
-
`),
|
|
115
|
-
`);return[`mkdir -p ${s}`,`(cd ${B} && ${i} add @stacksjs/tlsx@${o}) || true`,...
|
|
116
|
-
`),"TS_CLOUD_RPX_UNIT_EOF"),"systemctl daemon-reload","systemctl disable --now bun-gateway.service 2>/dev/null || true","systemctl disable --now bun-gateway-renew.timer bun-gateway-renew.service 2>/dev/null || true","rm -f /etc/systemd/system/bun-gateway-renew.timer /etc/systemd/system/bun-gateway-renew.service","systemctl disable --now ts-cloud-nginx.service 2>/dev/null || true",`for timer in /etc/systemd/system/rpx-cert-renew-*.timer; do [ -e "$timer" ] || continue; unit="$(basename "$timer")"; tenant="\${unit#rpx-cert-renew-}"; tenant="\${tenant%.timer}"; [ -f "${ne}/$tenant.json" ] && continue; systemctl disable --now "$unit" 2>/dev/null || true; rm -f "$timer" "/etc/systemd/system/rpx-cert-renew-$tenant.service" "${
|
|
117
|
-
`);n.push(`cat >> ${r} <<'TS_CLOUD_KEYS_EOF'`,i,"TS_CLOUD_KEYS_EOF",`chmod 600 ${r}`)}return n}function
|
|
118
|
-
`))} > ${
|
|
138
|
+
`.trim();return[`__tsc_fragment_candidate="$(mktemp "${e}.candidate.XXXXXX")"`,`cat > "$__tsc_fragment_candidate" <<'${r}'`,t,r,'chmod 0600 "$__tsc_fragment_candidate"',`if [ -f ${e} ]; then TS_CLOUD_RPX_CURRENT_FRAGMENT=${e} TS_CLOUD_RPX_CANDIDATE_FRAGMENT="$__tsc_fragment_candidate" ${s.bunBin} -e ${Io(n)}; fi`,`mv -f "$__tsc_fragment_candidate" ${e}`,`chmod 0600 ${e}`]}var Oo={high:"256M",max:"384M"},Do={high:"512M",max:"768M"};function lr(e){return`rpx-cert-renew-${(e||"app").replace(/[^a-z0-9._-]+/gi,"-")}.service`}function ur(e){let t=new Set;for(let r of e.proxies){let s=r.to;if(!s||s.startsWith("*")||s.includes(":")||!s.includes("."))continue;t.add(s)}return[...t]}function Ao(e){let{config:t,proxy:r}=e,s=t.acmeChallengeWebroot,n=ur(t);if(!r.onDemandTls||!s||n.length===0)return[];let i=e.bunBin??"/usr/local/bin/bun",o=r.version??"latest",a=t.productionCerts.certsDir,c=r.onDemandTlsEmail??`webmaster@${n[0]}`,l=`${i} ${B}/node_modules/@stacksjs/tlsx/dist/bin/cli.js`,u=n.join(","),p=n.join(" "),d=(e.slug||"app").replace(/[^a-z0-9._-]+/gi,"-"),m=`${et}/renew-certs-${d}.sh`,f=lr(d),S=`rpx-cert-renew-${d}.timer`,v=["#!/bin/sh","# Generated by ts-cloud — issue/renew rpx gateway TLS certs via tlsx http-01.","# The running gateway serves the challenge from $WEBROOT on :80, so this needs","# no downtime and no DNS credentials. Reloads the gateway only if a cert changed.","set -u",`CERTS='${a}'`,`WEBROOT='${s}'`,`EMAIL='${c}'`,`TLSX="${l}"`,`BUN='${i}'`,`DOMAINS='${u}'`,"DNS_ATTEMPTS='24'","DNS_DELAY_SECONDS='5'",`DNS_RESOLVERS='${bo.join(" ")}'`,"dns_resolves() {",' d="$1"'," for ns in $DNS_RESOLVERS; do",` if $BUN --eval "const{Resolver}=require('node:dns');const r=new Resolver();r.setServers([process.argv[1]]);r.resolve4(process.argv[2],e=>process.exit(e?1:0))" "$ns" "$d" >/dev/null 2>&1; then`," return 0"," fi"," done",' getent ahosts "$d" >/dev/null 2>&1',"}","wait_for_dns() {",' d="$1"'," attempt=1",' while ! dns_resolves "$d"; do',' if [ "$attempt" -ge "$DNS_ATTEMPTS" ]; then',' echo "DNS for $d did not become resolvable after $DNS_ATTEMPTS attempts" >&2'," return 1"," fi",' echo "Waiting for public DNS before ACME: $d (attempt $attempt/$DNS_ATTEMPTS)"',' sleep "$DNS_DELAY_SECONDS"'," attempt=$((attempt + 1))"," done","}",'before=$(cat "$CERTS"/*.crt 2>/dev/null | sha256sum)',`for d in ${p}; do`,' if [ ! -s "$CERTS/$d.crt" ]; then',' if wait_for_dns "$d"; then',' $TLSX acme:issue -d "$d" --method http-01 --webroot "$WEBROOT" --dir "$CERTS" --prod --email "$EMAIL" || echo "issue $d failed (non-fatal)"'," else",' echo "issue $d skipped until DNS resolves (non-fatal)"'," fi"," # rpx reloads its SNI set when a PEM appears. Complete that reload"," # before the next hostname starts http-01, or :80 can disappear in"," # the middle of the following challenge on a multi-domain deploy.",` [ -s "$CERTS/$d.crt" ] && systemctl restart ${me}`," fi","done",'$TLSX acme:renew --domains "$DOMAINS" --method http-01 --webroot "$WEBROOT" --dir "$CERTS" --days 30 --prod --email "$EMAIL" || echo "renew: some domains failed (non-fatal)"','rm -f "$CERTS"/*.chain.crt','after=$(cat "$CERTS"/*.crt 2>/dev/null | sha256sum)',`[ "$before" = "$after" ] || systemctl restart ${me}`].join(`
|
|
139
|
+
`),y=["[Unit]",`Description=Issue/renew rpx gateway TLS certs for ${d} (tlsx http-01)`,`After=network-online.target ${me}`,"Wants=network-online.target","","[Service]","Type=oneshot",`ExecStart=${m}`].join(`
|
|
140
|
+
`),g=["[Unit]",`Description=Daily rpx gateway TLS cert issuance/renewal for ${d}`,"","[Timer]","OnCalendar=*-*-* 03:30:00","RandomizedDelaySec=1h","Persistent=true","","[Install]","WantedBy=timers.target"].join(`
|
|
141
|
+
`);return[`mkdir -p ${s}`,`(cd ${B} && ${i} add @stacksjs/tlsx@${o}) || true`,...Ae(m,v,"TS_CLOUD_RENEW_EOF"),`chmod +x ${m}`,...Ae(`/etc/systemd/system/${f}`,y,"TS_CLOUD_RENEW_SVC_EOF"),...Ae(`/etc/systemd/system/${S}`,g,"TS_CLOUD_RENEW_TIMER_EOF"),"systemctl daemon-reload",`systemctl enable --now ${S} || true`,`${m} || true`]}function te(e){let{config:t,proxy:r}=e,s=e.bunBin??"/usr/local/bin/bun",n=r.version??"latest",i=t.productionCerts.certsDir,o=(e.slug||"app").replace(/[^a-z0-9._-]+/gi,"-"),a=JSON.stringify({slug:o,...t},null,2),c=Eo(ne,i),u=[`Environment=RPX_UPSTREAM_TIMEOUT=${r.upstreamTimeout??60}`];if(typeof r.maxUpstreamConns==="number")u.push(`Environment=RPX_MAX_UPSTREAM_CONNS=${r.maxUpstreamConns}`);let p=e.profile==="raspberry-pi"?Oo:Do,d=r.memoryHigh??p.high,m=r.memoryMax??p.max;return["set -euo pipefail",`mkdir -p ${et} ${ne} ${i} ${B}`,`rm -rf ${B}.next ${B}.prev`,`mkdir -p ${B}.next`,`(cd ${B}.next && ${s} add @stacksjs/rpx@${n})`,`mv ${B} ${B}.prev`,`mv ${B}.next ${B}`,`rm -rf ${B}.prev`,`ln -sfn ${B}/node_modules ${et}/node_modules`,...As(`${ne}/${o}.json`,a,"TS_CLOUD_RPX_FRAGMENT_EOF",{bunBin:s,preserveManagementDashboardRoutes:e.preserveManagementDashboardRoutes}),...Ae(ir,c,"TS_CLOUD_RPX_EOF"),`${s} build --production --compile --outfile ${Ze}.next ${ir}`,`chmod 0755 ${Ze}.next`,`mv -f ${Ze}.next ${Ze}`,...Ae(`/etc/systemd/system/${me}`,["[Unit]","Description=rpx reverse-proxy gateway (managed by ts-cloud)","After=network.target network-online.target","Wants=network-online.target","","[Service]","Type=simple",`ExecStart=${Ze}`,`WorkingDirectory=${B}`,"Environment=BUN_INSTALL=/root/.bun","Environment=APP_ENV=production","Environment=NODE_ENV=production",...u,"MemoryAccounting=true",`MemoryHigh=${d}`,`MemoryMax=${m}`,"CPUWeight=500","IOWeight=500","OOMPolicy=stop","Restart=always","RestartSec=5","StartLimitIntervalSec=120","StartLimitBurst=5",`ExecStartPre=/bin/sh -c 'for p in 80 443; do fuser -k -n tcp "$p" 2>/dev/null || true; done; sleep 1'`,"LimitNOFILE=1048576","AmbientCapabilities=CAP_NET_BIND_SERVICE","","[Install]","WantedBy=multi-user.target"].join(`
|
|
142
|
+
`),"TS_CLOUD_RPX_UNIT_EOF"),"systemctl daemon-reload","systemctl disable --now bun-gateway.service 2>/dev/null || true","systemctl disable --now bun-gateway-renew.timer bun-gateway-renew.service 2>/dev/null || true","rm -f /etc/systemd/system/bun-gateway-renew.timer /etc/systemd/system/bun-gateway-renew.service","systemctl disable --now ts-cloud-nginx.service 2>/dev/null || true",`for timer in /etc/systemd/system/rpx-cert-renew-*.timer; do [ -e "$timer" ] || continue; unit="$(basename "$timer")"; tenant="\${unit#rpx-cert-renew-}"; tenant="\${tenant%.timer}"; [ -f "${ne}/$tenant.json" ] && continue; systemctl disable --now "$unit" 2>/dev/null || true; rm -f "$timer" "/etc/systemd/system/rpx-cert-renew-$tenant.service" "${et}/renew-certs-$tenant.sh"; done`,`systemctl enable ${me}`,`systemctl restart ${me}`,...Ao(e)]}function $e(e){let t=(e.slug||"app").replace(/[^a-z0-9._-]+/gi,"-"),r=JSON.stringify({slug:t,...e.config},null,2);return["set -euo pipefail",`mkdir -p ${ne}`,...As(`${ne}/${t}.json`,r,"TS_CLOUD_RPX_FRAGMENT_EOF",{bunBin:"/usr/local/bin/bun",preserveManagementDashboardRoutes:e.preserveManagementDashboardRoutes}),`systemctl restart ${me}`]}function ke(e=[],t={}){let r=t.path??"/root/.ssh/authorized_keys",n=[`mkdir -p ${r.replace(/\/[^/]*$/,"")}`,`touch ${r}`,`sed -i '/^${Ns("# >>> ts-cloud managed keys >>>")}$/,/^${Ns("# <<< ts-cloud managed keys <<<")}$/d' ${r}`];if(e.length>0){let i=["# >>> ts-cloud managed keys >>>",...e.map((o)=>`${o.publicKey.trim()} ${o.name}`),"# <<< ts-cloud managed keys <<<"].join(`
|
|
143
|
+
`);n.push(`cat >> ${r} <<'TS_CLOUD_KEYS_EOF'`,i,"TS_CLOUD_KEYS_EOF",`chmod 600 ${r}`)}return n}function Ns(e){return e.replace(/[.*[\]\\/^$]/g,"\\$&")}function Ms(e,t){let r=`/tmp/ts-cloud-${e}.sh`,s=`TS_CLOUD_${e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}_EOF`;return[`cat > ${r} <<'${s}'`,t.replace(/\n$/,""),s,`chmod +x ${r}`,`bash ${r} || echo "ts-cloud: ${e} setup did not complete; continuing" >&2`,`rm -f ${r}`]}function Us(e,t){if(e===!1)return;if(e===!0||e===void 0)return t;return e}var ks={enabled:!0,ports:[80,443]},No={mode:"detection",paranoiaLevel:1};function ko(e=!0,t=[]){let r=Us(e,ks);if(!r||r.enabled===!1)return[];let s=[...new Set([...r.ports??ks.ports??[],...t])].sort((n,i)=>n-i);return Ms("ddos",Hs({...r,ports:s}))}function Ho(e=!0){let t=Us(e,No);if(!t||t.mode==="off")return[];return Ms("waf",Ls(t))}function zs(e={},t=[]){return[...ko(e.ddos,t),...Ho(e.waf)]}function Lo(e){return`${e}-sftp`}function Fs(e){return e.port??2222}function Mo(e){let t=e.sftp.storage;if(t?.type==="efs"&&t.path)return t.path;return`/var/sftp/${e.slug}`}function He(e){return`'${e.split("'").join("'\\''")}'`}function Bs(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[n,i]of Object.entries(e.users))if(!i.sshPublicKeys?.length)throw Error(`sftp: user ${n} needs at least one SSH public key`)}function Ks(e){let{slug:t,sftp:r}=e,s=Lo(t),n=Mo(e),i=Fs(r),o="/etc/ts-sftp/host_key",a="/etc/ts-sftp/users",c=r.serviceUser??"ts-sftp",l=[`# --- ts-sftp (${s}) ---`,`id -u ${c} >/dev/null 2>&1 || useradd --system --home-dir ${He(n)} --shell /usr/sbin/nologin ${c}`,'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 ${He(n)} /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 ${He(`${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'],u=[];for(let[p,d]of Object.entries(r.users)){let m=(d.homeDirectory??p).replace(/^\/+|\/+$/g,"");if(!m||m.split("/").includes(".."))throw Error(`sftp: invalid homeDirectory for user ${p}`);let f=`/etc/ts-sftp/users/${p}.pub`;l.push(`mkdir -p ${He(`${n}/${m}`)}`,`printf '%s\\n' ${He(d.sshPublicKeys.join(`
|
|
144
|
+
`))} > ${f}`,`chmod 644 ${f}`),u.push(`--user ${p}:${f}`)}return l.push(`chown -R ${c}:${c} ${He(n)} /etc/ts-sftp`,`cat > /etc/systemd/system/${s}.service <<TSCLOUD_SFTP_UNIT`,"[Unit]","Description=ts-sftp file transfer server","After=network.target","","[Service]",`User=${c}`,`ExecStart=$BUN_BIN /opt/ts-sftp/node_modules/ts-sftp/dist/bin/cli.js serve --root ${n} --host-key /etc/ts-sftp/host_key --port ${i}${r.readOnly?" --read-only":""} ${u.join(" ")}`,"Restart=always","RestartSec=2","NoNewPrivileges=true","PrivateTmp=true","ProtectSystem=strict",`ReadWritePaths=${n}`,"","[Install]","WantedBy=multi-user.target","TSCLOUD_SFTP_UNIT","systemctl daemon-reload",`systemctl enable ${s}.service`,`systemctl restart ${s}.service`),l}function js(e){return e?[Fs(e)]:[]}var Uo=[80,443];function St(e={}){if(e.enabled===!1)return[];let t=[...new Set([...Uo,...e.allowedPorts||[]])].filter((s)=>Number.isInteger(s)&&s>=1&&s<=65535).sort((s,n)=>s-n),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 s of t)r.push(`ufw allow ${s}/tcp`);return r.push("ufw --force enable"),r}function _e(e,t){let r=e.infrastructure?.compute??{},s=r.runtime==="php"||!!r.php,n=vt(e,{environment:t?.environment}),i=s||!!r.managedServices,o=i?ht():[],a=!j(r),c=s?[...o,...gt({versions:r.php?.versions,default:r.php?.default,extensions:r.php?.extensions,installNginx:a,optimizeForProduction:r.php?.optimizeForProduction,ini:r.php?.ini}),...a?rr():[]]:void 0,l=[],u=fe(e);if(!s&&i)l.push(...o);if(l.push(...De(e.notifications)),r.managedServices)l.push(...bt(r.managedServices,{mail:n.enabled?n:void 0}),...Me(u,r.managedServices));let p=e.infrastructure?.sftp;if(p)Bs(p,Le(e)),l.push(...Ks({slug:e.project.slug,sftp:p}));let d=r.firewall??(s?{enabled:!0}:{enabled:!1}),m=Gs(n);if(l.push(...St(m.length>0?{...d,allowedPorts:[...d.allowedPorts??[],...m]}:d)),l.push(...zs({ddos:r.ddos,waf:r.waf},[...r.firewall?.allowedPorts??[],...m])),l.push(...le(r.autoUpdates??s)),l.push(...vs(r.appUpdates)),l.push(...ue(r.monitoring??s)),l.push(...ke(r.sshKeys,{path:t?.authorizedKeysPath})),r.backups?.enabled)l.push(...wt({database:u,backups:r.backups}));return{runtime:r.runtime||"bun",runtimeVersion:r.runtimeVersion||"latest",phpBox:s,phpProvision:c,servicesProvision:l.length>0?l:void 0}}function G(e={}){let{runtime:t="bun",runtimeVersion:r="latest",systemPackages:s=[],database:n,phpProvision:i,servicesProvision:o,caddyfile:a,rpxProvision:c,baked:l=!1,swapGb:u=2}=e,p=new Set(s);if(n==="sqlite")p.add("sqlite3");else if(n==="mysql")p.add("mysql-client");else if(n==="postgres")p.add("postgresql-client");let d=`#!/bin/bash
|
|
119
145
|
set -euo pipefail
|
|
120
|
-
`,m=Math.floor(u);if(m>0)
|
|
146
|
+
`,m=Math.floor(u);if(m>0)d+=`
|
|
121
147
|
# Swap: a swapless box under memory pressure lets the kernel OOM killer choose
|
|
122
148
|
# victims box-wide (the gateway, a tenant app, postgres). A modest swapfile
|
|
123
149
|
# with low swappiness gives the kernel headroom without hurting responsiveness.
|
|
@@ -132,20 +158,20 @@ fi
|
|
|
132
158
|
grep -qE '^/swapfile\\s' /etc/fstab || echo '/swapfile none swap sw 0 0' >> /etc/fstab
|
|
133
159
|
echo 'vm.swappiness=10' > /etc/sysctl.d/99-ts-cloud-swap.conf
|
|
134
160
|
sysctl -w vm.swappiness=10 >/dev/null
|
|
135
|
-
`;if(!l){if(
|
|
161
|
+
`;if(!l){if(d+=`
|
|
136
162
|
export DEBIAN_FRONTEND=noninteractive
|
|
137
163
|
apt-get update -y
|
|
138
164
|
apt-get upgrade -y
|
|
139
165
|
apt-get install -y curl tar gzip unzip git ca-certificates
|
|
140
|
-
`,
|
|
141
|
-
apt-get install -y ${[...
|
|
142
|
-
`;if(i&&i.length>0)
|
|
166
|
+
`,p.size>0)d+=`
|
|
167
|
+
apt-get install -y ${[...p].join(" ")}
|
|
168
|
+
`;if(i&&i.length>0)d+=`
|
|
143
169
|
${i.join(`
|
|
144
170
|
`)}
|
|
145
|
-
`;if(o&&o.length>0)
|
|
171
|
+
`;if(o&&o.length>0)d+=`
|
|
146
172
|
${o.join(`
|
|
147
173
|
`)}
|
|
148
|
-
`;if(t==="bun")
|
|
174
|
+
`;if(t==="bun")d+=`
|
|
149
175
|
# cloud-init runs this with \`set -u\` and NO $HOME set. bun's install.sh
|
|
150
176
|
# dereferences $HOME even when BUN_INSTALL is set, so without this the install
|
|
151
177
|
# aborts with "HOME: unbound variable" and /usr/local/bin/bun never appears —
|
|
@@ -167,17 +193,17 @@ curl -fsSL https://bun.sh/install | bash${r==="latest"?"":` -s "bun-v${r}"`}
|
|
|
167
193
|
ln -sf /root/.bun/bin/bun /usr/local/bin/bun
|
|
168
194
|
echo 'export BUN_INSTALL="/root/.bun"' > /etc/profile.d/bun.sh
|
|
169
195
|
echo 'export PATH="$BUN_INSTALL/bin:$PATH"' >> /etc/profile.d/bun.sh
|
|
170
|
-
`;else if(t==="node"){let
|
|
171
|
-
curl -fsSL https://deb.nodesource.com/setup_${
|
|
196
|
+
`;else if(t==="node"){let f=r==="latest"||!r?"20":r.split(".")[0];d+=`
|
|
197
|
+
curl -fsSL https://deb.nodesource.com/setup_${f}.x | bash -
|
|
172
198
|
apt-get install -y nodejs
|
|
173
199
|
ln -sf /usr/bin/node /usr/local/bin/node
|
|
174
200
|
ln -sf /usr/bin/npm /usr/local/bin/npm
|
|
175
|
-
`}else if(t==="deno")
|
|
201
|
+
`}else if(t==="deno")d+=`
|
|
176
202
|
curl -fsSL https://deno.land/install.sh | sh
|
|
177
203
|
ln -sf /root/.deno/bin/deno /usr/local/bin/deno
|
|
178
|
-
`}if(
|
|
204
|
+
`}if(d+=`
|
|
179
205
|
mkdir -p /var/www /var/ts-cloud/staging /var/ts-cloud/releases
|
|
180
|
-
`,a)
|
|
206
|
+
`,a)d+=`
|
|
181
207
|
ARCH=$(uname -m | sed 's/x86_64/amd64/;s/aarch64/arm64/')
|
|
182
208
|
curl -fsSL "https://caddyserver.com/api/download?os=linux&arch=\${ARCH}" -o /usr/local/bin/caddy
|
|
183
209
|
chmod +x /usr/local/bin/caddy
|
|
@@ -220,19 +246,19 @@ CADDY_CONFIG_EOF
|
|
|
220
246
|
systemctl daemon-reload
|
|
221
247
|
systemctl enable caddy
|
|
222
248
|
systemctl start caddy
|
|
223
|
-
`;if(c&&c.length>0){let
|
|
224
|
-
${
|
|
249
|
+
`;if(c&&c.length>0){let f=c[0]==="set -euo pipefail"?c.slice(1):c;d+=`
|
|
250
|
+
${f.join(`
|
|
225
251
|
`)}
|
|
226
|
-
`}return
|
|
252
|
+
`}return d+=`
|
|
227
253
|
echo "ts-cloud bootstrap complete — instance is ready for site deploys"
|
|
228
|
-
`,
|
|
229
|
-
`),"TS_CLOUD_BASH_EOF"]}async runRemoteDeploy(e){let t=this.region,r=new mt(t);if(e.targets.length>0){let n=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(!n.CommandId)return{success:!1,instanceCount:0,perInstance:[],error:"Failed to send SSM command"};return this.pollSsmCommand(r,n.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 s=await r.sendCommandByTags({tags:e.tags,commands:this.bashWrap(e.commands),timeoutSeconds:e.timeoutSeconds||600,comment:e.comment});return{success:s.success,instanceCount:s.instanceCount,perInstance:s.perInstance.map((n)=>({instanceId:n.instanceId,status:n.status,output:n.output,error:n.error})),error:s.error}}async pollSsmCommand(e,t,r,s=600000){let i=Date.now(),o=new Set(["Success","Failed","Cancelled","TimedOut"]),a=[];while(Date.now()-i<s){await new Promise((u)=>setTimeout(u,3000));try{if(a=await e.listCommandInvocations({CommandId:t,Details:!0}),a.length>=r&&a.every((
|
|
230
|
-
`)}var
|
|
254
|
+
`,d}var Ws="/aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id";function Vs(e){let t=[{port:22,protocol:"tcp",cidr:"0.0.0.0/0"},{port:80,protocol:"tcp",cidr:"0.0.0.0/0"},{port:443,protocol:"tcp",cidr:"0.0.0.0/0"}],r=new Set;for(let s of Object.values(e.sites||{}))if(s&&typeof s.port==="number"&&![22,80,443].includes(s.port))r.add(s.port);for(let s of r)t.push({port:s,protocol:"tcp",cidr:"0.0.0.0/0"});return t}function Xs(e){let t=e.infrastructure?.compute??{},r=_e(e),s=t.proxy?.engine==="rpx"?te({proxy:t.proxy,config:ee(e.sites??{},{proxy:t.proxy,slug:e.project.slug}),slug:e.project.slug,bunBin:t.runtime==="node"||t.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0;return G({runtime:r.runtime,runtimeVersion:r.runtimeVersion,systemPackages:t.systemPackages,database:e.infrastructure?.database,phpProvision:r.phpProvision,servicesProvision:r.servicesProvision,rpxProvision:s,baked:t.bakedImage===!0,swapGb:t.swapGb})}function qs(e){return Buffer.from(e,"utf8").toString("base64")}function Ys(e){return e.infrastructure?.compute?.image??null}function $t(e,t){return`${e}-${t}-app-sg`}function pr(e,t,r="app"){return[{Key:"Project",Value:e},{Key:"Environment",Value:t},{Key:"Role",Value:r},{Key:"ManagedBy",Value:"ts-cloud"}]}function zo(e,t,r){if(!e?.length)return!1;let s=(n)=>e.find((i)=>i.Key===n)?.Value;return s("Project")===t&&s("Environment")===r}function Js(e,t){let r=$t(t.slug,t.environment);return e.find((s)=>{if(s.GroupName!==r)return!1;if(t.vpcId&&s.VpcId&&s.VpcId!==t.vpcId)return!1;if(!!s.Tags?.some((i)=>i.Key==="Project"))return zo(s.Tags,t.slug,t.environment);return!!t.vpcId&&s.VpcId===t.vpcId})}function Bo(e){try{let t=tn(Fo(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 _t{name="aws";usesCloudFormation=!0;region;ec2Client;cfnClient;constructor(e={}){this.region=e.region||"us-east-1",this.ec2Client=e.ec2Client??((t)=>new en(t)),this.cfnClient=e.cfnClient??((t)=>new Zs(t))}resolveRegion(e){return e.project.region||this.region}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e,s=this.resolveRegion(t),n=t.project.slug,i=t.infrastructure?.compute;if(!i)throw Error("infrastructure.compute is required to provision AWS compute");let o=this.ec2Client(s),a=await this.findComputeTargets({slug:n,environment:r,role:"app",region:s});if(a.length>0){let w=a[0];return{appInstanceId:w.id,appPublicIp:w.publicIp,appPublicIpv6:w.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}let c=Ys(t);if(!c){if(c=(await new mt(s).getParameter({Name:Ws})).Parameter?.Value??null,!c)throw Error("Could not resolve the Ubuntu 24.04 AMI from SSM")}let l=await o.describeVpcs(),u=(l.Vpcs||[]).find((w)=>w.IsDefault)||(l.Vpcs||[])[0];if(!u?.VpcId)throw Error("No VPC found to launch the instance into");let p=(await o.describeSubnets({Filters:[{Name:"vpc-id",Values:[u.VpcId]}]})).Subnets||[],d=p.find((w)=>w.MapPublicIpOnLaunch)||p[0],m=d?.SubnetId;if(!d?.MapPublicIpOnLaunch)console.warn("ts-cloud: no public subnet found; the instance may not get a public IP (deploys/SSL need one).");let f=$t(n,r),v=(await o.describeSecurityGroups({Filters:[{Name:"group-name",Values:[f]},{Name:"vpc-id",Values:[u.VpcId]}]})).SecurityGroups?.[0]?.GroupId;if(!v)v=(await o.createSecurityGroup({GroupName:f,Description:`ts-cloud ${n}/${r} app`,VpcId:u.VpcId,TagSpecifications:[{ResourceType:"security-group",Tags:pr(n,r)}]})).GroupId;let y=Vs(t);await o.authorizeSecurityGroupIngress({GroupId:v,IpPermissions:y.map((w)=>({IpProtocol:w.protocol,FromPort:w.port,ToPort:w.port,IpRanges:[{CidrIp:w.cidr}]}))}).catch((w)=>{if(!/InvalidPermission\.Duplicate/.test(w instanceof Error?w.message:""))throw w});let g=qs(Xs(t)),b=i.server?.instanceType||"t3.small",P=(await o.runInstances({ImageId:c,InstanceType:b,MinCount:1,MaxCount:1,SecurityGroupIds:v?[v]:void 0,SubnetId:m,UserData:g,IamInstanceProfile:i.server?.iamInstanceProfile?{Name:i.server.iamInstanceProfile}:void 0,TagSpecifications:[{ResourceType:"instance",Tags:[{Key:"Name",Value:`${n}-${r}-app`},...pr(n,r)]}]})).Instances?.[0]?.InstanceId;if(!P)throw Error("RunInstances did not return an instance id");let T=await o.waitForInstanceState(P,"running");if(!T)throw Error(`Instance ${P} did not reach 'running' before timeout`);return{appInstanceId:P,appPublicIp:T.PublicIpAddress,appPublicIpv6:ce(T.Ipv6Address),sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}async destroyCompute(e){let{config:t,environment:r}=e,s=t.project.slug,n=this.resolveRegion(t),i=this.ec2Client(n),o=[],c=(await this.findComputeTargets({slug:s,environment:r,role:"app",region:n})).map((f)=>f.id),l;if(c.length>0)l=(await i.describeInstances({InstanceIds:c}).catch(()=>({Reservations:[]}))).Reservations?.flatMap((S)=>S.Instances??[]).find((S)=>S.VpcId)?.VpcId;if(c.length>0)await i.terminateInstances(c),o.push(...c.map((f)=>`instance ${f}`)),await Promise.all(c.map((f)=>i.waitForInstanceState(f,"terminated").catch(()=>{return})));let u=$t(s,r),p=[{Name:"group-name",Values:[u]}];if(l)p.push({Name:"vpc-id",Values:[l]});let d=await i.describeSecurityGroups({Filters:p}).catch(()=>({SecurityGroups:[]})),m=Js(d.SecurityGroups??[],{slug:s,environment:r,vpcId:l});if(m?.GroupId)for(let f=0;f<10;f++)try{await i.deleteSecurityGroup(m.GroupId),o.push(`security group ${u}`);break}catch{await new Promise((S)=>setTimeout(S,3000))}return{destroyed:o}}async getComputeOutputs(e){let t=this.resolveRegion(e.config),r=E(e.config,e.environment),s=this.cfnClient(t);try{let n=await s.getStackOutputs(r);return{deployBucketName:n.deployBucketName,appInstanceId:n.appInstanceId,appPublicIp:n.appPublicIp,sshUser:"ec2-user"}}catch(n){if(!/does not exist|ValidationError/i.test(n instanceof Error?n.message:""))throw n;let o=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",region:t}))[0];return{appInstanceId:o?.id,appPublicIp:o?.publicIp,appPublicIpv6:o?.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}}async uploadRelease(e){let t=this.resolveRegion(e.config),s=(await this.getComputeOutputs({config:e.config,environment:e.environment})).deployBucketName;if(!s)throw Error("No deployBucketName in stack outputs. Re-deploy infrastructure to add the staging bucket.");return await new Qs(t).putObject({bucket:s,key:e.remoteKey,body:tn(e.localPath),contentType:"application/gzip"}),{artifactRef:`s3://${s}/${e.remoteKey}`}}async findComputeTargets(e){let t=e.region??this.region,r=this.ec2Client(t),s=[{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"]}],n=await r.describeInstances({Filters:s}),i=this.reservationsToTargets(n.Reservations);if(i.length>0||(e.role||"app")!=="app")return i;let o=e.stackName??`${e.slug}-${e.environment}`,a=Bo(o);if(!a)try{a=(await this.cfnClient(t).getStackOutputs(o)).appInstanceId??null}catch{a=null}if(!a)return[];try{let c=await r.describeInstances({InstanceIds:[a],Filters:[{Name:"instance-state-name",Values:["running","pending"]}]});return this.reservationsToTargets(c.Reservations)}catch{return[]}}reservationsToTargets(e){let t=[];for(let r of e||[])for(let s of r.Instances||[]){if(!s.InstanceId)continue;let n=s.Tags?.find((i)=>i.Key==="Name")?.Value;t.push({id:s.InstanceId,name:n,publicIp:s.PublicIpAddress,publicIpv6:ce(s.Ipv6Address),privateIp:s.PrivateIpAddress,status:s.State?.Name})}return t}bashWrap(e){return["bash <<'TS_CLOUD_BASH_EOF'",e.join(`
|
|
255
|
+
`),"TS_CLOUD_BASH_EOF"]}async runRemoteDeploy(e){let t=this.region,r=new mt(t);if(e.targets.length>0){let n=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(!n.CommandId)return{success:!1,instanceCount:0,perInstance:[],error:"Failed to send SSM command"};return this.pollSsmCommand(r,n.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 s=await r.sendCommandByTags({tags:e.tags,commands:this.bashWrap(e.commands),timeoutSeconds:e.timeoutSeconds||600,comment:e.comment});return{success:s.success,instanceCount:s.instanceCount,perInstance:s.perInstance.map((n)=>({instanceId:n.instanceId,status:n.status,output:n.output,error:n.error})),error:s.error}}async pollSsmCommand(e,t,r,s=600000){let i=Date.now(),o=new Set(["Success","Failed","Cancelled","TimedOut"]),a=[];while(Date.now()-i<s){await new Promise((u)=>setTimeout(u,3000));try{if(a=await e.listCommandInvocations({CommandId:t,Details:!0}),a.length>=r&&a.every((p)=>o.has(p.Status||"")))break}catch{}}let c=a.map((u)=>({instanceId:u.InstanceId,status:u.Status||"Unknown",output:u.StandardOutputContent,error:u.StandardErrorContent})),l=c.length>0&&c.every((u)=>u.status==="Success");return{success:l,instanceCount:c.length,perInstance:c,error:l?void 0:we(c,"One or more SSM command invocations failed")}}}function rn(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 dr(e,t,r={}){let s=Bun.spawn(["ssh",...rn(r),`${r.user??"root"}@${e}`,t],{stdout:"pipe",stderr:"pipe"}),[n,i]=await Promise.all([new Response(s.stdout).text(),new Response(s.stderr).text()]);return{code:await s.exited,stdout:n,stderr:i}}async function ie(e,t,r={}){let s=await dr(e,t,r);if(s.code!==0)throw Error(`ssh \`${t}\` on ${e} failed (${s.code}): ${s.stderr.trim()||s.stdout.trim()}`);return s.stdout}async function mr(e,t={}){let r=t.timeoutMs??180000,s=t.pollIntervalMs??5000,n=Date.now();while(Date.now()-n<r){let i=await dr(e,"echo ready",t);if(i.code===0&&i.stdout.includes("ready"))return;await new Promise((o)=>setTimeout(o,s))}throw Error(`SSH not ready on ${e} after ${r}ms`)}function tt(e={}){return["set -e","ts_cloud_script=$(mktemp /tmp/ts-cloud-deploy.XXXXXXXX)",`trap 'rm -f "$ts_cloud_script"' EXIT`,'cat > "$ts_cloud_script"',e.sudo?'sudo -n -H bash "$ts_cloud_script" < /dev/null':'bash "$ts_cloud_script" < /dev/null'].join(`
|
|
256
|
+
`)}var fr=tt();import{execFileSync as Zo,execSync as pn}from"node:child_process";import{createHash as ea,randomUUID as dn}from"node:crypto";import{createReadStream as ta,existsSync as ra,readFileSync as sa}from"node:fs";function sn(e={}){let t=Math.max(1,e.appServers??e.instances??1),r=!!e.servicesServer||t>1,s=t>1||!!e.server?.loadBalancer;return{appServers:t,loadBalancer:s,dedicatedServices:r,servicesOnApp:!r}}function nn(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 gr(e){let t=e.infrastructure?.compute??{},r=fe(e);return[...bt(t.managedServices??{mysql:!0,redis:!0},{bindPrivate:!0}),...Me(r,t.managedServices??{mysql:!0}),...le(!0),...ue(!0),...ke(t.sshKeys),...De(e.notifications),...t.backups?.enabled?[...wt({database:r,backups:t.backups})]:[]]}import{homedir as Ko}from"node:os";import{join as jo}from"node:path";var Tt={location:"fsn1",image:"ubuntu-24.04",sshUser:"root",sshPrivateKeyPath:"~/.ssh/id_ed25519"};function Pt(e){return e.startsWith("~/")?jo(Ko(),e.slice(2)):e}function Ue(...e){for(let t of e){let r=process.env[t]?.trim();if(r)return r}return}function ze(...e){for(let t of e){let r=t?.trim();if(r)return r}return}function rt(e,t){return ze(e,t?.hetzner?.apiToken,Ue("HCLOUD_TOKEN","HETZNER_API_TOKEN"))}function hr(e,t){return ze(t,e?.hetzner?.location,Ue("HCLOUD_LOCATION","HETZNER_LOCATION"))??Tt.location}function st(e,t){let r=e?.infrastructure?.compute;return ze(t,r?.image,e?.hetzner?.image,Ue("HCLOUD_IMAGE","HETZNER_IMAGE"))??Tt.image}function Go(e,t){return ze(t,e?.hetzner?.sshUser,Ue("HCLOUD_SSH_USER","HETZNER_SSH_USER"))??Tt.sshUser}function on(e,t){return Pt(ze(t,e?.hetzner?.sshPrivateKeyPath,Ue("HCLOUD_SSH_KEY","HETZNER_SSH_KEY"))??Tt.sshPrivateKeyPath)}function Wo(e,t,r){let s=ze(t,e?.hetzner?.sshPublicKeyPath,Ue("HCLOUD_SSH_PUBLIC_KEY","HETZNER_SSH_PUBLIC_KEY"));if(s)return Pt(s);return`${r??on(e)}.pub`}function an(e,t={}){let r=on(e,t.sshPrivateKeyPath);return{apiToken:rt(t.apiToken,e),location:hr(e,t.location),image:st(e,t.image),sshUser:Go(e,t.sshUser),sshPrivateKeyPath:r,sshPublicKeyPath:Wo(e,t.sshPublicKeyPath,r)}}var Vo="https://api.hetzner.cloud/v1";class xt extends Error{status;code;details;constructor(e,t,r,s){super(e);this.status=t;this.code=r;this.details=s;this.name="HetznerApiError"}}class Ct extends Error{action;constructor(e,t){super(e);this.action=t;this.name="HetznerActionError"}}class Rt{name="hetzner";apiToken;baseUrl;fetchImpl;constructor(e){this.apiToken=e.apiToken,this.baseUrl=e.baseUrl??Vo,this.fetchImpl=e.fetchImpl??fetch}async request(e,t,r){let s=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)}),n=await s.text(),i;try{i=n?JSON.parse(n):{}}catch{if(!s.ok){let o=n.trim().slice(0,200)||s.statusText||"Hetzner API error";throw Error(`Hetzner API ${e} ${t} (${s.status}): ${o}`)}throw Error(`Hetzner API ${e} ${t}: unexpected non-JSON response`)}if(!s.ok){let o=i.error?.message||s.statusText||"Hetzner API error",a=i.error?.code?` [${i.error.code}]`:"";throw new xt(`Hetzner API ${e} ${t} (${s.status})${a}: ${o}`,s.status,i.error?.code,i.error?.details)}return i}async requestAll(e,t){let r=[],s=1;for(;;){let n=e.includes("?")?"&":"?",i=await this.request("GET",`${e}${n}per_page=50&page=${s}`);r.push(...i[t]??[]);let o=i.meta?.pagination?.next_page;if(!o)return r;s=o}}async listServers(){return this.requestAll("/servers","servers")}async getServer(e){return(await this.request("GET",`/servers/${e}`)).server}async getServerMetrics(e,t){let r=new URLSearchParams({type:t.types.join(","),start:t.start.toISOString(),end:t.end.toISOString(),step:String(Math.max(60,Math.floor(t.step??60)))});return(await this.request("GET",`/servers/${e}/metrics?${r}`)).metrics}async listServerTypes(e){let t=e?`?name=${encodeURIComponent(e)}`:"";return this.requestAll(`/server_types${t}`,"server_types")}async getServerType(e){return(await this.listServerTypes(e)).find((t)=>t.name===e)??null}async createServer(e){let t=await this.request("POST","/servers",{name:e.name,server_type:e.serverType,image:e.image,location:e.location,datacenter:e.datacenter,ssh_keys:e.sshKeys,user_data:e.userData,labels:e.labels,firewalls:e.firewalls,networks:e.networks,start_after_create:!0});return{server:t.server,action:t.action}}async listNetworks(){return this.requestAll("/networks","networks")}async createNetwork(e){let t=e.ipRange??"10.0.0.0/16";return(await this.request("POST","/networks",{name:e.name,ip_range:t,subnets:[{type:"cloud",ip_range:t,network_zone:"eu-central"}],labels:e.labels})).network}async deleteNetwork(e){await this.request("DELETE",`/networks/${e}`)}async listLoadBalancers(){return this.requestAll("/load_balancers","load_balancers")}async createLoadBalancer(e){return(await this.request("POST","/load_balancers",{name:e.name,load_balancer_type:e.type??"lb11",location:e.location,network_zone:e.network?void 0:e.networkZone??"eu-central",network:e.network,labels:e.labels,targets:[{type:"label_selector",label_selector:{selector:e.labelSelector},use_private_ip:!!e.network}],services:e.services.map((r)=>({protocol:r.protocol??"tcp",listen_port:r.listenPort,destination_port:r.destinationPort,health_check:{protocol:"http",port:80,interval:15,timeout:10,retries:3,http:{path:"/",status_codes:["2??","3??"]}}}))})).load_balancer}async deleteLoadBalancer(e){await this.request("DELETE",`/load_balancers/${e}`)}async deleteServer(e){return(await this.request("DELETE",`/servers/${e}`)).action}async listFirewalls(){return this.requestAll("/firewalls","firewalls")}async createFirewall(e){let t=await this.request("POST","/firewalls",{name:e.name,rules:e.rules,labels:e.labels,apply_to:e.applyTo});return{firewall:t.firewall,actions:t.actions}}async setFirewallRules(e,t){return(await this.request("POST",`/firewalls/${e}/actions/set_rules`,{rules:t})).actions??[]}async deleteFirewall(e){await this.request("DELETE",`/firewalls/${e}`)}async applyFirewallToResources(e,t){return(await this.request("POST",`/firewalls/${e}/actions/apply_to_resources`,{apply_to:t})).actions}async listSshKeys(){return this.requestAll("/ssh_keys","ssh_keys")}async createSshKey(e){return(await this.request("POST","/ssh_keys",{name:e.name,public_key:e.publicKey,labels:e.labels})).ssh_key}async deleteSshKey(e){await this.request("DELETE",`/ssh_keys/${e}`)}async getAction(e){return(await this.request("GET",`/actions/${e}`)).action}async shutdownServer(e){return(await this.request("POST",`/servers/${e}/actions/shutdown`,{})).action}async powerOnServer(e){return(await this.request("POST",`/servers/${e}/actions/poweron`,{})).action}async changeServerType(e,t,r){return(await this.request("POST",`/servers/${e}/actions/change_type`,{server_type:t,upgrade_disk:r})).action}async powerOffServer(e){return(await this.request("POST",`/servers/${e}/actions/poweroff`,{})).action}async stopServer(e,t){if((await this.getServer(e)).status==="off")return;await this.shutdownServer(e);let s=t?.gracefulWaitMs??120000,n=t?.pollIntervalMs??3000,i=Date.now();while(Date.now()-i<s){if((await this.getServer(e)).status==="off")return;await new Promise((a)=>setTimeout(a,n))}let o=await this.powerOffServer(e);await this.waitForAction(o.id),await this.waitForServerStatus(e,"off")}async renameServer(e,t){return(await this.request("PUT",`/servers/${e}`,{name:t})).server}async listImages(e){let t=e?.type?`?type=${encodeURIComponent(e.type)}`:"";return this.requestAll(`/images${t}`,"images")}async getImage(e){return(await this.request("GET",`/images/${e}`)).image}async createImage(e,t){return this.request("POST",`/servers/${e}/actions/create_image`,{description:t.description,type:t.type??"snapshot",labels:t.labels})}async deleteImage(e){await this.request("DELETE",`/images/${e}`)}async rebuildServer(e,t){return(await this.request("POST",`/servers/${e}/actions/rebuild`,{image:t})).action}async listPrimaryIps(){return this.requestAll("/primary_ips","primary_ips")}async unassignPrimaryIp(e){return(await this.request("POST",`/primary_ips/${e}/actions/unassign`,{})).action}async assignPrimaryIp(e,t){return(await this.request("POST",`/primary_ips/${e}/actions/assign`,{assignee_id:t,assignee_type:"server"})).action}async waitForAction(e,t){let r=t?.pollIntervalMs??2000,s=t?.maxWaitMs??300000,n=Date.now();while(Date.now()-n<s){let i=await this.getAction(e);if(i.status==="success")return i;if(i.status==="error")throw new Ct(i.error?.message||"Hetzner action failed",i);await new Promise((o)=>setTimeout(o,r))}throw Error(`Timed out waiting for Hetzner action ${e}`)}async waitForServerRunning(e,t){let r=t?.pollIntervalMs??3000,s=t?.maxWaitMs??600000,n=Date.now();while(Date.now()-n<s){let i=await this.getServer(e);if(i.status==="running")return i;await new Promise((o)=>setTimeout(o,r))}throw Error(`Timed out waiting for server ${e} to reach running state`)}async waitForServerStatus(e,t,r){let s=r?.pollIntervalMs??3000,n=r?.maxWaitMs??600000,i=Date.now();while(Date.now()-i<n){let o=await this.getServer(e);if(o.status===t)return o;await new Promise((a)=>setTimeout(a,s))}throw Error(`Timed out waiting for server ${e} to reach ${t} state`)}}function Xo(e,t){let r=rt(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 nt(e){let[t,r]=e.trim().split(/\s+/);return r?`${t} ${r}`:t}function cn(e){if(!e)return"";return e.endsWith(`
|
|
231
257
|
`)?e:`${e}
|
|
232
258
|
`}function re(e,t={}){let r=t.scriptPath??"/var/lib/cloud/ts-cloud-bootstrap.sh",s=t.permissions??"0755",n=e.split(`
|
|
233
259
|
`).map((i)=>` ${i}`).join(`
|
|
234
260
|
`);return`#cloud-config
|
|
235
|
-
${
|
|
261
|
+
${cn(t.before)}write_files:
|
|
236
262
|
- path: ${r}
|
|
237
263
|
permissions: '${s}'
|
|
238
264
|
owner: root:root
|
|
@@ -240,17 +266,17 @@ ${en(t.before)}write_files:
|
|
|
240
266
|
${n}
|
|
241
267
|
runcmd:
|
|
242
268
|
- [ bash, ${r} ]
|
|
243
|
-
${
|
|
244
|
-
`,"utf8"),await Ho(n,s)}async function Pe(e){return nt(e)}async function xe(e,t){await Fe(e,t)}var Sr=268435456;function J(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function Ko(e){let t=Mo("sha256");for await(let r of zo(e))t.update(r);return t.digest("hex")}class he{name="hetzner";usesCloudFormation=!1;client;sshPrivateKeyPath;sshPublicKeyPath;sshUser;location;stateOnly;waitForBoot;bootWait;constructor(e={}){let t=tt(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 Ct({apiToken:t??""});let r=Zs(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,s=t.project.slug,n=t.infrastructure?.compute;if(!n)throw Error("infrastructure.compute is required to provision Hetzner compute");if(t.cloud?.attachTo)return this.attachToComputeInfrastructure(t.cloud.attachTo,t,r);let i=E(t,r),o=`${s}-${r}-app`,a=n.runtime==="php"||!!n.php,c=Ys(n);if(c.dedicatedServices||c.appServers>1)return a?this.provisionFleet(e,c):this.provisionBunFleet(e,c);let l=N(s,r,"app"),u=t.sites||{},d=Y(n)?[]:this.collectUpstreamPorts(u),p=`${s}-${r}-app-fw`,{firewall:m}=await this.ensureFirewall(p,l,Rt({allowSsh:n.allowSsh!==!1,sitePorts:d,allowedPorts:[...n.firewall?.allowedPorts??[],...Ls(t.infrastructure?.sftp)]})),g=await this.ensureSshKey(s,r,l),b=await Pe(i);if(b?.serverId){let D=await this.tryGetServer(b.serverId);if(D&&D.status!=="off")return this.outputsFromState(b,D)}let v=await this.findExistingServer(s,r,o);if(v&&v.status!=="off"){let D={provider:"hetzner",stackName:i,serverId:v.id,serverName:v.name,publicIp:v.public_net.ipv4?.ip,publicIpv6:ce(v.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await xe(i,D),this.outputsFromState(D,v)}let h=n.proxy?.engine==="rpx"?te({proxy:n.proxy,config:ee(u,{proxy:n.proxy,slug:t.project.slug}),slug:t.project.slug,bunBin:n.runtime==="node"||n.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,f=_e(t,{environment:r}),y=n.bakedImage===!0,S=j({runtime:f.runtime,runtimeVersion:f.runtimeVersion,systemPackages:n.systemPackages,database:t.infrastructure?.database,phpProvision:f.phpProvision,servicesProvision:f.servicesProvision,rpxProvision:h,baked:y,swapGb:n.swapGb}),P=re(S),T=Te(n.size),w=rt(t),{server:C,action:W}=await this.client.createServer({name:o,serverType:T,image:w,location:t.hetzner?.location||this.location,userData:P,labels:l,sshKeys:g?[g]:void 0,firewalls:[{firewall:m.id}]});await this.client.waitForAction(W.id);let O=await this.client.waitForServerRunning(C.id),L={provider:"hetzner",stackName:i,serverId:O.id,serverName:O.name,firewallId:m.id,publicIp:O.public_net.ipv4?.ip,publicIpv6:ce(O.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};await xe(i,L);let U=O.public_net.ipv4?.ip;if(U&&this.waitForBoot)await this.waitForSshReady(U),await this.waitForCloudInit(U);return this.outputsFromState(L,O)}async provisionFleet(e,t){let{config:r,environment:s}=e,n=r.project.slug,i=r.infrastructure.compute,o=E(r,s),a=Te(i.size),c=rt(r),l=r.hetzner?.location||this.location,u=i.bakedImage===!0,d=await Pe(o);if(d?.loadBalancerId){let k=(await this.client.listLoadBalancers().catch(()=>[])).find((_)=>_.id===d.loadBalancerId);if(k)return{appPublicIp:k.public_net?.ipv4?.ip,loadBalancerIp:k.public_net?.ipv4?.ip,servicesPrivateIp:d.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}let p=await this.ensureSshKey(n,s,N(n,s,"app")),m=`${n}-${s}-net`,b=(await this.client.listNetworks().catch(()=>[])).find((x)=>x.name===m)??await this.client.createNetwork({name:m,labels:N(n,s,"app")}),{firewall:v}=await this.ensureFirewall(`${n}-${s}-app-fw`,N(n,s,"app"),Rt({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),{firewall:h}=await this.ensureFirewall(`${n}-${s}-services-fw`,N(n,s,"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]}]),f=mr(r),y=re(j({runtime:"php",servicesProvision:f,baked:u,swapGb:i.swapGb})),S=await this.client.listServers().catch(()=>[]),P=[],T=S.find((x)=>G(x.labels,n,s,"services"));if(!T){let{server:x,action:k}=await this.client.createServer({name:`${n}-${s}-services`,serverType:Te(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:c,location:l,userData:y,labels:N(n,s,"services"),sshKeys:p?[p]:void 0,firewalls:[{firewall:h.id}],networks:[b.id]});await this.client.waitForAction(k.id),T=await this.client.waitForServerRunning(x.id),P.push(x.id)}let w=T.id,C=T.private_net?.[0]?.ip??(await this.client.getServer(w)).private_net?.[0]?.ip,W=[...le(!0),...ue(!0),...Ne(i.sshKeys),...Oe(r.notifications)],O=ft({versions:i.php?.versions,default:i.php?.default,extensions:i.php?.extensions,installNginx:!Y(i),optimizeForProduction:i.php?.optimizeForProduction,ini:i.php?.ini}),L=re(j({runtime:"php",phpProvision:O,servicesProvision:W,baked:u,swapGb:i.swapGb})),U=S.filter((x)=>G(x.labels,n,s,"app")),D=U.map((x)=>x.id);if(U.length>t.appServers)for(let x of U.slice(t.appServers))await this.client.deleteServer(x.id).catch(()=>{}),D.splice(D.indexOf(x.id),1);for(let x=U.length;x<t.appServers;x++){let{server:k,action:_}=await this.client.createServer({name:`${n}-${s}-app-${x+1}`,serverType:a,image:c,location:l,userData:L,labels:N(n,s,"app"),sshKeys:p?[p]:void 0,firewalls:[{firewall:v.id}],networks:[b.id]});await this.client.waitForAction(_.id),D.push(k.id),P.push(k.id)}if(this.waitForBoot&&P.length>0)await Promise.all(P.map(async(x)=>{let _=(await this.client.waitForServerRunning(x)).public_net.ipv4?.ip;if(_)await this.waitForSshReady(_),await this.waitForCloudInit(_)}));let F=`${n}-${s}-lb`,R,se;if(t.loadBalancer){let k=(await this.client.listLoadBalancers().catch(()=>[])).find((_)=>_.name===F)??await this.client.createLoadBalancer({name:F,location:l,network:b.id,labels:N(n,s,"lb"),labelSelector:`ts-cloud/project=${n},ts-cloud/environment=${s},ts-cloud/role=app`,services:[{listenPort:80,destinationPort:80},{listenPort:443,destinationPort:443}]});se=k.id,R=k.public_net?.ipv4?.ip}let M=R??(await this.client.getServer(D[0]).catch(()=>{return}))?.public_net.ipv4?.ip,Z={provider:"hetzner",stackName:o,networkId:b.id,loadBalancerId:se,servicesServerId:w,servicesPrivateIp:C,publicIp:M,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await xe(o,Z),{appPublicIp:M,loadBalancerIp:R,servicesPrivateIp:C,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async provisionBunFleet(e,t){let{config:r,environment:s}=e,n=r.project.slug,i=r.infrastructure.compute,o=E(r,s),a=Te(i.size),c=rt(r),l=r.hetzner?.location||this.location,u=i.bakedImage===!0,d=r.sites||{},p=await Pe(o);if(p?.lbServerId){let _=await this.tryGetServer(p.lbServerId);if(_&&_.status!=="off"){let I=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"},H=await this.findComputeTargets({slug:n,environment:s,role:"app",stackName:o});return this.refreshLbRoutes(_,d,H.map((X)=>({privateIp:X.privateIp,publicIp:X.publicIp})),I,n),{appPublicIp:_.public_net.ipv4?.ip??p.publicIp,loadBalancerIp:_.public_net.ipv4?.ip??p.publicIp,servicesPrivateIp:p.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}}let m=await this.ensureSshKey(n,s,N(n,s,"app")),g=`${n}-${s}-net`,v=(await this.client.listNetworks().catch(()=>[])).find((_)=>_.name===g)??await this.client.createNetwork({name:g,labels:N(n,s,"app")}),h=this.collectUpstreamPorts(d),{firewall:f}=await this.ensureFirewall(`${n}-${s}-app-fw`,N(n,s,"app"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},...h.map((_)=>({direction:"in",protocol:"tcp",port:String(_),source_ips:[v.ip_range],description:`ts-cloud port ${_} (private, LB-only)`}))]),{firewall:y}=await this.ensureFirewall(`${n}-${s}-lb-fw`,N(n,s,"lb"),Rt({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),S=await this.client.listServers().catch(()=>[]),P=[],T,w,C=!!i.servicesServer||!!i.managedServices,W=t.dedicatedServices&&C;if(W){let{firewall:_}=await this.ensureFirewall(`${n}-${s}-services-fw`,N(n,s,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[v.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[v.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[v.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[v.ip_range]}]),I=mr(r),H=re(j({runtime:"bun",servicesProvision:I,baked:u,swapGb:i.swapGb})),X=S.find((ae)=>G(ae.labels,n,s,"services"));if(!X){let{server:ae,action:qe}=await this.client.createServer({name:`${n}-${s}-services`,serverType:Te(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:c,location:l,userData:H,labels:N(n,s,"services"),sshKeys:m?[m]:void 0,firewalls:[{firewall:_.id}],networks:[v.id]});await this.client.waitForAction(qe.id),X=await this.client.waitForServerRunning(ae.id),P.push(ae.id)}T=X.id,w=X.private_net?.[0]?.ip??(await this.client.getServer(T)).private_net?.[0]?.ip}let O=W?{...i,managedServices:void 0,backups:void 0}:i,L=_e({...r,infrastructure:{...r.infrastructure,compute:O}},{environment:s}),U=re(j({runtime:L.runtime,runtimeVersion:L.runtimeVersion,systemPackages:i.systemPackages,database:r.infrastructure?.database,servicesProvision:L.servicesProvision,baked:u,swapGb:i.swapGb})),D=S.filter((_)=>G(_.labels,n,s,"app")),F=D.map((_)=>_.id);if(D.length>t.appServers)for(let _ of D.slice(t.appServers))await this.client.deleteServer(_.id).catch(()=>{}),F.splice(F.indexOf(_.id),1);for(let _=D.length;_<t.appServers;_++){let{server:I,action:H}=await this.client.createServer({name:`${n}-${s}-app-${_+1}`,serverType:a,image:c,location:l,userData:U,labels:N(n,s,"app"),sshKeys:m?[m]:void 0,firewalls:[{firewall:f.id}],networks:[v.id]});await this.client.waitForAction(H.id),F.push(I.id),P.push(I.id)}if(this.waitForBoot&&P.length>0)await Promise.all(P.map(async(_)=>{let H=(await this.client.waitForServerRunning(_)).public_net.ipv4?.ip;if(H)await this.waitForSshReady(H),await this.waitForCloudInit(H)}));let R=[];for(let _ of F){let I=S.find((H)=>H.id===_);if(!I||!I.private_net?.[0]?.ip)I=await this.client.getServer(_).catch(()=>I);R.push({privateIp:I?.private_net?.[0]?.ip,publicIp:I?.public_net.ipv4?.ip})}let se=`${n}-${s}-lb`,M,Z;if(t.loadBalancer){let _=S.find((H)=>G(H.labels,n,s,"lb")),I=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"};if(!_){let H=te({proxy:I,config:Ae(d,R,{proxy:I,slug:n}),slug:n,bunBin:L.runtime==="node"||L.runtime==="deno"?void 0:"/usr/local/bin/bun"}),X=re(j({runtime:"bun",rpxProvision:H,baked:!1})),ae=typeof i.loadBalancer==="object"?i.loadBalancer.size:void 0,{server:qe,action:Yt}=await this.client.createServer({name:se,serverType:Te(ae??"micro"),image:c,location:l,userData:X,labels:N(n,s,"lb"),sshKeys:m?[m]:void 0,firewalls:[{firewall:y.id}],networks:[v.id]});if(await this.client.waitForAction(Yt.id),_=await this.client.waitForServerRunning(qe.id),this.waitForBoot){let Xe=_.public_net.ipv4?.ip;if(Xe)await this.waitForSshReady(Xe),await this.waitForCloudInit(Xe)}}else this.refreshLbRoutes(_,d,R,I,n);M=_.id,Z=_.public_net.ipv4?.ip}let x=Z??(await this.client.getServer(F[0]).catch(()=>{return}))?.public_net.ipv4?.ip,k={provider:"hetzner",stackName:o,networkId:v.id,lbServerId:M,appServerIds:F,servicesServerId:T,servicesPrivateIp:w,publicIp:x,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await xe(o,k),{appPublicIp:x,loadBalancerIp:Z,servicesPrivateIp:w,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async destroyCompute(e){let{config:t,environment:r}=e,s=t.project.slug,n=E(t,r),i=await Pe(n),o=[],a=`${s}-${r}-lb`,l=(await this.client.listLoadBalancers().catch(()=>[])).find((f)=>f.name===a);if(l)try{await this.client.deleteLoadBalancer(l.id),o.push(`load balancer ${a}`)}catch{}let u=await this.client.listServers().catch(()=>[]),d=new Set;for(let f of u)if(G(f.labels,s,r,"app")||G(f.labels,s,r,"services")||G(f.labels,s,r,"lb"))d.add(f.id);if(i?.serverId)d.add(i.serverId);if(i?.servicesServerId)d.add(i.servicesServerId);if(i?.lbServerId)d.add(i.lbServerId);for(let f of i?.appServerIds??[])d.add(f);for(let f of d)try{await this.client.deleteServer(f),o.push(`server ${f}`)}catch{}let p=await this.client.listFirewalls().catch(()=>[]);for(let f of[`${s}-${r}-app-fw`,`${s}-${r}-services-fw`,`${s}-${r}-lb-fw`]){let y=p.find((S)=>S.name===f);if(!y)continue;for(let S=0;S<12;S++)try{await this.client.deleteFirewall(y.id),o.push(`firewall ${f}`);break}catch{await this.sleep(3000)}}let m=`${s}-${r}-net`,b=(await this.client.listNetworks().catch(()=>[])).find((f)=>f.name===m);if(b)for(let f=0;f<12;f++)try{await this.client.deleteNetwork(b.id),o.push(`network ${m}`);break}catch{await this.sleep(3000)}let h=(await this.client.listSshKeys().catch(()=>[])).filter((f)=>hr(f.labels,s,r));for(let f of h)try{await this.client.deleteSshKey(f.id),o.push(`ssh key ${f.name}`)}catch{}return await xe(n,{provider:"hetzner",stackName:n}).catch(()=>{}),{destroyed:o}}async getComputeOutputs(e){let t=E(e.config,e.environment),r=await Pe(t);if(r?.serverId){let i=await this.tryGetServer(r.serverId);if(i)return this.outputsFromState(r,i)}if(r?.lbServerId){let o=(await this.tryGetServer(r.lbServerId))?.public_net.ipv4?.ip??r.publicIp;return{...this.outputsFromState(r),appPublicIp:o,loadBalancerIp:o}}if(r?.loadBalancerId||r?.servicesPrivateIp)return this.outputsFromState(r);let n=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:E(e.config,e.environment)}))[0];return{deployStoragePath:"/var/ts-cloud/staging",appInstanceId:n?.id,appPublicIp:n?.publicIp,sshUser:this.sshUser}}async uploadRelease(e){let t=e.targets?.length?e.targets:await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:E(e.config,e.environment)});if(t.length===0)throw Error("No Hetzner compute targets found for release upload");let n=`/var/ts-cloud/staging/${`${e.remoteKey.replace(/^releases\//,"").replace(/\.tar\.gz$/,"").replace(/\//g,"-")}-${nn()}.tar.gz`}`,i=await Ko(e.localPath),o="/var/ts-cloud/artifacts",a=`${o}/${i}.tar.gz`;for(let c of t){if(!c.publicIp)throw Error(`Target ${c.id} has no public IP for SCP upload`);let l=["set -euo pipefail",`mkdir -p ${J(o)} /var/ts-cloud/staging`,`test -s ${J(a)}`,`cp -- ${J(a)} ${J(n)}`].join(`
|
|
245
|
-
`);try{this.sshExec(c.publicIp,l);continue}catch{}let u=`${o}/.${i}-${
|
|
246
|
-
`))}return{artifactRef:n}}async findComputeTargets(e){let t=e.role||"app",r=(i)=>({id:String(i.id),name:i.name,publicIp:i.public_net.ipv4?.ip,publicIpv6:ce(i.public_net.ipv6?.ip),privateIp:i.private_net?.[0]?.ip,status:i.status});if(t==="app"||t==="lb"||t==="services"){let i=await
|
|
247
|
-
`),r=[];for(let n of e.targets){if(!n.publicIp){r.push({instanceId:n.id,status:"Failed",error:"Missing public IP"});continue}try{let i=this.sshExec(n.publicIp,t);
|
|
248
|
-
`))}async findExistingServer(e,t,r){let s=await this.client.listServers(),n=s.find((o)=>
|
|
249
|
-
${n}`);if(/status:\s*(?:done|degraded)/.test(n))return}catch(n){if(n instanceof Error&&/cloud-init reported an error/.test(n.message))throw n}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:ce(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,...he.SSH_HOST_KEY_OPTS,...he.SSH_KEEPALIVE_OPTS,"-o","BatchMode=yes",...t,`${this.sshUser}@${e}`]}scpToHost(e,t,r){let s=["scp","-i",this.sshPrivateKeyPath,...he.SSH_HOST_KEY_OPTS,...he.SSH_KEEPALIVE_OPTS,"-o","BatchMode=yes",t,`${this.sshUser}@${e}:${r}`].map((i)=>`"${i.replace(/"/g,"\\\"")}"`).join(" "),n=3;for(let i=1;i<=3;i++)try{
|
|
250
|
-
`);try{let r=Bun.spawn(["bash","-c",t],{stdout:"pipe",stderr:"pipe",env:process.env}),[s,n,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:s,error:n}]}}catch(r){return{success:!1,instanceCount:1,perInstance:[{instanceId:"localhost",status:"Failed",error:r?.message??String(r)}],error:r?.message??String(r)}}}}function
|
|
251
|
-
`).find((i)=>i&&!i.startsWith("#"))?.trim().split(/\s+/);if(s.code!==0||!n?.[1]||!n[2])throw Error(`SSH host-key scan failed: ${s.stderr.trim()||"no key returned"}`);return{algorithm:n[1],key:n[2]}}function
|
|
252
|
-
`)){let i=n.trim();if(!i||i.startsWith("#")||i.startsWith("@"))continue;let[o,a,c]=i.split(/\s+/);if(!o||!a||!c)continue;if(o.split(",").includes(s))return{algorithm:a,key:c}}return null}function
|
|
253
|
-
`,{mode:384})}class
|
|
269
|
+
${cn(t.after)}`}function Et(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 yr={micro:"cpx11",small:"cx23",medium:"cx33",large:"cx43",xlarge:"cx53","2xlarge":"ccx33"};function Te(e){if(!e)return yr.micro;if(e in yr)return yr[e];return e}var A="ts-cloud";function N(e,t,r="app"){return{[`${A}/project`]:e,[`${A}/environment`]:t,[`${A}/role`]:r,[`${A}/managed-by`]:"ts-cloud"}}function W(e,t,r,s="app"){return Sr(e,t,r)&&e[`${A}/role`]===s}function Sr(e,t,r){if(!e)return!1;return e[`${A}/project`]===t&&e[`${A}/environment`]===r}import{mkdir as qo,readFile as Yo,rename as Jo,writeFile as Qo}from"node:fs/promises";import{join as un}from"node:path";var vr="storage/cloud/state";function ge(e=process.cwd()){return ln()?It(e,"state"):un(e,vr)}function Fe(e,t=process.cwd()){return un(ge(t),`${e}.json`)}async function Pe(e,t=process.cwd()){try{let r=await Yo(Fe(e,t),"utf8");return JSON.parse(r)}catch{return null}}async function Be(e,t,r=process.cwd()){let s=Fe(e,r);await qo(ge(r),{recursive:!0});let n=`${s}.${process.pid}.tmp`;await Qo(n,`${JSON.stringify(t,null,2)}
|
|
270
|
+
`,"utf8"),await Jo(n,s)}async function xe(e){return Pe(e)}async function Ce(e,t){await Be(e,t)}var br=268435456;function J(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function na(e){let t=ea("sha256");for await(let r of ta(e))t.update(r);return t.digest("hex")}class he{name="hetzner";usesCloudFormation=!1;client;sshPrivateKeyPath;sshPublicKeyPath;sshUser;location;stateOnly;waitForBoot;bootWait;constructor(e={}){let t=rt(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 Rt({apiToken:t??""});let r=an(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,s=t.project.slug,n=t.infrastructure?.compute;if(!n)throw Error("infrastructure.compute is required to provision Hetzner compute");if(t.cloud?.attachTo)return this.attachToComputeInfrastructure(t.cloud.attachTo,t,r);let i=E(t,r),o=`${s}-${r}-app`,a=n.runtime==="php"||!!n.php,c=sn(n);if(c.dedicatedServices||c.appServers>1)return a?this.provisionFleet(e,c):this.provisionBunFleet(e,c);let l=N(s,r,"app"),u=t.sites||{},p=j(n)?[]:this.collectUpstreamPorts(u),d=`${s}-${r}-app-fw`,{firewall:m}=await this.ensureFirewall(d,l,Et({allowSsh:n.allowSsh!==!1,sitePorts:p,allowedPorts:[...n.firewall?.allowedPorts??[],...js(t.infrastructure?.sftp)]})),f=await this.ensureSshKey(s,r,l),S=await xe(i);if(S?.serverId){let D=await this.tryGetServer(S.serverId);if(D&&D.status!=="off")return this.outputsFromState(S,D)}let v=await this.findExistingServer(s,r,o);if(v&&v.status!=="off"){let D={provider:"hetzner",stackName:i,serverId:v.id,serverName:v.name,publicIp:v.public_net.ipv4?.ip,publicIpv6:ce(v.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await Ce(i,D),this.outputsFromState(D,v)}let y=n.proxy?.engine==="rpx"?te({proxy:n.proxy,config:ee(u,{proxy:n.proxy,slug:t.project.slug}),slug:t.project.slug,bunBin:n.runtime==="node"||n.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,g=_e(t,{environment:r}),b=n.bakedImage===!0,h=G({runtime:g.runtime,runtimeVersion:g.runtimeVersion,systemPackages:n.systemPackages,database:t.infrastructure?.database,phpProvision:g.phpProvision,servicesProvision:g.servicesProvision,rpxProvision:y,baked:b,swapGb:n.swapGb}),P=re(h),T=Te(n.size),w=st(t),{server:C,action:V}=await this.client.createServer({name:o,serverType:T,image:w,location:t.hetzner?.location||this.location,userData:P,labels:l,sshKeys:f?[f]:void 0,firewalls:[{firewall:m.id}]});await this.client.waitForAction(V.id);let O=await this.client.waitForServerRunning(C.id),L={provider:"hetzner",stackName:i,serverId:O.id,serverName:O.name,firewallId:m.id,publicIp:O.public_net.ipv4?.ip,publicIpv6:ce(O.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};await Ce(i,L);let M=O.public_net.ipv4?.ip;if(M&&this.waitForBoot)await this.waitForSshReady(M),await this.waitForCloudInit(M);return this.outputsFromState(L,O)}async provisionFleet(e,t){let{config:r,environment:s}=e,n=r.project.slug,i=r.infrastructure.compute,o=E(r,s),a=Te(i.size),c=st(r),l=r.hetzner?.location||this.location,u=i.bakedImage===!0,p=await xe(o);if(p?.loadBalancerId){let k=(await this.client.listLoadBalancers().catch(()=>[])).find((_)=>_.id===p.loadBalancerId);if(k)return{appPublicIp:k.public_net?.ipv4?.ip,loadBalancerIp:k.public_net?.ipv4?.ip,servicesPrivateIp:p.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}let d=await this.ensureSshKey(n,s,N(n,s,"app")),m=`${n}-${s}-net`,S=(await this.client.listNetworks().catch(()=>[])).find((x)=>x.name===m)??await this.client.createNetwork({name:m,labels:N(n,s,"app")}),{firewall:v}=await this.ensureFirewall(`${n}-${s}-app-fw`,N(n,s,"app"),Et({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),{firewall:y}=await this.ensureFirewall(`${n}-${s}-services-fw`,N(n,s,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[S.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[S.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[S.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[S.ip_range]}]),g=gr(r),b=re(G({runtime:"php",servicesProvision:g,baked:u,swapGb:i.swapGb})),h=await this.client.listServers().catch(()=>[]),P=[],T=h.find((x)=>W(x.labels,n,s,"services"));if(!T){let{server:x,action:k}=await this.client.createServer({name:`${n}-${s}-services`,serverType:Te(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:c,location:l,userData:b,labels:N(n,s,"services"),sshKeys:d?[d]:void 0,firewalls:[{firewall:y.id}],networks:[S.id]});await this.client.waitForAction(k.id),T=await this.client.waitForServerRunning(x.id),P.push(x.id)}let w=T.id,C=T.private_net?.[0]?.ip??(await this.client.getServer(w)).private_net?.[0]?.ip,V=[...le(!0),...ue(!0),...ke(i.sshKeys),...De(r.notifications)],O=gt({versions:i.php?.versions,default:i.php?.default,extensions:i.php?.extensions,installNginx:!j(i),optimizeForProduction:i.php?.optimizeForProduction,ini:i.php?.ini}),L=re(G({runtime:"php",phpProvision:O,servicesProvision:V,baked:u,swapGb:i.swapGb})),M=h.filter((x)=>W(x.labels,n,s,"app")),D=M.map((x)=>x.id);if(M.length>t.appServers)for(let x of M.slice(t.appServers))await this.client.deleteServer(x.id).catch(()=>{}),D.splice(D.indexOf(x.id),1);for(let x=M.length;x<t.appServers;x++){let{server:k,action:_}=await this.client.createServer({name:`${n}-${s}-app-${x+1}`,serverType:a,image:c,location:l,userData:L,labels:N(n,s,"app"),sshKeys:d?[d]:void 0,firewalls:[{firewall:v.id}],networks:[S.id]});await this.client.waitForAction(_.id),D.push(k.id),P.push(k.id)}if(this.waitForBoot&&P.length>0)await Promise.all(P.map(async(x)=>{let _=(await this.client.waitForServerRunning(x)).public_net.ipv4?.ip;if(_)await this.waitForSshReady(_),await this.waitForCloudInit(_)}));let F=`${n}-${s}-lb`,R,se;if(t.loadBalancer){let k=(await this.client.listLoadBalancers().catch(()=>[])).find((_)=>_.name===F)??await this.client.createLoadBalancer({name:F,location:l,network:S.id,labels:N(n,s,"lb"),labelSelector:`ts-cloud/project=${n},ts-cloud/environment=${s},ts-cloud/role=app`,services:[{listenPort:80,destinationPort:80},{listenPort:443,destinationPort:443}]});se=k.id,R=k.public_net?.ipv4?.ip}let U=R??(await this.client.getServer(D[0]).catch(()=>{return}))?.public_net.ipv4?.ip,Z={provider:"hetzner",stackName:o,networkId:S.id,loadBalancerId:se,servicesServerId:w,servicesPrivateIp:C,publicIp:U,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await Ce(o,Z),{appPublicIp:U,loadBalancerIp:R,servicesPrivateIp:C,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async provisionBunFleet(e,t){let{config:r,environment:s}=e,n=r.project.slug,i=r.infrastructure.compute,o=E(r,s),a=Te(i.size),c=st(r),l=r.hetzner?.location||this.location,u=i.bakedImage===!0,p=r.sites||{},d=await xe(o);if(d?.lbServerId){let _=await this.tryGetServer(d.lbServerId);if(_&&_.status!=="off"){let I=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"},H=await this.findComputeTargets({slug:n,environment:s,role:"app",stackName:o});return this.refreshLbRoutes(_,p,H.map((Y)=>({privateIp:Y.privateIp,publicIp:Y.publicIp})),I,n),{appPublicIp:_.public_net.ipv4?.ip??d.publicIp,loadBalancerIp:_.public_net.ipv4?.ip??d.publicIp,servicesPrivateIp:d.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}}let m=await this.ensureSshKey(n,s,N(n,s,"app")),f=`${n}-${s}-net`,v=(await this.client.listNetworks().catch(()=>[])).find((_)=>_.name===f)??await this.client.createNetwork({name:f,labels:N(n,s,"app")}),y=this.collectUpstreamPorts(p),{firewall:g}=await this.ensureFirewall(`${n}-${s}-app-fw`,N(n,s,"app"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},...y.map((_)=>({direction:"in",protocol:"tcp",port:String(_),source_ips:[v.ip_range],description:`ts-cloud port ${_} (private, LB-only)`}))]),{firewall:b}=await this.ensureFirewall(`${n}-${s}-lb-fw`,N(n,s,"lb"),Et({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),h=await this.client.listServers().catch(()=>[]),P=[],T,w,C=!!i.servicesServer||!!i.managedServices,V=t.dedicatedServices&&C;if(V){let{firewall:_}=await this.ensureFirewall(`${n}-${s}-services-fw`,N(n,s,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[v.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[v.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[v.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[v.ip_range]}]),I=gr(r),H=re(G({runtime:"bun",servicesProvision:I,baked:u,swapGb:i.swapGb})),Y=h.find((ae)=>W(ae.labels,n,s,"services"));if(!Y){let{server:ae,action:qe}=await this.client.createServer({name:`${n}-${s}-services`,serverType:Te(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:c,location:l,userData:H,labels:N(n,s,"services"),sshKeys:m?[m]:void 0,firewalls:[{firewall:_.id}],networks:[v.id]});await this.client.waitForAction(qe.id),Y=await this.client.waitForServerRunning(ae.id),P.push(ae.id)}T=Y.id,w=Y.private_net?.[0]?.ip??(await this.client.getServer(T)).private_net?.[0]?.ip}let O=V?{...i,managedServices:void 0,backups:void 0}:i,L=_e({...r,infrastructure:{...r.infrastructure,compute:O}},{environment:s}),M=re(G({runtime:L.runtime,runtimeVersion:L.runtimeVersion,systemPackages:i.systemPackages,database:r.infrastructure?.database,servicesProvision:L.servicesProvision,baked:u,swapGb:i.swapGb})),D=h.filter((_)=>W(_.labels,n,s,"app")),F=D.map((_)=>_.id);if(D.length>t.appServers)for(let _ of D.slice(t.appServers))await this.client.deleteServer(_.id).catch(()=>{}),F.splice(F.indexOf(_.id),1);for(let _=D.length;_<t.appServers;_++){let{server:I,action:H}=await this.client.createServer({name:`${n}-${s}-app-${_+1}`,serverType:a,image:c,location:l,userData:M,labels:N(n,s,"app"),sshKeys:m?[m]:void 0,firewalls:[{firewall:g.id}],networks:[v.id]});await this.client.waitForAction(H.id),F.push(I.id),P.push(I.id)}if(this.waitForBoot&&P.length>0)await Promise.all(P.map(async(_)=>{let H=(await this.client.waitForServerRunning(_)).public_net.ipv4?.ip;if(H)await this.waitForSshReady(H),await this.waitForCloudInit(H)}));let R=[];for(let _ of F){let I=h.find((H)=>H.id===_);if(!I||!I.private_net?.[0]?.ip)I=await this.client.getServer(_).catch(()=>I);R.push({privateIp:I?.private_net?.[0]?.ip,publicIp:I?.public_net.ipv4?.ip})}let se=`${n}-${s}-lb`,U,Z;if(t.loadBalancer){let _=h.find((H)=>W(H.labels,n,s,"lb")),I=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"};if(!_){let H=te({proxy:I,config:Ne(p,R,{proxy:I,slug:n}),slug:n,bunBin:L.runtime==="node"||L.runtime==="deno"?void 0:"/usr/local/bin/bun"}),Y=re(G({runtime:"bun",rpxProvision:H,baked:!1})),ae=typeof i.loadBalancer==="object"?i.loadBalancer.size:void 0,{server:qe,action:Jt}=await this.client.createServer({name:se,serverType:Te(ae??"micro"),image:c,location:l,userData:Y,labels:N(n,s,"lb"),sshKeys:m?[m]:void 0,firewalls:[{firewall:b.id}],networks:[v.id]});if(await this.client.waitForAction(Jt.id),_=await this.client.waitForServerRunning(qe.id),this.waitForBoot){let Ye=_.public_net.ipv4?.ip;if(Ye)await this.waitForSshReady(Ye),await this.waitForCloudInit(Ye)}}else this.refreshLbRoutes(_,p,R,I,n);U=_.id,Z=_.public_net.ipv4?.ip}let x=Z??(await this.client.getServer(F[0]).catch(()=>{return}))?.public_net.ipv4?.ip,k={provider:"hetzner",stackName:o,networkId:v.id,lbServerId:U,appServerIds:F,servicesServerId:T,servicesPrivateIp:w,publicIp:x,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await Ce(o,k),{appPublicIp:x,loadBalancerIp:Z,servicesPrivateIp:w,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async destroyCompute(e){let{config:t,environment:r}=e,s=t.project.slug,n=E(t,r),i=await xe(n),o=[],a=`${s}-${r}-lb`,l=(await this.client.listLoadBalancers().catch(()=>[])).find((g)=>g.name===a);if(l)try{await this.client.deleteLoadBalancer(l.id),o.push(`load balancer ${a}`)}catch{}let u=await this.client.listServers().catch(()=>[]),p=new Set;for(let g of u)if(W(g.labels,s,r,"app")||W(g.labels,s,r,"services")||W(g.labels,s,r,"lb"))p.add(g.id);if(i?.serverId)p.add(i.serverId);if(i?.servicesServerId)p.add(i.servicesServerId);if(i?.lbServerId)p.add(i.lbServerId);for(let g of i?.appServerIds??[])p.add(g);for(let g of p)try{await this.client.deleteServer(g),o.push(`server ${g}`)}catch{}let d=await this.client.listFirewalls().catch(()=>[]);for(let g of[`${s}-${r}-app-fw`,`${s}-${r}-services-fw`,`${s}-${r}-lb-fw`]){let b=d.find((h)=>h.name===g);if(!b)continue;for(let h=0;h<12;h++)try{await this.client.deleteFirewall(b.id),o.push(`firewall ${g}`);break}catch{await this.sleep(3000)}}let m=`${s}-${r}-net`,S=(await this.client.listNetworks().catch(()=>[])).find((g)=>g.name===m);if(S)for(let g=0;g<12;g++)try{await this.client.deleteNetwork(S.id),o.push(`network ${m}`);break}catch{await this.sleep(3000)}let y=(await this.client.listSshKeys().catch(()=>[])).filter((g)=>Sr(g.labels,s,r));for(let g of y)try{await this.client.deleteSshKey(g.id),o.push(`ssh key ${g.name}`)}catch{}return await Ce(n,{provider:"hetzner",stackName:n}).catch(()=>{}),{destroyed:o}}async getComputeOutputs(e){let t=E(e.config,e.environment),r=await xe(t);if(r?.serverId){let i=await this.tryGetServer(r.serverId);if(i)return this.outputsFromState(r,i)}if(r?.lbServerId){let o=(await this.tryGetServer(r.lbServerId))?.public_net.ipv4?.ip??r.publicIp;return{...this.outputsFromState(r),appPublicIp:o,loadBalancerIp:o}}if(r?.loadBalancerId||r?.servicesPrivateIp)return this.outputsFromState(r);let n=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:E(e.config,e.environment)}))[0];return{deployStoragePath:"/var/ts-cloud/staging",appInstanceId:n?.id,appPublicIp:n?.publicIp,sshUser:this.sshUser}}async uploadRelease(e){let t=e.targets?.length?e.targets:await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:E(e.config,e.environment)});if(t.length===0)throw Error("No Hetzner compute targets found for release upload");let n=`/var/ts-cloud/staging/${`${e.remoteKey.replace(/^releases\//,"").replace(/\.tar\.gz$/,"").replace(/\//g,"-")}-${dn()}.tar.gz`}`,i=await na(e.localPath),o="/var/ts-cloud/artifacts",a=`${o}/${i}.tar.gz`;for(let c of t){if(!c.publicIp)throw Error(`Target ${c.id} has no public IP for SCP upload`);let l=["set -euo pipefail",`mkdir -p ${J(o)} /var/ts-cloud/staging`,`test -s ${J(a)}`,`cp -- ${J(a)} ${J(n)}`].join(`
|
|
271
|
+
`);try{this.sshExec(c.publicIp,l);continue}catch{}let u=`${o}/.${i}-${dn()}.tmp`;this.scpToHost(c.publicIp,e.localPath,u),this.sshExec(c.publicIp,["set -euo pipefail",`chmod 600 ${J(u)}`,`mv -f -- ${J(u)} ${J(a)}`,`cp -- ${J(a)} ${J(n)}`,`find ${J(o)} -type f -name '*.tar.gz' -mtime +7 -delete 2>/dev/null || true`].join(`
|
|
272
|
+
`))}return{artifactRef:n}}async findComputeTargets(e){let t=e.role||"app",r=(i)=>({id:String(i.id),name:i.name,publicIp:i.public_net.ipv4?.ip,publicIpv6:ce(i.public_net.ipv6?.ip),privateIp:i.private_net?.[0]?.ip,status:i.status});if(t==="app"||t==="lb"||t==="services"){let i=await xe(e.stackName??`${e.slug}-${e.environment}`),o=[...new Set(t==="app"?[i?.serverId,...i?.appServerIds??[]]:t==="lb"?[i?.lbServerId]:[i?.servicesServerId])].filter((l)=>typeof l==="number");if(this.stateOnly){if(o.length>0&&i?.publicIp)return o.map((l)=>({id:String(l),name:l===i.serverId?i.serverName:void 0,publicIp:i.publicIp,publicIpv6:i.publicIpv6,status:"running"}));if(t!=="app")return[];throw Error(`Hetzner API token required because '${e.stackName??`${e.slug}-${e.environment}`}' has no complete local compute state pin.`)}let a=await this.client.listServers();if(o.length>0){let l=[];for(let u of o){let p=a.find((d)=>d.id===u)??await this.tryGetServer(u);if(u===i?.serverId&&i.serverName&&p?.name!==i.serverName)continue;if(p&&p.status!=="off")l.push(p)}if(l.length>0)return l.map(r)}let c=a.filter((l)=>W(l.labels,e.slug,e.environment,t));if(c.length>0)return c.map(r);if(t==="app"){let l=a.filter((u)=>u.status!=="off"&&u.labels?.[`${A}/managed-by`]==="ts-cloud"&&u.labels?.[`${A}/environment`]===e.environment&&u.labels?.[`${A}/role`]==="app");if(l.length===1)return l.map(r)}return[]}if(this.stateOnly)throw Error(`Hetzner API token required to discover '${t}' compute targets.`);let n=(await this.client.listServers()).filter((i)=>W(i.labels,e.slug,e.environment,t));if(n.length>0)return n.map(r);return[]}async attachToComputeInfrastructure(e,t,r){let s=await this.client.listServers(),n=(d)=>s.filter((m)=>m.status!=="off"&&W(m.labels,e,r,d)),i=n("app");if(i.length===0)throw Error(`Cannot attach '${t.project.slug}' to '${e}': no running Hetzner app server is labeled for ${e}/${r}. Deploy the owner project first.`);let o=n("lb")[0],a=n("services")[0],c=i[0],l=o??c,u=E(t,r),p={provider:"hetzner",stackName:u,serverId:c.id,serverName:c.name,appServerIds:i.map((d)=>d.id),lbServerId:o?.id,servicesServerId:a?.id,servicesPrivateIp:a?.private_net?.[0]?.ip,publicIp:l.public_net.ipv4?.ip,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await Ce(u,p),this.outputsFromState(p)}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(`
|
|
273
|
+
`),r=[];for(let n of e.targets){if(!n.publicIp){r.push({instanceId:n.id,status:"Failed",error:"Missing public IP"});continue}try{let i=this.sshExec(n.publicIp,t);Ie(i),r.push({instanceId:n.id,status:"Success",output:i})}catch(i){r.push({instanceId:n.id,status:"Failed",error:i.message})}}let s=r.every((n)=>n.status==="Success");return{success:s,instanceCount:e.targets.length,perInstance:r,error:s?void 0:we(r,"One or more SSH deploy commands failed")}}async ensureSshKey(e,t,r){if(!ra(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 s=sa(this.sshPublicKeyPath,"utf8").trim(),n=nt(s),o=(await this.client.listSshKeys()).find((c)=>nt(c.public_key)===n);if(o)return o.id;return(await this.client.createSshKey({name:`${e}-${t}-deploy`,publicKey:s,labels:r})).id}async tryGetServer(e){try{return await this.client.getServer(e)}catch{return null}}refreshLbRoutes(e,t,r,s,n){let i=e.public_net.ipv4?.ip;if(!i){console.warn(`[ts-cloud] LB server '${e.name}' has no public IP — skipping the rpx route refresh; its routes may be stale.`);return}let o=r.filter((c)=>c.privateIp||c.publicIp);if(o.length===0){console.warn(`[ts-cloud] No routable app boxes found for LB '${e.name}' — leaving its current rpx routes untouched.`);return}let a=Ne(t,o,{proxy:s,slug:n});this.sshExec(i,$e({config:a,slug:n}).join(`
|
|
274
|
+
`))}async findExistingServer(e,t,r){let s=await this.client.listServers(),n=s.find((o)=>W(o.labels,e,t,"app")||o.name===r);if(n)return n;let i=s.filter((o)=>o.status!=="off"&&o.labels?.[`${A}/managed-by`]==="ts-cloud"&&o.labels?.[`${A}/environment`]===t&&o.labels?.[`${A}/role`]==="app");if(i.length===1){let o=i[0],a=o.labels?.[`${A}/project`]??"unknown";return console.warn(`[ts-cloud] No server named '${r}' found; adopting existing ts-cloud app server '${o.name}' (project label '${a}') for project '${e}' — `+"updating it in place instead of provisioning a new server."),o}return}async ensureFirewall(e,t,r){let n=(await this.client.listFirewalls()).find((o)=>o.name===e);if(n)return await this.client.setFirewallRules(n.id,r),{firewall:n};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,s=Date.now(),n;while(Date.now()-s<r)try{pn(`ssh ${this.sshBaseArgs(e,["-o","ConnectTimeout=5"]).map(J).join(" ")} true`,{stdio:"pipe",maxBuffer:br});return}catch(i){n=i,await this.sleep(t)}throw Error(`Timed out waiting for SSH on ${e} after ${r}ms: ${n?.message??"unknown error"}`)}async waitForCloudInit(e){let{cloudInitIntervalMs:t,cloudInitTimeoutMs:r}=this.bootWait,s=Date.now();while(Date.now()-s<r){try{let n=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(n))throw Error(`cloud-init reported an error on ${e}:
|
|
275
|
+
${n}`);if(/status:\s*(?:done|degraded)/.test(n))return}catch(n){if(n instanceof Error&&/cloud-init reported an error/.test(n.message))throw n}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:ce(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,...he.SSH_HOST_KEY_OPTS,...he.SSH_KEEPALIVE_OPTS,"-o","BatchMode=yes",...t,`${this.sshUser}@${e}`]}scpToHost(e,t,r){let s=["scp","-i",this.sshPrivateKeyPath,...he.SSH_HOST_KEY_OPTS,...he.SSH_KEEPALIVE_OPTS,"-o","BatchMode=yes",t,`${this.sshUser}@${e}:${r}`].map((i)=>`"${i.replace(/"/g,"\\\"")}"`).join(" "),n=3;for(let i=1;i<=3;i++)try{pn(s,{stdio:"pipe",maxBuffer:br});return}catch(o){if(i===3)throw Error(be(o))}}sshExec(e,t){try{return Zo("ssh",[...this.sshBaseArgs(e),fr],{encoding:"utf8",input:t,stdio:["pipe","pipe","pipe"],maxBuffer:br})}catch(r){throw Error(`${be(r)}${Je(r,t)}`)}}}class Ot{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(`
|
|
276
|
+
`);try{let r=Bun.spawn(["bash","-c",t],{stdout:"pipe",stderr:"pipe",env:process.env}),[s,n,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:s,error:n}]}}catch(r){return{success:!1,instanceCount:1,perInstance:[{instanceId:"localhost",status:"Failed",error:r?.message??String(r)}],error:r?.message??String(r)}}}}function wr(){let e=process.env.TS_CLOUD_DASHBOARD_BOX;return e!=null&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}import{createHash as va,randomUUID as Ln}from"node:crypto";import{createReadStream as ba}from"node:fs";import{isIP as wa}from"node:net";import{createHash as ia}from"node:crypto";import{appendFile as oa,mkdir as aa,readFile as ca}from"node:fs/promises";import{dirname as la}from"node:path";var mn=268435456,fn=async(e,t)=>{let r=Bun.spawn(e,{stdin:t===void 0?"ignore":Buffer.from(t),stdout:"pipe",stderr:"pipe"}),[s,n,i]=await Promise.all([r.exited,new Response(r.stdout).text(),new Response(r.stderr).text()]);return{code:s,signal:r.signalCode,stdout:n.slice(-mn),stderr:i.slice(-mn)}},gn=["-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR"],hn=["-o","ConnectTimeout=30","-o","ServerAliveInterval=15","-o","ServerAliveCountMax=4"];function yn(e){if(e.hostKey==="insecure")return[...gn];return["-o",`StrictHostKeyChecking=${e.hostKey.policy==="pin"?"yes":"accept-new"}`,"-o",`UserKnownHostsFile=${e.hostKey.knownHostsFile}`,"-o","LogLevel=ERROR"]}function Sn(e){let t=[...hn];if(e.connectTimeoutSec!==void 0)t[1]=`ConnectTimeout=${e.connectTimeoutSec}`;return t}function $r(e,t,r=[]){return["-i",e.identityFile,"-p",String(e.port??22),...yn(e),...Sn(e),"-o","BatchMode=yes",...r,`${e.user}@${t}`]}function vn(e,t,r,s){return["-i",e.identityFile,"-P",String(e.port??22),...yn(e),...Sn(e),"-o","BatchMode=yes",r,`${e.user}@${t}:${s}`]}function it(e){return`SHA256:${ia("sha256").update(Buffer.from(e,"base64")).digest("base64").replace(/=+$/,"")}`}async function bn(e,t=22,r=fn){let s=await r(["ssh-keyscan","-T","10","-p",String(t),"-t","ed25519",e]),n=s.stdout.split(`
|
|
277
|
+
`).find((i)=>i&&!i.startsWith("#"))?.trim().split(/\s+/);if(s.code!==0||!n?.[1]||!n[2])throw Error(`SSH host-key scan failed: ${s.stderr.trim()||"no key returned"}`);return{algorithm:n[1],key:n[2]}}function _r(e,t=22){return t===22?e:`[${e}]:${t}`}function wn(e,t,r){return`${_r(e,t)} ${r.algorithm} ${r.key}`}function $n(e,t,r=22){let s=_r(t,r);for(let n of e.split(`
|
|
278
|
+
`)){let i=n.trim();if(!i||i.startsWith("#")||i.startsWith("@"))continue;let[o,a,c]=i.split(/\s+/);if(!o||!a||!c)continue;if(o.split(",").includes(s))return{algorithm:a,key:c}}return null}function Tr(e=process.cwd()){return It(e,"ssh","known_hosts")}async function ua(e){try{return await ca(e,"utf8")}catch{return""}}async function pa(e,t){await aa(la(e),{recursive:!0}),await oa(e,`${t}
|
|
279
|
+
`,{mode:384})}class Dt{options;run;scan;readKnownHosts;appendKnownHosts;constructor(e,t={}){this.options=e;this.run=t.run??fn,this.scan=t.scan??bn,this.readKnownHosts=t.readKnownHosts??ua,this.appendKnownHosts=t.appendKnownHosts??pa}runnerFor(e={}){if(e.sudo!==void 0)return tt({sudo:e.sudo});return this.options.runner??tt()}async exec(e,t,r={}){let s=await this.run(["ssh",...$r(this.options,e),this.runnerFor(r)],t);if(s.code!==0){let n={status:s.code,signal:s.signal,stdout:s.stdout,stderr:s.stderr};throw Error(`${be(n)}${Je(n,t)}`)}return s.stdout}async scp(e,t,r){let s=["scp",...vn(this.options,e,t,r)],n=3;for(let i=1;i<=3;i++){let o=await this.run(s);if(o.code===0)return;if(i===3)throw Error(be({status:o.code,signal:o.signal,stdout:o.stdout,stderr:o.stderr}))}}async probe(e){return(await this.run(["ssh",...$r(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:it((await this.scan(e,t,this.run)).key),pinnedNow:!1}}catch{return{fingerprint:"",pinnedNow:!1}}let{policy:r,knownHostsFile:s}=this.options.hostKey,n=$n(await this.readKnownHosts(s),e,t);if(n)return{fingerprint:it(n.key),pinnedNow:!1};let i=await this.scan(e,t,this.run);if(r==="pin")return await this.appendKnownHosts(s,wn(e,t,i)),{fingerprint:it(i.key),pinnedNow:!0};return{fingerprint:it(i.key),pinnedNow:!1}}}import{isIP as da}from"node:net";var ye=1,Pr="/var/lib/ts-cloud";function Tn(e=ye){return`${Pr}/bootstrap.v${e}`}var Pn=1;function ma(e){return e==="aarch64"||e==="arm64"}function _n(e){let t=e.lanIp?.trim()||e.facts?.lanIp?.trim();return t&&da(t)!==0?t:void 0}function Nt(e,t,r){if(!At(e.infrastructure?.compute?.managedServices?.vitess))return;if(t==="raspberry-pi"||ma(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 Re(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function fa(){return`
|
|
254
280
|
# A Pi 5 has no battery-backed RTC and boots in 1970 until NTP answers. apt
|
|
255
281
|
# rejects Release files "from the future" and ACME rejects a skewed clock, so
|
|
256
282
|
# wait (bounded) for systemd-timesyncd before anything touches the network
|
|
@@ -266,7 +292,7 @@ if command -v timedatectl >/dev/null 2>&1; then
|
|
|
266
292
|
systemctl start systemd-time-wait-sync >/dev/null 2>&1 || true
|
|
267
293
|
fi
|
|
268
294
|
fi
|
|
269
|
-
`}function
|
|
295
|
+
`}function ga(){return`
|
|
270
296
|
# SD cards wear; a journal allowed to grow to the default 10% of the disk is
|
|
271
297
|
# the single biggest writer on an idle Pi. Bound it.
|
|
272
298
|
install -d -m 0755 /etc/systemd/journald.conf.d
|
|
@@ -277,30 +303,31 @@ MaxRetentionSec=7day
|
|
|
277
303
|
Compress=yes
|
|
278
304
|
TS_CLOUD_JOURNAL_EOF
|
|
279
305
|
systemctl restart systemd-journald
|
|
280
|
-
`}function
|
|
306
|
+
`}function ha(e){return`
|
|
281
307
|
# The deploy user uploads releases as itself (scp), while the scripts run as
|
|
282
308
|
# root through sudo. setgid group-writable directories let both write.
|
|
283
|
-
install -d -m 2775 -g "$(id -gn ${
|
|
284
|
-
`}function
|
|
309
|
+
install -d -m 2775 -g "$(id -gn ${Re(e)})" /var/ts-cloud/artifacts /var/ts-cloud/staging
|
|
310
|
+
`}function ya(e){let t=Re(e),r=`/home/${e}`;return[`chown -R ${t}:"$(id -gn ${t})" ${Re(`${r}/.ssh`)}`,`chmod 700 ${Re(`${r}/.ssh`)}`]}function xr(e){let{config:t,environment:r,profile:s,sudoUser:n}=e;Nt(t,s,e.facts?.arch);let i=t.infrastructure?.compute??{},o=t.sites??{},a=t.project.slug,c=e.lan?{...e.lan.hostname?{hostname:e.lan.hostname}:{},tls:e.lan.tls??"local-ca",..._n(e)?{ip:_n(e)}:{}}:void 0,l=i.proxy?.engine==="rpx"?ee(o,{proxy:i.proxy,slug:a,lan:c}):void 0,u=i.proxy?.engine==="rpx"&&l?te({proxy:i.proxy,config:l,slug:a,profile:s,bunBin:i.runtime==="node"||i.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,p=i.proxy?.engine==="rpx"&&l?$e({config:l,slug:a}):void 0,d=n?`/home/${n}/.ssh/authorized_keys`:void 0,m=_e(t,{environment:r,authorizedKeysPath:d}),f=n?[...m.servicesProvision??[],...ya(n)]:m.servicesProvision,S=[...new Set([...i.systemPackages??[],"psmisc","ca-certificates"])],v=i.swapGb??(s==="raspberry-pi"?Pn:void 0),y=G({runtime:m.runtime,runtimeVersion:m.runtimeVersion,systemPackages:S,database:t.infrastructure?.database,phpProvision:m.phpProvision,servicesProvision:f,rpxProvision:u,swapGb:v}).replace(/^#!\/bin\/bash\nset -euo pipefail\n/,""),g=Tn(),b=l?.localCa?` lan=${l.localCa.hosts.join(",")} tls=local-ca`:c?` lan=${c.hostname??`${a}.local`} tls=${c.tls??"local-ca"}`:"",h=`#!/bin/bash
|
|
285
311
|
set -euo pipefail
|
|
286
|
-
# ts-cloud ssh bootstrap v${ye} profile=${s}${
|
|
312
|
+
# ts-cloud ssh bootstrap v${ye} profile=${s}${b}
|
|
287
313
|
|
|
288
314
|
# Idempotence guard. This script may run again (a cloud-init rerun, a repeated
|
|
289
315
|
# adopt, a deploy): once this version has been applied, only the gateway's
|
|
290
316
|
# route fragment is refreshed, so a rerun cannot re-download the runtime or
|
|
291
317
|
# re-create swap on every boot.
|
|
292
|
-
if [ -e ${
|
|
318
|
+
if [ -e ${Re(g)} ]; then
|
|
293
319
|
echo "[ts-cloud] bootstrap v${ye} already applied; refreshing the gateway fragment only"
|
|
294
|
-
`;if(
|
|
320
|
+
`;if(p){let P=p[0]==="set -euo pipefail"?p.slice(1):p;h+=`${P.join(`
|
|
295
321
|
`)}
|
|
296
|
-
`}if(
|
|
322
|
+
`}if(h+=` exit 0
|
|
297
323
|
fi
|
|
298
|
-
`,
|
|
299
|
-
${
|
|
300
|
-
install -d -m 0755 ${
|
|
301
|
-
date -u +%Y-%m-%dT%H:%M:%SZ > ${
|
|
324
|
+
`,h+=fa(),s==="raspberry-pi")h+=ga();if(n)h+=ha(n);if(h+=`
|
|
325
|
+
${y}`,h+=`
|
|
326
|
+
install -d -m 0755 ${Re(Pr)}
|
|
327
|
+
date -u +%Y-%m-%dT%H:%M:%SZ > ${Re(g)}
|
|
302
328
|
echo "[ts-cloud] bootstrap v${ye} applied (${s}); gateway fragment at ${ne}/${a}.json"
|
|
303
|
-
`,
|
|
329
|
+
`,l?.localCa)h+=`echo "[ts-cloud] LAN certificate authority for ${l.localCa.hosts.join(", ")} at ${yt(l.localCa.dir)} (copy it to a client to trust this box)"
|
|
330
|
+
`;return h}var Se={user:"root",port:22,privateKeyPath:"~/.ssh/id_ed25519",hostKey:"pin",profile:"generic",publicIp:"auto"},xn=["pin","accept-new","insecure"],Cn=["raspberry-pi","generic"];function Ke(...e){for(let t of e){let r=process.env[t]?.trim();if(r)return r}return}function ot(...e){for(let t of e){let r=t?.trim();if(r)return r}return}function Rn(e,t){if(t?.length)return t;if(e?.ssh?.hosts?.length)return e.ssh.hosts;let r=Ke("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 En(e,t){return ot(t,e?.user,Ke("TS_CLOUD_SSH_USER"))??Se.user}function In(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:Ke("TS_CLOUD_SSH_PORT")}];for(let{source:s,value:n}of r){if(n===void 0||n==="")continue;let i=typeof n==="number"?n:Number(n);if(!Number.isInteger(i)||i<1||i>65535)throw Error(`Invalid SSH port from ${s}: ${String(n)}`);return i}return Se.port}function On(e,t){return Pt(ot(t,e?.privateKeyPath,Ke("TS_CLOUD_SSH_KEY"))??Se.privateKeyPath)}function Dn(e,t){let r=ot(t,e?.ssh?.hostKey,Ke("TS_CLOUD_SSH_HOST_KEY"))??Se.hostKey;if(!xn.includes(r))throw Error(`Invalid ssh.hostKey '${r}'. Use one of: ${xn.join(", ")}.`);return r}function An(e,t=Se.user,r){return r??e?.ssh?.sudo??t!=="root"}function Nn(e,t){let r=ot(t,e?.ssh?.profile,Ke("TS_CLOUD_SSH_PROFILE"))??Se.profile;if(!Cn.includes(r))throw Error(`Invalid ssh.profile '${r}'. Use one of: ${Cn.join(", ")}.`);return r}function kn(e,t){return ot(t,e?.ssh?.publicIp)??Se.publicIp}function Hn(e,t){return t??e?.ssh?.lan}function Cr(e,t={}){let r=Rn(e,t.hosts).map((s)=>({host:s.host,user:En(s,t.user),port:In(s,t.port),privateKeyPath:On(s,t.privateKeyPath),role:s.role??"app"}));return{hosts:r,hostKey:Dn(e,t.hostKey),sudo:An(e,r[0]?.user,t.sudo),profile:Nn(e,t.profile),publicIp:kn(e,t.publicIp),lan:Hn(e,t.lan)}}var Rr=`set -u
|
|
304
331
|
. /etc/os-release 2>/dev/null || true
|
|
305
332
|
# Strings are stripped of quotes, backslashes and newlines rather than escaped:
|
|
306
333
|
# nothing reported here legitimately contains them, and a probe that cannot
|
|
@@ -332,24 +359,24 @@ printf '"lanIp":"%s",' "$(json_str "$(hostname -I 2>/dev/null | awk '{print $1}'
|
|
|
332
359
|
printf '"tools":{"curl":%s,"tar":%s},' "$(bool command -v curl)" "$(bool command -v tar)"
|
|
333
360
|
printf '"privilege":"%s"' "$(sudo -n true >/dev/null 2>&1 && printf sudo || printf user)"
|
|
334
361
|
printf '}\\n'
|
|
335
|
-
`;function
|
|
362
|
+
`;function Er(e){let t=e.split(`
|
|
336
363
|
`).map((r)=>r.trim()).filter(Boolean).at(-1);if(!t||!t.startsWith("{"))throw Error(`Preflight returned no facts:
|
|
337
|
-
${e.trim().slice(-2000)}`);try{return JSON.parse(t)}catch(r){throw Error(`Preflight returned malformed facts: ${r.message}`)}}var
|
|
364
|
+
${e.trim().slice(-2000)}`);try{return JSON.parse(t)}catch(r){throw Error(`Preflight returned malformed facts: ${r.message}`)}}var je=1073741824;function Sa(e){return e==="aarch64"||e==="arm64"}function Ir(e,t){let r=[],s=e.arch??"";if(!Sa(s)&&!(s==="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 ${s||"an unknown architecture"}.`:`Unsupported architecture ${s||"(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 n=`${e.osId??""} ${e.osIdLike??""}`.toLowerCase();if(!/\b(?:debian|ubuntu|raspbian)\b/.test(n))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<je)r.push({code:"memory.low",severity:"error",message:`${(i/je).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*je)r.push({code:"memory.low",severity:"warning",message:`${(i/je).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*je)r.push({code:"disk.low",severity:"error",message:`${((e.diskFreeBytes??0)/je).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 Or(e){return e.some((t)=>t.severity==="error")}function Dr(e){if(e.length===0)return"No findings.";let t=Math.max(...e.map((r)=>r.code.length));return e.map((r)=>{let s=`${r.severity.padEnd(7)} ${r.code.padEnd(t)} ${r.message}`;return r.remediation?`${s}
|
|
338
365
|
${" ".repeat(t+10)}${r.remediation}`:s}).join(`
|
|
339
|
-
`)}var at="/var/ts-cloud/staging",
|
|
340
|
-
`);try{await this.exec(a.publicIp,c);continue}catch{}let l=`${
|
|
366
|
+
`)}var at="/var/ts-cloud/staging",kt="/var/ts-cloud/artifacts",Mn="TS_CLOUD_SSH_SKIP_BOOTSTRAP",$a=["size","instances","appServers","servicesServer","loadBalancer","fleet","image","bakedImage","allowSsh"];function Q(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function _a(e){let t=va("sha256");for await(let r of ba(e))t.update(r);return t.digest("hex")}function Un(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(At(e.infrastructure?.compute?.managedServices?.vitess))Nt(e,t.profile);let r=e.infrastructure?.compute??{};return $a.filter((s)=>r[s]!==void 0).map((s)=>`infrastructure.compute.${s} has no effect with the ssh provider; the host is what it is.`)}class Ht{name="ssh";usesCloudFormation=!1;settings;cwd;bootWait;transportInstance;constructor(e={}){this.settings=Cr(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 Dt({user:e.user,port:e.port,identityFile:e.privateKeyPath,hostKey:this.settings.hostKey==="insecure"?"insecure":{policy:this.settings.hostKey,knownHostsFile:Tr(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:at}}async uploadRelease(e){let t=e.targets?.length?e.targets:await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:E(e.config,e.environment)});if(t.length===0)throw Error("No ssh compute targets found for release upload");let s=`${e.remoteKey.replace(/^releases\//,"").replace(/\.tar\.gz$/,"").replace(/\//g,"-")}-${Ln()}.tar.gz`,n=`${at}/${s}`,i=await _a(e.localPath),o=`${kt}/${i}.tar.gz`;for(let a of t){if(!a.publicIp)throw Error(`Target ${a.id} has no address for SCP upload`);let c=["set -euo pipefail",`mkdir -p ${Q(kt)} ${Q(at)}`,`test -s ${Q(o)}`,`cp -- ${Q(o)} ${Q(n)}`].join(`
|
|
367
|
+
`);try{await this.exec(a.publicIp,c);continue}catch{}let l=`${kt}/.${i}-${Ln()}.tmp`;await this.transport.scp(a.publicIp,e.localPath,l),await this.exec(a.publicIp,["set -euo pipefail",`chmod 600 ${Q(l)}`,`mv -f -- ${Q(l)} ${Q(o)}`,`cp -- ${Q(o)} ${Q(n)}`,`find ${Q(kt)} -type f -name '*.tar.gz' -mtime +7 -delete 2>/dev/null || true`].join(`
|
|
341
368
|
`))}return{artifactRef:n}}async runRemoteDeploy(e){if(e.targets.length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets provided"};let t=e.commands.join(`
|
|
342
|
-
`),r=[];for(let n of e.targets){if(!n.publicIp){r.push({instanceId:n.id,status:"Failed",error:"Missing address"});continue}try{let i=await this.exec(n.publicIp,t);
|
|
343
|
-
${
|
|
344
|
-
${n}`);if(/status:\s*(?:done|degraded)/.test(n))return}catch(n){if(n instanceof Error&&/cloud-init reported an error/.test(n.message))throw n}await this.sleep(t)}throw Error(`Timed out waiting for cloud-init to finish on ${e} after ${r}ms`)}}function
|
|
345
|
-
`)||!/^(?: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(!
|
|
369
|
+
`),r=[];for(let n of e.targets){if(!n.publicIp){r.push({instanceId:n.id,status:"Failed",error:"Missing address"});continue}try{let i=await this.exec(n.publicIp,t);Ie(i),r.push({instanceId:n.id,status:"Success",output:i})}catch(i){r.push({instanceId:n.id,status:"Failed",error:i.message})}}let s=r.every((n)=>n.status==="Success");return{success:s,instanceCount:e.targets.length,perInstance:r,error:s?void 0:we(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,Rr,{sudo:!1}),r=Er(t);return{facts:r,findings:Ir(r,{user:this.host.user,profile:this.settings.profile})}}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e;for(let f of Un(t,this.settings))console.warn(`[ts-cloud] ${f}`);let s=this.host,n=E(t,r),i=await Pe(n,this.cwd),o=process.env[Mn]==="1"&&i?.provider==="ssh"&&i.host===s.host&&i.bootstrapVersion===ye,a=await this.ensureHostKey(s.host);if(a.pinnedNow)console.warn(`[ts-cloud] pinned ${s.host} host key ${a.fingerprint}`);await this.waitForSshReady(s.host);let{facts:c,findings:l}=await this.preflight(s.host);if(Or(l))throw Error(`Preflight failed for ${s.host}; refusing to bootstrap it.
|
|
370
|
+
${Dr(l)}`);for(let f of l)console.warn(`[ts-cloud] ${f.severity}: ${f.message}`);if(c.cloudInitPresent&&/running/i.test(c.cloudInitStatus??""))await this.waitForCloudInit(s.host);let u=c.lanIp?.trim()||(wa(s.host)!==0?s.host:void 0),p=i?.provider==="ssh"?i.bootstrappedAt:void 0;if(!o){let f=xr({config:t,environment:r,profile:this.settings.profile,facts:c,sudoUser:s.user!=="root"?s.user:void 0,lan:this.settings.lan,lanIp:u});Ie(await this.exec(s.host,f)),p=new Date().toISOString()}let d={provider:"ssh",stackName:n,host:s.host,sshUser:s.user,sshPort:s.port,hostKeyFingerprint:a.fingerprint||void 0,publicIp:this.settings.publicIp==="auto"?void 0:this.settings.publicIp,lanIp:c.lanIp||void 0,deployStoragePath:at,profile:this.settings.profile,bootstrapVersion:ye,bootstrappedAt:p};await Be(n,d,this.cwd);let m=await this.getComputeOutputs();if(j(t.infrastructure?.compute)&&cr(this.settings.lan)==="local-ca")m.lanCaCertPath=yt(),console.warn(`[ts-cloud] LAN certificate authority on ${s.host} at ${m.lanCaCertPath}. Fetch it with: scp ${s.user}@${s.host}:${m.lanCaCertPath} ./rpx-root-ca.crt`);return m}async destroyCompute(e){let t=E(e.config,e.environment),r=this.host;return console.warn(`[ts-cloud] forgot ${r.host} for ${t}; nothing was removed on the host (stop the systemd units and remove /var/ts-cloud and /etc/rpx by hand if you want it clean).`),await Be(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,s=Date.now();do{if(await this.transport.probe(e))return;await this.sleep(t)}while(Date.now()-s<r);throw Error(`Timed out waiting for SSH on ${e} after ${r}ms`)}async waitForCloudInit(e){let{cloudInitIntervalMs:t,cloudInitTimeoutMs:r}=this.bootWait,s=Date.now();while(Date.now()-s<r){try{let n=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(n))throw Error(`cloud-init reported an error on ${e}:
|
|
371
|
+
${n}`);if(/status:\s*(?:done|degraded)/.test(n))return}catch(n){if(n instanceof Error&&/cloud-init reported an error/.test(n.message))throw n}await this.sleep(t)}throw Error(`Timed out waiting for cloud-init to finish on ${e} after ${r}ms`)}}function Ar(e){if(wr())return new Ot;switch(e.provider??Le(e.config)){case"aws":return new _t({region:e.config.project.region});case"hetzner":return new he({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 Ht({hosts:e.config.ssh?.hosts,hostKey:e.config.ssh?.hostKey,sudo:e.config.ssh?.sudo,profile:e.config.ssh?.profile,publicIp:e.config.ssh?.publicIp,lan:e.config.ssh?.lan});default:throw Error(`Unknown cloud provider: ${e.provider??Le(e.config)}`)}}class zn{drivers=new Map;getDriver(e,t){let r=t??Le(e),s=`${r}:${e.project.slug}:${e.project.region||"default"}`,n=this.drivers.get(s);if(n)return n;let i=Ar({config:e,provider:r});return this.drivers.set(s,i),i}}var ld=new zn;var Fn="/var/lib/ts-cloud/bootstrap.sh",Bn={"raspberry-pi-os":"bootfs",ubuntu:"system-boot"},Ta=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,Pa=/^[a-z_][a-z0-9_-]{0,31}$/,xa=/^[A-Z]{2}$/;function X(e){return JSON.stringify(e)}function Ca(e){if(!Ta.test(e.hostname))throw Error(`Invalid hostname '${e.hostname}': use lowercase letters, digits and hyphens.`);if(!Pa.test(e.user))throw Error(`Invalid user '${e.user}': use a lowercase Unix user name.`);let t=e.publicKey.trim();if(!t||t.includes(`
|
|
372
|
+
`)||!/^(?: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(!xa.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 Ra(e,t){let r=[`hostname: ${X(e.hostname)}`,"manage_etc_hosts: true","users:",` - name: ${X(e.user)}`," ssh_authorized_keys:",` - ${X(e.publicKey.trim())}`,` sudo: ${X("ALL=(ALL) NOPASSWD:ALL")}`," shell: /bin/bash"," lock_passwd: true","ssh_pwauth: false"];if(e.timezone)r.push(`timezone: ${X(e.timezone)}`);if(e.locale)r.push(`locale: ${X(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(`
|
|
346
373
|
`)}
|
|
347
|
-
`}function
|
|
374
|
+
`}function Ea(e){let t=["version: 2","ethernets:"," eth0:"," match:",` name: ${X("e*")}`," dhcp4: true"," dhcp6: true"," optional: true"];if(e.wifi)t.push("wifis:"," wlan0:"," dhcp4: true"," dhcp6: true"," optional: true",` regulatory-domain: ${X(e.wifi.country)}`," access-points:",` ${X(e.wifi.ssid)}:`,` password: ${X(e.wifi.passphrase)}`);return`${t.join(`
|
|
348
375
|
`)}
|
|
349
|
-
`}function
|
|
376
|
+
`}function Ia(e){return[`instance-id: ${X(`ts-cloud-${e.hostname}`)}`,`local-hostname: ${X(e.hostname)}`].join(`
|
|
350
377
|
`)+`
|
|
351
|
-
`}function
|
|
352
|
-
`)}function
|
|
378
|
+
`}function Oa(e,t){return[`Copy user-data, network-config and meta-data onto the boot partition of the flashed card (the volume named '${Bn[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(`
|
|
379
|
+
`)}function Da(e,t,r){Ca(e);let s={scriptPath:Fn,permissions:"0700",before:Ra(e,r.os)};return{files:{"user-data":re(t,s),"network-config":Ea(e),"meta-data":Ia(e)},instructions:Oa(e,r.os)}}function Aa(e){return e.location?.name??e.datacenter?.location.name??"unknown"}function Ge(e){return typeof e==="number"&&Number.isFinite(e)?e:0}function Na(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(Ge(t.cores)<Ge(e.cores))r.push("CPU");if(Ge(t.memory)<Ge(e.memory))r.push("memory");if(Ge(t.disk)<Ge(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 Kn(e,t,r,s=!0){let[n,i]=await Promise.all([e.getServer(t),e.getServerType(r)]);if(!i)throw Error(`Hetzner server type ${r} was not found.`);let o=n.server_type,a=o.name===i.name;if(!a)Na(o,i);let c=Aa(n),l=i.locations?.find((u)=>u.name===c);return{serverId:t,serverName:n.name,location:c,currentType:o,targetType:i,capacityAvailable:l?.available!==!1,alreadyComplete:a,upgradeDisk:s}}function jn(e){if(e instanceof xt&&e.code==="resource_unavailable")return!0;if(e instanceof Ct){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 oe(e,t,r){await e?.onPhase?.(t,r)}async function Nr(e,t,r){await e.waitForAction(t.id,{pollIntervalMs:r.actionPollIntervalMs,maxWaitMs:r.actionTimeoutMs})}var Lt=async({client:e,hooks:t,actionPollIntervalMs:r,actionTimeoutMs:s,serverPollIntervalMs:n,serverTimeoutMs:i},o,a,c)=>{let l=await e.getServer(o.serverId);if(l.status!=="running"){await oe(t,c?"recovering":"powering-on",{serverId:o.serverId});let p=await e.powerOnServer(o.serverId);await Nr(e,p,{actionPollIntervalMs:r,actionTimeoutMs:s}),l=await e.waitForServerRunning(o.serverId,{pollIntervalMs:n,maxWaitMs:i})}await oe(t,"verifying",{serverId:o.serverId,recovered:c});let u=await t?.afterBoot?.(l,o.targetType,a,{recovered:c});return{server:l,verification:u}};async function ka(e){let{client:t,hooks:r}=e,s=e.upgradeDisk??!0;await oe(r,"planning",{serverId:e.serverId,targetType:e.targetType});let n=await Kn(t,e.serverId,e.targetType,s),i=await t.getServer(n.serverId);if(n.alreadyComplete){let c=await Lt(e,n,e.manifest,!1);return await oe(r,"complete",{alreadyComplete:!0}),{status:"already-complete",plan:n,verification:c.verification}}if(!n.capacityAvailable&&!e.attemptUnavailable)return await oe(r,"waiting-capacity",{location:n.location,targetType:n.targetType.name}),{status:"waiting-capacity",plan:n};let o=e.manifest;if(i.status==="off"&&!e.resumeFromOff){let c=await Lt(e,n,void 0,!0);return{status:"recovered",plan:n,server:c.server,verification:c.verification,retryable:!0,error:"Server was already off without a resumable resize checkpoint; powered it back on."}}if(i.status==="running"){await oe(r,"preflight",{serverId:n.serverId}),o=await r?.preflight?.(i,n.targetType),await oe(r,"shutting-down",{serverId:n.serverId});let c=await t.shutdownServer(n.serverId);await Nr(t,c,e),i=await t.waitForServerStatus(n.serverId,"off",{pollIntervalMs:e.serverPollIntervalMs,maxWaitMs:e.serverTimeoutMs})}try{await oe(r,"resizing",{serverId:n.serverId,from:n.currentType.name,to:n.targetType.name,upgradeDisk:s});let c=await t.changeServerType(n.serverId,n.targetType.name,s);await Nr(t,c,e)}catch(c){let l=await Lt(e,n,o,!0);return{status:"recovered",plan:n,server:l.server,manifest:o,verification:l.verification,retryable:jn(c),error:c instanceof Error?c.message:String(c)}}let a=await Lt(e,n,o,!1);if(a.verification&&!a.verification.ok)throw Error(`Resize completed but verification failed: ${(a.verification.failures??[]).join("; ")}`);return await oe(r,"complete",{serverId:n.serverId,targetType:n.targetType.name}),{status:"completed",plan:n,server:a.server,manifest:o,verification:a.verification}}var Ha=String.raw`
|
|
353
380
|
const { readdir, readFile, readlink, stat } = await import('node:fs/promises')
|
|
354
381
|
|
|
355
382
|
const text = (command) => {
|
|
@@ -441,7 +468,7 @@ console.log(JSON.stringify({
|
|
|
441
468
|
persistentData: persistentData.sort(),
|
|
442
469
|
dataCatalog: dataCatalog.sort(),
|
|
443
470
|
}))
|
|
444
|
-
`;function
|
|
471
|
+
`;function La(e){return`printf %s ${Buffer.from(e).toString("base64")} | base64 -d | bun -`}async function Ma(e){let t=await ie(e.host,La(Ha),e);return JSON.parse(t)}async function Ua(e,t){let r="";for(let s=1;s<=3;s++){let n=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,o,a]=await Promise.all([new Response(n.stdout).text(),new Response(n.stderr).text(),n.exited]),c=Number.parseInt(i.trim(),10);if(a===0&&c>0)return{domain:e,ok:c<500,status:c};if(r=o.trim()||`curl exited ${a}`,s<3)await Bun.sleep(500*s)}return{domain:e,ok:!1,error:r}}async function za(e,t){let r=[],s=0,n=Array.from({length:Math.min(4,e.length)},async()=>{for(;;){let i=s++,o=e[i];if(!o)return;r[i]=await Ua(o,t)}});return await Promise.all(n),r}async function kr(e){let t=await Ma(e),r=await za(t.routeDomains,e.routeTimeoutMs??15000);return{...t,routeProbes:r}}async function Fa(e){let t=await kr(e),r=t.routeProbes.filter((s)=>!s.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((s)=>s.domain).join(", ")}`);return await ie(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 We(e,t){let r=new Set(t);return e.filter((s)=>!r.has(s))}function Ba(e){return Math.floor((e.memory??0)*1024*1024*1024)}async function Ka(e){await ie(e.host,String.raw`set -e
|
|
445
472
|
root_source="$(findmnt -n -o SOURCE /)"
|
|
446
473
|
root_fs="$(findmnt -n -o FSTYPE /)"
|
|
447
474
|
parent="$(lsblk -n -o PKNAME "$root_source" | head -1)"
|
|
@@ -453,8 +480,8 @@ case "$root_fs" in
|
|
|
453
480
|
ext2|ext3|ext4) resize2fs "$root_source" ;;
|
|
454
481
|
xfs) xfs_growfs / ;;
|
|
455
482
|
*) echo "Unsupported root filesystem: $root_fs" >&2; exit 1 ;;
|
|
456
|
-
esac`,e)}async function
|
|
457
|
-
`)).toString("base64");await ie(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
|
|
483
|
+
esac`,e)}async function ja(e,t){let r=Buffer.from(t.join(`
|
|
484
|
+
`)).toString("base64");await ie(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 Ga(e,t,r,s={recovered:!1}){if(await mr(e.host,{...e,timeoutMs:e.sshTimeoutMs??600000}),!s.recovered)await Ka(e);if(r)await ja(e,r.runningServices);let n=await kr(e),i=[],o=r?We(r.runningServices,n.runningServices):[],a=r?We(r.releaseLinks,n.releaseLinks):[],c=r?We(r.routeFragments,n.routeFragments):[],l=r?We(r.routeIds,n.routeIds):[],u=r?.persistentData.map((h)=>h.split("=")[0])??[],p=n.persistentData.map((h)=>h.split("=")[0]),d=We(u,p),m=r?We(r.dataCatalog,n.dataCatalog):[],f=n.routeProbes.filter((h)=>!h.ok),S=s.recovered&&r?r.cpuCores:t.cores??0,v=s.recovered&&r?r.memoryBytes:Ba(t),y=n.cpuCores>=S,g=n.memoryBytes>=v*0.9,b=s.recovered||n.rootDiskBytes>=(t.disk??0)*1e9*0.95;if(n.failedUnits.length>0)i.push(`Failed services: ${n.failedUnits.join(", ")}`);if(o.length>0)i.push(`Services did not return: ${o.join(", ")}`);if(a.length>0)i.push(`Release links changed: ${a.join(", ")}`);if(c.length>0)i.push(`Route manifests changed: ${c.join(", ")}`);if(l.length>0)i.push(`Routes disappeared: ${l.join(", ")}`);if(d.length>0)i.push(`Persistent data paths disappeared: ${d.join(", ")}`);if(m.length>0)i.push(`Databases or volumes disappeared: ${m.join(", ")}`);if(f.length>0)i.push(`Unhealthy routes: ${f.map((h)=>h.domain).join(", ")}`);if(!y)i.push(`Expected at least ${S} CPU cores, found ${n.cpuCores}`);if(!g)i.push(`Expected at least ${v} bytes of RAM`);if(!b)i.push(`Expected approximately ${t.disk??0} GB root disk`);return{ok:i.length===0,checks:{cpuCores:n.cpuCores,memoryBytes:n.memoryBytes,rootDiskBytes:n.rootDiskBytes,rootFilesystemBytes:n.rootFilesystemBytes,runningServices:n.runningServices.length,releaseLinks:n.releaseLinks.length,routeFragments:n.routeFragments.length,routes:n.routeIds.length,healthyRoutes:n.routeProbes.filter((h)=>h.ok).length,persistentDataPaths:n.persistentData.length,databasesAndVolumes:n.dataCatalog.length,failedUnits:n.failedUnits.length},failures:i}}function Mt(e){return e.split("=",1)[0]??e}function Gn(e){return e.replace(/@[^.]+(?=\.service$)/,"")}function $d(e,t){let r=new Set(t.runningServices.map(Gn)),s=new Set(t.routeFragments.map(Mt)),n=new Set(t.releaseLinks.map(Mt)),i=new Set(t.routeIds),o=new Set(t.dataCatalog);return{stoppedServices:e.runningServices.filter((a)=>!r.has(Gn(a))),changedRouteFragments:e.routeFragments.filter((a)=>!s.has(Mt(a))),missingRouteIds:e.routeIds.filter((a)=>!i.has(a)),changedReleaseLinks:e.releaseLinks.filter((a)=>!n.has(Mt(a))),missingData:e.dataCatalog.filter((a)=>!o.has(a))}}function Wn(e){return e.infrastructure?.compute??{}}function Vn(e){let t=Wn(e),r=t.monitoring;return{firewallPorts:[...new Set([22,80,443,...t.firewall?.allowedPorts??[]])].filter((n)=>Number.isInteger(n)&&n>=1&&n<=65535).sort((n,i)=>n-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,journalMaxUse:"256M",journalRetention:"14day"}}function Wa(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","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 Va(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 Xn(e){let t=Wn(e),r=Vn(e),s=t.monitoring??!0,n=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"]:[],...Va(r.swapGb),...le(r.autoUpdates),...ue(s),...Wa(r),...St(n),"systemctl daemon-reload","systemctl reset-failed"]}var Xa=String.raw`
|
|
458
485
|
const text = (command) => {
|
|
459
486
|
const result = Bun.spawnSync(['bash', '-lc', command], { stdout: 'pipe', stderr: 'pipe' })
|
|
460
487
|
return result.stdout.toString().trim()
|
|
@@ -485,22 +512,22 @@ console.log(JSON.stringify({
|
|
|
485
512
|
failedUnits: lines("systemctl --failed --type=service --no-legend --plain | awk '{print $1}'"),
|
|
486
513
|
publicTcpPorts: [...new Set(publicTcpPorts)].sort((a, b) => a - b),
|
|
487
514
|
}))
|
|
488
|
-
`;function
|
|
489
|
-
`),s=`printf %s ${Buffer.from(r).toString("base64")} | base64 -d | bash`;await ie(t.host,s,t)}async function
|
|
490
|
-
`,"utf8"),await
|
|
491
|
-
`,"utf8"),async()=>{await
|
|
492
|
-
`)}function
|
|
515
|
+
`;function qa(e){return`printf %s ${Buffer.from(e).toString("base64")} | base64 -d | bun -`}async function Ya(e,t){let r=Xn(e).join(`
|
|
516
|
+
`),s=`printf %s ${Buffer.from(r).toString("base64")} | base64 -d | bash`;await ie(t.host,s,t)}async function Ja(e){let t=await ie(e.host,qa(Xa),e);return JSON.parse(t)}function Qa(e,t){let r=[],s=new Set(t.firewallPorts),n=e.firewallPorts.filter((o)=>!s.has(o)),i=t.firewallPorts.filter((o)=>!e.firewallPorts.includes(o));if(!t.firewallActive)r.push("UFW is not active");if(n.length>0)r.push(`UFW is missing ports: ${n.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 Ut,readFile as Za,rename as qn,rmdir as ec,stat as tc,unlink as rc,writeFile as Yn}from"node:fs/promises";import{join as zt}from"node:path";function Hr(e){return zt(ge(),`${e}-resize.json`)}function Jn(e){return zt(ge(),`${e}-resize.lock`)}async function sc(e){try{return JSON.parse(await Za(Hr(e),"utf8"))}catch{return null}}async function nc(e){let t=Hr(e.stackName);await Ut(ge(),{recursive:!0});let r=`${t}.${process.pid}.tmp`;await Yn(r,`${JSON.stringify(e,null,2)}
|
|
517
|
+
`,"utf8"),await qn(r,t)}async function ic(e,t=1800000){let r=Jn(e);await Ut(ge(),{recursive:!0});try{await Ut(r)}catch(s){if(Date.now()-(await tc(r)).mtimeMs<=t)throw Error(`Another resize process holds ${r}.`);await qn(r,`${r}.stale-${Date.now()}`),await Ut(r)}return await Yn(zt(r,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
|
|
518
|
+
`,"utf8"),async()=>{await rc(zt(r,"owner.json")).catch(()=>{}),await ec(r).catch(()=>{})}}function Ft(e){return Object.entries(e).map(([t,r])=>`${t}=${uc(String(r))}`).join(`
|
|
519
|
+
`)}function uc(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}var pc=new Set(["sqlite","sqlite3"]),dc=new Set([":memory:","memory"]);function mc(e){let t=e?.DB_CONNECTION?.trim().toLowerCase();return t!=null&&pc.has(t)}function fc(e){let t=e.trim().replace(/^\.\//,"");if(t===""||t.startsWith("/")||t.startsWith("~"))return;if(t.split("/").includes(".."))return;return t.replace(/\/+$/,"")}function Lr(e,t=[]){if(!mc(e))return{};let r=e?.DB_DATABASE?.trim();if(r&&dc.has(r.toLowerCase()))return{};if(!r)return{warning:"DB_CONNECTION is sqlite but DB_DATABASE names no 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, or list the file in the site's `sharedPaths`."};let s=fc(r);if(!s)return{};if(t.some((n)=>Qn(n)===s))return{};return{path:s}}function Bt(e,t=[]){let{path:r}=Lr(e,t);return r?[r]:[]}function Kr(e,t){let r=t==="bun"?"/usr/local/bin/bun":t==="deno"?"/usr/local/bin/deno":"/usr/local/bin/node",s=e.replace(/^(bun|node|deno)\s+/,"");return`${r} ${s}`}function Zn(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.
|
|
493
520
|
# An eighth of %sMB RAM. Set memoryHigh in config to override.
|
|
494
521
|
[Service]
|
|
495
522
|
MemoryAccounting=true
|
|
496
523
|
MemoryHigh=%sM
|
|
497
|
-
' "$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)"',...Hr()]}function Hr(){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 Qa(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']}function Wn(e){let{unitBase:t,unitPattern:r,port:s}=e,n=e.path&&e.path.startsWith("/")?e.path:"/",i=Math.max(10,e.intervalSeconds??60),o=Math.max(1,e.failuresBeforeRestart??3),a=`/usr/local/sbin/${t}-liveness`,l=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 > ${a} <<'TS_CLOUD_LIVENESS_EOF'`,"#!/bin/sh","set -eu",`exec 9>/run/${t}-liveness.lock`,"flock -n 9 || exit 0",l,'[ -n "$TS_CLOUD_UNIT" ] || exit 0','systemctl is-active --quiet "$TS_CLOUD_UNIT" || exit 0',`if curl -s -o /dev/null --max-time 5 "http://127.0.0.1:${s}${n}"; then`,` rm -f /run/${t}-liveness.fail`," exit 0","fi",`TS_CLOUD_FAILS=$(cat /run/${t}-liveness.fail 2>/dev/null || echo 0)`,"TS_CLOUD_FAILS=$((TS_CLOUD_FAILS + 1))",`echo "$TS_CLOUD_FAILS" > /run/${t}-liveness.fail`,`[ "$TS_CLOUD_FAILS" -ge ${o} ] || exit 0`,`logger -t ${t}-liveness "no HTTP response on 127.0.0.1:${s}${n} after $TS_CLOUD_FAILS checks; restarting $TS_CLOUD_UNIT"`,'systemctl restart "$TS_CLOUD_UNIT"',`rm -f /run/${t}-liveness.fail`,"TS_CLOUD_LIVENESS_EOF",`chmod +x ${a}`,`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=${a}`,"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`]}function Br(e){let{siteName:t,slug:r,artifactFetch:s,releaseId:n,execStart:i,envEntries:o,port:a,keepReleases:c=ct,preStartCommands:l=[],healthCheckPath:u,healthGateSeconds:d=5,liveness:p,memoryHigh:m="auto",memoryMax:g,cpuWeight:b,ioWeight:v,tasksMax:h,stopTimeout:f}=e,y=[...b!=null?[`CPUWeight=${b}`]:[],...v!=null?[`IOWeight=${v}`]:[],...h!=null?[`TasksMax=${h}`]:[],...f?[`TimeoutStopSec=${f}`]:[]],S=e.zeroDowntime??a!=null,P=e.appDir??`/var/www/${t}`,T=lt(P,n),w=`${r}-${t}`,C=`${w}.service`,W=pt(r,t,n),O=e.sharedPaths??[],L=Vn([".env",...O,...Ft(o,O)]),U=zt(o),D=l.length>0?[`cd ${T.release}`,...l]:[],F=["set -euo pipefail",...Lr(T),Mr(T),...s,...ut(T,L),...Ur(T),`tar xzf ${W} -C "$TS_CLOUD_STAGED"`,`rm -f ${W}`,`cat > ${T.shared}/.env <<'TS_CLOUD_ENV_EOF'`,U,"TS_CLOUD_ENV_EOF",`chmod 600 ${T.shared}/.env`,...zr(T),`find ${T.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' ${T.shared}/.env 2>/dev/null || true`,...Bt(T,L),...D];if(S&&a!=null){let R=`${w}@${n}.service`,se=u?u.startsWith("/")?u:`/${u}`:null,M=`{ echo "[ts-cloud] release ${n} failed its health gate — previous release keeps serving" >&2; journalctl -u ${R} -n 50 --no-pager >&2 || true; systemctl stop ${R} 2>/dev/null || true; exit 1; }`;return[...F,`cat > /etc/systemd/system/${w}@.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} release %i (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${T.releases}/%i`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...m&&m!=="auto"?[`MemoryHigh=${m}`]:[],...g?[`MemoryMax=${g}`]:[],...y,`EnvironmentFile=${T.releases}/%i/.env`,`Environment=PORT=${a}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...m==="auto"?Gn(`${w}@.service`):Hr(),...Qa(R),`TS_CLOUD_OLD_UNITS=$(systemctl list-units --plain --no-legend --type=service "${w}@*.service" 2>/dev/null | awk '{print $1}' | grep -v "^${R}$" || true)`,`if [ -f /etc/systemd/system/${C} ] && systemctl is-active --quiet ${C}; then echo "[ts-cloud] retiring pre-zero-downtime unit ${C} (one-time restart cutover)"; systemctl stop ${C}; fi`,`systemctl restart ${R}`,`TS_CLOUD_GATE_OK=1; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do sleep 1; systemctl is-active --quiet ${R} || { TS_CLOUD_GATE_OK=0; break; }; done`,`if [ "$TS_CLOUD_GATE_OK" -ne 1 ]; then echo "[ts-cloud] release ${n} could not overlap the previous release (no SO_REUSEPORT?) — retiring old instances and retrying" >&2; for TS_CLOUD_RU in \${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_RU" 2>/dev/null || true; done; systemctl restart ${R}; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do sleep 1; systemctl is-active --quiet ${R} || ${M}; done; fi`,...se?[`curl -sf -o /dev/null --max-time 10 "http://127.0.0.1:${a}${se}" || ${M}`]:[],...We(T),`systemctl enable ${R} 2>/dev/null || true`,'for TS_CLOUD_U in ${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done',`TS_CLOUD_LISTENING=0; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do if ss -ltnH "sport = :${a}" 2>/dev/null | grep -q .; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done`,`if [ "$TS_CLOUD_LISTENING" -ne 1 ]; then echo "[ts-cloud] nothing is listening on ${a} after retiring the previous release — restarting ${R} on the now-free port" >&2; systemctl restart ${R}; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do if ss -ltnH "sport = :${a}" 2>/dev/null | grep -q .; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done; fi`,`if [ "$TS_CLOUD_LISTENING" -ne 1 ]; then echo "[ts-cloud] ${R} is active but never bound ${a}" >&2; journalctl -u ${R} -n 50 --no-pager >&2 || true; exit 1; fi`,`systemctl list-unit-files --plain --no-legend "${w}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v -e "^${R}$" -e "^${w}@\\.service$" || true; } | while read -r TS_CLOUD_U; do systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done`,`if [ -f /etc/systemd/system/${C} ]; then systemctl disable ${C} 2>/dev/null || true; rm -f /etc/systemd/system/${C}; systemctl daemon-reload; fi`,...Ve(T,c),...p===!1?[]:Wn({unitBase:w,unitPattern:`${w}@*.service`,port:a,path:p?.path??u,intervalSeconds:p?.intervalSeconds,failuresBeforeRestart:p?.failuresBeforeRestart})]}return[...F,`cat > /etc/systemd/system/${C} <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${T.current}`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...m&&m!=="auto"?[`MemoryHigh=${m}`]:[],...g?[`MemoryMax=${g}`]:[],...y,`EnvironmentFile=${T.current}/.env`,...a?[`Environment=PORT=${a}`]:[],"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...m==="auto"?Gn(C):Hr(),`systemctl enable ${C}`,...We(T),`systemctl restart ${C}`,`systemctl is-active ${C}`,...Ve(T,c),...p===!1||!a?[]:Wn({unitBase:w,unitPattern:C,port:a,path:p?.path??u,intervalSeconds:p?.intervalSeconds,failuresBeforeRestart:p?.failuresBeforeRestart})]}function Kr(e){let{siteName:t,artifactFetch:r,releaseId:s,keepReleases:n=ct,preStartCommands:i=[]}=e,o=e.appDir??`/var/www/${t}`,a=lt(o,s),c=pt(e.slug,t,s),l=i.length>0?[`cd ${a.release}`,...i]:[];return["set -euo pipefail",...Lr(a),Mr(a),...r,...ut(a,[]),...Ur(a),`tar xzf ${c} -C "$TS_CLOUD_STAGED"`,...zr(a),`rm -f ${c}`,...l,...We(a),...Ve(a,n)]}function pt(e,t,r){return`/tmp/${[e,t,r].filter(Boolean).join("-")}-release.tar.gz`}function jr(e,t,r,s){return[`aws s3 cp "s3://${e}/${t}" ${s} --region ${r}`]}function Gr(e,t){return[`mv "${e}" ${t}`]}function Wr(){return['echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',"find /var/ts-cloud/staging -xdev -maxdepth 1 -type f -mmin +60 -delete 2>/dev/null || true",'find /tmp -xdev -maxdepth 1 -type f -name "*-release.tar.gz" -mmin +60 -delete 2>/dev/null || true',"find /root/.bun/install/cache -xdev -type f -mtime +7 -delete 2>/dev/null || true","find /root/.bun/install/cache -xdev -depth -type d -empty -delete 2>/dev/null || true","journalctl --vacuum-time=14d --vacuum-size=512M >/dev/null 2>&1 || true",'if command -v docker >/dev/null 2>&1; then docker image prune --all --force --filter "until=168h" >/dev/null 2>&1 || true; fi','if command -v podman >/dev/null 2>&1; then podman image prune --all --force --filter "until=168h" >/dev/null 2>&1 || true; fi',"if command -v apt-get >/dev/null 2>&1; then apt-get clean >/dev/null 2>&1 || true; fi",'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"']}import{copyFileSync as $c}from"node:fs";import{tmpdir as _c}from"node:os";import{join as Tc}from"node:path";var Za=`${A}/project`;function qn(e,t){let r=t.ownerSlug.trim(),s=t.selfSlug?.trim(),n={total:e.length,owner:[],self:[],others:new Map,unmanaged:[]};for(let i of e){let o=i.labels?.[Za]?.trim();if(!o){n.unmanaged.push(i.name);continue}if(o===r){n.owner.push(i.name);continue}if(s&&o===s){n.self.push(i.name);continue}let a=n.others.get(o);if(a)a.push(i.name);else n.others.set(o,[i.name])}return n}function Vr(e){let t=e.unmanaged.length;for(let r of e.others.values())t+=r.length;return t}function Xn(e,t){let r=Vr(e),s=[];if(s.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 s.push("Nothing outside the two projects being joined is reachable with it."),s;s.push(`${r} of them belong to neither project:`);for(let n of[...e.others.keys()].sort())s.push(` ${n}: ${[...e.others.get(n)].sort().join(", ")}`);if(e.unmanaged.length>0)s.push(` not managed by ts-cloud: ${[...e.unmanaged].sort().join(", ")}`);return s.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."),s}var ec=new Set(["laravel","php","statamic","wordpress"]);function Qn(e){if(e.framework)return e.framework;if(e.type&&ec.has(e.type))return"laravel";return"stacks"}var Yn=`eval "$(cd ${pe} && pantry env 2>/dev/null)"`,Jn="/usr/local/bin/bun",tc="storage/framework/core/buddy/src/cli.ts",rc="node_modules/@stacksjs/ts-cloud/dist/bin/stacks-scheduler.js",Zn={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:()=>`${Jn} ${rc}`,queueWorkerCommand:(e,{current:t})=>{let r=[`--queue=${e.queue||"default"}`,`--sleep=${e.sleep??3}`,`--tries=${e.tries??3}`,`--timeout=${e.timeout??60}`];return`${Jn} ${t}/${tc} queue:work ${r.join(" ")}`}},sc={id:"laravel",wrapExec:(e)=>`/bin/sh -lc '${Yn}; exec ${e}'`,schedulerMode:"cron",schedulerCommand:({current:e})=>`cd ${e} && ${Yn} && php artisan schedule:run`,queueWorkerCommand:(e,{current:t})=>{let r=`${t}/artisan`;if(e.horizon)return`php ${r} horizon`;let s=[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)s.push(`--max-jobs=${e.maxJobs}`);if(e.maxTime)s.push(`--max-time=${e.maxTime}`);return`php ${r} queue:work ${s.join(" ")}`}},nc={stacks:Zn,laravel:sc};function ei(e){return nc[e]??Zn}function ti(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ic(e){return`'${e.split("'").join("'\\''")}'`}function ri(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"unnamed"}function oc(e,t,r){return`${e}-${t}-queue-${r}`}function ac(e,t,r,s){return`${e}-${t}-daemon-${r.name?ri(r.name):ri(r.command).slice(0,32)||String(s)}`}function qr(e){let t=["[Unit]",`Description=${e.description}`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${e.workingDir}`,...Object.entries(e.environment??{}).map(([r,s])=>`Environment="${r}=${s}"`),`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(`
|
|
524
|
+
' "$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)"',...Mr()]}function Mr(){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 gc(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']}function ei(e){let{unitBase:t,unitPattern:r,port:s}=e,n=e.path&&e.path.startsWith("/")?e.path:"/",i=Math.max(10,e.intervalSeconds??60),o=Math.max(1,e.failuresBeforeRestart??3),a=`/usr/local/sbin/${t}-liveness`,l=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 > ${a} <<'TS_CLOUD_LIVENESS_EOF'`,"#!/bin/sh","set -eu",`exec 9>/run/${t}-liveness.lock`,"flock -n 9 || exit 0",l,'[ -n "$TS_CLOUD_UNIT" ] || exit 0','systemctl is-active --quiet "$TS_CLOUD_UNIT" || exit 0',`if curl -s -o /dev/null --max-time 5 "http://127.0.0.1:${s}${n}"; then`,` rm -f /run/${t}-liveness.fail`," exit 0","fi",`TS_CLOUD_FAILS=$(cat /run/${t}-liveness.fail 2>/dev/null || echo 0)`,"TS_CLOUD_FAILS=$((TS_CLOUD_FAILS + 1))",`echo "$TS_CLOUD_FAILS" > /run/${t}-liveness.fail`,`[ "$TS_CLOUD_FAILS" -ge ${o} ] || exit 0`,`logger -t ${t}-liveness "no HTTP response on 127.0.0.1:${s}${n} after $TS_CLOUD_FAILS checks; restarting $TS_CLOUD_UNIT"`,'systemctl restart "$TS_CLOUD_UNIT"',`rm -f /run/${t}-liveness.fail`,"TS_CLOUD_LIVENESS_EOF",`chmod +x ${a}`,`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=${a}`,"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`]}function jr(e){let{siteName:t,slug:r,artifactFetch:s,releaseId:n,execStart:i,envEntries:o,port:a,keepReleases:c=ct,preStartCommands:l=[],healthCheckPath:u,healthGateSeconds:p=5,liveness:d,memoryHigh:m="auto",memoryMax:f,cpuWeight:S,ioWeight:v,tasksMax:y,stopTimeout:g}=e,b=[...S!=null?[`CPUWeight=${S}`]:[],...v!=null?[`IOWeight=${v}`]:[],...y!=null?[`TasksMax=${y}`]:[],...g?[`TimeoutStopSec=${g}`]:[]],h=e.zeroDowntime??a!=null,P=e.appDir??`/var/www/${t}`,T=lt(P,n),w=`${r}-${t}`,C=`${w}.service`,V=pt(r,t,n),O=e.sharedPaths??[],L=ti([".env",...O,...Bt(o,O)]),M=Ft(o),D=l.length>0?[`cd ${T.release}`,...l]:[],F=["set -euo pipefail",...Ur(T),Fr(T),...s,...ut(T,L),...zr(T),`tar xzf ${V} -C "$TS_CLOUD_STAGED"`,`rm -f ${V}`,`cat > ${T.shared}/.env <<'TS_CLOUD_ENV_EOF'`,M,"TS_CLOUD_ENV_EOF",`chmod 600 ${T.shared}/.env`,...Br(T),`find ${T.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' ${T.shared}/.env 2>/dev/null || true`,...Kt(T,L),...D];if(h&&a!=null){let R=`${w}@${n}.service`,se=u?u.startsWith("/")?u:`/${u}`:null,U=`{ echo "[ts-cloud] release ${n} failed its health gate — previous release keeps serving" >&2; journalctl -u ${R} -n 50 --no-pager >&2 || true; systemctl stop ${R} 2>/dev/null || true; exit 1; }`;return[...F,`cat > /etc/systemd/system/${w}@.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} release %i (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${T.releases}/%i`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...m&&m!=="auto"?[`MemoryHigh=${m}`]:[],...f?[`MemoryMax=${f}`]:[],...b,`EnvironmentFile=${T.releases}/%i/.env`,`Environment=PORT=${a}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...m==="auto"?Zn(`${w}@.service`):Mr(),...gc(R),`TS_CLOUD_OLD_UNITS=$(systemctl list-units --plain --no-legend --type=service "${w}@*.service" 2>/dev/null | awk '{print $1}' | grep -v "^${R}$" || true)`,`if [ -f /etc/systemd/system/${C} ] && systemctl is-active --quiet ${C}; then echo "[ts-cloud] retiring pre-zero-downtime unit ${C} (one-time restart cutover)"; systemctl stop ${C}; fi`,`systemctl restart ${R}`,`TS_CLOUD_GATE_OK=1; for TS_CLOUD_I in $(seq 1 ${Math.max(1,p)}); do sleep 1; systemctl is-active --quiet ${R} || { TS_CLOUD_GATE_OK=0; break; }; done`,`if [ "$TS_CLOUD_GATE_OK" -ne 1 ]; then echo "[ts-cloud] release ${n} could not overlap the previous release (no SO_REUSEPORT?) — retiring old instances and retrying" >&2; for TS_CLOUD_RU in \${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_RU" 2>/dev/null || true; done; systemctl restart ${R}; for TS_CLOUD_I in $(seq 1 ${Math.max(1,p)}); do sleep 1; systemctl is-active --quiet ${R} || ${U}; done; fi`,...se?[`curl -sf -o /dev/null --max-time 10 "http://127.0.0.1:${a}${se}" || ${U}`]:[],...Ve(T),`systemctl enable ${R} 2>/dev/null || true`,'for TS_CLOUD_U in ${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done',`TS_CLOUD_LISTENING=0; for TS_CLOUD_I in $(seq 1 ${Math.max(1,p)}); do if ss -ltnH "sport = :${a}" 2>/dev/null | grep -q .; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done`,`if [ "$TS_CLOUD_LISTENING" -ne 1 ]; then echo "[ts-cloud] nothing is listening on ${a} after retiring the previous release — restarting ${R} on the now-free port" >&2; systemctl restart ${R}; for TS_CLOUD_I in $(seq 1 ${Math.max(1,p)}); do if ss -ltnH "sport = :${a}" 2>/dev/null | grep -q .; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done; fi`,`if [ "$TS_CLOUD_LISTENING" -ne 1 ]; then echo "[ts-cloud] ${R} is active but never bound ${a}" >&2; journalctl -u ${R} -n 50 --no-pager >&2 || true; exit 1; fi`,`systemctl list-unit-files --plain --no-legend "${w}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v -e "^${R}$" -e "^${w}@\\.service$" || true; } | while read -r TS_CLOUD_U; do systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done`,`if [ -f /etc/systemd/system/${C} ]; then systemctl disable ${C} 2>/dev/null || true; rm -f /etc/systemd/system/${C}; systemctl daemon-reload; fi`,...Xe(T,c),...d===!1?[]:ei({unitBase:w,unitPattern:`${w}@*.service`,port:a,path:d?.path??u,intervalSeconds:d?.intervalSeconds,failuresBeforeRestart:d?.failuresBeforeRestart})]}return[...F,`cat > /etc/systemd/system/${C} <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${T.current}`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...m&&m!=="auto"?[`MemoryHigh=${m}`]:[],...f?[`MemoryMax=${f}`]:[],...b,`EnvironmentFile=${T.current}/.env`,...a?[`Environment=PORT=${a}`]:[],"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...m==="auto"?Zn(C):Mr(),`systemctl enable ${C}`,...Ve(T),`systemctl restart ${C}`,`systemctl is-active ${C}`,...Xe(T,c),...d===!1||!a?[]:ei({unitBase:w,unitPattern:C,port:a,path:d?.path??u,intervalSeconds:d?.intervalSeconds,failuresBeforeRestart:d?.failuresBeforeRestart})]}function Gr(e){let{siteName:t,artifactFetch:r,releaseId:s,keepReleases:n=ct,preStartCommands:i=[]}=e,o=e.appDir??`/var/www/${t}`,a=lt(o,s),c=pt(e.slug,t,s),l=i.length>0?[`cd ${a.release}`,...i]:[];return["set -euo pipefail",...Ur(a),Fr(a),...r,...ut(a,[]),...zr(a),`tar xzf ${c} -C "$TS_CLOUD_STAGED"`,...Br(a),`rm -f ${c}`,...l,...Ve(a),...Xe(a,n)]}function pt(e,t,r){return`/tmp/${[e,t,r].filter(Boolean).join("-")}-release.tar.gz`}function Wr(e,t,r,s){return[`aws s3 cp "s3://${e}/${t}" ${s} --region ${r}`]}function Vr(e,t){return[`mv "${e}" ${t}`]}function Xr(){return['echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',"find /var/ts-cloud/staging -xdev -maxdepth 1 -type f -mmin +60 -delete 2>/dev/null || true",'find /tmp -xdev -maxdepth 1 -type f -name "*-release.tar.gz" -mmin +60 -delete 2>/dev/null || true',"find /root/.bun/install/cache -xdev -type f -mtime +7 -delete 2>/dev/null || true","find /root/.bun/install/cache -xdev -depth -type d -empty -delete 2>/dev/null || true","journalctl --vacuum-time=14d --vacuum-size=512M >/dev/null 2>&1 || true",'if command -v docker >/dev/null 2>&1; then docker image prune --all --force --filter "until=168h" >/dev/null 2>&1 || true; fi','if command -v podman >/dev/null 2>&1; then podman image prune --all --force --filter "until=168h" >/dev/null 2>&1 || true; fi',"if command -v apt-get >/dev/null 2>&1; then apt-get clean >/dev/null 2>&1 || true; fi",'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"']}import{copyFileSync as Uc}from"node:fs";import{tmpdir as zc}from"node:os";import{join as Fc}from"node:path";var hc=`${A}/project`;function ri(e,t){let r=t.ownerSlug.trim(),s=t.selfSlug?.trim(),n={total:e.length,owner:[],self:[],others:new Map,unmanaged:[]};for(let i of e){let o=i.labels?.[hc]?.trim();if(!o){n.unmanaged.push(i.name);continue}if(o===r){n.owner.push(i.name);continue}if(s&&o===s){n.self.push(i.name);continue}let a=n.others.get(o);if(a)a.push(i.name);else n.others.set(o,[i.name])}return n}function qr(e){let t=e.unmanaged.length;for(let r of e.others.values())t+=r.length;return t}function si(e,t){let r=qr(e),s=[];if(s.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 s.push("Nothing outside the two projects being joined is reachable with it."),s;s.push(`${r} of them belong to neither project:`);for(let n of[...e.others.keys()].sort())s.push(` ${n}: ${[...e.others.get(n)].sort().join(", ")}`);if(e.unmanaged.length>0)s.push(` not managed by ts-cloud: ${[...e.unmanaged].sort().join(", ")}`);return s.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."),s}var yc=new Set(["laravel","php","statamic","wordpress"]);function oi(e){if(e.framework)return e.framework;if(e.type&&yc.has(e.type))return"laravel";return"stacks"}var ni=`eval "$(cd ${pe} && pantry env 2>/dev/null)"`,ii="/usr/local/bin/bun",Sc="storage/framework/core/buddy/src/cli.ts",vc="node_modules/@stacksjs/ts-cloud/dist/bin/stacks-scheduler.js",ai={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:()=>`${ii} ${vc}`,queueWorkerCommand:(e,{current:t})=>{let r=[`--queue=${e.queue||"default"}`,`--sleep=${e.sleep??3}`,`--tries=${e.tries??3}`,`--timeout=${e.timeout??60}`];return`${ii} ${t}/${Sc} queue:work ${r.join(" ")}`}},bc={id:"laravel",wrapExec:(e)=>`/bin/sh -lc '${ni}; exec ${e}'`,schedulerMode:"cron",schedulerCommand:({current:e})=>`cd ${e} && ${ni} && php artisan schedule:run`,queueWorkerCommand:(e,{current:t})=>{let r=`${t}/artisan`;if(e.horizon)return`php ${r} horizon`;let s=[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)s.push(`--max-jobs=${e.maxJobs}`);if(e.maxTime)s.push(`--max-time=${e.maxTime}`);return`php ${r} queue:work ${s.join(" ")}`}},wc={stacks:ai,laravel:bc};function ci(e){return wc[e]??ai}function li(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $c(e){return`'${e.split("'").join("'\\''")}'`}function ui(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"unnamed"}function _c(e,t,r){return`${e}-${t}-queue-${r}`}function Tc(e,t,r,s){return`${e}-${t}-daemon-${r.name?ui(r.name):ui(r.command).slice(0,32)||String(s)}`}function Yr(e){let t=["[Unit]",`Description=${e.description}`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${e.workingDir}`,...Object.entries(e.environment??{}).map(([r,s])=>`Environment="${r}=${s}"`),`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(`
|
|
498
525
|
`)}
|
|
499
|
-
`}function
|
|
500
|
-
`.replace(/%/g,"\\%");c.push(`cat > ${v} <<'TS_CLOUD_CRON_EOF'`,
|
|
501
|
-
`);return[`cat > ${t} <<'TS_CLOUD_DNSCREDS_EOF'`,r,"TS_CLOUD_DNSCREDS_EOF",`chmod 600 ${t}`]}function
|
|
502
|
-
`)){let n=s.indexOf(dt);if(n===-1)continue;let[i,o]=s.slice(n+dt.length).trim().split(":");if(i)r.set(i,o)}return t.filter((s)=>r.get(s)==="missing")}function
|
|
503
|
-
`)}function
|
|
526
|
+
`}function Jr(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_UNIT_EOF'`,t.replace(/\n$/,""),"TS_CLOUD_UNIT_EOF"]}function Pc(e,t){return`/etc/cron.d/${e}-${t}-scheduler`}function Qr(e){let{slug:t,siteName:r,site:s}=e,i=`${e.appBase??`/var/www/${r}`}/current`,o=ci(oi(s)),a={current:i},c=[],l=[];(s.queues||[]).forEach((y,g)=>{let b=Math.max(1,y.processes??1);for(let h=0;h<b;h++){let P=_c(t,r,l.length);l.push(P),c.push(...Jr(P,Yr({description:`${r} queue worker ${g}.${h} (managed by ts-cloud)`,workingDir:i,execStart:o.wrapExec(o.queueWorkerCommand(y,a)),environment:o.execEnv,stopWaitSecs:y.stopWaitSecs??90})))}}),(s.daemons||[]).forEach((y,g)=>{let b=Math.max(1,y.processes??1);for(let h=0;h<b;h++){let P=`${Tc(t,r,y,g)}-${h}`;l.push(P),c.push(...Jr(P,Yr({description:`${r} daemon ${y.name||y.command} (managed by ts-cloud)`,workingDir:y.directory||i,execStart:o.wrapExec(y.command),environment:o.execEnv,restart:y.restart,user:y.user})))}});let d=s.scheduler,m=d===!0||typeof d==="object"&&d!==null,f=`${t}-${r}-scheduler`;if(m&&o.schedulerMode==="daemon")l.push(f),c.push(...Jr(f,Yr({description:`${r} scheduler (managed by ts-cloud)`,workingDir:i,execStart:o.wrapExec(o.schedulerCommand(a)),environment:o.execEnv})));let S=l.map((y)=>`${y}.service`).join(" ");c.push("systemctl daemon-reload",`TS_CLOUD_DESIRED="${S}"`,`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E '^${li(t)}-${li(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 y of l)c.push(`systemctl enable ${y}.service`,`systemctl restart ${y}.service`);let v=Pc(t,r);if(m&&o.schedulerMode==="cron"){let y=typeof d==="object"&&d!==null?d:void 0,g=`${o.schedulerCommand(a)} >> /dev/null 2>&1`;if(y?.heartbeatUrl){let h=y.heartbeatMethod||"GET",P=h==="GET"?"":`-X ${h} `;g+=` && curl -fsS -m 10 ${P}${$c(y.heartbeatUrl)} >/dev/null 2>&1`}let b=`* * * * * root ${g}
|
|
527
|
+
`.replace(/%/g,"\\%");c.push(`cat > ${v} <<'TS_CLOUD_CRON_EOF'`,b.replace(/\n$/,""),"TS_CLOUD_CRON_EOF",`chmod 644 ${v}`)}else c.push(`rm -f ${v}`);return c}function Zr(e){return!!(e.queues?.length||e.daemons?.length||e.scheduler)}function es(e){if(e.ssl?.provider)return e.ssl.provider;return e.domain?"letsencrypt":"none"}var pi={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 di(e){return`/etc/letsencrypt/ts-cloud-${e}.ini`}function xc(e){let t=e?pi[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 Cc(e){if(!e.credentials||Object.keys(e.credentials).length===0)return[];let t=di(e.provider),r=Object.entries(e.credentials).map(([s,n])=>`${s} = ${n}`).join(`
|
|
528
|
+
`);return[`cat > ${t} <<'TS_CLOUD_DNSCREDS_EOF'`,r,"TS_CLOUD_DNSCREDS_EOF",`chmod 600 ${t}`]}function Rc(e){let t=e.dns,r=e.wildcard?[`*.${e.domain}`,e.domain]:[e.domain,...e.aliases||[]].filter(Boolean),s=["certbot","--non-interactive","--agree-tos","--keep-until-expiring"];if(t){let n=pi[t.provider].plugin;if(s.push(`--${n}`),t.provider!=="route53"&&t.credentials)s.push(`--${n}-credentials ${di(t.provider)}`);if(typeof t.propagationSeconds==="number"&&t.provider!=="route53")s.push(`--${n}-propagation-seconds ${t.propagationSeconds}`);s.push("certonly")}else s.push("--nginx",`--nginx-ctl ${de}`,e.redirect===!1?"--no-redirect":"--redirect");if(e.email)s.push(`-m ${e.email}`);else s.push("--register-unsafely-without-email");for(let n of r)s.push(`-d ${n}`);return[s.join(" ")]}function ts(e){if(es(e)!=="letsencrypt"||!e.domain)return[];let t=e.ssl,r=t?.dns,s=t?.wildcard===!0;if(s&&!r)return[];return[...xc(r),...r?Cc(r):[],...Rc({domain:e.domain,aliases:e.aliases,email:t?.email,wildcard:s,dns:r})]}function mi(e){let{repository:t,releaseDir:r,commit:s}=e,n=t.branch||"main",i=t.url,o=[`rm -rf ${r}`,`mkdir -p ${r}`];if(t.strategy==="tag")if(t.tag)o.push(`git clone -q --depth 1 --branch ${q(t.tag)} ${q(i)} ${r}`),o.push(`printf '%s' ${q(t.tag)} > ${r}/.ts-cloud-tag`);else{let a=t.tagPattern||"v*";o.push(`TS_CLOUD_TAG="$(git ls-remote --tags --refs --sort=-v:refname ${q(i)} ${q(`refs/tags/${a}`)} | head -n1 | sed 's#.*refs/tags/##')"`,`test -n "$TS_CLOUD_TAG" || { echo "no tags matching" ${q(a)} "found in" ${q(i)} >&2; exit 1; }`,`git clone -q --depth 1 --branch "$TS_CLOUD_TAG" ${q(i)} ${r}`,`printf '%s' "$TS_CLOUD_TAG" > ${r}/.ts-cloud-tag`)}else if(s)o.push(`git -C ${r} init -q`,`git -C ${r} remote add origin ${q(i)}`,`git -C ${r} fetch -q --depth 1 origin ${q(s)}`,`git -C ${r} checkout -q FETCH_HEAD`);else o.push(`git clone -q --depth 1 --branch ${q(n)} ${q(i)} ${r}`);return o.push(`git -C ${r} rev-parse HEAD > ${r}/.ts-cloud-sha`),o}function q(e){return`'${e.split("'").join("'\\''")}'`}var jt="$CREATE_RELEASE",Gt="$ACTIVATE_RELEASE",yi="$RESTART_QUEUES",fi="composer install --no-interaction --prefer-dist --optimize-autoloader --no-dev",Ec=["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 Ic(e){switch(e){case"laravel":case"statamic":return[jt,fi,...Ec,Gt,yi];case"php":case"wordpress":return[jt,`${fi} || true`,Gt];case"static":case"spa":return[jt,Gt]}}function Oc(e,t){return e.replace(/^php\s+/,`${t} `).replace(/(\s)php\s+artisan\s+/g,`$1${t} artisan `)}function Dc(e,t){let r=Ft(t);return[`cat > ${e} <<'TS_CLOUD_ENV_EOF'`,r,"TS_CLOUD_ENV_EOF",`chmod 600 ${e}`]}function gi(e,t,r){return[`cat > ${e} <<'${r}'`,t.replace(/\n$/,""),r,`chmod 600 ${e}`]}function Ac(e,t){if(!t)return[];let r=[];if(t.composerAuth){let s=typeof t.composerAuth==="string"?t.composerAuth:JSON.stringify(t.composerAuth,null,2);r.push(...gi(`${e}/auth.json`,s,"TS_CLOUD_AUTHJSON_EOF"))}if(t.npmrc)r.push(...gi(`${e}/.npmrc`,t.npmrc,"TS_CLOUD_NPMRC_EOF"));return r}function Si(e){let t=e.healthCheck?.path;if(!t||!e.domain)return[];let s=`http://127.0.0.1${t.startsWith("/")?t:`/${t}`}`;return[`echo "[ts-cloud] health check ${s} (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 "${s}" 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 vi(e){let{siteName:t,site:r,releaseId:s,commit:n}=e;if(!r.repository?.url)throw Error(`Site '${t}' is a PHP/git site but has no repository.url to clone`);let i=e.appBase??`/var/www/${t}`,o="php",a=lt(i,s),c=r.sharedPaths??hi,l=[...c,...Bt(r.env,c)],u=r.keepReleases??ct,p=r.deployScript?.length?r.deployScript:Ic(r.type??"laravel"),d=["set -euo pipefail",'export HOME="${HOME:-/root}"','export COMPOSER_HOME="${COMPOSER_HOME:-/root/.composer}"',"export COMPOSER_ALLOW_SUPERUSER=1",Oe()];if(d.push(...Wt(i,{releaseId:s,commit:n,branch:r.repository.branch,keepLogs:u})),d.push(...ut(a,l)),r.env&&Object.keys(r.env).length>0)d.push(...Dc(`${a.shared}/.env`,r.env));for(let m of p){let f=m.trim();if(f===jt)d.push(...mi({repository:r.repository,releaseDir:a.release,commit:n})),d.push(...Kt(a,l)),d.push(`cd ${a.release}`),d.push(...Ac(a.release,r.credentials)),d.push(`chown -R www-data:www-data ${a.shared}/storage 2>/dev/null || true`,`[ -d ${a.release}/bootstrap/cache ] && chown -R www-data:www-data ${a.release}/bootstrap/cache 2>/dev/null || true`,`chmod -R ug+rwX ${a.shared}/storage 2>/dev/null || true`);else if(f===Gt)d.push(...Ve(a)),d.push(...Xe(a,u)),d.push(`(cd ${pe} && pantry restart php-fpm) 2>/dev/null || true`);else if(f===yi)d.push(`${o} artisan queue:restart || true`);else d.push(Oc(m,o))}return d}var Vt={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"]}},dt="ts-cloud-service:";function Nc(e){return e===!0||typeof e==="object"&&e!=null}function bi(e){if(!e)return[];return Object.keys(Vt).filter((t)=>Nc(e[t]))}function wi(e){if(e.length===0)return[];return[Oe(),"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 "${dt}$TS_CLOUD_SVC:present"; return 0; fi`," done",` if ts_cloud_port_open "$TS_CLOUD_PORT"; then echo "${dt}$TS_CLOUD_SVC:present"; return 0; fi`,` echo "${dt}$TS_CLOUD_SVC:missing"`," return 0","}",...e.filter((t)=>Vt[t]).map((t)=>`ts_cloud_probe ${t} ${Vt[t].port} ${Vt[t].binaries.join(" ")}`),"exit 0"]}function $i(e,t){if(!e)return[];let r=new Map;for(let s of e.split(`
|
|
529
|
+
`)){let n=s.indexOf(dt);if(n===-1)continue;let[i,o]=s.slice(n+dt.length).trim().split(":");if(i)r.set(i,o)}return t.filter((s)=>r.get(s)==="missing")}function _i(e,t,r){let s=r?` on ${r}`:"",n=e.map((o)=>`managedServices.${o}`).join(", "),i=e.length===1?`no ${e[0]}`:`none of ${e.join(", ")}`;return`This project declares ${n}, but '${t}' has ${i}${s}. 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 Ti="/var/lib/pantry/php-fpm/pool.d",kc=9100,Hc=400;function Xt(e){return(e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"site").slice(0,28)}function Pi(e){return`web_${Xt(e)}`}function Lc(e){let t=Xt(e),r=0;for(let s=0;s<t.length;s++)r=r*31+t.charCodeAt(s)>>>0;return kc+r%Hc}function rs(e){return`127.0.0.1:${Lc(e)}`}function Mc(e){let t=Xt(e.siteName),r=Pi(e.siteName),s=e.maxChildren??10;return[`; ts-cloud-managed pool for ${e.siteName} (site isolation)`,`[${t}]`,`user = ${r}`,`group = ${r}`,`listen = ${rs(e.siteName)}`,"pm = dynamic",`pm.max_children = ${s}`,"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(`
|
|
530
|
+
`)}function xi(e){let t=Pi(e.siteName),r=Xt(e.siteName),s=`${Ti}/${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 ${Ti}`,`cat > ${s} <<'TS_CLOUD_FPMPOOL_EOF'`,Mc(e).replace(/\n$/,""),"TS_CLOUD_FPMPOOL_EOF",`(cd ${pe} && pantry restart php-fpm) 2>/dev/null || true`]}var Yt={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};function Bc(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function Ii(e,t,r=Yt){let{config:s,environment:n,siteName:i,site:o,slug:a,sha:c,runtime:l,localTarballPath:u}=t,p=`releases/${i}/${c}.tar.gz`,d=E(s,n),m=await e.getComputeOutputs({config:s,environment:n}),f=await e.findComputeTargets({slug:a,environment:n,role:"app",stackName:d});if(f.length===0)return{success:!1,error:e.name==="aws"?`Stack '${d}' has no EC2 instances tagged Project=${a} Environment=${n} Role=app, and storage/cloud/state/${d}.json pins no live instance. For a shared box, record its instanceId there.`:`No Hetzner servers labeled ts-cloud/project=${a} ts-cloud/environment=${n} ts-cloud/role=app, and storage/cloud/state/${d}.json pins no live server. For a shared box, record its serverId there.`};let S=m.servicesPrivateIp?nn(m.servicesPrivateIp,fe(s)):Ri(fe(s)),v=Ci(vt(s,{environment:n})),y=s.infrastructure?.compute,g=j(y)?{HOST:"127.0.0.1"}:{},b=n==="production"?{APP_ENV:"production",NODE_ENV:"production"}:{},h={...S,...v,...g,...o.env||{},...b},P=Lr(h,o.sharedPaths??[]);if(P.warning)r.warn(`Site '${i}': ${P.warning}`);else if(P.path)r.info(`Site '${i}': sharing '${P.path}' so the SQLite database survives deploys.`);if(cs(o)){let Z=o.phpVersion??y?.php?.default??y?.php?.versions?.[0],x=Ee(a,i),k=Object.keys(S).length>0?{...o,env:h}:o,_=vi({siteName:i,site:k,releaseId:c,appBase:x,defaultPhpVersion:Z}),I=!j(y),Y=es(o)==="custom"&&o.ssl?.certPath&&o.ssl?.keyPath?{certPath:o.ssl.certPath,keyPath:o.ssl.keyPath}:void 0,ae=o.isolation?xi({siteName:i,appBase:x}):[],qe=I?tr({siteName:i,domain:o.domain||i,aliases:o.aliases,type:o.type,appDir:`${x}/current`,webDirectory:o.webDirectory,phpVersion:Z,fastcgiPass:o.isolation?rs(i):void 0,redirects:o.redirects,ssl:Y,auth:o.auth&&o.auth.enabled!==!1&&o.auth.password?{username:o.auth.username||"admin",password:o.auth.password,realm:o.auth.realm}:void 0,serverSnippet:er(o.nginx,y?.nginxTemplates),clientMaxBodySize:o.nginx?.clientMaxBodySize,hsts:o.ssl?.hsts,tlsProtocols:o.ssl?.tlsProtocols,security:o.security}):[],Jt=I?ts(o):[],Ye=Zr(o)?Qr({slug:a,siteName:i,site:o,phpVersion:Z,appBase:x}):[],ji=I?Si(o):[];r.step(`Deploying PHP site '${i}' to ${f.length} target(s)...`);let ve=await e.runRemoteDeploy({targets:f,commands:[...ns(x,a),..._,...ae,...qe,...Jt,...Ye,...ji],comment:`ts-cloud deploy ${a}/${i}@${c}`,tags:{Project:a,Environment:n,Role:"app"}}),hs=Ts(s.notifications,o.notifications);if(!ve.success)return await sr(hs,"deploy-failed",`❌ Deploy of ${a}/${i}@${c} failed: ${ve.error||"unknown error"}`),{success:!1,error:ve.error||"Remote PHP deploy failed",instanceCount:ve.instanceCount,perInstance:ve.perInstance};let Gi=o.domain?` → https://${o.domain}`:"";return await sr(hs,"deploy",`✅ Deployed ${a}/${i}@${c}${Gi}`),{success:!0,instanceCount:ve.instanceCount,perInstance:ve.perInstance}}if(!u)return{success:!1,error:`Site '${i}' requires a release tarball but none was provided`};let T=await e.uploadRelease({config:s,environment:n,localPath:u,remoteKey:p,targets:f}),w=pt(a,i,c),C=e.name==="aws"?Wr(m.deployBucketName,p,s.project.region||"us-east-1",w):Vr(T.artifactRef,w),V=K(o),O=Ee(a,i),L=V==="server-static"?Gr({siteName:i,slug:a,appDir:O,artifactFetch:C,releaseId:c,preStartCommands:o.preStart}):jr({siteName:i,slug:a,appDir:O,artifactFetch:C,releaseId:c,execStart:Kr(o.start,l),envEntries:h,port:o.port,preStartCommands:o.preStart,sharedPaths:o.sharedPaths,zeroDowntime:o.zeroDowntime!==!1,healthCheckPath:o.healthCheck?.path,memoryHigh:o.memoryHigh,memoryMax:o.memoryMax,cpuWeight:o.cpuWeight,ioWeight:o.ioWeight,tasksMax:o.tasksMax,stopTimeout:o.stopTimeout}),M=V==="server-static"&&!j(y)&&!!o.domain,D=M?tr({siteName:i,domain:o.domain,aliases:o.aliases,type:o.type==="spa"?"spa":"static",appDir:`${O}/current`,webDirectory:"",redirects:o.redirects,auth:o.auth&&o.auth.enabled!==!1&&o.auth.password?{username:o.auth.username||"admin",password:o.auth.password,realm:o.auth.realm}:void 0,serverSnippet:er(o.nginx,y?.nginxTemplates),clientMaxBodySize:o.nginx?.clientMaxBodySize,hsts:o.ssl?.hsts,tlsProtocols:o.ssl?.tlsProtocols,security:o.security}):[],F=M?ts(o):[],R=Zr(o)?Qr({slug:a,siteName:i,site:o,appBase:O}):[],se=[...Wt(O,{releaseId:c,commit:c,branch:o.repository?.branch??"main"}),...ns(O,a),...L,...D,...F,...R,...Xr()];r.step(`Deploying to ${f.length} target(s)...`);let U=await e.runRemoteDeploy({targets:f,commands:se,comment:`ts-cloud deploy ${a}/${i}@${c}`,tags:{Project:a,Environment:n,Role:"app"}});if(!U.success)return{success:!1,error:U.error||"Remote deploy failed",instanceCount:U.instanceCount,perInstance:U.perInstance};return{success:!0,instanceCount:U.instanceCount,perInstance:U.perInstance}}function qt(e){return`'${e.replaceAll("'","'\\''")}'`}function Kc(e,t,r=!1,s=[]){let n=`${e}-dashboard-`,i=t.map((a)=>`${e}-${a}.service`),o=r?[`export TS_CLOUD_DASHBOARD_KEEP_DOMAINS=${qt(JSON.stringify(s))}`,"rm -f /run/ts-cloud-dashboard-routes-changed",`/usr/local/bin/bun --bun -e ${qt(`
|
|
504
531
|
const { chmodSync, existsSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } = require('node:fs')
|
|
505
532
|
const { basename, join } = require('node:path')
|
|
506
533
|
const root = '/etc/rpx/sites.d'
|
|
@@ -528,15 +555,15 @@ MemoryHigh=%sM
|
|
|
528
555
|
changed = true
|
|
529
556
|
}
|
|
530
557
|
if (changed) writeFileSync('/run/ts-cloud-dashboard-routes-changed', '')
|
|
531
|
-
`)}`,"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=${qt(n)}`,`TS_CLOUD_DASHBOARD_SERVER_OWNER=${r?"1":"0"}`,`TS_CLOUD_DASHBOARD_DESIRED=${qt(` ${i.join(" ")} `)}`,"for TS_CLOUD_UNIT_FILE in /etc/systemd/system/*.service; do",' [ -e "$TS_CLOUD_UNIT_FILE" ] || continue',' TS_CLOUD_UNIT=$(basename "$TS_CLOUD_UNIT_FILE")',' case "$TS_CLOUD_UNIT" in'," *-dashboard-*.service)",' if [ "$TS_CLOUD_DASHBOARD_SERVER_OWNER" != 1 ]; then',' case "$TS_CLOUD_UNIT" in "$TS_CLOUD_DASHBOARD_PREFIX"*.service) ;; *) continue ;; esac'," fi",' case "$TS_CLOUD_DASHBOARD_DESIRED" in',' *" $TS_CLOUD_UNIT "*) ;;'," *)",' systemctl disable --now "$TS_CLOUD_UNIT" 2>/dev/null || true',' rm -f "$TS_CLOUD_UNIT_FILE"'," ;;"," esac"," ;;"," esac","done","systemctl daemon-reload","systemctl reset-failed",...o]}async function
|
|
558
|
+
`)}`,"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=${qt(n)}`,`TS_CLOUD_DASHBOARD_SERVER_OWNER=${r?"1":"0"}`,`TS_CLOUD_DASHBOARD_DESIRED=${qt(` ${i.join(" ")} `)}`,"for TS_CLOUD_UNIT_FILE in /etc/systemd/system/*.service; do",' [ -e "$TS_CLOUD_UNIT_FILE" ] || continue',' TS_CLOUD_UNIT=$(basename "$TS_CLOUD_UNIT_FILE")',' case "$TS_CLOUD_UNIT" in'," *-dashboard-*.service)",' if [ "$TS_CLOUD_DASHBOARD_SERVER_OWNER" != 1 ]; then',' case "$TS_CLOUD_UNIT" in "$TS_CLOUD_DASHBOARD_PREFIX"*.service) ;; *) continue ;; esac'," fi",' case "$TS_CLOUD_DASHBOARD_DESIRED" in',' *" $TS_CLOUD_UNIT "*) ;;'," *)",' systemctl disable --now "$TS_CLOUD_UNIT" 2>/dev/null || true',' rm -f "$TS_CLOUD_UNIT_FILE"'," ;;"," esac"," ;;"," esac","done","systemctl daemon-reload","systemctl reset-failed",...o]}async function jc(e,t,r,s){let{config:n,environment:i}=t,o=n.project.slug,a=E(n,i),c=await e.findComputeTargets({slug:o,environment:i,role:"app",stackName:a});if(c.length===0)return!0;let l=await e.runRemoteDeploy({targets:c,commands:Kc(o,r,!n.cloud?.attachTo,r.map((u)=>n.sites?.[u]?.domain).filter((u)=>typeof u==="string")),comment:`ts-cloud reconcile management dashboard ${o}`,tags:{Project:o,Environment:i,Role:"app"}});if(!l.success)return s.error(`Management dashboard reconciliation failed: ${l.error||"unknown error"}`),!1;return!0}async function Gc(e,t,r){let{config:s}=t,n=s.cloud?.attachTo;if(!n||!e.listReachableResources)return;let i;try{i=await e.listReachableResources()}catch(c){r.warn(`Could not determine this credential's reach: ${c instanceof Error?c.message:String(c)}`);return}let o=ri(i,{ownerSlug:n,selfSlug:s.project.slug}),a=qr(o)>0;for(let c of si(o,{ownerSlug:n,selfSlug:s.project.slug}))if(a)r.warn(c);else r.info(c)}async function Wc(e,t,r){let{config:s,environment:n}=t,i=s.cloud?.attachTo;if(!i)return!0;let o=bi(s.infrastructure?.compute?.managedServices);if(o.length===0)return!0;let a=s.project.slug,c=E(s,n),l=await e.findComputeTargets({slug:a,environment:n,role:"app",stackName:c});if(l.length===0)return!0;let u=await e.runRemoteDeploy({targets:l,commands:wi(o),comment:`ts-cloud preflight managed services ${a}`,tags:{Project:a,Environment:n,Role:"app"}});if(!u.success)return r.warn(`Could not check '${i}' for the declared services: ${u.error||"unknown error"}`),!0;let p=new Set;for(let d of u.perInstance)for(let m of $i(d.output,o))p.add(m);if(p.size===0)return!0;return r.error(_i([...p],i,l[0]?.publicIp)),!1}async function Vc(e,t,r){let{config:s,environment:n}=t;if(!s.cloud?.attachTo)return!0;let i=s.infrastructure?.compute,o=fe(s),a=Me(o,i?.managedServices??{});if(a.length===0)return!0;let c=s.project.slug,l=E(s,n),u=await e.findComputeTargets({slug:c,environment:n,role:"app",stackName:l});if(u.length===0)return!0;r.step(`Ensuring database '${o?.name}' + role exist on the shared box...`);let p=await e.runRemoteDeploy({targets:u,commands:a,comment:`ts-cloud ensure database ${c}/${o?.name}`,tags:{Project:c,Environment:n,Role:"app"}});if(!p.success)return r.error(`Ensuring database '${o?.name}' failed: ${p.error||"unknown error"}`),!1;return r.success(`Database '${o?.name}' is ready on ${p.instanceCount} target(s)`),!0}async function Xc(e){let{config:t,environment:r,driver:s,sha:n,runtime:i,tarballForSite:o,logger:a=Yt}=e,c=t.project.slug,l=e.cwd??process.cwd(),u=e.managementDashboard!==!1,p=ss(t);if(u)is(t,{cwd:l,logger:{info:a.info,warn:a.warn}});let d=!u||p?[]:os(t);if(u&&e.rpxConfig&&e.rpxConfig!==t&&!ss(e.rpxConfig))is(e.rpxConfig,{cwd:l,logger:{info:()=>{},warn:()=>{}}});if(u&&!await jc(s,e,os(t),a))return!1;let m=null,f=new Map;if(d.length>0)if(m=Ei(t.sites?.[d[0]],{cwd:l,slug:c,sha:n,siteName:d[0],logger:{info:a.info,warn:a.warn}}),!m){a.warn("Management dashboard: no artifact available — skipping dashboard site(s) for this deploy.");for(let b of d)if(t.sites)delete t.sites[b]}else for(let b of d){if(b===d[0]){f.set(b,m);continue}try{let h=Fc(zc(),`${c}-${b}-${n}.tar.gz`);Uc(m,h),f.set(b,h)}catch{f.set(b,m)}}let S=t.sites||{},v=Object.entries(S).filter(([b,h])=>{if(!h)return!1;let P=K(h);if(P==="bucket")return a.warn(`Site '${b}' targets a bucket — skipping (handled by the static-site path, not compute).`),!1;if(P==="redirect")return!1;if(P==="proxy")return!1;return!0});if(v.length===0)return as(e);if(await Gc(s,e,a),!await Wc(s,e,a))return!1;if(!await Vc(s,e,a))return!1;let y=(b)=>f.get(b)??o(b);for(let[b,h]of v){a.step(`Deploying site: ${b}`);let P=cs(h)?void 0:y(b),T=await Ii(s,{config:t,environment:r,siteName:b,site:h,slug:c,sha:n,runtime:i,localTarballPath:P},a);if(!T.success){if(a.error(`Deploy of '${b}' failed: ${T.error||"unknown error"}`),T.perInstance)for(let w of T.perInstance)a.error(` ${w.instanceId}: ${w.status}${w.error?` — ${w.error}`:""}`);return!1}if(a.success(`Deployed ${c}/${b}@${n} to ${T.instanceCount} target(s)`),T.perInstance)for(let w of T.perInstance)a.info(` ✓ ${w.instanceId}: ${w.status}`)}if(!await as(e))return!1;return!0}async function qc(e,t,r){let s=Es(e);if(!s||s.tls==="off")return s;let n=await Pe(t,r),i=n?.provider==="ssh"?n.lanIp:void 0;return i?{...s,ip:i}:s}async function as(e){let{config:t,environment:r,driver:s,logger:n=Yt}=e,i=e.rpxConfig??t,o=i.infrastructure?.compute?.proxy??t.infrastructure?.compute?.proxy;if(o?.engine!=="rpx")return!0;let a=i.sites||{},c=t.project.slug,l=E(t,r),u=await s.findComputeTargets({slug:c,environment:r,role:"lb",stackName:l});if(u.length>0){let y=(await s.findComputeTargets({slug:c,environment:r,role:"app",stackName:l})).map((h)=>({privateIp:h.privateIp,publicIp:h.publicIp})),g=Ne(a,y,{proxy:o,slug:c});if(g.proxies.length===0)return n.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;n.step(`Reloading the load balancer's rpx gateway with ${g.proxies.length} route(s)...`);let b=await s.runRemoteDeploy({targets:u,commands:$e({config:g,slug:c,preserveManagementDashboardRoutes:e.managementDashboard===!1}),comment:`ts-cloud rpx gateway reload ${c}`,tags:{Project:c,Environment:r,Role:"lb"}});if(!b.success)return n.error(`rpx gateway reload failed: ${b.error||"unknown error"}`),!1;return n.success(`rpx gateway reloaded on ${b.instanceCount} load balancer(s)`),!0}let p=await qc(t,l,e.cwd),d=ee(a,{proxy:o,slug:c,lan:p});if(d.proxies.length===0)return n.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;let m=await s.findComputeTargets({slug:c,environment:r,role:"app",stackName:l});if(m.length===0)return n.warn("rpx gateway: no compute targets found — skipping gateway reload."),!0;n.step(`Reloading rpx gateway with ${d.proxies.length} route(s)...`);let f=te({proxy:o,config:d,slug:c,profile:Is(t),preserveManagementDashboardRoutes:e.managementDashboard===!1}),S=await s.runRemoteDeploy({targets:m,commands:f,comment:`ts-cloud rpx gateway reload ${c}`,tags:{Project:c,Environment:r,Role:"app"}});if(!S.success)return n.error(`rpx gateway reload failed: ${S.error||"unknown error"}`),!1;return n.success(`rpx gateway reloaded on ${S.instanceCount} target(s)`),!0}async function Yc(e){let{config:t,environment:r,driver:s,logger:n=Yt}=e,i=e.rpxConfig??t,o=i.infrastructure?.compute?.proxy??t.infrastructure?.compute?.proxy;if(o?.engine!=="rpx"||!o.onDemandTls)return!0;let a=ee(i.sites||{},{proxy:o,slug:t.project.slug});if(a.proxies.length===0)return!0;let c=ur(a);if(c.length===0)return!0;let l=t.project.slug,u=E(t,r),p="lb",d=await s.findComputeTargets({slug:l,environment:r,role:p,stackName:u});if(d.length===0)p="app",d=await s.findComputeTargets({slug:l,environment:r,role:p,stackName:u});if(d.length===0)return n.warn("rpx TLS: no gateway targets found - skipping certificate issuance."),!0;n.step("Issuing rpx TLS certificates after DNS reconciliation...");let m=c.map((S)=>`test -s ${Bc(`${a.productionCerts.certsDir}/${S}.crt`)}`).join(" && "),f=await s.runRemoteDeploy({targets:d,commands:[`systemctl start ${lr(l)}`,m],comment:`ts-cloud rpx TLS issuance ${l}`,tags:{Project:l,Environment:r,Role:p}});if(!f.success)return n.error(`rpx TLS issuance failed: ${f.error||"unknown error"}`),!1;return n.success(`rpx TLS certificates reconciled on ${f.instanceCount} gateway target(s)`),!0}import{createHash as Jc}from"node:crypto";function mf(e){let t=us(e.name),r=ps(e.publicKey),s=Zc([...e.existingKeys??[],{name:t,publicKey:r}]);return Di(e.configText,s)}function ff(e){let t=us(e.name),r=(e.existingKeys??[]).filter((s)=>s.name!==t);if((e.existingKeys??[]).length===r.length)throw Error(`SSH key '${t}' does not exist in compute.sshKeys`);return Di(e.configText,r)}function ls(e=[]){return e.map((t)=>({name:t.name,publicKey:t.publicKey,type:el(t.publicKey),fingerprint:tl(t.publicKey),added:"configured"}))}function Di(e,t){let r=rl(e,"compute"),s=Qc(t),n=sl(e,r.start,r.end,"sshKeys");if(n){let c=n.propertyStart;while(c>0&&e[c-1]!==`
|
|
532
559
|
`&&/\s/.test(e[c-1]))c--;return`${e.slice(0,c)}${s}${e.slice(n.end+1)}`}let i=e.slice(0,r.end).trimEnd(),o=e.slice(r.end),a=i.endsWith(",")||i.endsWith("{")?"":",";return`${i}${a}
|
|
533
560
|
${s},
|
|
534
|
-
${o}`}function
|
|
535
|
-
${e.map((r)=>[" {",` name: '${
|
|
561
|
+
${o}`}function Qc(e){if(e.length===0)return" sshKeys: []";return` sshKeys: [
|
|
562
|
+
${e.map((r)=>[" {",` name: '${Oi(r.name)}',`,` publicKey: '${Oi(ps(r.publicKey))}',`," },"].join(`
|
|
536
563
|
`)).join(`
|
|
537
564
|
`)}
|
|
538
|
-
]`}function
|
|
539
|
-
`)a=!1;continue}if(c){if(u==="*"&&
|
|
565
|
+
]`}function Zc(e){let t=new Map;for(let r of e){let s=us(r.name);if(t.has(s))throw Error(`SSH key '${s}' already exists in compute.sshKeys`);t.set(s,{name:s,publicKey:ps(r.publicKey)})}return[...t.values()]}function us(e){let t=e.trim();if(!/^[\w@.+-]{2,80}$/.test(t))throw Error("SSH key name must be 2-80 characters and use letters, numbers, @, ., +, _, or -.");return t}function ps(e){let t=e.trim().replace(/\s+/g," "),[r,s]=t.split(" ");if(!/^(?:ssh-(?:ed25519|rsa)|ecdsa-sha2-nistp(?:256|384|521))$/.test(r??"")||!s)throw Error("Public key must be an OpenSSH public key, e.g. ssh-ed25519 AAAA... name@host.");return t}function el(e){return e.trim().split(/\s+/)[0]||"ssh"}function tl(e){let t=e.trim().split(/\s+/)[1];if(!t)return"-";try{return`SHA256:${Jc("sha256").update(Buffer.from(t,"base64")).digest("base64").replace(/=+$/,"")}`}catch{return"-"}}function Oi(e){return e.replace(/\\/g,"\\\\").replaceAll(String.fromCharCode(39),"\\'")}function rl(e,t){let r=new RegExp(`\\b${t}\\s*:\\s*{`,"g").exec(e);if(!r)throw Error(`Could not find ${t}: { ... } in cloud config.`);let s=e.indexOf("{",r.index);return{propertyStart:r.index,start:s,end:Ai(e,s,"{","}")}}function sl(e,t,r,s){let n=e.slice(t+1,r),i=new RegExp(`\\b${s}\\s*:\\s*\\[`,"g").exec(n);if(!i)return null;let o=t+1+i.index,a=e.indexOf("[",o);return{propertyStart:o,start:a,end:Ai(e,a,"[","]")}}function Ai(e,t,r,s){let n=0,i,o=!1,a=!1,c=!1;for(let l=t;l<e.length;l++){let u=e[l],p=e[l+1];if(a){if(u===`
|
|
566
|
+
`)a=!1;continue}if(c){if(u==="*"&&p==="/")c=!1,l++;continue}if(i){if(o){o=!1;continue}if(u==="\\"){o=!0;continue}if(u===i)i=void 0;continue}if(u==="/"&&p==="/"){a=!0,l++;continue}if(u==="/"&&p==="*"){c=!0,l++;continue}if(u==='"'||u==="'"||u==="`"){i=u;continue}if(u===r)n++;if(u===s){if(n--,n===0)return l}}throw Error(`Could not find matching ${s} in cloud config.`)}var ol=["rpx-gateway","nginx","php8.3-fpm","php8.2-fpm","mysql","mariadb","postgresql","redis","redis-server","meilisearch"],z="-";function al(e){let t=String.raw`
|
|
540
567
|
import { X509Certificate } from 'node:crypto'
|
|
541
568
|
import { existsSync, readdirSync, readFileSync, readlinkSync, statSync } from 'node:fs'
|
|
542
569
|
import { basename, join } from 'node:path'
|
|
@@ -682,7 +709,7 @@ if (runningUnits.length > 0) {
|
|
|
682
709
|
].join('='))
|
|
683
710
|
}
|
|
684
711
|
}
|
|
685
|
-
`;return`echo '${Buffer.from(t).toString("base64")}' | base64 -d | bun -`}function
|
|
712
|
+
`;return`echo '${Buffer.from(t).toString("base64")}' | base64 -d | bun -`}function cl(e={}){let t=["set +e",'echo "CPUS=$(nproc 2>/dev/null || echo 1)"',`read TS_TOTAL_1 TS_IDLE_1 <<EOF
|
|
686
713
|
$(awk '/^cpu /{idle=$5+$6; total=0; for(i=2;i<=NF;i++) total+=$i; print total, idle; exit}' /proc/stat 2>/dev/null)
|
|
687
714
|
EOF`,"sleep 0.2",`read TS_TOTAL_2 TS_IDLE_2 <<EOF
|
|
688
715
|
$(awk '/^cpu /{idle=$5+$6; total=0; for(i=2;i<=NF;i++) total+=$i; print total, idle; exit}' /proc/stat 2>/dev/null)
|
|
@@ -690,9 +717,9 @@ EOF`,`echo "CPUUSED=$(awk -v t1="$TS_TOTAL_1" -v i1="$TS_IDLE_1" -v t2="$TS_TOTA
|
|
|
690
717
|
$(free -m 2>/dev/null | awk '/^Mem:/{total=$2; used=$3; available=$7; cache=$6} /^Swap:/{print total, used, available, cache, $2, $3}')
|
|
691
718
|
EOF`,'echo "MEMTOTAL=${MEMTOTAL:-0}"','echo "MEMUSED=${MEMUSED:-0}"','echo "MEMAVAILABLE=${MEMAVAILABLE:-0}"','echo "MEMCACHE=${MEMCACHE:-0}"','echo "SWAPTOTAL=${SWAPTOTAL:-0}"','echo "SWAPUSED=${SWAPUSED:-0}"',`read DISKTOTG DISKUSEDG DISKPCT <<EOF
|
|
692
719
|
$(df -BG -P / 2>/dev/null | awk 'NR==2{gsub("G","",$2); gsub("G","",$3); gsub("%","",$5); print $2, $3, $5}')
|
|
693
|
-
EOF`,'echo "DISKPCT=${DISKPCT:-0}"','echo "DISKUSEDG=${DISKUSEDG:-0}"','echo "DISKTOTG=${DISKTOTG:-0}"',`echo "INODEPCT=$(df -Pi / 2>/dev/null | awk 'NR==2{gsub("%","",$5);print $5}')"`,`echo "NETRX=$(awk -F'[: ]+' 'NR>2 && $2!="lo"{sum+=$3} END{print sum+0}' /proc/net/dev 2>/dev/null)"`,`echo "NETTX=$(awk -F'[: ]+' 'NR>2 && $2!="lo"{sum+=$11} END{print sum+0}' /proc/net/dev 2>/dev/null)"`,". /var/lib/ts-cloud/bandwidth-state 2>/dev/null || true",'echo "NETRXRATE=${RX_RATE:-0}"','echo "NETTXRATE=${TX_RATE:-0}"','echo "NETRXTODAY=${DAY_RX:-0}"','echo "NETTXTODAY=${DAY_TX:-0}"','echo "NETRXMONTH=${MONTH_RX:-0}"','echo "NETTXMONTH=${MONTH_TX:-0}"','echo "NETMONTHKEY=${MONTH_KEY:-}"',`echo "PROCESSES=$(ps -e --no-headers 2>/dev/null | awk 'END{print NR+0}')"`,`echo "UPTIME=$(uptime -p 2>/dev/null | sed 's/^up //' || echo unknown)"`,`echo "UPTIME_SECONDS=$(cut -d' ' -f1 /proc/uptime 2>/dev/null || echo 0)"`,'echo "OS=$(. /etc/os-release 2>/dev/null; echo "$PRETTY_NAME")"'];if(e.includeServices!==!1)t.push(`for s in ${
|
|
694
|
-
`)){let s=r.trim();if(s.startsWith("DISCOVERED_SITE="))try{let n=JSON.parse(Buffer.from(s.slice(16),"base64").toString("utf8"));if(n?.domain&&n?.route)t.discoveredSites.push(n)}catch{}else if(s.startsWith("SVC=")){let[,n,i,o,a,c]=/^SVC=([^=]+)=([^=]+)(?:=([^=]*)(?:=([^=]*)(?:=(.*))?)?)?$/.exec(s)??[];if(n)t.services.push({name:n,status:i,memBytes:Number(o||0),enabled:a||z,since:c||z})}else{let n=s.indexOf("=");if(n>0)t[s.slice(0,n)]=s.slice(n+1)}}return t}function
|
|
695
|
-
`)){let s=r.trim();if(!s.startsWith("LOG="))continue;let n=s.indexOf("\t");if(n<0)continue;let i=s.slice(4,n),o=s.slice(n+1),a=/^(\d{4}-\d{2}-\d{2}T[^\s]+)\s+(\S+)\s+(.*)$/.exec(o),c=a?.[1]??"",l=a?.[2]??"",u=(a?.[3]??o).trim();if(!u)continue;t.push({source:i,timestamp:c,when:c?
|
|
696
|
-
`)){let c=a.trim();if(c.startsWith("PORT=")){let[l="",u="",
|
|
697
|
-
`)){let n=s.trim();if(!n.startsWith("DEPLOY="))continue;let i=n.split("\t"),o=i[0]?.replace(/^DEPLOY=/,"")??"",[a,c,l,u,
|
|
698
|
-
export{mt as $d,
|
|
720
|
+
EOF`,'echo "DISKPCT=${DISKPCT:-0}"','echo "DISKUSEDG=${DISKUSEDG:-0}"','echo "DISKTOTG=${DISKTOTG:-0}"',`echo "INODEPCT=$(df -Pi / 2>/dev/null | awk 'NR==2{gsub("%","",$5);print $5}')"`,`echo "NETRX=$(awk -F'[: ]+' 'NR>2 && $2!="lo"{sum+=$3} END{print sum+0}' /proc/net/dev 2>/dev/null)"`,`echo "NETTX=$(awk -F'[: ]+' 'NR>2 && $2!="lo"{sum+=$11} END{print sum+0}' /proc/net/dev 2>/dev/null)"`,". /var/lib/ts-cloud/bandwidth-state 2>/dev/null || true",'echo "NETRXRATE=${RX_RATE:-0}"','echo "NETTXRATE=${TX_RATE:-0}"','echo "NETRXTODAY=${DAY_RX:-0}"','echo "NETTXTODAY=${DAY_TX:-0}"','echo "NETRXMONTH=${MONTH_RX:-0}"','echo "NETTXMONTH=${MONTH_TX:-0}"','echo "NETMONTHKEY=${MONTH_KEY:-}"',`echo "PROCESSES=$(ps -e --no-headers 2>/dev/null | awk 'END{print NR+0}')"`,`echo "UPTIME=$(uptime -p 2>/dev/null | sed 's/^up //' || echo unknown)"`,`echo "UPTIME_SECONDS=$(cut -d' ' -f1 /proc/uptime 2>/dev/null || echo 0)"`,'echo "OS=$(. /etc/os-release 2>/dev/null; echo "$PRETTY_NAME")"'];if(e.includeServices!==!1)t.push(`for s in ${ol.join(" ")}; do st=$(systemctl is-active "$s" 2>/dev/null); if [ -n "$st" ] && [ "$st" != "inactive" ] && [ "$st" != "unknown" ]; then mem=$(systemctl show "$s" -p MemoryCurrent --value 2>/dev/null); en=$(systemctl is-enabled "$s" 2>/dev/null); since=$(systemctl show "$s" -p ActiveEnterTimestamp --value 2>/dev/null); echo "SVC=$s=$st=$mem=$en=$since"; fi; done`);if(e.includeSites!==!1)t.push(al(e.projectFilter));return t.push("true"),t}function ll(e){let t={services:[],discoveredSites:[]};for(let r of e.split(`
|
|
721
|
+
`)){let s=r.trim();if(s.startsWith("DISCOVERED_SITE="))try{let n=JSON.parse(Buffer.from(s.slice(16),"base64").toString("utf8"));if(n?.domain&&n?.route)t.discoveredSites.push(n)}catch{}else if(s.startsWith("SVC=")){let[,n,i,o,a,c]=/^SVC=([^=]+)=([^=]+)(?:=([^=]*)(?:=([^=]*)(?:=(.*))?)?)?$/.exec(s)??[];if(n)t.services.push({name:n,status:i,memBytes:Number(o||0),enabled:a||z,since:c||z})}else{let n=s.indexOf("=");if(n>0)t[s.slice(0,n)]=s.slice(n+1)}}return t}function ki(e){let t=e.infrastructure?.compute,r=[];if(t?.webServer==="rpx"||t?.proxy?.engine==="rpx")r.push({name:"rpx-gateway",status:"configured"});else if(t?.webServer==="nginx"||t?.webServer==null)r.push({name:"ts-cloud-nginx",status:"configured"});let s=t?.php?.versions??(t?.runtime==="php"?["8.3"]:[]);for(let o of s)r.push({name:`php${o}-fpm`,status:"configured"});let n=t?.managedServices??{},i=[["mysql","mysql"],["mariadb","mariadb"],["postgres","postgresql"],["redis","redis"],["memcached","memcached"],["meilisearch","meilisearch"]];for(let[o,a]of i)if(n[o])r.push({name:a,status:"configured"});return r}function ul(e){let t=e.infrastructure?.compute?.backups,r=!!t?.enabled,s=t?.schedule??"0 2 * * *";return{enabled:r,schedule:s,destination:r?t?.bucket??"local":"off",retention:r?t?.retentionCount??5:0,last:r?"pending first run":"not configured",size:r?z:"0 MB"}}function Hi(e){return e.infrastructure?.compute?.provider??e.cloud?.provider??e.provider??"aws"}function pl(e){if(Hi(e)==="hetzner")return hr(e);return e.project.region??"us-east-1"}function dl(e){let t=e.infrastructure?.compute?.monitoring,r=Number(typeof t==="object"?t?.alerts?.bandwidthTb??0:0);return Number.isFinite(r)&&r>0?Math.round(r*1000000000000):0}function ml(e,t){let r=Fe(E(e,t));if(!nl(r))return null;try{return JSON.parse(il(r,"utf8"))}catch{return null}}function fl(e){let t=e.sites??{},r=[];for(let[s,n]of Object.entries(t)){let i=n.queues??n.workers;if(Array.isArray(i)){for(let o of i)if(typeof o==="string")r.push({name:`${s}:${o}`,site:s,processes:1,status:"configured"});else if(o?.name)r.push({name:`${s}:${o.name}`,site:s,processes:o.processes??1,status:"configured"})}}return r}function Li(e){if(!e||e==="")return"/";return e.startsWith("/")?e:`/${e}`}function gl(e){let t=Li(e.path);if(!e.domain)return{route:"internal"};return{route:t==="/"?e.domain:`${e.domain}${t}`,href:`https://${e.domain}${t==="/"?"":t}`}}function Ni(e,t){let r=K(t);if(r==="redirect")return"redirect";if(r==="proxy")return"proxy";let s=String(t.build??"").toLowerCase(),n=String(t.start??"").toLowerCase();if(e==="main"||n.includes("buddy/src/cli.ts serve"))return"stacks";if(e==="api"||n.includes("/serve/api"))return"api";if(s.includes("buildblog"))return"bunpress blog";if(s.includes("bunpress"))return"bunpress";if(s.includes("site:build")||s.includes("stx"))return"stx static";if(r==="server-static")return t.spa?"spa":"static";if(r==="server-app")return"app";if(r==="server-php")return t.type??"php";return"bucket"}function hl(e){let t=K(e);if(t==="redirect"||t==="proxy")return"—";let r=`${e.start??""} ${e.build??""}`.toLowerCase();if(t==="server-static")return r.includes("bunpress")||r.includes("bun ")||r.includes("bunx ")?"static/bun":"static";if(t==="server-app")return r.includes("bun")?"bun":"node";if(t==="server-php")return`php ${e.php??e.phpVersion??"8.3"}`;return"static"}function yl(e){let t=K(e);if(t==="redirect")return"redirect";if(t==="proxy")return"proxy";if(t==="server-app")return"service";if(t==="server-static")return"server static";if(t==="server-php")return"php release";return"bucket"}function Sl(e){let t=new Map;return Object.entries(e.sites??{}).map(([r,s])=>{let n=Li(s.path),{route:i,href:o}=gl(s),a=s.domain?`${s.domain}${n}`:"",c=a?t.get(a):void 0;if(a&&!c)t.set(a,r);return{name:r,route:i,href:o,domain:s.domain??"internal",path:n,kind:Ni(r,s),type:Ni(r,s),runtime:hl(s),deploy:yl(s),tls:s.domain?s.ssl===!1?"http":"https":"loopback",ssl:s.domain?s.ssl!==!1:!1,status:c?"shadowed":"live",shadowedBy:c,lastDeploy:z}})}function vl(e,t,r){let s=new Map(e.map((n)=>[String(n.route),{...n,project:r,managedBy:"owner"}]));for(let n of t){let i=s.get(n.route),o=i?.name??`${n.project}:${n.name}`;s.set(n.route,{...i,...n,name:o,kind:i?.kind??n.kind,type:i?.type??n.kind,runtime:i?.runtime??n.runtime,deploy:i?.deploy??n.deploy,root:i?.root??n.root,branch:i?.branch??n.branch,managedBy:n.project===r?"owner":"attached"})}return[...s.values()].sort((n,i)=>{if(n.managedBy!==i.managedBy)return n.managedBy==="owner"?-1:1;return String(n.route).localeCompare(String(i.route))})}function ms(e){return`'${e.replaceAll("'","'\\''")}'`}function Mi(e){return e.replace(/[\\&/]/g,"\\$&")}function bl(e,t){if(e.length===0)return["true"];return["set +e",...e.map((r)=>{let s=ms(`${Ee(t,r)}/.ts-cloud/deploy-history.log`),n=Mi(r);return`TS_CLOUD_HISTORY=${s}; { [ -f "$TS_CLOUD_HISTORY" ] && tail -n 24 "$TS_CLOUD_HISTORY" | sed "s/^/DEPLOY=${n}\\t/"; } || true`}),"true"]}function Ui(e){return[...new Set(Object.values(e.sites??{}).map((t)=>t.domain).filter((t)=>typeof t==="string"&&t.length>0))]}function wl(e){return["set +e",'if command -v ss >/dev/null 2>&1; then ss -H -lntup 2>/dev/null | while read -r proto _state _recv _send local _peer rest; do [ -n "$proto" ] && [ -n "$local" ] && printf "PORT=%s\\t%s\\t%s\\n" "$proto" "$local" "$rest"; done; fi','if command -v ufw >/dev/null 2>&1; then ufw status numbered 2>/dev/null | sed "s/^/FIREWALL=/"; else echo "FIREWALL=ufw unavailable"; fi','journalctl _COMM=sshd --no-pager -n 30 -o short-iso 2>/dev/null | sed "s/^/AUTH=/" || true',...Ui(e).map((r)=>`TS_CLOUD_DOMAIN=${ms(r)}; TS_CLOUD_EXPIRY=$(echo | timeout 8 openssl s_client -servername "$TS_CLOUD_DOMAIN" -connect "$TS_CLOUD_DOMAIN:443" 2>/dev/null | openssl x509 -noout -enddate 2>/dev/null | cut -d= -f2-); [ -n "$TS_CLOUD_EXPIRY" ] && printf "CERT=%s\\t%s\\n" "$TS_CLOUD_DOMAIN" "$TS_CLOUD_EXPIRY" || printf "CERT=%s\\tunavailable\\n" "$TS_CLOUD_DOMAIN"`),"true"]}function $l(e){let t=new Map,r=(i,o)=>{if(i&&o&&!t.has(o))t.set(o,{pattern:i,label:o})},s=e.infrastructure?.compute,n=e.project.slug;if(s?.webServer==="rpx"||s?.proxy?.engine==="rpx")r("rpx-gateway","rpx-gateway");else r("nginx","nginx");for(let i of ki(e))r(i.name,i.name);for(let[i,o]of Object.entries(e.sites??{})){if(K(o)!=="server-app")continue;if(r(`${n}-${i}`,`${n}-${i}`),Array.isArray(o.queues??o.workers)&&(o.queues??o.workers).length)r(`${n}-${i}-queue-*`,`${n}-${i}-queues`);if(Array.isArray(o.daemons)&&o.daemons.length)r(`${n}-${i}-daemon-*`,`${n}-${i}-daemons`)}return[...t.values()]}function _l(e){let t=$l(e);if(t.length===0)return["true"];return["set +e",...t.map((r)=>{let s=ms(r.pattern),n=Mi(r.label);return`journalctl -u ${s} --no-pager -n 150 -o short-iso 2>/dev/null | sed "s/^/LOG=${n}\\t/" || true`}),'[ -f /var/log/ts-cloud-backup.log ] && tail -n 60 /var/log/ts-cloud-backup.log 2>/dev/null | sed "s/^/LOG=backups\\t/" || true',"true"]}function fs(e){let t=new Date(e);if(Number.isNaN(t.getTime()))return e||z;let r=Math.max(0,Math.round((Date.now()-t.getTime())/1000));if(r<60)return`${r}s ago`;let s=Math.round(r/60);if(s<60)return`${s}m ago`;let n=Math.round(s/60);if(n<48)return`${n}h ago`;return`${Math.round(n/24)}d ago`}function zi(e){if(/(?:error|failed|panic|fatal|exception|denied|unhealthy)/i.test(e))return"error";if(/(?:warn|warning|retry|restart|deprecated|timeout)/i.test(e))return"warn";return"info"}function Tl(e){let t=[];for(let r of e.split(`
|
|
722
|
+
`)){let s=r.trim();if(!s.startsWith("LOG="))continue;let n=s.indexOf("\t");if(n<0)continue;let i=s.slice(4,n),o=s.slice(n+1),a=/^(\d{4}-\d{2}-\d{2}T[^\s]+)\s+(\S+)\s+(.*)$/.exec(o),c=a?.[1]??"",l=a?.[2]??"",u=(a?.[3]??o).trim();if(!u)continue;t.push({source:i,timestamp:c,when:c?fs(c):z,host:l,message:u,level:zi(u)})}return t.sort((r,s)=>String(s.timestamp).localeCompare(String(r.timestamp))).slice(0,600)}function Fi(e){if(/^(?:127\.|localhost:|\[?::1\]?)/.test(e))return"loopback";if(/^(?:10\.|192\.168\.|172\.(?:1[6-9]|2\d|3[01])\.|169\.254\.|\[?f[cd][0-9a-f:])/i.test(e))return"private";return"public"}function Pl(e){if(Fi(e)!=="public")return"ok";if(/:(?:22|80|443)$/.test(e)||/^\*:(?:22|80|443)$/.test(e))return"ok";return"warn"}function xl(e){if(e==null)return"warn";if(e<8)return"bad";if(e<30)return"warn";return"ok"}function Cl(e){let t=[],r=[],s=[],n=[];for(let a of e.split(`
|
|
723
|
+
`)){let c=a.trim();if(c.startsWith("PORT=")){let[l="",u="",p=""]=c.slice(5).split("\t");if(l&&u)t.push({proto:l,listen:u,processName:p||z,exposure:Fi(u),tone:Pl(u)})}else if(c.startsWith("FIREWALL=")){let l=c.slice(9).trim();if(l)r.push(l)}else if(c.startsWith("AUTH=")){let l=c.slice(5),u=/^(\d{4}-\d{2}-\d{2}T[^\s]+)\s+(\S+)\s+(.*)$/.exec(l),p=(u?.[3]??l).trim();if(p)s.push({timestamp:u?.[1]??"",when:u?.[1]?fs(u[1]):z,host:u?.[2]??"",message:p,level:zi(p)})}else if(c.startsWith("CERT=")){let[l="",u=""]=c.slice(5).split("\t");if(!l)continue;let p=new Date(u),d=Number.isNaN(p.getTime())?null:Math.ceil((p.getTime()-Date.now())/86400000);n.push({domain:l,expires:Number.isNaN(p.getTime())?u||z:p.toISOString().slice(0,10),daysRemaining:d,status:xl(d)})}}let i=r.some((a)=>/Status:\s*active/i.test(a)),o=r.some((a)=>/unavailable/i.test(a));return{ports:t.slice(0,80),firewall:{status:i?"active":o?"unavailable":"inactive",summary:i?"ufw active":o?"ufw unavailable":"ufw inactive or not configured",rules:r.filter((a)=>a&&!/^Status:/i.test(a)).slice(0,60)},tlsCertificates:n,authEvents:s.sort((a,c)=>String(c.timestamp).localeCompare(String(a.timestamp))).slice(0,30)}}function gs(e){let r=e.infrastructure?.compute?.firewall??{},s=[...new Set([22,80,443,...r.allowedPorts??[]])],n=Ui(e);return{ports:s.map((i)=>({proto:"tcp",listen:`0.0.0.0:${i}`,processName:"configured firewall",exposure:"public",tone:[22,80,443].includes(Number(i))?"ok":"warn"})),firewall:{status:r.enabled===!1?"disabled":"configured",summary:r.enabled===!1?"host firewall disabled in config":"host firewall configured declaratively",rules:s.map((i)=>`ALLOW ${i}/tcp`)},tlsCertificates:n.map((i)=>({domain:i,expires:z,daysRemaining:null,status:"warn"})),authEvents:[]}}function Bi(e,t){let r=t.security??gs(e),s=!!t._serverReachable&&!t.metricsUnavailable,n=t.sites??[],i=n.filter((l)=>l.status==="shadowed"),o=(t.services??[]).filter((l)=>["failed","stopped"].includes(l.status)),a=(r.tlsCertificates??[]).filter((l)=>l.status!=="ok"),c=t.sshKeys??[];return[{name:"Live server probe",status:s?"pass":"warn",detail:s?"Metrics and remote checks are coming from the compute box.":"The dashboard is rendering config/state data until the box probe succeeds."},{name:"Managed services",status:o.length?"fail":"pass",detail:o.length?`${o.length} service(s) need attention.`:`${(t.services??[]).length} service(s) reported healthy or configured.`},{name:"Route conflicts",status:i.length?"warn":"pass",detail:i.length?`${i.map((l)=>l.name).join(", ")} is shadowed by an earlier route.`:`${n.length} site route(s) are unshadowed.`},{name:"SSH access",status:c.length?"pass":"warn",detail:c.length?`${c.length} declarative authorized key(s) configured.`:"No declarative SSH keys are configured."},{name:"Firewall",status:["active","configured"].includes(r.firewall?.status)?"pass":"warn",detail:r.firewall?.summary??"Firewall status unavailable."},{name:"TLS certificates",status:a.length?"warn":"pass",detail:a.length?`${a.length} certificate(s) need renewal visibility.`:`${(r.tlsCertificates??[]).length} certificate(s) look healthy.`}]}function Ki(e){let t=[];for(let r of e.serverDeploymentsDetail??e.serverDeployments??[])t.push({type:"deploy",tone:r.status==="failed"?"bad":"ok",title:`${r.site} deployed ${r.sha}`,detail:`${r.branch} · ${r.status}`,when:r.when,timestamp:r.timestamp});for(let r of e.serverLogs??[])if(r.level==="error"||r.level==="warn")t.push({type:"log",tone:r.level==="error"?"bad":"warn",title:`${r.source} ${r.level}`,detail:r.message,when:r.when,timestamp:r.timestamp});for(let r of e.sshKeys??[])t.push({type:"ssh",tone:"ok",title:`${r.name} authorized`,detail:r.fingerprint,when:r.added??z,timestamp:""});return t.sort((r,s)=>String(s.timestamp).localeCompare(String(r.timestamp))).slice(0,80)}function Rl(e,t={}){let r=[];for(let s of e.split(`
|
|
724
|
+
`)){let n=s.trim();if(!n.startsWith("DEPLOY="))continue;let i=n.split("\t"),o=i[0]?.replace(/^DEPLOY=/,"")??"",[a,c,l,u,p]=i.slice(1);if(!o||!a||!c)continue;let d=t[o]??{},m=K(d),f=(l||c).slice(0,7);r.push({sha:f,release:c,commit:l||c,site:o,branch:d.branch??(m==="server-static"?"build artifact":"main"),status:u||"unknown",when:fs(a),timestamp:a,took:"-",by:"ts-cloud",rc:p?.replace(/^rc=/,"")??"",steps:m==="server-static"?["upload artifact","publish static files"]:["upload artifact","restart service"]})}return r.sort((s,n)=>String(n.timestamp).localeCompare(String(s.timestamp)))}function El(e,t){let r=ml(e,t),s=ki(e),n=Sl(e),i=Math.max(1,Number(e.infrastructure?.compute?.disk?.size??1)),o={server:{name:r?.serverName??`${e.project.slug}-${t}-app`,provider:r?.provider??Hi(e),region:pl(e),ip:r?.publicIp??z,os:"Linux",uptime:z,probeStatus:"unavailable"},systemMetrics:{load:0,load5:0,load15:0,cpuUsedPct:0,cpus:Math.max(1,Number(e.infrastructure?.compute?.instances??1)),memUsedMb:0,memTotalMb:0,memAvailableMb:0,memCacheMb:0,swapUsedMb:0,swapTotalMb:0,diskUsedPct:0,diskUsedGb:0,diskTotalGb:i,inodeUsedPct:0,networkRxBytes:0,networkTxBytes:0,networkRxBytesPerSec:0,networkTxBytesPerSec:0,networkRxBytesToday:0,networkTxBytesToday:0,networkRxBytesMonth:0,networkTxBytesMonth:0,networkMonthKey:"",processes:0,uptimeSeconds:0},metricsUnavailable:!0,bandwidthBudgetBytes:dl(e),services:s,servicesDetail:s.map((a)=>({...a,since:z,memMb:0,auto:!0})),backup:ul(e),backupHistory:[],workers:fl(e),serverScheduler:{enabled:!1,lastRun:"not configured"},serverDeployments:[],serverDeploymentsDetail:[],deploymentsEmptyReason:"No deployment history has been recorded yet. Future server deploys will write /var/www/<site>/.ts-cloud/deploy-history.log.",serverLogs:[],serverLogsEmptyReason:"Live server logs are unavailable until the dashboard can reach the compute box.",security:gs(e),securityEmptyReason:"Live security checks are unavailable until the dashboard can reach the compute box.",sites:n,sitesDetail:n.map((a)=>{let c=e.sites?.[a.name]??{},l=K(c);return{...a,root:l==="server-static"?Ee(e.project.slug,a.name):`${Ee(e.project.slug,a.name)}/current`,branch:l==="server-static"?"build artifact":"main",build:c.build,php:c.php??c.phpVersion,aliases:Array.isArray(c.aliases)?c.aliases:[],redirects:c.redirects&&typeof c.redirects==="object"?c.redirects:{},envKeys:Object.keys(c.env??c.environment??{})}}),siteHealth:[],sshKeys:ls(e.infrastructure?.compute?.sshKeys??[]),_serverReachable:!1,_metricsStatus:"unavailable"};return o.diagnostics=Bi(e,o),o.activity=Ki(o),o.topology=ds(o,{project:e.project.name,environment:t}),o}async function Tf(e,t,r={}){if(!e.infrastructure?.compute)return null;let s=null;try{s=Ar({config:e})}catch{s=null}let n=null,i=0,o=[];if(s)try{if(o=await s.findComputeTargets({slug:e.project.slug,environment:t,role:"app"}),i=o.length,o.length){let p=(await s.runRemoteDeploy({targets:[o[0]],commands:cl({includeServices:!r.telemetryOnly,includeSites:r.includeSiteHealth!==!1,projectFilter:e.cloud?.attachTo?e.project.slug:void 0}),comment:`ts-cloud dashboard:build ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output;if(p)n=ll(p)}}catch{}let a=El(e,t),c=(u,p=0)=>{let d=Number(u);return Number.isFinite(d)?d:p};if(a.server.os=n?.OS||a.server.os,a.server.uptime=n?.UPTIME||a.server.uptime,n){if(a.server.probeStatus="live",a.metricsUnavailable=!1,a._metricsStatus="live",a.systemMetrics={load:c(n.LOAD),load5:c(n.LOAD5),load15:c(n.LOAD15),cpuUsedPct:c(n.CPUUSED),cpus:c(n.CPUS,1),memUsedMb:c(n.MEMUSED),memTotalMb:c(n.MEMTOTAL,1),memAvailableMb:c(n.MEMAVAILABLE),memCacheMb:c(n.MEMCACHE),swapUsedMb:c(n.SWAPUSED),swapTotalMb:c(n.SWAPTOTAL),diskUsedPct:c(n.DISKPCT),diskUsedGb:c(n.DISKUSEDG),diskTotalGb:c(n.DISKTOTG,1),inodeUsedPct:c(n.INODEPCT),networkRxBytes:c(n.NETRX),networkTxBytes:c(n.NETTX),networkRxBytesPerSec:c(n.NETRXRATE),networkTxBytesPerSec:c(n.NETTXRATE),networkRxBytesToday:c(n.NETRXTODAY),networkTxBytesToday:c(n.NETTXTODAY),networkRxBytesMonth:c(n.NETRXMONTH),networkTxBytesMonth:c(n.NETTXMONTH),networkMonthKey:n.NETMONTHKEY||"",processes:c(n.PROCESSES),uptimeSeconds:c(n.UPTIME_SECONDS)},n.services.length){let u=[...new Map(n.services.map((p)=>[p.name,p])).values()];a.services=u.map((p)=>({name:p.name,status:p.status==="active"?"running":p.status})),a.servicesDetail=u.map((p)=>({name:p.name,status:p.status==="active"?"running":p.status,since:p.since&&p.since!==z?p.since:a.server.uptime,memMb:Math.max(0,Math.round(Number(p.memBytes??0)/1024/1024)),auto:p.enabled?!["disabled","static","masked"].includes(p.enabled):!0}))}if(n.discoveredSites.length)a.sitesDetail=vl(a.sitesDetail,n.discoveredSites,e.project.slug),a.sites=a.sitesDetail.map((u)=>({name:u.name,project:u.project,managedBy:u.managedBy,route:u.route,href:u.href,domain:u.domain,path:u.path,kind:u.kind,type:u.type,runtime:u.runtime,deploy:u.deploy,tls:u.tls,status:u.status,httpStatus:u.httpStatus,responseMs:u.responseMs,tlsDaysRemaining:u.tlsDaysRemaining,checkedAt:u.checkedAt})),a.siteHealth=a.sitesDetail.map((u)=>({name:u.name,project:u.project,route:u.route,status:u.status,httpStatus:u.httpStatus,responseMs:u.responseMs,tlsDaysRemaining:u.tlsDaysRemaining,checkedAt:u.checkedAt}))}if(s&&o.length&&!r.telemetryOnly)await Promise.all([(async()=>{try{let u=Object.keys(e.sites??{}),d=(await s.runRemoteDeploy({targets:[o[0]],commands:bl(u,e.project.slug),comment:`ts-cloud dashboard:deploy-history ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",m=Rl(d,e.sites);a.serverDeployments=m.slice(0,5),a.serverDeploymentsDetail=m.slice(0,50),a.deploymentsEmptyReason=m.length?void 0:"No deployment history was found on the server yet. Deploy again to populate this timeline."}catch{a.deploymentsEmptyReason="Deployment history could not be read from the server."}})(),(async()=>{try{let p=(await s.runRemoteDeploy({targets:[o[0]],commands:_l(e),comment:`ts-cloud dashboard:server-logs ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",d=Tl(p);a.serverLogs=d,a.serverLogsEmptyReason=d.length?void 0:"No recent journal entries were found for the managed server units."}catch{a.serverLogsEmptyReason="Server logs could not be read from the box."}})(),(async()=>{try{let p=(await s.runRemoteDeploy({targets:[o[0]],commands:wl(e),comment:`ts-cloud dashboard:security ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",d=Cl(p),m=gs(e);if(!d.ports.length)d.ports=m.ports;if(!d.tlsCertificates.length)d.tlsCertificates=m.tlsCertificates;a.security=d,a.securityEmptyReason=void 0}catch{a.securityEmptyReason="Server security checks could not be read from the box."}})()]);else if(s&&i===0)a.deploymentsEmptyReason="No app server target was found for this environment.";let l=e.infrastructure?.compute?.sshKeys??e.infrastructure?.ssh?.keys??e.infrastructure?.sshKeys;if(Array.isArray(l)&&l.length)a.sshKeys=ls(l);return a._serverReachable=i>0&&!!n,a.diagnostics=Bi(e,a),a.activity=Ki(a),a.topology=ds(a,{project:e.project.name,environment:t}),a}
|
|
725
|
+
export{mt as $d,Il as ae,ce as be,qi as ce,Ol as de,Yi as ee,vs as fe,or as ge,vo as he,Es as ie,ee as je,j as ke,$e as le,ie as me,Pt as ne,an as oe,Rt as pe,Xo as qe,Et as re,Te as se,xe as te,Ce as ue,it as ve,bn as we,xr as xe,Cr as ye,Or as ze,Dr as Ae,Ht as Be,Ar as Ce,Bn as De,Da as Ee,Kn as Fe,ka as Ge,kr as He,Fa as Ie,Ga as Je,$d as Ke,Vn as Le,Ya as Me,Ja as Ne,Qa as Oe,sc as Pe,nc as Qe,ic as Re,oi as Se,Xc as Te,Yc as Ue,mf as Ve,ff as We,ls as Xe,Ai as Ye,al as Ze,cl as _e,ll as $e,vl as af,$l as bf,Tl as cf,Cl as df,Rl as ef,El as ff,Tf as gf};
|