@stacksjs/ts-cloud 0.16.22 → 0.16.24

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 (194) hide show
  1. package/dist/aws/client.d.ts +9 -0
  2. package/dist/aws/elasticache.d.ts +11 -9
  3. package/dist/aws/index.js +1 -1
  4. package/dist/bin/chunk-0cwbg3pf.js +1 -0
  5. package/dist/bin/{chunk-636jsmnz.js → chunk-0md2h0an.js} +6 -6
  6. package/dist/bin/chunk-0ytk5g2t.js +1 -0
  7. package/dist/bin/chunk-19tmmwmt.js +1 -0
  8. package/dist/bin/chunk-1fde3e2c.js +1 -0
  9. package/dist/bin/{chunk-5bsknbr7.js → chunk-1j9vy88a.js} +1 -1
  10. package/dist/bin/{chunk-c04dygzg.js → chunk-257sygzm.js} +5 -5
  11. package/dist/bin/{chunk-7xr71hnt.js → chunk-2q27v6vz.js} +2 -2
  12. package/dist/bin/chunk-3b8a3knq.js +1 -0
  13. package/dist/bin/{chunk-k97ms0bs.js → chunk-3jjggqfj.js} +5 -5
  14. package/dist/bin/{chunk-m51vpvr6.js → chunk-4sq6cvz5.js} +3 -3
  15. package/dist/bin/chunk-4y20ry45.js +1 -0
  16. package/dist/bin/{chunk-hmnaen1z.js → chunk-5kc8s9gp.js} +1 -1
  17. package/dist/bin/{chunk-8wnkx3jf.js → chunk-5x59x4qw.js} +2 -2
  18. package/dist/bin/chunk-6aj3h8yk.js +1 -0
  19. package/dist/bin/{chunk-95v6ry1x.js → chunk-6eesa8d1.js} +5 -5
  20. package/dist/bin/{chunk-a0me5fed.js → chunk-6nm91cfw.js} +2 -2
  21. package/dist/bin/{chunk-3425j97b.js → chunk-7412q5cz.js} +2 -2
  22. package/dist/bin/chunk-78w3bn85.js +1 -0
  23. package/dist/bin/{chunk-ardzx4dw.js → chunk-8e7n357e.js} +128 -128
  24. package/dist/bin/{chunk-jp23ed1q.js → chunk-8knkt6sd.js} +1 -1
  25. package/dist/bin/{chunk-2gd8kqzq.js → chunk-9464wvf2.js} +5 -5
  26. package/dist/bin/{chunk-k6apknm8.js → chunk-988qv730.js} +5 -5
  27. package/dist/bin/chunk-9b6af1sj.js +1 -0
  28. package/dist/bin/{chunk-87f5d9qj.js → chunk-9e7pqhj1.js} +1 -1
  29. package/dist/bin/chunk-a07jfqvs.js +1 -0
  30. package/dist/bin/chunk-a3rq51az.js +2 -0
  31. package/dist/bin/chunk-apw5bbjg.js +1 -0
  32. package/dist/bin/{chunk-v980gs11.js → chunk-ax41jhq7.js} +2 -2
  33. package/dist/bin/{chunk-12q8xrct.js → chunk-c35qm7as.js} +5 -5
  34. package/dist/bin/{chunk-330kytpm.js → chunk-d1psxeqj.js} +2 -2
  35. package/dist/bin/{chunk-qqqx70g6.js → chunk-f0fpp4mk.js} +2 -2
  36. package/dist/bin/chunk-fpy7nv5g.js +1 -0
  37. package/dist/bin/chunk-fq4nxfec.js +1 -0
  38. package/dist/bin/chunk-ghe1nawv.js +1 -0
  39. package/dist/bin/{chunk-n8dsby4k.js → chunk-hez48c69.js} +1 -1
  40. package/dist/bin/{chunk-wqydambz.js → chunk-hjv1k8s9.js} +16 -16
  41. package/dist/bin/chunk-hwqvx1zb.js +1 -0
  42. package/dist/bin/{chunk-24njmb7d.js → chunk-jdfbahjb.js} +110 -110
  43. package/dist/bin/chunk-jwdcx0mm.js +1 -0
  44. package/dist/bin/chunk-k9mzq7z9.js +1 -0
  45. package/dist/bin/chunk-kf1p7s61.js +1 -0
  46. package/dist/bin/{chunk-n7hmjzgd.js → chunk-m2gwzksz.js} +1 -1
  47. package/dist/bin/chunk-mh172wt8.js +1 -0
  48. package/dist/bin/{chunk-and7khsv.js → chunk-prj5b597.js} +2 -2
  49. package/dist/bin/chunk-q3xwh0r8.js +6 -0
  50. package/dist/bin/chunk-q8crt80d.js +1 -0
  51. package/dist/bin/chunk-r3hkc2s3.js +1 -0
  52. package/dist/bin/{chunk-7kj8f72p.js → chunk-rpfvv7hw.js} +1 -1
  53. package/dist/bin/{chunk-mz2jbtcs.js → chunk-wfa8j3wg.js} +3 -3
  54. package/dist/bin/{chunk-rm59bcnw.js → chunk-wffaqgcc.js} +62 -62
  55. package/dist/bin/chunk-wg20x65t.js +34 -0
  56. package/dist/{chunk-dv1jkay7.js → bin/chunk-wsedynyb.js} +7 -7
  57. package/dist/bin/chunk-xb82bmgf.js +1 -0
  58. package/dist/bin/{chunk-8agf66wn.js → chunk-xh5jcv64.js} +3 -3
  59. package/dist/bin/{chunk-v5bjbyve.js → chunk-xss6yj73.js} +2 -2
  60. package/dist/bin/chunk-xxgybh3b.js +1 -0
  61. package/dist/bin/{chunk-vskhr9qy.js → chunk-y6rgvb7r.js} +2 -2
  62. package/dist/bin/chunk-z5ycwy38.js +2 -0
  63. package/dist/bin/chunk-zq02x716.js +1 -0
  64. package/dist/bin/cli.js +335 -335
  65. package/dist/bin/dashboard-server.js +1 -1
  66. package/dist/chunk-1ba6keyk.js +1 -0
  67. package/dist/{chunk-3zzm5f28.js → chunk-3x9g48ey.js} +26 -26
  68. package/dist/chunk-4rkjhvgw.js +114 -0
  69. package/dist/{chunk-9s24pbbc.js → chunk-65yh2h1e.js} +1 -1
  70. package/dist/{chunk-x60w04y3.js → chunk-6e5j40n9.js} +2 -2
  71. package/dist/{chunk-5dz6bzdj.js → chunk-97trx8p9.js} +2 -2
  72. package/dist/{chunk-mgg0psgc.js → chunk-9ca1yafd.js} +2 -2
  73. package/dist/{chunk-jt49qs0f.js → chunk-bzbryxfm.js} +2 -2
  74. package/dist/{chunk-pffebjr8.js → chunk-d8w90gsb.js} +36 -36
  75. package/dist/{chunk-w4s3rswa.js → chunk-dm6kyz6e.js} +2 -2
  76. package/dist/chunk-e3axmek0.js +1 -0
  77. package/dist/chunk-e4z4tfh6.js +1 -0
  78. package/dist/{chunk-2dextjqf.js → chunk-e7m70ex1.js} +2 -2
  79. package/dist/{chunk-ezgpamw6.js → chunk-gvybjt7y.js} +1 -1
  80. package/dist/{bin/chunk-09d5qe73.js → chunk-h85wqdvr.js} +7 -7
  81. package/dist/{chunk-3jkc3s8c.js → chunk-hzbyj0xd.js} +19 -19
  82. package/dist/{chunk-9p89msvs.js → chunk-jrrw3ezm.js} +5 -5
  83. package/dist/{chunk-ms4dnha2.js → chunk-mv7hne2c.js} +1 -1
  84. package/dist/chunk-qa6jjv3m.js +1 -0
  85. package/dist/{chunk-pcns0kz4.js → chunk-qfqh21rq.js} +5 -5
  86. package/dist/{chunk-2ap78e1s.js → chunk-qrchr75r.js} +4 -4
  87. package/dist/{chunk-khatwx29.js → chunk-rgq7m90a.js} +99 -99
  88. package/dist/chunk-rnjgde95.js +1 -0
  89. package/dist/{chunk-pwywwdq2.js → chunk-rr1qjxyj.js} +1 -1
  90. package/dist/chunk-t4ynyk8k.js +34 -0
  91. package/dist/{chunk-kpyhx96m.js → chunk-v7y50hhf.js} +110 -110
  92. package/dist/chunk-vtm83crj.js +709 -0
  93. package/dist/chunk-wrpnnrdf.js +6 -0
  94. package/dist/{chunk-np8vgbv0.js → chunk-x9bpm5s1.js} +3 -3
  95. package/dist/{chunk-cfrv8110.js → chunk-zv85cpt2.js} +4 -4
  96. package/dist/deploy/index.js +1 -1
  97. package/dist/dns/index.js +1 -1
  98. package/dist/drivers/index.js +1 -1
  99. package/dist/index.js +78 -78
  100. package/dist/operations/index.js +1 -1
  101. package/dist/protection/index.js +1 -1
  102. package/dist/spend/index.js +1 -1
  103. package/dist/ui/404.html +1 -1
  104. package/dist/ui/accept-invitation.html +1 -1
  105. package/dist/ui/access-denied.html +1 -1
  106. package/dist/ui/account/automation.html +6 -6
  107. package/dist/ui/account/security.html +2 -2
  108. package/dist/ui/applications/compose.html +6 -6
  109. package/dist/ui/applications/new.html +2 -2
  110. package/dist/ui/data/backups.html +6 -6
  111. package/dist/ui/data/services.html +6 -6
  112. package/dist/ui/data/volumes.html +6 -6
  113. package/dist/ui/index.html +6 -6
  114. package/dist/ui/infrastructure/topology.html +6 -6
  115. package/dist/ui/integrations.html +1 -1
  116. package/dist/ui/operations/alerts.html +6 -6
  117. package/dist/ui/operations/configuration.html +6 -6
  118. package/dist/ui/operations/jobs.html +6 -6
  119. package/dist/ui/operations/maintenance.html +5 -5
  120. package/dist/ui/operations/observability.html +6 -6
  121. package/dist/ui/operations/previews.html +6 -6
  122. package/dist/ui/operations/queue.html +6 -6
  123. package/dist/ui/operations/regions.html +6 -6
  124. package/dist/ui/operations/releases.html +6 -6
  125. package/dist/ui/operations/spend.html +6 -6
  126. package/dist/ui/operations/workloads.html +6 -6
  127. package/dist/ui/security.html +1 -1
  128. package/dist/ui/server/actions.html +6 -6
  129. package/dist/ui/server/activity.html +1 -1
  130. package/dist/ui/server/capacity.html +5 -5
  131. package/dist/ui/server/database.html +5 -5
  132. package/dist/ui/server/deployments.html +5 -5
  133. package/dist/ui/server/diagnostics.html +2 -2
  134. package/dist/ui/server/firewall.html +6 -6
  135. package/dist/ui/server/fleet.html +6 -6
  136. package/dist/ui/server/logs.html +6 -6
  137. package/dist/ui/server/metrics.html +5 -5
  138. package/dist/ui/server/security.html +2 -2
  139. package/dist/ui/server/services.html +2 -2
  140. package/dist/ui/server/sites.html +6 -6
  141. package/dist/ui/server/ssh-keys.html +6 -6
  142. package/dist/ui/server/team.html +6 -6
  143. package/dist/ui/server/terminal.html +2 -2
  144. package/dist/ui/serverless/alarms.html +6 -6
  145. package/dist/ui/serverless/assets.html +2 -2
  146. package/dist/ui/serverless/cost.html +2 -2
  147. package/dist/ui/serverless/data.html +6 -6
  148. package/dist/ui/serverless/deployments.html +2 -2
  149. package/dist/ui/serverless/firewall.html +2 -2
  150. package/dist/ui/serverless/functions.html +6 -6
  151. package/dist/ui/serverless/logs.html +6 -6
  152. package/dist/ui/serverless/metrics.html +1 -1
  153. package/dist/ui/serverless/queues.html +5 -5
  154. package/dist/ui/serverless/secrets.html +6 -6
  155. package/dist/ui/serverless/traces.html +6 -6
  156. package/dist/ui/serverless.html +5 -5
  157. package/package.json +3 -3
  158. package/dist/bin/chunk-0cefbrxg.js +0 -1
  159. package/dist/bin/chunk-1srmd473.js +0 -1
  160. package/dist/bin/chunk-27ka240w.js +0 -1
  161. package/dist/bin/chunk-3bq69jqk.js +0 -1
  162. package/dist/bin/chunk-4pysr1ky.js +0 -1
  163. package/dist/bin/chunk-56zfvf7e.js +0 -1
  164. package/dist/bin/chunk-59nav625.js +0 -1
  165. package/dist/bin/chunk-8fjzcr2w.js +0 -1
  166. package/dist/bin/chunk-9fq0bezb.js +0 -1
  167. package/dist/bin/chunk-9wpy7r9f.js +0 -1
  168. package/dist/bin/chunk-eetz9jgy.js +0 -1
  169. package/dist/bin/chunk-eg6156wp.js +0 -1
  170. package/dist/bin/chunk-ezpz96kp.js +0 -1
  171. package/dist/bin/chunk-f2qpsrrj.js +0 -1
  172. package/dist/bin/chunk-f3sbq7pw.js +0 -2
  173. package/dist/bin/chunk-gmabk4qn.js +0 -1
  174. package/dist/bin/chunk-kr51h4gk.js +0 -1
  175. package/dist/bin/chunk-mbqwrs7a.js +0 -6
  176. package/dist/bin/chunk-nx8gpr90.js +0 -34
  177. package/dist/bin/chunk-q62ggp3g.js +0 -1
  178. package/dist/bin/chunk-q957s44c.js +0 -1
  179. package/dist/bin/chunk-rm6qnyce.js +0 -2
  180. package/dist/bin/chunk-rxehseyz.js +0 -1
  181. package/dist/bin/chunk-tfz7djw9.js +0 -1
  182. package/dist/bin/chunk-tr8901hb.js +0 -1
  183. package/dist/bin/chunk-vqb80dyg.js +0 -1
  184. package/dist/bin/chunk-wysyyysg.js +0 -1
  185. package/dist/bin/chunk-xfs7rscr.js +0 -1
  186. package/dist/chunk-2fa9cdyf.js +0 -1
  187. package/dist/chunk-6d5e10md.js +0 -1
  188. package/dist/chunk-9gypn8w9.js +0 -1
  189. package/dist/chunk-badb5mf3.js +0 -34
  190. package/dist/chunk-j6a577hr.js +0 -1
  191. package/dist/chunk-kw852q5m.js +0 -709
  192. package/dist/chunk-p0b08g9f.js +0 -114
  193. package/dist/chunk-whdbz3h8.js +0 -1
  194. package/dist/chunk-y6k0vwfn.js +0 -6
