@stacksjs/ts-cloud 0.16.78 → 0.16.79
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/{chunk-n5sapbxq.js → chunk-2wkw8qy0.js} +60 -58
- package/dist/bin/{chunk-hkqq09p2.js → chunk-fgnvksyx.js} +1 -1
- package/dist/bin/{chunk-2xtxktj3.js → chunk-grx14tmn.js} +1 -1
- package/dist/bin/cli.js +4 -4
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/{chunk-wxy6jk7d.js → chunk-p9cm5ynz.js} +55 -53
- package/dist/{chunk-m95n1mbv.js → chunk-wy0bqg1v.js} +1 -1
- package/dist/deploy/index.js +1 -1
- package/dist/drivers/index.js +1 -1
- package/dist/drivers/shared/runtime-isolation.d.ts +2 -0
- package/dist/index.js +1 -1
- package/dist/ui/404.html +1 -1
- package/dist/ui/accept-invitation.html +1 -1
- package/dist/ui/access-denied.html +1 -1
- package/dist/ui/account/automation.html +6 -6
- package/dist/ui/account/security.html +2 -2
- package/dist/ui/applications/compose.html +6 -6
- package/dist/ui/applications/new.html +2 -2
- package/dist/ui/data/backups.html +6 -6
- package/dist/ui/data/services.html +6 -6
- package/dist/ui/data/volumes.html +6 -6
- package/dist/ui/index.html +6 -6
- package/dist/ui/infrastructure/topology.html +6 -6
- package/dist/ui/integrations.html +1 -1
- package/dist/ui/operations/alerts.html +6 -6
- package/dist/ui/operations/configuration.html +5 -5
- package/dist/ui/operations/jobs.html +5 -5
- package/dist/ui/operations/maintenance.html +5 -5
- package/dist/ui/operations/observability.html +6 -6
- package/dist/ui/operations/previews.html +6 -6
- package/dist/ui/operations/queue.html +6 -6
- package/dist/ui/operations/regions.html +5 -5
- package/dist/ui/operations/releases.html +6 -6
- package/dist/ui/operations/spend.html +6 -6
- package/dist/ui/operations/workloads.html +6 -6
- package/dist/ui/security.html +2 -2
- package/dist/ui/server/actions.html +6 -6
- package/dist/ui/server/activity.html +2 -2
- package/dist/ui/server/capacity.html +6 -6
- package/dist/ui/server/database.html +6 -6
- package/dist/ui/server/deployments.html +6 -6
- package/dist/ui/server/diagnostics.html +2 -2
- package/dist/ui/server/firewall.html +6 -6
- package/dist/ui/server/fleet.html +6 -6
- package/dist/ui/server/logs.html +6 -6
- package/dist/ui/server/metrics.html +6 -6
- package/dist/ui/server/security.html +2 -2
- package/dist/ui/server/services.html +1 -1
- package/dist/ui/server/sites.html +6 -6
- package/dist/ui/server/ssh-keys.html +6 -6
- package/dist/ui/server/team.html +6 -6
- package/dist/ui/server/terminal.html +2 -2
- package/dist/ui/serverless/alarms.html +6 -6
- package/dist/ui/serverless/assets.html +2 -2
- package/dist/ui/serverless/cost.html +2 -2
- package/dist/ui/serverless/data.html +6 -6
- package/dist/ui/serverless/deployments.html +2 -2
- package/dist/ui/serverless/firewall.html +1 -1
- package/dist/ui/serverless/functions.html +6 -6
- package/dist/ui/serverless/logs.html +6 -6
- package/dist/ui/serverless/metrics.html +2 -2
- package/dist/ui/serverless/queues.html +6 -6
- package/dist/ui/serverless/secrets.html +6 -6
- package/dist/ui/serverless/traces.html +6 -6
- package/dist/ui/serverless.html +6 -6
- package/package.json +3 -3
|
@@ -60,7 +60,8 @@ ${a.join(`
|
|
|
60
60
|
# aborts with "HOME: unbound variable" and /usr/local/bin/bun never appears —
|
|
61
61
|
# breaking a from-scratch provision (adopting an existing box masked it).
|
|
62
62
|
export HOME="\${HOME:-/root}"
|
|
63
|
-
export BUN_INSTALL="/
|
|
63
|
+
export BUN_INSTALL="/opt/ts-cloud/bun"
|
|
64
|
+
install -d -m 755 /opt/ts-cloud /opt/ts-cloud/bun /opt/ts-cloud/bun/bin
|
|
64
65
|
# bun.sh's installer references $HOME internally and runs under this
|
|
65
66
|
# script's \`set -u\` (inherited by the piped bash) — cloud-init's runcmd
|
|
66
67
|
# environment doesn't export HOME by default, so without this the
|
|
@@ -73,8 +74,9 @@ export BUN_INSTALL="/root/.bun"
|
|
|
73
74
|
# actually done.
|
|
74
75
|
export HOME="\${HOME:-/root}"
|
|
75
76
|
curl -fsSL https://bun.sh/install | bash${r==="latest"?"":` -s "bun-v${r}"`}
|
|
76
|
-
|
|
77
|
-
|
|
77
|
+
chmod 755 /opt/ts-cloud/bun/bin/bun
|
|
78
|
+
ln -sf /opt/ts-cloud/bun/bin/bun /usr/local/bin/bun
|
|
79
|
+
echo 'export BUN_INSTALL="/opt/ts-cloud/bun"' > /etc/profile.d/bun.sh
|
|
78
80
|
echo 'export PATH="$BUN_INSTALL/bin:$PATH"' >> /etc/profile.d/bun.sh
|
|
79
81
|
`;else if(t==="node"){let y=r==="latest"||!r?"20":r.split(".")[0];_+=`
|
|
80
82
|
curl -fsSL https://deb.nodesource.com/setup_${y}.x | bash -
|
|
@@ -135,7 +137,7 @@ ${y.join(`
|
|
|
135
137
|
`}return _+=`
|
|
136
138
|
echo "ts-cloud bootstrap complete — instance is ready for site deploys"
|
|
137
139
|
`,_}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
|
-
`),"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
|
|
140
|
+
`),"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 ol,execSync as ho}from"node:child_process";import{createHash as al,randomUUID as So}from"node:crypto";import{createReadStream as cl,existsSync as ll,readFileSync as ul}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
141
|
`,{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
142
|
${D.join(`
|
|
141
143
|
`)}
|
|
@@ -150,15 +152,15 @@ RequiresMountsFor=${b.join(" ")}
|
|
|
150
152
|
`)}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
153
|
`).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
154
|
await (${Is.toString()})(JSON.parse(await Bun.file(process.env.TS_CLOUD_STORAGE_POLICY || ${JSON.stringify(Sn)}).text()), process.argv.slice(2));
|
|
153
|
-
`;return['command -v bun >/dev/null 2>&1 || { echo "Configured compute storage requires Bun on the host" >&2; exit 1; }',"install -d -m 0755 /etc/ts-cloud /usr/local/lib/ts-cloud /var/lib/ts-cloud",`printf %s ${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[
|
|
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.
|
|
155
|
+
`;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 ec(){return["if [ -x /usr/local/bin/bun ]; then",' TS_CLOUD_HOST_BUN="$(readlink -f /usr/local/bin/bun)"',' case "$TS_CLOUD_HOST_BUN" in /root/*|/home/*)'," install -d -m 755 /opt/ts-cloud /opt/ts-cloud/bun /opt/ts-cloud/bun/bin",' TS_CLOUD_BUN_STAGE="$(mktemp /opt/ts-cloud/bun/bin/.bun.XXXXXX)"',' install -m 755 "$TS_CLOUD_HOST_BUN" "$TS_CLOUD_BUN_STAGE"',' mv -f "$TS_CLOUD_BUN_STAGE" /opt/ts-cloud/bun/bin/bun'," ln -sfn /opt/ts-cloud/bun/bin/bun /usr/local/bin/bun"," ;; esac","fi"]}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[...ec(),`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}=${tc(String(r))}`).join(`
|
|
156
|
+
`)}function tc(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 rc(e){return`${Ue(e)}/deploy-history.log`}function nc(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 sc(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)}`,...sc(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}`,...oc(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 oc(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 ic(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(...ic(c,i));r.push(...f);continue}r.push(`if [ -e ${i} ]; then`,...f.map((g)=>` ${g}`),"fi")}return r}function ac(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),...ac(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 cc(e){return`${Ue(e)}/owner`}function Cn(e,t){let r=cc(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=nc(e,t.releaseId),s=rc(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 lc=new Set(["sqlite","sqlite3"]),uc=new Set([":memory:","memory"]);function pc(e){let t=e?.DB_CONNECTION?.trim().toLowerCase();return t!=null&&lc.has(t)}function dc(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(!pc(e))return{};let r=e?.DB_DATABASE_PATH?.trim()||e?.DB_DATABASE?.trim();if(r&&uc.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=dc(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 mc(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(mc),{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(fc),`journalctl --vacuum-time=${Ge("journalMaxAgeDays")}d --vacuum-size=${Ge("journalMaxSizeMb")}M >/dev/null 2>&1 || true`]}function fc(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 gc=/\.(?:[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&&!gc.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.
|
|
155
157
|
# An eighth of %sMB RAM. Set memoryHigh in config to override.
|
|
156
158
|
[Service]
|
|
157
159
|
MemoryAccounting=true
|
|
158
160
|
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),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(`
|
|
161
|
+
' "$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 hc(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,Sc=5,vc=60;function yc(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 ${Sc} "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 ${vc}); 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()],...hc(b),...yc({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
162
|
`)}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
|
-
`)}var Qc=di();import{homedir as
|
|
163
|
+
`)}var Qc=di();import{homedir as bc}from"node:os";import{join as Tc}from"node:path";var Cr={location:"fsn1",image:"ubuntu-24.04",sshUser:"root",sshPrivateKeyPath:"~/.ssh/id_ed25519"};function Pr(e){return e.startsWith("~/")?Tc(bc(),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 wc(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 Cc(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:wc(e,t.sshUser),sshPrivateKeyPath:r,sshPublicKeyPath:Cc(e,t.sshPublicKeyPath,r)}}var Pc="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??Pc,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
164
|
`)?e:`${e}
|
|
163
165
|
`}function se(e,t={}){let r=t.scriptPath??"/var/lib/cloud/ts-cloud-bootstrap.sh",n=t.permissions??"0755",s=e.split(`
|
|
164
166
|
`).map((i)=>` ${i}`).join(`
|
|
@@ -171,7 +173,7 @@ ${fo(t.before)}write_files:
|
|
|
171
173
|
${s}
|
|
172
174
|
runcmd:
|
|
173
175
|
- [ bash, ${r} ]
|
|
174
|
-
${fo(t.after)}`}function Dr(e){let t=new Set([80,443,...e.sitePorts,...e.allowedPorts??[]]);if(e.allowSsh)t.add(22);return[...t].map((r)=>({direction:"in",protocol:"tcp",port:String(r),source_ips:["0.0.0.0/0","::/0"],description:`ts-cloud port ${r}`}))}var In={micro:"cpx11",small:"cx23",medium:"cx33",large:"cx43",xlarge:"cx53","2xlarge":"ccx33"};function Ye(e){if(!e)return In.micro;if(e in In)return In[e];return e}var me="ts-cloud";function fe(e,t,r="app"){return{[`${me}/project`]:e,[`${me}/environment`]:t,[`${me}/role`]:r,[`${me}/managed-by`]:"ts-cloud"}}function ye(e,t,r,n="app"){return Ln(e,t,r)&&e[`${me}/role`]===n}function Ln(e,t,r){if(!e)return!1;return e[`${me}/project`]===t&&e[`${me}/environment`]===r}function
|
|
176
|
+
${fo(t.after)}`}function Dr(e){let t=new Set([80,443,...e.sitePorts,...e.allowedPorts??[]]);if(e.allowSsh)t.add(22);return[...t].map((r)=>({direction:"in",protocol:"tcp",port:String(r),source_ips:["0.0.0.0/0","::/0"],description:`ts-cloud port ${r}`}))}var In={micro:"cpx11",small:"cx23",medium:"cx33",large:"cx43",xlarge:"cx53","2xlarge":"ccx33"};function Ye(e){if(!e)return In.micro;if(e in In)return In[e];return e}var me="ts-cloud";function fe(e,t,r="app"){return{[`${me}/project`]:e,[`${me}/environment`]:t,[`${me}/role`]:r,[`${me}/managed-by`]:"ts-cloud"}}function ye(e,t,r,n="app"){return Ln(e,t,r)&&e[`${me}/role`]===n}function Ln(e,t,r){if(!e)return!1;return e[`${me}/project`]===t&&e[`${me}/environment`]===r}function Ec(e){return e.location?.name??e.datacenter?.location.name??"unknown"}function _t(e){return typeof e==="number"&&Number.isFinite(e)?e:0}function Rc(e,t){if(e.architecture&&t.architecture&&e.architecture!==t.architecture)throw Error(`Cannot resize ${e.name} (${e.architecture}) to ${t.name} (${t.architecture}) in place.`);let r=[];if(_t(t.cores)<_t(e.cores))r.push("CPU");if(_t(t.memory)<_t(e.memory))r.push("memory");if(_t(t.disk)<_t(e.disk))r.push("disk");if(r.length>0)throw Error(`Refusing an in-place downgrade from ${e.name} to ${t.name}: ${r.join(", ")} would shrink.`)}async function er(e,t,r,n=!0){let[s,i]=await Promise.all([e.getServer(t),e.getServerType(r)]);if(!i)throw Error(`Hetzner server type ${r} was not found.`);let a=s.server_type,c=a.name===i.name;if(!c)Rc(a,i);let f=Ec(s),g=i.locations?.find((h)=>h.name===f);return{serverId:t,serverName:s.name,location:f,currentType:a,targetType:i,capacityAvailable:g?.available!==!1,alreadyComplete:c,upgradeDisk:n}}function Hg(e){if(e instanceof Er&&e.code==="resource_unavailable")return!0;if(e instanceof Rr){if(e.action.error?.code==="resource_unavailable")return!0;if(/no fitting vhost|placement|free resources/i.test(e.action.error?.message??""))return!0}return/resource_unavailable|no fitting vhost|error during placement|free resources/i.test(e instanceof Error?e.message:String(e))}async function He(e,t,r){await e?.onPhase?.(t,r)}async function Un(e,t,r){await e.waitForAction(t.id,{pollIntervalMs:r.actionPollIntervalMs,maxWaitMs:r.actionTimeoutMs})}var xr=async({client:e,hooks:t,actionPollIntervalMs:r,actionTimeoutMs:n,serverPollIntervalMs:s,serverTimeoutMs:i},a,c,f)=>{let g=await e.getServer(a.serverId);if(g.status!=="running"){await He(t,f?"recovering":"powering-on",{serverId:a.serverId});let S=await e.powerOnServer(a.serverId);await Un(e,S,{actionPollIntervalMs:r,actionTimeoutMs:n}),g=await e.waitForServerRunning(a.serverId,{pollIntervalMs:s,maxWaitMs:i})}await He(t,"verifying",{serverId:a.serverId,recovered:f});let h=await t?.afterBoot?.(g,a.targetType,c,{recovered:f});return{server:g,verification:h}};async function li(e){let{client:t,hooks:r}=e,n=e.upgradeDisk??!0;await He(r,"planning",{serverId:e.serverId,targetType:e.targetType});let s=await er(t,e.serverId,e.targetType,n),i=await t.getServer(s.serverId);if(s.alreadyComplete){let f=await xr(e,s,e.manifest,!1);return await He(r,"complete",{alreadyComplete:!0}),{status:"already-complete",plan:s,verification:f.verification}}if(!s.capacityAvailable&&!e.attemptUnavailable)return await He(r,"waiting-capacity",{location:s.location,targetType:s.targetType.name}),{status:"waiting-capacity",plan:s};let a=e.manifest;if(i.status==="off"&&!e.resumeFromOff){let f=await xr(e,s,void 0,!0);return{status:"recovered",plan:s,server:f.server,verification:f.verification,retryable:!0,error:"Server was already off without a resumable resize checkpoint; powered it back on."}}if(i.status==="running"){await He(r,"preflight",{serverId:s.serverId}),a=await r?.preflight?.(i,s.targetType),await He(r,"shutting-down",{serverId:s.serverId});let f=await t.shutdownServer(s.serverId);await Un(t,f,e),i=await t.waitForServerStatus(s.serverId,"off",{pollIntervalMs:e.serverPollIntervalMs,maxWaitMs:e.serverTimeoutMs})}try{await He(r,"resizing",{serverId:s.serverId,from:s.currentType.name,to:s.targetType.name,upgradeDisk:n});let f=await t.changeServerType(s.serverId,s.targetType.name,n);await Un(t,f,e)}catch(f){let g=await xr(e,s,a,!0);return{status:"recovered",plan:s,server:g.server,manifest:a,verification:g.verification,retryable:Hg(f),error:f instanceof Error?f.message:String(f)}}let c=await xr(e,s,a,!1);if(c.verification&&!c.verification.ok)throw Error(`Resize completed but verification failed: ${(c.verification.failures??[]).join("; ")}`);return await He(r,"complete",{serverId:s.serverId,targetType:s.targetType.name}),{status:"completed",plan:s,server:c.server,manifest:a,verification:c.verification}}var Dc=String.raw`
|
|
175
177
|
const { readdir, readFile, readlink, stat } = await import('node:fs/promises')
|
|
176
178
|
|
|
177
179
|
const text = (command) => {
|
|
@@ -263,7 +265,7 @@ console.log(JSON.stringify({
|
|
|
263
265
|
persistentData: persistentData.sort(),
|
|
264
266
|
dataCatalog: dataCatalog.sort(),
|
|
265
267
|
}))
|
|
266
|
-
`;function
|
|
268
|
+
`;function xc(e){return`printf %s ${Buffer.from(e).toString("base64")} | base64 -d | bun -`}async function Ac(e){let t=await Ie(e.host,xc(Dc),e);return JSON.parse(t)}async function Ic(e,t){let r="";for(let n=1;n<=3;n++){let s=Bun.spawn(["curl","--location","--silent","--show-error","--output","/dev/null","--max-time",String(Math.max(1,Math.ceil(t/1000))),"--write-out","%{http_code}",`https://${e}/`],{stdout:"pipe",stderr:"pipe"}),[i,a,c]=await Promise.all([new Response(s.stdout).text(),new Response(s.stderr).text(),s.exited]),f=Number.parseInt(i.trim(),10);if(c===0&&f>0)return{domain:e,ok:f<500,status:f};if(r=a.trim()||`curl exited ${c}`,n<3)await Bun.sleep(500*n)}return{domain:e,ok:!1,error:r}}async function kc(e,t){let r=[],n=0,s=Array.from({length:Math.min(4,e.length)},async()=>{for(;;){let i=n++,a=e[i];if(!a)return;r[i]=await Ic(a,t)}});return await Promise.all(s),r}async function Vc(e){let t=await Ac(e),r=await kc(t.routeDomains,e.routeTimeoutMs??15000);return{...t,routeProbes:r}}async function qc(e){let t=await Vc(e),r=t.routeProbes.filter((n)=>!n.ok);if(t.failedUnits.length>0)throw Error(`Preflight found failed services: ${t.failedUnits.join(", ")}`);if(r.length>0)throw Error(`Preflight found unhealthy routes: ${r.map((n)=>n.domain).join(", ")}`);return await Ie(e.host,String.raw`systemctl list-units --type=service --state=running --no-legend --plain | awk '{print $1}' | while read -r unit; do if systemctl cat "$unit" 2>/dev/null | grep -Eq '/var/www|/usr/local/bin/rpx|/opt/ts-cloud'; then systemctl enable "$unit" >/dev/null 2>&1 || true; fi; done; systemctl daemon-reload; sync`,e),t}function vt(e,t){let r=new Set(t);return e.filter((n)=>!r.has(n))}function Nc(e){return Math.floor((e.memory??0)*1024*1024*1024)}async function Bc(e){await Ie(e.host,String.raw`set -e
|
|
267
269
|
root_source="$(findmnt -n -o SOURCE /)"
|
|
268
270
|
root_fs="$(findmnt -n -o FSTYPE /)"
|
|
269
271
|
parent="$(lsblk -n -o PKNAME "$root_source" | head -1)"
|
|
@@ -275,18 +277,18 @@ case "$root_fs" in
|
|
|
275
277
|
ext2|ext3|ext4) resize2fs "$root_source" ;;
|
|
276
278
|
xfs) xfs_growfs / ;;
|
|
277
279
|
*) echo "Unsupported root filesystem: $root_fs" >&2; exit 1 ;;
|
|
278
|
-
esac`,e)}async function
|
|
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
|
|
280
|
-
`,"utf8"),await
|
|
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(`
|
|
280
|
+
esac`,e)}async function el(e,t){let r=Buffer.from(t.join(`
|
|
281
|
+
`)).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 Bc(e);if(r)await el(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:Nc(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 tl,readFile as rl,rename as nl,writeFile as sl}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 rl(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 tl(yt(r),{recursive:!0});let s=`${n}.${process.pid}.tmp`;await sl(s,`${JSON.stringify(t,null,2)}
|
|
282
|
+
`,"utf8"),await nl(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 pl(e){let t=al("sha256");for await(let r of cl(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(`
|
|
283
|
+
`))}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 pl(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
284
|
`);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
|
-
`),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(!
|
|
285
|
+
`),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(!ll(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=ul(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
286
|
`))}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}:
|
|
285
|
-
${s}`);if(/status:\s*(?:done|degraded)/.test(s))return}catch(s){if(s instanceof Error&&/cloud-init reported an error/.test(s.message))throw s}await this.sleep(t)}throw Error(`Timed out waiting for cloud-init to finish on ${e} after ${r}ms`)}outputsFromState(e,t){return{deployStoragePath:e.deployStoragePath||"/var/ts-cloud/staging",appInstanceId:e.serverId?String(e.serverId):void 0,appPublicIp:t?.public_net.ipv4?.ip||e.publicIp,appPublicIpv6:De(t?.public_net.ipv6?.ip)||e.publicIpv6,sshUser:e.sshUser||this.sshUser,servicesPrivateIp:e.servicesPrivateIp}}static SSH_HOST_KEY_OPTS=["-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR"];static SSH_KEEPALIVE_OPTS=["-o","ConnectTimeout=30","-o","ServerAliveInterval=15","-o","ServerAliveCountMax=4"];sshBaseArgs(e,t=[]){return["-i",this.sshPrivateKeyPath,...Pe.SSH_HOST_KEY_OPTS,...Pe.SSH_KEEPALIVE_OPTS,"-o","BatchMode=yes",...t,`${this.sshUser}@${e}`]}scpToHost(e,t,r){let n=["scp",...Kt,"-i",this.sshPrivateKeyPath,...Pe.SSH_HOST_KEY_OPTS,...Pe.SSH_KEEPALIVE_OPTS,"-o","BatchMode=yes",t,`${this.sshUser}@${e}:${r}`].map((i)=>`"${i.replace(/"/g,"\\\"")}"`).join(" "),s=3;for(let i=1;i<=3;i++)try{ho(n,{stdio:"pipe",maxBuffer:kn});return}catch(a){if(i===3)throw Error(Xt(a))}}sshExec(e,t){try{return
|
|
286
|
-
`);try{let r=Bun.spawn(["bash","-c",t],{stdout:"pipe",stderr:"pipe",env:process.env}),[n,s,i]=await Promise.all([new Response(r.stdout).text(),new Response(r.stderr).text(),r.exited]);return{success:i===0,instanceCount:1,perInstance:[{instanceId:"localhost",status:i===0?"Success":"Failed",output:n,error:s}]}}catch(r){return{success:!1,instanceCount:1,perInstance:[{instanceId:"localhost",status:"Failed",error:r?.message??String(r)}],error:r?.message??String(r)}}}}function no(){let e=process.env.TS_CLOUD_DASHBOARD_BOX;return e!=null&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}import{createHash as
|
|
287
|
+
${s}`);if(/status:\s*(?:done|degraded)/.test(s))return}catch(s){if(s instanceof Error&&/cloud-init reported an error/.test(s.message))throw s}await this.sleep(t)}throw Error(`Timed out waiting for cloud-init to finish on ${e} after ${r}ms`)}outputsFromState(e,t){return{deployStoragePath:e.deployStoragePath||"/var/ts-cloud/staging",appInstanceId:e.serverId?String(e.serverId):void 0,appPublicIp:t?.public_net.ipv4?.ip||e.publicIp,appPublicIpv6:De(t?.public_net.ipv6?.ip)||e.publicIpv6,sshUser:e.sshUser||this.sshUser,servicesPrivateIp:e.servicesPrivateIp}}static SSH_HOST_KEY_OPTS=["-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR"];static SSH_KEEPALIVE_OPTS=["-o","ConnectTimeout=30","-o","ServerAliveInterval=15","-o","ServerAliveCountMax=4"];sshBaseArgs(e,t=[]){return["-i",this.sshPrivateKeyPath,...Pe.SSH_HOST_KEY_OPTS,...Pe.SSH_KEEPALIVE_OPTS,"-o","BatchMode=yes",...t,`${this.sshUser}@${e}`]}scpToHost(e,t,r){let n=["scp",...Kt,"-i",this.sshPrivateKeyPath,...Pe.SSH_HOST_KEY_OPTS,...Pe.SSH_KEEPALIVE_OPTS,"-o","BatchMode=yes",t,`${this.sshUser}@${e}:${r}`].map((i)=>`"${i.replace(/"/g,"\\\"")}"`).join(" "),s=3;for(let i=1;i<=3;i++)try{ho(n,{stdio:"pipe",maxBuffer:kn});return}catch(a){if(i===3)throw Error(Xt(a))}}sshExec(e,t){try{return ol("ssh",[...this.sshBaseArgs(e),Qc],{encoding:"utf8",input:t,stdio:["pipe","pipe","pipe"],maxBuffer:kn})}catch(r){throw Error(`${Xt(r)}${Zn(r,t)}`)}}}class ro{name="ssh";usesCloudFormation=!1;async getComputeOutputs(){return{appPublicIp:"127.0.0.1",sshUser:"root"}}async uploadRelease(e){return{artifactRef:e.localPath}}async findComputeTargets(e){if((e.role||"app")!=="app")return[];return[{id:"localhost",name:"localhost",publicIp:"127.0.0.1",status:"running"}]}async runRemoteDeploy(e){let t=e.commands.join(`
|
|
288
|
+
`);try{let r=Bun.spawn(["bash","-c",t],{stdout:"pipe",stderr:"pipe",env:process.env}),[n,s,i]=await Promise.all([new Response(r.stdout).text(),new Response(r.stderr).text(),r.exited]);return{success:i===0,instanceCount:1,perInstance:[{instanceId:"localhost",status:i===0?"Success":"Failed",output:n,error:s}]}}catch(r){return{success:!1,instanceCount:1,perInstance:[{instanceId:"localhost",status:"Failed",error:r?.message??String(r)}],error:r?.message??String(r)}}}}function no(){let e=process.env.TS_CLOUD_DASHBOARD_BOX;return e!=null&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}import{createHash as Pl,randomUUID as Co}from"node:crypto";import{createReadStream as El}from"node:fs";import{isIP as Rl}from"node:net";import{createHash as dl}from"node:crypto";import{appendFile as ml,mkdir as fl,readFile as gl}from"node:fs/promises";import{dirname as hl}from"node:path";var _o=268435456,vo=async(e,t)=>{let r=Bun.spawn(e,{stdin:t===void 0?"ignore":Buffer.from(t),stdout:"pipe",stderr:"pipe"}),[n,s,i]=await Promise.all([r.exited,new Response(r.stdout).text(),new Response(r.stderr).text()]);return{code:n,signal:r.signalCode,stdout:s.slice(-_o),stderr:i.slice(-_o)}},Gg=["-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR"],Vg=["-o","ConnectTimeout=30","-o","ServerAliveInterval=15","-o","ServerAliveCountMax=4"];function $o(e){if(e.hostKey==="insecure")return[...Gg];return["-o",`StrictHostKeyChecking=${e.hostKey.policy==="pin"?"yes":"accept-new"}`,"-o",`UserKnownHostsFile=${e.hostKey.knownHostsFile}`,"-o","LogLevel=ERROR"]}function yo(e){let t=[...Vg];if(e.connectTimeoutSec!==void 0)t[1]=`ConnectTimeout=${e.connectTimeoutSec}`;return t}function Kc(e,t,r=[]){return["-i",e.identityFile,"-p",String(e.port??22),...$o(e),...yo(e),"-o","BatchMode=yes",...r,`${e.user}@${t}`]}function qg(e,t,r,n){return["-i",e.identityFile,"-P",String(e.port??22),...$o(e),...yo(e),"-o","BatchMode=yes",r,`${e.user}@${t}:${n}`]}function It(e){return`SHA256:${dl("sha256").update(Buffer.from(e,"base64")).digest("base64").replace(/=+$/,"")}`}async function pi(e,t=22,r=vo){let n=await r(["ssh-keyscan","-T","10","-p",String(t),"-t","ed25519",e]),s=n.stdout.split(`
|
|
287
289
|
`).find((i)=>i&&!i.startsWith("#"))?.trim().split(/\s+/);if(n.code!==0||!s?.[1]||!s[2])throw Error(`SSH host-key scan failed: ${n.stderr.trim()||"no key returned"}`);return{algorithm:s[1],key:s[2]}}function Wc(e,t=22){return t===22?e:`[${e}]:${t}`}function jg(e,t,r){return`${Wc(e,t)} ${r.algorithm} ${r.key}`}function zg(e,t,r=22){let n=Wc(t,r);for(let s of e.split(`
|
|
288
|
-
`)){let i=s.trim();if(!i||i.startsWith("#")||i.startsWith("@"))continue;let[a,c,f]=i.split(/\s+/);if(!a||!c||!f)continue;if(a.split(",").includes(n))return{algorithm:c,key:f}}return null}function Jc(e=process.cwd()){return l(e,"ssh","known_hosts")}async function
|
|
289
|
-
`,{mode:384})}class bt{options;run;scan;readKnownHosts;appendKnownHosts;constructor(e,t={}){this.options=e;this.run=t.run??vo,this.scan=t.scan??pi,this.readKnownHosts=t.readKnownHosts??
|
|
290
|
+
`)){let i=s.trim();if(!i||i.startsWith("#")||i.startsWith("@"))continue;let[a,c,f]=i.split(/\s+/);if(!a||!c||!f)continue;if(a.split(",").includes(n))return{algorithm:c,key:f}}return null}function Jc(e=process.cwd()){return l(e,"ssh","known_hosts")}async function Sl(e){try{return await gl(e,"utf8")}catch{return""}}async function _l(e,t){await fl(hl(e),{recursive:!0}),await ml(e,`${t}
|
|
291
|
+
`,{mode:384})}class bt{options;run;scan;readKnownHosts;appendKnownHosts;constructor(e,t={}){this.options=e;this.run=t.run??vo,this.scan=t.scan??pi,this.readKnownHosts=t.readKnownHosts??Sl,this.appendKnownHosts=t.appendKnownHosts??_l}runnerFor(e={}){if(e.sudo!==void 0)return di({sudo:e.sudo});return this.options.runner??di()}async exec(e,t,r={}){let n=await this.run(["ssh",...Kc(this.options,e),this.runnerFor(r)],t);if(n.code!==0){let s={status:n.code,signal:n.signal,stdout:n.stdout,stderr:n.stderr};throw Error(`${Xt(s)}${Zn(s,t)}`)}return n.stdout}async scp(e,t,r){let n=["scp",...Kt,...qg(this.options,e,t,r)],s=3;for(let i=1;i<=3;i++){let a=await this.run(n);if(a.code===0)return;if(i===3)throw Error(Xt({status:a.code,signal:a.signal,stdout:a.stdout,stderr:a.stderr}))}}async probe(e){return(await this.run(["ssh",...Kc(this.options,e,["-o","ConnectTimeout=5"]),"true"])).code===0}async ensureHostKey(e){let t=this.options.port??22;if(this.options.hostKey==="insecure")try{return{fingerprint:It((await this.scan(e,t,this.run)).key),pinnedNow:!1}}catch{return{fingerprint:"",pinnedNow:!1}}let{policy:r,knownHostsFile:n}=this.options.hostKey,s=zg(await this.readKnownHosts(n),e,t);if(s)return{fingerprint:It(s.key),pinnedNow:!1};let i=await this.scan(e,t,this.run);if(r==="pin")return await this.appendKnownHosts(n,jg(e,t,i)),{fingerprint:It(i.key),pinnedNow:!0};return{fingerprint:It(i.key),pinnedNow:!1}}}import{isIP as vl}from"node:net";var ke=1,Xc="/var/lib/ts-cloud";function Kg(e=ke){return`${Xc}/bootstrap.v${e}`}var Wg=1;function $l(e){return e==="aarch64"||e==="arm64"}function bo(e){let t=e.lanIp?.trim()||e.facts?.lanIp?.trim();return t&&vl(t)!==0?t:void 0}function io(e,t,r){if(!xt(e.infrastructure?.compute?.managedServices?.vitess))return;if(t==="raspberry-pi"||$l(r))throw Error(`managedServices.vitess is enabled, but Vitess publishes only x86_64 release tarballs and this host is ${r??"a Raspberry Pi (arm64)"}. Drop managedServices.vitess or deploy it to an x86_64 host.`)}function st(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function yl(){return`
|
|
290
292
|
# A Pi 5 has no battery-backed RTC and boots in 1970 until NTP answers. apt
|
|
291
293
|
# rejects Release files "from the future" and ACME rejects a skewed clock, so
|
|
292
294
|
# wait (bounded) for systemd-timesyncd before anything touches the network
|
|
@@ -302,7 +304,7 @@ if command -v timedatectl >/dev/null 2>&1; then
|
|
|
302
304
|
systemctl start systemd-time-wait-sync >/dev/null 2>&1 || true
|
|
303
305
|
fi
|
|
304
306
|
fi
|
|
305
|
-
`}function
|
|
307
|
+
`}function bl(){return`
|
|
306
308
|
# SD cards wear; a journal allowed to grow to the default 10% of the disk is
|
|
307
309
|
# the single biggest writer on an idle Pi. Bound it.
|
|
308
310
|
install -d -m 0755 /etc/systemd/journald.conf.d
|
|
@@ -313,11 +315,11 @@ MaxRetentionSec=7day
|
|
|
313
315
|
Compress=yes
|
|
314
316
|
TS_CLOUD_JOURNAL_EOF
|
|
315
317
|
systemctl restart systemd-journald
|
|
316
|
-
`}function
|
|
318
|
+
`}function Tl(e){return`
|
|
317
319
|
# The deploy user uploads releases as itself (scp), while the scripts run as
|
|
318
320
|
# root through sudo. setgid group-writable directories let both write.
|
|
319
321
|
install -d -m 2775 -g "$(id -gn ${st(e)})" /var/ts-cloud/artifacts /var/ts-cloud/staging
|
|
320
|
-
`}function
|
|
322
|
+
`}function wl(e){let t=st(e),r=`/home/${e}`;return[`chown -R ${t}:"$(id -gn ${t})" ${st(`${r}/.ssh`)}`,`chmod 700 ${st(`${r}/.ssh`)}`]}function mi(e){let{config:t,environment:r,profile:n,sudoUser:s}=e;io(t,n,e.facts?.arch);let i={...t.infrastructure?.compute,proxy:w(t,{environment:e.environment,environmentType:e.environment})},a=t.sites??{},c=t.project.slug,f=e.lan?{...e.lan.hostname?{hostname:e.lan.hostname}:{},tls:e.lan.tls??"local-ca",...bo(e)?{ip:bo(e)}:{}}:void 0,g=i.proxy?.engine==="rpx"?B(a,{proxy:i.proxy,slug:c,lan:f,mail:C(t,{environment:e.environment,environmentType:e.environment})}):void 0,h=i.proxy?.engine==="rpx"&&g?G({proxy:i.proxy,config:g,slug:c,profile:n,bunBin:i.runtime==="node"||i.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,S=i.proxy?.engine==="rpx"&&g?Ne({config:g,slug:c}):void 0,_=s?`/home/${s}/.ssh/authorized_keys`:void 0,v=Qe(t,{environment:r,authorizedKeysPath:_}),y=s?[...v.servicesProvision??[],...wl(s)]:v.servicesProvision,T=[...new Set([...i.systemPackages??[],"psmisc","ca-certificates"])],x=i.swapGb??(n==="raspberry-pi"?Wg:void 0),q=M({runtime:v.runtime,runtimeVersion:v.runtimeVersion,systemPackages:T,database:t.infrastructure?.database,phpProvision:v.phpProvision,servicesProvision:y,rpxProvision:h,swapGb:x}).replace(/^#!\/bin\/bash\nset -euo pipefail\n/,""),H=Kg(),R=g?.localCa?` lan=${g.localCa.hosts.join(",")} tls=local-ca`:f?` lan=${f.hostname??`${c}.local`} tls=${f.tls??"local-ca"}`:"",L=`#!/bin/bash
|
|
321
323
|
set -euo pipefail
|
|
322
324
|
# ts-cloud ssh bootstrap v${ke} profile=${n}${R}
|
|
323
325
|
|
|
@@ -331,7 +333,7 @@ if [ -e ${st(H)} ]; then
|
|
|
331
333
|
`)}
|
|
332
334
|
`}if(L+=` exit 0
|
|
333
335
|
fi
|
|
334
|
-
`,L
|
|
336
|
+
`,L+=yl(),n==="raspberry-pi")L+=bl();if(s)L+=Tl(s);if(L+=`
|
|
335
337
|
${q}`,L+=`
|
|
336
338
|
install -d -m 0755 ${st(Xc)}
|
|
337
339
|
date -u +%Y-%m-%dT%H:%M:%SZ > ${st(H)}
|
|
@@ -371,21 +373,21 @@ printf '"privilege":"%s"' "$(sudo -n true >/dev/null 2>&1 && printf sudo || prin
|
|
|
371
373
|
printf '}\\n'
|
|
372
374
|
`;function Ai(e){let t=e.split(`
|
|
373
375
|
`).map((r)=>r.trim()).filter(Boolean).at(-1);if(!t||!t.startsWith("{"))throw Error(`Preflight returned no facts:
|
|
374
|
-
${e.trim().slice(-2000)}`);try{return JSON.parse(t)}catch(r){throw Error(`Preflight returned malformed facts: ${r.message}`)}}var Tt=1073741824;function
|
|
376
|
+
${e.trim().slice(-2000)}`);try{return JSON.parse(t)}catch(r){throw Error(`Preflight returned malformed facts: ${r.message}`)}}var Tt=1073741824;function Cl(e){return e==="aarch64"||e==="arm64"}function yi(e,t){let r=[],n=e.arch??"";if(!Cl(n)&&!(n==="x86_64"&&t.profile==="generic"))r.push({code:"arch.not-aarch64",severity:"error",message:t.profile==="raspberry-pi"?`The raspberry-pi profile expects a 64-bit ARM OS; this host reports ${n||"an unknown architecture"}.`:`Unsupported architecture ${n||"(unknown)"}.`,remediation:t.profile==="raspberry-pi"?"Flash the 64-bit Raspberry Pi OS or Ubuntu Server arm64 image.":"Use an x86_64 or arm64 Linux host."});let s=`${e.osId??""} ${e.osIdLike??""}`.toLowerCase();if(!/\b(?:debian|ubuntu|raspbian)\b/.test(s))r.push({code:"os.unsupported",severity:"error",message:`The bootstrap targets Debian and Ubuntu (apt); this host reports ${e.os||"an unknown OS"}.`,remediation:"Install Raspberry Pi OS, Debian or Ubuntu Server."});let i=e.memoryBytes??0;if(i<Tt)r.push({code:"memory.low",severity:"error",message:`${(i/Tt).toFixed(2)} GiB of memory; the runtime plus a gateway needs at least 1 GiB.`,remediation:"Use a host with 2 GiB or more."});else if(i<2*Tt)r.push({code:"memory.low",severity:"warning",message:`${(i/Tt).toFixed(2)} GiB of memory; on-box builds and managed services will be tight.`,remediation:"Build releases in CI rather than on the host, and keep managedServices small."});if((e.diskFreeBytes??0)<4*Tt)r.push({code:"disk.low",severity:"error",message:`${((e.diskFreeBytes??0)/Tt).toFixed(1)} GiB free on /; releases, the artifact cache and swap need at least 4 GiB.`,remediation:"Free space or use a larger card or disk."});if(t.user!=="root"&&!e.sudoOk)r.push({code:"sudo.missing",severity:"error",message:`${t.user} cannot run sudo without a password, and the bootstrap needs root.`,remediation:`Add '${t.user} ALL=(ALL) NOPASSWD:ALL' to /etc/sudoers.d/ts-cloud, or deploy as root.`});if(!e.timeSynced)r.push({code:"time.unsynced",severity:"warning",message:"The clock is not NTP-synchronised yet; the bootstrap waits for it before running apt.",remediation:"Nothing to do unless it never syncs: then check the network and systemd-timesyncd."});if(!e.httpsOk)r.push({code:"https.blocked",severity:"error",message:"The host cannot reach https://github.com, so it cannot download the runtime or packages.",remediation:"Check DNS, the default route and any egress firewall from the host."});if(e.cloudInitPresent&&/running/i.test(e.cloudInitStatus??""))r.push({code:"cloud-init.running",severity:"info",message:"cloud-init is still running its first boot; the adopt waits for it to finish."});if(e.piModel)r.push({code:"pi.model",severity:"info",message:e.piModel});if(e.kernelBits===32)r.push({code:"bits.32",severity:"error",message:"This is a 32-bit userland; bun ships no 32-bit build.",remediation:"Flash a 64-bit OS image."});return r}function Si(e){return e.some((t)=>t.severity==="error")}function Ii(e){if(e.length===0)return"No findings.";let t=Math.max(...e.map((r)=>r.code.length));return e.map((r)=>{let n=`${r.severity.padEnd(7)} ${r.code.padEnd(t)} ${r.message}`;return r.remediation?`${n}
|
|
375
377
|
${" ".repeat(t+10)}${r.remediation}`:n}).join(`
|
|
376
|
-
`)}var bi="/var/ts-cloud/staging",Hn=Fr,sp="TS_CLOUD_SSH_SKIP_BOOTSTRAP",
|
|
378
|
+
`)}var bi="/var/ts-cloud/staging",Hn=Fr,sp="TS_CLOUD_SSH_SKIP_BOOTSTRAP",Ol=["size","instances","appServers","servicesServer","loadBalancer","fleet","image","bakedImage","allowSsh"];function Wt(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function Dl(e){let t=Pl("sha256");for await(let r of El(e))t.update(r);return t.digest("hex")}function op(e,t){if(e.cloud?.attachTo)throw Error("cloud.attachTo is not supported by the ssh provider: it deploys to the hosts in ssh.hosts and nothing else.");if(t.hosts.length>1)throw Error(`ssh.hosts lists ${t.hosts.length} hosts; multi-host ssh fleets are not supported yet.`);if(xt(e.infrastructure?.compute?.managedServices?.vitess))io(e,t.profile);let r=e.infrastructure?.compute??{};return Ol.filter((n)=>r[n]!==void 0).map((n)=>`infrastructure.compute.${n} has no effect with the ssh provider; the host is what it is.`)}class Gr{name="ssh";usesCloudFormation=!1;settings;cwd;bootWait;transportInstance;constructor(e={}){this.settings=fi(void 0,{hosts:e.hosts,user:e.user,port:e.port,privateKeyPath:e.privateKeyPath,hostKey:e.hostKey,sudo:e.sudo,profile:e.profile,publicIp:e.publicIp,lan:e.lan}),this.cwd=e.cwd??process.cwd(),this.transportInstance=e.transport,this.bootWait={sshIntervalMs:e.bootWait?.sshIntervalMs??5000,sshTimeoutMs:e.bootWait?.sshTimeoutMs??300000,cloudInitIntervalMs:e.bootWait?.cloudInitIntervalMs??5000,cloudInitTimeoutMs:e.bootWait?.cloudInitTimeoutMs??600000}}get host(){if(this.settings.hosts.length>1)throw Error(`ssh.hosts lists ${this.settings.hosts.length} hosts; multi-host ssh fleets are not supported yet.`);return this.settings.hosts[0]}get transport(){if(!this.transportInstance){let e=this.host;this.transportInstance=new bt({user:e.user,port:e.port,identityFile:e.privateKeyPath,hostKey:this.settings.hostKey==="insecure"?"insecure":{policy:this.settings.hostKey,knownHostsFile:Jc(this.cwd)}})}return this.transportInstance}exec(e,t){return this.transport.exec(e,t,{sudo:this.settings.sudo})}async findComputeTargets(e){if((e.role||"app")!=="app")return[];let{host:t}=this.host;return[{id:t,name:t,publicIp:t,status:"running"}]}async getComputeOutputs(){let{host:e,user:t}=this.host;return{appInstanceId:e,appPublicIp:e,sshUser:t,deployStoragePath:bi}}async uploadRelease(e){let t=e.targets?.length?e.targets:await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:m(e.config,e.environment)});if(t.length===0)throw Error("No ssh compute targets found for release upload");let n=`${e.remoteKey.replace(/^releases\//,"").replace(/\.tar\.gz$/,"").replace(/\//g,"-")}-${Co()}.tar.gz`,s=`${bi}/${n}`,i=await Dl(e.localPath),a=`${Hn}/${i}.tar.gz`;for(let c of t){if(!c.publicIp)throw Error(`Target ${c.id} has no address for SCP upload`);let f=["set -euo pipefail",`mkdir -p ${Wt(Hn)} ${Wt(bi)}`,`test -s ${Wt(a)}`,`cp -- ${Wt(a)} ${Wt(s)}`].join(`
|
|
377
379
|
`);try{await this.exec(c.publicIp,f);continue}catch{}let g=`${Hn}/.${i}-${Co()}.tmp`;try{await this.transport.scp(c.publicIp,e.localPath,g),await this.exec(c.publicIp,Tr(g,a,s))}catch(h){throw await this.exec(c.publicIp,wr(g)).catch(()=>{}),h}}return{artifactRef:s}}async runRemoteDeploy(e){if(e.targets.length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets provided"};let t=e.commands.join(`
|
|
378
380
|
`),r=[];for(let s of e.targets){if(!s.publicIp){r.push({instanceId:s.id,status:"Failed",error:"Missing address"});continue}try{let i=await this.exec(s.publicIp,t);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")}}targetHost(){return this.host.host}ensureHostKey(e=this.host.host){return this.transport.ensureHostKey(e)}async preflight(e=this.host.host){let t=await this.transport.exec(e,hi,{sudo:!1}),r=Ai(t);return{facts:r,findings:yi(r,{user:this.host.user,profile:this.settings.profile})}}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e;for(let y of op(t,this.settings))console.warn(`[ts-cloud] ${y}`);let n=this.host,s=m(t,r),i=await ze(s,this.cwd),a=process.env[sp]==="1"&&i?.provider==="ssh"&&i.host===n.host&&i.bootstrapVersion===ke,c=await this.ensureHostKey(n.host);if(c.pinnedNow)console.warn(`[ts-cloud] pinned ${n.host} host key ${c.fingerprint}`);await this.waitForSshReady(n.host);let{facts:f,findings:g}=await this.preflight(n.host);if(Si(g))throw Error(`Preflight failed for ${n.host}; refusing to bootstrap it.
|
|
379
|
-
${Ii(g)}`);for(let y of g)console.warn(`[ts-cloud] ${y.severity}: ${y.message}`);if(f.cloudInitPresent&&/running/i.test(f.cloudInitStatus??""))await this.waitForCloudInit(n.host);let h=f.lanIp?.trim()||(
|
|
380
|
-
${s}`);if(/status:\s*(?:done|degraded)/.test(s))return}catch(s){if(s instanceof Error&&/cloud-init reported an error/.test(s.message))throw s}await this.sleep(t)}throw Error(`Timed out waiting for cloud-init to finish on ${e} after ${r}ms`)}}function F(e){let t=e.provider??ce(e.config);if(e.config.cloud?.residency&&(no()||t!=="hetzner"))throw Error("Residency policy requires a Hetzner host with live provider evidence");if(no())return new ro;switch(e.provider??ce(e.config)){case"aws":return new $r({region:e.config.project.region});case"hetzner":return new Pe({apiToken:e.config.hetzner?.apiToken,allowStateOnly:Boolean(e.config.cloud?.attachTo),sshPrivateKeyPath:e.config.hetzner?.sshPrivateKeyPath,sshPublicKeyPath:e.config.hetzner?.sshPublicKeyPath,sshUser:e.config.hetzner?.sshUser,location:e.config.hetzner?.location,residency:e.config.cloud?.residency});case"ssh":return new Gr({hosts:e.config.ssh?.hosts,hostKey:e.config.ssh?.hostKey,sudo:e.config.ssh?.sudo,profile:e.config.ssh?.profile,publicIp:e.config.ssh?.publicIp,lan:e.config.ssh?.lan});case"fly":throw Error("Fly.io has no box to provision or reach over SSH: deploy it with deployToFly() from @stacksjs/ts-cloud.");default:throw Error(`Unknown cloud provider: ${e.provider??ce(e.config)}`)}}class so{drivers=new Map;getDriver(e,t){let r=t??ce(e),n=`${r}:${e.project.slug}:${e.project.region||"default"}:${JSON.stringify(e.cloud?.residency||null)}`,s=this.drivers.get(n);if(s)return s;let i=F({config:e,provider:r});return this.drivers.set(n,i),i}}var ap=new so;var cp="/var/lib/ts-cloud/bootstrap.sh",dp={"raspberry-pi-os":"bootfs",ubuntu:"system-boot"},
|
|
381
|
-
`)||!/^(?:ssh|ecdsa|sk)-/.test(t))throw Error("publicKey must be one public key line, e.g. the contents of ~/.ssh/id_ed25519.pub.");if(e.wifi){if(!e.wifi.ssid)throw Error("wifi.ssid is required.");if(!e.wifi.passphrase)throw Error("wifi.passphrase is required.");if(!
|
|
381
|
+
${Ii(g)}`);for(let y of g)console.warn(`[ts-cloud] ${y.severity}: ${y.message}`);if(f.cloudInitPresent&&/running/i.test(f.cloudInitStatus??""))await this.waitForCloudInit(n.host);let h=f.lanIp?.trim()||(Rl(n.host)!==0?n.host:void 0),S=i?.provider==="ssh"?i.bootstrappedAt:void 0;if(!a){let y=mi({config:t,environment:r,profile:this.settings.profile,facts:f,sudoUser:n.user!=="root"?n.user:void 0,lan:this.settings.lan,lanIp:h});Or(await this.exec(n.host,y)),S=new Date().toISOString()}let _={provider:"ssh",stackName:s,host:n.host,sshUser:n.user,sshPort:n.port,hostKeyFingerprint:c.fingerprint||void 0,publicIp:this.settings.publicIp==="auto"?void 0:this.settings.publicIp,lanIp:f.lanIp||void 0,deployStoragePath:bi,profile:this.settings.profile,bootstrapVersion:ke,bootstrappedAt:S};await St(s,_,this.cwd);let v=await this.getComputeOutputs();if(j(t.infrastructure?.compute)&&dd(this.settings.lan)==="local-ca")v.lanCaCertPath=po(),console.warn(`[ts-cloud] LAN certificate authority on ${n.host} at ${v.lanCaCertPath}. Fetch it with: scp ${n.user}@${n.host}:${v.lanCaCertPath} ./rpx-root-ca.crt`);return v}async destroyCompute(e){let t=m(e.config,e.environment),r=this.host;return console.warn(`[ts-cloud] forgot ${r.host} for ${t}; nothing was removed on the host (stop the systemd units and remove /var/ts-cloud and /etc/rpx by hand if you want it clean).`),await St(t,{provider:"ssh",stackName:t,host:r.host,sshUser:r.user,sshPort:r.port},this.cwd).catch(()=>{}),{destroyed:[`local state for ${t}`]}}async sleep(e){await new Promise((t)=>setTimeout(t,e))}async waitForSshReady(e){let{sshIntervalMs:t,sshTimeoutMs:r}=this.bootWait,n=Date.now();do{if(await this.transport.probe(e))return;await this.sleep(t)}while(Date.now()-n<r);throw Error(`Timed out waiting for SSH on ${e} after ${r}ms`)}async waitForCloudInit(e){let{cloudInitIntervalMs:t,cloudInitTimeoutMs:r}=this.bootWait,n=Date.now();while(Date.now()-n<r){try{let s=await this.transport.exec(e,"if command -v cloud-init >/dev/null 2>&1; then cloud-init status --long 2>/dev/null || true; else echo 'status: done'; fi",{sudo:!1});if(/status:\s*error/.test(s))throw Error(`cloud-init reported an error on ${e}:
|
|
382
|
+
${s}`);if(/status:\s*(?:done|degraded)/.test(s))return}catch(s){if(s instanceof Error&&/cloud-init reported an error/.test(s.message))throw s}await this.sleep(t)}throw Error(`Timed out waiting for cloud-init to finish on ${e} after ${r}ms`)}}function F(e){let t=e.provider??ce(e.config);if(e.config.cloud?.residency&&(no()||t!=="hetzner"))throw Error("Residency policy requires a Hetzner host with live provider evidence");if(no())return new ro;switch(e.provider??ce(e.config)){case"aws":return new $r({region:e.config.project.region});case"hetzner":return new Pe({apiToken:e.config.hetzner?.apiToken,allowStateOnly:Boolean(e.config.cloud?.attachTo),sshPrivateKeyPath:e.config.hetzner?.sshPrivateKeyPath,sshPublicKeyPath:e.config.hetzner?.sshPublicKeyPath,sshUser:e.config.hetzner?.sshUser,location:e.config.hetzner?.location,residency:e.config.cloud?.residency});case"ssh":return new Gr({hosts:e.config.ssh?.hosts,hostKey:e.config.ssh?.hostKey,sudo:e.config.ssh?.sudo,profile:e.config.ssh?.profile,publicIp:e.config.ssh?.publicIp,lan:e.config.ssh?.lan});case"fly":throw Error("Fly.io has no box to provision or reach over SSH: deploy it with deployToFly() from @stacksjs/ts-cloud.");default:throw Error(`Unknown cloud provider: ${e.provider??ce(e.config)}`)}}class so{drivers=new Map;getDriver(e,t){let r=t??ce(e),n=`${r}:${e.project.slug}:${e.project.region||"default"}:${JSON.stringify(e.cloud?.residency||null)}`,s=this.drivers.get(n);if(s)return s;let i=F({config:e,provider:r});return this.drivers.set(n,i),i}}var ap=new so;var cp="/var/lib/ts-cloud/bootstrap.sh",dp={"raspberry-pi-os":"bootfs",ubuntu:"system-boot"},xl=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,Al=/^[a-z_][a-z0-9_-]{0,31}$/,Il=/^[A-Z]{2}$/;function Te(e){return JSON.stringify(e)}function Ll(e){if(!xl.test(e.hostname))throw Error(`Invalid hostname '${e.hostname}': use lowercase letters, digits and hyphens.`);if(!Al.test(e.user))throw Error(`Invalid user '${e.user}': use a lowercase Unix user name.`);let t=e.publicKey.trim();if(!t||t.includes(`
|
|
383
|
+
`)||!/^(?:ssh|ecdsa|sk)-/.test(t))throw Error("publicKey must be one public key line, e.g. the contents of ~/.ssh/id_ed25519.pub.");if(e.wifi){if(!e.wifi.ssid)throw Error("wifi.ssid is required.");if(!e.wifi.passphrase)throw Error("wifi.passphrase is required.");if(!Il.test(e.wifi.country))throw Error(`wifi.country must be a two-letter regulatory domain such as DE or US, not '${e.wifi.country}'.`)}}function Ul(e,t){let r=[`hostname: ${Te(e.hostname)}`,"manage_etc_hosts: true","users:",` - name: ${Te(e.user)}`," ssh_authorized_keys:",` - ${Te(e.publicKey.trim())}`,` sudo: ${Te("ALL=(ALL) NOPASSWD:ALL")}`," shell: /bin/bash"," lock_passwd: true","ssh_pwauth: false"];if(e.timezone)r.push(`timezone: ${Te(e.timezone)}`);if(e.locale)r.push(`locale: ${Te(e.locale)}`);if(r.push("package_update: true"),t==="raspberry-pi-os")r.push("rpi:"," enable_ssh: true"," interfaces:"," spi: false"," i2c: false"," onewire: false"," remote_gpio: false"," serial:"," console: false"," hardware: false");return`${r.join(`
|
|
382
384
|
`)}
|
|
383
|
-
`}function
|
|
385
|
+
`}function kl(e){let t=["version: 2","ethernets:"," eth0:"," match:",` name: ${Te("e*")}`," dhcp4: true"," dhcp6: true"," optional: true"];if(e.wifi)t.push("wifis:"," wlan0:"," dhcp4: true"," dhcp6: true"," optional: true",` regulatory-domain: ${Te(e.wifi.country)}`," access-points:",` ${Te(e.wifi.ssid)}:`,` password: ${Te(e.wifi.passphrase)}`);return`${t.join(`
|
|
384
386
|
`)}
|
|
385
|
-
`}function
|
|
387
|
+
`}function Hl(e){return[`instance-id: ${Te(`ts-cloud-${e.hostname}`)}`,`local-hostname: ${Te(e.hostname)}`].join(`
|
|
386
388
|
`)+`
|
|
387
|
-
`}function
|
|
388
|
-
`)}function Yc(e,t,r){
|
|
389
|
+
`}function Nl(e,t){return[`Copy user-data, network-config and meta-data onto the boot partition of the flashed card (the volume named '${dp[t]}'), replacing the files already there.`,"Eject the card, put it in the board and power it on.","The first boot takes a few minutes: cloud-init creates the user, waits for the clock to sync, then runs the ts-cloud bootstrap (packages, runtime, gateway).",`Then, from this machine: cloud ssh:preflight ${e.hostname}.local --user ${e.user}`,"When the preflight is clean, cloud deploy adopts the host and ships the sites."].join(`
|
|
390
|
+
`)}function Yc(e,t,r){Ll(e);let n={scriptPath:cp,permissions:"0700",before:Ul(e,r.os)};return{files:{"user-data":se(t,n),"network-config":kl(e),"meta-data":Hl(e)},instructions:Nl(e,r.os)}}function Po(e){return e.infrastructure?.compute??{}}function lp(e){let t=Po(e),r=t.monitoring;return{firewallPorts:[...new Set([22,80,443,...t.firewall?.allowedPorts??[]])].filter((s)=>Number.isInteger(s)&&s>=1&&s<=65535).sort((s,i)=>s-i),monitoring:r!==!1&&(typeof r!=="object"||r.enabled!==!1),autoUpdates:t.autoUpdates!==!1,swapGb:Math.max(0,Math.floor(t.swapGb??2)),sshPasswordAuthentication:!1,sshMaxStartups:"100:30:200",journalMaxUse:"256M",journalRetention:"14day"}}function Ml(e){return["install -d -m 0755 /etc/ssh/sshd_config.d /etc/systemd/journald.conf.d /etc/sysctl.d /etc/fail2ban/jail.d","cat > /etc/ssh/sshd_config.d/99-ts-cloud-hardening.conf <<'TS_CLOUD_SSH_EOF'","# Managed by ts-cloud host optimization.","PasswordAuthentication no","KbdInteractiveAuthentication no","PermitRootLogin prohibit-password","MaxAuthTries 4","LoginGraceTime 30",`MaxStartups ${e.sshMaxStartups}`,"TS_CLOUD_SSH_EOF","sshd -t","systemctl reload ssh","cat > /etc/systemd/journald.conf.d/99-ts-cloud-retention.conf <<'TS_CLOUD_JOURNAL_EOF'","[Journal]",`SystemMaxUse=${e.journalMaxUse}`,`MaxRetentionSec=${e.journalRetention}`,"Compress=yes","TS_CLOUD_JOURNAL_EOF","systemctl restart systemd-journald","journalctl --vacuum-size=256M --vacuum-time=14d >/dev/null","cat > /etc/sysctl.d/99-ts-cloud-production.conf <<'TS_CLOUD_SYSCTL_EOF'","# Managed by ts-cloud host optimization.","vm.swappiness=10","vm.dirty_background_ratio=5","vm.dirty_ratio=15","net.core.somaxconn=4096","net.ipv4.tcp_max_syn_backlog=4096","net.ipv4.tcp_fin_timeout=30","net.ipv4.tcp_keepalive_time=300","net.ipv4.tcp_keepalive_intvl=30","net.ipv4.tcp_keepalive_probes=5","fs.inotify.max_user_watches=524288","TS_CLOUD_SYSCTL_EOF","sysctl --system >/dev/null","export DEBIAN_FRONTEND=noninteractive","command -v fail2ban-client >/dev/null 2>&1 || apt-get install -y fail2ban","cat > /etc/fail2ban/jail.d/99-ts-cloud-sshd.conf <<'TS_CLOUD_FAIL2BAN_EOF'","[sshd]","enabled = true","backend = systemd","bantime = 1h","findtime = 10m","maxretry = 5","TS_CLOUD_FAIL2BAN_EOF","systemctl enable --now fail2ban","systemctl restart fail2ban"]}function Fl(e){if(e===0)return[];return["if ! swapon --show=NAME --noheadings 2>/dev/null | grep -qx '/swapfile'; then",` if [ ! -f /swapfile ]; then fallocate -l ${e}G /swapfile || dd if=/dev/zero of=/swapfile bs=1M count=${e*1024} status=none; fi`," chmod 600 /swapfile"," mkswap /swapfile >/dev/null"," swapon /swapfile","fi","grep -qE '^/swapfile\\s' /etc/fstab || echo '/swapfile none swap sw 0 0' >> /etc/fstab"]}function up(e){let t=Po(e),r=lp(e),n=t.monitoring??!0,s=t.firewall??{enabled:!0};return["set -euo pipefail",...j(t)?["systemctl disable --now nginx.service bun-gateway.service ts-cloud-nginx.service 2>/dev/null || true","systemctl reset-failed nginx.service bun-gateway.service ts-cloud-nginx.service 2>/dev/null || true"]:[],...Fl(r.swapGb),...Me(r.autoUpdates),...Le(n),...Ml(r),...lr(s),"systemctl daemon-reload","systemctl reset-failed"]}var zl=String.raw`
|
|
389
391
|
const text = (command) => {
|
|
390
392
|
const result = Bun.spawnSync(['bash', '-lc', command], { stdout: 'pipe', stderr: 'pipe' })
|
|
391
393
|
return result.stdout.toString().trim()
|
|
@@ -416,39 +418,39 @@ console.log(JSON.stringify({
|
|
|
416
418
|
failedUnits: lines("systemctl --failed --type=service --no-legend --plain | awk '{print $1}'"),
|
|
417
419
|
publicTcpPorts: [...new Set(publicTcpPorts)].sort((a, b) => a - b),
|
|
418
420
|
}))
|
|
419
|
-
`;function
|
|
420
|
-
`),n=`printf %s ${Buffer.from(r).toString("base64")} | base64 -d | bash`;await Ie(t.host,n,t)}async function jh(e){let t=await Ie(e.host,zl
|
|
421
|
-
`,"utf8"),await Eo(r,t)}async function Jh(e,t=1800000){let r=gp(e);await Ar(yt(),{recursive:!0});try{await Ar(r)}catch(n){if(Date.now()-(await
|
|
422
|
-
`,"utf8"),async()=>{await
|
|
421
|
+
`;function Bl(e){return`printf %s ${Buffer.from(e).toString("base64")} | base64 -d | bun -`}async function qh(e,t){let r=up(e).join(`
|
|
422
|
+
`),n=`printf %s ${Buffer.from(r).toString("base64")} | base64 -d | bash`;await Ie(t.host,n,t)}async function jh(e){let t=await Ie(e.host,Bl(zl),e);return JSON.parse(t)}function zh(e,t){let r=[],n=new Set(t.firewallPorts),s=e.firewallPorts.filter((a)=>!n.has(a)),i=t.firewallPorts.filter((a)=>!e.firewallPorts.includes(a));if(!t.firewallActive)r.push("UFW is not active");if(s.length>0)r.push(`UFW is missing ports: ${s.join(", ")}`);if(i.length>0)r.push(`UFW has unexpected ports: ${i.join(", ")}`);if(t.passwordAuthentication)r.push("SSH password authentication remains enabled");if(t.rootPasswordLogin)r.push("SSH root password login remains enabled");if(!t.fail2banActive)r.push("fail2ban is not active");if(e.autoUpdates&&!t.unattendedUpgradesActive)r.push("unattended upgrades are not active");if(e.monitoring&&!t.metricsTimerActive)r.push("metrics timer is not active");if(e.monitoring&&!t.metricsSnapshotFresh)r.push("metrics snapshot is stale");if(e.swapGb>0&&t.swapBytes<e.swapGb*1073741824*0.9)r.push("configured swap is missing");if(t.failedUnits.length>0)r.push(`failed services: ${t.failedUnits.join(", ")}`);return r}import{mkdir as Ar,readFile as Kl,rename as Eo,rmdir as jl,stat as Gl,unlink as Vl,writeFile as Ro}from"node:fs/promises";import{join as Ir}from"node:path";function Zc(e){return Ir(yt(),`${e}-resize.json`)}function gp(e){return Ir(yt(),`${e}-resize.lock`)}async function Kh(e){try{return JSON.parse(await Kl(Zc(e),"utf8"))}catch{return null}}async function Wh(e){let t=Zc(e.stackName);await Ar(yt(),{recursive:!0});let r=`${t}.${process.pid}.tmp`;await Ro(r,`${JSON.stringify(e,null,2)}
|
|
423
|
+
`,"utf8"),await Eo(r,t)}async function Jh(e,t=1800000){let r=gp(e);await Ar(yt(),{recursive:!0});try{await Ar(r)}catch(n){if(Date.now()-(await Gl(r)).mtimeMs<=t)throw Error(`Another resize process holds ${r}.`);await Eo(r,`${r}.stale-${Date.now()}`),await Ar(r)}return await Ro(Ir(r,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
|
|
424
|
+
`,"utf8"),async()=>{await Vl(Ir(r,"owner.json")).catch(()=>{}),await jl(r).catch(()=>{})}}async function Ci(e,t){let r=qe(t.publicKey),n=(await e.listSshKeys()).find((i)=>qe(i.public_key)===r);if(n)return{id:n.id,name:n.name,created:!1};let s=await e.createSshKey({name:t.name,publicKey:t.publicKey.trim(),labels:t.labels});return{id:s.id,name:s.name,created:!0}}async function Ei(e,t){let r=(await e.listFirewalls()).find((s)=>s.name===t.name);if(r)return await e.setFirewallRules(r.id,t.rules),{id:r.id,name:r.name,created:!1};let{firewall:n}=await e.createFirewall({name:t.name,rules:t.rules,labels:t.labels});return{id:n.id,name:n.name,created:!0}}async function vi(e,t){let{waitForRunning:r=!0,...n}=t,s=(await e.listServers()).find((a)=>a.name===t.name),i=!s;if(!s)s=(await e.createServer(n)).server;if(r)s=await e.waitForServerRunning(s.id);return{server:s,created:i}}function Ti(e){let t=e.public_net.ipv4?.ip;if(!t)throw Error(`Hetzner server "${e.name}" (#${e.id}) has no public IPv4`);return t}var ed="/aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id";function td(e){let t=e.sshPublicKey.trim(),r=["#cloud-config","disable_root: false","ssh_authorized_keys:",` - ${t}`];if(e.bootstrapScript){let s=e.bootstrapScript.split(`
|
|
423
425
|
`).map((i)=>` ${i}`).join(`
|
|
424
426
|
`);r.push("write_files:"," - path: /var/lib/cloud/box-bootstrap.sh"," permissions: '0755'"," owner: root:root"," content: |",s)}if(r.push("runcmd:",` - mkdir -p /root/.ssh && grep -qF "${t}" /root/.ssh/authorized_keys 2>/dev/null || echo "${t}" >> /root/.ssh/authorized_keys`),e.bootstrapScript)r.push(" - [ bash, /var/lib/cloud/box-bootstrap.sh ]");return`${r.join(`
|
|
425
427
|
`)}
|
|
426
|
-
`}function
|
|
427
|
-
`)}function xo(e){let t=Do(e),r=e.packages??[];return Object.entries(
|
|
428
|
+
`}function ql(e=[]){let t=[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"],description:"SSH"}];for(let r of e)t.push({direction:"in",protocol:r.protocol,...r.protocol==="icmp"?{}:{port:String(r.port)},source_ips:["0.0.0.0/0","::/0"]});return t}class wi{client;provider="hetzner";constructor(e){this.client=e}async ensureBox(e){let t=await Ci(this.client,{name:`${e.name}-key`,publicKey:e.sshPublicKey}),r=await Ei(this.client,{name:`${e.name}-fw`,rules:ql(e.ports)}),{server:n,created:s}=await vi(this.client,{name:e.name,serverType:e.size,image:e.image??"ubuntu-24.04",location:e.location,sshKeys:[t.id],firewalls:[{firewall:r.id}],userData:td(e),labels:e.labels});if(!s){if(!((await this.client.listFirewalls()).find((c)=>c.id===r.id)?.applied_to??[]).some((c)=>c.type==="server"&&c.server?.id===n.id)){let c=await this.client.applyFirewallToResources(r.id,[{type:"server",server:n.id}]);for(let f of c)await this.client.waitForAction(f.id).catch(()=>{})}}return{provider:"hetzner",id:String(n.id),name:n.name,publicIp:Ti(n),created:s}}async destroyBox(e){let t=[],r=(await this.client.listServers()).find((s)=>s.name===e);if(r){let s=await this.client.deleteServer(r.id);await this.client.waitForAction(s.id).catch(()=>{}),t.push(`server ${e} (#${r.id})`)}let n=(await this.client.listFirewalls()).find((s)=>s.name===`${e}-fw`);if(n)for(let s=0;s<10;s++)try{await this.client.deleteFirewall(n.id),t.push(`firewall ${e}-fw (#${n.id})`);break}catch{if(s===9)break;await new Promise((i)=>setTimeout(i,3000))}return{destroyed:t}}}function Wl(e=[]){let t=[{IpProtocol:"tcp",FromPort:22,ToPort:22,IpRanges:[{CidrIp:"0.0.0.0/0",Description:"SSH"}]}];for(let r of e)t.push(r.protocol==="icmp"?{IpProtocol:"icmp",FromPort:-1,ToPort:-1,IpRanges:[{CidrIp:"0.0.0.0/0"}]}:{IpProtocol:r.protocol,FromPort:r.port,ToPort:r.port,IpRanges:[{CidrIp:"0.0.0.0/0"}]});return t}class rd{provider="aws";ec2;ssm;constructor(e){this.ec2=e.ec2,this.ssm=e.ssm}async findInstance(e,t){return(await this.ec2.describeInstances({Filters:[{Name:"tag:Name",Values:[e]},{Name:"instance-state-name",Values:t}]})).Reservations?.flatMap((n)=>n.Instances??[])[0]}async waitForPublicIp(e,t=300000){let r=Date.now();while(Date.now()-r<t){let n=await this.ec2.getInstance(e);if(n?.State?.Name==="running"&&n.PublicIpAddress)return n;await new Promise((s)=>setTimeout(s,5000))}throw Error(`EC2 instance ${e} did not reach running with a public IP within ${t}ms`)}async ensureSecurityGroup(e){let t=`${e.name}-sg`,n=(await this.ec2.describeSecurityGroups({Filters:[{Name:"group-name",Values:[t]}]})).SecurityGroups?.[0]?.GroupId;if(n)return n;let s=await this.ec2.createSecurityGroup({GroupName:t,Description:`box ${e.name} (managed by ts-cloud box-provision)`});if(!s.GroupId)throw Error(`could not create security group ${t}`);return await this.ec2.authorizeSecurityGroupIngress({GroupId:s.GroupId,IpPermissions:Wl(e.ports)}),s.GroupId}async resolveImage(e){if(e.image?.startsWith("ami-"))return e.image;let r=(await this.ssm.getParameter({Name:ed})).Parameter?.Value;if(!r)throw Error(`could not resolve the Ubuntu 24.04 AMI via SSM (${ed})`);return r}async ensureBox(e){let t=await this.findInstance(e.name,["pending","running"]);if(t?.InstanceId){let f=await this.waitForPublicIp(t.InstanceId);return{provider:"aws",id:f.InstanceId,name:e.name,publicIp:f.PublicIpAddress,created:!1}}let[r,n]=await Promise.all([this.ensureSecurityGroup(e),this.resolveImage(e)]),s=[{Key:"Name",Value:e.name},...Object.entries(e.labels??{}).map(([f,g])=>({Key:f,Value:g}))],a=(await this.ec2.runInstances({ImageId:n,InstanceType:e.size,MinCount:1,MaxCount:1,SecurityGroupIds:[r],UserData:Buffer.from(td(e),"utf8").toString("base64"),TagSpecifications:[{ResourceType:"instance",Tags:s}]})).Instances?.[0]?.InstanceId;if(!a)throw Error(`RunInstances returned no instance for box ${e.name}`);let c=await this.waitForPublicIp(a);return{provider:"aws",id:a,name:e.name,publicIp:c.PublicIpAddress,created:!0}}async destroyBox(e){let t=[],r=await this.findInstance(e,["pending","running","stopping","stopped"]);if(r?.InstanceId){await this.ec2.terminateInstances([r.InstanceId]),t.push(`instance ${e} (${r.InstanceId})`);let i=Date.now();while(Date.now()-i<300000){let a=await this.ec2.getInstance(r.InstanceId);if(!a||a.State?.Name==="terminated")break;await new Promise((c)=>setTimeout(c,5000))}}let s=(await this.ec2.describeSecurityGroups({Filters:[{Name:"group-name",Values:[`${e}-sg`]}]})).SecurityGroups?.[0]?.GroupId;if(s)for(let i=0;i<10;i++)try{await this.ec2.deleteSecurityGroup(s),t.push(`security group ${e}-sg (${s})`);break}catch{if(i===9)break;await new Promise((a)=>setTimeout(a,3000))}return{destroyed:t}}}function Xh(e){if(e.provider==="hetzner"){if(!e.hetzner)throw Error('createBoxProvisioner: options.hetzner (a HetznerClient) is required for provider "hetzner"');return new wi(e.hetzner)}if(!e.aws)throw Error('createBoxProvisioner: options.aws ({ ec2, ssm }) is required for provider "aws"');return new rd(e.aws)}var oo="/opt/pantry/cli",pp=`${u}/pantry/.bin`,Yl={"google.com/chrome":{profile:"ts-cloud-pantry-chrome",binary:`${u}/pantry/google.com/chrome/*/lib/chrome-for-testing/chrome`}};function Oo(e){if(!e.startsWith("/")||/[^A-Za-z0-9_./*-]/.test(e)||e.includes("**")||e.split("/").slice(1).some((t)=>!t||t==="."||t===".."))throw Error("Sandbox paths must be absolute without traversal or AppArmor control syntax")}function Do(e){let t=[...new Set(e.sandboxedPackageProjects??[])].sort();if(t.length>16)throw Error("At most 16 sandboxed package projects may be declared");for(let r of t){Oo(r);let n=r.indexOf("*"),s=r.slice(r.lastIndexOf("/")+1);if(r.length>240||n!==-1&&(n!==r.length-1||!/^[A-Za-z0-9_][A-Za-z0-9_.-]+-\*$/.test(s)))throw Error("Sandbox project wildcards must follow a named final directory prefix")}if(t.length&&!(e.packages??[]).some((r)=>r==="google.com/chrome"||r.startsWith("google.com/chrome@")))throw Error("Sandboxed projects require the Chrome package to be explicitly declared");return t}function Xl(e,t,r=[]){if(Pt("sandbox profile",e),/[^A-Za-z0-9_.-]/.test(e))throw Error("Invalid sandbox profile name");let n=[...new Set([t,...r])];for(let i of n)Oo(i);let s=n.length===1?n[0]:`/{${n.map((i)=>i.slice(1)).join(",")}}`;return["# Written by ts-cloud: lets this pantry package create user namespaces for its","# sandbox, like Ubuntu's own profile for /opt/google/chrome/chrome.","abi <abi/4.0>,","include <tunables/global>","",`profile ${e} ${s} flags=(unconfined) {`," userns,","",` include if exists <local/${e}>`,"}",""].join(`
|
|
429
|
+
`)}function xo(e){let t=Do(e),r=e.packages??[];return Object.entries(Yl).filter(([n])=>r.some((s)=>s===n||s.startsWith(`${n}@`))).map(([,{profile:n,binary:s}])=>({name:n,content:Xl(n,s,t.map((i)=>`${i}/pantry/google.com/chrome/*/lib/chrome-for-testing/chrome`))}))}function mp(e){let t=xo(e);if(!t.length)return`set -euo pipefail
|
|
428
430
|
# No declared sandboxed package profiles.
|
|
429
431
|
`;return["set -euo pipefail","PROFILE_DIR=/etc/apparmor.d","PROFILE_STATE=/sys/kernel/security/apparmor/profiles",'[ "$(id -u)" = 0 ] || { echo "Sandbox policy convergence requires root" >&2; exit 1; }','command -v apparmor_parser >/dev/null || { echo "AppArmor parser is required" >&2; exit 1; }','[ -d "$PROFILE_DIR" ] && [ ! -L "$PROFILE_DIR" ] || { echo "AppArmor policy directory must be a real directory" >&2; exit 1; }','[ "$(stat -c %u "$PROFILE_DIR")" = 0 ] || { echo "AppArmor policy directory must be root-owned" >&2; exit 1; }','MODE=$(stat -c %a "$PROFILE_DIR")','(( (8#$MODE & 022) == 0 )) || { echo "AppArmor policy directory must not be group/other writable" >&2; exit 1; }','WORK=$(mktemp -d "$PROFILE_DIR/.ts-cloud-sandbox.XXXXXX")',"KEEP_BACKUP=0",`trap 'if [ "$KEEP_BACKUP" = 0 ]; then rm -rf -- "$WORK"; fi' EXIT`,...t.flatMap(({name:r,content:n})=>[`TARGET="$PROFILE_DIR/${r}"`,'if [ -L "$TARGET" ] || { [ -e "$TARGET" ] && [ ! -f "$TARGET" ]; }; then echo "Refusing non-regular sandbox policy" >&2; exit 1; fi','if [ -f "$TARGET" ] && [ "$(stat -c %u:%g "$TARGET")" != 0:0 ]; then echo "Sandbox policy must be root-owned" >&2; exit 1; fi','if [ -f "$TARGET" ]; then MODE=$(stat -c %a "$TARGET"); (( (8#$MODE & 022) == 0 )) || { echo "Sandbox policy must not be group/other writable" >&2; exit 1; }; fi','if [ ! -f "$TARGET" ]; then',' [ -r "$PROFILE_STATE" ] || { echo "Cannot inspect existing sandbox policy state" >&2; exit 1; }',' cat -- "$PROFILE_STATE" > "$WORK/profile-state"',' while IFS= read -r LOADED || [ -n "$LOADED" ]; do',' case "$LOADED" in',` "${r} ("*) echo "Refusing to replace an orphaned loaded policy without a recovery definition" >&2; exit 1 ;;`," esac",' done < "$WORK/profile-state"',"fi",`printf %s ${wt(kr(n))} | base64 -d > "$WORK/candidate"`,'apparmor_parser -Q -K "$WORK/candidate"','if [ -f "$TARGET" ] && cmp -s "$WORK/candidate" "$TARGET"; then',' apparmor_parser -r -K "$TARGET"',` echo "${Et} sandbox profile ${r} reconciled"`,"else"," HAD_PREVIOUS=0"," PREVIOUS_MODE=644",' if [ -f "$TARGET" ]; then cp -p -- "$TARGET" "$WORK/previous"; PREVIOUS_MODE=$(stat -c %a "$TARGET"); HAD_PREVIOUS=1; fi'," KEEP_BACKUP=1",' if install -m 644 -o root -g root "$WORK/candidate" "$WORK/ready" && mv -f -- "$WORK/ready" "$TARGET" && apparmor_parser -r -K "$TARGET"; then'," KEEP_BACKUP=0",` echo "${Et} sandbox profile ${r} converged"`," else"," KEEP_BACKUP=1",' if [ "$HAD_PREVIOUS" = 1 ]; then',' if install -m "$PREVIOUS_MODE" -o root -g root "$WORK/previous" "$WORK/restore" && mv -f -- "$WORK/restore" "$TARGET" && apparmor_parser -r -K "$TARGET"; then KEEP_BACKUP=0; fi'," else",' if [ ! -e "$TARGET" ] || apparmor_parser -R -K "$TARGET"; then rm -f -- "$TARGET"; KEEP_BACKUP=0; fi'," fi",' echo "Sandbox reload failed; retained recovery files if rollback failed: $WORK" >&2'," exit 1"," fi","fi"]),""].join(`
|
|
430
|
-
`)}var Et="ts-cloud:",
|
|
432
|
+
`)}var Et="ts-cloud:",Jl=["/usr/local/bin","/usr/bin","/bin"];function wt(e){return`'${e.split("'").join("'\\''")}'`}function kr(e){return Buffer.from(e,"utf8").toString("base64")}function Pt(e,t){if(!/^[a-z_][a-z0-9_.-]*$/i.test(t))throw Error(`Box ${e} "${t}" may only contain letters, digits, '.', '_' and '-'`)}function fp(e){return Object.entries(e).map(([t,r])=>{if(!/^[A-Z_][A-Z0-9_]*$/i.test(t))throw Error(`Environment variable name "${t}" is not valid`);let n=String(r).replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n");return`${t}="${n}"`}).join(`
|
|
431
433
|
`).concat(`
|
|
432
|
-
`)}function hp(e,t,r){let n=r.userUnit?"%h":"/root",s=["# Written by ts-cloud from the box declaration; edits here are overwritten.","[Unit]",`Description=${t.description??e}`,"After=network-online.target","","[Service]","Type=simple",`WorkingDirectory=${t.workingDirectory??n}`];if(t.environmentFile)s.push(`EnvironmentFile=${t.environmentFile}`);if(t.environment&&Object.keys(t.environment).length>0)s.push(`EnvironmentFile=${n}/.config/ts-cloud/${e}.env`);return s.push(`Environment=PATH=${[...t.path??[],...r.pantryOnPath===!1?[]:[pp],...
|
|
434
|
+
`)}function hp(e,t,r){let n=r.userUnit?"%h":"/root",s=["# Written by ts-cloud from the box declaration; edits here are overwritten.","[Unit]",`Description=${t.description??e}`,"After=network-online.target","","[Service]","Type=simple",`WorkingDirectory=${t.workingDirectory??n}`];if(t.environmentFile)s.push(`EnvironmentFile=${t.environmentFile}`);if(t.environment&&Object.keys(t.environment).length>0)s.push(`EnvironmentFile=${n}/.config/ts-cloud/${e}.env`);return s.push(`Environment=PATH=${[...t.path??[],...r.pantryOnPath===!1?[]:[pp],...Jl].join(":")}`),s.push(`ExecStart=${t.exec}`),s.push(`Restart=${t.restart??"always"}`),s.push(`RestartSec=${t.restartSec??10}`),s.push("","[Install]",`WantedBy=${r.userUnit?"default.target":"multi-user.target"}`,""),s.join(`
|
|
433
435
|
`)}function Ap(e){Do(e);let t=e.user?.name;if(t)Pt("user",t);for(let f of e.user?.groups??[])Pt("group",f);let r=Object.entries(e.services??{});for(let[f]of r)Pt("service",f);let n=e.pantryVersion,s=["set -euo pipefail","export DEBIAN_FRONTEND=noninteractive",`say() { echo "${Et} $*"; }`,"write_if_changed() {",' local path="$1" mode="$2" owner="$3" tmp'," tmp=$(mktemp)",' printf %s "$4" | base64 -d > "$tmp"',' if [ -f "$path" ] && cmp -s "$tmp" "$path"; then rm -f "$tmp"; return 1; fi',' install -D -m "$mode" -o "${owner%%:*}" -g "${owner##*:}" "$tmp" "$path"',' rm -f "$tmp"',"}",`PANTRY="${oo}/pantry"`,n?`if [ ! -x "$PANTRY" ] || ! "$PANTRY" --version 2>/dev/null | grep -q "pantry ${n.replace(/[^0-9A-Za-z.+-]/g,"")}\\b"; then`:'if [ ! -x "$PANTRY" ]; then'," (",...ht({version:n,installDir:oo}).map((f)=>` ${f}`)," )",' say "pantry $("$PANTRY" --version 2>/dev/null | head -1)"',"fi",`mkdir -p ${u}`],i=[...new Set(e.packages??[])];if(i.length>0){let f=Math.round((e.minFreeDiskGb??10)*1024*1024),g=`${u}/pantry/.ts-cloud-packages`,h=`${[...i].sort().join(`
|
|
434
436
|
`)}
|
|
435
437
|
`;if(s.push(`WANTED_PACKAGES=${wt(kr(h))}`,`if [ -f ${g} ] && [ "$(base64 -w0 < ${g})" = "$WANTED_PACKAGES" ]; then MISSING=0; else MISSING=1; fi`),s.push('if [ "$MISSING" = 1 ]; then'," FREE_KB=$(df -Pk / | awk 'NR==2 {print $4}')",` if [ "$FREE_KB" -lt ${f} ]; then`,` say "not installing packages: $((FREE_KB / 1048576)) GB free, the box declares at least ${e.minFreeDiskGb??10} GB"`," exit 3"," fi",` PANTRY_SERVICE_SCOPE=system PATH="${oo}:$PATH" sh -c ${wt(`cd ${u} && pantry install ${i.map(wt).join(" ")}`)}`,` chmod -R a+rX ${u}/pantry 2>/dev/null || true`,` printf %s "$WANTED_PACKAGES" | base64 -d > ${g}`,` say "packages ${i.join(" ")}"`,"fi"),xo(e).length>0)s.push("if command -v apparmor_parser >/dev/null 2>&1 && [ -d /etc/apparmor.d ]; then"," ("),s.push(...mp(e).trimEnd().split(`
|
|
436
|
-
`).map((S)=>` ${S}`)),s.push(" )","fi")}if(t)s.push(`if ! id -u ${t} >/dev/null 2>&1; then useradd --create-home --shell /bin/bash ${t}; say "created user ${t}"; fi`,...(e.user?.groups??[]).map((f)=>`if getent group ${f} >/dev/null && ! id -nG ${t} | tr ' ' '\\n' | grep -qx ${f}; then usermod -aG ${f} ${t}; say "added ${t} to ${f}"; fi`),`if [ "$(loginctl show-user ${t} -p Linger --value 2>/dev/null)" != yes ]; then loginctl enable-linger ${t}; say "enabled linger for ${t}"; fi`);s.push(...Io(e));let a=t?`${t}:${t}`:"root:root",c=t?"$SVC_HOME/.config/systemd/user":"/etc/systemd/system";if(r.length>0)s.push("RELOAD=0");for(let[f,g]of r){let h=hp(f,g,{userUnit:Boolean(t),pantryOnPath:i.length>0});s.push(`CHANGED_${f.replace(/[^A-Za-z0-9_]/g,"_")}=0`);let S=`CHANGED_${f.replace(/[^A-Za-z0-9_]/g,"_")}`;if(g.environment&&Object.keys(g.environment).length>0)s.push(`if write_if_changed "$SVC_HOME/.config/ts-cloud/${f}.env" 600 ${a} ${wt(kr(fp(g.environment)))}; then ${S}=1; fi`);s.push(`if write_if_changed "${c}/${f}.service" 644 ${a} ${wt(kr(h))}; then ${S}=1; RELOAD=1; fi`)}if(r.length>0)s.push('if [ "$RELOAD" = 1 ]; then svc daemon-reload; fi');for(let[f,g]of r){let h=`CHANGED_${f.replace(/[^A-Za-z0-9_]/g,"_")}`;s.push(`svc enable ${f}.service >/dev/null 2>&1 || svc enable ${f}.service`,`if ! svc is-active --quiet ${f}.service; then svc start ${f}.service; say "started ${f}"`,g.restartOnChange?`elif [ "$${h}" = 1 ]; then svc restart ${f}.service; say "restarted ${f}"`:
|
|
438
|
+
`).map((S)=>` ${S}`)),s.push(" )","fi")}if(t)s.push(`if ! id -u ${t} >/dev/null 2>&1; then useradd --create-home --shell /bin/bash ${t}; say "created user ${t}"; fi`,...(e.user?.groups??[]).map((f)=>`if getent group ${f} >/dev/null && ! id -nG ${t} | tr ' ' '\\n' | grep -qx ${f}; then usermod -aG ${f} ${t}; say "added ${t} to ${f}"; fi`),`if [ "$(loginctl show-user ${t} -p Linger --value 2>/dev/null)" != yes ]; then loginctl enable-linger ${t}; say "enabled linger for ${t}"; fi`);s.push(...Io(e));let a=t?`${t}:${t}`:"root:root",c=t?"$SVC_HOME/.config/systemd/user":"/etc/systemd/system";if(r.length>0)s.push("RELOAD=0");for(let[f,g]of r){let h=hp(f,g,{userUnit:Boolean(t),pantryOnPath:i.length>0});s.push(`CHANGED_${f.replace(/[^A-Za-z0-9_]/g,"_")}=0`);let S=`CHANGED_${f.replace(/[^A-Za-z0-9_]/g,"_")}`;if(g.environment&&Object.keys(g.environment).length>0)s.push(`if write_if_changed "$SVC_HOME/.config/ts-cloud/${f}.env" 600 ${a} ${wt(kr(fp(g.environment)))}; then ${S}=1; fi`);s.push(`if write_if_changed "${c}/${f}.service" 644 ${a} ${wt(kr(h))}; then ${S}=1; RELOAD=1; fi`)}if(r.length>0)s.push('if [ "$RELOAD" = 1 ]; then svc daemon-reload; fi');for(let[f,g]of r){let h=`CHANGED_${f.replace(/[^A-Za-z0-9_]/g,"_")}`;s.push(`svc enable ${f}.service >/dev/null 2>&1 || svc enable ${f}.service`,`if ! svc is-active --quiet ${f}.service; then svc start ${f}.service; say "started ${f}"`,g.restartOnChange?`elif [ "$${h}" = 1 ]; then svc restart ${f}.service; say "restarted ${f}"`:Zl(g)?`elif [ "$${h}" = 1 ]; then svc kill --kill-who=main -s ${Ao(f,g)} ${f}.service; say "changed ${f}; it restarts on the new unit once its current work is done"`:`elif [ "$${h}" = 1 ]; then say "changed ${f}; restart it to apply"`,"fi")}return s.push('say "converged"'),`${s.join(`
|
|
437
439
|
`)}
|
|
438
|
-
`}function Ao(e,t){let r=String(t.drainSignal).replace(/^SIG/i,"").toUpperCase();if(!/^[A-Z0-9]+$/.test(r))throw Error(`Box service "${e}" has an invalid drainSignal`);return`SIG${r}`}function
|
|
440
|
+
`}function Ao(e,t){let r=String(t.drainSignal).replace(/^SIG/i,"").toUpperCase();if(!/^[A-Z0-9]+$/.test(r))throw Error(`Box service "${e}" has an invalid drainSignal`);return`SIG${r}`}function Zl(e){return Boolean(e.drainSignal)&&(e.restart??"always")==="always"}function Io(e){let t=e.user?.name;if(!t)return["SVC_HOME=/root",'svc() { systemctl "$@"; }'];return[`SVC_UID=$(id -u ${t})`,`SVC_HOME=$(getent passwd ${t} | cut -d: -f6)`,`svc() { sudo -u ${t} XDG_RUNTIME_DIR="/run/user/$SVC_UID" systemctl --user "$@"; }`,'for _ in $(seq 1 30); do [ -S "/run/user/$SVC_UID/bus" ] && break; sleep 1; done']}function Ql(e){if(e.user?.name)Pt("user",e.user.name);let t=Object.entries(e.services??{}).filter(([,n])=>n.drainSignal),r=["set -euo pipefail",`say() { echo "${Et} $*"; }`,...Io(e)];for(let[n,s]of t){Pt("service",n);let i=Ao(n,s).slice(3),a=s.drainTimeoutSec??3600;r.push(`if svc is-active --quiet ${n}.service; then`,` PID=$(svc show -p MainPID --value ${n}.service)`,` svc kill --kill-who=main -s SIG${i} ${n}.service`,` say "draining ${n} (SIG${i})"`," WAITED=0",' while [ "$PID" != 0 ] && kill -0 "$PID" 2>/dev/null; do',` if [ "$WAITED" -ge ${a} ]; then say "${n} still busy after ${a}s; not powering off"; exit 4; fi`," sleep 5; WAITED=$((WAITED + 5))"," done",` svc stop ${n}.service`,` say "drained ${n} after \${WAITED}s"`,"fi")}return r.push('say "drained"'),`${r.join(`
|
|
439
441
|
`)}
|
|
440
442
|
`}function Lo(e,t){if(!e.resize||t.alreadyComplete)return"none";if(t.capacityAvailable||e.resize.attemptUnavailable)return"resize";if(e.resize.whenUnavailable==="keep-current")return"unavailable";throw Error(`${t.targetType.name} is out of stock in ${t.location}; set resize.attemptUnavailable to ask anyway, or whenUnavailable: 'keep-current' to wait`)}function nd(e){return e.split(`
|
|
441
|
-
`).filter((t)=>t.startsWith(Et)).map((t)=>t.slice(Et.length).trim())}async function Yh(e){let{box:t}=e;if(e.dryRun)return
|
|
442
|
-
`)}var id="dashboard";function ao(){return Q("dashboard-credentials.json")}function
|
|
443
|
-
`),
|
|
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
|
|
445
|
-
`),
|
|
443
|
+
`).filter((t)=>t.startsWith(Et)).map((t)=>t.slice(Et.length).trim())}async function Yh(e){let{box:t}=e;if(e.dryRun)return eu(e);let r=await new wi(e.client).ensureBox({name:t.name,size:t.size,image:t.image,location:t.location,ports:t.ports,sshPublicKey:e.sshPublicKey,labels:{"ts-cloud/role":"box","ts-cloud/managed-by":"ts-cloud",...t.labels}});await At(r.publicIp,{identityFile:e.identityFile});let n=new bt({user:"root",identityFile:e.identityFile,hostKey:{policy:"pin",knownHostsFile:e.knownHostsFile}}),s=[],i=await n.ensureHostKey(r.publicIp);if(i.pinnedNow)s.push(`pinned host key ${i.fingerprint}`);if(t.resize&&!r.created){let c=await er(e.client,Number(r.id),t.size,t.resize.upgradeDisk!==!1),f=Lo(t,c);if(f==="unavailable")s.push(`${c.targetType.name} is out of stock in ${c.location}; keeping ${c.currentType.name}`);if(f==="resize"){let g=await li({client:e.client,serverId:Number(r.id),targetType:c.targetType.name,upgradeDisk:c.upgradeDisk,attemptUnavailable:t.resize.attemptUnavailable,hooks:{preflight:async()=>{s.push(...nd(await n.exec(r.publicIp,Ql(t))))},onPhase:(h)=>e.onPhase?.(h)}});if(g.status==="completed")s.push(`resized ${c.currentType.name} to ${c.targetType.name}`);else if(g.status==="recovered")s.push(`could not resize to ${c.targetType.name} (${g.error}); back on ${c.currentType.name}`);else if(g.status==="waiting-capacity")s.push(`${c.targetType.name} is out of stock in ${c.location}; keeping ${c.currentType.name}`);await At(r.publicIp,{identityFile:e.identityFile})}}let a=await n.exec(r.publicIp,Ap(t));return{box:r,report:[...s,...nd(a)]}}async function eu(e){let{box:t}=e,r=(await e.client.listServers()).find((i)=>i.name===t.name);if(!r)return{box:{provider:"hetzner",id:"",name:t.name,publicIp:"",created:!1},report:[`would create ${t.name} (${t.size})`,"would converge"]};let n={provider:"hetzner",id:String(r.id),name:r.name,publicIp:r.public_net?.ipv4?.ip??"",created:!1},s=[];if(t.resize){let i=await er(e.client,r.id,t.size,t.resize.upgradeDisk!==!1),a=Lo(t,i);if(a==="resize")s.push(`would resize ${i.currentType.name} to ${i.targetType.name}${i.capacityAvailable?"":" (out of stock; asking placement anyway)"}, draining ${Object.entries(t.services??{}).filter(([,c])=>c.drainSignal).map(([c])=>c).join(", ")||"nothing"} first`);else if(a==="unavailable")s.push(`${i.targetType.name} is out of stock in ${i.location}; would keep ${i.currentType.name}`)}else if(r.server_type.name!==t.size)s.push(`runs ${r.server_type.name}, declared ${t.size}; set resize to change it`);return s.push("would converge"),{box:n,report:s}}import{copyFileSync as Mu}from"node:fs";import{tmpdir as Fu}from"node:os";import{join as zu}from"node:path";var tu=`${me}/project`;function Uo(e,t){let r=t.ownerSlug.trim(),n=t.selfSlug?.trim(),s={total:e.length,owner:[],self:[],others:new Map,unmanaged:[]};for(let i of e){let a=i.labels?.[tu]?.trim();if(!a){s.unmanaged.push(i.name);continue}if(a===r){s.owner.push(i.name);continue}if(n&&a===n){s.self.push(i.name);continue}let c=s.others.get(a);if(c)c.push(i.name);else s.others.set(a,[i.name])}return s}function Nn(e){let t=e.unmanaged.length;for(let r of e.others.values())t+=r.length;return t}function ko(e,t){let r=Nn(e),n=[];if(n.push(`Attaching to '${t.ownerSlug}' shares one provider project, so this deploy's credential can write to all ${e.total} server(s) it can see.`),r===0)return n.push("Nothing outside the two projects being joined is reachable with it."),n;n.push(`${r} of them belong to neither project:`);for(let s of[...e.others.keys()].sort())n.push(` ${s}: ${[...e.others.get(s)].sort().join(", ")}`);if(e.unmanaged.length>0)n.push(` not managed by ts-cloud: ${[...e.unmanaged].sort().join(", ")}`);return n.push("A compromised CI run or a mistargeted teardown in this project now reaches those. Keep the app in its own provider project instead if that is not acceptable, which rules out attaching."),n}import{execSync as No}from"node:child_process";import{randomBytes as nu}from"node:crypto";import{chmodSync as su,copyFileSync as ou,existsSync as ot,mkdirSync as Mo,readFileSync as Fo,statSync as iu,writeFileSync as Fn}from"node:fs";import{tmpdir as au}from"node:os";import{basename as cu,dirname as Bn,isAbsolute as zo,join as Se,resolve as lu}from"node:path";import{fileURLToPath as Bo}from"node:url";function Mn(e){if(!e||typeof e!=="object")return e;return Object.fromEntries(Object.keys(e).map((t)=>[t,""]))}function ru(e){let t=JSON.parse(JSON.stringify(e??{}));if(t.hetzner)delete t.hetzner.apiToken;delete t.aws,delete t.stateDir;for(let r of Object.values(t.sites??{})){if(r?.env)r.env=Mn(r.env);if(r?.environment)r.environment=Mn(r.environment)}for(let r of Object.values(t.environments??{}))if(r?.variables)r.variables=Mn(r.variables);for(let r of Object.values(t.infrastructure?.databases??{}))if(r?.password)r.password="";if(t.infrastructure?.appDatabase?.password)t.infrastructure.appDatabase.password="";if(t.infrastructure?.compute?.database?.password)t.infrastructure.compute.database.password="";if(t.infrastructure?.compute?.managedServices?.vitess?.password)t.infrastructure.compute.managedServices.vitess.password="";return t}function Ho(e){let t=ru(e);return["// Generated by ts-cloud for the management dashboard — do not edit.","//","// This is the project's resolved cloud config, inlined so it needs no","// imports on the box. Credentials are deliberately absent.",`export default ${JSON.stringify(t,null,2)}`,""].join(`
|
|
444
|
+
`)}var id="dashboard";function ao(){return Q("dashboard-credentials.json")}function uu(){return nu(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=uu();try{Mo(Bn(i),{recursive:!0}),Fn(i,`${JSON.stringify({username:t,password:a,generatedAt:new Date().toISOString()},null,2)}
|
|
445
|
+
`),su(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}
|
|
446
|
+
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 pu(){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 du(){return process.env.TS_CLOUD_UI_VERSION?.trim()||jo()}function mu(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=du();if(s.startsWith("file:")){let a=s.slice(5),c=zo(a)?a:lu(t,a);if(!ot(c)||!iu(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=cu(c),g=Se(n,f);if(c!==g)ou(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)}
|
|
447
|
+
`),pu()}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=mu(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(au(),`${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 fu(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(fu(t),!/^\/[a-zA-Z0-9_./-]+$/.test(e)||e.split("/").includes(".."))throw Error("Stacks backgroundBun requires a safe absolute release directory");return`${e}/${t}`}var gu=new Set(["laravel","php","statamic","wordpress"]);function Vr(e){if(e.framework)return e.framework;if(e.type&&gu.has(e.type))return"laravel";return"stacks"}var Vo=`eval "$(cd ${u} && pantry env 2>/dev/null)"`,hu="/usr/local/bin/bun",Nr={PATH:"/usr/local/bin:/usr/bin:/bin",BUN_INSTALL:"/opt/ts-cloud/bun",APP_ENV:"production",NODE_ENV:"production"};function jn(e){if(e.backgroundBun===void 0)return hu;return Go(e.current,e.backgroundBun)}function Su(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 _u="node_modules/@stacksjs/ts-cloud/dist/bin/stacks-scheduler.js",vu="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)} ${_u}`,queueWorkerCommand:(e,t)=>{if(t.backgroundBun!==void 0)Su(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}/${vu} ${n.join(" ")}`}},$u={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(" ")}`}},yu={stacks:qo,laravel:$u};function Wo(e){return yu[e]??qo}function Yo(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function bu(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 Tu(e,t,r){return`${e}-${t}-queue-${r}`}function wu(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
448
|
`)}
|
|
447
|
-
`}function Vn(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_UNIT_EOF'`,t.replace(/\n$/,""),"TS_CLOUD_UNIT_EOF"]}function
|
|
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
|
|
449
|
-
`);return[`cat > ${t} <<'TS_CLOUD_DNSCREDS_EOF'`,r,"TS_CLOUD_DNSCREDS_EOF",`chmod 600 ${t}`]}function
|
|
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",
|
|
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'`,
|
|
449
|
+
`}function Vn(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_UNIT_EOF'`,t.replace(/\n$/,""),"TS_CLOUD_UNIT_EOF"]}function Cu(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=Tu(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=`${wu(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=Cu(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}${bu(I.heartbeatUrl)} >/dev/null 2>&1`}let W=`* * * * * root ${V}
|
|
450
|
+
`.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 Pu(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 Eu(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(`
|
|
451
|
+
`);return[`cat > ${t} <<'TS_CLOUD_DNSCREDS_EOF'`,r,"TS_CLOUD_DNSCREDS_EOF",`chmod 600 ${t}`]}function Ru(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[...Pu(r),...r?Eu(r):[],...Ru({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",Ou=["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 Du(e){switch(e){case"laravel":case"statamic":return[Br,Pi,...Ou,Kr,xi];case"php":case"wordpress":return[Br,`${Pi} || true`,Kr];case"static":case"spa":return[Br,Kr]}}function xu(e,t){return e.replace(/^php\s+/,`${t} `).replace(/(\s)php\s+artisan\s+/g,`$1${t} artisan `)}function Au(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 Iu(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:Du(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(...Au(`${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(...Iu(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(xu(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 Lu(e){return e===!0||typeof e==="object"&&e!=null}function Hi(e){if(!e)return[];return Object.keys(jr).filter((t)=>Lu(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(`
|
|
452
|
+
`)){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",Uu=9100,ku=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 Hu(e){let t=Wr(e),r=0;for(let n=0;n<t.length;n++)r=r*31+t.charCodeAt(n)>>>0;return Uu+r%ku}function Qn(e){return`127.0.0.1:${Hu(e)}`}function Nu(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(`
|
|
453
|
+
`)}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'`,Nu(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 Bu(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 Ku(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
454
|
const { chmodSync, existsSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } = require('node:fs')
|
|
453
455
|
const { basename, join } = require('node:path')
|
|
454
456
|
const root = '/etc/rpx/sites.d'
|
|
@@ -476,4 +478,4 @@ This password is now in your deploy log. Set TS_CLOUD_UI_PASSWORD to a value of
|
|
|
476
478
|
changed = true
|
|
477
479
|
}
|
|
478
480
|
if (changed) writeFileSync('/run/ts-cloud-dashboard-routes-changed', '')
|
|
479
|
-
`)}`,"if [ -e /run/ts-cloud-dashboard-routes-changed ]; then"," systemctl restart rpx-gateway.service"," rm -f /run/ts-cloud-dashboard-routes-changed","fi"]:[];return["set -euo pipefail",`TS_CLOUD_DASHBOARD_PREFIX=${Yr(s)}`,`TS_CLOUD_DASHBOARD_SERVER_OWNER=${r?"1":"0"}`,`TS_CLOUD_DASHBOARD_DESIRED=${Yr(` ${i.join(" ")} `)}`,"for TS_CLOUD_UNIT_FILE in /etc/systemd/system/*.service; do",' [ -e "$TS_CLOUD_UNIT_FILE" ] || continue',' TS_CLOUD_UNIT=$(basename "$TS_CLOUD_UNIT_FILE")',' case "$TS_CLOUD_UNIT" in'," *-dashboard-*.service)",' if [ "$TS_CLOUD_DASHBOARD_SERVER_OWNER" != 1 ]; then',' case "$TS_CLOUD_UNIT" in "$TS_CLOUD_DASHBOARD_PREFIX"*.service) ;; *) continue ;; esac'," fi",' case "$TS_CLOUD_DASHBOARD_DESIRED" in',' *" $TS_CLOUD_UNIT "*) ;;'," *)",' systemctl disable --now "$TS_CLOUD_UNIT" 2>/dev/null || true',' rm -f "$TS_CLOUD_UNIT_FILE"'," ;;"," esac"," ;;"," esac","done","systemctl daemon-reload","systemctl reset-failed",...a]}async function Ku(e,t,r,n){let{config:s,environment:i}=t,a=s.project.slug,c=m(s,i),f=await e.findComputeTargets({slug:a,environment:i,role:"app",stackName:c});if(f.length===0)return!0;let g=await e.runRemoteDeploy({targets:f,commands:Bu(a,r,!s.cloud?.attachTo,r.map((h)=>s.sites?.[h]?.domain).filter((h)=>typeof h==="string")),comment:`ts-cloud reconcile management dashboard ${a}`,tags:{Project:a,Environment:i,Role:"app"}});if(!g.success)return n.error(`Management dashboard reconciliation failed: ${g.error||"unknown error"}`),!1;return!0}async function ju(e,t,r){let{config:n}=t,s=n.cloud?.attachTo;if(!s||!e.listReachableResources)return;let i;try{i=await e.listReachableResources()}catch(f){r.warn(`Could not determine this credential's reach: ${f instanceof Error?f.message:String(f)}`);return}let a=Uo(i,{ownerSlug:s,selfSlug:n.project.slug}),c=Nn(a)>0;for(let f of ko(a,{ownerSlug:s,selfSlug:n.project.slug}))if(c)r.warn(f);else r.info(f)}async function Gu(e,t,r){let{config:n,environment:s}=t,i=n.cloud?.attachTo;if(!i)return!0;let a=Hi(n.infrastructure?.compute?.managedServices);if(a.length===0)return!0;let c=n.project.slug,f=m(n,s),g=await e.findComputeTargets({slug:c,environment:s,role:"app",stackName:f});if(g.length===0)return!0;let h=await e.runRemoteDeploy({targets:g,commands:Ni(a),comment:`ts-cloud preflight managed services ${c}`,tags:{Project:c,Environment:s,Role:"app"}});if(!h.success)return r.warn(`Could not check '${i}' for the declared services: ${h.error||"unknown error"}`),!0;let S=new Set;for(let _ of h.perInstance)for(let v of Mi(_.output,a))S.add(v);if(S.size===0)return!0;return r.error(Fi([...S],i,g[0]?.publicIp)),!1}async function Vu(e,t,r){let{config:n,environment:s}=t,i=n.infrastructure?.compute,a=p(n);if(n.cloud?.attachTo&&a?.requireLocalPasswordAuth)throw Error("PostgreSQL host authentication can only be managed by an owned compute installation");if(!n.cloud?.attachTo&&!a?.requireLocalPasswordAuth)return!0;let c=ct(a,i?.managedServices??{});if(c.length===0)return!0;let f=n.project.slug,g=m(n,s),h=await e.findComputeTargets({slug:f,environment:s,role:"app",stackName:g});if(h.length===0)return!0;r.step(`Ensuring database '${a?.name}' + role exist on the shared box...`);let S=await e.runRemoteDeploy({targets:h,commands:c,comment:`ts-cloud ensure database ${f}/${a?.name}`,tags:{Project:f,Environment:s,Role:"app"}});if(!S.success)return r.error(`Ensuring database '${a?.name}' failed: ${S.error||"unknown error"}`),!1;return r.success(`Database '${a?.name}' is ready on ${S.instanceCount} target(s)`),!0}async function od(e){let{config:t,environment:r,driver:n,sha:s,runtime:i,tarballForSite:a,logger:c=Xr}=e,f=t.project.slug,g=e.cwd??process.cwd(),h=e.managementDashboard!==!1,S=pr(t);if(h)Ri(t,{cwd:g,logger:{info:c.info,warn:c.warn}});let _=!h||S?[]:Kn(t);if(h&&e.rpxConfig&&e.rpxConfig!==t&&!pr(e.rpxConfig))Ri(e.rpxConfig,{cwd:g,logger:{info:()=>{},warn:()=>{}}});if(h&&!await Ku(n,e,Kn(t),c))return!1;let v=null,y=new Map;if(_.length>0)if(v=co(t.sites?.[_[0]],{cwd:g,slug:f,sha:s,siteName:_[0],logger:{info:c.info,warn:c.warn}}),!v){c.warn("Management dashboard: no artifact available — skipping dashboard site(s) for this deploy.");for(let R of _)if(t.sites)delete t.sites[R]}else for(let R of _){if(R===_[0]){y.set(R,v);continue}try{let L=Fu(Mu(),`${f}-${R}-${s}.tar.gz`);Nu(v,L),y.set(R,L)}catch{y.set(R,v)}}let T=t.sites||{},x=Object.entries(T).filter(([R,L])=>{if(!L)return!1;let I=d(L);if(I==="bucket")return c.warn(`Site '${R}' targets a bucket — skipping (handled by the static-site path, not compute).`),!1;if(I==="redirect")return!1;if(I==="proxy")return!1;return!0});if(x.length===0)return Di(e);if(await ju(n,e,c),!await Gu(n,e,c))return!1;if(!await Vu(n,e,c))return!1;let q=(R)=>y.get(R)??a(R);for(let[R,L]of x){c.step(`Deploying site: ${R}`);let I=zr(L)?void 0:q(R),V=await lo(n,{config:t,environment:r,siteName:R,site:L,slug:f,sha:s,runtime:i,localTarballPath:I},c);if(!V.success){if(c.error(`Deploy of '${R}' failed: ${V.error||"unknown error"}`),V.perInstance)for(let W of V.perInstance)c.error(` ${W.instanceId}: ${W.status}${W.error?` — ${W.error}`:""}`);return!1}if(c.success(`Deployed ${f}/${R}@${s} to ${V.instanceCount} target(s)`),V.perInstance)for(let W of V.perInstance)c.info(` ✓ ${W.instanceId}: ${W.status}`)}if(!await Di(e))return!1;return!0}async function qu(e,t,r){let n=Cp(e);if(!n||n.tls==="off")return n;let s=await ze(t,r),i=s?.provider==="ssh"?s.lanIp:void 0;return i?{...n,ip:i}:n}async function Di(e){let{config:t,environment:r,driver:n,logger:s=Xr}=e,i=e.rpxConfig??t,a=w(i,{environment:r})??w(t,{environment:r});if(a?.engine!=="rpx")return!0;let c=i.sites||{},f=t.project.slug,g=m(t,r),h=await n.findComputeTargets({slug:f,environment:r,role:"lb",stackName:g});if(h.length>0){let H=(await n.findComputeTargets({slug:f,environment:r,role:"app",stackName:g})).map((I)=>({privateIp:I.privateIp,publicIp:I.publicIp})),R=rr(c,H,{proxy:a,slug:f});if(R.proxies.length===0)return s.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;s.step(`Reloading the load balancer's rpx gateway with ${R.proxies.length} route(s)...`);let L=await n.runRemoteDeploy({targets:h,commands:Ne({config:R,slug:f,preserveManagementDashboardRoutes:e.managementDashboard===!1}),comment:`ts-cloud rpx gateway reload ${f}`,tags:{Project:f,Environment:r,Role:"lb"}});if(!L.success)return s.error(`rpx gateway reload failed: ${L.error||"unknown error"}`),!1;return s.success(`rpx gateway reloaded on ${L.instanceCount} load balancer(s)`),!0}let S=await qu(t,g,e.cwd),_=B(c,{proxy:a,slug:f,lan:S,mail:C(t,{environment:r})});if(_.proxies.length===0)return s.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;let v=await n.findComputeTargets({slug:f,environment:r,role:"app",stackName:g});if(v.length===0)return s.warn("rpx gateway: no compute targets found — skipping gateway reload."),!0;let y=Boolean(t.cloud?.attachTo);if(y&&(a.version||a.tlsxVersion))s.warn(`rpx gateway: ignoring proxy.version/tlsxVersion — this project attaches to '${t.cloud?.attachTo}' and the gateway belongs to that box's owner.`);s.step(`Reloading rpx gateway with ${_.proxies.length} route(s)...`);let T=G({proxy:a,config:_,slug:f,tenant:y,profile:Ep(t),preserveManagementDashboardRoutes:e.managementDashboard===!1}),x=await n.runRemoteDeploy({targets:v,commands:T,comment:`ts-cloud rpx gateway reload ${f}`,tags:{Project:f,Environment:r,Role:"app"}});if(!x.success)return s.error(`rpx gateway reload failed: ${x.error||"unknown error"}`),!1;return s.success(`rpx gateway reloaded on ${x.instanceCount} target(s)`),!0}async function ad(e){let{config:t,environment:r,driver:n,logger:s=Xr}=e,i=e.rpxConfig??t,a=w(i,{environment:r})??w(t,{environment:r});if(a?.engine!=="rpx"||!a.onDemandTls)return!0;let c=B(i.sites||{},{proxy:a,slug:t.project.slug,mail:C(t,{environment:r})});if(c.proxies.length===0)return!0;let f=gd(c);if(f.length===0)return!0;let g=t.project.slug,h=m(t,r),S="lb",_=await n.findComputeTargets({slug:g,environment:r,role:S,stackName:h});if(_.length===0)S="app",_=await n.findComputeTargets({slug:g,environment:r,role:S,stackName:h});if(_.length===0)return s.warn("rpx TLS: no gateway targets found - skipping certificate issuance."),!0;s.step("Issuing rpx TLS certificates after DNS reconciliation...");let v=f.map((T)=>`test -s ${zu(`${c.productionCerts.certsDir}/${T}.crt`)}`).join(" && "),y=await n.runRemoteDeploy({targets:_,commands:[`systemctl start ${ud(g)}`,v],comment:`ts-cloud rpx TLS issuance ${g}`,tags:{Project:g,Environment:r,Role:S}});if(!y.success)return s.error(`rpx TLS issuance failed: ${y.error||"unknown error"}`),!1;return s.success(`rpx TLS certificates reconciled on ${y.instanceCount} gateway target(s)`),!0}var yp="658327ea-f89d-4fab-a63d-7e88639e58f6",Sp="4135ea2d-6df8-44a3-9df3-4b5a84be39ad",Ip="216adef6-5c7f-47e4-b989-5492eafa07d3",es="origin",Gi="origin-failover";function Vi(e,t){let r={TargetOriginId:es,ViewerProtocolPolicy:"redirect-to-https",Compress:!0,CachePolicyId:t==="dynamic"?Sp:yp,OriginRequestPolicyId:Ip,SmoothStreaming:!1,FieldLevelEncryptionId:"",TrustedSigners:{Enabled:!1,Quantity:0},TrustedKeyGroups:{Enabled:!1,Quantity:0},LambdaFunctionAssociations:{Quantity:0},FunctionAssociations:{Quantity:0},AllowedMethods:t==="dynamic"?{Quantity:7,Items:["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"],CachedMethods:{Quantity:2,Items:["GET","HEAD"]}}:{Quantity:3,Items:["GET","HEAD","OPTIONS"],CachedMethods:{Quantity:2,Items:["GET","HEAD"]}}};if(e!==null)r.PathPattern=e;return r}function Zh(e){let t=e.aliases;if(t.length===0)throw Error("buildCloudFrontOriginConfig: at least one alias is required");if(t.includes(e.originDomain))throw Error(`buildCloudFrontOriginConfig: originDomain ${e.originDomain} must not be one of the aliases (it would loop)`);if(e.originShield&&!e.originShieldRegion)throw Error("buildCloudFrontOriginConfig: originShieldRegion is required when originShield is enabled");let r=e.failoverOriginDomain;if(r!==void 0){if(t.includes(r))throw Error(`buildCloudFrontOriginConfig: failoverOriginDomain ${r} must not be one of the aliases (it would loop)`);if(r===e.originDomain)throw Error("buildCloudFrontOriginConfig: failoverOriginDomain must differ from originDomain")}else if(e.failoverStatusCodes)throw Error("buildCloudFrontOriginConfig: failoverStatusCodes needs failoverOriginDomain to fail over to");let n=e.originSecretHeader??"X-Origin-Verify",s=e.originSecret?{Quantity:1,Items:[{HeaderName:n,HeaderValue:e.originSecret}]}:{Quantity:0},i=[...e.behaviors??[]].sort((_,v)=>v.pathPattern.length-_.pathPattern.length),a=de(e,"buildCloudFrontOriginConfig"),c=(_,v,y,T={})=>({Id:_,DomainName:v,OriginPath:"",CustomHeaders:s,CustomOriginConfig:{HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only",OriginSslProtocols:{Quantity:1,Items:["TLSv1.2"]},OriginReadTimeout:30,OriginKeepaliveTimeout:5},ConnectionAttempts:T.ConnectionAttempts??3,ConnectionTimeout:T.ConnectionTimeout??10,OriginShield:y,OriginAccessControlId:""}),f=[c(es,e.originDomain,e.originShield?{Enabled:!0,OriginShieldRegion:e.originShieldRegion}:{Enabled:!1},a)],g={Quantity:0},h=Vi(null,"static");if(r!==void 0)f.push(c(Gi,r,{Enabled:!1})),g=un({primaryOriginId:es,secondaryOriginId:Gi,statusCodes:e.failoverStatusCodes}),kt(h.AllowedMethods,"the default cache behavior"),h.TargetOriginId=g.Items[0].Id;let S={CallerReference:e.callerReference??e.originDomain,Comment:e.comment??`Origin-fronted distribution for ${t[0]} → ${e.originDomain}`,Enabled:!0,Aliases:{Quantity:t.length,Items:t},DefaultRootObject:"",Origins:{Quantity:f.length,Items:f},OriginGroups:g,DefaultCacheBehavior:h,CacheBehaviors:{Quantity:i.length,Items:i.map((_)=>Vi(_.pathPattern,_.kind))},ViewerCertificate:{CloudFrontDefaultCertificate:!1,ACMCertificateArn:e.viewerCertificateArn,Certificate:e.viewerCertificateArn,CertificateSource:"acm",SSLSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"},PriceClass:e.priceClass??"PriceClass_All",HttpVersion:"http2and3",IsIPV6Enabled:!0,Restrictions:{GeoRestriction:{RestrictionType:"none",Quantity:0}},Logging:{Enabled:!1,IncludeCookies:!1,Bucket:"",Prefix:""},WebACLId:"",CustomErrorResponses:{Quantity:0}};return Nt(S,"buildCloudFrontOriginConfig"),S}export{Ng,Oc,Bg,De,_c,Yn,xg,Lc,Zn,Xt,Or,Yt,Og,_g,Fh,u,ht,Zs,_r,Ve,Lr,Lg,eo,M,$r,ei,ti,Mr,Zt,$g,Mg,Fr,Uh,Qh,Fg,Ug,Hh,Gh,Vh,Ur,ri,Qg,to,ni,ii,si,oi,ai,$c,Mc,ci,Qr,Ie,Fc,At,Uc,di,Qc,Hc,Hr,Gc,qe,se,er,Hg,li,Vc,qc,jc,zc,yt,je,ze,St,ui,gi,Pe,ro,no,Gg,Vg,Kc,qg,It,pi,Wc,jg,zg,Jc,bt,ke,Xc,Kg,Wg,io,mi,Ct,Jg,Xg,Yg,Zg,ep,tp,rp,np,ip,fi,hi,Ai,yi,Si,Ii,bi,sp,op,Gr,F,so,ap,cp,dp,Yc,lp,up,qh,jh,zh,Zc,gp,Kh,Wh,Jh,Ci,Ei,vi,Ti,ed,td,wi,rd,Xh,oo,pp,mp,fp,hp,Ap,nd,Yh,id,ao,sd,tr,Ri,co,Vr,lo,od,Di,ad,yp,Sp,Ip,Zh};
|
|
481
|
+
`)}`,"if [ -e /run/ts-cloud-dashboard-routes-changed ]; then"," systemctl restart rpx-gateway.service"," rm -f /run/ts-cloud-dashboard-routes-changed","fi"]:[];return["set -euo pipefail",`TS_CLOUD_DASHBOARD_PREFIX=${Yr(s)}`,`TS_CLOUD_DASHBOARD_SERVER_OWNER=${r?"1":"0"}`,`TS_CLOUD_DASHBOARD_DESIRED=${Yr(` ${i.join(" ")} `)}`,"for TS_CLOUD_UNIT_FILE in /etc/systemd/system/*.service; do",' [ -e "$TS_CLOUD_UNIT_FILE" ] || continue',' TS_CLOUD_UNIT=$(basename "$TS_CLOUD_UNIT_FILE")',' case "$TS_CLOUD_UNIT" in'," *-dashboard-*.service)",' if [ "$TS_CLOUD_DASHBOARD_SERVER_OWNER" != 1 ]; then',' case "$TS_CLOUD_UNIT" in "$TS_CLOUD_DASHBOARD_PREFIX"*.service) ;; *) continue ;; esac'," fi",' case "$TS_CLOUD_DASHBOARD_DESIRED" in',' *" $TS_CLOUD_UNIT "*) ;;'," *)",' systemctl disable --now "$TS_CLOUD_UNIT" 2>/dev/null || true',' rm -f "$TS_CLOUD_UNIT_FILE"'," ;;"," esac"," ;;"," esac","done","systemctl daemon-reload","systemctl reset-failed",...a]}async function ju(e,t,r,n){let{config:s,environment:i}=t,a=s.project.slug,c=m(s,i),f=await e.findComputeTargets({slug:a,environment:i,role:"app",stackName:c});if(f.length===0)return!0;let g=await e.runRemoteDeploy({targets:f,commands:Ku(a,r,!s.cloud?.attachTo,r.map((h)=>s.sites?.[h]?.domain).filter((h)=>typeof h==="string")),comment:`ts-cloud reconcile management dashboard ${a}`,tags:{Project:a,Environment:i,Role:"app"}});if(!g.success)return n.error(`Management dashboard reconciliation failed: ${g.error||"unknown error"}`),!1;return!0}async function Gu(e,t,r){let{config:n}=t,s=n.cloud?.attachTo;if(!s||!e.listReachableResources)return;let i;try{i=await e.listReachableResources()}catch(f){r.warn(`Could not determine this credential's reach: ${f instanceof Error?f.message:String(f)}`);return}let a=Uo(i,{ownerSlug:s,selfSlug:n.project.slug}),c=Nn(a)>0;for(let f of ko(a,{ownerSlug:s,selfSlug:n.project.slug}))if(c)r.warn(f);else r.info(f)}async function Vu(e,t,r){let{config:n,environment:s}=t,i=n.cloud?.attachTo;if(!i)return!0;let a=Hi(n.infrastructure?.compute?.managedServices);if(a.length===0)return!0;let c=n.project.slug,f=m(n,s),g=await e.findComputeTargets({slug:c,environment:s,role:"app",stackName:f});if(g.length===0)return!0;let h=await e.runRemoteDeploy({targets:g,commands:Ni(a),comment:`ts-cloud preflight managed services ${c}`,tags:{Project:c,Environment:s,Role:"app"}});if(!h.success)return r.warn(`Could not check '${i}' for the declared services: ${h.error||"unknown error"}`),!0;let S=new Set;for(let _ of h.perInstance)for(let v of Mi(_.output,a))S.add(v);if(S.size===0)return!0;return r.error(Fi([...S],i,g[0]?.publicIp)),!1}async function qu(e,t,r){let{config:n,environment:s}=t,i=n.infrastructure?.compute,a=p(n);if(n.cloud?.attachTo&&a?.requireLocalPasswordAuth)throw Error("PostgreSQL host authentication can only be managed by an owned compute installation");if(!n.cloud?.attachTo&&!a?.requireLocalPasswordAuth)return!0;let c=ct(a,i?.managedServices??{});if(c.length===0)return!0;let f=n.project.slug,g=m(n,s),h=await e.findComputeTargets({slug:f,environment:s,role:"app",stackName:g});if(h.length===0)return!0;r.step(`Ensuring database '${a?.name}' + role exist on the shared box...`);let S=await e.runRemoteDeploy({targets:h,commands:c,comment:`ts-cloud ensure database ${f}/${a?.name}`,tags:{Project:f,Environment:s,Role:"app"}});if(!S.success)return r.error(`Ensuring database '${a?.name}' failed: ${S.error||"unknown error"}`),!1;return r.success(`Database '${a?.name}' is ready on ${S.instanceCount} target(s)`),!0}async function od(e){let{config:t,environment:r,driver:n,sha:s,runtime:i,tarballForSite:a,logger:c=Xr}=e,f=t.project.slug,g=e.cwd??process.cwd(),h=e.managementDashboard!==!1,S=pr(t);if(h)Ri(t,{cwd:g,logger:{info:c.info,warn:c.warn}});let _=!h||S?[]:Kn(t);if(h&&e.rpxConfig&&e.rpxConfig!==t&&!pr(e.rpxConfig))Ri(e.rpxConfig,{cwd:g,logger:{info:()=>{},warn:()=>{}}});if(h&&!await ju(n,e,Kn(t),c))return!1;let v=null,y=new Map;if(_.length>0)if(v=co(t.sites?.[_[0]],{cwd:g,slug:f,sha:s,siteName:_[0],logger:{info:c.info,warn:c.warn}}),!v){c.warn("Management dashboard: no artifact available — skipping dashboard site(s) for this deploy.");for(let R of _)if(t.sites)delete t.sites[R]}else for(let R of _){if(R===_[0]){y.set(R,v);continue}try{let L=zu(Fu(),`${f}-${R}-${s}.tar.gz`);Mu(v,L),y.set(R,L)}catch{y.set(R,v)}}let T=t.sites||{},x=Object.entries(T).filter(([R,L])=>{if(!L)return!1;let I=d(L);if(I==="bucket")return c.warn(`Site '${R}' targets a bucket — skipping (handled by the static-site path, not compute).`),!1;if(I==="redirect")return!1;if(I==="proxy")return!1;return!0});if(x.length===0)return Di(e);if(await Gu(n,e,c),!await Vu(n,e,c))return!1;if(!await qu(n,e,c))return!1;let q=(R)=>y.get(R)??a(R);for(let[R,L]of x){c.step(`Deploying site: ${R}`);let I=zr(L)?void 0:q(R),V=await lo(n,{config:t,environment:r,siteName:R,site:L,slug:f,sha:s,runtime:i,localTarballPath:I},c);if(!V.success){if(c.error(`Deploy of '${R}' failed: ${V.error||"unknown error"}`),V.perInstance)for(let W of V.perInstance)c.error(` ${W.instanceId}: ${W.status}${W.error?` — ${W.error}`:""}`);return!1}if(c.success(`Deployed ${f}/${R}@${s} to ${V.instanceCount} target(s)`),V.perInstance)for(let W of V.perInstance)c.info(` ✓ ${W.instanceId}: ${W.status}`)}if(!await Di(e))return!1;return!0}async function Wu(e,t,r){let n=Cp(e);if(!n||n.tls==="off")return n;let s=await ze(t,r),i=s?.provider==="ssh"?s.lanIp:void 0;return i?{...n,ip:i}:n}async function Di(e){let{config:t,environment:r,driver:n,logger:s=Xr}=e,i=e.rpxConfig??t,a=w(i,{environment:r})??w(t,{environment:r});if(a?.engine!=="rpx")return!0;let c=i.sites||{},f=t.project.slug,g=m(t,r),h=await n.findComputeTargets({slug:f,environment:r,role:"lb",stackName:g});if(h.length>0){let H=(await n.findComputeTargets({slug:f,environment:r,role:"app",stackName:g})).map((I)=>({privateIp:I.privateIp,publicIp:I.publicIp})),R=rr(c,H,{proxy:a,slug:f});if(R.proxies.length===0)return s.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;s.step(`Reloading the load balancer's rpx gateway with ${R.proxies.length} route(s)...`);let L=await n.runRemoteDeploy({targets:h,commands:Ne({config:R,slug:f,preserveManagementDashboardRoutes:e.managementDashboard===!1}),comment:`ts-cloud rpx gateway reload ${f}`,tags:{Project:f,Environment:r,Role:"lb"}});if(!L.success)return s.error(`rpx gateway reload failed: ${L.error||"unknown error"}`),!1;return s.success(`rpx gateway reloaded on ${L.instanceCount} load balancer(s)`),!0}let S=await Wu(t,g,e.cwd),_=B(c,{proxy:a,slug:f,lan:S,mail:C(t,{environment:r})});if(_.proxies.length===0)return s.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;let v=await n.findComputeTargets({slug:f,environment:r,role:"app",stackName:g});if(v.length===0)return s.warn("rpx gateway: no compute targets found — skipping gateway reload."),!0;let y=Boolean(t.cloud?.attachTo);if(y&&(a.version||a.tlsxVersion))s.warn(`rpx gateway: ignoring proxy.version/tlsxVersion — this project attaches to '${t.cloud?.attachTo}' and the gateway belongs to that box's owner.`);s.step(`Reloading rpx gateway with ${_.proxies.length} route(s)...`);let T=G({proxy:a,config:_,slug:f,tenant:y,profile:Ep(t),preserveManagementDashboardRoutes:e.managementDashboard===!1}),x=await n.runRemoteDeploy({targets:v,commands:T,comment:`ts-cloud rpx gateway reload ${f}`,tags:{Project:f,Environment:r,Role:"app"}});if(!x.success)return s.error(`rpx gateway reload failed: ${x.error||"unknown error"}`),!1;return s.success(`rpx gateway reloaded on ${x.instanceCount} target(s)`),!0}async function ad(e){let{config:t,environment:r,driver:n,logger:s=Xr}=e,i=e.rpxConfig??t,a=w(i,{environment:r})??w(t,{environment:r});if(a?.engine!=="rpx"||!a.onDemandTls)return!0;let c=B(i.sites||{},{proxy:a,slug:t.project.slug,mail:C(t,{environment:r})});if(c.proxies.length===0)return!0;let f=gd(c);if(f.length===0)return!0;let g=t.project.slug,h=m(t,r),S="lb",_=await n.findComputeTargets({slug:g,environment:r,role:S,stackName:h});if(_.length===0)S="app",_=await n.findComputeTargets({slug:g,environment:r,role:S,stackName:h});if(_.length===0)return s.warn("rpx TLS: no gateway targets found - skipping certificate issuance."),!0;s.step("Issuing rpx TLS certificates after DNS reconciliation...");let v=f.map((T)=>`test -s ${Bu(`${c.productionCerts.certsDir}/${T}.crt`)}`).join(" && "),y=await n.runRemoteDeploy({targets:_,commands:[`systemctl start ${ud(g)}`,v],comment:`ts-cloud rpx TLS issuance ${g}`,tags:{Project:g,Environment:r,Role:S}});if(!y.success)return s.error(`rpx TLS issuance failed: ${y.error||"unknown error"}`),!1;return s.success(`rpx TLS certificates reconciled on ${y.instanceCount} gateway target(s)`),!0}var yp="658327ea-f89d-4fab-a63d-7e88639e58f6",Sp="4135ea2d-6df8-44a3-9df3-4b5a84be39ad",Ip="216adef6-5c7f-47e4-b989-5492eafa07d3",es="origin",Gi="origin-failover";function Vi(e,t){let r={TargetOriginId:es,ViewerProtocolPolicy:"redirect-to-https",Compress:!0,CachePolicyId:t==="dynamic"?Sp:yp,OriginRequestPolicyId:Ip,SmoothStreaming:!1,FieldLevelEncryptionId:"",TrustedSigners:{Enabled:!1,Quantity:0},TrustedKeyGroups:{Enabled:!1,Quantity:0},LambdaFunctionAssociations:{Quantity:0},FunctionAssociations:{Quantity:0},AllowedMethods:t==="dynamic"?{Quantity:7,Items:["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"],CachedMethods:{Quantity:2,Items:["GET","HEAD"]}}:{Quantity:3,Items:["GET","HEAD","OPTIONS"],CachedMethods:{Quantity:2,Items:["GET","HEAD"]}}};if(e!==null)r.PathPattern=e;return r}function Zh(e){let t=e.aliases;if(t.length===0)throw Error("buildCloudFrontOriginConfig: at least one alias is required");if(t.includes(e.originDomain))throw Error(`buildCloudFrontOriginConfig: originDomain ${e.originDomain} must not be one of the aliases (it would loop)`);if(e.originShield&&!e.originShieldRegion)throw Error("buildCloudFrontOriginConfig: originShieldRegion is required when originShield is enabled");let r=e.failoverOriginDomain;if(r!==void 0){if(t.includes(r))throw Error(`buildCloudFrontOriginConfig: failoverOriginDomain ${r} must not be one of the aliases (it would loop)`);if(r===e.originDomain)throw Error("buildCloudFrontOriginConfig: failoverOriginDomain must differ from originDomain")}else if(e.failoverStatusCodes)throw Error("buildCloudFrontOriginConfig: failoverStatusCodes needs failoverOriginDomain to fail over to");let n=e.originSecretHeader??"X-Origin-Verify",s=e.originSecret?{Quantity:1,Items:[{HeaderName:n,HeaderValue:e.originSecret}]}:{Quantity:0},i=[...e.behaviors??[]].sort((_,v)=>v.pathPattern.length-_.pathPattern.length),a=de(e,"buildCloudFrontOriginConfig"),c=(_,v,y,T={})=>({Id:_,DomainName:v,OriginPath:"",CustomHeaders:s,CustomOriginConfig:{HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only",OriginSslProtocols:{Quantity:1,Items:["TLSv1.2"]},OriginReadTimeout:30,OriginKeepaliveTimeout:5},ConnectionAttempts:T.ConnectionAttempts??3,ConnectionTimeout:T.ConnectionTimeout??10,OriginShield:y,OriginAccessControlId:""}),f=[c(es,e.originDomain,e.originShield?{Enabled:!0,OriginShieldRegion:e.originShieldRegion}:{Enabled:!1},a)],g={Quantity:0},h=Vi(null,"static");if(r!==void 0)f.push(c(Gi,r,{Enabled:!1})),g=un({primaryOriginId:es,secondaryOriginId:Gi,statusCodes:e.failoverStatusCodes}),kt(h.AllowedMethods,"the default cache behavior"),h.TargetOriginId=g.Items[0].Id;let S={CallerReference:e.callerReference??e.originDomain,Comment:e.comment??`Origin-fronted distribution for ${t[0]} → ${e.originDomain}`,Enabled:!0,Aliases:{Quantity:t.length,Items:t},DefaultRootObject:"",Origins:{Quantity:f.length,Items:f},OriginGroups:g,DefaultCacheBehavior:h,CacheBehaviors:{Quantity:i.length,Items:i.map((_)=>Vi(_.pathPattern,_.kind))},ViewerCertificate:{CloudFrontDefaultCertificate:!1,ACMCertificateArn:e.viewerCertificateArn,Certificate:e.viewerCertificateArn,CertificateSource:"acm",SSLSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"},PriceClass:e.priceClass??"PriceClass_All",HttpVersion:"http2and3",IsIPV6Enabled:!0,Restrictions:{GeoRestriction:{RestrictionType:"none",Quantity:0}},Logging:{Enabled:!1,IncludeCookies:!1,Bucket:"",Prefix:""},WebACLId:"",CustomErrorResponses:{Quantity:0}};return Nt(S,"buildCloudFrontOriginConfig"),S}export{Ng,Oc,Bg,De,_c,Yn,xg,Lc,Zn,Xt,Or,Yt,Og,_g,Fh,u,ht,Zs,_r,Ve,Lr,Lg,eo,M,$r,ei,ti,Mr,Zt,$g,Mg,Fr,Uh,Qh,Fg,Ug,Hh,Gh,Vh,Ur,ri,Qg,to,ni,ii,si,oi,ai,$c,Mc,ci,Qr,Ie,Fc,At,Uc,di,Qc,Hc,Hr,Gc,qe,se,er,Hg,li,Vc,qc,jc,zc,yt,je,ze,St,ui,gi,Pe,ro,no,Gg,Vg,Kc,qg,It,pi,Wc,jg,zg,Jc,bt,ke,Xc,Kg,Wg,io,mi,Ct,Jg,Xg,Yg,Zg,ep,tp,rp,np,ip,fi,hi,Ai,yi,Si,Ii,bi,sp,op,Gr,F,so,ap,cp,dp,Yc,lp,up,qh,jh,zh,Zc,gp,Kh,Wh,Jh,Ci,Ei,vi,Ti,ed,td,wi,rd,Xh,oo,pp,mp,fp,hp,Ap,nd,Yh,id,ao,sd,tr,Ri,co,Vr,lo,od,Di,ad,yp,Sp,Ip,Zh};
|