@stacksjs/ts-cloud 0.13.1 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/dist/aws/index.js +1 -1
  2. package/dist/bin/chunk-1a1m00zc.js +2 -0
  3. package/dist/bin/{chunk-y671cgz5.js → chunk-ajfvpq8r.js} +1 -1
  4. package/dist/bin/{chunk-jee6msvx.js → chunk-jgtdz9ac.js} +2 -2
  5. package/dist/bin/{chunk-88ysj8n5.js → chunk-zk1z04ng.js} +1 -1
  6. package/dist/bin/cli.js +5 -5
  7. package/dist/bin/dashboard-server.js +1 -1
  8. package/dist/{chunk-mcfdtg5w.js → chunk-1bxqrj7m.js} +1 -1
  9. package/dist/{chunk-t5tvt2r3.js → chunk-2k1tc16d.js} +94 -94
  10. package/dist/chunk-2ke75pzn.js +1 -0
  11. package/dist/{chunk-2s65yj3g.js → chunk-4w8d2mf0.js} +2 -2
  12. package/dist/{chunk-r4dpn715.js → chunk-9s5sm0wt.js} +6 -6
  13. package/dist/{chunk-asmv4fw1.js → chunk-a0d0h33y.js} +19 -19
  14. package/dist/chunk-a6jazwvy.js +1 -0
  15. package/dist/{chunk-vk513ge7.js → chunk-b2b79jtk.js} +60 -60
  16. package/dist/{chunk-y13zcbnp.js → chunk-b9pm7mbd.js} +84 -84
  17. package/dist/{chunk-hyj2ymp1.js → chunk-bkv2p4hp.js} +6 -6
  18. package/dist/{chunk-z7v4evbh.js → chunk-cwjskpj4.js} +2 -2
  19. package/dist/{chunk-xqx5szta.js → chunk-dky93h4d.js} +17 -17
  20. package/dist/{chunk-dzqz1sm0.js → chunk-etmbw4er.js} +3 -3
  21. package/dist/{chunk-p9fqsz06.js → chunk-gdbtz492.js} +2 -2
  22. package/dist/chunk-h1anhx3y.js +1 -0
  23. package/dist/{chunk-42kv07cs.js → chunk-jghkvdgt.js} +1 -1
  24. package/dist/{chunk-w5fmaaxa.js → chunk-jnt7ab86.js} +4 -4
  25. package/dist/chunk-kfwg1c6q.js +2 -0
  26. package/dist/chunk-kgw1dd9b.js +1 -0
  27. package/dist/chunk-phr1cqgf.js +1 -0
  28. package/dist/{chunk-nhtz2k8d.js → chunk-q4bk0htq.js} +5 -5
  29. package/dist/{chunk-ngdhqwf3.js → chunk-srh0ctd4.js} +3 -3
  30. package/dist/{chunk-8s9m8pyb.js → chunk-sxtgx8fj.js} +1 -1
  31. package/dist/{chunk-65ajja2a.js → chunk-t054j0zn.js} +1 -1
  32. package/dist/{chunk-6gtqjsg9.js → chunk-t5e5phth.js} +1 -1
  33. package/dist/{chunk-ds92qg3g.js → chunk-tg6yasej.js} +3 -3
  34. package/dist/{chunk-0g2jkhy5.js → chunk-trsaqsgv.js} +1 -1
  35. package/dist/{chunk-m5r0dt28.js → chunk-xacvkpf8.js} +2 -2
  36. package/dist/{chunk-nw0tvrrr.js → chunk-xv3w9q1a.js} +1 -1
  37. package/dist/{chunk-j7vsrx9g.js → chunk-zhg1kvw3.js} +5 -5
  38. package/dist/deploy/index.js +1 -1
  39. package/dist/dns/cloudflare-managed-headers.test.d.ts +1 -0
  40. package/dist/dns/cloudflare.d.ts +52 -0
  41. package/dist/dns/delegate-from-config.d.ts +40 -0
  42. package/dist/dns/index.d.ts +2 -2
  43. package/dist/dns/index.js +1 -1
  44. package/dist/drivers/index.js +1 -1
  45. package/dist/index.d.ts +2 -2
  46. package/dist/index.js +36 -36
  47. package/dist/operations/index.js +1 -1
  48. package/dist/protection/index.js +1 -1
  49. package/dist/spend/index.js +1 -1
  50. package/dist/ui/404.html +1 -1
  51. package/dist/ui/accept-invitation.html +1 -1
  52. package/dist/ui/access-denied.html +1 -1
  53. package/dist/ui/account/automation.html +6 -6
  54. package/dist/ui/account/security.html +2 -2
  55. package/dist/ui/applications/compose.html +6 -6
  56. package/dist/ui/applications/new.html +2 -2
  57. package/dist/ui/data/backups.html +6 -6
  58. package/dist/ui/data/services.html +6 -6
  59. package/dist/ui/data/volumes.html +6 -6
  60. package/dist/ui/index.html +6 -6
  61. package/dist/ui/infrastructure/topology.html +6 -6
  62. package/dist/ui/integrations.html +2 -2
  63. package/dist/ui/operations/alerts.html +6 -6
  64. package/dist/ui/operations/configuration.html +6 -6
  65. package/dist/ui/operations/jobs.html +6 -6
  66. package/dist/ui/operations/maintenance.html +6 -6
  67. package/dist/ui/operations/observability.html +6 -6
  68. package/dist/ui/operations/previews.html +6 -6
  69. package/dist/ui/operations/queue.html +6 -6
  70. package/dist/ui/operations/regions.html +6 -6
  71. package/dist/ui/operations/releases.html +6 -6
  72. package/dist/ui/operations/spend.html +6 -6
  73. package/dist/ui/operations/workloads.html +5 -5
  74. package/dist/ui/security.html +2 -2
  75. package/dist/ui/server/actions.html +6 -6
  76. package/dist/ui/server/activity.html +2 -2
  77. package/dist/ui/server/capacity.html +6 -6
  78. package/dist/ui/server/database.html +6 -6
  79. package/dist/ui/server/deployments.html +5 -5
  80. package/dist/ui/server/diagnostics.html +2 -2
  81. package/dist/ui/server/firewall.html +6 -6
  82. package/dist/ui/server/fleet.html +6 -6
  83. package/dist/ui/server/logs.html +6 -6
  84. package/dist/ui/server/metrics.html +5 -5
  85. package/dist/ui/server/security.html +2 -2
  86. package/dist/ui/server/services.html +2 -2
  87. package/dist/ui/server/sites.html +6 -6
  88. package/dist/ui/server/ssh-keys.html +6 -6
  89. package/dist/ui/server/team.html +6 -6
  90. package/dist/ui/server/terminal.html +2 -2
  91. package/dist/ui/serverless/alarms.html +5 -5
  92. package/dist/ui/serverless/assets.html +2 -2
  93. package/dist/ui/serverless/cost.html +2 -2
  94. package/dist/ui/serverless/data.html +6 -6
  95. package/dist/ui/serverless/deployments.html +2 -2
  96. package/dist/ui/serverless/firewall.html +1 -1
  97. package/dist/ui/serverless/functions.html +6 -6
  98. package/dist/ui/serverless/logs.html +6 -6
  99. package/dist/ui/serverless/metrics.html +2 -2
  100. package/dist/ui/serverless/queues.html +6 -6
  101. package/dist/ui/serverless/secrets.html +6 -6
  102. package/dist/ui/serverless/traces.html +6 -6
  103. package/dist/ui/serverless.html +6 -6
  104. package/package.json +3 -3
  105. package/dist/bin/chunk-2ahgpy3j.js +0 -2
  106. package/dist/chunk-05qawkra.js +0 -1
  107. package/dist/chunk-3qtce4mm.js +0 -1
  108. package/dist/chunk-3tt5em2c.js +0 -1
  109. package/dist/chunk-a1p70h5d.js +0 -2
  110. package/dist/chunk-jdq95b4h.js +0 -1
  111. package/dist/chunk-wr7tn9j5.js +0 -1
@@ -0,0 +1 @@
1
+ import{Vi,ji,zi,Ki,Ea,va}from"./chunk-zhg1kvw3.js";import"./chunk-sxtgx8fj.js";import"./chunk-kfwg1c6q.js";import"./chunk-t054j0zn.js";import"./chunk-trsaqsgv.js";import"./chunk-t5e5phth.js";import"./chunk-4w8d2mf0.js";export{Ea as deleteStaticSite,ji as deployStaticSite,va as deployStaticSiteFull,Vi as generateStaticSiteTemplate,Ki as invalidateCache,zi as uploadStaticFiles};
@@ -2,5 +2,5 @@ import*as T from"node:crypto";import{existsSync as W,readFileSync as J}from"node
2
2
  `),i="",s="",a="",o;for(let c of r){let h=c.trim();if(!h||h.startsWith("#"))continue;let A=h.match(/^\[([^\]]+)\]$/);if(A){i=A[1];continue}if(i===e){let[m,...f]=h.split("="),b=f.join("=").trim();if(m.trim()==="aws_access_key_id")s=b;else if(m.trim()==="aws_secret_access_key")a=b;else if(m.trim()==="aws_session_token")o=b}}return{accessKeyId:s,secretAccessKey:a,sessionToken:o}}ec2CredentialsCache;async getCredentials(){let t=process.env.AWS_ACCESS_KEY_ID,e=process.env.AWS_SECRET_ACCESS_KEY;if(t&&e)return{accessKeyId:t,secretAccessKey:e,sessionToken:process.env.AWS_SESSION_TOKEN};let r=this.loadCredentialsFromFile();if(r)return r;if(this.ec2CredentialsCache){let i=Date.now();if(this.ec2CredentialsCache.expiration>i+300000)return this.ec2CredentialsCache.credentials}try{let s=await(await fetch("http://169.254.169.254/latest/api/token",{method:"PUT",headers:{"X-aws-ec2-metadata-token-ttl-seconds":"21600"}})).text(),o=await(await fetch("http://169.254.169.254/latest/meta-data/iam/security-credentials/",{headers:{"X-aws-ec2-metadata-token":s}})).text(),h=await(await fetch(`http://169.254.169.254/latest/meta-data/iam/security-credentials/${o}`,{headers:{"X-aws-ec2-metadata-token":s}})).json(),A={accessKeyId:h.AccessKeyId,secretAccessKey:h.SecretAccessKey,sessionToken:h.Token};return this.ec2CredentialsCache={credentials:A,expiration:new Date(h.Expiration).getTime()},A}catch(i){throw Error("AWS credentials not found. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables, or run on an EC2 instance with an IAM role.")}}async request(t){if(t.method==="GET"&&this.config.cacheEnabled&&t.cacheKey){let i=this.getFromCache(t.cacheKey);if(i!==null)return i}let e=t.retries??this.config.maxRetries??3,r=null;for(let i=0;i<=e;i++)try{let s=await this.makeRequest(t);if(t.method==="GET"&&this.config.cacheEnabled&&t.cacheKey)this.setInCache(t.cacheKey,s,t.cacheTTL??this.config.defaultCacheTTL??60000);return s}catch(s){if(r=s,!this.shouldRetry(s))throw s;if(i===e)throw s;let o=this.calculateRetryDelay(i);await this.sleep(o)}throw r||Error("Request failed after retries")}async makeRequest(t){let e=t.credentials||(this.credentials?.accessKeyId?this.credentials:await this.getCredentials());if(!e||!e.accessKeyId||!e.secretAccessKey)throw Error("AWS credentials not provided");let r=this.buildUrl(t),i=this.signRequest(t,e),s=await fetch(r,{method:t.method,headers:i,body:t.body}),a=await s.text();if(!s.ok)throw this.parseError(a,s.status,s.headers);if(!a||a.trim()===""){if(t.returnHeaders)return{body:null,headers:this.headersToObject(s.headers)};return null}if(t.rawResponse){if(t.returnHeaders)return{body:a,headers:this.headersToObject(s.headers)};return a}let o;if(a.startsWith("<"))o=this.parseXmlResponse(a);else try{o=JSON.parse(a)}catch{o=a}if(t.returnHeaders)return{body:o,headers:this.headersToObject(s.headers)};return o}headersToObject(t){let e={};return t.forEach((r,i)=>{e[i]=r}),e}buildUrl(t){let{service:e,region:r,queryParams:i}=t,{path:s}=t,a,o="https";if(e==="s3"){let h=yr({region:r,path:s,bucket:t.bucket,endpoint:this.config.endpoint,forcePathStyle:this.config.forcePathStyle});o=h.protocol,a=h.host,s=h.path}else if(e==="cloudfront")a="cloudfront.amazonaws.com";else if(e==="iam")a="iam.amazonaws.com";else if(e==="route53")a="route53.amazonaws.com";else if(e==="route53domains")a="route53domains.us-east-1.amazonaws.com";else if(e==="ecr")a=`api.ecr.${r}.amazonaws.com`;else if(e==="ses")a=`email.${r}.amazonaws.com`;else a=`${e}.${r}.amazonaws.com`;let c=`${o}://${a}${s}`;if(i&&Object.keys(i).length>0){let h=Object.keys(i).map((A)=>`${this.uriEncode(A)}=${this.uriEncode(i[A])}`).join("&");c+=`?${h}`}return c}signRequest(t,e){let{service:r,region:i,method:s,queryParams:a,body:o}=t,{path:c}=t,h=new Date,A=this.getAmzDate(h),m=this.getDateStamp(h),f;if(r==="s3"){let S=yr({region:i,path:c,bucket:t.bucket,endpoint:this.config.endpoint,forcePathStyle:this.config.forcePathStyle});f=S.host,c=S.path}else if(r==="cloudfront")f="cloudfront.amazonaws.com";else if(r==="iam")f="iam.amazonaws.com";else if(r==="route53")f="route53.amazonaws.com";else if(r==="route53domains")f="route53domains.us-east-1.amazonaws.com";else if(r==="ecr")f=`api.ecr.${i}.amazonaws.com`;else if(r==="ses")f=`email.${i}.amazonaws.com`;else f=`${r}.${i}.amazonaws.com`;let b={host:f,"x-amz-date":A,...t.headers||{}};if(e.sessionToken)b["x-amz-security-token"]=e.sessionToken;if(o){if(!Object.keys(b).some((O)=>O.toLowerCase()==="content-type"))b["content-type"]="application/x-www-form-urlencoded";b["content-length"]=Buffer.byteLength(o).toString()}let p=this.sha256(o||"");b["x-amz-content-sha256"]=p;let C=c,E=a?Object.keys(a).sort().map((S)=>`${this.uriEncode(S)}=${this.uriEncode(a[S])}`).join("&"):"",d=Object.keys(b).sort((S,O)=>S.toLowerCase().localeCompare(O.toLowerCase())),u=d.map((S)=>`${S.toLowerCase()}:${b[S].trim()}
