@stacksjs/ts-cloud 0.16.90 → 0.16.92

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 (207) hide show
  1. package/dist/aws/client.d.ts +3 -5
  2. package/dist/aws/credentials.d.ts +9 -4
  3. package/dist/aws/index.js +1 -1
  4. package/dist/bin/{chunk-52snxrsx.js → chunk-00arzt4m.js} +97 -97
  5. package/dist/bin/chunk-0b6rv9dt.js +1 -0
  6. package/dist/bin/chunk-0qzt0swj.js +5 -0
  7. package/dist/bin/chunk-0rvzy2z7.js +1 -0
  8. package/dist/bin/{chunk-z9g7fa1w.js → chunk-0zepgwq9.js} +2 -2
  9. package/dist/bin/chunk-11hc309t.js +1 -0
  10. package/dist/bin/{chunk-qmwqntnx.js → chunk-1p7rtk98.js} +2 -2
  11. package/dist/bin/{chunk-qpasspad.js → chunk-32dr1fym.js} +5 -5
  12. package/dist/bin/{chunk-v3trt4q1.js → chunk-3h7gmatb.js} +3 -3
  13. package/dist/bin/{chunk-69mejej3.js → chunk-407wz1f4.js} +1 -1
  14. package/dist/bin/{chunk-xycxw00z.js → chunk-42nh9ac7.js} +8 -8
  15. package/dist/bin/chunk-49zcdbn0.js +1 -0
  16. package/dist/bin/chunk-4gv5j5s1.js +1 -0
  17. package/dist/bin/{chunk-gn7rdyz7.js → chunk-4kka906v.js} +2 -2
  18. package/dist/bin/{chunk-jqs2ywj2.js → chunk-55mv5w3m.js} +2 -2
  19. package/dist/bin/{chunk-4mep3m41.js → chunk-57yxbyh6.js} +5 -5
  20. package/dist/bin/chunk-5nfhjr0h.js +1 -0
  21. package/dist/bin/chunk-5njr2s5x.js +1 -0
  22. package/dist/bin/chunk-6qhgzf9a.js +1 -0
  23. package/dist/bin/{chunk-bycbwddj.js → chunk-6ty1wegm.js} +2 -2
  24. package/dist/bin/chunk-8ctmc30y.js +14 -0
  25. package/dist/bin/chunk-9g4qsx30.js +1 -0
  26. package/dist/bin/chunk-afvk9mbs.js +1 -0
  27. package/dist/bin/{chunk-9bmaq8q7.js → chunk-cb0yqrpk.js} +111 -113
  28. package/dist/bin/{chunk-bxks81wn.js → chunk-chx779q9.js} +3 -3
  29. package/dist/bin/chunk-ckbv6y4c.js +1 -0
  30. package/dist/bin/{chunk-6b6yr784.js → chunk-drc9y2fj.js} +2 -2
  31. package/dist/bin/chunk-eb591jvz.js +1 -0
  32. package/dist/bin/{chunk-b1cb27m8.js → chunk-eqqqbsjm.js} +7 -7
  33. package/dist/bin/{chunk-cgyk48s5.js → chunk-fcst782q.js} +1 -1
  34. package/dist/bin/{chunk-19mhwmfp.js → chunk-fmgv99xw.js} +1 -1
  35. package/dist/bin/{chunk-0e56zmps.js → chunk-g1s5s95g.js} +2 -2
  36. package/dist/bin/{chunk-ye2gymsr.js → chunk-gkgqss71.js} +3 -3
  37. package/dist/bin/chunk-gvacnz2y.js +1 -0
  38. package/dist/bin/{chunk-em9swj0k.js → chunk-h99kxww0.js} +1 -1
  39. package/dist/bin/chunk-j1dbkpha.js +1 -0
  40. package/dist/bin/{chunk-zfn3a9sx.js → chunk-j34ask5s.js} +2 -2
  41. package/dist/bin/{chunk-f7jzs1h1.js → chunk-j7j7gffr.js} +5 -5
  42. package/dist/bin/chunk-jjw5d8b9.js +1 -0
  43. package/dist/bin/{chunk-1wgyq50e.js → chunk-kbtx3q9m.js} +29 -30
  44. package/dist/bin/{chunk-t0r1rdj2.js → chunk-kdjrcvr6.js} +2 -2
  45. package/dist/bin/{chunk-76ekkat8.js → chunk-kefwtr8r.js} +3 -3
  46. package/dist/bin/{chunk-v1a0b9yq.js → chunk-kp84kged.js} +16 -16
  47. package/dist/bin/chunk-m5tpfe3s.js +1 -0
  48. package/dist/bin/{chunk-83tt2t15.js → chunk-mrkrn8dk.js} +5 -5
  49. package/dist/bin/chunk-n6yvpj86.js +1 -0
  50. package/dist/bin/{chunk-bkx2kapc.js → chunk-ncj8dpdp.js} +2 -2
  51. package/dist/bin/{chunk-w40r35vn.js → chunk-p6swcv5y.js} +1 -1
  52. package/dist/bin/{chunk-ndvma07s.js → chunk-pat56kbr.js} +5 -5
  53. package/dist/bin/chunk-q2hg6hmg.js +1 -0
  54. package/dist/bin/chunk-qd1jfsam.js +1 -0
  55. package/dist/bin/{chunk-yf2drw7r.js → chunk-r1q343bm.js} +1 -1
  56. package/dist/bin/chunk-r50x03ws.js +1 -0
  57. package/dist/bin/chunk-rhncmffy.js +1 -0
  58. package/dist/bin/chunk-seh19g93.js +1 -0
  59. package/dist/bin/{chunk-35325988.js → chunk-sjzzx539.js} +2 -2
  60. package/dist/bin/chunk-sxfdxk39.js +1 -0
  61. package/dist/bin/chunk-ty2pdbz3.js +1 -0
  62. package/dist/bin/chunk-tyeessz3.js +1 -0
  63. package/dist/bin/{chunk-dkdgwm13.js → chunk-v72zwetk.js} +82 -82
  64. package/dist/bin/chunk-we82q71y.js +1 -0
  65. package/dist/bin/{chunk-zn9wmqd1.js → chunk-xhqfha32.js} +2 -2
  66. package/dist/bin/{chunk-89v3ec9n.js → chunk-xk8nrvjz.js} +1 -1
  67. package/dist/bin/{chunk-88s5w4yt.js → chunk-zpk7fn1s.js} +6 -6
  68. package/dist/bin/cli.js +216 -216
  69. package/dist/bin/dashboard-server.js +1 -1
  70. package/dist/bin/stacks-queue-worker.js +1 -1
  71. package/dist/bin/stacks-scheduler.js +1 -1
  72. package/dist/chunk-0v77443p.js +1 -0
  73. package/dist/{chunk-z56sccfh.js → chunk-1087xz1v.js} +2 -2
  74. package/dist/{chunk-c8kf2268.js → chunk-1psh3mhm.js} +29 -30
  75. package/dist/chunk-4khjjgd3.js +1 -0
  76. package/dist/{chunk-4pztf7ws.js → chunk-4m5gpp6w.js} +5 -5
  77. package/dist/{chunk-3bvhthfb.js → chunk-72p2tdpe.js} +115 -117
  78. package/dist/chunk-7d9ek8rc.js +5 -0
  79. package/dist/chunk-872fdms3.js +1 -0
  80. package/dist/{chunk-cq079p4a.js → chunk-9f18pebj.js} +6 -6
  81. package/dist/{chunk-vq8bejep.js → chunk-a77mhcs7.js} +3 -3
  82. package/dist/chunk-bazah9w0.js +1 -0
  83. package/dist/{chunk-tmp2ym80.js → chunk-by7hejhg.js} +1 -1
  84. package/dist/{chunk-ax320pn8.js → chunk-byr76jcy.js} +19 -19
  85. package/dist/{chunk-m35z9vyn.js → chunk-c6kb5c5v.js} +4 -4
  86. package/dist/{chunk-1c6rvba9.js → chunk-cjm5j58y.js} +136 -136
  87. package/dist/{chunk-gpgmp9dt.js → chunk-dmv3vryr.js} +10 -10
  88. package/dist/{chunk-5t92a838.js → chunk-fe6m7wb0.js} +45 -45
  89. package/dist/{chunk-py8dq1ey.js → chunk-fne338jr.js} +5 -5
  90. package/dist/{chunk-nftqsker.js → chunk-h6kptkce.js} +2 -2
  91. package/dist/{chunk-fdf181e6.js → chunk-hcbrgyfz.js} +2 -2
  92. package/dist/{chunk-9pwvnh3f.js → chunk-jz6dacx1.js} +2 -2
  93. package/dist/{chunk-fjs0wgyw.js → chunk-kcem6dzk.js} +2 -2
  94. package/dist/{chunk-4ccv5c4m.js → chunk-q7yf28cc.js} +1 -1
  95. package/dist/{chunk-jx1zz1pw.js → chunk-qra9k26f.js} +1 -1
  96. package/dist/chunk-qs7814ya.js +1 -0
  97. package/dist/chunk-sd5a61c6.js +1 -0
  98. package/dist/{bin/chunk-8rkfwgb4.js → chunk-sjfc9my3.js} +7 -7
  99. package/dist/{chunk-84z2a1xn.js → chunk-sxqe8e9c.js} +7 -7
  100. package/dist/{chunk-g0bh9atv.js → chunk-t1wq0ckc.js} +2 -2
  101. package/dist/{chunk-c71hhcsb.js → chunk-tpvmpmxj.js} +1 -1
  102. package/dist/{chunk-tr54e9c0.js → chunk-x7cnfn7y.js} +2 -2
  103. package/dist/{chunk-fpad8xw9.js → chunk-xs9m0v31.js} +4 -4
  104. package/dist/chunk-zft558kj.js +1 -0
  105. package/dist/{chunk-fdby0vq9.js → chunk-zjkxhvn0.js} +100 -100
  106. package/dist/{chunk-e75dvdqf.js → chunk-zwayp7fz.js} +2 -2
  107. package/dist/{chunk-gdw52mn4.js → chunk-zy3kr4s2.js} +3 -3
  108. package/dist/deploy/index.js +1 -1
  109. package/dist/dns/index.js +1 -1
  110. package/dist/drivers/index.js +1 -1
  111. package/dist/index.js +31 -31
  112. package/dist/mail/index.js +2 -2
  113. package/dist/operations/index.js +1 -1
  114. package/dist/protection/index.js +1 -1
  115. package/dist/spend/index.js +1 -1
  116. package/dist/ui/404.html +1 -1
  117. package/dist/ui/accept-invitation.html +1 -1
  118. package/dist/ui/access-denied.html +1 -1
  119. package/dist/ui/account/automation.html +6 -6
  120. package/dist/ui/account/security.html +2 -2
  121. package/dist/ui/applications/compose.html +6 -6
  122. package/dist/ui/applications/new.html +2 -2
  123. package/dist/ui/data/backups.html +5 -5
  124. package/dist/ui/data/services.html +6 -6
  125. package/dist/ui/data/volumes.html +6 -6
  126. package/dist/ui/index.html +6 -6
  127. package/dist/ui/infrastructure/topology.html +5 -5
  128. package/dist/ui/integrations.html +2 -2
  129. package/dist/ui/operations/alerts.html +6 -6
  130. package/dist/ui/operations/configuration.html +6 -6
  131. package/dist/ui/operations/jobs.html +6 -6
  132. package/dist/ui/operations/maintenance.html +5 -5
  133. package/dist/ui/operations/observability.html +6 -6
  134. package/dist/ui/operations/previews.html +6 -6
  135. package/dist/ui/operations/queue.html +6 -6
  136. package/dist/ui/operations/regions.html +5 -5
  137. package/dist/ui/operations/releases.html +6 -6
  138. package/dist/ui/operations/spend.html +6 -6
  139. package/dist/ui/operations/workloads.html +6 -6
  140. package/dist/ui/security.html +1 -1
  141. package/dist/ui/server/actions.html +6 -6
  142. package/dist/ui/server/activity.html +2 -2
  143. package/dist/ui/server/capacity.html +6 -6
  144. package/dist/ui/server/database.html +5 -5
  145. package/dist/ui/server/deployments.html +5 -5
  146. package/dist/ui/server/diagnostics.html +2 -2
  147. package/dist/ui/server/firewall.html +6 -6
  148. package/dist/ui/server/fleet.html +5 -5
  149. package/dist/ui/server/logs.html +6 -6
  150. package/dist/ui/server/metrics.html +5 -5
  151. package/dist/ui/server/security.html +2 -2
  152. package/dist/ui/server/services.html +1 -1
  153. package/dist/ui/server/sites.html +5 -5
  154. package/dist/ui/server/ssh-keys.html +6 -6
  155. package/dist/ui/server/team.html +6 -6
  156. package/dist/ui/server/terminal.html +2 -2
  157. package/dist/ui/serverless/alarms.html +6 -6
  158. package/dist/ui/serverless/assets.html +1 -1
  159. package/dist/ui/serverless/cost.html +2 -2
  160. package/dist/ui/serverless/data.html +6 -6
  161. package/dist/ui/serverless/deployments.html +2 -2
  162. package/dist/ui/serverless/firewall.html +1 -1
  163. package/dist/ui/serverless/functions.html +6 -6
  164. package/dist/ui/serverless/logs.html +6 -6
  165. package/dist/ui/serverless/metrics.html +2 -2
  166. package/dist/ui/serverless/queues.html +6 -6
  167. package/dist/ui/serverless/secrets.html +5 -5
  168. package/dist/ui/serverless/traces.html +6 -6
  169. package/dist/ui/serverless.html +6 -6
  170. package/package.json +3 -3
  171. package/dist/bin/chunk-1qez75tb.js +0 -1
  172. package/dist/bin/chunk-1rrmswhq.js +0 -1
  173. package/dist/bin/chunk-1vw6khps.js +0 -1
  174. package/dist/bin/chunk-2h1q758c.js +0 -2
  175. package/dist/bin/chunk-3rjer1mp.js +0 -1
  176. package/dist/bin/chunk-4k2x5x3k.js +0 -1
  177. package/dist/bin/chunk-5tzygzdy.js +0 -1
  178. package/dist/bin/chunk-6wvjr3ne.js +0 -1
  179. package/dist/bin/chunk-71fa7yed.js +0 -1
  180. package/dist/bin/chunk-7haewmr7.js +0 -1
  181. package/dist/bin/chunk-86w3vzx8.js +0 -1
  182. package/dist/bin/chunk-8tfqpp9m.js +0 -1
  183. package/dist/bin/chunk-9tt7ahdf.js +0 -1
  184. package/dist/bin/chunk-9zwvysdn.js +0 -1
  185. package/dist/bin/chunk-b9ersj22.js +0 -1
  186. package/dist/bin/chunk-btrxye8p.js +0 -6
  187. package/dist/bin/chunk-haezjam0.js +0 -1
  188. package/dist/bin/chunk-hp1cqk45.js +0 -1
  189. package/dist/bin/chunk-mwprtzxp.js +0 -1
  190. package/dist/bin/chunk-nemj07g1.js +0 -1
  191. package/dist/bin/chunk-nfxxr6g7.js +0 -1
  192. package/dist/bin/chunk-q3mtvtem.js +0 -1
  193. package/dist/bin/chunk-qpd51n1j.js +0 -1
  194. package/dist/bin/chunk-rtpc6djg.js +0 -1
  195. package/dist/bin/chunk-s9k81gq6.js +0 -1
  196. package/dist/bin/chunk-wrcdcg7m.js +0 -1
  197. package/dist/bin/chunk-ybekawxv.js +0 -1
  198. package/dist/bin/chunk-zrw80j07.js +0 -1
  199. package/dist/chunk-03gf4e58.js +0 -1
  200. package/dist/chunk-86qwnp25.js +0 -1
  201. package/dist/chunk-8kn7rszy.js +0 -1
  202. package/dist/chunk-928z0h9b.js +0 -14
  203. package/dist/chunk-crpbs450.js +0 -1
  204. package/dist/chunk-m9szynnf.js +0 -6
  205. package/dist/chunk-ncet7ba7.js +0 -1
  206. package/dist/chunk-nh7rcks9.js +0 -1
  207. package/dist/chunk-ypsfkgme.js +0 -1