@@ -81,6 +81,15 @@ export interface AWSError extends Error {
81
81
  /**
82
82
  * AWS API Client - Makes authenticated requests to AWS services
83
83
  */
84
+ /**
85
+ * Convert parsed XML text the way the parser's own option did, minus the
86
+ * lossy cases: `true`/`false` become booleans, and text becomes a number only
87
+ * when the number prints back as exactly the same text. So `16` and
88
+ * `923076644019` are numbers, while `+18082188241` (a phone number), `7.0`
89
+ * (an engine version), `1.50`, `0x1F`, `1e3` and a 20-digit ID stay strings.
90
+ * Exported for tests.
91
+ */
92
+ export declare function coerceXmlValues(node: any): any;
84
93
  export declare class AWSClient {
85
94
  private credentials?;
86
95
  private config;
@@ -41,7 +41,13 @@ export interface CacheEngineVersion {
41
41
  export declare class ElastiCacheClient {
42
42
  private client;
43
43
  private region;
44
+ private profile?;
44
45
  constructor(region?: string, profile?: string);
46
+ /**
47
+ * Send one query-API action and return its `<{Action}Result>`, parsed with
48
+ * values kept as text.
49
+ */
50
+ private query;
45
51
  /**
46
52
  * List all cache clusters
47
53
  */
@@ -88,7 +94,11 @@ export declare class ElastiCacheClient {
88
94
  CacheEngineVersions: CacheEngineVersion[];
89
95
  }>;
90
96
  /**
91
- * Get cache cluster statistics (mock for now)
97
+ * The cluster's latest CloudWatch readings over the last ten minutes.
98
+ *
99
+ * A metric with no datapoint in that window is left undefined rather than
100
+ * reported as 0. Memcached publishes GetHits/GetMisses where Redis and
101
+ * Valkey publish CacheHits/CacheMisses.
92
102
  */
93
103
  getCacheStatistics(cacheClusterId: string): Promise<{
94
104
  cpuUtilization?: number;
@@ -97,12 +107,4 @@ export declare class ElastiCacheClient {
97
107
  misses?: number;
98
108
  connections?: number;
99
109
  }>;
100
- /**
101
- * Parse cache clusters from response
102
- */
103
- private parseCacheClusters;
104
- /**
105
- * Parse single cache cluster from response
106
- */
107
- private parseCacheCluster;
108
110
  }
package/dist/aws/index.js CHANGED
@@ -1 +1 @@
1
- import{he,rr,as,cs,Su,Ma,Fa,ds,ls,Ua,Ze,j,et,ie,E,fe,hn,Qa,_e,Ha,fn,An,yn,Ch,Eh,Ry,Dy,Py,Ny,vt,ky,By,_y,xy,Tt,bh,vh,Th,wt,wh,Rh,Dh,In,Oy,Ly,$y,nr,My,Fy,Uy,Ga,qa,Cu,Qy,Hy,Gy,ir,Ph,Nh,sr,tt,Sn,Va,Eu,qy,bu,Vy,Rt,jy,zy,Ky,Wy,se,Jy,Xy,Yy,Zy,or,eI,tI,rI,Cn,ja,za,vu,Tu,Ka,ar}from"../chunk-p0b08g9f.js";import{Ae,rt,En,kh}from"../chunk-badb5mf3.js";import{y}from"../chunk-9s24pbbc.js";import{xe}from"../chunk-w4s3rswa.js";import{z}from"../chunk-2dextjqf.js";import{nt,oe,Oe,ye,Dt,vn,ps,gs,cr,dr,Tn,lr,ms,hs,fs,As,K,ys,Is,Ss,Cs,ae,Es,bs,vs,w,Xa,wn,Ya,ce,ur}from"../chunk-5dz6bzdj.js";import{I}from"../chunk-ms4dnha2.js";import{vr,ve}from"../chunk-np8vgbv0.js";import{h}from"../chunk-jt49qs0f.js";import{o}from"../chunk-3zzm5f28.js";import{Tr,n,l,Yh}from"../chunk-y6k0vwfn.js";export{ce as ACMClient,ur as ACMDnsValidator,n as AWSClient,Va as ApplicationAutoScalingClient,rr as AwsBackupClient,Eh as BedrockAgentClient,Ch as BedrockAgentRuntimeClient,yn as BedrockClient,An as BedrockRuntimeClient,h as CloudFormationClient,y as CloudFrontClient,fe as CloudWatchLogsClient,ye as CloudflareProvider,vt as ComprehendClient,hn as ConnectClient,ls as CostExplorerClient,wn as DnsProviderFactory,_e as DynamoDBClient,vr as EC2Client,xe as ECRClient,Ze as ECSClient,ar as EFSClient,Qa as ELBv2Client,tt as ElastiCacheClient,En as EmailClient,sr as EventBridgeClient,Oe as GoDaddyProvider,Ae as IAMClient,Eu as ImapServer,ir as KendraClient,E as LambdaClient,Ha as OpenSearchClient,nt as PROXIABLE_RECORD_TYPES,Ga as PersonalizeClient,Cu as PersonalizeEventsClient,qa as PersonalizeRuntimeClient,In as PollyClient,oe as PorkbunProvider,z as RDSClient,Tt as RekognitionClient,I as Route53Client,Ua as Route53DomainsClient,K as Route53Provider,o as S3Client,rt as SESClient,et as SNSClient,ie as SQSClient,ve as SSMClient,he as STSClient,Sn as SchedulerClient,j as SecretsManagerClient,Rt as SmsClient,Ka as SmsVoiceClient,bu as SmtpServer,Cn as SupportClient,ja as SupportTemplates,wt as TextractClient,fn as TranscribeClient,nr as TranslateClient,ae as UnifiedDnsValidator,or as VoiceClient,ky as analyzeSentiment,fs as applyDeclaredZoneSettings,Ss as applyZoneMigration,l as buildQueryParams,Py as completeWithClaude,xy as containsPii,vh as countFacesInS3Image,Wy as createDeliveryReceiptHandler,w as createDnsProvider,bs as createGoDaddyValidator,ds as createObjectStorageClient,Es as createPorkbunValidator,tI as createRecordingHandler,vs as createRoute53Validator,$y as createSSML,zy as createScheduledSmsHandler,Ky as createSmsClient,jy as createSmsInboxHandler,Tu as createSmsInfrastructure,rI as createVoiceClient,eI as createVoicemailHandler,lr as delegateZone,ms as delegateZoneFromConfig,hs as describeDelegation,As as describeZoneSettings,Yh as detectCredentialSource,Xa as detectDnsProvider,bh as detectLabelsFromS3,_y as detectLanguage,Ya as dnsProviders,kh as email,ys as exportRoute53Zone,By as extractEntities,Rh as extractFormsFromS3,Dh as extractTablesFromS3,wh as extractTextFromS3,Jy as formatPhoneNumber,Ny as generateEmbeddings,Yy as getCountryCode,Qy as getRecommendations,Hy as getSimilarItems,vu as getSmsInfrastructureStatus,Th as isContentSafe,cr as isNameserverRegistrar,Zy as isSamePhoneNumber,Xy as isValidPhoneNumber,dr as isZoneHost,cs as keyMatchesFilters,Dy as listClaudeModels,Uy as listLanguages,Ly as listVoices,Su as migrateObjectStorage,se as normalizePhoneNumber,Is as planZoneMigration,Dt as policyTag,Ma as providerEndpoint,vn as qualifyName,gs as reconcileDeclaredRecords,as as remapKey,Ry as requestModelAccess,ps as resolveDeclaredRecords,Fa as resolveObjectStorage,Tr as resolveS3Endpoint,Nh as retrieveForRag,Tn as sameNameservers,Ph as search,za as setupSmsInfrastructure,qy as startImapServer,Vy as startSmtpServer,Oy as textToSpeech,Gy as trackEvent,My as translate,Fy as translateToMultiple,Cs as verifyZoneParity};
1
+ import{Ae,nr,ls,us,bu,Qa,Ha,ps,gs,Ga,tt,z,rt,se,E,ye,An,qa,Oe,Va,yn,In,Sn,vh,Th,Ny,ky,By,_y,wt,xy,Oy,Ly,$y,Rt,wh,Rh,Dh,Dt,Ph,Nh,kh,Cn,My,Fy,Uy,ir,Qy,Hy,Gy,ja,za,vu,qy,Vy,jy,sr,Bh,_h,or,nt,En,Ka,Tu,zy,wu,Ky,Pt,Wy,Jy,Xy,Yy,ae,Zy,eI,tI,rI,ar,nI,iI,sI,bn,Wa,Ja,Ru,Du,Xa,cr}from"../chunk-4rkjhvgw.js";import{Ie,it,vn,xh}from"../chunk-t4ynyk8k.js";import{y}from"../chunk-65yh2h1e.js";import{Le}from"../chunk-dm6kyz6e.js";import{K}from"../chunk-e7m70ex1.js";import{st,ce,$e,Se,Nt,wn,hs,fs,dr,lr,Rn,ur,As,ys,Is,Ss,W,Cs,Es,bs,vs,de,Ts,ws,Rs,w,ec,Dn,tc,le,pr}from"../chunk-97trx8p9.js";import{I}from"../chunk-mv7hne2c.js";import{Tr,we}from"../chunk-x9bpm5s1.js";import{f}from"../chunk-bzbryxfm.js";import{o}from"../chunk-3x9g48ey.js";import{Rr,di,n,l,tf}from"../chunk-wrpnnrdf.js";export{le as ACMClient,pr as ACMDnsValidator,n as AWSClient,Ka as ApplicationAutoScalingClient,nr as AwsBackupClient,Th as BedrockAgentClient,vh as BedrockAgentRuntimeClient,Sn as BedrockClient,In as BedrockRuntimeClient,f as CloudFormationClient,y as CloudFrontClient,ye as CloudWatchLogsClient,Se as CloudflareProvider,wt as ComprehendClient,An as ConnectClient,gs as CostExplorerClient,Dn as DnsProviderFactory,Oe as DynamoDBClient,Tr as EC2Client,Le as ECRClient,tt as ECSClient,cr as EFSClient,qa as ELBv2Client,nt as ElastiCacheClient,vn as EmailClient,or as EventBridgeClient,$e as GoDaddyProvider,Ie as IAMClient,Tu as ImapServer,sr as KendraClient,E as LambdaClient,Va as OpenSearchClient,st as PROXIABLE_RECORD_TYPES,ja as PersonalizeClient,vu as PersonalizeEventsClient,za as PersonalizeRuntimeClient,Cn as PollyClient,ce as PorkbunProvider,K as RDSClient,Rt as RekognitionClient,I as Route53Client,Ga as Route53DomainsClient,W as Route53Provider,o as S3Client,it as SESClient,rt as SNSClient,se as SQSClient,we as SSMClient,Ae as STSClient,En as SchedulerClient,z as SecretsManagerClient,Pt as SmsClient,Xa as SmsVoiceClient,wu as SmtpServer,bn as SupportClient,Wa as SupportTemplates,Dt as TextractClient,yn as TranscribeClient,ir as TranslateClient,de as UnifiedDnsValidator,ar as VoiceClient,xy as analyzeSentiment,Is as applyDeclaredZoneSettings,bs as applyZoneMigration,l as buildQueryParams,di as coerceXmlValues,By as completeWithClaude,$y as containsPii,Rh as countFacesInS3Image,Yy as createDeliveryReceiptHandler,w as createDnsProvider,ws as createGoDaddyValidator,ps as createObjectStorageClient,Ts as createPorkbunValidator,iI as createRecordingHandler,Rs as createRoute53Validator,Uy as createSSML,Jy as createScheduledSmsHandler,Xy as createSmsClient,Wy as createSmsInboxHandler,Du as createSmsInfrastructure,sI as createVoiceClient,nI as createVoicemailHandler,ur as delegateZone,As as delegateZoneFromConfig,ys as describeDelegation,Ss as describeZoneSettings,tf as detectCredentialSource,ec as detectDnsProvider,wh as detectLabelsFromS3,Ly as detectLanguage,tc as dnsProviders,xh as email,Cs as exportRoute53Zone,Oy as extractEntities,Nh as extractFormsFromS3,kh as extractTablesFromS3,Ph as extractTextFromS3,Zy as formatPhoneNumber,_y as generateEmbeddings,tI as getCountryCode,qy as getRecommendations,Vy as getSimilarItems,Ru as getSmsInfrastructureStatus,Dh as isContentSafe,dr as isNameserverRegistrar,rI as isSamePhoneNumber,eI as isValidPhoneNumber,lr as isZoneHost,us as keyMatchesFilters,ky as listClaudeModels,Gy as listLanguages,Fy as listVoices,bu as migrateObjectStorage,ae as normalizePhoneNumber,Es as planZoneMigration,Nt as policyTag,Qa as providerEndpoint,wn as qualifyName,fs as reconcileDeclaredRecords,ls as remapKey,Ny as requestModelAccess,hs as resolveDeclaredRecords,Ha as resolveObjectStorage,Rr as resolveS3Endpoint,_h as retrieveForRag,Rn as sameNameservers,Bh as search,Ja as setupSmsInfrastructure,zy as startImapServer,Ky as startSmtpServer,My as textToSpeech,jy as trackEvent,Qy as translate,Hy as translateToMultiple,vs as verifyZoneParity};
@@ -0,0 +1 @@
1
+ import{R}from"./chunk-1j9vy88a.js";import"./chunk-q3xwh0r8.js";export{R as LambdaClient};
@@ -1,9 +1,9 @@
1
- import{z,Ir}from"./chunk-24njmb7d.js";function G(e,t){return`/var/www/${e}-${t}`}var _e=new Set(["laravel","php","statamic","wordpress"]);function si(e){return e.type!=null&&_e.has(e.type)}function Ds(e){let t=e.proxyTo;if(t==null)return[];return(Array.isArray(t)?t:[t]).map((n)=>String(n).trim()).filter((n)=>n.length>0)}function Se(e){return Ds(e).length>0}function ee(e){if(e.deploy)return e.deploy;if(si(e))return"server";if(e.start)return"server";return"bucket"}function P(e){if(e.redirect)return"redirect";if(Se(e))return"proxy";if(si(e))return"server-php";if(ee(e)==="bucket")return"bucket";return e.start?"server-app":"server-static"}function mo(e){return e.infrastructure?.compute!=null||Boolean(e.cloud?.attachTo?.trim())}function ks(e,t={}){let r=[],n=[],i=e.sites||{},s=mo(e),c=Ir(e);if(c)r.push(c);let d=new Map;for(let[l,o]of Object.entries(i)){if(!o)continue;let f=ee(o),E=P(o);if(E==="redirect"){if(!o.domain)r.push(`Site '${l}' is a redirect site but has no \`domain\` to redirect from.`);if(!(typeof o.redirect==="string"?o.redirect:o.redirect?.to))r.push(`Site '${l}' is a redirect site but has no redirect target (\`redirect\` / \`redirect.to\`).`);if(!s)r.push(`Site '${l}' is a redirect site but no \`infrastructure.compute\` is configured to host the gateway that serves the redirect.`);let a=[];if(o.start)a.push("start");if(o.root)a.push("root");if(o.proxyTo)a.push("proxyTo");if(a.length>0)n.push(`Site '${l}' is a redirect site but also sets ${a.join(", ")}. These are ignored.`);continue}if(E==="proxy"){if(!o.domain)r.push(`Site '${l}' is a proxy site but has no \`domain\` to route from.`);if(!s)r.push(`Site '${l}' is a proxy site but no \`infrastructure.compute\` is configured to host the gateway that forwards it.`);let p=[];if(o.start)p.push("start");if(o.root)p.push("root");if(typeof o.port==="number")p.push("port");if(o.build)p.push("build");if(o.preStart&&o.preStart.length>0)p.push("preStart");if(p.length>0)n.push(`Site '${l}' sets \`proxyTo\`, so ts-cloud ships and supervises nothing for it. ${p.join(", ")} ${p.length===1?"is":"are"} ignored — remove ${p.length===1?"it":"them"}, or drop \`proxyTo\` to let ts-cloud own the service.`);continue}if(f==="server"&&!o.start&&!o.root){r.push(`Site '${l}' sets deploy:'server' but declares neither \`start\` (dynamic app) nor \`root\` (static site to serve). Add one.`);continue}if(E==="server-php"){if(!s)r.push(`Site '${l}' is a PHP site (type:'${o.type}') but no \`infrastructure.compute\` is configured. Add a server (infrastructure.compute) with PHP provisioning.`);if(!o.repository?.url)r.push(`Site '${l}' is a PHP site (type:'${o.type}') but has no \`repository.url\` to clone. PHP sites deploy via git.`)}else if(E==="server-app"){if(!s)r.push(`Site '${l}' deploys to a server (deploy:'server'${o.deploy?"":" inferred from `start`"}) but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`);if(typeof o.port==="number"){let p=t.occupiedPorts?.get(o.port);if(p)r.push(`Site '${l}' wants port ${o.port}, which project '${p}' already serves on this box. Attached projects share one port namespace. Give '${l}' a free port, or let the attach allocate one.`);let a=d.get(o.port);if(a)r.push(`Sites '${a}' and '${l}' both use port ${o.port}. Server apps sharing a box must use distinct ports.`);else d.set(o.port,l)}}else if(E==="server-static"){if(!o.root)r.push(`Site '${l}' is a server static site (deploy:'server', no \`start\`) but has no \`root\` directory to serve.`);if(!s)r.push(`Site '${l}' deploys to a server (deploy:'server') but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`)}else{if(!o.root)r.push(`Site '${l}' deploys to a bucket but has no \`root\` directory to upload.`);let p=[];if(o.start)p.push("start");if(typeof o.port==="number")p.push("port");if(o.preStart&&o.preStart.length>0)p.push("preStart");if(p.length>0)n.push(`Site '${l}' deploys to a bucket but sets server-only field(s): ${p.join(", ")}. These are ignored. Set deploy:'server' to use them.`)}}return{errors:r,warnings:n}}function _s(e){let t=P(e);return t!=="bucket"&&t!=="redirect"&&t!=="proxy"}function oc(e){return P(e)==="bucket"}function sc(e,t){if(z(e)==="serverless")return!0;let r=Object.entries(e.sites??{}).filter(([,i])=>i!=null),n=t?r.filter(([i])=>i===t):r;if(n.length===0)return!0;return!n.every(([,i])=>{let s=P(i);return s==="redirect"||s==="proxy"})}var O={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 M="/opt/pantry";function N(e){return`'${e.split("'").join("'\\''")}'`}function Sr(e={}){return["export DEBIAN_FRONTEND=noninteractive","export PANTRY_SERVICE_SCOPE=system","export PANTRY_INSTALL_DIR=/usr/local/bin",e.version?`export PANTRY_VERSION=${N(e.version)}`:'export PANTRY_VERSION="${PANTRY_VERSION:-latest}"',"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}"; unzip -o "${TMP}/${ZIP}" -d /usr/local/bin; chmod +x /usr/local/bin/pantry; rm -rf "${TMP}"','export PATH="/usr/local/bin:$PATH"',"mkdir -p /opt/pantry"]}function yt(){return'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true'}function Ye(e){if(e.length===0)return[];return[`(cd /opt/pantry && pantry install ${[...new Set(e)].map(N).join(" ")})`]}function go(e){return[...new Set(e)].flatMap((t)=>[`(cd /opt/pantry && pantry start ${N(t)})`,`(cd /opt/pantry && pantry enable ${N(t)})`])}var S="/etc/mail",T="mail-server",q="mail",F=`${M}/pantry/.bin`;function h(e){return`'${String(e).split("'").join("'\\''")}'`}function b(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function fe(e){return[e.version?`${O.mail}@${e.version}`:O.mail]}function Y(e,t){return`${S}/dkim/${t}.${e.dkim.selector}.pem`}function te(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 = ${b(e.bindAddress)}`,`port = ${e.ports.smtp}`,`hostname = ${b(e.hostname)}`];if(e.domains.length>0)t.push(`local_domains = ${b(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 = ${b(e.tls.certPath)}`);if(e.tls.keyPath)t.push(`key_path = ${b(e.tls.keyPath)}`);if(t.push("","[auth]",`enabled = ${e.mode==="server"}`,"","[antispam]",`dnsbl = ${e.spam.dnsbl}`,`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 = ${b(e.tls.acmeEmail)}`);if(t.push("","[webhook]",`enabled = ${!!e.webhookUrl}`),e.webhookUrl)t.push(`url = ${b(e.webhookUrl)}`);return t.push(""),t.join(`
2
- `)}function Te(e){let t=["# Generated by ts-cloud. See /etc/mail/config.toml for the rest.",`SMTP_DB_PATH=${te(e)}`,`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_SECURE_COOKIES=${e.tls.enabled}`);if(e.tls.requireForAuth)t.push("SMTP_REQUIRE_TLS_FOR_AUTH=true");if(e.dkim.enabled&&e.domains.length>0){let[r,...n]=e.domains;if(t.push(`DKIM_DOMAIN=${r}`,`DKIM_SELECTOR=${e.dkim.selector}`,`DKIM_PRIVATE_KEY_PATH=${Y(e,r)}`),n.length>0){let i=n.map((s)=>`${s}:${e.dkim.selector}:${Y(e,s)}`);t.push(`DKIM_EXTRA_KEYS=${i.join(",")}`)}}return t.push(""),t.join(`
1
+ import{z,Rr}from"./chunk-jdfbahjb.js";function K(e,t){return`/var/www/${e}-${t}`}var _e=new Set(["laravel","php","statamic","wordpress"]);function ai(e){return e.type!=null&&_e.has(e.type)}function _s(e){let t=e.proxyTo;if(t==null)return[];return(Array.isArray(t)?t:[t]).map((n)=>String(n).trim()).filter((n)=>n.length>0)}function Se(e){return _s(e).length>0}function ee(e){if(e.deploy)return e.deploy;if(ai(e))return"server";if(e.start)return"server";return"bucket"}function P(e){if(e.redirect)return"redirect";if(Se(e))return"proxy";if(ai(e))return"server-php";if(ee(e)==="bucket")return"bucket";return e.start?"server-app":"server-static"}function go(e){return e.infrastructure?.compute!=null||Boolean(e.cloud?.attachTo?.trim())}function xs(e,t={}){let r=[],n=[],i=e.sites||{},s=go(e),c=Rr(e);if(c)r.push(c);let d=new Map;for(let[l,o]of Object.entries(i)){if(!o)continue;let f=ee(o),E=P(o);if(E==="redirect"){if(!o.domain)r.push(`Site '${l}' is a redirect site but has no \`domain\` to redirect from.`);if(!(typeof o.redirect==="string"?o.redirect:o.redirect?.to))r.push(`Site '${l}' is a redirect site but has no redirect target (\`redirect\` / \`redirect.to\`).`);if(!s)r.push(`Site '${l}' is a redirect site but no \`infrastructure.compute\` is configured to host the gateway that serves the redirect.`);let a=[];if(o.start)a.push("start");if(o.root)a.push("root");if(o.proxyTo)a.push("proxyTo");if(a.length>0)n.push(`Site '${l}' is a redirect site but also sets ${a.join(", ")}. These are ignored.`);continue}if(E==="proxy"){if(!o.domain)r.push(`Site '${l}' is a proxy site but has no \`domain\` to route from.`);if(!s)r.push(`Site '${l}' is a proxy site but no \`infrastructure.compute\` is configured to host the gateway that forwards it.`);let p=[];if(o.start)p.push("start");if(o.root)p.push("root");if(typeof o.port==="number")p.push("port");if(o.build)p.push("build");if(o.preStart&&o.preStart.length>0)p.push("preStart");if(p.length>0)n.push(`Site '${l}' sets \`proxyTo\`, so ts-cloud ships and supervises nothing for it. ${p.join(", ")} ${p.length===1?"is":"are"} ignored — remove ${p.length===1?"it":"them"}, or drop \`proxyTo\` to let ts-cloud own the service.`);continue}if(f==="server"&&!o.start&&!o.root){r.push(`Site '${l}' sets deploy:'server' but declares neither \`start\` (dynamic app) nor \`root\` (static site to serve). Add one.`);continue}if(E==="server-php"){if(!s)r.push(`Site '${l}' is a PHP site (type:'${o.type}') but no \`infrastructure.compute\` is configured. Add a server (infrastructure.compute) with PHP provisioning.`);if(!o.repository?.url)r.push(`Site '${l}' is a PHP site (type:'${o.type}') but has no \`repository.url\` to clone. PHP sites deploy via git.`)}else if(E==="server-app"){if(!s)r.push(`Site '${l}' deploys to a server (deploy:'server'${o.deploy?"":" inferred from `start`"}) but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`);if(typeof o.port==="number"){let p=t.occupiedPorts?.get(o.port);if(p)r.push(`Site '${l}' wants port ${o.port}, which project '${p}' already serves on this box. Attached projects share one port namespace. Give '${l}' a free port, or let the attach allocate one.`);let a=d.get(o.port);if(a)r.push(`Sites '${a}' and '${l}' both use port ${o.port}. Server apps sharing a box must use distinct ports.`);else d.set(o.port,l)}}else if(E==="server-static"){if(!o.root)r.push(`Site '${l}' is a server static site (deploy:'server', no \`start\`) but has no \`root\` directory to serve.`);if(!s)r.push(`Site '${l}' deploys to a server (deploy:'server') but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`)}else{if(!o.root)r.push(`Site '${l}' deploys to a bucket but has no \`root\` directory to upload.`);let p=[];if(o.start)p.push("start");if(typeof o.port==="number")p.push("port");if(o.preStart&&o.preStart.length>0)p.push("preStart");if(p.length>0)n.push(`Site '${l}' deploys to a bucket but sets server-only field(s): ${p.join(", ")}. These are ignored. Set deploy:'server' to use them.`)}}return{errors:r,warnings:n}}function $s(e){let t=P(e);return t!=="bucket"&&t!=="redirect"&&t!=="proxy"}function ac(e){return P(e)==="bucket"}function cc(e,t){if(z(e)==="serverless")return!0;let r=Object.entries(e.sites??{}).filter(([,i])=>i!=null),n=t?r.filter(([i])=>i===t):r;if(n.length===0)return!0;return!n.every(([,i])=>{let s=P(i);return s==="redirect"||s==="proxy"})}var O={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 M="/opt/pantry";function N(e){return`'${e.split("'").join("'\\''")}'`}function br(e={}){return["export DEBIAN_FRONTEND=noninteractive","export PANTRY_SERVICE_SCOPE=system","export PANTRY_INSTALL_DIR=/usr/local/bin",e.version?`export PANTRY_VERSION=${N(e.version)}`:'export PANTRY_VERSION="${PANTRY_VERSION:-latest}"',"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}"; unzip -o "${TMP}/${ZIP}" -d /usr/local/bin; chmod +x /usr/local/bin/pantry; rm -rf "${TMP}"','export PATH="/usr/local/bin:$PATH"',"mkdir -p /opt/pantry"]}function St(){return'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true'}function Ze(e){if(e.length===0)return[];return[`(cd /opt/pantry && pantry install ${[...new Set(e)].map(N).join(" ")})`]}function fo(e){return[...new Set(e)].flatMap((t)=>[`(cd /opt/pantry && pantry start ${N(t)})`,`(cd /opt/pantry && pantry enable ${N(t)})`])}var S="/etc/mail",T="mail-server",q="mail",F=`${M}/pantry/.bin`;function h(e){return`'${String(e).split("'").join("'\\''")}'`}function b(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function fe(e){return[e.version?`${O.mail}@${e.version}`:O.mail]}function G(e,t){return`${S}/dkim/${t}.${e.dkim.selector}.pem`}function te(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 = ${b(e.bindAddress)}`,`port = ${e.ports.smtp}`,`hostname = ${b(e.hostname)}`];if(e.domains.length>0)t.push(`local_domains = ${b(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 = ${b(e.tls.certPath)}`);if(e.tls.keyPath)t.push(`key_path = ${b(e.tls.keyPath)}`);if(t.push("","[auth]",`enabled = ${e.mode==="server"}`,"","[antispam]",`dnsbl = ${e.spam.dnsbl}`,`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 = ${b(e.tls.acmeEmail)}`);if(t.push("","[webhook]",`enabled = ${!!e.webhookUrl}`),e.webhookUrl)t.push(`url = ${b(e.webhookUrl)}`);return t.push(""),t.join(`
2
+ `)}function Te(e){let t=["# Generated by ts-cloud. See /etc/mail/config.toml for the rest.",`SMTP_DB_PATH=${te(e)}`,`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_SECURE_COOKIES=${e.tls.enabled}`);if(e.tls.requireForAuth)t.push("SMTP_REQUIRE_TLS_FOR_AUTH=true");if(e.dkim.enabled&&e.domains.length>0){let[r,...n]=e.domains;if(t.push(`DKIM_DOMAIN=${r}`,`DKIM_SELECTOR=${e.dkim.selector}`,`DKIM_PRIVATE_KEY_PATH=${G(e,r)}`),n.length>0){let i=n.map((s)=>`${s}:${e.dkim.selector}:${G(e,s)}`);t.push(`DKIM_EXTRA_KEYS=${i.join(",")}`)}}return t.push(""),t.join(`
3
3
  `)}function he(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=${T}`,`Group=${T}`,`WorkingDirectory=${e.storagePath}`,`EnvironmentFile=${S}/mail.env`,`Environment="PATH=${F}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"`,`ExecStart=${F}/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 ve(e){if(!e.dkim.enabled||e.domains.length===0)return[];let t=[`mkdir -p ${S}/dkim`];for(let r of e.domains){let n=Y(e,r);t.push(`if [ ! -f ${h(n)} ]; then openssl genrsa -out ${h(n)} 2048; fi`,`chmod 0600 ${h(n)}`,`echo "DKIM ${e.dkim.selector}._domainkey.${r} IN TXT v=DKIM1; k=rsa; p=$(openssl rsa -in ${h(n)} -pubout -outform PEM 2>/dev/null | grep -v '^-----' | tr -d '\\n')"`)}return t.push(`chown -R ${T}:${T} ${S}/dkim`),t}function ye(e){if(e.accounts.length===0)return[];let t=(r)=>`runuser -u ${T} -- env SMTP_DB_PATH="$TS_CLOUD_MAIL_DB" ${F}/mail user:local ${r} || true`;return e.accounts.flatMap((r)=>[t(`create ${h(r.address)} ${h(r.password)} ${h(r.address)}`),t(`change-password ${h(r.address)} ${h(r.password)}`)])}function re(e){if(!e.enabled)return[];return[...Ye(fe(e)),`id -u ${T} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin ${T}`,`mkdir -p ${e.storagePath} ${S}`,`chown -R ${T}:${T} ${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(te(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'`,Te(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`,`chown root:${T} ${S}/mail.env`,...ve(e),`cat > /etc/systemd/system/${q}.service <<'TS_CLOUD_MAIL_UNIT_EOF'`,he(e),"TS_CLOUD_MAIL_UNIT_EOF","systemctl daemon-reload",`systemctl enable ${q}`,`systemctl restart ${q}`,...ye(e)]}var g=`${M}/pantry/.bin`,W=15306,K=15991,V=15999,ne=16101,w=2379,v="/var/lib/vitess",X=100;function ai(e){return e===!0||typeof e==="object"&&e!==null}function Ee(e){return typeof e==="object"&&e!==null?e:{}}function m(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 _="vitess",be=`${g}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`,ae="/usr/local/lib/vitess",Q=new Map;function j(e){return`${ae}/${e}.sh`}function D(e,t){return Q.set(e,Ce(t)),`/bin/sh ${j(e)}`}function se(){let e=[`mkdir -p ${ae}`];for(let[t,r]of Q)e.push(`cat > ${j(t)} <<'TS_CLOUD_VITESS_LAUNCHER_EOF'`,r,"TS_CLOUD_VITESS_LAUNCHER_EOF",`chmod 0755 ${j(t)}`);return e}function Ce(e){return["#!/bin/sh","set -e",`cd ${M}`,`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 ${g}/mysqld 2>/dev/null)")")"`,`VTROOT="$(dirname "$(dirname "$(readlink -f ${g}/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 ve(e){if(!e.dkim.enabled||e.domains.length===0)return[];let t=[`mkdir -p ${S}/dkim`];for(let r of e.domains){let n=G(e,r);t.push(`if [ ! -f ${h(n)} ]; then openssl genrsa -out ${h(n)} 2048; fi`,`chmod 0600 ${h(n)}`,`echo "DKIM ${e.dkim.selector}._domainkey.${r} IN TXT v=DKIM1; k=rsa; p=$(openssl rsa -in ${h(n)} -pubout -outform PEM 2>/dev/null | grep -v '^-----' | tr -d '\\n')"`)}return t.push(`chown -R ${T}:${T} ${S}/dkim`),t}function ye(e){if(e.accounts.length===0)return[];let t=(r)=>`runuser -u ${T} -- env SMTP_DB_PATH="$TS_CLOUD_MAIL_DB" ${F}/mail user:local ${r} || true`;return e.accounts.flatMap((r)=>[t(`create ${h(r.address)} ${h(r.password)} ${h(r.address)}`),t(`change-password ${h(r.address)} ${h(r.password)}`)])}function re(e){if(!e.enabled)return[];return[...Ze(fe(e)),`id -u ${T} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin ${T}`,`mkdir -p ${e.storagePath} ${S}`,`chown -R ${T}:${T} ${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(te(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'`,Te(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`,`chown root:${T} ${S}/mail.env`,...ve(e),`cat > /etc/systemd/system/${q}.service <<'TS_CLOUD_MAIL_UNIT_EOF'`,he(e),"TS_CLOUD_MAIL_UNIT_EOF","systemctl daemon-reload",`systemctl enable ${q}`,`systemctl restart ${q}`,...ye(e)]}var g=`${M}/pantry/.bin`,W=15306,Y=15991,V=15999,ne=16101,w=2379,v="/var/lib/vitess",X=100;function ci(e){return e===!0||typeof e==="object"&&e!==null}function Ee(e){return typeof e==="object"&&e!==null?e:{}}function m(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 _="vitess",be=`${g}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`,ae="/usr/local/lib/vitess",Q=new Map;function j(e){return`${ae}/${e}.sh`}function D(e,t){return Q.set(e,Ce(t)),`/bin/sh ${j(e)}`}function se(){let e=[`mkdir -p ${ae}`];for(let[t,r]of Q)e.push(`cat > ${j(t)} <<'TS_CLOUD_VITESS_LAUNCHER_EOF'`,r,"TS_CLOUD_VITESS_LAUNCHER_EOF",`chmod 0755 ${j(t)}`);return e}function Ce(e){return["#!/bin/sh","set -e",`cd ${M}`,`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 ${g}/mysqld 2>/dev/null)")")"`,`VTROOT="$(dirname "$(dirname "$(readlink -f ${g}/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 A(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=${_}`,`Group=${_}`,`Environment="PATH=${be}"`,`Environment="VTDATAROOT=${v}"`,...Object.entries(e.environment??{}).map(([r,n])=>`Environment="${r}=${n}"`),...(e.execStartPre??[]).map((r)=>`ExecStartPre=${r}`),`ExecStart=${e.execStart}`,"Restart=always","RestartSec=5","LimitNOFILE=65535","","[Install]","WantedBy=multi-user.target"),t.join(`
6
- `)}function oe(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_VITESS_UNIT_EOF'`,t,"TS_CLOUD_VITESS_UNIT_EOF"]}function Re(e){let t=e.cell??"zone1",r=e.vtgatePort??W,i=`${((e.keyspaces?.length)?e.keyspaces:[{name:"app"}]).map((s)=>{let c=(s.sharded?["-80","80-"]:["0"]).map((d)=>`shards:{name:"${d}"}`).join(" ");return`keyspaces:{name:"${s.name}" ${c}}`}).join(" ")} cells:"${t}"`;return A({description:"Vitess (vtcombo, single-process development stack)",execStart:D("vtcombo",[`${g}/vtcombo`,`--cell ${t}`,`--proto-topo ${m(i)}`,`--mysql-server-port ${r}`,"--mysql-server-bind-address 127.0.0.1","--mysql-auth-server-impl none","--start-mysql",`--port ${K}`,`--grpc-port ${V}`])})}function De(){return A({description:"etcd (Vitess topology store)",execStart:D("etcd",[`${g}/etcd`,`--data-dir ${v}/etcd`,`--listen-client-urls http://127.0.0.1:${w}`,`--advertise-client-urls http://127.0.0.1:${w}`]),execStartPre:[`+/bin/mkdir -p ${v}/etcd`,`+/bin/chown ${_}:${_} ${v}/etcd`]})}function J(e){return["--topo-implementation etcd2",`--topo-global-server-address ${e.etcdEndpoint??`http://127.0.0.1:${w}`}`,"--topo-global-root /vitess/global"]}function Ae(e){let t=!e.etcdEndpoint;return A({description:"Vitess vtctld (control plane)",after:t?["vitess-etcd.service"]:[],requires:t?["vitess-etcd.service"]:[],execStart:D("vtctld",[`${g}/vtctld`,...J(e),`--cell ${e.cell??"zone1"}`,"--service-map grpc-vtctl,grpc-vtctld",`--grpc-port ${V}`,`--port ${V+1}`])})}function Le(e,t,r){let n=e.cell??"zone1";return A({description:`Vitess vttablet (${t}/${r})`,after:["vitess-vtctld.service","vitess-mysqlctld.service"],requires:["vitess-mysqlctld.service"],execStart:D("vttablet",[`${g}/vttablet`,...J(e),`--tablet-path ${n}-${String(X).padStart(10,"0")}`,`--init-keyspace ${t}`,`--init-shard ${r}`,"--init-tablet-type replica",`--service-map ${m("grpc-queryservice,grpc-tabletmanager,grpc-updatestream")}`,`--port ${ne}`,`--grpc-port ${ne+1}`,`--db-port ${e.mysqlPort??3306}`,`--mycnf-mysql-port ${e.mysqlPort??3306}`])})}function Oe(e){return A({description:"Vitess mysqlctld (managed mysqld)",execStart:D("mysqlctld",[`${g}/mysqlctld`,`--tablet-uid ${X}`,`--mysql-port ${e.mysqlPort??3306}`,'--init-db-sql-file "$VTROOT/config/init_db.sql"',"--wait-time 2m"]),execStartPre:[`+/bin/mkdir -p ${v}`,`+/bin/chown ${_}:${_} ${v}`]})}var ce="/etc/vitess/auth.json",x="/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 ${x} ] && [ "$(cat ${x})" = "$VTESS_VTGATE_AUTH_SHA" ]; then VTESS_VTGATE_AUTH_CHANGED=0; fi`,`install -o ${_} -g ${_} -m 0600 "$VTESS_AUTH_TMP" ${ce}`,'rm -f "$VTESS_AUTH_TMP"']}function Ue(e){let t=e.cell??"zone1";return A({description:"Vitess vtgate (query router)",after:["vitess-vtctld.service"],execStart:D("vtgate",[`${g}/vtgate`,...J(e),`--cell ${t}`,`--cells-to-watch ${t}`,"--tablet-types-to-wait PRIMARY,REPLICA",`--service-map ${m("grpc-vtgateservice")}`,`--mysql-server-port ${e.vtgatePort??W}`,`--mysql-server-bind-address ${e.bindAddress??"127.0.0.1"}`,"--mysql-auth-server-impl static",`--mysql-auth-server-static-file ${ce}`,`--port ${K}`,`--grpc-port ${K+1}`])})}function Ie(e){let t=e.cell??"zone1",r=e.etcdEndpoint??`http://127.0.0.1:${w}`,n=`${g}/vtctldclient --server 127.0.0.1:${V}`,i=[`for i in $(seq 1 30); do ${n} GetCellInfoNames >/dev/null 2>&1 && break; sleep 2; done`,`if ! ${n} GetCellInfoNames 2>/dev/null | grep -qx ${m(t)}; then`,` ${n} AddCellInfo --root ${m(`/vitess/${t}`)} --server-address ${m(r)} ${m(t)}`,"fi"];for(let s of e.keyspaces??[]){let c=s.sharded?" --sharded":"";i.push(`if ! ${n} GetKeyspace ${m(s.name)} >/dev/null 2>&1; then`,` ${n} CreateKeyspace${c} ${m(s.name)}`,"fi");let d=`${t}-${String(X).padStart(10,"0")}`;for(let l of s.sharded?["-80","80-"]:["0"]){let o=`${s.name}/${l}`;i.push("for i in $(seq 1 90); do",` if ${n} GetShard ${m(o)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then break; fi`,` ${n} PlannedReparentShard ${m(o)} --new-primary ${m(d)} >/dev/null 2>&1 && break`,` ${n} InitShardPrimary --force ${m(o)} ${m(d)} >/dev/null 2>&1 && break`," sleep 2","done",`if ! ${n} GetShard ${m(o)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then`,` echo "no primary could be elected for ${o}" >&2; exit 1`,"fi")}i.push(`${n} RebuildKeyspaceGraph ${m(s.name)} >/dev/null`)}return i}function ie(e){let t=e.vtgatePort??W;return["for i in $(seq 1 60); do",` if (cd ${M} && eval "$(pantry env 2>/dev/null)"; MYSQL_PWD=${m(e.password??"")} ${g}/mysql -h 127.0.0.1 -P ${t} -u ${m(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 fo(e){if(!ai(e))return[];let t=Ee(e),r=t.mode==="combo";Q.clear();let n=['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",...Ye(Pe(t)),`VT_MYSQL_LIB="$(dirname "$(dirname "$(readlink -f ${g}/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 ${_} >/dev/null 2>&1 || useradd --system --home-dir ${v} --shell /usr/sbin/nologin ${_}`,`mkdir -p ${v}`,`chown -R ${_}:${_} ${v}`];if(r)return n.push(...oe("vitess-vtcombo",Re(t)),...se(),"systemctl daemon-reload","systemctl enable --now vitess-vtcombo.service",...ie(t)),n;n.push(...xe(t));let i=[];if(!t.etcdEndpoint)i.push(["vitess-etcd",De()]);i.push(["vitess-vtctld",Ae(t)],["vitess-mysqlctld",Oe(t)],["vitess-vtgate",Ue(t)]);for(let s of t.keyspaces??[])for(let c of s.sharded?["-80","80-"]:["0"])i.push([`vitess-vttablet-${s.name}-${c.replace(/-/g,"x")}`,Le(t,s.name,c)]);for(let[s,c]of i)n.push(...oe(s,c));n.push(...se()),n.push("systemctl daemon-reload");for(let[s]of i)n.push(`systemctl enable --now ${s}.service`);return n.push(`if [ "$VTESS_VTGATE_AUTH_CHANGED" = 1 ]; then systemctl restart vitess-vtgate.service; printf '%s\\n' "$VTESS_VTGATE_AUTH_SHA" > ${x}; chown ${_}:${_} ${x}; chmod 0600 ${x}; fi`,...Ie(t),...ie(t)),n}var ke=new Set(["singlestore","vitess"]);function ci(e){if(e?.engine&&ke.has(e.engine))return!1;return!e?.host||e.host==="127.0.0.1"||e.host==="localhost"}function br(e,t="psql"){let r=e?.port??5432;if(ci(e))return`${t} -p ${r} -U postgres`;let n=e?.username||"postgres";return`${e?.password?`PGPASSWORD='${e.password.replace(/'/g,"'\\''")}' `:""}${t} -h ${e.host} -p ${r} -U ${n} -w`}function y(e){return e===!0||typeof e==="object"&&e!=null}function Ne(e){let t=[],r=[];if(y(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(y(e.mariadb))t.push(O.mariadb),r.push("mariadb");if(y(e.postgres))t.push("postgresql.org"),r.push("postgres");if(y(e.redis))t.push("redis.io"),r.push("redis");if(y(e.memcached))t.push("memcached.org"),r.push("memcached");if(y(e.meilisearch))t.push("meilisearch.com"),r.push("meilisearch");return{packages:t,services:r}}function ho(e={},t={}){let r=Ne(e),n=fo(e.vitess),i=t.mail?re(t.mail):[];if(r.packages.length===0)return[...n,...i];return[...Ye(r.packages),...go(r.services),...n,...i]}function St(e,t={}){if(!e?.name)return[];if(!ci(e))return[];let r=e.name,n=e.username||r,i=e.password||"",s=y(t.postgres)||e.engine==="postgres",c=y(t.mariadb)||e.engine==="mariadb",d=y(t.mysql)||e.engine==="mysql";if(s&&!d&&!c){let a=(u)=>`"${u.replace(/"/g,'""')}"`,R=(u)=>`'${u.replace(/'/g,"''")}'`,L=(u,k)=>["DO $$ BEGIN",` IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${R(u)}) THEN`,` CREATE ROLE ${a(u)} LOGIN PASSWORD ${R(k)};`," ELSE",` ALTER ROLE ${a(u)} LOGIN PASSWORD ${R(k)};`," END IF;","END $$;"],U=(u)=>{let k=u.databases&&u.databases.length>0?u.databases:[r],B=[];for(let H of k)if(u.access==="readonly")B.push(`GRANT CONNECT ON DATABASE ${a(H)} TO ${a(u.username)};`,`\\connect ${a(H)}`,`GRANT USAGE ON SCHEMA public TO ${a(u.username)};`,`GRANT SELECT ON ALL TABLES IN SCHEMA public TO ${a(u.username)};`,`ALTER DEFAULT PRIVILEGES FOR ROLE ${a(n)} IN SCHEMA public GRANT SELECT ON TABLES TO ${a(u.username)};`,"\\connect postgres");else B.push(`GRANT ALL PRIVILEGES ON DATABASE ${a(H)} TO ${a(u.username)};`);return B},I=e.users||[],me=e.port??5432;return[yt(),`for i in $(seq 1 30); do pg_isready -p ${me} -q && break; sleep 2; done`,`${br(e)} <<'TS_CLOUD_PG_EOF'`,...L(n,i),`SELECT 'CREATE DATABASE ${a(r)} OWNER ${a(n)}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = ${R(r)})\\gexec`,...I.flatMap((u)=>[...L(u.username,u.password),...U(u)]),"TS_CLOUD_PG_EOF",...Me(e)]}let l=c?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock",o=(a)=>a.replace(/`/g,"``"),f=(a)=>a.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),E=(a)=>{let R=a.databases&&a.databases.length>0?a.databases:[r],L=a.access==="readonly"?"SELECT":"ALL PRIVILEGES",U=[`CREATE USER IF NOT EXISTS '${f(a.username)}'@'%' IDENTIFIED BY '${f(a.password)}';`,`CREATE USER IF NOT EXISTS '${f(a.username)}'@'localhost' IDENTIFIED BY '${f(a.password)}';`,`ALTER USER '${f(a.username)}'@'%' IDENTIFIED BY '${f(a.password)}';`,`ALTER USER '${f(a.username)}'@'localhost' IDENTIFIED BY '${f(a.password)}';`];for(let I of R)U.push(`GRANT ${L} ON \`${o(I)}\`.* TO '${f(a.username)}'@'%';`,`GRANT ${L} ON \`${o(I)}\`.* TO '${f(a.username)}'@'localhost';`);return U},p=e.users||[];return[yt(),`for i in $(seq 1 30); do mysqladmin --socket=${l} -u root ping 2>/dev/null | grep -q alive && break; sleep 2; done`,`mysql --socket=${l} -u root <<'TS_CLOUD_SQL_EOF'`,`CREATE DATABASE IF NOT EXISTS \`${o(r)}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`,...E({username:n,password:i}),...p.flatMap(E),"FLUSH PRIVILEGES;","TS_CLOUD_SQL_EOF"]}function Me(e){return[`${br(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 ac(e){if(!e?.name)return{};let t=e.engine==="singlestore",r=e.engine==="vitess",n=e.engine==="postgres"?"pgsql":t?"singlestore":r?"vitess":"mysql",i=e.port??(e.engine==="postgres"?5432:r?15306:3306),s={DB_CONNECTION:n,DB_HOST:e.host||"127.0.0.1",DB_PORT:String(i),DB_DATABASE:e.name};if(e.username)s.DB_USERNAME=e.username;if(e.password)s.DB_PASSWORD=e.password;if((t||r)&&e.ssl!==!1)s.DB_SSL="true";return s}var Z="/var/backups/ts-cloud",Ve="/etc/ts-cloud/backups.config.ts",le="/etc/cron.d/ts-cloud-backups",Zr="/usr/local/bin/ts-cloud-backup.sh";function we(e){if(!e.name)return null;let t=e.host||"127.0.0.1",r=e.engine==="postgres",n=r?"postgresql":"mysql",i=e.port??(r?5432:3306),s=(c)=>c.replace(/\\/g,"\\\\").replace(/'/g,"\\'");return[" {",` type: '${n}',`,` name: '${s(e.name)}',`," connection: {",` hostname: '${s(t)}',`,` port: ${i},`,` database: '${s(e.name)}',`,` username: '${s(e.username||e.name)}',`,` password: '${s(e.password||"")}',`," ssl: false,"," },"," includeSchema: true,"," includeData: true,"," },"].join(`
6
+ `)}function oe(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_VITESS_UNIT_EOF'`,t,"TS_CLOUD_VITESS_UNIT_EOF"]}function Re(e){let t=e.cell??"zone1",r=e.vtgatePort??W,i=`${((e.keyspaces?.length)?e.keyspaces:[{name:"app"}]).map((s)=>{let c=(s.sharded?["-80","80-"]:["0"]).map((d)=>`shards:{name:"${d}"}`).join(" ");return`keyspaces:{name:"${s.name}" ${c}}`}).join(" ")} cells:"${t}"`;return A({description:"Vitess (vtcombo, single-process development stack)",execStart:D("vtcombo",[`${g}/vtcombo`,`--cell ${t}`,`--proto-topo ${m(i)}`,`--mysql-server-port ${r}`,"--mysql-server-bind-address 127.0.0.1","--mysql-auth-server-impl none","--start-mysql",`--port ${Y}`,`--grpc-port ${V}`])})}function De(){return A({description:"etcd (Vitess topology store)",execStart:D("etcd",[`${g}/etcd`,`--data-dir ${v}/etcd`,`--listen-client-urls http://127.0.0.1:${w}`,`--advertise-client-urls http://127.0.0.1:${w}`]),execStartPre:[`+/bin/mkdir -p ${v}/etcd`,`+/bin/chown ${_}:${_} ${v}/etcd`]})}function J(e){return["--topo-implementation etcd2",`--topo-global-server-address ${e.etcdEndpoint??`http://127.0.0.1:${w}`}`,"--topo-global-root /vitess/global"]}function Ae(e){let t=!e.etcdEndpoint;return A({description:"Vitess vtctld (control plane)",after:t?["vitess-etcd.service"]:[],requires:t?["vitess-etcd.service"]:[],execStart:D("vtctld",[`${g}/vtctld`,...J(e),`--cell ${e.cell??"zone1"}`,"--service-map grpc-vtctl,grpc-vtctld",`--grpc-port ${V}`,`--port ${V+1}`])})}function Le(e,t,r){let n=e.cell??"zone1";return A({description:`Vitess vttablet (${t}/${r})`,after:["vitess-vtctld.service","vitess-mysqlctld.service"],requires:["vitess-mysqlctld.service"],execStart:D("vttablet",[`${g}/vttablet`,...J(e),`--tablet-path ${n}-${String(X).padStart(10,"0")}`,`--init-keyspace ${t}`,`--init-shard ${r}`,"--init-tablet-type replica",`--service-map ${m("grpc-queryservice,grpc-tabletmanager,grpc-updatestream")}`,`--port ${ne}`,`--grpc-port ${ne+1}`,`--db-port ${e.mysqlPort??3306}`,`--mycnf-mysql-port ${e.mysqlPort??3306}`])})}function Oe(e){return A({description:"Vitess mysqlctld (managed mysqld)",execStart:D("mysqlctld",[`${g}/mysqlctld`,`--tablet-uid ${X}`,`--mysql-port ${e.mysqlPort??3306}`,'--init-db-sql-file "$VTROOT/config/init_db.sql"',"--wait-time 2m"]),execStartPre:[`+/bin/mkdir -p ${v}`,`+/bin/chown ${_}:${_} ${v}`]})}var ce="/etc/vitess/auth.json",x="/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 ${x} ] && [ "$(cat ${x})" = "$VTESS_VTGATE_AUTH_SHA" ]; then VTESS_VTGATE_AUTH_CHANGED=0; fi`,`install -o ${_} -g ${_} -m 0600 "$VTESS_AUTH_TMP" ${ce}`,'rm -f "$VTESS_AUTH_TMP"']}function Ue(e){let t=e.cell??"zone1";return A({description:"Vitess vtgate (query router)",after:["vitess-vtctld.service"],execStart:D("vtgate",[`${g}/vtgate`,...J(e),`--cell ${t}`,`--cells-to-watch ${t}`,"--tablet-types-to-wait PRIMARY,REPLICA",`--service-map ${m("grpc-vtgateservice")}`,`--mysql-server-port ${e.vtgatePort??W}`,`--mysql-server-bind-address ${e.bindAddress??"127.0.0.1"}`,"--mysql-auth-server-impl static",`--mysql-auth-server-static-file ${ce}`,`--port ${Y}`,`--grpc-port ${Y+1}`])})}function Ie(e){let t=e.cell??"zone1",r=e.etcdEndpoint??`http://127.0.0.1:${w}`,n=`${g}/vtctldclient --server 127.0.0.1:${V}`,i=[`for i in $(seq 1 30); do ${n} GetCellInfoNames >/dev/null 2>&1 && break; sleep 2; done`,`if ! ${n} GetCellInfoNames 2>/dev/null | grep -qx ${m(t)}; then`,` ${n} AddCellInfo --root ${m(`/vitess/${t}`)} --server-address ${m(r)} ${m(t)}`,"fi"];for(let s of e.keyspaces??[]){let c=s.sharded?" --sharded":"";i.push(`if ! ${n} GetKeyspace ${m(s.name)} >/dev/null 2>&1; then`,` ${n} CreateKeyspace${c} ${m(s.name)}`,"fi");let d=`${t}-${String(X).padStart(10,"0")}`;for(let l of s.sharded?["-80","80-"]:["0"]){let o=`${s.name}/${l}`;i.push("for i in $(seq 1 90); do",` if ${n} GetShard ${m(o)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then break; fi`,` ${n} PlannedReparentShard ${m(o)} --new-primary ${m(d)} >/dev/null 2>&1 && break`,` ${n} InitShardPrimary --force ${m(o)} ${m(d)} >/dev/null 2>&1 && break`," sleep 2","done",`if ! ${n} GetShard ${m(o)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then`,` echo "no primary could be elected for ${o}" >&2; exit 1`,"fi")}i.push(`${n} RebuildKeyspaceGraph ${m(s.name)} >/dev/null`)}return i}function ie(e){let t=e.vtgatePort??W;return["for i in $(seq 1 60); do",` if (cd ${M} && eval "$(pantry env 2>/dev/null)"; MYSQL_PWD=${m(e.password??"")} ${g}/mysql -h 127.0.0.1 -P ${t} -u ${m(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 ho(e){if(!ci(e))return[];let t=Ee(e),r=t.mode==="combo";Q.clear();let n=['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",...Ze(Pe(t)),`VT_MYSQL_LIB="$(dirname "$(dirname "$(readlink -f ${g}/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 ${_} >/dev/null 2>&1 || useradd --system --home-dir ${v} --shell /usr/sbin/nologin ${_}`,`mkdir -p ${v}`,`chown -R ${_}:${_} ${v}`];if(r)return n.push(...oe("vitess-vtcombo",Re(t)),...se(),"systemctl daemon-reload","systemctl enable --now vitess-vtcombo.service",...ie(t)),n;n.push(...xe(t));let i=[];if(!t.etcdEndpoint)i.push(["vitess-etcd",De()]);i.push(["vitess-vtctld",Ae(t)],["vitess-mysqlctld",Oe(t)],["vitess-vtgate",Ue(t)]);for(let s of t.keyspaces??[])for(let c of s.sharded?["-80","80-"]:["0"])i.push([`vitess-vttablet-${s.name}-${c.replace(/-/g,"x")}`,Le(t,s.name,c)]);for(let[s,c]of i)n.push(...oe(s,c));n.push(...se()),n.push("systemctl daemon-reload");for(let[s]of i)n.push(`systemctl enable --now ${s}.service`);return n.push(`if [ "$VTESS_VTGATE_AUTH_CHANGED" = 1 ]; then systemctl restart vitess-vtgate.service; printf '%s\\n' "$VTESS_VTGATE_AUTH_SHA" > ${x}; chown ${_}:${_} ${x}; chmod 0600 ${x}; fi`,...Ie(t),...ie(t)),n}var ke=new Set(["singlestore","vitess"]);function li(e){if(e?.engine&&ke.has(e.engine))return!1;return!e?.host||e.host==="127.0.0.1"||e.host==="localhost"}function vr(e,t="psql"){let r=e?.port??5432;if(li(e))return`${t} -p ${r} -U postgres`;let n=e?.username||"postgres";return`${e?.password?`PGPASSWORD='${e.password.replace(/'/g,"'\\''")}' `:""}${t} -h ${e.host} -p ${r} -U ${n} -w`}function y(e){return e===!0||typeof e==="object"&&e!=null}function Ne(e){let t=[],r=[];if(y(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(y(e.mariadb))t.push(O.mariadb),r.push("mariadb");if(y(e.postgres))t.push("postgresql.org"),r.push("postgres");if(y(e.redis))t.push("redis.io"),r.push("redis");if(y(e.memcached))t.push("memcached.org"),r.push("memcached");if(y(e.meilisearch))t.push("meilisearch.com"),r.push("meilisearch");return{packages:t,services:r}}function yo(e={},t={}){let r=Ne(e),n=ho(e.vitess),i=t.mail?re(t.mail):[];if(r.packages.length===0)return[...n,...i];return[...Ze(r.packages),...fo(r.services),...n,...i]}function bt(e,t={}){if(!e?.name)return[];if(!li(e))return[];let r=e.name,n=e.username||r,i=e.password||"",s=y(t.postgres)||e.engine==="postgres",c=y(t.mariadb)||e.engine==="mariadb",d=y(t.mysql)||e.engine==="mysql";if(s&&!d&&!c){let a=(u)=>`"${u.replace(/"/g,'""')}"`,R=(u)=>`'${u.replace(/'/g,"''")}'`,L=(u,k)=>["DO $$ BEGIN",` IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${R(u)}) THEN`,` CREATE ROLE ${a(u)} LOGIN PASSWORD ${R(k)};`," ELSE",` ALTER ROLE ${a(u)} LOGIN PASSWORD ${R(k)};`," END IF;","END $$;"],U=(u)=>{let k=u.databases&&u.databases.length>0?u.databases:[r],B=[];for(let H of k)if(u.access==="readonly")B.push(`GRANT CONNECT ON DATABASE ${a(H)} TO ${a(u.username)};`,`\\connect ${a(H)}`,`GRANT USAGE ON SCHEMA public TO ${a(u.username)};`,`GRANT SELECT ON ALL TABLES IN SCHEMA public TO ${a(u.username)};`,`ALTER DEFAULT PRIVILEGES FOR ROLE ${a(n)} IN SCHEMA public GRANT SELECT ON TABLES TO ${a(u.username)};`,"\\connect postgres");else B.push(`GRANT ALL PRIVILEGES ON DATABASE ${a(H)} TO ${a(u.username)};`);return B},I=e.users||[],me=e.port??5432;return[St(),`for i in $(seq 1 30); do pg_isready -p ${me} -q && break; sleep 2; done`,`${vr(e)} <<'TS_CLOUD_PG_EOF'`,...L(n,i),`SELECT 'CREATE DATABASE ${a(r)} OWNER ${a(n)}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = ${R(r)})\\gexec`,...I.flatMap((u)=>[...L(u.username,u.password),...U(u)]),"TS_CLOUD_PG_EOF",...Me(e)]}let l=c?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock",o=(a)=>a.replace(/`/g,"``"),f=(a)=>a.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),E=(a)=>{let R=a.databases&&a.databases.length>0?a.databases:[r],L=a.access==="readonly"?"SELECT":"ALL PRIVILEGES",U=[`CREATE USER IF NOT EXISTS '${f(a.username)}'@'%' IDENTIFIED BY '${f(a.password)}';`,`CREATE USER IF NOT EXISTS '${f(a.username)}'@'localhost' IDENTIFIED BY '${f(a.password)}';`,`ALTER USER '${f(a.username)}'@'%' IDENTIFIED BY '${f(a.password)}';`,`ALTER USER '${f(a.username)}'@'localhost' IDENTIFIED BY '${f(a.password)}';`];for(let I of R)U.push(`GRANT ${L} ON \`${o(I)}\`.* TO '${f(a.username)}'@'%';`,`GRANT ${L} ON \`${o(I)}\`.* TO '${f(a.username)}'@'localhost';`);return U},p=e.users||[];return[St(),`for i in $(seq 1 30); do mysqladmin --socket=${l} -u root ping 2>/dev/null | grep -q alive && break; sleep 2; done`,`mysql --socket=${l} -u root <<'TS_CLOUD_SQL_EOF'`,`CREATE DATABASE IF NOT EXISTS \`${o(r)}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`,...E({username:n,password:i}),...p.flatMap(E),"FLUSH PRIVILEGES;","TS_CLOUD_SQL_EOF"]}function Me(e){return[`${vr(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 lc(e){if(!e?.name)return{};let t=e.engine==="singlestore",r=e.engine==="vitess",n=e.engine==="postgres"?"pgsql":t?"singlestore":r?"vitess":"mysql",i=e.port??(e.engine==="postgres"?5432:r?15306:3306),s={DB_CONNECTION:n,DB_HOST:e.host||"127.0.0.1",DB_PORT:String(i),DB_DATABASE:e.name};if(e.username)s.DB_USERNAME=e.username;if(e.password)s.DB_PASSWORD=e.password;if((t||r)&&e.ssl!==!1)s.DB_SSL="true";return s}var Z="/var/backups/ts-cloud",Ve="/etc/ts-cloud/backups.config.ts",le="/etc/cron.d/ts-cloud-backups",en="/usr/local/bin/ts-cloud-backup.sh";function we(e){if(!e.name)return null;let t=e.host||"127.0.0.1",r=e.engine==="postgres",n=r?"postgresql":"mysql",i=e.port??(r?5432:3306),s=(c)=>c.replace(/\\/g,"\\\\").replace(/'/g,"\\'");return[" {",` type: '${n}',`,` name: '${s(e.name)}',`," connection: {",` hostname: '${s(t)}',`,` port: ${i},`,` database: '${s(e.name)}',`,` username: '${s(e.username||e.name)}',`,` password: '${s(e.password||"")}',`," ssl: false,"," },"," includeSchema: true,"," includeData: true,"," },"].join(`
7
7
  `)}function Be(e,t){let r=e?we(e):null,n=t.bucket?[" destinations: ["," {"," type: 's3',",` bucket: '${t.bucket}',`," prefix: 'db-backups',",...t.endpoint?[` endpoint: '${t.endpoint}',`]:[]," optional: false,"," },"," ],"]:[];return["import type { BackupConfig } from 'ts-backups'","","const config: BackupConfig = {"," verbose: true,",` outputPath: '${Z}',`," retention: {",` count: ${t.retentionCount??5},`,` maxAge: ${t.retentionDays??30},`," },"," databases: [",...r?[r]:[]," ],",...n,"}","","export default config",""].join(`
8
- `)}function yo(e){let{database:t,backups:r}=e;if(!r.enabled)return[];let n=r.schedule||"0 2 * * *",i=Be(t,r);return["export DEBIAN_FRONTEND=noninteractive",`mkdir -p /etc/ts-cloud ${Z}`,"command -v bun >/dev/null 2>&1 || (curl -fsSL https://bun.sh/install | bash && ln -sf /root/.bun/bin/bun /usr/local/bin/bun)","bun add -g ts-backups || true",`cat > ${Ve} <<'TS_CLOUD_BACKUP_CFG_EOF'`,i.replace(/\n$/,""),"TS_CLOUD_BACKUP_CFG_EOF",`cat > ${Zr} <<'TS_CLOUD_BACKUP_RUN_EOF'`,"#!/bin/bash","set -uo pipefail",'export PATH="/root/.bun/bin:/usr/local/bin:$PATH"','notify() { [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "$1" || true; }',"cd /etc/ts-cloud",'if ! ts-backups backup --config /etc/ts-cloud/backups.config.ts; then notify "❌ ts-cloud backup failed"; exit 1; fi',"TS_CLOUD_BACKUP_RUN_EOF",`chmod +x ${Zr}`,`cat > ${le} <<'TS_CLOUD_BACKUP_CRON_EOF'`,`${n} root ${Zr} >> /var/log/ts-cloud-backup.log 2>&1`,"TS_CLOUD_BACKUP_CRON_EOF",`chmod 644 ${le}`]}function He(e){return e==="mariadb"?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock"}function li(e,t={}){if(!e?.name)return[];let r=e.name,n=e.engine==="postgres",i=t.from?`TS_CLOUD_DUMP="${t.from}"`:`TS_CLOUD_DUMP="$(find ${Z} -type f -name '*${r}*.sql' -o -type f -name '*${r}*.sql.gz' 2>/dev/null | xargs -r ls -1t 2>/dev/null | head -1)"`,s=n?`${br(e)} -d "${r}"`:`mysql --socket=${He(e.engine)} -u root "${r}"`;return["set -uo pipefail",'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true',i,'[ -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 | ${s}`,'echo "restore complete"']}var So=["storage",".env"],di=4;function C(e){return`${e.replace(/\/+$/,"")}/.ts-cloud`}function xs(e){return`${C(e)}/deploy-history.log`}function qe(e,t){return`${C(e)}/deploys/${t}.log`}function ue(e){return`${C(e)}/shared-paths`}function bo(e){return`${e.shared}/stx-images`}function Bt(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 $s(e){return typeof e==="string"?e:e.path}function cc(e){let t=new Map;for(let r of e)t.set($s(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 ui(e,t=So){let r=[`mkdir -p ${e.releases} ${e.shared} ${bo(e)}`,...Fe(e)],n=t.map((s)=>$e(e,s));for(let{path:s,target:c,seed:d}of n){if(!d)continue;if(r.push(`ts_cloud_adopt_shared '${s}' '${c}'`),de(s))r.push(`mkdir -p "$(dirname ${c})"`,`touch ${c}`);else if(s==="storage")r.push(`mkdir -p ${c}/app/public`,`mkdir -p ${c}/framework/cache/data`,`mkdir -p ${c}/framework/sessions`,`mkdir -p ${c}/framework/testing`,`mkdir -p ${c}/framework/views`,`mkdir -p ${c}/logs`);else r.push(`mkdir -p ${c}`)}let i=ue(e.base);return r.push(`mkdir -p ${C(e.base)}`,`cat > ${i} <<'TS_CLOUD_SHARED_PATHS_EOF'`,...n.map((s)=>`${s.path} ${s.target}`),"TS_CLOUD_SHARED_PATHS_EOF"),r}function Os(e,t=900){let r=`${C(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 Ls(e){let t=`${e.release}.incoming`;return[`rm -rf ${t}`,`mkdir -p ${t}`,...Ge(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 Ms(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 Ge(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 Us(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 vo(e,t=So){let r=[];for(let n of t){let{path:i,target:s,seed:c}=$e(e,n),d=`${e.release}/${i}`,l=[`rm -rf ${d}`,`mkdir -p "$(dirname ${d})"`,`ln -sfn ${s} ${d}`];if(c){if(i!==".env"&&de(i))r.push(...Ke(d,s));r.push(...l);continue}r.push(`if [ -e ${s} ]; then`,...l.map((o)=>` ${o}`),"fi")}return r}function pe(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 en(e){return[`ln -sfn ${e.release} ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`]}function lc(e,t={}){let r=t.to?[`[ -d ${e.releases}/${t.to} ] || { echo "rollback target ${e.releases}/${t.to} not found" >&2; exit 1; }`,...pe(e,`${e.releases}/${t.to}`),`ln -sfn ${e.releases}/${t.to} ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`]:[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,`TS_CLOUD_PREV=$(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_PREV" ] || { echo "no previous release to roll back to" >&2; exit 1; }',...pe(e,'"$TS_CLOUD_PREV"'),`ln -sfn "$TS_CLOUD_PREV" ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`,'echo "rolled back to $TS_CLOUD_PREV"'];if(!t.unitBase)return r;let n=t.unitBase;return[...r,`TS_CLOUD_RB_ID=$(basename "$(readlink -f ${e.current})")`,`if [ -f /etc/systemd/system/${n}@.service ]; then systemctl start "${n}@\${TS_CLOUD_RB_ID}.service"; sleep 2; systemctl is-active --quiet "${n}@\${TS_CLOUD_RB_ID}.service" || { echo "rolled-back release failed to start" >&2; exit 1; }; systemctl enable "${n}@\${TS_CLOUD_RB_ID}.service" 2>/dev/null || true; systemctl list-units --plain --no-legend --type=service "${n}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v "^${n}@\${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 /etc/systemd/system/${n}.service ]; then systemctl restart ${n}.service; fi`]}function tn(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`${C(e)}/owner`}function Bs(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 To(e,t){let r=C(e),n=qe(e,t.releaseId),i=xs(e),s=Math.max(1,t.keepLogs??20),c=t.commit||"",d=t.branch||"";return[`mkdir -p ${r}/deploys`,`exec > >(tee -a ${n}) 2>&1`,`echo "[ts-cloud] deploy ${t.releaseId} commit=${c} branch=${d} 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}" "${c}" "$TS_CLOUD_ST" "$TS_CLOUD_RC" >> ${i}`,"}","trap ts_cloud_record_deploy EXIT",`ls -1t ${r}/deploys/*.log 2>/dev/null | tail -n +${s+1} | while read -r TS_CLOUD_OLDLOG; do rm -f "$TS_CLOUD_OLDLOG"; done`]}
9
- export{G,si,Ds,P,mo,ks,_s,oc,sc,M,Sr,yt,Ye,go,ai,fo,ci,br,ho,St,ac,Zr,yo,li,So,di,xs,bo,Bt,$s,cc,ui,Os,Ls,Ms,Us,vo,en,lc,tn,Bs,To};
8
+ `)}function So(e){let{database:t,backups:r}=e;if(!r.enabled)return[];let n=r.schedule||"0 2 * * *",i=Be(t,r);return["export DEBIAN_FRONTEND=noninteractive",`mkdir -p /etc/ts-cloud ${Z}`,"command -v bun >/dev/null 2>&1 || (curl -fsSL https://bun.sh/install | bash && ln -sf /root/.bun/bin/bun /usr/local/bin/bun)","bun add -g ts-backups || true",`cat > ${Ve} <<'TS_CLOUD_BACKUP_CFG_EOF'`,i.replace(/\n$/,""),"TS_CLOUD_BACKUP_CFG_EOF",`cat > ${en} <<'TS_CLOUD_BACKUP_RUN_EOF'`,"#!/bin/bash","set -uo pipefail",'export PATH="/root/.bun/bin:/usr/local/bin:$PATH"','notify() { [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "$1" || true; }',"cd /etc/ts-cloud",'if ! ts-backups backup --config /etc/ts-cloud/backups.config.ts; then notify "❌ ts-cloud backup failed"; exit 1; fi',"TS_CLOUD_BACKUP_RUN_EOF",`chmod +x ${en}`,`cat > ${le} <<'TS_CLOUD_BACKUP_CRON_EOF'`,`${n} root ${en} >> /var/log/ts-cloud-backup.log 2>&1`,"TS_CLOUD_BACKUP_CRON_EOF",`chmod 644 ${le}`]}function He(e){return e==="mariadb"?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock"}function di(e,t={}){if(!e?.name)return[];let r=e.name,n=e.engine==="postgres",i=t.from?`TS_CLOUD_DUMP="${t.from}"`:`TS_CLOUD_DUMP="$(find ${Z} -type f -name '*${r}*.sql' -o -type f -name '*${r}*.sql.gz' 2>/dev/null | xargs -r ls -1t 2>/dev/null | head -1)"`,s=n?`${vr(e)} -d "${r}"`:`mysql --socket=${He(e.engine)} -u root "${r}"`;return["set -uo pipefail",'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true',i,'[ -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 | ${s}`,'echo "restore complete"']}var bo=["storage",".env"],ui=4;function C(e){return`${e.replace(/\/+$/,"")}/.ts-cloud`}function Os(e){return`${C(e)}/deploy-history.log`}function qe(e,t){return`${C(e)}/deploys/${t}.log`}function ue(e){return`${C(e)}/shared-paths`}function vo(e){return`${e.shared}/stx-images`}function Bt(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 Ls(e){return typeof e==="string"?e:e.path}function dc(e){let t=new Map;for(let r of e)t.set(Ls(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 pi(e,t=bo){let r=[`mkdir -p ${e.releases} ${e.shared} ${vo(e)}`,...Fe(e)],n=t.map((s)=>$e(e,s));for(let{path:s,target:c,seed:d}of n){if(!d)continue;if(r.push(`ts_cloud_adopt_shared '${s}' '${c}'`),de(s))r.push(`mkdir -p "$(dirname ${c})"`,`touch ${c}`);else if(s==="storage")r.push(`mkdir -p ${c}/app/public`,`mkdir -p ${c}/framework/cache/data`,`mkdir -p ${c}/framework/sessions`,`mkdir -p ${c}/framework/testing`,`mkdir -p ${c}/framework/views`,`mkdir -p ${c}/logs`);else r.push(`mkdir -p ${c}`)}let i=ue(e.base);return r.push(`mkdir -p ${C(e.base)}`,`cat > ${i} <<'TS_CLOUD_SHARED_PATHS_EOF'`,...n.map((s)=>`${s.path} ${s.target}`),"TS_CLOUD_SHARED_PATHS_EOF"),r}function Ms(e,t=900){let r=`${C(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 Us(e){let t=`${e.release}.incoming`;return[`rm -rf ${t}`,`mkdir -p ${t}`,...Ge(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 Bs(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 Ge(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 Fs(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 To(e,t=bo){let r=[];for(let n of t){let{path:i,target:s,seed:c}=$e(e,n),d=`${e.release}/${i}`,l=[`rm -rf ${d}`,`mkdir -p "$(dirname ${d})"`,`ln -sfn ${s} ${d}`];if(c){if(i!==".env"&&de(i))r.push(...Ye(d,s));r.push(...l);continue}r.push(`if [ -e ${s} ]; then`,...l.map((o)=>` ${o}`),"fi")}return r}function pe(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 tn(e){return[`ln -sfn ${e.release} ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`]}function uc(e,t={}){let r=t.to?[`[ -d ${e.releases}/${t.to} ] || { echo "rollback target ${e.releases}/${t.to} not found" >&2; exit 1; }`,...pe(e,`${e.releases}/${t.to}`),`ln -sfn ${e.releases}/${t.to} ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`]:[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,`TS_CLOUD_PREV=$(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_PREV" ] || { echo "no previous release to roll back to" >&2; exit 1; }',...pe(e,'"$TS_CLOUD_PREV"'),`ln -sfn "$TS_CLOUD_PREV" ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`,'echo "rolled back to $TS_CLOUD_PREV"'];if(!t.unitBase)return r;let n=t.unitBase;return[...r,`TS_CLOUD_RB_ID=$(basename "$(readlink -f ${e.current})")`,`if [ -f /etc/systemd/system/${n}@.service ]; then systemctl start "${n}@\${TS_CLOUD_RB_ID}.service"; sleep 2; systemctl is-active --quiet "${n}@\${TS_CLOUD_RB_ID}.service" || { echo "rolled-back release failed to start" >&2; exit 1; }; systemctl enable "${n}@\${TS_CLOUD_RB_ID}.service" 2>/dev/null || true; systemctl list-units --plain --no-legend --type=service "${n}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v "^${n}@\${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 /etc/systemd/system/${n}.service ]; then systemctl restart ${n}.service; fi`]}function rn(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 Ke(e){return`${C(e)}/owner`}function js(e,t){let r=Ke(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 Eo(e,t){let r=C(e),n=qe(e,t.releaseId),i=Os(e),s=Math.max(1,t.keepLogs??20),c=t.commit||"",d=t.branch||"";return[`mkdir -p ${r}/deploys`,`exec > >(tee -a ${n}) 2>&1`,`echo "[ts-cloud] deploy ${t.releaseId} commit=${c} branch=${d} 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}" "${c}" "$TS_CLOUD_ST" "$TS_CLOUD_RC" >> ${i}`,"}","trap ts_cloud_record_deploy EXIT",`ls -1t ${r}/deploys/*.log 2>/dev/null | tail -n +${s+1} | while read -r TS_CLOUD_OLDLOG; do rm -f "$TS_CLOUD_OLDLOG"; done`]}
9
+ export{K,ai,_s,P,go,xs,$s,ac,cc,M,br,St,Ze,fo,ci,ho,li,vr,yo,bt,lc,en,So,di,bo,ui,Os,vo,Bt,Ls,dc,pi,Ms,Us,Bs,Fs,To,tn,uc,rn,js,Eo};
@@ -0,0 +1 @@
1
+ import{zu,Hu,qu,Wu}from"./chunk-5x59x4qw.js";import"./chunk-2q27v6vz.js";import"./chunk-q3xwh0r8.js";import"./chunk-jdfbahjb.js";export{Wu as deleteFailoverReplicaBuckets,zu as ensureFailoverReplicaBuckets,Hu as grantFailoverReplicaAccess,qu as seedFailoverReplicas};
@@ -0,0 +1 @@
1
+ import{g}from"./chunk-2q27v6vz.js";import"./chunk-q3xwh0r8.js";export{g as S3Client};
@@ -0,0 +1 @@
1
+ import{Gu,Xr,Hi,oe,Ku,Fa,nd,ns,Ju,Xu,Qu,ja,qi,is,Va,Qr,gr,Yu,ti,Zu,za,id,od,os,Ha,qa,fr,Wi,hr,Wa,ss,ri,sd,Gi,Ga,Ka,Ki,ad,Ja,Xa,Qa,Ya,as,cd,ld,ep,dd,Za,Ji,ud,pd,cs,xt,ls,ds,us,ec,md,tc,ps,tp,ft,rp,rc,$t,nc,np,ic,gd,ip,Y,fd,ms,op,Xi,ni,ii,gs,hd,yd,sp,fs,hs}from"./chunk-hjv1k8s9.js";import"./chunk-257sygzm.js";import"./chunk-jdfbahjb.js";export{cs as AnomalyConfigStore,hd as AwsSpendTransport,yd as ComputeSpendTransport,os as CounterTracker,za as DEFAULT_METER_MAPPINGS,ja as DEFAULT_PRICE_BOOK,Wi as DEFAULT_THRESHOLDS,xt as DETECTABLE_SIGNALS,Hi as ENFORCEMENT_ACTIONS,Ki as ENFORCEMENT_DESCRIPTIONS,oe as ENFORCEMENT_SEVERITY,md as FOCUS_VERSION,Xr as METERS,Gu as METER_KEYS,Ku as MICRO_CENTS,sd as MIN_PROJECTION_CONFIDENCE,gd as RecordingSpendTransport,ud as SENSITIVITY_THRESHOLDS,ii as SPEND_CYCLE_SECONDS,rc as SPEND_GATE_SETTING,op as SPEND_LEASE_SETTING,ds as SignalSource,nc as SpendCapError,$t as SpendGate,Xi as SpendLoopLease,ms as SpendNotificationRouter,ni as SpendRunner,ft as SpendService,hr as SpendStore,ip as URGENT_SPEND_EVENTS,ad as USER_VISIBLE_ACTIONS,qa as aggregateDeltas,Ji as anomalyOptionsForSignal,np as assertSpendAllows,gr as budgetWindow,sp as compositeSpendTransport,ic as createEnforcementHandlers,dd as detectAnomalies,Za as detectLatestAnomaly,Ga as evaluateBudget,ep as ewma,id as findMapping,nd as findPriceEntry,Y as formatCents,ri as formatTimeToExhaustion,Gi as governingLimitCents,fs as handleSpendRequest,ti as hourBucket,Zu as hourBucketsBetween,Ya as isOperationAllowed,qi as isValidTimeZone,ec as lookbackHoursForSignal,as as median,cd as medianAbsoluteDeviation,Ka as mergeDecisions,Qu as mergePriceBooks,Ha as meterTelemetry,us as optionsForSignal,ss as percentOfLimit,Ja as planEnforcement,Yu as previousBudgetWindow,ns as priceUsage,Ju as priceUsageLines,Wa as projectSpend,ld as robustZScore,Xu as roundCents,pd as routeMatches,Xa as runEnforcement,fr as scopeKey,ls as signalDefinition,fd as spendNotificationText,hs as spendOpenApiPaths,gs as startSpendLoop,tp as streamFocusJsonl,Qa as strongestActiveAction,Fa as tieredMicroCents,ps as toFocusJsonl,tc as toFocusRecords,od as usageDeltaKey,Qr as utcInstantOfLocal,rp as zeroFill,Va as zoneOffsetMs,is as zonedParts};
@@ -1,2 +1,2 @@
1
- import{u}from"./chunk-mbqwrs7a.js";import{deflateRawSync as y}from"zlib";function d(n,e){let t=typeof e==="string"?Buffer.from(e,"utf-8"):e,i=y(t),r=f(t),s=new Date,l=(s.getHours()<<11|s.getMinutes()<<5|s.getSeconds()>>1)&65535,c=(s.getFullYear()-1980<<9|s.getMonth()+1<<5|s.getDate())&65535,m=Buffer.from(n,"utf-8"),a=Buffer.alloc(30+m.length);a.writeUInt32LE(67324752,0),a.writeUInt16LE(20,4),a.writeUInt16LE(0,6),a.writeUInt16LE(8,8),a.writeUInt16LE(l,10),a.writeUInt16LE(c,12),a.writeUInt32LE(r,14),a.writeUInt32LE(i.length,18),a.writeUInt32LE(t.length,22),a.writeUInt16LE(m.length,26),a.writeUInt16LE(0,28),m.copy(a,30);let o=Buffer.alloc(46+m.length);o.writeUInt32LE(33639248,0),o.writeUInt16LE(20,4),o.writeUInt16LE(20,6),o.writeUInt16LE(0,8),o.writeUInt16LE(8,10),o.writeUInt16LE(l,12),o.writeUInt16LE(c,14),o.writeUInt32LE(r,16),o.writeUInt32LE(i.length,20),o.writeUInt32LE(t.length,24),o.writeUInt16LE(m.length,28),o.writeUInt16LE(0,30),o.writeUInt16LE(0,32),o.writeUInt16LE(0,34),o.writeUInt16LE(0,36),o.writeUInt32LE(0,38),o.writeUInt32LE(0,42),m.copy(o,46);let p=a.length+i.length,h=o.length,g=Buffer.alloc(22);return g.writeUInt32LE(101010256,0),g.writeUInt16LE(0,4),g.writeUInt16LE(0,6),g.writeUInt16LE(1,8),g.writeUInt16LE(1,10),g.writeUInt32LE(h,12),g.writeUInt32LE(p,16),g.writeUInt16LE(0,20),Buffer.concat([a,i,o,g])}function f(n){let e=[];for(let i=0;i<256;i++){let r=i;for(let s=0;s<8;s++)r=r&1?3988292384^r>>>1:r>>>1;e[i]=r}let t=4294967295;for(let i=0;i<n.length;i++)t=e[(t^n[i])&255]^t>>>8;return(t^4294967295)>>>0}class R{client;region;constructor(n="us-east-1",e){this.region=n,this.client=new u(void 0,{profile:e})}async createFunction(n){return await this.client.request({service:"lambda",region:this.region,method:"POST",path:"/2015-03-31/functions",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})}async getFunction(n){return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2015-03-31/functions/${encodeURIComponent(n)}`,headers:{"Content-Type":"application/json"}})}async updateFunctionCode(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/code`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async updateFunctionCodeInline(n,e,t="index.js"){let i=d(t,e);return this.updateFunctionCode({FunctionName:n,ZipFile:i.toString("base64")})}async updateFunctionConfiguration(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/configuration`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async deleteFunction(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2015-03-31/functions/${encodeURIComponent(n)}`,headers:{"Content-Type":"application/json"}})}async invoke(n){let{FunctionName:e,InvocationType:t="RequestResponse",Payload:i,LogType:r}=n,s={"Content-Type":"application/json","X-Amz-Invocation-Type":t};if(r)s["X-Amz-Log-Type"]=r;let l=i?typeof i==="string"?i:JSON.stringify(i):void 0,c=await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/invocations`,headers:s,body:l,returnHeaders:!0});return{StatusCode:c.statusCode||200,FunctionError:c.headers?.["x-amz-function-error"],LogResult:c.headers?.["x-amz-log-result"],Payload:typeof c.body==="string"?c.body:JSON.stringify(c.body),ExecutedVersion:c.headers?.["x-amz-executed-version"]}}async listFunctions(n){let e={};if(n?.MaxItems)e.MaxItems=String(n.MaxItems);if(n?.Marker)e.Marker=n.Marker;if(n?.FunctionVersion)e.FunctionVersion=n.FunctionVersion;return await this.client.request({service:"lambda",region:this.region,method:"GET",path:"/2015-03-31/functions",queryParams:Object.keys(e).length>0?e:void 0,headers:{"Content-Type":"application/json"}})}async addPermission(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/policy`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async removePermission(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2015-03-31/functions/${encodeURIComponent(n)}/policy/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async publishVersion(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/versions`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async createAlias(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/aliases`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async updateAlias(n){let{FunctionName:e,Name:t,...i}=n;return this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/aliases/${encodeURIComponent(t)}`,headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}async getAlias(n,e){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2015-03-31/functions/${encodeURIComponent(n)}/aliases/${encodeURIComponent(e)}`})}catch(t){if(/ResourceNotFound/i.test(String(t?.message)))return null;throw t}}async getProvisionedConcurrencyConfig(n,e){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2019-09-30/functions/${encodeURIComponent(n)}/provisioned-concurrency`,queryParams:{Qualifier:e}})}catch(t){if(/ProvisionedConcurrencyConfigNotFound|ResourceNotFound/i.test(String(t?.message)))return null;throw t}}async putProvisionedConcurrencyConfig(n){let{FunctionName:e,Qualifier:t,ProvisionedConcurrentExecutions:i}=n;return this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2019-09-30/functions/${encodeURIComponent(e)}/provisioned-concurrency`,queryParams:{Qualifier:t},headers:{"Content-Type":"application/json"},body:JSON.stringify({ProvisionedConcurrentExecutions:i})})}async getFunctionConcurrency(n){try{return(await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`}))?.ReservedConcurrentExecutions??null}catch(e){if(/ResourceNotFound|ProvisionedConcurrencyConfigNotFound/i.test(String(e?.message)))return null;throw e}}async putFunctionConcurrency(n,e){await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`,headers:{"Content-Type":"application/json"},body:JSON.stringify({ReservedConcurrentExecutions:e})})}async deleteFunctionConcurrency(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`})}async deleteProvisionedConcurrencyConfig(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2019-09-30/functions/${encodeURIComponent(n)}/provisioned-concurrency`,queryParams:{Qualifier:e}})}async waitForFunctionActive(n,e=60){let t=Date.now(),i=e*1000;while(Date.now()-t<i)try{let r=await this.getFunction(n),s=r.Configuration?.State;if(s==="Active")return r.Configuration;if(s==="Failed")throw Error(`Function ${n} failed: ${r.Configuration?.StateReason}`);await new Promise((l)=>setTimeout(l,2000))}catch(r){if(r.code==="ResourceNotFoundException"){await new Promise((s)=>setTimeout(s,2000));continue}throw r}throw Error(`Timeout waiting for function ${n} to become active`)}async functionExists(n){try{return await this.getFunction(n),!0}catch(e){if(e.code==="ResourceNotFoundException"||e.statusCode===404)return!1;throw e}}async createFunctionUrl(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2021-10-31/functions/${encodeURIComponent(e)}/url`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async getFunctionUrl(n){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2021-10-31/functions/${encodeURIComponent(n)}/url`,headers:{"Content-Type":"application/json"}})}catch(e){if(e.statusCode===404)return null;throw e}}async deleteFunctionUrl(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2021-10-31/functions/${encodeURIComponent(n)}/url`,headers:{"Content-Type":"application/json"}})}async createFunctionWithCode(n){let{Code:e,Filename:t="index.js",...i}=n,r=d(t,e);return this.createFunction({...i,Code:{ZipFile:r.toString("base64")}})}async addFunctionUrlPermission(n){return this.addPermission({FunctionName:n,StatementId:"FunctionURLAllowPublicAccess",Action:"lambda:InvokeFunctionUrl",Principal:"*",FunctionUrlAuthType:"NONE"})}async publishLayerVersion(n){let{LayerName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2018-10-31/layers/${encodeURIComponent(e)}/versions`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async listLayerVersions(n,e){let t={};if(e?.CompatibleRuntime)t.CompatibleRuntime=e.CompatibleRuntime;if(e?.CompatibleArchitecture)t.CompatibleArchitecture=e.CompatibleArchitecture;if(e?.MaxItems)t.MaxItems=String(e.MaxItems);if(e?.Marker)t.Marker=e.Marker;return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions`,queryParams:Object.keys(t).length>0?t:void 0,headers:{"Content-Type":"application/json"}})}async getLayerVersion(n,e){return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions/${e}`,headers:{"Content-Type":"application/json"}})}async addLayerVersionPermission(n){let{LayerName:e,VersionNumber:t,...i}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2018-10-31/layers/${encodeURIComponent(e)}/versions/${t}/policy`,headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}async deleteLayerVersion(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions/${e}`,headers:{"Content-Type":"application/json"}})}}
1
+ import{u}from"./chunk-q3xwh0r8.js";import{deflateRawSync as y}from"zlib";function d(n,e){let t=typeof e==="string"?Buffer.from(e,"utf-8"):e,i=y(t),r=f(t),s=new Date,l=(s.getHours()<<11|s.getMinutes()<<5|s.getSeconds()>>1)&65535,c=(s.getFullYear()-1980<<9|s.getMonth()+1<<5|s.getDate())&65535,m=Buffer.from(n,"utf-8"),a=Buffer.alloc(30+m.length);a.writeUInt32LE(67324752,0),a.writeUInt16LE(20,4),a.writeUInt16LE(0,6),a.writeUInt16LE(8,8),a.writeUInt16LE(l,10),a.writeUInt16LE(c,12),a.writeUInt32LE(r,14),a.writeUInt32LE(i.length,18),a.writeUInt32LE(t.length,22),a.writeUInt16LE(m.length,26),a.writeUInt16LE(0,28),m.copy(a,30);let o=Buffer.alloc(46+m.length);o.writeUInt32LE(33639248,0),o.writeUInt16LE(20,4),o.writeUInt16LE(20,6),o.writeUInt16LE(0,8),o.writeUInt16LE(8,10),o.writeUInt16LE(l,12),o.writeUInt16LE(c,14),o.writeUInt32LE(r,16),o.writeUInt32LE(i.length,20),o.writeUInt32LE(t.length,24),o.writeUInt16LE(m.length,28),o.writeUInt16LE(0,30),o.writeUInt16LE(0,32),o.writeUInt16LE(0,34),o.writeUInt16LE(0,36),o.writeUInt32LE(0,38),o.writeUInt32LE(0,42),m.copy(o,46);let p=a.length+i.length,h=o.length,g=Buffer.alloc(22);return g.writeUInt32LE(101010256,0),g.writeUInt16LE(0,4),g.writeUInt16LE(0,6),g.writeUInt16LE(1,8),g.writeUInt16LE(1,10),g.writeUInt32LE(h,12),g.writeUInt32LE(p,16),g.writeUInt16LE(0,20),Buffer.concat([a,i,o,g])}function f(n){let e=[];for(let i=0;i<256;i++){let r=i;for(let s=0;s<8;s++)r=r&1?3988292384^r>>>1:r>>>1;e[i]=r}let t=4294967295;for(let i=0;i<n.length;i++)t=e[(t^n[i])&255]^t>>>8;return(t^4294967295)>>>0}class R{client;region;constructor(n="us-east-1",e){this.region=n,this.client=new u(void 0,{profile:e})}async createFunction(n){return await this.client.request({service:"lambda",region:this.region,method:"POST",path:"/2015-03-31/functions",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})}async getFunction(n){return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2015-03-31/functions/${encodeURIComponent(n)}`,headers:{"Content-Type":"application/json"}})}async updateFunctionCode(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/code`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async updateFunctionCodeInline(n,e,t="index.js"){let i=d(t,e);return this.updateFunctionCode({FunctionName:n,ZipFile:i.toString("base64")})}async updateFunctionConfiguration(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/configuration`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async deleteFunction(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2015-03-31/functions/${encodeURIComponent(n)}`,headers:{"Content-Type":"application/json"}})}async invoke(n){let{FunctionName:e,InvocationType:t="RequestResponse",Payload:i,LogType:r}=n,s={"Content-Type":"application/json","X-Amz-Invocation-Type":t};if(r)s["X-Amz-Log-Type"]=r;let l=i?typeof i==="string"?i:JSON.stringify(i):void 0,c=await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/invocations`,headers:s,body:l,returnHeaders:!0});return{StatusCode:c.statusCode||200,FunctionError:c.headers?.["x-amz-function-error"],LogResult:c.headers?.["x-amz-log-result"],Payload:typeof c.body==="string"?c.body:JSON.stringify(c.body),ExecutedVersion:c.headers?.["x-amz-executed-version"]}}async listFunctions(n){let e={};if(n?.MaxItems)e.MaxItems=String(n.MaxItems);if(n?.Marker)e.Marker=n.Marker;if(n?.FunctionVersion)e.FunctionVersion=n.FunctionVersion;return await this.client.request({service:"lambda",region:this.region,method:"GET",path:"/2015-03-31/functions",queryParams:Object.keys(e).length>0?e:void 0,headers:{"Content-Type":"application/json"}})}async addPermission(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/policy`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async removePermission(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2015-03-31/functions/${encodeURIComponent(n)}/policy/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async publishVersion(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/versions`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async createAlias(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/aliases`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async updateAlias(n){let{FunctionName:e,Name:t,...i}=n;return this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/aliases/${encodeURIComponent(t)}`,headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}async getAlias(n,e){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2015-03-31/functions/${encodeURIComponent(n)}/aliases/${encodeURIComponent(e)}`})}catch(t){if(/ResourceNotFound/i.test(String(t?.message)))return null;throw t}}async getProvisionedConcurrencyConfig(n,e){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2019-09-30/functions/${encodeURIComponent(n)}/provisioned-concurrency`,queryParams:{Qualifier:e}})}catch(t){if(/ProvisionedConcurrencyConfigNotFound|ResourceNotFound/i.test(String(t?.message)))return null;throw t}}async putProvisionedConcurrencyConfig(n){let{FunctionName:e,Qualifier:t,ProvisionedConcurrentExecutions:i}=n;return this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2019-09-30/functions/${encodeURIComponent(e)}/provisioned-concurrency`,queryParams:{Qualifier:t},headers:{"Content-Type":"application/json"},body:JSON.stringify({ProvisionedConcurrentExecutions:i})})}async getFunctionConcurrency(n){try{return(await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`}))?.ReservedConcurrentExecutions??null}catch(e){if(/ResourceNotFound|ProvisionedConcurrencyConfigNotFound/i.test(String(e?.message)))return null;throw e}}async putFunctionConcurrency(n,e){await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`,headers:{"Content-Type":"application/json"},body:JSON.stringify({ReservedConcurrentExecutions:e})})}async deleteFunctionConcurrency(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`})}async deleteProvisionedConcurrencyConfig(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2019-09-30/functions/${encodeURIComponent(n)}/provisioned-concurrency`,queryParams:{Qualifier:e}})}async waitForFunctionActive(n,e=60){let t=Date.now(),i=e*1000;while(Date.now()-t<i)try{let r=await this.getFunction(n),s=r.Configuration?.State;if(s==="Active")return r.Configuration;if(s==="Failed")throw Error(`Function ${n} failed: ${r.Configuration?.StateReason}`);await new Promise((l)=>setTimeout(l,2000))}catch(r){if(r.code==="ResourceNotFoundException"){await new Promise((s)=>setTimeout(s,2000));continue}throw r}throw Error(`Timeout waiting for function ${n} to become active`)}async functionExists(n){try{return await this.getFunction(n),!0}catch(e){if(e.code==="ResourceNotFoundException"||e.statusCode===404)return!1;throw e}}async createFunctionUrl(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2021-10-31/functions/${encodeURIComponent(e)}/url`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async getFunctionUrl(n){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2021-10-31/functions/${encodeURIComponent(n)}/url`,headers:{"Content-Type":"application/json"}})}catch(e){if(e.statusCode===404)return null;throw e}}async deleteFunctionUrl(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2021-10-31/functions/${encodeURIComponent(n)}/url`,headers:{"Content-Type":"application/json"}})}async createFunctionWithCode(n){let{Code:e,Filename:t="index.js",...i}=n,r=d(t,e);return this.createFunction({...i,Code:{ZipFile:r.toString("base64")}})}async addFunctionUrlPermission(n){return this.addPermission({FunctionName:n,StatementId:"FunctionURLAllowPublicAccess",Action:"lambda:InvokeFunctionUrl",Principal:"*",FunctionUrlAuthType:"NONE"})}async publishLayerVersion(n){let{LayerName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2018-10-31/layers/${encodeURIComponent(e)}/versions`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async listLayerVersions(n,e){let t={};if(e?.CompatibleRuntime)t.CompatibleRuntime=e.CompatibleRuntime;if(e?.CompatibleArchitecture)t.CompatibleArchitecture=e.CompatibleArchitecture;if(e?.MaxItems)t.MaxItems=String(e.MaxItems);if(e?.Marker)t.Marker=e.Marker;return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions`,queryParams:Object.keys(t).length>0?t:void 0,headers:{"Content-Type":"application/json"}})}async getLayerVersion(n,e){return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions/${e}`,headers:{"Content-Type":"application/json"}})}async addLayerVersionPermission(n){let{LayerName:e,VersionNumber:t,...i}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2018-10-31/layers/${encodeURIComponent(e)}/versions/${t}/policy`,headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}async deleteLayerVersion(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions/${e}`,headers:{"Content-Type":"application/json"}})}}
2
2
  export{R};