3
3
  `).join(""),g=d.map((S)=>S.toLowerCase()).join(";"),y=[s,C,E,u,g,p].join(`
4
4
  `),N="AWS4-HMAC-SHA256",w=r;if(r==="email")w="ses";let I=`${m}/${i}/${w}/aws4_request`,F=[N,A,I,this.sha256(y)].join(`
5
- `),q=this.getSignatureKey(e.secretAccessKey,m,i,w),U=this.hmac(q,F),j=`${N} Credential=${e.accessKeyId}/${I}, SignedHeaders=${g}, Signature=${U}`;return{...b,Authorization:j}}getAmzDate(t){return t.toISOString().replace(/[:-]|\.\d{3}/g,"")}getDateStamp(t){return t.toISOString().slice(0,10).replace(/-/g,"")}uriEncode(t){return encodeURIComponent(t).replace(/[!'()*]/g,(e)=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}sha256(t){return T.createHash("sha256").update(t,"utf8").digest("hex")}hmac(t,e){return T.createHmac("sha256",t).update(e,"utf8").digest("hex")}getSignatureKey(t,e,r,i){let s=T.createHmac("sha256",`AWS4${t}`).update(e).digest(),a=T.createHmac("sha256",s).update(r).digest(),o=T.createHmac("sha256",a).update(i).digest();return T.createHmac("sha256",o).update("aws4_request").digest()}parseXmlResponse(t){try{let e=this.xmlParser.parse(t);if(e.ErrorResponse)throw this.createErrorFromXml(e.ErrorResponse.Error);let r=Object.keys(e);if(r.length===1)return e[r[0]];return e}catch(e){if(e.code||e.statusCode)throw e;return{}}}parseError(t,e,r){let i=Error();if(i.statusCode=e,i.requestId=r.get("x-amzn-requestid")||r.get("x-amz-request-id")||void 0,t.startsWith("<"))try{let s=this.xmlParser.parse(t);if(s.ErrorResponse?.Error){let a=s.ErrorResponse.Error;return i.code=a.Code,i.message=`AWS Error [${a.Code}]: ${a.Message||"Unknown error"}`,i.type=a.Type,i}if(s.Error)return i.code=s.Error.Code,i.message=`AWS Error [${s.Error.Code}]: ${s.Error.Message||"Unknown error"}`,i}catch{}try{let s=JSON.parse(t);if(s.__type||s.code)return i.code=s.__type||s.code,i.message=`AWS Error [${i.code}]: ${s.message||s.Message||"Unknown error"}`,i}catch{}return i.message=`AWS API Error (${e}): ${t}`,i}createErrorFromXml(t){let e=Error();return e.code=t.Code,e.message=`AWS Error [${t.Code}]: ${t.Message||"Unknown error"}`,e.type=t.Type,e}isRetryableError(t){return["RequestTimeout","RequestTimeoutException","PriorRequestNotComplete","ConnectionError","ThrottlingException","Throttling","TooManyRequestsException","ProvisionedThroughputExceededException","RequestLimitExceeded","BandwidthLimitExceeded","SlowDown","ServiceUnavailable","ServiceUnavailableException","InternalError","InternalFailure","InternalServerError","InternalServiceException","TransientError","TransientFailure","IDPCommunicationErrorException","NetworkError","ConnectionRefusedException","EC2ThrottledException","503 Slow Down","500 InternalError"].includes(t)}isRetryableStatusCode(t){return t>=500||t===429}shouldRetry(t){if(t.name==="FetchError"||t.name==="TypeError"||t.code==="ECONNRESET")return!0;if(t.code&&this.isRetryableError(t.code))return!0;if(t.statusCode&&this.isRetryableStatusCode(t.statusCode))return!0;if(t.statusCode&&t.statusCode>=400&&t.statusCode<500&&t.statusCode!==429)return!1;if(t.statusCode)return!1;return!0}calculateRetryDelay(t){let e=this.config.retryDelay??1000,r=30000,i=Math.min(e*2**t,30000),s=Math.random()*0.3*i;return i+s}sleep(t){return new Promise((e)=>setTimeout(e,t))}getFromCache(t){let e=this.cache.get(t);if(!e)return null;if(Date.now()>e.expires)return this.cache.delete(t),null;return e.data}setInCache(t,e,r){this.cache.set(t,{data:e,expires:Date.now()+r})}clearCache(){this.cache.clear()}clearExpiredCache(){let t=Date.now();for(let[e,r]of this.cache.entries())if(t>r.expires)this.cache.delete(e)}}function l(t){let e={};for(let[r,i]of Object.entries(t)){if(i===void 0||i===null)continue;if(Array.isArray(i))i.forEach((s,a)=>{e[`${r}.${a+1}`]=String(s)});else if(typeof i==="object")for(let[s,a]of Object.entries(i))e[`${r}.${s}`]=String(a);else e[r]=String(i)}return e}function ah(){let t=process.env.AWS_ACCESS_KEY_ID,e=process.env.AWS_SECRET_ACCESS_KEY,r=t==="",i=e==="";if(t&&e)return{source:"env",emptyEnvKey:r,emptyEnvSecret:i,description:"environment variables (AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY)"};let s=process.env.AWS_PROFILE||"default",a=process.env.AWS_SHARED_CREDENTIALS_FILE||K(B(),".aws","credentials");if(W(a))return{source:"file",profile:s,emptyEnvKey:r,emptyEnvSecret:i,description:`~/.aws/credentials (profile: ${s})`};return{source:"ec2",emptyEnvKey:r,emptyEnvSecret:i,description:"EC2 instance metadata service (IMDSv2)"}}
6
- export{yr,n,l,ah};
5
+ `),q=this.getSignatureKey(e.secretAccessKey,m,i,w),U=this.hmac(q,F),j=`${N} Credential=${e.accessKeyId}/${I}, SignedHeaders=${g}, Signature=${U}`;return{...b,Authorization:j}}getAmzDate(t){return t.toISOString().replace(/[:-]|\.\d{3}/g,"")}getDateStamp(t){return t.toISOString().slice(0,10).replace(/-/g,"")}uriEncode(t){return encodeURIComponent(t).replace(/[!'()*]/g,(e)=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}sha256(t){return T.createHash("sha256").update(t,"utf8").digest("hex")}hmac(t,e){return T.createHmac("sha256",t).update(e,"utf8").digest("hex")}getSignatureKey(t,e,r,i){let s=T.createHmac("sha256",`AWS4${t}`).update(e).digest(),a=T.createHmac("sha256",s).update(r).digest(),o=T.createHmac("sha256",a).update(i).digest();return T.createHmac("sha256",o).update("aws4_request").digest()}parseXmlResponse(t){try{let e=this.xmlParser.parse(t);if(e.ErrorResponse)throw this.createErrorFromXml(e.ErrorResponse.Error);let r=Object.keys(e);if(r.length===1)return e[r[0]];return e}catch(e){if(e.code||e.statusCode)throw e;return{}}}parseError(t,e,r){let i=Error();if(i.statusCode=e,i.requestId=r.get("x-amzn-requestid")||r.get("x-amz-request-id")||void 0,t.startsWith("<"))try{let s=this.xmlParser.parse(t);if(s.ErrorResponse?.Error){let a=s.ErrorResponse.Error;return i.code=a.Code,i.message=`AWS Error [${a.Code}]: ${a.Message||"Unknown error"}`,i.type=a.Type,i}if(s.Error)return i.code=s.Error.Code,i.message=`AWS Error [${s.Error.Code}]: ${s.Error.Message||"Unknown error"}`,i}catch{}try{let s=JSON.parse(t);if(s.__type||s.code)return i.code=s.__type||s.code,i.message=`AWS Error [${i.code}]: ${s.message||s.Message||"Unknown error"}`,i}catch{}return i.message=`AWS API Error (${e}): ${t}`,i}createErrorFromXml(t){let e=Error();return e.code=t.Code,e.message=`AWS Error [${t.Code}]: ${t.Message||"Unknown error"}`,e.type=t.Type,e}isRetryableError(t){return["RequestTimeout","RequestTimeoutException","PriorRequestNotComplete","ConnectionError","ThrottlingException","Throttling","TooManyRequestsException","ProvisionedThroughputExceededException","RequestLimitExceeded","BandwidthLimitExceeded","SlowDown","ServiceUnavailable","ServiceUnavailableException","InternalError","InternalFailure","InternalServerError","InternalServiceException","TransientError","TransientFailure","IDPCommunicationErrorException","NetworkError","ConnectionRefusedException","EC2ThrottledException","503 Slow Down","500 InternalError"].includes(t)}isRetryableStatusCode(t){return t>=500||t===429}shouldRetry(t){if(t.name==="FetchError"||t.name==="TypeError"||t.code==="ECONNRESET")return!0;if(t.code&&this.isRetryableError(t.code))return!0;if(t.statusCode&&this.isRetryableStatusCode(t.statusCode))return!0;if(t.statusCode&&t.statusCode>=400&&t.statusCode<500&&t.statusCode!==429)return!1;if(t.statusCode)return!1;return!0}calculateRetryDelay(t){let e=this.config.retryDelay??1000,r=30000,i=Math.min(e*2**t,30000),s=Math.random()*0.3*i;return i+s}sleep(t){return new Promise((e)=>setTimeout(e,t))}getFromCache(t){let e=this.cache.get(t);if(!e)return null;if(Date.now()>e.expires)return this.cache.delete(t),null;return e.data}setInCache(t,e,r){this.cache.set(t,{data:e,expires:Date.now()+r})}clearCache(){this.cache.clear()}clearExpiredCache(){let t=Date.now();for(let[e,r]of this.cache.entries())if(t>r.expires)this.cache.delete(e)}}function l(t){let e={};for(let[r,i]of Object.entries(t)){if(i===void 0||i===null)continue;if(Array.isArray(i))i.forEach((s,a)=>{e[`${r}.${a+1}`]=String(s)});else if(typeof i==="object")for(let[s,a]of Object.entries(i))e[`${r}.${s}`]=String(a);else e[r]=String(i)}return e}function dh(){let t=process.env.AWS_ACCESS_KEY_ID,e=process.env.AWS_SECRET_ACCESS_KEY,r=t==="",i=e==="";if(t&&e)return{source:"env",emptyEnvKey:r,emptyEnvSecret:i,description:"environment variables (AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY)"};let s=process.env.AWS_PROFILE||"default",a=process.env.AWS_SHARED_CREDENTIALS_FILE||K(B(),".aws","credentials");if(W(a))return{source:"file",profile:s,emptyEnvKey:r,emptyEnvSecret:i,description:`~/.aws/credentials (profile: ${s})`};return{source:"ec2",emptyEnvKey:r,emptyEnvSecret:i,description:"EC2 instance metadata service (IMDSv2)"}}
6
+ export{yr,n,l,dh};
@@ -1,6 +1,6 @@
1
- var Xc={newConnectionsPerSecond:50,concurrentPerSource:100,synPerSecond:2000,burst:100,icmpPerSecond:5,banSeconds:600};function h(e){return{...Xc,...e.thresholds}}var _=/^(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{1,2})?$|^[0-9a-f:]+(?:\/\d{1,3})?$/i;function Br(e){if(!_.test(e))return!1;let[t,n]=e.split("/");if(t.includes(":"))return n==null||Number(n)>=0&&Number(n)<=128;let s=t.split(".");if(s.length!==4||s.some((a)=>Number(a)>255||a===""))return!1;return n==null||Number(n)>=0&&Number(n)<=32}function f(e){return[...new Set((e??[]).map((t)=>t.trim()).filter(Br))]}function y(e){let t=(e??[80,443]).filter((n)=>Number.isInteger(n)&&n>=1&&n<=65535);return[...new Set(t)].sort((n,s)=>n-s)}function Yc(e={}){let t=h(e);return{"net.ipv4.tcp_syncookies":"1","net.ipv4.tcp_max_syn_backlog":String(Math.max(4096,t.synPerSecond*4)),"net.ipv4.tcp_synack_retries":"2","net.ipv4.tcp_abort_on_overflow":"1","net.ipv4.tcp_fin_timeout":"15","net.ipv4.tcp_keepalive_time":"300","net.ipv4.tcp_keepalive_intvl":"30","net.ipv4.tcp_keepalive_probes":"3","net.core.somaxconn":"4096","net.core.netdev_max_backlog":"16384","net.ipv4.conf.all.rp_filter":"1","net.ipv4.conf.default.rp_filter":"1","net.ipv4.conf.all.accept_source_route":"0","net.ipv4.conf.all.accept_redirects":"0","net.ipv4.conf.all.send_redirects":"0","net.ipv6.conf.all.accept_redirects":"0","net.ipv6.conf.all.accept_source_route":"0","net.ipv4.icmp_echo_ignore_broadcasts":"1","net.ipv4.icmp_ignore_bogus_error_responses":"1","net.netfilter.nf_conntrack_max":"262144","net.netfilter.nf_conntrack_tcp_timeout_established":"3600"}}function Zc(e={}){let t=["# Managed by ts-cloud. Edits are overwritten on the next deploy.","# Network hardening against L3/L4 floods.",""];for(let[n,s]of Object.entries(Yc(e)))t.push(`${n} = ${s}`);return`${t.join(`
1
+ var Zc={newConnectionsPerSecond:50,concurrentPerSource:100,synPerSecond:2000,burst:100,icmpPerSecond:5,banSeconds:600};function h(e){return{...Zc,...e.thresholds}}var _=/^(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{1,2})?$|^[0-9a-f:]+(?:\/\d{1,3})?$/i;function Br(e){if(!_.test(e))return!1;let[t,n]=e.split("/");if(t.includes(":"))return n==null||Number(n)>=0&&Number(n)<=128;let s=t.split(".");if(s.length!==4||s.some((a)=>Number(a)>255||a===""))return!1;return n==null||Number(n)>=0&&Number(n)<=32}function f(e){return[...new Set((e??[]).map((t)=>t.trim()).filter(Br))]}function y(e){let t=(e??[80,443]).filter((n)=>Number.isInteger(n)&&n>=1&&n<=65535);return[...new Set(t)].sort((n,s)=>n-s)}function ed(e={}){let t=h(e);return{"net.ipv4.tcp_syncookies":"1","net.ipv4.tcp_max_syn_backlog":String(Math.max(4096,t.synPerSecond*4)),"net.ipv4.tcp_synack_retries":"2","net.ipv4.tcp_abort_on_overflow":"1","net.ipv4.tcp_fin_timeout":"15","net.ipv4.tcp_keepalive_time":"300","net.ipv4.tcp_keepalive_intvl":"30","net.ipv4.tcp_keepalive_probes":"3","net.core.somaxconn":"4096","net.core.netdev_max_backlog":"16384","net.ipv4.conf.all.rp_filter":"1","net.ipv4.conf.default.rp_filter":"1","net.ipv4.conf.all.accept_source_route":"0","net.ipv4.conf.all.accept_redirects":"0","net.ipv4.conf.all.send_redirects":"0","net.ipv6.conf.all.accept_redirects":"0","net.ipv6.conf.all.accept_source_route":"0","net.ipv4.icmp_echo_ignore_broadcasts":"1","net.ipv4.icmp_ignore_bogus_error_responses":"1","net.netfilter.nf_conntrack_max":"262144","net.netfilter.nf_conntrack_tcp_timeout_established":"3600"}}function td(e={}){let t=["# Managed by ts-cloud. Edits are overwritten on the next deploy.","# Network hardening against L3/L4 floods.",""];for(let[n,s]of Object.entries(ed(e)))t.push(`${n} = ${s}`);return`${t.join(`
2
2
  `)}
3
- `}function ed(e={}){let t=h(e),n=y(e.ports),s=f(e.allowlist),a=f(e.blocklist),l=e.monitorOnly?"counter":"counter drop",i=e.originProtection?.enabled?f(e.originProtection.cdnRanges):[],c=s.filter((r)=>!r.includes(":")),p=s.filter((r)=>r.includes(":")),u=a.filter((r)=>!r.includes(":")),o=["#!/usr/sbin/nft -f","# Managed by ts-cloud. Edits are overwritten on the next deploy.","","table inet ts_cloud_ddos","delete table inet ts_cloud_ddos","","table inet ts_cloud_ddos {"," # Sources that tripped a limit, with a timeout so a ban self-expires.",` set banned4 { type ipv4_addr; flags timeout; timeout ${t.banSeconds}s; }`,` set banned6 { type ipv6_addr; flags timeout; timeout ${t.banSeconds}s; }`];if(c.length>0)o.push(` set allow4 { type ipv4_addr; flags interval; elements = { ${c.join(", ")} } }`);if(p.length>0)o.push(` set allow6 { type ipv6_addr; flags interval; elements = { ${p.join(", ")} } }`);if(u.length>0)o.push(` set block4 { type ipv4_addr; flags interval; elements = { ${u.join(", ")} } }`);if(i.length>0)o.push(` set cdn4 { type ipv4_addr; flags interval; elements = { ${i.filter((r)=>!r.includes(":")).join(", ")} } }`);if(o.push(""," chain input {"," type filter hook input priority -150; policy accept;",""," # Established traffic is already paid for; never re-inspect it."," ct state established,related accept"," iif lo accept",""," # Invalid packets are never legitimate and are cheap to drop early."," ct state invalid counter drop"),c.length>0)o.push(" ip saddr @allow4 accept");if(p.length>0)o.push(" ip6 saddr @allow6 accept");if(u.length>0)o.push(" ip saddr @block4 counter drop");if(o.push(" ip saddr @banned4 counter drop"," ip6 saddr @banned6 counter drop",""),o.push(" # Nonsense TCP flag combinations: scanners and stack fingerprinting."," tcp flags & (fin|syn) == (fin|syn) counter drop"," tcp flags & (syn|rst) == (syn|rst) counter drop"," tcp flags & (fin|rst) == (fin|rst) counter drop"," tcp flags & (fin|ack) == fin counter drop"," tcp flags & (syn|fin|ack|rst|psh|urg) == 0x0 counter drop",""," # Ping stays usable, ping floods do not.",` ip protocol icmp icmp type echo-request limit rate ${t.icmpPerSecond}/second burst ${t.burst} packets accept`," ip protocol icmp icmp type echo-request counter drop",""),n.length>0){let r=n.join(", ");if(o.push(" # Platform-wide SYN ceiling. Above it the kernel falls back to cookies.",` tcp dport { ${r} } ct state new limit rate ${t.synPerSecond}/second burst ${t.burst} packets accept`,""," # Per-source new-connection rate. This is what stops one host hammering.",` tcp dport { ${r} } ct state new meter conn_rate4 { ip saddr limit rate over ${t.newConnectionsPerSecond}/second burst ${t.burst} packets } add @banned4 { ip saddr } ${l}`,` tcp dport { ${r} } ct state new meter conn_rate6 { ip6 saddr limit rate over ${t.newConnectionsPerSecond}/second burst ${t.burst} packets } add @banned6 { ip6 saddr } ${l}`,""," # Concurrency ceiling per source: the slow-loris defence.",` tcp dport { ${r} } ct state new meter conn_count4 { ip saddr ct count over ${t.concurrentPerSource} } ${l}`,` tcp dport { ${r} } ct state new meter conn_count6 { ip6 saddr ct count over ${t.concurrentPerSource} } ${l}`,""),i.length>0)o.push(" # Origin protection: reject traffic that skipped the CDN and came"," # straight to the box, which is how an attacker bypasses the edge.",` tcp dport { ${r} } ip saddr != @cdn4 counter drop`,"")}return o.push(" }","}",""),o.join(`
3
+ `}function rd(e={}){let t=h(e),n=y(e.ports),s=f(e.allowlist),a=f(e.blocklist),l=e.monitorOnly?"counter":"counter drop",i=e.originProtection?.enabled?f(e.originProtection.cdnRanges):[],c=s.filter((r)=>!r.includes(":")),p=s.filter((r)=>r.includes(":")),u=a.filter((r)=>!r.includes(":")),o=["#!/usr/sbin/nft -f","# Managed by ts-cloud. Edits are overwritten on the next deploy.","","table inet ts_cloud_ddos","delete table inet ts_cloud_ddos","","table inet ts_cloud_ddos {"," # Sources that tripped a limit, with a timeout so a ban self-expires.",` set banned4 { type ipv4_addr; flags timeout; timeout ${t.banSeconds}s; }`,` set banned6 { type ipv6_addr; flags timeout; timeout ${t.banSeconds}s; }`];if(c.length>0)o.push(` set allow4 { type ipv4_addr; flags interval; elements = { ${c.join(", ")} } }`);if(p.length>0)o.push(` set allow6 { type ipv6_addr; flags interval; elements = { ${p.join(", ")} } }`);if(u.length>0)o.push(` set block4 { type ipv4_addr; flags interval; elements = { ${u.join(", ")} } }`);if(i.length>0)o.push(` set cdn4 { type ipv4_addr; flags interval; elements = { ${i.filter((r)=>!r.includes(":")).join(", ")} } }`);if(o.push(""," chain input {"," type filter hook input priority -150; policy accept;",""," # Established traffic is already paid for; never re-inspect it."," ct state established,related accept"," iif lo accept",""," # Invalid packets are never legitimate and are cheap to drop early."," ct state invalid counter drop"),c.length>0)o.push(" ip saddr @allow4 accept");if(p.length>0)o.push(" ip6 saddr @allow6 accept");if(u.length>0)o.push(" ip saddr @block4 counter drop");if(o.push(" ip saddr @banned4 counter drop"," ip6 saddr @banned6 counter drop",""),o.push(" # Nonsense TCP flag combinations: scanners and stack fingerprinting."," tcp flags & (fin|syn) == (fin|syn) counter drop"," tcp flags & (syn|rst) == (syn|rst) counter drop"," tcp flags & (fin|rst) == (fin|rst) counter drop"," tcp flags & (fin|ack) == fin counter drop"," tcp flags & (syn|fin|ack|rst|psh|urg) == 0x0 counter drop",""," # Ping stays usable, ping floods do not.",` ip protocol icmp icmp type echo-request limit rate ${t.icmpPerSecond}/second burst ${t.burst} packets accept`," ip protocol icmp icmp type echo-request counter drop",""),n.length>0){let r=n.join(", ");if(o.push(" # Platform-wide SYN ceiling. Above it the kernel falls back to cookies.",` tcp dport { ${r} } ct state new limit rate ${t.synPerSecond}/second burst ${t.burst} packets accept`,""," # Per-source new-connection rate. This is what stops one host hammering.",` tcp dport { ${r} } ct state new meter conn_rate4 { ip saddr limit rate over ${t.newConnectionsPerSecond}/second burst ${t.burst} packets } add @banned4 { ip saddr } ${l}`,` tcp dport { ${r} } ct state new meter conn_rate6 { ip6 saddr limit rate over ${t.newConnectionsPerSecond}/second burst ${t.burst} packets } add @banned6 { ip6 saddr } ${l}`,""," # Concurrency ceiling per source: the slow-loris defence.",` tcp dport { ${r} } ct state new meter conn_count4 { ip saddr ct count over ${t.concurrentPerSource} } ${l}`,` tcp dport { ${r} } ct state new meter conn_count6 { ip6 saddr ct count over ${t.concurrentPerSource} } ${l}`,""),i.length>0)o.push(" # Origin protection: reject traffic that skipped the CDN and came"," # straight to the box, which is how an attacker bypasses the edge.",` tcp dport { ${r} } ip saddr != @cdn4 counter drop`,"")}return o.push(" }","}",""),o.join(`
4
4
  `)}function mi(e={}){return`#!/usr/bin/env bash
5
5
  # Managed by ts-cloud. Installs L3/L4 flood mitigation.
6
6
  set -euo pipefail
@@ -13,11 +13,11 @@ fi
13
13
 
14
14
  install -d -m 0755 /etc/ts-cloud /etc/nftables.d
15
15
  cat > /etc/sysctl.d/90-ts-cloud-ddos.conf <<'SYSCTL_EOF'
16
- ${Zc(e)}SYSCTL_EOF
16
+ ${td(e)}SYSCTL_EOF
17
17
  sysctl --system >/dev/null
18
18
 
19
19
  cat > /etc/nftables.d/ts-cloud-ddos.nft.new <<'NFT_EOF'
20
- ${ed(e)}NFT_EOF
20
+ ${rd(e)}NFT_EOF
21
21
 
22
22
  # Syntax-check before applying: a bad ruleset would leave the box unprotected.
23
23
  if ! nft -c -f /etc/nftables.d/ts-cloud-ddos.nft.new; then
@@ -40,5 +40,5 @@ include "/etc/nftables.d/ts-cloud-ddos.nft"
40
40
  fi
41
41
  systemctl enable nftables >/dev/null 2>&1 || true
42
42
  echo "ts-cloud: L3/L4 mitigation active"
43
- `}var b=["off","monitor","rate_limit","challenge","lockdown"];function Tp(e,t=[]){let n=[],s=Math.max(1,e.baselineRequestsPerSecond),a=e.requestsPerSecond/s,l=0,i=(g,v)=>{n.push(v),l=Math.max(l,b.indexOf(g))},c=a>=3;if(c)i("monitor",`Traffic is ${a.toFixed(1)}x the baseline.`);let p=e.topSourceShare>=0.25,u=e.errorRate>=0.25,o=(e.suspiciousAgentShare??0)>=0.5,r=e.uniqueSources>0&&e.requestsPerSecond/e.uniqueSources>=50;if(c&&p)i("rate_limit",`One source accounts for ${(e.topSourceShare*100).toFixed(0)}% of traffic.`);if(c&&r)i("rate_limit","Request rate per unique source is far above what a browser produces.");if(c&&u)i("challenge",`Error rate is ${(e.errorRate*100).toFixed(0)}% under load.`);if(c&&o)i("challenge","Most requests carry no recognisable browser agent.");if(a>=20&&(p||u||o||r))i("lockdown",`Traffic is ${a.toFixed(0)}x the baseline with attack-shaped characteristics.`);if(!c&&e.topSourceShare>=0.6&&e.requestsPerSecond>s)i("rate_limit","A single source dominates traffic without an overall surge.");let d=b[l],m={off:1,monitor:1,rate_limit:0.5,challenge:0.25,lockdown:0.1}[d];return{level:d,reasons:n,rateLimitFactor:m,challengeEnabled:d==="challenge"||d==="lockdown",staticOnly:d==="lockdown",banCandidates:d==="off"||d==="monitor"?[]:f(t)}}function xr(e,t){return Math.max(1,Math.floor(e*t.rateLimitFactor))}
44
- export{Xc,Br,Yc,Zc,ed,mi,Tp,xr};
43
+ `}var b=["off","monitor","rate_limit","challenge","lockdown"];function Rp(e,t=[]){let n=[],s=Math.max(1,e.baselineRequestsPerSecond),a=e.requestsPerSecond/s,l=0,i=(g,v)=>{n.push(v),l=Math.max(l,b.indexOf(g))},c=a>=3;if(c)i("monitor",`Traffic is ${a.toFixed(1)}x the baseline.`);let p=e.topSourceShare>=0.25,u=e.errorRate>=0.25,o=(e.suspiciousAgentShare??0)>=0.5,r=e.uniqueSources>0&&e.requestsPerSecond/e.uniqueSources>=50;if(c&&p)i("rate_limit",`One source accounts for ${(e.topSourceShare*100).toFixed(0)}% of traffic.`);if(c&&r)i("rate_limit","Request rate per unique source is far above what a browser produces.");if(c&&u)i("challenge",`Error rate is ${(e.errorRate*100).toFixed(0)}% under load.`);if(c&&o)i("challenge","Most requests carry no recognisable browser agent.");if(a>=20&&(p||u||o||r))i("lockdown",`Traffic is ${a.toFixed(0)}x the baseline with attack-shaped characteristics.`);if(!c&&e.topSourceShare>=0.6&&e.requestsPerSecond>s)i("rate_limit","A single source dominates traffic without an overall surge.");let d=b[l],m={off:1,monitor:1,rate_limit:0.5,challenge:0.25,lockdown:0.1}[d];return{level:d,reasons:n,rateLimitFactor:m,challengeEnabled:d==="challenge"||d==="lockdown",staticOnly:d==="lockdown",banCandidates:d==="off"||d==="monitor"?[]:f(t)}}function xr(e,t){return Math.max(1,Math.floor(e*t.rateLimitFactor))}
44
+ export{Zc,Br,ed,td,rd,mi,Rp,xr};
@@ -1,22 +1,22 @@
1
- import{ot,Yn,Zn,ei}from"./chunk-ds92qg3g.js";function S(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ch(t,e="/var/www"){let n=`${e}/${t}-`;return["set -u",`for TS_CLOUD_DIR in ${n}*; do`,' [ -d "$TS_CLOUD_DIR" ] || continue',' [ -d "$TS_CLOUD_DIR/releases" ] || continue',` TS_CLOUD_SITE="\${TS_CLOUD_DIR#${n}}"`," TS_CLOUD_ACTIVE=no",` for TS_CLOUD_UNIT in $(ls /etc/systemd/system/ 2>/dev/null | grep -E "^${S(t)}-$TS_CLOUD_SITE[-@.]" || true); do`,' systemctl is-active "$TS_CLOUD_UNIT" >/dev/null 2>&1 && TS_CLOUD_ACTIVE=yes'," done",' TS_CLOUD_SIZE="$(du -sh "$TS_CLOUD_DIR" 2>/dev/null | cut -f1)"',' echo "site:$TS_CLOUD_SITE:$TS_CLOUD_ACTIVE:${TS_CLOUD_SIZE:-?}"',"done","exit 0"]}function dh(t){if(!t)return[];let e=[];for(let n of t.split(`
2
- `)){let r=n.trim();if(!r.startsWith("site:"))continue;let[,s,o,i]=r.split(":");if(!s||o!=="no")continue;e.push({name:s,size:i||"?"})}return e}function lh(t,e,n){let r=t.map((o)=>` ${e}-${o.name} (${o.size})`).join(`
1
+ import{ot,Yn,Zn,ei}from"./chunk-tg6yasej.js";function S(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function lh(t,e="/var/www"){let n=`${e}/${t}-`;return["set -u",`for TS_CLOUD_DIR in ${n}*; do`,' [ -d "$TS_CLOUD_DIR" ] || continue',' [ -d "$TS_CLOUD_DIR/releases" ] || continue',` TS_CLOUD_SITE="\${TS_CLOUD_DIR#${n}}"`," TS_CLOUD_ACTIVE=no",` for TS_CLOUD_UNIT in $(ls /etc/systemd/system/ 2>/dev/null | grep -E "^${S(t)}-$TS_CLOUD_SITE[-@.]" || true); do`,' systemctl is-active "$TS_CLOUD_UNIT" >/dev/null 2>&1 && TS_CLOUD_ACTIVE=yes'," done",' TS_CLOUD_SIZE="$(du -sh "$TS_CLOUD_DIR" 2>/dev/null | cut -f1)"',' echo "site:$TS_CLOUD_SITE:$TS_CLOUD_ACTIVE:${TS_CLOUD_SIZE:-?}"',"done","exit 0"]}function uh(t){if(!t)return[];let e=[];for(let n of t.split(`
2
+ `)){let r=n.trim();if(!r.startsWith("site:"))continue;let[,s,o,i]=r.split(":");if(!s||o!=="no")continue;e.push({name:s,size:i||"?"})}return e}function ph(t,e,n){let r=t.map((o)=>` ${e}-${o.name} (${o.size})`).join(`
3
3
  `),s=t.length===1?"it":"them";return`This server still holds ${t.length} site tree${t.length===1?"":"s"} with nothing running for ${s}:
4
4
  ${r}
5
5
  `+"A site moved off this box keeps its files here on purpose — they are the rollback, and they are what makes "+`the move reversible until this server is destroyed. Destroying it now discards that.
6
- Verify the site is serving from its new home first, then re-run with ${n} to destroy it anyway.`}var _u="ts-cloud/project",Ou="ts-cloud/environment",Lu="ts-cloud/role";function d(t){return typeof t==="string"&&t.trim()?t.trim():void 0}function h(t){if(typeof t==="string")return d(t);if(t&&typeof t==="object")return d(t.name);return}function uh(t){let e={};for(let[n,r]of Object.entries(t?.labels??{}))if(typeof r==="string")e[n]=r;return{id:String(t?.id??""),name:d(t?.name)??"(unnamed)",status:d(t?.status)??"unknown",ipv4:d(t?.public_net?.ipv4?.ip)??d(t?.ipv4),ipv6:d(t?.public_net?.ipv6?.ip)??d(t?.ipv6),type:d(t?.server_type?.name)??d(t?.type),location:h(t?.location)??h(t?.datacenter?.location)??h(t?.datacenter),labels:e,project:d(e[_u]),environment:d(e[Ou]),role:d(e[Lu])}}function w(t){return t.slug?.trim()||"app"}function $u(t){let e=[];for(let n of t){let r=w(n);for(let s of n.proxies??[]){let o=d(s?.to);if(!o)continue;e.push({slug:r,host:o,path:d(s?.path)??"/",...x(s)})}}return e.sort((n,r)=>n.slug.localeCompare(r.slug)||n.host.localeCompare(r.host)||n.path.localeCompare(r.path))}function x(t){let e=t?.from;if(typeof e==="string"&&e.trim())return{target:e.trim(),kind:"app"};if(Array.isArray(e)&&e.length>0)return{target:e.filter((s)=>typeof s==="string").join(", "),kind:"app"};let n=t?.static;if(typeof n==="string"&&n.trim())return{target:n.trim(),kind:"static"};if(n&&typeof n==="object"&&d(n.dir))return{target:d(n.dir),kind:"static"};let r=typeof t?.redirect==="string"?d(t.redirect):d(t?.redirect?.to);if(r)return{target:r,kind:"redirect"};return{target:"(no upstream)",kind:"unknown"}}function Mu(t){let e=new Map;for(let n of t){let r=e.get(n.slug);if(r)r.push(n);else e.set(n.slug,[n])}return[...e.entries()].map(([n,r])=>({slug:n,routes:r})).sort((n,r)=>r.routes.length-n.routes.length||n.slug.localeCompare(r.slug))}async function ph(t,e,n=ot){if(!t.ipv4)return{server:t.name,routes:[],unavailable:"no public IPv4 address to reach it on"};if(t.status!=="running")return{server:t.name,ip:t.ipv4,routes:[],unavailable:`server is ${t.status}`};try{let r=await e(t.ipv4,Zn(n));if(r.code!==0){let s=r.stderr.trim().split(`
7
- `)[0]||`remote command exited ${r.code}`;return{server:t.name,ip:t.ipv4,routes:[],unavailable:s}}return{server:t.name,ip:t.ipv4,routes:$u(ei(r.stdout))}}catch(r){let s=r instanceof Error?r.message.split(`
8
- `)[0]:String(r);return{server:t.name,ip:t.ipv4,routes:[],unavailable:s}}}function u(t,e){let n=e==="/"?"/":e.replace(/\/+$/,"");return`${t.toLowerCase()}${n||"/"}`}function gh(t,e,n){let r=new Set(e.filter((a)=>a.slug===n).map((a)=>u(a.host,a.path))),s=[],o=[],i=[];for(let a of t)if(a.loopbackOnly)i.push(a);else if(a.domain&&r.has(u(a.domain,a.path)))s.push(a);else o.push(a);return{present:s,absent:o,loopback:i,foreign:e.filter((a)=>a.slug!==n)}}function Fu(t,e,n){let r=new Set;for(let s of e)for(let o of s.routes)if(o.slug===n)r.add(u(o.host,o.path));return t.filter((s)=>!s.loopbackOnly&&s.domain!==void 0&&!r.has(u(s.domain,s.path)))}function mh(t){let{slug:e,servers:n,probes:r,declared:s}=t,o=[];if(o.push(n.length===0?"No servers found.":`${n.length} server${n.length===1?"":"s"}:`),n.length>0)o.push("");let i=new Map(r.map((a)=>[a.server,a]));for(let a of n){let p=[a.ipv4,a.type,a.location,a.status].filter(Boolean);o.push(` ${a.name} ${p.join(" ")}`),o.push(` ${k(a)}`);let c=i.get(a.name);if(!c)o.push(" not probed, so co-tenants on this box are not listed");else if(c.unavailable)o.push(` could not read ${ot}: ${c.unavailable}`);else o.push(...P(c,e));o.push("")}return o.push(...C(t)),o}function k(t){if(!t.project)return"no ts-cloud labels: provisioned outside ts-cloud, or by a version that did not label boxes";let e=[t.environment,t.role&&`role ${t.role}`].filter(Boolean).join(", ");return`owned by '${t.project}'${e?` (${e})`:""}`}function P(t,e){let n=Mu(t.routes);if(n.length===0)return[` serves nothing: ${ot} is empty or absent`];let r=[` serves ${t.routes.length} route${t.routes.length===1?"":"s"} for ${n.length} project${n.length===1?"":"s"}:`];for(let s of n){r.push(` ${s.slug}${s.slug===e?" (this project)":""}`);for(let o of s.routes)r.push(` ${o.host}${o.path==="/"?"/":o.path} -> ${O(o)}`)}return r}function O(t){if(t.kind==="redirect")return`redirect to ${t.target}`;if(t.kind==="static")return`static ${t.target}`;return t.target}function C(t){let{slug:e,declared:n,probes:r,servers:s}=t;if(n.length===0)return[`This project ('${e}') declares no sites.`];let o=[`This project ('${e}') declares ${n.length} site${n.length===1?"":"s"}: `+n.map((c)=>c.name).join(", ")],i=n.filter((c)=>c.loopbackOnly);if(i.length>0)o.push(` ${i.length} with no domain, so the gateway never routes ${i.length===1?"it":"them"} (reached through another site's proxy): ${i.map((c)=>c.name).join(", ")}`);let a=r.filter((c)=>!c.unavailable);if(a.length===0)return o.push(" Nothing to reconcile them against: no box reported what it serves."),o;let p=Fu(n,a,e);if(o.push(` ${n.length-i.length-p.length} routed by a box above`),p.length>0){o.push(` ${p.length} not routed by any box above: ${p.map((b)=>b.name).join(", ")}`);let c=r.length-a.length,g=s.length-r.length;if(c>0)o.push(` Either they were never deployed, or they are on one of the ${c} server${c===1?"":"s"} that could not be read.`);else if(g>0)o.push(` Either they were never deployed, or they are on one of the ${g} server${g===1?"":"s"} this run did not probe.`);else o.push(" Either they were never deployed, or they are on a server this listing did not cover.")}return o}async function hh(t){let e=[];for(let n of t.steps)try{e.push({step:n,state:await n.satisfied()?"satisfied":"pending"})}catch(r){e.push({step:n,state:"unknown",reason:r instanceof Error?r.message:String(r)})}return e}function gc(t){return t.filter((e)=>e.state!=="satisfied")}function Uu(t){return gc(t).some((e)=>e.step.destructive===!0)}function fh(t,e){let n=gc(e),r=[`${t.operation} ${t.target}`];if(n.length===0)return r.push(" Nothing to do — every step is already satisfied."),r;for(let{step:o,state:i,reason:a}of e){let p=i==="satisfied"?"ok ":i==="unknown"?"? ":"→ ",c=[o.destructive?"DESTRUCTIVE":"",i==="satisfied"?"already done":""].filter(Boolean);if(r.push(` ${p}${o.title}${c.length>0?` [${c.join(", ")}]`:""}`),o.change)r.push(` ${o.change.from} → ${o.change.to}`);if(a)r.push(` could not check: ${a}`)}let s=n.filter((o)=>o.step.destructive).length;return r.push(` ${n.length} step(s) would run`+(s>0?`, ${s} irreversible — re-run with --confirm ${t.target}`:"")),r}async function Ah(t,e,n={}){let r={operation:t.operation,target:t.target,steps:[],success:!0};if(Uu(e)&&n.confirm!==t.target)throw Error(`${t.operation} includes an irreversible step. Re-run with --confirm ${t.target} to authorize it.`);for(let{step:s,state:o}of e){if(o==="satisfied"){r.steps.push({id:s.id,title:s.title,state:"skipped"}),n.log?.(`skip ${s.title} (already done)`);continue}n.audit?.({operation:t.operation,target:t.target,step:s.id,state:"started"});try{await s.apply(),r.steps.push({id:s.id,title:s.title,state:"applied"}),n.log?.(`done ${s.title}`),n.audit?.({operation:t.operation,target:t.target,step:s.id,state:"applied"})}catch(i){let a=i instanceof Error?i.message:String(i);return r.steps.push({id:s.id,title:s.title,state:"failed",error:a}),r.success=!1,n.log?.(`FAIL ${s.title}: ${a}`),n.audit?.({operation:t.operation,target:t.target,step:s.id,state:"failed",error:a}),r}}return r}function Qu(t){if(t.length===0)throw Error("A server name cannot be empty.");if(t.length>253)throw Error(`'${t}' is longer than the 253 characters a hostname allows.`);for(let e of t.split(".")){if(e.length===0)throw Error(`'${t}' has an empty label — a hostname cannot contain '..'.`);if(e.length>63)throw Error(`'${e}' is longer than the 63 characters a hostname label allows.`);if(!/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(e))throw Error(`'${e}' is not a valid hostname label. Use letters, digits and hyphens, not starting or ending with a hyphen.`)}}async function yh(t,e,n){if(Qu(e),t===e)throw Error(`'${t}' is already named that.`);if((await n.takenNames()).some((o)=>o===e&&o!==t))throw Error(`'${e}' is already taken. Server names have to be unique within a provider project.`);let s=[];if(n.providerName&&n.renameProvider){let{providerName:o,renameProvider:i}=n;s.push({id:"provider",title:"Rename the server at the provider",change:{from:t,to:e},satisfied:async()=>await o()===e,apply:()=>i(e)})}if(n.stateName&&n.writeStateName){let{stateName:o,writeStateName:i}=n;s.push({id:"state-pin",title:"Update the recorded name in the local driver state",change:{from:t,to:e},satisfied:async()=>{let a=await o();return a===void 0||a===e},apply:()=>i(e)})}if(n.remoteHostname&&n.setRemoteHostname){let{remoteHostname:o,setRemoteHostname:i}=n;s.push({id:"hostname",title:"Set the hostname on the box",change:{from:t,to:e},satisfied:async()=>await o()===e,apply:()=>i(e)})}return s.push({id:"inventory",title:"Rename the fleet inventory record",change:{from:t,to:e},satisfied:async()=>n.inventoryName()===e,apply:async()=>{await n.renameInventory(e)}}),{operation:"server:rename",target:t,steps:s}}function Ih(t){let e=`'${t.replace(/'/g,`'"'"'`)}'`;return["set -eu",'TS_CLOUD_OLD="$(hostname)"',`hostnamectl set-hostname ${e} 2>/dev/null || { echo ${e} > /etc/hostname && hostname ${e}; }`,'if grep -q "^127.0.1.1" /etc/hosts; then',` TS_CLOUD_HOSTS="$(sed -E "s/^127\\.0\\.1\\.1.*/127.0.1.1\\t${t}/" /etc/hosts)"`,` printf '%s\\n' "$TS_CLOUD_HOSTS" > /etc/hosts`,"else",` printf '127.0.1.1\\t%s\\n' ${e} >> /etc/hosts`,"fi",'printf "%s -> %s\\n" "$TS_CLOUD_OLD" "$(hostname)"'].join(`
9
- `)}function Sh(t,e,n){let r=e.trim();if(!r)return{problem:"No server named."};let[s,...o]=t.filter((c)=>c.name===r);if(s&&o.length===0)return{server:s};let i=t.filter((c)=>c.project===r);if(i.length>1&&n)i=i.filter((c)=>!c.environment||c.environment===n);let[a,...p]=i;if(a&&p.length===0)return{server:a};if(i.length>1)return{problem:`'${r}' owns ${i.length} servers (${i.map((c)=>c.name).join(", ")}). Name one of them, or narrow it by environment.`};return{problem:`No server matched '${r}'. Nothing is named that, and no box carries the label ts-cloud/project=${r}.`}}function Ch(t,e){let n=[];if(!e.project)n.push(`'${e.name}' carries no ts-cloud/project label, so it is not a box ts-cloud provisioned. Attaching to it would deploy into a host nothing manages.`);else if(e.project===t)n.push(`This project's slug is '${t}', which is also the slug that owns '${e.name}'. A tenant deploy owns the gateway fragment named after its slug, so attaching would overwrite '${e.project}'s own fragment and take its sites down. Change this project's slug first.`);if(e.status!=="running")n.push(`'${e.name}' is ${e.status}, so what it serves could not be read.`);if(!e.ipv4)n.push(`'${e.name}' has no public IPv4 address, so it cannot be reached to check what it serves.`);return n}function f(t,e){let n=e==="/"?"/":e.replace(/\/+$/,"");return`${t.toLowerCase()}${n||"/"}`}function bh(t,e,n){let r=[],s=Yn(n.filter((i)=>i.kind==="app").map((i)=>({slug:i.slug,proxies:[{from:i.target.split(",").map((a)=>a.trim())}]})),{ignoreSlug:t}),o=new Map;for(let i of n)if(i.slug!==t)o.set(f(i.host,i.path),i.slug);for(let i of e){if(i.port!==void 0){let a=s.get(i.port);if(a)r.push({kind:"port",site:i.name,detail:`port ${i.port}`,heldBy:a})}if(i.domain){let a=o.get(f(i.domain,i.path));if(a)r.push({kind:"route",site:i.name,detail:`${i.domain}${i.path==="/"?"/":i.path}`,heldBy:a})}}return r}function Eh(t){return t.registryRead&&t.conflicts.length===0}function vh(t){let{slug:e,owner:n,server:r,declared:s,conflicts:o}=t,i=[];i.push(`Attach '${e}' to '${r.name}' (${r.ipv4??"no IPv4"}), owned by '${n}'.`,""),i.push(` ${s.length} site${s.length===1?"":"s"} would deploy onto this box:`);for(let a of s){let p=a.loopbackOnly?`loopback only${a.port?` on :${a.port}`:""}`:`${a.domain}${a.path==="/"?"/":a.path}${a.port?` on :${a.port}`:""}`;i.push(` ${a.name} ${p} -> ${a.installBase??"(install path unresolved)"}`)}if(i.push(""),!t.registryRead)i.push(` Could not read what '${r.name}' already serves: ${t.registryProblem??"unknown reason"}`),i.push(" So this attach is UNCHECKED: a port or hostname already taken by another"),i.push(" project would not error, it would serve that project's site from your domain.");else if(o.length>0){i.push(` ${o.length} conflict${o.length===1?"":"s"} with what the box already serves:`);for(let a of o)i.push(` site '${a.site}' wants ${a.detail}, held by '${a.heldBy}'`);i.push(""),i.push(" Two services on one port do not error: the kernel load-balances, and each"),i.push(" domain serves the other's site about half the time. Pick free ports and"),i.push(" hostnames, then re-run.")}else i.push(` No conflicts with what '${r.name}' already serves.`);return i}function Xn(t,e){return`/tmp/ts-cloud-move-${t}-${e}.tar.gz`}function mc(t,e){return`${t}-${e}*.service`}function l(t){return`'${t.split("'").join("'\\''")}'`}function Hu(t,e){return["set -eu",`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E ${l(m(t,e))} || true); do`,' systemctl stop "$unit" 2>/dev/null || true',"done"].join(`
10
- `)}function m(t,e){return`^${t}-${e}-((queue|daemon)-.*|scheduler)\\.service$`}function Gu(t,e){return y(m(t,e))}function y(t){return[`ls /etc/systemd/system/ 2>/dev/null | grep -E ${l(t)} | while read -r unit; do`,' systemctl is-active "$unit" >/dev/null 2>&1 && echo "active:$unit" || true',"done"].join(`
11
- `)}function qu(t){return!t.split(`
12
- `).some((e)=>e.trim().startsWith("active:"))}function Vu(t,e,n){let r=Xn(t,e);return["set -eu",`test -d ${l(n)} || { echo "no site tree at ${n}" >&2; exit 1; }`,`rm -f ${l(r)}`,`tar czf ${l(r)} -C "$(dirname ${l(n)})" "$(basename ${l(n)})" -C /etc/systemd/system $(cd /etc/systemd/system && ls ${mc(t,e)} 2>/dev/null | tr '\\n' ' ')`,`sha256sum ${l(r)} | cut -d' ' -f1`].join(`
13
- `)}function ju(t,e,n){let r=Xn(t,e);return["set -eu",`test -f ${l(r)} || { echo "archive not staged at ${r}" >&2; exit 1; }`,`mkdir -p "$(dirname ${l(n)})"`,`tar xzf ${l(r)} -C "$(dirname ${l(n)})" "$(basename ${l(n)})"`,`tar xzf ${l(r)} -C /etc/systemd/system --wildcards ${l(mc(t,e))} 2>/dev/null || true`,"systemctl daemon-reload",`systemctl enable ${t}-${e}.service 2>/dev/null || true`,`systemctl restart ${t}-${e}.service`,`rm -f ${l(r)}`].join(`
14
- `)}function zu(t,e,n){return[`test -d ${l(n)} && echo tree:present || echo tree:absent`,`systemctl is-active ${t}-${e}.service >/dev/null 2>&1 && echo unit:active || echo unit:inactive`].join(`
15
- `)}function Ku(t){return t.includes("tree:present")&&t.includes("unit:active")}function Wu(t,e="/",n=10){let r=`http://127.0.0.1:${t}${e.startsWith("/")?e:`/${e}`}`;return["set -eu",`for i in $(seq 1 ${n}); do`,` if curl -fsS -o /dev/null --max-time 5 ${l(r)}; then echo healthy; exit 0; fi`," sleep 3","done",`echo "no healthy response from ${r}" >&2`,"exit 1"].join(`
16
- `)}function Ju(t,e){return["set -eu",`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E ${l(v(t,e))} || true); do`,' systemctl disable --now "$unit" 2>/dev/null || true',"done",`rm -f /etc/rpx/sites.d/${t}.json 2>/dev/null || true`,"systemctl reload rpx-gateway.service 2>/dev/null || systemctl restart rpx-gateway.service 2>/dev/null || true"].join(`
17
- `)}function v(t,e){return`^${t}-${e}[-@.]`}function Xu(t,e){return y(v(t,e))}function Yu(t){return!t.split(`
18
- `).some((e)=>e.trim().startsWith("active:"))}function Th(t,e){return`/tmp/ts-cloud-move-${t}-${e}-certs.tar.gz`}function wh(t,e){return["set -u",...e.map((n)=>`if [ -s ${l(`${t}/${n}.crt`)} ]; then echo "cert:${n}:$(sha256sum ${l(`${t}/${n}.crt`)} | cut -d' ' -f1)"; else echo "cert:${n}:absent"; fi`)].join(`
19
- `)}function Rh(t){let e=new Map;for(let n of t.split(`
20
- `)){let r=n.trim();if(!r.startsWith("cert:"))continue;let[,s,o]=r.split(":");if(s&&o)e.set(s,o)}return e}function Dh(t,e){for(let[n,r]of t){if(r==="absent")continue;if(e.get(n)!==r)return!1}return!0}function Ph(t,e,n){let r=e.flatMap((s)=>[`${s}.crt`,`${s}.key`]);return["set -eu",`rm -f ${l(n)}`,`cd ${l(t)} 2>/dev/null || { echo "no certs dir at ${t}" >&2; exit 0; }`,`TS_CLOUD_CERTS="$(ls ${r.map(l).join(" ")} 2>/dev/null | tr '\\n' ' ' || true)"`,'[ -n "$TS_CLOUD_CERTS" ] || { echo "no certificates to carry"; exit 0; }',`tar czf ${l(n)} $TS_CLOUD_CERTS`].join(`
21
- `)}function Nh(t,e){return["set -eu",`[ -s ${l(e)} ] || { echo "no certificate archive staged"; exit 0; }`,`mkdir -p ${l(t)}`,`tar xzf ${l(e)} -C ${l(t)}`,`chmod 600 ${l(t)}/*.key 2>/dev/null || true`,`rm -f ${l(e)}`].join(`
22
- `)}async function kh(t,e){let{slug:n,siteName:r,appBase:s,from:o,to:i,targetAddress:a}=t;if(o===i)throw Error(`'${r}' is already on ${i}.`);if(t.database&&!e.database)throw Error(`'${r}' uses the on-box database '${t.database.name}', which lives in the engine's own data directory rather than in the site tree, and this move has no way to carry it. Moving the site without it would cut traffic over to an empty database.`);if(t.database&&e.database&&await e.database.targetHasData())throw Error(`${i} already has a database named '${t.database.name}' with tables in it. Restoring this site's dump over it would destroy that data. Rename or drop it on the target first, or point this project at a different database name.`);let p=[{id:"pause-workers",title:`Stop background work on ${o} so the snapshot is consistent`,satisfied:async()=>qu(await e.runOnSource(Gu(n,r))),apply:async()=>{await e.runOnSource(Hu(n,r))}},...e.database?[{id:"database-dump",title:`Dump the '${t.database?.name}' database on ${o}`,satisfied:async()=>!1,apply:()=>e.database.dump()}]:[],{id:"snapshot",title:`Archive the site's tree and units on ${o}`,change:{from:`${o}:${s}`,to:Xn(n,r)},satisfied:async()=>!1,apply:async()=>{await e.runOnSource(Vu(n,r,s))}},{id:"transfer",title:`Carry the archive to ${i}`,change:{from:o,to:i},satisfied:()=>e.archiveStaged(),apply:()=>e.transferArchive()},...e.database?[{id:"database-transfer",title:`Carry the database dump to ${i}`,change:{from:o,to:i},satisfied:()=>e.database.dumpStaged(),apply:()=>e.database.transferDump()},{id:"database-restore",title:`Create and load '${t.database?.name}' on ${i}`,satisfied:async()=>!1,apply:()=>e.database.restore()}]:[],{id:"restore",title:`Unpack the site on ${i} and start it`,change:{from:Xn(n,r),to:`${i}:${s}`},satisfied:async()=>Ku(await e.runOnTarget(zu(n,r,s))),apply:async()=>{await e.runOnTarget(ju(n,r,s))}}];if(t.port!=null){let{port:c}=t;p.push({id:"health",title:`Wait for the site to answer on ${i} (127.0.0.1:${c})`,satisfied:async()=>!1,apply:async()=>{await e.runOnTarget(Wu(c,t.healthCheckPath??"/"))}})}return p.push(...e.certificates?[{id:"certificates",title:`Carry the site's TLS material to ${i}`,satisfied:()=>e.certificates.inPlace(),apply:()=>e.certificates.carry()}]:[],{id:"gateway",title:`Route the site on ${i}`,satisfied:()=>e.targetRoutesSite(),apply:()=>e.refreshTargetGateway()},{id:"dns",title:`Point DNS at ${i}`,change:{from:`${o}`,to:a},satisfied:async()=>await e.publishedAddress()===a,apply:async()=>{let c=await e.cutoverDns();if(c.length>0)throw Error(c.join("; "))}},{id:"drain-source",title:`Stop the site on ${o}, leaving its files in place`,satisfied:async()=>Yu(await e.runOnSource(Xu(n,r))),apply:async()=>{await e.runOnSource(Ju(n,r))}}),{operation:"site:move",target:r,steps:p}}export{ch,dh,lh,_u,Ou,Lu,uh,$u,Mu,ph,gh,Fu,mh,hh,gc,Uu,fh,Ah,Qu,yh,Ih,Sh,Ch,bh,Eh,vh,Xn,mc,Hu,Gu,qu,Vu,ju,zu,Ku,Wu,Ju,Xu,Yu,Th,wh,Rh,Dh,Ph,Nh,kh};
6
+ Verify the site is serving from its new home first, then re-run with ${n} to destroy it anyway.`}var Lu="ts-cloud/project",$u="ts-cloud/environment",Mu="ts-cloud/role";function d(t){return typeof t==="string"&&t.trim()?t.trim():void 0}function h(t){if(typeof t==="string")return d(t);if(t&&typeof t==="object")return d(t.name);return}function gh(t){let e={};for(let[n,r]of Object.entries(t?.labels??{}))if(typeof r==="string")e[n]=r;return{id:String(t?.id??""),name:d(t?.name)??"(unnamed)",status:d(t?.status)??"unknown",ipv4:d(t?.public_net?.ipv4?.ip)??d(t?.ipv4),ipv6:d(t?.public_net?.ipv6?.ip)??d(t?.ipv6),type:d(t?.server_type?.name)??d(t?.type),location:h(t?.location)??h(t?.datacenter?.location)??h(t?.datacenter),labels:e,project:d(e[Lu]),environment:d(e[$u]),role:d(e[Mu])}}function w(t){return t.slug?.trim()||"app"}function Fu(t){let e=[];for(let n of t){let r=w(n);for(let s of n.proxies??[]){let o=d(s?.to);if(!o)continue;e.push({slug:r,host:o,path:d(s?.path)??"/",...x(s)})}}return e.sort((n,r)=>n.slug.localeCompare(r.slug)||n.host.localeCompare(r.host)||n.path.localeCompare(r.path))}function x(t){let e=t?.from;if(typeof e==="string"&&e.trim())return{target:e.trim(),kind:"app"};if(Array.isArray(e)&&e.length>0)return{target:e.filter((s)=>typeof s==="string").join(", "),kind:"app"};let n=t?.static;if(typeof n==="string"&&n.trim())return{target:n.trim(),kind:"static"};if(n&&typeof n==="object"&&d(n.dir))return{target:d(n.dir),kind:"static"};let r=typeof t?.redirect==="string"?d(t.redirect):d(t?.redirect?.to);if(r)return{target:r,kind:"redirect"};return{target:"(no upstream)",kind:"unknown"}}function Uu(t){let e=new Map;for(let n of t){let r=e.get(n.slug);if(r)r.push(n);else e.set(n.slug,[n])}return[...e.entries()].map(([n,r])=>({slug:n,routes:r})).sort((n,r)=>r.routes.length-n.routes.length||n.slug.localeCompare(r.slug))}async function mh(t,e,n=ot){if(!t.ipv4)return{server:t.name,routes:[],unavailable:"no public IPv4 address to reach it on"};if(t.status!=="running")return{server:t.name,ip:t.ipv4,routes:[],unavailable:`server is ${t.status}`};try{let r=await e(t.ipv4,Zn(n));if(r.code!==0){let s=r.stderr.trim().split(`
7
+ `)[0]||`remote command exited ${r.code}`;return{server:t.name,ip:t.ipv4,routes:[],unavailable:s}}return{server:t.name,ip:t.ipv4,routes:Fu(ei(r.stdout))}}catch(r){let s=r instanceof Error?r.message.split(`
8
+ `)[0]:String(r);return{server:t.name,ip:t.ipv4,routes:[],unavailable:s}}}function u(t,e){let n=e==="/"?"/":e.replace(/\/+$/,"");return`${t.toLowerCase()}${n||"/"}`}function hh(t,e,n){let r=new Set(e.filter((a)=>a.slug===n).map((a)=>u(a.host,a.path))),s=[],o=[],i=[];for(let a of t)if(a.loopbackOnly)i.push(a);else if(a.domain&&r.has(u(a.domain,a.path)))s.push(a);else o.push(a);return{present:s,absent:o,loopback:i,foreign:e.filter((a)=>a.slug!==n)}}function Qu(t,e,n){let r=new Set;for(let s of e)for(let o of s.routes)if(o.slug===n)r.add(u(o.host,o.path));return t.filter((s)=>!s.loopbackOnly&&s.domain!==void 0&&!r.has(u(s.domain,s.path)))}function fh(t){let{slug:e,servers:n,probes:r,declared:s}=t,o=[];if(o.push(n.length===0?"No servers found.":`${n.length} server${n.length===1?"":"s"}:`),n.length>0)o.push("");let i=new Map(r.map((a)=>[a.server,a]));for(let a of n){let p=[a.ipv4,a.type,a.location,a.status].filter(Boolean);o.push(` ${a.name} ${p.join(" ")}`),o.push(` ${k(a)}`);let c=i.get(a.name);if(!c)o.push(" not probed, so co-tenants on this box are not listed");else if(c.unavailable)o.push(` could not read ${ot}: ${c.unavailable}`);else o.push(...P(c,e));o.push("")}return o.push(...C(t)),o}function k(t){if(!t.project)return"no ts-cloud labels: provisioned outside ts-cloud, or by a version that did not label boxes";let e=[t.environment,t.role&&`role ${t.role}`].filter(Boolean).join(", ");return`owned by '${t.project}'${e?` (${e})`:""}`}function P(t,e){let n=Uu(t.routes);if(n.length===0)return[` serves nothing: ${ot} is empty or absent`];let r=[` serves ${t.routes.length} route${t.routes.length===1?"":"s"} for ${n.length} project${n.length===1?"":"s"}:`];for(let s of n){r.push(` ${s.slug}${s.slug===e?" (this project)":""}`);for(let o of s.routes)r.push(` ${o.host}${o.path==="/"?"/":o.path} -> ${O(o)}`)}return r}function O(t){if(t.kind==="redirect")return`redirect to ${t.target}`;if(t.kind==="static")return`static ${t.target}`;return t.target}function C(t){let{slug:e,declared:n,probes:r,servers:s}=t;if(n.length===0)return[`This project ('${e}') declares no sites.`];let o=[`This project ('${e}') declares ${n.length} site${n.length===1?"":"s"}: `+n.map((c)=>c.name).join(", ")],i=n.filter((c)=>c.loopbackOnly);if(i.length>0)o.push(` ${i.length} with no domain, so the gateway never routes ${i.length===1?"it":"them"} (reached through another site's proxy): ${i.map((c)=>c.name).join(", ")}`);let a=r.filter((c)=>!c.unavailable);if(a.length===0)return o.push(" Nothing to reconcile them against: no box reported what it serves."),o;let p=Qu(n,a,e);if(o.push(` ${n.length-i.length-p.length} routed by a box above`),p.length>0){o.push(` ${p.length} not routed by any box above: ${p.map((b)=>b.name).join(", ")}`);let c=r.length-a.length,g=s.length-r.length;if(c>0)o.push(` Either they were never deployed, or they are on one of the ${c} server${c===1?"":"s"} that could not be read.`);else if(g>0)o.push(` Either they were never deployed, or they are on one of the ${g} server${g===1?"":"s"} this run did not probe.`);else o.push(" Either they were never deployed, or they are on a server this listing did not cover.")}return o}async function Ah(t){let e=[];for(let n of t.steps)try{e.push({step:n,state:await n.satisfied()?"satisfied":"pending"})}catch(r){e.push({step:n,state:"unknown",reason:r instanceof Error?r.message:String(r)})}return e}function hc(t){return t.filter((e)=>e.state!=="satisfied")}function Hu(t){return hc(t).some((e)=>e.step.destructive===!0)}function yh(t,e){let n=hc(e),r=[`${t.operation} ${t.target}`];if(n.length===0)return r.push(" Nothing to do — every step is already satisfied."),r;for(let{step:o,state:i,reason:a}of e){let p=i==="satisfied"?"ok ":i==="unknown"?"? ":"→ ",c=[o.destructive?"DESTRUCTIVE":"",i==="satisfied"?"already done":""].filter(Boolean);if(r.push(` ${p}${o.title}${c.length>0?` [${c.join(", ")}]`:""}`),o.change)r.push(` ${o.change.from} → ${o.change.to}`);if(a)r.push(` could not check: ${a}`)}let s=n.filter((o)=>o.step.destructive).length;return r.push(` ${n.length} step(s) would run`+(s>0?`, ${s} irreversible — re-run with --confirm ${t.target}`:"")),r}async function Ih(t,e,n={}){let r={operation:t.operation,target:t.target,steps:[],success:!0};if(Hu(e)&&n.confirm!==t.target)throw Error(`${t.operation} includes an irreversible step. Re-run with --confirm ${t.target} to authorize it.`);for(let{step:s,state:o}of e){if(o==="satisfied"){r.steps.push({id:s.id,title:s.title,state:"skipped"}),n.log?.(`skip ${s.title} (already done)`);continue}n.audit?.({operation:t.operation,target:t.target,step:s.id,state:"started"});try{await s.apply(),r.steps.push({id:s.id,title:s.title,state:"applied"}),n.log?.(`done ${s.title}`),n.audit?.({operation:t.operation,target:t.target,step:s.id,state:"applied"})}catch(i){let a=i instanceof Error?i.message:String(i);return r.steps.push({id:s.id,title:s.title,state:"failed",error:a}),r.success=!1,n.log?.(`FAIL ${s.title}: ${a}`),n.audit?.({operation:t.operation,target:t.target,step:s.id,state:"failed",error:a}),r}}return r}function Gu(t){if(t.length===0)throw Error("A server name cannot be empty.");if(t.length>253)throw Error(`'${t}' is longer than the 253 characters a hostname allows.`);for(let e of t.split(".")){if(e.length===0)throw Error(`'${t}' has an empty label — a hostname cannot contain '..'.`);if(e.length>63)throw Error(`'${e}' is longer than the 63 characters a hostname label allows.`);if(!/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(e))throw Error(`'${e}' is not a valid hostname label. Use letters, digits and hyphens, not starting or ending with a hyphen.`)}}async function Sh(t,e,n){if(Gu(e),t===e)throw Error(`'${t}' is already named that.`);if((await n.takenNames()).some((o)=>o===e&&o!==t))throw Error(`'${e}' is already taken. Server names have to be unique within a provider project.`);let s=[];if(n.providerName&&n.renameProvider){let{providerName:o,renameProvider:i}=n;s.push({id:"provider",title:"Rename the server at the provider",change:{from:t,to:e},satisfied:async()=>await o()===e,apply:()=>i(e)})}if(n.stateName&&n.writeStateName){let{stateName:o,writeStateName:i}=n;s.push({id:"state-pin",title:"Update the recorded name in the local driver state",change:{from:t,to:e},satisfied:async()=>{let a=await o();return a===void 0||a===e},apply:()=>i(e)})}if(n.remoteHostname&&n.setRemoteHostname){let{remoteHostname:o,setRemoteHostname:i}=n;s.push({id:"hostname",title:"Set the hostname on the box",change:{from:t,to:e},satisfied:async()=>await o()===e,apply:()=>i(e)})}return s.push({id:"inventory",title:"Rename the fleet inventory record",change:{from:t,to:e},satisfied:async()=>n.inventoryName()===e,apply:async()=>{await n.renameInventory(e)}}),{operation:"server:rename",target:t,steps:s}}function Ch(t){let e=`'${t.replace(/'/g,`'"'"'`)}'`;return["set -eu",'TS_CLOUD_OLD="$(hostname)"',`hostnamectl set-hostname ${e} 2>/dev/null || { echo ${e} > /etc/hostname && hostname ${e}; }`,'if grep -q "^127.0.1.1" /etc/hosts; then',` TS_CLOUD_HOSTS="$(sed -E "s/^127\\.0\\.1\\.1.*/127.0.1.1\\t${t}/" /etc/hosts)"`,` printf '%s\\n' "$TS_CLOUD_HOSTS" > /etc/hosts`,"else",` printf '127.0.1.1\\t%s\\n' ${e} >> /etc/hosts`,"fi",'printf "%s -> %s\\n" "$TS_CLOUD_OLD" "$(hostname)"'].join(`
9
+ `)}function bh(t,e,n){let r=e.trim();if(!r)return{problem:"No server named."};let[s,...o]=t.filter((c)=>c.name===r);if(s&&o.length===0)return{server:s};let i=t.filter((c)=>c.project===r);if(i.length>1&&n)i=i.filter((c)=>!c.environment||c.environment===n);let[a,...p]=i;if(a&&p.length===0)return{server:a};if(i.length>1)return{problem:`'${r}' owns ${i.length} servers (${i.map((c)=>c.name).join(", ")}). Name one of them, or narrow it by environment.`};return{problem:`No server matched '${r}'. Nothing is named that, and no box carries the label ts-cloud/project=${r}.`}}function Eh(t,e){let n=[];if(!e.project)n.push(`'${e.name}' carries no ts-cloud/project label, so it is not a box ts-cloud provisioned. Attaching to it would deploy into a host nothing manages.`);else if(e.project===t)n.push(`This project's slug is '${t}', which is also the slug that owns '${e.name}'. A tenant deploy owns the gateway fragment named after its slug, so attaching would overwrite '${e.project}'s own fragment and take its sites down. Change this project's slug first.`);if(e.status!=="running")n.push(`'${e.name}' is ${e.status}, so what it serves could not be read.`);if(!e.ipv4)n.push(`'${e.name}' has no public IPv4 address, so it cannot be reached to check what it serves.`);return n}function f(t,e){let n=e==="/"?"/":e.replace(/\/+$/,"");return`${t.toLowerCase()}${n||"/"}`}function vh(t,e,n){let r=[],s=Yn(n.filter((i)=>i.kind==="app").map((i)=>({slug:i.slug,proxies:[{from:i.target.split(",").map((a)=>a.trim())}]})),{ignoreSlug:t}),o=new Map;for(let i of n)if(i.slug!==t)o.set(f(i.host,i.path),i.slug);for(let i of e){if(i.port!==void 0){let a=s.get(i.port);if(a)r.push({kind:"port",site:i.name,detail:`port ${i.port}`,heldBy:a})}if(i.domain){let a=o.get(f(i.domain,i.path));if(a)r.push({kind:"route",site:i.name,detail:`${i.domain}${i.path==="/"?"/":i.path}`,heldBy:a})}}return r}function Th(t){return t.registryRead&&t.conflicts.length===0}function wh(t){let{slug:e,owner:n,server:r,declared:s,conflicts:o}=t,i=[];i.push(`Attach '${e}' to '${r.name}' (${r.ipv4??"no IPv4"}), owned by '${n}'.`,""),i.push(` ${s.length} site${s.length===1?"":"s"} would deploy onto this box:`);for(let a of s){let p=a.loopbackOnly?`loopback only${a.port?` on :${a.port}`:""}`:`${a.domain}${a.path==="/"?"/":a.path}${a.port?` on :${a.port}`:""}`;i.push(` ${a.name} ${p} -> ${a.installBase??"(install path unresolved)"}`)}if(i.push(""),!t.registryRead)i.push(` Could not read what '${r.name}' already serves: ${t.registryProblem??"unknown reason"}`),i.push(" So this attach is UNCHECKED: a port or hostname already taken by another"),i.push(" project would not error, it would serve that project's site from your domain.");else if(o.length>0){i.push(` ${o.length} conflict${o.length===1?"":"s"} with what the box already serves:`);for(let a of o)i.push(` site '${a.site}' wants ${a.detail}, held by '${a.heldBy}'`);i.push(""),i.push(" Two services on one port do not error: the kernel load-balances, and each"),i.push(" domain serves the other's site about half the time. Pick free ports and"),i.push(" hostnames, then re-run.")}else i.push(` No conflicts with what '${r.name}' already serves.`);return i}function Xn(t,e){return`/tmp/ts-cloud-move-${t}-${e}.tar.gz`}function fc(t,e){return`${t}-${e}*.service`}function l(t){return`'${t.split("'").join("'\\''")}'`}function qu(t,e){return["set -eu",`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E ${l(m(t,e))} || true); do`,' systemctl stop "$unit" 2>/dev/null || true',"done"].join(`
10
+ `)}function m(t,e){return`^${t}-${e}-((queue|daemon)-.*|scheduler)\\.service$`}function Vu(t,e){return y(m(t,e))}function y(t){return[`ls /etc/systemd/system/ 2>/dev/null | grep -E ${l(t)} | while read -r unit; do`,' systemctl is-active "$unit" >/dev/null 2>&1 && echo "active:$unit" || true',"done"].join(`
11
+ `)}function ju(t){return!t.split(`
12
+ `).some((e)=>e.trim().startsWith("active:"))}function zu(t,e,n){let r=Xn(t,e);return["set -eu",`test -d ${l(n)} || { echo "no site tree at ${n}" >&2; exit 1; }`,`rm -f ${l(r)}`,`tar czf ${l(r)} -C "$(dirname ${l(n)})" "$(basename ${l(n)})" -C /etc/systemd/system $(cd /etc/systemd/system && ls ${fc(t,e)} 2>/dev/null | tr '\\n' ' ')`,`sha256sum ${l(r)} | cut -d' ' -f1`].join(`
13
+ `)}function Ku(t,e,n){let r=Xn(t,e);return["set -eu",`test -f ${l(r)} || { echo "archive not staged at ${r}" >&2; exit 1; }`,`mkdir -p "$(dirname ${l(n)})"`,`tar xzf ${l(r)} -C "$(dirname ${l(n)})" "$(basename ${l(n)})"`,`tar xzf ${l(r)} -C /etc/systemd/system --wildcards ${l(fc(t,e))} 2>/dev/null || true`,"systemctl daemon-reload",`systemctl enable ${t}-${e}.service 2>/dev/null || true`,`systemctl restart ${t}-${e}.service`,`rm -f ${l(r)}`].join(`
14
+ `)}function Wu(t,e,n){return[`test -d ${l(n)} && echo tree:present || echo tree:absent`,`systemctl is-active ${t}-${e}.service >/dev/null 2>&1 && echo unit:active || echo unit:inactive`].join(`
15
+ `)}function Ju(t){return t.includes("tree:present")&&t.includes("unit:active")}function Xu(t,e="/",n=10){let r=`http://127.0.0.1:${t}${e.startsWith("/")?e:`/${e}`}`;return["set -eu",`for i in $(seq 1 ${n}); do`,` if curl -fsS -o /dev/null --max-time 5 ${l(r)}; then echo healthy; exit 0; fi`," sleep 3","done",`echo "no healthy response from ${r}" >&2`,"exit 1"].join(`
16
+ `)}function Yu(t,e){return["set -eu",`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E ${l(v(t,e))} || true); do`,' systemctl disable --now "$unit" 2>/dev/null || true',"done",`rm -f /etc/rpx/sites.d/${t}.json 2>/dev/null || true`,"systemctl reload rpx-gateway.service 2>/dev/null || systemctl restart rpx-gateway.service 2>/dev/null || true"].join(`
17
+ `)}function v(t,e){return`^${t}-${e}[-@.]`}function Zu(t,e){return y(v(t,e))}function ep(t){return!t.split(`
18
+ `).some((e)=>e.trim().startsWith("active:"))}function Rh(t,e){return`/tmp/ts-cloud-move-${t}-${e}-certs.tar.gz`}function Dh(t,e){return["set -u",...e.map((n)=>`if [ -s ${l(`${t}/${n}.crt`)} ]; then echo "cert:${n}:$(sha256sum ${l(`${t}/${n}.crt`)} | cut -d' ' -f1)"; else echo "cert:${n}:absent"; fi`)].join(`
19
+ `)}function Ph(t){let e=new Map;for(let n of t.split(`
20
+ `)){let r=n.trim();if(!r.startsWith("cert:"))continue;let[,s,o]=r.split(":");if(s&&o)e.set(s,o)}return e}function Nh(t,e){for(let[n,r]of t){if(r==="absent")continue;if(e.get(n)!==r)return!1}return!0}function kh(t,e,n){let r=e.flatMap((s)=>[`${s}.crt`,`${s}.key`]);return["set -eu",`rm -f ${l(n)}`,`cd ${l(t)} 2>/dev/null || { echo "no certs dir at ${t}" >&2; exit 0; }`,`TS_CLOUD_CERTS="$(ls ${r.map(l).join(" ")} 2>/dev/null | tr '\\n' ' ' || true)"`,'[ -n "$TS_CLOUD_CERTS" ] || { echo "no certificates to carry"; exit 0; }',`tar czf ${l(n)} $TS_CLOUD_CERTS`].join(`
21
+ `)}function Bh(t,e){return["set -eu",`[ -s ${l(e)} ] || { echo "no certificate archive staged"; exit 0; }`,`mkdir -p ${l(t)}`,`tar xzf ${l(e)} -C ${l(t)}`,`chmod 600 ${l(t)}/*.key 2>/dev/null || true`,`rm -f ${l(e)}`].join(`
22
+ `)}async function xh(t,e){let{slug:n,siteName:r,appBase:s,from:o,to:i,targetAddress:a}=t;if(o===i)throw Error(`'${r}' is already on ${i}.`);if(t.database&&!e.database)throw Error(`'${r}' uses the on-box database '${t.database.name}', which lives in the engine's own data directory rather than in the site tree, and this move has no way to carry it. Moving the site without it would cut traffic over to an empty database.`);if(t.database&&e.database&&await e.database.targetHasData())throw Error(`${i} already has a database named '${t.database.name}' with tables in it. Restoring this site's dump over it would destroy that data. Rename or drop it on the target first, or point this project at a different database name.`);let p=[{id:"pause-workers",title:`Stop background work on ${o} so the snapshot is consistent`,satisfied:async()=>ju(await e.runOnSource(Vu(n,r))),apply:async()=>{await e.runOnSource(qu(n,r))}},...e.database?[{id:"database-dump",title:`Dump the '${t.database?.name}' database on ${o}`,satisfied:async()=>!1,apply:()=>e.database.dump()}]:[],{id:"snapshot",title:`Archive the site's tree and units on ${o}`,change:{from:`${o}:${s}`,to:Xn(n,r)},satisfied:async()=>!1,apply:async()=>{await e.runOnSource(zu(n,r,s))}},{id:"transfer",title:`Carry the archive to ${i}`,change:{from:o,to:i},satisfied:()=>e.archiveStaged(),apply:()=>e.transferArchive()},...e.database?[{id:"database-transfer",title:`Carry the database dump to ${i}`,change:{from:o,to:i},satisfied:()=>e.database.dumpStaged(),apply:()=>e.database.transferDump()},{id:"database-restore",title:`Create and load '${t.database?.name}' on ${i}`,satisfied:async()=>!1,apply:()=>e.database.restore()}]:[],{id:"restore",title:`Unpack the site on ${i} and start it`,change:{from:Xn(n,r),to:`${i}:${s}`},satisfied:async()=>Ju(await e.runOnTarget(Wu(n,r,s))),apply:async()=>{await e.runOnTarget(Ku(n,r,s))}}];if(t.port!=null){let{port:c}=t;p.push({id:"health",title:`Wait for the site to answer on ${i} (127.0.0.1:${c})`,satisfied:async()=>!1,apply:async()=>{await e.runOnTarget(Xu(c,t.healthCheckPath??"/"))}})}return p.push(...e.certificates?[{id:"certificates",title:`Carry the site's TLS material to ${i}`,satisfied:()=>e.certificates.inPlace(),apply:()=>e.certificates.carry()}]:[],{id:"gateway",title:`Route the site on ${i}`,satisfied:()=>e.targetRoutesSite(),apply:()=>e.refreshTargetGateway()},{id:"dns",title:`Point DNS at ${i}`,change:{from:`${o}`,to:a},satisfied:async()=>await e.publishedAddress()===a,apply:async()=>{let c=await e.cutoverDns();if(c.length>0)throw Error(c.join("; "))}},{id:"drain-source",title:`Stop the site on ${o}, leaving its files in place`,satisfied:async()=>ep(await e.runOnSource(Zu(n,r))),apply:async()=>{await e.runOnSource(Yu(n,r))}}),{operation:"site:move",target:r,steps:p}}export{lh,uh,ph,Lu,$u,Mu,gh,Fu,Uu,mh,hh,Qu,fh,Ah,hc,Hu,yh,Ih,Gu,Sh,Ch,bh,Eh,vh,Th,wh,Xn,fc,qu,Vu,ju,zu,Ku,Wu,Ju,Xu,Yu,Zu,ep,Rh,Dh,Ph,Nh,kh,Bh,xh};
@@ -0,0 +1 @@
1
+ import{j}from"./chunk-1bxqrj7m.js";import"./chunk-4w8d2mf0.js";export{j as RDSClient};