@@ -0,0 +1 @@
1
+ import{Yt,gu,fu,es,p,k,ya}from"./chunk-0qzt0swj.js";import"./chunk-cb0yqrpk.js";import"./chunk-8ctmc30y.js";export{p as AWSClient,k as buildQueryParams,fu as canonicalUriFor,es as coerceXmlValues,ya as detectCredentialSource,Yt as resolveS3Endpoint,gu as signingNameFor};
@@ -1,2 +1,2 @@
1
- function Xs(n){let t=new RegExp("[\\u007F-\\uFFFF]","g");return JSON.stringify(n).replace(t,(o)=>`\\u${o.charCodeAt(0).toString(16).padStart(4,"0")}`)}
2
- export{Xs};
1
+ function ia(n){let t=new RegExp("[\\u007F-\\uFFFF]","g");return JSON.stringify(n).replace(t,(o)=>`\\u${o.charCodeAt(0).toString(16).padStart(4,"0")}`)}
2
+ export{ia};
@@ -1,2 +1,2 @@
1
- import{p}from"./chunk-btrxye8p.js";import{L,x}from"./chunk-bkx2kapc.js";class V{client;region;constructor(e="us-east-1",i){this.region=e,this.client=new p}async createQueue(e){let t={Action:"CreateQueue",QueueName:e.fifo&&!e.queueName.endsWith(".fifo")?`${e.queueName}.fifo`:e.queueName,Version:"2012-11-05"},s=1;if(e.visibilityTimeout!==void 0)t[`Attribute.${s}.Name`]="VisibilityTimeout",t[`Attribute.${s}.Value`]=e.visibilityTimeout.toString(),s++;if(e.messageRetentionPeriod!==void 0)t[`Attribute.${s}.Name`]="MessageRetentionPeriod",t[`Attribute.${s}.Value`]=e.messageRetentionPeriod.toString(),s++;if(e.delaySeconds!==void 0)t[`Attribute.${s}.Name`]="DelaySeconds",t[`Attribute.${s}.Value`]=e.delaySeconds.toString(),s++;if(e.maxMessageSize!==void 0)t[`Attribute.${s}.Name`]="MaximumMessageSize",t[`Attribute.${s}.Value`]=e.maxMessageSize.toString(),s++;if(e.receiveMessageWaitTime!==void 0)t[`Attribute.${s}.Name`]="ReceiveMessageWaitTimeSeconds",t[`Attribute.${s}.Value`]=e.receiveMessageWaitTime.toString(),s++;if(e.fifo){if(t[`Attribute.${s}.Name`]="FifoQueue",t[`Attribute.${s}.Value`]="true",s++,e.contentBasedDeduplication)t[`Attribute.${s}.Name`]="ContentBasedDeduplication",t[`Attribute.${s}.Value`]="true",s++}if(e.deadLetterTargetArn&&e.maxReceiveCount)t[`Attribute.${s}.Name`]="RedrivePolicy",t[`Attribute.${s}.Value`]=JSON.stringify({deadLetterTargetArn:e.deadLetterTargetArn,maxReceiveCount:e.maxReceiveCount}),s++;if(e.tags&&Object.keys(e.tags).length>0){let a=1;for(let[u,n]of Object.entries(e.tags))t[`Tag.${a}.Key`]=u,t[`Tag.${a}.Value`]=n,a++}let r=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{QueueUrl:r.QueueUrl||r.CreateQueueResult?.QueueUrl}}async listQueues(e){let i={Action:"ListQueues",Version:"2012-11-05"};if(e)i.QueueNamePrefix=e;let t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()}),s=[];if(t.QueueUrl)s.push(t.QueueUrl);else if(t.ListQueuesResult?.QueueUrl)if(Array.isArray(t.ListQueuesResult.QueueUrl))s.push(...t.ListQueuesResult.QueueUrl);else s.push(t.ListQueuesResult.QueueUrl);return{QueueUrls:s}}async getQueueAttributes(e){let i={Action:"GetQueueAttributes",QueueUrl:e,Version:"2012-11-05","AttributeName.1":"All"},t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()}),s={};for(let r of x(L(t,"GetQueueAttributes")?.Attribute))s[r.Name]=String(r.Value);return{Attributes:s}}async getQueueUrl(e){let i={Action:"GetQueueUrl",QueueName:e,Version:"2012-11-05"},t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()});return{QueueUrl:t.QueueUrl||t.GetQueueUrlResult?.QueueUrl}}async deleteQueue(e){let i={Action:"DeleteQueue",QueueUrl:e,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()})}async purgeQueue(e){let i={Action:"PurgeQueue",QueueUrl:e,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()})}async sendMessage(e){let i={Action:"SendMessage",QueueUrl:e.queueUrl,MessageBody:e.messageBody,Version:"2012-11-05"};if(e.delaySeconds!==void 0)i.DelaySeconds=e.delaySeconds;if(e.messageGroupId)i.MessageGroupId=e.messageGroupId;if(e.messageDeduplicationId)i.MessageDeduplicationId=e.messageDeduplicationId;let t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()});return{MessageId:t.MessageId||t.SendMessageResult?.MessageId}}async receiveMessages(e){let i={Action:"ReceiveMessage",QueueUrl:e.queueUrl,Version:"2012-11-05"};if(e.maxMessages!==void 0)i.MaxNumberOfMessages=e.maxMessages;if(e.visibilityTimeout!==void 0)i.VisibilityTimeout=e.visibilityTimeout;if(e.waitTimeSeconds!==void 0)i.WaitTimeSeconds=e.waitTimeSeconds;let t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()}),s=[],r=t.Message||t.ReceiveMessageResult?.Message;if(r)if(Array.isArray(r))s.push(...r.map((a)=>({MessageId:a.MessageId,ReceiptHandle:a.ReceiptHandle,Body:a.Body})));else s.push({MessageId:r.MessageId,ReceiptHandle:r.ReceiptHandle,Body:r.Body});return{Messages:s}}async deleteMessage(e,i){let t={Action:"DeleteMessage",QueueUrl:e,ReceiptHandle:i,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()})}}
1
+ import{p}from"./chunk-0qzt0swj.js";import{L,x}from"./chunk-ncj8dpdp.js";class V{client;region;constructor(e="us-east-1",i){this.region=e,this.client=new p}async createQueue(e){let t={Action:"CreateQueue",QueueName:e.fifo&&!e.queueName.endsWith(".fifo")?`${e.queueName}.fifo`:e.queueName,Version:"2012-11-05"},s=1;if(e.visibilityTimeout!==void 0)t[`Attribute.${s}.Name`]="VisibilityTimeout",t[`Attribute.${s}.Value`]=e.visibilityTimeout.toString(),s++;if(e.messageRetentionPeriod!==void 0)t[`Attribute.${s}.Name`]="MessageRetentionPeriod",t[`Attribute.${s}.Value`]=e.messageRetentionPeriod.toString(),s++;if(e.delaySeconds!==void 0)t[`Attribute.${s}.Name`]="DelaySeconds",t[`Attribute.${s}.Value`]=e.delaySeconds.toString(),s++;if(e.maxMessageSize!==void 0)t[`Attribute.${s}.Name`]="MaximumMessageSize",t[`Attribute.${s}.Value`]=e.maxMessageSize.toString(),s++;if(e.receiveMessageWaitTime!==void 0)t[`Attribute.${s}.Name`]="ReceiveMessageWaitTimeSeconds",t[`Attribute.${s}.Value`]=e.receiveMessageWaitTime.toString(),s++;if(e.fifo){if(t[`Attribute.${s}.Name`]="FifoQueue",t[`Attribute.${s}.Value`]="true",s++,e.contentBasedDeduplication)t[`Attribute.${s}.Name`]="ContentBasedDeduplication",t[`Attribute.${s}.Value`]="true",s++}if(e.deadLetterTargetArn&&e.maxReceiveCount)t[`Attribute.${s}.Name`]="RedrivePolicy",t[`Attribute.${s}.Value`]=JSON.stringify({deadLetterTargetArn:e.deadLetterTargetArn,maxReceiveCount:e.maxReceiveCount}),s++;if(e.tags&&Object.keys(e.tags).length>0){let a=1;for(let[u,n]of Object.entries(e.tags))t[`Tag.${a}.Key`]=u,t[`Tag.${a}.Value`]=n,a++}let r=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{QueueUrl:r.QueueUrl||r.CreateQueueResult?.QueueUrl}}async listQueues(e){let i={Action:"ListQueues",Version:"2012-11-05"};if(e)i.QueueNamePrefix=e;let t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()}),s=[];if(t.QueueUrl)s.push(t.QueueUrl);else if(t.ListQueuesResult?.QueueUrl)if(Array.isArray(t.ListQueuesResult.QueueUrl))s.push(...t.ListQueuesResult.QueueUrl);else s.push(t.ListQueuesResult.QueueUrl);return{QueueUrls:s}}async getQueueAttributes(e){let i={Action:"GetQueueAttributes",QueueUrl:e,Version:"2012-11-05","AttributeName.1":"All"},t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()}),s={};for(let r of x(L(t,"GetQueueAttributes")?.Attribute))s[r.Name]=String(r.Value);return{Attributes:s}}async getQueueUrl(e){let i={Action:"GetQueueUrl",QueueName:e,Version:"2012-11-05"},t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()});return{QueueUrl:t.QueueUrl||t.GetQueueUrlResult?.QueueUrl}}async deleteQueue(e){let i={Action:"DeleteQueue",QueueUrl:e,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()})}async purgeQueue(e){let i={Action:"PurgeQueue",QueueUrl:e,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()})}async sendMessage(e){let i={Action:"SendMessage",QueueUrl:e.queueUrl,MessageBody:e.messageBody,Version:"2012-11-05"};if(e.delaySeconds!==void 0)i.DelaySeconds=e.delaySeconds;if(e.messageGroupId)i.MessageGroupId=e.messageGroupId;if(e.messageDeduplicationId)i.MessageDeduplicationId=e.messageDeduplicationId;let t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()});return{MessageId:t.MessageId||t.SendMessageResult?.MessageId}}async receiveMessages(e){let i={Action:"ReceiveMessage",QueueUrl:e.queueUrl,Version:"2012-11-05"};if(e.maxMessages!==void 0)i.MaxNumberOfMessages=e.maxMessages;if(e.visibilityTimeout!==void 0)i.VisibilityTimeout=e.visibilityTimeout;if(e.waitTimeSeconds!==void 0)i.WaitTimeSeconds=e.waitTimeSeconds;let t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()}),s=[],r=t.Message||t.ReceiveMessageResult?.Message;if(r)if(Array.isArray(r))s.push(...r.map((a)=>({MessageId:a.MessageId,ReceiptHandle:a.ReceiptHandle,Body:a.Body})));else s.push({MessageId:r.MessageId,ReceiptHandle:r.ReceiptHandle,Body:r.Body});return{Messages:s}}async deleteMessage(e,i){let t={Action:"DeleteMessage",QueueUrl:e,ReceiptHandle:i,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()})}}
2
2
  export{V};
