@stacksjs/ts-cloud 0.12.13 → 0.12.14

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 (118) hide show
  1. package/dist/aws/index.js +1 -1
  2. package/dist/bin/{chunk-bnv8yd9w.js → chunk-16rs9egs.js} +1 -1
  3. package/dist/bin/{chunk-w7k5rvmw.js → chunk-1rcsm0px.js} +1 -1
  4. package/dist/bin/{chunk-nnkhrm4n.js → chunk-1wvrtg42.js} +2 -2
  5. package/dist/bin/{chunk-96xtj5j6.js → chunk-1x7mm26k.js} +1 -1
  6. package/dist/bin/{chunk-7h6h8yxm.js → chunk-2paqksap.js} +3 -3
  7. package/dist/bin/{chunk-2hpnd4g4.js → chunk-3gwmejhk.js} +1 -1
  8. package/dist/bin/{chunk-jcyrm5q0.js → chunk-4201mvaj.js} +1 -1
  9. package/dist/bin/chunk-61ysn56t.js +1 -0
  10. package/dist/bin/{chunk-d5qhwtkg.js → chunk-6vay4ggv.js} +4 -4
  11. package/dist/bin/{chunk-xgepx8yx.js → chunk-92nng29y.js} +1 -1
  12. package/dist/bin/{chunk-1fj5gk6r.js → chunk-9q8zjavc.js} +52 -52
  13. package/dist/bin/{chunk-5gehfky4.js → chunk-a929za72.js} +2 -2
  14. package/dist/bin/{chunk-6xw0r4gn.js → chunk-bj5nq0kn.js} +11 -11
  15. package/dist/bin/{chunk-13dhcjjb.js → chunk-dbmk60r7.js} +2 -2
  16. package/dist/bin/chunk-f1ke4ygp.js +1 -0
  17. package/dist/bin/{chunk-p9hd27k4.js → chunk-f8mbjwme.js} +1 -1
  18. package/dist/bin/{chunk-ymbwekjm.js → chunk-fnr6k11h.js} +1 -1
  19. package/dist/bin/chunk-mzfct5en.js +1 -0
  20. package/dist/bin/{chunk-6zk2n3wk.js → chunk-n6qqa2fr.js} +29 -29
  21. package/dist/bin/{chunk-wvhqjr80.js → chunk-ngav845g.js} +2 -2
  22. package/dist/bin/{chunk-jh1593zx.js → chunk-nrnq9adz.js} +1 -1
  23. package/dist/bin/{chunk-84tvv3x1.js → chunk-pega3x2x.js} +1 -1
  24. package/dist/bin/{chunk-55kmbzr5.js → chunk-pt2bz3kr.js} +1 -1
  25. package/dist/bin/chunk-q5aj280b.js +1 -0
  26. package/dist/bin/{chunk-0vsxpmfj.js → chunk-rpg5k3wt.js} +2 -2
  27. package/dist/bin/{chunk-dh2qmxw9.js → chunk-vwyq2s2k.js} +1 -1
  28. package/dist/bin/{chunk-x5x9dzk7.js → chunk-w637s5q0.js} +1 -1
  29. package/dist/bin/{chunk-gj5jkhfr.js → chunk-wr6a423y.js} +3 -3
  30. package/dist/bin/{chunk-9jfjzycs.js → chunk-y7ece16e.js} +10 -10
  31. package/dist/bin/{chunk-12e9v1dw.js → chunk-ydpnsp4x.js} +1 -1
  32. package/dist/bin/cli.js +76 -76
  33. package/dist/bin/dashboard-server.js +1 -1
  34. package/dist/{chunk-edqhhcg9.js → chunk-5g1hsrab.js} +3 -3
  35. package/dist/chunk-5qqb671d.js +1 -0
  36. package/dist/{chunk-zmyv76f0.js → chunk-5ww7kc5z.js} +4 -4
  37. package/dist/{chunk-sct6mdgc.js → chunk-6j8f4ahv.js} +16 -16
  38. package/dist/{chunk-3qp10j0j.js → chunk-7hy9p6xr.js} +3 -3
  39. package/dist/{chunk-tnjae324.js → chunk-7kwha0fw.js} +61 -61
  40. package/dist/{chunk-g8fpsdyq.js → chunk-9mhcjht7.js} +4 -4
  41. package/dist/{chunk-wpqj98h8.js → chunk-bqaqkmtr.js} +2 -2
  42. package/dist/{chunk-7ww65b66.js → chunk-djd9xgkz.js} +70 -70
  43. package/dist/{chunk-1kp3y2s7.js → chunk-hw3p6pth.js} +1 -1
  44. package/dist/{chunk-emg3shmb.js → chunk-pkan6evc.js} +2 -2
  45. package/dist/{chunk-13d54txj.js → chunk-qzwack6w.js} +2 -2
  46. package/dist/{chunk-9c29rnk3.js → chunk-ttq6dvft.js} +7 -7
  47. package/dist/chunk-vpy3zjqv.js +1 -0
  48. package/dist/{chunk-ej4sm2tw.js → chunk-vva43vnp.js} +5 -5
  49. package/dist/{chunk-1n3ckctd.js → chunk-xxbvjq8g.js} +22 -22
  50. package/dist/deploy/index.js +1 -1
  51. package/dist/dns/index.js +1 -1
  52. package/dist/drivers/index.js +1 -1
  53. package/dist/index.d.ts +1 -1
  54. package/dist/index.js +19 -19
  55. package/dist/operations/index.js +1 -1
  56. package/dist/protection/index.js +1 -1
  57. package/dist/spend/index.js +1 -1
  58. package/dist/ui/404.html +1 -1
  59. package/dist/ui/accept-invitation.html +1 -1
  60. package/dist/ui/access-denied.html +1 -1
  61. package/dist/ui/account/automation.html +6 -6
  62. package/dist/ui/account/security.html +2 -2
  63. package/dist/ui/applications/compose.html +6 -6
  64. package/dist/ui/applications/new.html +1 -1
  65. package/dist/ui/data/backups.html +6 -6
  66. package/dist/ui/data/services.html +6 -6
  67. package/dist/ui/data/volumes.html +6 -6
  68. package/dist/ui/index.html +6 -6
  69. package/dist/ui/infrastructure/topology.html +6 -6
  70. package/dist/ui/integrations.html +2 -2
  71. package/dist/ui/operations/alerts.html +6 -6
  72. package/dist/ui/operations/configuration.html +6 -6
  73. package/dist/ui/operations/jobs.html +6 -6
  74. package/dist/ui/operations/maintenance.html +6 -6
  75. package/dist/ui/operations/observability.html +6 -6
  76. package/dist/ui/operations/previews.html +5 -5
  77. package/dist/ui/operations/queue.html +6 -6
  78. package/dist/ui/operations/regions.html +6 -6
  79. package/dist/ui/operations/releases.html +6 -6
  80. package/dist/ui/operations/spend.html +6 -6
  81. package/dist/ui/operations/workloads.html +6 -6
  82. package/dist/ui/security.html +2 -2
  83. package/dist/ui/server/actions.html +5 -5
  84. package/dist/ui/server/activity.html +2 -2
  85. package/dist/ui/server/capacity.html +5 -5
  86. package/dist/ui/server/database.html +5 -5
  87. package/dist/ui/server/deployments.html +6 -6
  88. package/dist/ui/server/diagnostics.html +1 -1
  89. package/dist/ui/server/firewall.html +6 -6
  90. package/dist/ui/server/fleet.html +6 -6
  91. package/dist/ui/server/logs.html +6 -6
  92. package/dist/ui/server/metrics.html +6 -6
  93. package/dist/ui/server/security.html +2 -2
  94. package/dist/ui/server/services.html +2 -2
  95. package/dist/ui/server/sites.html +5 -5
  96. package/dist/ui/server/ssh-keys.html +6 -6
  97. package/dist/ui/server/team.html +5 -5
  98. package/dist/ui/server/terminal.html +2 -2
  99. package/dist/ui/serverless/alarms.html +6 -6
  100. package/dist/ui/serverless/assets.html +2 -2
  101. package/dist/ui/serverless/cost.html +2 -2
  102. package/dist/ui/serverless/data.html +6 -6
  103. package/dist/ui/serverless/deployments.html +2 -2
  104. package/dist/ui/serverless/firewall.html +2 -2
  105. package/dist/ui/serverless/functions.html +6 -6
  106. package/dist/ui/serverless/logs.html +6 -6
  107. package/dist/ui/serverless/metrics.html +2 -2
  108. package/dist/ui/serverless/queues.html +5 -5
  109. package/dist/ui/serverless/secrets.html +6 -6
  110. package/dist/ui/serverless/traces.html +6 -6
  111. package/dist/ui/serverless.html +5 -5
  112. package/package.json +3 -3
  113. package/dist/bin/chunk-de88yqwy.js +0 -1
  114. package/dist/bin/chunk-qz3za76g.js +0 -1
  115. package/dist/bin/chunk-rxwecjgc.js +0 -1
  116. package/dist/bin/chunk-xaafj6kf.js +0 -1
  117. package/dist/chunk-7by4rm7y.js +0 -1
  118. package/dist/chunk-n688m5fp.js +0 -1
