@stacksjs/ts-cloud 0.16.76 → 0.16.78

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/bin/{chunk-cvbass8r.js → chunk-2xtxktj3.js} +1 -1
  2. package/dist/bin/{chunk-fp9zajws.js → chunk-hkqq09p2.js} +1 -1
  3. package/dist/bin/{chunk-t3hsn9tf.js → chunk-n5sapbxq.js} +13 -13
  4. package/dist/bin/cli.js +4 -4
  5. package/dist/bin/dashboard-server.js +1 -1
  6. package/dist/{chunk-ga00dvdb.js → chunk-m95n1mbv.js} +1 -1
  7. package/dist/{chunk-4a1qcgpb.js → chunk-wxy6jk7d.js} +11 -11
  8. package/dist/deploy/index.js +1 -1
  9. package/dist/drivers/index.js +1 -1
  10. package/dist/index.js +1 -1
  11. package/dist/ui/404.html +1 -1
  12. package/dist/ui/accept-invitation.html +1 -1
  13. package/dist/ui/access-denied.html +1 -1
  14. package/dist/ui/account/automation.html +6 -6
  15. package/dist/ui/account/security.html +2 -2
  16. package/dist/ui/applications/compose.html +6 -6
  17. package/dist/ui/applications/new.html +2 -2
  18. package/dist/ui/data/backups.html +6 -6
  19. package/dist/ui/data/services.html +6 -6
  20. package/dist/ui/data/volumes.html +6 -6
  21. package/dist/ui/index.html +6 -6
  22. package/dist/ui/infrastructure/topology.html +6 -6
  23. package/dist/ui/integrations.html +1 -1
  24. package/dist/ui/operations/alerts.html +6 -6
  25. package/dist/ui/operations/configuration.html +6 -6
  26. package/dist/ui/operations/jobs.html +5 -5
  27. package/dist/ui/operations/maintenance.html +6 -6
  28. package/dist/ui/operations/observability.html +6 -6
  29. package/dist/ui/operations/previews.html +6 -6
  30. package/dist/ui/operations/queue.html +6 -6
  31. package/dist/ui/operations/regions.html +6 -6
  32. package/dist/ui/operations/releases.html +6 -6
  33. package/dist/ui/operations/spend.html +5 -5
  34. package/dist/ui/operations/workloads.html +6 -6
  35. package/dist/ui/security.html +1 -1
  36. package/dist/ui/server/actions.html +6 -6
  37. package/dist/ui/server/activity.html +2 -2
  38. package/dist/ui/server/capacity.html +5 -5
  39. package/dist/ui/server/database.html +6 -6
  40. package/dist/ui/server/deployments.html +5 -5
  41. package/dist/ui/server/diagnostics.html +2 -2
  42. package/dist/ui/server/firewall.html +6 -6
  43. package/dist/ui/server/fleet.html +5 -5
  44. package/dist/ui/server/logs.html +5 -5
  45. package/dist/ui/server/metrics.html +5 -5
  46. package/dist/ui/server/security.html +1 -1
  47. package/dist/ui/server/services.html +1 -1
  48. package/dist/ui/server/sites.html +6 -6
  49. package/dist/ui/server/ssh-keys.html +6 -6
  50. package/dist/ui/server/team.html +6 -6
  51. package/dist/ui/server/terminal.html +2 -2
  52. package/dist/ui/serverless/alarms.html +6 -6
  53. package/dist/ui/serverless/assets.html +1 -1
  54. package/dist/ui/serverless/cost.html +2 -2
  55. package/dist/ui/serverless/data.html +6 -6
  56. package/dist/ui/serverless/deployments.html +2 -2
  57. package/dist/ui/serverless/firewall.html +1 -1
  58. package/dist/ui/serverless/functions.html +6 -6
  59. package/dist/ui/serverless/logs.html +6 -6
  60. package/dist/ui/serverless/metrics.html +2 -2
  61. package/dist/ui/serverless/queues.html +6 -6
  62. package/dist/ui/serverless/secrets.html +6 -6
  63. package/dist/ui/serverless/traces.html +6 -6
  64. package/dist/ui/serverless.html +5 -5
  65. package/package.json +3 -3