@@ -1,11 +1,11 @@
1
- import{H,Fr}from"./chunk-9bmaq8q7.js";function W(e,t){return`/var/www/${e}-${t}`}var me=new Set(["laravel","php","statamic","wordpress"]);function ki(e){return e.type!=null&&me.has(e.type)}function Bs(e){let t=e.proxyTo;if(t==null)return[];return(Array.isArray(t)?t:[t]).map((s)=>String(s).trim()).filter((s)=>s.length>0)}function fe(e){return Bs(e).length>0}function re(e){if(e.deploy)return e.deploy;if(ki(e))return"server";if(e.start)return"server";return"bucket"}function A(e){if(e.redirect)return"redirect";if(fe(e))return"proxy";if(ki(e))return"server-php";if(re(e)==="bucket")return"bucket";return e.start?"server-app":"server-static"}function Io(e){return e.infrastructure?.compute!=null||Boolean(e.cloud?.attachTo?.trim())}function Fs(e,t={}){let r=[],s=[],o=e.sites||{},n=Io(e),a=Fr(e);if(a)r.push(a);let p=new Map;for(let[c,i]of Object.entries(o)){if(!i)continue;let m=re(i),C=A(i);if(C==="redirect"){if(!i.domain)r.push(`Site '${c}' is a redirect site but has no \`domain\` to redirect from.`);if(!(typeof i.redirect==="string"?i.redirect:i.redirect?.to))r.push(`Site '${c}' is a redirect site but has no redirect target (\`redirect\` / \`redirect.to\`).`);if(!n)r.push(`Site '${c}' is a redirect site but no \`infrastructure.compute\` is configured to host the gateway that serves the redirect.`);let l=[];if(i.start)l.push("start");if(i.root)l.push("root");if(i.proxyTo)l.push("proxyTo");if(l.length>0)s.push(`Site '${c}' is a redirect site but also sets ${l.join(", ")}. These are ignored.`);continue}if(C==="proxy"){if(!i.domain)r.push(`Site '${c}' is a proxy site but has no \`domain\` to route from.`);if(!n)r.push(`Site '${c}' is a proxy site but no \`infrastructure.compute\` is configured to host the gateway that forwards it.`);let u=[];if(i.start)u.push("start");if(i.root)u.push("root");if(typeof i.port==="number")u.push("port");if(i.build)u.push("build");if(i.preStart&&i.preStart.length>0)u.push("preStart");if(u.length>0)s.push(`Site '${c}' sets \`proxyTo\`, so ts-cloud ships and supervises nothing for it. ${u.join(", ")} ${u.length===1?"is":"are"} ignored — remove ${u.length===1?"it":"them"}, or drop \`proxyTo\` to let ts-cloud own the service.`);continue}if(m==="server"&&!i.start&&!i.root){r.push(`Site '${c}' sets deploy:'server' but declares neither \`start\` (dynamic app) nor \`root\` (static site to serve). Add one.`);continue}if(C==="server-php"){if(!n)r.push(`Site '${c}' is a PHP site (type:'${i.type}') but no \`infrastructure.compute\` is configured. Add a server (infrastructure.compute) with PHP provisioning.`);if(!i.repository?.url)r.push(`Site '${c}' is a PHP site (type:'${i.type}') but has no \`repository.url\` to clone. PHP sites deploy via git.`)}else if(C==="server-app"){if(!n)r.push(`Site '${c}' deploys to a server (deploy:'server'${i.deploy?"":" inferred from `start`"}) but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`);if(typeof i.port==="number"){let u=t.occupiedPorts?.get(i.port);if(u)r.push(`Site '${c}' wants port ${i.port}, which project '${u}' already serves on this box. Attached projects share one port namespace. Give '${c}' a free port, or let the attach allocate one.`);let l=p.get(i.port);if(l)r.push(`Sites '${l}' and '${c}' both use port ${i.port}. Server apps sharing a box must use distinct ports.`);else p.set(i.port,c)}}else if(C==="server-static"){if(!i.root)r.push(`Site '${c}' is a server static site (deploy:'server', no \`start\`) but has no \`root\` directory to serve.`);if(!n)r.push(`Site '${c}' deploys to a server (deploy:'server') but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`)}else{if(!i.root)r.push(`Site '${c}' deploys to a bucket but has no \`root\` directory to upload.`);let u=[];if(i.start)u.push("start");if(typeof i.port==="number")u.push("port");if(i.preStart&&i.preStart.length>0)u.push("preStart");if(u.length>0)s.push(`Site '${c}' deploys to a bucket but sets server-only field(s): ${u.join(", ")}. These are ignored. Set deploy:'server' to use them.`)}}return{errors:r,warnings:s}}function js(e){let t=A(e);return t!=="bucket"&&t!=="redirect"&&t!=="proxy"}function Wc(e){return A(e)==="bucket"}function Kc(e,t){if(H(e)==="serverless")return!0;let r=Object.entries(e.sites??{}).filter(([,o])=>o!=null),s=t?r.filter(([o])=>o===t):r;if(s.length===0)return!0;return!s.every(([,o])=>{let n=A(o);return n==="redirect"||n==="proxy"})}var x={php:"php.net",nginx:"nginx.org",composer:"getcomposer.org",mysql:"mysql.com",mariadb:"mariadb.com/server",postgres:"postgresql.org",vitess:"vitess.io",etcd:"etcd.io",redis:"redis.io",memcached:"memcached.org",meilisearch:"meilisearch.com",mail:"github.com/mail-os/mail",git:"git-scm.com",certbot:"certbot.eff.org",bun:"bun.sh",node:"nodejs.org",deno:"deno.land"};var R="/opt/pantry";function U(e){return`'${e.split("'").join("'\\''")}'`}function Tt(e={}){let t=e.installDir??"/usr/local/bin",r=e.version?`export PANTRY_VERSION=${U(e.version)}`:'export PANTRY_VERSION="${PANTRY_VERSION:-latest}"';return["export DEBIAN_FRONTEND=noninteractive","export PANTRY_SERVICE_SCOPE=system",`export PANTRY_INSTALL_DIR=${t}`,r,"command -v curl >/dev/null 2>&1 || (apt-get update -y && apt-get install -y curl ca-certificates)","command -v unzip >/dev/null 2>&1 || (apt-get update -y && apt-get install -y unzip)",`OS=$(uname -s | tr '[:upper:]' '[:lower:]'); ARCH=$(uname -m); case "$ARCH" in x86_64|amd64) ARCH=x64 ;; arm64|aarch64) ARCH=arm64 ;; esac; ZIP="pantry-\${OS}-\${ARCH}.zip"; if [ "\${PANTRY_VERSION:-latest}" = latest ]; then REL='latest/download'; else REL="download/v\${PANTRY_VERSION}"; fi; TMP=$(mktemp -d); curl -fsSL -o "\${TMP}/\${ZIP}" "https://github.com/pantry-pm/pantry/releases/\${REL}/\${ZIP}"; mkdir -p ${t}; unzip -o "\${TMP}/\${ZIP}" -d ${t}; chmod +x ${t}/pantry; rm -rf "\${TMP}"`,`export PATH="${t}:$PATH"`,"mkdir -p /opt/pantry"]}function Ve(){return'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true'}function it(e){if(e.length===0)return[];let t=[...new Set(e)],r=new Set(["/opt/pantry","/opt/pantry/pantry"]);for(let o of t){let n="/opt/pantry/pantry";for(let a of o.split("@")[0].split("/")){if(!/^[a-zA-Z0-9._-]+$/.test(a))throw Error("Invalid pantry package domain");n+=`/${a}`,r.add(n)}}let s=[...r].map(U).join(" ");return[`(umask 022; mkdir -p ${s} && chmod 0755 ${s} && cd /opt/pantry && pantry install ${t.map(U).join(" ")})`]}function Po(e){return[...new Set(e)].flatMap((t)=>[`(cd /opt/pantry && pantry start ${U(t)})`,`(cd /opt/pantry && pantry enable ${U(t)})`])}var S="/etc/mail",g="mail-server",F="mail",Y=`${R}/pantry/.bin`;function h(e){return`'${String(e).split("'").join("'\\''")}'`}function P(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function Te(e){return[e.version?`${x.mail}@${e.version}`:x.mail]}function K(e,t){return`${S}/dkim/${t}.${e.dkim.selector}.pem`}function se(e){return`${e.storagePath}/smtp.db`}function ge(e){let t=["# Generated by ts-cloud. Edits are overwritten on the next deploy —","# change `services.mail` in the cloud config instead.","","[server]",`host = ${P(e.bindAddress)}`,`port = ${e.ports.smtp}`,`hostname = ${P(e.hostname)}`];if(e.domains.length>0)t.push(`local_domains = ${P(e.domains.join(", "))}`);if(e.mode==="catcher")t.push("catch_all = true");if(t.push(`max_message_size = ${e.maxMessageSize}`,"","[tls]",`enabled = ${e.tls.enabled}`),e.tls.certPath)t.push(`cert_path = ${P(e.tls.certPath)}`);if(e.tls.keyPath)t.push(`key_path = ${P(e.tls.keyPath)}`);if(t.push("","[auth]",`enabled = ${e.mode==="server"}`,"","[antispam]",`dnsbl = ${e.spam.dnsbl}`,`dnsbl_reject = ${e.spam.dnsblReject}`,`greylist = ${e.spam.greylist}`,`spam_filter = ${e.spam.enabled}`,`junk_score = ${e.spam.junkScore}`,`reject_score = ${e.spam.rejectScore}`,"","[dkim]",`rotation_enabled = ${e.dkim.enabled&&e.dkim.rotate}`,`rotation_interval_days = ${e.dkim.rotateIntervalDays}`,"","[acme]",`enabled = ${e.tls.acme}`),e.tls.acmeEmail)t.push(`email = ${P(e.tls.acmeEmail)}`);if(t.push("","[webhook]",`enabled = ${!!e.webhookUrl}`),e.webhookUrl)t.push(`url = ${P(e.webhookUrl)}`);return t.push(""),t.join(`
1
+ import{H,Vr}from"./chunk-cb0yqrpk.js";function W(e,t){return`/var/www/${e}-${t}`}var me=new Set(["laravel","php","statamic","wordpress"]);function xi(e){return e.type!=null&&me.has(e.type)}function Ws(e){let t=e.proxyTo;if(t==null)return[];return(Array.isArray(t)?t:[t]).map((s)=>String(s).trim()).filter((s)=>s.length>0)}function fe(e){return Ws(e).length>0}function re(e){if(e.deploy)return e.deploy;if(xi(e))return"server";if(e.start)return"server";return"bucket"}function A(e){if(e.redirect)return"redirect";if(fe(e))return"proxy";if(xi(e))return"server-php";if(re(e)==="bucket")return"bucket";return e.start?"server-app":"server-static"}function xo(e){return e.infrastructure?.compute!=null||Boolean(e.cloud?.attachTo?.trim())}function Ks(e,t={}){let r=[],s=[],o=e.sites||{},n=xo(e),a=Vr(e);if(a)r.push(a);let p=new Map;for(let[c,i]of Object.entries(o)){if(!i)continue;let m=re(i),C=A(i);if(C==="redirect"){if(!i.domain)r.push(`Site '${c}' is a redirect site but has no \`domain\` to redirect from.`);if(!(typeof i.redirect==="string"?i.redirect:i.redirect?.to))r.push(`Site '${c}' is a redirect site but has no redirect target (\`redirect\` / \`redirect.to\`).`);if(!n)r.push(`Site '${c}' is a redirect site but no \`infrastructure.compute\` is configured to host the gateway that serves the redirect.`);let l=[];if(i.start)l.push("start");if(i.root)l.push("root");if(i.proxyTo)l.push("proxyTo");if(l.length>0)s.push(`Site '${c}' is a redirect site but also sets ${l.join(", ")}. These are ignored.`);continue}if(C==="proxy"){if(!i.domain)r.push(`Site '${c}' is a proxy site but has no \`domain\` to route from.`);if(!n)r.push(`Site '${c}' is a proxy site but no \`infrastructure.compute\` is configured to host the gateway that forwards it.`);let u=[];if(i.start)u.push("start");if(i.root)u.push("root");if(typeof i.port==="number")u.push("port");if(i.build)u.push("build");if(i.preStart&&i.preStart.length>0)u.push("preStart");if(u.length>0)s.push(`Site '${c}' sets \`proxyTo\`, so ts-cloud ships and supervises nothing for it. ${u.join(", ")} ${u.length===1?"is":"are"} ignored — remove ${u.length===1?"it":"them"}, or drop \`proxyTo\` to let ts-cloud own the service.`);continue}if(m==="server"&&!i.start&&!i.root){r.push(`Site '${c}' sets deploy:'server' but declares neither \`start\` (dynamic app) nor \`root\` (static site to serve). Add one.`);continue}if(C==="server-php"){if(!n)r.push(`Site '${c}' is a PHP site (type:'${i.type}') but no \`infrastructure.compute\` is configured. Add a server (infrastructure.compute) with PHP provisioning.`);if(!i.repository?.url)r.push(`Site '${c}' is a PHP site (type:'${i.type}') but has no \`repository.url\` to clone. PHP sites deploy via git.`)}else if(C==="server-app"){if(!n)r.push(`Site '${c}' deploys to a server (deploy:'server'${i.deploy?"":" inferred from `start`"}) but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`);if(typeof i.port==="number"){let u=t.occupiedPorts?.get(i.port);if(u)r.push(`Site '${c}' wants port ${i.port}, which project '${u}' already serves on this box. Attached projects share one port namespace. Give '${c}' a free port, or let the attach allocate one.`);let l=p.get(i.port);if(l)r.push(`Sites '${l}' and '${c}' both use port ${i.port}. Server apps sharing a box must use distinct ports.`);else p.set(i.port,c)}}else if(C==="server-static"){if(!i.root)r.push(`Site '${c}' is a server static site (deploy:'server', no \`start\`) but has no \`root\` directory to serve.`);if(!n)r.push(`Site '${c}' deploys to a server (deploy:'server') but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`)}else{if(!i.root)r.push(`Site '${c}' deploys to a bucket but has no \`root\` directory to upload.`);let u=[];if(i.start)u.push("start");if(typeof i.port==="number")u.push("port");if(i.preStart&&i.preStart.length>0)u.push("preStart");if(u.length>0)s.push(`Site '${c}' deploys to a bucket but sets server-only field(s): ${u.join(", ")}. These are ignored. Set deploy:'server' to use them.`)}}return{errors:r,warnings:s}}function Js(e){let t=A(e);return t!=="bucket"&&t!=="redirect"&&t!=="proxy"}function tl(e){return A(e)==="bucket"}function rl(e,t){if(H(e)==="serverless")return!0;let r=Object.entries(e.sites??{}).filter(([,o])=>o!=null),s=t?r.filter(([o])=>o===t):r;if(s.length===0)return!0;return!s.every(([,o])=>{let n=A(o);return n==="redirect"||n==="proxy"})}var x={php:"php.net",nginx:"nginx.org",composer:"getcomposer.org",mysql:"mysql.com",mariadb:"mariadb.com/server",postgres:"postgresql.org",vitess:"vitess.io",etcd:"etcd.io",redis:"redis.io",memcached:"memcached.org",meilisearch:"meilisearch.com",mail:"github.com/mail-os/mail",git:"git-scm.com",certbot:"certbot.eff.org",bun:"bun.sh",node:"nodejs.org",deno:"deno.land"};var R="/opt/pantry";function U(e){return`'${e.split("'").join("'\\''")}'`}function wt(e={}){let t=e.installDir??"/usr/local/bin",r=e.version?`export PANTRY_VERSION=${U(e.version)}`:'export PANTRY_VERSION="${PANTRY_VERSION:-latest}"';return["export DEBIAN_FRONTEND=noninteractive","export PANTRY_SERVICE_SCOPE=system",`export PANTRY_INSTALL_DIR=${t}`,r,"command -v curl >/dev/null 2>&1 || (apt-get update -y && apt-get install -y curl ca-certificates)","command -v unzip >/dev/null 2>&1 || (apt-get update -y && apt-get install -y unzip)",`OS=$(uname -s | tr '[:upper:]' '[:lower:]'); ARCH=$(uname -m); case "$ARCH" in x86_64|amd64) ARCH=x64 ;; arm64|aarch64) ARCH=arm64 ;; esac; ZIP="pantry-\${OS}-\${ARCH}.zip"; if [ "\${PANTRY_VERSION:-latest}" = latest ]; then REL='latest/download'; else REL="download/v\${PANTRY_VERSION}"; fi; TMP=$(mktemp -d); curl -fsSL -o "\${TMP}/\${ZIP}" "https://github.com/pantry-pm/pantry/releases/\${REL}/\${ZIP}"; mkdir -p ${t}; unzip -o "\${TMP}/\${ZIP}" -d ${t}; chmod +x ${t}/pantry; rm -rf "\${TMP}"`,`export PATH="${t}:$PATH"`,"mkdir -p /opt/pantry"]}function ze(){return'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true'}function st(e){if(e.length===0)return[];let t=[...new Set(e)],r=new Set(["/opt/pantry","/opt/pantry/pantry"]);for(let o of t){let n="/opt/pantry/pantry";for(let a of o.split("@")[0].split("/")){if(!/^[a-zA-Z0-9._-]+$/.test(a))throw Error("Invalid pantry package domain");n+=`/${a}`,r.add(n)}}let s=[...r].map(U).join(" ");return[`(umask 022; mkdir -p ${s} && chmod 0755 ${s} && cd /opt/pantry && pantry install ${t.map(U).join(" ")})`]}function _o(e){return[...new Set(e)].flatMap((t)=>[`(cd /opt/pantry && pantry start ${U(t)})`,`(cd /opt/pantry && pantry enable ${U(t)})`])}var S="/etc/mail",g="mail-server",F="mail",Y=`${R}/pantry/.bin`;function h(e){return`'${String(e).split("'").join("'\\''")}'`}function P(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function Te(e){return[e.version?`${x.mail}@${e.version}`:x.mail]}function K(e,t){return`${S}/dkim/${t}.${e.dkim.selector}.pem`}function se(e){return`${e.storagePath}/smtp.db`}function ge(e){let t=["# Generated by ts-cloud. Edits are overwritten on the next deploy —","# change `services.mail` in the cloud config instead.","","[server]",`host = ${P(e.bindAddress)}`,`port = ${e.ports.smtp}`,`hostname = ${P(e.hostname)}`];if(e.domains.length>0)t.push(`local_domains = ${P(e.domains.join(", "))}`);if(e.mode==="catcher")t.push("catch_all = true");if(t.push(`max_message_size = ${e.maxMessageSize}`,"","[tls]",`enabled = ${e.tls.enabled}`),e.tls.certPath)t.push(`cert_path = ${P(e.tls.certPath)}`);if(e.tls.keyPath)t.push(`key_path = ${P(e.tls.keyPath)}`);if(t.push("","[auth]",`enabled = ${e.mode==="server"}`,"","[antispam]",`dnsbl = ${e.spam.dnsbl}`,`dnsbl_reject = ${e.spam.dnsblReject}`,`greylist = ${e.spam.greylist}`,`spam_filter = ${e.spam.enabled}`,`junk_score = ${e.spam.junkScore}`,`reject_score = ${e.spam.rejectScore}`,"","[dkim]",`rotation_enabled = ${e.dkim.enabled&&e.dkim.rotate}`,`rotation_interval_days = ${e.dkim.rotateIntervalDays}`,"","[acme]",`enabled = ${e.tls.acme}`),e.tls.acmeEmail)t.push(`email = ${P(e.tls.acmeEmail)}`);if(t.push("","[webhook]",`enabled = ${!!e.webhookUrl}`),e.webhookUrl)t.push(`url = ${P(e.webhookUrl)}`);return t.push(""),t.join(`
2
2
  `)}function he(e){let t=["# Generated by ts-cloud. See /etc/mail/config.toml for the rest.",`SMTP_HOSTNAME=${e.hostname}`,`SMTP_DB_PATH=${se(e)}`,`SMTP_DNSBL_REJECT=${e.spam.dnsblReject}`,`SMTP_DELIVERY_METHOD=${e.delivery==="ses"?"ses":"direct"}`];if(e.delivery==="ses")t.push(`SMTP_SES_REGION=${e.sesRegion}`);if(e.ports.submission)t.push(`SUBMISSION_PORT=${e.ports.submission}`);if(e.ports.submissions)t.push(`SMTPS_PORT=${e.ports.submissions}`);if(e.ports.imap)t.push("IMAP_ENABLED=1",`IMAP_PORT=${e.ports.imap}`);if(e.webmail.enabled)t.push("SMTP_ENABLE_WEBMAIL=true",`SMTP_WEBMAIL_PORT=${e.webmail.port}`,`SMTP_WEBMAIL_TLS=${e.webmail.tls}`,`SMTP_WEBMAIL_SECURE_COOKIES=${e.webmail.secureCookies}`,`SMTP_WEBMAIL_ATTACHMENT_MAX_FILE=${e.webmail.attachmentMaxFileBytes}`,`SMTP_WEBMAIL_ATTACHMENT_MAX_TOTAL=${e.webmail.attachmentMaxTotalBytes}`,`SMTP_WEBMAIL_ATTACHMENT_MAX_COUNT=${e.webmail.attachmentMaxCount}`,`SMTP_WEBMAIL_UNDO_SEND_SECONDS=${e.webmail.undoSendSeconds}`);if(e.tls.requireForAuth)t.push("SMTP_REQUIRE_TLS_FOR_AUTH=true");if(e.dkim.enabled&&e.domains.length>0){let r=e.domains.find((o)=>o!==e.hostname)||e.hostname,s=e.domains.filter((o)=>o!==r);if(t.push(`DKIM_DOMAIN=${r}`,`DKIM_SELECTOR=${e.dkim.selector}`,`DKIM_PRIVATE_KEY_PATH=${K(e,r)}`),s.length>0){let o=s.map((n)=>`${n}:${e.dkim.selector}:${K(e,n)}`);t.push(`DKIM_EXTRA_KEYS=${o.join(",")}`)}}return t.push(""),t.join(`
3
3
  `)}function ye(e){let t=[e.ports.smtp,e.ports.submission,e.ports.submissions,e.ports.imap,e.ports.imaps].some((r)=>typeof r==="number"&&r<1024);return["[Unit]","Description=Mail server (SMTP/IMAP + webmail)","After=network-online.target","Wants=network-online.target","","[Service]","Type=simple",`User=${g}`,`Group=${g}`,`WorkingDirectory=${e.storagePath}`,`EnvironmentFile=${S}/mail.env`,...e.tls.systemCredentials?[`LoadCredential=server.crt:${e.tls.systemCredentials.certPath}`,`LoadCredential=server.key:${e.tls.systemCredentials.keyPath}`]:[],`Environment="PATH=${Y}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"`,`ExecStart=${Y}/mail serve --config ${S}/config.toml`,"Restart=always","RestartSec=5","LimitNOFILE=65536",...t?["AmbientCapabilities=CAP_NET_BIND_SERVICE","CapabilityBoundingSet=CAP_NET_BIND_SERVICE"]:[],"NoNewPrivileges=true","PrivateTmp=true","ProtectSystem=strict","ProtectHome=true","ProtectKernelTunables=true","ProtectKernelModules=true","ProtectControlGroups=true",`ReadWritePaths=${e.storagePath} ${S}`,"","[Install]","WantedBy=multi-user.target",""].join(`
4
- `)}function Ee(e){if(!e.dkim.enabled||e.domains.length===0)return[];let t=[`mkdir -p ${S}/dkim`];for(let r of e.domains){let s=K(e,r);t.push(`if [ ! -f ${h(s)} ]; then openssl genrsa -out ${h(s)} 2048; fi`,`chmod 0600 ${h(s)}`,`echo "DKIM ${e.dkim.selector}._domainkey.${r} IN TXT v=DKIM1; k=rsa; p=$(openssl rsa -in ${h(s)} -pubout -outform PEM 2>/dev/null | grep -v '^-----' | tr -d '\\n')"`)}return t.push(`chown -R ${g}:${g} ${S}/dkim`),t}function ve(e){if(e.accounts.length===0)return[];let t=(r)=>`runuser -u ${g} -- env SMTP_DB_PATH="$TS_CLOUD_MAIL_DB" ${Y}/mail user:local ${r}`;return e.accounts.flatMap((r)=>[t(`create ${h(r.address)} ${h(r.password)} ${h(r.address)}`),...r.passwordPolicy==="managed"?[t(`change-password ${h(r.address)} ${h(r.password)}`)]:[]])}function Do(e){if(!e.enabled)return[];return[...it(Te(e)),`id -u ${g} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin ${g}`,`mkdir -p ${e.storagePath} ${S}`,`chown root:${g} ${S}`,`chmod 0750 ${S}`,`chown -R ${g}:${g} ${e.storagePath}`,`TS_CLOUD_MAIL_DB="$(grep -sE '^SMTP_DB_PATH=' ${S}/mail.env | head -1 | cut -d= -f2- || true)"`,`[ -n "$TS_CLOUD_MAIL_DB" ] || TS_CLOUD_MAIL_DB=${h(se(e))}`,`cat > ${S}/config.toml <<'TS_CLOUD_MAIL_CONF_EOF'`,ge(e),"TS_CLOUD_MAIL_CONF_EOF",`cat > ${S}/mail.env <<'TS_CLOUD_MAIL_ENV_EOF'`,he(e),"TS_CLOUD_MAIL_ENV_EOF",`sed -i "s|^SMTP_DB_PATH=.*|SMTP_DB_PATH=$TS_CLOUD_MAIL_DB|" ${S}/mail.env`,`chmod 0640 ${S}/mail.env ${S}/config.toml`,`chown root:${g} ${S}/mail.env ${S}/config.toml`,...Ee(e),`cat > /etc/systemd/system/${F}.service <<'TS_CLOUD_MAIL_UNIT_EOF'`,ye(e),"TS_CLOUD_MAIL_UNIT_EOF",...e.tls.systemCredentials?["cat > /etc/systemd/system/ts-cloud-mail-tls.path <<'TS_CLOUD_MAIL_TLS_PATH'","[Unit]","Description=Refresh mail after gateway certificate renewal","[Path]",`PathChanged=${e.tls.systemCredentials.certPath}`,`PathChanged=${e.tls.systemCredentials.keyPath}`,"Unit=ts-cloud-mail-tls.service","[Install]","WantedBy=multi-user.target","TS_CLOUD_MAIL_TLS_PATH","cat > /etc/systemd/system/ts-cloud-mail-tls.service <<'TS_CLOUD_MAIL_TLS_UNIT'","[Unit]","Description=Load renewed mail TLS credentials","[Service]","Type=oneshot","ExecStart=/usr/bin/systemctl restart mail.service","TS_CLOUD_MAIL_TLS_UNIT"]:["systemctl disable --now ts-cloud-mail-tls.path 2>/dev/null || true"],"systemctl daemon-reload",...e.tls.systemCredentials?["systemctl enable --now ts-cloud-mail-tls.path"]:[],`systemctl enable ${F}`,`systemctl restart ${F}`,...ve(e)]}var T=`${R}/pantry/.bin`,z=15306,j=15991,w=15999,ne=16101,B=2379,y="/var/lib/vitess",J=100;function Ni(e){return e===!0||typeof e==="object"&&e!==null}function Ce(e){return typeof e==="object"&&e!==null?e:{}}function _(e){return`'${String(e).split("'").join("'\\''")}'`}function Pe(e){let r=[e.version?`vitess.io@${e.version}`:"vitess.io"];if(e.mode!=="combo"&&!e.etcdEndpoint)r.push("etcd.io");return r.push("mysql.com@8.0.43"),r}var f="vitess",Re=`${T}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`,ce="/usr/local/lib/vitess",Q=new Map;function X(e){return`${ce}/${e}.sh`}function D(e,t){return Q.set(e,be(t)),`/bin/sh ${X(e)}`}function oe(){let e=[`mkdir -p ${ce}`];for(let[t,r]of Q)e.push(`cat > ${X(t)} <<'TS_CLOUD_VITESS_LAUNCHER_EOF'`,r,"TS_CLOUD_VITESS_LAUNCHER_EOF",`chmod 0755 ${X(t)}`);return e}function be(e){return["#!/bin/sh","set -e",`cd ${R}`,`PANTRY_ENV="$(pantry env 2>/dev/null | grep -E '^(export [A-Za-z_]|[A-Za-z_][A-Za-z0-9_]*=)' || true)"`,'if [ -n "$PANTRY_ENV" ]; then eval "$PANTRY_ENV"; fi',`VT_MYSQL_ROOT="$(dirname "$(dirname "$(readlink -f ${T}/mysqld 2>/dev/null)")")"`,`VTROOT="$(dirname "$(dirname "$(readlink -f ${T}/mysqlctld 2>/dev/null)")")"`,"export VT_MYSQL_ROOT VTROOT",'LD_LIBRARY_PATH="$VT_MYSQL_ROOT/lib:$VTROOT/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"',"export LD_LIBRARY_PATH",`exec ${e.join(" ")}`].join(`
4
+ `)}function Ee(e){if(!e.dkim.enabled||e.domains.length===0)return[];let t=[`mkdir -p ${S}/dkim`];for(let r of e.domains){let s=K(e,r);t.push(`if [ ! -f ${h(s)} ]; then openssl genrsa -out ${h(s)} 2048; fi`,`chmod 0600 ${h(s)}`,`echo "DKIM ${e.dkim.selector}._domainkey.${r} IN TXT v=DKIM1; k=rsa; p=$(openssl rsa -in ${h(s)} -pubout -outform PEM 2>/dev/null | grep -v '^-----' | tr -d '\\n')"`)}return t.push(`chown -R ${g}:${g} ${S}/dkim`),t}function ve(e){if(e.accounts.length===0)return[];let t=(r)=>`runuser -u ${g} -- env SMTP_DB_PATH="$TS_CLOUD_MAIL_DB" ${Y}/mail user:local ${r}`;return e.accounts.flatMap((r)=>[t(`create ${h(r.address)} ${h(r.password)} ${h(r.address)}`),...r.passwordPolicy==="managed"?[t(`change-password ${h(r.address)} ${h(r.password)}`)]:[]])}function Oo(e){if(!e.enabled)return[];return[...st(Te(e)),`id -u ${g} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin ${g}`,`mkdir -p ${e.storagePath} ${S}`,`chown root:${g} ${S}`,`chmod 0750 ${S}`,`chown -R ${g}:${g} ${e.storagePath}`,`TS_CLOUD_MAIL_DB="$(grep -sE '^SMTP_DB_PATH=' ${S}/mail.env | head -1 | cut -d= -f2- || true)"`,`[ -n "$TS_CLOUD_MAIL_DB" ] || TS_CLOUD_MAIL_DB=${h(se(e))}`,`cat > ${S}/config.toml <<'TS_CLOUD_MAIL_CONF_EOF'`,ge(e),"TS_CLOUD_MAIL_CONF_EOF",`cat > ${S}/mail.env <<'TS_CLOUD_MAIL_ENV_EOF'`,he(e),"TS_CLOUD_MAIL_ENV_EOF",`sed -i "s|^SMTP_DB_PATH=.*|SMTP_DB_PATH=$TS_CLOUD_MAIL_DB|" ${S}/mail.env`,`chmod 0640 ${S}/mail.env ${S}/config.toml`,`chown root:${g} ${S}/mail.env ${S}/config.toml`,...Ee(e),`cat > /etc/systemd/system/${F}.service <<'TS_CLOUD_MAIL_UNIT_EOF'`,ye(e),"TS_CLOUD_MAIL_UNIT_EOF",...e.tls.systemCredentials?["cat > /etc/systemd/system/ts-cloud-mail-tls.path <<'TS_CLOUD_MAIL_TLS_PATH'","[Unit]","Description=Refresh mail after gateway certificate renewal","[Path]",`PathChanged=${e.tls.systemCredentials.certPath}`,`PathChanged=${e.tls.systemCredentials.keyPath}`,"Unit=ts-cloud-mail-tls.service","[Install]","WantedBy=multi-user.target","TS_CLOUD_MAIL_TLS_PATH","cat > /etc/systemd/system/ts-cloud-mail-tls.service <<'TS_CLOUD_MAIL_TLS_UNIT'","[Unit]","Description=Load renewed mail TLS credentials","[Service]","Type=oneshot","ExecStart=/usr/bin/systemctl restart mail.service","TS_CLOUD_MAIL_TLS_UNIT"]:["systemctl disable --now ts-cloud-mail-tls.path 2>/dev/null || true"],"systemctl daemon-reload",...e.tls.systemCredentials?["systemctl enable --now ts-cloud-mail-tls.path"]:[],`systemctl enable ${F}`,`systemctl restart ${F}`,...ve(e)]}var T=`${R}/pantry/.bin`,z=15306,j=15991,w=15999,ne=16101,B=2379,y="/var/lib/vitess",J=100;function _i(e){return e===!0||typeof e==="object"&&e!==null}function Ce(e){return typeof e==="object"&&e!==null?e:{}}function _(e){return`'${String(e).split("'").join("'\\''")}'`}function Pe(e){let r=[e.version?`vitess.io@${e.version}`:"vitess.io"];if(e.mode!=="combo"&&!e.etcdEndpoint)r.push("etcd.io");return r.push("mysql.com@8.0.43"),r}var f="vitess",Re=`${T}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`,ce="/usr/local/lib/vitess",Q=new Map;function X(e){return`${ce}/${e}.sh`}function D(e,t){return Q.set(e,be(t)),`/bin/sh ${X(e)}`}function oe(){let e=[`mkdir -p ${ce}`];for(let[t,r]of Q)e.push(`cat > ${X(t)} <<'TS_CLOUD_VITESS_LAUNCHER_EOF'`,r,"TS_CLOUD_VITESS_LAUNCHER_EOF",`chmod 0755 ${X(t)}`);return e}function be(e){return["#!/bin/sh","set -e",`cd ${R}`,`PANTRY_ENV="$(pantry env 2>/dev/null | grep -E '^(export [A-Za-z_]|[A-Za-z_][A-Za-z0-9_]*=)' || true)"`,'if [ -n "$PANTRY_ENV" ]; then eval "$PANTRY_ENV"; fi',`VT_MYSQL_ROOT="$(dirname "$(dirname "$(readlink -f ${T}/mysqld 2>/dev/null)")")"`,`VTROOT="$(dirname "$(dirname "$(readlink -f ${T}/mysqlctld 2>/dev/null)")")"`,"export VT_MYSQL_ROOT VTROOT",'LD_LIBRARY_PATH="$VT_MYSQL_ROOT/lib:$VTROOT/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"',"export LD_LIBRARY_PATH",`exec ${e.join(" ")}`].join(`
5
5
  `)}function L(e){let t=["[Unit]",`Description=${e.description}`,`After=network.target${e.after?.length?` ${e.after.join(" ")}`:""}`];if(e.requires?.length)t.push(`Requires=${e.requires.join(" ")}`);return t.push("","[Service]","Type=simple",`User=${f}`,`Group=${f}`,`Environment="PATH=${Re}"`,`Environment="VTDATAROOT=${y}"`,...Object.entries(e.environment??{}).map(([r,s])=>`Environment="${r}=${s}"`),...(e.execStartPre??[]).map((r)=>`ExecStartPre=${r}`),`ExecStart=${e.execStart}`,"Restart=always","RestartSec=5","LimitNOFILE=65535","","[Install]","WantedBy=multi-user.target"),t.join(`
6
- `)}function ie(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_VITESS_UNIT_EOF'`,t,"TS_CLOUD_VITESS_UNIT_EOF"]}function De(e){let t=e.cell??"zone1",r=e.vtgatePort??z,o=`${((e.keyspaces?.length)?e.keyspaces:[{name:"app"}]).map((n)=>{let a=(n.sharded?["-80","80-"]:["0"]).map((p)=>`shards:{name:"${p}"}`).join(" ");return`keyspaces:{name:"${n.name}" ${a}}`}).join(" ")} cells:"${t}"`;return L({description:"Vitess (vtcombo, single-process development stack)",execStart:D("vtcombo",[`${T}/vtcombo`,`--cell ${t}`,`--proto-topo ${_(o)}`,`--mysql-server-port ${r}`,"--mysql-server-bind-address 127.0.0.1","--mysql-auth-server-impl none","--start-mysql",`--port ${j}`,`--grpc-port ${w}`])})}function Le(){return L({description:"etcd (Vitess topology store)",execStart:D("etcd",[`${T}/etcd`,`--data-dir ${y}/etcd`,`--listen-client-urls http://127.0.0.1:${B}`,`--advertise-client-urls http://127.0.0.1:${B}`]),execStartPre:[`+/bin/mkdir -p ${y}/etcd`,`+/bin/chown ${f}:${f} ${y}/etcd`]})}function Z(e){return["--topo-implementation etcd2",`--topo-global-server-address ${e.etcdEndpoint??`http://127.0.0.1:${B}`}`,"--topo-global-root /vitess/global"]}function Ae(e){let t=!e.etcdEndpoint;return L({description:"Vitess vtctld (control plane)",after:t?["vitess-etcd.service"]:[],requires:t?["vitess-etcd.service"]:[],execStart:D("vtctld",[`${T}/vtctld`,...Z(e),`--cell ${e.cell??"zone1"}`,"--service-map grpc-vtctl,grpc-vtctld",`--grpc-port ${w}`,`--port ${w+1}`])})}function Oe(e,t,r){let s=e.cell??"zone1";return L({description:`Vitess vttablet (${t}/${r})`,after:["vitess-vtctld.service","vitess-mysqlctld.service"],requires:["vitess-mysqlctld.service"],execStart:D("vttablet",[`${T}/vttablet`,...Z(e),`--tablet-path ${s}-${String(J).padStart(10,"0")}`,`--init-keyspace ${t}`,`--init-shard ${r}`,"--init-tablet-type replica",`--service-map ${_("grpc-queryservice,grpc-tabletmanager,grpc-updatestream")}`,`--port ${ne}`,`--grpc-port ${ne+1}`,`--db-port ${e.mysqlPort??3306}`,`--mycnf-mysql-port ${e.mysqlPort??3306}`])})}function Ue(e){return L({description:"Vitess mysqlctld (managed mysqld)",execStart:D("mysqlctld",[`${T}/mysqlctld`,`--tablet-uid ${J}`,`--mysql-port ${e.mysqlPort??3306}`,'--init-db-sql-file "$VTROOT/config/init_db.sql"',"--wait-time 2m"]),execStartPre:[`+/bin/mkdir -p ${y}`,`+/bin/chown ${f}:${f} ${y}`]})}var le="/etc/vitess/auth.json",k="/var/lib/vitess/vtgate-auth.sha256";function xe(e){let t=e.username??"vitess",r=e.password??"";return["mkdir -p /etc/vitess",'VTESS_AUTH_TMP="$(mktemp)"',`cat > "$VTESS_AUTH_TMP" <<'TS_CLOUD_VITESS_AUTH_EOF'`,JSON.stringify({[t]:[{Password:r,UserData:t}]}),"TS_CLOUD_VITESS_AUTH_EOF",`VTESS_VTGATE_AUTH_SHA="$(sha256sum "$VTESS_AUTH_TMP" | awk '{print $1}')"`,"VTESS_VTGATE_AUTH_CHANGED=1",`if [ -f ${k} ] && [ "$(cat ${k})" = "$VTESS_VTGATE_AUTH_SHA" ]; then VTESS_VTGATE_AUTH_CHANGED=0; fi`,`install -o ${f} -g ${f} -m 0600 "$VTESS_AUTH_TMP" ${le}`,'rm -f "$VTESS_AUTH_TMP"']}function ke(e){let t=e.cell??"zone1";return L({description:"Vitess vtgate (query router)",after:["vitess-vtctld.service"],execStart:D("vtgate",[`${T}/vtgate`,...Z(e),`--cell ${t}`,`--cells-to-watch ${t}`,"--tablet-types-to-wait PRIMARY,REPLICA",`--service-map ${_("grpc-vtgateservice")}`,`--mysql-server-port ${e.vtgatePort??z}`,`--mysql-server-bind-address ${e.bindAddress??"127.0.0.1"}`,"--mysql-auth-server-impl static",`--mysql-auth-server-static-file ${le}`,`--port ${j}`,`--grpc-port ${j+1}`])})}function Ie(e){let t=e.cell??"zone1",r=e.etcdEndpoint??`http://127.0.0.1:${B}`,s=`${T}/vtctldclient --server 127.0.0.1:${w}`,o=[`for i in $(seq 1 30); do ${s} GetCellInfoNames >/dev/null 2>&1 && break; sleep 2; done`,`if ! ${s} GetCellInfoNames 2>/dev/null | grep -qx ${_(t)}; then`,` ${s} AddCellInfo --root ${_(`/vitess/${t}`)} --server-address ${_(r)} ${_(t)}`,"fi"];for(let n of e.keyspaces??[]){let a=n.sharded?" --sharded":"";o.push(`if ! ${s} GetKeyspace ${_(n.name)} >/dev/null 2>&1; then`,` ${s} CreateKeyspace${a} ${_(n.name)}`,"fi");let p=`${t}-${String(J).padStart(10,"0")}`;for(let c of n.sharded?["-80","80-"]:["0"]){let i=`${n.name}/${c}`;o.push("for i in $(seq 1 90); do",` if ${s} GetShard ${_(i)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then break; fi`,` ${s} PlannedReparentShard ${_(i)} --new-primary ${_(p)} >/dev/null 2>&1 && break`,` ${s} InitShardPrimary --force ${_(i)} ${_(p)} >/dev/null 2>&1 && break`," sleep 2","done",`if ! ${s} GetShard ${_(i)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then`,` echo "no primary could be elected for ${i}" >&2; exit 1`,"fi")}o.push(`${s} RebuildKeyspaceGraph ${_(n.name)} >/dev/null`)}return o}function ae(e){let t=e.vtgatePort??z;return["for i in $(seq 1 60); do",` if (cd ${R} && eval "$(pantry env 2>/dev/null)"; MYSQL_PWD=${_(e.password??"")} ${T}/mysql -h 127.0.0.1 -P ${t} -u ${_(e.username??"vitess")} --connect-timeout=2 -e 'SHOW KEYSPACES') >/dev/null 2>&1; then`,` echo "vtgate is serving on ${t}"; exit 0`," fi"," sleep 2","done",`echo "vtgate did not become ready on port ${t}" >&2`,"exit 1"]}function ko(e){if(!Ni(e))return[];let t=Ce(e),r=t.mode==="combo";Q.clear();let s=['if [ "$(uname -m)" != "x86_64" ]; then',' echo "vitess: Vitess publishes only x86_64 release tarballs; this box is $(uname -m). Drop managedServices.vitess or use an x86_64 host." >&2'," exit 1","fi",...it(Pe(t)),`VT_MYSQL_LIB="$(dirname "$(dirname "$(readlink -f ${T}/mysqld)")")/lib"`,'if [ -d "$VT_MYSQL_LIB" ]; then',` printf '%s\\n' "$VT_MYSQL_LIB" > /etc/ld.so.conf.d/vitess-mysql.conf`," ldconfig","else",' echo "mysqld library directory not found under $VT_MYSQL_LIB" >&2; exit 1',"fi",`id -u ${f} >/dev/null 2>&1 || useradd --system --home-dir ${y} --shell /usr/sbin/nologin ${f}`,`mkdir -p ${y}`,`chown -R ${f}:${f} ${y}`];if(r)return s.push(...ie("vitess-vtcombo",De(t)),...oe(),"systemctl daemon-reload","systemctl enable --now vitess-vtcombo.service",...ae(t)),s;s.push(...xe(t));let o=[];if(!t.etcdEndpoint)o.push(["vitess-etcd",Le()]);o.push(["vitess-vtctld",Ae(t)],["vitess-mysqlctld",Ue(t)],["vitess-vtgate",ke(t)]);for(let n of t.keyspaces??[])for(let a of n.sharded?["-80","80-"]:["0"])o.push([`vitess-vttablet-${n.name}-${a.replace(/-/g,"x")}`,Oe(t,n.name,a)]);for(let[n,a]of o)s.push(...ie(n,a));s.push(...oe()),s.push("systemctl daemon-reload");for(let[n]of o)s.push(`systemctl enable --now ${n}.service`);return s.push(`if [ "$VTESS_VTGATE_AUTH_CHANGED" = 1 ]; then systemctl restart vitess-vtgate.service; printf '%s\\n' "$VTESS_VTGATE_AUTH_SHA" > ${k}; chown ${f}:${f} ${k}; chmod 0600 ${k}; fi`,...Ie(t),...ae(t)),s}var Me=new Set(["singlestore","vitess"]);function gn(e){if(e?.engine&&Me.has(e.engine))return!1;return!e?.host||e.host==="127.0.0.1"||e.host==="localhost"}function Et(e,t="psql"){let r=e?.port??5432;if(gn(e))return`${t} -p ${r} -U postgres`;let s=e?.username||"postgres";return`${e?.password?`PGPASSWORD='${e.password.replace(/'/g,"'\\''")}' `:""}${t} -h ${e.host} -p ${r} -U ${s} -w`}function E(e){return e===!0||typeof e==="object"&&e!=null}function Ne(e){let t=[],r=[];if(E(e.mysql))t.push(typeof e.mysql==="object"&&e.mysql.version?`mysql.com@${e.mysql.version}`:"mysql.com@8.0.43"),r.push("mysql");else if(E(e.mariadb))t.push(x.mariadb),r.push("mariadb");if(E(e.postgres))t.push("postgresql.org"),r.push("postgres");if(E(e.redis))t.push("redis.io"),r.push("redis");if(E(e.memcached))t.push("memcached.org"),r.push("memcached");if(E(e.meilisearch))t.push("meilisearch.com"),r.push("meilisearch");return{packages:t,services:r}}function No(e={},t={}){let r=Ne(e),s=ko(e.vitess),o=t.mail?Do(t.mail):[];if(r.packages.length===0)return[...s,...o];return[...it(r.packages),...Po(r.services),...s,...o]}function wt(e,t={}){if(e?.requireLocalPasswordAuth&&(e.engine!=="postgres"||!gn(e)||!e.name||!e.username||!e.password||e.users?.some((l)=>!l.password)))throw Error("Password authentication requires a named local PostgreSQL database and nonempty login passwords");if(!e?.name)return[];if(!gn(e))return[];let r=e.name,s=e.username||r,o=e.password||"",n=E(t.postgres)||e.engine==="postgres",a=E(t.mariadb)||e.engine==="mariadb",p=E(t.mysql)||e.engine==="mysql";if(n&&!p&&!a){let l=(d)=>`"${d.replace(/"/g,'""')}"`,b=(d)=>`'${d.replace(/'/g,"''")}'`,O=(d,N)=>[...e.requireLocalPasswordAuth?["SET password_encryption = 'scram-sha-256';"]:[],"DO $$ BEGIN",` IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${b(d)}) THEN`,` CREATE ROLE ${l(d)} LOGIN PASSWORD ${b(N)};`," ELSE",` ALTER ROLE ${l(d)} LOGIN PASSWORD ${b(N)};`," END IF;","END $$;"],I=(d)=>{let N=d.databases&&d.databases.length>0?d.databases:[r],G=[];for(let q of N)if(d.access==="readonly")G.push(`GRANT CONNECT ON DATABASE ${l(q)} TO ${l(d.username)};`,`\\connect ${l(q)}`,`GRANT USAGE ON SCHEMA public TO ${l(d.username)};`,`GRANT SELECT ON ALL TABLES IN SCHEMA public TO ${l(d.username)};`,`ALTER DEFAULT PRIVILEGES FOR ROLE ${l(s)} IN SCHEMA public GRANT SELECT ON TABLES TO ${l(d.username)};`,"\\connect postgres");else G.push(`GRANT ALL PRIVILEGES ON DATABASE ${l(q)} TO ${l(d.username)};`);return G},M=e.users||[],Se=e.port??5432;return[Ve(),`for i in $(seq 1 30); do pg_isready -p ${Se} -q && break; sleep 2; done`,`${Et(e)}${e.requireLocalPasswordAuth?" -v ON_ERROR_STOP=1":""} <<'TS_CLOUD_PG_EOF'`,...O(s,o),`SELECT 'CREATE DATABASE ${l(r)} OWNER ${l(s)}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = ${b(r)})\\gexec`,...M.flatMap((d)=>[...O(d.username,d.password),...I(d)]),"TS_CLOUD_PG_EOF",...e.requireLocalPasswordAuth?[`TS_CLOUD_PG_HBA=$(${Et(e)} -Atc 'SHOW hba_file')`,'case "$TS_CLOUD_PG_HBA" in /*) ;; *) echo "Invalid PostgreSQL authentication path" >&2; exit 1 ;; esac','[ -f "$TS_CLOUD_PG_HBA.before-ts-cloud-password-auth" ] || cp -p "$TS_CLOUD_PG_HBA" "$TS_CLOUD_PG_HBA.before-ts-cloud-password-auth"','TS_CLOUD_PG_AUTH=$(mktemp "$TS_CLOUD_PG_HBA.ts-cloud.XXXXXXXX")',"{"," printf '%s\\n' '# BEGIN ts-cloud password authentication' 'host all all 127.0.0.1/32 scram-sha-256' 'host all all ::1/128 scram-sha-256' 'host replication all 127.0.0.1/32 scram-sha-256' 'host replication all ::1/128 scram-sha-256' '# END ts-cloud password authentication'",` sed '/^# BEGIN ts-cloud password authentication$/,/^# END ts-cloud password authentication$/d' "$TS_CLOUD_PG_HBA"`,'} > "$TS_CLOUD_PG_AUTH"','chown --reference="$TS_CLOUD_PG_HBA" "$TS_CLOUD_PG_AUTH"','chmod --reference="$TS_CLOUD_PG_HBA" "$TS_CLOUD_PG_AUTH"','mv -f "$TS_CLOUD_PG_AUTH" "$TS_CLOUD_PG_HBA"',`${Et(e)} -v ON_ERROR_STOP=1 -c 'SELECT pg_reload_conf()'`]:[],...we(e)]}let c=a?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock",i=(l)=>l.replace(/`/g,"``"),m=(l)=>l.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),C=(l)=>{let b=l.databases&&l.databases.length>0?l.databases:[r],O=l.access==="readonly"?"SELECT":"ALL PRIVILEGES",I=[`CREATE USER IF NOT EXISTS '${m(l.username)}'@'%' IDENTIFIED BY '${m(l.password)}';`,`CREATE USER IF NOT EXISTS '${m(l.username)}'@'localhost' IDENTIFIED BY '${m(l.password)}';`,`ALTER USER '${m(l.username)}'@'%' IDENTIFIED BY '${m(l.password)}';`,`ALTER USER '${m(l.username)}'@'localhost' IDENTIFIED BY '${m(l.password)}';`];for(let M of b)I.push(`GRANT ${O} ON \`${i(M)}\`.* TO '${m(l.username)}'@'%';`,`GRANT ${O} ON \`${i(M)}\`.* TO '${m(l.username)}'@'localhost';`);return I},u=e.users||[];return[Ve(),`for i in $(seq 1 30); do mysqladmin --socket=${c} -u root ping 2>/dev/null | grep -q alive && break; sleep 2; done`,`mysql --socket=${c} -u root <<'TS_CLOUD_SQL_EOF'`,`CREATE DATABASE IF NOT EXISTS \`${i(r)}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`,...C({username:s,password:o}),...u.flatMap(C),"FLUSH PRIVILEGES;","TS_CLOUD_SQL_EOF"]}function we(e){return[`${Et(e)} -tA <<'TS_CLOUD_PG_CAP_EOF' || true`,"\\set QUIET on","SELECT CASE WHEN used::float / NULLIF(cap, 0) >= 0.8"," THEN '[ts-cloud] postgres is at ' || used || '/' || cap || ' connections on this server.'"," || ' Raise max_connections (ALTER SYSTEM SET max_connections = ...; then restart) or'"," || ' set idle_session_timeout so abandoned pools are reclaimed.'"," ELSE NULL END","FROM (SELECT (SELECT count(*) FROM pg_stat_activity) AS used,"," (SELECT setting::int FROM pg_settings WHERE name = 'max_connections') AS cap) c","WHERE CASE WHEN used::float / NULLIF(cap, 0) >= 0.8 THEN true ELSE false END;","SELECT '[ts-cloud] ' || coalesce(datname, '(background)') || ': ' || count(*) || ' connection(s), oldest idle ' ||"," coalesce(round(extract(epoch from max(now() - state_change)) / 60)::text || 'm', 'n/a')","FROM pg_stat_activity","WHERE (SELECT count(*)::float / NULLIF((SELECT setting::int FROM pg_settings WHERE name = 'max_connections'), 0) FROM pg_stat_activity) >= 0.8","GROUP BY datname ORDER BY count(*) DESC;","TS_CLOUD_PG_CAP_EOF"]}function Jc(e){if(!e?.name)return{};let t=e.engine==="singlestore",r=e.engine==="vitess",s=e.engine==="postgres"?"pgsql":t?"singlestore":r?"vitess":"mysql",o=e.port??(e.engine==="postgres"?5432:r?15306:3306),n={DB_CONNECTION:s,DB_HOST:e.host||"127.0.0.1",DB_PORT:String(o),DB_DATABASE:e.name};if(e.username)n.DB_USERNAME=e.username;if(e.password)n.DB_PASSWORD=e.password;if((t||r)&&e.ssl!==!1)n.DB_SSL="true";return n}var V="/var/backups/ts-cloud",ee="/etc/ts-cloud/backups.config.ts",pe="/etc/cron.d/ts-cloud-backups",fn="/usr/local/bin/ts-cloud-backup.sh";function Be(e){if(!e.name)return null;if(!["postgres","mysql","mariadb"].includes(e.engine||""))throw Error("Unsupported scheduled SQL backup engine");return JSON.stringify({type:e.engine==="postgres"?"postgresql":"mysql",name:e.name,connection:{hostname:e.host||"127.0.0.1",port:e.port??(e.engine==="postgres"?5432:3306),database:e.name,username:e.username||e.name,password:e.password||"",ssl:!1},includeSchema:!0,includeData:!0})}function He(e,t){let r=e?Be(e):null,s=t.bucket?{type:"s3",bucket:t.bucket,prefix:t.prefix||"db-backups",...t.endpoint?{endpoint:t.endpoint}:{},...t.region?{region:t.region}:{},keepDays:t.retentionDays??30,optional:!1,...t.encryptionKey?{encryption:{keyEnv:"TS_CLOUD_BACKUP_ENCRYPTION_KEY"}}:{}}:void 0,o={verbose:!0,outputPath:V,retention:{count:t.retentionCount??5,maxAge:t.retentionDays??30},databases:[],files:t.files||[],destinations:s?[s]:[]};return["import type { BackupConfig } from 'ts-backups'",`const config: BackupConfig = ${JSON.stringify(o,null,2)}`,`config.databases = [
6
+ `)}function ie(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_VITESS_UNIT_EOF'`,t,"TS_CLOUD_VITESS_UNIT_EOF"]}function De(e){let t=e.cell??"zone1",r=e.vtgatePort??z,o=`${((e.keyspaces?.length)?e.keyspaces:[{name:"app"}]).map((n)=>{let a=(n.sharded?["-80","80-"]:["0"]).map((p)=>`shards:{name:"${p}"}`).join(" ");return`keyspaces:{name:"${n.name}" ${a}}`}).join(" ")} cells:"${t}"`;return L({description:"Vitess (vtcombo, single-process development stack)",execStart:D("vtcombo",[`${T}/vtcombo`,`--cell ${t}`,`--proto-topo ${_(o)}`,`--mysql-server-port ${r}`,"--mysql-server-bind-address 127.0.0.1","--mysql-auth-server-impl none","--start-mysql",`--port ${j}`,`--grpc-port ${w}`])})}function Le(){return L({description:"etcd (Vitess topology store)",execStart:D("etcd",[`${T}/etcd`,`--data-dir ${y}/etcd`,`--listen-client-urls http://127.0.0.1:${B}`,`--advertise-client-urls http://127.0.0.1:${B}`]),execStartPre:[`+/bin/mkdir -p ${y}/etcd`,`+/bin/chown ${f}:${f} ${y}/etcd`]})}function Z(e){return["--topo-implementation etcd2",`--topo-global-server-address ${e.etcdEndpoint??`http://127.0.0.1:${B}`}`,"--topo-global-root /vitess/global"]}function Ae(e){let t=!e.etcdEndpoint;return L({description:"Vitess vtctld (control plane)",after:t?["vitess-etcd.service"]:[],requires:t?["vitess-etcd.service"]:[],execStart:D("vtctld",[`${T}/vtctld`,...Z(e),`--cell ${e.cell??"zone1"}`,"--service-map grpc-vtctl,grpc-vtctld",`--grpc-port ${w}`,`--port ${w+1}`])})}function Oe(e,t,r){let s=e.cell??"zone1";return L({description:`Vitess vttablet (${t}/${r})`,after:["vitess-vtctld.service","vitess-mysqlctld.service"],requires:["vitess-mysqlctld.service"],execStart:D("vttablet",[`${T}/vttablet`,...Z(e),`--tablet-path ${s}-${String(J).padStart(10,"0")}`,`--init-keyspace ${t}`,`--init-shard ${r}`,"--init-tablet-type replica",`--service-map ${_("grpc-queryservice,grpc-tabletmanager,grpc-updatestream")}`,`--port ${ne}`,`--grpc-port ${ne+1}`,`--db-port ${e.mysqlPort??3306}`,`--mycnf-mysql-port ${e.mysqlPort??3306}`])})}function Ue(e){return L({description:"Vitess mysqlctld (managed mysqld)",execStart:D("mysqlctld",[`${T}/mysqlctld`,`--tablet-uid ${J}`,`--mysql-port ${e.mysqlPort??3306}`,'--init-db-sql-file "$VTROOT/config/init_db.sql"',"--wait-time 2m"]),execStartPre:[`+/bin/mkdir -p ${y}`,`+/bin/chown ${f}:${f} ${y}`]})}var le="/etc/vitess/auth.json",k="/var/lib/vitess/vtgate-auth.sha256";function xe(e){let t=e.username??"vitess",r=e.password??"";return["mkdir -p /etc/vitess",'VTESS_AUTH_TMP="$(mktemp)"',`cat > "$VTESS_AUTH_TMP" <<'TS_CLOUD_VITESS_AUTH_EOF'`,JSON.stringify({[t]:[{Password:r,UserData:t}]}),"TS_CLOUD_VITESS_AUTH_EOF",`VTESS_VTGATE_AUTH_SHA="$(sha256sum "$VTESS_AUTH_TMP" | awk '{print $1}')"`,"VTESS_VTGATE_AUTH_CHANGED=1",`if [ -f ${k} ] && [ "$(cat ${k})" = "$VTESS_VTGATE_AUTH_SHA" ]; then VTESS_VTGATE_AUTH_CHANGED=0; fi`,`install -o ${f} -g ${f} -m 0600 "$VTESS_AUTH_TMP" ${le}`,'rm -f "$VTESS_AUTH_TMP"']}function ke(e){let t=e.cell??"zone1";return L({description:"Vitess vtgate (query router)",after:["vitess-vtctld.service"],execStart:D("vtgate",[`${T}/vtgate`,...Z(e),`--cell ${t}`,`--cells-to-watch ${t}`,"--tablet-types-to-wait PRIMARY,REPLICA",`--service-map ${_("grpc-vtgateservice")}`,`--mysql-server-port ${e.vtgatePort??z}`,`--mysql-server-bind-address ${e.bindAddress??"127.0.0.1"}`,"--mysql-auth-server-impl static",`--mysql-auth-server-static-file ${le}`,`--port ${j}`,`--grpc-port ${j+1}`])})}function Ie(e){let t=e.cell??"zone1",r=e.etcdEndpoint??`http://127.0.0.1:${B}`,s=`${T}/vtctldclient --server 127.0.0.1:${w}`,o=[`for i in $(seq 1 30); do ${s} GetCellInfoNames >/dev/null 2>&1 && break; sleep 2; done`,`if ! ${s} GetCellInfoNames 2>/dev/null | grep -qx ${_(t)}; then`,` ${s} AddCellInfo --root ${_(`/vitess/${t}`)} --server-address ${_(r)} ${_(t)}`,"fi"];for(let n of e.keyspaces??[]){let a=n.sharded?" --sharded":"";o.push(`if ! ${s} GetKeyspace ${_(n.name)} >/dev/null 2>&1; then`,` ${s} CreateKeyspace${a} ${_(n.name)}`,"fi");let p=`${t}-${String(J).padStart(10,"0")}`;for(let c of n.sharded?["-80","80-"]:["0"]){let i=`${n.name}/${c}`;o.push("for i in $(seq 1 90); do",` if ${s} GetShard ${_(i)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then break; fi`,` ${s} PlannedReparentShard ${_(i)} --new-primary ${_(p)} >/dev/null 2>&1 && break`,` ${s} InitShardPrimary --force ${_(i)} ${_(p)} >/dev/null 2>&1 && break`," sleep 2","done",`if ! ${s} GetShard ${_(i)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then`,` echo "no primary could be elected for ${i}" >&2; exit 1`,"fi")}o.push(`${s} RebuildKeyspaceGraph ${_(n.name)} >/dev/null`)}return o}function ae(e){let t=e.vtgatePort??z;return["for i in $(seq 1 60); do",` if (cd ${R} && eval "$(pantry env 2>/dev/null)"; MYSQL_PWD=${_(e.password??"")} ${T}/mysql -h 127.0.0.1 -P ${t} -u ${_(e.username??"vitess")} --connect-timeout=2 -e 'SHOW KEYSPACES') >/dev/null 2>&1; then`,` echo "vtgate is serving on ${t}"; exit 0`," fi"," sleep 2","done",`echo "vtgate did not become ready on port ${t}" >&2`,"exit 1"]}function $o(e){if(!_i(e))return[];let t=Ce(e),r=t.mode==="combo";Q.clear();let s=['if [ "$(uname -m)" != "x86_64" ]; then',' echo "vitess: Vitess publishes only x86_64 release tarballs; this box is $(uname -m). Drop managedServices.vitess or use an x86_64 host." >&2'," exit 1","fi",...st(Pe(t)),`VT_MYSQL_LIB="$(dirname "$(dirname "$(readlink -f ${T}/mysqld)")")/lib"`,'if [ -d "$VT_MYSQL_LIB" ]; then',` printf '%s\\n' "$VT_MYSQL_LIB" > /etc/ld.so.conf.d/vitess-mysql.conf`," ldconfig","else",' echo "mysqld library directory not found under $VT_MYSQL_LIB" >&2; exit 1',"fi",`id -u ${f} >/dev/null 2>&1 || useradd --system --home-dir ${y} --shell /usr/sbin/nologin ${f}`,`mkdir -p ${y}`,`chown -R ${f}:${f} ${y}`];if(r)return s.push(...ie("vitess-vtcombo",De(t)),...oe(),"systemctl daemon-reload","systemctl enable --now vitess-vtcombo.service",...ae(t)),s;s.push(...xe(t));let o=[];if(!t.etcdEndpoint)o.push(["vitess-etcd",Le()]);o.push(["vitess-vtctld",Ae(t)],["vitess-mysqlctld",Ue(t)],["vitess-vtgate",ke(t)]);for(let n of t.keyspaces??[])for(let a of n.sharded?["-80","80-"]:["0"])o.push([`vitess-vttablet-${n.name}-${a.replace(/-/g,"x")}`,Oe(t,n.name,a)]);for(let[n,a]of o)s.push(...ie(n,a));s.push(...oe()),s.push("systemctl daemon-reload");for(let[n]of o)s.push(`systemctl enable --now ${n}.service`);return s.push(`if [ "$VTESS_VTGATE_AUTH_CHANGED" = 1 ]; then systemctl restart vitess-vtgate.service; printf '%s\\n' "$VTESS_VTGATE_AUTH_SHA" > ${k}; chown ${f}:${f} ${k}; chmod 0600 ${k}; fi`,...Ie(t),...ae(t)),s}var Me=new Set(["singlestore","vitess"]);function fn(e){if(e?.engine&&Me.has(e.engine))return!1;return!e?.host||e.host==="127.0.0.1"||e.host==="localhost"}function At(e,t="psql"){let r=e?.port??5432;if(fn(e))return`${t} -p ${r} -U postgres`;let s=e?.username||"postgres";return`${e?.password?`PGPASSWORD='${e.password.replace(/'/g,"'\\''")}' `:""}${t} -h ${e.host} -p ${r} -U ${s} -w`}function E(e){return e===!0||typeof e==="object"&&e!=null}function Ne(e){let t=[],r=[];if(E(e.mysql))t.push(typeof e.mysql==="object"&&e.mysql.version?`mysql.com@${e.mysql.version}`:"mysql.com@8.0.43"),r.push("mysql");else if(E(e.mariadb))t.push(x.mariadb),r.push("mariadb");if(E(e.postgres))t.push("postgresql.org"),r.push("postgres");if(E(e.redis))t.push("redis.io"),r.push("redis");if(E(e.memcached))t.push("memcached.org"),r.push("memcached");if(E(e.meilisearch))t.push("meilisearch.com"),r.push("meilisearch");return{packages:t,services:r}}function Lo(e={},t={}){let r=Ne(e),s=$o(e.vitess),o=t.mail?Oo(t.mail):[];if(r.packages.length===0)return[...s,...o];return[...st(r.packages),..._o(r.services),...s,...o]}function Rt(e,t={}){if(e?.requireLocalPasswordAuth&&(e.engine!=="postgres"||!fn(e)||!e.name||!e.username||!e.password||e.users?.some((l)=>!l.password)))throw Error("Password authentication requires a named local PostgreSQL database and nonempty login passwords");if(!e?.name)return[];if(!fn(e))return[];let r=e.name,s=e.username||r,o=e.password||"",n=E(t.postgres)||e.engine==="postgres",a=E(t.mariadb)||e.engine==="mariadb",p=E(t.mysql)||e.engine==="mysql";if(n&&!p&&!a){let l=(d)=>`"${d.replace(/"/g,'""')}"`,b=(d)=>`'${d.replace(/'/g,"''")}'`,O=(d,N)=>[...e.requireLocalPasswordAuth?["SET password_encryption = 'scram-sha-256';"]:[],"DO $$ BEGIN",` IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${b(d)}) THEN`,` CREATE ROLE ${l(d)} LOGIN PASSWORD ${b(N)};`," ELSE",` ALTER ROLE ${l(d)} LOGIN PASSWORD ${b(N)};`," END IF;","END $$;"],I=(d)=>{let N=d.databases&&d.databases.length>0?d.databases:[r],G=[];for(let q of N)if(d.access==="readonly")G.push(`GRANT CONNECT ON DATABASE ${l(q)} TO ${l(d.username)};`,`\\connect ${l(q)}`,`GRANT USAGE ON SCHEMA public TO ${l(d.username)};`,`GRANT SELECT ON ALL TABLES IN SCHEMA public TO ${l(d.username)};`,`ALTER DEFAULT PRIVILEGES FOR ROLE ${l(s)} IN SCHEMA public GRANT SELECT ON TABLES TO ${l(d.username)};`,"\\connect postgres");else G.push(`GRANT ALL PRIVILEGES ON DATABASE ${l(q)} TO ${l(d.username)};`);return G},M=e.users||[],Se=e.port??5432;return[ze(),`for i in $(seq 1 30); do pg_isready -p ${Se} -q && break; sleep 2; done`,`${At(e)}${e.requireLocalPasswordAuth?" -v ON_ERROR_STOP=1":""} <<'TS_CLOUD_PG_EOF'`,...O(s,o),`SELECT 'CREATE DATABASE ${l(r)} OWNER ${l(s)}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = ${b(r)})\\gexec`,...M.flatMap((d)=>[...O(d.username,d.password),...I(d)]),"TS_CLOUD_PG_EOF",...e.requireLocalPasswordAuth?[`TS_CLOUD_PG_HBA=$(${At(e)} -Atc 'SHOW hba_file')`,'case "$TS_CLOUD_PG_HBA" in /*) ;; *) echo "Invalid PostgreSQL authentication path" >&2; exit 1 ;; esac','[ -f "$TS_CLOUD_PG_HBA.before-ts-cloud-password-auth" ] || cp -p "$TS_CLOUD_PG_HBA" "$TS_CLOUD_PG_HBA.before-ts-cloud-password-auth"','TS_CLOUD_PG_AUTH=$(mktemp "$TS_CLOUD_PG_HBA.ts-cloud.XXXXXXXX")',"{"," printf '%s\\n' '# BEGIN ts-cloud password authentication' 'host all all 127.0.0.1/32 scram-sha-256' 'host all all ::1/128 scram-sha-256' 'host replication all 127.0.0.1/32 scram-sha-256' 'host replication all ::1/128 scram-sha-256' '# END ts-cloud password authentication'",` sed '/^# BEGIN ts-cloud password authentication$/,/^# END ts-cloud password authentication$/d' "$TS_CLOUD_PG_HBA"`,'} > "$TS_CLOUD_PG_AUTH"','chown --reference="$TS_CLOUD_PG_HBA" "$TS_CLOUD_PG_AUTH"','chmod --reference="$TS_CLOUD_PG_HBA" "$TS_CLOUD_PG_AUTH"','mv -f "$TS_CLOUD_PG_AUTH" "$TS_CLOUD_PG_HBA"',`${At(e)} -v ON_ERROR_STOP=1 -c 'SELECT pg_reload_conf()'`]:[],...we(e)]}let c=a?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock",i=(l)=>l.replace(/`/g,"``"),m=(l)=>l.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),C=(l)=>{let b=l.databases&&l.databases.length>0?l.databases:[r],O=l.access==="readonly"?"SELECT":"ALL PRIVILEGES",I=[`CREATE USER IF NOT EXISTS '${m(l.username)}'@'%' IDENTIFIED BY '${m(l.password)}';`,`CREATE USER IF NOT EXISTS '${m(l.username)}'@'localhost' IDENTIFIED BY '${m(l.password)}';`,`ALTER USER '${m(l.username)}'@'%' IDENTIFIED BY '${m(l.password)}';`,`ALTER USER '${m(l.username)}'@'localhost' IDENTIFIED BY '${m(l.password)}';`];for(let M of b)I.push(`GRANT ${O} ON \`${i(M)}\`.* TO '${m(l.username)}'@'%';`,`GRANT ${O} ON \`${i(M)}\`.* TO '${m(l.username)}'@'localhost';`);return I},u=e.users||[];return[ze(),`for i in $(seq 1 30); do mysqladmin --socket=${c} -u root ping 2>/dev/null | grep -q alive && break; sleep 2; done`,`mysql --socket=${c} -u root <<'TS_CLOUD_SQL_EOF'`,`CREATE DATABASE IF NOT EXISTS \`${i(r)}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`,...C({username:s,password:o}),...u.flatMap(C),"FLUSH PRIVILEGES;","TS_CLOUD_SQL_EOF"]}function we(e){return[`${At(e)} -tA <<'TS_CLOUD_PG_CAP_EOF' || true`,"\\set QUIET on","SELECT CASE WHEN used::float / NULLIF(cap, 0) >= 0.8"," THEN '[ts-cloud] postgres is at ' || used || '/' || cap || ' connections on this server.'"," || ' Raise max_connections (ALTER SYSTEM SET max_connections = ...; then restart) or'"," || ' set idle_session_timeout so abandoned pools are reclaimed.'"," ELSE NULL END","FROM (SELECT (SELECT count(*) FROM pg_stat_activity) AS used,"," (SELECT setting::int FROM pg_settings WHERE name = 'max_connections') AS cap) c","WHERE CASE WHEN used::float / NULLIF(cap, 0) >= 0.8 THEN true ELSE false END;","SELECT '[ts-cloud] ' || coalesce(datname, '(background)') || ': ' || count(*) || ' connection(s), oldest idle ' ||"," coalesce(round(extract(epoch from max(now() - state_change)) / 60)::text || 'm', 'n/a')","FROM pg_stat_activity","WHERE (SELECT count(*)::float / NULLIF((SELECT setting::int FROM pg_settings WHERE name = 'max_connections'), 0) FROM pg_stat_activity) >= 0.8","GROUP BY datname ORDER BY count(*) DESC;","TS_CLOUD_PG_CAP_EOF"]}function nl(e){if(!e?.name)return{};let t=e.engine==="singlestore",r=e.engine==="vitess",s=e.engine==="postgres"?"pgsql":t?"singlestore":r?"vitess":"mysql",o=e.port??(e.engine==="postgres"?5432:r?15306:3306),n={DB_CONNECTION:s,DB_HOST:e.host||"127.0.0.1",DB_PORT:String(o),DB_DATABASE:e.name};if(e.username)n.DB_USERNAME=e.username;if(e.password)n.DB_PASSWORD=e.password;if((t||r)&&e.ssl!==!1)n.DB_SSL="true";return n}var V="/var/backups/ts-cloud",ee="/etc/ts-cloud/backups.config.ts",pe="/etc/cron.d/ts-cloud-backups",hn="/usr/local/bin/ts-cloud-backup.sh";function Be(e){if(!e.name)return null;if(!["postgres","mysql","mariadb"].includes(e.engine||""))throw Error("Unsupported scheduled SQL backup engine");return JSON.stringify({type:e.engine==="postgres"?"postgresql":"mysql",name:e.name,connection:{hostname:e.host||"127.0.0.1",port:e.port??(e.engine==="postgres"?5432:3306),database:e.name,username:e.username||e.name,password:e.password||"",ssl:!1},includeSchema:!0,includeData:!0})}function He(e,t){let r=e?Be(e):null,s=t.bucket?{type:"s3",bucket:t.bucket,prefix:t.prefix||"db-backups",...t.endpoint?{endpoint:t.endpoint}:{},...t.region?{region:t.region}:{},keepDays:t.retentionDays??30,optional:!1,...t.encryptionKey?{encryption:{keyEnv:"TS_CLOUD_BACKUP_ENCRYPTION_KEY"}}:{}}:void 0,o={verbose:!0,outputPath:V,retention:{count:t.retentionCount??5,maxAge:t.retentionDays??30},databases:[],files:t.files||[],destinations:s?[s]:[]};return["import type { BackupConfig } from 'ts-backups'",`const config: BackupConfig = ${JSON.stringify(o,null,2)}`,`config.databases = [
7
7
  ${r||""}
8
8
  ]`,...t.credentials?["config.destinations![0]!.credentials = { accessKeyId: process.env.TS_CLOUD_BACKUP_ACCESS_KEY!, secretAccessKey: process.env.TS_CLOUD_BACKUP_SECRET_KEY! }"]:[],"export default config",""].join(`
9
- `)}function xi(e){let{database:t,backups:r}=e;if(!r.enabled)return[];if(r.credentials&&(!r.bucket||!r.credentials.accessKeyId||!r.credentials.secretAccessKey))throw Error("Scheduled backups require complete destination credentials and a bucket");if(r.encryptionKey&&(r.encryptionKey.length<32||!r.bucket))throw Error("Encrypted offsite backups require a bucket and a separate recovery key of at least 32 characters");let s=r.version||"0.1.6",o=r.archive||(!r.version?{url:"https://github.com/stacksjs/ts-backups/releases/download/v0.1.6/ts-backups-0.1.6.tgz",sha256:"20b8295d8c092f9e0ed17239b0233e781d71466077b555f163d67dfcfa2a9744"}:void 0);if(!/^\d+\.\d+\.\d+$/.test(s))throw Error("Pin a released ts-backups version");let n=r.schedule||"0 2 * * *";if(!/^[0-9*,/ -]+$/.test(n)||n.trim().split(/\s+/).length!==5)throw Error("Invalid backup schedule");let a=(i)=>`'${i.replace(/'/g,"'\\''")}'`;if(o){let i=new URL(o.url);if(i.protocol!=="https:"||i.username||i.password||!/^[a-f0-9]{64}$/i.test(o.sha256))throw Error("Backup archives require an HTTPS URL and SHA-256 checksum")}let p=Object.entries({...r.credentials?{TS_CLOUD_BACKUP_ACCESS_KEY:r.credentials.accessKeyId,TS_CLOUD_BACKUP_SECRET_KEY:r.credentials.secretAccessKey}:{},...r.encryptionKey?{TS_CLOUD_BACKUP_ENCRYPTION_KEY:r.encryptionKey}:{}}).map(([i,m])=>`${i}=${a(m)}`).join(`
10
- `),c="/opt/ts-cloud/backups";return["(","umask 077",`mkdir -p /etc/ts-cloud ${V} ${c}`,`chmod 700 ${V} ${c}`,'export PATH="/opt/ts-cloud/bun/bin:/opt/pantry/pantry/.bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"',`test -f ${c}/package.json || printf '%s' '{"private":true}' > ${c}/package.json`,...o?[`curl --fail --silent --show-error --location ${a(o.url)} --output ${c}/release.tgz`,`printf '%s\\n' ${a(`${o.sha256.toLowerCase()} ${c}/release.tgz`)} | sha256sum --check --status`,`bun add --cwd ${c} --no-save ${c}/release.tgz`,`test "$(cd ${c} && bun -e 'console.log((await Bun.file("node_modules/ts-backups/package.json").json()).version)')" = ${a(s)}`]:[`bun add --cwd ${c} --no-save ts-backups@${s}`],`printf '%s' ${a(He(t,r))} > ${ee}`,`printf '%s\\n' ${a(p)} > /etc/ts-cloud/backups.env`,`chmod 600 ${ee} /etc/ts-cloud/backups.env`,`cat > ${fn} <<'TS_CLOUD_BACKUP_RUN_EOF'`,"#!/bin/bash","set -euo pipefail","umask 077","exec 9>/run/lock/ts-cloud-backups.lock","flock -n 9 || exit 0",'export PATH="/opt/ts-cloud/bun/bin:/opt/pantry/pantry/.bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"','eval "$(cd /opt/pantry && pantry env)"',"set -a",". /etc/ts-cloud/backups.env","set +a",'notify() { [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "$1" || true; }',"cd /etc/ts-cloud",`if ! ${c}/node_modules/.bin/ts-backups start --config ${ee}; then notify "ts-cloud backup failed"; exit 1; fi`,"date -u +%FT%TZ > /var/backups/ts-cloud/last-success","TS_CLOUD_BACKUP_RUN_EOF",`chmod 700 ${fn}`,`printf '%s\\n' ${a(`${n} root ${fn} >> /var/log/ts-cloud-backup.log 2>&1`)} > ${pe}`,`chmod 644 ${pe}`,")"]}function Ge(e){return e==="mariadb"?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock"}function _i(e,t={}){if(!e?.name)return[];let r=e.name,s=e.engine==="postgres",o=t.from?`TS_CLOUD_DUMP="${t.from}"`:`TS_CLOUD_DUMP="$(find ${V} -type f -name '*${r}*.sql' -o -type f -name '*${r}*.sql.gz' 2>/dev/null | xargs -r ls -1t 2>/dev/null | head -1)"`,n=s?`${Et(e)} -d "${r}"`:`mysql --socket=${Ge(e.engine)} -u root "${r}"`;return["set -uo pipefail",'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true',o,'[ -n "$TS_CLOUD_DUMP" ] && [ -f "$TS_CLOUD_DUMP" ] || { echo "no backup dump found to restore" >&2; exit 1; }','echo "[ts-cloud] restoring '+r+' from $TS_CLOUD_DUMP"',`case "$TS_CLOUD_DUMP" in *.gz) gunzip -c "$TS_CLOUD_DUMP" ;; *) cat "$TS_CLOUD_DUMP" ;; esac | ${n}`,'echo "restore complete"']}var xo=["storage",".env"],Oi=4;function v(e){return`${e.replace(/\/+$/,"")}/.ts-cloud`}function Vs(e){return`${v(e)}/deploy-history.log`}function qe(e,t){return`${v(e)}/deploys/${t}.log`}function ue(e){return`${v(e)}/shared-paths`}function _o(e){return`${e.shared}/stx-images`}function $i(e){return`${e.shared}/stx-bundles`}function Ht(e,t){let r=e.replace(/\/+$/,"");return{base:r,releases:`${r}/releases`,shared:`${r}/shared`,current:`${r}/current`,release:`${r}/releases/${t}`}}function de(e){let t=e.split("/").pop()||e;if(t===".env"||t.startsWith(".env."))return!0;return/\.[a-z0-9]+$/i.test(t)}function zs(e){return typeof e==="string"?e:e.path}function Xc(e){let t=new Map;for(let r of e)t.set(zs(r),r);return[...t.values()]}function $e(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 Fe(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 Li(e,t=xo){let r=[`mkdir -p ${e.releases} ${e.shared} ${_o(e)} ${$i(e)}`,...Fe(e)],s=t.map((n)=>$e(e,n));for(let{path:n,target:a,seed:p}of s){if(!p)continue;if(r.push(`ts_cloud_adopt_shared '${n}' '${a}'`),de(n))r.push(`mkdir -p "$(dirname ${a})"`,`touch ${a}`);else if(n==="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 o=ue(e.base);return r.push(`mkdir -p ${v(e.base)}`,`cat > ${o} <<'TS_CLOUD_SHARED_PATHS_EOF'`,...s.map((n)=>`${n.path} ${n.target}`),"TS_CLOUD_SHARED_PATHS_EOF"),r}function Hs(e,t=900){let r=`${v(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 Gs(e){let t=`${e.release}.incoming`;return[`rm -rf ${t}`,`mkdir -p ${t}`,...Ye(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 qs(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 Ye(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 Ws(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 Ke(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 Oo(e,t=xo){let r=[];for(let s of t){let{path:o,target:n,seed:a}=$e(e,s),p=`${e.release}/${o}`,c=[`rm -rf ${p}`,`mkdir -p "$(dirname ${p})"`,`ln -sfn ${n} ${p}`];if(a){if(o!==".env"&&de(o))r.push(...Ke(p,n));r.push(...c);continue}r.push(`if [ -e ${n} ]; then`,...c.map((i)=>` ${i}`),"fi")}return r}function je(e,t){let r=ue(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 hn(e){return[`ln -sfn ${e.release} ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`]}function te(e){return`${v(e)}/previous-release`}function Ks(e,t="TS_CLOUD_PREV_CURRENT"){let r=te(e.base);return[`if [ -n "\${${t}:-}" ] && [ -d "$${t}" ] && [ "$(readlink -f "$${t}")" != "$(readlink -f ${e.release})" ]; then mkdir -p ${v(e.base)}; basename "$${t}" > ${r}; fi`]}function _e(e,t){let r=te(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 Qc(e,t={}){return[..._e(e,t.to),'echo "would roll back from $(basename "${TS_CLOUD_CURRENT:-none}") to $TS_CLOUD_RB_ID (dry run: nothing changed)"']}function Yc(e,t={}){let r=Math.max(1,t.gateSeconds??5),s=t.systemdDir??"/etc/systemd/system",o=[`ln -sfn "$TS_CLOUD_RB_TARGET" ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`,`rm -f ${te(e.base)}`,'echo "rolled back to $TS_CLOUD_RB_ID"'],n=[..._e(e,t.to),...je(e,'"$TS_CLOUD_RB_TARGET"')];if(!t.unitBase)return[...n,...o];let a=t.unitBase,p=`${a}@\${TS_CLOUD_RB_ID}.service`;return[...n,`if [ -f ${s}/${a}@.service ]; then`,` systemctl start "${p}"`,` for TS_CLOUD_I in $(seq 1 ${r}); do sleep 1; systemctl is-active --quiet "${p}" || { echo "the release rolled back to, $TS_CLOUD_RB_ID, did not stay up; the current release keeps serving" >&2; journalctl -u "${p}" -n 30 --no-pager >&2 || true; systemctl stop "${p}" 2>/dev/null || true; exit 1; }; done`,...o.map((c)=>` ${c}`),` systemctl enable "${p}" 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 ${s}/${a}.service ]; then`,...o.map((c)=>` ${c}`),` systemctl restart ${a}.service`,"else",...o.map((c)=>` ${c}`),"fi"]}function yn(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 We(e){return`${v(e)}/owner`}function Js(e,t){let r=We(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 $o(e,t){let r=v(e),s=qe(e,t.releaseId),o=Vs(e),n=Math.max(1,t.keepLogs??20),a=t.commit||"",p=t.branch||"";return[`mkdir -p ${r}/deploys`,`exec > >(tee -a ${s}) 2>&1`,`echo "[ts-cloud] deploy ${t.releaseId} commit=${a} branch=${p} 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" >> ${o}`,"}","trap ts_cloud_record_deploy EXIT",`ls -1t ${r}/deploys/*.log 2>/dev/null | tail -n +${n+1} | while read -r TS_CLOUD_OLDLOG; do rm -f "$TS_CLOUD_OLDLOG"; done`]}
11
- export{W,ki,Bs,A,Io,Fs,js,Wc,Kc,R,Tt,Ve,it,Po,Do,Ni,ko,gn,Et,No,wt,Jc,fn,xi,_i,xo,Oi,Vs,_o,$i,Ht,zs,Xc,Li,Hs,Gs,qs,Ws,Oo,hn,Ks,Qc,Yc,yn,Js,$o};
9
+ `)}function Oi(e){let{database:t,backups:r}=e;if(!r.enabled)return[];if(r.credentials&&(!r.bucket||!r.credentials.accessKeyId||!r.credentials.secretAccessKey))throw Error("Scheduled backups require complete destination credentials and a bucket");if(r.encryptionKey&&(r.encryptionKey.length<32||!r.bucket))throw Error("Encrypted offsite backups require a bucket and a separate recovery key of at least 32 characters");let s=r.version||"0.1.6",o=r.archive||(!r.version?{url:"https://github.com/stacksjs/ts-backups/releases/download/v0.1.6/ts-backups-0.1.6.tgz",sha256:"20b8295d8c092f9e0ed17239b0233e781d71466077b555f163d67dfcfa2a9744"}:void 0);if(!/^\d+\.\d+\.\d+$/.test(s))throw Error("Pin a released ts-backups version");let n=r.schedule||"0 2 * * *";if(!/^[0-9*,/ -]+$/.test(n)||n.trim().split(/\s+/).length!==5)throw Error("Invalid backup schedule");let a=(i)=>`'${i.replace(/'/g,"'\\''")}'`;if(o){let i=new URL(o.url);if(i.protocol!=="https:"||i.username||i.password||!/^[a-f0-9]{64}$/i.test(o.sha256))throw Error("Backup archives require an HTTPS URL and SHA-256 checksum")}let p=Object.entries({...r.credentials?{TS_CLOUD_BACKUP_ACCESS_KEY:r.credentials.accessKeyId,TS_CLOUD_BACKUP_SECRET_KEY:r.credentials.secretAccessKey}:{},...r.encryptionKey?{TS_CLOUD_BACKUP_ENCRYPTION_KEY:r.encryptionKey}:{}}).map(([i,m])=>`${i}=${a(m)}`).join(`
10
+ `),c="/opt/ts-cloud/backups";return["(","umask 077",`mkdir -p /etc/ts-cloud ${V} ${c}`,`chmod 700 ${V} ${c}`,'export PATH="/opt/ts-cloud/bun/bin:/opt/pantry/pantry/.bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"',`test -f ${c}/package.json || printf '%s' '{"private":true}' > ${c}/package.json`,...o?[`curl --fail --silent --show-error --location ${a(o.url)} --output ${c}/release.tgz`,`printf '%s\\n' ${a(`${o.sha256.toLowerCase()} ${c}/release.tgz`)} | sha256sum --check --status`,`bun add --cwd ${c} --no-save ${c}/release.tgz`,`test "$(cd ${c} && bun -e 'console.log((await Bun.file("node_modules/ts-backups/package.json").json()).version)')" = ${a(s)}`]:[`bun add --cwd ${c} --no-save ts-backups@${s}`],`printf '%s' ${a(He(t,r))} > ${ee}`,`printf '%s\\n' ${a(p)} > /etc/ts-cloud/backups.env`,`chmod 600 ${ee} /etc/ts-cloud/backups.env`,`cat > ${hn} <<'TS_CLOUD_BACKUP_RUN_EOF'`,"#!/bin/bash","set -euo pipefail","umask 077","exec 9>/run/lock/ts-cloud-backups.lock","flock -n 9 || exit 0",'export PATH="/opt/ts-cloud/bun/bin:/opt/pantry/pantry/.bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"','eval "$(cd /opt/pantry && pantry env)"',"set -a",". /etc/ts-cloud/backups.env","set +a",'notify() { [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "$1" || true; }',"cd /etc/ts-cloud",`if ! ${c}/node_modules/.bin/ts-backups start --config ${ee}; then notify "ts-cloud backup failed"; exit 1; fi`,"date -u +%FT%TZ > /var/backups/ts-cloud/last-success","TS_CLOUD_BACKUP_RUN_EOF",`chmod 700 ${hn}`,`printf '%s\\n' ${a(`${n} root ${hn} >> /var/log/ts-cloud-backup.log 2>&1`)} > ${pe}`,`chmod 644 ${pe}`,")"]}function Ve(e){return e==="mariadb"?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock"}function $i(e,t={}){if(!e?.name)return[];let r=e.name,s=e.engine==="postgres",o=t.from?`TS_CLOUD_DUMP="${t.from}"`:`TS_CLOUD_DUMP="$(find ${V} -type f -name '*${r}*.sql' -o -type f -name '*${r}*.sql.gz' 2>/dev/null | xargs -r ls -1t 2>/dev/null | head -1)"`,n=s?`${At(e)} -d "${r}"`:`mysql --socket=${Ve(e.engine)} -u root "${r}"`;return["set -uo pipefail",'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true',o,'[ -n "$TS_CLOUD_DUMP" ] && [ -f "$TS_CLOUD_DUMP" ] || { echo "no backup dump found to restore" >&2; exit 1; }','echo "[ts-cloud] restoring '+r+' from $TS_CLOUD_DUMP"',`case "$TS_CLOUD_DUMP" in *.gz) gunzip -c "$TS_CLOUD_DUMP" ;; *) cat "$TS_CLOUD_DUMP" ;; esac | ${n}`,'echo "restore complete"']}var Mo=["storage",".env"],Li=4;function v(e){return`${e.replace(/\/+$/,"")}/.ts-cloud`}function Xs(e){return`${v(e)}/deploy-history.log`}function Ge(e,t){return`${v(e)}/deploys/${t}.log`}function ue(e){return`${v(e)}/shared-paths`}function Uo(e){return`${e.shared}/stx-images`}function Mi(e){return`${e.shared}/stx-bundles`}function qt(e,t){let r=e.replace(/\/+$/,"");return{base:r,releases:`${r}/releases`,shared:`${r}/shared`,current:`${r}/current`,release:`${r}/releases/${t}`}}function de(e){let t=e.split("/").pop()||e;if(t===".env"||t.startsWith(".env."))return!0;return/\.[a-z0-9]+$/i.test(t)}function Qs(e){return typeof e==="string"?e:e.path}function il(e){let t=new Map;for(let r of e)t.set(Qs(r),r);return[...t.values()]}function $e(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 qe(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 Ui(e,t=Mo){let r=[`mkdir -p ${e.releases} ${e.shared} ${Uo(e)} ${Mi(e)}`,...qe(e)],s=t.map((n)=>$e(e,n));for(let{path:n,target:a,seed:p}of s){if(!p)continue;if(r.push(`ts_cloud_adopt_shared '${n}' '${a}'`),de(n))r.push(`mkdir -p "$(dirname ${a})"`,`touch ${a}`);else if(n==="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 o=ue(e.base);return r.push(`mkdir -p ${v(e.base)}`,`cat > ${o} <<'TS_CLOUD_SHARED_PATHS_EOF'`,...s.map((n)=>`${n.path} ${n.target}`),"TS_CLOUD_SHARED_PATHS_EOF"),r}function Ys(e,t=900){let r=`${v(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 Zs(e){let t=`${e.release}.incoming`;return[`rm -rf ${t}`,`mkdir -p ${t}`,...Fe(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 ea(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 Fe(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 ta(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 Ye(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 Bo(e,t=Mo){let r=[];for(let s of t){let{path:o,target:n,seed:a}=$e(e,s),p=`${e.release}/${o}`,c=[`rm -rf ${p}`,`mkdir -p "$(dirname ${p})"`,`ln -sfn ${n} ${p}`];if(a){if(o!==".env"&&de(o))r.push(...Ye(p,n));r.push(...c);continue}r.push(`if [ -e ${n} ]; then`,...c.map((i)=>` ${i}`),"fi")}return r}function Ke(e,t){let r=ue(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 yn(e){return[`ln -sfn ${e.release} ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`]}function te(e){return`${v(e)}/previous-release`}function ra(e,t="TS_CLOUD_PREV_CURRENT"){let r=te(e.base);return[`if [ -n "\${${t}:-}" ] && [ -d "$${t}" ] && [ "$(readlink -f "$${t}")" != "$(readlink -f ${e.release})" ]; then mkdir -p ${v(e.base)}; basename "$${t}" > ${r}; fi`]}function _e(e,t){let r=te(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 ol(e,t={}){return[..._e(e,t.to),'echo "would roll back from $(basename "${TS_CLOUD_CURRENT:-none}") to $TS_CLOUD_RB_ID (dry run: nothing changed)"']}function sl(e,t={}){let r=Math.max(1,t.gateSeconds??5),s=t.systemdDir??"/etc/systemd/system",o=[`ln -sfn "$TS_CLOUD_RB_TARGET" ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`,`rm -f ${te(e.base)}`,'echo "rolled back to $TS_CLOUD_RB_ID"'],n=[..._e(e,t.to),...Ke(e,'"$TS_CLOUD_RB_TARGET"')];if(!t.unitBase)return[...n,...o];let a=t.unitBase,p=`${a}@\${TS_CLOUD_RB_ID}.service`;return[...n,`if [ -f ${s}/${a}@.service ]; then`,` systemctl start "${p}"`,` for TS_CLOUD_I in $(seq 1 ${r}); do sleep 1; systemctl is-active --quiet "${p}" || { echo "the release rolled back to, $TS_CLOUD_RB_ID, did not stay up; the current release keeps serving" >&2; journalctl -u "${p}" -n 30 --no-pager >&2 || true; systemctl stop "${p}" 2>/dev/null || true; exit 1; }; done`,...o.map((c)=>` ${c}`),` systemctl enable "${p}" 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 ${s}/${a}.service ]; then`,...o.map((c)=>` ${c}`),` systemctl restart ${a}.service`,"else",...o.map((c)=>` ${c}`),"fi"]}function bn(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 je(e){return`${v(e)}/owner`}function na(e,t){let r=je(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 Fo(e,t){let r=v(e),s=Ge(e,t.releaseId),o=Xs(e),n=Math.max(1,t.keepLogs??20),a=t.commit||"",p=t.branch||"";return[`mkdir -p ${r}/deploys`,`exec > >(tee -a ${s}) 2>&1`,`echo "[ts-cloud] deploy ${t.releaseId} commit=${a} branch=${p} 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" >> ${o}`,"}","trap ts_cloud_record_deploy EXIT",`ls -1t ${r}/deploys/*.log 2>/dev/null | tail -n +${n+1} | while read -r TS_CLOUD_OLDLOG; do rm -f "$TS_CLOUD_OLDLOG"; done`]}
11
+ export{W,xi,Ws,A,xo,Ks,Js,tl,rl,R,wt,ze,st,_o,Oo,_i,$o,fn,At,Lo,Rt,nl,hn,Oi,$i,Mo,Li,Xs,Uo,Mi,qt,Qs,il,Ui,Ys,Zs,ea,ta,Bo,yn,ra,ol,sl,bn,na,Fo};