package/dist/aws/index.js CHANGED
@@ -1 +1 @@
1
- import{le,Jt,ji,zi,Hl,Aa,ya,Ki,Wi,Ia,ze,V,Ke,te,C,ue,rn,Sa,De,Ca,nn,sn,on,wm,Rm,PA,NA,kA,BA,At,xA,_A,OA,LA,yt,Dm,Pm,Nm,It,km,Bm,xm,an,$A,MA,FA,Xt,UA,QA,HA,ba,Ea,Gl,GA,qA,VA,Yt,_m,Om,Zt,We,cn,va,ql,jA,Vl,zA,St,KA,WA,JA,XA,re,YA,ZA,ey,ty,er,ry,ny,iy,dn,Ta,wa,jl,zl,Ra,tr}from"../chunk-zmyv76f0.js";import{pe,Je,ln,Lm}from"../chunk-thpce63q.js";import{y}from"../chunk-6g81m01r.js";import{Pe}from"../chunk-r5emv4x8.js";import{j}from"../chunk-zftpjxkr.js";import{un,Ne,Ct,bt,Et,pn,Xi,Yi,ge,Zi,es,ts,rs,ne,ns,is,ss,T,Da,gn,Pa,ie,rr}from"../chunk-emg3shmb.js";import{h}from"../chunk-wjgnfg6q.js";import{gr,Ie}from"../chunk-6nvn041c.js";import{f}from"../chunk-jb8em9ba.js";import{a}from"../chunk-3kapcdpn.js";import{mr,n,l,th}from"../chunk-30h9rgfn.js";export{ie as ACMClient,rr as ACMDnsValidator,n as AWSClient,va as ApplicationAutoScalingClient,Jt as AwsBackupClient,Rm as BedrockAgentClient,wm as BedrockAgentRuntimeClient,on as BedrockClient,sn as BedrockRuntimeClient,f as CloudFormationClient,y as CloudFrontClient,ue as CloudWatchLogsClient,bt as CloudflareProvider,At as ComprehendClient,rn as ConnectClient,Wi as CostExplorerClient,gn as DnsProviderFactory,De as DynamoDBClient,gr as EC2Client,Pe as ECRClient,ze as ECSClient,tr as EFSClient,Sa as ELBv2Client,We as ElastiCacheClient,ln as EmailClient,Zt as EventBridgeClient,Ct as GoDaddyProvider,pe as IAMClient,ql as ImapServer,Yt as KendraClient,C as LambdaClient,Ca as OpenSearchClient,un as PROXIABLE_RECORD_TYPES,ba as PersonalizeClient,Gl as PersonalizeEventsClient,Ea as PersonalizeRuntimeClient,an as PollyClient,Ne as PorkbunProvider,j as RDSClient,yt as RekognitionClient,h as Route53Client,Ia as Route53DomainsClient,ge as Route53Provider,a as S3Client,Je as SESClient,Ke as SNSClient,te as SQSClient,Ie as SSMClient,le as STSClient,cn as SchedulerClient,V as SecretsManagerClient,St as SmsClient,Ra as SmsVoiceClient,Vl as SmtpServer,dn as SupportClient,Ta as SupportTemplates,It as TextractClient,nn as TranscribeClient,Xt as TranslateClient,ne as UnifiedDnsValidator,er as VoiceClient,xA as analyzeSentiment,ts as applyZoneMigration,l as buildQueryParams,kA as completeWithClaude,LA as containsPii,Pm as countFacesInS3Image,XA as createDeliveryReceiptHandler,T as createDnsProvider,is as createGoDaddyValidator,Ki as createObjectStorageClient,ns as createPorkbunValidator,ny as createRecordingHandler,ss as createRoute53Validator,FA as createSSML,WA as createScheduledSmsHandler,JA as createSmsClient,KA as createSmsInboxHandler,zl as createSmsInfrastructure,iy as createVoiceClient,ry as createVoicemailHandler,th as detectCredentialSource,Da as detectDnsProvider,Dm as detectLabelsFromS3,OA as detectLanguage,Pa as dnsProviders,Lm as email,Zi as exportRoute53Zone,_A as extractEntities,Bm as extractFormsFromS3,xm as extractTablesFromS3,km as extractTextFromS3,YA as formatPhoneNumber,BA as generateEmbeddings,ey as getCountryCode,GA as getRecommendations,qA as getSimilarItems,jl as getSmsInfrastructureStatus,Nm as isContentSafe,ty as isSamePhoneNumber,ZA as isValidPhoneNumber,zi as keyMatchesFilters,NA as listClaudeModels,HA as listLanguages,MA as listVoices,Hl as migrateObjectStorage,re as normalizePhoneNumber,es as planZoneMigration,Et as policyTag,Aa as providerEndpoint,pn as qualifyName,Yi as reconcileDeclaredRecords,ji as remapKey,PA as requestModelAccess,Xi as resolveDeclaredRecords,ya as resolveObjectStorage,mr as resolveS3Endpoint,Om as retrieveForRag,_m as search,wa as setupSmsInfrastructure,jA as startImapServer,zA as startSmtpServer,$A as textToSpeech,VA as trackEvent,UA as translate,QA as translateToMultiple,rs as verifyZoneParity};
1
+ import{le,Jt,zi,Ki,Hl,ya,Ia,Wi,Ji,Sa,ze,V,Ke,te,C,ue,rn,Ca,De,ba,nn,sn,on,wm,Rm,PA,NA,kA,BA,At,xA,_A,OA,LA,yt,Dm,Pm,Nm,It,km,Bm,xm,an,$A,MA,FA,Xt,UA,QA,HA,Ea,va,Gl,GA,qA,VA,Yt,_m,Om,Zt,We,cn,Ta,ql,jA,Vl,zA,St,KA,WA,JA,XA,re,YA,ZA,ey,ty,er,ry,ny,iy,dn,wa,Ra,jl,zl,Da,tr}from"../chunk-5ww7kc5z.js";import{pe,Je,ln,Lm}from"../chunk-thpce63q.js";import{y}from"../chunk-6g81m01r.js";import{Pe}from"../chunk-r5emv4x8.js";import{j}from"../chunk-zftpjxkr.js";import{un,Ne,Ct,bt,Et,pn,Yi,Zi,ge,es,ts,rs,ns,ne,is,ss,os,T,Pa,gn,Na,ie,rr}from"../chunk-pkan6evc.js";import{h}from"../chunk-wjgnfg6q.js";import{gr,Ie}from"../chunk-6nvn041c.js";import{f}from"../chunk-jb8em9ba.js";import{a}from"../chunk-3kapcdpn.js";import{mr,n,l,th}from"../chunk-30h9rgfn.js";export{ie as ACMClient,rr as ACMDnsValidator,n as AWSClient,Ta as ApplicationAutoScalingClient,Jt as AwsBackupClient,Rm as BedrockAgentClient,wm as BedrockAgentRuntimeClient,on as BedrockClient,sn as BedrockRuntimeClient,f as CloudFormationClient,y as CloudFrontClient,ue as CloudWatchLogsClient,bt as CloudflareProvider,At as ComprehendClient,rn as ConnectClient,Ji as CostExplorerClient,gn as DnsProviderFactory,De as DynamoDBClient,gr as EC2Client,Pe as ECRClient,ze as ECSClient,tr as EFSClient,Ca as ELBv2Client,We as ElastiCacheClient,ln as EmailClient,Zt as EventBridgeClient,Ct as GoDaddyProvider,pe as IAMClient,ql as ImapServer,Yt as KendraClient,C as LambdaClient,ba as OpenSearchClient,un as PROXIABLE_RECORD_TYPES,Ea as PersonalizeClient,Gl as PersonalizeEventsClient,va as PersonalizeRuntimeClient,an as PollyClient,Ne as PorkbunProvider,j as RDSClient,yt as RekognitionClient,h as Route53Client,Sa as Route53DomainsClient,ge as Route53Provider,a as S3Client,Je as SESClient,Ke as SNSClient,te as SQSClient,Ie as SSMClient,le as STSClient,cn as SchedulerClient,V as SecretsManagerClient,St as SmsClient,Da as SmsVoiceClient,Vl as SmtpServer,dn as SupportClient,wa as SupportTemplates,It as TextractClient,nn as TranscribeClient,Xt as TranslateClient,ne as UnifiedDnsValidator,er as VoiceClient,xA as analyzeSentiment,rs as applyZoneMigration,l as buildQueryParams,kA as completeWithClaude,LA as containsPii,Pm as countFacesInS3Image,XA as createDeliveryReceiptHandler,T as createDnsProvider,ss as createGoDaddyValidator,Wi as createObjectStorageClient,is as createPorkbunValidator,ny as createRecordingHandler,os as createRoute53Validator,FA as createSSML,WA as createScheduledSmsHandler,JA as createSmsClient,KA as createSmsInboxHandler,zl as createSmsInfrastructure,iy as createVoiceClient,ry as createVoicemailHandler,th as detectCredentialSource,Pa as detectDnsProvider,Dm as detectLabelsFromS3,OA as detectLanguage,Na as dnsProviders,Lm as email,es as exportRoute53Zone,_A as extractEntities,Bm as extractFormsFromS3,xm as extractTablesFromS3,km as extractTextFromS3,YA as formatPhoneNumber,BA as generateEmbeddings,ey as getCountryCode,GA as getRecommendations,qA as getSimilarItems,jl as getSmsInfrastructureStatus,Nm as isContentSafe,ty as isSamePhoneNumber,ZA as isValidPhoneNumber,Ki as keyMatchesFilters,NA as listClaudeModels,HA as listLanguages,MA as listVoices,Hl as migrateObjectStorage,re as normalizePhoneNumber,ts as planZoneMigration,Et as policyTag,ya as providerEndpoint,pn as qualifyName,Zi as reconcileDeclaredRecords,zi as remapKey,PA as requestModelAccess,Yi as resolveDeclaredRecords,Ia as resolveObjectStorage,mr as resolveS3Endpoint,Om as retrieveForRag,_m as search,Ra as setupSmsInfrastructure,jA as startImapServer,zA as startSmtpServer,$A as textToSpeech,VA as trackEvent,UA as translate,QA as translateToMultiple,ns as verifyZoneParity};
@@ -1,4 +1,4 @@
1
- import{Ke,A,Ft,Cr,hi}from"./chunk-6xw0r4gn.js";import{execSync as D}from"node:child_process";import{randomBytes as R}from"node:crypto";import{chmodSync as j,copyFileSync as x,existsSync as u,mkdirSync as w,readFileSync as U,statSync as N,writeFileSync as m}from"node:fs";import{tmpdir as E}from"node:os";import{basename as P,dirname as v,isAbsolute as O,join as a,resolve as B}from"node:path";import{fileURLToPath as C}from"node:url";function h(e){if(!e||typeof e!=="object")return e;return Object.fromEntries(Object.keys(e).map((r)=>[r,""]))}function M(e){let r=JSON.parse(JSON.stringify(e??{}));if(r.hetzner)delete r.hetzner.apiToken;delete r.aws,delete r.stateDir;for(let t of Object.values(r.sites??{})){if(t?.env)t.env=h(t.env);if(t?.environment)t.environment=h(t.environment)}for(let t of Object.values(r.environments??{}))if(t?.variables)t.variables=h(t.variables);for(let t of Object.values(r.infrastructure?.databases??{}))if(t?.password)t.password="";if(r.infrastructure?.appDatabase?.password)r.infrastructure.appDatabase.password="";if(r.infrastructure?.compute?.database?.password)r.infrastructure.compute.database.password="";if(r.infrastructure?.compute?.managedServices?.vitess?.password)r.infrastructure.compute.managedServices.vitess.password="";return r}function y(e){let r=M(e);return["// Generated by ts-cloud for the management dashboard — do not edit.","//","// This is the project's resolved cloud config, inlined so it needs no","// imports on the box. Credentials are deliberately absent.",`export default ${JSON.stringify(r,null,2)}`,""].join(`
1
+ import{Ke,A,Ft,Cr,hi}from"./chunk-bj5nq0kn.js";import{execSync as D}from"node:child_process";import{randomBytes as R}from"node:crypto";import{chmodSync as j,copyFileSync as x,existsSync as u,mkdirSync as w,readFileSync as U,statSync as N,writeFileSync as m}from"node:fs";import{tmpdir as E}from"node:os";import{basename as P,dirname as v,isAbsolute as O,join as a,resolve as B}from"node:path";import{fileURLToPath as C}from"node:url";function h(e){if(!e||typeof e!=="object")return e;return Object.fromEntries(Object.keys(e).map((r)=>[r,""]))}function M(e){let r=JSON.parse(JSON.stringify(e??{}));if(r.hetzner)delete r.hetzner.apiToken;delete r.aws,delete r.stateDir;for(let t of Object.values(r.sites??{})){if(t?.env)t.env=h(t.env);if(t?.environment)t.environment=h(t.environment)}for(let t of Object.values(r.environments??{}))if(t?.variables)t.variables=h(t.variables);for(let t of Object.values(r.infrastructure?.databases??{}))if(t?.password)t.password="";if(r.infrastructure?.appDatabase?.password)r.infrastructure.appDatabase.password="";if(r.infrastructure?.compute?.database?.password)r.infrastructure.compute.database.password="";if(r.infrastructure?.compute?.managedServices?.vitess?.password)r.infrastructure.compute.managedServices.vitess.password="";return r}function y(e){let r=M(e);return["// Generated by ts-cloud for the management dashboard — do not edit.","//","// This is the project's resolved cloud config, inlined so it needs no","// imports on the box. Credentials are deliberately absent.",`export default ${JSON.stringify(r,null,2)}`,""].join(`
2
2
  `)}var Jl="dashboard";function La(){return Ke("dashboard-credentials.json")}function F(){return R(24).toString("base64url")}function Xl(e,r,t){let s=process.env.TS_CLOUD_UI_PASSWORD?.trim();if(s)return{password:s,source:"env"};if(b(process.env.TS_CLOUD_UI_PUBLIC))return{password:void 0,source:"public"};let n=La(),i=A(e,"dashboard-credentials.json");try{if(u(i)){let o=JSON.parse(U(i,"utf8"));if(o?.password)return{password:o.password,source:"generated"}}}catch{}let d=F();try{w(v(i),{recursive:!0}),m(i,`${JSON.stringify({username:r,password:d,generatedAt:new Date().toISOString()},null,2)}
3
3
  `),j(i,384),t.info(`Management dashboard: generated a password for '${r}' and saved it to ${n} (read it there — it is not printed). Set TS_CLOUD_UI_PASSWORD to pin your own, or TS_CLOUD_UI_PUBLIC=1 to serve without auth.`)}catch(o){t.warn(`Management dashboard: could not persist the generated password (${o?.message??o}). Using it for this deploy only — pass: ${d}
4
4
  This password is now in your deploy log. Set TS_CLOUD_UI_PASSWORD to a value of your own and redeploy once ${n} is writable.`)}return{password:d,source:"generated"}}var I={info:()=>{},warn:()=>{}};function b(e){return e!=null&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function J(){return Ke("dashboard-release")}function L(){let e=v(C(import.meta.url));for(let r of[a(e,"..","..","package.json"),a(e,"..","package.json")])try{let t=JSON.parse(U(r,"utf8"));if(t.name==="@stacksjs/ts-cloud"&&t.version)return`^${t.version}`}catch{}return"latest"}function z(){return process.env.TS_CLOUD_UI_VERSION?.trim()||L()}function V(e,r,t){if(!e?.project?.slug)return t.warn("Management dashboard: the cloud config has no project slug — skipping the live dashboard."),null;let s=A(r,"dashboard-release");try{w(s,{recursive:!0}),m(a(s,"cloud.config.ts"),y(e));let n=z();if(n.startsWith("file:")){let d=n.slice(5),o=O(d)?d:B(r,d);if(!u(o)||!N(o).isFile())n=L(),t.warn(`Management dashboard: TS_CLOUD_UI_VERSION points to a missing package file (${o}); using the deploying ts-cloud version ${n} instead.`);else{let c=P(o),l=a(s,c);if(o!==l)x(o,l);n=`file:./${c}`}}let i={name:"ts-cloud-dashboard",private:!0,type:"module",dependencies:{"@stacksjs/ts-cloud":n}};return m(a(s,"package.json"),`${JSON.stringify(i,null,2)}
@@ -1 +1 @@
1
- import{Cl,Al,Il,Rl,du,uu}from"./chunk-13dhcjjb.js";import"./chunk-wvhqjr80.js";import"./chunk-yhxpmk29.js";import"./chunk-vymg9ywg.js";import"./chunk-57w9nsjk.js";import"./chunk-80zkjpfz.js";import"./chunk-bckm6fre.js";export{du as deleteStaticSite,Al as deployStaticSite,uu as deployStaticSiteFull,Cl as generateStaticSiteTemplate,Rl as invalidateCache,Il as uploadStaticFiles};
1
+ import{Cl,Al,Il,Rl,du,uu}from"./chunk-dbmk60r7.js";import"./chunk-ngav845g.js";import"./chunk-yhxpmk29.js";import"./chunk-vymg9ywg.js";import"./chunk-57w9nsjk.js";import"./chunk-80zkjpfz.js";import"./chunk-bckm6fre.js";export{du as deleteStaticSite,Al as deployStaticSite,uu as deployStaticSiteFull,Cl as generateStaticSiteTemplate,Rl as invalidateCache,Il as uploadStaticFiles};
@@ -1,8 +1,8 @@
1
- import{h}from"./chunk-gj5jkhfr.js";var y=(e)=>e==null?void 0:String(e),w=(e)=>Number(e)===1,C=(e,r)=>{try{return e==null?r:JSON.parse(String(e))}catch{return r}};function b(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),scope:{type:String(e.scope_type),id:String(e.scope_id),environmentId:y(e.environment_id),resourceId:y(e.resource_id),previewId:y(e.preview_id)},key:String(e.key),kind:String(e.kind),value:y(e.value),valueFingerprint:String(e.value_fingerprint),secretRef:y(e.secret_ref),backend:String(e.backend),backendVersion:y(e.backend_version),origin:String(e.origin),required:w(e.required),metadata:C(e.metadata,{}),lastUsedAt:y(e.last_used_at),rotatedAt:y(e.rotated_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function I(e){return{entryId:String(e.entry_id),resourceId:String(e.resource_id),injectionTarget:String(e.injection_target),required:w(e.required),requiresRedeploy:w(e.requires_redeploy),lastDeployedVersion:e.last_deployed_version==null?void 0:Number(e.last_deployed_version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}class hr{controlPlane;now;constructor(e,r=()=>new Date){this.controlPlane=e;this.now=r}get(e){let r=this.controlPlane.database.query("SELECT * FROM configuration_entries WHERE id=?").get(e);return r?b(r):void 0}find(e,r,n){let t=this.controlPlane.database.query("SELECT * FROM configuration_entries WHERE project_id=? AND scope_type=? AND scope_id=? AND key=?").get(e,r.type,r.id,n);return t?b(t):void 0}list(e){let r=["project_id=?"],n=[e.projectId];if(e.scope)r.push("scope_type=?","scope_id=?"),n.push(e.scope.type,e.scope.id);if(e.kind)r.push("kind=?"),n.push(e.kind);return this.controlPlane.database.query(`SELECT * FROM configuration_entries WHERE ${r.join(" AND ")} ORDER BY key,scope_type,scope_id`).all(...n).map(b)}create(e){this.validateScope(e),this.validateEntry(e);let r=crypto.randomUUID(),n=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO configuration_entries (id,organization_id,project_id,scope_type,scope_id,environment_id,resource_id,preview_id,key,kind,value,value_fingerprint,secret_ref,backend,backend_version,origin,required,metadata,last_used_at,rotated_at,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[r,e.organizationId,e.projectId,e.scope.type,e.scope.id,e.scope.environmentId??null,e.scope.resourceId??null,e.scope.previewId??null,e.key,e.kind,e.value??null,e.valueFingerprint,e.secretRef??null,e.backend,e.backendVersion??null,e.origin,e.required?1:0,JSON.stringify(e.metadata),e.lastUsedAt??null,e.rotatedAt??null,1,n,n]),this.get(r)}update(e,r,n){let t=this.get(e);if(!t)throw Error("Configuration entry was not found.");if(this.validateEntry({...t,...n}),this.controlPlane.database.run("UPDATE configuration_entries SET value=?,value_fingerprint=?,secret_ref=?,backend=?,backend_version=?,required=?,metadata=?,rotated_at=?,version=version+1,updated_at=? WHERE id=? AND version=?",[n.value??null,n.valueFingerprint,n.secretRef??null,n.backend,n.backendVersion??null,n.required?1:0,JSON.stringify(n.metadata),n.rotatedAt??null,this.now().toISOString(),e,r]).changes!==1)throw Error("Configuration entry changed; refresh and retry.");return this.get(e)}remove(e,r){let n=this.get(e);if(!n)throw Error("Configuration entry was not found.");if(n.version!==r)throw Error("Configuration entry changed; refresh and retry.");if(this.controlPlane.database.run("DELETE FROM configuration_entries WHERE id=? AND version=?",[e,r]).changes<1)throw Error("Configuration entry changed; refresh and retry.");return n}setDependency(e){let r=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO configuration_dependencies (entry_id,resource_id,injection_target,required,requires_redeploy,last_deployed_version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?) ON CONFLICT(entry_id,resource_id) DO UPDATE SET injection_target=excluded.injection_target,required=excluded.required,requires_redeploy=excluded.requires_redeploy,last_deployed_version=excluded.last_deployed_version,updated_at=excluded.updated_at",[e.entryId,e.resourceId,e.injectionTarget,e.required?1:0,e.requiresRedeploy?1:0,e.lastDeployedVersion??null,r,r]),this.dependencies(e.entryId).find((n)=>n.resourceId===e.resourceId)}dependencies(e){return this.controlPlane.database.query("SELECT * FROM configuration_dependencies WHERE entry_id=? ORDER BY resource_id").all(e).map(I)}dependenciesForResource(e){return this.controlPlane.database.query("SELECT * FROM configuration_dependencies WHERE resource_id=? ORDER BY entry_id").all(e).map(I)}mutation(e){let r=this.controlPlane.database.query("SELECT request_hash,result FROM configuration_mutations WHERE idempotency_key=?").get(e);return r?{requestHash:r.request_hash,result:C(r.result,{})}:void 0}recordMutation(e){this.controlPlane.database.run("INSERT INTO configuration_mutations (id,project_id,idempotency_key,request_hash,result,actor_id,created_at) VALUES (?,?,?,?,?,?,?)",[crypto.randomUUID(),e.projectId,e.idempotencyKey,e.requestHash,JSON.stringify(e.result),e.actorId??null,this.now().toISOString()])}validateEntry(e){if(!/^[A-Za-z_][A-Za-z0-9_]{0,255}$/.test(e.key))throw Error(`Invalid configuration key: ${e.key}`);if(e.kind==="variable"&&(e.value==null||e.secretRef||e.backend!=="plaintext"))throw Error("Variables require a plaintext value and cannot use a secret backend.");if(e.kind==="secret"&&(e.value!=null||!e.secretRef||e.backend==="plaintext"))throw Error("Secrets require a non-plaintext backend reference and cannot store a plaintext value.")}validateScope(e){let r=this.controlPlane.getProject(e.projectId);if(!r||r.organizationId!==e.organizationId)throw Error("Configuration project does not belong to the organization.");let n=e.scope;if(n.type==="project"){if(n.id!==e.projectId||n.environmentId||n.resourceId||n.previewId)throw Error("Project configuration scope must reference only its project.");return}if(n.type==="environment"){let i=this.controlPlane.database.query("SELECT project_id FROM environments WHERE id=?").get(n.id);if(!i||i.project_id!==e.projectId||n.environmentId&&n.environmentId!==n.id||n.resourceId||n.previewId)throw Error("Environment configuration scope does not belong to the project.");return}if(n.type==="service"||n.type==="function"){let i=this.controlPlane.getResource(n.id);if(!i||i.projectId!==e.projectId||n.type==="function"&&i.kind!=="function"||n.resourceId&&n.resourceId!==n.id||n.environmentId&&i.environmentId!==n.environmentId||n.previewId)throw Error(`${n.type==="function"?"Function":"Service"} configuration scope does not belong to the project.`);return}let t=this.controlPlane.database.query("SELECT project_id,base_environment_id,resource_id FROM preview_instances WHERE id=?").get(n.id);if(!t||t.project_id!==e.projectId||n.previewId&&n.previewId!==n.id||n.environmentId&&n.environmentId!==t.base_environment_id||n.resourceId&&n.resourceId!==t.resource_id)throw Error("Preview configuration scope does not belong to the project.")}}var E=/^[A-Za-z_][A-Za-z0-9_]{0,255}$/;function j(e){let r={n:`
1
+ import{h}from"./chunk-wr6a423y.js";var y=(e)=>e==null?void 0:String(e),w=(e)=>Number(e)===1,C=(e,r)=>{try{return e==null?r:JSON.parse(String(e))}catch{return r}};function b(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),scope:{type:String(e.scope_type),id:String(e.scope_id),environmentId:y(e.environment_id),resourceId:y(e.resource_id),previewId:y(e.preview_id)},key:String(e.key),kind:String(e.kind),value:y(e.value),valueFingerprint:String(e.value_fingerprint),secretRef:y(e.secret_ref),backend:String(e.backend),backendVersion:y(e.backend_version),origin:String(e.origin),required:w(e.required),metadata:C(e.metadata,{}),lastUsedAt:y(e.last_used_at),rotatedAt:y(e.rotated_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function I(e){return{entryId:String(e.entry_id),resourceId:String(e.resource_id),injectionTarget:String(e.injection_target),required:w(e.required),requiresRedeploy:w(e.requires_redeploy),lastDeployedVersion:e.last_deployed_version==null?void 0:Number(e.last_deployed_version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}class hr{controlPlane;now;constructor(e,r=()=>new Date){this.controlPlane=e;this.now=r}get(e){let r=this.controlPlane.database.query("SELECT * FROM configuration_entries WHERE id=?").get(e);return r?b(r):void 0}find(e,r,n){let t=this.controlPlane.database.query("SELECT * FROM configuration_entries WHERE project_id=? AND scope_type=? AND scope_id=? AND key=?").get(e,r.type,r.id,n);return t?b(t):void 0}list(e){let r=["project_id=?"],n=[e.projectId];if(e.scope)r.push("scope_type=?","scope_id=?"),n.push(e.scope.type,e.scope.id);if(e.kind)r.push("kind=?"),n.push(e.kind);return this.controlPlane.database.query(`SELECT * FROM configuration_entries WHERE ${r.join(" AND ")} ORDER BY key,scope_type,scope_id`).all(...n).map(b)}create(e){this.validateScope(e),this.validateEntry(e);let r=crypto.randomUUID(),n=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO configuration_entries (id,organization_id,project_id,scope_type,scope_id,environment_id,resource_id,preview_id,key,kind,value,value_fingerprint,secret_ref,backend,backend_version,origin,required,metadata,last_used_at,rotated_at,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[r,e.organizationId,e.projectId,e.scope.type,e.scope.id,e.scope.environmentId??null,e.scope.resourceId??null,e.scope.previewId??null,e.key,e.kind,e.value??null,e.valueFingerprint,e.secretRef??null,e.backend,e.backendVersion??null,e.origin,e.required?1:0,JSON.stringify(e.metadata),e.lastUsedAt??null,e.rotatedAt??null,1,n,n]),this.get(r)}update(e,r,n){let t=this.get(e);if(!t)throw Error("Configuration entry was not found.");if(this.validateEntry({...t,...n}),this.controlPlane.database.run("UPDATE configuration_entries SET value=?,value_fingerprint=?,secret_ref=?,backend=?,backend_version=?,required=?,metadata=?,rotated_at=?,version=version+1,updated_at=? WHERE id=? AND version=?",[n.value??null,n.valueFingerprint,n.secretRef??null,n.backend,n.backendVersion??null,n.required?1:0,JSON.stringify(n.metadata),n.rotatedAt??null,this.now().toISOString(),e,r]).changes!==1)throw Error("Configuration entry changed; refresh and retry.");return this.get(e)}remove(e,r){let n=this.get(e);if(!n)throw Error("Configuration entry was not found.");if(n.version!==r)throw Error("Configuration entry changed; refresh and retry.");if(this.controlPlane.database.run("DELETE FROM configuration_entries WHERE id=? AND version=?",[e,r]).changes<1)throw Error("Configuration entry changed; refresh and retry.");return n}setDependency(e){let r=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO configuration_dependencies (entry_id,resource_id,injection_target,required,requires_redeploy,last_deployed_version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?) ON CONFLICT(entry_id,resource_id) DO UPDATE SET injection_target=excluded.injection_target,required=excluded.required,requires_redeploy=excluded.requires_redeploy,last_deployed_version=excluded.last_deployed_version,updated_at=excluded.updated_at",[e.entryId,e.resourceId,e.injectionTarget,e.required?1:0,e.requiresRedeploy?1:0,e.lastDeployedVersion??null,r,r]),this.dependencies(e.entryId).find((n)=>n.resourceId===e.resourceId)}dependencies(e){return this.controlPlane.database.query("SELECT * FROM configuration_dependencies WHERE entry_id=? ORDER BY resource_id").all(e).map(I)}dependenciesForResource(e){return this.controlPlane.database.query("SELECT * FROM configuration_dependencies WHERE resource_id=? ORDER BY entry_id").all(e).map(I)}mutation(e){let r=this.controlPlane.database.query("SELECT request_hash,result FROM configuration_mutations WHERE idempotency_key=?").get(e);return r?{requestHash:r.request_hash,result:C(r.result,{})}:void 0}recordMutation(e){this.controlPlane.database.run("INSERT INTO configuration_mutations (id,project_id,idempotency_key,request_hash,result,actor_id,created_at) VALUES (?,?,?,?,?,?,?)",[crypto.randomUUID(),e.projectId,e.idempotencyKey,e.requestHash,JSON.stringify(e.result),e.actorId??null,this.now().toISOString()])}validateEntry(e){if(!/^[A-Za-z_][A-Za-z0-9_]{0,255}$/.test(e.key))throw Error(`Invalid configuration key: ${e.key}`);if(e.kind==="variable"&&(e.value==null||e.secretRef||e.backend!=="plaintext"))throw Error("Variables require a plaintext value and cannot use a secret backend.");if(e.kind==="secret"&&(e.value!=null||!e.secretRef||e.backend==="plaintext"))throw Error("Secrets require a non-plaintext backend reference and cannot store a plaintext value.")}validateScope(e){let r=this.controlPlane.getProject(e.projectId);if(!r||r.organizationId!==e.organizationId)throw Error("Configuration project does not belong to the organization.");let n=e.scope;if(n.type==="project"){if(n.id!==e.projectId||n.environmentId||n.resourceId||n.previewId)throw Error("Project configuration scope must reference only its project.");return}if(n.type==="environment"){let i=this.controlPlane.database.query("SELECT project_id FROM environments WHERE id=?").get(n.id);if(!i||i.project_id!==e.projectId||n.environmentId&&n.environmentId!==n.id||n.resourceId||n.previewId)throw Error("Environment configuration scope does not belong to the project.");return}if(n.type==="service"||n.type==="function"){let i=this.controlPlane.getResource(n.id);if(!i||i.projectId!==e.projectId||n.type==="function"&&i.kind!=="function"||n.resourceId&&n.resourceId!==n.id||n.environmentId&&i.environmentId!==n.environmentId||n.previewId)throw Error(`${n.type==="function"?"Function":"Service"} configuration scope does not belong to the project.`);return}let t=this.controlPlane.database.query("SELECT project_id,base_environment_id,resource_id FROM preview_instances WHERE id=?").get(n.id);if(!t||t.project_id!==e.projectId||n.previewId&&n.previewId!==n.id||n.environmentId&&n.environmentId!==t.base_environment_id||n.resourceId&&n.resourceId!==t.resource_id)throw Error("Preview configuration scope does not belong to the project.")}}var E=/^[A-Za-z_][A-Za-z0-9_]{0,255}$/;function j(e){let r={n:`
2
2
  `,r:"\r",t:"\t","\\":"\\",'"':'"',$:"$"};return e.replace(/\\(n|r|t|\\|"|\$)/g,(n,t)=>r[t])}function qa(e){let r={},n=[],t=e.replace(/\r\n?/g,`
3
3
  `).split(`
4
4
  `);for(let i=0;i<t.length;i++){let s=i+1,c=t[i];if(!c.trim()||c.trimStart().startsWith("#"))continue;if(/^\s*export\s+/.test(c))c=c.replace(/^\s*export\s+/,"");let u=c.match(/^\s*([^=\s]+)\s*=\s*(.*)$/);if(!u){n.push({line:s,severity:"error",code:"invalid_line",message:"Expected KEY=VALUE."});continue}let o=u[1],a=u[2];if(!E.test(o)){n.push({line:s,key:o,severity:"error",code:"invalid_key",message:`Invalid environment variable name: ${o}`});continue}let d=a;if(a.startsWith('"')||a.startsWith("'")){let g=a[0],l=[a.slice(1)],v=!1;while(!0){let f=l[l.length-1],m=!1,S=-1;for(let k=0;k<f.length;k++){if(g==='"'&&f[k]==="\\"&&!m){m=!0;continue}if(f[k]===g&&!m){S=k;break}m=!1}if(S>=0){l[l.length-1]=f.slice(0,S),v=!0;break}if(++i>=t.length)break;l.push(t[i])}if(!v){n.push({line:s,key:o,severity:"error",code:"unterminated_quote",message:`Unterminated quoted value for ${o}.`});continue}if(d=l.join(`
5
5
  `),g==='"')d=j(d)}else d=a.replace(/\s+#.*$/,"").trim();if(Object.hasOwn(r,o)){let g=r[o]!==d;if(n.push({line:s,key:o,severity:g?"error":"warning",code:g?"conflict":"duplicate",message:g?`${o} has conflicting values.`:`${o} is duplicated with the same value.`}),g)continue}r[o]=d}return{values:r,diagnostics:n,valid:!n.some((i)=>i.severity==="error")}}function Ha(e){return Object.entries(e).sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>{if(!E.test(r))throw Error(`Invalid environment variable name: ${r}`);return`${r}=${JSON.stringify(n)}`}).join(`
6
6
  `)+(Object.keys(e).length?`
7
7
  `:"")}import{createCipheriv as x,createDecipheriv as P,createHash as _,randomBytes as q}from"node:crypto";class St{controlPlane;now;kind="local_encrypted";key;constructor(e,r,n=()=>new Date){this.controlPlane=e;this.now=n;if(!r)throw Error("Configuration encryption key is required.");this.key=_("sha256").update(`ts-cloud:configuration:${r}`).digest()}encrypt(e){let r=q(12),n=x("aes-256-gcm",this.key,r),t=Buffer.concat([n.update(e,"utf8"),n.final()]);return`v1.${r.toString("base64url")}.${n.getAuthTag().toString("base64url")}.${t.toString("base64url")}`}decrypt(e){let[r,n,t,i]=e.split(".");if(r!=="v1"||!n||!t||!i)throw Error("Encrypted configuration secret is unavailable.");try{let s=P("aes-256-gcm",this.key,Buffer.from(n,"base64url"));return s.setAuthTag(Buffer.from(t,"base64url")),Buffer.concat([s.update(Buffer.from(i,"base64url")),s.final()]).toString("utf8")}catch{throw Error("Encrypted configuration secret could not be decrypted.")}}async put(e){if(!e.value)throw Error("Configuration secrets cannot be empty.");let r=e.reference??`secret://configuration/${e.name}/${crypto.randomUUID()}`;if(!/^secret:\/\/configuration\/[A-Za-z0-9._/-]+$/.test(r))throw Error("Invalid local configuration secret reference.");let t=(this.controlPlane.database.query("SELECT version FROM configuration_secret_values WHERE reference=?").get(r)?.version??0)+1,i=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO configuration_secret_values (reference,ciphertext,fingerprint,version,created_at,updated_at) VALUES (?,?,?,?,?,?) ON CONFLICT(reference) DO UPDATE SET ciphertext=excluded.ciphertext,fingerprint=excluded.fingerprint,version=excluded.version,updated_at=excluded.updated_at",[r,this.encrypt(e.value),_("sha256").update(e.value).digest("hex"),t,i,i]),{reference:r,version:String(t)}}async resolve(e){let r=this.controlPlane.database.query("SELECT ciphertext FROM configuration_secret_values WHERE reference=?").get(e);if(!r)throw Error("Configuration secret was not found.");return this.decrypt(r.ciphertext)}async remove(e){this.controlPlane.database.run("DELETE FROM configuration_secret_values WHERE reference=?",[e])}async validate(e){return!!this.controlPlane.database.query("SELECT 1 AS found FROM configuration_secret_values WHERE reference=?").get(e)}}class yr{client;region;kind="aws_secrets_manager";constructor(e,r){this.client=e;this.region=r}async put(e){if(e.reference){let n=this.id(e.reference),t=await this.client.putSecretValue({SecretId:n,SecretString:e.value,ClientRequestToken:e.idempotencyKey});return{reference:e.reference,version:t.VersionId??e.idempotencyKey}}let r=await this.client.createSecret({Name:e.name,SecretString:e.value,ClientRequestToken:e.idempotencyKey,Tags:[{Key:"managed-by",Value:"ts-cloud"}]});return{reference:`aws-sm://${this.region}/${encodeURIComponent(r.ARN??r.Name??e.name)}`,version:r.VersionId??e.idempotencyKey}}async resolve(e){let r=await this.client.getSecretValue({SecretId:this.id(e)});if(r.SecretString==null)throw Error("AWS Secrets Manager value is unavailable.");return r.SecretString}async remove(e){await this.client.deleteSecret({SecretId:this.id(e),RecoveryWindowInDays:7})}async validate(e){try{return await this.client.describeSecret(this.id(e)),!0}catch{return!1}}id(e){let r=new URL(e);if(r.protocol!=="aws-sm:"||r.hostname!==this.region)throw Error("Invalid AWS Secrets Manager reference.");return decodeURIComponent(r.pathname.slice(1))}}class Sr{client;region;kind="aws_ssm";constructor(e,r){this.client=e;this.region=r}async put(e){let r=e.reference?this.name(e.reference):`/${e.name.replace(/^\/+/,"")}`,n=await this.client.putParameter({Name:r,Value:e.value,Type:"SecureString",Overwrite:!!e.reference,Description:"Managed by ts-cloud"});return{reference:`aws-ssm://${this.region}${r}`,version:String(n.Version??1)}}async resolve(e){let r=await this.client.getParameter({Name:this.name(e),WithDecryption:!0});if(r.Parameter?.Value==null)throw Error("AWS SSM parameter value is unavailable.");return r.Parameter.Value}async remove(e){await this.client.deleteParameter({Name:this.name(e)})}async validate(e){try{return!!(await this.client.getParameter({Name:this.name(e),WithDecryption:!1})).Parameter}catch{return!1}}name(e){let r=new URL(e);if(r.protocol!=="aws-ssm:"||r.hostname!==this.region||!r.pathname.startsWith("/"))throw Error("Invalid AWS SSM reference.");return r.pathname}}class br{kind="external";async put(){throw Error("External secret references cannot be written by ts-cloud.")}async resolve(){throw Error("External secrets must be resolved by the deployment provider.")}async remove(){}async validate(e){return/^(?:vault|doppler|op|external):\/\//.test(e)}}import{createHmac as A}from"node:crypto";var D=/^(?:secret|aws-sm|aws-ssm|vault|doppler|op|external):\/\//,O=/^(?:AWS_|TS_CLOUD_|PORT$|HOST$)/;function p(e){return[...new Set(e)].sort()}function R(e,r={}){let n=e.kind==="secret";return{id:e.id,key:e.key,kind:e.kind,scope:e.scope,inherited:!!r.inherited,overridden:!!r.overridden,required:e.required,backend:!n||r.canReadSecretMetadata?e.backend:void 0,backendVersion:!n||r.canReadSecretMetadata?e.backendVersion:void 0,reference:n&&r.canReadSecretMetadata?e.secretRef:void 0,value:!n?e.value:void 0,lastUsedAt:e.lastUsedAt,rotatedAt:e.rotatedAt,version:e.version,updatedAt:e.updatedAt}}class vr{store;backends=new Map;fingerprintKey;now;constructor(e,r){if(this.store=e,this.fingerprintKey=r.fingerprintKey??r.encryptionKey,this.now=r.now??(()=>new Date),!this.fingerprintKey)throw Error("Configuration fingerprint key is required.");let n=r.backends??[new St(e.controlPlane,r.encryptionKey,this.now)];for(let t of n)this.backends.set(t.kind,t)}list(e){let r=e.search?.toLowerCase();return this.store.list(e).filter((n)=>!r||n.key.toLowerCase().includes(r)).map((n)=>R(n,{canReadSecretMetadata:e.canReadSecretMetadata}))}plan(e){let r=this.store.list({projectId:e.projectId,scope:e.scope}),n=new Map(r.map((o)=>[o.key,o])),t=[],i=[],s=[],c=[];for(let[o,a]of Object.entries(e.values)){t.push(...this.warnings(o,a));let d=n.get(o);if(!d)i.push(o);else if(d.valueFingerprint!==this.fingerprint(a))s.push(o);else c.push(o)}let u=e.removeMissing?r.filter((o)=>!Object.hasOwn(e.values,o.key)).map((o)=>o.key):[];return{added:p(i),changed:p(s),removed:p(u),unchanged:p(c),affectedResourceIds:this.affectedResources(e.projectId,e.scope,[...i,...s,...u]),warnings:t}}async set(e){let r=this.requestHash(e),n=e.idempotencyKey;if(n){let f=this.store.mutation(n);if(f){if(f.requestHash!==r)throw Error("Idempotency key was already used for a different configuration mutation.");let m=this.store.get(String(f.result.entryId??""));if(!m)throw Error("Idempotent configuration result is no longer available.");return{entry:m,mutation:f.result.mutation,warnings:[]}}}if(e.value!=null&&D.test(e.value))throw Error("Secret references must use the reference field, not a plaintext value field.");let t=this.store.find(e.projectId,e.scope,e.key),i=this.fingerprint(e.value??e.reference??"");if(t&&e.expectedVersion!=null&&t.version!==e.expectedVersion)throw Error("Configuration entry changed; refresh and retry.");if(t&&t.kind!==e.kind)throw Error("Delete the existing entry before changing between variable and secret kinds.");let s=e.kind==="variable"?"plaintext":e.backend??(e.reference?"external":"local_encrypted");if(!!t&&(t.valueFingerprint!==i||t.backend!==s||t.required!==!!e.required)&&(this.isProduction(t)||this.store.dependencies(t.id).length>0)&&!e.confirmed)throw Error("Confirmation is required because this replacement affects production or dependent services.");let u=e.reference,o;if(e.kind==="secret"){let f=this.backend(s);if(e.reference&&e.value==null){if(!await f.validate(e.reference))throw Error("Secret backend reference is unavailable or invalid.");o=t?.backendVersion??"external"}else{if(e.value==null)throw Error("A secret value or external reference is required.");let m=await f.put({reference:t?.backend===s?t.secretRef:void 0,name:this.backendName(e),value:e.value,idempotencyKey:n??crypto.randomUUID()});u=m.reference,o=m.version}}let a=e.kind==="variable"?e.value:void 0;if(e.kind==="variable"&&a==null)throw Error("A variable value is required.");let d=!t||t.valueFingerprint!==i||t.backend!==s||t.secretRef!==u||t.backendVersion!==o||t.required!==!!e.required,g=t?d?this.store.update(t.id,t.version,{value:a,valueFingerprint:i,secretRef:u,backend:s,backendVersion:o,required:!!e.required,metadata:h(e.metadata??t.metadata),rotatedAt:e.kind==="secret"?this.now().toISOString():t.rotatedAt}):t:this.store.create({organizationId:e.organizationId,projectId:e.projectId,scope:e.scope,key:e.key,kind:e.kind,value:a,valueFingerprint:i,secretRef:u,backend:s,backendVersion:o,origin:e.origin??"managed",required:!!e.required,metadata:h(e.metadata??{}),rotatedAt:e.kind==="secret"?this.now().toISOString():void 0}),l=this.affectedResources(e.projectId,e.scope,[e.key]),v={added:t?[]:[e.key],changed:t&&d?[e.key]:[],removed:[],unchanged:t&&!d?[e.key]:[],affectedResourceIds:l,versions:{[e.key]:g.version}};if(n)this.store.recordMutation({projectId:e.projectId,idempotencyKey:n,requestHash:r,actorId:e.actorId,result:{entryId:g.id,mutation:v}});return this.audit(e.projectId,e.actorId,t&&d?"configuration.updated":t?"configuration.unchanged":"configuration.created",g,l),{entry:g,mutation:v,warnings:this.warnings(e.key,e.value??"")}}async importDotenv(e){let r=qa(e.source);if(!r.valid)return{document:r,warnings:[]};let n=new Set(e.secretKeys??[]),t={added:[],changed:[],removed:[],unchanged:[],affectedResourceIds:[],versions:{}},i=[];for(let[s,c]of Object.entries(r.values)){let u=await this.set({...e,source:void 0,key:s,value:c,kind:n.has(s)?"secret":"variable",idempotencyKey:e.idempotencyKey?`${e.idempotencyKey}:${s}`:void 0});t.added.push(...u.mutation.added),t.changed.push(...u.mutation.changed),t.unchanged.push(...u.mutation.unchanged),t.affectedResourceIds.push(...u.mutation.affectedResourceIds),Object.assign(t.versions,u.mutation.versions),i.push(...u.warnings)}return t.added=p(t.added),t.changed=p(t.changed),t.unchanged=p(t.unchanged),t.affectedResourceIds=p(t.affectedResourceIds),{document:r,mutation:t,warnings:i}}exportVariables(e){return Ha(Object.fromEntries(this.store.list({projectId:e.projectId,scope:e.scope,kind:"variable"}).map((r)=>[r.key,r.value??""])))}async transfer(e){let r=this.store.get(e.entryId);if(!r)throw Error("Configuration entry was not found.");if(r.scope.type===e.targetScope.type&&r.scope.id===e.targetScope.id)throw Error("Choose a different destination scope.");let n=r.kind==="variable"?r.value:r.backend==="external"?void 0:await this.backend(r.backend).resolve(r.secretRef),t=r.kind==="secret"?r.backend:void 0,i=await this.set({organizationId:r.organizationId,projectId:r.projectId,scope:e.targetScope,key:r.key,kind:r.kind,value:n,reference:r.backend==="external"?r.secretRef:void 0,backend:t,required:r.required,metadata:r.metadata,confirmed:e.confirmed,actorId:e.actorId,idempotencyKey:e.idempotencyKey?`${e.idempotencyKey}:copy`:void 0,origin:r.origin});if(e.mode==="move")await this.remove({entryId:r.id,expectedVersion:r.version,confirmed:e.confirmed,actorId:e.actorId});let s={added:i.mutation.added,changed:i.mutation.changed,removed:e.mode==="move"?[r.key]:[],unchanged:i.mutation.unchanged,affectedResourceIds:p([...i.mutation.affectedResourceIds,...this.affectedResources(r.projectId,r.scope,[r.key])]),versions:i.mutation.versions};return{entry:i.entry,mutation:s}}async resolve(e){let r=this.store.list({projectId:e.projectId}),n=r.filter((a)=>this.applies(a,e)).sort((a,d)=>this.rank(a.scope.type)-this.rank(d.scope.type)),t=new Map,i=new Set;for(let a of n){if(t.has(a.key))i.add(a.key);t.set(a.key,a)}let s={},c={},u=[],o=new Set(e.allowedPreviewSecrets??[]);for(let[a,d]of t){if(e.previewId&&d.kind==="secret"&&d.scope.type!=="preview"&&(!e.trustedPreview||!o.has(a)))continue;if(d.kind==="variable")s[a]=d.value??"";else if(e.nativeReferences)s[a]=d.secretRef;else{let g=this.backend(d.backend);if(!await g.validate(d.secretRef)){if(u.push({key:a,code:"stale_reference",message:`${a} points to an unavailable secret.`}),d.required)u.push({key:a,code:"missing_required",message:`${a} is required but unavailable.`});continue}s[a]=await g.resolve(d.secretRef)}c[a]=R(d,{inherited:d.scope.type!==(e.previewId?"preview":e.functionId?"function":e.resourceId?"service":e.environmentId?"environment":"project"),overridden:i.has(a),canReadSecretMetadata:e.canReadSecretMetadata}),this.store.controlPlane.database.run("UPDATE configuration_entries SET last_used_at=? WHERE id=?",[this.now().toISOString(),d.id])}return{values:s,entries:c,warnings:u,configurationHash:this.fingerprint([...t.values()].map((a)=>`${a.key}:${a.valueFingerprint}:${a.version}`).sort().join(`
8
- `))}}async reveal(e){let r=this.store.get(e.entryId);if(!r||r.kind!=="secret")throw Error("Configuration secret was not found.");if(!e.canRevealSecrets)throw Error("Secret reveal permission is required.");if(!e.recentlyAuthenticated)throw Error("Recent authentication is required to reveal a secret.");let n=await this.backend(r.backend).resolve(r.secretRef);return this.audit(r.projectId,e.actorId,"configuration.secret.revealed",r,[]),n}async remove(e){let r=this.store.get(e.entryId);if(!r)throw Error("Configuration entry was not found.");let n=this.store.dependencies(r.id);if(((r.scope.environmentId?this.store.controlPlane.listEnvironments(r.projectId).some((c)=>c.id===r.scope.environmentId&&c.kind==="production"):r.scope.type==="project")||n.length)&&!e.confirmed)throw Error("Confirmation is required because this configuration affects production or dependent services.");if(r.kind==="secret"&&r.backend!=="external")await this.backend(r.backend).remove(r.secretRef);this.store.remove(r.id,e.expectedVersion);let i=p(n.map((c)=>c.resourceId)),s={added:[],changed:[],removed:[r.key],unchanged:[],affectedResourceIds:i,versions:{}};return this.audit(r.projectId,e.actorId,"configuration.deleted",r,i),s}applies(e,r){if(e.scope.type==="project")return!0;if(e.scope.type==="environment")return e.scope.id===r.environmentId;if(e.scope.type==="service")return e.scope.id===r.resourceId;if(e.scope.type==="function")return e.scope.id===r.functionId;return e.scope.id===r.previewId}rank(e){return{project:0,environment:1,service:2,function:3,preview:4}[e]}fingerprint(e){return`hmac-sha256:${A("sha256",this.fingerprintKey).update(e).digest("hex")}`}requestHash(e){return this.fingerprint(JSON.stringify({...e,idempotencyKey:void 0,actorId:void 0}))}backend(e){let r=this.backends.get(e);if(!r)throw Error(`Configuration secret backend is not configured: ${e}`);return r}backendName(e){return`ts-cloud/${e.projectId}/${e.scope.type}/${e.scope.id}/${e.key}`.replace(/[^A-Za-z0-9/_+=.@-]/g,"-")}isProduction(e){return e.scope.type==="project"||!!e.scope.environmentId&&this.store.controlPlane.listEnvironments(e.projectId).some((r)=>r.id===e.scope.environmentId&&r.kind==="production")}warnings(e,r){let n=[];if(O.test(e))n.push({key:e,code:"reserved",message:`${e} may be reserved by the runtime or provider.`});if(Buffer.byteLength(r)>65536)n.push({key:e,code:"limit",message:`${e} exceeds the portable 64 KiB value limit.`});return n}affectedResources(e,r,n){let t=this.store.list({projectId:e,scope:r}).filter((i)=>n.includes(i.key)).flatMap((i)=>this.store.dependencies(i.id).map((s)=>s.resourceId));if(r.type==="service"||r.type==="function")return p([...t,r.id]);if(r.type==="environment")return p([...t,...this.store.controlPlane.listResources(e,r.id).map((i)=>i.id)]);if(r.type==="preview"){let i=this.store.controlPlane.database.query("SELECT resource_id FROM preview_instances WHERE id=?").get(r.id);return p([...t,...i?[i.resource_id]:[]])}return p([...t,...this.store.controlPlane.listResources(e).map((i)=>i.id)])}audit(e,r,n,t,i){this.store.controlPlane.appendEvent({projectId:e,actorId:r,type:n,payload:{entryId:t.id,key:t.key,kind:t.kind,scopeType:t.scope.type,scopeId:t.scope.id,backend:t.backend,version:t.version,affectedResourceIds:i}})}}async function Qr(e,r,n,t){let i={added:0,changed:0,removed:0,overridden:0},s=async(c,u)=>{let o=e.store.list({projectId:r.project.id,scope:c,kind:"variable"}),a=new Set(Object.keys(u));for(let d of o.filter((g)=>g.origin==="config"&&!a.has(g.key)))await e.remove({entryId:d.id,expectedVersion:d.version,confirmed:!0,actorId:t}),i.removed++;for(let[d,g]of Object.entries(u)){let l=e.store.find(r.project.id,c,d);if(l?.origin!=="config"){if(l)i.overridden++;else await e.set({organizationId:r.organization.id,projectId:r.project.id,scope:c,key:d,kind:"variable",value:String(g),origin:"config",confirmed:!0,actorId:t}),i.added++;continue}if(l.value===String(g))continue;await e.set({organizationId:r.organization.id,projectId:r.project.id,scope:c,key:d,kind:"variable",value:String(g),origin:"config",confirmed:!0,actorId:t,expectedVersion:l.version}),i.changed++}};for(let[c,u]of Object.entries(n.environments??{})){let o=r.environments.get(c);if(!o)continue;let a=u,d={...a.variables??{},...a.app?.env??{}};await s({type:"environment",id:o.id,environmentId:o.id},d);for(let[g,l]of Object.entries(n.sites??{})){let v=r.store.listResources(r.project.id,o.id).find((f)=>f.kind==="application"&&f.slug===g);if(v)await s({type:"service",id:v.id,environmentId:o.id,resourceId:v.id},{...l.env??{}})}for(let[g,l]of Object.entries(n.infrastructure?.functions??{})){let v=r.store.listResources(r.project.id,o.id).find((f)=>f.kind==="function"&&f.slug===g);if(v)await s({type:"function",id:v.id,environmentId:o.id,resourceId:v.id},{...l.environment??{}})}}return i}export{hr,qa,Ha,St,yr,Sr,br,vr,Qr};
8
+ `))}}async reveal(e){let r=this.store.get(e.entryId);if(!r||r.kind!=="secret")throw Error("Configuration secret was not found.");if(!e.canRevealSecrets)throw Error("Secret reveal permission is required.");if(!e.recentlyAuthenticated)throw Error("Recent authentication is required to reveal a secret.");let n=await this.backend(r.backend).resolve(r.secretRef);return this.audit(r.projectId,e.actorId,"configuration.secret.revealed",r,[]),n}async remove(e){let r=this.store.get(e.entryId);if(!r)throw Error("Configuration entry was not found.");let n=this.store.dependencies(r.id);if(((r.scope.environmentId?this.store.controlPlane.listEnvironments(r.projectId).some((c)=>c.id===r.scope.environmentId&&c.kind==="production"):r.scope.type==="project")||n.length)&&!e.confirmed)throw Error("Confirmation is required because this configuration affects production or dependent services.");if(r.kind==="secret"&&r.backend!=="external")await this.backend(r.backend).remove(r.secretRef);this.store.remove(r.id,e.expectedVersion);let i=p(n.map((c)=>c.resourceId)),s={added:[],changed:[],removed:[r.key],unchanged:[],affectedResourceIds:i,versions:{}};return this.audit(r.projectId,e.actorId,"configuration.deleted",r,i),s}applies(e,r){if(e.scope.type==="project")return!0;if(e.scope.type==="environment")return e.scope.id===r.environmentId;if(e.scope.type==="service")return e.scope.id===r.resourceId;if(e.scope.type==="function")return e.scope.id===r.functionId;return e.scope.id===r.previewId}rank(e){return{project:0,environment:1,service:2,function:3,preview:4}[e]}fingerprint(e){return`hmac-sha256:${A("sha256",this.fingerprintKey).update(e).digest("hex")}`}requestHash(e){return this.fingerprint(JSON.stringify({...e,idempotencyKey:void 0,actorId:void 0}))}backend(e){let r=this.backends.get(e);if(!r)throw Error(`Configuration secret backend is not configured: ${e}`);return r}backendName(e){return`ts-cloud/${e.projectId}/${e.scope.type}/${e.scope.id}/${e.key}`.replace(/[^A-Za-z0-9/_+=.@-]/g,"-")}isProduction(e){return e.scope.type==="project"||!!e.scope.environmentId&&this.store.controlPlane.listEnvironments(e.projectId).some((r)=>r.id===e.scope.environmentId&&r.kind==="production")}warnings(e,r){let n=[];if(O.test(e))n.push({key:e,code:"reserved",message:`${e} may be reserved by the runtime or provider.`});if(Buffer.byteLength(r)>65536)n.push({key:e,code:"limit",message:`${e} exceeds the portable 64 KiB value limit.`});return n}affectedResources(e,r,n){let t=this.store.list({projectId:e,scope:r}).filter((i)=>n.includes(i.key)).flatMap((i)=>this.store.dependencies(i.id).map((s)=>s.resourceId));if(r.type==="service"||r.type==="function")return p([...t,r.id]);if(r.type==="environment")return p([...t,...this.store.controlPlane.listResources(e,r.id).map((i)=>i.id)]);if(r.type==="preview"){let i=this.store.controlPlane.database.query("SELECT resource_id FROM preview_instances WHERE id=?").get(r.id);return p([...t,...i?[i.resource_id]:[]])}return p([...t,...this.store.controlPlane.listResources(e).map((i)=>i.id)])}audit(e,r,n,t,i){this.store.controlPlane.appendEvent({projectId:e,actorId:r,type:n,payload:{entryId:t.id,key:t.key,kind:t.kind,scopeType:t.scope.type,scopeId:t.scope.id,backend:t.backend,version:t.version,affectedResourceIds:i}})}}async function Yr(e,r,n,t){let i={added:0,changed:0,removed:0,overridden:0},s=async(c,u)=>{let o=e.store.list({projectId:r.project.id,scope:c,kind:"variable"}),a=new Set(Object.keys(u));for(let d of o.filter((g)=>g.origin==="config"&&!a.has(g.key)))await e.remove({entryId:d.id,expectedVersion:d.version,confirmed:!0,actorId:t}),i.removed++;for(let[d,g]of Object.entries(u)){let l=e.store.find(r.project.id,c,d);if(l?.origin!=="config"){if(l)i.overridden++;else await e.set({organizationId:r.organization.id,projectId:r.project.id,scope:c,key:d,kind:"variable",value:String(g),origin:"config",confirmed:!0,actorId:t}),i.added++;continue}if(l.value===String(g))continue;await e.set({organizationId:r.organization.id,projectId:r.project.id,scope:c,key:d,kind:"variable",value:String(g),origin:"config",confirmed:!0,actorId:t,expectedVersion:l.version}),i.changed++}};for(let[c,u]of Object.entries(n.environments??{})){let o=r.environments.get(c);if(!o)continue;let a=u,d={...a.variables??{},...a.app?.env??{}};await s({type:"environment",id:o.id,environmentId:o.id},d);for(let[g,l]of Object.entries(n.sites??{})){let v=r.store.listResources(r.project.id,o.id).find((f)=>f.kind==="application"&&f.slug===g);if(v)await s({type:"service",id:v.id,environmentId:o.id,resourceId:v.id},{...l.env??{}})}for(let[g,l]of Object.entries(n.infrastructure?.functions??{})){let v=r.store.listResources(r.project.id,o.id).find((f)=>f.kind==="function"&&f.slug===g);if(v)await s({type:"function",id:v.id,environmentId:o.id,resourceId:v.id},{...l.environment??{}})}}return i}export{hr,qa,Ha,St,yr,Sr,br,vr,Yr};
@@ -1 +1 @@
1
- import{dt,zl,Yo,Vi,Pu,Zo,es,zi,_t,Nu,ql,ku,Du,j,ts,xu}from"./chunk-x5x9dzk7.js";import"./chunk-4zbnwt9b.js";import"./chunk-vymg9ywg.js";import"./chunk-80zkjpfz.js";import"./chunk-7h6h8yxm.js";import"./chunk-bckm6fre.js";import"./chunk-6xw0r4gn.js";export{Vi as assertEnvWithinLimit,Yo as buildFunctionEnv,Pu as deployServerlessApp,ku as getCommandRecord,zl as infraEnvFromOutputs,ql as listCommandHistory,Zo as redeployServerlessApp,dt as resolveServerlessFunctions,xu as restoreServerlessDatabase,es as rollbackServerlessApp,Nu as runAndRecordCommand,Du as runDbQuery,_t as runRemoteCommand,ts as scaleServerlessDatabase,j as serverlessInfo,zi as setMaintenance};
1
+ import{dt,zl,Yo,Vi,Pu,Zo,es,zi,_t,Nu,ql,ku,Du,j,ts,xu}from"./chunk-w637s5q0.js";import"./chunk-4zbnwt9b.js";import"./chunk-vymg9ywg.js";import"./chunk-80zkjpfz.js";import"./chunk-2paqksap.js";import"./chunk-bckm6fre.js";import"./chunk-bj5nq0kn.js";export{Vi as assertEnvWithinLimit,Yo as buildFunctionEnv,Pu as deployServerlessApp,ku as getCommandRecord,zl as infraEnvFromOutputs,ql as listCommandHistory,Zo as redeployServerlessApp,dt as resolveServerlessFunctions,xu as restoreServerlessDatabase,es as rollbackServerlessApp,Nu as runAndRecordCommand,Du as runDbQuery,_t as runRemoteCommand,ts as scaleServerlessDatabase,j as serverlessInfo,zi as setMaintenance};
@@ -1,6 +1,6 @@
1
- import{Ql}from"./chunk-wge61ccr.js";var g={};Ql(g,{ProgressBar:()=>v,Spinner:()=>o,box:()=>he,checkAwsCli:()=>As,checkAwsCredentials:()=>Is,colorize:()=>Lt,colors:()=>T,confirm:()=>d,error:()=>r,formatBytes:()=>en,formatDuration:()=>b,getAwsAccountId:()=>Rs,getAwsRegions:()=>Ps,header:()=>i,info:()=>e,prompt:()=>I,select:()=>fo,step:()=>m,success:()=>n,table:()=>c,warn:()=>a,warning:()=>Er});var T={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m"};function Lt(t,s){return`${T[s]}${t}${T.reset}`}function n(t){console.log(`${T.green}✓${T.reset} ${t}`)}function r(t){console.error(`${T.red}✗${T.reset} ${t}`)}function a(t){console.warn(`${T.yellow}⚠${T.reset} ${t}`)}var Er=a;function e(t){console.log(`${T.blue}ℹ${T.reset} ${t}`)}function m(t){console.log(`${T.cyan}→${T.reset} ${t}`)}function i(t){console.log(`
1
+ import{Ql}from"./chunk-wge61ccr.js";var g={};Ql(g,{ProgressBar:()=>v,Spinner:()=>o,box:()=>he,checkAwsCli:()=>As,checkAwsCredentials:()=>Is,colorize:()=>Lt,colors:()=>T,confirm:()=>d,error:()=>r,formatBytes:()=>tn,formatDuration:()=>b,getAwsAccountId:()=>Rs,getAwsRegions:()=>Ps,header:()=>i,info:()=>e,prompt:()=>I,select:()=>fo,step:()=>m,success:()=>n,table:()=>c,warn:()=>a,warning:()=>Er});var T={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m"};function Lt(t,s){return`${T[s]}${t}${T.reset}`}function n(t){console.log(`${T.green}✓${T.reset} ${t}`)}function r(t){console.error(`${T.red}✗${T.reset} ${t}`)}function a(t){console.warn(`${T.yellow}⚠${T.reset} ${t}`)}var Er=a;function e(t){console.log(`${T.blue}ℹ${T.reset} ${t}`)}function m(t){console.log(`${T.cyan}→${T.reset} ${t}`)}function i(t){console.log(`
2
2
  ${T.bright}${T.cyan}${t}${T.reset}
3
3
  `)}var x=!!(process.env.CI||process.env.GITHUB_ACTIONS||process.env.BUILDKITE||process.env.CIRCLECI||process.env.GITLAB_CI);class o{frames=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];interval=null;currentFrame=0;message;constructor(t){this.message=t}get text(){return this.message}set text(t){if(this.message=t,x&&this.interval)console.log(` ${t}`)}start(){if(x){console.log(` ${this.message}`),this.interval=!0;return}this.interval=setInterval(()=>{process.stdout.write(`\r${T.cyan}${this.frames[this.currentFrame]}${T.reset} ${this.message}`),this.currentFrame=(this.currentFrame+1)%this.frames.length},80)}succeed(t){this.stop(),n(t||this.message)}fail(t){this.stop(),r(t||this.message)}warn(t){this.stop(),Er(t||this.message)}stop(){if(this.interval){if(!x)process.stdout.write("\r");if(typeof this.interval==="object")clearInterval(this.interval);this.interval=null}}}class v{total;current=0;width=40;constructor(t){this.total=t}update(t){this.current=t,this.render()}increment(){this.current++,this.render()}render(){let t=Math.floor(this.current/this.total*100),s=Math.floor(this.current/this.total*this.width),l=this.width-s,u=`${"█".repeat(s)}${"░".repeat(l)}`;if(process.stdout.write(`\r${T.cyan}${u}${T.reset} ${t}% (${this.current}/${this.total})`),this.current>=this.total)process.stdout.write(`
4
- `)}}async function I(t,s){let l=await import("node:readline"),u=l.createInterface({input:process.stdin,output:process.stdout});return new Promise((p)=>{let h=s?`${T.cyan}?${T.reset} ${t} ${T.gray}(${s})${T.reset}: `:`${T.cyan}?${T.reset} ${t}: `;u.question(h,(f)=>{u.close(),p(f||s||"")})})}async function d(t,s=!1){let l=await I(`${t} (y/n)`,s?"y":"n");return l.toLowerCase()==="y"||l.toLowerCase()==="yes"}async function fo(t,s){console.log(`${T.cyan}?${T.reset} ${t}`),s.forEach((p,h)=>{console.log(` ${T.gray}${h+1}.${T.reset} ${p}`)});let l=await I("Select","1"),u=Number.parseInt(l)-1;if(u>=0&&u<s.length)return s[u];return s[0]}function c(t,s){let l=t.map((p,h)=>{let f=Math.max(...s.map((w)=>(w[h]||"").length));return Math.max(p.length,f)}),u=t.map((p,h)=>p.padEnd(l[h])).join(" ");console.log(Lt(u,"bright")),console.log(Lt("─".repeat(u.length),"gray")),s.forEach((p)=>{let h=p.map((f,w)=>(f||"").padEnd(l[w])).join(" ");console.log(h)})}function en(t){if(t===0)return"0 B";let s=1024,l=["B","KB","MB","GB","TB"],u=Math.floor(Math.log(t)/Math.log(s));return`${Number.parseFloat((t/s**u).toFixed(2))} ${l[u]}`}function b(t){if(t<1000)return`${t}ms`;let s=Math.floor(t/1000);if(s<60)return`${s}s`;let l=Math.floor(s/60),u=s%60;if(l<60)return`${l}m ${u}s`;let p=Math.floor(l/60),h=l%60;return`${p}h ${h}m`}function he(t,s="cyan"){let l=t.split(`
4
+ `)}}async function I(t,s){let l=await import("node:readline"),u=l.createInterface({input:process.stdin,output:process.stdout});return new Promise((p)=>{let h=s?`${T.cyan}?${T.reset} ${t} ${T.gray}(${s})${T.reset}: `:`${T.cyan}?${T.reset} ${t}: `;u.question(h,(f)=>{u.close(),p(f||s||"")})})}async function d(t,s=!1){let l=await I(`${t} (y/n)`,s?"y":"n");return l.toLowerCase()==="y"||l.toLowerCase()==="yes"}async function fo(t,s){console.log(`${T.cyan}?${T.reset} ${t}`),s.forEach((p,h)=>{console.log(` ${T.gray}${h+1}.${T.reset} ${p}`)});let l=await I("Select","1"),u=Number.parseInt(l)-1;if(u>=0&&u<s.length)return s[u];return s[0]}function c(t,s){let l=t.map((p,h)=>{let f=Math.max(...s.map((w)=>(w[h]||"").length));return Math.max(p.length,f)}),u=t.map((p,h)=>p.padEnd(l[h])).join(" ");console.log(Lt(u,"bright")),console.log(Lt("─".repeat(u.length),"gray")),s.forEach((p)=>{let h=p.map((f,w)=>(f||"").padEnd(l[w])).join(" ");console.log(h)})}function tn(t){if(t===0)return"0 B";let s=1024,l=["B","KB","MB","GB","TB"],u=Math.floor(Math.log(t)/Math.log(s));return`${Number.parseFloat((t/s**u).toFixed(2))} ${l[u]}`}function b(t){if(t<1000)return`${t}ms`;let s=Math.floor(t/1000);if(s<60)return`${s}s`;let l=Math.floor(s/60),u=s%60;if(l<60)return`${l}m ${u}s`;let p=Math.floor(l/60),h=l%60;return`${p}h ${h}m`}function he(t,s="cyan"){let l=t.split(`
5
5
  `),u=Math.max(...l.map((h)=>h.length)),p="─".repeat(u+2);console.log(Lt(`┌${p}┐`,s)),l.forEach((h)=>{console.log(Lt(`│ ${h.padEnd(u)} │`,s))}),console.log(Lt(`└${p}┘`,s))}async function As(){return!0}async function Is(){try{let{AWSClient:t}=await import("./chunk-c51xp8f7.js");return await new t().request({service:"sts",region:"us-east-1",method:"POST",path:"/",body:new URLSearchParams({Action:"GetCallerIdentity",Version:"2011-06-15"}).toString()}),!0}catch{return!1}}async function Rs(){try{let{AWSClient:t}=await import("./chunk-c51xp8f7.js"),l=await new t().request({service:"sts",region:"us-east-1",method:"POST",path:"/",body:new URLSearchParams({Action:"GetCallerIdentity",Version:"2011-06-15"}).toString()});return l.Account||l.GetCallerIdentityResult?.Account||null}catch{return null}}async function Ps(){try{let{AWSClient:t}=await import("./chunk-c51xp8f7.js"),l=await new t().request({service:"ec2",region:"us-east-1",method:"POST",path:"/",body:new URLSearchParams({Action:"DescribeRegions",Version:"2016-11-15"}).toString()}),u=[];if(l.regionInfo){let p=Array.isArray(l.regionInfo)?l.regionInfo:[l.regionInfo];u.push(...p.map((h)=>h.regionName))}return u.length>0?u:y()}catch{return y()}}function y(){return["us-east-1","us-east-2","us-west-1","us-west-2","eu-west-1","eu-central-1","ap-southeast-1","ap-northeast-1"]}
6
- export{T,Lt,n,r,a,Er,e,m,i,o,I,d,fo,c,en,he,As,Is,Rs,Ps,g};
6
+ export{T,Lt,n,r,a,Er,e,m,i,o,I,d,fo,c,tn,he,As,Is,Rs,Ps,g};
@@ -1 +1 @@
1
- import{hr,qa,Ha,St,yr,Sr,br,vr,Qr}from"./chunk-nnkhrm4n.js";import"./chunk-gj5jkhfr.js";import"./chunk-6xw0r4gn.js";export{yr as AwsSecretsManagerConfigurationBackend,Sr as AwsSsmConfigurationBackend,vr as ConfigurationService,hr as ConfigurationStore,br as ExternalConfigurationBackend,St as LocalEncryptedConfigurationBackend,qa as parseDotenv,Ha as serializeDotenv,Qr as synchronizeConfiguredConfiguration};
1
+ import{hr,qa,Ha,St,yr,Sr,br,vr,Yr}from"./chunk-1wvrtg42.js";import"./chunk-wr6a423y.js";import"./chunk-bj5nq0kn.js";export{yr as AwsSecretsManagerConfigurationBackend,Sr as AwsSsmConfigurationBackend,vr as ConfigurationService,hr as ConfigurationStore,br as ExternalConfigurationBackend,St as LocalEncryptedConfigurationBackend,qa as parseDotenv,Ha as serializeDotenv,Yr as synchronizeConfiguredConfiguration};
@@ -1,2 +1,2 @@
1
- import{Ao,on,Ks,bi,Po,No}from"./chunk-6xw0r4gn.js";import{e}from"./chunk-7h6h8yxm.js";import{bt}from"./chunk-ynr22ma8.js";import{execFileSync as C}from"node:child_process";import{mkdirSync as w,mkdtempSync as I,rmSync as U,writeFileSync as g}from"node:fs";import{tmpdir as j}from"node:os";import{dirname as O,join as o}from"node:path";function E(s,t){for(let r of t){let d=o(s,r.name);w(O(d),{recursive:!0}),g(d,r.data,r.mode?{mode:r.mode}:void 0)}}async function Lu(s){let{app:t,projectRoot:r,region:d,repository:u}=s,x=t.architecture??"x86_64",R=x==="arm64"?"linux/arm64":"linux/amd64",b=t.kind==="php",n=s.onStep??(()=>{}),a=I(o(j(),"tscloud-img-"));try{let h=o(a,"app");w(h,{recursive:!0});let f,y;if(b){Po({projectRoot:r,app:t,skipBuild:s.skipBuild,onStep:n}),n("staging application tree");let i=No(r);E(h,i),E(o(a,"runtime"),bi().map((c)=>({name:c.path,data:c.contents,mode:c.mode})));let v=t.handlers?.http??"public/index.php";f={http:v,queue:t.handlers?.queue??v,cli:t.handlers?.cli??v},y=Ao(i.map((c)=>`${c.name}:${c.data.length}`).join("|"))}else{n("bundling application");let i=await on({projectRoot:r,app:t,skipBuild:s.skipBuild,onStep:n});g(o(h,"index.mjs"),i.bundle),f=i.handlers,y=i.sha256}let B=y.slice(0,16);g(o(a,"Dockerfile"),Ks({kind:t.kind??"node",phpVersion:t.phpVersion,architecture:x}));let k=new bt(d),p;try{p=(await k.describeRepositories({repositoryNames:[u]})).repositories?.[0]?.repositoryUri??""}catch{p=""}if(!p)n(`creating ECR repository ${u}`),p=(await k.createRepository({repositoryName:u,imageScanningConfiguration:{scanOnPush:!0}})).repository?.repositoryUri??"";if(!p)throw Error(`could not resolve ECR repository URI for ${u}`);let l=`${p}:${B}`;n("docker build"),C("docker",["build","--platform",R,"--provenance=false","--sbom=false","-t",l,a],{stdio:"inherit"}),n("ecr auth + push");let m=(await k.getAuthorizationToken()).authorizationData?.[0];if(!m?.authorizationToken||!m.proxyEndpoint)throw Error("failed to get an ECR authorization token");let A=m.proxyEndpoint.replace(/^https?:\/\//,""),S=o(a,".docker");return w(S,{recursive:!0}),g(o(S,"config.json"),JSON.stringify({auths:{[A]:{auth:m.authorizationToken}}})),C("docker",["push",l],{stdio:"inherit",env:{...process.env,DOCKER_CONFIG:S}}),e(`Image: ${l}`),{imageUri:l,tag:B,handlers:f}}finally{U(a,{recursive:!0,force:!0})}}
1
+ import{Ao,sn,Ks,bi,Po,No}from"./chunk-bj5nq0kn.js";import{e}from"./chunk-2paqksap.js";import{bt}from"./chunk-ynr22ma8.js";import{execFileSync as C}from"node:child_process";import{mkdirSync as w,mkdtempSync as I,rmSync as U,writeFileSync as g}from"node:fs";import{tmpdir as j}from"node:os";import{dirname as O,join as o}from"node:path";function E(s,t){for(let r of t){let d=o(s,r.name);w(O(d),{recursive:!0}),g(d,r.data,r.mode?{mode:r.mode}:void 0)}}async function Lu(s){let{app:t,projectRoot:r,region:d,repository:u}=s,x=t.architecture??"x86_64",R=x==="arm64"?"linux/arm64":"linux/amd64",b=t.kind==="php",n=s.onStep??(()=>{}),a=I(o(j(),"tscloud-img-"));try{let h=o(a,"app");w(h,{recursive:!0});let f,y;if(b){Po({projectRoot:r,app:t,skipBuild:s.skipBuild,onStep:n}),n("staging application tree");let i=No(r);E(h,i),E(o(a,"runtime"),bi().map((c)=>({name:c.path,data:c.contents,mode:c.mode})));let v=t.handlers?.http??"public/index.php";f={http:v,queue:t.handlers?.queue??v,cli:t.handlers?.cli??v},y=Ao(i.map((c)=>`${c.name}:${c.data.length}`).join("|"))}else{n("bundling application");let i=await sn({projectRoot:r,app:t,skipBuild:s.skipBuild,onStep:n});g(o(h,"index.mjs"),i.bundle),f=i.handlers,y=i.sha256}let B=y.slice(0,16);g(o(a,"Dockerfile"),Ks({kind:t.kind??"node",phpVersion:t.phpVersion,architecture:x}));let k=new bt(d),p;try{p=(await k.describeRepositories({repositoryNames:[u]})).repositories?.[0]?.repositoryUri??""}catch{p=""}if(!p)n(`creating ECR repository ${u}`),p=(await k.createRepository({repositoryName:u,imageScanningConfiguration:{scanOnPush:!0}})).repository?.repositoryUri??"";if(!p)throw Error(`could not resolve ECR repository URI for ${u}`);let l=`${p}:${B}`;n("docker build"),C("docker",["build","--platform",R,"--provenance=false","--sbom=false","-t",l,a],{stdio:"inherit"}),n("ecr auth + push");let m=(await k.getAuthorizationToken()).authorizationData?.[0];if(!m?.authorizationToken||!m.proxyEndpoint)throw Error("failed to get an ECR authorization token");let A=m.proxyEndpoint.replace(/^https?:\/\//,""),S=o(a,".docker");return w(S,{recursive:!0}),g(o(S,"config.json"),JSON.stringify({auths:{[A]:{auth:m.authorizationToken}}})),C("docker",["push",l],{stdio:"inherit",env:{...process.env,DOCKER_CONFIG:S}}),e(`Image: ${l}`),{imageUri:l,tag:B,handlers:f}}finally{U(a,{recursive:!0,force:!0})}}
2
2
  export{Lu};
@@ -0,0 +1 @@
1
+ import{ti}from"./chunk-9q8zjavc.js";import"./chunk-7a7n6p2m.js";import"./chunk-16rs9egs.js";import"./chunk-6vay4ggv.js";import"./chunk-vymg9ywg.js";import"./chunk-80zkjpfz.js";import"./chunk-bckm6fre.js";import"./chunk-bj5nq0kn.js";export{ti as resolveServerDashboardData};
@@ -1,9 +1,9 @@
1
- import{V,wr}from"./chunk-6xw0r4gn.js";function W(e,t){return`/var/www/${e}-${t}`}var _e=new Set(["laravel","php","statamic","wordpress"]);function ni(e){return e.type!=null&&_e.has(e.type)}function gs(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 gs(e).length>0}function ee(e){if(e.deploy)return e.deploy;if(ni(e))return"server";if(e.start)return"server";return"bucket"}function P(e){if(e.redirect)return"redirect";if(Se(e))return"proxy";if(ni(e))return"server-php";if(ee(e)==="bucket")return"bucket";return e.start?"server-app":"server-static"}function so(e){return e.infrastructure?.compute!=null||Boolean(e.cloud?.attachTo?.trim())}function fs(e,t={}){let r=[],n=[],i=e.sites||{},s=so(e),c=wr(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 hs(e){let t=P(e);return t!=="bucket"&&t!=="redirect"&&t!=="proxy"}function Ma(e){return P(e)==="bucket"}function Ua(e,t){if(V(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 gr(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 ft(){return'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true'}function Ge(e){if(e.length===0)return[];return[`(cd /opt/pantry && pantry install ${[...new Set(e)].map(N).join(" ")})`]}function ao(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",F="mail",G=`${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(`
1
+ import{V,wr}from"./chunk-bj5nq0kn.js";function W(e,t){return`/var/www/${e}-${t}`}var _e=new Set(["laravel","php","statamic","wordpress"]);function ni(e){return e.type!=null&&_e.has(e.type)}function gs(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 gs(e).length>0}function ee(e){if(e.deploy)return e.deploy;if(ni(e))return"server";if(e.start)return"server";return"bucket"}function P(e){if(e.redirect)return"redirect";if(Se(e))return"proxy";if(ni(e))return"server-php";if(ee(e)==="bucket")return"bucket";return e.start?"server-app":"server-static"}function so(e){return e.infrastructure?.compute!=null||Boolean(e.cloud?.attachTo?.trim())}function fs(e,t={}){let r=[],n=[],i=e.sites||{},s=so(e),c=wr(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 hs(e){let t=P(e);return t!=="bucket"&&t!=="redirect"&&t!=="proxy"}function Ma(e){return P(e)==="bucket"}function Ua(e,t){if(V(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 gr(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 ft(){return'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true'}function Ge(e){if(e.length===0)return[];return[`(cd /opt/pantry && pantry install ${[...new Set(e)].map(N).join(" ")})`]}function ao(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",F="mail",G=`${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
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(`
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=${G}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"`,`ExecStart=${G}/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
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" ${G}/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[...Ge(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/${F}.service <<'TS_CLOUD_MAIL_UNIT_EOF'`,he(e),"TS_CLOUD_MAIL_UNIT_EOF","systemctl daemon-reload",`systemctl enable ${F}`,`systemctl restart ${F}`,...ye(e)]}var g=`${M}/pantry/.bin`,X=15306,K=15991,w=15999,ne=16101,B=2379,v="/var/lib/vitess",z=100;function ii(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??X,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 ${w}`])})}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:${B}`,`--advertise-client-urls http://127.0.0.1:${B}`]),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:${B}`}`,"--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 ${w}`,`--port ${w+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(z).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 ${z}`,`--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??X}`,`--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:${B}`,n=`${g}/vtctldclient --server 127.0.0.1:${w}`,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(z).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??X;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 co(e){if(!ii(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",...Ge(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 oi(e){if(e?.engine&&ke.has(e.engine))return!1;return!e?.host||e.host==="127.0.0.1"||e.host==="localhost"}function fr(e,t="psql"){let r=e?.port??5432;if(oi(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 lo(e={},t={}){let r=Ne(e),n=co(e.vitess),i=t.mail?re(t.mail):[];if(r.packages.length===0)return[...n,...i];return[...Ge(r.packages),...ao(r.services),...n,...i]}function ht(e,t={}){if(!e?.name)return[];if(!oi(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],H=[];for(let q of k)if(u.access==="readonly")H.push(`GRANT CONNECT ON DATABASE ${a(q)} TO ${a(u.username)};`,`\\connect ${a(q)}`,`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 H.push(`GRANT ALL PRIVILEGES ON DATABASE ${a(q)} TO ${a(u.username)};`);return H},I=e.users||[],me=e.port??5432;return[ft(),`for i in $(seq 1 30); do pg_isready -p ${me} -q && break; sleep 2; done`,`${fr(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[ft(),`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[`${fr(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 Ba(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",Gr="/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??X,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 ${w}`])})}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:${B}`,`--advertise-client-urls http://127.0.0.1:${B}`]),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:${B}`}`,"--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 ${w}`,`--port ${w+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(z).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 ${z}`,`--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??X}`,`--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:${B}`,n=`${g}/vtctldclient --server 127.0.0.1:${w}`,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(z).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??X;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 co(e){if(!ii(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",...Ge(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 oi(e){if(e?.engine&&ke.has(e.engine))return!1;return!e?.host||e.host==="127.0.0.1"||e.host==="localhost"}function fr(e,t="psql"){let r=e?.port??5432;if(oi(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 lo(e={},t={}){let r=Ne(e),n=co(e.vitess),i=t.mail?re(t.mail):[];if(r.packages.length===0)return[...n,...i];return[...Ge(r.packages),...ao(r.services),...n,...i]}function ht(e,t={}){if(!e?.name)return[];if(!oi(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],H=[];for(let q of k)if(u.access==="readonly")H.push(`GRANT CONNECT ON DATABASE ${a(q)} TO ${a(u.username)};`,`\\connect ${a(q)}`,`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 H.push(`GRANT ALL PRIVILEGES ON DATABASE ${a(q)} TO ${a(u.username)};`);return H},I=e.users||[],me=e.port??5432;return[ft(),`for i in $(seq 1 30); do pg_isready -p ${me} -q && break; sleep 2; done`,`${fr(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[ft(),`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[`${fr(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 Ba(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",Kr="/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 uo(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 > ${Gr} <<'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 ${Gr}`,`cat > ${le} <<'TS_CLOUD_BACKUP_CRON_EOF'`,`${n} root ${Gr} >> /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 si(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?`${fr(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 po=["storage",".env"],ai=4;function C(e){return`${e.replace(/\/+$/,"")}/.ts-cloud`}function ys(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 Ot(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 Ss(e){return typeof e==="string"?e:e.path}function Fa(e){let t=new Map;for(let r of e)t.set(Ss(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 ci(e,t=po){let r=[`mkdir -p ${e.releases} ${e.shared}`,...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 bs(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 vs(e){let t=`${e.release}.incoming`;return[`rm -rf ${t}`,`mkdir -p ${t}`,...Ye(e),'if [ "$TS_CLOUD_IS_LIVE" = "yes" ]; then',` TS_CLOUD_STAGED=${t}`,"else",` rm -rf ${e.release}`,` mkdir -p ${e.release}`,` rmdir ${t}`,` TS_CLOUD_STAGED=${e.release}`,"fi"]}function Ts(e){let t=`TS_CLOUD_TRAP_LIVE="$(readlink -f ${e.current} 2>/dev/null || true)"`,r=`TS_CLOUD_TRAP_TARGET="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`;return`trap '${`if [ $? -ne 0 ]; then ${t}; ${r}; [ "$TS_CLOUD_TRAP_LIVE" = "$TS_CLOUD_TRAP_TARGET" ] || rm -rf ${e.release}; fi`}' EXIT`}function Ye(e){return[`TS_CLOUD_LIVE_PATH="$(readlink -f ${e.current} 2>/dev/null || true)"`,`TS_CLOUD_RELEASE_PATH="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`,'if [ -n "$TS_CLOUD_LIVE_PATH" ] && [ "$TS_CLOUD_LIVE_PATH" = "$TS_CLOUD_RELEASE_PATH" ]; then TS_CLOUD_IS_LIVE=yes; else TS_CLOUD_IS_LIVE=no; fi']}function Es(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 mo(e,t=po){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 Kr(e){return[`ln -sfn ${e.release} ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`]}function ja(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 Jr(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 ws(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 go(e,t){let r=C(e),n=qe(e,t.releaseId),i=ys(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{W,ni,gs,P,so,fs,hs,Ma,Ua,M,gr,ft,Ge,ao,ii,co,oi,fr,lo,ht,Ba,Gr,uo,si,po,ai,ys,Ot,Ss,Fa,ci,bs,vs,Ts,Es,mo,Kr,ja,Jr,ws,go};
8
+ `)}function uo(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 > ${Kr} <<'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 ${Kr}`,`cat > ${le} <<'TS_CLOUD_BACKUP_CRON_EOF'`,`${n} root ${Kr} >> /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 si(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?`${fr(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 po=["storage",".env"],ai=4;function C(e){return`${e.replace(/\/+$/,"")}/.ts-cloud`}function ys(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 Ot(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 Ss(e){return typeof e==="string"?e:e.path}function Fa(e){let t=new Map;for(let r of e)t.set(Ss(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 ci(e,t=po){let r=[`mkdir -p ${e.releases} ${e.shared}`,...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 bs(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 vs(e){let t=`${e.release}.incoming`;return[`rm -rf ${t}`,`mkdir -p ${t}`,...Ye(e),'if [ "$TS_CLOUD_IS_LIVE" = "yes" ]; then',` TS_CLOUD_STAGED=${t}`,"else",` rm -rf ${e.release}`,` mkdir -p ${e.release}`,` rmdir ${t}`,` TS_CLOUD_STAGED=${e.release}`,"fi"]}function Ts(e){let t=`TS_CLOUD_TRAP_LIVE="$(readlink -f ${e.current} 2>/dev/null || true)"`,r=`TS_CLOUD_TRAP_TARGET="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`;return`trap '${`if [ $? -ne 0 ]; then ${t}; ${r}; [ "$TS_CLOUD_TRAP_LIVE" = "$TS_CLOUD_TRAP_TARGET" ] || rm -rf ${e.release}; fi`}' EXIT`}function Ye(e){return[`TS_CLOUD_LIVE_PATH="$(readlink -f ${e.current} 2>/dev/null || true)"`,`TS_CLOUD_RELEASE_PATH="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`,'if [ -n "$TS_CLOUD_LIVE_PATH" ] && [ "$TS_CLOUD_LIVE_PATH" = "$TS_CLOUD_RELEASE_PATH" ]; then TS_CLOUD_IS_LIVE=yes; else TS_CLOUD_IS_LIVE=no; fi']}function Es(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 mo(e,t=po){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 Jr(e){return[`ln -sfn ${e.release} ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`]}function ja(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 Xr(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 ws(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 go(e,t){let r=C(e),n=qe(e,t.releaseId),i=ys(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{W,ni,gs,P,so,fs,hs,Ma,Ua,M,gr,ft,Ge,ao,ii,co,oi,fr,lo,ht,Ba,Kr,uo,si,po,ai,ys,Ot,Ss,Fa,ci,bs,vs,Ts,Es,mo,Jr,ja,Xr,ws,go};
@@ -1 +1 @@
1
- import{Jl,La,Xl,no,io,oo,ms}from"./chunk-bnv8yd9w.js";import"./chunk-6xw0r4gn.js";export{Jl as MANAGEMENT_DASHBOARD_SITE,ms as buildManagementDashboardArtifact,La as dashboardCredentialsFile,io as ensureManagementDashboard,oo as managementDashboardSiteNames,Xl as resolveDashboardAuth,no as resolveUiSource};
1
+ import{Jl,La,Xl,no,io,oo,ms}from"./chunk-16rs9egs.js";import"./chunk-bj5nq0kn.js";export{Jl as MANAGEMENT_DASHBOARD_SITE,ms as buildManagementDashboardArtifact,La as dashboardCredentialsFile,io as ensureManagementDashboard,oo as managementDashboardSiteNames,Xl as resolveDashboardAuth,no as resolveUiSource};