@@ -1,4 +1,4 @@
1
- import{A}from"./chunk-24njmb7d.js";var oe=["project:read","config:read","config:write","deployments:read","deployments:create","deployments:cancel","deployments:rollback","runtime:read","runtime:restart","runtime:logs","runtime:terminal","data:read","data:write","data:admin","backups:read","backups:create","backups:restore","secrets:read","secrets:write","fleet:read","fleet:manage","users:read","users:manage","users:transfer-ownership","audit:read","billing:read","billing:manage","security:read","security:manage","security:waive","sources:read","sources:manage","applications:read","applications:manage","automation:read","automation:manage","tags:manage"],K=["project:read","config:read","deployments:read","runtime:read","runtime:logs","data:read","backups:read","security:read","sources:read","applications:read","billing:read"],Ee={owner:new Set(oe),admin:new Set(oe.filter((e)=>e!=="users:transfer-ownership")),deployer:new Set([...K,"deployments:create","deployments:cancel","deployments:rollback","sources:manage","applications:manage"]),operator:new Set([...K,"runtime:restart","backups:create","security:manage","sources:manage","applications:manage"]),viewer:new Set(K),auditor:new Set(["project:read","config:read","deployments:read","runtime:read","data:read","backups:read","audit:read","security:read","sources:read","applications:read"])};function nn(e){return Ee[e]}function P(e,t){if(e.type==="organization")return e.id===void 0||e.id===t.organizationId;if(!e.id)return!1;if(e.type==="project")return e.id===t.projectId;if(e.type==="environment")return e.id===t.environmentId;return e.id===t.resourceId}function ee(e){let{membership:t,capability:r,target:i}=e;if(!t||t.status!=="active"||t.organizationId!==i.organizationId)return{allowed:!1,reason:"inactive-membership"};let a=e.grants.filter((s)=>s.organizationId===i.organizationId&&s.membershipId===t.id&&s.capability===r&&P(s.scope,i)),E=a.find((s)=>s.effect==="deny");if(E)return{allowed:!1,reason:"explicit-deny",inheritedFrom:{kind:"grant",id:E.id,scope:E.scope}};let T=a.find((s)=>s.effect==="allow");if(T)return{allowed:!0,reason:"explicit-allow",inheritedFrom:{kind:"grant",id:T.id,scope:T.scope}};if(!P(t.scope,i))return{allowed:!1,reason:"scope-mismatch"};if(nn(t.roleTemplate).has(r))return{allowed:!0,reason:"role-template",inheritedFrom:{kind:"membership",id:t.id,scope:t.scope}};return{allowed:!1,reason:"missing-capability"}}function on(e){return oe.filter((t)=>ee({...e,capability:t}).allowed)}import{createHash as S,randomBytes as Te}from"node:crypto";import{chmodSync as H,existsSync as Z,mkdirSync as se,statSync as de}from"node:fs";import{dirname as te}from"node:path";import{Database as Ne}from"bun:sqlite";var l=40,j=[{version:1,name:"core_control_plane",sql:`
1
+ import{A}from"./chunk-jdfbahjb.js";var se=["project:read","config:read","config:write","deployments:read","deployments:create","deployments:cancel","deployments:rollback","runtime:read","runtime:restart","runtime:logs","runtime:terminal","data:read","data:write","data:admin","backups:read","backups:create","backups:restore","secrets:read","secrets:write","fleet:read","fleet:manage","users:read","users:manage","users:transfer-ownership","audit:read","billing:read","billing:manage","security:read","security:manage","security:waive","sources:read","sources:manage","applications:read","applications:manage","automation:read","automation:manage","tags:manage"],K=["project:read","config:read","deployments:read","runtime:read","runtime:logs","data:read","backups:read","security:read","sources:read","applications:read","billing:read"],Ee={owner:new Set(se),admin:new Set(se.filter((e)=>e!=="users:transfer-ownership")),deployer:new Set([...K,"deployments:create","deployments:cancel","deployments:rollback","sources:manage","applications:manage"]),operator:new Set([...K,"runtime:restart","backups:create","security:manage","sources:manage","applications:manage"]),viewer:new Set(K),auditor:new Set(["project:read","config:read","deployments:read","runtime:read","data:read","backups:read","audit:read","security:read","sources:read","applications:read"])};function on(e){return Ee[e]}function P(e,t){if(e.type==="organization")return e.id===void 0||e.id===t.organizationId;if(!e.id)return!1;if(e.type==="project")return e.id===t.projectId;if(e.type==="environment")return e.id===t.environmentId;return e.id===t.resourceId}function te(e){let{membership:t,capability:r,target:i}=e;if(!t||t.status!=="active"||t.organizationId!==i.organizationId)return{allowed:!1,reason:"inactive-membership"};let a=e.grants.filter((s)=>s.organizationId===i.organizationId&&s.membershipId===t.id&&s.capability===r&&P(s.scope,i)),E=a.find((s)=>s.effect==="deny");if(E)return{allowed:!1,reason:"explicit-deny",inheritedFrom:{kind:"grant",id:E.id,scope:E.scope}};let T=a.find((s)=>s.effect==="allow");if(T)return{allowed:!0,reason:"explicit-allow",inheritedFrom:{kind:"grant",id:T.id,scope:T.scope}};if(!P(t.scope,i))return{allowed:!1,reason:"scope-mismatch"};if(on(t.roleTemplate).has(r))return{allowed:!0,reason:"role-template",inheritedFrom:{kind:"membership",id:t.id,scope:t.scope}};return{allowed:!1,reason:"missing-capability"}}function sn(e){return se.filter((t)=>te({...e,capability:t}).allowed)}import{createHash as S,randomBytes as oe}from"node:crypto";import{chmodSync as H,existsSync as Z,mkdirSync as Te,statSync as de}from"node:fs";import{dirname as ee}from"node:path";import{Database as Ne}from"bun:sqlite";var l=40,j=[{version:1,name:"core_control_plane",sql:`
2
2
  CREATE TABLE projects (
3
3
  id TEXT PRIMARY KEY,
4
4
  slug TEXT NOT NULL UNIQUE,
@@ -1476,15 +1476,15 @@ import{A}from"./chunk-24njmb7d.js";var oe=["project:read","config:read","config:
1476
1476
  CREATE INDEX telemetry_kind_scope_time_idx
1477
1477
  ON telemetry_records(project_id, kind, timestamp);
1478
1478
  `}];class p extends Error{constructor(e,t,r){super(`${e} ${t} changed since version ${r}`);this.name="OptimisticConcurrencyError"}}class x extends Error{constructor(e,t){super(`Operation cannot transition from ${e} to ${t}`);this.name="InvalidOperationTransitionError"}}class I extends Error{constructor(e,t){super(`Control-plane schema version ${e} is newer than supported version ${t}`);this.name="UnsupportedSchemaVersionError"}}var ie=65536,q=16384,ce=["succeeded","failed","cancelled","timed_out"],Le={queued:["running","cancelled","timed_out"],running:["queued","succeeded","failed","cancelled","timed_out"],succeeded:[],failed:["queued"],cancelled:["queued"],timed_out:["queued"]},_e=/(?:^|_)(?:authorization|cookie|credential|password|passwd|secret|token|api_?key|private_?key|access_?key)(?:$|_)/i,re=/(?:authorization|password|secret|token|api[_-]?key|private[_-]?key|access[_-]?key)\s*[=:]\s*[^\s,;]+/gi;function _(e){if(typeof e!=="string")return{};try{return JSON.parse(e)}catch{return{}}}function d(e){return typeof e==="string"?e:void 0}function G(e,t){if(t&&_e.test(t))return"[REDACTED]";if(e===null||typeof e==="boolean"||typeof e==="number")return e;if(typeof e==="string")return e.replace(re,"[REDACTED]");if(Array.isArray(e))return e.map((r)=>G(r));if(e&&typeof e==="object"){let r={};for(let[i,a]of Object.entries(e))r[i]=G(a,i);return r}return String(e??"")}function h(e,t=ie){let r=G(e),i=JSON.stringify(r);if(Buffer.byteLength(i)<=t)return r;return{truncated:!0,originalBytes:Buffer.byteLength(i),preview:i.slice(0,Math.max(0,t-128))}}function N(e){return JSON.stringify(h(e))}function M(e){if(!e)return;let t=e.replace(re,"[REDACTED]");return Buffer.byteLength(t)<=q?t:`${t.slice(0,q-24)}
1479
- [output truncated]`}function v(e){return{id:String(e.id),slug:String(e.slug),name:String(e.name),description:d(e.description),organizationId:d(e.organization_id),desiredConfigHash:d(e.desired_config_hash),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function D(e){return{id:String(e.id),projectId:String(e.project_id),slug:String(e.slug),name:String(e.name),kind:String(e.kind),region:d(e.region),desiredState:_(e.desired_state),discoveredState:_(e.discovered_state),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function y(e){return{id:String(e.id),projectId:String(e.project_id),environmentId:d(e.environment_id),kind:String(e.kind),slug:String(e.slug),name:String(e.name),provider:d(e.provider),providerId:d(e.provider_id),desiredState:_(e.desired_state),discoveredState:_(e.discovered_state),metadata:_(e.metadata),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function f(e){return{id:String(e.id),kind:String(e.kind),externalId:d(e.external_id),displayName:String(e.display_name),metadata:_(e.metadata),disabledAt:d(e.disabled_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function u(e){return{id:String(e.id),projectId:d(e.project_id),environmentId:d(e.environment_id),resourceId:d(e.resource_id),actorId:d(e.actor_id),kind:String(e.kind),state:String(e.state),correlationId:String(e.correlation_id),idempotencyKey:d(e.idempotency_key),input:_(e.input),output:_(e.output),error:d(e.error),attempt:Number(e.attempt),priority:Number(e.priority),leaseOwner:d(e.lease_owner),leaseExpiresAt:d(e.lease_expires_at),cancelRequestedAt:d(e.cancel_requested_at),startedAt:d(e.started_at),finishedAt:d(e.finished_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Y(e){return{id:String(e.id),sequence:Number(e.sequence),organizationId:d(e.organization_id),projectId:d(e.project_id),operationId:d(e.operation_id),resourceId:d(e.resource_id),actorId:d(e.actor_id),correlationId:String(e.correlation_id),type:String(e.type),level:String(e.level),payload:_(e.payload),createdAt:String(e.created_at)}}function O(e){return{id:String(e.id),projectId:String(e.project_id),name:String(e.name),normalizedName:String(e.normalized_name),color:String(e.color),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function b(e){return{id:String(e.id),actorKey:String(e.actor_key),name:String(e.name),routeId:String(e.route_id),query:_(e.query),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function F(e){return{actorKey:String(e.actor_key),entityType:String(e.entity_type),entityId:String(e.entity_id),favorite:Number(e.favorite)===1,lastVisitedAt:String(e.last_visited_at),visitCount:Number(e.visit_count)}}function z(e){return{id:String(e.id),slug:String(e.slug),name:String(e.name),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function B(e){let t=String(e.scope_type);return{type:t,...t==="organization"?{}:{id:String(e.scope_id)}}}function k(e){return{id:String(e.id),organizationId:String(e.organization_id),actorId:String(e.actor_id),roleTemplate:String(e.role_template),scope:B(e),source:String(e.source??"manual"),status:String(e.status),sessionVersion:Number(e.session_version),lastActiveAt:d(e.last_active_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function R(e,t){let r=d(e.accepted_at),i=d(e.revoked_at),a=String(e.expires_at),E=i?"revoked":r?"accepted":a<=t?"expired":"pending";return{id:String(e.id),organizationId:String(e.organization_id),email:String(e.email),roleTemplate:String(e.role_template),scope:B(e),invitedByActorId:d(e.invited_by_actor_id),acceptedByActorId:d(e.accepted_by_actor_id),expiresAt:a,acceptedAt:r,revokedAt:i,state:E,createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function w(e){return{id:String(e.id),organizationId:String(e.organization_id),membershipId:String(e.membership_id),effect:String(e.effect),capability:String(e.capability),scope:B(e),source:String(e.source??"manual"),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function g(e){return{type:e.type,id:e.id??null}}function le(e){return Array.from({length:e},()=>"?").join(", ")}function o(e,t,r){return e.run(t,r)}class Ar{path;database;nowFn;idFn;constructor(e={}){this.path=e.path??A(e.cwd??process.cwd(),"control-plane.sqlite"),this.nowFn=e.now??(()=>new Date),this.idFn=e.id??(()=>crypto.randomUUID());let t=this.path===":memory:";if(!t){se(te(this.path),{recursive:!0,mode:448});try{H(te(this.path),448)}catch{}}if(this.database=new Ne(this.path,{create:!0,strict:!0}),this.database.run("PRAGMA foreign_keys = ON"),this.database.run(`PRAGMA busy_timeout = ${Math.max(100,e.busyTimeoutMs??5000)}`),!t)this.database.run("PRAGMA journal_mode = WAL"),this.database.run("PRAGMA synchronous = NORMAL");if(this.migrate(),!t)this.secureDatabaseFiles()}now(){return this.nowFn().toISOString()}secureDatabaseFiles(){for(let e of[this.path,`${this.path}-wal`,`${this.path}-shm`]){if(!Z(e))continue;try{H(e,384)}catch{}}}backupTo(e){this.database.run("VACUUM INTO ?",[e]);try{H(e,384)}catch{}}migrate(){let e=this.database.query("PRAGMA user_version").get(),t=Number(e?.user_version??0);if(t>l)throw new I(t,l);if(t===l)return;let r;if(t>0&&this.path!==":memory:")r=`${this.path}.v${t}.${Date.now()}.bak`,this.backupTo(r);try{if(this.database.transaction(()=>{for(let a of j){if(a.version<=t)continue;this.database.run(a.sql),o(this.database,"INSERT INTO schema_migrations (version, name, applied_at) VALUES (?, ?, ?)",[a.version,a.name,this.now()]),this.database.run(`PRAGMA user_version = ${a.version}`)}}).exclusive(),r)this.setSetting("storage.last_backup",{path:r,createdAt:this.now(),reason:"pre-migration"})}catch(i){let a=r?` Restore from ${r}.`:"";throw Error(`Control-plane migration from schema ${t} failed.${a} ${i instanceof Error?i.message:String(i)}`)}}close(){if(this.path!==":memory:")this.secureDatabaseFiles();this.database.close()}transaction(e){return this.database.transaction(e).immediate()}createProject(e){let t=e.id??this.idFn(),r=this.now();return o(this.database,"INSERT INTO projects (id, slug, name, description, organization_id, desired_config_hash, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",[t,e.slug,e.name,e.description??null,e.organizationId??null,e.desiredConfigHash??null,r,r]),this.getProject(t)}getProject(e){let t=this.database.query("SELECT * FROM projects WHERE id = ?").get(e);return t?v(t):void 0}getProjectBySlug(e){let t=this.database.query("SELECT * FROM projects WHERE slug = ?").get(e);return t?v(t):void 0}listProjects(){return this.database.query("SELECT * FROM projects ORDER BY name COLLATE NOCASE, id").all().map(v)}updateProject(e,t,r){let i=this.getProject(e);if(!i||i.version!==t)throw new p("Project",e,t);if(o(this.database,`UPDATE projects SET name = ?, description = ?, organization_id = ?, desired_config_hash = ?, version = version + 1, updated_at = ?
1479
+ [output truncated]`}function v(e){return{id:String(e.id),slug:String(e.slug),name:String(e.name),description:d(e.description),organizationId:d(e.organization_id),desiredConfigHash:d(e.desired_config_hash),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function D(e){return{id:String(e.id),projectId:String(e.project_id),slug:String(e.slug),name:String(e.name),kind:String(e.kind),region:d(e.region),desiredState:_(e.desired_state),discoveredState:_(e.discovered_state),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function y(e){return{id:String(e.id),projectId:String(e.project_id),environmentId:d(e.environment_id),kind:String(e.kind),slug:String(e.slug),name:String(e.name),provider:d(e.provider),providerId:d(e.provider_id),desiredState:_(e.desired_state),discoveredState:_(e.discovered_state),metadata:_(e.metadata),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function f(e){return{id:String(e.id),kind:String(e.kind),externalId:d(e.external_id),displayName:String(e.display_name),metadata:_(e.metadata),disabledAt:d(e.disabled_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function u(e){return{id:String(e.id),projectId:d(e.project_id),environmentId:d(e.environment_id),resourceId:d(e.resource_id),actorId:d(e.actor_id),kind:String(e.kind),state:String(e.state),correlationId:String(e.correlation_id),idempotencyKey:d(e.idempotency_key),input:_(e.input),output:_(e.output),error:d(e.error),attempt:Number(e.attempt),priority:Number(e.priority),leaseOwner:d(e.lease_owner),leaseExpiresAt:d(e.lease_expires_at),cancelRequestedAt:d(e.cancel_requested_at),startedAt:d(e.started_at),finishedAt:d(e.finished_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Y(e){return{id:String(e.id),sequence:Number(e.sequence),organizationId:d(e.organization_id),projectId:d(e.project_id),operationId:d(e.operation_id),resourceId:d(e.resource_id),actorId:d(e.actor_id),correlationId:String(e.correlation_id),type:String(e.type),level:String(e.level),payload:_(e.payload),createdAt:String(e.created_at)}}function O(e){return{id:String(e.id),projectId:String(e.project_id),name:String(e.name),normalizedName:String(e.normalized_name),color:String(e.color),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function b(e){return{id:String(e.id),actorKey:String(e.actor_key),name:String(e.name),routeId:String(e.route_id),query:_(e.query),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function F(e){return{actorKey:String(e.actor_key),entityType:String(e.entity_type),entityId:String(e.entity_id),favorite:Number(e.favorite)===1,lastVisitedAt:String(e.last_visited_at),visitCount:Number(e.visit_count)}}function z(e){return{id:String(e.id),slug:String(e.slug),name:String(e.name),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function B(e){let t=String(e.scope_type);return{type:t,...t==="organization"?{}:{id:String(e.scope_id)}}}function k(e){return{id:String(e.id),organizationId:String(e.organization_id),actorId:String(e.actor_id),roleTemplate:String(e.role_template),scope:B(e),source:String(e.source??"manual"),status:String(e.status),sessionVersion:Number(e.session_version),lastActiveAt:d(e.last_active_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function R(e,t){let r=d(e.accepted_at),i=d(e.revoked_at),a=String(e.expires_at),E=i?"revoked":r?"accepted":a<=t?"expired":"pending";return{id:String(e.id),organizationId:String(e.organization_id),email:String(e.email),roleTemplate:String(e.role_template),scope:B(e),invitedByActorId:d(e.invited_by_actor_id),acceptedByActorId:d(e.accepted_by_actor_id),expiresAt:a,acceptedAt:r,revokedAt:i,state:E,createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function w(e){return{id:String(e.id),organizationId:String(e.organization_id),membershipId:String(e.membership_id),effect:String(e.effect),capability:String(e.capability),scope:B(e),source:String(e.source??"manual"),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function g(e){return{type:e.type,id:e.id??null}}function le(e){return Array.from({length:e},()=>"?").join(", ")}function o(e,t,r){return e.run(t,r)}class Ir{path;database;nowFn;idFn;constructor(e={}){this.path=e.path??A(e.cwd??process.cwd(),"control-plane.sqlite"),this.nowFn=e.now??(()=>new Date),this.idFn=e.id??(()=>crypto.randomUUID());let t=this.path===":memory:";if(!t){Te(ee(this.path),{recursive:!0,mode:448});try{H(ee(this.path),448)}catch{}}if(this.database=new Ne(this.path,{create:!0,strict:!0}),this.database.run("PRAGMA foreign_keys = ON"),this.database.run(`PRAGMA busy_timeout = ${Math.max(100,e.busyTimeoutMs??5000)}`),!t)this.database.run("PRAGMA journal_mode = WAL"),this.database.run("PRAGMA synchronous = NORMAL");if(this.migrate(),!t)this.secureDatabaseFiles()}now(){return this.nowFn().toISOString()}secureDatabaseFiles(){for(let e of[this.path,`${this.path}-wal`,`${this.path}-shm`]){if(!Z(e))continue;try{H(e,384)}catch{}}}backupTo(e){this.database.run("VACUUM INTO ?",[e]);try{H(e,384)}catch{}}migrate(){let e=this.database.query("PRAGMA user_version").get(),t=Number(e?.user_version??0);if(t>l)throw new I(t,l);if(t===l)return;let r;if(t>0&&this.path!==":memory:")r=`${this.path}.v${t}.${Date.now()}.bak`,this.backupTo(r);try{if(this.database.transaction(()=>{for(let a of j){if(a.version<=t)continue;this.database.run(a.sql),o(this.database,"INSERT INTO schema_migrations (version, name, applied_at) VALUES (?, ?, ?)",[a.version,a.name,this.now()]),this.database.run(`PRAGMA user_version = ${a.version}`)}}).exclusive(),r)this.setSetting("storage.last_backup",{path:r,createdAt:this.now(),reason:"pre-migration"})}catch(i){let a=r?` Restore from ${r}.`:"";throw Error(`Control-plane migration from schema ${t} failed.${a} ${i instanceof Error?i.message:String(i)}`)}}close(){if(this.path!==":memory:")this.secureDatabaseFiles();this.database.close()}transaction(e){return this.database.transaction(e).immediate()}createProject(e){let t=e.id??this.idFn(),r=this.now();return o(this.database,"INSERT INTO projects (id, slug, name, description, organization_id, desired_config_hash, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",[t,e.slug,e.name,e.description??null,e.organizationId??null,e.desiredConfigHash??null,r,r]),this.getProject(t)}getProject(e){let t=this.database.query("SELECT * FROM projects WHERE id = ?").get(e);return t?v(t):void 0}getProjectBySlug(e){let t=this.database.query("SELECT * FROM projects WHERE slug = ?").get(e);return t?v(t):void 0}listProjects(){return this.database.query("SELECT * FROM projects ORDER BY name COLLATE NOCASE, id").all().map(v)}updateProject(e,t,r){let i=this.getProject(e);if(!i||i.version!==t)throw new p("Project",e,t);if(o(this.database,`UPDATE projects SET name = ?, description = ?, organization_id = ?, desired_config_hash = ?, version = version + 1, updated_at = ?
1480
1480
  WHERE id = ? AND version = ?`,[r.name??i.name,r.description===null?null:r.description??i.description??null,r.organizationId===null?null:r.organizationId??i.organizationId??null,r.desiredConfigHash===null?null:r.desiredConfigHash??i.desiredConfigHash??null,this.now(),e,t]).changes!==1)throw new p("Project",e,t);return this.getProject(e)}createEnvironment(e){let t=e.id??this.idFn(),r=this.now();return o(this.database,`INSERT INTO environments (id, project_id, slug, name, kind, region, desired_state, discovered_state, created_at, updated_at)
1481
1481
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[t,e.projectId,e.slug,e.name,e.kind,e.region??null,N(e.desiredState??{}),N(e.discoveredState??{}),r,r]),D(this.database.query("SELECT * FROM environments WHERE id = ?").get(t))}listEnvironments(e){return this.database.query("SELECT * FROM environments WHERE project_id = ? ORDER BY name COLLATE NOCASE, id").all(e).map(D)}getEnvironmentBySlug(e,t){let r=this.database.query("SELECT * FROM environments WHERE project_id = ? AND slug = ?").get(e,t);return r?D(r):void 0}createResource(e){let t=e.id??this.idFn(),r=this.now();return o(this.database,`INSERT INTO resources (id, project_id, environment_id, kind, slug, name, provider, provider_id, desired_state, discovered_state, metadata, created_at, updated_at)
1482
1482
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[t,e.projectId,e.environmentId??null,e.kind,e.slug,e.name,e.provider??null,e.providerId??null,N(e.desiredState??{}),N(e.discoveredState??{}),N(e.metadata??{}),r,r]),y(this.database.query("SELECT * FROM resources WHERE id = ?").get(t))}listResources(e,t){return(t?this.database.query("SELECT * FROM resources WHERE project_id = ? AND environment_id = ? ORDER BY kind, name COLLATE NOCASE").all(e,t):this.database.query("SELECT * FROM resources WHERE project_id = ? ORDER BY kind, name COLLATE NOCASE").all(e)).map(y)}getResource(e){let t=this.database.query("SELECT * FROM resources WHERE id = ?").get(e);return t?y(t):void 0}updateResource(e,t,r){let i=this.getResource(e);if(!i||i.version!==t)throw new p("Resource",e,t);if(o(this.database,`UPDATE resources SET name = ?, provider = ?, provider_id = ?, desired_state = ?, discovered_state = ?, metadata = ?,
1483
1483
  version = version + 1, updated_at = ? WHERE id = ? AND version = ?`,[r.name??i.name,r.provider===null?null:r.provider??i.provider??null,r.providerId===null?null:r.providerId??i.providerId??null,N(r.desiredState??i.desiredState),N(r.discoveredState??i.discoveredState),N(r.metadata??i.metadata),this.now(),e,t]).changes!==1)throw new p("Resource",e,t);return this.getResource(e)}createActor(e){let t=e.id??this.idFn(),r=this.now();return o(this.database,"INSERT INTO actors (id, kind, external_id, display_name, metadata, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[t,e.kind,e.externalId??null,e.displayName,N(e.metadata??{}),r,r]),f(this.database.query("SELECT * FROM actors WHERE id = ?").get(t))}getActorByExternalId(e,t){let r=this.database.query("SELECT * FROM actors WHERE kind = ? AND external_id = ?").get(e,t);return r?f(r):void 0}getActor(e){let t=this.database.query("SELECT * FROM actors WHERE id = ?").get(e);return t?f(t):void 0}createOrganization(e){let t=e.slug.trim().toLowerCase();if(!/^[a-z0-9][a-z0-9-]{1,62}[a-z0-9]$/.test(t))throw Error("Organization slugs must contain 3-64 lowercase letters, numbers, or dashes");let r=e.name.trim();if(!r||r.length>100)throw Error("Organization names must contain 1-100 characters");let i=e.id??this.idFn(),a=this.now();return o(this.database,"INSERT INTO organizations (id, slug, name, created_at, updated_at) VALUES (?, ?, ?, ?, ?)",[i,t,r,a,a]),this.getOrganization(i)}getOrganization(e){let t=this.database.query("SELECT * FROM organizations WHERE id = ?").get(e);return t?z(t):void 0}getOrganizationBySlug(e){let t=this.database.query("SELECT * FROM organizations WHERE slug = ?").get(e.trim().toLowerCase());return t?z(t):void 0}listOrganizations(e){return(e?this.database.query(`SELECT organizations.* FROM organizations JOIN organization_memberships ON organization_memberships.organization_id = organizations.id
1484
1484
  WHERE organization_memberships.actor_id = ? AND organization_memberships.status = 'active' ORDER BY organizations.name COLLATE NOCASE`).all(e):this.database.query("SELECT * FROM organizations ORDER BY name COLLATE NOCASE").all()).map(z)}normalizeAuthorizationScope(e,t={type:"organization"}){if(t.type==="organization"){if(t.id&&t.id!==e)throw Error("Organization scope does not match the requested organization");return{type:"organization"}}if(!t.id)throw Error(`${t.type} scopes require an ID`);if(!this.resolveAuthorizationTarget(e,t))throw Error("Authorization scope was not found in this organization");return{type:t.type,id:t.id}}resolveAuthorizationTarget(e,t){if(!this.getOrganization(e))return;if(t.type==="organization")return{organizationId:e};if(!t.id)return;if(t.type==="project"){let i=this.database.query("SELECT id FROM projects WHERE id = ? AND organization_id = ?").get(t.id,e);return i?{organizationId:e,projectId:String(i.id)}:void 0}if(t.type==="environment"){let i=this.database.query("SELECT environments.id, environments.project_id FROM environments JOIN projects ON projects.id = environments.project_id WHERE environments.id = ? AND projects.organization_id = ?").get(t.id,e);return i?{organizationId:e,projectId:String(i.project_id),environmentId:String(i.id)}:void 0}let r=this.database.query(`SELECT resources.id, resources.project_id, resources.environment_id FROM resources
1485
1485
  JOIN projects ON projects.id = resources.project_id WHERE resources.id = ? AND projects.organization_id = ?`).get(t.id,e);return r?{organizationId:e,projectId:String(r.project_id),environmentId:d(r.environment_id),resourceId:String(r.id)}:void 0}createMembership(e){if(!this.getActor(e.actorId))throw Error("Membership actor was not found");let t=this.normalizeAuthorizationScope(e.organizationId,e.scope);if(e.roleTemplate==="owner"&&t.type!=="organization")throw Error("Owners must be scoped to the organization");let r=e.id??this.idFn(),i=this.now();o(this.database,`INSERT INTO organization_memberships (id, organization_id, actor_id, role_template, scope_type, scope_id, source, created_at, updated_at)
1486
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[r,e.organizationId,e.actorId,e.roleTemplate,t.type,t.id??null,e.source??"manual",i,i]);let a=this.getMembership(r);return this.appendEvent({organizationId:e.organizationId,actorId:e.performedByActorId,type:"organization.membership.created",payload:{membershipId:r,actorId:e.actorId,roleTemplate:e.roleTemplate,scope:g(t)}}),a}getMembership(e){let t=this.database.query("SELECT * FROM organization_memberships WHERE id = ?").get(e);return t?k(t):void 0}getMembershipForActor(e,t){let r=this.database.query("SELECT * FROM organization_memberships WHERE organization_id = ? AND actor_id = ?").get(e,t);return r?k(r):void 0}listMemberships(e,t={}){let r=t.includeRevoked?"":"AND status = 'active'";return this.database.query(`SELECT * FROM organization_memberships WHERE organization_id = ? ${r} ORDER BY created_at, id`).all(e).map(k)}updateMembership(e){let t=this.getMembership(e.id);if(!t)throw Error("Membership was not found");let r=this.normalizeAuthorizationScope(t.organizationId,e.scope??t.scope);if(e.roleTemplate==="owner"&&r.type!=="organization")throw Error("Owners must be scoped to the organization");if(t.roleTemplate==="owner"&&t.status==="active"&&(e.roleTemplate!=="owner"||r.type!=="organization"))this.assertAnotherOwner(t);return o(this.database,"UPDATE organization_memberships SET role_template = ?, scope_type = ?, scope_id = ?, session_version = session_version + 1, updated_at = ? WHERE id = ?",[e.roleTemplate,r.type,r.id??null,this.now(),t.id]),this.appendEvent({organizationId:t.organizationId,actorId:e.actorId,type:"organization.membership.updated",payload:{membershipId:t.id,from:{roleTemplate:t.roleTemplate,scope:g(t.scope)},to:{roleTemplate:e.roleTemplate,scope:g(r)}}}),this.getMembership(t.id)}revokeMembership(e,t){let r=this.getMembership(e);if(!r)throw Error("Membership was not found");if(r.status==="revoked")return r;if(r.roleTemplate==="owner")this.assertAnotherOwner(r);return o(this.database,"UPDATE organization_memberships SET status = 'revoked', session_version = session_version + 1, updated_at = ? WHERE id = ?",[this.now(),e]),this.appendEvent({organizationId:r.organizationId,actorId:t,type:"organization.membership.revoked",payload:{membershipId:e}}),this.getMembership(e)}touchMembership(e){let t=this.now();o(this.database,"UPDATE organization_memberships SET last_active_at = ?, updated_at = ? WHERE id = ? AND status = ?",[t,t,e,"active"]);let r=this.getMembership(e);if(!r)throw Error("Membership was not found");return r}assertAnotherOwner(e){if(Number(this.database.query("SELECT COUNT(*) AS count FROM organization_memberships WHERE organization_id = ? AND status = ? AND role_template = 'owner'").get(e.organizationId,"active")?.count??0)<=1)throw Error("Cannot remove or demote the last organization owner")}createInvitation(e){let t=e.email.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)||t.length>254)throw Error("A valid invitation email is required");let r=this.normalizeAuthorizationScope(e.organizationId,e.scope);if(e.roleTemplate==="owner"&&r.type!=="organization")throw Error("Owners must be scoped to the organization");let i=Te(32).toString("base64url"),a=S("sha256").update(i).digest("hex"),E=e.id??this.idFn(),T=this.now(),s=new Date(this.nowFn().getTime()+Math.min(2592000000,Math.max(60000,e.expiresInMs??604800000))).toISOString();return o(this.database,`INSERT INTO organization_invitations (id, organization_id, email, role_template, scope_type, scope_id, token_hash, invited_by_actor_id, expires_at, created_at, updated_at)
1487
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[E,e.organizationId,t,e.roleTemplate,r.type,r.id??null,a,e.invitedByActorId??null,s,T,T]),this.appendEvent({organizationId:e.organizationId,actorId:e.invitedByActorId,type:"organization.invitation.created",payload:{invitationId:E,email:t,roleTemplate:e.roleTemplate,scope:g(r),expiresAt:s}}),{invitation:this.getInvitation(E),token:i}}getInvitation(e){let t=this.database.query("SELECT * FROM organization_invitations WHERE id = ?").get(e);return t?R(t,this.now()):void 0}listInvitations(e){return this.database.query("SELECT * FROM organization_invitations WHERE organization_id = ? ORDER BY created_at DESC").all(e).map((t)=>R(t,this.now()))}inspectInvitationToken(e){let t=S("sha256").update(e).digest("hex"),r=this.database.query("SELECT * FROM organization_invitations WHERE token_hash = ?").get(t);return r?R(r,this.now()):void 0}acceptInvitation(e,t){let r=S("sha256").update(e).digest("hex");return this.transaction(()=>{let i=this.database.query("SELECT * FROM organization_invitations WHERE token_hash = ?").get(r);if(!i)throw Error("Invitation is invalid");let a=R(i,this.now());if(a.state!=="pending")throw Error(`Invitation is ${a.state}`);if(!this.getActor(t))throw Error("Invitation actor was not found");if(o(this.database,"UPDATE organization_invitations SET accepted_by_actor_id = ?, accepted_at = ?, updated_at = ? WHERE id = ? AND accepted_at IS NULL AND revoked_at IS NULL AND expires_at > ?",[t,this.now(),this.now(),a.id,this.now()]).changes!==1)throw Error("Invitation is no longer available");let T=this.getMembershipForActor(a.organizationId,t),s=T??this.createMembership({organizationId:a.organizationId,actorId:t,roleTemplate:a.roleTemplate,scope:a.scope,source:"invitation"});if(T&&a.roleTemplate==="owner"&&T.roleTemplate!=="owner")s=this.updateMembership({id:T.id,roleTemplate:"owner",scope:{type:"organization"},actorId:t});else if(T)for(let c of nn(a.roleTemplate))this.upsertGrant({organizationId:a.organizationId,membershipId:T.id,effect:"allow",capability:c,scope:a.scope,source:"invitation"});return this.appendEvent({organizationId:a.organizationId,actorId:t,type:"organization.invitation.accepted",payload:{invitationId:a.id,membershipId:s.id}}),{invitation:this.getInvitation(a.id),membership:this.getMembership(s.id)}})}revokeInvitation(e,t){let r=this.getInvitation(e);if(!r)throw Error("Invitation was not found");if(r.acceptedAt)throw Error("Accepted invitations cannot be revoked");if(!r.revokedAt)o(this.database,"UPDATE organization_invitations SET revoked_at = ?, updated_at = ? WHERE id = ?",[this.now(),this.now(),e]);return this.appendEvent({organizationId:r.organizationId,actorId:t,type:"organization.invitation.revoked",payload:{invitationId:e}}),this.getInvitation(e)}reissueInvitation(e,t){let r=this.getInvitation(e);if(!r)throw Error("Invitation was not found");if(r.state==="accepted")throw Error("Accepted invitations cannot be reissued");return this.revokeInvitation(e,t),this.createInvitation({organizationId:r.organizationId,email:r.email,roleTemplate:r.roleTemplate,scope:r.scope,invitedByActorId:t})}upsertGrant(e){if(!oe.includes(e.capability))throw Error("Unknown authorization capability");let t=this.getMembership(e.membershipId);if(!t||t.organizationId!==e.organizationId)throw Error("Grant membership was not found in this organization");let r=this.normalizeAuthorizationScope(e.organizationId,e.scope),i=this.now(),a=this.database.query("SELECT * FROM authorization_grants WHERE membership_id = ? AND effect = ? AND capability = ? AND scope_type = ? AND scope_id IS ?").get(e.membershipId,e.effect,e.capability,r.type,r.id??null);if(a)return w(a);let E=e.id??this.idFn();return o(this.database,`INSERT INTO authorization_grants (id, organization_id, membership_id, effect, capability, scope_type, scope_id, source, created_at, updated_at)
1486
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[r,e.organizationId,e.actorId,e.roleTemplate,t.type,t.id??null,e.source??"manual",i,i]);let a=this.getMembership(r);return this.appendEvent({organizationId:e.organizationId,actorId:e.performedByActorId,type:"organization.membership.created",payload:{membershipId:r,actorId:e.actorId,roleTemplate:e.roleTemplate,scope:g(t)}}),a}getMembership(e){let t=this.database.query("SELECT * FROM organization_memberships WHERE id = ?").get(e);return t?k(t):void 0}getMembershipForActor(e,t){let r=this.database.query("SELECT * FROM organization_memberships WHERE organization_id = ? AND actor_id = ?").get(e,t);return r?k(r):void 0}listMemberships(e,t={}){let r=t.includeRevoked?"":"AND status = 'active'";return this.database.query(`SELECT * FROM organization_memberships WHERE organization_id = ? ${r} ORDER BY created_at, id`).all(e).map(k)}updateMembership(e){let t=this.getMembership(e.id);if(!t)throw Error("Membership was not found");let r=this.normalizeAuthorizationScope(t.organizationId,e.scope??t.scope);if(e.roleTemplate==="owner"&&r.type!=="organization")throw Error("Owners must be scoped to the organization");if(t.roleTemplate==="owner"&&t.status==="active"&&(e.roleTemplate!=="owner"||r.type!=="organization"))this.assertAnotherOwner(t);return o(this.database,"UPDATE organization_memberships SET role_template = ?, scope_type = ?, scope_id = ?, session_version = session_version + 1, updated_at = ? WHERE id = ?",[e.roleTemplate,r.type,r.id??null,this.now(),t.id]),this.appendEvent({organizationId:t.organizationId,actorId:e.actorId,type:"organization.membership.updated",payload:{membershipId:t.id,from:{roleTemplate:t.roleTemplate,scope:g(t.scope)},to:{roleTemplate:e.roleTemplate,scope:g(r)}}}),this.getMembership(t.id)}revokeMembership(e,t){let r=this.getMembership(e);if(!r)throw Error("Membership was not found");if(r.status==="revoked")return r;if(r.roleTemplate==="owner")this.assertAnotherOwner(r);return o(this.database,"UPDATE organization_memberships SET status = 'revoked', session_version = session_version + 1, updated_at = ? WHERE id = ?",[this.now(),e]),this.appendEvent({organizationId:r.organizationId,actorId:t,type:"organization.membership.revoked",payload:{membershipId:e}}),this.getMembership(e)}touchMembership(e){let t=this.now();o(this.database,"UPDATE organization_memberships SET last_active_at = ?, updated_at = ? WHERE id = ? AND status = ?",[t,t,e,"active"]);let r=this.getMembership(e);if(!r)throw Error("Membership was not found");return r}assertAnotherOwner(e){if(Number(this.database.query("SELECT COUNT(*) AS count FROM organization_memberships WHERE organization_id = ? AND status = ? AND role_template = 'owner'").get(e.organizationId,"active")?.count??0)<=1)throw Error("Cannot remove or demote the last organization owner")}createInvitation(e){let t=e.email.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)||t.length>254)throw Error("A valid invitation email is required");let r=this.normalizeAuthorizationScope(e.organizationId,e.scope);if(e.roleTemplate==="owner"&&r.type!=="organization")throw Error("Owners must be scoped to the organization");let i=oe(32).toString("base64url"),a=S("sha256").update(i).digest("hex"),E=e.id??this.idFn(),T=this.now(),s=new Date(this.nowFn().getTime()+Math.min(2592000000,Math.max(60000,e.expiresInMs??604800000))).toISOString();return o(this.database,`INSERT INTO organization_invitations (id, organization_id, email, role_template, scope_type, scope_id, token_hash, invited_by_actor_id, expires_at, created_at, updated_at)
1487
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[E,e.organizationId,t,e.roleTemplate,r.type,r.id??null,a,e.invitedByActorId??null,s,T,T]),this.appendEvent({organizationId:e.organizationId,actorId:e.invitedByActorId,type:"organization.invitation.created",payload:{invitationId:E,email:t,roleTemplate:e.roleTemplate,scope:g(r),expiresAt:s}}),{invitation:this.getInvitation(E),token:i}}getInvitation(e){let t=this.database.query("SELECT * FROM organization_invitations WHERE id = ?").get(e);return t?R(t,this.now()):void 0}listInvitations(e){return this.database.query("SELECT * FROM organization_invitations WHERE organization_id = ? ORDER BY created_at DESC").all(e).map((t)=>R(t,this.now()))}inspectInvitationToken(e){let t=S("sha256").update(e).digest("hex"),r=this.database.query("SELECT * FROM organization_invitations WHERE token_hash = ?").get(t);return r?R(r,this.now()):void 0}acceptInvitation(e,t){let r=S("sha256").update(e).digest("hex");return this.transaction(()=>{let i=this.database.query("SELECT * FROM organization_invitations WHERE token_hash = ?").get(r);if(!i)throw Error("Invitation is invalid");let a=R(i,this.now());if(a.state!=="pending")throw Error(`Invitation is ${a.state}`);if(!this.getActor(t))throw Error("Invitation actor was not found");if(o(this.database,"UPDATE organization_invitations SET accepted_by_actor_id = ?, accepted_at = ?, updated_at = ? WHERE id = ? AND accepted_at IS NULL AND revoked_at IS NULL AND expires_at > ?",[t,this.now(),this.now(),a.id,this.now()]).changes!==1)throw Error("Invitation is no longer available");let T=this.getMembershipForActor(a.organizationId,t),s=T??this.createMembership({organizationId:a.organizationId,actorId:t,roleTemplate:a.roleTemplate,scope:a.scope,source:"invitation"});if(T&&a.roleTemplate==="owner"&&T.roleTemplate!=="owner")s=this.updateMembership({id:T.id,roleTemplate:"owner",scope:{type:"organization"},actorId:t});else if(T)for(let c of on(a.roleTemplate))this.upsertGrant({organizationId:a.organizationId,membershipId:T.id,effect:"allow",capability:c,scope:a.scope,source:"invitation"});return this.appendEvent({organizationId:a.organizationId,actorId:t,type:"organization.invitation.accepted",payload:{invitationId:a.id,membershipId:s.id}}),{invitation:this.getInvitation(a.id),membership:this.getMembership(s.id)}})}revokeInvitation(e,t){let r=this.getInvitation(e);if(!r)throw Error("Invitation was not found");if(r.acceptedAt)throw Error("Accepted invitations cannot be revoked");if(!r.revokedAt)o(this.database,"UPDATE organization_invitations SET revoked_at = ?, updated_at = ? WHERE id = ?",[this.now(),this.now(),e]);return this.appendEvent({organizationId:r.organizationId,actorId:t,type:"organization.invitation.revoked",payload:{invitationId:e}}),this.getInvitation(e)}reissueInvitation(e,t){let r=this.getInvitation(e);if(!r)throw Error("Invitation was not found");if(r.state==="accepted")throw Error("Accepted invitations cannot be reissued");return this.revokeInvitation(e,t),this.createInvitation({organizationId:r.organizationId,email:r.email,roleTemplate:r.roleTemplate,scope:r.scope,invitedByActorId:t})}upsertGrant(e){if(!se.includes(e.capability))throw Error("Unknown authorization capability");let t=this.getMembership(e.membershipId);if(!t||t.organizationId!==e.organizationId)throw Error("Grant membership was not found in this organization");let r=this.normalizeAuthorizationScope(e.organizationId,e.scope),i=this.now(),a=this.database.query("SELECT * FROM authorization_grants WHERE membership_id = ? AND effect = ? AND capability = ? AND scope_type = ? AND scope_id IS ?").get(e.membershipId,e.effect,e.capability,r.type,r.id??null);if(a)return w(a);let E=e.id??this.idFn();return o(this.database,`INSERT INTO authorization_grants (id, organization_id, membership_id, effect, capability, scope_type, scope_id, source, created_at, updated_at)
1488
1488
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[E,e.organizationId,e.membershipId,e.effect,e.capability,r.type,r.id??null,e.source??"manual",i,i]),o(this.database,"UPDATE organization_memberships SET session_version = session_version + 1, updated_at = ? WHERE id = ?",[i,e.membershipId]),this.appendEvent({organizationId:e.organizationId,actorId:e.actorId,type:"organization.grant.created",payload:{grantId:E,membershipId:e.membershipId,effect:e.effect,capability:e.capability,scope:g(r)}}),this.getGrant(E)}getGrant(e){let t=this.database.query("SELECT * FROM authorization_grants WHERE id = ?").get(e);return t?w(t):void 0}listGrants(e){return this.database.query("SELECT * FROM authorization_grants WHERE membership_id = ? ORDER BY effect DESC, capability, scope_type, scope_id").all(e).map(w)}removeGrant(e,t){let r=this.getGrant(e);if(!r)return!1;let i=o(this.database,"DELETE FROM authorization_grants WHERE id = ?",[e]).changes===1;if(i)o(this.database,"UPDATE organization_memberships SET session_version = session_version + 1, updated_at = ? WHERE id = ?",[this.now(),r.membershipId]),this.appendEvent({organizationId:r.organizationId,actorId:t,type:"organization.grant.removed",payload:{grantId:e,membershipId:r.membershipId}});return i}createOperation(e){if(e.idempotencyKey){let a=this.database.query("SELECT * FROM operations WHERE idempotency_key = ?").get(e.idempotencyKey);if(a)return u(a)}let t=e.id??this.idFn(),r=e.correlationId??this.idFn(),i=this.now();try{return this.transaction(()=>(o(this.database,`INSERT INTO operations (id, project_id, environment_id, resource_id, actor_id, kind, state, correlation_id, idempotency_key, input, output, priority, created_at, updated_at)
1489
1489
  VALUES (?, ?, ?, ?, ?, ?, 'queued', ?, ?, ?, '{}', ?, ?, ?)`,[t,e.projectId??null,e.environmentId??null,e.resourceId??null,e.actorId??null,e.kind,r,e.idempotencyKey??null,N(e.input??{}),e.priority??0,i,i]),this.appendEvent({projectId:e.projectId,operationId:t,resourceId:e.resourceId,actorId:e.actorId,correlationId:r,type:"operation.queued",payload:{kind:e.kind}}),this.getOperation(t)))}catch(a){if(e.idempotencyKey){let E=this.database.query("SELECT * FROM operations WHERE idempotency_key = ?").get(e.idempotencyKey);if(E)return u(E)}throw a}}getOperation(e){let t=this.database.query("SELECT * FROM operations WHERE id = ?").get(e);return t?u(t):void 0}listOperations(e={}){let t=[],r=[];if(e.projectId)t.push("project_id = ?"),r.push(e.projectId);if(e.state)t.push("state = ?"),r.push(e.state);if(e.kind)t.push("kind = ?"),r.push(e.kind);if(e.before)t.push("created_at < ?"),r.push(e.before);let i=Math.min(500,Math.max(1,e.limit??100));r.push(i);let a=t.length?`WHERE ${t.join(" AND ")}`:"";return this.database.query(`SELECT * FROM operations ${a} ORDER BY created_at DESC, id DESC LIMIT ?`).all(...r).map(u)}claimNextOperation(e,t=60000,r){let i=this.now(),a=new Date(this.nowFn().getTime()+t).toISOString();return this.transaction(()=>{let E=r?.length?`AND kind IN (${le(r.length)})`:"",T=r?[...r]:[],s=this.database.query(`SELECT * FROM operations WHERE state = 'queued' ${E} ORDER BY priority DESC, created_at ASC, id ASC LIMIT 1`).get(...T);if(!s)return;let c=u(s);if(o(this.database,`UPDATE operations SET state = 'running', attempt = attempt + 1, lease_owner = ?, lease_expires_at = ?,
1490
1490
  started_at = COALESCE(started_at, ?), updated_at = ?, version = version + 1 WHERE id = ? AND state = 'queued' AND version = ?`,[e,a,i,i,c.id,c.version]).changes!==1)return;return this.appendEvent({projectId:c.projectId,operationId:c.id,resourceId:c.resourceId,actorId:c.actorId,correlationId:c.correlationId,type:"operation.running",payload:{attempt:c.attempt+1,workerId:e}}),this.getOperation(c.id)})}claimOperation(e,t,r=60000){let i=this.now(),a=new Date(this.nowFn().getTime()+r).toISOString();return this.transaction(()=>{let E=this.getOperation(e);if(!E||E.state!=="queued")return;if(o(this.database,`UPDATE operations SET state = 'running', attempt = attempt + 1, lease_owner = ?, lease_expires_at = ?,
@@ -1504,4 +1504,4 @@ import{A}from"./chunk-24njmb7d.js";var oe=["project:read","config:read","config:
1504
1504
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i.id,i.organizationId,i.membershipId,i.effect,i.capability,i.scope.type,i.scope.id??null,i.source??"manual",i.createdAt,i.updatedAt]);for(let i of e.operations)o(this.database,`INSERT INTO operations (id, project_id, environment_id, resource_id, actor_id, kind, state, correlation_id, idempotency_key,
1505
1505
  input, output, error, attempt, priority, lease_owner, lease_expires_at, cancel_requested_at, started_at, finished_at, version, created_at, updated_at)
1506
1506
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i.id,i.projectId??null,i.environmentId??null,i.resourceId??null,i.actorId??null,i.kind,i.state,i.correlationId,i.idempotencyKey??null,N(i.input),N(i.output),M(i.error)??null,i.attempt,i.priority,i.leaseOwner??null,i.leaseExpiresAt??null,i.cancelRequestedAt??null,i.startedAt??null,i.finishedAt??null,i.version,i.createdAt,i.updatedAt]);for(let i of e.events)o(this.database,`INSERT INTO events (sequence, id, organization_id, project_id, operation_id, resource_id, actor_id, correlation_id, type, level, payload, created_at)
1507
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i.sequence,i.id,i.organizationId??null,i.projectId??null,i.operationId??null,i.resourceId??null,i.actorId??null,i.correlationId,i.type,i.level,N(i.payload),i.createdAt]);for(let[i,a]of Object.entries(e.settings))o(this.database,"INSERT INTO settings (key, value, updated_at) VALUES (?, ?, ?)",[i,N(a),this.now()]);for(let i of e.tags??[])o(this.database,"INSERT INTO tags (id, project_id, name, normalized_name, color, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[i.id,i.projectId,i.name,i.normalizedName,i.color,i.createdAt,i.updatedAt]);for(let i of e.resourceTags??[])o(this.database,"INSERT INTO resource_tags (resource_id, tag_id, created_at) VALUES (?, ?, ?)",[i.resourceId,i.tagId,i.createdAt]);for(let i of e.savedFilters??[])o(this.database,"INSERT INTO saved_filters (id, actor_key, name, route_id, query, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[i.id,i.actorKey,i.name,i.routeId,N(i.query),i.createdAt,i.updatedAt]);for(let i of e.navigationItems??[])o(this.database,"INSERT INTO navigation_items (actor_key, entity_type, entity_id, favorite, last_visited_at, visit_count) VALUES (?, ?, ?, ?, ?, ?)",[i.actorKey,i.entityType,i.entityId,i.favorite?1:0,i.lastVisitedAt,i.visitCount])})}}var pe=new Set(["domain","domains","hostname","hostnames","url","repository","repo","image","label","labels"]),ue=new Set(["sha","commit","commitsha","release","releaseid"]);function ae(e,t){if(!e||typeof e!=="object"||Array.isArray(e))return[];let r=[];for(let[i,a]of Object.entries(e)){if(!t.has(i.toLowerCase()))continue;if(typeof a==="string")r.push(a);else if(Array.isArray(a))r.push(...a.filter((E)=>typeof E==="string"))}return r}function Q(e){return e.toLowerCase().trim().replace(/[^a-z0-9._:/@-]+/g," ")}function W(e,t,r){let i=Q(e),a=Q(t),E=Q(r);if(!i)return 0;if(a===i)return 1000;if(a.startsWith(i))return 800-Math.min(100,a.length-i.length);if(a.includes(i))return 650-Math.min(100,a.indexOf(i));let T=i.split(/\s+/).filter(Boolean);if(T.every((c)=>E.includes(c)))return 400+T.length*10;let s=0;for(let c of i){if(s=E.indexOf(c,s),s<0)return 0;s++}return Math.max(1,180-Math.floor(E.length/20))}function Ce(e,t){let r=e.kind.toLowerCase();if(r==="server"||r==="compute")return{type:"server",href:`/server/metrics?env=${encodeURIComponent(t)}`};if(r.includes("database")||["mysql","postgres","postgresql","sqlite","redis"].includes(r))return{type:"database",href:`/server/database?env=${encodeURIComponent(t)}&database=${encodeURIComponent(e.slug)}`};return{type:"service",href:`/server/sites?env=${encodeURIComponent(t)}&service=${encodeURIComponent(e.slug)}`}}function Vs(e,t){let r=e.getProject(t.projectId);if(!r)return[];let i=e.listEnvironments(r.id),a=new Map(i.map((n)=>[n.id,n])),E=e.listResourceTags(r.id),T=new Map;for(let n of E){let L=T.get(n.resourceId)??[];L.push({id:n.tag.id,name:n.tag.name,color:n.tag.color}),T.set(n.resourceId,L)}let s=[],c=t.allowedResourceSlugs!==void 0;if(!c){s.push({type:"project",id:r.id,title:r.name,subtitle:r.slug,href:`/?project=${encodeURIComponent(r.slug)}`,tags:[],score:0});for(let n of i)s.push({type:"environment",id:n.id,title:n.name,subtitle:`${r.name} · ${n.kind}`,href:`/?env=${encodeURIComponent(n.slug)}`,environment:n.slug,tags:[],score:0})}let V=e.listResources(r.id).filter((n)=>!t.allowedResourceSlugs||t.allowedResourceSlugs.has(n.slug));for(let n of V){let L=n.environmentId?a.get(n.environmentId):void 0,C=T.get(n.id)??[],U=ae(n.desiredState,pe),m=[n.name,n.slug,n.kind,n.provider,n.providerId,L?.slug,...U,...C.map((ne)=>ne.name)].filter(Boolean).join(" "),X=Ce(n,L?.slug??i[0]?.slug??"");s.push({type:X.type,id:n.id,title:n.name,subtitle:[n.kind,...U.slice(0,2)].join(" · "),href:X.href,environment:L?.slug,provider:n.provider,tags:C,score:W(t.query,n.name,m)})}if(!c)for(let n of e.listOperations({projectId:r.id,limit:500})){let L=n.environmentId?a.get(n.environmentId):void 0,C=ae(n.input,ue),U=n.kind.includes("deploy"),m=C[0]??n.kind,X=[n.kind,n.id,n.correlationId,n.state,...C].join(" ");s.push({type:U?"deployment":"operation",id:n.id,title:m,subtitle:`${n.kind} · ${n.state}`,href:`/server/activity?env=${encodeURIComponent(L?.slug??i[0]?.slug??"")}&operation=${encodeURIComponent(n.id)}`,environment:L?.slug,status:n.state,tags:[],score:W(t.query,m,X)})}for(let n of s)if(n.score===0)n.score=W(t.query,n.title,`${n.title} ${n.subtitle} ${n.environment??""} ${n.provider??""}`);let J={service:0,server:1,database:2,deployment:3,environment:4,project:5,operation:6};return s.filter((n)=>n.score>0).sort((n,L)=>L.score-n.score||J[n.type]-J[L.type]||n.title.localeCompare(L.title)||n.id.localeCompare(L.id)).slice(0,Math.min(50,Math.max(1,t.limit??20)))}export{oe,nn,ee,on,h,Ar,Vs};
1507
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i.sequence,i.id,i.organizationId??null,i.projectId??null,i.operationId??null,i.resourceId??null,i.actorId??null,i.correlationId,i.type,i.level,N(i.payload),i.createdAt]);for(let[i,a]of Object.entries(e.settings))o(this.database,"INSERT INTO settings (key, value, updated_at) VALUES (?, ?, ?)",[i,N(a),this.now()]);for(let i of e.tags??[])o(this.database,"INSERT INTO tags (id, project_id, name, normalized_name, color, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[i.id,i.projectId,i.name,i.normalizedName,i.color,i.createdAt,i.updatedAt]);for(let i of e.resourceTags??[])o(this.database,"INSERT INTO resource_tags (resource_id, tag_id, created_at) VALUES (?, ?, ?)",[i.resourceId,i.tagId,i.createdAt]);for(let i of e.savedFilters??[])o(this.database,"INSERT INTO saved_filters (id, actor_key, name, route_id, query, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[i.id,i.actorKey,i.name,i.routeId,N(i.query),i.createdAt,i.updatedAt]);for(let i of e.navigationItems??[])o(this.database,"INSERT INTO navigation_items (actor_key, entity_type, entity_id, favorite, last_visited_at, visit_count) VALUES (?, ?, ?, ?, ?, ?)",[i.actorKey,i.entityType,i.entityId,i.favorite?1:0,i.lastVisitedAt,i.visitCount])})}}var pe=new Set(["domain","domains","hostname","hostnames","url","repository","repo","image","label","labels"]),ue=new Set(["sha","commit","commitsha","release","releaseid"]);function ae(e,t){if(!e||typeof e!=="object"||Array.isArray(e))return[];let r=[];for(let[i,a]of Object.entries(e)){if(!t.has(i.toLowerCase()))continue;if(typeof a==="string")r.push(a);else if(Array.isArray(a))r.push(...a.filter((E)=>typeof E==="string"))}return r}function Q(e){return e.toLowerCase().trim().replace(/[^a-z0-9._:/@-]+/g," ")}function W(e,t,r){let i=Q(e),a=Q(t),E=Q(r);if(!i)return 0;if(a===i)return 1000;if(a.startsWith(i))return 800-Math.min(100,a.length-i.length);if(a.includes(i))return 650-Math.min(100,a.indexOf(i));let T=i.split(/\s+/).filter(Boolean);if(T.every((c)=>E.includes(c)))return 400+T.length*10;let s=0;for(let c of i){if(s=E.indexOf(c,s),s<0)return 0;s++}return Math.max(1,180-Math.floor(E.length/20))}function Ce(e,t){let r=e.kind.toLowerCase();if(r==="server"||r==="compute")return{type:"server",href:`/server/metrics?env=${encodeURIComponent(t)}`};if(r.includes("database")||["mysql","postgres","postgresql","sqlite","redis"].includes(r))return{type:"database",href:`/server/database?env=${encodeURIComponent(t)}&database=${encodeURIComponent(e.slug)}`};return{type:"service",href:`/server/sites?env=${encodeURIComponent(t)}&service=${encodeURIComponent(e.slug)}`}}function Hs(e,t){let r=e.getProject(t.projectId);if(!r)return[];let i=e.listEnvironments(r.id),a=new Map(i.map((n)=>[n.id,n])),E=e.listResourceTags(r.id),T=new Map;for(let n of E){let L=T.get(n.resourceId)??[];L.push({id:n.tag.id,name:n.tag.name,color:n.tag.color}),T.set(n.resourceId,L)}let s=[],c=t.allowedResourceSlugs!==void 0;if(!c){s.push({type:"project",id:r.id,title:r.name,subtitle:r.slug,href:`/?project=${encodeURIComponent(r.slug)}`,tags:[],score:0});for(let n of i)s.push({type:"environment",id:n.id,title:n.name,subtitle:`${r.name} · ${n.kind}`,href:`/?env=${encodeURIComponent(n.slug)}`,environment:n.slug,tags:[],score:0})}let V=e.listResources(r.id).filter((n)=>!t.allowedResourceSlugs||t.allowedResourceSlugs.has(n.slug));for(let n of V){let L=n.environmentId?a.get(n.environmentId):void 0,C=T.get(n.id)??[],U=ae(n.desiredState,pe),m=[n.name,n.slug,n.kind,n.provider,n.providerId,L?.slug,...U,...C.map((ne)=>ne.name)].filter(Boolean).join(" "),X=Ce(n,L?.slug??i[0]?.slug??"");s.push({type:X.type,id:n.id,title:n.name,subtitle:[n.kind,...U.slice(0,2)].join(" · "),href:X.href,environment:L?.slug,provider:n.provider,tags:C,score:W(t.query,n.name,m)})}if(!c)for(let n of e.listOperations({projectId:r.id,limit:500})){let L=n.environmentId?a.get(n.environmentId):void 0,C=ae(n.input,ue),U=n.kind.includes("deploy"),m=C[0]??n.kind,X=[n.kind,n.id,n.correlationId,n.state,...C].join(" ");s.push({type:U?"deployment":"operation",id:n.id,title:m,subtitle:`${n.kind} · ${n.state}`,href:`/server/activity?env=${encodeURIComponent(L?.slug??i[0]?.slug??"")}&operation=${encodeURIComponent(n.id)}`,environment:L?.slug,status:n.state,tags:[],score:W(t.query,m,X)})}for(let n of s)if(n.score===0)n.score=W(t.query,n.title,`${n.title} ${n.subtitle} ${n.environment??""} ${n.provider??""}`);let J={service:0,server:1,database:2,deployment:3,environment:4,project:5,operation:6};return s.filter((n)=>n.score>0).sort((n,L)=>L.score-n.score||J[n.type]-J[L.type]||n.title.localeCompare(L.title)||n.id.localeCompare(L.id)).slice(0,Math.min(50,Math.max(1,t.limit??20)))}export{se,on,te,sn,h,Ir,Hs};
@@ -1,5 +1,5 @@
1
- import{mi,u}from"./chunk-mbqwrs7a.js";import{pi}from"./chunk-rm6qnyce.js";import*as c from"node:crypto";import{readFileSync as B}from"node:fs";import{readdir as L}from"node:fs/promises";import{join as z}from"node:path";function vt(e){if(e){let i=D(e);if(!i)throw Error(`AWS profile '${e}' not found in ~/.aws/credentials`);return i}let t=process.env.AWS_ACCESS_KEY_ID,s=process.env.AWS_SECRET_ACCESS_KEY;if(t&&s)return{accessKeyId:t,secretAccessKey:s,sessionToken:process.env.AWS_SESSION_TOKEN};return D(process.env.AWS_PROFILE||"default")??{accessKeyId:"",secretAccessKey:""}}function D(e){let{existsSync:t,readFileSync:s}=pi("node:fs"),{homedir:i}=pi("node:os"),{join:n}=pi("node:path"),r=process.env.AWS_SHARED_CREDENTIALS_FILE||n(i(),".aws","credentials");if(!t(r))return null;let o=s(r,"utf-8"),a=null,l,d,y;for(let h of o.split(`
2
- `)){let m=h.trim();if(!m||m.startsWith("#")||m.startsWith(";"))continue;let p=m.match(/^\[([^\]]+)\]$/);if(p){if(a===e&&l&&d)return{accessKeyId:l,secretAccessKey:d,sessionToken:y};a=p[1],l=void 0,d=void 0,y=void 0;continue}if(a===e){let[b,...S]=m.split("="),f=S.join("=").trim();switch(b.trim().toLowerCase()){case"aws_access_key_id":l=f;break;case"aws_secret_access_key":d=f;break;case"aws_session_token":y=f;break}}}if(a===e&&l&&d)return{accessKeyId:l,secretAccessKey:d,sessionToken:y};return null}function U(e){let{buffer:t,byteOffset:s,byteLength:i}=e;if(t instanceof ArrayBuffer)return t.slice(s,s+i);let n=new ArrayBuffer(i);return new Uint8Array(n).set(new Uint8Array(e)),n}function j(e,t){let s=e?.[t]??e;if(s===null||typeof s!=="object"||Array.isArray(s))return s;let i={...s};return delete i["@_xmlns"],i}class g{client;region;explicitProfile;endpoint;endpointProtocol="https";forcePathStyle;explicitCredentials;constructor(e="us-east-1",t,s){let i=typeof e==="string"?s:e,n=typeof e==="string"?e:e.region??"us-east-1",r=typeof e==="string"?t:e.profile,o=i?.endpoint?mi({region:n,path:"/",endpoint:i.endpoint}):void 0;this.region=n,this.explicitProfile=r,this.endpoint=o?.host,this.endpointProtocol=o?.protocol??"https",this.forcePathStyle=i?.forcePathStyle,this.explicitCredentials=i?.credentials,this.client=new u(i?.credentials,{profile:r,endpoint:i?.endpoint,forcePathStyle:i?.forcePathStyle})}getCredentials(){if(this.explicitCredentials?.accessKeyId&&this.explicitCredentials.secretAccessKey)return this.explicitCredentials;let e=vt(this.explicitProfile);if(e.accessKeyId&&e.secretAccessKey)return e;throw Error("S3 credentials not found. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY (or pass explicit credentials/profile), or configure ~/.aws/credentials.")}s3BaseHost(){return this.endpoint||`s3.${this.region}.amazonaws.com`}s3VirtualHost(e){return this.forcePathStyle?this.s3BaseHost():`${e}.${this.s3BaseHost()}`}objectPath(e,t){return this.forcePathStyle?`/${e}/${t}`:`/${t}`}objectUrl(e,t){return`${this.endpointProtocol}://${this.s3VirtualHost(e)}${this.objectPath(e,t)}`}async listBuckets(){let e=await this.client.request({service:"s3",region:this.region,method:"GET",path:"/"}),t=[],i=(e?.ListAllMyBucketsResult??e)?.Buckets?.Bucket;if(i){let n=Array.isArray(i)?i:[i];for(let r of n)t.push({Name:r.Name,CreationDate:r.CreationDate})}return{Buckets:t}}async createBucket(e,t){let s={};if(t?.acl)s["x-amz-acl"]=t.acl;let i;if(this.region!=="us-east-1"&&!this.endpoint)i=`<?xml version="1.0" encoding="UTF-8"?>
1
+ import{gi,u}from"./chunk-q3xwh0r8.js";import{mi}from"./chunk-z5ycwy38.js";import*as c from"node:crypto";import{readFileSync as B}from"node:fs";import{readdir as L}from"node:fs/promises";import{join as z}from"node:path";function vt(e){if(e){let i=D(e);if(!i)throw Error(`AWS profile '${e}' not found in ~/.aws/credentials`);return i}let t=process.env.AWS_ACCESS_KEY_ID,s=process.env.AWS_SECRET_ACCESS_KEY;if(t&&s)return{accessKeyId:t,secretAccessKey:s,sessionToken:process.env.AWS_SESSION_TOKEN};return D(process.env.AWS_PROFILE||"default")??{accessKeyId:"",secretAccessKey:""}}function D(e){let{existsSync:t,readFileSync:s}=mi("node:fs"),{homedir:i}=mi("node:os"),{join:n}=mi("node:path"),r=process.env.AWS_SHARED_CREDENTIALS_FILE||n(i(),".aws","credentials");if(!t(r))return null;let o=s(r,"utf-8"),a=null,l,d,y;for(let h of o.split(`
2
+ `)){let m=h.trim();if(!m||m.startsWith("#")||m.startsWith(";"))continue;let p=m.match(/^\[([^\]]+)\]$/);if(p){if(a===e&&l&&d)return{accessKeyId:l,secretAccessKey:d,sessionToken:y};a=p[1],l=void 0,d=void 0,y=void 0;continue}if(a===e){let[b,...S]=m.split("="),f=S.join("=").trim();switch(b.trim().toLowerCase()){case"aws_access_key_id":l=f;break;case"aws_secret_access_key":d=f;break;case"aws_session_token":y=f;break}}}if(a===e&&l&&d)return{accessKeyId:l,secretAccessKey:d,sessionToken:y};return null}function U(e){let{buffer:t,byteOffset:s,byteLength:i}=e;if(t instanceof ArrayBuffer)return t.slice(s,s+i);let n=new ArrayBuffer(i);return new Uint8Array(n).set(new Uint8Array(e)),n}function j(e,t){let s=e?.[t]??e;if(s===null||typeof s!=="object"||Array.isArray(s))return s;let i={...s};return delete i["@_xmlns"],i}class g{client;region;explicitProfile;endpoint;endpointProtocol="https";forcePathStyle;explicitCredentials;constructor(e="us-east-1",t,s){let i=typeof e==="string"?s:e,n=typeof e==="string"?e:e.region??"us-east-1",r=typeof e==="string"?t:e.profile,o=i?.endpoint?gi({region:n,path:"/",endpoint:i.endpoint}):void 0;this.region=n,this.explicitProfile=r,this.endpoint=o?.host,this.endpointProtocol=o?.protocol??"https",this.forcePathStyle=i?.forcePathStyle,this.explicitCredentials=i?.credentials,this.client=new u(i?.credentials,{profile:r,endpoint:i?.endpoint,forcePathStyle:i?.forcePathStyle})}getCredentials(){if(this.explicitCredentials?.accessKeyId&&this.explicitCredentials.secretAccessKey)return this.explicitCredentials;let e=vt(this.explicitProfile);if(e.accessKeyId&&e.secretAccessKey)return e;throw Error("S3 credentials not found. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY (or pass explicit credentials/profile), or configure ~/.aws/credentials.")}s3BaseHost(){return this.endpoint||`s3.${this.region}.amazonaws.com`}s3VirtualHost(e){return this.forcePathStyle?this.s3BaseHost():`${e}.${this.s3BaseHost()}`}objectPath(e,t){return this.forcePathStyle?`/${e}/${t}`:`/${t}`}objectUrl(e,t){return`${this.endpointProtocol}://${this.s3VirtualHost(e)}${this.objectPath(e,t)}`}async listBuckets(){let e=await this.client.request({service:"s3",region:this.region,method:"GET",path:"/"}),t=[],i=(e?.ListAllMyBucketsResult??e)?.Buckets?.Bucket;if(i){let n=Array.isArray(i)?i:[i];for(let r of n)t.push({Name:r.Name,CreationDate:r.CreationDate})}return{Buckets:t}}async createBucket(e,t){let s={};if(t?.acl)s["x-amz-acl"]=t.acl;let i;if(this.region!=="us-east-1"&&!this.endpoint)i=`<?xml version="1.0" encoding="UTF-8"?>
3
3
  <CreateBucketConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
4
4
  <LocationConstraint>${this.region}</LocationConstraint>
5
5
  </CreateBucketConfiguration>`,s["Content-Type"]="application/xml";await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,headers:s,body:i})}async deleteBucket(e){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${e}`})}async emptyAndDeleteBucket(e){let t=!0;while(t){let s=await this.listAllObjects({bucket:e});if(s.length===0){t=!1;break}let i=s.map((n)=>n.Key);for(let n=0;n<i.length;n+=1000){let r=i.slice(n,n+1000);await this.deleteObjects(e,r)}}await this.deleteBucket(e)}async listAllObjects(e){let t=[],s;do{let i={"list-type":"2","max-keys":"1000"};if(e.prefix)i.prefix=e.prefix;if(s)i["continuation-token"]=s;let n=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e.bucket}`,queryParams:i}),r=n?.ListBucketResult??n,o=r?.Contents;if(o){let l=Array.isArray(o)?o:[o];for(let d of l)t.push({Key:d.Key,LastModified:d.LastModified||"",Size:Number.parseInt(d.Size||"0"),ETag:d.ETag})}let a=r?.IsTruncated;s=a==="true"||a===!0?r?.NextContinuationToken:void 0}while(s);return t}async list(e){let t=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e.bucket}`}),s=[],n=(t?.ListBucketResult??t)?.Contents;if(n){let r=Array.isArray(n)?n:[n];for(let o of r){if(e.prefix&&!o.Key?.startsWith(e.prefix))continue;if(s.push({Key:o.Key||"",LastModified:o.LastModified||"",Size:Number.parseInt(o.Size||"0"),ETag:o.ETag}),e.maxKeys&&s.length>=e.maxKeys)break}}return s}async putObject(e){let t={};if(e.acl)t["x-amz-acl"]=e.acl;if(e.cacheControl)t["Cache-Control"]=e.cacheControl;if(e.contentType)t["Content-Type"]=e.contentType;if(e.metadata)for(let[n,r]of Object.entries(e.metadata))t[`x-amz-meta-${n}`]=r;let s=e.key.split("/").map((n)=>encodeURIComponent(n)).join("/"),i=e.body instanceof Uint8Array&&!Buffer.isBuffer(e.body)?Buffer.from(e.body):e.body;if(Buffer.isBuffer(i)||i instanceof Uint8Array){let n=Buffer.isBuffer(i)?i:Buffer.from(i),{accessKeyId:r,secretAccessKey:o,sessionToken:a}=this.getCredentials(),l=this.s3VirtualHost(e.bucket),d=this.objectPath(e.bucket,s),y=this.objectUrl(e.bucket,s),h=new Date,m=h.toISOString().replace(/[:-]|\.\d{3}/g,""),p=h.toISOString().slice(0,10).replace(/-/g,""),b=c.createHash("sha256").update(n).digest("hex"),S={host:l,"x-amz-date":m,"x-amz-content-sha256":b,...t};if(a)S["x-amz-security-token"]=a;let f=Object.keys(S).sort().map((P)=>`${P.toLowerCase()}:${S[P].trim()}