@@ -136,19 +136,19 @@ ${y.join(`
136
136
  echo "ts-cloud bootstrap complete — instance is ready for site deploys"
137
137
  `,_}var Ps="/aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id";function Es(e,t){let r=[{port:22,protocol:"tcp",cidr:"0.0.0.0/0"},{port:80,protocol:"tcp",cidr:"0.0.0.0/0"},{port:443,protocol:"tcp",cidr:"0.0.0.0/0"}],n=new Set;for(let s of Object.values(e.sites||{}))if(s&&typeof s.port==="number"&&![22,80,443].includes(s.port))n.add(s.port);for(let s of Ze(C(e,{environment:t})))n.add(s);for(let s of n)r.push({port:s,protocol:"tcp",cidr:"0.0.0.0/0"});return r}function Rs(e,t){let r={...e.infrastructure?.compute,proxy:w(e,{environment:t})},n=Qe(e,{environment:t}),s=r.proxy?.engine==="rpx"?G({proxy:r.proxy,config:B(e.sites??{},{proxy:r.proxy,slug:e.project.slug,mail:C(e,{environment:t})}),slug:e.project.slug,bunBin:r.runtime==="node"||r.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0;return M({runtime:n.runtime,runtimeVersion:n.runtimeVersion,systemPackages:r.systemPackages,database:e.infrastructure?.database,phpProvision:n.phpProvision,servicesProvision:n.servicesProvision,rpxProvision:s,baked:r.bakedImage===!0,swapGb:r.swapGb})}function Os(e){return Buffer.from(e,"utf8").toString("base64")}function Ds(e){return e.infrastructure?.compute?.image??null}function ur(e,t){return`${e}-${t}-app-sg`}function hn(e,t,r="app"){return[{Key:"Project",Value:e},{Key:"Environment",Value:t},{Key:"Role",Value:r},{Key:"ManagedBy",Value:"ts-cloud"}]}function Xa(e,t,r){if(!e?.length)return!1;let n=(s)=>e.find((i)=>i.Key===s)?.Value;return n("Project")===t&&n("Environment")===r}function xs(e,t){let r=ur(t.slug,t.environment);return e.find((n)=>{if(n.GroupName!==r)return!1;if(t.vpcId&&n.VpcId&&n.VpcId!==t.vpcId)return!1;if(!!n.Tags?.some((i)=>i.Key==="Project"))return Xa(n.Tags,t.slug,t.environment);return!!t.vpcId&&n.VpcId===t.vpcId})}function Za(e){try{let t=As(Ja(process.cwd(),"storage/cloud/state",`${e}.json`),"utf8"),r=JSON.parse(t);return typeof r.instanceId==="string"&&r.instanceId.length>0?r.instanceId:null}catch{return null}}class $r{name="aws";usesCloudFormation=!0;region;ec2Client;cfnClient;constructor(e={}){this.region=e.region||"us-east-1",this.ec2Client=e.ec2Client??((t)=>new qr(t)),this.cfnClient=e.cfnClient??((t)=>new A(t))}resolveRegion(e){return e.project.region||this.region}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e,n=this.resolveRegion(t),s=t.project.slug,i=t.infrastructure?.compute;if(!i)throw Error("infrastructure.compute is required to provision AWS compute");let a=this.ec2Client(n),c=await this.findComputeTargets({slug:s,environment:r,role:"app",region:n});if(c.length>0){let W=c[0];return{appInstanceId:W.id,appPublicIp:W.publicIp,appPublicIpv6:W.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}let f=Ds(t);if(!f){if(f=(await new Be(n).getParameter({Name:Ps})).Parameter?.Value??null,!f)throw Error("Could not resolve the Ubuntu 24.04 AMI from SSM")}let g=await a.describeVpcs(),h=(g.Vpcs||[]).find((W)=>W.IsDefault)||(g.Vpcs||[])[0];if(!h?.VpcId)throw Error("No VPC found to launch the instance into");let S=(await a.describeSubnets({Filters:[{Name:"vpc-id",Values:[h.VpcId]}]})).Subnets||[],_=S.find((W)=>W.MapPublicIpOnLaunch)||S[0],v=_?.SubnetId;if(!_?.MapPublicIpOnLaunch)console.warn("ts-cloud: no public subnet found; the instance may not get a public IP (deploys/SSL need one).");let y=ur(s,r),x=(await a.describeSecurityGroups({Filters:[{Name:"group-name",Values:[y]},{Name:"vpc-id",Values:[h.VpcId]}]})).SecurityGroups?.[0]?.GroupId;if(!x)x=(await a.createSecurityGroup({GroupName:y,Description:`ts-cloud ${s}/${r} app`,VpcId:h.VpcId,TagSpecifications:[{ResourceType:"security-group",Tags:hn(s,r)}]})).GroupId;let q=Es(t,r);await a.authorizeSecurityGroupIngress({GroupId:x,IpPermissions:q.map((W)=>({IpProtocol:W.protocol,FromPort:W.port,ToPort:W.port,IpRanges:[{CidrIp:W.cidr}]}))}).catch((W)=>{if(!/InvalidPermission\.Duplicate/.test(W instanceof Error?W.message:""))throw W});let H=Os(Rs(t,r)),R=i.server?.instanceType||"t3.small",I=(await a.runInstances({ImageId:f,InstanceType:R,MinCount:1,MaxCount:1,SecurityGroupIds:x?[x]:void 0,SubnetId:v,UserData:H,IamInstanceProfile:i.server?.iamInstanceProfile?{Name:i.server.iamInstanceProfile}:void 0,TagSpecifications:[{ResourceType:"instance",Tags:[{Key:"Name",Value:`${s}-${r}-app`},...hn(s,r)]}]})).Instances?.[0]?.InstanceId;if(!I)throw Error("RunInstances did not return an instance id");let V=await a.waitForInstanceState(I,"running");if(!V)throw Error(`Instance ${I} did not reach 'running' before timeout`);return{appInstanceId:I,appPublicIp:V.PublicIpAddress,appPublicIpv6:De(V.Ipv6Address),sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}async destroyCompute(e){let{config:t,environment:r}=e,n=t.project.slug,s=this.resolveRegion(t),i=this.ec2Client(s),a=[],f=(await this.findComputeTargets({slug:n,environment:r,role:"app",region:s})).map((y)=>y.id),g;if(f.length>0)g=(await i.describeInstances({InstanceIds:f}).catch(()=>({Reservations:[]}))).Reservations?.flatMap((T)=>T.Instances??[]).find((T)=>T.VpcId)?.VpcId;if(f.length>0)await i.terminateInstances(f),a.push(...f.map((y)=>`instance ${y}`)),await Promise.all(f.map((y)=>i.waitForInstanceState(y,"terminated").catch(()=>{return})));let h=ur(n,r),S=[{Name:"group-name",Values:[h]}];if(g)S.push({Name:"vpc-id",Values:[g]});let _=await i.describeSecurityGroups({Filters:S}).catch(()=>({SecurityGroups:[]})),v=xs(_.SecurityGroups??[],{slug:n,environment:r,vpcId:g});if(v?.GroupId)for(let y=0;y<10;y++)try{await i.deleteSecurityGroup(v.GroupId),a.push(`security group ${h}`);break}catch{await new Promise((T)=>setTimeout(T,3000))}return{destroyed:a}}async getComputeOutputs(e){let t=this.resolveRegion(e.config),r=m(e.config,e.environment),n=this.cfnClient(t);try{let s=await n.getStackOutputs(r);return{deployBucketName:s.deployBucketName,appInstanceId:s.appInstanceId,appPublicIp:s.appPublicIp,sshUser:"ec2-user"}}catch(s){if(!/does not exist|ValidationError/i.test(s instanceof Error?s.message:""))throw s;let a=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",region:t}))[0];return{appInstanceId:a?.id,appPublicIp:a?.publicIp,appPublicIpv6:a?.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}}async uploadRelease(e){let t=this.resolveRegion(e.config),n=(await this.getComputeOutputs({config:e.config,environment:e.environment})).deployBucketName;if(!n)throw Error("No deployBucketName in stack outputs. Re-deploy infrastructure to add the staging bucket.");return await new o(t).putObject({bucket:n,key:e.remoteKey,body:As(e.localPath),contentType:"application/gzip"}),{artifactRef:`s3://${n}/${e.remoteKey}`}}async findComputeTargets(e){let t=e.region??this.region,r=this.ec2Client(t),n=[{Name:"tag:Project",Values:[e.slug]},{Name:"tag:Environment",Values:[e.environment]},{Name:"tag:Role",Values:[e.role||"app"]},{Name:"instance-state-name",Values:["running","pending"]}],s=await r.describeInstances({Filters:n}),i=this.reservationsToTargets(s.Reservations);if(i.length>0||(e.role||"app")!=="app")return i;let a=e.stackName??`${e.slug}-${e.environment}`,c=Za(a);if(!c)try{c=(await this.cfnClient(t).getStackOutputs(a)).appInstanceId??null}catch{c=null}if(!c)return[];try{let f=await r.describeInstances({InstanceIds:[c],Filters:[{Name:"instance-state-name",Values:["running","pending"]}]});return this.reservationsToTargets(f.Reservations)}catch{return[]}}reservationsToTargets(e){let t=[];for(let r of e||[])for(let n of r.Instances||[]){if(!n.InstanceId)continue;let s=n.Tags?.find((i)=>i.Key==="Name")?.Value;t.push({id:n.InstanceId,name:s,publicIp:n.PublicIpAddress,publicIpv6:De(n.Ipv6Address),privateIp:n.PrivateIpAddress,status:n.State?.Name})}return t}bashWrap(e){return["bash <<'TS_CLOUD_BASH_EOF'",e.join(`
138
138
  `),"TS_CLOUD_BASH_EOF"]}async runRemoteDeploy(e){let t=this.region,r=new Be(t);if(e.targets.length>0){let s=await r.sendCommand({InstanceIds:e.targets.map((i)=>i.id),DocumentName:"AWS-RunShellScript",Parameters:{commands:this.bashWrap(e.commands)},TimeoutSeconds:e.timeoutSeconds||600,Comment:e.comment});if(!s.CommandId)return{success:!1,instanceCount:0,perInstance:[],error:"Failed to send SSM command"};return this.pollSsmCommand(r,s.CommandId,e.targets.length,((e.timeoutSeconds||600)+30)*1000)}if(!e.tags||Object.keys(e.tags).length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets or tags provided for AWS deploy"};let n=await r.sendCommandByTags({tags:e.tags,commands:this.bashWrap(e.commands),timeoutSeconds:e.timeoutSeconds||600,comment:e.comment});return{success:n.success,instanceCount:n.instanceCount,perInstance:n.perInstance.map((s)=>({instanceId:s.instanceId,status:s.status,output:s.output,error:s.error})),error:n.error}}async pollSsmCommand(e,t,r,n=600000){let i=Date.now(),a=new Set(["Success","Failed","Cancelled","TimedOut"]),c=[];while(Date.now()-i<n){await new Promise((h)=>setTimeout(h,3000));try{if(c=await e.listCommandInvocations({CommandId:t,Details:!0}),c.length>=r&&c.every((S)=>a.has(S.Status||"")))break}catch{}}let f=c.map((h)=>({instanceId:h.InstanceId,status:h.Status||"Unknown",output:h.StandardOutputContent,error:h.StandardErrorContent})),g=f.length>0&&f.every((h)=>h.status==="Success");return{success:g,instanceCount:f.length,perInstance:f,error:g?void 0:Yt(f,"One or more SSM command invocations failed")}}}import{execFileSync as sl,execSync as ho}from"node:child_process";import{createHash as ol,randomUUID as So}from"node:crypto";import{createReadStream as al,existsSync as cl,readFileSync as ll}from"node:fs";async function Is(e,t){let r=await import("node:fs"),n=await import("node:path"),s=await import("node:child_process"),i="/etc/ts-cloud/compute-storage.json",a="/var/lib/ts-cloud/compute-storage-state.json",c="/run/ts-cloud-root-web",f=t[0]??"status";if(!["plan","status","check","apply","ensure-site","reclaim"].includes(f))throw Error(`Unknown compute storage command: ${f}`);let g=(b,k)=>{try{return JSON.parse(r.readFileSync(b,"utf8"))}catch(P){if(P.code==="ENOENT")return k;throw P}},h=(b,k)=>{r.mkdirSync(n.dirname(b),{recursive:!0});let P=`${b}.${process.pid}.tmp`;r.writeFileSync(P,`${JSON.stringify(k,null,2)}
139
- `,{mode:420}),r.renameSync(P,b)},S=(b,k)=>s.execFileSync(b,k,{encoding:"utf8",maxBuffer:16777216}),_=(b,k)=>{let P=s.spawnSync(b,k,{encoding:"utf8"});return P.status===0?P.stdout.trim():""},v=(b)=>!!_("findmnt",["-n","--mountpoint",b]),y=(b,k)=>{try{let P=r.statSync(b),O=r.statSync(k);return P.dev===O.dev&&P.ino===O.ino}catch{return!1}},T=g("/var/lib/ts-cloud/compute-storage-state.json",{entries:[]}),x=e.deploymentStorage,q=e.volumes.find((b)=>b.key===x?.volume),H=(b,k)=>{if(!q)return[];let P=[];for(let O of r.readdirSync(e.webRoot,{withFileTypes:!0})){if(!O.isDirectory()||O.isSymbolicLink())continue;let D=n.join(e.webRoot,O.name);if(b&&D!==b&&D!==n.join(e.webRoot,`${k}-shared`))continue;for(let J of["releases",...x?.includeBackups===!1?[]:["backups"]]){let Y=n.join(D,J);if(!r.existsSync(Y)||!r.lstatSync(Y).isDirectory())continue;P.push({source:Y,destination:n.join(q.mountPath,J,O.name)})}}return P},R=(b)=>{try{return v(b.mountPath)&&r.statSync(b.mountPath).dev===r.statSync(b.device).rdev}catch{return!1}},L=(b)=>{let k=r.statfsSync(b),P=(k.blocks-k.bfree)*k.bsize,O=k.bavail*k.bsize;return{path:b,sizeBytes:k.blocks*k.bsize,usedBytes:P,availableBytes:O,usedPercent:Math.ceil(100*P/(P+O))}},I=()=>{let b=[],k=[L("/")];for(let O of e.volumes)if(!R(O))b.push(`missing or incorrect volume mount: ${O.mountPath}`);else k.push(L(O.mountPath));for(let O of T.entries)if(!v(O.source)||!y(O.source,O.destination))b.push(`missing deployment mount: ${O.source}`);let P=new Set(T.entries.map((O)=>O.source));for(let O of H())if(!P.has(O.source))b.push(`deployment needs volume placement: ${O.source}`);return{timestamp:new Date().toISOString(),volumes:e.volumes.map((O)=>({key:O.key,name:O.name,id:O.id,size:O.size,mountPath:O.mountPath})),disks:k,mounts:T.entries.length,problems:b}};if(f==="plan")return console.log(JSON.stringify({volumes:e.volumes,entries:H(),state:T},null,2));if(f==="status"||f==="check"){let b=I();if(f==="check"){h("/var/lib/ts-cloud/compute-storage-status.json",b);let k="/var/lib/ts-cloud/compute-storage-alert.json",P=g(k,{problems:[]});if(JSON.stringify(P.problems)!==JSON.stringify(b.problems)){let O=b.problems.join("; ")||"all configured mounts are healthy",D=`${b.problems.length?"Storage alert":"Storage recovered"} on ${_("hostname",[])}: ${O}`;S("/usr/local/bin/ts-cloud-notify",[D.length>1800?`${D.slice(0,1600)}... Full report: /var/lib/ts-cloud/compute-storage-status.json`:D])}h(k,{problems:b.problems,timestamp:b.timestamp})}if(console.log(JSON.stringify(b)),b.problems.length)process.exitCode=1;return b}if(process.getuid?.()!==0)throw Error("Compute storage changes require root");let V=()=>{let O=r.readFileSync("/etc/fstab","utf8");if(!r.existsSync("/etc/fstab.before-ts-cloud-storage"))r.copyFileSync("/etc/fstab","/etc/fstab.before-ts-cloud-storage");let D=[];for(let X of e.volumes){let Z=S("blkid",["-s","UUID","-o","value",X.device]).trim();if(!Z)throw Error(`Volume ${X.name} has no filesystem UUID`);D.push(`UUID=${Z} ${X.mountPath} ext4 defaults,noatime,nodev,nosuid,nofail,x-systemd.device-timeout=30s 0 2`)}for(let X of T.entries)D.push(`${X.destination} ${X.source} none bind,nofail,x-systemd.requires-mounts-for=${q.mountPath} 0 0`);let J=`# BEGIN ts-cloud compute storage
139
+ `,{mode:420}),r.renameSync(P,b)},S=(b,k)=>s.execFileSync(b,k,{encoding:"utf8",maxBuffer:16777216}),_=(b,k)=>{let P=s.spawnSync(b,k,{encoding:"utf8"});return P.status===0?P.stdout.trim():""},v=(b)=>!!_("findmnt",["-n","--mountpoint",b]),y=(b,k)=>{try{let P=r.statSync(b),O=r.statSync(k);return P.dev===O.dev&&P.ino===O.ino}catch{return!1}},T=g("/var/lib/ts-cloud/compute-storage-state.json",{entries:[]}),x=e.deploymentStorage,q=e.volumes.find((b)=>b.key===x?.volume),H=(b,k)=>{if(!q)return[];let P=[];for(let O of r.readdirSync(e.webRoot,{withFileTypes:!0})){if(!O.isDirectory()||O.isSymbolicLink())continue;let D=n.join(e.webRoot,O.name);if(b&&D!==b&&D!==n.join(e.webRoot,`${k}-shared`))continue;for(let J of["releases",...x?.includeBackups===!1?[]:["backups"]]){let Y=n.join(D,J);if(!r.existsSync(Y)||!r.lstatSync(Y).isDirectory())continue;P.push({source:Y,destination:n.join(q.mountPath,J,O.name)})}}return P},R=(b)=>{try{return v(b.mountPath)&&r.statSync(b.mountPath).dev===r.statSync(b.device).rdev}catch{return!1}},L=(b)=>{let k=r.statfsSync(b),P=(k.blocks-k.bfree)*k.bsize,O=k.bavail*k.bsize;return{path:b,sizeBytes:k.blocks*k.bsize,usedBytes:P,availableBytes:O,usedPercent:Math.ceil(100*P/(P+O))}},I=()=>{let b=[],k=[L("/")];for(let O of e.volumes)if(!R(O))b.push(`missing or incorrect volume mount: ${O.mountPath}`);else k.push(L(O.mountPath));for(let O of T.entries)if(!v(O.source)||!y(O.source,O.destination))b.push(`missing deployment mount: ${O.source}`);let P=new Set(T.entries.map((O)=>O.source));for(let O of H())if(!P.has(O.source))b.push(`deployment needs volume placement: ${O.source}`);return{timestamp:new Date().toISOString(),volumes:e.volumes.map((O)=>({key:O.key,name:O.name,id:O.id,size:O.size,mountPath:O.mountPath})),disks:k,mounts:T.entries.length,problems:b}};if(f==="plan")return console.log(JSON.stringify({volumes:e.volumes,entries:H(),state:T},null,2));if(f==="status"||f==="check"){let b=I();if(f==="check"){h("/var/lib/ts-cloud/compute-storage-status.json",b);let k="/var/lib/ts-cloud/compute-storage-alert.json",P=g(k,{problems:[]});if(JSON.stringify(P.problems)!==JSON.stringify(b.problems)){let O=b.problems.join("; ")||"all configured mounts are healthy",D=`${b.problems.length?"Storage alert":"Storage recovered"} on ${_("hostname",[])}: ${O}`;S("/usr/local/bin/ts-cloud-notify",[D.length>1800?`${D.slice(0,1600)}... Full report: /var/lib/ts-cloud/compute-storage-status.json`:D])}h(k,{problems:b.problems,timestamp:b.timestamp})}if(console.log(JSON.stringify(b)),b.problems.length)process.exitCode=1;return b}if(process.getuid?.()!==0)throw Error("Compute storage changes require root");let V=()=>{let O=r.readFileSync("/etc/fstab","utf8");if(!r.existsSync("/etc/fstab.before-ts-cloud-storage"))r.copyFileSync("/etc/fstab","/etc/fstab.before-ts-cloud-storage");let D=[];for(let X of e.volumes){let ee=S("blkid",["-s","UUID","-o","value",X.device]).trim();if(!ee)throw Error(`Volume ${X.name} has no filesystem UUID`);D.push(`UUID=${ee} ${X.mountPath} ext4 defaults,noatime,nodev,nosuid,nofail,x-systemd.device-timeout=30s 0 2`)}for(let X of T.entries)D.push(`${X.destination} ${X.source} none bind,nofail,x-systemd.requires-mounts-for=${q.mountPath} 0 0`);let J=`# BEGIN ts-cloud compute storage
140
140
  ${D.join(`
141
141
  `)}
142
- # END ts-cloud compute storage`,Y;if(O.includes("# BEGIN ts-cloud compute storage")){let X=O.indexOf("# BEGIN ts-cloud compute storage"),Z=O.indexOf("# END ts-cloud compute storage",X);if(Z<0)throw Error("Incomplete managed storage block in fstab");Y=O.slice(0,X)+J+O.slice(Z+30)}else Y=`${O.trimEnd()}
142
+ # END ts-cloud compute storage`,Y;if(O.includes("# BEGIN ts-cloud compute storage")){let X=O.indexOf("# BEGIN ts-cloud compute storage"),ee=O.indexOf("# END ts-cloud compute storage",X);if(ee<0)throw Error("Incomplete managed storage block in fstab");Y=O.slice(0,X)+J+O.slice(ee+30)}else Y=`${O.trimEnd()}
143
143
  ${J}
144
- `;r.writeFileSync("/etc/fstab.ts-cloud-new",Y),r.renameSync("/etc/fstab.ts-cloud-new","/etc/fstab")},W=()=>{for(let b of e.volumes){if(!r.existsSync(b.device)||!r.statSync(b.device).isBlockDevice())throw Error(`Volume device missing: ${b.device}`);let k=_("blkid",["-s","TYPE","-o","value",b.device]);if(!k){if(!b.allowFormat)throw Error(`Refusing to format adopted volume ${b.name}; no recognized filesystem`);S("mkfs.ext4",["-m","1",b.device]),k="ext4"}if(k!=="ext4")throw Error(`Refusing to replace ${k} filesystem on ${b.name}`);if(r.mkdirSync(b.mountPath,{recursive:!0}),v(b.mountPath)&&!R(b))throw Error(`Another filesystem occupies ${b.mountPath}`);if(!v(b.mountPath)&&r.readdirSync(b.mountPath).length)throw Error(`Refusing to hide existing files beneath ${b.mountPath}`);if(!v(b.mountPath))S("mount",["-o","noatime,nodev,nosuid",b.device,b.mountPath]);if(!R(b))throw Error(`Volume identity verification failed: ${b.name}`);S("resize2fs",[b.device]),b.allowFormat=!1}h("/etc/ts-cloud/compute-storage.json",e),V(),S("systemctl",["daemon-reload"])},{dlopen:K,read:ee}=await import("bun:ffi"),te=K("libc.so.6",{flock:{args:["i32","i32"],returns:"i32"},__errno_location:{args:[],returns:"ptr"}}),ne=[],ie=(b,k=!0)=>{r.mkdirSync(n.dirname(b),{recursive:!0});let P=r.openSync(b,r.constants.O_CREAT|r.constants.O_RDWR|r.constants.O_NOFOLLOW,384);if(te.symbols.flock(P,k?2:6)!==0){let O=ee.i32(te.symbols.__errno_location());if(r.closeSync(P),!k&&O===11)return!1;throw Error(`Could not acquire lock: ${b} (errno ${O})`)}return ne.push(P),!0},oe=()=>{let b=[];for(let k of r.readdirSync("/proc").filter((P)=>/^\d+$/.test(P))){let P=[];try{P=r.readdirSync(`/proc/${k}/fd`)}catch{continue}for(let O of["cwd","exe",...P.map((D)=>`fd/${D}`)]){let D=`/proc/${k}/${O}`;try{let J=r.readlinkSync(D);if(!J.startsWith(`${e.webRoot}/`)||!J.includes("/releases/"))continue;let Y=!1;if(O.startsWith("fd/")){let X=r.readFileSync(`/proc/${k}/fdinfo/${O.slice(3)}`,"utf8").match(/^flags:\s+(\d+)/m);Y=!!X&&(Number.parseInt(X[1],8)&3)!==0&&r.statSync(D).isFile()}b.push({file:J,write:Y,device:r.statSync(D).dev})}catch{}}}return b},re=async(b,k)=>{r.mkdirSync(b.destination,{recursive:!0});let P=["rsync","-aHAXx","--numeric-ids","--delete",...k?["--checksum"]:[],`${b.source}/`,`${b.destination}/`],D=await Bun.spawn(P,{stdout:"inherit",stderr:"inherit"}).exited;if(D!==0&&!(D===24&&!k))throw Error(`rsync failed (${D}): ${b.source}`)},pe=async()=>{let b=S("systemctl",["list-units","--type=service","--state=running","--no-legend","--plain"]).split(`
144
+ `;r.writeFileSync("/etc/fstab.ts-cloud-new",Y),r.renameSync("/etc/fstab.ts-cloud-new","/etc/fstab")},W=()=>{for(let b of e.volumes){if(!r.existsSync(b.device)||!r.statSync(b.device).isBlockDevice())throw Error(`Volume device missing: ${b.device}`);let k=_("blkid",["-s","TYPE","-o","value",b.device]);if(!k){if(!b.allowFormat)throw Error(`Refusing to format adopted volume ${b.name}; no recognized filesystem`);S("mkfs.ext4",["-m","1",b.device]),k="ext4"}if(k!=="ext4")throw Error(`Refusing to replace ${k} filesystem on ${b.name}`);if(r.mkdirSync(b.mountPath,{recursive:!0}),v(b.mountPath)&&!R(b))throw Error(`Another filesystem occupies ${b.mountPath}`);if(!v(b.mountPath)&&r.readdirSync(b.mountPath).length)throw Error(`Refusing to hide existing files beneath ${b.mountPath}`);if(!v(b.mountPath))S("mount",["-o","noatime,nodev,nosuid",b.device,b.mountPath]);if(!R(b))throw Error(`Volume identity verification failed: ${b.name}`);S("resize2fs",[b.device]),b.allowFormat=!1}h("/etc/ts-cloud/compute-storage.json",e),V(),S("systemctl",["daemon-reload"])},{dlopen:K,read:te}=await import("bun:ffi"),Z=K("libc.so.6",{flock:{args:["i32","i32"],returns:"i32"},__errno_location:{args:[],returns:"ptr"}}),re=[],ie=(b,k=!0)=>{r.mkdirSync(n.dirname(b),{recursive:!0});let P=r.openSync(b,r.constants.O_CREAT|r.constants.O_RDWR|r.constants.O_NOFOLLOW,384);if(Z.symbols.flock(P,k?2:6)!==0){let O=te.i32(Z.symbols.__errno_location());if(r.closeSync(P),!k&&O===11)return!1;throw Error(`Could not acquire lock: ${b} (errno ${O})`)}return re.push(P),!0},oe=()=>{let b=[];for(let k of r.readdirSync("/proc").filter((P)=>/^\d+$/.test(P))){let P=[];try{P=r.readdirSync(`/proc/${k}/fd`)}catch{continue}for(let O of["cwd","exe",...P.map((D)=>`fd/${D}`)]){let D=`/proc/${k}/${O}`;try{let J=r.readlinkSync(D);if(!J.startsWith(`${e.webRoot}/`)||!J.includes("/releases/"))continue;let Y=!1;if(O.startsWith("fd/")){let X=r.readFileSync(`/proc/${k}/fdinfo/${O.slice(3)}`,"utf8").match(/^flags:\s+(\d+)/m);Y=!!X&&(Number.parseInt(X[1],8)&3)!==0&&r.statSync(D).isFile()}b.push({file:J,write:Y,device:r.statSync(D).dev})}catch{}}}return b},ne=async(b,k)=>{r.mkdirSync(b.destination,{recursive:!0});let P=["rsync","-aHAXx","--numeric-ids","--delete",...k?["--checksum"]:[],`${b.source}/`,`${b.destination}/`],D=await Bun.spawn(P,{stdout:"inherit",stderr:"inherit"}).exited;if(D!==0&&!(D===24&&!k))throw Error(`rsync failed (${D}): ${b.source}`)},pe=async()=>{let b=S("systemctl",["list-units","--type=service","--state=running","--no-legend","--plain"]).split(`
145
145
  `).map((Y)=>Y.trim().split(/\s+/)[0]).filter(Boolean),k={};if(b.length){let Y=S("systemctl",["show",...b,"-p","Id","-p","MainPID","-p","WorkingDirectory"]);for(let X of Y.split(`
146
146
 
147
- `)){let Z=Object.fromEntries(X.split(`
148
- `).filter(Boolean).map((le)=>{let E=le.indexOf("=");return[le.slice(0,E),le.slice(E+1)]}));if(Z.WorkingDirectory?.startsWith(`${e.webRoot}/`)||/^(?:mail|rpx-gateway|postgresql|mysql|redis)[@.]/.test(Z.Id??""))k[Z.Id]=Number(Z.MainPID)}}let P=new Map;if(r.existsSync("/etc/rpx/sites.d"))for(let Y of r.readdirSync("/etc/rpx/sites.d").filter((X)=>X.endsWith(".json"))){let X=JSON.parse(r.readFileSync(n.join("/etc/rpx/sites.d",Y),"utf8"));for(let Z of X.proxies??[]){if(typeof Z.to!=="string"||!/^[a-zA-Z0-9.-]+$/.test(Z.to))continue;let le=typeof Z.path==="string"&&Z.path.startsWith("/")?Z.path:"/";P.set(`${Z.to}${le}`,{domain:Z.to,path:le})}}let O=[...P.values()],D=[],J=0;return await Promise.all(Array.from({length:Math.min(8,O.length)},async()=>{while(J<O.length){let Y=O[J++],X=Bun.spawn(["curl","-sS","--max-time","12","--output","/dev/null","--write-out","%{http_code}","--resolve",`${Y.domain}:443:127.0.0.1`,`https://${Y.domain}${Y.path}`],{stdout:"pipe",stderr:"pipe"}),[Z,,le]=await Promise.all([new Response(X.stdout).text(),new Response(X.stderr).text(),X.exited]),E=Number(Z);D.push({...Y,status:E,ok:le===0&&E>=200&&E<500})}})),{routes:D.sort((Y,X)=>`${Y.domain}${Y.path}`.localeCompare(`${X.domain}${X.path}`)),services:k}},ge=()=>{let b=[q.mountPath,...T.entries.map((P)=>P.source)],k=new Set(["rpx-gateway.service",...x?.dependentUnits??[]]);for(let P of r.readdirSync("/etc/systemd/system")){if(!P.endsWith(".service"))continue;try{if(r.readFileSync(`/etc/systemd/system/${P}`,"utf8").includes(e.webRoot))k.add(P)}catch{}}for(let P of k){let O=`/etc/systemd/system/${P}.d`;r.mkdirSync(O,{recursive:!0}),r.writeFileSync(`${O}/ts-cloud-storage.conf`,`[Unit]
147
+ `)){let ee=Object.fromEntries(X.split(`
148
+ `).filter(Boolean).map((le)=>{let E=le.indexOf("=");return[le.slice(0,E),le.slice(E+1)]}));if(ee.WorkingDirectory?.startsWith(`${e.webRoot}/`)||/^(?:mail|rpx-gateway|postgresql|mysql|redis)[@.]/.test(ee.Id??""))k[ee.Id]=Number(ee.MainPID)}}let P=new Map;if(r.existsSync("/etc/rpx/sites.d"))for(let Y of r.readdirSync("/etc/rpx/sites.d").filter((X)=>X.endsWith(".json"))){let X=JSON.parse(r.readFileSync(n.join("/etc/rpx/sites.d",Y),"utf8"));for(let ee of X.proxies??[]){if(typeof ee.to!=="string"||!/^[a-zA-Z0-9.-]+$/.test(ee.to))continue;let le=typeof ee.path==="string"&&ee.path.startsWith("/")?ee.path:"/";P.set(`${ee.to}${le}`,{domain:ee.to,path:le})}}let O=[...P.values()],D=[],J=0;return await Promise.all(Array.from({length:Math.min(8,O.length)},async()=>{while(J<O.length){let Y=O[J++],X=Bun.spawn(["curl","-sS","--max-time","12","--output","/dev/null","--write-out","%{http_code}","--resolve",`${Y.domain}:443:127.0.0.1`,`https://${Y.domain}${Y.path}`],{stdout:"pipe",stderr:"pipe"}),[ee,,le]=await Promise.all([new Response(X.stdout).text(),new Response(X.stderr).text(),X.exited]),E=Number(ee);D.push({...Y,status:E,ok:le===0&&E>=200&&E<500})}})),{routes:D.sort((Y,X)=>`${Y.domain}${Y.path}`.localeCompare(`${X.domain}${X.path}`)),services:k}},ge=()=>{let b=[q.mountPath,...T.entries.map((P)=>P.source)],k=new Set(["rpx-gateway.service",...x?.dependentUnits??[]]);for(let P of r.readdirSync("/etc/systemd/system")){if(!P.endsWith(".service"))continue;try{if(r.readFileSync(`/etc/systemd/system/${P}`,"utf8").includes(e.webRoot))k.add(P)}catch{}}for(let P of k){let O=`/etc/systemd/system/${P}.d`;r.mkdirSync(O,{recursive:!0}),r.writeFileSync(`${O}/ts-cloud-storage.conf`,`[Unit]
149
149
  RequiresMountsFor=${b.join(" ")}
150
150
  `)}S("systemctl",["daemon-reload"])};try{let b=[...new Set([...x?.locks??[],"/run/lock/ts-cloud-host-cleanup.lock"])];if(f==="reclaim"){for(let E of["/run/lock/ts-cloud-compute-storage.lock",...b])if(!ie(E,!1))return console.log(`Deferring deployment storage reclamation; lock busy: ${E}`),{deferred:!0,lock:E}}else ie("/run/lock/ts-cloud-compute-storage.lock");T=g("/var/lib/ts-cloud/compute-storage-state.json",{entries:[]});let k=g("/etc/ts-cloud/compute-storage.json",null);if(k){for(let E of k.volumes)if(!e.volumes.some((N)=>N.id===E.id&&N.key===E.key&&N.mountPath===E.mountPath))throw Error(`Refusing to remove or relocate managed volume ${E.name}; migrate its data explicitly first`);if(T.entries.length&&(k.deploymentStorage?.volume!==x?.volume||k.deploymentStorage?.includeBackups!==!1!==(x?.includeBackups!==!1)))throw Error("Refusing to change an active deployment-storage policy; migrate its data explicitly first")}if(f==="apply")W();for(let E of e.volumes)if(!R(E))throw Error(`Required volume is not mounted: ${E.name}`);if(!x||!q)return{volumes:e.volumes};if(f==="ensure-site"){let[E,N]=t.slice(1);if(!E?.startsWith(`${e.webRoot}/`)||!/^[\w-]+$/.test(n.basename(E))||E.includes("..")||!/^[\w-]+$/.test(N??""))throw Error("Invalid deployment site path or project slug");if(r.mkdirSync(n.join(E,"releases"),{recursive:!0}),x.includeBackups!==!1)r.mkdirSync(n.join(e.webRoot,`${N}-shared`,"backups"),{recursive:!0})}let P=(f==="reclaim"?[]:H(f==="ensure-site"?t[1]:void 0,t[2])).filter((E)=>!T.entries.some((N)=>N.source===E.source));for(let E of T.entries)if(!v(E.source)||!y(E.source,E.destination))throw Error(`Recorded deployment mount is missing: ${E.source}`);if(!P.length&&f==="ensure-site")return{inherited:!0,volume:q.name};if(!P.length&&f==="apply"){ge();let E=I();return h("/var/lib/ts-cloud/compute-storage-status.json",E),console.log(JSON.stringify(E)),E}if(!x.migrateExisting&&P.some((E)=>r.readdirSync(E.source).length>0))throw Error("Existing deployments require deploymentStorage.migrateExisting: true");if(P.length){let E=S("du",["-scx","--block-size=1",...P.map((he)=>he.source)]).trim().split(`
151
- `).at(-1)?.split(/\s+/)[0],N=r.statfsSync(q.mountPath);if(Number(E)>N.bavail*N.bsize)throw Error("Insufficient free volume capacity for a verified deployment copy")}if(!r.existsSync("/run/ts-cloud-root-web"))r.mkdirSync("/run/ts-cloud-root-web");if(!v("/run/ts-cloud-root-web"))S("mount",["--bind",e.webRoot,"/run/ts-cloud-root-web"]);S("mount",["--make-private","/run/ts-cloud-root-web"]);let O=r.statSync(e.webRoot).dev;for(let E of T.entries){let N=n.join("/run/ts-cloud-root-web",n.relative(e.webRoot,E.source));if(r.existsSync(N)&&(r.statSync(N).dev!==O||y(N,E.destination)))throw Error(`Root recovery view contains a deployment mount: ${N}`)}for(let E=0;E<P.length;E++){if(v(P[E].source)&&y(P[E].source,P[E].destination))continue;console.log(`copy ${E+1}/${P.length}: ${P[E].source}`),await re(P[E],!1)}if(f!=="reclaim")for(let E of b)ie(E);for(let E of r.readdirSync(e.webRoot,{withFileTypes:!0}).filter((N)=>N.isDirectory()).sort((N,he)=>N.name.localeCompare(he.name)))ie(n.join(e.webRoot,E.name,".ts-cloud/deploy.lock"));for(let E of f==="reclaim"?[]:H(f==="ensure-site"?t[1]:void 0,t[2]))if(!T.entries.some((N)=>N.source===E.source)&&!P.some((N)=>N.source===E.source))P.push(E);if(P.length)console.log("Checking application services and HTTPS routes before activation");let D=P.length?await pe():void 0;if(D)h("/var/lib/ts-cloud/compute-storage-health-before.json",D);let J=oe().filter((E)=>E.write);if(J.length)throw Error(`Live writable files must be shared before migration: ${J.map((E)=>E.file).join(", ")}`);let Y={entries:[...T.entries],fstab:r.readFileSync("/etc/fstab","utf8")};if(P.length)S("sync",[]);let X=[];try{for(let E=0;E<P.length;E++){let N=P[E];if(v(N.source)){if(!y(N.source,N.destination))throw Error(`Unrecorded mount occupies ${N.source}`);T.entries.push(N),h("/var/lib/ts-cloud/compute-storage-state.json",T);continue}if(console.log(`verify and mount ${E+1}/${P.length}: ${N.source}`),await re(N,!0),S("mount",["--bind",N.destination,N.source]),!y(N.source,N.destination))throw Error(`Bind verification failed: ${N.source}`);X.push(N),T.entries.push(N),h("/var/lib/ts-cloud/compute-storage-state.json",T),V()}if(V(),S("findmnt",["--verify"]),T.activatedAt=new Date().toISOString(),h("/var/lib/ts-cloud/compute-storage-state.json",T),ge(),D){console.log("Checking application services and HTTPS routes after activation");let E=await pe();h("/var/lib/ts-cloud/compute-storage-health-after.json",E);let N=D.routes.filter((ae)=>ae.ok&&!E.routes.some((_e)=>_e.domain===ae.domain&&_e.path===ae.path&&_e.ok)),he=Object.keys(D.services).filter((ae)=>!E.services[ae]);if(N.length||he.length)throw Error(`Application verification failed: ${N.map((ae)=>ae.domain+ae.path).concat(he).join(", ")}`);console.log(`Verified ${E.routes.length} routes and ${Object.keys(E.services).length} services`)}}catch(E){let N=[];for(let he of X.reverse())try{S("umount",[he.source])}catch{N.push(he),console.error(`Rollback mount busy, original data retained: ${he.source}`)}if(T.entries=[...Y.entries,...N],r.writeFileSync("/etc/fstab",Y.fstab),N.length)V();throw h("/var/lib/ts-cloud/compute-storage-state.json",T),S("systemctl",["daemon-reload"]),E}let Z=oe().filter((E)=>E.device===O).map((E)=>E.file);for(let E of T.entries){if(!v(E.source)||!y(E.source,E.destination))throw Error(`Lost deployment mount: ${E.source}`);let N=n.join("/run/ts-cloud-root-web",n.relative(e.webRoot,E.source));if(!r.existsSync(N))continue;if(r.statSync(N).dev!==O||y(N,E.destination))throw Error(`Refusing to clean a deployment volume through the root recovery view: ${N}`);let he="";try{he=n.basename(r.realpathSync(n.join(n.dirname(E.source),"current")))}catch{}for(let ae of r.readdirSync(N,{withFileTypes:!0})){let _e=n.join(N,ae.name);if(n.basename(E.source)==="backups"){if(ae.isFile()&&r.existsSync(n.join(E.destination,ae.name)))r.unlinkSync(_e)}else if(ae.isDirectory()&&!ae.isSymbolicLink()&&ae.name!==he&&!Z.some((Rt)=>Rt===n.join(E.source,ae.name)||Rt.startsWith(`${n.join(E.source,ae.name)}/`)))r.rmSync(_e,{recursive:!0})}}S("sync",[]);let le=I();return h("/var/lib/ts-cloud/compute-storage-status.json",le),console.log(JSON.stringify(le)),le}finally{for(let b of ne.reverse())te.symbols.flock(b,8),r.closeSync(b);te.close()}}var Sn="/etc/ts-cloud/compute-storage.json",Ke="/usr/local/lib/ts-cloud/compute-storage.mjs";function ei(e,t){let r=Object.entries(e.infrastructure?.compute?.volumes??{}).map(([s,i])=>{if(!/^[a-z][a-z0-9-]*$/.test(s))throw Error(`Invalid compute volume key: ${s}`);if(!Number.isInteger(i.size)||i.size<10||i.size>10240)throw Error(`compute.volumes.${s}.size must be a whole number from 10 to 10240 GB`);if(!i.mountPath.startsWith("/")||!i.mountPath.slice(1).split("/").every((c)=>/^[\w-]+$/.test(c))||i.mountPath==="/var"||i.mountPath==="/var/lib"||["/etc","/usr","/var/www","/root","/boot","/dev","/proc","/sys","/run","/bin","/sbin","/lib"].some((c)=>i.mountPath===c||i.mountPath.startsWith(`${c}/`)))throw Error(`Unsafe compute volume mount path: ${i.mountPath}`);let a=i.name??`${e.project.slug}-${t}-${s}`;if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(a))throw Error(`Invalid compute volume name: ${a}`);return{...i,key:s,name:a,mountPath:i.mountPath.replace(/\/+$/,"")}});for(let s of r)if(r.some((i)=>i!==s&&(i.name===s.name||i.mountPath===s.mountPath||i.mountPath.startsWith(`${s.mountPath}/`))))throw Error("Compute volumes must have distinct names and non-overlapping mount paths");let n=e.infrastructure?.compute?.deploymentStorage;for(let s of n?.locks??[])if(!s.startsWith("/run/lock/")||!s.slice(10).split("/").every((i)=>/^[\w.-]+$/.test(i)&&i!=="."&&i!=="..")||s==="/run/lock/ts-cloud-compute-storage.lock")throw Error(`Invalid deployment storage lock: ${s}`);for(let s of n?.dependentUnits??[])if(!/^[\w@.-]+\.service$/.test(s))throw Error(`Invalid deployment storage dependent unit: ${s}`);if(n&&!r.some((s)=>s.key===n.volume))throw Error(`deploymentStorage.volume references an undeclared compute volume: ${n.volume}`);return r}function dr(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function ti(e){let t=`${Sn}.candidate`,r=`#!/usr/bin/env bun
151
+ `).at(-1)?.split(/\s+/)[0],N=r.statfsSync(q.mountPath);if(Number(E)>N.bavail*N.bsize)throw Error("Insufficient free volume capacity for a verified deployment copy")}if(!r.existsSync("/run/ts-cloud-root-web"))r.mkdirSync("/run/ts-cloud-root-web");if(!v("/run/ts-cloud-root-web"))S("mount",["--bind",e.webRoot,"/run/ts-cloud-root-web"]);S("mount",["--make-private","/run/ts-cloud-root-web"]);let O=r.statSync(e.webRoot).dev;for(let E of T.entries){let N=n.join("/run/ts-cloud-root-web",n.relative(e.webRoot,E.source));if(r.existsSync(N)&&(r.statSync(N).dev!==O||y(N,E.destination)))throw Error(`Root recovery view contains a deployment mount: ${N}`)}for(let E=0;E<P.length;E++){if(v(P[E].source)&&y(P[E].source,P[E].destination))continue;console.log(`copy ${E+1}/${P.length}: ${P[E].source}`),await ne(P[E],!1)}if(f!=="reclaim")for(let E of b)ie(E);for(let E of r.readdirSync(e.webRoot,{withFileTypes:!0}).filter((N)=>N.isDirectory()).sort((N,he)=>N.name.localeCompare(he.name)))ie(n.join(e.webRoot,E.name,".ts-cloud/deploy.lock"));for(let E of f==="reclaim"?[]:H(f==="ensure-site"?t[1]:void 0,t[2]))if(!T.entries.some((N)=>N.source===E.source)&&!P.some((N)=>N.source===E.source))P.push(E);if(P.length)console.log("Checking application services and HTTPS routes before activation");let D=P.length?await pe():void 0;if(D)h("/var/lib/ts-cloud/compute-storage-health-before.json",D);let J=oe().filter((E)=>E.write);if(J.length)throw Error(`Live writable files must be shared before migration: ${J.map((E)=>E.file).join(", ")}`);let Y={entries:[...T.entries],fstab:r.readFileSync("/etc/fstab","utf8")};if(P.length)S("sync",[]);let X=[];try{for(let E=0;E<P.length;E++){let N=P[E];if(v(N.source)){if(!y(N.source,N.destination))throw Error(`Unrecorded mount occupies ${N.source}`);T.entries.push(N),h("/var/lib/ts-cloud/compute-storage-state.json",T);continue}if(console.log(`verify and mount ${E+1}/${P.length}: ${N.source}`),await ne(N,!0),S("mount",["--bind",N.destination,N.source]),!y(N.source,N.destination))throw Error(`Bind verification failed: ${N.source}`);X.push(N),T.entries.push(N),h("/var/lib/ts-cloud/compute-storage-state.json",T),V()}if(V(),S("findmnt",["--verify"]),T.activatedAt=new Date().toISOString(),h("/var/lib/ts-cloud/compute-storage-state.json",T),ge(),D){console.log("Checking application services and HTTPS routes after activation");let E=await pe();h("/var/lib/ts-cloud/compute-storage-health-after.json",E);let N=D.routes.filter((ae)=>ae.ok&&!E.routes.some((_e)=>_e.domain===ae.domain&&_e.path===ae.path&&_e.ok)),he=Object.keys(D.services).filter((ae)=>!E.services[ae]);if(N.length||he.length)throw Error(`Application verification failed: ${N.map((ae)=>ae.domain+ae.path).concat(he).join(", ")}`);console.log(`Verified ${E.routes.length} routes and ${Object.keys(E.services).length} services`)}}catch(E){let N=[];for(let he of X.reverse())try{S("umount",[he.source])}catch{N.push(he),console.error(`Rollback mount busy, original data retained: ${he.source}`)}if(T.entries=[...Y.entries,...N],r.writeFileSync("/etc/fstab",Y.fstab),N.length)V();throw h("/var/lib/ts-cloud/compute-storage-state.json",T),S("systemctl",["daemon-reload"]),E}let ee=oe().filter((E)=>E.device===O).map((E)=>E.file);for(let E of T.entries){if(!v(E.source)||!y(E.source,E.destination))throw Error(`Lost deployment mount: ${E.source}`);let N=n.join("/run/ts-cloud-root-web",n.relative(e.webRoot,E.source));if(!r.existsSync(N))continue;if(r.statSync(N).dev!==O||y(N,E.destination))throw Error(`Refusing to clean a deployment volume through the root recovery view: ${N}`);let he="";try{he=n.basename(r.realpathSync(n.join(n.dirname(E.source),"current")))}catch{}for(let ae of r.readdirSync(N,{withFileTypes:!0})){let _e=n.join(N,ae.name);if(n.basename(E.source)==="backups"){if(ae.isFile()&&r.existsSync(n.join(E.destination,ae.name)))r.unlinkSync(_e)}else if(ae.isDirectory()&&!ae.isSymbolicLink()&&ae.name!==he&&!ee.some((Rt)=>Rt===n.join(E.source,ae.name)||Rt.startsWith(`${n.join(E.source,ae.name)}/`)))r.rmSync(_e,{recursive:!0})}}S("sync",[]);let le=I();return h("/var/lib/ts-cloud/compute-storage-status.json",le),console.log(JSON.stringify(le)),le}finally{for(let b of re.reverse())Z.symbols.flock(b,8),r.closeSync(b);Z.close()}}var Sn="/etc/ts-cloud/compute-storage.json",Ke="/usr/local/lib/ts-cloud/compute-storage.mjs";function ei(e,t){let r=Object.entries(e.infrastructure?.compute?.volumes??{}).map(([s,i])=>{if(!/^[a-z][a-z0-9-]*$/.test(s))throw Error(`Invalid compute volume key: ${s}`);if(!Number.isInteger(i.size)||i.size<10||i.size>10240)throw Error(`compute.volumes.${s}.size must be a whole number from 10 to 10240 GB`);if(!i.mountPath.startsWith("/")||!i.mountPath.slice(1).split("/").every((c)=>/^[\w-]+$/.test(c))||i.mountPath==="/var"||i.mountPath==="/var/lib"||["/etc","/usr","/var/www","/root","/boot","/dev","/proc","/sys","/run","/bin","/sbin","/lib"].some((c)=>i.mountPath===c||i.mountPath.startsWith(`${c}/`)))throw Error(`Unsafe compute volume mount path: ${i.mountPath}`);let a=i.name??`${e.project.slug}-${t}-${s}`;if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(a))throw Error(`Invalid compute volume name: ${a}`);return{...i,key:s,name:a,mountPath:i.mountPath.replace(/\/+$/,"")}});for(let s of r)if(r.some((i)=>i!==s&&(i.name===s.name||i.mountPath===s.mountPath||i.mountPath.startsWith(`${s.mountPath}/`))))throw Error("Compute volumes must have distinct names and non-overlapping mount paths");let n=e.infrastructure?.compute?.deploymentStorage;for(let s of n?.locks??[])if(!s.startsWith("/run/lock/")||!s.slice(10).split("/").every((i)=>/^[\w.-]+$/.test(i)&&i!=="."&&i!=="..")||s==="/run/lock/ts-cloud-compute-storage.lock")throw Error(`Invalid deployment storage lock: ${s}`);for(let s of n?.dependentUnits??[])if(!/^[\w@.-]+\.service$/.test(s))throw Error(`Invalid deployment storage dependent unit: ${s}`);if(n&&!r.some((s)=>s.key===n.volume))throw Error(`deploymentStorage.volume references an undeclared compute volume: ${n.volume}`);return r}function dr(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function ti(e){let t=`${Sn}.candidate`,r=`#!/usr/bin/env bun
152
152
  await (${Is.toString()})(JSON.parse(await Bun.file(process.env.TS_CLOUD_STORAGE_POLICY || ${JSON.stringify(Sn)}).text()), process.argv.slice(2));
153
153
  `;return['command -v bun >/dev/null 2>&1 || { echo "Configured compute storage requires Bun on the host" >&2; exit 1; }',"install -d -m 0755 /etc/ts-cloud /usr/local/lib/ts-cloud /var/lib/ts-cloud",`printf %s ${dr(Buffer.from(r).toString("base64"))} | base64 -d > ${Ke}.new`,`chmod 0755 ${Ke}.new && mv ${Ke}.new ${Ke}`,`printf %s ${dr(JSON.stringify(e))} > ${t}`,`chmod 0644 ${t}`,`TS_CLOUD_STORAGE_POLICY=${t} bun ${Ke} apply 2>&1 | tee /var/log/ts-cloud-compute-storage.log`,`rm -f ${t}`,"cat > /etc/systemd/system/ts-cloud-storage-check.service <<'TS_CLOUD_STORAGE_SERVICE'","[Unit]","Description=Check configured compute storage and deployment mounts","[Service]","Type=oneshot",`ExecStart=/usr/local/bin/bun ${Ke} check`,"TS_CLOUD_STORAGE_SERVICE","cat > /etc/systemd/system/ts-cloud-storage-check.timer <<'TS_CLOUD_STORAGE_TIMER'","[Unit]","Description=Check compute storage every minute","[Timer]","OnBootSec=2min","OnUnitActiveSec=1min","[Install]","WantedBy=timers.target","TS_CLOUD_STORAGE_TIMER","systemctl daemon-reload","systemctl enable --now ts-cloud-storage-check.timer","cat > /etc/systemd/system/ts-cloud-storage-reclaim.service <<'TS_CLOUD_RECLAIM_SERVICE'","[Unit]","Description=Reclaim inactive root copies of volume-backed deployments","[Service]","Type=oneshot",`ExecStart=/usr/local/bin/bun ${Ke} reclaim`,"Nice=19","IOSchedulingClass=idle","TS_CLOUD_RECLAIM_SERVICE","cat > /etc/systemd/system/ts-cloud-storage-reclaim.timer <<'TS_CLOUD_RECLAIM_TIMER'","[Unit]","Description=Reclaim retired deployment copies hourly","[Timer]","OnCalendar=hourly","RandomizedDelaySec=5min","Persistent=true","[Install]","WantedBy=timers.target","TS_CLOUD_RECLAIM_TIMER","systemctl daemon-reload","systemctl enable --now ts-cloud-storage-reclaim.timer"]}function Mr(e,t){return[`if [ -f ${Sn} ]; then bun ${Ke} ensure-site ${dr(e)} ${dr(t)}; fi`]}import{createHash as Qa}from"node:crypto";function pt(e){if(!/^[a-z0-9][a-z0-9-]*$/.test(e))throw Error("Runtime isolation requires a safe project slug");return`tsc-${e.length<=24?e:`${e.slice(0,15)}-${Qa("sha256").update(e).digest("hex").slice(0,8)}`}`}function Ut(e,t,r){return[`User=${e}`,`Group=${e}`,"NoNewPrivileges=true","PrivateTmp=true","ProtectHome=true","ProtectProc=invisible","InaccessiblePaths=-/run/postgresql -/var/run/postgresql","TemporaryFileSystem=/var/www:ro",`BindPaths=${t} -/var/www/${r}-shared`,"UMask=0077",`Environment=HOME=/var/lib/ts-cloud/${e}`]}function Ls(e,t,r){let n=pt(e);if(!t.startsWith(`/var/www/${e}-`)||t.slice(9).includes("/"))throw Error("Runtime isolation requires a project-namespaced application directory");let s=`/var/lib/ts-cloud/${n}`,i=`/var/www/${e}-shared`,a=[...new Set([t,...r])];for(let c of a)if(!/^\/[a-zA-Z0-9_./-]+$/.test(c)||c.split("/").includes("..")||!(c===t||c.startsWith(`${t}/`)||c===i||c.startsWith(`${i}/`)))throw Error(`Runtime isolation cannot take ownership outside project ${e}`);return[`if ! id -u ${n} >/dev/null 2>&1; then useradd --system --user-group --create-home --home-dir ${s} --shell /usr/sbin/nologin ${n}; fi`,`[ "$(id -u ${n})" != 0 ] && [ "$(getent passwd ${n} | cut -d: -f6)" = ${s} ] || { echo 'Unexpected runtime isolation identity' >&2; exit 1; }`,`install -d -m 700 -o ${n} -g ${n} ${s}`,...a.map((c)=>`chown -hR ${n}:${n} ${c}`),`chmod 750 ${t}`]}function fr(e){return Object.entries(e).map(([t,r])=>`${t}=${ec(String(r))}`).join(`
154
154
  `)}function ec(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}var gr=["storage",".env"],Ht=4;function Ue(e){return`${e.replace(/\/+$/,"")}/.ts-cloud`}function tc(e){return`${Ue(e)}/deploy-history.log`}function rc(e,t){return`${Ue(e)}/deploys/${t}.log`}function Us(e){return`${Ue(e)}/shared-paths`}function hr(e){return`${e.shared}/stx-images`}function Mt(e){return`${e.shared}/stx-bundles`}function Zt(e,t){let r=e.replace(/\/+$/,"");return{base:r,releases:`${r}/releases`,shared:`${r}/shared`,current:`${r}/current`,release:`${r}/releases/${t}`}}function ks(e){let t=e.split("/").pop()||e;if(t===".env"||t.startsWith(".env."))return!0;return/\.[a-z0-9]+$/i.test(t)}function _n(e){return typeof e==="string"?e:e.path}function Hs(e){let t=new Map;for(let r of e)t.set(_n(r),r);return[...t.values()]}function Ns(e,t){if(typeof t==="string")return{path:t,target:`${e.shared}/${t}`,seed:!0};return{path:t.path,target:t.target??`${e.shared}/${t.path}`,seed:t.seed!==!1}}function nc(e){return["ts_cloud_adopt_shared() {",' TS_CLOUD_SP="$1"',' TS_CLOUD_DST="$2"',` TS_CLOUD_SRC="${e.current}/$TS_CLOUD_SP"`,' if [ -e "$TS_CLOUD_DST" ]; then return 0; fi',' if [ -L "$TS_CLOUD_SRC" ] || [ ! -e "$TS_CLOUD_SRC" ]; then return 0; fi',' mkdir -p "$(dirname "$TS_CLOUD_DST")"',' cp -a "$TS_CLOUD_SRC" "$TS_CLOUD_DST"'," for TS_CLOUD_SIDECAR in -wal -shm; do",' if [ -f "$TS_CLOUD_SRC$TS_CLOUD_SIDECAR" ]; then cp -a "$TS_CLOUD_SRC$TS_CLOUD_SIDECAR" "$TS_CLOUD_DST$TS_CLOUD_SIDECAR"; fi'," done",' echo "[ts-cloud] adopted $TS_CLOUD_SP from the live release into shared/ — it now survives deploys"'," return 0","}"]}function Ft(e,t=gr){let r=[`mkdir -p ${e.releases} ${e.shared} ${hr(e)} ${Mt(e)}`,...nc(e)],n=t.map((i)=>Ns(e,i));for(let{path:i,target:a,seed:c}of n){if(!c)continue;if(r.push(`ts_cloud_adopt_shared '${i}' '${a}'`),ks(i))r.push(`mkdir -p "$(dirname ${a})"`,`touch ${a}`);else if(i==="storage")r.push(`mkdir -p ${a}/app/public`,`mkdir -p ${a}/framework/cache/data`,`mkdir -p ${a}/framework/sessions`,`mkdir -p ${a}/framework/testing`,`mkdir -p ${a}/framework/views`,`mkdir -p ${a}/logs`);else r.push(`mkdir -p ${a}`)}let s=Us(e.base);return r.push(`mkdir -p ${Ue(e.base)}`,`cat > ${s} <<'TS_CLOUD_SHARED_PATHS_EOF'`,...n.map((i)=>`${i.path} ${i.target}`),"TS_CLOUD_SHARED_PATHS_EOF"),r}function vn(e,t=900){let r=`${Ue(e.base)}/deploy.lock`;return[`mkdir -p "$(dirname ${r})"`,`exec 9>${r}`,`flock -w ${t} 9 || { echo "[ts-cloud] another deploy of this site has held the lock for ${t}s — refusing to race it" >&2; exit 1; }`]}function $n(e){let t=`${e.release}.incoming`;return[`rm -rf ${t}`,`mkdir -p ${t}`,...sc(e),'if [ "$TS_CLOUD_IS_LIVE" = "yes" ]; then',` TS_CLOUD_STAGED=${t}`,"else",` rm -rf ${e.release}`,` mkdir -p ${e.release}`,` rmdir ${t}`,` TS_CLOUD_STAGED=${e.release}`,"fi"]}function yn(e){let t=`TS_CLOUD_TRAP_LIVE="$(readlink -f ${e.current} 2>/dev/null || true)"`,r=`TS_CLOUD_TRAP_TARGET="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`;return`trap '${`if [ $? -ne 0 ]; then ${t}; ${r}; [ "$TS_CLOUD_TRAP_LIVE" = "$TS_CLOUD_TRAP_TARGET" ] || rm -rf ${e.release}; fi`}' EXIT`}function sc(e){return[`TS_CLOUD_LIVE_PATH="$(readlink -f ${e.current} 2>/dev/null || true)"`,`TS_CLOUD_RELEASE_PATH="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`,'if [ -n "$TS_CLOUD_LIVE_PATH" ] && [ "$TS_CLOUD_LIVE_PATH" = "$TS_CLOUD_RELEASE_PATH" ]; then TS_CLOUD_IS_LIVE=yes; else TS_CLOUD_IS_LIVE=no; fi']}function bn(e){let t=`${e.release}.incoming`;return[`if [ "$TS_CLOUD_STAGED" = "${t}" ]; then`,` rm -rf ${e.release}.previous`,` mv ${e.release} ${e.release}.previous`,` mv ${t} ${e.release}`,` rm -rf ${e.release}.previous`,"fi"]}function oc(e,t){return[`if [ -f ${e} ] && [ ! -L ${e} ] && [ -s ${e} ] && [ ! -s ${t} ]; then`,` cp -a ${e} ${t}`,` echo "[ts-cloud] seeded shared/ from the release's own copy of the file"`,"fi"]}function Sr(e,t=gr){let r=[];for(let n of t){let{path:s,target:i,seed:a}=Ns(e,n),c=`${e.release}/${s}`,f=[`rm -rf ${c}`,`mkdir -p "$(dirname ${c})"`,`ln -sfn ${i} ${c}`];if(a){if(s!==".env"&&ks(s))r.push(...oc(c,i));r.push(...f);continue}r.push(`if [ -e ${i} ]; then`,...f.map((g)=>` ${g}`),"fi")}return r}function ic(e,t){let r=Us(e.base);return[`if [ -f ${r} ]; then`,' while IFS="\t" read -r TS_CLOUD_SP TS_CLOUD_TGT; do',' [ -n "$TS_CLOUD_SP" ] || continue',` [ -n "$TS_CLOUD_TGT" ] || TS_CLOUD_TGT="${e.shared}/$TS_CLOUD_SP"`,' [ -e "$TS_CLOUD_TGT" ] || continue',` rm -rf ${t}/"$TS_CLOUD_SP"`,` mkdir -p "$(dirname ${t}/"$TS_CLOUD_SP")"`,` ln -sfn "$TS_CLOUD_TGT" ${t}/"$TS_CLOUD_SP"`,` done < ${r}`,"fi"]}function dt(e){return[`ln -sfn ${e.release} ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`]}function Tn(e){return`${Ue(e)}/previous-release`}function wn(e,t="TS_CLOUD_PREV_CURRENT"){let r=Tn(e.base);return[`if [ -n "\${${t}:-}" ] && [ -d "$${t}" ] && [ "$(readlink -f "$${t}")" != "$(readlink -f ${e.release})" ]; then mkdir -p ${Ue(e.base)}; basename "$${t}" > ${r}; fi`]}function Ms(e,t){let r=Tn(e.base);return[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,...t?[`TS_CLOUD_RB_TARGET=${e.releases}/${t}`]:["TS_CLOUD_RB_TARGET=",`if [ -f ${r} ]; then TS_CLOUD_REC="${e.releases}/$(cat ${r})"; if [ -d "$TS_CLOUD_REC" ] && [ "$(readlink -f "$TS_CLOUD_REC")" != "$TS_CLOUD_CURRENT" ]; then TS_CLOUD_RB_TARGET="$TS_CLOUD_REC"; fi; fi`,`[ -n "$TS_CLOUD_RB_TARGET" ] || TS_CLOUD_RB_TARGET=$(ls -1dt ${e.releases}/*/ 2>/dev/null | sed 's#/$##' | while read -r r; do [ "$(readlink -f "$r")" != "$TS_CLOUD_CURRENT" ] && { echo "$r"; break; }; done)`],'[ -n "$TS_CLOUD_RB_TARGET" ] && [ -d "$TS_CLOUD_RB_TARGET" ] || { echo "no release to roll back to (looked for ${TS_CLOUD_RB_TARGET:-a previous release})" >&2; exit 1; }','[ "$(readlink -f "$TS_CLOUD_RB_TARGET")" != "$TS_CLOUD_CURRENT" ] || { echo "$(basename "$TS_CLOUD_RB_TARGET") is already the live release" >&2; exit 1; }','TS_CLOUD_RB_ID=$(basename "$TS_CLOUD_RB_TARGET")']}function $g(e,t={}){return[...Ms(e,t.to),'echo "would roll back from $(basename "${TS_CLOUD_CURRENT:-none}") to $TS_CLOUD_RB_ID (dry run: nothing changed)"']}function Mg(e,t={}){let r=Math.max(1,t.gateSeconds??5),n=t.systemdDir??"/etc/systemd/system",s=[`ln -sfn "$TS_CLOUD_RB_TARGET" ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`,`rm -f ${Tn(e.base)}`,'echo "rolled back to $TS_CLOUD_RB_ID"'],i=[...Ms(e,t.to),...ic(e,'"$TS_CLOUD_RB_TARGET"')];if(!t.unitBase)return[...i,...s];let a=t.unitBase,c=`${a}@\${TS_CLOUD_RB_ID}.service`;return[...i,`if [ -f ${n}/${a}@.service ]; then`,` systemctl start "${c}"`,` for TS_CLOUD_I in $(seq 1 ${r}); do sleep 1; systemctl is-active --quiet "${c}" || { echo "the release rolled back to, $TS_CLOUD_RB_ID, did not stay up; the current release keeps serving" >&2; journalctl -u "${c}" -n 30 --no-pager >&2 || true; systemctl stop "${c}" 2>/dev/null || true; exit 1; }; done`,...s.map((f)=>` ${f}`),` systemctl enable "${c}" 2>/dev/null || true`,` systemctl list-units --plain --no-legend --type=service "${a}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v "^${a}@\${TS_CLOUD_RB_ID}.service$" || true; } | while read -r TS_CLOUD_U; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done`,`elif [ -f ${n}/${a}.service ]; then`,...s.map((f)=>` ${f}`),` systemctl restart ${a}.service`,"else",...s.map((f)=>` ${f}`),"fi"]}function mt(e,t=4){let r=Math.max(1,t);return[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,`ls -1dt ${e.releases}/*/ 2>/dev/null | sed 's#/$##' | tail -n +${r+1} | while read -r TS_CLOUD_OLD; do`,' [ "$(readlink -f "$TS_CLOUD_OLD")" = "$TS_CLOUD_CURRENT" ] || rm -rf "$TS_CLOUD_OLD"',"done"]}function ac(e){return`${Ue(e)}/owner`}function Cn(e,t){let r=ac(e);return[`if [ -f "${r}" ]; then`,` TS_CLOUD_OWNER=$(cat "${r}")`,` if [ "$TS_CLOUD_OWNER" != "${t}" ]; then`,` echo "[ts-cloud] REFUSING deploy: ${e} belongs to project '$TS_CLOUD_OWNER', not '${t}'. Another project on this box derives the same site key — give one of them a distinct site name/domain, or remove ${r} to transfer ownership." >&2`," exit 1"," fi","else",` mkdir -p "$(dirname "${r}")"`,` printf '%s\\n' "${t}" > "${r}"`,"fi"]}function vr(e,t){let r=Ue(e),n=rc(e,t.releaseId),s=tc(e),i=Math.max(1,t.keepLogs??20),a=t.commit||"",c=t.branch||"";return[`mkdir -p ${r}/deploys`,`exec > >(tee -a ${n}) 2>&1`,`echo "[ts-cloud] deploy ${t.releaseId} commit=${a} branch=${c} starting $(date -u +%Y-%m-%dT%H:%M:%SZ)"`,"ts_cloud_record_deploy() {"," TS_CLOUD_RC=$?",' if [ "$TS_CLOUD_RC" -eq 0 ]; then TS_CLOUD_ST=success; else TS_CLOUD_ST=failed; fi',` printf '%s\\t%s\\t%s\\t%s\\trc=%s\\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "${t.releaseId}" "${a}" "$TS_CLOUD_ST" "$TS_CLOUD_RC" >> ${s}`,"}","trap ts_cloud_record_deploy EXIT",`ls -1t ${r}/deploys/*.log 2>/dev/null | tail -n +${i+1} | while read -r TS_CLOUD_OLDLOG; do rm -f "$TS_CLOUD_OLDLOG"; done`]}var cc=new Set(["sqlite","sqlite3"]),lc=new Set([":memory:","memory"]);function uc(e){let t=e?.DB_CONNECTION?.trim().toLowerCase();return t!=null&&cc.has(t)}function pc(e){let t=e.trim().replace(/^\.\//,"");if(t===""||t.startsWith("/")||t.startsWith("~"))return;if(t.split("/").includes(".."))return;return t.replace(/\/+$/,"")}function Pn(e,t=[]){if(!uc(e))return{};let r=e?.DB_DATABASE_PATH?.trim()||e?.DB_DATABASE?.trim();if(r&&lc.has(r.toLowerCase()))return{};if(!r)return{warning:"DB_CONNECTION is sqlite but neither DB_DATABASE_PATH nor DB_DATABASE names a file, so ts-cloud cannot tell where the database lives. If it is written inside the release directory, the next deploy discards it. Set DB_DATABASE_PATH, or list the file in the site's `sharedPaths`."};let n=pc(r);if(!n)return{};if(t.some((s)=>_n(s)===n))return{};return{path:n}}function yr(e,t=[]){let{path:r}=Pn(e,t);return r?[r]:[]}var Fr="/var/ts-cloud/artifacts",Uh="/usr/local/bin/ts-cloud-host-cleanup.sh",Qh="ts-cloud-host-cleanup";var Fg=Object.freeze({stagingMaxAgeMinutes:60,artifactMaxAgeDays:2,artifactUploadMaxAgeMinutes:60,bunCacheMaxAgeDays:7,journalMaxAgeDays:14,journalMaxSizeMb:512,containerImageMaxAgeHours:168}),Ug=Object.freeze({artifactMaxAgeDays:0,bunCacheMaxAgeDays:1,journalMaxAgeDays:3,journalMaxSizeMb:256,containerImageMaxAgeHours:24}),Hh=50,Gh=85,Vh="daily";function Fs(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function et(e,t,r=0){if(!Number.isInteger(t)||t<r)throw Error(`hostCleanup: ${e} must be a whole number >= ${r} (got ${t})`)}function zs(e,t){for(let[r,n]of Object.entries(t))et(`${e}.${r}`,n);et(`${e}.stagingMaxAgeMinutes`,t.stagingMaxAgeMinutes,15),et(`${e}.artifactUploadMaxAgeMinutes`,t.artifactUploadMaxAgeMinutes,15),et(`${e}.journalMaxSizeMb`,t.journalMaxSizeMb,1)}function dc(e,t){let r=`hostCleanup.paths[${t}]`,n=e.path?.replace(/\/+$/,"")??"";if(!n.startsWith("/")||n===""||/[\s'"`$\\]/.test(n)||n.split("/").includes(".."))throw Error(`${r}.path must be an absolute directory with no spaces, quotes or '..' (got ${JSON.stringify(e.path)})`);if(n==="/var/www"||n.startsWith("/var/www/"))throw Error(`${r}.path must not be under /var/www: releases are pruned by keepReleases`);if(!e.pattern||/^[*?]+$/.test(e.pattern)||e.pattern.includes("/")||/[\n'"`]/.test(e.pattern))throw Error(`${r}.pattern must be a file-name glob naming something, not a bare wildcard (got ${JSON.stringify(e.pattern)})`);if(et(`${r}.maxAgeDays`,e.maxAgeDays),e.type!==void 0&&e.type!=="file"&&e.type!=="directory")throw Error(`${r}.type must be 'file' or 'directory'`)}function Ur(e){let t=typeof e==="object"&&e!==null?e:{},r=e!==!1,n={...Fg,...Bs(t.retention)};zs("hostCleanup.retention",n);let s=null;if(t.pressure!==!1){let c=typeof t.pressure==="object"?t.pressure:{},f=c.lowWaterPercent??50,g=c.highWaterPercent??85;if(et("hostCleanup.pressure.lowWaterPercent",f),et("hostCleanup.pressure.highWaterPercent",g,1),g>100||f>=g)throw Error(`hostCleanup.pressure: need 0 <= lowWaterPercent < highWaterPercent <= 100 (got ${f} and ${g})`);let h={...Ug,...Bs(c.escalated)},S=Object.fromEntries(Object.keys(n).map((_)=>[_,Math.min(n[_],h[_]??n[_])]));zs("hostCleanup.pressure.escalated",S),s={lowWaterPercent:f,highWaterPercent:g,escalated:S}}let i=t.schedule??"daily";if(!/^[\w*:,./~ -]+$/.test(i))throw Error(`hostCleanup.schedule must be a systemd OnCalendar expression (got ${JSON.stringify(i)})`);let a=t.paths??[];return a.forEach(dc),{enabled:r,timer:r&&t.timer!==!1,schedule:i,retention:n,pressure:s,paths:a}}function Bs(e){return Object.fromEntries(Object.entries(e??{}).filter(([,t])=>t!==void 0))}var zt={stagingMaxAgeMinutes:"TS_CLOUD_HC_STAGING_MIN",artifactMaxAgeDays:"TS_CLOUD_HC_ARTIFACT_DAYS",artifactUploadMaxAgeMinutes:"TS_CLOUD_HC_UPLOAD_MIN",bunCacheMaxAgeDays:"TS_CLOUD_HC_BUN_DAYS",journalMaxAgeDays:"TS_CLOUD_HC_JOURNAL_DAYS",journalMaxSizeMb:"TS_CLOUD_HC_JOURNAL_MB",containerImageMaxAgeHours:"TS_CLOUD_HC_IMAGE_HOURS"};function En(e){return Object.keys(zt).map((t)=>`${zt[t]}=${e[t]}`).join(" ")}var Ge=(e)=>`"$${zt[e]}"`;function Ks(e){return[`find /var/ts-cloud/staging -xdev -maxdepth 1 -type f -mmin +${Ge("stagingMaxAgeMinutes")} -delete 2>/dev/null || true`,`find /tmp -xdev -maxdepth 1 -type f -name "*-release.tar.gz" -mmin +${Ge("stagingMaxAgeMinutes")} -delete 2>/dev/null || true`,`find /var/ts-cloud/artifacts -xdev -maxdepth 1 -type f -name "*.tar.gz" -mtime +${Ge("artifactMaxAgeDays")} -delete 2>/dev/null || true`,`find /var/ts-cloud/artifacts -xdev -maxdepth 1 -type f -name ".*.tmp" -mmin +${Ge("artifactUploadMaxAgeMinutes")} -delete 2>/dev/null || true`,...e.map(mc),`journalctl --vacuum-time=${Ge("journalMaxAgeDays")}d --vacuum-size=${Ge("journalMaxSizeMb")}M >/dev/null 2>&1 || true`]}function mc(e){let t=Fs(e.path.replace(/\/+$/,"")),r=Fs(e.pattern);return e.type==="directory"?`find ${t} -xdev -mindepth 1 -maxdepth 1 -type d -name ${r} -mtime +${e.maxAgeDays} -exec rm -rf -- {} + 2>/dev/null || true`:`find ${t} -xdev -mindepth 1 -maxdepth 1 -type f -name ${r} -mtime +${e.maxAgeDays} -delete 2>/dev/null || true`}function js(){return[`find /root/.bun/install/cache -xdev -type f -mtime +${Ge("bunCacheMaxAgeDays")} -delete 2>/dev/null || true`,`find /root/.bun/install/cache -xdev -depth -type d -empty -mtime +${Ge("bunCacheMaxAgeDays")} -delete 2>/dev/null || true`,`if command -v docker >/dev/null 2>&1; then docker image prune --all --force --filter "until=\${${zt.containerImageMaxAgeHours}}h" >/dev/null 2>&1 || true; fi`,`if command -v podman >/dev/null 2>&1; then podman image prune --all --force --filter "until=\${${zt.containerImageMaxAgeHours}}h" >/dev/null 2>&1 || true; fi`,"if command -v apt-get >/dev/null 2>&1; then apt-get clean >/dev/null 2>&1 || true; fi"]}function Gs(e){return[`${e}="$(df -P / 2>/dev/null | awk 'NR==2 {sub(/%/, "", $5); print $5}' || true)"`,`case "$${e}" in ''|*[!0-9]*) ${e}=-1 ;; esac`]}function ri(e){let{retention:t,pressure:r,paths:n}=Ur(e),s='echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',i='echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"';if(!r)return['echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',En(t),...Ks(n),...js(),'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"'];let{lowWaterPercent:a,highWaterPercent:c,escalated:f}=r;return['echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',...Gs("TS_CLOUD_HC_BEFORE"),"TS_CLOUD_HC_TIER=normal",En(t),`if [ "$TS_CLOUD_HC_BEFORE" -ge 0 ] && [ "$TS_CLOUD_HC_BEFORE" -lt ${a} ]; then`," TS_CLOUD_HC_TIER=light",` echo "[ts-cloud] host cleanup: / at \${TS_CLOUD_HC_BEFORE}% (under ${a}%), skipping cache and image pruning"`,`elif [ "$TS_CLOUD_HC_BEFORE" -ge ${c} ]; then`," TS_CLOUD_HC_TIER=pressure",` ${En(f)}`,` echo "[ts-cloud] warning: / at \${TS_CLOUD_HC_BEFORE}% (at or above ${c}%), host cleanup is using shortened retention windows" >&2`,"fi",...Ks(n),'if [ "$TS_CLOUD_HC_TIER" != light ]; then',...js().map((g)=>` ${g}`),"fi",'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"',...Gs("TS_CLOUD_HC_AFTER"),`echo "[ts-cloud] host-cleanup {\\"event\\":\\"host-cleanup\\",\\"tier\\":\\"$TS_CLOUD_HC_TIER\\",\\"diskBeforePercent\\":$TS_CLOUD_HC_BEFORE,\\"diskAfterPercent\\":$TS_CLOUD_HC_AFTER,\\"lowWaterPercent\\":${a},\\"highWaterPercent\\":${c}}"`,"mkdir -p /var/lib/ts-cloud 2>/dev/null || true",'TS_CLOUD_HC_PREV="$(cat /var/lib/ts-cloud/host-cleanup.alert 2>/dev/null || echo ok)"',`if [ "$TS_CLOUD_HC_AFTER" -ge ${c} ]; then`,` echo "[ts-cloud] warning: / still at \${TS_CLOUD_HC_AFTER}% after host cleanup (high-water ${c}%); something outside ts-cloud's retention rules is filling the disk" >&2`,` if [ "$TS_CLOUD_HC_PREV" != alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "⚠️ $(hostname): / at \${TS_CLOUD_HC_AFTER}% after host cleanup (high-water ${c}%)" >/dev/null 2>&1 || true; fi`," echo alert > /var/lib/ts-cloud/host-cleanup.alert 2>/dev/null || true","else",` if [ "$TS_CLOUD_HC_PREV" = alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "✅ $(hostname): / back under ${c}% after host cleanup (\${TS_CLOUD_HC_AFTER}%)" >/dev/null 2>&1 || true; fi`," echo ok > /var/lib/ts-cloud/host-cleanup.alert 2>/dev/null || true","fi"]}function Qg(e){return["#!/usr/bin/env bash","# Managed by ts-cloud: rewritten on every deploy. Configure compute.hostCleanup instead of editing.","set -uo pipefail","TS_CLOUD_HC_LOCK=/run/lock/ts-cloud-host-cleanup.lock","[ -d /run/lock ] || TS_CLOUD_HC_LOCK=/tmp/ts-cloud-host-cleanup.lock",'if command -v flock >/dev/null 2>&1 && exec 9>"$TS_CLOUD_HC_LOCK"; then',' if ! flock -n 9; then echo "[ts-cloud] host cleanup already running; skipping"; exit 0; fi',"fi",...ri(e),"exit 0"]}function Rn(e,t,r,n,s){return[`cat > ${e}.ts-cloud-new <<'${r}' || true`,...t,r,`if [ -s ${e}.ts-cloud-new ] && ! cmp -s ${e}.ts-cloud-new ${e}; then chmod ${n} ${e}.ts-cloud-new && mv -f ${e}.ts-cloud-new ${e}${s?` && ${s}=1`:""} || true; else rm -f ${e}.ts-cloud-new; fi`]}function to(e){let t=Ur(e),r="/etc/systemd/system/ts-cloud-host-cleanup",n=["if [ -f /etc/systemd/system/ts-cloud-host-cleanup.timer ]; then"," systemctl disable --now ts-cloud-host-cleanup.timer >/dev/null 2>&1 || true"," rm -f /etc/systemd/system/ts-cloud-host-cleanup.timer /etc/systemd/system/ts-cloud-host-cleanup.service"," systemctl daemon-reload >/dev/null 2>&1 || true","fi"];if(!t.enabled)return[...n,"rm -f /usr/local/bin/ts-cloud-host-cleanup.sh"];let s=Rn("/usr/local/bin/ts-cloud-host-cleanup.sh",Qg(e),"TS_CLOUD_HOST_CLEANUP_EOF","755");if(!t.timer)return[...s,...n];return[...s,"TS_CLOUD_HC_UNITS_CHANGED=0","if command -v systemctl >/dev/null 2>&1 && [ -d /etc/systemd/system ]; then",...Rn("/etc/systemd/system/ts-cloud-host-cleanup.service",["[Unit]","Description=ts-cloud host cleanup (bounded disk retention)","After=local-fs.target","","[Service]","Type=oneshot","ExecStart=/usr/local/bin/ts-cloud-host-cleanup.sh","Nice=19","IOSchedulingClass=idle"],"TS_CLOUD_HOST_CLEANUP_SVC_EOF","644","TS_CLOUD_HC_UNITS_CHANGED"),...Rn("/etc/systemd/system/ts-cloud-host-cleanup.timer",["[Unit]","Description=Run ts-cloud host cleanup on a schedule, independent of deploys","","[Timer]",`OnCalendar=${t.schedule}`,"RandomizedDelaySec=1h","Persistent=true","","[Install]","WantedBy=timers.target"],"TS_CLOUD_HOST_CLEANUP_TMR_EOF","644","TS_CLOUD_HC_UNITS_CHANGED"),' if [ "$TS_CLOUD_HC_UNITS_CHANGED" -eq 1 ]; then systemctl daemon-reload >/dev/null 2>&1 || true; fi'," systemctl enable --now ts-cloud-host-cleanup.timer >/dev/null 2>&1 || true","fi"]}function ni(e){let t=to(e);if(!Ur(e).enabled)return t;return[...t,'if [ -x /usr/local/bin/ts-cloud-host-cleanup.sh ]; then /usr/local/bin/ts-cloud-host-cleanup.sh < /dev/null || echo "[ts-cloud] warning: host cleanup exited $?" >&2; fi']}function Ys(e,t,r={}){if(!t.length)return[];let n=Object.entries(r).flatMap(([s,i])=>{if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(s))throw Error("Invalid pre-start environment variable name");if(["PORT","PORT_BACKEND","PORT_ADMIN","PORT_FRONTEND"].includes(s))return[];return[`export ${s}=${We(String(i))}`]});return[`cd ${e}`,`if [ -d ${u} ] && command -v pantry >/dev/null 2>&1; then`,` ${Ce()}`,"fi",...n,...t]}var fc=/\.(?:[cm]?[jt]sx?)$/;function ii(e,t,r){let n=t==="bun"?"/usr/local/bin/bun":t==="deno"?"/usr/local/bin/deno":"/usr/local/bin/node",s=e.trim();if(/^(?:bun|node|deno)\s+/.test(s))return`${n} ${s.replace(/^(?:bun|node|deno)\s+/,"")}`;let[i="",...a]=s.split(/\s+/);if(i&&!fc.test(i)){let c=i.startsWith("/")?i:r&&i.startsWith("./")?`${r.replace(/\/+$/,"")}/${i.replace(/^\.\//,"")}`:void 0;if(c)return[c,...a].join(" ")}return`${n} ${s}`}function Vs(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.
@@ -156,7 +156,7 @@ await (${Is.toString()})(JSON.parse(await Bun.file(process.env.TS_CLOUD_STORAGE_
156
156
  [Service]
157
157
  MemoryAccounting=true
158
158
  MemoryHigh=%sM
159
- ' "$TS_CLOUD_MEM_MB" "$TS_CLOUD_HIGH_MB" > /etc/systemd/system/${e}.d/50-ts-cloud-memory.conf`,"systemctl daemon-reload",'echo "[ts-cloud] memoryHigh=auto resolved to ${TS_CLOUD_HIGH_MB}M (one eighth of ${TS_CLOUD_MEM_MB}M)"',...Dn()]}function br(e,t={auto:!0}){let r=t.auto===!1?[]:[`/etc/systemd/system/${e}.d/50-ts-cloud-memory.conf`];for(let n of["/etc/systemd/system.control","/run/systemd/system.control"]){if(t.high)r.push(`${n}/${e}.d/50-MemoryHigh.conf`);if(t.max)r.push(`${n}/${e}.d/50-MemoryMax.conf`)}if(r.length===0)return[];return["TS_CLOUD_MEM_CLEARED=0",...r.map((n)=>`if [ -f ${n} ]; then rm -f ${n}; TS_CLOUD_MEM_CLEARED=1; echo "[ts-cloud] removed ${n}: memory limits now come from config"; fi`),'if [ "$TS_CLOUD_MEM_CLEARED" = 1 ]; then systemctl daemon-reload; fi']}function Dn(){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']}var tt={path:"/",intervalSeconds:60,failuresBeforeRestart:3,timeoutSeconds:10,startupGraceSeconds:600,maxBackoffSeconds:3600,backoffBaseSeconds:300};function Bt(e,t,r){return typeof e==="number"&&Number.isFinite(e)?Math.max(r,Math.floor(e)):t}function qs(e){let{unitBase:t,unitPattern:r,port:n}=e,s=e.path&&e.path.startsWith("/")?e.path:tt.path,i=Bt(e.intervalSeconds,tt.intervalSeconds,10),a=Bt(e.failuresBeforeRestart,tt.failuresBeforeRestart,1),c=Bt(e.timeoutSeconds,tt.timeoutSeconds,1),f=Bt(e.startupGraceSeconds,tt.startupGraceSeconds,0),g=Bt(e.maxBackoffSeconds,tt.maxBackoffSeconds,0),h=Math.min(tt.backoffBaseSeconds,g),S=`/usr/local/sbin/${t}-liveness`,_=`/run/${t}-liveness`,v=`${t}-liveness`,y=`127.0.0.1:${n}${s}`,x=r.includes("@*")?`TS_CLOUD_UNIT=$(systemctl list-units --plain --no-legend --type=service '${r}' 2>/dev/null | awk '{print $1}' | head -1)`:`TS_CLOUD_UNIT=${r}`;return[`cat > ${S} <<'TS_CLOUD_LIVENESS_EOF'`,"#!/bin/sh",`# Liveness check for ${t}, written by ts-cloud on every deploy.`,`# Settings: interval=${i}s timeout=${c}s failures=${a} startup-grace=${f}s max-backoff=${g}s`,"set -eu",`TS_CLOUD_STATE=${_}`,'exec 9>"$TS_CLOUD_STATE.lock"',"flock -n 9 || exit 0",x,'[ -n "$TS_CLOUD_UNIT" ] || exit 0','systemctl is-active --quiet "$TS_CLOUD_UNIT" || exit 0',"TS_CLOUD_RC=0",`curl -s -o /dev/null --max-time ${c} "http://${y}" || TS_CLOUD_RC=$?`,'if [ "$TS_CLOUD_RC" -eq 0 ]; then',' rm -f "$TS_CLOUD_STATE.fail"',' if [ -f "$TS_CLOUD_STATE.restarts" ]; then',` TS_CLOUD_LAST=$(awk '{print $2}' "$TS_CLOUD_STATE.restarts" 2>/dev/null || true)`,` case "$TS_CLOUD_LAST" in ''|*[!0-9]*) TS_CLOUD_LAST=0 ;; esac`,` [ $(($(date +%s) - TS_CLOUD_LAST)) -lt ${g} ] || rm -f "$TS_CLOUD_STATE.restarts"`," fi"," exit 0","fi",'case "$TS_CLOUD_RC" in'," 7) TS_CLOUD_WHY='connection refused' ;;",` 28) TS_CLOUD_WHY='no response within ${c}s' ;;`,' *) TS_CLOUD_WHY="curl exit $TS_CLOUD_RC" ;;',"esac",'TS_CLOUD_SINCE=$(systemctl show "$TS_CLOUD_UNIT" -p ActiveEnterTimestampMonotonic --value 2>/dev/null || true)',"TS_CLOUD_UPTIME=$(cut -d' ' -f1 /proc/uptime 2>/dev/null || true)",`TS_CLOUD_AGE=$(awk -v up="$TS_CLOUD_UPTIME" -v since="$TS_CLOUD_SINCE" 'BEGIN { if (since + 0 > 0 && up + 0 > 0) print int(up - since / 1000000); else print -1 }')`,`case "$TS_CLOUD_AGE" in ''|*[!0-9-]*) TS_CLOUD_AGE=-1 ;; esac`,'if [ "$TS_CLOUD_AGE" -lt 0 ]; then',' TS_CLOUD_PID=$(systemctl show "$TS_CLOUD_UNIT" -p MainPID --value 2>/dev/null || true)',` case "$TS_CLOUD_PID" in ''|0|*[!0-9]*) ;; *) TS_CLOUD_AGE=$(ps -o etimes= -p "$TS_CLOUD_PID" 2>/dev/null | tr -d ' ' || true) ;; esac`,` case "$TS_CLOUD_AGE" in ''|*[!0-9]*) TS_CLOUD_AGE=-1 ;; esac`,"fi",`if [ "$TS_CLOUD_AGE" -ge 0 ] && [ "$TS_CLOUD_AGE" -lt ${f} ]; then`,' rm -f "$TS_CLOUD_STATE.fail"',` logger -t ${v} "$TS_CLOUD_UNIT is \${TS_CLOUD_AGE}s old, inside its ${f}s startup grace; not counting this failed check on ${y} ($TS_CLOUD_WHY)"`," exit 0","fi",'TS_CLOUD_FAILS=$(cat "$TS_CLOUD_STATE.fail" 2>/dev/null || echo 0)',`case "$TS_CLOUD_FAILS" in ''|*[!0-9]*) TS_CLOUD_FAILS=0 ;; esac`,"TS_CLOUD_FAILS=$((TS_CLOUD_FAILS + 1))",'echo "$TS_CLOUD_FAILS" > "$TS_CLOUD_STATE.fail"',`if [ "$TS_CLOUD_FAILS" -lt ${a} ]; then`,` logger -t ${v} "check $TS_CLOUD_FAILS of ${a} failed on ${y} ($TS_CLOUD_WHY)"`," exit 0","fi","TS_CLOUD_NOW=$(date +%s)","TS_CLOUD_STREAK=0","TS_CLOUD_LAST=0",'[ ! -f "$TS_CLOUD_STATE.restarts" ] || read -r TS_CLOUD_STREAK TS_CLOUD_LAST < "$TS_CLOUD_STATE.restarts" || true',`case "$TS_CLOUD_STREAK" in ''|*[!0-9]*) TS_CLOUD_STREAK=0 ;; esac`,`case "$TS_CLOUD_LAST" in ''|*[!0-9]*) TS_CLOUD_LAST=0 ;; esac`,'if [ "$TS_CLOUD_STREAK" -gt 0 ]; then',` TS_CLOUD_WAIT=${h}`," TS_CLOUD_I=1",` while [ "$TS_CLOUD_I" -lt "$TS_CLOUD_STREAK" ] && [ "$TS_CLOUD_WAIT" -lt ${g} ]; do TS_CLOUD_WAIT=$((TS_CLOUD_WAIT * 2)); TS_CLOUD_I=$((TS_CLOUD_I + 1)); done`,` [ "$TS_CLOUD_WAIT" -le ${g} ] || TS_CLOUD_WAIT=${g}`," TS_CLOUD_ELAPSED=$((TS_CLOUD_NOW - TS_CLOUD_LAST))",' if [ "$TS_CLOUD_ELAPSED" -lt "$TS_CLOUD_WAIT" ]; then',` logger -t ${v} "holding off: $TS_CLOUD_STREAK liveness restart(s) in a row have not brought $TS_CLOUD_UNIT back; next restart allowed in $((TS_CLOUD_WAIT - TS_CLOUD_ELAPSED))s ($TS_CLOUD_WHY on ${y})"`," exit 0"," fi","fi","TS_CLOUD_STREAK=$((TS_CLOUD_STREAK + 1))",`logger -t ${v} "no HTTP response on ${y} after $TS_CLOUD_FAILS checks ($TS_CLOUD_WHY); restarting $TS_CLOUD_UNIT (liveness restart $TS_CLOUD_STREAK in a row)"`,'echo "$TS_CLOUD_STREAK $TS_CLOUD_NOW" > "$TS_CLOUD_STATE.restarts"','rm -f "$TS_CLOUD_STATE.fail"','systemctl restart "$TS_CLOUD_UNIT"',"TS_CLOUD_LIVENESS_EOF",`chmod +x ${S}`,`rm -f ${_}.fail ${_}.restarts`,`cat > /etc/systemd/system/${t}-liveness.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=Liveness check for ${t} (managed by ts-cloud)`,"","[Service]","Type=oneshot",`ExecStart=${S}`,"TS_CLOUD_UNIT_EOF",`cat > /etc/systemd/system/${t}-liveness.timer <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=Run the ${t} liveness check every ${i}s`,"","[Timer]",`OnUnitActiveSec=${i}s`,`OnBootSec=${i}s`,"Persistent=true","","[Install]","WantedBy=timers.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",`systemctl enable --now ${t}-liveness.timer >/dev/null 2>&1 || true`]}var Ws=20,On=3,hc=5,Sc=60;function vc(e){let{paths:t,unitBase:r,releaseId:n,port:s}=e,i=`${r}@${n}.service`,a=`${r}.service`,c=Math.max(1,e.healthGateSeconds??5),f=e.healthCheckPath?e.healthCheckPath.startsWith("/")?e.healthCheckPath:`/${e.healthCheckPath}`:null,g=f?`curl -sf -o /dev/null --max-time ${hc} "http://127.0.0.1:${s}${f}"`:null,h=(S)=>`{ echo "[ts-cloud] release ${n} ${S}" >&2; ts_cloud_restore_previous; exit 1; }`;return[`TS_CLOUD_OLD_UNITS=$(systemctl list-units --plain --no-legend --type=service "${r}@*.service" 2>/dev/null | awk '{print $1}' | grep -v "^${i}$" || true)`,`TS_CLOUD_PREV_CURRENT="$(readlink ${t.current} 2>/dev/null || true)"`,"TS_CLOUD_LEGACY_STOPPED=0","ts_cloud_restore_previous() {",` journalctl -u ${i} -n 50 --no-pager >&2 || true`,` systemctl stop ${i} 2>/dev/null || true`,` systemctl disable ${i} 2>/dev/null || true`,` if [ -n "$TS_CLOUD_PREV_CURRENT" ] && [ -d "$TS_CLOUD_PREV_CURRENT" ]; then ln -sfn "$TS_CLOUD_PREV_CURRENT" ${t.current}.tmp && mv -Tf ${t.current}.tmp ${t.current}; fi`,' for TS_CLOUD_RU in ${TS_CLOUD_OLD_UNITS}; do systemctl enable "$TS_CLOUD_RU" 2>/dev/null || true; systemctl start "$TS_CLOUD_RU" 2>/dev/null || true; done',` if [ "$TS_CLOUD_LEGACY_STOPPED" -eq 1 ]; then systemctl start ${a} 2>/dev/null || true; fi`,' if [ -n "$TS_CLOUD_OLD_UNITS" ] || [ "$TS_CLOUD_LEGACY_STOPPED" -eq 1 ]; then echo "[ts-cloud] previous release restored and serving" >&2; else echo "[ts-cloud] there was no previous release to restore" >&2; fi',"}",`if [ -f /etc/systemd/system/${a} ] && systemctl is-active --quiet ${a}; then echo "[ts-cloud] retiring pre-zero-downtime unit ${a} (one-time restart cutover)"; systemctl stop ${a}; TS_CLOUD_LEGACY_STOPPED=1; fi`,'TS_CLOUD_STARTED_AT="@$(date +%s)"',`systemctl restart ${i}`,`TS_CLOUD_GATE_OK=1; for TS_CLOUD_I in $(seq 1 ${c}); do sleep 1; systemctl is-active --quiet ${i} || { TS_CLOUD_GATE_OK=0; break; }; done`,'if [ "$TS_CLOUD_GATE_OK" -ne 1 ]; then',` if journalctl -u ${i} --since "$TS_CLOUD_STARTED_AT" -o cat --no-pager 2>/dev/null | grep -iE 'EADDRINUSE|address already in use|port [0-9]+ (is )?in use|Failed to start server' >/dev/null; then`,` echo "[ts-cloud] release ${n} could not share :${s} with the previous release (no SO_REUSEPORT?) — retiring it and retrying" >&2`,' for TS_CLOUD_RU in ${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_RU" 2>/dev/null || true; done',` systemctl restart ${i}`,` for TS_CLOUD_I in $(seq 1 ${c}); do sleep 1; systemctl is-active --quiet ${i} || ${h("failed its health gate on the free port")}; done`," else",` ${h("crashed on start — the previous release was never stopped")}`," fi","fi",`if ss -ltnpH "sport = :${s}" >/dev/null 2>&1; then`," TS_CLOUD_BOUND=0",` for TS_CLOUD_I in $(seq 1 ${Sc}); do`,` TS_CLOUD_NEW_PID="$(systemctl show -p MainPID --value ${i} 2>/dev/null || true)"`,` if [ -n "$TS_CLOUD_NEW_PID" ] && [ "$TS_CLOUD_NEW_PID" != "0" ] && ss -ltnpH "sport = :${s}" 2>/dev/null | grep "pid=$TS_CLOUD_NEW_PID," >/dev/null; then TS_CLOUD_BOUND=1; break; fi`,` systemctl is-active --quiet ${i} || break`,` sleep ${On}`," done",` [ "$TS_CLOUD_BOUND" -eq 1 ] || ${h(`never took :${s}`)}`,"else",' echo "[ts-cloud] cannot read listener PIDs on this host — the response probes run without the bind check" >&2',"fi",...g?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${Ws}); do if ${g}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${On}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${h(`never answered ${f}`)}`]:[],...dt(t),`systemctl enable ${i} 2>/dev/null || true`,'for TS_CLOUD_U in ${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done',`TS_CLOUD_LISTENING=0; for TS_CLOUD_I in $(seq 1 ${c}); do if ss -ltnH "sport = :${s}" 2>/dev/null | grep . >/dev/null; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done`,`if [ "$TS_CLOUD_LISTENING" -ne 1 ]; then echo "[ts-cloud] nothing is listening on ${s} after retiring the previous release — restarting ${i} on the now-free port" >&2; systemctl restart ${i}; for TS_CLOUD_I in $(seq 1 ${c}); do if ss -ltnH "sport = :${s}" 2>/dev/null | grep . >/dev/null; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done; fi`,`[ "$TS_CLOUD_LISTENING" -eq 1 ] || ${h(`is active but never bound :${s}`)}`,...g?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${Ws}); do if ${g}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${On}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${h(`stopped answering ${f} once it served alone`)}`]:[],...wn(t),`systemctl list-unit-files --plain --no-legend "${r}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v -e "^${i}$" -e "^${r}@\\.service$" || true; } | while read -r TS_CLOUD_U; do systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done`,`if [ -f /etc/systemd/system/${a} ]; then systemctl disable ${a} 2>/dev/null || true; rm -f /etc/systemd/system/${a}; systemctl daemon-reload; fi`]}function Xs(e,t){if(!t.length)return[];let r=We(e.release);return[`if [ -e ${r} ] || [ -L ${r} ]; then`,...t,"fi"]}function si(e){let{siteName:t,slug:r,artifactFetch:n,releaseId:s,execStart:i,envEntries:a,port:c,keepReleases:f=Ht,preStartCommands:g=[],postActivateCommands:h=[],beforeResetCommands:S=[],healthCheckPath:_,healthGateSeconds:v=5,liveness:y,memoryHigh:T="auto",memoryMax:x,cpuWeight:q,ioWeight:H,tasksMax:R,stopTimeout:L}=e,I=[...q!=null?[`CPUWeight=${q}`]:[],...H!=null?[`IOWeight=${H}`]:[],...R!=null?[`TasksMax=${R}`]:[],...L?[`TimeoutStopSec=${L}`]:[]],V=e.zeroDowntime??c!=null,W=e.appDir??`/var/www/${t}`,K=Zt(W,s),ee=`${r}-${t}`,te=`${ee}.service`,ne=ai(r,t,s),ie=e.sharedPaths??[],oe=Hs([".env",...ie,...yr(a,ie)]),re=fr(a),pe=Ys(K.release,g,a),ge=["set -euo pipefail",...vn(K),...n,...Ft(K,oe),...Xs(K,S),yn(K),...$n(K),`tar xzf ${ne} -C "$TS_CLOUD_STAGED"`,`rm -f ${ne}`,`cat > ${K.shared}/.env <<'TS_CLOUD_ENV_EOF'`,re,"TS_CLOUD_ENV_EOF",`chmod 600 ${K.shared}/.env`,...bn(K),`find ${K.release} -maxdepth 1 \\( -type f -o -type l \\) -name '.env*' ! -name '.env.example' ! -name '*.example' -delete`,`sed -i -E '/^[[:space:]]*(PORT|PORT_BACKEND|PORT_ADMIN|PORT_FRONTEND)[[:space:]]*=/d' ${K.shared}/.env 2>/dev/null || true`,...Sr(K,oe),...pe,...e.isolation?Ls(e.slug||t,K.base,oe.flatMap((b)=>typeof b==="string"||!b.target?[]:[b.target])):[]];if(V&&c!=null){let b=`${ee}@${s}.service`,k=_?_.startsWith("/")?_:`/${_}`:null;return[...ge,`cat > /etc/systemd/system/${ee}@.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} release %i (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",...e.isolation?Ut(pt(e.slug||t),K.base,e.slug||t):[],`WorkingDirectory=${K.releases}/%i`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...T&&T!=="auto"?[`MemoryHigh=${T}`]:[],...x?[`MemoryMax=${x}`]:[],...I,`EnvironmentFile=${K.releases}/%i/.env`,`Environment=PORT=${c}`,`Environment=STX_IMAGE_CACHE_DIR=${hr(K)}`,`Environment=STX_BUNDLE_CACHE_DIR=${Mt(K)}`,`Environment=STX_BUNDLE_CACHE_DIR=${Mt(K)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...T==="auto"?Vs(`${ee}@.service`):[...br(`${ee}@.service`),...Dn()],...gc(b),...vc({paths:K,unitBase:ee,releaseId:s,port:c,healthCheckPath:k,healthGateSeconds:v}),...h,...mt(K,f),...y===!1?[]:qs({...y,unitBase:ee,unitPattern:`${ee}@*.service`,port:c,path:y?.path??_})]}return[...ge,`cat > /etc/systemd/system/${te} <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",...e.isolation?Ut(pt(e.slug||t),K.base,e.slug||t):[],`WorkingDirectory=${K.current}`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...T&&T!=="auto"?[`MemoryHigh=${T}`]:[],...x?[`MemoryMax=${x}`]:[],...I,`EnvironmentFile=${K.current}/.env`,...c?[`Environment=PORT=${c}`]:[],`Environment=STX_IMAGE_CACHE_DIR=${hr(K)}`,`Environment=STX_BUNDLE_CACHE_DIR=${Mt(K)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...br(te,{auto:T!=="auto",high:T!=="auto",max:Boolean(x)}),...T==="auto"?Vs(te):Dn(),`systemctl enable ${te}`,`TS_CLOUD_PREV_CURRENT="$(readlink ${K.current} 2>/dev/null || true)"`,...dt(K),`systemctl restart ${te}`,`for TS_CLOUD_I in $(seq 1 ${Math.max(1,v)}); do sleep 1; systemctl is-active --quiet ${te} || { echo "[ts-cloud] release ${s} of ${te} did not stay up — restoring the previous release" >&2; journalctl -u ${te} -n 50 --no-pager >&2 || true; if [ -n "$TS_CLOUD_PREV_CURRENT" ] && [ -d "$TS_CLOUD_PREV_CURRENT" ] && [ "$(readlink -f "$TS_CLOUD_PREV_CURRENT")" != "$(readlink -f ${K.release})" ]; then ln -sfn "$TS_CLOUD_PREV_CURRENT" ${K.current}.tmp && mv -Tf ${K.current}.tmp ${K.current}; systemctl restart ${te} || true; fi; exit 1; }; done`,...wn(K),...h,...mt(K,f),...y===!1||!c?[]:qs({...y,unitBase:ee,unitPattern:te,port:c,path:y?.path??_})]}function oi(e){let{siteName:t,artifactFetch:r,releaseId:n,keepReleases:s=Ht,preStartCommands:i=[],postActivateCommands:a=[],beforeResetCommands:c=[]}=e,f=e.appDir??`/var/www/${t}`,g=Zt(f,n),h=ai(e.slug,t,n),S=Ys(g.release,i);return["set -euo pipefail",...vn(g),...r,...Ft(g,[]),...Xs(g,c),yn(g),...$n(g),`tar xzf ${h} -C "$TS_CLOUD_STAGED"`,...bn(g),`rm -f ${h}`,...S,...dt(g),...a,...mt(g,s)]}function ai(e,t,r){return`/tmp/${[e,t,r].filter(Boolean).join("-")}-release.tar.gz`}function $c(e,t,r,n){return[`aws s3 cp "s3://${e}/${t}" ${n} --region ${r}`]}function Mc(e,t){return[`mv "${e}" ${t}`]}function We(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function Tr(e,t,r){return["set -euo pipefail",`chmod 600 ${We(e)}`,`mv -f -- ${We(e)} ${We(t)}`,`cp -- ${We(t)} ${We(r)}`].join(`
159
+ ' "$TS_CLOUD_MEM_MB" "$TS_CLOUD_HIGH_MB" > /etc/systemd/system/${e}.d/50-ts-cloud-memory.conf`,"systemctl daemon-reload",'echo "[ts-cloud] memoryHigh=auto resolved to ${TS_CLOUD_HIGH_MB}M (one eighth of ${TS_CLOUD_MEM_MB}M)"',...Dn()]}function br(e,t={auto:!0}){let r=t.auto===!1?[]:[`/etc/systemd/system/${e}.d/50-ts-cloud-memory.conf`];for(let n of["/etc/systemd/system.control","/run/systemd/system.control"]){if(t.high)r.push(`${n}/${e}.d/50-MemoryHigh.conf`);if(t.max)r.push(`${n}/${e}.d/50-MemoryMax.conf`)}if(r.length===0)return[];return["TS_CLOUD_MEM_CLEARED=0",...r.map((n)=>`if [ -f ${n} ]; then rm -f ${n}; TS_CLOUD_MEM_CLEARED=1; echo "[ts-cloud] removed ${n}: memory limits now come from config"; fi`),'if [ "$TS_CLOUD_MEM_CLEARED" = 1 ]; then systemctl daemon-reload; fi']}function Dn(){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']}var tt={path:"/",intervalSeconds:60,failuresBeforeRestart:3,timeoutSeconds:10,startupGraceSeconds:600,maxBackoffSeconds:3600,backoffBaseSeconds:300};function Bt(e,t,r){return typeof e==="number"&&Number.isFinite(e)?Math.max(r,Math.floor(e)):t}function qs(e){let{unitBase:t,unitPattern:r,port:n}=e,s=e.path&&e.path.startsWith("/")?e.path:tt.path,i=Bt(e.intervalSeconds,tt.intervalSeconds,10),a=Bt(e.failuresBeforeRestart,tt.failuresBeforeRestart,1),c=Bt(e.timeoutSeconds,tt.timeoutSeconds,1),f=Bt(e.startupGraceSeconds,tt.startupGraceSeconds,0),g=Bt(e.maxBackoffSeconds,tt.maxBackoffSeconds,0),h=Math.min(tt.backoffBaseSeconds,g),S=`/usr/local/sbin/${t}-liveness`,_=`/run/${t}-liveness`,v=`${t}-liveness`,y=`127.0.0.1:${n}${s}`,x=r.includes("@*")?`TS_CLOUD_UNIT=$(systemctl list-units --plain --no-legend --type=service '${r}' 2>/dev/null | awk '{print $1}' | head -1)`:`TS_CLOUD_UNIT=${r}`;return[`cat > ${S} <<'TS_CLOUD_LIVENESS_EOF'`,"#!/bin/sh",`# Liveness check for ${t}, written by ts-cloud on every deploy.`,`# Settings: interval=${i}s timeout=${c}s failures=${a} startup-grace=${f}s max-backoff=${g}s`,"set -eu",`TS_CLOUD_STATE=${_}`,'exec 9>"$TS_CLOUD_STATE.lock"',"flock -n 9 || exit 0",x,'[ -n "$TS_CLOUD_UNIT" ] || exit 0','systemctl is-active --quiet "$TS_CLOUD_UNIT" || exit 0',"TS_CLOUD_RC=0",`curl -s -o /dev/null --max-time ${c} "http://${y}" || TS_CLOUD_RC=$?`,'if [ "$TS_CLOUD_RC" -eq 0 ]; then',' rm -f "$TS_CLOUD_STATE.fail"',' if [ -f "$TS_CLOUD_STATE.restarts" ]; then',` TS_CLOUD_LAST=$(awk '{print $2}' "$TS_CLOUD_STATE.restarts" 2>/dev/null || true)`,` case "$TS_CLOUD_LAST" in ''|*[!0-9]*) TS_CLOUD_LAST=0 ;; esac`,` [ $(($(date +%s) - TS_CLOUD_LAST)) -lt ${g} ] || rm -f "$TS_CLOUD_STATE.restarts"`," fi"," exit 0","fi",'case "$TS_CLOUD_RC" in'," 7) TS_CLOUD_WHY='connection refused' ;;",` 28) TS_CLOUD_WHY='no response within ${c}s' ;;`,' *) TS_CLOUD_WHY="curl exit $TS_CLOUD_RC" ;;',"esac",'TS_CLOUD_SINCE=$(systemctl show "$TS_CLOUD_UNIT" -p ActiveEnterTimestampMonotonic --value 2>/dev/null || true)',"TS_CLOUD_UPTIME=$(cut -d' ' -f1 /proc/uptime 2>/dev/null || true)",`TS_CLOUD_AGE=$(awk -v up="$TS_CLOUD_UPTIME" -v since="$TS_CLOUD_SINCE" 'BEGIN { if (since + 0 > 0 && up + 0 > 0) print int(up - since / 1000000); else print -1 }')`,`case "$TS_CLOUD_AGE" in ''|*[!0-9-]*) TS_CLOUD_AGE=-1 ;; esac`,'if [ "$TS_CLOUD_AGE" -lt 0 ]; then',' TS_CLOUD_PID=$(systemctl show "$TS_CLOUD_UNIT" -p MainPID --value 2>/dev/null || true)',` case "$TS_CLOUD_PID" in ''|0|*[!0-9]*) ;; *) TS_CLOUD_AGE=$(ps -o etimes= -p "$TS_CLOUD_PID" 2>/dev/null | tr -d ' ' || true) ;; esac`,` case "$TS_CLOUD_AGE" in ''|*[!0-9]*) TS_CLOUD_AGE=-1 ;; esac`,"fi",`if [ "$TS_CLOUD_AGE" -ge 0 ] && [ "$TS_CLOUD_AGE" -lt ${f} ]; then`,' rm -f "$TS_CLOUD_STATE.fail"',` logger -t ${v} "$TS_CLOUD_UNIT is \${TS_CLOUD_AGE}s old, inside its ${f}s startup grace; not counting this failed check on ${y} ($TS_CLOUD_WHY)"`," exit 0","fi",'TS_CLOUD_FAILS=$(cat "$TS_CLOUD_STATE.fail" 2>/dev/null || echo 0)',`case "$TS_CLOUD_FAILS" in ''|*[!0-9]*) TS_CLOUD_FAILS=0 ;; esac`,"TS_CLOUD_FAILS=$((TS_CLOUD_FAILS + 1))",'echo "$TS_CLOUD_FAILS" > "$TS_CLOUD_STATE.fail"',`if [ "$TS_CLOUD_FAILS" -lt ${a} ]; then`,` logger -t ${v} "check $TS_CLOUD_FAILS of ${a} failed on ${y} ($TS_CLOUD_WHY)"`," exit 0","fi","TS_CLOUD_NOW=$(date +%s)","TS_CLOUD_STREAK=0","TS_CLOUD_LAST=0",'[ ! -f "$TS_CLOUD_STATE.restarts" ] || read -r TS_CLOUD_STREAK TS_CLOUD_LAST < "$TS_CLOUD_STATE.restarts" || true',`case "$TS_CLOUD_STREAK" in ''|*[!0-9]*) TS_CLOUD_STREAK=0 ;; esac`,`case "$TS_CLOUD_LAST" in ''|*[!0-9]*) TS_CLOUD_LAST=0 ;; esac`,'if [ "$TS_CLOUD_STREAK" -gt 0 ]; then',` TS_CLOUD_WAIT=${h}`," TS_CLOUD_I=1",` while [ "$TS_CLOUD_I" -lt "$TS_CLOUD_STREAK" ] && [ "$TS_CLOUD_WAIT" -lt ${g} ]; do TS_CLOUD_WAIT=$((TS_CLOUD_WAIT * 2)); TS_CLOUD_I=$((TS_CLOUD_I + 1)); done`,` [ "$TS_CLOUD_WAIT" -le ${g} ] || TS_CLOUD_WAIT=${g}`," TS_CLOUD_ELAPSED=$((TS_CLOUD_NOW - TS_CLOUD_LAST))",' if [ "$TS_CLOUD_ELAPSED" -lt "$TS_CLOUD_WAIT" ]; then',` logger -t ${v} "holding off: $TS_CLOUD_STREAK liveness restart(s) in a row have not brought $TS_CLOUD_UNIT back; next restart allowed in $((TS_CLOUD_WAIT - TS_CLOUD_ELAPSED))s ($TS_CLOUD_WHY on ${y})"`," exit 0"," fi","fi","TS_CLOUD_STREAK=$((TS_CLOUD_STREAK + 1))",`logger -t ${v} "no HTTP response on ${y} after $TS_CLOUD_FAILS checks ($TS_CLOUD_WHY); restarting $TS_CLOUD_UNIT (liveness restart $TS_CLOUD_STREAK in a row)"`,'echo "$TS_CLOUD_STREAK $TS_CLOUD_NOW" > "$TS_CLOUD_STATE.restarts"','rm -f "$TS_CLOUD_STATE.fail"','systemctl restart "$TS_CLOUD_UNIT"',"TS_CLOUD_LIVENESS_EOF",`chmod +x ${S}`,`rm -f ${_}.fail ${_}.restarts`,`cat > /etc/systemd/system/${t}-liveness.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=Liveness check for ${t} (managed by ts-cloud)`,"","[Service]","Type=oneshot",`ExecStart=${S}`,"TS_CLOUD_UNIT_EOF",`cat > /etc/systemd/system/${t}-liveness.timer <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=Run the ${t} liveness check every ${i}s`,"","[Timer]",`OnUnitActiveSec=${i}s`,`OnBootSec=${i}s`,"Persistent=true","","[Install]","WantedBy=timers.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",`systemctl enable --now ${t}-liveness.timer >/dev/null 2>&1 || true`]}var Ws=20,On=3,hc=5,Sc=60;function vc(e){let{paths:t,unitBase:r,releaseId:n,port:s}=e,i=`${r}@${n}.service`,a=`${r}.service`,c=Math.max(1,e.healthGateSeconds??5),f=e.healthCheckPath?e.healthCheckPath.startsWith("/")?e.healthCheckPath:`/${e.healthCheckPath}`:null,g=f?`curl -sf -o /dev/null --max-time ${hc} "http://127.0.0.1:${s}${f}"`:null,h=(S)=>`{ echo "[ts-cloud] release ${n} ${S}" >&2; ts_cloud_restore_previous; exit 1; }`;return[`TS_CLOUD_OLD_UNITS=$(systemctl list-units --plain --no-legend --type=service "${r}@*.service" 2>/dev/null | awk '{print $1}' | grep -v "^${i}$" || true)`,`TS_CLOUD_PREV_CURRENT="$(readlink ${t.current} 2>/dev/null || true)"`,"TS_CLOUD_LEGACY_STOPPED=0","ts_cloud_restore_previous() {",` journalctl -u ${i} -n 50 --no-pager >&2 || true`,` systemctl stop ${i} 2>/dev/null || true`,` systemctl disable ${i} 2>/dev/null || true`,` if [ -n "$TS_CLOUD_PREV_CURRENT" ] && [ -d "$TS_CLOUD_PREV_CURRENT" ]; then ln -sfn "$TS_CLOUD_PREV_CURRENT" ${t.current}.tmp && mv -Tf ${t.current}.tmp ${t.current}; fi`,' for TS_CLOUD_RU in ${TS_CLOUD_OLD_UNITS}; do systemctl enable "$TS_CLOUD_RU" 2>/dev/null || true; systemctl start "$TS_CLOUD_RU" 2>/dev/null || true; done',` if [ "$TS_CLOUD_LEGACY_STOPPED" -eq 1 ]; then systemctl start ${a} 2>/dev/null || true; fi`,' if [ -n "$TS_CLOUD_OLD_UNITS" ] || [ "$TS_CLOUD_LEGACY_STOPPED" -eq 1 ]; then echo "[ts-cloud] previous release restored and serving" >&2; else echo "[ts-cloud] there was no previous release to restore" >&2; fi',"}",`if [ -f /etc/systemd/system/${a} ] && systemctl is-active --quiet ${a}; then echo "[ts-cloud] retiring pre-zero-downtime unit ${a} (one-time restart cutover)"; systemctl stop ${a}; TS_CLOUD_LEGACY_STOPPED=1; fi`,'TS_CLOUD_STARTED_AT="@$(date +%s)"',`systemctl restart ${i}`,`TS_CLOUD_GATE_OK=1; for TS_CLOUD_I in $(seq 1 ${c}); do sleep 1; systemctl is-active --quiet ${i} || { TS_CLOUD_GATE_OK=0; break; }; done`,'if [ "$TS_CLOUD_GATE_OK" -ne 1 ]; then',` if journalctl -u ${i} --since "$TS_CLOUD_STARTED_AT" -o cat --no-pager 2>/dev/null | grep -iE 'EADDRINUSE|address already in use|port [0-9]+ (is )?in use|Failed to start server' >/dev/null; then`,` echo "[ts-cloud] release ${n} could not share :${s} with the previous release (no SO_REUSEPORT?) — retiring it and retrying" >&2`,' for TS_CLOUD_RU in ${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_RU" 2>/dev/null || true; done',` systemctl restart ${i}`,` for TS_CLOUD_I in $(seq 1 ${c}); do sleep 1; systemctl is-active --quiet ${i} || ${h("failed its health gate on the free port")}; done`," else",` ${h("crashed on start — the previous release was never stopped")}`," fi","fi",`if ss -ltnpH "sport = :${s}" >/dev/null 2>&1; then`," TS_CLOUD_BOUND=0",` for TS_CLOUD_I in $(seq 1 ${Sc}); do`,` TS_CLOUD_NEW_PID="$(systemctl show -p MainPID --value ${i} 2>/dev/null || true)"`,` if [ -n "$TS_CLOUD_NEW_PID" ] && [ "$TS_CLOUD_NEW_PID" != "0" ] && ss -ltnpH "sport = :${s}" 2>/dev/null | grep "pid=$TS_CLOUD_NEW_PID," >/dev/null; then TS_CLOUD_BOUND=1; break; fi`,` systemctl is-active --quiet ${i} || break`,` sleep ${On}`," done",` [ "$TS_CLOUD_BOUND" -eq 1 ] || ${h(`never took :${s}`)}`,"else",' echo "[ts-cloud] cannot read listener PIDs on this host — the response probes run without the bind check" >&2',"fi",...g?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${Ws}); do if ${g}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${On}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${h(`never answered ${f}`)}`]:[],...dt(t),`systemctl enable ${i} 2>/dev/null || true`,'for TS_CLOUD_U in ${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done',`TS_CLOUD_LISTENING=0; for TS_CLOUD_I in $(seq 1 ${c}); do if ss -ltnH "sport = :${s}" 2>/dev/null | grep . >/dev/null; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done`,`if [ "$TS_CLOUD_LISTENING" -ne 1 ]; then echo "[ts-cloud] nothing is listening on ${s} after retiring the previous release — restarting ${i} on the now-free port" >&2; systemctl restart ${i}; for TS_CLOUD_I in $(seq 1 ${c}); do if ss -ltnH "sport = :${s}" 2>/dev/null | grep . >/dev/null; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done; fi`,`[ "$TS_CLOUD_LISTENING" -eq 1 ] || ${h(`is active but never bound :${s}`)}`,...g?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${Ws}); do if ${g}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${On}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${h(`stopped answering ${f} once it served alone`)}`]:[],...wn(t),`systemctl list-unit-files --plain --no-legend "${r}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v -e "^${i}$" -e "^${r}@\\.service$" || true; } | while read -r TS_CLOUD_U; do systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done`,`if [ -f /etc/systemd/system/${a} ]; then systemctl disable ${a} 2>/dev/null || true; rm -f /etc/systemd/system/${a}; systemctl daemon-reload; fi`]}function Xs(e,t){if(!t.length)return[];let r=We(e.release);return[`if [ -e ${r} ] || [ -L ${r} ]; then`,...t,"fi"]}function si(e){let{siteName:t,slug:r,artifactFetch:n,releaseId:s,execStart:i,envEntries:a,port:c,keepReleases:f=Ht,preStartCommands:g=[],postActivateCommands:h=[],beforeResetCommands:S=[],healthCheckPath:_,healthGateSeconds:v=5,liveness:y,memoryHigh:T="auto",memoryMax:x,cpuWeight:q,ioWeight:H,tasksMax:R,stopTimeout:L}=e,I=[...q!=null?[`CPUWeight=${q}`]:[],...H!=null?[`IOWeight=${H}`]:[],...R!=null?[`TasksMax=${R}`]:[],...L?[`TimeoutStopSec=${L}`]:[]],V=e.zeroDowntime??c!=null,W=e.appDir??`/var/www/${t}`,K=Zt(W,s),te=`${r}-${t}`,Z=`${te}.service`,re=ai(r,t,s),ie=e.sharedPaths??[],oe=Hs([".env",...ie,...yr(a,ie)]),ne=fr(a),pe=Ys(K.release,g,a),ge=["set -euo pipefail",...vn(K),...n,...Ft(K,oe),...Xs(K,S),yn(K),...$n(K),`tar xzf ${re} -C "$TS_CLOUD_STAGED"`,`rm -f ${re}`,`cat > ${K.shared}/.env <<'TS_CLOUD_ENV_EOF'`,ne,"TS_CLOUD_ENV_EOF",`chmod 600 ${K.shared}/.env`,...bn(K),`find ${K.release} -maxdepth 1 \\( -type f -o -type l \\) -name '.env*' ! -name '.env.example' ! -name '*.example' -delete`,`sed -i -E '/^[[:space:]]*(PORT|PORT_BACKEND|PORT_ADMIN|PORT_FRONTEND)[[:space:]]*=/d' ${K.shared}/.env 2>/dev/null || true`,...Sr(K,oe),...pe,...e.isolation?Ls(e.slug||t,K.base,oe.flatMap((b)=>typeof b==="string"||!b.target?[]:[b.target])):[]];if(V&&c!=null){let b=`${te}@${s}.service`,k=_?_.startsWith("/")?_:`/${_}`:null;return[...ge,`cat > /etc/systemd/system/${te}@.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} release %i (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",...e.isolation?Ut(pt(e.slug||t),K.base,e.slug||t):[],`WorkingDirectory=${K.releases}/%i`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...T&&T!=="auto"?[`MemoryHigh=${T}`]:[],...x?[`MemoryMax=${x}`]:[],...I,`EnvironmentFile=${K.releases}/%i/.env`,`Environment=PORT=${c}`,`Environment=STX_IMAGE_CACHE_DIR=${hr(K)}`,`Environment=STX_BUNDLE_CACHE_DIR=${Mt(K)}`,`Environment=STX_BUNDLE_CACHE_DIR=${Mt(K)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...T==="auto"?Vs(`${te}@.service`):[...br(`${te}@.service`),...Dn()],...gc(b),...vc({paths:K,unitBase:te,releaseId:s,port:c,healthCheckPath:k,healthGateSeconds:v}),...h,...mt(K,f),...y===!1?[]:qs({...y,unitBase:te,unitPattern:`${te}@*.service`,port:c,path:y?.path??_})]}return[...ge,`cat > /etc/systemd/system/${Z} <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",...e.isolation?Ut(pt(e.slug||t),K.base,e.slug||t):[],`WorkingDirectory=${K.current}`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...T&&T!=="auto"?[`MemoryHigh=${T}`]:[],...x?[`MemoryMax=${x}`]:[],...I,`EnvironmentFile=${K.current}/.env`,...c?[`Environment=PORT=${c}`]:[],`Environment=STX_IMAGE_CACHE_DIR=${hr(K)}`,`Environment=STX_BUNDLE_CACHE_DIR=${Mt(K)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...br(Z,{auto:T!=="auto",high:T!=="auto",max:Boolean(x)}),...T==="auto"?Vs(Z):Dn(),`systemctl enable ${Z}`,`TS_CLOUD_PREV_CURRENT="$(readlink ${K.current} 2>/dev/null || true)"`,...dt(K),`systemctl restart ${Z}`,`for TS_CLOUD_I in $(seq 1 ${Math.max(1,v)}); do sleep 1; systemctl is-active --quiet ${Z} || { echo "[ts-cloud] release ${s} of ${Z} did not stay up — restoring the previous release" >&2; journalctl -u ${Z} -n 50 --no-pager >&2 || true; if [ -n "$TS_CLOUD_PREV_CURRENT" ] && [ -d "$TS_CLOUD_PREV_CURRENT" ] && [ "$(readlink -f "$TS_CLOUD_PREV_CURRENT")" != "$(readlink -f ${K.release})" ]; then ln -sfn "$TS_CLOUD_PREV_CURRENT" ${K.current}.tmp && mv -Tf ${K.current}.tmp ${K.current}; systemctl restart ${Z} || true; fi; exit 1; }; done`,...wn(K),...h,...mt(K,f),...y===!1||!c?[]:qs({...y,unitBase:te,unitPattern:Z,port:c,path:y?.path??_})]}function oi(e){let{siteName:t,artifactFetch:r,releaseId:n,keepReleases:s=Ht,preStartCommands:i=[],postActivateCommands:a=[],beforeResetCommands:c=[]}=e,f=e.appDir??`/var/www/${t}`,g=Zt(f,n),h=ai(e.slug,t,n),S=Ys(g.release,i);return["set -euo pipefail",...vn(g),...r,...Ft(g,[]),...Xs(g,c),yn(g),...$n(g),`tar xzf ${h} -C "$TS_CLOUD_STAGED"`,...bn(g),`rm -f ${h}`,...S,...dt(g),...a,...mt(g,s)]}function ai(e,t,r){return`/tmp/${[e,t,r].filter(Boolean).join("-")}-release.tar.gz`}function $c(e,t,r,n){return[`aws s3 cp "s3://${e}/${t}" ${n} --region ${r}`]}function Mc(e,t){return[`mv "${e}" ${t}`]}function We(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function Tr(e,t,r){return["set -euo pipefail",`chmod 600 ${We(e)}`,`mv -f -- ${We(e)} ${We(t)}`,`cp -- ${We(t)} ${We(r)}`].join(`
160
160
  `)}function wr(e){return`rm -f -- ${We(e)} 2>/dev/null || true`}function xn(e={}){let t=Math.max(1,e.appServers??e.instances??1),r=!!e.servicesServer||t>1,n=t>1||!!e.server?.loadBalancer;return{appServers:t,loadBalancer:n,dedicatedServices:r,servicesOnApp:!r}}function Js(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 An(e){let t=e.infrastructure?.compute??{},r=p(e);return[...ir(t.managedServices??{mysql:!0,redis:!0},{bindPrivate:!0}),...ct(r,t.managedServices??{mysql:!0}),...Me(!0),...Le(!0),...lt(t.sshKeys),...Je(e.notifications),...t.backups?.enabled?[...ar({database:r,backups:t.backups})]:[]]}var Kt=["-S","ssh"];function ci(e={},t="ssh"){let r=[];if(e.identityFile)r.push("-i",e.identityFile);if(e.port)r.push(t==="scp"?"-P":"-p",String(e.port));return r.push("-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR","-o",`ConnectTimeout=${e.connectTimeoutSec??10}`),r}async function Qr(e,t,r={}){let n=Bun.spawn(["ssh",...ci(r),`${r.user??"root"}@${e}`,t],{stdout:"pipe",stderr:"pipe"}),[s,i]=await Promise.all([new Response(n.stdout).text(),new Response(n.stderr).text()]);return{code:await n.exited,stdout:s,stderr:i}}async function Ie(e,t,r={}){let n=await Qr(e,t,r);if(n.code!==0)throw Error(`ssh \`${t}\` on ${e} failed (${n.code}): ${n.stderr.trim()||n.stdout.trim()}`);return n.stdout}async function Fc(e,t,r,n={}){let s=Bun.spawn(["scp",...Kt,...ci(n,"scp"),...t,`${n.user??"root"}@${e}:${r}`],{stdout:"pipe",stderr:"pipe"}),i=await s.exited;if(i!==0){let a=await new Response(s.stderr).text();throw Error(`scp to ${e}:${r} failed (${i}): ${a.trim()}`)}}async function At(e,t={}){let r=t.timeoutMs??180000,n=t.pollIntervalMs??5000,s=Date.now();while(Date.now()-s<r){let i=await Qr(e,"echo ready",t);if(i.code===0&&i.stdout.includes("ready"))return;await new Promise((a)=>setTimeout(a,n))}throw Error(`SSH not ready on ${e} after ${r}ms`)}async function Uc(e,t={}){let r=t.timeoutMs??300000,n=t.pollIntervalMs??5000,s=Date.now();while(Date.now()-s<r){let i=await Qr(e,"cloud-init status 2>/dev/null || echo unknown",t);if(i.stdout.includes("status: done"))return;if(i.stdout.includes("status: error"))throw Error(`cloud-init reported an error on ${e}; check /var/log/cloud-init-output.log`);await new Promise((a)=>setTimeout(a,n))}throw Error(`cloud-init did not finish on ${e} after ${r}ms`)}function di(e={}){return["set -e","ts_cloud_script=$(mktemp /tmp/ts-cloud-deploy.XXXXXXXX)",`trap 'rm -f "$ts_cloud_script"' EXIT`,'cat > "$ts_cloud_script"',e.sudo?'sudo -n -H bash "$ts_cloud_script" < /dev/null':'bash "$ts_cloud_script" < /dev/null'].join(`
161
161
  `)}var Qc=di();import{homedir as yc}from"node:os";import{join as bc}from"node:path";var Cr={location:"fsn1",image:"ubuntu-24.04",sshUser:"root",sshPrivateKeyPath:"~/.ssh/id_ed25519"};function Pr(e){return e.startsWith("~/")?bc(yc(),e.slice(2)):e}function ft(...e){for(let t of e){let r=process.env[t]?.trim();if(r)return r}return}function gt(...e){for(let t of e){let r=t?.trim();if(r)return r}return}function jt(e,t){return gt(e,t?.hetzner?.apiToken,ft("HCLOUD_TOKEN","HETZNER_API_TOKEN"))}function Hc(e,t){return gt(t,e?.hetzner?.location,ft("HCLOUD_LOCATION","HETZNER_LOCATION"))??Cr.location}function Gt(e,t){let r=e?.infrastructure?.compute;return gt(t,r?.image,e?.hetzner?.image,ft("HCLOUD_IMAGE","HETZNER_IMAGE"))??Cr.image}function Tc(e,t){return gt(t,e?.hetzner?.sshUser,ft("HCLOUD_SSH_USER","HETZNER_SSH_USER"))??Cr.sshUser}function Qs(e,t){return Pr(gt(t,e?.hetzner?.sshPrivateKeyPath,ft("HCLOUD_SSH_KEY","HETZNER_SSH_KEY"))??Cr.sshPrivateKeyPath)}function wc(e,t,r){let n=gt(t,e?.hetzner?.sshPublicKeyPath,ft("HCLOUD_SSH_PUBLIC_KEY","HETZNER_SSH_PUBLIC_KEY"));if(n)return Pr(n);return`${r??Qs(e)}.pub`}function uo(e,t={}){let r=Qs(e,t.sshPrivateKeyPath);return{apiToken:jt(t.apiToken,e),location:Hc(e,t.location),image:Gt(e,t.image),sshUser:Tc(e,t.sshUser),sshPrivateKeyPath:r,sshPublicKeyPath:wc(e,t.sshPublicKeyPath,r)}}var Cc="https://api.hetzner.cloud/v1";class Er extends Error{status;code;details;constructor(e,t,r,n){super(e);this.status=t;this.code=r;this.details=n;this.name="HetznerApiError"}}class Rr extends Error{action;constructor(e,t){super(e);this.action=t;this.name="HetznerActionError"}}function mo(e){return e.map((t)=>({type:"server",server:{id:t.server}}))}class Hr{name="hetzner";apiToken;baseUrl;fetchImpl;constructor(e){this.apiToken=e.apiToken,this.baseUrl=e.baseUrl??Cc,this.fetchImpl=e.fetchImpl??fetch}async request(e,t,r){let n=await this.fetchImpl(`${this.baseUrl}${t}`,{method:e,headers:{Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},body:r===void 0?void 0:JSON.stringify(r)}),s=await n.text(),i;try{i=s?JSON.parse(s):{}}catch{if(!n.ok){let a=s.trim().slice(0,200)||n.statusText||"Hetzner API error";throw Error(`Hetzner API ${e} ${t} (${n.status}): ${a}`)}throw Error(`Hetzner API ${e} ${t}: unexpected non-JSON response`)}if(!n.ok){let a=i.error?.message||n.statusText||"Hetzner API error",c=i.error?.code?` [${i.error.code}]`:"";throw new Er(`Hetzner API ${e} ${t} (${n.status})${c}: ${a}`,n.status,i.error?.code,i.error?.details)}return i}async requestAll(e,t){let r=[],n=1;for(;;){let s=e.includes("?")?"&":"?",i=await this.request("GET",`${e}${s}per_page=50&page=${n}`);r.push(...i[t]??[]);let a=i.meta?.pagination?.next_page;if(!a)return r;n=a}}async listServers(){return this.requestAll("/servers","servers")}async getLocation(e){let r=(await this.request("GET",`/locations?name=${encodeURIComponent(e)}`)).locations.find((n)=>n.name===e);if(!r)throw Error(`Hetzner location not found: ${e}`);return r}async getServer(e){return(await this.request("GET",`/servers/${e}`)).server}async listVolumes(){return this.requestAll("/volumes","volumes")}async getVolume(e){return(await this.request("GET",`/volumes/${e}`)).volume}async createVolume(e){return this.request("POST","/volumes",{...e,automount:!1})}async attachVolume(e,t){return(await this.request("POST",`/volumes/${e}/actions/attach`,{server:t,automount:!1})).action}async resizeVolume(e,t){return(await this.request("POST",`/volumes/${e}/actions/resize`,{size:t})).action}async protectVolume(e,t){return(await this.request("POST",`/volumes/${e}/actions/change_protection`,{delete:t})).action}async getServerMetrics(e,t){let r=new URLSearchParams({type:t.types.join(","),start:t.start.toISOString(),end:t.end.toISOString(),step:String(Math.max(60,Math.floor(t.step??60)))});return(await this.request("GET",`/servers/${e}/metrics?${r}`)).metrics}async listServerTypes(e){let t=e?`?name=${encodeURIComponent(e)}`:"";return this.requestAll(`/server_types${t}`,"server_types")}async getServerType(e){return(await this.listServerTypes(e)).find((t)=>t.name===e)??null}async createServer(e){let t=await this.request("POST","/servers",{name:e.name,server_type:e.serverType,image:e.image,location:e.location,datacenter:e.datacenter,ssh_keys:e.sshKeys,user_data:e.userData,labels:e.labels,firewalls:e.firewalls,networks:e.networks,start_after_create:!0});return{server:t.server,action:t.action}}async listNetworks(){return this.requestAll("/networks","networks")}async createNetwork(e){let t=e.ipRange??"10.0.0.0/16";return(await this.request("POST","/networks",{name:e.name,ip_range:t,subnets:[{type:"cloud",ip_range:t,network_zone:"eu-central"}],labels:e.labels})).network}async deleteNetwork(e){await this.request("DELETE",`/networks/${e}`)}async listLoadBalancers(){return this.requestAll("/load_balancers","load_balancers")}async createLoadBalancer(e){return(await this.request("POST","/load_balancers",{name:e.name,load_balancer_type:e.type??"lb11",location:e.location,network_zone:e.network?void 0:e.networkZone??"eu-central",network:e.network,labels:e.labels,targets:[{type:"label_selector",label_selector:{selector:e.labelSelector},use_private_ip:!!e.network}],services:e.services.map((r)=>({protocol:r.protocol??"tcp",listen_port:r.listenPort,destination_port:r.destinationPort,health_check:{protocol:"http",port:80,interval:15,timeout:10,retries:3,http:{path:"/",status_codes:["2??","3??"]}}}))})).load_balancer}async deleteLoadBalancer(e){await this.request("DELETE",`/load_balancers/${e}`)}async deleteServer(e){return(await this.request("DELETE",`/servers/${e}`)).action}async listFirewalls(){return this.requestAll("/firewalls","firewalls")}async createFirewall(e){let t=await this.request("POST","/firewalls",{name:e.name,rules:e.rules,labels:e.labels,apply_to:e.applyTo?mo(e.applyTo):void 0});return{firewall:t.firewall,actions:t.actions}}async setFirewallRules(e,t){return(await this.request("POST",`/firewalls/${e}/actions/set_rules`,{rules:t})).actions??[]}async deleteFirewall(e){await this.request("DELETE",`/firewalls/${e}`)}async applyFirewallToResources(e,t){return(await this.request("POST",`/firewalls/${e}/actions/apply_to_resources`,{apply_to:mo(t)})).actions}async listSshKeys(){return this.requestAll("/ssh_keys","ssh_keys")}async createSshKey(e){return(await this.request("POST","/ssh_keys",{name:e.name,public_key:e.publicKey,labels:e.labels})).ssh_key}async deleteSshKey(e){await this.request("DELETE",`/ssh_keys/${e}`)}async getAction(e){return(await this.request("GET",`/actions/${e}`)).action}async shutdownServer(e){return(await this.request("POST",`/servers/${e}/actions/shutdown`,{})).action}async powerOnServer(e){return(await this.request("POST",`/servers/${e}/actions/poweron`,{})).action}async changeServerType(e,t,r){return(await this.request("POST",`/servers/${e}/actions/change_type`,{server_type:t,upgrade_disk:r})).action}async powerOffServer(e){return(await this.request("POST",`/servers/${e}/actions/poweroff`,{})).action}async stopServer(e,t){if((await this.getServer(e)).status==="off")return;await this.shutdownServer(e);let n=t?.gracefulWaitMs??120000,s=t?.pollIntervalMs??3000,i=Date.now();while(Date.now()-i<n){if((await this.getServer(e)).status==="off")return;await new Promise((c)=>setTimeout(c,s))}let a=await this.powerOffServer(e);await this.waitForAction(a.id),await this.waitForServerStatus(e,"off")}async renameServer(e,t){return(await this.request("PUT",`/servers/${e}`,{name:t})).server}async listImages(e){let t=e?.type?`?type=${encodeURIComponent(e.type)}`:"";return this.requestAll(`/images${t}`,"images")}async getImage(e){return(await this.request("GET",`/images/${e}`)).image}async createImage(e,t){return this.request("POST",`/servers/${e}/actions/create_image`,{description:t.description,type:t.type??"snapshot",labels:t.labels})}async deleteImage(e){await this.request("DELETE",`/images/${e}`)}async rebuildServer(e,t){return(await this.request("POST",`/servers/${e}/actions/rebuild`,{image:t})).action}async listPrimaryIps(){return this.requestAll("/primary_ips","primary_ips")}async unassignPrimaryIp(e){return(await this.request("POST",`/primary_ips/${e}/actions/unassign`,{})).action}async assignPrimaryIp(e,t){return(await this.request("POST",`/primary_ips/${e}/actions/assign`,{assignee_id:t,assignee_type:"server"})).action}async waitForAction(e,t){let r=t?.pollIntervalMs??2000,n=t?.maxWaitMs??300000,s=Date.now();while(Date.now()-s<n){let i=await this.getAction(e);if(i.status==="success")return i;if(i.status==="error")throw new Rr(i.error?.message||"Hetzner action failed",i);await new Promise((a)=>setTimeout(a,r))}throw Error(`Timed out waiting for Hetzner action ${e}`)}async waitForServerRunning(e,t){let r=t?.pollIntervalMs??3000,n=t?.maxWaitMs??600000,s=Date.now();while(Date.now()-s<n){let i=await this.getServer(e);if(i.status==="running")return i;await new Promise((a)=>setTimeout(a,r))}throw Error(`Timed out waiting for server ${e} to reach running state`)}async waitForServerStatus(e,t,r){let n=r?.pollIntervalMs??3000,s=r?.maxWaitMs??600000,i=Date.now();while(Date.now()-i<s){let a=await this.getServer(e);if(a.status===t)return a;await new Promise((c)=>setTimeout(c,n))}throw Error(`Timed out waiting for server ${e} to reach ${t} state`)}}function Gc(e,t){let r=jt(e,t);if(!r)throw Error("Hetzner API token required. Set hetzner.apiToken in cloud.config.ts or HCLOUD_TOKEN / HETZNER_API_TOKEN.");return r}function qe(e){let[t,r]=e.trim().split(/\s+/);return r?`${t} ${r}`:t}function fo(e){if(!e)return"";return e.endsWith(`
162
162
  `)?e:`${e}
@@ -278,7 +278,7 @@ case "$root_fs" in
278
278
  esac`,e)}async function Bc(e,t){let r=Buffer.from(t.join(`
279
279
  `)).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 jc(e,t,r,n={recovered:!1}){if(await At(e.host,{...e,timeoutMs:e.sshTimeoutMs??600000}),!n.recovered)await Nc(e);if(r)await Bc(e,r.runningServices);let s=await Vc(e),i=[],a=r?vt(r.runningServices,s.runningServices):[],c=r?vt(r.releaseLinks,s.releaseLinks):[],f=r?vt(r.routeFragments,s.routeFragments):[],g=r?vt(r.routeIds,s.routeIds):[],h=r?.persistentData.map((L)=>L.split("=")[0])??[],S=s.persistentData.map((L)=>L.split("=")[0]),_=vt(h,S),v=r?vt(r.dataCatalog,s.dataCatalog):[],y=s.routeProbes.filter((L)=>!L.ok),T=n.recovered&&r?r.cpuCores:t.cores??0,x=n.recovered&&r?r.memoryBytes:kc(t),q=s.cpuCores>=T,H=s.memoryBytes>=x*0.9,R=n.recovered||s.rootDiskBytes>=(t.disk??0)*1e9*0.95;if(s.failedUnits.length>0)i.push(`Failed services: ${s.failedUnits.join(", ")}`);if(a.length>0)i.push(`Services did not return: ${a.join(", ")}`);if(c.length>0)i.push(`Release links changed: ${c.join(", ")}`);if(f.length>0)i.push(`Route manifests changed: ${f.join(", ")}`);if(g.length>0)i.push(`Routes disappeared: ${g.join(", ")}`);if(_.length>0)i.push(`Persistent data paths disappeared: ${_.join(", ")}`);if(v.length>0)i.push(`Databases or volumes disappeared: ${v.join(", ")}`);if(y.length>0)i.push(`Unhealthy routes: ${y.map((L)=>L.domain).join(", ")}`);if(!q)i.push(`Expected at least ${T} CPU cores, found ${s.cpuCores}`);if(!H)i.push(`Expected at least ${x} bytes of RAM`);if(!R)i.push(`Expected approximately ${t.disk??0} GB root disk`);return{ok:i.length===0,checks:{cpuCores:s.cpuCores,memoryBytes:s.memoryBytes,rootDiskBytes:s.rootDiskBytes,rootFilesystemBytes:s.rootFilesystemBytes,runningServices:s.runningServices.length,releaseLinks:s.releaseLinks.length,routeFragments:s.routeFragments.length,routes:s.routeIds.length,healthyRoutes:s.routeProbes.filter((L)=>L.ok).length,persistentDataPaths:s.persistentData.length,databasesAndVolumes:s.dataCatalog.length,failedUnits:s.failedUnits.length},failures:i}}import{mkdir as el,readFile as tl,rename as rl,writeFile as nl}from"node:fs/promises";import{join as go}from"node:path";var zc="storage/cloud/state";function yt(e=process.cwd()){return il()?l(e,"state"):go(e,zc)}function je(e,t=process.cwd()){return go(yt(t),`${e}.json`)}async function ze(e,t=process.cwd()){try{let r=await tl(je(e,t),"utf8");return JSON.parse(r)}catch{return null}}async function St(e,t,r=process.cwd()){let n=je(e,r);await el(yt(r),{recursive:!0});let s=`${n}.${process.pid}.tmp`;await nl(s,`${JSON.stringify(t,null,2)}
280
280
  `,"utf8"),await rl(s,n)}async function rt(e){return ze(e)}async function nt(e,t){await St(e,t)}async function ui(e,t,r){let n=r.length?await e.listVolumes():[];return r.map((s)=>{let i=n.filter((g)=>g.name===s.name);if(i.length>1)throw Error(`Ambiguous volume name: ${s.name}`);let a=i[0];if(a&&a.server!==null&&a.server!==t.id)throw Error(`Volume ${a.name} belongs to another server; refusing to detach live storage`);let c=t.location?.name??t.datacenter?.location.name;if(a&&a.location.name!==c)throw Error(`Volume ${a.name} is in ${a.location.name}, server is in ${c}`);if(a&&a.size>s.size)throw Error(`Refusing to shrink volume ${a.name}: ${a.size} GB to ${s.size} GB`);let f=[];if(!a)f.push("create");else{if(a.server===null)f.push("attach");if(a.size<s.size)f.push("grow")}if(!a||a.protection.delete!==(s.deleteProtection!==!1))f.push("protect");return f.push("mount"),{declaration:s,existing:a,actions:f}})}async function gi(e,t,r){let n=[];for(let s of r){let i=s.existing,a=!i;if(!i){let c=await e.createVolume({name:s.declaration.name,size:s.declaration.size,server:t.id,labels:{...t.labels,"ts-cloud/volume":s.declaration.key}});await e.waitForAction(c.action.id);for(let f of c.next_actions??[])await e.waitForAction(f.id);i=await e.getVolume(c.volume.id)}if(i.server===null)await e.waitForAction((await e.attachVolume(i.id,t.id)).id),i=await e.getVolume(i.id);if(i.server!==t.id||i.location.name!==(t.location?.name??t.datacenter?.location.name))throw Error(`Volume attachment verification failed: ${i.name}`);if(i.linux_device!==`/dev/disk/by-id/scsi-0HC_Volume_${i.id}`)throw Error(`Unexpected Hetzner volume device: ${i.name}`);if(i.size<s.declaration.size)await e.waitForAction((await e.resizeVolume(i.id,s.declaration.size)).id);if(i.protection.delete!==(s.declaration.deleteProtection!==!1))await e.waitForAction((await e.protectVolume(i.id,s.declaration.deleteProtection!==!1)).id);n.push({...s.declaration,id:i.id,device:i.linux_device,allowFormat:a})}return n}var kn=268435456;function Vt(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function ul(e){let t=ol("sha256");for await(let r of al(e))t.update(r);return t.digest("hex")}class Pe{name="hetzner";usesCloudFormation=!1;client;sshPrivateKeyPath;sshPublicKeyPath;sshUser;location;stateOnly;residency;waitForBoot;bootWait;async applyComputeChanges(e){let{config:t,environment:r}=e;if(t.cloud?.attachTo)throw Error("Only the compute owner may reconcile server size and volumes");let n=t.infrastructure?.compute;if(n?.resize&&!n.size)throw Error("compute.resize requires an explicit compute.size");let s=ei(t,r),i=xn(n??{});if(i.appServers>1||i.dedicatedServices)throw Error("Managed compute volumes currently require a single app server");let a=await this.getComputeOutputs(e);if(!a.appInstanceId)throw Error("No existing compute server found; provision the server first");let c=await this.client.getServer(Number(a.appInstanceId)),f=await ui(this.client,c,s),g=n?.resize&&n.size?await er(this.client,c.id,Ye(n.size),n.resize.upgradeDisk!==!1):void 0,h={serverId:String(c.id),changes:f.flatMap((y)=>y.actions.map((T)=>({resource:y.declaration.name,action:T,detail:`${y.declaration.size} GB at ${y.declaration.mountPath}`})))};if(n?.deploymentStorage)h.changes.push({resource:n.deploymentStorage.volume,action:"place-deployments",detail:`Reconcile release directories${n.deploymentStorage.includeBackups!==!1?" and deployment backups":""} on the volume; ${n.deploymentStorage.migrateExisting?"verify and migrate existing files":"refuse nonempty directories"}`});if(g&&!g.alreadyComplete)if(!g.capacityAvailable){if(n?.resize?.whenUnavailable!=="keep-current")throw Error(`${g.targetType.name} is unavailable in ${g.location}`);h.waitingForCapacity=`${g.targetType.name} unavailable in ${g.location}; keeping ${c.server_type.name} running`}else h.changes.push({resource:c.name,action:"resize",detail:`${c.server_type.name} to ${g.targetType.name}`});if(e.dryRun)return h;if(h.waitingForCapacity)console.warn(`[ts-cloud] ${h.waitingForCapacity}`);let S=await gi(this.client,c,f),_=[{id:String(c.id),name:c.name,publicIp:c.public_net.ipv4?.ip}],v=[...Je(t.notifications),...n?.volumes||n?.deploymentStorage?ti({volumes:S,deploymentStorage:n?.deploymentStorage,webRoot:"/var/www"}):[],...n?.monitoring!==!1?Le(n?.monitoring):[]];if(v.length){let y=await this.runRemoteDeploy({targets:_,commands:v,timeoutSeconds:7200,comment:"ts-cloud apply configured compute storage"});if(!y.success)throw Error(y.error||y.perInstance.map((T)=>T.error||T.output).join(`
281
- `))}if(g?.capacityAvailable&&!g.alreadyComplete){let y={host:_[0].publicIp,user:this.sshUser,identityFile:this.sshPrivateKeyPath},T=await li({client:this.client,serverId:c.id,targetType:g.targetType.name,upgradeDisk:g.upgradeDisk,hooks:{preflight:()=>qc(y),afterBoot:(x,q,H,R)=>jc(y,q,H,R)}});if(T.status!=="completed"&&T.status!=="already-complete")throw Error(`Resize did not complete: ${T.status}`)}return h}constructor(e={}){this.residency=e.residency;let t=jt(e.apiToken);if(this.stateOnly=!e.client&&!t&&e.allowStateOnly===!0,!e.client&&!t&&!this.stateOnly)throw Error("Hetzner API token required. Set hetzner.apiToken in cloud.config.ts or HCLOUD_TOKEN / HETZNER_API_TOKEN.");this.client=e.client??new Hr({apiToken:t??""});let r=uo(void 0,{sshPrivateKeyPath:e.sshPrivateKeyPath,sshPublicKeyPath:e.sshPublicKeyPath,sshUser:e.sshUser,location:e.location});this.sshPrivateKeyPath=r.sshPrivateKeyPath,this.sshPublicKeyPath=r.sshPublicKeyPath,this.sshUser=r.sshUser,this.location=r.location,this.waitForBoot=e.waitForBoot??!0,this.bootWait={sshIntervalMs:e.bootWait?.sshIntervalMs??5000,sshTimeoutMs:e.bootWait?.sshTimeoutMs??300000,cloudInitIntervalMs:e.bootWait?.cloudInitIntervalMs??5000,cloudInitTimeoutMs:e.bootWait?.cloudInitTimeoutMs??600000}}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e,n=t.project.slug,s=t.infrastructure?.compute;if(!s)throw Error("infrastructure.compute is required to provision Hetzner compute");if(t.cloud?.attachTo)return this.attachToComputeInfrastructure(t.cloud.attachTo,t,r);let i=m(t,r),a=`${n}-${r}-app`,c=s.runtime==="php"||!!s.php,f=xn(s),g=t.cloud?.residency||this.residency,{assertComputeResidency:h}=await import("./chunk-nh7rcks9.js"),S=(b)=>{if(g)h(g,{country:b.location?.country||b.datacenter?.location?.country,location:b.location?.name||b.datacenter?.location?.name})};if(g){if(f.dedicatedServices||f.appServers>1)throw Error("Residency policy currently requires single-host compute");let b=await this.client.getLocation(t.hetzner?.location||this.location);h(g,{country:b.country,location:b.name})}if(f.dedicatedServices||f.appServers>1)return c?this.provisionFleet(e,f):this.provisionBunFleet(e,f);let _=fe(n,r,"app"),v=t.sites||{},y=j(s)?[]:this.collectUpstreamPorts(v),T=`${n}-${r}-app-fw`,{firewall:x}=await this.ensureFirewall(T,_,Dr({allowSsh:s.allowSsh!==!1,sitePorts:y,allowedPorts:[...s.firewall?.allowedPorts??[],...Cs(t.infrastructure?.sftp),...Ze(C(t,{environment:r}))]})),q=await this.ensureSshKey(n,r,_),H=await rt(i);if(H?.serverId){let b=await this.tryGetServer(H.serverId);if(b&&b.status!=="off"&&b.labels?.["ts-cloud/project"]===n&&b.labels?.["ts-cloud/environment"]===r){if(S(b),s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(H,b)}}let R=await this.findExistingServer(n,r,a);if(R&&R.status!=="off"){S(R);let b={provider:"hetzner",stackName:i,serverId:R.id,serverName:R.name,publicIp:R.public_net.ipv4?.ip,publicIpv6:De(R.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};if(await nt(i,b),s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(b,R)}let L=w(t,{environment:r}),I=L?.engine==="rpx"?G({proxy:L,config:B(v,{proxy:L,slug:t.project.slug,mail:C(t,{environment:r})}),slug:t.project.slug,bunBin:s.runtime==="node"||s.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,V=Qe(t,{environment:r}),W=s.bakedImage===!0,K=M({runtime:V.runtime,runtimeVersion:V.runtimeVersion,systemPackages:s.systemPackages,database:t.infrastructure?.database,phpProvision:V.phpProvision,servicesProvision:V.servicesProvision,rpxProvision:I,baked:W,swapGb:s.swapGb}),ee=se(K),te=Ye(s.size),ne=Gt(t),{server:ie,action:oe}=await this.client.createServer({name:a,serverType:te,image:ne,location:t.hetzner?.location||this.location,userData:ee,labels:_,sshKeys:q?[q]:void 0,firewalls:[{firewall:x.id}]});await this.client.waitForAction(oe.id);let re=await this.client.waitForServerRunning(ie.id);S(re);let pe={provider:"hetzner",stackName:i,serverId:re.id,serverName:re.name,firewallId:x.id,publicIp:re.public_net.ipv4?.ip,publicIpv6:De(re.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};await nt(i,pe);let ge=re.public_net.ipv4?.ip;if(ge&&this.waitForBoot)await this.waitForSshReady(ge),await this.waitForCloudInit(ge);if(s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(pe,re)}async provisionFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,i=r.infrastructure.compute,a=m(r,n),c=Ye(i.size),f=Gt(r),g=r.hetzner?.location||this.location,h=i.bakedImage===!0,S=await rt(a);if(S?.loadBalancerId){let O=(await this.client.listLoadBalancers().catch(()=>[])).find((D)=>D.id===S.loadBalancerId);if(O)return{appPublicIp:O.public_net?.ipv4?.ip,loadBalancerIp:O.public_net?.ipv4?.ip,servicesPrivateIp:S.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}let _=await this.ensureSshKey(s,n,fe(s,n,"app")),v=`${s}-${n}-net`,T=(await this.client.listNetworks().catch(()=>[])).find((P)=>P.name===v)??await this.client.createNetwork({name:v,labels:fe(s,n,"app")}),{firewall:x}=await this.ensureFirewall(`${s}-${n}-app-fw`,fe(s,n,"app"),Dr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),{firewall:q}=await this.ensureFirewall(`${s}-${n}-services-fw`,fe(s,n,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[T.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[T.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[T.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[T.ip_range]}]),H=An(r),R=se(M({runtime:"php",servicesProvision:H,baked:h,swapGb:i.swapGb})),L=await this.client.listServers().catch(()=>[]),I=[],V=L.find((P)=>ye(P.labels,s,n,"services"));if(!V){let{server:P,action:O}=await this.client.createServer({name:`${s}-${n}-services`,serverType:Ye(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:f,location:g,userData:R,labels:fe(s,n,"services"),sshKeys:_?[_]:void 0,firewalls:[{firewall:q.id}],networks:[T.id]});await this.client.waitForAction(O.id),V=await this.client.waitForServerRunning(P.id),I.push(P.id)}let W=V.id,K=V.private_net?.[0]?.ip??(await this.client.getServer(W)).private_net?.[0]?.ip,ee=[...Me(!0),...Le(!0),...lt(i.sshKeys),...Je(r.notifications)],te=cr({versions:i.php?.versions,default:i.php?.default,extensions:i.php?.extensions,installNginx:!j(i),optimizeForProduction:i.php?.optimizeForProduction,ini:i.php?.ini}),ne=se(M({runtime:"php",phpProvision:te,servicesProvision:ee,baked:h,swapGb:i.swapGb})),ie=L.filter((P)=>ye(P.labels,s,n,"app")),oe=ie.map((P)=>P.id);if(ie.length>t.appServers)for(let P of ie.slice(t.appServers))await this.client.deleteServer(P.id).catch(()=>{}),oe.splice(oe.indexOf(P.id),1);for(let P=ie.length;P<t.appServers;P++){let{server:O,action:D}=await this.client.createServer({name:`${s}-${n}-app-${P+1}`,serverType:c,image:f,location:g,userData:ne,labels:fe(s,n,"app"),sshKeys:_?[_]:void 0,firewalls:[{firewall:x.id}],networks:[T.id]});await this.client.waitForAction(D.id),oe.push(O.id),I.push(O.id)}if(this.waitForBoot&&I.length>0)await Promise.all(I.map(async(P)=>{let D=(await this.client.waitForServerRunning(P)).public_net.ipv4?.ip;if(D)await this.waitForSshReady(D),await this.waitForCloudInit(D)}));let re=`${s}-${n}-lb`,pe,ge;if(t.loadBalancer){let O=(await this.client.listLoadBalancers().catch(()=>[])).find((D)=>D.name===re)??await this.client.createLoadBalancer({name:re,location:g,network:T.id,labels:fe(s,n,"lb"),labelSelector:`ts-cloud/project=${s},ts-cloud/environment=${n},ts-cloud/role=app`,services:[{listenPort:80,destinationPort:80},{listenPort:443,destinationPort:443}]});ge=O.id,pe=O.public_net?.ipv4?.ip}let b=pe??(await this.client.getServer(oe[0]).catch(()=>{return}))?.public_net.ipv4?.ip,k={provider:"hetzner",stackName:a,networkId:T.id,loadBalancerId:ge,servicesServerId:W,servicesPrivateIp:K,publicIp:b,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await nt(a,k),{appPublicIp:b,loadBalancerIp:pe,servicesPrivateIp:K,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async provisionBunFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,i=r.infrastructure.compute,a=m(r,n),c=Ye(i.size),f=Gt(r),g=r.hetzner?.location||this.location,h=i.bakedImage===!0,S=r.sites||{},_=await rt(a);if(_?.lbServerId){let D=await this.tryGetServer(_.lbServerId);if(D&&D.status!=="off"){let J=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"},Y=await this.findComputeTargets({slug:s,environment:n,role:"app",stackName:a});return this.refreshLbRoutes(D,S,Y.map((X)=>({privateIp:X.privateIp,publicIp:X.publicIp})),J,s),{appPublicIp:D.public_net.ipv4?.ip??_.publicIp,loadBalancerIp:D.public_net.ipv4?.ip??_.publicIp,servicesPrivateIp:_.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}}let v=await this.ensureSshKey(s,n,fe(s,n,"app")),y=`${s}-${n}-net`,x=(await this.client.listNetworks().catch(()=>[])).find((D)=>D.name===y)??await this.client.createNetwork({name:y,labels:fe(s,n,"app")}),q=this.collectUpstreamPorts(S),{firewall:H}=await this.ensureFirewall(`${s}-${n}-app-fw`,fe(s,n,"app"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},...q.map((D)=>({direction:"in",protocol:"tcp",port:String(D),source_ips:[x.ip_range],description:`ts-cloud port ${D} (private, LB-only)`}))]),{firewall:R}=await this.ensureFirewall(`${s}-${n}-lb-fw`,fe(s,n,"lb"),Dr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),L=await this.client.listServers().catch(()=>[]),I=[],V,W,K=!!i.servicesServer||!!i.managedServices,ee=t.dedicatedServices&&K;if(ee){let{firewall:D}=await this.ensureFirewall(`${s}-${n}-services-fw`,fe(s,n,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[x.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[x.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[x.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[x.ip_range]}]),J=An(r),Y=se(M({runtime:"bun",servicesProvision:J,baked:h,swapGb:i.swapGb})),X=L.find((Z)=>ye(Z.labels,s,n,"services"));if(!X){let{server:Z,action:le}=await this.client.createServer({name:`${s}-${n}-services`,serverType:Ye(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:f,location:g,userData:Y,labels:fe(s,n,"services"),sshKeys:v?[v]:void 0,firewalls:[{firewall:D.id}],networks:[x.id]});await this.client.waitForAction(le.id),X=await this.client.waitForServerRunning(Z.id),I.push(Z.id)}V=X.id,W=X.private_net?.[0]?.ip??(await this.client.getServer(V)).private_net?.[0]?.ip}let te=ee?{...i,managedServices:void 0,backups:void 0}:i,ne=Qe({...r,infrastructure:{...r.infrastructure,compute:te}},{environment:n}),ie=se(M({runtime:ne.runtime,runtimeVersion:ne.runtimeVersion,systemPackages:i.systemPackages,database:r.infrastructure?.database,servicesProvision:ne.servicesProvision,baked:h,swapGb:i.swapGb})),oe=L.filter((D)=>ye(D.labels,s,n,"app")),re=oe.map((D)=>D.id);if(oe.length>t.appServers)for(let D of oe.slice(t.appServers))await this.client.deleteServer(D.id).catch(()=>{}),re.splice(re.indexOf(D.id),1);for(let D=oe.length;D<t.appServers;D++){let{server:J,action:Y}=await this.client.createServer({name:`${s}-${n}-app-${D+1}`,serverType:c,image:f,location:g,userData:ie,labels:fe(s,n,"app"),sshKeys:v?[v]:void 0,firewalls:[{firewall:H.id}],networks:[x.id]});await this.client.waitForAction(Y.id),re.push(J.id),I.push(J.id)}if(this.waitForBoot&&I.length>0)await Promise.all(I.map(async(D)=>{let Y=(await this.client.waitForServerRunning(D)).public_net.ipv4?.ip;if(Y)await this.waitForSshReady(Y),await this.waitForCloudInit(Y)}));let pe=[];for(let D of re){let J=L.find((Y)=>Y.id===D);if(!J||!J.private_net?.[0]?.ip)J=await this.client.getServer(D).catch(()=>J);pe.push({privateIp:J?.private_net?.[0]?.ip,publicIp:J?.public_net.ipv4?.ip})}let ge=`${s}-${n}-lb`,b,k;if(t.loadBalancer){let D=L.find((Y)=>ye(Y.labels,s,n,"lb")),J=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"};if(!D){let Y=G({proxy:J,config:rr(S,pe,{proxy:J,slug:s}),slug:s,bunBin:ne.runtime==="node"||ne.runtime==="deno"?void 0:"/usr/local/bin/bun"}),X=se(M({runtime:"bun",rpxProvision:Y,baked:!1})),Z=typeof i.loadBalancer==="object"?i.loadBalancer.size:void 0,{server:le,action:E}=await this.client.createServer({name:ge,serverType:Ye(Z??"micro"),image:f,location:g,userData:X,labels:fe(s,n,"lb"),sshKeys:v?[v]:void 0,firewalls:[{firewall:R.id}],networks:[x.id]});if(await this.client.waitForAction(E.id),D=await this.client.waitForServerRunning(le.id),this.waitForBoot){let N=D.public_net.ipv4?.ip;if(N)await this.waitForSshReady(N),await this.waitForCloudInit(N)}}else this.refreshLbRoutes(D,S,pe,J,s);b=D.id,k=D.public_net.ipv4?.ip}let P=k??(await this.client.getServer(re[0]).catch(()=>{return}))?.public_net.ipv4?.ip,O={provider:"hetzner",stackName:a,networkId:x.id,lbServerId:b,appServerIds:re,servicesServerId:V,servicesPrivateIp:W,publicIp:P,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await nt(a,O),{appPublicIp:P,loadBalancerIp:k,servicesPrivateIp:W,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async destroyCompute(e){let{config:t,environment:r}=e,n=t.project.slug,s=m(t,r),i=await rt(s),a=[],c=`${n}-${r}-lb`,g=(await this.client.listLoadBalancers().catch(()=>[])).find((H)=>H.name===c);if(g)try{await this.client.deleteLoadBalancer(g.id),a.push(`load balancer ${c}`)}catch{}let h=await this.client.listServers().catch(()=>[]),S=new Set;for(let H of h)if(ye(H.labels,n,r,"app")||ye(H.labels,n,r,"services")||ye(H.labels,n,r,"lb"))S.add(H.id);if(i?.serverId)S.add(i.serverId);if(i?.servicesServerId)S.add(i.servicesServerId);if(i?.lbServerId)S.add(i.lbServerId);for(let H of i?.appServerIds??[])S.add(H);for(let H of S)try{await this.client.deleteServer(H),a.push(`server ${H}`)}catch{}let _=await this.client.listFirewalls().catch(()=>[]);for(let H of[`${n}-${r}-app-fw`,`${n}-${r}-services-fw`,`${n}-${r}-lb-fw`]){let R=_.find((L)=>L.name===H);if(!R)continue;for(let L=0;L<12;L++)try{await this.client.deleteFirewall(R.id),a.push(`firewall ${H}`);break}catch{await this.sleep(3000)}}let v=`${n}-${r}-net`,T=(await this.client.listNetworks().catch(()=>[])).find((H)=>H.name===v);if(T)for(let H=0;H<12;H++)try{await this.client.deleteNetwork(T.id),a.push(`network ${v}`);break}catch{await this.sleep(3000)}let q=(await this.client.listSshKeys().catch(()=>[])).filter((H)=>Ln(H.labels,n,r));for(let H of q)try{await this.client.deleteSshKey(H.id),a.push(`ssh key ${H.name}`)}catch{}return await nt(s,{provider:"hetzner",stackName:s}).catch(()=>{}),{destroyed:a}}async getComputeOutputs(e){let t=m(e.config,e.environment),r=await rt(t);if(r?.serverId){let i=await this.tryGetServer(r.serverId);if(i)return this.outputsFromState(r,i)}if(r?.lbServerId){let a=(await this.tryGetServer(r.lbServerId))?.public_net.ipv4?.ip??r.publicIp;return{...this.outputsFromState(r),appPublicIp:a,loadBalancerIp:a}}if(r?.loadBalancerId||r?.servicesPrivateIp)return this.outputsFromState(r);let s=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:m(e.config,e.environment)}))[0];return{deployStoragePath:"/var/ts-cloud/staging",appInstanceId:s?.id,appPublicIp:s?.publicIp,sshUser:this.sshUser}}async uploadRelease(e){let t=e.targets?.length?e.targets:await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:m(e.config,e.environment)});if(t.length===0)throw Error("No Hetzner compute targets found for release upload");let s=`/var/ts-cloud/staging/${`${e.remoteKey.replace(/^releases\//,"").replace(/\.tar\.gz$/,"").replace(/\//g,"-")}-${So()}.tar.gz`}`,i=await ul(e.localPath),a=Fr,c=`${a}/${i}.tar.gz`;for(let f of t){if(!f.publicIp)throw Error(`Target ${f.id} has no public IP for SCP upload`);let g=["set -euo pipefail",`mkdir -p ${Vt(a)} /var/ts-cloud/staging`,`test -s ${Vt(c)}`,`cp -- ${Vt(c)} ${Vt(s)}`].join(`
281
+ `))}if(g?.capacityAvailable&&!g.alreadyComplete){let y={host:_[0].publicIp,user:this.sshUser,identityFile:this.sshPrivateKeyPath},T=await li({client:this.client,serverId:c.id,targetType:g.targetType.name,upgradeDisk:g.upgradeDisk,hooks:{preflight:()=>qc(y),afterBoot:(x,q,H,R)=>jc(y,q,H,R)}});if(T.status!=="completed"&&T.status!=="already-complete")throw Error(`Resize did not complete: ${T.status}`)}return h}constructor(e={}){this.residency=e.residency;let t=jt(e.apiToken);if(this.stateOnly=!e.client&&!t&&e.allowStateOnly===!0,!e.client&&!t&&!this.stateOnly)throw Error("Hetzner API token required. Set hetzner.apiToken in cloud.config.ts or HCLOUD_TOKEN / HETZNER_API_TOKEN.");this.client=e.client??new Hr({apiToken:t??""});let r=uo(void 0,{sshPrivateKeyPath:e.sshPrivateKeyPath,sshPublicKeyPath:e.sshPublicKeyPath,sshUser:e.sshUser,location:e.location});this.sshPrivateKeyPath=r.sshPrivateKeyPath,this.sshPublicKeyPath=r.sshPublicKeyPath,this.sshUser=r.sshUser,this.location=r.location,this.waitForBoot=e.waitForBoot??!0,this.bootWait={sshIntervalMs:e.bootWait?.sshIntervalMs??5000,sshTimeoutMs:e.bootWait?.sshTimeoutMs??300000,cloudInitIntervalMs:e.bootWait?.cloudInitIntervalMs??5000,cloudInitTimeoutMs:e.bootWait?.cloudInitTimeoutMs??600000}}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e,n=t.project.slug,s=t.infrastructure?.compute;if(!s)throw Error("infrastructure.compute is required to provision Hetzner compute");if(t.cloud?.attachTo)return this.attachToComputeInfrastructure(t.cloud.attachTo,t,r);let i=m(t,r),a=`${n}-${r}-app`,c=s.runtime==="php"||!!s.php,f=xn(s),g=t.cloud?.residency||this.residency,{assertComputeResidency:h}=await import("./chunk-nh7rcks9.js"),S=(b)=>{if(g)h(g,{country:b.location?.country||b.datacenter?.location?.country,location:b.location?.name||b.datacenter?.location?.name})};if(g){if(f.dedicatedServices||f.appServers>1)throw Error("Residency policy currently requires single-host compute");let b=await this.client.getLocation(t.hetzner?.location||this.location);h(g,{country:b.country,location:b.name})}if(f.dedicatedServices||f.appServers>1)return c?this.provisionFleet(e,f):this.provisionBunFleet(e,f);let _=fe(n,r,"app"),v=t.sites||{},y=j(s)?[]:this.collectUpstreamPorts(v),T=`${n}-${r}-app-fw`,{firewall:x}=await this.ensureFirewall(T,_,Dr({allowSsh:s.allowSsh!==!1,sitePorts:y,allowedPorts:[...s.firewall?.allowedPorts??[],...Cs(t.infrastructure?.sftp),...Ze(C(t,{environment:r}))]})),q=await this.ensureSshKey(n,r,_),H=await rt(i);if(H?.serverId){let b=await this.tryGetServer(H.serverId);if(b&&b.status!=="off"&&b.labels?.["ts-cloud/project"]===n&&b.labels?.["ts-cloud/environment"]===r){if(S(b),s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(H,b)}}let R=await this.findExistingServer(n,r,a);if(R&&R.status!=="off"){S(R);let b={provider:"hetzner",stackName:i,serverId:R.id,serverName:R.name,publicIp:R.public_net.ipv4?.ip,publicIpv6:De(R.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};if(await nt(i,b),s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(b,R)}let L=w(t,{environment:r}),I=L?.engine==="rpx"?G({proxy:L,config:B(v,{proxy:L,slug:t.project.slug,mail:C(t,{environment:r})}),slug:t.project.slug,bunBin:s.runtime==="node"||s.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,V=Qe(t,{environment:r}),W=s.bakedImage===!0,K=M({runtime:V.runtime,runtimeVersion:V.runtimeVersion,systemPackages:s.systemPackages,database:t.infrastructure?.database,phpProvision:V.phpProvision,servicesProvision:V.servicesProvision,rpxProvision:I,baked:W,swapGb:s.swapGb}),te=se(K),Z=Ye(s.size),re=Gt(t),{server:ie,action:oe}=await this.client.createServer({name:a,serverType:Z,image:re,location:t.hetzner?.location||this.location,userData:te,labels:_,sshKeys:q?[q]:void 0,firewalls:[{firewall:x.id}]});await this.client.waitForAction(oe.id);let ne=await this.client.waitForServerRunning(ie.id);S(ne);let pe={provider:"hetzner",stackName:i,serverId:ne.id,serverName:ne.name,firewallId:x.id,publicIp:ne.public_net.ipv4?.ip,publicIpv6:De(ne.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};await nt(i,pe);let ge=ne.public_net.ipv4?.ip;if(ge&&this.waitForBoot)await this.waitForSshReady(ge),await this.waitForCloudInit(ge);if(s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(pe,ne)}async provisionFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,i=r.infrastructure.compute,a=m(r,n),c=Ye(i.size),f=Gt(r),g=r.hetzner?.location||this.location,h=i.bakedImage===!0,S=await rt(a);if(S?.loadBalancerId){let O=(await this.client.listLoadBalancers().catch(()=>[])).find((D)=>D.id===S.loadBalancerId);if(O)return{appPublicIp:O.public_net?.ipv4?.ip,loadBalancerIp:O.public_net?.ipv4?.ip,servicesPrivateIp:S.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}let _=await this.ensureSshKey(s,n,fe(s,n,"app")),v=`${s}-${n}-net`,T=(await this.client.listNetworks().catch(()=>[])).find((P)=>P.name===v)??await this.client.createNetwork({name:v,labels:fe(s,n,"app")}),{firewall:x}=await this.ensureFirewall(`${s}-${n}-app-fw`,fe(s,n,"app"),Dr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),{firewall:q}=await this.ensureFirewall(`${s}-${n}-services-fw`,fe(s,n,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[T.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[T.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[T.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[T.ip_range]}]),H=An(r),R=se(M({runtime:"php",servicesProvision:H,baked:h,swapGb:i.swapGb})),L=await this.client.listServers().catch(()=>[]),I=[],V=L.find((P)=>ye(P.labels,s,n,"services"));if(!V){let{server:P,action:O}=await this.client.createServer({name:`${s}-${n}-services`,serverType:Ye(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:f,location:g,userData:R,labels:fe(s,n,"services"),sshKeys:_?[_]:void 0,firewalls:[{firewall:q.id}],networks:[T.id]});await this.client.waitForAction(O.id),V=await this.client.waitForServerRunning(P.id),I.push(P.id)}let W=V.id,K=V.private_net?.[0]?.ip??(await this.client.getServer(W)).private_net?.[0]?.ip,te=[...Me(!0),...Le(!0),...lt(i.sshKeys),...Je(r.notifications)],Z=cr({versions:i.php?.versions,default:i.php?.default,extensions:i.php?.extensions,installNginx:!j(i),optimizeForProduction:i.php?.optimizeForProduction,ini:i.php?.ini}),re=se(M({runtime:"php",phpProvision:Z,servicesProvision:te,baked:h,swapGb:i.swapGb})),ie=L.filter((P)=>ye(P.labels,s,n,"app")),oe=ie.map((P)=>P.id);if(ie.length>t.appServers)for(let P of ie.slice(t.appServers))await this.client.deleteServer(P.id).catch(()=>{}),oe.splice(oe.indexOf(P.id),1);for(let P=ie.length;P<t.appServers;P++){let{server:O,action:D}=await this.client.createServer({name:`${s}-${n}-app-${P+1}`,serverType:c,image:f,location:g,userData:re,labels:fe(s,n,"app"),sshKeys:_?[_]:void 0,firewalls:[{firewall:x.id}],networks:[T.id]});await this.client.waitForAction(D.id),oe.push(O.id),I.push(O.id)}if(this.waitForBoot&&I.length>0)await Promise.all(I.map(async(P)=>{let D=(await this.client.waitForServerRunning(P)).public_net.ipv4?.ip;if(D)await this.waitForSshReady(D),await this.waitForCloudInit(D)}));let ne=`${s}-${n}-lb`,pe,ge;if(t.loadBalancer){let O=(await this.client.listLoadBalancers().catch(()=>[])).find((D)=>D.name===ne)??await this.client.createLoadBalancer({name:ne,location:g,network:T.id,labels:fe(s,n,"lb"),labelSelector:`ts-cloud/project=${s},ts-cloud/environment=${n},ts-cloud/role=app`,services:[{listenPort:80,destinationPort:80},{listenPort:443,destinationPort:443}]});ge=O.id,pe=O.public_net?.ipv4?.ip}let b=pe??(await this.client.getServer(oe[0]).catch(()=>{return}))?.public_net.ipv4?.ip,k={provider:"hetzner",stackName:a,networkId:T.id,loadBalancerId:ge,servicesServerId:W,servicesPrivateIp:K,publicIp:b,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await nt(a,k),{appPublicIp:b,loadBalancerIp:pe,servicesPrivateIp:K,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async provisionBunFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,i=r.infrastructure.compute,a=m(r,n),c=Ye(i.size),f=Gt(r),g=r.hetzner?.location||this.location,h=i.bakedImage===!0,S=r.sites||{},_=await rt(a);if(_?.lbServerId){let D=await this.tryGetServer(_.lbServerId);if(D&&D.status!=="off"){let J=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"},Y=await this.findComputeTargets({slug:s,environment:n,role:"app",stackName:a});return this.refreshLbRoutes(D,S,Y.map((X)=>({privateIp:X.privateIp,publicIp:X.publicIp})),J,s),{appPublicIp:D.public_net.ipv4?.ip??_.publicIp,loadBalancerIp:D.public_net.ipv4?.ip??_.publicIp,servicesPrivateIp:_.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}}let v=await this.ensureSshKey(s,n,fe(s,n,"app")),y=`${s}-${n}-net`,x=(await this.client.listNetworks().catch(()=>[])).find((D)=>D.name===y)??await this.client.createNetwork({name:y,labels:fe(s,n,"app")}),q=this.collectUpstreamPorts(S),{firewall:H}=await this.ensureFirewall(`${s}-${n}-app-fw`,fe(s,n,"app"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},...q.map((D)=>({direction:"in",protocol:"tcp",port:String(D),source_ips:[x.ip_range],description:`ts-cloud port ${D} (private, LB-only)`}))]),{firewall:R}=await this.ensureFirewall(`${s}-${n}-lb-fw`,fe(s,n,"lb"),Dr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),L=await this.client.listServers().catch(()=>[]),I=[],V,W,K=!!i.servicesServer||!!i.managedServices,te=t.dedicatedServices&&K;if(te){let{firewall:D}=await this.ensureFirewall(`${s}-${n}-services-fw`,fe(s,n,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[x.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[x.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[x.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[x.ip_range]}]),J=An(r),Y=se(M({runtime:"bun",servicesProvision:J,baked:h,swapGb:i.swapGb})),X=L.find((ee)=>ye(ee.labels,s,n,"services"));if(!X){let{server:ee,action:le}=await this.client.createServer({name:`${s}-${n}-services`,serverType:Ye(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:f,location:g,userData:Y,labels:fe(s,n,"services"),sshKeys:v?[v]:void 0,firewalls:[{firewall:D.id}],networks:[x.id]});await this.client.waitForAction(le.id),X=await this.client.waitForServerRunning(ee.id),I.push(ee.id)}V=X.id,W=X.private_net?.[0]?.ip??(await this.client.getServer(V)).private_net?.[0]?.ip}let Z=te?{...i,managedServices:void 0,backups:void 0}:i,re=Qe({...r,infrastructure:{...r.infrastructure,compute:Z}},{environment:n}),ie=se(M({runtime:re.runtime,runtimeVersion:re.runtimeVersion,systemPackages:i.systemPackages,database:r.infrastructure?.database,servicesProvision:re.servicesProvision,baked:h,swapGb:i.swapGb})),oe=L.filter((D)=>ye(D.labels,s,n,"app")),ne=oe.map((D)=>D.id);if(oe.length>t.appServers)for(let D of oe.slice(t.appServers))await this.client.deleteServer(D.id).catch(()=>{}),ne.splice(ne.indexOf(D.id),1);for(let D=oe.length;D<t.appServers;D++){let{server:J,action:Y}=await this.client.createServer({name:`${s}-${n}-app-${D+1}`,serverType:c,image:f,location:g,userData:ie,labels:fe(s,n,"app"),sshKeys:v?[v]:void 0,firewalls:[{firewall:H.id}],networks:[x.id]});await this.client.waitForAction(Y.id),ne.push(J.id),I.push(J.id)}if(this.waitForBoot&&I.length>0)await Promise.all(I.map(async(D)=>{let Y=(await this.client.waitForServerRunning(D)).public_net.ipv4?.ip;if(Y)await this.waitForSshReady(Y),await this.waitForCloudInit(Y)}));let pe=[];for(let D of ne){let J=L.find((Y)=>Y.id===D);if(!J||!J.private_net?.[0]?.ip)J=await this.client.getServer(D).catch(()=>J);pe.push({privateIp:J?.private_net?.[0]?.ip,publicIp:J?.public_net.ipv4?.ip})}let ge=`${s}-${n}-lb`,b,k;if(t.loadBalancer){let D=L.find((Y)=>ye(Y.labels,s,n,"lb")),J=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"};if(!D){let Y=G({proxy:J,config:rr(S,pe,{proxy:J,slug:s}),slug:s,bunBin:re.runtime==="node"||re.runtime==="deno"?void 0:"/usr/local/bin/bun"}),X=se(M({runtime:"bun",rpxProvision:Y,baked:!1})),ee=typeof i.loadBalancer==="object"?i.loadBalancer.size:void 0,{server:le,action:E}=await this.client.createServer({name:ge,serverType:Ye(ee??"micro"),image:f,location:g,userData:X,labels:fe(s,n,"lb"),sshKeys:v?[v]:void 0,firewalls:[{firewall:R.id}],networks:[x.id]});if(await this.client.waitForAction(E.id),D=await this.client.waitForServerRunning(le.id),this.waitForBoot){let N=D.public_net.ipv4?.ip;if(N)await this.waitForSshReady(N),await this.waitForCloudInit(N)}}else this.refreshLbRoutes(D,S,pe,J,s);b=D.id,k=D.public_net.ipv4?.ip}let P=k??(await this.client.getServer(ne[0]).catch(()=>{return}))?.public_net.ipv4?.ip,O={provider:"hetzner",stackName:a,networkId:x.id,lbServerId:b,appServerIds:ne,servicesServerId:V,servicesPrivateIp:W,publicIp:P,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await nt(a,O),{appPublicIp:P,loadBalancerIp:k,servicesPrivateIp:W,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async destroyCompute(e){let{config:t,environment:r}=e,n=t.project.slug,s=m(t,r),i=await rt(s),a=[],c=`${n}-${r}-lb`,g=(await this.client.listLoadBalancers().catch(()=>[])).find((H)=>H.name===c);if(g)try{await this.client.deleteLoadBalancer(g.id),a.push(`load balancer ${c}`)}catch{}let h=await this.client.listServers().catch(()=>[]),S=new Set;for(let H of h)if(ye(H.labels,n,r,"app")||ye(H.labels,n,r,"services")||ye(H.labels,n,r,"lb"))S.add(H.id);if(i?.serverId)S.add(i.serverId);if(i?.servicesServerId)S.add(i.servicesServerId);if(i?.lbServerId)S.add(i.lbServerId);for(let H of i?.appServerIds??[])S.add(H);for(let H of S)try{await this.client.deleteServer(H),a.push(`server ${H}`)}catch{}let _=await this.client.listFirewalls().catch(()=>[]);for(let H of[`${n}-${r}-app-fw`,`${n}-${r}-services-fw`,`${n}-${r}-lb-fw`]){let R=_.find((L)=>L.name===H);if(!R)continue;for(let L=0;L<12;L++)try{await this.client.deleteFirewall(R.id),a.push(`firewall ${H}`);break}catch{await this.sleep(3000)}}let v=`${n}-${r}-net`,T=(await this.client.listNetworks().catch(()=>[])).find((H)=>H.name===v);if(T)for(let H=0;H<12;H++)try{await this.client.deleteNetwork(T.id),a.push(`network ${v}`);break}catch{await this.sleep(3000)}let q=(await this.client.listSshKeys().catch(()=>[])).filter((H)=>Ln(H.labels,n,r));for(let H of q)try{await this.client.deleteSshKey(H.id),a.push(`ssh key ${H.name}`)}catch{}return await nt(s,{provider:"hetzner",stackName:s}).catch(()=>{}),{destroyed:a}}async getComputeOutputs(e){let t=m(e.config,e.environment),r=await rt(t);if(r?.serverId){let i=await this.tryGetServer(r.serverId);if(i)return this.outputsFromState(r,i)}if(r?.lbServerId){let a=(await this.tryGetServer(r.lbServerId))?.public_net.ipv4?.ip??r.publicIp;return{...this.outputsFromState(r),appPublicIp:a,loadBalancerIp:a}}if(r?.loadBalancerId||r?.servicesPrivateIp)return this.outputsFromState(r);let s=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:m(e.config,e.environment)}))[0];return{deployStoragePath:"/var/ts-cloud/staging",appInstanceId:s?.id,appPublicIp:s?.publicIp,sshUser:this.sshUser}}async uploadRelease(e){let t=e.targets?.length?e.targets:await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:m(e.config,e.environment)});if(t.length===0)throw Error("No Hetzner compute targets found for release upload");let s=`/var/ts-cloud/staging/${`${e.remoteKey.replace(/^releases\//,"").replace(/\.tar\.gz$/,"").replace(/\//g,"-")}-${So()}.tar.gz`}`,i=await ul(e.localPath),a=Fr,c=`${a}/${i}.tar.gz`;for(let f of t){if(!f.publicIp)throw Error(`Target ${f.id} has no public IP for SCP upload`);let g=["set -euo pipefail",`mkdir -p ${Vt(a)} /var/ts-cloud/staging`,`test -s ${Vt(c)}`,`cp -- ${Vt(c)} ${Vt(s)}`].join(`
282
282
  `);try{this.sshExec(f.publicIp,g);continue}catch{}let h=`${a}/.${i}-${So()}.tmp`;try{this.scpToHost(f.publicIp,e.localPath,h),this.sshExec(f.publicIp,Tr(h,c,s))}catch(S){try{this.sshExec(f.publicIp,wr(h))}catch{}throw S}}return{artifactRef:s}}async findComputeTargets(e){let{assertComputeResidency:t}=await import("./chunk-nh7rcks9.js"),r=e.role||"app",n=(a)=>{if(this.residency)t(this.residency,{country:a.location?.country||a.datacenter?.location?.country,location:a.location?.name||a.datacenter?.location?.name});return{id:String(a.id),name:a.name,publicIp:a.public_net.ipv4?.ip,publicIpv6:De(a.public_net.ipv6?.ip),privateIp:a.private_net?.[0]?.ip,status:a.status}};if(r==="app"||r==="lb"||r==="services"){let a=await rt(e.stackName??`${e.slug}-${e.environment}`),c=[...new Set(r==="app"?[a?.serverId,...a?.appServerIds??[]]:r==="lb"?[a?.lbServerId]:[a?.servicesServerId])].filter((h)=>typeof h==="number");if(this.stateOnly){if(this.residency)throw Error("Residency requires fresh provider evidence; a local state pin alone is insufficient");if(c.length>0&&a?.publicIp)return c.map((h)=>({id:String(h),name:h===a.serverId?a.serverName:void 0,publicIp:a.publicIp,publicIpv6:a.publicIpv6,status:"running"}));if(r!=="app")return[];throw Error(`Hetzner API token required because '${e.stackName??`${e.slug}-${e.environment}`}' has no complete local compute state pin.`)}let f=await this.client.listServers();if(c.length>0){let h=[];for(let S of c){let _=f.find((v)=>v.id===S)??await this.tryGetServer(S);if(S===a?.serverId&&a.serverName&&_?.name!==a.serverName)continue;if(_&&_.status!=="off")h.push(_)}if(h.length>0)return h.map(n)}let g=f.filter((h)=>ye(h.labels,e.slug,e.environment,r));if(g.length>0)return g.map(n);if(r==="app"){let h=f.filter((S)=>S.status!=="off"&&S.labels?.[`${me}/managed-by`]==="ts-cloud"&&S.labels?.[`${me}/environment`]===e.environment&&S.labels?.[`${me}/role`]==="app");if(h.length===1)return h.map(n)}return[]}if(this.stateOnly)throw Error(`Hetzner API token required to discover '${r}' compute targets.`);let i=(await this.client.listServers()).filter((a)=>ye(a.labels,e.slug,e.environment,r));if(i.length>0)return i.map(n);return[]}async attachToComputeInfrastructure(e,t,r){let n=await this.client.listServers(),s=(_)=>n.filter((v)=>v.status!=="off"&&ye(v.labels,e,r,_)),i=s("app");if(i.length===0)throw Error(`Cannot attach '${t.project.slug}' to '${e}': no running Hetzner app server is labeled for ${e}/${r}. Deploy the owner project first.`);let a=s("lb")[0],c=s("services")[0],f=i[0],g=a??f,h=m(t,r),S={provider:"hetzner",stackName:h,serverId:f.id,serverName:f.name,appServerIds:i.map((_)=>_.id),lbServerId:a?.id,servicesServerId:c?.id,servicesPrivateIp:c?.private_net?.[0]?.ip,publicIp:g.public_net.ipv4?.ip,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await nt(h,S),this.outputsFromState(S)}async listReachableResources(){return(await this.client.listServers()).map((t)=>({name:t.name,labels:t.labels}))}async runRemoteDeploy(e){if(e.targets.length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets provided"};let t=e.commands.join(`
283
283
  `),r=[];for(let s of e.targets){if(!s.publicIp){r.push({instanceId:s.id,status:"Failed",error:"Missing public IP"});continue}try{let i=this.sshExec(s.publicIp,t);Or(i),r.push({instanceId:s.id,status:"Success",output:i})}catch(i){r.push({instanceId:s.id,status:"Failed",error:i.message})}}let n=r.every((s)=>s.status==="Success");return{success:n,instanceCount:e.targets.length,perInstance:r,error:n?void 0:Yt(r,"One or more SSH deploy commands failed")}}async ensureSshKey(e,t,r){if(!cl(this.sshPublicKeyPath))throw Error(`SSH public key not found at ${this.sshPublicKeyPath}. ts-cloud deploys to Hetzner over SSH and needs a public key to authorize on the server. Generate one (\`ssh-keygen -t ed25519\`) or set hetzner.sshPrivateKeyPath / HCLOUD_SSH_PUBLIC_KEY.`);let n=ll(this.sshPublicKeyPath,"utf8").trim(),s=qe(n),a=(await this.client.listSshKeys()).find((f)=>qe(f.public_key)===s);if(a)return a.id;return(await this.client.createSshKey({name:`${e}-${t}-deploy`,publicKey:n,labels:r})).id}async tryGetServer(e){try{return await this.client.getServer(e)}catch{return null}}refreshLbRoutes(e,t,r,n,s){let i=e.public_net.ipv4?.ip;if(!i){console.warn(`[ts-cloud] LB server '${e.name}' has no public IP — skipping the rpx route refresh; its routes may be stale.`);return}let a=r.filter((f)=>f.privateIp||f.publicIp);if(a.length===0){console.warn(`[ts-cloud] No routable app boxes found for LB '${e.name}' — leaving its current rpx routes untouched.`);return}let c=rr(t,a,{proxy:n,slug:s});this.sshExec(i,Ne({config:c,slug:s}).join(`
284
284
  `))}async findExistingServer(e,t,r){let n=await this.client.listServers(),s=n.find((a)=>ye(a.labels,e,t,"app")||a.name===r);if(s)return s;let i=n.filter((a)=>a.status!=="off"&&a.labels?.[`${me}/managed-by`]==="ts-cloud"&&a.labels?.[`${me}/environment`]===t&&a.labels?.[`${me}/role`]==="app");if(i.length===1){let a=i[0],c=a.labels?.[`${me}/project`]??"unknown";return console.warn(`[ts-cloud] No server named '${r}' found; adopting existing ts-cloud app server '${a.name}' (project label '${c}') for project '${e}' — `+"updating it in place instead of provisioning a new server."),a}return}async ensureFirewall(e,t,r){let s=(await this.client.listFirewalls()).find((a)=>a.name===e);if(s)return await this.client.setFirewallRules(s.id,r),{firewall:s};let{firewall:i}=await this.client.createFirewall({name:e,labels:t,rules:r});return{firewall:i}}collectUpstreamPorts(e){let t=new Set;for(let r of Object.values(e))if(typeof r.port==="number")t.add(r.port);return[...t].filter((r)=>![80,443].includes(r))}async sleep(e){await new Promise((t)=>setTimeout(t,e))}async waitForSshReady(e){let{sshIntervalMs:t,sshTimeoutMs:r}=this.bootWait,n=Date.now(),s;while(Date.now()-n<r)try{ho(`ssh ${this.sshBaseArgs(e,["-o","ConnectTimeout=5"]).map(Vt).join(" ")} true`,{stdio:"pipe",maxBuffer:kn});return}catch(i){s=i,await this.sleep(t)}throw Error(`Timed out waiting for SSH on ${e} after ${r}ms: ${s?.message??"unknown error"}`)}async waitForCloudInit(e){let{cloudInitIntervalMs:t,cloudInitTimeoutMs:r}=this.bootWait,n=Date.now();while(Date.now()-n<r){try{let s=this.sshExec(e,"if command -v cloud-init >/dev/null 2>&1; then cloud-init status --long 2>/dev/null || true; else echo 'status: done'; fi");if(/status:\s*error/.test(s))throw Error(`cloud-init reported an error on ${e}:
@@ -442,13 +442,13 @@ console.log(JSON.stringify({
442
442
  `)}var id="dashboard";function ao(){return Q("dashboard-credentials.json")}function lu(){return ru(24).toString("base64url")}function sd(e,t,r){let n=process.env.TS_CLOUD_UI_PASSWORD?.trim();if(n)return{password:n,source:"env"};if(zn(process.env.TS_CLOUD_UI_PUBLIC))return{password:void 0,source:"public"};let s=ao(),i=l(e,"dashboard-credentials.json");try{if(ot(i)){let c=JSON.parse(Fo(i,"utf8"));if(c?.password)return{password:c.password,source:"generated"}}}catch{}let a=lu();try{Mo(Bn(i),{recursive:!0}),Fn(i,`${JSON.stringify({username:t,password:a,generatedAt:new Date().toISOString()},null,2)}
443
443
  `),nu(i,384),r.info(`Management dashboard: generated a password for '${t}' and saved it to ${s} (read it there — it is not printed). Set TS_CLOUD_UI_PASSWORD to pin your own, or TS_CLOUD_UI_PUBLIC=1 to serve without auth.`)}catch(c){r.warn(`Management dashboard: could not persist the generated password (${c?.message??c}). Using it for this deploy only — pass: ${a}
444
444
  This password is now in your deploy log. Set TS_CLOUD_UI_PASSWORD to a value of your own and redeploy once ${s} is writable.`)}return{password:a,source:"generated"}}var Ko={info:()=>{},warn:()=>{}};function zn(e){return e!=null&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function uu(){return Q("dashboard-release")}function jo(){let e=Bn(Bo(import.meta.url));for(let t of[Se(e,"..","..","package.json"),Se(e,"..","package.json")])try{let r=JSON.parse(Fo(t,"utf8"));if(r.name==="@stacksjs/ts-cloud"&&r.version)return`^${r.version}`}catch{}return"latest"}function pu(){return process.env.TS_CLOUD_UI_VERSION?.trim()||jo()}function du(e,t,r){if(!e?.project?.slug)return r.warn("Management dashboard: the cloud config has no project slug — skipping the live dashboard."),null;let n=l(t,"dashboard-release");try{Mo(n,{recursive:!0}),Fn(Se(n,"cloud.config.ts"),Ho(e));let s=pu();if(s.startsWith("file:")){let a=s.slice(5),c=zo(a)?a:cu(t,a);if(!ot(c)||!ou(c).isFile())s=jo(),r.warn(`Management dashboard: TS_CLOUD_UI_VERSION points to a missing package file (${c}); using the deploying ts-cloud version ${s} instead.`);else{let f=au(c),g=Se(n,f);if(c!==g)su(c,g);s=`file:./${f}`}}let i={name:"ts-cloud-dashboard",private:!0,type:"module",dependencies:{"@stacksjs/ts-cloud":s}};return Fn(Se(n,"package.json"),`${JSON.stringify(i,null,2)}
445
- `),uu()}catch(s){return r.warn(`Management dashboard: could not stage the live release (${s?.message??s}) — skipping.`),null}}function tr(e){if(ot(Se(e,"packages","ui","pages"))||ot(Se(e,"packages","ui","package.json")))return{uiRoot:"packages/ui/dist",build:"cd packages/ui && bun install && bun run build"};let t=Bn(Bo(import.meta.url)),r=[Se(t,"ui"),Se(t,"..","ui"),Se(t,"..","..","ui"),Se(t,"..","dist","ui")];for(let n of r)if(ot(Se(n,"index.html"))||ot(Se(n,"serverless.html")))return{uiRoot:n,build:!1};return null}function Ri(e,t={}){let r=t.logger??Ko,n=t.cwd??process.cwd();if(zn(process.env.TS_CLOUD_UI_DISABLE))return r.info("Management dashboard: skipped (TS_CLOUD_UI_DISABLE set)."),e;if(e.cloud?.attachTo)return r.info(`Management dashboard: ${e.project.slug} is attached to ${e.cloud.attachTo}; the server owner's dashboard monitors every attached project.`),e;if(pr(e))return e;let s=e.environments&&Object.keys(e.environments)[0],i=process.env.TS_CLOUD_UI_DOMAIN?.trim()||void 0,a=Number(process.env.TS_CLOUD_UI_PORT)||void 0,c={...e.sites??{}};if(!zn(process.env.TS_CLOUD_UI_STATIC)){let v=du(e,n,r);if(!v)return e;let y=Zi(e,s??"production",{uiRoot:v,build:!1,domain:i,port:a,live:!0});if(y.length===0)return r.info("Management dashboard: no domain resolved (set TS_CLOUD_UI_DOMAIN or configure a site domain) — skipping."),e;for(let{name:T,site:x}of y)c[T]=x,r.info(`Management dashboard → https://${x.domain} (sign in with your ts-cloud account; the first deploy prints an admin password once)`);return e.sites=c,e}let f=tr(n);if(!f)return r.info("Management dashboard: UI not found (no local ui/ or packaged dist/ui) — skipping auto-deploy."),e;let g=process.env.TS_CLOUD_UI_USERNAME?.trim()||"admin",h=sd(n,g,r),S=Zi(e,s??"production",{uiRoot:f.uiRoot,build:f.build,domain:i,username:g,password:h.password,realm:process.env.TS_CLOUD_UI_REALM?.trim()||void 0,live:!1,port:a});if(S.length===0)return r.info("Management dashboard: no domain resolved (set TS_CLOUD_UI_DOMAIN or configure a site domain) — skipping."),e;let _=h.source==="public"?"NO AUTH — TS_CLOUD_UI_PUBLIC is set (dashboard is publicly reachable)":h.source==="env"?"htpasswd-protected (TS_CLOUD_UI_PASSWORD)":`htpasswd-protected (auto-generated — see ${ao()})`;r.warn("Management dashboard: static mode — one shared password, and no per-site collaborators. Unset TS_CLOUD_UI_STATIC for the live dashboard.");for(let{name:v,site:y}of S)c[v]=y,r.info(`Management dashboard → https://${y.domain} (${_})`);return e.sites=c,e}function Kn(e){return Object.keys(e.sites??{}).filter(mr)}function co(e,t){if(!e?.root)return null;let r=t.cwd??process.cwd(),n=t.logger??Ko;try{if(typeof e.build==="string"&&e.build.trim())n.info(`Management dashboard: building UI (${e.build})`),No(e.build,{cwd:r,stdio:"inherit"});let s=zo(e.root)?e.root:Se(r,e.root);if(!ot(s))return n.warn(`Management dashboard: build output not found at ${s} — skipping dashboard artifact.`),null;let i=Se(iu(),`${t.slug}-${t.siteName??id}-${t.sha}.tar.gz`);return No(`tar czf "${i}" -C "${s}" .`,{stdio:"inherit"}),i}catch(s){return n.warn(`Management dashboard: failed to build artifact — ${s?.message??s}. Skipping dashboard deploy.`),null}}function mu(e){let t=e.split("/");if(!/^[a-zA-Z0-9_./-]+$/.test(e)||e.startsWith("/")||t.some((r)=>!r||r==="."||r==="..")||t.at(-1)!=="bun")throw Error("Stacks backgroundBun must select a safe release-relative Bun executable")}function Go(e,t){if(mu(t),!/^\/[a-zA-Z0-9_./-]+$/.test(e)||e.split("/").includes(".."))throw Error("Stacks backgroundBun requires a safe absolute release directory");return`${e}/${t}`}var fu=new Set(["laravel","php","statamic","wordpress"]);function Vr(e){if(e.framework)return e.framework;if(e.type&&fu.has(e.type))return"laravel";return"stacks"}var Vo=`eval "$(cd ${u} && pantry env 2>/dev/null)"`,gu="/usr/local/bin/bun",Nr={PATH:"/usr/local/bin:/usr/bin:/bin",BUN_INSTALL:"/root/.bun",APP_ENV:"production",NODE_ENV:"production"};function jn(e){if(e.backgroundBun===void 0)return gu;return Go(e.current,e.backgroundBun)}function hu(e){let t=e.queue??"default",r=[e.sleep,e.tries,e.timeout,e.processes,e.stopWaitSecs];if(typeof t!=="string"||!/^[a-zA-Z0-9_.:,{}/@+-]+$/.test(t||"default")||r.some((n)=>n!==void 0&&(typeof n!=="number"||!Number.isFinite(n))))throw Error("Stacks background queue options require safe queue names and finite numeric values")}var Su="node_modules/@stacksjs/ts-cloud/dist/bin/stacks-scheduler.js",_u="node_modules/@stacksjs/ts-cloud/dist/bin/stacks-queue-worker.js",qo={id:"stacks",wrapExec:(e)=>e,execEnv:Nr,executionEnvironment:(e)=>{let t=jn(e);return e.backgroundBun===void 0?Nr:{...Nr,PATH:`${t.slice(0,t.lastIndexOf("/"))}:${Nr.PATH}`,TS_CLOUD_BACKGROUND_BUN:e.backgroundBun}},schedulerMode:"daemon",schedulerCommand:(e)=>`${jn(e)} ${Su}`,queueWorkerCommand:(e,t)=>{if(t.backgroundBun!==void 0)hu(e);let{current:r}=t,n=[`--queue=${e.queue||"default"}`,`--sleep=${e.sleep??3}`,`--tries=${e.tries??3}`,`--timeout=${e.timeout??60}`];return`${jn(t)} ${r}/${_u} ${n.join(" ")}`}},vu={id:"laravel",wrapExec:(e)=>`/bin/sh -lc '${Vo}; exec ${e}'`,schedulerMode:"cron",schedulerCommand:({current:e})=>`cd ${e} && ${Vo} && php artisan schedule:run`,queueWorkerCommand:(e,{current:t})=>{let r=`${t}/artisan`;if(e.horizon)return`php ${r} horizon`;let n=[e.connection||"default",`--queue=${e.queue||"default"}`,`--sleep=${e.sleep??3}`,`--tries=${e.tries??3}`,`--timeout=${e.timeout??60}`,`--memory=${e.memory??128}`];if(e.maxJobs)n.push(`--max-jobs=${e.maxJobs}`);if(e.maxTime)n.push(`--max-time=${e.maxTime}`);return`php ${r} queue:work ${n.join(" ")}`}},$u={stacks:qo,laravel:vu};function Wo(e){return $u[e]??qo}function Yo(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function yu(e){return`'${e.split("'").join("'\\''")}'`}function Xo(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"unnamed"}function Jo(e,t){return`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E '^${Yo(e)}-${Yo(t)}-((queue|daemon)-.*|scheduler)\\.service$' || true); do`}function qn(e){return[Jo(e.slug,e.siteName),' systemctl stop "$unit"',"done"]}function bu(e,t,r){return`${e}-${t}-queue-${r}`}function Tu(e,t,r,n){return`${e}-${t}-daemon-${r.name?Xo(r.name):Xo(r.command).slice(0,32)||String(n)}`}function Gn(e){let t=["[Unit]",`Description=${e.description}`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${e.workingDir}`,...Object.entries(e.environment??{}).map(([r,n])=>`Environment="${r}=${n}"`),`ExecStart=${e.execStart}`,`Restart=${e.restart||"always"}`,"RestartSec=5","MemoryAccounting=true",`MemoryHigh=${e.memoryHigh??"2G"}`,...e.memoryMax?[`MemoryMax=${e.memoryMax}`]:[]];if(e.isolatedUser){if(!e.isolationRoot||!e.isolationSlug)throw Error("Runtime isolation requires its project directory");t.push(...Ut(e.isolatedUser,e.isolationRoot,e.isolationSlug))}else 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(`
445
+ `),uu()}catch(s){return r.warn(`Management dashboard: could not stage the live release (${s?.message??s}) — skipping.`),null}}function tr(e){if(ot(Se(e,"packages","ui","pages"))||ot(Se(e,"packages","ui","package.json")))return{uiRoot:"packages/ui/dist",build:"cd packages/ui && bun install && bun run build"};let t=Bn(Bo(import.meta.url)),r=[Se(t,"ui"),Se(t,"..","ui"),Se(t,"..","..","ui"),Se(t,"..","dist","ui")];for(let n of r)if(ot(Se(n,"index.html"))||ot(Se(n,"serverless.html")))return{uiRoot:n,build:!1};return null}function Ri(e,t={}){let r=t.logger??Ko,n=t.cwd??process.cwd();if(zn(process.env.TS_CLOUD_UI_DISABLE))return r.info("Management dashboard: skipped (TS_CLOUD_UI_DISABLE set)."),e;if(e.cloud?.attachTo)return r.info(`Management dashboard: ${e.project.slug} is attached to ${e.cloud.attachTo}; the server owner's dashboard monitors every attached project.`),e;if(pr(e))return e;let s=e.environments&&Object.keys(e.environments)[0],i=process.env.TS_CLOUD_UI_DOMAIN?.trim()||void 0,a=Number(process.env.TS_CLOUD_UI_PORT)||void 0,c={...e.sites??{}};if(!zn(process.env.TS_CLOUD_UI_STATIC)){let v=du(e,n,r);if(!v)return e;let y=Zi(e,s??"production",{uiRoot:v,build:!1,domain:i,port:a,live:!0});if(y.length===0)return r.info("Management dashboard: no domain resolved (set TS_CLOUD_UI_DOMAIN or configure a site domain) — skipping."),e;for(let{name:T,site:x}of y)c[T]=x,r.info(`Management dashboard → https://${x.domain} (sign in with your ts-cloud account; the first deploy prints an admin password once)`);return e.sites=c,e}let f=tr(n);if(!f)return r.info("Management dashboard: UI not found (no local ui/ or packaged dist/ui) — skipping auto-deploy."),e;let g=process.env.TS_CLOUD_UI_USERNAME?.trim()||"admin",h=sd(n,g,r),S=Zi(e,s??"production",{uiRoot:f.uiRoot,build:f.build,domain:i,username:g,password:h.password,realm:process.env.TS_CLOUD_UI_REALM?.trim()||void 0,live:!1,port:a});if(S.length===0)return r.info("Management dashboard: no domain resolved (set TS_CLOUD_UI_DOMAIN or configure a site domain) — skipping."),e;let _=h.source==="public"?"NO AUTH — TS_CLOUD_UI_PUBLIC is set (dashboard is publicly reachable)":h.source==="env"?"htpasswd-protected (TS_CLOUD_UI_PASSWORD)":`htpasswd-protected (auto-generated — see ${ao()})`;r.warn("Management dashboard: static mode — one shared password, and no per-site collaborators. Unset TS_CLOUD_UI_STATIC for the live dashboard.");for(let{name:v,site:y}of S)c[v]=y,r.info(`Management dashboard → https://${y.domain} (${_})`);return e.sites=c,e}function Kn(e){return Object.keys(e.sites??{}).filter(mr)}function co(e,t){if(!e?.root)return null;let r=t.cwd??process.cwd(),n=t.logger??Ko;try{if(typeof e.build==="string"&&e.build.trim())n.info(`Management dashboard: building UI (${e.build})`),No(e.build,{cwd:r,stdio:"inherit"});let s=zo(e.root)?e.root:Se(r,e.root);if(!ot(s))return n.warn(`Management dashboard: build output not found at ${s} — skipping dashboard artifact.`),null;let i=Se(iu(),`${t.slug}-${t.siteName??id}-${t.sha}.tar.gz`);return No(`tar czf "${i}" -C "${s}" .`,{stdio:"inherit"}),i}catch(s){return n.warn(`Management dashboard: failed to build artifact — ${s?.message??s}. Skipping dashboard deploy.`),null}}function mu(e){let t=e.split("/");if(!/^[a-zA-Z0-9_./-]+$/.test(e)||e.startsWith("/")||t.some((r)=>!r||r==="."||r==="..")||t.at(-1)!=="bun")throw Error("Stacks backgroundBun must select a safe release-relative Bun executable")}function Go(e,t){if(mu(t),!/^\/[a-zA-Z0-9_./-]+$/.test(e)||e.split("/").includes(".."))throw Error("Stacks backgroundBun requires a safe absolute release directory");return`${e}/${t}`}var fu=new Set(["laravel","php","statamic","wordpress"]);function Vr(e){if(e.framework)return e.framework;if(e.type&&fu.has(e.type))return"laravel";return"stacks"}var Vo=`eval "$(cd ${u} && pantry env 2>/dev/null)"`,gu="/usr/local/bin/bun",Nr={PATH:"/usr/local/bin:/usr/bin:/bin",BUN_INSTALL:"/root/.bun",APP_ENV:"production",NODE_ENV:"production"};function jn(e){if(e.backgroundBun===void 0)return gu;return Go(e.current,e.backgroundBun)}function hu(e){let t=e.queue??"default",r=[e.sleep,e.tries,e.timeout,e.processes,e.stopWaitSecs];if(typeof t!=="string"||!/^[a-zA-Z0-9_.:,{}/@+-]+$/.test(t||"default")||r.some((n)=>n!==void 0&&(typeof n!=="number"||!Number.isFinite(n))))throw Error("Stacks background queue options require safe queue names and finite numeric values")}var Su="node_modules/@stacksjs/ts-cloud/dist/bin/stacks-scheduler.js",_u="node_modules/@stacksjs/ts-cloud/dist/bin/stacks-queue-worker.js",qo={id:"stacks",wrapExec:(e)=>e,execEnv:Nr,executionEnvironment:(e)=>{let t=jn(e);return e.backgroundBun===void 0?Nr:{...Nr,PATH:`${t.slice(0,t.lastIndexOf("/"))}:${Nr.PATH}`,TS_CLOUD_BACKGROUND_BUN:e.backgroundBun}},schedulerMode:"daemon",schedulerCommand:(e)=>`${jn(e)} ${Su}`,queueWorkerCommand:(e,t)=>{if(t.backgroundBun!==void 0)hu(e);let{current:r}=t,n=[`--queue=${e.queue||"default"}`,`--sleep=${e.sleep??3}`,`--tries=${e.tries??3}`,`--timeout=${e.timeout??60}`];return`${jn(t)} ${r}/${_u} ${n.join(" ")}`}},vu={id:"laravel",wrapExec:(e)=>`/bin/sh -lc '${Vo}; exec ${e}'`,schedulerMode:"cron",schedulerCommand:({current:e})=>`cd ${e} && ${Vo} && php artisan schedule:run`,queueWorkerCommand:(e,{current:t})=>{let r=`${t}/artisan`;if(e.horizon)return`php ${r} horizon`;let n=[e.connection||"default",`--queue=${e.queue||"default"}`,`--sleep=${e.sleep??3}`,`--tries=${e.tries??3}`,`--timeout=${e.timeout??60}`,`--memory=${e.memory??128}`];if(e.maxJobs)n.push(`--max-jobs=${e.maxJobs}`);if(e.maxTime)n.push(`--max-time=${e.maxTime}`);return`php ${r} queue:work ${n.join(" ")}`}},$u={stacks:qo,laravel:vu};function Wo(e){return $u[e]??qo}function Yo(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function yu(e){return`'${e.split("'").join("'\\''")}'`}function Xo(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"unnamed"}function Jo(e,t){return`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E '^${Yo(e)}-${Yo(t)}-((queue|daemon)-.*|scheduler)\\.service$' || true); do`}function qn(e){return[Jo(e.slug,e.siteName),' systemctl stop "$unit"',"done"]}function bu(e,t,r){return`${e}-${t}-queue-${r}`}function Tu(e,t,r,n){return`${e}-${t}-daemon-${r.name?Xo(r.name):Xo(r.command).slice(0,32)||String(n)}`}function Gn(e){let t=["[Unit]",`Description=${e.description}`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${e.workingDir}`,...Object.entries(e.environment??{}).map(([r,n])=>`Environment="${r}=${n}"`),...e.environmentFile?[`EnvironmentFile=-${e.environmentFile}`]:[],`ExecStart=${e.execStart}`,`Restart=${e.restart||"always"}`,"RestartSec=5","MemoryAccounting=true",`MemoryHigh=${e.memoryHigh??"2G"}`,...e.memoryMax?[`MemoryMax=${e.memoryMax}`]:[]];if(e.isolatedUser){if(!e.isolationRoot||!e.isolationSlug)throw Error("Runtime isolation requires its project directory");t.push(...Ut(e.isolatedUser,e.isolationRoot,e.isolationSlug))}else 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(`
446
446
  `)}
447
- `}function Vn(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_UNIT_EOF'`,t.replace(/\n$/,""),"TS_CLOUD_UNIT_EOF"]}function wu(e,t){return`/etc/cron.d/${e}-${t}-scheduler`}function Wn(e){let t=e.site.isolation&&!["laravel","php","statamic","wordpress"].includes(e.site.type||"")?pt(e.slug):void 0,{slug:r,siteName:n,site:s}=e,i=e.appBase??`/var/www/${n}`,a=`${i}/current`,c=Wo(Vr(s)),f=c.id==="stacks"&&s.backgroundBun!==void 0;if(f&&(!e.releaseId||!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(e.releaseId)))throw Error("Stacks backgroundBun requires a safe physical releaseId");let g=f?`${i}/releases/${e.releaseId}`:a,h={current:g,backgroundBun:s.backgroundBun},S=c.executionEnvironment?.(h)??c.execEnv,_=[],v=[];(s.queues||[]).forEach((I,V)=>{let W=c.wrapExec(c.queueWorkerCommand(I,h)),K=Math.max(1,I.processes??1);for(let ee=0;ee<K;ee++){let te=bu(r,n,v.length);v.push(te),_.push(...Vn(te,Gn({description:`${n} queue worker ${V}.${ee} (managed by ts-cloud)`,workingDir:g,execStart:W,environment:S,isolatedUser:t,isolationRoot:i,isolationSlug:r,stopWaitSecs:I.stopWaitSecs??90})))}}),(s.daemons||[]).forEach((I,V)=>{if(t&&I.user&&I.user!==t)throw Error("An isolated runtime daemon cannot change its project identity");let W=Math.max(1,I.processes??1);for(let K=0;K<W;K++){let ee=`${Tu(r,n,I,V)}-${K}`;v.push(ee),_.push(...Vn(ee,Gn({description:`${n} daemon ${I.name||I.command} (managed by ts-cloud)`,workingDir:I.directory||a,execStart:c.wrapExec(I.command),environment:c.execEnv,restart:I.restart,user:I.user,isolatedUser:t,isolationRoot:i,isolationSlug:r})))}});let x=s.scheduler,q=x===!0||typeof x==="object"&&x!==null,H=`${r}-${n}-scheduler`;if(q&&c.schedulerMode==="daemon"){v.push(H);let I=typeof x==="object"&&x!==null?x:{};_.push(...Vn(H,Gn({description:`${n} scheduler (managed by ts-cloud)`,workingDir:g,execStart:c.wrapExec(c.schedulerCommand(h)),environment:S,isolatedUser:t,isolationRoot:i,isolationSlug:r,memoryHigh:I.memoryHigh,memoryMax:I.memoryMax})),...br(`${H}.service`,{auto:!1,high:Boolean(I.memoryHigh),max:Boolean(I.memoryMax)}))}let R=v.map((I)=>`${I}.service`).join(" ");_.push("systemctl daemon-reload",`TS_CLOUD_DESIRED="${R}"`,Jo(r,n),' case " $TS_CLOUD_DESIRED " in',' *" $unit "*) ;;',' *) systemctl stop "$unit"; systemctl disable "$unit"; rm -f "/etc/systemd/system/$unit" ;;'," esac","done","systemctl daemon-reload");for(let I of v)_.push(`systemctl enable ${I}.service`,`systemctl restart ${I}.service`);let L=wu(r,n);if(q&&c.schedulerMode==="cron"){let I=typeof x==="object"&&x!==null?x:void 0,V=`${c.schedulerCommand(h)} >> /dev/null 2>&1`;if(I?.heartbeatUrl){let K=I.heartbeatMethod||"GET",ee=K==="GET"?"":`-X ${K} `;V+=` && curl -fsS -m 10 ${ee}${yu(I.heartbeatUrl)} >/dev/null 2>&1`}let W=`* * * * * root ${V}
447
+ `}function Vn(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_UNIT_EOF'`,t.replace(/\n$/,""),"TS_CLOUD_UNIT_EOF"]}function wu(e,t){return`/etc/cron.d/${e}-${t}-scheduler`}function Wn(e){let t=e.site.isolation&&!["laravel","php","statamic","wordpress"].includes(e.site.type||"")?pt(e.slug):void 0,{slug:r,siteName:n,site:s}=e,i=e.appBase??`/var/www/${n}`,a=`${i}/current`,c=Wo(Vr(s)),f=c.id==="stacks"&&s.backgroundBun!==void 0;if(f&&(!e.releaseId||!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(e.releaseId)))throw Error("Stacks backgroundBun requires a safe physical releaseId");let g=f?`${i}/releases/${e.releaseId}`:a,h={current:g,backgroundBun:s.backgroundBun},S=c.executionEnvironment?.(h)??c.execEnv,_=[],v=[];(s.queues||[]).forEach((I,V)=>{let W=c.wrapExec(c.queueWorkerCommand(I,h)),K=Math.max(1,I.processes??1);for(let te=0;te<K;te++){let Z=bu(r,n,v.length);v.push(Z),_.push(...Vn(Z,Gn({description:`${n} queue worker ${V}.${te} (managed by ts-cloud)`,workingDir:g,execStart:W,environment:S,isolatedUser:t,isolationRoot:i,isolationSlug:r,stopWaitSecs:I.stopWaitSecs??90})))}}),(s.daemons||[]).forEach((I,V)=>{if(t&&I.user&&I.user!==t)throw Error("An isolated runtime daemon cannot change its project identity");let W=Math.max(1,I.processes??1),K=I.directory||a,te=I.command.trim().replace(/^\.\//,()=>`${K.replace(/\/+$/,"")}/`);for(let Z=0;Z<W;Z++){let re=`${Tu(r,n,I,V)}-${Z}`;v.push(re),_.push(...Vn(re,Gn({description:`${n} daemon ${I.name||I.command} (managed by ts-cloud)`,workingDir:K,execStart:c.wrapExec(te),environment:c.execEnv,environmentFile:`${a}/.env`,restart:I.restart,user:I.user,isolatedUser:t,isolationRoot:i,isolationSlug:r})))}});let x=s.scheduler,q=x===!0||typeof x==="object"&&x!==null,H=`${r}-${n}-scheduler`;if(q&&c.schedulerMode==="daemon"){v.push(H);let I=typeof x==="object"&&x!==null?x:{};_.push(...Vn(H,Gn({description:`${n} scheduler (managed by ts-cloud)`,workingDir:g,execStart:c.wrapExec(c.schedulerCommand(h)),environment:S,isolatedUser:t,isolationRoot:i,isolationSlug:r,memoryHigh:I.memoryHigh,memoryMax:I.memoryMax})),...br(`${H}.service`,{auto:!1,high:Boolean(I.memoryHigh),max:Boolean(I.memoryMax)}))}let R=v.map((I)=>`${I}.service`).join(" ");_.push("systemctl daemon-reload",`TS_CLOUD_DESIRED="${R}"`,Jo(r,n),' case " $TS_CLOUD_DESIRED " in',' *" $unit "*) ;;',' *) systemctl stop "$unit"; systemctl disable "$unit"; rm -f "/etc/systemd/system/$unit" ;;'," esac","done","systemctl daemon-reload");for(let I of v)_.push(`systemctl enable ${I}.service`,`systemctl restart ${I}.service`);let L=wu(r,n);if(q&&c.schedulerMode==="cron"){let I=typeof x==="object"&&x!==null?x:void 0,V=`${c.schedulerCommand(h)} >> /dev/null 2>&1`;if(I?.heartbeatUrl){let K=I.heartbeatMethod||"GET",te=K==="GET"?"":`-X ${K} `;V+=` && curl -fsS -m 10 ${te}${yu(I.heartbeatUrl)} >/dev/null 2>&1`}let W=`* * * * * root ${V}
448
448
  `.replace(/%/g,"\\%");_.push(`cat > ${L} <<'TS_CLOUD_CRON_EOF'`,W.replace(/\n$/,""),"TS_CLOUD_CRON_EOF",`chmod 644 ${L}`)}else _.push(`rm -f ${L}`);return _}function Zo(e){return!!(e.queues?.length||e.daemons?.length||e.scheduler)}function Xn(e){if(e.ssl?.provider)return e.ssl.provider;return e.domain?"letsencrypt":"none"}var Qo={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 _i(e){return`/etc/letsencrypt/ts-cloud-${e}.ini`}function Cu(e){let t=e?Qo[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 Pu(e){if(!e.credentials||Object.keys(e.credentials).length===0)return[];let t=_i(e.provider),r=Object.entries(e.credentials).map(([n,s])=>`${n} = ${s}`).join(`
449
449
  `);return[`cat > ${t} <<'TS_CLOUD_DNSCREDS_EOF'`,r,"TS_CLOUD_DNSCREDS_EOF",`chmod 600 ${t}`]}function Eu(e){let t=e.dns,r=e.wildcard?[`*.${e.domain}`,e.domain]:[e.domain,...e.aliases||[]].filter(Boolean),n=["certbot","--non-interactive","--agree-tos","--keep-until-expiring"];if(t){let s=Qo[t.provider].plugin;if(n.push(`--${s}`),t.provider!=="route53"&&t.credentials)n.push(`--${s}-credentials ${_i(t.provider)}`);if(typeof t.propagationSeconds==="number"&&t.provider!=="route53")n.push(`--${s}-propagation-seconds ${t.propagationSeconds}`);n.push("certonly")}else n.push("--nginx",`--nginx-ctl ${Fe}`,e.redirect===!1?"--no-redirect":"--redirect");if(e.email)n.push(`-m ${e.email}`);else n.push("--register-unsafely-without-email");for(let s of r)n.push(`-d ${s}`);return[n.join(" ")]}function Jn(e){if(Xn(e)!=="letsencrypt"||!e.domain)return[];let t=e.ssl,r=t?.dns,n=t?.wildcard===!0;if(n&&!r)return[];return[...Cu(r),...r?Pu(r):[],...Eu({domain:e.domain,aliases:e.aliases,email:t?.email,wildcard:n,dns:r})]}function $i(e){let{repository:t,releaseDir:r,commit:n}=e,s=t.branch||"main",i=t.url,a=[`rm -rf ${r}`,`mkdir -p ${r}`];if(t.strategy==="tag")if(t.tag)a.push(`git clone -q --depth 1 --branch ${we(t.tag)} ${we(i)} ${r}`),a.push(`printf '%s' ${we(t.tag)} > ${r}/.ts-cloud-tag`);else{let c=t.tagPattern||"v*";a.push(`TS_CLOUD_TAG="$(git ls-remote --tags --refs --sort=-v:refname ${we(i)} ${we(`refs/tags/${c}`)} | head -n1 | sed 's#.*refs/tags/##')"`,`test -n "$TS_CLOUD_TAG" || { echo "no tags matching" ${we(c)} "found in" ${we(i)} >&2; exit 1; }`,`git clone -q --depth 1 --branch "$TS_CLOUD_TAG" ${we(i)} ${r}`,`printf '%s' "$TS_CLOUD_TAG" > ${r}/.ts-cloud-tag`)}else if(n)a.push(`git -C ${r} init -q`,`git -C ${r} remote add origin ${we(i)}`,`git -C ${r} fetch -q --depth 1 origin ${we(n)}`,`git -C ${r} checkout -q FETCH_HEAD`);else a.push(`git clone -q --depth 1 --branch ${we(s)} ${we(i)} ${r}`);return a.push(`git -C ${r} rev-parse HEAD > ${r}/.ts-cloud-sha`),a}function we(e){return`'${e.split("'").join("'\\''")}'`}var Br="$CREATE_RELEASE",Kr="$ACTIVATE_RELEASE",xi="$RESTART_QUEUES",Pi="composer install --no-interaction --prefer-dist --optimize-autoloader --no-dev",Ru=["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 Ou(e){switch(e){case"laravel":case"statamic":return[Br,Pi,...Ru,Kr,xi];case"php":case"wordpress":return[Br,`${Pi} || true`,Kr];case"static":case"spa":return[Br,Kr]}}function Du(e,t){return e.replace(/^php\s+/,`${t} `).replace(/(\s)php\s+artisan\s+/g,`$1${t} artisan `)}function xu(e,t){let r=fr(t);return[`cat > ${e} <<'TS_CLOUD_ENV_EOF'`,r,"TS_CLOUD_ENV_EOF",`chmod 600 ${e}`]}function Oi(e,t,r){return[`cat > ${e} <<'${r}'`,t.replace(/\n$/,""),r,`chmod 600 ${e}`]}function Au(e,t){if(!t)return[];let r=[];if(t.composerAuth){let n=typeof t.composerAuth==="string"?t.composerAuth:JSON.stringify(t.composerAuth,null,2);r.push(...Oi(`${e}/auth.json`,n,"TS_CLOUD_AUTHJSON_EOF"))}if(t.npmrc)r.push(...Oi(`${e}/.npmrc`,t.npmrc,"TS_CLOUD_NPMRC_EOF"));return r}function Li(e){let t=e.healthCheck?.path;if(!t||!e.domain)return[];let n=`http://127.0.0.1${t.startsWith("/")?t:`/${t}`}`;return[`echo "[ts-cloud] health check ${n} (Host: ${e.domain})"`,"TS_CLOUD_HC_OK=0",`for i in $(seq 1 10); do TS_CLOUD_HC=$(curl -s -o /dev/null -w "%{http_code}" -H "Host: ${e.domain}" -m 10 "${n}" 2>/dev/null || echo 000); case "$TS_CLOUD_HC" in 2*|3*) TS_CLOUD_HC_OK=1; break ;; esac; sleep 3; done`,'[ "$TS_CLOUD_HC_OK" = 1 ] && echo "health check passed ($TS_CLOUD_HC)" || { echo "health check FAILED (last=$TS_CLOUD_HC)" >&2; exit 1; }']}function Ui(e){let{siteName:t,site:r,releaseId:n,commit:s}=e;if(!r.repository?.url)throw Error(`Site '${t}' is a PHP/git site but has no repository.url to clone`);let i=e.appBase??`/var/www/${t}`,a="php",c=Zt(i,n),f=r.sharedPaths??gr,g=[...f,...yr(r.env,f)],h=r.keepReleases??Ht,S=r.deployScript?.length?r.deployScript:Ou(r.type??"laravel"),_=["set -euo pipefail",'export HOME="${HOME:-/root}"','export COMPOSER_HOME="${COMPOSER_HOME:-/root/.composer}"',"export COMPOSER_ALLOW_SUPERUSER=1",Ce()];if(_.push(...vr(i,{releaseId:n,commit:s,branch:r.repository.branch,keepLogs:h})),_.push(...Ft(c,g)),r.env&&Object.keys(r.env).length>0)_.push(...xu(`${c.shared}/.env`,r.env));for(let v of S){let y=v.trim();if(y===Br)_.push(...$i({repository:r.repository,releaseDir:c.release,commit:s})),_.push(...Sr(c,g)),_.push(`cd ${c.release}`),_.push(...Au(c.release,r.credentials)),_.push(`chown -R www-data:www-data ${c.shared}/storage 2>/dev/null || true`,`[ -d ${c.release}/bootstrap/cache ] && chown -R www-data:www-data ${c.release}/bootstrap/cache 2>/dev/null || true`,`chmod -R ug+rwX ${c.shared}/storage 2>/dev/null || true`);else if(y===Kr)_.push(...dt(c)),_.push(...mt(c,h)),_.push(`(cd ${u} && pantry restart php-fpm) 2>/dev/null || true`);else if(y===xi)_.push(`${a} artisan queue:restart || true`);else _.push(Du(v,a))}return _}var jr={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"]}},Jt="ts-cloud-service:";function Iu(e){return e===!0||typeof e==="object"&&e!=null}function Hi(e){if(!e)return[];return Object.keys(jr).filter((t)=>Iu(e[t]))}function Ni(e){if(e.length===0)return[];return[Ce(),"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 "${Jt}$TS_CLOUD_SVC:present"; return 0; fi`," done",` if ts_cloud_port_open "$TS_CLOUD_PORT"; then echo "${Jt}$TS_CLOUD_SVC:present"; return 0; fi`,` echo "${Jt}$TS_CLOUD_SVC:missing"`," return 0","}",...e.filter((t)=>jr[t]).map((t)=>`ts_cloud_probe ${t} ${jr[t].port} ${jr[t].binaries.join(" ")}`),"exit 0"]}function Mi(e,t){if(!e)return[];let r=new Map;for(let n of e.split(`
450
450
  `)){let s=n.indexOf(Jt);if(s===-1)continue;let[i,a]=n.slice(s+Jt.length).trim().split(":");if(i)r.set(i,a)}return t.filter((n)=>r.get(n)==="missing")}function Fi(e,t,r){let n=r?` on ${r}`:"",s=e.map((a)=>`managedServices.${a}`).join(", "),i=e.length===1?`no ${e[0]}`:`none of ${e.join(", ")}`;return`This project declares ${s}, but '${t}' has ${i}${n}. Attach mode does not provision services on the owner's box, so nothing will install ${e.length===1?"it":"them"}. Point the app at an external service, or ask the owner of '${t}' to add ${e.length===1?"it":"them"} to their own config and re-provision.`}var zi="/var/lib/pantry/php-fpm/pool.d",Lu=9100,Uu=400;function Wr(e){return(e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"site").slice(0,28)}function Bi(e){return`web_${Wr(e)}`}function ku(e){let t=Wr(e),r=0;for(let n=0;n<t.length;n++)r=r*31+t.charCodeAt(n)>>>0;return Lu+r%Uu}function Qn(e){return`127.0.0.1:${ku(e)}`}function Hu(e){let t=Wr(e.siteName),r=Bi(e.siteName),n=e.maxChildren??10;return[`; ts-cloud-managed pool for ${e.siteName} (site isolation)`,`[${t}]`,`user = ${r}`,`group = ${r}`,`listen = ${Qn(e.siteName)}`,"pm = dynamic",`pm.max_children = ${n}`,"pm.start_servers = 2","pm.min_spare_servers = 1","pm.max_spare_servers = 3","pm.max_requests = 500","catch_workers_output = yes",`php_admin_value[open_basedir] = ${e.appBase}:/tmp`,""].join(`
451
- `)}function Ki(e){let t=Bi(e.siteName),r=Wr(e.siteName),n=`${zi}/${r}.conf`;return[`getent group ${t} >/dev/null || groupadd --system ${t}`,`id -u ${t} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin -g ${t} ${t}`,`usermod -aG ${t} www-data 2>/dev/null || true`,`chown -R ${t}:${t} ${e.appBase} || true`,`chmod -R g+rX ${e.appBase} || true`,`chmod 600 ${e.appBase}/shared/.env 2>/dev/null || true`,`mkdir -p ${zi}`,`cat > ${n} <<'TS_CLOUD_FPMPOOL_EOF'`,Hu(e).replace(/\n$/,""),"TS_CLOUD_FPMPOOL_EOF",`(cd ${u} && pantry restart php-fpm) 2>/dev/null || true`]}var Xr={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};function zu(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function lo(e,t,r=Xr){let{config:n,environment:s,siteName:i,site:a,slug:c,sha:f,runtime:g,localTarballPath:h}=t,S=`releases/${i}/${f}.tar.gz`,_=m(n,s),v=await e.getComputeOutputs({config:n,environment:s}),y=await e.findComputeTargets({slug:c,environment:s,role:"app",stackName:_});if(y.length===0)return{success:!1,error:e.name==="aws"?`Stack '${_}' has no EC2 instances tagged Project=${c} Environment=${s} Role=app, and storage/cloud/state/${_}.json pins no live instance. For a shared box, record its instanceId there.`:`No Hetzner servers labeled ts-cloud/project=${c} ts-cloud/environment=${s} ts-cloud/role=app, and storage/cloud/state/${_}.json pins no live server. For a shared box, record its serverId there.`};let T=v.servicesPrivateIp?Js(v.servicesPrivateIp,p(n)):ps(p(n)),x=Ji(C(n,{environment:s})),q=n.infrastructure?.compute,H=ni(q?.hostCleanup),R=j({...q,proxy:w(n,{environment:s})})?{HOST:"127.0.0.1"}:{},L=s==="production"?{APP_ENV:"production",NODE_ENV:"production"}:{},I={...T,...x,...R,...a.env||{},...L},V=Pn(I,a.sharedPaths??[]);if(V.warning)r.warn(`Site '${i}': ${V.warning}`);else if(V.path)r.info(`Site '${i}': sharing '${V.path}' so the SQLite database survives deploys.`);if(zr(a)){let P=a.phpVersion??q?.php?.default??q?.php?.versions?.[0],O=U(c,i),D=Object.keys(T).length>0?{...a,env:I}:a,J=Ui({siteName:i,site:D,releaseId:f,appBase:O,defaultPhpVersion:P}),Y=!j(q),Z=Xn(a)==="custom"&&a.ssl?.certPath&&a.ssl?.keyPath?{certPath:a.ssl.certPath,keyPath:a.ssl.keyPath}:void 0,le=a.isolation?Ki({siteName:i,appBase:O}):[],E=Y?mn({siteName:i,domain:a.domain||i,aliases:a.aliases,type:a.type,appDir:`${O}/current`,webDirectory:a.webDirectory,phpVersion:P,fastcgiPass:a.isolation?Qn(i):void 0,redirects:a.redirects,ssl:Z,auth:a.auth&&a.auth.enabled!==!1&&a.auth.password?{username:a.auth.username||"admin",password:a.auth.password,realm:a.auth.realm}:void 0,serverSnippet:dn(a.nginx,q?.nginxTemplates),clientMaxBodySize:a.nginx?.clientMaxBodySize,hsts:a.ssl?.hsts,tlsProtocols:a.ssl?.tlsProtocols,security:a.security}):[],N=Y?Jn(a):[],he=Zo(a)?Wn({slug:c,siteName:i,site:a,phpVersion:P,appBase:O}):[],ae=Y?Li(a):[];r.step(`Deploying PHP site '${i}' to ${y.length} target(s)...`);let _e=await e.runRemoteDeploy({targets:y,commands:[...Cn(O,c),...Mr(O,c),...J,...le,...E,...N,...he,...ae,...H],comment:`ts-cloud deploy ${c}/${i}@${f}`,tags:{Project:c,Environment:s,Role:"app"}}),Rt=hs(n.notifications,a.notifications);if(!_e.success)return await ji(e,y,H,r),await gn(Rt,"deploy-failed",`❌ Deploy of ${c}/${i}@${f} failed: ${_e.error||"unknown error"}`),{success:!1,error:_e.error||"Remote PHP deploy failed",instanceCount:_e.instanceCount,perInstance:_e.perInstance};let qi=a.domain?` → https://${a.domain}`:"";return await gn(Rt,"deploy",`✅ Deployed ${c}/${i}@${f}${qi}`),{success:!0,instanceCount:_e.instanceCount,perInstance:_e.perInstance}}if(!h)return{success:!1,error:`Site '${i}' requires a release tarball but none was provided`};let W=await e.uploadRelease({config:n,environment:s,localPath:h,remoteKey:S,targets:y}),K=ai(c,i,f),ee=e.name==="aws"?$c(v.deployBucketName,S,n.project.region||"us-east-1",K):Mc(W.artifactRef,K),te=d(a),ne=U(c,i),ie=Wn({slug:c,siteName:i,site:a,appBase:ne,releaseId:f}),oe=te==="server-static"?oi({siteName:i,slug:c,appDir:ne,artifactFetch:ee,releaseId:f,preStartCommands:a.preStart,postActivateCommands:ie,beforeResetCommands:qn({slug:c,siteName:i})}):si({siteName:i,slug:c,appDir:ne,artifactFetch:ee,releaseId:f,execStart:ii(a.start,g,`${ne.replace(/\/+$/,"")}/releases/%i`),envEntries:I,isolation:a.isolation,port:a.port,preStartCommands:a.preStart,postActivateCommands:ie,beforeResetCommands:qn({slug:c,siteName:i}),sharedPaths:a.sharedPaths,zeroDowntime:a.zeroDowntime!==!1,healthCheckPath:a.healthCheck?.path,liveness:a.liveness,memoryHigh:a.memoryHigh,memoryMax:a.memoryMax,cpuWeight:a.cpuWeight,ioWeight:a.ioWeight,tasksMax:a.tasksMax,stopTimeout:a.stopTimeout}),re=te==="server-static"&&!j(q)&&!!a.domain,pe=re?mn({siteName:i,domain:a.domain,aliases:a.aliases,type:a.type==="spa"?"spa":"static",appDir:`${ne}/current`,webDirectory:"",redirects:a.redirects,auth:a.auth&&a.auth.enabled!==!1&&a.auth.password?{username:a.auth.username||"admin",password:a.auth.password,realm:a.auth.realm}:void 0,serverSnippet:dn(a.nginx,q?.nginxTemplates),clientMaxBodySize:a.nginx?.clientMaxBodySize,hsts:a.ssl?.hsts,tlsProtocols:a.ssl?.tlsProtocols,security:a.security}):[],ge=re?Jn(a):[],b=[...vr(ne,{releaseId:f,commit:f,branch:a.repository?.branch??"main"}),...Cn(ne,c),...Mr(ne,c),...oe,...pe,...ge,...H];r.step(`Deploying to ${y.length} target(s)...`);let k=await e.runRemoteDeploy({targets:y,commands:b,comment:`ts-cloud deploy ${c}/${i}@${f}`,tags:{Project:c,Environment:s,Role:"app"}});if(!k.success)return await ji(e,y,H,r),{success:!1,error:k.error||"Remote deploy failed",instanceCount:k.instanceCount,perInstance:k.perInstance};return{success:!0,instanceCount:k.instanceCount,perInstance:k.perInstance}}async function ji(e,t,r,n){if(r.length===0)return;try{let s=await e.runRemoteDeploy({targets:t,commands:r,comment:"ts-cloud host cleanup after failed deploy"});if(!s.success)n.warn(`Host cleanup after the failed deploy did not complete: ${s.error||"unknown error"}`)}catch(s){n.warn(`Host cleanup after the failed deploy did not run: ${s.message}`)}}function Yr(e){return`'${e.replaceAll("'","'\\''")}'`}function Bu(e,t,r=!1,n=[]){let s=`${e}-dashboard-`,i=t.map((c)=>`${e}-${c}.service`),a=r?[`export TS_CLOUD_DASHBOARD_KEEP_DOMAINS=${Yr(JSON.stringify(n))}`,"rm -f /run/ts-cloud-dashboard-routes-changed",`/usr/local/bin/bun --bun -e ${Yr(`
451
+ `)}function Ki(e){let t=Bi(e.siteName),r=Wr(e.siteName),n=`${zi}/${r}.conf`;return[`getent group ${t} >/dev/null || groupadd --system ${t}`,`id -u ${t} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin -g ${t} ${t}`,`usermod -aG ${t} www-data 2>/dev/null || true`,`chown -R ${t}:${t} ${e.appBase} || true`,`chmod -R g+rX ${e.appBase} || true`,`chmod 600 ${e.appBase}/shared/.env 2>/dev/null || true`,`mkdir -p ${zi}`,`cat > ${n} <<'TS_CLOUD_FPMPOOL_EOF'`,Hu(e).replace(/\n$/,""),"TS_CLOUD_FPMPOOL_EOF",`(cd ${u} && pantry restart php-fpm) 2>/dev/null || true`]}var Xr={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};function zu(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function lo(e,t,r=Xr){let{config:n,environment:s,siteName:i,site:a,slug:c,sha:f,runtime:g,localTarballPath:h}=t,S=`releases/${i}/${f}.tar.gz`,_=m(n,s),v=await e.getComputeOutputs({config:n,environment:s}),y=await e.findComputeTargets({slug:c,environment:s,role:"app",stackName:_});if(y.length===0)return{success:!1,error:e.name==="aws"?`Stack '${_}' has no EC2 instances tagged Project=${c} Environment=${s} Role=app, and storage/cloud/state/${_}.json pins no live instance. For a shared box, record its instanceId there.`:`No Hetzner servers labeled ts-cloud/project=${c} ts-cloud/environment=${s} ts-cloud/role=app, and storage/cloud/state/${_}.json pins no live server. For a shared box, record its serverId there.`};let T=v.servicesPrivateIp?Js(v.servicesPrivateIp,p(n)):ps(p(n)),x=Ji(C(n,{environment:s})),q=n.infrastructure?.compute,H=ni(q?.hostCleanup),R=j({...q,proxy:w(n,{environment:s})})?{HOST:"127.0.0.1"}:{},L=s==="production"?{APP_ENV:"production",NODE_ENV:"production"}:{},I={...T,...x,...R,...a.env||{},...L},V=Pn(I,a.sharedPaths??[]);if(V.warning)r.warn(`Site '${i}': ${V.warning}`);else if(V.path)r.info(`Site '${i}': sharing '${V.path}' so the SQLite database survives deploys.`);if(zr(a)){let P=a.phpVersion??q?.php?.default??q?.php?.versions?.[0],O=U(c,i),D=Object.keys(T).length>0?{...a,env:I}:a,J=Ui({siteName:i,site:D,releaseId:f,appBase:O,defaultPhpVersion:P}),Y=!j(q),ee=Xn(a)==="custom"&&a.ssl?.certPath&&a.ssl?.keyPath?{certPath:a.ssl.certPath,keyPath:a.ssl.keyPath}:void 0,le=a.isolation?Ki({siteName:i,appBase:O}):[],E=Y?mn({siteName:i,domain:a.domain||i,aliases:a.aliases,type:a.type,appDir:`${O}/current`,webDirectory:a.webDirectory,phpVersion:P,fastcgiPass:a.isolation?Qn(i):void 0,redirects:a.redirects,ssl:ee,auth:a.auth&&a.auth.enabled!==!1&&a.auth.password?{username:a.auth.username||"admin",password:a.auth.password,realm:a.auth.realm}:void 0,serverSnippet:dn(a.nginx,q?.nginxTemplates),clientMaxBodySize:a.nginx?.clientMaxBodySize,hsts:a.ssl?.hsts,tlsProtocols:a.ssl?.tlsProtocols,security:a.security}):[],N=Y?Jn(a):[],he=Zo(a)?Wn({slug:c,siteName:i,site:a,phpVersion:P,appBase:O}):[],ae=Y?Li(a):[];r.step(`Deploying PHP site '${i}' to ${y.length} target(s)...`);let _e=await e.runRemoteDeploy({targets:y,commands:[...Cn(O,c),...Mr(O,c),...J,...le,...E,...N,...he,...ae,...H],comment:`ts-cloud deploy ${c}/${i}@${f}`,tags:{Project:c,Environment:s,Role:"app"}}),Rt=hs(n.notifications,a.notifications);if(!_e.success)return await ji(e,y,H,r),await gn(Rt,"deploy-failed",`❌ Deploy of ${c}/${i}@${f} failed: ${_e.error||"unknown error"}`),{success:!1,error:_e.error||"Remote PHP deploy failed",instanceCount:_e.instanceCount,perInstance:_e.perInstance};let qi=a.domain?` → https://${a.domain}`:"";return await gn(Rt,"deploy",`✅ Deployed ${c}/${i}@${f}${qi}`),{success:!0,instanceCount:_e.instanceCount,perInstance:_e.perInstance}}if(!h)return{success:!1,error:`Site '${i}' requires a release tarball but none was provided`};let W=await e.uploadRelease({config:n,environment:s,localPath:h,remoteKey:S,targets:y}),K=ai(c,i,f),te=e.name==="aws"?$c(v.deployBucketName,S,n.project.region||"us-east-1",K):Mc(W.artifactRef,K),Z=d(a),re=U(c,i),ie=Wn({slug:c,siteName:i,site:a,appBase:re,releaseId:f}),oe=Z==="server-static"?oi({siteName:i,slug:c,appDir:re,artifactFetch:te,releaseId:f,preStartCommands:a.preStart,postActivateCommands:ie,beforeResetCommands:qn({slug:c,siteName:i})}):si({siteName:i,slug:c,appDir:re,artifactFetch:te,releaseId:f,execStart:ii(a.start,g,`${re.replace(/\/+$/,"")}/releases/%i`),envEntries:I,isolation:a.isolation,port:a.port,preStartCommands:a.preStart,postActivateCommands:ie,beforeResetCommands:qn({slug:c,siteName:i}),sharedPaths:a.sharedPaths,zeroDowntime:a.zeroDowntime!==!1,healthCheckPath:a.healthCheck?.path,liveness:a.liveness,memoryHigh:a.memoryHigh,memoryMax:a.memoryMax,cpuWeight:a.cpuWeight,ioWeight:a.ioWeight,tasksMax:a.tasksMax,stopTimeout:a.stopTimeout}),ne=Z==="server-static"&&!j(q)&&!!a.domain,pe=ne?mn({siteName:i,domain:a.domain,aliases:a.aliases,type:a.type==="spa"?"spa":"static",appDir:`${re}/current`,webDirectory:"",redirects:a.redirects,auth:a.auth&&a.auth.enabled!==!1&&a.auth.password?{username:a.auth.username||"admin",password:a.auth.password,realm:a.auth.realm}:void 0,serverSnippet:dn(a.nginx,q?.nginxTemplates),clientMaxBodySize:a.nginx?.clientMaxBodySize,hsts:a.ssl?.hsts,tlsProtocols:a.ssl?.tlsProtocols,security:a.security}):[],ge=ne?Jn(a):[],b=[...vr(re,{releaseId:f,commit:f,branch:a.repository?.branch??"main"}),...Cn(re,c),...Mr(re,c),...oe,...pe,...ge,...H];r.step(`Deploying to ${y.length} target(s)...`);let k=await e.runRemoteDeploy({targets:y,commands:b,comment:`ts-cloud deploy ${c}/${i}@${f}`,tags:{Project:c,Environment:s,Role:"app"}});if(!k.success)return await ji(e,y,H,r),{success:!1,error:k.error||"Remote deploy failed",instanceCount:k.instanceCount,perInstance:k.perInstance};return{success:!0,instanceCount:k.instanceCount,perInstance:k.perInstance}}async function ji(e,t,r,n){if(r.length===0)return;try{let s=await e.runRemoteDeploy({targets:t,commands:r,comment:"ts-cloud host cleanup after failed deploy"});if(!s.success)n.warn(`Host cleanup after the failed deploy did not complete: ${s.error||"unknown error"}`)}catch(s){n.warn(`Host cleanup after the failed deploy did not run: ${s.message}`)}}function Yr(e){return`'${e.replaceAll("'","'\\''")}'`}function Bu(e,t,r=!1,n=[]){let s=`${e}-dashboard-`,i=t.map((c)=>`${e}-${c}.service`),a=r?[`export TS_CLOUD_DASHBOARD_KEEP_DOMAINS=${Yr(JSON.stringify(n))}`,"rm -f /run/ts-cloud-dashboard-routes-changed",`/usr/local/bin/bun --bun -e ${Yr(`
452
452
  const { chmodSync, existsSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } = require('node:fs')
453
453
  const { basename, join } = require('node:path')
454
454
  const root = '/etc/rpx/sites.d'