@stacksjs/ts-cloud 0.16.44 → 0.16.45

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 (136) hide show
  1. package/dist/bin/{chunk-gn03w47w.js → chunk-01w4zbex.js} +1 -1
  2. package/dist/bin/{chunk-nmqjmx30.js → chunk-12x968en.js} +1 -1
  3. package/dist/bin/chunk-1xxmyx0r.js +1 -0
  4. package/dist/bin/{chunk-kdsgbvep.js → chunk-23m8kbwh.js} +1 -1
  5. package/dist/bin/{chunk-bj7ashn6.js → chunk-2gqhzn2r.js} +1 -1
  6. package/dist/bin/chunk-45qr2bd3.js +1 -0
  7. package/dist/bin/chunk-4nn00brw.js +1 -0
  8. package/dist/bin/{chunk-t80pxn04.js → chunk-50r8znqt.js} +6 -6
  9. package/dist/bin/chunk-5f1n5d80.js +1 -0
  10. package/dist/bin/{chunk-s64d5nw2.js → chunk-5mm6qn6m.js} +1 -1
  11. package/dist/bin/chunk-5xr76cms.js +1 -0
  12. package/dist/bin/{chunk-q40k9jvk.js → chunk-65yvjecx.js} +2 -2
  13. package/dist/bin/{chunk-5amvqed8.js → chunk-6y6g726g.js} +3 -3
  14. package/dist/bin/{chunk-f64jvh96.js → chunk-7qbxq0be.js} +2 -2
  15. package/dist/bin/{chunk-8z4wgqkh.js → chunk-cz2wq0tf.js} +1 -1
  16. package/dist/bin/chunk-d0tmmzy5.js +1 -0
  17. package/dist/bin/{chunk-erf79tm2.js → chunk-dawvjb7v.js} +21 -21
  18. package/dist/bin/{chunk-7p2va3nj.js → chunk-de69nra4.js} +1 -1
  19. package/dist/bin/{chunk-tf8qxy9k.js → chunk-dj03v81n.js} +20 -20
  20. package/dist/bin/chunk-fqghdpvr.js +1 -0
  21. package/dist/bin/{chunk-35x7z78g.js → chunk-frzpqsbj.js} +1 -1
  22. package/dist/bin/chunk-gkdr09xx.js +1 -0
  23. package/dist/bin/{chunk-xxe9ga9r.js → chunk-gyvkravq.js} +3 -3
  24. package/dist/bin/{chunk-jaexpxs8.js → chunk-her9ny96.js} +1 -1
  25. package/dist/bin/{chunk-3hkppc7h.js → chunk-kqxk1pds.js} +1 -1
  26. package/dist/bin/{chunk-hfnpjy9y.js → chunk-n2c6y0k1.js} +1 -1
  27. package/dist/bin/{chunk-3v2pd05g.js → chunk-nhqz2j90.js} +1 -1
  28. package/dist/bin/chunk-pg65zy8y.js +1 -0
  29. package/dist/bin/chunk-pr1dg1km.js +1 -0
  30. package/dist/bin/{chunk-dkf2kcsc.js → chunk-psvqpztv.js} +3 -3
  31. package/dist/bin/{chunk-ce1qnjs2.js → chunk-pzj1ac7x.js} +1 -1
  32. package/dist/bin/{chunk-gngsb689.js → chunk-q4dywv80.js} +2 -2
  33. package/dist/bin/{chunk-pf9dbm3b.js → chunk-q8b77zgw.js} +1 -1
  34. package/dist/bin/{chunk-qj6tr7bw.js → chunk-qq1f07te.js} +3 -3
  35. package/dist/bin/chunk-r1kg6yxp.js +1 -0
  36. package/dist/bin/{chunk-mgwmt2et.js → chunk-rdkr74y2.js} +2 -2
  37. package/dist/bin/{chunk-jh1vmant.js → chunk-rgcrsd5m.js} +1 -1
  38. package/dist/bin/chunk-t1mmfpn1.js +1 -0
  39. package/dist/bin/chunk-thph4z3k.js +1 -0
  40. package/dist/bin/chunk-txykq6f1.js +1 -0
  41. package/dist/bin/{chunk-2r9tj1ac.js → chunk-v09tfezh.js} +5 -5
  42. package/dist/bin/{chunk-dryvqne2.js → chunk-v7t6f8aw.js} +2 -2
  43. package/dist/bin/{chunk-knzje4ka.js → chunk-vjg2fymw.js} +1 -1
  44. package/dist/bin/chunk-vt3hjh9q.js +1 -0
  45. package/dist/bin/{chunk-sg8hcdev.js → chunk-w29z877b.js} +1 -1
  46. package/dist/bin/{chunk-7593hjcq.js → chunk-xdk0gmxt.js} +1 -1
  47. package/dist/bin/{chunk-fkzp9sg5.js → chunk-xe527q1k.js} +1 -1
  48. package/dist/bin/{chunk-9eqpnanr.js → chunk-xx9mrcfs.js} +1 -1
  49. package/dist/bin/{chunk-vjfwnj9z.js → chunk-ym9h629y.js} +4 -4
  50. package/dist/bin/{chunk-cqc4e8md.js → chunk-yp3a0j9n.js} +1 -1
  51. package/dist/bin/{chunk-kzpzkdpd.js → chunk-z8k9mcn5.js} +1 -1
  52. package/dist/bin/chunk-z8scg2vy.js +1 -0
  53. package/dist/bin/{chunk-pnj95hwr.js → chunk-znd507q9.js} +1 -1
  54. package/dist/bin/cli.js +98 -98
  55. package/dist/bin/dashboard-server.js +1 -1
  56. package/dist/{chunk-txwnpxzf.js → chunk-294kdscm.js} +1 -1
  57. package/dist/{chunk-a102vqez.js → chunk-vv5fmmhr.js} +1 -1
  58. package/dist/deploy/index.js +1 -1
  59. package/dist/drivers/factory.d.ts +3 -3
  60. package/dist/drivers/index.js +1 -1
  61. package/dist/fly/client.d.ts +153 -0
  62. package/dist/fly/deploy.d.ts +72 -0
  63. package/dist/fly/index.d.ts +2 -0
  64. package/dist/index.d.ts +1 -0
  65. package/dist/index.js +26 -26
  66. package/dist/ui/404.html +1 -1
  67. package/dist/ui/accept-invitation.html +1 -1
  68. package/dist/ui/access-denied.html +1 -1
  69. package/dist/ui/account/automation.html +5 -5
  70. package/dist/ui/account/security.html +2 -2
  71. package/dist/ui/applications/compose.html +6 -6
  72. package/dist/ui/applications/new.html +2 -2
  73. package/dist/ui/data/backups.html +6 -6
  74. package/dist/ui/data/services.html +6 -6
  75. package/dist/ui/data/volumes.html +6 -6
  76. package/dist/ui/index.html +6 -6
  77. package/dist/ui/infrastructure/topology.html +6 -6
  78. package/dist/ui/integrations.html +1 -1
  79. package/dist/ui/operations/alerts.html +6 -6
  80. package/dist/ui/operations/configuration.html +6 -6
  81. package/dist/ui/operations/jobs.html +6 -6
  82. package/dist/ui/operations/maintenance.html +5 -5
  83. package/dist/ui/operations/observability.html +6 -6
  84. package/dist/ui/operations/previews.html +6 -6
  85. package/dist/ui/operations/queue.html +6 -6
  86. package/dist/ui/operations/regions.html +5 -5
  87. package/dist/ui/operations/releases.html +6 -6
  88. package/dist/ui/operations/spend.html +6 -6
  89. package/dist/ui/operations/workloads.html +6 -6
  90. package/dist/ui/security.html +1 -1
  91. package/dist/ui/server/actions.html +6 -6
  92. package/dist/ui/server/activity.html +1 -1
  93. package/dist/ui/server/capacity.html +6 -6
  94. package/dist/ui/server/database.html +6 -6
  95. package/dist/ui/server/deployments.html +6 -6
  96. package/dist/ui/server/diagnostics.html +1 -1
  97. package/dist/ui/server/firewall.html +6 -6
  98. package/dist/ui/server/fleet.html +6 -6
  99. package/dist/ui/server/logs.html +6 -6
  100. package/dist/ui/server/metrics.html +6 -6
  101. package/dist/ui/server/security.html +2 -2
  102. package/dist/ui/server/services.html +1 -1
  103. package/dist/ui/server/sites.html +6 -6
  104. package/dist/ui/server/ssh-keys.html +6 -6
  105. package/dist/ui/server/team.html +6 -6
  106. package/dist/ui/server/terminal.html +1 -1
  107. package/dist/ui/serverless/alarms.html +6 -6
  108. package/dist/ui/serverless/assets.html +2 -2
  109. package/dist/ui/serverless/cost.html +2 -2
  110. package/dist/ui/serverless/data.html +6 -6
  111. package/dist/ui/serverless/deployments.html +2 -2
  112. package/dist/ui/serverless/firewall.html +1 -1
  113. package/dist/ui/serverless/functions.html +6 -6
  114. package/dist/ui/serverless/logs.html +6 -6
  115. package/dist/ui/serverless/metrics.html +2 -2
  116. package/dist/ui/serverless/queues.html +6 -6
  117. package/dist/ui/serverless/secrets.html +6 -6
  118. package/dist/ui/serverless/traces.html +6 -6
  119. package/dist/ui/serverless.html +5 -5
  120. package/package.json +3 -3
  121. package/dist/bin/chunk-26rf5dy2.js +0 -1
  122. package/dist/bin/chunk-5khcwxhn.js +0 -1
  123. package/dist/bin/chunk-5nc1g18b.js +0 -1
  124. package/dist/bin/chunk-71ep1g7k.js +0 -1
  125. package/dist/bin/chunk-7fh7b8r1.js +0 -1
  126. package/dist/bin/chunk-7nsjehvx.js +0 -1
  127. package/dist/bin/chunk-bb08ms5q.js +0 -1
  128. package/dist/bin/chunk-g3a9a8bx.js +0 -1
  129. package/dist/bin/chunk-jv9qp13h.js +0 -1
  130. package/dist/bin/chunk-k9ate69x.js +0 -1
  131. package/dist/bin/chunk-mh3rgn0e.js +0 -1
  132. package/dist/bin/chunk-nfb3ew1v.js +0 -1
  133. package/dist/bin/chunk-qgqgdkg0.js +0 -1
  134. package/dist/bin/chunk-s77kny9g.js +0 -1
  135. package/dist/bin/chunk-vn05n5z6.js +0 -1
  136. package/dist/bin/chunk-yxpzm8ce.js +0 -1
@@ -1,4 +1,4 @@
1
- import{ia,Be,A,H,w,F,xe,Jt}from"./chunk-tf8qxy9k.js";import{ae,fn,re,hn,h,Or,ra}from"./chunk-pnj95hwr.js";import{Le,S,gs,hr,mi,gi,mt,nn,vc,$t,on,Je,Me,Xe,Cc,ft,yr,Ue,Qe,fi,hi,io,oo,Ye,sn,vr,ht,m,go,Ps,Ds}from"./chunk-vjfwnj9z.js";import{zt,p}from"./chunk-dkf2kcsc.js";import{g}from"./chunk-nmqjmx30.js";import{me}from"./chunk-kzpzkdpd.js";import{Dr,Tt,kr,Nr,xr,_r,gn}from"./chunk-8z4wgqkh.js";import{qe,ur,Yi,O,tn,mc,gc,_t,li,di}from"./chunk-t80pxn04.js";import{v}from"./chunk-7593hjcq.js";import{oe,G,si}from"./chunk-3v2pd05g.js";import{E}from"./chunk-gn03w47w.js";import{V}from"./chunk-9eqpnanr.js";import{I}from"./chunk-7p2va3nj.js";import{J,P,U,Ir,xo,Pr,un}from"./chunk-cqc4e8md.js";import{wo}from"./chunk-xxe9ga9r.js";import{K,Os,$s,Po,Ft,z,Ls}from"./chunk-qj6tr7bw.js";import{js,Vs}from"./chunk-jaexpxs8.js";import{ms}from"./chunk-nj9x0tb8.js";import{rn}from"./chunk-5nmt4s5w.js";import{_,N,ea}from"./chunk-kbwm0sqv.js";import{createHash as jT}from"node:crypto";import{existsSync as uo,mkdtempSync as cp,readdirSync as cb,rmSync as fs,statSync as Sb}from"node:fs";import{readFile as Li,writeFile as ls}from"node:fs/promises";import{tmpdir as kd}from"node:os";import{dirname as UT,extname as Fa,join as Ct,normalize as zT,relative as VT,resolve as qT,sep as GT}from"node:path";import{fileURLToPath as JT}from"node:url";class $d extends Error{status;code;requestId;constructor(e,t,r,n){super(r);this.status=e;this.code=t;this.requestId=n}}class Gi{options;baseUrl;fetchFn;constructor(e){this.options=e;this.baseUrl=e.baseUrl.replace(/\/$/,""),this.fetchFn=e.fetch??fetch}async request(e,t={}){let r=await this.fetchFn(`${this.baseUrl}${e}`,{...t,headers:{accept:"application/json",authorization:`Bearer ${this.options.token}`,...t.headers}}),n=await r.json().catch(()=>({}));if(!r.ok)throw new $d(r.status,n.error?.code??"api_error",n.error?.message??"API request failed.",n.error?.requestId??r.headers.get("x-request-id")??void 0);return n}listProjects(e={}){return this.request(`/api/v1/projects?${new URLSearchParams(Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).map(([t,r])=>[t,String(r)])))}`)}listEnvironments(e,t={}){return this.request(`/api/v1/projects/${encodeURIComponent(e)}/environments?${new URLSearchParams(Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0).map(([r,n])=>[r,String(n)])))}`)}listServices(e,t){return this.request(`/api/v1/services?${new URLSearchParams({projectId:e,...t?{environmentId:t}:{}})}`)}listOperations(e){return this.request(`/api/v1/operations${e?`?projectId=${encodeURIComponent(e)}`:""}`)}listComposeTemplates(){return this.request("/api/v1/compose-templates")}listComposeApplications(e,t){return this.request(`/api/v1/compose-applications?${new URLSearchParams({projectId:e,...t?{environmentId:t}:{}})}`)}previewCompose(e){return this.request("/api/v1/compose-applications/preview",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}createComposeApplication(e){return this.request("/api/v1/compose-applications",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}composeServices(e){return this.request(`/api/v1/compose-applications/${encodeURIComponent(e)}/services`)}composeAction(e,t,r={}){return this.request(`/api/v1/compose-applications/${encodeURIComponent(e)}/${t}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r)})}releaseCapabilities(e,t={}){return this.request(`/api/v1/releases/capabilities?${new URLSearchParams({kind:e,health:String(!!t.health),replicas:String(t.replicas??1)})}`)}listReleases(e,t={}){return this.request(`/api/v1/releases?${new URLSearchParams({projectId:e,...t})}`)}createReleaseArtifact(e){return this.request("/api/v1/release-artifacts",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}createRelease(e){return this.request("/api/v1/releases",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}releaseAction(e,t,r={}){return this.request(`/api/v1/releases/${encodeURIComponent(e)}/${t}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r)})}createDeployment(e,t){return this.request("/api/v1/deployments",{method:"POST",headers:{"content-type":"application/json","idempotency-key":t},body:JSON.stringify(e)})}detectApplication(e){return this.request("/api/v1/application-detections",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}planApplication(e){return this.request("/api/v1/application-plans",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}listApplicationDrafts(e){return this.request(`/api/v1/application-drafts?projectId=${encodeURIComponent(e)}`)}createApplicationDraft(e){return this.request("/api/v1/application-drafts",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}updateApplicationDraft(e){return this.request("/api/v1/application-drafts",{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}createApplication(e,t){return this.request("/api/v1/applications",{method:"POST",headers:{"content-type":"application/json","idempotency-key":t},body:JSON.stringify(e)})}uploadApplicationArtifact(e,t,r){return this.request("/api/v1/application-artifacts",{method:"POST",headers:{"content-type":"application/octet-stream","x-project-id":e,"x-artifact-filename":t},body:r})}listRegistryConnections(){return this.request("/api/v1/registry-connections")}createRegistryConnection(e){return this.request("/api/v1/registry-connections",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}updateRegistryConnection(e){return this.request("/api/v1/registry-connections",{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}disconnectRegistryConnection(e){return this.request("/api/v1/registry-connections",{method:"DELETE",headers:{"content-type":"application/json"},body:JSON.stringify({id:e})})}listQueue(e={}){let t=new URLSearchParams(Object.entries(e).filter(([,r])=>r!==void 0).map(([r,n])=>[r,String(n)]));return this.request(`/api/v1/queue?${t}`)}operationLogs(e,t={}){let r=new URLSearchParams(Object.entries(t).filter(([,n])=>n!==void 0).map(([n,i])=>[n,String(i)]));return this.request(`/api/v1/operations/${encodeURIComponent(e)}/logs?${r}`)}streamOperationLogs(e,t=0){return this.fetchFn(`${this.baseUrl}/api/v1/operations/${encodeURIComponent(e)}/logs/stream`,{headers:{accept:"text/event-stream",authorization:`Bearer ${this.options.token}`,"last-event-id":String(t)}})}cancelOperation(e){return this.request(`/api/v1/operations/${encodeURIComponent(e)}/cancel`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"})}retryOperation(e,t,r=0){return this.request(`/api/v1/operations/${encodeURIComponent(e)}/retry`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({errorClass:t,delayMs:r})})}queueSettings(){return this.request("/api/v1/queue/settings")}updateQueueSettings(e){return this.request("/api/v1/queue/settings",{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({confirm:"update queue limits",concurrency:e})})}listPreviews(e){return this.request(`/api/v1/previews${e?`?projectId=${encodeURIComponent(e)}`:""}`)}listPreviewDefinitions(e){return this.request(`/api/v1/preview-definitions?projectId=${encodeURIComponent(e)}`)}createPreviewDefinition(e){return this.request("/api/v1/preview-definitions",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}createPreview(e){return this.request("/api/v1/previews",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}destroyPreview(e,t){return this.request(`/api/v1/previews/${encodeURIComponent(e)}/destroy`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({confirm:t})})}extendPreview(e,t){return this.request(`/api/v1/previews/${encodeURIComponent(e)}/extend`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({hours:t})})}rebuildPreview(e){return this.request(`/api/v1/previews/${encodeURIComponent(e)}/rebuild`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"})}usage(e={}){let t=new URLSearchParams;for(let[r,n]of Object.entries(e))if(n)t.set(r,String(n));return this.request(`/api/v1/usage${t.size>0?`?${t}`:""}`)}usageRollups(e){let t=new URLSearchParams({from:e.from,to:e.to});if(e.projectId)t.set("projectId",e.projectId);if(e.environmentId)t.set("environmentId",e.environmentId);if(e.limit)t.set("limit",String(e.limit));for(let r of e.meters??[])t.append("meter",r);return this.request(`/api/v1/usage/rollups?${t}`)}allowance(e="deploy",t={}){let r=new URLSearchParams({operation:e});if(t.projectId)r.set("projectId",t.projectId);if(t.environmentId)r.set("environmentId",t.environmentId);return this.request(`/api/v1/spend/allowance?${r}`)}budgets(e={}){let t=new URLSearchParams;for(let[r,n]of Object.entries(e))if(n)t.set(r,String(n));return this.request(`/api/v1/spend/budgets${t.size>0?`?${t}`:""}`)}anomalies(e={}){let t=new URLSearchParams;if(e.projectId)t.set("projectId",e.projectId);if(e.since)t.set("since",e.since);if(e.unacknowledged)t.set("unacknowledged","true");return this.request(`/api/v1/spend/anomalies${t.size>0?`?${t}`:""}`)}}import{createHash as TS}from"node:crypto";import{lstatSync as Nb,readdirSync as Mb,readFileSync as $b}from"node:fs";import{relative as Lb,resolve as xp,sep as Bb}from"node:path";function Fb(e){return new Map(e.map((t)=>[t.path.replace(/^\.\//,"").replace(/\\/g,"/"),t]))}function zo(e,t,r){return{path:e,reason:t,weight:r}}function Dp(e){try{return e?.content?JSON.parse(e.content):{}}catch{return{}}}function ws(e,t,r,n,i,o){return{framework:e,strategy:t,confidence:r,evidence:n,defaults:{build:i,runtime:{target:t==="static"?"serverless":t==="serverless"?"serverless":t==="dockerfile"||t==="prebuilt_image"?"container":"server",architecture:"x86_64",port:t==="static"||t==="serverless"?void 0:3000,healthCheck:t==="static"?void 0:{protocol:"http",path:"/health"}}},description:o}}function kt(e){let t=Fb(e.slice(0,1e4)),r=[];if(t.has("Dockerfile"))r.push(ws("dockerfile","dockerfile",0.99,[zo("Dockerfile","A root Dockerfile defines an explicit reproducible build.",1)],{kind:"dockerfile",context:".",dockerfile:"Dockerfile"},"Build the repository with its Dockerfile and run the resulting OCI image."));let n=Dp(t.get("composer.json"));if(t.has("artisan")&&n.require?.["laravel/framework"])r.push(ws("laravel","server",0.98,[zo("artisan","Laravel Artisan entrypoint is present.",0.45),zo("composer.json","Requires laravel/framework.",0.55)],{kind:"server",runtime:"php",runtimeVersion:"8.3",installCommand:"composer install --no-dev --prefer-dist --optimize-autoloader",buildCommand:"php artisan config:cache && php artisan route:cache && php artisan view:cache",startCommand:"php artisan serve --host=0.0.0.0 --port=$PORT"},"Install a production Composer tree, warm Laravel caches, and run the HTTP application."));else if(t.has("composer.json"))r.push(ws("php","server",0.82,[zo("composer.json","Composer metadata identifies a PHP application.",0.8)],{kind:"server",runtime:"php",runtimeVersion:"8.3",installCommand:"composer install --no-dev --prefer-dist --optimize-autoloader",startCommand:"php -S 0.0.0.0:$PORT -t public"},"Install Composer dependencies and run the configured PHP document root."));let i=Dp(t.get("package.json"));if(t.has("package.json")){let o=t.has("bun.lock")||t.has("bun.lockb")||i.engines?.bun,s=o?"bun":"node",c=o?"bun":"node",u=[zo("package.json",`Defines ${i.scripts?.build?"build and ":""}${i.scripts?.start?"start ":""}scripts.`,0.55)];if(o)u.push(zo(t.has("bun.lock")?"bun.lock":t.has("bun.lockb")?"bun.lockb":"package.json","Pins the Bun package manager/runtime.",0.35));let a=!!(i.dependencies?.vite||i.devDependencies?.vite||i.dependencies?.["@stacksjs/bunpress"]||i.devDependencies?.["@stacksjs/bunpress"])&&!i.scripts?.start,f=a?{kind:"static",installCommand:`${s} install --frozen-lockfile`,buildCommand:`${s} run build`,publishDirectory:"dist"}:{kind:"server",runtime:s,installCommand:`${s} install --frozen-lockfile`,buildCommand:i.scripts?.build?`${s} run build`:void 0,startCommand:i.scripts?.start?`${s} run start`:s==="bun"?"bun run index.ts":"node index.js"};r.push(ws(c,f.kind,Math.min(0.94,u.reduce((T,R)=>T+R.weight,0)),u,f,a?"Install dependencies, build static assets, and publish the output directory.":`Install dependencies, build if configured, and start the ${s} server.`))}if(!r.length&&(t.has("index.html")||t.has("public/index.html")))r.push(ws("static","static",0.78,[zo(t.has("index.html")?"index.html":"public/index.html","A static HTML entrypoint is present.",0.78)],{kind:"static",publishDirectory:t.has("index.html")?".":"public"},"Publish the static directory without a runtime process."));if(!r.length)r.push(ws("unknown","buildpack",0.2,[],{kind:"buildpack",runtime:"node"},"No supported framework signature was conclusive; choose commands and runtime manually."));return r.sort((o,s)=>s.confidence-o.confidence||o.framework.localeCompare(s.framework))}function Jn(e,t={}){let r=xp(e),n=t.maxFiles??1e4,i=t.maxContentBytes??262144,o=[],s=new Set(["Dockerfile","package.json","composer.json","index.html","public/index.html","bun.lock","bun.lockb","artisan"]),c=new Set([".git",".ts-cloud",".cache",".next",".nuxt",".output",".turbo",".bun","node_modules","vendor","pantry","dist","build","coverage"]),u=(a)=>{for(let f of Mb(a).sort()){if(c.has(f))continue;let T=xp(a,f),R=Lb(r,T).split(Bb).join("/");if(!R||R.startsWith("../"))throw Error("Detection path escaped the application root");let D=Nb(T);if(D.isSymbolicLink())throw Error(`Detection refuses symbolic links: ${R}`);if(D.isDirectory())u(T);else if(D.isFile()){if(o.length>=n)throw Error("Application file-count limit exceeded");let W={path:R,size:D.size};if(s.has(R)&&D.size<=i)W.content=$b(T,"utf8");o.push(W)}}};return u(r),o}function Bd(e){if(Array.isArray(e))return`[${e.map(Bd).join(",")}]`;if(e&&typeof e==="object")return`{${Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>`${JSON.stringify(t)}:${Bd(r)}`).join(",")}}`;return JSON.stringify(e)??"null"}function pa(e){return!!e&&!e.startsWith("/")&&!e.split("/").includes("..")&&!/[\0\r\n]/.test(e)}function pn(e,t,r,n){return{path:e,code:t,message:r,alternatives:n}}function Ld(e){return JSON.parse(JSON.stringify(e))}function jb(e){let t=Object.fromEntries(Object.entries(e.environment??{}).map(([r,n])=>[r,typeof n==="string"?n:`\${${n.secretRef}}`]));if(e.build.kind==="prebuilt_image"||e.build.kind==="dockerfile")return Ld({infrastructure:{containers:{[e.slug]:{source:e.source,build:e.build,port:e.runtime.port,cpu:e.runtime.cpu,memory:e.runtime.memoryMb,architecture:e.runtime.architecture,healthCheck:e.runtime.healthCheck,environment:t}}}});if(e.runtime.target==="serverless"||e.build.kind==="serverless")return Ld({serverless:{apps:{[e.slug]:{source:e.source,build:e.build,architecture:e.runtime.architecture,environment:t,domain:e.domain}}}});return Ld({sites:{[e.slug]:{source:e.source,build:e.build,port:e.runtime.port,architecture:e.runtime.architecture,healthCheck:e.runtime.healthCheck,env:t,domain:e.domain?.hostname}}})}function ce(e,t=[]){let r=[],n=(W)=>/(?:secret|token|password|passwd|private[_-]?key|api[_-]?key)/i.test(W),i=Object.fromEntries(Object.entries(e.environment??{}).map(([W,Y])=>{if(typeof Y==="string"&&n(W))return r.push(pn(`environment.${W}`,"write_only_secret_required",`${W} must be supplied through the write-only secrets boundary.`)),[W,{secretRef:W}];return[W,Y]})),o=e.build;if(e.build.kind==="dockerfile"&&e.build.buildArgs){let W=Object.fromEntries(Object.entries(e.build.buildArgs).map(([Y,ee])=>{if(n(Y))return r.push(pn(`build.buildArgs.${Y}`,"write_only_build_secret_required",`${Y} must be declared in secretNames instead of buildArgs.`)),[Y,"[REDACTED]"];return[Y,ee]}));o={...e.build,buildArgs:W}}if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(e.slug))r.push(pn("slug","invalid_slug","Slug must contain 2-63 lowercase letters, numbers, or hyphens."));if(!pa((e.source.kind==="git"?e.source.monorepoRoot:e.source.kind==="local"?e.source.root:".")??"."))r.push(pn("source","unsafe_source_root","Source root must stay inside the source tree."));if(e.source.kind==="git"&&e.source.sparsePaths?.some((W)=>!pa(W)))r.push(pn("source.sparsePaths","unsafe_sparse_path","Sparse checkout paths must stay inside the repository."));if(e.build.kind==="dockerfile"&&(!pa(e.build.context)||!pa(e.build.dockerfile)))r.push(pn("build","unsafe_docker_path","Docker context and Dockerfile must stay inside the source tree."));if(e.build.kind==="static"&&!pa(e.build.publishDirectory))r.push(pn("build.publishDirectory","invalid_publish_directory","A safe static publish directory is required."));if(e.build.kind==="server"&&!e.build.startCommand.trim())r.push(pn("build.startCommand","missing_start_command","A server start command is required.",["Use static output","Use a Dockerfile"]));if(e.source.kind==="image"&&e.build.kind!=="prebuilt_image")r.push(pn("build.kind","image_requires_prebuilt","An OCI image source must use the prebuilt-image strategy.",["Select prebuilt image"]));if(e.build.kind==="prebuilt_image"&&e.runtime.target!=="container")r.push(pn("runtime.target","image_requires_container","Prebuilt images require the container runtime target.",["Select container target"]));if(e.runtime.target==="serverless"&&e.build.kind==="dockerfile")r.push(pn("runtime.target","unsupported_serverless_dockerfile","Dockerfile builds currently target the container service path.",["Select container target","Select serverless package"]));if(e.runtime.port!==void 0&&(!Number.isInteger(e.runtime.port)||e.runtime.port<1||e.runtime.port>65535))r.push(pn("runtime.port","invalid_port","Port must be an integer from 1 to 65535."));let s=e.runtime.healthCheck;if(s&&s.protocol!=="tcp"&&(!s.path||!s.path.startsWith("/")||/[\r\n]/.test(s.path)))r.push(pn("runtime.healthCheck.path","invalid_health_path","HTTP health checks require a path beginning with /."));if(e.domain?.hostname&&(!/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/i.test(e.domain.hostname)||e.domain.hostname.includes("..")))r.push(pn("domain.hostname","invalid_domain","Domain must be a valid DNS hostname."));let c=Object.values(i).flatMap((W)=>typeof W==="object"?[W.secretRef]:[]),u=[...new Set([...e.requiredSecretNames??[],...e.build.kind==="dockerfile"?e.build.secretNames??[]:[],...c])].sort(),a=new Set(t),f=u.filter((W)=>!a.has(W)),T={apiVersion:"ts-cloud.dev/v1",kind:"Application",metadata:{name:e.name,slug:e.slug,projectId:e.projectId,environmentId:e.environmentId},spec:{source:e.source,build:o,runtime:e.runtime,environment:i,domain:e.domain}},R=[...new Set([e.source.kind==="git"?"git:read":e.source.kind==="image"?"registry:pull":e.source.kind==="artifact"?"artifact:inspect":"filesystem:read",e.runtime.target==="container"?"containers":e.runtime.target==="serverless"?"serverless":"servers",e.domain?"dns":""])].filter(Boolean).sort(),D=[...new Set([e.runtime.target,e.runtime.cpu?`${e.runtime.cpu} vCPU`:"",e.runtime.memoryMb?`${e.runtime.memoryMb} MB memory`:"",(e.runtime.minInstances??0)>0?`${e.runtime.minInstances} minimum instances`:"scales from zero where supported",e.domain?"managed DNS/TLS":""])].filter(Boolean);return{valid:r.length===0&&f.length===0,issues:r,missingSecrets:f,manifest:T,configPatch:jb({...e,build:o,environment:i}),capabilityRequirements:R,costDrivers:D,serializedManifest:`${Bd(T)}
1
+ import{ia,Fe,A,H,w,B,xe,Jt}from"./chunk-dj03v81n.js";import{ae,fn,re,hn,h,Or,ra}from"./chunk-znd507q9.js";import{Le,S,gs,hr,mi,gi,mt,nn,vc,$t,on,Je,Me,Xe,Cc,ft,yr,Ue,Qe,fi,hi,io,oo,Ye,sn,vr,ht,m,go,Ps,Ds}from"./chunk-ym9h629y.js";import{zt,p}from"./chunk-psvqpztv.js";import{g}from"./chunk-12x968en.js";import{me}from"./chunk-z8k9mcn5.js";import{Dr,Tt,kr,Nr,xr,_r,gn}from"./chunk-cz2wq0tf.js";import{qe,ur,Yi,O,tn,mc,gc,_t,li,di}from"./chunk-50r8znqt.js";import{v}from"./chunk-xdk0gmxt.js";import{oe,G,si}from"./chunk-nhqz2j90.js";import{E}from"./chunk-01w4zbex.js";import{V}from"./chunk-xx9mrcfs.js";import{I}from"./chunk-de69nra4.js";import{J,P,U,Ir,xo,Pr,un}from"./chunk-yp3a0j9n.js";import{wo}from"./chunk-gyvkravq.js";import{K,Os,$s,Po,Bt,z,Ls}from"./chunk-qq1f07te.js";import{js,Vs}from"./chunk-her9ny96.js";import{ms}from"./chunk-nj9x0tb8.js";import{rn}from"./chunk-5nmt4s5w.js";import{_,N,ea}from"./chunk-kbwm0sqv.js";import{createHash as jT}from"node:crypto";import{existsSync as uo,mkdtempSync as cp,readdirSync as cb,rmSync as fs,statSync as Sb}from"node:fs";import{readFile as Li,writeFile as ls}from"node:fs/promises";import{tmpdir as kd}from"node:os";import{dirname as UT,extname as Fa,join as Ct,normalize as zT,relative as VT,resolve as qT,sep as GT}from"node:path";import{fileURLToPath as JT}from"node:url";class $d extends Error{status;code;requestId;constructor(e,t,r,n){super(r);this.status=e;this.code=t;this.requestId=n}}class Gi{options;baseUrl;fetchFn;constructor(e){this.options=e;this.baseUrl=e.baseUrl.replace(/\/$/,""),this.fetchFn=e.fetch??fetch}async request(e,t={}){let r=await this.fetchFn(`${this.baseUrl}${e}`,{...t,headers:{accept:"application/json",authorization:`Bearer ${this.options.token}`,...t.headers}}),n=await r.json().catch(()=>({}));if(!r.ok)throw new $d(r.status,n.error?.code??"api_error",n.error?.message??"API request failed.",n.error?.requestId??r.headers.get("x-request-id")??void 0);return n}listProjects(e={}){return this.request(`/api/v1/projects?${new URLSearchParams(Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).map(([t,r])=>[t,String(r)])))}`)}listEnvironments(e,t={}){return this.request(`/api/v1/projects/${encodeURIComponent(e)}/environments?${new URLSearchParams(Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0).map(([r,n])=>[r,String(n)])))}`)}listServices(e,t){return this.request(`/api/v1/services?${new URLSearchParams({projectId:e,...t?{environmentId:t}:{}})}`)}listOperations(e){return this.request(`/api/v1/operations${e?`?projectId=${encodeURIComponent(e)}`:""}`)}listComposeTemplates(){return this.request("/api/v1/compose-templates")}listComposeApplications(e,t){return this.request(`/api/v1/compose-applications?${new URLSearchParams({projectId:e,...t?{environmentId:t}:{}})}`)}previewCompose(e){return this.request("/api/v1/compose-applications/preview",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}createComposeApplication(e){return this.request("/api/v1/compose-applications",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}composeServices(e){return this.request(`/api/v1/compose-applications/${encodeURIComponent(e)}/services`)}composeAction(e,t,r={}){return this.request(`/api/v1/compose-applications/${encodeURIComponent(e)}/${t}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r)})}releaseCapabilities(e,t={}){return this.request(`/api/v1/releases/capabilities?${new URLSearchParams({kind:e,health:String(!!t.health),replicas:String(t.replicas??1)})}`)}listReleases(e,t={}){return this.request(`/api/v1/releases?${new URLSearchParams({projectId:e,...t})}`)}createReleaseArtifact(e){return this.request("/api/v1/release-artifacts",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}createRelease(e){return this.request("/api/v1/releases",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}releaseAction(e,t,r={}){return this.request(`/api/v1/releases/${encodeURIComponent(e)}/${t}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r)})}createDeployment(e,t){return this.request("/api/v1/deployments",{method:"POST",headers:{"content-type":"application/json","idempotency-key":t},body:JSON.stringify(e)})}detectApplication(e){return this.request("/api/v1/application-detections",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}planApplication(e){return this.request("/api/v1/application-plans",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}listApplicationDrafts(e){return this.request(`/api/v1/application-drafts?projectId=${encodeURIComponent(e)}`)}createApplicationDraft(e){return this.request("/api/v1/application-drafts",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}updateApplicationDraft(e){return this.request("/api/v1/application-drafts",{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}createApplication(e,t){return this.request("/api/v1/applications",{method:"POST",headers:{"content-type":"application/json","idempotency-key":t},body:JSON.stringify(e)})}uploadApplicationArtifact(e,t,r){return this.request("/api/v1/application-artifacts",{method:"POST",headers:{"content-type":"application/octet-stream","x-project-id":e,"x-artifact-filename":t},body:r})}listRegistryConnections(){return this.request("/api/v1/registry-connections")}createRegistryConnection(e){return this.request("/api/v1/registry-connections",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}updateRegistryConnection(e){return this.request("/api/v1/registry-connections",{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}disconnectRegistryConnection(e){return this.request("/api/v1/registry-connections",{method:"DELETE",headers:{"content-type":"application/json"},body:JSON.stringify({id:e})})}listQueue(e={}){let t=new URLSearchParams(Object.entries(e).filter(([,r])=>r!==void 0).map(([r,n])=>[r,String(n)]));return this.request(`/api/v1/queue?${t}`)}operationLogs(e,t={}){let r=new URLSearchParams(Object.entries(t).filter(([,n])=>n!==void 0).map(([n,i])=>[n,String(i)]));return this.request(`/api/v1/operations/${encodeURIComponent(e)}/logs?${r}`)}streamOperationLogs(e,t=0){return this.fetchFn(`${this.baseUrl}/api/v1/operations/${encodeURIComponent(e)}/logs/stream`,{headers:{accept:"text/event-stream",authorization:`Bearer ${this.options.token}`,"last-event-id":String(t)}})}cancelOperation(e){return this.request(`/api/v1/operations/${encodeURIComponent(e)}/cancel`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"})}retryOperation(e,t,r=0){return this.request(`/api/v1/operations/${encodeURIComponent(e)}/retry`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({errorClass:t,delayMs:r})})}queueSettings(){return this.request("/api/v1/queue/settings")}updateQueueSettings(e){return this.request("/api/v1/queue/settings",{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({confirm:"update queue limits",concurrency:e})})}listPreviews(e){return this.request(`/api/v1/previews${e?`?projectId=${encodeURIComponent(e)}`:""}`)}listPreviewDefinitions(e){return this.request(`/api/v1/preview-definitions?projectId=${encodeURIComponent(e)}`)}createPreviewDefinition(e){return this.request("/api/v1/preview-definitions",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}createPreview(e){return this.request("/api/v1/previews",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}destroyPreview(e,t){return this.request(`/api/v1/previews/${encodeURIComponent(e)}/destroy`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({confirm:t})})}extendPreview(e,t){return this.request(`/api/v1/previews/${encodeURIComponent(e)}/extend`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({hours:t})})}rebuildPreview(e){return this.request(`/api/v1/previews/${encodeURIComponent(e)}/rebuild`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"})}usage(e={}){let t=new URLSearchParams;for(let[r,n]of Object.entries(e))if(n)t.set(r,String(n));return this.request(`/api/v1/usage${t.size>0?`?${t}`:""}`)}usageRollups(e){let t=new URLSearchParams({from:e.from,to:e.to});if(e.projectId)t.set("projectId",e.projectId);if(e.environmentId)t.set("environmentId",e.environmentId);if(e.limit)t.set("limit",String(e.limit));for(let r of e.meters??[])t.append("meter",r);return this.request(`/api/v1/usage/rollups?${t}`)}allowance(e="deploy",t={}){let r=new URLSearchParams({operation:e});if(t.projectId)r.set("projectId",t.projectId);if(t.environmentId)r.set("environmentId",t.environmentId);return this.request(`/api/v1/spend/allowance?${r}`)}budgets(e={}){let t=new URLSearchParams;for(let[r,n]of Object.entries(e))if(n)t.set(r,String(n));return this.request(`/api/v1/spend/budgets${t.size>0?`?${t}`:""}`)}anomalies(e={}){let t=new URLSearchParams;if(e.projectId)t.set("projectId",e.projectId);if(e.since)t.set("since",e.since);if(e.unacknowledged)t.set("unacknowledged","true");return this.request(`/api/v1/spend/anomalies${t.size>0?`?${t}`:""}`)}}import{createHash as TS}from"node:crypto";import{lstatSync as Nb,readdirSync as Mb,readFileSync as $b}from"node:fs";import{relative as Lb,resolve as xp,sep as Bb}from"node:path";function Fb(e){return new Map(e.map((t)=>[t.path.replace(/^\.\//,"").replace(/\\/g,"/"),t]))}function zo(e,t,r){return{path:e,reason:t,weight:r}}function Dp(e){try{return e?.content?JSON.parse(e.content):{}}catch{return{}}}function ws(e,t,r,n,i,o){return{framework:e,strategy:t,confidence:r,evidence:n,defaults:{build:i,runtime:{target:t==="static"?"serverless":t==="serverless"?"serverless":t==="dockerfile"||t==="prebuilt_image"?"container":"server",architecture:"x86_64",port:t==="static"||t==="serverless"?void 0:3000,healthCheck:t==="static"?void 0:{protocol:"http",path:"/health"}}},description:o}}function kt(e){let t=Fb(e.slice(0,1e4)),r=[];if(t.has("Dockerfile"))r.push(ws("dockerfile","dockerfile",0.99,[zo("Dockerfile","A root Dockerfile defines an explicit reproducible build.",1)],{kind:"dockerfile",context:".",dockerfile:"Dockerfile"},"Build the repository with its Dockerfile and run the resulting OCI image."));let n=Dp(t.get("composer.json"));if(t.has("artisan")&&n.require?.["laravel/framework"])r.push(ws("laravel","server",0.98,[zo("artisan","Laravel Artisan entrypoint is present.",0.45),zo("composer.json","Requires laravel/framework.",0.55)],{kind:"server",runtime:"php",runtimeVersion:"8.3",installCommand:"composer install --no-dev --prefer-dist --optimize-autoloader",buildCommand:"php artisan config:cache && php artisan route:cache && php artisan view:cache",startCommand:"php artisan serve --host=0.0.0.0 --port=$PORT"},"Install a production Composer tree, warm Laravel caches, and run the HTTP application."));else if(t.has("composer.json"))r.push(ws("php","server",0.82,[zo("composer.json","Composer metadata identifies a PHP application.",0.8)],{kind:"server",runtime:"php",runtimeVersion:"8.3",installCommand:"composer install --no-dev --prefer-dist --optimize-autoloader",startCommand:"php -S 0.0.0.0:$PORT -t public"},"Install Composer dependencies and run the configured PHP document root."));let i=Dp(t.get("package.json"));if(t.has("package.json")){let o=t.has("bun.lock")||t.has("bun.lockb")||i.engines?.bun,s=o?"bun":"node",c=o?"bun":"node",u=[zo("package.json",`Defines ${i.scripts?.build?"build and ":""}${i.scripts?.start?"start ":""}scripts.`,0.55)];if(o)u.push(zo(t.has("bun.lock")?"bun.lock":t.has("bun.lockb")?"bun.lockb":"package.json","Pins the Bun package manager/runtime.",0.35));let a=!!(i.dependencies?.vite||i.devDependencies?.vite||i.dependencies?.["@stacksjs/bunpress"]||i.devDependencies?.["@stacksjs/bunpress"])&&!i.scripts?.start,f=a?{kind:"static",installCommand:`${s} install --frozen-lockfile`,buildCommand:`${s} run build`,publishDirectory:"dist"}:{kind:"server",runtime:s,installCommand:`${s} install --frozen-lockfile`,buildCommand:i.scripts?.build?`${s} run build`:void 0,startCommand:i.scripts?.start?`${s} run start`:s==="bun"?"bun run index.ts":"node index.js"};r.push(ws(c,f.kind,Math.min(0.94,u.reduce((T,R)=>T+R.weight,0)),u,f,a?"Install dependencies, build static assets, and publish the output directory.":`Install dependencies, build if configured, and start the ${s} server.`))}if(!r.length&&(t.has("index.html")||t.has("public/index.html")))r.push(ws("static","static",0.78,[zo(t.has("index.html")?"index.html":"public/index.html","A static HTML entrypoint is present.",0.78)],{kind:"static",publishDirectory:t.has("index.html")?".":"public"},"Publish the static directory without a runtime process."));if(!r.length)r.push(ws("unknown","buildpack",0.2,[],{kind:"buildpack",runtime:"node"},"No supported framework signature was conclusive; choose commands and runtime manually."));return r.sort((o,s)=>s.confidence-o.confidence||o.framework.localeCompare(s.framework))}function Jn(e,t={}){let r=xp(e),n=t.maxFiles??1e4,i=t.maxContentBytes??262144,o=[],s=new Set(["Dockerfile","package.json","composer.json","index.html","public/index.html","bun.lock","bun.lockb","artisan"]),c=new Set([".git",".ts-cloud",".cache",".next",".nuxt",".output",".turbo",".bun","node_modules","vendor","pantry","dist","build","coverage"]),u=(a)=>{for(let f of Mb(a).sort()){if(c.has(f))continue;let T=xp(a,f),R=Lb(r,T).split(Bb).join("/");if(!R||R.startsWith("../"))throw Error("Detection path escaped the application root");let D=Nb(T);if(D.isSymbolicLink())throw Error(`Detection refuses symbolic links: ${R}`);if(D.isDirectory())u(T);else if(D.isFile()){if(o.length>=n)throw Error("Application file-count limit exceeded");let W={path:R,size:D.size};if(s.has(R)&&D.size<=i)W.content=$b(T,"utf8");o.push(W)}}};return u(r),o}function Bd(e){if(Array.isArray(e))return`[${e.map(Bd).join(",")}]`;if(e&&typeof e==="object")return`{${Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>`${JSON.stringify(t)}:${Bd(r)}`).join(",")}}`;return JSON.stringify(e)??"null"}function pa(e){return!!e&&!e.startsWith("/")&&!e.split("/").includes("..")&&!/[\0\r\n]/.test(e)}function pn(e,t,r,n){return{path:e,code:t,message:r,alternatives:n}}function Ld(e){return JSON.parse(JSON.stringify(e))}function jb(e){let t=Object.fromEntries(Object.entries(e.environment??{}).map(([r,n])=>[r,typeof n==="string"?n:`\${${n.secretRef}}`]));if(e.build.kind==="prebuilt_image"||e.build.kind==="dockerfile")return Ld({infrastructure:{containers:{[e.slug]:{source:e.source,build:e.build,port:e.runtime.port,cpu:e.runtime.cpu,memory:e.runtime.memoryMb,architecture:e.runtime.architecture,healthCheck:e.runtime.healthCheck,environment:t}}}});if(e.runtime.target==="serverless"||e.build.kind==="serverless")return Ld({serverless:{apps:{[e.slug]:{source:e.source,build:e.build,architecture:e.runtime.architecture,environment:t,domain:e.domain}}}});return Ld({sites:{[e.slug]:{source:e.source,build:e.build,port:e.runtime.port,architecture:e.runtime.architecture,healthCheck:e.runtime.healthCheck,env:t,domain:e.domain?.hostname}}})}function ce(e,t=[]){let r=[],n=(W)=>/(?:secret|token|password|passwd|private[_-]?key|api[_-]?key)/i.test(W),i=Object.fromEntries(Object.entries(e.environment??{}).map(([W,Y])=>{if(typeof Y==="string"&&n(W))return r.push(pn(`environment.${W}`,"write_only_secret_required",`${W} must be supplied through the write-only secrets boundary.`)),[W,{secretRef:W}];return[W,Y]})),o=e.build;if(e.build.kind==="dockerfile"&&e.build.buildArgs){let W=Object.fromEntries(Object.entries(e.build.buildArgs).map(([Y,ee])=>{if(n(Y))return r.push(pn(`build.buildArgs.${Y}`,"write_only_build_secret_required",`${Y} must be declared in secretNames instead of buildArgs.`)),[Y,"[REDACTED]"];return[Y,ee]}));o={...e.build,buildArgs:W}}if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(e.slug))r.push(pn("slug","invalid_slug","Slug must contain 2-63 lowercase letters, numbers, or hyphens."));if(!pa((e.source.kind==="git"?e.source.monorepoRoot:e.source.kind==="local"?e.source.root:".")??"."))r.push(pn("source","unsafe_source_root","Source root must stay inside the source tree."));if(e.source.kind==="git"&&e.source.sparsePaths?.some((W)=>!pa(W)))r.push(pn("source.sparsePaths","unsafe_sparse_path","Sparse checkout paths must stay inside the repository."));if(e.build.kind==="dockerfile"&&(!pa(e.build.context)||!pa(e.build.dockerfile)))r.push(pn("build","unsafe_docker_path","Docker context and Dockerfile must stay inside the source tree."));if(e.build.kind==="static"&&!pa(e.build.publishDirectory))r.push(pn("build.publishDirectory","invalid_publish_directory","A safe static publish directory is required."));if(e.build.kind==="server"&&!e.build.startCommand.trim())r.push(pn("build.startCommand","missing_start_command","A server start command is required.",["Use static output","Use a Dockerfile"]));if(e.source.kind==="image"&&e.build.kind!=="prebuilt_image")r.push(pn("build.kind","image_requires_prebuilt","An OCI image source must use the prebuilt-image strategy.",["Select prebuilt image"]));if(e.build.kind==="prebuilt_image"&&e.runtime.target!=="container")r.push(pn("runtime.target","image_requires_container","Prebuilt images require the container runtime target.",["Select container target"]));if(e.runtime.target==="serverless"&&e.build.kind==="dockerfile")r.push(pn("runtime.target","unsupported_serverless_dockerfile","Dockerfile builds currently target the container service path.",["Select container target","Select serverless package"]));if(e.runtime.port!==void 0&&(!Number.isInteger(e.runtime.port)||e.runtime.port<1||e.runtime.port>65535))r.push(pn("runtime.port","invalid_port","Port must be an integer from 1 to 65535."));let s=e.runtime.healthCheck;if(s&&s.protocol!=="tcp"&&(!s.path||!s.path.startsWith("/")||/[\r\n]/.test(s.path)))r.push(pn("runtime.healthCheck.path","invalid_health_path","HTTP health checks require a path beginning with /."));if(e.domain?.hostname&&(!/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/i.test(e.domain.hostname)||e.domain.hostname.includes("..")))r.push(pn("domain.hostname","invalid_domain","Domain must be a valid DNS hostname."));let c=Object.values(i).flatMap((W)=>typeof W==="object"?[W.secretRef]:[]),u=[...new Set([...e.requiredSecretNames??[],...e.build.kind==="dockerfile"?e.build.secretNames??[]:[],...c])].sort(),a=new Set(t),f=u.filter((W)=>!a.has(W)),T={apiVersion:"ts-cloud.dev/v1",kind:"Application",metadata:{name:e.name,slug:e.slug,projectId:e.projectId,environmentId:e.environmentId},spec:{source:e.source,build:o,runtime:e.runtime,environment:i,domain:e.domain}},R=[...new Set([e.source.kind==="git"?"git:read":e.source.kind==="image"?"registry:pull":e.source.kind==="artifact"?"artifact:inspect":"filesystem:read",e.runtime.target==="container"?"containers":e.runtime.target==="serverless"?"serverless":"servers",e.domain?"dns":""])].filter(Boolean).sort(),D=[...new Set([e.runtime.target,e.runtime.cpu?`${e.runtime.cpu} vCPU`:"",e.runtime.memoryMb?`${e.runtime.memoryMb} MB memory`:"",(e.runtime.minInstances??0)>0?`${e.runtime.minInstances} minimum instances`:"scales from zero where supported",e.domain?"managed DNS/TLS":""])].filter(Boolean);return{valid:r.length===0&&f.length===0,issues:r,missingSecrets:f,manifest:T,configPatch:jb({...e,build:o,environment:i}),capabilityRequirements:R,costDrivers:D,serializedManifest:`${Bd(T)}
2
2
  `}}function Op(e){let t=e.replace(/\\/g,"/");return!!t&&!t.startsWith("/")&&!/^[A-Za-z]:\//.test(t)&&!t.split("/").includes("..")&&!/[\0\r\n]/.test(t)}function _p(e,t,r={}){let n=r.maxBytes??104857600,i=r.maxEntries??1e4,o=r.maxExpandedBytes??524288000;if(e.byteLength>n)throw Error("Archive exceeds the compressed size limit");let s=new DataView(e.buffer,e.byteOffset,e.byteLength),c=[],u=0;if(t.toLowerCase().endsWith(".zip")||e[0]===80&&e[1]===75){let f=0;while(f+30<=e.length){let T=s.getUint32(f,!0);if(T===33639248||T===101010256)break;if(T!==67324752)throw Error("Malformed ZIP local header");let R=s.getUint16(f+6,!0),D=s.getUint32(f+18,!0),W=s.getUint32(f+22,!0),Y=s.getUint16(f+26,!0),ee=s.getUint16(f+28,!0);if(R&8)throw Error("ZIP data descriptors are not accepted for uploaded artifacts");let ne=new TextDecoder().decode(e.subarray(f+30,f+30+Y));if(!Op(ne))throw Error(`Unsafe archive path: ${ne}`);if(c.push(ne),u+=W,c.length>i||u>o)throw Error("Archive expansion limit exceeded");f+=30+Y+ee+D}return{format:"zip",entries:c.length,expandedBytes:u,paths:c}}if(!t.toLowerCase().match(/\.(?:tar|tar\.gz|tgz)$/))throw Error("Only ZIP and uncompressed TAR artifacts are supported");let a=0;while(a+512<=e.length){let f=e.subarray(a,a+512);if(f.every((Y)=>Y===0))break;let T=(Y,ee)=>new TextDecoder().decode(f.subarray(Y,Y+ee)).replace(/\0.*$/,""),R=`${T(345,155)}${T(345,155)?"/":""}${T(0,100)}`,D=Number.parseInt(T(124,12).trim()||"0",8),W=String.fromCharCode(f[156]??0);if(!Op(R))throw Error(`Unsafe archive path: ${R}`);if(W==="1"||W==="2")throw Error(`Archive links are not accepted: ${R}`);if(!Number.isFinite(D)||D<0)throw Error("Malformed TAR entry size");if(c.push(R),u+=D,c.length>i||u>o)throw Error("Archive expansion limit exceeded");a+=512+Math.ceil(D/512)*512}return{format:"tar",entries:c.length,expandedBytes:u,paths:c}}var Np=new Set(["source","build","runtime","environment","domain","review"]);function Mp(e,t){try{return typeof e==="string"?JSON.parse(e):t}catch{return t}}function $p(e){return/(?:secret|token|password|passwd|private[_-]?key|api[_-]?key)/i.test(e)}function Lp(e){for(let[r,n]of Object.entries(e.environment??{}))if(typeof n==="string"&&$p(r)&&n)throw Error(`${r} must be stored through the write-only secrets boundary`);if(e.build.kind==="dockerfile"){for(let[r,n]of Object.entries(e.build.buildArgs??{}))if($p(r)&&n)throw Error(`${r} must be declared as a build secret name`)}let t=JSON.stringify(e);if(/https?:\/\/[^/@\s]+:[^/@\s]+@/i.test(t))throw Error("Drafts cannot contain credential-bearing URLs")}function Bp(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),schemaVersion:Number(e.schema_version),name:String(e.name),step:String(e.step),input:Mp(e.input,{}),suppliedSecretNames:Mp(e.supplied_secret_names,[]),status:String(e.status),version:Number(e.version),createdByActorId:e.created_by_actor_id?String(e.created_by_actor_id):void 0,createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}class Xn{controlPlane;nowFn;idFn;constructor(e,t={}){this.controlPlane=e;this.nowFn=t.now??(()=>new Date),this.idFn=t.id??(()=>crypto.randomUUID())}now(){return this.nowFn().toISOString()}create(e){if(Lp(e.draft),e.draft.projectId!==e.projectId)throw Error("Draft project does not match its storage scope");let t=this.controlPlane.getProject(e.projectId);if(!t||t.organizationId!==e.organizationId)throw Error("Draft project was not found");let r=this.idFn(),n=this.now(),i=e.step??"source";if(!Np.has(i))throw Error("Invalid draft step");let o=[...new Set(e.suppliedSecretNames??[])].sort(),s=ce(e.draft,o).valid?"ready":"draft";return this.controlPlane.database.run("INSERT INTO application_drafts (id, organization_id, project_id, schema_version, name, step, input, supplied_secret_names, status, created_by_actor_id, created_at, updated_at) VALUES (?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?)",[r,e.organizationId,e.projectId,e.name.trim().slice(0,100),i,JSON.stringify(e.draft),JSON.stringify(o),s,e.actorId??null,n,n]),this.controlPlane.appendEvent({organizationId:e.organizationId,projectId:e.projectId,actorId:e.actorId,type:"application.draft.created",payload:{draftId:r,step:i,status:s,requiredSecretNames:e.draft.requiredSecretNames??[]}}),this.get(r)}get(e){let t=this.controlPlane.database.query("SELECT * FROM application_drafts WHERE id=?").get(e);return t?Bp(t):void 0}list(e){return this.controlPlane.database.query("SELECT * FROM application_drafts WHERE project_id=? ORDER BY updated_at DESC").all(e).map(Bp)}update(e,t,r){let n=this.get(e);if(!n||n.version!==t)throw Error(`Application draft ${e} changed since version ${t}`);if(!Np.has(r.step))throw Error("Invalid draft step");if(r.draft.projectId!==n.projectId)throw Error("Draft project cannot be changed");Lp(r.draft);let i=[...new Set(r.suppliedSecretNames??n.suppliedSecretNames)].sort(),o=ce(r.draft,i).valid?"ready":"draft",s=this.now();if(this.controlPlane.database.run("UPDATE application_drafts SET name=?, step=?, input=?, supplied_secret_names=?, status=?, version=version+1, updated_at=? WHERE id=? AND version=?",[r.draft.name.slice(0,100),r.step,JSON.stringify(r.draft),JSON.stringify(i),o,s,e,t]).changes!==1)throw Error(`Application draft ${e} changed since version ${t}`);return this.controlPlane.appendEvent({organizationId:n.organizationId,projectId:n.projectId,actorId:r.actorId,type:"application.draft.updated",payload:{draftId:e,fromVersion:t,toVersion:t+1,step:r.step,status:o}}),this.get(e)}markApplied(e,t,r){let n=this.get(e);if(!n||n.version!==t)throw Error(`Application draft ${e} changed since version ${t}`);let i=ce(n.input,n.suppliedSecretNames);if(!i.valid)throw Error(`Draft is not deployable: ${[...i.issues.map((s)=>s.message),...i.missingSecrets.map((s)=>`Missing secret ${s}`)].join("; ")}`);let o=this.now();return this.controlPlane.database.run("UPDATE application_drafts SET status='applied', step='review', version=version+1, updated_at=? WHERE id=? AND version=?",[o,e,t]),this.controlPlane.appendEvent({organizationId:n.organizationId,projectId:n.projectId,actorId:r,type:"application.draft.applied",payload:h({draftId:e,manifest:i.manifest})}),this.get(e)}}import{createCipheriv as Ub,createDecipheriv as zb,createHash as Up,randomBytes as Vb}from"node:crypto";function ga(e){return typeof e==="string"&&e?e:void 0}function Fd(e){return Up("sha256").update(e).digest("hex").slice(0,16)}function Fp(e){let t=new URL(e.includes("://")?e:`https://${e}`);if(t.protocol!=="https:"&&!["localhost","127.0.0.1","::1"].includes(t.hostname))throw Error("Registry host must use HTTPS");if(t.username||t.password||t.search||t.hash)throw Error("Registry host cannot contain credentials");return`${t.protocol}//${t.host}`}function qb(e){return{id:String(e.id),organizationId:String(e.organization_id),provider:String(e.provider),name:String(e.name),host:String(e.host),credentialConfigured:!!e.credential_ciphertext,credentialFingerprint:ga(e.credential_fingerprint),credentialExpiresAt:ga(e.credential_expires_at),status:String(e.status),healthMessage:ga(e.health_message),lastTestedAt:ga(e.last_tested_at),version:Number(e.version),createdByActorId:ga(e.created_by_actor_id),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}class Qn{controlPlane;key;nowFn;idFn;constructor(e,t){this.controlPlane=e;if(!t.encryptionKey)throw Error("Registry encryption key is required");this.key=Up("sha256").update(`ts-cloud:registry:${t.encryptionKey}`).digest(),this.nowFn=t.now??(()=>new Date),this.idFn=t.id??(()=>crypto.randomUUID())}now(){return this.nowFn().toISOString()}encrypt(e){let t=Vb(12),r=Ub("aes-256-gcm",this.key,t),n=Buffer.concat([r.update(e,"utf8"),r.final()]);return`v1.${t.toString("base64url")}.${r.getAuthTag().toString("base64url")}.${n.toString("base64url")}`}decrypt(e){let[t,r,n,i]=e.split(".");if(t!=="v1"||!r||!n||!i)throw Error("Registry credential envelope is invalid");let o=zb("aes-256-gcm",this.key,Buffer.from(r,"base64url"));return o.setAuthTag(Buffer.from(n,"base64url")),Buffer.concat([o.update(Buffer.from(i,"base64url")),o.final()]).toString("utf8")}current(e){let t=qb(e);return t.status!=="disconnected"&&t.credentialExpiresAt&&new Date(t.credentialExpiresAt).getTime()<=this.nowFn().getTime()?{...t,status:"expired",healthMessage:"Registry credential expired; rotate it before pulling images."}:t}create(e){if(!["docker_hub","ghcr","ecr","gcr","generic"].includes(e.provider))throw Error("A supported registry provider is required");let t=e.credential?JSON.stringify(e.credential):void 0,r=this.idFn(),n=this.now();return this.controlPlane.database.run("INSERT INTO registry_connections (id, organization_id, provider, name, host, credential_ciphertext, credential_fingerprint, credential_expires_at, created_by_actor_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[r,e.organizationId,e.provider,e.name.trim().slice(0,80),Fp(e.host),t?this.encrypt(t):null,t?Fd(t):null,e.credentialExpiresAt??null,e.actorId??null,n,n]),this.controlPlane.appendEvent({organizationId:e.organizationId,actorId:e.actorId,type:"registry.connection.created",payload:{connectionId:r,provider:e.provider,host:Fp(e.host),credentialConfigured:!!t}}),this.get(r)}get(e){let t=this.controlPlane.database.query("SELECT * FROM registry_connections WHERE id=?").get(e);return t?this.current(t):void 0}list(e){return this.controlPlane.database.query("SELECT * FROM registry_connections WHERE organization_id=? ORDER BY name").all(e).map((t)=>this.current(t))}credential(e){let t=this.controlPlane.database.query("SELECT credential_ciphertext FROM registry_connections WHERE id=?").get(e);return t?.credential_ciphertext?JSON.parse(this.decrypt(String(t.credential_ciphertext))):void 0}rotate(e,t,r={}){let n=this.get(e);if(!n||n.status==="disconnected")throw Error("Registry connection was not found");let i=JSON.stringify(t);return this.controlPlane.database.run("UPDATE registry_connections SET credential_ciphertext=?, credential_fingerprint=?, credential_expires_at=?, status='pending', health_message=NULL, version=version+1, updated_at=? WHERE id=?",[this.encrypt(i),Fd(i),r.expiresAt??null,this.now(),e]),this.controlPlane.appendEvent({organizationId:n.organizationId,actorId:r.actorId,type:"registry.credential.rotated",payload:{connectionId:e,fingerprint:Fd(i),expiresAt:r.expiresAt??null}}),this.get(e)}disconnect(e,t){let r=this.get(e);if(!r)throw Error("Registry connection was not found");return this.controlPlane.database.run("UPDATE registry_connections SET credential_ciphertext=NULL, credential_fingerprint=NULL, status='disconnected', health_message='Disconnected by an administrator', version=version+1, updated_at=? WHERE id=?",[this.now(),e]),this.controlPlane.appendEvent({organizationId:r.organizationId,actorId:t,type:"registry.connection.disconnected",level:"warning",payload:{connectionId:e}}),this.get(e)}async test(e,t={}){let r=this.get(e);if(!r||["disconnected","expired"].includes(r.status))throw Error("Active registry connection was not found");let n=this.credential(e),i=t.fetch??fetch,o=new AbortController,s=setTimeout(()=>o.abort(),t.timeoutMs??15000),c=n?.token?`Bearer ${n.token}`:n?.username||n?.password?`Basic ${Buffer.from(`${n.username??""}:${n.password??""}`).toString("base64")}`:void 0;try{let u=await i(`${r.host}/v2/`,{method:"GET",redirect:"error",signal:o.signal,headers:c?{Authorization:c}:void 0}),a=u.headers.get("www-authenticate")??"";if(u.status===401&&a.startsWith("Bearer ")&&n){let R=Object.fromEntries([...a.slice(7).matchAll(/(\w+)="([^"]+)"/g)].map((ne)=>[ne[1],ne[2]])),D=new URL(R.realm??"");if(D.protocol!=="https:")throw Error("Registry authentication realm must use HTTPS");if(R.service)D.searchParams.set("service",R.service);if(t.image)D.searchParams.set("scope",`repository:${zp(t.image).repository}:pull`);let W=await i(D,{signal:o.signal,redirect:"error",headers:c?{Authorization:c}:void 0});if(!W.ok)throw Error(`Registry authentication failed (${W.status})`);let Y=await W.json(),ee=Y.token??Y.access_token;if(!ee)throw Error("Registry did not return an access token");u=t.image?await jp(i,r.host,t.image,ee,o.signal):await i(`${r.host}/v2/`,{signal:o.signal,redirect:"error",headers:{Authorization:`Bearer ${ee}`}})}else if(u.ok&&t.image)u=await jp(i,r.host,t.image,n?.token,o.signal,c);let f=u.ok?"healthy":"degraded",T=u.ok?t.image?"Registry image is readable.":"Registry connection is healthy.":`Registry request failed (${u.status})`;return this.controlPlane.database.run("UPDATE registry_connections SET status=?, health_message=?, last_tested_at=?, version=version+1, updated_at=? WHERE id=?",[f,T,this.now(),this.now(),e]),this.get(e)}catch(u){let a=o.signal.aborted?"Registry request timed out.":u instanceof Error?u.message:"Registry test failed";return this.controlPlane.database.run("UPDATE registry_connections SET status='degraded', health_message=?, last_tested_at=?, version=version+1, updated_at=? WHERE id=?",[a.slice(0,1000),this.now(),this.now(),e]),this.get(e)}finally{clearTimeout(s)}}}function zp(e){let t=e.replace(/^https?:\/\//,""),r=t.indexOf("/");if(r<1)throw Error("Image must include registry/repository");let n=t.slice(r+1),i=n.lastIndexOf("@"),o=n.lastIndexOf(":"),s=i>=0?i:o>n.lastIndexOf("/")?o:-1,c=s>=0?n.slice(0,s):n,u=s>=0?n.slice(s+1):"latest";if(!/^[A-Za-z0-9_.\/-]+$/.test(c)||!/^[A-Za-z0-9_.:+-]+$/.test(u))throw Error("Image reference is invalid");return{repository:c,reference:u}}async function jp(e,t,r,n,i,o){let s=zp(r);return e(`${t}/v2/${s.repository}/manifests/${encodeURIComponent(s.reference)}`,{method:"HEAD",redirect:"error",signal:i,headers:{Accept:"application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json",...n?{Authorization:`Bearer ${n}`}:o?{Authorization:o}:{}}})}import{createHash as Gb}from"node:crypto";import{chmodSync as Vp,existsSync as qp,mkdirSync as Jb,renameSync as Hb,unlinkSync as Gp,writeFileSync as Wb}from"node:fs";import{basename as Kb,join as Qb}from"node:path";function jd(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),filename:String(e.filename),sha256:String(e.sha256),size:Number(e.size),format:String(e.format),entryCount:Number(e.entry_count),expandedBytes:Number(e.expanded_bytes),createdByActorId:e.created_by_actor_id?String(e.created_by_actor_id):void 0,createdAt:String(e.created_at)}}class Yn{controlPlane;root;idFn;nowFn;constructor(e,t){this.controlPlane=e;this.root=A(t.cwd,"artifacts"),this.idFn=t.id??(()=>crypto.randomUUID()),this.nowFn=t.now??(()=>new Date)}create(e){let t=this.controlPlane.getProject(e.projectId);if(!t||t.organizationId!==e.organizationId)throw Error("Artifact project was not found");let r=Kb(e.filename).slice(0,200);if(!r||r!==e.filename)throw Error("Artifact filename must not contain a path");let n=_p(e.bytes,r),i=Gb("sha256").update(e.bytes).digest("hex"),o=this.controlPlane.database.query("SELECT * FROM application_artifacts WHERE project_id=? AND sha256=?").get(e.projectId,i);if(o)return jd(o);let s=this.idFn();Jb(this.root,{recursive:!0,mode:448}),Vp(this.root,448);let c=Qb(this.root,`${s}.archive`),u=`${c}.partial`;try{Wb(u,e.bytes,{mode:384,flag:"wx"}),Hb(u,c),Vp(c,384),this.controlPlane.database.run("INSERT INTO application_artifacts (id, organization_id, project_id, filename, storage_path, sha256, size, format, entry_count, expanded_bytes, created_by_actor_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[s,e.organizationId,e.projectId,r,c,i,e.bytes.byteLength,n.format,n.entries,n.expandedBytes,e.actorId??null,this.nowFn().toISOString()])}catch(a){if(qp(u))Gp(u);if(qp(c))Gp(c);throw a}return this.controlPlane.appendEvent({organizationId:e.organizationId,projectId:e.projectId,actorId:e.actorId,type:"application.artifact.created",payload:{artifactId:s,filename:r,sha256:i,size:e.bytes.byteLength,entries:n.entries}}),this.get(s)}get(e){let t=this.controlPlane.database.query("SELECT * FROM application_artifacts WHERE id=?").get(e);return t?jd(t):void 0}list(e){return this.controlPlane.database.query("SELECT * FROM application_artifacts WHERE project_id=? ORDER BY created_at DESC").all(e).map(jd)}}function zr(e){let t=e.drafts.get(e.draftId);if(!t||t.version!==e.expectedVersion)throw Error(`Application draft ${e.draftId} changed since version ${e.expectedVersion}`);if(t.status==="applied")throw Error("Application draft was already applied");let r=e.controlPlane.getProject(t.projectId),n=r?e.controlPlane.listEnvironments(r.id).find((a)=>a.id===t.input.environmentId):void 0;if(!r||!n||n.projectId!==r.id||r.organizationId!==t.organizationId)throw Error("Draft deployment scope was not found");if(e.confirmEnvironment!==n.slug)throw Error(`Type ${n.slug} to confirm this deployment target`);let i=ce(t.input,t.suppliedSecretNames);if(!i.valid)throw Error(`Application plan is invalid: ${[...i.issues.map((a)=>a.message),...i.missingSecrets.map((a)=>`Missing secret ${a}`)].join("; ")}`);let o=e.controlPlane.listResources(r.id,n.id).find((a)=>a.kind==="application"&&a.slug===t.input.slug),s=JSON.parse(JSON.stringify({manifest:i.manifest,configPatch:i.configPatch})),c=o?e.controlPlane.updateResource(o.id,o.version,{name:t.input.name,desiredState:s}):e.controlPlane.createResource({projectId:r.id,environmentId:n.id,kind:"application",slug:t.input.slug,name:t.input.name,desiredState:s,metadata:{source:"application-onboarding",draftId:t.id}}),u=new S(e.controlPlane).enqueue({projectId:r.id,environmentId:n.id,resourceId:c.id,actorId:e.actorId,kind:"application.create",idempotencyKey:`application-draft:${t.id}:v${t.version}`,correlationId:`application-draft:${t.id}`,input:s,lockKey:`resource:${c.id}`,providerKey:c.provider??"default",buildSlot:t.input.build.kind!=="prebuilt_image",maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;return e.drafts.markApplied(t.id,t.version,e.actorId),e.controlPlane.appendEvent({organizationId:t.organizationId,projectId:r.id,resourceId:c.id,operationId:u.id,actorId:e.actorId,type:"application.create.queued",payload:{draftId:t.id,environment:n.slug,strategy:t.input.build.kind,costDrivers:i.costDrivers}}),{plan:i,resource:c,operation:u}}function sr(e){let t=["static","compute","serverless_zip","serverless_image"].includes(e.kind),r=["container","compose"].includes(e.kind)&&(e.replicas??1)>1,n=e.kind==="container"||e.kind==="serverless_zip"||e.kind==="serverless_image",i=(o,s)=>s&&(o==="atomic"?e.kind==="static"||e.hasHealthGate:e.hasHealthGate);return[{strategy:"atomic",supported:i("atomic",t),explanation:t?e.hasHealthGate||e.kind==="static"?"Activate an immutable version with an atomic pointer/alias switch.":"Atomic activation needs a readiness gate for this runtime.":"This driver has no atomic pointer or alias primitive.",capacityMultiplier:1,costImpact:"none",rollback:"Switch the pointer/alias back to the previous immutable release."},{strategy:"rolling",supported:i("rolling",r),explanation:r?e.hasHealthGate?"Replace healthy replicas within the configured capacity envelope.":"Rolling activation requires a health/readiness gate.":"Rolling activation requires a capable container/Compose driver and at least two replicas.",capacityMultiplier:1.5,costImpact:"temporary",rollback:"Stop replacement and restore the prior task/service definition."},{strategy:"blue_green",supported:i("blue_green",n),explanation:n?e.hasHealthGate?"Provision a complete green target and switch traffic after health passes.":"Blue-green requires a health gate before traffic can switch.":"The provider does not expose two traffic-addressable revisions.",capacityMultiplier:2,costImpact:"temporary",rollback:"Return all traffic to the preserved blue target."},{strategy:"canary",supported:i("canary",n),explanation:n?e.hasHealthGate?"Shift bounded traffic steps while evaluating health.":"Canary requires a health gate and measurable traffic target.":"The provider does not expose weighted traffic primitives.",capacityMultiplier:1.25,costImpact:"temporary",rollback:"Set canary weight to zero and preserve its diagnostics."}]}function Ha(e,t){let r=sr(e).find((n)=>n.strategy===t);if(!r.supported)throw Error(`${t} is unavailable: ${r.explanation}`);return r}import{createHash as Yb}from"node:crypto";var Xb=/^sha256:[a-f0-9]{64}$/,Zb=/^[a-f0-9]{40,64}$/i;function Di(e){return typeof e==="string"&&e?e:void 0}function Vo(e,t){try{return JSON.parse(String(e))}catch{return t}}function Jp(e){return{id:String(e.id),organizationId:String(e.organization_id),digest:String(e.digest),kind:String(e.kind),uri:String(e.uri),size:Number(e.size),mediaType:String(e.media_type),provenance:Vo(e.provenance,{}),attestation:Vo(e.attestation,{}),verifiedAt:String(e.verified_at),createdAt:String(e.created_at)}}function Hp(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:String(e.environment_id),resourceId:String(e.resource_id),artifactId:String(e.artifact_id),kind:String(e.kind),sourceSha:Di(e.source_sha),configHash:String(e.config_hash),manifest:Vo(e.manifest,{}),provenance:Vo(e.provenance,{}),strategy:String(e.strategy),status:String(e.status),healthGate:e.health_gate==null?void 0:Vo(e.health_gate,void 0),hooks:Vo(e.hooks,{migrations:"none",preActivate:[],postActivate:[]}),drainSeconds:Number(e.drain_seconds),graceSeconds:Number(e.grace_seconds),automaticRollback:Number(e.automatic_rollback)===1,rollbackAttempts:Number(e.rollback_attempts),previousReleaseId:Di(e.previous_release_id),promotedFromReleaseId:Di(e.promoted_from_release_id),actorId:Di(e.actor_id),trigger:String(e.trigger),pinned:Number(e.pinned)===1,pinReason:Di(e.pin_reason),activatedAt:Di(e.activated_at),failedAt:Di(e.failed_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function eS(e){return{sequence:Number(e.sequence),id:String(e.id),releaseId:String(e.release_id),fromStatus:Di(e.from_status),toStatus:String(e.to_status),trafficPercent:e.traffic_percent==null?void 0:Number(e.traffic_percent),health:Vo(e.health,{}),message:String(e.message),operationId:Di(e.operation_id),createdAt:String(e.created_at)}}function tS(e,t){let r=[],n=(i,o,s)=>{if(JSON.stringify(o)===JSON.stringify(s))return;if(o&&s&&typeof o==="object"&&typeof s==="object"&&!Array.isArray(o)&&!Array.isArray(s)){for(let c of[...new Set([...Object.keys(o),...Object.keys(s)])].sort())n(i?`${i}.${c}`:c,o[c],s[c]);return}r.push({path:i,...o!==void 0?{before:o}:{},...s!==void 0?{after:s}:{}})};return n("",e,t),r}class Ud{controlPlane;now;id;constructor(e,t={}){this.controlPlane=e;this.now=t.now??(()=>new Date),this.id=t.id??(()=>crypto.randomUUID())}registerArtifact(e){if(!Xb.test(e.digest)||!/^(?:s3|https|oci|file):/.test(e.uri)||!Number.isInteger(e.size)||e.size<0)throw Error("Artifact requires a SHA-256 digest, supported immutable URI, and non-negative byte size");let t=this.controlPlane.database.query("SELECT * FROM release_artifacts WHERE organization_id=? AND digest=?").get(e.organizationId,e.digest);if(t)return Jp(t);let r=this.id(),n=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO release_artifacts (id, organization_id, digest, kind, uri, size, media_type, provenance, attestation, verified_at, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[r,e.organizationId,e.digest,e.kind,e.uri,e.size,e.mediaType??"application/octet-stream",JSON.stringify(h(e.provenance??{})),JSON.stringify(h(e.attestation??{})),n,n]),this.getArtifact(r)}getArtifact(e){let t=this.controlPlane.database.query("SELECT * FROM release_artifacts WHERE id=?").get(e);return t?Jp(t):void 0}create(e){let t=this.getArtifact(e.artifactId),r=this.controlPlane.getResource(e.resourceId),n=this.controlPlane.listEnvironments(e.projectId).find((T)=>T.id===e.environmentId);if(!t||t.organizationId!==e.organizationId||t.kind!==e.kind)throw Error("Release artifact does not match the organization and deployable kind");if(!r||r.projectId!==e.projectId||r.environmentId!==e.environmentId||!n)throw Error("Release target scope does not match the resource");if(e.sourceSha&&!Zb.test(e.sourceSha))throw Error("Release source must be an immutable commit SHA");Ha({kind:e.kind,provider:r.provider,hasHealthGate:!!e.healthGate,replicas:e.replicas},e.strategy);let i=h(e.config),o=Yb("sha256").update(JSON.stringify(i)).digest("hex"),s=this.active(e.resourceId),c=this.id(),u=this.now().toISOString(),a=e.approvalRequired?"awaiting_approval":"built",f=e.hooks??{migrations:"none",preActivate:[],postActivate:[]};return this.controlPlane.database.run("INSERT INTO releases (id, organization_id, project_id, environment_id, resource_id, artifact_id, kind, source_sha, config_hash, manifest, provenance, strategy, status, health_gate, hooks, drain_seconds, grace_seconds, automatic_rollback, previous_release_id, promoted_from_release_id, actor_id, trigger, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[c,e.organizationId,e.projectId,e.environmentId,e.resourceId,e.artifactId,e.kind,e.sourceSha??null,o,JSON.stringify(h(e.manifest)),JSON.stringify(h(e.provenance??{})),e.strategy,a,e.healthGate?JSON.stringify(e.healthGate):null,JSON.stringify(f),Math.max(0,Math.min(3600,Math.floor(e.drainSeconds??30))),Math.max(0,Math.min(3600,Math.floor(e.graceSeconds??30))),e.automaticRollback===!1?0:1,s?.id??null,e.promotedFromReleaseId??null,e.actorId??null,e.trigger??"manual",u,u]),this.recordTransition(c,void 0,a,{message:e.promotedFromReleaseId?"Immutable artifact promoted without rebuild.":"Immutable release record created."}),this.get(c)}get(e){let t=this.controlPlane.database.query("SELECT * FROM releases WHERE id=?").get(e);return t?Hp(t):void 0}list(e={}){return this.controlPlane.database.query("SELECT * FROM releases ORDER BY created_at DESC, rowid DESC").all().map(Hp).filter((t)=>(!e.projectId||t.projectId===e.projectId)&&(!e.environmentId||t.environmentId===e.environmentId)&&(!e.resourceId||t.resourceId===e.resourceId)&&(!e.status||t.status===e.status))}active(e){return this.list({resourceId:e,status:"active"})[0]}transitions(e){return this.controlPlane.database.query("SELECT * FROM release_transitions WHERE release_id=? ORDER BY sequence").all(e).map(eS)}recordTransition(e,t,r,n){this.controlPlane.database.run("INSERT INTO release_transitions (id, release_id, from_status, to_status, traffic_percent, health, message, operation_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",[this.id(),e,t??null,r,n.trafficPercent??null,JSON.stringify(h(n.health??{})),n.message.slice(0,1000),n.operationId??null,this.now().toISOString()])}progress(e,t){let r=this.get(e);if(!r)throw Error(`Release ${e} was not found`);return this.recordTransition(e,r.status,r.status,t),this.transitions(e).at(-1)}transition(e,t,r){let n=this.get(e);if(!n)throw Error(`Release ${e} was not found`);if(!{built:["awaiting_approval","activating","failed"],awaiting_approval:["built","failed"],activating:["active","failed","rolled_back"],active:["superseded","failed","rolled_back"],failed:["activating","rolled_back"],rolled_back:["activating"],superseded:["activating"]}[n.status].includes(t))throw Error(`Invalid release transition ${n.status} → ${t}`);let o=this.now().toISOString();if(t==="active"){let s=this.active(n.resourceId);if(s&&s.id!==e)this.controlPlane.database.run("UPDATE releases SET status='superseded', updated_at=? WHERE id=?",[o,s.id]),this.recordTransition(s.id,"active","superseded",{message:`Superseded by ${e}.`,operationId:r.operationId})}return this.controlPlane.database.run("UPDATE releases SET status=?, rollback_attempts=rollback_attempts+?, activated_at=CASE WHEN ?='active' THEN ? ELSE activated_at END, failed_at=CASE WHEN ?='failed' THEN ? ELSE failed_at END, updated_at=? WHERE id=?",[t,t==="rolled_back"?1:0,t,o,t,o,o,e]),this.recordTransition(e,n.status,t,r),this.get(e)}approve(e,t){let r=this.get(e);if(!r||r.status!=="awaiting_approval")throw Error("Release is not awaiting approval");let n=this.id(),i=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO release_approvals (id, release_id, environment_id, decision, actor_id, comment, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[n,e,r.environmentId,t.decision,t.actorId,t.comment?.slice(0,1000)??null,i]),this.transition(e,t.decision==="approved"?"built":"failed",{message:t.decision==="approved"?"Environment gate approved.":"Environment gate rejected."})}approvals(e){return this.controlPlane.database.query("SELECT * FROM release_approvals WHERE release_id=? ORDER BY created_at").all(e).map((t)=>({id:String(t.id),releaseId:String(t.release_id),environmentId:String(t.environment_id),decision:String(t.decision),actorId:String(t.actor_id),comment:Di(t.comment),createdAt:String(t.created_at)}))}promote(e,t){let r=this.get(e);if(!r||!["active","superseded"].includes(r.status))throw Error("Only a tested active/superseded release can be promoted");return this.create({organizationId:r.organizationId,projectId:r.projectId,environmentId:t.targetEnvironmentId,resourceId:t.targetResourceId,artifactId:r.artifactId,kind:r.kind,sourceSha:r.sourceSha,config:t.config,manifest:r.manifest,provenance:r.provenance,strategy:t.strategy??r.strategy,healthGate:t.healthGate??r.healthGate,hooks:r.hooks,drainSeconds:r.drainSeconds,graceSeconds:r.graceSeconds,automaticRollback:r.automaticRollback,promotedFromReleaseId:r.id,actorId:t.actorId,trigger:"promotion",approvalRequired:t.approvalRequired})}compare(e,t){let r=this.get(e),n=this.get(t);if(!r||!n)throw Error("Both releases are required for comparison");return{artifactChanged:r.artifactId!==n.artifactId,sourceChanged:r.sourceSha!==n.sourceSha,configChanged:r.configHash!==n.configHash,manifestChanges:tS(r.manifest,n.manifest),dataCaveat:n.hooks.migrations==="none"?"No database migration is recorded.":`Database hooks are ${n.hooks.migrations}; release rollback does not roll back data.`}}pin(e,t,r){if(!this.get(e))throw Error("Release was not found");return this.controlPlane.database.run("UPDATE releases SET pinned=?, pin_reason=?, updated_at=? WHERE id=?",[t?1:0,t?r?.slice(0,500)??"operator":null,this.now().toISOString(),e]),this.get(e)}retentionCandidates(e){let t=Math.max(1,Math.min(100,Math.floor(e.keepPerResource??10))),r=new Map;for(let n of this.list()){let i=r.get(n.resourceId)??[];i.push(n),r.set(n.resourceId,i)}return[...r.values()].flatMap((n)=>n.slice(t)).filter((n)=>new Date(n.createdAt)<e.before&&!n.pinned&&!["active","activating","awaiting_approval"].includes(n.status)&&!this.list().some((i)=>i.previousReleaseId===n.id&&["active","activating"].includes(i.status)))}}class st{controlPlane;releases;queue;constructor(e){this.controlPlane=e;this.releases=new Ud(e),this.queue=new S(e)}enqueueActivation(e,t={}){let r=this.releases.get(e.id);if(!r)throw Error("Release was not found");if(!["built","failed","rolled_back","superseded"].includes(r.status))throw Error(`Release ${r.status} cannot be activated`);let n=t.action??"activate",i=this.queue.enqueue({projectId:r.projectId,environmentId:r.environmentId,resourceId:r.resourceId,actorId:t.actorId,kind:`release.${n}`,idempotencyKey:`release:${r.id}:${n}:${r.rollbackAttempts}`,correlationId:`release:${r.id}`,input:{releaseId:r.id,targetReleaseId:t.targetReleaseId??null},lockKey:`resource:${r.resourceId}`,providerKey:this.controlPlane.getResource(r.resourceId)?.provider??"default",maxAttempts:r.automaticRollback?2:1,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:365}).operation;return this.releases.transition(r.id,"activating",{message:`${n} queued.`,operationId:i.id,trafficPercent:0}),i}completeHealthGate(e,t){let r=this.releases.get(e);if(!r||r.status!=="activating")throw Error("Release is not activating");if(t.healthy)return{release:this.releases.transition(r.id,"active",{message:t.message??"Health gate passed; activation completed.",operationId:t.operationId,trafficPercent:100,health:t.health})};let n=this.releases.transition(r.id,"failed",{message:t.message??"Health gate failed.",operationId:t.operationId,trafficPercent:0,health:t.health}),i=r.previousReleaseId?this.releases.get(r.previousReleaseId):void 0;if(!r.automaticRollback||r.rollbackAttempts>=1||!i)return{release:n};let o=this.queue.enqueue({projectId:r.projectId,environmentId:r.environmentId,resourceId:r.resourceId,kind:"release.rollback",idempotencyKey:`release:${r.id}:automatic-rollback`,correlationId:`release:${r.id}`,input:{releaseId:r.id,targetReleaseId:i.id,automatic:!0},lockKey:`resource:${r.resourceId}`,providerKey:this.controlPlane.getResource(r.resourceId)?.provider??"default",maxAttempts:1,retryClasses:[],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:365}).operation;return{release:n,rollbackOperation:o}}enqueueRollback(e,t={}){let r=this.releases.get(e.id);if(!r||r.status!=="active")throw Error("Only the active release can be rolled back");let n=t.targetReleaseId?this.releases.get(t.targetReleaseId):r.previousReleaseId?this.releases.get(r.previousReleaseId):void 0;if(!n||n.resourceId!==r.resourceId||!["superseded","active"].includes(n.status))throw Error("Rollback requires a preserved prior release for the same resource");return this.queue.enqueue({projectId:r.projectId,environmentId:r.environmentId,resourceId:r.resourceId,actorId:t.actorId,kind:"release.rollback",idempotencyKey:`release:${r.id}:manual-rollback:${n.id}`,correlationId:`release:${r.id}`,input:{releaseId:r.id,targetReleaseId:n.id,automatic:!1},lockKey:`resource:${r.resourceId}`,providerKey:this.controlPlane.getResource(r.resourceId)?.provider??"default",maxAttempts:1,retryClasses:[],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:365}).operation}}function rS(e){if(e.strategy==="canary")return[5,25,50,100].map((t,r)=>({step:`canary-${t}`,trafficPercent:t,waitSeconds:r===3?e.drainSeconds:e.graceSeconds,requiresHealth:!0}));if(e.strategy==="blue_green")return[{step:"green-health",trafficPercent:0,waitSeconds:e.graceSeconds,requiresHealth:!0},{step:"traffic-switch",trafficPercent:100,waitSeconds:e.drainSeconds,requiresHealth:!0}];if(e.strategy==="rolling")return[{step:"rolling-replacement",trafficPercent:50,waitSeconds:e.graceSeconds,requiresHealth:!0},{step:"rolling-complete",trafficPercent:100,waitSeconds:e.drainSeconds,requiresHealth:!0}];return[{step:"immutable-switch",trafficPercent:100,waitSeconds:e.drainSeconds,requiresHealth:!!e.healthGate}]}async function Wp(e,t){if(t.release.artifactId!==t.artifact.id)throw Error("Release activation artifact identity changed");Ha({kind:t.release.kind,hasHealthGate:!!t.release.healthGate,replicas:Number(t.release.manifest?.replicas)||void 0},t.release.strategy);let r=e.capability(t);if(!r.supported)throw Error(`${t.release.strategy} is unavailable in ${e.name}: ${r.explanation}`);return e.activate({...t,transitions:rS(t.release)})}async function Kp(e,t){if(!t.previous)throw Error("Rollback requires the preserved previous release");return e.rollback({...t,transitions:[{step:"rollback",trafficPercent:0,waitSeconds:t.release.drainSeconds,requiresHealth:!0}]})}var nS=["release.activate","release.rollback"];function iS(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function Qp(e){let t=new st(e.store),r=async(n)=>{let i=iS(n.operation.input),o=typeof i.releaseId==="string"?i.releaseId:"",s=t.releases.get(o);if(!s)throw Error(`Queued release ${o||"(missing)"} was not found`);if(s.projectId!==n.operation.projectId||s.environmentId!==n.operation.environmentId||s.resourceId!==n.operation.resourceId)throw Error("Queued release does not match the operation scope");let c=t.releases.getArtifact(s.artifactId);if(!c||c.digest!==t.releases.getArtifact(s.artifactId)?.digest)throw Error("Immutable release artifact is unavailable");let u=typeof i.targetReleaseId==="string"&&i.targetReleaseId?i.targetReleaseId:s.previousReleaseId,a=u?t.releases.get(u):void 0;if(a&&(a.resourceId!==s.resourceId||a.artifactId===s.artifactId&&a.id===s.id))throw Error("Rollback target does not match the release resource");let f=await e.resolveDriver(s);n.checkpoint("verify",`Verifying ${c.digest} and ${s.configHash} for ${f.name}.`),n.log(`Artifact ${c.digest}; source ${s.sourceSha??"not recorded"}; config ${s.configHash}.`,{stream:"system"}),n.throwIfCancellationRequested();let T;try{T=n.operation.kind==="release.rollback"?await Kp(f,{release:s,artifact:c,previous:a}):await Wp(f,{release:s,artifact:c,previous:a})}catch(R){if(n.operation.kind==="release.activate"&&t.releases.get(s.id)?.status==="activating")t.completeHealthGate(s.id,{healthy:!1,operationId:n.operation.id,message:R instanceof Error?R.message:String(R)});throw R}for(let R of T.transitions)t.releases.progress(s.id,{message:`${n.operation.kind==="release.rollback"?"Rollback":"Activation"} traffic at ${R.trafficPercent}%.`,trafficPercent:R.trafficPercent,health:R.observed,operationId:n.operation.id}),n.log(`Traffic ${R.trafficPercent}%: ${R.healthy?"healthy":"unhealthy"}.`,{stream:R.healthy?"step":"stderr",step:"health"});if(n.checkpoint("health","Evaluating the provider health result."),!T.activated||!T.healthy){if(n.operation.kind==="release.activate"&&t.releases.get(s.id)?.status==="activating")t.completeHealthGate(s.id,{healthy:!1,operationId:n.operation.id,health:{resourceVersions:T.resourceVersions},message:T.error??"Provider health gate failed."});throw Error(T.error??`${f.name} reported an unhealthy release`)}if(n.operation.kind==="release.activate"&&s.healthGate?.name){if(!e.resolveHealthGate)throw t.completeHealthGate(s.id,{healthy:!1,operationId:n.operation.id,message:`Named health gate ${s.healthGate.name} is not available to this worker.`}),Error(`Named health gate ${s.healthGate.name} is unavailable`);n.checkpoint("named-health-gate",`Waiting on ${s.healthGate.name}.`);let R=await e.resolveHealthGate(s.healthGate.name,s);if(n.log(`${s.healthGate.name}: ${R.healthy?"healthy":"unhealthy"}${R.message?` — ${R.message}`:""}.`,{stream:R.healthy?"step":"stderr",step:"health"}),!R.healthy)throw t.completeHealthGate(s.id,{healthy:!1,operationId:n.operation.id,health:R.evidence,message:R.message??`Named health gate ${s.healthGate.name} failed.`}),Error(R.message??`Named health gate ${s.healthGate.name} failed`)}if(n.operation.kind==="release.rollback"){let R=t.releases.get(s.id);if(R.status!=="rolled_back")t.releases.transition(R.id,"rolled_back",{message:`Traffic restored through ${f.name}.`,operationId:n.operation.id,trafficPercent:0,health:{resourceVersions:T.resourceVersions}});if(a&&a.status!=="active"){let D=a.status==="activating"?a:t.releases.transition(a.id,"activating",{message:"Rollback target restoring traffic.",operationId:n.operation.id,trafficPercent:0});t.releases.transition(D.id,"active",{message:"Previous immutable release restored.",operationId:n.operation.id,trafficPercent:100,health:{resourceVersions:T.resourceVersions}})}}else t.completeHealthGate(s.id,{healthy:!0,operationId:n.operation.id,health:{providerVersion:T.providerVersion??null,resourceVersions:T.resourceVersions},message:"Provider activation and health gates completed."});return n.checkpoint("finalize","Persisted the terminal release state."),{releaseId:s.id,artifactDigest:c.digest,provider:f.name,providerVersion:T.providerVersion??null,resourceVersions:T.resourceVersions,status:t.releases.get(s.id).status}};return Object.fromEntries(nS.map((n)=>[n,r]))}import{createCipheriv as oS,createDecipheriv as sS,createHash as tg,randomBytes as zd}from"node:crypto";var rg={github:{repositories:!0,branches:!0,tags:!0,webhooks:!0,pullRequests:!0,tokenRefresh:!0,deployKeys:!0},gitlab:{repositories:!0,branches:!0,tags:!0,webhooks:!0,pullRequests:!0,tokenRefresh:!0,deployKeys:!0},bitbucket:{repositories:!0,branches:!0,tags:!0,webhooks:!0,pullRequests:!0,tokenRefresh:!0,deployKeys:!0},gitea:{repositories:!0,branches:!0,tags:!0,webhooks:!0,pullRequests:!0,tokenRefresh:!1,deployKeys:!0},generic_https:{repositories:!1,branches:!0,tags:!0,webhooks:!1,pullRequests:!1,tokenRefresh:!1,deployKeys:!1},generic_ssh:{repositories:!1,branches:!0,tags:!0,webhooks:!1,pullRequests:!1,tokenRefresh:!1,deployKeys:!0}};function Rt(e){return typeof e==="string"&&e?e:void 0}function Go(e,t){try{return typeof e==="string"?JSON.parse(e):t}catch{return t}}function Oi(e){return JSON.stringify(h(e))}function qo(e){return tg("sha256").update(e).digest("hex")}function Yp(e){let t=e.trim().replace(/\/$/,""),r=new URL(t.includes("://")?t:`https://${t}`);if(r.username||r.password||r.search||r.hash)throw Error("Source host cannot contain credentials, a query, or a fragment");if(r.protocol!=="https:"&&!(r.protocol==="http:"&&["localhost","127.0.0.1","::1"].includes(r.hostname)))throw Error("Source host must use HTTPS");return`${r.protocol}//${r.host}${r.pathname.replace(/\/$/,"")}`}function Xp(e){let t=e.trim();if(t.length<2||t.length>80)throw Error("Connection name must contain 2-80 characters");return t}function Vd(e){let t=e.trim().replace(/^\/+|\/+$/g,"");if(!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(t))throw Error("Repository must use owner/name format");return t}function Zp(e){let t=e.trim()||".";if(t.startsWith("/")||t.split("/").includes("..")||/[\0\r\n]/.test(t))throw Error("Monorepo root must stay inside the repository");return t.replace(/^\.\//,"")||"."}function Wa(e){return[...new Set((e??[]).map((t)=>t.trim()).filter(Boolean))].slice(0,100)}function aS(e){let t=e.trim();if(/\r|\n/.test(t)||/https?:\/\/[^/@\s]+:[^/@\s]+@/i.test(t))throw Error("Clone URL cannot contain credentials or control characters");if(!/^(?:https?:\/\/|ssh:\/\/|git@[A-Za-z0-9.-]+:)/.test(t))throw Error("Clone URL must use HTTPS or SSH");return t}function cS(e){return{id:String(e.id),organizationId:String(e.organization_id),provider:String(e.provider),name:String(e.name),host:String(e.host),owner:Rt(e.owner),authKind:String(e.auth_kind),credentialConfigured:!!e.credential_ciphertext,credentialFingerprint:Rt(e.credential_fingerprint),grantedScopes:Go(e.granted_scopes,[]),capabilities:Go(e.capabilities,rg[String(e.provider)]),status:String(e.status),healthMessage:Rt(e.health_message),lastTestedAt:Rt(e.last_tested_at),lastSyncedAt:Rt(e.last_synced_at),credentialExpiresAt:Rt(e.credential_expires_at),version:Number(e.version),createdByActorId:Rt(e.created_by_actor_id),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function qd(e){return{id:String(e.id),connectionId:String(e.connection_id),providerRepositoryId:String(e.provider_repository_id),fullName:String(e.full_name),cloneUrl:String(e.clone_url),defaultBranch:String(e.default_branch),visibility:String(e.visibility),archived:Number(e.archived)===1,metadata:Go(e.metadata,{}),syncedAt:String(e.synced_at)}}function eg(e){return{id:String(e.id),projectId:String(e.project_id),environmentId:Rt(e.environment_id),resourceId:Rt(e.resource_id),connectionId:String(e.connection_id),repositoryId:Rt(e.repository_id),repositoryFullName:String(e.repository_full_name),defaultBranch:String(e.default_branch),branchRule:Rt(e.branch_rule),tagRule:Rt(e.tag_rule),monorepoRoot:String(e.monorepo_root),includePaths:Go(e.include_paths,[]),excludePaths:Go(e.exclude_paths,[]),submodules:Number(e.submodules)===1,cloneDepth:e.clone_depth==null?void 0:Number(e.clone_depth),deployKeyId:Rt(e.deploy_key_id),autoDeploy:Number(e.auto_deploy)===1,pullRequestPreviews:Number(e.pull_request_previews)===1,status:String(e.status),disabledReason:Rt(e.disabled_reason),version:Number(e.version),createdByActorId:Rt(e.created_by_actor_id),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Gd(e){return{id:String(e.id),connectionId:String(e.connection_id),name:String(e.name),publicKey:String(e.public_key),publicKeyFingerprint:String(e.public_key_fingerprint),host:String(e.host),hostKey:String(e.host_key),hostKeyFingerprint:String(e.host_key_fingerprint),createdByActorId:Rt(e.created_by_actor_id),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Jd(e){return{id:String(e.id),connectionId:String(e.connection_id),repositoryId:Rt(e.repository_id),repositoryFullName:String(e.repository_full_name),providerWebhookId:Rt(e.provider_webhook_id),events:Go(e.events,[]),status:String(e.status),healthMessage:Rt(e.health_message),lastDeliveryAt:Rt(e.last_delivery_at),lastReconciledAt:Rt(e.last_reconciled_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Hd(e){return{id:String(e.id),connectionId:String(e.connection_id),webhookId:String(e.webhook_id),providerDeliveryId:String(e.provider_delivery_id),event:String(e.event),action:Rt(e.action),commitSha:Rt(e.commit_sha),signatureStatus:String(e.signature_status),status:String(e.status),payloadSummary:Go(e.payload_summary,{}),operationId:Rt(e.operation_id),error:Rt(e.error),receivedAt:String(e.received_at),processedAt:Rt(e.processed_at)}}class rr{controlPlane;key;nowFn;idFn;constructor(e,t={}){this.controlPlane=e;this.key=t.encryptionKey?tg("sha256").update(t.encryptionKey).digest():void 0,this.nowFn=t.now??(()=>new Date),this.idFn=t.id??(()=>crypto.randomUUID())}now(){return this.nowFn().toISOString()}run(e,t){this.controlPlane.database.run(e,t)}encrypt(e){if(!this.key)throw Error("Source credential encryption key is not configured");let t=zd(12),r=oS("aes-256-gcm",this.key,t),n=Buffer.concat([r.update(e,"utf8"),r.final()]);return`v1.${t.toString("base64url")}.${r.getAuthTag().toString("base64url")}.${n.toString("base64url")}`}decrypt(e){if(!this.key)throw Error("Source credential encryption key is not configured");let[t,r,n,i]=e.split(".");if(t!=="v1"||!r||!n||!i)throw Error("Encrypted source credential is unavailable");let o=sS("aes-256-gcm",this.key,Buffer.from(r,"base64url"));return o.setAuthTag(Buffer.from(n,"base64url")),Buffer.concat([o.update(Buffer.from(i,"base64url")),o.final()]).toString("utf8")}createConnection(e){if(!this.controlPlane.getOrganization(e.organizationId))throw Error("Source connection organization was not found");let t=this.now(),r=this.idFn(),n=e.credential?JSON.stringify(e.credential):void 0;return this.run(`INSERT INTO source_connections (id, organization_id, provider, name, host, owner, auth_kind, credential_ciphertext, credential_fingerprint, granted_scopes, capabilities, status, credential_expires_at, created_by_actor_id, created_at, updated_at)
3
3
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?, ?, ?)`,[r,e.organizationId,e.provider,Xp(e.name),Yp(e.host),e.owner?.trim()||null,e.authKind??(n?"access_token":"none"),n?this.encrypt(n):null,n?qo(n).slice(0,16):null,Oi([...new Set(e.grantedScopes??[])].sort()),Oi(rg[e.provider]),e.credentialExpiresAt??null,e.createdByActorId??null,t,t]),this.controlPlane.appendEvent({organizationId:e.organizationId,actorId:e.createdByActorId,type:"source.connection.created",payload:{connectionId:r,provider:e.provider,host:Yp(e.host),owner:e.owner??null,scopes:e.grantedScopes??[]}}),this.getConnection(r)}getConnection(e){let t=this.controlPlane.database.query("SELECT * FROM source_connections WHERE id = ?").get(e);return t?this.currentConnection(t):void 0}listConnections(e){return this.controlPlane.database.query("SELECT * FROM source_connections WHERE organization_id = ? ORDER BY name").all(e).map((t)=>this.currentConnection(t))}currentConnection(e){let t=cS(e);if(t.status!=="disconnected"&&t.credentialExpiresAt&&new Date(t.credentialExpiresAt).getTime()<=this.nowFn().getTime())return{...t,status:"expired",healthMessage:"Source credential expired; rotate it before deploying."};return t}getCredential(e){let t=this.controlPlane.database.query("SELECT credential_ciphertext FROM source_connections WHERE id = ?").get(e);return t?.credential_ciphertext?JSON.parse(this.decrypt(String(t.credential_ciphertext))):void 0}rotateCredential(e,t,r={}){let n=this.getConnection(e);if(!n||n.status==="disconnected")throw Error("Active source connection was not found");let i=JSON.stringify(t);return this.run("UPDATE source_connections SET credential_ciphertext = ?, credential_fingerprint = ?, credential_expires_at = ?, status = 'pending', health_message = NULL, version = version + 1, updated_at = ? WHERE id = ?",[this.encrypt(i),qo(i).slice(0,16),r.expiresAt??null,this.now(),e]),this.controlPlane.appendEvent({organizationId:n.organizationId,actorId:r.actorId,type:"source.credential.rotated",payload:{connectionId:e,fingerprint:qo(i).slice(0,16),expiresAt:r.expiresAt??null}}),this.getConnection(e)}updateHealth(e,t){let r=this.getConnection(e);if(!r||["disconnected","expired"].includes(r.status))throw Error("Active source connection was not found");let n=this.now(),i=t.grantedScopes?[...new Set(t.grantedScopes.map((o)=>o.trim()).filter(Boolean))].sort():void 0;if(this.run("UPDATE source_connections SET status = ?, health_message = ?, granted_scopes = COALESCE(?, granted_scopes), last_tested_at = COALESCE(?, last_tested_at), last_synced_at = COALESCE(?, last_synced_at), version = version + 1, updated_at = ? WHERE id = ?",[t.status,t.message?.slice(0,1000)??null,i?Oi(i):null,t.tested?n:null,t.synced?n:null,n,e]),i&&JSON.stringify(i)!==JSON.stringify([...r.grantedScopes].sort()))this.controlPlane.appendEvent({organizationId:r.organizationId,type:"source.connection.scopes_updated",payload:{connectionId:e,grantedScopes:i}});return this.getConnection(e)}upsertRepository(e){let t=this.getConnection(e.connectionId);if(!t||["disconnected","expired"].includes(t.status))throw Error("Active source connection was not found");let r=this.now(),n=this.controlPlane.database.query("SELECT id FROM source_repositories WHERE connection_id = ? AND provider_repository_id = ?").get(e.connectionId,e.providerRepositoryId),i=n?String(n.id):this.idFn();return this.run(`INSERT INTO source_repositories (id, connection_id, provider_repository_id, full_name, clone_url, default_branch, visibility, archived, metadata, synced_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
4
4
  ON CONFLICT(connection_id, provider_repository_id) DO UPDATE SET full_name=excluded.full_name, clone_url=excluded.clone_url, default_branch=excluded.default_branch, visibility=excluded.visibility, archived=excluded.archived, metadata=excluded.metadata, synced_at=excluded.synced_at`,[i,e.connectionId,e.providerRepositoryId,Vd(e.fullName),aS(e.cloneUrl),e.defaultBranch.trim()||"main",e.visibility,e.archived?1:0,Oi(e.metadata),r]),qd(this.controlPlane.database.query("SELECT * FROM source_repositories WHERE id = ?").get(i))}listRepositories(e,t,r=100){let n=t?.trim().toLowerCase();return(n?this.controlPlane.database.query("SELECT * FROM source_repositories WHERE connection_id = ? AND lower(full_name) LIKE ? ORDER BY full_name LIMIT ?").all(e,`%${n}%`,Math.min(500,r)):this.controlPlane.database.query("SELECT * FROM source_repositories WHERE connection_id = ? ORDER BY full_name LIMIT ?").all(e,Math.min(500,r))).map(qd)}getRepository(e){let t=this.controlPlane.database.query("SELECT * FROM source_repositories WHERE id = ?").get(e);return t?qd(t):void 0}createDeployKey(e){let t=this.getConnection(e.connectionId);if(!t||["disconnected","expired"].includes(t.status)||!t.capabilities.deployKeys)throw Error("An active deploy-key capable source connection is required");if(!/^ssh-(?:ed25519|rsa)\s+[A-Za-z0-9+/=]+/.test(e.publicKey.trim()))throw Error("A valid SSH public key is required");if(!/BEGIN (?:OPENSSH|RSA) PRIVATE KEY/.test(e.privateKey))throw Error("A valid SSH private key is required");if(!/^(?:ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp\d+)\s+[A-Za-z0-9+/=]+/.test(e.hostKey.trim()))throw Error("A pinned SSH host key is required");let r=this.idFn(),n=this.now(),i=`sha256:${qo(e.publicKey.trim())}`,o=`sha256:${qo(e.hostKey.trim())}`;return this.run("INSERT INTO source_deploy_keys (id, connection_id, name, public_key, public_key_fingerprint, private_key_ciphertext, host, host_key, host_key_fingerprint, created_by_actor_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[r,e.connectionId,Xp(e.name),e.publicKey.trim(),i,this.encrypt(e.privateKey),e.host.trim().toLowerCase(),e.hostKey.trim(),o,e.actorId??null,n,n]),this.controlPlane.appendEvent({organizationId:t.organizationId,actorId:e.actorId,type:"source.deploy_key.created",payload:{connectionId:e.connectionId,deployKeyId:r,publicFingerprint:i,hostFingerprint:o}}),Gd(this.controlPlane.database.query("SELECT * FROM source_deploy_keys WHERE id = ?").get(r))}getDeployKey(e){let t=this.controlPlane.database.query("SELECT * FROM source_deploy_keys WHERE id = ?").get(e);return t?Gd(t):void 0}listDeployKeys(e){return this.controlPlane.database.query("SELECT * FROM source_deploy_keys WHERE connection_id = ? ORDER BY name, created_at").all(e).map(Gd)}revokeDeployKey(e,t){let r=this.getDeployKey(e),n=r?this.getConnection(r.connectionId):void 0;if(!r||!n)throw Error("Deploy key was not found");let i=this.listBindings({connectionId:n.id}).filter((s)=>s.deployKeyId===e),o=this.now();return this.controlPlane.database.transaction(()=>{this.run("UPDATE source_bindings SET deploy_key_id=NULL, status='disabled', auto_deploy=0, disabled_reason='Source deploy key was revoked', version=version+1, updated_at=? WHERE deploy_key_id=?",[o,e]),this.run("DELETE FROM source_deploy_keys WHERE id=?",[e])})(),this.controlPlane.appendEvent({organizationId:n.organizationId,actorId:t,type:"source.deploy_key.revoked",level:"warning",payload:{connectionId:n.id,deployKeyId:e,affectedBindingIds:i.map((s)=>s.id)}}),{affectedBindings:i}}getDeployPrivateKey(e){let t=this.controlPlane.database.query("SELECT private_key_ciphertext FROM source_deploy_keys WHERE id = ?").get(e);if(!t)throw Error("Deploy key was not found");return this.decrypt(String(t.private_key_ciphertext))}createBinding(e){let t=this.getConnection(e.connectionId);if(!t||["disconnected","expired"].includes(t.status))throw Error("Active source connection was not found");if(e.repositoryId&&this.getRepository(e.repositoryId)?.connectionId!==t.id)throw Error("Repository does not belong to this connection");if(e.deployKeyId&&this.getDeployKey(e.deployKeyId)?.connectionId!==t.id)throw Error("Deploy key does not belong to this connection");let r=this.idFn(),n=this.now();return this.run(`INSERT INTO source_bindings (id, project_id, environment_id, resource_id, connection_id, repository_id, repository_full_name, default_branch, branch_rule, tag_rule, monorepo_root, include_paths, exclude_paths, submodules, clone_depth, deploy_key_id, auto_deploy, pull_request_previews, status, created_by_actor_id, created_at, updated_at)
@@ -30,7 +30,7 @@ data: ${JSON.stringify(rt)}
30
30
  default_role = ?, enabled = ?, enforce_sso = ?, updated_at = ? WHERE id = ?`,[t,r,n,i,e.clientSecret?this.encrypt(e.clientSecret):null,JSON.stringify(o),JSON.stringify(s),e.defaultRole??c.defaultRole,e.enabled??c.enabled?1:0,e.enforceSso??c.enforceSso?1:0,u,c.id]),this.getOidcProvider(c.id)}if(!e.clientSecret)throw Error("OIDC client secret is required for a new provider");let a=e.id??this.idFn();return this.run(`INSERT INTO auth_oidc_providers (id, organization_id, slug, name, issuer, client_id,
31
31
  client_secret_ciphertext, scopes, allowed_domains, default_role, enabled, enforce_sso, created_at, updated_at)
32
32
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[a,e.organizationId,t,r,n,i,this.encrypt(e.clientSecret),JSON.stringify(o),JSON.stringify(s),e.defaultRole??"viewer",e.enabled===!1?0:1,e.enforceSso?1:0,u,u]),this.getOidcProvider(a)}getOidcProvider(e){let t=this.controlPlane.database.query("SELECT * FROM auth_oidc_providers WHERE id = ?").get(e);return t?Za(t):void 0}getOidcProviderBySlug(e){let t=this.controlPlane.database.query("SELECT * FROM auth_oidc_providers WHERE slug = ? COLLATE NOCASE").get(e.trim());return t?Za(t):void 0}listOidcProviders(e,t={}){return(e?this.controlPlane.database.query("SELECT * FROM auth_oidc_providers WHERE organization_id = ? ORDER BY name COLLATE NOCASE").all(e):this.controlPlane.database.query("SELECT * FROM auth_oidc_providers ORDER BY name COLLATE NOCASE").all()).map(Za).filter((n)=>t.includeDisabled||n.enabled)}setOidcProviderEnabled(e,t){let r=this.now();if(this.controlPlane.database.run("UPDATE auth_oidc_providers SET enabled = ?, enforce_sso = CASE WHEN ? = 0 THEN 0 ELSE enforce_sso END, updated_at = ? WHERE id = ?",[t?1:0,t?1:0,r,e]).changes!==1)throw Error("OIDC provider was not found");if(!t)this.run("UPDATE auth_oidc_transactions SET consumed_at = ? WHERE provider_id = ? AND consumed_at IS NULL",[r,e]);return this.getOidcProvider(e)}getOidcProviderCredentials(e){let t=this.controlPlane.database.query("SELECT * FROM auth_oidc_providers WHERE id = ?").get(e);if(!t||typeof t.client_secret_ciphertext!=="string")throw Error("OIDC provider credentials are unavailable");return{provider:Za(t),clientSecret:this.decrypt(t.client_secret_ciphertext)}}beginOidcTransaction(e,t,r){if(!this.getOidcProvider(e)?.enabled)throw Error("OIDC provider is unavailable");let i=this.idFn(),o=Ui(32).toString("base64url"),s=Ui(32).toString("base64url"),c=Ui(64).toString("base64url"),u=this.now(),a=new Date(this.nowFn().getTime()+Ag).toISOString();return this.run(`INSERT INTO auth_oidc_transactions (id, provider_id, state_hash, nonce_ciphertext, verifier_ciphertext,
33
- redirect_uri, return_path, expires_at, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i,e,yi(o),this.encrypt(s),this.encrypt(c),t,r,a,u]),{transaction:this.getOidcTransaction(i),state:o,nonce:s,verifier:c}}getOidcTransaction(e){let t=this.controlPlane.database.query("SELECT * FROM auth_oidc_transactions WHERE id = ?").get(e);return t?wg(t,this.now()):void 0}consumeOidcTransaction(e,t){return this.controlPlane.transaction(()=>{let r=this.controlPlane.database.query("SELECT * FROM auth_oidc_transactions WHERE provider_id = ? AND state_hash = ?").get(e,yi(t));if(!r)throw Error("OIDC transaction is invalid");let n=wg(r,this.now());if(n.state!=="pending")throw Error(`OIDC transaction is ${n.state}`);if(this.controlPlane.database.run("UPDATE auth_oidc_transactions SET consumed_at = ? WHERE id = ? AND consumed_at IS NULL AND expires_at > ?",[this.now(),n.id,this.now()]).changes!==1)throw Error("OIDC transaction is no longer available");return{transaction:this.getOidcTransaction(n.id),nonce:this.decrypt(String(r.nonce_ciphertext)),verifier:this.decrypt(String(r.verifier_ciphertext))}})}getOidcSubject(e,t){let r=this.controlPlane.database.query("SELECT * FROM auth_oidc_subjects WHERE provider_id = ? AND subject = ?").get(e,t);return r?LS(r):void 0}linkOidcSubject(e,t,r,n){let i=this.getOidcProvider(e),o=this.getIdentity(t);if(!i||!o)throw Error("OIDC provider or identity was not found");let s=ru(n);if(!r.trim()||r.length>512)throw Error("OIDC subject is invalid");let c=this.getOidcSubject(e,r);if(c&&c.identityId!==t)throw Error("OIDC subject is already linked to another identity");let u=this.now();if(c)return this.run("UPDATE auth_oidc_subjects SET email = ?, last_login_at = ? WHERE id = ?",[s,u,c.id]),this.getOidcSubject(e,r);let a=this.idFn();return this.run("INSERT INTO auth_oidc_subjects (id, provider_id, identity_id, subject, email, linked_at, last_login_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[a,e,t,r,s,u,u]),this.getOidcSubject(e,r)}purgeExpired(){let e=this.now(),t=this.controlPlane.database.run("DELETE FROM auth_action_tokens WHERE expires_at < ? OR consumed_at IS NOT NULL",[e]).changes,r=this.controlPlane.database.run("DELETE FROM auth_sessions WHERE revoked_at IS NOT NULL OR idle_expires_at < ? OR absolute_expires_at < ?",[e,e]).changes;return this.controlPlane.database.run("DELETE FROM auth_mfa_challenges WHERE consumed_at IS NOT NULL OR expires_at < ?",[e]),this.controlPlane.database.run("DELETE FROM auth_oidc_transactions WHERE consumed_at IS NOT NULL OR expires_at < ?",[e]),{actionTokens:t,sessions:r}}}async function ba(e,t){let r=e.notifications?.email?.from;if(!r)return!1;try{let{EmailClient:n}=await import("./chunk-vn05n5z6.js");return await new n({region:e.project.region,defaultFrom:r}).send(t),!0}catch{return!1}}import{randomBytes as BS}from"node:crypto";import{chmodSync as FS,existsSync as jS,mkdirSync as US,readFileSync as zS,writeFileSync as VS}from"node:fs";import{dirname as qS}from"node:path";function x(e){let t=process.env.TS_CLOUD_AUTH_ENCRYPTION_KEY?.trim();if(t)return t;let r=A(e,"auth-encryption-key");try{if(jS(r)){let i=zS(r,"utf8").trim();if(i)return i}}catch{}let n=BS(32).toString("base64url");try{US(qS(r),{recursive:!0,mode:448}),VS(r,`${n}
33
+ redirect_uri, return_path, expires_at, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i,e,yi(o),this.encrypt(s),this.encrypt(c),t,r,a,u]),{transaction:this.getOidcTransaction(i),state:o,nonce:s,verifier:c}}getOidcTransaction(e){let t=this.controlPlane.database.query("SELECT * FROM auth_oidc_transactions WHERE id = ?").get(e);return t?wg(t,this.now()):void 0}consumeOidcTransaction(e,t){return this.controlPlane.transaction(()=>{let r=this.controlPlane.database.query("SELECT * FROM auth_oidc_transactions WHERE provider_id = ? AND state_hash = ?").get(e,yi(t));if(!r)throw Error("OIDC transaction is invalid");let n=wg(r,this.now());if(n.state!=="pending")throw Error(`OIDC transaction is ${n.state}`);if(this.controlPlane.database.run("UPDATE auth_oidc_transactions SET consumed_at = ? WHERE id = ? AND consumed_at IS NULL AND expires_at > ?",[this.now(),n.id,this.now()]).changes!==1)throw Error("OIDC transaction is no longer available");return{transaction:this.getOidcTransaction(n.id),nonce:this.decrypt(String(r.nonce_ciphertext)),verifier:this.decrypt(String(r.verifier_ciphertext))}})}getOidcSubject(e,t){let r=this.controlPlane.database.query("SELECT * FROM auth_oidc_subjects WHERE provider_id = ? AND subject = ?").get(e,t);return r?LS(r):void 0}linkOidcSubject(e,t,r,n){let i=this.getOidcProvider(e),o=this.getIdentity(t);if(!i||!o)throw Error("OIDC provider or identity was not found");let s=ru(n);if(!r.trim()||r.length>512)throw Error("OIDC subject is invalid");let c=this.getOidcSubject(e,r);if(c&&c.identityId!==t)throw Error("OIDC subject is already linked to another identity");let u=this.now();if(c)return this.run("UPDATE auth_oidc_subjects SET email = ?, last_login_at = ? WHERE id = ?",[s,u,c.id]),this.getOidcSubject(e,r);let a=this.idFn();return this.run("INSERT INTO auth_oidc_subjects (id, provider_id, identity_id, subject, email, linked_at, last_login_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[a,e,t,r,s,u,u]),this.getOidcSubject(e,r)}purgeExpired(){let e=this.now(),t=this.controlPlane.database.run("DELETE FROM auth_action_tokens WHERE expires_at < ? OR consumed_at IS NOT NULL",[e]).changes,r=this.controlPlane.database.run("DELETE FROM auth_sessions WHERE revoked_at IS NOT NULL OR idle_expires_at < ? OR absolute_expires_at < ?",[e,e]).changes;return this.controlPlane.database.run("DELETE FROM auth_mfa_challenges WHERE consumed_at IS NOT NULL OR expires_at < ?",[e]),this.controlPlane.database.run("DELETE FROM auth_oidc_transactions WHERE consumed_at IS NOT NULL OR expires_at < ?",[e]),{actionTokens:t,sessions:r}}}async function ba(e,t){let r=e.notifications?.email?.from;if(!r)return!1;try{let{EmailClient:n}=await import("./chunk-pr1dg1km.js");return await new n({region:e.project.region,defaultFrom:r}).send(t),!0}catch{return!1}}import{randomBytes as BS}from"node:crypto";import{chmodSync as FS,existsSync as jS,mkdirSync as US,readFileSync as zS,writeFileSync as VS}from"node:fs";import{dirname as qS}from"node:path";function x(e){let t=process.env.TS_CLOUD_AUTH_ENCRYPTION_KEY?.trim();if(t)return t;let r=A(e,"auth-encryption-key");try{if(jS(r)){let i=zS(r,"utf8").trim();if(i)return i}}catch{}let n=BS(32).toString("base64url");try{US(qS(r),{recursive:!0,mode:448}),VS(r,`${n}
34
34
  `,{mode:384}),FS(r,384)}catch{}return n}import{constants as GS,createHash as ou,createPublicKey as JS,createVerify as HS,timingSafeEqual as WS}from"node:crypto";var Pg=new Set(["RS256","PS256","ES256"]),Rg=60;function ec(e,t){let r=new URL(e),n=["127.0.0.1","::1","localhost"].includes(r.hostname);if(r.protocol!=="https:"&&!(r.protocol==="http:"&&n))throw Error(`${t} must use HTTPS`);if(r.username||r.password||r.hash)throw Error(`${t} contains unsupported URL components`);return r}function su(e,t){if(!e||typeof e!=="object"||Array.isArray(e))throw Error(`${t} is invalid`);return e}async function au(e,t){if(!e.ok)throw Error(`${t} failed with HTTP ${e.status}`);if(!(e.headers.get("content-type")??"").toLowerCase().includes("application/json"))throw Error(`${t} returned an unsupported content type`);if(Number(e.headers.get("content-length")??0)>1048576)throw Error(`${t} response is too large`);let i=await e.text();if(i.length>1048576)throw Error(`${t} response is too large`);try{return su(JSON.parse(i),t)}catch(o){if(o instanceof Error&&o.message===`${t} is invalid`)throw o;throw Error(`${t} returned invalid JSON`)}}function KS(e,t){let r=ou("sha256").update(e).digest(),n=ou("sha256").update(t).digest();return WS(r,n)}function xg(e){if(!e)return"/";let t=e.trim();if(!t.startsWith("/")||t.startsWith("//")||t.includes("\\")||/[\r\n]/.test(t))return"/";try{let r=new URL(t,"https://local.invalid");return r.origin==="https://local.invalid"?`${r.pathname}${r.search}${r.hash}`:"/"}catch{return"/"}}async function Pn(e,t=fetch){let r=ec(e.issuer,"OIDC issuer"),n=new URL(`${r.pathname.replace(/\/$/,"")}/.well-known/openid-configuration`,r.origin),i=await au(await t(n,{headers:{accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(1e4)}),"OIDC discovery");if(i.issuer!==e.issuer)throw Error("OIDC discovery issuer does not match the configured issuer");for(let s of["authorization_endpoint","token_endpoint","jwks_uri"]){if(typeof i[s]!=="string")throw Error(`OIDC discovery is missing ${s}`);ec(i[s],`OIDC ${s}`)}if(Array.isArray(i.response_types_supported)&&!i.response_types_supported.includes("code"))throw Error("OIDC provider does not support authorization code flow");if(Array.isArray(i.code_challenge_methods_supported)&&!i.code_challenge_methods_supported.includes("S256"))throw Error("OIDC provider does not support PKCE S256");let o=Array.isArray(i.id_token_signing_alg_values_supported)?i.id_token_signing_alg_values_supported.filter((s)=>typeof s==="string"):[];if(o.length>0&&!o.some((s)=>Pg.has(s)))throw Error("OIDC provider does not offer a supported ID-token signing algorithm");return i}async function cu(e,t,r,n,i=fetch){let o=e.getOidcProviderBySlug(t);if(!o?.enabled)throw Error("OIDC provider is unavailable");let s=ec(r,"Application origin").origin,c=await Pn(o,i),u=`${s}/auth/oidc/${encodeURIComponent(o.slug)}/callback`,a=e.beginOidcTransaction(o.id,u,xg(n)),f=new URL(c.authorization_endpoint);return f.searchParams.set("response_type","code"),f.searchParams.set("client_id",o.clientId),f.searchParams.set("redirect_uri",u),f.searchParams.set("scope",o.scopes.join(" ")),f.searchParams.set("state",a.state),f.searchParams.set("nonce",a.nonce),f.searchParams.set("code_challenge",ou("sha256").update(a.verifier).digest("base64url")),f.searchParams.set("code_challenge_method","S256"),{authorizationUrl:f.href,expiresAt:a.transaction.expiresAt}}function QS(e){if(e.length>32768)throw Error("OIDC ID token is too large");let t=e.split(".");if(t.length!==3||t.some((r)=>!r))throw Error("OIDC ID token is malformed");try{return{header:su(JSON.parse(Buffer.from(t[0],"base64url").toString("utf8")),"OIDC ID-token header"),claims:su(JSON.parse(Buffer.from(t[1],"base64url").toString("utf8")),"OIDC ID-token claims"),signingInput:`${t[0]}.${t[1]}`,signature:Buffer.from(t[2],"base64url")}}catch(r){if(r instanceof Error&&r.message.startsWith("OIDC"))throw r;throw Error("OIDC ID token is malformed")}}async function YS(e,t,r){let n=QS(e),i=typeof n.header.alg==="string"?n.header.alg:"",o=typeof n.header.kid==="string"?n.header.kid:"";if(!Pg.has(i)||!o)throw Error("OIDC ID token uses an unsupported signing key");if(t.id_token_signing_alg_values_supported&&!t.id_token_signing_alg_values_supported.includes(i))throw Error("OIDC ID-token algorithm was not advertised by the provider");let s=await au(await r(t.jwks_uri,{headers:{accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(1e4)}),"OIDC signing-key request");if(!Array.isArray(s.keys))throw Error("OIDC signing-key response is invalid");let c=s.keys.find((T)=>{if(!T||typeof T!=="object"||Array.isArray(T))return!1;let R=T;return R.kid===o&&(!R.alg||R.alg===i)&&(!R.use||R.use==="sig")});if(!c)throw Error("OIDC ID-token signing key was not found");let u=JS({key:c,format:"jwk"}),a=HS("SHA256").update(n.signingInput).end();if(!(i==="PS256"?a.verify({key:u,padding:GS.RSA_PKCS1_PSS_PADDING,saltLength:32},n.signature):i==="ES256"?a.verify({key:u,dsaEncoding:"ieee-p1363"},n.signature):a.verify(u,n.signature)))throw Error("OIDC ID-token signature is invalid");return n.claims}function XS(e,t,r,n){if(e.iss!==t.issuer)throw Error("OIDC ID-token issuer is invalid");let i=typeof e.aud==="string"?[e.aud]:Array.isArray(e.aud)?e.aud.filter((u)=>typeof u==="string"):[];if(!i.includes(t.clientId))throw Error("OIDC ID-token audience is invalid");if((i.length>1||e.azp!==void 0)&&e.azp!==t.clientId)throw Error("OIDC ID-token authorized party is invalid");let o=Math.floor(n.getTime()/1000);if(typeof e.exp!=="number"||e.exp<o-Rg)throw Error("OIDC ID token is expired");if(typeof e.iat!=="number"||e.iat>o+Rg)throw Error("OIDC ID-token issued-at time is invalid");if(typeof e.nonce!=="string"||!KS(e.nonce,r))throw Error("OIDC ID-token nonce is invalid");if(typeof e.sub!=="string"||!e.sub||e.sub.length>512)throw Error("OIDC ID-token subject is invalid");if(e.email_verified!==!0||typeof e.email!=="string")throw Error("OIDC provider did not return a verified email address");let s=e.email.trim().toLowerCase();if(s.length>254||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s))throw Error("OIDC provider returned an invalid email address");let c=s.split("@")[1];if(!c||!t.allowedDomains.includes(c))throw Error("OIDC email domain is not allowed for this organization");return{provider:t,subject:e.sub,email:s,name:typeof e.name==="string"?e.name.slice(0,120):void 0,claims:e}}async function du(e,t,r=fetch){let n=e.getOidcProviderBySlug(t.providerSlug);if(!n?.enabled)throw Error("OIDC provider is unavailable");if(!t.state||t.state.length>512||!t.code||t.code.length>4096)throw Error("OIDC callback is incomplete");let i=ec(t.origin,"Application origin").origin,o=e.consumeOidcTransaction(n.id,t.state),s=`${i}/auth/oidc/${encodeURIComponent(n.slug)}/callback`;if(o.transaction.redirectUri!==s)throw Error("OIDC callback redirect URI does not match the original request");let{clientSecret:c}=e.getOidcProviderCredentials(n.id),u=await Pn(n,r),a=new URLSearchParams({grant_type:"authorization_code",code:t.code,redirect_uri:o.transaction.redirectUri,code_verifier:o.verifier}),f={accept:"application/json","content-type":"application/x-www-form-urlencoded"},T=u.token_endpoint_auth_methods_supported??["client_secret_basic"];if(T.includes("client_secret_basic")){let W=(ee)=>new URLSearchParams({value:ee}).toString().slice(6),Y=`${W(n.clientId)}:${W(c)}`;f.authorization=`Basic ${Buffer.from(Y).toString("base64")}`}else if(T.includes("client_secret_post"))a.set("client_id",n.clientId),a.set("client_secret",c);else throw Error("OIDC provider does not support a configured client authentication method");let R=await au(await r(u.token_endpoint,{method:"POST",headers:f,body:a,redirect:"error",signal:AbortSignal.timeout(1e4)}),"OIDC token exchange");if(typeof R.id_token!=="string")throw Error("OIDC token response did not include an ID token");let D=await YS(R.id_token,u,r);return{identity:XS(D,n,o.nonce,t.now??new Date),returnPath:o.transaction.returnPath}}import{createHash as ZS,randomBytes as ev}from"node:crypto";var Og=new Set(ae),_g=7776000000,Ng=31536000000,Mg=86400000;function zi(e){return typeof e==="string"?e:void 0}function Dg(e){return ZS("sha256").update(e).digest("hex")}function tv(e){try{let t=JSON.parse(String(e));return Array.isArray(t)?t.filter((r)=>typeof r==="string"&&Og.has(r)):[]}catch{return[]}}function rv(e){let t=String(e.scope_type);return t==="organization"?{type:t}:{type:t,id:String(e.scope_id)}}function uu(e){let t=zi(e.disabled_at);return{id:String(e.id),organizationId:String(e.organization_id),actorId:String(e.actor_id),slug:String(e.slug),name:String(e.name),description:zi(e.description),createdByActorId:zi(e.created_by_actor_id),disabledAt:t,createdAt:String(e.created_at),updatedAt:String(e.updated_at),state:t?"disabled":"active"}}function lu(e,t){let r=zi(e.revoked_at),n=String(e.expires_at);return{id:String(e.id),serviceAccountId:String(e.service_account_id),name:String(e.name),prefix:String(e.token_prefix),capabilities:tv(e.capabilities),scope:rv(e),expiresAt:n,lastUsedAt:zi(e.last_used_at),lastNetworkHint:zi(e.last_network_hint),revokedAt:r,rotatedFromTokenId:zi(e.rotated_from_token_id),createdByActorId:zi(e.created_by_actor_id),createdAt:String(e.created_at),updatedAt:String(e.updated_at),state:r?"revoked":n<=t?"expired":"active"}}function nv(e){let t={};try{t=JSON.parse(String(e.response_body))}catch{}return{id:String(e.id),tokenId:String(e.token_id),key:String(e.idempotency_key),requestHash:String(e.request_hash),operationId:zi(e.operation_id),responseStatus:Number(e.response_status),responseBody:t,expiresAt:String(e.expires_at),createdAt:String(e.created_at)}}class ze{controlPlane;nowFn;idFn;constructor(e,t={}){this.controlPlane=e;this.nowFn=t.now??(()=>new Date),this.idFn=t.id??(()=>crypto.randomUUID())}now(){return this.nowFn().toISOString()}run(e,t){this.controlPlane.database.run(e,t)}createServiceAccount(e){if(!this.controlPlane.getOrganization(e.organizationId))throw Error("Service-account organization was not found");let t=e.slug.trim().toLowerCase();if(!/^[a-z0-9][a-z0-9-]{1,47}$/.test(t))throw Error("Service-account slug must be 2-48 lowercase letters, numbers or dashes");let r=e.name.trim().slice(0,100);if(!r)throw Error("Service-account name is required");let n=this.controlPlane.createActor({kind:"service_account",externalId:`service-account:${e.organizationId}:${t}`,displayName:r,metadata:{source:"api",serviceAccountSlug:t}}),i=this.idFn(),o=this.now();this.run(`INSERT INTO service_accounts (id, organization_id, actor_id, slug, name, description, created_by_actor_id, created_at, updated_at)
35
35
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i,e.organizationId,n.id,t,r,e.description?.trim().slice(0,500)||null,e.createdByActorId??null,o,o]);let s=this.controlPlane.createMembership({organizationId:e.organizationId,actorId:n.id,roleTemplate:e.roleTemplate,scope:e.scope,source:"manual",performedByActorId:e.createdByActorId}),c=e.scope??{type:"organization"};return this.controlPlane.appendEvent({organizationId:e.organizationId,actorId:e.createdByActorId,type:"api.service_account.created",payload:{serviceAccountId:i,roleTemplate:e.roleTemplate,scope:{type:c.type,id:c.id??null}}}),{serviceAccount:this.getServiceAccount(i),membership:s}}getServiceAccount(e){let t=this.controlPlane.database.query("SELECT * FROM service_accounts WHERE id = ?").get(e);return t?uu(t):void 0}getServiceAccountBySlug(e,t){let r=this.controlPlane.database.query("SELECT * FROM service_accounts WHERE organization_id = ? AND slug = ? COLLATE NOCASE").get(e,t.trim());return r?uu(r):void 0}listServiceAccounts(e,t={}){return this.controlPlane.database.query("SELECT * FROM service_accounts WHERE organization_id = ? ORDER BY name COLLATE NOCASE").all(e).map(uu).filter((r)=>t.includeDisabled||r.state==="active")}disableServiceAccount(e,t){let r=this.getServiceAccount(e);if(!r)throw Error("Service account was not found");let n=this.now();return this.controlPlane.transaction(()=>{this.run("UPDATE service_accounts SET disabled_at = ?, updated_at = ? WHERE id = ?",[n,n,e]),this.run("UPDATE api_tokens SET revoked_at = ?, updated_at = ? WHERE service_account_id = ? AND revoked_at IS NULL",[n,n,e]);let i=this.controlPlane.getMembershipForActor(r.organizationId,r.actorId);if(i?.status==="active")this.controlPlane.revokeMembership(i.id)}),this.controlPlane.appendEvent({organizationId:r.organizationId,actorId:t,type:"api.service_account.disabled",payload:{serviceAccountId:e}}),this.getServiceAccount(e)}createToken(e){let t=this.getServiceAccount(e.serviceAccountId);if(!t||t.state!=="active")throw Error("Service account is unavailable");let r=this.controlPlane.getMembershipForActor(t.organizationId,t.actorId);if(!r||r.status!=="active")throw Error("Service-account membership is unavailable");let n=[...new Set(e.capabilities)];if(n.length===0||n.some((R)=>!Og.has(R)))throw Error("API token requires valid explicit capabilities");let i=e.scope??r.scope,o=this.controlPlane.resolveAuthorizationTarget(t.organizationId,i);if(!o)throw Error("API token scope was not found in this organization");for(let R of n)if(!re({membership:r,grants:this.controlPlane.listGrants(r.id),capability:R,target:o}).allowed)throw Error(`Service-account membership does not grant ${R} at the token scope`);let s=e.expiresAt?new Date(e.expiresAt):new Date(this.nowFn().getTime()+_g);if(!Number.isFinite(s.getTime())||s.getTime()<=this.nowFn().getTime()+60000||s.getTime()>this.nowFn().getTime()+Ng)throw Error("API token expiry must be between one minute and one year from now");let c=this.idFn(),u=ev(32).toString("base64url"),a=`tsc_v1.${c}.${u}`,f=`tsc_v1.${c.slice(0,8)}`,T=this.now();return this.run(`INSERT INTO api_tokens (id, service_account_id, name, token_hash, token_prefix, capabilities, scope_type, scope_id,
36
36
  expires_at, rotated_from_token_id, created_by_actor_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[c,t.id,e.name.trim().slice(0,100)||"API token",Dg(a),f,JSON.stringify(n.sort()),i.type,i.type==="organization"?null:i.id??null,s.toISOString(),e.rotatedFromTokenId??null,e.createdByActorId??null,T,T]),this.controlPlane.appendEvent({organizationId:t.organizationId,actorId:e.createdByActorId,type:"api.token.created",payload:{serviceAccountId:t.id,tokenId:c,prefix:f,capabilities:n,scope:{type:i.type,id:i.id??null},expiresAt:s.toISOString(),rotatedFromTokenId:e.rotatedFromTokenId??null}}),{token:this.getToken(c),secret:a}}getToken(e){let t=this.controlPlane.database.query("SELECT * FROM api_tokens WHERE id = ?").get(e);return t?lu(t,this.now()):void 0}listTokens(e,t={}){return this.controlPlane.database.query("SELECT * FROM api_tokens WHERE service_account_id = ? ORDER BY created_at DESC").all(e).map((r)=>lu(r,this.now())).filter((r)=>t.includeInactive||r.state==="active")}verifyToken(e,t){let r=/^tsc_v1\.([^.]+)\.[A-Za-z0-9_-]{40,}$/.exec(e);if(!r)return;let n=this.controlPlane.database.query("SELECT * FROM api_tokens WHERE id = ? AND token_hash = ?").get(r[1],Dg(e));if(!n)return;let i=lu(n,this.now()),o=this.getServiceAccount(i.serviceAccountId);if(!o||o.state!=="active"||i.state!=="active")return;let s=this.controlPlane.getActor(o.actorId),c=this.controlPlane.getMembershipForActor(o.organizationId,o.actorId);if(!s||s.disabledAt||!c||c.status!=="active")return;let u=this.now(),a=!i.lastUsedAt||this.nowFn().getTime()-new Date(i.lastUsedAt).getTime()>=3600000;if(this.run("UPDATE api_tokens SET last_used_at = ?, last_network_hint = ?, updated_at = ? WHERE id = ?",[u,t?.slice(0,128)??null,u,i.id]),a)this.controlPlane.appendEvent({organizationId:o.organizationId,actorId:s.id,type:"api.token.used",payload:{serviceAccountId:o.id,tokenId:i.id,prefix:i.prefix}});return{serviceAccount:o,token:this.getToken(i.id),actor:s,membership:c}}rotateToken(e,t){let r=this.getToken(e);if(!r||r.state!=="active")throw Error("Active API token was not found");let n=this.createToken({serviceAccountId:r.serviceAccountId,name:`${r.name} (rotated)`,capabilities:r.capabilities,scope:r.scope,expiresAt:r.expiresAt,createdByActorId:t,rotatedFromTokenId:r.id}),i=this.getServiceAccount(r.serviceAccountId);return this.controlPlane.appendEvent({organizationId:i?.organizationId,actorId:t,type:"api.token.rotated",payload:{serviceAccountId:r.serviceAccountId,previousTokenId:r.id,tokenId:n.token.id}}),n}revokeToken(e,t){let r=this.getToken(e);if(!r)throw Error("API token was not found");if(r.state==="active"){let n=this.now();this.run("UPDATE api_tokens SET revoked_at = ?, updated_at = ? WHERE id = ?",[n,n,e]);let i=this.getServiceAccount(r.serviceAccountId);this.controlPlane.appendEvent({organizationId:i?.organizationId,actorId:t,type:"api.token.revoked",payload:{serviceAccountId:r.serviceAccountId,tokenId:e}})}return this.getToken(e)}getIdempotency(e,t){let r=this.controlPlane.database.query("SELECT * FROM api_idempotency_records WHERE token_id = ? AND idempotency_key = ? AND expires_at > ?").get(e,t,this.now());return r?nv(r):void 0}saveIdempotency(e){if(!/^[A-Za-z0-9._:-]{8,128}$/.test(e.key))throw Error("Idempotency-Key must contain 8-128 safe characters");let t=this.getIdempotency(e.tokenId,e.key);if(t){if(t.requestHash!==e.requestHash)throw Error("Idempotency-Key was already used for a different request");return t}let r=this.idFn(),n=this.now(),i=new Date(this.nowFn().getTime()+Mg).toISOString();return this.run(`INSERT INTO api_idempotency_records (id, token_id, idempotency_key, request_hash, operation_id, response_status, response_body, expires_at, created_at)
@@ -42,7 +42,7 @@ data: ${JSON.stringify(rt)}
42
42
  SELECT 1 FROM backup_jobs bj WHERE bj.recovery_point_id=rp.id
43
43
  AND bj.kind IN ('restore','drill') AND bj.status IN ('queued','running','cleanup_required')
44
44
  )
45
- ORDER BY rp.expires_at,rp.id`).all(e.toISOString(),e.toISOString()).map(mu),r=new Set;for(let n of new Set(t.map((i)=>i.projectId)))for(let i of this.listPolicies(n)){let o=this.listRecoveryPoints(i.projectId,i.id).filter((c)=>c.status==="available").sort((c,u)=>u.pointInTime.localeCompare(c.pointInTime));for(let c of o.slice(0,Math.max(0,i.retention.keepLast??0)))r.add(c.id);let s=[[i.retention.hourly,(c)=>c.toISOString().slice(0,13)],[i.retention.daily,(c)=>c.toISOString().slice(0,10)],[i.retention.weekly,(c)=>new Date(Date.UTC(c.getUTCFullYear(),c.getUTCMonth(),c.getUTCDate()-(c.getUTCDay()+6)%7)).toISOString().slice(0,10)],[i.retention.monthly,(c)=>c.toISOString().slice(0,7)]];for(let[c,u]of s){let a=new Set;for(let f of o){let T=u(new Date(f.pointInTime));if(a.has(T))continue;if(a.add(T),a.size<=Math.max(0,c??0))r.add(f.id)}}}return t.filter((n)=>!r.has(n.id))}coverage(e,t=this.now()){let r=new Map(this.listDestinations(e).map((n)=>[n.id,n]));return this.listPolicies(e).map((n)=>{let i=this.listRecoveryPoints(e,n.id).filter((c)=>c.status==="available"),o=i[0],s=o?(t.getTime()-new Date(o.pointInTime).getTime())/60000:Number.POSITIVE_INFINITY;return{policy:n,lastRecoveryPoint:o,missedRpo:n.enabled&&s>n.expectedRpoMinutes,unverified:i.filter((c)=>c.verificationState!=="verified").length,destinationHealthy:r.get(n.destinationId)?.status==="healthy"}})}}import{createCipheriv as gv,createDecipheriv as mv,createHash as Hg,randomBytes as Wg}from"node:crypto";var hu=Buffer.from("TSCB1"),oc=(e)=>`sha256:${Hg("sha256").update(e).digest("hex")}`;function Kg(e){return Hg("sha256").update(e).digest()}function fv(e,t,r){let n=r?Buffer.from(r):Wg(12);if(n.length!==12)throw Error("Backup encryption IV must contain 12 bytes.");let i=gv("aes-256-gcm",Kg(t),n),o=Buffer.concat([i.update(e),i.final()]),s=i.getAuthTag();return Buffer.concat([hu,n,s,o])}function hv(e,t){let r=Buffer.from(e);if(!r.subarray(0,hu.length).equals(hu))throw Error("Backup does not contain a valid encrypted envelope.");let n=r.subarray(5,17),i=r.subarray(17,33),o=r.subarray(33),s=mv("aes-256-gcm",Kg(t),n);return s.setAuthTag(i),Buffer.concat([s.update(o),s.final()])}function yv(e){let t;try{t=JSON.parse(e)}catch{throw Error("Backup destination credential must be a JSON object with accessKeyId and secretAccessKey.")}if(!t.accessKeyId||!t.secretAccessKey)throw Error("Backup destination credential requires accessKeyId and secretAccessKey.");if(t.expiresAt){let r=new Date(String(t.expiresAt));if(!Number.isFinite(r.getTime()))throw Error("Backup destination credential expiresAt must be an ISO timestamp.");if(r.getTime()<=Date.now())throw Error("Backup destination credential has expired.")}return{accessKeyId:String(t.accessKeyId),secretAccessKey:String(t.secretAccessKey),sessionToken:t.sessionToken?String(t.sessionToken):void 0}}async function Qg(e,t,r=new Date){if(!e.credentialRef)return{status:"default"};try{let n=JSON.parse(await t.resolve(e.credentialRef));if(!n.accessKeyId||!n.secretAccessKey)return{status:"invalid"};if(!n.expiresAt)return{status:"static"};let i=new Date(String(n.expiresAt));if(!Number.isFinite(i.getTime()))return{status:"invalid"};let o=i.getTime()-r.getTime();return{status:o<=0?"expired":o<=604800000?"expiring":"valid",expiresAt:i.toISOString()}}catch{return{status:"invalid"}}}class ii{secrets;clientFactory;multipartThreshold;partSize;constructor(e,t=(i,o)=>new g(i.region??"us-east-1",void 0,{endpoint:i.endpoint?new URL(i.endpoint).host:void 0,forcePathStyle:i.forcePathStyle,credentials:o}),r=8388608,n=8388608){this.secrets=e;this.clientFactory=t;this.multipartThreshold=r;this.partSize=n}async client(e){let t=e.credentialRef?yv(await this.secrets.resolve(e.credentialRef)):void 0;return this.clientFactory(e,t)}async test(e){if(!e.bucket)throw Error("S3 destination has no configured bucket.");let t=await this.client(e),r=`${e.prefix?`${e.prefix.replace(/\/$/,"")}/`:""}.ts-cloud-health/${crypto.randomUUID()}`;await t.putObject({bucket:e.bucket,key:r,body:"ts-cloud backup destination health check",contentType:"text/plain"});try{let n=await t.getObjectBytes(e.bucket,r);if(Buffer.from(n.body).toString()!=="ts-cloud backup destination health check")throw Error("Backup destination health object was corrupted.")}finally{await t.deleteObject(e.bucket,r)}}async upload(e,t){if(!e.bucket)throw Error("S3 destination has no configured bucket.");let r=await this.client(e),n=oc(t.body),i=e.encryption!=="provider"?await this.secrets.resolve(e.encryptionKeyRef):void 0,o=i?t.resume?.encryptionIv?Buffer.from(t.resume.encryptionIv,"base64url"):Wg(12):void 0,s=i?fv(t.body,i,o):Buffer.from(t.body),c=oc(s),u=`${e.prefix?`${e.prefix.replace(/\/$/,"")}/`:""}${t.key.replace(/^\/+/,"")}`,a=t.contentType??"application/octet-stream",f={"ts-cloud-format":"v1","ts-cloud-sha256":c.slice(7),"ts-cloud-encrypted":i?"true":"false"};if(t.resume&&t.resume.key!==u)throw Error("Multipart checkpoint does not match the requested backup key.");if(t.resume&&i&&!t.resume.encryptionIv)throw Error("Encrypted multipart checkpoint has no resumable envelope state.");if(t.resume&&i&&t.resume.plaintextChecksum!==n)throw Error("Encrypted multipart checkpoint does not match the backup payload.");if(s.length<this.multipartThreshold)await r.putObject({bucket:e.bucket,key:u,body:s,contentType:a,metadata:f});else{let T=t.resume?void 0:await r.createMultipartUpload(e.bucket,u,{contentType:a,metadata:f}),R=t.resume??{uploadId:T.UploadId,key:u,parts:[],bytesUploaded:0,encryptionIv:o?.toString("base64url"),plaintextChecksum:n},D=new Map(R.parts.map((Y)=>[Y.PartNumber,Y])),W=Math.ceil(s.length/this.partSize);for(let Y=0;Y<W;Y++){let ee=Y+1;if(!D.has(ee)){let ne=Y*this.partSize,he=await r.uploadPart(e.bucket,u,R.uploadId,ee,s.subarray(ne,Math.min(s.length,ne+this.partSize)));D.set(ee,{PartNumber:ee,ETag:he.ETag})}R.parts=[...D.values()].sort((ne,he)=>ne.PartNumber-he.PartNumber),R.bytesUploaded=Math.min(s.length,ee*this.partSize),t.checkpoint?.(R)}await r.completeMultipartUpload(e.bucket,u,R.uploadId,R.parts)}return{uri:`s3://${e.bucket}/${u}`,key:u,sizeBytes:s.length,checksum:c,manifest:{format:"ts-cloud-backup-v1",encrypted:!!i,plaintextChecksum:n,storageChecksum:c,contentType:a}}}async download(e,t){if(!e.bucket)throw Error("S3 destination has no configured bucket.");let r=await this.client(e),n=await r.getObjectBytes(e.bucket,t.key),i=Buffer.from(n.body);if(oc(i)!==t.checksum)throw Error("Backup checksum verification failed; object is corrupt.");let o=t.manifest.encrypted?hv(i,await this.secrets.resolve(e.encryptionKeyRef)):i;if(oc(o)!==t.manifest.plaintextChecksum)throw Error("Backup plaintext checksum verification failed.");return o}async abortPartial(e,t){if(!e.bucket)throw Error("S3 destination has no configured bucket.");await(await this.client(e)).abortMultipartUpload(e.bucket,t.key,t.uploadId)}async delete(e,t){if(!e.bucket)throw Error("S3 destination has no configured bucket.");await(await this.client(e)).deleteObject(e.bucket,t)}}import{createHash as bv}from"node:crypto";var Sv=(e)=>`sha256:${bv("sha256").update(e).digest("hex")}`;class Jr{store;queue;now;constructor(e,t,r=()=>new Date){this.store=e;this.queue=t;this.now=r}enqueueBackup(e,t=this.now().toISOString(),r){if(!e.enabled)throw Error("Backup policy is disabled.");let n=this.store.createJob({projectId:e.projectId,policyId:e.id,kind:"backup",status:"queued",idempotencyKey:`backup:${e.id}:${t}`,target:{scheduledFor:t},cancellability:"checkpoint_only",progress:{phase:"queued"}});if(!n.operationId){let i=this.queue.enqueue({projectId:e.projectId,environmentId:e.environmentId,resourceId:e.resourceId,actorId:r,kind:"backup.run",input:{backupJobId:n.id},lockKey:e.dataServiceId?`data-service:${e.dataServiceId}`:e.resourceId?`resource:${e.resourceId}`:`backup-policy:${e.id}`,providerKey:"backup",maxAttempts:3,timeoutSeconds:14400,retryClasses:["provider_transient"],resumePolicy:"requeue"});return this.store.updateJob(n.id,{operationId:i.operation.id})}return n}enqueueDue(e=this.now()){return this.store.duePolicies(e).map((t)=>{let r=t.nextRunAt;return this.store.advancePolicy(t.id,r),this.enqueueBackup(t,r)})}enqueueVerification(e){let t=this.store.createJob({projectId:e.projectId,policyId:e.policyId,recoveryPointId:e.id,kind:"verify",status:"queued",idempotencyKey:`verify:${e.id}:${e.checksum}`,target:{},cancellability:"safe",progress:{phase:"queued"}});if(!t.operationId){let r=this.queue.enqueue({projectId:e.projectId,resourceId:e.resourceId,kind:"backup.verify",input:{backupJobId:t.id},lockKey:`recovery-point:${e.id}`,providerKey:"backup",maxAttempts:2,timeoutSeconds:7200,retryClasses:["provider_transient"],resumePolicy:"requeue"});return this.store.updateJob(t.id,{operationId:r.operation.id})}return t}planRestore(e,t){if(e.status!=="available")throw Error("Only available recovery points can be restored.");if(e.verificationState!=="verified")throw Error("Restore requires a verified recovery point.");if(t.mode==="in_place"){if(!t.recentAuth)throw Error("In-place restore requires recent authentication.");if(t.confirm!==t.targetName)throw Error(`Type ${t.targetName} to confirm in-place restore.`);if(!t.downtimeAcknowledged)throw Error("In-place restore requires downtime acknowledgement.");let r=t.safetyBackupId?this.store.getRecoveryPoint(t.safetyBackupId):void 0;if(!r||r.id===e.id||r.status!=="available"||r.verificationState!=="verified"||r.resourceId!==e.resourceId||r.dataServiceId!==e.dataServiceId)throw Error("In-place restore requires a distinct verified safety backup for the same target.")}return{point:e,mode:t.mode,target:{...t.target,inPlace:t.mode==="in_place",restoreMode:t.mode},warnings:t.mode==="in_place"?["The target is locked against deployments and backup work.","Downtime and data replacement are expected.","Provider cancellation may stop only at a checkpoint."]:["An isolated target is created and health-validated before cleanup."]}}enqueueRestore(e,t){let r=this.planRestore(e,t),n=t.drill?"drill":"restore",i=Sv(JSON.stringify({point:e.id,mode:t.mode,target:t.target,safety:t.safetyBackupId,drill:!!t.drill})),o=this.store.createJob({projectId:e.projectId,policyId:e.policyId,recoveryPointId:e.id,kind:n,status:"queued",idempotencyKey:`${n}:${i}`,target:r.target,restoreMode:r.mode,cancellability:"checkpoint_only",safetyBackupId:t.safetyBackupId,progress:{phase:"queued",warnings:r.warnings}});if(!o.operationId){let s=this.queue.enqueue({projectId:e.projectId,resourceId:e.resourceId,actorId:t.actorId,kind:t.drill?"backup.drill":"backup.restore",input:{backupJobId:o.id},lockKey:e.dataServiceId?`data-service:${e.dataServiceId}`:e.resourceId?`resource:${e.resourceId}`:`recovery-point:${e.id}`,providerKey:"backup",maxAttempts:1,timeoutSeconds:14400,retryClasses:[],resumePolicy:"fail"});return this.store.updateJob(o.id,{operationId:s.operation.id})}return o}enqueueRetention(e=this.now()){return this.store.retentionCandidates(e).map((t)=>{let r=this.store.createJob({projectId:t.projectId,policyId:t.policyId,recoveryPointId:t.id,kind:"cleanup",status:"queued",idempotencyKey:`cleanup:${t.id}:${t.expiresAt}`,target:{},cancellability:"safe",progress:{phase:"queued"}});if(!r.operationId){let n=this.queue.enqueue({projectId:t.projectId,resourceId:t.resourceId,kind:"backup.cleanup",input:{backupJobId:r.id},lockKey:`recovery-point:${t.id}`,providerKey:"backup",maxAttempts:3,timeoutSeconds:7200,retryClasses:["provider_transient"],resumePolicy:"requeue"});return this.store.updateJob(r.id,{operationId:n.operation.id})}return r})}}function Yg(e){let t=e.now??(()=>new Date),r=new Jr(e.store,e.queue,t),n=(c)=>{let u=c.recoveryPointId?e.store.getRecoveryPoint(c.recoveryPointId):void 0,a=c.policyId?e.store.getPolicy(c.policyId):u?.policyId?e.store.getPolicy(u.policyId):void 0;if(!a)throw Error("Backup policy was not found.");let f=e.store.getDestination(u?.destinationId??a.destinationId),T=e.resolveSource(a);if(!f)throw Error("Backup destination was not found.");if(!T)throw Error(`No ${a.resourceKind} backup adapter is configured.`);return{point:u,policy:a,destination:f,source:T}},i=(c)=>{let u=c.operation.input,a=e.store.getJob(String(u.backupJobId??""));if(!a)throw Error("Backup job was not found.");return e.store.updateJob(a.id,{status:"running",startedAt:a.startedAt??t().toISOString(),progress:{...a.progress,phase:"running"}}),a},o=(c,u)=>{let a=e.store.getJob(c.id)??c;e.store.updateJob(c.id,{status:"failed",finishedAt:t().toISOString(),error:u instanceof Error?u.message:String(u),progress:{...a.progress,phase:"failed"}})};return{"backup.run":async(c)=>{let u=i(c);try{let{policy:a,destination:f,source:T}=n(u),R=await T.create(a,c),D=e.resolveDestination(f),W=R.mode==="object"?await(async()=>{if(!D)throw Error("Backup destination adapter is not configured.");let he=e.store.getJob(u.id)?.progress,te=he?.multipart,De=te&&typeof te==="object"&&!Array.isArray(te)&&typeof te.uploadId==="string"&&typeof te.key==="string"&&Array.isArray(te.parts)?te:void 0;return D.upload(f,{key:R.key,body:R.body,contentType:R.contentType,resume:De,checkpoint:(tt)=>{c.checkpoint("uploading",`Uploaded ${Number(tt.bytesUploaded??0)} backup bytes.`),e.store.updateJob(u.id,{progress:{phase:"uploading",multipart:{...tt}}})}})})():{uri:R.uri,key:R.uri,sizeBytes:R.sizeBytes,checksum:R.checksum,manifest:{format:"ts-cloud-backup-v1",encrypted:!1,plaintextChecksum:R.checksum,storageChecksum:R.checksum,contentType:"application/provider-snapshot"}},Y=a.retention.expireAfterDays?new Date(t().getTime()+a.retention.expireAfterDays*86400000).toISOString():void 0,ee=e.store.getJob(u.id)?.startedAt,ne=e.store.createRecoveryPoint({projectId:a.projectId,policyId:a.id,destinationId:f.id,resourceId:a.resourceId,dataServiceId:a.dataServiceId,backupJobId:u.id,kind:a.resourceKind,pointInTime:t().toISOString(),uri:W.uri,sizeBytes:W.sizeBytes,checksum:W.checksum,manifest:{...R.manifest,...W.manifest,storageKey:W.key},toolVersion:R.toolVersion,engineVersion:R.engineVersion,expiresAt:Y,lockedUntil:f.immutability.defaultRetentionDays?new Date(t().getTime()+f.immutability.defaultRetentionDays*86400000).toISOString():void 0,held:!1,pinned:!1,status:"available",verificationState:"unverified",durationMs:Math.max(0,t().getTime()-new Date(ee??t().toISOString()).getTime())});if(R.mode==="external"&&f.provider==="aws_backup")e.store.recordDestinationTest(f.id,{ok:!0});return e.store.updateJob(u.id,{status:"succeeded",recoveryPointId:ne.id,finishedAt:t().toISOString(),progress:{phase:"stored",recoveryPointId:ne.id}}),r.enqueueVerification(ne),{backupJobId:u.id,recoveryPointId:ne.id}}catch(a){let f=e.store.getJob(u.id),T=f?.progress.multipart,R=(()=>{try{return n(u)}catch{return}})();if(R?.destination.provider==="aws_backup")e.store.recordDestinationTest(R.destination.id,{ok:!1,error:a instanceof Error?a.message:String(a)});let D=!1;if(T&&typeof T==="object"&&!Array.isArray(T)&&R){let W=e.resolveDestination(R.destination);if(D=!0,W?.abortPartial)try{await W.abortPartial(R.destination,T),D=!1,e.store.updateJob(u.id,{progress:{...f.progress,partialCleanup:"aborted"}})}catch{e.store.updateJob(u.id,{progress:{...f.progress,partialCleanup:"required"}})}}if(D)e.store.updateJob(u.id,{status:"cleanup_required",finishedAt:t().toISOString(),error:a instanceof Error?a.message:String(a),progress:{...e.store.getJob(u.id)?.progress??{},phase:"cleanup_required"}});else o(u,a);throw a}},"backup.verify":async(c)=>{let u=i(c);try{let{point:a,destination:f,source:T}=n(u);if(!a)throw Error("Recovery point was not found.");e.store.updateRecoveryPoint(a.id,{verificationState:"verifying"});let R;if(a.uri.startsWith("s3:")){let D=e.resolveDestination(f);if(!D)throw Error("Backup destination adapter is not configured.");let W=await D.download(f,{key:String(a.manifest.storageKey??""),checksum:a.checksum,manifest:a.manifest}),Y=T.verify?await T.verify(a,W,c):{};R={bytes:W.length,checksum:a.checksum,...Y}}else if(T.verifyExternal)R=await T.verifyExternal(a,c);else throw Error("External recovery point verification is not supported.");return e.store.updateRecoveryPoint(a.id,{verificationState:"verified",verifiedAt:t().toISOString(),manifest:{...a.manifest,verification:R}}),e.store.updateJob(u.id,{status:"succeeded",finishedAt:t().toISOString(),progress:{phase:"verified",evidence:R}}),{backupJobId:u.id,recoveryPointId:a.id,evidence:R}}catch(a){if(u.recoveryPointId)e.store.updateRecoveryPoint(u.recoveryPointId,{verificationState:/checksum|corrupt|authentic/i.test(a instanceof Error?a.message:String(a))?"corrupt":"failed"});throw o(u,a),a}},"backup.restore":async(c)=>s(c,!1),"backup.drill":async(c)=>s(c,!0),"backup.cleanup":async(c)=>{let u=i(c);try{let{point:a,destination:f,source:T}=n(u);if(!a)throw Error("Recovery point was not found.");if(!e.store.retentionCandidates(t()).some((R)=>R.id===a.id))throw Error("Recovery point is held, pinned, locked, or in active use.");if(e.store.updateRecoveryPoint(a.id,{status:"deleting"}),a.uri.startsWith("s3:")){let R=e.resolveDestination(f);if(!R)throw Error("Destination cleanup is unavailable.");await R.delete(f,String(a.manifest.storageKey??""))}else if(T.deleteExternal)await T.deleteExternal(a,c);else throw Error("External recovery point cleanup is unavailable.");return e.store.updateRecoveryPoint(a.id,{status:"deleted"}),e.store.updateJob(u.id,{status:"succeeded",finishedAt:t().toISOString(),progress:{phase:"deleted"}}),{backupJobId:u.id,recoveryPointId:a.id,deleted:!0}}catch(a){throw o(u,a),a}}};async function s(c,u){let a=i(c);try{let{point:f,policy:T,destination:R,source:D}=n(a);if(!f)throw Error("Recovery point was not found.");if(u&&!D.cleanup)throw Error("This backup source cannot safely clean a recovery drill target.");let W=f.uri.startsWith("s3:")?e.resolveDestination(R):void 0,Y=W?await W.download(R,{key:String(f.manifest.storageKey??""),checksum:f.checksum,manifest:f.manifest}):void 0,ee=await D.restore(f,Y,a.target,c),ne=D.validateHealth?await D.validateHealth({...a.target,...ee},c):{healthy:!0,mode:"adapter"},he=e.validateHealth?await e.validateHealth(T,a.target):{healthy:!0,mode:"not_configured"},te={...ne,healthy:ne.healthy===!0&&he.healthy===!0,configured:he};if(te.healthy!==!0)throw Error("Restored target did not pass its configured health check.");if(u&&D.cleanup)await D.cleanup({...a.target,provider:f.manifest.provider??null},c);return e.store.updateJob(a.id,{status:"succeeded",finishedAt:t().toISOString(),healthResult:te,progress:{phase:u?"drill_cleaned":"restored",restored:ee}}),{backupJobId:a.id,recoveryPointId:f.id,restored:ee,health:te,cleaned:u}}catch(f){let T=(()=>{try{return n(a)}catch{return}})(),R=f instanceof Error?f.message:String(f),D=!1;if(u&&T?.source.cleanup)try{await T.source.cleanup({...a.target,provider:T.point?.manifest.provider??null},c)}catch{D=!0}if(D)e.store.updateJob(a.id,{status:"cleanup_required",finishedAt:t().toISOString(),error:R,progress:{...a.progress,phase:"cleanup_required"}});else o(a,f);throw f}}}import{createHash as vv}from"node:crypto";var wv=(e)=>`sha256:${vv("sha256").update(e).digest("hex")}`;class yu{dataServices;client;constructor(e,t=new me){this.dataServices=e;this.client=t}service(e){let t=e.dataServiceId?this.dataServices.get(e.dataServiceId):void 0;if(!t||!["aws_rds","aws_aurora"].includes(t.provider))throw Error("Managed database backup policy requires an RDS or Aurora data service.");return t}async waitForSnapshot(e,t,r){for(;;){r.throwIfCancellationRequested?.(),r.heartbeat?.();let n=e==="aws_aurora"?(await this.client.describeDBClusterSnapshots({DBClusterSnapshotIdentifier:t})).DBClusterSnapshots[0]:(await this.client.describeDBSnapshots({DBSnapshotIdentifier:t})).DBSnapshots?.[0];if(!n)throw Error("Provider snapshot was not found.");let i=n,o=String(i.Status??i.DBSnapshotStatus??"unknown");if(r.checkpoint?.("provider_snapshot",`Database snapshot ${t} is ${o}.`),o==="available")return i;if(["deleted","deleting","failed"].includes(o))throw Error(`Provider snapshot ${t} failed with state ${o}.`);await Bun.sleep(5000)}}async create(e,t){let r=this.service(e),n=String(t.operation?.id??new Date().toISOString()).replace(/[^A-Za-z0-9]/g,"").slice(0,20),i=`${r.placement.slice(0,42).replace(/-+$/,"")}-${n}`;if(r.provider==="aws_aurora")await this.client.createDBClusterSnapshot(r.placement,i);else await this.client.createDBSnapshot({DBInstanceIdentifier:r.placement,DBSnapshotIdentifier:i});await this.waitForSnapshot(r.provider,i,t);let o=`${r.provider}:${r.placement}:${i}`;return{mode:"external",uri:`aws-backup:${o}`,checksum:wv(o),sizeBytes:0,manifest:{provider:r.provider,sourceId:r.placement,snapshotId:i,plan:r.plan,engine:r.engine},engineVersion:r.engineVersion,toolVersion:"aws-rds-api-2014-10-31"}}async verifyExternal(e,t){let r=String(e.manifest.snapshotId??""),n=String(e.manifest.provider??"");if(!r)throw Error("Snapshot recovery point has no snapshot ID.");let i=await this.waitForSnapshot(n,r,t),o=String(i.Status??i.DBSnapshotStatus??"unknown");return{snapshotId:r,status:o,encrypted:i.Encrypted??i.StorageEncrypted??!0}}async restore(e,t,r,n){let i=String(r.targetId??""),o=String(e.manifest.snapshotId??""),s=String(e.manifest.provider??"");if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(i))throw Error("Managed restore requires a valid distinct targetId.");if(i===e.manifest.sourceId)throw Error("Managed restore target must differ from its source.");if(s==="aws_aurora"){let c=e.manifest.engine==="postgres"?"aurora-postgresql":"aurora-mysql";await this.client.restoreDBClusterFromSnapshot({DBClusterIdentifier:i,SnapshotIdentifier:o,Engine:c,EngineVersion:e.engineVersion,DeletionProtection:!0,ServerlessV2ScalingConfiguration:{MinCapacity:Number(r.minCapacity)||0.5,MaxCapacity:Number(r.maxCapacity)||4}}),await this.client.createDBInstance({DBInstanceIdentifier:`${i}-writer-1`,DBClusterIdentifier:i,DBInstanceClass:String(r.plan??e.manifest.plan??"db.serverless"),Engine:c,PubliclyAccessible:!1})}else await this.client.restoreDBInstanceFromDBSnapshot({DBInstanceIdentifier:i,DBSnapshotIdentifier:o,DBInstanceClass:String(r.plan??e.manifest.plan??""),PubliclyAccessible:!1,DeletionProtection:!0,Tags:[{Key:"managed-by",Value:"ts-cloud-restore"}]});return{targetId:i,provider:s,status:"creating",isolated:!0}}async validateHealth(e,t){let r=String(e.targetId??""),n=String(e.provider??"");for(;;){t.throwIfCancellationRequested?.(),t.heartbeat?.();let i=n==="aws_aurora"?(await this.client.describeDBClusters({DBClusterIdentifier:r})).DBClusters?.[0]:(await this.client.describeDBInstances({DBInstanceIdentifier:r})).DBInstances?.[0];if(!i)throw Error("Restored managed database was not found.");let o=String(i.Status??i.DBInstanceStatus??"unknown");if(t.checkpoint?.("provider_restore",`Restored database ${r} is ${o}.`),o==="available")return{healthy:!0,targetId:r,provider:n,status:o};if(["deleted","deleting","failed","incompatible-restore"].includes(o))throw Error(`Restored managed database ${r} failed with state ${o}.`);await Bun.sleep(5000)}}async cleanup(e,t){let r=String(e.targetId??""),n=String(e.provider??"");if(!r)throw Error("Restore cleanup target is required.");if(n==="aws_aurora")await this.client.deleteDBInstance({DBInstanceIdentifier:`${r}-writer-1`,SkipFinalSnapshot:!0}),await this.client.modifyDBCluster({DBClusterIdentifier:r,DeletionProtection:!1,ApplyImmediately:!0}),await this.client.deleteDBCluster(r);else await this.client.modifyDBInstance({DBInstanceIdentifier:r,DeletionProtection:!1,ApplyImmediately:!0}),await this.client.deleteDBInstance({DBInstanceIdentifier:r,SkipFinalSnapshot:!0,DeleteAutomatedBackups:!0})}async deleteExternal(e,t){let r=String(e.manifest.snapshotId??"");if(e.manifest.provider==="aws_aurora")await this.client.deleteDBClusterSnapshot(r);else await this.client.deleteDBSnapshot(r)}}var Br=(e,t="none",r=!1)=>({supported:!0,downtime:t,destructive:r,explanation:e}),Cr=(e)=>({supported:!1,downtime:"none",destructive:!1,explanation:e});function Zt(e,t){let r=["aws_rds","aws_aurora","aws_elasticache"].includes(t),n=["server","container"].includes(t),i=["postgres","mysql","mariadb"].includes(e),o=e==="redis",s={};return s.create=t==="external"?Cr("External services can be adopted as read-only inventory."):Br(r?"Provision through the provider API.":"Provision through the owning runtime driver.","possible"),s.observe=t==="external"?Cr("External observation requires a configured provider adapter."):Br("Provider/runtime health and endpoint metadata are observable."),s.connect=Br("Connection guidance uses secret references and never returns a password by default."),s.backup=i&&(r||n)?Br(r?"Create a provider snapshot.":"Create a consistent engine-native dump.","possible"):Cr("This cache path is not a durable backup source."),s.restore=r&&i?Br("Restore creates a reviewed provider target.","required",!0):Cr("Restore requires a configured provider restore runner."),s.restart=t==="external"?Cr("External restart requires a configured provider adapter."):Br(r?"Provider restart/failover semantics apply.":"Restart the owning service unit.","required"),s.resize=t==="aws_elasticache"?Cr("ElastiCache resizing requires a replication-group migration runner."):r?Br("Provider plan/storage modification may enter a maintenance window.","possible"):n?Br("Edit host/container resources and reconcile.","required"):Cr("External resize requires a configured provider adapter."),s.version=n?Cr("Runtime version upgrades require an explicit image migration runner."):r&&t!=="aws_elasticache"?Br(i?"Major versions require compatibility preflight and backup.":"Engine upgrades require a maintenance window.","required"):Cr("External upgrades require a configured provider adapter."),s.rotate=t==="aws_elasticache"||t==="external"||n&&!i&&!o?Cr("Credential rotation is not available for this provider/engine path."):Br("Rotate through the secret backend, update the engine, then flag dependent releases."),s.expose=n?Cr("Direct container publishing is refused; use a reviewed firewall and proxy policy."):t==="aws_rds"?Br("Exposure is reconciled through security groups; public access defaults off."):Cr("Exposure changes require a provider-specific network runner."),s.delete=t==="external"?Cr("External deletion requires a configured provider adapter."):Br(r?"Final snapshot is supported where the provider allows it.":"A final engine backup is required unless explicitly retained.","required",!0),s.logs=n?Br("Read bounded service logs from the runtime."):Cr("Provider log export is not configured for this adapter."),s.slow_queries=n&&i?Br("Read bounded runtime logs after engine slow-query logging is enabled."):Cr("A slow-query log runner is not configured for this provider."),s.users=n&&i?Br("Logical users can be listed; creation requires a referenced secondary credential."):Cr("User management requires an engine connection runner."),s.databases=n&&i?Br("Logical databases can be listed, created, and confirmation-gated for deletion."):Cr("Logical database management requires an engine connection runner."),{actions:s,endpointTypes:r?["internal","external","tunnel"]:["internal","tunnel"],metrics:o?["connections","memory","evictions","hit_rate","latency"]:["connections","cpu","storage","read_latency","write_latency","iops"]}}var As=(e)=>e==null?void 0:String(e),dc=(e)=>Number(e)===1,sc=(e)=>{try{return JSON.parse(String(e))}catch{return{}}};function Xg(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:As(e.environment_id),resourceId:As(e.resource_id),name:String(e.name),engine:String(e.engine),provider:String(e.provider),placement:String(e.placement),engineVersion:As(e.engine_version),plan:String(e.plan),storageGb:e.storage_gb==null?void 0:Number(e.storage_gb),highAvailability:dc(e.high_availability),publicExposure:dc(e.public_exposure),allowedCidrs:sc(e.allowed_cidrs),desiredState:sc(e.desired_state),observedState:sc(e.observed_state),capabilities:sc(e.capabilities),credentialRef:As(e.credential_ref),status:String(e.status),origin:String(e.origin),managementEnabled:dc(e.management_enabled),ownerActorId:As(e.owner_actor_id),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}class er{controlPlane;now;constructor(e,t=()=>new Date){this.controlPlane=e;this.now=t}create(e){if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(e.name))throw Error("Data service names must be 2-63 lowercase letters, numbers, or dashes.");if(e.publicExposure&&(!e.allowedCidrs.length||e.allowedCidrs.includes("0.0.0.0/0")))throw Error("Public exposure requires explicit narrow CIDRs; 0.0.0.0/0 is refused.");let t=crypto.randomUUID(),r=this.now().toISOString(),n=Zt(e.engine,e.provider);return this.controlPlane.database.run("INSERT INTO data_services (id,organization_id,project_id,environment_id,resource_id,name,engine,provider,placement,engine_version,plan,storage_gb,high_availability,public_exposure,allowed_cidrs,desired_state,observed_state,capabilities,credential_ref,status,origin,management_enabled,owner_actor_id,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.organizationId,e.projectId,e.environmentId??null,e.resourceId??null,e.name,e.engine,e.provider,e.placement,e.engineVersion??null,e.plan,e.storageGb??null,e.highAvailability?1:0,e.publicExposure?1:0,JSON.stringify(e.allowedCidrs),JSON.stringify(e.desiredState),JSON.stringify(e.observedState),JSON.stringify(n),e.credentialRef??null,e.status,e.origin,e.managementEnabled?1:0,e.ownerActorId??null,1,r,r]),this.get(t)}get(e){let t=this.controlPlane.database.query("SELECT * FROM data_services WHERE id=?").get(e);return t?Xg(t):void 0}list(e,t){return this.controlPlane.database.query(`SELECT * FROM data_services WHERE project_id=?${t?" AND environment_id=?":""} ORDER BY name`).all(e,...t?[t]:[]).map(Xg)}update(e,t,r){let n=this.get(e);if(!n)throw Error("Data service was not found.");if(n.version!==t)throw Error("Data service changed; refresh before retrying.");let i={...n,...r};if(i.publicExposure&&(!i.allowedCidrs.length||i.allowedCidrs.includes("0.0.0.0/0")))throw Error("Public exposure requires explicit narrow CIDRs; 0.0.0.0/0 is refused.");if(this.controlPlane.database.run("UPDATE data_services SET plan=?,storage_gb=?,engine_version=?,high_availability=?,public_exposure=?,allowed_cidrs=?,desired_state=?,observed_state=?,status=?,management_enabled=?,credential_ref=?,version=version+1,updated_at=? WHERE id=? AND version=?",[i.plan,i.storageGb??null,i.engineVersion??null,i.highAvailability?1:0,i.publicExposure?1:0,JSON.stringify(i.allowedCidrs),JSON.stringify(i.desiredState),JSON.stringify(i.observedState),i.status,i.managementEnabled?1:0,i.credentialRef??null,this.now().toISOString(),e,t]).changes!==1)throw Error("Data service changed; refresh before retrying.");return this.get(e)}credential(e){let t=this.controlPlane.database.query("SELECT * FROM data_service_credentials WHERE service_id=? ORDER BY version DESC LIMIT 1").get(e);return t?{id:String(t.id),serviceId:String(t.service_id),username:String(t.username),secretRef:String(t.secret_ref),version:Number(t.version),createdAt:String(t.created_at),rotatedAt:As(t.rotated_at)}:void 0}saveCredential(e,t,r){let n=this.credential(e),i=n?.id??crypto.randomUUID(),o=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO data_service_credentials (id,service_id,username,secret_ref,version,created_at,rotated_at) VALUES (?,?,?,?,?,?,?) ON CONFLICT(service_id,username) DO UPDATE SET secret_ref=excluded.secret_ref,version=data_service_credentials.version+1,rotated_at=excluded.rotated_at",[i,e,t,r,n?.version??1,n?.createdAt??o,n?o:null]),this.credential(e)}addDependency(e){let t=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO data_service_dependencies (service_id,resource_id,secret_ref,requires_redeploy,created_at) VALUES (?,?,?,?,?) ON CONFLICT(service_id,resource_id) DO UPDATE SET secret_ref=excluded.secret_ref,requires_redeploy=excluded.requires_redeploy",[e.serviceId,e.resourceId,e.secretRef,e.requiresRedeploy?1:0,t]),{...e,createdAt:t}}dependencies(e){return this.controlPlane.database.query("SELECT * FROM data_service_dependencies WHERE service_id=? ORDER BY resource_id").all(e).map((t)=>({serviceId:String(t.service_id),resourceId:String(t.resource_id),secretRef:String(t.secret_ref),requiresRedeploy:dc(t.requires_redeploy),createdAt:String(t.created_at)}))}removeDependency(e,t){return this.controlPlane.database.run("DELETE FROM data_service_dependencies WHERE service_id=? AND resource_id=?",[e,t]).changes===1}remove(e){this.controlPlane.database.run("DELETE FROM data_services WHERE id=?",[e])}}function Zg(){let t=crypto.getRandomValues(new Uint8Array(40));return Array.from(t,(r)=>"ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@#$%^&*_-+="[r%69]).join("")}function Bn(e,t){return t.map((r)=>{let n=r.type==="tunnel"?"127.0.0.1":r.host,i=e.engine==="redis"?`redis-cli -h ${n} -p ${r.port}${r.tls?" --tls":""}`:e.engine==="postgres"?`psql "host=${n} port=${r.port} dbname=${r.database??"postgres"} sslmode=${r.tls?"require":"disable"}"`:e.engine==="mongodb"?`mongosh "mongodb://${n}:${r.port}/${r.database??"admin"}${r.tls?"?tls=true":""}"`:e.engine==="libsql"?`turso db shell ${r.tls?"https":"http"}://${n}:${r.port}`:`mysql --host=${n} --port=${r.port} --database=${r.database??"mysql"} --ssl-mode=${r.tls?"REQUIRED":"DISABLED"}`;return{type:r.type,command:i,secretRef:e.credentialRef}})}class jr{store;queue;secrets;constructor(e,t,r){this.store=e;this.queue=t;this.secrets=r}async create(e){let t,r;if(e.provider!=="aws_elasticache"){let n=e.username??"app",i=Zg();r=`secret://data-services/${e.projectId}/${e.name}/${n}`,await this.secrets.put(r,i),t={username:n,password:i,secretRef:r}}try{let n=this.store.create({...e,credentialRef:r,status:"planning"});if(t)this.store.saveCredential(n.id,t.username,t.secretRef);let i=this.enqueue(n,"create",{});return{service:n,credential:t,operationId:i}}catch(n){if(r)await this.secrets.remove(r);throw n}}plan(e,t,r={}){let n=e.capabilities.actions[t],i=t==="version"&&String(r.engineVersion??"").split(".")[0]!==String(e.engineVersion??"").split(".")[0];return{service:e,action:t,capability:n,changes:r,preflight:{backupRequired:["delete","restore"].includes(t)||i,compatibilityRequired:i,typedConfirmation:n.destructive?e.name:void 0,retentionChoiceRequired:t==="delete"},warnings:[...n.downtime!=="none"?[`Downtime is ${n.downtime}.`]:[],...e.origin==="adopted"&&!e.managementEnabled?["Adopted resource is read-only until management is explicitly enabled."]:[]]}}enqueue(e,t,r,n){let i=this.plan(e,t,r);if(!i.capability.supported)throw Error(i.capability.explanation);if(e.origin==="adopted"&&!e.managementEnabled&&t!=="observe")throw Error("Adopted resources remain read-only until management is explicitly enabled.");if(i.preflight.typedConfirmation&&r.confirm!==i.preflight.typedConfirmation)throw Error(`Type ${i.preflight.typedConfirmation} to confirm ${t}.`);if(i.preflight.retentionChoiceRequired&&!["final_backup","retain"].includes(String(r.retention??"")))throw Error("Deletion requires retention final_backup or retain.");if(i.preflight.compatibilityRequired&&(r.compatibilityReviewed!==!0||!r.backupId))throw Error("Major version changes require compatibilityReviewed=true and a backupId.");if(t==="restore"){let o=String(r.backupId??""),s=String(r.targetId??"");if(!o||!s)throw Error("Restore requires both backupId and targetId.");if(s===e.placement)throw Error("Restore targetId must differ from the source placement.");if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(s))throw Error("Restore targetId must be 2-63 lowercase letters, numbers, or dashes.")}return this.queue.enqueue({projectId:e.projectId,environmentId:e.environmentId,resourceId:e.resourceId,actorId:n,kind:"data_service.action",input:{serviceId:e.id,action:t,...r},lockKey:`data-service:${e.id}`,providerKey:e.provider,maxAttempts:3,timeoutSeconds:7200,retryClasses:["provider_transient"],resumePolicy:"requeue"}).operation.id}async rotate(e,t,r){let n=this.store.credential(e.id);if(!n)throw Error("Data service credential metadata was not found.");let i=Zg(),o=`${n.secretRef}/v${n.version+1}`;await this.secrets.put(o,i);try{return await t.action(e,"rotate",{username:n.username,secretRef:o},i,r),this.store.saveCredential(e.id,n.username,o),this.store.update(e.id,e.version,{credentialRef:o}),{credential:{username:n.username,password:i,secretRef:o},dependencies:this.store.dependencies(e.id).filter((s)=>s.requiresRedeploy).map((s)=>s.resourceId)}}catch(s){throw await this.secrets.remove(o),s}}}function em(e){return{"data_service.action":async(t)=>{let r=t.operation.input,n=e.store.get(String(r.serviceId??"")),i=String(r.action??"");if(!n)throw Error("Data service was not found.");let o=e.resolveAdapter(n);if(!o||o.provider!==n.provider||!o.engines.includes(n.engine))throw Error(`No ${n.provider}/${n.engine} adapter is configured.`);if(i==="rotate"){let c=await new jr(e.store,new S(e.store.controlPlane),e.secrets).rotate(n,o,t);return{serviceId:n.id,action:i,username:c.credential.username,secretRef:c.credential.secretRef,dependencies:c.dependencies}}let s=n.credentialRef?await e.secrets.resolve(n.credentialRef):void 0;try{let c=i==="observe"?await o.observe(n):i==="create"?await o.apply(n,s,t):await o.action(n,i,r,s,t),u=e.store.get(n.id);return e.store.update(n.id,u.version,{observedState:c,status:i==="delete"?r.retention==="retain"?"retained":"deleting":"available"}),{serviceId:n.id,action:i,observed:c}}catch(c){let u=e.store.get(n.id);if(e.store.update(n.id,u.version,{status:"failed",observedState:{...u.observedState,error:c instanceof Error?c.message:String(c)}}),/temporar|timeout|unavailable|throttl/i.test(c instanceof Error?c.message:String(c)))throw new Le(c instanceof Error?c.message:String(c),"provider_transient");throw c}}}}class ks{transport;constructor(e){this.transport=e}observe(e){return this.transport.observe(e.placement)}apply(e,t){return this.transport.apply({id:e.placement,name:e.name,engine:e.engine,engineVersion:e.engineVersion??null,plan:e.plan,storageGb:e.storageGb??null,highAvailability:e.highAvailability,publicExposure:e.publicExposure,allowedCidrs:e.allowedCidrs,username:e.desiredState.username??"app",desiredState:e.desiredState},t)}action(e,t,r,n,i){return this.transport.execute(e.placement,t,{engine:e.engine,engineVersion:e.engineVersion??null,plan:e.plan,desiredState:e.desiredState,...r},n,i)}}class jn extends ks{provider="aws_rds";engines=["postgres","mysql","mariadb"]}class Vn extends ks{provider="aws_aurora";engines=["postgres","mysql"]}class zn extends ks{provider="aws_elasticache";engines=["redis"]}class Hn extends ks{provider="server";engines=["postgres","mysql","mariadb","redis","mongodb","libsql"]}class qn extends ks{provider="container";engines=["postgres","mysql","mariadb","redis","mongodb","libsql"]}var fc=(e,t)=>{let r=e.desiredState;return e[t]??(r&&typeof r==="object"&&!Array.isArray(r)?r[t]:void 0)},Ut=(e,t,r)=>{let n=fc(e,t);return n==null?r:String(n)},mn=(e,t)=>{let r=fc(e,t);return r==null?void 0:Number(r)},ko=(e,t)=>{let r=fc(e,t);return r==null?void 0:r===!0||r==="true"},Rs=(e,t)=>{let r=fc(e,t);return Array.isArray(r)?r.map(String):[]},pc=(e,t)=>Ut(t,"snapshotId")??`${e}-final-${new Date().toISOString().replace(/[^0-9]/g,"").slice(0,14)}`;function uc(e){if(!e)throw Error("RDS instance was not found.");return{providerId:e.DBInstanceIdentifier??null,status:e.DBInstanceStatus??"unknown",engine:e.Engine??null,engineVersion:e.EngineVersion??null,plan:e.DBInstanceClass??null,storageGb:e.AllocatedStorage??null,highAvailability:e.MultiAZ??!1,publicExposure:e.PubliclyAccessible??!1,endpoint:e.Endpoint?.Address??null,port:e.Endpoint?.Port??null,username:e.MasterUsername??null,database:e.DBName??null,encrypted:e.StorageEncrypted??!1}}class Gn{client;constructor(e=new me){this.client=e}async observe(e){return uc(await this.client.describeDBInstance(e))}async apply(e,t){let r=String(e.id),n=await this.client.createDBInstance({DBInstanceIdentifier:r,DBInstanceClass:String(e.plan),Engine:String(e.engine),MasterUsername:Ut(e,"username","app"),MasterUserPassword:t,DBName:Ut(e,"database"),AllocatedStorage:mn(e,"storageGb"),VpcSecurityGroupIds:Rs(e,"securityGroupIds"),DBSubnetGroupName:Ut(e,"subnetGroup"),BackupRetentionPeriod:mn(e,"backupRetentionDays")??7,MultiAZ:ko(e,"highAvailability"),EngineVersion:Ut(e,"engineVersion"),PubliclyAccessible:ko(e,"publicExposure")??!1,StorageType:Ut(e,"storageType","gp3"),StorageEncrypted:!0,KmsKeyId:Ut(e,"kmsKeyId"),DeletionProtection:!0,Tags:[{Key:"managed-by",Value:"ts-cloud"}]});return uc(n.DBInstance)}async execute(e,t,r,n,i){if(t==="observe")return this.observe(e);if(t==="restart")return await this.client.rebootDBInstance({DBInstanceIdentifier:e}),{status:"rebooting"};if(t==="backup"){let o=pc(e,r);return await this.client.createDBSnapshot({DBInstanceIdentifier:e,DBSnapshotIdentifier:o}),{status:"snapshotting",snapshotId:o}}if(t==="restore"){let o=String(r.targetId),s=await this.client.restoreDBInstanceFromDBSnapshot({DBInstanceIdentifier:o,DBSnapshotIdentifier:String(r.backupId),DBInstanceClass:Ut(r,"plan"),DBSubnetGroupName:Ut(r,"subnetGroup"),MultiAZ:ko(r,"highAvailability"),PubliclyAccessible:!1,StorageType:Ut(r,"storageType"),VpcSecurityGroupIds:Rs(r,"securityGroupIds"),DeletionProtection:!0,Tags:[{Key:"managed-by",Value:"ts-cloud"}]});return{...uc(s.DBInstance),sourceId:e,restoreTargetId:o}}if(t==="delete"){if(r.retention==="retain")return{status:"retained"};let o=pc(e,r);return await this.client.modifyDBInstance({DBInstanceIdentifier:e,DeletionProtection:!1,ApplyImmediately:!0}),await this.client.deleteDBInstance({DBInstanceIdentifier:e,SkipFinalSnapshot:!1,FinalDBSnapshotIdentifier:o,DeleteAutomatedBackups:!1}),{status:"deleting",finalSnapshotId:o}}if(["resize","version","rotate","expose"].includes(t)){let o=await this.client.modifyDBInstance({DBInstanceIdentifier:e,DBInstanceClass:Ut(r,"plan"),AllocatedStorage:mn(r,"storageGb"),MasterUserPassword:t==="rotate"?n:void 0,EngineVersion:Ut(r,"engineVersion"),MultiAZ:ko(r,"highAvailability"),PubliclyAccessible:ko(r,"publicExposure"),VpcSecurityGroupIds:Rs(r,"securityGroupIds"),ApplyImmediately:ko(r,"applyImmediately")??!0});return uc(o.DBInstance)}throw Error(`RDS action ${t} requires an engine connection runner.`)}}function bu(e){if(!e)throw Error("Aurora cluster was not found.");return{providerId:e.DBClusterIdentifier??null,status:e.Status??"unknown",engine:e.Engine??null,engineVersion:e.EngineVersion??null,endpoint:e.Endpoint??null,readerEndpoint:e.ReaderEndpoint??null,port:e.Port??null,username:e.MasterUsername??null,database:e.DatabaseName??null,encrypted:e.StorageEncrypted??!1,highAvailability:e.MultiAZ??!0}}class Wn{client;constructor(e=new me){this.client=e}async observe(e){let t=await this.client.describeDBClusters({DBClusterIdentifier:e});return bu(t.DBClusters?.[0])}async apply(e,t){let r=String(e.id),n=String(e.engine)==="postgres"?"aurora-postgresql":"aurora-mysql";return await this.client.createDBCluster({DBClusterIdentifier:r,Engine:n,EngineVersion:Ut(e,"engineVersion"),MasterUsername:Ut(e,"username","app"),MasterUserPassword:t,DatabaseName:Ut(e,"database"),DBSubnetGroupName:Ut(e,"subnetGroup"),VpcSecurityGroupIds:Rs(e,"securityGroupIds"),BackupRetentionPeriod:mn(e,"backupRetentionDays")??7,StorageEncrypted:!0,KmsKeyId:Ut(e,"kmsKeyId"),DeletionProtection:!0,ServerlessV2ScalingConfiguration:{MinCapacity:mn(e,"minCapacity")??0.5,MaxCapacity:mn(e,"maxCapacity")??4}}),await this.client.createDBInstance({DBInstanceIdentifier:`${r}-writer-1`,DBClusterIdentifier:r,DBInstanceClass:String(e.plan||"db.serverless"),Engine:n,PubliclyAccessible:ko(e,"publicExposure")??!1}),{status:"creating",providerId:r}}async execute(e,t,r,n){if(t==="observe")return this.observe(e);if(t==="restart")return await this.client.rebootDBCluster(e),{status:"rebooting"};if(t==="backup"){let i=pc(e,r);return await this.client.createDBClusterSnapshot(e,i),{status:"snapshotting",snapshotId:i}}if(t==="restore"){let i=String(r.targetId),o=String(r.engine)==="postgres"?"aurora-postgresql":"aurora-mysql",s=await this.client.restoreDBClusterFromSnapshot({DBClusterIdentifier:i,SnapshotIdentifier:String(r.backupId),Engine:o,EngineVersion:Ut(r,"engineVersion"),DBSubnetGroupName:Ut(r,"subnetGroup"),VpcSecurityGroupIds:Rs(r,"securityGroupIds"),DeletionProtection:!0,ServerlessV2ScalingConfiguration:{MinCapacity:mn(r,"minCapacity")??0.5,MaxCapacity:mn(r,"maxCapacity")??4}});return await this.client.createDBInstance({DBInstanceIdentifier:`${i}-writer-1`,DBClusterIdentifier:i,DBInstanceClass:Ut(r,"plan","db.serverless"),Engine:o,PubliclyAccessible:!1}),{...bu(s.DBCluster),sourceId:e,restoreTargetId:i}}if(t==="delete"){if(r.retention==="retain")return{status:"retained"};let i=pc(e,r);return await this.client.modifyDBCluster({DBClusterIdentifier:e,DeletionProtection:!1,ApplyImmediately:!0}),await this.client.deleteDBCluster(e,i),{status:"deleting",finalSnapshotId:i}}if(["resize","version","rotate"].includes(t)){let i=await this.client.modifyDBCluster({DBClusterIdentifier:e,ServerlessV2ScalingConfiguration:mn(r,"minCapacity")==null&&mn(r,"maxCapacity")==null?void 0:{MinCapacity:mn(r,"minCapacity")??0.5,MaxCapacity:mn(r,"maxCapacity")??4},EngineVersion:Ut(r,"engineVersion"),MasterUserPassword:t==="rotate"?n:void 0,ApplyImmediately:ko(r,"applyImmediately")??!0});return bu(i.DBCluster)}throw Error(`Aurora action ${t} requires an engine connection runner.`)}}class Kn{client;constructor(e=new ie){this.client=e}async observe(e){let t=(await this.client.describeCacheClusters(e)).CacheClusters[0];if(!t)throw Error("ElastiCache cluster was not found.");let r=t.CacheNodes?.[0]?.Endpoint;return{providerId:t.CacheClusterId,status:t.CacheClusterStatus,engine:t.Engine,engineVersion:t.EngineVersion,plan:t.CacheNodeType,nodes:t.NumCacheNodes,endpoint:r?.Address??null,port:r?.Port??null}}async apply(e){let t=await this.client.createCacheCluster({cacheClusterId:String(e.id),engine:"redis",cacheNodeType:String(e.plan),numCacheNodes:mn(e,"nodes")??1,engineVersion:Ut(e,"engineVersion"),port:mn(e,"port"),securityGroupIds:Rs(e,"securityGroupIds"),subnetGroupName:Ut(e,"subnetGroup"),tags:[{Key:"managed-by",Value:"ts-cloud"}]});return{providerId:t.CacheCluster.CacheClusterId,status:t.CacheCluster.CacheClusterStatus}}async execute(e,t,r){if(t==="observe")return this.observe(e);if(t==="restart"){let n=(await this.client.describeCacheClusters(e)).CacheClusters[0];return await this.client.rebootCacheCluster(e,n?.CacheNodes?.map((i)=>i.CacheNodeId)??["0001"]),{status:"rebooting"}}if(t==="delete"){if(r.retention==="retain")return{status:"retained"};return await this.client.deleteCacheCluster(e),{status:"deleting"}}throw Error(`ElastiCache action ${t} is not supported by this cluster mode.`)}}import{mkdir as Iv,writeFile as Cv}from"node:fs/promises";import{join as Ev}from"node:path";async function vn(e,t,r=!1){let n=Bun.spawn(["docker",...e],{stdin:t==null?"ignore":"pipe",stdout:"pipe",stderr:"pipe"}),i=new Response(n.stdout).text(),o=new Response(n.stderr).text();if(t!=null)n.stdin.write(t),n.stdin.end();let[s,c,u]=await Promise.all([n.exited,i,o]);if(s!==0&&!r)throw Error(`Docker command failed (${s}): ${u.trim()||c.trim()}`);return{code:s,stdout:c,stderr:u}}class tm{async ensureNetwork(e){if((await vn(["network","inspect",e],void 0,!0)).code!==0)await vn(["network","create","--internal",e])}async seedSecret(e,t){await vn(["volume","create",e]),await vn(["run","--rm","-i","-v",`${e}:/run/target`,"alpine:3.21","sh","-c","umask 077; cat > /run/target/credential"],t)}async removeVolume(e){await vn(["volume","rm",e],void 0,!0)}async inspect(e){let t=await vn(["inspect",e],void 0,!0);if(t.code!==0)return;return JSON.parse(t.stdout)[0]}async run(e){await vn(["run",...e])}async exec(e,t,r){return(await vn(["exec","-i",e,...t],r)).stdout}async update(e,t){await vn(["update",...t,e])}async restart(e){await vn(["restart",e])}async remove(e){await vn(["rm","--force",e],void 0,!0)}async logs(e,t){let r=await vn(["logs","--tail",String(Math.min(2000,Math.max(1,t))),e],void 0,!0);return`${r.stdout}${r.stderr}`.slice(-262144)}async stats(e){let t=await vn(["stats","--no-stream","--format","{{json .}}",e],void 0,!0);if(t.code!==0||!t.stdout.trim())return{};let r=JSON.parse(t.stdout.trim());return{cpuPercent:String(r.CPUPerc??""),memoryUsage:String(r.MemUsage??""),memoryPercent:String(r.MemPerc??""),networkIo:String(r.NetIO??""),blockIo:String(r.BlockIO??""),pids:Number(r.PIDs??0)}}}var Tv={postgres:{image:"postgres:17-alpine",port:5432,dataPath:"/var/lib/postgresql/data"},mysql:{image:"mysql:8.4",port:3306,dataPath:"/var/lib/mysql"},mariadb:{image:"mariadb:11.7",port:3306,dataPath:"/var/lib/mysql"},redis:{image:"redis:7.4-alpine",port:6379,dataPath:"/data"},mongodb:{image:"mongo:8.0",port:27017,dataPath:"/data/db"}};function Vi(e,t="app"){let r=String(e??t);if(!/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(r))throw Error("Database identifiers must be letters, numbers, or underscores.");return r}function Ko(e){if(!/^[a-z0-9][a-z0-9_.-]{1,62}$/i.test(e))throw Error("Runtime placement must be a valid container identifier.");return`tscloud-data-${e.toLowerCase()}`}function Av(e,t){let r=e.desiredState;return e[t]??(r&&typeof r==="object"&&!Array.isArray(r)?r[t]:void 0)}function va(e){return e.Config?.Labels??{}}class ot{runtime;backupRoot;constructor(e=new tm,t=A(process.cwd(),"backups","data")){this.runtime=e;this.backupRoot=t}async observe(e){let t=Ko(e),r=await this.runtime.inspect(t);if(!r)throw Error(`Data container ${t} was not found.`);let n=va(r),i=await this.runtime.stats(t),o=r.NetworkSettings?.Ports??{},s=Object.values(o).flat().find(Boolean);return{providerId:t,status:r.State?.Status??"unknown",healthy:r.State?.Health?.Status??null,engine:n["ts-cloud.engine"]??null,engineVersion:n["ts-cloud.engine-version"]??null,username:n["ts-cloud.username"]??null,database:n["ts-cloud.database"]??null,endpoint:s?.HostIp||"127.0.0.1",port:s?.HostPort?Number(s.HostPort):null,image:r.Config?.Image??null,startedAt:r.State?.StartedAt??null,metrics:i}}async apply(e,t){let r=String(e.id),n=Ko(r),i=String(e.engine);if(i==="libsql")throw Error("libSQL requires an explicitly configured runtime image.");let o=Tv[i];if(!o)throw Error(`Unsupported runtime data engine ${i}.`);if(!t)throw Error(`${i} requires a managed credential.`);if(e.publicExposure===!0)throw Error("Container public exposure requires an external reviewed firewall policy; direct publishing is refused.");let s=Vi(e.username),c=Vi(Av(e,"database")),u=`${n}-secret`,a=`${n}-data`,f=i==="redis"?`appendonly yes
45
+ ORDER BY rp.expires_at,rp.id`).all(e.toISOString(),e.toISOString()).map(mu),r=new Set;for(let n of new Set(t.map((i)=>i.projectId)))for(let i of this.listPolicies(n)){let o=this.listRecoveryPoints(i.projectId,i.id).filter((c)=>c.status==="available").sort((c,u)=>u.pointInTime.localeCompare(c.pointInTime));for(let c of o.slice(0,Math.max(0,i.retention.keepLast??0)))r.add(c.id);let s=[[i.retention.hourly,(c)=>c.toISOString().slice(0,13)],[i.retention.daily,(c)=>c.toISOString().slice(0,10)],[i.retention.weekly,(c)=>new Date(Date.UTC(c.getUTCFullYear(),c.getUTCMonth(),c.getUTCDate()-(c.getUTCDay()+6)%7)).toISOString().slice(0,10)],[i.retention.monthly,(c)=>c.toISOString().slice(0,7)]];for(let[c,u]of s){let a=new Set;for(let f of o){let T=u(new Date(f.pointInTime));if(a.has(T))continue;if(a.add(T),a.size<=Math.max(0,c??0))r.add(f.id)}}}return t.filter((n)=>!r.has(n.id))}coverage(e,t=this.now()){let r=new Map(this.listDestinations(e).map((n)=>[n.id,n]));return this.listPolicies(e).map((n)=>{let i=this.listRecoveryPoints(e,n.id).filter((c)=>c.status==="available"),o=i[0],s=o?(t.getTime()-new Date(o.pointInTime).getTime())/60000:Number.POSITIVE_INFINITY;return{policy:n,lastRecoveryPoint:o,missedRpo:n.enabled&&s>n.expectedRpoMinutes,unverified:i.filter((c)=>c.verificationState!=="verified").length,destinationHealthy:r.get(n.destinationId)?.status==="healthy"}})}}import{createCipheriv as gv,createDecipheriv as mv,createHash as Hg,randomBytes as Wg}from"node:crypto";var hu=Buffer.from("TSCB1"),oc=(e)=>`sha256:${Hg("sha256").update(e).digest("hex")}`;function Kg(e){return Hg("sha256").update(e).digest()}function fv(e,t,r){let n=r?Buffer.from(r):Wg(12);if(n.length!==12)throw Error("Backup encryption IV must contain 12 bytes.");let i=gv("aes-256-gcm",Kg(t),n),o=Buffer.concat([i.update(e),i.final()]),s=i.getAuthTag();return Buffer.concat([hu,n,s,o])}function hv(e,t){let r=Buffer.from(e);if(!r.subarray(0,hu.length).equals(hu))throw Error("Backup does not contain a valid encrypted envelope.");let n=r.subarray(5,17),i=r.subarray(17,33),o=r.subarray(33),s=mv("aes-256-gcm",Kg(t),n);return s.setAuthTag(i),Buffer.concat([s.update(o),s.final()])}function yv(e){let t;try{t=JSON.parse(e)}catch{throw Error("Backup destination credential must be a JSON object with accessKeyId and secretAccessKey.")}if(!t.accessKeyId||!t.secretAccessKey)throw Error("Backup destination credential requires accessKeyId and secretAccessKey.");if(t.expiresAt){let r=new Date(String(t.expiresAt));if(!Number.isFinite(r.getTime()))throw Error("Backup destination credential expiresAt must be an ISO timestamp.");if(r.getTime()<=Date.now())throw Error("Backup destination credential has expired.")}return{accessKeyId:String(t.accessKeyId),secretAccessKey:String(t.secretAccessKey),sessionToken:t.sessionToken?String(t.sessionToken):void 0}}async function Qg(e,t,r=new Date){if(!e.credentialRef)return{status:"default"};try{let n=JSON.parse(await t.resolve(e.credentialRef));if(!n.accessKeyId||!n.secretAccessKey)return{status:"invalid"};if(!n.expiresAt)return{status:"static"};let i=new Date(String(n.expiresAt));if(!Number.isFinite(i.getTime()))return{status:"invalid"};let o=i.getTime()-r.getTime();return{status:o<=0?"expired":o<=604800000?"expiring":"valid",expiresAt:i.toISOString()}}catch{return{status:"invalid"}}}class ii{secrets;clientFactory;multipartThreshold;partSize;constructor(e,t=(i,o)=>new g(i.region??"us-east-1",void 0,{endpoint:i.endpoint?new URL(i.endpoint).host:void 0,forcePathStyle:i.forcePathStyle,credentials:o}),r=8388608,n=8388608){this.secrets=e;this.clientFactory=t;this.multipartThreshold=r;this.partSize=n}async client(e){let t=e.credentialRef?yv(await this.secrets.resolve(e.credentialRef)):void 0;return this.clientFactory(e,t)}async test(e){if(!e.bucket)throw Error("S3 destination has no configured bucket.");let t=await this.client(e),r=`${e.prefix?`${e.prefix.replace(/\/$/,"")}/`:""}.ts-cloud-health/${crypto.randomUUID()}`;await t.putObject({bucket:e.bucket,key:r,body:"ts-cloud backup destination health check",contentType:"text/plain"});try{let n=await t.getObjectBytes(e.bucket,r);if(Buffer.from(n.body).toString()!=="ts-cloud backup destination health check")throw Error("Backup destination health object was corrupted.")}finally{await t.deleteObject(e.bucket,r)}}async upload(e,t){if(!e.bucket)throw Error("S3 destination has no configured bucket.");let r=await this.client(e),n=oc(t.body),i=e.encryption!=="provider"?await this.secrets.resolve(e.encryptionKeyRef):void 0,o=i?t.resume?.encryptionIv?Buffer.from(t.resume.encryptionIv,"base64url"):Wg(12):void 0,s=i?fv(t.body,i,o):Buffer.from(t.body),c=oc(s),u=`${e.prefix?`${e.prefix.replace(/\/$/,"")}/`:""}${t.key.replace(/^\/+/,"")}`,a=t.contentType??"application/octet-stream",f={"ts-cloud-format":"v1","ts-cloud-sha256":c.slice(7),"ts-cloud-encrypted":i?"true":"false"};if(t.resume&&t.resume.key!==u)throw Error("Multipart checkpoint does not match the requested backup key.");if(t.resume&&i&&!t.resume.encryptionIv)throw Error("Encrypted multipart checkpoint has no resumable envelope state.");if(t.resume&&i&&t.resume.plaintextChecksum!==n)throw Error("Encrypted multipart checkpoint does not match the backup payload.");if(s.length<this.multipartThreshold)await r.putObject({bucket:e.bucket,key:u,body:s,contentType:a,metadata:f});else{let T=t.resume?void 0:await r.createMultipartUpload(e.bucket,u,{contentType:a,metadata:f}),R=t.resume??{uploadId:T.UploadId,key:u,parts:[],bytesUploaded:0,encryptionIv:o?.toString("base64url"),plaintextChecksum:n},D=new Map(R.parts.map((Y)=>[Y.PartNumber,Y])),W=Math.ceil(s.length/this.partSize);for(let Y=0;Y<W;Y++){let ee=Y+1;if(!D.has(ee)){let ne=Y*this.partSize,he=await r.uploadPart(e.bucket,u,R.uploadId,ee,s.subarray(ne,Math.min(s.length,ne+this.partSize)));D.set(ee,{PartNumber:ee,ETag:he.ETag})}R.parts=[...D.values()].sort((ne,he)=>ne.PartNumber-he.PartNumber),R.bytesUploaded=Math.min(s.length,ee*this.partSize),t.checkpoint?.(R)}await r.completeMultipartUpload(e.bucket,u,R.uploadId,R.parts)}return{uri:`s3://${e.bucket}/${u}`,key:u,sizeBytes:s.length,checksum:c,manifest:{format:"ts-cloud-backup-v1",encrypted:!!i,plaintextChecksum:n,storageChecksum:c,contentType:a}}}async download(e,t){if(!e.bucket)throw Error("S3 destination has no configured bucket.");let r=await this.client(e),n=await r.getObjectBytes(e.bucket,t.key),i=Buffer.from(n.body);if(oc(i)!==t.checksum)throw Error("Backup checksum verification failed; object is corrupt.");let o=t.manifest.encrypted?hv(i,await this.secrets.resolve(e.encryptionKeyRef)):i;if(oc(o)!==t.manifest.plaintextChecksum)throw Error("Backup plaintext checksum verification failed.");return o}async abortPartial(e,t){if(!e.bucket)throw Error("S3 destination has no configured bucket.");await(await this.client(e)).abortMultipartUpload(e.bucket,t.key,t.uploadId)}async delete(e,t){if(!e.bucket)throw Error("S3 destination has no configured bucket.");await(await this.client(e)).deleteObject(e.bucket,t)}}import{createHash as bv}from"node:crypto";var Sv=(e)=>`sha256:${bv("sha256").update(e).digest("hex")}`;class Jr{store;queue;now;constructor(e,t,r=()=>new Date){this.store=e;this.queue=t;this.now=r}enqueueBackup(e,t=this.now().toISOString(),r){if(!e.enabled)throw Error("Backup policy is disabled.");let n=this.store.createJob({projectId:e.projectId,policyId:e.id,kind:"backup",status:"queued",idempotencyKey:`backup:${e.id}:${t}`,target:{scheduledFor:t},cancellability:"checkpoint_only",progress:{phase:"queued"}});if(!n.operationId){let i=this.queue.enqueue({projectId:e.projectId,environmentId:e.environmentId,resourceId:e.resourceId,actorId:r,kind:"backup.run",input:{backupJobId:n.id},lockKey:e.dataServiceId?`data-service:${e.dataServiceId}`:e.resourceId?`resource:${e.resourceId}`:`backup-policy:${e.id}`,providerKey:"backup",maxAttempts:3,timeoutSeconds:14400,retryClasses:["provider_transient"],resumePolicy:"requeue"});return this.store.updateJob(n.id,{operationId:i.operation.id})}return n}enqueueDue(e=this.now()){return this.store.duePolicies(e).map((t)=>{let r=t.nextRunAt;return this.store.advancePolicy(t.id,r),this.enqueueBackup(t,r)})}enqueueVerification(e){let t=this.store.createJob({projectId:e.projectId,policyId:e.policyId,recoveryPointId:e.id,kind:"verify",status:"queued",idempotencyKey:`verify:${e.id}:${e.checksum}`,target:{},cancellability:"safe",progress:{phase:"queued"}});if(!t.operationId){let r=this.queue.enqueue({projectId:e.projectId,resourceId:e.resourceId,kind:"backup.verify",input:{backupJobId:t.id},lockKey:`recovery-point:${e.id}`,providerKey:"backup",maxAttempts:2,timeoutSeconds:7200,retryClasses:["provider_transient"],resumePolicy:"requeue"});return this.store.updateJob(t.id,{operationId:r.operation.id})}return t}planRestore(e,t){if(e.status!=="available")throw Error("Only available recovery points can be restored.");if(e.verificationState!=="verified")throw Error("Restore requires a verified recovery point.");if(t.mode==="in_place"){if(!t.recentAuth)throw Error("In-place restore requires recent authentication.");if(t.confirm!==t.targetName)throw Error(`Type ${t.targetName} to confirm in-place restore.`);if(!t.downtimeAcknowledged)throw Error("In-place restore requires downtime acknowledgement.");let r=t.safetyBackupId?this.store.getRecoveryPoint(t.safetyBackupId):void 0;if(!r||r.id===e.id||r.status!=="available"||r.verificationState!=="verified"||r.resourceId!==e.resourceId||r.dataServiceId!==e.dataServiceId)throw Error("In-place restore requires a distinct verified safety backup for the same target.")}return{point:e,mode:t.mode,target:{...t.target,inPlace:t.mode==="in_place",restoreMode:t.mode},warnings:t.mode==="in_place"?["The target is locked against deployments and backup work.","Downtime and data replacement are expected.","Provider cancellation may stop only at a checkpoint."]:["An isolated target is created and health-validated before cleanup."]}}enqueueRestore(e,t){let r=this.planRestore(e,t),n=t.drill?"drill":"restore",i=Sv(JSON.stringify({point:e.id,mode:t.mode,target:t.target,safety:t.safetyBackupId,drill:!!t.drill})),o=this.store.createJob({projectId:e.projectId,policyId:e.policyId,recoveryPointId:e.id,kind:n,status:"queued",idempotencyKey:`${n}:${i}`,target:r.target,restoreMode:r.mode,cancellability:"checkpoint_only",safetyBackupId:t.safetyBackupId,progress:{phase:"queued",warnings:r.warnings}});if(!o.operationId){let s=this.queue.enqueue({projectId:e.projectId,resourceId:e.resourceId,actorId:t.actorId,kind:t.drill?"backup.drill":"backup.restore",input:{backupJobId:o.id},lockKey:e.dataServiceId?`data-service:${e.dataServiceId}`:e.resourceId?`resource:${e.resourceId}`:`recovery-point:${e.id}`,providerKey:"backup",maxAttempts:1,timeoutSeconds:14400,retryClasses:[],resumePolicy:"fail"});return this.store.updateJob(o.id,{operationId:s.operation.id})}return o}enqueueRetention(e=this.now()){return this.store.retentionCandidates(e).map((t)=>{let r=this.store.createJob({projectId:t.projectId,policyId:t.policyId,recoveryPointId:t.id,kind:"cleanup",status:"queued",idempotencyKey:`cleanup:${t.id}:${t.expiresAt}`,target:{},cancellability:"safe",progress:{phase:"queued"}});if(!r.operationId){let n=this.queue.enqueue({projectId:t.projectId,resourceId:t.resourceId,kind:"backup.cleanup",input:{backupJobId:r.id},lockKey:`recovery-point:${t.id}`,providerKey:"backup",maxAttempts:3,timeoutSeconds:7200,retryClasses:["provider_transient"],resumePolicy:"requeue"});return this.store.updateJob(r.id,{operationId:n.operation.id})}return r})}}function Yg(e){let t=e.now??(()=>new Date),r=new Jr(e.store,e.queue,t),n=(c)=>{let u=c.recoveryPointId?e.store.getRecoveryPoint(c.recoveryPointId):void 0,a=c.policyId?e.store.getPolicy(c.policyId):u?.policyId?e.store.getPolicy(u.policyId):void 0;if(!a)throw Error("Backup policy was not found.");let f=e.store.getDestination(u?.destinationId??a.destinationId),T=e.resolveSource(a);if(!f)throw Error("Backup destination was not found.");if(!T)throw Error(`No ${a.resourceKind} backup adapter is configured.`);return{point:u,policy:a,destination:f,source:T}},i=(c)=>{let u=c.operation.input,a=e.store.getJob(String(u.backupJobId??""));if(!a)throw Error("Backup job was not found.");return e.store.updateJob(a.id,{status:"running",startedAt:a.startedAt??t().toISOString(),progress:{...a.progress,phase:"running"}}),a},o=(c,u)=>{let a=e.store.getJob(c.id)??c;e.store.updateJob(c.id,{status:"failed",finishedAt:t().toISOString(),error:u instanceof Error?u.message:String(u),progress:{...a.progress,phase:"failed"}})};return{"backup.run":async(c)=>{let u=i(c);try{let{policy:a,destination:f,source:T}=n(u),R=await T.create(a,c),D=e.resolveDestination(f),W=R.mode==="object"?await(async()=>{if(!D)throw Error("Backup destination adapter is not configured.");let he=e.store.getJob(u.id)?.progress,te=he?.multipart,De=te&&typeof te==="object"&&!Array.isArray(te)&&typeof te.uploadId==="string"&&typeof te.key==="string"&&Array.isArray(te.parts)?te:void 0;return D.upload(f,{key:R.key,body:R.body,contentType:R.contentType,resume:De,checkpoint:(tt)=>{c.checkpoint("uploading",`Uploaded ${Number(tt.bytesUploaded??0)} backup bytes.`),e.store.updateJob(u.id,{progress:{phase:"uploading",multipart:{...tt}}})}})})():{uri:R.uri,key:R.uri,sizeBytes:R.sizeBytes,checksum:R.checksum,manifest:{format:"ts-cloud-backup-v1",encrypted:!1,plaintextChecksum:R.checksum,storageChecksum:R.checksum,contentType:"application/provider-snapshot"}},Y=a.retention.expireAfterDays?new Date(t().getTime()+a.retention.expireAfterDays*86400000).toISOString():void 0,ee=e.store.getJob(u.id)?.startedAt,ne=e.store.createRecoveryPoint({projectId:a.projectId,policyId:a.id,destinationId:f.id,resourceId:a.resourceId,dataServiceId:a.dataServiceId,backupJobId:u.id,kind:a.resourceKind,pointInTime:t().toISOString(),uri:W.uri,sizeBytes:W.sizeBytes,checksum:W.checksum,manifest:{...R.manifest,...W.manifest,storageKey:W.key},toolVersion:R.toolVersion,engineVersion:R.engineVersion,expiresAt:Y,lockedUntil:f.immutability.defaultRetentionDays?new Date(t().getTime()+f.immutability.defaultRetentionDays*86400000).toISOString():void 0,held:!1,pinned:!1,status:"available",verificationState:"unverified",durationMs:Math.max(0,t().getTime()-new Date(ee??t().toISOString()).getTime())});if(R.mode==="external"&&f.provider==="aws_backup")e.store.recordDestinationTest(f.id,{ok:!0});return e.store.updateJob(u.id,{status:"succeeded",recoveryPointId:ne.id,finishedAt:t().toISOString(),progress:{phase:"stored",recoveryPointId:ne.id}}),r.enqueueVerification(ne),{backupJobId:u.id,recoveryPointId:ne.id}}catch(a){let f=e.store.getJob(u.id),T=f?.progress.multipart,R=(()=>{try{return n(u)}catch{return}})();if(R?.destination.provider==="aws_backup")e.store.recordDestinationTest(R.destination.id,{ok:!1,error:a instanceof Error?a.message:String(a)});let D=!1;if(T&&typeof T==="object"&&!Array.isArray(T)&&R){let W=e.resolveDestination(R.destination);if(D=!0,W?.abortPartial)try{await W.abortPartial(R.destination,T),D=!1,e.store.updateJob(u.id,{progress:{...f.progress,partialCleanup:"aborted"}})}catch{e.store.updateJob(u.id,{progress:{...f.progress,partialCleanup:"required"}})}}if(D)e.store.updateJob(u.id,{status:"cleanup_required",finishedAt:t().toISOString(),error:a instanceof Error?a.message:String(a),progress:{...e.store.getJob(u.id)?.progress??{},phase:"cleanup_required"}});else o(u,a);throw a}},"backup.verify":async(c)=>{let u=i(c);try{let{point:a,destination:f,source:T}=n(u);if(!a)throw Error("Recovery point was not found.");e.store.updateRecoveryPoint(a.id,{verificationState:"verifying"});let R;if(a.uri.startsWith("s3:")){let D=e.resolveDestination(f);if(!D)throw Error("Backup destination adapter is not configured.");let W=await D.download(f,{key:String(a.manifest.storageKey??""),checksum:a.checksum,manifest:a.manifest}),Y=T.verify?await T.verify(a,W,c):{};R={bytes:W.length,checksum:a.checksum,...Y}}else if(T.verifyExternal)R=await T.verifyExternal(a,c);else throw Error("External recovery point verification is not supported.");return e.store.updateRecoveryPoint(a.id,{verificationState:"verified",verifiedAt:t().toISOString(),manifest:{...a.manifest,verification:R}}),e.store.updateJob(u.id,{status:"succeeded",finishedAt:t().toISOString(),progress:{phase:"verified",evidence:R}}),{backupJobId:u.id,recoveryPointId:a.id,evidence:R}}catch(a){if(u.recoveryPointId)e.store.updateRecoveryPoint(u.recoveryPointId,{verificationState:/checksum|corrupt|authentic/i.test(a instanceof Error?a.message:String(a))?"corrupt":"failed"});throw o(u,a),a}},"backup.restore":async(c)=>s(c,!1),"backup.drill":async(c)=>s(c,!0),"backup.cleanup":async(c)=>{let u=i(c);try{let{point:a,destination:f,source:T}=n(u);if(!a)throw Error("Recovery point was not found.");if(!e.store.retentionCandidates(t()).some((R)=>R.id===a.id))throw Error("Recovery point is held, pinned, locked, or in active use.");if(e.store.updateRecoveryPoint(a.id,{status:"deleting"}),a.uri.startsWith("s3:")){let R=e.resolveDestination(f);if(!R)throw Error("Destination cleanup is unavailable.");await R.delete(f,String(a.manifest.storageKey??""))}else if(T.deleteExternal)await T.deleteExternal(a,c);else throw Error("External recovery point cleanup is unavailable.");return e.store.updateRecoveryPoint(a.id,{status:"deleted"}),e.store.updateJob(u.id,{status:"succeeded",finishedAt:t().toISOString(),progress:{phase:"deleted"}}),{backupJobId:u.id,recoveryPointId:a.id,deleted:!0}}catch(a){throw o(u,a),a}}};async function s(c,u){let a=i(c);try{let{point:f,policy:T,destination:R,source:D}=n(a);if(!f)throw Error("Recovery point was not found.");if(u&&!D.cleanup)throw Error("This backup source cannot safely clean a recovery drill target.");let W=f.uri.startsWith("s3:")?e.resolveDestination(R):void 0,Y=W?await W.download(R,{key:String(f.manifest.storageKey??""),checksum:f.checksum,manifest:f.manifest}):void 0,ee=await D.restore(f,Y,a.target,c),ne=D.validateHealth?await D.validateHealth({...a.target,...ee},c):{healthy:!0,mode:"adapter"},he=e.validateHealth?await e.validateHealth(T,a.target):{healthy:!0,mode:"not_configured"},te={...ne,healthy:ne.healthy===!0&&he.healthy===!0,configured:he};if(te.healthy!==!0)throw Error("Restored target did not pass its configured health check.");if(u&&D.cleanup)await D.cleanup({...a.target,provider:f.manifest.provider??null},c);return e.store.updateJob(a.id,{status:"succeeded",finishedAt:t().toISOString(),healthResult:te,progress:{phase:u?"drill_cleaned":"restored",restored:ee}}),{backupJobId:a.id,recoveryPointId:f.id,restored:ee,health:te,cleaned:u}}catch(f){let T=(()=>{try{return n(a)}catch{return}})(),R=f instanceof Error?f.message:String(f),D=!1;if(u&&T?.source.cleanup)try{await T.source.cleanup({...a.target,provider:T.point?.manifest.provider??null},c)}catch{D=!0}if(D)e.store.updateJob(a.id,{status:"cleanup_required",finishedAt:t().toISOString(),error:R,progress:{...a.progress,phase:"cleanup_required"}});else o(a,f);throw f}}}import{createHash as vv}from"node:crypto";var wv=(e)=>`sha256:${vv("sha256").update(e).digest("hex")}`;class yu{dataServices;client;constructor(e,t=new me){this.dataServices=e;this.client=t}service(e){let t=e.dataServiceId?this.dataServices.get(e.dataServiceId):void 0;if(!t||!["aws_rds","aws_aurora"].includes(t.provider))throw Error("Managed database backup policy requires an RDS or Aurora data service.");return t}async waitForSnapshot(e,t,r){for(;;){r.throwIfCancellationRequested?.(),r.heartbeat?.();let n=e==="aws_aurora"?(await this.client.describeDBClusterSnapshots({DBClusterSnapshotIdentifier:t})).DBClusterSnapshots[0]:(await this.client.describeDBSnapshots({DBSnapshotIdentifier:t})).DBSnapshots?.[0];if(!n)throw Error("Provider snapshot was not found.");let i=n,o=String(i.Status??i.DBSnapshotStatus??"unknown");if(r.checkpoint?.("provider_snapshot",`Database snapshot ${t} is ${o}.`),o==="available")return i;if(["deleted","deleting","failed"].includes(o))throw Error(`Provider snapshot ${t} failed with state ${o}.`);await Bun.sleep(5000)}}async create(e,t){let r=this.service(e),n=String(t.operation?.id??new Date().toISOString()).replace(/[^A-Za-z0-9]/g,"").slice(0,20),i=`${r.placement.slice(0,42).replace(/-+$/,"")}-${n}`;if(r.provider==="aws_aurora")await this.client.createDBClusterSnapshot(r.placement,i);else await this.client.createDBSnapshot({DBInstanceIdentifier:r.placement,DBSnapshotIdentifier:i});await this.waitForSnapshot(r.provider,i,t);let o=`${r.provider}:${r.placement}:${i}`;return{mode:"external",uri:`aws-backup:${o}`,checksum:wv(o),sizeBytes:0,manifest:{provider:r.provider,sourceId:r.placement,snapshotId:i,plan:r.plan,engine:r.engine},engineVersion:r.engineVersion,toolVersion:"aws-rds-api-2014-10-31"}}async verifyExternal(e,t){let r=String(e.manifest.snapshotId??""),n=String(e.manifest.provider??"");if(!r)throw Error("Snapshot recovery point has no snapshot ID.");let i=await this.waitForSnapshot(n,r,t),o=String(i.Status??i.DBSnapshotStatus??"unknown");return{snapshotId:r,status:o,encrypted:i.Encrypted??i.StorageEncrypted??!0}}async restore(e,t,r,n){let i=String(r.targetId??""),o=String(e.manifest.snapshotId??""),s=String(e.manifest.provider??"");if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(i))throw Error("Managed restore requires a valid distinct targetId.");if(i===e.manifest.sourceId)throw Error("Managed restore target must differ from its source.");if(s==="aws_aurora"){let c=e.manifest.engine==="postgres"?"aurora-postgresql":"aurora-mysql";await this.client.restoreDBClusterFromSnapshot({DBClusterIdentifier:i,SnapshotIdentifier:o,Engine:c,EngineVersion:e.engineVersion,DeletionProtection:!0,ServerlessV2ScalingConfiguration:{MinCapacity:Number(r.minCapacity)||0.5,MaxCapacity:Number(r.maxCapacity)||4}}),await this.client.createDBInstance({DBInstanceIdentifier:`${i}-writer-1`,DBClusterIdentifier:i,DBInstanceClass:String(r.plan??e.manifest.plan??"db.serverless"),Engine:c,PubliclyAccessible:!1})}else await this.client.restoreDBInstanceFromDBSnapshot({DBInstanceIdentifier:i,DBSnapshotIdentifier:o,DBInstanceClass:String(r.plan??e.manifest.plan??""),PubliclyAccessible:!1,DeletionProtection:!0,Tags:[{Key:"managed-by",Value:"ts-cloud-restore"}]});return{targetId:i,provider:s,status:"creating",isolated:!0}}async validateHealth(e,t){let r=String(e.targetId??""),n=String(e.provider??"");for(;;){t.throwIfCancellationRequested?.(),t.heartbeat?.();let i=n==="aws_aurora"?(await this.client.describeDBClusters({DBClusterIdentifier:r})).DBClusters?.[0]:(await this.client.describeDBInstances({DBInstanceIdentifier:r})).DBInstances?.[0];if(!i)throw Error("Restored managed database was not found.");let o=String(i.Status??i.DBInstanceStatus??"unknown");if(t.checkpoint?.("provider_restore",`Restored database ${r} is ${o}.`),o==="available")return{healthy:!0,targetId:r,provider:n,status:o};if(["deleted","deleting","failed","incompatible-restore"].includes(o))throw Error(`Restored managed database ${r} failed with state ${o}.`);await Bun.sleep(5000)}}async cleanup(e,t){let r=String(e.targetId??""),n=String(e.provider??"");if(!r)throw Error("Restore cleanup target is required.");if(n==="aws_aurora")await this.client.deleteDBInstance({DBInstanceIdentifier:`${r}-writer-1`,SkipFinalSnapshot:!0}),await this.client.modifyDBCluster({DBClusterIdentifier:r,DeletionProtection:!1,ApplyImmediately:!0}),await this.client.deleteDBCluster(r);else await this.client.modifyDBInstance({DBInstanceIdentifier:r,DeletionProtection:!1,ApplyImmediately:!0}),await this.client.deleteDBInstance({DBInstanceIdentifier:r,SkipFinalSnapshot:!0,DeleteAutomatedBackups:!0})}async deleteExternal(e,t){let r=String(e.manifest.snapshotId??"");if(e.manifest.provider==="aws_aurora")await this.client.deleteDBClusterSnapshot(r);else await this.client.deleteDBSnapshot(r)}}var Fr=(e,t="none",r=!1)=>({supported:!0,downtime:t,destructive:r,explanation:e}),Cr=(e)=>({supported:!1,downtime:"none",destructive:!1,explanation:e});function Zt(e,t){let r=["aws_rds","aws_aurora","aws_elasticache"].includes(t),n=["server","container"].includes(t),i=["postgres","mysql","mariadb"].includes(e),o=e==="redis",s={};return s.create=t==="external"?Cr("External services can be adopted as read-only inventory."):Fr(r?"Provision through the provider API.":"Provision through the owning runtime driver.","possible"),s.observe=t==="external"?Cr("External observation requires a configured provider adapter."):Fr("Provider/runtime health and endpoint metadata are observable."),s.connect=Fr("Connection guidance uses secret references and never returns a password by default."),s.backup=i&&(r||n)?Fr(r?"Create a provider snapshot.":"Create a consistent engine-native dump.","possible"):Cr("This cache path is not a durable backup source."),s.restore=r&&i?Fr("Restore creates a reviewed provider target.","required",!0):Cr("Restore requires a configured provider restore runner."),s.restart=t==="external"?Cr("External restart requires a configured provider adapter."):Fr(r?"Provider restart/failover semantics apply.":"Restart the owning service unit.","required"),s.resize=t==="aws_elasticache"?Cr("ElastiCache resizing requires a replication-group migration runner."):r?Fr("Provider plan/storage modification may enter a maintenance window.","possible"):n?Fr("Edit host/container resources and reconcile.","required"):Cr("External resize requires a configured provider adapter."),s.version=n?Cr("Runtime version upgrades require an explicit image migration runner."):r&&t!=="aws_elasticache"?Fr(i?"Major versions require compatibility preflight and backup.":"Engine upgrades require a maintenance window.","required"):Cr("External upgrades require a configured provider adapter."),s.rotate=t==="aws_elasticache"||t==="external"||n&&!i&&!o?Cr("Credential rotation is not available for this provider/engine path."):Fr("Rotate through the secret backend, update the engine, then flag dependent releases."),s.expose=n?Cr("Direct container publishing is refused; use a reviewed firewall and proxy policy."):t==="aws_rds"?Fr("Exposure is reconciled through security groups; public access defaults off."):Cr("Exposure changes require a provider-specific network runner."),s.delete=t==="external"?Cr("External deletion requires a configured provider adapter."):Fr(r?"Final snapshot is supported where the provider allows it.":"A final engine backup is required unless explicitly retained.","required",!0),s.logs=n?Fr("Read bounded service logs from the runtime."):Cr("Provider log export is not configured for this adapter."),s.slow_queries=n&&i?Fr("Read bounded runtime logs after engine slow-query logging is enabled."):Cr("A slow-query log runner is not configured for this provider."),s.users=n&&i?Fr("Logical users can be listed; creation requires a referenced secondary credential."):Cr("User management requires an engine connection runner."),s.databases=n&&i?Fr("Logical databases can be listed, created, and confirmation-gated for deletion."):Cr("Logical database management requires an engine connection runner."),{actions:s,endpointTypes:r?["internal","external","tunnel"]:["internal","tunnel"],metrics:o?["connections","memory","evictions","hit_rate","latency"]:["connections","cpu","storage","read_latency","write_latency","iops"]}}var As=(e)=>e==null?void 0:String(e),dc=(e)=>Number(e)===1,sc=(e)=>{try{return JSON.parse(String(e))}catch{return{}}};function Xg(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:As(e.environment_id),resourceId:As(e.resource_id),name:String(e.name),engine:String(e.engine),provider:String(e.provider),placement:String(e.placement),engineVersion:As(e.engine_version),plan:String(e.plan),storageGb:e.storage_gb==null?void 0:Number(e.storage_gb),highAvailability:dc(e.high_availability),publicExposure:dc(e.public_exposure),allowedCidrs:sc(e.allowed_cidrs),desiredState:sc(e.desired_state),observedState:sc(e.observed_state),capabilities:sc(e.capabilities),credentialRef:As(e.credential_ref),status:String(e.status),origin:String(e.origin),managementEnabled:dc(e.management_enabled),ownerActorId:As(e.owner_actor_id),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}class er{controlPlane;now;constructor(e,t=()=>new Date){this.controlPlane=e;this.now=t}create(e){if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(e.name))throw Error("Data service names must be 2-63 lowercase letters, numbers, or dashes.");if(e.publicExposure&&(!e.allowedCidrs.length||e.allowedCidrs.includes("0.0.0.0/0")))throw Error("Public exposure requires explicit narrow CIDRs; 0.0.0.0/0 is refused.");let t=crypto.randomUUID(),r=this.now().toISOString(),n=Zt(e.engine,e.provider);return this.controlPlane.database.run("INSERT INTO data_services (id,organization_id,project_id,environment_id,resource_id,name,engine,provider,placement,engine_version,plan,storage_gb,high_availability,public_exposure,allowed_cidrs,desired_state,observed_state,capabilities,credential_ref,status,origin,management_enabled,owner_actor_id,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.organizationId,e.projectId,e.environmentId??null,e.resourceId??null,e.name,e.engine,e.provider,e.placement,e.engineVersion??null,e.plan,e.storageGb??null,e.highAvailability?1:0,e.publicExposure?1:0,JSON.stringify(e.allowedCidrs),JSON.stringify(e.desiredState),JSON.stringify(e.observedState),JSON.stringify(n),e.credentialRef??null,e.status,e.origin,e.managementEnabled?1:0,e.ownerActorId??null,1,r,r]),this.get(t)}get(e){let t=this.controlPlane.database.query("SELECT * FROM data_services WHERE id=?").get(e);return t?Xg(t):void 0}list(e,t){return this.controlPlane.database.query(`SELECT * FROM data_services WHERE project_id=?${t?" AND environment_id=?":""} ORDER BY name`).all(e,...t?[t]:[]).map(Xg)}update(e,t,r){let n=this.get(e);if(!n)throw Error("Data service was not found.");if(n.version!==t)throw Error("Data service changed; refresh before retrying.");let i={...n,...r};if(i.publicExposure&&(!i.allowedCidrs.length||i.allowedCidrs.includes("0.0.0.0/0")))throw Error("Public exposure requires explicit narrow CIDRs; 0.0.0.0/0 is refused.");if(this.controlPlane.database.run("UPDATE data_services SET plan=?,storage_gb=?,engine_version=?,high_availability=?,public_exposure=?,allowed_cidrs=?,desired_state=?,observed_state=?,status=?,management_enabled=?,credential_ref=?,version=version+1,updated_at=? WHERE id=? AND version=?",[i.plan,i.storageGb??null,i.engineVersion??null,i.highAvailability?1:0,i.publicExposure?1:0,JSON.stringify(i.allowedCidrs),JSON.stringify(i.desiredState),JSON.stringify(i.observedState),i.status,i.managementEnabled?1:0,i.credentialRef??null,this.now().toISOString(),e,t]).changes!==1)throw Error("Data service changed; refresh before retrying.");return this.get(e)}credential(e){let t=this.controlPlane.database.query("SELECT * FROM data_service_credentials WHERE service_id=? ORDER BY version DESC LIMIT 1").get(e);return t?{id:String(t.id),serviceId:String(t.service_id),username:String(t.username),secretRef:String(t.secret_ref),version:Number(t.version),createdAt:String(t.created_at),rotatedAt:As(t.rotated_at)}:void 0}saveCredential(e,t,r){let n=this.credential(e),i=n?.id??crypto.randomUUID(),o=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO data_service_credentials (id,service_id,username,secret_ref,version,created_at,rotated_at) VALUES (?,?,?,?,?,?,?) ON CONFLICT(service_id,username) DO UPDATE SET secret_ref=excluded.secret_ref,version=data_service_credentials.version+1,rotated_at=excluded.rotated_at",[i,e,t,r,n?.version??1,n?.createdAt??o,n?o:null]),this.credential(e)}addDependency(e){let t=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO data_service_dependencies (service_id,resource_id,secret_ref,requires_redeploy,created_at) VALUES (?,?,?,?,?) ON CONFLICT(service_id,resource_id) DO UPDATE SET secret_ref=excluded.secret_ref,requires_redeploy=excluded.requires_redeploy",[e.serviceId,e.resourceId,e.secretRef,e.requiresRedeploy?1:0,t]),{...e,createdAt:t}}dependencies(e){return this.controlPlane.database.query("SELECT * FROM data_service_dependencies WHERE service_id=? ORDER BY resource_id").all(e).map((t)=>({serviceId:String(t.service_id),resourceId:String(t.resource_id),secretRef:String(t.secret_ref),requiresRedeploy:dc(t.requires_redeploy),createdAt:String(t.created_at)}))}removeDependency(e,t){return this.controlPlane.database.run("DELETE FROM data_service_dependencies WHERE service_id=? AND resource_id=?",[e,t]).changes===1}remove(e){this.controlPlane.database.run("DELETE FROM data_services WHERE id=?",[e])}}function Zg(){let t=crypto.getRandomValues(new Uint8Array(40));return Array.from(t,(r)=>"ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@#$%^&*_-+="[r%69]).join("")}function Bn(e,t){return t.map((r)=>{let n=r.type==="tunnel"?"127.0.0.1":r.host,i=e.engine==="redis"?`redis-cli -h ${n} -p ${r.port}${r.tls?" --tls":""}`:e.engine==="postgres"?`psql "host=${n} port=${r.port} dbname=${r.database??"postgres"} sslmode=${r.tls?"require":"disable"}"`:e.engine==="mongodb"?`mongosh "mongodb://${n}:${r.port}/${r.database??"admin"}${r.tls?"?tls=true":""}"`:e.engine==="libsql"?`turso db shell ${r.tls?"https":"http"}://${n}:${r.port}`:`mysql --host=${n} --port=${r.port} --database=${r.database??"mysql"} --ssl-mode=${r.tls?"REQUIRED":"DISABLED"}`;return{type:r.type,command:i,secretRef:e.credentialRef}})}class jr{store;queue;secrets;constructor(e,t,r){this.store=e;this.queue=t;this.secrets=r}async create(e){let t,r;if(e.provider!=="aws_elasticache"){let n=e.username??"app",i=Zg();r=`secret://data-services/${e.projectId}/${e.name}/${n}`,await this.secrets.put(r,i),t={username:n,password:i,secretRef:r}}try{let n=this.store.create({...e,credentialRef:r,status:"planning"});if(t)this.store.saveCredential(n.id,t.username,t.secretRef);let i=this.enqueue(n,"create",{});return{service:n,credential:t,operationId:i}}catch(n){if(r)await this.secrets.remove(r);throw n}}plan(e,t,r={}){let n=e.capabilities.actions[t],i=t==="version"&&String(r.engineVersion??"").split(".")[0]!==String(e.engineVersion??"").split(".")[0];return{service:e,action:t,capability:n,changes:r,preflight:{backupRequired:["delete","restore"].includes(t)||i,compatibilityRequired:i,typedConfirmation:n.destructive?e.name:void 0,retentionChoiceRequired:t==="delete"},warnings:[...n.downtime!=="none"?[`Downtime is ${n.downtime}.`]:[],...e.origin==="adopted"&&!e.managementEnabled?["Adopted resource is read-only until management is explicitly enabled."]:[]]}}enqueue(e,t,r,n){let i=this.plan(e,t,r);if(!i.capability.supported)throw Error(i.capability.explanation);if(e.origin==="adopted"&&!e.managementEnabled&&t!=="observe")throw Error("Adopted resources remain read-only until management is explicitly enabled.");if(i.preflight.typedConfirmation&&r.confirm!==i.preflight.typedConfirmation)throw Error(`Type ${i.preflight.typedConfirmation} to confirm ${t}.`);if(i.preflight.retentionChoiceRequired&&!["final_backup","retain"].includes(String(r.retention??"")))throw Error("Deletion requires retention final_backup or retain.");if(i.preflight.compatibilityRequired&&(r.compatibilityReviewed!==!0||!r.backupId))throw Error("Major version changes require compatibilityReviewed=true and a backupId.");if(t==="restore"){let o=String(r.backupId??""),s=String(r.targetId??"");if(!o||!s)throw Error("Restore requires both backupId and targetId.");if(s===e.placement)throw Error("Restore targetId must differ from the source placement.");if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(s))throw Error("Restore targetId must be 2-63 lowercase letters, numbers, or dashes.")}return this.queue.enqueue({projectId:e.projectId,environmentId:e.environmentId,resourceId:e.resourceId,actorId:n,kind:"data_service.action",input:{serviceId:e.id,action:t,...r},lockKey:`data-service:${e.id}`,providerKey:e.provider,maxAttempts:3,timeoutSeconds:7200,retryClasses:["provider_transient"],resumePolicy:"requeue"}).operation.id}async rotate(e,t,r){let n=this.store.credential(e.id);if(!n)throw Error("Data service credential metadata was not found.");let i=Zg(),o=`${n.secretRef}/v${n.version+1}`;await this.secrets.put(o,i);try{return await t.action(e,"rotate",{username:n.username,secretRef:o},i,r),this.store.saveCredential(e.id,n.username,o),this.store.update(e.id,e.version,{credentialRef:o}),{credential:{username:n.username,password:i,secretRef:o},dependencies:this.store.dependencies(e.id).filter((s)=>s.requiresRedeploy).map((s)=>s.resourceId)}}catch(s){throw await this.secrets.remove(o),s}}}function em(e){return{"data_service.action":async(t)=>{let r=t.operation.input,n=e.store.get(String(r.serviceId??"")),i=String(r.action??"");if(!n)throw Error("Data service was not found.");let o=e.resolveAdapter(n);if(!o||o.provider!==n.provider||!o.engines.includes(n.engine))throw Error(`No ${n.provider}/${n.engine} adapter is configured.`);if(i==="rotate"){let c=await new jr(e.store,new S(e.store.controlPlane),e.secrets).rotate(n,o,t);return{serviceId:n.id,action:i,username:c.credential.username,secretRef:c.credential.secretRef,dependencies:c.dependencies}}let s=n.credentialRef?await e.secrets.resolve(n.credentialRef):void 0;try{let c=i==="observe"?await o.observe(n):i==="create"?await o.apply(n,s,t):await o.action(n,i,r,s,t),u=e.store.get(n.id);return e.store.update(n.id,u.version,{observedState:c,status:i==="delete"?r.retention==="retain"?"retained":"deleting":"available"}),{serviceId:n.id,action:i,observed:c}}catch(c){let u=e.store.get(n.id);if(e.store.update(n.id,u.version,{status:"failed",observedState:{...u.observedState,error:c instanceof Error?c.message:String(c)}}),/temporar|timeout|unavailable|throttl/i.test(c instanceof Error?c.message:String(c)))throw new Le(c instanceof Error?c.message:String(c),"provider_transient");throw c}}}}class ks{transport;constructor(e){this.transport=e}observe(e){return this.transport.observe(e.placement)}apply(e,t){return this.transport.apply({id:e.placement,name:e.name,engine:e.engine,engineVersion:e.engineVersion??null,plan:e.plan,storageGb:e.storageGb??null,highAvailability:e.highAvailability,publicExposure:e.publicExposure,allowedCidrs:e.allowedCidrs,username:e.desiredState.username??"app",desiredState:e.desiredState},t)}action(e,t,r,n,i){return this.transport.execute(e.placement,t,{engine:e.engine,engineVersion:e.engineVersion??null,plan:e.plan,desiredState:e.desiredState,...r},n,i)}}class jn extends ks{provider="aws_rds";engines=["postgres","mysql","mariadb"]}class Vn extends ks{provider="aws_aurora";engines=["postgres","mysql"]}class zn extends ks{provider="aws_elasticache";engines=["redis"]}class Hn extends ks{provider="server";engines=["postgres","mysql","mariadb","redis","mongodb","libsql"]}class qn extends ks{provider="container";engines=["postgres","mysql","mariadb","redis","mongodb","libsql"]}var fc=(e,t)=>{let r=e.desiredState;return e[t]??(r&&typeof r==="object"&&!Array.isArray(r)?r[t]:void 0)},Ut=(e,t,r)=>{let n=fc(e,t);return n==null?r:String(n)},mn=(e,t)=>{let r=fc(e,t);return r==null?void 0:Number(r)},ko=(e,t)=>{let r=fc(e,t);return r==null?void 0:r===!0||r==="true"},Rs=(e,t)=>{let r=fc(e,t);return Array.isArray(r)?r.map(String):[]},pc=(e,t)=>Ut(t,"snapshotId")??`${e}-final-${new Date().toISOString().replace(/[^0-9]/g,"").slice(0,14)}`;function uc(e){if(!e)throw Error("RDS instance was not found.");return{providerId:e.DBInstanceIdentifier??null,status:e.DBInstanceStatus??"unknown",engine:e.Engine??null,engineVersion:e.EngineVersion??null,plan:e.DBInstanceClass??null,storageGb:e.AllocatedStorage??null,highAvailability:e.MultiAZ??!1,publicExposure:e.PubliclyAccessible??!1,endpoint:e.Endpoint?.Address??null,port:e.Endpoint?.Port??null,username:e.MasterUsername??null,database:e.DBName??null,encrypted:e.StorageEncrypted??!1}}class Gn{client;constructor(e=new me){this.client=e}async observe(e){return uc(await this.client.describeDBInstance(e))}async apply(e,t){let r=String(e.id),n=await this.client.createDBInstance({DBInstanceIdentifier:r,DBInstanceClass:String(e.plan),Engine:String(e.engine),MasterUsername:Ut(e,"username","app"),MasterUserPassword:t,DBName:Ut(e,"database"),AllocatedStorage:mn(e,"storageGb"),VpcSecurityGroupIds:Rs(e,"securityGroupIds"),DBSubnetGroupName:Ut(e,"subnetGroup"),BackupRetentionPeriod:mn(e,"backupRetentionDays")??7,MultiAZ:ko(e,"highAvailability"),EngineVersion:Ut(e,"engineVersion"),PubliclyAccessible:ko(e,"publicExposure")??!1,StorageType:Ut(e,"storageType","gp3"),StorageEncrypted:!0,KmsKeyId:Ut(e,"kmsKeyId"),DeletionProtection:!0,Tags:[{Key:"managed-by",Value:"ts-cloud"}]});return uc(n.DBInstance)}async execute(e,t,r,n,i){if(t==="observe")return this.observe(e);if(t==="restart")return await this.client.rebootDBInstance({DBInstanceIdentifier:e}),{status:"rebooting"};if(t==="backup"){let o=pc(e,r);return await this.client.createDBSnapshot({DBInstanceIdentifier:e,DBSnapshotIdentifier:o}),{status:"snapshotting",snapshotId:o}}if(t==="restore"){let o=String(r.targetId),s=await this.client.restoreDBInstanceFromDBSnapshot({DBInstanceIdentifier:o,DBSnapshotIdentifier:String(r.backupId),DBInstanceClass:Ut(r,"plan"),DBSubnetGroupName:Ut(r,"subnetGroup"),MultiAZ:ko(r,"highAvailability"),PubliclyAccessible:!1,StorageType:Ut(r,"storageType"),VpcSecurityGroupIds:Rs(r,"securityGroupIds"),DeletionProtection:!0,Tags:[{Key:"managed-by",Value:"ts-cloud"}]});return{...uc(s.DBInstance),sourceId:e,restoreTargetId:o}}if(t==="delete"){if(r.retention==="retain")return{status:"retained"};let o=pc(e,r);return await this.client.modifyDBInstance({DBInstanceIdentifier:e,DeletionProtection:!1,ApplyImmediately:!0}),await this.client.deleteDBInstance({DBInstanceIdentifier:e,SkipFinalSnapshot:!1,FinalDBSnapshotIdentifier:o,DeleteAutomatedBackups:!1}),{status:"deleting",finalSnapshotId:o}}if(["resize","version","rotate","expose"].includes(t)){let o=await this.client.modifyDBInstance({DBInstanceIdentifier:e,DBInstanceClass:Ut(r,"plan"),AllocatedStorage:mn(r,"storageGb"),MasterUserPassword:t==="rotate"?n:void 0,EngineVersion:Ut(r,"engineVersion"),MultiAZ:ko(r,"highAvailability"),PubliclyAccessible:ko(r,"publicExposure"),VpcSecurityGroupIds:Rs(r,"securityGroupIds"),ApplyImmediately:ko(r,"applyImmediately")??!0});return uc(o.DBInstance)}throw Error(`RDS action ${t} requires an engine connection runner.`)}}function bu(e){if(!e)throw Error("Aurora cluster was not found.");return{providerId:e.DBClusterIdentifier??null,status:e.Status??"unknown",engine:e.Engine??null,engineVersion:e.EngineVersion??null,endpoint:e.Endpoint??null,readerEndpoint:e.ReaderEndpoint??null,port:e.Port??null,username:e.MasterUsername??null,database:e.DatabaseName??null,encrypted:e.StorageEncrypted??!1,highAvailability:e.MultiAZ??!0}}class Wn{client;constructor(e=new me){this.client=e}async observe(e){let t=await this.client.describeDBClusters({DBClusterIdentifier:e});return bu(t.DBClusters?.[0])}async apply(e,t){let r=String(e.id),n=String(e.engine)==="postgres"?"aurora-postgresql":"aurora-mysql";return await this.client.createDBCluster({DBClusterIdentifier:r,Engine:n,EngineVersion:Ut(e,"engineVersion"),MasterUsername:Ut(e,"username","app"),MasterUserPassword:t,DatabaseName:Ut(e,"database"),DBSubnetGroupName:Ut(e,"subnetGroup"),VpcSecurityGroupIds:Rs(e,"securityGroupIds"),BackupRetentionPeriod:mn(e,"backupRetentionDays")??7,StorageEncrypted:!0,KmsKeyId:Ut(e,"kmsKeyId"),DeletionProtection:!0,ServerlessV2ScalingConfiguration:{MinCapacity:mn(e,"minCapacity")??0.5,MaxCapacity:mn(e,"maxCapacity")??4}}),await this.client.createDBInstance({DBInstanceIdentifier:`${r}-writer-1`,DBClusterIdentifier:r,DBInstanceClass:String(e.plan||"db.serverless"),Engine:n,PubliclyAccessible:ko(e,"publicExposure")??!1}),{status:"creating",providerId:r}}async execute(e,t,r,n){if(t==="observe")return this.observe(e);if(t==="restart")return await this.client.rebootDBCluster(e),{status:"rebooting"};if(t==="backup"){let i=pc(e,r);return await this.client.createDBClusterSnapshot(e,i),{status:"snapshotting",snapshotId:i}}if(t==="restore"){let i=String(r.targetId),o=String(r.engine)==="postgres"?"aurora-postgresql":"aurora-mysql",s=await this.client.restoreDBClusterFromSnapshot({DBClusterIdentifier:i,SnapshotIdentifier:String(r.backupId),Engine:o,EngineVersion:Ut(r,"engineVersion"),DBSubnetGroupName:Ut(r,"subnetGroup"),VpcSecurityGroupIds:Rs(r,"securityGroupIds"),DeletionProtection:!0,ServerlessV2ScalingConfiguration:{MinCapacity:mn(r,"minCapacity")??0.5,MaxCapacity:mn(r,"maxCapacity")??4}});return await this.client.createDBInstance({DBInstanceIdentifier:`${i}-writer-1`,DBClusterIdentifier:i,DBInstanceClass:Ut(r,"plan","db.serverless"),Engine:o,PubliclyAccessible:!1}),{...bu(s.DBCluster),sourceId:e,restoreTargetId:i}}if(t==="delete"){if(r.retention==="retain")return{status:"retained"};let i=pc(e,r);return await this.client.modifyDBCluster({DBClusterIdentifier:e,DeletionProtection:!1,ApplyImmediately:!0}),await this.client.deleteDBCluster(e,i),{status:"deleting",finalSnapshotId:i}}if(["resize","version","rotate"].includes(t)){let i=await this.client.modifyDBCluster({DBClusterIdentifier:e,ServerlessV2ScalingConfiguration:mn(r,"minCapacity")==null&&mn(r,"maxCapacity")==null?void 0:{MinCapacity:mn(r,"minCapacity")??0.5,MaxCapacity:mn(r,"maxCapacity")??4},EngineVersion:Ut(r,"engineVersion"),MasterUserPassword:t==="rotate"?n:void 0,ApplyImmediately:ko(r,"applyImmediately")??!0});return bu(i.DBCluster)}throw Error(`Aurora action ${t} requires an engine connection runner.`)}}class Kn{client;constructor(e=new ie){this.client=e}async observe(e){let t=(await this.client.describeCacheClusters(e)).CacheClusters[0];if(!t)throw Error("ElastiCache cluster was not found.");let r=t.CacheNodes?.[0]?.Endpoint;return{providerId:t.CacheClusterId,status:t.CacheClusterStatus,engine:t.Engine,engineVersion:t.EngineVersion,plan:t.CacheNodeType,nodes:t.NumCacheNodes,endpoint:r?.Address??null,port:r?.Port??null}}async apply(e){let t=await this.client.createCacheCluster({cacheClusterId:String(e.id),engine:"redis",cacheNodeType:String(e.plan),numCacheNodes:mn(e,"nodes")??1,engineVersion:Ut(e,"engineVersion"),port:mn(e,"port"),securityGroupIds:Rs(e,"securityGroupIds"),subnetGroupName:Ut(e,"subnetGroup"),tags:[{Key:"managed-by",Value:"ts-cloud"}]});return{providerId:t.CacheCluster.CacheClusterId,status:t.CacheCluster.CacheClusterStatus}}async execute(e,t,r){if(t==="observe")return this.observe(e);if(t==="restart"){let n=(await this.client.describeCacheClusters(e)).CacheClusters[0];return await this.client.rebootCacheCluster(e,n?.CacheNodes?.map((i)=>i.CacheNodeId)??["0001"]),{status:"rebooting"}}if(t==="delete"){if(r.retention==="retain")return{status:"retained"};return await this.client.deleteCacheCluster(e),{status:"deleting"}}throw Error(`ElastiCache action ${t} is not supported by this cluster mode.`)}}import{mkdir as Iv,writeFile as Cv}from"node:fs/promises";import{join as Ev}from"node:path";async function vn(e,t,r=!1){let n=Bun.spawn(["docker",...e],{stdin:t==null?"ignore":"pipe",stdout:"pipe",stderr:"pipe"}),i=new Response(n.stdout).text(),o=new Response(n.stderr).text();if(t!=null)n.stdin.write(t),n.stdin.end();let[s,c,u]=await Promise.all([n.exited,i,o]);if(s!==0&&!r)throw Error(`Docker command failed (${s}): ${u.trim()||c.trim()}`);return{code:s,stdout:c,stderr:u}}class tm{async ensureNetwork(e){if((await vn(["network","inspect",e],void 0,!0)).code!==0)await vn(["network","create","--internal",e])}async seedSecret(e,t){await vn(["volume","create",e]),await vn(["run","--rm","-i","-v",`${e}:/run/target`,"alpine:3.21","sh","-c","umask 077; cat > /run/target/credential"],t)}async removeVolume(e){await vn(["volume","rm",e],void 0,!0)}async inspect(e){let t=await vn(["inspect",e],void 0,!0);if(t.code!==0)return;return JSON.parse(t.stdout)[0]}async run(e){await vn(["run",...e])}async exec(e,t,r){return(await vn(["exec","-i",e,...t],r)).stdout}async update(e,t){await vn(["update",...t,e])}async restart(e){await vn(["restart",e])}async remove(e){await vn(["rm","--force",e],void 0,!0)}async logs(e,t){let r=await vn(["logs","--tail",String(Math.min(2000,Math.max(1,t))),e],void 0,!0);return`${r.stdout}${r.stderr}`.slice(-262144)}async stats(e){let t=await vn(["stats","--no-stream","--format","{{json .}}",e],void 0,!0);if(t.code!==0||!t.stdout.trim())return{};let r=JSON.parse(t.stdout.trim());return{cpuPercent:String(r.CPUPerc??""),memoryUsage:String(r.MemUsage??""),memoryPercent:String(r.MemPerc??""),networkIo:String(r.NetIO??""),blockIo:String(r.BlockIO??""),pids:Number(r.PIDs??0)}}}var Tv={postgres:{image:"postgres:17-alpine",port:5432,dataPath:"/var/lib/postgresql/data"},mysql:{image:"mysql:8.4",port:3306,dataPath:"/var/lib/mysql"},mariadb:{image:"mariadb:11.7",port:3306,dataPath:"/var/lib/mysql"},redis:{image:"redis:7.4-alpine",port:6379,dataPath:"/data"},mongodb:{image:"mongo:8.0",port:27017,dataPath:"/data/db"}};function Vi(e,t="app"){let r=String(e??t);if(!/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(r))throw Error("Database identifiers must be letters, numbers, or underscores.");return r}function Ko(e){if(!/^[a-z0-9][a-z0-9_.-]{1,62}$/i.test(e))throw Error("Runtime placement must be a valid container identifier.");return`tscloud-data-${e.toLowerCase()}`}function Av(e,t){let r=e.desiredState;return e[t]??(r&&typeof r==="object"&&!Array.isArray(r)?r[t]:void 0)}function va(e){return e.Config?.Labels??{}}class ot{runtime;backupRoot;constructor(e=new tm,t=A(process.cwd(),"backups","data")){this.runtime=e;this.backupRoot=t}async observe(e){let t=Ko(e),r=await this.runtime.inspect(t);if(!r)throw Error(`Data container ${t} was not found.`);let n=va(r),i=await this.runtime.stats(t),o=r.NetworkSettings?.Ports??{},s=Object.values(o).flat().find(Boolean);return{providerId:t,status:r.State?.Status??"unknown",healthy:r.State?.Health?.Status??null,engine:n["ts-cloud.engine"]??null,engineVersion:n["ts-cloud.engine-version"]??null,username:n["ts-cloud.username"]??null,database:n["ts-cloud.database"]??null,endpoint:s?.HostIp||"127.0.0.1",port:s?.HostPort?Number(s.HostPort):null,image:r.Config?.Image??null,startedAt:r.State?.StartedAt??null,metrics:i}}async apply(e,t){let r=String(e.id),n=Ko(r),i=String(e.engine);if(i==="libsql")throw Error("libSQL requires an explicitly configured runtime image.");let o=Tv[i];if(!o)throw Error(`Unsupported runtime data engine ${i}.`);if(!t)throw Error(`${i} requires a managed credential.`);if(e.publicExposure===!0)throw Error("Container public exposure requires an external reviewed firewall policy; direct publishing is refused.");let s=Vi(e.username),c=Vi(Av(e,"database")),u=`${n}-secret`,a=`${n}-data`,f=i==="redis"?`appendonly yes
46
46
  protected-mode yes
47
47
  requirepass ${t.replaceAll("\\","\\\\").replaceAll(`
48
48
  `,"")}
@@ -57,7 +57,7 @@ protected-mode yes
57
57
  requirepass ${n.replaceAll("\\","\\\\").replaceAll(`
58
58
  `,"")}
59
59
  `:n;if(await this.runtime.seedSecret(`${i}-secret`,f),c==="redis")await this.runtime.restart(i);return{status:c==="redis"?"restarting":"running",username:u}}if(t==="delete"){if(r.retention==="retain")return{status:"retained"};let o=await this.backup(e,r);return await this.runtime.remove(i),await this.runtime.removeVolume(`${i}-secret`),await this.runtime.removeVolume(`${i}-data`),{status:"deleted",finalBackupId:o.backupId??null,backupPath:o.path??null}}if(t==="expose")throw Error("Direct container exposure is refused; use a reviewed firewall and proxy policy.");throw Error(`${t} requires a configured engine lifecycle runner.`)}}import{createCipheriv as kv,createDecipheriv as Rv,createHash as rm,randomBytes as Pv}from"node:crypto";class tr{controlPlane;now;key;constructor(e,t,r=()=>new Date){this.controlPlane=e;this.now=r;if(!t)throw Error("Data-service encryption key is required.");this.key=rm("sha256").update(`ts-cloud:data-services:${t}`).digest()}encrypt(e){let t=Pv(12),r=kv("aes-256-gcm",this.key,t),n=Buffer.concat([r.update(e,"utf8"),r.final()]);return`v1.${t.toString("base64url")}.${r.getAuthTag().toString("base64url")}.${n.toString("base64url")}`}decrypt(e){let[t,r,n,i]=e.split(".");if(t!=="v1"||!r||!n||!i)throw Error("Encrypted data-service secret is unavailable.");try{let o=Rv("aes-256-gcm",this.key,Buffer.from(r,"base64url"));return o.setAuthTag(Buffer.from(n,"base64url")),Buffer.concat([o.update(Buffer.from(i,"base64url")),o.final()]).toString("utf8")}catch{throw Error("Encrypted data-service secret could not be decrypted.")}}async put(e,t){if(!/^secret:\/\/data-services\/[A-Za-z0-9._/-]+$/.test(e))throw Error("Invalid data-service secret reference.");if(!t)throw Error("Data-service secret cannot be empty.");let r=this.now().toISOString();this.controlPlane.database.run("INSERT INTO data_service_secrets (reference,ciphertext,fingerprint,created_at,updated_at) VALUES (?,?,?,?,?) ON CONFLICT(reference) DO UPDATE SET ciphertext=excluded.ciphertext,fingerprint=excluded.fingerprint,updated_at=excluded.updated_at",[e,this.encrypt(t),rm("sha256").update(t).digest("hex"),r,r])}async resolve(e){let t=this.controlPlane.database.query("SELECT ciphertext FROM data_service_secrets WHERE reference = ?").get(e);if(!t)throw Error("Data-service secret was not found.");return this.decrypt(t.ciphertext)}async remove(e){this.controlPlane.database.run("DELETE FROM data_service_secrets WHERE reference = ?",[e])}}import{existsSync as wa}from"node:fs";import{mkdir as yc,readdir as xv,rename as Su,rm as xs}from"node:fs/promises";import{relative as Dv,resolve as Zr,sep as bc}from"node:path";function Qo(e,t){if(t==="gzip")return Buffer.from(Bun.gzipSync(Uint8Array.from(e)));if(t==="zstd")return Buffer.from(Bun.zstdCompressSync(Uint8Array.from(e)));return Buffer.from(e)}function Ji(e,t){if(t==="gzip")return Buffer.from(Bun.gunzipSync(Uint8Array.from(e)));if(t==="zstd")return Buffer.from(Bun.zstdDecompressSync(Uint8Array.from(e)));return Buffer.from(e)}async function vu(e,t){let r=Bun.spawn(["tar",...e],{stdin:t?Buffer.from(t):void 0,stdout:"pipe",stderr:"pipe"}),[n,i,o]=await Promise.all([r.exited,new Response(r.stdout).arrayBuffer(),new Response(r.stderr).text()]);if(n!==0)throw Error(o.trim()||`tar exited with status ${n}.`);return{stdout:Buffer.from(i),stderr:o}}function Ov(e){let t=e.replaceAll("\\","/").replace(/^\.\//,"");return!!t&&!t.startsWith("/")&&!t.split("/").includes("..")}class im{async create(e,t,r){return(await vu(["-C",e,"-cf","-",...r.map((i)=>`--exclude=${i}`),"--",...t])).stdout}async extract(e,t){await yc(t,{recursive:!0,mode:448}),await vu(["-C",t,"-xf","-"],e)}async inspect(e){let t=await vu(["-tf","-"],e),r=t.stdout.toString().split(`
60
- `).filter(Boolean);if(r.some((n)=>!Ov(n)))throw Error("Backup archive contains an unsafe path.");return{entries:r,bytes:e.byteLength}}}function nm(e,t){if(!t.trim())throw Error("File backup paths cannot be empty.");let r=Zr(e,t),n=Dv(e,r);if(n===".."||n.startsWith(`..${bc}`)||n==="")throw Error(`File backup path ${t} is outside the project root.`);return n}function hc(e){let t=String(e.targetId??e.path??"");if(!/^[A-Za-z0-9][A-Za-z0-9_.-]{1,127}$/.test(t))throw Error("File restores require a safe target name.");return t}class wu{runtime;root;restoreRoot;constructor(e,t=new im,r=A(e,"restores","files")){this.runtime=t;this.root=Zr(e),this.restoreRoot=Zr(r)}paths(e){let t=[...new Set(e.includePatterns.map((r)=>nm(this.root,r)))];if(!t.length)throw Error("File backup policies require at least one project-relative path.");for(let r of t)if(!wa(Zr(this.root,r)))throw Error(`File backup path ${r} was not found.`);return t.filter((r)=>!t.some((n)=>n!==r&&r.startsWith(`${n}${bc}`)))}async create(e,t){let r=this.paths(e),n=await this.runtime.create(this.root,r,e.excludePatterns),i=await this.runtime.inspect(n),o=e.compression??"none",s=Qo(n,o),c=String(t.operation?.id??new Date().toISOString()).replace(/[^A-Za-z0-9]/g,"").slice(0,32);return{mode:"object",key:`${e.projectId}/files/${c}.tar${o==="none"?"":o==="gzip"?".gz":".zst"}`,body:s,contentType:o==="gzip"?"application/gzip":o==="zstd"?"application/zstd":"application/x-tar",manifest:{archive:"tar",compression:o,sourcePaths:r,excluded:e.excludePatterns,entries:i.entries.length},toolVersion:"system-tar"}}async restore(e,t,r,n){if(!t)throw Error("File restore requires an archive payload.");let i=Ji(t,String(e.manifest.compression??"none"));if(await this.runtime.inspect(i),r.restoreMode==="in_place"){let s=Zr(this.restoreRoot,`.staging-${hc(r)}`),c=Zr(this.restoreRoot,`.rollback-${hc(r)}`),u=Array.isArray(e.manifest.sourcePaths)?e.manifest.sourcePaths.map(String):[];if(!u.length)throw Error("File recovery point has no source path manifest.");await xs(s,{recursive:!0,force:!0}),await xs(c,{recursive:!0,force:!0}),await this.runtime.extract(i,s),await yc(c,{recursive:!0,mode:448});let a=[];try{for(let f of u){let T=Zr(this.root,nm(this.root,f)),R=Zr(s,f),D=Zr(c,f);if(await yc(Zr(D,".."),{recursive:!0}),wa(T))await Su(T,D);await yc(Zr(T,".."),{recursive:!0}),await Su(R,T),a.push(f)}}catch(f){for(let T of a.reverse()){let R=Zr(this.root,T),D=Zr(c,T);if(await xs(R,{recursive:!0,force:!0}),wa(D))await Su(D,R)}throw f}finally{await xs(s,{recursive:!0,force:!0})}return await xs(c,{recursive:!0,force:!0}),{path:this.root,restoredPaths:u,inPlace:!0}}let o=Zr(this.restoreRoot,hc(r));if(wa(o))throw Error("The isolated file restore target already exists.");return await this.runtime.extract(i,o),{path:o,isolated:!0}}async verify(e,t,r){let n=Ji(t,String(e.manifest.compression??"none")),i=await this.runtime.inspect(n);return{archive:"tar",entries:i.entries.length,uncompressedBytes:i.bytes}}async validateHealth(e,t){let r=String(e.path??"");if(!r||!r.startsWith(`${this.restoreRoot}${bc}`)||!wa(r))throw Error("Isolated file restore target was not found.");let n=await xv(r);return{healthy:!0,path:r,topLevelEntries:n.length}}async cleanup(e,t){let r=hc(e),n=Zr(this.restoreRoot,r);if(!n.startsWith(`${this.restoreRoot}${bc}`))throw Error("Refusing to clean a file restore outside the restore root.");await xs(n,{recursive:!0,force:!0})}}class Iu{services;secrets;transport;constructor(e,t,r=new ot){this.services=e;this.secrets=t;this.transport=r}async create(e,t){if(!e.dataServiceId)throw Error("Logical database backups require a data service.");let r=this.services.get(e.dataServiceId);if(!r)throw Error("Logical database service was not found.");if(!["container","server"].includes(r.provider))throw Error("Logical database backups require an on-box data service.");let n=await this.transport.exportLogicalBackup(r.id),i=e.compression??"none",o=Qo(n.body,i),s=String(t.operation?.id??new Date().toISOString()).replace(/[^A-Za-z0-9]/g,"").slice(0,32);return{mode:"object",key:`${e.projectId}/databases/${r.id}/${s}.sql${i==="none"?"":i==="gzip"?".gz":".zst"}`,body:o,contentType:i==="gzip"?"application/gzip":i==="zstd"?"application/zstd":"application/sql",engineVersion:n.engineVersion,toolVersion:"engine-native",manifest:{format:"logical-sql-v1",sourceDataServiceId:r.id,engine:n.engine,database:n.database,username:n.username,compression:i}}}async restore(e,t,r,n){if(!t)throw Error("Logical database backup body is unavailable.");let i=String(e.dataServiceId??e.manifest.sourceDataServiceId??""),o=String(r.dataServiceId??r.targetId??""),s=r.inPlace===!0;if(!i||!o)throw Error("Logical database restore requires source and target identifiers.");if(s&&o!==i)throw Error("An in-place restore must target the source data service.");let c=this.services.get(i);if(!c?.credentialRef)throw Error("Logical database credential reference was not found.");let u=await this.secrets.resolve(c.credentialRef);return this.transport.restoreLogicalBackup({sourceId:i,targetId:o,body:Ji(t,String(e.manifest.compression??"none")),credential:u,inPlace:s})}async cleanup(e,t){if(e.inPlace===!0)throw Error("In-place database restores cannot be cleaned as drills.");let r=String(e.dataServiceId??e.targetId??"");if(!r)throw Error("Database cleanup requires a target identifier.");await this.transport.removeRestoredService(r)}}var Cu=/^[A-Za-z0-9][A-Za-z0-9_.-]{1,127}$/;async function Yo(e,t,r=!1){let n=Bun.spawn(["docker",...e],{stdin:t?"pipe":"ignore",stdout:"pipe",stderr:"pipe"}),i=new Response(n.stdout).arrayBuffer(),o=new Response(n.stderr).text();if(t)n.stdin.write(t),n.stdin.end();let[s,c,u]=await Promise.all([n.exited,i,o]);if(s!==0&&!r)throw Error(`Docker volume command failed (${s}): ${u.trim()}`);return{code:s,stdout:Buffer.from(c),stderr:u}}class om{async exists(e){return(await Yo(["volume","inspect",e],void 0,!0)).code===0}async export(e){return(await Yo(["run","--rm","-v",`${e}:/source:ro`,"alpine:3.21","tar","-C","/source","-czf","-","."])).stdout}async import(e,t,r=!1){if(!await this.exists(e))await Yo(["volume","create",e]);try{if(r)await Yo(["run","--rm","-v",`${e}:/target`,"alpine:3.21","sh","-c","find /target -mindepth 1 -delete"]);await Yo(["run","--rm","-i","-v",`${e}:/target`,"alpine:3.21","tar","-C","/target","--no-same-owner","-xzf","-"],t)}catch(n){throw await this.remove(e),n}}async remove(e){await Yo(["volume","rm",e],void 0,!0)}async probe(e){let t=(await Yo(["run","--rm","-v",`${e}:/target:ro`,"alpine:3.21","sh","-c",`find /target -mindepth 1 -printf '%s\\n' | awk '{n+=1;b+=$1} END {print n ":" b}'`])).stdout.toString(),[r,n]=t.trim().split(":").map(Number);if(!Number.isFinite(r)||!Number.isFinite(n))throw Error("Restored volume health probe returned invalid output.");return{entries:r,bytes:n}}}class Eu{runtime;constructor(e=new om){this.runtime=e}async create(e,t){let r=String(e.includePatterns?.[0]??e.resourceId??"");if(!Cu.test(r))throw Error("Volume backups require a valid named-volume resource identifier.");if(!await this.runtime.exists(r))throw Error(`Volume ${r} was not found.`);let n=await this.runtime.export(r),i=Buffer.from(Bun.gunzipSync(Uint8Array.from(n))),o=e.compression??"gzip",s=o==="gzip"?n:Qo(i,o),c=String(t.operation?.id??new Date().toISOString()).replace(/[^A-Za-z0-9]/g,"").slice(0,32);return{mode:"object",key:`${e.projectId}/volumes/${r}/${c}.tar${o==="none"?"":o==="gzip"?".gz":".zst"}`,body:s,contentType:o==="gzip"?"application/gzip":o==="zstd"?"application/zstd":"application/x-tar",toolVersion:"alpine-tar",manifest:{format:"docker-volume-tar-v1",archive:"tar",compression:o,sourceVolume:r}}}async restore(e,t,r,n){if(!t)throw Error("Volume backup body is unavailable.");let i=String(e.manifest.sourceVolume??e.resourceId??""),o=String(r.volumeName??r.targetId??"");if(!Cu.test(o))throw Error("Volume restore requires a valid target volume name.");if(o===i&&r.inPlace!==!0)throw Error("An isolated volume restore requires a distinct target.");let s=await this.runtime.exists(o);if(!r.inPlace&&s)throw Error(`Restore target volume ${o} already exists.`);if(r.inPlace===!0&&o!==i)throw Error("An in-place volume restore must target the source volume.");if(r.inPlace===!0&&!s)throw Error("The in-place target volume was not found.");let c=String(e.manifest.compression??"gzip"),u=c==="gzip"?Buffer.from(t):Buffer.from(Bun.gzipSync(Uint8Array.from(Ji(t,c))));await this.runtime.import(o,u,r.inPlace===!0);let a=await this.runtime.probe(o);return{volumeName:o,healthy:!0,...a}}async cleanup(e,t){if(e.inPlace===!0)throw Error("In-place volume restores cannot be cleaned as drills.");let r=String(e.volumeName??e.targetId??"");if(!Cu.test(r))throw Error("Volume cleanup requires a valid target volume name.");await this.runtime.remove(r)}}import{existsSync as Tu}from"node:fs";import{mkdir as _v,readFile as sm,rm as Nv,writeFile as am}from"node:fs/promises";import{basename as pm,resolve as Ro,sep as cm}from"node:path";import{Database as Mv}from"bun:sqlite";function dm(e){let t=String(e.targetId??e.path??"");if(!/^[A-Za-z0-9][A-Za-z0-9_.-]{1,127}$/.test(t))throw Error("Control-plane restores require a safe target name.");return t}function um(e){let t=JSON.parse(Buffer.from(e).toString());if(t.format!=="ts-cloud-control-plane-v1"||!t.database)throw Error("Control-plane backup archive is invalid.");if(!Array.isArray(t.config)||t.config.some((r)=>pm(r.name)!==r.name))throw Error("Control-plane backup contains an unsafe config path.");return t}function lm(e){let t=Mv.deserialize(Uint8Array.from(e));try{let r=t.query("PRAGMA integrity_check").get()?.integrity_check??"unknown",n=t.query("SELECT count(*) AS count FROM sqlite_master WHERE type='table'").get()?.count??0;if(r!=="ok")throw Error(`Restored control-plane integrity check failed: ${r}.`);return{integrity:r,tables:n}}finally{t.close()}}class Au{controlPlane;root;restoreRoot;constructor(e,t,r=A(t,"restores","control-plane")){this.controlPlane=e;this.root=Ro(t),this.restoreRoot=Ro(r)}async create(e,t){let r=e.includePatterns.length?e.includePatterns:["cloud.config.ts"],n=[];for(let u of r){let a=pm(u),f=Ro(this.root,a);if(a!==u&&u!==`./${a}`)throw Error("Control-plane config paths must be project-root files.");if(Tu(f))n.push({name:a,body:(await sm(f)).toString("base64")})}let i={format:"ts-cloud-control-plane-v1",createdAt:new Date().toISOString(),database:Buffer.from(this.controlPlane.database.serialize()).toString("base64"),config:n},o=e.compression??"none",s=Qo(Buffer.from(JSON.stringify(i)),o),c=String(t.operation?.id??i.createdAt).replace(/[^A-Za-z0-9]/g,"").slice(0,32);return{mode:"object",key:`${e.projectId}/control-plane/${c}.json${o==="none"?"":o==="gzip"?".gz":".zst"}`,body:s,contentType:o==="gzip"?"application/gzip":o==="zstd"?"application/zstd":"application/vnd.ts-cloud.control-plane+json",manifest:{format:i.format,configFiles:n.map((u)=>u.name),sensitive:!0,compression:o},toolVersion:"bun-sqlite-serialize"}}async restore(e,t,r,n){if(!t)throw Error("Control-plane restore requires an archive payload.");if(r.restoreMode==="in_place")throw Error("A live control plane can only be restored into an isolated recovery target.");let i=um(Ji(t,String(e.manifest.compression??"none"))),o=Ro(this.restoreRoot,dm(r));if(Tu(o))throw Error("The isolated control-plane restore target already exists.");await _v(o,{recursive:!0,mode:448}),await am(Ro(o,"control-plane.sqlite"),Buffer.from(i.database,"base64"),{mode:384});for(let s of i.config)await am(Ro(o,s.name),Buffer.from(s.body,"base64"),{mode:384});return{path:o,isolated:!0,configFiles:i.config.length}}async verify(e,t,r){let n=um(Ji(t,String(e.manifest.compression??"none")));return{...lm(Buffer.from(n.database,"base64")),configFiles:n.config.length}}async validateHealth(e,t){let r=String(e.path??""),n=Ro(r,"control-plane.sqlite");if(!r.startsWith(`${this.restoreRoot}${cm}`)||!Tu(n))throw Error("Isolated control-plane database was not found.");return{healthy:!0,...lm(await sm(n))}}async cleanup(e,t){let r=Ro(this.restoreRoot,dm(e));if(!r.startsWith(`${this.restoreRoot}${cm}`))throw Error("Refusing to clean a control-plane restore outside the restore root.");await Nv(r,{recursive:!0,force:!0})}}import{createHash as $v}from"node:crypto";function ku(e,t){return e.find((r)=>r.startsWith(`${t}:`))?.slice(t.length+1)}function Lv(e){let t=ku(e.includePatterns,"resource")??e.includePatterns.find((i)=>i.startsWith("arn:")),r=ku(e.includePatterns,"role"),n=ku(e.includePatterns,"vault")??"Default";if(!t?.startsWith("arn:"))throw Error("Infrastructure backups require resource:<arn> in include patterns.");if(!r?.startsWith("arn:"))throw Error("Infrastructure backups require role:<iam-role-arn> in include patterns.");if(!/^[A-Za-z0-9_.-]{2,50}$/.test(n))throw Error("Infrastructure backup vault name is invalid.");return{resourceArn:t,roleArn:r,vaultName:n}}async function Bv(e,t,r){for(;;){r.throwIfCancellationRequested(),r.heartbeat();let n=await e.describeBackupJob(t),i=String(n.State??"");if(r.checkpoint("provider_backup",`AWS Backup job ${t} is ${i||"pending"}.`),i==="COMPLETED"&&n.RecoveryPointArn)return{recoveryPointArn:n.RecoveryPointArn,sizeBytes:Number(n.BackupSizeInBytes??0)};if(["ABORTED","EXPIRED","FAILED"].includes(i))throw Error(`AWS Backup job ${t} failed: ${n.StatusMessage??i}.`);await Bun.sleep(5000)}}async function Fv(e,t,r){for(;;){r.throwIfCancellationRequested(),r.heartbeat();let n=await e.describeRestoreJob(t),i=String(n.Status??"");if(r.checkpoint("provider_restore",`AWS Backup restore ${t} is ${i||"pending"}.`),i==="COMPLETED"&&n.CreatedResourceArn)return n.CreatedResourceArn;if(["ABORTED","FAILED"].includes(i))throw Error(`AWS Backup restore ${t} failed: ${n.StatusMessage??i}.`);await Bun.sleep(5000)}}class Ru{client;constructor(e=new Sa){this.client=e}async create(e,t){let r=Lv(e),n=String(t.operation.id).replace(/[^A-Za-z0-9-]/g,"").slice(0,64),i=await this.client.startBackupJob({BackupVaultName:r.vaultName,ResourceArn:r.resourceArn,IamRoleArn:r.roleArn,IdempotencyToken:n}),o=await Bv(this.client,i.BackupJobId,t),s=`sha256:${$v("sha256").update(o.recoveryPointArn).digest("hex")}`;return{mode:"external",uri:o.recoveryPointArn,checksum:s,sizeBytes:o.sizeBytes,toolVersion:"aws-backup-api",manifest:{provider:"aws_backup",resourceArn:r.resourceArn,roleArn:r.roleArn,vaultName:r.vaultName,providerBackupJobId:i.BackupJobId,recoveryPointArn:o.recoveryPointArn}}}async verifyExternal(e,t){let r=String(e.manifest.providerBackupJobId??""),n=await this.client.describeBackupJob(r);if(n.State!=="COMPLETED"||n.RecoveryPointArn!==e.uri)throw Error(`AWS Backup recovery point verification failed: ${n.StatusMessage??n.State??"unknown"}.`);return{state:n.State,recoveryPointArn:n.RecoveryPointArn,sizeBytes:Number(n.BackupSizeInBytes??e.sizeBytes)}}async restore(e,t,r,n){if(r.inPlace===!0)throw Error("AWS Backup infrastructure restores must create isolated resources.");let i=String(r.roleArn??e.manifest.roleArn??""),o=r.metadata&&typeof r.metadata==="object"&&!Array.isArray(r.metadata)?Object.fromEntries(Object.entries(r.metadata).map(([u,a])=>[u,String(a)])):{};if(!i.startsWith("arn:"))throw Error("AWS Backup restore requires an IAM role ARN.");if(!Object.keys(o).length)throw Error("AWS Backup restore requires provider restore metadata.");let s=await this.client.startRestoreJob({RecoveryPointArn:e.uri,IamRoleArn:i,Metadata:o,IdempotencyToken:String(n.operation.id).replace(/[^A-Za-z0-9-]/g,"").slice(0,64)}),c=await Fv(this.client,s.RestoreJobId,n);return{providerRestoreJobId:s.RestoreJobId,createdResourceArn:c,isolated:!0,healthy:!0}}async validateHealth(e,t){let r=String(e.createdResourceArn??"");return{healthy:r.startsWith("arn:"),createdResourceArn:r}}async deleteExternal(e,t){await this.client.deleteRecoveryPoint(String(e.manifest.vaultName??""),e.uri)}}import{existsSync as YI}from"node:fs";import{join as jf}from"node:path";import{pathToFileURL as XI}from"node:url";import{existsSync as gm,statSync as mm}from"fs";import{resolve as Ca}from"path";import jv from"process";import{existsSync as Vv,mkdirSync as Rx,readdirSync as Px,readFileSync as qv,writeFileSync as xx}from"fs";import{homedir as _s}from"os";import{dirname as _x,resolve as _i}from"path";import Zc from"process";import{existsSync as fm,statSync as hm}from"fs";import{existsSync as Wu,mkdirSync as Gv,readdirSync as Jv,writeFileSync as Hv}from"fs";import{homedir as Ns}from"os";import{dirname as ym,resolve as an}from"path";import Zo from"process";import{join as Wv,relative as Kv,resolve as bm}from"path";import jc from"process";import{existsSync as of,mkdirSync as Vx,readdirSync as qx,writeFileSync as Gx}from"fs";import{homedir as Pu}from"os";import{dirname as Wx,resolve as en}from"path";import Ta from"process";import{join as Qv,relative as Yv,resolve as Sm}from"path";import Uc from"process";import{existsSync as sf,mkdirSync as Zx,readdirSync as eD,writeFileSync as tD}from"fs";import{dirname as nD,resolve as zc}from"path";import Ku from"process";import{Buffer as Do}from"buffer";import{createCipheriv as Xv,createDecipheriv as Zv,randomBytes as xu}from"crypto";import{closeSync as Du,createReadStream as vm,createWriteStream as ew,existsSync as Ou,fsyncSync as wm,openSync as Im,writeFileSync as tw}from"fs";import{access as rw,constants as Cm,mkdir as nw,readdir as Sc,rename as Em,stat as Ms,unlink as wc,writeFile as _u}from"fs/promises";import{join as Bs}from"path";import Er from"process";import{pipeline as iw}from"stream/promises";import{createGzip as Tm}from"zlib";import Fs from"process";import Qi from"process";import{Buffer as Wi}from"buffer";import{createCipheriv as ow,createDecipheriv as sw,randomBytes as Nu}from"crypto";import{closeSync as Mu,createReadStream as Am,createWriteStream as aw,existsSync as Ic,fsyncSync as km,openSync as Rm,writeFileSync as cw}from"fs";import{access as dw,constants as Pm,mkdir as uw,readdir as Ec,rename as xm,stat as Us,unlink as Tc,writeFile as $u}from"fs/promises";import{isAbsolute as lw,join as zs,resolve as pw}from"path";import vt from"process";import{pipeline as gw}from"stream/promises";import{createGzip as Dm}from"zlib";import qs from"process";import Xi from"process";import Ac from"process";import{existsSync as kc}from"fs";import{resolve as Lu}from"path";import{existsSync as mw}from"fs";import{existsSync as fw,readdirSync as hw}from"fs";import{extname as Bu,resolve as Om}from"path";import yw from"process";import{join as bw,relative as Sw,resolve as _m}from"path";import Vc from"process";import{Buffer as Ki}from"buffer";import{createCipheriv as vw,createDecipheriv as ww,randomBytes as Fu}from"crypto";import{closeSync as ju,createReadStream as Nm,createWriteStream as Iw,existsSync as Rc,fsyncSync as Mm,openSync as $m,writeFileSync as Cw}from"fs";import{access as Ew,constants as Lm,mkdir as Tw,readdir as Pc,rename as Bm,stat as Gs,unlink as xc,writeFile as Uu}from"fs/promises";import{isAbsolute as Aw,join as Js,resolve as kw}from"path";import wt from"process";import{pipeline as Rw}from"stream/promises";import{createGzip as Fm}from"zlib";import Hs from"process";import Zi from"process";import Oc from"process";import{existsSync as _c}from"fs";import{resolve as Zm}from"path";import{existsSync as WI}from"fs";class ef{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),o=n??this.options.ttl,s=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:o,hits:0,size:s}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!gm(e))return!0;return mm(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,n){try{let i=gm(r)?mm(r):null,o=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:o},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class tf{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let o=await t(),s=performance.now()-n;return this.recordMetric({operation:e,duration:s,timestamp:i,...r}),o}catch(o){let s=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:s,timestamp:i,...r}),o}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,o)=>i+o,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}var Fc=new ef,sl=new tf;var rf=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function nf(e={}){let{name:t="",alias:r}=e,n=["config",".config"];if(t)n.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let i=r===void 0?[]:Array.isArray(r)?r:[r];for(let o of i){if(!o)continue;if(n.push(o,`.${o}.config`,`${o}.config`,`.${o}`),t)n.push(`${t}.${o}.config`,`.${t}.${o}.config`)}return Array.from(new Set(n.filter(Boolean)))}function Uv(e){return nf(e).flatMap((r)=>rf.map((n)=>Ca(e.directory,`${r}${n}`)))}function zv(e={}){let t=Ca(e.cwd||jv.cwd());return Array.from(new Set([t,Ca(t,"config"),Ca(t,".config"),e.configDir?Ca(t,e.configDir):void 0].filter((r)=>Boolean(r))))}var Pw=Object.defineProperty,xw=(e)=>e;function Dw(e,t){this[e]=xw.bind(null,t)}var Ow=(e,t)=>{for(var r in t)Pw(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Dw.bind(t,r)})},_w=(e,t)=>()=>(e&&(t=e(e=0)),t),af={};Ow(af,{withErrorRecovery:()=>uf,tryLoadConfig:()=>rI,loadConfigWithResult:()=>eI,loadConfig:()=>ff,isRetryableError:()=>Ww,isConfigNotFoundError:()=>Hw,isBunfigError:()=>lf,globalPerformanceMonitor:()=>Ra,globalCache:()=>Ws,getEnvOrDefault:()=>Kw,generateConfigTypes:()=>nI,defaultGeneratedDir:()=>Cf,defaultConfigDir:()=>If,deepMergeWithArrayStrategy:()=>ll,deepMerge:()=>pf,createLibraryConfig:()=>iI,config:()=>tI,bunfigPlugin:()=>oI,applyEnvVarsToConfig:()=>Ea,TypeGenerationError:()=>rl,SchemaValidationError:()=>ka,PluginError:()=>il,PerformanceMonitor:()=>cl,FileSystemError:()=>tl,ErrorFactory:()=>Oo,EnvVarError:()=>Kc,EnvProcessor:()=>ed,ConfigValidator:()=>pl,ConfigValidationError:()=>Zu,ConfigNotFoundError:()=>Wc,ConfigMergeError:()=>el,ConfigLoader:()=>gl,ConfigLoadError:()=>Aa,ConfigFileLoader:()=>td,ConfigCache:()=>al,CacheUtils:()=>yf,BunfigError:()=>wn,BrowserConfigError:()=>nl,ArrayMergeStrategies:()=>vf});class al{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),o=n??this.options.ttl,s=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:o,hits:0,size:s}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!fm(e))return!0;return hm(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,n){try{let i=fm(r)?hm(r):null,o=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:o},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class cl{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let o=await t(),s=performance.now()-n;return this.recordMetric({operation:e,duration:s,timestamp:i,...r}),o}catch(o){let s=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:s,timestamp:i,...r}),o}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,o)=>i+o,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function Nw(e,t={}){let n=Object.keys(t).sort().map((i)=>`${i}:${t[i]}`).join("|");return n?`${e}:${n}`:e}function Mw(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function $w(e){return e.getStats().size*2}function dl(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Bt(t[0])&&"id"in t[0]&&t[0].id===3&&Bt(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Bt(t)&&Bt(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(Bt(e)&&"arr"in e&&Array.isArray(e.arr)&&Bt(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Bt(t[0])&&Bt(e[0])){let n=[...t];for(let i of e)if(Bt(i)&&"name"in i){if(!n.find((s)=>Bt(s)&&("name"in s)&&s.name===i.name))n.push(i)}else if(Bt(i)&&"path"in i){if(!n.find((s)=>Bt(s)&&("path"in s)&&s.path===i.path))n.push(i)}else if(!n.some((o)=>qc(o,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!Bt(t)||!Bt(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(Bt(i)&&Bt(r[n]))r[n]=dl(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&Bt(i[0])&&Bt(r[n][0])){let o=[...i];for(let s of r[n])if(Bt(s)&&"name"in s){if(!o.find((u)=>Bt(u)&&("name"in u)&&u.name===s.name))o.push(s)}else if(Bt(s)&&"path"in s){if(!o.find((u)=>Bt(u)&&("path"in u)&&u.path===s.path))o.push(s)}else if(!o.some((c)=>qc(c,s)))o.push(s);r[n]=o}else if(i.every((o)=>typeof o==="string")&&r[n].every((o)=>typeof o==="string")){let o=[...i];for(let s of r[n])if(!o.includes(s))o.push(s);r[n]=o}else r[n]=i;else r[n]=i}return r}function qc(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!qc(e[r],t[r]))return!1;return!0}if(Bt(e)&&Bt(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!qc(e[i],t[i]))return!1}return!0}return!1}function Bt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Lw(e,t){if(!sf(e))return null;try{let r=await import(e),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return dl(t,n)}catch{return null}}catch{return null}}async function Bw({name:e="",cwd:t,defaultConfig:r}){let n=t||Ku.cwd(),i=[".ts",".js",".mjs",".cjs",".json"],o=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let s of o)for(let c of i){let u=zc(n,`${s}${c}`),a=await Lw(u,r);if(a!==null)return a}try{let s=zc(n,"package.json");if(sf(s)){let u=(await import(s))[e];if(u&&typeof u==="object"&&!Array.isArray(u))try{return dl(r,u)}catch{}}}catch{}return r}function Fw(e,t={}){let r=Uc.cwd();while(r.includes("storage"))r=Sm(r,"..");let n=Sm(r,e||"");if(t?.relative)return Yv(Uc.cwd(),n);return n}async function jw(){try{let e=await Bw({name:"clarity",defaultConfig:Mc,cwd:Uc.cwd(),endpoint:"",headers:{}});return{...Mc,...e}}catch{return Mc}}function qt(){if(Qi.env.NODE_ENV==="test"||Qi.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Uw(){if(Qi.env.NODE_ENV==="test"||Qi.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Qi<"u"){let e=Qi.type;if(e==="renderer"||e==="worker")return!1;return!!(Qi.versions&&(Qi.versions.node||Qi.versions.bun))}return!1}class cf{async format(e){let t=await Uw(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Fs.pid,hostname:t(),environment:Fs.env.NODE_ENV||"development",platform:Fs.platform,version:Fs.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Fs.env.NODE_ENV||Fs.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Gc{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...Yu},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new cf,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??Er.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),o=this.generateKey();this.currentKeyId=i,this.keys.set(i,o),this.encryptionKeys.set(i,{key:o,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...$c,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...$c};return{...$c,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Yu.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let r=(async()=>{let i,o=0,s=3,c=1000;while(o<s)try{try{try{await rw(this.config.logDirectory,Cm.F_OK|Cm.W_OK)}catch(a){if(a instanceof Error&&"code"in a)if(a.code==="ENOENT")await nw(this.config.logDirectory,{recursive:!0,mode:493});else if(a.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw a;else throw a}}catch(a){throw console.error("Debug: [writeToFile] Failed to create log directory:",a),a}let u=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Do.from(e);try{if(!Ou(this.currentLogFile))await _u(this.currentLogFile,"",{mode:420});if(i=Im(this.currentLogFile,"a",420),tw(i,u,{flag:"a"}),wm(i),i!==void 0)Du(i),i=void 0;if((await Ms(this.currentLogFile)).size===0){if(await _u(this.currentLogFile,u,{flag:"w",mode:420}),(await Ms(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(a){let f=a;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(o<s-1){let T=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${o+1}/${s}:`,T);let R=c*2**o;await new Promise((D)=>setTimeout(D,R)),o++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(i!==void 0)try{Du(i)}catch(a){console.error("Debug: [writeToFile] Error closing file descriptor:",a)}}}catch(u){if(o===s-1){let f=u,T=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",T),u}o++;let a=c*2**(o-1);await new Promise((f)=>setTimeout(f,a))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Bs(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Bs(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Bs(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(qt())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,c],[,u])=>u.createdAt.getTime()-c.createdAt.getTime()),o=typeof t.maxKeys==="number"?t.maxKeys:1,s=Math.max(1,o);if(i.length>s)for(let[c]of i.slice(s))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return xu(16).toString("hex")}generateKey(){return xu(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=xu(16),n=Xv("aes-256-gcm",t,r),i=Do.concat([n.update(e,"utf8"),n.final()]),o=n.getAuthTag();return{encrypted:Do.concat([r,i,o]),iv:r}}async compressData(e){return new Promise((t,r)=>{let n=Tm(),i=[];n.on("data",(o)=>i.push(o)),n.on("end",()=>t(Do.from(Do.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(qt())return;let e=await Ms(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await Sc(this.config.logDirectory),o=i.filter((u)=>u.startsWith(this.name)&&/\.log\.\d+$/.test(u)).sort((u,a)=>{let f=Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),s=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await Ms(r).catch(()=>null))try{if(await Em(r,c),t.compress)try{let u=`${c}.gz`;await this.compressLogFile(c,u),await wc(c)}catch(u){console.error("Error compressing rotated file:",u)}if(o.length===0&&!i.some((u)=>u.endsWith(".log.1")))try{let u=`${r}.1`;await _u(u,"")}catch(u){console.error("Error creating backup file:",u)}}catch(u){console.error(`Error during rotation: ${u instanceof Error?u.message:String(u)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),o=r.replace(/\.log$/,`-${i}.log`);if(await Ms(r).catch(()=>null))await Em(r,o)}if(this.currentLogFile=n,t.maxFiles){let o=(await Sc(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,c)=>c.localeCompare(s));for(let s of o.slice(t.maxFiles))await wc(Bs(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=vm(e),n=ew(t),i=Tm();await iw(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Ou(this.currentLogFile))try{let e=Im(this.currentLogFile,"r+");wm(e),Du(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!qt()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Sc(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await wc(Bs(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?Pt.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:o,showTimestamp:s=!0}=e,c=(D)=>D.replace(this.ANSI_PATTERN,"");if(!this.fancy){let D=[];if(s)D.push(t);if(o==="warning")D.push("WARN");else if(o==="error")D.push("ERROR");else if(r)D.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)D.push(n.replace(/[[\]]/g,""));return D.push(i),D.join(" ")}let u=Er.stdout.columns||120,a="";if(o==="warning"||o==="error")a=`${r} ${i}`;else if(o==="info"||o==="success")a=`${r} ${n} ${i}`;else a=`${r} ${n} ${Pt.cyan(i)}`;if(!s)return a.trim();let f=c(a).trim().length,T=c(t).length,R=Math.max(1,u-2-f-T);return`${a.trim()}${" ".repeat(R)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(o,s)=>{let c=Number.parseInt(s,10);return c<t[0].length?String(t[0][c]):o});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(o,s)=>{if(s==="%")return"%";if(n>=t.length)return o;let c=t[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return o}});if(n<t.length)i+=` ${t.slice(n).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return i}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),o=this.formatFileTimestamp(n),s,c;if(t instanceof Error)s=t.message,c=t.stack;else s=this.formatMessage(t,r);if(this.fancy&&!qt()){let a=bf[e],f=this.options.showTags!==!1&&this.name?Pt.gray(this.formatTag(this.name)):"",T;switch(e){case"debug":T=this.formatConsoleMessage({timestamp:i,icon:a,tag:f,message:Pt.gray(s),level:e}),console.error(T);break;case"info":T=this.formatConsoleMessage({timestamp:i,icon:a,tag:f,message:s,level:e}),console.error(T);break;case"success":T=this.formatConsoleMessage({timestamp:i,icon:a,tag:f,message:Pt.green(s),level:e}),console.error(T);break;case"warning":T=this.formatConsoleMessage({timestamp:i,icon:a,tag:f,message:s,level:e}),console.warn(T);break;case"error":if(T=this.formatConsoleMessage({timestamp:i,icon:a,tag:f,message:s,level:e}),console.error(T),c){let R=c.split(`
60
+ `).filter(Boolean);if(r.some((n)=>!Ov(n)))throw Error("Backup archive contains an unsafe path.");return{entries:r,bytes:e.byteLength}}}function nm(e,t){if(!t.trim())throw Error("File backup paths cannot be empty.");let r=Zr(e,t),n=Dv(e,r);if(n===".."||n.startsWith(`..${bc}`)||n==="")throw Error(`File backup path ${t} is outside the project root.`);return n}function hc(e){let t=String(e.targetId??e.path??"");if(!/^[A-Za-z0-9][A-Za-z0-9_.-]{1,127}$/.test(t))throw Error("File restores require a safe target name.");return t}class wu{runtime;root;restoreRoot;constructor(e,t=new im,r=A(e,"restores","files")){this.runtime=t;this.root=Zr(e),this.restoreRoot=Zr(r)}paths(e){let t=[...new Set(e.includePatterns.map((r)=>nm(this.root,r)))];if(!t.length)throw Error("File backup policies require at least one project-relative path.");for(let r of t)if(!wa(Zr(this.root,r)))throw Error(`File backup path ${r} was not found.`);return t.filter((r)=>!t.some((n)=>n!==r&&r.startsWith(`${n}${bc}`)))}async create(e,t){let r=this.paths(e),n=await this.runtime.create(this.root,r,e.excludePatterns),i=await this.runtime.inspect(n),o=e.compression??"none",s=Qo(n,o),c=String(t.operation?.id??new Date().toISOString()).replace(/[^A-Za-z0-9]/g,"").slice(0,32);return{mode:"object",key:`${e.projectId}/files/${c}.tar${o==="none"?"":o==="gzip"?".gz":".zst"}`,body:s,contentType:o==="gzip"?"application/gzip":o==="zstd"?"application/zstd":"application/x-tar",manifest:{archive:"tar",compression:o,sourcePaths:r,excluded:e.excludePatterns,entries:i.entries.length},toolVersion:"system-tar"}}async restore(e,t,r,n){if(!t)throw Error("File restore requires an archive payload.");let i=Ji(t,String(e.manifest.compression??"none"));if(await this.runtime.inspect(i),r.restoreMode==="in_place"){let s=Zr(this.restoreRoot,`.staging-${hc(r)}`),c=Zr(this.restoreRoot,`.rollback-${hc(r)}`),u=Array.isArray(e.manifest.sourcePaths)?e.manifest.sourcePaths.map(String):[];if(!u.length)throw Error("File recovery point has no source path manifest.");await xs(s,{recursive:!0,force:!0}),await xs(c,{recursive:!0,force:!0}),await this.runtime.extract(i,s),await yc(c,{recursive:!0,mode:448});let a=[];try{for(let f of u){let T=Zr(this.root,nm(this.root,f)),R=Zr(s,f),D=Zr(c,f);if(await yc(Zr(D,".."),{recursive:!0}),wa(T))await Su(T,D);await yc(Zr(T,".."),{recursive:!0}),await Su(R,T),a.push(f)}}catch(f){for(let T of a.reverse()){let R=Zr(this.root,T),D=Zr(c,T);if(await xs(R,{recursive:!0,force:!0}),wa(D))await Su(D,R)}throw f}finally{await xs(s,{recursive:!0,force:!0})}return await xs(c,{recursive:!0,force:!0}),{path:this.root,restoredPaths:u,inPlace:!0}}let o=Zr(this.restoreRoot,hc(r));if(wa(o))throw Error("The isolated file restore target already exists.");return await this.runtime.extract(i,o),{path:o,isolated:!0}}async verify(e,t,r){let n=Ji(t,String(e.manifest.compression??"none")),i=await this.runtime.inspect(n);return{archive:"tar",entries:i.entries.length,uncompressedBytes:i.bytes}}async validateHealth(e,t){let r=String(e.path??"");if(!r||!r.startsWith(`${this.restoreRoot}${bc}`)||!wa(r))throw Error("Isolated file restore target was not found.");let n=await xv(r);return{healthy:!0,path:r,topLevelEntries:n.length}}async cleanup(e,t){let r=hc(e),n=Zr(this.restoreRoot,r);if(!n.startsWith(`${this.restoreRoot}${bc}`))throw Error("Refusing to clean a file restore outside the restore root.");await xs(n,{recursive:!0,force:!0})}}class Iu{services;secrets;transport;constructor(e,t,r=new ot){this.services=e;this.secrets=t;this.transport=r}async create(e,t){if(!e.dataServiceId)throw Error("Logical database backups require a data service.");let r=this.services.get(e.dataServiceId);if(!r)throw Error("Logical database service was not found.");if(!["container","server"].includes(r.provider))throw Error("Logical database backups require an on-box data service.");let n=await this.transport.exportLogicalBackup(r.id),i=e.compression??"none",o=Qo(n.body,i),s=String(t.operation?.id??new Date().toISOString()).replace(/[^A-Za-z0-9]/g,"").slice(0,32);return{mode:"object",key:`${e.projectId}/databases/${r.id}/${s}.sql${i==="none"?"":i==="gzip"?".gz":".zst"}`,body:o,contentType:i==="gzip"?"application/gzip":i==="zstd"?"application/zstd":"application/sql",engineVersion:n.engineVersion,toolVersion:"engine-native",manifest:{format:"logical-sql-v1",sourceDataServiceId:r.id,engine:n.engine,database:n.database,username:n.username,compression:i}}}async restore(e,t,r,n){if(!t)throw Error("Logical database backup body is unavailable.");let i=String(e.dataServiceId??e.manifest.sourceDataServiceId??""),o=String(r.dataServiceId??r.targetId??""),s=r.inPlace===!0;if(!i||!o)throw Error("Logical database restore requires source and target identifiers.");if(s&&o!==i)throw Error("An in-place restore must target the source data service.");let c=this.services.get(i);if(!c?.credentialRef)throw Error("Logical database credential reference was not found.");let u=await this.secrets.resolve(c.credentialRef);return this.transport.restoreLogicalBackup({sourceId:i,targetId:o,body:Ji(t,String(e.manifest.compression??"none")),credential:u,inPlace:s})}async cleanup(e,t){if(e.inPlace===!0)throw Error("In-place database restores cannot be cleaned as drills.");let r=String(e.dataServiceId??e.targetId??"");if(!r)throw Error("Database cleanup requires a target identifier.");await this.transport.removeRestoredService(r)}}var Cu=/^[A-Za-z0-9][A-Za-z0-9_.-]{1,127}$/;async function Yo(e,t,r=!1){let n=Bun.spawn(["docker",...e],{stdin:t?"pipe":"ignore",stdout:"pipe",stderr:"pipe"}),i=new Response(n.stdout).arrayBuffer(),o=new Response(n.stderr).text();if(t)n.stdin.write(t),n.stdin.end();let[s,c,u]=await Promise.all([n.exited,i,o]);if(s!==0&&!r)throw Error(`Docker volume command failed (${s}): ${u.trim()}`);return{code:s,stdout:Buffer.from(c),stderr:u}}class om{async exists(e){return(await Yo(["volume","inspect",e],void 0,!0)).code===0}async export(e){return(await Yo(["run","--rm","-v",`${e}:/source:ro`,"alpine:3.21","tar","-C","/source","-czf","-","."])).stdout}async import(e,t,r=!1){if(!await this.exists(e))await Yo(["volume","create",e]);try{if(r)await Yo(["run","--rm","-v",`${e}:/target`,"alpine:3.21","sh","-c","find /target -mindepth 1 -delete"]);await Yo(["run","--rm","-i","-v",`${e}:/target`,"alpine:3.21","tar","-C","/target","--no-same-owner","-xzf","-"],t)}catch(n){throw await this.remove(e),n}}async remove(e){await Yo(["volume","rm",e],void 0,!0)}async probe(e){let t=(await Yo(["run","--rm","-v",`${e}:/target:ro`,"alpine:3.21","sh","-c",`find /target -mindepth 1 -printf '%s\\n' | awk '{n+=1;b+=$1} END {print n ":" b}'`])).stdout.toString(),[r,n]=t.trim().split(":").map(Number);if(!Number.isFinite(r)||!Number.isFinite(n))throw Error("Restored volume health probe returned invalid output.");return{entries:r,bytes:n}}}class Eu{runtime;constructor(e=new om){this.runtime=e}async create(e,t){let r=String(e.includePatterns?.[0]??e.resourceId??"");if(!Cu.test(r))throw Error("Volume backups require a valid named-volume resource identifier.");if(!await this.runtime.exists(r))throw Error(`Volume ${r} was not found.`);let n=await this.runtime.export(r),i=Buffer.from(Bun.gunzipSync(Uint8Array.from(n))),o=e.compression??"gzip",s=o==="gzip"?n:Qo(i,o),c=String(t.operation?.id??new Date().toISOString()).replace(/[^A-Za-z0-9]/g,"").slice(0,32);return{mode:"object",key:`${e.projectId}/volumes/${r}/${c}.tar${o==="none"?"":o==="gzip"?".gz":".zst"}`,body:s,contentType:o==="gzip"?"application/gzip":o==="zstd"?"application/zstd":"application/x-tar",toolVersion:"alpine-tar",manifest:{format:"docker-volume-tar-v1",archive:"tar",compression:o,sourceVolume:r}}}async restore(e,t,r,n){if(!t)throw Error("Volume backup body is unavailable.");let i=String(e.manifest.sourceVolume??e.resourceId??""),o=String(r.volumeName??r.targetId??"");if(!Cu.test(o))throw Error("Volume restore requires a valid target volume name.");if(o===i&&r.inPlace!==!0)throw Error("An isolated volume restore requires a distinct target.");let s=await this.runtime.exists(o);if(!r.inPlace&&s)throw Error(`Restore target volume ${o} already exists.`);if(r.inPlace===!0&&o!==i)throw Error("An in-place volume restore must target the source volume.");if(r.inPlace===!0&&!s)throw Error("The in-place target volume was not found.");let c=String(e.manifest.compression??"gzip"),u=c==="gzip"?Buffer.from(t):Buffer.from(Bun.gzipSync(Uint8Array.from(Ji(t,c))));await this.runtime.import(o,u,r.inPlace===!0);let a=await this.runtime.probe(o);return{volumeName:o,healthy:!0,...a}}async cleanup(e,t){if(e.inPlace===!0)throw Error("In-place volume restores cannot be cleaned as drills.");let r=String(e.volumeName??e.targetId??"");if(!Cu.test(r))throw Error("Volume cleanup requires a valid target volume name.");await this.runtime.remove(r)}}import{existsSync as Tu}from"node:fs";import{mkdir as _v,readFile as sm,rm as Nv,writeFile as am}from"node:fs/promises";import{basename as pm,resolve as Ro,sep as cm}from"node:path";import{Database as Mv}from"bun:sqlite";function dm(e){let t=String(e.targetId??e.path??"");if(!/^[A-Za-z0-9][A-Za-z0-9_.-]{1,127}$/.test(t))throw Error("Control-plane restores require a safe target name.");return t}function um(e){let t=JSON.parse(Buffer.from(e).toString());if(t.format!=="ts-cloud-control-plane-v1"||!t.database)throw Error("Control-plane backup archive is invalid.");if(!Array.isArray(t.config)||t.config.some((r)=>pm(r.name)!==r.name))throw Error("Control-plane backup contains an unsafe config path.");return t}function lm(e){let t=Mv.deserialize(Uint8Array.from(e));try{let r=t.query("PRAGMA integrity_check").get()?.integrity_check??"unknown",n=t.query("SELECT count(*) AS count FROM sqlite_master WHERE type='table'").get()?.count??0;if(r!=="ok")throw Error(`Restored control-plane integrity check failed: ${r}.`);return{integrity:r,tables:n}}finally{t.close()}}class Au{controlPlane;root;restoreRoot;constructor(e,t,r=A(t,"restores","control-plane")){this.controlPlane=e;this.root=Ro(t),this.restoreRoot=Ro(r)}async create(e,t){let r=e.includePatterns.length?e.includePatterns:["cloud.config.ts"],n=[];for(let u of r){let a=pm(u),f=Ro(this.root,a);if(a!==u&&u!==`./${a}`)throw Error("Control-plane config paths must be project-root files.");if(Tu(f))n.push({name:a,body:(await sm(f)).toString("base64")})}let i={format:"ts-cloud-control-plane-v1",createdAt:new Date().toISOString(),database:Buffer.from(this.controlPlane.database.serialize()).toString("base64"),config:n},o=e.compression??"none",s=Qo(Buffer.from(JSON.stringify(i)),o),c=String(t.operation?.id??i.createdAt).replace(/[^A-Za-z0-9]/g,"").slice(0,32);return{mode:"object",key:`${e.projectId}/control-plane/${c}.json${o==="none"?"":o==="gzip"?".gz":".zst"}`,body:s,contentType:o==="gzip"?"application/gzip":o==="zstd"?"application/zstd":"application/vnd.ts-cloud.control-plane+json",manifest:{format:i.format,configFiles:n.map((u)=>u.name),sensitive:!0,compression:o},toolVersion:"bun-sqlite-serialize"}}async restore(e,t,r,n){if(!t)throw Error("Control-plane restore requires an archive payload.");if(r.restoreMode==="in_place")throw Error("A live control plane can only be restored into an isolated recovery target.");let i=um(Ji(t,String(e.manifest.compression??"none"))),o=Ro(this.restoreRoot,dm(r));if(Tu(o))throw Error("The isolated control-plane restore target already exists.");await _v(o,{recursive:!0,mode:448}),await am(Ro(o,"control-plane.sqlite"),Buffer.from(i.database,"base64"),{mode:384});for(let s of i.config)await am(Ro(o,s.name),Buffer.from(s.body,"base64"),{mode:384});return{path:o,isolated:!0,configFiles:i.config.length}}async verify(e,t,r){let n=um(Ji(t,String(e.manifest.compression??"none")));return{...lm(Buffer.from(n.database,"base64")),configFiles:n.config.length}}async validateHealth(e,t){let r=String(e.path??""),n=Ro(r,"control-plane.sqlite");if(!r.startsWith(`${this.restoreRoot}${cm}`)||!Tu(n))throw Error("Isolated control-plane database was not found.");return{healthy:!0,...lm(await sm(n))}}async cleanup(e,t){let r=Ro(this.restoreRoot,dm(e));if(!r.startsWith(`${this.restoreRoot}${cm}`))throw Error("Refusing to clean a control-plane restore outside the restore root.");await Nv(r,{recursive:!0,force:!0})}}import{createHash as $v}from"node:crypto";function ku(e,t){return e.find((r)=>r.startsWith(`${t}:`))?.slice(t.length+1)}function Lv(e){let t=ku(e.includePatterns,"resource")??e.includePatterns.find((i)=>i.startsWith("arn:")),r=ku(e.includePatterns,"role"),n=ku(e.includePatterns,"vault")??"Default";if(!t?.startsWith("arn:"))throw Error("Infrastructure backups require resource:<arn> in include patterns.");if(!r?.startsWith("arn:"))throw Error("Infrastructure backups require role:<iam-role-arn> in include patterns.");if(!/^[A-Za-z0-9_.-]{2,50}$/.test(n))throw Error("Infrastructure backup vault name is invalid.");return{resourceArn:t,roleArn:r,vaultName:n}}async function Bv(e,t,r){for(;;){r.throwIfCancellationRequested(),r.heartbeat();let n=await e.describeBackupJob(t),i=String(n.State??"");if(r.checkpoint("provider_backup",`AWS Backup job ${t} is ${i||"pending"}.`),i==="COMPLETED"&&n.RecoveryPointArn)return{recoveryPointArn:n.RecoveryPointArn,sizeBytes:Number(n.BackupSizeInBytes??0)};if(["ABORTED","EXPIRED","FAILED"].includes(i))throw Error(`AWS Backup job ${t} failed: ${n.StatusMessage??i}.`);await Bun.sleep(5000)}}async function Fv(e,t,r){for(;;){r.throwIfCancellationRequested(),r.heartbeat();let n=await e.describeRestoreJob(t),i=String(n.Status??"");if(r.checkpoint("provider_restore",`AWS Backup restore ${t} is ${i||"pending"}.`),i==="COMPLETED"&&n.CreatedResourceArn)return n.CreatedResourceArn;if(["ABORTED","FAILED"].includes(i))throw Error(`AWS Backup restore ${t} failed: ${n.StatusMessage??i}.`);await Bun.sleep(5000)}}class Ru{client;constructor(e=new Sa){this.client=e}async create(e,t){let r=Lv(e),n=String(t.operation.id).replace(/[^A-Za-z0-9-]/g,"").slice(0,64),i=await this.client.startBackupJob({BackupVaultName:r.vaultName,ResourceArn:r.resourceArn,IamRoleArn:r.roleArn,IdempotencyToken:n}),o=await Bv(this.client,i.BackupJobId,t),s=`sha256:${$v("sha256").update(o.recoveryPointArn).digest("hex")}`;return{mode:"external",uri:o.recoveryPointArn,checksum:s,sizeBytes:o.sizeBytes,toolVersion:"aws-backup-api",manifest:{provider:"aws_backup",resourceArn:r.resourceArn,roleArn:r.roleArn,vaultName:r.vaultName,providerBackupJobId:i.BackupJobId,recoveryPointArn:o.recoveryPointArn}}}async verifyExternal(e,t){let r=String(e.manifest.providerBackupJobId??""),n=await this.client.describeBackupJob(r);if(n.State!=="COMPLETED"||n.RecoveryPointArn!==e.uri)throw Error(`AWS Backup recovery point verification failed: ${n.StatusMessage??n.State??"unknown"}.`);return{state:n.State,recoveryPointArn:n.RecoveryPointArn,sizeBytes:Number(n.BackupSizeInBytes??e.sizeBytes)}}async restore(e,t,r,n){if(r.inPlace===!0)throw Error("AWS Backup infrastructure restores must create isolated resources.");let i=String(r.roleArn??e.manifest.roleArn??""),o=r.metadata&&typeof r.metadata==="object"&&!Array.isArray(r.metadata)?Object.fromEntries(Object.entries(r.metadata).map(([u,a])=>[u,String(a)])):{};if(!i.startsWith("arn:"))throw Error("AWS Backup restore requires an IAM role ARN.");if(!Object.keys(o).length)throw Error("AWS Backup restore requires provider restore metadata.");let s=await this.client.startRestoreJob({RecoveryPointArn:e.uri,IamRoleArn:i,Metadata:o,IdempotencyToken:String(n.operation.id).replace(/[^A-Za-z0-9-]/g,"").slice(0,64)}),c=await Fv(this.client,s.RestoreJobId,n);return{providerRestoreJobId:s.RestoreJobId,createdResourceArn:c,isolated:!0,healthy:!0}}async validateHealth(e,t){let r=String(e.createdResourceArn??"");return{healthy:r.startsWith("arn:"),createdResourceArn:r}}async deleteExternal(e,t){await this.client.deleteRecoveryPoint(String(e.manifest.vaultName??""),e.uri)}}import{existsSync as YI}from"node:fs";import{join as jf}from"node:path";import{pathToFileURL as XI}from"node:url";import{existsSync as gm,statSync as mm}from"fs";import{resolve as Ca}from"path";import jv from"process";import{existsSync as Vv,mkdirSync as Rx,readdirSync as Px,readFileSync as qv,writeFileSync as xx}from"fs";import{homedir as _s}from"os";import{dirname as _x,resolve as _i}from"path";import Zc from"process";import{existsSync as fm,statSync as hm}from"fs";import{existsSync as Wu,mkdirSync as Gv,readdirSync as Jv,writeFileSync as Hv}from"fs";import{homedir as Ns}from"os";import{dirname as ym,resolve as an}from"path";import Zo from"process";import{join as Wv,relative as Kv,resolve as bm}from"path";import jc from"process";import{existsSync as of,mkdirSync as Vx,readdirSync as qx,writeFileSync as Gx}from"fs";import{homedir as Pu}from"os";import{dirname as Wx,resolve as en}from"path";import Ta from"process";import{join as Qv,relative as Yv,resolve as Sm}from"path";import Uc from"process";import{existsSync as sf,mkdirSync as Zx,readdirSync as eD,writeFileSync as tD}from"fs";import{dirname as nD,resolve as zc}from"path";import Ku from"process";import{Buffer as Do}from"buffer";import{createCipheriv as Xv,createDecipheriv as Zv,randomBytes as xu}from"crypto";import{closeSync as Du,createReadStream as vm,createWriteStream as ew,existsSync as Ou,fsyncSync as wm,openSync as Im,writeFileSync as tw}from"fs";import{access as rw,constants as Cm,mkdir as nw,readdir as Sc,rename as Em,stat as Ms,unlink as wc,writeFile as _u}from"fs/promises";import{join as Bs}from"path";import Er from"process";import{pipeline as iw}from"stream/promises";import{createGzip as Tm}from"zlib";import Fs from"process";import Qi from"process";import{Buffer as Wi}from"buffer";import{createCipheriv as ow,createDecipheriv as sw,randomBytes as Nu}from"crypto";import{closeSync as Mu,createReadStream as Am,createWriteStream as aw,existsSync as Ic,fsyncSync as km,openSync as Rm,writeFileSync as cw}from"fs";import{access as dw,constants as Pm,mkdir as uw,readdir as Ec,rename as xm,stat as Us,unlink as Tc,writeFile as $u}from"fs/promises";import{isAbsolute as lw,join as zs,resolve as pw}from"path";import vt from"process";import{pipeline as gw}from"stream/promises";import{createGzip as Dm}from"zlib";import qs from"process";import Xi from"process";import Ac from"process";import{existsSync as kc}from"fs";import{resolve as Lu}from"path";import{existsSync as mw}from"fs";import{existsSync as fw,readdirSync as hw}from"fs";import{extname as Bu,resolve as Om}from"path";import yw from"process";import{join as bw,relative as Sw,resolve as _m}from"path";import Vc from"process";import{Buffer as Ki}from"buffer";import{createCipheriv as vw,createDecipheriv as ww,randomBytes as Fu}from"crypto";import{closeSync as ju,createReadStream as Nm,createWriteStream as Iw,existsSync as Rc,fsyncSync as Mm,openSync as $m,writeFileSync as Cw}from"fs";import{access as Ew,constants as Lm,mkdir as Tw,readdir as Pc,rename as Bm,stat as Gs,unlink as xc,writeFile as Uu}from"fs/promises";import{isAbsolute as Aw,join as Js,resolve as kw}from"path";import wt from"process";import{pipeline as Rw}from"stream/promises";import{createGzip as Fm}from"zlib";import Hs from"process";import Zi from"process";import Oc from"process";import{existsSync as _c}from"fs";import{resolve as Zm}from"path";import{existsSync as WI}from"fs";class ef{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),o=n??this.options.ttl,s=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:o,hits:0,size:s}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!gm(e))return!0;return mm(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,n){try{let i=gm(r)?mm(r):null,o=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:o},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class tf{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let o=await t(),s=performance.now()-n;return this.recordMetric({operation:e,duration:s,timestamp:i,...r}),o}catch(o){let s=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:s,timestamp:i,...r}),o}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,o)=>i+o,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}var Fc=new ef,sl=new tf;var rf=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function nf(e={}){let{name:t="",alias:r}=e,n=["config",".config"];if(t)n.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let i=r===void 0?[]:Array.isArray(r)?r:[r];for(let o of i){if(!o)continue;if(n.push(o,`.${o}.config`,`${o}.config`,`.${o}`),t)n.push(`${t}.${o}.config`,`.${t}.${o}.config`)}return Array.from(new Set(n.filter(Boolean)))}function Uv(e){return nf(e).flatMap((r)=>rf.map((n)=>Ca(e.directory,`${r}${n}`)))}function zv(e={}){let t=Ca(e.cwd||jv.cwd());return Array.from(new Set([t,Ca(t,"config"),Ca(t,".config"),e.configDir?Ca(t,e.configDir):void 0].filter((r)=>Boolean(r))))}var Pw=Object.defineProperty,xw=(e)=>e;function Dw(e,t){this[e]=xw.bind(null,t)}var Ow=(e,t)=>{for(var r in t)Pw(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Dw.bind(t,r)})},_w=(e,t)=>()=>(e&&(t=e(e=0)),t),af={};Ow(af,{withErrorRecovery:()=>uf,tryLoadConfig:()=>rI,loadConfigWithResult:()=>eI,loadConfig:()=>ff,isRetryableError:()=>Ww,isConfigNotFoundError:()=>Hw,isBunfigError:()=>lf,globalPerformanceMonitor:()=>Ra,globalCache:()=>Ws,getEnvOrDefault:()=>Kw,generateConfigTypes:()=>nI,defaultGeneratedDir:()=>Cf,defaultConfigDir:()=>If,deepMergeWithArrayStrategy:()=>ll,deepMerge:()=>pf,createLibraryConfig:()=>iI,config:()=>tI,bunfigPlugin:()=>oI,applyEnvVarsToConfig:()=>Ea,TypeGenerationError:()=>rl,SchemaValidationError:()=>ka,PluginError:()=>il,PerformanceMonitor:()=>cl,FileSystemError:()=>tl,ErrorFactory:()=>Oo,EnvVarError:()=>Kc,EnvProcessor:()=>ed,ConfigValidator:()=>pl,ConfigValidationError:()=>Zu,ConfigNotFoundError:()=>Wc,ConfigMergeError:()=>el,ConfigLoader:()=>gl,ConfigLoadError:()=>Aa,ConfigFileLoader:()=>td,ConfigCache:()=>al,CacheUtils:()=>yf,BunfigError:()=>wn,BrowserConfigError:()=>nl,ArrayMergeStrategies:()=>vf});class al{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),o=n??this.options.ttl,s=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:o,hits:0,size:s}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!fm(e))return!0;return hm(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,n){try{let i=fm(r)?hm(r):null,o=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:o},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class cl{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let o=await t(),s=performance.now()-n;return this.recordMetric({operation:e,duration:s,timestamp:i,...r}),o}catch(o){let s=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:s,timestamp:i,...r}),o}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,o)=>i+o,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function Nw(e,t={}){let n=Object.keys(t).sort().map((i)=>`${i}:${t[i]}`).join("|");return n?`${e}:${n}`:e}function Mw(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function $w(e){return e.getStats().size*2}function dl(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Ft(t[0])&&"id"in t[0]&&t[0].id===3&&Ft(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Ft(t)&&Ft(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(Ft(e)&&"arr"in e&&Array.isArray(e.arr)&&Ft(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Ft(t[0])&&Ft(e[0])){let n=[...t];for(let i of e)if(Ft(i)&&"name"in i){if(!n.find((s)=>Ft(s)&&("name"in s)&&s.name===i.name))n.push(i)}else if(Ft(i)&&"path"in i){if(!n.find((s)=>Ft(s)&&("path"in s)&&s.path===i.path))n.push(i)}else if(!n.some((o)=>qc(o,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!Ft(t)||!Ft(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(Ft(i)&&Ft(r[n]))r[n]=dl(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&Ft(i[0])&&Ft(r[n][0])){let o=[...i];for(let s of r[n])if(Ft(s)&&"name"in s){if(!o.find((u)=>Ft(u)&&("name"in u)&&u.name===s.name))o.push(s)}else if(Ft(s)&&"path"in s){if(!o.find((u)=>Ft(u)&&("path"in u)&&u.path===s.path))o.push(s)}else if(!o.some((c)=>qc(c,s)))o.push(s);r[n]=o}else if(i.every((o)=>typeof o==="string")&&r[n].every((o)=>typeof o==="string")){let o=[...i];for(let s of r[n])if(!o.includes(s))o.push(s);r[n]=o}else r[n]=i;else r[n]=i}return r}function qc(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!qc(e[r],t[r]))return!1;return!0}if(Ft(e)&&Ft(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!qc(e[i],t[i]))return!1}return!0}return!1}function Ft(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Lw(e,t){if(!sf(e))return null;try{let r=await import(e),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return dl(t,n)}catch{return null}}catch{return null}}async function Bw({name:e="",cwd:t,defaultConfig:r}){let n=t||Ku.cwd(),i=[".ts",".js",".mjs",".cjs",".json"],o=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let s of o)for(let c of i){let u=zc(n,`${s}${c}`),a=await Lw(u,r);if(a!==null)return a}try{let s=zc(n,"package.json");if(sf(s)){let u=(await import(s))[e];if(u&&typeof u==="object"&&!Array.isArray(u))try{return dl(r,u)}catch{}}}catch{}return r}function Fw(e,t={}){let r=Uc.cwd();while(r.includes("storage"))r=Sm(r,"..");let n=Sm(r,e||"");if(t?.relative)return Yv(Uc.cwd(),n);return n}async function jw(){try{let e=await Bw({name:"clarity",defaultConfig:Mc,cwd:Uc.cwd(),endpoint:"",headers:{}});return{...Mc,...e}}catch{return Mc}}function qt(){if(Qi.env.NODE_ENV==="test"||Qi.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Uw(){if(Qi.env.NODE_ENV==="test"||Qi.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Qi<"u"){let e=Qi.type;if(e==="renderer"||e==="worker")return!1;return!!(Qi.versions&&(Qi.versions.node||Qi.versions.bun))}return!1}class cf{async format(e){let t=await Uw(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Fs.pid,hostname:t(),environment:Fs.env.NODE_ENV||"development",platform:Fs.platform,version:Fs.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Fs.env.NODE_ENV||Fs.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Gc{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...Yu},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new cf,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??Er.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),o=this.generateKey();this.currentKeyId=i,this.keys.set(i,o),this.encryptionKeys.set(i,{key:o,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...$c,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...$c};return{...$c,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Yu.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let r=(async()=>{let i,o=0,s=3,c=1000;while(o<s)try{try{try{await rw(this.config.logDirectory,Cm.F_OK|Cm.W_OK)}catch(a){if(a instanceof Error&&"code"in a)if(a.code==="ENOENT")await nw(this.config.logDirectory,{recursive:!0,mode:493});else if(a.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw a;else throw a}}catch(a){throw console.error("Debug: [writeToFile] Failed to create log directory:",a),a}let u=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Do.from(e);try{if(!Ou(this.currentLogFile))await _u(this.currentLogFile,"",{mode:420});if(i=Im(this.currentLogFile,"a",420),tw(i,u,{flag:"a"}),wm(i),i!==void 0)Du(i),i=void 0;if((await Ms(this.currentLogFile)).size===0){if(await _u(this.currentLogFile,u,{flag:"w",mode:420}),(await Ms(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(a){let f=a;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(o<s-1){let T=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${o+1}/${s}:`,T);let R=c*2**o;await new Promise((D)=>setTimeout(D,R)),o++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(i!==void 0)try{Du(i)}catch(a){console.error("Debug: [writeToFile] Error closing file descriptor:",a)}}}catch(u){if(o===s-1){let f=u,T=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",T),u}o++;let a=c*2**(o-1);await new Promise((f)=>setTimeout(f,a))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Bs(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Bs(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Bs(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(qt())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,c],[,u])=>u.createdAt.getTime()-c.createdAt.getTime()),o=typeof t.maxKeys==="number"?t.maxKeys:1,s=Math.max(1,o);if(i.length>s)for(let[c]of i.slice(s))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return xu(16).toString("hex")}generateKey(){return xu(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=xu(16),n=Xv("aes-256-gcm",t,r),i=Do.concat([n.update(e,"utf8"),n.final()]),o=n.getAuthTag();return{encrypted:Do.concat([r,i,o]),iv:r}}async compressData(e){return new Promise((t,r)=>{let n=Tm(),i=[];n.on("data",(o)=>i.push(o)),n.on("end",()=>t(Do.from(Do.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(qt())return;let e=await Ms(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await Sc(this.config.logDirectory),o=i.filter((u)=>u.startsWith(this.name)&&/\.log\.\d+$/.test(u)).sort((u,a)=>{let f=Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),s=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await Ms(r).catch(()=>null))try{if(await Em(r,c),t.compress)try{let u=`${c}.gz`;await this.compressLogFile(c,u),await wc(c)}catch(u){console.error("Error compressing rotated file:",u)}if(o.length===0&&!i.some((u)=>u.endsWith(".log.1")))try{let u=`${r}.1`;await _u(u,"")}catch(u){console.error("Error creating backup file:",u)}}catch(u){console.error(`Error during rotation: ${u instanceof Error?u.message:String(u)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),o=r.replace(/\.log$/,`-${i}.log`);if(await Ms(r).catch(()=>null))await Em(r,o)}if(this.currentLogFile=n,t.maxFiles){let o=(await Sc(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,c)=>c.localeCompare(s));for(let s of o.slice(t.maxFiles))await wc(Bs(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=vm(e),n=ew(t),i=Tm();await iw(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Ou(this.currentLogFile))try{let e=Im(this.currentLogFile,"r+");wm(e),Du(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!qt()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Sc(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await wc(Bs(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?Pt.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:o,showTimestamp:s=!0}=e,c=(D)=>D.replace(this.ANSI_PATTERN,"");if(!this.fancy){let D=[];if(s)D.push(t);if(o==="warning")D.push("WARN");else if(o==="error")D.push("ERROR");else if(r)D.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)D.push(n.replace(/[[\]]/g,""));return D.push(i),D.join(" ")}let u=Er.stdout.columns||120,a="";if(o==="warning"||o==="error")a=`${r} ${i}`;else if(o==="info"||o==="success")a=`${r} ${n} ${i}`;else a=`${r} ${n} ${Pt.cyan(i)}`;if(!s)return a.trim();let f=c(a).trim().length,T=c(t).length,R=Math.max(1,u-2-f-T);return`${a.trim()}${" ".repeat(R)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(o,s)=>{let c=Number.parseInt(s,10);return c<t[0].length?String(t[0][c]):o});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(o,s)=>{if(s==="%")return"%";if(n>=t.length)return o;let c=t[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return o}});if(n<t.length)i+=` ${t.slice(n).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return i}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),o=this.formatFileTimestamp(n),s,c;if(t instanceof Error)s=t.message,c=t.stack;else s=this.formatMessage(t,r);if(this.fancy&&!qt()){let a=bf[e],f=this.options.showTags!==!1&&this.name?Pt.gray(this.formatTag(this.name)):"",T;switch(e){case"debug":T=this.formatConsoleMessage({timestamp:i,icon:a,tag:f,message:Pt.gray(s),level:e}),console.error(T);break;case"info":T=this.formatConsoleMessage({timestamp:i,icon:a,tag:f,message:s,level:e}),console.error(T);break;case"success":T=this.formatConsoleMessage({timestamp:i,icon:a,tag:f,message:Pt.green(s),level:e}),console.error(T);break;case"warning":T=this.formatConsoleMessage({timestamp:i,icon:a,tag:f,message:s,level:e}),console.warn(T);break;case"error":if(T=this.formatConsoleMessage({timestamp:i,icon:a,tag:f,message:s,level:e}),console.error(T),c){let R=c.split(`
61
61
  `);for(let D of R)if(D.trim()&&!D.includes(s))console.error(this.formatConsoleMessage({timestamp:i,message:Pt.gray(` ${D}`),level:e,showTimestamp:!1}))}break}}else if(!qt()){if(console.error(`${o} ${this.environment}.${e.toUpperCase()}: ${s}`),c)console.error(c)}if(!this.shouldLog(e))return;let u=`${o} ${this.environment}.${e.toUpperCase()}: ${s}
62
62
  `;if(c)u+=`${c}
63
63
  `;u=u.replace(this.ANSI_PATTERN,""),await this.writeToFile(u)}time(e){let t=performance.now();if(this.fancy&&!qt()){let r=this.options.showTags!==!1&&this.name?Pt.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:Pt.blue("◐"),tag:r,message:`${Pt.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),o=`${e} completed in ${i}ms`,s=new Date,c=this.formatConsoleTimestamp(s),a=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${o}`;if(r)a+=` ${JSON.stringify(r)}`;if(a+=`
@@ -116,8 +116,8 @@ export type ConfigOf = Config
116
116
  `;r+=`| Variable | Type | Description | Example |
117
117
  `,r+=`|----------|------|-------------|----------|
118
118
  `;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
119
- `;return r}}function VI(e,t,r={}){return _f(e,t,r,new WeakMap)}function _f(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:o=!1,customMerger:s}=r;if(t===null||t===void 0)return o?e:t;if(s){let c=s(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return Nf(e,t,i,n);if(!Fn(t)||!Fn(e))return t;return HI(e,t,r,n)}function Nf(e,t,r,n){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return qI(e,t);case"smart":return GI(e,t,n);default:return t}return t}function qI(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>ol(i,n)))r.push(n);return r}function GI(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(Fn(t[0])&&Fn(e[0]))return JI(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}function JI(e,t,r){let n=[...t];for(let i of e){if(!Fn(i)){n.push(i);continue}let o=["id","name","key","path","type"],s=!1;for(let c of o)if(c in i){if(n.find((a)=>Fn(a)&&(c in a)&&a[c]===i[c])){s=!0;break}}if(!s)n.push(i)}return n}function HI(e,t,r,n){let i=t;if(Fn(i)&&n.has(i))return n.get(i);let o={...e};if(Fn(i))n.set(i,o);for(let s in i){if(!Object.prototype.hasOwnProperty.call(i,s))continue;let c=i[s],u=o[s];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){o[s]=c;continue}if(Fn(c)&&Fn(u))o[s]=_f(u,c,r,n);else if(Array.isArray(c)||Array.isArray(u))o[s]=Nf(u,c,r.arrayMergeMode||"smart",n);else o[s]=c}return o}function Mf(e,t,r="replace"){return VI(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function ol(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!ol(e[r],t[r]))return!1;return!0}if(Fn(e)&&Fn(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!ol(e[i],t[i]))return!1}return!0}return!1}function Fn(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class $f{extensions=rf;async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:o,trackPerformance:s=!0,verbose:c=!1}=r;if(i){let a=Fc.getWithFileCheck("file",e);if(a){if(c)console.log(`Configuration loaded from cache: ${e}`);return a}}let u=async()=>{if(!_c(e))return null;try{let a=`?t=${Date.now()}`,f=await import(e+a),T=f.default||f,R="default"in f,D=Object.keys(f).length>0;if(!R&&!D)throw new Yc(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof T!=="object"||T===null||Array.isArray(T))throw new Yc(e,Error("Configuration must export a valid object"),"unknown");let ee={config:Mf(t,T,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)Fc.setWithFileCheck("file",ee,e,o);return ee}catch(a){throw a instanceof Error?Xo.configLoad(e,a):Xo.configLoad(e,Error(String(a)))}};if(s)return sl.track("loadFromPath",u,{path:e});return u()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){return Uv({name:e,directory:t,alias:r})}generateNamePatterns(e,t){return nf({name:e,alias:t})}checkFileAccess(e){return zI(async()=>_c(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!_c(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let o of i)for(let s of this.extensions){let c=Zm(e,`${o}${s}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:i}=await import("fs"),o=i(e);for(let s of o)if(this.looksLikeConfigFile(s)){let c=Zm(e,s);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(e))}async validateConfigFile(e){let t=[];try{if(!_c(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),o=i(e,"utf8");JSON.parse(o)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}var KI=/^https?:\/\//;class Lf{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:o=!0,customRules:s=[],trackPerformance:c=!0,verbose:u=!1}=r,a=async()=>{let f=[],T=[],R={stopOnFirstError:n,validateRequired:i,validateTypes:o,customRules:s,trackPerformance:c,verbose:u};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,R);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...s],R);else return this.validateWithJSONSchema(e,t,R)}catch(D){return f.push({path:"",message:`Validation failed: ${D}`,rule:"system"}),{isValid:!1,errors:f,warnings:T}}};if(c)return await sl.track("validateConfiguration",a);return a()}async validateWithSchemaFile(e,t,r){try{if(!WI(t))throw new Xc(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),i=n.default||n;if(Array.isArray(i))return this.validateWithRules(e,i,r);else return this.validateWithJSONSchema(e,i,r)}catch(n){throw new Xc(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,o){if(o.validateTypes&&t.type){let s=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(s)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${s}`,expected:c.join(" or "),actual:s,rule:"type"}),o.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),o.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let s=0;s<e.length;s++){let c=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(e[s],t.items,c,n,i,o),o.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let s=e;if(o.validateRequired&&t.required){for(let c of t.required)if(!(c in s)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),o.stopOnFirstError)return}}if(t.properties){for(let[c,u]of Object.entries(t.properties))if(c in s){let a=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(s[c],u,a,n,i,o),o.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let u of Object.keys(s))if(!c.has(u))i.push({path:r?`${r}.${u}`:u,message:`Additional property '${u}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let o of t)try{let s=this.getValueByPath(e,o.path),c=this.validateWithRule(s,o,o.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:o.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,o,s]=n;t.push({path:i,required:!o,type:this.mapTypeScriptType(s)})}return t}mapTypeScriptType(e){switch(e.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:KI},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var bi=new rd("bunfig",{showTags:!0});function QI(e){if(!e)return"";let t=Array.isArray(e)?e.filter(Boolean):[e];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class Bf{fileLoader=new $f;envProcessor=new fl;validator=new Lf;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:o,...s}=e;try{if(r?.enabled){let u=this.checkCache(s.name||"",s);if(u)return u}let c;try{c=await this.loadConfigurationStrategies(s,!0,r)}catch(u){if(s.configFile)throw u;let a=s.__strictErrorHandling;if(u instanceof Error&&u.name==="ConfigNotFoundError"){if(a)throw u;c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(u instanceof Error&&u.name==="ConfigLoadError"){let f=u.message.includes("EACCES")||u.message.includes("EPERM")||u.message.includes("permission denied"),T=!f&&(u.message.includes("syntax")||u.message.includes("Expected")||u.message.includes("Unexpected")||u.message.includes("BuildMessage")||u.message.includes("errors building")),R=u.message.includes("Configuration must export a valid object")||u.message.includes("Configuration file is empty and exports nothing");if(a&&(R||f))throw u;if(T&&(!a||!R))c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!a)c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${u.message}`]};else throw u}else c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${u instanceof Error?u.message:String(u)}`]}}if(i||o)await this.validateConfiguration(c.config,i,o,s.name);if(r?.enabled&&c)this.cacheResult(s.name||"",c,r,s);if(n?.enabled){let u={operation:"loadConfig",duration:Date.now()-t,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(u);if(n.slowThreshold&&u.duration>n.slowThreshold)bi.warn(`Slow configuration loading detected: ${u.duration}ms for ${s.name}`);c.metrics=u}return c}catch(c){if(c instanceof Error&&c.name==="ConfigNotFoundError")throw c;let u=Date.now()-t;throw bi.error(`Configuration loading failed after ${u}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,configFile:o,cwd:s,configDir:c,defaultConfig:u,checkEnv:a=!0,arrayStrategy:f="replace",verbose:T=!1}=e,R=s||Zc.cwd(),D=[];if(o){let he=_i(R,o);D.push(he);let te=a?Ia(n,u,T):u,De=await this.fileLoader.tryLoadFromPaths([he],te,{arrayStrategy:f,verbose:T,cacheTtl:r?.ttl,useCache:!r?.ttl||r.ttl>100});if(!De)throw Xo.configNotFound(n||o,D,i);if(T)bi.success(`Configuration loaded from explicit path: ${he}`);return this.finalizeResult(De,D,a,n,T)}let W=await this.loadLocalConfiguration(n,i,R,c,u,f,T,a,r);if(W)return D.push(...this.getLocalSearchPaths(n,i,R,c)),this.finalizeResult(W,D,a,n,T);let Y=await this.loadHomeConfiguration(n,i,u,f,T,a);if(Y)return D.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(Y,D,a,n,T);let ee=await this.loadPackageJsonConfiguration(n,i,R,u,f,T,a);if(ee)return D.push(_i(R,"package.json")),this.finalizeResult(ee,D,a,n,T);if(D.push(...this.getAllSearchPaths(n,i,R,c)),t)throw Xo.configNotFound(n,D,i);return{...await this.applyEnvironmentVariables(n,u,a,T),warnings:[`No configuration file found for "${n}"${QI(i)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,o,s,c,u){let a=c?Ia(e,i,s):i,f=this.getLocalDirectories(r,n);for(let T of f){if(s)bi.info(`Searching for configuration in: ${T}`);let R=this.fileLoader.generateConfigPaths(e,T,t),D=await this.fileLoader.tryLoadFromPaths(R,a,{arrayStrategy:o,verbose:s,cacheTtl:u?.ttl,useCache:!u?.ttl||u.ttl>100});if(D){if(s)bi.success(`Configuration loaded from: ${D.source.path}`);return D}}return null}async loadHomeConfiguration(e,t,r,n,i,o){if(!e)return null;let s=o?Ia(e,r,i):r,c=[_i(_s(),".config",e),_i(_s(),".config"),_s()];for(let u of c){if(i)bi.info(`Checking home directory: ${u}`);let a=this.fileLoader.generateConfigPaths(e,u,t),f=await this.fileLoader.tryLoadFromPaths(a,s,{arrayStrategy:n,verbose:i});if(f){if(i)bi.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,o,s){let c=s?Ia(e,n,o):n;try{let u=_i(r,"package.json");if(!Vv(u))return null;let a={};try{a=JSON.parse(qv(u,"utf8"))}catch(R){if(o)bi.warn("Failed to parse package.json:",[R instanceof Error?R:Error(String(R))]);return null}let f=a[e],T=e;if(!f&&t){let R=Array.isArray(t)?t:[t];for(let D of R){if(!D)continue;if(a[D]){f=a[D],T=D;break}}}if(f&&typeof f==="object"&&!Array.isArray(f)){if(o)bi.success(`Configuration loaded from package.json: ${T}`);return{config:Mf(c,f,i),source:{type:"package.json",path:u,priority:30,timestamp:new Date}}}}catch(u){if(o)bi.warn("Failed to load package.json:",[u instanceof Error?u:Error(String(u))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Ia(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let o=r(e);if(o)i.push(...o)}if(t){let o=await this.validator.validateConfiguration(e,t);if(!o.isValid)i.push(...o.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(i.length>0)throw Xo.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return Fc.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);Fc.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let n=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${n}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configFile)r.push(`configFile:${t.configFile}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return zv({cwd:e,configDir:t})}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(_i(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),o=[];for(let s of i)o.push(...this.fileLoader.generateConfigPaths(e,s,t));return o}getHomeSearchPaths(e,t){if(!e)return[];let r=[_i(_s(),".config",e),_i(_s(),".config"),_s()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}var Hu=new Bf;async function Ff(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let n;if(r)n=await Hu.loadConfig(e);else n=await Hu.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){if(e.configFile)throw n;let i=n instanceof Error?n.name:"UnknownError",o=n instanceof Error?n.message:String(n);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||o.includes("config"))&&e.verbose)bi.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let c=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await Hu.applyEnvironmentVariables(c.name||"",t,!0,c.verbose||!1))?.config??t;return t}}function Ia(e,t,r=!1){let n=new fl,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function o(s,c=[]){let u={...s};for(let[a,f]of Object.entries(s)){let T=[...c,a],R=[`${i}_${T.join("_").toUpperCase()}`,`${i}_${T.map((Y)=>Y.toUpperCase()).join("")}`,`${i}_${T.map((Y)=>Y.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],D,W;for(let Y of R)if(D=Zc.env[Y],D!==void 0){W=Y;break}if(D!==void 0&&W)if(typeof f==="boolean")u[a]=["true","1","yes"].includes(D.toLowerCase());else if(typeof f==="number"){let Y=Number(D);if(!Number.isNaN(Y))u[a]=Y}else if(Array.isArray(f))try{u[a]=JSON.parse(D)}catch{u[a]=D.split(",").map((Y)=>Y.trim())}else u[a]=D;else if(f&&typeof f==="object"&&!Array.isArray(f))u[a]=o(f,T)}return u}return o(t)}var aO=_i(Zc.cwd(),"config"),cO=_i(Zc.cwd(),"src/generated");var Dn={project:{name:"my-project",slug:"my-project",region:"us-east-1"},environments:{production:{type:"production"}}},rs=null;function ZI(e){return e.project?.slug===Dn.project?.slug&&Object.keys(e.environments??{}).length===1&&!!e.environments?.production}async function eC(){let e=[jf(process.cwd(),"config","cloud.ts"),jf(process.cwd(),"config","cloud.js")];for(let t of e){if(!YI(t))continue;let r=await import(`${XI(t).href}?t=${Date.now()}`),n=r.tsCloud??r.default?.tsCloud??r.default??r.cloud??r.config;if(n)return n}return null}async function tC(){if(!rs){if(rs=await Ff({name:"cloud",defaultConfig:Dn}),ZI(rs))rs=await eC()??rs;ia(rs.stateDir)}return rs}var Hi=tC;var rC=async(e)=>{let t=Bun.spawn(e,{stdout:"pipe",stderr:"pipe"}),[r,n,i]=await Promise.all([t.exited,new Response(t.stdout).text(),new Response(t.stderr).text()]);return{code:r,stdout:n,stderr:i}};class Fr{async scan(e,t){return Yi(e,t)}async exec(e,t){if(e.trustState!=="pinned")throw Error("SSH host key must be pinned before remote execution.");return rC(["ssh","-p",String(e.sshPort),"-o","BatchMode=yes","-o","StrictHostKeyChecking=yes","-o","ConnectTimeout=10",`${e.sshUser}@${e.endpoint}`,t])}}var nC=ur,iC=`set -eu; printf '{'; printf '"os":"%s",' "$(. /etc/os-release 2>/dev/null; printf %s "\${PRETTY_NAME:-Linux}")"; printf '"arch":"%s",' "$(uname -m)"; printf '"cpuCores":%s,' "$(getconf _NPROCESSORS_ONLN)"; printf '"memoryBytes":%s,' "$(awk '/MemTotal/{print $2*1024}' /proc/meminfo)"; printf '"diskBytes":%s,' "$(df -B1 / | awk 'NR==2{print $2}')"; printf '"diskFreeBytes":%s,' "$(df -B1 / | awk 'NR==2{print $4}')"; printf '"dnsOk":'; getent hosts example.com >/dev/null && printf true || printf false; printf ',"timeSkewSeconds":0,"tools":{"curl":"'; command -v curl >/dev/null && printf installed; printf '","tar":"'; command -v tar >/dev/null && printf installed; printf '"},"privilege":"'; sudo -n true >/dev/null 2>&1 && printf sudo || printf user; printf '"}'`;class it{provider;transport;discoverer;constructor(e,t=new Fr,r){this.provider=e;this.transport=t;this.discoverer=r}discover(e){return this.discoverer?.(e)??Promise.resolve([])}async test(e){try{let t=await this.transport.scan(e.endpoint,e.sshPort);return{reachable:!0,hostKeyAlgorithm:t.algorithm,hostKeyFingerprint:nC(t.key),latencyMs:0}}catch{return{reachable:!1,hostKeyAlgorithm:"unknown",hostKeyFingerprint:"",latencyMs:0}}}async validate(e){let t=await this.transport.exec(e,iC);if(t.code!==0)throw Error(`Fleet validation failed: ${t.stderr.trim()||t.code}`);try{return JSON.parse(t.stdout)}catch{throw Error("Fleet validation returned malformed facts.")}}async bootstrap(e,t){let r=await this.transport.exec(e,`sudo -n ts-cloud-agent bootstrap --version 1 --steps ${t.length}`);if(r.code!==0)throw Error(`Fleet bootstrap failed: ${r.stderr.trim()||r.code}`);return{version:"1"}}capabilities(){return{document:{supported:!0,reason:"fleet-capabilities/v1; sha256:driver-contract"},validate:{supported:!0},bootstrap:{supported:!0},heartbeat:{supported:!0},drain:{supported:!0},archive:{supported:!0},terminate:{supported:!1,reason:"Inventory removal never terminates provider infrastructure."}}}}function Uf(e,t){return{"fleet.bootstrap":async(r)=>{let n=r.operation.input&&typeof r.operation.input==="object"&&!Array.isArray(r.operation.input)?r.operation.input:{},i=e.get(String(n.serverId??""));if(!i)throw Error("Queued fleet server was not found.");let o=t.find((u)=>u.provider===i.provider);if(!o)throw Error(`No ${i.provider} fleet driver is configured.`);let s=Array.isArray(n.steps)?n.steps.map(String):[];if(r.checkpoint("preflight","Rechecking pinned trust and healthy validation."),i.trustState!=="pinned"||!i.validation?.valid)throw Error("Fleet bootstrap requires pinned trust and a healthy validation report.");r.checkpoint("bootstrap","Applying the reviewed idempotent bootstrap plan.");let c=await o.bootstrap(i,s);return e.update(i.id,{bootstrapVersion:c.version,status:"ready"}),r.checkpoint("verify","Bootstrap completed; heartbeat can now establish freshness."),{serverId:i.id,bootstrapVersion:c.version,steps:s.length}}}}var Ni=(e)=>e==null?void 0:String(e),ns=(e,t)=>{try{return JSON.parse(String(e))}catch{return t}},hl=(e)=>({id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),resourceId:String(e.resource_id),name:String(e.name),provider:String(e.provider),providerId:Ni(e.provider_id),region:Ni(e.region),zone:Ni(e.zone),endpoint:String(e.endpoint),sshUser:String(e.ssh_user),sshPort:Number(e.ssh_port),credentialRef:String(e.credential_ref),hostKeyAlgorithm:Ni(e.host_key_algorithm),hostKeyFingerprint:Ni(e.host_key_fingerprint),pendingHostKey:Ni(e.pending_host_key),roles:ns(e.roles,[]),labels:ns(e.labels,{}),taints:ns(e.taints,[]),capacity:ns(e.capacity,{}),usage:ns(e.usage,{}),capabilities:ns(e.capabilities,{}),status:String(e.status),trustState:String(e.trust_state),validation:ns(e.validation,void 0),bootstrapVersion:Ni(e.bootstrap_version),heartbeatAt:Ni(e.heartbeat_at),lastSeenAt:Ni(e.last_seen_at),archivedAt:Ni(e.archived_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)});class ke{control;now;id;constructor(e,t=()=>new Date,r=()=>crypto.randomUUID()){this.control=e;this.now=t;this.id=r}get(e){let t=this.control.database.query("SELECT * FROM fleet_servers WHERE id=?").get(e);return t?hl(t):void 0}list(e,t=!1){return this.control.database.query("SELECT * FROM fleet_servers WHERE project_id=? ORDER BY name").all(e).map(hl).filter((r)=>t||r.status!=="archived")}findProvider(e,t,r){let n=this.control.database.query("SELECT * FROM fleet_servers WHERE organization_id=? AND provider=? AND provider_id=? AND archived_at IS NULL").get(e,t,r);return n?hl(n):void 0}create(e){let t=this.id(),r=this.now().toISOString();return this.control.database.run("INSERT INTO fleet_servers (id,organization_id,project_id,resource_id,name,provider,provider_id,region,zone,endpoint,ssh_user,ssh_port,credential_ref,host_key_algorithm,host_key_fingerprint,pending_host_key,roles,labels,taints,capacity,usage,capabilities,status,trust_state,validation,bootstrap_version,heartbeat_at,last_seen_at,archived_at,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.organizationId,e.projectId,e.resourceId,e.name,e.provider,e.providerId??null,e.region??null,e.zone??null,e.endpoint,e.sshUser,e.sshPort,e.credentialRef,e.hostKeyAlgorithm??null,e.hostKeyFingerprint??null,e.pendingHostKey??null,JSON.stringify(e.roles),JSON.stringify(e.labels),JSON.stringify(e.taints),JSON.stringify(e.capacity),JSON.stringify(e.usage),JSON.stringify(e.capabilities),e.status,e.trustState,JSON.stringify(e.validation??{}),e.bootstrapVersion??null,e.heartbeatAt??null,e.lastSeenAt??null,e.archivedAt??null,r,r]),this.get(t)}update(e,t){let r=this.get(e);if(!r)throw Error("Server was not found.");let n={...r,...t},i=this.now().toISOString();return this.control.database.run("UPDATE fleet_servers SET name=?,provider_id=?,region=?,zone=?,endpoint=?,ssh_user=?,ssh_port=?,credential_ref=?,host_key_algorithm=?,host_key_fingerprint=?,pending_host_key=?,roles=?,labels=?,taints=?,capacity=?,usage=?,capabilities=?,status=?,trust_state=?,validation=?,bootstrap_version=?,heartbeat_at=?,last_seen_at=?,archived_at=?,version=version+1,updated_at=? WHERE id=?",[n.name,n.providerId??null,n.region??null,n.zone??null,n.endpoint,n.sshUser,n.sshPort,n.credentialRef,n.hostKeyAlgorithm??null,n.hostKeyFingerprint??null,n.pendingHostKey??null,JSON.stringify(n.roles),JSON.stringify(n.labels),JSON.stringify(n.taints),JSON.stringify(n.capacity),JSON.stringify(n.usage),JSON.stringify(n.capabilities),n.status,n.trustState,JSON.stringify(n.validation??{}),n.bootstrapVersion??null,n.heartbeatAt??null,n.lastSeenAt??null,n.archivedAt??null,i,e]),this.get(e)}}var oC=/^(?:[A-Za-z0-9](?:[A-Za-z0-9.-]{0,251}[A-Za-z0-9])?|\[[0-9a-fA-F:]+\])$/;class Nn{store;drivers;now;queue;constructor(e,t,r,n=()=>new Date){this.store=e;this.drivers=t;this.now=n;this.queue=r??new S(e.control)}driver(e){let t=this.drivers.find((r)=>r.provider===e);if(!t)throw Error(`No ${e} fleet driver is configured.`);return t}enroll(e){if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(e.name))throw Error("Server name is invalid.");if(!oC.test(e.endpoint)||e.sshUser==="root"||!e.credentialRef.startsWith("secret://"))throw Error("Enrollment requires a valid endpoint, non-root SSH user, and secret credential reference.");let t=e.providerId?this.store.findProvider(e.organizationId,e.provider,e.providerId):void 0;if(t)return this.store.update(t.id,{endpoint:e.endpoint,region:e.region,zone:e.zone});let r=this.store.control.createResource({projectId:e.projectId,kind:"server",slug:e.name,name:e.name,provider:e.provider,providerId:e.providerId}),n=this.driver(e.provider);return this.store.create({...e,resourceId:r.id,sshPort:e.sshPort??22,labels:e.labels??{},taints:[],capacity:{},usage:{},capabilities:n.capabilities(),status:"pending",trustState:"unverified"})}async test(e){let t=this.store.get(e);if(!t)throw Error("Server was not found.");let r=await this.driver(t.provider).test(t);if(!r.reachable)return this.store.update(e,{status:"unreachable"});if(t.hostKeyFingerprint&&t.hostKeyFingerprint!==r.hostKeyFingerprint)return this.store.update(e,{status:"degraded",trustState:"rotation_pending",pendingHostKey:r.hostKeyFingerprint});return this.store.update(e,{hostKeyAlgorithm:r.hostKeyAlgorithm,hostKeyFingerprint:r.hostKeyFingerprint,pendingHostKey:void 0,trustState:"pinned",status:"validating",lastSeenAt:this.now().toISOString()})}reviewHostKey(e,t){let r=this.store.get(e);if(!r||r.pendingHostKey!==t)throw Error("Pending host key does not match.");return this.store.update(e,{hostKeyFingerprint:t,pendingHostKey:void 0,trustState:"pinned",status:"validating"})}async validate(e){let t=this.store.get(e);if(!t||t.trustState!=="pinned")throw Error("Pin the SSH host key before validation.");let r=await this.driver(t.provider).validate(t),n=[];if(!["x64","arm64","x86_64","aarch64"].includes(r.arch??""))n.push({code:"arch.unsupported",severity:"error",message:"Unsupported architecture.",remediation:"Use x86_64 or arm64 Linux."});for(let s of["curl","tar"])if(!r.tools?.[s])n.push({code:`tool.${s}`,severity:"error",message:`${s} is missing.`,remediation:`Install ${s} before bootstrap.`});if(Math.abs(r.timeSkewSeconds??0)>60)n.push({code:"time.skew",severity:"error",message:"Clock skew exceeds 60 seconds.",remediation:"Enable NTP synchronization."});if(!r.dnsOk)n.push({code:"dns.failed",severity:"error",message:"DNS validation failed.",remediation:"Repair resolver configuration."});let i={valid:!n.some((s)=>s.severity==="error"),facts:r,findings:n,validatedAt:this.now().toISOString(),validatorVersion:"1"},o={cpu:r.cpuCores??0,memoryBytes:r.memoryBytes??0,diskBytes:r.diskBytes??0};return this.store.update(e,{validation:i,capacity:o,status:i.valid?"ready":"degraded"})}bootstrap(e,t=!1){let r=this.store.get(e);if(!r?.validation?.valid)throw Error("A healthy validation report is required.");let n=["install runtime dependencies","install ts-cloud agent","configure heartbeat","verify least-privilege access"];if(!t)return{preview:!0,steps:n};let i=this.queue.enqueue({projectId:r.projectId,resourceId:r.resourceId,kind:"fleet.bootstrap",input:{serverId:e,steps:n},lockKey:`server:${e}`,providerKey:r.provider}).operation;return{preview:!1,steps:n,operation:i}}heartbeat(e,t){let r=this.store.get(e);if(!r)throw Error("Server was not found.");let n=this.now().toISOString();return this.store.update(e,{usage:t.usage,capabilities:t.capabilities??r.capabilities,heartbeatAt:n,lastSeenAt:n,status:r.status==="draining"||r.status==="drained"?r.status:"ready"})}drain(e,t=!1){return this.store.update(e,{status:t?"drained":"draining"})}uncordon(e){return this.store.update(e,{status:"ready"})}archive(e,t){let r=this.store.get(e);if(!r||t!==r.name)throw Error("Exact server name confirmation is required.");return this.store.update(e,{status:"archived",archivedAt:this.now().toISOString()})}}import{createHash as yl,createPublicKey as qf,verify as sC}from"node:crypto";function Pa(e){if(e===null||typeof e!=="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(Pa).join(",")}]`;return`{${Object.keys(e).sort().map((t)=>`${JSON.stringify(t)}:${Pa(e[t])}`).join(",")}}`}var Gf=(e)=>yl("sha256").update(Pa(e)).digest("hex"),nd=(e)=>yl("sha256").update(Pa(e)).digest("hex"),Jf=(e)=>yl("sha256").update(qf(e).export({type:"spki",format:"der"})).digest("hex");function Hf(e,t,r){try{return sC(null,Buffer.from(Pa(e)),qf(r),Buffer.from(t,"base64"))}catch{return!1}}var zf=(e)=>e.replace(/^v/,"").split(/[.-]/).slice(0,3).map((t)=>Number(t)||0),Vf=(e,t)=>{let r=zf(e),n=zf(t);for(let i=0;i<3;i++){let o=(r[i]??0)-(n[i]??0);if(o)return o}return 0};function Wf(e,t){let r=[];if(t.schemaVersion<e.minimumSchema)r.push(`schema ${t.schemaVersion} is below ${e.minimumSchema}`);if(t.schemaVersion>e.maximumSchema)r.push(`schema ${t.schemaVersion} is above ${e.maximumSchema}`);if(e.minimumVersion&&Vf(t.currentVersion,e.minimumVersion)<0)r.push(`platform ${t.currentVersion} is below ${e.minimumVersion}`);if(Vf(e.version,t.currentVersion)<=0)r.push(`version ${e.version} is not newer than ${t.currentVersion}`);if(!e.artifacts.some((n)=>n.platform===t.platform&&n.architecture===t.architecture))r.push(`no artifact for ${t.platform}/${t.architecture}`);return{compatible:r.length===0,reasons:r}}var to=(e,t)=>{try{return JSON.parse(String(e))}catch{return t}},Rr=(e)=>e==null?void 0:String(e),aC=(e)=>({id:String(e.id),organizationId:String(e.organization_id),name:String(e.name),algorithm:"ed25519",publicKeyPem:String(e.public_key_pem),fingerprint:String(e.fingerprint),revokedAt:Rr(e.revoked_at),createdAt:String(e.created_at)}),Kf=(e)=>({id:String(e.id),organizationId:String(e.organization_id),version:String(e.version),channel:String(e.channel),publishedAt:String(e.published_at),keyId:String(e.key_id),digest:String(e.digest),document:to(e.document,{}),signature:String(e.signature),verificationStatus:String(e.verification_status),compatibility:to(e.compatibility,{compatible:!1,reasons:[]}),createdAt:String(e.created_at)}),Qf=(e)=>({id:String(e.id),projectId:String(e.project_id),name:String(e.name),schedule:String(e.schedule),timezone:String(e.timezone),durationMinutes:Number(e.duration_minutes),allowedOperations:to(e.allowed_operations,[]),requireApproval:Number(e.require_approval)===1,enabled:Number(e.enabled)===1,createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),Yf=(e)=>({id:String(e.id),projectId:String(e.project_id),manifestId:String(e.manifest_id),windowId:Rr(e.window_id),fromVersion:String(e.from_version),strategy:String(e.strategy),batchSize:Number(e.batch_size),healthGate:to(e.health_gate,{}),status:String(e.status),currentStage:Rr(e.current_stage),backupId:Rr(e.backup_id),approvedBy:Rr(e.approved_by),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),bl=(e)=>({id:String(e.id),campaignId:String(e.campaign_id),serverId:Rr(e.server_id),target:String(e.target),cohort:Number(e.cohort),previousVersion:String(e.previous_version),status:String(e.status),evidence:to(e.evidence,{}),error:Rr(e.error),startedAt:Rr(e.started_at),finishedAt:Rr(e.finished_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),Xf=(e)=>({id:String(e.id),projectId:String(e.project_id),kind:String(e.kind),criteria:to(e.criteria,{}),candidates:to(e.candidates,[]),candidateDigest:String(e.candidate_digest),estimatedBytes:Number(e.estimated_bytes),status:String(e.status),confirmation:Rr(e.confirmation),expiresAt:String(e.expires_at),result:to(e.result,{}),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),Zf=(e)=>({id:String(e.id),projectId:String(e.project_id),backupPolicyId:Rr(e.backup_policy_id),recoveryPointId:Rr(e.recovery_point_id),topologyId:Rr(e.topology_id),scenario:String(e.scenario),isolatedTarget:String(e.isolated_target),expectedRpoMinutes:Number(e.expected_rpo_minutes),expectedRtoMinutes:Number(e.expected_rto_minutes),status:String(e.status),operationId:Rr(e.operation_id),evidence:to(e.evidence,{}),measuredRpoMinutes:e.measured_rpo_minutes==null?void 0:Number(e.measured_rpo_minutes),measuredRtoMinutes:e.measured_rto_minutes==null?void 0:Number(e.measured_rto_minutes),cleanupVerified:Number(e.cleanup_verified)===1,error:Rr(e.error),startedAt:Rr(e.started_at),finishedAt:Rr(e.finished_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)});class Ln{control;now;id;constructor(e,t=()=>new Date,r=()=>crypto.randomUUID()){this.control=e;this.now=t;this.id=r}addTrustedKey(e){let t=this.id(),r=this.now().toISOString(),n=Jf(e.publicKeyPem);return this.control.database.run("INSERT INTO platform_trusted_keys (id,organization_id,name,algorithm,public_key_pem,fingerprint,created_at) VALUES (?,?,?,'ed25519',?,?,?)",[t,e.organizationId,e.name,e.publicKeyPem,n,r]),this.key(t)}key(e){let t=this.control.database.query("SELECT * FROM platform_trusted_keys WHERE id=?").get(e);return t?aC(t):void 0}revokeKey(e){return this.control.database.run("UPDATE platform_trusted_keys SET revoked_at=? WHERE id=?",[this.now().toISOString(),e]),this.key(e)}importManifest(e){let t=this.key(e.keyId);if(!t||t.organizationId!==e.organizationId)throw Error("Trusted update key was not found.");if(t.revokedAt)throw Error("Update signing key is revoked.");if(!Hf(e.document,e.signature,t.publicKeyPem))throw Error("Update manifest signature is invalid.");let r=Wf(e.document,e.current),n=Gf(e.document),i=this.id(),o=this.now().toISOString();return this.control.database.run("INSERT INTO platform_update_manifests (id,organization_id,version,channel,published_at,key_id,digest,document,signature,verification_status,compatibility,created_at) VALUES (?,?,?,?,?,?,?,?,?,'verified',?,?)",[i,e.organizationId,e.document.version,e.document.channel,new Date(e.document.publishedAt).toISOString(),e.keyId,n,JSON.stringify(e.document),e.signature,JSON.stringify(r),o]),this.manifest(i)}manifest(e){let t=this.control.database.query("SELECT * FROM platform_update_manifests WHERE id=?").get(e);return t?Kf(t):void 0}manifests(e){return this.control.database.query("SELECT * FROM platform_update_manifests WHERE organization_id=? ORDER BY published_at DESC").all(e).map(Kf)}createWindow(e){let t=this.id(),r=this.now().toISOString();return this.control.database.run("INSERT INTO maintenance_windows (id,project_id,name,schedule,timezone,duration_minutes,allowed_operations,require_approval,enabled,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,1,?,?)",[t,e.projectId,e.name,e.schedule,e.timezone,e.durationMinutes,JSON.stringify(e.allowedOperations),e.requireApproval===!1?0:1,r,r]),this.window(t)}window(e){let t=this.control.database.query("SELECT * FROM maintenance_windows WHERE id=?").get(e);return t?Qf(t):void 0}windows(e){return this.control.database.query("SELECT * FROM maintenance_windows WHERE project_id=? ORDER BY name").all(e).map(Qf)}createCampaign(e){return this.control.transaction(()=>{let t=this.manifest(e.manifestId);if(!t?.compatibility.compatible||t.verificationStatus!=="verified")throw Error("A verified compatible update manifest is required.");if(!e.backupId)throw Error("A verified pre-upgrade backup is required.");let r=this.id(),n=this.now().toISOString();return this.control.database.run("INSERT INTO platform_upgrade_campaigns (id,project_id,manifest_id,window_id,from_version,strategy,batch_size,health_gate,status,backup_id,approved_by,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?, 'planned',?,?,?,?)",[r,e.projectId,e.manifestId,e.windowId??null,e.fromVersion,e.strategy,e.batchSize,JSON.stringify(e.healthGate),e.backupId,e.approvedBy??null,n,n]),e.targets.forEach((i,o)=>this.control.database.run("INSERT INTO platform_upgrade_targets (id,campaign_id,server_id,target,cohort,previous_version,status,created_at,updated_at) VALUES (?,?,?,?,?,?,'pending',?,?)",[this.id(),r,i.serverId??null,i.target,e.strategy==="canary"?o===0?0:1+Math.floor((o-1)/e.batchSize):Math.floor(o/e.batchSize),i.previousVersion,n,n])),this.campaign(r)})}campaign(e){let t=this.control.database.query("SELECT * FROM platform_upgrade_campaigns WHERE id=?").get(e);return t?Yf(t):void 0}campaigns(e){return this.control.database.query("SELECT * FROM platform_upgrade_campaigns WHERE project_id=? ORDER BY created_at DESC").all(e).map(Yf)}targets(e){return this.control.database.query("SELECT * FROM platform_upgrade_targets WHERE campaign_id=? ORDER BY cohort,target").all(e).map(bl)}updateCampaign(e,t){let r=this.campaign(e);if(!r)throw Error("Upgrade campaign was not found.");let n={...r,...t};return this.control.database.run("UPDATE platform_upgrade_campaigns SET status=?,current_stage=?,updated_at=? WHERE id=?",[n.status,n.currentStage??null,this.now().toISOString(),e]),this.campaign(e)}updateTarget(e,t){let r=this.control.database.query("SELECT * FROM platform_upgrade_targets WHERE id=?").get(e);if(!r)throw Error("Upgrade target was not found.");let n={...bl(r),...t};return this.control.database.run("UPDATE platform_upgrade_targets SET status=?,evidence=?,error=?,started_at=?,finished_at=?,updated_at=? WHERE id=?",[n.status,JSON.stringify(n.evidence),n.error??null,n.startedAt??null,n.finishedAt??null,this.now().toISOString(),e]),bl(this.control.database.query("SELECT * FROM platform_upgrade_targets WHERE id=?").get(e))}createCleanup(e){let t=[...e.candidates].sort((s,c)=>s.id.localeCompare(c.id)),r=nd(t),n=this.id(),i=this.now().toISOString(),o=new Date(this.now().getTime()+(e.ttlMinutes??60)*60000).toISOString();return this.control.database.run("INSERT INTO cleanup_plans (id,project_id,kind,criteria,candidates,candidate_digest,estimated_bytes,status,expires_at,created_at,updated_at) VALUES (?,?,?,?,?,?,?,'preview',?,?,?)",[n,e.projectId,e.kind,JSON.stringify(e.criteria),JSON.stringify(t),r,t.reduce((s,c)=>s+c.bytes,0),o,i,i]),this.cleanup(n)}cleanup(e){let t=this.control.database.query("SELECT * FROM cleanup_plans WHERE id=?").get(e);return t?Xf(t):void 0}cleanups(e){return this.control.database.query("SELECT * FROM cleanup_plans WHERE project_id=? ORDER BY created_at DESC").all(e).map(Xf)}updateCleanup(e,t){let r=this.cleanup(e);if(!r)throw Error("Cleanup plan was not found.");let n={...r,...t};return this.control.database.run("UPDATE cleanup_plans SET status=?,confirmation=?,result=?,updated_at=? WHERE id=?",[n.status,n.confirmation??null,JSON.stringify(n.result),this.now().toISOString(),e]),this.cleanup(e)}createDrill(e){if(!/^isolated:\/\//.test(e.isolatedTarget))throw Error("DR drills require an isolated target.");let t=this.id(),r=this.now().toISOString();return this.control.database.run("INSERT INTO disaster_recovery_drills (id,project_id,backup_policy_id,recovery_point_id,topology_id,scenario,isolated_target,expected_rpo_minutes,expected_rto_minutes,status,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,'planned',?,?)",[t,e.projectId,e.backupPolicyId??null,e.recoveryPointId??null,e.topologyId??null,e.scenario,e.isolatedTarget,e.expectedRpoMinutes,e.expectedRtoMinutes,r,r]),this.drill(t)}drill(e){let t=this.control.database.query("SELECT * FROM disaster_recovery_drills WHERE id=?").get(e);return t?Zf(t):void 0}drills(e){return this.control.database.query("SELECT * FROM disaster_recovery_drills WHERE project_id=? ORDER BY created_at DESC").all(e).map(Zf)}updateDrill(e,t){let r=this.drill(e);if(!r)throw Error("DR drill was not found.");let n={...r,...t};return this.control.database.run("UPDATE disaster_recovery_drills SET status=?,operation_id=?,evidence=?,measured_rpo_minutes=?,measured_rto_minutes=?,cleanup_verified=?,error=?,started_at=?,finished_at=?,updated_at=? WHERE id=?",[n.status,n.operationId??null,JSON.stringify(n.evidence),n.measuredRpoMinutes??null,n.measuredRtoMinutes??null,n.cleanupVerified?1:0,n.error??null,n.startedAt??null,n.finishedAt??null,this.now().toISOString(),e]),this.drill(e)}}function cC(e,t=new Date){if(!e.enabled)return!1;let r=new Date(e.schedule);if(!Number.isNaN(r.getTime()))return t>=r&&t.getTime()<=r.getTime()+e.durationMinutes*60000;let n=/^(\d{2}):(\d{2})$/.exec(e.schedule);if(!n)return!1;let i=new Intl.DateTimeFormat("en-US",{timeZone:e.timezone,hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).formatToParts(t),o=Number(i.find((c)=>c.type==="hour")?.value)*60+Number(i.find((c)=>c.type==="minute")?.value),s=Number(n[1])*60+Number(n[2]);return o>=s&&o<s+e.durationMinutes}class Mn{store;now;queue;constructor(e,t,r=()=>new Date){this.store=e;this.now=r;this.queue=t??new S(e.control)}enqueueCampaign(e,t={}){let r=this.store.campaign(e);if(!r)throw Error("Upgrade campaign was not found.");let n=r.windowId?this.store.window(r.windowId):void 0;if(n&&!n.allowedOperations.includes("platform.upgrade"))throw Error("Maintenance window does not permit platform upgrades.");if(n&&!t.overrideWindow&&!cC(n,this.now()))throw Error("Upgrade is outside its maintenance window.");if(n?.requireApproval&&!t.approvedBy&&!r.approvedBy)throw Error("Maintenance approval is required.");let i=this.queue.enqueue({projectId:r.projectId,actorId:t.approvedBy,kind:"maintenance.upgrade",input:{campaignId:e},lockKey:"platform-upgrade",providerKey:"platform",timeoutSeconds:7200,cancellationMode:"cooperative",resumePolicy:"fail"}).operation;return{campaign:this.store.updateCampaign(e,{status:"queued"}),operation:i}}async previewCleanup(e,t){let r=t.find((n)=>n.kind===e.kind);if(!r)throw Error(`No ${e.kind} cleanup driver is configured.`);return this.store.createCleanup({...e,candidates:await r.discover(e.criteria)})}enqueueCleanup(e,t){let r=this.store.cleanup(e);if(!r||r.status!=="preview")throw Error("A current cleanup preview is required.");if(new Date(r.expiresAt)<=this.now())throw Error("Cleanup preview expired; generate it again.");let n=`DELETE ${r.candidates.length} ${r.kind}`;if(t!==n)throw Error(`Exact confirmation ${n} is required.`);let i=this.queue.enqueue({projectId:r.projectId,kind:"maintenance.cleanup",input:{planId:e},lockKey:`cleanup:${r.kind}`,providerKey:"cleanup",timeoutSeconds:3600,cancellationMode:"cooperative"}).operation;return{plan:this.store.updateCleanup(e,{status:"approved",confirmation:t}),operation:i}}enqueueDrill(e){let t=this.store.drill(e);if(!t||t.status!=="planned")throw Error("A planned DR drill is required.");let r=this.queue.enqueue({projectId:t.projectId,kind:"maintenance.drill",input:{drillId:e},lockKey:`drill:${t.scenario}:${t.id}`,providerKey:"recovery",timeoutSeconds:7200,cancellationMode:"cooperative"}).operation;return{drill:this.store.updateDrill(e,{status:"queued",operationId:r.id}),operation:r}}}var Sl=(e)=>e&&typeof e==="object"&&!Array.isArray(e)?e:{};function eh(e){return{"maintenance.upgrade":async(i)=>{let o=e.store.campaign(String(Sl(i.operation.input).campaignId??""));if(!o||!e.platform)throw Error("Upgrade campaign or platform maintenance driver is unavailable.");let s=e.store.manifest(o.manifestId);if(!s?.compatibility.compatible||s.verificationStatus!=="verified")throw Error("Update manifest is no longer verified and compatible.");let c=s.document.artifacts.find((a)=>a.platform===process.platform&&a.architecture===process.arch)??s.document.artifacts[0];if(!c)throw Error("No update artifact matches this platform.");e.store.updateCampaign(o.id,{status:"running",currentStage:"preflight"});let u=[];try{for(let a of[...new Set(e.store.targets(o.id).map((f)=>f.cohort))].sort((f,T)=>f-T)){e.store.updateCampaign(o.id,{currentStage:`cohort:${a}`});for(let f of e.store.targets(o.id).filter((T)=>T.cohort===a)){i.throwIfCancellationRequested(),i.checkpoint(`download:${f.target}`,"Downloading signed platform artifact."),e.store.updateTarget(f.id,{status:"downloading",startedAt:new Date().toISOString()});let T=await e.platform.download({target:f,artifact:c,signal:i.signal});if(T.sha256!==c.sha256)throw Error(`Artifact checksum mismatch for ${f.target}.`);i.checkpoint(`install:${f.target}`,"Installing verified artifact."),e.store.updateTarget(f.id,{status:"installing"}),await e.platform.install({target:f,path:T.path,version:s.version,signal:i.signal}),u.push(f);let R=await e.platform.health({target:f,gate:o.healthGate});if(!R.healthy)throw Error(`Upgrade health gate failed for ${f.target}.`);e.store.updateTarget(f.id,{status:"healthy",evidence:R.evidence,finishedAt:new Date().toISOString()})}}return e.store.updateCampaign(o.id,{status:"succeeded",currentStage:void 0}),{campaignId:o.id,version:s.version,targets:u.length}}catch(a){e.store.updateCampaign(o.id,{status:"rolling_back",currentStage:"rollback"});for(let f of u.reverse())e.store.updateTarget(f.id,{status:"rolling_back"}),await e.platform.rollback({target:f,version:f.previousVersion,signal:i.signal}),e.store.updateTarget(f.id,{status:"rolled_back",finishedAt:new Date().toISOString()});throw e.store.updateCampaign(o.id,{status:"rolled_back",currentStage:void 0}),a}},"maintenance.cleanup":async(i)=>{let o=e.store.cleanup(String(Sl(i.operation.input).planId??""));if(!o||o.status!=="approved")throw Error("Approved cleanup plan was not found.");if(nd([...o.candidates].sort((f,T)=>f.id.localeCompare(T.id)))!==o.candidateDigest)throw Error("Cleanup candidate set changed after preview.");let s=e.cleanup?.find((f)=>f.kind===o.kind);if(!s)throw Error(`No ${o.kind} cleanup driver is configured.`);e.store.updateCleanup(o.id,{status:"running"});let c=[],u=[];for(let f of o.candidates){i.throwIfCancellationRequested();try{await s.remove(f),c.push(f.id)}catch(T){u.push({id:f.id,error:T instanceof Error?T.message:String(T)})}}let a=u.length?c.length?"partial":"failed":"succeeded";if(e.store.updateCleanup(o.id,{status:a,result:{removed:c,failed:u,reclaimedBytes:o.candidates.filter((f)=>c.includes(f.id)).reduce((f,T)=>f+T.bytes,0)}}),u.length)throw Error(`Cleanup failed for ${u.length} candidate(s).`);return{planId:o.id,removed:c.length,reclaimedBytes:o.estimatedBytes}},"maintenance.drill":async(i)=>{let o=e.store.drill(String(Sl(i.operation.input).drillId??""));if(!o)throw Error("DR drill was not found.");let s=e.recovery?.find((T)=>T.scenario===o.scenario);if(!s)throw Error(`No ${o.scenario} recovery driver is configured.`);let c=new Date;e.store.updateDrill(o.id,{status:"restoring",startedAt:c.toISOString()});let u=o.isolatedTarget,a={},f={};try{i.checkpoint("restore","Restoring into isolated drill target.");let T=await s.restore({drill:o,signal:i.signal});if(!T.target.startsWith("isolated://"))throw Error("Recovery driver attempted a non-isolated target.");u=T.target,a=T.evidence;let R=(c.getTime()-new Date(T.recoveryPointAt).getTime())/60000;e.store.updateDrill(o.id,{status:"verifying",measuredRpoMinutes:R,evidence:{restore:a}}),i.checkpoint("verify","Running recovery health checks without production traffic.");let D=await s.verify({drill:o,target:u});f=D.evidence;let W=(Date.now()-c.getTime())/60000;if(!D.healthy||R>o.expectedRpoMinutes||W>o.expectedRtoMinutes)throw Error("DR drill failed its health, RPO, or RTO objective.");e.store.updateDrill(o.id,{measuredRpoMinutes:R,measuredRtoMinutes:W,evidence:{restore:a,verify:f}})}catch(T){throw e.store.updateDrill(o.id,{status:"failed",error:T instanceof Error?T.message:String(T),evidence:{restore:a,verify:f}}),T}finally{e.store.updateDrill(o.id,{status:"cleaning"});try{await s.cleanup({drill:o,target:u});let T=e.store.drill(o.id);e.store.updateDrill(o.id,{status:T.error?"failed":"passed",cleanupVerified:!0,finishedAt:new Date().toISOString()})}catch(T){e.store.updateDrill(o.id,{status:"cleanup_required",cleanupVerified:!1,error:T instanceof Error?T.message:String(T),finishedAt:new Date().toISOString()})}}return{drillId:o.id,status:e.store.drill(o.id).status}}}}var th={releases:{select:"SELECT id,created_at,0 bytes FROM releases WHERE project_id=? AND pinned=0 AND status IN ('failed','rolled_back','superseded') AND created_at<?",remove:"DELETE FROM releases WHERE id=?"},artifacts:{select:"SELECT a.id,a.created_at,a.size bytes FROM release_artifacts a WHERE a.organization_id=? AND NOT EXISTS(SELECT 1 FROM releases r WHERE r.artifact_id=a.id) AND a.created_at<?",remove:"DELETE FROM release_artifacts WHERE id=?"},operations:{select:"SELECT id,created_at,0 bytes FROM operations WHERE project_id=? AND state IN ('succeeded','failed','cancelled','timed_out') AND updated_at<?",remove:"DELETE FROM operations WHERE id=?"},logs:{select:"SELECT l.id,l.created_at,length(l.message) bytes FROM operation_logs l JOIN operations o ON o.id=l.operation_id WHERE o.project_id=? AND o.state IN ('succeeded','failed','cancelled','timed_out') AND l.created_at<?",remove:"DELETE FROM operation_logs WHERE id=?"},previews:{select:"SELECT id,created_at,0 bytes FROM preview_instances WHERE project_id=? AND status IN ('destroyed','failed') AND updated_at<?",remove:"DELETE FROM preview_instances WHERE id=?"},snapshots:{select:"SELECT id,created_at,size_bytes bytes FROM recovery_points WHERE project_id=? AND pinned=0 AND held=0 AND status IN ('failed','deleted') AND created_at<?",remove:"DELETE FROM recovery_points WHERE id=?"},orphaned_resources:{select:"SELECT id,created_at,COALESCE(capacity_bytes,0) bytes FROM persistent_volumes WHERE project_id=? AND status='orphaned' AND orphaned_at<?",remove:"UPDATE persistent_volumes SET status='deleted',deleted_at=datetime('now'),updated_at=datetime('now') WHERE id=? AND status='orphaned'"}};class Un{kind;control;projectId;organizationId;constructor(e,t,r,n){this.kind=e;this.control=t;this.projectId=r;this.organizationId=n}async discover(e){let t=Math.max(1,Math.min(3650,Number(e.olderThanDays??30))),r=new Date(Date.now()-t*86400000).toISOString(),n=th[this.kind],i=this.kind==="artifacts"?this.organizationId:this.projectId;return this.control.database.query(n.select).all(i,r).map((s)=>({id:String(s.id),kind:this.kind,label:`${this.kind}:${String(s.id)}`,bytes:Number(s.bytes??0),metadata:{createdAt:String(s.created_at)}}))}async remove(e){if(this.control.database.run(th[this.kind].remove,[e.id]).changes!==1)throw Error(`${e.label} changed or is no longer removable.`)}}var wi=(e,t)=>{try{return JSON.parse(String(e))}catch{return t}},yn=(e)=>e==null?void 0:String(e),ih=()=>({cpu:0,memoryBytes:0,diskBytes:0,gpu:0}),Ks=(e={})=>({...ih(),...e});function rh(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),name:String(e.name),purpose:String(e.purpose),backend:String(e.backend),region:yn(e.region),architecture:yn(e.architecture),labels:wi(e.labels,{}),requiredServerLabels:wi(e.required_server_labels,{}),toleratedTaints:wi(e.tolerated_taints,[]),capacity:Ks(wi(e.capacity,{})),reserved:wi(e.reserved,{}),maxWorkloads:Number(e.max_workloads),costWeight:Number(e.cost_weight),spreadKey:yn(e.spread_key),concurrency:Number(e.concurrency),ephemeralWorkspaces:Number(e.ephemeral_workspaces)===1,allowProductionSecrets:Number(e.allow_production_secrets)===1,status:String(e.status),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function nh(e){return{id:String(e.id),projectId:String(e.project_id),environmentId:yn(e.environment_id),resourceId:String(e.resource_id),releaseId:yn(e.release_id),poolId:String(e.pool_id),serverId:yn(e.server_id),purpose:String(e.purpose),requirements:wi(e.requirements,{}),decision:wi(e.decision,{}),stateful:Number(e.stateful)===1,autoReschedule:Number(e.auto_reschedule)===1,status:String(e.status),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function dC(e){return{id:String(e.id),projectId:String(e.project_id),resourceId:yn(e.resource_id),poolId:String(e.pool_id),placementId:yn(e.placement_id),operationId:yn(e.operation_id),sourceSha:String(e.source_sha),buildSpec:wi(e.build_spec,{}),credentialPolicy:wi(e.credential_policy,{productionSecrets:!1,shortLivedTokenExpiresAt:""}),workspace:yn(e.workspace),cacheKey:yn(e.cache_key),artifactUri:yn(e.artifact_uri),artifactDigest:yn(e.artifact_digest),status:String(e.status),cleanupAt:yn(e.cleanup_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}class xn{control;now;id;constructor(e,t=()=>new Date,r=()=>crypto.randomUUID()){this.control=e;this.now=t;this.id=r}createPool(e){let t=this.id(),r=this.now().toISOString();return this.control.database.run("INSERT INTO capacity_pools (id,organization_id,project_id,name,purpose,backend,region,architecture,labels,required_server_labels,tolerated_taints,capacity,reserved,max_workloads,cost_weight,spread_key,concurrency,ephemeral_workspaces,allow_production_secrets,status,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.organizationId,e.projectId,e.name,e.purpose,e.backend,e.region??null,e.architecture??null,JSON.stringify(e.labels),JSON.stringify(e.requiredServerLabels),JSON.stringify(e.toleratedTaints),JSON.stringify(Ks(e.capacity)),"{}",e.maxWorkloads,e.costWeight,e.spreadKey??null,e.concurrency,e.ephemeralWorkspaces?1:0,e.allowProductionSecrets?1:0,e.status,r,r]),this.getPool(t)}getPool(e){let t=this.control.database.query("SELECT * FROM capacity_pools WHERE id=?").get(e);return t?rh(t):void 0}listPools(e){return this.control.database.query("SELECT * FROM capacity_pools WHERE project_id=? ORDER BY name").all(e).map(rh)}updatePool(e,t){let r=this.getPool(e);if(!r)throw Error("Capacity pool was not found.");let n={...r,...t},i=this.now().toISOString();return this.control.database.run("UPDATE capacity_pools SET status=?,reserved=?,capacity=?,concurrency=?,version=version+1,updated_at=? WHERE id=?",[n.status,JSON.stringify(n.reserved),JSON.stringify(n.capacity),n.concurrency,i,e]),this.getPool(e)}addMember(e,t,r={}){let n=this.now().toISOString();this.control.database.run("INSERT INTO capacity_pool_members (pool_id,server_id,capacity_override,status,created_at,updated_at) VALUES (?,?,?,'active',?,?) ON CONFLICT(pool_id,server_id) DO UPDATE SET capacity_override=excluded.capacity_override,status='active',updated_at=excluded.updated_at",[e,t,JSON.stringify(r),n,n])}members(e){return this.control.database.query("SELECT * FROM capacity_pool_members WHERE pool_id=? ORDER BY server_id").all(e).map((t)=>({serverId:String(t.server_id),status:String(t.status),capacityOverride:wi(t.capacity_override,{})}))}memberStatus(e,t,r){this.control.database.run("UPDATE capacity_pool_members SET status=?,updated_at=? WHERE pool_id=? AND server_id=?",[r,this.now().toISOString(),e,t])}listPlacements(e,t){let r=this.control.database.query("SELECT * FROM workload_placements WHERE project_id=? ORDER BY created_at,id").all(e).map(nh);return t?.length?r.filter((n)=>t.includes(n.status)):r}getPlacement(e){let t=this.control.database.query("SELECT * FROM workload_placements WHERE id=?").get(e);return t?nh(t):void 0}activeUsage(e,t){let r=this.control.database.query("SELECT l.resources,l.server_id FROM capacity_leases l WHERE l.pool_id=? AND l.state='active' AND l.expires_at>?").all(e,this.now().toISOString()),n=t?r.filter((i)=>String(i.server_id)===t):r;return{resources:n.reduce((i,o)=>{let s=Ks(wi(o.resources,{}));for(let c of Object.keys(i))i[c]+=s[c];return i},ih()),count:n.length}}expireLeases(){return this.control.database.run("UPDATE capacity_leases SET state='expired',updated_at=? WHERE state='active' AND expires_at<=?",[this.now().toISOString(),this.now().toISOString()]).changes}reserve(e){return this.control.transaction(()=>{this.expireLeases();let t=this.id(),r=this.id(),n=this.now().toISOString(),i=new Date(this.now().getTime()+(e.requirements.leaseSeconds??300)*1000).toISOString();return this.control.database.run("INSERT INTO workload_placements (id,project_id,environment_id,resource_id,release_id,pool_id,server_id,purpose,requirements,decision,stateful,auto_reschedule,status,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,'reserved',?,?)",[t,e.projectId,e.environmentId??null,e.resourceId,e.releaseId??null,e.decision.poolId,e.decision.serverId??null,e.requirements.purpose,JSON.stringify(e.requirements),JSON.stringify(e.decision),e.requirements.stateful?1:0,e.requirements.autoReschedule&&!e.requirements.stateful?1:0,n,n]),this.control.database.run("INSERT INTO capacity_leases (id,placement_id,pool_id,server_id,resources,state,expires_at,created_at,updated_at) VALUES (?,?,?,?,?,'active',?,?,?)",[r,t,e.decision.poolId,e.decision.serverId??null,JSON.stringify(Ks(e.requirements.resources)),i,n,n]),this.getPlacement(t)})}transitionPlacement(e,t){if(!this.getPlacement(e))throw Error("Placement was not found.");let n=this.now().toISOString();if(this.control.database.run("UPDATE workload_placements SET status=?,version=version+1,updated_at=? WHERE id=?",[t,n,e]),["released","failed","blocked"].includes(t))this.control.database.run("UPDATE capacity_leases SET state='released',updated_at=? WHERE placement_id=? AND state='active'",[n,e]);return this.getPlacement(e)}createBuild(e){let t=this.id(),r=this.now().toISOString();return this.control.database.run("INSERT INTO remote_builds (id,project_id,resource_id,pool_id,placement_id,operation_id,source_sha,build_spec,credential_policy,status,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,'queued',?,?)",[t,e.projectId,e.resourceId??null,e.poolId,e.placementId??null,e.operationId??null,e.sourceSha,JSON.stringify(e.buildSpec),JSON.stringify({productionSecrets:!1,shortLivedTokenExpiresAt:e.tokenExpiresAt}),r,r]),this.getBuild(t)}getBuild(e){let t=this.control.database.query("SELECT * FROM remote_builds WHERE id=?").get(e);return t?dC(t):void 0}updateBuild(e,t){let r=this.getBuild(e);if(!r)throw Error("Remote build was not found.");let n={...r,...t},i=this.now().toISOString();return this.control.database.run("UPDATE remote_builds SET operation_id=?,workspace=?,cache_key=?,artifact_uri=?,artifact_digest=?,status=?,cleanup_at=?,updated_at=? WHERE id=?",[n.operationId??null,n.workspace??null,n.cacheKey??null,n.artifactUri??null,n.artifactDigest??null,n.status,n.cleanupAt??null,i,e]),this.getBuild(e)}}var id=["cpu","memoryBytes","diskBytes","gpu"],oh=(e,t={})=>Object.entries(t).every(([r,n])=>e[r]===n),uC=(e,t,r)=>Object.fromEntries(id.map((n)=>[n,Math.max(0,e[n]-t[n]-(r[n]??0))])),lC=(e,t)=>id.every((r)=>e[r]>=(t[r]??0)),pC=(e,t)=>id.reduce((r,n)=>r+(t[n]??0)/(e[n]||1),0);class _n{store;fleet;constructor(e,t){this.store=e;this.fleet=t}poolCandidates(e,t,r){let n=[];for(let i of this.store.listPools(e)){if(i.id===r)continue;let o=[];if(i.status!=="active")o.push(`pool is ${i.status}`);if(i.purpose!==t.purpose)o.push(`purpose is ${i.purpose}`);if(t.region&&i.region!==t.region)o.push(`region is ${i.region??"unset"}`);if(t.architecture&&i.architecture!==t.architecture)o.push(`architecture is ${i.architecture??"unset"}`);if(!oh(i.labels,t.labels))o.push("pool labels do not match");if(i.backend==="server"){let s=this.store.members(i.id);if(!s.length)n.push(this.decision(i,void 0,t,[...o,"pool has no servers"]));for(let c of s){let u=this.fleet.get(c.serverId),a=[...o];if(!u)a.push("server is missing");else this.serverReasons(i,u,c.status,t,a);n.push(this.decision(i,u,t,a,c.capacityOverride))}}else n.push(this.decision(i,void 0,t,o))}return n.sort((i,o)=>Number(o.eligible)-Number(i.eligible)||i.score.cost-o.score.cost||i.score.spread-o.score.spread||i.score.fit-o.score.fit||i.poolName.localeCompare(o.poolName)||(i.serverId??"").localeCompare(o.serverId??""))}serverReasons(e,t,r,n,i){if(r!=="active")i.push(`member is ${r}`);if(t.status!=="ready")i.push(`server is ${t.status}`);if(!t.roles.includes(n.purpose==="build"?"build":n.purpose))i.push(`server lacks ${n.purpose} role`);if(!oh(t.labels,e.requiredServerLabels))i.push("server labels do not match pool selector");for(let o of t.taints)if(!e.toleratedTaints.includes(o))i.push(`taint ${o} is not tolerated`)}decision(e,t,r,n,i={}){let o=Ks({...t?.capacity,...i}),s=t?Object.fromEntries(id.map((a)=>[a,Math.min(e.capacity[a],o[a])])):e.capacity,c=this.store.activeUsage(e.id,t?.id),u=uC(s,c.resources,e.reserved);if(c.count>=e.maxWorkloads)n.push("workload limit reached");if(r.purpose==="build"&&c.count>=e.concurrency)n.push("build concurrency reached");if(!lC(u,r.resources))n.push("insufficient capacity");return{poolId:e.id,poolName:e.name,serverId:t?.id,eligible:n.length===0,reasons:n,available:u,score:{fit:pC(u,r.resources),spread:c.count,cost:e.costWeight}}}explain(e,t){return this.poolCandidates(e,t)}place(e){return this.store.control.transaction(()=>{let t=this.poolCandidates(e.projectId,e.requirements).find((r)=>r.eligible);if(!t)throw Error(`No eligible capacity: ${this.explain(e.projectId,e.requirements).flatMap((r)=>r.reasons).join("; ")}`);return this.store.reserve({...e,decision:t})})}activate(e){return this.store.transitionPlacement(e,"active")}release(e){return this.store.transitionPlacement(e,"released")}drainPool(e){let t=this.store.updatePool(e,{status:"draining"}),r=[],n=[];for(let i of this.store.listPlacements(t.projectId,["reserved","active"]).filter((o)=>o.poolId===e)){if(i.stateful){n.push(this.store.transitionPlacement(i.id,"blocked"));continue}this.store.transitionPlacement(i.id,"moving");let o=this.place({projectId:i.projectId,environmentId:i.environmentId,resourceId:i.resourceId,releaseId:i.releaseId,requirements:i.requirements});r.push(this.activate(o.id)),this.store.transitionPlacement(i.id,"released")}return{pool:t,moved:r,blocked:n}}drainServer(e,t){this.store.memberStatus(e,t,"draining");let r=this.store.getPool(e);if(!r)throw Error("Capacity pool was not found.");let n=[],i=[];for(let o of this.store.listPlacements(r.projectId,["reserved","active"]).filter((s)=>s.poolId===e&&s.serverId===t)){if(o.stateful){i.push(this.store.transitionPlacement(o.id,"blocked"));continue}this.store.transitionPlacement(o.id,"moving");let s=this.poolCandidates(o.projectId,o.requirements).find((u)=>u.eligible);if(!s){i.push(this.store.transitionPlacement(o.id,"blocked"));continue}let c=this.store.reserve({projectId:o.projectId,environmentId:o.environmentId,resourceId:o.resourceId,releaseId:o.releaseId,requirements:o.requirements,decision:s});n.push(this.activate(c.id)),this.store.transitionPlacement(o.id,"released")}return{moved:n,blocked:i}}reconcileFailure(e){let t=this.fleet.get(e);if(!t)throw Error("Server was not found.");let r=[],n=[];for(let i of this.store.listPlacements(t.projectId,["active"]).filter((o)=>o.serverId===e)){if(i.stateful||!i.autoReschedule){n.push(this.store.transitionPlacement(i.id,"blocked"));continue}this.store.transitionPlacement(i.id,"failed");let o=this.place({projectId:i.projectId,environmentId:i.environmentId,resourceId:i.resourceId,releaseId:i.releaseId,requirements:i.requirements});r.push(this.activate(o.id))}return{rescheduled:r,blocked:n}}}var ro=(e,t)=>{try{return JSON.parse(String(e))}catch{return t}},ai=(e)=>e==null?void 0:String(e),sh=(e)=>({id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:ai(e.environment_id),name:String(e.name),hostname:String(e.hostname),homeRegion:String(e.home_region),regions:ro(e.regions,[]),trafficPolicy:String(e.traffic_policy),dataPolicy:ro(e.data_policy,{replicate:[],maxLagSeconds:60,retainOnDestroy:!0}),status:String(e.status),activeRegion:String(e.active_region),revision:ai(e.revision),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),vl=(e)=>({id:String(e.id),topologyId:String(e.topology_id),region:String(e.region),role:String(e.role),provider:String(e.provider),stackId:ai(e.stack_id),stackRevision:ai(e.stack_revision),status:String(e.status),health:ro(e.health,{}),lastHealthyAt:ai(e.last_healthy_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),wl=(e)=>({id:String(e.id),topologyId:String(e.topology_id),kind:String(e.kind),sourceRegion:String(e.source_region),targetRegion:String(e.target_region),config:ro(e.config,{}),status:String(e.status),checkpoint:ai(e.checkpoint),lagSeconds:e.lag_seconds==null?void 0:Number(e.lag_seconds),lastVerifiedAt:ai(e.last_verified_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),Il=(e)=>({id:String(e.id),topologyId:String(e.topology_id),hostname:String(e.hostname),dnsProvider:String(e.dns_provider),cdnEnabled:Number(e.cdn_enabled)===1,wafEnabled:Number(e.waf_enabled)===1,weights:ro(e.weights,{}),desiredWeights:ro(e.desired_weights,{}),status:String(e.status),providerState:ro(e.provider_state,{}),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),ah=(e)=>({id:String(e.id),topologyId:String(e.topology_id),operationId:ai(e.operation_id),kind:String(e.kind),requestedRegion:ai(e.requested_region),revision:ai(e.revision),plan:ro(e.plan,[]),currentStep:ai(e.current_step),completedSteps:ro(e.completed_steps,[]),status:String(e.status),error:ai(e.error),createdAt:String(e.created_at),updatedAt:String(e.updated_at)});class On{control;now;id;constructor(e,t=()=>new Date,r=()=>crypto.randomUUID()){this.control=e;this.now=t;this.id=r}create(e){return this.control.transaction(()=>{if(e.regions.length<2||new Set(e.regions.map((o)=>o.region)).size!==e.regions.length||e.regions.filter((o)=>o.role==="primary").length!==1)throw Error("A topology requires unique regions and exactly one primary.");let t=e.regions.find((o)=>o.role==="primary"),r=this.id(),n=this.now().toISOString();this.control.database.run("INSERT INTO regional_topologies (id,organization_id,project_id,environment_id,name,hostname,home_region,regions,traffic_policy,data_policy,status,active_region,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,'draft',?,?,?)",[r,e.organizationId,e.projectId,e.environmentId??null,e.name,e.hostname,t.region,JSON.stringify(e.regions),e.trafficPolicy,JSON.stringify(e.dataPolicy),t.region,n,n]);for(let o of e.regions)this.control.database.run("INSERT INTO regional_targets (id,topology_id,region,role,provider,status,created_at,updated_at) VALUES (?,?,?,?,?,'pending',?,?)",[this.id(),r,o.region,o.role,o.provider,n,n]);for(let o of e.dataPolicy.replicate)for(let s of e.regions)for(let c of e.regions.filter((u)=>u.region!==s.region))this.control.database.run("INSERT INTO regional_replication_channels (id,topology_id,kind,source_region,target_region,config,status,created_at,updated_at) VALUES (?,?,?,?,?,?,'pending',?,?)",[this.id(),r,o,s.region,c.region,"{}",n,n]);let i=Object.fromEntries(e.regions.map((o)=>[o.region,o.region===t.region?100:0]));return this.control.database.run("INSERT INTO regional_traffic_routes (id,topology_id,hostname,dns_provider,cdn_enabled,waf_enabled,weights,desired_weights,status,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?, 'pending',?,?)",[this.id(),r,e.hostname,e.dnsProvider??"route53",e.cdnEnabled?1:0,e.wafEnabled?1:0,JSON.stringify(i),JSON.stringify(i),n,n]),this.get(r)})}get(e){let t=this.control.database.query("SELECT * FROM regional_topologies WHERE id=?").get(e);return t?sh(t):void 0}list(e){return this.control.database.query("SELECT * FROM regional_topologies WHERE project_id=? ORDER BY name").all(e).map(sh)}targets(e){return this.control.database.query("SELECT * FROM regional_targets WHERE topology_id=? ORDER BY role,region").all(e).map(vl)}channels(e){return this.control.database.query("SELECT * FROM regional_replication_channels WHERE topology_id=? ORDER BY kind,target_region").all(e).map(wl)}route(e){let t=this.control.database.query("SELECT * FROM regional_traffic_routes WHERE topology_id=?").get(e);return t?Il(t):void 0}updateTopology(e,t){let r=this.get(e);if(!r)throw Error("Regional topology was not found.");let n={...r,...t},i=this.now().toISOString();return this.control.database.run("UPDATE regional_topologies SET status=?,active_region=?,revision=?,regions=?,version=version+1,updated_at=? WHERE id=?",[n.status,n.activeRegion,n.revision??null,JSON.stringify(n.regions),i,e]),this.get(e)}updateTarget(e,t){let r=this.control.database.query("SELECT * FROM regional_targets WHERE id=?").get(e);if(!r)throw Error("Regional target was not found.");let n=vl(r),i={...n,...t},o=this.now().toISOString();return this.control.database.run("UPDATE regional_targets SET role=?,stack_id=?,stack_revision=?,status=?,health=?,last_healthy_at=?,version=version+1,updated_at=? WHERE id=?",[i.role,i.stackId??null,i.stackRevision??null,i.status,JSON.stringify(i.health),i.lastHealthyAt??null,o,e]),vl(this.control.database.query("SELECT * FROM regional_targets WHERE id=?").get(e))}updateChannel(e,t){let r=this.control.database.query("SELECT * FROM regional_replication_channels WHERE id=?").get(e);if(!r)throw Error("Replication channel was not found.");let n=wl(r),i={...n,...t},o=this.now().toISOString();return this.control.database.run("UPDATE regional_replication_channels SET status=?,checkpoint=?,lag_seconds=?,last_verified_at=?,version=version+1,updated_at=? WHERE id=?",[i.status,i.checkpoint??null,i.lagSeconds??null,i.lastVerifiedAt??null,o,e]),wl(this.control.database.query("SELECT * FROM regional_replication_channels WHERE id=?").get(e))}updateRoute(e,t){let r=this.control.database.query("SELECT * FROM regional_traffic_routes WHERE id=?").get(e);if(!r)throw Error("Traffic route was not found.");let n=Il(r),i={...n,...t},o=this.now().toISOString();return this.control.database.run("UPDATE regional_traffic_routes SET weights=?,desired_weights=?,status=?,provider_state=?,version=version+1,updated_at=? WHERE id=?",[JSON.stringify(i.weights),JSON.stringify(i.desiredWeights),i.status,JSON.stringify(i.providerState),o,e]),Il(this.control.database.query("SELECT * FROM regional_traffic_routes WHERE id=?").get(e))}createExecution(e){let t=this.id(),r=this.now().toISOString();return this.control.database.run("INSERT INTO regional_executions (id,topology_id,operation_id,kind,requested_region,revision,plan,status,created_at,updated_at) VALUES (?,?,?,?,?,?,?,'queued',?,?)",[t,e.topologyId,e.operationId??null,e.kind,e.requestedRegion??null,e.revision??null,JSON.stringify(e.plan),r,r]),this.execution(t)}execution(e){let t=this.control.database.query("SELECT * FROM regional_executions WHERE id=?").get(e);return t?ah(t):void 0}executions(e){return this.control.database.query("SELECT * FROM regional_executions WHERE topology_id=? ORDER BY created_at DESC").all(e).map(ah)}updateExecution(e,t){let r=this.execution(e);if(!r)throw Error("Regional execution was not found.");let n={...r,...t},i=this.now().toISOString();return this.control.database.run("UPDATE regional_executions SET operation_id=?,current_step=?,completed_steps=?,status=?,error=?,updated_at=? WHERE id=?",[n.operationId??null,n.currentStep??null,JSON.stringify(n.completedSteps),n.status,n.error??null,i,e]),this.execution(e)}}class $n{store;queue;constructor(e,t){this.store=e;this.queue=t??new S(e.control)}create(e){return this.store.create(e)}plan(e,t,r){if(!this.store.get(e))throw Error("Regional topology was not found.");let i=this.store.targets(e),o=this.store.channels(e);if(t==="rollout")return[...i.filter((s)=>s.role==="secondary").map((s)=>`apply:${s.region}`),...i.filter((s)=>s.role==="primary").map((s)=>`apply:${s.region}`),...o.map((s)=>`replicate:${s.kind}:${s.targetRegion}`),"traffic:activate"];if(t==="failover"||t==="failback")return[`health:${r}`,`replication:${r}`,`traffic:${r}`,`roles:${r}`];if(t==="destroy")return["traffic:drain",...i.filter((s)=>s.role==="secondary").map((s)=>`delete:${s.region}`),...i.filter((s)=>s.role==="primary").map((s)=>`delete:${s.region}`),"complete"];return["observe","repair"]}enqueue(e){let t=this.store.get(e.topologyId);if(!t)throw Error("Regional topology was not found.");if(["failover","failback"].includes(e.kind)&&(!e.targetRegion||!t.regions.some((o)=>o.region===e.targetRegion)))throw Error("A topology target region is required.");if(e.kind==="failover"&&e.targetRegion===t.activeRegion)throw Error("Target region is already active.");if((e.kind==="destroy"||e.deleteData)&&e.confirmation!==t.name)throw Error("Exact topology name confirmation is required.");if(e.deleteData&&t.dataPolicy.retainOnDestroy)throw Error("Topology policy requires regional data retention.");if(e.kind==="rollout"&&!/^[A-Za-z0-9._:@/-]{7,200}$/.test(e.revision??""))throw Error("An immutable revision is required.");let r=this.plan(t.id,e.kind,e.targetRegion),n=this.store.createExecution({topologyId:t.id,kind:e.kind,requestedRegion:e.targetRegion,revision:e.revision,plan:r}),i=this.queue.enqueue({projectId:t.projectId,environmentId:t.environmentId,kind:`region.${e.kind}`,input:{executionId:n.id,manifest:e.manifest??{},deleteData:e.deleteData===!0},lockKey:`regional-topology:${t.id}`,providerKey:"multi-region",timeoutSeconds:7200,cancellationMode:"provider_non_cancellable",resumePolicy:"requeue",maxAttempts:3}).operation;return this.store.updateExecution(n.id,{operationId:i.id}),{execution:this.store.execution(n.id),operation:i}}}var gC=(e)=>e&&typeof e==="object"&&!Array.isArray(e)?e:{};function ch(e,t){let r=(a)=>{let f=t.find((T)=>T.provider===a.provider);if(!f)throw Error(`No ${a.provider} regional driver is configured.`);return f},n=(a,f,T)=>{a.throwIfCancellationRequested(),a.checkpoint(T,T),e.updateExecution(f.id,{status:"running",currentStep:T,completedSteps:[...e.execution(f.id).completedSteps,T]})},i=async(a,f)=>{let T=e.route(a.id);if(!T)throw Error("Regional traffic route was not found.");let R=e.targets(a.id).find((W)=>W.region===a.activeRegion)??e.targets(a.id)[0];if(!R)throw Error("Regional traffic target was not found.");e.updateRoute(T.id,{status:"applying",desiredWeights:f});let D=await r(R).applyTraffic({route:e.route(a.id),topology:a,weights:f});e.updateRoute(T.id,{status:Object.values(f).every((W)=>W===0)?"drained":"in_sync",weights:f,providerState:D.providerState})},o=async(a,f,T,R)=>{e.updateTopology(T.id,{status:"provisioning"});let D=f.revision,W=R.manifest??{},Y=e.targets(T.id).sort((ne,he)=>Number(ne.role==="primary")-Number(he.role==="primary"));for(let ne of Y){n(a,f,`apply:${ne.region}`),e.updateTarget(ne.id,{status:"provisioning"});let he=await r(ne).applyStack({target:ne,revision:D,manifest:W,signal:a.signal}),te=await r(ne).health({target:e.updateTarget(ne.id,{stackId:he.stackId,stackRevision:D})});if(!te.healthy)throw Error(`Regional health gate failed in ${ne.region}.`);e.updateTarget(ne.id,{status:"ready",health:te.evidence,lastHealthyAt:new Date().toISOString()})}for(let ne of e.channels(T.id)){n(a,f,`replicate:${ne.kind}:${ne.targetRegion}`),e.updateChannel(ne.id,{status:"configuring"});let he=Y.find((tt)=>tt.region===ne.sourceRegion),te=await r(he).configureReplication({channel:ne,topology:T}),De=await r(he).verifyReplication({channel:e.updateChannel(ne.id,{checkpoint:te.checkpoint,lagSeconds:te.lagSeconds}),topology:T});if(!De.healthy||De.lagSeconds>T.dataPolicy.maxLagSeconds)throw Error(`${ne.kind} replication to ${ne.targetRegion} exceeds the RPO.`);e.updateChannel(ne.id,{status:"in_sync",checkpoint:De.checkpoint,lagSeconds:De.lagSeconds,lastVerifiedAt:new Date().toISOString()})}n(a,f,"traffic:activate");let ee=Object.fromEntries(T.regions.map((ne)=>[ne.region,ne.region===T.activeRegion?100:0]));return await i(T,ee),e.updateTopology(T.id,{status:"ready",revision:D}),{revision:D,activeRegion:T.activeRegion}},s=async(a,f,T)=>{let R=f.requestedRegion,D=e.targets(T.id).find((ee)=>ee.region===R);if(!D)throw Error("Requested regional target was not found.");e.updateTopology(T.id,{status:f.kind==="failover"?"failing_over":"failing_back"}),n(a,f,`health:${R}`);let W=await r(D).health({target:D});if(!W.healthy)throw Error(`Target region ${R} is unhealthy.`);e.updateTarget(D.id,{status:"ready",health:W.evidence,lastHealthyAt:new Date().toISOString()}),n(a,f,`replication:${R}`);for(let ee of e.channels(T.id).filter((ne)=>ne.targetRegion===R)){let ne=await r(D).verifyReplication({channel:ee,topology:T});if(!ne.healthy||ne.lagSeconds>T.dataPolicy.maxLagSeconds)throw Error(`${ee.kind} replication is outside the failover RPO.`);e.updateChannel(ee.id,{status:"in_sync",checkpoint:ne.checkpoint,lagSeconds:ne.lagSeconds,lastVerifiedAt:new Date().toISOString()})}n(a,f,`traffic:${R}`),await i(T,Object.fromEntries(T.regions.map((ee)=>[ee.region,ee.region===R?100:0]))),n(a,f,`roles:${R}`);let Y=T.regions.map((ee)=>({...ee,role:ee.region===R?"primary":"secondary"}));for(let ee of e.targets(T.id))e.updateTarget(ee.id,{role:ee.region===R?"primary":"secondary"});return e.updateTopology(T.id,{status:f.kind==="failover"?"failed_over":"ready",activeRegion:R,regions:Y}),{activeRegion:R}},c=async(a,f,T,R)=>{e.updateTopology(T.id,{status:"destroying"}),n(a,f,"traffic:drain"),await i(T,Object.fromEntries(T.regions.map((W)=>[W.region,0])));let D=R.deleteData!==!0;for(let W of e.targets(T.id).sort((Y,ee)=>Number(Y.role==="primary")-Number(ee.role==="primary")))n(a,f,`delete:${W.region}`),e.updateTarget(W.id,{status:"deleting"}),await r(W).deleteStack({target:W,retainData:D,signal:a.signal}),e.updateTarget(W.id,{status:"deleted"});return n(a,f,"complete"),e.updateTopology(T.id,{status:"destroyed"}),{destroyed:!0,dataRetained:D}},u=async(a)=>{let f=gC(a.operation.input),T=e.execution(String(f.executionId??""));if(!T)throw Error("Regional execution was not found.");let R=e.get(T.topologyId);if(!R)throw Error("Regional topology was not found.");try{let D;if(T.kind==="rollout")D=await o(a,T,R,f);else if(T.kind==="failover"||T.kind==="failback")D=await s(a,T,R);else if(T.kind==="destroy")D=await c(a,T,R,f);else throw Error("Regional reconciliation is not configured.");return e.updateExecution(T.id,{status:"succeeded",currentStep:void 0}),{executionId:T.id,...D}}catch(D){if(e.updateExecution(T.id,{status:a.cancellationRequested()?"cancelled":"failed",error:D instanceof Error?D.message:String(D)}),e.get(R.id)?.status!=="destroyed")e.updateTopology(R.id,{status:"failed"});throw D}};return{"region.rollout":u,"region.failover":u,"region.failback":u,"region.destroy":u,"region.reconcile":u}}class Cl{provider;reason;constructor(e,t="Configure a regional provider transport before executing this operation."){this.provider=e;this.reason=t}fail(){throw Error(this.reason)}async applyStack(){return this.fail()}async deleteStack(){this.fail()}async health(){return this.fail()}async configureReplication(){return this.fail()}async verifyReplication(){return this.fail()}async applyTraffic(){return this.fail()}}function Mi(e,t,r){return[e,t,r].map((n)=>encodeURIComponent(n)).join(":")}function mC(e){return Object.fromEntries(["start","stop","restart","redeploy","scale","logs","exec","inspect","files"].map((t)=>[t,{supported:!1,reason:e}]))}function is(e,t,r=["exec","files"]){let n=mC(t);for(let i of e)n[i]={supported:!0,requiresConfirmation:!["logs","inspect"].includes(i),requiresRecentAuth:r.includes(i)};return n}var fC=/(?:secret|password|passwd|token|api[_-]?key|private[_-]?key|credential|authorization|cookie)/i;function so(e){let t=String(e??"").trim().toLowerCase();if(["active","running","ready","healthy","available","steady","active:running"].includes(t))return"running";if(["activating","pending","provisioning","starting","created","initializing"].includes(t))return"starting";if(["deactivating","stopping","draining","terminating"].includes(t))return"stopping";if(["inactive","stopped","complete","completed","exited","disabled"].includes(t))return"stopped";if(["degraded","unhealthy","warning"].includes(t))return"degraded";if(["failed","dead","error","crashed","oomkilled"].includes(t))return"failed";return"unknown"}function no(e){if(Array.isArray(e))return e.map((r)=>no(r));if(!e||typeof e!=="object")return e;let t={};for(let[r,n]of Object.entries(e))t[r]=fC.test(r)?"[REDACTED]":no(n);return t}function os(e,t=new Date){if(!e)return;let r=new Date(e).getTime();return Number.isFinite(r)?Math.max(0,Math.floor((t.getTime()-r)/1000)):void 0}function dh(e){let t=Number(e);return Number.isFinite(t)&&t>=0?t:void 0}function hC(e){let t=String(e?.message??e);if(/(?:unauthorized|accessdenied|forbidden|credentials)/i.test(t))return"unauthorized";if(/(?:timeout|unreachable|econnrefused|enotfound|network)/i.test(t))return"unreachable";return"error"}async function uh(e,t={},r={}){let n=t.now??new Date,i=Math.max(100,r.timeoutMs??1e4),o=Math.max(1,r.staleAfterSeconds??60),s=await Promise.all(e.map(async(u)=>{try{let a=await Promise.race([u.discover({...t,now:n}),new Promise((f,T)=>setTimeout(()=>T(Error(`Runtime source ${u.id} timed out after ${i}ms`)),i))]);return{workloads:a,source:{id:u.id,provider:u.provider,status:"fresh",discoveredAt:n.toISOString(),staleAfterSeconds:o,itemCount:a.length}}}catch(a){return{workloads:[],source:{id:u.id,provider:u.provider,status:hC(a),discoveredAt:n.toISOString(),staleAfterSeconds:o,itemCount:0,message:String(a?.message??a).slice(0,500)}}}})),c=s.map((u)=>u.source);return{generatedAt:n.toISOString(),workloads:s.flatMap((u)=>u.workloads).sort((u,a)=>u.name.localeCompare(a.name)||u.id.localeCompare(a.id)),sources:c,degraded:c.some((u)=>u.status!=="fresh")}}function yC(e,t){if(!t)return e;return e.startsWith(t)?e.slice(t.length):e}function lh(e,t,r){let n=yC(e,t);return`${r??""}${n}`}function ph(e,t,r){if(r&&r.some((n)=>e.startsWith(n)))return!1;if(t&&t.length>0)return t.some((n)=>e.startsWith(n));return!0}async function bC(e,t,r){let n=0,i=[],o=Math.max(1,Math.min(t,e.length||1));for(let s=0;s<o;s++)i.push((async()=>{while(!0){let c=n++;if(c>=e.length)return;await r(e[c],c)}})());await Promise.all(i)}function gh(e){if(e.client)return e.client;return mh({provider:e.provider,region:e.region,endpoint:e.endpoint,forcePathStyle:e.forcePathStyle,credentials:e.credentials})}async function ts(e){let t=e.concurrency??8,r=gh(e.from),n=gh(e.to),i=await r.listAllObjects({bucket:e.from.bucket,prefix:e.from.prefix}),o={copied:0,skipped:0,excluded:0,bytesCopied:0,errors:[],excludedKeys:[],deleted:[]},s=[];for(let f of i){if(!ph(f.Key,e.include,e.exclude)){o.excluded++,o.excludedKeys.push(f.Key);continue}s.push({source:f,destKey:lh(f.Key,e.from.prefix,e.to.prefix)})}if(e.dryRun){o.plan=s.map(({source:R,destKey:D})=>({key:R.Key,destKey:D,size:R.Size}));let f=i.length,T=0;for(let R of i){T++;let D=!ph(R.Key,e.include,e.exclude);e.onProgress?.({key:R.Key,destKey:D?"":lh(R.Key,e.from.prefix,e.to.prefix),size:R.Size,action:D?"excluded":"planned",index:T,total:f})}return o}let c=s.length,u=0;await bC(s,t,async({source:f,destKey:T})=>{let R=++u;try{if(!e.force){let Y=await n.headObject(e.to.bucket,T);if(Y&&Y.ContentLength===f.Size){o.skipped++,e.onProgress?.({key:f.Key,destKey:T,size:f.Size,action:"skipped",index:R,total:c});return}}let{body:D,contentType:W}=await r.getObjectBytes(e.from.bucket,f.Key);await n.putObject({bucket:e.to.bucket,key:T,body:D,contentType:W}),o.copied++,o.bytesCopied+=D.byteLength,e.onProgress?.({key:f.Key,destKey:T,size:f.Size,action:"copied",index:R,total:c})}catch(D){o.errors.push({key:f.Key,message:D?.message??String(D)}),e.onProgress?.({key:f.Key,destKey:T,size:f.Size,action:"error",index:R,total:c})}});let a=new Set(s.map((f)=>f.destKey));if(e.deleteExtraneous){let T=(await n.listAllObjects({bucket:e.to.bucket,prefix:e.to.prefix})).filter((R)=>!a.has(R.Key)).map((R)=>R.Key);for(let R of T)try{await n.deleteObject(e.to.bucket,R),o.deleted.push(R)}catch(D){o.errors.push({key:R,message:`delete failed: ${D?.message??String(D)}`})}}if(e.verify){let f=await n.listAllObjects({bucket:e.to.bucket,prefix:e.to.prefix}),T=new Map(f.map((Y)=>[Y.Key,Y.Size])),R=[],D=[],W=0;for(let{source:Y,destKey:ee}of s){if(!T.has(ee)){R.push(ee);continue}let ne=T.get(ee);if(ne!==Y.Size){D.push({key:ee,expected:Y.Size,actual:ne});continue}W++}o.verification={ok:R.length===0&&D.length===0,matched:W,missing:R,sizeMismatches:D}}return o}var SC={aws:"us-east-1",backblaze:"us-west-004",hetzner:"fsn1"};function vC(e,t){switch(e){case"backblaze":return`s3.${t}.backblazeb2.com`;case"hetzner":return`${t}.your-objectstorage.com`;case"aws":default:return}}function In(...e){for(let t of e){let r=process.env[t];if(r)return r}return}function wC(e,t){if(t?.accessKeyId&&t.secretAccessKey)return t;let r,n;if(e==="backblaze")r=In("B2_APPLICATION_KEY_ID","B2_KEY_ID","S3_ACCESS_KEY_ID","AWS_ACCESS_KEY_ID"),n=In("B2_APPLICATION_KEY","B2_SECRET_KEY","S3_SECRET_ACCESS_KEY","AWS_SECRET_ACCESS_KEY");else if(e==="hetzner")r=In("HETZNER_S3_ACCESS_KEY","HETZNER_ACCESS_KEY","S3_ACCESS_KEY_ID","AWS_ACCESS_KEY_ID"),n=In("HETZNER_S3_SECRET_KEY","HETZNER_SECRET_KEY","S3_SECRET_ACCESS_KEY","AWS_SECRET_ACCESS_KEY");else r=In("S3_ACCESS_KEY_ID"),n=In("S3_SECRET_ACCESS_KEY");if(r&&n)return{accessKeyId:r,secretAccessKey:n,sessionToken:In("AWS_SESSION_TOKEN")};return}function IC(e={}){let t=e.provider||In("OBJECT_STORAGE_PROVIDER","STORAGE_PROVIDER")||"aws",r=e.region||(t==="backblaze"?In("B2_REGION"):void 0)||(t==="hetzner"?In("HETZNER_S3_REGION","HETZNER_REGION"):void 0)||In("S3_REGION","AWS_REGION","AWS_DEFAULT_REGION")||SC[t],n=e.endpoint||In("S3_ENDPOINT")||vC(t,r),i=e.forcePathStyle??In("S3_FORCE_PATH_STYLE")==="true",o=wC(t,e.credentials),s=(c)=>{let u=n||`s3.${r}.amazonaws.com`;return i?`https://${u}/${c}`:`https://${c}.${u}`};return{provider:t,region:r,endpoint:n,forcePathStyle:i,credentials:o,profile:e.profile,publicBaseUrl:s}}function mh(e={}){let t=IC(e),r={endpoint:t.endpoint,forcePathStyle:t.forcePathStyle,credentials:t.credentials};return new g(t.region,t.profile,r)}class Nt{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new p(void 0,{profile:t})}async describeServices(e){let t={cluster:e.cluster,services:e.services};return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DescribeServices","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async listServices(e,t={}){let r={cluster:e,...t};return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.ListServices","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)})}async listTasks(e,t,r={}){let n={cluster:e,...r};if(t)n.serviceName=t;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.ListTasks","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(n)})}async describeTasks(e,t){let r={cluster:e,tasks:t};return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DescribeTasks","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)})}async updateService(e){let t={cluster:e.cluster,service:e.service};if(e.forceNewDeployment!==void 0)t.forceNewDeployment=e.forceNewDeployment;if(e.desiredCount!==void 0)t.desiredCount=e.desiredCount;if(e.taskDefinition)t.taskDefinition=e.taskDefinition;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.UpdateService","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async createService(e){let t={cluster:e.cluster,serviceName:e.serviceName,taskDefinition:e.taskDefinition,desiredCount:e.desiredCount};if(e.launchType)t.launchType=e.launchType;if(e.networkConfiguration)t.networkConfiguration=e.networkConfiguration;if(e.loadBalancers)t.loadBalancers=e.loadBalancers;if(e.healthCheckGracePeriodSeconds!==void 0)t.healthCheckGracePeriodSeconds=e.healthCheckGracePeriodSeconds;if(e.deploymentConfiguration)t.deploymentConfiguration=e.deploymentConfiguration;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.CreateService","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async deleteService(e){let t={cluster:e.cluster,service:e.service};if(e.force!==void 0)t.force=e.force;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DeleteService","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async listClusters(e={}){return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.ListClusters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(e)})}async describeClusters(e){let t={clusters:e,include:["ATTACHMENTS","CONFIGURATIONS","SETTINGS","STATISTICS","TAGS"]};return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DescribeClusters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async stopTask(e){let t={cluster:e.cluster,task:e.task};if(e.reason)t.reason=e.reason;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.StopTask","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async runTask(e){let t={cluster:e.cluster,taskDefinition:e.taskDefinition};if(e.count!==void 0)t.count=e.count;if(e.launchType)t.launchType=e.launchType;if(e.networkConfiguration)t.networkConfiguration=e.networkConfiguration;if(e.overrides)t.overrides=e.overrides;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.RunTask","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async registerTaskDefinition(e){return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.RegisterTaskDefinition","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(e)})}async deregisterTaskDefinition(e){return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DeregisterTaskDefinition","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({taskDefinition:e})})}async describeTaskDefinition(e){return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DescribeTaskDefinition","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({taskDefinition:e,include:["TAGS"]})})}async listTaskDefinitionFamilies(e){let t={};if(e?.familyPrefix)t.familyPrefix=e.familyPrefix;if(e?.status)t.status=e.status;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.ListTaskDefinitionFamilies","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async waitForServiceStable(e,t,r=40,n=15000){for(let i=0;i<r;i++){let s=(await this.describeServices({cluster:e,services:[t]})).services?.[0];if(s){let c=s.deployments?.find((u)=>u.status==="PRIMARY");if(c&&c.runningCount===c.desiredCount&&s.deployments?.length===1)return!0}await new Promise((c)=>setTimeout(c,n))}return!1}async forceNewDeployment(e,t){return this.updateService({cluster:e,service:t,forceNewDeployment:!0})}async scaleService(e,t,r){return this.updateService({cluster:e,service:t,desiredCount:r})}}class de{client;region;constructor(e="us-east-1"){this.region=e,this.client=new p}buildFormBody(e){return Object.entries(e).filter(([,r])=>r!==void 0).map(([r,n])=>`${encodeURIComponent(r)}=${encodeURIComponent(n)}`).join("&")}async createTopic(e){let t={Action:"CreateTopic",Version:"2010-03-31",Name:e.Name};if(e.DisplayName)t["Attributes.entry.1.key"]="DisplayName",t["Attributes.entry.1.value"]=e.DisplayName;if(e.Tags)e.Tags.forEach((n,i)=>{t[`Tags.member.${i+1}.Key`]=n.Key,t[`Tags.member.${i+1}.Value`]=n.Value});if(e.Attributes){let n=e.DisplayName?2:1;Object.entries(e.Attributes).forEach(([i,o])=>{t[`Attributes.entry.${n}.key`]=i,t[`Attributes.entry.${n}.value`]=o,n++})}let r=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)});return{TopicArn:_(r,"CreateTopic")?.TopicArn}}async deleteTopic(e){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteTopic",Version:"2010-03-31",TopicArn:e})})}async listTopics(e){let t={Action:"ListTopics",Version:"2010-03-31"};if(e)t.NextToken=e;let r=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)}),n=r?.ListTopicsResponse?.ListTopicsResult||r?.ListTopicsResult,i=n?.Topics?.member;return{Topics:Array.isArray(i)?i:i?[i]:[],NextToken:n?.NextToken}}async getTopicAttributes(e){let t=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"GetTopicAttributes",Version:"2010-03-31",TopicArn:e})}),r=N(_(t,"GetTopicAttributes")?.Attributes?.entry),n={TopicArn:e};for(let i of r)n[i.key]=String(i.value);return n}async setTopicAttributes(e){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"SetTopicAttributes",Version:"2010-03-31",TopicArn:e.TopicArn,AttributeName:e.AttributeName,AttributeValue:e.AttributeValue})})}async subscribe(e){let t={Action:"Subscribe",Version:"2010-03-31",TopicArn:e.TopicArn,Protocol:e.Protocol,Endpoint:e.Endpoint};if(e.ReturnSubscriptionArn)t.ReturnSubscriptionArn="true";if(e.Attributes){let n=1;Object.entries(e.Attributes).forEach(([i,o])=>{t[`Attributes.entry.${n}.key`]=i,t[`Attributes.entry.${n}.value`]=o,n++})}let r=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)});return{SubscriptionArn:_(r,"Subscribe")?.SubscriptionArn}}async unsubscribe(e){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"Unsubscribe",Version:"2010-03-31",SubscriptionArn:e})})}async listSubscriptionsByTopic(e,t){let r={Action:"ListSubscriptionsByTopic",Version:"2010-03-31",TopicArn:e};if(t)r.NextToken=t;let n=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(r)}),i=_(n,"ListSubscriptionsByTopic");return{Subscriptions:N(i?.Subscriptions?.member),NextToken:i?.NextToken||void 0}}async publish(e){let t={Action:"Publish",Version:"2010-03-31",Message:e.Message};if(e.TopicArn)t.TopicArn=e.TopicArn;if(e.TargetArn)t.TargetArn=e.TargetArn;if(e.PhoneNumber)t.PhoneNumber=e.PhoneNumber;if(e.Subject)t.Subject=e.Subject;if(e.MessageStructure)t.MessageStructure=e.MessageStructure;if(e.MessageAttributes){let n=1;Object.entries(e.MessageAttributes).forEach(([i,o])=>{if(t[`MessageAttributes.entry.${n}.Name`]=i,t[`MessageAttributes.entry.${n}.Value.DataType`]=o.DataType,o.StringValue)t[`MessageAttributes.entry.${n}.Value.StringValue`]=o.StringValue;if(o.BinaryValue)t[`MessageAttributes.entry.${n}.Value.BinaryValue`]=o.BinaryValue;n++})}let r=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)});return{MessageId:_(r,"Publish")?.MessageId}}async publishSMS(e,t,r){let n={};if(r)n["AWS.SNS.SMS.SenderID"]={DataType:"String",StringValue:r};return this.publish({PhoneNumber:e,Message:t,MessageAttributes:Object.keys(n).length>0?n:void 0})}async subscribeEmail(e,t){return this.subscribe({TopicArn:e,Protocol:"email",Endpoint:t})}async subscribeLambda(e,t){return this.subscribe({TopicArn:e,Protocol:"lambda",Endpoint:t})}async subscribeSqs(e,t,r){let n={};if(r)n.RawMessageDelivery="true";return this.subscribe({TopicArn:e,Protocol:"sqs",Endpoint:t,Attributes:Object.keys(n).length>0?n:void 0})}async subscribeHttp(e,t,r){let n=t.startsWith("https")?"https":"http",i={};if(r)i.RawMessageDelivery="true";return this.subscribe({TopicArn:e,Protocol:n,Endpoint:t,Attributes:Object.keys(i).length>0?i:void 0})}async subscribeSms(e,t){return this.subscribe({TopicArn:e,Protocol:"sms",Endpoint:t})}async topicExists(e){try{return await this.getTopicAttributes(e),!0}catch(t){if(t.code==="NotFound"||t.statusCode===404)return!1;throw t}}async getSMSAttributes(){let e=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"GetSMSAttributes",Version:"2010-03-31"})}),t=N(_(e,"GetSMSAttributes")?.attributes?.entry),r={};for(let n of t)r[n.key]=String(n.value);return r}async setSMSAttributes(e){let t={Action:"SetSMSAttributes",Version:"2010-03-31"},r=1;Object.entries(e).forEach(([n,i])=>{if(i!==void 0)t[`attributes.entry.${r}.key`]=n,t[`attributes.entry.${r}.value`]=i,r++}),await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)})}async checkIfPhoneNumberIsOptedOut(e){let t=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"CheckIfPhoneNumberIsOptedOut",Version:"2010-03-31",phoneNumber:e})});return ea(_(t,"CheckIfPhoneNumberIsOptedOut")?.isOptedOut)}async listPhoneNumbersOptedOut(e){let t={Action:"ListPhoneNumbersOptedOut",Version:"2010-03-31"};if(e)t.nextToken=e;let r=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)}),n=_(r,"ListPhoneNumbersOptedOut");return{phoneNumbers:N(n?.phoneNumbers?.member).map(String),nextToken:n?.nextToken||void 0}}async optInPhoneNumber(e){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"OptInPhoneNumber",Version:"2010-03-31",phoneNumber:e})})}async listSMSSandboxPhoneNumbers(e){let t={Action:"ListSMSSandboxPhoneNumbers",Version:"2010-03-31"};if(e)t.NextToken=e;let r=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)}),n=_(r,"ListSMSSandboxPhoneNumbers");return{PhoneNumbers:N(n?.PhoneNumbers?.member),NextToken:n?.NextToken||void 0}}async createSMSSandboxPhoneNumber(e,t){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"CreateSMSSandboxPhoneNumber",Version:"2010-03-31",PhoneNumber:e,LanguageCode:t||"en-US"})})}async verifySMSSandboxPhoneNumber(e,t){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"VerifySMSSandboxPhoneNumber",Version:"2010-03-31",PhoneNumber:e,OneTimePassword:t})})}async deleteSMSSandboxPhoneNumber(e){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteSMSSandboxPhoneNumber",Version:"2010-03-31",PhoneNumber:e})})}async getSMSSandboxAccountStatus(){let e=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"GetSMSSandboxAccountStatus",Version:"2010-03-31"})});return{IsInSandbox:ea(_(e,"GetSMSSandboxAccountStatus")?.IsInSandbox)}}}class q{client;region;endpoint;constructor(e="us-east-1",t){this.region=e,this.endpoint=t?.endpoint,this.client=new p}async request(e,t){if(this.endpoint){let r=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-amz-json-1.0","X-Amz-Target":`DynamoDB_20120810.${e}`},body:JSON.stringify(t)});if(!r.ok){let n=await r.text();throw Error(`DynamoDB request failed: ${r.status} ${n}`)}return r.json()}return this.client.request({service:"dynamodb",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.0","X-Amz-Target":`DynamoDB_20120810.${e}`},body:JSON.stringify(t)})}async createTable(e){return this.request("CreateTable",e)}async deleteTable(e){return this.request("DeleteTable",e)}async describeTable(e){return this.request("DescribeTable",e)}async listTables(e){return this.request("ListTables",e||{})}async putItem(e){return this.request("PutItem",e)}async getItem(e){return this.request("GetItem",e)}async updateItem(e){return this.request("UpdateItem",e)}async deleteItem(e){return this.request("DeleteItem",e)}async query(e){return this.request("Query",e)}async scan(e){return this.request("Scan",e)}async batchWriteItem(e){return this.request("BatchWriteItem",e)}async batchGetItem(e){return this.request("BatchGetItem",e)}async updateTimeToLive(e){return this.request("UpdateTimeToLive",e)}static marshal(e){let t={};for(let[r,n]of Object.entries(e))t[r]=q.marshalValue(n);return t}static marshalValue(e){if(e===null||e===void 0)return{NULL:!0};if(typeof e==="string")return{S:e};if(typeof e==="number")return{N:String(e)};if(typeof e==="boolean")return{BOOL:e};if(Array.isArray(e))return{L:e.map((t)=>q.marshalValue(t))};if(typeof e==="object")return{M:q.marshal(e)};return{S:String(e)}}static unmarshal(e){let t={};for(let[r,n]of Object.entries(e))t[r]=q.unmarshalValue(n);return t}static unmarshalValue(e){if(e.S!==void 0)return e.S;if(e.N!==void 0)return Number(e.N);if(e.BOOL!==void 0)return e.BOOL;if(e.NULL!==void 0)return null;if(e.L!==void 0)return e.L.map((t)=>q.unmarshalValue(t));if(e.M!==void 0)return q.unmarshal(e.M);if(e.SS!==void 0)return e.SS;if(e.NS!==void 0)return e.NS.map(Number);return null}}var $_=(()=>{let e=new Uint32Array(256);for(let t=0;t<256;t++){let r=t;for(let n=0;n<8;n++)r=r&1?3988292384^r>>>1:r>>>1;e[t]=r>>>0}return e})();class be{client;region;constructor(e="us-east-1"){this.region=e,this.client=new p}async request(e,t){return this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`AWSEvents.${e}`},body:JSON.stringify(t)})}async putRule(e){return this.request("PutRule",e)}async deleteRule(e){return this.request("DeleteRule",e)}async describeRule(e){return this.request("DescribeRule",e)}async listRules(e){return this.request("ListRules",e||{})}async listEventBuses(e){return this.request("ListEventBuses",e||{})}async enableRule(e){return this.request("EnableRule",e)}async disableRule(e){return this.request("DisableRule",e)}async putTargets(e){return this.request("PutTargets",e)}async removeTargets(e){return this.request("RemoveTargets",e)}async listTargetsByRule(e){return this.request("ListTargetsByRule",e)}async putEvents(e){return this.request("PutEvents",e)}async createSchedule(e){return this.client.request({service:"scheduler",region:this.region,method:"POST",path:`/schedules/${e.Name}`,headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}}class $e{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new p}async createRule(e){let t={Action:"PutRule",Name:e.name,ScheduleExpression:e.scheduleExpression,Version:"2015-10-07"};if(e.description)t.Description=e.description;if(e.state)t.State=e.state;else t.State="ENABLED";return{RuleArn:(await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.PutRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:e.name,ScheduleExpression:e.scheduleExpression,State:e.state||"ENABLED",Description:e.description})})).RuleArn}}async putTargets(e,t){await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.PutTargets","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Rule:e,Targets:t})})}async listRules(e){let t={};if(e)t.NamePrefix=e;return{Rules:(await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.ListRules","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})).Rules||[]}}async describeRule(e){let t=await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.DescribeRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:e})});return{Name:t.Name,Arn:t.Arn,ScheduleExpression:t.ScheduleExpression,State:t.State,Description:t.Description}}async listTargetsByRule(e){return{Targets:(await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.ListTargetsByRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Rule:e})})).Targets||[]}}async deleteRule(e,t){if(t)try{let r=await this.listTargetsByRule(e);if(r.Targets&&r.Targets.length>0)await this.removeTargets(e,r.Targets.map((n)=>n.Id))}catch{}await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.DeleteRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:e,Force:t||!1})})}async removeTargets(e,t){await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.RemoveTargets","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Rule:e,Ids:t})})}async enableRule(e){await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.EnableRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:e})})}async disableRule(e){await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.DisableRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:e})})}async createLambdaSchedule(e){let t=await this.createRule({name:e.name,scheduleExpression:e.scheduleExpression,description:e.description,state:"ENABLED"});return await this.putTargets(e.name,[{Id:"1",Arn:e.functionArn,Input:e.input}]),t}async createEcsSchedule(e){let t=await this.createRule({name:e.name,scheduleExpression:e.scheduleExpression,description:e.description,state:"ENABLED"});return await this.putTargets(e.name,[{Id:"1",Arn:e.clusterArn,RoleArn:e.roleArn,Input:JSON.stringify({containerOverrides:[]})}]),t}async listSchedules(e){let t={};if(e?.NamePrefix)t.NamePrefix=e.NamePrefix;if(e?.State)t.State=e.State;let r=e?.GroupName||"default";return{Schedules:(await this.client.request({service:"scheduler",region:this.region,method:"GET",path:"/schedules",queryParams:{...t,ScheduleGroup:r}}))?.Schedules||[]}}async getSchedule(e){try{let t={};if(e.GroupName)t.groupName=e.GroupName;return await this.client.request({service:"scheduler",region:this.region,method:"GET",path:`/schedules/${encodeURIComponent(e.Name)}`,queryParams:Object.keys(t).length>0?t:void 0})}catch(t){if(t.statusCode===404||t.code==="ResourceNotFoundException")return null;throw t}}async createSchedule(e){let t={ScheduleExpression:e.ScheduleExpression,FlexibleTimeWindow:e.FlexibleTimeWindow,Target:e.Target};if(e.GroupName)t.GroupName=e.GroupName;if(e.ScheduleExpressionTimezone)t.ScheduleExpressionTimezone=e.ScheduleExpressionTimezone;if(e.Description)t.Description=e.Description;if(e.State)t.State=e.State;if(e.StartDate)t.StartDate=e.StartDate.toISOString();if(e.EndDate)t.EndDate=e.EndDate.toISOString();return{ScheduleArn:(await this.client.request({service:"scheduler",region:this.region,method:"POST",path:`/schedules/${encodeURIComponent(e.Name)}`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}))?.ScheduleArn||""}}async updateSchedule(e){let t={};if(e.GroupName)t.GroupName=e.GroupName;if(e.ScheduleExpression)t.ScheduleExpression=e.ScheduleExpression;if(e.ScheduleExpressionTimezone)t.ScheduleExpressionTimezone=e.ScheduleExpressionTimezone;if(e.Description!==void 0)t.Description=e.Description;if(e.State)t.State=e.State;if(e.FlexibleTimeWindow)t.FlexibleTimeWindow=e.FlexibleTimeWindow;if(e.Target)t.Target=e.Target;return{ScheduleArn:(await this.client.request({service:"scheduler",region:this.region,method:"PUT",path:`/schedules/${encodeURIComponent(e.Name)}`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}))?.ScheduleArn||""}}async deleteSchedule(e){let t={};if(e.GroupName)t.groupName=e.GroupName;await this.client.request({service:"scheduler",region:this.region,method:"DELETE",path:`/schedules/${encodeURIComponent(e.Name)}`,queryParams:Object.keys(t).length>0?t:void 0})}async listScheduleGroups(e){let t={};if(e?.NamePrefix)t.NamePrefix=e.NamePrefix;return{ScheduleGroups:(await this.client.request({service:"scheduler",region:this.region,method:"GET",path:"/schedule-groups",queryParams:Object.keys(t).length>0?t:void 0}))?.ScheduleGroups||[]}}}function Qs(e){return e?.split("/").at(-1)??e?.split(":").at(-1)??"unknown"}function fh(e,t,r,n="ecs:aws",i=[]){let o=r.now??new Date;return e.map((s)=>{let c=s.serviceName??Qs(s.serviceArn),u=t.filter((ne)=>!s.clusterArn||ne.clusterArn===s.clusterArn),a=u.some((ne)=>!!ne.group)?u.filter((ne)=>ne.group===`service:${c}`):u,f=s.status==="ACTIVE"?(s.runningCount??0)<(s.desiredCount??0)?"degraded":"running":so(s.status),T=i.find((ne)=>ne.taskDefinitionArn===s.taskDefinition),R=Array.isArray(T?.containerDefinitions)?T.containerDefinitions:[],D=[...new Set(R.map((ne)=>ne.logConfiguration?.options?.["awslogs-group"]).filter((ne)=>typeof ne==="string"))],W=R.flatMap((ne)=>(ne.mountPoints??[]).map((he)=>({source:he.sourceVolume,target:he.containerPath,type:"volume",readOnly:!!he.readOnly}))),Y=R.flatMap((ne)=>(ne.portMappings??[]).map((he,te)=>({id:`${ne.name??"container"}:${te}`,name:ne.name,mode:T?.networkMode,ports:[{container:he.containerPort,host:he.hostPort,protocol:he.protocol}]}))),ee=r.project&&r.environment&&c.startsWith(`${r.project}-${r.environment}-`)?c.slice(`${r.project}-${r.environment}-`.length):c;return{id:Mi("ecs",n,s.serviceArn??c),provider:"ecs",kind:"service",name:c,status:f,rawStatus:s.status,health:f==="running"?"healthy":f==="failed"||f==="degraded"?"unhealthy":"unknown",desiredReplicas:s.desiredCount,runningReplicas:s.runningCount,image:R[0]?.image,runtime:s.launchType??"ECS",version:Qs(s.taskDefinition),ageSeconds:os(s.deployments?.[0]?.createdAt,o),restartCount:0,tags:{},links:{project:r.project,environment:r.environment,service:ee,release:Qs(s.taskDefinition),providerId:s.serviceArn},replicas:a.map((ne)=>{let he=so(ne.lastStatus);return{id:Mi("ecs",n,ne.taskArn??Qs(ne.taskArn)),name:Qs(ne.taskArn),status:he,rawStatus:ne.lastStatus,createdAt:ne.createdAt,startedAt:ne.startedAt,stoppedAt:ne.stoppedAt,host:ne.containerInstanceArn,containers:(ne.containers??[]).map((te)=>({id:te.containerArn??te.name??"container",name:te.name??"container",image:R.find((De)=>De.name===te.name)?.image,imageDigest:te.imageDigest,status:so(te.lastStatus),rawStatus:te.lastStatus,exitCode:te.exitCode,reason:te.reason,runtime:"ecs"}))}}),networks:Y,mounts:W,capabilities:is(["start","stop","restart","redeploy","scale","inspect",...D.length?["logs"]:[]],"This ECS runtime does not expose exec or file transfer; logs require an awslogs task-definition driver"),config:no({clusterArn:s.clusterArn,taskDefinition:s.taskDefinition,launchType:s.launchType,pendingCount:s.pendingCount,deployments:s.deployments,logGroups:D,executionRoleArn:T?.executionRoleArn,taskRoleArn:T?.taskRoleArn,cpu:T?.cpu,memory:T?.memory}),discoveredAt:o.toISOString(),sourceId:n}})}function hh(e,t,r="lambda:aws"){let n=t.now??new Date;return e.map((i)=>{let o=i.FunctionName??Qs(i.FunctionArn),s=i.State==="Active"?"running":so(i.State);return{id:Mi("lambda",r,i.FunctionArn??o),provider:"lambda",kind:"function",name:o,status:s,rawStatus:i.State,health:s==="running"?"healthy":s==="failed"?"unhealthy":"unknown",desiredReplicas:void 0,runningReplicas:void 0,image:void 0,runtime:i.Runtime,version:i.Version,architecture:i.Architectures?.join(", "),ageSeconds:os(i.LastModified,n),restartCount:0,tags:{},links:{project:t.project,environment:t.environment,service:o,providerId:i.FunctionArn},resources:{memoryLimitBytes:i.MemorySize==null?void 0:i.MemorySize*1024*1024},replicas:[],networks:[],mounts:[],capabilities:is(["logs","inspect"],"Lambda has no persistent process to start, stop, restart, exec, or browse files; deploy a release to replace code"),config:no({handler:i.Handler,timeout:i.Timeout,codeSize:i.CodeSize,stateReason:i.StateReason,environmentKeys:Object.keys(i.Environment?.Variables??{})}),discoveredAt:n.toISOString(),sourceId:r}})}function CC(e){let t=e.trim();if(!t)return[];let r=JSON.parse(t);if(!Array.isArray(r))throw Error("Docker inspect output must be an array");return r.filter((n)=>n&&typeof n.Id==="string")}function EC(e){let t=Object.entries(e.NetworkSettings?.Ports??{}).flatMap(([r,n])=>{let[i,o]=r.split("/");return(n??[]).map((s)=>({container:Number(i)||void 0,host:Number(s.HostPort)||void 0,protocol:o,address:s.HostIp}))});return Object.entries(e.NetworkSettings?.Networks??{}).map(([r,n])=>({id:n.NetworkID||r,name:r,mode:e.HostConfig?.NetworkMode,addresses:[n.IPAddress,n.GlobalIPv6Address].filter(Boolean),ports:t}))}function TC(e){return(e.Mounts??[]).filter((t)=>!!t.Destination).map((t)=>({source:t.Source,target:t.Destination,type:t.Type,readOnly:t.RW===!1}))}function AC(e,t,r=t.server??"local"){let n=t.now??new Date;return e.map((i)=>{let o=i.State?.OOMKilled?"oomkilled":i.State?.Restarting?"starting":i.State?.Status,s=so(o),c=(i.Name??i.Id.slice(0,12)).replace(/^\//,""),u=i.Config?.Labels??{},a=TC(i),f=EC(i),T={id:i.Id,name:c,image:i.Config?.Image,imageDigest:i.Image,runtime:"docker",status:s,rawStatus:o,exitCode:i.State?.ExitCode,reason:i.State?.Error,resources:{memoryLimitBytes:i.HostConfig?.Memory||void 0},networks:f,mounts:a};return{id:Mi("docker",r,i.Id),provider:"docker",kind:"container",name:c,status:s,rawStatus:o,health:s==="running"?"healthy":s==="failed"?"unhealthy":"unknown",desiredReplicas:1,runningReplicas:s==="running"?1:0,image:i.Config?.Image,runtime:"docker",ageSeconds:os(i.State?.StartedAt,n),restartCount:i.RestartCount??0,tags:u,links:{project:t.project,environment:t.environment,server:t.server??r.replace(/^docker:/,""),service:u["com.docker.compose.service"]??u["ts-cloud.service"]??c,release:u["ts-cloud.release"],providerId:i.Id},resources:T.resources,replicas:[{id:Mi("docker",r,`${i.Id}:0`),name:c,status:s,rawStatus:o,startedAt:i.State?.StartedAt,stoppedAt:i.State?.FinishedAt,restartCount:i.RestartCount,containers:[T],resources:T.resources}],networks:f,mounts:a,capabilities:is(["start","stop","restart","logs","exec","inspect","files"],"Use the owning Compose service for redeploy and scale"),config:no({image:i.Config?.Image,labels:u,environmentKeys:(i.Config?.Env??[]).map((R)=>R.split("=",1)[0]),networkMode:i.HostConfig?.NetworkMode}),discoveredAt:n.toISOString(),sourceId:r}})}class El{inspect;id;provider="docker";constructor(e,t="docker:local"){this.inspect=e;this.id=t}async discover(e){return AC(CC(await this.inspect(e)),e,this.id)}}function kC(e){let t=[];for(let r of e.split(`
120
- `)){if(!r.startsWith("TSCLOUD_SYSTEMD\t"))continue;let[,n,i,o,s,c,u,a,f,T,R,D,W,Y]=r.split("\t");if(!n||!/^[A-Za-z0-9_.@:-]+\.service$/.test(n))continue;t.push({unit:n,load:i,active:o,sub:s,description:c,enabled:u,pid:Number(a)||void 0,memoryBytes:dh(f),restartCount:Number(T)||0,activeSince:R||void 0,fragmentPath:D||void 0,workingDirectory:W?.startsWith("/")?W:void 0,user:Y||void 0})}return t}function RC(e,t,r=t.server??"local"){let n=t.now??new Date;return e.map((i)=>{let o=so(i.active==="active"?i.sub||i.active:i.active),s=i.unit.replace(/\.service$/,""),c=/^(.*?) (?:release [^ ]+|queue worker|daemon |scheduler)(?: |$)/.exec(i.description??"")?.[1]??(t.project&&s.startsWith(`${t.project}-`)?s.slice(t.project.length+1).split("@",1)[0]:void 0),u=s.includes("@")?s.slice(s.indexOf("@")+1):void 0,a=i.workingDirectory?[{target:i.workingDirectory,type:"working-directory"}]:[],f=["start","stop","restart","logs","exec","inspect",...a.length?["files"]:[]];return{id:Mi("systemd",r,i.unit),provider:"systemd",kind:"service",name:s,displayName:i.description||s,status:o,rawStatus:[i.load,i.active,i.sub].filter(Boolean).join("/"),health:o==="running"?"healthy":o==="failed"?"unhealthy":"unknown",desiredReplicas:1,runningReplicas:o==="running"?1:0,ageSeconds:os(i.activeSince,n),restartCount:i.restartCount,tags:{enabled:i.enabled??"unknown"},links:{project:t.project,environment:t.environment,server:t.server??r.replace(/^systemd:/,""),service:c,release:u,providerId:i.unit},resources:{memoryBytes:i.memoryBytes},replicas:[{id:Mi("systemd",r,`${i.unit}:main`),name:"main",status:o,pid:i.pid,startedAt:i.activeSince,restartCount:i.restartCount,resources:{memoryBytes:i.memoryBytes}}],networks:[],mounts:a,capabilities:is(f,a.length?"This systemd runtime does not support redeploy or replica scaling through the scoped explorer":"File transfer requires a provider-reported service working directory; redeploy and scaling are unavailable"),config:no({fragmentPath:i.fragmentPath,workingDirectory:i.workingDirectory,user:i.user,environment:i.environment,enabled:i.enabled}),discoveredAt:n.toISOString(),sourceId:r}})}class Tl{read;id;provider="systemd";constructor(e,t="systemd:local"){this.read=e;this.id=t}async discover(e){return RC(kC(await this.read(e)),e,this.id)}}function PC(e,t){if(!e.success)throw Error(e.error||e.perInstance?.[0]?.error||`${t} discovery failed`);return e.perInstance?.[0]?.output??""}function xC(){return["set -uo pipefail",'command -v systemctl >/dev/null 2>&1 || { echo "systemctl is unavailable" >&2; exit 127; }',"systemctl list-units --type=service --all --plain --no-legend 2>/dev/null | awk '{print $1}' | while IFS= read -r unit; do",' [ -n "$unit" ] || continue',' clean() { printf "%s" "$1" | tr "\\t\\r\\n" " "; }',' load=$(systemctl show "$unit" -p LoadState --value 2>/dev/null || true)',' active=$(systemctl show "$unit" -p ActiveState --value 2>/dev/null || true)',' sub=$(systemctl show "$unit" -p SubState --value 2>/dev/null || true)',' description=$(systemctl show "$unit" -p Description --value 2>/dev/null || true)',' enabled=$(systemctl is-enabled "$unit" 2>/dev/null || true)',' pid=$(systemctl show "$unit" -p MainPID --value 2>/dev/null || true)',' memory=$(systemctl show "$unit" -p MemoryCurrent --value 2>/dev/null || true)',' restarts=$(systemctl show "$unit" -p NRestarts --value 2>/dev/null || true)',' since=$(systemctl show "$unit" -p ActiveEnterTimestamp --value 2>/dev/null || true)',' fragment=$(systemctl show "$unit" -p FragmentPath --value 2>/dev/null || true)',' working=$(systemctl show "$unit" -p WorkingDirectory --value 2>/dev/null || true)',' user=$(systemctl show "$unit" -p User --value 2>/dev/null || true)',' printf "TSCLOUD_SYSTEMD\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n" "$(clean "$unit")" "$(clean "$load")" "$(clean "$active")" "$(clean "$sub")" "$(clean "$description")" "$(clean "$enabled")" "$(clean "$pid")" "$(clean "$memory")" "$(clean "$restarts")" "$(clean "$since")" "$(clean "$fragment")" "$(clean "$working")" "$(clean "$user")"',"done"]}function DC(){return["set -uo pipefail",'if ! command -v docker >/dev/null 2>&1; then echo "[]"; exit 0; fi',"ids=$(docker ps -aq)",'if [ -z "$ids" ]; then echo "[]"; else docker inspect $ids; fi']}function yh(e,t,r,n,i){let o=`${e}:${r.id}`,s=async()=>PC(await t.runRemoteDeploy({targets:[r],commands:e==="systemd"?xC():DC(),timeoutSeconds:30,comment:`ts-cloud runtime discovery:${e}`,tags:{Project:n.project.slug,Environment:i,Role:"app"}}),o);return e==="systemd"?new Tl(s,o):new El(s,o)}async function od(e,t=100){let r=[],n;for(let i=0;i<t;i++){let o=await e(n);if(r.push(...o.items),!o.nextToken)return r;n=o.nextToken}throw Error(`Provider pagination exceeded ${t} pages`)}class bh{client;prefix;id="ecs:aws";provider="ecs";constructor(e,t){this.client=e;this.prefix=t}async discover(e){let t=await od(async(o)=>{let s=await this.client.listClusters({nextToken:o,maxResults:100});return{items:s.clusterArns??[],nextToken:s.nextToken}}),r=[],n=[],i=[];for(let o of t){let s=(await od(async(c)=>{let u=await this.client.listServices(o,{nextToken:c,maxResults:100});return{items:u.serviceArns??[],nextToken:u.nextToken}})).filter((c)=>c.split("/").at(-1)?.startsWith(this.prefix));for(let c=0;c<s.length;c+=10){let u=await this.client.describeServices({cluster:o,services:s.slice(c,c+10)});r.push(...u.services??[])}for(let c of r.filter((u)=>u.clusterArn===o||!u.clusterArn)){let u=await od(async(a)=>{let f=await this.client.listTasks(o,c.serviceName,{nextToken:a,maxResults:100});return{items:f.taskArns??[],nextToken:f.nextToken}});for(let a=0;a<u.length;a+=100){let f=await this.client.describeTasks(o,u.slice(a,a+100));n.push(...f.tasks??[])}}}if(this.client.describeTaskDefinition)for(let o of[...new Set(r.map((s)=>s.taskDefinition).filter((s)=>!!s))]){let s=await this.client.describeTaskDefinition(o);if(s.taskDefinition)i.push(s.taskDefinition)}return fh(r,n,e,this.id,i)}}class Sh{client;prefix;id="lambda:aws";provider="lambda";constructor(e,t){this.client=e;this.prefix=t}async discover(e){let t=(await od(async(r)=>{let n=await this.client.listFunctions({Marker:r,MaxItems:50});return{items:n.Functions??[],nextToken:n.NextMarker}})).filter((r)=>r.FunctionName?.startsWith(this.prefix));return hh(t,e,this.id)}}async function OC(e,t,r={}){let n=[],i=H(e),o=F(e),s=e.aws?.profile,c=e.aws?.region??e.project.region??"us-east-1",u=`${e.project.slug}-${t}`;if(i!=="serverless"){let a=r.driver??O({config:e}),f=await a.findComputeTargets({slug:e.project.slug,environment:t,role:"app"});for(let T of f)n.push(yh("systemd",a,T,e,t)),n.push(yh("docker",a,T,e,t))}if(o==="aws")n.push(new bh(r.ecs??new Nt(c,s),u)),n.push(new Sh(r.lambda??new I(c,s),u));return n}async function Ii(e,t,r={}){let n={project:e.project.slug,environment:t};try{return await uh(await OC(e,t,r),n)}catch(i){return{generatedAt:new Date().toISOString(),workloads:[],sources:[{id:"runtime:bootstrap",provider:F(e)==="aws"?"ecs":"systemd",status:"error",discoveredAt:new Date().toISOString(),staleAfterSeconds:60,itemCount:0,message:String(i?.message??i).slice(0,500)}],degraded:!0}}}var vh=65536,xa=49152,ad=/^[A-Za-z0-9_.@:-]+\.service$/,cd=/^[a-fA-F0-9]{12,128}$/,_C=["/boot","/dev","/etc","/proc","/root","/run","/sys","/var/run"];function Ys(e){let t=Buffer.from(e);return t.byteLength<=vh?e:`${t.subarray(0,vh-24).toString("utf8")}
119
+ `;return r}}function VI(e,t,r={}){return _f(e,t,r,new WeakMap)}function _f(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:o=!1,customMerger:s}=r;if(t===null||t===void 0)return o?e:t;if(s){let c=s(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return Nf(e,t,i,n);if(!Fn(t)||!Fn(e))return t;return HI(e,t,r,n)}function Nf(e,t,r,n){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return qI(e,t);case"smart":return GI(e,t,n);default:return t}return t}function qI(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>ol(i,n)))r.push(n);return r}function GI(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(Fn(t[0])&&Fn(e[0]))return JI(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}function JI(e,t,r){let n=[...t];for(let i of e){if(!Fn(i)){n.push(i);continue}let o=["id","name","key","path","type"],s=!1;for(let c of o)if(c in i){if(n.find((a)=>Fn(a)&&(c in a)&&a[c]===i[c])){s=!0;break}}if(!s)n.push(i)}return n}function HI(e,t,r,n){let i=t;if(Fn(i)&&n.has(i))return n.get(i);let o={...e};if(Fn(i))n.set(i,o);for(let s in i){if(!Object.prototype.hasOwnProperty.call(i,s))continue;let c=i[s],u=o[s];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){o[s]=c;continue}if(Fn(c)&&Fn(u))o[s]=_f(u,c,r,n);else if(Array.isArray(c)||Array.isArray(u))o[s]=Nf(u,c,r.arrayMergeMode||"smart",n);else o[s]=c}return o}function Mf(e,t,r="replace"){return VI(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function ol(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!ol(e[r],t[r]))return!1;return!0}if(Fn(e)&&Fn(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!ol(e[i],t[i]))return!1}return!0}return!1}function Fn(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class $f{extensions=rf;async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:o,trackPerformance:s=!0,verbose:c=!1}=r;if(i){let a=Fc.getWithFileCheck("file",e);if(a){if(c)console.log(`Configuration loaded from cache: ${e}`);return a}}let u=async()=>{if(!_c(e))return null;try{let a=`?t=${Date.now()}`,f=await import(e+a),T=f.default||f,R="default"in f,D=Object.keys(f).length>0;if(!R&&!D)throw new Yc(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof T!=="object"||T===null||Array.isArray(T))throw new Yc(e,Error("Configuration must export a valid object"),"unknown");let ee={config:Mf(t,T,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)Fc.setWithFileCheck("file",ee,e,o);return ee}catch(a){throw a instanceof Error?Xo.configLoad(e,a):Xo.configLoad(e,Error(String(a)))}};if(s)return sl.track("loadFromPath",u,{path:e});return u()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){return Uv({name:e,directory:t,alias:r})}generateNamePatterns(e,t){return nf({name:e,alias:t})}checkFileAccess(e){return zI(async()=>_c(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!_c(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let o of i)for(let s of this.extensions){let c=Zm(e,`${o}${s}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:i}=await import("fs"),o=i(e);for(let s of o)if(this.looksLikeConfigFile(s)){let c=Zm(e,s);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(e))}async validateConfigFile(e){let t=[];try{if(!_c(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),o=i(e,"utf8");JSON.parse(o)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}var KI=/^https?:\/\//;class Lf{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:o=!0,customRules:s=[],trackPerformance:c=!0,verbose:u=!1}=r,a=async()=>{let f=[],T=[],R={stopOnFirstError:n,validateRequired:i,validateTypes:o,customRules:s,trackPerformance:c,verbose:u};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,R);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...s],R);else return this.validateWithJSONSchema(e,t,R)}catch(D){return f.push({path:"",message:`Validation failed: ${D}`,rule:"system"}),{isValid:!1,errors:f,warnings:T}}};if(c)return await sl.track("validateConfiguration",a);return a()}async validateWithSchemaFile(e,t,r){try{if(!WI(t))throw new Xc(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),i=n.default||n;if(Array.isArray(i))return this.validateWithRules(e,i,r);else return this.validateWithJSONSchema(e,i,r)}catch(n){throw new Xc(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,o){if(o.validateTypes&&t.type){let s=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(s)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${s}`,expected:c.join(" or "),actual:s,rule:"type"}),o.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),o.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let s=0;s<e.length;s++){let c=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(e[s],t.items,c,n,i,o),o.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let s=e;if(o.validateRequired&&t.required){for(let c of t.required)if(!(c in s)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),o.stopOnFirstError)return}}if(t.properties){for(let[c,u]of Object.entries(t.properties))if(c in s){let a=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(s[c],u,a,n,i,o),o.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let u of Object.keys(s))if(!c.has(u))i.push({path:r?`${r}.${u}`:u,message:`Additional property '${u}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let o of t)try{let s=this.getValueByPath(e,o.path),c=this.validateWithRule(s,o,o.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:o.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,o,s]=n;t.push({path:i,required:!o,type:this.mapTypeScriptType(s)})}return t}mapTypeScriptType(e){switch(e.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:KI},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var bi=new rd("bunfig",{showTags:!0});function QI(e){if(!e)return"";let t=Array.isArray(e)?e.filter(Boolean):[e];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class Bf{fileLoader=new $f;envProcessor=new fl;validator=new Lf;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:o,...s}=e;try{if(r?.enabled){let u=this.checkCache(s.name||"",s);if(u)return u}let c;try{c=await this.loadConfigurationStrategies(s,!0,r)}catch(u){if(s.configFile)throw u;let a=s.__strictErrorHandling;if(u instanceof Error&&u.name==="ConfigNotFoundError"){if(a)throw u;c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(u instanceof Error&&u.name==="ConfigLoadError"){let f=u.message.includes("EACCES")||u.message.includes("EPERM")||u.message.includes("permission denied"),T=!f&&(u.message.includes("syntax")||u.message.includes("Expected")||u.message.includes("Unexpected")||u.message.includes("BuildMessage")||u.message.includes("errors building")),R=u.message.includes("Configuration must export a valid object")||u.message.includes("Configuration file is empty and exports nothing");if(a&&(R||f))throw u;if(T&&(!a||!R))c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!a)c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${u.message}`]};else throw u}else c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${u instanceof Error?u.message:String(u)}`]}}if(i||o)await this.validateConfiguration(c.config,i,o,s.name);if(r?.enabled&&c)this.cacheResult(s.name||"",c,r,s);if(n?.enabled){let u={operation:"loadConfig",duration:Date.now()-t,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(u);if(n.slowThreshold&&u.duration>n.slowThreshold)bi.warn(`Slow configuration loading detected: ${u.duration}ms for ${s.name}`);c.metrics=u}return c}catch(c){if(c instanceof Error&&c.name==="ConfigNotFoundError")throw c;let u=Date.now()-t;throw bi.error(`Configuration loading failed after ${u}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,configFile:o,cwd:s,configDir:c,defaultConfig:u,checkEnv:a=!0,arrayStrategy:f="replace",verbose:T=!1}=e,R=s||Zc.cwd(),D=[];if(o){let he=_i(R,o);D.push(he);let te=a?Ia(n,u,T):u,De=await this.fileLoader.tryLoadFromPaths([he],te,{arrayStrategy:f,verbose:T,cacheTtl:r?.ttl,useCache:!r?.ttl||r.ttl>100});if(!De)throw Xo.configNotFound(n||o,D,i);if(T)bi.success(`Configuration loaded from explicit path: ${he}`);return this.finalizeResult(De,D,a,n,T)}let W=await this.loadLocalConfiguration(n,i,R,c,u,f,T,a,r);if(W)return D.push(...this.getLocalSearchPaths(n,i,R,c)),this.finalizeResult(W,D,a,n,T);let Y=await this.loadHomeConfiguration(n,i,u,f,T,a);if(Y)return D.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(Y,D,a,n,T);let ee=await this.loadPackageJsonConfiguration(n,i,R,u,f,T,a);if(ee)return D.push(_i(R,"package.json")),this.finalizeResult(ee,D,a,n,T);if(D.push(...this.getAllSearchPaths(n,i,R,c)),t)throw Xo.configNotFound(n,D,i);return{...await this.applyEnvironmentVariables(n,u,a,T),warnings:[`No configuration file found for "${n}"${QI(i)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,o,s,c,u){let a=c?Ia(e,i,s):i,f=this.getLocalDirectories(r,n);for(let T of f){if(s)bi.info(`Searching for configuration in: ${T}`);let R=this.fileLoader.generateConfigPaths(e,T,t),D=await this.fileLoader.tryLoadFromPaths(R,a,{arrayStrategy:o,verbose:s,cacheTtl:u?.ttl,useCache:!u?.ttl||u.ttl>100});if(D){if(s)bi.success(`Configuration loaded from: ${D.source.path}`);return D}}return null}async loadHomeConfiguration(e,t,r,n,i,o){if(!e)return null;let s=o?Ia(e,r,i):r,c=[_i(_s(),".config",e),_i(_s(),".config"),_s()];for(let u of c){if(i)bi.info(`Checking home directory: ${u}`);let a=this.fileLoader.generateConfigPaths(e,u,t),f=await this.fileLoader.tryLoadFromPaths(a,s,{arrayStrategy:n,verbose:i});if(f){if(i)bi.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,o,s){let c=s?Ia(e,n,o):n;try{let u=_i(r,"package.json");if(!Vv(u))return null;let a={};try{a=JSON.parse(qv(u,"utf8"))}catch(R){if(o)bi.warn("Failed to parse package.json:",[R instanceof Error?R:Error(String(R))]);return null}let f=a[e],T=e;if(!f&&t){let R=Array.isArray(t)?t:[t];for(let D of R){if(!D)continue;if(a[D]){f=a[D],T=D;break}}}if(f&&typeof f==="object"&&!Array.isArray(f)){if(o)bi.success(`Configuration loaded from package.json: ${T}`);return{config:Mf(c,f,i),source:{type:"package.json",path:u,priority:30,timestamp:new Date}}}}catch(u){if(o)bi.warn("Failed to load package.json:",[u instanceof Error?u:Error(String(u))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Ia(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let o=r(e);if(o)i.push(...o)}if(t){let o=await this.validator.validateConfiguration(e,t);if(!o.isValid)i.push(...o.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(i.length>0)throw Xo.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return Fc.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);Fc.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let n=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${n}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configFile)r.push(`configFile:${t.configFile}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return zv({cwd:e,configDir:t})}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(_i(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),o=[];for(let s of i)o.push(...this.fileLoader.generateConfigPaths(e,s,t));return o}getHomeSearchPaths(e,t){if(!e)return[];let r=[_i(_s(),".config",e),_i(_s(),".config"),_s()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}var Hu=new Bf;async function Ff(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let n;if(r)n=await Hu.loadConfig(e);else n=await Hu.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){if(e.configFile)throw n;let i=n instanceof Error?n.name:"UnknownError",o=n instanceof Error?n.message:String(n);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||o.includes("config"))&&e.verbose)bi.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let c=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await Hu.applyEnvironmentVariables(c.name||"",t,!0,c.verbose||!1))?.config??t;return t}}function Ia(e,t,r=!1){let n=new fl,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function o(s,c=[]){let u={...s};for(let[a,f]of Object.entries(s)){let T=[...c,a],R=[`${i}_${T.join("_").toUpperCase()}`,`${i}_${T.map((Y)=>Y.toUpperCase()).join("")}`,`${i}_${T.map((Y)=>Y.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],D,W;for(let Y of R)if(D=Zc.env[Y],D!==void 0){W=Y;break}if(D!==void 0&&W)if(typeof f==="boolean")u[a]=["true","1","yes"].includes(D.toLowerCase());else if(typeof f==="number"){let Y=Number(D);if(!Number.isNaN(Y))u[a]=Y}else if(Array.isArray(f))try{u[a]=JSON.parse(D)}catch{u[a]=D.split(",").map((Y)=>Y.trim())}else u[a]=D;else if(f&&typeof f==="object"&&!Array.isArray(f))u[a]=o(f,T)}return u}return o(t)}var aO=_i(Zc.cwd(),"config"),cO=_i(Zc.cwd(),"src/generated");var Dn={project:{name:"my-project",slug:"my-project",region:"us-east-1"},environments:{production:{type:"production"}}},rs=null;function ZI(e){return e.project?.slug===Dn.project?.slug&&Object.keys(e.environments??{}).length===1&&!!e.environments?.production}async function eC(){let e=[jf(process.cwd(),"config","cloud.ts"),jf(process.cwd(),"config","cloud.js")];for(let t of e){if(!YI(t))continue;let r=await import(`${XI(t).href}?t=${Date.now()}`),n=r.tsCloud??r.default?.tsCloud??r.default??r.cloud??r.config;if(n)return n}return null}async function tC(){if(!rs){if(rs=await Ff({name:"cloud",defaultConfig:Dn}),ZI(rs))rs=await eC()??rs;ia(rs.stateDir)}return rs}var Hi=tC;var rC=async(e)=>{let t=Bun.spawn(e,{stdout:"pipe",stderr:"pipe"}),[r,n,i]=await Promise.all([t.exited,new Response(t.stdout).text(),new Response(t.stderr).text()]);return{code:r,stdout:n,stderr:i}};class Br{async scan(e,t){return Yi(e,t)}async exec(e,t){if(e.trustState!=="pinned")throw Error("SSH host key must be pinned before remote execution.");return rC(["ssh","-p",String(e.sshPort),"-o","BatchMode=yes","-o","StrictHostKeyChecking=yes","-o","ConnectTimeout=10",`${e.sshUser}@${e.endpoint}`,t])}}var nC=ur,iC=`set -eu; printf '{'; printf '"os":"%s",' "$(. /etc/os-release 2>/dev/null; printf %s "\${PRETTY_NAME:-Linux}")"; printf '"arch":"%s",' "$(uname -m)"; printf '"cpuCores":%s,' "$(getconf _NPROCESSORS_ONLN)"; printf '"memoryBytes":%s,' "$(awk '/MemTotal/{print $2*1024}' /proc/meminfo)"; printf '"diskBytes":%s,' "$(df -B1 / | awk 'NR==2{print $2}')"; printf '"diskFreeBytes":%s,' "$(df -B1 / | awk 'NR==2{print $4}')"; printf '"dnsOk":'; getent hosts example.com >/dev/null && printf true || printf false; printf ',"timeSkewSeconds":0,"tools":{"curl":"'; command -v curl >/dev/null && printf installed; printf '","tar":"'; command -v tar >/dev/null && printf installed; printf '"},"privilege":"'; sudo -n true >/dev/null 2>&1 && printf sudo || printf user; printf '"}'`;class it{provider;transport;discoverer;constructor(e,t=new Br,r){this.provider=e;this.transport=t;this.discoverer=r}discover(e){return this.discoverer?.(e)??Promise.resolve([])}async test(e){try{let t=await this.transport.scan(e.endpoint,e.sshPort);return{reachable:!0,hostKeyAlgorithm:t.algorithm,hostKeyFingerprint:nC(t.key),latencyMs:0}}catch{return{reachable:!1,hostKeyAlgorithm:"unknown",hostKeyFingerprint:"",latencyMs:0}}}async validate(e){let t=await this.transport.exec(e,iC);if(t.code!==0)throw Error(`Fleet validation failed: ${t.stderr.trim()||t.code}`);try{return JSON.parse(t.stdout)}catch{throw Error("Fleet validation returned malformed facts.")}}async bootstrap(e,t){let r=await this.transport.exec(e,`sudo -n ts-cloud-agent bootstrap --version 1 --steps ${t.length}`);if(r.code!==0)throw Error(`Fleet bootstrap failed: ${r.stderr.trim()||r.code}`);return{version:"1"}}capabilities(){return{document:{supported:!0,reason:"fleet-capabilities/v1; sha256:driver-contract"},validate:{supported:!0},bootstrap:{supported:!0},heartbeat:{supported:!0},drain:{supported:!0},archive:{supported:!0},terminate:{supported:!1,reason:"Inventory removal never terminates provider infrastructure."}}}}function Uf(e,t){return{"fleet.bootstrap":async(r)=>{let n=r.operation.input&&typeof r.operation.input==="object"&&!Array.isArray(r.operation.input)?r.operation.input:{},i=e.get(String(n.serverId??""));if(!i)throw Error("Queued fleet server was not found.");let o=t.find((u)=>u.provider===i.provider);if(!o)throw Error(`No ${i.provider} fleet driver is configured.`);let s=Array.isArray(n.steps)?n.steps.map(String):[];if(r.checkpoint("preflight","Rechecking pinned trust and healthy validation."),i.trustState!=="pinned"||!i.validation?.valid)throw Error("Fleet bootstrap requires pinned trust and a healthy validation report.");r.checkpoint("bootstrap","Applying the reviewed idempotent bootstrap plan.");let c=await o.bootstrap(i,s);return e.update(i.id,{bootstrapVersion:c.version,status:"ready"}),r.checkpoint("verify","Bootstrap completed; heartbeat can now establish freshness."),{serverId:i.id,bootstrapVersion:c.version,steps:s.length}}}}var Ni=(e)=>e==null?void 0:String(e),ns=(e,t)=>{try{return JSON.parse(String(e))}catch{return t}},hl=(e)=>({id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),resourceId:String(e.resource_id),name:String(e.name),provider:String(e.provider),providerId:Ni(e.provider_id),region:Ni(e.region),zone:Ni(e.zone),endpoint:String(e.endpoint),sshUser:String(e.ssh_user),sshPort:Number(e.ssh_port),credentialRef:String(e.credential_ref),hostKeyAlgorithm:Ni(e.host_key_algorithm),hostKeyFingerprint:Ni(e.host_key_fingerprint),pendingHostKey:Ni(e.pending_host_key),roles:ns(e.roles,[]),labels:ns(e.labels,{}),taints:ns(e.taints,[]),capacity:ns(e.capacity,{}),usage:ns(e.usage,{}),capabilities:ns(e.capabilities,{}),status:String(e.status),trustState:String(e.trust_state),validation:ns(e.validation,void 0),bootstrapVersion:Ni(e.bootstrap_version),heartbeatAt:Ni(e.heartbeat_at),lastSeenAt:Ni(e.last_seen_at),archivedAt:Ni(e.archived_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)});class ke{control;now;id;constructor(e,t=()=>new Date,r=()=>crypto.randomUUID()){this.control=e;this.now=t;this.id=r}get(e){let t=this.control.database.query("SELECT * FROM fleet_servers WHERE id=?").get(e);return t?hl(t):void 0}list(e,t=!1){return this.control.database.query("SELECT * FROM fleet_servers WHERE project_id=? ORDER BY name").all(e).map(hl).filter((r)=>t||r.status!=="archived")}findProvider(e,t,r){let n=this.control.database.query("SELECT * FROM fleet_servers WHERE organization_id=? AND provider=? AND provider_id=? AND archived_at IS NULL").get(e,t,r);return n?hl(n):void 0}create(e){let t=this.id(),r=this.now().toISOString();return this.control.database.run("INSERT INTO fleet_servers (id,organization_id,project_id,resource_id,name,provider,provider_id,region,zone,endpoint,ssh_user,ssh_port,credential_ref,host_key_algorithm,host_key_fingerprint,pending_host_key,roles,labels,taints,capacity,usage,capabilities,status,trust_state,validation,bootstrap_version,heartbeat_at,last_seen_at,archived_at,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.organizationId,e.projectId,e.resourceId,e.name,e.provider,e.providerId??null,e.region??null,e.zone??null,e.endpoint,e.sshUser,e.sshPort,e.credentialRef,e.hostKeyAlgorithm??null,e.hostKeyFingerprint??null,e.pendingHostKey??null,JSON.stringify(e.roles),JSON.stringify(e.labels),JSON.stringify(e.taints),JSON.stringify(e.capacity),JSON.stringify(e.usage),JSON.stringify(e.capabilities),e.status,e.trustState,JSON.stringify(e.validation??{}),e.bootstrapVersion??null,e.heartbeatAt??null,e.lastSeenAt??null,e.archivedAt??null,r,r]),this.get(t)}update(e,t){let r=this.get(e);if(!r)throw Error("Server was not found.");let n={...r,...t},i=this.now().toISOString();return this.control.database.run("UPDATE fleet_servers SET name=?,provider_id=?,region=?,zone=?,endpoint=?,ssh_user=?,ssh_port=?,credential_ref=?,host_key_algorithm=?,host_key_fingerprint=?,pending_host_key=?,roles=?,labels=?,taints=?,capacity=?,usage=?,capabilities=?,status=?,trust_state=?,validation=?,bootstrap_version=?,heartbeat_at=?,last_seen_at=?,archived_at=?,version=version+1,updated_at=? WHERE id=?",[n.name,n.providerId??null,n.region??null,n.zone??null,n.endpoint,n.sshUser,n.sshPort,n.credentialRef,n.hostKeyAlgorithm??null,n.hostKeyFingerprint??null,n.pendingHostKey??null,JSON.stringify(n.roles),JSON.stringify(n.labels),JSON.stringify(n.taints),JSON.stringify(n.capacity),JSON.stringify(n.usage),JSON.stringify(n.capabilities),n.status,n.trustState,JSON.stringify(n.validation??{}),n.bootstrapVersion??null,n.heartbeatAt??null,n.lastSeenAt??null,n.archivedAt??null,i,e]),this.get(e)}}var oC=/^(?:[A-Za-z0-9](?:[A-Za-z0-9.-]{0,251}[A-Za-z0-9])?|\[[0-9a-fA-F:]+\])$/;class Nn{store;drivers;now;queue;constructor(e,t,r,n=()=>new Date){this.store=e;this.drivers=t;this.now=n;this.queue=r??new S(e.control)}driver(e){let t=this.drivers.find((r)=>r.provider===e);if(!t)throw Error(`No ${e} fleet driver is configured.`);return t}enroll(e){if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(e.name))throw Error("Server name is invalid.");if(!oC.test(e.endpoint)||e.sshUser==="root"||!e.credentialRef.startsWith("secret://"))throw Error("Enrollment requires a valid endpoint, non-root SSH user, and secret credential reference.");let t=e.providerId?this.store.findProvider(e.organizationId,e.provider,e.providerId):void 0;if(t)return this.store.update(t.id,{endpoint:e.endpoint,region:e.region,zone:e.zone});let r=this.store.control.createResource({projectId:e.projectId,kind:"server",slug:e.name,name:e.name,provider:e.provider,providerId:e.providerId}),n=this.driver(e.provider);return this.store.create({...e,resourceId:r.id,sshPort:e.sshPort??22,labels:e.labels??{},taints:[],capacity:{},usage:{},capabilities:n.capabilities(),status:"pending",trustState:"unverified"})}async test(e){let t=this.store.get(e);if(!t)throw Error("Server was not found.");let r=await this.driver(t.provider).test(t);if(!r.reachable)return this.store.update(e,{status:"unreachable"});if(t.hostKeyFingerprint&&t.hostKeyFingerprint!==r.hostKeyFingerprint)return this.store.update(e,{status:"degraded",trustState:"rotation_pending",pendingHostKey:r.hostKeyFingerprint});return this.store.update(e,{hostKeyAlgorithm:r.hostKeyAlgorithm,hostKeyFingerprint:r.hostKeyFingerprint,pendingHostKey:void 0,trustState:"pinned",status:"validating",lastSeenAt:this.now().toISOString()})}reviewHostKey(e,t){let r=this.store.get(e);if(!r||r.pendingHostKey!==t)throw Error("Pending host key does not match.");return this.store.update(e,{hostKeyFingerprint:t,pendingHostKey:void 0,trustState:"pinned",status:"validating"})}async validate(e){let t=this.store.get(e);if(!t||t.trustState!=="pinned")throw Error("Pin the SSH host key before validation.");let r=await this.driver(t.provider).validate(t),n=[];if(!["x64","arm64","x86_64","aarch64"].includes(r.arch??""))n.push({code:"arch.unsupported",severity:"error",message:"Unsupported architecture.",remediation:"Use x86_64 or arm64 Linux."});for(let s of["curl","tar"])if(!r.tools?.[s])n.push({code:`tool.${s}`,severity:"error",message:`${s} is missing.`,remediation:`Install ${s} before bootstrap.`});if(Math.abs(r.timeSkewSeconds??0)>60)n.push({code:"time.skew",severity:"error",message:"Clock skew exceeds 60 seconds.",remediation:"Enable NTP synchronization."});if(!r.dnsOk)n.push({code:"dns.failed",severity:"error",message:"DNS validation failed.",remediation:"Repair resolver configuration."});let i={valid:!n.some((s)=>s.severity==="error"),facts:r,findings:n,validatedAt:this.now().toISOString(),validatorVersion:"1"},o={cpu:r.cpuCores??0,memoryBytes:r.memoryBytes??0,diskBytes:r.diskBytes??0};return this.store.update(e,{validation:i,capacity:o,status:i.valid?"ready":"degraded"})}bootstrap(e,t=!1){let r=this.store.get(e);if(!r?.validation?.valid)throw Error("A healthy validation report is required.");let n=["install runtime dependencies","install ts-cloud agent","configure heartbeat","verify least-privilege access"];if(!t)return{preview:!0,steps:n};let i=this.queue.enqueue({projectId:r.projectId,resourceId:r.resourceId,kind:"fleet.bootstrap",input:{serverId:e,steps:n},lockKey:`server:${e}`,providerKey:r.provider}).operation;return{preview:!1,steps:n,operation:i}}heartbeat(e,t){let r=this.store.get(e);if(!r)throw Error("Server was not found.");let n=this.now().toISOString();return this.store.update(e,{usage:t.usage,capabilities:t.capabilities??r.capabilities,heartbeatAt:n,lastSeenAt:n,status:r.status==="draining"||r.status==="drained"?r.status:"ready"})}drain(e,t=!1){return this.store.update(e,{status:t?"drained":"draining"})}uncordon(e){return this.store.update(e,{status:"ready"})}archive(e,t){let r=this.store.get(e);if(!r||t!==r.name)throw Error("Exact server name confirmation is required.");return this.store.update(e,{status:"archived",archivedAt:this.now().toISOString()})}}import{createHash as yl,createPublicKey as qf,verify as sC}from"node:crypto";function Pa(e){if(e===null||typeof e!=="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(Pa).join(",")}]`;return`{${Object.keys(e).sort().map((t)=>`${JSON.stringify(t)}:${Pa(e[t])}`).join(",")}}`}var Gf=(e)=>yl("sha256").update(Pa(e)).digest("hex"),nd=(e)=>yl("sha256").update(Pa(e)).digest("hex"),Jf=(e)=>yl("sha256").update(qf(e).export({type:"spki",format:"der"})).digest("hex");function Hf(e,t,r){try{return sC(null,Buffer.from(Pa(e)),qf(r),Buffer.from(t,"base64"))}catch{return!1}}var zf=(e)=>e.replace(/^v/,"").split(/[.-]/).slice(0,3).map((t)=>Number(t)||0),Vf=(e,t)=>{let r=zf(e),n=zf(t);for(let i=0;i<3;i++){let o=(r[i]??0)-(n[i]??0);if(o)return o}return 0};function Wf(e,t){let r=[];if(t.schemaVersion<e.minimumSchema)r.push(`schema ${t.schemaVersion} is below ${e.minimumSchema}`);if(t.schemaVersion>e.maximumSchema)r.push(`schema ${t.schemaVersion} is above ${e.maximumSchema}`);if(e.minimumVersion&&Vf(t.currentVersion,e.minimumVersion)<0)r.push(`platform ${t.currentVersion} is below ${e.minimumVersion}`);if(Vf(e.version,t.currentVersion)<=0)r.push(`version ${e.version} is not newer than ${t.currentVersion}`);if(!e.artifacts.some((n)=>n.platform===t.platform&&n.architecture===t.architecture))r.push(`no artifact for ${t.platform}/${t.architecture}`);return{compatible:r.length===0,reasons:r}}var to=(e,t)=>{try{return JSON.parse(String(e))}catch{return t}},Rr=(e)=>e==null?void 0:String(e),aC=(e)=>({id:String(e.id),organizationId:String(e.organization_id),name:String(e.name),algorithm:"ed25519",publicKeyPem:String(e.public_key_pem),fingerprint:String(e.fingerprint),revokedAt:Rr(e.revoked_at),createdAt:String(e.created_at)}),Kf=(e)=>({id:String(e.id),organizationId:String(e.organization_id),version:String(e.version),channel:String(e.channel),publishedAt:String(e.published_at),keyId:String(e.key_id),digest:String(e.digest),document:to(e.document,{}),signature:String(e.signature),verificationStatus:String(e.verification_status),compatibility:to(e.compatibility,{compatible:!1,reasons:[]}),createdAt:String(e.created_at)}),Qf=(e)=>({id:String(e.id),projectId:String(e.project_id),name:String(e.name),schedule:String(e.schedule),timezone:String(e.timezone),durationMinutes:Number(e.duration_minutes),allowedOperations:to(e.allowed_operations,[]),requireApproval:Number(e.require_approval)===1,enabled:Number(e.enabled)===1,createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),Yf=(e)=>({id:String(e.id),projectId:String(e.project_id),manifestId:String(e.manifest_id),windowId:Rr(e.window_id),fromVersion:String(e.from_version),strategy:String(e.strategy),batchSize:Number(e.batch_size),healthGate:to(e.health_gate,{}),status:String(e.status),currentStage:Rr(e.current_stage),backupId:Rr(e.backup_id),approvedBy:Rr(e.approved_by),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),bl=(e)=>({id:String(e.id),campaignId:String(e.campaign_id),serverId:Rr(e.server_id),target:String(e.target),cohort:Number(e.cohort),previousVersion:String(e.previous_version),status:String(e.status),evidence:to(e.evidence,{}),error:Rr(e.error),startedAt:Rr(e.started_at),finishedAt:Rr(e.finished_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),Xf=(e)=>({id:String(e.id),projectId:String(e.project_id),kind:String(e.kind),criteria:to(e.criteria,{}),candidates:to(e.candidates,[]),candidateDigest:String(e.candidate_digest),estimatedBytes:Number(e.estimated_bytes),status:String(e.status),confirmation:Rr(e.confirmation),expiresAt:String(e.expires_at),result:to(e.result,{}),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),Zf=(e)=>({id:String(e.id),projectId:String(e.project_id),backupPolicyId:Rr(e.backup_policy_id),recoveryPointId:Rr(e.recovery_point_id),topologyId:Rr(e.topology_id),scenario:String(e.scenario),isolatedTarget:String(e.isolated_target),expectedRpoMinutes:Number(e.expected_rpo_minutes),expectedRtoMinutes:Number(e.expected_rto_minutes),status:String(e.status),operationId:Rr(e.operation_id),evidence:to(e.evidence,{}),measuredRpoMinutes:e.measured_rpo_minutes==null?void 0:Number(e.measured_rpo_minutes),measuredRtoMinutes:e.measured_rto_minutes==null?void 0:Number(e.measured_rto_minutes),cleanupVerified:Number(e.cleanup_verified)===1,error:Rr(e.error),startedAt:Rr(e.started_at),finishedAt:Rr(e.finished_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)});class Ln{control;now;id;constructor(e,t=()=>new Date,r=()=>crypto.randomUUID()){this.control=e;this.now=t;this.id=r}addTrustedKey(e){let t=this.id(),r=this.now().toISOString(),n=Jf(e.publicKeyPem);return this.control.database.run("INSERT INTO platform_trusted_keys (id,organization_id,name,algorithm,public_key_pem,fingerprint,created_at) VALUES (?,?,?,'ed25519',?,?,?)",[t,e.organizationId,e.name,e.publicKeyPem,n,r]),this.key(t)}key(e){let t=this.control.database.query("SELECT * FROM platform_trusted_keys WHERE id=?").get(e);return t?aC(t):void 0}revokeKey(e){return this.control.database.run("UPDATE platform_trusted_keys SET revoked_at=? WHERE id=?",[this.now().toISOString(),e]),this.key(e)}importManifest(e){let t=this.key(e.keyId);if(!t||t.organizationId!==e.organizationId)throw Error("Trusted update key was not found.");if(t.revokedAt)throw Error("Update signing key is revoked.");if(!Hf(e.document,e.signature,t.publicKeyPem))throw Error("Update manifest signature is invalid.");let r=Wf(e.document,e.current),n=Gf(e.document),i=this.id(),o=this.now().toISOString();return this.control.database.run("INSERT INTO platform_update_manifests (id,organization_id,version,channel,published_at,key_id,digest,document,signature,verification_status,compatibility,created_at) VALUES (?,?,?,?,?,?,?,?,?,'verified',?,?)",[i,e.organizationId,e.document.version,e.document.channel,new Date(e.document.publishedAt).toISOString(),e.keyId,n,JSON.stringify(e.document),e.signature,JSON.stringify(r),o]),this.manifest(i)}manifest(e){let t=this.control.database.query("SELECT * FROM platform_update_manifests WHERE id=?").get(e);return t?Kf(t):void 0}manifests(e){return this.control.database.query("SELECT * FROM platform_update_manifests WHERE organization_id=? ORDER BY published_at DESC").all(e).map(Kf)}createWindow(e){let t=this.id(),r=this.now().toISOString();return this.control.database.run("INSERT INTO maintenance_windows (id,project_id,name,schedule,timezone,duration_minutes,allowed_operations,require_approval,enabled,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,1,?,?)",[t,e.projectId,e.name,e.schedule,e.timezone,e.durationMinutes,JSON.stringify(e.allowedOperations),e.requireApproval===!1?0:1,r,r]),this.window(t)}window(e){let t=this.control.database.query("SELECT * FROM maintenance_windows WHERE id=?").get(e);return t?Qf(t):void 0}windows(e){return this.control.database.query("SELECT * FROM maintenance_windows WHERE project_id=? ORDER BY name").all(e).map(Qf)}createCampaign(e){return this.control.transaction(()=>{let t=this.manifest(e.manifestId);if(!t?.compatibility.compatible||t.verificationStatus!=="verified")throw Error("A verified compatible update manifest is required.");if(!e.backupId)throw Error("A verified pre-upgrade backup is required.");let r=this.id(),n=this.now().toISOString();return this.control.database.run("INSERT INTO platform_upgrade_campaigns (id,project_id,manifest_id,window_id,from_version,strategy,batch_size,health_gate,status,backup_id,approved_by,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?, 'planned',?,?,?,?)",[r,e.projectId,e.manifestId,e.windowId??null,e.fromVersion,e.strategy,e.batchSize,JSON.stringify(e.healthGate),e.backupId,e.approvedBy??null,n,n]),e.targets.forEach((i,o)=>this.control.database.run("INSERT INTO platform_upgrade_targets (id,campaign_id,server_id,target,cohort,previous_version,status,created_at,updated_at) VALUES (?,?,?,?,?,?,'pending',?,?)",[this.id(),r,i.serverId??null,i.target,e.strategy==="canary"?o===0?0:1+Math.floor((o-1)/e.batchSize):Math.floor(o/e.batchSize),i.previousVersion,n,n])),this.campaign(r)})}campaign(e){let t=this.control.database.query("SELECT * FROM platform_upgrade_campaigns WHERE id=?").get(e);return t?Yf(t):void 0}campaigns(e){return this.control.database.query("SELECT * FROM platform_upgrade_campaigns WHERE project_id=? ORDER BY created_at DESC").all(e).map(Yf)}targets(e){return this.control.database.query("SELECT * FROM platform_upgrade_targets WHERE campaign_id=? ORDER BY cohort,target").all(e).map(bl)}updateCampaign(e,t){let r=this.campaign(e);if(!r)throw Error("Upgrade campaign was not found.");let n={...r,...t};return this.control.database.run("UPDATE platform_upgrade_campaigns SET status=?,current_stage=?,updated_at=? WHERE id=?",[n.status,n.currentStage??null,this.now().toISOString(),e]),this.campaign(e)}updateTarget(e,t){let r=this.control.database.query("SELECT * FROM platform_upgrade_targets WHERE id=?").get(e);if(!r)throw Error("Upgrade target was not found.");let n={...bl(r),...t};return this.control.database.run("UPDATE platform_upgrade_targets SET status=?,evidence=?,error=?,started_at=?,finished_at=?,updated_at=? WHERE id=?",[n.status,JSON.stringify(n.evidence),n.error??null,n.startedAt??null,n.finishedAt??null,this.now().toISOString(),e]),bl(this.control.database.query("SELECT * FROM platform_upgrade_targets WHERE id=?").get(e))}createCleanup(e){let t=[...e.candidates].sort((s,c)=>s.id.localeCompare(c.id)),r=nd(t),n=this.id(),i=this.now().toISOString(),o=new Date(this.now().getTime()+(e.ttlMinutes??60)*60000).toISOString();return this.control.database.run("INSERT INTO cleanup_plans (id,project_id,kind,criteria,candidates,candidate_digest,estimated_bytes,status,expires_at,created_at,updated_at) VALUES (?,?,?,?,?,?,?,'preview',?,?,?)",[n,e.projectId,e.kind,JSON.stringify(e.criteria),JSON.stringify(t),r,t.reduce((s,c)=>s+c.bytes,0),o,i,i]),this.cleanup(n)}cleanup(e){let t=this.control.database.query("SELECT * FROM cleanup_plans WHERE id=?").get(e);return t?Xf(t):void 0}cleanups(e){return this.control.database.query("SELECT * FROM cleanup_plans WHERE project_id=? ORDER BY created_at DESC").all(e).map(Xf)}updateCleanup(e,t){let r=this.cleanup(e);if(!r)throw Error("Cleanup plan was not found.");let n={...r,...t};return this.control.database.run("UPDATE cleanup_plans SET status=?,confirmation=?,result=?,updated_at=? WHERE id=?",[n.status,n.confirmation??null,JSON.stringify(n.result),this.now().toISOString(),e]),this.cleanup(e)}createDrill(e){if(!/^isolated:\/\//.test(e.isolatedTarget))throw Error("DR drills require an isolated target.");let t=this.id(),r=this.now().toISOString();return this.control.database.run("INSERT INTO disaster_recovery_drills (id,project_id,backup_policy_id,recovery_point_id,topology_id,scenario,isolated_target,expected_rpo_minutes,expected_rto_minutes,status,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,'planned',?,?)",[t,e.projectId,e.backupPolicyId??null,e.recoveryPointId??null,e.topologyId??null,e.scenario,e.isolatedTarget,e.expectedRpoMinutes,e.expectedRtoMinutes,r,r]),this.drill(t)}drill(e){let t=this.control.database.query("SELECT * FROM disaster_recovery_drills WHERE id=?").get(e);return t?Zf(t):void 0}drills(e){return this.control.database.query("SELECT * FROM disaster_recovery_drills WHERE project_id=? ORDER BY created_at DESC").all(e).map(Zf)}updateDrill(e,t){let r=this.drill(e);if(!r)throw Error("DR drill was not found.");let n={...r,...t};return this.control.database.run("UPDATE disaster_recovery_drills SET status=?,operation_id=?,evidence=?,measured_rpo_minutes=?,measured_rto_minutes=?,cleanup_verified=?,error=?,started_at=?,finished_at=?,updated_at=? WHERE id=?",[n.status,n.operationId??null,JSON.stringify(n.evidence),n.measuredRpoMinutes??null,n.measuredRtoMinutes??null,n.cleanupVerified?1:0,n.error??null,n.startedAt??null,n.finishedAt??null,this.now().toISOString(),e]),this.drill(e)}}function cC(e,t=new Date){if(!e.enabled)return!1;let r=new Date(e.schedule);if(!Number.isNaN(r.getTime()))return t>=r&&t.getTime()<=r.getTime()+e.durationMinutes*60000;let n=/^(\d{2}):(\d{2})$/.exec(e.schedule);if(!n)return!1;let i=new Intl.DateTimeFormat("en-US",{timeZone:e.timezone,hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).formatToParts(t),o=Number(i.find((c)=>c.type==="hour")?.value)*60+Number(i.find((c)=>c.type==="minute")?.value),s=Number(n[1])*60+Number(n[2]);return o>=s&&o<s+e.durationMinutes}class Mn{store;now;queue;constructor(e,t,r=()=>new Date){this.store=e;this.now=r;this.queue=t??new S(e.control)}enqueueCampaign(e,t={}){let r=this.store.campaign(e);if(!r)throw Error("Upgrade campaign was not found.");let n=r.windowId?this.store.window(r.windowId):void 0;if(n&&!n.allowedOperations.includes("platform.upgrade"))throw Error("Maintenance window does not permit platform upgrades.");if(n&&!t.overrideWindow&&!cC(n,this.now()))throw Error("Upgrade is outside its maintenance window.");if(n?.requireApproval&&!t.approvedBy&&!r.approvedBy)throw Error("Maintenance approval is required.");let i=this.queue.enqueue({projectId:r.projectId,actorId:t.approvedBy,kind:"maintenance.upgrade",input:{campaignId:e},lockKey:"platform-upgrade",providerKey:"platform",timeoutSeconds:7200,cancellationMode:"cooperative",resumePolicy:"fail"}).operation;return{campaign:this.store.updateCampaign(e,{status:"queued"}),operation:i}}async previewCleanup(e,t){let r=t.find((n)=>n.kind===e.kind);if(!r)throw Error(`No ${e.kind} cleanup driver is configured.`);return this.store.createCleanup({...e,candidates:await r.discover(e.criteria)})}enqueueCleanup(e,t){let r=this.store.cleanup(e);if(!r||r.status!=="preview")throw Error("A current cleanup preview is required.");if(new Date(r.expiresAt)<=this.now())throw Error("Cleanup preview expired; generate it again.");let n=`DELETE ${r.candidates.length} ${r.kind}`;if(t!==n)throw Error(`Exact confirmation ${n} is required.`);let i=this.queue.enqueue({projectId:r.projectId,kind:"maintenance.cleanup",input:{planId:e},lockKey:`cleanup:${r.kind}`,providerKey:"cleanup",timeoutSeconds:3600,cancellationMode:"cooperative"}).operation;return{plan:this.store.updateCleanup(e,{status:"approved",confirmation:t}),operation:i}}enqueueDrill(e){let t=this.store.drill(e);if(!t||t.status!=="planned")throw Error("A planned DR drill is required.");let r=this.queue.enqueue({projectId:t.projectId,kind:"maintenance.drill",input:{drillId:e},lockKey:`drill:${t.scenario}:${t.id}`,providerKey:"recovery",timeoutSeconds:7200,cancellationMode:"cooperative"}).operation;return{drill:this.store.updateDrill(e,{status:"queued",operationId:r.id}),operation:r}}}var Sl=(e)=>e&&typeof e==="object"&&!Array.isArray(e)?e:{};function eh(e){return{"maintenance.upgrade":async(i)=>{let o=e.store.campaign(String(Sl(i.operation.input).campaignId??""));if(!o||!e.platform)throw Error("Upgrade campaign or platform maintenance driver is unavailable.");let s=e.store.manifest(o.manifestId);if(!s?.compatibility.compatible||s.verificationStatus!=="verified")throw Error("Update manifest is no longer verified and compatible.");let c=s.document.artifacts.find((a)=>a.platform===process.platform&&a.architecture===process.arch)??s.document.artifacts[0];if(!c)throw Error("No update artifact matches this platform.");e.store.updateCampaign(o.id,{status:"running",currentStage:"preflight"});let u=[];try{for(let a of[...new Set(e.store.targets(o.id).map((f)=>f.cohort))].sort((f,T)=>f-T)){e.store.updateCampaign(o.id,{currentStage:`cohort:${a}`});for(let f of e.store.targets(o.id).filter((T)=>T.cohort===a)){i.throwIfCancellationRequested(),i.checkpoint(`download:${f.target}`,"Downloading signed platform artifact."),e.store.updateTarget(f.id,{status:"downloading",startedAt:new Date().toISOString()});let T=await e.platform.download({target:f,artifact:c,signal:i.signal});if(T.sha256!==c.sha256)throw Error(`Artifact checksum mismatch for ${f.target}.`);i.checkpoint(`install:${f.target}`,"Installing verified artifact."),e.store.updateTarget(f.id,{status:"installing"}),await e.platform.install({target:f,path:T.path,version:s.version,signal:i.signal}),u.push(f);let R=await e.platform.health({target:f,gate:o.healthGate});if(!R.healthy)throw Error(`Upgrade health gate failed for ${f.target}.`);e.store.updateTarget(f.id,{status:"healthy",evidence:R.evidence,finishedAt:new Date().toISOString()})}}return e.store.updateCampaign(o.id,{status:"succeeded",currentStage:void 0}),{campaignId:o.id,version:s.version,targets:u.length}}catch(a){e.store.updateCampaign(o.id,{status:"rolling_back",currentStage:"rollback"});for(let f of u.reverse())e.store.updateTarget(f.id,{status:"rolling_back"}),await e.platform.rollback({target:f,version:f.previousVersion,signal:i.signal}),e.store.updateTarget(f.id,{status:"rolled_back",finishedAt:new Date().toISOString()});throw e.store.updateCampaign(o.id,{status:"rolled_back",currentStage:void 0}),a}},"maintenance.cleanup":async(i)=>{let o=e.store.cleanup(String(Sl(i.operation.input).planId??""));if(!o||o.status!=="approved")throw Error("Approved cleanup plan was not found.");if(nd([...o.candidates].sort((f,T)=>f.id.localeCompare(T.id)))!==o.candidateDigest)throw Error("Cleanup candidate set changed after preview.");let s=e.cleanup?.find((f)=>f.kind===o.kind);if(!s)throw Error(`No ${o.kind} cleanup driver is configured.`);e.store.updateCleanup(o.id,{status:"running"});let c=[],u=[];for(let f of o.candidates){i.throwIfCancellationRequested();try{await s.remove(f),c.push(f.id)}catch(T){u.push({id:f.id,error:T instanceof Error?T.message:String(T)})}}let a=u.length?c.length?"partial":"failed":"succeeded";if(e.store.updateCleanup(o.id,{status:a,result:{removed:c,failed:u,reclaimedBytes:o.candidates.filter((f)=>c.includes(f.id)).reduce((f,T)=>f+T.bytes,0)}}),u.length)throw Error(`Cleanup failed for ${u.length} candidate(s).`);return{planId:o.id,removed:c.length,reclaimedBytes:o.estimatedBytes}},"maintenance.drill":async(i)=>{let o=e.store.drill(String(Sl(i.operation.input).drillId??""));if(!o)throw Error("DR drill was not found.");let s=e.recovery?.find((T)=>T.scenario===o.scenario);if(!s)throw Error(`No ${o.scenario} recovery driver is configured.`);let c=new Date;e.store.updateDrill(o.id,{status:"restoring",startedAt:c.toISOString()});let u=o.isolatedTarget,a={},f={};try{i.checkpoint("restore","Restoring into isolated drill target.");let T=await s.restore({drill:o,signal:i.signal});if(!T.target.startsWith("isolated://"))throw Error("Recovery driver attempted a non-isolated target.");u=T.target,a=T.evidence;let R=(c.getTime()-new Date(T.recoveryPointAt).getTime())/60000;e.store.updateDrill(o.id,{status:"verifying",measuredRpoMinutes:R,evidence:{restore:a}}),i.checkpoint("verify","Running recovery health checks without production traffic.");let D=await s.verify({drill:o,target:u});f=D.evidence;let W=(Date.now()-c.getTime())/60000;if(!D.healthy||R>o.expectedRpoMinutes||W>o.expectedRtoMinutes)throw Error("DR drill failed its health, RPO, or RTO objective.");e.store.updateDrill(o.id,{measuredRpoMinutes:R,measuredRtoMinutes:W,evidence:{restore:a,verify:f}})}catch(T){throw e.store.updateDrill(o.id,{status:"failed",error:T instanceof Error?T.message:String(T),evidence:{restore:a,verify:f}}),T}finally{e.store.updateDrill(o.id,{status:"cleaning"});try{await s.cleanup({drill:o,target:u});let T=e.store.drill(o.id);e.store.updateDrill(o.id,{status:T.error?"failed":"passed",cleanupVerified:!0,finishedAt:new Date().toISOString()})}catch(T){e.store.updateDrill(o.id,{status:"cleanup_required",cleanupVerified:!1,error:T instanceof Error?T.message:String(T),finishedAt:new Date().toISOString()})}}return{drillId:o.id,status:e.store.drill(o.id).status}}}}var th={releases:{select:"SELECT id,created_at,0 bytes FROM releases WHERE project_id=? AND pinned=0 AND status IN ('failed','rolled_back','superseded') AND created_at<?",remove:"DELETE FROM releases WHERE id=?"},artifacts:{select:"SELECT a.id,a.created_at,a.size bytes FROM release_artifacts a WHERE a.organization_id=? AND NOT EXISTS(SELECT 1 FROM releases r WHERE r.artifact_id=a.id) AND a.created_at<?",remove:"DELETE FROM release_artifacts WHERE id=?"},operations:{select:"SELECT id,created_at,0 bytes FROM operations WHERE project_id=? AND state IN ('succeeded','failed','cancelled','timed_out') AND updated_at<?",remove:"DELETE FROM operations WHERE id=?"},logs:{select:"SELECT l.id,l.created_at,length(l.message) bytes FROM operation_logs l JOIN operations o ON o.id=l.operation_id WHERE o.project_id=? AND o.state IN ('succeeded','failed','cancelled','timed_out') AND l.created_at<?",remove:"DELETE FROM operation_logs WHERE id=?"},previews:{select:"SELECT id,created_at,0 bytes FROM preview_instances WHERE project_id=? AND status IN ('destroyed','failed') AND updated_at<?",remove:"DELETE FROM preview_instances WHERE id=?"},snapshots:{select:"SELECT id,created_at,size_bytes bytes FROM recovery_points WHERE project_id=? AND pinned=0 AND held=0 AND status IN ('failed','deleted') AND created_at<?",remove:"DELETE FROM recovery_points WHERE id=?"},orphaned_resources:{select:"SELECT id,created_at,COALESCE(capacity_bytes,0) bytes FROM persistent_volumes WHERE project_id=? AND status='orphaned' AND orphaned_at<?",remove:"UPDATE persistent_volumes SET status='deleted',deleted_at=datetime('now'),updated_at=datetime('now') WHERE id=? AND status='orphaned'"}};class Un{kind;control;projectId;organizationId;constructor(e,t,r,n){this.kind=e;this.control=t;this.projectId=r;this.organizationId=n}async discover(e){let t=Math.max(1,Math.min(3650,Number(e.olderThanDays??30))),r=new Date(Date.now()-t*86400000).toISOString(),n=th[this.kind],i=this.kind==="artifacts"?this.organizationId:this.projectId;return this.control.database.query(n.select).all(i,r).map((s)=>({id:String(s.id),kind:this.kind,label:`${this.kind}:${String(s.id)}`,bytes:Number(s.bytes??0),metadata:{createdAt:String(s.created_at)}}))}async remove(e){if(this.control.database.run(th[this.kind].remove,[e.id]).changes!==1)throw Error(`${e.label} changed or is no longer removable.`)}}var wi=(e,t)=>{try{return JSON.parse(String(e))}catch{return t}},yn=(e)=>e==null?void 0:String(e),ih=()=>({cpu:0,memoryBytes:0,diskBytes:0,gpu:0}),Ks=(e={})=>({...ih(),...e});function rh(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),name:String(e.name),purpose:String(e.purpose),backend:String(e.backend),region:yn(e.region),architecture:yn(e.architecture),labels:wi(e.labels,{}),requiredServerLabels:wi(e.required_server_labels,{}),toleratedTaints:wi(e.tolerated_taints,[]),capacity:Ks(wi(e.capacity,{})),reserved:wi(e.reserved,{}),maxWorkloads:Number(e.max_workloads),costWeight:Number(e.cost_weight),spreadKey:yn(e.spread_key),concurrency:Number(e.concurrency),ephemeralWorkspaces:Number(e.ephemeral_workspaces)===1,allowProductionSecrets:Number(e.allow_production_secrets)===1,status:String(e.status),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function nh(e){return{id:String(e.id),projectId:String(e.project_id),environmentId:yn(e.environment_id),resourceId:String(e.resource_id),releaseId:yn(e.release_id),poolId:String(e.pool_id),serverId:yn(e.server_id),purpose:String(e.purpose),requirements:wi(e.requirements,{}),decision:wi(e.decision,{}),stateful:Number(e.stateful)===1,autoReschedule:Number(e.auto_reschedule)===1,status:String(e.status),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function dC(e){return{id:String(e.id),projectId:String(e.project_id),resourceId:yn(e.resource_id),poolId:String(e.pool_id),placementId:yn(e.placement_id),operationId:yn(e.operation_id),sourceSha:String(e.source_sha),buildSpec:wi(e.build_spec,{}),credentialPolicy:wi(e.credential_policy,{productionSecrets:!1,shortLivedTokenExpiresAt:""}),workspace:yn(e.workspace),cacheKey:yn(e.cache_key),artifactUri:yn(e.artifact_uri),artifactDigest:yn(e.artifact_digest),status:String(e.status),cleanupAt:yn(e.cleanup_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}class xn{control;now;id;constructor(e,t=()=>new Date,r=()=>crypto.randomUUID()){this.control=e;this.now=t;this.id=r}createPool(e){let t=this.id(),r=this.now().toISOString();return this.control.database.run("INSERT INTO capacity_pools (id,organization_id,project_id,name,purpose,backend,region,architecture,labels,required_server_labels,tolerated_taints,capacity,reserved,max_workloads,cost_weight,spread_key,concurrency,ephemeral_workspaces,allow_production_secrets,status,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.organizationId,e.projectId,e.name,e.purpose,e.backend,e.region??null,e.architecture??null,JSON.stringify(e.labels),JSON.stringify(e.requiredServerLabels),JSON.stringify(e.toleratedTaints),JSON.stringify(Ks(e.capacity)),"{}",e.maxWorkloads,e.costWeight,e.spreadKey??null,e.concurrency,e.ephemeralWorkspaces?1:0,e.allowProductionSecrets?1:0,e.status,r,r]),this.getPool(t)}getPool(e){let t=this.control.database.query("SELECT * FROM capacity_pools WHERE id=?").get(e);return t?rh(t):void 0}listPools(e){return this.control.database.query("SELECT * FROM capacity_pools WHERE project_id=? ORDER BY name").all(e).map(rh)}updatePool(e,t){let r=this.getPool(e);if(!r)throw Error("Capacity pool was not found.");let n={...r,...t},i=this.now().toISOString();return this.control.database.run("UPDATE capacity_pools SET status=?,reserved=?,capacity=?,concurrency=?,version=version+1,updated_at=? WHERE id=?",[n.status,JSON.stringify(n.reserved),JSON.stringify(n.capacity),n.concurrency,i,e]),this.getPool(e)}addMember(e,t,r={}){let n=this.now().toISOString();this.control.database.run("INSERT INTO capacity_pool_members (pool_id,server_id,capacity_override,status,created_at,updated_at) VALUES (?,?,?,'active',?,?) ON CONFLICT(pool_id,server_id) DO UPDATE SET capacity_override=excluded.capacity_override,status='active',updated_at=excluded.updated_at",[e,t,JSON.stringify(r),n,n])}members(e){return this.control.database.query("SELECT * FROM capacity_pool_members WHERE pool_id=? ORDER BY server_id").all(e).map((t)=>({serverId:String(t.server_id),status:String(t.status),capacityOverride:wi(t.capacity_override,{})}))}memberStatus(e,t,r){this.control.database.run("UPDATE capacity_pool_members SET status=?,updated_at=? WHERE pool_id=? AND server_id=?",[r,this.now().toISOString(),e,t])}listPlacements(e,t){let r=this.control.database.query("SELECT * FROM workload_placements WHERE project_id=? ORDER BY created_at,id").all(e).map(nh);return t?.length?r.filter((n)=>t.includes(n.status)):r}getPlacement(e){let t=this.control.database.query("SELECT * FROM workload_placements WHERE id=?").get(e);return t?nh(t):void 0}activeUsage(e,t){let r=this.control.database.query("SELECT l.resources,l.server_id FROM capacity_leases l WHERE l.pool_id=? AND l.state='active' AND l.expires_at>?").all(e,this.now().toISOString()),n=t?r.filter((i)=>String(i.server_id)===t):r;return{resources:n.reduce((i,o)=>{let s=Ks(wi(o.resources,{}));for(let c of Object.keys(i))i[c]+=s[c];return i},ih()),count:n.length}}expireLeases(){return this.control.database.run("UPDATE capacity_leases SET state='expired',updated_at=? WHERE state='active' AND expires_at<=?",[this.now().toISOString(),this.now().toISOString()]).changes}reserve(e){return this.control.transaction(()=>{this.expireLeases();let t=this.id(),r=this.id(),n=this.now().toISOString(),i=new Date(this.now().getTime()+(e.requirements.leaseSeconds??300)*1000).toISOString();return this.control.database.run("INSERT INTO workload_placements (id,project_id,environment_id,resource_id,release_id,pool_id,server_id,purpose,requirements,decision,stateful,auto_reschedule,status,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,'reserved',?,?)",[t,e.projectId,e.environmentId??null,e.resourceId,e.releaseId??null,e.decision.poolId,e.decision.serverId??null,e.requirements.purpose,JSON.stringify(e.requirements),JSON.stringify(e.decision),e.requirements.stateful?1:0,e.requirements.autoReschedule&&!e.requirements.stateful?1:0,n,n]),this.control.database.run("INSERT INTO capacity_leases (id,placement_id,pool_id,server_id,resources,state,expires_at,created_at,updated_at) VALUES (?,?,?,?,?,'active',?,?,?)",[r,t,e.decision.poolId,e.decision.serverId??null,JSON.stringify(Ks(e.requirements.resources)),i,n,n]),this.getPlacement(t)})}transitionPlacement(e,t){if(!this.getPlacement(e))throw Error("Placement was not found.");let n=this.now().toISOString();if(this.control.database.run("UPDATE workload_placements SET status=?,version=version+1,updated_at=? WHERE id=?",[t,n,e]),["released","failed","blocked"].includes(t))this.control.database.run("UPDATE capacity_leases SET state='released',updated_at=? WHERE placement_id=? AND state='active'",[n,e]);return this.getPlacement(e)}createBuild(e){let t=this.id(),r=this.now().toISOString();return this.control.database.run("INSERT INTO remote_builds (id,project_id,resource_id,pool_id,placement_id,operation_id,source_sha,build_spec,credential_policy,status,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,'queued',?,?)",[t,e.projectId,e.resourceId??null,e.poolId,e.placementId??null,e.operationId??null,e.sourceSha,JSON.stringify(e.buildSpec),JSON.stringify({productionSecrets:!1,shortLivedTokenExpiresAt:e.tokenExpiresAt}),r,r]),this.getBuild(t)}getBuild(e){let t=this.control.database.query("SELECT * FROM remote_builds WHERE id=?").get(e);return t?dC(t):void 0}updateBuild(e,t){let r=this.getBuild(e);if(!r)throw Error("Remote build was not found.");let n={...r,...t},i=this.now().toISOString();return this.control.database.run("UPDATE remote_builds SET operation_id=?,workspace=?,cache_key=?,artifact_uri=?,artifact_digest=?,status=?,cleanup_at=?,updated_at=? WHERE id=?",[n.operationId??null,n.workspace??null,n.cacheKey??null,n.artifactUri??null,n.artifactDigest??null,n.status,n.cleanupAt??null,i,e]),this.getBuild(e)}}var id=["cpu","memoryBytes","diskBytes","gpu"],oh=(e,t={})=>Object.entries(t).every(([r,n])=>e[r]===n),uC=(e,t,r)=>Object.fromEntries(id.map((n)=>[n,Math.max(0,e[n]-t[n]-(r[n]??0))])),lC=(e,t)=>id.every((r)=>e[r]>=(t[r]??0)),pC=(e,t)=>id.reduce((r,n)=>r+(t[n]??0)/(e[n]||1),0);class _n{store;fleet;constructor(e,t){this.store=e;this.fleet=t}poolCandidates(e,t,r){let n=[];for(let i of this.store.listPools(e)){if(i.id===r)continue;let o=[];if(i.status!=="active")o.push(`pool is ${i.status}`);if(i.purpose!==t.purpose)o.push(`purpose is ${i.purpose}`);if(t.region&&i.region!==t.region)o.push(`region is ${i.region??"unset"}`);if(t.architecture&&i.architecture!==t.architecture)o.push(`architecture is ${i.architecture??"unset"}`);if(!oh(i.labels,t.labels))o.push("pool labels do not match");if(i.backend==="server"){let s=this.store.members(i.id);if(!s.length)n.push(this.decision(i,void 0,t,[...o,"pool has no servers"]));for(let c of s){let u=this.fleet.get(c.serverId),a=[...o];if(!u)a.push("server is missing");else this.serverReasons(i,u,c.status,t,a);n.push(this.decision(i,u,t,a,c.capacityOverride))}}else n.push(this.decision(i,void 0,t,o))}return n.sort((i,o)=>Number(o.eligible)-Number(i.eligible)||i.score.cost-o.score.cost||i.score.spread-o.score.spread||i.score.fit-o.score.fit||i.poolName.localeCompare(o.poolName)||(i.serverId??"").localeCompare(o.serverId??""))}serverReasons(e,t,r,n,i){if(r!=="active")i.push(`member is ${r}`);if(t.status!=="ready")i.push(`server is ${t.status}`);if(!t.roles.includes(n.purpose==="build"?"build":n.purpose))i.push(`server lacks ${n.purpose} role`);if(!oh(t.labels,e.requiredServerLabels))i.push("server labels do not match pool selector");for(let o of t.taints)if(!e.toleratedTaints.includes(o))i.push(`taint ${o} is not tolerated`)}decision(e,t,r,n,i={}){let o=Ks({...t?.capacity,...i}),s=t?Object.fromEntries(id.map((a)=>[a,Math.min(e.capacity[a],o[a])])):e.capacity,c=this.store.activeUsage(e.id,t?.id),u=uC(s,c.resources,e.reserved);if(c.count>=e.maxWorkloads)n.push("workload limit reached");if(r.purpose==="build"&&c.count>=e.concurrency)n.push("build concurrency reached");if(!lC(u,r.resources))n.push("insufficient capacity");return{poolId:e.id,poolName:e.name,serverId:t?.id,eligible:n.length===0,reasons:n,available:u,score:{fit:pC(u,r.resources),spread:c.count,cost:e.costWeight}}}explain(e,t){return this.poolCandidates(e,t)}place(e){return this.store.control.transaction(()=>{let t=this.poolCandidates(e.projectId,e.requirements).find((r)=>r.eligible);if(!t)throw Error(`No eligible capacity: ${this.explain(e.projectId,e.requirements).flatMap((r)=>r.reasons).join("; ")}`);return this.store.reserve({...e,decision:t})})}activate(e){return this.store.transitionPlacement(e,"active")}release(e){return this.store.transitionPlacement(e,"released")}drainPool(e){let t=this.store.updatePool(e,{status:"draining"}),r=[],n=[];for(let i of this.store.listPlacements(t.projectId,["reserved","active"]).filter((o)=>o.poolId===e)){if(i.stateful){n.push(this.store.transitionPlacement(i.id,"blocked"));continue}this.store.transitionPlacement(i.id,"moving");let o=this.place({projectId:i.projectId,environmentId:i.environmentId,resourceId:i.resourceId,releaseId:i.releaseId,requirements:i.requirements});r.push(this.activate(o.id)),this.store.transitionPlacement(i.id,"released")}return{pool:t,moved:r,blocked:n}}drainServer(e,t){this.store.memberStatus(e,t,"draining");let r=this.store.getPool(e);if(!r)throw Error("Capacity pool was not found.");let n=[],i=[];for(let o of this.store.listPlacements(r.projectId,["reserved","active"]).filter((s)=>s.poolId===e&&s.serverId===t)){if(o.stateful){i.push(this.store.transitionPlacement(o.id,"blocked"));continue}this.store.transitionPlacement(o.id,"moving");let s=this.poolCandidates(o.projectId,o.requirements).find((u)=>u.eligible);if(!s){i.push(this.store.transitionPlacement(o.id,"blocked"));continue}let c=this.store.reserve({projectId:o.projectId,environmentId:o.environmentId,resourceId:o.resourceId,releaseId:o.releaseId,requirements:o.requirements,decision:s});n.push(this.activate(c.id)),this.store.transitionPlacement(o.id,"released")}return{moved:n,blocked:i}}reconcileFailure(e){let t=this.fleet.get(e);if(!t)throw Error("Server was not found.");let r=[],n=[];for(let i of this.store.listPlacements(t.projectId,["active"]).filter((o)=>o.serverId===e)){if(i.stateful||!i.autoReschedule){n.push(this.store.transitionPlacement(i.id,"blocked"));continue}this.store.transitionPlacement(i.id,"failed");let o=this.place({projectId:i.projectId,environmentId:i.environmentId,resourceId:i.resourceId,releaseId:i.releaseId,requirements:i.requirements});r.push(this.activate(o.id))}return{rescheduled:r,blocked:n}}}var ro=(e,t)=>{try{return JSON.parse(String(e))}catch{return t}},ai=(e)=>e==null?void 0:String(e),sh=(e)=>({id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:ai(e.environment_id),name:String(e.name),hostname:String(e.hostname),homeRegion:String(e.home_region),regions:ro(e.regions,[]),trafficPolicy:String(e.traffic_policy),dataPolicy:ro(e.data_policy,{replicate:[],maxLagSeconds:60,retainOnDestroy:!0}),status:String(e.status),activeRegion:String(e.active_region),revision:ai(e.revision),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),vl=(e)=>({id:String(e.id),topologyId:String(e.topology_id),region:String(e.region),role:String(e.role),provider:String(e.provider),stackId:ai(e.stack_id),stackRevision:ai(e.stack_revision),status:String(e.status),health:ro(e.health,{}),lastHealthyAt:ai(e.last_healthy_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),wl=(e)=>({id:String(e.id),topologyId:String(e.topology_id),kind:String(e.kind),sourceRegion:String(e.source_region),targetRegion:String(e.target_region),config:ro(e.config,{}),status:String(e.status),checkpoint:ai(e.checkpoint),lagSeconds:e.lag_seconds==null?void 0:Number(e.lag_seconds),lastVerifiedAt:ai(e.last_verified_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),Il=(e)=>({id:String(e.id),topologyId:String(e.topology_id),hostname:String(e.hostname),dnsProvider:String(e.dns_provider),cdnEnabled:Number(e.cdn_enabled)===1,wafEnabled:Number(e.waf_enabled)===1,weights:ro(e.weights,{}),desiredWeights:ro(e.desired_weights,{}),status:String(e.status),providerState:ro(e.provider_state,{}),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),ah=(e)=>({id:String(e.id),topologyId:String(e.topology_id),operationId:ai(e.operation_id),kind:String(e.kind),requestedRegion:ai(e.requested_region),revision:ai(e.revision),plan:ro(e.plan,[]),currentStep:ai(e.current_step),completedSteps:ro(e.completed_steps,[]),status:String(e.status),error:ai(e.error),createdAt:String(e.created_at),updatedAt:String(e.updated_at)});class On{control;now;id;constructor(e,t=()=>new Date,r=()=>crypto.randomUUID()){this.control=e;this.now=t;this.id=r}create(e){return this.control.transaction(()=>{if(e.regions.length<2||new Set(e.regions.map((o)=>o.region)).size!==e.regions.length||e.regions.filter((o)=>o.role==="primary").length!==1)throw Error("A topology requires unique regions and exactly one primary.");let t=e.regions.find((o)=>o.role==="primary"),r=this.id(),n=this.now().toISOString();this.control.database.run("INSERT INTO regional_topologies (id,organization_id,project_id,environment_id,name,hostname,home_region,regions,traffic_policy,data_policy,status,active_region,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,'draft',?,?,?)",[r,e.organizationId,e.projectId,e.environmentId??null,e.name,e.hostname,t.region,JSON.stringify(e.regions),e.trafficPolicy,JSON.stringify(e.dataPolicy),t.region,n,n]);for(let o of e.regions)this.control.database.run("INSERT INTO regional_targets (id,topology_id,region,role,provider,status,created_at,updated_at) VALUES (?,?,?,?,?,'pending',?,?)",[this.id(),r,o.region,o.role,o.provider,n,n]);for(let o of e.dataPolicy.replicate)for(let s of e.regions)for(let c of e.regions.filter((u)=>u.region!==s.region))this.control.database.run("INSERT INTO regional_replication_channels (id,topology_id,kind,source_region,target_region,config,status,created_at,updated_at) VALUES (?,?,?,?,?,?,'pending',?,?)",[this.id(),r,o,s.region,c.region,"{}",n,n]);let i=Object.fromEntries(e.regions.map((o)=>[o.region,o.region===t.region?100:0]));return this.control.database.run("INSERT INTO regional_traffic_routes (id,topology_id,hostname,dns_provider,cdn_enabled,waf_enabled,weights,desired_weights,status,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?, 'pending',?,?)",[this.id(),r,e.hostname,e.dnsProvider??"route53",e.cdnEnabled?1:0,e.wafEnabled?1:0,JSON.stringify(i),JSON.stringify(i),n,n]),this.get(r)})}get(e){let t=this.control.database.query("SELECT * FROM regional_topologies WHERE id=?").get(e);return t?sh(t):void 0}list(e){return this.control.database.query("SELECT * FROM regional_topologies WHERE project_id=? ORDER BY name").all(e).map(sh)}targets(e){return this.control.database.query("SELECT * FROM regional_targets WHERE topology_id=? ORDER BY role,region").all(e).map(vl)}channels(e){return this.control.database.query("SELECT * FROM regional_replication_channels WHERE topology_id=? ORDER BY kind,target_region").all(e).map(wl)}route(e){let t=this.control.database.query("SELECT * FROM regional_traffic_routes WHERE topology_id=?").get(e);return t?Il(t):void 0}updateTopology(e,t){let r=this.get(e);if(!r)throw Error("Regional topology was not found.");let n={...r,...t},i=this.now().toISOString();return this.control.database.run("UPDATE regional_topologies SET status=?,active_region=?,revision=?,regions=?,version=version+1,updated_at=? WHERE id=?",[n.status,n.activeRegion,n.revision??null,JSON.stringify(n.regions),i,e]),this.get(e)}updateTarget(e,t){let r=this.control.database.query("SELECT * FROM regional_targets WHERE id=?").get(e);if(!r)throw Error("Regional target was not found.");let n=vl(r),i={...n,...t},o=this.now().toISOString();return this.control.database.run("UPDATE regional_targets SET role=?,stack_id=?,stack_revision=?,status=?,health=?,last_healthy_at=?,version=version+1,updated_at=? WHERE id=?",[i.role,i.stackId??null,i.stackRevision??null,i.status,JSON.stringify(i.health),i.lastHealthyAt??null,o,e]),vl(this.control.database.query("SELECT * FROM regional_targets WHERE id=?").get(e))}updateChannel(e,t){let r=this.control.database.query("SELECT * FROM regional_replication_channels WHERE id=?").get(e);if(!r)throw Error("Replication channel was not found.");let n=wl(r),i={...n,...t},o=this.now().toISOString();return this.control.database.run("UPDATE regional_replication_channels SET status=?,checkpoint=?,lag_seconds=?,last_verified_at=?,version=version+1,updated_at=? WHERE id=?",[i.status,i.checkpoint??null,i.lagSeconds??null,i.lastVerifiedAt??null,o,e]),wl(this.control.database.query("SELECT * FROM regional_replication_channels WHERE id=?").get(e))}updateRoute(e,t){let r=this.control.database.query("SELECT * FROM regional_traffic_routes WHERE id=?").get(e);if(!r)throw Error("Traffic route was not found.");let n=Il(r),i={...n,...t},o=this.now().toISOString();return this.control.database.run("UPDATE regional_traffic_routes SET weights=?,desired_weights=?,status=?,provider_state=?,version=version+1,updated_at=? WHERE id=?",[JSON.stringify(i.weights),JSON.stringify(i.desiredWeights),i.status,JSON.stringify(i.providerState),o,e]),Il(this.control.database.query("SELECT * FROM regional_traffic_routes WHERE id=?").get(e))}createExecution(e){let t=this.id(),r=this.now().toISOString();return this.control.database.run("INSERT INTO regional_executions (id,topology_id,operation_id,kind,requested_region,revision,plan,status,created_at,updated_at) VALUES (?,?,?,?,?,?,?,'queued',?,?)",[t,e.topologyId,e.operationId??null,e.kind,e.requestedRegion??null,e.revision??null,JSON.stringify(e.plan),r,r]),this.execution(t)}execution(e){let t=this.control.database.query("SELECT * FROM regional_executions WHERE id=?").get(e);return t?ah(t):void 0}executions(e){return this.control.database.query("SELECT * FROM regional_executions WHERE topology_id=? ORDER BY created_at DESC").all(e).map(ah)}updateExecution(e,t){let r=this.execution(e);if(!r)throw Error("Regional execution was not found.");let n={...r,...t},i=this.now().toISOString();return this.control.database.run("UPDATE regional_executions SET operation_id=?,current_step=?,completed_steps=?,status=?,error=?,updated_at=? WHERE id=?",[n.operationId??null,n.currentStep??null,JSON.stringify(n.completedSteps),n.status,n.error??null,i,e]),this.execution(e)}}class $n{store;queue;constructor(e,t){this.store=e;this.queue=t??new S(e.control)}create(e){return this.store.create(e)}plan(e,t,r){if(!this.store.get(e))throw Error("Regional topology was not found.");let i=this.store.targets(e),o=this.store.channels(e);if(t==="rollout")return[...i.filter((s)=>s.role==="secondary").map((s)=>`apply:${s.region}`),...i.filter((s)=>s.role==="primary").map((s)=>`apply:${s.region}`),...o.map((s)=>`replicate:${s.kind}:${s.targetRegion}`),"traffic:activate"];if(t==="failover"||t==="failback")return[`health:${r}`,`replication:${r}`,`traffic:${r}`,`roles:${r}`];if(t==="destroy")return["traffic:drain",...i.filter((s)=>s.role==="secondary").map((s)=>`delete:${s.region}`),...i.filter((s)=>s.role==="primary").map((s)=>`delete:${s.region}`),"complete"];return["observe","repair"]}enqueue(e){let t=this.store.get(e.topologyId);if(!t)throw Error("Regional topology was not found.");if(["failover","failback"].includes(e.kind)&&(!e.targetRegion||!t.regions.some((o)=>o.region===e.targetRegion)))throw Error("A topology target region is required.");if(e.kind==="failover"&&e.targetRegion===t.activeRegion)throw Error("Target region is already active.");if((e.kind==="destroy"||e.deleteData)&&e.confirmation!==t.name)throw Error("Exact topology name confirmation is required.");if(e.deleteData&&t.dataPolicy.retainOnDestroy)throw Error("Topology policy requires regional data retention.");if(e.kind==="rollout"&&!/^[A-Za-z0-9._:@/-]{7,200}$/.test(e.revision??""))throw Error("An immutable revision is required.");let r=this.plan(t.id,e.kind,e.targetRegion),n=this.store.createExecution({topologyId:t.id,kind:e.kind,requestedRegion:e.targetRegion,revision:e.revision,plan:r}),i=this.queue.enqueue({projectId:t.projectId,environmentId:t.environmentId,kind:`region.${e.kind}`,input:{executionId:n.id,manifest:e.manifest??{},deleteData:e.deleteData===!0},lockKey:`regional-topology:${t.id}`,providerKey:"multi-region",timeoutSeconds:7200,cancellationMode:"provider_non_cancellable",resumePolicy:"requeue",maxAttempts:3}).operation;return this.store.updateExecution(n.id,{operationId:i.id}),{execution:this.store.execution(n.id),operation:i}}}var gC=(e)=>e&&typeof e==="object"&&!Array.isArray(e)?e:{};function ch(e,t){let r=(a)=>{let f=t.find((T)=>T.provider===a.provider);if(!f)throw Error(`No ${a.provider} regional driver is configured.`);return f},n=(a,f,T)=>{a.throwIfCancellationRequested(),a.checkpoint(T,T),e.updateExecution(f.id,{status:"running",currentStep:T,completedSteps:[...e.execution(f.id).completedSteps,T]})},i=async(a,f)=>{let T=e.route(a.id);if(!T)throw Error("Regional traffic route was not found.");let R=e.targets(a.id).find((W)=>W.region===a.activeRegion)??e.targets(a.id)[0];if(!R)throw Error("Regional traffic target was not found.");e.updateRoute(T.id,{status:"applying",desiredWeights:f});let D=await r(R).applyTraffic({route:e.route(a.id),topology:a,weights:f});e.updateRoute(T.id,{status:Object.values(f).every((W)=>W===0)?"drained":"in_sync",weights:f,providerState:D.providerState})},o=async(a,f,T,R)=>{e.updateTopology(T.id,{status:"provisioning"});let D=f.revision,W=R.manifest??{},Y=e.targets(T.id).sort((ne,he)=>Number(ne.role==="primary")-Number(he.role==="primary"));for(let ne of Y){n(a,f,`apply:${ne.region}`),e.updateTarget(ne.id,{status:"provisioning"});let he=await r(ne).applyStack({target:ne,revision:D,manifest:W,signal:a.signal}),te=await r(ne).health({target:e.updateTarget(ne.id,{stackId:he.stackId,stackRevision:D})});if(!te.healthy)throw Error(`Regional health gate failed in ${ne.region}.`);e.updateTarget(ne.id,{status:"ready",health:te.evidence,lastHealthyAt:new Date().toISOString()})}for(let ne of e.channels(T.id)){n(a,f,`replicate:${ne.kind}:${ne.targetRegion}`),e.updateChannel(ne.id,{status:"configuring"});let he=Y.find((tt)=>tt.region===ne.sourceRegion),te=await r(he).configureReplication({channel:ne,topology:T}),De=await r(he).verifyReplication({channel:e.updateChannel(ne.id,{checkpoint:te.checkpoint,lagSeconds:te.lagSeconds}),topology:T});if(!De.healthy||De.lagSeconds>T.dataPolicy.maxLagSeconds)throw Error(`${ne.kind} replication to ${ne.targetRegion} exceeds the RPO.`);e.updateChannel(ne.id,{status:"in_sync",checkpoint:De.checkpoint,lagSeconds:De.lagSeconds,lastVerifiedAt:new Date().toISOString()})}n(a,f,"traffic:activate");let ee=Object.fromEntries(T.regions.map((ne)=>[ne.region,ne.region===T.activeRegion?100:0]));return await i(T,ee),e.updateTopology(T.id,{status:"ready",revision:D}),{revision:D,activeRegion:T.activeRegion}},s=async(a,f,T)=>{let R=f.requestedRegion,D=e.targets(T.id).find((ee)=>ee.region===R);if(!D)throw Error("Requested regional target was not found.");e.updateTopology(T.id,{status:f.kind==="failover"?"failing_over":"failing_back"}),n(a,f,`health:${R}`);let W=await r(D).health({target:D});if(!W.healthy)throw Error(`Target region ${R} is unhealthy.`);e.updateTarget(D.id,{status:"ready",health:W.evidence,lastHealthyAt:new Date().toISOString()}),n(a,f,`replication:${R}`);for(let ee of e.channels(T.id).filter((ne)=>ne.targetRegion===R)){let ne=await r(D).verifyReplication({channel:ee,topology:T});if(!ne.healthy||ne.lagSeconds>T.dataPolicy.maxLagSeconds)throw Error(`${ee.kind} replication is outside the failover RPO.`);e.updateChannel(ee.id,{status:"in_sync",checkpoint:ne.checkpoint,lagSeconds:ne.lagSeconds,lastVerifiedAt:new Date().toISOString()})}n(a,f,`traffic:${R}`),await i(T,Object.fromEntries(T.regions.map((ee)=>[ee.region,ee.region===R?100:0]))),n(a,f,`roles:${R}`);let Y=T.regions.map((ee)=>({...ee,role:ee.region===R?"primary":"secondary"}));for(let ee of e.targets(T.id))e.updateTarget(ee.id,{role:ee.region===R?"primary":"secondary"});return e.updateTopology(T.id,{status:f.kind==="failover"?"failed_over":"ready",activeRegion:R,regions:Y}),{activeRegion:R}},c=async(a,f,T,R)=>{e.updateTopology(T.id,{status:"destroying"}),n(a,f,"traffic:drain"),await i(T,Object.fromEntries(T.regions.map((W)=>[W.region,0])));let D=R.deleteData!==!0;for(let W of e.targets(T.id).sort((Y,ee)=>Number(Y.role==="primary")-Number(ee.role==="primary")))n(a,f,`delete:${W.region}`),e.updateTarget(W.id,{status:"deleting"}),await r(W).deleteStack({target:W,retainData:D,signal:a.signal}),e.updateTarget(W.id,{status:"deleted"});return n(a,f,"complete"),e.updateTopology(T.id,{status:"destroyed"}),{destroyed:!0,dataRetained:D}},u=async(a)=>{let f=gC(a.operation.input),T=e.execution(String(f.executionId??""));if(!T)throw Error("Regional execution was not found.");let R=e.get(T.topologyId);if(!R)throw Error("Regional topology was not found.");try{let D;if(T.kind==="rollout")D=await o(a,T,R,f);else if(T.kind==="failover"||T.kind==="failback")D=await s(a,T,R);else if(T.kind==="destroy")D=await c(a,T,R,f);else throw Error("Regional reconciliation is not configured.");return e.updateExecution(T.id,{status:"succeeded",currentStep:void 0}),{executionId:T.id,...D}}catch(D){if(e.updateExecution(T.id,{status:a.cancellationRequested()?"cancelled":"failed",error:D instanceof Error?D.message:String(D)}),e.get(R.id)?.status!=="destroyed")e.updateTopology(R.id,{status:"failed"});throw D}};return{"region.rollout":u,"region.failover":u,"region.failback":u,"region.destroy":u,"region.reconcile":u}}class Cl{provider;reason;constructor(e,t="Configure a regional provider transport before executing this operation."){this.provider=e;this.reason=t}fail(){throw Error(this.reason)}async applyStack(){return this.fail()}async deleteStack(){this.fail()}async health(){return this.fail()}async configureReplication(){return this.fail()}async verifyReplication(){return this.fail()}async applyTraffic(){return this.fail()}}function Mi(e,t,r){return[e,t,r].map((n)=>encodeURIComponent(n)).join(":")}function mC(e){return Object.fromEntries(["start","stop","restart","redeploy","scale","logs","exec","inspect","files"].map((t)=>[t,{supported:!1,reason:e}]))}function is(e,t,r=["exec","files"]){let n=mC(t);for(let i of e)n[i]={supported:!0,requiresConfirmation:!["logs","inspect"].includes(i),requiresRecentAuth:r.includes(i)};return n}var fC=/(?:secret|password|passwd|token|api[_-]?key|private[_-]?key|credential|authorization|cookie)/i;function so(e){let t=String(e??"").trim().toLowerCase();if(["active","running","ready","healthy","available","steady","active:running"].includes(t))return"running";if(["activating","pending","provisioning","starting","created","initializing"].includes(t))return"starting";if(["deactivating","stopping","draining","terminating"].includes(t))return"stopping";if(["inactive","stopped","complete","completed","exited","disabled"].includes(t))return"stopped";if(["degraded","unhealthy","warning"].includes(t))return"degraded";if(["failed","dead","error","crashed","oomkilled"].includes(t))return"failed";return"unknown"}function no(e){if(Array.isArray(e))return e.map((r)=>no(r));if(!e||typeof e!=="object")return e;let t={};for(let[r,n]of Object.entries(e))t[r]=fC.test(r)?"[REDACTED]":no(n);return t}function os(e,t=new Date){if(!e)return;let r=new Date(e).getTime();return Number.isFinite(r)?Math.max(0,Math.floor((t.getTime()-r)/1000)):void 0}function dh(e){let t=Number(e);return Number.isFinite(t)&&t>=0?t:void 0}function hC(e){let t=String(e?.message??e);if(/(?:unauthorized|accessdenied|forbidden|credentials)/i.test(t))return"unauthorized";if(/(?:timeout|unreachable|econnrefused|enotfound|network)/i.test(t))return"unreachable";return"error"}async function uh(e,t={},r={}){let n=t.now??new Date,i=Math.max(100,r.timeoutMs??1e4),o=Math.max(1,r.staleAfterSeconds??60),s=await Promise.all(e.map(async(u)=>{try{let a=await Promise.race([u.discover({...t,now:n}),new Promise((f,T)=>setTimeout(()=>T(Error(`Runtime source ${u.id} timed out after ${i}ms`)),i))]);return{workloads:a,source:{id:u.id,provider:u.provider,status:"fresh",discoveredAt:n.toISOString(),staleAfterSeconds:o,itemCount:a.length}}}catch(a){return{workloads:[],source:{id:u.id,provider:u.provider,status:hC(a),discoveredAt:n.toISOString(),staleAfterSeconds:o,itemCount:0,message:String(a?.message??a).slice(0,500)}}}})),c=s.map((u)=>u.source);return{generatedAt:n.toISOString(),workloads:s.flatMap((u)=>u.workloads).sort((u,a)=>u.name.localeCompare(a.name)||u.id.localeCompare(a.id)),sources:c,degraded:c.some((u)=>u.status!=="fresh")}}function yC(e,t){if(!t)return e;return e.startsWith(t)?e.slice(t.length):e}function lh(e,t,r){let n=yC(e,t);return`${r??""}${n}`}function ph(e,t,r){if(r&&r.some((n)=>e.startsWith(n)))return!1;if(t&&t.length>0)return t.some((n)=>e.startsWith(n));return!0}async function bC(e,t,r){let n=0,i=[],o=Math.max(1,Math.min(t,e.length||1));for(let s=0;s<o;s++)i.push((async()=>{while(!0){let c=n++;if(c>=e.length)return;await r(e[c],c)}})());await Promise.all(i)}function gh(e){if(e.client)return e.client;return mh({provider:e.provider,region:e.region,endpoint:e.endpoint,forcePathStyle:e.forcePathStyle,credentials:e.credentials})}async function ts(e){let t=e.concurrency??8,r=gh(e.from),n=gh(e.to),i=await r.listAllObjects({bucket:e.from.bucket,prefix:e.from.prefix}),o={copied:0,skipped:0,excluded:0,bytesCopied:0,errors:[],excludedKeys:[],deleted:[]},s=[];for(let f of i){if(!ph(f.Key,e.include,e.exclude)){o.excluded++,o.excludedKeys.push(f.Key);continue}s.push({source:f,destKey:lh(f.Key,e.from.prefix,e.to.prefix)})}if(e.dryRun){o.plan=s.map(({source:R,destKey:D})=>({key:R.Key,destKey:D,size:R.Size}));let f=i.length,T=0;for(let R of i){T++;let D=!ph(R.Key,e.include,e.exclude);e.onProgress?.({key:R.Key,destKey:D?"":lh(R.Key,e.from.prefix,e.to.prefix),size:R.Size,action:D?"excluded":"planned",index:T,total:f})}return o}let c=s.length,u=0;await bC(s,t,async({source:f,destKey:T})=>{let R=++u;try{if(!e.force){let Y=await n.headObject(e.to.bucket,T);if(Y&&Y.ContentLength===f.Size){o.skipped++,e.onProgress?.({key:f.Key,destKey:T,size:f.Size,action:"skipped",index:R,total:c});return}}let{body:D,contentType:W}=await r.getObjectBytes(e.from.bucket,f.Key);await n.putObject({bucket:e.to.bucket,key:T,body:D,contentType:W}),o.copied++,o.bytesCopied+=D.byteLength,e.onProgress?.({key:f.Key,destKey:T,size:f.Size,action:"copied",index:R,total:c})}catch(D){o.errors.push({key:f.Key,message:D?.message??String(D)}),e.onProgress?.({key:f.Key,destKey:T,size:f.Size,action:"error",index:R,total:c})}});let a=new Set(s.map((f)=>f.destKey));if(e.deleteExtraneous){let T=(await n.listAllObjects({bucket:e.to.bucket,prefix:e.to.prefix})).filter((R)=>!a.has(R.Key)).map((R)=>R.Key);for(let R of T)try{await n.deleteObject(e.to.bucket,R),o.deleted.push(R)}catch(D){o.errors.push({key:R,message:`delete failed: ${D?.message??String(D)}`})}}if(e.verify){let f=await n.listAllObjects({bucket:e.to.bucket,prefix:e.to.prefix}),T=new Map(f.map((Y)=>[Y.Key,Y.Size])),R=[],D=[],W=0;for(let{source:Y,destKey:ee}of s){if(!T.has(ee)){R.push(ee);continue}let ne=T.get(ee);if(ne!==Y.Size){D.push({key:ee,expected:Y.Size,actual:ne});continue}W++}o.verification={ok:R.length===0&&D.length===0,matched:W,missing:R,sizeMismatches:D}}return o}var SC={aws:"us-east-1",backblaze:"us-west-004",hetzner:"fsn1"};function vC(e,t){switch(e){case"backblaze":return`s3.${t}.backblazeb2.com`;case"hetzner":return`${t}.your-objectstorage.com`;case"aws":default:return}}function In(...e){for(let t of e){let r=process.env[t];if(r)return r}return}function wC(e,t){if(t?.accessKeyId&&t.secretAccessKey)return t;let r,n;if(e==="backblaze")r=In("B2_APPLICATION_KEY_ID","B2_KEY_ID","S3_ACCESS_KEY_ID","AWS_ACCESS_KEY_ID"),n=In("B2_APPLICATION_KEY","B2_SECRET_KEY","S3_SECRET_ACCESS_KEY","AWS_SECRET_ACCESS_KEY");else if(e==="hetzner")r=In("HETZNER_S3_ACCESS_KEY","HETZNER_ACCESS_KEY","S3_ACCESS_KEY_ID","AWS_ACCESS_KEY_ID"),n=In("HETZNER_S3_SECRET_KEY","HETZNER_SECRET_KEY","S3_SECRET_ACCESS_KEY","AWS_SECRET_ACCESS_KEY");else r=In("S3_ACCESS_KEY_ID"),n=In("S3_SECRET_ACCESS_KEY");if(r&&n)return{accessKeyId:r,secretAccessKey:n,sessionToken:In("AWS_SESSION_TOKEN")};return}function IC(e={}){let t=e.provider||In("OBJECT_STORAGE_PROVIDER","STORAGE_PROVIDER")||"aws",r=e.region||(t==="backblaze"?In("B2_REGION"):void 0)||(t==="hetzner"?In("HETZNER_S3_REGION","HETZNER_REGION"):void 0)||In("S3_REGION","AWS_REGION","AWS_DEFAULT_REGION")||SC[t],n=e.endpoint||In("S3_ENDPOINT")||vC(t,r),i=e.forcePathStyle??In("S3_FORCE_PATH_STYLE")==="true",o=wC(t,e.credentials),s=(c)=>{let u=n||`s3.${r}.amazonaws.com`;return i?`https://${u}/${c}`:`https://${c}.${u}`};return{provider:t,region:r,endpoint:n,forcePathStyle:i,credentials:o,profile:e.profile,publicBaseUrl:s}}function mh(e={}){let t=IC(e),r={endpoint:t.endpoint,forcePathStyle:t.forcePathStyle,credentials:t.credentials};return new g(t.region,t.profile,r)}class Nt{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new p(void 0,{profile:t})}async describeServices(e){let t={cluster:e.cluster,services:e.services};return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DescribeServices","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async listServices(e,t={}){let r={cluster:e,...t};return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.ListServices","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)})}async listTasks(e,t,r={}){let n={cluster:e,...r};if(t)n.serviceName=t;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.ListTasks","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(n)})}async describeTasks(e,t){let r={cluster:e,tasks:t};return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DescribeTasks","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)})}async updateService(e){let t={cluster:e.cluster,service:e.service};if(e.forceNewDeployment!==void 0)t.forceNewDeployment=e.forceNewDeployment;if(e.desiredCount!==void 0)t.desiredCount=e.desiredCount;if(e.taskDefinition)t.taskDefinition=e.taskDefinition;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.UpdateService","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async createService(e){let t={cluster:e.cluster,serviceName:e.serviceName,taskDefinition:e.taskDefinition,desiredCount:e.desiredCount};if(e.launchType)t.launchType=e.launchType;if(e.networkConfiguration)t.networkConfiguration=e.networkConfiguration;if(e.loadBalancers)t.loadBalancers=e.loadBalancers;if(e.healthCheckGracePeriodSeconds!==void 0)t.healthCheckGracePeriodSeconds=e.healthCheckGracePeriodSeconds;if(e.deploymentConfiguration)t.deploymentConfiguration=e.deploymentConfiguration;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.CreateService","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async deleteService(e){let t={cluster:e.cluster,service:e.service};if(e.force!==void 0)t.force=e.force;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DeleteService","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async listClusters(e={}){return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.ListClusters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(e)})}async describeClusters(e){let t={clusters:e,include:["ATTACHMENTS","CONFIGURATIONS","SETTINGS","STATISTICS","TAGS"]};return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DescribeClusters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async stopTask(e){let t={cluster:e.cluster,task:e.task};if(e.reason)t.reason=e.reason;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.StopTask","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async runTask(e){let t={cluster:e.cluster,taskDefinition:e.taskDefinition};if(e.count!==void 0)t.count=e.count;if(e.launchType)t.launchType=e.launchType;if(e.networkConfiguration)t.networkConfiguration=e.networkConfiguration;if(e.overrides)t.overrides=e.overrides;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.RunTask","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async registerTaskDefinition(e){return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.RegisterTaskDefinition","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(e)})}async deregisterTaskDefinition(e){return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DeregisterTaskDefinition","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({taskDefinition:e})})}async describeTaskDefinition(e){return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DescribeTaskDefinition","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({taskDefinition:e,include:["TAGS"]})})}async listTaskDefinitionFamilies(e){let t={};if(e?.familyPrefix)t.familyPrefix=e.familyPrefix;if(e?.status)t.status=e.status;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.ListTaskDefinitionFamilies","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async waitForServiceStable(e,t,r=40,n=15000){for(let i=0;i<r;i++){let s=(await this.describeServices({cluster:e,services:[t]})).services?.[0];if(s){let c=s.deployments?.find((u)=>u.status==="PRIMARY");if(c&&c.runningCount===c.desiredCount&&s.deployments?.length===1)return!0}await new Promise((c)=>setTimeout(c,n))}return!1}async forceNewDeployment(e,t){return this.updateService({cluster:e,service:t,forceNewDeployment:!0})}async scaleService(e,t,r){return this.updateService({cluster:e,service:t,desiredCount:r})}}class de{client;region;constructor(e="us-east-1"){this.region=e,this.client=new p}buildFormBody(e){return Object.entries(e).filter(([,r])=>r!==void 0).map(([r,n])=>`${encodeURIComponent(r)}=${encodeURIComponent(n)}`).join("&")}async createTopic(e){let t={Action:"CreateTopic",Version:"2010-03-31",Name:e.Name};if(e.DisplayName)t["Attributes.entry.1.key"]="DisplayName",t["Attributes.entry.1.value"]=e.DisplayName;if(e.Tags)e.Tags.forEach((n,i)=>{t[`Tags.member.${i+1}.Key`]=n.Key,t[`Tags.member.${i+1}.Value`]=n.Value});if(e.Attributes){let n=e.DisplayName?2:1;Object.entries(e.Attributes).forEach(([i,o])=>{t[`Attributes.entry.${n}.key`]=i,t[`Attributes.entry.${n}.value`]=o,n++})}let r=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)});return{TopicArn:_(r,"CreateTopic")?.TopicArn}}async deleteTopic(e){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteTopic",Version:"2010-03-31",TopicArn:e})})}async listTopics(e){let t={Action:"ListTopics",Version:"2010-03-31"};if(e)t.NextToken=e;let r=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)}),n=r?.ListTopicsResponse?.ListTopicsResult||r?.ListTopicsResult,i=n?.Topics?.member;return{Topics:Array.isArray(i)?i:i?[i]:[],NextToken:n?.NextToken}}async getTopicAttributes(e){let t=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"GetTopicAttributes",Version:"2010-03-31",TopicArn:e})}),r=N(_(t,"GetTopicAttributes")?.Attributes?.entry),n={TopicArn:e};for(let i of r)n[i.key]=String(i.value);return n}async setTopicAttributes(e){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"SetTopicAttributes",Version:"2010-03-31",TopicArn:e.TopicArn,AttributeName:e.AttributeName,AttributeValue:e.AttributeValue})})}async subscribe(e){let t={Action:"Subscribe",Version:"2010-03-31",TopicArn:e.TopicArn,Protocol:e.Protocol,Endpoint:e.Endpoint};if(e.ReturnSubscriptionArn)t.ReturnSubscriptionArn="true";if(e.Attributes){let n=1;Object.entries(e.Attributes).forEach(([i,o])=>{t[`Attributes.entry.${n}.key`]=i,t[`Attributes.entry.${n}.value`]=o,n++})}let r=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)});return{SubscriptionArn:_(r,"Subscribe")?.SubscriptionArn}}async unsubscribe(e){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"Unsubscribe",Version:"2010-03-31",SubscriptionArn:e})})}async listSubscriptionsByTopic(e,t){let r={Action:"ListSubscriptionsByTopic",Version:"2010-03-31",TopicArn:e};if(t)r.NextToken=t;let n=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(r)}),i=_(n,"ListSubscriptionsByTopic");return{Subscriptions:N(i?.Subscriptions?.member),NextToken:i?.NextToken||void 0}}async publish(e){let t={Action:"Publish",Version:"2010-03-31",Message:e.Message};if(e.TopicArn)t.TopicArn=e.TopicArn;if(e.TargetArn)t.TargetArn=e.TargetArn;if(e.PhoneNumber)t.PhoneNumber=e.PhoneNumber;if(e.Subject)t.Subject=e.Subject;if(e.MessageStructure)t.MessageStructure=e.MessageStructure;if(e.MessageAttributes){let n=1;Object.entries(e.MessageAttributes).forEach(([i,o])=>{if(t[`MessageAttributes.entry.${n}.Name`]=i,t[`MessageAttributes.entry.${n}.Value.DataType`]=o.DataType,o.StringValue)t[`MessageAttributes.entry.${n}.Value.StringValue`]=o.StringValue;if(o.BinaryValue)t[`MessageAttributes.entry.${n}.Value.BinaryValue`]=o.BinaryValue;n++})}let r=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)});return{MessageId:_(r,"Publish")?.MessageId}}async publishSMS(e,t,r){let n={};if(r)n["AWS.SNS.SMS.SenderID"]={DataType:"String",StringValue:r};return this.publish({PhoneNumber:e,Message:t,MessageAttributes:Object.keys(n).length>0?n:void 0})}async subscribeEmail(e,t){return this.subscribe({TopicArn:e,Protocol:"email",Endpoint:t})}async subscribeLambda(e,t){return this.subscribe({TopicArn:e,Protocol:"lambda",Endpoint:t})}async subscribeSqs(e,t,r){let n={};if(r)n.RawMessageDelivery="true";return this.subscribe({TopicArn:e,Protocol:"sqs",Endpoint:t,Attributes:Object.keys(n).length>0?n:void 0})}async subscribeHttp(e,t,r){let n=t.startsWith("https")?"https":"http",i={};if(r)i.RawMessageDelivery="true";return this.subscribe({TopicArn:e,Protocol:n,Endpoint:t,Attributes:Object.keys(i).length>0?i:void 0})}async subscribeSms(e,t){return this.subscribe({TopicArn:e,Protocol:"sms",Endpoint:t})}async topicExists(e){try{return await this.getTopicAttributes(e),!0}catch(t){if(t.code==="NotFound"||t.statusCode===404)return!1;throw t}}async getSMSAttributes(){let e=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"GetSMSAttributes",Version:"2010-03-31"})}),t=N(_(e,"GetSMSAttributes")?.attributes?.entry),r={};for(let n of t)r[n.key]=String(n.value);return r}async setSMSAttributes(e){let t={Action:"SetSMSAttributes",Version:"2010-03-31"},r=1;Object.entries(e).forEach(([n,i])=>{if(i!==void 0)t[`attributes.entry.${r}.key`]=n,t[`attributes.entry.${r}.value`]=i,r++}),await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)})}async checkIfPhoneNumberIsOptedOut(e){let t=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"CheckIfPhoneNumberIsOptedOut",Version:"2010-03-31",phoneNumber:e})});return ea(_(t,"CheckIfPhoneNumberIsOptedOut")?.isOptedOut)}async listPhoneNumbersOptedOut(e){let t={Action:"ListPhoneNumbersOptedOut",Version:"2010-03-31"};if(e)t.nextToken=e;let r=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)}),n=_(r,"ListPhoneNumbersOptedOut");return{phoneNumbers:N(n?.phoneNumbers?.member).map(String),nextToken:n?.nextToken||void 0}}async optInPhoneNumber(e){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"OptInPhoneNumber",Version:"2010-03-31",phoneNumber:e})})}async listSMSSandboxPhoneNumbers(e){let t={Action:"ListSMSSandboxPhoneNumbers",Version:"2010-03-31"};if(e)t.NextToken=e;let r=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)}),n=_(r,"ListSMSSandboxPhoneNumbers");return{PhoneNumbers:N(n?.PhoneNumbers?.member),NextToken:n?.NextToken||void 0}}async createSMSSandboxPhoneNumber(e,t){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"CreateSMSSandboxPhoneNumber",Version:"2010-03-31",PhoneNumber:e,LanguageCode:t||"en-US"})})}async verifySMSSandboxPhoneNumber(e,t){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"VerifySMSSandboxPhoneNumber",Version:"2010-03-31",PhoneNumber:e,OneTimePassword:t})})}async deleteSMSSandboxPhoneNumber(e){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteSMSSandboxPhoneNumber",Version:"2010-03-31",PhoneNumber:e})})}async getSMSSandboxAccountStatus(){let e=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"GetSMSSandboxAccountStatus",Version:"2010-03-31"})});return{IsInSandbox:ea(_(e,"GetSMSSandboxAccountStatus")?.IsInSandbox)}}}class q{client;region;endpoint;constructor(e="us-east-1",t){this.region=e,this.endpoint=t?.endpoint,this.client=new p}async request(e,t){if(this.endpoint){let r=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-amz-json-1.0","X-Amz-Target":`DynamoDB_20120810.${e}`},body:JSON.stringify(t)});if(!r.ok){let n=await r.text();throw Error(`DynamoDB request failed: ${r.status} ${n}`)}return r.json()}return this.client.request({service:"dynamodb",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.0","X-Amz-Target":`DynamoDB_20120810.${e}`},body:JSON.stringify(t)})}async createTable(e){return this.request("CreateTable",e)}async deleteTable(e){return this.request("DeleteTable",e)}async describeTable(e){return this.request("DescribeTable",e)}async listTables(e){return this.request("ListTables",e||{})}async putItem(e){return this.request("PutItem",e)}async getItem(e){return this.request("GetItem",e)}async updateItem(e){return this.request("UpdateItem",e)}async deleteItem(e){return this.request("DeleteItem",e)}async query(e){return this.request("Query",e)}async scan(e){return this.request("Scan",e)}async batchWriteItem(e){return this.request("BatchWriteItem",e)}async batchGetItem(e){return this.request("BatchGetItem",e)}async updateTimeToLive(e){return this.request("UpdateTimeToLive",e)}static marshal(e){let t={};for(let[r,n]of Object.entries(e))t[r]=q.marshalValue(n);return t}static marshalValue(e){if(e===null||e===void 0)return{NULL:!0};if(typeof e==="string")return{S:e};if(typeof e==="number")return{N:String(e)};if(typeof e==="boolean")return{BOOL:e};if(Array.isArray(e))return{L:e.map((t)=>q.marshalValue(t))};if(typeof e==="object")return{M:q.marshal(e)};return{S:String(e)}}static unmarshal(e){let t={};for(let[r,n]of Object.entries(e))t[r]=q.unmarshalValue(n);return t}static unmarshalValue(e){if(e.S!==void 0)return e.S;if(e.N!==void 0)return Number(e.N);if(e.BOOL!==void 0)return e.BOOL;if(e.NULL!==void 0)return null;if(e.L!==void 0)return e.L.map((t)=>q.unmarshalValue(t));if(e.M!==void 0)return q.unmarshal(e.M);if(e.SS!==void 0)return e.SS;if(e.NS!==void 0)return e.NS.map(Number);return null}}var $_=(()=>{let e=new Uint32Array(256);for(let t=0;t<256;t++){let r=t;for(let n=0;n<8;n++)r=r&1?3988292384^r>>>1:r>>>1;e[t]=r>>>0}return e})();class be{client;region;constructor(e="us-east-1"){this.region=e,this.client=new p}async request(e,t){return this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`AWSEvents.${e}`},body:JSON.stringify(t)})}async putRule(e){return this.request("PutRule",e)}async deleteRule(e){return this.request("DeleteRule",e)}async describeRule(e){return this.request("DescribeRule",e)}async listRules(e){return this.request("ListRules",e||{})}async listEventBuses(e){return this.request("ListEventBuses",e||{})}async enableRule(e){return this.request("EnableRule",e)}async disableRule(e){return this.request("DisableRule",e)}async putTargets(e){return this.request("PutTargets",e)}async removeTargets(e){return this.request("RemoveTargets",e)}async listTargetsByRule(e){return this.request("ListTargetsByRule",e)}async putEvents(e){return this.request("PutEvents",e)}async createSchedule(e){return this.client.request({service:"scheduler",region:this.region,method:"POST",path:`/schedules/${e.Name}`,headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}}class $e{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new p}async createRule(e){let t={Action:"PutRule",Name:e.name,ScheduleExpression:e.scheduleExpression,Version:"2015-10-07"};if(e.description)t.Description=e.description;if(e.state)t.State=e.state;else t.State="ENABLED";return{RuleArn:(await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.PutRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:e.name,ScheduleExpression:e.scheduleExpression,State:e.state||"ENABLED",Description:e.description})})).RuleArn}}async putTargets(e,t){await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.PutTargets","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Rule:e,Targets:t})})}async listRules(e){let t={};if(e)t.NamePrefix=e;return{Rules:(await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.ListRules","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})).Rules||[]}}async describeRule(e){let t=await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.DescribeRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:e})});return{Name:t.Name,Arn:t.Arn,ScheduleExpression:t.ScheduleExpression,State:t.State,Description:t.Description}}async listTargetsByRule(e){return{Targets:(await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.ListTargetsByRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Rule:e})})).Targets||[]}}async deleteRule(e,t){if(t)try{let r=await this.listTargetsByRule(e);if(r.Targets&&r.Targets.length>0)await this.removeTargets(e,r.Targets.map((n)=>n.Id))}catch{}await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.DeleteRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:e,Force:t||!1})})}async removeTargets(e,t){await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.RemoveTargets","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Rule:e,Ids:t})})}async enableRule(e){await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.EnableRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:e})})}async disableRule(e){await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.DisableRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:e})})}async createLambdaSchedule(e){let t=await this.createRule({name:e.name,scheduleExpression:e.scheduleExpression,description:e.description,state:"ENABLED"});return await this.putTargets(e.name,[{Id:"1",Arn:e.functionArn,Input:e.input}]),t}async createEcsSchedule(e){let t=await this.createRule({name:e.name,scheduleExpression:e.scheduleExpression,description:e.description,state:"ENABLED"});return await this.putTargets(e.name,[{Id:"1",Arn:e.clusterArn,RoleArn:e.roleArn,Input:JSON.stringify({containerOverrides:[]})}]),t}async listSchedules(e){let t={};if(e?.NamePrefix)t.NamePrefix=e.NamePrefix;if(e?.State)t.State=e.State;let r=e?.GroupName||"default";return{Schedules:(await this.client.request({service:"scheduler",region:this.region,method:"GET",path:"/schedules",queryParams:{...t,ScheduleGroup:r}}))?.Schedules||[]}}async getSchedule(e){try{let t={};if(e.GroupName)t.groupName=e.GroupName;return await this.client.request({service:"scheduler",region:this.region,method:"GET",path:`/schedules/${encodeURIComponent(e.Name)}`,queryParams:Object.keys(t).length>0?t:void 0})}catch(t){if(t.statusCode===404||t.code==="ResourceNotFoundException")return null;throw t}}async createSchedule(e){let t={ScheduleExpression:e.ScheduleExpression,FlexibleTimeWindow:e.FlexibleTimeWindow,Target:e.Target};if(e.GroupName)t.GroupName=e.GroupName;if(e.ScheduleExpressionTimezone)t.ScheduleExpressionTimezone=e.ScheduleExpressionTimezone;if(e.Description)t.Description=e.Description;if(e.State)t.State=e.State;if(e.StartDate)t.StartDate=e.StartDate.toISOString();if(e.EndDate)t.EndDate=e.EndDate.toISOString();return{ScheduleArn:(await this.client.request({service:"scheduler",region:this.region,method:"POST",path:`/schedules/${encodeURIComponent(e.Name)}`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}))?.ScheduleArn||""}}async updateSchedule(e){let t={};if(e.GroupName)t.GroupName=e.GroupName;if(e.ScheduleExpression)t.ScheduleExpression=e.ScheduleExpression;if(e.ScheduleExpressionTimezone)t.ScheduleExpressionTimezone=e.ScheduleExpressionTimezone;if(e.Description!==void 0)t.Description=e.Description;if(e.State)t.State=e.State;if(e.FlexibleTimeWindow)t.FlexibleTimeWindow=e.FlexibleTimeWindow;if(e.Target)t.Target=e.Target;return{ScheduleArn:(await this.client.request({service:"scheduler",region:this.region,method:"PUT",path:`/schedules/${encodeURIComponent(e.Name)}`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}))?.ScheduleArn||""}}async deleteSchedule(e){let t={};if(e.GroupName)t.groupName=e.GroupName;await this.client.request({service:"scheduler",region:this.region,method:"DELETE",path:`/schedules/${encodeURIComponent(e.Name)}`,queryParams:Object.keys(t).length>0?t:void 0})}async listScheduleGroups(e){let t={};if(e?.NamePrefix)t.NamePrefix=e.NamePrefix;return{ScheduleGroups:(await this.client.request({service:"scheduler",region:this.region,method:"GET",path:"/schedule-groups",queryParams:Object.keys(t).length>0?t:void 0}))?.ScheduleGroups||[]}}}function Qs(e){return e?.split("/").at(-1)??e?.split(":").at(-1)??"unknown"}function fh(e,t,r,n="ecs:aws",i=[]){let o=r.now??new Date;return e.map((s)=>{let c=s.serviceName??Qs(s.serviceArn),u=t.filter((ne)=>!s.clusterArn||ne.clusterArn===s.clusterArn),a=u.some((ne)=>!!ne.group)?u.filter((ne)=>ne.group===`service:${c}`):u,f=s.status==="ACTIVE"?(s.runningCount??0)<(s.desiredCount??0)?"degraded":"running":so(s.status),T=i.find((ne)=>ne.taskDefinitionArn===s.taskDefinition),R=Array.isArray(T?.containerDefinitions)?T.containerDefinitions:[],D=[...new Set(R.map((ne)=>ne.logConfiguration?.options?.["awslogs-group"]).filter((ne)=>typeof ne==="string"))],W=R.flatMap((ne)=>(ne.mountPoints??[]).map((he)=>({source:he.sourceVolume,target:he.containerPath,type:"volume",readOnly:!!he.readOnly}))),Y=R.flatMap((ne)=>(ne.portMappings??[]).map((he,te)=>({id:`${ne.name??"container"}:${te}`,name:ne.name,mode:T?.networkMode,ports:[{container:he.containerPort,host:he.hostPort,protocol:he.protocol}]}))),ee=r.project&&r.environment&&c.startsWith(`${r.project}-${r.environment}-`)?c.slice(`${r.project}-${r.environment}-`.length):c;return{id:Mi("ecs",n,s.serviceArn??c),provider:"ecs",kind:"service",name:c,status:f,rawStatus:s.status,health:f==="running"?"healthy":f==="failed"||f==="degraded"?"unhealthy":"unknown",desiredReplicas:s.desiredCount,runningReplicas:s.runningCount,image:R[0]?.image,runtime:s.launchType??"ECS",version:Qs(s.taskDefinition),ageSeconds:os(s.deployments?.[0]?.createdAt,o),restartCount:0,tags:{},links:{project:r.project,environment:r.environment,service:ee,release:Qs(s.taskDefinition),providerId:s.serviceArn},replicas:a.map((ne)=>{let he=so(ne.lastStatus);return{id:Mi("ecs",n,ne.taskArn??Qs(ne.taskArn)),name:Qs(ne.taskArn),status:he,rawStatus:ne.lastStatus,createdAt:ne.createdAt,startedAt:ne.startedAt,stoppedAt:ne.stoppedAt,host:ne.containerInstanceArn,containers:(ne.containers??[]).map((te)=>({id:te.containerArn??te.name??"container",name:te.name??"container",image:R.find((De)=>De.name===te.name)?.image,imageDigest:te.imageDigest,status:so(te.lastStatus),rawStatus:te.lastStatus,exitCode:te.exitCode,reason:te.reason,runtime:"ecs"}))}}),networks:Y,mounts:W,capabilities:is(["start","stop","restart","redeploy","scale","inspect",...D.length?["logs"]:[]],"This ECS runtime does not expose exec or file transfer; logs require an awslogs task-definition driver"),config:no({clusterArn:s.clusterArn,taskDefinition:s.taskDefinition,launchType:s.launchType,pendingCount:s.pendingCount,deployments:s.deployments,logGroups:D,executionRoleArn:T?.executionRoleArn,taskRoleArn:T?.taskRoleArn,cpu:T?.cpu,memory:T?.memory}),discoveredAt:o.toISOString(),sourceId:n}})}function hh(e,t,r="lambda:aws"){let n=t.now??new Date;return e.map((i)=>{let o=i.FunctionName??Qs(i.FunctionArn),s=i.State==="Active"?"running":so(i.State);return{id:Mi("lambda",r,i.FunctionArn??o),provider:"lambda",kind:"function",name:o,status:s,rawStatus:i.State,health:s==="running"?"healthy":s==="failed"?"unhealthy":"unknown",desiredReplicas:void 0,runningReplicas:void 0,image:void 0,runtime:i.Runtime,version:i.Version,architecture:i.Architectures?.join(", "),ageSeconds:os(i.LastModified,n),restartCount:0,tags:{},links:{project:t.project,environment:t.environment,service:o,providerId:i.FunctionArn},resources:{memoryLimitBytes:i.MemorySize==null?void 0:i.MemorySize*1024*1024},replicas:[],networks:[],mounts:[],capabilities:is(["logs","inspect"],"Lambda has no persistent process to start, stop, restart, exec, or browse files; deploy a release to replace code"),config:no({handler:i.Handler,timeout:i.Timeout,codeSize:i.CodeSize,stateReason:i.StateReason,environmentKeys:Object.keys(i.Environment?.Variables??{})}),discoveredAt:n.toISOString(),sourceId:r}})}function CC(e){let t=e.trim();if(!t)return[];let r=JSON.parse(t);if(!Array.isArray(r))throw Error("Docker inspect output must be an array");return r.filter((n)=>n&&typeof n.Id==="string")}function EC(e){let t=Object.entries(e.NetworkSettings?.Ports??{}).flatMap(([r,n])=>{let[i,o]=r.split("/");return(n??[]).map((s)=>({container:Number(i)||void 0,host:Number(s.HostPort)||void 0,protocol:o,address:s.HostIp}))});return Object.entries(e.NetworkSettings?.Networks??{}).map(([r,n])=>({id:n.NetworkID||r,name:r,mode:e.HostConfig?.NetworkMode,addresses:[n.IPAddress,n.GlobalIPv6Address].filter(Boolean),ports:t}))}function TC(e){return(e.Mounts??[]).filter((t)=>!!t.Destination).map((t)=>({source:t.Source,target:t.Destination,type:t.Type,readOnly:t.RW===!1}))}function AC(e,t,r=t.server??"local"){let n=t.now??new Date;return e.map((i)=>{let o=i.State?.OOMKilled?"oomkilled":i.State?.Restarting?"starting":i.State?.Status,s=so(o),c=(i.Name??i.Id.slice(0,12)).replace(/^\//,""),u=i.Config?.Labels??{},a=TC(i),f=EC(i),T={id:i.Id,name:c,image:i.Config?.Image,imageDigest:i.Image,runtime:"docker",status:s,rawStatus:o,exitCode:i.State?.ExitCode,reason:i.State?.Error,resources:{memoryLimitBytes:i.HostConfig?.Memory||void 0},networks:f,mounts:a};return{id:Mi("docker",r,i.Id),provider:"docker",kind:"container",name:c,status:s,rawStatus:o,health:s==="running"?"healthy":s==="failed"?"unhealthy":"unknown",desiredReplicas:1,runningReplicas:s==="running"?1:0,image:i.Config?.Image,runtime:"docker",ageSeconds:os(i.State?.StartedAt,n),restartCount:i.RestartCount??0,tags:u,links:{project:t.project,environment:t.environment,server:t.server??r.replace(/^docker:/,""),service:u["com.docker.compose.service"]??u["ts-cloud.service"]??c,release:u["ts-cloud.release"],providerId:i.Id},resources:T.resources,replicas:[{id:Mi("docker",r,`${i.Id}:0`),name:c,status:s,rawStatus:o,startedAt:i.State?.StartedAt,stoppedAt:i.State?.FinishedAt,restartCount:i.RestartCount,containers:[T],resources:T.resources}],networks:f,mounts:a,capabilities:is(["start","stop","restart","logs","exec","inspect","files"],"Use the owning Compose service for redeploy and scale"),config:no({image:i.Config?.Image,labels:u,environmentKeys:(i.Config?.Env??[]).map((R)=>R.split("=",1)[0]),networkMode:i.HostConfig?.NetworkMode}),discoveredAt:n.toISOString(),sourceId:r}})}class El{inspect;id;provider="docker";constructor(e,t="docker:local"){this.inspect=e;this.id=t}async discover(e){return AC(CC(await this.inspect(e)),e,this.id)}}function kC(e){let t=[];for(let r of e.split(`
120
+ `)){if(!r.startsWith("TSCLOUD_SYSTEMD\t"))continue;let[,n,i,o,s,c,u,a,f,T,R,D,W,Y]=r.split("\t");if(!n||!/^[A-Za-z0-9_.@:-]+\.service$/.test(n))continue;t.push({unit:n,load:i,active:o,sub:s,description:c,enabled:u,pid:Number(a)||void 0,memoryBytes:dh(f),restartCount:Number(T)||0,activeSince:R||void 0,fragmentPath:D||void 0,workingDirectory:W?.startsWith("/")?W:void 0,user:Y||void 0})}return t}function RC(e,t,r=t.server??"local"){let n=t.now??new Date;return e.map((i)=>{let o=so(i.active==="active"?i.sub||i.active:i.active),s=i.unit.replace(/\.service$/,""),c=/^(.*?) (?:release [^ ]+|queue worker|daemon |scheduler)(?: |$)/.exec(i.description??"")?.[1]??(t.project&&s.startsWith(`${t.project}-`)?s.slice(t.project.length+1).split("@",1)[0]:void 0),u=s.includes("@")?s.slice(s.indexOf("@")+1):void 0,a=i.workingDirectory?[{target:i.workingDirectory,type:"working-directory"}]:[],f=["start","stop","restart","logs","exec","inspect",...a.length?["files"]:[]];return{id:Mi("systemd",r,i.unit),provider:"systemd",kind:"service",name:s,displayName:i.description||s,status:o,rawStatus:[i.load,i.active,i.sub].filter(Boolean).join("/"),health:o==="running"?"healthy":o==="failed"?"unhealthy":"unknown",desiredReplicas:1,runningReplicas:o==="running"?1:0,ageSeconds:os(i.activeSince,n),restartCount:i.restartCount,tags:{enabled:i.enabled??"unknown"},links:{project:t.project,environment:t.environment,server:t.server??r.replace(/^systemd:/,""),service:c,release:u,providerId:i.unit},resources:{memoryBytes:i.memoryBytes},replicas:[{id:Mi("systemd",r,`${i.unit}:main`),name:"main",status:o,pid:i.pid,startedAt:i.activeSince,restartCount:i.restartCount,resources:{memoryBytes:i.memoryBytes}}],networks:[],mounts:a,capabilities:is(f,a.length?"This systemd runtime does not support redeploy or replica scaling through the scoped explorer":"File transfer requires a provider-reported service working directory; redeploy and scaling are unavailable"),config:no({fragmentPath:i.fragmentPath,workingDirectory:i.workingDirectory,user:i.user,environment:i.environment,enabled:i.enabled}),discoveredAt:n.toISOString(),sourceId:r}})}class Tl{read;id;provider="systemd";constructor(e,t="systemd:local"){this.read=e;this.id=t}async discover(e){return RC(kC(await this.read(e)),e,this.id)}}function PC(e,t){if(!e.success)throw Error(e.error||e.perInstance?.[0]?.error||`${t} discovery failed`);return e.perInstance?.[0]?.output??""}function xC(){return["set -uo pipefail",'command -v systemctl >/dev/null 2>&1 || { echo "systemctl is unavailable" >&2; exit 127; }',"systemctl list-units --type=service --all --plain --no-legend 2>/dev/null | awk '{print $1}' | while IFS= read -r unit; do",' [ -n "$unit" ] || continue',' clean() { printf "%s" "$1" | tr "\\t\\r\\n" " "; }',' load=$(systemctl show "$unit" -p LoadState --value 2>/dev/null || true)',' active=$(systemctl show "$unit" -p ActiveState --value 2>/dev/null || true)',' sub=$(systemctl show "$unit" -p SubState --value 2>/dev/null || true)',' description=$(systemctl show "$unit" -p Description --value 2>/dev/null || true)',' enabled=$(systemctl is-enabled "$unit" 2>/dev/null || true)',' pid=$(systemctl show "$unit" -p MainPID --value 2>/dev/null || true)',' memory=$(systemctl show "$unit" -p MemoryCurrent --value 2>/dev/null || true)',' restarts=$(systemctl show "$unit" -p NRestarts --value 2>/dev/null || true)',' since=$(systemctl show "$unit" -p ActiveEnterTimestamp --value 2>/dev/null || true)',' fragment=$(systemctl show "$unit" -p FragmentPath --value 2>/dev/null || true)',' working=$(systemctl show "$unit" -p WorkingDirectory --value 2>/dev/null || true)',' user=$(systemctl show "$unit" -p User --value 2>/dev/null || true)',' printf "TSCLOUD_SYSTEMD\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n" "$(clean "$unit")" "$(clean "$load")" "$(clean "$active")" "$(clean "$sub")" "$(clean "$description")" "$(clean "$enabled")" "$(clean "$pid")" "$(clean "$memory")" "$(clean "$restarts")" "$(clean "$since")" "$(clean "$fragment")" "$(clean "$working")" "$(clean "$user")"',"done"]}function DC(){return["set -uo pipefail",'if ! command -v docker >/dev/null 2>&1; then echo "[]"; exit 0; fi',"ids=$(docker ps -aq)",'if [ -z "$ids" ]; then echo "[]"; else docker inspect $ids; fi']}function yh(e,t,r,n,i){let o=`${e}:${r.id}`,s=async()=>PC(await t.runRemoteDeploy({targets:[r],commands:e==="systemd"?xC():DC(),timeoutSeconds:30,comment:`ts-cloud runtime discovery:${e}`,tags:{Project:n.project.slug,Environment:i,Role:"app"}}),o);return e==="systemd"?new Tl(s,o):new El(s,o)}async function od(e,t=100){let r=[],n;for(let i=0;i<t;i++){let o=await e(n);if(r.push(...o.items),!o.nextToken)return r;n=o.nextToken}throw Error(`Provider pagination exceeded ${t} pages`)}class bh{client;prefix;id="ecs:aws";provider="ecs";constructor(e,t){this.client=e;this.prefix=t}async discover(e){let t=await od(async(o)=>{let s=await this.client.listClusters({nextToken:o,maxResults:100});return{items:s.clusterArns??[],nextToken:s.nextToken}}),r=[],n=[],i=[];for(let o of t){let s=(await od(async(c)=>{let u=await this.client.listServices(o,{nextToken:c,maxResults:100});return{items:u.serviceArns??[],nextToken:u.nextToken}})).filter((c)=>c.split("/").at(-1)?.startsWith(this.prefix));for(let c=0;c<s.length;c+=10){let u=await this.client.describeServices({cluster:o,services:s.slice(c,c+10)});r.push(...u.services??[])}for(let c of r.filter((u)=>u.clusterArn===o||!u.clusterArn)){let u=await od(async(a)=>{let f=await this.client.listTasks(o,c.serviceName,{nextToken:a,maxResults:100});return{items:f.taskArns??[],nextToken:f.nextToken}});for(let a=0;a<u.length;a+=100){let f=await this.client.describeTasks(o,u.slice(a,a+100));n.push(...f.tasks??[])}}}if(this.client.describeTaskDefinition)for(let o of[...new Set(r.map((s)=>s.taskDefinition).filter((s)=>!!s))]){let s=await this.client.describeTaskDefinition(o);if(s.taskDefinition)i.push(s.taskDefinition)}return fh(r,n,e,this.id,i)}}class Sh{client;prefix;id="lambda:aws";provider="lambda";constructor(e,t){this.client=e;this.prefix=t}async discover(e){let t=(await od(async(r)=>{let n=await this.client.listFunctions({Marker:r,MaxItems:50});return{items:n.Functions??[],nextToken:n.NextMarker}})).filter((r)=>r.FunctionName?.startsWith(this.prefix));return hh(t,e,this.id)}}async function OC(e,t,r={}){let n=[],i=H(e),o=B(e),s=e.aws?.profile,c=e.aws?.region??e.project.region??"us-east-1",u=`${e.project.slug}-${t}`;if(i!=="serverless"){let a=r.driver??O({config:e}),f=await a.findComputeTargets({slug:e.project.slug,environment:t,role:"app"});for(let T of f)n.push(yh("systemd",a,T,e,t)),n.push(yh("docker",a,T,e,t))}if(o==="aws")n.push(new bh(r.ecs??new Nt(c,s),u)),n.push(new Sh(r.lambda??new I(c,s),u));return n}async function Ii(e,t,r={}){let n={project:e.project.slug,environment:t};try{return await uh(await OC(e,t,r),n)}catch(i){return{generatedAt:new Date().toISOString(),workloads:[],sources:[{id:"runtime:bootstrap",provider:B(e)==="aws"?"ecs":"systemd",status:"error",discoveredAt:new Date().toISOString(),staleAfterSeconds:60,itemCount:0,message:String(i?.message??i).slice(0,500)}],degraded:!0}}}var vh=65536,xa=49152,ad=/^[A-Za-z0-9_.@:-]+\.service$/,cd=/^[a-fA-F0-9]{12,128}$/,_C=["/boot","/dev","/etc","/proc","/root","/run","/sys","/var/run"];function Ys(e){let t=Buffer.from(e);return t.byteLength<=vh?e:`${t.subarray(0,vh-24).toString("utf8")}
121
121
  [output truncated]`}function sd(e){return{success:!1,instanceCount:0,perInstance:[],error:e instanceof Error?e.message:String(e)}}function ci(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function NC(e,t){return Number.isFinite(e)?Math.min(1e4,Math.max(0,Math.floor(e))):t}function MC(e){let t=e.config,r=typeof t.clusterArn==="string"?t.clusterArn:void 0,n=e.links.providerId||e.name;return r&&n?{cluster:r,service:n}:void 0}function $C(e,t){return e.find((r)=>r.id===t.links.server)??(e.length===1?e[0]:void 0)}function LC(e,t){if(e.provider==="systemd"){let r=e.links.providerId;if(!r||!ad.test(r)||!["start","stop","restart"].includes(t))return;return[`systemctl ${t} ${r}`,`systemctl is-active ${r} 2>/dev/null || true`]}if(e.provider==="docker"){let r=e.links.providerId;if(!r||!cd.test(r)||!["start","stop","restart"].includes(t))return;return[`docker ${t} ${r}`,`docker inspect --format '{{.State.Status}}' ${r}`]}return}function BC(e,t){if(!t.startsWith("/")||t.includes("\x00"))return{ok:!1,error:"An absolute path is required."};let r=[];for(let c of t.split("/")){if(!c||c===".")continue;if(c===".."){if(!r.length)return{ok:!1,error:"Path traversal is not allowed."};r.pop()}else r.push(c)}let n=`/${r.join("/")}`;if(_C.some((c)=>n===c||n.startsWith(`${c}/`)))return{ok:!1,error:"Sensitive host paths are not available through runtime file access."};let i=e.links.project?.replace(/[^A-Za-z0-9_-]/g,""),o=e.links.service?.replace(/[^A-Za-z0-9_-]/g,"");if(![...i&&o?[`/var/www/${i}/${o}`,`/srv/${i}/${o}`]:[],...e.mounts.map((c)=>c.target).filter((c)=>c.startsWith("/"))].some((c)=>n===c||n.startsWith(`${c.replace(/\/$/,"")}/`)))return{ok:!1,error:"Path is outside this service’s owned roots."};return{ok:!0,path:n}}function FC(e,t){let r=e.links.project?.replace(/[^A-Za-z0-9_-]/g,""),n=e.links.service?.replace(/[^A-Za-z0-9_-]/g,"");return[...r&&n?[`/var/www/${r}/${n}`,`/srv/${r}/${n}`]:[],...e.mounts.map((i)=>i.target).filter((i)=>i.startsWith("/"))].sort((i,o)=>o.length-i.length).find((i)=>t===i||t.startsWith(`${i.replace(/\/$/,"")}/`))}var wh={process:["ps","-eo","pid,ppid,user,%cpu,%mem,etime,command","--sort=-%cpu"],sockets:["ss","-lntup"],filesystem:["df","-h"]};class Se{config;environment;dependencies;region;profile;constructor(e,t,r={}){this.config=e;this.environment=t;this.dependencies=r;this.region=e.aws?.region??e.project.region??"us-east-1",this.profile=e.aws?.profile}async inventory(){return this.dependencies.inventory?.()??Ii(this.config,this.environment,{driver:this.dependencies.driver})}async workload(e){return(await this.inventory()).workloads.find((t)=>t.id===e)}async remote(e,t,r,n){let i=this.dependencies.driver??O({config:this.config}),o=await i.findComputeTargets({slug:this.config.project.slug,environment:this.environment,role:"app"}),s=$C(o,e);if(!s)throw Error("The workload server is no longer reachable in this scope.");return i.runRemoteDeploy({targets:[s],commands:t,timeoutSeconds:r,comment:n,tags:{Project:this.config.project.slug,Environment:this.environment,Role:"app"}})}async run(e){let t=await this.workload(e.workloadId),r={workloadId:e.workloadId,action:e.action};if(!t)return{...r,ok:!1,error:"Workload was not found in the current project and environment."};let n=t.capabilities[e.action];if(!n.supported)return{...r,ok:!1,error:n.reason??`${e.action} is unsupported for ${t.provider}.`};if(n.requiresConfirmation&&e.confirm!==t.name)return{...r,ok:!1,error:`Type "${t.name}" to ${e.action} this workload.`};if(n.requiresRecentAuth&&!e.recentAuth)return{...r,ok:!1,error:"Sign in again before using elevated runtime access."};if(e.action==="inspect")return{...r,ok:!0,workload:t};if(t.provider==="systemd"||t.provider==="docker"){let i=LC(t,e.action);if(!i)return{...r,ok:!1,error:`${e.action} is not implemented for ${t.provider}.`};let o=await this.remote(t,["set -uo pipefail",...i],60,`ts-cloud runtime:${e.action}`).catch(sd);return{...r,ok:o.success,command:i[0],stdout:Ys(o.perInstance?.[0]?.output??""),stderr:Ys(o.perInstance?.[0]?.error??o.error??""),error:o.success?void 0:o.error??"Runtime operation failed."}}if(t.provider==="ecs"){let i=MC(t);if(!i)return{...r,ok:!1,error:"ECS cluster or service identity is unavailable."};let o=this.dependencies.ecs??new Nt(this.region,this.profile);if(e.action==="scale"){let s=NC(e.replicas,t.desiredReplicas??1);return await o.scaleService(i.cluster,i.service,s),{...r,ok:!0,command:`ecs scale ${t.name} ${s}`}}if(e.action==="start"||e.action==="stop"){let s=e.action==="stop"?0:Math.max(1,t.desiredReplicas??1);return await o.scaleService(i.cluster,i.service,s),{...r,ok:!0,command:`ecs scale ${t.name} ${s}`}}if(e.action==="restart"||e.action==="redeploy")return await o.forceNewDeployment(i.cluster,i.service),{...r,ok:!0,command:`ecs redeploy ${t.name}`}}return{...r,ok:!1,error:`${e.action} is not implemented for ${t.provider}.`}}async exec(e){let t={workloadId:e.workloadId,preset:e.preset},r=await this.workload(e.workloadId);if(!r)return{...t,ok:!1,error:"Workload was not found in the current project and environment."};if(process.env.TS_CLOUD_RUNTIME_EXEC==="0")return{...t,ok:!1,error:"Runtime exec is disabled by TS_CLOUD_RUNTIME_EXEC."};if(!r.capabilities.exec.supported)return{...t,ok:!1,error:r.capabilities.exec.reason??"Exec is unsupported for this workload."};if(e.confirm!==r.name)return{...t,ok:!1,error:`Type "${r.name}" to open exec access.`};if(!e.recentAuth)return{...t,ok:!1,error:"Sign in again before using elevated runtime access."};let n=e.preset&&wh[e.preset];if(!n&&!e.command?.trim())return{...t,ok:!1,error:"Choose a diagnostic preset or provide a command."};if(e.command&&r.provider!=="docker")return{...t,ok:!1,error:"Free-form exec is restricted to isolated containers; use a diagnostic preset for system services."};let i=r.links.providerId??"",o;if(r.provider==="docker"&&cd.test(i)){let c=e.command?.trim()||n.map(ci).join(" ");o=`docker exec ${i} sh -lc ${ci(c)}`}else if(r.provider==="systemd"&&ad.test(i)&&e.preset)o=e.preset==="process"?`systemctl status ${i} --no-pager --full`:wh[e.preset].map(ci).join(" ");if(!o)return{...t,ok:!1,error:"Exec target identity is invalid or unsupported."};let s=await this.remote(r,["set -uo pipefail",o],60,"ts-cloud runtime:exec").catch(sd);return{...t,ok:s.success,command:o,stdout:Ys(s.perInstance?.[0]?.output??""),stderr:Ys(s.perInstance?.[0]?.error??s.error??""),error:s.success?void 0:s.error??"Exec command failed."}}async readFile(e){let t={workloadId:e.workloadId,path:e.path},r=await this.fileTarget(e);if("error"in r)return{...t,ok:!1,error:r.error};let{workload:n,path:i,root:o,providerId:s}=r,u=`sh -c ${ci('resolved=$(realpath -m "$1"); root=$(realpath -m "$3"); case "$resolved" in "$root"|"$root"/*) ;; *) exit 73;; esac; test -f "$resolved"; size=$(wc -c < "$resolved"); printf "__TSCLOUD_SIZE__=%s\\n" "$size"; head -c "$2" "$resolved" | base64')} sh ${ci(i)} ${xa} ${ci(o)}`,a=n.provider==="docker"?`docker exec ${s} ${u}`:u,f=await this.remote(n,[a],30,"ts-cloud runtime:file-read").catch(sd);if(!f.success)return{...t,ok:!1,error:f.error??f.perInstance?.[0]?.error??"File read failed."};let T=f.perInstance?.[0]?.output??"",R=/__TSCLOUD_SIZE__=(\d+)\r?\n/.exec(T);if(!R)return{...t,ok:!1,error:"The remote file response was invalid."};let D=Number(R[1]),W=T.slice((R.index??0)+R[0].length).replace(/\s+/g,"");if(Buffer.from(W,"base64").byteLength>xa)return{...t,ok:!1,error:"The remote file exceeded the transfer limit."};return{...t,ok:!0,contentBase64:W,size:D,truncated:D>xa}}async writeFile(e){let t={workloadId:e.workloadId,path:e.path},r=await this.fileTarget(e);if("error"in r)return{...t,ok:!1,error:r.error};if(!/^[A-Za-z0-9+/]*={0,2}$/.test(e.contentBase64))return{...t,ok:!1,error:"File content must be valid base64."};let n=Buffer.from(e.contentBase64,"base64");if(n.toString("base64")!==e.contentBase64)return{...t,ok:!1,error:"File content must be canonical base64."};if(n.byteLength>xa)return{...t,ok:!1,error:`File uploads are limited to ${xa} bytes.`};let{workload:i,path:o,root:s,providerId:c}=r,a=`sh -c ${ci('resolved=$(realpath -m "$1"); root=$(realpath -m "$2"); case "$resolved" in "$root"|"$root"/*) ;; *) exit 73;; esac; mkdir -p "$(dirname "$resolved")"; tmp="$resolved.ts-cloud-$$"; base64 -d > "$tmp"; chmod 600 "$tmp"; mv "$tmp" "$resolved"')} sh ${ci(o)} ${ci(s)}`,f=i.provider==="docker"?`printf %s ${ci(e.contentBase64)} | docker exec -i ${c} ${a}`:`printf %s ${ci(e.contentBase64)} | ${a}`,T=await this.remote(i,[f],30,"ts-cloud runtime:file-write").catch(sd);return{...t,ok:T.success,size:n.byteLength,truncated:!1,error:T.success?void 0:T.error??T.perInstance?.[0]?.error??"File write failed."}}async fileTarget(e){let t=await this.workload(e.workloadId);if(!t)return{error:"Workload was not found in the current project and environment."};if(process.env.TS_CLOUD_RUNTIME_FILE_ACCESS==="0")return{error:"Runtime file access is disabled by TS_CLOUD_RUNTIME_FILE_ACCESS."};if(!t.capabilities.files.supported)return{error:t.capabilities.files.reason??"File access is unsupported for this workload."};if(e.confirm!==t.name)return{error:`Type "${t.name}" to access workload files.`};if(!e.recentAuth)return{error:"Sign in again before using elevated runtime access."};let r=BC(t,e.path);if(!r.ok)return{error:r.error};let n=FC(t,r.path),i=t.links.providerId??"";if(!n||t.provider==="systemd"&&!ad.test(i)||t.provider==="docker"&&!cd.test(i))return{error:"File target identity is invalid or unsupported."};return{workload:t,path:r.path,root:n,providerId:i}}async logs(e,t={}){let r=await this.workload(e);if(!r)throw Error("Workload was not found in the current project and environment.");if(!r.capabilities.logs.supported)throw Error(r.capabilities.logs.reason??"Logs are unsupported for this workload.");let n=Math.min(1000,Math.max(1,Math.floor(t.limit??200)));if(r.provider==="lambda"||r.provider==="ecs"){let f=this.dependencies.logs??new oe(this.region,this.profile),T=r.config.logGroups,R=r.provider==="lambda"?`/aws/lambda/${r.name}`:Array.isArray(T)&&typeof T[0]==="string"?T[0]:void 0;if(!R)throw Error("The ECS task definition does not declare an awslogs group.");let D=await f.filterLogEvents({logGroupName:R,startTime:t.since?.getTime(),limit:n}),W=(D.events??[]).slice(0,n).map((Y)=>({timestamp:Y.timestamp==null?void 0:new Date(Y.timestamp).toISOString(),message:Ys(String(Y.message??""))}));return{workloadId:e,provider:r.provider,lines:W,nextCursor:D.nextToken,truncated:(D.events?.length??0)>=n}}let i=r.links.providerId??"",o=t.since&&Number.isFinite(t.since.getTime())?t.since:void 0,s=r.provider==="systemd"&&ad.test(i)?`journalctl -u ${i} --no-pager -n ${n} -o short-iso${o?` --since ${ci(o.toISOString())}`:""}`:r.provider==="docker"&&cd.test(i)?`docker logs --timestamps --tail ${n}${o?` --since ${Math.floor(o.getTime()/1000)}`:""} ${i} 2>&1`:void 0;if(!s)throw Error("Log target identity is invalid.");let c=await this.remote(r,[s],30,"ts-cloud runtime:logs");if(!c.success)throw Error(c.error??c.perInstance?.[0]?.error??"Log read failed.");let u=Ys(c.perInstance?.[0]?.output??""),a=u.split(`
122
122
  `).filter(Boolean).slice(-n).map((f)=>{let T=/^(\d{4}-\d{2}-\d{2}T\S+)\s+(.*)$/.exec(f);return{timestamp:T?.[1],message:T?.[2]??f}});return{workloadId:e,provider:r.provider,lines:a,truncated:u.includes("[output truncated]")||a.length>=n}}}import{randomUUID as jC}from"node:crypto";class Al{records=new Map;maxBufferBytes;ttlMs;now;constructor(e={}){this.maxBufferBytes=Math.max(1024,e.maxBufferBytes??262144),this.ttlMs=Math.max(1000,e.ttlMs??900000),this.now=e.now??(()=>new Date)}create(e,t){this.sweep();let r=this.now().toISOString(),n={id:jC(),workloadId:t,kind:e,state:"open",chunks:[],cursor:0,droppedBytes:0,bufferedBytes:0,createdAt:r,updatedAt:r,abort:new AbortController,listeners:new Set};return this.records.set(n.id,n),this.snapshot(n,0)}signal(e){return this.records.get(e)?.abort.signal}append(e,t,r="stdout"){let n=this.records.get(e);if(!n||n.state!=="open"||!t)return n?this.snapshot(n,n.cursor):void 0;let i=Buffer.from(t),o=i.byteLength>this.maxBufferBytes?i.subarray(i.byteLength-this.maxBufferBytes).toString("utf8"):t,s={cursor:++n.cursor,stream:r,data:o,at:this.now().toISOString()};n.chunks.push(s),n.bufferedBytes+=Buffer.byteLength(o),n.updatedAt=s.at;while(n.bufferedBytes>this.maxBufferBytes&&n.chunks.length>1){let c=n.chunks.shift(),u=Buffer.byteLength(c.data);n.bufferedBytes-=u,n.droppedBytes+=u}return this.publish(n),this.snapshot(n,s.cursor-1)}read(e,t,r=0){let n=this.records.get(e);if(!n||n.workloadId!==t)return;return n.updatedAt=this.now().toISOString(),this.snapshot(n,Math.max(0,Math.floor(r)))}close(e,t="complete",r){let n=this.records.get(e);if(!n||n.state!=="open")return n?this.snapshot(n,n.cursor):void 0;if(n.state=t,n.error=r,n.updatedAt=this.now().toISOString(),t==="cancelled")n.abort.abort();return this.publish(n),this.snapshot(n,n.cursor)}cancel(e,t){let r=this.records.get(e);if(!r||r.workloadId!==t)return;return this.close(e,"cancelled")}subscribe(e,t,r){let n=this.records.get(e);if(!n||n.workloadId!==t)return;return n.listeners.add(r),()=>n.listeners.delete(r)}sweep(){let e=this.now().getTime()-this.ttlMs,t=0;for(let[r,n]of this.records){if(new Date(n.updatedAt).getTime()>e)continue;n.abort.abort(),this.records.delete(r),t++}return t}clear(){for(let e of this.records.values())e.abort.abort();this.records.clear()}snapshot(e,t){let r=e.chunks[0]?.cursor??e.cursor+1,n=t>0&&t<r-1;return{id:e.id,workloadId:e.workloadId,kind:e.kind,state:e.state,chunks:e.chunks.filter((i)=>n||i.cursor>t),cursor:e.cursor,reset:n,droppedBytes:e.droppedBytes,createdAt:e.createdAt,updatedAt:e.updatedAt,error:e.error}}publish(e){let t=this.snapshot(e,0);for(let r of e.listeners)r(t)}}import{createHash as UC}from"node:crypto";var xl={info:0,low:1,medium:2,high:3,critical:4},Dl={record:0,warn:1,block:2},Ih=new Set(["skipped","unavailable","unsupported","stale"]);function Vt(e){return typeof e==="string"?e:void 0}function _o(e,t){try{return JSON.parse(String(e))}catch{return t}}function Ci(e){return JSON.stringify(h(e))}function zC(e){if(!e)return;return String(h(e,2000))}function kl(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:Vt(e.project_id),environmentId:Vt(e.environment_id),resourceId:Vt(e.resource_id),releaseId:Vt(e.release_id),scannerId:String(e.scanner_id),scannerVersion:String(e.scanner_version),status:String(e.status),error:Vt(e.error),metadata:_o(e.metadata,{}),findingsCount:Number(e.findings_count),startedAt:String(e.started_at),completedAt:String(e.completed_at),durationMs:Number(e.duration_ms)}}function Ch(e){return{id:String(e.id),fingerprint:String(e.fingerprint),organizationId:String(e.organization_id),projectId:Vt(e.project_id),environmentId:Vt(e.environment_id),resourceId:Vt(e.resource_id),releaseId:Vt(e.release_id),scanRunId:String(e.scan_run_id),scannerId:String(e.scanner_id),scannerVersion:String(e.scanner_version),ruleId:String(e.rule_id),severity:String(e.severity),title:String(e.title),description:String(e.description),evidence:_o(e.evidence,{}),remediation:Vt(e.remediation),subject:String(e.subject),status:String(e.status),ownerActorId:Vt(e.owner_actor_id),recurrenceCount:Number(e.recurrence_count),firstSeenAt:String(e.first_seen_at),lastSeenAt:String(e.last_seen_at),resolvedAt:Vt(e.resolved_at),updatedAt:String(e.updated_at)}}function Rl(e){return{id:String(e.id),organizationId:String(e.organization_id),environmentId:Vt(e.environment_id),name:String(e.name),rules:_o(e.rules,[]),requiredScanners:_o(e.required_scanners,[]),scannerFailMode:String(e.scanner_fail_mode),enabled:Number(e.enabled)===1,version:Number(e.version),createdByActorId:Vt(e.created_by_actor_id),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Eh(e,t){let r=Vt(e.revoked_at),n=String(e.expires_at);return{id:String(e.id),findingId:String(e.finding_id),policyId:Vt(e.policy_id),reason:String(e.reason),referenceUrl:Vt(e.reference_url),createdByActorId:String(e.created_by_actor_id),expiresAt:n,revokedAt:r,state:r?"revoked":n<=t?"expired":"active",createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Pl(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:Vt(e.environment_id),releaseId:String(e.release_id),kind:String(e.kind),format:String(e.format),digest:String(e.digest),summary:_o(e.summary,{}),content:Vt(e.content),sensitive:Number(e.sensitive)===1,createdAt:String(e.created_at)}}function Th(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:String(e.environment_id),operationId:Vt(e.operation_id),policyId:String(e.policy_id),policyVersion:Number(e.policy_version),outcome:String(e.outcome),scannerVersions:_o(e.scanner_versions,{}),findingIds:_o(e.finding_ids,[]),waiverIds:_o(e.waiver_ids,[]),explanation:String(e.explanation),createdAt:String(e.created_at)}}function VC(e,t){let r=[e.trim().toLowerCase(),t.ruleId.trim().toLowerCase(),t.organizationId,t.projectId??"",t.environmentId??"",t.resourceId??"",t.releaseId??"",t.subject.trim().toLowerCase()].join("\x00");return UC("sha256").update(r).digest("hex")}function Ah(e){if(!e)return;let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")throw Error("Security references must use HTTP or HTTPS");return t.toString()}function kh(e){if(!e.length)throw Error("A security policy needs at least one rule");return e.map((t)=>{if(!(t.minimumSeverity in xl))throw Error(`Unknown security severity: ${t.minimumSeverity}`);if(!(t.action in Dl))throw Error(`Unknown security policy action: ${t.action}`);return{minimumSeverity:t.minimumSeverity,action:t.action,...t.scannerId?{scannerId:t.scannerId.trim()}:{}}})}class xt{controlPlane;nowFn;idFn;constructor(e,t={}){this.controlPlane=e;this.nowFn=t.now??(()=>new Date),this.idFn=t.id??(()=>crypto.randomUUID())}now(){return this.nowFn().toISOString()}run(e,t){this.controlPlane.database.run(e,t)}recordScan(e){if(!e.organizationId||!e.scannerId.trim()||!e.scannerVersion.trim())throw Error("Organization, scanner id, and scanner version are required");let t=e.completedAt??this.now(),r=e.startedAt??t,n=e.durationMs??Math.max(0,new Date(t).getTime()-new Date(r).getTime()),i=e.findings??[],o=this.idFn(),s=new Set,c=[];return this.controlPlane.transaction(()=>{this.run(`INSERT INTO security_scan_runs
123
123
  (id, organization_id, project_id, environment_id, resource_id, release_id, scanner_id, scanner_version, status, error, metadata, findings_count, started_at, completed_at, duration_ms)
@@ -147,7 +147,7 @@ export type ConfigOf = Config
147
147
  `)){let i=n.trim();if(i.startsWith("DB="))t.push(i.slice(3));else if(i.startsWith("USER="))r.push(i.slice(5))}return{databases:[...new Set(t)].filter(Boolean).sort(),users:[...new Set(r)].filter(Boolean).sort()}}async function cn(e,t,r,n){let i;try{i=O({config:e})}catch(u){return{ok:!1,error:`Could not initialize the cloud driver: ${u?.message??u}`}}let o=e.project.slug,s=await i.findComputeTargets({slug:o,environment:t,role:"app"});if(!s.length)return{ok:!1,error:"No app server target was found for this environment."};let c=await i.runRemoteDeploy({targets:[s[0]],commands:["set -uo pipefail",...r],comment:n,tags:{Project:o,Environment:t,Role:"app"}});return{ok:c.success,stdout:c.perInstance?.[0]?.output??"",stderr:c.perInstance?.[0]?.error??c.error??""}}function md(e,t){return{ok:!1,error:`${t} is not available for ${e}: it is an external cluster, so this box has no engine to administer. ${e==="vitess"?"Create a keyspace with `vtctldclient CreateKeyspace`, and manage vtgate credentials on the cluster.":"Use the provider console or the cluster's own admin connection."}`}}async function jh(e,t){let r=ds(e);if(gd(r)&&r!=="vitess")return{...md(r,"Listing databases"),engine:r,databases:[],users:[]};let n=await cn(e,t,bE(r,w(e)),"ts-cloud db:list"),i=n.ok&&n.stdout?EE(n.stdout):{databases:[],users:[]};return{...n,engine:r,...i}}async function Uh(e,t,r){let n=ds(e);if(gd(n))return md(n,"Creating a database");return cn(e,t,IE(n,r,w(e)),`ts-cloud db:create ${r}`)}async function zh(e,t,r){let n=ds(e);if(gd(n))return md(n,"Creating a database user");return cn(e,t,CE(n,r,w(e)),`ts-cloud db:user ${r.username}`)}var zl="/var/backups/ts-cloud/databases";function es(e,t,r=zl,n){let o=`${r}/${t}-$TS_CLOUD_BACKUP_STAMP.sql.gz`,s=`mkdir -p ${r}`;if(e==="postgres")return[s,'TS_CLOUD_BACKUP_STAMP="$(date +%Y%m%d-%H%M%S)"',`${Pr(n,"pg_dump")} ${t} | gzip > "${o}"`,`echo "BACKUP=${o}"`,`ls -l "${o}"`];let c=e==="mariadb"?pd.mariadb:pd.mysql;return[s,'TS_CLOUD_BACKUP_STAMP="$(date +%Y%m%d-%H%M%S)"',`mysqldump --socket=${c} -u root ${t} | gzip > "${o}"`,`echo "BACKUP=${o}"`,`ls -l "${o}"`]}function TE(e=zl){return[`ls -1t ${e}/*.sql.gz 2>/dev/null | head -50 | sed 's|^|BACKUP=|' || true`]}function AE(e){let t=[];for(let r of e.split(`
148
148
  `)){let n=r.trim();if(!n.startsWith("BACKUP="))continue;let i=n.slice(7),s=(i.split("/").pop()??i).replace(/-\d{8}-\d{6}\.sql\.gz$/,"");if(i)t.push({file:i,database:s})}return t}async function Vh(e,t,r){if(!co(r))return{ok:!1,error:"Database name must be a valid identifier.",database:r};let n=ds(e);if(gd(n))return{...md(n,"Backing up"),database:r};return{...await cn(e,t,es(n,r,zl,w(e)),`ts-cloud db:backup ${r}`),database:r}}async function qh(e,t){let r=await cn(e,t,TE(),"ts-cloud db:backups"),n=r.ok&&r.stdout?AE(r.stdout):[];return{...r,backups:n}}async function Gh(e,t){let r=ds(e),n={keyspaces:[],shards:[],tablets:[]};if(r!=="vitess")return{ok:!1,error:"The configured database engine is not Vitess.",engine:r,...n};let i=await cn(e,t,vE(w(e)),"ts-cloud vitess:topology"),o=i.ok&&i.stdout?wE(i.stdout):n;return{...i,engine:r,...o}}function Jh(e){return e.filter((t)=>t.state.toUpperCase()!=="SERVING")}function Hh(e){let t=new Set(e.tablets.filter((r)=>r.type.toUpperCase()==="PRIMARY"&&r.state.toUpperCase()==="SERVING").map((r)=>`${r.keyspace}/${r.shard}`));return e.shards.filter((r)=>!t.has(`${r.keyspace}/${r.shard}`))}var Vl="/usr/local/bin/vtctldclient",kE="21.0.0";function hd(e){return`'${String(e).split("'").join("'\\''")}'`}function yd(e){return w(e)?.vitess??{}}function Wh(e){return/^[A-Za-z_][A-Za-z0-9_]{0,63}$/.test(e)}function RE(e){return/^[0-9a-f]{8}(?:_[0-9a-f]{4}){3}_[0-9a-f]{12}$/i.test(e)}function PE(e=kE){let t=hd(e);return[`if ${Vl} --version 2>/dev/null | grep -q ${t}; then echo "vtctldclient ${e} already installed"; else`," command -v curl >/dev/null 2>&1 || (apt-get update -y && apt-get install -y curl ca-certificates)",' if [ "$(uname -m)" != "x86_64" ]; then',' echo "vtctldclient: Vitess publishes only an x86_64 release tarball; this box is $(uname -m). Build from source or install via pantry." >&2'," exit 1"," fi",' tmp="$(mktemp -d)"',` api="https://api.github.com/repos/vitessio/vitess/releases/tags/v${e}"`,` url="$(curl -fsSL "$api" | grep -oE '"browser_download_url"[[:space:]]*:[[:space:]]*"[^"]+vitess-[0-9][^"]*\\.tar\\.gz"' | head -1 | sed -E 's/.*"(https[^"]+)"/\\1/')"`,' if [ -z "$url" ]; then echo "vtctldclient: no release tarball found for v'+e+'" >&2; rm -rf "$tmp"; exit 1; fi',` curl -fsSL "$url" | tar -xz -C "$tmp" --strip-components=2 --wildcards --occurrence=1 '*/bin/vtctldclient' || true`,' if [ ! -s "$tmp/vtctldclient" ]; then',' echo "vtctldclient: could not extract the binary from $url" >&2',' rm -rf "$tmp"; exit 1'," fi",` install -m 0755 "$tmp/vtctldclient" ${Vl}`,' rm -rf "$tmp"',` echo "installed vtctldclient ${e}"`,"fi"]}function Kh(e){if(!e.vtctldAddr)return null;return`${Vl} --server ${hd(e.vtctldAddr)}`}function xE(e,t,r={}){let n=Kh(e);if(!n)return null;let i=r.sharded?" --sharded":"";return[`${n} CreateKeyspace${i} ${hd(t)}`]}function DE(e,t,r){let n=Kh(e);if(!n)return null;return['vschema_tmp="$(mktemp)"',`cat > "$vschema_tmp" <<'TS_CLOUD_VSCHEMA_EOF'`,r,"TS_CLOUD_VSCHEMA_EOF",`${n} ApplyVSchema --vschema-file "$vschema_tmp" ${hd(t)}`,'rm -f "$vschema_tmp"']}function OE(e,t,r="vitess"){return Xs([`SET @@ddl_strategy='${r}';`,t.endsWith(";")?t:`${t};`],e,Zs)}function _E(e,t){let r=t?[`USE ${t.replace(/[^A-Z0-9_]/gi,"")};`,"SHOW VITESS_MIGRATIONS;"]:["SHOW VITESS_MIGRATIONS;"],n=Xs(r,e,Zs);return n[0]=n[0].replace(" --skip-column-names",""),n}function NE(e){let t=e.split(`
149
149
  `).map((s)=>s.trimEnd()).filter((s)=>s.trim().length>0);if(t.length===0)return[];let r=t[0].split("\t").map((s)=>s.trim()),n=(s)=>r.indexOf(s),i={uuid:n("migration_uuid"),keyspace:n("keyspace"),shard:n("shard"),table:n("mysql_table"),status:n("migration_status"),strategy:n("strategy"),added:n("added_timestamp"),completed:n("completed_timestamp"),progress:n("progress")};if(i.uuid===-1)return[];let o=[];for(let s of t.slice(1)){let c=s.split("\t"),u=(f)=>f>=0?(c[f]??"").trim():"",a=u(i.uuid);if(!a)continue;o.push({uuid:a,keyspace:u(i.keyspace),shard:u(i.shard),table:u(i.table),status:u(i.status),strategy:u(i.strategy),added:u(i.added),completed:u(i.completed),progress:u(i.progress)})}return o}function ME(e){return e.filter((t)=>t.status.toLowerCase()==="failed")}function $E(e){return e.filter((t)=>["running","queued","ready"].includes(t.status.toLowerCase()))}function LE(e,t,r){let n=r.toUpperCase();return Xs([`ALTER VITESS_MIGRATION '${t}' ${n};`],e,Zs)}function ta(e){if(ds(e)!=="vitess")return{ok:!1,error:"The configured database engine is not Vitess."};return null}function fd(e){if(!e.vtctldAddr)return{ok:!1,error:"No vtctld address is configured. Creating keyspaces and applying a VSchema are topology operations that vtgate cannot perform. Set `infrastructure.appDatabase.vitess.vtctldAddr` (for example `vtctld.internal:15999`) and redeploy."};return null}async function Qh(e,t){let r=ta(e);if(r)return r;let n=yd(e);return cn(e,t,PE(n.clientVersion),"ts-cloud vitess:install-client")}async function Yh(e,t,r,n={}){let i=ta(e);if(i)return{...i,keyspace:r};if(!Wh(r))return{ok:!1,error:"Keyspace name must be a valid identifier.",keyspace:r};let o=yd(e),s=fd(o);if(s)return{...s,keyspace:r};let c=xE(o,r,n);if(!c)return{...fd({}),keyspace:r};return{...await cn(e,t,c,`ts-cloud vitess:create-keyspace ${r}`),keyspace:r}}async function Xh(e,t,r,n){let i=ta(e);if(i)return{...i,keyspace:r};if(!Wh(r))return{ok:!1,error:"Keyspace name must be a valid identifier.",keyspace:r};try{let a=JSON.parse(n);if(!a||typeof a!=="object")return{ok:!1,error:"The VSchema must be a JSON object.",keyspace:r}}catch(a){return{ok:!1,error:`The VSchema is not valid JSON: ${a?.message??a}`,keyspace:r}}let o=yd(e),s=fd(o);if(s)return{...s,keyspace:r};let c=DE(o,r,n);if(!c)return{...fd({}),keyspace:r};return{...await cn(e,t,c,`ts-cloud vitess:apply-vschema ${r}`),keyspace:r}}async function Zh(e,t,r){let n=ta(e);if(n)return n;if(!r.trim())return{ok:!1,error:"No SQL was provided."};let i=yd(e);return cn(e,t,OE(w(e),r,i.ddlStrategy??"vitess"),"ts-cloud vitess:apply-schema")}async function ey(e,t,r){let n=ta(e);if(n)return{...n,migrations:[],failed:[],running:[]};let i=await cn(e,t,_E(w(e),r),"ts-cloud vitess:migrations"),o=i.ok&&i.stdout?NE(i.stdout):[];return{...i,migrations:o,failed:ME(o),running:$E(o)}}async function ty(e,t,r,n){let i=ta(e);if(i)return{...i,uuid:r};if(!RE(r))return{ok:!1,error:"Migration UUID is not in the expected format.",uuid:r};return{...await cn(e,t,LE(w(e),r,n),`ts-cloud vitess:migration ${n} ${r}`),uuid:r}}function BE(e){let t=e.infrastructure?.appDatabase;if(t?.engine&&t.engine!=="vitess")return`This project already declares ${t.engine} as its application database.`;let r=e.infrastructure?.compute?.managedServices,n=r?["mysql","mariadb","postgres"].find((i)=>Boolean(r[i])):void 0;if(n)return`This server already declares the ${n} database service.`;return}function FE(e,t){let r=t.keyspace.trim(),n=t.username.trim(),i=t.password,o=BE(e);if(o)throw Error(o);if(!co(r))throw Error("Keyspace must contain letters, numbers, or underscores and cannot start with a number.");if(!co(n))throw Error("Username must contain letters, numbers, or underscores and cannot start with a number.");if(i.length<16)throw Error("Password must contain at least 16 characters.");if(t.confirm!==r)throw Error(`Type "${r}" to confirm Vitess provisioning.`);let s={mode:"cluster",cell:"zone1",keyspaces:[{name:r,sharded:t.sharded===!0}],vtgatePort:15306,username:n,password:i,bindAddress:"127.0.0.1"};return{service:s,appDatabase:{engine:"vitess",name:r,username:n,host:"127.0.0.1",port:15306,ssl:!1},commands:[...Ir(),...xo(s)]}}async function ry(e,t,r){let n=FE(e,r);return{...await cn(e,t,n.commands,`ts-cloud vitess:provision ${n.appDatabase.name}`),database:n.appDatabase,service:Object.fromEntries(Object.entries(n.service).filter(([o])=>o!=="password"))}}var jE={capability:"runtime:terminal",scope:"organization"};var UE={"GET /api/health":{capability:"project:read",anyUser:!0},"GET /api/dashboard-data":{capability:"project:read",anyUser:!0},"GET /api/config":{capability:"config:read",anyUser:!0},"GET /api/me":{capability:"project:read",anyUser:!0},"GET /api/search":{capability:"project:read",anyUser:!0},"GET /api/search/preferences":{capability:"project:read",anyUser:!0},"POST /api/search/preferences":{capability:"project:read",anyUser:!0},"DELETE /api/search/preferences":{capability:"project:read",anyUser:!0},"GET /api/auth/security":{capability:"project:read",anyUser:!0},"GET /api/auth/sessions":{capability:"project:read",anyUser:!0},"DELETE /api/auth/sessions":{capability:"project:read",anyUser:!0},"POST /api/auth/sessions/revoke-others":{capability:"project:read",anyUser:!0},"POST /api/auth/password/change":{capability:"project:read",anyUser:!0},"POST /api/auth/mfa/enroll":{capability:"project:read",anyUser:!0},"POST /api/auth/mfa/verify":{capability:"project:read",anyUser:!0},"DELETE /api/auth/mfa":{capability:"project:read",anyUser:!0},"POST /api/auth/step-up":{capability:"project:read",anyUser:!0},"GET /api/auth/oidc/providers":{capability:"users:read",scope:"organization"},"POST /api/auth/oidc/providers":{capability:"users:manage",scope:"organization"},"PATCH /api/auth/oidc/providers":{capability:"users:manage",scope:"organization"},"GET /api/automation":{capability:"users:read",scope:"organization"},"POST /api/automation/service-accounts":{capability:"users:manage",scope:"organization"},"PATCH /api/automation/service-accounts":{capability:"users:manage",scope:"organization"},"POST /api/automation/tokens":{capability:"users:manage",scope:"organization"},"POST /api/automation/tokens/rotate":{capability:"users:manage",scope:"organization"},"DELETE /api/automation/tokens":{capability:"users:manage",scope:"organization"},"GET /api/security/posture":{capability:"security:read"},"GET /api/security/export":{capability:"security:read"},"POST /api/security/scan":{capability:"security:manage"},"POST /api/security/review":{capability:"deployments:create"},"POST /api/security/policies":{capability:"security:manage"},"PATCH /api/security/policies":{capability:"security:manage"},"POST /api/security/waivers":{capability:"security:waive"},"DELETE /api/security/waivers":{capability:"security:waive"},"PATCH /api/security/findings":{capability:"security:manage"},"POST /api/security/comments":{capability:"security:manage"},"GET /api/sources":{capability:"sources:read"},"POST /api/sources/connections":{capability:"sources:manage"},"PATCH /api/sources/connections":{capability:"sources:manage"},"DELETE /api/sources/connections":{capability:"sources:manage"},"POST /api/sources/deploy-keys":{capability:"sources:manage"},"DELETE /api/sources/deploy-keys":{capability:"sources:manage"},"POST /api/sources/repositories/sync":{capability:"sources:manage"},"GET /api/sources/references":{capability:"sources:read"},"POST /api/sources/bindings":{capability:"sources:manage"},"PATCH /api/sources/bindings":{capability:"sources:manage"},"POST /api/sources/webhooks":{capability:"sources:manage"},"PATCH /api/sources/webhooks":{capability:"sources:manage"},"DELETE /api/sources/webhooks":{capability:"sources:manage"},"GET /api/onboarding":{capability:"applications:read"},"POST /api/onboarding/detect":{capability:"applications:manage"},"POST /api/onboarding/plan":{capability:"applications:manage"},"POST /api/onboarding/drafts":{capability:"applications:manage"},"PATCH /api/onboarding/drafts":{capability:"applications:manage"},"POST /api/onboarding/artifacts":{capability:"applications:manage"},"POST /api/onboarding/registries":{capability:"applications:manage"},"PATCH /api/onboarding/registries":{capability:"applications:manage"},"DELETE /api/onboarding/registries":{capability:"applications:manage"},"POST /api/onboarding/apply":{capability:"applications:manage"},"GET /api/compose":{capability:"applications:read",anyUser:!0},"POST /api/compose/preview":{capability:"applications:manage",anyUser:!0},"POST /api/compose/import":{capability:"applications:manage",anyUser:!0},"POST /api/compose/template":{capability:"applications:manage",anyUser:!0},"POST /api/compose/action":{capability:"project:read",anyUser:!0},"POST /api/compose/logs":{capability:"runtime:logs",anyUser:!0},"POST /api/compose/shell":{capability:"runtime:terminal",scope:"organization"},"GET /api/compose/import":{capability:"applications:manage"},"GET /api/compose/template":{capability:"applications:manage"},"GET /api/compose/logs":{capability:"runtime:logs"},"GET /api/compose/shell":{capability:"runtime:terminal",scope:"organization"},"GET /api/organization":{capability:"users:read",scope:"organization"},"GET /api/organization/invitations":{capability:"users:read",scope:"organization"},"POST /api/organization/invitations":{capability:"users:manage",scope:"organization"},"DELETE /api/organization/invitations":{capability:"users:manage",scope:"organization"},"POST /api/organization/invitations/resend":{capability:"users:manage",scope:"organization"},"PATCH /api/organization/memberships":{capability:"users:manage",scope:"organization"},"DELETE /api/organization/memberships":{capability:"users:manage",scope:"organization"},"POST /api/organization/grants":{capability:"users:manage",scope:"organization"},"DELETE /api/organization/grants":{capability:"users:manage",scope:"organization"},"GET /api/control-plane/operations":{capability:"deployments:read"},"GET /api/control-plane/events":{capability:"audit:read"},"GET /api/queue":{capability:"deployments:read",anyUser:!0},"GET /api/queue/logs":{capability:"deployments:read",anyUser:!0},"GET /api/queue/stream":{capability:"deployments:read",anyUser:!0},"POST /api/queue/cancel":{capability:"deployments:cancel",anyUser:!0},"POST /api/queue/retry":{capability:"deployments:create",anyUser:!0},"GET /api/queue/settings":{capability:"deployments:read"},"PATCH /api/queue/settings":{capability:"automation:manage",scope:"organization"},"DELETE /api/queue/history":{capability:"automation:manage",scope:"organization"},"GET /api/previews":{capability:"deployments:read",anyUser:!0},"GET /api/releases":{capability:"deployments:read",anyUser:!0},"POST /api/releases/action":{capability:"deployments:create",anyUser:!0},"POST /api/previews/deploy":{capability:"deployments:create",anyUser:!0},"POST /api/previews/destroy":{capability:"deployments:cancel",anyUser:!0},"POST /api/previews/extend":{capability:"deployments:create",anyUser:!0},"POST /api/previews/rebuild":{capability:"deployments:create",anyUser:!0},"POST /api/previews/definitions":{capability:"config:write",anyUser:!0},"POST /api/previews/cleanup":{capability:"automation:manage",scope:"organization"},"GET /api/tags":{capability:"project:read"},"POST /api/tags":{capability:"tags:manage"},"DELETE /api/tags":{capability:"tags:manage"},"POST /api/sites/deploy":{capability:"deployments:create",scope:"site",siteFrom:"body"},"PATCH /api/sites":{capability:"config:write",scope:"site",siteFrom:"body"},"POST /api/sites":{capability:"config:write"},"DELETE /api/sites":{capability:"config:write"},"POST /api/env":{capability:"config:write"},"GET /api/ssh-keys":{capability:"fleet:read"},"POST /api/ssh-keys":{capability:"fleet:manage"},"DELETE /api/ssh-keys":{capability:"fleet:manage"},"GET /api/firewall":{capability:"fleet:read"},"POST /api/firewall":{capability:"fleet:manage"},"DELETE /api/firewall":{capability:"fleet:manage"},"GET /api/databases":{capability:"data:read"},"POST /api/databases":{capability:"data:admin"},"GET /api/databases/vitess":{capability:"data:read"},"GET /api/databases/vitess/migrations":{capability:"data:read"},"POST /api/databases/vitess/migrations/action":{capability:"data:admin"},"POST /api/databases/vitess/provision":{capability:"runtime:terminal",scope:"organization"},"POST /api/databases/vitess/keyspaces":{capability:"data:admin"},"POST /api/databases/vitess/vschema":{capability:"data:admin"},"POST /api/databases/vitess/schema":{capability:"data:admin"},"POST /api/databases/vitess/install-client":{capability:"data:admin"},"GET /api/databases/backups":{capability:"backups:read"},"POST /api/databases/backup":{capability:"backups:create"},"POST /api/databases/users":{capability:"data:admin"},"GET /api/data-services":{capability:"data:read"},"GET /api/data-services/capabilities":{capability:"data:read"},"GET /api/data-services/connections":{capability:"data:read"},"POST /api/data-services/preview":{capability:"data:read"},"POST /api/data-services":{capability:"data:admin"},"POST /api/data-services/action":{capability:"data:admin"},"POST /api/data-services/dependencies":{capability:"data:admin"},"POST /api/data-services/management":{capability:"data:admin"},"POST /api/data-services/reveal":{capability:"data:admin"},"GET /api/backups":{capability:"backups:read"},"POST /api/backups/destinations":{capability:"backups:create"},"POST /api/backups/destinations/test":{capability:"backups:create"},"POST /api/backups/policies":{capability:"backups:create"},"POST /api/backups/run":{capability:"backups:create"},"POST /api/backups/verify":{capability:"backups:create"},"POST /api/backups/restore":{capability:"backups:restore"},"POST /api/backups/recovery-points":{capability:"backups:create"},"POST /api/backups/retention":{capability:"backups:create"},"GET /api/configuration":{capability:"config:read"},"GET /api/configuration/export":{capability:"config:read"},"POST /api/configuration/plan":{capability:"config:read"},"POST /api/configuration":{capability:"config:write"},"POST /api/configuration/import":{capability:"config:write"},"POST /api/configuration/dependencies":{capability:"config:write"},"POST /api/configuration/transfer":{capability:"config:write"},"POST /api/configuration/bulk":{capability:"config:write"},"POST /api/configuration/reveal":{capability:"secrets:read"},"DELETE /api/configuration":{capability:"config:write"},"GET /api/volumes":{capability:"data:read"},"POST /api/volumes":{capability:"data:admin"},"POST /api/volumes/attach":{capability:"data:admin"},"POST /api/volumes/detach":{capability:"data:admin"},"POST /api/volumes/resize":{capability:"data:admin"},"POST /api/volumes/snapshot":{capability:"backups:create"},"POST /api/volumes/restore":{capability:"backups:restore"},"POST /api/volumes/adopt":{capability:"data:admin"},"POST /api/volumes/discover":{capability:"data:read"},"DELETE /api/volumes":{capability:"data:admin"},"GET /api/fleet":{capability:"fleet:read"},"POST /api/fleet":{capability:"fleet:manage"},"POST /api/fleet/action":{capability:"fleet:manage"},"GET /api/capacity":{capability:"fleet:read"},"POST /api/capacity":{capability:"fleet:manage"},"POST /api/capacity/member":{capability:"fleet:manage"},"POST /api/capacity/explain":{capability:"fleet:read"},"POST /api/capacity/action":{capability:"fleet:manage"},"GET /api/regions":{capability:"config:read"},"POST /api/regions":{capability:"config:write"},"POST /api/regions/action":{capability:"config:write"},"GET /api/maintenance":{capability:"automation:read"},"POST /api/maintenance/cleanup-preview":{capability:"automation:manage"},"POST /api/maintenance/cleanup-apply":{capability:"automation:manage"},"POST /api/maintenance/drill":{capability:"automation:manage"},"POST /api/maintenance/drill-run":{capability:"automation:manage"},"GET /api/actions":{capability:"runtime:read"},"GET /api/runtime/workloads":{capability:"runtime:read"},"GET /api/runtime/logs":{capability:"runtime:logs"},"POST /api/runtime/log-sessions":{capability:"runtime:logs"},"GET /api/runtime/log-sessions":{capability:"runtime:logs"},"GET /api/runtime/log-stream":{capability:"runtime:logs"},"DELETE /api/runtime/log-sessions":{capability:"runtime:logs"},"POST /api/runtime/exec-sessions":{capability:"runtime:terminal",scope:"organization"},"GET /api/runtime/exec-sessions":{capability:"runtime:terminal",scope:"organization"},"GET /api/runtime/exec-stream":{capability:"runtime:terminal",scope:"organization"},"DELETE /api/runtime/exec-sessions":{capability:"runtime:terminal",scope:"organization"},"POST /api/runtime/files/read":{capability:"runtime:terminal",scope:"organization"},"POST /api/runtime/files/write":{capability:"runtime:terminal",scope:"organization"},"POST /api/runtime/operations":{capability:"runtime:restart"},"GET /api/telemetry/status":{capability:"runtime:read"},"GET /api/telemetry/settings":{capability:"runtime:read"},"PATCH /api/telemetry/settings":{capability:"config:write",scope:"organization"},"GET /api/telemetry/query":{capability:"runtime:logs"},"GET /api/telemetry/tail":{capability:"runtime:logs"},"GET /api/telemetry/series":{capability:"runtime:read"},"POST /api/telemetry/refresh":{capability:"runtime:logs"},"POST /api/telemetry/export":{capability:"runtime:logs"},"GET /api/telemetry/saved-queries":{capability:"runtime:logs"},"POST /api/telemetry/saved-queries":{capability:"runtime:logs"},"DELETE /api/telemetry/saved-queries":{capability:"runtime:logs"},"GET /api/health/checks":{capability:"runtime:read"},"POST /api/health/checks":{capability:"config:write"},"PATCH /api/health/checks":{capability:"config:write"},"POST /api/health/checks/test":{capability:"runtime:read"},"POST /api/health/checks/run":{capability:"runtime:restart"},"GET /api/protection":{capability:"security:read"},"POST /api/protection/attack-mode":{capability:"security:manage"},"POST /api/protection/pause":{capability:"security:manage"},"GET /api/protection/ip-rules":{capability:"security:read"},"POST /api/protection/ip-rules":{capability:"security:manage"},"DELETE /api/protection/ip-rules":{capability:"security:manage"},"GET /api/usage":{capability:"billing:read"},"GET /api/spend/budgets":{capability:"billing:read"},"POST /api/spend/budgets":{capability:"billing:manage"},"PATCH /api/spend/budgets":{capability:"billing:manage"},"DELETE /api/spend/budgets":{capability:"billing:manage"},"POST /api/spend/check":{capability:"billing:manage"},"GET /api/spend/enforcement":{capability:"billing:read"},"POST /api/spend/release":{capability:"billing:manage"},"GET /api/spend/anomalies":{capability:"billing:read"},"POST /api/spend/anomalies/acknowledge":{capability:"billing:manage"},"GET /api/alerts":{capability:"runtime:read"},"GET /api/alerts/rules":{capability:"runtime:read"},"POST /api/alerts/rules":{capability:"config:write"},"PATCH /api/alerts/rules":{capability:"config:write"},"POST /api/alerts/evaluate":{capability:"runtime:restart"},"POST /api/alerts/action":{capability:"runtime:restart"},"POST /api/alerts/silences":{capability:"config:write"},"GET /api/notifications/channels":{capability:"automation:read",scope:"organization"},"POST /api/notifications/channels":{capability:"automation:manage",scope:"organization"},"PATCH /api/notifications/channels":{capability:"automation:manage",scope:"organization"},"POST /api/notifications/channels/test":{capability:"automation:manage",scope:"organization"},"GET /api/notifications/routes":{capability:"automation:read",scope:"organization"},"POST /api/notifications/routes":{capability:"automation:manage",scope:"organization"},"PATCH /api/notifications/routes":{capability:"automation:manage",scope:"organization"},"POST /api/notifications/routes/preview":{capability:"automation:read",scope:"organization"},"GET /api/notifications/deliveries":{capability:"automation:read",scope:"organization"},"POST /api/notifications/deliveries/retry":{capability:"automation:manage",scope:"organization"},"GET /api/jobs":{capability:"automation:read"},"POST /api/jobs":{capability:"automation:manage"},"PATCH /api/jobs":{capability:"automation:manage"},"POST /api/jobs/preview":{capability:"automation:read"},"POST /api/jobs/action":{capability:"automation:manage"},"POST /api/jobs/reconcile":{capability:"automation:manage"},"GET /api/jobs/history":{capability:"automation:read"},"GET /api/workers":{capability:"automation:read"},"POST /api/workers/action":{capability:"automation:manage"},"POST /api/actions/run":{capability:"fleet:manage"},"GET /api/server/operations":{capability:"fleet:read"},"POST /api/server/operations/run":{capability:"fleet:manage"},"POST /api/server/command":{capability:"runtime:terminal",scope:"organization"},"GET /api/terminal":{capability:"runtime:terminal",scope:"organization"},"GET /api/users":{capability:"users:read",scope:"organization"},"POST /api/users":{capability:"users:manage",scope:"organization"},"DELETE /api/users":{capability:"users:manage",scope:"organization"},"GET /api/serverless/operations":{capability:"deployments:read"},"POST /api/serverless/operations/run":{capability:"deployments:create"},"POST /api/serverless/command":{capability:"runtime:terminal",scope:"organization"},"GET /api/serverless/dlq":{capability:"data:read"},"POST /api/serverless/dlq/redrive":{capability:"data:write"},"POST /api/serverless/dlq/purge":{capability:"data:admin"},"GET /api/serverless/secrets":{capability:"secrets:read"},"POST /api/serverless/secrets":{capability:"secrets:write"},"DELETE /api/serverless/secrets":{capability:"secrets:write"},"POST /api/serverless/functions/config":{capability:"config:write"},"GET /api/serverless/alarms":{capability:"runtime:read"},"POST /api/serverless/alarms":{capability:"config:write"},"DELETE /api/serverless/alarms":{capability:"config:write"},"GET /api/serverless/traces":{capability:"runtime:read"},"POST /api/serverless/scheduler":{capability:"automation:manage"}};function ql(e,t){return UE[`${e.toUpperCase()} ${t}`]??jE}import{createHmac as zE,randomBytes as VE,timingSafeEqual as qE}from"node:crypto";import{chmodSync as GE,existsSync as JE,mkdirSync as HE,readFileSync as WE,writeFileSync as KE}from"node:fs";import{dirname as QE}from"node:path";var _a="ts_cloud_session";var YE=28800000;function ny(e){let t=process.env.TS_CLOUD_DASHBOARD_SECRET?.trim();if(t)return t;let r=A(e,"dashboard-secret");try{if(JE(r)){let i=WE(r,"utf8").trim();if(i)return i}}catch{}let n=VE(32).toString("base64url");try{HE(QE(r),{recursive:!0}),KE(r,`${n}
150
- `),GE(r,384)}catch{}return n}function XE(e,t){return zE("sha256",t).update(e).digest("base64url")}function iy(e,t){if(!e)return null;let r=e.lastIndexOf(".");if(r<=0)return null;let n=e.slice(0,r),i=e.slice(r+1),o=XE(n,t),s=Buffer.from(i),c=Buffer.from(o);if(s.length!==c.length||!qE(s,c))return null;try{let u=JSON.parse(Buffer.from(n,"base64url").toString("utf8"));if(typeof u?.u!=="string"||typeof u?.exp!=="number")return null;if(u.mv!==void 0&&(!u.mv||typeof u.mv!=="object"||Array.isArray(u.mv)||Object.values(u.mv).some((a)=>!Number.isInteger(a)||a<1)))return null;if(Date.now()>=u.exp)return null;return u}catch{return null}}function Gl(e,t){if(!e)return;for(let r of e.split(";")){let n=r.indexOf("=");if(n<0)continue;if(r.slice(0,n).trim()===t)return decodeURIComponent(r.slice(n+1).trim())}return}function na(e,t={secure:!0}){let r=Math.floor((t.maxAgeMs??YE)/1000),n=[`${_a}=${encodeURIComponent(e)}`,"Path=/","HttpOnly","SameSite=Lax",`Max-Age=${r}`];if(t.secure)n.push("Secure");return n.join("; ")}function bd(e={secure:!0}){let t=[`${_a}=`,"Path=/","HttpOnly","SameSite=Lax","Max-Age=0"];if(e.secure)t.push("Secure");return t.join("; ")}import{chmodSync as ZE,existsSync as eT,mkdirSync as tT,readFileSync as rT,writeFileSync as nT}from"node:fs";import{dirname as iT}from"node:path";function oy(){return Be("dashboard-users.json")}function Sd(e){return/^[a-z0-9][a-z0-9._-]{1,31}$/i.test(e)}function oT(e){if(!e||typeof e.username!=="string"||!Sd(e.username)||typeof e.passwordHash!=="string")return null;let t=e.role==="admin"?"admin":"member",r={};if(e.sites&&typeof e.sites==="object"){for(let[n,i]of Object.entries(e.sites))if(i==="owner"||i==="collaborator")r[n]=i}return{username:e.username,passwordHash:e.passwordHash,role:t,sites:r,name:typeof e.name==="string"?e.name:void 0,email:typeof e.email==="string"?e.email.trim().toLowerCase():void 0,createdAt:typeof e.createdAt==="string"?e.createdAt:void 0}}function sT(e){try{let t=JSON.parse(e);if(!Array.isArray(t?.users))return[];return t.users.map(oT).filter((r)=>r!==null)}catch{return[]}}function sy(e){return A(e,"dashboard-users.json")}function dn(e){let t=sy(e);if(!eT(t))return[];try{return sT(rT(t,"utf8"))}catch{return[]}}function vd(e,t){let r=sy(e);tT(iT(r),{recursive:!0}),nT(r,`${JSON.stringify({users:t},null,2)}
150
+ `),GE(r,384)}catch{}return n}function XE(e,t){return zE("sha256",t).update(e).digest("base64url")}function iy(e,t){if(!e)return null;let r=e.lastIndexOf(".");if(r<=0)return null;let n=e.slice(0,r),i=e.slice(r+1),o=XE(n,t),s=Buffer.from(i),c=Buffer.from(o);if(s.length!==c.length||!qE(s,c))return null;try{let u=JSON.parse(Buffer.from(n,"base64url").toString("utf8"));if(typeof u?.u!=="string"||typeof u?.exp!=="number")return null;if(u.mv!==void 0&&(!u.mv||typeof u.mv!=="object"||Array.isArray(u.mv)||Object.values(u.mv).some((a)=>!Number.isInteger(a)||a<1)))return null;if(Date.now()>=u.exp)return null;return u}catch{return null}}function Gl(e,t){if(!e)return;for(let r of e.split(";")){let n=r.indexOf("=");if(n<0)continue;if(r.slice(0,n).trim()===t)return decodeURIComponent(r.slice(n+1).trim())}return}function na(e,t={secure:!0}){let r=Math.floor((t.maxAgeMs??YE)/1000),n=[`${_a}=${encodeURIComponent(e)}`,"Path=/","HttpOnly","SameSite=Lax",`Max-Age=${r}`];if(t.secure)n.push("Secure");return n.join("; ")}function bd(e={secure:!0}){let t=[`${_a}=`,"Path=/","HttpOnly","SameSite=Lax","Max-Age=0"];if(e.secure)t.push("Secure");return t.join("; ")}import{chmodSync as ZE,existsSync as eT,mkdirSync as tT,readFileSync as rT,writeFileSync as nT}from"node:fs";import{dirname as iT}from"node:path";function oy(){return Fe("dashboard-users.json")}function Sd(e){return/^[a-z0-9][a-z0-9._-]{1,31}$/i.test(e)}function oT(e){if(!e||typeof e.username!=="string"||!Sd(e.username)||typeof e.passwordHash!=="string")return null;let t=e.role==="admin"?"admin":"member",r={};if(e.sites&&typeof e.sites==="object"){for(let[n,i]of Object.entries(e.sites))if(i==="owner"||i==="collaborator")r[n]=i}return{username:e.username,passwordHash:e.passwordHash,role:t,sites:r,name:typeof e.name==="string"?e.name:void 0,email:typeof e.email==="string"?e.email.trim().toLowerCase():void 0,createdAt:typeof e.createdAt==="string"?e.createdAt:void 0}}function sT(e){try{let t=JSON.parse(e);if(!Array.isArray(t?.users))return[];return t.users.map(oT).filter((r)=>r!==null)}catch{return[]}}function sy(e){return A(e,"dashboard-users.json")}function dn(e){let t=sy(e);if(!eT(t))return[];try{return sT(rT(t,"utf8"))}catch{return[]}}function vd(e,t){let r=sy(e);tT(iT(r),{recursive:!0}),nT(r,`${JSON.stringify({users:t},null,2)}
151
151
  `),ZE(r,384)}function ui(e,t){let r=t.trim().toLowerCase();return e.find((n)=>n.username.toLowerCase()===r)}function ay(e,t="admin"){let r=dn(e);if(r.some((s)=>s.role==="admin"))return{users:r};let n=process.env.TS_CLOUD_UI_PASSWORD?.trim()||Bl(),i={username:t,passwordHash:No(n),role:"admin",sites:{},name:"Administrator",createdAt:new Date().toISOString()},o=[...r,i];return vd(e,o),{users:o,generated:{username:t,password:n}}}function Na(e,t){let r=dn(e),n=ui(r,t.username),i=t.password?.trim()||(n?void 0:Bl()),o={username:n?.username??t.username,passwordHash:i?No(i):n.passwordHash,role:n?.role??"member",sites:t.sites,name:t.name??n?.name,email:t.email?.trim().toLowerCase()??n?.email,createdAt:n?.createdAt??new Date().toISOString()},s=n?r.map((c)=>c.username.toLowerCase()===o.username.toLowerCase()?o:c):[...r,o];return vd(e,s),{user:o,password:i}}function wd(e,t,r){let n=dn(e),i=ui(n,t);if(!i)throw Error("Authentication user was not found");let o={...i,passwordHash:r};return vd(e,n.map((s)=>s.username.toLowerCase()===i.username.toLowerCase()?o:s)),o}function Jl(e,t){let r=dn(e),n=ui(r,t);if(!n)return{ok:!1,error:`No such user: ${t}`};if(n.role==="admin"&&r.filter((i)=>i.role==="admin").length===1)return{ok:!1,error:"Cannot remove the last admin."};return vd(e,r.filter((i)=>i.username.toLowerCase()!==n.username.toLowerCase())),{ok:!0}}function oa(e){return{username:e.username,name:e.name??e.username,role:e.role,email:e.email,sites:e.sites,siteCount:Object.keys(e.sites).length,createdAt:e.createdAt}}var aT={username:"local",passwordHash:"",role:"admin",sites:{},name:"Local (auth disabled)"};function cy(e){let{cwd:t,enabled:r,secret:n,authorization:i,authentication:o}=e,s=(u)=>{if(!o)return;let a=Gl(u.headers.get("cookie"),_a);return a?.startsWith("v2.")?o.verifySessionToken(a):void 0},c=(u)=>{let a=i.store.getActorByExternalId("user",`dashboard:${u.username.toLowerCase()}`),f=a?i.store.getMembershipForActor(i.organizationId,a.id):void 0;return{actor:a,membership:f}};return{enabled:r,resolveUser(u){if(!r)return aT;let a=Gl(u.headers.get("cookie"),_a),f=s(u),T=f?void 0:iy(a,n),R=f?.identity.username??T?.u;if(!R)return null;let D=ui(dn(t),R);if(!D)return null;let{membership:W}=c(D);if(!W||W.status!=="active"||!f&&T?.mv?.[i.organizationId]!==W.sessionVersion)return null;if(!W.lastActiveAt||Date.now()-new Date(W.lastActiveAt).getTime()>300000)i.store.touchMembership(W.id);return D},resolveSession(u){return s(u)?.session??null},check(u,a,f,T){if(!r)return{ok:!0};if(!f)return{ok:!1,status:401,error:"Sign in to continue.",unauthenticated:!0};let R=ql(u.method,a);if(R.anyUser)return{ok:!0};if(R.siteFrom==="body"&&!T)return{ok:!1,status:400,error:"This request must name a site."};let{membership:D}=c(f);if(!D)return{ok:!1,status:401,error:"Sign in to continue.",unauthenticated:!0};let W=R.scope==="organization"?{organizationId:i.organizationId}:i.store.resolveAuthorizationTarget(i.organizationId,{type:"project",id:i.projectId});if(R.scope==="site"){let ee=new URL(u.url).searchParams.get("env")??i.defaultEnvironment,ne=i.store.getEnvironmentBySlug(i.projectId,ee),he=i.store.listResources(i.projectId,ne?.id).find((te)=>te.kind==="application"&&te.slug===T);W=he?i.store.resolveAuthorizationTarget(i.organizationId,{type:"resource",id:he.id}):void 0}if(!(W?re({membership:D,grants:i.store.listGrants(D.id),capability:R.capability,target:W}):{allowed:!1}).allowed)return{ok:!1,status:403,error:"You do not have access to this."};return{ok:!0}}}}async function dy(e,t){if(ql(e.method,t).siteFrom!=="body")return;try{let n=await e.clone().json();return String(n?.name??"").trim()||void 0}catch{return}}import{createHash as cT}from"node:crypto";function uy(e,t,r){for(let n of r){let i=gr(t.store,n);if(e.getIdentityByActor(i.id))continue;e.createIdentity({actorId:i.id,username:n.username,email:n.email,emailVerified:!!n.email,passwordHash:n.passwordHash,requiresPasswordUpgrade:!0})}}function dT(e,t,r){let n=r.split("@")[0].toLowerCase().replace(/[^a-z0-9._-]/g,"-").replace(/^[^a-z0-9]+/,"").slice(0,24),i=/^[a-z0-9][a-z0-9._-]{1,31}$/.test(n)?n:"sso-user";if(!e.getIdentityByUsername(i)&&!ui(t,i))return i;let o=cT("sha256").update(r).digest("hex").slice(0,7);return`${i.slice(0,24)}-${o}`}function ly(e,t,r,n){if(n.provider.organizationId!==t.organization.id)throw Error("OIDC provider is not configured for this organization");let i=e.getOidcSubject(n.provider.id,n.subject),o=i?e.getIdentity(i.identityId):e.getIdentityByEmail(n.email);if(o?.disabledAt)throw Error("OIDC identity is disabled");if(!i&&o&&!o.emailVerifiedAt)throw Error("OIDC cannot automatically link an unverified local email address");let s=dn(r),c=!1,u=o?ui(s,o.username):void 0;if(o&&!u)throw Error("OIDC identity has no dashboard user");if(!o){let T=dT(e,s,n.email);u=Na(r,{username:T,name:n.name,email:n.email,sites:{}}).user;let D=gr(t.store,u);o=e.createIdentity({actorId:D.id,username:u.username,email:n.email,emailVerified:!0,passwordHash:u.passwordHash}),c=!0}else if(o.email!==n.email)o=e.setVerifiedEmail(o.id,n.email);let a=t.store.getActor(o.actorId);if(!a)throw Error("OIDC identity actor was not found");let f=t.store.getMembershipForActor(t.organization.id,a.id);if(f?.status==="revoked")throw Error("OIDC organization membership is revoked");if(!f)t.store.createMembership({organizationId:t.organization.id,actorId:a.id,roleTemplate:n.provider.defaultRole,scope:{type:"organization"},source:"manual"});return e.linkOidcSubject(n.provider.id,o.id,n.subject,n.email),{identity:o,user:u,provisioned:c}}function py(e,t,r){let n=t.store.getMembershipForActor(t.organization.id,r.actorId);if(!n||n.status!=="active"||n.roleTemplate==="owner"||!r.emailVerifiedAt||!r.email)return!1;let i=r.email.split("@")[1]?.toLowerCase();return e.listOidcProviders(t.organization.id).some((o)=>o.enforceSso&&!!i&&o.allowedDomains.includes(i))}function uT(e){return e.replace(/[&<>"']/g,(t)=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}function gy(e=!1,t=[]){let r=e?"/serverless":"/",n=t.map((o)=>`<a class="sso-button" href="/auth/oidc/${encodeURIComponent(o.slug)}/start?return=${encodeURIComponent(r)}">Continue with ${uT(o.name)}</a>`).join("");return`<!doctype html>
152
152
  <html lang="en">
153
153
  <head>
@@ -437,7 +437,7 @@ export type ConfigOf = Config
437
437
  },
438
438
  ${u}`}class Ql{client;region;constructor(e="us-east-1"){this.region=e,this.client=new p}async getTraceSummaries(e){let t={StartTime:Math.floor(e.startTime.getTime()/1000),EndTime:Math.floor(e.endTime.getTime()/1000),TimeRangeType:"Event",Sampling:!1};if(e.filterExpression)t.FilterExpression=e.filterExpression;if(e.nextToken)t.NextToken=e.nextToken;let r=await this.client.request({service:"xray",region:this.region,method:"POST",path:"/TraceSummaries",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});return{summaries:r?.TraceSummaries??[],nextToken:r?.NextToken}}async batchGetTraces(e){if(!e.length)return[];return(await this.client.request({service:"xray",region:this.region,method:"POST",path:"/Traces",headers:{"Content-Type":"application/json"},body:JSON.stringify({TraceIds:e.slice(0,5)})}))?.Traces??[]}}var xy=65536;function Ur(e){return e.length<=xy?e:`${e.slice(0,xy)}
439
439
 
440
- [output truncated]`}function Xl(e,t){return e.environments?.[t]?.app}function Zl(e,t,r){let n=[],i=Xl(e,t);n.push({id:"redeploy",label:"Redeploy current build",group:"deploy",target:"app",mutates:!0,confirm:"redeploy"}),n.push({id:"rollback",label:"Roll back to previous build",group:"deploy",target:"app",mutates:!0,confirm:"rollback",danger:!0});let o=r.maintenance?.enabled;if(o!==!0)n.push({id:"maintenance:on",label:"Enable maintenance mode",group:"maintenance",target:"app",mutates:!0,confirm:"maintenance",danger:!0});if(o!==!1)n.push({id:"maintenance:off",label:"Disable maintenance mode",group:"maintenance",target:"app",mutates:!0,confirm:"live"});if(i?.assets||r.assetsInfo)n.push({id:"assets:invalidate",label:"Invalidate CDN cache",group:"assets",target:"assets",mutates:!0,confirm:"invalidate"});if(i?.database?.connection==="aurora-serverless")n.push({id:"db:scale",label:"Scale Aurora capacity",group:"database",target:"database",mutates:!0,confirm:"scale",inputs:[{name:"min",label:"Min ACUs",placeholder:String(i.database.minCapacity??0.5)},{name:"max",label:"Max ACUs",placeholder:String(i.database.maxCapacity??4)}]});for(let s of r.queues??[]){let c=String(s?.name??"").trim();if(c&&/^[A-Za-z0-9_-]+$/.test(c))n.push({id:`queue:purge:${c}`,label:`Purge queue (${c})`,group:"queue",target:c,mutates:!0,confirm:c,danger:!0})}return n}function Dy(e,t,r,n){return Zl(t,r,n).find((i)=>i.id===e)}async function ET(e,t,r){try{let n=new v(r),{Stacks:i}=await n.describeStacks({stackName:xe(e,t)}),o={};for(let u of i?.[0]?.Outputs??[])if(u.OutputKey)o[u.OutputKey]=u.OutputValue??"";let s=o.AssetsCdnDomain;if(!s)return null;return(await new E(r).findDistributionByDomain(s))?.Id??null}catch{return null}}async function Oy(e,t,r,n={}){try{if(r.id==="redeploy")return await Os(e,t),{operation:r.id,command:"serverless redeploy",ok:!0,stdout:"Redeploy complete."};if(r.id==="rollback")return await $s(e,t),{operation:r.id,command:"serverless rollback",ok:!0,stdout:"Rollback complete."};if(r.id==="maintenance:on")return await Po(e,t,!0),{operation:r.id,command:"maintenance on",ok:!0,stdout:"Application is now in maintenance mode."};if(r.id==="maintenance:off")return await Po(e,t,!1),{operation:r.id,command:"maintenance off",ok:!0,stdout:"Application is live."};if(r.id==="db:scale"){let i=Number(n.min),o=Number(n.max);if(!Number.isFinite(i)||!Number.isFinite(o)||i<=0||o<i)return{operation:r.id,ok:!1,error:"Provide valid Aurora capacities (0 < min ≤ max)."};return await Ls(e,t,i,o),{operation:r.id,command:`db:scale ${i}-${o} ACU`,ok:!0,stdout:`Scaling applied (${i}-${o} ACUs); takes effect shortly.`}}if(r.id==="assets:invalidate"){let i=await z(e,t),o=await ET(e,t,i.region);if(!o)return{operation:r.id,ok:!1,error:"Could not resolve the asset CloudFront distribution for this environment."};let c=await new E(i.region).invalidateAll(o);return{operation:r.id,command:`cloudfront invalidate ${o} /*`,ok:!0,stdout:`Invalidation ${c?.Id??"created"} for ${o} (/*).`}}if(r.group==="queue"&&r.id.startsWith("queue:purge:")){let i=r.target,o=await z(e,t),s=new V(o.region),c=`${o.slug}-${t}-${i}`,{QueueUrl:u}=await s.getQueueUrl(c);return await s.purgeQueue(u),{operation:r.id,command:`sqs purge ${c}`,ok:!0,stdout:`Purged queue ${c}.`}}return{operation:r.id,ok:!1,error:"Unknown or unavailable serverless operation."}}catch(i){return{operation:r.id,ok:!1,error:Ur(i?.message??String(i))}}}async function _y(e,t,r){let n=r.trim();if(!n)return{operation:"command",ok:!1,error:"A command is required."};try{let i=await Ft(e,t,n);return{operation:"command",command:n,ok:!0,stdout:Ur(i||"(no output)")}}catch(i){return{operation:"command",command:n,ok:!1,error:Ur(i?.message??String(i))}}}var ep="No dead-letter queue is provisioned for this environment.";async function tp(e,t,r){try{let{QueueUrl:n}=await e.getQueueUrl(`${t}-${r}-dlq`);return n}catch{return null}}async function Ny(e,t,r=10){try{let n=await z(e,t),i=new V(n.region),o=await tp(i,n.slug,t);if(!o)return{ok:!1,messages:[],error:ep};return{ok:!0,messages:((await i.receiveMessages({queueUrl:o,maxMessages:Math.min(10,Math.max(1,r)),waitTimeSeconds:1,visibilityTimeout:2})).Messages??[]).map((u)=>({id:u.MessageId,receiptHandle:u.ReceiptHandle,body:Ur(String(u.Body??""))}))}}catch(n){return{ok:!1,messages:[],error:Ur(n?.message??String(n))}}}async function My(e,t,r={}){try{let n=await z(e,t),i=Xl(e,t),s=(i?Jt(i,n.slug,t):[]).map((D)=>D.name.replace(`${n.slug}-${t}-`,"")),c=r.targetQueue&&s.includes(r.targetQueue)?r.targetQueue:s[0];if(!c)return{operation:"dlq:redrive",ok:!1,error:"No source queue is configured to redrive into."};let u=new V(n.region),a=await tp(u,n.slug,t);if(!a)return{operation:"dlq:redrive",ok:!1,error:ep};let{QueueUrl:f}=await u.getQueueUrl(`${n.slug}-${t}-${c}`),T=Math.min(50,Math.max(1,r.max??10)),R=0;while(R<T){let W=(await u.receiveMessages({queueUrl:a,maxMessages:Math.min(10,T-R),waitTimeSeconds:1,visibilityTimeout:30})).Messages??[];if(!W.length)break;for(let Y of W)await u.sendMessage({queueUrl:f,messageBody:String(Y.Body??"")}),await u.deleteMessage(a,Y.ReceiptHandle),R++}return{operation:"dlq:redrive",command:`redrive → ${c}`,ok:!0,stdout:`Moved ${R} message(s) from the DLQ to ${c}.`}}catch(n){return{operation:"dlq:redrive",ok:!1,error:Ur(n?.message??String(n))}}}async function $y(e,t){try{let r=await z(e,t),n=new V(r.region),i=await tp(n,r.slug,t);if(!i)return{operation:"dlq:purge",ok:!1,error:ep};return await n.purgeQueue(i),{operation:"dlq:purge",command:"sqs purge dlq",ok:!0,stdout:"Dead-letter queue purged."}}catch(r){return{operation:"dlq:purge",ok:!1,error:Ur(r?.message??String(r))}}}function Ly(e,t){let r=Xl(e,t);if(!r?.secrets)return[];return Array.isArray(r.secrets)?r.secrets.map((n)=>({key:n.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),secretId:n})):Object.entries(r.secrets).map(([n,i])=>({key:n,secretId:String(i)}))}async function By(e,t,r,n){if(!r.trim())return{operation:"secret:set",ok:!1,error:"A secret id is required."};try{let i=await z(e,t),o=new K(i.region);try{await o.putSecretValue({SecretId:r,SecretString:n})}catch{await o.createSecret({Name:r,SecretString:n})}return{operation:"secret:set",command:`secret set ${r}`,ok:!0,stdout:`Secret ${r} updated. Redeploy to apply it to the functions.`}}catch(i){return{operation:"secret:set",ok:!1,error:Ur(i?.message??String(i))}}}async function Fy(e,t,r){if(!r.trim())return{operation:"secret:delete",ok:!1,error:"A secret id is required."};try{let n=await z(e,t);return await new K(n.region).deleteSecret({SecretId:r,RecoveryWindowInDays:7}),{operation:"secret:delete",command:`secret delete ${r}`,ok:!0,stdout:`Secret ${r} scheduled for deletion (recoverable for 7 days).`}}catch(n){return{operation:"secret:delete",ok:!1,error:Ur(n?.message??String(n))}}}var TT=new Set(["http","queue","cli"]);async function jy(e,t,r,n){if(!TT.has(r))return{operation:"function:config",ok:!1,error:`Unknown function mode '${r}'.`};let i=n.memory==null?void 0:Number(n.memory),o=n.timeout==null?void 0:Number(n.timeout);if(i!=null&&(!Number.isInteger(i)||i<128||i>10240))return{operation:"function:config",ok:!1,error:"Memory must be an integer between 128 and 10240 MB."};if(o!=null&&(!Number.isInteger(o)||o<1||o>900))return{operation:"function:config",ok:!1,error:"Timeout must be an integer between 1 and 900 seconds."};if(i==null&&o==null)return{operation:"function:config",ok:!1,error:"Provide a memory and/or timeout value."};try{let s=await z(e,t),c=new I(s.region),u=`${s.slug}-${t}-${r}`;await c.updateFunctionConfiguration({FunctionName:u,...i!=null?{MemorySize:i}:{},...o!=null?{Timeout:o}:{}});let a=[i!=null?`${i} MB`:"",o!=null?`${o}s`:""].filter(Boolean).join(", ");return{operation:"function:config",command:`update ${u} (${a})`,ok:!0,stdout:`Updated ${u}: ${a}.`}}catch(s){return{operation:"function:config",ok:!1,error:Ur(s?.message??String(s))}}}var Yl=[{key:"http-errors",label:"HTTP function errors",namespace:"AWS/Lambda",metricName:"Errors",statistic:"Sum",comparison:"GreaterThanThreshold",fnMode:"http",unit:"errors / 5 min"},{key:"http-throttles",label:"HTTP function throttles",namespace:"AWS/Lambda",metricName:"Throttles",statistic:"Sum",comparison:"GreaterThanThreshold",fnMode:"http",unit:"throttles / 5 min"},{key:"http-duration",label:"HTTP function duration (avg)",namespace:"AWS/Lambda",metricName:"Duration",statistic:"Average",comparison:"GreaterThanThreshold",fnMode:"http",unit:"ms"},{key:"http-concurrency",label:"HTTP concurrent executions",namespace:"AWS/Lambda",metricName:"ConcurrentExecutions",statistic:"Maximum",comparison:"GreaterThanThreshold",fnMode:"http",unit:"concurrent"},{key:"queue-errors",label:"Queue function errors",namespace:"AWS/Lambda",metricName:"Errors",statistic:"Sum",comparison:"GreaterThanThreshold",fnMode:"queue",unit:"errors / 5 min"}];function AT(e){return Yl.find((t)=>t.key===e)}async function Uy(e,t){try{let r=await z(e,t);return{ok:!0,alarms:await new G(r.region).describeAlarms({AlarmNamePrefix:`${r.slug}-${t}-`,MaxRecords:100}),presets:Yl}}catch(r){return{ok:!1,alarms:[],presets:Yl,error:Ur(r?.message??String(r))}}}async function zy(e,t,r,n){let i=AT(r);if(!i)return{operation:"alarm:create",ok:!1,error:`Unknown alarm metric '${r}'.`};if(!Number.isFinite(n)||n<0)return{operation:"alarm:create",ok:!1,error:"Provide a non-negative threshold."};try{let o=await z(e,t),s=new G(o.region),c=`${o.slug}-${t}-${i.key}`,u=i.fnMode?[{Name:"FunctionName",Value:`${o.slug}-${t}-${i.fnMode}`}]:[];return await s.putMetricAlarm({AlarmName:c,Namespace:i.namespace,MetricName:i.metricName,ComparisonOperator:i.comparison,Threshold:n,EvaluationPeriods:1,Period:300,Statistic:i.statistic,Dimensions:u,AlarmDescription:`ts-cloud: ${i.label} > ${n} ${i.unit}`}),{operation:"alarm:create",command:`alarm ${c}`,ok:!0,stdout:`Alarm ${c} armed at ${n} ${i.unit}.`}}catch(o){return{operation:"alarm:create",ok:!1,error:Ur(o?.message??String(o))}}}async function Vy(e,t,r){try{let n=await z(e,t);if(!r.startsWith(`${n.slug}-${t}-`))return{operation:"alarm:delete",ok:!1,error:"Refusing to delete an alarm outside this environment."};return await new G(n.region).deleteAlarms([r]),{operation:"alarm:delete",command:`delete alarm ${r}`,ok:!0,stdout:`Alarm ${r} deleted.`}}catch(n){return{operation:"alarm:delete",ok:!1,error:Ur(n?.message??String(n))}}}function kT(e){let t=e.HasFault?"fault":e.HasError?"error":e.HasThrottle?"throttle":"ok";return{id:String(e.Id??""),timestamp:Number.isFinite(Number(e.StartTime))?new Date(Number(e.StartTime)*1000).toISOString():void 0,durationMs:Math.round((e.Duration??0)*1000),responseMs:Math.round((e.ResponseTime??0)*1000),status:t,method:e.Http?.HttpMethod??"-",url:e.Http?.HttpURL??"-",httpStatus:e.Http?.HttpStatus??0}}async function Cd(e,t,r=30){try{let n=await z(e,t),i=new Ql(n.region),o=new Date,s=new Date(o.getTime()-Math.min(360,Math.max(1,r))*60000),c=`${n.slug}-${t}-http`,u=await i.getTraceSummaries({startTime:s,endTime:o,filterExpression:`service("${c}")`});if(!u.summaries.length)u=await i.getTraceSummaries({startTime:s,endTime:o});return{ok:!0,traces:u.summaries.slice(0,100).map(kT)}}catch(n){return{ok:!1,traces:[],error:Ur(n?.message??String(n))}}}async function rp(e,t,r){try{let n=await z(e,t),i=`${n.slug}-${t}-scheduler`;if(r==="run"){let s=await Ft(e,t,"schedule:run");return{operation:"scheduler:run",command:"schedule:run",ok:!0,stdout:Ur(s||"Scheduler run triggered.")}}let o=new be(n.region);if(r==="enable")await o.enableRule({Name:i});else await o.disableRule({Name:i});return{operation:`scheduler:${r}`,command:`${r} ${i}`,ok:!0,stdout:`Scheduler rule ${i} ${r}d.`}}catch(n){return{operation:`scheduler:${r}`,ok:!1,error:Ur(n?.message??String(n))}}}function kn(e){let t=Ed(e.name),r=ip(e.configText);if(xT(e.configText,r.start,r.end,t))throw Error(`Site '${t}' already exists in cloud.config.ts`);let n=PT({...e,name:t}),i=e.configText.slice(0,r.end).trimEnd(),o=e.configText.slice(r.end),s=i.endsWith("{")?`
440
+ [output truncated]`}function Xl(e,t){return e.environments?.[t]?.app}function Zl(e,t,r){let n=[],i=Xl(e,t);n.push({id:"redeploy",label:"Redeploy current build",group:"deploy",target:"app",mutates:!0,confirm:"redeploy"}),n.push({id:"rollback",label:"Roll back to previous build",group:"deploy",target:"app",mutates:!0,confirm:"rollback",danger:!0});let o=r.maintenance?.enabled;if(o!==!0)n.push({id:"maintenance:on",label:"Enable maintenance mode",group:"maintenance",target:"app",mutates:!0,confirm:"maintenance",danger:!0});if(o!==!1)n.push({id:"maintenance:off",label:"Disable maintenance mode",group:"maintenance",target:"app",mutates:!0,confirm:"live"});if(i?.assets||r.assetsInfo)n.push({id:"assets:invalidate",label:"Invalidate CDN cache",group:"assets",target:"assets",mutates:!0,confirm:"invalidate"});if(i?.database?.connection==="aurora-serverless")n.push({id:"db:scale",label:"Scale Aurora capacity",group:"database",target:"database",mutates:!0,confirm:"scale",inputs:[{name:"min",label:"Min ACUs",placeholder:String(i.database.minCapacity??0.5)},{name:"max",label:"Max ACUs",placeholder:String(i.database.maxCapacity??4)}]});for(let s of r.queues??[]){let c=String(s?.name??"").trim();if(c&&/^[A-Za-z0-9_-]+$/.test(c))n.push({id:`queue:purge:${c}`,label:`Purge queue (${c})`,group:"queue",target:c,mutates:!0,confirm:c,danger:!0})}return n}function Dy(e,t,r,n){return Zl(t,r,n).find((i)=>i.id===e)}async function ET(e,t,r){try{let n=new v(r),{Stacks:i}=await n.describeStacks({stackName:xe(e,t)}),o={};for(let u of i?.[0]?.Outputs??[])if(u.OutputKey)o[u.OutputKey]=u.OutputValue??"";let s=o.AssetsCdnDomain;if(!s)return null;return(await new E(r).findDistributionByDomain(s))?.Id??null}catch{return null}}async function Oy(e,t,r,n={}){try{if(r.id==="redeploy")return await Os(e,t),{operation:r.id,command:"serverless redeploy",ok:!0,stdout:"Redeploy complete."};if(r.id==="rollback")return await $s(e,t),{operation:r.id,command:"serverless rollback",ok:!0,stdout:"Rollback complete."};if(r.id==="maintenance:on")return await Po(e,t,!0),{operation:r.id,command:"maintenance on",ok:!0,stdout:"Application is now in maintenance mode."};if(r.id==="maintenance:off")return await Po(e,t,!1),{operation:r.id,command:"maintenance off",ok:!0,stdout:"Application is live."};if(r.id==="db:scale"){let i=Number(n.min),o=Number(n.max);if(!Number.isFinite(i)||!Number.isFinite(o)||i<=0||o<i)return{operation:r.id,ok:!1,error:"Provide valid Aurora capacities (0 < min ≤ max)."};return await Ls(e,t,i,o),{operation:r.id,command:`db:scale ${i}-${o} ACU`,ok:!0,stdout:`Scaling applied (${i}-${o} ACUs); takes effect shortly.`}}if(r.id==="assets:invalidate"){let i=await z(e,t),o=await ET(e,t,i.region);if(!o)return{operation:r.id,ok:!1,error:"Could not resolve the asset CloudFront distribution for this environment."};let c=await new E(i.region).invalidateAll(o);return{operation:r.id,command:`cloudfront invalidate ${o} /*`,ok:!0,stdout:`Invalidation ${c?.Id??"created"} for ${o} (/*).`}}if(r.group==="queue"&&r.id.startsWith("queue:purge:")){let i=r.target,o=await z(e,t),s=new V(o.region),c=`${o.slug}-${t}-${i}`,{QueueUrl:u}=await s.getQueueUrl(c);return await s.purgeQueue(u),{operation:r.id,command:`sqs purge ${c}`,ok:!0,stdout:`Purged queue ${c}.`}}return{operation:r.id,ok:!1,error:"Unknown or unavailable serverless operation."}}catch(i){return{operation:r.id,ok:!1,error:Ur(i?.message??String(i))}}}async function _y(e,t,r){let n=r.trim();if(!n)return{operation:"command",ok:!1,error:"A command is required."};try{let i=await Bt(e,t,n);return{operation:"command",command:n,ok:!0,stdout:Ur(i||"(no output)")}}catch(i){return{operation:"command",command:n,ok:!1,error:Ur(i?.message??String(i))}}}var ep="No dead-letter queue is provisioned for this environment.";async function tp(e,t,r){try{let{QueueUrl:n}=await e.getQueueUrl(`${t}-${r}-dlq`);return n}catch{return null}}async function Ny(e,t,r=10){try{let n=await z(e,t),i=new V(n.region),o=await tp(i,n.slug,t);if(!o)return{ok:!1,messages:[],error:ep};return{ok:!0,messages:((await i.receiveMessages({queueUrl:o,maxMessages:Math.min(10,Math.max(1,r)),waitTimeSeconds:1,visibilityTimeout:2})).Messages??[]).map((u)=>({id:u.MessageId,receiptHandle:u.ReceiptHandle,body:Ur(String(u.Body??""))}))}}catch(n){return{ok:!1,messages:[],error:Ur(n?.message??String(n))}}}async function My(e,t,r={}){try{let n=await z(e,t),i=Xl(e,t),s=(i?Jt(i,n.slug,t):[]).map((D)=>D.name.replace(`${n.slug}-${t}-`,"")),c=r.targetQueue&&s.includes(r.targetQueue)?r.targetQueue:s[0];if(!c)return{operation:"dlq:redrive",ok:!1,error:"No source queue is configured to redrive into."};let u=new V(n.region),a=await tp(u,n.slug,t);if(!a)return{operation:"dlq:redrive",ok:!1,error:ep};let{QueueUrl:f}=await u.getQueueUrl(`${n.slug}-${t}-${c}`),T=Math.min(50,Math.max(1,r.max??10)),R=0;while(R<T){let W=(await u.receiveMessages({queueUrl:a,maxMessages:Math.min(10,T-R),waitTimeSeconds:1,visibilityTimeout:30})).Messages??[];if(!W.length)break;for(let Y of W)await u.sendMessage({queueUrl:f,messageBody:String(Y.Body??"")}),await u.deleteMessage(a,Y.ReceiptHandle),R++}return{operation:"dlq:redrive",command:`redrive → ${c}`,ok:!0,stdout:`Moved ${R} message(s) from the DLQ to ${c}.`}}catch(n){return{operation:"dlq:redrive",ok:!1,error:Ur(n?.message??String(n))}}}async function $y(e,t){try{let r=await z(e,t),n=new V(r.region),i=await tp(n,r.slug,t);if(!i)return{operation:"dlq:purge",ok:!1,error:ep};return await n.purgeQueue(i),{operation:"dlq:purge",command:"sqs purge dlq",ok:!0,stdout:"Dead-letter queue purged."}}catch(r){return{operation:"dlq:purge",ok:!1,error:Ur(r?.message??String(r))}}}function Ly(e,t){let r=Xl(e,t);if(!r?.secrets)return[];return Array.isArray(r.secrets)?r.secrets.map((n)=>({key:n.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),secretId:n})):Object.entries(r.secrets).map(([n,i])=>({key:n,secretId:String(i)}))}async function By(e,t,r,n){if(!r.trim())return{operation:"secret:set",ok:!1,error:"A secret id is required."};try{let i=await z(e,t),o=new K(i.region);try{await o.putSecretValue({SecretId:r,SecretString:n})}catch{await o.createSecret({Name:r,SecretString:n})}return{operation:"secret:set",command:`secret set ${r}`,ok:!0,stdout:`Secret ${r} updated. Redeploy to apply it to the functions.`}}catch(i){return{operation:"secret:set",ok:!1,error:Ur(i?.message??String(i))}}}async function Fy(e,t,r){if(!r.trim())return{operation:"secret:delete",ok:!1,error:"A secret id is required."};try{let n=await z(e,t);return await new K(n.region).deleteSecret({SecretId:r,RecoveryWindowInDays:7}),{operation:"secret:delete",command:`secret delete ${r}`,ok:!0,stdout:`Secret ${r} scheduled for deletion (recoverable for 7 days).`}}catch(n){return{operation:"secret:delete",ok:!1,error:Ur(n?.message??String(n))}}}var TT=new Set(["http","queue","cli"]);async function jy(e,t,r,n){if(!TT.has(r))return{operation:"function:config",ok:!1,error:`Unknown function mode '${r}'.`};let i=n.memory==null?void 0:Number(n.memory),o=n.timeout==null?void 0:Number(n.timeout);if(i!=null&&(!Number.isInteger(i)||i<128||i>10240))return{operation:"function:config",ok:!1,error:"Memory must be an integer between 128 and 10240 MB."};if(o!=null&&(!Number.isInteger(o)||o<1||o>900))return{operation:"function:config",ok:!1,error:"Timeout must be an integer between 1 and 900 seconds."};if(i==null&&o==null)return{operation:"function:config",ok:!1,error:"Provide a memory and/or timeout value."};try{let s=await z(e,t),c=new I(s.region),u=`${s.slug}-${t}-${r}`;await c.updateFunctionConfiguration({FunctionName:u,...i!=null?{MemorySize:i}:{},...o!=null?{Timeout:o}:{}});let a=[i!=null?`${i} MB`:"",o!=null?`${o}s`:""].filter(Boolean).join(", ");return{operation:"function:config",command:`update ${u} (${a})`,ok:!0,stdout:`Updated ${u}: ${a}.`}}catch(s){return{operation:"function:config",ok:!1,error:Ur(s?.message??String(s))}}}var Yl=[{key:"http-errors",label:"HTTP function errors",namespace:"AWS/Lambda",metricName:"Errors",statistic:"Sum",comparison:"GreaterThanThreshold",fnMode:"http",unit:"errors / 5 min"},{key:"http-throttles",label:"HTTP function throttles",namespace:"AWS/Lambda",metricName:"Throttles",statistic:"Sum",comparison:"GreaterThanThreshold",fnMode:"http",unit:"throttles / 5 min"},{key:"http-duration",label:"HTTP function duration (avg)",namespace:"AWS/Lambda",metricName:"Duration",statistic:"Average",comparison:"GreaterThanThreshold",fnMode:"http",unit:"ms"},{key:"http-concurrency",label:"HTTP concurrent executions",namespace:"AWS/Lambda",metricName:"ConcurrentExecutions",statistic:"Maximum",comparison:"GreaterThanThreshold",fnMode:"http",unit:"concurrent"},{key:"queue-errors",label:"Queue function errors",namespace:"AWS/Lambda",metricName:"Errors",statistic:"Sum",comparison:"GreaterThanThreshold",fnMode:"queue",unit:"errors / 5 min"}];function AT(e){return Yl.find((t)=>t.key===e)}async function Uy(e,t){try{let r=await z(e,t);return{ok:!0,alarms:await new G(r.region).describeAlarms({AlarmNamePrefix:`${r.slug}-${t}-`,MaxRecords:100}),presets:Yl}}catch(r){return{ok:!1,alarms:[],presets:Yl,error:Ur(r?.message??String(r))}}}async function zy(e,t,r,n){let i=AT(r);if(!i)return{operation:"alarm:create",ok:!1,error:`Unknown alarm metric '${r}'.`};if(!Number.isFinite(n)||n<0)return{operation:"alarm:create",ok:!1,error:"Provide a non-negative threshold."};try{let o=await z(e,t),s=new G(o.region),c=`${o.slug}-${t}-${i.key}`,u=i.fnMode?[{Name:"FunctionName",Value:`${o.slug}-${t}-${i.fnMode}`}]:[];return await s.putMetricAlarm({AlarmName:c,Namespace:i.namespace,MetricName:i.metricName,ComparisonOperator:i.comparison,Threshold:n,EvaluationPeriods:1,Period:300,Statistic:i.statistic,Dimensions:u,AlarmDescription:`ts-cloud: ${i.label} > ${n} ${i.unit}`}),{operation:"alarm:create",command:`alarm ${c}`,ok:!0,stdout:`Alarm ${c} armed at ${n} ${i.unit}.`}}catch(o){return{operation:"alarm:create",ok:!1,error:Ur(o?.message??String(o))}}}async function Vy(e,t,r){try{let n=await z(e,t);if(!r.startsWith(`${n.slug}-${t}-`))return{operation:"alarm:delete",ok:!1,error:"Refusing to delete an alarm outside this environment."};return await new G(n.region).deleteAlarms([r]),{operation:"alarm:delete",command:`delete alarm ${r}`,ok:!0,stdout:`Alarm ${r} deleted.`}}catch(n){return{operation:"alarm:delete",ok:!1,error:Ur(n?.message??String(n))}}}function kT(e){let t=e.HasFault?"fault":e.HasError?"error":e.HasThrottle?"throttle":"ok";return{id:String(e.Id??""),timestamp:Number.isFinite(Number(e.StartTime))?new Date(Number(e.StartTime)*1000).toISOString():void 0,durationMs:Math.round((e.Duration??0)*1000),responseMs:Math.round((e.ResponseTime??0)*1000),status:t,method:e.Http?.HttpMethod??"-",url:e.Http?.HttpURL??"-",httpStatus:e.Http?.HttpStatus??0}}async function Cd(e,t,r=30){try{let n=await z(e,t),i=new Ql(n.region),o=new Date,s=new Date(o.getTime()-Math.min(360,Math.max(1,r))*60000),c=`${n.slug}-${t}-http`,u=await i.getTraceSummaries({startTime:s,endTime:o,filterExpression:`service("${c}")`});if(!u.summaries.length)u=await i.getTraceSummaries({startTime:s,endTime:o});return{ok:!0,traces:u.summaries.slice(0,100).map(kT)}}catch(n){return{ok:!1,traces:[],error:Ur(n?.message??String(n))}}}async function rp(e,t,r){try{let n=await z(e,t),i=`${n.slug}-${t}-scheduler`;if(r==="run"){let s=await Bt(e,t,"schedule:run");return{operation:"scheduler:run",command:"schedule:run",ok:!0,stdout:Ur(s||"Scheduler run triggered.")}}let o=new be(n.region);if(r==="enable")await o.enableRule({Name:i});else await o.disableRule({Name:i});return{operation:`scheduler:${r}`,command:`${r} ${i}`,ok:!0,stdout:`Scheduler rule ${i} ${r}d.`}}catch(n){return{operation:`scheduler:${r}`,ok:!1,error:Ur(n?.message??String(n))}}}function kn(e){let t=Ed(e.name),r=ip(e.configText);if(xT(e.configText,r.start,r.end,t))throw Error(`Site '${t}' already exists in cloud.config.ts`);let n=PT({...e,name:t}),i=e.configText.slice(0,r.end).trimEnd(),o=e.configText.slice(r.end),s=i.endsWith("{")?`
441
441
  `:i.endsWith(",")?`
442
442
 
443
443
  `:`,
@@ -474,29 +474,29 @@ data: ${JSON.stringify({cursor:o,at:new Date().toISOString()})}
474
474
  ${c}
475
475
  ${u}`);return null}return n}catch(i){if(n)fs(n,{recursive:!0,force:!0});if(process.env.TSCLOUD_DASHBOARD_VERBOSE)console.warn(`ts-cloud dashboard: live UI build errored; serving the pre-built UI. ${i.message}`);return null}}function fA(e){let t=e.infrastructure?.compute?.managedServices?JSON.parse(JSON.stringify(e.infrastructure.compute.managedServices)):void 0;if(t?.vitess?.password)t.vitess.password="";return{project:{name:e.project?.name,slug:e.project?.slug,region:e.project?.region},provider:e.provider,environments:Object.keys(e.environments??{}),compute:e.infrastructure?.compute?{provider:e.infrastructure.compute.provider,runtime:e.infrastructure.compute.runtime,webServer:e.infrastructure.compute.webServer,proxy:e.infrastructure.compute.proxy?{engine:e.infrastructure.compute.proxy.engine,onDemandTls:e.infrastructure.compute.proxy.onDemandTls,cdn:!!e.infrastructure.compute.proxy.cdn}:void 0,managedServices:t,sshKeys:_t(da(e)).map((r)=>({name:r.name,type:r.type,fingerprint:r.fingerprint,added:r.added}))}:void 0,sites:Object.fromEntries(Object.entries(e.sites??{}).map(([r,n])=>[r,{domain:n.domain,path:n.path,type:n.type,deploy:n.deploy,root:n.root,port:n.port,ssl:n.ssl}]))}}function wb(e){return[{id:"status",label:"Refresh Cloud Status",description:"Runs the local ts-cloud status checks against configured providers.",command:["status","--env",e],mutates:!1},{id:"doctor",label:"Run Doctor",description:"Checks local tooling, credentials, and provider access.",command:["doctor"],mutates:!1},{id:"security-scan",label:"Security Scan",description:"Runs the pre-deploy scanner from this checkout.",command:["deploy:security-scan","--source",".","--fail-on","critical"],mutates:!1},{id:"deploy",label:"Deploy Environment",description:"Deploys the selected environment from the local checkout.",command:["deploy","--env",e,"--yes"],mutates:!0,confirm:"deploy"}]}function hA(e,t){return wb(t).find((r)=>r.id===e)}function gb(e){if(e.length<=db)return e;return`${e.slice(0,db)}
476
476
 
477
- [output truncated]`}async function mb(e,t,r){let n=e.getReader(),i=new TextDecoder,o="";while(!0){let{done:c,value:u}=await n.read();if(c)break;let a=i.decode(u,{stream:!0});if(o+=a,a)r?.(t,a)}let s=i.decode();if(s)o+=s,r?.(t,s);return o}async function ap(e,t){let r=Bun.spawn([process.execPath,t.cliEntry,...e.command],{cwd:t.cwd,stdout:"pipe",stderr:"pipe",env:{...process.env,...t.env}}),n=()=>{try{r.kill()}catch{}};if(t.signal?.aborted)n();else t.signal?.addEventListener("abort",n,{once:!0});try{let[i,o,s]=await Promise.all([mb(r.stdout,"stdout",t.onOutput),mb(r.stderr,"stderr",t.onOutput),r.exited]);return{action:e.id,command:["cloud",...e.command].join(" "),exitCode:s,ok:s===0,stdout:gb(i),stderr:gb(o)}}finally{t.signal?.removeEventListener("abort",n)}}function yA(){return Object.entries(process.env).filter(([e,t])=>!!t&&t.length>=8&&/(?:secret|token|password|passwd|private|credential|api.?key|access.?key)/i.test(e)).map(([,e])=>e)}var bA=new Set(["/server/sites","/server/deployments","/server/logs","/integrations","/applications/new","/applications/compose","/operations/queue","/operations/previews","/operations/releases","/operations/workloads","/operations/observability","/operations/alerts","/operations/jobs","/data/backups","/account/security","/security","/access-denied"]);function SA(e){let t=Fa(e);if(t&&t!==".html")return!1;let r=e.replace(/\.html$/,"").replace(/\/+$/,"")||"/";if(r==="/")return!1;return!bA.has(r)}var vA={"/":"runtime:read","/server/activity":"audit:read","/server/sites":"project:read","/server/deployments":"deployments:read","/server/logs":"runtime:logs","/server/metrics":"runtime:read","/server/services":"runtime:read","/data/backups":"backups:read","/data/volumes":"data:read","/server/fleet":"fleet:read","/server/capacity":"fleet:read","/server/actions":"runtime:restart","/server/database":"data:read","/server/firewall":"fleet:read","/infrastructure/topology":"fleet:read","/server/security":"security:read","/security":"security:read","/integrations":"sources:read","/applications/new":"applications:read","/applications/compose":"applications:read","/operations/queue":"deployments:read","/operations/previews":"deployments:read","/operations/releases":"deployments:read","/operations/regions":"deployments:read","/operations/maintenance":"deployments:read","/operations/workloads":"runtime:read","/operations/observability":"runtime:logs","/operations/alerts":"runtime:read","/operations/jobs":"automation:read","/operations/configuration":"config:read","/server/ssh-keys":"fleet:read","/server/terminal":"runtime:terminal","/server/team":"users:read","/account/security":"project:read","/account/automation":"users:read","/serverless":"project:read","/serverless/deployments":"deployments:read","/serverless/logs":"runtime:logs","/serverless/metrics":"runtime:read","/serverless/traces":"runtime:read","/serverless/functions":"config:read","/serverless/queues":"data:read","/serverless/data":"data:read","/serverless/assets":"project:read","/serverless/secrets":"secrets:read","/serverless/firewall":"fleet:read","/serverless/alarms":"runtime:read","/serverless/cost":"project:read"};function fb(e,t){if(t.role==="admin")return!0;let r=Fa(e);if(r&&r!==".html")return!0;if(t.organizationSource==="legacy")return!SA(e);let n=e.replace(/\.html$/,"").replace(/\/+$/,"")||"/";if(n==="/access-denied")return!0;let i=vA[n];return!!i&&!!t.capabilities?.includes(i)}function wA(e,t){let r=decodeURIComponent(t).replace(/^\/+/,""),i=zT(r===""?"index.html":r);if(i.startsWith("..")||i.includes("/../"))return null;let o=Ct(e,i);if(uo(o)&&!Sb(o).isDirectory())return o;if(!Fa(o)&&uo(`${o}.html`))return`${o}.html`;if(!Fa(o)&&uo(Ct(o,"index.html")))return Ct(o,"index.html");return null}async function hb(e,t){let r=wA(e,t);if(!r){let o=Ct(e,"404.html");if(uo(o))return new Response(await Li(o),{status:404,headers:{"content-type":"text/html; charset=utf-8"}});return Rd("Not found",404)}if(Sb(r).isDirectory())return Rd("Not found",404);let n=await Li(r),i=YT[Fa(r)]??"application/octet-stream";return new Response(n,{headers:{"content-type":i}})}var Ad=["observe","backup","restore","restart","resize","version","rotate","expose","delete","logs","slow_queries","users","databases"],yb=new WeakMap;async function bb(e){let t=yb.get(e);if(t)return t;let r=await import("./chunk-knzje4ka.js"),n=new r.SpendStore(e),i={store:n,service:new r.SpendService(n),gate:new r.SpendGate(e)};return yb.set(e,i),i}async function cr(e={}){QT();let t=e.cwd??process.cwd(),r=e.host??HT,n=e.port??WT,i=e.cliEntry??process.argv[1];if(e.box)process.env.TS_CLOUD_DASHBOARD_BOX="1";await oA(t);let o=e.config??await Hi(),s=process.env.TS_CLOUD_DASHBOARD_DB_PASSWORD,c=w(o);if(s&&c&&!c.password)c.password=s;let u=o.infrastructure?.compute?.managedServices?.vitess;if(s&&u&&typeof u==="object"&&!u.password)u.password=s;let a=y(t,o);if(a.reconciliation.failed>0)console.warn(` ts-cloud dashboard: marked ${a.reconciliation.failed} orphaned operation(s) as failed after restart.`);let f=Object.keys(o.environments??{}),T=nA(o,e.environment),R=sA(t),D=await ps(o,T),W=new Map([[T,D]]),Y=new Map([[T,Date.now()]]),ee=new Map([[T,Date.now()]]),ne=new Map,he=Math.min(300000,Math.max(5000,Number(process.env.TS_CLOUD_DASHBOARD_REFRESH_MS)||30000)),te=Math.min(1800000,Math.max(60000,Number(process.env.TS_CLOUD_DASHBOARD_SITE_REFRESH_MS)||300000)),De=H(o)!=="serverless",tt=(C)=>{let Te=W.get(C);if(Te&&!ub(Y.get(C),Date.now(),he))return Promise.resolve(Te);let _e=ne.get(C);if(_e)return _e;let Ce=!De||ub(ee.get(C),Date.now(),te),Ge=ps(o,C,{includeSiteHealth:Ce}).then((gt)=>{let L=W.get(C),$r=Ce?gt:pA(L,gt);if(W.set(C,$r),Y.set(C,Date.now()),Ce)ee.set(C,Date.now());if(L?._serverReachable!==$r._serverReachable||L?._metricsStatus!==$r._metricsStatus||(L?.sitesDetail?.length??0)!==($r.sitesDetail?.length??0))pi();return $r}).finally(()=>ne.delete(C));return ne.set(C,Ge),Ge},je=wo(t),Gt=process.env.TS_CLOUD_DASHBOARD_TELEMETRY?.trim();if(e.box&&Gt!=="0"&&(Gt==="1"||!o.cloud?.attachTo)){let C=!1,Te=Date.now()+300000,_e=async()=>{if(C)return;C=!0;try{let Ge=Date.now(),gt=Ge>=Te;if(gt)Te=Ge+300000;let L=a.environments.get(T);await oi({controlPlane:a.store,projectId:a.project.id,environmentId:L?.id,config:o,environment:T,force:!0,lightweight:!0,includeSiteHealth:gt})}catch(Ge){if(e.verbose)console.warn(` ts-cloud dashboard: background telemetry collection failed: ${Ge instanceof Error?Ge.message:String(Ge)}`)}finally{C=!1}};_e(),setInterval(()=>void _e(),60000).unref?.()}let Re=new Map,Ke=new Map,Et=new Set,Ti=0;function lo(C,Te){if(C.role==="admin"&&!a.store.getActorByExternalId("user",`dashboard:${C.username.toLowerCase()}`))return C;let _e=a.store.getActorByExternalId("user",`dashboard:${C.username.toLowerCase()}`),Ce=_e?a.store.getMembershipForActor(a.organization.id,_e.id):void 0;if(!Ce||Ce.status!=="active")return{...C,role:"member",sites:{},capabilities:[]};let Ge=a.store.listGrants(Ce.id),gt=a.store.resolveAuthorizationTarget(a.organization.id,Ce.scope)??a.store.resolveAuthorizationTarget(a.organization.id,{type:"project",id:a.project.id}),L=hn({membership:Ce,grants:Ge,target:gt});if(Ce.roleTemplate==="owner"||Ce.roleTemplate==="admin")return{...C,role:"admin",sites:{},organizationRole:Ce.roleTemplate,organizationSource:Ce.source,capabilities:L};let $r=a.environments.get(Te),Kt={};for(let Ze of a.store.listResources(a.project.id,$r?.id).filter((nt)=>nt.kind==="application")){let nt=a.store.resolveAuthorizationTarget(a.organization.id,{type:"resource",id:Ze.id});if(!nt||!re({membership:Ce,grants:Ge,capability:"project:read",target:nt}).allowed)continue;Kt[Ze.slug]=re({membership:Ce,grants:Ge,capability:"config:write",target:nt}).allowed?"owner":"collaborator"}return{...C,role:"member",sites:Kt,organizationRole:Ce.roleTemplate,organizationSource:Ce.source,capabilities:L}}function pi(){Ti+=1,Re.clear();for(let C of Et)fs(C,{recursive:!0,force:!0});Et.clear()}let Ai=(C,Te)=>`${Te}:${C.role==="admin"?"admin":`member:${Object.entries(C.sites).sort(([_e],[Ce])=>_e.localeCompare(Ce)).map(([_e,Ce])=>`${_e}=${Ce}`).join(",")}`}:${[...C.capabilities??[]].sort().join(",")}`;async function ki(C,Te){let _e=lo(C,Te),Ce=Ai(_e,Te),Ge=Re.get(Ce);if(Ge)return Ge;let gt=Ke.get(Ce);if(gt)return gt;let L=Ti,$r=(async()=>{let Kt=W.get(Te)??await ps(o,Te);W.set(Te,Kt);let Ze={...Wl(Kt,{user:_e,slug:o.project.slug}),viewer:{role:_e.role,organizationRole:_e.organizationRole,organizationSource:_e.organizationSource,capabilities:_e.capabilities??[]}},nt=await mA(t,Ze);if(nt&&L!==Ti)return fs(nt,{recursive:!0,force:!0}),je?.uiRoot;if(nt)Et.add(nt);let wr=nt??je?.uiRoot;if(wr)Re.set(Ce,wr);return wr})();Ke.set(Ce,$r);try{return await $r}finally{Ke.delete(Ce)}}let Ri=await ki({username:"",passwordHash:"",role:"admin",sites:{}},T);if(!Ri)throw Error("ts-cloud dashboard UI not found. Run `bun run build` in ts-cloud or reinstall the package.");let Q=new WeakMap,ge=process.env.TS_CLOUD_DASHBOARD_TERMINAL!=="0",Ee=process.env.TS_CLOUD_DASHBOARD_AUTH==="0";if(Ee&&e.box)throw Error("TS_CLOUD_DASHBOARD_AUTH=0 is refused in box mode: the dashboard is internet-facing there, and disabling auth would expose a root shell.");let Pe=!Ee,Ot=ny(t),Ht=Pe?ay(t,process.env.TS_CLOUD_UI_USERNAME?.trim()||"admin"):void 0,Ie=new Oe(a.store,{encryptionKey:x(t)}),lt=new ze(a.store),rt=new xt(a.store),Ve=new rr(a.store,{encryptionKey:x(t)}),Mr=new Xn(a.store),hs=new Yn(a.store,{cwd:t}),Pi=new Qn(a.store,{encryptionKey:x(t)}),At=new S(a.store,{workerId:`dashboard:${process.pid}`}),Mt=new er(a.store),Bi=new tr(a.store,x(t)),po=new Dr(a.store),ja=new jr(Mt,At,Bi),mo=o.project?.region??"us-east-1",dp=x(t),ln=new _r(po,{encryptionKey:dp,backends:[new Tt(a.store,dp),new kr(new K(mo),mo),new Nr(new qe(mo),mo),new xr]});await gn(ln,a,o);let Pd=new me(mo),Ib={aws_rds:new jn(new Gn(Pd)),aws_aurora:new Vn(new Wn(Pd)),aws_elasticache:new zn(new Kn(new ie(mo))),server:new Hn(new ot),container:new qn(new ot)},up=(C)=>Ib[C.provider],Qt=new ni(a.store),Bo=new Jr(Qt,At),lp=new ii(Bi),Cb={managed_database:new yu(Mt,Pd),logical_database:new Iu(Mt,Bi),volume:new Eu,files:new wu(t),control_plane:new Au(a.store,t),infrastructure:new Ru(new Sa(mo))},Eb=(C)=>Cb[C.resourceKind],Tb=(C)=>C.provider==="aws_backup"?void 0:lp,xd=new mt(a.store),Dd=[new $t,new on(A(t,"volumes"))],Fi=new nn(xd,Dd,At),ua=new ke(a.store),xi=new Nn(ua,[new it("aws"),new it("hetzner"),new it("ssh")],At),fo=new xn(a.store),pp=new _n(fo,ua),Fo=new On(a.store),gp=new $n(Fo,At),ji=new Ln(a.store),Od=new Mn(ji,At),mp=["releases","artifacts","operations","logs","previews","snapshots","orphaned_resources"].map((C)=>new Un(C,a.store,a.project.id,a.organization.id)),br=new Wr(a.store),fp=new ri(br,{queue:At}),Wt=new Xe(a.store),ho=new Je(a.store),Cn=new st(a.store),We=new ft(a.store,{encryptionKey:x(t)}),Ab=()=>bb(a.store);for(let C of a.environments.values())Kr(br,o,{organization:a.organization,project:a.project,environment:C,resources:a.store.listResources(a.project.id,C.id)});let En=new yr(We,{emailImpl:async(C)=>{let{email:Te}=await import("./chunk-vn05n5z6.js");return Te.send(C)}}),hp=async(C)=>{let Te=sn(We,a.project.id,C),_e=[];for(let Ce of Te.filter((Ge)=>Ge.notify&&Ge.alert))_e.push(...await En.deliverAll(En.enqueue(a.organization.id,Ce.alert,Ce.transition)));return _e.push(...await En.deliverAll(En.enqueueRemindersAndEscalations(a.organization.id,We.listAlerts(a.project.id,{environmentId:C,states:["firing"]})))),_e.push(...await En.retryDue()),{evaluations:Te,deliveries:_e}},_d=!1,kb=async()=>{if(_d)return;_d=!0;try{for(let C of a.environments.values())for(let Te of We.listHealthChecks(a.project.id,C.id).filter((_e)=>_e.enabled)){let _e=We.listHealthResults(Te.id,1)[0];if(_e&&Date.now()-new Date(_e.checkedAt).getTime()<Te.intervalSeconds*1000)continue;let Ce=await new Ue(We).runAndEvaluate(Te);for(let Ge of Ce.evaluations.filter((gt)=>gt.notify&&gt.alert))await En.deliverAll(En.enqueue(a.organization.id,Ge.alert,Ge.transition))}}finally{_d=!1}},yp=setInterval(()=>{for(let C of a.environments.values())hp(C.id).catch((Te)=>console.error("ts-cloud alert evaluation failed:",Te))},60000);yp.unref?.();let bp=setInterval(()=>{kb().catch((C)=>console.error("ts-cloud health check evaluation failed:",C))},30000);bp.unref?.();let Sp=setInterval(()=>{try{fp.tick()}catch(C){console.error("ts-cloud scheduled job evaluation failed:",C)}},30000);Sp.unref?.();let vp=setInterval(()=>{try{Bo.enqueueDue(),Bo.enqueueRetention()}catch(C){console.error("ts-cloud backup policy evaluation failed:",C)}},30000);vp.unref?.(),Wt.cleanup();let wp=setInterval(()=>{try{Wt.cleanup()}catch(C){console.error("ts-cloud preview cleanup failed:",C)}},3600000);wp.unref?.();let Rb=e.queueWorker??!0,Pb=yA(),xb=async(C,Te)=>{let Ce=(C.environmentId?a.store.listEnvironments(C.projectId).find((Ge)=>Ge.id===C.environmentId):void 0)?.slug??String(T);if(Te.kind==="dashboard_operation"&&Te.operationId){let Ge=W.get(Ce)??D,gt=Zn(Te.operationId,o,Ge);if(!gt||gt.danger||!["scheduler","backup","worker"].includes(gt.group))return{ok:!1,stderr:"The allowlisted dashboard operation is no longer available."};let L=await qr(o,Ce,gt);return{ok:L.ok,stdout:L.stdout,stderr:L.stderr??L.error,retryable:/temporar|unavailable|timeout|network/i.test(L.stderr??L.error??""),output:{command:L.command??null,operation:L.operation}}}if(Te.kind==="serverless_scheduler"){let Ge=await rp(o,Ce,"run");return{ok:Ge.ok,stdout:Ge.stdout,stderr:Ge.error,retryable:/temporar|unavailable|timeout|network/i.test(Ge.error??""),output:{command:Ge.command??null,operation:"serverless_scheduler"}}}return{ok:!1,stderr:`No safe executor is configured for ${Te.kind}.`}},Ua=Rb?new gs(At,{...Cc({store:a.store,execute:async(C,Te)=>{let _e=Te.operation.input&&typeof Te.operation.input==="object"&&!Array.isArray(Te.operation.input)?Te.operation.input:{},Ce=_e.source&&typeof _e.source==="object"?_e.source:void 0,Ge=t,gt,L,$r;try{if(Ce?.bindingId&&Ce?.connectionId&&Ce?.commitSha){let Ze=Ve.getBinding(String(Ce.bindingId)),nt=Ve.getConnection(String(Ce.connectionId));if(!Ze||!nt||Ze.connectionId!==nt.id)throw Error("Queued source binding is no longer available");let mr=(Ze.repositoryId?Ve.getRepository(Ze.repositoryId):Ve.listRepositories(nt.id).find((Ss)=>Ss.fullName.toLowerCase()===Ze.repositoryFullName.toLowerCase()))?.cloneUrl;if(!mr&&nt.provider==="generic_ssh")mr=`git@${new URL(nt.host).hostname}:${Ze.repositoryFullName}.git`;if(!mr)mr=new URL(`/${Ze.repositoryFullName}.git`,nt.host.endsWith("/")?nt.host:`${nt.host}/`).href;let ye=Ze.deployKeyId?Ve.getDeployKey(Ze.deployKeyId):void 0,Lt=ye&&Ze.deployKeyId?{...ye,privateKey:Ve.getDeployPrivateKey(Ze.deployKeyId)}:void 0;if(["github","gitlab","bitbucket","gitea"].includes(nt.provider)&&C.target.previewId){let Ss=Io(nt,Ve.getCredential(nt.id)),ue=Wt.previews.getInstance(C.target.previewId);$r=async(Tn,Ja)=>{try{await Ss.setCommitStatus(Ze.repositoryFullName,String(Ce.commitSha),{state:Tn,url:ue?.url,description:Ja})}catch(vs){Te.log(`Could not publish source status: ${vs instanceof Error?vs.message:String(vs)}`,{stream:"stderr"})}},await $r("pending",`Preview deployment started for ${String(Ce.commitSha).slice(0,12)}`)}gt=cp(Ct(kd(),"ts-cloud-queued-source-")),Te.log(`Checking out immutable source commit ${Ce.commitSha}.`,{stream:"system"}),Ge=(await Qd({remote:mr,binding:Ze,destination:Ct(gt,"checkout"),ref:String(Ce.branch??Ze.defaultBranch),commitSha:String(Ce.commitSha)},{credential:Ve.getCredential(nt.id),deployKey:Lt})).directory}if(Te.operation.kind!=="preview.destroy"){let Ze=C.target.previewId?Wt.previews.getInstance(C.target.previewId):void 0,nt=Ze?Wt.previews.getDefinition(Ze.definitionId):void 0,wr=Te.operation.resourceId?a.store.getResource(Te.operation.resourceId):void 0;if(L=await ln.resolve({projectId:a.project.id,environmentId:Te.operation.environmentId,resourceId:Te.operation.resourceId,functionId:wr?.kind==="function"?wr.id:void 0,previewId:Ze?.id,trustedPreview:!!Ze&&!Ze.fork,allowedPreviewSecrets:nt?.inheritedSecrets}),L.warnings.some((mr)=>mr.code==="missing_required"))throw Error(`Required deployment configuration is unavailable: ${L.warnings.filter((mr)=>mr.code==="missing_required").map((mr)=>mr.key).join(", ")}`);if(Te.operation.resourceId)for(let mr of Object.values(L.entries))po.setDependency({entryId:mr.id,resourceId:Te.operation.resourceId,injectionTarget:"environment",required:mr.required,requiresRedeploy:!0});Te.log(`Resolved configuration ${L.configurationHash.slice(0,18)} for ${Object.keys(L.values).length} keys.`,{stream:"system"})}let Kt=await ap(C,{cwd:Ge,cliEntry:i,signal:Te.signal,env:L?.values,onOutput:(Ze,nt)=>Te.log(nt,{stream:Ze,step:"execute",secrets:[...Pb,...Object.entries(L?.entries??{}).filter(([,wr])=>wr.kind==="secret").map(([wr])=>L.values[wr]).filter(Boolean)]})});if(Kt.ok&&Te.operation.resourceId&&L)for(let Ze of Object.values(L.entries))po.setDependency({entryId:Ze.id,resourceId:Te.operation.resourceId,injectionTarget:"environment",required:Ze.required,requiresRedeploy:!1,lastDeployedVersion:Ze.version});return await $r?.(Kt.ok?"success":"failure",Kt.ok?`Preview is ready at ${String(Ce?.commitSha).slice(0,12)}`:`Preview deployment failed at ${String(Ce?.commitSha).slice(0,12)}`),Kt}catch(Kt){throw await $r?.("error",`Preview deployment could not complete at ${String(Ce?.commitSha).slice(0,12)}`),Kt}finally{if(gt)fs(gt,{recursive:!0,force:!0})}}}),...Vg({store:br,executor:xb}),...em({store:Mt,secrets:Bi,resolveAdapter:up}),...Uf(ua,xi.drivers),...ch(Fo,[new Cl("aws","AWS regional execution requires an injected AwsRegionalTransport; topology and plans were preserved without provider mutation.")]),...eh({store:ji,cleanup:mp}),...vc(xd,Dd),...Yg({store:Qt,queue:At,resolveSource:Eb,resolveDestination:Tb,validateHealth:async(C,Te)=>{if(!C.healthCheckId)return{healthy:!0,mode:"adapter"};let _e=We.getHealthCheck(C.healthCheckId);if(!_e||_e.projectId!==C.projectId)return{healthy:!1,error:"Configured restore health check was not found."};let Ce=await new Ue(We).runAndEvaluate(_e);return{healthy:Ce.result.status==="healthy",healthCheckId:_e.id,healthResultId:Ce.result.id,target:Te}}}),...Qp({store:a.store,resolveDriver:e.releaseDriver??((C)=>({name:`${a.store.getResource(C.resourceId)?.provider??"provider"} release driver`,capability:()=>({strategy:C.strategy,supported:!1,explanation:"This dashboard process has no immutable activation driver configured for the target provider.",capacityMultiplier:1,costImpact:"none",rollback:"The previous release remains preserved; configure a release driver before retrying."}),activate:async()=>{throw Error("Immutable activation driver is not configured")},rollback:async()=>{throw Error("Immutable rollback driver is not configured")}})),resolveHealthGate:async(C,Te)=>{let _e=We.listHealthChecks(Te.projectId,Te.environmentId).find((Ge)=>Ge.enabled&&Ge.name===C&&(!Ge.resourceId||Ge.resourceId===Te.resourceId));if(!_e)return{healthy:!1,message:`Named health gate ${C} was not found for this release.`};let Ce=await new Ue(We).runAndEvaluate(_e);return{healthy:Ce.result.status==="healthy",evidence:{healthCheckId:_e.id,healthResultId:Ce.result.id,status:Ce.result.status,timings:Ce.result.timings},message:Ce.result.message}}})},{parallelism:e.queueParallelism??(Number(process.env.TS_CLOUD_QUEUE_PARALLELISM)||8),onError:(C)=>console.error("ts-cloud deployment queue worker failed:",C)}):void 0;if(ei(a),dd(rt,le(a,String(T)),D),Ht)ud(a,Ht.users),uy(Ie,a,Ht.users);let jt=cy({cwd:t,enabled:Pe,secret:Ot,authentication:Ie,authorization:{store:a.store,organizationId:a.organization.id,projectId:a.project.id,defaultEnvironment:String(T)}}),Yt=new Al,Ip=setInterval(()=>Yt.sweep(),60000);Ip.unref?.();let za=new Ma,Nd=new Ma(3,900000,900000),Va=new Ma(8,900000,900000),Cp=setInterval(()=>za.prune(),300000),Ep=setInterval(()=>Nd.prune(),300000),Tp=setInterval(()=>Va.prune(),300000);if(Cp.unref?.(),Ep.unref?.(),Tp.unref?.(),Pe){if(Ht?.generated)console.warn(`
477
+ [output truncated]`}async function mb(e,t,r){let n=e.getReader(),i=new TextDecoder,o="";while(!0){let{done:c,value:u}=await n.read();if(c)break;let a=i.decode(u,{stream:!0});if(o+=a,a)r?.(t,a)}let s=i.decode();if(s)o+=s,r?.(t,s);return o}async function ap(e,t){let r=Bun.spawn([process.execPath,t.cliEntry,...e.command],{cwd:t.cwd,stdout:"pipe",stderr:"pipe",env:{...process.env,...t.env}}),n=()=>{try{r.kill()}catch{}};if(t.signal?.aborted)n();else t.signal?.addEventListener("abort",n,{once:!0});try{let[i,o,s]=await Promise.all([mb(r.stdout,"stdout",t.onOutput),mb(r.stderr,"stderr",t.onOutput),r.exited]);return{action:e.id,command:["cloud",...e.command].join(" "),exitCode:s,ok:s===0,stdout:gb(i),stderr:gb(o)}}finally{t.signal?.removeEventListener("abort",n)}}function yA(){return Object.entries(process.env).filter(([e,t])=>!!t&&t.length>=8&&/(?:secret|token|password|passwd|private|credential|api.?key|access.?key)/i.test(e)).map(([,e])=>e)}var bA=new Set(["/server/sites","/server/deployments","/server/logs","/integrations","/applications/new","/applications/compose","/operations/queue","/operations/previews","/operations/releases","/operations/workloads","/operations/observability","/operations/alerts","/operations/jobs","/data/backups","/account/security","/security","/access-denied"]);function SA(e){let t=Fa(e);if(t&&t!==".html")return!1;let r=e.replace(/\.html$/,"").replace(/\/+$/,"")||"/";if(r==="/")return!1;return!bA.has(r)}var vA={"/":"runtime:read","/server/activity":"audit:read","/server/sites":"project:read","/server/deployments":"deployments:read","/server/logs":"runtime:logs","/server/metrics":"runtime:read","/server/services":"runtime:read","/data/backups":"backups:read","/data/volumes":"data:read","/server/fleet":"fleet:read","/server/capacity":"fleet:read","/server/actions":"runtime:restart","/server/database":"data:read","/server/firewall":"fleet:read","/infrastructure/topology":"fleet:read","/server/security":"security:read","/security":"security:read","/integrations":"sources:read","/applications/new":"applications:read","/applications/compose":"applications:read","/operations/queue":"deployments:read","/operations/previews":"deployments:read","/operations/releases":"deployments:read","/operations/regions":"deployments:read","/operations/maintenance":"deployments:read","/operations/workloads":"runtime:read","/operations/observability":"runtime:logs","/operations/alerts":"runtime:read","/operations/jobs":"automation:read","/operations/configuration":"config:read","/server/ssh-keys":"fleet:read","/server/terminal":"runtime:terminal","/server/team":"users:read","/account/security":"project:read","/account/automation":"users:read","/serverless":"project:read","/serverless/deployments":"deployments:read","/serverless/logs":"runtime:logs","/serverless/metrics":"runtime:read","/serverless/traces":"runtime:read","/serverless/functions":"config:read","/serverless/queues":"data:read","/serverless/data":"data:read","/serverless/assets":"project:read","/serverless/secrets":"secrets:read","/serverless/firewall":"fleet:read","/serverless/alarms":"runtime:read","/serverless/cost":"project:read"};function fb(e,t){if(t.role==="admin")return!0;let r=Fa(e);if(r&&r!==".html")return!0;if(t.organizationSource==="legacy")return!SA(e);let n=e.replace(/\.html$/,"").replace(/\/+$/,"")||"/";if(n==="/access-denied")return!0;let i=vA[n];return!!i&&!!t.capabilities?.includes(i)}function wA(e,t){let r=decodeURIComponent(t).replace(/^\/+/,""),i=zT(r===""?"index.html":r);if(i.startsWith("..")||i.includes("/../"))return null;let o=Ct(e,i);if(uo(o)&&!Sb(o).isDirectory())return o;if(!Fa(o)&&uo(`${o}.html`))return`${o}.html`;if(!Fa(o)&&uo(Ct(o,"index.html")))return Ct(o,"index.html");return null}async function hb(e,t){let r=wA(e,t);if(!r){let o=Ct(e,"404.html");if(uo(o))return new Response(await Li(o),{status:404,headers:{"content-type":"text/html; charset=utf-8"}});return Rd("Not found",404)}if(Sb(r).isDirectory())return Rd("Not found",404);let n=await Li(r),i=YT[Fa(r)]??"application/octet-stream";return new Response(n,{headers:{"content-type":i}})}var Ad=["observe","backup","restore","restart","resize","version","rotate","expose","delete","logs","slow_queries","users","databases"],yb=new WeakMap;async function bb(e){let t=yb.get(e);if(t)return t;let r=await import("./chunk-vjg2fymw.js"),n=new r.SpendStore(e),i={store:n,service:new r.SpendService(n),gate:new r.SpendGate(e)};return yb.set(e,i),i}async function cr(e={}){QT();let t=e.cwd??process.cwd(),r=e.host??HT,n=e.port??WT,i=e.cliEntry??process.argv[1];if(e.box)process.env.TS_CLOUD_DASHBOARD_BOX="1";await oA(t);let o=e.config??await Hi(),s=process.env.TS_CLOUD_DASHBOARD_DB_PASSWORD,c=w(o);if(s&&c&&!c.password)c.password=s;let u=o.infrastructure?.compute?.managedServices?.vitess;if(s&&u&&typeof u==="object"&&!u.password)u.password=s;let a=y(t,o);if(a.reconciliation.failed>0)console.warn(` ts-cloud dashboard: marked ${a.reconciliation.failed} orphaned operation(s) as failed after restart.`);let f=Object.keys(o.environments??{}),T=nA(o,e.environment),R=sA(t),D=await ps(o,T),W=new Map([[T,D]]),Y=new Map([[T,Date.now()]]),ee=new Map([[T,Date.now()]]),ne=new Map,he=Math.min(300000,Math.max(5000,Number(process.env.TS_CLOUD_DASHBOARD_REFRESH_MS)||30000)),te=Math.min(1800000,Math.max(60000,Number(process.env.TS_CLOUD_DASHBOARD_SITE_REFRESH_MS)||300000)),De=H(o)!=="serverless",tt=(C)=>{let Te=W.get(C);if(Te&&!ub(Y.get(C),Date.now(),he))return Promise.resolve(Te);let _e=ne.get(C);if(_e)return _e;let Ce=!De||ub(ee.get(C),Date.now(),te),Ge=ps(o,C,{includeSiteHealth:Ce}).then((gt)=>{let L=W.get(C),$r=Ce?gt:pA(L,gt);if(W.set(C,$r),Y.set(C,Date.now()),Ce)ee.set(C,Date.now());if(L?._serverReachable!==$r._serverReachable||L?._metricsStatus!==$r._metricsStatus||(L?.sitesDetail?.length??0)!==($r.sitesDetail?.length??0))pi();return $r}).finally(()=>ne.delete(C));return ne.set(C,Ge),Ge},je=wo(t),Gt=process.env.TS_CLOUD_DASHBOARD_TELEMETRY?.trim();if(e.box&&Gt!=="0"&&(Gt==="1"||!o.cloud?.attachTo)){let C=!1,Te=Date.now()+300000,_e=async()=>{if(C)return;C=!0;try{let Ge=Date.now(),gt=Ge>=Te;if(gt)Te=Ge+300000;let L=a.environments.get(T);await oi({controlPlane:a.store,projectId:a.project.id,environmentId:L?.id,config:o,environment:T,force:!0,lightweight:!0,includeSiteHealth:gt})}catch(Ge){if(e.verbose)console.warn(` ts-cloud dashboard: background telemetry collection failed: ${Ge instanceof Error?Ge.message:String(Ge)}`)}finally{C=!1}};_e(),setInterval(()=>void _e(),60000).unref?.()}let Re=new Map,Ke=new Map,Et=new Set,Ti=0;function lo(C,Te){if(C.role==="admin"&&!a.store.getActorByExternalId("user",`dashboard:${C.username.toLowerCase()}`))return C;let _e=a.store.getActorByExternalId("user",`dashboard:${C.username.toLowerCase()}`),Ce=_e?a.store.getMembershipForActor(a.organization.id,_e.id):void 0;if(!Ce||Ce.status!=="active")return{...C,role:"member",sites:{},capabilities:[]};let Ge=a.store.listGrants(Ce.id),gt=a.store.resolveAuthorizationTarget(a.organization.id,Ce.scope)??a.store.resolveAuthorizationTarget(a.organization.id,{type:"project",id:a.project.id}),L=hn({membership:Ce,grants:Ge,target:gt});if(Ce.roleTemplate==="owner"||Ce.roleTemplate==="admin")return{...C,role:"admin",sites:{},organizationRole:Ce.roleTemplate,organizationSource:Ce.source,capabilities:L};let $r=a.environments.get(Te),Kt={};for(let Ze of a.store.listResources(a.project.id,$r?.id).filter((nt)=>nt.kind==="application")){let nt=a.store.resolveAuthorizationTarget(a.organization.id,{type:"resource",id:Ze.id});if(!nt||!re({membership:Ce,grants:Ge,capability:"project:read",target:nt}).allowed)continue;Kt[Ze.slug]=re({membership:Ce,grants:Ge,capability:"config:write",target:nt}).allowed?"owner":"collaborator"}return{...C,role:"member",sites:Kt,organizationRole:Ce.roleTemplate,organizationSource:Ce.source,capabilities:L}}function pi(){Ti+=1,Re.clear();for(let C of Et)fs(C,{recursive:!0,force:!0});Et.clear()}let Ai=(C,Te)=>`${Te}:${C.role==="admin"?"admin":`member:${Object.entries(C.sites).sort(([_e],[Ce])=>_e.localeCompare(Ce)).map(([_e,Ce])=>`${_e}=${Ce}`).join(",")}`}:${[...C.capabilities??[]].sort().join(",")}`;async function ki(C,Te){let _e=lo(C,Te),Ce=Ai(_e,Te),Ge=Re.get(Ce);if(Ge)return Ge;let gt=Ke.get(Ce);if(gt)return gt;let L=Ti,$r=(async()=>{let Kt=W.get(Te)??await ps(o,Te);W.set(Te,Kt);let Ze={...Wl(Kt,{user:_e,slug:o.project.slug}),viewer:{role:_e.role,organizationRole:_e.organizationRole,organizationSource:_e.organizationSource,capabilities:_e.capabilities??[]}},nt=await mA(t,Ze);if(nt&&L!==Ti)return fs(nt,{recursive:!0,force:!0}),je?.uiRoot;if(nt)Et.add(nt);let wr=nt??je?.uiRoot;if(wr)Re.set(Ce,wr);return wr})();Ke.set(Ce,$r);try{return await $r}finally{Ke.delete(Ce)}}let Ri=await ki({username:"",passwordHash:"",role:"admin",sites:{}},T);if(!Ri)throw Error("ts-cloud dashboard UI not found. Run `bun run build` in ts-cloud or reinstall the package.");let Q=new WeakMap,ge=process.env.TS_CLOUD_DASHBOARD_TERMINAL!=="0",Ee=process.env.TS_CLOUD_DASHBOARD_AUTH==="0";if(Ee&&e.box)throw Error("TS_CLOUD_DASHBOARD_AUTH=0 is refused in box mode: the dashboard is internet-facing there, and disabling auth would expose a root shell.");let Pe=!Ee,Ot=ny(t),Ht=Pe?ay(t,process.env.TS_CLOUD_UI_USERNAME?.trim()||"admin"):void 0,Ie=new Oe(a.store,{encryptionKey:x(t)}),lt=new ze(a.store),rt=new xt(a.store),Ve=new rr(a.store,{encryptionKey:x(t)}),Mr=new Xn(a.store),hs=new Yn(a.store,{cwd:t}),Pi=new Qn(a.store,{encryptionKey:x(t)}),At=new S(a.store,{workerId:`dashboard:${process.pid}`}),Mt=new er(a.store),Bi=new tr(a.store,x(t)),po=new Dr(a.store),ja=new jr(Mt,At,Bi),mo=o.project?.region??"us-east-1",dp=x(t),ln=new _r(po,{encryptionKey:dp,backends:[new Tt(a.store,dp),new kr(new K(mo),mo),new Nr(new qe(mo),mo),new xr]});await gn(ln,a,o);let Pd=new me(mo),Ib={aws_rds:new jn(new Gn(Pd)),aws_aurora:new Vn(new Wn(Pd)),aws_elasticache:new zn(new Kn(new ie(mo))),server:new Hn(new ot),container:new qn(new ot)},up=(C)=>Ib[C.provider],Qt=new ni(a.store),Bo=new Jr(Qt,At),lp=new ii(Bi),Cb={managed_database:new yu(Mt,Pd),logical_database:new Iu(Mt,Bi),volume:new Eu,files:new wu(t),control_plane:new Au(a.store,t),infrastructure:new Ru(new Sa(mo))},Eb=(C)=>Cb[C.resourceKind],Tb=(C)=>C.provider==="aws_backup"?void 0:lp,xd=new mt(a.store),Dd=[new $t,new on(A(t,"volumes"))],Fi=new nn(xd,Dd,At),ua=new ke(a.store),xi=new Nn(ua,[new it("aws"),new it("hetzner"),new it("ssh")],At),fo=new xn(a.store),pp=new _n(fo,ua),Fo=new On(a.store),gp=new $n(Fo,At),ji=new Ln(a.store),Od=new Mn(ji,At),mp=["releases","artifacts","operations","logs","previews","snapshots","orphaned_resources"].map((C)=>new Un(C,a.store,a.project.id,a.organization.id)),br=new Wr(a.store),fp=new ri(br,{queue:At}),Wt=new Xe(a.store),ho=new Je(a.store),Cn=new st(a.store),We=new ft(a.store,{encryptionKey:x(t)}),Ab=()=>bb(a.store);for(let C of a.environments.values())Kr(br,o,{organization:a.organization,project:a.project,environment:C,resources:a.store.listResources(a.project.id,C.id)});let En=new yr(We,{emailImpl:async(C)=>{let{email:Te}=await import("./chunk-pr1dg1km.js");return Te.send(C)}}),hp=async(C)=>{let Te=sn(We,a.project.id,C),_e=[];for(let Ce of Te.filter((Ge)=>Ge.notify&&Ge.alert))_e.push(...await En.deliverAll(En.enqueue(a.organization.id,Ce.alert,Ce.transition)));return _e.push(...await En.deliverAll(En.enqueueRemindersAndEscalations(a.organization.id,We.listAlerts(a.project.id,{environmentId:C,states:["firing"]})))),_e.push(...await En.retryDue()),{evaluations:Te,deliveries:_e}},_d=!1,kb=async()=>{if(_d)return;_d=!0;try{for(let C of a.environments.values())for(let Te of We.listHealthChecks(a.project.id,C.id).filter((_e)=>_e.enabled)){let _e=We.listHealthResults(Te.id,1)[0];if(_e&&Date.now()-new Date(_e.checkedAt).getTime()<Te.intervalSeconds*1000)continue;let Ce=await new Ue(We).runAndEvaluate(Te);for(let Ge of Ce.evaluations.filter((gt)=>gt.notify&&gt.alert))await En.deliverAll(En.enqueue(a.organization.id,Ge.alert,Ge.transition))}}finally{_d=!1}},yp=setInterval(()=>{for(let C of a.environments.values())hp(C.id).catch((Te)=>console.error("ts-cloud alert evaluation failed:",Te))},60000);yp.unref?.();let bp=setInterval(()=>{kb().catch((C)=>console.error("ts-cloud health check evaluation failed:",C))},30000);bp.unref?.();let Sp=setInterval(()=>{try{fp.tick()}catch(C){console.error("ts-cloud scheduled job evaluation failed:",C)}},30000);Sp.unref?.();let vp=setInterval(()=>{try{Bo.enqueueDue(),Bo.enqueueRetention()}catch(C){console.error("ts-cloud backup policy evaluation failed:",C)}},30000);vp.unref?.(),Wt.cleanup();let wp=setInterval(()=>{try{Wt.cleanup()}catch(C){console.error("ts-cloud preview cleanup failed:",C)}},3600000);wp.unref?.();let Rb=e.queueWorker??!0,Pb=yA(),xb=async(C,Te)=>{let Ce=(C.environmentId?a.store.listEnvironments(C.projectId).find((Ge)=>Ge.id===C.environmentId):void 0)?.slug??String(T);if(Te.kind==="dashboard_operation"&&Te.operationId){let Ge=W.get(Ce)??D,gt=Zn(Te.operationId,o,Ge);if(!gt||gt.danger||!["scheduler","backup","worker"].includes(gt.group))return{ok:!1,stderr:"The allowlisted dashboard operation is no longer available."};let L=await qr(o,Ce,gt);return{ok:L.ok,stdout:L.stdout,stderr:L.stderr??L.error,retryable:/temporar|unavailable|timeout|network/i.test(L.stderr??L.error??""),output:{command:L.command??null,operation:L.operation}}}if(Te.kind==="serverless_scheduler"){let Ge=await rp(o,Ce,"run");return{ok:Ge.ok,stdout:Ge.stdout,stderr:Ge.error,retryable:/temporar|unavailable|timeout|network/i.test(Ge.error??""),output:{command:Ge.command??null,operation:"serverless_scheduler"}}}return{ok:!1,stderr:`No safe executor is configured for ${Te.kind}.`}},Ua=Rb?new gs(At,{...Cc({store:a.store,execute:async(C,Te)=>{let _e=Te.operation.input&&typeof Te.operation.input==="object"&&!Array.isArray(Te.operation.input)?Te.operation.input:{},Ce=_e.source&&typeof _e.source==="object"?_e.source:void 0,Ge=t,gt,L,$r;try{if(Ce?.bindingId&&Ce?.connectionId&&Ce?.commitSha){let Ze=Ve.getBinding(String(Ce.bindingId)),nt=Ve.getConnection(String(Ce.connectionId));if(!Ze||!nt||Ze.connectionId!==nt.id)throw Error("Queued source binding is no longer available");let mr=(Ze.repositoryId?Ve.getRepository(Ze.repositoryId):Ve.listRepositories(nt.id).find((Ss)=>Ss.fullName.toLowerCase()===Ze.repositoryFullName.toLowerCase()))?.cloneUrl;if(!mr&&nt.provider==="generic_ssh")mr=`git@${new URL(nt.host).hostname}:${Ze.repositoryFullName}.git`;if(!mr)mr=new URL(`/${Ze.repositoryFullName}.git`,nt.host.endsWith("/")?nt.host:`${nt.host}/`).href;let ye=Ze.deployKeyId?Ve.getDeployKey(Ze.deployKeyId):void 0,Lt=ye&&Ze.deployKeyId?{...ye,privateKey:Ve.getDeployPrivateKey(Ze.deployKeyId)}:void 0;if(["github","gitlab","bitbucket","gitea"].includes(nt.provider)&&C.target.previewId){let Ss=Io(nt,Ve.getCredential(nt.id)),ue=Wt.previews.getInstance(C.target.previewId);$r=async(Tn,Ja)=>{try{await Ss.setCommitStatus(Ze.repositoryFullName,String(Ce.commitSha),{state:Tn,url:ue?.url,description:Ja})}catch(vs){Te.log(`Could not publish source status: ${vs instanceof Error?vs.message:String(vs)}`,{stream:"stderr"})}},await $r("pending",`Preview deployment started for ${String(Ce.commitSha).slice(0,12)}`)}gt=cp(Ct(kd(),"ts-cloud-queued-source-")),Te.log(`Checking out immutable source commit ${Ce.commitSha}.`,{stream:"system"}),Ge=(await Qd({remote:mr,binding:Ze,destination:Ct(gt,"checkout"),ref:String(Ce.branch??Ze.defaultBranch),commitSha:String(Ce.commitSha)},{credential:Ve.getCredential(nt.id),deployKey:Lt})).directory}if(Te.operation.kind!=="preview.destroy"){let Ze=C.target.previewId?Wt.previews.getInstance(C.target.previewId):void 0,nt=Ze?Wt.previews.getDefinition(Ze.definitionId):void 0,wr=Te.operation.resourceId?a.store.getResource(Te.operation.resourceId):void 0;if(L=await ln.resolve({projectId:a.project.id,environmentId:Te.operation.environmentId,resourceId:Te.operation.resourceId,functionId:wr?.kind==="function"?wr.id:void 0,previewId:Ze?.id,trustedPreview:!!Ze&&!Ze.fork,allowedPreviewSecrets:nt?.inheritedSecrets}),L.warnings.some((mr)=>mr.code==="missing_required"))throw Error(`Required deployment configuration is unavailable: ${L.warnings.filter((mr)=>mr.code==="missing_required").map((mr)=>mr.key).join(", ")}`);if(Te.operation.resourceId)for(let mr of Object.values(L.entries))po.setDependency({entryId:mr.id,resourceId:Te.operation.resourceId,injectionTarget:"environment",required:mr.required,requiresRedeploy:!0});Te.log(`Resolved configuration ${L.configurationHash.slice(0,18)} for ${Object.keys(L.values).length} keys.`,{stream:"system"})}let Kt=await ap(C,{cwd:Ge,cliEntry:i,signal:Te.signal,env:L?.values,onOutput:(Ze,nt)=>Te.log(nt,{stream:Ze,step:"execute",secrets:[...Pb,...Object.entries(L?.entries??{}).filter(([,wr])=>wr.kind==="secret").map(([wr])=>L.values[wr]).filter(Boolean)]})});if(Kt.ok&&Te.operation.resourceId&&L)for(let Ze of Object.values(L.entries))po.setDependency({entryId:Ze.id,resourceId:Te.operation.resourceId,injectionTarget:"environment",required:Ze.required,requiresRedeploy:!1,lastDeployedVersion:Ze.version});return await $r?.(Kt.ok?"success":"failure",Kt.ok?`Preview is ready at ${String(Ce?.commitSha).slice(0,12)}`:`Preview deployment failed at ${String(Ce?.commitSha).slice(0,12)}`),Kt}catch(Kt){throw await $r?.("error",`Preview deployment could not complete at ${String(Ce?.commitSha).slice(0,12)}`),Kt}finally{if(gt)fs(gt,{recursive:!0,force:!0})}}}),...Vg({store:br,executor:xb}),...em({store:Mt,secrets:Bi,resolveAdapter:up}),...Uf(ua,xi.drivers),...ch(Fo,[new Cl("aws","AWS regional execution requires an injected AwsRegionalTransport; topology and plans were preserved without provider mutation.")]),...eh({store:ji,cleanup:mp}),...vc(xd,Dd),...Yg({store:Qt,queue:At,resolveSource:Eb,resolveDestination:Tb,validateHealth:async(C,Te)=>{if(!C.healthCheckId)return{healthy:!0,mode:"adapter"};let _e=We.getHealthCheck(C.healthCheckId);if(!_e||_e.projectId!==C.projectId)return{healthy:!1,error:"Configured restore health check was not found."};let Ce=await new Ue(We).runAndEvaluate(_e);return{healthy:Ce.result.status==="healthy",healthCheckId:_e.id,healthResultId:Ce.result.id,target:Te}}}),...Qp({store:a.store,resolveDriver:e.releaseDriver??((C)=>({name:`${a.store.getResource(C.resourceId)?.provider??"provider"} release driver`,capability:()=>({strategy:C.strategy,supported:!1,explanation:"This dashboard process has no immutable activation driver configured for the target provider.",capacityMultiplier:1,costImpact:"none",rollback:"The previous release remains preserved; configure a release driver before retrying."}),activate:async()=>{throw Error("Immutable activation driver is not configured")},rollback:async()=>{throw Error("Immutable rollback driver is not configured")}})),resolveHealthGate:async(C,Te)=>{let _e=We.listHealthChecks(Te.projectId,Te.environmentId).find((Ge)=>Ge.enabled&&Ge.name===C&&(!Ge.resourceId||Ge.resourceId===Te.resourceId));if(!_e)return{healthy:!1,message:`Named health gate ${C} was not found for this release.`};let Ce=await new Ue(We).runAndEvaluate(_e);return{healthy:Ce.result.status==="healthy",evidence:{healthCheckId:_e.id,healthResultId:Ce.result.id,status:Ce.result.status,timings:Ce.result.timings},message:Ce.result.message}}})},{parallelism:e.queueParallelism??(Number(process.env.TS_CLOUD_QUEUE_PARALLELISM)||8),onError:(C)=>console.error("ts-cloud deployment queue worker failed:",C)}):void 0;if(ei(a),dd(rt,le(a,String(T)),D),Ht)ud(a,Ht.users),uy(Ie,a,Ht.users);let jt=cy({cwd:t,enabled:Pe,secret:Ot,authentication:Ie,authorization:{store:a.store,organizationId:a.organization.id,projectId:a.project.id,defaultEnvironment:String(T)}}),Yt=new Al,Ip=setInterval(()=>Yt.sweep(),60000);Ip.unref?.();let za=new Ma,Nd=new Ma(3,900000,900000),Va=new Ma(8,900000,900000),Cp=setInterval(()=>za.prune(),300000),Ep=setInterval(()=>Nd.prune(),300000),Tp=setInterval(()=>Va.prune(),300000);if(Cp.unref?.(),Ep.unref?.(),Tp.unref?.(),Pe){if(Ht?.generated)console.warn(`
478
478
  ts-cloud dashboard: created the first admin.
479
479
  username: ${Ht.generated.username}
480
480
  password: ${Ht.generated.password}
481
481
  Saved (hashed) to ${oy()}. This password is shown once.
482
482
  `)}else console.warn(" ts-cloud dashboard: authentication is DISABLED (TS_CLOUD_DASHBOARD_AUTH=0). Every request runs as an admin.");let yo=r!=="127.0.0.1"&&r!=="localhost",Md=(C)=>jT("sha256").update(`${Ot}:${C}`).digest("hex").slice(0,16),Db=Zd({controlPlane:a.store,identities:lt,sources:Ve,applications:{drafts:Mr,artifacts:hs,registries:Pi}}),Ap=(C)=>C.headers.get("user-agent")?.trim().slice(0,256)||void 0,qa=(C,Te,_e,Ce="local")=>Ie.createSession({identityId:C,authMethod:Ce,userAgent:Ap(Te),networkHint:Md(_e)}),Ne=(C)=>{let Te=a.store.getActorByExternalId("user",`dashboard:${C.username.toLowerCase()}`),_e=Te?a.store.getMembershipForActor(a.organization.id,Te.id):void 0;return{actor:Te,membership:_e,grants:_e?a.store.listGrants(_e.id):[]}},ys=(C,Te,_e)=>{if(C.role==="admin")return!0;let Ce=a.store.getOperation(Te),Ge=Ne(C);if(!Ce||!Ge.membership)return!1;let gt=Ce.resourceId?{type:"resource",id:Ce.resourceId}:Ce.environmentId?{type:"environment",id:Ce.environmentId}:Ce.projectId?{type:"project",id:Ce.projectId}:{type:"organization"},L=a.store.resolveAuthorizationTarget(a.organization.id,gt);return!!L&&re({membership:Ge.membership,grants:Ge.grants,capability:_e,target:L}).allowed},Sr=(C,Te,_e)=>{if(C.role==="admin")return!0;let Ce=Ne(C);if(!Ce.membership)return!1;let Ge=a.store.resolveAuthorizationTarget(a.organization.id,{type:"resource",id:Te});return!!Ge&&re({membership:Ce.membership,grants:Ce.grants,capability:_e,target:Ge}).allowed},la=(C,Te,_e)=>{if(C.role==="admin")return!0;let Ce=Ne(C);if(!Ce.membership)return!1;let Ge=a.store.resolveAuthorizationTarget(a.organization.id,{type:"environment",id:Te});return!!Ge&&re({membership:Ce.membership,grants:Ce.grants,capability:_e,target:Ge}).allowed},Ga=(C,Te)=>{if(C.role==="admin")return!0;let _e=Ne(C);if(!_e.membership)return!1;let Ce=a.store.resolveAuthorizationTarget(a.organization.id,{type:"organization"});return!!Ce&&re({membership:_e.membership,grants:_e.grants,capability:Te,target:Ce}).allowed},bs=Bun.serve({hostname:r,port:n,idleTimeout:30,websocket:{open(C){if(!ge){C.send(`The web terminal is disabled (TS_CLOUD_DASHBOARD_TERMINAL=0).\r
483
483
  `),C.close();return}let Te=ab((_e)=>C.send(_e),{cwd:t,onExit:()=>{try{C.close()}catch{}}});Q.set(C,Te),C.send(`Connected to ${r==="127.0.0.1"?"localhost":r} shell. This is a line-oriented shell (no full-screen apps).\r
484
- `)},message(C,Te){Q.get(C)?.write(typeof Te==="string"?Te:new TextDecoder().decode(Te))},close(C){Q.get(C)?.close(),Q.delete(C)}},async fetch(C,Te){let _e=Date.now(),Ce=C.clone(),Ge=C.headers.get("x-request-id")?.slice(0,128)||crypto.randomUUID(),gt=!["GET","HEAD","OPTIONS"].includes(C.method.toUpperCase()),L=new URL(C.url),Kt=await(async()=>{let Ze=Te??bs,nt=rA(r,Ze.port??n),wr=await Db(C,Md(Ze.requestIP(C)?.address??"unknown"));if(wr)return wr;let mr=L.searchParams.get("env"),ye=iA(f,T,mr),Lt=W.get(ye);if(!Lt)Lt=await tt(ye);try{if(!cA(C))return b({ok:!1,error:"Cross-site requests are not allowed."},403);let jo=/^\/api\/source\/webhooks\/([A-Za-z0-9_-]{16,200})$/.exec(L.pathname);if(jo&&C.method==="POST"){let d=await lg({sources:Ve,controlPlane:a.store,endpointToken:jo[1],headers:C.headers,rawBody:new Uint8Array(await C.arrayBuffer())});return b({accepted:d.accepted,duplicate:d.duplicate,status:d.status,operationIds:d.operations.map((l)=>l.id),message:d.message},d.accepted?202:404)}let Ss=/^\/auth\/oidc\/([a-z0-9-]+)\/(start|callback)$/.exec(L.pathname);if(Ss&&C.method==="GET"){let[,d,l]=Ss;if(!nt)return new Response(null,{status:302,headers:{location:"/login?sso_error=configuration"}});if(l==="start")try{let k=await cu(Ie,d,nt,L.searchParams.get("return")??void 0,e.oidcFetch);return new Response(null,{status:302,headers:{location:k.authorizationUrl,"cache-control":"no-store"}})}catch(k){return a.store.appendEvent({organizationId:a.organization.id,type:"auth.oidc.start_failed",level:"warning",payload:{provider:d,reason:k instanceof Error?k.message.slice(0,200):"unknown"}}),new Response(null,{status:302,headers:{location:"/login?sso_error=start","cache-control":"no-store"}})}try{if(L.searchParams.has("error")){let X=Ie.getOidcProviderBySlug(d),j=L.searchParams.get("state");if(X&&j)Ie.consumeOidcTransaction(X.id,j);throw Error("OIDC provider returned an authorization error")}let k=await du(Ie,{providerSlug:d,state:L.searchParams.get("state")??"",code:L.searchParams.get("code")??"",origin:nt},e.oidcFetch),M=ly(Ie,a,t,k.identity);Ie.recordLogin(M.identity.id);let B=qa(M.identity.id,C,Ze.requestIP(C)?.address??"unknown","oidc");return pi(),a.store.appendEvent({organizationId:a.organization.id,actorId:M.identity.actorId,type:"auth.login.succeeded",payload:{method:"oidc",provider:d,provisioned:M.provisioned}}),new Response(null,{status:302,headers:{location:k.returnPath,"cache-control":"no-store","set-cookie":na(B.token,{secure:yo,maxAgeMs:Eo})}})}catch(k){return a.store.appendEvent({organizationId:a.organization.id,type:"auth.oidc.callback_failed",level:"warning",payload:{provider:d,reason:k instanceof Error?k.message.slice(0,200):"unknown"}}),new Response(null,{status:302,headers:{location:"/login?sso_error=callback","cache-control":"no-store"}})}}if(L.pathname==="/api/invitations/accept"&&C.method==="POST"){let d=await se(C),l=String(d.token??"").trim(),k=String(d.username??"").trim(),M=String(d.password??"");if(!l||!Sd(k)||M.length<12)return b({ok:!1,error:"Invitation token, valid username, and a password of at least 12 characters are required."},422);let B=a.store.inspectInvitationToken(l);if(!B||B.state!=="pending")return b({ok:!1,error:B?`Invitation is ${B.state}`:"Invitation is invalid"},B?409:404);let X=ui(dn(t),k),j=Ie.getIdentityByUsername(k);if(X&&!Ei(M,j?.passwordHash??X.passwordHash))return b({ok:!1,error:"That username already exists; enter its current password to continue."},401);let Z=Ie.getIdentityByEmail(B.email);if(Z&&Z.id!==j?.id)return b({ok:!1,error:"This invitation belongs to an existing account. Sign in with that account or ask an owner to resend it."},409);let fe=Na(t,{username:k,password:X?void 0:M,name:typeof d.name==="string"?d.name:void 0,email:B.email,sites:X?.sites??{}}),pe=gr(a.store,fe.user);try{let He=a.store.acceptInvitation(l,pe.id),ve=j?Ie.setVerifiedEmail(j.id,He.invitation.email):Ie.createIdentity({actorId:pe.id,username:fe.user.username,email:He.invitation.email,emailVerified:!0,passwordHash:fe.user.passwordHash}),Fe=qa(ve.id,C,Ze.requestIP(C)?.address??"unknown");return pi(),b({ok:!0,user:oa(fe.user),organization:a.organization,membership:He.membership},200,{"set-cookie":na(Fe.token,{secure:yo,maxAgeMs:Eo})})}catch(He){if(!X)Jl(t,fe.user.username);let ve=He instanceof Error?He.message:"Invitation could not be accepted.";return b({ok:!1,error:ve},ve.includes("expired")||ve.includes("revoked")||ve.includes("accepted")?409:404)}}if(L.pathname==="/api/auth/password-reset/request"&&C.method==="POST"){let d=await se(C),l=String(d.identifier??"").trim().toLowerCase(),k=Ze.requestIP(C)?.address??"unknown",M=Nd.check(l,k),B=l.includes("@")?Ie.getIdentityByEmail(l):Ie.getIdentityByUsername(l);if(M.allowed)Nd.recordFailure(l,k);if(M.allowed&&B?.email&&B.emailVerifiedAt&&!B.disabledAt){Ie.revokeActionTokens(B.id,"password_reset");let X=Ie.createActionToken(B.id,"password_reset"),j=`${L.origin}/reset-password?token=${encodeURIComponent(X.token)}`,Z=await ba(o,{to:B.email,subject:"Reset your ts-cloud password",text:`Reset your ts-cloud password: ${j}
484
+ `)},message(C,Te){Q.get(C)?.write(typeof Te==="string"?Te:new TextDecoder().decode(Te))},close(C){Q.get(C)?.close(),Q.delete(C)}},async fetch(C,Te){let _e=Date.now(),Ce=C.clone(),Ge=C.headers.get("x-request-id")?.slice(0,128)||crypto.randomUUID(),gt=!["GET","HEAD","OPTIONS"].includes(C.method.toUpperCase()),L=new URL(C.url),Kt=await(async()=>{let Ze=Te??bs,nt=rA(r,Ze.port??n),wr=await Db(C,Md(Ze.requestIP(C)?.address??"unknown"));if(wr)return wr;let mr=L.searchParams.get("env"),ye=iA(f,T,mr),Lt=W.get(ye);if(!Lt)Lt=await tt(ye);try{if(!cA(C))return b({ok:!1,error:"Cross-site requests are not allowed."},403);let jo=/^\/api\/source\/webhooks\/([A-Za-z0-9_-]{16,200})$/.exec(L.pathname);if(jo&&C.method==="POST"){let d=await lg({sources:Ve,controlPlane:a.store,endpointToken:jo[1],headers:C.headers,rawBody:new Uint8Array(await C.arrayBuffer())});return b({accepted:d.accepted,duplicate:d.duplicate,status:d.status,operationIds:d.operations.map((l)=>l.id),message:d.message},d.accepted?202:404)}let Ss=/^\/auth\/oidc\/([a-z0-9-]+)\/(start|callback)$/.exec(L.pathname);if(Ss&&C.method==="GET"){let[,d,l]=Ss;if(!nt)return new Response(null,{status:302,headers:{location:"/login?sso_error=configuration"}});if(l==="start")try{let k=await cu(Ie,d,nt,L.searchParams.get("return")??void 0,e.oidcFetch);return new Response(null,{status:302,headers:{location:k.authorizationUrl,"cache-control":"no-store"}})}catch(k){return a.store.appendEvent({organizationId:a.organization.id,type:"auth.oidc.start_failed",level:"warning",payload:{provider:d,reason:k instanceof Error?k.message.slice(0,200):"unknown"}}),new Response(null,{status:302,headers:{location:"/login?sso_error=start","cache-control":"no-store"}})}try{if(L.searchParams.has("error")){let X=Ie.getOidcProviderBySlug(d),j=L.searchParams.get("state");if(X&&j)Ie.consumeOidcTransaction(X.id,j);throw Error("OIDC provider returned an authorization error")}let k=await du(Ie,{providerSlug:d,state:L.searchParams.get("state")??"",code:L.searchParams.get("code")??"",origin:nt},e.oidcFetch),M=ly(Ie,a,t,k.identity);Ie.recordLogin(M.identity.id);let F=qa(M.identity.id,C,Ze.requestIP(C)?.address??"unknown","oidc");return pi(),a.store.appendEvent({organizationId:a.organization.id,actorId:M.identity.actorId,type:"auth.login.succeeded",payload:{method:"oidc",provider:d,provisioned:M.provisioned}}),new Response(null,{status:302,headers:{location:k.returnPath,"cache-control":"no-store","set-cookie":na(F.token,{secure:yo,maxAgeMs:Eo})}})}catch(k){return a.store.appendEvent({organizationId:a.organization.id,type:"auth.oidc.callback_failed",level:"warning",payload:{provider:d,reason:k instanceof Error?k.message.slice(0,200):"unknown"}}),new Response(null,{status:302,headers:{location:"/login?sso_error=callback","cache-control":"no-store"}})}}if(L.pathname==="/api/invitations/accept"&&C.method==="POST"){let d=await se(C),l=String(d.token??"").trim(),k=String(d.username??"").trim(),M=String(d.password??"");if(!l||!Sd(k)||M.length<12)return b({ok:!1,error:"Invitation token, valid username, and a password of at least 12 characters are required."},422);let F=a.store.inspectInvitationToken(l);if(!F||F.state!=="pending")return b({ok:!1,error:F?`Invitation is ${F.state}`:"Invitation is invalid"},F?409:404);let X=ui(dn(t),k),j=Ie.getIdentityByUsername(k);if(X&&!Ei(M,j?.passwordHash??X.passwordHash))return b({ok:!1,error:"That username already exists; enter its current password to continue."},401);let Z=Ie.getIdentityByEmail(F.email);if(Z&&Z.id!==j?.id)return b({ok:!1,error:"This invitation belongs to an existing account. Sign in with that account or ask an owner to resend it."},409);let fe=Na(t,{username:k,password:X?void 0:M,name:typeof d.name==="string"?d.name:void 0,email:F.email,sites:X?.sites??{}}),pe=gr(a.store,fe.user);try{let He=a.store.acceptInvitation(l,pe.id),ve=j?Ie.setVerifiedEmail(j.id,He.invitation.email):Ie.createIdentity({actorId:pe.id,username:fe.user.username,email:He.invitation.email,emailVerified:!0,passwordHash:fe.user.passwordHash}),Be=qa(ve.id,C,Ze.requestIP(C)?.address??"unknown");return pi(),b({ok:!0,user:oa(fe.user),organization:a.organization,membership:He.membership},200,{"set-cookie":na(Be.token,{secure:yo,maxAgeMs:Eo})})}catch(He){if(!X)Jl(t,fe.user.username);let ve=He instanceof Error?He.message:"Invitation could not be accepted.";return b({ok:!1,error:ve},ve.includes("expired")||ve.includes("revoked")||ve.includes("accepted")?409:404)}}if(L.pathname==="/api/auth/password-reset/request"&&C.method==="POST"){let d=await se(C),l=String(d.identifier??"").trim().toLowerCase(),k=Ze.requestIP(C)?.address??"unknown",M=Nd.check(l,k),F=l.includes("@")?Ie.getIdentityByEmail(l):Ie.getIdentityByUsername(l);if(M.allowed)Nd.recordFailure(l,k);if(M.allowed&&F?.email&&F.emailVerifiedAt&&!F.disabledAt){Ie.revokeActionTokens(F.id,"password_reset");let X=Ie.createActionToken(F.id,"password_reset"),j=`${L.origin}/reset-password?token=${encodeURIComponent(X.token)}`,Z=await ba(o,{to:F.email,subject:"Reset your ts-cloud password",text:`Reset your ts-cloud password: ${j}
485
485
 
486
- This link expires in one hour and can be used once.`});a.store.appendEvent({organizationId:a.organization.id,actorId:B.actorId,type:"auth.password_reset.requested",payload:{delivered:Z}})}return b({ok:!0,message:"If that account has a verified email, a reset link has been sent."},202)}if(L.pathname==="/api/auth/password-reset/complete"&&C.method==="POST"){let d=await se(C),l=String(d.token??"").trim(),k=String(d.password??"");if(!l||k.length<12)return b({ok:!1,error:"A valid reset token and password of at least 12 characters are required."},422);try{let M=Ie.consumeActionToken(l,"password_reset"),B=No(k),X=Ie.updatePassword(M.identityId,B);return wd(t,X.username,B),a.store.appendEvent({organizationId:a.organization.id,actorId:X.actorId,type:"auth.password_reset.completed"}),b({ok:!0,message:"Password changed. Sign in again."},200,{"set-cookie":bd({secure:yo})})}catch(M){let B=M instanceof Error?M.message:"Password reset failed.";return b({ok:!1,error:B.replace("Action token","Reset link")},B.includes("consumed")||B.includes("expired")?409:404)}}if(L.pathname==="/api/login"&&C.method==="POST"){let d=await se(C),l=String(d.username??"").trim(),k=String(d.password??""),M=Ze.requestIP(C)?.address??"unknown",B=za.check(l,M);if(!B.allowed)return b({ok:!1,error:`Too many failed attempts. Try again in ${Math.ceil((B.retryAfterSeconds??0)/60)} minute(s).`},429,{"retry-after":String(B.retryAfterSeconds??60)});let X=ui(dn(t),l),j=Ie.getIdentityByUsername(l),Z=j?.passwordHash??X?.passwordHash??tA;if(!(Ei(k,Z)&&!!X&&!!j&&!j.disabledAt))return za.recordFailure(l,M),b({ok:!1,error:"Incorrect username or password."},401);if(py(Ie,a,j))return b({ok:!1,error:"Single sign-on is required for this account."},403);za.recordSuccess(l,M);let pe=j,He=pe.requiresPasswordUpgrade||Bh(pe.passwordHash);if(He){let Fe=No(k);pe=Ie.rehashPassword(pe.id,Fe),wd(t,pe.username,Fe)}if(Ie.recordLogin(pe.id),Ie.getMfaFactor(pe.id)?.state==="active"){let Fe=Ie.createMfaChallenge(pe.id,"login");return a.store.appendEvent({organizationId:a.organization.id,actorId:pe.actorId,type:"auth.mfa.challenge.created",payload:{purpose:"login"}}),b({ok:!0,mfaRequired:!0,challengeToken:Fe.token,passwordUpgraded:He})}let ve=qa(pe.id,C,M);return a.store.appendEvent({organizationId:a.organization.id,actorId:pe.actorId,type:"auth.login.succeeded",payload:{method:"local"}}),b({ok:!0,user:oa(X),passwordUpgraded:He},200,{"set-cookie":na(ve.token,{secure:yo,maxAgeMs:Eo})})}if(L.pathname==="/api/auth/mfa/complete"&&C.method==="POST"){let d=await se(C),l=String(d.challengeToken??"").trim(),k=String(d.code??"").trim(),M=Ze.requestIP(C)?.address??"unknown",X=Ie.inspectMfaChallengeToken(l,"login")?.identityId??"unknown-mfa",j=Va.check(X,M);if(!j.allowed)return b({ok:!1,error:"Too many MFA attempts. Try again later."},429,{"retry-after":String(j.retryAfterSeconds??60)});try{let Z=Ie.completeMfaChallenge(l,k,"login");Va.recordSuccess(X,M);let fe=new Date().toISOString(),pe=Ie.createSession({identityId:Z.identity.id,userAgent:Ap(C),networkHint:Md(M),mfaAt:fe,recentAuthAt:fe});return a.store.appendEvent({organizationId:a.organization.id,actorId:Z.identity.actorId,type:"auth.mfa.succeeded",payload:{purpose:"login",method:Z.method}}),b({ok:!0},200,{"set-cookie":na(pe.token,{secure:yo,maxAgeMs:Eo})})}catch{return Va.recordFailure(X,M),b({ok:!1,error:"Authenticator or recovery code is incorrect."},401)}}if(L.pathname==="/api/logout"&&C.method==="POST"){let d=jt.resolveSession(C);if(d)Ie.revokeSession(d.identityId,d.id);let l=bd({secure:yo});if(C.headers.get("accept")?.includes("text/html"))return new Response(null,{status:302,headers:{location:"/login","set-cookie":l}});return b({ok:!0},200,{"set-cookie":l})}if(L.pathname==="/login"){let d=Ie.listOidcProviders(a.organization.id).map((l)=>({slug:l.slug,name:l.name}));return new Response(gy(D?.mode==="serverless",d),{headers:{"content-type":"text/html; charset=utf-8"}})}if(L.pathname==="/forgot-password"||L.pathname==="/reset-password")return new Response(my(L.pathname==="/reset-password"?"reset":"request"),{headers:{"content-type":"text/html; charset=utf-8"}});if(L.pathname==="/accept-invitation")return hb(Ri,L.pathname);let ue=jt.resolveUser(C);if(!ue){if(!L.pathname.startsWith("/api/")&&C.headers.get("accept")?.includes("text/html"))return new Response(null,{status:302,headers:{location:"/login"}});return b({ok:!1,error:"Sign in to continue."},401)}let Tn=lo(ue,ye);if(L.pathname==="/api/me"){let d=a.store.getActorByExternalId("user",`dashboard:${ue.username.toLowerCase()}`),l=d?a.store.getMembershipForActor(a.organization.id,d.id):void 0,k=a.store.resolveAuthorizationTarget(a.organization.id,l?.scope??{type:"project",id:a.project.id})??a.store.resolveAuthorizationTarget(a.organization.id,{type:"project",id:a.project.id});return b({ok:!0,user:oa(ue),authEnabled:Pe,organization:a.organization,membership:l,capabilities:hn({membership:l,grants:l?a.store.listGrants(l.id):[],target:k})})}if(L.pathname.startsWith("/api/")){let d=await dy(C,L.pathname),l=jt.check(C,L.pathname,ue,d);if(!l.ok)return b({ok:!1,error:l.error},l.status??403);if(Pe&&lA.has(`${C.method.toUpperCase()} ${L.pathname}`)){let k=jt.resolveSession(C);if(!k||!Ie.isRecentlyAuthenticated(k))return b({ok:!1,error:"Recent authentication is required for this change.",stepUpRequired:!0},401)}}if(L.pathname==="/api/auth/security"&&C.method==="GET"){let d=Ne(ue),l=d.actor?Ie.getIdentityByActor(d.actor.id):void 0,k=jt.resolveSession(C);return b({identity:l?{username:l.username,email:l.email,emailVerifiedAt:l.emailVerifiedAt,requiresPasswordUpgrade:l.requiresPasswordUpgrade,lastLoginAt:l.lastLoginAt}:void 0,currentSessionId:k?.id,sessions:l?Ie.listSessions(l.id,{includeInactive:!0}):[],mfa:l?{factor:Ie.getMfaFactor(l.id),recoveryCodesRemaining:Ie.remainingRecoveryCodes(l.id)}:void 0})}if(L.pathname==="/api/auth/oidc/providers"&&C.method==="GET")return b({providers:Ie.listOidcProviders(a.organization.id,{includeDisabled:!0}),callbackOrigin:nt,callbackPattern:nt?`${nt}/auth/oidc/{slug}/callback`:void 0,localOwnerRecovery:!0});if(L.pathname==="/api/auth/oidc/providers"&&C.method==="POST"){let d=await se(C),l=Ne(ue),k=l.actor?Ie.getIdentityByActor(l.actor.id):void 0,M=d.enforceSso===!0;if(M&&(!k?.emailVerifiedAt||Ie.remainingRecoveryCodes(k.id)<1))return b({ok:!1,error:"Verify the owner email and generate MFA recovery codes before enforcing SSO."},409);try{let B=Td(d.defaultRole),X=Ie.upsertOidcProvider({id:typeof d.id==="string"?d.id:void 0,organizationId:a.organization.id,slug:String(d.slug??""),name:String(d.name??""),issuer:String(d.issuer??""),clientId:String(d.clientId??""),clientSecret:typeof d.clientSecret==="string"&&d.clientSecret?d.clientSecret:void 0,scopes:Array.isArray(d.scopes)?d.scopes.map(String):void 0,allowedDomains:Array.isArray(d.allowedDomains)?d.allowedDomains.map(String):[],defaultRole:B&&B!=="owner"?B:void 0,enabled:d.enabled!==!1,enforceSso:M});return a.store.appendEvent({organizationId:a.organization.id,actorId:l.actor?.id,type:"auth.oidc.provider.configured",payload:{providerId:X.id,issuer:X.issuer,enabled:X.enabled,enforceSso:X.enforceSso}}),b({ok:!0,provider:X})}catch(B){return b({ok:!1,error:B instanceof Error?B.message:"OIDC provider could not be saved."},422)}}if(L.pathname==="/api/auth/oidc/providers"&&C.method==="PATCH"){let d=await se(C),l=Ie.getOidcProvider(String(d.id??""));if(!l||l.organizationId!==a.organization.id)return b({ok:!1,error:"OIDC provider was not found."},404);let k=Ne(ue),M=Ie.setOidcProviderEnabled(l.id,d.enabled===!0);return a.store.appendEvent({organizationId:a.organization.id,actorId:k.actor?.id,type:M.enabled?"auth.oidc.provider.enabled":"auth.oidc.provider.disabled",payload:{providerId:l.id}}),b({ok:!0,provider:M})}if(L.pathname==="/api/automation"&&C.method==="GET"){let d=lt.listServiceAccounts(a.organization.id,{includeDisabled:!0}).map((l)=>{let k=a.store.getMembershipForActor(a.organization.id,l.actorId),M=l.createdByActorId?a.store.getActor(l.createdByActorId):void 0,B=lt.listTokens(l.id,{includeInactive:!0}).map((X)=>({...X,createdBy:X.createdByActorId?a.store.getActor(X.createdByActorId):void 0}));return{account:l,createdBy:M,membership:k,tokens:B}});return b({accounts:d,apiBaseUrl:`${L.origin}/api/v1`,openApiUrl:`${L.origin}/api/v1/openapi.json`,tokenEnvironmentVariable:"TS_CLOUD_API_TOKEN"})}if(L.pathname==="/api/automation/service-accounts"&&C.method==="POST"){let d=await se(C),l=Ne(ue),k=Td(d.roleTemplate),M=Ba(d);if(!l.actor||!k||k==="owner"||!M)return b({ok:!1,error:"A non-owner role and valid organization scope are required."},422);try{let B=lt.createServiceAccount({organizationId:a.organization.id,slug:String(d.slug??""),name:String(d.name??""),description:typeof d.description==="string"?d.description:void 0,roleTemplate:k,scope:M,createdByActorId:l.actor.id});return b({ok:!0,...B},201)}catch(B){return b({ok:!1,error:B instanceof Error?B.message:"Service account could not be created."},422)}}if(L.pathname==="/api/automation/service-accounts"&&C.method==="PATCH"){let d=await se(C),l=Ne(ue),k=lt.getServiceAccount(String(d.id??""));if(!k||k.organizationId!==a.organization.id)return b({ok:!1,error:"Service account was not found."},404);return b({ok:!0,account:lt.disableServiceAccount(k.id,l.actor?.id)})}if(L.pathname==="/api/automation/tokens"&&C.method==="POST"){let d=await se(C),l=Ne(ue),k=lt.getServiceAccount(String(d.serviceAccountId??"")),M=Ba(d);if(!l.actor||!k||k.organizationId!==a.organization.id||!M||!Array.isArray(d.capabilities))return b({ok:!1,error:"Service account, explicit capabilities, and valid scope are required."},422);try{let B=lt.createToken({serviceAccountId:k.id,name:String(d.name??"API token"),capabilities:d.capabilities.map(String),scope:M,expiresAt:typeof d.expiresAt==="string"?d.expiresAt:void 0,createdByActorId:l.actor.id});return b({ok:!0,token:B.token,secret:B.secret,revealOnce:!0},201)}catch(B){return b({ok:!1,error:B instanceof Error?B.message:"API token could not be created."},422)}}if(L.pathname==="/api/automation/tokens/rotate"&&C.method==="POST"){let d=await se(C),l=Ne(ue),k=lt.getToken(String(d.id??"")),M=k?lt.getServiceAccount(k.serviceAccountId):void 0;if(!l.actor||!k||M?.organizationId!==a.organization.id)return b({ok:!1,error:"API token was not found."},404);try{let B=lt.rotateToken(k.id,l.actor.id);return b({ok:!0,token:B.token,secret:B.secret,revealOnce:!0,overlap:!0},201)}catch(B){return b({ok:!1,error:B instanceof Error?B.message:"API token could not be rotated."},409)}}if(L.pathname==="/api/automation/tokens"&&C.method==="DELETE"){let d=await se(C),l=Ne(ue),k=lt.getToken(String(d.id??"")),M=k?lt.getServiceAccount(k.serviceAccountId):void 0;if(!k||M?.organizationId!==a.organization.id)return b({ok:!1,error:"API token was not found."},404);return b({ok:!0,token:lt.revokeToken(k.id,l.actor?.id)})}if(L.pathname==="/api/onboarding"&&C.method==="GET"){let d=Ve.listConnections(a.organization.id);return b({drafts:Mr.list(a.project.id),artifacts:hs.list(a.project.id),registries:Pi.list(a.organization.id),sourceConnections:d,repositories:d.flatMap((l)=>Ve.listRepositories(l.id)),project:{id:a.project.id,slug:a.project.slug,name:a.project.name},environments:[...a.environments.values()].map((l)=>({id:l.id,slug:l.slug,name:l.name,kind:l.kind,region:l.region})),resources:a.store.listResources(a.project.id).filter((l)=>l.kind==="application").map((l)=>({id:l.id,slug:l.slug,name:l.name,environmentId:l.environmentId}))})}if(L.pathname==="/api/onboarding/detect"&&C.method==="POST"){let d=await se(C);try{if(d.source?.kind==="git"){let M=Ve.getConnection(String(d.source.connectionId??"")),B=Ve.getRepository(String(d.source.repositoryId??""));if(!M||M.organizationId!==a.organization.id||!B||B.connectionId!==M.id)throw Error("Authorized Git repository was not found");let X=typeof d.source.deployKeyId==="string"?Ve.getDeployKey(d.source.deployKeyId):void 0;if(X&&X.connectionId!==M.id)throw Error("Deploy key does not belong to this connection");let j=cp(Ct(kd(),"ts-cloud-onboarding-git-"));try{let Z=await Qd({remote:B.cloneUrl,destination:Ct(j,"checkout"),ref:String(d.source.ref??B.defaultBranch),sparsePaths:Array.isArray(d.source.sparsePaths)?d.source.sparsePaths.map(String):void 0,binding:{id:"detection",projectId:a.project.id,connectionId:M.id,repositoryId:B.id,repositoryFullName:B.fullName,defaultBranch:B.defaultBranch,monorepoRoot:String(d.source.monorepoRoot??"."),includePaths:[],excludePaths:[],submodules:d.source.submodules===!0,cloneDepth:1,deployKeyId:X?.id,autoDeploy:!1,pullRequestPreviews:!1,status:"active",version:1,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}},{credential:Ve.getCredential(M.id),deployKey:X?{...X,privateKey:Ve.getDeployPrivateKey(X.id)}:void 0,timeoutMs:120000});return b({ok:!0,commitSha:Z.commitSha,candidates:kt(Jn(Z.directory))})}finally{fs(j,{recursive:!0,force:!0})}}if(Array.isArray(d.files)){if(d.files.length>1e4)throw Error("Detection file-count limit exceeded");let M=d.files.map((B)=>({path:String(B.path??""),size:Number(B.size??0),content:typeof B.content==="string"?B.content.slice(0,262144):void 0}));return b({ok:!0,candidates:kt(M)})}let l=qT(t,String(d.root??".")),k=VT(t,l);if(k===".."||k.startsWith(`..${GT}`))throw Error("Detection root must stay inside the project");return b({ok:!0,candidates:kt(Jn(l))})}catch(l){return b({ok:!1,error:l instanceof Error?l.message:"Application detection failed."},422)}}if(L.pathname==="/api/onboarding/plan"&&C.method==="POST"){let d=await se(C);try{return b({ok:!0,plan:ce(d.draft,Array.isArray(d.suppliedSecretNames)?d.suppliedSecretNames.map(String):[])})}catch(l){return b({ok:!1,error:l instanceof Error?l.message:"Application plan could not be generated."},422)}}if(L.pathname==="/api/onboarding/drafts"&&C.method==="POST"){let d=await se(C),l=Ne(ue);try{return b({ok:!0,draft:Mr.create({organizationId:a.organization.id,projectId:a.project.id,name:String(d.name??d.draft?.name??"Application draft"),draft:{...d.draft,projectId:a.project.id},step:d.step,suppliedSecretNames:Array.isArray(d.suppliedSecretNames)?d.suppliedSecretNames.map(String):[],actorId:l.actor?.id})},201)}catch(k){return b({ok:!1,error:k instanceof Error?k.message:"Application draft could not be saved."},422)}}if(L.pathname==="/api/onboarding/drafts"&&C.method==="PATCH"){let d=await se(C),l=Ne(ue),k=Mr.get(String(d.id??""));if(!k||k.projectId!==a.project.id)return b({ok:!1,error:"Application draft was not found."},404);try{return b({ok:!0,draft:Mr.update(k.id,Number(d.version),{draft:{...d.draft,projectId:a.project.id},step:d.step,suppliedSecretNames:Array.isArray(d.suppliedSecretNames)?d.suppliedSecretNames.map(String):void 0,actorId:l.actor?.id})})}catch(M){return b({ok:!1,error:M instanceof Error?M.message:"Application draft could not be updated."},409)}}if(L.pathname==="/api/onboarding/artifacts"&&C.method==="POST"){let d=Ne(ue);if(Number(C.headers.get("content-length")??0)>104857600)return b({ok:!1,error:"Artifact exceeds the 100 MB upload limit."},413);try{let k=new Uint8Array(await C.arrayBuffer());return b({ok:!0,artifact:hs.create({organizationId:a.organization.id,projectId:a.project.id,filename:C.headers.get("x-artifact-filename")??"application.zip",bytes:k,actorId:d.actor?.id})},201)}catch(k){return b({ok:!1,error:k instanceof Error?k.message:"Artifact could not be inspected."},422)}}if(L.pathname==="/api/onboarding/registries"&&C.method==="POST"){let d=await se(C),l=Ne(ue);try{return b({ok:!0,registry:Pi.create({organizationId:a.organization.id,provider:d.provider,name:String(d.name??"Container registry"),host:String(d.host??""),credential:d.token||d.password?{username:typeof d.username==="string"?d.username:void 0,password:typeof d.password==="string"?d.password:void 0,token:typeof d.token==="string"?d.token:void 0}:void 0,credentialExpiresAt:typeof d.credentialExpiresAt==="string"?d.credentialExpiresAt:void 0,actorId:l.actor?.id})},201)}catch(k){return b({ok:!1,error:k instanceof Error?k.message:"Registry connection could not be created."},422)}}if(L.pathname==="/api/onboarding/registries"&&C.method==="PATCH"){let d=await se(C),l=Ne(ue),k=Pi.get(String(d.id??""));if(!k||k.organizationId!==a.organization.id)return b({ok:!1,error:"Registry connection was not found."},404);try{if(d.action==="test")return b({ok:!0,registry:await Pi.test(k.id,{image:typeof d.image==="string"?d.image:void 0})});if(d.action==="rotate")return b({ok:!0,registry:Pi.rotate(k.id,{username:typeof d.username==="string"?d.username:void 0,password:typeof d.password==="string"?d.password:void 0,token:typeof d.token==="string"?d.token:void 0},{expiresAt:typeof d.expiresAt==="string"?d.expiresAt:void 0,actorId:l.actor?.id})});return b({ok:!1,error:"Registry action must be test or rotate."},422)}catch(M){return b({ok:!1,error:M instanceof Error?M.message:"Registry connection could not be updated."},422)}}if(L.pathname==="/api/onboarding/registries"&&C.method==="DELETE"){let d=await se(C),l=Ne(ue),k=Pi.get(String(d.id??""));if(!k||k.organizationId!==a.organization.id)return b({ok:!1,error:"Registry connection was not found."},404);let M=Mr.list(a.project.id).filter((B)=>B.input.source.kind==="image"&&B.input.source.registryConnectionId===k.id||B.input.build.kind==="prebuilt_image"&&B.input.build.registryConnectionId===k.id);if(d.preview===!0)return b({ok:!0,preview:!0,affectedDrafts:M});return b({ok:!0,registry:Pi.disconnect(k.id,l.actor?.id),affectedDrafts:M})}if(L.pathname==="/api/onboarding/apply"&&C.method==="POST"){let d=await se(C),l=Ne(ue);try{let k=zr({controlPlane:a.store,drafts:Mr,draftId:String(d.id??""),expectedVersion:Number(d.version),confirmEnvironment:String(d.confirmEnvironment??""),actorId:l.actor?.id});return b({ok:!0,resource:k.resource,operation:k.operation,plan:k.plan},202)}catch(k){return b({ok:!1,error:k instanceof Error?k.message:"Application plan could not be applied."},422)}}if(L.pathname==="/api/sources"&&C.method==="GET"){let d=Ve.listConnections(a.organization.id);return b({connections:d,bindings:Ve.listBindings({projectId:a.project.id}),repositories:d.flatMap((l)=>Ve.listRepositories(l.id)),deployKeys:d.flatMap((l)=>Ve.listDeployKeys(l.id)),webhooks:d.flatMap((l)=>Ve.listWebhooks(l.id)).map((l)=>({...l,deliveries:Ve.listDeliveries(l.id,20)})),project:{id:a.project.id,slug:a.project.slug},environment:le(a,String(ye)),resources:a.store.listResources(a.project.id,le(a,String(ye)).environmentId).filter((l)=>l.kind==="application").map((l)=>({id:l.id,slug:l.slug,name:l.name}))})}if(L.pathname==="/api/sources/connections"&&C.method==="POST"){let d=await se(C),l=Ne(ue),k=String(d.provider??"");if(!["github","gitlab","bitbucket","gitea","generic_https","generic_ssh"].includes(k))return b({ok:!1,error:"A supported Git provider is required."},422);try{let M=k==="github"&&(d.privateKey||d.appId)?{appId:typeof d.appId==="string"?d.appId:void 0,installationId:typeof d.installationId==="string"?d.installationId:void 0,privateKey:typeof d.privateKey==="string"?d.privateKey:void 0}:k!=="generic_ssh"&&d.token?{token:typeof d.token==="string"?d.token:void 0,username:typeof d.username==="string"?d.username:void 0}:void 0,B={github:"https://github.com",gitlab:"https://gitlab.com",bitbucket:"https://bitbucket.org",gitea:"https://gitea.com"},X,j,Z;if(a.store.database.transaction(()=>{if(X=Ve.createConnection({organizationId:a.organization.id,provider:k,name:String(d.name??k),host:String(d.host??B[k]??""),owner:typeof d.owner==="string"?d.owner:void 0,authKind:d.authKind,credential:M,grantedScopes:Array.isArray(d.grantedScopes)?d.grantedScopes.map(String):[],credentialExpiresAt:typeof d.credentialExpiresAt==="string"?d.credentialExpiresAt:void 0,createdByActorId:l.actor?.id}),typeof d.repositoryUrl==="string"&&typeof d.repositoryFullName==="string")j=Ve.upsertRepository({connectionId:X.id,providerRepositoryId:`manual:${d.repositoryFullName}`,fullName:d.repositoryFullName,cloneUrl:d.repositoryUrl,defaultBranch:String(d.defaultBranch??"main"),visibility:"unknown",archived:!1,metadata:{source:"manual"}});if(k==="generic_ssh")Z=Ve.createDeployKey({connectionId:X.id,name:String(d.deployKeyName??"Repository deploy key"),publicKey:String(d.publicKey??""),privateKey:String(d.deployPrivateKey??""),host:String(d.sshHost??""),hostKey:String(d.hostKey??""),actorId:l.actor?.id})})(),d.test===!0)X=await Yd(Ve,X.id,j?.id);return b({ok:!0,connection:X,repository:j,deployKey:Z},201)}catch(M){return b({ok:!1,error:M instanceof Error?M.message:"Source connection could not be created."},422)}}if(L.pathname==="/api/sources/connections"&&C.method==="PATCH"){let d=await se(C),l=Ne(ue),k=Ve.getConnection(String(d.id??""));if(!k||k.organizationId!==a.organization.id)return b({ok:!1,error:"Source connection was not found."},404);try{if(d.action==="test")return b({ok:!0,connection:await Yd(Ve,k.id,typeof d.repositoryId==="string"?d.repositoryId:void 0)});if(d.action==="rotate")return b({ok:!0,connection:Ve.rotateCredential(k.id,{token:typeof d.token==="string"?d.token:void 0,username:typeof d.username==="string"?d.username:void 0,appId:typeof d.appId==="string"?d.appId:void 0,installationId:typeof d.installationId==="string"?d.installationId:void 0,privateKey:typeof d.privateKey==="string"?d.privateKey:void 0},{expiresAt:typeof d.expiresAt==="string"?d.expiresAt:void 0,actorId:l.actor?.id})});return b({ok:!1,error:"Connection action must be test or rotate."},422)}catch(M){return b({ok:!1,error:M instanceof Error?M.message:"Source connection could not be updated."},422)}}if(L.pathname==="/api/sources/connections"&&C.method==="DELETE"){let d=await se(C),l=Ne(ue),k=Ve.getConnection(String(d.id??""));if(!k||k.organizationId!==a.organization.id)return b({ok:!1,error:"Source connection was not found."},404);let M=Ve.listBindings({connectionId:k.id,status:"active"});if(d.preview===!0)return b({ok:!0,preview:!0,affectedBindings:M});return b({ok:!0,...Ve.disconnectConnection(k.id,l.actor?.id)})}if(L.pathname==="/api/sources/deploy-keys"&&C.method==="POST"){let d=await se(C),l=Ne(ue),k=Ve.getConnection(String(d.connectionId??""));if(!k||k.organizationId!==a.organization.id)return b({ok:!1,error:"Source connection was not found."},404);try{return b({ok:!0,deployKey:Ve.createDeployKey({connectionId:k.id,name:String(d.name??"Repository deploy key"),publicKey:String(d.publicKey??""),privateKey:String(d.privateKey??""),host:String(d.host??""),hostKey:String(d.hostKey??""),actorId:l.actor?.id})},201)}catch(M){return b({ok:!1,error:M instanceof Error?M.message:"Deploy key could not be stored."},422)}}if(L.pathname==="/api/sources/deploy-keys"&&C.method==="DELETE"){let d=await se(C),l=Ne(ue),k=Ve.getDeployKey(String(d.id??"")),M=k?Ve.getConnection(k.connectionId):void 0;if(!k||!M||M.organizationId!==a.organization.id)return b({ok:!1,error:"Deploy key was not found."},404);let B=Ve.listBindings({connectionId:M.id}).filter((X)=>X.deployKeyId===k.id);if(d.preview===!0)return b({ok:!0,preview:!0,affectedBindings:B});return b({ok:!0,...Ve.revokeDeployKey(k.id,l.actor?.id)})}if(L.pathname==="/api/sources/repositories/sync"&&C.method==="POST"){let d=await se(C),l=Ve.getConnection(String(d.connectionId??""));if(!l||l.organizationId!==a.organization.id)return b({ok:!1,error:"Source connection was not found."},404);try{return b({ok:!0,repositories:await Vr(Ve,String(d.connectionId??""),{search:typeof d.search==="string"?d.search:void 0})})}catch(k){return b({ok:!1,error:k instanceof Error?k.message:"Repositories could not be synchronized."},422)}}if(L.pathname==="/api/sources/references"&&C.method==="GET"){let d=Ve.getConnection(String(L.searchParams.get("connectionId")??""));if(!d||d.organizationId!==a.organization.id)return b({ok:!1,error:"Source connection was not found."},404);try{return b(await nr(Ve,{connectionId:String(L.searchParams.get("connectionId")??""),repository:String(L.searchParams.get("repository")??""),repositoryId:L.searchParams.get("repositoryId")??void 0,deployKeyId:L.searchParams.get("deployKeyId")??void 0,type:L.searchParams.get("type")==="tags"?"tags":"branches",cursor:L.searchParams.get("cursor")??void 0}))}catch(l){return b({ok:!1,error:l instanceof Error?l.message:"References could not be listed."},422)}}if(L.pathname==="/api/sources/bindings"&&C.method==="POST"){let d=await se(C),l=Ne(ue),k=le(a,String(ye)),M=Ve.getConnection(String(d.connectionId??""));if(!M||M.organizationId!==a.organization.id)return b({ok:!1,error:"Source connection was not found."},404);try{return b({ok:!0,binding:Ve.createBinding({projectId:a.project.id,environmentId:k.environmentId,resourceId:typeof d.resourceId==="string"?d.resourceId:void 0,connectionId:String(d.connectionId??""),repositoryId:typeof d.repositoryId==="string"?d.repositoryId:void 0,repositoryFullName:String(d.repositoryFullName??""),defaultBranch:String(d.defaultBranch??"main"),branchRule:typeof d.branchRule==="string"?d.branchRule:void 0,tagRule:typeof d.tagRule==="string"?d.tagRule:void 0,monorepoRoot:String(d.monorepoRoot??"."),includePaths:Array.isArray(d.includePaths)?d.includePaths.map(String):[],excludePaths:Array.isArray(d.excludePaths)?d.excludePaths.map(String):[],submodules:d.submodules===!0,cloneDepth:d.cloneDepth?Number(d.cloneDepth):void 0,deployKeyId:typeof d.deployKeyId==="string"&&d.deployKeyId?d.deployKeyId:void 0,autoDeploy:d.autoDeploy!==!1,pullRequestPreviews:d.pullRequestPreviews!==!1,actorId:l.actor?.id})},201)}catch(B){return b({ok:!1,error:B instanceof Error?B.message:"Source binding could not be created."},422)}}if(L.pathname==="/api/sources/bindings"&&C.method==="PATCH"){let d=await se(C),l=Ne(ue),k=Ve.getBinding(String(d.id??""));if(!k||k.projectId!==a.project.id)return b({ok:!1,error:"Source binding was not found."},404);try{return b({ok:!0,binding:Ve.updateBinding(k.id,Number(d.version),{defaultBranch:d.defaultBranch,branchRule:d.branchRule,tagRule:d.tagRule,monorepoRoot:d.monorepoRoot,includePaths:d.includePaths,excludePaths:d.excludePaths,submodules:d.submodules,cloneDepth:d.cloneDepth,deployKeyId:d.deployKeyId,autoDeploy:d.autoDeploy,pullRequestPreviews:d.pullRequestPreviews,status:d.status,disabledReason:d.disabledReason,actorId:l.actor?.id})})}catch(M){return b({ok:!1,error:M instanceof Error?M.message:"Source binding could not be updated."},409)}}if(L.pathname==="/api/sources/webhooks"&&C.method==="POST"){let d=await se(C),l=Ve.getConnection(String(d.connectionId??""));if(!l||l.organizationId!==a.organization.id)return b({ok:!1,error:"Source connection was not found."},404);try{let k=Ve.createWebhook({connectionId:String(d.connectionId??""),repositoryId:typeof d.repositoryId==="string"?d.repositoryId:void 0,repositoryFullName:String(d.repositoryFullName??""),events:Array.isArray(d.events)?d.events.map(String):void 0,secret:typeof d.secret==="string"?d.secret:void 0}),M=process.env.TS_CLOUD_WEBHOOK_BASE_URL?.trim()||nt,B=M?Dt(M,k.webhook):void 0,X=d.reconcile!==!1&&M?await ir(Ve,k.webhook.id,M):k.webhook;return b({ok:!0,webhook:X,endpoint:B,endpointRevealOnce:!0},201)}catch(k){return b({ok:!1,error:k instanceof Error?k.message:"Source webhook could not be created."},422)}}if(L.pathname==="/api/sources/webhooks"&&C.method==="PATCH"){let d=await se(C),l=process.env.TS_CLOUD_WEBHOOK_BASE_URL?.trim()||nt,k=Ve.getWebhook(String(d.id??"")),M=k?Ve.getConnection(k.connectionId):void 0;if(!k||!M||M.organizationId!==a.organization.id)return b({ok:!1,error:"Source webhook was not found."},404);if(!l)return b({ok:!1,error:"Set TS_CLOUD_WEBHOOK_BASE_URL to reconcile provider webhooks."},422);try{return b({ok:!0,webhook:await ir(Ve,String(d.id??""),l)})}catch(B){return b({ok:!1,error:B instanceof Error?B.message:"Source webhook could not be reconciled."},422)}}if(L.pathname==="/api/sources/webhooks"&&C.method==="DELETE"){let d=await se(C),l=Ve.getWebhook(String(d.id??"")),k=l?Ve.getConnection(l.connectionId):void 0;if(!l||!k||k.organizationId!==a.organization.id)return b({ok:!1,error:"Source webhook was not found."},404);try{return b({ok:!0,webhook:await qi(Ve,String(d.id??""))})}catch(M){return b({ok:!1,error:M instanceof Error?M.message:"Source webhook could not be removed."},422)}}if(L.pathname==="/api/security/posture"&&C.method==="GET"){let d=le(a,String(ye)),l=rt.listFindings({...d,limit:500});return b({scope:d,summary:rt.summary(d.organizationId,d.projectId,d.environmentId),findings:l,scans:rt.listScanRuns({...d,limit:100}),policies:rt.listPolicies(d.organizationId).filter((k)=>!k.environmentId||k.environmentId===d.environmentId),waivers:l.flatMap((k)=>rt.listWaivers(k.id)),decisions:rt.listDecisions(d.environmentId,50),actors:a.store.listMemberships(a.organization.id).map((k)=>a.store.getActor(k.actorId)).filter(Boolean)})}if(L.pathname==="/api/security/export"&&C.method==="GET")return b(rt.exportPosture(a.organization.id));if(L.pathname==="/api/security/scan"&&C.method==="POST"){let d=le(a,String(ye)),l=await new ss(rt).run(new Da,{...d,artifactRoot:t}),k=dd(rt,d,Lt??{});return b({ok:!0,source:l,host:k,summary:rt.summary(d.organizationId,d.projectId,d.environmentId)})}if(L.pathname==="/api/security/review"&&C.method==="POST")try{let d=le(a,String(ye));return b({ok:!0,...ar(rt,{scope:d,desiredConfigHash:a.project.desiredConfigHash})})}catch(d){return b({ok:!1,error:d instanceof Error?d.message:"Security change review failed."},409)}if(L.pathname==="/api/security/policies"&&C.method==="POST"){let d=await se(C),l=Ne(ue);if(!l.actor)return b({ok:!1,error:"An organization actor is required."},403);try{let k=rt.createPolicy({organizationId:a.organization.id,environmentId:d.environmentId===null?void 0:String(d.environmentId??le(a,String(ye)).environmentId),name:String(d.name??""),scannerFailMode:d.scannerFailMode==="open"?"open":"closed",requiredScanners:Array.isArray(d.requiredScanners)?d.requiredScanners.map(String):[],rules:Array.isArray(d.rules)?d.rules.map((M)=>({minimumSeverity:String(M.minimumSeverity),action:String(M.action),scannerId:M.scannerId?String(M.scannerId):void 0})):[],actorId:l.actor.id});return b({ok:!0,policy:k},201)}catch(k){return b({ok:!1,error:k instanceof Error?k.message:"Security policy could not be created."},422)}}if(L.pathname==="/api/security/policies"&&C.method==="PATCH"){let d=await se(C),l=Ne(ue),k=rt.getPolicy(String(d.id??""));if(!l.actor||!k||k.organizationId!==a.organization.id)return b({ok:!1,error:"Security policy was not found."},404);try{return b({ok:!0,policy:rt.updatePolicy(k.id,Number(d.version),{name:typeof d.name==="string"?d.name:void 0,scannerFailMode:d.scannerFailMode==="open"||d.scannerFailMode==="closed"?d.scannerFailMode:void 0,requiredScanners:Array.isArray(d.requiredScanners)?d.requiredScanners.map(String):void 0,rules:Array.isArray(d.rules)?d.rules.map((M)=>({minimumSeverity:String(M.minimumSeverity),action:String(M.action),scannerId:M.scannerId?String(M.scannerId):void 0})):void 0,enabled:typeof d.enabled==="boolean"?d.enabled:void 0,actorId:l.actor.id})})}catch(M){return b({ok:!1,error:M instanceof Error?M.message:"Security policy could not be updated."},409)}}if(L.pathname==="/api/security/waivers"&&C.method==="POST"){let d=await se(C),l=Ne(ue);if(!l.actor)return b({ok:!1,error:"An organization actor is required."},403);try{return b({ok:!0,waiver:rt.createWaiver({findingId:String(d.findingId??""),policyId:typeof d.policyId==="string"?d.policyId:void 0,reason:String(d.reason??""),referenceUrl:typeof d.referenceUrl==="string"?d.referenceUrl:void 0,expiresAt:String(d.expiresAt??""),actorId:l.actor.id})},201)}catch(k){return b({ok:!1,error:k instanceof Error?k.message:"Security waiver could not be created."},422)}}if(L.pathname==="/api/security/waivers"&&C.method==="DELETE"){let d=await se(C),l=Ne(ue);if(!l.actor)return b({ok:!1,error:"An organization actor is required."},403);try{return b({ok:!0,waiver:rt.revokeWaiver(String(d.id??""),l.actor.id)})}catch(k){return b({ok:!1,error:k instanceof Error?k.message:"Security waiver could not be revoked."},404)}}if(L.pathname==="/api/security/findings"&&C.method==="PATCH"){let d=await se(C),l=Ne(ue),k=rt.getFinding(String(d.id??""));if(!l.actor||!k||k.organizationId!==a.organization.id)return b({ok:!1,error:"Security finding was not found."},404);try{let M=d.action==="acknowledge"?rt.acknowledgeFinding(k.id,l.actor.id):rt.assignFinding(k.id,typeof d.ownerActorId==="string"&&d.ownerActorId?d.ownerActorId:void 0,l.actor.id);return b({ok:!0,finding:M})}catch(M){return b({ok:!1,error:M instanceof Error?M.message:"Security finding could not be updated."},422)}}if(L.pathname==="/api/security/comments"&&C.method==="POST"){let d=await se(C),l=Ne(ue);if(!l.actor)return b({ok:!1,error:"An organization actor is required."},403);try{return b({ok:!0,comment:rt.addComment({findingId:String(d.findingId??""),actorId:l.actor.id,body:String(d.body??""),referenceUrl:typeof d.referenceUrl==="string"?d.referenceUrl:void 0})},201)}catch(k){return b({ok:!1,error:k instanceof Error?k.message:"Comment could not be saved."},422)}}if(L.pathname==="/api/auth/sessions"&&C.method==="GET"){let d=jt.resolveSession(C);return b({currentSessionId:d?.id,sessions:d?Ie.listSessions(d.identityId,{includeInactive:!0}):[]})}if(L.pathname==="/api/auth/sessions"&&C.method==="DELETE"){let d=await se(C),l=jt.resolveSession(C);if(!l)return b({ok:!1,error:"Sign in again to manage sessions."},401);let k=String(d.id??""),M=Ie.revokeSession(l.identityId,k),B=k===l.id&&M?{"set-cookie":bd({secure:yo})}:void 0;return b({ok:M,signedOut:k===l.id&&M},M?200:404,B)}if(L.pathname==="/api/auth/sessions/revoke-others"&&C.method==="POST"){let d=jt.resolveSession(C);if(!d)return b({ok:!1,error:"Sign in again to manage sessions."},401);return b({ok:!0,revoked:Ie.revokeOtherSessions(d.identityId,d.id)})}if(L.pathname==="/api/auth/password/change"&&C.method==="POST"){let d=await se(C),l=String(d.currentPassword??""),k=String(d.password??""),M=Ne(ue),B=M.actor?Ie.getIdentityByActor(M.actor.id):void 0;if(!B||!Ei(l,B.passwordHash))return b({ok:!1,error:"Current password is incorrect."},401);if(k.length<12)return b({ok:!1,error:"New password must be at least 12 characters."},422);if(Ei(k,B.passwordHash))return b({ok:!1,error:"Choose a different password."},409);let X=No(k),j=Ie.updatePassword(B.id,X);wd(t,j.username,X);let Z=qa(j.id,C,Ze.requestIP(C)?.address??"unknown");return a.store.appendEvent({organizationId:a.organization.id,actorId:j.actorId,type:"auth.password.changed"}),b({ok:!0,message:"Password changed and other sessions were signed out."},200,{"set-cookie":na(Z.token,{secure:yo,maxAgeMs:Eo})})}if(L.pathname==="/api/auth/mfa/enroll"&&C.method==="POST"){let d=await se(C),l=jt.resolveSession(C),k=Ne(ue),M=k.actor?Ie.getIdentityByActor(k.actor.id):void 0;if(!l||!M)return b({ok:!1,error:"Sign in again before enabling MFA."},401);if(!Ei(String(d.password??""),M.passwordHash))return b({ok:!1,error:"Current password is incorrect."},401);try{let B=Ie.beginTotpEnrollment(M.id,{issuer:a.organization.name});return a.store.appendEvent({organizationId:a.organization.id,actorId:M.actorId,type:"auth.mfa.enrollment.started"}),b({factor:B.factor,secret:B.secret,uri:B.uri})}catch(B){return b({ok:!1,error:B instanceof Error?B.message:"MFA enrollment failed."},409)}}if(L.pathname==="/api/auth/mfa/verify"&&C.method==="POST"){let d=await se(C),l=jt.resolveSession(C),k=Ne(ue),M=k.actor?Ie.getIdentityByActor(k.actor.id):void 0;if(!l||!M)return b({ok:!1,error:"Sign in again before enabling MFA."},401);try{let B=Ie.verifyTotpEnrollment(M.id,String(d.code??""));return Ie.markSessionStepUp(l.id,!0),a.store.appendEvent({organizationId:a.organization.id,actorId:M.actorId,type:"auth.mfa.enabled",payload:{recoveryCodeCount:B.recoveryCodes.length}}),b(B)}catch(B){return b({ok:!1,error:B instanceof Error?B.message:"MFA enrollment failed."},422)}}if(L.pathname==="/api/auth/mfa"&&C.method==="DELETE"){let d=await se(C),l=jt.resolveSession(C),k=Ne(ue),M=k.actor?Ie.getIdentityByActor(k.actor.id):void 0;if(!l||!M||!Ei(String(d.password??""),M.passwordHash))return b({ok:!1,error:"Current password is incorrect."},401);let B=Ie.verifyMfaCode(M.id,String(d.code??""));if(!B.valid||!B.method)return b({ok:!1,error:"Authenticator or recovery code is incorrect."},401);return Ie.disableMfa(M.id),Ie.revokeOtherSessions(M.id,l.id),Ie.markSessionStepUp(l.id),a.store.appendEvent({organizationId:a.organization.id,actorId:M.actorId,type:"auth.mfa.disabled",payload:{method:B.method}}),b({ok:!0})}if(L.pathname==="/api/auth/step-up"&&C.method==="POST"){let d=await se(C),l=jt.resolveSession(C),k=Ne(ue),M=k.actor?Ie.getIdentityByActor(k.actor.id):void 0;if(!l||!M||!Ei(String(d.password??""),M.passwordHash))return b({ok:!1,error:"Current password is incorrect."},401);let B=Ie.getMfaFactor(M.id);if(B?.state==="active"){if(!Ie.verifyMfaCode(M.id,String(d.code??"")).valid)return b({ok:!1,error:"Authenticator or recovery code is incorrect."},401)}let X=Ie.markSessionStepUp(l.id,B?.state==="active");return a.store.appendEvent({organizationId:a.organization.id,actorId:M.actorId,type:"auth.step_up.succeeded",payload:{mfa:B?.state==="active"}}),b({ok:!0,recentAuthAt:X.recentAuthAt})}if(L.pathname==="/api/terminal"){if(!ge)return b({ok:!1,error:"The web terminal is disabled."},403);if(Ze.upgrade(C))return;return Rd("WebSocket upgrade failed",400)}if(L.pathname==="/api/health"){let d=a.store.health();return b({ok:!0,cwd:t,environment:ye,environments:f,uiRoot:await ki(ue,ye),liveData:Re.size>0,terminal:ge,localPackage:import.meta.url.includes("/Code/Libraries/ts-cloud/"),controlPlane:{schemaVersion:d.schemaVersion,supportedSchemaVersion:d.supportedSchemaVersion,integrity:d.integrity,pendingRetryableOperations:d.pendingRetryableOperations}})}if(L.pathname==="/api/control-plane/operations"){let d=L.searchParams.get("state"),l=d&&["queued","running","succeeded","failed","cancelled","timed_out"].includes(d)?d:void 0;return b({operations:a.store.listOperations({projectId:a.project.id,state:l,kind:L.searchParams.get("kind")??void 0,limit:Number(L.searchParams.get("limit"))||100})})}if(L.pathname==="/api/queue"&&C.method==="GET"){let d=L.searchParams.get("state"),l=d&&["queued","running","succeeded","failed","cancelled","timed_out"].includes(d)?d:void 0,k=At.list({projectId:a.project.id,state:l,limit:Number(L.searchParams.get("limit"))||250}).filter((M)=>ys(ue,M.operation.id,"deployments:read")).map((M)=>{let B=M.operation.resourceId?a.store.getResource(M.operation.resourceId):void 0,X=M.operation.environmentId?a.store.listEnvironments(a.project.id).find((fe)=>fe.id===M.operation.environmentId):void 0,j=M.operation.actorId?a.store.getActor(M.operation.actorId):void 0,Z=M.operation.input;return{...M,target:B?{id:B.id,name:B.name,slug:B.slug,kind:B.kind}:X?{id:X.id,name:X.name,slug:X.slug,kind:"environment"}:{id:a.project.id,name:a.project.name,slug:a.project.slug,kind:"project"},actor:j?{id:j.id,name:j.displayName,kind:j.kind}:void 0,commit:Z.revision??Z.source?.commitSha??null}});return b({operations:k,concurrency:At.limits})}if(L.pathname==="/api/queue/logs"&&C.method==="GET"){let d=String(L.searchParams.get("id")??"");if(!ys(ue,d,"deployments:read"))return b({ok:!1,error:"Operation was not found in this scope."},404);let l=At.logs(d,{after:Number(L.searchParams.get("after"))||0,limit:Number(L.searchParams.get("limit"))||500});return b({entries:l,cursor:l.at(-1)?.sequence??(Number(L.searchParams.get("after"))||0),operation:a.store.getOperation(d)})}if(L.pathname==="/api/queue/stream"&&C.method==="GET"){let d=String(L.searchParams.get("id")??"");if(!ys(ue,d,"deployments:read"))return b({ok:!1,error:"Operation was not found in this scope."},404);let l=C.headers.get("last-event-id")?.trim(),k=Number(l||L.searchParams.get("after")||0),M=new TextEncoder,B,X=!1,j=new ReadableStream({start(Z){let fe=()=>{if(X)return;let pe=jt.resolveUser(C);if(!pe||!ys(pe,d,"deployments:read")){if(X=!0,B)clearInterval(B);Z.close();return}let He=At.logs(d,{after:k,limit:500});for(let Fe of He)k=Fe.sequence,Z.enqueue(M.encode(`id: ${Fe.sequence}
486
+ This link expires in one hour and can be used once.`});a.store.appendEvent({organizationId:a.organization.id,actorId:F.actorId,type:"auth.password_reset.requested",payload:{delivered:Z}})}return b({ok:!0,message:"If that account has a verified email, a reset link has been sent."},202)}if(L.pathname==="/api/auth/password-reset/complete"&&C.method==="POST"){let d=await se(C),l=String(d.token??"").trim(),k=String(d.password??"");if(!l||k.length<12)return b({ok:!1,error:"A valid reset token and password of at least 12 characters are required."},422);try{let M=Ie.consumeActionToken(l,"password_reset"),F=No(k),X=Ie.updatePassword(M.identityId,F);return wd(t,X.username,F),a.store.appendEvent({organizationId:a.organization.id,actorId:X.actorId,type:"auth.password_reset.completed"}),b({ok:!0,message:"Password changed. Sign in again."},200,{"set-cookie":bd({secure:yo})})}catch(M){let F=M instanceof Error?M.message:"Password reset failed.";return b({ok:!1,error:F.replace("Action token","Reset link")},F.includes("consumed")||F.includes("expired")?409:404)}}if(L.pathname==="/api/login"&&C.method==="POST"){let d=await se(C),l=String(d.username??"").trim(),k=String(d.password??""),M=Ze.requestIP(C)?.address??"unknown",F=za.check(l,M);if(!F.allowed)return b({ok:!1,error:`Too many failed attempts. Try again in ${Math.ceil((F.retryAfterSeconds??0)/60)} minute(s).`},429,{"retry-after":String(F.retryAfterSeconds??60)});let X=ui(dn(t),l),j=Ie.getIdentityByUsername(l),Z=j?.passwordHash??X?.passwordHash??tA;if(!(Ei(k,Z)&&!!X&&!!j&&!j.disabledAt))return za.recordFailure(l,M),b({ok:!1,error:"Incorrect username or password."},401);if(py(Ie,a,j))return b({ok:!1,error:"Single sign-on is required for this account."},403);za.recordSuccess(l,M);let pe=j,He=pe.requiresPasswordUpgrade||Bh(pe.passwordHash);if(He){let Be=No(k);pe=Ie.rehashPassword(pe.id,Be),wd(t,pe.username,Be)}if(Ie.recordLogin(pe.id),Ie.getMfaFactor(pe.id)?.state==="active"){let Be=Ie.createMfaChallenge(pe.id,"login");return a.store.appendEvent({organizationId:a.organization.id,actorId:pe.actorId,type:"auth.mfa.challenge.created",payload:{purpose:"login"}}),b({ok:!0,mfaRequired:!0,challengeToken:Be.token,passwordUpgraded:He})}let ve=qa(pe.id,C,M);return a.store.appendEvent({organizationId:a.organization.id,actorId:pe.actorId,type:"auth.login.succeeded",payload:{method:"local"}}),b({ok:!0,user:oa(X),passwordUpgraded:He},200,{"set-cookie":na(ve.token,{secure:yo,maxAgeMs:Eo})})}if(L.pathname==="/api/auth/mfa/complete"&&C.method==="POST"){let d=await se(C),l=String(d.challengeToken??"").trim(),k=String(d.code??"").trim(),M=Ze.requestIP(C)?.address??"unknown",X=Ie.inspectMfaChallengeToken(l,"login")?.identityId??"unknown-mfa",j=Va.check(X,M);if(!j.allowed)return b({ok:!1,error:"Too many MFA attempts. Try again later."},429,{"retry-after":String(j.retryAfterSeconds??60)});try{let Z=Ie.completeMfaChallenge(l,k,"login");Va.recordSuccess(X,M);let fe=new Date().toISOString(),pe=Ie.createSession({identityId:Z.identity.id,userAgent:Ap(C),networkHint:Md(M),mfaAt:fe,recentAuthAt:fe});return a.store.appendEvent({organizationId:a.organization.id,actorId:Z.identity.actorId,type:"auth.mfa.succeeded",payload:{purpose:"login",method:Z.method}}),b({ok:!0},200,{"set-cookie":na(pe.token,{secure:yo,maxAgeMs:Eo})})}catch{return Va.recordFailure(X,M),b({ok:!1,error:"Authenticator or recovery code is incorrect."},401)}}if(L.pathname==="/api/logout"&&C.method==="POST"){let d=jt.resolveSession(C);if(d)Ie.revokeSession(d.identityId,d.id);let l=bd({secure:yo});if(C.headers.get("accept")?.includes("text/html"))return new Response(null,{status:302,headers:{location:"/login","set-cookie":l}});return b({ok:!0},200,{"set-cookie":l})}if(L.pathname==="/login"){let d=Ie.listOidcProviders(a.organization.id).map((l)=>({slug:l.slug,name:l.name}));return new Response(gy(D?.mode==="serverless",d),{headers:{"content-type":"text/html; charset=utf-8"}})}if(L.pathname==="/forgot-password"||L.pathname==="/reset-password")return new Response(my(L.pathname==="/reset-password"?"reset":"request"),{headers:{"content-type":"text/html; charset=utf-8"}});if(L.pathname==="/accept-invitation")return hb(Ri,L.pathname);let ue=jt.resolveUser(C);if(!ue){if(!L.pathname.startsWith("/api/")&&C.headers.get("accept")?.includes("text/html"))return new Response(null,{status:302,headers:{location:"/login"}});return b({ok:!1,error:"Sign in to continue."},401)}let Tn=lo(ue,ye);if(L.pathname==="/api/me"){let d=a.store.getActorByExternalId("user",`dashboard:${ue.username.toLowerCase()}`),l=d?a.store.getMembershipForActor(a.organization.id,d.id):void 0,k=a.store.resolveAuthorizationTarget(a.organization.id,l?.scope??{type:"project",id:a.project.id})??a.store.resolveAuthorizationTarget(a.organization.id,{type:"project",id:a.project.id});return b({ok:!0,user:oa(ue),authEnabled:Pe,organization:a.organization,membership:l,capabilities:hn({membership:l,grants:l?a.store.listGrants(l.id):[],target:k})})}if(L.pathname.startsWith("/api/")){let d=await dy(C,L.pathname),l=jt.check(C,L.pathname,ue,d);if(!l.ok)return b({ok:!1,error:l.error},l.status??403);if(Pe&&lA.has(`${C.method.toUpperCase()} ${L.pathname}`)){let k=jt.resolveSession(C);if(!k||!Ie.isRecentlyAuthenticated(k))return b({ok:!1,error:"Recent authentication is required for this change.",stepUpRequired:!0},401)}}if(L.pathname==="/api/auth/security"&&C.method==="GET"){let d=Ne(ue),l=d.actor?Ie.getIdentityByActor(d.actor.id):void 0,k=jt.resolveSession(C);return b({identity:l?{username:l.username,email:l.email,emailVerifiedAt:l.emailVerifiedAt,requiresPasswordUpgrade:l.requiresPasswordUpgrade,lastLoginAt:l.lastLoginAt}:void 0,currentSessionId:k?.id,sessions:l?Ie.listSessions(l.id,{includeInactive:!0}):[],mfa:l?{factor:Ie.getMfaFactor(l.id),recoveryCodesRemaining:Ie.remainingRecoveryCodes(l.id)}:void 0})}if(L.pathname==="/api/auth/oidc/providers"&&C.method==="GET")return b({providers:Ie.listOidcProviders(a.organization.id,{includeDisabled:!0}),callbackOrigin:nt,callbackPattern:nt?`${nt}/auth/oidc/{slug}/callback`:void 0,localOwnerRecovery:!0});if(L.pathname==="/api/auth/oidc/providers"&&C.method==="POST"){let d=await se(C),l=Ne(ue),k=l.actor?Ie.getIdentityByActor(l.actor.id):void 0,M=d.enforceSso===!0;if(M&&(!k?.emailVerifiedAt||Ie.remainingRecoveryCodes(k.id)<1))return b({ok:!1,error:"Verify the owner email and generate MFA recovery codes before enforcing SSO."},409);try{let F=Td(d.defaultRole),X=Ie.upsertOidcProvider({id:typeof d.id==="string"?d.id:void 0,organizationId:a.organization.id,slug:String(d.slug??""),name:String(d.name??""),issuer:String(d.issuer??""),clientId:String(d.clientId??""),clientSecret:typeof d.clientSecret==="string"&&d.clientSecret?d.clientSecret:void 0,scopes:Array.isArray(d.scopes)?d.scopes.map(String):void 0,allowedDomains:Array.isArray(d.allowedDomains)?d.allowedDomains.map(String):[],defaultRole:F&&F!=="owner"?F:void 0,enabled:d.enabled!==!1,enforceSso:M});return a.store.appendEvent({organizationId:a.organization.id,actorId:l.actor?.id,type:"auth.oidc.provider.configured",payload:{providerId:X.id,issuer:X.issuer,enabled:X.enabled,enforceSso:X.enforceSso}}),b({ok:!0,provider:X})}catch(F){return b({ok:!1,error:F instanceof Error?F.message:"OIDC provider could not be saved."},422)}}if(L.pathname==="/api/auth/oidc/providers"&&C.method==="PATCH"){let d=await se(C),l=Ie.getOidcProvider(String(d.id??""));if(!l||l.organizationId!==a.organization.id)return b({ok:!1,error:"OIDC provider was not found."},404);let k=Ne(ue),M=Ie.setOidcProviderEnabled(l.id,d.enabled===!0);return a.store.appendEvent({organizationId:a.organization.id,actorId:k.actor?.id,type:M.enabled?"auth.oidc.provider.enabled":"auth.oidc.provider.disabled",payload:{providerId:l.id}}),b({ok:!0,provider:M})}if(L.pathname==="/api/automation"&&C.method==="GET"){let d=lt.listServiceAccounts(a.organization.id,{includeDisabled:!0}).map((l)=>{let k=a.store.getMembershipForActor(a.organization.id,l.actorId),M=l.createdByActorId?a.store.getActor(l.createdByActorId):void 0,F=lt.listTokens(l.id,{includeInactive:!0}).map((X)=>({...X,createdBy:X.createdByActorId?a.store.getActor(X.createdByActorId):void 0}));return{account:l,createdBy:M,membership:k,tokens:F}});return b({accounts:d,apiBaseUrl:`${L.origin}/api/v1`,openApiUrl:`${L.origin}/api/v1/openapi.json`,tokenEnvironmentVariable:"TS_CLOUD_API_TOKEN"})}if(L.pathname==="/api/automation/service-accounts"&&C.method==="POST"){let d=await se(C),l=Ne(ue),k=Td(d.roleTemplate),M=Ba(d);if(!l.actor||!k||k==="owner"||!M)return b({ok:!1,error:"A non-owner role and valid organization scope are required."},422);try{let F=lt.createServiceAccount({organizationId:a.organization.id,slug:String(d.slug??""),name:String(d.name??""),description:typeof d.description==="string"?d.description:void 0,roleTemplate:k,scope:M,createdByActorId:l.actor.id});return b({ok:!0,...F},201)}catch(F){return b({ok:!1,error:F instanceof Error?F.message:"Service account could not be created."},422)}}if(L.pathname==="/api/automation/service-accounts"&&C.method==="PATCH"){let d=await se(C),l=Ne(ue),k=lt.getServiceAccount(String(d.id??""));if(!k||k.organizationId!==a.organization.id)return b({ok:!1,error:"Service account was not found."},404);return b({ok:!0,account:lt.disableServiceAccount(k.id,l.actor?.id)})}if(L.pathname==="/api/automation/tokens"&&C.method==="POST"){let d=await se(C),l=Ne(ue),k=lt.getServiceAccount(String(d.serviceAccountId??"")),M=Ba(d);if(!l.actor||!k||k.organizationId!==a.organization.id||!M||!Array.isArray(d.capabilities))return b({ok:!1,error:"Service account, explicit capabilities, and valid scope are required."},422);try{let F=lt.createToken({serviceAccountId:k.id,name:String(d.name??"API token"),capabilities:d.capabilities.map(String),scope:M,expiresAt:typeof d.expiresAt==="string"?d.expiresAt:void 0,createdByActorId:l.actor.id});return b({ok:!0,token:F.token,secret:F.secret,revealOnce:!0},201)}catch(F){return b({ok:!1,error:F instanceof Error?F.message:"API token could not be created."},422)}}if(L.pathname==="/api/automation/tokens/rotate"&&C.method==="POST"){let d=await se(C),l=Ne(ue),k=lt.getToken(String(d.id??"")),M=k?lt.getServiceAccount(k.serviceAccountId):void 0;if(!l.actor||!k||M?.organizationId!==a.organization.id)return b({ok:!1,error:"API token was not found."},404);try{let F=lt.rotateToken(k.id,l.actor.id);return b({ok:!0,token:F.token,secret:F.secret,revealOnce:!0,overlap:!0},201)}catch(F){return b({ok:!1,error:F instanceof Error?F.message:"API token could not be rotated."},409)}}if(L.pathname==="/api/automation/tokens"&&C.method==="DELETE"){let d=await se(C),l=Ne(ue),k=lt.getToken(String(d.id??"")),M=k?lt.getServiceAccount(k.serviceAccountId):void 0;if(!k||M?.organizationId!==a.organization.id)return b({ok:!1,error:"API token was not found."},404);return b({ok:!0,token:lt.revokeToken(k.id,l.actor?.id)})}if(L.pathname==="/api/onboarding"&&C.method==="GET"){let d=Ve.listConnections(a.organization.id);return b({drafts:Mr.list(a.project.id),artifacts:hs.list(a.project.id),registries:Pi.list(a.organization.id),sourceConnections:d,repositories:d.flatMap((l)=>Ve.listRepositories(l.id)),project:{id:a.project.id,slug:a.project.slug,name:a.project.name},environments:[...a.environments.values()].map((l)=>({id:l.id,slug:l.slug,name:l.name,kind:l.kind,region:l.region})),resources:a.store.listResources(a.project.id).filter((l)=>l.kind==="application").map((l)=>({id:l.id,slug:l.slug,name:l.name,environmentId:l.environmentId}))})}if(L.pathname==="/api/onboarding/detect"&&C.method==="POST"){let d=await se(C);try{if(d.source?.kind==="git"){let M=Ve.getConnection(String(d.source.connectionId??"")),F=Ve.getRepository(String(d.source.repositoryId??""));if(!M||M.organizationId!==a.organization.id||!F||F.connectionId!==M.id)throw Error("Authorized Git repository was not found");let X=typeof d.source.deployKeyId==="string"?Ve.getDeployKey(d.source.deployKeyId):void 0;if(X&&X.connectionId!==M.id)throw Error("Deploy key does not belong to this connection");let j=cp(Ct(kd(),"ts-cloud-onboarding-git-"));try{let Z=await Qd({remote:F.cloneUrl,destination:Ct(j,"checkout"),ref:String(d.source.ref??F.defaultBranch),sparsePaths:Array.isArray(d.source.sparsePaths)?d.source.sparsePaths.map(String):void 0,binding:{id:"detection",projectId:a.project.id,connectionId:M.id,repositoryId:F.id,repositoryFullName:F.fullName,defaultBranch:F.defaultBranch,monorepoRoot:String(d.source.monorepoRoot??"."),includePaths:[],excludePaths:[],submodules:d.source.submodules===!0,cloneDepth:1,deployKeyId:X?.id,autoDeploy:!1,pullRequestPreviews:!1,status:"active",version:1,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}},{credential:Ve.getCredential(M.id),deployKey:X?{...X,privateKey:Ve.getDeployPrivateKey(X.id)}:void 0,timeoutMs:120000});return b({ok:!0,commitSha:Z.commitSha,candidates:kt(Jn(Z.directory))})}finally{fs(j,{recursive:!0,force:!0})}}if(Array.isArray(d.files)){if(d.files.length>1e4)throw Error("Detection file-count limit exceeded");let M=d.files.map((F)=>({path:String(F.path??""),size:Number(F.size??0),content:typeof F.content==="string"?F.content.slice(0,262144):void 0}));return b({ok:!0,candidates:kt(M)})}let l=qT(t,String(d.root??".")),k=VT(t,l);if(k===".."||k.startsWith(`..${GT}`))throw Error("Detection root must stay inside the project");return b({ok:!0,candidates:kt(Jn(l))})}catch(l){return b({ok:!1,error:l instanceof Error?l.message:"Application detection failed."},422)}}if(L.pathname==="/api/onboarding/plan"&&C.method==="POST"){let d=await se(C);try{return b({ok:!0,plan:ce(d.draft,Array.isArray(d.suppliedSecretNames)?d.suppliedSecretNames.map(String):[])})}catch(l){return b({ok:!1,error:l instanceof Error?l.message:"Application plan could not be generated."},422)}}if(L.pathname==="/api/onboarding/drafts"&&C.method==="POST"){let d=await se(C),l=Ne(ue);try{return b({ok:!0,draft:Mr.create({organizationId:a.organization.id,projectId:a.project.id,name:String(d.name??d.draft?.name??"Application draft"),draft:{...d.draft,projectId:a.project.id},step:d.step,suppliedSecretNames:Array.isArray(d.suppliedSecretNames)?d.suppliedSecretNames.map(String):[],actorId:l.actor?.id})},201)}catch(k){return b({ok:!1,error:k instanceof Error?k.message:"Application draft could not be saved."},422)}}if(L.pathname==="/api/onboarding/drafts"&&C.method==="PATCH"){let d=await se(C),l=Ne(ue),k=Mr.get(String(d.id??""));if(!k||k.projectId!==a.project.id)return b({ok:!1,error:"Application draft was not found."},404);try{return b({ok:!0,draft:Mr.update(k.id,Number(d.version),{draft:{...d.draft,projectId:a.project.id},step:d.step,suppliedSecretNames:Array.isArray(d.suppliedSecretNames)?d.suppliedSecretNames.map(String):void 0,actorId:l.actor?.id})})}catch(M){return b({ok:!1,error:M instanceof Error?M.message:"Application draft could not be updated."},409)}}if(L.pathname==="/api/onboarding/artifacts"&&C.method==="POST"){let d=Ne(ue);if(Number(C.headers.get("content-length")??0)>104857600)return b({ok:!1,error:"Artifact exceeds the 100 MB upload limit."},413);try{let k=new Uint8Array(await C.arrayBuffer());return b({ok:!0,artifact:hs.create({organizationId:a.organization.id,projectId:a.project.id,filename:C.headers.get("x-artifact-filename")??"application.zip",bytes:k,actorId:d.actor?.id})},201)}catch(k){return b({ok:!1,error:k instanceof Error?k.message:"Artifact could not be inspected."},422)}}if(L.pathname==="/api/onboarding/registries"&&C.method==="POST"){let d=await se(C),l=Ne(ue);try{return b({ok:!0,registry:Pi.create({organizationId:a.organization.id,provider:d.provider,name:String(d.name??"Container registry"),host:String(d.host??""),credential:d.token||d.password?{username:typeof d.username==="string"?d.username:void 0,password:typeof d.password==="string"?d.password:void 0,token:typeof d.token==="string"?d.token:void 0}:void 0,credentialExpiresAt:typeof d.credentialExpiresAt==="string"?d.credentialExpiresAt:void 0,actorId:l.actor?.id})},201)}catch(k){return b({ok:!1,error:k instanceof Error?k.message:"Registry connection could not be created."},422)}}if(L.pathname==="/api/onboarding/registries"&&C.method==="PATCH"){let d=await se(C),l=Ne(ue),k=Pi.get(String(d.id??""));if(!k||k.organizationId!==a.organization.id)return b({ok:!1,error:"Registry connection was not found."},404);try{if(d.action==="test")return b({ok:!0,registry:await Pi.test(k.id,{image:typeof d.image==="string"?d.image:void 0})});if(d.action==="rotate")return b({ok:!0,registry:Pi.rotate(k.id,{username:typeof d.username==="string"?d.username:void 0,password:typeof d.password==="string"?d.password:void 0,token:typeof d.token==="string"?d.token:void 0},{expiresAt:typeof d.expiresAt==="string"?d.expiresAt:void 0,actorId:l.actor?.id})});return b({ok:!1,error:"Registry action must be test or rotate."},422)}catch(M){return b({ok:!1,error:M instanceof Error?M.message:"Registry connection could not be updated."},422)}}if(L.pathname==="/api/onboarding/registries"&&C.method==="DELETE"){let d=await se(C),l=Ne(ue),k=Pi.get(String(d.id??""));if(!k||k.organizationId!==a.organization.id)return b({ok:!1,error:"Registry connection was not found."},404);let M=Mr.list(a.project.id).filter((F)=>F.input.source.kind==="image"&&F.input.source.registryConnectionId===k.id||F.input.build.kind==="prebuilt_image"&&F.input.build.registryConnectionId===k.id);if(d.preview===!0)return b({ok:!0,preview:!0,affectedDrafts:M});return b({ok:!0,registry:Pi.disconnect(k.id,l.actor?.id),affectedDrafts:M})}if(L.pathname==="/api/onboarding/apply"&&C.method==="POST"){let d=await se(C),l=Ne(ue);try{let k=zr({controlPlane:a.store,drafts:Mr,draftId:String(d.id??""),expectedVersion:Number(d.version),confirmEnvironment:String(d.confirmEnvironment??""),actorId:l.actor?.id});return b({ok:!0,resource:k.resource,operation:k.operation,plan:k.plan},202)}catch(k){return b({ok:!1,error:k instanceof Error?k.message:"Application plan could not be applied."},422)}}if(L.pathname==="/api/sources"&&C.method==="GET"){let d=Ve.listConnections(a.organization.id);return b({connections:d,bindings:Ve.listBindings({projectId:a.project.id}),repositories:d.flatMap((l)=>Ve.listRepositories(l.id)),deployKeys:d.flatMap((l)=>Ve.listDeployKeys(l.id)),webhooks:d.flatMap((l)=>Ve.listWebhooks(l.id)).map((l)=>({...l,deliveries:Ve.listDeliveries(l.id,20)})),project:{id:a.project.id,slug:a.project.slug},environment:le(a,String(ye)),resources:a.store.listResources(a.project.id,le(a,String(ye)).environmentId).filter((l)=>l.kind==="application").map((l)=>({id:l.id,slug:l.slug,name:l.name}))})}if(L.pathname==="/api/sources/connections"&&C.method==="POST"){let d=await se(C),l=Ne(ue),k=String(d.provider??"");if(!["github","gitlab","bitbucket","gitea","generic_https","generic_ssh"].includes(k))return b({ok:!1,error:"A supported Git provider is required."},422);try{let M=k==="github"&&(d.privateKey||d.appId)?{appId:typeof d.appId==="string"?d.appId:void 0,installationId:typeof d.installationId==="string"?d.installationId:void 0,privateKey:typeof d.privateKey==="string"?d.privateKey:void 0}:k!=="generic_ssh"&&d.token?{token:typeof d.token==="string"?d.token:void 0,username:typeof d.username==="string"?d.username:void 0}:void 0,F={github:"https://github.com",gitlab:"https://gitlab.com",bitbucket:"https://bitbucket.org",gitea:"https://gitea.com"},X,j,Z;if(a.store.database.transaction(()=>{if(X=Ve.createConnection({organizationId:a.organization.id,provider:k,name:String(d.name??k),host:String(d.host??F[k]??""),owner:typeof d.owner==="string"?d.owner:void 0,authKind:d.authKind,credential:M,grantedScopes:Array.isArray(d.grantedScopes)?d.grantedScopes.map(String):[],credentialExpiresAt:typeof d.credentialExpiresAt==="string"?d.credentialExpiresAt:void 0,createdByActorId:l.actor?.id}),typeof d.repositoryUrl==="string"&&typeof d.repositoryFullName==="string")j=Ve.upsertRepository({connectionId:X.id,providerRepositoryId:`manual:${d.repositoryFullName}`,fullName:d.repositoryFullName,cloneUrl:d.repositoryUrl,defaultBranch:String(d.defaultBranch??"main"),visibility:"unknown",archived:!1,metadata:{source:"manual"}});if(k==="generic_ssh")Z=Ve.createDeployKey({connectionId:X.id,name:String(d.deployKeyName??"Repository deploy key"),publicKey:String(d.publicKey??""),privateKey:String(d.deployPrivateKey??""),host:String(d.sshHost??""),hostKey:String(d.hostKey??""),actorId:l.actor?.id})})(),d.test===!0)X=await Yd(Ve,X.id,j?.id);return b({ok:!0,connection:X,repository:j,deployKey:Z},201)}catch(M){return b({ok:!1,error:M instanceof Error?M.message:"Source connection could not be created."},422)}}if(L.pathname==="/api/sources/connections"&&C.method==="PATCH"){let d=await se(C),l=Ne(ue),k=Ve.getConnection(String(d.id??""));if(!k||k.organizationId!==a.organization.id)return b({ok:!1,error:"Source connection was not found."},404);try{if(d.action==="test")return b({ok:!0,connection:await Yd(Ve,k.id,typeof d.repositoryId==="string"?d.repositoryId:void 0)});if(d.action==="rotate")return b({ok:!0,connection:Ve.rotateCredential(k.id,{token:typeof d.token==="string"?d.token:void 0,username:typeof d.username==="string"?d.username:void 0,appId:typeof d.appId==="string"?d.appId:void 0,installationId:typeof d.installationId==="string"?d.installationId:void 0,privateKey:typeof d.privateKey==="string"?d.privateKey:void 0},{expiresAt:typeof d.expiresAt==="string"?d.expiresAt:void 0,actorId:l.actor?.id})});return b({ok:!1,error:"Connection action must be test or rotate."},422)}catch(M){return b({ok:!1,error:M instanceof Error?M.message:"Source connection could not be updated."},422)}}if(L.pathname==="/api/sources/connections"&&C.method==="DELETE"){let d=await se(C),l=Ne(ue),k=Ve.getConnection(String(d.id??""));if(!k||k.organizationId!==a.organization.id)return b({ok:!1,error:"Source connection was not found."},404);let M=Ve.listBindings({connectionId:k.id,status:"active"});if(d.preview===!0)return b({ok:!0,preview:!0,affectedBindings:M});return b({ok:!0,...Ve.disconnectConnection(k.id,l.actor?.id)})}if(L.pathname==="/api/sources/deploy-keys"&&C.method==="POST"){let d=await se(C),l=Ne(ue),k=Ve.getConnection(String(d.connectionId??""));if(!k||k.organizationId!==a.organization.id)return b({ok:!1,error:"Source connection was not found."},404);try{return b({ok:!0,deployKey:Ve.createDeployKey({connectionId:k.id,name:String(d.name??"Repository deploy key"),publicKey:String(d.publicKey??""),privateKey:String(d.privateKey??""),host:String(d.host??""),hostKey:String(d.hostKey??""),actorId:l.actor?.id})},201)}catch(M){return b({ok:!1,error:M instanceof Error?M.message:"Deploy key could not be stored."},422)}}if(L.pathname==="/api/sources/deploy-keys"&&C.method==="DELETE"){let d=await se(C),l=Ne(ue),k=Ve.getDeployKey(String(d.id??"")),M=k?Ve.getConnection(k.connectionId):void 0;if(!k||!M||M.organizationId!==a.organization.id)return b({ok:!1,error:"Deploy key was not found."},404);let F=Ve.listBindings({connectionId:M.id}).filter((X)=>X.deployKeyId===k.id);if(d.preview===!0)return b({ok:!0,preview:!0,affectedBindings:F});return b({ok:!0,...Ve.revokeDeployKey(k.id,l.actor?.id)})}if(L.pathname==="/api/sources/repositories/sync"&&C.method==="POST"){let d=await se(C),l=Ve.getConnection(String(d.connectionId??""));if(!l||l.organizationId!==a.organization.id)return b({ok:!1,error:"Source connection was not found."},404);try{return b({ok:!0,repositories:await Vr(Ve,String(d.connectionId??""),{search:typeof d.search==="string"?d.search:void 0})})}catch(k){return b({ok:!1,error:k instanceof Error?k.message:"Repositories could not be synchronized."},422)}}if(L.pathname==="/api/sources/references"&&C.method==="GET"){let d=Ve.getConnection(String(L.searchParams.get("connectionId")??""));if(!d||d.organizationId!==a.organization.id)return b({ok:!1,error:"Source connection was not found."},404);try{return b(await nr(Ve,{connectionId:String(L.searchParams.get("connectionId")??""),repository:String(L.searchParams.get("repository")??""),repositoryId:L.searchParams.get("repositoryId")??void 0,deployKeyId:L.searchParams.get("deployKeyId")??void 0,type:L.searchParams.get("type")==="tags"?"tags":"branches",cursor:L.searchParams.get("cursor")??void 0}))}catch(l){return b({ok:!1,error:l instanceof Error?l.message:"References could not be listed."},422)}}if(L.pathname==="/api/sources/bindings"&&C.method==="POST"){let d=await se(C),l=Ne(ue),k=le(a,String(ye)),M=Ve.getConnection(String(d.connectionId??""));if(!M||M.organizationId!==a.organization.id)return b({ok:!1,error:"Source connection was not found."},404);try{return b({ok:!0,binding:Ve.createBinding({projectId:a.project.id,environmentId:k.environmentId,resourceId:typeof d.resourceId==="string"?d.resourceId:void 0,connectionId:String(d.connectionId??""),repositoryId:typeof d.repositoryId==="string"?d.repositoryId:void 0,repositoryFullName:String(d.repositoryFullName??""),defaultBranch:String(d.defaultBranch??"main"),branchRule:typeof d.branchRule==="string"?d.branchRule:void 0,tagRule:typeof d.tagRule==="string"?d.tagRule:void 0,monorepoRoot:String(d.monorepoRoot??"."),includePaths:Array.isArray(d.includePaths)?d.includePaths.map(String):[],excludePaths:Array.isArray(d.excludePaths)?d.excludePaths.map(String):[],submodules:d.submodules===!0,cloneDepth:d.cloneDepth?Number(d.cloneDepth):void 0,deployKeyId:typeof d.deployKeyId==="string"&&d.deployKeyId?d.deployKeyId:void 0,autoDeploy:d.autoDeploy!==!1,pullRequestPreviews:d.pullRequestPreviews!==!1,actorId:l.actor?.id})},201)}catch(F){return b({ok:!1,error:F instanceof Error?F.message:"Source binding could not be created."},422)}}if(L.pathname==="/api/sources/bindings"&&C.method==="PATCH"){let d=await se(C),l=Ne(ue),k=Ve.getBinding(String(d.id??""));if(!k||k.projectId!==a.project.id)return b({ok:!1,error:"Source binding was not found."},404);try{return b({ok:!0,binding:Ve.updateBinding(k.id,Number(d.version),{defaultBranch:d.defaultBranch,branchRule:d.branchRule,tagRule:d.tagRule,monorepoRoot:d.monorepoRoot,includePaths:d.includePaths,excludePaths:d.excludePaths,submodules:d.submodules,cloneDepth:d.cloneDepth,deployKeyId:d.deployKeyId,autoDeploy:d.autoDeploy,pullRequestPreviews:d.pullRequestPreviews,status:d.status,disabledReason:d.disabledReason,actorId:l.actor?.id})})}catch(M){return b({ok:!1,error:M instanceof Error?M.message:"Source binding could not be updated."},409)}}if(L.pathname==="/api/sources/webhooks"&&C.method==="POST"){let d=await se(C),l=Ve.getConnection(String(d.connectionId??""));if(!l||l.organizationId!==a.organization.id)return b({ok:!1,error:"Source connection was not found."},404);try{let k=Ve.createWebhook({connectionId:String(d.connectionId??""),repositoryId:typeof d.repositoryId==="string"?d.repositoryId:void 0,repositoryFullName:String(d.repositoryFullName??""),events:Array.isArray(d.events)?d.events.map(String):void 0,secret:typeof d.secret==="string"?d.secret:void 0}),M=process.env.TS_CLOUD_WEBHOOK_BASE_URL?.trim()||nt,F=M?Dt(M,k.webhook):void 0,X=d.reconcile!==!1&&M?await ir(Ve,k.webhook.id,M):k.webhook;return b({ok:!0,webhook:X,endpoint:F,endpointRevealOnce:!0},201)}catch(k){return b({ok:!1,error:k instanceof Error?k.message:"Source webhook could not be created."},422)}}if(L.pathname==="/api/sources/webhooks"&&C.method==="PATCH"){let d=await se(C),l=process.env.TS_CLOUD_WEBHOOK_BASE_URL?.trim()||nt,k=Ve.getWebhook(String(d.id??"")),M=k?Ve.getConnection(k.connectionId):void 0;if(!k||!M||M.organizationId!==a.organization.id)return b({ok:!1,error:"Source webhook was not found."},404);if(!l)return b({ok:!1,error:"Set TS_CLOUD_WEBHOOK_BASE_URL to reconcile provider webhooks."},422);try{return b({ok:!0,webhook:await ir(Ve,String(d.id??""),l)})}catch(F){return b({ok:!1,error:F instanceof Error?F.message:"Source webhook could not be reconciled."},422)}}if(L.pathname==="/api/sources/webhooks"&&C.method==="DELETE"){let d=await se(C),l=Ve.getWebhook(String(d.id??"")),k=l?Ve.getConnection(l.connectionId):void 0;if(!l||!k||k.organizationId!==a.organization.id)return b({ok:!1,error:"Source webhook was not found."},404);try{return b({ok:!0,webhook:await qi(Ve,String(d.id??""))})}catch(M){return b({ok:!1,error:M instanceof Error?M.message:"Source webhook could not be removed."},422)}}if(L.pathname==="/api/security/posture"&&C.method==="GET"){let d=le(a,String(ye)),l=rt.listFindings({...d,limit:500});return b({scope:d,summary:rt.summary(d.organizationId,d.projectId,d.environmentId),findings:l,scans:rt.listScanRuns({...d,limit:100}),policies:rt.listPolicies(d.organizationId).filter((k)=>!k.environmentId||k.environmentId===d.environmentId),waivers:l.flatMap((k)=>rt.listWaivers(k.id)),decisions:rt.listDecisions(d.environmentId,50),actors:a.store.listMemberships(a.organization.id).map((k)=>a.store.getActor(k.actorId)).filter(Boolean)})}if(L.pathname==="/api/security/export"&&C.method==="GET")return b(rt.exportPosture(a.organization.id));if(L.pathname==="/api/security/scan"&&C.method==="POST"){let d=le(a,String(ye)),l=await new ss(rt).run(new Da,{...d,artifactRoot:t}),k=dd(rt,d,Lt??{});return b({ok:!0,source:l,host:k,summary:rt.summary(d.organizationId,d.projectId,d.environmentId)})}if(L.pathname==="/api/security/review"&&C.method==="POST")try{let d=le(a,String(ye));return b({ok:!0,...ar(rt,{scope:d,desiredConfigHash:a.project.desiredConfigHash})})}catch(d){return b({ok:!1,error:d instanceof Error?d.message:"Security change review failed."},409)}if(L.pathname==="/api/security/policies"&&C.method==="POST"){let d=await se(C),l=Ne(ue);if(!l.actor)return b({ok:!1,error:"An organization actor is required."},403);try{let k=rt.createPolicy({organizationId:a.organization.id,environmentId:d.environmentId===null?void 0:String(d.environmentId??le(a,String(ye)).environmentId),name:String(d.name??""),scannerFailMode:d.scannerFailMode==="open"?"open":"closed",requiredScanners:Array.isArray(d.requiredScanners)?d.requiredScanners.map(String):[],rules:Array.isArray(d.rules)?d.rules.map((M)=>({minimumSeverity:String(M.minimumSeverity),action:String(M.action),scannerId:M.scannerId?String(M.scannerId):void 0})):[],actorId:l.actor.id});return b({ok:!0,policy:k},201)}catch(k){return b({ok:!1,error:k instanceof Error?k.message:"Security policy could not be created."},422)}}if(L.pathname==="/api/security/policies"&&C.method==="PATCH"){let d=await se(C),l=Ne(ue),k=rt.getPolicy(String(d.id??""));if(!l.actor||!k||k.organizationId!==a.organization.id)return b({ok:!1,error:"Security policy was not found."},404);try{return b({ok:!0,policy:rt.updatePolicy(k.id,Number(d.version),{name:typeof d.name==="string"?d.name:void 0,scannerFailMode:d.scannerFailMode==="open"||d.scannerFailMode==="closed"?d.scannerFailMode:void 0,requiredScanners:Array.isArray(d.requiredScanners)?d.requiredScanners.map(String):void 0,rules:Array.isArray(d.rules)?d.rules.map((M)=>({minimumSeverity:String(M.minimumSeverity),action:String(M.action),scannerId:M.scannerId?String(M.scannerId):void 0})):void 0,enabled:typeof d.enabled==="boolean"?d.enabled:void 0,actorId:l.actor.id})})}catch(M){return b({ok:!1,error:M instanceof Error?M.message:"Security policy could not be updated."},409)}}if(L.pathname==="/api/security/waivers"&&C.method==="POST"){let d=await se(C),l=Ne(ue);if(!l.actor)return b({ok:!1,error:"An organization actor is required."},403);try{return b({ok:!0,waiver:rt.createWaiver({findingId:String(d.findingId??""),policyId:typeof d.policyId==="string"?d.policyId:void 0,reason:String(d.reason??""),referenceUrl:typeof d.referenceUrl==="string"?d.referenceUrl:void 0,expiresAt:String(d.expiresAt??""),actorId:l.actor.id})},201)}catch(k){return b({ok:!1,error:k instanceof Error?k.message:"Security waiver could not be created."},422)}}if(L.pathname==="/api/security/waivers"&&C.method==="DELETE"){let d=await se(C),l=Ne(ue);if(!l.actor)return b({ok:!1,error:"An organization actor is required."},403);try{return b({ok:!0,waiver:rt.revokeWaiver(String(d.id??""),l.actor.id)})}catch(k){return b({ok:!1,error:k instanceof Error?k.message:"Security waiver could not be revoked."},404)}}if(L.pathname==="/api/security/findings"&&C.method==="PATCH"){let d=await se(C),l=Ne(ue),k=rt.getFinding(String(d.id??""));if(!l.actor||!k||k.organizationId!==a.organization.id)return b({ok:!1,error:"Security finding was not found."},404);try{let M=d.action==="acknowledge"?rt.acknowledgeFinding(k.id,l.actor.id):rt.assignFinding(k.id,typeof d.ownerActorId==="string"&&d.ownerActorId?d.ownerActorId:void 0,l.actor.id);return b({ok:!0,finding:M})}catch(M){return b({ok:!1,error:M instanceof Error?M.message:"Security finding could not be updated."},422)}}if(L.pathname==="/api/security/comments"&&C.method==="POST"){let d=await se(C),l=Ne(ue);if(!l.actor)return b({ok:!1,error:"An organization actor is required."},403);try{return b({ok:!0,comment:rt.addComment({findingId:String(d.findingId??""),actorId:l.actor.id,body:String(d.body??""),referenceUrl:typeof d.referenceUrl==="string"?d.referenceUrl:void 0})},201)}catch(k){return b({ok:!1,error:k instanceof Error?k.message:"Comment could not be saved."},422)}}if(L.pathname==="/api/auth/sessions"&&C.method==="GET"){let d=jt.resolveSession(C);return b({currentSessionId:d?.id,sessions:d?Ie.listSessions(d.identityId,{includeInactive:!0}):[]})}if(L.pathname==="/api/auth/sessions"&&C.method==="DELETE"){let d=await se(C),l=jt.resolveSession(C);if(!l)return b({ok:!1,error:"Sign in again to manage sessions."},401);let k=String(d.id??""),M=Ie.revokeSession(l.identityId,k),F=k===l.id&&M?{"set-cookie":bd({secure:yo})}:void 0;return b({ok:M,signedOut:k===l.id&&M},M?200:404,F)}if(L.pathname==="/api/auth/sessions/revoke-others"&&C.method==="POST"){let d=jt.resolveSession(C);if(!d)return b({ok:!1,error:"Sign in again to manage sessions."},401);return b({ok:!0,revoked:Ie.revokeOtherSessions(d.identityId,d.id)})}if(L.pathname==="/api/auth/password/change"&&C.method==="POST"){let d=await se(C),l=String(d.currentPassword??""),k=String(d.password??""),M=Ne(ue),F=M.actor?Ie.getIdentityByActor(M.actor.id):void 0;if(!F||!Ei(l,F.passwordHash))return b({ok:!1,error:"Current password is incorrect."},401);if(k.length<12)return b({ok:!1,error:"New password must be at least 12 characters."},422);if(Ei(k,F.passwordHash))return b({ok:!1,error:"Choose a different password."},409);let X=No(k),j=Ie.updatePassword(F.id,X);wd(t,j.username,X);let Z=qa(j.id,C,Ze.requestIP(C)?.address??"unknown");return a.store.appendEvent({organizationId:a.organization.id,actorId:j.actorId,type:"auth.password.changed"}),b({ok:!0,message:"Password changed and other sessions were signed out."},200,{"set-cookie":na(Z.token,{secure:yo,maxAgeMs:Eo})})}if(L.pathname==="/api/auth/mfa/enroll"&&C.method==="POST"){let d=await se(C),l=jt.resolveSession(C),k=Ne(ue),M=k.actor?Ie.getIdentityByActor(k.actor.id):void 0;if(!l||!M)return b({ok:!1,error:"Sign in again before enabling MFA."},401);if(!Ei(String(d.password??""),M.passwordHash))return b({ok:!1,error:"Current password is incorrect."},401);try{let F=Ie.beginTotpEnrollment(M.id,{issuer:a.organization.name});return a.store.appendEvent({organizationId:a.organization.id,actorId:M.actorId,type:"auth.mfa.enrollment.started"}),b({factor:F.factor,secret:F.secret,uri:F.uri})}catch(F){return b({ok:!1,error:F instanceof Error?F.message:"MFA enrollment failed."},409)}}if(L.pathname==="/api/auth/mfa/verify"&&C.method==="POST"){let d=await se(C),l=jt.resolveSession(C),k=Ne(ue),M=k.actor?Ie.getIdentityByActor(k.actor.id):void 0;if(!l||!M)return b({ok:!1,error:"Sign in again before enabling MFA."},401);try{let F=Ie.verifyTotpEnrollment(M.id,String(d.code??""));return Ie.markSessionStepUp(l.id,!0),a.store.appendEvent({organizationId:a.organization.id,actorId:M.actorId,type:"auth.mfa.enabled",payload:{recoveryCodeCount:F.recoveryCodes.length}}),b(F)}catch(F){return b({ok:!1,error:F instanceof Error?F.message:"MFA enrollment failed."},422)}}if(L.pathname==="/api/auth/mfa"&&C.method==="DELETE"){let d=await se(C),l=jt.resolveSession(C),k=Ne(ue),M=k.actor?Ie.getIdentityByActor(k.actor.id):void 0;if(!l||!M||!Ei(String(d.password??""),M.passwordHash))return b({ok:!1,error:"Current password is incorrect."},401);let F=Ie.verifyMfaCode(M.id,String(d.code??""));if(!F.valid||!F.method)return b({ok:!1,error:"Authenticator or recovery code is incorrect."},401);return Ie.disableMfa(M.id),Ie.revokeOtherSessions(M.id,l.id),Ie.markSessionStepUp(l.id),a.store.appendEvent({organizationId:a.organization.id,actorId:M.actorId,type:"auth.mfa.disabled",payload:{method:F.method}}),b({ok:!0})}if(L.pathname==="/api/auth/step-up"&&C.method==="POST"){let d=await se(C),l=jt.resolveSession(C),k=Ne(ue),M=k.actor?Ie.getIdentityByActor(k.actor.id):void 0;if(!l||!M||!Ei(String(d.password??""),M.passwordHash))return b({ok:!1,error:"Current password is incorrect."},401);let F=Ie.getMfaFactor(M.id);if(F?.state==="active"){if(!Ie.verifyMfaCode(M.id,String(d.code??"")).valid)return b({ok:!1,error:"Authenticator or recovery code is incorrect."},401)}let X=Ie.markSessionStepUp(l.id,F?.state==="active");return a.store.appendEvent({organizationId:a.organization.id,actorId:M.actorId,type:"auth.step_up.succeeded",payload:{mfa:F?.state==="active"}}),b({ok:!0,recentAuthAt:X.recentAuthAt})}if(L.pathname==="/api/terminal"){if(!ge)return b({ok:!1,error:"The web terminal is disabled."},403);if(Ze.upgrade(C))return;return Rd("WebSocket upgrade failed",400)}if(L.pathname==="/api/health"){let d=a.store.health();return b({ok:!0,cwd:t,environment:ye,environments:f,uiRoot:await ki(ue,ye),liveData:Re.size>0,terminal:ge,localPackage:import.meta.url.includes("/Code/Libraries/ts-cloud/"),controlPlane:{schemaVersion:d.schemaVersion,supportedSchemaVersion:d.supportedSchemaVersion,integrity:d.integrity,pendingRetryableOperations:d.pendingRetryableOperations}})}if(L.pathname==="/api/control-plane/operations"){let d=L.searchParams.get("state"),l=d&&["queued","running","succeeded","failed","cancelled","timed_out"].includes(d)?d:void 0;return b({operations:a.store.listOperations({projectId:a.project.id,state:l,kind:L.searchParams.get("kind")??void 0,limit:Number(L.searchParams.get("limit"))||100})})}if(L.pathname==="/api/queue"&&C.method==="GET"){let d=L.searchParams.get("state"),l=d&&["queued","running","succeeded","failed","cancelled","timed_out"].includes(d)?d:void 0,k=At.list({projectId:a.project.id,state:l,limit:Number(L.searchParams.get("limit"))||250}).filter((M)=>ys(ue,M.operation.id,"deployments:read")).map((M)=>{let F=M.operation.resourceId?a.store.getResource(M.operation.resourceId):void 0,X=M.operation.environmentId?a.store.listEnvironments(a.project.id).find((fe)=>fe.id===M.operation.environmentId):void 0,j=M.operation.actorId?a.store.getActor(M.operation.actorId):void 0,Z=M.operation.input;return{...M,target:F?{id:F.id,name:F.name,slug:F.slug,kind:F.kind}:X?{id:X.id,name:X.name,slug:X.slug,kind:"environment"}:{id:a.project.id,name:a.project.name,slug:a.project.slug,kind:"project"},actor:j?{id:j.id,name:j.displayName,kind:j.kind}:void 0,commit:Z.revision??Z.source?.commitSha??null}});return b({operations:k,concurrency:At.limits})}if(L.pathname==="/api/queue/logs"&&C.method==="GET"){let d=String(L.searchParams.get("id")??"");if(!ys(ue,d,"deployments:read"))return b({ok:!1,error:"Operation was not found in this scope."},404);let l=At.logs(d,{after:Number(L.searchParams.get("after"))||0,limit:Number(L.searchParams.get("limit"))||500});return b({entries:l,cursor:l.at(-1)?.sequence??(Number(L.searchParams.get("after"))||0),operation:a.store.getOperation(d)})}if(L.pathname==="/api/queue/stream"&&C.method==="GET"){let d=String(L.searchParams.get("id")??"");if(!ys(ue,d,"deployments:read"))return b({ok:!1,error:"Operation was not found in this scope."},404);let l=C.headers.get("last-event-id")?.trim(),k=Number(l||L.searchParams.get("after")||0),M=new TextEncoder,F,X=!1,j=new ReadableStream({start(Z){let fe=()=>{if(X)return;let pe=jt.resolveUser(C);if(!pe||!ys(pe,d,"deployments:read")){if(X=!0,F)clearInterval(F);Z.close();return}let He=At.logs(d,{after:k,limit:500});for(let Be of He)k=Be.sequence,Z.enqueue(M.encode(`id: ${Be.sequence}
487
487
  event: log
488
- data: ${JSON.stringify(Fe)}
488
+ data: ${JSON.stringify(Be)}
489
489
 
490
- `));let ve=a.store.getOperation(d);if(ve&&["succeeded","failed","cancelled","timed_out"].includes(ve.state)&&At.logs(d,{after:k,limit:1}).length===0){if(X=!0,B)clearInterval(B);Z.enqueue(M.encode(`event: complete
490
+ `));let ve=a.store.getOperation(d);if(ve&&["succeeded","failed","cancelled","timed_out"].includes(ve.state)&&At.logs(d,{after:k,limit:1}).length===0){if(X=!0,F)clearInterval(F);Z.enqueue(M.encode(`event: complete
491
491
  data: ${JSON.stringify({state:ve.state,cursor:k})}
492
492
 
493
- `)),Z.close()}};if(fe(),!X)B=setInterval(fe,500);C.signal.addEventListener("abort",()=>{if(X=!0,B)clearInterval(B);try{Z.close()}catch{}},{once:!0})},cancel(){if(X=!0,B)clearInterval(B)}});return new Response(j,{headers:{"content-type":"text/event-stream","cache-control":"no-store","x-accel-buffering":"no"}})}if(L.pathname==="/api/queue/cancel"&&C.method==="POST"){let d=await se(C),l=String(d.id??"");if(!ys(ue,l,"deployments:cancel"))return b({ok:!1,error:"Operation was not found or cannot be cancelled in this scope."},404);let k=gr(a.store,ue);try{return b({ok:!0,operation:At.requestCancellation(l,k.id)})}catch(M){return b({ok:!1,error:M instanceof Error?M.message:"Cancellation failed."},409)}}if(L.pathname==="/api/queue/retry"&&C.method==="POST"){let d=await se(C),l=String(d.id??"");if(!ys(ue,l,"deployments:create"))return b({ok:!1,error:"Operation was not found or cannot be retried in this scope."},404);let k=gr(a.store,ue);try{return b({ok:!0,operation:At.retry(l,String(d.errorClass??"manual"),{delayMs:Number(d.delayMs)||0,actorId:k.id})})}catch(M){return b({ok:!1,error:M instanceof Error?M.message:"Retry failed."},409)}}if(L.pathname==="/api/queue/settings"&&C.method==="GET")return b({concurrency:At.limits});if(L.pathname==="/api/queue/settings"&&C.method==="PATCH"){let d=await se(C);if(d.confirm!=="update queue limits")return b({ok:!1,error:'Type "update queue limits" to confirm production concurrency changes.'},409);let l=gr(a.store,ue);return b({ok:!0,concurrency:At.configureConcurrency(d.concurrency??{},{organizationId:a.organization.id,actorId:l.id})})}if(L.pathname==="/api/queue/history"&&C.method==="DELETE"){let d=await se(C);if(d.confirm!=="clear completed")return b({ok:!1,error:'Type "clear completed" to confirm retained history cleanup.'},409);let l=gr(a.store,ue);return b({ok:!0,deleted:At.clearCompleted({projectId:a.project.id,before:typeof d.before==="string"?d.before:void 0,actorId:l.id})})}if(L.pathname==="/api/previews"&&C.method==="GET"){let d=Wt.previews.listInstances({projectId:a.project.id}).filter((M)=>Sr(ue,M.resourceId,"deployments:read")),l=Wt.previews.listDefinitions(a.project.id).filter((M)=>Sr(ue,M.resourceId,"project:read")),k=a.store.listResources(a.project.id).filter((M)=>M.kind==="application"&&Sr(ue,M.id,"project:read")).map((M)=>({id:M.id,slug:M.slug,name:M.name,environmentId:M.environmentId}));return b({previews:d,definitions:l,resources:k,environments:[...a.environments.values()]})}if(L.pathname==="/api/releases"&&C.method==="GET"){let d=[...a.environments.values()],l=a.store.listResources(a.project.id).filter((B)=>Sr(ue,B.id,"deployments:read")),k=new Set(l.map((B)=>B.id)),M=Cn.releases.list({projectId:a.project.id}).filter((B)=>k.has(B.resourceId)).map((B)=>{let X=l.find((fe)=>fe.id===B.resourceId),j=d.find((fe)=>fe.id===B.environmentId),Z=B.previousReleaseId?Cn.releases.get(B.previousReleaseId):void 0;return{...B,resource:X?{id:X.id,name:X.name,slug:X.slug,provider:X.provider}:void 0,environment:j?{id:j.id,name:j.name,slug:j.slug,kind:j.kind}:void 0,artifact:Cn.releases.getArtifact(B.artifactId),transitions:Cn.releases.transitions(B.id),approvals:Cn.releases.approvals(B.id),previous:Z,comparison:Z?Cn.releases.compare(Z.id,B.id):void 0,capabilities:sr({kind:B.kind,provider:X?.provider,hasHealthGate:!!B.healthGate,replicas:Number(B.manifest?.replicas)||1})}});return b({releases:M,resources:l.map((B)=>({id:B.id,name:B.name,slug:B.slug,environmentId:B.environmentId,provider:B.provider})),environments:d})}if(L.pathname==="/api/releases/action"&&C.method==="POST"){let d=await se(C),l=Cn.releases.get(String(d.id??"")),k=String(d.action??"");if(!l||!Sr(ue,l.resourceId,"deployments:create"))return b({ok:!1,error:"Release was not found in this scope."},404);let M=gr(a.store,ue);try{if(k==="activate")return b({ok:!0,operation:Cn.enqueueActivation(l,{actorId:M.id})});if(k==="rollback"){let B=a.store.getResource(l.resourceId);if(d.confirm!==B?.slug)return b({ok:!1,error:`Type "${B?.slug??""}" to confirm rollback.`},409);return b({ok:!0,operation:Cn.enqueueRollback(l,{actorId:M.id,targetReleaseId:typeof d.targetReleaseId==="string"?d.targetReleaseId:void 0})})}if(k==="approve"){let B=a.store.listEnvironments(l.projectId).find((X)=>X.id===l.environmentId);if(d.confirm!==B?.slug)return b({ok:!1,error:`Type "${B?.slug??""}" to confirm the environment gate.`},409);return b({ok:!0,release:Cn.releases.approve(l.id,{actorId:M.id,decision:d.decision==="rejected"?"rejected":"approved",comment:typeof d.comment==="string"?d.comment:void 0})})}if(k==="pin")return b({ok:!0,release:Cn.releases.pin(l.id,d.pinned!==!1,typeof d.reason==="string"?d.reason:void 0)});if(k==="promote"){let B=a.store.getResource(String(d.targetResourceId??"")),X=B?a.store.listEnvironments(l.projectId).find((j)=>j.id===B.environmentId):void 0;if(!B||!X||!Sr(ue,B.id,"deployments:create"))return b({ok:!1,error:"Promotion target was not found in this scope."},404);if(d.confirm!==X.slug)return b({ok:!1,error:`Type "${X.slug}" to confirm promotion.`},409);return b({ok:!0,release:Cn.releases.promote(l.id,{targetEnvironmentId:X.id,targetResourceId:B.id,config:d.config&&typeof d.config==="object"?d.config:{},strategy:typeof d.strategy==="string"?d.strategy:void 0,actorId:M.id,approvalRequired:d.approvalRequired===!0})})}return b({ok:!1,error:"Unsupported release action."},422)}catch(B){return b({ok:!1,error:B instanceof Error?B.message:"Release action failed."},409)}}if(L.pathname==="/api/compose"&&C.method==="GET"){let d=ho.applications.list({projectId:a.project.id}).filter((l)=>Sr(ue,l.resourceId,"applications:read")).map((l)=>({...l,services:ho.applications.services(l.id)}));return b({applications:d,templates:hr(),environments:[...a.environments.values()]})}if(L.pathname==="/api/compose/preview"&&C.method==="POST"){let d=await se(C),l=String(d.environmentId??"");if(!la(ue,l,"applications:manage"))return b({ok:!1,error:"Environment was not found in this scope."},404);try{return b({ok:!0,result:ho.applications.preview(String(d.source??""),{name:String(d.name??""),slug:typeof d.slug==="string"?d.slug:void 0,projectId:a.project.id,environmentId:l})})}catch(k){return b({ok:!1,error:k instanceof Error?k.message:"Compose could not be parsed."},422)}}if((L.pathname==="/api/compose/import"||L.pathname==="/api/compose/template")&&C.method==="POST"){let d=await se(C),l=String(d.environmentId??"");if(!la(ue,l,"applications:manage"))return b({ok:!1,error:"Environment was not found in this scope."},404);let k=gr(a.store,ue);try{let M=L.pathname.endsWith("/template")?ho.applications.fromTemplate(String(d.templateId??""),d.inputs&&typeof d.inputs==="object"?d.inputs:{},{name:String(d.name??""),projectId:a.project.id,environmentId:l,version:typeof d.templateVersion==="string"?d.templateVersion:void 0,createdByActorId:k.id}):ho.applications.import(String(d.source??""),{name:String(d.name??""),slug:typeof d.slug==="string"?d.slug:void 0,projectId:a.project.id,environmentId:l,createdByActorId:k.id});return b({ok:!0,application:M.application,diagnostics:M.parsed.diagnostics})}catch(M){return b({ok:!1,error:M instanceof Error?M.message:"Compose application could not be saved."},422)}}if(L.pathname==="/api/compose/action"&&C.method==="POST"){let d=await se(C),l=ho.applications.get(String(d.id??"")),k=String(d.action??""),M=k==="delete"||k==="stop"?"deployments:cancel":"deployments:create";if(!l||!Sr(ue,l.resourceId,M))return b({ok:!1,error:"Compose application was not found in this scope."},404);try{let B=gr(a.store,ue);return b({ok:!0,operation:ho.enqueue(l,k,{actorId:B.id,service:typeof d.service==="string"?d.service:void 0,replicas:Number.isFinite(Number(d.replicas))?Number(d.replicas):void 0,removeVolumes:d.removeVolumes===!0,confirmation:typeof d.confirm==="string"?d.confirm:void 0})})}catch(B){return b({ok:!1,error:B instanceof Error?B.message:"Compose operation could not be queued."},409)}}if((L.pathname==="/api/compose/logs"||L.pathname==="/api/compose/shell")&&C.method==="POST"){let d=await se(C),l=ho.applications.get(String(d.id??"")),k=L.pathname.endsWith("/shell"),M=k?"runtime:terminal":"runtime:logs";if(!l||!Sr(ue,l.resourceId,M))return b({ok:!1,error:"Compose service was not found in this scope."},404);let B=String(d.service??"");if(!l.manifest.spec.services[B])return b({ok:!1,error:"Compose service was not found."},404);if(k&&d.confirm!==B)return b({ok:!1,error:`Type "${B}" to run a service command.`},409);let X=a.store.listEnvironments(l.projectId).find((Z)=>Z.id===l.environmentId)?.slug;if(!X)return b({ok:!1,error:"Compose environment was not found."},404);let j=k?gi(l.manifest,B,Array.isArray(d.command)?d.command.map(String):["sh"]):mi(l.manifest,B,Number(d.lines)||200);return b(await or(o,X,j))}if(L.pathname==="/api/previews/definitions"&&C.method==="POST"){let d=await se(C),l=String(d.resourceId??"");if(!Sr(ue,l,"config:write"))return b({ok:!1,error:"Application was not found in this scope."},404);let k=gr(a.store,ue);try{return b({ok:!0,definition:Wt.previews.createDefinition({...d,projectId:a.project.id,resourceId:l,baseEnvironmentId:String(d.baseEnvironmentId??""),domainPattern:String(d.domainPattern??""),createdByActorId:k.id})})}catch(M){return b({ok:!1,error:M instanceof Error?M.message:"Preview policy could not be created."},409)}}if(L.pathname==="/api/previews/deploy"&&C.method==="POST"){let d=await se(C),l=Wt.previews.getDefinition(String(d.definitionId??""));if(!l||!Sr(ue,l.resourceId,"deployments:create"))return b({ok:!1,error:"Preview policy was not found in this scope."},404);let k=gr(a.store,ue);try{let M=Wt.previews.upsert({definitionId:l.id,sourceProvider:"dashboard",repository:"dashboard",branch:String(d.branch??""),pullRequestNumber:Number(d.pullRequestNumber)||void 0,commitSha:String(d.commitSha??""),createdByActorId:k.id});return b({ok:!0,preview:M.preview,operation:Wt.enqueueDeploy(M.preview,{created:M.created,actorId:k.id})})}catch(M){return b({ok:!1,error:M instanceof Error?M.message:"Preview could not be queued."},409)}}if(L.pathname==="/api/previews/destroy"&&C.method==="POST"){let d=await se(C),l=Wt.previews.getInstance(String(d.id??""));if(!l||!Sr(ue,l.resourceId,"deployments:cancel"))return b({ok:!1,error:"Preview was not found in this scope."},404);if(d.confirm!==l.name)return b({ok:!1,error:`Type "${l.name}" to confirm tagged teardown.`},409);let k=gr(a.store,ue);return b({ok:!0,operation:Wt.enqueueDestroy(l,"dashboard",k.id)})}if(L.pathname==="/api/previews/extend"&&C.method==="POST"){let d=await se(C),l=Wt.previews.getInstance(String(d.id??""));if(!l||!Sr(ue,l.resourceId,"deployments:create"))return b({ok:!1,error:"Preview was not found in this scope."},404);return b({ok:!0,preview:Wt.previews.extend(l.id,Number(d.hours))})}if(L.pathname==="/api/previews/rebuild"&&C.method==="POST"){let d=await se(C),l=Wt.previews.getInstance(String(d.id??""));if(!l||!Sr(ue,l.resourceId,"deployments:create"))return b({ok:!1,error:"Preview was not found in this scope."},404);let k=gr(a.store,ue);return b({ok:!0,operation:Wt.enqueueDeploy(l,{actorId:k.id,reason:"manual_rebuild"})})}if(L.pathname==="/api/previews/cleanup"&&C.method==="POST"){let d=await se(C);if(!d.dryRun&&d.confirm!=="cleanup previews")return b({ok:!1,error:'Type "cleanup previews" to confirm teardown.'},409);let l=gr(a.store,ue);return b({ok:!0,...Wt.cleanup({dryRun:d.dryRun===!0,maxAgeHours:Number(d.maxAgeHours)||void 0,keepCount:Number(d.keepCount)||void 0,actorId:l.id})})}if(L.pathname==="/api/control-plane/events")return b({events:a.store.listEvents({organizationId:a.organization.id,projectId:a.project.id,operationId:L.searchParams.get("operationId")??void 0,correlationId:L.searchParams.get("correlationId")??void 0,afterSequence:Number(L.searchParams.get("afterSequence"))||void 0,limit:Number(L.searchParams.get("limit"))||200})});if(L.pathname==="/api/search"){let d=String(L.searchParams.get("q")??"").trim().slice(0,128),l=Tn.role==="member"?new Set(Object.keys(Tn.sites)):void 0,k=d?ra(a.store,{projectId:a.project.id,query:d,allowedResourceSlugs:l,limit:Number(L.searchParams.get("limit"))||20}):[];return b({query:d,results:k,stale:!1})}if(L.pathname==="/api/search/preferences"&&C.method==="GET"){let d=`dashboard:${ue.username.toLowerCase()}`;return b({savedFilters:a.store.listSavedFilters(d),navigation:a.store.listNavigation(d)})}if(L.pathname==="/api/search/preferences"&&C.method==="POST"){let d=`dashboard:${ue.username.toLowerCase()}`,l=await se(C),k=String(l.action??"");if(k==="save-filter")return b({savedFilter:a.store.saveFilter(d,String(l.name??""),String(l.routeId??""),l.query??{})});if(k==="favorite")return b({navigation:a.store.setFavorite(d,String(l.entityType??""),String(l.entityId??""),l.favorite!==!1)});if(k==="visit")return b({navigation:a.store.recordNavigation(d,String(l.entityType??""),String(l.entityId??""))});return b({ok:!1,error:"Unknown search preference action."},422)}if(L.pathname==="/api/search/preferences"&&C.method==="DELETE"){let d=`dashboard:${ue.username.toLowerCase()}`,l=await se(C);return b({ok:a.store.deleteSavedFilter(d,String(l.id??""))})}if(L.pathname==="/api/organization"&&C.method==="GET"){let d=a.store.listMemberships(a.organization.id,{includeRevoked:!0}).map((l)=>{let k=a.store.getActor(l.actorId);return{...l,actor:k?{id:k.id,displayName:k.displayName,externalId:k.externalId,disabledAt:k.disabledAt}:void 0,grants:a.store.listGrants(l.id)}});return b({organization:a.organization,project:a.project,environments:a.store.listEnvironments(a.project.id),resources:a.store.listResources(a.project.id).map((l)=>({id:l.id,environmentId:l.environmentId,kind:l.kind,slug:l.slug,name:l.name})),memberships:d,invitations:a.store.listInvitations(a.organization.id)})}if(L.pathname==="/api/organization/invitations"&&C.method==="GET")return b({invitations:a.store.listInvitations(a.organization.id)});if(L.pathname==="/api/organization/invitations"&&C.method==="POST"){let d=await se(C),l=Td(d.roleTemplate),k=Ba(d);if(!l||!k)return b({ok:!1,error:"Choose a valid role template and resource scope."},422);let M=Ne(ue);if(!M.actor||!M.membership)return b({ok:!1,error:"Your organization membership is unavailable."},403);if(l==="owner"&&(!Ei(String(d.password??""),ue.passwordHash)||M.membership.roleTemplate!=="owner"))return b({ok:!1,error:"Owner invitations require an owner to re-enter their password."},401);try{let B=a.store.createInvitation({organizationId:a.organization.id,email:String(d.email??""),roleTemplate:l,scope:k,invitedByActorId:M.actor.id,expiresInMs:Number(d.expiresInMs)||void 0}),X=`${L.origin}/accept-invitation?token=${encodeURIComponent(B.token)}`,j=await ba(o,{to:B.invitation.email,subject:"Your ts-cloud organization invitation",text:`Accept your ts-cloud invitation: ${X}
493
+ `)),Z.close()}};if(fe(),!X)F=setInterval(fe,500);C.signal.addEventListener("abort",()=>{if(X=!0,F)clearInterval(F);try{Z.close()}catch{}},{once:!0})},cancel(){if(X=!0,F)clearInterval(F)}});return new Response(j,{headers:{"content-type":"text/event-stream","cache-control":"no-store","x-accel-buffering":"no"}})}if(L.pathname==="/api/queue/cancel"&&C.method==="POST"){let d=await se(C),l=String(d.id??"");if(!ys(ue,l,"deployments:cancel"))return b({ok:!1,error:"Operation was not found or cannot be cancelled in this scope."},404);let k=gr(a.store,ue);try{return b({ok:!0,operation:At.requestCancellation(l,k.id)})}catch(M){return b({ok:!1,error:M instanceof Error?M.message:"Cancellation failed."},409)}}if(L.pathname==="/api/queue/retry"&&C.method==="POST"){let d=await se(C),l=String(d.id??"");if(!ys(ue,l,"deployments:create"))return b({ok:!1,error:"Operation was not found or cannot be retried in this scope."},404);let k=gr(a.store,ue);try{return b({ok:!0,operation:At.retry(l,String(d.errorClass??"manual"),{delayMs:Number(d.delayMs)||0,actorId:k.id})})}catch(M){return b({ok:!1,error:M instanceof Error?M.message:"Retry failed."},409)}}if(L.pathname==="/api/queue/settings"&&C.method==="GET")return b({concurrency:At.limits});if(L.pathname==="/api/queue/settings"&&C.method==="PATCH"){let d=await se(C);if(d.confirm!=="update queue limits")return b({ok:!1,error:'Type "update queue limits" to confirm production concurrency changes.'},409);let l=gr(a.store,ue);return b({ok:!0,concurrency:At.configureConcurrency(d.concurrency??{},{organizationId:a.organization.id,actorId:l.id})})}if(L.pathname==="/api/queue/history"&&C.method==="DELETE"){let d=await se(C);if(d.confirm!=="clear completed")return b({ok:!1,error:'Type "clear completed" to confirm retained history cleanup.'},409);let l=gr(a.store,ue);return b({ok:!0,deleted:At.clearCompleted({projectId:a.project.id,before:typeof d.before==="string"?d.before:void 0,actorId:l.id})})}if(L.pathname==="/api/previews"&&C.method==="GET"){let d=Wt.previews.listInstances({projectId:a.project.id}).filter((M)=>Sr(ue,M.resourceId,"deployments:read")),l=Wt.previews.listDefinitions(a.project.id).filter((M)=>Sr(ue,M.resourceId,"project:read")),k=a.store.listResources(a.project.id).filter((M)=>M.kind==="application"&&Sr(ue,M.id,"project:read")).map((M)=>({id:M.id,slug:M.slug,name:M.name,environmentId:M.environmentId}));return b({previews:d,definitions:l,resources:k,environments:[...a.environments.values()]})}if(L.pathname==="/api/releases"&&C.method==="GET"){let d=[...a.environments.values()],l=a.store.listResources(a.project.id).filter((F)=>Sr(ue,F.id,"deployments:read")),k=new Set(l.map((F)=>F.id)),M=Cn.releases.list({projectId:a.project.id}).filter((F)=>k.has(F.resourceId)).map((F)=>{let X=l.find((fe)=>fe.id===F.resourceId),j=d.find((fe)=>fe.id===F.environmentId),Z=F.previousReleaseId?Cn.releases.get(F.previousReleaseId):void 0;return{...F,resource:X?{id:X.id,name:X.name,slug:X.slug,provider:X.provider}:void 0,environment:j?{id:j.id,name:j.name,slug:j.slug,kind:j.kind}:void 0,artifact:Cn.releases.getArtifact(F.artifactId),transitions:Cn.releases.transitions(F.id),approvals:Cn.releases.approvals(F.id),previous:Z,comparison:Z?Cn.releases.compare(Z.id,F.id):void 0,capabilities:sr({kind:F.kind,provider:X?.provider,hasHealthGate:!!F.healthGate,replicas:Number(F.manifest?.replicas)||1})}});return b({releases:M,resources:l.map((F)=>({id:F.id,name:F.name,slug:F.slug,environmentId:F.environmentId,provider:F.provider})),environments:d})}if(L.pathname==="/api/releases/action"&&C.method==="POST"){let d=await se(C),l=Cn.releases.get(String(d.id??"")),k=String(d.action??"");if(!l||!Sr(ue,l.resourceId,"deployments:create"))return b({ok:!1,error:"Release was not found in this scope."},404);let M=gr(a.store,ue);try{if(k==="activate")return b({ok:!0,operation:Cn.enqueueActivation(l,{actorId:M.id})});if(k==="rollback"){let F=a.store.getResource(l.resourceId);if(d.confirm!==F?.slug)return b({ok:!1,error:`Type "${F?.slug??""}" to confirm rollback.`},409);return b({ok:!0,operation:Cn.enqueueRollback(l,{actorId:M.id,targetReleaseId:typeof d.targetReleaseId==="string"?d.targetReleaseId:void 0})})}if(k==="approve"){let F=a.store.listEnvironments(l.projectId).find((X)=>X.id===l.environmentId);if(d.confirm!==F?.slug)return b({ok:!1,error:`Type "${F?.slug??""}" to confirm the environment gate.`},409);return b({ok:!0,release:Cn.releases.approve(l.id,{actorId:M.id,decision:d.decision==="rejected"?"rejected":"approved",comment:typeof d.comment==="string"?d.comment:void 0})})}if(k==="pin")return b({ok:!0,release:Cn.releases.pin(l.id,d.pinned!==!1,typeof d.reason==="string"?d.reason:void 0)});if(k==="promote"){let F=a.store.getResource(String(d.targetResourceId??"")),X=F?a.store.listEnvironments(l.projectId).find((j)=>j.id===F.environmentId):void 0;if(!F||!X||!Sr(ue,F.id,"deployments:create"))return b({ok:!1,error:"Promotion target was not found in this scope."},404);if(d.confirm!==X.slug)return b({ok:!1,error:`Type "${X.slug}" to confirm promotion.`},409);return b({ok:!0,release:Cn.releases.promote(l.id,{targetEnvironmentId:X.id,targetResourceId:F.id,config:d.config&&typeof d.config==="object"?d.config:{},strategy:typeof d.strategy==="string"?d.strategy:void 0,actorId:M.id,approvalRequired:d.approvalRequired===!0})})}return b({ok:!1,error:"Unsupported release action."},422)}catch(F){return b({ok:!1,error:F instanceof Error?F.message:"Release action failed."},409)}}if(L.pathname==="/api/compose"&&C.method==="GET"){let d=ho.applications.list({projectId:a.project.id}).filter((l)=>Sr(ue,l.resourceId,"applications:read")).map((l)=>({...l,services:ho.applications.services(l.id)}));return b({applications:d,templates:hr(),environments:[...a.environments.values()]})}if(L.pathname==="/api/compose/preview"&&C.method==="POST"){let d=await se(C),l=String(d.environmentId??"");if(!la(ue,l,"applications:manage"))return b({ok:!1,error:"Environment was not found in this scope."},404);try{return b({ok:!0,result:ho.applications.preview(String(d.source??""),{name:String(d.name??""),slug:typeof d.slug==="string"?d.slug:void 0,projectId:a.project.id,environmentId:l})})}catch(k){return b({ok:!1,error:k instanceof Error?k.message:"Compose could not be parsed."},422)}}if((L.pathname==="/api/compose/import"||L.pathname==="/api/compose/template")&&C.method==="POST"){let d=await se(C),l=String(d.environmentId??"");if(!la(ue,l,"applications:manage"))return b({ok:!1,error:"Environment was not found in this scope."},404);let k=gr(a.store,ue);try{let M=L.pathname.endsWith("/template")?ho.applications.fromTemplate(String(d.templateId??""),d.inputs&&typeof d.inputs==="object"?d.inputs:{},{name:String(d.name??""),projectId:a.project.id,environmentId:l,version:typeof d.templateVersion==="string"?d.templateVersion:void 0,createdByActorId:k.id}):ho.applications.import(String(d.source??""),{name:String(d.name??""),slug:typeof d.slug==="string"?d.slug:void 0,projectId:a.project.id,environmentId:l,createdByActorId:k.id});return b({ok:!0,application:M.application,diagnostics:M.parsed.diagnostics})}catch(M){return b({ok:!1,error:M instanceof Error?M.message:"Compose application could not be saved."},422)}}if(L.pathname==="/api/compose/action"&&C.method==="POST"){let d=await se(C),l=ho.applications.get(String(d.id??"")),k=String(d.action??""),M=k==="delete"||k==="stop"?"deployments:cancel":"deployments:create";if(!l||!Sr(ue,l.resourceId,M))return b({ok:!1,error:"Compose application was not found in this scope."},404);try{let F=gr(a.store,ue);return b({ok:!0,operation:ho.enqueue(l,k,{actorId:F.id,service:typeof d.service==="string"?d.service:void 0,replicas:Number.isFinite(Number(d.replicas))?Number(d.replicas):void 0,removeVolumes:d.removeVolumes===!0,confirmation:typeof d.confirm==="string"?d.confirm:void 0})})}catch(F){return b({ok:!1,error:F instanceof Error?F.message:"Compose operation could not be queued."},409)}}if((L.pathname==="/api/compose/logs"||L.pathname==="/api/compose/shell")&&C.method==="POST"){let d=await se(C),l=ho.applications.get(String(d.id??"")),k=L.pathname.endsWith("/shell"),M=k?"runtime:terminal":"runtime:logs";if(!l||!Sr(ue,l.resourceId,M))return b({ok:!1,error:"Compose service was not found in this scope."},404);let F=String(d.service??"");if(!l.manifest.spec.services[F])return b({ok:!1,error:"Compose service was not found."},404);if(k&&d.confirm!==F)return b({ok:!1,error:`Type "${F}" to run a service command.`},409);let X=a.store.listEnvironments(l.projectId).find((Z)=>Z.id===l.environmentId)?.slug;if(!X)return b({ok:!1,error:"Compose environment was not found."},404);let j=k?gi(l.manifest,F,Array.isArray(d.command)?d.command.map(String):["sh"]):mi(l.manifest,F,Number(d.lines)||200);return b(await or(o,X,j))}if(L.pathname==="/api/previews/definitions"&&C.method==="POST"){let d=await se(C),l=String(d.resourceId??"");if(!Sr(ue,l,"config:write"))return b({ok:!1,error:"Application was not found in this scope."},404);let k=gr(a.store,ue);try{return b({ok:!0,definition:Wt.previews.createDefinition({...d,projectId:a.project.id,resourceId:l,baseEnvironmentId:String(d.baseEnvironmentId??""),domainPattern:String(d.domainPattern??""),createdByActorId:k.id})})}catch(M){return b({ok:!1,error:M instanceof Error?M.message:"Preview policy could not be created."},409)}}if(L.pathname==="/api/previews/deploy"&&C.method==="POST"){let d=await se(C),l=Wt.previews.getDefinition(String(d.definitionId??""));if(!l||!Sr(ue,l.resourceId,"deployments:create"))return b({ok:!1,error:"Preview policy was not found in this scope."},404);let k=gr(a.store,ue);try{let M=Wt.previews.upsert({definitionId:l.id,sourceProvider:"dashboard",repository:"dashboard",branch:String(d.branch??""),pullRequestNumber:Number(d.pullRequestNumber)||void 0,commitSha:String(d.commitSha??""),createdByActorId:k.id});return b({ok:!0,preview:M.preview,operation:Wt.enqueueDeploy(M.preview,{created:M.created,actorId:k.id})})}catch(M){return b({ok:!1,error:M instanceof Error?M.message:"Preview could not be queued."},409)}}if(L.pathname==="/api/previews/destroy"&&C.method==="POST"){let d=await se(C),l=Wt.previews.getInstance(String(d.id??""));if(!l||!Sr(ue,l.resourceId,"deployments:cancel"))return b({ok:!1,error:"Preview was not found in this scope."},404);if(d.confirm!==l.name)return b({ok:!1,error:`Type "${l.name}" to confirm tagged teardown.`},409);let k=gr(a.store,ue);return b({ok:!0,operation:Wt.enqueueDestroy(l,"dashboard",k.id)})}if(L.pathname==="/api/previews/extend"&&C.method==="POST"){let d=await se(C),l=Wt.previews.getInstance(String(d.id??""));if(!l||!Sr(ue,l.resourceId,"deployments:create"))return b({ok:!1,error:"Preview was not found in this scope."},404);return b({ok:!0,preview:Wt.previews.extend(l.id,Number(d.hours))})}if(L.pathname==="/api/previews/rebuild"&&C.method==="POST"){let d=await se(C),l=Wt.previews.getInstance(String(d.id??""));if(!l||!Sr(ue,l.resourceId,"deployments:create"))return b({ok:!1,error:"Preview was not found in this scope."},404);let k=gr(a.store,ue);return b({ok:!0,operation:Wt.enqueueDeploy(l,{actorId:k.id,reason:"manual_rebuild"})})}if(L.pathname==="/api/previews/cleanup"&&C.method==="POST"){let d=await se(C);if(!d.dryRun&&d.confirm!=="cleanup previews")return b({ok:!1,error:'Type "cleanup previews" to confirm teardown.'},409);let l=gr(a.store,ue);return b({ok:!0,...Wt.cleanup({dryRun:d.dryRun===!0,maxAgeHours:Number(d.maxAgeHours)||void 0,keepCount:Number(d.keepCount)||void 0,actorId:l.id})})}if(L.pathname==="/api/control-plane/events")return b({events:a.store.listEvents({organizationId:a.organization.id,projectId:a.project.id,operationId:L.searchParams.get("operationId")??void 0,correlationId:L.searchParams.get("correlationId")??void 0,afterSequence:Number(L.searchParams.get("afterSequence"))||void 0,limit:Number(L.searchParams.get("limit"))||200})});if(L.pathname==="/api/search"){let d=String(L.searchParams.get("q")??"").trim().slice(0,128),l=Tn.role==="member"?new Set(Object.keys(Tn.sites)):void 0,k=d?ra(a.store,{projectId:a.project.id,query:d,allowedResourceSlugs:l,limit:Number(L.searchParams.get("limit"))||20}):[];return b({query:d,results:k,stale:!1})}if(L.pathname==="/api/search/preferences"&&C.method==="GET"){let d=`dashboard:${ue.username.toLowerCase()}`;return b({savedFilters:a.store.listSavedFilters(d),navigation:a.store.listNavigation(d)})}if(L.pathname==="/api/search/preferences"&&C.method==="POST"){let d=`dashboard:${ue.username.toLowerCase()}`,l=await se(C),k=String(l.action??"");if(k==="save-filter")return b({savedFilter:a.store.saveFilter(d,String(l.name??""),String(l.routeId??""),l.query??{})});if(k==="favorite")return b({navigation:a.store.setFavorite(d,String(l.entityType??""),String(l.entityId??""),l.favorite!==!1)});if(k==="visit")return b({navigation:a.store.recordNavigation(d,String(l.entityType??""),String(l.entityId??""))});return b({ok:!1,error:"Unknown search preference action."},422)}if(L.pathname==="/api/search/preferences"&&C.method==="DELETE"){let d=`dashboard:${ue.username.toLowerCase()}`,l=await se(C);return b({ok:a.store.deleteSavedFilter(d,String(l.id??""))})}if(L.pathname==="/api/organization"&&C.method==="GET"){let d=a.store.listMemberships(a.organization.id,{includeRevoked:!0}).map((l)=>{let k=a.store.getActor(l.actorId);return{...l,actor:k?{id:k.id,displayName:k.displayName,externalId:k.externalId,disabledAt:k.disabledAt}:void 0,grants:a.store.listGrants(l.id)}});return b({organization:a.organization,project:a.project,environments:a.store.listEnvironments(a.project.id),resources:a.store.listResources(a.project.id).map((l)=>({id:l.id,environmentId:l.environmentId,kind:l.kind,slug:l.slug,name:l.name})),memberships:d,invitations:a.store.listInvitations(a.organization.id)})}if(L.pathname==="/api/organization/invitations"&&C.method==="GET")return b({invitations:a.store.listInvitations(a.organization.id)});if(L.pathname==="/api/organization/invitations"&&C.method==="POST"){let d=await se(C),l=Td(d.roleTemplate),k=Ba(d);if(!l||!k)return b({ok:!1,error:"Choose a valid role template and resource scope."},422);let M=Ne(ue);if(!M.actor||!M.membership)return b({ok:!1,error:"Your organization membership is unavailable."},403);if(l==="owner"&&(!Ei(String(d.password??""),ue.passwordHash)||M.membership.roleTemplate!=="owner"))return b({ok:!1,error:"Owner invitations require an owner to re-enter their password."},401);try{let F=a.store.createInvitation({organizationId:a.organization.id,email:String(d.email??""),roleTemplate:l,scope:k,invitedByActorId:M.actor.id,expiresInMs:Number(d.expiresInMs)||void 0}),X=`${L.origin}/accept-invitation?token=${encodeURIComponent(F.token)}`,j=await ba(o,{to:F.invitation.email,subject:"Your ts-cloud organization invitation",text:`Accept your ts-cloud invitation: ${X}
494
494
 
495
- This link expires ${B.invitation.expiresAt} and can be used once.`});return b({invitation:B.invitation,token:B.token,acceptUrl:X,delivered:j},201)}catch(B){return b({ok:!1,error:B instanceof Error?B.message:"Invitation could not be created."},422)}}if(L.pathname==="/api/organization/invitations"&&C.method==="DELETE"){let d=await se(C),l=Ne(ue);try{return b({invitation:a.store.revokeInvitation(String(d.id??""),l.actor?.id)})}catch(k){return b({ok:!1,error:k instanceof Error?k.message:"Invitation could not be revoked."},409)}}if(L.pathname==="/api/organization/invitations/resend"&&C.method==="POST"){let d=await se(C),l=Ne(ue);try{let k=a.store.reissueInvitation(String(d.id??""),l.actor?.id),M=`${L.origin}/accept-invitation?token=${encodeURIComponent(k.token)}`,B=await ba(o,{to:k.invitation.email,subject:"Your ts-cloud organization invitation",text:`Accept your ts-cloud invitation: ${M}
495
+ This link expires ${F.invitation.expiresAt} and can be used once.`});return b({invitation:F.invitation,token:F.token,acceptUrl:X,delivered:j},201)}catch(F){return b({ok:!1,error:F instanceof Error?F.message:"Invitation could not be created."},422)}}if(L.pathname==="/api/organization/invitations"&&C.method==="DELETE"){let d=await se(C),l=Ne(ue);try{return b({invitation:a.store.revokeInvitation(String(d.id??""),l.actor?.id)})}catch(k){return b({ok:!1,error:k instanceof Error?k.message:"Invitation could not be revoked."},409)}}if(L.pathname==="/api/organization/invitations/resend"&&C.method==="POST"){let d=await se(C),l=Ne(ue);try{let k=a.store.reissueInvitation(String(d.id??""),l.actor?.id),M=`${L.origin}/accept-invitation?token=${encodeURIComponent(k.token)}`,F=await ba(o,{to:k.invitation.email,subject:"Your ts-cloud organization invitation",text:`Accept your ts-cloud invitation: ${M}
496
496
 
497
- This replacement link expires ${k.invitation.expiresAt} and can be used once.`});return b({invitation:k.invitation,token:k.token,acceptUrl:M,delivered:B})}catch(k){return b({ok:!1,error:k instanceof Error?k.message:"Invitation could not be resent."},409)}}if(L.pathname==="/api/organization/memberships"&&C.method==="PATCH"){let d=await se(C),l=a.store.getMembership(String(d.id??"")),k=Td(d.roleTemplate),M=Ba(d);if(!l||l.organizationId!==a.organization.id)return b({ok:!1,error:"Membership was not found."},404);if(!k||!M)return b({ok:!1,error:"Choose a valid role template and resource scope."},422);let B=Ne(ue);if((l.roleTemplate==="owner"||k==="owner")&&(!Ei(String(d.password??""),ue.passwordHash)||B.membership?.roleTemplate!=="owner"))return b({ok:!1,error:"Ownership changes require an owner to re-enter their password."},401);let j=a.store.resolveAuthorizationTarget(a.organization.id,M)??a.store.resolveAuthorizationTarget(a.organization.id,{type:"project",id:a.project.id}),Z=a.store.listGrants(l.id),fe=hn({membership:l,grants:Z,target:j}),pe={...l,roleTemplate:k,scope:M},He=hn({membership:pe,grants:Z,target:j}),ve={gained:He.filter((Fe)=>!fe.includes(Fe)),lost:fe.filter((Fe)=>!He.includes(Fe))};if(d.preview===!0)return b({membership:l,proposed:{roleTemplate:k,scope:M},accessDiff:ve});if(String(d.confirm??"")!==l.id)return b({ok:!1,error:`Confirm this change with membership ID ${l.id}.`,accessDiff:ve},409);try{return b({membership:a.store.updateMembership({id:l.id,roleTemplate:k,scope:M,actorId:B.actor?.id}),accessDiff:ve})}catch(Fe){return b({ok:!1,error:Fe instanceof Error?Fe.message:"Membership could not be updated."},409)}}if(L.pathname==="/api/organization/memberships"&&C.method==="DELETE"){let d=await se(C),l=a.store.getMembership(String(d.id??""));if(!l||l.organizationId!==a.organization.id)return b({ok:!1,error:"Membership was not found."},404);if(String(d.confirm??"")!==l.id)return b({ok:!1,error:`Confirm removal with membership ID ${l.id}.`},409);let k=Ne(ue);if(l.roleTemplate==="owner"&&(k.membership?.roleTemplate!=="owner"||!Ei(String(d.password??""),ue.passwordHash)))return b({ok:!1,error:"Removing an owner requires an owner to re-enter their current password."},401);try{return b({membership:a.store.revokeMembership(l.id,k.actor?.id)})}catch(M){return b({ok:!1,error:M instanceof Error?M.message:"Membership could not be removed."},409)}}if(L.pathname==="/api/organization/grants"&&C.method==="POST"){let d=await se(C),l=String(d.capability??""),k=d.effect==="deny"?"deny":d.effect==="allow"?"allow":void 0,M=Ba(d),B=Ne(ue);if(!k||!M||!ae.includes(l))return b({ok:!1,error:"Choose a valid capability, effect, and resource scope."},422);try{return b({grant:a.store.upsertGrant({organizationId:a.organization.id,membershipId:String(d.membershipId??""),effect:k,capability:l,scope:M,actorId:B.actor?.id})},201)}catch(X){return b({ok:!1,error:X instanceof Error?X.message:"Grant could not be created."},422)}}if(L.pathname==="/api/organization/grants"&&C.method==="DELETE"){let d=await se(C),l=Ne(ue),k=a.store.getGrant(String(d.id??""));if(!k||k.organizationId!==a.organization.id)return b({ok:!1,error:"Grant was not found."},404);return b({ok:a.store.removeGrant(k.id,l.actor?.id)})}if(L.pathname==="/api/tags"&&C.method==="GET")return b({tags:a.store.listTags(a.project.id),assignments:a.store.listResourceTags(a.project.id)});if(L.pathname==="/api/tags"&&C.method==="POST"){let d=await se(C),l=a.store.upsertTag(a.project.id,String(d.name??""),String(d.color??"#5a8be0"));if(d.resourceId)a.store.assignTag(String(d.resourceId),l.id);return b({tag:l},201)}if(L.pathname==="/api/tags"&&C.method==="DELETE"){let d=await se(C);return a.store.removeTag(String(d.resourceId??""),String(d.tagId??"")),b({ok:!0})}if(L.pathname==="/"&&!fb(L.pathname,Tn))return new Response(null,{status:302,headers:{location:`/server/sites?env=${encodeURIComponent(ye)}`}});if(L.pathname==="/"&&Lt?.mode==="serverless")return new Response(null,{status:302,headers:{location:`/serverless?env=${encodeURIComponent(ye)}`}});let Ja=by(L.pathname);if(Ja)return new Response(null,{status:308,headers:{location:`${Ja}?env=${encodeURIComponent(ye)}`}});if(L.pathname==="/api/env"&&C.method==="POST"){let d=await se(C),l=String(d.env??"");if(!f.includes(l))return b({ok:!1,error:`Unknown environment '${l}'.`,environments:f},404);return b({ok:!0,environment:l,environments:f,href:`?env=${encodeURIComponent(l)}`})}if(L.pathname==="/api/config"){let d={...fA(o),environment:ye,environments:f};return b(vy(d,Tn))}if(L.pathname==="/api/ssh-keys"&&C.method==="GET")return b({configPath:R,keys:_t(da(o))});if(L.pathname==="/api/ssh-keys"&&C.method==="POST"){if(!R)return b({ok:!1,error:"No cloud config file was found in this checkout."},404);let d=await se(C),l=await Li(R,"utf8"),k=da(o),M=mc({configText:l,name:String(d.name??""),publicKey:String(d.publicKey??""),existingKeys:k});return await ls(R,M),lb(o,[...k,{name:String(d.name??"").trim(),publicKey:String(d.publicKey??"").trim().replace(/\s+/g," ")}]),b({ok:!0,configPath:R,keys:_t(da(o))})}if(L.pathname==="/api/ssh-keys"&&C.method==="DELETE"){if(!R)return b({ok:!1,error:"No cloud config file was found in this checkout."},404);let d=await se(C),l=String(d.name??L.searchParams.get("name")??""),k=await Li(R,"utf8"),M=da(o),B=gc({configText:k,name:l,existingKeys:M});return await ls(R,B),lb(o,M.filter((X)=>X.name!==l.trim())),b({ok:!0,configPath:R,keys:_t(da(o))})}if(L.pathname==="/api/firewall"&&C.method==="GET")return b({configPath:R,alwaysOpen:[22,80,443],ports:sp(o)});if(L.pathname==="/api/firewall"&&C.method==="POST"){if(!R)return b({ok:!1,error:"No cloud config file was found in this checkout."},404);let d=await se(C),l=Number(d.port);if(!$a(l))return b({ok:!1,error:"Port must be an integer between 1 and 65535."},422);let k=sp(o),M=await Li(R,"utf8");try{await ls(R,ky(M,l,k))}catch(j){return b({ok:!1,error:j?.message??String(j)},422)}let B=us([...k,l]);pb(o,B);let X=d.apply===!1?null:await or(o,ye,`ufw allow ${l}/tcp`).catch((j)=>({ok:!1,error:String(j?.message??j)}));return b({ok:!0,configPath:R,ports:B,apply:X})}if(L.pathname==="/api/firewall"&&C.method==="DELETE"){if(!R)return b({ok:!1,error:"No cloud config file was found in this checkout."},404);let d=await se(C),l=Number(d.port??L.searchParams.get("port"));if(!$a(l))return b({ok:!1,error:"Port must be an integer between 1 and 65535."},422);let k=sp(o),M=await Li(R,"utf8");await ls(R,Ry(M,l,k));let B=us(k.filter((j)=>j!==l));pb(o,B);let X=d.apply===!1?null:await or(o,ye,`ufw delete allow ${l}/tcp`).catch((j)=>({ok:!1,error:String(j?.message??j)}));return b({ok:!0,configPath:R,ports:B,apply:X})}if(L.pathname==="/api/sites"&&C.method==="POST"){if(!R)return b({ok:!1,error:"No cloud config file was found in this checkout."},404);let d=await se(C),l=String(d.name??"").trim(),k=String(d.root??"").trim();if(!l||!k)return b({ok:!1,error:"Site name and root are required."},422);let M={deploy:d.deploy==="bucket"?"bucket":"server",root:k,path:String(d.path??"").trim()||void 0,domain:String(d.domain??"").trim()||void 0,build:String(d.build??"").trim()||void 0,start:String(d.start??"").trim()||void 0,port:d.port?Number(d.port):void 0,type:String(d.type??"").trim()||void 0};if(M.port!==void 0&&(!Number.isInteger(M.port)||M.port<1||M.port>65535))return b({ok:!1,error:"Port must be a number between 1 and 65535."},422);let B=await Li(R,"utf8"),X=kn({configText:B,name:l,root:M.root,domain:M.domain,path:M.path,deploy:M.deploy,build:M.build,start:M.start,port:M.port,type:M.type});return await ls(R,X),aA(o,l,Object.fromEntries(Object.entries(M).filter(([,j])=>j!==void 0))),Lt=await ps(o,ye),W.set(ye,Lt),b({ok:!0,configPath:R,site:l,data:Lt})}if(L.pathname==="/api/sites"&&C.method==="DELETE"){if(!R)return b({ok:!1,error:"No cloud config file was found in this checkout."},404);let d=await se(C),l=String(d.name??L.searchParams.get("name")??"").trim();if(!l||!o.sites?.[l])return b({ok:!1,error:`Site '${l}' was not found.`},404);let k=await Li(R,"utf8");return await ls(R,qy({configText:k,name:l})),delete o.sites[l],Lt=await ps(o,ye),W.set(ye,Lt),b({ok:!0,configPath:R,site:l,data:Lt})}if(L.pathname==="/api/sites"&&C.method==="PATCH"){if(!R)return b({ok:!1,error:"No cloud config file was found in this checkout."},404);let d=await se(C),l=String(d.name??"").trim(),k=o.sites?.[l];if(!l||!k)return b({ok:!1,error:`Site '${l}' was not found.`},404);if(Tn.role==="member"){let X=Cy(d);if(!X.ok)return b({ok:!1,error:X.error},403);let j=Ey({siteName:l,body:d,sites:o.sites??{},ownSites:Object.keys(Tn.sites)});if(!j.ok)return b({ok:!1,error:j.error},409)}if(d.port!==void 0&&d.port!==null&&d.port!==""&&(!Number.isInteger(Number(d.port))||Number(d.port)<1||Number(d.port)>65535))return b({ok:!1,error:"Port must be a number between 1 and 65535."},422);if(typeof d.domain==="string"&&d.domain.trim()&&!np(d.domain.trim()))return b({ok:!1,error:`Domain '${d.domain.trim()}' is not a valid hostname.`},422);let M=await Li(R,"utf8"),B=(X,j)=>{M=Gy({configText:M,siteName:l,key:X,valueText:j})};if(d.ssl!==void 0)B("ssl",Jy(d.ssl)),k.ssl=d.ssl;if(d.env!==void 0&&d.env&&typeof d.env==="object")B("env",Wy(d.env)),k.env=d.env;if(d.aliases!==void 0&&Array.isArray(d.aliases)){let X=d.aliases.map((j)=>String(j));B("aliases",Ky(X)),k.aliases=X.map((j)=>j.trim().toLowerCase()).filter(Boolean)}if(d.redirects!==void 0&&d.redirects&&typeof d.redirects==="object")B("redirects",Qy(d.redirects)),k.redirects=d.redirects;for(let X of["domain","path","build","start","type","root","php"])if(typeof d[X]==="string"&&d[X].trim())B(X,Hy(String(d[X]).trim())),k[X]=String(d[X]).trim();if(d.port!==void 0&&d.port!==null&&d.port!=="")B("port",String(Number(d.port))),k.port=Number(d.port);return await ls(R,M),Lt=await ps(o,ye),W.set(ye,Lt),b({ok:!0,configPath:R,site:l,data:Lt})}if(L.pathname==="/api/sites/deploy"&&C.method==="POST"){let d=await se(C),l=String(d.name??"").trim();if(!l||!o.sites?.[l])return b({ok:!1,error:`Site '${l}' was not found.`},404);if(d.confirm!==l)return b({ok:!1,error:`Type "${l}" to deploy this site.`},409);let k=le(a,String(ye));await new ss(rt).run(new Da,{...k,artifactRoot:t}),dd(rt,k,Lt??{});let M=ar(rt,{scope:k,desiredConfigHash:a.project.desiredConfigHash});if(M.decision.outcome==="block")return b({ok:!1,error:`Deployment blocked by security policy: ${M.decision.explanation}`,securityReview:M},409);let B={id:`deploy:${l}`,label:`Deploy ${l}`,description:`Deploy the ${l} site for ${ye}.`,command:["deploy","--env",ye,"--site",l,"--yes"],mutates:!0},X=await ao({controlPlane:a,environment:ye,actor:ue,kind:"dashboard.site.deploy",resourceSlug:l,input:{site:l},execute:()=>ap(B,{cwd:t,cliEntry:i})});return b({...X.result,controlPlaneOperation:X.operation,securityReview:M})}if(L.pathname==="/api/actions")return b(wb(ye));if(L.pathname==="/api/server/operations")return b(Hr(o,Lt));if(L.pathname==="/api/runtime/workloads"&&C.method==="GET"){let d=await Ii(o,ye);return b(d)}if(L.pathname==="/api/runtime/logs"&&C.method==="GET"){let d=String(L.searchParams.get("workload")??"");if(!d)return b({ok:!1,error:"A workload query parameter is required."},422);let l=Math.min(1000,Math.max(1,Number(L.searchParams.get("limit"))||200));try{return b(await new Se(o,ye).logs(d,{limit:l}))}catch(k){return b({ok:!1,error:String(k?.message??k)},404)}}if(L.pathname==="/api/runtime/log-sessions"&&C.method==="POST"){let d=await se(C),l=String(d.workloadId??"");if(!l)return b({ok:!1,error:"A workloadId is required."},422);let k=await Ii(o,ye),M=k.workloads.find((j)=>j.id===l);if(!M)return b({ok:!1,error:"Workload was not found in the current project and environment."},404);if(!M.capabilities.logs.supported)return b({ok:!1,error:M.capabilities.logs.reason??"Logs are unsupported for this workload."},409);let B=new Se(o,ye,{inventory:async()=>k}),X=Yt.create("logs",l);return(async()=>{let j=new Date(Date.now()-Math.min(3600000,Math.max(1000,Number(d.sinceMs)||60000)));try{for(let Z=0;Z<200&&!Yt.signal(X.id)?.aborted;Z++){let fe=await B.logs(l,{limit:Math.min(500,Math.max(1,Number(d.limit)||200)),since:j});for(let pe of fe.lines)if(Yt.append(X.id,`${pe.timestamp?`${pe.timestamp} `:""}${pe.message}
498
- `),pe.timestamp)j=new Date(Math.max(j.getTime(),new Date(pe.timestamp).getTime()+1));await Bun.sleep(3000)}if(!Yt.signal(X.id)?.aborted)Yt.close(X.id,"complete")}catch(Z){Yt.append(X.id,Z instanceof Error?Z.message:String(Z),"stderr"),Yt.close(X.id,"failed",Z instanceof Error?Z.message:String(Z))}})(),b({ok:!0,session:X,streamUrl:`/api/runtime/log-stream?id=${encodeURIComponent(X.id)}&workload=${encodeURIComponent(l)}`},201)}if((L.pathname==="/api/runtime/log-stream"||L.pathname==="/api/runtime/exec-stream")&&C.method==="GET"){let d=String(L.searchParams.get("id")??""),l=String(L.searchParams.get("workload")??""),k=Number(C.headers.get("last-event-id")??L.searchParams.get("after")??0)||0,M=Yt.read(d,l,k),B=L.pathname.includes("exec")?"exec":"logs";if(!M||M.kind!==B)return b({ok:!1,error:"Runtime stream was not found in this workload scope."},404);return XT(Yt,M,k,C.signal)}if((L.pathname==="/api/runtime/log-sessions"||L.pathname==="/api/runtime/exec-sessions")&&C.method==="DELETE"){let d=await se(C),l=Yt.cancel(String(d.id??""),String(d.workloadId??""));if(!l)return b({ok:!1,error:"Runtime stream was not found in this workload scope."},404);return b({ok:!0,session:l})}if(L.pathname==="/api/runtime/exec-sessions"&&C.method==="POST"){let d=await se(C),l=String(d.workloadId??""),k=await Ii(o,ye),M=k.workloads.find((Z)=>Z.id===l);if(!M)return b({ok:!1,error:"Workload was not found in the current project and environment."},404);let B=jt.resolveSession(C),X=new Se(o,ye,{inventory:async()=>k}),j=Yt.create("exec",l);return ao({controlPlane:a,environment:ye,actor:ue,kind:"runtime.exec",resourceSlug:M.links.service,input:{workloadId:l,provider:M.provider,preset:d.preset?String(d.preset):null,freeForm:!!String(d.command??"").trim()},execute:()=>X.exec({workloadId:l,preset:["process","sockets","filesystem"].includes(String(d.preset))?String(d.preset):void 0,command:typeof d.command==="string"?d.command:void 0,confirm:String(d.confirm??""),recentAuth:!Pe||!!B&&Ie.isRecentlyAuthenticated(B)})}).then(({result:Z,operation:fe})=>{if(Yt.append(j.id,`operation ${fe.id}
499
- `,"system"),Z.stdout)Yt.append(j.id,Z.stdout,"stdout");if(Z.stderr)Yt.append(j.id,Z.stderr,"stderr");Yt.close(j.id,Z.ok?"complete":"failed",Z.error)}).catch((Z)=>{let fe=Z instanceof Error?Z.message:String(Z);Yt.append(j.id,fe,"stderr"),Yt.close(j.id,"failed",fe)}),b({ok:!0,session:j,streamUrl:`/api/runtime/exec-stream?id=${encodeURIComponent(j.id)}&workload=${encodeURIComponent(l)}`},202)}if(L.pathname==="/api/runtime/files/read"&&C.method==="POST"){let d=await se(C),l=await Ii(o,ye),k=jt.resolveSession(C),M=await new Se(o,ye,{inventory:async()=>l}).readFile({workloadId:String(d.workloadId??""),path:String(d.path??""),confirm:String(d.confirm??""),recentAuth:!Pe||!!k&&Ie.isRecentlyAuthenticated(k)});return b(M,M.ok?200:409)}if(L.pathname==="/api/runtime/files/write"&&C.method==="POST"){let d=await se(C),l=await Ii(o,ye),k=String(d.workloadId??""),M=l.workloads.find((Z)=>Z.id===k);if(!M)return b({ok:!1,error:"Workload was not found in the current project and environment."},404);let B=jt.resolveSession(C),X=new Se(o,ye,{inventory:async()=>l}),j=await ao({controlPlane:a,environment:ye,actor:ue,kind:"runtime.file.write",resourceSlug:M.links.service,input:{workloadId:k,provider:M.provider,path:String(d.path??""),bytes:Buffer.from(String(d.contentBase64??""),"base64").byteLength},execute:()=>X.writeFile({workloadId:k,path:String(d.path??""),contentBase64:String(d.contentBase64??""),confirm:String(d.confirm??""),recentAuth:!Pe||!!B&&Ie.isRecentlyAuthenticated(B)})});return b({...j.result,controlPlaneOperation:j.operation},j.result.ok?200:409)}if(L.pathname==="/api/runtime/operations"&&C.method==="POST"){let d=await se(C),l=String(d.workloadId??""),k=String(d.action??"");if(!l||!["start","stop","restart","redeploy","scale","inspect"].includes(k))return b({ok:!1,error:"A valid workloadId and lifecycle action are required."},422);let M=await Ii(o,ye),B=M.workloads.find((fe)=>fe.id===l);if(!B)return b({ok:!1,error:"Workload was not found in the current project and environment."},404);let X=jt.resolveSession(C),j=new Se(o,ye,{inventory:async()=>M}),Z=await ao({controlPlane:a,environment:ye,actor:ue,kind:`runtime.${k}`,resourceSlug:B.links.service,input:{workloadId:l,provider:B.provider,action:k,replicas:d.replicas==null?null:Number(d.replicas)},execute:()=>j.run({workloadId:l,action:k,replicas:d.replicas==null?void 0:Number(d.replicas),confirm:String(d.confirm??""),recentAuth:!Pe||!!X&&Ie.isRecentlyAuthenticated(X)})});return b({...Z.result,controlPlaneOperation:Z.operation},Z.result.ok?200:409)}if(L.pathname.startsWith("/api/protection")){let d=ue.role==="admin"||Ga(ue,"security:read"),l=ue.role==="admin"||Ga(ue,"security:manage");if(!d)return b({ok:!1,error:"Protection controls require security:read."},403);let{ProtectionControlStore:k,describePosture:M}=await import("./chunk-ce1qnjs2.js"),B=new k(a.store),X=()=>{if(!l)throw Error("Changing protection controls requires security:manage.")};if(L.pathname==="/api/protection"&&C.method==="GET"){let j=B.current();return b({ok:!0,posture:M(j),controls:j,raw:B.raw()})}if(L.pathname==="/api/protection/attack-mode"&&C.method==="POST"){X();let j=await se(C);if(j.enabled===!1)return b({ok:!0,disabled:B.disableAttackMode()});return b({ok:!0,control:B.enableAttackMode({hours:j.hours==null?void 0:Number(j.hours),reason:String(j.reason??"Enabled from the dashboard."),actorId:Ne(ue).actor?.id})})}if(L.pathname==="/api/protection/pause"&&C.method==="POST"){X();let j=await se(C);if(j.enabled===!1)return b({ok:!0,resumed:B.resumeMitigations()});return b({ok:!0,control:B.pauseMitigations({hours:j.hours==null?void 0:Number(j.hours),reason:String(j.reason??""),actorId:Ne(ue).actor?.id})})}if(L.pathname==="/api/protection/ip-rules"&&C.method==="GET")return b({ok:!0,ipRules:B.current().ipRules});if(L.pathname==="/api/protection/ip-rules"&&(C.method==="POST"||C.method==="DELETE")){X();let j=await se(C),Z=j.list==="allow"?"allow":"block",fe=C.method==="POST"?B.addIpRule(Z,String(j.cidr??"")):B.removeIpRule(Z,String(j.cidr??""));return b({ok:!0,ipRules:fe})}return b({ok:!1,error:"Protection endpoint was not found."},404)}if(L.pathname.startsWith("/api/spend/")||L.pathname==="/api/usage"){let d=await Ab(),{store:l,service:k,gate:M}=d,B=ue.role==="admin"||Ga(ue,"billing:read"),X=ue.role==="admin"||Ga(ue,"billing:manage");if(!B)return b({ok:!1,error:"Spend data requires the billing:read capability."},403);let j=a.environments.get(ye),Z={organizationId:a.organization.id,projectId:a.project.id,environmentId:j?.id},fe=()=>{if(!X)throw Error("Changing a budget requires the billing:manage capability.")};if(L.pathname==="/api/usage"&&C.method==="GET")return b({ok:!0,...k.usageReport({organizationId:Z.organizationId,projectId:Z.projectId,period:L.searchParams.get("period")??"monthly",timezone:L.searchParams.get("timezone")??void 0})});if(L.pathname==="/api/spend/budgets"&&C.method==="GET")return b({ok:!0,budgets:l.listBudgets({organizationId:Z.organizationId,projectId:Z.projectId}).map((pe)=>({...pe,status:k.status(pe)}))});if(L.pathname==="/api/spend/budgets"&&C.method==="POST"){fe();let pe=await se(C),He=String(pe.scope??"project"),ve=l.createBudget({organizationId:Z.organizationId,projectId:He==="organization"?void 0:Z.projectId,environmentId:He==="environment"?Z.environmentId:void 0,name:String(pe.name??"").trim(),period:pe.period??"monthly",timezone:pe.timezone?String(pe.timezone):void 0,softLimitCents:pe.softLimitCents==null?void 0:Math.round(Number(pe.softLimitCents)),hardLimitCents:pe.hardLimitCents==null?void 0:Math.round(Number(pe.hardLimitCents)),graceSeconds:pe.graceSeconds==null?void 0:Number(pe.graceSeconds),dryRun:pe.dryRun!==!1});return b({ok:!0,budget:ve})}if(L.pathname==="/api/spend/budgets"&&C.method==="PATCH"){fe();let pe=await se(C),He=String(pe.id??""),ve=l.getBudget(He);if(!ve||ve.organizationId!==Z.organizationId)return b({ok:!1,error:"Budget was not found."},404);return b({ok:!0,budget:l.updateBudget(He,{softLimitCents:pe.softLimitCents==null?ve.softLimitCents:Math.round(Number(pe.softLimitCents)),hardLimitCents:pe.hardLimitCents==null?ve.hardLimitCents:Math.round(Number(pe.hardLimitCents)),enabled:pe.enabled==null?ve.enabled:pe.enabled===!0,dryRun:pe.dryRun==null?ve.dryRun:pe.dryRun===!0},pe.expectedVersion==null?void 0:Number(pe.expectedVersion))})}if(L.pathname==="/api/spend/budgets"&&C.method==="DELETE"){fe();let pe=await se(C),He=String(pe.id??""),ve=l.getBudget(He);if(!ve||ve.organizationId!==Z.organizationId)return b({ok:!1,error:"Budget was not found."},404);let Fe=M.closeBudget(He);return l.deleteBudget(He),b({ok:!0,deleted:!0,lifted:Fe})}if(L.pathname==="/api/spend/check"&&C.method==="POST"){fe();let pe=await se(C),{SpendRunner:He}=await import("./chunk-knzje4ka.js"),ve=new He({controlPlane:a.store,store:l,alerts:We});if(pe.apply!==!0){let we=l.budgetsForScope(Z.organizationId,Z.projectId,Z.environmentId);return b({ok:!0,applied:!1,preview:we.map((Ae)=>k.status(Ae))})}let Fe=await ve.run({...Z,environmentKind:j?.kind});return b({ok:!0,applied:!0,result:Fe})}if(L.pathname==="/api/spend/enforcement"&&C.method==="GET")return b({ok:!0,enforcement:M.listUnder({organizationId:Z.organizationId})});if(L.pathname==="/api/spend/release"&&C.method==="POST"){fe();let pe=await se(C),He=M.close(String(pe.budgetId??""),pe.action);return b({ok:He,released:He,note:He?"The next spend cycle re-applies this if spend is still over the threshold.":"That action was not in force."})}if(L.pathname==="/api/spend/anomalies"&&C.method==="GET")return b({ok:!0,anomalies:l.listAnomalies({organizationId:Z.organizationId,projectId:Z.projectId,unacknowledgedOnly:L.searchParams.get("unacknowledged")==="true"})});if(L.pathname==="/api/spend/anomalies/acknowledge"&&C.method==="POST"){fe();let pe=await se(C);return b({ok:!0,acknowledged:l.acknowledgeAnomaly(String(pe.id??""))})}return b({ok:!1,error:"Spend endpoint was not found."},404)}if(L.pathname.startsWith("/api/health/")||L.pathname.startsWith("/api/alerts")||L.pathname.startsWith("/api/notifications/")){let d=a.environments.get(ye),l=a.store.listResources(a.project.id,d?.id),k=ue.role==="admin"||!!d&&la(ue,d.id,"runtime:read")?l:l.filter((j)=>Sr(ue,j.id,"runtime:read")),M=(j)=>!j||k.some((Z)=>Z.id===j),B=(j)=>{if(!j)return;let Z=l.find((fe)=>fe.id===j||fe.slug===j);if(!Z)throw Error("Alert resource was not found.");if(!M(Z.id))throw Error("Alert resource is outside your authorized scope.");return Z.id},X=Ne(ue).actor;if(L.pathname==="/api/health/checks"&&C.method==="GET")return b({ok:!0,checks:We.listHealthChecks(a.project.id,d?.id).filter((j)=>M(j.resourceId)).map((j)=>({...j,results:We.listHealthResults(j.id,20)}))});if(L.pathname==="/api/health/checks"&&C.method==="POST"){let j=await se(C),Z=String(j.kind??"http");if(Z==="command"&&ue.role!=="admin")return b({ok:!1,error:"Command health checks require an administrator."},403);let fe={method:String(j.config?.method??"GET").toUpperCase().slice(0,10),path:j.config?.path?String(j.config.path).slice(0,500):void 0,port:j.config?.port==null?void 0:Number(j.config.port),command:Array.isArray(j.config?.command)?j.config.command.map(String).slice(0,20):void 0,expectedStatuses:Array.isArray(j.config?.expectedStatuses)?j.config.expectedStatuses.map(Number).filter(Number.isInteger).slice(0,20):void 0,expectedBody:j.config?.expectedBody?String(j.config.expectedBody).slice(0,500):void 0};return b({ok:!0,check:We.createHealthCheck({projectId:a.project.id,environmentId:d?.id,resourceId:B(j.resourceId??j.resource),name:String(j.name??""),kind:Z,target:String(j.target??""),config:fe,intervalSeconds:Number(j.intervalSeconds)||60,timeoutSeconds:Number(j.timeoutSeconds)||10,failureThreshold:Number(j.failureThreshold)||3,recoveryThreshold:Number(j.recoveryThreshold)||2,regions:Array.isArray(j.regions)?j.regions.map(String):["local"],enabled:j.enabled!==!1})},201)}if(L.pathname==="/api/health/checks"&&C.method==="PATCH"){let j=await se(C),Z=We.getHealthCheck(String(j.id??""));if(!Z||!M(Z.resourceId))return b({ok:!1,error:"Health check was not found."},404);return b({ok:!0,check:We.setHealthCheckEnabled(Z.id,j.enabled!==!1)})}if(L.pathname==="/api/health/checks/test"&&C.method==="POST"){let j=await se(C),Z=We.getHealthCheck(String(j.id??""));if(!Z||!M(Z.resourceId))return b({ok:!1,error:"Health check was not found."},404);return b({ok:!0,productionIncidentCreated:!1,result:await new Ue(We).probe(Z)})}if(L.pathname==="/api/health/checks/run"&&C.method==="POST"){let j=await se(C),Z=We.getHealthCheck(String(j.id??""));if(!Z||!M(Z.resourceId))return b({ok:!1,error:"Health check was not found."},404);let fe=await new Ue(We).runAndEvaluate(Z),pe=[];for(let He of fe.evaluations.filter((ve)=>ve.notify&&ve.alert)){let ve=En.enqueue(a.organization.id,He.alert,He.transition);pe.push(...await En.deliverAll(ve))}return b({ok:!0,...fe,deliveries:pe})}if(L.pathname==="/api/alerts/rules"&&C.method==="GET")return b({ok:!0,rules:We.listRules(a.project.id,d?.id).filter((j)=>M(j.resourceId))});if(L.pathname==="/api/alerts/rules"&&C.method==="POST"){let j=await se(C),Z=j.healthCheckId?We.getHealthCheck(String(j.healthCheckId)):void 0;if(j.healthCheckId&&(!Z||!M(Z.resourceId)))return b({ok:!1,error:"Health check was not found."},404);return b({ok:!0,rule:We.createRule({projectId:a.project.id,environmentId:d?.id,resourceId:B(j.resourceId??j.resource)??Z?.resourceId,healthCheckId:Z?.id,name:String(j.name??""),signal:String(j.signal??(Z?"health":"")),operator:String(j.operator??(Z?"unhealthy":"gt")),threshold:j.threshold==null?void 0:Number(j.threshold),recoveryThreshold:j.recoveryThreshold==null?void 0:Number(j.recoveryThreshold),windowMs:Number(j.windowMs)||300000,consecutive:Number(j.consecutive)||Z?.failureThreshold||3,recoveryConsecutive:Number(j.recoveryConsecutive)||Z?.recoveryThreshold||2,noDataPolicy:["ignore","pending","firing"].includes(String(j.noDataPolicy))?j.noDataPolicy:"pending",severity:["info","warning","critical"].includes(String(j.severity))?j.severity:"warning",groupBy:Array.isArray(j.groupBy)?j.groupBy.map(String):[],labels:j.labels&&typeof j.labels==="object"?j.labels:{},enabled:j.enabled!==!1})},201)}if(L.pathname==="/api/alerts/rules"&&C.method==="PATCH"){let j=await se(C),Z=We.getRule(String(j.id??""));if(!Z||!M(Z.resourceId))return b({ok:!1,error:"Alert rule was not found."},404);return b({ok:!0,rule:We.setRuleEnabled(Z.id,j.enabled!==!1)})}if(L.pathname==="/api/alerts/evaluate"&&C.method==="POST")return b({ok:!0,...await hp(d?.id)});if(L.pathname==="/api/alerts"&&C.method==="GET")return b({ok:!0,alerts:We.listAlerts(a.project.id,{environmentId:d?.id,states:L.searchParams.getAll("state").length?L.searchParams.getAll("state"):void 0,limit:Number(L.searchParams.get("limit"))||200}).filter((j)=>M(j.resourceId)).map((j)=>({...j,deliveries:We.listDeliveries({alertId:j.id,limit:50})}))});if(L.pathname==="/api/alerts/action"&&C.method==="POST"){let j=await se(C),Z=We.getAlert(String(j.id??""));if(!Z||!M(Z.resourceId))return b({ok:!1,error:"Alert was not found."},404);let fe=String(j.action??"");if(fe==="acknowledge")return b({ok:!0,alert:We.acknowledge(Z.id,X?.id??"")});if(fe==="assign")return b({ok:!0,alert:We.assign(Z.id,j.ownerActorId==="me"?X?.id:j.ownerActorId?String(j.ownerActorId):void 0,X?.id)});if(fe==="silence"){if(ue.role!=="admin")return b({ok:!1,error:"Silencing production alerts requires an administrator."},403);let pe=jt.resolveSession(C);if(Pe&&(!pe||!Ie.isRecentlyAuthenticated(pe)))return b({ok:!1,error:"Recent authentication is required to silence alerts.",stepUpRequired:!0},401);return b({ok:!0,alert:We.silenceAlert(Z.id,String(j.until??""),X?.id)})}return b({ok:!1,error:"Action must be acknowledge, assign, or silence."},422)}if(L.pathname==="/api/alerts/silences"&&C.method==="POST"){let j=await se(C);return b({ok:!0,id:We.createSilence({projectId:a.project.id,environmentId:d?.id,resourceId:B(j.resourceId??j.resource),matcher:j.matcher,reason:String(j.reason??""),startsAt:String(j.startsAt??new Date().toISOString()),endsAt:String(j.endsAt??""),timezone:String(j.timezone??"UTC"),actorId:X?.id})},201)}if(L.pathname==="/api/notifications/channels"&&C.method==="GET")return b({ok:!0,channels:We.listChannels(a.organization.id)});if(L.pathname==="/api/notifications/channels"&&C.method==="POST"){let j=await se(C),Z=String(j.kind??""),fe=Z==="email"?{to:j.config?.to,from:j.config?.from}:Z==="telegram"?{chatId:String(j.config?.chatId??"")}:{};return b({ok:!0,channel:We.createChannel({organizationId:a.organization.id,name:String(j.name??""),kind:Z,config:fe,credential:j.credential?String(j.credential):void 0,actorId:X?.id})},201)}if(L.pathname==="/api/notifications/channels"&&C.method==="PATCH"){let j=await se(C),Z=String(j.id??"");if(j.credential)return b({ok:!0,channel:We.rotateChannel(Z,String(j.credential))});let fe=String(j.status??"paused");if(!["active","paused","disabled"].includes(fe))return b({ok:!1,error:"Channel status must be active, paused, or disabled."},422);return b({ok:!0,channel:We.setChannelStatus(Z,fe)})}if(L.pathname==="/api/notifications/channels/test"&&C.method==="POST"){let j=await se(C);return b({ok:!0,productionIncidentCreated:!1,result:await En.testChannel(String(j.id??""))})}if(L.pathname==="/api/notifications/routes"&&C.method==="GET")return b({ok:!0,routes:We.listRoutes(a.organization.id)});if(L.pathname==="/api/notifications/routes"&&C.method==="POST"){let j=await se(C),Z=Array.isArray(j.channelIds)?j.channelIds.map(String):[];if(Z.some((fe)=>We.getChannel(fe)?.organizationId!==a.organization.id))return b({ok:!1,error:"Route contains an unavailable channel."},422);return b({ok:!0,route:We.createRoute({organizationId:a.organization.id,name:String(j.name??""),priority:Number(j.priority)||0,matcher:j.matcher&&typeof j.matcher==="object"?j.matcher:{},channelIds:Z,quietHours:j.quietHours,groupWaitSeconds:Number(j.groupWaitSeconds)||30,reminderSeconds:j.reminderSeconds==null?void 0:Number(j.reminderSeconds),escalation:Array.isArray(j.escalation)?j.escalation:[],template:j.template?String(j.template):void 0,rateLimitPerMinute:Number(j.rateLimitPerMinute)||60,enabled:j.enabled!==!1})},201)}if(L.pathname==="/api/notifications/routes"&&C.method==="PATCH"){let j=await se(C),Z=We.getRoute(String(j.id??""));if(!Z||Z.organizationId!==a.organization.id)return b({ok:!1,error:"Notification route was not found."},404);return b({ok:!0,route:We.setRouteEnabled(Z.id,j.enabled!==!1)})}if(L.pathname==="/api/notifications/routes/preview"&&C.method==="POST"){let j=await se(C),fe=(j.alertId?We.getAlert(String(j.alertId)):void 0)??{id:"preview",ruleId:"preview",projectId:a.project.id,environmentId:d?.id,resourceId:B(j.resourceId??j.resource),dedupKey:"preview",groupKey:String(j.groupKey??"default"),state:"firing",severity:["info","warning","critical"].includes(String(j.severity))?j.severity:"warning",title:String(j.title??"Rule preview"),evidence:{},failureCount:1,recoveryCount:0,occurrenceCount:1,firstSeenAt:new Date().toISOString(),lastSeenAt:new Date().toISOString(),firingAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return b({ok:!0,productionIncidentCreated:!1,matches:En.preview(a.organization.id,fe,String(j.eventType??"firing")).map((pe)=>({route:pe.route,channels:pe.channels,quiet:pe.quiet}))})}if(L.pathname==="/api/notifications/deliveries"&&C.method==="GET")return b({ok:!0,deliveries:We.listDeliveries({alertId:L.searchParams.get("alertId")??void 0,states:L.searchParams.getAll("state"),limit:Number(L.searchParams.get("limit"))||200})});if(L.pathname==="/api/notifications/deliveries/retry"&&C.method==="POST"){let j=await se(C),Z=We.getDelivery(String(j.id??""));if(!Z)return b({ok:!1,error:"Delivery was not found."},404);return We.updateDelivery(Z.id,{state:"retrying",attempt:Math.max(0,Z.attempt-1),nextAttemptAt:new Date().toISOString()}),b({ok:!0,delivery:await En.deliver(Z.id)})}}if(L.pathname.startsWith("/api/jobs")||L.pathname.startsWith("/api/workers")){let d=a.environments.get(ye),l=a.store.listResources(a.project.id,d?.id),M=ue.role==="admin"||!!d&&la(ue,d.id,"automation:read")?l:l.filter((we)=>Sr(ue,we.id,"automation:read")),B=(we)=>!we||M.some((Ae)=>Ae.id===we),X=Ne(ue).actor,j=W.get(ye)??D,Z=Hr(o,j),fe=Z.filter((we)=>!we.danger&&["scheduler","backup","worker"].includes(we.group)),pe=H(o),He=()=>{let we=jt.resolveSession(C);return!Pe||!!we&&Ie.isRecentlyAuthenticated(we)},ve=(we)=>{if(!we||typeof we!=="object"||Array.isArray(we))return{};let Ae=Object.entries(we).slice(0,50);if(Ae.some(([,et])=>typeof et!=="string"||!/^(?:secret|ssm|arn|env):\/\//.test(et)))throw Error("Job payload values must be secret or environment references, never inline values.");return Object.fromEntries(Ae)},Fe=(we,Ae,et)=>a.store.appendEvent({organizationId:a.organization.id,projectId:a.project.id,resourceId:et,actorId:X?.id,type:`job.${we}`,payload:Ae});if(L.pathname==="/api/jobs/preview"&&C.method==="POST"){let we=await se(C);try{return b({ok:!0,productionExecutionCreated:!1,preview:ct(String(we.expression??""),String(we.timezone??"UTC"),new Date(we.from?String(we.from):Date.now()),Number(we.count)||5)})}catch(Ae){return b({ok:!1,error:Ae instanceof Error?Ae.message:"Schedule preview could not be generated.",productionExecutionCreated:!1},422)}}if(L.pathname==="/api/jobs"&&C.method==="GET")return b({ok:!0,jobs:br.list(a.project.id,{environmentId:d?.id}).filter((we)=>B(we.resourceId)).map((we)=>({...we,preview:ct(we.normalizedExpression,we.timezone,new Date,5),capability:ti(we),lastExecution:br.listExecutions(we.id,1)[0]}))});if(L.pathname==="/api/jobs"&&C.method==="POST"){let we=await se(C),Ae=String(we.provider??(pe==="serverless"?"eventbridge":"server")),et=pe==="serverless"?"eventbridge":"server";if(Ae!==et)return b({ok:!1,error:`${pe} environments accept ${et} schedules through this adapter.`},422);let ut=we.operationId?String(we.operationId):void 0;if(Ae==="server"&&(!ut||!fe.some((Xt)=>Xt.id===ut)))return b({ok:!1,error:"Server jobs require an allowlisted operation target."},422);let St=ti({provider:Ae,expression:String(we.expression??""),flexibleMinutes:Number(we.flexibleMinutes)||0,missedRunPolicy:we.missedRunPolicy==="catch_up"?"catch_up":"skip",overlapPolicy:["allow","forbid","replace"].includes(String(we.overlapPolicy))?we.overlapPolicy:"forbid"});if(!St.supported)return b({ok:!1,error:St.notes.join(" ")},422);let bn=we.resourceId?l.find((Xt)=>Xt.id===we.resourceId||Xt.slug===we.resourceId):void 0;if(we.resourceId&&(!bn||!B(bn.id)))return b({ok:!1,error:"Job resource was not found."},404);try{let Xt=Ae==="server"?{kind:"dashboard_operation",operationId:ut}:{kind:"serverless_scheduler",action:"run"},bo=br.create({organizationId:a.organization.id,projectId:a.project.id,environmentId:d?.id,resourceId:bn?.id,name:String(we.name??""),provider:Ae,expression:String(we.expression??""),timezone:String(we.timezone??"UTC"),startsAt:we.startsAt?String(we.startsAt):void 0,endsAt:we.endsAt?String(we.endsAt):void 0,flexibleMinutes:Number(we.flexibleMinutes)||0,target:Xt,payloadRefs:ve(we.payloadRefs),missedRunPolicy:we.missedRunPolicy==="catch_up"?"catch_up":"skip",overlapPolicy:["allow","forbid","replace"].includes(String(we.overlapPolicy))?we.overlapPolicy:"forbid",retryPolicy:{maxAttempts:Number(we.maxAttempts)||3,backoffSeconds:Number(we.backoffSeconds)||30,deadLetterRef:we.deadLetterRef?String(we.deadLetterRef):void 0},timeoutSeconds:Number(we.timeoutSeconds)||900,enabled:we.enabled!==!1,origin:"managed",ownerActorId:X?.id,observedState:{},reconciliationStatus:"pending"});return Fe("created",{jobId:bo.id,provider:bo.provider,expression:bo.normalizedExpression},bo.resourceId),b({ok:!0,job:bo,capability:St},201)}catch(Xt){return b({ok:!1,error:Xt instanceof Error?Xt.message:"Scheduled job could not be created."},422)}}if(L.pathname==="/api/jobs"&&C.method==="PATCH"){let we=await se(C),Ae=br.get(String(we.id??""));if(!Ae||!B(Ae.resourceId))return b({ok:!1,error:"Scheduled job was not found."},404);if(Ae.origin==="config")return b({ok:!1,error:"Config-defined schedules must be edited in cloud.config.ts and reconciled."},409);let et=we.missedRunPolicy==null?void 0:String(we.missedRunPolicy),ut=we.overlapPolicy==null?void 0:String(we.overlapPolicy);if(et&&!["skip","catch_up"].includes(et))return b({ok:!1,error:"Missed-run policy must be skip or catch_up."},422);if(ut&&!["allow","forbid","replace"].includes(ut))return b({ok:!1,error:"Overlap policy must be allow, forbid, or replace."},422);try{let St=br.updateSchedule(Ae.id,{expression:we.expression?String(we.expression):void 0,timezone:we.timezone?String(we.timezone):void 0,missedRunPolicy:et,overlapPolicy:ut,timeoutSeconds:we.timeoutSeconds==null?void 0:Number(we.timeoutSeconds)});return Fe("updated",{jobId:St.id,expression:St.normalizedExpression,version:St.version},St.resourceId),b({ok:!0,job:St})}catch(St){return b({ok:!1,error:St instanceof Error?St.message:"Scheduled job could not be updated."},422)}}if(L.pathname==="/api/jobs/action"&&C.method==="POST"){let we=await se(C),Ae=br.get(String(we.id??""));if(!Ae||!B(Ae.resourceId))return b({ok:!1,error:"Scheduled job was not found."},404);let et=String(we.action??"");if(et==="run"){let ut=fp.enqueue(Ae,{trigger:"manual",actorId:X?.id});return Fe("run_queued",{jobId:Ae.id,executionId:ut.id},Ae.resourceId),b({ok:!0,execution:ut},202)}if(["disable","delete"].includes(et)&&d?.kind==="production"){if(String(we.confirm??"")!==et)return b({ok:!1,error:`Type "${et}" to confirm this production change.`},409);if(!He())return b({ok:!1,error:"Recent authentication is required for this production change.",stepUpRequired:!0},401)}if(et==="enable"||et==="disable"){let ut=br.setEnabled(Ae.id,et==="enable");return Fe(et==="enable"?"enabled":"disabled",{jobId:Ae.id},Ae.resourceId),b({ok:!0,job:ut})}if(et==="delete")try{return br.remove(Ae.id),Fe("deleted",{jobId:Ae.id,name:Ae.name},Ae.resourceId),b({ok:!0,deleted:Ae.id})}catch(ut){return b({ok:!1,error:ut instanceof Error?ut.message:"Scheduled job could not be deleted."},409)}return b({ok:!1,error:"Action must be run, enable, disable, or delete."},422)}if(L.pathname==="/api/jobs/history"&&C.method==="GET"){let we=br.get(String(L.searchParams.get("jobId")??""));if(!we||!B(we.resourceId))return b({ok:!1,error:"Scheduled job was not found."},404);return b({ok:!0,executions:br.listExecutions(we.id,Number(L.searchParams.get("limit"))||100).map((Ae)=>({...Ae,logs:Ae.operationId?At.logs(Ae.operationId,{limit:500}):[]}))})}if(L.pathname==="/api/jobs/reconcile"&&C.method==="POST"){if(!d)return b({ok:!1,error:"Environment was not found."},404);let we=Kr(br,o,{organization:a.organization,project:a.project,environment:d,resources:l});return Fe("reconciled",we),b({ok:!0,reconciliation:we})}if(L.pathname==="/api/workers"&&C.method==="GET"){let we=Array.isArray(j.workersDetail??j.workers)?j.workersDetail??j.workers:[];return b({ok:!0,workers:br.listWorkers(a.project.id,d?.id).filter((Ae)=>B(Ae.resourceId)).map((Ae)=>{let et=we.find((ut)=>ut.name===Ae.name||ut.site===Ae.target.site);return et?{...Ae,observedState:{...Ae.observedState,status:et.status??"configured",currentJob:et.currentJob??null,failures:Number(et.failed??et.failures)||0,processed:Number(et.processed)||0}}:Ae})})}if(L.pathname==="/api/workers/action"&&C.method==="POST"){let we=await se(C),Ae=br.getWorker(String(we.id??""));if(!Ae||!B(Ae.resourceId))return b({ok:!1,error:"Worker was not found."},404);let et=String(we.action??"");if(et==="restart"){if(String(we.confirm??"")!==Ae.name)return b({ok:!1,error:`Type "${Ae.name}" to restart this worker.`},409);let ut=Z.find((Xt)=>Xt.id===Ae.target.operationId);if(!ut)return b({ok:!1,error:"The allowlisted worker restart operation is unavailable."},409);let St=await qr(o,ye,ut),bn=br.reconcileWorker(Ae.id,St.ok?"in_sync":"unavailable",{...Ae.observedState,lastRestartAt:new Date().toISOString(),command:St.command??null,error:St.error??St.stderr??null});return Fe("worker_restarted",{workerId:Ae.id,ok:St.ok},Ae.resourceId),b({...St,worker:bn},St.ok?200:409)}if(et==="scale")return b({ok:!1,error:Ae.provider==="systemd"?"Systemd worker scale is config-managed; edit the worker definition and reconcile.":"This provider does not expose safe worker scaling through the current adapter."},422);return b({ok:!1,error:"Action must be restart or scale."},422)}}if(L.pathname.startsWith("/api/telemetry/")){let d=a.environments.get(ye),l=new Ye(a.store),k=a.store.listResources(a.project.id,d?.id),M=["/api/telemetry/query","/api/telemetry/tail","/api/telemetry/export","/api/telemetry/saved-queries","/api/telemetry/refresh"].includes(L.pathname)?"runtime:logs":"runtime:read",B=ue.role==="admin"||!!d&&la(ue,d.id,M),X=B?k:k.filter((ve)=>Sr(ue,ve.id,M)),j=(ve)=>Zy(X,B,ve),Z=(ve)=>{let Fe=new Date,we={"1h":3600000,"6h":21600000,"24h":86400000,"7d":604800000,"30d":2592000000},Ae=String(ve.to??Fe.toISOString()),et=String(ve.from??new Date(new Date(Ae).getTime()-(we[String(ve.range??"1h")]??we["1h"])).toISOString()),ut=(bn)=>{let Xt=(Array.isArray(bn)?bn:String(bn??"").split(",")).map(String).filter(Boolean);return Xt.length?Xt:void 0},St=ut(ve.kinds)?.filter((bn)=>["metric","log","trace","request","event"].includes(bn));return{projectId:a.project.id,environmentId:d?.id,resourceIds:j(ve.resources),kinds:St,names:ut(ve.names),sources:ut(ve.sources),levels:ut(ve.levels),from:et,to:Ae,text:String(ve.text??"")||void 0,traceId:String(ve.traceId??"")||void 0,requestId:String(ve.requestId??"")||void 0,deploymentId:String(ve.deploymentId??"")||void 0,releaseId:String(ve.releaseId??"")||void 0,workloadId:String(ve.workloadId??"")||void 0,cursor:String(ve.cursor??"")||void 0,limit:Number(ve.limit)||void 0}},fe=Object.fromEntries(L.searchParams.entries()),pe=(ve=!1)=>oi({controlPlane:a.store,projectId:a.project.id,environmentId:d?.id,config:o,environment:ye,force:ve,lightweight:!ve}),He=()=>{let ve=a.store.getSetting(`telemetry.collection:${a.project.id}:${d?.id??"all"}`)??{};return{generatedAt:String(ve.generatedAt??new Date().toISOString()),cached:!0,statuses:Array.isArray(ve.statuses)?ve.statuses:[],errors:Array.isArray(ve.errors)?ve.errors:[],policy:ve.policy??Qe(a.store,a.project.id)}};if(L.pathname==="/api/telemetry/status"&&C.method==="GET"){pe(!1);let ve=He(),Fe=B?ve.statuses:l.status(a.project.id,d?.id,ve.policy.rawDays,ve.policy.samplingRate,X.map((Ae)=>Ae.id)),we=Fe.reduce((Ae,et)=>Ae+et.estimatedDailyBytes*30,0);return b({ok:!0,generatedAt:ve.generatedAt,cached:ve.cached,sources:Fe,errors:B?ve.errors:[],policy:ve.policy,retention:{rawDays:ve.policy.rawDays,downsampleAfterDays:ve.policy.downsampleAfterDays,downsampleBucketMs:ve.policy.downsampleBucketMs,maxRecords:ve.policy.maxRecords},estimatedMonthlyBytes:we,estimatedMonthlyCostUsd:hi(we,ve.policy),costEstimateConfigured:ve.policy.estimatedStorageUsdPerGbMonth>0})}if(L.pathname==="/api/telemetry/settings"&&C.method==="GET")return b({ok:!0,policy:Qe(a.store,a.project.id)});if(L.pathname==="/api/telemetry/settings"&&C.method==="PATCH"){let ve=fi(a.store,a.project.id,await se(C));return sb(a.project.id),b({ok:!0,policy:ve})}if(L.pathname==="/api/telemetry/query"&&C.method==="GET"){pe(!1);let ve=He();return b({ok:!0,collection:{generatedAt:ve.generatedAt,cached:ve.cached},...l.query(Z(fe))})}if(L.pathname==="/api/telemetry/tail"&&C.method==="GET"){pe(!1);let ve=new TextEncoder,Fe=new Date,we=Z({...fe,kinds:fe.kinds||"log,request,event,trace",from:fe.from||new Date(Fe.getTime()-120000).toISOString(),to:Fe.toISOString(),limit:Math.min(1000,Number(fe.limit)||200),cursor:void 0}),Ae=C.headers.get("last-event-id")||String(fe.cursor??"")||void 0,et,ut=!1,St=!1,bn=new ReadableStream({start(Xt){let bo=()=>{if(ut)return;if(ut=!0,et)clearInterval(et);C.signal.removeEventListener("abort",bo);try{Xt.close()}catch{}},Rp=async()=>{if(ut||St)return;St=!0;try{let Uo=l.tail({...we,to:new Date(Date.now()+1000).toISOString()},Ae);for(let Pp of Uo.records)Ae=oo(Pp)??Ae,Xt.enqueue(ve.encode(`id: ${Ae??""}
497
+ This replacement link expires ${k.invitation.expiresAt} and can be used once.`});return b({invitation:k.invitation,token:k.token,acceptUrl:M,delivered:F})}catch(k){return b({ok:!1,error:k instanceof Error?k.message:"Invitation could not be resent."},409)}}if(L.pathname==="/api/organization/memberships"&&C.method==="PATCH"){let d=await se(C),l=a.store.getMembership(String(d.id??"")),k=Td(d.roleTemplate),M=Ba(d);if(!l||l.organizationId!==a.organization.id)return b({ok:!1,error:"Membership was not found."},404);if(!k||!M)return b({ok:!1,error:"Choose a valid role template and resource scope."},422);let F=Ne(ue);if((l.roleTemplate==="owner"||k==="owner")&&(!Ei(String(d.password??""),ue.passwordHash)||F.membership?.roleTemplate!=="owner"))return b({ok:!1,error:"Ownership changes require an owner to re-enter their password."},401);let j=a.store.resolveAuthorizationTarget(a.organization.id,M)??a.store.resolveAuthorizationTarget(a.organization.id,{type:"project",id:a.project.id}),Z=a.store.listGrants(l.id),fe=hn({membership:l,grants:Z,target:j}),pe={...l,roleTemplate:k,scope:M},He=hn({membership:pe,grants:Z,target:j}),ve={gained:He.filter((Be)=>!fe.includes(Be)),lost:fe.filter((Be)=>!He.includes(Be))};if(d.preview===!0)return b({membership:l,proposed:{roleTemplate:k,scope:M},accessDiff:ve});if(String(d.confirm??"")!==l.id)return b({ok:!1,error:`Confirm this change with membership ID ${l.id}.`,accessDiff:ve},409);try{return b({membership:a.store.updateMembership({id:l.id,roleTemplate:k,scope:M,actorId:F.actor?.id}),accessDiff:ve})}catch(Be){return b({ok:!1,error:Be instanceof Error?Be.message:"Membership could not be updated."},409)}}if(L.pathname==="/api/organization/memberships"&&C.method==="DELETE"){let d=await se(C),l=a.store.getMembership(String(d.id??""));if(!l||l.organizationId!==a.organization.id)return b({ok:!1,error:"Membership was not found."},404);if(String(d.confirm??"")!==l.id)return b({ok:!1,error:`Confirm removal with membership ID ${l.id}.`},409);let k=Ne(ue);if(l.roleTemplate==="owner"&&(k.membership?.roleTemplate!=="owner"||!Ei(String(d.password??""),ue.passwordHash)))return b({ok:!1,error:"Removing an owner requires an owner to re-enter their current password."},401);try{return b({membership:a.store.revokeMembership(l.id,k.actor?.id)})}catch(M){return b({ok:!1,error:M instanceof Error?M.message:"Membership could not be removed."},409)}}if(L.pathname==="/api/organization/grants"&&C.method==="POST"){let d=await se(C),l=String(d.capability??""),k=d.effect==="deny"?"deny":d.effect==="allow"?"allow":void 0,M=Ba(d),F=Ne(ue);if(!k||!M||!ae.includes(l))return b({ok:!1,error:"Choose a valid capability, effect, and resource scope."},422);try{return b({grant:a.store.upsertGrant({organizationId:a.organization.id,membershipId:String(d.membershipId??""),effect:k,capability:l,scope:M,actorId:F.actor?.id})},201)}catch(X){return b({ok:!1,error:X instanceof Error?X.message:"Grant could not be created."},422)}}if(L.pathname==="/api/organization/grants"&&C.method==="DELETE"){let d=await se(C),l=Ne(ue),k=a.store.getGrant(String(d.id??""));if(!k||k.organizationId!==a.organization.id)return b({ok:!1,error:"Grant was not found."},404);return b({ok:a.store.removeGrant(k.id,l.actor?.id)})}if(L.pathname==="/api/tags"&&C.method==="GET")return b({tags:a.store.listTags(a.project.id),assignments:a.store.listResourceTags(a.project.id)});if(L.pathname==="/api/tags"&&C.method==="POST"){let d=await se(C),l=a.store.upsertTag(a.project.id,String(d.name??""),String(d.color??"#5a8be0"));if(d.resourceId)a.store.assignTag(String(d.resourceId),l.id);return b({tag:l},201)}if(L.pathname==="/api/tags"&&C.method==="DELETE"){let d=await se(C);return a.store.removeTag(String(d.resourceId??""),String(d.tagId??"")),b({ok:!0})}if(L.pathname==="/"&&!fb(L.pathname,Tn))return new Response(null,{status:302,headers:{location:`/server/sites?env=${encodeURIComponent(ye)}`}});if(L.pathname==="/"&&Lt?.mode==="serverless")return new Response(null,{status:302,headers:{location:`/serverless?env=${encodeURIComponent(ye)}`}});let Ja=by(L.pathname);if(Ja)return new Response(null,{status:308,headers:{location:`${Ja}?env=${encodeURIComponent(ye)}`}});if(L.pathname==="/api/env"&&C.method==="POST"){let d=await se(C),l=String(d.env??"");if(!f.includes(l))return b({ok:!1,error:`Unknown environment '${l}'.`,environments:f},404);return b({ok:!0,environment:l,environments:f,href:`?env=${encodeURIComponent(l)}`})}if(L.pathname==="/api/config"){let d={...fA(o),environment:ye,environments:f};return b(vy(d,Tn))}if(L.pathname==="/api/ssh-keys"&&C.method==="GET")return b({configPath:R,keys:_t(da(o))});if(L.pathname==="/api/ssh-keys"&&C.method==="POST"){if(!R)return b({ok:!1,error:"No cloud config file was found in this checkout."},404);let d=await se(C),l=await Li(R,"utf8"),k=da(o),M=mc({configText:l,name:String(d.name??""),publicKey:String(d.publicKey??""),existingKeys:k});return await ls(R,M),lb(o,[...k,{name:String(d.name??"").trim(),publicKey:String(d.publicKey??"").trim().replace(/\s+/g," ")}]),b({ok:!0,configPath:R,keys:_t(da(o))})}if(L.pathname==="/api/ssh-keys"&&C.method==="DELETE"){if(!R)return b({ok:!1,error:"No cloud config file was found in this checkout."},404);let d=await se(C),l=String(d.name??L.searchParams.get("name")??""),k=await Li(R,"utf8"),M=da(o),F=gc({configText:k,name:l,existingKeys:M});return await ls(R,F),lb(o,M.filter((X)=>X.name!==l.trim())),b({ok:!0,configPath:R,keys:_t(da(o))})}if(L.pathname==="/api/firewall"&&C.method==="GET")return b({configPath:R,alwaysOpen:[22,80,443],ports:sp(o)});if(L.pathname==="/api/firewall"&&C.method==="POST"){if(!R)return b({ok:!1,error:"No cloud config file was found in this checkout."},404);let d=await se(C),l=Number(d.port);if(!$a(l))return b({ok:!1,error:"Port must be an integer between 1 and 65535."},422);let k=sp(o),M=await Li(R,"utf8");try{await ls(R,ky(M,l,k))}catch(j){return b({ok:!1,error:j?.message??String(j)},422)}let F=us([...k,l]);pb(o,F);let X=d.apply===!1?null:await or(o,ye,`ufw allow ${l}/tcp`).catch((j)=>({ok:!1,error:String(j?.message??j)}));return b({ok:!0,configPath:R,ports:F,apply:X})}if(L.pathname==="/api/firewall"&&C.method==="DELETE"){if(!R)return b({ok:!1,error:"No cloud config file was found in this checkout."},404);let d=await se(C),l=Number(d.port??L.searchParams.get("port"));if(!$a(l))return b({ok:!1,error:"Port must be an integer between 1 and 65535."},422);let k=sp(o),M=await Li(R,"utf8");await ls(R,Ry(M,l,k));let F=us(k.filter((j)=>j!==l));pb(o,F);let X=d.apply===!1?null:await or(o,ye,`ufw delete allow ${l}/tcp`).catch((j)=>({ok:!1,error:String(j?.message??j)}));return b({ok:!0,configPath:R,ports:F,apply:X})}if(L.pathname==="/api/sites"&&C.method==="POST"){if(!R)return b({ok:!1,error:"No cloud config file was found in this checkout."},404);let d=await se(C),l=String(d.name??"").trim(),k=String(d.root??"").trim();if(!l||!k)return b({ok:!1,error:"Site name and root are required."},422);let M={deploy:d.deploy==="bucket"?"bucket":"server",root:k,path:String(d.path??"").trim()||void 0,domain:String(d.domain??"").trim()||void 0,build:String(d.build??"").trim()||void 0,start:String(d.start??"").trim()||void 0,port:d.port?Number(d.port):void 0,type:String(d.type??"").trim()||void 0};if(M.port!==void 0&&(!Number.isInteger(M.port)||M.port<1||M.port>65535))return b({ok:!1,error:"Port must be a number between 1 and 65535."},422);let F=await Li(R,"utf8"),X=kn({configText:F,name:l,root:M.root,domain:M.domain,path:M.path,deploy:M.deploy,build:M.build,start:M.start,port:M.port,type:M.type});return await ls(R,X),aA(o,l,Object.fromEntries(Object.entries(M).filter(([,j])=>j!==void 0))),Lt=await ps(o,ye),W.set(ye,Lt),b({ok:!0,configPath:R,site:l,data:Lt})}if(L.pathname==="/api/sites"&&C.method==="DELETE"){if(!R)return b({ok:!1,error:"No cloud config file was found in this checkout."},404);let d=await se(C),l=String(d.name??L.searchParams.get("name")??"").trim();if(!l||!o.sites?.[l])return b({ok:!1,error:`Site '${l}' was not found.`},404);let k=await Li(R,"utf8");return await ls(R,qy({configText:k,name:l})),delete o.sites[l],Lt=await ps(o,ye),W.set(ye,Lt),b({ok:!0,configPath:R,site:l,data:Lt})}if(L.pathname==="/api/sites"&&C.method==="PATCH"){if(!R)return b({ok:!1,error:"No cloud config file was found in this checkout."},404);let d=await se(C),l=String(d.name??"").trim(),k=o.sites?.[l];if(!l||!k)return b({ok:!1,error:`Site '${l}' was not found.`},404);if(Tn.role==="member"){let X=Cy(d);if(!X.ok)return b({ok:!1,error:X.error},403);let j=Ey({siteName:l,body:d,sites:o.sites??{},ownSites:Object.keys(Tn.sites)});if(!j.ok)return b({ok:!1,error:j.error},409)}if(d.port!==void 0&&d.port!==null&&d.port!==""&&(!Number.isInteger(Number(d.port))||Number(d.port)<1||Number(d.port)>65535))return b({ok:!1,error:"Port must be a number between 1 and 65535."},422);if(typeof d.domain==="string"&&d.domain.trim()&&!np(d.domain.trim()))return b({ok:!1,error:`Domain '${d.domain.trim()}' is not a valid hostname.`},422);let M=await Li(R,"utf8"),F=(X,j)=>{M=Gy({configText:M,siteName:l,key:X,valueText:j})};if(d.ssl!==void 0)F("ssl",Jy(d.ssl)),k.ssl=d.ssl;if(d.env!==void 0&&d.env&&typeof d.env==="object")F("env",Wy(d.env)),k.env=d.env;if(d.aliases!==void 0&&Array.isArray(d.aliases)){let X=d.aliases.map((j)=>String(j));F("aliases",Ky(X)),k.aliases=X.map((j)=>j.trim().toLowerCase()).filter(Boolean)}if(d.redirects!==void 0&&d.redirects&&typeof d.redirects==="object")F("redirects",Qy(d.redirects)),k.redirects=d.redirects;for(let X of["domain","path","build","start","type","root","php"])if(typeof d[X]==="string"&&d[X].trim())F(X,Hy(String(d[X]).trim())),k[X]=String(d[X]).trim();if(d.port!==void 0&&d.port!==null&&d.port!=="")F("port",String(Number(d.port))),k.port=Number(d.port);return await ls(R,M),Lt=await ps(o,ye),W.set(ye,Lt),b({ok:!0,configPath:R,site:l,data:Lt})}if(L.pathname==="/api/sites/deploy"&&C.method==="POST"){let d=await se(C),l=String(d.name??"").trim();if(!l||!o.sites?.[l])return b({ok:!1,error:`Site '${l}' was not found.`},404);if(d.confirm!==l)return b({ok:!1,error:`Type "${l}" to deploy this site.`},409);let k=le(a,String(ye));await new ss(rt).run(new Da,{...k,artifactRoot:t}),dd(rt,k,Lt??{});let M=ar(rt,{scope:k,desiredConfigHash:a.project.desiredConfigHash});if(M.decision.outcome==="block")return b({ok:!1,error:`Deployment blocked by security policy: ${M.decision.explanation}`,securityReview:M},409);let F={id:`deploy:${l}`,label:`Deploy ${l}`,description:`Deploy the ${l} site for ${ye}.`,command:["deploy","--env",ye,"--site",l,"--yes"],mutates:!0},X=await ao({controlPlane:a,environment:ye,actor:ue,kind:"dashboard.site.deploy",resourceSlug:l,input:{site:l},execute:()=>ap(F,{cwd:t,cliEntry:i})});return b({...X.result,controlPlaneOperation:X.operation,securityReview:M})}if(L.pathname==="/api/actions")return b(wb(ye));if(L.pathname==="/api/server/operations")return b(Hr(o,Lt));if(L.pathname==="/api/runtime/workloads"&&C.method==="GET"){let d=await Ii(o,ye);return b(d)}if(L.pathname==="/api/runtime/logs"&&C.method==="GET"){let d=String(L.searchParams.get("workload")??"");if(!d)return b({ok:!1,error:"A workload query parameter is required."},422);let l=Math.min(1000,Math.max(1,Number(L.searchParams.get("limit"))||200));try{return b(await new Se(o,ye).logs(d,{limit:l}))}catch(k){return b({ok:!1,error:String(k?.message??k)},404)}}if(L.pathname==="/api/runtime/log-sessions"&&C.method==="POST"){let d=await se(C),l=String(d.workloadId??"");if(!l)return b({ok:!1,error:"A workloadId is required."},422);let k=await Ii(o,ye),M=k.workloads.find((j)=>j.id===l);if(!M)return b({ok:!1,error:"Workload was not found in the current project and environment."},404);if(!M.capabilities.logs.supported)return b({ok:!1,error:M.capabilities.logs.reason??"Logs are unsupported for this workload."},409);let F=new Se(o,ye,{inventory:async()=>k}),X=Yt.create("logs",l);return(async()=>{let j=new Date(Date.now()-Math.min(3600000,Math.max(1000,Number(d.sinceMs)||60000)));try{for(let Z=0;Z<200&&!Yt.signal(X.id)?.aborted;Z++){let fe=await F.logs(l,{limit:Math.min(500,Math.max(1,Number(d.limit)||200)),since:j});for(let pe of fe.lines)if(Yt.append(X.id,`${pe.timestamp?`${pe.timestamp} `:""}${pe.message}
498
+ `),pe.timestamp)j=new Date(Math.max(j.getTime(),new Date(pe.timestamp).getTime()+1));await Bun.sleep(3000)}if(!Yt.signal(X.id)?.aborted)Yt.close(X.id,"complete")}catch(Z){Yt.append(X.id,Z instanceof Error?Z.message:String(Z),"stderr"),Yt.close(X.id,"failed",Z instanceof Error?Z.message:String(Z))}})(),b({ok:!0,session:X,streamUrl:`/api/runtime/log-stream?id=${encodeURIComponent(X.id)}&workload=${encodeURIComponent(l)}`},201)}if((L.pathname==="/api/runtime/log-stream"||L.pathname==="/api/runtime/exec-stream")&&C.method==="GET"){let d=String(L.searchParams.get("id")??""),l=String(L.searchParams.get("workload")??""),k=Number(C.headers.get("last-event-id")??L.searchParams.get("after")??0)||0,M=Yt.read(d,l,k),F=L.pathname.includes("exec")?"exec":"logs";if(!M||M.kind!==F)return b({ok:!1,error:"Runtime stream was not found in this workload scope."},404);return XT(Yt,M,k,C.signal)}if((L.pathname==="/api/runtime/log-sessions"||L.pathname==="/api/runtime/exec-sessions")&&C.method==="DELETE"){let d=await se(C),l=Yt.cancel(String(d.id??""),String(d.workloadId??""));if(!l)return b({ok:!1,error:"Runtime stream was not found in this workload scope."},404);return b({ok:!0,session:l})}if(L.pathname==="/api/runtime/exec-sessions"&&C.method==="POST"){let d=await se(C),l=String(d.workloadId??""),k=await Ii(o,ye),M=k.workloads.find((Z)=>Z.id===l);if(!M)return b({ok:!1,error:"Workload was not found in the current project and environment."},404);let F=jt.resolveSession(C),X=new Se(o,ye,{inventory:async()=>k}),j=Yt.create("exec",l);return ao({controlPlane:a,environment:ye,actor:ue,kind:"runtime.exec",resourceSlug:M.links.service,input:{workloadId:l,provider:M.provider,preset:d.preset?String(d.preset):null,freeForm:!!String(d.command??"").trim()},execute:()=>X.exec({workloadId:l,preset:["process","sockets","filesystem"].includes(String(d.preset))?String(d.preset):void 0,command:typeof d.command==="string"?d.command:void 0,confirm:String(d.confirm??""),recentAuth:!Pe||!!F&&Ie.isRecentlyAuthenticated(F)})}).then(({result:Z,operation:fe})=>{if(Yt.append(j.id,`operation ${fe.id}
499
+ `,"system"),Z.stdout)Yt.append(j.id,Z.stdout,"stdout");if(Z.stderr)Yt.append(j.id,Z.stderr,"stderr");Yt.close(j.id,Z.ok?"complete":"failed",Z.error)}).catch((Z)=>{let fe=Z instanceof Error?Z.message:String(Z);Yt.append(j.id,fe,"stderr"),Yt.close(j.id,"failed",fe)}),b({ok:!0,session:j,streamUrl:`/api/runtime/exec-stream?id=${encodeURIComponent(j.id)}&workload=${encodeURIComponent(l)}`},202)}if(L.pathname==="/api/runtime/files/read"&&C.method==="POST"){let d=await se(C),l=await Ii(o,ye),k=jt.resolveSession(C),M=await new Se(o,ye,{inventory:async()=>l}).readFile({workloadId:String(d.workloadId??""),path:String(d.path??""),confirm:String(d.confirm??""),recentAuth:!Pe||!!k&&Ie.isRecentlyAuthenticated(k)});return b(M,M.ok?200:409)}if(L.pathname==="/api/runtime/files/write"&&C.method==="POST"){let d=await se(C),l=await Ii(o,ye),k=String(d.workloadId??""),M=l.workloads.find((Z)=>Z.id===k);if(!M)return b({ok:!1,error:"Workload was not found in the current project and environment."},404);let F=jt.resolveSession(C),X=new Se(o,ye,{inventory:async()=>l}),j=await ao({controlPlane:a,environment:ye,actor:ue,kind:"runtime.file.write",resourceSlug:M.links.service,input:{workloadId:k,provider:M.provider,path:String(d.path??""),bytes:Buffer.from(String(d.contentBase64??""),"base64").byteLength},execute:()=>X.writeFile({workloadId:k,path:String(d.path??""),contentBase64:String(d.contentBase64??""),confirm:String(d.confirm??""),recentAuth:!Pe||!!F&&Ie.isRecentlyAuthenticated(F)})});return b({...j.result,controlPlaneOperation:j.operation},j.result.ok?200:409)}if(L.pathname==="/api/runtime/operations"&&C.method==="POST"){let d=await se(C),l=String(d.workloadId??""),k=String(d.action??"");if(!l||!["start","stop","restart","redeploy","scale","inspect"].includes(k))return b({ok:!1,error:"A valid workloadId and lifecycle action are required."},422);let M=await Ii(o,ye),F=M.workloads.find((fe)=>fe.id===l);if(!F)return b({ok:!1,error:"Workload was not found in the current project and environment."},404);let X=jt.resolveSession(C),j=new Se(o,ye,{inventory:async()=>M}),Z=await ao({controlPlane:a,environment:ye,actor:ue,kind:`runtime.${k}`,resourceSlug:F.links.service,input:{workloadId:l,provider:F.provider,action:k,replicas:d.replicas==null?null:Number(d.replicas)},execute:()=>j.run({workloadId:l,action:k,replicas:d.replicas==null?void 0:Number(d.replicas),confirm:String(d.confirm??""),recentAuth:!Pe||!!X&&Ie.isRecentlyAuthenticated(X)})});return b({...Z.result,controlPlaneOperation:Z.operation},Z.result.ok?200:409)}if(L.pathname.startsWith("/api/protection")){let d=ue.role==="admin"||Ga(ue,"security:read"),l=ue.role==="admin"||Ga(ue,"security:manage");if(!d)return b({ok:!1,error:"Protection controls require security:read."},403);let{ProtectionControlStore:k,describePosture:M}=await import("./chunk-pzj1ac7x.js"),F=new k(a.store),X=()=>{if(!l)throw Error("Changing protection controls requires security:manage.")};if(L.pathname==="/api/protection"&&C.method==="GET"){let j=F.current();return b({ok:!0,posture:M(j),controls:j,raw:F.raw()})}if(L.pathname==="/api/protection/attack-mode"&&C.method==="POST"){X();let j=await se(C);if(j.enabled===!1)return b({ok:!0,disabled:F.disableAttackMode()});return b({ok:!0,control:F.enableAttackMode({hours:j.hours==null?void 0:Number(j.hours),reason:String(j.reason??"Enabled from the dashboard."),actorId:Ne(ue).actor?.id})})}if(L.pathname==="/api/protection/pause"&&C.method==="POST"){X();let j=await se(C);if(j.enabled===!1)return b({ok:!0,resumed:F.resumeMitigations()});return b({ok:!0,control:F.pauseMitigations({hours:j.hours==null?void 0:Number(j.hours),reason:String(j.reason??""),actorId:Ne(ue).actor?.id})})}if(L.pathname==="/api/protection/ip-rules"&&C.method==="GET")return b({ok:!0,ipRules:F.current().ipRules});if(L.pathname==="/api/protection/ip-rules"&&(C.method==="POST"||C.method==="DELETE")){X();let j=await se(C),Z=j.list==="allow"?"allow":"block",fe=C.method==="POST"?F.addIpRule(Z,String(j.cidr??"")):F.removeIpRule(Z,String(j.cidr??""));return b({ok:!0,ipRules:fe})}return b({ok:!1,error:"Protection endpoint was not found."},404)}if(L.pathname.startsWith("/api/spend/")||L.pathname==="/api/usage"){let d=await Ab(),{store:l,service:k,gate:M}=d,F=ue.role==="admin"||Ga(ue,"billing:read"),X=ue.role==="admin"||Ga(ue,"billing:manage");if(!F)return b({ok:!1,error:"Spend data requires the billing:read capability."},403);let j=a.environments.get(ye),Z={organizationId:a.organization.id,projectId:a.project.id,environmentId:j?.id},fe=()=>{if(!X)throw Error("Changing a budget requires the billing:manage capability.")};if(L.pathname==="/api/usage"&&C.method==="GET")return b({ok:!0,...k.usageReport({organizationId:Z.organizationId,projectId:Z.projectId,period:L.searchParams.get("period")??"monthly",timezone:L.searchParams.get("timezone")??void 0})});if(L.pathname==="/api/spend/budgets"&&C.method==="GET")return b({ok:!0,budgets:l.listBudgets({organizationId:Z.organizationId,projectId:Z.projectId}).map((pe)=>({...pe,status:k.status(pe)}))});if(L.pathname==="/api/spend/budgets"&&C.method==="POST"){fe();let pe=await se(C),He=String(pe.scope??"project"),ve=l.createBudget({organizationId:Z.organizationId,projectId:He==="organization"?void 0:Z.projectId,environmentId:He==="environment"?Z.environmentId:void 0,name:String(pe.name??"").trim(),period:pe.period??"monthly",timezone:pe.timezone?String(pe.timezone):void 0,softLimitCents:pe.softLimitCents==null?void 0:Math.round(Number(pe.softLimitCents)),hardLimitCents:pe.hardLimitCents==null?void 0:Math.round(Number(pe.hardLimitCents)),graceSeconds:pe.graceSeconds==null?void 0:Number(pe.graceSeconds),dryRun:pe.dryRun!==!1});return b({ok:!0,budget:ve})}if(L.pathname==="/api/spend/budgets"&&C.method==="PATCH"){fe();let pe=await se(C),He=String(pe.id??""),ve=l.getBudget(He);if(!ve||ve.organizationId!==Z.organizationId)return b({ok:!1,error:"Budget was not found."},404);return b({ok:!0,budget:l.updateBudget(He,{softLimitCents:pe.softLimitCents==null?ve.softLimitCents:Math.round(Number(pe.softLimitCents)),hardLimitCents:pe.hardLimitCents==null?ve.hardLimitCents:Math.round(Number(pe.hardLimitCents)),enabled:pe.enabled==null?ve.enabled:pe.enabled===!0,dryRun:pe.dryRun==null?ve.dryRun:pe.dryRun===!0},pe.expectedVersion==null?void 0:Number(pe.expectedVersion))})}if(L.pathname==="/api/spend/budgets"&&C.method==="DELETE"){fe();let pe=await se(C),He=String(pe.id??""),ve=l.getBudget(He);if(!ve||ve.organizationId!==Z.organizationId)return b({ok:!1,error:"Budget was not found."},404);let Be=M.closeBudget(He);return l.deleteBudget(He),b({ok:!0,deleted:!0,lifted:Be})}if(L.pathname==="/api/spend/check"&&C.method==="POST"){fe();let pe=await se(C),{SpendRunner:He}=await import("./chunk-vjg2fymw.js"),ve=new He({controlPlane:a.store,store:l,alerts:We});if(pe.apply!==!0){let we=l.budgetsForScope(Z.organizationId,Z.projectId,Z.environmentId);return b({ok:!0,applied:!1,preview:we.map((Ae)=>k.status(Ae))})}let Be=await ve.run({...Z,environmentKind:j?.kind});return b({ok:!0,applied:!0,result:Be})}if(L.pathname==="/api/spend/enforcement"&&C.method==="GET")return b({ok:!0,enforcement:M.listUnder({organizationId:Z.organizationId})});if(L.pathname==="/api/spend/release"&&C.method==="POST"){fe();let pe=await se(C),He=M.close(String(pe.budgetId??""),pe.action);return b({ok:He,released:He,note:He?"The next spend cycle re-applies this if spend is still over the threshold.":"That action was not in force."})}if(L.pathname==="/api/spend/anomalies"&&C.method==="GET")return b({ok:!0,anomalies:l.listAnomalies({organizationId:Z.organizationId,projectId:Z.projectId,unacknowledgedOnly:L.searchParams.get("unacknowledged")==="true"})});if(L.pathname==="/api/spend/anomalies/acknowledge"&&C.method==="POST"){fe();let pe=await se(C);return b({ok:!0,acknowledged:l.acknowledgeAnomaly(String(pe.id??""))})}return b({ok:!1,error:"Spend endpoint was not found."},404)}if(L.pathname.startsWith("/api/health/")||L.pathname.startsWith("/api/alerts")||L.pathname.startsWith("/api/notifications/")){let d=a.environments.get(ye),l=a.store.listResources(a.project.id,d?.id),k=ue.role==="admin"||!!d&&la(ue,d.id,"runtime:read")?l:l.filter((j)=>Sr(ue,j.id,"runtime:read")),M=(j)=>!j||k.some((Z)=>Z.id===j),F=(j)=>{if(!j)return;let Z=l.find((fe)=>fe.id===j||fe.slug===j);if(!Z)throw Error("Alert resource was not found.");if(!M(Z.id))throw Error("Alert resource is outside your authorized scope.");return Z.id},X=Ne(ue).actor;if(L.pathname==="/api/health/checks"&&C.method==="GET")return b({ok:!0,checks:We.listHealthChecks(a.project.id,d?.id).filter((j)=>M(j.resourceId)).map((j)=>({...j,results:We.listHealthResults(j.id,20)}))});if(L.pathname==="/api/health/checks"&&C.method==="POST"){let j=await se(C),Z=String(j.kind??"http");if(Z==="command"&&ue.role!=="admin")return b({ok:!1,error:"Command health checks require an administrator."},403);let fe={method:String(j.config?.method??"GET").toUpperCase().slice(0,10),path:j.config?.path?String(j.config.path).slice(0,500):void 0,port:j.config?.port==null?void 0:Number(j.config.port),command:Array.isArray(j.config?.command)?j.config.command.map(String).slice(0,20):void 0,expectedStatuses:Array.isArray(j.config?.expectedStatuses)?j.config.expectedStatuses.map(Number).filter(Number.isInteger).slice(0,20):void 0,expectedBody:j.config?.expectedBody?String(j.config.expectedBody).slice(0,500):void 0};return b({ok:!0,check:We.createHealthCheck({projectId:a.project.id,environmentId:d?.id,resourceId:F(j.resourceId??j.resource),name:String(j.name??""),kind:Z,target:String(j.target??""),config:fe,intervalSeconds:Number(j.intervalSeconds)||60,timeoutSeconds:Number(j.timeoutSeconds)||10,failureThreshold:Number(j.failureThreshold)||3,recoveryThreshold:Number(j.recoveryThreshold)||2,regions:Array.isArray(j.regions)?j.regions.map(String):["local"],enabled:j.enabled!==!1})},201)}if(L.pathname==="/api/health/checks"&&C.method==="PATCH"){let j=await se(C),Z=We.getHealthCheck(String(j.id??""));if(!Z||!M(Z.resourceId))return b({ok:!1,error:"Health check was not found."},404);return b({ok:!0,check:We.setHealthCheckEnabled(Z.id,j.enabled!==!1)})}if(L.pathname==="/api/health/checks/test"&&C.method==="POST"){let j=await se(C),Z=We.getHealthCheck(String(j.id??""));if(!Z||!M(Z.resourceId))return b({ok:!1,error:"Health check was not found."},404);return b({ok:!0,productionIncidentCreated:!1,result:await new Ue(We).probe(Z)})}if(L.pathname==="/api/health/checks/run"&&C.method==="POST"){let j=await se(C),Z=We.getHealthCheck(String(j.id??""));if(!Z||!M(Z.resourceId))return b({ok:!1,error:"Health check was not found."},404);let fe=await new Ue(We).runAndEvaluate(Z),pe=[];for(let He of fe.evaluations.filter((ve)=>ve.notify&&ve.alert)){let ve=En.enqueue(a.organization.id,He.alert,He.transition);pe.push(...await En.deliverAll(ve))}return b({ok:!0,...fe,deliveries:pe})}if(L.pathname==="/api/alerts/rules"&&C.method==="GET")return b({ok:!0,rules:We.listRules(a.project.id,d?.id).filter((j)=>M(j.resourceId))});if(L.pathname==="/api/alerts/rules"&&C.method==="POST"){let j=await se(C),Z=j.healthCheckId?We.getHealthCheck(String(j.healthCheckId)):void 0;if(j.healthCheckId&&(!Z||!M(Z.resourceId)))return b({ok:!1,error:"Health check was not found."},404);return b({ok:!0,rule:We.createRule({projectId:a.project.id,environmentId:d?.id,resourceId:F(j.resourceId??j.resource)??Z?.resourceId,healthCheckId:Z?.id,name:String(j.name??""),signal:String(j.signal??(Z?"health":"")),operator:String(j.operator??(Z?"unhealthy":"gt")),threshold:j.threshold==null?void 0:Number(j.threshold),recoveryThreshold:j.recoveryThreshold==null?void 0:Number(j.recoveryThreshold),windowMs:Number(j.windowMs)||300000,consecutive:Number(j.consecutive)||Z?.failureThreshold||3,recoveryConsecutive:Number(j.recoveryConsecutive)||Z?.recoveryThreshold||2,noDataPolicy:["ignore","pending","firing"].includes(String(j.noDataPolicy))?j.noDataPolicy:"pending",severity:["info","warning","critical"].includes(String(j.severity))?j.severity:"warning",groupBy:Array.isArray(j.groupBy)?j.groupBy.map(String):[],labels:j.labels&&typeof j.labels==="object"?j.labels:{},enabled:j.enabled!==!1})},201)}if(L.pathname==="/api/alerts/rules"&&C.method==="PATCH"){let j=await se(C),Z=We.getRule(String(j.id??""));if(!Z||!M(Z.resourceId))return b({ok:!1,error:"Alert rule was not found."},404);return b({ok:!0,rule:We.setRuleEnabled(Z.id,j.enabled!==!1)})}if(L.pathname==="/api/alerts/evaluate"&&C.method==="POST")return b({ok:!0,...await hp(d?.id)});if(L.pathname==="/api/alerts"&&C.method==="GET")return b({ok:!0,alerts:We.listAlerts(a.project.id,{environmentId:d?.id,states:L.searchParams.getAll("state").length?L.searchParams.getAll("state"):void 0,limit:Number(L.searchParams.get("limit"))||200}).filter((j)=>M(j.resourceId)).map((j)=>({...j,deliveries:We.listDeliveries({alertId:j.id,limit:50})}))});if(L.pathname==="/api/alerts/action"&&C.method==="POST"){let j=await se(C),Z=We.getAlert(String(j.id??""));if(!Z||!M(Z.resourceId))return b({ok:!1,error:"Alert was not found."},404);let fe=String(j.action??"");if(fe==="acknowledge")return b({ok:!0,alert:We.acknowledge(Z.id,X?.id??"")});if(fe==="assign")return b({ok:!0,alert:We.assign(Z.id,j.ownerActorId==="me"?X?.id:j.ownerActorId?String(j.ownerActorId):void 0,X?.id)});if(fe==="silence"){if(ue.role!=="admin")return b({ok:!1,error:"Silencing production alerts requires an administrator."},403);let pe=jt.resolveSession(C);if(Pe&&(!pe||!Ie.isRecentlyAuthenticated(pe)))return b({ok:!1,error:"Recent authentication is required to silence alerts.",stepUpRequired:!0},401);return b({ok:!0,alert:We.silenceAlert(Z.id,String(j.until??""),X?.id)})}return b({ok:!1,error:"Action must be acknowledge, assign, or silence."},422)}if(L.pathname==="/api/alerts/silences"&&C.method==="POST"){let j=await se(C);return b({ok:!0,id:We.createSilence({projectId:a.project.id,environmentId:d?.id,resourceId:F(j.resourceId??j.resource),matcher:j.matcher,reason:String(j.reason??""),startsAt:String(j.startsAt??new Date().toISOString()),endsAt:String(j.endsAt??""),timezone:String(j.timezone??"UTC"),actorId:X?.id})},201)}if(L.pathname==="/api/notifications/channels"&&C.method==="GET")return b({ok:!0,channels:We.listChannels(a.organization.id)});if(L.pathname==="/api/notifications/channels"&&C.method==="POST"){let j=await se(C),Z=String(j.kind??""),fe=Z==="email"?{to:j.config?.to,from:j.config?.from}:Z==="telegram"?{chatId:String(j.config?.chatId??"")}:{};return b({ok:!0,channel:We.createChannel({organizationId:a.organization.id,name:String(j.name??""),kind:Z,config:fe,credential:j.credential?String(j.credential):void 0,actorId:X?.id})},201)}if(L.pathname==="/api/notifications/channels"&&C.method==="PATCH"){let j=await se(C),Z=String(j.id??"");if(j.credential)return b({ok:!0,channel:We.rotateChannel(Z,String(j.credential))});let fe=String(j.status??"paused");if(!["active","paused","disabled"].includes(fe))return b({ok:!1,error:"Channel status must be active, paused, or disabled."},422);return b({ok:!0,channel:We.setChannelStatus(Z,fe)})}if(L.pathname==="/api/notifications/channels/test"&&C.method==="POST"){let j=await se(C);return b({ok:!0,productionIncidentCreated:!1,result:await En.testChannel(String(j.id??""))})}if(L.pathname==="/api/notifications/routes"&&C.method==="GET")return b({ok:!0,routes:We.listRoutes(a.organization.id)});if(L.pathname==="/api/notifications/routes"&&C.method==="POST"){let j=await se(C),Z=Array.isArray(j.channelIds)?j.channelIds.map(String):[];if(Z.some((fe)=>We.getChannel(fe)?.organizationId!==a.organization.id))return b({ok:!1,error:"Route contains an unavailable channel."},422);return b({ok:!0,route:We.createRoute({organizationId:a.organization.id,name:String(j.name??""),priority:Number(j.priority)||0,matcher:j.matcher&&typeof j.matcher==="object"?j.matcher:{},channelIds:Z,quietHours:j.quietHours,groupWaitSeconds:Number(j.groupWaitSeconds)||30,reminderSeconds:j.reminderSeconds==null?void 0:Number(j.reminderSeconds),escalation:Array.isArray(j.escalation)?j.escalation:[],template:j.template?String(j.template):void 0,rateLimitPerMinute:Number(j.rateLimitPerMinute)||60,enabled:j.enabled!==!1})},201)}if(L.pathname==="/api/notifications/routes"&&C.method==="PATCH"){let j=await se(C),Z=We.getRoute(String(j.id??""));if(!Z||Z.organizationId!==a.organization.id)return b({ok:!1,error:"Notification route was not found."},404);return b({ok:!0,route:We.setRouteEnabled(Z.id,j.enabled!==!1)})}if(L.pathname==="/api/notifications/routes/preview"&&C.method==="POST"){let j=await se(C),fe=(j.alertId?We.getAlert(String(j.alertId)):void 0)??{id:"preview",ruleId:"preview",projectId:a.project.id,environmentId:d?.id,resourceId:F(j.resourceId??j.resource),dedupKey:"preview",groupKey:String(j.groupKey??"default"),state:"firing",severity:["info","warning","critical"].includes(String(j.severity))?j.severity:"warning",title:String(j.title??"Rule preview"),evidence:{},failureCount:1,recoveryCount:0,occurrenceCount:1,firstSeenAt:new Date().toISOString(),lastSeenAt:new Date().toISOString(),firingAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return b({ok:!0,productionIncidentCreated:!1,matches:En.preview(a.organization.id,fe,String(j.eventType??"firing")).map((pe)=>({route:pe.route,channels:pe.channels,quiet:pe.quiet}))})}if(L.pathname==="/api/notifications/deliveries"&&C.method==="GET")return b({ok:!0,deliveries:We.listDeliveries({alertId:L.searchParams.get("alertId")??void 0,states:L.searchParams.getAll("state"),limit:Number(L.searchParams.get("limit"))||200})});if(L.pathname==="/api/notifications/deliveries/retry"&&C.method==="POST"){let j=await se(C),Z=We.getDelivery(String(j.id??""));if(!Z)return b({ok:!1,error:"Delivery was not found."},404);return We.updateDelivery(Z.id,{state:"retrying",attempt:Math.max(0,Z.attempt-1),nextAttemptAt:new Date().toISOString()}),b({ok:!0,delivery:await En.deliver(Z.id)})}}if(L.pathname.startsWith("/api/jobs")||L.pathname.startsWith("/api/workers")){let d=a.environments.get(ye),l=a.store.listResources(a.project.id,d?.id),M=ue.role==="admin"||!!d&&la(ue,d.id,"automation:read")?l:l.filter((we)=>Sr(ue,we.id,"automation:read")),F=(we)=>!we||M.some((Ae)=>Ae.id===we),X=Ne(ue).actor,j=W.get(ye)??D,Z=Hr(o,j),fe=Z.filter((we)=>!we.danger&&["scheduler","backup","worker"].includes(we.group)),pe=H(o),He=()=>{let we=jt.resolveSession(C);return!Pe||!!we&&Ie.isRecentlyAuthenticated(we)},ve=(we)=>{if(!we||typeof we!=="object"||Array.isArray(we))return{};let Ae=Object.entries(we).slice(0,50);if(Ae.some(([,et])=>typeof et!=="string"||!/^(?:secret|ssm|arn|env):\/\//.test(et)))throw Error("Job payload values must be secret or environment references, never inline values.");return Object.fromEntries(Ae)},Be=(we,Ae,et)=>a.store.appendEvent({organizationId:a.organization.id,projectId:a.project.id,resourceId:et,actorId:X?.id,type:`job.${we}`,payload:Ae});if(L.pathname==="/api/jobs/preview"&&C.method==="POST"){let we=await se(C);try{return b({ok:!0,productionExecutionCreated:!1,preview:ct(String(we.expression??""),String(we.timezone??"UTC"),new Date(we.from?String(we.from):Date.now()),Number(we.count)||5)})}catch(Ae){return b({ok:!1,error:Ae instanceof Error?Ae.message:"Schedule preview could not be generated.",productionExecutionCreated:!1},422)}}if(L.pathname==="/api/jobs"&&C.method==="GET")return b({ok:!0,jobs:br.list(a.project.id,{environmentId:d?.id}).filter((we)=>F(we.resourceId)).map((we)=>({...we,preview:ct(we.normalizedExpression,we.timezone,new Date,5),capability:ti(we),lastExecution:br.listExecutions(we.id,1)[0]}))});if(L.pathname==="/api/jobs"&&C.method==="POST"){let we=await se(C),Ae=String(we.provider??(pe==="serverless"?"eventbridge":"server")),et=pe==="serverless"?"eventbridge":"server";if(Ae!==et)return b({ok:!1,error:`${pe} environments accept ${et} schedules through this adapter.`},422);let ut=we.operationId?String(we.operationId):void 0;if(Ae==="server"&&(!ut||!fe.some((Xt)=>Xt.id===ut)))return b({ok:!1,error:"Server jobs require an allowlisted operation target."},422);let St=ti({provider:Ae,expression:String(we.expression??""),flexibleMinutes:Number(we.flexibleMinutes)||0,missedRunPolicy:we.missedRunPolicy==="catch_up"?"catch_up":"skip",overlapPolicy:["allow","forbid","replace"].includes(String(we.overlapPolicy))?we.overlapPolicy:"forbid"});if(!St.supported)return b({ok:!1,error:St.notes.join(" ")},422);let bn=we.resourceId?l.find((Xt)=>Xt.id===we.resourceId||Xt.slug===we.resourceId):void 0;if(we.resourceId&&(!bn||!F(bn.id)))return b({ok:!1,error:"Job resource was not found."},404);try{let Xt=Ae==="server"?{kind:"dashboard_operation",operationId:ut}:{kind:"serverless_scheduler",action:"run"},bo=br.create({organizationId:a.organization.id,projectId:a.project.id,environmentId:d?.id,resourceId:bn?.id,name:String(we.name??""),provider:Ae,expression:String(we.expression??""),timezone:String(we.timezone??"UTC"),startsAt:we.startsAt?String(we.startsAt):void 0,endsAt:we.endsAt?String(we.endsAt):void 0,flexibleMinutes:Number(we.flexibleMinutes)||0,target:Xt,payloadRefs:ve(we.payloadRefs),missedRunPolicy:we.missedRunPolicy==="catch_up"?"catch_up":"skip",overlapPolicy:["allow","forbid","replace"].includes(String(we.overlapPolicy))?we.overlapPolicy:"forbid",retryPolicy:{maxAttempts:Number(we.maxAttempts)||3,backoffSeconds:Number(we.backoffSeconds)||30,deadLetterRef:we.deadLetterRef?String(we.deadLetterRef):void 0},timeoutSeconds:Number(we.timeoutSeconds)||900,enabled:we.enabled!==!1,origin:"managed",ownerActorId:X?.id,observedState:{},reconciliationStatus:"pending"});return Be("created",{jobId:bo.id,provider:bo.provider,expression:bo.normalizedExpression},bo.resourceId),b({ok:!0,job:bo,capability:St},201)}catch(Xt){return b({ok:!1,error:Xt instanceof Error?Xt.message:"Scheduled job could not be created."},422)}}if(L.pathname==="/api/jobs"&&C.method==="PATCH"){let we=await se(C),Ae=br.get(String(we.id??""));if(!Ae||!F(Ae.resourceId))return b({ok:!1,error:"Scheduled job was not found."},404);if(Ae.origin==="config")return b({ok:!1,error:"Config-defined schedules must be edited in cloud.config.ts and reconciled."},409);let et=we.missedRunPolicy==null?void 0:String(we.missedRunPolicy),ut=we.overlapPolicy==null?void 0:String(we.overlapPolicy);if(et&&!["skip","catch_up"].includes(et))return b({ok:!1,error:"Missed-run policy must be skip or catch_up."},422);if(ut&&!["allow","forbid","replace"].includes(ut))return b({ok:!1,error:"Overlap policy must be allow, forbid, or replace."},422);try{let St=br.updateSchedule(Ae.id,{expression:we.expression?String(we.expression):void 0,timezone:we.timezone?String(we.timezone):void 0,missedRunPolicy:et,overlapPolicy:ut,timeoutSeconds:we.timeoutSeconds==null?void 0:Number(we.timeoutSeconds)});return Be("updated",{jobId:St.id,expression:St.normalizedExpression,version:St.version},St.resourceId),b({ok:!0,job:St})}catch(St){return b({ok:!1,error:St instanceof Error?St.message:"Scheduled job could not be updated."},422)}}if(L.pathname==="/api/jobs/action"&&C.method==="POST"){let we=await se(C),Ae=br.get(String(we.id??""));if(!Ae||!F(Ae.resourceId))return b({ok:!1,error:"Scheduled job was not found."},404);let et=String(we.action??"");if(et==="run"){let ut=fp.enqueue(Ae,{trigger:"manual",actorId:X?.id});return Be("run_queued",{jobId:Ae.id,executionId:ut.id},Ae.resourceId),b({ok:!0,execution:ut},202)}if(["disable","delete"].includes(et)&&d?.kind==="production"){if(String(we.confirm??"")!==et)return b({ok:!1,error:`Type "${et}" to confirm this production change.`},409);if(!He())return b({ok:!1,error:"Recent authentication is required for this production change.",stepUpRequired:!0},401)}if(et==="enable"||et==="disable"){let ut=br.setEnabled(Ae.id,et==="enable");return Be(et==="enable"?"enabled":"disabled",{jobId:Ae.id},Ae.resourceId),b({ok:!0,job:ut})}if(et==="delete")try{return br.remove(Ae.id),Be("deleted",{jobId:Ae.id,name:Ae.name},Ae.resourceId),b({ok:!0,deleted:Ae.id})}catch(ut){return b({ok:!1,error:ut instanceof Error?ut.message:"Scheduled job could not be deleted."},409)}return b({ok:!1,error:"Action must be run, enable, disable, or delete."},422)}if(L.pathname==="/api/jobs/history"&&C.method==="GET"){let we=br.get(String(L.searchParams.get("jobId")??""));if(!we||!F(we.resourceId))return b({ok:!1,error:"Scheduled job was not found."},404);return b({ok:!0,executions:br.listExecutions(we.id,Number(L.searchParams.get("limit"))||100).map((Ae)=>({...Ae,logs:Ae.operationId?At.logs(Ae.operationId,{limit:500}):[]}))})}if(L.pathname==="/api/jobs/reconcile"&&C.method==="POST"){if(!d)return b({ok:!1,error:"Environment was not found."},404);let we=Kr(br,o,{organization:a.organization,project:a.project,environment:d,resources:l});return Be("reconciled",we),b({ok:!0,reconciliation:we})}if(L.pathname==="/api/workers"&&C.method==="GET"){let we=Array.isArray(j.workersDetail??j.workers)?j.workersDetail??j.workers:[];return b({ok:!0,workers:br.listWorkers(a.project.id,d?.id).filter((Ae)=>F(Ae.resourceId)).map((Ae)=>{let et=we.find((ut)=>ut.name===Ae.name||ut.site===Ae.target.site);return et?{...Ae,observedState:{...Ae.observedState,status:et.status??"configured",currentJob:et.currentJob??null,failures:Number(et.failed??et.failures)||0,processed:Number(et.processed)||0}}:Ae})})}if(L.pathname==="/api/workers/action"&&C.method==="POST"){let we=await se(C),Ae=br.getWorker(String(we.id??""));if(!Ae||!F(Ae.resourceId))return b({ok:!1,error:"Worker was not found."},404);let et=String(we.action??"");if(et==="restart"){if(String(we.confirm??"")!==Ae.name)return b({ok:!1,error:`Type "${Ae.name}" to restart this worker.`},409);let ut=Z.find((Xt)=>Xt.id===Ae.target.operationId);if(!ut)return b({ok:!1,error:"The allowlisted worker restart operation is unavailable."},409);let St=await qr(o,ye,ut),bn=br.reconcileWorker(Ae.id,St.ok?"in_sync":"unavailable",{...Ae.observedState,lastRestartAt:new Date().toISOString(),command:St.command??null,error:St.error??St.stderr??null});return Be("worker_restarted",{workerId:Ae.id,ok:St.ok},Ae.resourceId),b({...St,worker:bn},St.ok?200:409)}if(et==="scale")return b({ok:!1,error:Ae.provider==="systemd"?"Systemd worker scale is config-managed; edit the worker definition and reconcile.":"This provider does not expose safe worker scaling through the current adapter."},422);return b({ok:!1,error:"Action must be restart or scale."},422)}}if(L.pathname.startsWith("/api/telemetry/")){let d=a.environments.get(ye),l=new Ye(a.store),k=a.store.listResources(a.project.id,d?.id),M=["/api/telemetry/query","/api/telemetry/tail","/api/telemetry/export","/api/telemetry/saved-queries","/api/telemetry/refresh"].includes(L.pathname)?"runtime:logs":"runtime:read",F=ue.role==="admin"||!!d&&la(ue,d.id,M),X=F?k:k.filter((ve)=>Sr(ue,ve.id,M)),j=(ve)=>Zy(X,F,ve),Z=(ve)=>{let Be=new Date,we={"1h":3600000,"6h":21600000,"24h":86400000,"7d":604800000,"30d":2592000000},Ae=String(ve.to??Be.toISOString()),et=String(ve.from??new Date(new Date(Ae).getTime()-(we[String(ve.range??"1h")]??we["1h"])).toISOString()),ut=(bn)=>{let Xt=(Array.isArray(bn)?bn:String(bn??"").split(",")).map(String).filter(Boolean);return Xt.length?Xt:void 0},St=ut(ve.kinds)?.filter((bn)=>["metric","log","trace","request","event"].includes(bn));return{projectId:a.project.id,environmentId:d?.id,resourceIds:j(ve.resources),kinds:St,names:ut(ve.names),sources:ut(ve.sources),levels:ut(ve.levels),from:et,to:Ae,text:String(ve.text??"")||void 0,traceId:String(ve.traceId??"")||void 0,requestId:String(ve.requestId??"")||void 0,deploymentId:String(ve.deploymentId??"")||void 0,releaseId:String(ve.releaseId??"")||void 0,workloadId:String(ve.workloadId??"")||void 0,cursor:String(ve.cursor??"")||void 0,limit:Number(ve.limit)||void 0}},fe=Object.fromEntries(L.searchParams.entries()),pe=(ve=!1)=>oi({controlPlane:a.store,projectId:a.project.id,environmentId:d?.id,config:o,environment:ye,force:ve,lightweight:!ve}),He=()=>{let ve=a.store.getSetting(`telemetry.collection:${a.project.id}:${d?.id??"all"}`)??{};return{generatedAt:String(ve.generatedAt??new Date().toISOString()),cached:!0,statuses:Array.isArray(ve.statuses)?ve.statuses:[],errors:Array.isArray(ve.errors)?ve.errors:[],policy:ve.policy??Qe(a.store,a.project.id)}};if(L.pathname==="/api/telemetry/status"&&C.method==="GET"){pe(!1);let ve=He(),Be=F?ve.statuses:l.status(a.project.id,d?.id,ve.policy.rawDays,ve.policy.samplingRate,X.map((Ae)=>Ae.id)),we=Be.reduce((Ae,et)=>Ae+et.estimatedDailyBytes*30,0);return b({ok:!0,generatedAt:ve.generatedAt,cached:ve.cached,sources:Be,errors:F?ve.errors:[],policy:ve.policy,retention:{rawDays:ve.policy.rawDays,downsampleAfterDays:ve.policy.downsampleAfterDays,downsampleBucketMs:ve.policy.downsampleBucketMs,maxRecords:ve.policy.maxRecords},estimatedMonthlyBytes:we,estimatedMonthlyCostUsd:hi(we,ve.policy),costEstimateConfigured:ve.policy.estimatedStorageUsdPerGbMonth>0})}if(L.pathname==="/api/telemetry/settings"&&C.method==="GET")return b({ok:!0,policy:Qe(a.store,a.project.id)});if(L.pathname==="/api/telemetry/settings"&&C.method==="PATCH"){let ve=fi(a.store,a.project.id,await se(C));return sb(a.project.id),b({ok:!0,policy:ve})}if(L.pathname==="/api/telemetry/query"&&C.method==="GET"){pe(!1);let ve=He();return b({ok:!0,collection:{generatedAt:ve.generatedAt,cached:ve.cached},...l.query(Z(fe))})}if(L.pathname==="/api/telemetry/tail"&&C.method==="GET"){pe(!1);let ve=new TextEncoder,Be=new Date,we=Z({...fe,kinds:fe.kinds||"log,request,event,trace",from:fe.from||new Date(Be.getTime()-120000).toISOString(),to:Be.toISOString(),limit:Math.min(1000,Number(fe.limit)||200),cursor:void 0}),Ae=C.headers.get("last-event-id")||String(fe.cursor??"")||void 0,et,ut=!1,St=!1,bn=new ReadableStream({start(Xt){let bo=()=>{if(ut)return;if(ut=!0,et)clearInterval(et);C.signal.removeEventListener("abort",bo);try{Xt.close()}catch{}},Rp=async()=>{if(ut||St)return;St=!0;try{let Uo=l.tail({...we,to:new Date(Date.now()+1000).toISOString()},Ae);for(let Pp of Uo.records)Ae=oo(Pp)??Ae,Xt.enqueue(ve.encode(`id: ${Ae??""}
500
500
  event: record
501
501
  data: ${JSON.stringify(Pp)}
502
502
 
@@ -506,6 +506,6 @@ data: ${JSON.stringify({message:Uo instanceof Error?Uo.message:String(Uo)})}
506
506
  `))}finally{St=!1}};Rp(),et=setInterval(()=>{if(Rp(),!ut)Xt.enqueue(ve.encode(`event: heartbeat
507
507
  data: ${JSON.stringify({cursor:Ae,at:new Date().toISOString()})}
508
508
 
509
- `))},5000),et.unref?.(),C.signal.addEventListener("abort",bo,{once:!0})},cancel(){if(ut=!0,et)clearInterval(et)}});return new Response(bn,{headers:{"cache-control":"no-cache, no-transform",connection:"keep-alive","content-type":"text/event-stream; charset=utf-8","x-accel-buffering":"no"}})}if(L.pathname==="/api/telemetry/series"&&C.method==="GET"){pe(!1);let ve=He(),Fe=["sum","avg","min","max","count","p50","p90","p95","p99"].includes(String(fe.aggregation))?fe.aggregation:"avg",we=Z({...fe,kinds:"metric",limit:5000}),Ae=l.series({...we,bucketMs:Number(fe.bucketMs)||60000,aggregation:Fe,timezone:String(fe.timezone??"UTC"),compareFrom:fe.compareFrom,compareTo:fe.compareTo});return b({ok:!0,collection:{generatedAt:ve.generatedAt,cached:ve.cached},query:{aggregation:Fe,bucketMs:Number(fe.bucketMs)||60000,timezone:String(fe.timezone??"UTC")},series:Ae})}if(L.pathname==="/api/telemetry/refresh"&&C.method==="POST")return b({ok:!0,...await pe(!0)});if(L.pathname==="/api/telemetry/export"&&C.method==="POST"){let ve=await se(C);await pe(!1);let Fe=l.query({...Z(ve),limit:Math.min(5000,Number(ve.limit)||5000),cursor:void 0});if((ve.format==="csv"?"csv":"json")==="json")return new Response(JSON.stringify({exportedAt:new Date().toISOString(),query:Z(ve),...Fe},null,2),{headers:{"content-disposition":'attachment; filename="ts-cloud-telemetry.json"',"content-type":"application/json; charset=utf-8"}});let Ae=["timestamp","kind","source","name","level","value","unit","message","traceId","requestId","deploymentId","releaseId","workloadId"],et=[Ae.join(","),...Fe.records.map((ut)=>Ae.map((St)=>`"${String(ut[St]??"").replaceAll('"','""')}"`).join(","))].join(`
510
- `);return new Response(et,{headers:{"content-disposition":'attachment; filename="ts-cloud-telemetry.csv"',"content-type":"text/csv; charset=utf-8"}})}if(L.pathname==="/api/telemetry/saved-queries"&&C.method==="GET"){let ve=Ne(ue);return b({ok:!0,queries:l.listSavedQueries(a.project.id,ve.actor?.id)})}if(L.pathname==="/api/telemetry/saved-queries"&&C.method==="POST"){let ve=await se(C),Fe=Ne(ue);return b({ok:!0,query:l.saveQuery(a.project.id,Fe.actor?.id,String(ve.name??""),Z(ve.query??ve))},201)}if(L.pathname==="/api/telemetry/saved-queries"&&C.method==="DELETE"){let ve=await se(C),Fe=Ne(ue),we=l.deleteSavedQuery(a.project.id,Fe.actor?.id,String(ve.id??""));return b({ok:we},we?200:404)}}if(L.pathname.startsWith("/api/configuration")){let d=a.environments.get(ye),l=ue.role==="admin"||!!Tn.capabilities?.includes("secrets:read"),k=ue.role==="admin"||!!Tn.capabilities?.includes("secrets:write"),M={projectId:a.project.id,environmentId:d?.id},B={"cache-control":"no-store"};if(L.pathname==="/api/configuration"&&C.method==="GET"){let X=Object.fromEntries(L.searchParams),j=X.scopeType||X.scopeId?aa(X,M):void 0,Z=["variable","secret"].includes(String(X.kind))?X.kind:void 0,fe=j?.type==="preview"?Wt.previews.getInstance(j.id):void 0,pe=fe?Wt.previews.getDefinition(fe.definitionId):void 0,He=j?await ln.resolve({projectId:a.project.id,environmentId:j.environmentId,resourceId:j.resourceId,functionId:j.type==="function"?j.id:void 0,previewId:j.previewId,trustedPreview:!!fe&&!fe.fork,allowedPreviewSecrets:pe?.inheritedSecrets,nativeReferences:!0,canReadSecretMetadata:l}):void 0,ve=a.store.listResources(a.project.id);return b({ok:!0,entries:ln.list({projectId:a.project.id,scope:j,kind:Z,search:X.search,canReadSecretMetadata:l}),effectiveEntries:He?Object.values(He.entries).filter((Fe)=>!Z||Fe.kind===Z).filter((Fe)=>!X.search||Fe.key.toLowerCase().includes(String(X.search).toLowerCase())):[],configurationHash:He?.configurationHash,warnings:He?.warnings??[],scopes:{project:a.project,environments:a.store.listEnvironments(a.project.id),resources:ve.filter((Fe)=>Fe.kind!=="function"),functions:ve.filter((Fe)=>Fe.kind==="function"),previews:Wt.previews.listInstances({projectId:a.project.id}).filter((Fe)=>Fe.status!=="destroyed").map((Fe)=>({id:Fe.id,name:Fe.name,environmentId:Fe.baseEnvironmentId,resourceId:Fe.resourceId,fork:Fe.fork,status:Fe.status}))}},200,B)}if(L.pathname==="/api/configuration/export"&&C.method==="GET"){let X=aa(Object.fromEntries(L.searchParams),M);return new Response(ln.exportVariables({projectId:a.project.id,scope:X}),{headers:{...B,"content-disposition":'attachment; filename="ts-cloud.env"',"content-type":"text/plain; charset=utf-8"}})}if(L.pathname==="/api/configuration/plan"&&C.method==="POST"){let X=await se(C),j=aa(X,M),Z=X.values&&typeof X.values==="object"&&!Array.isArray(X.values)?Object.fromEntries(Object.entries(X.values).map(([fe,pe])=>[fe,String(pe)])):{};return b({ok:!0,plan:ln.plan({projectId:a.project.id,scope:j,values:Z,removeMissing:X.removeMissing===!0})},200,B)}if(L.pathname==="/api/configuration"&&C.method==="POST"){let X=await se(C),j=aa(X,M),Z=X.kind==="secret"?"secret":"variable",fe=String(X.key??"");if(Z==="secret"&&!k)return b({ok:!1,error:"Secret write permission is required."},403,B);try{let pe=await ln.set({organizationId:a.organization.id,projectId:a.project.id,scope:j,key:fe,kind:Z,value:X.value==null?void 0:String(X.value),reference:X.reference==null?void 0:String(X.reference),backend:X.backend,required:X.required===!0,expectedVersion:X.expectedVersion==null?void 0:Number(X.expectedVersion),confirmed:String(X.confirm??"")===fe,idempotencyKey:C.headers.get("idempotency-key")??X.idempotencyKey,actorId:Ne(ue).actor?.id});return b({ok:!0,entry:ln.list({projectId:a.project.id,scope:j,canReadSecretMetadata:l}).find((He)=>He.id===pe.entry.id),mutation:pe.mutation,warnings:pe.warnings},pe.mutation.added.length?201:200,B)}catch(pe){return b({ok:!1,error:pe instanceof Error?pe.message:String(pe)},409,B)}}if(L.pathname==="/api/configuration/import"&&C.method==="POST"){let X=await se(C),j=aa(X,M),Z=Array.isArray(X.secretKeys)?X.secretKeys.map(String):[];if(Z.length&&!k)return b({ok:!1,error:"Secret write permission is required."},403,B);try{let fe=await ln.importDotenv({organizationId:a.organization.id,projectId:a.project.id,scope:j,source:String(X.source??""),secretKeys:Z,backend:X.backend,confirmed:X.confirm==="import",idempotencyKey:C.headers.get("idempotency-key")??X.idempotencyKey,actorId:Ne(ue).actor?.id});return b({ok:fe.document.valid,diagnostics:fe.document.diagnostics,mutation:fe.mutation,warnings:fe.warnings},fe.document.valid?200:422,B)}catch(fe){return b({ok:!1,error:fe instanceof Error?fe.message:String(fe)},409,B)}}if(L.pathname==="/api/configuration/dependencies"&&C.method==="POST"){let X=await se(C),j=po.get(String(X.entryId??"")),Z=a.store.getResource(String(X.resourceId??""));if(!j||j.projectId!==a.project.id||!Z||Z.projectId!==a.project.id)return b({ok:!1,error:"Configuration entry or dependent resource was not found."},404,B);return b({ok:!0,dependency:po.setDependency({entryId:j.id,resourceId:Z.id,injectionTarget:["native_reference","file"].includes(String(X.injectionTarget))?X.injectionTarget:"environment",required:X.required!==!1,requiresRedeploy:X.requiresRedeploy!==!1,lastDeployedVersion:X.lastDeployedVersion==null?void 0:Number(X.lastDeployedVersion)})},200,B)}if(L.pathname==="/api/configuration/transfer"&&C.method==="POST"){let X=await se(C),j=po.get(String(X.id??"")),Z=aa({...X,scopeType:X.targetScopeType,scopeId:X.targetScopeId},M);if(!j||j.projectId!==a.project.id)return b({ok:!1,error:"Configuration entry was not found."},404,B);if(j.kind==="secret"&&!k)return b({ok:!1,error:"Secret write permission is required."},403,B);try{let fe=await ln.transfer({entryId:j.id,targetScope:Z,mode:X.mode==="move"?"move":"copy",confirmed:X.confirm===j.key,actorId:Ne(ue).actor?.id,idempotencyKey:C.headers.get("idempotency-key")??X.idempotencyKey});return b({ok:!0,entry:ln.list({projectId:a.project.id,scope:Z,canReadSecretMetadata:l}).find((pe)=>pe.id===fe.entry.id),mutation:fe.mutation},200,B)}catch(fe){return b({ok:!1,error:fe instanceof Error?fe.message:String(fe)},409,B)}}if(L.pathname==="/api/configuration/bulk"&&C.method==="POST"){let X=await se(C),j=Array.isArray(X.ids)?X.ids.map(String).slice(0,500):[],Z=j.map((pe)=>po.get(pe)).filter((pe)=>!!pe&&pe.projectId===a.project.id);if(Z.length!==j.length)return b({ok:!1,error:"One or more configuration entries were not found."},404,B);if(Z.some((pe)=>pe.kind==="secret")&&!k)return b({ok:!1,error:"Secret write permission is required."},403,B);if(X.action!=="delete"||X.confirm!=="bulk")return b({ok:!1,error:"Bulk deletion requires action delete and confirm bulk."},409,B);let fe=[];try{for(let pe of Z)fe.push(await ln.remove({entryId:pe.id,expectedVersion:pe.version,confirmed:!0,actorId:Ne(ue).actor?.id}));return b({ok:!0,removed:fe.flatMap((pe)=>pe.removed),affectedResourceIds:[...new Set(fe.flatMap((pe)=>pe.affectedResourceIds))].sort()},200,B)}catch(pe){return b({ok:!1,error:pe instanceof Error?pe.message:String(pe),partial:fe.flatMap((He)=>He.removed)},409,B)}}if(L.pathname==="/api/configuration/reveal"&&C.method==="POST"){let X=await se(C),j=jt.resolveSession(C);try{return b({ok:!0,value:await ln.reveal({entryId:String(X.id??""),canRevealSecrets:l,recentlyAuthenticated:!Pe||!!j&&Ie.isRecentlyAuthenticated(j),actorId:Ne(ue).actor?.id})},200,B)}catch(Z){return b({ok:!1,error:Z instanceof Error?Z.message:String(Z)},403,B)}}if(L.pathname==="/api/configuration"&&C.method==="DELETE"){let X=await se(C),j=po.get(String(X.id??""));if(j?.kind==="secret"&&!k)return b({ok:!1,error:"Secret write permission is required."},403,B);if(!j||j.projectId!==a.project.id)return b({ok:!1,error:"Configuration entry was not found."},404,B);try{return b({ok:!0,mutation:await ln.remove({entryId:j.id,expectedVersion:Number(X.expectedVersion),confirmed:String(X.confirm??"")===j.key,actorId:Ne(ue).actor?.id})},200,B)}catch(Z){return b({ok:!1,error:Z instanceof Error?Z.message:String(Z)},409,B)}}}if(L.pathname.startsWith("/api/fleet")){let d=Ne(ue).actor?.id,l=(k,M=409)=>b({ok:!1,error:k instanceof Error?k.message:String(k)},M,{"cache-control":"no-store"});if(L.pathname==="/api/fleet"&&C.method==="GET")return b({ok:!0,servers:ua.list(a.project.id),resources:a.store.listResources(a.project.id),operations:At.list({projectId:a.project.id,limit:200}).filter((k)=>k.operation.kind.startsWith("fleet."))},200,{"cache-control":"no-store"});if(L.pathname==="/api/fleet"&&C.method==="POST"){let k=await se(C);try{return b({ok:!0,server:xi.enroll({organizationId:a.organization.id,projectId:a.project.id,name:String(k.name??""),provider:["aws","hetzner"].includes(String(k.provider))?k.provider:"ssh",providerId:k.providerId?String(k.providerId):void 0,region:k.region?String(k.region):void 0,zone:k.zone?String(k.zone):void 0,endpoint:String(k.endpoint??""),sshUser:String(k.sshUser??"deploy"),sshPort:k.sshPort?Number(k.sshPort):22,credentialRef:String(k.credentialRef??""),roles:Array.isArray(k.roles)?k.roles:[],labels:k.labels&&typeof k.labels==="object"?k.labels:{}})},201)}catch(M){return l(M,422)}}if(L.pathname==="/api/fleet/action"&&C.method==="POST"){let k=await se(C),M=String(k.id??""),B=String(k.action??"");try{if(B==="test")return b({ok:!0,server:await xi.test(M)});if(B==="validate")return b({ok:!0,server:await xi.validate(M)});if(B==="review_host_key")return b({ok:!0,server:xi.reviewHostKey(M,String(k.fingerprint??""))});if(B==="bootstrap")return b({ok:!0,...xi.bootstrap(M,k.confirmed===!0)},k.confirmed===!0?202:200);if(B==="heartbeat")return b({ok:!0,server:xi.heartbeat(M,{usage:k.usage&&typeof k.usage==="object"?k.usage:{}})});if(B==="drain")return b({ok:!0,server:xi.drain(M,k.completed===!0)});if(B==="uncordon")return b({ok:!0,server:xi.uncordon(M)});if(B==="archive")return b({ok:!0,server:xi.archive(M,String(k.confirmation??""))});return l("Unsupported fleet action.",422)}catch(X){return l(X)}}}if(L.pathname.startsWith("/api/capacity")){let d=(l,k=409)=>b({ok:!1,error:l instanceof Error?l.message:String(l)},k,{"cache-control":"no-store"});if(L.pathname==="/api/capacity"&&C.method==="GET")return b({ok:!0,pools:fo.listPools(a.project.id),placements:fo.listPlacements(a.project.id),servers:ua.list(a.project.id)},200,{"cache-control":"no-store"});if(L.pathname==="/api/capacity"&&C.method==="POST"){let l=await se(C);try{return b({ok:!0,pool:fo.createPool({organizationId:a.organization.id,projectId:a.project.id,name:String(l.name??""),purpose:String(l.purpose??"application"),backend:String(l.backend??"server"),region:l.region?String(l.region):void 0,architecture:l.architecture?String(l.architecture):void 0,labels:l.labels&&typeof l.labels==="object"?l.labels:{},requiredServerLabels:l.requiredServerLabels&&typeof l.requiredServerLabels==="object"?l.requiredServerLabels:{},toleratedTaints:Array.isArray(l.toleratedTaints)?l.toleratedTaints.map(String):[],capacity:l.capacity&&typeof l.capacity==="object"?l.capacity:{},maxWorkloads:Number(l.maxWorkloads??10),costWeight:Number(l.costWeight??1),spreadKey:l.spreadKey?String(l.spreadKey):void 0,concurrency:Number(l.concurrency??1),ephemeralWorkspaces:!0,allowProductionSecrets:!1,status:"active"})},201)}catch(k){return d(k,422)}}if(L.pathname==="/api/capacity/member"&&C.method==="POST"){let l=await se(C);try{return fo.addMember(String(l.poolId??""),String(l.serverId??"")),b({ok:!0,pool:fo.getPool(String(l.poolId??""))})}catch(k){return d(k,422)}}if(L.pathname==="/api/capacity/explain"&&C.method==="POST"){let l=await se(C);try{return b({ok:!0,decisions:pp.explain(a.project.id,{purpose:String(l.purpose??"application"),resources:l.resources&&typeof l.resources==="object"?l.resources:{},region:l.region?String(l.region):void 0,architecture:l.architecture?String(l.architecture):void 0,labels:l.labels&&typeof l.labels==="object"?l.labels:{}})})}catch(k){return d(k,422)}}if(L.pathname==="/api/capacity/action"&&C.method==="POST"){let l=await se(C);try{if(l.action==="drain")return b({ok:!0,...pp.drainPool(String(l.poolId??""))});if(l.action==="enable")return b({ok:!0,pool:fo.updatePool(String(l.poolId??""),{status:"active"})});if(l.action==="disable")return b({ok:!0,pool:fo.updatePool(String(l.poolId??""),{status:"disabled"})});return d("Unsupported capacity action.",422)}catch(k){return d(k,422)}}}if(L.pathname.startsWith("/api/regions")){let d=(l,k=409)=>b({ok:!1,error:l instanceof Error?l.message:String(l)},k,{"cache-control":"no-store"});if(L.pathname==="/api/regions"&&C.method==="GET")return b({ok:!0,topologies:Fo.list(a.project.id).map((l)=>({topology:l,targets:Fo.targets(l.id),channels:Fo.channels(l.id),route:Fo.route(l.id),executions:Fo.executions(l.id)}))},200,{"cache-control":"no-store"});if(L.pathname==="/api/regions"&&C.method==="POST"){let l=await se(C);try{return b({ok:!0,topology:gp.create({organizationId:a.organization.id,projectId:a.project.id,environmentId:a.environments.get(ye)?.id,name:String(l.name??""),hostname:String(l.hostname??""),regions:Array.isArray(l.regions)?l.regions:[],trafficPolicy:l.trafficPolicy==="weighted"||l.trafficPolicy==="latency"?l.trafficPolicy:"active_passive",dataPolicy:{replicate:Array.isArray(l.replicate)?l.replicate:["s3","dynamodb","secrets"],maxLagSeconds:Number(l.maxLagSeconds??30),retainOnDestroy:l.retainOnDestroy!==!1},dnsProvider:"route53",cdnEnabled:l.cdnEnabled===!0,wafEnabled:l.wafEnabled===!0})},201)}catch(k){return d(k,422)}}if(L.pathname==="/api/regions/action"&&C.method==="POST"){let l=await se(C);try{return b({ok:!0,...gp.enqueue({topologyId:String(l.topologyId??""),kind:String(l.action??""),targetRegion:l.targetRegion?String(l.targetRegion):void 0,revision:l.revision?String(l.revision):void 0,manifest:l.manifest&&typeof l.manifest==="object"?l.manifest:{},confirmation:l.confirmation?String(l.confirmation):void 0,deleteData:l.deleteData===!0})},202)}catch(k){return d(k,422)}}}if(L.pathname.startsWith("/api/maintenance")){let d=(l,k=409)=>b({ok:!1,error:l instanceof Error?l.message:String(l)},k,{"cache-control":"no-store"});if(L.pathname==="/api/maintenance"&&C.method==="GET")return b({ok:!0,manifests:ji.manifests(a.organization.id),windows:ji.windows(a.project.id),campaigns:ji.campaigns(a.project.id).map((l)=>({campaign:l,targets:ji.targets(l.id)})),cleanups:ji.cleanups(a.project.id),drills:ji.drills(a.project.id)},200,{"cache-control":"no-store"});if(L.pathname==="/api/maintenance/cleanup-preview"&&C.method==="POST"){let l=await se(C);try{return b({ok:!0,plan:await Od.previewCleanup({projectId:a.project.id,kind:String(l.kind??"operations"),criteria:{olderThanDays:Number(l.olderThanDays??30)}},mp)},201)}catch(k){return d(k,422)}}if(L.pathname==="/api/maintenance/cleanup-apply"&&C.method==="POST"){let l=await se(C);try{return b({ok:!0,...Od.enqueueCleanup(String(l.planId??""),String(l.confirmation??""))},202)}catch(k){return d(k,422)}}if(L.pathname==="/api/maintenance/drill"&&C.method==="POST"){let l=await se(C);try{return b({ok:!0,drill:ji.createDrill({projectId:a.project.id,scenario:String(l.scenario??"control_plane"),isolatedTarget:String(l.isolatedTarget??""),expectedRpoMinutes:Number(l.expectedRpoMinutes??60),expectedRtoMinutes:Number(l.expectedRtoMinutes??30),recoveryPointId:l.recoveryPointId?String(l.recoveryPointId):void 0,topologyId:l.topologyId?String(l.topologyId):void 0})},201)}catch(k){return d(k,422)}}if(L.pathname==="/api/maintenance/drill-run"&&C.method==="POST"){let l=await se(C);try{return b({ok:!0,...Od.enqueueDrill(String(l.drillId??""))},202)}catch(k){return d(k,422)}}}if(L.pathname.startsWith("/api/volumes")){let d=a.environments.get(ye),l=Ne(ue).actor?.id,k=(M,B=409)=>b({ok:!1,error:M instanceof Error?M.message:String(M)},B,{"cache-control":"no-store"});if(L.pathname==="/api/volumes"&&C.method==="GET"){let M=xd.inventory(a.project.id,d?.id),B=a.store.listResources(a.project.id,d?.id).map((X)=>({id:X.id,name:X.name,slug:X.slug,kind:X.kind,provider:X.provider,providerId:X.providerId}));return b({ok:!0,volumes:M,resources:B,operations:At.list({projectId:a.project.id,limit:100}).filter((X)=>X.operation.kind.startsWith("volume.")),recoveryPoints:Qt.listRecoveryPoints(a.project.id).filter((X)=>X.kind==="volume"),providers:Dd.map((X)=>({provider:X.provider,type:X.type,capabilities:X.capabilities()}))},200,{"cache-control":"no-store"})}if(L.pathname==="/api/volumes"&&C.method==="POST"){let M=await se(C);try{return b({ok:!0,...Fi.create({organizationId:a.organization.id,projectId:a.project.id,environmentId:d?.id,resourceId:M.resourceId?String(M.resourceId):void 0,name:String(M.name??""),provider:String(M.provider??"docker"),type:M.type==="docker"?"docker":M.type,capacityBytes:M.capacityBytes==null?void 0:Number(M.capacityBytes),filesystem:M.filesystem?String(M.filesystem):void 0,encrypted:M.encrypted===!0,desiredState:M.desiredState&&typeof M.desiredState==="object"?M.desiredState:{},actorId:l})},202,{"cache-control":"no-store"})}catch(B){return k(B,422)}}if(L.pathname==="/api/volumes/attach"&&C.method==="POST"){let M=await se(C);try{return b({ok:!0,...Fi.attach(String(M.volumeId??""),{resourceId:String(M.resourceId??""),targetPath:String(M.targetPath??""),readOnly:M.readOnly===!0,uid:M.uid==null?void 0:Number(M.uid),gid:M.gid==null?void 0:Number(M.gid),mode:M.mode?String(M.mode):void 0,propagation:M.propagation,driverOptions:M.driverOptions&&typeof M.driverOptions==="object"?M.driverOptions:{},actorId:l})},202)}catch(B){return k(B,422)}}if(L.pathname==="/api/volumes/detach"&&C.method==="POST"){let M=await se(C);try{return b({ok:!0,...Fi.detach(String(M.volumeId??""),String(M.attachmentId??""),{force:M.force===!0,drained:M.drained===!0,unmounted:M.unmounted===!0,confirmation:M.confirmation?String(M.confirmation):void 0,actorId:l})},202)}catch(B){return k(B)}}if(L.pathname==="/api/volumes/resize"&&C.method==="POST"){let M=await se(C);try{return b({ok:!0,...Fi.resize(String(M.volumeId??""),Number(M.capacityBytes),{drained:M.drained===!0,actorId:l})},202)}catch(B){return k(B,422)}}if(L.pathname==="/api/volumes/snapshot"&&C.method==="POST"){let M=await se(C);try{return b({ok:!0,...Fi.snapshot(String(M.volumeId??""),{name:M.name?String(M.name):void 0,actorId:l})},202)}catch(B){return k(B,422)}}if(L.pathname==="/api/volumes/restore"&&C.method==="POST"){let M=await se(C);try{return b({ok:!0,...Fi.restore(String(M.snapshotId??""),{name:String(M.name??""),actorId:l})},202)}catch(B){return k(B,422)}}if(L.pathname==="/api/volumes/discover"&&C.method==="POST")try{return b({ok:!0,volumes:await Fi.discover({organizationId:a.organization.id,projectId:a.project.id,environmentId:d?.id,actorId:l})})}catch(M){return k(M,502)}if(L.pathname==="/api/volumes/adopt"&&C.method==="POST"){let M=await se(C);try{return b({ok:!0,volume:Fi.adopt(String(M.volumeId??""),{name:String(M.name??""),actorId:l})})}catch(B){return k(B,422)}}if(L.pathname==="/api/volumes"&&C.method==="DELETE"){let M=await se(C),B=jt.resolveSession(C);try{return b({ok:!0,...Fi.delete(String(M.volumeId??""),{recentAuthAt:!Pe||B&&Ie.isRecentlyAuthenticated(B)?new Date().toISOString():void 0,confirmation:M.confirmation?String(M.confirmation):void 0,backupOverride:M.backupOverride===!0,backupOverrideConfirmation:M.backupOverrideConfirmation?String(M.backupOverrideConfirmation):void 0,actorId:l})},202)}catch(X){return k(X)}}}if(L.pathname==="/api/backups"&&C.method==="GET"){let d=a.environments.get(ye),l=Qt.listPolicies(a.project.id,d?.id),k=new Set(l.map((Z)=>Z.id)),M=Qt.listRecoveryPoints(a.project.id).filter((Z)=>!Z.policyId||k.has(Z.policyId)),B=Qt.listJobs(a.project.id).filter((Z)=>!Z.policyId||k.has(Z.policyId)),X=(Z)=>({...Z,credentialRef:void 0,encryptionKeyRef:void 0,credentialsConfigured:!!Z.credentialRef,clientEncryptionConfigured:!!Z.encryptionKeyRef}),j=await Promise.all(Qt.listDestinations(a.project.id).map(async(Z)=>({...X(Z),credentialStatus:await Qg(Z,Bi)})));return b({ok:!0,destinations:j,policies:l,recoveryPoints:M,jobs:B,coverage:Qt.coverage(a.project.id).filter((Z)=>k.has(Z.policy.id)),resources:d?a.store.listResources(a.project.id,d.id).map((Z)=>({id:Z.id,name:Z.name,slug:Z.slug,kind:Z.kind})):[]})}if(L.pathname==="/api/backups/destinations"&&C.method==="POST"){let d=await se(C),l=String(d.name??"").trim(),k=String(d.provider??""),M=String(d.encryption??"provider"),B=`secret://data-services/backups/${a.project.id}/${l}`,X=[];if(!["aws_s3","s3_compatible","aws_backup"].includes(k))return b({ok:!1,error:"A supported backup destination provider is required."},422);if(!["provider","client_side","both"].includes(M))return b({ok:!1,error:"Encryption must be provider, client_side, or both."},422);try{let j,Z;if(d.credentials&&typeof d.credentials==="object"&&!Array.isArray(d.credentials))j=`${B}/credentials`,await Bi.put(j,JSON.stringify(d.credentials)),X.push(j);if(M!=="provider"){let pe=String(d.encryptionKey??"");if(pe.length<32)throw Error("Client-side encryption keys must contain at least 32 characters.");Z=`${B}/encryption-key`,await Bi.put(Z,pe),X.push(Z)}let fe=Qt.createDestination({organizationId:a.organization.id,projectId:a.project.id,name:l,provider:k,endpoint:d.endpoint?String(d.endpoint):void 0,endpointPolicy:d.endpointPolicy==="allow_private"?"allow_private":"public_https",bucket:d.bucket?String(d.bucket):void 0,prefix:String(d.prefix??""),region:d.region?String(d.region):mo,forcePathStyle:d.forcePathStyle===!0,credentialRef:j,encryption:M,encryptionKeyRef:Z,immutability:d.immutability&&typeof d.immutability==="object"&&!Array.isArray(d.immutability)?d.immutability:{},status:"untested"});return b({ok:!0,destination:{...fe,credentialRef:void 0,encryptionKeyRef:void 0,credentialsConfigured:!!j,clientEncryptionConfigured:!!Z}},201)}catch(j){for(let Z of X)await Bi.remove(Z).catch(()=>{});return b({ok:!1,error:j instanceof Error?j.message:String(j)},422)}}if(L.pathname==="/api/backups/destinations/test"&&C.method==="POST"){let d=await se(C),l=Qt.getDestination(String(d.id??""));if(!l||l.projectId!==a.project.id)return b({ok:!1,error:"Backup destination was not found."},404);if(l.provider==="aws_backup")return b({ok:!1,error:"AWS Backup destinations are verified by creating a provider recovery point."},422);try{return await lp.test(l),b({ok:!0,destination:Qt.recordDestinationTest(l.id,{ok:!0})})}catch(k){let M=k instanceof Error?k.message:String(k);return Qt.recordDestinationTest(l.id,{ok:!1,error:M}),b({ok:!1,error:M},502)}}if(L.pathname==="/api/backups/policies"&&C.method==="POST"){let d=await se(C),l=a.environments.get(ye),k=Qt.getDestination(String(d.destinationId??"")),M=String(d.resourceKind??""),B=d.dataServiceId?String(d.dataServiceId):void 0,X=B?Mt.get(B):void 0,j=d.resourceId?String(d.resourceId):void 0,Z=j?a.store.getResource(j):void 0;if(!l)return b({ok:!1,error:"Environment was not found."},404);if(!k||k.projectId!==a.project.id)return b({ok:!1,error:"Backup destination was not found."},404);if(!["managed_database","logical_database","volume","files","control_plane","infrastructure"].includes(M))return b({ok:!1,error:"A supported backup resource kind is required."},422);if(B&&(!X||X.projectId!==a.project.id||X.environmentId!==l.id))return b({ok:!1,error:"Data service was not found in this environment."},404);if(j&&(!Z||Z.projectId!==a.project.id||Z.environmentId!==l.id))return b({ok:!1,error:"Resource was not found in this environment."},404);if(M==="managed_database"&&!X)return b({ok:!1,error:"Managed database policies require a data service."},422);if(M==="logical_database"&&(!X||!["container","server"].includes(X.provider)))return b({ok:!1,error:"Logical database policies require an on-box data service."},422);if(M==="volume"&&(!Z||!/^[A-Za-z0-9][A-Za-z0-9_.-]{1,127}$/.test(String(d.volumeName??""))))return b({ok:!1,error:"Volume policies require a scoped resource and valid volumeName."},422);let fe=Array.isArray(d.includePatterns)?d.includePatterns.map(String).filter(Boolean):[];if(M==="files"&&(!Z||!fe.length))return b({ok:!1,error:"File policies require a scoped resource and at least one project-relative include path."},422);if(M==="control_plane"&&k.encryption==="provider")return b({ok:!1,error:"Control-plane policies require a destination with client-side encryption."},422);if(M==="infrastructure"&&(k.provider!=="aws_backup"||!fe.some((pe)=>pe.startsWith("resource:arn:"))||!fe.some((pe)=>pe.startsWith("role:arn:"))))return b({ok:!1,error:"Infrastructure policies require an AWS Backup destination plus resource:<arn> and role:<arn> include values."},422);try{let pe=Qt.createPolicy({organizationId:a.organization.id,projectId:a.project.id,environmentId:l.id,resourceId:j,dataServiceId:B,destinationId:k.id,name:String(d.name??"").trim(),resourceKind:M,schedule:String(d.schedule??"daily"),timezone:String(d.timezone??"UTC"),retention:d.retention&&typeof d.retention==="object"&&!Array.isArray(d.retention)?d.retention:{keepLast:7,expireAfterDays:30},compression:["none","gzip","zstd"].includes(String(d.compression))?d.compression:"gzip",encryption:["destination","client_side","both"].includes(String(d.encryption))?d.encryption:"destination",includePatterns:M==="volume"?[String(d.volumeName),...fe]:fe,excludePatterns:Array.isArray(d.excludePatterns)?d.excludePatterns.map(String):[],expectedRpoMinutes:Math.max(1,Number(d.expectedRpoMinutes)||1440),expectedRtoMinutes:Math.max(1,Number(d.expectedRtoMinutes)||120),healthCheckId:d.healthCheckId?String(d.healthCheckId):void 0,enabled:d.enabled!==!1});return b({ok:!0,policy:pe},201)}catch(pe){return b({ok:!1,error:pe instanceof Error?pe.message:String(pe)},422)}}if(L.pathname==="/api/backups/run"&&C.method==="POST"){let d=await se(C),l=Qt.getPolicy(String(d.policyId??"")),k=a.environments.get(ye);if(!l||l.projectId!==a.project.id||l.environmentId!==k?.id)return b({ok:!1,error:"Backup policy was not found in this environment."},404);try{let M=Bo.enqueueBackup(l,new Date().toISOString(),Ne(ue).actor?.id);return b({ok:!0,job:M},202)}catch(M){return b({ok:!1,error:M instanceof Error?M.message:String(M)},409)}}if(L.pathname==="/api/backups/verify"&&C.method==="POST"){let d=await se(C),l=Qt.getRecoveryPoint(String(d.recoveryPointId??""));if(!l||l.projectId!==a.project.id)return b({ok:!1,error:"Recovery point was not found."},404);return b({ok:!0,job:Bo.enqueueVerification(l)},202)}if(L.pathname==="/api/backups/restore"&&C.method==="POST"){let d=await se(C),l=Qt.getRecoveryPoint(String(d.recoveryPointId??"")),k=d.mode==="in_place"?"in_place":"isolated",M=d.target&&typeof d.target==="object"&&!Array.isArray(d.target)?{...d.target,inPlace:k==="in_place"}:{inPlace:k==="in_place"},B=jt.resolveSession(C),X={mode:k,target:M,targetName:String(d.targetName??""),confirm:d.confirm?String(d.confirm):void 0,recentAuth:!Pe||!!B&&Ie.isRecentlyAuthenticated(B),downtimeAcknowledged:d.downtimeAcknowledged===!0,safetyBackupId:d.safetyBackupId?String(d.safetyBackupId):void 0};if(!l||l.projectId!==a.project.id)return b({ok:!1,error:"Recovery point was not found."},404);if(d.drill===!0&&k!=="isolated")return b({ok:!1,error:"Recovery drills must use an isolated target."},422);try{let j=Bo.planRestore(l,X);if(d.execute!==!0)return b({ok:!0,plan:j,executionCreated:!1});let Z=Bo.enqueueRestore(l,{...X,drill:d.drill===!0,actorId:Ne(ue).actor?.id});return b({ok:!0,plan:j,job:Z},202)}catch(j){return b({ok:!1,error:j instanceof Error?j.message:String(j)},409)}}if(L.pathname==="/api/backups/recovery-points"&&C.method==="POST"){let d=await se(C),l=Qt.getRecoveryPoint(String(d.id??""));if(!l||l.projectId!==a.project.id)return b({ok:!1,error:"Recovery point was not found."},404);if(d.held==null&&d.pinned==null)return b({ok:!1,error:"held or pinned must be provided."},422);return b({ok:!0,recoveryPoint:Qt.updateRecoveryPoint(l.id,{held:d.held==null?l.held:d.held===!0,pinned:d.pinned==null?l.pinned:d.pinned===!0})})}if(L.pathname==="/api/backups/retention"&&C.method==="POST")return b({ok:!0,jobs:Bo.enqueueRetention()},202);if(L.pathname==="/api/data-services/capabilities"&&C.method==="GET"){let d=String(L.searchParams.get("engine")??""),l=String(L.searchParams.get("provider")??"");if(!["postgres","mysql","mariadb","redis","mongodb","libsql"].includes(d)||!["aws_rds","aws_aurora","aws_elasticache","server","container","external"].includes(l))return b({ok:!1,error:"A supported engine and provider are required."},422);return b({ok:!0,engine:d,provider:l,capabilities:Zt(d,l)})}if(L.pathname==="/api/data-services"&&C.method==="GET"){let d=a.environments.get(ye),l=Mt.list(a.project.id,d?.id).map((k)=>{let M=Mt.credential(k.id);return{...k,credentialRef:void 0,credential:M?{configured:!0,username:M.username,version:M.version,rotatedAt:M.rotatedAt}:void 0,dependencies:Mt.dependencies(k.id).map((B)=>({resourceId:B.resourceId,requiresRedeploy:B.requiresRedeploy}))}});return b({ok:!0,services:l})}if(L.pathname==="/api/data-services/preview"&&C.method==="POST"){let d=await se(C);if(d.id){let M=Mt.get(String(d.id)),B=a.environments.get(ye),X=String(d.action??"");if(!M||M.projectId!==a.project.id||M.environmentId!==B?.id)return b({ok:!1,error:"Data service was not found in this environment."},404);if(!Ad.includes(X))return b({ok:!1,error:`Action must be one of: ${Ad.join(", ")}.`},422);try{return b({ok:!0,plan:ja.plan(M,X,d.changes??{})})}catch(j){return b({ok:!1,error:j instanceof Error?j.message:String(j)},422)}}let l=String(d.engine??""),k=String(d.provider??"");if(!["postgres","mysql","mariadb","redis","mongodb","libsql"].includes(l)||!["aws_rds","aws_aurora","aws_elasticache","server","container","external"].includes(k))return b({ok:!1,error:"A supported engine and provider are required."},422);return b({ok:!0,capabilities:Zt(l,k),defaults:{publicExposure:!1,backupRetentionDays:7,deletionProtection:!0},productionExecutionCreated:!1})}if(L.pathname==="/api/data-services"&&C.method==="POST"){let d=await se(C),l=String(d.engine??""),k=String(d.provider??""),M=a.environments.get(ye),B=Ne(ue);if(!M)return b({ok:!1,error:"Environment was not found."},404);if(!["postgres","mysql","mariadb","redis","mongodb","libsql"].includes(l)||!["aws_rds","aws_aurora","aws_elasticache","server","container","external"].includes(k))return b({ok:!1,error:"A supported engine and provider are required."},422);let X={organizationId:a.organization.id,projectId:a.project.id,environmentId:M.id,resourceId:d.resourceId?String(d.resourceId):void 0,name:String(d.name??"").trim(),engine:l,provider:k,placement:String(d.placement??d.name??"").trim(),engineVersion:d.engineVersion?String(d.engineVersion):void 0,plan:String(d.plan??(k==="aws_elasticache"?"cache.t4g.micro":k==="aws_aurora"?"db.serverless":"db.t4g.micro")),storageGb:d.storageGb==null?void 0:Number(d.storageGb),highAvailability:d.highAvailability===!0,publicExposure:d.publicExposure===!0,allowedCidrs:Array.isArray(d.allowedCidrs)?d.allowedCidrs.map(String):[],desiredState:d.desiredState&&typeof d.desiredState==="object"&&!Array.isArray(d.desiredState)?d.desiredState:{},observedState:{},origin:d.adopt===!0?"adopted":"managed",managementEnabled:d.adopt!==!0,ownerActorId:B.actor?.id,username:d.username?String(d.username):void 0};try{if(d.adopt===!0){let Z=Mt.create({...X,status:"adopted",credentialRef:void 0});return b({ok:!0,service:Z,readOnly:!0},201)}if(!up({provider:k,engine:l}))return b({ok:!1,error:`No ${k}/${l} provisioning adapter is configured; adopt it read-only or choose a supported provider.`},422);let j=await ja.create(X);return b({ok:!0,service:j.service,operationId:j.operationId,oneTimeCredential:j.credential},201)}catch(j){return b({ok:!1,error:j instanceof Error?j.message:String(j)},422)}}if(L.pathname==="/api/data-services/connections"&&C.method==="GET"){let d=Mt.get(String(L.searchParams.get("id")??"")),l=a.environments.get(ye);if(!d||d.projectId!==a.project.id||d.environmentId!==l?.id)return b({ok:!1,error:"Data service was not found in this environment."},404);let k=typeof d.observedState.endpoint==="string"?d.observedState.endpoint:void 0,M=typeof d.observedState.readerEndpoint==="string"?d.observedState.readerEndpoint:void 0,B=Number(d.observedState.port)||(d.engine==="postgres"?5432:d.engine==="redis"?6379:d.engine==="mongodb"?27017:d.engine==="libsql"?8080:3306),X=typeof d.observedState.database==="string"?d.observedState.database:void 0,j=typeof d.observedState.tls==="boolean"?d.observedState.tls:d.provider.startsWith("aws_"),Z=[...k?[{type:d.publicExposure?"external":"internal",host:k,port:B,database:X,tls:j}]:[],...M?[{type:"internal",host:M,port:B,database:X,tls:j}]:[],{type:"tunnel",host:k??d.placement,port:B,database:X,tls:j}];return b({ok:!0,serviceId:d.id,guidance:Bn(d,Z)})}if(L.pathname==="/api/data-services/action"&&C.method==="POST"){let d=await se(C),l=Mt.get(String(d.id??"")),k=a.environments.get(ye),M=String(d.action??"");if(!l||l.projectId!==a.project.id||l.environmentId!==k?.id)return b({ok:!1,error:"Data service was not found in this environment."},404);if(!Ad.includes(M))return b({ok:!1,error:`Action must be one of: ${Ad.join(", ")}.`},422);let B=d.changes&&typeof d.changes==="object"&&!Array.isArray(d.changes)?d.changes:{};try{let X=ja.plan(l,M,B);if(d.execute!==!0)return b({ok:!0,plan:X,productionExecutionCreated:!1});let j=ja.enqueue(l,M,B,Ne(ue).actor?.id);return b({ok:!0,plan:X,operationId:j},202)}catch(X){return b({ok:!1,error:X instanceof Error?X.message:String(X)},409)}}if(L.pathname==="/api/data-services/dependencies"&&C.method==="POST"){let d=await se(C),l=Mt.get(String(d.id??"")),k=a.environments.get(ye),M=a.store.getResource(String(d.resourceId??""));if(!l||l.projectId!==a.project.id||l.environmentId!==k?.id)return b({ok:!1,error:"Data service was not found in this environment."},404);if(!M||M.projectId!==a.project.id||M.environmentId!==k?.id)return b({ok:!1,error:"Dependent resource was not found in this environment."},404);if(d.remove===!0)return b({ok:Mt.removeDependency(l.id,M.id)});return Mt.addDependency({serviceId:l.id,resourceId:M.id,secretRef:l.credentialRef??`secret://data-services/${l.projectId}/${l.name}`,requiresRedeploy:d.requiresRedeploy!==!1}),b({ok:!0,dependencies:Mt.dependencies(l.id).map((B)=>({resourceId:B.resourceId,requiresRedeploy:B.requiresRedeploy}))})}if(L.pathname==="/api/data-services/management"&&C.method==="POST"){let d=await se(C),l=Mt.get(String(d.id??"")),k=a.environments.get(ye);if(!l||l.projectId!==a.project.id||l.environmentId!==k?.id)return b({ok:!1,error:"Data service was not found in this environment."},404);if(l.origin!=="adopted"||d.reviewed!==!0||d.confirm!==l.name)return b({ok:!1,error:`Enabling management requires reviewed=true and typing ${l.name}.`},409);return b({ok:!0,service:Mt.update(l.id,l.version,{managementEnabled:!0})})}if(L.pathname==="/api/data-services/reveal"&&C.method==="POST"){let d=await se(C),l=Mt.get(String(d.id??"")),k=a.environments.get(ye),M=l?Mt.credential(l.id):void 0;if(!l||l.projectId!==a.project.id||l.environmentId!==k?.id)return b({ok:!1,error:"Data service was not found in this environment."},404);if(!M)return b({ok:!1,error:"No managed credential is configured."},404);return b({ok:!0,credential:{username:M.username,password:await Bi.resolve(M.secretRef),version:M.version}},200,{"cache-control":"no-store"})}if(L.pathname==="/api/databases"&&C.method==="GET")return b(await jh(o,ye));if(L.pathname==="/api/databases"&&C.method==="POST"){let d=await se(C),l=String(d.name??"").trim();if(!co(l))return b({ok:!1,error:"Database name must be a valid identifier (letters, numbers, underscore; not starting with a digit)."},422);return b({...await Uh(o,ye,l),name:l})}if(L.pathname==="/api/databases/vitess"&&C.method==="GET"){let d=await Gh(o,ye);return b({...d,unhealthy:Jh(d.tablets),missingPrimary:Hh(d)})}if(L.pathname==="/api/databases/vitess/provision"&&C.method==="POST"){let d=await se(C);try{return b(await ry(o,ye,{keyspace:String(d.keyspace??""),username:String(d.username??""),password:String(d.password??""),sharded:d.sharded===!0,confirm:String(d.confirm??"")}))}catch(l){return b({ok:!1,error:l instanceof Error?l.message:String(l)},422)}}if(L.pathname==="/api/databases/vitess/migrations"&&C.method==="GET"){let d=L.searchParams.get("keyspace")??void 0;return b(await ey(o,ye,d))}if(L.pathname==="/api/databases/vitess/migrations/action"&&C.method==="POST"){let d=await se(C),l=String(d.uuid??"").trim(),k=String(d.action??"");if(!["retry","cancel","cleanup","complete"].includes(k))return b({ok:!1,error:"Unknown migration action."},422);return b(await ty(o,ye,l,k))}if(L.pathname==="/api/databases/vitess/keyspaces"&&C.method==="POST"){let d=await se(C),l=String(d.name??"").trim(),k=d.sharded===!0;return b(await Yh(o,ye,l,{sharded:k}))}if(L.pathname==="/api/databases/vitess/vschema"&&C.method==="POST"){let d=await se(C),l=String(d.keyspace??"").trim(),k=typeof d.vschema==="string"?d.vschema:JSON.stringify(d.vschema??null);return b(await Xh(o,ye,l,k))}if(L.pathname==="/api/databases/vitess/schema"&&C.method==="POST"){let d=await se(C),l=String(d.sql??"");return b(await Zh(o,ye,l))}if(L.pathname==="/api/databases/vitess/install-client"&&C.method==="POST")return b(await Qh(o,ye));if(L.pathname==="/api/databases/backups"&&C.method==="GET")return b(await qh(o,ye));if(L.pathname==="/api/databases/backup"&&C.method==="POST"){let d=await se(C),l=String(d.database??"").trim();if(!co(l))return b({ok:!1,error:"Database name must be a valid identifier."},422);if(d.confirm!==l)return b({ok:!1,error:`Type "${l}" to back up this database.`},409);return b(await Vh(o,ye,l))}if(L.pathname==="/api/databases/users"&&C.method==="POST"){let d=await se(C),l=String(d.username??"").trim(),k=String(d.password??""),M=String(d.database??"").trim()||void 0,B=d.access==="readonly"?"readonly":"all";if(!co(l))return b({ok:!1,error:"Username must be a valid identifier."},422);if(!k)return b({ok:!1,error:"Password is required."},422);if(M&&!co(M))return b({ok:!1,error:"Database must be a valid identifier."},422);return b({...await zh(o,ye,{username:l,password:k,database:M,access:B}),username:l})}if(L.pathname==="/api/dashboard-data")return Lt=W.get(ye)??await tt(ye),tt(ye),b(Wl(Lt,{user:Tn,slug:o.project.slug}));if(L.pathname==="/api/users"&&C.method==="GET")return b({ok:!0,users:dn(t).map(oa)});if(L.pathname==="/api/users"&&C.method==="POST"){let d=await se(C),l=String(d.username??"").trim();if(!Sd(l))return b({ok:!1,error:"Username must be 2-32 characters: letters, numbers, dot, dash or underscore."},422);let k=d.sites&&typeof d.sites==="object"?d.sites:{},M=new Set(Object.keys(o.sites??{})),B={};for(let[Z,fe]of Object.entries(k)){if(!M.has(Z))return b({ok:!1,error:`Site '${Z}' was not found.`},404);if(fe!=="owner"&&fe!=="collaborator")return b({ok:!1,error:`Unknown site role '${fe}'. Use 'owner' or 'collaborator'.`},422);B[Z]=fe}let X=typeof d.password==="string"&&d.password.trim()?d.password.trim():void 0;if(X&&X.length<12)return b({ok:!1,error:"Password must be at least 12 characters."},422);let j=Na(t,{username:l,password:X,name:typeof d.name==="string"?d.name:void 0,sites:B});return ud(a,dn(t)),pi(),b({ok:!0,user:oa(j.user),password:j.password})}if(L.pathname==="/api/users"&&C.method==="DELETE"){let d=await se(C),l=String(d.username??"").trim();if(l.toLowerCase()===ue.username.toLowerCase())return b({ok:!1,error:"You cannot remove your own account."},409);let k=ui(dn(t),l),M=k?a.store.getActorByExternalId("user",`dashboard:${k.username.toLowerCase()}`):void 0,B=M?a.store.getMembershipForActor(a.organization.id,M.id):void 0;if(B&&B.source!=="legacy")return b({ok:!1,error:"Organization members must be removed from Organization access."},409);let X=Jl(t,l);if(!X.ok)return b(X,409);return ud(a,dn(t)),Re.clear(),b({ok:!0,username:l})}if(L.pathname==="/api/actions/run"&&C.method==="POST"){let d=await C.json().catch(()=>({})),l=d.action?hA(d.action,ye):void 0;if(!l)return b({ok:!1,error:"Unknown dashboard action."},404);if(l.mutates&&d.confirm!==l.confirm)return b({ok:!1,error:`Type "${l.confirm}" to run this action.`},409);let k=await ao({controlPlane:a,environment:ye,actor:ue,kind:`dashboard.action.${l.id}`,input:{action:l.id},execute:()=>ap(l,{cwd:t,cliEntry:i})});return b({...k.result,controlPlaneOperation:k.operation})}if(L.pathname==="/api/server/operations/run"&&C.method==="POST"){let d=await C.json().catch(()=>({})),l=d.operation?Zn(d.operation,o,Lt):void 0;if(!l)return b({ok:!1,error:"Unknown or unavailable server operation."},404);if(l.mutates&&d.confirm!==l.confirm)return b({ok:!1,error:`Type "${l.confirm}" to run this operation.`},409);let k=le(a,String(ye));await new ss(rt).run(new Da,{...k,artifactRoot:t});let M=ar(rt,{scope:k,desiredConfigHash:a.project.desiredConfigHash});if(M.decision.outcome==="block")return b({ok:!1,error:`Operation blocked by security policy: ${M.decision.explanation}`,securityReview:M},409);let B=await ao({controlPlane:a,environment:ye,actor:ue,kind:`dashboard.server.${l.id}`,resourceSlug:l.target,input:{operation:l.id,target:l.target,to:d.to??null},execute:()=>qr(o,ye,l,{to:d.to})});return b({...B.result,controlPlaneOperation:B.operation,securityReview:M})}if(L.pathname==="/api/server/command"&&C.method==="POST"){let d=await C.json().catch(()=>({}));if(d.confirm!=="run")return b({ok:!1,error:'Type "run" to execute this command on the server.'},409);let l=await ao({controlPlane:a,environment:ye,actor:ue,kind:"dashboard.server.command",input:{source:"interactive-command"},execute:()=>or(o,ye,String(d.command??""))});return b({...l.result,controlPlaneOperation:l.operation})}if(L.pathname==="/api/serverless/operations")return b(Zl(o,ye,Lt));if(L.pathname==="/api/serverless/operations/run"&&C.method==="POST"){let d=await C.json().catch(()=>({})),l=d.operation?Dy(d.operation,o,ye,Lt):void 0;if(!l)return b({ok:!1,error:"Unknown or unavailable serverless operation."},404);if(l.mutates&&d.confirm!==l.confirm)return b({ok:!1,error:`Type "${l.confirm}" to run this operation.`},409);let k=await ao({controlPlane:a,environment:ye,actor:ue,kind:`dashboard.serverless.${l.id}`,input:{operation:l.id,min:d.min??null,max:d.max??null},execute:()=>Oy(o,ye,l,{min:d.min,max:d.max})});return Lt=await ps(o,ye),W.set(ye,Lt),b({...k.result,controlPlaneOperation:k.operation})}if(L.pathname==="/api/serverless/command"&&C.method==="POST"){let d=await C.json().catch(()=>({}));if(d.confirm!=="run")return b({ok:!1,error:'Type "run" to execute this command.'},409);return b(await _y(o,ye,String(d.command??"")))}if(L.pathname==="/api/serverless/dlq"&&C.method==="GET"){let d=Number(L.searchParams.get("max"))||10;return b(await Ny(o,ye,d))}if(L.pathname==="/api/serverless/dlq/redrive"&&C.method==="POST"){let d=await C.json().catch(()=>({}));if(d.confirm!=="redrive")return b({ok:!1,error:'Type "redrive" to move messages back onto a source queue.'},409);return b(await My(o,ye,{max:d.max,targetQueue:d.targetQueue}))}if(L.pathname==="/api/serverless/dlq/purge"&&C.method==="POST"){if((await C.json().catch(()=>({}))).confirm!=="purge")return b({ok:!1,error:'Type "purge" to permanently discard every DLQ message.'},409);return b(await $y(o,ye))}if(L.pathname==="/api/serverless/secrets"&&C.method==="GET")return b({secrets:Ly(o,ye)});if(L.pathname==="/api/serverless/secrets"&&C.method==="POST"){let d=await C.json().catch(()=>({})),l=String(d.secretId??"").trim();if(!l)return b({ok:!1,error:"A secret id is required."},422);if(typeof d.value!=="string"||d.value==="")return b({ok:!1,error:"A non-empty value is required."},422);return b(await By(o,ye,l,d.value))}if(L.pathname==="/api/serverless/secrets"&&C.method==="DELETE"){let d=await C.json().catch(()=>({})),l=String(d.secretId??"").trim();if(!l)return b({ok:!1,error:"A secret id is required."},422);if(d.confirm!==l)return b({ok:!1,error:`Type "${l}" to delete this secret.`},409);return b(await Fy(o,ye,l))}if(L.pathname==="/api/serverless/functions/config"&&C.method==="POST"){let d=await C.json().catch(()=>({})),l=String(d.mode??"").trim();if(d.confirm!==l)return b({ok:!1,error:`Type "${l}" to update this function.`},409);return b(await jy(o,ye,l,{memory:d.memory,timeout:d.timeout}))}if(L.pathname==="/api/serverless/alarms"&&C.method==="GET")return b(await Uy(o,ye));if(L.pathname==="/api/serverless/alarms"&&C.method==="POST"){let d=await C.json().catch(()=>({})),l=String(d.preset??"").trim(),k=Number(d.threshold);if(!l)return b({ok:!1,error:"An alarm metric is required."},422);if(!Number.isFinite(k))return b({ok:!1,error:"A numeric threshold is required."},422);return b(await zy(o,ye,l,k))}if(L.pathname==="/api/serverless/alarms"&&C.method==="DELETE"){let d=await C.json().catch(()=>({})),l=String(d.name??"").trim();if(!l)return b({ok:!1,error:"An alarm name is required."},422);if(d.confirm!==l)return b({ok:!1,error:`Type "${l}" to delete this alarm.`},409);return b(await Vy(o,ye,l))}if(L.pathname==="/api/serverless/traces"&&C.method==="GET"){let d=Number(L.searchParams.get("minutes"))||30;return b(await Cd(o,ye,d))}if(L.pathname==="/api/serverless/scheduler"&&C.method==="POST"){let d=await C.json().catch(()=>({})),l=String(d.action??"").trim();if(l!=="enable"&&l!=="disable"&&l!=="run")return b({ok:!1,error:"Unknown scheduler action."},422);if(d.confirm!==l)return b({ok:!1,error:`Type "${l}" to ${l} the scheduler.`},409);return b(await rp(o,ye,l))}if(!fb(L.pathname,Tn))return new Response(null,{status:302,headers:{location:`/access-denied?env=${encodeURIComponent(ye)}`}});let vs=await ki(ue,ye);if(!vs)return Rd("ts-cloud dashboard UI is unavailable.",503);return hb(vs,L.pathname)}catch(jo){if(e.verbose)console.error(jo);return b({ok:!1,error:jo?.message??String(jo)},500)}})();if(!Kt)return Kt;if(gt&&(L.pathname.startsWith("/api/")||L.pathname.startsWith("/auth/"))){let Ze;if((Ce.headers.get("content-type")||"").includes("application/json"))Ze=await Ce.json().catch(()=>{return});let wr=jt.resolveUser(C),mr=wr?Ne(wr).actor:void 0;a.store.appendEvent({organizationId:a.organization.id,projectId:a.project.id,actorId:mr?.id,correlationId:Ge,type:Kt.status<400?"dashboard.mutation.succeeded":"dashboard.mutation.failed",level:Kt.status<400?"info":"warning",payload:eA(C.method,L.pathname,Ze,Kt.status,Date.now()-_e)})}return Kt.headers.set("x-request-id",Ge),Kt}});Ua?.start();let Ob=e.spendLoop??!0,kp;if(Ob)(async()=>{let{SpendRunner:C,SpendLoopLease:Te,startSpendLoop:_e}=await import("./chunk-knzje4ka.js"),{store:Ce}=await bb(a.store),Ge=new C({controlPlane:a.store,store:Ce,alerts:We});kp=_e(Ge,{lease:new Te(a.store,{owner:`dashboard:${process.pid}`}),onError:(gt)=>console.error(`[ts-cloud] spend cycle failed: ${gt instanceof Error?gt.message:String(gt)}`)})})();let _b=bs.stop.bind(bs);return bs.stop=(C)=>{clearInterval(Cp),clearInterval(Ep),clearInterval(Tp),clearInterval(Ip),clearInterval(wp),clearInterval(yp),clearInterval(bp),clearInterval(Sp),clearInterval(vp),pi(),Yt.clear(),Ua?.stop(),kp?.();let Te=_b(C);if(Ua)Ua.settled().finally(()=>a.store.close());else a.store.close();return Te},{server:bs,url:`http://${r}:${bs.port}/`}}
511
- export{Oe,x,Pn,y,Dn,Hi,kn,es,Fr,it,ke,Nn,xn,_n,On,$n,Ln,Mn,Un,ie,Zt,er,Bn,jr,jn,Vn,zn,Hn,qn,Gn,Wn,Kn,ot,tr,rr,Dt,Vr,nr,ir,qi,kt,Jn,ce,Xn,Qn,Yn,zr,Hr,Zn,qr,or,sr,st,Nt,xt,Gr,le,ei,ac,cc,ar,lc,q,Gi,ze,at,ct,ti,Wr,Kr,ri,ni,ii,Jr,ts,de,be,$e,Se,oi,cr};
509
+ `))},5000),et.unref?.(),C.signal.addEventListener("abort",bo,{once:!0})},cancel(){if(ut=!0,et)clearInterval(et)}});return new Response(bn,{headers:{"cache-control":"no-cache, no-transform",connection:"keep-alive","content-type":"text/event-stream; charset=utf-8","x-accel-buffering":"no"}})}if(L.pathname==="/api/telemetry/series"&&C.method==="GET"){pe(!1);let ve=He(),Be=["sum","avg","min","max","count","p50","p90","p95","p99"].includes(String(fe.aggregation))?fe.aggregation:"avg",we=Z({...fe,kinds:"metric",limit:5000}),Ae=l.series({...we,bucketMs:Number(fe.bucketMs)||60000,aggregation:Be,timezone:String(fe.timezone??"UTC"),compareFrom:fe.compareFrom,compareTo:fe.compareTo});return b({ok:!0,collection:{generatedAt:ve.generatedAt,cached:ve.cached},query:{aggregation:Be,bucketMs:Number(fe.bucketMs)||60000,timezone:String(fe.timezone??"UTC")},series:Ae})}if(L.pathname==="/api/telemetry/refresh"&&C.method==="POST")return b({ok:!0,...await pe(!0)});if(L.pathname==="/api/telemetry/export"&&C.method==="POST"){let ve=await se(C);await pe(!1);let Be=l.query({...Z(ve),limit:Math.min(5000,Number(ve.limit)||5000),cursor:void 0});if((ve.format==="csv"?"csv":"json")==="json")return new Response(JSON.stringify({exportedAt:new Date().toISOString(),query:Z(ve),...Be},null,2),{headers:{"content-disposition":'attachment; filename="ts-cloud-telemetry.json"',"content-type":"application/json; charset=utf-8"}});let Ae=["timestamp","kind","source","name","level","value","unit","message","traceId","requestId","deploymentId","releaseId","workloadId"],et=[Ae.join(","),...Be.records.map((ut)=>Ae.map((St)=>`"${String(ut[St]??"").replaceAll('"','""')}"`).join(","))].join(`
510
+ `);return new Response(et,{headers:{"content-disposition":'attachment; filename="ts-cloud-telemetry.csv"',"content-type":"text/csv; charset=utf-8"}})}if(L.pathname==="/api/telemetry/saved-queries"&&C.method==="GET"){let ve=Ne(ue);return b({ok:!0,queries:l.listSavedQueries(a.project.id,ve.actor?.id)})}if(L.pathname==="/api/telemetry/saved-queries"&&C.method==="POST"){let ve=await se(C),Be=Ne(ue);return b({ok:!0,query:l.saveQuery(a.project.id,Be.actor?.id,String(ve.name??""),Z(ve.query??ve))},201)}if(L.pathname==="/api/telemetry/saved-queries"&&C.method==="DELETE"){let ve=await se(C),Be=Ne(ue),we=l.deleteSavedQuery(a.project.id,Be.actor?.id,String(ve.id??""));return b({ok:we},we?200:404)}}if(L.pathname.startsWith("/api/configuration")){let d=a.environments.get(ye),l=ue.role==="admin"||!!Tn.capabilities?.includes("secrets:read"),k=ue.role==="admin"||!!Tn.capabilities?.includes("secrets:write"),M={projectId:a.project.id,environmentId:d?.id},F={"cache-control":"no-store"};if(L.pathname==="/api/configuration"&&C.method==="GET"){let X=Object.fromEntries(L.searchParams),j=X.scopeType||X.scopeId?aa(X,M):void 0,Z=["variable","secret"].includes(String(X.kind))?X.kind:void 0,fe=j?.type==="preview"?Wt.previews.getInstance(j.id):void 0,pe=fe?Wt.previews.getDefinition(fe.definitionId):void 0,He=j?await ln.resolve({projectId:a.project.id,environmentId:j.environmentId,resourceId:j.resourceId,functionId:j.type==="function"?j.id:void 0,previewId:j.previewId,trustedPreview:!!fe&&!fe.fork,allowedPreviewSecrets:pe?.inheritedSecrets,nativeReferences:!0,canReadSecretMetadata:l}):void 0,ve=a.store.listResources(a.project.id);return b({ok:!0,entries:ln.list({projectId:a.project.id,scope:j,kind:Z,search:X.search,canReadSecretMetadata:l}),effectiveEntries:He?Object.values(He.entries).filter((Be)=>!Z||Be.kind===Z).filter((Be)=>!X.search||Be.key.toLowerCase().includes(String(X.search).toLowerCase())):[],configurationHash:He?.configurationHash,warnings:He?.warnings??[],scopes:{project:a.project,environments:a.store.listEnvironments(a.project.id),resources:ve.filter((Be)=>Be.kind!=="function"),functions:ve.filter((Be)=>Be.kind==="function"),previews:Wt.previews.listInstances({projectId:a.project.id}).filter((Be)=>Be.status!=="destroyed").map((Be)=>({id:Be.id,name:Be.name,environmentId:Be.baseEnvironmentId,resourceId:Be.resourceId,fork:Be.fork,status:Be.status}))}},200,F)}if(L.pathname==="/api/configuration/export"&&C.method==="GET"){let X=aa(Object.fromEntries(L.searchParams),M);return new Response(ln.exportVariables({projectId:a.project.id,scope:X}),{headers:{...F,"content-disposition":'attachment; filename="ts-cloud.env"',"content-type":"text/plain; charset=utf-8"}})}if(L.pathname==="/api/configuration/plan"&&C.method==="POST"){let X=await se(C),j=aa(X,M),Z=X.values&&typeof X.values==="object"&&!Array.isArray(X.values)?Object.fromEntries(Object.entries(X.values).map(([fe,pe])=>[fe,String(pe)])):{};return b({ok:!0,plan:ln.plan({projectId:a.project.id,scope:j,values:Z,removeMissing:X.removeMissing===!0})},200,F)}if(L.pathname==="/api/configuration"&&C.method==="POST"){let X=await se(C),j=aa(X,M),Z=X.kind==="secret"?"secret":"variable",fe=String(X.key??"");if(Z==="secret"&&!k)return b({ok:!1,error:"Secret write permission is required."},403,F);try{let pe=await ln.set({organizationId:a.organization.id,projectId:a.project.id,scope:j,key:fe,kind:Z,value:X.value==null?void 0:String(X.value),reference:X.reference==null?void 0:String(X.reference),backend:X.backend,required:X.required===!0,expectedVersion:X.expectedVersion==null?void 0:Number(X.expectedVersion),confirmed:String(X.confirm??"")===fe,idempotencyKey:C.headers.get("idempotency-key")??X.idempotencyKey,actorId:Ne(ue).actor?.id});return b({ok:!0,entry:ln.list({projectId:a.project.id,scope:j,canReadSecretMetadata:l}).find((He)=>He.id===pe.entry.id),mutation:pe.mutation,warnings:pe.warnings},pe.mutation.added.length?201:200,F)}catch(pe){return b({ok:!1,error:pe instanceof Error?pe.message:String(pe)},409,F)}}if(L.pathname==="/api/configuration/import"&&C.method==="POST"){let X=await se(C),j=aa(X,M),Z=Array.isArray(X.secretKeys)?X.secretKeys.map(String):[];if(Z.length&&!k)return b({ok:!1,error:"Secret write permission is required."},403,F);try{let fe=await ln.importDotenv({organizationId:a.organization.id,projectId:a.project.id,scope:j,source:String(X.source??""),secretKeys:Z,backend:X.backend,confirmed:X.confirm==="import",idempotencyKey:C.headers.get("idempotency-key")??X.idempotencyKey,actorId:Ne(ue).actor?.id});return b({ok:fe.document.valid,diagnostics:fe.document.diagnostics,mutation:fe.mutation,warnings:fe.warnings},fe.document.valid?200:422,F)}catch(fe){return b({ok:!1,error:fe instanceof Error?fe.message:String(fe)},409,F)}}if(L.pathname==="/api/configuration/dependencies"&&C.method==="POST"){let X=await se(C),j=po.get(String(X.entryId??"")),Z=a.store.getResource(String(X.resourceId??""));if(!j||j.projectId!==a.project.id||!Z||Z.projectId!==a.project.id)return b({ok:!1,error:"Configuration entry or dependent resource was not found."},404,F);return b({ok:!0,dependency:po.setDependency({entryId:j.id,resourceId:Z.id,injectionTarget:["native_reference","file"].includes(String(X.injectionTarget))?X.injectionTarget:"environment",required:X.required!==!1,requiresRedeploy:X.requiresRedeploy!==!1,lastDeployedVersion:X.lastDeployedVersion==null?void 0:Number(X.lastDeployedVersion)})},200,F)}if(L.pathname==="/api/configuration/transfer"&&C.method==="POST"){let X=await se(C),j=po.get(String(X.id??"")),Z=aa({...X,scopeType:X.targetScopeType,scopeId:X.targetScopeId},M);if(!j||j.projectId!==a.project.id)return b({ok:!1,error:"Configuration entry was not found."},404,F);if(j.kind==="secret"&&!k)return b({ok:!1,error:"Secret write permission is required."},403,F);try{let fe=await ln.transfer({entryId:j.id,targetScope:Z,mode:X.mode==="move"?"move":"copy",confirmed:X.confirm===j.key,actorId:Ne(ue).actor?.id,idempotencyKey:C.headers.get("idempotency-key")??X.idempotencyKey});return b({ok:!0,entry:ln.list({projectId:a.project.id,scope:Z,canReadSecretMetadata:l}).find((pe)=>pe.id===fe.entry.id),mutation:fe.mutation},200,F)}catch(fe){return b({ok:!1,error:fe instanceof Error?fe.message:String(fe)},409,F)}}if(L.pathname==="/api/configuration/bulk"&&C.method==="POST"){let X=await se(C),j=Array.isArray(X.ids)?X.ids.map(String).slice(0,500):[],Z=j.map((pe)=>po.get(pe)).filter((pe)=>!!pe&&pe.projectId===a.project.id);if(Z.length!==j.length)return b({ok:!1,error:"One or more configuration entries were not found."},404,F);if(Z.some((pe)=>pe.kind==="secret")&&!k)return b({ok:!1,error:"Secret write permission is required."},403,F);if(X.action!=="delete"||X.confirm!=="bulk")return b({ok:!1,error:"Bulk deletion requires action delete and confirm bulk."},409,F);let fe=[];try{for(let pe of Z)fe.push(await ln.remove({entryId:pe.id,expectedVersion:pe.version,confirmed:!0,actorId:Ne(ue).actor?.id}));return b({ok:!0,removed:fe.flatMap((pe)=>pe.removed),affectedResourceIds:[...new Set(fe.flatMap((pe)=>pe.affectedResourceIds))].sort()},200,F)}catch(pe){return b({ok:!1,error:pe instanceof Error?pe.message:String(pe),partial:fe.flatMap((He)=>He.removed)},409,F)}}if(L.pathname==="/api/configuration/reveal"&&C.method==="POST"){let X=await se(C),j=jt.resolveSession(C);try{return b({ok:!0,value:await ln.reveal({entryId:String(X.id??""),canRevealSecrets:l,recentlyAuthenticated:!Pe||!!j&&Ie.isRecentlyAuthenticated(j),actorId:Ne(ue).actor?.id})},200,F)}catch(Z){return b({ok:!1,error:Z instanceof Error?Z.message:String(Z)},403,F)}}if(L.pathname==="/api/configuration"&&C.method==="DELETE"){let X=await se(C),j=po.get(String(X.id??""));if(j?.kind==="secret"&&!k)return b({ok:!1,error:"Secret write permission is required."},403,F);if(!j||j.projectId!==a.project.id)return b({ok:!1,error:"Configuration entry was not found."},404,F);try{return b({ok:!0,mutation:await ln.remove({entryId:j.id,expectedVersion:Number(X.expectedVersion),confirmed:String(X.confirm??"")===j.key,actorId:Ne(ue).actor?.id})},200,F)}catch(Z){return b({ok:!1,error:Z instanceof Error?Z.message:String(Z)},409,F)}}}if(L.pathname.startsWith("/api/fleet")){let d=Ne(ue).actor?.id,l=(k,M=409)=>b({ok:!1,error:k instanceof Error?k.message:String(k)},M,{"cache-control":"no-store"});if(L.pathname==="/api/fleet"&&C.method==="GET")return b({ok:!0,servers:ua.list(a.project.id),resources:a.store.listResources(a.project.id),operations:At.list({projectId:a.project.id,limit:200}).filter((k)=>k.operation.kind.startsWith("fleet."))},200,{"cache-control":"no-store"});if(L.pathname==="/api/fleet"&&C.method==="POST"){let k=await se(C);try{return b({ok:!0,server:xi.enroll({organizationId:a.organization.id,projectId:a.project.id,name:String(k.name??""),provider:["aws","hetzner"].includes(String(k.provider))?k.provider:"ssh",providerId:k.providerId?String(k.providerId):void 0,region:k.region?String(k.region):void 0,zone:k.zone?String(k.zone):void 0,endpoint:String(k.endpoint??""),sshUser:String(k.sshUser??"deploy"),sshPort:k.sshPort?Number(k.sshPort):22,credentialRef:String(k.credentialRef??""),roles:Array.isArray(k.roles)?k.roles:[],labels:k.labels&&typeof k.labels==="object"?k.labels:{}})},201)}catch(M){return l(M,422)}}if(L.pathname==="/api/fleet/action"&&C.method==="POST"){let k=await se(C),M=String(k.id??""),F=String(k.action??"");try{if(F==="test")return b({ok:!0,server:await xi.test(M)});if(F==="validate")return b({ok:!0,server:await xi.validate(M)});if(F==="review_host_key")return b({ok:!0,server:xi.reviewHostKey(M,String(k.fingerprint??""))});if(F==="bootstrap")return b({ok:!0,...xi.bootstrap(M,k.confirmed===!0)},k.confirmed===!0?202:200);if(F==="heartbeat")return b({ok:!0,server:xi.heartbeat(M,{usage:k.usage&&typeof k.usage==="object"?k.usage:{}})});if(F==="drain")return b({ok:!0,server:xi.drain(M,k.completed===!0)});if(F==="uncordon")return b({ok:!0,server:xi.uncordon(M)});if(F==="archive")return b({ok:!0,server:xi.archive(M,String(k.confirmation??""))});return l("Unsupported fleet action.",422)}catch(X){return l(X)}}}if(L.pathname.startsWith("/api/capacity")){let d=(l,k=409)=>b({ok:!1,error:l instanceof Error?l.message:String(l)},k,{"cache-control":"no-store"});if(L.pathname==="/api/capacity"&&C.method==="GET")return b({ok:!0,pools:fo.listPools(a.project.id),placements:fo.listPlacements(a.project.id),servers:ua.list(a.project.id)},200,{"cache-control":"no-store"});if(L.pathname==="/api/capacity"&&C.method==="POST"){let l=await se(C);try{return b({ok:!0,pool:fo.createPool({organizationId:a.organization.id,projectId:a.project.id,name:String(l.name??""),purpose:String(l.purpose??"application"),backend:String(l.backend??"server"),region:l.region?String(l.region):void 0,architecture:l.architecture?String(l.architecture):void 0,labels:l.labels&&typeof l.labels==="object"?l.labels:{},requiredServerLabels:l.requiredServerLabels&&typeof l.requiredServerLabels==="object"?l.requiredServerLabels:{},toleratedTaints:Array.isArray(l.toleratedTaints)?l.toleratedTaints.map(String):[],capacity:l.capacity&&typeof l.capacity==="object"?l.capacity:{},maxWorkloads:Number(l.maxWorkloads??10),costWeight:Number(l.costWeight??1),spreadKey:l.spreadKey?String(l.spreadKey):void 0,concurrency:Number(l.concurrency??1),ephemeralWorkspaces:!0,allowProductionSecrets:!1,status:"active"})},201)}catch(k){return d(k,422)}}if(L.pathname==="/api/capacity/member"&&C.method==="POST"){let l=await se(C);try{return fo.addMember(String(l.poolId??""),String(l.serverId??"")),b({ok:!0,pool:fo.getPool(String(l.poolId??""))})}catch(k){return d(k,422)}}if(L.pathname==="/api/capacity/explain"&&C.method==="POST"){let l=await se(C);try{return b({ok:!0,decisions:pp.explain(a.project.id,{purpose:String(l.purpose??"application"),resources:l.resources&&typeof l.resources==="object"?l.resources:{},region:l.region?String(l.region):void 0,architecture:l.architecture?String(l.architecture):void 0,labels:l.labels&&typeof l.labels==="object"?l.labels:{}})})}catch(k){return d(k,422)}}if(L.pathname==="/api/capacity/action"&&C.method==="POST"){let l=await se(C);try{if(l.action==="drain")return b({ok:!0,...pp.drainPool(String(l.poolId??""))});if(l.action==="enable")return b({ok:!0,pool:fo.updatePool(String(l.poolId??""),{status:"active"})});if(l.action==="disable")return b({ok:!0,pool:fo.updatePool(String(l.poolId??""),{status:"disabled"})});return d("Unsupported capacity action.",422)}catch(k){return d(k,422)}}}if(L.pathname.startsWith("/api/regions")){let d=(l,k=409)=>b({ok:!1,error:l instanceof Error?l.message:String(l)},k,{"cache-control":"no-store"});if(L.pathname==="/api/regions"&&C.method==="GET")return b({ok:!0,topologies:Fo.list(a.project.id).map((l)=>({topology:l,targets:Fo.targets(l.id),channels:Fo.channels(l.id),route:Fo.route(l.id),executions:Fo.executions(l.id)}))},200,{"cache-control":"no-store"});if(L.pathname==="/api/regions"&&C.method==="POST"){let l=await se(C);try{return b({ok:!0,topology:gp.create({organizationId:a.organization.id,projectId:a.project.id,environmentId:a.environments.get(ye)?.id,name:String(l.name??""),hostname:String(l.hostname??""),regions:Array.isArray(l.regions)?l.regions:[],trafficPolicy:l.trafficPolicy==="weighted"||l.trafficPolicy==="latency"?l.trafficPolicy:"active_passive",dataPolicy:{replicate:Array.isArray(l.replicate)?l.replicate:["s3","dynamodb","secrets"],maxLagSeconds:Number(l.maxLagSeconds??30),retainOnDestroy:l.retainOnDestroy!==!1},dnsProvider:"route53",cdnEnabled:l.cdnEnabled===!0,wafEnabled:l.wafEnabled===!0})},201)}catch(k){return d(k,422)}}if(L.pathname==="/api/regions/action"&&C.method==="POST"){let l=await se(C);try{return b({ok:!0,...gp.enqueue({topologyId:String(l.topologyId??""),kind:String(l.action??""),targetRegion:l.targetRegion?String(l.targetRegion):void 0,revision:l.revision?String(l.revision):void 0,manifest:l.manifest&&typeof l.manifest==="object"?l.manifest:{},confirmation:l.confirmation?String(l.confirmation):void 0,deleteData:l.deleteData===!0})},202)}catch(k){return d(k,422)}}}if(L.pathname.startsWith("/api/maintenance")){let d=(l,k=409)=>b({ok:!1,error:l instanceof Error?l.message:String(l)},k,{"cache-control":"no-store"});if(L.pathname==="/api/maintenance"&&C.method==="GET")return b({ok:!0,manifests:ji.manifests(a.organization.id),windows:ji.windows(a.project.id),campaigns:ji.campaigns(a.project.id).map((l)=>({campaign:l,targets:ji.targets(l.id)})),cleanups:ji.cleanups(a.project.id),drills:ji.drills(a.project.id)},200,{"cache-control":"no-store"});if(L.pathname==="/api/maintenance/cleanup-preview"&&C.method==="POST"){let l=await se(C);try{return b({ok:!0,plan:await Od.previewCleanup({projectId:a.project.id,kind:String(l.kind??"operations"),criteria:{olderThanDays:Number(l.olderThanDays??30)}},mp)},201)}catch(k){return d(k,422)}}if(L.pathname==="/api/maintenance/cleanup-apply"&&C.method==="POST"){let l=await se(C);try{return b({ok:!0,...Od.enqueueCleanup(String(l.planId??""),String(l.confirmation??""))},202)}catch(k){return d(k,422)}}if(L.pathname==="/api/maintenance/drill"&&C.method==="POST"){let l=await se(C);try{return b({ok:!0,drill:ji.createDrill({projectId:a.project.id,scenario:String(l.scenario??"control_plane"),isolatedTarget:String(l.isolatedTarget??""),expectedRpoMinutes:Number(l.expectedRpoMinutes??60),expectedRtoMinutes:Number(l.expectedRtoMinutes??30),recoveryPointId:l.recoveryPointId?String(l.recoveryPointId):void 0,topologyId:l.topologyId?String(l.topologyId):void 0})},201)}catch(k){return d(k,422)}}if(L.pathname==="/api/maintenance/drill-run"&&C.method==="POST"){let l=await se(C);try{return b({ok:!0,...Od.enqueueDrill(String(l.drillId??""))},202)}catch(k){return d(k,422)}}}if(L.pathname.startsWith("/api/volumes")){let d=a.environments.get(ye),l=Ne(ue).actor?.id,k=(M,F=409)=>b({ok:!1,error:M instanceof Error?M.message:String(M)},F,{"cache-control":"no-store"});if(L.pathname==="/api/volumes"&&C.method==="GET"){let M=xd.inventory(a.project.id,d?.id),F=a.store.listResources(a.project.id,d?.id).map((X)=>({id:X.id,name:X.name,slug:X.slug,kind:X.kind,provider:X.provider,providerId:X.providerId}));return b({ok:!0,volumes:M,resources:F,operations:At.list({projectId:a.project.id,limit:100}).filter((X)=>X.operation.kind.startsWith("volume.")),recoveryPoints:Qt.listRecoveryPoints(a.project.id).filter((X)=>X.kind==="volume"),providers:Dd.map((X)=>({provider:X.provider,type:X.type,capabilities:X.capabilities()}))},200,{"cache-control":"no-store"})}if(L.pathname==="/api/volumes"&&C.method==="POST"){let M=await se(C);try{return b({ok:!0,...Fi.create({organizationId:a.organization.id,projectId:a.project.id,environmentId:d?.id,resourceId:M.resourceId?String(M.resourceId):void 0,name:String(M.name??""),provider:String(M.provider??"docker"),type:M.type==="docker"?"docker":M.type,capacityBytes:M.capacityBytes==null?void 0:Number(M.capacityBytes),filesystem:M.filesystem?String(M.filesystem):void 0,encrypted:M.encrypted===!0,desiredState:M.desiredState&&typeof M.desiredState==="object"?M.desiredState:{},actorId:l})},202,{"cache-control":"no-store"})}catch(F){return k(F,422)}}if(L.pathname==="/api/volumes/attach"&&C.method==="POST"){let M=await se(C);try{return b({ok:!0,...Fi.attach(String(M.volumeId??""),{resourceId:String(M.resourceId??""),targetPath:String(M.targetPath??""),readOnly:M.readOnly===!0,uid:M.uid==null?void 0:Number(M.uid),gid:M.gid==null?void 0:Number(M.gid),mode:M.mode?String(M.mode):void 0,propagation:M.propagation,driverOptions:M.driverOptions&&typeof M.driverOptions==="object"?M.driverOptions:{},actorId:l})},202)}catch(F){return k(F,422)}}if(L.pathname==="/api/volumes/detach"&&C.method==="POST"){let M=await se(C);try{return b({ok:!0,...Fi.detach(String(M.volumeId??""),String(M.attachmentId??""),{force:M.force===!0,drained:M.drained===!0,unmounted:M.unmounted===!0,confirmation:M.confirmation?String(M.confirmation):void 0,actorId:l})},202)}catch(F){return k(F)}}if(L.pathname==="/api/volumes/resize"&&C.method==="POST"){let M=await se(C);try{return b({ok:!0,...Fi.resize(String(M.volumeId??""),Number(M.capacityBytes),{drained:M.drained===!0,actorId:l})},202)}catch(F){return k(F,422)}}if(L.pathname==="/api/volumes/snapshot"&&C.method==="POST"){let M=await se(C);try{return b({ok:!0,...Fi.snapshot(String(M.volumeId??""),{name:M.name?String(M.name):void 0,actorId:l})},202)}catch(F){return k(F,422)}}if(L.pathname==="/api/volumes/restore"&&C.method==="POST"){let M=await se(C);try{return b({ok:!0,...Fi.restore(String(M.snapshotId??""),{name:String(M.name??""),actorId:l})},202)}catch(F){return k(F,422)}}if(L.pathname==="/api/volumes/discover"&&C.method==="POST")try{return b({ok:!0,volumes:await Fi.discover({organizationId:a.organization.id,projectId:a.project.id,environmentId:d?.id,actorId:l})})}catch(M){return k(M,502)}if(L.pathname==="/api/volumes/adopt"&&C.method==="POST"){let M=await se(C);try{return b({ok:!0,volume:Fi.adopt(String(M.volumeId??""),{name:String(M.name??""),actorId:l})})}catch(F){return k(F,422)}}if(L.pathname==="/api/volumes"&&C.method==="DELETE"){let M=await se(C),F=jt.resolveSession(C);try{return b({ok:!0,...Fi.delete(String(M.volumeId??""),{recentAuthAt:!Pe||F&&Ie.isRecentlyAuthenticated(F)?new Date().toISOString():void 0,confirmation:M.confirmation?String(M.confirmation):void 0,backupOverride:M.backupOverride===!0,backupOverrideConfirmation:M.backupOverrideConfirmation?String(M.backupOverrideConfirmation):void 0,actorId:l})},202)}catch(X){return k(X)}}}if(L.pathname==="/api/backups"&&C.method==="GET"){let d=a.environments.get(ye),l=Qt.listPolicies(a.project.id,d?.id),k=new Set(l.map((Z)=>Z.id)),M=Qt.listRecoveryPoints(a.project.id).filter((Z)=>!Z.policyId||k.has(Z.policyId)),F=Qt.listJobs(a.project.id).filter((Z)=>!Z.policyId||k.has(Z.policyId)),X=(Z)=>({...Z,credentialRef:void 0,encryptionKeyRef:void 0,credentialsConfigured:!!Z.credentialRef,clientEncryptionConfigured:!!Z.encryptionKeyRef}),j=await Promise.all(Qt.listDestinations(a.project.id).map(async(Z)=>({...X(Z),credentialStatus:await Qg(Z,Bi)})));return b({ok:!0,destinations:j,policies:l,recoveryPoints:M,jobs:F,coverage:Qt.coverage(a.project.id).filter((Z)=>k.has(Z.policy.id)),resources:d?a.store.listResources(a.project.id,d.id).map((Z)=>({id:Z.id,name:Z.name,slug:Z.slug,kind:Z.kind})):[]})}if(L.pathname==="/api/backups/destinations"&&C.method==="POST"){let d=await se(C),l=String(d.name??"").trim(),k=String(d.provider??""),M=String(d.encryption??"provider"),F=`secret://data-services/backups/${a.project.id}/${l}`,X=[];if(!["aws_s3","s3_compatible","aws_backup"].includes(k))return b({ok:!1,error:"A supported backup destination provider is required."},422);if(!["provider","client_side","both"].includes(M))return b({ok:!1,error:"Encryption must be provider, client_side, or both."},422);try{let j,Z;if(d.credentials&&typeof d.credentials==="object"&&!Array.isArray(d.credentials))j=`${F}/credentials`,await Bi.put(j,JSON.stringify(d.credentials)),X.push(j);if(M!=="provider"){let pe=String(d.encryptionKey??"");if(pe.length<32)throw Error("Client-side encryption keys must contain at least 32 characters.");Z=`${F}/encryption-key`,await Bi.put(Z,pe),X.push(Z)}let fe=Qt.createDestination({organizationId:a.organization.id,projectId:a.project.id,name:l,provider:k,endpoint:d.endpoint?String(d.endpoint):void 0,endpointPolicy:d.endpointPolicy==="allow_private"?"allow_private":"public_https",bucket:d.bucket?String(d.bucket):void 0,prefix:String(d.prefix??""),region:d.region?String(d.region):mo,forcePathStyle:d.forcePathStyle===!0,credentialRef:j,encryption:M,encryptionKeyRef:Z,immutability:d.immutability&&typeof d.immutability==="object"&&!Array.isArray(d.immutability)?d.immutability:{},status:"untested"});return b({ok:!0,destination:{...fe,credentialRef:void 0,encryptionKeyRef:void 0,credentialsConfigured:!!j,clientEncryptionConfigured:!!Z}},201)}catch(j){for(let Z of X)await Bi.remove(Z).catch(()=>{});return b({ok:!1,error:j instanceof Error?j.message:String(j)},422)}}if(L.pathname==="/api/backups/destinations/test"&&C.method==="POST"){let d=await se(C),l=Qt.getDestination(String(d.id??""));if(!l||l.projectId!==a.project.id)return b({ok:!1,error:"Backup destination was not found."},404);if(l.provider==="aws_backup")return b({ok:!1,error:"AWS Backup destinations are verified by creating a provider recovery point."},422);try{return await lp.test(l),b({ok:!0,destination:Qt.recordDestinationTest(l.id,{ok:!0})})}catch(k){let M=k instanceof Error?k.message:String(k);return Qt.recordDestinationTest(l.id,{ok:!1,error:M}),b({ok:!1,error:M},502)}}if(L.pathname==="/api/backups/policies"&&C.method==="POST"){let d=await se(C),l=a.environments.get(ye),k=Qt.getDestination(String(d.destinationId??"")),M=String(d.resourceKind??""),F=d.dataServiceId?String(d.dataServiceId):void 0,X=F?Mt.get(F):void 0,j=d.resourceId?String(d.resourceId):void 0,Z=j?a.store.getResource(j):void 0;if(!l)return b({ok:!1,error:"Environment was not found."},404);if(!k||k.projectId!==a.project.id)return b({ok:!1,error:"Backup destination was not found."},404);if(!["managed_database","logical_database","volume","files","control_plane","infrastructure"].includes(M))return b({ok:!1,error:"A supported backup resource kind is required."},422);if(F&&(!X||X.projectId!==a.project.id||X.environmentId!==l.id))return b({ok:!1,error:"Data service was not found in this environment."},404);if(j&&(!Z||Z.projectId!==a.project.id||Z.environmentId!==l.id))return b({ok:!1,error:"Resource was not found in this environment."},404);if(M==="managed_database"&&!X)return b({ok:!1,error:"Managed database policies require a data service."},422);if(M==="logical_database"&&(!X||!["container","server"].includes(X.provider)))return b({ok:!1,error:"Logical database policies require an on-box data service."},422);if(M==="volume"&&(!Z||!/^[A-Za-z0-9][A-Za-z0-9_.-]{1,127}$/.test(String(d.volumeName??""))))return b({ok:!1,error:"Volume policies require a scoped resource and valid volumeName."},422);let fe=Array.isArray(d.includePatterns)?d.includePatterns.map(String).filter(Boolean):[];if(M==="files"&&(!Z||!fe.length))return b({ok:!1,error:"File policies require a scoped resource and at least one project-relative include path."},422);if(M==="control_plane"&&k.encryption==="provider")return b({ok:!1,error:"Control-plane policies require a destination with client-side encryption."},422);if(M==="infrastructure"&&(k.provider!=="aws_backup"||!fe.some((pe)=>pe.startsWith("resource:arn:"))||!fe.some((pe)=>pe.startsWith("role:arn:"))))return b({ok:!1,error:"Infrastructure policies require an AWS Backup destination plus resource:<arn> and role:<arn> include values."},422);try{let pe=Qt.createPolicy({organizationId:a.organization.id,projectId:a.project.id,environmentId:l.id,resourceId:j,dataServiceId:F,destinationId:k.id,name:String(d.name??"").trim(),resourceKind:M,schedule:String(d.schedule??"daily"),timezone:String(d.timezone??"UTC"),retention:d.retention&&typeof d.retention==="object"&&!Array.isArray(d.retention)?d.retention:{keepLast:7,expireAfterDays:30},compression:["none","gzip","zstd"].includes(String(d.compression))?d.compression:"gzip",encryption:["destination","client_side","both"].includes(String(d.encryption))?d.encryption:"destination",includePatterns:M==="volume"?[String(d.volumeName),...fe]:fe,excludePatterns:Array.isArray(d.excludePatterns)?d.excludePatterns.map(String):[],expectedRpoMinutes:Math.max(1,Number(d.expectedRpoMinutes)||1440),expectedRtoMinutes:Math.max(1,Number(d.expectedRtoMinutes)||120),healthCheckId:d.healthCheckId?String(d.healthCheckId):void 0,enabled:d.enabled!==!1});return b({ok:!0,policy:pe},201)}catch(pe){return b({ok:!1,error:pe instanceof Error?pe.message:String(pe)},422)}}if(L.pathname==="/api/backups/run"&&C.method==="POST"){let d=await se(C),l=Qt.getPolicy(String(d.policyId??"")),k=a.environments.get(ye);if(!l||l.projectId!==a.project.id||l.environmentId!==k?.id)return b({ok:!1,error:"Backup policy was not found in this environment."},404);try{let M=Bo.enqueueBackup(l,new Date().toISOString(),Ne(ue).actor?.id);return b({ok:!0,job:M},202)}catch(M){return b({ok:!1,error:M instanceof Error?M.message:String(M)},409)}}if(L.pathname==="/api/backups/verify"&&C.method==="POST"){let d=await se(C),l=Qt.getRecoveryPoint(String(d.recoveryPointId??""));if(!l||l.projectId!==a.project.id)return b({ok:!1,error:"Recovery point was not found."},404);return b({ok:!0,job:Bo.enqueueVerification(l)},202)}if(L.pathname==="/api/backups/restore"&&C.method==="POST"){let d=await se(C),l=Qt.getRecoveryPoint(String(d.recoveryPointId??"")),k=d.mode==="in_place"?"in_place":"isolated",M=d.target&&typeof d.target==="object"&&!Array.isArray(d.target)?{...d.target,inPlace:k==="in_place"}:{inPlace:k==="in_place"},F=jt.resolveSession(C),X={mode:k,target:M,targetName:String(d.targetName??""),confirm:d.confirm?String(d.confirm):void 0,recentAuth:!Pe||!!F&&Ie.isRecentlyAuthenticated(F),downtimeAcknowledged:d.downtimeAcknowledged===!0,safetyBackupId:d.safetyBackupId?String(d.safetyBackupId):void 0};if(!l||l.projectId!==a.project.id)return b({ok:!1,error:"Recovery point was not found."},404);if(d.drill===!0&&k!=="isolated")return b({ok:!1,error:"Recovery drills must use an isolated target."},422);try{let j=Bo.planRestore(l,X);if(d.execute!==!0)return b({ok:!0,plan:j,executionCreated:!1});let Z=Bo.enqueueRestore(l,{...X,drill:d.drill===!0,actorId:Ne(ue).actor?.id});return b({ok:!0,plan:j,job:Z},202)}catch(j){return b({ok:!1,error:j instanceof Error?j.message:String(j)},409)}}if(L.pathname==="/api/backups/recovery-points"&&C.method==="POST"){let d=await se(C),l=Qt.getRecoveryPoint(String(d.id??""));if(!l||l.projectId!==a.project.id)return b({ok:!1,error:"Recovery point was not found."},404);if(d.held==null&&d.pinned==null)return b({ok:!1,error:"held or pinned must be provided."},422);return b({ok:!0,recoveryPoint:Qt.updateRecoveryPoint(l.id,{held:d.held==null?l.held:d.held===!0,pinned:d.pinned==null?l.pinned:d.pinned===!0})})}if(L.pathname==="/api/backups/retention"&&C.method==="POST")return b({ok:!0,jobs:Bo.enqueueRetention()},202);if(L.pathname==="/api/data-services/capabilities"&&C.method==="GET"){let d=String(L.searchParams.get("engine")??""),l=String(L.searchParams.get("provider")??"");if(!["postgres","mysql","mariadb","redis","mongodb","libsql"].includes(d)||!["aws_rds","aws_aurora","aws_elasticache","server","container","external"].includes(l))return b({ok:!1,error:"A supported engine and provider are required."},422);return b({ok:!0,engine:d,provider:l,capabilities:Zt(d,l)})}if(L.pathname==="/api/data-services"&&C.method==="GET"){let d=a.environments.get(ye),l=Mt.list(a.project.id,d?.id).map((k)=>{let M=Mt.credential(k.id);return{...k,credentialRef:void 0,credential:M?{configured:!0,username:M.username,version:M.version,rotatedAt:M.rotatedAt}:void 0,dependencies:Mt.dependencies(k.id).map((F)=>({resourceId:F.resourceId,requiresRedeploy:F.requiresRedeploy}))}});return b({ok:!0,services:l})}if(L.pathname==="/api/data-services/preview"&&C.method==="POST"){let d=await se(C);if(d.id){let M=Mt.get(String(d.id)),F=a.environments.get(ye),X=String(d.action??"");if(!M||M.projectId!==a.project.id||M.environmentId!==F?.id)return b({ok:!1,error:"Data service was not found in this environment."},404);if(!Ad.includes(X))return b({ok:!1,error:`Action must be one of: ${Ad.join(", ")}.`},422);try{return b({ok:!0,plan:ja.plan(M,X,d.changes??{})})}catch(j){return b({ok:!1,error:j instanceof Error?j.message:String(j)},422)}}let l=String(d.engine??""),k=String(d.provider??"");if(!["postgres","mysql","mariadb","redis","mongodb","libsql"].includes(l)||!["aws_rds","aws_aurora","aws_elasticache","server","container","external"].includes(k))return b({ok:!1,error:"A supported engine and provider are required."},422);return b({ok:!0,capabilities:Zt(l,k),defaults:{publicExposure:!1,backupRetentionDays:7,deletionProtection:!0},productionExecutionCreated:!1})}if(L.pathname==="/api/data-services"&&C.method==="POST"){let d=await se(C),l=String(d.engine??""),k=String(d.provider??""),M=a.environments.get(ye),F=Ne(ue);if(!M)return b({ok:!1,error:"Environment was not found."},404);if(!["postgres","mysql","mariadb","redis","mongodb","libsql"].includes(l)||!["aws_rds","aws_aurora","aws_elasticache","server","container","external"].includes(k))return b({ok:!1,error:"A supported engine and provider are required."},422);let X={organizationId:a.organization.id,projectId:a.project.id,environmentId:M.id,resourceId:d.resourceId?String(d.resourceId):void 0,name:String(d.name??"").trim(),engine:l,provider:k,placement:String(d.placement??d.name??"").trim(),engineVersion:d.engineVersion?String(d.engineVersion):void 0,plan:String(d.plan??(k==="aws_elasticache"?"cache.t4g.micro":k==="aws_aurora"?"db.serverless":"db.t4g.micro")),storageGb:d.storageGb==null?void 0:Number(d.storageGb),highAvailability:d.highAvailability===!0,publicExposure:d.publicExposure===!0,allowedCidrs:Array.isArray(d.allowedCidrs)?d.allowedCidrs.map(String):[],desiredState:d.desiredState&&typeof d.desiredState==="object"&&!Array.isArray(d.desiredState)?d.desiredState:{},observedState:{},origin:d.adopt===!0?"adopted":"managed",managementEnabled:d.adopt!==!0,ownerActorId:F.actor?.id,username:d.username?String(d.username):void 0};try{if(d.adopt===!0){let Z=Mt.create({...X,status:"adopted",credentialRef:void 0});return b({ok:!0,service:Z,readOnly:!0},201)}if(!up({provider:k,engine:l}))return b({ok:!1,error:`No ${k}/${l} provisioning adapter is configured; adopt it read-only or choose a supported provider.`},422);let j=await ja.create(X);return b({ok:!0,service:j.service,operationId:j.operationId,oneTimeCredential:j.credential},201)}catch(j){return b({ok:!1,error:j instanceof Error?j.message:String(j)},422)}}if(L.pathname==="/api/data-services/connections"&&C.method==="GET"){let d=Mt.get(String(L.searchParams.get("id")??"")),l=a.environments.get(ye);if(!d||d.projectId!==a.project.id||d.environmentId!==l?.id)return b({ok:!1,error:"Data service was not found in this environment."},404);let k=typeof d.observedState.endpoint==="string"?d.observedState.endpoint:void 0,M=typeof d.observedState.readerEndpoint==="string"?d.observedState.readerEndpoint:void 0,F=Number(d.observedState.port)||(d.engine==="postgres"?5432:d.engine==="redis"?6379:d.engine==="mongodb"?27017:d.engine==="libsql"?8080:3306),X=typeof d.observedState.database==="string"?d.observedState.database:void 0,j=typeof d.observedState.tls==="boolean"?d.observedState.tls:d.provider.startsWith("aws_"),Z=[...k?[{type:d.publicExposure?"external":"internal",host:k,port:F,database:X,tls:j}]:[],...M?[{type:"internal",host:M,port:F,database:X,tls:j}]:[],{type:"tunnel",host:k??d.placement,port:F,database:X,tls:j}];return b({ok:!0,serviceId:d.id,guidance:Bn(d,Z)})}if(L.pathname==="/api/data-services/action"&&C.method==="POST"){let d=await se(C),l=Mt.get(String(d.id??"")),k=a.environments.get(ye),M=String(d.action??"");if(!l||l.projectId!==a.project.id||l.environmentId!==k?.id)return b({ok:!1,error:"Data service was not found in this environment."},404);if(!Ad.includes(M))return b({ok:!1,error:`Action must be one of: ${Ad.join(", ")}.`},422);let F=d.changes&&typeof d.changes==="object"&&!Array.isArray(d.changes)?d.changes:{};try{let X=ja.plan(l,M,F);if(d.execute!==!0)return b({ok:!0,plan:X,productionExecutionCreated:!1});let j=ja.enqueue(l,M,F,Ne(ue).actor?.id);return b({ok:!0,plan:X,operationId:j},202)}catch(X){return b({ok:!1,error:X instanceof Error?X.message:String(X)},409)}}if(L.pathname==="/api/data-services/dependencies"&&C.method==="POST"){let d=await se(C),l=Mt.get(String(d.id??"")),k=a.environments.get(ye),M=a.store.getResource(String(d.resourceId??""));if(!l||l.projectId!==a.project.id||l.environmentId!==k?.id)return b({ok:!1,error:"Data service was not found in this environment."},404);if(!M||M.projectId!==a.project.id||M.environmentId!==k?.id)return b({ok:!1,error:"Dependent resource was not found in this environment."},404);if(d.remove===!0)return b({ok:Mt.removeDependency(l.id,M.id)});return Mt.addDependency({serviceId:l.id,resourceId:M.id,secretRef:l.credentialRef??`secret://data-services/${l.projectId}/${l.name}`,requiresRedeploy:d.requiresRedeploy!==!1}),b({ok:!0,dependencies:Mt.dependencies(l.id).map((F)=>({resourceId:F.resourceId,requiresRedeploy:F.requiresRedeploy}))})}if(L.pathname==="/api/data-services/management"&&C.method==="POST"){let d=await se(C),l=Mt.get(String(d.id??"")),k=a.environments.get(ye);if(!l||l.projectId!==a.project.id||l.environmentId!==k?.id)return b({ok:!1,error:"Data service was not found in this environment."},404);if(l.origin!=="adopted"||d.reviewed!==!0||d.confirm!==l.name)return b({ok:!1,error:`Enabling management requires reviewed=true and typing ${l.name}.`},409);return b({ok:!0,service:Mt.update(l.id,l.version,{managementEnabled:!0})})}if(L.pathname==="/api/data-services/reveal"&&C.method==="POST"){let d=await se(C),l=Mt.get(String(d.id??"")),k=a.environments.get(ye),M=l?Mt.credential(l.id):void 0;if(!l||l.projectId!==a.project.id||l.environmentId!==k?.id)return b({ok:!1,error:"Data service was not found in this environment."},404);if(!M)return b({ok:!1,error:"No managed credential is configured."},404);return b({ok:!0,credential:{username:M.username,password:await Bi.resolve(M.secretRef),version:M.version}},200,{"cache-control":"no-store"})}if(L.pathname==="/api/databases"&&C.method==="GET")return b(await jh(o,ye));if(L.pathname==="/api/databases"&&C.method==="POST"){let d=await se(C),l=String(d.name??"").trim();if(!co(l))return b({ok:!1,error:"Database name must be a valid identifier (letters, numbers, underscore; not starting with a digit)."},422);return b({...await Uh(o,ye,l),name:l})}if(L.pathname==="/api/databases/vitess"&&C.method==="GET"){let d=await Gh(o,ye);return b({...d,unhealthy:Jh(d.tablets),missingPrimary:Hh(d)})}if(L.pathname==="/api/databases/vitess/provision"&&C.method==="POST"){let d=await se(C);try{return b(await ry(o,ye,{keyspace:String(d.keyspace??""),username:String(d.username??""),password:String(d.password??""),sharded:d.sharded===!0,confirm:String(d.confirm??"")}))}catch(l){return b({ok:!1,error:l instanceof Error?l.message:String(l)},422)}}if(L.pathname==="/api/databases/vitess/migrations"&&C.method==="GET"){let d=L.searchParams.get("keyspace")??void 0;return b(await ey(o,ye,d))}if(L.pathname==="/api/databases/vitess/migrations/action"&&C.method==="POST"){let d=await se(C),l=String(d.uuid??"").trim(),k=String(d.action??"");if(!["retry","cancel","cleanup","complete"].includes(k))return b({ok:!1,error:"Unknown migration action."},422);return b(await ty(o,ye,l,k))}if(L.pathname==="/api/databases/vitess/keyspaces"&&C.method==="POST"){let d=await se(C),l=String(d.name??"").trim(),k=d.sharded===!0;return b(await Yh(o,ye,l,{sharded:k}))}if(L.pathname==="/api/databases/vitess/vschema"&&C.method==="POST"){let d=await se(C),l=String(d.keyspace??"").trim(),k=typeof d.vschema==="string"?d.vschema:JSON.stringify(d.vschema??null);return b(await Xh(o,ye,l,k))}if(L.pathname==="/api/databases/vitess/schema"&&C.method==="POST"){let d=await se(C),l=String(d.sql??"");return b(await Zh(o,ye,l))}if(L.pathname==="/api/databases/vitess/install-client"&&C.method==="POST")return b(await Qh(o,ye));if(L.pathname==="/api/databases/backups"&&C.method==="GET")return b(await qh(o,ye));if(L.pathname==="/api/databases/backup"&&C.method==="POST"){let d=await se(C),l=String(d.database??"").trim();if(!co(l))return b({ok:!1,error:"Database name must be a valid identifier."},422);if(d.confirm!==l)return b({ok:!1,error:`Type "${l}" to back up this database.`},409);return b(await Vh(o,ye,l))}if(L.pathname==="/api/databases/users"&&C.method==="POST"){let d=await se(C),l=String(d.username??"").trim(),k=String(d.password??""),M=String(d.database??"").trim()||void 0,F=d.access==="readonly"?"readonly":"all";if(!co(l))return b({ok:!1,error:"Username must be a valid identifier."},422);if(!k)return b({ok:!1,error:"Password is required."},422);if(M&&!co(M))return b({ok:!1,error:"Database must be a valid identifier."},422);return b({...await zh(o,ye,{username:l,password:k,database:M,access:F}),username:l})}if(L.pathname==="/api/dashboard-data")return Lt=W.get(ye)??await tt(ye),tt(ye),b(Wl(Lt,{user:Tn,slug:o.project.slug}));if(L.pathname==="/api/users"&&C.method==="GET")return b({ok:!0,users:dn(t).map(oa)});if(L.pathname==="/api/users"&&C.method==="POST"){let d=await se(C),l=String(d.username??"").trim();if(!Sd(l))return b({ok:!1,error:"Username must be 2-32 characters: letters, numbers, dot, dash or underscore."},422);let k=d.sites&&typeof d.sites==="object"?d.sites:{},M=new Set(Object.keys(o.sites??{})),F={};for(let[Z,fe]of Object.entries(k)){if(!M.has(Z))return b({ok:!1,error:`Site '${Z}' was not found.`},404);if(fe!=="owner"&&fe!=="collaborator")return b({ok:!1,error:`Unknown site role '${fe}'. Use 'owner' or 'collaborator'.`},422);F[Z]=fe}let X=typeof d.password==="string"&&d.password.trim()?d.password.trim():void 0;if(X&&X.length<12)return b({ok:!1,error:"Password must be at least 12 characters."},422);let j=Na(t,{username:l,password:X,name:typeof d.name==="string"?d.name:void 0,sites:F});return ud(a,dn(t)),pi(),b({ok:!0,user:oa(j.user),password:j.password})}if(L.pathname==="/api/users"&&C.method==="DELETE"){let d=await se(C),l=String(d.username??"").trim();if(l.toLowerCase()===ue.username.toLowerCase())return b({ok:!1,error:"You cannot remove your own account."},409);let k=ui(dn(t),l),M=k?a.store.getActorByExternalId("user",`dashboard:${k.username.toLowerCase()}`):void 0,F=M?a.store.getMembershipForActor(a.organization.id,M.id):void 0;if(F&&F.source!=="legacy")return b({ok:!1,error:"Organization members must be removed from Organization access."},409);let X=Jl(t,l);if(!X.ok)return b(X,409);return ud(a,dn(t)),Re.clear(),b({ok:!0,username:l})}if(L.pathname==="/api/actions/run"&&C.method==="POST"){let d=await C.json().catch(()=>({})),l=d.action?hA(d.action,ye):void 0;if(!l)return b({ok:!1,error:"Unknown dashboard action."},404);if(l.mutates&&d.confirm!==l.confirm)return b({ok:!1,error:`Type "${l.confirm}" to run this action.`},409);let k=await ao({controlPlane:a,environment:ye,actor:ue,kind:`dashboard.action.${l.id}`,input:{action:l.id},execute:()=>ap(l,{cwd:t,cliEntry:i})});return b({...k.result,controlPlaneOperation:k.operation})}if(L.pathname==="/api/server/operations/run"&&C.method==="POST"){let d=await C.json().catch(()=>({})),l=d.operation?Zn(d.operation,o,Lt):void 0;if(!l)return b({ok:!1,error:"Unknown or unavailable server operation."},404);if(l.mutates&&d.confirm!==l.confirm)return b({ok:!1,error:`Type "${l.confirm}" to run this operation.`},409);let k=le(a,String(ye));await new ss(rt).run(new Da,{...k,artifactRoot:t});let M=ar(rt,{scope:k,desiredConfigHash:a.project.desiredConfigHash});if(M.decision.outcome==="block")return b({ok:!1,error:`Operation blocked by security policy: ${M.decision.explanation}`,securityReview:M},409);let F=await ao({controlPlane:a,environment:ye,actor:ue,kind:`dashboard.server.${l.id}`,resourceSlug:l.target,input:{operation:l.id,target:l.target,to:d.to??null},execute:()=>qr(o,ye,l,{to:d.to})});return b({...F.result,controlPlaneOperation:F.operation,securityReview:M})}if(L.pathname==="/api/server/command"&&C.method==="POST"){let d=await C.json().catch(()=>({}));if(d.confirm!=="run")return b({ok:!1,error:'Type "run" to execute this command on the server.'},409);let l=await ao({controlPlane:a,environment:ye,actor:ue,kind:"dashboard.server.command",input:{source:"interactive-command"},execute:()=>or(o,ye,String(d.command??""))});return b({...l.result,controlPlaneOperation:l.operation})}if(L.pathname==="/api/serverless/operations")return b(Zl(o,ye,Lt));if(L.pathname==="/api/serverless/operations/run"&&C.method==="POST"){let d=await C.json().catch(()=>({})),l=d.operation?Dy(d.operation,o,ye,Lt):void 0;if(!l)return b({ok:!1,error:"Unknown or unavailable serverless operation."},404);if(l.mutates&&d.confirm!==l.confirm)return b({ok:!1,error:`Type "${l.confirm}" to run this operation.`},409);let k=await ao({controlPlane:a,environment:ye,actor:ue,kind:`dashboard.serverless.${l.id}`,input:{operation:l.id,min:d.min??null,max:d.max??null},execute:()=>Oy(o,ye,l,{min:d.min,max:d.max})});return Lt=await ps(o,ye),W.set(ye,Lt),b({...k.result,controlPlaneOperation:k.operation})}if(L.pathname==="/api/serverless/command"&&C.method==="POST"){let d=await C.json().catch(()=>({}));if(d.confirm!=="run")return b({ok:!1,error:'Type "run" to execute this command.'},409);return b(await _y(o,ye,String(d.command??"")))}if(L.pathname==="/api/serverless/dlq"&&C.method==="GET"){let d=Number(L.searchParams.get("max"))||10;return b(await Ny(o,ye,d))}if(L.pathname==="/api/serverless/dlq/redrive"&&C.method==="POST"){let d=await C.json().catch(()=>({}));if(d.confirm!=="redrive")return b({ok:!1,error:'Type "redrive" to move messages back onto a source queue.'},409);return b(await My(o,ye,{max:d.max,targetQueue:d.targetQueue}))}if(L.pathname==="/api/serverless/dlq/purge"&&C.method==="POST"){if((await C.json().catch(()=>({}))).confirm!=="purge")return b({ok:!1,error:'Type "purge" to permanently discard every DLQ message.'},409);return b(await $y(o,ye))}if(L.pathname==="/api/serverless/secrets"&&C.method==="GET")return b({secrets:Ly(o,ye)});if(L.pathname==="/api/serverless/secrets"&&C.method==="POST"){let d=await C.json().catch(()=>({})),l=String(d.secretId??"").trim();if(!l)return b({ok:!1,error:"A secret id is required."},422);if(typeof d.value!=="string"||d.value==="")return b({ok:!1,error:"A non-empty value is required."},422);return b(await By(o,ye,l,d.value))}if(L.pathname==="/api/serverless/secrets"&&C.method==="DELETE"){let d=await C.json().catch(()=>({})),l=String(d.secretId??"").trim();if(!l)return b({ok:!1,error:"A secret id is required."},422);if(d.confirm!==l)return b({ok:!1,error:`Type "${l}" to delete this secret.`},409);return b(await Fy(o,ye,l))}if(L.pathname==="/api/serverless/functions/config"&&C.method==="POST"){let d=await C.json().catch(()=>({})),l=String(d.mode??"").trim();if(d.confirm!==l)return b({ok:!1,error:`Type "${l}" to update this function.`},409);return b(await jy(o,ye,l,{memory:d.memory,timeout:d.timeout}))}if(L.pathname==="/api/serverless/alarms"&&C.method==="GET")return b(await Uy(o,ye));if(L.pathname==="/api/serverless/alarms"&&C.method==="POST"){let d=await C.json().catch(()=>({})),l=String(d.preset??"").trim(),k=Number(d.threshold);if(!l)return b({ok:!1,error:"An alarm metric is required."},422);if(!Number.isFinite(k))return b({ok:!1,error:"A numeric threshold is required."},422);return b(await zy(o,ye,l,k))}if(L.pathname==="/api/serverless/alarms"&&C.method==="DELETE"){let d=await C.json().catch(()=>({})),l=String(d.name??"").trim();if(!l)return b({ok:!1,error:"An alarm name is required."},422);if(d.confirm!==l)return b({ok:!1,error:`Type "${l}" to delete this alarm.`},409);return b(await Vy(o,ye,l))}if(L.pathname==="/api/serverless/traces"&&C.method==="GET"){let d=Number(L.searchParams.get("minutes"))||30;return b(await Cd(o,ye,d))}if(L.pathname==="/api/serverless/scheduler"&&C.method==="POST"){let d=await C.json().catch(()=>({})),l=String(d.action??"").trim();if(l!=="enable"&&l!=="disable"&&l!=="run")return b({ok:!1,error:"Unknown scheduler action."},422);if(d.confirm!==l)return b({ok:!1,error:`Type "${l}" to ${l} the scheduler.`},409);return b(await rp(o,ye,l))}if(!fb(L.pathname,Tn))return new Response(null,{status:302,headers:{location:`/access-denied?env=${encodeURIComponent(ye)}`}});let vs=await ki(ue,ye);if(!vs)return Rd("ts-cloud dashboard UI is unavailable.",503);return hb(vs,L.pathname)}catch(jo){if(e.verbose)console.error(jo);return b({ok:!1,error:jo?.message??String(jo)},500)}})();if(!Kt)return Kt;if(gt&&(L.pathname.startsWith("/api/")||L.pathname.startsWith("/auth/"))){let Ze;if((Ce.headers.get("content-type")||"").includes("application/json"))Ze=await Ce.json().catch(()=>{return});let wr=jt.resolveUser(C),mr=wr?Ne(wr).actor:void 0;a.store.appendEvent({organizationId:a.organization.id,projectId:a.project.id,actorId:mr?.id,correlationId:Ge,type:Kt.status<400?"dashboard.mutation.succeeded":"dashboard.mutation.failed",level:Kt.status<400?"info":"warning",payload:eA(C.method,L.pathname,Ze,Kt.status,Date.now()-_e)})}return Kt.headers.set("x-request-id",Ge),Kt}});Ua?.start();let Ob=e.spendLoop??!0,kp;if(Ob)(async()=>{let{SpendRunner:C,SpendLoopLease:Te,startSpendLoop:_e}=await import("./chunk-vjg2fymw.js"),{store:Ce}=await bb(a.store),Ge=new C({controlPlane:a.store,store:Ce,alerts:We});kp=_e(Ge,{lease:new Te(a.store,{owner:`dashboard:${process.pid}`}),onError:(gt)=>console.error(`[ts-cloud] spend cycle failed: ${gt instanceof Error?gt.message:String(gt)}`)})})();let _b=bs.stop.bind(bs);return bs.stop=(C)=>{clearInterval(Cp),clearInterval(Ep),clearInterval(Tp),clearInterval(Ip),clearInterval(wp),clearInterval(yp),clearInterval(bp),clearInterval(Sp),clearInterval(vp),pi(),Yt.clear(),Ua?.stop(),kp?.();let Te=_b(C);if(Ua)Ua.settled().finally(()=>a.store.close());else a.store.close();return Te},{server:bs,url:`http://${r}:${bs.port}/`}}
511
+ export{Oe,x,Pn,y,Dn,Hi,kn,es,Br,it,ke,Nn,xn,_n,On,$n,Ln,Mn,Un,ie,Zt,er,Bn,jr,jn,Vn,zn,Hn,qn,Gn,Wn,Kn,ot,tr,rr,Dt,Vr,nr,ir,qi,kt,Jn,ce,Xn,Qn,Yn,zr,Hr,Zn,qr,or,sr,st,Nt,xt,Gr,le,ei,ac,cc,ar,lc,q,Gi,ze,at,ct,ti,Wr,Kr,ri,ni,ii,Jr,ts,de,be,$e,Se,oi,cr};