@stacksjs/ts-cloud 0.9.2 → 0.9.4

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 (191) hide show
  1. package/dist/aws/index.js +1 -269
  2. package/dist/bin/chunk-00kg80qg.js +1 -0
  3. package/dist/bin/chunk-09nwf2gy.js +34 -0
  4. package/dist/bin/chunk-1k5kszjp.js +111 -0
  5. package/dist/bin/chunk-21e0mavm.js +1 -0
  6. package/dist/bin/chunk-271gk1n2.js +6 -0
  7. package/dist/bin/chunk-2empps47.js +2 -0
  8. package/dist/bin/chunk-38pq971s.js +2 -0
  9. package/dist/bin/chunk-3gykfyq4.js +37 -0
  10. package/dist/bin/chunk-3vqfexc4.js +70 -0
  11. package/dist/bin/chunk-4vrqm9h0.js +2 -0
  12. package/dist/bin/chunk-598yf4bs.js +1 -0
  13. package/dist/bin/chunk-5ectjq0b.js +1 -0
  14. package/dist/bin/chunk-5erkxpt7.js +512 -0
  15. package/dist/bin/chunk-5mrtzemj.js +1 -0
  16. package/dist/bin/chunk-5n9fmabb.js +1 -0
  17. package/dist/bin/chunk-9knpg30y.js +1 -0
  18. package/dist/bin/chunk-9pvsff8g.js +1 -0
  19. package/dist/bin/chunk-ax9mr6wm.js +44 -0
  20. package/dist/bin/chunk-axhnkn5g.js +2 -0
  21. package/dist/bin/chunk-c1vcdgvr.js +1 -0
  22. package/dist/bin/chunk-ctd2vg9w.js +2 -0
  23. package/dist/bin/chunk-dbgffky8.js +1 -0
  24. package/dist/bin/chunk-ddk4rt4j.js +6 -0
  25. package/dist/bin/chunk-dwr30vbv.js +1 -0
  26. package/dist/bin/chunk-e0rkrq70.js +1 -0
  27. package/dist/bin/chunk-e3xrwh9z.js +1 -0
  28. package/dist/bin/chunk-etrb03mt.js +1507 -0
  29. package/dist/bin/chunk-fhc6ntvd.js +2 -0
  30. package/dist/bin/chunk-fpm59y25.js +6 -0
  31. package/dist/bin/chunk-fvbxvq6b.js +1 -0
  32. package/dist/bin/chunk-fy8j3y8p.js +92 -0
  33. package/dist/bin/chunk-fz21b57w.js +1 -0
  34. package/dist/bin/chunk-gavvf0pg.js +141 -0
  35. package/dist/bin/chunk-ggn7ax8p.js +4 -0
  36. package/dist/bin/chunk-gpe2prkm.js +1 -0
  37. package/dist/bin/chunk-h5pa5men.js +2 -0
  38. package/dist/bin/chunk-hm08xdxf.js +2 -0
  39. package/dist/bin/chunk-hzgz13nf.js +1 -0
  40. package/dist/bin/chunk-j703btc5.js +50 -0
  41. package/dist/bin/chunk-k9t9wvms.js +1 -0
  42. package/dist/bin/chunk-m669wtgr.js +1 -0
  43. package/dist/bin/chunk-m7dgskt1.js +1 -0
  44. package/dist/bin/chunk-mh0kdzqp.js +2 -0
  45. package/dist/bin/chunk-mr0atd2s.js +2 -0
  46. package/dist/bin/chunk-mz0wbbsj.js +3 -0
  47. package/dist/bin/chunk-ngcyftm2.js +1 -0
  48. package/dist/bin/chunk-p66ptpmr.js +2 -0
  49. package/dist/bin/chunk-qk9qgepa.js +1 -0
  50. package/dist/bin/chunk-rxcvf10f.js +7364 -0
  51. package/dist/bin/chunk-rytk89az.js +60 -0
  52. package/dist/bin/chunk-tga3hhwk.js +6 -0
  53. package/dist/bin/chunk-tx0tqq2k.js +8 -0
  54. package/dist/bin/chunk-vek8a0w6.js +1 -0
  55. package/dist/bin/chunk-vm3q5gf2.js +3 -0
  56. package/dist/bin/chunk-y7s5r8y6.js +3 -0
  57. package/dist/bin/chunk-yv9sth30.js +1 -0
  58. package/dist/bin/chunk-zmegvjp8.js +581 -0
  59. package/dist/bin/cli.js +417 -10597
  60. package/dist/bin/dashboard-server.js +1 -6998
  61. package/dist/chunk-0ccta6z6.js +6 -0
  62. package/dist/chunk-0k1cs6pp.js +1 -0
  63. package/dist/chunk-1egjn203.js +704 -0
  64. package/dist/chunk-2wx29qga.js +5 -0
  65. package/dist/chunk-5m5rqmv7.js +1 -0
  66. package/dist/chunk-8ea5022g.js +114 -0
  67. package/dist/chunk-8xqn3c0w.js +2 -0
  68. package/dist/chunk-b4esxhmw.js +2 -0
  69. package/dist/chunk-b8e5wzwn.js +44 -0
  70. package/dist/chunk-bggt4n6e.js +2 -0
  71. package/dist/chunk-cwkg37rs.js +37 -0
  72. package/dist/chunk-dskvqt67.js +7355 -0
  73. package/dist/chunk-gahsdmxf.js +1617 -0
  74. package/dist/chunk-gnv3r2jg.js +1 -0
  75. package/dist/chunk-hg3c48cp.js +34 -0
  76. package/dist/chunk-m5azeva3.js +2 -0
  77. package/dist/chunk-r3qf56b3.js +92 -0
  78. package/dist/chunk-sdqa9ghv.js +141 -0
  79. package/dist/chunk-svrvvcm7.js +1 -0
  80. package/dist/chunk-v0p3hpc3.js +60 -0
  81. package/dist/chunk-wdzjbecg.js +50 -0
  82. package/dist/chunk-ww8k3g7j.js +1 -0
  83. package/dist/chunk-xmqfc62w.js +1 -0
  84. package/dist/chunk-xrebj679.js +435 -0
  85. package/dist/chunk-xt3s24vr.js +2 -0
  86. package/dist/chunk-y21zk0pn.js +4 -0
  87. package/dist/deploy/attach-credentials.d.ts +57 -0
  88. package/dist/deploy/index.js +1 -168
  89. package/dist/deploy/site-ports.d.ts +151 -0
  90. package/dist/deploy/site-target.d.ts +24 -1
  91. package/dist/dns/index.js +1 -41
  92. package/dist/drivers/index.js +1 -154
  93. package/dist/index.js +100 -6129
  94. package/dist/protection/index.js +1 -89
  95. package/dist/push/index.js +1 -509
  96. package/dist/spend/index.js +1 -173
  97. package/dist/ui/404.html +16 -548
  98. package/dist/ui/_stx/chunk.5ddb5087.js +90 -0
  99. package/dist/ui/_stx/chunk.9fd39d5b.js +86 -0
  100. package/dist/ui/_stx/chunk.d5301f79.js +119 -0
  101. package/dist/ui/_stx/crosswind.222ed683.css +1 -0
  102. package/dist/ui/_stx/crosswind.616c25f3.css +1 -0
  103. package/dist/ui/_stx/crosswind.80baa894.css +320 -0
  104. package/dist/ui/_stx/crosswind.906ee17c.css +1 -0
  105. package/dist/ui/_stx/crosswind.996ed49e.css +1 -0
  106. package/dist/ui/_stx/crosswind.b7a99a5c.css +1 -0
  107. package/dist/ui/_stx/router.fa5bc4dc.js +4 -0
  108. package/dist/ui/_stx/runtime.c696d17a.js +1 -0
  109. package/dist/ui/_stx/style.448ab192.css +1 -0
  110. package/dist/ui/accept-invitation.html +2 -1133
  111. package/dist/ui/access-denied.html +7 -1130
  112. package/dist/ui/account/automation.html +12 -1134
  113. package/dist/ui/account/security.html +13 -1136
  114. package/dist/ui/applications/compose.html +12 -1134
  115. package/dist/ui/applications/new.html +13 -1137
  116. package/dist/ui/data/backups.html +91 -1136
  117. package/dist/ui/data/services.html +89 -1136
  118. package/dist/ui/data/volumes.html +61 -1136
  119. package/dist/ui/index.html +60 -1136
  120. package/dist/ui/infrastructure/topology.html +128 -1135
  121. package/dist/ui/integrations.html +13 -1138
  122. package/dist/ui/operations/alerts.html +59 -1136
  123. package/dist/ui/operations/configuration.html +13 -1135
  124. package/dist/ui/operations/jobs.html +87 -1136
  125. package/dist/ui/operations/maintenance.html +12 -1134
  126. package/dist/ui/operations/observability.html +93 -1136
  127. package/dist/ui/operations/previews.html +12 -1134
  128. package/dist/ui/operations/queue.html +12 -1134
  129. package/dist/ui/operations/regions.html +12 -1134
  130. package/dist/ui/operations/releases.html +12 -1134
  131. package/dist/ui/operations/spend.html +65 -1136
  132. package/dist/ui/operations/workloads.html +115 -1136
  133. package/dist/ui/robots.txt +2 -0
  134. package/dist/ui/security.html +24 -1136
  135. package/dist/ui/server/actions.html +67 -1138
  136. package/dist/ui/server/activity.html +7 -1130
  137. package/dist/ui/server/capacity.html +12 -1134
  138. package/dist/ui/server/database.html +166 -1135
  139. package/dist/ui/server/deployments.html +60 -1136
  140. package/dist/ui/server/diagnostics.html +7 -1130
  141. package/dist/ui/server/firewall.html +286 -1212
  142. package/dist/ui/server/fleet.html +45 -1136
  143. package/dist/ui/server/logs.html +34 -1135
  144. package/dist/ui/server/metrics.html +124 -1140
  145. package/dist/ui/server/security.html +7 -1130
  146. package/dist/ui/server/services.html +46 -1133
  147. package/dist/ui/server/sites.html +287 -1137
  148. package/dist/ui/server/ssh-keys.html +62 -1135
  149. package/dist/ui/server/team.html +155 -1136
  150. package/dist/ui/server/terminal.html +97 -1183
  151. package/dist/ui/serverless/alarms.html +62 -1135
  152. package/dist/ui/serverless/assets.html +47 -1132
  153. package/dist/ui/serverless/cost.html +7 -1130
  154. package/dist/ui/serverless/data.html +46 -1135
  155. package/dist/ui/serverless/deployments.html +47 -1132
  156. package/dist/ui/serverless/firewall.html +7 -1130
  157. package/dist/ui/serverless/functions.html +50 -1136
  158. package/dist/ui/serverless/logs.html +34 -1135
  159. package/dist/ui/serverless/metrics.html +7 -1130
  160. package/dist/ui/serverless/queues.html +58 -1135
  161. package/dist/ui/serverless/secrets.html +62 -1136
  162. package/dist/ui/serverless/traces.html +12 -1134
  163. package/dist/ui/serverless.html +64 -1137
  164. package/dist/ui-src/pages/server/firewall.stx +14 -14
  165. package/package.json +3 -3
  166. package/dist/chunk-01d86gt1.js +0 -1324
  167. package/dist/chunk-050r7ycy.js +0 -46516
  168. package/dist/chunk-29rse4p1.js +0 -12203
  169. package/dist/chunk-32e7ya18.js +0 -642
  170. package/dist/chunk-4cjrg98a.js +0 -597
  171. package/dist/chunk-50jpda9q.js +0 -371
  172. package/dist/chunk-6a1t7fnq.js +0 -12121
  173. package/dist/chunk-728jvrr0.js +0 -1701
  174. package/dist/chunk-7m60qnc8.js +0 -1762
  175. package/dist/chunk-aa2dkn7b.js +0 -205
  176. package/dist/chunk-d48vtdj4.js +0 -433
  177. package/dist/chunk-f55nkpvb.js +0 -8
  178. package/dist/chunk-fgk8cqew.js +0 -152
  179. package/dist/chunk-he9a874b.js +0 -769
  180. package/dist/chunk-hg7rhrgd.js +0 -7274
  181. package/dist/chunk-k2yyatfw.js +0 -10
  182. package/dist/chunk-k4px0bnv.js +0 -23
  183. package/dist/chunk-nsgqsmrh.js +0 -1779
  184. package/dist/chunk-qr803fye.js +0 -2122
  185. package/dist/chunk-rds0sy87.js +0 -1771
  186. package/dist/chunk-rxgchb08.js +0 -42033
  187. package/dist/chunk-ttz2ra5j.js +0 -12
  188. package/dist/chunk-v0bahtg2.js +0 -4
  189. package/dist/chunk-va2yd85b.js +0 -200
  190. package/dist/chunk-x9s0cqfx.js +0 -13
  191. package/dist/chunk-zqtpg06c.js +0 -1752
@@ -0,0 +1,704 @@
1
+ import{ud as Iu}from"./chunk-v0p3hpc3.js";import{Bd as ea,Cd as Hu,Dd as Xa,Ed as zt,Fd as ot,Gd as ts,Hd as Nu}from"./chunk-2wx29qga.js";import{Jd as si,Kd as Hs,Oe as zp,Pe as Ts,Rd as Yu,Td as ko,Ud as Kr,Wd as Cn,Xd as Et,Yd as oi,nf as Xu}from"./chunk-8ea5022g.js";import{of as Ya}from"./chunk-hg3c48cp.js";import{sf as An}from"./chunk-sdqa9ghv.js";import{tf as $u}from"./chunk-bggt4n6e.js";import{uf as Un}from"./chunk-m5azeva3.js";import{$f as Dg,Bg as DR,Bh as Lg,Eh as Qo,Jg as nr,Xf as Ja,Yf as XR,Zf as qR,_f as Rg,ag as hp,bg as _n,gg as Hr,ph as fp,qh as Sp}from"./chunk-xrebj679.js";import{Oh as FI}from"./chunk-y21zk0pn.js";import{Ph as wr}from"./chunk-b4esxhmw.js";import{Qh as Zu,Rh as lr}from"./chunk-r3qf56b3.js";import{Th as gi,Uh as Gu}from"./chunk-0ccta6z6.js";import{$h as qt,Ai as Be,Ak as NI,Bi as kI,Ci as Wh,Di as fs,Gi as bI,Li as vI,Mi as OI,Ni as BI,Nk as ne,Oi as JI,Pk as Nd,Qi as TI,Qk as Qh,Rk as Lh,Ui as Ss,Yh as ms,Zh as fu,ai as Na,ak as Mh,hi as Oe,ii as Su,ik as zI,ji as DI,lk as WI,mk as Gi,ni as hs,qk as Ua,rk as jI,sk as UI,vi as $I,vj as xh,vk as dI,wi as CI,wk as HI,zi as As,zk as qo}from"./chunk-gahsdmxf.js";import{$m as Au,$s as ju,Ll as S_,Nl as fa,Ol as _t,Pl as Du,Rl as Ur,Tl as ht,Ul as Yl,Wm as wu,fm as ci,ft as Uu,gm as vu,hm as Ou,ms as Bu,ns as Ju,ps as Tu,qs as as,rs as zu,ss as Wu}from"./chunk-dskvqt67.js";import{qt as tt}from"./chunk-xt3s24vr.js";import{createHash as am}from"node:crypto";function sm(e){return am("sha256").update(wn(e)).digest("hex")}function wn(e){if(Array.isArray(e))return`[${e.map((t)=>wn(t)).join(",")}]`;if(e&&typeof e==="object")return`{${Object.entries(e).filter(([,t])=>t!==void 0&&typeof t!=="function").sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>`${JSON.stringify(t)}:${wn(r)}`).join(",")}}`;return JSON.stringify(e)??"null"}function Ke(e,t){let r=`dashboard:${t.username.toLowerCase()}`;return e.getActorByExternalId("user",r)??e.createActor({kind:"user",externalId:r,displayName:t.name??t.username,metadata:{source:"dashboard",role:t.role}})}function _u(e,t){let r=new Su({cwd:e}),n=sm(t),i=r.getProjectBySlug(t.project.slug),a=t.project.slug.length>=3?t.project.slug:`${t.project.slug}-org`,s=(i?.organizationId?r.getOrganization(i.organizationId):void 0)??r.getOrganizationBySlug(a)??r.createOrganization({id:i?.organizationId,slug:a,name:t.project.name}),d=i?i.name!==t.project.name||i.desiredConfigHash!==n||i.organizationId!==s.id?r.updateProject(i.id,i.version,{name:t.project.name,organizationId:s.id,desiredConfigHash:n}):i:r.createProject({organizationId:s.id,slug:t.project.slug,name:t.project.name,desiredConfigHash:n}),c=new Map;for(let[_,R]of Object.entries(t.environments??{})){let y=r.getEnvironmentBySlug(d.id,_)??r.createEnvironment({projectId:d.id,slug:_,name:_.replace(/(^|[-_])(\w)/g,(B,N,F)=>F.toUpperCase()),kind:String(R?.type??_),region:R?.region??t.project.region,desiredState:Oe(R)});c.set(_,y);let $=new Map(r.listResources(d.id,y.id).map((B)=>[`${B.kind}:${B.slug}`,B])),b=(B,N,F,J)=>{let Z=`${B}:${N}`,O=$.get(Z),K=Oe(J);if(O){if(O.name!==F||wn(O.desiredState)!==wn(K))$.set(Z,r.updateResource(O.id,O.version,{name:F,desiredState:K}));return}let ae=r.createResource({projectId:d.id,environmentId:y.id,kind:B,slug:N,name:F,provider:t.cloud?.provider,desiredState:K,metadata:{source:"cloud-config"}});$.set(Z,ae)};for(let[B,N]of Object.entries(t.sites??{}))b("application",B,B,N);let z=R?.app;if(z)for(let B of["http","queue","cli"])b("function",B,`${B.toUpperCase()} function`,{...Oe(z),function:B});let C=t.infrastructure;for(let[B,N]of Object.entries(C?.functions??{}))b("function",B,B,N);if(C?.compute)b("server",`${d.slug}-server`,d.name,{...Oe(C.compute),label:d.name});for(let[B,N]of Object.entries(C?.databases??{}))b("database",B,B,N);if(C?.appDatabase)b("database","application-database","Application database",C.appDatabase);else if(C?.database)b("database","application-database","Application database",{engine:C.database})}let o=new Be(r).recoverExpired(),g=r.reconcileOrphanedOperations({policy:"fail"}),h={requeued:o.requeued+g.requeued,failed:o.failed+o.cancelled+g.failed};return{store:r,organization:s,project:d,environments:c,reconciliation:h}}var om=["project:read","config:read","deployments:read","deployments:create","runtime:read","runtime:logs"];function Ka(e,t){let{store:r,organization:n,project:i}=e,a=new Set;for(let s of t){let d=Ke(r,s);a.add(d.id);let c=r.getMembershipForActor(n.id,d.id);if(c&&c.source!=="legacy")continue;let o=r.listResources(i.id).filter((E)=>E.kind==="application"&&Object.hasOwn(s.sites,E.slug)),g=s.role==="admin"?"owner":"viewer",h=s.role==="admin"||o.length===0?{type:"organization"}:{type:"resource",id:o[0].id},_=c?c.roleTemplate!==g||wn(c.scope)!==wn(h)?r.updateMembership({id:c.id,roleTemplate:g,scope:h,actorId:d.id}):c:r.createMembership({organizationId:n.id,actorId:d.id,roleTemplate:g,scope:h,source:"legacy"}),R=new Set;if(s.role==="member"&&o.length===0)for(let E of fu("viewer"))R.add(`deny|${E}|organization|`);for(let E of o){let y=s.sites[E.slug];for(let $ of om)R.add(`allow|${$}|resource|${E.id}`);if(y==="owner")R.add(`allow|config:write|resource|${E.id}`)}for(let E of r.listGrants(_.id).filter((y)=>y.source==="legacy")){let y=`${E.effect}|${E.capability}|${E.scope.type}|${E.scope.id??""}`;if(!R.has(y))r.removeGrant(E.id,d.id)}for(let E of R){let[y,$,b,z]=E.split("|");r.upsertGrant({organizationId:n.id,membershipId:_.id,effect:y,capability:$,scope:b==="organization"?{type:"organization"}:{type:b,id:z},source:"legacy"})}}for(let s of r.listMemberships(n.id))if(s.source==="legacy"&&!a.has(s.actorId))r.revokeMembership(s.id)}async function yr(e){let{controlPlane:t,environment:r,actor:n}=e,i=Ke(t.store,n),a=t.environments.get(r),s=e.resourceSlug&&a?t.store.listResources(t.project.id,a.id).find((g)=>g.slug===e.resourceSlug):void 0,d=new Be(t.store,{workerId:`dashboard:${process.pid}`}),c=d.enqueue({projectId:t.project.id,environmentId:a?.id,resourceId:s?.id,actorId:i.id,kind:e.kind,input:e.input??{},lockKey:s?`resource:${s.id}`:a?`environment:${a.id}`:`project:${t.project.id}`,providerKey:s?.provider??"dashboard",buildSlot:e.kind.includes("deploy"),maxAttempts:1,timeoutSeconds:3600,resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;if(!d.claim(c.id)?.operation)throw Error(`Could not claim control-plane operation ${c.id}`);try{let g=await e.execute(),h=typeof g.stdout==="string"?String(g.stdout):"",_=typeof g.stderr==="string"?String(g.stderr):"";if(h)d.appendLog(c.id,h,{stream:"stdout"});if(_)d.appendLog(c.id,_,{stream:"stderr"});let R=g.ok?d.complete(c.id,hu(g)):d.fail(c.id,dm(g),hu(g));return{result:g,operation:R}}catch(g){throw d.fail(c.id,g instanceof Error?g.message:String(g),{ok:!1,threw:!0}),g}}function dm(e){let t=e;return String(t.error??t.stderr??"Operation failed")}function hu(e){let t=e,r=typeof t.stdout==="string"?t.stdout:"",n=typeof t.stderr==="string"?t.stderr:"",i={ok:e.ok,stdoutBytes:Buffer.byteLength(r),stderrBytes:Buffer.byteLength(n)};if(typeof t.operation==="string")i.operation=t.operation;if(typeof t.error==="string")i.error=t.error;return Oe(i)}var Ru=[{id:"server.overview",path:"/",label:"Dashboard",group:"overview",modes:["server"],adminOnly:!0,legacyPaths:["/server"]},{id:"server.activity",path:"/server/activity",label:"Activity",group:"overview",modes:["server"],adminOnly:!0,legacyPaths:["/activity"]},{id:"services.list",path:"/server/sites",label:"Services",group:"applications",modes:["server"],adminOnly:!1,legacyPaths:["/sites","/services"]},{id:"deployments.list",path:"/server/deployments",label:"Deployments",group:"applications",modes:["server"],adminOnly:!1,legacyPaths:["/deployments"]},{id:"logs.list",path:"/server/logs",label:"Logs",group:"applications",modes:["server"],adminOnly:!1,legacyPaths:["/logs"]},{id:"sources.integrations",path:"/integrations",label:"Git integrations",group:"applications",modes:["server","serverless"],adminOnly:!1},{id:"applications.create",path:"/applications/new",label:"Create application",group:"applications",modes:["server","serverless"],adminOnly:!1},{id:"applications.compose",path:"/applications/compose",label:"Compose applications",group:"applications",modes:["server"],adminOnly:!1},{id:"operations.queue",path:"/operations/queue",label:"Deployment queue",group:"operations",modes:["server","serverless"],adminOnly:!1},{id:"operations.previews",path:"/operations/previews",label:"Preview environments",group:"operations",modes:["server","serverless"],adminOnly:!1},{id:"operations.releases",path:"/operations/releases",label:"Releases & promotion",group:"operations",modes:["server","serverless"],adminOnly:!1},{id:"runtime.workloads",path:"/operations/workloads",label:"Workloads",group:"operations",modes:["server","serverless"],adminOnly:!1},{id:"observability.overview",path:"/operations/observability",label:"Observability",group:"operations",modes:["server","serverless"],adminOnly:!1},{id:"alerts.overview",path:"/operations/alerts",label:"Alerts & health",group:"operations",modes:["server","serverless"],adminOnly:!1},{id:"spend.overview",path:"/operations/spend",label:"Spend & budgets",group:"operations",modes:["server","serverless"],adminOnly:!1},{id:"automation.jobs",path:"/operations/jobs",label:"Workers & schedules",group:"operations",modes:["server","serverless"],adminOnly:!1,legacyPaths:["/server/workers","/serverless/scheduler"]},{id:"configuration.entries",path:"/operations/configuration",label:"Environment & secrets",group:"operations",modes:["server","serverless"],adminOnly:!1,legacyPaths:["/serverless/secrets"]},{id:"metrics.overview",path:"/server/metrics",label:"Metrics",group:"operations",modes:["server"],adminOnly:!0},{id:"runtime.services",path:"/server/services",label:"Runtime services",group:"operations",modes:["server"],adminOnly:!0},{id:"backups.list",path:"/data/backups",label:"Backups & recovery",group:"operations",modes:["server","serverless"],adminOnly:!1,legacyPaths:["/server/backups"]},{id:"volumes.list",path:"/data/volumes",label:"Persistent volumes",group:"operations",modes:["server","serverless"],adminOnly:!1,legacyPaths:[]},{id:"fleet.list",path:"/server/fleet",label:"Fleet inventory",group:"operations",modes:["server"],adminOnly:!1,legacyPaths:[]},{id:"operations.run",path:"/server/actions",label:"Run operations",group:"operations",modes:["server"],adminOnly:!0},{id:"infrastructure.topology",path:"/infrastructure/topology",label:"Infrastructure map",group:"infrastructure",modes:["server","serverless"],adminOnly:!0,legacyPaths:["/topology"]},{id:"data.services",path:"/data/services",label:"Data services",group:"infrastructure",modes:["server","serverless"],adminOnly:!1,legacyPaths:["/database","/databases","/server/database","/serverless/data"]},{id:"network.firewall",path:"/server/firewall",label:"Network & firewall",group:"infrastructure",modes:["server"],adminOnly:!0},{id:"security.posture",path:"/security",label:"Security posture",group:"infrastructure",modes:["server","serverless"],adminOnly:!1,legacyPaths:["/server/security"]},{id:"access.ssh",path:"/server/ssh-keys",label:"SSH keys",group:"infrastructure",modes:["server"],adminOnly:!0},{id:"runtime.terminal",path:"/server/terminal",label:"Terminal",group:"infrastructure",modes:["server"],adminOnly:!0},{id:"organization.people",path:"/server/team",label:"People & access",group:"organization",modes:["server","serverless"],adminOnly:!0,legacyPaths:["/team"]},{id:"organization.automation",path:"/account/automation",label:"API & automation",group:"organization",modes:["server","serverless"],adminOnly:!0},{id:"serverless.overview",path:"/serverless",label:"Dashboard",group:"overview",modes:["serverless"],adminOnly:!0},{id:"serverless.deployments",path:"/serverless/deployments",label:"Deployments",group:"overview",modes:["serverless"],adminOnly:!0},{id:"serverless.logs",path:"/serverless/logs",label:"Logs",group:"overview",modes:["serverless"],adminOnly:!0},{id:"serverless.metrics",path:"/serverless/metrics",label:"Metrics",group:"overview",modes:["serverless"],adminOnly:!0},{id:"serverless.traces",path:"/serverless/traces",label:"Traces",group:"overview",modes:["serverless"],adminOnly:!0},{id:"serverless.functions",path:"/serverless/functions",label:"Functions",group:"compute-data",modes:["serverless"],adminOnly:!0},{id:"serverless.queues",path:"/serverless/queues",label:"Queues",group:"compute-data",modes:["serverless"],adminOnly:!0},{id:"serverless.assets",path:"/serverless/assets",label:"Assets",group:"compute-data",modes:["serverless"],adminOnly:!0},{id:"serverless.network",path:"/serverless/firewall",label:"Network",group:"settings",modes:["serverless"],adminOnly:!0},{id:"serverless.alerts",path:"/serverless/alarms",label:"Alerts",group:"settings",modes:["serverless"],adminOnly:!0},{id:"serverless.cost",path:"/serverless/cost",label:"Costs",group:"settings",modes:["serverless"],adminOnly:!0}],cm=new Map(Ru.flatMap((e)=>(e.legacyPaths??[]).map((t)=>[t,e.path])));function pu(e){return cm.get(e)}function TC(e,t){return Ru.filter((r)=>r.modes.includes(e)&&(!t||!r.adminOnly))}import Zr from"node:process";import{existsSync as lm}from"node:fs";import{join as gm}from"node:path";async function NC(e){let t=Date.now(),r=e.sourceDir??"dist";if(!lm(gm(r,"index.html")))return gd(t,`${r}/ has no index.html — build first.`);if(!Zr.env.AWS_ACCESS_KEY_ID||!Zr.env.AWS_SECRET_ACCESS_KEY)return gd(t,"Missing AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY in env.");let n=um(e.dnsProvider);if("error"in n)return gd(t,n.error);let i=await Iu({siteName:e.siteName,region:e.region??"us-east-1",domain:e.domain,bucket:e.bucket,stackName:e.stackName,certificateArn:e.certificateArn,defaultRootObject:e.defaultRootObject??"index.html",errorDocument:e.errorDocument??"404.html",cacheControl:e.cacheControl??"max-age=3600, public",sourceDir:r,cleanBucket:e.cleanBucket??!1,singlePageApp:e.singlePageApp??!1,dnsProvider:n,tags:{ManagedBy:"ts-cloud",Application:e.siteName,...e.tags},onProgress:e.onProgress});return{success:!!i.success,domain:i.domain,url:i.domain?`https://${i.domain}`:i.distributionDomain?`https://${i.distributionDomain}`:void 0,bucket:i.bucket,distributionId:i.distributionId,distributionDomain:i.distributionDomain,certificateArn:i.certificateArn,filesUploaded:i.filesUploaded,filesSkipped:i.filesSkipped,message:i.message,durationMs:Date.now()-t}}function um(e){let t=typeof e==="string"?{provider:e}:e??{provider:"porkbun"};if(t.provider==="porkbun"){let r=t,n=r?.apiKey??Zr.env.PORKBUN_API_KEY,i=r?.secretKey??Zr.env.PORKBUN_SECRET_KEY??Zr.env.PORKBUN_SECRET_API_KEY;if(!n||!i)return{error:"Missing PORKBUN_API_KEY / PORKBUN_SECRET_KEY in env."};return{provider:"porkbun",apiKey:n,secretKey:i}}if(t.provider==="godaddy"){let r=t,n=r?.apiKey??Zr.env.GODADDY_API_KEY,i=r?.secretKey??Zr.env.GODADDY_API_SECRET,a=r?.environment??Zr.env.GODADDY_ENVIRONMENT;if(!n||!i)return{error:"Missing GODADDY_API_KEY / GODADDY_API_SECRET in env."};return{provider:"godaddy",apiKey:n,apiSecret:i,environment:a}}return{error:`Unsupported DNS provider: ${t.provider}`}}function gd(e,t){return{success:!1,message:t,durationMs:Date.now()-e}}import{createHash as hm}from"node:crypto";var fm=`let coldStart = true
2
+ const initializedAt = new Date().toISOString()
3
+ export const handler = async (event) => {
4
+ const currentColdStart = coldStart
5
+ coldStart = false
6
+ const path = event.rawPath || event.requestContext?.http?.path || '/'
7
+ const statusCode = path === '/api/health' || path === '/health' ? 200 : 404
8
+ return {
9
+ statusCode,
10
+ headers: { 'content-type': 'application/json', 'cache-control': 'no-store' },
11
+ body: JSON.stringify({ ok: statusCode === 200, service: 'ts-cloud-static-api', path, coldStart: currentColdStart, initializedAt })
12
+ }
13
+ }
14
+ `;function yu(e){let t=e;return String(t?.code||t?.name||t?.statusCode||"")}function Sm(e){return["NoSuchEntity","ResourceNotFoundException","404"].includes(yu(e))}function mu(e){return["EntityAlreadyExists","ResourceAlreadyExistsException","ResourceConflictException","409"].includes(yu(e))}function Eu(e,t){let r=e?.Items;if(!r)return[];if(Array.isArray(r))return r;let n=r[t];if(n===void 0)return[];return Array.isArray(n)?n:[n]}function ud(e){let t=e?.Aliases?.Items;if(Array.isArray(t))return t.map(String);if(typeof t==="string")return[t];return[]}function _m(e){if(!/^[A-Z0-9]{8,32}$/.test(e.distributionId))throw Error("CloudFront distribution ID is invalid");if(!/^(?=.{1,253}$)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z0-9-]{2,63}$/.test(e.expectedAlias))throw Error("Expected CloudFront alias is invalid");if(!/^[A-Za-z0-9-_]{1,64}$/.test(e.functionName))throw Error("Lambda function name is invalid");let t=e.pathPattern?.startsWith("/")?e.pathPattern:`/${e.pathPattern||"api/*"}`;if(t==="/"||t==="/*"||!t.endsWith("*"))throw Error("API path must be a non-default wildcard pattern such as /api/*");let r=e.originId||`${e.functionName}-url`,n=e.roleName||`${e.functionName}-execution`;if(!/^[A-Za-z0-9_.-]{1,64}$/.test(n))throw Error("IAM role name is invalid");let i=e.memorySize??256,a=e.timeout??10,s=e.logRetentionDays??14;if(i<128||i>10240)throw Error("Lambda memory must be between 128 and 10240 MB");if(a<1||a>900)throw Error("Lambda timeout must be between 1 and 900 seconds");return{region:e.region||"us-east-1",pathPattern:t,originId:r,roleName:n,memorySize:i,timeout:a,logRetentionDays:s}}function Rm(e){let t=e.region||"us-east-1";return{cloudfront:new An(e.profile),iam:new Ya(t,e.profile),lambda:new Et(t,e.profile),logs:new oi(t,e.profile),sts:new si(t,e.profile),sleep:(r)=>new Promise((n)=>setTimeout(n,r))}}async function ZC(e,t){let r=_m(e),n=t||Rm({profile:e.profile,region:r.region}),[i,a,s]=await Promise.all([n.sts.getCallerIdentity(),n.cloudfront.getDistribution(e.distributionId),n.cloudfront.getDistributionConfig(e.distributionId)]);if(!i.Account)throw Error("AWS identity did not return an account ID");if(!a.Enabled)throw Error(`CloudFront distribution ${e.distributionId} is disabled`);if(!(ud(a).length?ud(a):ud(s.DistributionConfig)).includes(e.expectedAlias))throw Error(`Distribution ${e.distributionId} does not contain expected alias ${e.expectedAlias}`);let c,o=!0;try{c=await n.iam.getRole({RoleName:r.roleName})}catch(de){if(!Sm(de))throw de;o=!1}let g=c?.Arn||`arn:aws:iam::${i.Account}:role/${r.roleName}`,h=await n.lambda.functionExists(e.functionName),_=h?await n.lambda.getFunctionUrl(e.functionName):null,R=await n.cloudfront.listOriginAccessControls(),E=`${e.functionName}-lambda-url`,y=R.some((de)=>de.Name===E&&de.OriginAccessControlOriginType==="lambda"),$=Eu(s.DistributionConfig.Origins,"Origin"),b=Eu(s.DistributionConfig.CacheBehaviors,"CacheBehavior"),z=$.some((de)=>String(de.Id)===r.originId),C=b.some((de)=>String(de.PathPattern)===r.pathPattern),B=[...!o?[`create IAM execution role ${r.roleName}`]:[`reconcile IAM execution policy ${r.roleName}`],...h?[`update Lambda ${e.functionName} code and configuration`]:[`create Lambda ${e.functionName}`],...!_?["create private AWS_IAM function URL"]:[],...!y?[`create Lambda origin access control ${E}`]:[],"grant CloudFront function-URL and invocation permissions",`${C?"reconcile":"add"} ${r.pathPattern} behavior without changing the default behavior`],N={command:`cloud cdn:origin:remove ${e.distributionId} FUNCTION_URL_HOST --id ${r.originId} --path '${r.pathPattern}' --apply --confirm 'remove:${e.distributionId}:${r.pathPattern}'`,removeFunction:!h,removeRole:!o},F={mode:e.apply?"apply":"plan",accountId:i.Account,identityArn:i.Arn,distribution:{id:a.Id,arn:a.ARN,alias:e.expectedAlias,domainName:a.DomainName,status:a.Status},function:{name:e.functionName,existed:h,runtime:"nodejs22.x",urlExisted:!!_,url:_?.FunctionUrl},role:{name:r.roleName,existed:o,arn:g},origin:{id:r.originId,pathPattern:r.pathPattern,existed:z,behaviorExisted:C,accessControlExisted:y},changes:B,rollback:N,applied:!1};if(!e.apply)return F;let J=`${e.distributionId}:${r.pathPattern}`;if(e.confirm!==J)throw Error(`Pass exact confirmation token ${J} to mutate the live distribution`);if(!c)c=await n.iam.createRole({RoleName:r.roleName,Description:`Execution role for ${e.functionName}`,AssumeRolePolicyDocument:JSON.stringify({Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]}),Tags:[{Key:"ManagedBy",Value:"ts-cloud"}]});await n.iam.putRolePolicy({RoleName:r.roleName,PolicyName:"lambda-logs",PolicyDocument:JSON.stringify({Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["logs:CreateLogStream","logs:PutLogEvents"],Resource:`arn:aws:logs:${r.region}:${i.Account}:log-group:/aws/lambda/${e.functionName}:*`}]})});try{await n.logs.createLogGroup(`/aws/lambda/${e.functionName}`,{ManagedBy:"ts-cloud"})}catch(de){if(!mu(de))throw de}await n.logs.putRetentionPolicy(`/aws/lambda/${e.functionName}`,r.logRetentionDays);let Z=e.code||fm;if(h)await n.lambda.updateFunctionCodeInline(e.functionName,Z,"index.mjs"),await n.lambda.waitForFunctionActive(e.functionName),await n.lambda.updateFunctionConfiguration({FunctionName:e.functionName,Runtime:"nodejs22.x",Role:c.Arn,Handler:"index.handler",Description:`Private API origin for ${e.expectedAlias}`,Timeout:r.timeout,MemorySize:r.memorySize});else{let de;for(let Ae=0;Ae<8;Ae++)try{await n.lambda.createFunctionWithCode({FunctionName:e.functionName,Runtime:"nodejs22.x",Role:c.Arn,Handler:"index.handler",Code:Z,Filename:"index.mjs",Description:`Private API origin for ${e.expectedAlias}`,Timeout:r.timeout,MemorySize:r.memorySize}),de=void 0;break}catch(ze){if(de=ze,!String(ze.message).toLowerCase().includes("role"))throw ze;await n.sleep(1000)}if(de)throw de}await n.lambda.waitForFunctionActive(e.functionName);let O=_||await n.lambda.createFunctionUrl({FunctionName:e.functionName,AuthType:"AWS_IAM",InvokeMode:"BUFFERED"});if(!O.FunctionUrl)throw Error("Lambda did not return a function URL");let K=new URL(O.FunctionUrl).hostname,ae=await n.cloudfront.findOrCreateOriginAccessControl(E,"lambda"),Se=a.ARN||`arn:aws:cloudfront::${i.Account}:distribution/${e.distributionId}`,Te=[{FunctionName:e.functionName,StatementId:"AllowCloudFrontFunctionUrl",Action:"lambda:InvokeFunctionUrl",Principal:"cloudfront.amazonaws.com",SourceArn:Se,FunctionUrlAuthType:"AWS_IAM"},{FunctionName:e.functionName,StatementId:"AllowCloudFrontInvoke",Action:"lambda:InvokeFunction",Principal:"cloudfront.amazonaws.com",SourceArn:Se,InvokedViaFunctionUrl:!0}];for(let de of Te)try{await n.lambda.addPermission(de)}catch(Ae){if(!mu(Ae))throw Ae}return await n.cloudfront.upsertExistingDistributionOrigin(e.distributionId,{id:r.originId,domainName:K,pathPattern:r.pathPattern,originAccessControlId:ae.Id}),{...F,function:{...F.function,url:O.FunctionUrl},applied:!0}}async function KC(e){let t=`https://${e.alias}/`,r=`https://${e.alias}/api/health`,n=await fetch(t,{redirect:"follow",headers:{"cache-control":"no-cache"}}),i=new Uint8Array(await n.arrayBuffer()),a=hm("sha256").update(i).digest("hex"),s=Date.now(),d=await fetch(r,{redirect:"follow",headers:{"cache-control":"no-cache"}}),c=Date.now()-s,o=await d.text(),g=o;try{g=JSON.parse(o)}catch{}let h;if(e.logs&&e.functionName){let _=await e.logs.filterLogEvents({logGroupName:`/aws/lambda/${e.functionName}`,startTime:s-60000,filterPattern:'"Init Duration"',limit:25});for(let R of _.events||[]){let E=R.message?.match(/Init Duration:\s*([0-9.]+)\s*ms/i);if(E)h=Number(E[1])}}return{frontend:{url:t,status:n.status,sha256:a,unchanged:e.expectedFrontendSha256?a===e.expectedFrontendSha256:void 0,bytes:i.byteLength},api:{url:r,status:d.status,latencyMs:c,healthy:d.ok&&!!g?.ok,body:g},coldStart:{observed:h!==void 0,initDurationMs:h},verifiedAt:(e.now?.()||new Date).toISOString()}}function YC(e){let t=(e.memoryMb||256)/1024,r=Math.max(0,e.requests-(e.includeFreeTier===!1?0:1e6)),n=Math.max(0,e.requests*(e.averageDurationMs/1000)*t-(e.includeFreeTier===!1?0:400000)),i=r/1e6*0.2+n*0.0000166667,a=9.010025,s=16.425;return{lambdaUsd:Number(i.toFixed(2)),alwaysOnFargateAndAlbUsd:Number(25.435025000000003 .toFixed(2)),assumptions:["us-east-1 public list rates snapshot, July 2026","Lambda x86 request and duration pricing with optional monthly free tier","Fargate comparison uses one always-on 0.25 vCPU/0.5 GB task plus one ALB before LCU charges","excludes CloudFront, data transfer, logs, taxes, and application data services"]}}import{createHash as pm}from"node:crypto";function Im(e){let t=e;return String(t?.code||t?.name||t?.statusCode||"")}function mm(e){return Im(e)==="ValidationError"&&String(e.message).includes("does not exist")}function Em(e){return Object.fromEntries((e||[]).map((t)=>[t.OutputKey,t.OutputValue]))}function ym(e){let t=e?.Aliases?.Items??e?.Aliases;if(Array.isArray(t))return t.map(String);if(typeof t==="string")return[t];return[]}function Pu(e){if(!/^[a-z][a-z0-9-]{1,62}$/.test(e.slug))throw Error("Slug must be a lowercase DNS-safe identifier");if(!/^[A-Z0-9]{8,32}$/.test(e.distributionId))throw Error("CloudFront distribution ID is invalid");if(!/^(?=.{1,253}$)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z0-9-]{2,63}$/.test(e.expectedAlias))throw Error("Expected distribution alias is invalid");let t=e.imageUri.match(/@((?:sha256:)[a-f0-9]{64})$/i)?.[1];if(!t)throw Error("Container image must use an immutable ECR digest URI ending in @sha256:<64 hex>");let r=e.stackName||`${e.slug}-backend`;if(!/^[A-Za-z][A-Za-z0-9-]{0,127}$/.test(r))throw Error("CloudFormation stack name is invalid");let n=e.pathPattern||"/api/*";if(!/^\/[A-Za-z0-9_.*?~!$&'()+,;=:@%/-]+\*$/.test(n)||n==="/*")throw Error("Backend path must be a non-default wildcard pattern");let i=e.originId||`${e.slug}-backend`;if(!/^[A-Za-z0-9_.-]{1,128}$/.test(i))throw Error("CloudFront origin ID is invalid");if(e.originVerifySecret&&e.originVerifySecret.length<24)throw Error("Origin verification secret must contain at least 24 characters");if(!!e.originDomain!==!!e.certificateArn)throw Error("A custom origin domain and matching ACM certificate ARN must be provided together");return{stackName:r,region:e.region||"us-east-1",pathPattern:n,originId:i,digest:t}}function wm(e){let t=e.region||"us-east-1";return{cloudformation:new wr(t,e.profile),cloudfront:new An(e.profile),sts:new si(t,e.profile),fetch,sleep:(r)=>new Promise((n)=>setTimeout(n,r))}}function Am(e){let t=Pu(e),r=Au({name:e.name,slug:e.slug,domain:e.originDomain||e.expectedAlias,imageUri:e.imageUri,certificateArn:e.certificateArn,originVerifySecret:e.originVerifySecret,desiredCount:e.desiredCount,database:e.database,cache:e.cache,queue:e.queue}),n=wu(r);return n.Description=`Managed backend for existing static frontend ${e.expectedAlias}`,n.Metadata={ManagedBy:"ts-cloud",ExistingDistributionId:e.distributionId,ExistingDistributionAlias:e.expectedAlias,BackendPathPattern:t.pathPattern,ContainerDigest:t.digest},n}async function Pm(e,t,r){let n;for(let i=0;i<30;i++){let a=Date.now();try{let s=await e.fetch(t,{redirect:"manual",headers:r?{"x-origin-verify":r}:void 0}),d=Date.now()-a,c=await s.text(),o=c;try{o=JSON.parse(c)}catch{}if(s.ok)return{url:t,status:s.status,latencyMs:d,body:o};n=Error(`origin returned ${s.status}`)}catch(s){n=s}if(i<29)await e.sleep(1e4)}throw Error(`Backend origin did not become healthy: ${n instanceof Error?n.message:String(n)}`)}async function ik(e,t){let r=Pu(e),n=t||wm({region:r.region,profile:e.profile}),[i,a]=await Promise.all([n.sts.getCallerIdentity(),n.cloudfront.getDistribution(e.distributionId)]);if(!i.Account)throw Error("AWS identity did not return an account ID");if(!a.Enabled)throw Error(`CloudFront distribution ${e.distributionId} is disabled`);if(!ym(a).includes(e.expectedAlias))throw Error(`Distribution ${e.distributionId} does not contain expected alias ${e.expectedAlias}`);let s;try{s=(await n.cloudformation.describeStacks({stackName:r.stackName})).Stacks[0]}catch(B){if(!mm(B))throw B}let d=Am(e),c=JSON.stringify(d);if(Buffer.byteLength(c)>51200)throw Error("Generated template exceeds the direct CloudFormation template body limit");let o=Object.values(d.Resources||{}).reduce((B,N)=>{return B[N.Type]=(B[N.Type]||0)+1,B},{}),g=[`cloud cdn:origin:remove ${e.distributionId} ${e.originDomain||"ALB_HOST"} --id ${r.originId} --path '${r.pathPattern}' --profile ${e.profile||"default"} --apply --confirm 'remove:${e.distributionId}:${r.pathPattern}'`,`After CloudFront is deployed, restore external DNS if changed and delete stack ${r.stackName} only with an approved data-retention decision.`],h={mode:e.apply?"apply":"plan",accountId:i.Account,stack:{name:r.stackName,existed:!!s,status:s?.StackStatus,templateSha256:pm("sha256").update(c).digest("hex"),resourceCount:Object.keys(d.Resources||{}).length,resourceTypes:o},distribution:{id:a.Id,alias:e.expectedAlias,domainName:a.DomainName,status:a.Status,pathPattern:r.pathPattern,originId:r.originId},artifact:{imageUri:e.imageUri,digest:r.digest},services:{database:e.database!==!1,cache:e.cache!==!1,queue:e.queue!==!1,mail:"ses",desiredCount:e.desiredCount||1},cloudFrontApplied:!1,dnsApplied:!1,applied:!1,rollback:g};if(!e.apply)return h;let _=`${e.distributionId}:${r.pathPattern}:${r.stackName}`;if(e.confirm!==_)throw Error(`Pass exact confirmation token ${_} to provision the backend and change live routing`);if(s)try{await n.cloudformation.updateStack({stackName:r.stackName,templateBody:c,capabilities:["CAPABILITY_NAMED_IAM"],tags:[{Key:"ManagedBy",Value:"ts-cloud"},{Key:"Application",Value:e.slug}]}),await n.cloudformation.waitForStack(r.stackName,"stack-update-complete")}catch(B){if(!String(B.message).includes("No updates are to be performed"))throw B}else await n.cloudformation.createStack({stackName:r.stackName,templateBody:c,capabilities:["CAPABILITY_NAMED_IAM"],onFailure:"ROLLBACK",tags:[{Key:"ManagedBy",Value:"ts-cloud"},{Key:"Application",Value:e.slug}]}),await n.cloudformation.waitForStack(r.stackName,"stack-create-complete");let R=(await n.cloudformation.describeStacks({stackName:r.stackName})).Stacks[0],E=Em(R?.Outputs),y=E.AppLoadBalancerDnsName;if(!y)throw Error("Backend stack did not return AppLoadBalancerDnsName");let $=!1;if(e.originDomain&&e.originDomain!==y){if(!n.dns)throw Error(`External DNS provider is required to map ${e.originDomain} to ${y}`);let B=await n.dns.upsertRecord(e.originDomain,{name:e.originDomain,type:"CNAME",content:y,ttl:300});if(!B.success)throw Error(B.message||"External DNS update failed");$=!0}let b=e.originDomain||y,z=e.certificateArn?"https-only":"http-only",C=e.skipHealthCheck?void 0:await Pm(n,`${z==="https-only"?"https":"http"}://${b}/api/health`,e.originVerifySecret);return await n.cloudfront.upsertExistingDistributionOrigin(e.distributionId,{id:r.originId,domainName:b,pathPattern:r.pathPattern,protocolPolicy:z,customHeaders:e.originVerifySecret?{"X-Origin-Verify":e.originVerifySecret}:void 0}),{...h,outputs:E,health:C,cloudFrontApplied:!0,dnsApplied:$,applied:!0}}function ak(e={}){let r={fargate:730*(e.desiredCount||1)*0.012342500000000001,applicationLoadBalancer:16.425,natGateway:32.85,postgres:730*(e.multiAzDatabase?0.032:0.016),redis:23.36};return{monthlyUsd:Number(Object.values(r).reduce((n,i)=>n+i,0).toFixed(2)),components:Object.fromEntries(Object.entries(r).map(([n,i])=>[n,Number(i.toFixed(2))])),assumptions:["us-east-1 public on-demand rate snapshot, July 2026","one 0.25 vCPU/0.5 GB Linux Fargate task unless desiredCount is changed","one ALB before LCU charges and one NAT gateway before data processing","single-AZ db.t4g.micro PostgreSQL by default and two cache.t4g.micro Redis nodes","excludes storage, backups, CloudFront, data transfer, public IPv4, logs, email, queue requests, taxes, and free-tier credits"]}}import{execFileSync as Dm}from"node:child_process";import{createHash as $m}from"node:crypto";import{existsSync as Cu,mkdirSync as Cm,mkdtempSync as km,readdirSync as bm,readFileSync as vm,rmSync as Om,statSync as ku,writeFileSync as Bm}from"node:fs";import{tmpdir as Jm}from"node:os";import{basename as Tm,join as di,relative as zm,resolve as hd}from"node:path";var Wm=new Set([".git","node_modules","dist","coverage"]);function bu(e,t=e){let r=[];for(let n of bm(e).sort()){if(Wm.has(n))continue;let i=di(e,n);if(Du(i,t))continue;let a=ku(i);if(a.isDirectory())r.push(...bu(i,t));else if(a.isFile())r.push(zm(t,i))}return r}function jm(e){let t=hd(e);if(!Cu(t)||!ku(t).isDirectory())throw Error(`Container context does not exist: ${t}`);let r=$m("sha256");for(let n of bu(t))r.update(n),r.update("\x00"),r.update(vm(di(t,n))),r.update("\x00");return r.digest("hex")}function Um(e){return{ecr:new $u(e.region||"us-east-1",e.profile),run:(t,r,n)=>{Dm(t,r,{cwd:n?.cwd,env:n?.env,stdio:n?.stdio||"inherit"})}}}async function fk(e,t){let r=hd(e.context),n=hd(e.dockerfile||di(r,"Dockerfile"));if(!Cu(n))throw Error(`Dockerfile does not exist: ${n}`);if(!e.repository.split("/").every((E)=>/^[a-z0-9][a-z0-9._-]*$/.test(E)&&!/[._-]$/.test(E)&&!/[._-]{2}/.test(E)))throw Error("ECR repository name is invalid");let s=t||Um(e),d=jm(r),c=`sha-${d.slice(0,20)}`,o="";try{o=(await s.ecr.describeRepositories({repositoryNames:[e.repository]})).repositories?.[0]?.repositoryUri||""}catch{}if(!o)o=(await s.ecr.createRepository({repositoryName:e.repository,imageTagMutability:"IMMUTABLE",imageScanningConfiguration:{scanOnPush:!0},tags:[{Key:"ManagedBy",Value:"ts-cloud"}]})).repository?.repositoryUri||"";if(!o)throw Error(`Could not resolve ECR repository URI for ${e.repository}`);await s.ecr.putLifecyclePolicy({repositoryName:e.repository,lifecyclePolicyText:JSON.stringify({rules:[{rulePriority:1,description:"Retain the newest 25 release images",selection:{tagStatus:"any",countType:"imageCountMoreThan",countNumber:25},action:{type:"expire"}}]})});let g=`${o}:${c}`,h=km(di(Jm(),"ts-cloud-container-"));try{s.run("docker",["version"],{stdio:"ignore"}),s.run("docker",["build","--platform",e.platform||"linux/amd64","--provenance=false","--sbom=false","--file",n,"--tag",g,r],{cwd:r});let E=(await s.ecr.getAuthorizationToken()).authorizationData?.[0];if(!E?.authorizationToken||!E.proxyEndpoint)throw Error("ECR did not return Docker authorization data");let y=E.proxyEndpoint.replace(/^https?:\/\//,""),$=di(h,"docker");Cm($,{recursive:!0}),Bm(di($,"config.json"),JSON.stringify({auths:{[y]:{auth:E.authorizationToken}}}),{mode:384}),s.run("docker",["push",g],{env:{...process.env,DOCKER_CONFIG:$}})}finally{Om(h,{recursive:!0,force:!0})}let R=(await s.ecr.describeImages({repositoryName:e.repository,imageIds:[{imageTag:c}]})).imageDetails?.[0]?.imageDigest;if(!R||!/^sha256:[a-f0-9]{64}$/i.test(R))throw Error(`ECR did not return an immutable digest for ${Tm(g)}`);return{repository:e.repository,tag:c,imageUri:g,digest:R,digestUri:`${o}@${R}`,contextSha256:d}}import{existsSync as Hm,readdirSync as Nm,readFileSync as Fm,statSync as Vm}from"node:fs";import{join as Fu,relative as Lm}from"node:path";function Dn(e,t){let r=e.environments?.[t]?.app;if(!r)throw Error(`No serverless app configured for environment '${t}'. Add environments.${t}.app to your config.`);let n=e.project.slug,i=e.environments?.[t]?.region||e.project.region||"us-east-1";return{app:r,slug:n,region:i,stackName:ci(e,t),artifactBucket:vu(n,t),assetsBucket:Ou(n,t)}}async function Pn(e,t=8){let r;for(let n=0;n<t;n++)try{return await e()}catch(i){let a=i?.code||i?.name||"",s=String(i?.message||"");if(a==="ResourceConflictException"||/update is in progress|currently in the following state/i.test(s)){r=i,await new Promise((d)=>setTimeout(d,3000));continue}throw i}throw r}var Vu=(e,t)=>`releases/${e}/${t}/current.json`;async function rs(e,t,r,n){try{return await e.getObjectJson(t,Vu(r,n))}catch{return null}}async function Lu(e,t,r,n,i){await e.putObjectJson(t,Vu(r,n),i)}async function xm(e,t){if(!e.secrets)return{};let r=new Kr(t),n={},i=Array.isArray(e.secrets)?e.secrets.map((a)=>({envName:a.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),secretId:a})):Object.entries(e.secrets).map(([a,s])=>({envName:a,secretId:s}));if(Array.isArray(e.secrets)){let a=new Map;for(let{envName:d,secretId:c}of i)a.set(d,[...a.get(d)??[],c]);let s=[...a.entries()].filter(([,d])=>d.length>1);if(s.length){let d=s.map(([c,o])=>`${c} ← ${o.join(", ")}`).join("; ");throw Error(`serverless secrets: multiple secrets map to the same env var (${d}). Use the map form { ENV_NAME: 'secret/id' } to disambiguate.`)}}for(let{envName:a,secretId:s}of i){let c=(await r.getSecretValue({SecretId:s})).SecretString??"";try{let o=JSON.parse(c);if(o&&typeof o==="object"&&!Array.isArray(o)){for(let[g,h]of Object.entries(o))n[g]=String(h);continue}}catch{}n[a]=c}return n}function xu(e,t){let r={},n=t.DbProxyEndpoint||t.DbEndpoint;if(n)r.DB_CONNECTION="mysql",r.DB_HOST=n,r.DB_PORT="3306",r.DB_DATABASE=r.DB_DATABASE||"app";if(t.CacheEndpoint){if(r.REDIS_HOST=t.CacheEndpoint,r.REDIS_PORT="6379",e.cache?.driver==="elasticache")r.CACHE_STORE="redis",r.CACHE_DRIVER="redis",r.SESSION_DRIVER="redis"}return r}function qa(e,t,r,n,i,a,s,d={}){let c=e.kind==="php"?ju({cacheDriver:e.cache?.driver==="elasticache"?"redis":"dynamodb"}):{};return{TSCLOUD_LAMBDA_MODE:n,TSCLOUD_ENV:r,MAINTENANCE_MODE:"0",...e.octane?{TSCLOUD_OCTANE:"1"}:{},...e.serveAssets?{TSCLOUD_SERVE_ASSETS:"1"}:{},...e.redirectRobotsTxt===!1?{TSCLOUD_REDIRECT_ROBOTS_TXT:"0"}:{},...c,...d,...t.app.cache?.driver!=="elasticache"?{TSCLOUD_CACHE_TABLE:`${t.slug}-${r}-cache`}:{},...s?{TSCLOUD_QUEUE:s,SQS_QUEUE:s}:{},...a?{ASSET_URL:a}:{},...e.env??{},...i}}function Mm(e){let t=e.slice(e.lastIndexOf(".")).toLowerCase();return{".html":"text/html",".css":"text/css",".js":"text/javascript",".mjs":"text/javascript",".json":"application/json",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".txt":"text/plain",".map":"application/json"}[t]??"application/octet-stream"}function*Mu(e){for(let t of Nm(e)){let r=Fu(e,t);if(Vm(r).isDirectory())yield*Mu(r);else yield r}}async function Qm(e,t,r,n,i=!1){let a=0;for(let s of Mu(r)){let d=Lm(r,s).replace(/\\/g,"/");if(!i&&d.split("/").some((c)=>c.startsWith(".")))continue;await e.putObject({bucket:t,key:`${n}/${d}`,body:Fm(s),contentType:Mm(s),cacheControl:"public, max-age=31536000, immutable"}),a++}return a}function Gm(e,t){let r=Object.entries(t).reduce((n,[i,a])=>n+Buffer.byteLength(`${i}=${a}`,"utf8"),0);if(r>4096){let n=Object.entries(t).map(([i,a])=>[i,Buffer.byteLength(`${i}=${a}`,"utf8")]).sort((i,a)=>a[1]-i[1]).slice(0,5).map(([i,a])=>`${i} (${a}B)`).join(", ");throw Error(`${e}: environment variables total ${r}B, over AWS's 4096B limit (${r-4096}B too large). Largest: ${n}. Move large/secret values out of env — store them in Secrets Manager and fetch at cold start.`)}}async function qi(e,t,r,n){Gm(t,r),await Pn(()=>e.updateFunctionConfiguration({FunctionName:t,Environment:{Variables:r}})),await e.waitForFunctionActive(t,120);let i=n.kind==="image"?{FunctionName:t,ImageUri:n.imageUri}:{FunctionName:t,S3Bucket:n.bucket,S3Key:n.key};await Pn(()=>e.updateFunctionCode(i)),await e.waitForFunctionActive(t,120)}async function es(e,t){let n=(await Pn(()=>e.publishVersion({FunctionName:t}))).Version;if(!n)throw Error(`publishVersion returned no version for ${t}`);return await Pn(()=>e.updateAlias({FunctionName:t,Name:"live",FunctionVersion:n})),n}async function Zm(e,t,r={}){let n=Dn(e,t),{app:i,slug:a,region:s,stackName:d,artifactBucket:c}=n,o=r.projectRoot??process.cwd();ts(`Deploying serverless app: ${a} (${t})`),zt(`Stack: ${d}`),zt(`Region: ${s}`);let g=new lr(s),h=new wr(s),_=new Et(s),R=i.kind==="php",E=i.packaging==="image",y=Tu(i),$,b,z,C,B=[];if(E&&y.usesLayer&&y.layerKind!=="php")throw Error(`packaging: 'image' currently supports PHP and managed Node runtimes. ${y.kind}${y.kind==="node"?` ${y.version}`:""} uses a custom runtime — `+"use the default zip packaging (the runtime layer is built + attached automatically).");if(E){ot("Building + pushing container image");let{buildAndPushServerlessImage:U}=await import("./chunk-svrvvcm7.js"),M=await U({app:i,projectRoot:o,region:s,repository:`${a}-${t}`,skipBuild:r.skipBuild,onStep:(_e)=>zt(` ${_e}`)});$=M.handlers,b={kind:"image",imageUri:M.imageUri},z=M.tag,B.push({ParameterKey:"ImageUri",ParameterValue:M.imageUri})}else{ot("Packaging application");let U=R?Uu({projectRoot:o,app:i,skipBuild:r.skipBuild,onStep:(Pe)=>zt(` ${Pe}`)}):await Ju({projectRoot:o,app:i,skipBuild:r.skipBuild,onStep:(Pe)=>zt(` ${Pe}`)}),M=Bu(a,t,U.sha256);if(zt(`Artifact: ${U.sha256.slice(0,12)} (${(U.zip.length/1024).toFixed(0)} KB)`),$=U.handlers,z=U.sha256,y.usesLayer){let Pe=y.layerEnvVar?process.env[y.layerEnvVar]:void 0;if(C=i.layers??(Pe?[Pe]:void 0),!C?.length){let G=y.layerKind==="php"?"serverless:build-php-layer":y.layerKind==="bun"?"serverless:build-bun-layer":"serverless:build-node-layer";throw Error(`${y.kind} apps on provided.al2023 need a runtime layer. Set environments.<env>.app.layers or the ${y.layerEnvVar} env var (build one with \`cloud ${G}\`)${y.kind==="node"?", or use a managed Node version (18/20/22)":""}.`)}}if(!await g.bucketExists(c))ot(`Creating artifact bucket ${c}`),await g.createBucket(c);if(await g.headObject(c,M).then((Pe)=>Pe!==null).catch(()=>!1))zt("Artifact already uploaded — reusing");else ot("Uploading artifact"),await g.putObject({bucket:c,key:M,body:U.zip,contentType:"application/zip"});b={kind:"zip",bucket:c,key:M},B.push({ParameterKey:"ArtifactBucket",ParameterValue:c},{ParameterKey:"ArtifactKey",ParameterValue:M})}let N=Wu({config:e,environment:t,app:i,handlers:$,runtimeLayers:C}),F=JSON.stringify(N.template),J=["CAPABILITY_NAMED_IAM"],Z=await h.describeStacks({stackName:d}).then((U)=>U.Stacks[0]?.StackStatus).catch(()=>{return}),O=Z!==void 0;if(Z&&/DELETE_IN_PROGRESS/.test(Z))ot("Waiting for an in-progress stack delete to finish"),await h.waitForStack(d,"stack-delete-complete").catch(()=>{}),O=!1;else if(Z&&/(?:ROLLBACK_COMPLETE|REVIEW_IN_PROGRESS|CREATE_FAILED)/.test(Z))ot(`Deleting unusable stack (status ${Z}) before recreate`),await h.deleteStack(d),await h.waitForStack(d,"stack-delete-complete").catch(()=>{}),O=!1;ot(O?"Updating infrastructure stack":"Creating infrastructure stack");try{if(O)await h.updateStack({stackName:d,templateBody:F,parameters:B,capabilities:J}),await h.waitForStack(d,"stack-update-complete");else await h.createStack({stackName:d,templateBody:F,parameters:B,capabilities:J,onFailure:"DELETE"}),await h.waitForStack(d,"stack-create-complete")}catch(U){if(/No updates are to be performed/i.test(String(U?.message)))zt("No infrastructure changes");else throw U}let K=await h.getStackOutputs(d).catch(()=>({})),ae;if(i.assets){let U=Fu(o,i.assets);if(Hm(U)){let M=i.assetDomain||K.AssetsCdnDomain;ae=M?`https://${M}/${z}`:void 0,ot(`Syncing assets from ${i.assets}`);let _e=await Qm(g,n.assetsBucket,U,z,i.dotFilesAsAssets);zt(`Uploaded ${_e} asset(s)${ae?` → ${ae}`:""}`)}else Xa(`Assets directory not found: ${U}`)}ot("Resolving secrets");let Se=await xm(i,s);if(i.database?.connection==="aurora-serverless")try{let M=await new Kr(s).getSecretValue({SecretId:`${a}/${t}/db`}),_e=JSON.parse(M.SecretString??"{}");if(_e.username)Se.DB_USERNAME=_e.username;if(_e.password)Se.DB_PASSWORD=_e.password}catch(U){Xa(`Could not resolve Aurora DB credentials: ${U.message}`)}if(!await g.bucketExists(c))await g.createBucket(c);let Te=await rs(g,c,a,t),de={},Ae=N.queueNames[0],ze=xu(i,K);if(ot("Activating functions"),de.http=qa(i,n,t,"http",Se,ae,Ae,ze),await qi(_,N.functionNames.http,de.http,b),de.cli=qa(i,n,t,"cli",Se,ae,Ae,ze),await qi(_,N.functionNames.cli,de.cli,b),N.queueNames.length)de.queue=qa(i,n,t,"queue",Se,ae,Ae,ze),await qi(_,N.functionNames.queue,de.queue,b);let ue=(i.provisionedConcurrency??0)>0,P={};if(ue){if(ot("Publishing versions + flipping live alias"),P.http=await es(_,N.functionNames.http),P.cli=await es(_,N.functionNames.cli),N.queueNames.length)P.queue=await es(_,N.functionNames.queue)}if(await Lu(g,c,a,t,{sha:z,code:b,previousSha:Te?.sha,previousCode:Te?.code,previousFunctionEnv:Te?.functionEnv,...ue?{functionVersions:P,previousFunctionVersions:Te?.functionVersions}:{},functionEnv:de,functionNames:{http:N.functionNames.http,cli:N.functionNames.cli,...N.queueNames.length?{queue:N.functionNames.queue}:{}},assetUrl:ae,timestamp:new Date().toISOString()}),!r.skipDeployHooks&&i.deploy?.length){ot("Running deploy hooks");for(let U of i.deploy){zt(` deploy: ${U}`);let M=await _.invoke({FunctionName:N.functionNames.cli,InvocationType:"RequestResponse",Payload:{command:U},LogType:"Tail"});if(M.FunctionError)throw Hu("Deploy hook failed — the new build is ALREADY LIVE."),zt(` Roll back with: cloud serverless:rollback --env ${t}`),Error(`Deploy hook failed (${U}): ${M.Payload}`)}}let T=K.HttpApiEndpoint;if(!r.skipHealthCheck&&T){ot("Health check");try{let U=await fetch(T,{method:"GET"});zt(`GET ${T} → ${U.status}`)}catch(U){Xa(`Health check could not reach ${T}: ${U.message}`)}}Nu(["Serverless deploy complete","",T?`URL: ${T}`:"",`Stack: ${d}`,`Build: ${z.slice(0,12)}`].filter(Boolean).join(`
15
+ `),"green")}async function fd(e,t){let r=Dn(e,t),n=new lr(r.region),i=new Et(r.region),a=await rs(n,r.artifactBucket,r.slug,t);if(!a)throw Error("No previous release to redeploy. Run a full deploy first.");ts(`Redeploying ${r.slug} (${t}) — build ${a.sha.slice(0,12)}`);for(let[s,d]of Object.entries(a.functionNames)){if(!d)continue;ot(`Re-activating ${s} (${d})`),await qi(i,d,a.functionEnv[s]??{},a.code);let c=a.functionVersions?.[s];if(c)await Pn(()=>i.updateAlias({FunctionName:d,Name:"live",FunctionVersion:c}))}ea("Redeploy complete")}async function Sd(e,t){let r=Dn(e,t),n=new lr(r.region),i=new Et(r.region),a=await rs(n,r.artifactBucket,r.slug,t);if(!a?.previousCode)throw Error("No previous release to roll back to.");ts(`Rolling back ${r.slug} (${t}) → ${a.previousSha?.slice(0,12)}`);for(let[s,d]of Object.entries(a.functionNames)){if(!d)continue;ot(`Restoring ${s} (${d})`);let c=a.previousFunctionEnv?.[s]??a.functionEnv[s]??{};await qi(i,d,c,a.previousCode);let o=a.previousFunctionVersions?.[s];if(o)await Pn(()=>i.updateAlias({FunctionName:d,Name:"live",FunctionVersion:o}))}await Lu(n,r.artifactBucket,r.slug,t,{...a,sha:a.previousSha??a.sha,code:a.previousCode,functionEnv:a.previousFunctionEnv??a.functionEnv,functionVersions:a.previousFunctionVersions??a.functionVersions,previousSha:void 0,previousCode:void 0,previousFunctionEnv:void 0,previousFunctionVersions:void 0,timestamp:new Date().toISOString()}),ea("Rollback complete")}async function ns(e,t,r,n){let i=Dn(e,t),a=new Et(i.region),s=`${i.slug}-${t}-http`,c={...(await a.getFunction(s)).Configuration?.Environment?.Variables??{}};if(c.MAINTENANCE_MODE=r?"1":"0",r&&n)c.MAINTENANCE_BYPASS_SECRET=n;if(!r)delete c.MAINTENANCE_BYPASS_SECRET;if(await Pn(()=>a.updateFunctionConfiguration({FunctionName:s,Environment:{Variables:c}})),(i.app.provisionedConcurrency??0)>0)await a.waitForFunctionActive(s,120),await es(a,s);ea(r?"Application is now in maintenance mode (503)":"Application is live")}async function li(e,t,r){let n=Dn(e,t),i=new Et(n.region),a=`${n.slug}-${t}-cli`,s=await i.invoke({FunctionName:a,InvocationType:"RequestResponse",Payload:{command:r},LogType:"Tail"});if(s.FunctionError)throw Error(`Command failed: ${s.Payload}`);return s.Payload??""}async function rt(e,t){let r=Dn(e,t),n=new wr(r.region),i=new Et(r.region),a=new lr(r.region),s="not deployed",d={};try{let{Stacks:E}=await n.describeStacks({stackName:r.stackName});s=E?.[0]?.StackStatus??s;for(let y of E?.[0]?.Outputs??[])if(y.OutputKey)d[y.OutputKey]=y.OutputValue??""}catch{}let c=zu(r.app,r.slug,t),o=r.app.provisionedConcurrency??0,g=["http","cli",...c.length?["queue"]:[]],h=`${r.slug}-${t}`,_=[];for(let E of g){let y=`${h}-${E}`,$={mode:E,name:y,version:"$LATEST"};if(o>0){let b=await i.getAlias(y,"live").catch(()=>null);if(b?.FunctionVersion){$.version=b.FunctionVersion;let z=await i.getProvisionedConcurrencyConfig(y,"live").catch(()=>null);if(z)$.provisioned={status:z.Status??"-",allocated:z.AllocatedProvisionedConcurrentExecutions??0,requested:z.RequestedProvisionedConcurrentExecutions??0}}}_.push($)}let R=await rs(a,r.artifactBucket,r.slug,t).catch(()=>null);return{slug:r.slug,environment:t,region:r.region,stackStatus:s,endpoint:d.HttpApiEndpoint,assetUrl:R?.assetUrl,scheduler:r.app.scheduler??"on",queues:c,provisionedConcurrency:o,functions:_,lastRelease:R?{sha:R.sha,timestamp:R.timestamp}:void 0}}function Km(e,t){return`${e}-${t}-db`}async function Qu(e,t,r,n){let i=Dn(e,t);if(i.app.database?.connection!=="aurora-serverless")throw Error("No Aurora Serverless v2 database is configured for this environment.");let{RDSClient:a}=await import("./chunk-xmqfc62w.js"),s=new a(i.region),d=Km(i.slug,t);ot(`Scaling ${d} → ${r}–${n} ACUs`),await s.modifyDBCluster({DBClusterIdentifier:d,ServerlessV2ScalingConfiguration:{MinCapacity:r,MaxCapacity:n},ApplyImmediately:!0}),ea(`Scaling applied to ${d} (takes effect shortly).`)}class Ar{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new gi(Zu(t))}async query(e){let t=new URLSearchParams(Gu({Version:"2010-08-01",...e})).toString();return this.client.request({service:"monitoring",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t})}async getMetricStatistics(e){let t={Action:"GetMetricStatistics",Namespace:e.Namespace,MetricName:e.MetricName,StartTime:e.StartTime.toISOString(),EndTime:e.EndTime.toISOString(),Period:e.Period};(e.Statistics??[]).forEach((a,s)=>{t[`Statistics.member.${s+1}`]=a}),(e.ExtendedStatistics??[]).forEach((a,s)=>{t[`ExtendedStatistics.member.${s+1}`]=a}),(e.Dimensions??[]).forEach((a,s)=>{t[`Dimensions.member.${s+1}.Name`]=a.Name,t[`Dimensions.member.${s+1}.Value`]=a.Value});let r=await this.query(t),i=(r.GetMetricStatisticsResult||r)?.Datapoints?.member??[];if(!Array.isArray(i))i=i?[i]:[];return i.map((a)=>{let s={},d=a.ExtendedStatistics?.entry;if(d){if(!Array.isArray(d))d=[d];for(let c of d)if(c?.key!=null)s[c.key]=Number(c.value)}return{Timestamp:a.Timestamp,Sum:a.Sum!=null?Number(a.Sum):void 0,Average:a.Average!=null?Number(a.Average):void 0,Maximum:a.Maximum!=null?Number(a.Maximum):void 0,Minimum:a.Minimum!=null?Number(a.Minimum):void 0,Percentiles:Object.keys(s).length?s:void 0,Unit:a.Unit}})}async getMetricSeries(e){let t=/^p\d/.test(e.Stat);return(await this.getMetricStatistics({Namespace:e.Namespace,MetricName:e.MetricName,Dimensions:e.Dimensions,StartTime:e.StartTime,EndTime:e.EndTime,Period:e.Period,Statistics:t?[]:[e.Stat],ExtendedStatistics:t?[e.Stat]:[]})).slice().sort((n,i)=>new Date(n.Timestamp??0).getTime()-new Date(i.Timestamp??0).getTime()).map((n)=>t?n.Percentiles?.[e.Stat]??0:n[e.Stat]??0)}async describeAlarms(e){let t={Action:"DescribeAlarms"};if(e?.AlarmNamePrefix)t.AlarmNamePrefix=e.AlarmNamePrefix;if(e?.MaxRecords)t.MaxRecords=e.MaxRecords;let r=await this.query(t),i=(r.DescribeAlarmsResult||r)?.MetricAlarms?.member??[];if(!Array.isArray(i))i=i?[i]:[];return i.map((a)=>({AlarmName:a.AlarmName,StateValue:a.StateValue,MetricName:a.MetricName,ComparisonOperator:a.ComparisonOperator,Threshold:a.Threshold!=null?Number(a.Threshold):void 0,Namespace:a.Namespace}))}async putMetricAlarm(e){let t={Action:"PutMetricAlarm",AlarmName:e.AlarmName,Namespace:e.Namespace,MetricName:e.MetricName,ComparisonOperator:e.ComparisonOperator,Threshold:e.Threshold,EvaluationPeriods:e.EvaluationPeriods,Period:e.Period,Statistic:e.Statistic};if(e.AlarmDescription)t.AlarmDescription=e.AlarmDescription;(e.Dimensions??[]).forEach((r,n)=>{t[`Dimensions.member.${n+1}.Name`]=r.Name,t[`Dimensions.member.${n+1}.Value`]=r.Value}),(e.AlarmActions??[]).forEach((r,n)=>{t[`AlarmActions.member.${n+1}`]=r}),await this.query(t)}async deleteAlarms(e){if(!e.length)return;let t={Action:"DeleteAlarms"};e.forEach((r,n)=>{t[`AlarmNames.member.${n+1}`]=r}),await this.query(t)}}class _d{client;region;constructor(e="us-east-1"){this.region=e,this.client=new gi}async call(e,t){return this.client.request({service:"wafv2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`AWSWAF_20190729.${e}`},body:JSON.stringify(t)})}async listWebACLs(e="REGIONAL"){return(await this.call("ListWebACLs",{Scope:e,Limit:100}))?.WebACLs??[]}async getWebACLRules(e,t,r="REGIONAL"){return((await this.call("GetWebACL",{Name:e,Id:t,Scope:r}))?.WebACL?.Rules??[]).map((a)=>({Name:a.Name,Priority:a.Priority,Action:a.Action?Object.keys(a.Action)[0]:a.OverrideAction?Object.keys(a.OverrideAction)[0]:"count"}))}}var Ym=[{index:0,id:"clients",label:"Clients"},{index:1,id:"dns",label:"DNS & TLS"},{index:2,id:"edge",label:"Edge"},{index:3,id:"routing",label:"Routing"},{index:4,id:"apps",label:"Applications"},{index:5,id:"runtime",label:"Background runtime"},{index:6,id:"data",label:"Data services"},{index:7,id:"durability",label:"Durability"}],Xm=[{index:0,id:"clients",label:"Clients"},{index:1,id:"dns",label:"DNS & TLS"},{index:2,id:"edge",label:"Edge"},{index:3,id:"entry",label:"Entry points"},{index:4,id:"compute",label:"Compute"},{index:5,id:"messaging",label:"Messaging & pooling"},{index:6,id:"data",label:"Data services"},{index:7,id:"durability",label:"Durability"}],qm=[{match:/^redis/,kind:"cache",label:"Redis"},{match:/^(?:mysql|mariadb)/,kind:"database",label:"MySQL"},{match:/^postgres/,kind:"database",label:"PostgreSQL"},{match:/^meilisearch/,kind:"database",label:"Meilisearch"},{match:/^vitess|^vtgate/,kind:"database",label:"Vitess"},{match:/^memcached/,kind:"cache",label:"Memcached"}],eE=/^(?:rpx-gateway|nginx|caddy|traefik|haproxy)$/;function Q(e,t=""){let r=e==null?"":String(e).trim();return r&&r!=="-"&&r!=="—"?r:t}function tE(e){return Array.isArray(e)?e.length:0}function Kt(e){let t=Q(e).toLowerCase();if(!t)return"unknown";if(["running","live","active","available","success","ok","healthy","enabled"].includes(t))return"ok";if(["failed","stopped","unreachable","error","critical","disabled"].includes(t))return"bad";if(["configured","creating","pending","degraded","shadowed","warn","unknown"].includes(t))return"warn";return"warn"}function Ne(e,t,r){if(r.has(t.source)&&r.has(t.target))e.push(t)}function $n(e,t={}){let r=[],n=[],i=[],a=e.server??{},s=Array.isArray(e.sites)?e.sites:[],d=Array.isArray(e.services)?e.services:[],c=Array.isArray(e.workers)?e.workers:[],o=e.security??{},g=!!e._serverReachable&&!e.metricsUnavailable,h="box";if(!g)i.push("The compute box could not be probed, so live service state is missing; the shape comes from your cloud config.");r.push({id:"internet",label:"Internet",kind:"internet",layer:0,status:"ok",sub:"Public traffic",facts:[],external:!0});let _=[...new Set(s.map((J)=>Q(J.domain)||Q(J.route).split("/")[0]).filter((J)=>J&&J!=="internal"&&J!=="loopback"))],R=Array.isArray(o.tlsCertificates)?o.tlsCertificates:[],E=R.filter((J)=>Number(J?.daysRemaining??999)<21).length;r.push({id:"dns",label:_.length===1?_[0]:"Public domains",kind:"dns",layer:1,status:E?"warn":_.length?"ok":"unknown",sub:_.length>1?`${_.length} domains`:"DNS & certificates",facts:[{label:"Domains",value:_.length?_.slice(0,6).join(", "):"none resolved"},{label:"Certificates",value:R.length?`${R.length} issued`:"none reported"},...E?[{label:"Expiring",value:`${E} within 21 days`}]:[]],href:"/server/security",external:!0});let y=o.firewall??{},$=Array.isArray(o.ports)?o.ports:[];r.push({id:"firewall",label:"Host firewall",kind:"firewall",layer:2,status:Kt(y.status),sub:Q(y.summary,"Inbound filtering"),facts:[{label:"State",value:Q(y.status,"unknown")},{label:"Open ports",value:$.length?$.map((J)=>Q(J.listen)).join(", "):"not reported"}],href:"/server/firewall",group:"box"});let b=d.find((J)=>eE.test(Q(J.name)));r.push({id:"proxy",label:Q(b?.name,"Reverse proxy"),kind:"proxy",layer:3,status:b?Kt(b.status):"unknown",sub:"TLS termination & routing",facts:[{label:"Service",value:Q(b?.name,"not detected")},{label:"State",value:Q(b?.status,g?"not running":"not probed")},{label:"Routes",value:`${s.length} site${s.length===1?"":"s"}`}],href:"/server/services",group:"box"});for(let J of s){let Z=`site:${Q(J.name)}`;if(!Q(J.name))continue;r.push({id:Z,label:Q(J.name),kind:"site",layer:4,status:Kt(J.status),sub:Q(J.runtime,"runtime"),facts:[{label:"Route",value:Q(J.route,"internal")},{label:"Runtime",value:Q(J.runtime,"unknown")},{label:"Delivery",value:Q(J.deploy,"unknown")},{label:"TLS",value:Q(J.tls,"unknown")},...J.responseMs!=null?[{label:"Response",value:`${Math.round(Number(J.responseMs))} ms`}]:[],...J.httpStatus!=null?[{label:"HTTP",value:String(J.httpStatus)}]:[]],href:"/server/sites",group:"box"})}for(let J of c){let Z=`worker:${Q(J.name)}`;if(!Q(J.name))continue;r.push({id:Z,label:Q(J.name),kind:"worker",layer:5,status:Kt(J.status),sub:`${Number(J.processes??1)} process${Number(J.processes??1)===1?"":"es"}`,facts:[{label:"Processes",value:String(J.processes??1)},{label:"State",value:Q(J.status,"unknown")},...Q(J.site)?[{label:"Site",value:Q(J.site)}]:[]],href:"/operations/jobs",group:"box"})}let z=e.serverScheduler??{};if(z.enabled)r.push({id:"scheduler",label:"Scheduler",kind:"scheduler",layer:5,status:"ok",sub:"Cron dispatch",facts:[{label:"Last run",value:Q(z.lastRun,"unknown")}],href:"/operations/jobs",group:"box"});let C=d.map((J)=>{let Z=Q(J.name),O=qm.find((K)=>K.match.test(Z));return O?{service:J,name:Z,...O}:null}).filter((J)=>!!J);for(let J of C)r.push({id:`data:${J.name}`,label:J.label,kind:J.kind,layer:6,status:Kt(J.service.status),sub:J.name,facts:[{label:"Unit",value:J.name},{label:"State",value:Q(J.service.status,"unknown")}],href:"/data/services",group:"box"});let B=e.backup??{};if(B.enabled)r.push({id:"backup",label:"Backups",kind:"backup",layer:7,status:"ok",sub:Q(B.destination,"destination"),facts:[{label:"Destination",value:Q(B.destination,"unknown")},{label:"Schedule",value:Q(B.schedule,"unknown")},{label:"Retention",value:`${B.retention??0} copies`},{label:"Last run",value:Q(B.last,"unknown")}],href:"/data/backups"});let N=new Set(r.map((J)=>J.id));Ne(n,{source:"internet",target:"dns",flow:"request",label:"https"},N),Ne(n,{source:"dns",target:"firewall",flow:"request",label:"443/80"},N),Ne(n,{source:"firewall",target:"proxy",flow:"request"},N);for(let J of s){let Z=`site:${Q(J.name)}`;Ne(n,{source:"proxy",target:Z,flow:"request",label:Q(J.path)||void 0,status:Kt(J.status)},N)}for(let J of c){let Z=`worker:${Q(J.name)}`,O=`site:${Q(J.site)}`;if(N.has(O))Ne(n,{source:O,target:Z,flow:"async",label:"queue"},N);else Ne(n,{source:"proxy",target:Z,flow:"async",label:"queue"},N)}for(let J of c)Ne(n,{source:"scheduler",target:`worker:${Q(J.name)}`,flow:"async",label:"dispatch"},N);let F=[...s.map((J)=>`site:${Q(J.name)}`),...c.map((J)=>`worker:${Q(J.name)}`)];for(let J of C)for(let Z of F)Ne(n,{source:Z,target:`data:${J.name}`,flow:"data",label:"localhost"},N);if(C.length&&F.length)i.push("Data-service edges show co-location on the box: every process on it can reach localhost. They are not a declared per-site binding.");for(let J of C)Ne(n,{source:`data:${J.name}`,target:"backup",flow:"backup",label:"snapshot"},N);for(let J of s)Ne(n,{source:`site:${Q(J.name)}`,target:"backup",flow:"backup"},N);return{mode:"server",project:Q(t.project)||Q(e.project?.name)||Q(a.name,"project"),environment:Q(t.environment)||Q(e.environment,"production"),provider:Q(a.provider,"unknown"),region:Q(a.region,"unknown"),generatedAt:new Date().toISOString(),layers:Ym,groups:[{id:"box",label:Q(a.name,"App server"),sub:[Q(a.provider),Q(a.region),Q(a.ip)].filter(Boolean).join(" · ")}],nodes:r,links:n,notes:i}}function is(e,t={}){let r=[],n=[],i=[],a=e.app??{},s=Array.isArray(e.functions)?e.functions:[],d=Array.isArray(e.queues)?e.queues:[],c=e.metrics??{};if(!s.length)i.push("No Lambda functions were read for this environment, so the compute layer is empty rather than assumed.");r.push({id:"internet",label:"Internet",kind:"internet",layer:0,status:"ok",sub:"Public traffic",facts:[],external:!0});let o=Q(a.url),g=o.replace(/^https?:\/\//,"").split("/")[0];r.push({id:"dns",label:g||"Application domain",kind:"dns",layer:1,status:g?"ok":"unknown",sub:"DNS & certificates",facts:[{label:"Endpoint",value:o||"not resolved"}],external:!0});let h=e.waf;if(h)r.push({id:"waf",label:"WAF",kind:"waf",layer:2,status:Kt(h.status??"active"),sub:Q(h.scope,"Managed rules"),facts:[{label:"Web ACL",value:Q(h.name,"unnamed")},...h.blocked!=null?[{label:"Blocked (24h)",value:String(h.blocked)}]:[],{label:"Rules",value:String(tE(e.wafRules))}],href:"/serverless/firewall"});let _=e.assetsInfo;if(_)r.push({id:"cdn",label:"Asset CDN",kind:"cdn",layer:2,status:"ok",sub:Q(_.cdn,"CloudFront"),facts:[{label:"Distribution",value:Q(_.cdn,"unknown")},{label:"Custom domain",value:Q(_.customDomain,"none")}],href:"/serverless/assets"}),r.push({id:"assets",label:"Asset bucket",kind:"storage",layer:6,status:"ok",sub:Q(_.bucket,"S3"),facts:[{label:"Bucket",value:Q(_.bucket,"unknown")},..._.files?[{label:"Objects",value:String(_.files)}]:[],..._.sizeMb?[{label:"Size",value:`${_.sizeMb} MB`}]:[]],href:"/serverless/assets"});let R=s.find((O)=>Q(O.key).startsWith("http"));r.push({id:"gateway",label:"HTTP entry point",kind:"gateway",layer:3,status:R?"ok":"unknown",sub:"Function URL / API Gateway",facts:[{label:"Endpoint",value:o||"not resolved"},{label:"Invocations (24h)",value:String(c.invocations??0)},...c.errorRatePct!=null?[{label:"Error rate",value:`${c.errorRatePct}%`}]:[]],href:"/serverless/metrics"});for(let O of s){let K=`fn:${Q(O.name)}`;if(!Q(O.name))continue;let ae=Number(O.errors??0),Se=Number(O.invocations??0);r.push({id:K,label:Q(O.key,Q(O.name)),kind:"function",layer:4,status:ae>0?Se&&ae/Se>0.02?"bad":"warn":Se?"ok":"idle",sub:Q(O.runtime,"lambda"),facts:[{label:"Function",value:Q(O.name)},{label:"Memory",value:`${O.memory??0} MB`},{label:"Timeout",value:`${O.timeout??0}s`},{label:"Invocations (24h)",value:String(Se)},{label:"Errors (24h)",value:String(ae)},{label:"p95",value:`${O.p95??0} ms`},...O.provisioned?[{label:"Provisioned",value:Q(O.provisioned)}]:[]],href:"/serverless/functions"})}for(let O of d){let K=`queue:${Q(O.name)}`;if(!Q(O.name))continue;let ae=Number(O.dlq??0);r.push({id:K,label:Q(O.name),kind:"queue",layer:5,status:ae>0?"bad":Number(O.visible??0)>0?"warn":"ok",sub:"SQS",facts:[{label:"Visible",value:String(O.visible??0)},{label:"In flight",value:String(O.inFlight??0)},{label:"Processed (24h)",value:String(O.processed??0)},{label:"Dead letter",value:String(ae)}],href:"/serverless/queues"})}let E=e.aurora;if(E)r.push({id:"database",label:"Aurora Serverless",kind:"database",layer:6,status:Kt(E.status),sub:Q(E.engine,"aurora"),facts:[{label:"Cluster",value:Q(E.id,"unknown")},{label:"Capacity",value:`${E.currentAcu??0} ACU (${E.minAcu??0}–${E.maxAcu??0})`},{label:"Connections",value:String(E.connections??0)}],href:"/serverless/data"});let y=e.proxy;if(y)r.push({id:"rds-proxy",label:"RDS Proxy",kind:"database",layer:5,status:Kt(y.status),sub:"Connection pooling",facts:[{label:"Proxy",value:Q(y.name,"unknown")},{label:"Endpoint",value:Q(y.endpoint,"unknown")},{label:"Pooled",value:String(y.pooledConns??0)}],href:"/serverless/data"});let $=e.redis;if($)r.push({id:"cache",label:"ElastiCache",kind:"cache",layer:6,status:Kt($.status),sub:Q($.node,"redis"),facts:[{label:"Group",value:Q($.id,"unknown")},{label:"Hit rate",value:`${$.hitRate??0}%`}],href:"/serverless/data"});let b=e.efs;if(b)r.push({id:"efs",label:"EFS",kind:"filesystem",layer:6,status:Kt(b.status),sub:Q(b.mount,"/mnt/local"),facts:[{label:"File system",value:Q(b.id,"unknown")},{label:"Mount",value:Q(b.mount,"unknown")},{label:"Size",value:`${b.sizeMb??0} MB`}],href:"/data/volumes"});let z=e.scheduler??{};if(z.enabled)r.push({id:"scheduler",label:"Scheduler",kind:"scheduler",layer:3,status:"ok",sub:Q(z.expression,"rate(1 minute)"),facts:[{label:"Expression",value:Q(z.expression,"unknown")},{label:"Last run",value:Q(z.lastRun,"unknown")}],href:"/operations/jobs"});let C=new Set(r.map((O)=>O.id)),B=C.has("waf")?"waf":"gateway";Ne(n,{source:"internet",target:"dns",flow:"request",label:"https"},C),Ne(n,{source:"dns",target:B,flow:"request"},C),Ne(n,{source:"dns",target:"cdn",flow:"request",label:"assets"},C),Ne(n,{source:"waf",target:"gateway",flow:"request",label:"allowed"},C),Ne(n,{source:"cdn",target:"assets",flow:"data",label:"origin"},C);let N=s.filter((O)=>Q(O.key).startsWith("http")),F=s.filter((O)=>Q(O.key).startsWith("queue")),J=s.filter((O)=>Q(O.key).startsWith("cli"));for(let O of N)Ne(n,{source:"gateway",target:`fn:${Q(O.name)}`,flow:"request",label:"invoke"},C);for(let O of J)Ne(n,{source:"scheduler",target:`fn:${Q(O.name)}`,flow:"async",label:"schedule"},C);for(let O of d){for(let K of N)Ne(n,{source:`fn:${Q(K.name)}`,target:`queue:${Q(O.name)}`,flow:"async",label:"publish"},C);for(let K of F)Ne(n,{source:`queue:${Q(O.name)}`,target:`fn:${Q(K.name)}`,flow:"async",label:"consume"},C)}let Z=["rds-proxy","database","cache","efs","assets"];for(let O of s){let K=`fn:${Q(O.name)}`;if(C.has("rds-proxy"))Ne(n,{source:K,target:"rds-proxy",flow:"data",label:"pooled"},C);else Ne(n,{source:K,target:"database",flow:"data",label:"sql"},C);for(let ae of Z.filter((Se)=>Se!=="rds-proxy"&&Se!=="database"))Ne(n,{source:K,target:ae,flow:"data"},C)}return Ne(n,{source:"rds-proxy",target:"database",flow:"data",label:"sql"},C),{mode:"serverless",project:Q(t.project)||Q(a.name,"application"),environment:Q(t.environment)||Q(a.env,"production"),provider:"aws",region:Q(a.region,"unknown"),generatedAt:new Date().toISOString(),layers:Xm,groups:[],nodes:r,links:n,notes:i}}function rE(e,t,r={}){return e==="serverless"?is(t,r):$n(t,r)}function Ku(e){return String(e).padStart(2,"0")}function ui(e){return`${e.getUTCFullYear()}-${Ku(e.getUTCMonth()+1)}-${Ku(e.getUTCDate())}`}function nE(e){let t=Math.max(0,Math.round((Date.now()-e)/1000));if(t<60)return`${t}s ago`;let r=Math.round(t/60);if(r<60)return`${r}m ago`;let n=Math.round(r/60);if(n<48)return`${n}h ago`;return`${Math.round(n/24)}d ago`}async function ta(e,t,r,n,i,a){let s=await e.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:r,Dimensions:[{Name:"FunctionName",Value:t}],StartTime:i,EndTime:a,Period:86400,Statistics:[n]}).catch(()=>[]);if(!s.length)return 0;if(n==="Sum")return s.reduce((d,c)=>d+(c.Sum??0),0);if(n==="Maximum")return Math.max(...s.map((d)=>d.Maximum??0));return s.reduce((d,c)=>d+(c.Average??0),0)/s.length}async function ra(e,t,r,n,i,a,s){let d=await e.getMetricStatistics({Namespace:t,MetricName:r,Dimensions:n,StartTime:a,EndTime:s,Period:86400,Statistics:[i]}).catch(()=>[]);if(!d.length)return 0;if(i==="Sum")return d.reduce((c,o)=>c+(o.Sum??0),0);if(i==="Maximum")return Math.max(...d.map((c)=>c.Maximum??0));return d.reduce((c,o)=>c+(o.Average??0),0)/d.length}async function Rd(e,t,r,n,i){let a=await e.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"Duration",Dimensions:[{Name:"FunctionName",Value:t}],StartTime:n,EndTime:i,Period:86400,ExtendedStatistics:[r]}).catch(()=>[]);return Math.round(a.reduce((s,d)=>s+(d.Percentiles?.[r]??0),0))}async function na(e,t){let r=await rt(e,t),n=r.region,i=new Ar(n),a=new Et(n),s=new oi(n),d=new Date,c=new Date(d.getTime()-86400000),o=e.environments?.[t]?.app,g={};g.app={name:r.slug,env:t,region:n,runtime:o?.kind==="php"?`php-${o?.phpVersion??"8.3"} (fpm)`:o?.kind??"node",url:r.endpoint??"",build:r.lastRelease?.sha?.slice(0,7)??"—",deployedAt:r.lastRelease?.timestamp??"—"},g.maintenance={enabled:!1},g.scheduler={enabled:r.scheduler!=="off",expression:r.scheduler==="sub-minute"?"rate(1 minute) · sub-minute":"rate(1 minute)",lastRun:"—"};let h=0,_=0,R=0,E=[],y=[],$=[];for(let B of r.functions){let[N,F,J,Z,O,K,ae,Se,Te]=await Promise.all([ta(i,B.name,"Invocations","Sum",c,d),ta(i,B.name,"Errors","Sum",c,d),ta(i,B.name,"Throttles","Sum",c,d),ta(i,B.name,"Duration","Average",c,d),a.getFunction(B.name).catch(()=>null),Rd(i,B.name,"p50",c,d),Rd(i,B.name,"p95",c,d),Rd(i,B.name,"p99",c,d),i.getMetricSeries({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:[{Name:"FunctionName",Value:B.name}],StartTime:new Date(d.getTime()-43200000),EndTime:d,Period:3600,Stat:"Sum"}).catch(()=>[])]);h+=N,_+=F,R=Math.max(R,Z);let de=O?.Configuration?.MemorySize??0,Ae=Object.keys(O?.Configuration?.Environment?.Variables??{}),ze=[],ue=0;try{let{events:T=[]}=await s.filterLogEvents({logGroupName:`/aws/lambda/${B.name}`,startTime:c.getTime(),limit:120});for(let U of T){let M=(U.message??"").trim(),_e=/Max Memory Used:\s*(\d+)\s*MB/.exec(M);if(_e)ue=Math.max(ue,Number(_e[1]));if(M&&!/^(?:START|END|REPORT|INIT_START)/.test(M))$.push({source:B.mode||B.name,timestamp:new Date(U.timestamp??0).toISOString(),when:nE(U.timestamp??0),message:M.slice(0,400),level:/error|exception|fatal|panic|traceback/i.test(M)?"error":/warn|warning|timeout|retr(?:y|ies)|throttl/i.test(M)?"warn":"info"})}ze=T.filter((U)=>!/^(?:START|END|REPORT|INIT_START)/.test((U.message??"").trim())).slice(-6).map((U)=>({ts:new Date(U.timestamp??0).toISOString().slice(11,19),msg:(U.message??"").trim().slice(0,120),err:/error|exception|fatal/i.test(U.message??"")}))}catch{}let P=Math.max(1,...Te);E.push({key:B.mode,name:B.name,version:B.version,memory:de,timeout:O?.Configuration?.Timeout??0,runtime:O?.Configuration?.Runtime??"provided.al2023",invocations:Math.round(N),errors:Math.round(F),p95:ae||Math.round(Z),status:"active",provisioned:B.provisioned?`${B.provisioned.allocated}/${B.provisioned.requested}`:void 0}),y.push({key:B.mode,name:B.name,runtime:O?.Configuration?.Runtime??"provided.al2023",arch:O?.Configuration?.Architectures?.[0]??"x86_64",memory:de,timeout:O?.Configuration?.Timeout??0,ephemeral:O?.Configuration?.EphemeralStorage?.Size??512,version:B.version,concurrency:o?.concurrency??"—",invocations:Math.round(N),errors:Math.round(F),throttles:Math.round(J),p50:K||Math.round(Z),p95:ae||Math.round(Z),p99:Se||Math.round(Z),maxMem:ue,spark:Te.length?Te.map((T)=>Math.round(T/P*100)):[0],env:Ae.length?Ae:["(none)"],recent:ze.length?ze:[{ts:"—",msg:"no recent events",err:!1}]})}g.functions=E,g.functionsDetail=y,g.serverlessLogs=$.sort((B,N)=>String(N.timestamp).localeCompare(String(B.timestamp))).slice(0,600),g.serverlessLogsEmptyReason=$.length?void 0:"No recent function logs were found in CloudWatch for this environment.";let b=h?Number((_/h*100).toFixed(2)):0,z=Math.round(await ta(i,r.functions[0]?.name??"","ConcurrentExecutions","Maximum",c,d));g.metrics={invocations:Math.round(h),errorRatePct:b,p95Ms:Math.round(R),coldStartPct:void 0,concurrency:z,estCostUsd:void 0};try{let B=new Cn(n),N=[],F=[],J=0;try{let{QueueUrl:O}=await B.getQueueUrl(`${r.slug}-${t}-dlq`),{Attributes:K}=await B.getQueueAttributes(O);J=Number(K.ApproximateNumberOfMessages??0)}catch{}let Z=o?as(o,r.slug,t):[];for(let O of Z){let K=O.name.replace(`${r.slug}-${t}-`,""),ae=0,Se=0;try{let{QueueUrl:de}=await B.getQueueUrl(O.name),{Attributes:Ae}=await B.getQueueAttributes(de);ae=Number(Ae.ApproximateNumberOfMessages??0),Se=Number(Ae.ApproximateNumberOfMessagesNotVisible??0)}catch{}let Te=Math.round(await ra(i,"AWS/SQS","NumberOfMessagesDeleted",[{Name:"QueueName",Value:O.name}],"Sum",c,d));N.push({name:K,visible:ae,inFlight:Se,processed:Te,dlq:J}),F.push({name:O.name,short:K,visible:ae,inFlight:Se,delayed:0,processed:Te,oldestSec:0,concurrency:O.concurrency??o?.queueConcurrency??"—",tries:o?.queueTries??3,visTimeout:(o?.queueTimeout??120)*6,dlq:J})}if(N.length)g.queues=N;if(F.length)g.queuesDetail=F;g.dlqItems=[]}catch{}try{let B=new wr(n),{Stacks:N}=await B.describeStacks({stackName:ci(e,t)}),F={};for(let J of N?.[0]?.Outputs??[])if(J.OutputKey)F[J.OutputKey]=J.OutputValue??"";if(o?.database?.connection==="aurora-serverless"){let J=`${r.slug}-${t}-db`,Z=[{Name:"DBClusterIdentifier",Value:J}],[O,K]=await Promise.all([ra(i,"AWS/RDS","ServerlessDatabaseCapacity",Z,"Average",c,d),ra(i,"AWS/RDS","DatabaseConnections",Z,"Maximum",c,d)]);if(g.aurora={id:J,engine:"aurora-mysql",minAcu:o?.database?.minCapacity??0.5,maxAcu:o?.database?.maxCapacity??4,currentAcu:O?Number(O.toFixed(1)):o?.database?.minCapacity??0.5,database:"app",connections:Math.round(K),status:F.DbEndpoint?"available":"creating"},o?.rdsProxy)g.proxy={name:`${r.slug}-${t}-proxy`,endpoint:F.DbProxyEndpoint??"—",pooledConns:Math.round(K),status:"available"}}if(o?.cache?.driver==="elasticache"){let J=`${r.slug}-${t}-cache`,Z=[{Name:"CacheClusterId",Value:`${J}-001`}],[O,K]=await Promise.all([ra(i,"AWS/ElastiCache","CacheHits",Z,"Sum",c,d),ra(i,"AWS/ElastiCache","CacheMisses",Z,"Sum",c,d)]),ae=O+K>0?Number((O/(O+K)*100).toFixed(1)):0;g.redis={id:J,node:"cache.t4g.micro",engine:"redis",hitRate:ae,status:F.CacheEndpoint?"available":"creating"}}if(o?.efs){let J=0;try{if(F.EfsFileSystemId){let Z=new Xu(n),{FileSystems:O}=await Z.describeFileSystems({FileSystemId:F.EfsFileSystemId});J=Number(((O?.[0]?.SizeInBytes?.Value??0)/1048576).toFixed(1))}}catch{}g.efs={id:F.EfsFileSystemId??"efs",mount:"/mnt/local",sizeMb:J,status:"available"}}g.assetsInfo=F.AssetsCdnDomain?{bucket:F.AssetsBucketName??`${r.slug}-${t}-assets`,cdn:F.AssetsCdnDomain,customDomain:o?.assetDomain??"—",assetUrl:r.assetUrl??"—",files:0,sizeMb:0,cacheHitPct:0,build:g.app.build}:void 0}catch{}if(g.assetsInfo)try{let N=await new lr(n).list({bucket:g.assetsInfo.bucket,maxKeys:1000});g.assetsInfo.files=N.length,g.assetsInfo.sizeMb=Number((N.reduce((F,J)=>F+(J.Size??0),0)/1048576).toFixed(1)),g.assetsRecent=N.slice(0,8).map((F)=>({path:`/${F.Key}`,size:`${Math.max(1,Math.round((F.Size??0)/1024))} KB`,type:F.Key.split(".").pop()??""}))}catch{}try{if(o?.secrets){let B=Array.isArray(o.secrets)?o.secrets.map((N)=>({key:N.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),source:N})):Object.entries(o.secrets).map(([N,F])=>({key:N,source:String(F)}));g.secretsList=B.map((N)=>({...N,updated:"—"}))}}catch{}try{let B=new lr(n),N=`${r.slug}-${t}-deployments`,F=await B.getObjectJson(N,`deployments/${r.slug}/${t}/history.json`).catch(()=>null);if(F?.records?.length)g.deploymentsDetail=F.records.slice(-12).reverse().map((J)=>({sha:(J.sha??"").slice(0,7),status:J.status??"success",when:J.timestamp??"—",took:J.took??"—",by:J.by??"—",version:J.version??"—",hooks:J.hooks??[]}))}catch{}g.metricsTotals={invocations:g.metrics.invocations,errors:Math.round(_),errorRatePct:b,p95Ms:g.metrics.p95Ms,throttles:y.reduce((B,N)=>B+N.throttles,0),coldStartPct:void 0,estCostUsd:void 0,concurrency:z},g.metricsPerFn=y.map((B)=>({key:B.key,invocations:B.invocations,errors:B.errors,throttles:B.throttles,avgMs:B.p50,maxMs:B.p99,costUsd:void 0}));try{g.invSpark=await i.getMetricSeries({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:[{Name:"FunctionName",Value:r.functions.find((B)=>B.mode==="http")?.name??""}],StartTime:new Date(d.getTime()-86400000),EndTime:d,Period:3600,Stat:"Sum"})}catch{}try{let B=new Yu,N=d,F=new Date(Date.UTC(N.getUTCFullYear(),N.getUTCMonth(),1)),J=new Date(Date.UTC(N.getUTCFullYear(),N.getUTCMonth()-1,1)),[Z,O]=await Promise.all([B.getCostByService({start:ui(F),end:ui(N),granularity:"MONTHLY"}).catch(()=>[]),B.getCostByService({start:ui(J),end:ui(F),granularity:"MONTHLY"}).catch(()=>[])]);if(Z.length){let K=Z.reduce((ue,P)=>ue+P.amount,0),ae=O.reduce((ue,P)=>ue+P.amount,0),Se=N.getUTCDate(),Te=new Date(Date.UTC(N.getUTCFullYear(),N.getUTCMonth()+1,0)).getUTCDate();g.costSummary={monthToDateUsd:Number(K.toFixed(2)),projectedUsd:Number((K/Se*Te).toFixed(2)),lastMonthUsd:Number(ae.toFixed(2)),dailyAvgUsd:Number((K/Se).toFixed(2))},g.costServices=Z.filter((ue)=>ue.amount>0).sort((ue,P)=>P.amount-ue.amount).slice(0,12).map((ue)=>({name:ue.service,usd:Number(ue.amount.toFixed(2)),note:""})),g.metrics.estCostUsd=Number((K/Se).toFixed(2)),g.metricsTotals.estCostUsd=g.metrics.estCostUsd,g.costTrend=await B.getDailyTotals({start:ui(F),end:ui(N)}).catch(()=>[]);let de=Z.find((ue)=>/lambda/i.test(ue.service))?.amount??0,Ae=(ue)=>ue.invocations*(ue.p50/1000)*(ue.memory/1024),ze=y.reduce((ue,P)=>ue+Ae(P),0)||1;g.costPerFn=y.map((ue)=>({key:ue.key,requests:ue.invocations,gbSec:Math.round(Ae(ue)),usd:Number((de*(Ae(ue)/ze)).toFixed(2))}))}}catch{}if(o?.firewall)try{let B=await i.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"BlockedRequests",StartTime:c,EndTime:d,Period:86400,Statistics:["Sum"]}).catch(()=>[]),N=await i.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"AllowedRequests",StartTime:c,EndTime:d,Period:86400,Statistics:["Sum"]}).catch(()=>[]);g.waf={enabled:!0,scope:"REGIONAL",acl:`${r.slug}-${t}-waf`,allowed24h:Math.round(N.reduce((F,J)=>F+(J.Sum??0),0)),blocked24h:Math.round(B.reduce((F,J)=>F+(J.Sum??0),0))};try{let F=new _d(n),J=await F.listWebACLs("REGIONAL"),Z=J.find((O)=>O.Name?.includes(`${r.slug}-${t}`))??J[0];if(Z?.Name&&Z.Id){g.waf.acl=Z.Name;let O=await F.getWebACLRules(Z.Name,Z.Id,"REGIONAL");if(O.length)g.wafRules=O.map((K)=>({name:K.Name??"—",detail:`priority ${K.Priority??0}`,action:K.Action??"count",blocked24h:0}))}}catch{}}catch{}let C=[];if(g.aurora)C.push({name:"Aurora Serverless v2",detail:`${g.aurora.id} · ${g.aurora.minAcu}-${g.aurora.maxAcu} ACU`,status:g.aurora.status});if(g.proxy)C.push({name:"RDS Proxy",detail:g.proxy.name,status:g.proxy.status});if(g.redis)C.push({name:`ElastiCache (${g.redis.engine})`,detail:`${g.redis.node} · ${g.redis.hitRate}% hit rate`,status:g.redis.status});if(g.efs)C.push({name:"EFS",detail:`${g.efs.mount} · ${g.efs.sizeMb} MB`,status:g.efs.status});if(C.length)g.dataServices=C;if(r.scheduler!=="off"&&o?.kind==="php")try{let B=await li(e,t,"schedule:list"),N=[];for(let F of(B||"").split(`
16
+ `)){let J=/^\s*([\d*/,\-\s]+?)\s{2,}(.+?)(?:\s{2,}Next Due.*)?$/.exec(F);if(J&&/[*\d]/.test(J[1])&&J[1].trim().split(/\s+/).length===5)N.push({command:J[2].trim().replace(/^php artisan /,""),cron:J[1].trim(),desc:"",lastRun:"—",lastStatus:"ok"})}if(N.length)g.schedulerTasks=N}catch{}return g.topology=is(g,{project:e.project.name,environment:t}),g}function Yr(e){let t=Number(e);return Number.isFinite(t)&&t>=0?t:null}function iE(e){if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return null;let t=Date.parse(`${e}T12:00:00.000Z`);return Number.isFinite(t)?new Date(t).toISOString():null}function qu(e,t){if(!e||typeof e!=="object")return[];let r={source:t.name},n=[],i=t.now,a=(o,g,h,_=i)=>{if(g!==null)n.push({name:o,value:g,unit:h,timestamp:_,attributes:r})};a("storage.egress.month",Yr(e.monthBytes),"bytes"),a("storage.egress.today",Yr(e.todayBytes),"bytes"),a("storage.egress.projected_month",Yr(e.projectedMonthBytes),"bytes");let s=Yr(e.budgetBytes);if(s!==null&&s>0){a("storage.egress.budget",s,"bytes");let o=e.budgetUsedPercent,g=typeof o==="number"&&Number.isFinite(o)?o:Yr(e.monthBytes)!==null?Math.round(Yr(e.monthBytes)/s*1000)/10:null;a("storage.egress.budget_used_percent",g,"percent")}let d=t.maxReplayDays??45,c=Array.isArray(e.days)?e.days.slice(-d):[];for(let o of c){let g=iE(String(o?.date??"")),h=Yr(o?.bytes);if(!g||h===null)continue;n.push({name:"storage.egress.day",value:h,unit:"bytes",timestamp:g,attributes:r});let _=Yr(o?.downloads);if(_!==null)n.push({name:"storage.egress.day_downloads",value:_,unit:"count",timestamp:g,attributes:r})}return n}async function eh(e,t=process.env,r=fetch){let n=e.tokenEnv?t[e.tokenEnv]:void 0,i=await r(e.url,{headers:n?{Authorization:`Bearer ${n}`}:{},signal:AbortSignal.timeout(1e4)});if(!i.ok)throw Error(`HTTP ${i.status}`);return await i.json()}async function pd(e,t){let r=[],n=[];if(!Array.isArray(e)||e.length===0)return{metrics:r,errors:n};let i=await Promise.all(e.map(async(a)=>{if(!a?.name||!a?.url)return{endpoint:a,error:"egress endpoint needs both a name and a url"};try{let s=await eh(a,t.env,t.fetchImpl);return{endpoint:a,report:s}}catch(s){return{endpoint:a,error:s instanceof Error?s.message:String(s)}}}));for(let a of i){let s=`egress:${a.endpoint?.name??"unnamed"}`;if("error"in a&&a.error){n.push({source:s,message:a.error});continue}r.push(...qu(a.report,{name:a.endpoint.name,now:t.now}))}return{metrics:r,errors:n}}import{createHash as K$}from"node:crypto";import{existsSync as Fr,mkdtempSync as Vg,readdirSync as SI,rmSync as ei,statSync as VI}from"node:fs";import{readFile as pr,writeFile as Xn}from"node:fs/promises";import{tmpdir as rd}from"node:os";import{dirname as Y$,extname as Fa,join as ke,normalize as X$,relative as q$,resolve as eC,sep as tC}from"node:path";import{fileURLToPath as rC}from"node:url";class Id extends Error{status;code;requestId;constructor(e,t,r,n){super(r);this.status=e;this.code=t;this.requestId=n}}class th{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 Id(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 KE}from"node:crypto";import{lstatSync as aE,readdirSync as sE,readFileSync as oE}from"node:fs";import{relative as dE,resolve as rh,sep as cE}from"node:path";function lE(e){return new Map(e.map((t)=>[t.path.replace(/^\.\//,"").replace(/\\/g,"/"),t]))}function kn(e,t,r){return{path:e,reason:t,weight:r}}function nh(e){try{return e?.content?JSON.parse(e.content):{}}catch{return{}}}function hi(e,t,r,n,i,a){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:a}}function fi(e){let t=lE(e.slice(0,1e4)),r=[];if(t.has("Dockerfile"))r.push(hi("dockerfile","dockerfile",0.99,[kn("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=nh(t.get("composer.json"));if(t.has("artisan")&&n.require?.["laravel/framework"])r.push(hi("laravel","server",0.98,[kn("artisan","Laravel Artisan entrypoint is present.",0.45),kn("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(hi("php","server",0.82,[kn("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=nh(t.get("package.json"));if(t.has("package.json")){let a=t.has("bun.lock")||t.has("bun.lockb")||i.engines?.bun,s=a?"bun":"node",d=a?"bun":"node",c=[kn("package.json",`Defines ${i.scripts?.build?"build and ":""}${i.scripts?.start?"start ":""}scripts.`,0.55)];if(a)c.push(kn(t.has("bun.lock")?"bun.lock":t.has("bun.lockb")?"bun.lockb":"package.json","Pins the Bun package manager/runtime.",0.35));let o=!!(i.dependencies?.vite||i.devDependencies?.vite||i.dependencies?.["@stacksjs/bunpress"]||i.devDependencies?.["@stacksjs/bunpress"])&&!i.scripts?.start,g=o?{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(hi(d,g.kind,Math.min(0.94,c.reduce((h,_)=>h+_.weight,0)),c,g,o?"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(hi("static","static",0.78,[kn(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(hi("unknown","buildpack",0.2,[],{kind:"buildpack",runtime:"node"},"No supported framework signature was conclusive; choose commands and runtime manually."));return r.sort((a,s)=>s.confidence-a.confidence||a.framework.localeCompare(s.framework))}function md(e,t={}){let r=rh(e),n=t.maxFiles??1e4,i=t.maxContentBytes??262144,a=[],s=new Set(["Dockerfile","package.json","composer.json","index.html","public/index.html","bun.lock","bun.lockb","artisan"]),d=new Set([".git",".ts-cloud",".cache",".next",".nuxt",".output",".turbo",".bun","node_modules","vendor","pantry","dist","build","coverage"]),c=(o)=>{for(let g of sE(o).sort()){if(d.has(g))continue;let h=rh(o,g),_=dE(r,h).split(cE).join("/");if(!_||_.startsWith("../"))throw Error("Detection path escaped the application root");let R=aE(h);if(R.isSymbolicLink())throw Error(`Detection refuses symbolic links: ${_}`);if(R.isDirectory())c(h);else if(R.isFile()){if(a.length>=n)throw Error("Application file-count limit exceeded");let E={path:_,size:R.size};if(s.has(_)&&R.size<=i)E.content=oE(h,"utf8");a.push(E)}}};return c(r),a}function yd(e){if(Array.isArray(e))return`[${e.map(yd).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)}:${yd(r)}`).join(",")}}`;return JSON.stringify(e)??"null"}function ia(e){return!!e&&!e.startsWith("/")&&!e.split("/").includes("..")&&!/[\0\r\n]/.test(e)}function vt(e,t,r,n){return{path:e,code:t,message:r,alternatives:n}}function Ed(e){return JSON.parse(JSON.stringify(e))}function gE(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 Ed({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 Ed({serverless:{apps:{[e.slug]:{source:e.source,build:e.build,architecture:e.runtime.architecture,environment:t,domain:e.domain}}}});return Ed({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 Yt(e,t=[]){let r=[],n=(E)=>/(?:secret|token|password|passwd|private[_-]?key|api[_-]?key)/i.test(E),i=Object.fromEntries(Object.entries(e.environment??{}).map(([E,y])=>{if(typeof y==="string"&&n(E))return r.push(vt(`environment.${E}`,"write_only_secret_required",`${E} must be supplied through the write-only secrets boundary.`)),[E,{secretRef:E}];return[E,y]})),a=e.build;if(e.build.kind==="dockerfile"&&e.build.buildArgs){let E=Object.fromEntries(Object.entries(e.build.buildArgs).map(([y,$])=>{if(n(y))return r.push(vt(`build.buildArgs.${y}`,"write_only_build_secret_required",`${y} must be declared in secretNames instead of buildArgs.`)),[y,"[REDACTED]"];return[y,$]}));a={...e.build,buildArgs:E}}if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(e.slug))r.push(vt("slug","invalid_slug","Slug must contain 2-63 lowercase letters, numbers, or hyphens."));if(!ia((e.source.kind==="git"?e.source.monorepoRoot:e.source.kind==="local"?e.source.root:".")??"."))r.push(vt("source","unsafe_source_root","Source root must stay inside the source tree."));if(e.source.kind==="git"&&e.source.sparsePaths?.some((E)=>!ia(E)))r.push(vt("source.sparsePaths","unsafe_sparse_path","Sparse checkout paths must stay inside the repository."));if(e.build.kind==="dockerfile"&&(!ia(e.build.context)||!ia(e.build.dockerfile)))r.push(vt("build","unsafe_docker_path","Docker context and Dockerfile must stay inside the source tree."));if(e.build.kind==="static"&&!ia(e.build.publishDirectory))r.push(vt("build.publishDirectory","invalid_publish_directory","A safe static publish directory is required."));if(e.build.kind==="server"&&!e.build.startCommand.trim())r.push(vt("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(vt("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(vt("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(vt("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(vt("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(vt("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(vt("domain.hostname","invalid_domain","Domain must be a valid DNS hostname."));let d=Object.values(i).flatMap((E)=>typeof E==="object"?[E.secretRef]:[]),c=[...new Set([...e.requiredSecretNames??[],...e.build.kind==="dockerfile"?e.build.secretNames??[]:[],...d])].sort(),o=new Set(t),g=c.filter((E)=>!o.has(E)),h={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:a,runtime:e.runtime,environment:i,domain:e.domain}},_=[...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(),R=[...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&&g.length===0,issues:r,missingSecrets:g,manifest:h,configPatch:gE({...e,build:a,environment:i}),capabilityRequirements:_,costDrivers:R,serializedManifest:`${yd(h)}
17
+ `}}function ih(e){let t=e.replace(/\\/g,"/");return!!t&&!t.startsWith("/")&&!/^[A-Za-z]:\//.test(t)&&!t.split("/").includes("..")&&!/[\0\r\n]/.test(t)}function ah(e,t,r={}){let n=r.maxBytes??104857600,i=r.maxEntries??1e4,a=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),d=[],c=0;if(t.toLowerCase().endsWith(".zip")||e[0]===80&&e[1]===75){let g=0;while(g+30<=e.length){let h=s.getUint32(g,!0);if(h===33639248||h===101010256)break;if(h!==67324752)throw Error("Malformed ZIP local header");let _=s.getUint16(g+6,!0),R=s.getUint32(g+18,!0),E=s.getUint32(g+22,!0),y=s.getUint16(g+26,!0),$=s.getUint16(g+28,!0);if(_&8)throw Error("ZIP data descriptors are not accepted for uploaded artifacts");let b=new TextDecoder().decode(e.subarray(g+30,g+30+y));if(!ih(b))throw Error(`Unsafe archive path: ${b}`);if(d.push(b),c+=E,d.length>i||c>a)throw Error("Archive expansion limit exceeded");g+=30+y+$+R}return{format:"zip",entries:d.length,expandedBytes:c,paths:d}}if(!t.toLowerCase().match(/\.(?:tar|tar\.gz|tgz)$/))throw Error("Only ZIP and uncompressed TAR artifacts are supported");let o=0;while(o+512<=e.length){let g=e.subarray(o,o+512);if(g.every((y)=>y===0))break;let h=(y,$)=>new TextDecoder().decode(g.subarray(y,y+$)).replace(/\0.*$/,""),_=`${h(345,155)}${h(345,155)?"/":""}${h(0,100)}`,R=Number.parseInt(h(124,12).trim()||"0",8),E=String.fromCharCode(g[156]??0);if(!ih(_))throw Error(`Unsafe archive path: ${_}`);if(E==="1"||E==="2")throw Error(`Archive links are not accepted: ${_}`);if(!Number.isFinite(R)||R<0)throw Error("Malformed TAR entry size");if(d.push(_),c+=R,d.length>i||c>a)throw Error("Archive expansion limit exceeded");o+=512+Math.ceil(R/512)*512}return{format:"tar",entries:d.length,expandedBytes:c,paths:d}}var sh=new Set(["source","build","runtime","environment","domain","review"]);function oh(e,t){try{return typeof e==="string"?JSON.parse(e):t}catch{return t}}function dh(e){return/(?:secret|token|password|passwd|private[_-]?key|api[_-]?key)/i.test(e)}function ch(e){for(let[r,n]of Object.entries(e.environment??{}))if(typeof n==="string"&&dh(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(dh(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 lh(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:oh(e.input,{}),suppliedSecretNames:oh(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 wd{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(ch(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(!sh.has(i))throw Error("Invalid draft step");let a=[...new Set(e.suppliedSecretNames??[])].sort(),s=Yt(e.draft,a).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(a),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?lh(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(lh)}update(e,t,r){let n=this.get(e);if(!n||n.version!==t)throw Error(`Application draft ${e} changed since version ${t}`);if(!sh.has(r.step))throw Error("Invalid draft step");if(r.draft.projectId!==n.projectId)throw Error("Draft project cannot be changed");ch(r.draft);let i=[...new Set(r.suppliedSecretNames??n.suppliedSecretNames)].sort(),a=Yt(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),a,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:a}}),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=Yt(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 a=this.now();return this.controlPlane.database.run("UPDATE application_drafts SET status='applied', step='review', version=version+1, updated_at=? WHERE id=? AND version=?",[a,e,t]),this.controlPlane.appendEvent({organizationId:n.organizationId,projectId:n.projectId,actorId:r,type:"application.draft.applied",payload:Oe({draftId:e,manifest:i.manifest})}),this.get(e)}}import{createCipheriv as uE,createDecipheriv as hE,createHash as hh,randomBytes as fE}from"node:crypto";function aa(e){return typeof e==="string"&&e?e:void 0}function Ad(e){return hh("sha256").update(e).digest("hex").slice(0,16)}function gh(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 SE(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:aa(e.credential_fingerprint),credentialExpiresAt:aa(e.credential_expires_at),status:String(e.status),healthMessage:aa(e.health_message),lastTestedAt:aa(e.last_tested_at),version:Number(e.version),createdByActorId:aa(e.created_by_actor_id),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}class Pd{controlPlane;key;nowFn;idFn;constructor(e,t){this.controlPlane=e;if(!t.encryptionKey)throw Error("Registry encryption key is required");this.key=hh("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=fE(12),r=uE("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 a=hE("aes-256-gcm",this.key,Buffer.from(r,"base64url"));return a.setAuthTag(Buffer.from(n,"base64url")),Buffer.concat([a.update(Buffer.from(i,"base64url")),a.final()]).toString("utf8")}current(e){let t=SE(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),gh(e.host),t?this.encrypt(t):null,t?Ad(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:gh(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),Ad(i),r.expiresAt??null,this.now(),e]),this.controlPlane.appendEvent({organizationId:n.organizationId,actorId:r.actorId,type:"registry.credential.rotated",payload:{connectionId:e,fingerprint:Ad(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,a=new AbortController,s=setTimeout(()=>a.abort(),t.timeoutMs??15000),d=n?.token?`Bearer ${n.token}`:n?.username||n?.password?`Basic ${Buffer.from(`${n.username??""}:${n.password??""}`).toString("base64")}`:void 0;try{let c=await i(`${r.host}/v2/`,{method:"GET",redirect:"error",signal:a.signal,headers:d?{Authorization:d}:void 0}),o=c.headers.get("www-authenticate")??"";if(c.status===401&&o.startsWith("Bearer ")&&n){let _=Object.fromEntries([...o.slice(7).matchAll(/(\w+)="([^"]+)"/g)].map((b)=>[b[1],b[2]])),R=new URL(_.realm??"");if(R.protocol!=="https:")throw Error("Registry authentication realm must use HTTPS");if(_.service)R.searchParams.set("service",_.service);if(t.image)R.searchParams.set("scope",`repository:${fh(t.image).repository}:pull`);let E=await i(R,{signal:a.signal,redirect:"error",headers:d?{Authorization:d}:void 0});if(!E.ok)throw Error(`Registry authentication failed (${E.status})`);let y=await E.json(),$=y.token??y.access_token;if(!$)throw Error("Registry did not return an access token");c=t.image?await uh(i,r.host,t.image,$,a.signal):await i(`${r.host}/v2/`,{signal:a.signal,redirect:"error",headers:{Authorization:`Bearer ${$}`}})}else if(c.ok&&t.image)c=await uh(i,r.host,t.image,n?.token,a.signal,d);let g=c.ok?"healthy":"degraded",h=c.ok?t.image?"Registry image is readable.":"Registry connection is healthy.":`Registry request failed (${c.status})`;return this.controlPlane.database.run("UPDATE registry_connections SET status=?, health_message=?, last_tested_at=?, version=version+1, updated_at=? WHERE id=?",[g,h,this.now(),this.now(),e]),this.get(e)}catch(c){let o=a.signal.aborted?"Registry request timed out.":c instanceof Error?c.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=?",[o.slice(0,1000),this.now(),this.now(),e]),this.get(e)}finally{clearTimeout(s)}}}function fh(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("@"),a=n.lastIndexOf(":"),s=i>=0?i:a>n.lastIndexOf("/")?a:-1,d=s>=0?n.slice(0,s):n,c=s>=0?n.slice(s+1):"latest";if(!/^[A-Za-z0-9_.\/-]+$/.test(d)||!/^[A-Za-z0-9_.:+-]+$/.test(c))throw Error("Image reference is invalid");return{repository:d,reference:c}}async function uh(e,t,r,n,i,a){let s=fh(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}`}:a?{Authorization:a}:{}}})}import{createHash as _E}from"node:crypto";import{chmodSync as Sh,existsSync as _h,mkdirSync as RE,renameSync as pE,unlinkSync as Rh,writeFileSync as IE}from"node:fs";import{basename as mE,join as EE}from"node:path";function Dd(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 $d{controlPlane;root;idFn;nowFn;constructor(e,t){this.controlPlane=e;this.root=_t(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=mE(e.filename).slice(0,200);if(!r||r!==e.filename)throw Error("Artifact filename must not contain a path");let n=ah(e.bytes,r),i=_E("sha256").update(e.bytes).digest("hex"),a=this.controlPlane.database.query("SELECT * FROM application_artifacts WHERE project_id=? AND sha256=?").get(e.projectId,i);if(a)return Dd(a);let s=this.idFn();RE(this.root,{recursive:!0,mode:448}),Sh(this.root,448);let d=EE(this.root,`${s}.archive`),c=`${d}.partial`;try{IE(c,e.bytes,{mode:384,flag:"wx"}),pE(c,d),Sh(d,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,d,i,e.bytes.byteLength,n.format,n.entries,n.expandedBytes,e.actorId??null,this.nowFn().toISOString()])}catch(o){if(_h(c))Rh(c);if(_h(d))Rh(d);throw o}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?Dd(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(Dd)}}function ss(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((o)=>o.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=Yt(t.input,t.suppliedSecretNames);if(!i.valid)throw Error(`Application plan is invalid: ${[...i.issues.map((o)=>o.message),...i.missingSecrets.map((o)=>`Missing secret ${o}`)].join("; ")}`);let a=e.controlPlane.listResources(r.id,n.id).find((o)=>o.kind==="application"&&o.slug===t.input.slug),s=JSON.parse(JSON.stringify({manifest:i.manifest,configPatch:i.configPatch})),d=a?e.controlPlane.updateResource(a.id,a.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}}),c=new Be(e.controlPlane).enqueue({projectId:r.id,environmentId:n.id,resourceId:d.id,actorId:e.actorId,kind:"application.create",idempotencyKey:`application-draft:${t.id}:v${t.version}`,correlationId:`application-draft:${t.id}`,input:s,lockKey:`resource:${d.id}`,providerKey:d.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:d.id,operationId:c.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:d,operation:c}}function sa(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=(a,s)=>s&&(a==="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 os(e,t){let r=sa(e).find((n)=>n.strategy===t);if(!r.supported)throw Error(`${t} is unavailable: ${r.explanation}`);return r}import{createHash as yE}from"node:crypto";var wE=/^sha256:[a-f0-9]{64}$/,AE=/^[a-f0-9]{40,64}$/i;function gr(e){return typeof e==="string"&&e?e:void 0}function bn(e,t){try{return JSON.parse(String(e))}catch{return t}}function ph(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:bn(e.provenance,{}),attestation:bn(e.attestation,{}),verifiedAt:String(e.verified_at),createdAt:String(e.created_at)}}function Ih(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:gr(e.source_sha),configHash:String(e.config_hash),manifest:bn(e.manifest,{}),provenance:bn(e.provenance,{}),strategy:String(e.strategy),status:String(e.status),healthGate:e.health_gate==null?void 0:bn(e.health_gate,void 0),hooks:bn(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:gr(e.previous_release_id),promotedFromReleaseId:gr(e.promoted_from_release_id),actorId:gr(e.actor_id),trigger:String(e.trigger),pinned:Number(e.pinned)===1,pinReason:gr(e.pin_reason),activatedAt:gr(e.activated_at),failedAt:gr(e.failed_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function PE(e){return{sequence:Number(e.sequence),id:String(e.id),releaseId:String(e.release_id),fromStatus:gr(e.from_status),toStatus:String(e.to_status),trafficPercent:e.traffic_percent==null?void 0:Number(e.traffic_percent),health:bn(e.health,{}),message:String(e.message),operationId:gr(e.operation_id),createdAt:String(e.created_at)}}function DE(e,t){let r=[],n=(i,a,s)=>{if(JSON.stringify(a)===JSON.stringify(s))return;if(a&&s&&typeof a==="object"&&typeof s==="object"&&!Array.isArray(a)&&!Array.isArray(s)){for(let d of[...new Set([...Object.keys(a),...Object.keys(s)])].sort())n(i?`${i}.${d}`:d,a[d],s[d]);return}r.push({path:i,...a!==void 0?{before:a}:{},...s!==void 0?{after:s}:{}})};return n("",e,t),r}class Cd{controlPlane;now;id;constructor(e,t={}){this.controlPlane=e;this.now=t.now??(()=>new Date),this.id=t.id??(()=>crypto.randomUUID())}registerArtifact(e){if(!wE.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 ph(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(Oe(e.provenance??{})),JSON.stringify(Oe(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?ph(t):void 0}create(e){let t=this.getArtifact(e.artifactId),r=this.controlPlane.getResource(e.resourceId),n=this.controlPlane.listEnvironments(e.projectId).find((h)=>h.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&&!AE.test(e.sourceSha))throw Error("Release source must be an immutable commit SHA");os({kind:e.kind,provider:r.provider,hasHealthGate:!!e.healthGate,replicas:e.replicas},e.strategy);let i=Oe(e.config),a=yE("sha256").update(JSON.stringify(i)).digest("hex"),s=this.active(e.resourceId),d=this.id(),c=this.now().toISOString(),o=e.approvalRequired?"awaiting_approval":"built",g=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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[d,e.organizationId,e.projectId,e.environmentId,e.resourceId,e.artifactId,e.kind,e.sourceSha??null,a,JSON.stringify(Oe(e.manifest)),JSON.stringify(Oe(e.provenance??{})),e.strategy,o,e.healthGate?JSON.stringify(e.healthGate):null,JSON.stringify(g),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",c,c]),this.recordTransition(d,void 0,o,{message:e.promotedFromReleaseId?"Immutable artifact promoted without rebuild.":"Immutable release record created."}),this.get(d)}get(e){let t=this.controlPlane.database.query("SELECT * FROM releases WHERE id=?").get(e);return t?Ih(t):void 0}list(e={}){return this.controlPlane.database.query("SELECT * FROM releases ORDER BY created_at DESC, rowid DESC").all().map(Ih).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(PE)}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(Oe(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 a=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=?",[a,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,a,t,a,a,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:gr(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:DE(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 vn{controlPlane;releases;queue;constructor(e){this.controlPlane=e;this.releases=new Cd(e),this.queue=new Be(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 a=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:a}}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 $E(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 mh(e,t){if(t.release.artifactId!==t.artifact.id)throw Error("Release activation artifact identity changed");os({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:$E(t.release)})}async function Eh(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 CE=["release.activate","release.rollback"];function kE(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function yh(e){let t=new vn(e.store),r=async(n)=>{let i=kE(n.operation.input),a=typeof i.releaseId==="string"?i.releaseId:"",s=t.releases.get(a);if(!s)throw Error(`Queued release ${a||"(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 d=t.releases.getArtifact(s.artifactId);if(!d||d.digest!==t.releases.getArtifact(s.artifactId)?.digest)throw Error("Immutable release artifact is unavailable");let c=typeof i.targetReleaseId==="string"&&i.targetReleaseId?i.targetReleaseId:s.previousReleaseId,o=c?t.releases.get(c):void 0;if(o&&(o.resourceId!==s.resourceId||o.artifactId===s.artifactId&&o.id===s.id))throw Error("Rollback target does not match the release resource");let g=await e.resolveDriver(s);n.checkpoint("verify",`Verifying ${d.digest} and ${s.configHash} for ${g.name}.`),n.log(`Artifact ${d.digest}; source ${s.sourceSha??"not recorded"}; config ${s.configHash}.`,{stream:"system"}),n.throwIfCancellationRequested();let h;try{h=n.operation.kind==="release.rollback"?await Eh(g,{release:s,artifact:d,previous:o}):await mh(g,{release:s,artifact:d,previous:o})}catch(_){if(n.operation.kind==="release.activate"&&t.releases.get(s.id)?.status==="activating")t.completeHealthGate(s.id,{healthy:!1,operationId:n.operation.id,message:_ instanceof Error?_.message:String(_)});throw _}for(let _ of h.transitions)t.releases.progress(s.id,{message:`${n.operation.kind==="release.rollback"?"Rollback":"Activation"} traffic at ${_.trafficPercent}%.`,trafficPercent:_.trafficPercent,health:_.observed,operationId:n.operation.id}),n.log(`Traffic ${_.trafficPercent}%: ${_.healthy?"healthy":"unhealthy"}.`,{stream:_.healthy?"step":"stderr",step:"health"});if(n.checkpoint("health","Evaluating the provider health result."),!h.activated||!h.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:h.resourceVersions},message:h.error??"Provider health gate failed."});throw Error(h.error??`${g.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 _=await e.resolveHealthGate(s.healthGate.name,s);if(n.log(`${s.healthGate.name}: ${_.healthy?"healthy":"unhealthy"}${_.message?` — ${_.message}`:""}.`,{stream:_.healthy?"step":"stderr",step:"health"}),!_.healthy)throw t.completeHealthGate(s.id,{healthy:!1,operationId:n.operation.id,health:_.evidence,message:_.message??`Named health gate ${s.healthGate.name} failed.`}),Error(_.message??`Named health gate ${s.healthGate.name} failed`)}if(n.operation.kind==="release.rollback"){let _=t.releases.get(s.id);if(_.status!=="rolled_back")t.releases.transition(_.id,"rolled_back",{message:`Traffic restored through ${g.name}.`,operationId:n.operation.id,trafficPercent:0,health:{resourceVersions:h.resourceVersions}});if(o&&o.status!=="active"){let R=o.status==="activating"?o:t.releases.transition(o.id,"activating",{message:"Rollback target restoring traffic.",operationId:n.operation.id,trafficPercent:0});t.releases.transition(R.id,"active",{message:"Previous immutable release restored.",operationId:n.operation.id,trafficPercent:100,health:{resourceVersions:h.resourceVersions}})}}else t.completeHealthGate(s.id,{healthy:!0,operationId:n.operation.id,health:{providerVersion:h.providerVersion??null,resourceVersions:h.resourceVersions},message:"Provider activation and health gates completed."});return n.checkpoint("finalize","Persisted the terminal release state."),{releaseId:s.id,artifactDigest:d.digest,provider:g.name,providerVersion:h.providerVersion??null,resourceVersions:h.resourceVersions,status:t.releases.get(s.id).status}};return Object.fromEntries(CE.map((n)=>[n,r]))}import{createCipheriv as bE,createDecipheriv as vE,createHash as $h,randomBytes as kd}from"node:crypto";var Ch={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 ve(e){return typeof e==="string"&&e?e:void 0}function Bn(e,t){try{return typeof e==="string"?JSON.parse(e):t}catch{return t}}function ur(e){return JSON.stringify(Oe(e))}function On(e){return $h("sha256").update(e).digest("hex")}function wh(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 Ah(e){let t=e.trim();if(t.length<2||t.length>80)throw Error("Connection name must contain 2-80 characters");return t}function bd(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 Ph(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 ds(e){return[...new Set((e??[]).map((t)=>t.trim()).filter(Boolean))].slice(0,100)}function OE(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 BE(e){return{id:String(e.id),organizationId:String(e.organization_id),provider:String(e.provider),name:String(e.name),host:String(e.host),owner:ve(e.owner),authKind:String(e.auth_kind),credentialConfigured:!!e.credential_ciphertext,credentialFingerprint:ve(e.credential_fingerprint),grantedScopes:Bn(e.granted_scopes,[]),capabilities:Bn(e.capabilities,Ch[String(e.provider)]),status:String(e.status),healthMessage:ve(e.health_message),lastTestedAt:ve(e.last_tested_at),lastSyncedAt:ve(e.last_synced_at),credentialExpiresAt:ve(e.credential_expires_at),version:Number(e.version),createdByActorId:ve(e.created_by_actor_id),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function vd(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:Bn(e.metadata,{}),syncedAt:String(e.synced_at)}}function Dh(e){return{id:String(e.id),projectId:String(e.project_id),environmentId:ve(e.environment_id),resourceId:ve(e.resource_id),connectionId:String(e.connection_id),repositoryId:ve(e.repository_id),repositoryFullName:String(e.repository_full_name),defaultBranch:String(e.default_branch),branchRule:ve(e.branch_rule),tagRule:ve(e.tag_rule),monorepoRoot:String(e.monorepo_root),includePaths:Bn(e.include_paths,[]),excludePaths:Bn(e.exclude_paths,[]),submodules:Number(e.submodules)===1,cloneDepth:e.clone_depth==null?void 0:Number(e.clone_depth),deployKeyId:ve(e.deploy_key_id),autoDeploy:Number(e.auto_deploy)===1,pullRequestPreviews:Number(e.pull_request_previews)===1,status:String(e.status),disabledReason:ve(e.disabled_reason),version:Number(e.version),createdByActorId:ve(e.created_by_actor_id),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Od(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:ve(e.created_by_actor_id),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Bd(e){return{id:String(e.id),connectionId:String(e.connection_id),repositoryId:ve(e.repository_id),repositoryFullName:String(e.repository_full_name),providerWebhookId:ve(e.provider_webhook_id),events:Bn(e.events,[]),status:String(e.status),healthMessage:ve(e.health_message),lastDeliveryAt:ve(e.last_delivery_at),lastReconciledAt:ve(e.last_reconciled_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Jd(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:ve(e.action),commitSha:ve(e.commit_sha),signatureStatus:String(e.signature_status),status:String(e.status),payloadSummary:Bn(e.payload_summary,{}),operationId:ve(e.operation_id),error:ve(e.error),receivedAt:String(e.received_at),processedAt:ve(e.processed_at)}}class Td{controlPlane;key;nowFn;idFn;constructor(e,t={}){this.controlPlane=e;this.key=t.encryptionKey?$h("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=kd(12),r=bE("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 a=vE("aes-256-gcm",this.key,Buffer.from(r,"base64url"));return a.setAuthTag(Buffer.from(n,"base64url")),Buffer.concat([a.update(Buffer.from(i,"base64url")),a.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)
18
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?, ?, ?)`,[r,e.organizationId,e.provider,Ah(e.name),wh(e.host),e.owner?.trim()||null,e.authKind??(n?"access_token":"none"),n?this.encrypt(n):null,n?On(n).slice(0,16):null,ur([...new Set(e.grantedScopes??[])].sort()),ur(Ch[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:wh(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=BE(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),On(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:On(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((a)=>a.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?ur(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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
19
+ 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,bd(e.fullName),OE(e.cloneUrl),e.defaultBranch.trim()||"main",e.visibility,e.archived?1:0,ur(e.metadata),r]),vd(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(vd)}getRepository(e){let t=this.controlPlane.database.query("SELECT * FROM source_repositories WHERE id = ?").get(e);return t?vd(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:${On(e.publicKey.trim())}`,a=`sha256:${On(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,Ah(e.name),e.publicKey.trim(),i,this.encrypt(e.privateKey),e.host.trim().toLowerCase(),e.hostKey.trim(),a,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:a}}),Od(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?Od(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(Od)}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),a=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=?",[a,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)
20
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, ?, ?)`,[r,e.projectId,e.environmentId??null,e.resourceId??null,e.connectionId,e.repositoryId??null,bd(e.repositoryFullName),e.defaultBranch?.trim()||"main",e.branchRule?.trim()||null,e.tagRule?.trim()||null,Ph(e.monorepoRoot??"."),ur(ds(e.includePaths)),ur(ds(e.excludePaths)),e.submodules?1:0,e.cloneDepth??null,e.deployKeyId??null,e.autoDeploy===!1?0:1,e.pullRequestPreviews===!1?0:1,e.actorId??null,n,n]),this.controlPlane.appendEvent({organizationId:t.organizationId,projectId:e.projectId,actorId:e.actorId,type:"source.binding.created",payload:{bindingId:r,connectionId:e.connectionId,repository:e.repositoryFullName,branch:e.defaultBranch??"main"}}),this.getBinding(r)}getBinding(e){let t=this.controlPlane.database.query("SELECT * FROM source_bindings WHERE id = ?").get(e);return t?Dh(t):void 0}listBindings(e={}){return this.controlPlane.database.query("SELECT * FROM source_bindings ORDER BY created_at DESC").all().map(Dh).filter((r)=>(!e.connectionId||r.connectionId===e.connectionId)&&(!e.projectId||r.projectId===e.projectId)&&(!e.status||r.status===e.status))}updateBinding(e,t,r){let n=this.getBinding(e);if(!n||n.version!==t)throw Error(`Source binding ${e} changed since version ${t}`);let i=this.getConnection(n.connectionId);if((!i||["disconnected","expired"].includes(i.status))&&(r.status==="active"||r.autoDeploy===!0))throw Error("Rotate or reconnect the source credential before enabling this binding");if(r.deployKeyId&&this.getDeployKey(r.deployKeyId)?.connectionId!==n.connectionId)throw Error("Deploy key does not belong to this connection");let a=this.now();if(this.controlPlane.database.run("UPDATE source_bindings SET default_branch=?, branch_rule=?, tag_rule=?, monorepo_root=?, include_paths=?, exclude_paths=?, submodules=?, clone_depth=?, deploy_key_id=?, auto_deploy=?, pull_request_previews=?, status=?, disabled_reason=?, version=version+1, updated_at=? WHERE id=? AND version=?",[r.defaultBranch?.trim()||n.defaultBranch,r.branchRule===void 0?n.branchRule??null:r.branchRule.trim()||null,r.tagRule===void 0?n.tagRule??null:r.tagRule.trim()||null,r.monorepoRoot===void 0?n.monorepoRoot:Ph(r.monorepoRoot),ur(r.includePaths===void 0?n.includePaths:ds(r.includePaths)),ur(r.excludePaths===void 0?n.excludePaths:ds(r.excludePaths)),r.submodules??n.submodules?1:0,r.cloneDepth===void 0?n.cloneDepth??null:r.cloneDepth,r.deployKeyId===void 0?n.deployKeyId??null:r.deployKeyId,r.autoDeploy??n.autoDeploy?1:0,r.pullRequestPreviews??n.pullRequestPreviews?1:0,r.status??n.status,r.disabledReason===void 0?n.disabledReason??null:r.disabledReason.slice(0,1000),a,e,t]).changes!==1)throw Error(`Source binding ${e} changed since version ${t}`);let d=this.getConnection(n.connectionId);return this.controlPlane.appendEvent({organizationId:d.organizationId,projectId:n.projectId,actorId:r.actorId,type:"source.binding.updated",payload:{bindingId:e,fromVersion:t,toVersion:t+1,status:r.status??n.status}}),this.getBinding(e)}createWebhook(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");let r=this.idFn(),n=this.now(),i=e.endpointToken??kd(24).toString("base64url"),a=e.secret??kd(32).toString("base64url"),s=[...new Set(e.events??["push","pull_request"])].filter((d)=>["push","pull_request"].includes(d));if(!s.length)throw Error("At least one supported webhook event is required");return this.run("INSERT INTO source_webhooks (id, connection_id, repository_id, repository_full_name, endpoint_token_hash, endpoint_token_ciphertext, secret_ciphertext, events, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?)",[r,e.connectionId,e.repositoryId??null,bd(e.repositoryFullName),On(i),this.encrypt(i),this.encrypt(a),ur(s),n,n]),this.controlPlane.appendEvent({organizationId:t.organizationId,type:"source.webhook.created",payload:{webhookId:r,connectionId:t.id,repository:e.repositoryFullName,events:s}}),{webhook:{...this.getWebhook(r),endpointToken:i},secret:a}}getWebhook(e){let t=this.controlPlane.database.query("SELECT * FROM source_webhooks WHERE id = ?").get(e);return t?Bd(t):void 0}getWebhookByEndpointToken(e){let t=this.controlPlane.database.query("SELECT * FROM source_webhooks WHERE endpoint_token_hash = ?").get(On(e));return t?Bd(t):void 0}getWebhookSecret(e){let t=this.controlPlane.database.query("SELECT secret_ciphertext FROM source_webhooks WHERE id = ?").get(e);if(!t)throw Error("Source webhook was not found");return this.decrypt(String(t.secret_ciphertext))}getWebhookEndpointToken(e){let t=this.controlPlane.database.query("SELECT endpoint_token_ciphertext FROM source_webhooks WHERE id = ?").get(e);if(!t?.endpoint_token_ciphertext)throw Error("Source webhook endpoint token is unavailable");return this.decrypt(String(t.endpoint_token_ciphertext))}listWebhooks(e){return this.controlPlane.database.query("SELECT * FROM source_webhooks WHERE connection_id = ? ORDER BY repository_full_name").all(e).map(Bd)}updateWebhookState(e,t){let r=this.getWebhook(e);if(!r)throw Error("Source webhook was not found");let n=this.now();this.run("UPDATE source_webhooks SET provider_webhook_id=COALESCE(?, provider_webhook_id), status=?, health_message=?, last_reconciled_at=COALESCE(?, last_reconciled_at), updated_at=? WHERE id=?",[t.providerWebhookId??null,t.status,t.healthMessage?.slice(0,1000)??null,t.reconciled?n:null,n,e]);let i=this.getConnection(r.connectionId);if(i)this.controlPlane.appendEvent({organizationId:i.organizationId,type:"source.webhook.updated",payload:{webhookId:e,connectionId:i.id,repository:r.repositoryFullName,status:t.status,reconciled:t.reconciled??!1,providerWebhookId:t.providerWebhookId??r.providerWebhookId??null}});return this.getWebhook(e)}getDeliveryByProviderId(e,t){let r=this.controlPlane.database.query("SELECT * FROM source_webhook_deliveries WHERE connection_id = ? AND provider_delivery_id = ?").get(e,t);return r?Jd(r):void 0}recordDelivery(e){let t=this.getDeliveryByProviderId(e.connectionId,e.providerDeliveryId);if(t)return{delivery:t,duplicate:!0};let r=this.idFn(),n=this.now();return this.controlPlane.database.transaction(()=>{this.run("INSERT INTO source_webhook_deliveries (id, connection_id, webhook_id, provider_delivery_id, event, action, commit_sha, signature_status, status, payload_summary, operation_id, error, received_at, processed_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[r,e.connectionId,e.webhookId,e.providerDeliveryId,e.event.slice(0,100),e.action?.slice(0,100)??null,e.commitSha?.slice(0,128)??null,e.signatureStatus,e.status,ur(e.payloadSummary??{}),e.operationId??null,e.error?.slice(0,2000)??null,n,["enqueued","ignored","rejected","failed"].includes(e.status)?n:null]),this.run("UPDATE source_webhooks SET last_delivery_at=?, updated_at=? WHERE id=?",[n,n,e.webhookId])})(),{delivery:this.getDeliveryByProviderId(e.connectionId,e.providerDeliveryId),duplicate:!1}}updateDelivery(e,t){this.run("UPDATE source_webhook_deliveries SET status=?, operation_id=?, error=?, processed_at=? WHERE id=?",[t.status,t.operationId??null,t.error?.slice(0,2000)??null,this.now(),e]);let r=this.controlPlane.database.query("SELECT * FROM source_webhook_deliveries WHERE id = ?").get(e);if(!r)throw Error("Source webhook delivery was not found");return Jd(r)}listDeliveries(e,t=100){return this.controlPlane.database.query("SELECT * FROM source_webhook_deliveries WHERE webhook_id = ? ORDER BY received_at DESC LIMIT ?").all(e,Math.min(500,Math.max(1,t))).map(Jd)}disconnectConnection(e,t){let r=this.getConnection(e);if(!r)throw Error("Source connection was not found");let n=this.listBindings({connectionId:e,status:"active"}),i=this.now();return this.controlPlane.database.transaction(()=>{this.run("UPDATE source_connections SET status='disconnected', credential_ciphertext=NULL, health_message='Disconnected by an administrator', version=version+1, updated_at=? WHERE id=?",[i,e]),this.run("UPDATE source_bindings SET status='disabled', auto_deploy=0, disabled_reason='Source connection was disconnected', version=version+1, updated_at=? WHERE connection_id=? AND status='active'",[i,e]),this.run("UPDATE source_webhooks SET status='disabled', health_message='Source connection was disconnected', updated_at=? WHERE connection_id=?",[i,e])})(),this.controlPlane.appendEvent({organizationId:r.organizationId,actorId:t,type:"source.connection.disconnected",level:"warning",payload:{connectionId:e,affectedBindingIds:n.map((a)=>a.id),affectedRepositories:n.map((a)=>a.repositoryFullName)}}),{connection:this.getConnection(e),affectedBindings:n}}}import{createSign as JE}from"node:crypto";class Si extends Error{status;retryAfterSeconds;constructor(e,t,r){super(e);this.status=t;this.retryAfterSeconds=r;this.name="SourceProviderError"}}var bh={repositories:!0,branches:!0,tags:!0,webhooks:!0,pullRequests:!0,tokenRefresh:!0,deployKeys:!0};function Xr(e){let t=Number(e??"1");return Number.isInteger(t)&&t>0?t:1}function qr(e){return Math.max(1,Math.min(100,e??50))}function Vt(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 oa(e){let t=new URL(e);if(t.username||t.password||t.protocol!=="https:")throw Error("Webhook endpoint must be credential-free HTTPS");return t.href}function kh(e){return Buffer.from(e).toString("base64url")}function TE(e,t){if(!e.appId||!e.privateKey)throw Error("GitHub App credentials require appId and privateKey");let r=kh(JSON.stringify({alg:"RS256",typ:"JWT"})),n=Math.floor(t.getTime()/1000)-30,i=kh(JSON.stringify({iat:n,exp:n+540,iss:e.appId})),a=JE("RSA-SHA256");return a.update(`${r}.${i}`),a.end(),`${r}.${i}.${a.sign(e.privateKey).toString("base64url")}`}class da{connection;credential;capabilities=bh;fetchFn;timeoutMs;nowFn;constructor(e,t,r={}){this.connection=e;this.credential=t;this.fetchFn=r.fetch??((n,i)=>globalThis.fetch(n,i)),this.timeoutMs=Math.max(100,r.timeoutMs??20000),this.nowFn=r.now??(()=>new Date)}async request(e,t={}){let r=new URL(`${this.apiRoot().replace(/\/$/,"")}/`),n=new URL(e.replace(/^\//,""),r);if(n.origin!==r.origin)throw Error("Provider pagination cannot leave the configured host");let i=new AbortController,a=setTimeout(()=>i.abort(),this.timeoutMs);try{let s=await this.fetchFn(n,{...t,redirect:"error",signal:i.signal,headers:{Accept:"application/json","User-Agent":"ts-cloud-source/1",...await this.authorization(),...t.headers}});if(!s.ok){let d=Number(s.headers.get("retry-after")??""),c=s.headers.get("x-request-id")??s.headers.get("x-github-request-id");throw new Si(`Source provider request failed (${s.status})${c?` [request ${c}]`:""}`,s.status,Number.isFinite(d)?d:void 0)}if(s.status===204)return{data:void 0,headers:s.headers};return{data:await s.json(),headers:s.headers}}catch(s){if(s instanceof Si)throw s;if(i.signal.aborted)throw new Si(`Source provider request exceeded ${this.timeoutMs}ms`);throw new Si(s instanceof Error?s.message.replace(/(?:token|password|secret)=[^\s&]+/gi,"$1=[REDACTED]"):"Source provider request failed")}finally{clearTimeout(a)}}async deleteWebhook(e,t){await this.request(this.webhookPath(e,t),{method:"DELETE"})}}class vh extends da{provider="github";installationToken;apiRoot(){return this.connection.host==="https://github.com"?"https://api.github.com":`${this.connection.host}/api/v3`}async authorization(){if(this.credential?.token)return{Authorization:`Bearer ${this.credential.token}`,"X-GitHub-Api-Version":"2022-11-28"};if(!this.credential?.installationId)return{};if(!this.installationToken||this.installationToken.expiresAt<this.nowFn().getTime()+60000){let e=TE(this.credential,this.nowFn()),t=this.apiRoot().replace(/\/$/,""),r=new AbortController,n=setTimeout(()=>r.abort(),this.timeoutMs);try{let i=await this.fetchFn(`${t}/app/installations/${encodeURIComponent(this.credential.installationId)}/access_tokens`,{method:"POST",signal:r.signal,redirect:"error",headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${e}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"ts-cloud-source/1"}});if(!i.ok)throw new Si(`GitHub App token refresh failed (${i.status})`,i.status);let a=await i.json();this.installationToken={value:a.token,expiresAt:new Date(a.expires_at).getTime()}}finally{clearTimeout(n)}}return{Authorization:`Bearer ${this.installationToken.value}`,"X-GitHub-Api-Version":"2022-11-28"}}async testConnection(){let e=this.credential?.installationId?"/installation/repositories?per_page=1":"/user",{data:t,headers:r}=await this.request(e);return{ok:!0,account:t.login??this.connection.owner,scopes:(r.get("x-oauth-scopes")??this.connection.grantedScopes.join(",")).split(",").map((n)=>n.trim()).filter(Boolean),message:"GitHub connection is healthy"}}async listRepositories(e={}){let t=qr(e.limit),r=Xr(e.cursor),n=this.credential?.installationId?`/installation/repositories?per_page=${t}&page=${r}`:`/user/repos?per_page=${t}&page=${r}&sort=updated`,{data:i}=await this.request(n),a=Array.isArray(i)?i:i.repositories;return{repositories:(e.search?a.filter((d)=>d.full_name.toLowerCase().includes(e.search.toLowerCase())):a).map((d)=>({providerRepositoryId:String(d.id),fullName:d.full_name,cloneUrl:d.clone_url,defaultBranch:d.default_branch||"main",visibility:d.visibility??(d.private?"private":"public"),archived:!!d.archived,metadata:{}})),nextCursor:a.length===t?String(r+1):void 0}}async refs(e,t,r={}){let n=qr(r.limit),i=Xr(r.cursor),{data:a}=await this.request(`/repos/${Vt(e)}/${t}?per_page=${n}&page=${i}`);return{refs:a.map((s)=>({name:s.name,commitSha:s.commit.sha,protected:s.protected})),nextCursor:a.length===n?String(i+1):void 0}}listBranches(e,t){return this.refs(e,"branches",t)}listTags(e,t){return this.refs(e,"tags",t)}webhookPath(e,t){return`/repos/${Vt(e)}/hooks${t?`/${encodeURIComponent(t)}`:""}`}hook(e){return{providerWebhookId:String(e.id),active:e.active,events:e.events,url:e.config.url??""}}async createWebhook(e,t){let{data:r}=await this.request(this.webhookPath(e),{method:"POST",body:JSON.stringify({name:"web",active:!0,events:t.events,config:{url:oa(t.url),content_type:"json",secret:t.secret,insecure_ssl:"0"}}),headers:{"Content-Type":"application/json"}});return this.hook(r)}async listWebhooks(e){let{data:t}=await this.request(this.webhookPath(e));return t.map((r)=>this.hook(r))}async updateWebhook(e,t,r){let{data:n}=await this.request(this.webhookPath(e,t),{method:"PATCH",body:JSON.stringify({active:!0,events:r.events,config:{url:oa(r.url),content_type:"json",secret:r.secret,insecure_ssl:"0"}}),headers:{"Content-Type":"application/json"}});return this.hook(n)}async setCommitStatus(e,t,r){await this.request(`/repos/${Vt(e)}/statuses/${encodeURIComponent(t)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({state:r.state,target_url:r.url,description:r.description.slice(0,140),context:r.context??"ts-cloud/preview"})})}}class Oh extends da{provider="gitlab";apiRoot(){return`${this.connection.host}/api/v4`}async authorization(){return this.credential?.token?{"PRIVATE-TOKEN":this.credential.token}:{}}async testConnection(){let{data:e}=await this.request("/user");return{ok:!0,account:e.username,scopes:this.connection.grantedScopes,message:"GitLab connection is healthy"}}async listRepositories(e={}){let t=qr(e.limit),r=Xr(e.cursor),n=e.search?`&search=${encodeURIComponent(e.search)}`:"",{data:i,headers:a}=await this.request(`/projects?membership=true&simple=true&order_by=last_activity_at&per_page=${t}&page=${r}${n}`);return{repositories:i.map((s)=>({providerRepositoryId:String(s.id),fullName:s.path_with_namespace,cloneUrl:s.http_url_to_repo,defaultBranch:s.default_branch??"main",visibility:s.visibility??"unknown",archived:!!s.archived,metadata:{}})),nextCursor:a.get("x-next-page")||void 0}}async refs(e,t,r={}){let n=qr(r.limit),i=Xr(r.cursor),{data:a,headers:s}=await this.request(`/projects/${encodeURIComponent(Vt(e))}/repository/${t}?per_page=${n}&page=${i}`);return{refs:a.map((d)=>({name:d.name,commitSha:d.commit.id,protected:d.protected})),nextCursor:s.get("x-next-page")||void 0}}listBranches(e,t){return this.refs(e,"branches",t)}listTags(e,t){return this.refs(e,"tags",t)}webhookPath(e,t){return`/projects/${encodeURIComponent(Vt(e))}/hooks${t?`/${encodeURIComponent(t)}`:""}`}hook(e){return{providerWebhookId:String(e.id),active:!0,events:[...e.push_events?["push"]:[],...e.merge_requests_events?["pull_request"]:[]],url:e.url}}body(e){return JSON.stringify({url:oa(e.url),token:e.secret,enable_ssl_verification:!0,push_events:e.events.includes("push"),merge_requests_events:e.events.includes("pull_request")})}async createWebhook(e,t){let{data:r}=await this.request(this.webhookPath(e),{method:"POST",body:this.body(t),headers:{"Content-Type":"application/json"}});return this.hook(r)}async listWebhooks(e){let{data:t}=await this.request(this.webhookPath(e));return t.map((r)=>this.hook(r))}async updateWebhook(e,t,r){let{data:n}=await this.request(this.webhookPath(e,t),{method:"PUT",body:this.body(r),headers:{"Content-Type":"application/json"}});return this.hook(n)}async setCommitStatus(e,t,r){let n=r.state==="failure"||r.state==="error"?"failed":r.state;await this.request(`/projects/${encodeURIComponent(Vt(e))}/statuses/${encodeURIComponent(t)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({state:n,target_url:r.url,description:r.description.slice(0,255),name:r.context??"ts-cloud/preview"})})}}class Bh extends da{provider="bitbucket";apiRoot(){return this.connection.host==="https://bitbucket.org"?"https://api.bitbucket.org/2.0":`${this.connection.host}/2.0`}async authorization(){return this.credential?.token?{Authorization:`Bearer ${this.credential.token}`}:{}}async testConnection(){let{data:e}=await this.request("/user");return{ok:!0,account:e.username??e.display_name,scopes:this.connection.grantedScopes,message:"Bitbucket connection is healthy"}}async listRepositories(e={}){if(!this.connection.owner)throw Error("Bitbucket repository discovery requires an owner/workspace");let t=Xr(e.cursor),r=qr(e.limit),n=e.search?`&q=name~%22${encodeURIComponent(e.search)}%22`:"",{data:i}=await this.request(`/repositories/${encodeURIComponent(this.connection.owner)}?pagelen=${r}&page=${t}${n}`);return{repositories:i.values.map((a)=>({providerRepositoryId:a.uuid,fullName:a.full_name,cloneUrl:a.links.clone.find((s)=>s.name==="https")?.href??a.links.clone[0]?.href??"",defaultBranch:a.mainbranch?.name??"main",visibility:a.is_private?"private":"public",archived:!1,metadata:{}})),nextCursor:i.next?String(t+1):void 0}}async refs(e,t,r={}){let n=Xr(r.cursor),i=qr(r.limit),{data:a}=await this.request(`/repositories/${Vt(e)}/refs/${t}?pagelen=${i}&page=${n}`);return{refs:a.values.map((s)=>({name:s.name,commitSha:s.target.hash})),nextCursor:a.next?String(n+1):void 0}}listBranches(e,t){return this.refs(e,"branches",t)}listTags(e,t){return this.refs(e,"tags",t)}webhookPath(e,t){return`/repositories/${Vt(e)}/hooks${t?`/${encodeURIComponent(t)}`:""}`}hook(e){return{providerWebhookId:e.uuid,active:e.active,events:e.events.map((t)=>t.replace("repo:push","push").replace("pullrequest:","pull_request:")),url:e.url}}body(e){return JSON.stringify({description:"ts-cloud deploy",url:oa(e.url),active:!0,events:e.events.map((t)=>t==="push"?"repo:push":t.replace("pull_request:","pullrequest:"))})}async createWebhook(e,t){let{data:r}=await this.request(this.webhookPath(e),{method:"POST",body:this.body(t),headers:{"Content-Type":"application/json"}});return this.hook(r)}async listWebhooks(e){let{data:t}=await this.request(this.webhookPath(e));return t.values.map((r)=>this.hook(r))}async updateWebhook(e,t,r){let{data:n}=await this.request(this.webhookPath(e,t),{method:"PUT",body:this.body(r),headers:{"Content-Type":"application/json"}});return this.hook(n)}async setCommitStatus(e,t,r){let n=r.state==="success"?"SUCCESSFUL":r.state==="pending"?"INPROGRESS":"FAILED";await this.request(`/repositories/${Vt(e)}/commit/${encodeURIComponent(t)}/statuses/build/ts-cloud-preview`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({state:n,key:"ts-cloud-preview",name:r.context??"ts-cloud/preview",url:r.url,description:r.description.slice(0,255)})})}}class Jh extends da{provider="gitea";capabilities={...bh,tokenRefresh:!1};apiRoot(){return`${this.connection.host}/api/v1`}async authorization(){return this.credential?.token?{Authorization:`token ${this.credential.token}`}:{}}async testConnection(){let{data:e}=await this.request("/user");return{ok:!0,account:e.login,scopes:this.connection.grantedScopes,message:"Gitea connection is healthy"}}async listRepositories(e={}){let t=Xr(e.cursor),r=qr(e.limit),n=e.search?`/repos/search?q=${encodeURIComponent(e.search)}&limit=${r}&page=${t}`:`/user/repos?limit=${r}&page=${t}`,{data:i,headers:a}=await this.request(n),s=Array.isArray(i)?i:i.data;return{repositories:s.map((d)=>({providerRepositoryId:String(d.id),fullName:d.full_name,cloneUrl:d.clone_url,defaultBranch:d.default_branch??"main",visibility:d.private?"private":"public",archived:!!d.archived,metadata:{}})),nextCursor:a.get("x-hasmore")==="true"||s.length===r?String(t+1):void 0}}async refs(e,t,r={}){let n=Xr(r.cursor),i=qr(r.limit),{data:a}=await this.request(`/repos/${Vt(e)}/${t}?limit=${i}&page=${n}`);return{refs:a.map((s)=>({name:s.name,commitSha:s.commit.id})),nextCursor:a.length===i?String(n+1):void 0}}listBranches(e,t){return this.refs(e,"branches",t)}listTags(e,t){return this.refs(e,"tags",t)}webhookPath(e,t){return`/repos/${Vt(e)}/hooks${t?`/${encodeURIComponent(t)}`:""}`}hook(e){return{providerWebhookId:String(e.id),active:e.active,events:e.events??[],url:e.config.url??""}}body(e){return JSON.stringify({type:"gitea",active:!0,events:e.events,config:{url:oa(e.url),content_type:"json",secret:e.secret,insecure_ssl:"0"}})}async createWebhook(e,t){let{data:r}=await this.request(this.webhookPath(e),{method:"POST",body:this.body(t),headers:{"Content-Type":"application/json"}});return this.hook(r)}async listWebhooks(e){let{data:t}=await this.request(this.webhookPath(e));return t.map((r)=>this.hook(r))}async updateWebhook(e,t,r){let{data:n}=await this.request(this.webhookPath(e,t),{method:"PATCH",body:this.body(r),headers:{"Content-Type":"application/json"}});return this.hook(n)}async setCommitStatus(e,t,r){await this.request(`/repos/${Vt(e)}/statuses/${encodeURIComponent(t)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({state:r.state,target_url:r.url,description:r.description.slice(0,140),context:r.context??"ts-cloud/preview"})})}}function en(e,t,r={}){switch(e.provider){case"github":return new vh(e,t,r);case"gitlab":return new Oh(e,t,r);case"bitbucket":return new Bh(e,t,r);case"gitea":return new Jh(e,t,r);default:throw Error(`${e.provider} uses bounded Git discovery instead of a hosted provider API`)}}import{createHmac as zE,timingSafeEqual as WE}from"node:crypto";function yt(e,t){if(e instanceof Headers)return e.get(t)??void 0;return Object.entries(e).find(([n])=>n.toLowerCase()===t.toLowerCase())?.[1]}function Th(e,t){let r=Buffer.from(e),n=Buffer.from(t);return r.length===n.length&&WE(r,n)}function jE(e,t){return zE("sha256",e).update(t).digest("hex")}function UE(e,t,r,n,i){if(e==="gitlab")return Th(yt(r,"x-gitlab-token")??"",t);let a=e==="github"?yt(r,"x-hub-signature-256"):e==="gitea"?yt(r,"x-gitea-signature"):yt(r,"x-hub-signature")??yt(r,"x-ts-cloud-signature");if(!a)return!1;if(e==="generic_https"||e==="generic_ssh"){let s=Number(yt(r,"x-ts-cloud-timestamp"));if(!Number.isFinite(s)||Math.abs(i.getTime()-s*1000)>300000)return!1}return Th(a.replace(/^sha256=/,""),jE(t,n))}function HE(e,t){return{github:["x-github-delivery"],gitlab:["x-gitlab-event-uuid","x-request-id"],bitbucket:["x-request-uuid"],gitea:["x-gitea-delivery"],generic_https:["x-ts-cloud-delivery"],generic_ssh:["x-ts-cloud-delivery"]}[e].map((n)=>yt(t,n)?.trim()).find(Boolean)}function tn(e){let t=String(e??"").trim().replace(/^\/+|\/+$/g,"");return/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(t)?t:""}function zd(e){return[...new Set(e.flatMap((t)=>{if(!t||typeof t!=="object")return[];let r=t;return[...r.added??[],...r.modified??[],...r.removed??[]].map(String)}).filter((t)=>t&&!t.includes("\x00")).slice(0,500))]}function NE(e,t,r){let n=e,i=t,a=r;if(n==="github"){let s=yt(i,"x-github-event"),d=tn(a.repository?.full_name);if(s==="push")return{event:"push",repository:d,ref:String(a.ref??""),branch:String(a.ref??"").replace(/^refs\/heads\//,""),tag:String(a.ref??"").startsWith("refs/tags/")?String(a.ref).replace(/^refs\/tags\//,""):void 0,commitSha:String(a.after??a.head_commit?.id??""),changedPaths:zd(a.commits??[]),deleted:a.deleted===!0||/^0{40,64}$/.test(String(a.after??""))};if(s==="pull_request")return{event:"pull_request",action:String(a.action??""),repository:d,branch:String(a.pull_request?.head?.ref??""),commitSha:String(a.pull_request?.head?.sha??""),changedPaths:[],pullRequestNumber:Number(a.number)||void 0,fork:tn(a.pull_request?.head?.repo?.full_name)!==d}}if(n==="gitlab"){let s=String(a.object_kind??"").toLowerCase(),d=tn(a.project?.path_with_namespace);if(s==="push"||s==="tag_push")return{event:"push",repository:d,ref:String(a.ref??""),branch:String(a.ref??"").replace(/^refs\/heads\//,""),tag:s==="tag_push"?String(a.ref??"").replace(/^refs\/tags\//,""):void 0,commitSha:String(a.checkout_sha??a.after??""),changedPaths:zd(a.commits??[]),deleted:/^0{40,64}$/.test(String(a.after??""))};if(s==="merge_request")return{event:"pull_request",action:String(a.object_attributes?.action??a.object_attributes?.state??""),repository:d,branch:String(a.object_attributes?.source_branch??""),commitSha:String(a.object_attributes?.last_commit?.id??""),changedPaths:[],pullRequestNumber:Number(a.object_attributes?.iid)||void 0,fork:a.object_attributes?.source_project_id!==a.object_attributes?.target_project_id}}if(n==="bitbucket"){let s=yt(i,"x-event-key")??"",d=tn(a.repository?.full_name);if(s==="repo:push"){let c=a.push?.changes?.[0]??{},o=c.new??c.old??{},g=c.new?.target??c.old?.target;return{event:"push",repository:d,ref:String(o.name??""),branch:o.type==="branch"?String(o.name):void 0,tag:o.type==="tag"?String(o.name):void 0,commitSha:String(g?.hash??""),changedPaths:[],deleted:c.closed===!0||c.new==null}}if(s.startsWith("pullrequest:"))return{event:"pull_request",action:s.replace("pullrequest:",""),repository:d,branch:String(a.pullrequest?.source?.branch?.name??""),commitSha:String(a.pullrequest?.source?.commit?.hash??""),changedPaths:[],pullRequestNumber:Number(a.pullrequest?.id)||void 0,fork:tn(a.pullrequest?.source?.repository?.full_name)!==d}}if(n==="gitea"){let s=yt(i,"x-gitea-event"),d=tn(a.repository?.full_name);if(s==="push")return{event:"push",repository:d,ref:String(a.ref??""),branch:String(a.ref??"").replace(/^refs\/heads\//,""),tag:String(a.ref??"").startsWith("refs/tags/")?String(a.ref).replace(/^refs\/tags\//,""):void 0,commitSha:String(a.after??""),changedPaths:zd(a.commits??[]),deleted:a.deleted===!0||/^0{40,64}$/.test(String(a.after??""))};if(s==="pull_request")return{event:"pull_request",action:String(a.action??""),repository:d,branch:String(a.pull_request?.head?.ref??""),commitSha:String(a.pull_request?.head?.sha??""),changedPaths:[],pullRequestNumber:Number(a.number)||void 0,fork:tn(a.pull_request?.head?.repo?.full_name)!==d}}if(n==="generic_https"||n==="generic_ssh"){if(a.event!=="push"&&a.event!=="pull_request")return;return{event:a.event,action:typeof a.action==="string"?a.action:void 0,repository:tn(a.repository),ref:typeof a.ref==="string"?a.ref:void 0,branch:typeof a.branch==="string"?a.branch:void 0,tag:typeof a.tag==="string"?a.tag:void 0,commitSha:String(a.commitSha??""),changedPaths:Array.isArray(a.changedPaths)?a.changedPaths.map(String).slice(0,500):[],pullRequestNumber:Number(a.pullRequestNumber)||void 0,fork:a.fork===!0,deleted:a.deleted===!0}}return}function _i(e,t){let r="^";for(let n=0;n<t.length;n++){let i=t[n];if(i==="*"&&t[n+1]==="*")r+=".*",n++;else if(i==="*")r+="[^/]*";else if(i==="?")r+="[^/]";else r+=i.replace(/[|\\{}()[\]^$+?.]/g,"\\$&")}return new RegExp(`${r}$`).test(e)}function FE(e,t){if(t.event==="pull_request")return e.pullRequestPreviews;if(!e.autoDeploy)return!1;if(t.tag)return!!e.tagRule&&_i(t.tag,e.tagRule);return _i(t.branch??"",e.branchRule??e.defaultBranch)}function VE(e,t){if(!t.length)return!0;return t.filter((n)=>!e.excludePaths.some((i)=>_i(n,i))).some((n)=>!e.includePaths.length||e.includePaths.some((i)=>_i(n,i)))}function zh(e,t){return yt(t,e==="github"?"x-github-event":e==="gitlab"?"x-gitlab-event":e==="bitbucket"?"x-event-key":e==="gitea"?"x-gitea-event":"x-ts-cloud-event")??"unknown"}function Jn(){return{accepted:!1,duplicate:!1,status:"rejected",operations:[],message:"Webhook unavailable"}}async function jh(e){if(e.rawBody.byteLength>2097152)return Jn();let t=e.sources.getWebhookByEndpointToken(e.endpointToken);if(!t||t.status==="disabled")return Jn();let r=e.sources.getConnection(t.connectionId);if(!r||r.status==="disconnected"||r.status==="expired")return Jn();let n=HE(r.provider,e.headers);if(!n||n.length>200)return Jn();if(!UE(r.provider,e.sources.getWebhookSecret(t.id),e.headers,e.rawBody,e.now??new Date))return e.sources.recordDelivery({connectionId:r.id,webhookId:t.id,providerDeliveryId:n,event:zh(r.provider,e.headers),signatureStatus:yt(e.headers,"x-hub-signature-256")||yt(e.headers,"x-gitlab-token")||yt(e.headers,"x-hub-signature")||yt(e.headers,"x-gitea-signature")?"invalid":"missing",status:"rejected",error:"Webhook signature verification failed"}),Jn();let a;try{a=JSON.parse(new TextDecoder().decode(e.rawBody))}catch{return Jn()}let s=NE(r.provider,e.headers,a);if(!s||!s.repository||!/^[a-f0-9]{7,64}$/i.test(s.commitSha))return e.sources.recordDelivery({connectionId:r.id,webhookId:t.id,providerDeliveryId:n,event:zh(r.provider,e.headers),signatureStatus:"verified",status:"rejected",error:"Unsupported or malformed source event"}),Jn();let d=e.sources.recordDelivery({connectionId:r.id,webhookId:t.id,providerDeliveryId:n,event:s.event,action:s.action,commitSha:s.commitSha,signatureStatus:"verified",status:"accepted",payloadSummary:{repository:s.repository,ref:s.ref??null,branch:s.branch??null,tag:s.tag??null,commitSha:s.commitSha,pullRequestNumber:s.pullRequestNumber??null,changedPathCount:s.changedPaths.length}});if(d.duplicate&&d.delivery.status!=="accepted")return{accepted:!0,duplicate:!0,status:"duplicate",operations:[],message:"Delivery already processed"};let c=new Wh(e.controlPlane),o=e.sources.listBindings({connectionId:r.id,status:"active"}).filter((R)=>{if(R.repositoryFullName.toLowerCase()!==s.repository.toLowerCase()||!VE(R,s.changedPaths))return!1;let E=R.resourceId?c.getDefinitionForResource(R.resourceId):void 0,y=s.event==="push"&&!!E?.branchRule&&!!s.branch&&_i(s.branch,E.branchRule);return FE(R,s)||y});if(!o.length)return e.sources.updateDelivery(d.delivery.id,{status:"ignored"}),{accepted:!0,duplicate:d.duplicate,status:"ignored",operations:[],message:"Verified event did not match an active deployment rule"};let g=new Be(e.controlPlane),h=new Set(["closed","merged","declined"]),_=o.flatMap((R)=>{if(s.event==="push"&&R.resourceId&&s.branch){let y=c.getDefinitionForResource(R.resourceId);if(y?.branchRule&&_i(s.branch,y.branchRule)){let $=c.findForBranch(y.id,s.repository,s.branch);if(s.deleted){if(!y.cleanupOnClose||!$||$.status==="destroyed")return[];let B=g.enqueue({projectId:R.projectId,environmentId:R.environmentId,resourceId:R.resourceId,kind:"preview.destroy",idempotencyKey:`preview:${$.id}:branch-delete:${n}`,correlationId:`preview:${$.id}`,input:{previewId:$.id,reason:"branch_deleted",source:{repository:s.repository,commitSha:s.commitSha,branch:s.branch}},lockKey:`preview:${$.id}`,providerKey:r.provider,maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;return c.transition($.id,"queued",{operationId:B.id}),[B]}let b=c.upsert({definitionId:y.id,sourceProvider:r.provider,repository:s.repository,branch:s.branch,commitSha:s.commitSha});if(!b.changed)return[];let z=b.created?"preview.create":"preview.update",C=g.enqueue({projectId:R.projectId,environmentId:R.environmentId,resourceId:R.resourceId,kind:z,idempotencyKey:`preview:${b.preview.id}:${s.commitSha}`,correlationId:`preview:${b.preview.id}`,input:{previewId:b.preview.id,source:{connectionId:r.id,bindingId:R.id,repository:s.repository,commitSha:s.commitSha,branch:s.branch,monorepoRoot:R.monorepoRoot,submodules:R.submodules,cloneDepth:R.cloneDepth??null}},lockKey:`preview:${b.preview.id}`,providerKey:r.provider,buildSlot:!0,maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;return c.transition(b.preview.id,"queued",{operationId:C.id}),[C]}}if(s.event==="pull_request"&&R.resourceId&&s.pullRequestNumber){let y=c.getDefinitionForResource(R.resourceId);if(y){let $=h.has(String(s.action??"").toLowerCase()),b=c.findForPullRequest(y.id,s.repository,s.pullRequestNumber);if($){if(!y.cleanupOnClose||!b||b.status==="destroyed")return[];let z=g.enqueue({projectId:R.projectId,environmentId:R.environmentId,resourceId:R.resourceId,kind:"preview.destroy",idempotencyKey:`preview:${b.id}:destroy:${n}`,correlationId:`preview:${b.id}`,input:{previewId:b.id,reason:"pull_request_closed",source:{repository:s.repository,commitSha:s.commitSha,branch:s.branch??null,pullRequestNumber:s.pullRequestNumber}},lockKey:`preview:${b.id}`,providerKey:r.provider,maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;return c.transition(b.id,"queued",{operationId:z.id}),[z]}try{let z=c.upsert({definitionId:y.id,sourceProvider:r.provider,repository:s.repository,branch:s.branch??`pr-${s.pullRequestNumber}`,pullRequestNumber:s.pullRequestNumber,fork:s.fork,commitSha:s.commitSha});if(!z.changed)return[];let C=z.created?"preview.create":"preview.update",B=g.enqueue({projectId:R.projectId,environmentId:R.environmentId,resourceId:R.resourceId,kind:C,idempotencyKey:`preview:${z.preview.id}:${s.commitSha}`,correlationId:`preview:${z.preview.id}`,input:{previewId:z.preview.id,source:{connectionId:r.id,bindingId:R.id,repository:s.repository,commitSha:s.commitSha,branch:s.branch??null,pullRequestNumber:s.pullRequestNumber,fork:!!s.fork,monorepoRoot:R.monorepoRoot,submodules:R.submodules,cloneDepth:R.cloneDepth??null},inheritedSecretNames:z.inheritedSecrets},lockKey:`preview:${z.preview.id}`,providerKey:r.provider,buildSlot:!0,maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;return c.transition(z.preview.id,"queued",{operationId:B.id}),[B]}catch(z){return e.controlPlane.appendEvent({projectId:R.projectId,resourceId:R.resourceId,type:"preview.rejected",level:"warning",payload:{repository:s.repository,pullRequestNumber:s.pullRequestNumber,fork:!!s.fork,reason:z instanceof Error?z.message:String(z)}}),[]}}}let E=s.event==="pull_request"?"deploy.preview":"deploy.source";return[g.enqueue({projectId:R.projectId,environmentId:R.environmentId,resourceId:R.resourceId,kind:E,idempotencyKey:`source:${r.id}:${n}:${R.id}:${s.commitSha}`,correlationId:`source:${n}`,input:{source:{connectionId:r.id,bindingId:R.id,repository:s.repository,commitSha:s.commitSha,branch:s.branch??null,tag:s.tag??null,monorepoRoot:R.monorepoRoot,submodules:R.submodules,cloneDepth:R.cloneDepth??null},preview:s.event==="pull_request"?{number:s.pullRequestNumber??null,action:s.action??null}:null},lockKey:R.resourceId?`resource:${R.resourceId}`:`environment:${R.environmentId??R.projectId}`,providerKey:r.provider,buildSlot:!0,maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:s.event==="pull_request"?14:90}).operation]});if(!_.length)return e.sources.updateDelivery(d.delivery.id,{status:"ignored"}),{accepted:!0,duplicate:d.duplicate,status:"ignored",operations:[],message:"Verified event required no preview lifecycle change"};return e.sources.updateDelivery(d.delivery.id,{status:"enqueued",operationId:_[0]?.id}),e.controlPlane.appendEvent({organizationId:r.organizationId,projectId:o[0]?.projectId,operationId:_[0]?.id,type:"source.webhook.enqueued",payload:{webhookId:t.id,deliveryId:d.delivery.id,repository:s.repository,commitSha:s.commitSha,operationIds:_.map((R)=>R.id)}}),{accepted:!0,duplicate:d.duplicate,status:"enqueued",operations:_,message:`${_.length} deployment operation${_.length===1?"":"s"} enqueued`}}function Ri(e,t){if(!t.endpointToken)throw Error("The webhook endpoint token is only available at creation time");let r=new URL(e);if(r.protocol!=="https:"&&!["localhost","127.0.0.1","::1"].includes(r.hostname))throw Error("Webhook base URL must use HTTPS");return new URL(`/api/source/webhooks/${encodeURIComponent(t.endpointToken)}`,r).href}import{chmodSync as Uh,mkdtempSync as LE,rmSync as xE,writeFileSync as Hh}from"node:fs";import{tmpdir as ME}from"node:os";import{join as cs,resolve as QE}from"node:path";function Fh(e,t){let r=e.trim();if(/\r|\n|\0/.test(r))throw Error("Git remote contains control characters");if(r.startsWith("https://")){let i=new URL(r);if(i.username||i.password||i.search||i.hash)throw Error("HTTPS Git remotes cannot contain credentials, queries, or fragments");return i.href}let n=r.startsWith("ssh://")?new URL(r).hostname:r.match(/^git@([A-Za-z0-9.-]+):/)?.[1];if(!n)throw Error("Git remote must use credential-free HTTPS or SSH");if(!t||t.host.toLowerCase()!==n.toLowerCase())throw Error("SSH Git remote requires a deploy key with a pinned key for the same host");return r}function GE(e,t,r){let n=e.replaceAll(t,"[REMOTE]").slice(0,4000);for(let i of[r?.token,r?.privateKey])if(i)n=n.replaceAll(i,"[REDACTED]");return n}function ZE(e){let t={PATH:process.env.PATH??"/usr/local/bin:/usr/bin:/bin",HOME:"/nonexistent",GIT_TERMINAL_PROMPT:"0",GIT_CONFIG_NOSYSTEM:"1",GIT_OPTIONAL_LOCKS:"0"},r;if(e.credential?.token){let n=e.credential.username??"oauth2";t.GIT_CONFIG_COUNT="1",t.GIT_CONFIG_KEY_0="http.extraHeader",t.GIT_CONFIG_VALUE_0=`Authorization: Basic ${Buffer.from(`${n}:${e.credential.token}`).toString("base64")}`}if(e.deployKey){r=LE(cs(ME(),"ts-cloud-git-transport-"));let n=cs(r,"key"),i=cs(r,"known_hosts");Hh(n,e.deployKey.privateKey,{mode:384}),Hh(i,`${e.deployKey.host} ${e.deployKey.hostKey}
21
+ `,{mode:384}),Uh(n,384),Uh(i,384),t.GIT_SSH_COMMAND=`ssh -i ${n} -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes -o UserKnownHostsFile=${i} -o GlobalKnownHostsFile=/dev/null -o BatchMode=yes`}return{env:t,cleanup:()=>{if(r)xE(r,{recursive:!0,force:!0})}}}async function Tn(e,t,r){let n=ZE(r),i=Bun.spawn([r.executable??"git",...e],{stdout:"pipe",stderr:"pipe",env:n.env}),a=Math.max(100,r.timeoutMs??120000),s,d=new Promise((c,o)=>{s=setTimeout(()=>{i.kill(),o(Error(`Git operation exceeded ${a}ms`))},a)});try{let c=Promise.all([i.exited,new Response(i.stdout).text(),new Response(i.stderr).text()]),[o,g,h]=await Promise.race([c,d]);if(o!==0)throw Error(GE(h||`Git exited with ${o}`,t,r.credential));return g}finally{if(s)clearTimeout(s);n.cleanup()}}function Nh(e,t){let r=new Map;for(let n of e.split(`
22
+ `)){let i=n.trim().match(/^([a-f0-9]{40,64})\s+(.+)$/i);if(!i||!i[2].startsWith(t)||i[2].endsWith("^{}"))continue;let a=i[2].slice(t.length);r.set(a,{name:a,commitSha:i[1]})}return[...r.values()].sort((n,i)=>n.name.localeCompare(i.name))}async function Wd(e,t={}){let r=Fh(e,t.deployKey),n=await Tn(["ls-remote","--heads","--tags","--",r],r,t);return{branches:Nh(n,"refs/heads/"),tags:Nh(n,"refs/tags/")}}async function jd(e,t={}){let r=Fh(e.remote,t.deployKey),n=QE(e.destination),i=e.ref?.trim()||e.binding.defaultBranch;if(!/^[A-Za-z0-9._/-]{1,255}$/.test(i)||i.startsWith("-")||i.includes(".."))throw Error("Git ref contains unsupported characters");let a=["clone","--no-tags","--single-branch","--branch",i],s=[...new Set(e.sparsePaths??[])];if(s.some((c)=>!c||c.startsWith("/")||c.split("/").includes("..")||/[\0\r\n]/.test(c)))throw Error("Sparse checkout paths must stay inside the repository");if(s.length)a.push("--filter=blob:none","--no-checkout");if(e.binding.cloneDepth)a.push("--depth",String(e.binding.cloneDepth));if(e.binding.submodules)a.push("--recurse-submodules","--shallow-submodules");if(a.push("--",r,n),await Tn(a,r,t),s.length)await Tn(["-C",n,"sparse-checkout","set","--cone","--",...s],r,t),await Tn(["-C",n,"checkout","--force"],r,t);if(e.commitSha){if(!/^[a-f0-9]{40,64}$/i.test(e.commitSha))throw Error("Expected source commit must be an immutable 40-64 character SHA");await Tn(["-C",n,"fetch","--no-tags","--depth","1","origin",e.commitSha],r,t),await Tn(["-C",n,"checkout","--detach","--force",e.commitSha],r,t)}let d=(await Tn(["-C",n,"rev-parse","HEAD"],r,t)).trim();if(!/^[a-f0-9]{40,64}$/i.test(d))throw Error("Git clone did not produce a valid commit SHA");if(e.commitSha&&d.toLowerCase()!==e.commitSha.toLowerCase())throw Error(`Git checkout resolved ${d} instead of the requested immutable commit`);return{directory:e.binding.monorepoRoot==="."?n:cs(n,e.binding.monorepoRoot),commitSha:d}}function ca(e){return["github","gitlab","bitbucket","gitea"].includes(e)}async function Ud(e,t,r){let n=e.getConnection(t);if(!n||["disconnected","expired"].includes(n.status))throw Error("Active source connection was not found");try{if(ca(n.provider)){let s=await en(n,e.getCredential(n.id)).testConnection();return e.updateHealth(n.id,{status:s.ok?"healthy":"degraded",message:s.message,tested:!0,grantedScopes:s.scopes})}let i=r?e.getRepository(r):e.listRepositories(n.id,void 0,1)[0];if(!i)return e.updateHealth(n.id,{status:"degraded",message:"Add a repository URL before testing this generic connection.",tested:!0});let a=n.provider==="generic_ssh"?e.listBindings({connectionId:n.id}).map((s)=>s.deployKeyId).filter(Boolean).map((s)=>e.getDeployKey(s)).find(Boolean):void 0;return await Wd(i.cloneUrl,{credential:e.getCredential(n.id),deployKey:a?{...a,privateKey:e.getDeployPrivateKey(a.id)}:void 0}),e.updateHealth(n.id,{status:"healthy",message:"Git repository access is healthy.",tested:!0})}catch(i){return e.updateHealth(n.id,{status:"degraded",message:i instanceof Error?i.message:"Connection test failed",tested:!0})}}async function ls(e,t,r={}){let n=e.getConnection(t);if(!n||!ca(n.provider)||["disconnected","expired"].includes(n.status))throw Error("A hosted active source connection is required for repository discovery");let i=en(n,e.getCredential(n.id)),a=[],s;for(let d=0;d<Math.min(20,Math.max(1,r.maxPages??10));d++){let c=await i.listRepositories({cursor:s,search:r.search,limit:100});for(let o of c.repositories)a.push(e.upsertRepository({connectionId:n.id,...o}));if(s=c.nextCursor,!s)break}return e.updateHealth(n.id,{status:"healthy",message:`${a.length} repositories synchronized.`,synced:!0}),a}async function gs(e,t){let r=e.getConnection(t.connectionId);if(!r||["disconnected","expired"].includes(r.status))throw Error("Active source connection was not found");if(ca(r.provider)){let d=en(r,e.getCredential(r.id));return t.type==="tags"?d.listTags(t.repository,t):d.listBranches(t.repository,t)}let n=t.repositoryId?e.getRepository(t.repositoryId):e.listRepositories(r.id).find((d)=>d.fullName===t.repository);if(!n||n.connectionId!==r.id)throw Error("Generic repository metadata was not found");let i=t.deployKeyId?e.getDeployKey(t.deployKeyId):void 0;if(i&&i.connectionId!==r.id)throw Error("Deploy key does not belong to this connection");let a=await Wd(n.cloneUrl,{credential:e.getCredential(r.id),deployKey:i?{...i,privateKey:e.getDeployPrivateKey(i.id)}:void 0});return{refs:(t.type==="tags"?a.tags:a.branches).slice(0,Math.min(500,t.limit??100))}}async function la(e,t,r){let n=e.getWebhook(t),i=n?e.getConnection(n.connectionId):void 0;if(!n||!i||["disconnected","expired"].includes(i.status))throw Error("Active source webhook was not found");let a=Ri(r,{...n,endpointToken:e.getWebhookEndpointToken(n.id)});if(!ca(i.provider))return e.updateWebhookState(n.id,{status:"healthy",healthMessage:"Manual webhook endpoint is ready.",reconciled:!0});try{let s=en(i,e.getCredential(i.id)),d=e.getWebhookSecret(n.id),c=n.providerWebhookId?await s.updateWebhook(n.repositoryFullName,n.providerWebhookId,{url:a,secret:d,events:n.events}):await s.createWebhook(n.repositoryFullName,{url:a,secret:d,events:n.events});return e.updateWebhookState(n.id,{providerWebhookId:c.providerWebhookId,status:c.active?"healthy":"degraded",healthMessage:c.active?"Provider webhook is synchronized.":"Provider webhook exists but is inactive.",reconciled:!0})}catch(s){return e.updateWebhookState(n.id,{status:"degraded",healthMessage:s instanceof Error?s.message:"Webhook reconciliation failed",reconciled:!0})}}async function Vh(e,t){let r=e.getWebhook(t),n=r?e.getConnection(r.connectionId):void 0;if(!r||!n)throw Error("Source webhook was not found");if(ca(n.provider)&&r.providerWebhookId&&!["disconnected","expired"].includes(n.status))await en(n,e.getCredential(n.id)).deleteWebhook(r.repositoryFullName,r.providerWebhookId);return e.updateWebhookState(r.id,{status:"disabled",healthMessage:"Webhook disabled."})}var us="1.6.0";function Hd(){let e={type:"object",required:["error"],properties:{error:{type:"object",required:["code","message","requestId"],properties:{code:{type:"string"},message:{type:"string"},requestId:{type:"string",format:"uuid"},details:{}}}}},t=(n)=>({type:"object",required:["data","page","requestId"],properties:{data:{type:"array",items:n},page:{type:"object",required:["hasMore"],properties:{nextCursor:{type:"string"},hasMore:{type:"boolean"}}},requestId:{type:"string",format:"uuid"}}}),r=(n)=>({"200":{description:"A stable cursor page.",content:{"application/json":{schema:t(n)}}},default:{$ref:"#/components/responses/Error"}});return{openapi:"3.1.0",info:{title:"ts-cloud API",version:us,description:"Additive changes are released within v1. Breaking request or response changes require a new URL version."},servers:[{url:"/"}],security:[{bearerAuth:[]}],paths:{...Lh(),"/api/v1/projects":{get:{operationId:"listProjects",summary:"List accessible projects",parameters:[{$ref:"#/components/parameters/Limit"},{$ref:"#/components/parameters/Cursor"}],responses:r({$ref:"#/components/schemas/Project"})}},"/api/v1/projects/{projectId}/environments":{get:{operationId:"listEnvironments",summary:"List accessible project environments",parameters:[{$ref:"#/components/parameters/ProjectId"},{$ref:"#/components/parameters/Limit"},{$ref:"#/components/parameters/Cursor"}],responses:r({$ref:"#/components/schemas/Environment"})}},"/api/v1/services":{get:{operationId:"listServices",summary:"List accessible services",parameters:[{name:"projectId",in:"query",required:!0,schema:{type:"string"}},{name:"environmentId",in:"query",schema:{type:"string"}},{$ref:"#/components/parameters/Limit"},{$ref:"#/components/parameters/Cursor"}],responses:r({$ref:"#/components/schemas/Service"})}},"/api/v1/source/connections":{get:{operationId:"listSourceConnections",summary:"List safe Git connection metadata",parameters:[{$ref:"#/components/parameters/Limit"},{$ref:"#/components/parameters/Cursor"}],responses:r({$ref:"#/components/schemas/SourceConnection"})},post:{operationId:"createSourceConnection",summary:"Create an encrypted Git connection",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["provider","name","host"],properties:{provider:{type:"string",enum:["github","gitlab","bitbucket","gitea","generic_https","generic_ssh"]},name:{type:"string"},host:{type:"string",format:"uri"},token:{type:"string",writeOnly:!0},repositoryFullName:{type:"string"},repositoryUrl:{type:"string"}}}}}},responses:{"201":{description:"Encrypted connection created."},default:{$ref:"#/components/responses/Error"}}},delete:{operationId:"disconnectSourceConnection",summary:"Preview or safely disconnect a Git connection",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["id"],properties:{id:{type:"string"},preview:{type:"boolean"}}}}}},responses:{"200":{description:"Impact preview or disconnected connection."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/source/repositories":{get:{operationId:"listSourceRepositories",summary:"List or synchronize granted repositories",parameters:[{name:"connectionId",in:"query",required:!0,schema:{type:"string"}},{name:"sync",in:"query",schema:{type:"boolean"}},{name:"search",in:"query",schema:{type:"string"}},{$ref:"#/components/parameters/Limit"},{$ref:"#/components/parameters/Cursor"}],responses:r({$ref:"#/components/schemas/SourceRepository"})}},"/api/v1/source/refs":{get:{operationId:"listSourceRefs",summary:"List repository branches or tags",parameters:[{name:"connectionId",in:"query",required:!0,schema:{type:"string"}},{name:"repository",in:"query",required:!0,schema:{type:"string"}},{name:"repositoryId",in:"query",schema:{type:"string"}},{name:"type",in:"query",schema:{type:"string",enum:["branches","tags"]}}],responses:{"200":{description:"Provider reference page."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/source/bindings":{post:{operationId:"createSourceBinding",summary:"Bind a repository to an application",requestBody:{required:!0,content:{"application/json":{schema:{$ref:"#/components/schemas/SourceBindingRequest"}}}},responses:{"201":{description:"Source binding created."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/source/webhooks":{post:{operationId:"createSourceWebhook",summary:"Create and optionally reconcile a signed webhook",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["connectionId","repositoryFullName","baseUrl"],properties:{connectionId:{type:"string"},repositoryId:{type:"string"},repositoryFullName:{type:"string"},baseUrl:{type:"string",format:"uri"},events:{type:"array",items:{type:"string",enum:["push","pull_request"]}},reconcile:{type:"boolean"}}}}}},responses:{"201":{description:"Webhook endpoint created; endpoint is revealed once."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/application-detections":{post:{operationId:"detectApplication",summary:"Detect bounded application build candidates",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["files"],properties:{files:{type:"array",maxItems:1e4,items:{$ref:"#/components/schemas/DetectionFile"}}}}}}},responses:{"200":{description:"Ranked detection candidates with evidence."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/application-plans":{post:{operationId:"planApplication",summary:"Validate and normalize an application manifest",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["draft"],properties:{draft:{$ref:"#/components/schemas/ApplicationInput"},suppliedSecretNames:{type:"array",uniqueItems:!0,items:{type:"string"}}}}}}},responses:{"200":{description:"Validated plan, config patch, capabilities, costs, and missing secret names."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/application-drafts":{get:{operationId:"listApplicationDrafts",summary:"List resumable secret-free drafts",parameters:[{name:"projectId",in:"query",required:!0,schema:{type:"string"}},{$ref:"#/components/parameters/Limit"},{$ref:"#/components/parameters/Cursor"}],responses:r({$ref:"#/components/schemas/ApplicationDraft"})},post:{operationId:"createApplicationDraft",summary:"Create a resumable application draft",requestBody:{required:!0,content:{"application/json":{schema:{$ref:"#/components/schemas/ApplicationDraftCreateRequest"}}}},responses:{"201":{description:"Draft created."},default:{$ref:"#/components/responses/Error"}}},patch:{operationId:"updateApplicationDraft",summary:"Optimistically update a draft",requestBody:{required:!0,content:{"application/json":{schema:{allOf:[{$ref:"#/components/schemas/ApplicationDraftCreateRequest"},{type:"object",required:["id","version","step"],properties:{id:{type:"string"},version:{type:"integer",minimum:1}}}]}}}},responses:{"200":{description:"Updated draft."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/applications":{post:{operationId:"createApplication",summary:"Confirm and queue an application plan",parameters:[{name:"Idempotency-Key",in:"header",required:!0,schema:{type:"string",minLength:8,maxLength:128}}],requestBody:{required:!0,content:{"application/json":{schema:{type:"object",additionalProperties:!1,required:["draftId","version","confirmEnvironment"],properties:{draftId:{type:"string"},version:{type:"integer",minimum:1},confirmEnvironment:{type:"string",description:"Exact target environment slug."}}}}}},responses:{"202":{description:"Application operation queued; identical requests replay safely."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/application-artifacts":{post:{operationId:"uploadApplicationArtifact",summary:"Inspect and store a bounded ZIP or TAR source artifact",parameters:[{name:"X-Project-Id",in:"header",required:!0,schema:{type:"string"}},{name:"X-Artifact-Filename",in:"header",required:!0,schema:{type:"string"}}],requestBody:{required:!0,content:{"application/octet-stream":{schema:{type:"string",format:"binary",maxLength:104857600}}}},responses:{"201":{description:"Deduplicated artifact metadata; archive contents are never executed."},"413":{$ref:"#/components/responses/Error"},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/registry-connections":{get:{operationId:"listRegistryConnections",summary:"List safe private-registry metadata",parameters:[{$ref:"#/components/parameters/Limit"},{$ref:"#/components/parameters/Cursor"}],responses:r({$ref:"#/components/schemas/RegistryConnection"})},post:{operationId:"createRegistryConnection",summary:"Create an encrypted private-registry connection",requestBody:{required:!0,content:{"application/json":{schema:{$ref:"#/components/schemas/RegistryConnectionRequest"}}}},responses:{"201":{description:"Encrypted registry connection created."},default:{$ref:"#/components/responses/Error"}}},patch:{operationId:"updateRegistryConnection",summary:"Test access or rotate write-only credentials",requestBody:{required:!0,content:{"application/json":{schema:{allOf:[{$ref:"#/components/schemas/RegistryConnectionRequest"},{type:"object",required:["id","action"],properties:{id:{type:"string"},action:{type:"string",enum:["test","rotate"]},image:{type:"string"}}}]}}}},responses:{"200":{description:"Safe connection health metadata."},default:{$ref:"#/components/responses/Error"}}},delete:{operationId:"disconnectRegistryConnection",summary:"Disconnect and erase registry credentials",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",additionalProperties:!1,required:["id"],properties:{id:{type:"string"}}}}}},responses:{"200":{description:"Credentials erased and connection disconnected."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/queue":{get:{operationId:"listQueue",summary:"List authorized durable operations and blocking metadata",parameters:[{name:"projectId",in:"query",schema:{type:"string"}},{name:"state",in:"query",schema:{type:"string",enum:["queued","running","succeeded","failed","cancelled","timed_out"]}},{$ref:"#/components/parameters/Limit"},{$ref:"#/components/parameters/Cursor"}],responses:r({$ref:"#/components/schemas/QueueOperation"})}},"/api/v1/preview-definitions":{get:{operationId:"listPreviewDefinitions",summary:"List preview policies",responses:r({type:"object"})},post:{operationId:"createPreviewDefinition",summary:"Configure bounded preview policy",responses:{"200":{description:"Preview definition created."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/previews":{get:{operationId:"listPreviews",summary:"List authorized persistent previews",responses:r({type:"object"})},post:{operationId:"createPreview",summary:"Create or update one immutable preview identity",responses:{"200":{description:"Preview deployment queued."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/previews/{previewId}/destroy":{post:{operationId:"destroyPreview",summary:"Confirm tagged preview teardown",responses:{"200":{description:"Teardown queued."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/previews/{previewId}/extend":{post:{operationId:"extendPreview",summary:"Extend preview TTL",responses:{"200":{description:"Expiry extended."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/previews/{previewId}/rebuild":{post:{operationId:"rebuildPreview",summary:"Rebuild the exact recorded commit",responses:{"200":{description:"Rebuild queued."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/previews/cleanup":{post:{operationId:"cleanupPreviews",summary:"Dry-run or queue TTL/keep-count teardown",responses:{"200":{description:"Cleanup plan or operations."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/compose-templates":{get:{operationId:"listComposeTemplates",summary:"List pinned verified application templates",responses:r({type:"object"})}},"/api/v1/compose-applications":{get:{operationId:"listComposeApplications",summary:"List authorized multi-service applications",responses:r({type:"object"})},post:{operationId:"createComposeApplication",summary:"Import Compose or materialize a template",responses:{"200":{description:"Editable normalized application."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/compose-applications/preview":{post:{operationId:"previewComposeApplication",summary:"Parse and diagnose Compose without mutation",responses:{"200":{description:"Normalized preview and actionable diagnostics."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/compose-applications/{applicationId}/services":{get:{operationId:"listComposeServices",summary:"Inspect per-service desired and observed state",responses:{"200":{description:"Service topology and status."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/compose-applications/{applicationId}/{action}":{post:{operationId:"operateComposeApplication",summary:"Deploy, redeploy, start, stop, scale, or delete through the durable queue",responses:{"200":{description:"Scoped operation queued."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/release-artifacts":{post:{operationId:"createReleaseArtifact",summary:"Register a verified content-addressed artifact",responses:{"200":{description:"Artifact identity registered."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/releases":{get:{operationId:"listReleases",summary:"List unified authorized release history",responses:r({type:"object"})},post:{operationId:"createRelease",summary:"Create an immutable release from an existing artifact",responses:{"200":{description:"Release record created."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/releases/capabilities":{get:{operationId:"getReleaseCapabilities",summary:"Explain supported strategies, capacity, cost, and rollback",responses:{"200":{description:"Provider-aware strategy capabilities."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/releases/{releaseId}":{get:{operationId:"getRelease",summary:"Inspect provenance, approvals, health, and transitions",responses:{"200":{description:"Release detail."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/releases/{releaseId}/{action}":{post:{operationId:"operateRelease",summary:"Promote, approve, activate, roll back, report health, or pin",responses:{"200":{description:"Release lifecycle updated."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/queue/settings":{get:{operationId:"getQueueSettings",summary:"Get effective concurrency limits",responses:{"200":{description:"Queue concurrency settings."},default:{$ref:"#/components/responses/Error"}}},patch:{operationId:"updateQueueSettings",summary:"Confirm and audit production concurrency changes",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",additionalProperties:!1,required:["confirm","concurrency"],properties:{confirm:{const:"update queue limits"},concurrency:{$ref:"#/components/schemas/QueueConcurrency"}}}}}},responses:{"200":{description:"Updated effective limits."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/queue/history":{delete:{operationId:"clearQueueHistory",summary:"Clear terminal jobs whose retention has elapsed",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",additionalProperties:!1,required:["confirm"],properties:{confirm:{const:"clear completed"},before:{type:"string",format:"date-time"},projectId:{type:"string"}}}}}},responses:{"200":{description:"Eligible history cleared with an audit event."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/operations/{operationId}/logs":{get:{operationId:"listOperationLogs",summary:"Resume ordered sanitized operation logs from a cursor",parameters:[{$ref:"#/components/parameters/OperationId"},{name:"after",in:"query",schema:{type:"integer",minimum:0}},{$ref:"#/components/parameters/Limit"}],responses:{"200":{description:"Ordered log chunks and next cursor."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/operations/{operationId}/logs/stream":{get:{operationId:"streamOperationLogs",summary:"Stream authorized operation logs with Last-Event-ID resume",parameters:[{$ref:"#/components/parameters/OperationId"},{name:"Last-Event-ID",in:"header",schema:{type:"integer",minimum:0}}],responses:{"200":{description:"Server-sent log and completion events.",content:{"text/event-stream":{schema:{type:"string"}}}},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/operations/{operationId}/cancel":{post:{operationId:"cancelOperation",summary:"Cancel queued work or request cooperative running cancellation",parameters:[{$ref:"#/components/parameters/OperationId"}],requestBody:{content:{"application/json":{schema:{type:"object"}}}},responses:{"200":{description:"Cancellation state recorded."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/operations/{operationId}/retry":{post:{operationId:"retryOperation",summary:"Retry an allow-listed failure class within the attempt limit",parameters:[{$ref:"#/components/parameters/OperationId"}],requestBody:{required:!0,content:{"application/json":{schema:{type:"object",additionalProperties:!1,required:["errorClass"],properties:{errorClass:{type:"string"},delayMs:{type:"integer",minimum:0}}}}}},responses:{"200":{description:"Retry queued."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/deployments":{post:{operationId:"createDeployment",summary:"Queue a deployment",parameters:[{name:"Idempotency-Key",in:"header",required:!0,schema:{type:"string",minLength:8,maxLength:128}}],requestBody:{required:!0,content:{"application/json":{schema:{$ref:"#/components/schemas/DeploymentRequest"}}}},responses:{"202":{description:"Queued operation.",content:{"application/json":{schema:{$ref:"#/components/schemas/OperationResponse"}}}},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/operations":{get:{operationId:"listOperations",summary:"List scoped operations",parameters:[{name:"projectId",in:"query",schema:{type:"string"}},{$ref:"#/components/parameters/Limit"},{$ref:"#/components/parameters/Cursor"}],responses:r({$ref:"#/components/schemas/Operation"})}},"/api/v1/events":{get:{operationId:"listEvents",summary:"List scoped audit events",parameters:[{name:"projectId",in:"query",schema:{type:"string"}},{name:"after",in:"query",schema:{type:"integer",minimum:0}},{$ref:"#/components/parameters/Limit"}],responses:r({$ref:"#/components/schemas/Event"})}},"/api/v1/events/stream":{get:{operationId:"streamEvents",summary:"Stream scoped audit events",responses:{"200":{description:"Authenticated server-sent event stream.",content:{"text/event-stream":{schema:{type:"string"}}}},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/openapi.json":{get:{operationId:"getOpenApi",summary:"Get the OpenAPI contract",security:[],responses:{"200":{description:"OpenAPI 3.1 contract."}}}}},components:{securitySchemes:{bearerAuth:{type:"http",scheme:"bearer",bearerFormat:"tsc_v1"}},parameters:{Limit:{name:"limit",in:"query",schema:{type:"integer",minimum:1,maximum:100,default:50}},Cursor:{name:"cursor",in:"query",schema:{type:"string"}},ProjectId:{name:"projectId",in:"path",required:!0,schema:{type:"string"}},OperationId:{name:"operationId",in:"path",required:!0,schema:{type:"string"}}},responses:{Error:{description:"Stable error envelope.",content:{"application/json":{schema:e}}}},schemas:{Project:{type:"object",required:["id","slug","name"],properties:{id:{type:"string"},slug:{type:"string"},name:{type:"string"},description:{type:"string"}}},Environment:{type:"object",required:["id","projectId","slug","name","kind"],properties:{id:{type:"string"},projectId:{type:"string"},slug:{type:"string"},name:{type:"string"},kind:{type:"string"},region:{type:"string"}}},Service:{type:"object",required:["id","projectId","kind","slug","name"],properties:{id:{type:"string"},projectId:{type:"string"},environmentId:{type:"string"},kind:{type:"string"},slug:{type:"string"},name:{type:"string"},metadata:{type:"object",additionalProperties:!0}}},SourceConnection:{type:"object",required:["id","provider","name","host","status","credentialConfigured"],properties:{id:{type:"string"},provider:{type:"string"},name:{type:"string"},host:{type:"string"},status:{type:"string"},credentialConfigured:{type:"boolean"},credentialFingerprint:{type:"string"},grantedScopes:{type:"array",items:{type:"string"}}}},SourceRepository:{type:"object",required:["id","connectionId","fullName","cloneUrl","defaultBranch"],properties:{id:{type:"string"},connectionId:{type:"string"},fullName:{type:"string"},cloneUrl:{type:"string"},defaultBranch:{type:"string"},visibility:{type:"string"},archived:{type:"boolean"}}},SourceBindingRequest:{type:"object",additionalProperties:!1,required:["projectId","connectionId","repositoryFullName"],properties:{projectId:{type:"string"},environmentId:{type:"string"},resourceId:{type:"string"},connectionId:{type:"string"},repositoryId:{type:"string"},repositoryFullName:{type:"string"},defaultBranch:{type:"string"},branchRule:{type:"string"},tagRule:{type:"string"},monorepoRoot:{type:"string"},includePaths:{type:"array",items:{type:"string"}},excludePaths:{type:"array",items:{type:"string"}},submodules:{type:"boolean"},cloneDepth:{type:"integer",minimum:1},deployKeyId:{type:"string"},autoDeploy:{type:"boolean"},pullRequestPreviews:{type:"boolean"}}},DetectionFile:{type:"object",additionalProperties:!1,required:["path"],properties:{path:{type:"string"},size:{type:"integer",minimum:0},content:{type:"string",maxLength:262144}}},ApplicationInput:{type:"object",additionalProperties:!1,required:["schemaVersion","name","slug","projectId","environmentId","source","build","runtime"],properties:{schemaVersion:{const:1},name:{type:"string"},slug:{type:"string"},projectId:{type:"string"},environmentId:{type:"string"},source:{type:"object",required:["kind"],properties:{kind:{type:"string",enum:["git","local","artifact","image"]}},additionalProperties:!0},build:{type:"object",required:["kind"],properties:{kind:{type:"string",enum:["dockerfile","buildpack","static","server","serverless","prebuilt_image"]},secretNames:{type:"array",uniqueItems:!0,items:{type:"string"}}},additionalProperties:!0},runtime:{type:"object",required:["architecture","target"],properties:{architecture:{type:"string",enum:["x86_64","arm64"]},target:{type:"string",enum:["server","serverless","container"]},port:{type:"integer",minimum:1,maximum:65535},healthCheck:{type:"object",additionalProperties:!0}},additionalProperties:!0},environment:{type:"object",additionalProperties:{oneOf:[{type:"string"},{type:"object",additionalProperties:!1,required:["secretRef"],properties:{secretRef:{type:"string"}}}]}},requiredSecretNames:{type:"array",uniqueItems:!0,items:{type:"string"}},domain:{type:"object",properties:{hostname:{type:"string"},path:{type:"string"},tls:{type:"boolean"}}}}},ApplicationDraftCreateRequest:{type:"object",additionalProperties:!1,required:["projectId","draft"],properties:{projectId:{type:"string"},name:{type:"string"},draft:{$ref:"#/components/schemas/ApplicationInput"},step:{type:"string",enum:["source","build","runtime","environment","domain","review"]},suppliedSecretNames:{type:"array",uniqueItems:!0,description:"Names only; values must use the secrets boundary.",items:{type:"string"}}}},ApplicationDraft:{type:"object",required:["id","projectId","input","step","status","version"],properties:{id:{type:"string"},projectId:{type:"string"},input:{$ref:"#/components/schemas/ApplicationInput"},step:{type:"string"},suppliedSecretNames:{type:"array",items:{type:"string"}},status:{type:"string",enum:["draft","ready","applied"]},version:{type:"integer"},createdAt:{type:"string",format:"date-time"},updatedAt:{type:"string",format:"date-time"}}},RegistryConnectionRequest:{type:"object",properties:{provider:{type:"string",enum:["docker_hub","ghcr","ecr","gcr","generic"]},name:{type:"string"},host:{type:"string"},username:{type:"string",writeOnly:!0},password:{type:"string",writeOnly:!0},token:{type:"string",writeOnly:!0},credentialExpiresAt:{type:"string",format:"date-time"},expiresAt:{type:"string",format:"date-time"}}},RegistryConnection:{type:"object",required:["id","provider","name","host","credentialConfigured","status","version"],properties:{id:{type:"string"},provider:{type:"string"},name:{type:"string"},host:{type:"string"},credentialConfigured:{type:"boolean"},credentialFingerprint:{type:"string"},credentialExpiresAt:{type:"string",format:"date-time"},status:{type:"string",enum:["pending","healthy","degraded","expired","disconnected"]},healthMessage:{type:"string"},lastTestedAt:{type:"string",format:"date-time"},version:{type:"integer"}}},QueueConcurrency:{type:"object",additionalProperties:!1,properties:{project:{type:"integer",minimum:1,maximum:100},environment:{type:"integer",minimum:1,maximum:100},provider:{type:"integer",minimum:1,maximum:100},builds:{type:"integer",minimum:1,maximum:100}}},QueueOperation:{allOf:[{$ref:"#/components/schemas/Operation"},{type:"object",required:["queue"],properties:{queue:{type:"object",required:["maxAttempts","availableAt","timeoutSeconds","retryClasses","resumePolicy","cancellationMode","retentionUntil"],properties:{lockKey:{type:"string"},providerKey:{type:"string"},buildSlot:{type:"boolean"},maxAttempts:{type:"integer"},availableAt:{type:"string",format:"date-time"},timeoutSeconds:{type:"integer"},heartbeatAt:{type:"string",format:"date-time"},currentStep:{type:"string"},blockedReason:{type:"string"},retryClasses:{type:"array",items:{type:"string"}},resumePolicy:{type:"string",enum:["fail","requeue"]},cancellationMode:{type:"string",enum:["cooperative","provider_non_cancellable"]},retentionUntil:{type:"string",format:"date-time"}}},approximatePosition:{type:"object",properties:{ahead:{type:"integer"},precision:{const:"bounded"}}}}}]},DeploymentRequest:{type:"object",additionalProperties:!1,required:["projectId","environmentId"],properties:{projectId:{type:"string"},environmentId:{type:"string"},serviceId:{type:"string"},action:{type:"string",enum:["deploy","rollback"],default:"deploy"},revision:{type:"string"}}},Operation:{type:"object",required:["id","state","kind","correlationId","createdAt"],properties:{id:{type:"string"},state:{type:"string"},kind:{type:"string"},correlationId:{type:"string"},createdAt:{type:"string",format:"date-time"}}},OperationResponse:{type:"object",required:["operation","idempotentReplay","requestId"],properties:{operation:{$ref:"#/components/schemas/Operation"},idempotentReplay:{type:"boolean"},requestId:{type:"string",format:"uuid"}}},Event:{type:"object",required:["id","sequence","type","level","correlationId","createdAt"],properties:{id:{type:"string"},sequence:{type:"integer"},type:{type:"string"},level:{type:"string"},correlationId:{type:"string"},payload:{},createdAt:{type:"string",format:"date-time"}}}}}}}function YE(e){return Buffer.from(JSON.stringify(e)).toString("base64url")}function XE(e){if(!e)return;try{let t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return t&&typeof t==="object"&&!Array.isArray(t)?t:void 0}catch{return}}function wt(e,t,r,n=["createdAt","id"]){let i=Math.min(100,Math.max(1,Number(t.searchParams.get("limit"))||50)),a=XE(t.searchParams.get("cursor"));if(t.searchParams.has("cursor")&&!a)throw new ne("invalid_cursor","The pagination cursor is invalid.",400);let s=0;if(a){let g=e.findIndex((h)=>n.every((_)=>h[_]===a[_]));if(g<0)throw new ne("invalid_cursor","The pagination cursor is no longer available.",400);s=g+1}let d=e.slice(s,s+i),c=s+i<e.length,o=d.at(-1);return{data:d,page:{hasMore:c,nextCursor:c&&o?YE(Object.fromEntries(n.map((g)=>[g,o[g]]))):void 0},requestId:r}}function Fd(e){let t=new Nd(e.controlPlane,e.identities),r=new Be(e.controlPlane),n=new fs(e.controlPlane),i=new Ss(e.controlPlane),a=new vn(e.controlPlane),s=e.spend?.store??new xh(e.controlPlane,{now:e.now}),d={store:s,service:e.spend?.service??new Mh(s)},c=new Map,o=e.now??(()=>new Date),g=e.rateLimit??120,h=(R,E,y,$={})=>new Response(JSON.stringify(R),{status:E,headers:{"content-type":"application/json; charset=utf-8","cache-control":"no-store","x-request-id":y,"x-api-version":us,...$}}),_=(R,E,y,$,b,z)=>h({error:{code:R,message:E,requestId:$,details:b}},y,$,z);return async(R,E)=>{let y=new URL(R.url);if(!y.pathname.startsWith("/api/v1"))return;let $=crypto.randomUUID();if(y.pathname==="/api/v1/openapi.json"&&R.method==="GET")return h(Hd(),200,$,{"cache-control":"public, max-age=300"});let b=R.headers.get("authorization")??"",z=b.startsWith("Bearer ")?b.slice(7).trim():"",C=z?e.identities.verifyToken(z,E):void 0;if(!C)return _("unauthorized","A valid bearer token is required.",401,$,void 0,{"www-authenticate":'Bearer realm="ts-cloud", error="invalid_token"'});let B=c.get(C.token.id),N=o().getTime(),F=!B||N-B.start>=60000?{start:N,count:0}:B;F.count+=1,c.set(C.token.id,F);let J=Math.max(0,g-F.count),Z={"x-ratelimit-limit":String(g),"x-ratelimit-remaining":String(J),"x-ratelimit-reset":String(Math.ceil((F.start+60000)/1000))};if(F.count>g)return _("rate_limited","API rate limit exceeded.",429,$,void 0,{...Z,"retry-after":String(Math.max(1,Math.ceil((F.start+60000-N)/1000)))});try{let O,K=async()=>{let P=await R.text();if(P.length>1048576)throw new ne("payload_too_large","Request body exceeds 1 MB.",413);try{return JSON.parse(P)}catch{throw new ne("invalid_json","Request body must be valid JSON.",400)}},ae=/^\/api\/v1\/projects\/([^/]+)\/environments$/.exec(y.pathname),Se=/^\/api\/v1\/operations\/([^/]+)\/logs(?:\/(stream))?$/.exec(y.pathname),Te=/^\/api\/v1\/operations\/([^/]+)\/(cancel|retry)$/.exec(y.pathname),de=/^\/api\/v1\/previews\/([^/]+)\/(destroy|extend|rebuild)$/.exec(y.pathname),Ae=/^\/api\/v1\/compose-applications\/([^/]+)\/(deploy|redeploy|start|stop|scale|delete)$/.exec(y.pathname),ze=/^\/api\/v1\/compose-applications\/([^/]+)\/services$/.exec(y.pathname),ue=/^\/api\/v1\/releases\/([^/]+)\/(promote|approve|activate|rollback|health|pin)$/.exec(y.pathname);if(R.method==="GET"&&y.pathname==="/api/v1/projects")O=wt(t.listProjects(C),y,$);else if(R.method==="GET"&&ae)O=wt(t.listEnvironments(C,decodeURIComponent(ae[1])),y,$);else if(R.method==="GET"&&y.pathname==="/api/v1/services"){let P=y.searchParams.get("projectId");if(!P)throw new ne("validation_error","projectId is required.",422);O=wt(t.listServices(C,P,y.searchParams.get("environmentId")??void 0),y,$)}else if(R.method==="GET"&&y.pathname==="/api/v1/operations")O=wt(t.listOperations(C,y.searchParams.get("projectId")??void 0),y,$);else if(R.method==="GET"&&y.pathname==="/api/v1/previews"){let P=y.searchParams.get("projectId")??void 0,T=n.previews.listInstances({projectId:P}).filter((U)=>{try{return t.authorize(C,"deployments:read",{type:"resource",id:U.resourceId}),!0}catch{return!1}}).map((U)=>({...U}));O=wt(T,y,$)}else if(R.method==="GET"&&y.pathname==="/api/v1/compose-templates")O=wt(hs().map((P)=>({...P})),y,$,["id","version"]);else if(R.method==="GET"&&y.pathname==="/api/v1/releases/capabilities"){let P=String(y.searchParams.get("kind")??"");O={capabilities:sa({kind:P,hasHealthGate:y.searchParams.get("health")==="true",replicas:Number(y.searchParams.get("replicas"))||1}),requestId:$}}else if(R.method==="GET"&&y.pathname==="/api/v1/releases"){let P=y.searchParams.get("projectId");if(!P)throw new ne("validation_error","projectId is required.",422);t.authorize(C,"project:read",{type:"project",id:P});let T=a.releases.list({projectId:P,environmentId:y.searchParams.get("environmentId")??void 0,resourceId:y.searchParams.get("resourceId")??void 0}).filter((U)=>{try{return t.authorize(C,"deployments:read",{type:"resource",id:U.resourceId}),!0}catch{return!1}}).map((U)=>({...U,artifact:a.releases.getArtifact(U.artifactId),transitions:a.releases.transitions(U.id),approvals:a.releases.approvals(U.id)}));O=wt(T,y,$)}else if(R.method==="POST"&&y.pathname==="/api/v1/release-artifacts"){let P=await K();t.authorize(C,"applications:manage",{type:"organization"}),O={artifact:a.releases.registerArtifact({organizationId:C.serviceAccount.organizationId,digest:String(P.digest??""),kind:String(P.kind??""),uri:String(P.uri??""),size:Number(P.size),mediaType:typeof P.mediaType==="string"?P.mediaType:void 0,provenance:P.provenance,attestation:P.attestation}),requestId:$}}else if(R.method==="POST"&&y.pathname==="/api/v1/releases"){let P=await K(),T=String(P.resourceId??"");t.authorize(C,"applications:manage",{type:"resource",id:T}),O={release:a.releases.create({organizationId:C.serviceAccount.organizationId,projectId:String(P.projectId??""),environmentId:String(P.environmentId??""),resourceId:T,artifactId:String(P.artifactId??""),kind:String(P.kind??""),sourceSha:typeof P.sourceSha==="string"?P.sourceSha:void 0,config:P.config??{},manifest:P.manifest??{},provenance:P.provenance,strategy:String(P.strategy??"atomic"),healthGate:P.healthGate,hooks:P.hooks,drainSeconds:Number(P.drainSeconds)||void 0,graceSeconds:Number(P.graceSeconds)||void 0,automaticRollback:P.automaticRollback!==!1,actorId:C.actor.id,trigger:typeof P.trigger==="string"?P.trigger:"api",approvalRequired:P.approvalRequired===!0,replicas:Number(P.replicas)||void 0}),requestId:$}}else if(R.method==="GET"&&/^\/api\/v1\/releases\/[^/]+$/.test(y.pathname)){let P=decodeURIComponent(y.pathname.split("/").at(-1)),T=a.releases.get(P);if(!T)throw new ne("not_found","Release was not found.",404);t.authorize(C,"deployments:read",{type:"resource",id:T.resourceId}),O={release:T,artifact:a.releases.getArtifact(T.artifactId),transitions:a.releases.transitions(P),approvals:a.releases.approvals(P),requestId:$}}else if(R.method==="POST"&&ue){let P=a.releases.get(decodeURIComponent(ue[1]));if(!P)throw new ne("not_found","Release was not found.",404);let T=await K(),U=ue[2];if(U==="promote"){let M=String(T.targetResourceId??"");t.authorize(C,"deployments:create",{type:"resource",id:M}),O={release:a.releases.promote(P.id,{targetEnvironmentId:String(T.targetEnvironmentId??""),targetResourceId:M,config:T.config??{},strategy:T.strategy,healthGate:T.healthGate,actorId:C.actor.id,approvalRequired:T.approvalRequired===!0}),requestId:$}}else if(U==="approve")t.authorize(C,"deployments:create",{type:"resource",id:P.resourceId}),O={release:a.releases.approve(P.id,{actorId:C.actor.id,decision:T.decision==="rejected"?"rejected":"approved",comment:typeof T.comment==="string"?T.comment:void 0}),requestId:$};else if(U==="activate")t.authorize(C,"deployments:create",{type:"resource",id:P.resourceId}),O={operation:t.operation(a.enqueueActivation(P,{actorId:C.actor.id})),requestId:$};else if(U==="rollback")t.authorize(C,"deployments:create",{type:"resource",id:P.resourceId}),O={operation:t.operation(a.enqueueRollback(P,{actorId:C.actor.id,targetReleaseId:typeof T.targetReleaseId==="string"?T.targetReleaseId:void 0})),requestId:$};else if(U==="health"){t.authorize(C,"deployments:create",{type:"resource",id:P.resourceId});let M=a.completeHealthGate(P.id,{healthy:T.healthy===!0,operationId:typeof T.operationId==="string"?T.operationId:void 0,health:T.health,message:typeof T.message==="string"?T.message:void 0});O={release:M.release,rollbackOperation:M.rollbackOperation?t.operation(M.rollbackOperation):void 0,requestId:$}}else t.authorize(C,"deployments:create",{type:"resource",id:P.resourceId}),O={release:a.releases.pin(P.id,T.pinned!==!1,typeof T.reason==="string"?T.reason:void 0),requestId:$}}else if(R.method==="GET"&&y.pathname==="/api/v1/compose-applications"){let P=y.searchParams.get("projectId");if(!P)throw new ne("validation_error","projectId is required.",422);t.authorize(C,"project:read",{type:"project",id:P});let T=i.applications.list({projectId:P,environmentId:y.searchParams.get("environmentId")??void 0}).filter((U)=>{try{return t.authorize(C,"deployments:read",{type:"resource",id:U.resourceId}),!0}catch{return!1}}).map((U)=>({...U,services:i.applications.services(U.id)}));O=wt(T,y,$)}else if(R.method==="POST"&&y.pathname==="/api/v1/compose-applications/preview"){let P=await K(),T=String(P.projectId??"");t.authorize(C,"project:read",{type:"project",id:T}),O={result:i.applications.preview(String(P.source??""),{name:String(P.name??""),slug:typeof P.slug==="string"?P.slug:void 0,projectId:T,environmentId:String(P.environmentId??"")}),requestId:$}}else if(R.method==="POST"&&y.pathname==="/api/v1/compose-applications"){let P=await K(),T=String(P.projectId??"");t.authorize(C,"applications:manage",{type:"environment",id:String(P.environmentId??"")});let U={name:String(P.name??""),slug:typeof P.slug==="string"?P.slug:void 0,projectId:T,environmentId:String(P.environmentId??""),createdByActorId:C.actor.id},M=typeof P.templateId==="string"?i.applications.fromTemplate(P.templateId,P.inputs&&typeof P.inputs==="object"&&!Array.isArray(P.inputs)?P.inputs:{},{...U,version:typeof P.templateVersion==="string"?P.templateVersion:void 0}):i.applications.import(String(P.source??""),U);O={application:M.application,diagnostics:M.parsed.diagnostics,requestId:$}}else if(R.method==="GET"&&ze){let P=i.applications.get(decodeURIComponent(ze[1]));if(!P)throw new ne("not_found","Compose application was not found.",404);t.authorize(C,"deployments:read",{type:"resource",id:P.resourceId}),O={application:P,services:i.applications.services(P.id),requestId:$}}else if(R.method==="POST"&&Ae){let P=i.applications.get(decodeURIComponent(Ae[1]));if(!P)throw new ne("not_found","Compose application was not found.",404);let T=Ae[2],U=await K();t.authorize(C,T==="delete"||T==="stop"?"deployments:cancel":"deployments:create",{type:"resource",id:P.resourceId}),O={operation:t.operation(i.enqueue(P,T,{actorId:C.actor.id,service:typeof U.service==="string"?U.service:void 0,replicas:Number.isFinite(Number(U.replicas))?Number(U.replicas):void 0,removeVolumes:U.removeVolumes===!0,confirmation:typeof U.confirm==="string"?U.confirm:void 0})),requestId:$}}else if(R.method==="GET"&&y.pathname==="/api/v1/preview-definitions"){let P=y.searchParams.get("projectId");if(!P)throw new ne("validation_error","projectId is required.",422);t.authorize(C,"project:read",{type:"project",id:P}),O=wt(n.previews.listDefinitions(P).map((T)=>({...T})),y,$)}else if(R.method==="POST"&&y.pathname==="/api/v1/preview-definitions"){let P=await K();t.authorize(C,"config:write",{type:"resource",id:String(P.resourceId??"")}),O={definition:n.previews.createDefinition({...P,projectId:String(P.projectId??""),resourceId:String(P.resourceId??""),baseEnvironmentId:String(P.baseEnvironmentId??""),domainPattern:String(P.domainPattern??""),createdByActorId:C.actor.id}),requestId:$}}else if(R.method==="POST"&&y.pathname==="/api/v1/previews"){let P=await K(),T=n.previews.getDefinition(String(P.definitionId??""));if(!T)throw new ne("not_found","Preview definition was not found.",404);t.authorize(C,"deployments:create",{type:"resource",id:T.resourceId});let U=n.previews.upsert({definitionId:T.id,sourceProvider:"api",repository:typeof P.repository==="string"?P.repository:"api",branch:String(P.branch??""),pullRequestNumber:Number(P.pullRequestNumber)||void 0,fork:P.fork===!0,commitSha:String(P.commitSha??""),createdByActorId:C.actor.id});O={preview:U.preview,operation:t.operation(n.enqueueDeploy(U.preview,{created:U.created,actorId:C.actor.id})),requestId:$}}else if(R.method==="POST"&&de){let P=n.previews.getInstance(decodeURIComponent(de[1]));if(!P)throw new ne("not_found","Preview was not found.",404);let T=await K(),U=de[2];if(U==="destroy"){if(t.authorize(C,"deployments:cancel",{type:"resource",id:P.resourceId}),T.confirm!==P.name)throw new ne("confirmation_required",`Type ${P.name} to confirm preview teardown.`,409);O={operation:t.operation(n.enqueueDestroy(P,"api",C.actor.id)),requestId:$}}else if(U==="extend")t.authorize(C,"deployments:create",{type:"resource",id:P.resourceId}),O={preview:n.previews.extend(P.id,Number(T.hours)),requestId:$};else t.authorize(C,"deployments:create",{type:"resource",id:P.resourceId}),O={operation:t.operation(n.enqueueDeploy(P,{actorId:C.actor.id,reason:"manual_rebuild"})),requestId:$}}else if(R.method==="POST"&&y.pathname==="/api/v1/previews/cleanup"){t.authorize(C,"automation:manage",{type:"organization"});let P=await K();if(!P.dryRun&&P.confirm!=="cleanup previews")throw new ne("confirmation_required","Type cleanup previews to confirm preview cleanup.",409);O={...n.cleanup({dryRun:P.dryRun===!0,maxAgeHours:Number(P.maxAgeHours)||void 0,keepCount:Number(P.keepCount)||void 0,actorId:C.actor.id}),requestId:$}}else if(R.method==="GET"&&y.pathname==="/api/v1/queue"){let P=y.searchParams.get("projectId")??void 0,T=y.searchParams.get("state"),U=r.list({projectId:P,state:["queued","running","succeeded","failed","cancelled","timed_out"].includes(T)?T:void 0,limit:500}).filter((M)=>{let _e=M.operation.resourceId?{type:"resource",id:M.operation.resourceId}:M.operation.environmentId?{type:"environment",id:M.operation.environmentId}:M.operation.projectId?{type:"project",id:M.operation.projectId}:{type:"organization"};try{return t.authorize(C,"deployments:read",_e),!0}catch{return!1}}).map((M)=>({...t.operation(M.operation),queue:M.job,approximatePosition:M.approximatePosition}));O=wt(U,y,$)}else if(R.method==="GET"&&y.pathname==="/api/v1/queue/settings")t.authorize(C,"deployments:read",C.token.scope),O={concurrency:r.limits,requestId:$};else if(R.method==="PATCH"&&y.pathname==="/api/v1/queue/settings"){t.authorize(C,"automation:manage",{type:"organization"});let P=await K();if(P.confirm!=="update queue limits")throw new ne("confirmation_required","Type update queue limits to confirm production concurrency changes.",409);O={concurrency:r.configureConcurrency(P.concurrency??{},{organizationId:C.serviceAccount.organizationId,actorId:C.actor.id}),requestId:$}}else if(R.method==="DELETE"&&y.pathname==="/api/v1/queue/history"){t.authorize(C,"automation:manage",{type:"organization"});let P=await K();if(P.confirm!=="clear completed")throw new ne("confirmation_required","Type clear completed to confirm queue retention cleanup.",409);O={deleted:r.clearCompleted({before:typeof P.before==="string"?P.before:void 0,actorId:C.actor.id,projectId:typeof P.projectId==="string"?P.projectId:void 0}),requestId:$}}else if(R.method==="GET"&&Se){let P=e.controlPlane.getOperation(decodeURIComponent(Se[1]));if(!P)throw new ne("not_found","Operation was not found.",404);let T=P.resourceId?{type:"resource",id:P.resourceId}:P.environmentId?{type:"environment",id:P.environmentId}:P.projectId?{type:"project",id:P.projectId}:{type:"organization"};t.authorize(C,"deployments:read",T);let U=R.headers.get("last-event-id")?.trim(),M=Number(U||y.searchParams.get("after")||0);if(Se[2]==="stream"){let Pe=new TextEncoder,G=M,pe,he=!1,ie=new ReadableStream({start(ft){let ti=()=>{if(he)return;if(!e.identities.verifyToken(z,E)){if(he=!0,pe)clearInterval(pe);ft.close();return}let dr=r.logs(P.id,{after:G,limit:500});for(let We of dr)G=We.sequence,ft.enqueue(Pe.encode(`id: ${We.sequence}
23
+ event: log
24
+ data: ${JSON.stringify(We)}
25
+
26
+ `));let be=e.controlPlane.getOperation(P.id);if(be&&["succeeded","failed","cancelled","timed_out"].includes(be.state)&&!r.logs(P.id,{after:G,limit:1}).length){if(he=!0,pe)clearInterval(pe);ft.enqueue(Pe.encode(`event: complete
27
+ data: ${JSON.stringify({state:be.state,cursor:G})}
28
+
29
+ `)),ft.close()}};if(ti(),!he)pe=setInterval(ti,500);R.signal.addEventListener("abort",()=>{if(he=!0,pe)clearInterval(pe);try{ft.close()}catch{}},{once:!0})},cancel(){if(he=!0,pe)clearInterval(pe)}});return new Response(ie,{headers:{"content-type":"text/event-stream","cache-control":"no-store","x-accel-buffering":"no","x-request-id":$,...Z}})}let _e=r.logs(P.id,{after:M,limit:Number(y.searchParams.get("limit"))||void 0});O={data:_e,cursor:_e.at(-1)?.sequence??M,hasMore:_e.length>=Math.min(1000,Math.max(1,Number(y.searchParams.get("limit"))||200)),requestId:$}}else if(R.method==="POST"&&Te){let P=e.controlPlane.getOperation(decodeURIComponent(Te[1]));if(!P)throw new ne("not_found","Operation was not found.",404);let T=P.resourceId?{type:"resource",id:P.resourceId}:P.environmentId?{type:"environment",id:P.environmentId}:P.projectId?{type:"project",id:P.projectId}:{type:"organization"},U=await K();if(Te[2]==="cancel")t.authorize(C,"deployments:cancel",T),O={operation:t.operation(r.requestCancellation(P.id,C.actor.id)),requestId:$};else t.authorize(C,"deployments:create",T),O={operation:t.operation(r.retry(P.id,String(U.errorClass??"manual"),{delayMs:Number(U.delayMs)||0,actorId:C.actor.id})),requestId:$}}else if(R.method==="GET"&&y.pathname==="/api/v1/source/connections"){if(!e.sources)throw new ne("not_found","Source integrations are unavailable.",404);t.authorize(C,"sources:read",C.token.scope),O=wt(e.sources.listConnections(C.serviceAccount.organizationId),y,$,["createdAt","id"])}else if(R.method==="GET"&&y.pathname==="/api/v1/source/repositories"){if(!e.sources)throw new ne("not_found","Source integrations are unavailable.",404);t.authorize(C,"sources:read",C.token.scope);let P=e.sources.getConnection(y.searchParams.get("connectionId")??"");if(!P||P.organizationId!==C.serviceAccount.organizationId)throw new ne("not_found","Source connection was not found.",404);if(y.searchParams.get("sync")==="true")t.authorize(C,"sources:manage",{type:"organization"}),await ls(e.sources,P.id,{search:y.searchParams.get("search")??void 0});O=wt(e.sources.listRepositories(P.id,y.searchParams.get("search")??void 0),y,$,["fullName","id"])}else if(R.method==="GET"&&y.pathname==="/api/v1/source/refs"){if(!e.sources)throw new ne("not_found","Source integrations are unavailable.",404);t.authorize(C,"sources:read",C.token.scope);let P=y.searchParams.get("connectionId")??"",T=e.sources.getConnection(P);if(!T||T.organizationId!==C.serviceAccount.organizationId)throw new ne("not_found","Source connection was not found.",404);O=await gs(e.sources,{connectionId:P,repository:y.searchParams.get("repository")??"",repositoryId:y.searchParams.get("repositoryId")??void 0,type:y.searchParams.get("type")==="tags"?"tags":"branches",cursor:y.searchParams.get("cursor")??void 0,deployKeyId:y.searchParams.get("deployKeyId")??void 0})}else if(R.method==="POST"&&y.pathname==="/api/v1/application-detections"){t.authorize(C,"applications:manage",C.token.scope);let P=await K();if(!Array.isArray(P.files)||P.files.length>1e4)throw new ne("validation_error","files must contain at most 10,000 entries.",422);O={candidates:fi(P.files.map((T)=>({path:String(T.path??""),size:Number(T.size??0),content:typeof T.content==="string"?T.content.slice(0,262144):void 0}))),requestId:$}}else if(R.method==="POST"&&y.pathname==="/api/v1/application-plans"){t.authorize(C,"applications:manage",C.token.scope);let P=await K();O={plan:Yt(P.draft,Array.isArray(P.suppliedSecretNames)?P.suppliedSecretNames.map(String):[]),requestId:$}}else if(R.method==="GET"&&y.pathname==="/api/v1/application-drafts"){if(!e.applications)throw new ne("not_found","Application onboarding is unavailable.",404);let P=y.searchParams.get("projectId")??"";t.authorize(C,"applications:read",{type:"project",id:P}),O=wt(e.applications.drafts.list(P),y,$,["updatedAt","id"])}else if(R.method==="POST"&&y.pathname==="/api/v1/application-drafts"){if(!e.applications)throw new ne("not_found","Application onboarding is unavailable.",404);let P=await K(),T=String(P.projectId??P.draft?.projectId??"");t.authorize(C,"applications:manage",{type:"project",id:T});let U=e.controlPlane.getProject(T);if(!U||U.organizationId!==C.serviceAccount.organizationId)throw new ne("not_found","Project was not found.",404);let M=e.applications.drafts.create({organizationId:U.organizationId,projectId:T,name:String(P.name??P.draft?.name??"Application draft"),draft:{...P.draft,projectId:T},step:P.step,suppliedSecretNames:Array.isArray(P.suppliedSecretNames)?P.suppliedSecretNames.map(String):[],actorId:C.actor.id});return h({draft:M,requestId:$},201,$,Z)}else if(R.method==="PATCH"&&y.pathname==="/api/v1/application-drafts"){if(!e.applications)throw new ne("not_found","Application onboarding is unavailable.",404);let P=await K(),T=e.applications.drafts.get(String(P.id??""));if(!T)throw new ne("not_found","Application draft was not found.",404);t.authorize(C,"applications:manage",{type:"project",id:T.projectId}),O={draft:e.applications.drafts.update(T.id,Number(P.version),{draft:{...P.draft,projectId:T.projectId},step:P.step,suppliedSecretNames:Array.isArray(P.suppliedSecretNames)?P.suppliedSecretNames.map(String):void 0,actorId:C.actor.id}),requestId:$}}else if(R.method==="POST"&&y.pathname==="/api/v1/applications"){if(!e.applications)throw new ne("not_found","Application onboarding is unavailable.",404);let P=R.headers.get("idempotency-key")??"";if(!P)throw new ne("idempotency_required","Idempotency-Key is required for application creation.",428);if(!/^[A-Za-z0-9._:-]{8,128}$/.test(P))throw new ne("validation_error","Idempotency-Key must contain 8-128 safe characters.",422);let T=await K(),U=e.applications.drafts.get(String(T.draftId??""));if(!U)throw new ne("not_found","Application draft was not found.",404);t.authorize(C,"applications:manage",{type:"project",id:U.projectId});let M=KE("sha256").update(`POST
30
+ /api/v1/applications
31
+ ${JSON.stringify(T)}`).digest("hex"),_e=e.identities.getIdempotency(C.token.id,P);if(_e){if(_e.requestHash!==M)throw new ne("idempotency_conflict","Idempotency-Key was already used for another request.",409);let G=_e.operationId?e.controlPlane.getOperation(_e.operationId):void 0,pe=G?.resourceId?e.controlPlane.getResource(G.resourceId):void 0;if(!G||!pe)throw new ne("idempotency_unavailable","The original application operation is no longer available.",409);return h({resource:pe,operation:t.operation(G),plan:Yt(U.input,U.suppliedSecretNames),idempotentReplay:!0,requestId:$},202,$,{...Z,"idempotent-replayed":"true"})}let Pe=ss({controlPlane:e.controlPlane,drafts:e.applications.drafts,draftId:U.id,expectedVersion:Number(T.version),confirmEnvironment:String(T.confirmEnvironment??""),actorId:C.actor.id});return e.identities.saveIdempotency({tokenId:C.token.id,key:P,requestHash:M,operationId:Pe.operation.id,responseStatus:202,responseBody:{draftId:U.id}}),h({resource:Pe.resource,operation:t.operation(Pe.operation),plan:Pe.plan,idempotentReplay:!1,requestId:$},202,$,Z)}else if(R.method==="GET"&&y.pathname==="/api/v1/registry-connections"){if(!e.applications)throw new ne("not_found","Application onboarding is unavailable.",404);t.authorize(C,"applications:read",C.token.scope),O=wt(e.applications.registries.list(C.serviceAccount.organizationId),y,$,["createdAt","id"])}else if(R.method==="POST"&&y.pathname==="/api/v1/registry-connections"){if(!e.applications)throw new ne("not_found","Application onboarding is unavailable.",404);t.authorize(C,"applications:manage",{type:"organization"});let P=await K(),T=e.applications.registries.create({organizationId:C.serviceAccount.organizationId,provider:P.provider,name:String(P.name??"Container registry"),host:String(P.host??""),credential:P.token||P.password?{username:typeof P.username==="string"?P.username:void 0,password:typeof P.password==="string"?P.password:void 0,token:typeof P.token==="string"?P.token:void 0}:void 0,credentialExpiresAt:typeof P.credentialExpiresAt==="string"?P.credentialExpiresAt:void 0,actorId:C.actor.id});return h({registry:T,requestId:$},201,$,Z)}else if(R.method==="PATCH"&&y.pathname==="/api/v1/registry-connections"){if(!e.applications)throw new ne("not_found","Application onboarding is unavailable.",404);t.authorize(C,"applications:manage",{type:"organization"});let P=await K(),T=e.applications.registries.get(String(P.id??""));if(!T||T.organizationId!==C.serviceAccount.organizationId)throw new ne("not_found","Registry connection was not found.",404);if(P.action==="test")O={registry:await e.applications.registries.test(T.id,{image:typeof P.image==="string"?P.image:void 0}),requestId:$};else if(P.action==="rotate")O={registry:e.applications.registries.rotate(T.id,{username:P.username,password:P.password,token:P.token},{expiresAt:P.expiresAt,actorId:C.actor.id}),requestId:$};else throw new ne("validation_error","action must be test or rotate.",422)}else if(R.method==="DELETE"&&y.pathname==="/api/v1/registry-connections"){if(!e.applications)throw new ne("not_found","Application onboarding is unavailable.",404);t.authorize(C,"applications:manage",{type:"organization"});let P=await K(),T=e.applications.registries.get(String(P.id??""));if(!T||T.organizationId!==C.serviceAccount.organizationId)throw new ne("not_found","Registry connection was not found.",404);O={registry:e.applications.registries.disconnect(T.id,C.actor.id),requestId:$}}else if(R.method==="POST"&&y.pathname==="/api/v1/application-artifacts"){if(!e.applications?.artifacts)throw new ne("not_found","Application artifact storage is unavailable.",404);let P=R.headers.get("x-project-id")??"";t.authorize(C,"applications:manage",{type:"project",id:P});let T=e.controlPlane.getProject(P);if(!T||T.organizationId!==C.serviceAccount.organizationId)throw new ne("not_found","Project was not found.",404);if(Number(R.headers.get("content-length")??0)>104857600)throw new ne("payload_too_large","Artifact exceeds 100 MB.",413);let M=e.applications.artifacts.create({organizationId:T.organizationId,projectId:P,filename:R.headers.get("x-artifact-filename")??"application.zip",bytes:new Uint8Array(await R.arrayBuffer()),actorId:C.actor.id});return h({artifact:M,requestId:$},201,$,Z)}else if(R.method==="POST"&&y.pathname==="/api/v1/source/connections"){if(!e.sources)throw new ne("not_found","Source integrations are unavailable.",404);t.authorize(C,"sources:manage",{type:"organization"});let P=await K(),T=String(P.provider??"");if(!["github","gitlab","bitbucket","gitea","generic_https","generic_ssh"].includes(T))throw new ne("validation_error","A supported provider is required.",422);let U=T==="github"&&(P.privateKey||P.appId)?{appId:typeof P.appId==="string"?P.appId:void 0,installationId:typeof P.installationId==="string"?P.installationId:void 0,privateKey:typeof P.privateKey==="string"?P.privateKey:void 0}:T!=="generic_ssh"&&P.token?{token:String(P.token),username:typeof P.username==="string"?P.username:void 0}:void 0,M,_e,Pe;return e.controlPlane.database.transaction(()=>{if(M=e.sources.createConnection({organizationId:C.serviceAccount.organizationId,provider:T,name:String(P.name??T),host:String(P.host??""),owner:typeof P.owner==="string"?P.owner:void 0,authKind:P.authKind,credential:U,createdByActorId:C.actor.id}),typeof P.repositoryUrl==="string"&&typeof P.repositoryFullName==="string")_e=e.sources.upsertRepository({connectionId:M.id,providerRepositoryId:`manual:${P.repositoryFullName}`,fullName:P.repositoryFullName,cloneUrl:P.repositoryUrl,defaultBranch:String(P.defaultBranch??"main"),visibility:"unknown",archived:!1,metadata:{source:"api"}});if(T==="generic_ssh")Pe=e.sources.createDeployKey({connectionId:M.id,name:String(P.deployKeyName??"Repository deploy key"),publicKey:String(P.publicKey??""),privateKey:String(P.deployPrivateKey??""),host:String(P.sshHost??""),hostKey:String(P.hostKey??""),actorId:C.actor.id})})(),h({connection:M,repository:_e,deployKey:Pe,requestId:$},201,$,Z)}else if(R.method==="POST"&&y.pathname==="/api/v1/source/bindings"){if(!e.sources)throw new ne("not_found","Source integrations are unavailable.",404);let P=await K(),T=String(P.projectId??"");t.authorize(C,"sources:manage",{type:"project",id:T});let U=e.sources.getConnection(String(P.connectionId??""));if(!U||U.organizationId!==C.serviceAccount.organizationId)throw new ne("not_found","Source connection was not found.",404);let M=e.sources.createBinding({projectId:T,environmentId:typeof P.environmentId==="string"?P.environmentId:void 0,resourceId:typeof P.resourceId==="string"?P.resourceId:void 0,connectionId:U.id,repositoryId:typeof P.repositoryId==="string"?P.repositoryId:void 0,repositoryFullName:String(P.repositoryFullName??""),defaultBranch:String(P.defaultBranch??"main"),branchRule:typeof P.branchRule==="string"?P.branchRule:void 0,tagRule:typeof P.tagRule==="string"?P.tagRule:void 0,monorepoRoot:String(P.monorepoRoot??"."),includePaths:Array.isArray(P.includePaths)?P.includePaths.map(String):[],excludePaths:Array.isArray(P.excludePaths)?P.excludePaths.map(String):[],submodules:P.submodules===!0,cloneDepth:typeof P.cloneDepth==="number"?P.cloneDepth:void 0,deployKeyId:typeof P.deployKeyId==="string"&&P.deployKeyId?P.deployKeyId:void 0,autoDeploy:P.autoDeploy!==!1,pullRequestPreviews:P.pullRequestPreviews!==!1,actorId:C.actor.id});return h({binding:M,requestId:$},201,$,Z)}else if(R.method==="POST"&&y.pathname==="/api/v1/source/webhooks"){if(!e.sources)throw new ne("not_found","Source integrations are unavailable.",404);t.authorize(C,"sources:manage",{type:"organization"});let P=await K(),T=e.sources.getConnection(String(P.connectionId??""));if(!T||T.organizationId!==C.serviceAccount.organizationId)throw new ne("not_found","Source connection was not found.",404);let U=typeof P.baseUrl==="string"?P.baseUrl:void 0;if(!U)throw new ne("validation_error","baseUrl is required.",422);let M=e.sources.createWebhook({connectionId:T.id,repositoryId:typeof P.repositoryId==="string"?P.repositoryId:void 0,repositoryFullName:String(P.repositoryFullName??""),events:Array.isArray(P.events)?P.events.map(String):void 0}),_e=Ri(U,M.webhook),Pe=P.reconcile===!1?M.webhook:await la(e.sources,M.webhook.id,U);return h({webhook:Pe,endpoint:_e,endpointRevealOnce:!0,requestId:$},201,$,Z)}else if(R.method==="DELETE"&&y.pathname==="/api/v1/source/connections"){if(!e.sources)throw new ne("not_found","Source integrations are unavailable.",404);t.authorize(C,"sources:manage",{type:"organization"});let P=await K(),T=e.sources.getConnection(String(P.id??""));if(!T||T.organizationId!==C.serviceAccount.organizationId)throw new ne("not_found","Source connection was not found.",404);let U=e.sources.listBindings({connectionId:T.id,status:"active"});if(P.preview===!0)return h({preview:!0,affectedBindings:U,requestId:$},200,$,Z);return h({...e.sources.disconnectConnection(T.id,C.actor.id),requestId:$},200,$,Z)}else if(R.method==="GET"&&(y.pathname==="/api/v1/events"||y.pathname==="/api/v1/events/stream")){let P=t.listEvents(C,y.searchParams.get("projectId")??void 0,Number(y.searchParams.get("after"))||void 0);if(y.pathname.endsWith("/stream")){let T=new TextEncoder,U=P.reduce((G,pe)=>Math.max(G,Number(pe.sequence)),Number(y.searchParams.get("after"))||0),M,_e=!1,Pe=new ReadableStream({start(G){let pe=(he)=>G.enqueue(T.encode(`id: ${he.sequence}
32
+ event: ${he.type}
33
+ data: ${JSON.stringify(he)}
34
+
35
+ `));if(P.length)P.forEach(pe);else G.enqueue(T.encode(`: connected
36
+
37
+ `));M=setInterval(()=>{if(_e)return;let he=e.identities.verifyToken(z,E);if(!he){if(_e=!0,M)clearInterval(M);G.close();return}try{let ie=t.listEvents(he,y.searchParams.get("projectId")??void 0,U);for(let ft of ie)pe(ft),U=Math.max(U,Number(ft.sequence));if(!ie.length)G.enqueue(T.encode(`: heartbeat ${Date.now()}
38
+
39
+ `))}catch{if(_e=!0,M)clearInterval(M);G.close()}},1000),R.signal.addEventListener("abort",()=>{if(_e=!0,M)clearInterval(M);try{G.close()}catch{}},{once:!0})},cancel(){if(_e=!0,M)clearInterval(M)}});return new Response(Pe,{status:200,headers:{"content-type":"text/event-stream","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no","x-request-id":$,...Z}})}O=wt(P,y,$,["sequence","id"])}else if(R.method==="POST"&&y.pathname==="/api/v1/deployments"){let P=R.headers.get("idempotency-key")??"";if(!P)throw new ne("idempotency_required","Idempotency-Key is required for deployment requests.",428);let T=await R.text();if(T.length>1048576)throw new ne("payload_too_large","Request body exceeds 1 MB.",413);let U;try{U=JSON.parse(T)}catch{throw new ne("invalid_json","Request body must be valid JSON.",400)}if(!U||typeof U.projectId!=="string"||typeof U.environmentId!=="string"||U.action!==void 0&&!["deploy","rollback"].includes(U.action))throw new ne("validation_error","projectId, environmentId, and a valid action are required.",422);let M=t.createDeployment(C,U,P);return h({operation:M.operation,idempotentReplay:M.replay,requestId:$},202,$,{...Z,...M.replay?{"idempotent-replayed":"true"}:{}})}else{let P=await Qh({...d,authorization:t,now:o},C,{method:R.method,url:y,body:K});if(P===void 0)throw new ne("not_found","API resource was not found.",404);O=P}return h(O,200,$,Z)}catch(O){if(O instanceof ne)return _(O.code,O.message,O.status,$,O.details,Z);if(y.pathname.startsWith("/api/v1/source/")||y.pathname.startsWith("/api/v1/application")||y.pathname.startsWith("/api/v1/compose-")||y.pathname==="/api/v1/registry-connections")return _("validation_error",O instanceof Error?O.message:"Integration request could not be completed.",422,$,void 0,Z);return _("internal_error","The API request could not be completed.",500,$,void 0,Z)}}}import{createCipheriv as ny,createDecipheriv as iy,createHash as qh,randomBytes as Pr}from"node:crypto";import{createHmac as qE,timingSafeEqual as ey}from"node:crypto";var Vd="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";function _s(e){let t=0,r=0,n="";for(let i of e){r=r<<8|i,t+=8;while(t>=5)n+=Vd[r>>>t-5&31],t-=5}if(t>0)n+=Vd[r<<5-t&31];return n}function Gh(e){let t=e.toUpperCase().replace(/[^A-Z2-7]/g,""),r=0,n=0,i=[];for(let a of t){let s=Vd.indexOf(a);if(s<0)throw Error("Invalid base32 secret");if(n=n<<5|s,r+=5,r>=8)i.push(n>>>r-8&255),r-=8}return Buffer.from(i)}function Ld(e,t,r=6){let n=Buffer.alloc(8);n.writeBigUInt64BE(BigInt(t));let i=qE("sha1",Gh(e)).update(n).digest(),a=i[i.length-1]&15,s=(i[a]&127)<<24|(i[a+1]&255)<<16|(i[a+2]&255)<<8|i[a+3]&255;return String(s%10**r).padStart(r,"0")}function ty(e,t=Date.now(),r=30){return Ld(e,Math.floor(t/1000/r))}function ry(e,t,r=Date.now(),n=1){return ga(e,t,r,n)!==void 0}function ga(e,t,r=Date.now(),n=1){let i=t.replace(/[\s-]/g,"");if(!/^\d{6}$/.test(i))return;let a=Buffer.from(i),s=Math.floor(r/1000/30);for(let d=-n;d<=n;d++){if(s+d<0)continue;let c=Buffer.from(Ld(e,s+d));if(a.length===c.length&&ey(a,c))return s+d}return}function xd(e){let t=e.issuer?.trim()||"ts-cloud",r=`${t}:${e.account}`;return`otpauth://totp/${encodeURIComponent(r)}?secret=${encodeURIComponent(e.secret)}&issuer=${encodeURIComponent(t)}&algorithm=SHA1&digits=6&period=30`}var ef=1800000,rn=43200000,tf=3600000,rf=300000,nf=600000;function Wt(e){return typeof e==="string"?e:void 0}function af(e){if(typeof e!=="string")return{};try{return JSON.parse(e)}catch{return{}}}function ay(e){let t=e.trim();if(!/^[a-z0-9][a-z0-9._-]{1,31}$/i.test(t))throw Error("Username must be 2-32 characters: letters, numbers, dot, dash or underscore");return t}function Md(e){if(e===void 0||!e.trim())return;let t=e.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)||t.length>254)throw Error("A valid email address is required");return t}function sy(e){let t=e.trim().toLowerCase();if(!/^[a-z0-9][a-z0-9-]{1,47}$/.test(t))throw Error("OIDC provider slug must be 2-48 lowercase letters, numbers or dashes");return t}function oy(e){let t=new URL(e.trim());if(t.search||t.hash||t.username||t.password)throw Error("OIDC issuer cannot contain credentials, a query, or a fragment");if(t.protocol!=="https:"&&!(t.protocol==="http:"&&["127.0.0.1","::1","localhost"].includes(t.hostname)))throw Error("OIDC issuer must use HTTPS");return t.href.replace(/\/$/,"")}function dy(e){let t=[...new Set(e.map((r)=>r.trim().toLowerCase()).filter(Boolean))];if(t.length===0)throw Error("At least one explicit OIDC email domain is required");if(t.some((r)=>!/^[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?$/.test(r)||!r.includes(".")||r.includes("..")))throw Error("OIDC email domains must be explicit DNS names without wildcards");return t}function cy(e){let t=[...new Set(["openid",...e??["email","profile"]].map((r)=>r.trim()).filter(Boolean))];if(t.some((r)=>!/^[\x21\x23-\x5B\x5D-\x7E]+$/.test(r)))throw Error("OIDC scopes contain unsupported characters");return t}function Xt(e){return qh("sha256").update(e).digest("hex")}function ua(e){return{id:String(e.id),actorId:String(e.actor_id),username:String(e.username),email:Wt(e.email),emailVerifiedAt:Wt(e.email_verified_at),passwordHash:String(e.password_hash),credentialVersion:Number(e.credential_version),requiresPasswordUpgrade:Number(e.requires_password_upgrade)===1,disabledAt:Wt(e.disabled_at),lastLoginAt:Wt(e.last_login_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Zh(e,t){let r=Wt(e.consumed_at),n=String(e.expires_at);return{id:String(e.id),identityId:String(e.identity_id),type:String(e.type),metadata:af(e.metadata),expiresAt:n,consumedAt:r,createdAt:String(e.created_at),state:r?"consumed":n<=t?"expired":"pending"}}function Qd(e,t){let r=Wt(e.revoked_at),n=String(e.idle_expires_at),i=String(e.absolute_expires_at);return{id:String(e.id),identityId:String(e.identity_id),credentialVersion:Number(e.credential_version),authMethod:String(e.auth_method),userAgent:Wt(e.user_agent),networkHint:Wt(e.network_hint),createdAt:String(e.created_at),lastUsedAt:String(e.last_used_at),idleExpiresAt:n,absoluteExpiresAt:i,recentAuthAt:String(e.recent_auth_at),mfaAt:Wt(e.mfa_at),revokedAt:r,state:r?"revoked":n<=t||i<=t?"expired":"active"}}function Kh(e){let t=Wt(e.verified_at),r=Wt(e.disabled_at);return{id:String(e.id),identityId:String(e.identity_id),type:"totp",label:String(e.label),createdAt:String(e.created_at),verifiedAt:t,disabledAt:r,state:r?"disabled":t?"active":"pending"}}function Gd(e,t){let r=Wt(e.consumed_at),n=String(e.expires_at),i=Number(e.attempts);return{id:String(e.id),identityId:String(e.identity_id),purpose:String(e.purpose),attempts:i,expiresAt:n,consumedAt:r,createdAt:String(e.created_at),state:r?"consumed":i>=5?"locked":n<=t?"expired":"pending"}}function Yh(e){let t=af(e);return Array.isArray(t)?t.filter((r)=>typeof r==="string"):[]}function Rs(e){return{id:String(e.id),organizationId:String(e.organization_id),slug:String(e.slug),name:String(e.name),issuer:String(e.issuer),clientId:String(e.client_id),hasClientSecret:typeof e.client_secret_ciphertext==="string"&&e.client_secret_ciphertext.length>0,scopes:Yh(e.scopes),allowedDomains:Yh(e.allowed_domains),defaultRole:String(e.default_role),enabled:Number(e.enabled)===1,enforceSso:Number(e.enforce_sso)===1,createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Xh(e,t){let r=Wt(e.consumed_at),n=String(e.expires_at);return{id:String(e.id),providerId:String(e.provider_id),redirectUri:String(e.redirect_uri),returnPath:String(e.return_path),expiresAt:n,consumedAt:r,createdAt:String(e.created_at),state:r?"consumed":n<=t?"expired":"pending"}}function ly(e){return{id:String(e.id),providerId:String(e.provider_id),identityId:String(e.identity_id),subject:String(e.subject),email:String(e.email),linkedAt:String(e.linked_at),lastLoginAt:String(e.last_login_at)}}class ps{controlPlane;nowFn;idFn;encryptionKey;constructor(e,t={}){this.controlPlane=e;this.nowFn=t.now??(()=>new Date),this.idFn=t.id??(()=>crypto.randomUUID()),this.encryptionKey=t.encryptionKey?qh("sha256").update(t.encryptionKey).digest():void 0}now(){return this.nowFn().toISOString()}run(e,t){this.controlPlane.database.run(e,t)}encrypt(e){if(!this.encryptionKey)throw Error("Authentication encryption key is not configured");let t=Pr(12),r=ny("aes-256-gcm",this.encryptionKey,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.encryptionKey)throw Error("Authentication encryption key is not configured");let[t,r,n,i]=e.split(".");if(t!=="v1"||!r||!n||!i)throw Error("Encrypted authentication value is unavailable");let a=iy("aes-256-gcm",this.encryptionKey,Buffer.from(r,"base64url"));return a.setAuthTag(Buffer.from(n,"base64url")),Buffer.concat([a.update(Buffer.from(i,"base64url")),a.final()]).toString("utf8")}createIdentity(e){if(!this.controlPlane.getActor(e.actorId))throw Error("Authentication actor was not found");let t=ay(e.username),r=Md(e.email),n=e.id??this.idFn(),i=this.now();return this.run(`INSERT INTO auth_identities (id, actor_id, username, email, email_verified_at, password_hash, requires_password_upgrade, created_at, updated_at)
40
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n,e.actorId,t,r??null,e.emailVerified&&r?i:null,e.passwordHash,e.requiresPasswordUpgrade?1:0,i,i]),this.getIdentity(n)}getIdentity(e){let t=this.controlPlane.database.query("SELECT * FROM auth_identities WHERE id = ?").get(e);return t?ua(t):void 0}getIdentityByActor(e){let t=this.controlPlane.database.query("SELECT * FROM auth_identities WHERE actor_id = ?").get(e);return t?ua(t):void 0}getIdentityByUsername(e){let t=this.controlPlane.database.query("SELECT * FROM auth_identities WHERE username = ? COLLATE NOCASE").get(e.trim());return t?ua(t):void 0}getIdentityByEmail(e){let t=this.controlPlane.database.query("SELECT * FROM auth_identities WHERE email = ? COLLATE NOCASE").get(e.trim().toLowerCase());return t?ua(t):void 0}listIdentities(){return this.controlPlane.database.query("SELECT * FROM auth_identities ORDER BY username COLLATE NOCASE").all().map(ua)}updatePassword(e,t,r={}){if(!this.getIdentity(e))throw Error("Authentication identity was not found");let i=this.now();return this.controlPlane.transaction(()=>{if(this.run(`UPDATE auth_identities SET password_hash = ?, credential_version = credential_version + 1,
41
+ requires_password_upgrade = ?, updated_at = ? WHERE id = ?`,[t,r.requiresUpgrade?1:0,i,e]),r.revokeSessions!==!1)this.run("UPDATE auth_sessions SET revoked_at = ? WHERE identity_id = ? AND revoked_at IS NULL",[i,e])}),this.getIdentity(e)}rehashPassword(e,t){let r=this.now();this.run("UPDATE auth_identities SET password_hash = ?, requires_password_upgrade = 0, updated_at = ? WHERE id = ?",[t,r,e]);let n=this.getIdentity(e);if(!n)throw Error("Authentication identity was not found");return n}setVerifiedEmail(e,t){let r=Md(t),n=this.now();this.run("UPDATE auth_identities SET email = ?, email_verified_at = ?, updated_at = ? WHERE id = ?",[r,n,n,e]);let i=this.getIdentity(e);if(!i)throw Error("Authentication identity was not found");return i}recordLogin(e){let t=this.now();this.run("UPDATE auth_identities SET last_login_at = ?, updated_at = ? WHERE id = ?",[t,t,e]);let r=this.getIdentity(e);if(!r)throw Error("Authentication identity was not found");return r}setDisabled(e,t){let r=this.now();this.controlPlane.transaction(()=>{if(this.run("UPDATE auth_identities SET disabled_at = ?, credential_version = credential_version + 1, updated_at = ? WHERE id = ?",[t?r:null,r,e]),t)this.run("UPDATE auth_sessions SET revoked_at = ? WHERE identity_id = ? AND revoked_at IS NULL",[r,e])});let n=this.getIdentity(e);if(!n)throw Error("Authentication identity was not found");return n}createActionToken(e,t,r={}){if(!this.getIdentity(e))throw Error("Authentication identity was not found");let n=Pr(32).toString("base64url"),i=this.idFn(),a=this.now(),s=new Date(this.nowFn().getTime()+Math.min(86400000,Math.max(60000,r.ttlMs??tf))).toISOString();return this.run("INSERT INTO auth_action_tokens (id, identity_id, type, token_hash, metadata, expires_at, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[i,e,t,Xt(n),JSON.stringify(r.metadata??{}),s,a]),{actionToken:this.getActionToken(i),token:n}}getActionToken(e){let t=this.controlPlane.database.query("SELECT * FROM auth_action_tokens WHERE id = ?").get(e);return t?Zh(t,this.now()):void 0}consumeActionToken(e,t){return this.controlPlane.transaction(()=>{let r=this.controlPlane.database.query("SELECT * FROM auth_action_tokens WHERE token_hash = ? AND type = ?").get(Xt(e),t);if(!r)throw Error("Action token is invalid");let n=Zh(r,this.now());if(n.state!=="pending")throw Error(`Action token is ${n.state}`);if(this.controlPlane.database.run("UPDATE auth_action_tokens SET consumed_at = ? WHERE id = ? AND consumed_at IS NULL AND expires_at > ?",[this.now(),n.id,this.now()]).changes!==1)throw Error("Action token is no longer available");return this.getActionToken(n.id)})}revokeActionTokens(e,t){return this.controlPlane.database.run("UPDATE auth_action_tokens SET consumed_at = ? WHERE identity_id = ? AND type = ? AND consumed_at IS NULL",[this.now(),e,t]).changes}createSession(e){let t=this.getIdentity(e.identityId);if(!t||t.disabledAt)throw Error("Authentication identity is unavailable");let r=this.idFn(),n=Pr(32).toString("base64url"),i=`v2.${r}.${n}`,a=this.now(),s=Math.min(86400000,Math.max(60000,e.idleTtlMs??ef)),d=Math.min(2592000000,Math.max(s,e.absoluteTtlMs??rn));return this.run(`INSERT INTO auth_sessions (id, identity_id, token_hash, credential_version, auth_method, user_agent, network_hint,
42
+ created_at, last_used_at, idle_expires_at, absolute_expires_at, recent_auth_at, mfa_at)
43
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[r,t.id,Xt(i),t.credentialVersion,e.authMethod??"local",e.userAgent?.slice(0,256)??null,e.networkHint?.slice(0,128)??null,a,a,new Date(this.nowFn().getTime()+s).toISOString(),new Date(this.nowFn().getTime()+d).toISOString(),e.recentAuthAt??a,e.mfaAt??null]),{session:this.getSession(r),token:i}}getSession(e){let t=this.controlPlane.database.query("SELECT * FROM auth_sessions WHERE id = ?").get(e);return t?Qd(t,this.now()):void 0}verifySessionToken(e){let t=/^v2\.([^.]+)\.[A-Za-z0-9_-]{40,}$/.exec(e);if(!t)return;let r=this.controlPlane.database.query("SELECT * FROM auth_sessions WHERE id = ? AND token_hash = ?").get(t[1],Xt(e));if(!r)return;let n=Qd(r,this.now()),i=this.getIdentity(n.identityId);if(!i||i.disabledAt||n.state!=="active"||n.credentialVersion!==i.credentialVersion)return;let a=this.now(),s=new Date(r.idle_expires_at).getTime()-new Date(r.last_used_at).getTime();return this.run("UPDATE auth_sessions SET last_used_at = ?, idle_expires_at = ? WHERE id = ?",[a,new Date(Math.min(this.nowFn().getTime()+s,new Date(n.absoluteExpiresAt).getTime())).toISOString(),n.id]),{identity:i,session:this.getSession(n.id)}}listSessions(e,t={}){let r=this.controlPlane.database.query("SELECT * FROM auth_sessions WHERE identity_id = ? ORDER BY last_used_at DESC").all(e).map((n)=>Qd(n,this.now()));return t.includeInactive?r:r.filter((n)=>n.state==="active")}revokeSession(e,t){return this.controlPlane.database.run("UPDATE auth_sessions SET revoked_at = ? WHERE id = ? AND identity_id = ? AND revoked_at IS NULL",[this.now(),t,e]).changes===1}revokeOtherSessions(e,t){return this.controlPlane.database.run("UPDATE auth_sessions SET revoked_at = ? WHERE identity_id = ? AND id != ? AND revoked_at IS NULL",[this.now(),e,t]).changes}getMfaFactor(e){let t=this.controlPlane.database.query("SELECT * FROM auth_mfa_factors WHERE identity_id = ?").get(e);return t?Kh(t):void 0}beginTotpEnrollment(e,t={}){let r=this.getIdentity(e);if(!r)throw Error("Authentication identity was not found");let n=this.getMfaFactor(e);if(n?.state==="active")throw Error("MFA is already enabled");let i=_s(Pr(20)),a=t.label?.trim().slice(0,80)||r.email||r.username,s=n?.id??this.idFn(),d=this.now();return this.controlPlane.transaction(()=>{if(n)this.run("UPDATE auth_mfa_factors SET label = ?, secret_ciphertext = ?, created_at = ?, verified_at = NULL, disabled_at = NULL WHERE id = ?",[a,this.encrypt(i),d,s]);else this.run("INSERT INTO auth_mfa_factors (id, identity_id, label, secret_ciphertext, created_at) VALUES (?, ?, ?, ?, ?)",[s,e,a,this.encrypt(i),d]);this.run("DELETE FROM auth_recovery_codes WHERE identity_id = ?",[e])}),{factor:this.getMfaFactor(e),secret:i,uri:xd({secret:i,account:a,issuer:t.issuer})}}verifyTotpEnrollment(e,t){let r=this.controlPlane.database.query("SELECT * FROM auth_mfa_factors WHERE identity_id = ?").get(e);if(!r||Kh(r).state!=="pending")throw Error("MFA enrollment is not pending");let n=ga(this.decrypt(String(r.secret_ciphertext)),t,this.nowFn().getTime());if(n===void 0)throw Error("Authenticator code is invalid");let i=Array.from({length:10},()=>{let s=_s(Pr(8)).slice(0,12);return`${s.slice(0,4)}-${s.slice(4,8)}-${s.slice(8)}`}),a=this.now();return this.controlPlane.transaction(()=>{this.run("UPDATE auth_mfa_factors SET verified_at = ?, disabled_at = NULL, last_used_step = ? WHERE identity_id = ?",[a,n,e]),this.run("DELETE FROM auth_recovery_codes WHERE identity_id = ?",[e]);for(let s of i)this.run("INSERT INTO auth_recovery_codes (id, identity_id, code_hash, created_at) VALUES (?, ?, ?, ?)",[this.idFn(),e,Xt(`${e}:${s.replace(/-/g,"").toUpperCase()}`),a])}),{factor:this.getMfaFactor(e),recoveryCodes:i}}verifyMfaCode(e,t,r={}){let n=this.controlPlane.database.query("SELECT * FROM auth_mfa_factors WHERE identity_id = ? AND verified_at IS NOT NULL AND disabled_at IS NULL").get(e);if(!n)return{valid:!1};let i=ga(this.decrypt(String(n.secret_ciphertext)),t,this.nowFn().getTime());if(i!==void 0){if(this.controlPlane.database.run("UPDATE auth_mfa_factors SET last_used_step = ? WHERE identity_id = ? AND (last_used_step IS NULL OR last_used_step < ?)",[i,e,i]).changes===1)return{valid:!0,method:"totp"}}let a=t.replace(/[-\s]/g,"").toUpperCase();if(!/^[A-Z2-7]{12}$/.test(a))return{valid:!1};let s=Xt(`${e}:${a}`),d=this.controlPlane.database.query("SELECT * FROM auth_recovery_codes WHERE identity_id = ? AND code_hash = ? AND consumed_at IS NULL").get(e,s);if(!d)return{valid:!1};if(r.consumeRecovery!==!1){if(this.controlPlane.database.run("UPDATE auth_recovery_codes SET consumed_at = ? WHERE id = ? AND consumed_at IS NULL",[this.now(),String(d.id)]).changes!==1)return{valid:!1}}return{valid:!0,method:"recovery"}}remainingRecoveryCodes(e){return Number(this.controlPlane.database.query("SELECT COUNT(*) AS count FROM auth_recovery_codes WHERE identity_id = ? AND consumed_at IS NULL").get(e)?.count??0)}disableMfa(e){let t=this.now();this.controlPlane.transaction(()=>{this.run("UPDATE auth_mfa_factors SET disabled_at = ? WHERE identity_id = ? AND disabled_at IS NULL",[t,e]),this.run("DELETE FROM auth_recovery_codes WHERE identity_id = ?",[e]),this.run("UPDATE auth_mfa_challenges SET consumed_at = ? WHERE identity_id = ? AND consumed_at IS NULL",[t,e])})}createMfaChallenge(e,t){if(this.getMfaFactor(e)?.state!=="active")throw Error("MFA is not enabled");let r=Pr(32).toString("base64url"),n=this.idFn(),i=this.now(),a=new Date(this.nowFn().getTime()+rf).toISOString();return this.controlPlane.transaction(()=>{this.run("UPDATE auth_mfa_challenges SET consumed_at = ? WHERE identity_id = ? AND purpose = ? AND consumed_at IS NULL",[i,e,t]),this.run("INSERT INTO auth_mfa_challenges (id, identity_id, purpose, token_hash, expires_at, created_at) VALUES (?, ?, ?, ?, ?, ?)",[n,e,t,Xt(r),a,i])}),{challenge:this.getMfaChallenge(n),token:r}}getMfaChallenge(e){let t=this.controlPlane.database.query("SELECT * FROM auth_mfa_challenges WHERE id = ?").get(e);return t?Gd(t,this.now()):void 0}inspectMfaChallengeToken(e,t){let r=this.controlPlane.database.query("SELECT * FROM auth_mfa_challenges WHERE token_hash = ? AND purpose = ?").get(Xt(e),t);return r?Gd(r,this.now()):void 0}completeMfaChallenge(e,t,r){let n=this.controlPlane.database.query("SELECT * FROM auth_mfa_challenges WHERE token_hash = ? AND purpose = ?").get(Xt(e),r);if(!n)throw Error("MFA challenge is invalid");let i=Gd(n,this.now());if(i.state!=="pending")throw Error(`MFA challenge is ${i.state}`);let a=this.verifyMfaCode(i.identityId,t);if(!a.valid||!a.method)throw this.run("UPDATE auth_mfa_challenges SET attempts = attempts + 1 WHERE id = ?",[i.id]),Error("Authenticator or recovery code is invalid");if(this.controlPlane.database.run("UPDATE auth_mfa_challenges SET consumed_at = ? WHERE id = ? AND consumed_at IS NULL AND attempts < 5 AND expires_at > ?",[this.now(),i.id,this.now()]).changes!==1)throw Error("MFA challenge is no longer available");return{identity:this.getIdentity(i.identityId),challenge:this.getMfaChallenge(i.id),method:a.method}}markSessionStepUp(e,t=!1){let r=this.now();this.run("UPDATE auth_sessions SET recent_auth_at = ?, mfa_at = CASE WHEN ? = 1 THEN ? ELSE mfa_at END WHERE id = ? AND revoked_at IS NULL",[r,t?1:0,r,e]);let n=this.getSession(e);if(!n)throw Error("Authentication session was not found");return n}isRecentlyAuthenticated(e,t=600000){return this.nowFn().getTime()-new Date(e.recentAuthAt).getTime()<=t}upsertOidcProvider(e){if(!this.controlPlane.getOrganization(e.organizationId))throw Error("OIDC provider organization was not found");let t=sy(e.slug),r=e.name.trim().slice(0,80);if(!r)throw Error("OIDC provider name is required");let n=oy(e.issuer),i=e.clientId.trim();if(!i||i.length>512)throw Error("OIDC client ID is required");let a=cy(e.scopes),s=dy(e.allowedDomains),d=e.id?this.getOidcProvider(e.id):this.getOidcProviderBySlug(t),c=this.now();if(d){if(d.organizationId!==e.organizationId)throw Error("OIDC provider belongs to another organization");return this.run(`UPDATE auth_oidc_providers SET slug = ?, name = ?, issuer = ?, client_id = ?,
44
+ client_secret_ciphertext = COALESCE(?, client_secret_ciphertext), scopes = ?, allowed_domains = ?,
45
+ default_role = ?, enabled = ?, enforce_sso = ?, updated_at = ? WHERE id = ?`,[t,r,n,i,e.clientSecret?this.encrypt(e.clientSecret):null,JSON.stringify(a),JSON.stringify(s),e.defaultRole??d.defaultRole,e.enabled??d.enabled?1:0,e.enforceSso??d.enforceSso?1:0,c,d.id]),this.getOidcProvider(d.id)}if(!e.clientSecret)throw Error("OIDC client secret is required for a new provider");let o=e.id??this.idFn();return this.run(`INSERT INTO auth_oidc_providers (id, organization_id, slug, name, issuer, client_id,
46
+ client_secret_ciphertext, scopes, allowed_domains, default_role, enabled, enforce_sso, created_at, updated_at)
47
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[o,e.organizationId,t,r,n,i,this.encrypt(e.clientSecret),JSON.stringify(a),JSON.stringify(s),e.defaultRole??"viewer",e.enabled===!1?0:1,e.enforceSso?1:0,c,c]),this.getOidcProvider(o)}getOidcProvider(e){let t=this.controlPlane.database.query("SELECT * FROM auth_oidc_providers WHERE id = ?").get(e);return t?Rs(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?Rs(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(Rs).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:Rs(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(),a=Pr(32).toString("base64url"),s=Pr(32).toString("base64url"),d=Pr(64).toString("base64url"),c=this.now(),o=new Date(this.nowFn().getTime()+nf).toISOString();return this.run(`INSERT INTO auth_oidc_transactions (id, provider_id, state_hash, nonce_ciphertext, verifier_ciphertext,
48
+ redirect_uri, return_path, expires_at, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i,e,Xt(a),this.encrypt(s),this.encrypt(d),t,r,o,c]),{transaction:this.getOidcTransaction(i),state:a,nonce:s,verifier:d}}getOidcTransaction(e){let t=this.controlPlane.database.query("SELECT * FROM auth_oidc_transactions WHERE id = ?").get(e);return t?Xh(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,Xt(t));if(!r)throw Error("OIDC transaction is invalid");let n=Xh(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?ly(r):void 0}linkOidcSubject(e,t,r,n){let i=this.getOidcProvider(e),a=this.getIdentity(t);if(!i||!a)throw Error("OIDC provider or identity was not found");let s=Md(n);if(!r.trim()||r.length>512)throw Error("OIDC subject is invalid");let d=this.getOidcSubject(e,r);if(d&&d.identityId!==t)throw Error("OIDC subject is already linked to another identity");let c=this.now();if(d)return this.run("UPDATE auth_oidc_subjects SET email = ?, last_login_at = ? WHERE id = ?",[s,c,d.id]),this.getOidcSubject(e,r);let o=this.idFn();return this.run("INSERT INTO auth_oidc_subjects (id, provider_id, identity_id, subject, email, linked_at, last_login_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[o,e,t,r,s,c,c]),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 ha(e,t){let r=e.notifications?.email?.from;if(!r)return!1;try{let{EmailClient:n}=await import("./chunk-0k1cs6pp.js");return await new n({region:e.project.region,defaultFrom:r}).send(t),!0}catch{return!1}}import{randomBytes as gy}from"node:crypto";import{chmodSync as uy,existsSync as hy,mkdirSync as fy,readFileSync as Sy,writeFileSync as _y}from"node:fs";import{dirname as Ry}from"node:path";function py(){return fa("auth-encryption-key")}function nn(e){let t=process.env.TS_CLOUD_AUTH_ENCRYPTION_KEY?.trim();if(t)return t;let r=_t(e,"auth-encryption-key");try{if(hy(r)){let i=Sy(r,"utf8").trim();if(i)return i}}catch{}let n=gy(32).toString("base64url");try{fy(Ry(r),{recursive:!0,mode:448}),_y(r,`${n}
49
+ `,{mode:384}),uy(r,384)}catch{}return n}import{constants as sf,createHash as Zd,createPublicKey as Iy,createVerify as my,timingSafeEqual as Ey}from"node:crypto";var df=new Set(["RS256","PS256","ES256"]),of=60;function Is(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 Kd(e,t){if(!e||typeof e!=="object"||Array.isArray(e))throw Error(`${t} is invalid`);return e}async function Yd(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 Kd(JSON.parse(i),t)}catch(a){if(a instanceof Error&&a.message===`${t} is invalid`)throw a;throw Error(`${t} returned invalid JSON`)}}function yy(e,t){let r=Zd("sha256").update(e).digest(),n=Zd("sha256").update(t).digest();return Ey(r,n)}function cf(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 Xd(e,t=fetch){let r=Is(e.issuer,"OIDC issuer"),n=new URL(`${r.pathname.replace(/\/$/,"")}/.well-known/openid-configuration`,r.origin),i=await Yd(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}`);Is(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 a=Array.isArray(i.id_token_signing_alg_values_supported)?i.id_token_signing_alg_values_supported.filter((s)=>typeof s==="string"):[];if(a.length>0&&!a.some((s)=>df.has(s)))throw Error("OIDC provider does not offer a supported ID-token signing algorithm");return i}async function qd(e,t,r,n,i=fetch){let a=e.getOidcProviderBySlug(t);if(!a?.enabled)throw Error("OIDC provider is unavailable");let s=Is(r,"Application origin").origin,d=await Xd(a,i),c=`${s}/auth/oidc/${encodeURIComponent(a.slug)}/callback`,o=e.beginOidcTransaction(a.id,c,cf(n)),g=new URL(d.authorization_endpoint);return g.searchParams.set("response_type","code"),g.searchParams.set("client_id",a.clientId),g.searchParams.set("redirect_uri",c),g.searchParams.set("scope",a.scopes.join(" ")),g.searchParams.set("state",o.state),g.searchParams.set("nonce",o.nonce),g.searchParams.set("code_challenge",Zd("sha256").update(o.verifier).digest("base64url")),g.searchParams.set("code_challenge_method","S256"),{authorizationUrl:g.href,expiresAt:o.transaction.expiresAt}}function wy(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:Kd(JSON.parse(Buffer.from(t[0],"base64url").toString("utf8")),"OIDC ID-token header"),claims:Kd(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 Ay(e,t,r){let n=wy(e),i=typeof n.header.alg==="string"?n.header.alg:"",a=typeof n.header.kid==="string"?n.header.kid:"";if(!df.has(i)||!a)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 Yd(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 d=s.keys.find((h)=>{if(!h||typeof h!=="object"||Array.isArray(h))return!1;let _=h;return _.kid===a&&(!_.alg||_.alg===i)&&(!_.use||_.use==="sig")});if(!d)throw Error("OIDC ID-token signing key was not found");let c=Iy({key:d,format:"jwk"}),o=my("SHA256").update(n.signingInput).end();if(!(i==="PS256"?o.verify({key:c,padding:sf.RSA_PKCS1_PSS_PADDING,saltLength:32},n.signature):i==="ES256"?o.verify({key:c,dsaEncoding:"ieee-p1363"},n.signature):o.verify(c,n.signature)))throw Error("OIDC ID-token signature is invalid");return n.claims}function Py(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((c)=>typeof c==="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 a=Math.floor(n.getTime()/1000);if(typeof e.exp!=="number"||e.exp<a-of)throw Error("OIDC ID token is expired");if(typeof e.iat!=="number"||e.iat>a+of)throw Error("OIDC ID-token issued-at time is invalid");if(typeof e.nonce!=="string"||!yy(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 d=s.split("@")[1];if(!d||!t.allowedDomains.includes(d))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 ec(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=Is(t.origin,"Application origin").origin,a=e.consumeOidcTransaction(n.id,t.state),s=`${i}/auth/oidc/${encodeURIComponent(n.slug)}/callback`;if(a.transaction.redirectUri!==s)throw Error("OIDC callback redirect URI does not match the original request");let{clientSecret:d}=e.getOidcProviderCredentials(n.id),c=await Xd(n,r),o=new URLSearchParams({grant_type:"authorization_code",code:t.code,redirect_uri:a.transaction.redirectUri,code_verifier:a.verifier}),g={accept:"application/json","content-type":"application/x-www-form-urlencoded"},h=c.token_endpoint_auth_methods_supported??["client_secret_basic"];if(h.includes("client_secret_basic")){let E=($)=>new URLSearchParams({value:$}).toString().slice(6),y=`${E(n.clientId)}:${E(d)}`;g.authorization=`Basic ${Buffer.from(y).toString("base64")}`}else if(h.includes("client_secret_post"))o.set("client_id",n.clientId),o.set("client_secret",d);else throw Error("OIDC provider does not support a configured client authentication method");let _=await Yd(await r(c.token_endpoint,{method:"POST",headers:g,body:o,redirect:"error",signal:AbortSignal.timeout(1e4)}),"OIDC token exchange");if(typeof _.id_token!=="string")throw Error("OIDC token response did not include an ID token");let R=await Ay(_.id_token,c,r);return{identity:Py(R,n,a.nonce,t.now??new Date),returnPath:a.transaction.returnPath}}import{createHash as Dy,randomBytes as $y}from"node:crypto";var gf=new Set(ms),uf=7776000000,hf=31536000000,ff=86400000;function Dr(e){return typeof e==="string"?e:void 0}function lf(e){return Dy("sha256").update(e).digest("hex")}function Cy(e){try{let t=JSON.parse(String(e));return Array.isArray(t)?t.filter((r)=>typeof r==="string"&&gf.has(r)):[]}catch{return[]}}function ky(e){let t=String(e.scope_type);return t==="organization"?{type:t}:{type:t,id:String(e.scope_id)}}function tc(e){let t=Dr(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:Dr(e.description),createdByActorId:Dr(e.created_by_actor_id),disabledAt:t,createdAt:String(e.created_at),updatedAt:String(e.updated_at),state:t?"disabled":"active"}}function rc(e,t){let r=Dr(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:Cy(e.capabilities),scope:ky(e),expiresAt:n,lastUsedAt:Dr(e.last_used_at),lastNetworkHint:Dr(e.last_network_hint),revokedAt:r,rotatedFromTokenId:Dr(e.rotated_from_token_id),createdByActorId:Dr(e.created_by_actor_id),createdAt:String(e.created_at),updatedAt:String(e.updated_at),state:r?"revoked":n<=t?"expired":"active"}}function by(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:Dr(e.operation_id),responseStatus:Number(e.response_status),responseBody:t,expiresAt:String(e.expires_at),createdAt:String(e.created_at)}}class Es{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(),a=this.now();this.run(`INSERT INTO service_accounts (id, organization_id, actor_id, slug, name, description, created_by_actor_id, created_at, updated_at)
50
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i,e.organizationId,n.id,t,r,e.description?.trim().slice(0,500)||null,e.createdByActorId??null,a,a]);let s=this.controlPlane.createMembership({organizationId:e.organizationId,actorId:n.id,roleTemplate:e.roleTemplate,scope:e.scope,source:"manual",performedByActorId:e.createdByActorId}),d=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:d.type,id:d.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?tc(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?tc(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(tc).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((_)=>!gf.has(_)))throw Error("API token requires valid explicit capabilities");let i=e.scope??r.scope,a=this.controlPlane.resolveAuthorizationTarget(t.organizationId,i);if(!a)throw Error("API token scope was not found in this organization");for(let _ of n)if(!qt({membership:r,grants:this.controlPlane.listGrants(r.id),capability:_,target:a}).allowed)throw Error(`Service-account membership does not grant ${_} at the token scope`);let s=e.expiresAt?new Date(e.expiresAt):new Date(this.nowFn().getTime()+uf);if(!Number.isFinite(s.getTime())||s.getTime()<=this.nowFn().getTime()+60000||s.getTime()>this.nowFn().getTime()+hf)throw Error("API token expiry must be between one minute and one year from now");let d=this.idFn(),c=$y(32).toString("base64url"),o=`tsc_v1.${d}.${c}`,g=`tsc_v1.${d.slice(0,8)}`,h=this.now();return this.run(`INSERT INTO api_tokens (id, service_account_id, name, token_hash, token_prefix, capabilities, scope_type, scope_id,
51
+ expires_at, rotated_from_token_id, created_by_actor_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[d,t.id,e.name.trim().slice(0,100)||"API token",lf(o),g,JSON.stringify(n.sort()),i.type,i.type==="organization"?null:i.id??null,s.toISOString(),e.rotatedFromTokenId??null,e.createdByActorId??null,h,h]),this.controlPlane.appendEvent({organizationId:t.organizationId,actorId:e.createdByActorId,type:"api.token.created",payload:{serviceAccountId:t.id,tokenId:d,prefix:g,capabilities:n,scope:{type:i.type,id:i.id??null},expiresAt:s.toISOString(),rotatedFromTokenId:e.rotatedFromTokenId??null}}),{token:this.getToken(d),secret:o}}getToken(e){let t=this.controlPlane.database.query("SELECT * FROM api_tokens WHERE id = ?").get(e);return t?rc(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)=>rc(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],lf(e));if(!n)return;let i=rc(n,this.now()),a=this.getServiceAccount(i.serviceAccountId);if(!a||a.state!=="active"||i.state!=="active")return;let s=this.controlPlane.getActor(a.actorId),d=this.controlPlane.getMembershipForActor(a.organizationId,a.actorId);if(!s||s.disabledAt||!d||d.status!=="active")return;let c=this.now(),o=!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 = ?",[c,t?.slice(0,128)??null,c,i.id]),o)this.controlPlane.appendEvent({organizationId:a.organizationId,actorId:s.id,type:"api.token.used",payload:{serviceAccountId:a.id,tokenId:i.id,prefix:i.prefix}});return{serviceAccount:a,token:this.getToken(i.id),actor:s,membership:d}}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?by(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()+ff).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)
52
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[r,e.tokenId,e.key,e.requestHash,e.operationId??null,e.responseStatus,JSON.stringify(e.responseBody),i,n]),this.getIdempotency(e.tokenId,e.key)}purgeExpired(){let e=this.now(),t=this.controlPlane.database.run("DELETE FROM api_tokens WHERE (expires_at < ? OR revoked_at IS NOT NULL) AND created_at < ?",[e,new Date(this.nowFn().getTime()-2592000000).toISOString()]).changes,r=this.controlPlane.database.run("DELETE FROM api_idempotency_records WHERE expires_at < ?",[e]).changes;return{tokens:t,idempotency:r}}}import{isIP as yf}from"node:net";var vy={every_minute:"* * * * *",every_five_minutes:"*/5 * * * *",hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 0"},Oy={JAN:1,FEB:2,MAR:3,APR:4,MAY:5,JUN:6,JUL:7,AUG:8,SEP:9,OCT:10,NOV:11,DEC:12},Sf={SUN:0,MON:1,TUE:2,WED:3,THU:4,FRI:5,SAT:6};function _f(e){try{return new Intl.DateTimeFormat("en",{timeZone:e}).format(new Date),e}catch{throw Error(`Unknown schedule timezone: ${e}`)}}function ys(e,t,r,n){let i=t[e.toUpperCase()]??Number(e);if(!Number.isInteger(i)||i<r||i>n)throw Error(`Schedule field value ${e} is outside ${r}-${n}.`);return i}function pi(e,t,r,n={},i){if(e==="*"||e==="?")return;let a=new Set;for(let s of e.split(",")){let[d,c]=s.split("/"),o=c?ys(c,{},1,r-t+1):1,g,h;if(d==="*")g=t,h=r;else if(d.includes("-")){let _=d.split("-");g=ys(_[0],n,t,r),h=ys(_[1],n,t,r)}else g=ys(d,n,t,r),h=g;if(h<g)throw Error("Schedule ranges must be ascending.");for(let _=g;_<=h;_+=o)a.add(i?i(_):_===7&&r===7?0:_)}return a}function By(e,t){let r=Object.fromEntries(new Intl.DateTimeFormat("en-US",{timeZone:t,year:"numeric",month:"numeric",day:"numeric",weekday:"short",hour:"numeric",minute:"numeric",hourCycle:"h23"}).formatToParts(e).map((n)=>[n.type,n.value]));return{minute:Number(r.minute),hour:Number(r.hour),day:Number(r.day),month:Number(r.month),weekday:Sf[r.weekday.toUpperCase()],year:Number(r.year),key:`${r.year}-${r.month}-${r.day} ${r.hour}:${r.minute}`}}function Rf(e){let r=(e.startsWith("cron(")?e.slice(5,-1).trim():e.trim()).split(/\s+/);if(r.length!==5&&r.length!==6)throw Error("Cron schedules require five standard fields or six EventBridge fields.");let[n,i,a,s,d,c]=r,o=r.length===6;return{minute:pi(n,0,59),hour:pi(i,0,23),day:pi(a,1,31),month:pi(s,1,12,Oy),weekday:pi(d,o?1:0,7,Sf,o?(g)=>g===7?6:g-1:void 0),year:c?pi(c,1970,2199):void 0,dayWildcard:a==="*"||a==="?",weekdayWildcard:d==="*"||d==="?"}}function Jy(e,t){if(!((!t.minute||t.minute.has(e.minute))&&(!t.hour||t.hour.has(e.hour))&&(!t.month||t.month.has(e.month))&&(!t.year||t.year.has(e.year))))return!1;let n=!t.day||t.day.has(e.day),i=!t.weekday||t.weekday.has(e.weekday);return t.dayWildcard?i:t.weekdayWildcard?n:n||i}function pf(e){let t=/^rate\(\s*(\d+)\s+(minute|minutes|hour|hours|day|days)\s*\)$/i.exec(e);if(!t)return;let r=Number(t[1]);if(r<1)throw Error("Rate amount must be positive.");return r*(t[2].toLowerCase().startsWith("minute")?60000:t[2].toLowerCase().startsWith("hour")?3600000:86400000)}function an(e){let t=e.trim(),r=vy[t.toLowerCase()]??t;if(!r)throw Error("Schedule expression is required.");let n=pf(r);if(n){let i=n/60000;return{original:t,normalized:`rate(${i} minutes)`,kind:"rate",description:i%1440===0?`Every ${i/1440} day(s)`:i%60===0?`Every ${i/60} hour(s)`:`Every ${i} minute(s)`}}return Rf(r),{original:t,normalized:r.startsWith("cron(")?r:`cron(${r})`,kind:"cron",description:`Cron ${r.replace(/^cron\(|\)$/g,"")}`}}function zn(e,t,r=new Date,n=5){let i=an(e),a=_f(t),s=Math.min(20,Math.max(1,n)),d=pf(i.normalized);if(d)return Array.from({length:s},(R,E)=>new Date(r.getTime()+d*(E+1)).toISOString());let c=Rf(i.normalized),o=[],g=new Set,h=new Date(Math.floor(r.getTime()/60000)*60000+60000),_=0;while(o.length<s&&_<1100000){let R=By(h,a);if(Jy(R,c)&&!g.has(R.key))o.push(h.toISOString()),g.add(R.key);h=new Date(h.getTime()+60000),_++}if(o.length<s)throw Error("Schedule produced no runs within the bounded preview horizon.");return o}function Wn(e,t="UTC",r=new Date,n=5){let i=an(e),a=zn(i.normalized,t,r,n),s=i.kind==="cron"?["Server cron and EventBridge use the same wall-clock preview; provider-specific extensions are retained only when supported."]:["Rate schedules use elapsed-time intervals and are not shifted by DST."];return{...i,timezone:_f(t),nextRuns:a,capabilities:{server:i.kind==="cron",eventbridge:!0,notes:s}}}function Sa(e){let t=an(e.expression),r=t.normalized.slice(5,-1).trim().split(/\s+/),n=t.kind==="cron"&&r.length===5;if(e.provider==="server")return{provider:"server",supported:n,features:{timezone:!0,flexibleWindow:!1,catchUp:!1,replaceOverlap:!1},notes:[t.kind==="rate"?"Server cron requires a cron expression; use an equivalent cron schedule.":r.length!==5?"EventBridge six-field cron extensions cannot be installed as server cron.":"Cron is reconciled through a root-owned ts-cloud entry.",e.missedRunPolicy==="catch_up"?"Catch-up is handled by the control plane, not cron.":"Missed runs are skipped by cron."]};if(e.provider==="eventbridge")return{provider:"eventbridge",supported:!0,features:{timezone:!0,flexibleWindow:!0,catchUp:!1,replaceOverlap:!1},notes:["Five-field cron is translated explicitly to EventBridge six-field syntax. Flexible windows are provider-native; overlap and catch-up remain control-plane policies."]};if(e.provider==="lambda")return{provider:"lambda",supported:!0,features:{timezone:!0,flexibleWindow:!0,catchUp:!1,replaceOverlap:!1},notes:["The schedule invokes one immutable Lambda target."]};return{provider:"platform",supported:!0,features:{timezone:!0,flexibleWindow:!0,catchUp:!0,replaceOverlap:!0},notes:["The durable control-plane worker enforces all configured policies."]}}function ws(e){let t=Sa({...e,provider:"server"});if(!t.supported)throw Error(t.notes.join(" "));let n=an(e.expression).normalized.slice(5,-1);return{path:`/etc/cron.d/ts-cloud-${e.id}`,content:`CRON_TZ=${e.timezone}
53
+ ${n} root /usr/local/bin/cloud jobs:dispatch ${e.id} --scheduled >/dev/null 2>&1
54
+ `}}function Ty(e){let t=an(e);if(t.kind==="rate")return e;let r=t.normalized.slice(5,-1).trim().split(/\s+/);if(r.length===6)return t.normalized;let[n,i,a,s,d]=r,c=d==="*"?"?":d.replace(/(^|[,-])0(?=$|[,-])/g,(o,g)=>`${g}1`);return a==="*"&&d!=="*"?`cron(${n} ${i} ? ${s} ${c} *)`:`cron(${n} ${i} ${a} ${s} ? *)`}function If(e){let t=Sa(e);if(!t.supported)throw Error(t.notes.join(" "));return{Name:`ts-cloud-${e.id}`,ScheduleExpression:Ty(e.expression),ScheduleExpressionTimezone:e.timezone,State:e.enabled?"ENABLED":"DISABLED",FlexibleTimeWindow:e.flexibleMinutes?{Mode:"FLEXIBLE",MaximumWindowInMinutes:e.flexibleMinutes}:{Mode:"OFF"},Target:{kind:e.target.kind,functionName:e.target.functionName??null,payloadRefs:e.payloadRefs},RetryPolicy:{MaximumRetryAttempts:e.retryPolicy.maxAttempts,MaximumEventAgeInSeconds:e.timeoutSeconds},DeadLetterRef:e.retryPolicy.deadLetterRef??null}}function oO(e,t){if(!t)return{status:"unavailable",observedState:{message:"Provider observation is unavailable."}};let r=String(t.expression??""),n=t.enabled;return{status:r&&r!==e.normalizedExpression||typeof n==="boolean"&&n!==e.enabled?"drifted":"in_sync",observedState:t}}function zy(e){if(e.provider==="server"){let t=ws(e);return{path:t.path,content:t.content,enabled:e.enabled}}if(e.provider==="eventbridge")return If(e);throw Error(`No reconciliation adapter is configured for ${e.provider} schedules.`)}function nc(e,t){if(Array.isArray(e))return Array.isArray(t)&&e.length===t.length&&e.every((r,n)=>nc(r,t[n]));if(e&&typeof e==="object"){if(!t||typeof t!=="object"||Array.isArray(t))return!1;return Object.entries(e).every(([r,n])=>nc(n,t[r]))}return e===t}class Wy{transport;provider="server";constructor(e){this.transport=e}async observe(e){let t=ws(e),r=await this.transport.read(t.path);return r==null?void 0:{path:t.path,content:r,enabled:!0}}async apply(e,t){let r=String(t.path??"");if(!e.enabled){await this.transport.removeRootOwned(r);return}await this.transport.writeRootOwned(r,String(t.content??""))}async remove(e){await this.transport.removeRootOwned(ws(e).path)}matches(e,t){if(e.enabled===!1)return!1;return e.path===t.path&&e.content===t.content}}class jy{transport;provider="eventbridge";constructor(e){this.transport=e}observe(e){return this.transport.get(`ts-cloud-${e.id}`)}apply(e,t){return this.transport.put(t)}remove(e){return this.transport.remove(`ts-cloud-${e.id}`)}matches(e,t){return nc(e,t)}}class Uy{store;constructor(e){this.store=e}async reconcile(e,t,r={}){if(t.provider!==e.provider)return this.store.reconcile(e.id,"unsupported",{provider:t.provider,message:`Adapter ${t.provider} cannot reconcile ${e.provider}.`});try{let n=zy(e),i=await t.observe(e);if(i&&t.matches(n,i))return this.store.reconcile(e.id,"in_sync",{provider:t.provider,observed:i});if(r.apply===!1)return this.store.reconcile(e.id,i?"drifted":"unavailable",{provider:t.provider,observed:i??null,applyRequired:!0});if(await t.apply(e,n),!e.enabled)return this.store.reconcile(e.id,"in_sync",{provider:t.provider,observed:null,disabled:!0});let a=await t.observe(e);return this.store.reconcile(e.id,a&&t.matches(n,a)?"in_sync":"drifted",{provider:t.provider,observed:a??null,applied:!0})}catch(n){return this.store.reconcile(e.id,"unavailable",{provider:t.provider,error:n instanceof Error?n.message:String(n)})}}async remove(e,t){if(e.origin==="config")throw Error("Config-defined jobs must be removed from configuration, not destructively deleted.");if(t.provider!==e.provider)throw Error(`Adapter ${t.provider} cannot remove ${e.provider}.`);await t.remove(e),this.store.remove(e.id)}}function Hy(e){if(e.queues===!0)return[{queue:"default",processes:e.queueConcurrency??1}];if(!Array.isArray(e.queues))return[];return e.queues.map((t)=>{if(typeof t==="string")return{queue:t,processes:e.queueConcurrency??1};let[r,n]=Object.entries(t)[0]??["default",e.queueConcurrency??1];return{queue:r,processes:n}})}function ic(e,t,r){let n=new Set,i=new Set,a=new Map(r.resources.map((h)=>[h.slug,h])),s=0,d=0;for(let[h,_]of Object.entries(t.sites??{})){let R=a.get(h);if(_.scheduler){let $=`config:site:${h}:scheduler`;n.add($),e.upsertConfigJob({organizationId:r.organization.id,projectId:r.project.id,environmentId:r.environment.id,resourceId:R?.id,name:`${h} scheduler`,provider:"server",expression:"* * * * *",timezone:"UTC",flexibleMinutes:0,target:{kind:"dashboard_operation",operationId:`scheduler:run:${h}`},payloadRefs:{},missedRunPolicy:"skip",overlapPolicy:"forbid",retryPolicy:{maxAttempts:3,backoffSeconds:30},timeoutSeconds:300,enabled:!0,origin:"config",sourceKey:$,observedState:{source:"cloud.config.ts"},reconciliationStatus:"pending"}),s++}let E=_,y=Array.isArray(E.queues??E.workers)?E.queues??E.workers:[];for(let[$,b]of y.entries()){let z=typeof b==="string"?{queue:b}:b,C=String(z.queue??z.name??"default"),B=`config:site:${h}:worker:${$}:${C}`;i.add(B),e.upsertWorker({organizationId:r.organization.id,projectId:r.project.id,environmentId:r.environment.id,resourceId:R?.id,name:`${h}:${C}`,provider:"systemd",queue:C,processes:Number(z.processes)||1,timeoutSeconds:Number(z.timeout)||60,restartPolicy:"always",target:{operationId:`worker:restart:${h}`,site:h},enabled:!0,origin:"config",sourceKey:B,observedState:{source:"cloud.config.ts",currentJob:null,failures:0},reconciliationStatus:"pending"}),d++}}let c=t.infrastructure?.compute?.backups;if(c?.enabled)n.add("config:platform:backup"),e.upsertConfigJob({organizationId:r.organization.id,projectId:r.project.id,environmentId:r.environment.id,name:"Scheduled backup",provider:"server",expression:String(c.schedule??"0 2 * * *"),timezone:String(c.timezone??"UTC"),flexibleMinutes:0,target:{kind:"dashboard_operation",operationId:"backup:run"},payloadRefs:{},missedRunPolicy:"skip",overlapPolicy:"forbid",retryPolicy:{maxAttempts:3,backoffSeconds:60},timeoutSeconds:3600,enabled:!0,origin:"config",sourceKey:"config:platform:backup",observedState:{source:"cloud.config.ts"},reconciliationStatus:"pending"}),s++;let o=t.environments?.[r.environment.slug]?.app;if(o){if(o.scheduler!=="off"){let h=`config:serverless:${r.environment.slug}:scheduler`;n.add(h),e.upsertConfigJob({organizationId:r.organization.id,projectId:r.project.id,environmentId:r.environment.id,name:`${r.environment.name} serverless scheduler`,provider:"eventbridge",expression:"rate(1 minute)",timezone:"UTC",flexibleMinutes:0,target:{kind:"serverless_scheduler",action:"schedule:run"},payloadRefs:{},missedRunPolicy:o.scheduler==="sub-minute"?"catch_up":"skip",overlapPolicy:"forbid",retryPolicy:{maxAttempts:3,backoffSeconds:30},timeoutSeconds:o.cliTimeout??900,enabled:!0,origin:"config",sourceKey:h,observedState:{source:"cloud.config.ts",mode:o.scheduler??"on"},reconciliationStatus:"pending"}),s++}for(let{queue:h,processes:_}of Hy(o)){let R=`config:serverless:${r.environment.slug}:worker:${h}`;i.add(R),e.upsertWorker({organizationId:r.organization.id,projectId:r.project.id,environmentId:r.environment.id,name:`${r.environment.name}:${h}`,provider:"lambda",queue:h,processes:_,timeoutSeconds:o.queueTimeout??120,restartPolicy:"on_failure",target:{function:"queue",queue:h},enabled:!0,origin:"config",sourceKey:R,observedState:{source:"cloud.config.ts",currentJob:null,failures:0},reconciliationStatus:"pending"}),d++}}let g=0;for(let h of e.list(r.project.id,{environmentId:r.environment.id}).filter((_)=>_.origin==="config"&&_.sourceKey&&!n.has(_.sourceKey)))e.reconcile(h.id,"drifted",{...h.observedState,reason:"Definition is no longer present in configuration; retained for non-destructive review."}),g++;for(let h of e.listWorkers(r.project.id,r.environment.id).filter((_)=>_.origin==="config"&&_.sourceKey&&!i.has(_.sourceKey)))e.reconcileWorker(h.id,"drifted",{...h.observedState,reason:"Definition is no longer present in configuration; retained for non-destructive review."}),g++;return{jobs:s,workers:d,drifted:g}}class ac{store;queue;constructor(e,t={}){this.store=e;this.queue=t.queue??new Be(e.controlPlane)}enqueue(e,t){let r=new Date(t.scheduledFor??this.store.now()).toISOString(),n=`${e.id}:${t.trigger==="manual"?crypto.randomUUID():r}`,i=this.store.activeExecution(e.id);if(i&&e.overlapPolicy==="forbid")return this.store.createExecution({jobId:e.id,trigger:t.trigger,scheduledFor:r,idempotencyKey:n,status:"skipped",output:{reason:"overlap_forbidden",activeExecutionId:i.id}});if(i&&e.overlapPolicy==="replace"&&i.operationId)try{this.queue.requestCancellation(i.operationId,t.actorId)}catch{}let a=this.store.createExecution({jobId:e.id,trigger:t.trigger,scheduledFor:r,idempotencyKey:n,status:"queued",output:{semantics:"at_least_once"}});if(a.operationId)return a;let s=this.queue.enqueue({projectId:e.projectId,environmentId:e.environmentId,resourceId:e.resourceId,actorId:t.actorId,kind:"job.execute",input:{jobId:e.id,executionId:a.id},idempotencyKey:`job-execution:${a.id}`,lockKey:e.overlapPolicy==="allow"?`job-execution:${a.id}`:`job:${e.id}`,maxAttempts:e.retryPolicy.maxAttempts,timeoutSeconds:e.timeoutSeconds,retryClasses:["job_transient"],resumePolicy:"requeue"}).operation;return this.store.attachOperation(a.id,s.id)}tick(e=this.store.now()){let t=[];for(let r of this.store.due(e.toISOString())){let n=r.nextRunAt,i=zn(r.normalizedExpression,r.timezone,e,1)[0];if(r.missedRunPolicy==="catch_up"){let a=n,s=0;while(a<=e.toISOString()&&s<10)t.push(this.enqueue(r,{trigger:a===n?"scheduled":"catch_up",scheduledFor:a})),a=zn(r.normalizedExpression,r.timezone,new Date(a),1)[0],s++}else t.push(this.enqueue(r,{trigger:"scheduled",scheduledFor:n}));this.store.markScheduled(r.id,n,i)}return t}}function mf(e){return{"job.execute":async(r)=>{let n=r.operation.input&&typeof r.operation.input==="object"&&!Array.isArray(r.operation.input)?r.operation.input:{},i=e.store.get(String(n.jobId??"")),a=e.store.getExecution(String(n.executionId??""));if(!i||!a)throw Error("Scheduled job execution is no longer available.");e.store.transitionExecution(a.id,"running",{attempt:r.operation.attempt}),r.checkpoint("execute",`Running ${i.name} on ${i.provider}.`),r.log(`Trigger ${a.trigger}; scheduled for ${a.scheduledFor}; semantics at-least-once.`,{stream:"system"});let s=await e.executor(i,i.target,r);if(s.stdout)r.log(s.stdout,{stream:"stdout"});if(s.stderr)r.log(s.stderr,{stream:"stderr"});if(!s.ok){if(e.store.transitionExecution(a.id,r.operation.attempt>=i.retryPolicy.maxAttempts?"dead":"failed",{attempt:r.operation.attempt,error:s.stderr??"Job execution failed."}),s.retryable)throw new As(s.stderr??"Scheduled job failed transiently.","job_transient");throw Error(s.stderr??"Scheduled job failed.")}return e.store.transitionExecution(a.id,"succeeded",{attempt:r.operation.attempt,output:s.output??{}}),{jobId:i.id,executionId:a.id,provider:i.provider}}}}var Rt=(e)=>typeof e==="string"&&e?e:void 0,Ef=(e)=>Number(e)===1,jn=(e)=>{try{return JSON.parse(String(e))}catch{return{}}},sn=(e,t,r,n)=>{let i=Number(e);return Number.isFinite(i)?Math.min(n,Math.max(r,Math.floor(i))):t};function Ps(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:Rt(e.environment_id),resourceId:Rt(e.resource_id),name:String(e.name),provider:String(e.provider),expression:String(e.expression),normalizedExpression:String(e.normalized_expression),timezone:String(e.timezone),startsAt:Rt(e.starts_at),endsAt:Rt(e.ends_at),flexibleMinutes:Number(e.flexible_minutes),target:jn(e.target),payloadRefs:jn(e.payload_refs),missedRunPolicy:String(e.missed_run_policy),overlapPolicy:String(e.overlap_policy),retryPolicy:jn(e.retry_policy),timeoutSeconds:Number(e.timeout_seconds),enabled:Ef(e.enabled),origin:String(e.origin),sourceKey:Rt(e.source_key),ownerActorId:Rt(e.owner_actor_id),observedState:jn(e.observed_state),reconciliationStatus:String(e.reconciliation_status),nextRunAt:Rt(e.next_run_at),lastScheduledFor:Rt(e.last_scheduled_for),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Ds(e){return{id:String(e.id),jobId:String(e.job_id),operationId:Rt(e.operation_id),trigger:String(e.trigger),scheduledFor:String(e.scheduled_for),idempotencyKey:String(e.idempotency_key),status:String(e.status),attempt:Number(e.attempt),startedAt:Rt(e.started_at),finishedAt:Rt(e.finished_at),output:jn(e.output),error:Rt(e.error),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function sc(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:Rt(e.environment_id),resourceId:Rt(e.resource_id),name:String(e.name),provider:String(e.provider),queue:String(e.queue),processes:Number(e.processes),timeoutSeconds:Number(e.timeout_seconds),restartPolicy:String(e.restart_policy),target:jn(e.target),enabled:Ef(e.enabled),origin:String(e.origin),sourceKey:Rt(e.source_key),ownerActorId:Rt(e.owner_actor_id),observedState:jn(e.observed_state),reconciliationStatus:String(e.reconciliation_status),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}class oc{controlPlane;options;constructor(e,t={}){this.controlPlane=e;this.options=t}now(){return this.options.now?.()??new Date}create(e){if(!e.name.trim())throw Error("Scheduled jobs require a name.");let t=Wn(e.expression,e.timezone,this.now(),1),r=crypto.randomUUID(),n=this.now().toISOString(),i=e.startsAt?new Date(e.startsAt).toISOString():void 0,a=e.endsAt?new Date(e.endsAt).toISOString():void 0;if(i&&a&&i>=a)throw Error("Schedule start must be before end.");let s=t.nextRuns.find((d)=>(!i||d>=i)&&(!a||d<=a));return this.controlPlane.database.run("INSERT INTO scheduled_jobs (id,organization_id,project_id,environment_id,resource_id,name,provider,expression,normalized_expression,timezone,starts_at,ends_at,flexible_minutes,target,payload_refs,missed_run_policy,overlap_policy,retry_policy,timeout_seconds,enabled,origin,source_key,owner_actor_id,observed_state,reconciliation_status,next_run_at,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[r,e.organizationId,e.projectId,e.environmentId??null,e.resourceId??null,e.name.trim().slice(0,120),e.provider,e.expression,t.normalized,e.timezone,i??null,a??null,sn(e.flexibleMinutes,0,0,1440),JSON.stringify(e.target),JSON.stringify(e.payloadRefs),e.missedRunPolicy,e.overlapPolicy,JSON.stringify({maxAttempts:sn(e.retryPolicy.maxAttempts,3,1,20),backoffSeconds:sn(e.retryPolicy.backoffSeconds,30,0,86400),deadLetterRef:e.retryPolicy.deadLetterRef}),sn(e.timeoutSeconds,900,1,86400),e.enabled?1:0,e.origin,e.sourceKey??null,e.ownerActorId??null,JSON.stringify(e.observedState),e.reconciliationStatus,s??null,1,n,n]),this.get(r)}get(e){let t=this.controlPlane.database.query("SELECT * FROM scheduled_jobs WHERE id=?").get(e);return t?Ps(t):void 0}getBySource(e,t,r){let n=this.controlPlane.database.query("SELECT * FROM scheduled_jobs WHERE project_id=? AND environment_id IS ? AND source_key=?").get(e,t??null,r);return n?Ps(n):void 0}list(e,t={}){let r=["project_id=?"],n=[e];if(t.environmentId)r.push("environment_id=?"),n.push(t.environmentId);if(t.resourceIds?.length)r.push(`resource_id IN (${t.resourceIds.map(()=>"?").join(",")})`),n.push(...t.resourceIds);if(t.enabled!=null)r.push("enabled=?"),n.push(t.enabled?1:0);return this.controlPlane.database.query(`SELECT * FROM scheduled_jobs WHERE ${r.join(" AND ")} ORDER BY next_run_at IS NULL,next_run_at,name`).all(...n).map(Ps)}setEnabled(e,t){this.controlPlane.database.run("UPDATE scheduled_jobs SET enabled=?,version=version+1,updated_at=? WHERE id=?",[t?1:0,this.now().toISOString(),e]);let r=this.get(e);if(!r)throw Error("Scheduled job was not found.");return r}updateSchedule(e,t){let r=this.get(e);if(!r)throw Error("Scheduled job was not found.");let n=t.expression??r.expression,i=t.timezone??r.timezone,a=Wn(n,i,this.now(),1),s=this.now().toISOString();return this.controlPlane.database.run("UPDATE scheduled_jobs SET expression=?,normalized_expression=?,timezone=?,missed_run_policy=?,overlap_policy=?,timeout_seconds=?,next_run_at=?,reconciliation_status=?,version=version+1,updated_at=? WHERE id=?",[n,a.normalized,i,t.missedRunPolicy??r.missedRunPolicy,t.overlapPolicy??r.overlapPolicy,sn(t.timeoutSeconds,r.timeoutSeconds,1,86400),a.nextRuns[0],"pending",s,e]),this.get(e)}remove(e){let t=this.get(e);if(!t)throw Error("Scheduled job was not found.");if(t.origin==="config")throw Error("Config-defined jobs must be removed from configuration, not destructively deleted.");this.controlPlane.database.run("DELETE FROM scheduled_jobs WHERE id=?",[e])}markScheduled(e,t,r){this.controlPlane.database.run("UPDATE scheduled_jobs SET last_scheduled_for=?,next_run_at=?,updated_at=? WHERE id=?",[t,r??null,this.now().toISOString(),e])}reconcile(e,t,r){return this.controlPlane.database.run("UPDATE scheduled_jobs SET reconciliation_status=?,observed_state=?,updated_at=? WHERE id=?",[t,JSON.stringify(r),this.now().toISOString(),e]),this.get(e)}upsertConfigJob(e){let t=this.getBySource(e.projectId,e.environmentId,e.sourceKey);if(!t)return this.create(e);let r=Wn(e.expression,e.timezone,this.now(),1),n=this.now().toISOString();if(t.resourceId===e.resourceId&&t.name===e.name&&t.provider===e.provider&&t.expression===e.expression&&t.normalizedExpression===r.normalized&&t.timezone===e.timezone&&JSON.stringify(t.target)===JSON.stringify(e.target)&&JSON.stringify(t.payloadRefs)===JSON.stringify(e.payloadRefs)&&t.missedRunPolicy===e.missedRunPolicy&&t.overlapPolicy===e.overlapPolicy&&JSON.stringify(t.retryPolicy)===JSON.stringify(e.retryPolicy)&&t.timeoutSeconds===e.timeoutSeconds&&t.enabled===e.enabled)return t;return this.controlPlane.database.run("UPDATE scheduled_jobs SET resource_id=?,name=?,provider=?,expression=?,normalized_expression=?,timezone=?,target=?,payload_refs=?,missed_run_policy=?,overlap_policy=?,retry_policy=?,timeout_seconds=?,enabled=?,observed_state=?,reconciliation_status=?,next_run_at=COALESCE(next_run_at,?),version=version+1,updated_at=? WHERE id=?",[e.resourceId??null,e.name,e.provider,e.expression,r.normalized,e.timezone,JSON.stringify(e.target),JSON.stringify(e.payloadRefs),e.missedRunPolicy,e.overlapPolicy,JSON.stringify(e.retryPolicy),e.timeoutSeconds,e.enabled?1:0,JSON.stringify(e.observedState),e.reconciliationStatus,r.nextRuns[0],n,t.id]),this.get(t.id)}due(e=this.now().toISOString()){return this.controlPlane.database.query("SELECT * FROM scheduled_jobs WHERE enabled=1 AND next_run_at IS NOT NULL AND next_run_at<=? AND (starts_at IS NULL OR starts_at<=?) AND (ends_at IS NULL OR ends_at>=?) ORDER BY next_run_at LIMIT 200").all(e,e,e).map(Ps)}createExecution(e){let t=this.controlPlane.database.query("SELECT * FROM job_executions WHERE idempotency_key=?").get(e.idempotencyKey);if(t)return Ds(t);let r=crypto.randomUUID(),n=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO job_executions (id,job_id,operation_id,trigger,scheduled_for,idempotency_key,status,attempt,output,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?)",[r,e.jobId,e.operationId??null,e.trigger,e.scheduledFor,e.idempotencyKey,e.status,0,JSON.stringify(e.output),n,n]),this.getExecution(r)}getExecution(e){let t=this.controlPlane.database.query("SELECT * FROM job_executions WHERE id=?").get(e);return t?Ds(t):void 0}listExecutions(e,t=100){return this.controlPlane.database.query("SELECT * FROM job_executions WHERE job_id=? ORDER BY scheduled_for DESC,created_at DESC LIMIT ?").all(e,Math.min(1000,Math.max(1,t))).map(Ds)}activeExecution(e){let t=this.controlPlane.database.query("SELECT * FROM job_executions WHERE job_id=? AND status IN ('queued','running') ORDER BY created_at DESC LIMIT 1").get(e);return t?Ds(t):void 0}attachOperation(e,t){return this.controlPlane.database.run("UPDATE job_executions SET operation_id=?,updated_at=? WHERE id=?",[t,this.now().toISOString(),e]),this.getExecution(e)}transitionExecution(e,t,r={}){let n=this.now().toISOString(),i=t==="running"?n:null,a=["succeeded","failed","skipped","dead"].includes(t)?n:null;return this.controlPlane.database.run("UPDATE job_executions SET status=?,attempt=COALESCE(?,attempt),started_at=COALESCE(started_at,?),finished_at=?,output=COALESCE(?,output),error=?,updated_at=? WHERE id=?",[t,r.attempt??null,i,a,r.output?JSON.stringify(r.output):null,r.error?.slice(0,2000)??null,n,e]),this.getExecution(e)}upsertWorker(e){let t=e.sourceKey?this.controlPlane.database.query("SELECT * FROM worker_definitions WHERE project_id=? AND source_key=? AND environment_id IS ?").get(e.projectId,e.sourceKey,e.environmentId??null):void 0,r=t?sc(t):void 0,n=r?.id??crypto.randomUUID(),i=this.now().toISOString(),a=sn(e.processes,1,0,1000),s=sn(e.timeoutSeconds,60,1,86400);if(r&&r.resourceId===e.resourceId&&r.name===e.name.slice(0,120)&&r.provider===e.provider&&r.queue===e.queue.slice(0,200)&&r.processes===a&&r.timeoutSeconds===s&&r.restartPolicy===e.restartPolicy&&JSON.stringify(r.target)===JSON.stringify(e.target)&&r.enabled===e.enabled)return r;return this.controlPlane.database.run("INSERT INTO worker_definitions (id,organization_id,project_id,environment_id,resource_id,name,provider,queue,processes,timeout_seconds,restart_policy,target,enabled,origin,source_key,owner_actor_id,observed_state,reconciliation_status,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET name=excluded.name,resource_id=excluded.resource_id,provider=excluded.provider,queue=excluded.queue,processes=excluded.processes,timeout_seconds=excluded.timeout_seconds,restart_policy=excluded.restart_policy,target=excluded.target,enabled=excluded.enabled,observed_state=excluded.observed_state,reconciliation_status=excluded.reconciliation_status,version=worker_definitions.version+1,updated_at=excluded.updated_at",[n,e.organizationId,e.projectId,e.environmentId??null,e.resourceId??null,e.name.slice(0,120),e.provider,e.queue.slice(0,200),a,s,e.restartPolicy,JSON.stringify(e.target),e.enabled?1:0,e.origin,e.sourceKey??null,e.ownerActorId??null,JSON.stringify(e.observedState),e.reconciliationStatus,1,r?.createdAt??i,i]),this.getWorker(n)}getWorker(e){let t=this.controlPlane.database.query("SELECT * FROM worker_definitions WHERE id=?").get(e);return t?sc(t):void 0}listWorkers(e,t){return this.controlPlane.database.query(`SELECT * FROM worker_definitions WHERE project_id=?${t?" AND environment_id=?":""} ORDER BY name`).all(e,...t?[t]:[]).map(sc)}setWorkerProcesses(e,t){this.controlPlane.database.run("UPDATE worker_definitions SET processes=?,reconciliation_status='pending',version=version+1,updated_at=? WHERE id=?",[sn(t,1,0,1000),this.now().toISOString(),e]);let r=this.getWorker(e);if(!r)throw Error("Worker was not found.");return r}reconcileWorker(e,t,r){this.controlPlane.database.run("UPDATE worker_definitions SET reconciliation_status=?,observed_state=?,updated_at=? WHERE id=?",[t,JSON.stringify(r),this.now().toISOString(),e]);let n=this.getWorker(e);if(!n)throw Error("Worker was not found.");return n}}var Ie=(e)=>e==null?void 0:String(e),$s=(e)=>Number(e)===1,on=(e,t)=>{try{return JSON.parse(String(e))}catch{return t}};function wf(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),name:String(e.name),provider:String(e.provider),endpoint:Ie(e.endpoint),endpointPolicy:String(e.endpoint_policy),bucket:Ie(e.bucket),prefix:String(e.prefix),region:Ie(e.region),forcePathStyle:$s(e.force_path_style),credentialRef:Ie(e.credential_ref),encryption:String(e.encryption),encryptionKeyRef:Ie(e.encryption_key_ref),immutability:on(e.immutability,{}),status:String(e.status),lastTestedAt:Ie(e.last_tested_at),lastSuccessAt:Ie(e.last_success_at),lastFailureAt:Ie(e.last_failure_at),lastError:Ie(e.last_error),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function dc(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:Ie(e.environment_id),resourceId:Ie(e.resource_id),dataServiceId:Ie(e.data_service_id),destinationId:String(e.destination_id),name:String(e.name),resourceKind:String(e.resource_kind),schedule:String(e.schedule),timezone:String(e.timezone),retention:on(e.retention,{}),compression:String(e.compression),encryption:String(e.encryption),includePatterns:on(e.include_patterns,[]),excludePatterns:on(e.exclude_patterns,[]),expectedRpoMinutes:Number(e.expected_rpo_minutes),expectedRtoMinutes:Number(e.expected_rto_minutes),healthCheckId:Ie(e.health_check_id),enabled:$s(e.enabled),nextRunAt:Ie(e.next_run_at),lastRunAt:Ie(e.last_run_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function cc(e){return{id:String(e.id),projectId:String(e.project_id),policyId:Ie(e.policy_id),destinationId:String(e.destination_id),resourceId:Ie(e.resource_id),dataServiceId:Ie(e.data_service_id),backupJobId:Ie(e.backup_job_id),kind:String(e.kind),pointInTime:String(e.point_in_time),uri:String(e.uri),sizeBytes:Number(e.size_bytes),checksum:String(e.checksum),manifest:on(e.manifest,{}),toolVersion:Ie(e.tool_version),engineVersion:Ie(e.engine_version),expiresAt:Ie(e.expires_at),lockedUntil:Ie(e.locked_until),held:$s(e.held),pinned:$s(e.pinned),status:String(e.status),verificationState:String(e.verification_state),verifiedAt:Ie(e.verified_at),durationMs:e.duration_ms==null?void 0:Number(e.duration_ms),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function lc(e){return{id:String(e.id),projectId:String(e.project_id),policyId:Ie(e.policy_id),recoveryPointId:Ie(e.recovery_point_id),operationId:Ie(e.operation_id),kind:String(e.kind),status:String(e.status),idempotencyKey:String(e.idempotency_key),target:on(e.target,{}),restoreMode:Ie(e.restore_mode),cancellability:String(e.cancellability),safetyBackupId:Ie(e.safety_backup_id),healthResult:e.health_result?on(e.health_result,{}):void 0,progress:on(e.progress,{}),error:Ie(e.error),startedAt:Ie(e.started_at),finishedAt:Ie(e.finished_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Ny(e){let t=e.toLowerCase();if(t==="localhost"||t.endsWith(".localhost")||t.endsWith(".local")||t.endsWith(".internal"))return!0;if(yf(t)===6)return t==="::1"||t.startsWith("fe80:");if(yf(t)!==4)return!1;let[r,n]=t.split(".").map(Number);return r===10||r===127||r===0||r===169&&n===254||r===172&&n>=16&&n<=31||r===192&&n===168}function Fy(e){if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(e.name))throw Error("Backup destination names must be 2-63 lowercase letters, numbers, or dashes.");if(e.provider!=="aws_backup"&&!e.bucket)throw Error("S3 backup destinations require a bucket.");if(e.provider==="s3_compatible"&&!e.endpoint)throw Error("S3-compatible destinations require an explicit endpoint.");if(e.provider==="s3_compatible"&&!e.credentialRef)throw Error("S3-compatible destinations require a credential reference.");if(e.encryption!=="provider"&&!e.encryptionKeyRef)throw Error("Client-side encryption requires an encryption key reference.");if(e.endpoint){let t=new URL(e.endpoint);if(t.protocol!=="https:"||t.username||t.password||t.search||t.hash||t.pathname!=="/")throw Error("Backup endpoints must be origin-only HTTPS URLs without credentials, paths, queries, or fragments.");if(Ny(t.hostname)&&e.endpointPolicy!=="allow_private")throw Error("Private backup endpoints require endpointPolicy allow_private.")}}class gc{controlPlane;now;constructor(e,t=()=>new Date){this.controlPlane=e;this.now=t}createDestination(e){Fy(e);let t=crypto.randomUUID(),r=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO backup_destinations (id,organization_id,project_id,name,provider,endpoint,endpoint_policy,bucket,prefix,region,force_path_style,credential_ref,encryption,encryption_key_ref,immutability,status,last_tested_at,last_success_at,last_failure_at,last_error,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.organizationId,e.projectId,e.name,e.provider,e.endpoint??null,e.endpointPolicy,e.bucket??null,e.prefix,e.region??null,e.forcePathStyle?1:0,e.credentialRef??null,e.encryption,e.encryptionKeyRef??null,JSON.stringify(e.immutability),e.status,e.lastTestedAt??null,e.lastSuccessAt??null,e.lastFailureAt??null,e.lastError??null,1,r,r]),this.getDestination(t)}getDestination(e){let t=this.controlPlane.database.query("SELECT * FROM backup_destinations WHERE id=?").get(e);return t?wf(t):void 0}listDestinations(e){return this.controlPlane.database.query("SELECT * FROM backup_destinations WHERE project_id=? ORDER BY name").all(e).map(wf)}recordDestinationTest(e,t){let r=this.now().toISOString();return this.controlPlane.database.run("UPDATE backup_destinations SET status=?,last_tested_at=?,last_success_at=CASE WHEN ? THEN ? ELSE last_success_at END,last_failure_at=CASE WHEN ? THEN last_failure_at ELSE ? END,last_error=?,version=version+1,updated_at=? WHERE id=?",[t.ok?"healthy":"failing",r,t.ok?1:0,r,t.ok?1:0,r,t.ok?null:String(t.error??"Destination test failed.").slice(0,1000),r,e]),this.getDestination(e)}createPolicy(e){if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(e.name))throw Error("Backup policy names must be lowercase slugs.");if(!e.resourceId&&!e.dataServiceId&&!["control_plane","infrastructure"].includes(e.resourceKind))throw Error("A backup policy requires a resource or data service target.");let t=this.getDestination(e.destinationId);if(!t||t.projectId!==e.projectId)throw Error("Backup destination was not found.");if(e.resourceKind==="control_plane"&&t.encryption==="provider")throw Error("Control-plane backups require client-side destination encryption.");if(["logical_database","volume","files","control_plane"].includes(e.resourceKind)&&t.provider==="aws_backup")throw Error(`${e.resourceKind} backups require an object-storage destination.`);if(e.resourceKind==="infrastructure"&&t.provider!=="aws_backup")throw Error("Infrastructure backups require an AWS Backup destination.");let r=an(e.schedule),n=zn(r.normalized,e.timezone,this.now(),1)[0],i=crypto.randomUUID(),a=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO backup_policies (id,organization_id,project_id,environment_id,resource_id,data_service_id,destination_id,name,resource_kind,schedule,timezone,retention,compression,encryption,include_patterns,exclude_patterns,expected_rpo_minutes,expected_rto_minutes,health_check_id,enabled,next_run_at,last_run_at,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[i,e.organizationId,e.projectId,e.environmentId??null,e.resourceId??null,e.dataServiceId??null,e.destinationId,e.name,e.resourceKind,r.normalized,e.timezone,JSON.stringify(e.retention),e.compression,e.encryption,JSON.stringify(e.includePatterns),JSON.stringify(e.excludePatterns),e.expectedRpoMinutes,e.expectedRtoMinutes,e.healthCheckId??null,e.enabled?1:0,n,e.lastRunAt??null,1,a,a]),this.getPolicy(i)}getPolicy(e){let t=this.controlPlane.database.query("SELECT * FROM backup_policies WHERE id=?").get(e);return t?dc(t):void 0}listPolicies(e,t){return this.controlPlane.database.query(`SELECT * FROM backup_policies WHERE project_id=?${t?" AND environment_id=?":""} ORDER BY name`).all(e,...t?[t]:[]).map(dc)}duePolicies(e=this.now()){return this.controlPlane.database.query("SELECT * FROM backup_policies WHERE enabled=1 AND next_run_at<=? ORDER BY next_run_at,id").all(e.toISOString()).map(dc)}advancePolicy(e,t){let r=this.getPolicy(e);if(!r)throw Error("Backup policy was not found.");let n=zn(r.schedule,r.timezone,new Date(t),1)[0];return this.controlPlane.database.run("UPDATE backup_policies SET last_run_at=?,next_run_at=?,version=version+1,updated_at=? WHERE id=?",[t,n,this.now().toISOString(),e]),this.getPolicy(e)}createJob(e){let t=this.controlPlane.database.query("SELECT * FROM backup_jobs WHERE idempotency_key=?").get(e.idempotencyKey);if(t)return lc(t);let r=crypto.randomUUID(),n=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO backup_jobs (id,project_id,policy_id,recovery_point_id,operation_id,kind,status,idempotency_key,target,restore_mode,cancellability,safety_backup_id,health_result,progress,error,started_at,finished_at,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[r,e.projectId,e.policyId??null,e.recoveryPointId??null,e.operationId??null,e.kind,e.status,e.idempotencyKey,JSON.stringify(e.target),e.restoreMode??null,e.cancellability,e.safetyBackupId??null,e.healthResult?JSON.stringify(e.healthResult):null,JSON.stringify(e.progress),e.error??null,e.startedAt??null,e.finishedAt??null,n,n]),this.getJob(r)}getJob(e){let t=this.controlPlane.database.query("SELECT * FROM backup_jobs WHERE id=?").get(e);return t?lc(t):void 0}listJobs(e){return this.controlPlane.database.query("SELECT * FROM backup_jobs WHERE project_id=? ORDER BY created_at DESC").all(e).map(lc)}updateJob(e,t){let r=this.getJob(e);if(!r)throw Error("Backup job was not found.");let n={...r,...t};return this.controlPlane.database.run("UPDATE backup_jobs SET status=?,operation_id=?,recovery_point_id=?,progress=?,health_result=?,error=?,started_at=?,finished_at=?,safety_backup_id=?,updated_at=? WHERE id=?",[n.status,n.operationId??null,n.recoveryPointId??null,JSON.stringify(n.progress),n.healthResult?JSON.stringify(n.healthResult):null,n.error??null,n.startedAt??null,n.finishedAt??null,n.safetyBackupId??null,this.now().toISOString(),e]),this.getJob(e)}createRecoveryPoint(e){if(!/^sha256:[a-f0-9]{64}$/i.test(e.checksum))throw Error("Recovery points require a SHA-256 checksum.");if(typeof e.uri!=="string"||!["s3:","aws-backup:","file:"].some((n)=>e.uri.startsWith(n)))throw Error("Recovery point URI uses an unsupported destination scheme.");let t=crypto.randomUUID(),r=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO recovery_points (id,project_id,policy_id,destination_id,resource_id,data_service_id,backup_job_id,kind,point_in_time,uri,size_bytes,checksum,manifest,tool_version,engine_version,expires_at,locked_until,held,pinned,status,verification_state,verified_at,duration_ms,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.projectId,e.policyId??null,e.destinationId,e.resourceId??null,e.dataServiceId??null,e.backupJobId??null,e.kind,e.pointInTime,e.uri,e.sizeBytes,e.checksum,JSON.stringify(e.manifest),e.toolVersion??null,e.engineVersion??null,e.expiresAt??null,e.lockedUntil??null,e.held?1:0,e.pinned?1:0,e.status,e.verificationState,e.verifiedAt??null,e.durationMs??null,r,r]),this.getRecoveryPoint(t)}getRecoveryPoint(e){let t=this.controlPlane.database.query("SELECT * FROM recovery_points WHERE id=?").get(e);return t?cc(t):void 0}listRecoveryPoints(e,t){return this.controlPlane.database.query(`SELECT * FROM recovery_points WHERE project_id=?${t?" AND policy_id=?":""} ORDER BY point_in_time DESC`).all(e,...t?[t]:[]).map(cc)}updateRecoveryPoint(e,t){let r=this.getRecoveryPoint(e);if(!r)throw Error("Recovery point was not found.");let n={...r,...t};return this.controlPlane.database.run("UPDATE recovery_points SET status=?,verification_state=?,verified_at=?,held=?,pinned=?,manifest=?,duration_ms=?,updated_at=? WHERE id=?",[n.status,n.verificationState,n.verifiedAt??null,n.held?1:0,n.pinned?1:0,JSON.stringify(n.manifest),n.durationMs??null,this.now().toISOString(),e]),this.getRecoveryPoint(e)}retentionCandidates(e=this.now()){let t=this.controlPlane.database.query(`SELECT rp.* FROM recovery_points rp
55
+ WHERE rp.status='available' AND rp.held=0 AND rp.pinned=0
56
+ AND rp.expires_at IS NOT NULL AND rp.expires_at<=?
57
+ AND (rp.locked_until IS NULL OR rp.locked_until<=?)
58
+ AND NOT EXISTS (
59
+ SELECT 1 FROM backup_jobs bj WHERE bj.recovery_point_id=rp.id
60
+ AND bj.kind IN ('restore','drill') AND bj.status IN ('queued','running','cleanup_required')
61
+ )
62
+ ORDER BY rp.expires_at,rp.id`).all(e.toISOString(),e.toISOString()).map(cc),r=new Set;for(let n of new Set(t.map((i)=>i.projectId)))for(let i of this.listPolicies(n)){let a=this.listRecoveryPoints(i.projectId,i.id).filter((d)=>d.status==="available").sort((d,c)=>c.pointInTime.localeCompare(d.pointInTime));for(let d of a.slice(0,Math.max(0,i.retention.keepLast??0)))r.add(d.id);let s=[[i.retention.hourly,(d)=>d.toISOString().slice(0,13)],[i.retention.daily,(d)=>d.toISOString().slice(0,10)],[i.retention.weekly,(d)=>{return new Date(Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate()-(d.getUTCDay()+6)%7)).toISOString().slice(0,10)}],[i.retention.monthly,(d)=>d.toISOString().slice(0,7)]];for(let[d,c]of s){let o=new Set;for(let g of a){let h=c(new Date(g.pointInTime));if(o.has(h))continue;if(o.add(h),o.size<=Math.max(0,d??0))r.add(g.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((d)=>d.status==="available"),a=i[0],s=a?(t.getTime()-new Date(a.pointInTime).getTime())/60000:Number.POSITIVE_INFINITY;return{policy:n,lastRecoveryPoint:a,missedRpo:n.enabled&&s>n.expectedRpoMinutes,unverified:i.filter((d)=>d.verificationState!=="verified").length,destinationHealthy:r.get(n.destinationId)?.status==="healthy"}})}}import{createCipheriv as Vy,createDecipheriv as Ly,createHash as Af,randomBytes as Pf}from"node:crypto";var uc=Buffer.from("TSCB1"),Cs=(e)=>`sha256:${Af("sha256").update(e).digest("hex")}`;function Df(e){return Af("sha256").update(e).digest()}function xy(e,t,r){let n=r?Buffer.from(r):Pf(12);if(n.length!==12)throw Error("Backup encryption IV must contain 12 bytes.");let i=Vy("aes-256-gcm",Df(t),n),a=Buffer.concat([i.update(e),i.final()]),s=i.getAuthTag();return Buffer.concat([uc,n,s,a])}function My(e,t){let r=Buffer.from(e);if(!r.subarray(0,uc.length).equals(uc))throw Error("Backup does not contain a valid encrypted envelope.");let n=r.subarray(5,17),i=r.subarray(17,33),a=r.subarray(33),s=Ly("aes-256-gcm",Df(t),n);return s.setAuthTag(i),Buffer.concat([s.update(a),s.final()])}function Qy(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 $f(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 a=i.getTime()-r.getTime();return{status:a<=0?"expired":a<=604800000?"expiring":"valid",expiresAt:i.toISOString()}}catch{return{status:"invalid"}}}class hc{secrets;clientFactory;multipartThreshold;partSize;constructor(e,t=(i,a)=>new lr(i.region??"us-east-1",void 0,{endpoint:i.endpoint?new URL(i.endpoint).host:void 0,forcePathStyle:i.forcePathStyle,credentials:a}),r=8388608,n=8388608){this.secrets=e;this.clientFactory=t;this.multipartThreshold=r;this.partSize=n}async client(e){let t=e.credentialRef?Qy(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=Cs(t.body),i=e.encryption!=="provider"?await this.secrets.resolve(e.encryptionKeyRef):void 0,a=i?t.resume?.encryptionIv?Buffer.from(t.resume.encryptionIv,"base64url"):Pf(12):void 0,s=i?xy(t.body,i,a):Buffer.from(t.body),d=Cs(s),c=`${e.prefix?`${e.prefix.replace(/\/$/,"")}/`:""}${t.key.replace(/^\/+/,"")}`,o=t.contentType??"application/octet-stream",g={"ts-cloud-format":"v1","ts-cloud-sha256":d.slice(7),"ts-cloud-encrypted":i?"true":"false"};if(t.resume&&t.resume.key!==c)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:c,body:s,contentType:o,metadata:g});else{let h=t.resume?void 0:await r.createMultipartUpload(e.bucket,c,{contentType:o,metadata:g}),_=t.resume??{uploadId:h.UploadId,key:c,parts:[],bytesUploaded:0,encryptionIv:a?.toString("base64url"),plaintextChecksum:n},R=new Map(_.parts.map((y)=>[y.PartNumber,y])),E=Math.ceil(s.length/this.partSize);for(let y=0;y<E;y++){let $=y+1;if(!R.has($)){let b=y*this.partSize,z=await r.uploadPart(e.bucket,c,_.uploadId,$,s.subarray(b,Math.min(s.length,b+this.partSize)));R.set($,{PartNumber:$,ETag:z.ETag})}_.parts=[...R.values()].sort((b,z)=>b.PartNumber-z.PartNumber),_.bytesUploaded=Math.min(s.length,$*this.partSize),t.checkpoint?.(_)}await r.completeMultipartUpload(e.bucket,c,_.uploadId,_.parts)}return{uri:`s3://${e.bucket}/${c}`,key:c,sizeBytes:s.length,checksum:d,manifest:{format:"ts-cloud-backup-v1",encrypted:!!i,plaintextChecksum:n,storageChecksum:d,contentType:o}}}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(Cs(i)!==t.checksum)throw Error("Backup checksum verification failed; object is corrupt.");let a=t.manifest.encrypted?My(i,await this.secrets.resolve(e.encryptionKeyRef)):i;if(Cs(a)!==t.manifest.plaintextChecksum)throw Error("Backup plaintext checksum verification failed.");return a}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 Gy}from"node:crypto";var Zy=(e)=>`sha256:${Gy("sha256").update(e).digest("hex")}`;class ks{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=Zy(JSON.stringify({point:e.id,mode:t.mode,target:t.target,safety:t.safetyBackupId,drill:!!t.drill})),a=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(!a.operationId){let s=this.queue.enqueue({projectId:e.projectId,resourceId:e.resourceId,actorId:t.actorId,kind:t.drill?"backup.drill":"backup.restore",input:{backupJobId:a.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(a.id,{operationId:s.operation.id})}return a}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 Cf(e){let t=e.now??(()=>new Date),r=new ks(e.store,e.queue,t),n=(d)=>{let c=d.recoveryPointId?e.store.getRecoveryPoint(d.recoveryPointId):void 0,o=d.policyId?e.store.getPolicy(d.policyId):c?.policyId?e.store.getPolicy(c.policyId):void 0;if(!o)throw Error("Backup policy was not found.");let g=e.store.getDestination(c?.destinationId??o.destinationId),h=e.resolveSource(o);if(!g)throw Error("Backup destination was not found.");if(!h)throw Error(`No ${o.resourceKind} backup adapter is configured.`);return{point:c,policy:o,destination:g,source:h}},i=(d)=>{let c=d.operation.input,o=e.store.getJob(String(c.backupJobId??""));if(!o)throw Error("Backup job was not found.");return e.store.updateJob(o.id,{status:"running",startedAt:o.startedAt??t().toISOString(),progress:{...o.progress,phase:"running"}}),o},a=(d,c)=>{let o=e.store.getJob(d.id)??d;e.store.updateJob(d.id,{status:"failed",finishedAt:t().toISOString(),error:c instanceof Error?c.message:String(c),progress:{...o.progress,phase:"failed"}})};return{"backup.run":async(d)=>{let c=i(d);try{let{policy:o,destination:g,source:h}=n(c),_=await h.create(o,d),R=e.resolveDestination(g),E=_.mode==="object"?await(async()=>{if(!R)throw Error("Backup destination adapter is not configured.");let z=e.store.getJob(c.id)?.progress,C=z?.multipart,B=C&&typeof C==="object"&&!Array.isArray(C)&&typeof C.uploadId==="string"&&typeof C.key==="string"&&Array.isArray(C.parts)?C:void 0;return R.upload(g,{key:_.key,body:_.body,contentType:_.contentType,resume:B,checkpoint:(N)=>{d.checkpoint("uploading",`Uploaded ${Number(N.bytesUploaded??0)} backup bytes.`),e.store.updateJob(c.id,{progress:{phase:"uploading",multipart:{...N}}})}})})():{uri:_.uri,key:_.uri,sizeBytes:_.sizeBytes,checksum:_.checksum,manifest:{format:"ts-cloud-backup-v1",encrypted:!1,plaintextChecksum:_.checksum,storageChecksum:_.checksum,contentType:"application/provider-snapshot"}},y=o.retention.expireAfterDays?new Date(t().getTime()+o.retention.expireAfterDays*86400000).toISOString():void 0,$=e.store.getJob(c.id)?.startedAt,b=e.store.createRecoveryPoint({projectId:o.projectId,policyId:o.id,destinationId:g.id,resourceId:o.resourceId,dataServiceId:o.dataServiceId,backupJobId:c.id,kind:o.resourceKind,pointInTime:t().toISOString(),uri:E.uri,sizeBytes:E.sizeBytes,checksum:E.checksum,manifest:{..._.manifest,...E.manifest,storageKey:E.key},toolVersion:_.toolVersion,engineVersion:_.engineVersion,expiresAt:y,lockedUntil:g.immutability.defaultRetentionDays?new Date(t().getTime()+g.immutability.defaultRetentionDays*86400000).toISOString():void 0,held:!1,pinned:!1,status:"available",verificationState:"unverified",durationMs:Math.max(0,t().getTime()-new Date($??t().toISOString()).getTime())});if(_.mode==="external"&&g.provider==="aws_backup")e.store.recordDestinationTest(g.id,{ok:!0});return e.store.updateJob(c.id,{status:"succeeded",recoveryPointId:b.id,finishedAt:t().toISOString(),progress:{phase:"stored",recoveryPointId:b.id}}),r.enqueueVerification(b),{backupJobId:c.id,recoveryPointId:b.id}}catch(o){let g=e.store.getJob(c.id),h=g?.progress.multipart,_=(()=>{try{return n(c)}catch{return}})();if(_?.destination.provider==="aws_backup")e.store.recordDestinationTest(_.destination.id,{ok:!1,error:o instanceof Error?o.message:String(o)});let R=!1;if(h&&typeof h==="object"&&!Array.isArray(h)&&_){let E=e.resolveDestination(_.destination);if(R=!0,E?.abortPartial)try{await E.abortPartial(_.destination,h),R=!1,e.store.updateJob(c.id,{progress:{...g.progress,partialCleanup:"aborted"}})}catch{e.store.updateJob(c.id,{progress:{...g.progress,partialCleanup:"required"}})}}if(R)e.store.updateJob(c.id,{status:"cleanup_required",finishedAt:t().toISOString(),error:o instanceof Error?o.message:String(o),progress:{...e.store.getJob(c.id)?.progress??{},phase:"cleanup_required"}});else a(c,o);throw o}},"backup.verify":async(d)=>{let c=i(d);try{let{point:o,destination:g,source:h}=n(c);if(!o)throw Error("Recovery point was not found.");e.store.updateRecoveryPoint(o.id,{verificationState:"verifying"});let _;if(o.uri.startsWith("s3:")){let R=e.resolveDestination(g);if(!R)throw Error("Backup destination adapter is not configured.");let E=await R.download(g,{key:String(o.manifest.storageKey??""),checksum:o.checksum,manifest:o.manifest}),y=h.verify?await h.verify(o,E,d):{};_={bytes:E.length,checksum:o.checksum,...y}}else if(h.verifyExternal)_=await h.verifyExternal(o,d);else throw Error("External recovery point verification is not supported.");return e.store.updateRecoveryPoint(o.id,{verificationState:"verified",verifiedAt:t().toISOString(),manifest:{...o.manifest,verification:_}}),e.store.updateJob(c.id,{status:"succeeded",finishedAt:t().toISOString(),progress:{phase:"verified",evidence:_}}),{backupJobId:c.id,recoveryPointId:o.id,evidence:_}}catch(o){if(c.recoveryPointId)e.store.updateRecoveryPoint(c.recoveryPointId,{verificationState:/checksum|corrupt|authentic/i.test(o instanceof Error?o.message:String(o))?"corrupt":"failed"});throw a(c,o),o}},"backup.restore":async(d)=>s(d,!1),"backup.drill":async(d)=>s(d,!0),"backup.cleanup":async(d)=>{let c=i(d);try{let{point:o,destination:g,source:h}=n(c);if(!o)throw Error("Recovery point was not found.");if(!e.store.retentionCandidates(t()).some((_)=>_.id===o.id))throw Error("Recovery point is held, pinned, locked, or in active use.");if(e.store.updateRecoveryPoint(o.id,{status:"deleting"}),o.uri.startsWith("s3:")){let _=e.resolveDestination(g);if(!_)throw Error("Destination cleanup is unavailable.");await _.delete(g,String(o.manifest.storageKey??""))}else if(h.deleteExternal)await h.deleteExternal(o,d);else throw Error("External recovery point cleanup is unavailable.");return e.store.updateRecoveryPoint(o.id,{status:"deleted"}),e.store.updateJob(c.id,{status:"succeeded",finishedAt:t().toISOString(),progress:{phase:"deleted"}}),{backupJobId:c.id,recoveryPointId:o.id,deleted:!0}}catch(o){throw a(c,o),o}}};async function s(d,c){let o=i(d);try{let{point:g,policy:h,destination:_,source:R}=n(o);if(!g)throw Error("Recovery point was not found.");if(c&&!R.cleanup)throw Error("This backup source cannot safely clean a recovery drill target.");let E=g.uri.startsWith("s3:")?e.resolveDestination(_):void 0,y=E?await E.download(_,{key:String(g.manifest.storageKey??""),checksum:g.checksum,manifest:g.manifest}):void 0,$=await R.restore(g,y,o.target,d),b=R.validateHealth?await R.validateHealth({...o.target,...$},d):{healthy:!0,mode:"adapter"},z=e.validateHealth?await e.validateHealth(h,o.target):{healthy:!0,mode:"not_configured"},C={...b,healthy:b.healthy===!0&&z.healthy===!0,configured:z};if(C.healthy!==!0)throw Error("Restored target did not pass its configured health check.");if(c&&R.cleanup)await R.cleanup({...o.target,provider:g.manifest.provider??null},d);return e.store.updateJob(o.id,{status:"succeeded",finishedAt:t().toISOString(),healthResult:C,progress:{phase:c?"drill_cleaned":"restored",restored:$}}),{backupJobId:o.id,recoveryPointId:g.id,restored:$,health:C,cleaned:c}}catch(g){let h=(()=>{try{return n(o)}catch{return}})(),_=g instanceof Error?g.message:String(g),R=!1;if(c&&h?.source.cleanup)try{await h.source.cleanup({...o.target,provider:h.point?.manifest.provider??null},d)}catch{R=!0}if(R)e.store.updateJob(o.id,{status:"cleanup_required",finishedAt:t().toISOString(),error:_,progress:{...o.progress,phase:"cleanup_required"}});else a(o,g);throw g}}}import{createHash as Ky}from"node:crypto";var Yy=(e)=>`sha256:${Ky("sha256").update(e).digest("hex")}`;class fc{dataServices;client;constructor(e,t=new Un){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,a=String(i.Status??i.DBSnapshotStatus??"unknown");if(r.checkpoint?.("provider_snapshot",`Database snapshot ${t} is ${a}.`),a==="available")return i;if(["deleted","deleting","failed"].includes(a))throw Error(`Provider snapshot ${t} failed with state ${a}.`);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 a=`${r.provider}:${r.placement}:${i}`;return{mode:"external",uri:`aws-backup:${a}`,checksum:Yy(a),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),a=String(i.Status??i.DBSnapshotStatus??"unknown");return{snapshotId:r,status:a,encrypted:i.Encrypted??i.StorageEncrypted??!0}}async restore(e,t,r,n){let i=String(r.targetId??""),a=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 d=e.manifest.engine==="postgres"?"aurora-postgresql":"aurora-mysql";await this.client.restoreDBClusterFromSnapshot({DBClusterIdentifier:i,SnapshotIdentifier:a,Engine:d,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:d,PubliclyAccessible:!1})}else await this.client.restoreDBInstanceFromDBSnapshot({DBInstanceIdentifier:i,DBSnapshotIdentifier:a,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 a=String(i.Status??i.DBInstanceStatus??"unknown");if(t.checkpoint?.("provider_restore",`Restored database ${r} is ${a}.`),a==="available")return{healthy:!0,targetId:r,provider:n,status:a};if(["deleted","deleting","failed","incompatible-restore"].includes(a))throw Error(`Restored managed database ${r} failed with state ${a}.`);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 pt=(e,t="none",r=!1)=>({supported:!0,downtime:t,destructive:r,explanation:e}),dt=(e)=>({supported:!1,downtime:"none",destructive:!1,explanation:e});function _a(e,t){let r=["aws_rds","aws_aurora","aws_elasticache"].includes(t),n=["server","container"].includes(t),i=["postgres","mysql","mariadb"].includes(e),a=e==="redis",s={};return s.create=t==="external"?dt("External services can be adopted as read-only inventory."):pt(r?"Provision through the provider API.":"Provision through the owning runtime driver.","possible"),s.observe=t==="external"?dt("External observation requires a configured provider adapter."):pt("Provider/runtime health and endpoint metadata are observable."),s.connect=pt("Connection guidance uses secret references and never returns a password by default."),s.backup=i&&(r||n)?pt(r?"Create a provider snapshot.":"Create a consistent engine-native dump.","possible"):dt("This cache path is not a durable backup source."),s.restore=r&&i?pt("Restore creates a reviewed provider target.","required",!0):dt("Restore requires a configured provider restore runner."),s.restart=t==="external"?dt("External restart requires a configured provider adapter."):pt(r?"Provider restart/failover semantics apply.":"Restart the owning service unit.","required"),s.resize=t==="aws_elasticache"?dt("ElastiCache resizing requires a replication-group migration runner."):r?pt("Provider plan/storage modification may enter a maintenance window.","possible"):n?pt("Edit host/container resources and reconcile.","required"):dt("External resize requires a configured provider adapter."),s.version=n?dt("Runtime version upgrades require an explicit image migration runner."):r&&t!=="aws_elasticache"?pt(i?"Major versions require compatibility preflight and backup.":"Engine upgrades require a maintenance window.","required"):dt("External upgrades require a configured provider adapter."),s.rotate=t==="aws_elasticache"||t==="external"||n&&!i&&!a?dt("Credential rotation is not available for this provider/engine path."):pt("Rotate through the secret backend, update the engine, then flag dependent releases."),s.expose=n?dt("Direct container publishing is refused; use a reviewed firewall and proxy policy."):t==="aws_rds"?pt("Exposure is reconciled through security groups; public access defaults off."):dt("Exposure changes require a provider-specific network runner."),s.delete=t==="external"?dt("External deletion requires a configured provider adapter."):pt(r?"Final snapshot is supported where the provider allows it.":"A final engine backup is required unless explicitly retained.","required",!0),s.logs=n?pt("Read bounded service logs from the runtime."):dt("Provider log export is not configured for this adapter."),s.slow_queries=n&&i?pt("Read bounded runtime logs after engine slow-query logging is enabled."):dt("A slow-query log runner is not configured for this provider."),s.users=n&&i?pt("Logical users can be listed; creation requires a referenced secondary credential."):dt("User management requires an engine connection runner."),s.databases=n&&i?pt("Logical databases can be listed, created, and confirmation-gated for deletion."):dt("Logical database management requires an engine connection runner."),{actions:s,endpointTypes:r?["internal","external","tunnel"]:["internal","tunnel"],metrics:a?["connections","memory","evictions","hit_rate","latency"]:["connections","cpu","storage","read_latency","write_latency","iops"]}}var Ii=(e)=>e==null?void 0:String(e),vs=(e)=>Number(e)===1,bs=(e)=>{try{return JSON.parse(String(e))}catch{return{}}};function kf(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:Ii(e.environment_id),resourceId:Ii(e.resource_id),name:String(e.name),engine:String(e.engine),provider:String(e.provider),placement:String(e.placement),engineVersion:Ii(e.engine_version),plan:String(e.plan),storageGb:e.storage_gb==null?void 0:Number(e.storage_gb),highAvailability:vs(e.high_availability),publicExposure:vs(e.public_exposure),allowedCidrs:bs(e.allowed_cidrs),desiredState:bs(e.desired_state),observedState:bs(e.observed_state),capabilities:bs(e.capabilities),credentialRef:Ii(e.credential_ref),status:String(e.status),origin:String(e.origin),managementEnabled:vs(e.management_enabled),ownerActorId:Ii(e.owner_actor_id),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}class Sc{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=_a(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?kf(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(kf)}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:Ii(t.rotated_at)}:void 0}saveCredential(e,t,r){let n=this.credential(e),i=n?.id??crypto.randomUUID(),a=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??a,n?a: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:vs(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 bf(){let t=crypto.getRandomValues(new Uint8Array(40));return Array.from(t,(r)=>"ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@#$%^&*_-+="[r%69]).join("")}function vf(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 Os{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=bf();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 a=String(r.backupId??""),s=String(r.targetId??"");if(!a||!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=bf(),a=`${n.secretRef}/v${n.version+1}`;await this.secrets.put(a,i);try{return await t.action(e,"rotate",{username:n.username,secretRef:a},i,r),this.store.saveCredential(e.id,n.username,a),this.store.update(e.id,e.version,{credentialRef:a}),{credential:{username:n.username,password:i,secretRef:a},dependencies:this.store.dependencies(e.id).filter((s)=>s.requiresRedeploy).map((s)=>s.resourceId)}}catch(s){throw await this.secrets.remove(a),s}}}function Of(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 a=e.resolveAdapter(n);if(!a||a.provider!==n.provider||!a.engines.includes(n.engine))throw Error(`No ${n.provider}/${n.engine} adapter is configured.`);if(i==="rotate"){let d=await new Os(e.store,new Be(e.store.controlPlane),e.secrets).rotate(n,a,t);return{serviceId:n.id,action:i,username:d.credential.username,secretRef:d.credential.secretRef,dependencies:d.dependencies}}let s=n.credentialRef?await e.secrets.resolve(n.credentialRef):void 0;try{let d=i==="observe"?await a.observe(n):i==="create"?await a.apply(n,s,t):await a.action(n,i,r,s,t),c=e.store.get(n.id);return e.store.update(n.id,c.version,{observedState:d,status:i==="delete"?r.retention==="retain"?"retained":"deleting":"available"}),{serviceId:n.id,action:i,observed:d}}catch(d){let c=e.store.get(n.id);if(e.store.update(n.id,c.version,{status:"failed",observedState:{...c.observedState,error:d instanceof Error?d.message:String(d)}}),/temporar|timeout|unavailable|throttl/i.test(d instanceof Error?d.message:String(d)))throw new As(d instanceof Error?d.message:String(d),"provider_transient");throw d}}}}class mi{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 _c extends mi{provider="aws_rds";engines=["postgres","mysql","mariadb"]}class Rc extends mi{provider="aws_aurora";engines=["postgres","mysql"]}class pc extends mi{provider="aws_elasticache";engines=["redis"]}class Ic extends mi{provider="server";engines=["postgres","mysql","mariadb","redis","mongodb","libsql"]}class mc extends mi{provider="container";engines=["postgres","mysql","mariadb","redis","mongodb","libsql"]}var zs=(e,t)=>{let r=e.desiredState;return e[t]??(r&&typeof r==="object"&&!Array.isArray(r)?r[t]:void 0)},Fe=(e,t,r)=>{let n=zs(e,t);return n==null?r:String(n)},Ot=(e,t)=>{let r=zs(e,t);return r==null?void 0:Number(r)},dn=(e,t)=>{let r=zs(e,t);return r==null?void 0:r===!0||r==="true"},Ei=(e,t)=>{let r=zs(e,t);return Array.isArray(r)?r.map(String):[]},Js=(e,t)=>Fe(t,"snapshotId")??`${e}-final-${new Date().toISOString().replace(/[^0-9]/g,"").slice(0,14)}`;function Bs(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 yc{client;constructor(e=new Un){this.client=e}async observe(e){return Bs(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:Fe(e,"username","app"),MasterUserPassword:t,DBName:Fe(e,"database"),AllocatedStorage:Ot(e,"storageGb"),VpcSecurityGroupIds:Ei(e,"securityGroupIds"),DBSubnetGroupName:Fe(e,"subnetGroup"),BackupRetentionPeriod:Ot(e,"backupRetentionDays")??7,MultiAZ:dn(e,"highAvailability"),EngineVersion:Fe(e,"engineVersion"),PubliclyAccessible:dn(e,"publicExposure")??!1,StorageType:Fe(e,"storageType","gp3"),StorageEncrypted:!0,KmsKeyId:Fe(e,"kmsKeyId"),DeletionProtection:!0,Tags:[{Key:"managed-by",Value:"ts-cloud"}]});return Bs(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 a=Js(e,r);return await this.client.createDBSnapshot({DBInstanceIdentifier:e,DBSnapshotIdentifier:a}),{status:"snapshotting",snapshotId:a}}if(t==="restore"){let a=String(r.targetId),s=await this.client.restoreDBInstanceFromDBSnapshot({DBInstanceIdentifier:a,DBSnapshotIdentifier:String(r.backupId),DBInstanceClass:Fe(r,"plan"),DBSubnetGroupName:Fe(r,"subnetGroup"),MultiAZ:dn(r,"highAvailability"),PubliclyAccessible:!1,StorageType:Fe(r,"storageType"),VpcSecurityGroupIds:Ei(r,"securityGroupIds"),DeletionProtection:!0,Tags:[{Key:"managed-by",Value:"ts-cloud"}]});return{...Bs(s.DBInstance),sourceId:e,restoreTargetId:a}}if(t==="delete"){if(r.retention==="retain")return{status:"retained"};let a=Js(e,r);return await this.client.modifyDBInstance({DBInstanceIdentifier:e,DeletionProtection:!1,ApplyImmediately:!0}),await this.client.deleteDBInstance({DBInstanceIdentifier:e,SkipFinalSnapshot:!1,FinalDBSnapshotIdentifier:a,DeleteAutomatedBackups:!1}),{status:"deleting",finalSnapshotId:a}}if(["resize","version","rotate","expose"].includes(t)){let a=await this.client.modifyDBInstance({DBInstanceIdentifier:e,DBInstanceClass:Fe(r,"plan"),AllocatedStorage:Ot(r,"storageGb"),MasterUserPassword:t==="rotate"?n:void 0,EngineVersion:Fe(r,"engineVersion"),MultiAZ:dn(r,"highAvailability"),PubliclyAccessible:dn(r,"publicExposure"),VpcSecurityGroupIds:Ei(r,"securityGroupIds"),ApplyImmediately:dn(r,"applyImmediately")??!0});return Bs(a.DBInstance)}throw Error(`RDS action ${t} requires an engine connection runner.`)}}function Ec(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 wc{client;constructor(e=new Un){this.client=e}async observe(e){let t=await this.client.describeDBClusters({DBClusterIdentifier:e});return Ec(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:Fe(e,"engineVersion"),MasterUsername:Fe(e,"username","app"),MasterUserPassword:t,DatabaseName:Fe(e,"database"),DBSubnetGroupName:Fe(e,"subnetGroup"),VpcSecurityGroupIds:Ei(e,"securityGroupIds"),BackupRetentionPeriod:Ot(e,"backupRetentionDays")??7,StorageEncrypted:!0,KmsKeyId:Fe(e,"kmsKeyId"),DeletionProtection:!0,ServerlessV2ScalingConfiguration:{MinCapacity:Ot(e,"minCapacity")??0.5,MaxCapacity:Ot(e,"maxCapacity")??4}}),await this.client.createDBInstance({DBInstanceIdentifier:`${r}-writer-1`,DBClusterIdentifier:r,DBInstanceClass:String(e.plan||"db.serverless"),Engine:n,PubliclyAccessible:dn(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=Js(e,r);return await this.client.createDBClusterSnapshot(e,i),{status:"snapshotting",snapshotId:i}}if(t==="restore"){let i=String(r.targetId),a=String(r.engine)==="postgres"?"aurora-postgresql":"aurora-mysql",s=await this.client.restoreDBClusterFromSnapshot({DBClusterIdentifier:i,SnapshotIdentifier:String(r.backupId),Engine:a,EngineVersion:Fe(r,"engineVersion"),DBSubnetGroupName:Fe(r,"subnetGroup"),VpcSecurityGroupIds:Ei(r,"securityGroupIds"),DeletionProtection:!0,ServerlessV2ScalingConfiguration:{MinCapacity:Ot(r,"minCapacity")??0.5,MaxCapacity:Ot(r,"maxCapacity")??4}});return await this.client.createDBInstance({DBInstanceIdentifier:`${i}-writer-1`,DBClusterIdentifier:i,DBInstanceClass:Fe(r,"plan","db.serverless"),Engine:a,PubliclyAccessible:!1}),{...Ec(s.DBCluster),sourceId:e,restoreTargetId:i}}if(t==="delete"){if(r.retention==="retain")return{status:"retained"};let i=Js(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:Ot(r,"minCapacity")==null&&Ot(r,"maxCapacity")==null?void 0:{MinCapacity:Ot(r,"minCapacity")??0.5,MaxCapacity:Ot(r,"maxCapacity")??4},EngineVersion:Fe(r,"engineVersion"),MasterUserPassword:t==="rotate"?n:void 0,ApplyImmediately:dn(r,"applyImmediately")??!0});return Ec(i.DBCluster)}throw Error(`Aurora action ${t} requires an engine connection runner.`)}}class Ac{client;constructor(e=new Ts){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:Ot(e,"nodes")??1,engineVersion:Fe(e,"engineVersion"),port:Ot(e,"port"),securityGroupIds:Ei(e,"securityGroupIds"),subnetGroupName:Fe(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 Xy,writeFile as qy}from"node:fs/promises";import{join as ew}from"node:path";async function jt(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(),a=new Response(n.stderr).text();if(t!=null)n.stdin.write(t),n.stdin.end();let[s,d,c]=await Promise.all([n.exited,i,a]);if(s!==0&&!r)throw Error(`Docker command failed (${s}): ${c.trim()||d.trim()}`);return{code:s,stdout:d,stderr:c}}class Bf{async ensureNetwork(e){if((await jt(["network","inspect",e],void 0,!0)).code!==0)await jt(["network","create","--internal",e])}async seedSecret(e,t){await jt(["volume","create",e]),await jt(["run","--rm","-i","-v",`${e}:/run/target`,"alpine:3.21","sh","-c","umask 077; cat > /run/target/credential"],t)}async removeVolume(e){await jt(["volume","rm",e],void 0,!0)}async inspect(e){let t=await jt(["inspect",e],void 0,!0);if(t.code!==0)return;return JSON.parse(t.stdout)[0]}async run(e){await jt(["run",...e])}async exec(e,t,r){return(await jt(["exec","-i",e,...t],r)).stdout}async update(e,t){await jt(["update",...t,e])}async restart(e){await jt(["restart",e])}async remove(e){await jt(["rm","--force",e],void 0,!0)}async logs(e,t){let r=await jt(["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 jt(["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 tw={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 $r(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 Hn(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 rw(e,t){let r=e.desiredState;return e[t]??(r&&typeof r==="object"&&!Array.isArray(r)?r[t]:void 0)}function Ra(e){return e.Config?.Labels??{}}class yi{runtime;backupRoot;constructor(e=new Bf,t=_t(process.cwd(),"backups","data")){this.runtime=e;this.backupRoot=t}async observe(e){let t=Hn(e),r=await this.runtime.inspect(t);if(!r)throw Error(`Data container ${t} was not found.`);let n=Ra(r),i=await this.runtime.stats(t),a=r.NetworkSettings?.Ports??{},s=Object.values(a).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=Hn(r),i=String(e.engine);if(i==="libsql")throw Error("libSQL requires an explicitly configured runtime image.");let a=tw[i];if(!a)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=$r(e.username),d=$r(rw(e,"database")),c=`${n}-secret`,o=`${n}-data`,g=i==="redis"?`appendonly yes
63
+ protected-mode yes
64
+ requirepass ${t.replaceAll("\\","\\\\").replaceAll(`
65
+ `,"")}
66
+ `:t;await this.runtime.ensureNetwork("ts-cloud-data"),await this.runtime.seedSecret(c,g);let h=["-d","--name",n,"--restart","unless-stopped","--network","ts-cloud-data","--label","managed-by=ts-cloud","--label",`ts-cloud.engine=${i}`,"--label",`ts-cloud.engine-version=${e.engineVersion??""}`,"--label",`ts-cloud.username=${s}`,"--label",`ts-cloud.database=${d}`,"-p",`127.0.0.1:${a.port}:${a.port}`,"-v",`${o}:${a.dataPath}`,"-v",`${c}:/run/ts-cloud-secrets:ro`];if(i==="postgres")h.push("-e",`POSTGRES_USER=${s}`,"-e",`POSTGRES_DB=${d}`,"-e","POSTGRES_PASSWORD_FILE=/run/ts-cloud-secrets/credential");if(i==="mysql"||i==="mariadb")h.push("-e",`MYSQL_USER=${s}`,"-e",`MYSQL_DATABASE=${d}`,"-e","MYSQL_PASSWORD_FILE=/run/ts-cloud-secrets/credential","-e","MYSQL_ROOT_PASSWORD_FILE=/run/ts-cloud-secrets/credential");if(i==="mongodb")h.push("-e",`MONGO_INITDB_ROOT_USERNAME=${s}`,"-e","MONGO_INITDB_ROOT_PASSWORD_FILE=/run/ts-cloud-secrets/credential");if(h.push(a.image),i==="redis")h.push("redis-server","/run/ts-cloud-secrets/credential");return await this.runtime.run(h),{providerId:n,status:"starting",engine:i,endpoint:"127.0.0.1",port:a.port,username:s,database:d}}async exportLogicalBackup(e){let t=Hn(e),r=await this.runtime.inspect(t);if(!r)throw Error(`Data container ${t} was not found.`);let n=Ra(r),i=n["ts-cloud.engine"],a=$r(n["ts-cloud.username"]),s=$r(n["ts-cloud.database"]),d;if(i==="postgres")d=await this.runtime.exec(t,["sh","-c",'export PGPASSWORD="$(cat /run/ts-cloud-secrets/credential)"; exec pg_dumpall --clean --if-exists -U "$POSTGRES_USER"']);else if(i==="mysql"||i==="mariadb")d=await this.runtime.exec(t,["sh","-c",'export MYSQL_PWD="$(cat /run/ts-cloud-secrets/credential)"; exec mysqldump -u root --all-databases --single-transaction --add-drop-database --routines --events --triggers']);else throw Error(`${i} does not support engine-native SQL backups.`);return{body:new TextEncoder().encode(d),engine:i,database:s,username:a,engineVersion:n["ts-cloud.engine-version"]||void 0}}async restoreLogicalBackup(e){let t=Hn(e.sourceId),r=Hn(e.targetId),n=await this.runtime.inspect(t);if(!n)throw Error(`Data container ${t} was not found.`);let i=Ra(n),a=i["ts-cloud.engine"],s=$r(i["ts-cloud.username"]),d=$r(i["ts-cloud.database"]);if(!["postgres","mysql","mariadb"].includes(a))throw Error(`${a} does not support engine-native SQL restores.`);if(!e.inPlace){if(e.sourceId===e.targetId)throw Error("An isolated restore requires a distinct target identifier.");if(await this.runtime.inspect(r))throw Error(`Restore target ${r} already exists.`);await this.apply({id:e.targetId,engine:a,engineVersion:i["ts-cloud.engine-version"]??"",username:s,database:d,publicExposure:!1},e.credential)}let c=a==="postgres"?["sh","-c",'export PGPASSWORD="$(cat /run/ts-cloud-secrets/credential)"; exec psql -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d postgres']:["sh","-c",'export MYSQL_PWD="$(cat /run/ts-cloud-secrets/credential)"; exec mysql -u root'],o=new TextDecoder("utf-8",{fatal:!0}).decode(e.body),g;for(let h=0;h<30;h++)try{await this.runtime.exec(r,c,o);let _=a==="postgres"?["sh","-c",'export PGPASSWORD="$(cat /run/ts-cloud-secrets/credential)"; exec psql -U "$POSTGRES_USER" -Atc "SELECT 1"']:["sh","-c",'export MYSQL_PWD="$(cat /run/ts-cloud-secrets/credential)"; exec mysql -u root -N -e "SELECT 1"'];if((await this.runtime.exec(r,_)).trim()!=="1")throw Error("Restored database health probe returned an unexpected result.");return{status:"available",providerId:r,engine:a,database:d,username:s,healthy:!0}}catch(_){if(g=_,h<29)await Bun.sleep(1000)}throw g instanceof Error?g:Error("Restored database did not become ready.")}async removeRestoredService(e){let t=Hn(e);await this.runtime.remove(t),await this.runtime.removeVolume(`${t}-secret`),await this.runtime.removeVolume(`${t}-data`)}async backup(e,t){let r=await this.exportLogicalBackup(e),{engine:n,database:i,username:a}=r,s=String(t.snapshotId??`${e}-${new Date().toISOString().replace(/[^0-9]/g,"").slice(0,14)}`);if(!/^[A-Za-z0-9_.-]{2,120}$/.test(s))throw Error("Backup identifier contains unsupported characters.");await Xy(this.backupRoot,{recursive:!0,mode:448});let d=ew(this.backupRoot,`${s}.sql`);return await qy(d,r.body,{mode:384}),{status:"available",backupId:s,path:d,engine:n,database:i,username:a}}async execute(e,t,r,n){let i=Hn(e);if(t==="observe")return this.observe(e);if(t==="backup")return this.backup(e,r);if(t==="restart")return await this.runtime.restart(i),{status:"restarting"};if(t==="logs"||t==="slow_queries")return{logs:await this.runtime.logs(i,Number(r.lines)||500)};if(t==="databases"||t==="users"){let a=await this.runtime.inspect(i);if(!a)throw Error(`Data container ${i} was not found.`);let s=Ra(a),d=s["ts-cloud.engine"],c=$r(s["ts-cloud.username"]),o=String(r.operation??"list");if(!["postgres","mysql","mariadb"].includes(d))throw Error(`${t} is available only for SQL runtime engines.`);if(t==="users"&&o!=="list")throw Error("Creating users requires a referenced secondary credential.");if(o==="list"){let g=d==="postgres"?["sh","-c",`export PGPASSWORD="$(cat /run/ts-cloud-secrets/credential)"; exec psql -U "$POSTGRES_USER" -Atc '${t==="databases"?"SELECT datname FROM pg_database WHERE datistemplate = false ORDER BY datname":"SELECT usename FROM pg_user ORDER BY usename"}'`]:["sh","-c",`export MYSQL_PWD="$(cat /run/ts-cloud-secrets/credential)"; exec mysql -u root -N -e '${t==="databases"?"SHOW DATABASES":"SELECT User FROM mysql.user ORDER BY User"}'`],h=await this.runtime.exec(i,g);return{[t]:h.split(`
67
+ `).map((_)=>_.trim()).filter(Boolean)}}if(t==="databases"&&["create","delete"].includes(o)){let g=$r(r.database);if(o==="delete"&&r.confirm!==g)throw Error(`Type ${g} to confirm logical database deletion.`);let h=d==="postgres"?`${o==="create"?"CREATE":"DROP"} DATABASE "${g}";
68
+ `:`${o==="create"?"CREATE":"DROP"} DATABASE \`${g}\`;
69
+ `,_=d==="postgres"?["sh","-c",'export PGPASSWORD="$(cat /run/ts-cloud-secrets/credential)"; exec psql -U "$POSTGRES_USER"']:["sh","-c",'export MYSQL_PWD="$(cat /run/ts-cloud-secrets/credential)"; exec mysql -u root'];return await this.runtime.exec(i,_,h),{status:"available",database:g,operation:o}}throw Error(`Unsupported ${t} operation ${o}.`)}if(t==="resize"){let a=[];if(r.memoryMb)a.push("--memory",`${Number(r.memoryMb)}m`);if(r.cpus)a.push("--cpus",String(Number(r.cpus)));if(!a.length)throw Error("Resize requires memoryMb or cpus.");return await this.runtime.update(i,a),{status:"running",memoryMb:r.memoryMb??null,cpus:r.cpus??null}}if(t==="rotate"){if(!n)throw Error("Credential rotation requires a generated secret.");let a=await this.runtime.inspect(i);if(!a)throw Error(`Data container ${i} was not found.`);let s=Ra(a),d=s["ts-cloud.engine"],c=$r(s["ts-cloud.username"]),o=n.replaceAll("'","''").replaceAll(`
70
+ `,"");if(d==="postgres")await this.runtime.exec(i,["sh","-c",'export PGPASSWORD="$(cat /run/ts-cloud-secrets/credential)"; exec psql -U "$POSTGRES_USER"'],`ALTER USER "${c}" PASSWORD '${o}';
71
+ `);else if(d==="mysql"||d==="mariadb")await this.runtime.exec(i,["sh","-c",'export MYSQL_PWD="$(cat /run/ts-cloud-secrets/credential)"; exec mysql -u root'],`ALTER USER '${c}'@'%' IDENTIFIED BY '${o}';
72
+ `);else if(d!=="redis")throw Error(`${d} credential rotation requires an engine runner.`);let g=d==="redis"?`appendonly yes
73
+ protected-mode yes
74
+ requirepass ${n.replaceAll("\\","\\\\").replaceAll(`
75
+ `,"")}
76
+ `:n;if(await this.runtime.seedSecret(`${i}-secret`,g),d==="redis")await this.runtime.restart(i);return{status:d==="redis"?"restarting":"running",username:c}}if(t==="delete"){if(r.retention==="retain")return{status:"retained"};let a=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:a.backupId??null,backupPath:a.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 nw,createDecipheriv as iw,createHash as Jf,randomBytes as aw}from"node:crypto";class Pc{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=Jf("sha256").update(`ts-cloud:data-services:${t}`).digest()}encrypt(e){let t=aw(12),r=nw("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 a=iw("aes-256-gcm",this.key,Buffer.from(r,"base64url"));return a.setAuthTag(Buffer.from(n,"base64url")),Buffer.concat([a.update(Buffer.from(i,"base64url")),a.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),Jf("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 pa}from"node:fs";import{mkdir as js,readdir as sw,rename as Dc,rm as wi}from"node:fs/promises";import{relative as ow,resolve as At,sep as Us}from"node:path";function Nn(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 Cr(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 $c(e,t){let r=Bun.spawn(["tar",...e],{stdin:t?Buffer.from(t):void 0,stdout:"pipe",stderr:"pipe"}),[n,i,a]=await Promise.all([r.exited,new Response(r.stdout).arrayBuffer(),new Response(r.stderr).text()]);if(n!==0)throw Error(a.trim()||`tar exited with status ${n}.`);return{stdout:Buffer.from(i),stderr:a}}function dw(e){let t=e.replaceAll("\\","/").replace(/^\.\//,"");return!!t&&!t.startsWith("/")&&!t.split("/").includes("..")}class zf{async create(e,t,r){return(await $c(["-C",e,"-cf","-",...r.map((i)=>`--exclude=${i}`),"--",...t])).stdout}async extract(e,t){await js(t,{recursive:!0,mode:448}),await $c(["-C",t,"-xf","-"],e)}async inspect(e){let t=await $c(["-tf","-"],e),r=t.stdout.toString().split(`
77
+ `).filter(Boolean);if(r.some((n)=>!dw(n)))throw Error("Backup archive contains an unsafe path.");return{entries:r,bytes:e.byteLength}}}function Tf(e,t){if(!t.trim())throw Error("File backup paths cannot be empty.");let r=At(e,t),n=ow(e,r);if(n===".."||n.startsWith(`..${Us}`)||n==="")throw Error(`File backup path ${t} is outside the project root.`);return n}function Ws(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 Cc{runtime;root;restoreRoot;constructor(e,t=new zf,r=_t(e,"restores","files")){this.runtime=t;this.root=At(e),this.restoreRoot=At(r)}paths(e){let t=[...new Set(e.includePatterns.map((r)=>Tf(this.root,r)))];if(!t.length)throw Error("File backup policies require at least one project-relative path.");for(let r of t)if(!pa(At(this.root,r)))throw Error(`File backup path ${r} was not found.`);return t.filter((r)=>!t.some((n)=>n!==r&&r.startsWith(`${n}${Us}`)))}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),a=e.compression??"none",s=Nn(n,a),d=String(t.operation?.id??new Date().toISOString()).replace(/[^A-Za-z0-9]/g,"").slice(0,32);return{mode:"object",key:`${e.projectId}/files/${d}.tar${a==="none"?"":a==="gzip"?".gz":".zst"}`,body:s,contentType:a==="gzip"?"application/gzip":a==="zstd"?"application/zstd":"application/x-tar",manifest:{archive:"tar",compression:a,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=Cr(t,String(e.manifest.compression??"none"));if(await this.runtime.inspect(i),r.restoreMode==="in_place"){let s=At(this.restoreRoot,`.staging-${Ws(r)}`),d=At(this.restoreRoot,`.rollback-${Ws(r)}`),c=Array.isArray(e.manifest.sourcePaths)?e.manifest.sourcePaths.map(String):[];if(!c.length)throw Error("File recovery point has no source path manifest.");await wi(s,{recursive:!0,force:!0}),await wi(d,{recursive:!0,force:!0}),await this.runtime.extract(i,s),await js(d,{recursive:!0,mode:448});let o=[];try{for(let g of c){let h=At(this.root,Tf(this.root,g)),_=At(s,g),R=At(d,g);if(await js(At(R,".."),{recursive:!0}),pa(h))await Dc(h,R);await js(At(h,".."),{recursive:!0}),await Dc(_,h),o.push(g)}}catch(g){for(let h of o.reverse()){let _=At(this.root,h),R=At(d,h);if(await wi(_,{recursive:!0,force:!0}),pa(R))await Dc(R,_)}throw g}finally{await wi(s,{recursive:!0,force:!0})}return await wi(d,{recursive:!0,force:!0}),{path:this.root,restoredPaths:c,inPlace:!0}}let a=At(this.restoreRoot,Ws(r));if(pa(a))throw Error("The isolated file restore target already exists.");return await this.runtime.extract(i,a),{path:a,isolated:!0}}async verify(e,t,r){let n=Cr(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}${Us}`)||!pa(r))throw Error("Isolated file restore target was not found.");let n=await sw(r);return{healthy:!0,path:r,topLevelEntries:n.length}}async cleanup(e,t){let r=Ws(e),n=At(this.restoreRoot,r);if(!n.startsWith(`${this.restoreRoot}${Us}`))throw Error("Refusing to clean a file restore outside the restore root.");await wi(n,{recursive:!0,force:!0})}}class kc{services;secrets;transport;constructor(e,t,r=new yi){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",a=Nn(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:a,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??""),a=String(r.dataServiceId??r.targetId??""),s=r.inPlace===!0;if(!i||!a)throw Error("Logical database restore requires source and target identifiers.");if(s&&a!==i)throw Error("An in-place restore must target the source data service.");let d=this.services.get(i);if(!d?.credentialRef)throw Error("Logical database credential reference was not found.");let c=await this.secrets.resolve(d.credentialRef);return this.transport.restoreLogicalBackup({sourceId:i,targetId:a,body:Cr(t,String(e.manifest.compression??"none")),credential:c,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 bc=/^[A-Za-z0-9][A-Za-z0-9_.-]{1,127}$/;async function Fn(e,t,r=!1){let n=Bun.spawn(["docker",...e],{stdin:t?"pipe":"ignore",stdout:"pipe",stderr:"pipe"}),i=new Response(n.stdout).arrayBuffer(),a=new Response(n.stderr).text();if(t)n.stdin.write(t),n.stdin.end();let[s,d,c]=await Promise.all([n.exited,i,a]);if(s!==0&&!r)throw Error(`Docker volume command failed (${s}): ${c.trim()}`);return{code:s,stdout:Buffer.from(d),stderr:c}}class Wf{async exists(e){return(await Fn(["volume","inspect",e],void 0,!0)).code===0}async export(e){return(await Fn(["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 Fn(["volume","create",e]);try{if(r)await Fn(["run","--rm","-v",`${e}:/target`,"alpine:3.21","sh","-c","find /target -mindepth 1 -delete"]);await Fn(["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 Fn(["volume","rm",e],void 0,!0)}async probe(e){let t=(await Fn(["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 vc{runtime;constructor(e=new Wf){this.runtime=e}async create(e,t){let r=String(e.includePatterns?.[0]??e.resourceId??"");if(!bc.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))),a=e.compression??"gzip",s=a==="gzip"?n:Nn(i,a),d=String(t.operation?.id??new Date().toISOString()).replace(/[^A-Za-z0-9]/g,"").slice(0,32);return{mode:"object",key:`${e.projectId}/volumes/${r}/${d}.tar${a==="none"?"":a==="gzip"?".gz":".zst"}`,body:s,contentType:a==="gzip"?"application/gzip":a==="zstd"?"application/zstd":"application/x-tar",toolVersion:"alpine-tar",manifest:{format:"docker-volume-tar-v1",archive:"tar",compression:a,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??""),a=String(r.volumeName??r.targetId??"");if(!bc.test(a))throw Error("Volume restore requires a valid target volume name.");if(a===i&&r.inPlace!==!0)throw Error("An isolated volume restore requires a distinct target.");let s=await this.runtime.exists(a);if(!r.inPlace&&s)throw Error(`Restore target volume ${a} already exists.`);if(r.inPlace===!0&&a!==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 d=String(e.manifest.compression??"gzip"),c=d==="gzip"?Buffer.from(t):Buffer.from(Bun.gzipSync(Uint8Array.from(Cr(t,d))));await this.runtime.import(a,c,r.inPlace===!0);let o=await this.runtime.probe(a);return{volumeName:a,healthy:!0,...o}}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(!bc.test(r))throw Error("Volume cleanup requires a valid target volume name.");await this.runtime.remove(r)}}import{existsSync as Oc}from"node:fs";import{mkdir as cw,readFile as jf,rm as lw,writeFile as Uf}from"node:fs/promises";import{basename as Lf,resolve as cn,sep as Hf}from"node:path";import{Database as gw}from"bun:sqlite";function Nf(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 Ff(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)=>Lf(r.name)!==r.name))throw Error("Control-plane backup contains an unsafe config path.");return t}function Vf(e){let t=gw.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 Bc{controlPlane;root;restoreRoot;constructor(e,t,r=_t(t,"restores","control-plane")){this.controlPlane=e;this.root=cn(t),this.restoreRoot=cn(r)}async create(e,t){let r=e.includePatterns.length?e.includePatterns:["cloud.config.ts"],n=[];for(let c of r){let o=Lf(c),g=cn(this.root,o);if(o!==c&&c!==`./${o}`)throw Error("Control-plane config paths must be project-root files.");if(Oc(g))n.push({name:o,body:(await jf(g)).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},a=e.compression??"none",s=Nn(Buffer.from(JSON.stringify(i)),a),d=String(t.operation?.id??i.createdAt).replace(/[^A-Za-z0-9]/g,"").slice(0,32);return{mode:"object",key:`${e.projectId}/control-plane/${d}.json${a==="none"?"":a==="gzip"?".gz":".zst"}`,body:s,contentType:a==="gzip"?"application/gzip":a==="zstd"?"application/zstd":"application/vnd.ts-cloud.control-plane+json",manifest:{format:i.format,configFiles:n.map((c)=>c.name),sensitive:!0,compression:a},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=Ff(Cr(t,String(e.manifest.compression??"none"))),a=cn(this.restoreRoot,Nf(r));if(Oc(a))throw Error("The isolated control-plane restore target already exists.");await cw(a,{recursive:!0,mode:448}),await Uf(cn(a,"control-plane.sqlite"),Buffer.from(i.database,"base64"),{mode:384});for(let s of i.config)await Uf(cn(a,s.name),Buffer.from(s.body,"base64"),{mode:384});return{path:a,isolated:!0,configFiles:i.config.length}}async verify(e,t,r){let n=Ff(Cr(t,String(e.manifest.compression??"none")));return{...Vf(Buffer.from(n.database,"base64")),configFiles:n.config.length}}async validateHealth(e,t){let r=String(e.path??""),n=cn(r,"control-plane.sqlite");if(!r.startsWith(`${this.restoreRoot}${Hf}`)||!Oc(n))throw Error("Isolated control-plane database was not found.");return{healthy:!0,...Vf(await jf(n))}}async cleanup(e,t){let r=cn(this.restoreRoot,Nf(e));if(!r.startsWith(`${this.restoreRoot}${Hf}`))throw Error("Refusing to clean a control-plane restore outside the restore root.");await lw(r,{recursive:!0,force:!0})}}import{createHash as uw}from"node:crypto";function Jc(e,t){return e.find((r)=>r.startsWith(`${t}:`))?.slice(t.length+1)}function hw(e){let t=Jc(e.includePatterns,"resource")??e.includePatterns.find((i)=>i.startsWith("arn:")),r=Jc(e.includePatterns,"role"),n=Jc(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 fw(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 Sw(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 Tc{client;constructor(e=new Hs){this.client=e}async create(e,t){let r=hw(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}),a=await fw(this.client,i.BackupJobId,t),s=`sha256:${uw("sha256").update(a.recoveryPointArn).digest("hex")}`;return{mode:"external",uri:a.recoveryPointArn,checksum:s,sizeBytes:a.sizeBytes,toolVersion:"aws-backup-api",manifest:{provider:"aws_backup",resourceArn:r.resourceArn,roleArn:r.roleArn,vaultName:r.vaultName,providerBackupJobId:i.BackupJobId,recoveryPointArn:a.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??""),a=r.metadata&&typeof r.metadata==="object"&&!Array.isArray(r.metadata)?Object.fromEntries(Object.entries(r.metadata).map(([c,o])=>[c,String(o)])):{};if(!i.startsWith("arn:"))throw Error("AWS Backup restore requires an IAM role ARN.");if(!Object.keys(a).length)throw Error("AWS Backup restore requires provider restore metadata.");let s=await this.client.startRestoreJob({RecoveryPointArn:e.uri,IamRoleArn:i,Metadata:a,IdempotencyToken:String(n.operation.id).replace(/[^A-Za-z0-9-]/g,"").slice(0,64)}),d=await Sw(this.client,s.RestoreJobId,n);return{providerRestoreJobId:s.RestoreJobId,createdResourceArn:d,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 AP}from"node:fs";import{join as f_}from"node:path";import{pathToFileURL as PP}from"node:url";import{existsSync as xf,statSync as Mf}from"fs";import{existsSync as _w,mkdirSync as HB,readdirSync as NB,readFileSync as Rw,writeFileSync as FB}from"fs";import{homedir as Ai}from"os";import{dirname as xB,resolve as Lt}from"path";import Eo from"process";import{existsSync as Qf,statSync as Gf}from"fs";import{existsSync as rl,mkdirSync as pw,readdirSync as Iw,writeFileSync as mw}from"fs";import{homedir as Pi}from"os";import{dirname as Zf,resolve as Dt}from"path";import Vn from"process";import{join as Ew,relative as yw,resolve as Kf}from"path";import oo from"process";import{existsSync as BS,mkdirSync as t1,readdirSync as r1,writeFileSync as n1}from"fs";import{homedir as zc}from"os";import{dirname as s1,resolve as Pt}from"path";import ma from"process";import{join as ww,relative as Aw,resolve as Yf}from"path";import co from"process";import{existsSync as JS,mkdirSync as g1,readdirSync as u1,writeFileSync as h1}from"fs";import{dirname as S1,resolve as lo}from"path";import nl from"process";import{Buffer as ln}from"buffer";import{createCipheriv as Pw,createDecipheriv as Dw,randomBytes as Wc}from"crypto";import{closeSync as jc,createReadStream as Xf,createWriteStream as $w,existsSync as Uc,fsyncSync as qf,openSync as eS,writeFileSync as Cw}from"fs";import{access as kw,constants as tS,mkdir as bw,readdir as Ns,rename as rS,stat as Di,unlink as Fs,writeFile as Hc}from"fs/promises";import{join as $i}from"path";import ct from"process";import{pipeline as vw}from"stream/promises";import{createGzip as nS}from"zlib";import Ci from"process";import vr from"process";import{Buffer as kr}from"buffer";import{createCipheriv as Ow,createDecipheriv as Bw,randomBytes as Nc}from"crypto";import{closeSync as Fc,createReadStream as iS,createWriteStream as Jw,existsSync as Vs,fsyncSync as aS,openSync as sS,writeFileSync as Tw}from"fs";import{access as zw,constants as oS,mkdir as Ww,readdir as Ls,rename as dS,stat as ki,unlink as xs,writeFile as Vc}from"fs/promises";import{isAbsolute as jw,join as bi,resolve as Uw}from"path";import me from"process";import{pipeline as Hw}from"stream/promises";import{createGzip as cS}from"zlib";import vi from"process";import Or from"process";import Ms from"process";import{existsSync as Qs}from"fs";import{resolve as Lc}from"path";import{existsSync as Nw}from"fs";import{existsSync as Fw,readdirSync as Vw}from"fs";import{extname as xc,resolve as lS}from"path";import Lw from"process";import{join as xw,relative as Mw,resolve as gS}from"path";import go from"process";import{Buffer as br}from"buffer";import{createCipheriv as Qw,createDecipheriv as Gw,randomBytes as Mc}from"crypto";import{closeSync as Qc,createReadStream as uS,createWriteStream as Zw,existsSync as Gs,fsyncSync as hS,openSync as fS,writeFileSync as Kw}from"fs";import{access as Yw,constants as SS,mkdir as Xw,readdir as Zs,rename as _S,stat as Oi,unlink as Ks,writeFile as Gc}from"fs/promises";import{isAbsolute as qw,join as Bi,resolve as eA}from"path";import Ee from"process";import{pipeline as tA}from"stream/promises";import{createGzip as RS}from"zlib";import Ji from"process";import Br from"process";import Xs from"process";import{existsSync as qs}from"fs";import{resolve as el}from"path";import{existsSync as EP}from"fs";class vS{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),a=n??this.options.ttl,s=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:a,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(!xf(e))return!0;return Mf(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=xf(r)?Mf(r):null,a=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:a},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 OS{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let a=await t(),s=performance.now()-n;return this.recordMetric({operation:e,duration:s,timestamp:i,...r}),a}catch(a){let s=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:s,timestamp:i,...r}),a}}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,a)=>i+a,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 so=new vS,fl=new OS;var rA=Object.defineProperty,nA=(e)=>e;function iA(e,t){this[e]=nA.bind(null,t)}var aA=(e,t)=>{for(var r in t)rA(e,r,{get:t[r],enumerable:!0,configurable:!0,set:iA.bind(t,r)})},sA=(e,t)=>()=>(e&&(t=e(e=0)),t),TS={};aA(TS,{withErrorRecovery:()=>jS,tryLoadConfig:()=>kA,loadConfigWithResult:()=>$A,loadConfig:()=>VS,isRetryableError:()=>EA,isConfigNotFoundError:()=>mA,isBunfigError:()=>US,globalPerformanceMonitor:()=>wa,globalCache:()=>Ti,getEnvOrDefault:()=>yA,generateConfigTypes:()=>bA,defaultGeneratedDir:()=>YS,defaultConfigDir:()=>KS,deepMergeWithArrayStrategy:()=>Il,deepMerge:()=>HS,createLibraryConfig:()=>vA,config:()=>CA,bunfigPlugin:()=>OA,applyEnvVarsToConfig:()=>Ia,TypeGenerationError:()=>ll,SchemaValidationError:()=>ya,PluginError:()=>ul,PerformanceMonitor:()=>_l,FileSystemError:()=>cl,ErrorFactory:()=>gn,EnvVarError:()=>Ro,EnvProcessor:()=>yo,ConfigValidator:()=>ml,ConfigValidationError:()=>ol,ConfigNotFoundError:()=>_o,ConfigMergeError:()=>dl,ConfigLoader:()=>El,ConfigLoadError:()=>Ea,ConfigFileLoader:()=>wo,ConfigCache:()=>Sl,CacheUtils:()=>xS,BunfigError:()=>Ut,BrowserConfigError:()=>gl,ArrayMergeStrategies:()=>GS});class Sl{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),a=n??this.options.ttl,s=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:a,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(!Qf(e))return!0;return Gf(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=Qf(r)?Gf(r):null,a=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:a},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 _l{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let a=await t(),s=performance.now()-n;return this.recordMetric({operation:e,duration:s,timestamp:i,...r}),a}catch(a){let s=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:s,timestamp:i,...r}),a}}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,a)=>i+a,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 oA(e,t={}){let n=Object.keys(t).sort().map((i)=>`${i}:${t[i]}`).join("|");return n?`${e}:${n}`:e}function dA(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function cA(e){return e.getStats().size*2}function Rl(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Ue(t[0])&&"id"in t[0]&&t[0].id===3&&Ue(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Ue(t)&&Ue(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(Ue(e)&&"arr"in e&&Array.isArray(e.arr)&&Ue(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Ue(t[0])&&Ue(e[0])){let n=[...t];for(let i of e)if(Ue(i)&&"name"in i){if(!n.find((s)=>Ue(s)&&("name"in s)&&s.name===i.name))n.push(i)}else if(Ue(i)&&"path"in i){if(!n.find((s)=>Ue(s)&&("path"in s)&&s.path===i.path))n.push(i)}else if(!n.some((a)=>uo(a,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(!Ue(t)||!Ue(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(Ue(i)&&Ue(r[n]))r[n]=Rl(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&Ue(i[0])&&Ue(r[n][0])){let a=[...i];for(let s of r[n])if(Ue(s)&&"name"in s){if(!a.find((c)=>Ue(c)&&("name"in c)&&c.name===s.name))a.push(s)}else if(Ue(s)&&"path"in s){if(!a.find((c)=>Ue(c)&&("path"in c)&&c.path===s.path))a.push(s)}else if(!a.some((d)=>uo(d,s)))a.push(s);r[n]=a}else if(i.every((a)=>typeof a==="string")&&r[n].every((a)=>typeof a==="string")){let a=[...i];for(let s of r[n])if(!a.includes(s))a.push(s);r[n]=a}else r[n]=i;else r[n]=i}return r}function uo(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(!uo(e[r],t[r]))return!1;return!0}if(Ue(e)&&Ue(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(!uo(e[i],t[i]))return!1}return!0}return!1}function Ue(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function lA(e,t){if(!JS(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 Rl(t,n)}catch{return null}}catch{return null}}async function gA({name:e="",cwd:t,defaultConfig:r}){let n=t||nl.cwd(),i=[".ts",".js",".mjs",".cjs",".json"],a=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let s of a)for(let d of i){let c=lo(n,`${s}${d}`),o=await lA(c,r);if(o!==null)return o}try{let s=lo(n,"package.json");if(JS(s)){let c=(await import(s))[e];if(c&&typeof c==="object"&&!Array.isArray(c))try{return Rl(r,c)}catch{}}}catch{}return r}function uA(e,t={}){let r=co.cwd();while(r.includes("storage"))r=Yf(r,"..");let n=Yf(r,e||"");if(t?.relative)return Aw(co.cwd(),n);return n}async function hA(){try{let e=await gA({name:"clarity",defaultConfig:ro,cwd:co.cwd(),endpoint:"",headers:{}});return{...ro,...e}}catch{return ro}}function Le(){if(vr.env.NODE_ENV==="test"||vr.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function fA(){if(vr.env.NODE_ENV==="test"||vr.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof vr<"u"){let e=vr.type;if(e==="renderer"||e==="worker")return!1;return!!(vr.versions&&(vr.versions.node||vr.versions.bun))}return!1}class zS{async format(e){let t=await fA(),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:Ci.pid,hostname:t(),environment:Ci.env.NODE_ENV||"development",platform:Ci.platform,version:Ci.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Ci.env.NODE_ENV||Ci.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class ho{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={...al},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new zS,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??ct.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(),a=this.generateKey();this.currentKeyId=i,this.keys.set(i,a),this.encryptionKeys.set(i,{key:a,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...no,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...no};return{...no,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:al.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,a=0,s=3,d=1000;while(a<s)try{try{try{await kw(this.config.logDirectory,tS.F_OK|tS.W_OK)}catch(o){if(o instanceof Error&&"code"in o)if(o.code==="ENOENT")await bw(this.config.logDirectory,{recursive:!0,mode:493});else if(o.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw o;else throw o}}catch(o){throw console.error("Debug: [writeToFile] Failed to create log directory:",o),o}let c=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:ln.from(e);try{if(!Uc(this.currentLogFile))await Hc(this.currentLogFile,"",{mode:420});if(i=eS(this.currentLogFile,"a",420),Cw(i,c,{flag:"a"}),qf(i),i!==void 0)jc(i),i=void 0;if((await Di(this.currentLogFile)).size===0){if(await Hc(this.currentLogFile,c,{flag:"w",mode:420}),(await Di(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(o){let g=o;if(g.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(g.code)){if(a<s-1){let h=typeof g.message==="string"?g.message:"Unknown error";console.error(`Network error during write attempt ${a+1}/${s}:`,h);let _=d*2**a;await new Promise((R)=>setTimeout(R,_)),a++;continue}}if(g?.code&&["ENOSPC","EDQUOT"].includes(g.code))throw Error(`Disk quota exceeded or no space left on device: ${g.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",g),g}finally{if(i!==void 0)try{jc(i)}catch(o){console.error("Debug: [writeToFile] Error closing file descriptor:",o)}}}catch(c){if(a===s-1){let g=c,h=typeof g.message==="string"?g.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),c}a++;let o=d*2**(a-1);await new Promise((g)=>setTimeout(g,o))}})();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 $i(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 $i(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return $i(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Le())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(([,d],[,c])=>c.createdAt.getTime()-d.createdAt.getTime()),a=typeof t.maxKeys==="number"?t.maxKeys:1,s=Math.max(1,a);if(i.length>s)for(let[d]of i.slice(s))this.encryptionKeys.delete(d),this.keys.delete(d)}generateKeyId(){return Wc(16).toString("hex")}generateKey(){return Wc(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=Wc(16),n=Pw("aes-256-gcm",t,r),i=ln.concat([n.update(e,"utf8"),n.final()]),a=n.getAuthTag();return{encrypted:ln.concat([r,i,a]),iv:r}}async compressData(e){return new Promise((t,r)=>{let n=nS(),i=[];n.on("data",(a)=>i.push(a)),n.on("end",()=>t(ln.from(ln.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(Le())return;let e=await Di(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 Ns(this.config.logDirectory),a=i.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,o)=>{let g=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(o.match(/\.log\.(\d+)$/)?.[1]||"0")-g}),s=a.length>0?Number.parseInt(a[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,d=`${r}.${s}`;if(await Di(r).catch(()=>null))try{if(await rS(r,d),t.compress)try{let c=`${d}.gz`;await this.compressLogFile(d,c),await Fs(d)}catch(c){console.error("Error compressing rotated file:",c)}if(a.length===0&&!i.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await Hc(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),a=r.replace(/\.log$/,`-${i}.log`);if(await Di(r).catch(()=>null))await rS(r,a)}if(this.currentLogFile=n,t.maxFiles){let a=(await Ns(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,d)=>d.localeCompare(s));for(let s of a.slice(t.maxFiles))await Fs($i(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=Xf(e),n=$w(t),i=nS();await vw(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()})),Uc(this.currentLogFile))try{let e=eS(this.currentLogFile,"r+");qf(e),jc(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(!Le()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Ns(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Fs($i(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?Je.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:a,showTimestamp:s=!0}=e,d=(R)=>R.replace(this.ANSI_PATTERN,"");if(!this.fancy){let R=[];if(s)R.push(t);if(a==="warning")R.push("WARN");else if(a==="error")R.push("ERROR");else if(r)R.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)R.push(n.replace(/[[\]]/g,""));return R.push(i),R.join(" ")}let c=ct.stdout.columns||120,o="";if(a==="warning"||a==="error")o=`${r} ${i}`;else if(a==="info"||a==="success")o=`${r} ${n} ${i}`;else o=`${r} ${n} ${Je.cyan(i)}`;if(!s)return o.trim();let g=d(o).trim().length,h=d(t).length,_=Math.max(1,c-2-g-h);return`${o.trim()}${" ".repeat(_)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(a,s)=>{let d=Number.parseInt(s,10);return d<t[0].length?String(t[0][d]):a});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(a,s)=>{if(s==="%")return"%";if(n>=t.length)return a;let d=t[n++];switch(s){case"s":return String(d);case"d":case"i":return Number(d).toString();case"j":case"o":return JSON.stringify(d,null,2);default:return a}});if(n<t.length)i+=` ${t.slice(n).map((a)=>typeof a==="object"?JSON.stringify(a,null,2):String(a)).join(" ")}`;return i}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),a=this.formatFileTimestamp(n),s,d;if(t instanceof Error)s=t.message,d=t.stack;else s=this.formatMessage(t,r);if(this.fancy&&!Le()){let o=MS[e],g=this.options.showTags!==!1&&this.name?Je.gray(this.formatTag(this.name)):"",h;switch(e){case"debug":h=this.formatConsoleMessage({timestamp:i,icon:o,tag:g,message:Je.gray(s),level:e}),console.error(h);break;case"info":h=this.formatConsoleMessage({timestamp:i,icon:o,tag:g,message:s,level:e}),console.error(h);break;case"success":h=this.formatConsoleMessage({timestamp:i,icon:o,tag:g,message:Je.green(s),level:e}),console.error(h);break;case"warning":h=this.formatConsoleMessage({timestamp:i,icon:o,tag:g,message:s,level:e}),console.warn(h);break;case"error":if(h=this.formatConsoleMessage({timestamp:i,icon:o,tag:g,message:s,level:e}),console.error(h),d){let _=d.split(`
78
+ `);for(let R of _)if(R.trim()&&!R.includes(s))console.error(this.formatConsoleMessage({timestamp:i,message:Je.gray(` ${R}`),level:e,showTimestamp:!1}))}break}}else if(!Le()){if(console.error(`${a} ${this.environment}.${e.toUpperCase()}: ${s}`),d)console.error(d)}if(!this.shouldLog(e))return;let c=`${a} ${this.environment}.${e.toUpperCase()}: ${s}
79
+ `;if(d)c+=`${d}
80
+ `;c=c.replace(this.ANSI_PATTERN,""),await this.writeToFile(c)}time(e){let t=performance.now();if(this.fancy&&!Le()){let r=this.options.showTags!==!1&&this.name?Je.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:Je.blue("◐"),tag:r,message:`${Je.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),a=`${e} completed in ${i}ms`,s=new Date,d=this.formatConsoleTimestamp(s),o=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${a}`;if(r)o+=` ${JSON.stringify(r)}`;if(o+=`
81
+ `,o=o.replace(this.ANSI_PATTERN,""),this.fancy&&!Le()){let g=this.options.showTags!==!1&&this.name?Je.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:d,icon:Je.green("✓"),tag:g,message:`${a}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Le())console.error(o.trim());await this.writeToFile(o)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new ho(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(Le())throw Error("createReadStream is not supported in browser environments");if(!Uc(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Xf(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=ln.isBuffer(e)?e:ln.from(e,"base64"),i=n.slice(0,16),a=n.slice(-16),s=n.slice(16,-16),d=Dw("aes-256-gcm",r,i);return d.setAuthTag(a),ln.concat([d.update(s),d.final()]).toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Le()}isServerMode(){return!Le()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t);if(this.fancy&&!Le()){let a=e.split(`
82
+ `),s=Math.max(...a.map((g)=>g.length))+2,d=`┌${"─".repeat(s)}┐`,c=`└${"─".repeat(s)}┘`,o=a.map((g)=>{let h=" ".repeat(s-g.length-2);return`│ ${g}${h} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:Je.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:Je.cyan(d)})),o.forEach((g)=>console.error(this.formatConsoleMessage({timestamp:r,message:Je.cyan(g),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:Je.cyan(c),showTimestamp:!1}))}else if(!Le())console.error(`${n} ${this.environment}.INFO: [BOX] ${e}`);let i=`${n} ${this.environment}.INFO: [BOX] ${e}
83
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}async prompt(e){if(Le())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${Je.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();ct.stdin.removeListener("data",r);try{if(typeof ct.stdin.setRawMode==="function")ct.stdin.setRawMode(!1)}catch{}ct.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof ct.stdin.setRawMode==="function")ct.stdin.setRawMode(!0)}catch{}ct.stdin.resume(),ct.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let s=/%([sdijfo%])/g,d=0;if(r=e.replace(s,(c,o)=>{if(o==="%")return"%";if(d>=t.length)return c;let g=t[d++];switch(o){case"s":return String(g);case"d":case"i":return Number(g).toString();case"j":case"o":return JSON.stringify(g,null,2);default:return c}}),d<t.length)r+=` ${t.slice(d).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`}if(this.fancy&&!Le()){let s=this.options.showTags!==!1&&this.name?Je.gray(this.formatTag(this.name)):"",d=Je.blue("◐");console.error(`${d} ${s} ${Je.cyan(r)}`)}let a=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
84
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(a)}progress(e,t=""){if(!this.enabled||!this.fancy||Le()||e<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let r=20;return this.activeProgressBar={total:e,current:0,message:t,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(s,d)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Le())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,s)),d!==void 0)this.activeProgressBar.message=d;let c=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,c)},finish:(s)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Le())return;if(this.activeProgressBar.current=this.activeProgressBar.total,s!==void 0)this.activeProgressBar.message=s;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(s,d="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Le())return;ct.stdout.write(`${"\r".padEnd(ct.stdout.columns||80)}\r`),this.log(d,s),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(e,t=!1){if(!this.enabled||!this.fancy||Le()||!ct.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,a=Je.green("━".repeat(n)),s=Je.gray("━".repeat(i)),d=`[${a}${s}]`,c=`${r}%`.padStart(4),o=e.message?` ${e.message}`:"",g=t||r===100?Je.green("✓"):Je.blue("▶"),h=this.options.showTags!==!1&&this.name?` ${Je.gray(this.formatTag(this.name))}`:"",_=`\r${g}${h} ${d} ${c}${o}`,R=ct.stdout.columns||80,E=" ".repeat(Math.max(0,R-_.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${_}${E}`,ct.stdout.write(e.lastRenderedLine),t)ct.stdout.write(`
85
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Le()||!ct.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(Le()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Ns(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let a=$i(this.config.logDirectory,n);if(e.before)try{if((await Di(a)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${a}:`,s);continue}r.push(a)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Fs(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function to(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Ce(t[0])&&"id"in t[0]&&t[0].id===3&&Ce(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Ce(t)&&Ce(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(Ce(e)&&"arr"in e&&Array.isArray(e.arr)&&Ce(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Ce(t[0])&&Ce(e[0])){let n=[...t];for(let i of e)if(Ce(i)&&"name"in i){if(!n.find((s)=>Ce(s)&&("name"in s)&&s.name===i.name))n.push(i)}else if(Ce(i)&&"path"in i){if(!n.find((s)=>Ce(s)&&("path"in s)&&s.path===i.path))n.push(i)}else if(!n.some((a)=>fo(a,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(!Ce(t)||!Ce(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(Ce(i)&&Ce(r[n]))r[n]=to(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&Ce(i[0])&&Ce(r[n][0])){let a=[...i];for(let s of r[n])if(Ce(s)&&"name"in s){if(!a.find((c)=>Ce(c)&&("name"in c)&&c.name===s.name))a.push(s)}else if(Ce(s)&&"path"in s){if(!a.find((c)=>Ce(c)&&("path"in c)&&c.path===s.path))a.push(s)}else if(!a.some((d)=>fo(d,s)))a.push(s);r[n]=a}else if(i.every((a)=>typeof a==="string")&&r[n].every((a)=>typeof a==="string")){let a=[...i];for(let s of r[n])if(!a.includes(s))a.push(s);r[n]=a}else r[n]=i;else r[n]=i}return r}function pl(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:to(e,t);if(Array.isArray(e))return r==="replace"?t:to(e,t);if(!Ce(t)||!Ce(e))return t;let n={...e};for(let i of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,i))continue;let a=t[i],s=n[i];if(a===null||a===void 0)continue;if(Array.isArray(a)||Array.isArray(s))if(r==="replace")n[i]=a;else n[i]=to(s,a);else if(Ce(a)&&Ce(s))n[i]=pl(s,a,r);else n[i]=a}return n}function fo(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(!fo(e[r],t[r]))return!1;return!0}if(Ce(e)&&Ce(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(!fo(e[i],t[i]))return!1}return!0}return!1}function Ce(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Ys(e,t,r="replace"){if(!BS(e))return null;try{let n=await import(e),i=n.default||n;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return pl(t,i,r)}catch{return null}}catch{return null}}function SA(e,t,r=!1){if(!e)return t;let n=e.toUpperCase().replace(/-/g,"_"),i={...t};function a(s,d=[]){let c={...s};for(let[o,g]of Object.entries(s)){let h=[...d,o],_=(y)=>y.replace(/([A-Z])/g,"_$1").toUpperCase(),R=`${n}_${h.map(_).join("_")}`,E=`${n}_${h.map((y)=>y.toUpperCase()).join("_")}`;if(r)gt.info(`Checking environment variable ${R} for config ${e}.${h.join(".")}`);if(typeof g==="object"&&g!==null&&!Array.isArray(g))c[o]=a(g,h);else{let y=ma.env[R]||ma.env[E];if(y!==void 0){if(r)gt.info(`Using environment variable ${y?R:E} for config ${e}.${h.join(".")}`);if(typeof g==="number")c[o]=Number(y);else if(typeof g==="boolean")c[o]=y.toLowerCase()==="true";else if(Array.isArray(g))try{let $=JSON.parse(y);if(Array.isArray($))c[o]=$;else c[o]=y.split(",").map((b)=>b.trim())}catch{c[o]=y.split(",").map(($)=>$.trim())}else c[o]=y}}}return c}return a(i)}async function _A({name:e="",alias:t,cwd:r,configDir:n,defaultConfig:i,verbose:a=!1,checkEnv:s=!0,arrayStrategy:d="replace"}){let c=s&&typeof i==="object"&&i!==null&&!Array.isArray(i)?SA(e,i,a):i,o=r||ma.cwd(),g=[".ts",".js",".mjs",".cjs",".json"];if(a)gt.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${o}`);let h=[e,`.${e}`].filter(Boolean),_=[`${e}.config`,`.${e}.config`].filter(Boolean),R=t?[t,`.${t}`]:[],E=t?[`${t}.config`,`.${t}.config`]:[],y=Array.from(new Set([o,Pt(o,"config"),Pt(o,".config"),n?Pt(o,n):void 0].filter(Boolean)));for(let $ of y){if(a)gt.info(`Searching for configuration in: ${$}`);let z=[Pt(o,"config"),Pt(o,".config")].concat(n?[Pt(o,n)]:[]).includes($)?[...h,..._,...R,...E]:[..._,...h,...E,...R];for(let C of z)for(let B of g){let N=Pt($,`${C}${B}`),F=await Ys(N,c,d);if(F!==null){if(a)gt.success(`Configuration loaded from: ${N}`);return F}}}if(e){let $=Pt(zc(),".config",e),b=["config",`${e}.config`];if(t)b.push(`${t}.config`);if(a)gt.info(`Checking user config directory: ${$}`);for(let z of b)for(let C of g){let B=Pt($,`${z}${C}`),N=await Ys(B,c,d);if(N!==null){if(a)gt.success(`Configuration loaded from user config directory: ${B}`);return N}}}if(e){let $=Pt(zc(),".config"),b=[`.${e}.config`];if(t)b.push(`.${t}.config`);if(a)gt.info(`Checking user config directory for dotfile configs: ${$}`);for(let z of b)for(let C of g){let B=Pt($,`${z}${C}`),N=await Ys(B,c,d);if(N!==null){if(a)gt.success(`Configuration loaded from user config directory dotfile: ${B}`);return N}}}if(e){let $=zc(),b=[`.${e}.config`,`.${e}`];if(t)b.push(`.${t}.config`),b.push(`.${t}`);if(a)gt.info(`Checking user home directory for dotfile configs: ${$}`);for(let z of b)for(let C of g){let B=Pt($,`${z}${C}`),N=await Ys(B,c,d);if(N!==null){if(a)gt.success(`Configuration loaded from user home directory: ${B}`);return N}}}try{let $=Pt(o,"package.json");if(BS($)){let b=await import($),z=b[e];if(!z&&t){if(z=b[t],z&&a)gt.success(`Using alias "${t}" configuration from package.json`)}if(z&&typeof z==="object"&&!Array.isArray(z))try{if(a)gt.success(`Configuration loaded from package.json: ${z===b[e]?e:t}`);return pl(c,z,d)}catch(C){if(a)gt.warn("Failed to merge package.json config:",C)}}}catch($){if(a)gt.warn("Failed to load package.json:",$)}if(a)gt.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return c}function RA(e,t={}){let r=oo.cwd();while(r.includes("storage"))r=Kf(r,"..");let n=Kf(r,e||"");if(t?.relative)return yw(oo.cwd(),n);return n}async function pA(){try{let e=await _A({name:"clarity",alias:"logging",defaultConfig:io,cwd:oo.cwd()});return{...io,...e||{}}}catch{return io}}function Ye(){if(Or.env.NODE_ENV==="test"||Or.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function IA(){if(Or.env.NODE_ENV==="test"||Or.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Or<"u"){let e=Or.type;if(e==="renderer"||e==="worker")return!1;return!!(Or.versions&&(Or.versions.node||Or.versions.bun))}return!1}class WS{async format(e){let t=await IA(),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:vi.pid,hostname:t(),environment:vi.env.NODE_ENV||"development",platform:vi.platform,version:vi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:vi.env.NODE_ENV||vi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class So{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...sl},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new WS,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??me.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(),a=this.generateKey();this.currentKeyId=i,this.keys.set(i,a),this.encryptionKeys.set(i,{key:a,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...ao,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...ao};return{...ao,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:sl.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,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}shouldWriteToFile(){return!Ye()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let i,a=0,s=3,d=1000;while(a<s)try{try{try{await zw(this.config.logDirectory,oS.F_OK|oS.W_OK)}catch(o){if(o instanceof Error&&"code"in o)if(o.code==="ENOENT")await Ww(this.config.logDirectory,{recursive:!0,mode:493});else if(o.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw o;else throw o}}catch(o){throw console.error("Debug: [writeToFile] Failed to create log directory:",o),o}let c=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:kr.from(e);try{if(!Vs(this.currentLogFile))await Vc(this.currentLogFile,"",{mode:420});if(i=sS(this.currentLogFile,"a",420),Tw(i,c,{flag:"a"}),aS(i),i!==void 0)Fc(i),i=void 0;if((await ki(this.currentLogFile)).size===0){if(await Vc(this.currentLogFile,c,{flag:"w",mode:420}),(await ki(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(o){let g=o;if(g.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(g.code)){if(a<s-1){let h=typeof g.message==="string"?g.message:"Unknown error";console.error(`Network error during write attempt ${a+1}/${s}:`,h);let _=d*2**a;await new Promise((R)=>setTimeout(R,_)),a++;continue}}if(g?.code&&["ENOSPC","EDQUOT"].includes(g.code))throw Error(`Disk quota exceeded or no space left on device: ${g.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",g),g}finally{if(i!==void 0)try{Fc(i)}catch(o){console.error("Debug: [writeToFile] Error closing file descriptor:",o)}}}catch(c){if(a===s-1){let g=c,h=typeof g.message==="string"?g.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),c}a++;let o=d*2**(a-1);await new Promise((g)=>setTimeout(g,o))}})();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 bi(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 bi(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return bi(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Ye())return;if(!this.shouldWriteToFile())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(([,d],[,c])=>c.createdAt.getTime()-d.createdAt.getTime()),a=typeof t.maxKeys==="number"?t.maxKeys:1,s=Math.max(1,a);if(i.length>s)for(let[d]of i.slice(s))this.encryptionKeys.delete(d),this.keys.delete(d)}generateKeyId(){return Nc(16).toString("hex")}generateKey(){return Nc(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=Nc(16),n=Ow("aes-256-gcm",t,r),i=kr.isBuffer(e)?e:kr.from(e,"utf8"),a=n.update(i),s=n.final(),d=a.length+s.length,c=n.getAuthTag(),o=kr.allocUnsafe(16+d+16);return r.copy(o,0),a.copy(o,16),s.copy(o,16+a.length),c.copy(o,16+d),{encrypted:o,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=cS(),i=[];n.on("data",(a)=>i.push(a)),n.on("end",()=>t(kr.from(kr.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(Ye())return;if(!this.shouldWriteToFile())return;let e=await ki(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 Ls(this.config.logDirectory),a=i.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,o)=>{let g=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(o.match(/\.log\.(\d+)$/)?.[1]||"0")-g}),s=a.length>0?Number.parseInt(a[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,d=`${r}.${s}`;if(await ki(r).catch(()=>null))try{if(await dS(r,d),t.compress)try{let c=`${d}.gz`;await this.compressLogFile(d,c),await xs(d)}catch(c){console.error("Error compressing rotated file:",c)}if(a.length===0&&!i.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await Vc(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),a=r.replace(/\.log$/,`-${i}.log`);if(await ki(r).catch(()=>null))await dS(r,a)}if(this.currentLogFile=n,t.maxFiles){let a=(await Ls(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,d)=>d.localeCompare(s));for(let s of a.slice(t.maxFiles))await xs(bi(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=iS(e),n=Jw(t),i=cS();await Hw(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);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}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()})),Vs(this.currentLogFile))try{let e=sS(this.currentLogFile,"r+");aS(e),Fc(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(!Ye()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Ls(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await xs(bi(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.shouldStyleConsole()?we.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Ye())return!1;let e=typeof me.env.NO_COLOR<"u",t=me.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof me.stderr<"u"&&me.stderr.isTTY||typeof me.stdout<"u"&&me.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:a,showTimestamp:s=!0}=e,d=(R)=>R.replace(this.ANSI_PATTERN,"");if(!this.fancy){let R=[];if(s)R.push(t);if(a==="warning")R.push("WARN");else if(a==="error")R.push("ERROR");else if(r)R.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)R.push(n.replace(/[[\]]/g,""));return R.push(i),R.join(" ")}let c=me.stdout.columns||120,o="";if(a==="warning"||a==="error")o=`${r} ${i}`;else if(a==="info"||a==="success")o=`${r} ${n} ${i}`;else o=`${r} ${n} ${we.cyan(i)}`;if(!s)return o.trim();let g=d(o).trim().length,h=d(t).length,_=Math.max(1,c-2-g-h);return`${o.trim()}${" ".repeat(_)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(a,s)=>{let d=Number.parseInt(s,10);return d<t[0].length?String(t[0][d]):a});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(a,s)=>{if(s==="%")return"%";if(n>=t.length)return a;let d=t[n++];switch(s){case"s":return String(d);case"d":case"i":return Number(d).toString();case"j":case"o":return JSON.stringify(d,null,2);default:return a}});if(n<t.length)i+=` ${t.slice(n).map((a)=>typeof a==="object"?JSON.stringify(a,null,2):String(a)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let a=we.underline(we.blue(n)),s=this.toAbsoluteFilePath(i);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let d=`file://${encodeURI(s)}`,c="\x1B]8;;",o="\x1B\\";return`\x1B]8;;${d}\x1B\\${a}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${a}\x1B]8;;\x1B\\`;return a}),t=t.replace(/`([^`]+)`/g,(r,n)=>we.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>we.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>we.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>we.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>we.strikethrough(n)),t}supportsHyperlinks(){if(Ye())return!1;let e=me.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=me.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(jw(t)||t.startsWith("./")||t.startsWith("../"))t=Uw(t);else return null;return Vs(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),a=this.formatFileTimestamp(n),s,d;if(t instanceof Error)s=t.message,d=t.stack;else s=this.formatMessage(t,r);let{consoleText:c,fileText:o}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let h=this.options.showIcons===!1?"":QS[e],_=this.options.showTags!==!1&&this.name?we.gray(this.formatTag(this.name)):"",R;switch(e){case"debug":R=this.formatConsoleMessage({timestamp:i,icon:h,tag:_,message:we.gray(c),level:e}),console.error(R);break;case"info":R=this.formatConsoleMessage({timestamp:i,icon:h,tag:_,message:c,level:e}),console.warn(R);break;case"success":R=this.formatConsoleMessage({timestamp:i,icon:h,tag:_,message:we.green(c),level:e}),console.error(R);break;case"warning":R=this.formatConsoleMessage({timestamp:i,icon:h,tag:_,message:c,level:e}),console.warn(R);break;case"error":if(R=this.formatConsoleMessage({timestamp:i,icon:h,tag:_,message:c,level:e}),console.error(R),d){let E=d.split(`
86
+ `);for(let y of E)if(y.trim()&&!y.includes(s))console.error(this.formatConsoleMessage({timestamp:i,message:we.gray(` ${y}`),level:e,showTimestamp:!1}))}break}}else if(!Ye()){if(console.error(`${a} ${this.environment}.${e.toUpperCase()}: ${s}`),d)console.error(d)}if(!this.shouldLog(e))return;let g=`${a} ${this.environment}.${e.toUpperCase()}: ${o}
87
+ `;if(d)g+=`${d}
88
+ `;if(g=g.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(g)}progress(e,t=""){let r={update:(d,c)=>{},finish:(d)=>{},interrupt:(d,c)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!Ye()&&me.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(d,c)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,d),this.activeProgressBar.total),c!==void 0)this.activeProgressBar.message=c;if(this.shouldStyleConsole()&&!Ye()&&me.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(d)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,d)},interrupt:(d,c="info")=>{if(!Ye()&&me.stdout.isTTY)me.stdout.write(`
89
+ `);if(this[c==="warning"?"warn":c](d),this.activeProgressBar&&this.shouldStyleConsole()&&!Ye()&&me.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?we.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":we.blue("◐"),tag:r,message:`${we.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),a=`${e} completed in ${i}ms`,s=new Date,d=this.formatConsoleTimestamp(s),o=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${a}`;if(r)o+=` ${JSON.stringify(r)}`;if(o+=`
90
+ `,o=o.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let g=this.options.showTags!==!1&&this.name?we.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:d,icon:this.options.showIcons===!1?"":we.green("✓"),tag:g,message:`${a}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Ye())console.error(o.trim());if(this.shouldWriteToFile())await this.writeToFile(o)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new So(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(Ye())throw Error("createReadStream is not supported in browser environments");if(!Vs(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return iS(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=kr.isBuffer(e)?e:kr.from(e,"base64"),i=n.subarray(0,16),a=n.subarray(n.length-16),s=n.subarray(16,n.length-16),d=Bw("aes-256-gcm",r,i);d.setAuthTag(a);let c=d.update(s),o=d.final(),g=c.length+o.length,h=kr.allocUnsafe(g);return c.copy(h,0),o.copy(h,c.length),h.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Ye()}isServerMode(){return!Ye()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:i,fileText:a}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let d=i.split(`
91
+ `),c=Math.max(...d.map((_)=>_.length))+2,o=`┌${"─".repeat(c)}┐`,g=`└${"─".repeat(c)}┘`,h=d.map((_)=>{return this.formatConsoleMessage({timestamp:r,message:we.cyan(_),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:we.cyan(o),showTimestamp:!1})),h.forEach((_)=>console.error(_)),console.error(this.formatConsoleMessage({timestamp:r,message:we.cyan(g),showTimestamp:!1}))}else if(!Ye())console.error(`${n} ${this.environment}.INFO: [BOX] ${a}`);let s=`${n} ${this.environment}.INFO: [BOX] ${a}
92
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(e){if(Ye())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${we.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();me.stdin.removeListener("data",r);try{if(typeof me.stdin.setRawMode==="function")me.stdin.setRawMode(!1)}catch{}me.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof me.stdin.setRawMode==="function")me.stdin.setRawMode(!0)}catch{}me.stdin.resume(),me.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let c=/%([sdijfo%])/g,o=0;if(r=e.replace(c,(g,h)=>{if(h==="%")return"%";if(o>=t.length)return g;let _=t[o++];switch(h){case"s":return String(_);case"d":case"i":return Number(_).toString();case"j":case"o":return JSON.stringify(_,null,2);default:return g}}),o<t.length)r+=` ${t.slice(o).map((g)=>typeof g==="object"?JSON.stringify(g,null,2):String(g)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?we.gray(this.formatTag(this.name)):"",o=this.options.showIcons===!1?"":`${we.blue("◐")} `;console.error(`${o}${c} ${we.cyan(n)}`)}let d=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
93
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(d)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!me.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,a=we.green("━".repeat(n)),s=we.gray("━".repeat(i)),d=`[${a}${s}]`,c=`${r}%`.padStart(4),o=e.message?` ${e.message}`:"",g=this.options.showIcons===!1?"":t||r===100?we.green("✓"):we.blue("▶"),h=this.options.showTags!==!1&&this.name?` ${we.gray(this.formatTag(this.name))}`:"",_=`\r${g}${h} ${d} ${c}${o}`,R=me.stdout.columns||80,E=" ".repeat(Math.max(0,R-_.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${_}${E}`,me.stdout.write(e.lastRenderedLine),t)me.stdout.write(`
94
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Ye()||!me.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(Ye()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Ls(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let a=bi(this.config.logDirectory,n);if(e.before)try{if((await ki(a)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${a}:`,s);continue}r.push(a)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await xs(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function jS(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:a}=t,s=Error("Unknown error occurred");for(let d=0;d<=r;d++)try{return await e()}catch(c){if(s=c instanceof Error?c:Error(String(c)),d===r||!i(s))break;if(n>0)await new Promise((o)=>setTimeout(o,n))}if(a!==void 0)return a;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}function US(e){return e instanceof Ut}function mA(e){return e instanceof _o}function EA(e){if(US(e))return e.code==="FILE_SYSTEM_ERROR"||e.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((r)=>e.message.toLowerCase().includes(r.toLowerCase()))}class yo{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:n,useCamelCase:i=!0,useBackwardCompatibility:a=!0,customParsers:s={},verbose:d=!1,trackPerformance:c=!0}=r,o=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let g=n||this.generateEnvPrefix(e),h={...t};return this.processObject(h,[],g,{useCamelCase:i,useBackwardCompatibility:a,customParsers:s,verbose:d,configName:e}),{config:h,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return wa.track("applyEnvironmentVariables",o,{configName:e});return o()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,n){for(let[i,a]of Object.entries(e)){let s=[...t,i],d=s.map((g)=>this.formatEnvKey(g,n.useCamelCase)),c=`${r}_${d.join("_")}`,o=n.useBackwardCompatibility?`${r}_${s.map((g)=>g.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof a==="object"&&a!==null&&!Array.isArray(a))this.processObject(a,s,r,n);else{let g=Ms.env[c]||(o?Ms.env[o]:void 0);if(g!==void 0){if(n.verbose){let h=Ms.env[c]?c:o}try{e[i]=this.parseEnvironmentValue(g,typeof a,c,n.customParsers,n.configName)}catch(h){if(h instanceof Ro)throw h;throw gn.envVar(c,g,typeof a,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[a,s]of Object.entries(n))try{return s(e)}catch{continue}for(let a of this.defaultParsers)if(a.canParse(e,t))try{return a.parse(e)}catch{throw gn.envVar(r,e,`${t} (via ${a.name} parser)`,i)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,i]of Object.entries(Ms.env))if(n.startsWith(r)&&i!==void 0)t[n]=i;return t}validateEnvironmentVariable(e,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))n.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(i){n.push(`Cannot parse value "${t}" as ${r}: ${i}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(e,t,r={}){let{prefix:n,format:i="text"}=r,a=n||this.generateEnvPrefix(e),s=[];switch(this.extractEnvVarInfo(t,[],a,s),i){case"markdown":return this.formatAsMarkdown(s,e);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,e)}}extractEnvVarInfo(e,t,r,n){for(let[i,a]of Object.entries(e)){let s=[...t,i],d=`${r}_${s.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof a==="object"&&a!==null&&!Array.isArray(a))this.extractEnvVarInfo(a,s,r,n);else n.push({key:d,type:Array.isArray(a)?"array":typeof a,description:`Configuration for ${s.join(".")}`,example:this.generateExample(a)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
95
+
96
+ `;for(let n of e)r+=`${n.key}
97
+ `,r+=` Type: ${n.type}
98
+ `,r+=` Description: ${n.description}
99
+ `,r+=` Example: ${n.example}
100
+
101
+ `;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
102
+
103
+ `;r+=`| Variable | Type | Description | Example |
104
+ `,r+=`|----------|------|-------------|----------|
105
+ `;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
106
+ `;return r}}function yA(e,t){let r=LS("process");if(typeof r>"u"||!r.env)return t;let n=r.env[e];return n!==void 0?n:t}function HS(e,t,r={}){return NS(e,t,r,new WeakMap)}function NS(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:a=!1,customMerger:s}=r;if(t===null||t===void 0)return a?e:t;if(s){let d=s(e,t);if(d!==void 0)return d}if(Array.isArray(t)||Array.isArray(e))return FS(e,t,i,n);if(!xt(t)||!xt(e))return t;return DA(e,t,r,n)}function FS(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 wA(e,t);case"smart":return AA(e,t,n);default:return t}return t}function wA(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>il(i,n)))r.push(n);return r}function AA(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(xt(t[0])&&xt(e[0]))return PA(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 PA(e,t,r){let n=[...t];for(let i of e){if(!xt(i)){n.push(i);continue}let a=["id","name","key","path","type"],s=!1;for(let d of a)if(d in i){if(n.find((o)=>xt(o)&&(d in o)&&o[d]===i[d])){s=!0;break}}if(!s)n.push(i)}return n}function DA(e,t,r,n){let i=t;if(xt(i)&&n.has(i))return n.get(i);let a={...e};if(xt(i))n.set(i,a);for(let s in i){if(!Object.prototype.hasOwnProperty.call(i,s))continue;let d=i[s],c=a[s];if(r.skipNullish&&(d===null||d===void 0))continue;if(d===null||d===void 0){a[s]=d;continue}if(xt(d)&&xt(c))a[s]=NS(c,d,r,n);else if(Array.isArray(d)||Array.isArray(c))a[s]=FS(c,d,r.arrayMergeMode||"smart",n);else a[s]=d}return a}function Il(e,t,r="replace"){return HS(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function il(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(!il(e[r],t[r]))return!1;return!0}if(xt(e)&&xt(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(!il(e[i],t[i]))return!1}return!0}return!1}function xt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class wo{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:a,trackPerformance:s=!0,verbose:d=!1}=r;if(i){let o=Ti.getWithFileCheck("file",e);if(o){if(d)console.log(`Configuration loaded from cache: ${e}`);return o}}let c=async()=>{if(!Qs(e))return null;try{let o=`?t=${Date.now()}`,g=await import(e+o),h=g.default||g,_="default"in g,R=Object.keys(g).length>0;if(!_&&!R)throw new Ea(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof h!=="object"||h===null||Array.isArray(h))throw new Ea(e,Error("Configuration must export a valid object"),"unknown");let $={config:Il(t,h,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)Ti.setWithFileCheck("file",$,e,a);return $}catch(o){throw o instanceof Error?gn.configLoad(e,o):gn.configLoad(e,Error(String(o)))}};if(s)return wa.track("loadFromPath",c,{path:e});return c()}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){let n=this.generateNamePatterns(e,r),i=[];for(let a of n)for(let s of this.extensions)i.push(Lc(t,`${a}${s}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return jS(async()=>{return Qs(e)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!Qs(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let a of i)for(let s of this.extensions){let d=Lc(e,`${a}${s}`);if(await this.checkFileAccess(d))n.push(d)}}else try{let{readdirSync:i}=await import("fs"),a=i(e);for(let s of a)if(this.looksLikeConfigFile(s)){let d=Lc(e,s);if(await this.checkFileAccess(d))n.push(d)}}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(!Qs(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"),a=i(e,"utf8");JSON.parse(a)}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}}class ml{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:a=!0,customRules:s=[],trackPerformance:d=!0,verbose:c=!1}=r,o=async()=>{let g=[],h=[],_={stopOnFirstError:n,validateRequired:i,validateTypes:a,customRules:s,trackPerformance:d,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,_);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...s],_);else return this.validateWithJSONSchema(e,t,_)}catch(R){return g.push({path:"",message:`Validation failed: ${R}`,rule:"system"}),{isValid:!1,errors:g,warnings:h}}};if(d)return await wa.track("validateConfiguration",o);return o()}async validateWithSchemaFile(e,t,r){try{if(!Nw(t))throw new ya(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 ya(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,a){if(a.validateTypes&&t.type){let s=Array.isArray(e)?"array":typeof e,d=Array.isArray(t.type)?t.type:[t.type];if(!d.includes(s)){if(n.push({path:r,message:`Expected type ${d.join(" or ")}, got ${s}`,expected:d.join(" or "),actual:s,rule:"type"}),a.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"}),a.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 d=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(e[s],t.items,d,n,i,a),a.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let s=e;if(a.validateRequired&&t.required){for(let d of t.required)if(!(d in s)){if(n.push({path:r?`${r}.${d}`:d,message:`Missing required property '${d}'`,expected:"required",rule:"required"}),a.stopOnFirstError)return}}if(t.properties){for(let[d,c]of Object.entries(t.properties))if(d in s){let o=r?`${r}.${d}`:d;if(this.validateObjectAgainstSchema(s[d],c,o,n,i,a),a.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let d=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(s))if(!d.has(c))i.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let a of t)try{let s=this.getValueByPath(e,a.path),d=this.validateWithRule(s,a,a.path);if(n.push(...d),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:a.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,a,s]=n;t.push({path:i,required:!a,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:ZS},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class El{fileLoader=new wo;envProcessor=new yo;validator=new ml;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:a,...s}=e;try{if(r?.enabled){let c=this.checkCache(s.name||"",s);if(c)return c}let d;try{d=await this.loadConfigurationStrategies(s,!0,r)}catch(c){let o=s.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(o)throw c;d={...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(c instanceof Error&&c.name==="ConfigLoadError"){let g=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),h=!g&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),_=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(o&&(_||g))throw c;if(h&&(!o||!_))d={...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(!o)d={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else d={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(i||a)await this.validateConfiguration(d.config,i,a,s.name);if(r?.enabled&&d)this.cacheResult(s.name||"",d,r,s);if(n?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(c);if(n.slowThreshold&&c.duration>n.slowThreshold)er.warn(`Slow configuration loading detected: ${c.duration}ms for ${s.name}`);d.metrics=c}return d}catch(d){let c=Date.now()-t;throw er.error(`Configuration loading failed after ${c}ms:`,[d instanceof Error?d:Error(String(d))]),d}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:a,configDir:s,defaultConfig:d,checkEnv:c=!0,arrayStrategy:o="replace",verbose:g=!1}=e,h=a||Vn.cwd(),_=[],R=await this.loadLocalConfiguration(n,i,h,s,d,o,g,c,r);if(R)return _.push(...this.getLocalSearchPaths(n,i,h,s)),this.finalizeResult(R,_,c,n,g);let E=await this.loadHomeConfiguration(n,i,d,o,g,c);if(E)return _.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(E,_,c,n,g);let y=await this.loadPackageJsonConfiguration(n,i,h,d,o,g,c);if(y)return _.push(Dt(h,"package.json")),this.finalizeResult(y,_,c,n,g);if(_.push(...this.getAllSearchPaths(n,i,h,s)),t)throw gn.configNotFound(n,_,i);return{...await this.applyEnvironmentVariables(n,d,c,g),warnings:[`No configuration file found for "${n}"${i?` or alias "${i}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,a,s,d,c){let o=d?Ia(e,i,s):i,g=this.getLocalDirectories(r,n);for(let h of g){if(s)er.info(`Searching for configuration in: ${h}`);let _=this.fileLoader.generateConfigPaths(e,h,t),R=await this.fileLoader.tryLoadFromPaths(_,o,{arrayStrategy:a,verbose:s,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(R){if(s)er.success(`Configuration loaded from: ${R.source.path}`);return R}}return null}async loadHomeConfiguration(e,t,r,n,i,a){if(!e)return null;let s=a?Ia(e,r,i):r,d=[Dt(Pi(),".config",e),Dt(Pi(),".config"),Pi()];for(let c of d){if(i)er.info(`Checking home directory: ${c}`);let o=this.fileLoader.generateConfigPaths(e,c,t),g=await this.fileLoader.tryLoadFromPaths(o,s,{arrayStrategy:n,verbose:i});if(g){if(i)er.success(`Configuration loaded from home directory: ${g.source.path}`);return g}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,a,s){let d=s?Ia(e,n,a):n;try{let c=Dt(r,"package.json");if(!rl(c))return null;let o=await import(c),g=o[e],h=e;if(!g&&t)g=o[t],h=t;if(g&&typeof g==="object"&&!Array.isArray(g)){if(a)er.success(`Configuration loaded from package.json: ${h}`);return{config:Il(d,g,i),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(a)er.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}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 a=r(e);if(a)i.push(...a)}if(t){let a=await this.validator.validateConfiguration(e,t);if(!a.isValid)i.push(...a.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(i.length>0)throw gn.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return Ti.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);Ti.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,Dt(e,"config"),Dt(e,".config"),t?Dt(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(Dt(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),a=[];for(let s of i)a.push(...this.fileLoader.generateConfigPaths(e,s,t));return a}getHomeSearchPaths(e,t){if(!e)return[];let r=[Dt(Pi(),".config",e),Dt(Pi(),".config"),Pi()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function pS(e){let r=!(e.message.includes("EACCES")||e.message.includes("EPERM")||e.message.includes("permission denied"))&&(e.message.includes("syntax")||e.message.includes("Expected")||e.message.includes("Unexpected")||e.message.includes("BuildMessage")),n=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return r||n}async function $A(e){return Jr.loadConfig({...e,__strictErrorHandling:!0})}async function VS(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 Jr.loadConfig(e);else n=await Jr.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let i=n instanceof Error?n.name:"UnknownError",a=n instanceof Error?n.message:String(n);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||a.includes("config"))&&e.verbose)er.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let d=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await Jr.applyEnvironmentVariables(d.name||"",t,!0,d.verbose||!1))?.config??t;return t}}async function CA(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await Jr.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&pS(r)))return(await Jr.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await Jr.loadConfig({...e,cwd:e.cwd||Vn.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&pS(t)))return(await Jr.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function kA(e,t,r="replace"){let n=new wo;try{let i=await n.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return i?i.config:null}catch{return null}}function Ia(e,t,r=!1){let n=new yo,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function a(s,d=[]){let c={...s};for(let[o,g]of Object.entries(s)){let h=[...d,o],_=[`${i}_${h.join("_").toUpperCase()}`,`${i}_${h.map((y)=>y.toUpperCase()).join("")}`,`${i}_${h.map((y)=>y.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],R,E;for(let y of _)if(R=Vn.env[y],R!==void 0){E=y;break}if(R!==void 0&&E)if(typeof g==="boolean")c[o]=["true","1","yes"].includes(R.toLowerCase());else if(typeof g==="number"){let y=Number(R);if(!Number.isNaN(y))c[o]=y}else if(Array.isArray(g))try{c[o]=JSON.parse(R)}catch{c[o]=R.split(",").map((y)=>y.trim())}else c[o]=R;else if(g&&typeof g==="object"&&!Array.isArray(g))c[o]=a(g,h)}return c}return a(t)}function bA(e){let t=Dt(Vn.cwd(),e.configDir),r=Dt(Vn.cwd(),e.generatedDir),n=Dt(r,"config-types.ts");if(!rl(Zf(n)))pw(Zf(n),{recursive:!0,mode:511});let i=rl(t)?Iw(t).map((s)=>s.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],a=`// Generated by bunfig v${aP}
107
+ export type ConfigNames = ${i.length?`'${i.join("' | '")}'`:"string"}
108
+ `;mw(n,a,{mode:438})}function vA(e){let t=null,r=null,n=()=>{if(!r)r=VS(e).then((a)=>{return t=a,a},(a)=>{let s="defaultConfig"in e?e.defaultConfig:{};if(t=s,"verbose"in e&&e.verbose)er.warn("Config loading failed, using defaults:",[a instanceof Error?a:Error(String(a))]);return s});return r},i="defaultConfig"in e?e.defaultConfig:{};return t=i,n(),new Proxy({},{get(a,s){if(t)return t[s];let d=i[s];return n(),d},has(a,s){return s in(t||i)},ownKeys(){return Object.keys(t||i)},getOwnPropertyDescriptor(a,s){return Object.getOwnPropertyDescriptor(t||i,s)},set(a,s,d){if(!t)t={...i};return t[s]=d,!0}})}function OA(e){let t=lS(Lw.cwd(),e?.configDir||"./config");function r(){if(!Fw(t))return[];let i=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),a=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],s=Vw(t).filter((c)=>i.has(xc(c))).map((c)=>({base:c.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:c})),d=new Map;for(let{base:c,file:o}of s){let g=xc(o).toLowerCase(),h=d.get(c);if(!h){d.set(c,o);continue}let _=xc(h).toLowerCase();if(a.indexOf(g)<a.indexOf(_))d.set(c,o)}return Array.from(d.entries()).map(([c,o])=>({base:c,file:o})).sort((c,o)=>c.base.localeCompare(o.base))}function n(){let i=r(),a=i.map((o)=>o.base),s=a.length?a.map((o)=>`'${o}'`).join(" | "):"string",d=i.length?`{
109
+ ${i.map((o)=>{let g=lS(t,o.file).replace(/\\/g,"/");return` '${o.base}': typeof import('${g}').default`}).join(`,
110
+ `)}
111
+ }`:"Record<string, any>";return`export type ConfigNames = ${s}
112
+ export type ConfigByName = ${d}
113
+ export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
114
+ export type ConfigOf = Config
115
+ `}return{name:"bunfig-plugin",setup(i){i.onResolve({filter:/^virtual:bunfig-types$/},(a)=>{return{path:a.path,namespace:"bunfig-virtual"}}),i.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:n(),loader:"ts"}})}}}var LS,Ti,wa,xS,BA,JA,IS,ro,al,lt,Je,TA,mS,zA,ES,WA,jA,Zc,UA,yS,wS,Kc,HA,NA,FA,VA,no,MS,LA,gt,xA,MA,AS,io,sl,Xe,we,QA,PS,GA,DS,ZA,KA,Yc,YA,$S,CS,XA,Xc,qA,eP,tP,rP,nP,ao,QS,iP,aP="0.15.6",Ut,_o,Ea,ol,dl,Ro,cl,ll,ya,gl,ul,gn,GS,ZS,er,Jr,KS,YS,sP=sA(async()=>{LS=import.meta.require,Ti=new Sl,wa=new _l,xS={createKey:oA,isEquivalent:dA,estimateMemoryUsage:cA},BA=lo(nl.cwd(),"config"),JA=lo(nl.cwd(),"src/generated"),IS=co.env.CLARITY_LOG_DIR||ww(uA(),"logs"),ro={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:IS,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},al=await hA(),lt={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,reset:"\x1B[0m"},Je=lt,TA=lt.red,mS=lt.green,zA=lt.yellow,ES=lt.blue,WA=lt.magenta,jA=lt.cyan,Zc=lt.white,UA=lt.gray,yS=lt.bgRed,wS=lt.bgYellow,Kc=lt.bold,HA=lt.dim,NA=lt.italic,FA=lt.underline,VA=lt.reset,no={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},MS={debug:"\uD83D\uDD0D",info:ES("ℹ"),success:mS("✓"),warning:wS(Zc(Kc(" WARN "))),error:yS(Zc(Kc(" ERROR ")))},LA=new ho("stacks"),gt=new ho("bunfig",{showTags:!0}),xA=Pt(ma.cwd(),"config"),MA=Pt(ma.cwd(),"src/generated"),AS=oo.env.CLARITY_LOG_DIR||Ew(RA(),"logs"),io={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:AS,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},sl=await pA(),Xe={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},we=Xe,QA=Xe.red,PS=Xe.green,GA=Xe.yellow,DS=Xe.blue,ZA=Xe.magenta,KA=Xe.cyan,Yc=Xe.white,YA=Xe.gray,$S=Xe.bgRed,CS=Xe.bgYellow,XA=Xe.bgGray,Xc=Xe.bold,qA=Xe.dim,eP=Xe.italic,tP=Xe.underline,rP=Xe.strikethrough,nP=Xe.reset,ao={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},QS={debug:"\uD83D\uDD0D",info:DS("ℹ"),success:PS("✓"),warning:CS(Yc(Xc(" WARN "))),error:$S(Yc(Xc(" ERROR ")))},iP=new So("stacks"),Ut=class extends Error{timestamp;context;constructor(t,r={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=r,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([r,n])=>`${r}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},_o=class extends Ut{code="CONFIG_NOT_FOUND";constructor(t,r,n){let i=n?` or alias "${n}"`:"";super(`Configuration "${t}"${i} not found`,{configName:t,alias:n,searchPaths:r,searchPathCount:r.length})}},Ea=class extends Ut{code="CONFIG_LOAD_ERROR";constructor(t,r,n){super(`Failed to load configuration from "${t}": ${r.message}`,{configPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},ol=class extends Ut{code="CONFIG_VALIDATION_ERROR";constructor(t,r,n){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:n,validationErrors:r,errorCount:r.length})}},dl=class extends Ut{code="CONFIG_MERGE_ERROR";constructor(t,r,n,i){super(`Failed to merge configuration from "${t}" with "${r}": ${n.message}`,{sourcePath:t,targetPath:r,configName:i,originalError:n.name,originalMessage:n.message});this.cause=n}},Ro=class extends Ut{code="ENV_VAR_ERROR";constructor(t,r,n,i){super(`Failed to parse environment variable "${t}" with value "${r}" as ${n}`,{envKey:t,envValue:r,expectedType:n,configName:i})}},cl=class extends Ut{code="FILE_SYSTEM_ERROR";constructor(t,r,n){super(`File system ${t} failed for "${r}": ${n.message}`,{operation:t,path:r,originalError:n.name,originalMessage:n.message});this.cause=n}},ll=class extends Ut{code="TYPE_GENERATION_ERROR";constructor(t,r,n){super(`Failed to generate types from "${t}" to "${r}": ${n.message}`,{configDir:t,outputPath:r,originalError:n.name,originalMessage:n.message});this.cause=n}},ya=class extends Ut{code="SCHEMA_VALIDATION_ERROR";constructor(t,r,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:t,configName:n,validationErrors:r,errorCount:r.length})}},gl=class extends Ut{code="BROWSER_CONFIG_ERROR";constructor(t,r,n,i){super(`Failed to fetch configuration from "${t}": ${r} ${n}`,{endpoint:t,status:r,statusText:n,configName:i})}},ul=class extends Ut{code="PLUGIN_ERROR";constructor(t,r,n){super(`Plugin "${t}" failed during ${r}: ${n.message}`,{pluginName:t,operation:r,originalError:n.name,originalMessage:n.message});this.cause=n}},gn={configNotFound(e,t,r){return new _o(e,t,r)},configLoad(e,t,r){return new Ea(e,t,r)},configValidation(e,t,r){return new ol(e,t,r)},configMerge(e,t,r,n){return new dl(e,t,r,n)},envVar(e,t,r,n){return new Ro(e,t,r,n)},fileSystem(e,t,r){return new cl(e,t,r)},typeGeneration(e,t,r){return new ll(e,t,r)},schemaValidation(e,t,r){return new ya(e,t,r)},browserConfig(e,t,r,n){return new gl(e,t,r,n)},plugin(e,t,r){return new ul(e,t,r)}},GS={replace:"replace",concat:"concat",smart:"smart"},ZS=/^https?:\/\//,er=new So("bunfig",{showTags:!0}),Jr=new El,KS=Dt(Vn.cwd(),"config"),YS=Dt(Vn.cwd(),"src/generated")});function oP(e,t={}){let r=go.cwd();while(r.includes("storage"))r=gS(r,"..");let n=gS(r,e||"");if(t?.relative)return Mw(go.cwd(),n);return n}var dP=go.env.CLARITY_LOG_DIR||xw(oP(),"logs"),XS={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:dP,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},po={...XS},rJ=(async()=>{try{let{loadConfig:e}=await sP().then(()=>TS),t=await e({name:"clarity",alias:"logging",defaultConfig:XS,cwd:go.cwd()});if(t)Object.assign(po,t)}catch{}return po})();function qe(){if(Br.env.NODE_ENV==="test"||Br.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function cP(){if(Br.env.NODE_ENV==="test"||Br.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Br<"u"){let e=Br.type;if(e==="renderer"||e==="worker")return!1;return!!(Br.versions&&(Br.versions.node||Br.versions.bun))}return!1}class qS{async format(e){let t=await cP(),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:Ji.pid,hostname:t(),environment:Ji.env.NODE_ENV||"development",platform:Ji.platform,version:Ji.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Ji.env.NODE_ENV||Ji.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var nt={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},De=nt,nJ=nt.red,lP=nt.green,iJ=nt.yellow,gP=nt.blue,aJ=nt.magenta,sJ=nt.cyan,kS=nt.white,oJ=nt.gray,uP=nt.bgRed,hP=nt.bgYellow,dJ=nt.bgGray,bS=nt.bold,cJ=nt.dim,lJ=nt.italic,gJ=nt.underline,uJ=nt.strikethrough,hJ=nt.reset,qc={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},fP={debug:"\uD83D\uDD0D",info:gP("ℹ"),success:lP("✓"),warning:hP(kS(bS(" WARN "))),error:uP(kS(bS(" ERROR ")))};class Ao{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...po},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new qS,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??Ee.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,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),a=this.generateKey();this.currentKeyId=i,this.keys.set(i,a),this.encryptionKeys.set(i,{key:a,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...qc,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...qc};return{...qc,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:po.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,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}shouldWriteToFile(){return!qe()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let i,a=0,s=3,d=1000;while(a<s)try{try{try{await Yw(this.config.logDirectory,SS.F_OK|SS.W_OK)}catch(o){if(o instanceof Error&&"code"in o)if(o.code==="ENOENT")await Xw(this.config.logDirectory,{recursive:!0,mode:493});else if(o.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw o;else throw o}}catch(o){throw console.error("Debug: [writeToFile] Failed to create log directory:",o),o}let c=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:br.from(e);try{if(!Gs(this.currentLogFile))await Gc(this.currentLogFile,"",{mode:420});if(i=fS(this.currentLogFile,"a",420),Kw(i,c,{flag:"a"}),hS(i),i!==void 0)Qc(i),i=void 0;if((await Oi(this.currentLogFile)).size===0){if(await Gc(this.currentLogFile,c,{flag:"w",mode:420}),(await Oi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(o){let g=o;if(g.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(g.code)){if(a<s-1){let h=typeof g.message==="string"?g.message:"Unknown error";console.error(`Network error during write attempt ${a+1}/${s}:`,h);let _=d*2**a;await new Promise((R)=>setTimeout(R,_)),a++;continue}}if(g?.code&&["ENOSPC","EDQUOT"].includes(g.code))throw Error(`Disk quota exceeded or no space left on device: ${g.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",g),g}finally{if(i!==void 0)try{Qc(i)}catch(o){console.error("Debug: [writeToFile] Error closing file descriptor:",o)}}}catch(c){if(a===s-1){let g=c,h=typeof g.message==="string"?g.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),c}a++;let o=d*2**(a-1);await new Promise((g)=>setTimeout(g,o))}})();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 Bi(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 Bi(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Bi(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(qe())return;if(!this.shouldWriteToFile())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(([,d],[,c])=>c.createdAt.getTime()-d.createdAt.getTime()),a=typeof t.maxKeys==="number"?t.maxKeys:1,s=Math.max(1,a);if(i.length>s)for(let[d]of i.slice(s))this.encryptionKeys.delete(d),this.keys.delete(d)}generateKeyId(){return Mc(16).toString("hex")}generateKey(){return Mc(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=Mc(16),n=Qw("aes-256-gcm",t,r),i=br.isBuffer(e)?e:br.from(e,"utf8"),a=n.update(i),s=n.final(),d=a.length+s.length,c=n.getAuthTag(),o=br.allocUnsafe(16+d+16);return r.copy(o,0),a.copy(o,16),s.copy(o,16+a.length),c.copy(o,16+d),{encrypted:o,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=RS(),i=[];n.on("data",(a)=>i.push(a)),n.on("end",()=>t(br.from(br.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(qe())return;if(!this.shouldWriteToFile())return;let e=await Oi(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 Zs(this.config.logDirectory),a=i.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,o)=>{let g=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(o.match(/\.log\.(\d+)$/)?.[1]||"0")-g}),s=a.length>0?Number.parseInt(a[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,d=`${r}.${s}`;if(await Oi(r).catch(()=>null))try{if(await _S(r,d),t.compress)try{let c=`${d}.gz`;await this.compressLogFile(d,c),await Ks(d)}catch(c){console.error("Error compressing rotated file:",c)}if(a.length===0&&!i.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await Gc(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),a=r.replace(/\.log$/,`-${i}.log`);if(await Oi(r).catch(()=>null))await _S(r,a)}if(this.currentLogFile=n,t.maxFiles){let a=(await Zs(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,d)=>d.localeCompare(s));for(let s of a.slice(t.maxFiles))await Ks(Bi(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=uS(e),n=Zw(t),i=RS();await tA(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);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}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()})),Gs(this.currentLogFile))try{let e=fS(this.currentLogFile,"r+");hS(e),Qc(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(!qe()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Zs(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Ks(Bi(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.shouldStyleConsole()?De.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||qe())return!1;let e=typeof Ee.env.NO_COLOR<"u",t=Ee.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof Ee.stderr<"u"&&Ee.stderr.isTTY||typeof Ee.stdout<"u"&&Ee.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:a,showTimestamp:s=!0}=e,d=(R)=>R.replace(this.ANSI_PATTERN,"");if(!this.fancy){let R=[];if(s)R.push(t);if(a==="warning")R.push("WARN");else if(a==="error")R.push("ERROR");else if(r)R.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)R.push(n.replace(/[[\]]/g,""));return R.push(i),R.join(" ")}let c=Ee.stdout.columns||120,o="";if(a==="warning"||a==="error")o=`${r} ${i}`;else if(a==="info"||a==="success")o=`${r} ${n} ${i}`;else o=`${r} ${n} ${De.cyan(i)}`;if(!s)return o.trim();let g=d(o).trim().length,h=d(t).length,_=Math.max(1,c-2-g-h);return`${o.trim()}${" ".repeat(_)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(a,s)=>{let d=Number.parseInt(s,10);return d<t[0].length?String(t[0][d]):a});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(a,s)=>{if(s==="%")return"%";if(n>=t.length)return a;let d=t[n++];switch(s){case"s":return String(d);case"d":case"i":return Number(d).toString();case"j":case"o":return JSON.stringify(d,null,2);default:return a}});if(n<t.length)i+=` ${t.slice(n).map((a)=>typeof a==="object"?JSON.stringify(a,null,2):String(a)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let a=De.underline(De.blue(n)),s=this.toAbsoluteFilePath(i);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let d=`file://${encodeURI(s)}`,c="\x1B]8;;",o="\x1B\\";return`\x1B]8;;${d}\x1B\\${a}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${a}\x1B]8;;\x1B\\`;return a}),t=t.replace(/`([^`]+)`/g,(r,n)=>De.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>De.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>De.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>De.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>De.strikethrough(n)),t}supportsHyperlinks(){if(qe())return!1;let e=Ee.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=Ee.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(qw(t)||t.startsWith("./")||t.startsWith("../"))t=eA(t);else return null;return Gs(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let n=new Date,i=this.formatConsoleTimestamp(n),a=this.formatFileTimestamp(n),s,d;if(t instanceof Error)s=t.message,d=t.stack;else s=this.formatMessage(t,r);let{consoleText:c,fileText:o}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let h=this.options.showIcons===!1?"":fP[e],_=this.options.showTags!==!1&&this.name?De.gray(this.formatTag(this.name)):"",R;switch(e){case"debug":R=this.formatConsoleMessage({timestamp:i,icon:h,tag:_,message:De.gray(c),level:e}),console.error(R);break;case"info":R=this.formatConsoleMessage({timestamp:i,icon:h,tag:_,message:c,level:e}),console.warn(R);break;case"success":R=this.formatConsoleMessage({timestamp:i,icon:h,tag:_,message:De.green(c),level:e}),console.error(R);break;case"warning":R=this.formatConsoleMessage({timestamp:i,icon:h,tag:_,message:c,level:e}),console.warn(R);break;case"error":if(R=this.formatConsoleMessage({timestamp:i,icon:h,tag:_,message:c,level:e}),console.error(R),d){let E=d.split(`
116
+ `);for(let y of E)if(y.trim()&&!y.includes(s))console.error(this.formatConsoleMessage({timestamp:i,message:De.gray(` ${y}`),level:e,showTimestamp:!1}))}break}}else if(!qe()){if(console.error(`${a} ${this.environment}.${e.toUpperCase()}: ${s}`),d)console.error(d)}let g=`${a} ${this.environment}.${e.toUpperCase()}: ${o}
117
+ `;if(d)g+=`${d}
118
+ `;if(g=g.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(g)}progress(e,t=""){let r={update:(d,c)=>{},finish:(d)=>{},interrupt:(d,c)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!qe()&&Ee.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(d,c)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,d),this.activeProgressBar.total),c!==void 0)this.activeProgressBar.message=c;if(this.shouldStyleConsole()&&!qe()&&Ee.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(d)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,d)},interrupt:(d,c="info")=>{if(!qe()&&Ee.stdout.isTTY)Ee.stdout.write(`
119
+ `);if(this[c==="warning"?"warn":c](d),this.activeProgressBar&&this.shouldStyleConsole()&&!qe()&&Ee.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?De.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":De.blue("◐"),tag:r,message:`${De.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),a=`${e} completed in ${i}ms`,s=new Date,d=this.formatConsoleTimestamp(s),o=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${a}`;if(r)o+=` ${JSON.stringify(r)}`;if(o+=`
120
+ `,o=o.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let g=this.options.showTags!==!1&&this.name?De.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:d,icon:this.options.showIcons===!1?"":De.green("✓"),tag:g,message:`${a}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!qe())console.error(o.trim());if(this.shouldWriteToFile())await this.writeToFile(o)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new Ao(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(qe())throw Error("createReadStream is not supported in browser environments");if(!Gs(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return uS(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=br.isBuffer(e)?e:br.from(e,"base64"),i=n.subarray(0,16),a=n.subarray(n.length-16),s=n.subarray(16,n.length-16),d=Gw("aes-256-gcm",r,i);d.setAuthTag(a);let c=d.update(s),o=d.final(),g=c.length+o.length,h=br.allocUnsafe(g);return c.copy(h,0),o.copy(h,c.length),h.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return qe()}isServerMode(){return!qe()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:i,fileText:a}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let d=i.split(`
121
+ `),c=Math.max(...d.map((_)=>_.length))+2,o=`┌${"─".repeat(c)}┐`,g=`└${"─".repeat(c)}┘`,h=d.map((_)=>{return this.formatConsoleMessage({timestamp:r,message:De.cyan(_),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:De.cyan(o),showTimestamp:!1})),h.forEach((_)=>console.error(_)),console.error(this.formatConsoleMessage({timestamp:r,message:De.cyan(g),showTimestamp:!1}))}else if(!qe())console.error(`${n} ${this.environment}.INFO: [BOX] ${a}`);let s=`${n} ${this.environment}.INFO: [BOX] ${a}
122
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(e){if(qe())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${De.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();Ee.stdin.removeListener("data",r);try{if(typeof Ee.stdin.setRawMode==="function")Ee.stdin.setRawMode(!1)}catch{}Ee.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof Ee.stdin.setRawMode==="function")Ee.stdin.setRawMode(!0)}catch{}Ee.stdin.resume(),Ee.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let c=/%([sdijfo%])/g,o=0;if(r=e.replace(c,(g,h)=>{if(h==="%")return"%";if(o>=t.length)return g;let _=t[o++];switch(h){case"s":return String(_);case"d":case"i":return Number(_).toString();case"j":case"o":return JSON.stringify(_,null,2);default:return g}}),o<t.length)r+=` ${t.slice(o).map((g)=>typeof g==="object"?JSON.stringify(g,null,2):String(g)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?De.gray(this.formatTag(this.name)):"",o=this.options.showIcons===!1?"":`${De.blue("◐")} `;console.error(`${o}${c} ${De.cyan(n)}`)}let d=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
123
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(d)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!Ee.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,a=De.green("━".repeat(n)),s=De.gray("━".repeat(i)),d=`[${a}${s}]`,c=`${r}%`.padStart(4),o=e.message?` ${e.message}`:"",g=this.options.showIcons===!1?"":t||r===100?De.green("✓"):De.blue("▶"),h=this.options.showTags!==!1&&this.name?` ${De.gray(this.formatTag(this.name))}`:"",_=`\r${g}${h} ${d} ${c}${o}`,R=Ee.stdout.columns||80,E=" ".repeat(Math.max(0,R-_.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${_}${E}`,Ee.stdout.write(e.lastRenderedLine),t)Ee.stdout.write(`
124
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||qe()||!Ee.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(qe()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Zs(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let a=Bi(this.config.logDirectory,n);if(e.before)try{if((await Oi(a)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${a}:`,s);continue}r.push(a)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Ks(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var fJ=new Ao("stacks");class tr extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}}class e_ extends tr{code="CONFIG_NOT_FOUND";constructor(e,t,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],i="";if(n.length===1)i=` or alias "${n[0]}"`;else if(n.length>1)i=` or aliases ${n.map((a)=>`"${a}"`).join(", ")}`;super(`Configuration "${e}"${i} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}}class Io extends tr{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}}class t_ extends tr{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}}class r_ extends tr{code="CONFIG_MERGE_ERROR";constructor(e,t,r,n){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}}class yl extends tr{code="ENV_VAR_ERROR";constructor(e,t,r,n){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:n})}}class n_ extends tr{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class i_ extends tr{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class mo extends tr{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}}class a_ extends tr{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,n){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:n})}}class s_ extends tr{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}}var zi={configNotFound(e,t,r){return new e_(e,t,r)},configLoad(e,t,r){return new Io(e,t,r)},configValidation(e,t,r){return new t_(e,t,r)},configMerge(e,t,r,n){return new r_(e,t,r,n)},envVar(e,t,r,n){return new yl(e,t,r,n)},fileSystem(e,t,r){return new n_(e,t,r)},typeGeneration(e,t,r){return new i_(e,t,r)},schemaValidation(e,t,r){return new mo(e,t,r)},browserConfig(e,t,r,n){return new a_(e,t,r,n)},plugin(e,t,r){return new s_(e,t,r)}};async function SP(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:a}=t,s=Error("Unknown error occurred");for(let d=0;d<=r;d++)try{return await e()}catch(c){if(s=c instanceof Error?c:Error(String(c)),d===r||!i(s))break;if(n>0)await new Promise((o)=>setTimeout(o,n))}if(a!==void 0)return a;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}class wl{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:n,useCamelCase:i=!0,useBackwardCompatibility:a=!0,customParsers:s={},verbose:d=!1,trackPerformance:c=!0}=r,o=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let g=n||this.generateEnvPrefix(e),h={...t};return this.processObject(h,[],g,{useCamelCase:i,useBackwardCompatibility:a,customParsers:s,verbose:d,configName:e}),{config:h,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return fl.track("applyEnvironmentVariables",o,{configName:e});return o()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,n){for(let[i,a]of Object.entries(e)){let s=[...t,i],d=s.map((g)=>this.formatEnvKey(g,n.useCamelCase)),c=`${r}_${d.join("_")}`,o=n.useBackwardCompatibility?`${r}_${s.map((g)=>g.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof a==="object"&&a!==null&&!Array.isArray(a))this.processObject(a,s,r,n);else{let g=Xs.env[c]||(o?Xs.env[o]:void 0);if(g!==void 0){if(n.verbose){let h=Xs.env[c]?c:o}try{e[i]=this.parseEnvironmentValue(g,typeof a,c,n.customParsers,n.configName)}catch(h){if(h instanceof yl)throw h;throw zi.envVar(c,g,typeof a,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[a,s]of Object.entries(n))try{return s(e)}catch{continue}for(let a of this.defaultParsers)if(a.canParse(e,t))try{return a.parse(e)}catch{throw zi.envVar(r,e,`${t} (via ${a.name} parser)`,i)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,i]of Object.entries(Xs.env))if(n.startsWith(r)&&i!==void 0)t[n]=i;return t}validateEnvironmentVariable(e,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))n.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(i){n.push(`Cannot parse value "${t}" as ${r}: ${i}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(e,t,r={}){let{prefix:n,format:i="text"}=r,a=n||this.generateEnvPrefix(e),s=[];switch(this.extractEnvVarInfo(t,[],a,s),i){case"markdown":return this.formatAsMarkdown(s,e);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,e)}}extractEnvVarInfo(e,t,r,n){for(let[i,a]of Object.entries(e)){let s=[...t,i],d=`${r}_${s.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof a==="object"&&a!==null&&!Array.isArray(a))this.extractEnvVarInfo(a,s,r,n);else n.push({key:d,type:Array.isArray(a)?"array":typeof a,description:`Configuration for ${s.join(".")}`,example:this.generateExample(a)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
125
+
126
+ `;for(let n of e)r+=`${n.key}
127
+ `,r+=` Type: ${n.type}
128
+ `,r+=` Description: ${n.description}
129
+ `,r+=` Example: ${n.example}
130
+
131
+ `;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
132
+
133
+ `;r+=`| Variable | Type | Description | Example |
134
+ `,r+=`|----------|------|-------------|----------|
135
+ `;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
136
+ `;return r}}function _P(e,t,r={}){return o_(e,t,r,new WeakMap)}function o_(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:a=!1,customMerger:s}=r;if(t===null||t===void 0)return a?e:t;if(s){let d=s(e,t);if(d!==void 0)return d}if(Array.isArray(t)||Array.isArray(e))return d_(e,t,i,n);if(!Mt(t)||!Mt(e))return t;return mP(e,t,r,n)}function d_(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 RP(e,t);case"smart":return pP(e,t,n);default:return t}return t}function RP(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>hl(i,n)))r.push(n);return r}function pP(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(Mt(t[0])&&Mt(e[0]))return IP(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 IP(e,t,r){let n=[...t];for(let i of e){if(!Mt(i)){n.push(i);continue}let a=["id","name","key","path","type"],s=!1;for(let d of a)if(d in i){if(n.find((o)=>Mt(o)&&(d in o)&&o[d]===i[d])){s=!0;break}}if(!s)n.push(i)}return n}function mP(e,t,r,n){let i=t;if(Mt(i)&&n.has(i))return n.get(i);let a={...e};if(Mt(i))n.set(i,a);for(let s in i){if(!Object.prototype.hasOwnProperty.call(i,s))continue;let d=i[s],c=a[s];if(r.skipNullish&&(d===null||d===void 0))continue;if(d===null||d===void 0){a[s]=d;continue}if(Mt(d)&&Mt(c))a[s]=o_(c,d,r,n);else if(Array.isArray(d)||Array.isArray(c))a[s]=d_(c,d,r.arrayMergeMode||"smart",n);else a[s]=d}return a}function c_(e,t,r="replace"){return _P(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function hl(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(!hl(e[r],t[r]))return!1;return!0}if(Mt(e)&&Mt(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(!hl(e[i],t[i]))return!1}return!0}return!1}function Mt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class l_{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:a,trackPerformance:s=!0,verbose:d=!1}=r;if(i){let o=so.getWithFileCheck("file",e);if(o){if(d)console.log(`Configuration loaded from cache: ${e}`);return o}}let c=async()=>{if(!qs(e))return null;try{let o=`?t=${Date.now()}`,g=await import(e+o),h=g.default||g,_="default"in g,R=Object.keys(g).length>0;if(!_&&!R)throw new Io(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof h!=="object"||h===null||Array.isArray(h))throw new Io(e,Error("Configuration must export a valid object"),"unknown");let $={config:c_(t,h,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)so.setWithFileCheck("file",$,e,a);return $}catch(o){throw o instanceof Error?zi.configLoad(e,o):zi.configLoad(e,Error(String(o)))}};if(s)return fl.track("loadFromPath",c,{path:e});return c()}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){let n=this.generateNamePatterns(e,r),i=[];for(let a of n)for(let s of this.extensions)i.push(el(t,`${a}${s}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);let n=t===void 0?[]:Array.isArray(t)?t:[t];for(let a of n){if(!a)continue;if(r.push(a,`.${a}.config`,`${a}.config`,`.${a}`),e)r.push(`${e}.${a}.config`,`.${e}.${a}.config`)}let i=new Set;return r.filter((a)=>{if(!a||i.has(a))return!1;return i.add(a),!0})}checkFileAccess(e){return SP(async()=>{return qs(e)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!qs(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let a of i)for(let s of this.extensions){let d=el(e,`${a}${s}`);if(await this.checkFileAccess(d))n.push(d)}}else try{let{readdirSync:i}=await import("fs"),a=i(e);for(let s of a)if(this.looksLikeConfigFile(s)){let d=el(e,s);if(await this.checkFileAccess(d))n.push(d)}}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(!qs(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"),a=i(e,"utf8");JSON.parse(a)}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 yP=/^https?:\/\//;class g_{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:a=!0,customRules:s=[],trackPerformance:d=!0,verbose:c=!1}=r,o=async()=>{let g=[],h=[],_={stopOnFirstError:n,validateRequired:i,validateTypes:a,customRules:s,trackPerformance:d,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,_);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...s],_);else return this.validateWithJSONSchema(e,t,_)}catch(R){return g.push({path:"",message:`Validation failed: ${R}`,rule:"system"}),{isValid:!1,errors:g,warnings:h}}};if(d)return await fl.track("validateConfiguration",o);return o()}async validateWithSchemaFile(e,t,r){try{if(!EP(t))throw new mo(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 mo(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,a){if(a.validateTypes&&t.type){let s=Array.isArray(e)?"array":typeof e,d=Array.isArray(t.type)?t.type:[t.type];if(!d.includes(s)){if(n.push({path:r,message:`Expected type ${d.join(" or ")}, got ${s}`,expected:d.join(" or "),actual:s,rule:"type"}),a.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"}),a.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 d=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(e[s],t.items,d,n,i,a),a.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let s=e;if(a.validateRequired&&t.required){for(let d of t.required)if(!(d in s)){if(n.push({path:r?`${r}.${d}`:d,message:`Missing required property '${d}'`,expected:"required",rule:"required"}),a.stopOnFirstError)return}}if(t.properties){for(let[d,c]of Object.entries(t.properties))if(d in s){let o=r?`${r}.${d}`:d;if(this.validateObjectAgainstSchema(s[d],c,o,n,i,a),a.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let d=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(s))if(!d.has(c))i.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let a of t)try{let s=this.getValueByPath(e,a.path),d=this.validateWithRule(s,a,a.path);if(n.push(...d),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:a.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,a,s]=n;t.push({path:i,required:!a,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:yP},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var hr=new Ao("bunfig",{showTags:!0});function wP(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 u_{fileLoader=new l_;envProcessor=new wl;validator=new g_;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:a,...s}=e;try{if(r?.enabled){let c=this.checkCache(s.name||"",s);if(c)return c}let d;try{d=await this.loadConfigurationStrategies(s,!0,r)}catch(c){let o=s.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(o)throw c;d={...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(c instanceof Error&&c.name==="ConfigLoadError"){let g=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),h=!g&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),_=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(o&&(_||g))throw c;if(h&&(!o||!_))d={...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(!o)d={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else d={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(i||a)await this.validateConfiguration(d.config,i,a,s.name);if(r?.enabled&&d)this.cacheResult(s.name||"",d,r,s);if(n?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(c);if(n.slowThreshold&&c.duration>n.slowThreshold)hr.warn(`Slow configuration loading detected: ${c.duration}ms for ${s.name}`);d.metrics=c}return d}catch(d){if(d instanceof Error&&d.name==="ConfigNotFoundError")throw d;let c=Date.now()-t;throw hr.error(`Configuration loading failed after ${c}ms:`,[d instanceof Error?d:Error(String(d))]),d}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:a,configDir:s,defaultConfig:d,checkEnv:c=!0,arrayStrategy:o="replace",verbose:g=!1}=e,h=a||Eo.cwd(),_=[],R=await this.loadLocalConfiguration(n,i,h,s,d,o,g,c,r);if(R)return _.push(...this.getLocalSearchPaths(n,i,h,s)),this.finalizeResult(R,_,c,n,g);let E=await this.loadHomeConfiguration(n,i,d,o,g,c);if(E)return _.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(E,_,c,n,g);let y=await this.loadPackageJsonConfiguration(n,i,h,d,o,g,c);if(y)return _.push(Lt(h,"package.json")),this.finalizeResult(y,_,c,n,g);if(_.push(...this.getAllSearchPaths(n,i,h,s)),t)throw zi.configNotFound(n,_,i);return{...await this.applyEnvironmentVariables(n,d,c,g),warnings:[`No configuration file found for "${n}"${wP(i)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,a,s,d,c){let o=d?eo(e,i,s):i,g=this.getLocalDirectories(r,n);for(let h of g){if(s)hr.info(`Searching for configuration in: ${h}`);let _=this.fileLoader.generateConfigPaths(e,h,t),R=await this.fileLoader.tryLoadFromPaths(_,o,{arrayStrategy:a,verbose:s,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(R){if(s)hr.success(`Configuration loaded from: ${R.source.path}`);return R}}return null}async loadHomeConfiguration(e,t,r,n,i,a){if(!e)return null;let s=a?eo(e,r,i):r,d=[Lt(Ai(),".config",e),Lt(Ai(),".config"),Ai()];for(let c of d){if(i)hr.info(`Checking home directory: ${c}`);let o=this.fileLoader.generateConfigPaths(e,c,t),g=await this.fileLoader.tryLoadFromPaths(o,s,{arrayStrategy:n,verbose:i});if(g){if(i)hr.success(`Configuration loaded from home directory: ${g.source.path}`);return g}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,a,s){let d=s?eo(e,n,a):n;try{let c=Lt(r,"package.json");if(!_w(c))return null;let o={};try{o=JSON.parse(Rw(c,"utf8"))}catch(_){if(a)hr.warn("Failed to parse package.json:",[_ instanceof Error?_:Error(String(_))]);return null}let g=o[e],h=e;if(!g&&t){let _=Array.isArray(t)?t:[t];for(let R of _){if(!R)continue;if(o[R]){g=o[R],h=R;break}}}if(g&&typeof g==="object"&&!Array.isArray(g)){if(a)hr.success(`Configuration loaded from package.json: ${h}`);return{config:c_(d,g,i),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(a)hr.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}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:eo(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 a=r(e);if(a)i.push(...a)}if(t){let a=await this.validator.validateConfiguration(e,t);if(!a.isValid)i.push(...a.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(i.length>0)throw zi.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return so.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);so.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.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,Lt(e,"config"),Lt(e,".config"),t?Lt(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(Lt(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),a=[];for(let s of i)a.push(...this.fileLoader.generateConfigPaths(e,s,t));return a}getHomeSearchPaths(e,t){if(!e)return[];let r=[Lt(Ai(),".config",e),Lt(Ai(),".config"),Ai()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}var tl=new u_;async function h_(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 tl.loadConfig(e);else n=await tl.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let i=n instanceof Error?n.name:"UnknownError",a=n instanceof Error?n.message:String(n);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||a.includes("config"))&&e.verbose)hr.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let d=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await tl.applyEnvironmentVariables(d.name||"",t,!0,d.verbose||!1))?.config??t;return t}}function eo(e,t,r=!1){let n=new wl,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function a(s,d=[]){let c={...s};for(let[o,g]of Object.entries(s)){let h=[...d,o],_=[`${i}_${h.join("_").toUpperCase()}`,`${i}_${h.map((y)=>y.toUpperCase()).join("")}`,`${i}_${h.map((y)=>y.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],R,E;for(let y of _)if(R=Eo.env[y],R!==void 0){E=y;break}if(R!==void 0&&E)if(typeof g==="boolean")c[o]=["true","1","yes"].includes(R.toLowerCase());else if(typeof g==="number"){let y=Number(R);if(!Number.isNaN(y))c[o]=y}else if(Array.isArray(g))try{c[o]=JSON.parse(R)}catch{c[o]=R.split(",").map((y)=>y.trim())}else c[o]=R;else if(g&&typeof g==="object"&&!Array.isArray(g))c[o]=a(g,h)}return c}return a(t)}var IJ=Lt(Eo.cwd(),"config"),mJ=Lt(Eo.cwd(),"src/generated");var Al={project:{name:"my-project",slug:"my-project",region:"us-east-1"},environments:{production:{type:"production"}}},Ln=null;function DP(e){return e.project?.slug===Al.project?.slug&&Object.keys(e.environments??{}).length===1&&!!e.environments?.production}async function $P(){let e=[f_(process.cwd(),"config","cloud.ts"),f_(process.cwd(),"config","cloud.js")];for(let t of e){if(!AP(t))continue;let r=await import(`${PP(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 CP(){if(!Ln){if(Ln=await h_({name:"cloud",defaultConfig:Al}),DP(Ln))Ln=await $P()??Ln;S_(Ln.stateDir)}return Ln}var __=CP,$J=Al;var un=(e)=>e==null?void 0:String(e),Dl=(e)=>Number(e)===1,p_=(e,t)=>{try{return e==null?t:JSON.parse(String(e))}catch{return t}};function Pl(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),scope:{type:String(e.scope_type),id:String(e.scope_id),environmentId:un(e.environment_id),resourceId:un(e.resource_id),previewId:un(e.preview_id)},key:String(e.key),kind:String(e.kind),value:un(e.value),valueFingerprint:String(e.value_fingerprint),secretRef:un(e.secret_ref),backend:String(e.backend),backendVersion:un(e.backend_version),origin:String(e.origin),required:Dl(e.required),metadata:p_(e.metadata,{}),lastUsedAt:un(e.last_used_at),rotatedAt:un(e.rotated_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function R_(e){return{entryId:String(e.entry_id),resourceId:String(e.resource_id),injectionTarget:String(e.injection_target),required:Dl(e.required),requiresRedeploy:Dl(e.requires_redeploy),lastDeployedVersion:e.last_deployed_version==null?void 0:Number(e.last_deployed_version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}class $l{controlPlane;now;constructor(e,t=()=>new Date){this.controlPlane=e;this.now=t}get(e){let t=this.controlPlane.database.query("SELECT * FROM configuration_entries WHERE id=?").get(e);return t?Pl(t):void 0}find(e,t,r){let n=this.controlPlane.database.query("SELECT * FROM configuration_entries WHERE project_id=? AND scope_type=? AND scope_id=? AND key=?").get(e,t.type,t.id,r);return n?Pl(n):void 0}list(e){let t=["project_id=?"],r=[e.projectId];if(e.scope)t.push("scope_type=?","scope_id=?"),r.push(e.scope.type,e.scope.id);if(e.kind)t.push("kind=?"),r.push(e.kind);return this.controlPlane.database.query(`SELECT * FROM configuration_entries WHERE ${t.join(" AND ")} ORDER BY key,scope_type,scope_id`).all(...r).map(Pl)}create(e){this.validateScope(e),this.validateEntry(e);let t=crypto.randomUUID(),r=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO configuration_entries (id,organization_id,project_id,scope_type,scope_id,environment_id,resource_id,preview_id,key,kind,value,value_fingerprint,secret_ref,backend,backend_version,origin,required,metadata,last_used_at,rotated_at,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.organizationId,e.projectId,e.scope.type,e.scope.id,e.scope.environmentId??null,e.scope.resourceId??null,e.scope.previewId??null,e.key,e.kind,e.value??null,e.valueFingerprint,e.secretRef??null,e.backend,e.backendVersion??null,e.origin,e.required?1:0,JSON.stringify(e.metadata),e.lastUsedAt??null,e.rotatedAt??null,1,r,r]),this.get(t)}update(e,t,r){let n=this.get(e);if(!n)throw Error("Configuration entry was not found.");if(this.validateEntry({...n,...r}),this.controlPlane.database.run("UPDATE configuration_entries SET value=?,value_fingerprint=?,secret_ref=?,backend=?,backend_version=?,required=?,metadata=?,rotated_at=?,version=version+1,updated_at=? WHERE id=? AND version=?",[r.value??null,r.valueFingerprint,r.secretRef??null,r.backend,r.backendVersion??null,r.required?1:0,JSON.stringify(r.metadata),r.rotatedAt??null,this.now().toISOString(),e,t]).changes!==1)throw Error("Configuration entry changed; refresh and retry.");return this.get(e)}remove(e,t){let r=this.get(e);if(!r)throw Error("Configuration entry was not found.");if(r.version!==t)throw Error("Configuration entry changed; refresh and retry.");if(this.controlPlane.database.run("DELETE FROM configuration_entries WHERE id=? AND version=?",[e,t]).changes<1)throw Error("Configuration entry changed; refresh and retry.");return r}setDependency(e){let t=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO configuration_dependencies (entry_id,resource_id,injection_target,required,requires_redeploy,last_deployed_version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?) ON CONFLICT(entry_id,resource_id) DO UPDATE SET injection_target=excluded.injection_target,required=excluded.required,requires_redeploy=excluded.requires_redeploy,last_deployed_version=excluded.last_deployed_version,updated_at=excluded.updated_at",[e.entryId,e.resourceId,e.injectionTarget,e.required?1:0,e.requiresRedeploy?1:0,e.lastDeployedVersion??null,t,t]),this.dependencies(e.entryId).find((r)=>r.resourceId===e.resourceId)}dependencies(e){return this.controlPlane.database.query("SELECT * FROM configuration_dependencies WHERE entry_id=? ORDER BY resource_id").all(e).map(R_)}dependenciesForResource(e){return this.controlPlane.database.query("SELECT * FROM configuration_dependencies WHERE resource_id=? ORDER BY entry_id").all(e).map(R_)}mutation(e){let t=this.controlPlane.database.query("SELECT request_hash,result FROM configuration_mutations WHERE idempotency_key=?").get(e);return t?{requestHash:t.request_hash,result:p_(t.result,{})}:void 0}recordMutation(e){this.controlPlane.database.run("INSERT INTO configuration_mutations (id,project_id,idempotency_key,request_hash,result,actor_id,created_at) VALUES (?,?,?,?,?,?,?)",[crypto.randomUUID(),e.projectId,e.idempotencyKey,e.requestHash,JSON.stringify(e.result),e.actorId??null,this.now().toISOString()])}validateEntry(e){if(!/^[A-Za-z_][A-Za-z0-9_]{0,255}$/.test(e.key))throw Error(`Invalid configuration key: ${e.key}`);if(e.kind==="variable"&&(e.value==null||e.secretRef||e.backend!=="plaintext"))throw Error("Variables require a plaintext value and cannot use a secret backend.");if(e.kind==="secret"&&(e.value!=null||!e.secretRef||e.backend==="plaintext"))throw Error("Secrets require a non-plaintext backend reference and cannot store a plaintext value.")}validateScope(e){let t=this.controlPlane.getProject(e.projectId);if(!t||t.organizationId!==e.organizationId)throw Error("Configuration project does not belong to the organization.");let r=e.scope;if(r.type==="project"){if(r.id!==e.projectId||r.environmentId||r.resourceId||r.previewId)throw Error("Project configuration scope must reference only its project.");return}if(r.type==="environment"){let i=this.controlPlane.database.query("SELECT project_id FROM environments WHERE id=?").get(r.id);if(!i||i.project_id!==e.projectId||r.environmentId&&r.environmentId!==r.id||r.resourceId||r.previewId)throw Error("Environment configuration scope does not belong to the project.");return}if(r.type==="service"||r.type==="function"){let i=this.controlPlane.getResource(r.id);if(!i||i.projectId!==e.projectId||r.type==="function"&&i.kind!=="function"||r.resourceId&&r.resourceId!==r.id||r.environmentId&&i.environmentId!==r.environmentId||r.previewId)throw Error(`${r.type==="function"?"Function":"Service"} configuration scope does not belong to the project.`);return}let n=this.controlPlane.database.query("SELECT project_id,base_environment_id,resource_id FROM preview_instances WHERE id=?").get(r.id);if(!n||n.project_id!==e.projectId||r.previewId&&r.previewId!==r.id||r.environmentId&&r.environmentId!==n.base_environment_id||r.resourceId&&r.resourceId!==n.resource_id)throw Error("Preview configuration scope does not belong to the project.")}}var I_=/^[A-Za-z_][A-Za-z0-9_]{0,255}$/;function kP(e){let t={n:`
137
+ `,r:"\r",t:"\t","\\":"\\",'"':'"',$:"$"};return e.replace(/\\(n|r|t|\\|"|\$)/g,(r,n)=>t[n])}function m_(e){let t={},r=[],n=e.replace(/\r\n?/g,`
138
+ `).split(`
139
+ `);for(let i=0;i<n.length;i++){let a=i+1,s=n[i];if(!s.trim()||s.trimStart().startsWith("#"))continue;if(/^\s*export\s+/.test(s))s=s.replace(/^\s*export\s+/,"");let d=s.match(/^\s*([^=\s]+)\s*=\s*(.*)$/);if(!d){r.push({line:a,severity:"error",code:"invalid_line",message:"Expected KEY=VALUE."});continue}let c=d[1],o=d[2];if(!I_.test(c)){r.push({line:a,key:c,severity:"error",code:"invalid_key",message:`Invalid environment variable name: ${c}`});continue}let g=o;if(o.startsWith('"')||o.startsWith("'")){let h=o[0],_=[o.slice(1)],R=!1;while(!0){let E=_[_.length-1],y=!1,$=-1;for(let b=0;b<E.length;b++){if(h==='"'&&E[b]==="\\"&&!y){y=!0;continue}if(E[b]===h&&!y){$=b;break}y=!1}if($>=0){_[_.length-1]=E.slice(0,$),R=!0;break}if(++i>=n.length)break;_.push(n[i])}if(!R){r.push({line:a,key:c,severity:"error",code:"unterminated_quote",message:`Unterminated quoted value for ${c}.`});continue}if(g=_.join(`
140
+ `),h==='"')g=kP(g)}else g=o.replace(/\s+#.*$/,"").trim();if(Object.hasOwn(t,c)){let h=t[c]!==g;if(r.push({line:a,key:c,severity:h?"error":"warning",code:h?"conflict":"duplicate",message:h?`${c} has conflicting values.`:`${c} is duplicated with the same value.`}),h)continue}t[c]=g}return{values:t,diagnostics:r,valid:!r.some((i)=>i.severity==="error")}}function E_(e){return Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>{if(!I_.test(t))throw Error(`Invalid environment variable name: ${t}`);return`${t}=${JSON.stringify(r)}`}).join(`
141
+ `)+(Object.keys(e).length?`
142
+ `:"")}import{createCipheriv as bP,createDecipheriv as vP,createHash as y_,randomBytes as OP}from"node:crypto";class Aa{controlPlane;now;kind="local_encrypted";key;constructor(e,t,r=()=>new Date){this.controlPlane=e;this.now=r;if(!t)throw Error("Configuration encryption key is required.");this.key=y_("sha256").update(`ts-cloud:configuration:${t}`).digest()}encrypt(e){let t=OP(12),r=bP("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 configuration secret is unavailable.");try{let a=vP("aes-256-gcm",this.key,Buffer.from(r,"base64url"));return a.setAuthTag(Buffer.from(n,"base64url")),Buffer.concat([a.update(Buffer.from(i,"base64url")),a.final()]).toString("utf8")}catch{throw Error("Encrypted configuration secret could not be decrypted.")}}async put(e){if(!e.value)throw Error("Configuration secrets cannot be empty.");let t=e.reference??`secret://configuration/${e.name}/${crypto.randomUUID()}`;if(!/^secret:\/\/configuration\/[A-Za-z0-9._/-]+$/.test(t))throw Error("Invalid local configuration secret reference.");let n=(this.controlPlane.database.query("SELECT version FROM configuration_secret_values WHERE reference=?").get(t)?.version??0)+1,i=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO configuration_secret_values (reference,ciphertext,fingerprint,version,created_at,updated_at) VALUES (?,?,?,?,?,?) ON CONFLICT(reference) DO UPDATE SET ciphertext=excluded.ciphertext,fingerprint=excluded.fingerprint,version=excluded.version,updated_at=excluded.updated_at",[t,this.encrypt(e.value),y_("sha256").update(e.value).digest("hex"),n,i,i]),{reference:t,version:String(n)}}async resolve(e){let t=this.controlPlane.database.query("SELECT ciphertext FROM configuration_secret_values WHERE reference=?").get(e);if(!t)throw Error("Configuration secret was not found.");return this.decrypt(t.ciphertext)}async remove(e){this.controlPlane.database.run("DELETE FROM configuration_secret_values WHERE reference=?",[e])}async validate(e){return!!this.controlPlane.database.query("SELECT 1 AS found FROM configuration_secret_values WHERE reference=?").get(e)}}class Cl{client;region;kind="aws_secrets_manager";constructor(e,t){this.client=e;this.region=t}async put(e){if(e.reference){let r=this.id(e.reference),n=await this.client.putSecretValue({SecretId:r,SecretString:e.value,ClientRequestToken:e.idempotencyKey});return{reference:e.reference,version:n.VersionId??e.idempotencyKey}}let t=await this.client.createSecret({Name:e.name,SecretString:e.value,ClientRequestToken:e.idempotencyKey,Tags:[{Key:"managed-by",Value:"ts-cloud"}]});return{reference:`aws-sm://${this.region}/${encodeURIComponent(t.ARN??t.Name??e.name)}`,version:t.VersionId??e.idempotencyKey}}async resolve(e){let t=await this.client.getSecretValue({SecretId:this.id(e)});if(t.SecretString==null)throw Error("AWS Secrets Manager value is unavailable.");return t.SecretString}async remove(e){await this.client.deleteSecret({SecretId:this.id(e),RecoveryWindowInDays:7})}async validate(e){try{return await this.client.describeSecret(this.id(e)),!0}catch{return!1}}id(e){let t=new URL(e);if(t.protocol!=="aws-sm:"||t.hostname!==this.region)throw Error("Invalid AWS Secrets Manager reference.");return decodeURIComponent(t.pathname.slice(1))}}class kl{client;region;kind="aws_ssm";constructor(e,t){this.client=e;this.region=t}async put(e){let t=e.reference?this.name(e.reference):`/${e.name.replace(/^\/+/,"")}`,r=await this.client.putParameter({Name:t,Value:e.value,Type:"SecureString",Overwrite:!!e.reference,Description:"Managed by ts-cloud"});return{reference:`aws-ssm://${this.region}${t}`,version:String(r.Version??1)}}async resolve(e){let t=await this.client.getParameter({Name:this.name(e),WithDecryption:!0});if(t.Parameter?.Value==null)throw Error("AWS SSM parameter value is unavailable.");return t.Parameter.Value}async remove(e){await this.client.deleteParameter({Name:this.name(e)})}async validate(e){try{return!!(await this.client.getParameter({Name:this.name(e),WithDecryption:!1})).Parameter}catch{return!1}}name(e){let t=new URL(e);if(t.protocol!=="aws-ssm:"||t.hostname!==this.region||!t.pathname.startsWith("/"))throw Error("Invalid AWS SSM reference.");return t.pathname}}class bl{kind="external";async put(){throw Error("External secret references cannot be written by ts-cloud.")}async resolve(){throw Error("External secrets must be resolved by the deployment provider.")}async remove(){}async validate(e){return/^(?:vault|doppler|op|external):\/\//.test(e)}}import{createHmac as BP}from"node:crypto";var JP=/^(?:secret|aws-sm|aws-ssm|vault|doppler|op|external):\/\//,TP=/^(?:AWS_|TS_CLOUD_|PORT$|HOST$)/;function Bt(e){return[...new Set(e)].sort()}function w_(e,t={}){let r=e.kind==="secret";return{id:e.id,key:e.key,kind:e.kind,scope:e.scope,inherited:!!t.inherited,overridden:!!t.overridden,required:e.required,backend:!r||t.canReadSecretMetadata?e.backend:void 0,backendVersion:!r||t.canReadSecretMetadata?e.backendVersion:void 0,reference:r&&t.canReadSecretMetadata?e.secretRef:void 0,value:!r?e.value:void 0,lastUsedAt:e.lastUsedAt,rotatedAt:e.rotatedAt,version:e.version,updatedAt:e.updatedAt}}class vl{store;backends=new Map;fingerprintKey;now;constructor(e,t){if(this.store=e,this.fingerprintKey=t.fingerprintKey??t.encryptionKey,this.now=t.now??(()=>new Date),!this.fingerprintKey)throw Error("Configuration fingerprint key is required.");let r=t.backends??[new Aa(e.controlPlane,t.encryptionKey,this.now)];for(let n of r)this.backends.set(n.kind,n)}list(e){let t=e.search?.toLowerCase();return this.store.list(e).filter((r)=>!t||r.key.toLowerCase().includes(t)).map((r)=>w_(r,{canReadSecretMetadata:e.canReadSecretMetadata}))}plan(e){let t=this.store.list({projectId:e.projectId,scope:e.scope}),r=new Map(t.map((c)=>[c.key,c])),n=[],i=[],a=[],s=[];for(let[c,o]of Object.entries(e.values)){n.push(...this.warnings(c,o));let g=r.get(c);if(!g)i.push(c);else if(g.valueFingerprint!==this.fingerprint(o))a.push(c);else s.push(c)}let d=e.removeMissing?t.filter((c)=>!Object.hasOwn(e.values,c.key)).map((c)=>c.key):[];return{added:Bt(i),changed:Bt(a),removed:Bt(d),unchanged:Bt(s),affectedResourceIds:this.affectedResources(e.projectId,e.scope,[...i,...a,...d]),warnings:n}}async set(e){let t=this.requestHash(e),r=e.idempotencyKey;if(r){let E=this.store.mutation(r);if(E){if(E.requestHash!==t)throw Error("Idempotency key was already used for a different configuration mutation.");let y=this.store.get(String(E.result.entryId??""));if(!y)throw Error("Idempotent configuration result is no longer available.");return{entry:y,mutation:E.result.mutation,warnings:[]}}}if(e.value!=null&&JP.test(e.value))throw Error("Secret references must use the reference field, not a plaintext value field.");let n=this.store.find(e.projectId,e.scope,e.key),i=this.fingerprint(e.value??e.reference??"");if(n&&e.expectedVersion!=null&&n.version!==e.expectedVersion)throw Error("Configuration entry changed; refresh and retry.");if(n&&n.kind!==e.kind)throw Error("Delete the existing entry before changing between variable and secret kinds.");let a=e.kind==="variable"?"plaintext":e.backend??(e.reference?"external":"local_encrypted");if(!!n&&(n.valueFingerprint!==i||n.backend!==a||n.required!==!!e.required)&&(this.isProduction(n)||this.store.dependencies(n.id).length>0)&&!e.confirmed)throw Error("Confirmation is required because this replacement affects production or dependent services.");let d=e.reference,c;if(e.kind==="secret"){let E=this.backend(a);if(e.reference&&e.value==null){if(!await E.validate(e.reference))throw Error("Secret backend reference is unavailable or invalid.");c=n?.backendVersion??"external"}else{if(e.value==null)throw Error("A secret value or external reference is required.");let y=await E.put({reference:n?.backend===a?n.secretRef:void 0,name:this.backendName(e),value:e.value,idempotencyKey:r??crypto.randomUUID()});d=y.reference,c=y.version}}let o=e.kind==="variable"?e.value:void 0;if(e.kind==="variable"&&o==null)throw Error("A variable value is required.");let g=!n||n.valueFingerprint!==i||n.backend!==a||n.secretRef!==d||n.backendVersion!==c||n.required!==!!e.required,h=n?g?this.store.update(n.id,n.version,{value:o,valueFingerprint:i,secretRef:d,backend:a,backendVersion:c,required:!!e.required,metadata:Oe(e.metadata??n.metadata),rotatedAt:e.kind==="secret"?this.now().toISOString():n.rotatedAt}):n:this.store.create({organizationId:e.organizationId,projectId:e.projectId,scope:e.scope,key:e.key,kind:e.kind,value:o,valueFingerprint:i,secretRef:d,backend:a,backendVersion:c,origin:e.origin??"managed",required:!!e.required,metadata:Oe(e.metadata??{}),rotatedAt:e.kind==="secret"?this.now().toISOString():void 0}),_=this.affectedResources(e.projectId,e.scope,[e.key]),R={added:n?[]:[e.key],changed:n&&g?[e.key]:[],removed:[],unchanged:n&&!g?[e.key]:[],affectedResourceIds:_,versions:{[e.key]:h.version}};if(r)this.store.recordMutation({projectId:e.projectId,idempotencyKey:r,requestHash:t,actorId:e.actorId,result:{entryId:h.id,mutation:R}});return this.audit(e.projectId,e.actorId,n&&g?"configuration.updated":n?"configuration.unchanged":"configuration.created",h,_),{entry:h,mutation:R,warnings:this.warnings(e.key,e.value??"")}}async importDotenv(e){let t=m_(e.source);if(!t.valid)return{document:t,warnings:[]};let r=new Set(e.secretKeys??[]),n={added:[],changed:[],removed:[],unchanged:[],affectedResourceIds:[],versions:{}},i=[];for(let[a,s]of Object.entries(t.values)){let d=await this.set({...e,source:void 0,key:a,value:s,kind:r.has(a)?"secret":"variable",idempotencyKey:e.idempotencyKey?`${e.idempotencyKey}:${a}`:void 0});n.added.push(...d.mutation.added),n.changed.push(...d.mutation.changed),n.unchanged.push(...d.mutation.unchanged),n.affectedResourceIds.push(...d.mutation.affectedResourceIds),Object.assign(n.versions,d.mutation.versions),i.push(...d.warnings)}return n.added=Bt(n.added),n.changed=Bt(n.changed),n.unchanged=Bt(n.unchanged),n.affectedResourceIds=Bt(n.affectedResourceIds),{document:t,mutation:n,warnings:i}}exportVariables(e){return E_(Object.fromEntries(this.store.list({projectId:e.projectId,scope:e.scope,kind:"variable"}).map((t)=>[t.key,t.value??""])))}async transfer(e){let t=this.store.get(e.entryId);if(!t)throw Error("Configuration entry was not found.");if(t.scope.type===e.targetScope.type&&t.scope.id===e.targetScope.id)throw Error("Choose a different destination scope.");let r=t.kind==="variable"?t.value:t.backend==="external"?void 0:await this.backend(t.backend).resolve(t.secretRef),n=t.kind==="secret"?t.backend:void 0,i=await this.set({organizationId:t.organizationId,projectId:t.projectId,scope:e.targetScope,key:t.key,kind:t.kind,value:r,reference:t.backend==="external"?t.secretRef:void 0,backend:n,required:t.required,metadata:t.metadata,confirmed:e.confirmed,actorId:e.actorId,idempotencyKey:e.idempotencyKey?`${e.idempotencyKey}:copy`:void 0,origin:t.origin});if(e.mode==="move")await this.remove({entryId:t.id,expectedVersion:t.version,confirmed:e.confirmed,actorId:e.actorId});let a={added:i.mutation.added,changed:i.mutation.changed,removed:e.mode==="move"?[t.key]:[],unchanged:i.mutation.unchanged,affectedResourceIds:Bt([...i.mutation.affectedResourceIds,...this.affectedResources(t.projectId,t.scope,[t.key])]),versions:i.mutation.versions};return{entry:i.entry,mutation:a}}async resolve(e){let t=this.store.list({projectId:e.projectId}),r=t.filter((o)=>this.applies(o,e)).sort((o,g)=>this.rank(o.scope.type)-this.rank(g.scope.type)),n=new Map,i=new Set;for(let o of r){if(n.has(o.key))i.add(o.key);n.set(o.key,o)}let a={},s={},d=[],c=new Set(e.allowedPreviewSecrets??[]);for(let[o,g]of n){if(e.previewId&&g.kind==="secret"&&g.scope.type!=="preview"&&(!e.trustedPreview||!c.has(o)))continue;if(g.kind==="variable")a[o]=g.value??"";else if(e.nativeReferences)a[o]=g.secretRef;else{let h=this.backend(g.backend);if(!await h.validate(g.secretRef)){if(d.push({key:o,code:"stale_reference",message:`${o} points to an unavailable secret.`}),g.required)d.push({key:o,code:"missing_required",message:`${o} is required but unavailable.`});continue}a[o]=await h.resolve(g.secretRef)}s[o]=w_(g,{inherited:g.scope.type!==(e.previewId?"preview":e.functionId?"function":e.resourceId?"service":e.environmentId?"environment":"project"),overridden:i.has(o),canReadSecretMetadata:e.canReadSecretMetadata}),this.store.controlPlane.database.run("UPDATE configuration_entries SET last_used_at=? WHERE id=?",[this.now().toISOString(),g.id])}return{values:a,entries:s,warnings:d,configurationHash:this.fingerprint([...n.values()].map((o)=>`${o.key}:${o.valueFingerprint}:${o.version}`).sort().join(`
143
+ `))}}async reveal(e){let t=this.store.get(e.entryId);if(!t||t.kind!=="secret")throw Error("Configuration secret was not found.");if(!e.canRevealSecrets)throw Error("Secret reveal permission is required.");if(!e.recentlyAuthenticated)throw Error("Recent authentication is required to reveal a secret.");let r=await this.backend(t.backend).resolve(t.secretRef);return this.audit(t.projectId,e.actorId,"configuration.secret.revealed",t,[]),r}async remove(e){let t=this.store.get(e.entryId);if(!t)throw Error("Configuration entry was not found.");let r=this.store.dependencies(t.id);if(((t.scope.environmentId?this.store.controlPlane.listEnvironments(t.projectId).some((s)=>s.id===t.scope.environmentId&&s.kind==="production"):t.scope.type==="project")||r.length)&&!e.confirmed)throw Error("Confirmation is required because this configuration affects production or dependent services.");if(t.kind==="secret"&&t.backend!=="external")await this.backend(t.backend).remove(t.secretRef);this.store.remove(t.id,e.expectedVersion);let i=Bt(r.map((s)=>s.resourceId)),a={added:[],changed:[],removed:[t.key],unchanged:[],affectedResourceIds:i,versions:{}};return this.audit(t.projectId,e.actorId,"configuration.deleted",t,i),a}applies(e,t){if(e.scope.type==="project")return!0;if(e.scope.type==="environment")return e.scope.id===t.environmentId;if(e.scope.type==="service")return e.scope.id===t.resourceId;if(e.scope.type==="function")return e.scope.id===t.functionId;return e.scope.id===t.previewId}rank(e){return{project:0,environment:1,service:2,function:3,preview:4}[e]}fingerprint(e){return`hmac-sha256:${BP("sha256",this.fingerprintKey).update(e).digest("hex")}`}requestHash(e){return this.fingerprint(JSON.stringify({...e,idempotencyKey:void 0,actorId:void 0}))}backend(e){let t=this.backends.get(e);if(!t)throw Error(`Configuration secret backend is not configured: ${e}`);return t}backendName(e){return`ts-cloud/${e.projectId}/${e.scope.type}/${e.scope.id}/${e.key}`.replace(/[^A-Za-z0-9/_+=.@-]/g,"-")}isProduction(e){return e.scope.type==="project"||!!e.scope.environmentId&&this.store.controlPlane.listEnvironments(e.projectId).some((t)=>t.id===e.scope.environmentId&&t.kind==="production")}warnings(e,t){let r=[];if(TP.test(e))r.push({key:e,code:"reserved",message:`${e} may be reserved by the runtime or provider.`});if(Buffer.byteLength(t)>65536)r.push({key:e,code:"limit",message:`${e} exceeds the portable 64 KiB value limit.`});return r}affectedResources(e,t,r){let n=this.store.list({projectId:e,scope:t}).filter((i)=>r.includes(i.key)).flatMap((i)=>this.store.dependencies(i.id).map((a)=>a.resourceId));if(t.type==="service"||t.type==="function")return Bt([...n,t.id]);if(t.type==="environment")return Bt([...n,...this.store.controlPlane.listResources(e,t.id).map((i)=>i.id)]);if(t.type==="preview"){let i=this.store.controlPlane.database.query("SELECT resource_id FROM preview_instances WHERE id=?").get(t.id);return Bt([...n,...i?[i.resource_id]:[]])}return Bt([...n,...this.store.controlPlane.listResources(e).map((i)=>i.id)])}audit(e,t,r,n,i){this.store.controlPlane.appendEvent({projectId:e,actorId:t,type:r,payload:{entryId:n.id,key:n.key,kind:n.kind,scopeType:n.scope.type,scopeId:n.scope.id,backend:n.backend,version:n.version,affectedResourceIds:i}})}}async function A_(e,t,r,n){let i={added:0,changed:0,removed:0,overridden:0},a=async(s,d)=>{let c=e.store.list({projectId:t.project.id,scope:s,kind:"variable"}),o=new Set(Object.keys(d));for(let g of c.filter((h)=>h.origin==="config"&&!o.has(h.key)))await e.remove({entryId:g.id,expectedVersion:g.version,confirmed:!0,actorId:n}),i.removed++;for(let[g,h]of Object.entries(d)){let _=e.store.find(t.project.id,s,g);if(_?.origin!=="config"){if(_)i.overridden++;else await e.set({organizationId:t.organization.id,projectId:t.project.id,scope:s,key:g,kind:"variable",value:String(h),origin:"config",confirmed:!0,actorId:n}),i.added++;continue}if(_.value===String(h))continue;await e.set({organizationId:t.organization.id,projectId:t.project.id,scope:s,key:g,kind:"variable",value:String(h),origin:"config",confirmed:!0,actorId:n,expectedVersion:_.version}),i.changed++}};for(let[s,d]of Object.entries(r.environments??{})){let c=t.environments.get(s);if(!c)continue;let o=d,g={...o.variables??{},...o.app?.env??{}};await a({type:"environment",id:c.id,environmentId:c.id},g);for(let[h,_]of Object.entries(r.sites??{})){let R=t.store.listResources(t.project.id,c.id).find((E)=>E.kind==="application"&&E.slug===h);if(R)await a({type:"service",id:R.id,environmentId:c.id,resourceId:R.id},{..._.env??{}})}for(let[h,_]of Object.entries(r.infrastructure?.functions??{})){let R=t.store.listResources(t.project.id,c.id).find((E)=>E.kind==="function"&&E.slug===h);if(R)await a({type:"function",id:R.id,environmentId:c.id,resourceId:R.id},{..._.environment??{}})}}return i}import{createHash as zP}from"node:crypto";var P_=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 D_{async scan(e,t){let r=await P_(["ssh-keyscan","-T","10","-p",String(t),"-t","ed25519",e]),n=r.stdout.split(`
144
+ `).find((i)=>i&&!i.startsWith("#"))?.trim().split(/\s+/);if(r.code!==0||!n?.[1]||!n[2])throw Error(`SSH host-key scan failed: ${r.stderr.trim()||"no key returned"}`);return{algorithm:n[1],key:n[2]}}async exec(e,t){if(e.trustState!=="pinned")throw Error("SSH host key must be pinned before remote execution.");return P_(["ssh","-p",String(e.sshPort),"-o","BatchMode=yes","-o","StrictHostKeyChecking=yes","-o","ConnectTimeout=10",`${e.sshUser}@${e.endpoint}`,t])}}var WP=(e)=>`SHA256:${zP("sha256").update(Buffer.from(e,"base64")).digest("base64").replace(/=+$/,"")}`,jP=`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 Pa{provider;transport;discoverer;constructor(e,t=new D_,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:WP(t.key),latencyMs:0}}catch{return{reachable:!1,hostKeyAlgorithm:"unknown",hostKeyFingerprint:"",latencyMs:0}}}async validate(e){let t=await this.transport.exec(e,jP);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 $_(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 a=t.find((c)=>c.provider===i.provider);if(!a)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 d=await a.bootstrap(i,s);return e.update(i.id,{bootstrapVersion:d.version,status:"ready"}),r.checkpoint("verify","Bootstrap completed; heartbeat can now establish freshness."),{serverId:i.id,bootstrapVersion:d.version,steps:s.length}}}}var fr=(e)=>e==null?void 0:String(e),xn=(e,t)=>{try{return JSON.parse(String(e))}catch{return t}},Ol=(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:fr(e.provider_id),region:fr(e.region),zone:fr(e.zone),endpoint:String(e.endpoint),sshUser:String(e.ssh_user),sshPort:Number(e.ssh_port),credentialRef:String(e.credential_ref),hostKeyAlgorithm:fr(e.host_key_algorithm),hostKeyFingerprint:fr(e.host_key_fingerprint),pendingHostKey:fr(e.pending_host_key),roles:xn(e.roles,[]),labels:xn(e.labels,{}),taints:xn(e.taints,[]),capacity:xn(e.capacity,{}),usage:xn(e.usage,{}),capabilities:xn(e.capabilities,{}),status:String(e.status),trustState:String(e.trust_state),validation:xn(e.validation,void 0),bootstrapVersion:fr(e.bootstrap_version),heartbeatAt:fr(e.heartbeat_at),lastSeenAt:fr(e.last_seen_at),archivedAt:fr(e.archived_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)});class Bl{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?Ol(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(Ol).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?Ol(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 UP=/^(?:[A-Za-z0-9](?:[A-Za-z0-9.-]{0,251}[A-Za-z0-9])?|\[[0-9a-fA-F:]+\])$/;class Jl{store;drivers;now;queue;constructor(e,t,r,n=()=>new Date){this.store=e;this.drivers=t;this.now=n;this.queue=r??new Be(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(!UP.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"},a={cpu:r.cpuCores??0,memoryBytes:r.memoryBytes??0,diskBytes:r.diskBytes??0};return this.store.update(e,{validation:i,capacity:a,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 Tl,createPublicKey as b_,verify as HP}from"node:crypto";function Da(e){if(e===null||typeof e!=="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(Da).join(",")}]`;return`{${Object.keys(e).sort().map((t)=>`${JSON.stringify(t)}:${Da(e[t])}`).join(",")}}`}var v_=(e)=>Tl("sha256").update(Da(e)).digest("hex"),Po=(e)=>Tl("sha256").update(Da(e)).digest("hex"),O_=(e)=>Tl("sha256").update(b_(e).export({type:"spki",format:"der"})).digest("hex");function B_(e,t,r){try{return HP(null,Buffer.from(Da(e)),b_(r),Buffer.from(t,"base64"))}catch{return!1}}var C_=(e)=>e.replace(/^v/,"").split(/[.-]/).slice(0,3).map((t)=>Number(t)||0),k_=(e,t)=>{let r=C_(e),n=C_(t);for(let i=0;i<3;i++){let a=(r[i]??0)-(n[i]??0);if(a)return a}return 0};function J_(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&&k_(t.currentVersion,e.minimumVersion)<0)r.push(`platform ${t.currentVersion} is below ${e.minimumVersion}`);if(k_(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 Tr=(e,t)=>{try{return JSON.parse(String(e))}catch{return t}},ut=(e)=>e==null?void 0:String(e),NP=(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:ut(e.revoked_at),createdAt:String(e.created_at)}),T_=(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:Tr(e.document,{}),signature:String(e.signature),verificationStatus:String(e.verification_status),compatibility:Tr(e.compatibility,{compatible:!1,reasons:[]}),createdAt:String(e.created_at)}),z_=(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:Tr(e.allowed_operations,[]),requireApproval:Number(e.require_approval)===1,enabled:Number(e.enabled)===1,createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),W_=(e)=>({id:String(e.id),projectId:String(e.project_id),manifestId:String(e.manifest_id),windowId:ut(e.window_id),fromVersion:String(e.from_version),strategy:String(e.strategy),batchSize:Number(e.batch_size),healthGate:Tr(e.health_gate,{}),status:String(e.status),currentStage:ut(e.current_stage),backupId:ut(e.backup_id),approvedBy:ut(e.approved_by),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),zl=(e)=>({id:String(e.id),campaignId:String(e.campaign_id),serverId:ut(e.server_id),target:String(e.target),cohort:Number(e.cohort),previousVersion:String(e.previous_version),status:String(e.status),evidence:Tr(e.evidence,{}),error:ut(e.error),startedAt:ut(e.started_at),finishedAt:ut(e.finished_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),j_=(e)=>({id:String(e.id),projectId:String(e.project_id),kind:String(e.kind),criteria:Tr(e.criteria,{}),candidates:Tr(e.candidates,[]),candidateDigest:String(e.candidate_digest),estimatedBytes:Number(e.estimated_bytes),status:String(e.status),confirmation:ut(e.confirmation),expiresAt:String(e.expires_at),result:Tr(e.result,{}),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),U_=(e)=>({id:String(e.id),projectId:String(e.project_id),backupPolicyId:ut(e.backup_policy_id),recoveryPointId:ut(e.recovery_point_id),topologyId:ut(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:ut(e.operation_id),evidence:Tr(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:ut(e.error),startedAt:ut(e.started_at),finishedAt:ut(e.finished_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)});class Wl{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=O_(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?NP(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(!B_(e.document,e.signature,t.publicKeyPem))throw Error("Update manifest signature is invalid.");let r=J_(e.document,e.current),n=v_(e.document),i=this.id(),a=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),a]),this.manifest(i)}manifest(e){let t=this.control.database.query("SELECT * FROM platform_update_manifests WHERE id=?").get(e);return t?T_(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(T_)}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?z_(t):void 0}windows(e){return this.control.database.query("SELECT * FROM maintenance_windows WHERE project_id=? ORDER BY name").all(e).map(z_)}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,a)=>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"?a===0?0:1+Math.floor((a-1)/e.batchSize):Math.floor(a/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?W_(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(W_)}targets(e){return this.control.database.query("SELECT * FROM platform_upgrade_targets WHERE campaign_id=? ORDER BY cohort,target").all(e).map(zl)}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={...zl(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]),zl(this.control.database.query("SELECT * FROM platform_upgrade_targets WHERE id=?").get(e))}createCleanup(e){let t=[...e.candidates].sort((s,d)=>s.id.localeCompare(d.id)),r=Po(t),n=this.id(),i=this.now().toISOString(),a=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,d)=>s+d.bytes,0),a,i,i]),this.cleanup(n)}cleanup(e){let t=this.control.database.query("SELECT * FROM cleanup_plans WHERE id=?").get(e);return t?j_(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(j_)}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?U_(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(U_)}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 FP(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),a=Number(i.find((d)=>d.type==="hour")?.value)*60+Number(i.find((d)=>d.type==="minute")?.value),s=Number(n[1])*60+Number(n[2]);return a>=s&&a<s+e.durationMinutes}class jl{store;now;queue;constructor(e,t,r=()=>new Date){this.store=e;this.now=r;this.queue=t??new Be(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&&!FP(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 Ul=(e)=>e&&typeof e==="object"&&!Array.isArray(e)?e:{};function H_(e){return{"maintenance.upgrade":async(i)=>{let a=e.store.campaign(String(Ul(i.operation.input).campaignId??""));if(!a||!e.platform)throw Error("Upgrade campaign or platform maintenance driver is unavailable.");let s=e.store.manifest(a.manifestId);if(!s?.compatibility.compatible||s.verificationStatus!=="verified")throw Error("Update manifest is no longer verified and compatible.");let d=s.document.artifacts.find((o)=>o.platform===process.platform&&o.architecture===process.arch)??s.document.artifacts[0];if(!d)throw Error("No update artifact matches this platform.");e.store.updateCampaign(a.id,{status:"running",currentStage:"preflight"});let c=[];try{for(let o of[...new Set(e.store.targets(a.id).map((g)=>g.cohort))].sort((g,h)=>g-h)){e.store.updateCampaign(a.id,{currentStage:`cohort:${o}`});for(let g of e.store.targets(a.id).filter((h)=>h.cohort===o)){i.throwIfCancellationRequested(),i.checkpoint(`download:${g.target}`,"Downloading signed platform artifact."),e.store.updateTarget(g.id,{status:"downloading",startedAt:new Date().toISOString()});let h=await e.platform.download({target:g,artifact:d,signal:i.signal});if(h.sha256!==d.sha256)throw Error(`Artifact checksum mismatch for ${g.target}.`);i.checkpoint(`install:${g.target}`,"Installing verified artifact."),e.store.updateTarget(g.id,{status:"installing"}),await e.platform.install({target:g,path:h.path,version:s.version,signal:i.signal}),c.push(g);let _=await e.platform.health({target:g,gate:a.healthGate});if(!_.healthy)throw Error(`Upgrade health gate failed for ${g.target}.`);e.store.updateTarget(g.id,{status:"healthy",evidence:_.evidence,finishedAt:new Date().toISOString()})}}return e.store.updateCampaign(a.id,{status:"succeeded",currentStage:void 0}),{campaignId:a.id,version:s.version,targets:c.length}}catch(o){e.store.updateCampaign(a.id,{status:"rolling_back",currentStage:"rollback"});for(let g of c.reverse())e.store.updateTarget(g.id,{status:"rolling_back"}),await e.platform.rollback({target:g,version:g.previousVersion,signal:i.signal}),e.store.updateTarget(g.id,{status:"rolled_back",finishedAt:new Date().toISOString()});throw e.store.updateCampaign(a.id,{status:"rolled_back",currentStage:void 0}),o}},"maintenance.cleanup":async(i)=>{let a=e.store.cleanup(String(Ul(i.operation.input).planId??""));if(!a||a.status!=="approved")throw Error("Approved cleanup plan was not found.");if(Po([...a.candidates].sort((g,h)=>g.id.localeCompare(h.id)))!==a.candidateDigest)throw Error("Cleanup candidate set changed after preview.");let s=e.cleanup?.find((g)=>g.kind===a.kind);if(!s)throw Error(`No ${a.kind} cleanup driver is configured.`);e.store.updateCleanup(a.id,{status:"running"});let d=[],c=[];for(let g of a.candidates){i.throwIfCancellationRequested();try{await s.remove(g),d.push(g.id)}catch(h){c.push({id:g.id,error:h instanceof Error?h.message:String(h)})}}let o=c.length?d.length?"partial":"failed":"succeeded";if(e.store.updateCleanup(a.id,{status:o,result:{removed:d,failed:c,reclaimedBytes:a.candidates.filter((g)=>d.includes(g.id)).reduce((g,h)=>g+h.bytes,0)}}),c.length)throw Error(`Cleanup failed for ${c.length} candidate(s).`);return{planId:a.id,removed:d.length,reclaimedBytes:a.estimatedBytes}},"maintenance.drill":async(i)=>{let a=e.store.drill(String(Ul(i.operation.input).drillId??""));if(!a)throw Error("DR drill was not found.");let s=e.recovery?.find((h)=>h.scenario===a.scenario);if(!s)throw Error(`No ${a.scenario} recovery driver is configured.`);let d=new Date;e.store.updateDrill(a.id,{status:"restoring",startedAt:d.toISOString()});let c=a.isolatedTarget,o={},g={};try{i.checkpoint("restore","Restoring into isolated drill target.");let h=await s.restore({drill:a,signal:i.signal});if(!h.target.startsWith("isolated://"))throw Error("Recovery driver attempted a non-isolated target.");c=h.target,o=h.evidence;let _=(d.getTime()-new Date(h.recoveryPointAt).getTime())/60000;e.store.updateDrill(a.id,{status:"verifying",measuredRpoMinutes:_,evidence:{restore:o}}),i.checkpoint("verify","Running recovery health checks without production traffic.");let R=await s.verify({drill:a,target:c});g=R.evidence;let E=(Date.now()-d.getTime())/60000;if(!R.healthy||_>a.expectedRpoMinutes||E>a.expectedRtoMinutes)throw Error("DR drill failed its health, RPO, or RTO objective.");e.store.updateDrill(a.id,{measuredRpoMinutes:_,measuredRtoMinutes:E,evidence:{restore:o,verify:g}})}catch(h){throw e.store.updateDrill(a.id,{status:"failed",error:h instanceof Error?h.message:String(h),evidence:{restore:o,verify:g}}),h}finally{e.store.updateDrill(a.id,{status:"cleaning"});try{await s.cleanup({drill:a,target:c});let h=e.store.drill(a.id);e.store.updateDrill(a.id,{status:h.error?"failed":"passed",cleanupVerified:!0,finishedAt:new Date().toISOString()})}catch(h){e.store.updateDrill(a.id,{status:"cleanup_required",cleanupVerified:!1,error:h instanceof Error?h.message:String(h),finishedAt:new Date().toISOString()})}}return{drillId:a.id,status:e.store.drill(a.id).status}}}}class VP{transport;constructor(e){this.transport=e}download(e){return this.transport.download({target:e.target.target,url:e.artifact.url,signal:e.signal})}install(e){return this.transport.install({target:e.target.target,path:e.path,version:e.version,signal:e.signal})}health(e){return this.transport.health({target:e.target.target,gate:e.gate})}rollback(e){return this.transport.rollback({target:e.target.target,version:e.version,signal:e.signal})}}var N_={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 Hl{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=N_[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(N_[this.kind].remove,[e.id]).changes!==1)throw Error(`${e.label} changed or is no longer removable.`)}}class LP{scenario;transport;constructor(e,t){this.scenario=e;this.transport=t}restore(e){return this.transport.restore({scenario:this.scenario,...e})}verify(e){return this.transport.verify({scenario:this.scenario,...e})}cleanup(e){return this.transport.cleanup({scenario:this.scenario,...e})}}var rr=(e,t)=>{try{return JSON.parse(String(e))}catch{return t}},Jt=(e)=>e==null?void 0:String(e),L_=()=>({cpu:0,memoryBytes:0,diskBytes:0,gpu:0}),Wi=(e={})=>({...L_(),...e});function F_(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:Jt(e.region),architecture:Jt(e.architecture),labels:rr(e.labels,{}),requiredServerLabels:rr(e.required_server_labels,{}),toleratedTaints:rr(e.tolerated_taints,[]),capacity:Wi(rr(e.capacity,{})),reserved:rr(e.reserved,{}),maxWorkloads:Number(e.max_workloads),costWeight:Number(e.cost_weight),spreadKey:Jt(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 V_(e){return{id:String(e.id),projectId:String(e.project_id),environmentId:Jt(e.environment_id),resourceId:String(e.resource_id),releaseId:Jt(e.release_id),poolId:String(e.pool_id),serverId:Jt(e.server_id),purpose:String(e.purpose),requirements:rr(e.requirements,{}),decision:rr(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 xP(e){return{id:String(e.id),projectId:String(e.project_id),resourceId:Jt(e.resource_id),poolId:String(e.pool_id),placementId:Jt(e.placement_id),operationId:Jt(e.operation_id),sourceSha:String(e.source_sha),buildSpec:rr(e.build_spec,{}),credentialPolicy:rr(e.credential_policy,{productionSecrets:!1,shortLivedTokenExpiresAt:""}),workspace:Jt(e.workspace),cacheKey:Jt(e.cache_key),artifactUri:Jt(e.artifact_uri),artifactDigest:Jt(e.artifact_digest),status:String(e.status),cleanupAt:Jt(e.cleanup_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}class Nl{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(Wi(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?F_(t):void 0}listPools(e){return this.control.database.query("SELECT * FROM capacity_pools WHERE project_id=? ORDER BY name").all(e).map(F_)}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:rr(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(V_);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?V_(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,a)=>{let s=Wi(rr(a.resources,{}));for(let d of Object.keys(i))i[d]+=s[d];return i},L_()),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(Wi(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?xP(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 Do=["cpu","memoryBytes","diskBytes","gpu"],x_=(e,t={})=>Object.entries(t).every(([r,n])=>e[r]===n),MP=(e,t,r)=>Object.fromEntries(Do.map((n)=>[n,Math.max(0,e[n]-t[n]-(r[n]??0))])),QP=(e,t)=>Do.every((r)=>e[r]>=(t[r]??0)),GP=(e,t)=>Do.reduce((r,n)=>r+(t[n]??0)/(e[n]||1),0);class Fl{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 a=[];if(i.status!=="active")a.push(`pool is ${i.status}`);if(i.purpose!==t.purpose)a.push(`purpose is ${i.purpose}`);if(t.region&&i.region!==t.region)a.push(`region is ${i.region??"unset"}`);if(t.architecture&&i.architecture!==t.architecture)a.push(`architecture is ${i.architecture??"unset"}`);if(!x_(i.labels,t.labels))a.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,[...a,"pool has no servers"]));for(let d of s){let c=this.fleet.get(d.serverId),o=[...a];if(!c)o.push("server is missing");else this.serverReasons(i,c,d.status,t,o);n.push(this.decision(i,c,t,o,d.capacityOverride))}}else n.push(this.decision(i,void 0,t,a))}return n.sort((i,a)=>Number(a.eligible)-Number(i.eligible)||i.score.cost-a.score.cost||i.score.spread-a.score.spread||i.score.fit-a.score.fit||i.poolName.localeCompare(a.poolName)||(i.serverId??"").localeCompare(a.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(!x_(t.labels,e.requiredServerLabels))i.push("server labels do not match pool selector");for(let a of t.taints)if(!e.toleratedTaints.includes(a))i.push(`taint ${a} is not tolerated`)}decision(e,t,r,n,i={}){let a=Wi({...t?.capacity,...i}),s=t?Object.fromEntries(Do.map((o)=>[o,Math.min(e.capacity[o],a[o])])):e.capacity,d=this.store.activeUsage(e.id,t?.id),c=MP(s,d.resources,e.reserved);if(d.count>=e.maxWorkloads)n.push("workload limit reached");if(r.purpose==="build"&&d.count>=e.concurrency)n.push("build concurrency reached");if(!QP(c,r.resources))n.push("insufficient capacity");return{poolId:e.id,poolName:e.name,serverId:t?.id,eligible:n.length===0,reasons:n,available:c,score:{fit:GP(c,r.resources),spread:d.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((a)=>a.poolId===e)){if(i.stateful){n.push(this.store.transitionPlacement(i.id,"blocked"));continue}this.store.transitionPlacement(i.id,"moving");let a=this.place({projectId:i.projectId,environmentId:i.environmentId,resourceId:i.resourceId,releaseId:i.releaseId,requirements:i.requirements});r.push(this.activate(a.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 a of this.store.listPlacements(r.projectId,["reserved","active"]).filter((s)=>s.poolId===e&&s.serverId===t)){if(a.stateful){i.push(this.store.transitionPlacement(a.id,"blocked"));continue}this.store.transitionPlacement(a.id,"moving");let s=this.poolCandidates(a.projectId,a.requirements).find((c)=>c.eligible);if(!s){i.push(this.store.transitionPlacement(a.id,"blocked"));continue}let d=this.store.reserve({projectId:a.projectId,environmentId:a.environmentId,resourceId:a.resourceId,releaseId:a.releaseId,requirements:a.requirements,decision:s});n.push(this.activate(d.id)),this.store.transitionPlacement(a.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((a)=>a.serverId===e)){if(i.stateful||!i.autoReschedule){n.push(this.store.transitionPlacement(i.id,"blocked"));continue}this.store.transitionPlacement(i.id,"failed");let a=this.place({projectId:i.projectId,environmentId:i.environmentId,resourceId:i.resourceId,releaseId:i.releaseId,requirements:i.requirements});r.push(this.activate(a.id))}return{rescheduled:r,blocked:n}}}class ZP{store;placement;now;queue;constructor(e,t,r,n=()=>new Date){this.store=e;this.placement=t;this.now=n;this.queue=r??new Be(e.control)}enqueue(e){if(!/^[a-f0-9]{7,64}$/i.test(e.sourceSha))throw Error("A pinned source commit SHA is required.");let t={purpose:"build",resources:{cpu:1,memoryBytes:1073741824,diskBytes:5368709120},leaseSeconds:3600,...e.requirements},r=this.placement.place({projectId:e.projectId,resourceId:e.resourceId,requirements:t}),n=new Date(this.now().getTime()+900000).toISOString(),i=this.store.createBuild({projectId:e.projectId,resourceId:e.resourceId,poolId:r.poolId,placementId:r.id,sourceSha:e.sourceSha,buildSpec:e.buildSpec,tokenExpiresAt:n}),a=this.queue.enqueue({projectId:e.projectId,resourceId:e.resourceId,kind:"build.remote",input:{buildId:i.id},lockKey:`build:${i.id}`,providerKey:`pool:${r.poolId}`,buildSlot:!0,timeoutSeconds:3600,cancellationMode:"cooperative",resumePolicy:"fail"}).operation;return i=this.store.updateBuild(i.id,{operationId:a.id}),i}cancel(e){let t=this.store.getBuild(e);if(!t)throw Error("Remote build was not found.");if(t.operationId)this.queue.requestCancellation(t.operationId);return this.store.updateBuild(e,{status:"cancelled"})}}var KP=/^sha256:[a-f0-9]{64}$/,YP=/^(?:s3|https|oci):\/\//;function ET(e,t){return{"build.remote":async(r)=>{let n=r.operation.input&&typeof r.operation.input==="object"&&!Array.isArray(r.operation.input)?r.operation.input:{},i=e.getBuild(String(n.buildId??""));if(!i)throw Error("Queued remote build was not found.");let a=e.getPool(i.poolId);if(!a||a.purpose!=="build"||a.status!=="active")throw Error("The selected build pool is unavailable.");if(!a.ephemeralWorkspaces)throw Error("Remote builds require an ephemeral workspace pool.");if(i.credentialPolicy.productionSecrets||a.allowProductionSecrets)throw Error("Production secrets are forbidden in remote build workers.");if(new Date(i.credentialPolicy.shortLivedTokenExpiresAt)<=new Date)throw Error("The short-lived build credential has expired.");let s=t.find((c)=>c.backend===a.backend);if(!s)throw Error(`No ${a.backend} remote build driver is configured.`);let d=`build://${a.id}/${i.id}`;e.updateBuild(i.id,{status:"running",workspace:d}),r.checkpoint("checkout",`Preparing isolated workspace for ${i.sourceSha}.`);try{r.throwIfCancellationRequested(),r.checkpoint("build","Executing resource-limited build.");let c=await s.run({build:e.getBuild(i.id),pool:a,signal:r.signal,log:(o)=>r.log(o,{stream:"stdout"})});if(r.throwIfCancellationRequested(),!KP.test(c.artifactDigest)||!YP.test(c.artifactUri))throw Error("Builder returned an unverified artifact reference.");return e.updateBuild(i.id,{status:"uploading",cacheKey:c.cacheKey,artifactUri:c.artifactUri,artifactDigest:c.artifactDigest}),r.checkpoint("verify","Verified content-addressed artifact upload."),await s.cleanup({build:e.getBuild(i.id),pool:a}),e.updateBuild(i.id,{status:"succeeded",workspace:void 0,cleanupAt:new Date().toISOString()}),{buildId:i.id,artifactUri:c.artifactUri,artifactDigest:c.artifactDigest,cacheKey:c.cacheKey??null}}catch(c){try{await s.cleanup({build:e.getBuild(i.id),pool:a}),e.updateBuild(i.id,{status:r.cancellationRequested()?"cancelled":"failed",workspace:void 0,cleanupAt:new Date().toISOString()})}catch{e.updateBuild(i.id,{status:"cleanup_required"})}throw c}}}}class $o{backend;transport;handles=new Map;constructor(e,t){this.backend=e;this.transport=t}async run({build:e,pool:t,signal:r,log:n}){let i=await this.transport.provision({backend:this.backend,pool:t,build:e,tokenExpiresAt:e.credentialPolicy.shortLivedTokenExpiresAt});return this.handles.set(e.id,i.handle),n(`${this.backend} builder provisioned`),await this.transport.execute({handle:i.handle,spec:e.buildSpec,sourceSha:e.sourceSha,signal:r,onLog:n}),this.transport.publish({handle:i.handle,sourceSha:e.sourceSha})}async cleanup({build:e}){let t=this.handles.get(e.id);if(!t)return;await this.transport.destroy({handle:t}),this.handles.delete(e.id)}}var wT=(e)=>new $o("server",e),AT=(e)=>new $o("ecs",e),PT=(e)=>new $o("asg",e);var zr=(e,t)=>{try{return JSON.parse(String(e))}catch{return t}},Qt=(e)=>e==null?void 0:String(e),M_=(e)=>({id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:Qt(e.environment_id),name:String(e.name),hostname:String(e.hostname),homeRegion:String(e.home_region),regions:zr(e.regions,[]),trafficPolicy:String(e.traffic_policy),dataPolicy:zr(e.data_policy,{replicate:[],maxLagSeconds:60,retainOnDestroy:!0}),status:String(e.status),activeRegion:String(e.active_region),revision:Qt(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:Qt(e.stack_id),stackRevision:Qt(e.stack_revision),status:String(e.status),health:zr(e.health,{}),lastHealthyAt:Qt(e.last_healthy_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),Ll=(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:zr(e.config,{}),status:String(e.status),checkpoint:Qt(e.checkpoint),lagSeconds:e.lag_seconds==null?void 0:Number(e.lag_seconds),lastVerifiedAt:Qt(e.last_verified_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),xl=(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:zr(e.weights,{}),desiredWeights:zr(e.desired_weights,{}),status:String(e.status),providerState:zr(e.provider_state,{}),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),Q_=(e)=>({id:String(e.id),topologyId:String(e.topology_id),operationId:Qt(e.operation_id),kind:String(e.kind),requestedRegion:Qt(e.requested_region),revision:Qt(e.revision),plan:zr(e.plan,[]),currentStep:Qt(e.current_step),completedSteps:zr(e.completed_steps,[]),status:String(e.status),error:Qt(e.error),createdAt:String(e.created_at),updatedAt:String(e.updated_at)});class Ml{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((a)=>a.region)).size!==e.regions.length||e.regions.filter((a)=>a.role==="primary").length!==1)throw Error("A topology requires unique regions and exactly one primary.");let t=e.regions.find((a)=>a.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 a 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,a.region,a.role,a.provider,n,n]);for(let a of e.dataPolicy.replicate)for(let s of e.regions)for(let d of e.regions.filter((c)=>c.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,a,s.region,d.region,"{}",n,n]);let i=Object.fromEntries(e.regions.map((a)=>[a.region,a.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?M_(t):void 0}list(e){return this.control.database.query("SELECT * FROM regional_topologies WHERE project_id=? ORDER BY name").all(e).map(M_)}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(Ll)}route(e){let t=this.control.database.query("SELECT * FROM regional_traffic_routes WHERE topology_id=?").get(e);return t?xl(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},a=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,a,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=Ll(r),i={...n,...t},a=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,a,e]),Ll(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=xl(r),i={...n,...t},a=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),a,e]),xl(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?Q_(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(Q_)}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 Ql{store;queue;constructor(e,t){this.store=e;this.queue=t??new Be(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),a=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}`),...a.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((a)=>a.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 XP=(e)=>e&&typeof e==="object"&&!Array.isArray(e)?e:{};function G_(e,t){let r=(o)=>{let g=t.find((h)=>h.provider===o.provider);if(!g)throw Error(`No ${o.provider} regional driver is configured.`);return g},n=(o,g,h)=>{o.throwIfCancellationRequested(),o.checkpoint(h,h),e.updateExecution(g.id,{status:"running",currentStep:h,completedSteps:[...e.execution(g.id).completedSteps,h]})},i=async(o,g)=>{let h=e.route(o.id);if(!h)throw Error("Regional traffic route was not found.");let _=e.targets(o.id).find((E)=>E.region===o.activeRegion)??e.targets(o.id)[0];if(!_)throw Error("Regional traffic target was not found.");e.updateRoute(h.id,{status:"applying",desiredWeights:g});let R=await r(_).applyTraffic({route:e.route(o.id),topology:o,weights:g});e.updateRoute(h.id,{status:Object.values(g).every((E)=>E===0)?"drained":"in_sync",weights:g,providerState:R.providerState})},a=async(o,g,h,_)=>{e.updateTopology(h.id,{status:"provisioning"});let R=g.revision,E=_.manifest??{},y=e.targets(h.id).sort((b,z)=>Number(b.role==="primary")-Number(z.role==="primary"));for(let b of y){n(o,g,`apply:${b.region}`),e.updateTarget(b.id,{status:"provisioning"});let z=await r(b).applyStack({target:b,revision:R,manifest:E,signal:o.signal}),C=await r(b).health({target:e.updateTarget(b.id,{stackId:z.stackId,stackRevision:R})});if(!C.healthy)throw Error(`Regional health gate failed in ${b.region}.`);e.updateTarget(b.id,{status:"ready",health:C.evidence,lastHealthyAt:new Date().toISOString()})}for(let b of e.channels(h.id)){n(o,g,`replicate:${b.kind}:${b.targetRegion}`),e.updateChannel(b.id,{status:"configuring"});let z=y.find((N)=>N.region===b.sourceRegion),C=await r(z).configureReplication({channel:b,topology:h}),B=await r(z).verifyReplication({channel:e.updateChannel(b.id,{checkpoint:C.checkpoint,lagSeconds:C.lagSeconds}),topology:h});if(!B.healthy||B.lagSeconds>h.dataPolicy.maxLagSeconds)throw Error(`${b.kind} replication to ${b.targetRegion} exceeds the RPO.`);e.updateChannel(b.id,{status:"in_sync",checkpoint:B.checkpoint,lagSeconds:B.lagSeconds,lastVerifiedAt:new Date().toISOString()})}n(o,g,"traffic:activate");let $=Object.fromEntries(h.regions.map((b)=>[b.region,b.region===h.activeRegion?100:0]));return await i(h,$),e.updateTopology(h.id,{status:"ready",revision:R}),{revision:R,activeRegion:h.activeRegion}},s=async(o,g,h)=>{let _=g.requestedRegion,R=e.targets(h.id).find(($)=>$.region===_);if(!R)throw Error("Requested regional target was not found.");e.updateTopology(h.id,{status:g.kind==="failover"?"failing_over":"failing_back"}),n(o,g,`health:${_}`);let E=await r(R).health({target:R});if(!E.healthy)throw Error(`Target region ${_} is unhealthy.`);e.updateTarget(R.id,{status:"ready",health:E.evidence,lastHealthyAt:new Date().toISOString()}),n(o,g,`replication:${_}`);for(let $ of e.channels(h.id).filter((b)=>b.targetRegion===_)){let b=await r(R).verifyReplication({channel:$,topology:h});if(!b.healthy||b.lagSeconds>h.dataPolicy.maxLagSeconds)throw Error(`${$.kind} replication is outside the failover RPO.`);e.updateChannel($.id,{status:"in_sync",checkpoint:b.checkpoint,lagSeconds:b.lagSeconds,lastVerifiedAt:new Date().toISOString()})}n(o,g,`traffic:${_}`),await i(h,Object.fromEntries(h.regions.map(($)=>[$.region,$.region===_?100:0]))),n(o,g,`roles:${_}`);let y=h.regions.map(($)=>({...$,role:$.region===_?"primary":"secondary"}));for(let $ of e.targets(h.id))e.updateTarget($.id,{role:$.region===_?"primary":"secondary"});return e.updateTopology(h.id,{status:g.kind==="failover"?"failed_over":"ready",activeRegion:_,regions:y}),{activeRegion:_}},d=async(o,g,h,_)=>{e.updateTopology(h.id,{status:"destroying"}),n(o,g,"traffic:drain"),await i(h,Object.fromEntries(h.regions.map((E)=>[E.region,0])));let R=_.deleteData!==!0;for(let E of e.targets(h.id).sort((y,$)=>Number(y.role==="primary")-Number($.role==="primary")))n(o,g,`delete:${E.region}`),e.updateTarget(E.id,{status:"deleting"}),await r(E).deleteStack({target:E,retainData:R,signal:o.signal}),e.updateTarget(E.id,{status:"deleted"});return n(o,g,"complete"),e.updateTopology(h.id,{status:"destroyed"}),{destroyed:!0,dataRetained:R}},c=async(o)=>{let g=XP(o.operation.input),h=e.execution(String(g.executionId??""));if(!h)throw Error("Regional execution was not found.");let _=e.get(h.topologyId);if(!_)throw Error("Regional topology was not found.");try{let R;if(h.kind==="rollout")R=await a(o,h,_,g);else if(h.kind==="failover"||h.kind==="failback")R=await s(o,h,_);else if(h.kind==="destroy")R=await d(o,h,_,g);else throw Error("Regional reconciliation is not configured.");return e.updateExecution(h.id,{status:"succeeded",currentStep:void 0}),{executionId:h.id,...R}}catch(R){if(e.updateExecution(h.id,{status:o.cancellationRequested()?"cancelled":"failed",error:R instanceof Error?R.message:String(R)}),e.get(_.id)?.status!=="destroyed")e.updateTopology(_.id,{status:"failed"});throw R}};return{"region.rollout":c,"region.failover":c,"region.failback":c,"region.destroy":c,"region.reconcile":c}}class qP{transport;provider="aws";constructor(e){this.transport=e}async applyStack({target:e,revision:t,manifest:r}){return this.transport.applyCloudFormation({region:e.region,stackId:e.stackId,revision:t,manifest:r})}async deleteStack({target:e,retainData:t}){if(!e.stackId)return;await this.transport.deleteCloudFormation({region:e.region,stackId:e.stackId,retainData:t})}async health({target:e}){if(!e.stackId)return{healthy:!1,evidence:{reason:"stack is not provisioned"}};return this.transport.stackHealth({region:e.region,stackId:e.stackId})}async configureReplication({channel:e}){let t={sourceRegion:e.sourceRegion,targetRegion:e.targetRegion,config:e.config};if(e.kind==="s3")return this.transport.configureS3Replication(t);if(e.kind==="dynamodb")return this.transport.configureDynamoGlobalTable(t);return this.transport.replicateSecrets(t)}async verifyReplication({channel:e}){return this.transport.verifyReplication({kind:e.kind,sourceRegion:e.sourceRegion,targetRegion:e.targetRegion,checkpoint:e.checkpoint})}async applyTraffic({route:e,weights:t}){return this.transport.applyEdge({hostname:e.hostname,weights:t,route53:e.dnsProvider==="route53",cloudFront:e.cdnEnabled,waf:e.wafEnabled})}}class Gl{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 Sr(e,t,r){return[e,t,r].map((n)=>encodeURIComponent(n)).join(":")}function eD(e){return Object.fromEntries(["start","stop","restart","redeploy","scale","logs","exec","inspect","files"].map((t)=>[t,{supported:!1,reason:e}]))}function Mn(e,t,r=["exec","files"]){let n=eD(t);for(let i of e)n[i]={supported:!0,requiresConfirmation:!["logs","inspect"].includes(i),requiresRecentAuth:r.includes(i)};return n}var tD=/(?:secret|password|passwd|token|api[_-]?key|private[_-]?key|credential|authorization|cookie)/i;function jr(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 Wr(e){if(Array.isArray(e))return e.map((r)=>Wr(r));if(!e||typeof e!=="object")return e;let t={};for(let[r,n]of Object.entries(e))t[r]=tD.test(r)?"[REDACTED]":Wr(n);return t}function Qn(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 Z_(e){let t=Number(e);return Number.isFinite(t)&&t>=0?t:void 0}function rD(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 K_(e,t={},r={}){let n=t.now??new Date,i=Math.max(100,r.timeoutMs??1e4),a=Math.max(1,r.staleAfterSeconds??60),s=await Promise.all(e.map(async(c)=>{try{let o=await Promise.race([c.discover({...t,now:n}),new Promise((g,h)=>setTimeout(()=>h(Error(`Runtime source ${c.id} timed out after ${i}ms`)),i))]);return{workloads:o,source:{id:c.id,provider:c.provider,status:"fresh",discoveredAt:n.toISOString(),staleAfterSeconds:a,itemCount:o.length}}}catch(o){return{workloads:[],source:{id:c.id,provider:c.provider,status:rD(o),discoveredAt:n.toISOString(),staleAfterSeconds:a,itemCount:0,message:String(o?.message??o).slice(0,500)}}}})),d=s.map((c)=>c.source);return{generatedAt:n.toISOString(),workloads:s.flatMap((c)=>c.workloads).sort((c,o)=>c.name.localeCompare(o.name)||c.id.localeCompare(o.id)),sources:d,degraded:d.some((c)=>c.status!=="fresh")}}function ji(e){return e?.split("/").at(-1)??e?.split(":").at(-1)??"unknown"}function Y_(e,t,r,n="ecs:aws",i=[]){let a=r.now??new Date;return e.map((s)=>{let d=s.serviceName??ji(s.serviceArn),c=t.filter((b)=>!s.clusterArn||b.clusterArn===s.clusterArn),o=c.some((b)=>!!b.group)?c.filter((b)=>b.group===`service:${d}`):c,g=s.status==="ACTIVE"?(s.runningCount??0)<(s.desiredCount??0)?"degraded":"running":jr(s.status),h=i.find((b)=>b.taskDefinitionArn===s.taskDefinition),_=Array.isArray(h?.containerDefinitions)?h.containerDefinitions:[],R=[...new Set(_.map((b)=>b.logConfiguration?.options?.["awslogs-group"]).filter((b)=>typeof b==="string"))],E=_.flatMap((b)=>(b.mountPoints??[]).map((z)=>({source:z.sourceVolume,target:z.containerPath,type:"volume",readOnly:!!z.readOnly}))),y=_.flatMap((b)=>(b.portMappings??[]).map((z,C)=>({id:`${b.name??"container"}:${C}`,name:b.name,mode:h?.networkMode,ports:[{container:z.containerPort,host:z.hostPort,protocol:z.protocol}]}))),$=r.project&&r.environment&&d.startsWith(`${r.project}-${r.environment}-`)?d.slice(`${r.project}-${r.environment}-`.length):d;return{id:Sr("ecs",n,s.serviceArn??d),provider:"ecs",kind:"service",name:d,status:g,rawStatus:s.status,health:g==="running"?"healthy":g==="failed"||g==="degraded"?"unhealthy":"unknown",desiredReplicas:s.desiredCount,runningReplicas:s.runningCount,image:_[0]?.image,runtime:s.launchType??"ECS",version:ji(s.taskDefinition),ageSeconds:Qn(s.deployments?.[0]?.createdAt,a),restartCount:0,tags:{},links:{project:r.project,environment:r.environment,service:$,release:ji(s.taskDefinition),providerId:s.serviceArn},replicas:o.map((b)=>{let z=jr(b.lastStatus);return{id:Sr("ecs",n,b.taskArn??ji(b.taskArn)),name:ji(b.taskArn),status:z,rawStatus:b.lastStatus,createdAt:b.createdAt,startedAt:b.startedAt,stoppedAt:b.stoppedAt,host:b.containerInstanceArn,containers:(b.containers??[]).map((C)=>({id:C.containerArn??C.name??"container",name:C.name??"container",image:_.find((B)=>B.name===C.name)?.image,imageDigest:C.imageDigest,status:jr(C.lastStatus),rawStatus:C.lastStatus,exitCode:C.exitCode,reason:C.reason,runtime:"ecs"}))}}),networks:y,mounts:E,capabilities:Mn(["start","stop","restart","redeploy","scale","inspect",...R.length?["logs"]:[]],"This ECS runtime does not expose exec or file transfer; logs require an awslogs task-definition driver"),config:Wr({clusterArn:s.clusterArn,taskDefinition:s.taskDefinition,launchType:s.launchType,pendingCount:s.pendingCount,deployments:s.deployments,logGroups:R,executionRoleArn:h?.executionRoleArn,taskRoleArn:h?.taskRoleArn,cpu:h?.cpu,memory:h?.memory}),discoveredAt:a.toISOString(),sourceId:n}})}function X_(e,t,r="lambda:aws"){let n=t.now??new Date;return e.map((i)=>{let a=i.FunctionName??ji(i.FunctionArn),s=i.State==="Active"?"running":jr(i.State);return{id:Sr("lambda",r,i.FunctionArn??a),provider:"lambda",kind:"function",name:a,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:Qn(i.LastModified,n),restartCount:0,tags:{},links:{project:t.project,environment:t.environment,service:a,providerId:i.FunctionArn},resources:{memoryLimitBytes:i.MemorySize==null?void 0:i.MemorySize*1024*1024},replicas:[],networks:[],mounts:[],capabilities:Mn(["logs","inspect"],"Lambda has no persistent process to start, stop, restart, exec, or browse files; deploy a release to replace code"),config:Wr({handler:i.Handler,timeout:i.Timeout,codeSize:i.CodeSize,stateReason:i.StateReason,environmentKeys:Object.keys(i.Environment?.Variables??{})}),discoveredAt:n.toISOString(),sourceId:r}})}function nD(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 iD(e){let t=Object.entries(e.NetworkSettings?.Ports??{}).flatMap(([r,n])=>{let[i,a]=r.split("/");return(n??[]).map((s)=>({container:Number(i)||void 0,host:Number(s.HostPort)||void 0,protocol:a,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 aD(e){return(e.Mounts??[]).filter((t)=>!!t.Destination).map((t)=>({source:t.Source,target:t.Destination,type:t.Type,readOnly:t.RW===!1}))}function sD(e,t,r=t.server??"local"){let n=t.now??new Date;return e.map((i)=>{let a=i.State?.OOMKilled?"oomkilled":i.State?.Restarting?"starting":i.State?.Status,s=jr(a),d=(i.Name??i.Id.slice(0,12)).replace(/^\//,""),c=i.Config?.Labels??{},o=aD(i),g=iD(i),h={id:i.Id,name:d,image:i.Config?.Image,imageDigest:i.Image,runtime:"docker",status:s,rawStatus:a,exitCode:i.State?.ExitCode,reason:i.State?.Error,resources:{memoryLimitBytes:i.HostConfig?.Memory||void 0},networks:g,mounts:o};return{id:Sr("docker",r,i.Id),provider:"docker",kind:"container",name:d,status:s,rawStatus:a,health:s==="running"?"healthy":s==="failed"?"unhealthy":"unknown",desiredReplicas:1,runningReplicas:s==="running"?1:0,image:i.Config?.Image,runtime:"docker",ageSeconds:Qn(i.State?.StartedAt,n),restartCount:i.RestartCount??0,tags:c,links:{project:t.project,environment:t.environment,server:t.server??r.replace(/^docker:/,""),service:c["com.docker.compose.service"]??c["ts-cloud.service"]??d,release:c["ts-cloud.release"],providerId:i.Id},resources:h.resources,replicas:[{id:Sr("docker",r,`${i.Id}:0`),name:d,status:s,rawStatus:a,startedAt:i.State?.StartedAt,stoppedAt:i.State?.FinishedAt,restartCount:i.RestartCount,containers:[h],resources:h.resources}],networks:g,mounts:o,capabilities:Mn(["start","stop","restart","logs","exec","inspect","files"],"Use the owning Compose service for redeploy and scale"),config:Wr({image:i.Config?.Image,labels:c,environmentKeys:(i.Config?.Env??[]).map((_)=>_.split("=",1)[0]),networkMode:i.HostConfig?.NetworkMode}),discoveredAt:n.toISOString(),sourceId:r}})}class Zl{inspect;id;provider="docker";constructor(e,t="docker:local"){this.inspect=e;this.id=t}async discover(e){return sD(nD(await this.inspect(e)),e,this.id)}}function oD(e){let t=[];for(let r of e.split(`
145
+ `)){if(!r.startsWith("TSCLOUD_SYSTEMD\t"))continue;let[,n,i,a,s,d,c,o,g,h,_,R,E,y]=r.split("\t");if(!n||!/^[A-Za-z0-9_.@:-]+\.service$/.test(n))continue;t.push({unit:n,load:i,active:a,sub:s,description:d,enabled:c,pid:Number(o)||void 0,memoryBytes:Z_(g),restartCount:Number(h)||0,activeSince:_||void 0,fragmentPath:R||void 0,workingDirectory:E?.startsWith("/")?E:void 0,user:y||void 0})}return t}function dD(e,t,r=t.server??"local"){let n=t.now??new Date;return e.map((i)=>{let a=jr(i.active==="active"?i.sub||i.active:i.active),s=i.unit.replace(/\.service$/,""),d=/^(.*?) (?: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),c=s.includes("@")?s.slice(s.indexOf("@")+1):void 0,o=i.workingDirectory?[{target:i.workingDirectory,type:"working-directory"}]:[],g=["start","stop","restart","logs","exec","inspect",...o.length?["files"]:[]];return{id:Sr("systemd",r,i.unit),provider:"systemd",kind:"service",name:s,displayName:i.description||s,status:a,rawStatus:[i.load,i.active,i.sub].filter(Boolean).join("/"),health:a==="running"?"healthy":a==="failed"?"unhealthy":"unknown",desiredReplicas:1,runningReplicas:a==="running"?1:0,ageSeconds:Qn(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:d,release:c,providerId:i.unit},resources:{memoryBytes:i.memoryBytes},replicas:[{id:Sr("systemd",r,`${i.unit}:main`),name:"main",status:a,pid:i.pid,startedAt:i.activeSince,restartCount:i.restartCount,resources:{memoryBytes:i.memoryBytes}}],networks:[],mounts:o,capabilities:Mn(g,o.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:Wr({fragmentPath:i.fragmentPath,workingDirectory:i.workingDirectory,user:i.user,environment:i.environment,enabled:i.enabled}),discoveredAt:n.toISOString(),sourceId:r}})}class Kl{read;id;provider="systemd";constructor(e,t="systemd:local"){this.read=e;this.id=t}async discover(e){return dD(oD(await this.read(e)),e,this.id)}}function cD(e,t){if(!e.success)throw Error(e.error||e.perInstance?.[0]?.error||`${t} discovery failed`);return e.perInstance?.[0]?.output??""}function lD(){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 gD(){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 q_(e,t,r,n,i){let a=`${e}:${r.id}`,s=async()=>cD(await t.runRemoteDeploy({targets:[r],commands:e==="systemd"?lD():gD(),timeoutSeconds:30,comment:`ts-cloud runtime discovery:${e}`,tags:{Project:n.project.slug,Environment:i,Role:"app"}}),a);return e==="systemd"?new Kl(s,a):new Zl(s,a)}async function Co(e,t=100){let r=[],n;for(let i=0;i<t;i++){let a=await e(n);if(r.push(...a.items),!a.nextToken)return r;n=a.nextToken}throw Error(`Provider pagination exceeded ${t} pages`)}class eR{client;prefix;id="ecs:aws";provider="ecs";constructor(e,t){this.client=e;this.prefix=t}async discover(e){let t=await Co(async(a)=>{let s=await this.client.listClusters({nextToken:a,maxResults:100});return{items:s.clusterArns??[],nextToken:s.nextToken}}),r=[],n=[],i=[];for(let a of t){let s=(await Co(async(d)=>{let c=await this.client.listServices(a,{nextToken:d,maxResults:100});return{items:c.serviceArns??[],nextToken:c.nextToken}})).filter((d)=>d.split("/").at(-1)?.startsWith(this.prefix));for(let d=0;d<s.length;d+=10){let c=await this.client.describeServices({cluster:a,services:s.slice(d,d+10)});r.push(...c.services??[])}for(let d of r.filter((c)=>c.clusterArn===a||!c.clusterArn)){let c=await Co(async(o)=>{let g=await this.client.listTasks(a,d.serviceName,{nextToken:o,maxResults:100});return{items:g.taskArns??[],nextToken:g.nextToken}});for(let o=0;o<c.length;o+=100){let g=await this.client.describeTasks(a,c.slice(o,o+100));n.push(...g.tasks??[])}}}if(this.client.describeTaskDefinition)for(let a of[...new Set(r.map((s)=>s.taskDefinition).filter((s)=>!!s))]){let s=await this.client.describeTaskDefinition(a);if(s.taskDefinition)i.push(s.taskDefinition)}return Y_(r,n,e,this.id,i)}}class tR{client;prefix;id="lambda:aws";provider="lambda";constructor(e,t){this.client=e;this.prefix=t}async discover(e){let t=(await Co(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 X_(t,e,this.id)}}async function uD(e,t,r={}){let n=[],i=Ur(e),a=Yl(e),s=e.aws?.profile,d=e.aws?.region??e.project.region??"us-east-1",c=`${e.project.slug}-${t}`;if(i!=="serverless"){let o=r.driver??nr({config:e}),g=await o.findComputeTargets({slug:e.project.slug,environment:t,role:"app"});for(let h of g)n.push(q_("systemd",o,h,e,t)),n.push(q_("docker",o,h,e,t))}if(a==="aws")n.push(new eR(r.ecs??new ko(d,s),c)),n.push(new tR(r.lambda??new Et(d,s),c));return n}async function ir(e,t,r={}){let n={project:e.project.slug,environment:t};try{return await K_(await uD(e,t,r),n)}catch(i){return{generatedAt:new Date().toISOString(),workloads:[],sources:[{id:"runtime:bootstrap",provider:Yl(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 rR=65536,$a=49152,vo=/^[A-Za-z0-9_.@:-]+\.service$/,Oo=/^[a-fA-F0-9]{12,128}$/,hD=["/boot","/dev","/etc","/proc","/root","/run","/sys","/var/run"];function Ui(e){let t=Buffer.from(e);return t.byteLength<=rR?e:`${t.subarray(0,rR-24).toString("utf8")}
146
+ [output truncated]`}function bo(e){return{success:!1,instanceCount:0,perInstance:[],error:e instanceof Error?e.message:String(e)}}function Gt(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function fD(e,t){return Number.isFinite(e)?Math.min(1e4,Math.max(0,Math.floor(e))):t}function SD(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 _D(e,t){return e.find((r)=>r.id===t.links.server)??(e.length===1?e[0]:void 0)}function RD(e,t){if(e.provider==="systemd"){let r=e.links.providerId;if(!r||!vo.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||!Oo.test(r)||!["start","stop","restart"].includes(t))return;return[`docker ${t} ${r}`,`docker inspect --format '{{.State.Status}}' ${r}`]}return}function pD(e,t){if(!t.startsWith("/")||t.includes("\x00"))return{ok:!1,error:"An absolute path is required."};let r=[];for(let d of t.split("/")){if(!d||d===".")continue;if(d===".."){if(!r.length)return{ok:!1,error:"Path traversal is not allowed."};r.pop()}else r.push(d)}let n=`/${r.join("/")}`;if(hD.some((d)=>n===d||n.startsWith(`${d}/`)))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,""),a=e.links.service?.replace(/[^A-Za-z0-9_-]/g,"");if(![...i&&a?[`/var/www/${i}/${a}`,`/srv/${i}/${a}`]:[],...e.mounts.map((d)=>d.target).filter((d)=>d.startsWith("/"))].some((d)=>n===d||n.startsWith(`${d.replace(/\/$/,"")}/`)))return{ok:!1,error:"Path is outside this service’s owned roots."};return{ok:!0,path:n}}function ID(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,a)=>a.length-i.length).find((i)=>t===i||t.startsWith(`${i.replace(/\/$/,"")}/`))}var nR={process:["ps","-eo","pid,ppid,user,%cpu,%mem,etime,command","--sort=-%cpu"],sockets:["ss","-lntup"],filesystem:["df","-h"]};class _r{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?.()??ir(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??nr({config:this.config}),a=await i.findComputeTargets({slug:this.config.project.slug,environment:this.environment,role:"app"}),s=_D(a,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=RD(t,e.action);if(!i)return{...r,ok:!1,error:`${e.action} is not implemented for ${t.provider}.`};let a=await this.remote(t,["set -uo pipefail",...i],60,`ts-cloud runtime:${e.action}`).catch(bo);return{...r,ok:a.success,command:i[0],stdout:Ui(a.perInstance?.[0]?.output??""),stderr:Ui(a.perInstance?.[0]?.error??a.error??""),error:a.success?void 0:a.error??"Runtime operation failed."}}if(t.provider==="ecs"){let i=SD(t);if(!i)return{...r,ok:!1,error:"ECS cluster or service identity is unavailable."};let a=this.dependencies.ecs??new ko(this.region,this.profile);if(e.action==="scale"){let s=fD(e.replicas,t.desiredReplicas??1);return await a.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 a.scaleService(i.cluster,i.service,s),{...r,ok:!0,command:`ecs scale ${t.name} ${s}`}}if(e.action==="restart"||e.action==="redeploy")return await a.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&&nR[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??"",a;if(r.provider==="docker"&&Oo.test(i)){let d=e.command?.trim()||n.map(Gt).join(" ");a=`docker exec ${i} sh -lc ${Gt(d)}`}else if(r.provider==="systemd"&&vo.test(i)&&e.preset)a=e.preset==="process"?`systemctl status ${i} --no-pager --full`:nR[e.preset].map(Gt).join(" ");if(!a)return{...t,ok:!1,error:"Exec target identity is invalid or unsupported."};let s=await this.remote(r,["set -uo pipefail",a],60,"ts-cloud runtime:exec").catch(bo);return{...t,ok:s.success,command:a,stdout:Ui(s.perInstance?.[0]?.output??""),stderr:Ui(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:a,providerId:s}=r,c=`sh -c ${Gt('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 ${Gt(i)} ${$a} ${Gt(a)}`,o=n.provider==="docker"?`docker exec ${s} ${c}`:c,g=await this.remote(n,[o],30,"ts-cloud runtime:file-read").catch(bo);if(!g.success)return{...t,ok:!1,error:g.error??g.perInstance?.[0]?.error??"File read failed."};let h=g.perInstance?.[0]?.output??"",_=/__TSCLOUD_SIZE__=(\d+)\r?\n/.exec(h);if(!_)return{...t,ok:!1,error:"The remote file response was invalid."};let R=Number(_[1]),E=h.slice((_.index??0)+_[0].length).replace(/\s+/g,"");if(Buffer.from(E,"base64").byteLength>$a)return{...t,ok:!1,error:"The remote file exceeded the transfer limit."};return{...t,ok:!0,contentBase64:E,size:R,truncated:R>$a}}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>$a)return{...t,ok:!1,error:`File uploads are limited to ${$a} bytes.`};let{workload:i,path:a,root:s,providerId:d}=r,o=`sh -c ${Gt('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 ${Gt(a)} ${Gt(s)}`,g=i.provider==="docker"?`printf %s ${Gt(e.contentBase64)} | docker exec -i ${d} ${o}`:`printf %s ${Gt(e.contentBase64)} | ${o}`,h=await this.remote(i,[g],30,"ts-cloud runtime:file-write").catch(bo);return{...t,ok:h.success,size:n.byteLength,truncated:!1,error:h.success?void 0:h.error??h.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=pD(t,e.path);if(!r.ok)return{error:r.error};let n=ID(t,r.path),i=t.links.providerId??"";if(!n||t.provider==="systemd"&&!vo.test(i)||t.provider==="docker"&&!Oo.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 g=this.dependencies.logs??new oi(this.region,this.profile),h=r.config.logGroups,_=r.provider==="lambda"?`/aws/lambda/${r.name}`:Array.isArray(h)&&typeof h[0]==="string"?h[0]:void 0;if(!_)throw Error("The ECS task definition does not declare an awslogs group.");let R=await g.filterLogEvents({logGroupName:_,startTime:t.since?.getTime(),limit:n}),E=(R.events??[]).slice(0,n).map((y)=>({timestamp:y.timestamp==null?void 0:new Date(y.timestamp).toISOString(),message:Ui(String(y.message??""))}));return{workloadId:e,provider:r.provider,lines:E,nextCursor:R.nextToken,truncated:(R.events?.length??0)>=n}}let i=r.links.providerId??"",a=t.since&&Number.isFinite(t.since.getTime())?t.since:void 0,s=r.provider==="systemd"&&vo.test(i)?`journalctl -u ${i} --no-pager -n ${n} -o short-iso${a?` --since ${Gt(a.toISOString())}`:""}`:r.provider==="docker"&&Oo.test(i)?`docker logs --timestamps --tail ${n}${a?` --since ${Math.floor(a.getTime()/1000)}`:""} ${i} 2>&1`:void 0;if(!s)throw Error("Log target identity is invalid.");let d=await this.remote(r,[s],30,"ts-cloud runtime:logs");if(!d.success)throw Error(d.error??d.perInstance?.[0]?.error??"Log read failed.");let c=Ui(d.perInstance?.[0]?.output??""),o=c.split(`
147
+ `).filter(Boolean).slice(-n).map((g)=>{let h=/^(\d{4}-\d{2}-\d{2}T\S+)\s+(.*)$/.exec(g);return{timestamp:h?.[1],message:h?.[2]??g}});return{workloadId:e,provider:r.provider,lines:o,truncated:c.includes("[output truncated]")||o.length>=n}}}import{randomUUID as mD}from"node:crypto";class Xl{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:mD(),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),a=i.byteLength>this.maxBufferBytes?i.subarray(i.byteLength-this.maxBufferBytes).toString("utf8"):t,s={cursor:++n.cursor,stream:r,data:a,at:this.now().toISOString()};n.chunks.push(s),n.bufferedBytes+=Buffer.byteLength(a),n.updatedAt=s.at;while(n.bufferedBytes>this.maxBufferBytes&&n.chunks.length>1){let d=n.chunks.shift(),c=Buffer.byteLength(d.data);n.bufferedBytes-=c,n.droppedBytes+=c}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 ED}from"node:crypto";var rg={info:0,low:1,medium:2,high:3,critical:4},ng={record:0,warn:1,block:2},iR=new Set(["skipped","unavailable","unsupported","stale"]);function Ve(e){return typeof e==="string"?e:void 0}function hn(e,t){try{return JSON.parse(String(e))}catch{return t}}function ar(e){return JSON.stringify(Oe(e))}function yD(e){if(!e)return;return String(Oe(e,2000))}function ql(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:Ve(e.project_id),environmentId:Ve(e.environment_id),resourceId:Ve(e.resource_id),releaseId:Ve(e.release_id),scannerId:String(e.scanner_id),scannerVersion:String(e.scanner_version),status:String(e.status),error:Ve(e.error),metadata:hn(e.metadata,{}),findingsCount:Number(e.findings_count),startedAt:String(e.started_at),completedAt:String(e.completed_at),durationMs:Number(e.duration_ms)}}function aR(e){return{id:String(e.id),fingerprint:String(e.fingerprint),organizationId:String(e.organization_id),projectId:Ve(e.project_id),environmentId:Ve(e.environment_id),resourceId:Ve(e.resource_id),releaseId:Ve(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:hn(e.evidence,{}),remediation:Ve(e.remediation),subject:String(e.subject),status:String(e.status),ownerActorId:Ve(e.owner_actor_id),recurrenceCount:Number(e.recurrence_count),firstSeenAt:String(e.first_seen_at),lastSeenAt:String(e.last_seen_at),resolvedAt:Ve(e.resolved_at),updatedAt:String(e.updated_at)}}function eg(e){return{id:String(e.id),organizationId:String(e.organization_id),environmentId:Ve(e.environment_id),name:String(e.name),rules:hn(e.rules,[]),requiredScanners:hn(e.required_scanners,[]),scannerFailMode:String(e.scanner_fail_mode),enabled:Number(e.enabled)===1,version:Number(e.version),createdByActorId:Ve(e.created_by_actor_id),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function sR(e,t){let r=Ve(e.revoked_at),n=String(e.expires_at);return{id:String(e.id),findingId:String(e.finding_id),policyId:Ve(e.policy_id),reason:String(e.reason),referenceUrl:Ve(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 tg(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:Ve(e.environment_id),releaseId:String(e.release_id),kind:String(e.kind),format:String(e.format),digest:String(e.digest),summary:hn(e.summary,{}),content:Ve(e.content),sensitive:Number(e.sensitive)===1,createdAt:String(e.created_at)}}function oR(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:String(e.environment_id),operationId:Ve(e.operation_id),policyId:String(e.policy_id),policyVersion:Number(e.policy_version),outcome:String(e.outcome),scannerVersions:hn(e.scanner_versions,{}),findingIds:hn(e.finding_ids,[]),waiverIds:hn(e.waiver_ids,[]),explanation:String(e.explanation),createdAt:String(e.created_at)}}function wD(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 ED("sha256").update(r).digest("hex")}function dR(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 cR(e){if(!e.length)throw Error("A security policy needs at least one rule");return e.map((t)=>{if(!(t.minimumSeverity in rg))throw Error(`Unknown security severity: ${t.minimumSeverity}`);if(!(t.action in ng))throw Error(`Unknown security policy action: ${t.action}`);return{minimumSeverity:t.minimumSeverity,action:t.action,...t.scannerId?{scannerId:t.scannerId.trim()}:{}}})}class Ca{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??[],a=this.idFn(),s=new Set,d=[];return this.controlPlane.transaction(()=>{this.run(`INSERT INTO security_scan_runs
148
+ (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)
149
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[a,e.organizationId,e.projectId??null,e.environmentId??null,e.resourceId??null,e.releaseId??null,e.scannerId.trim(),e.scannerVersion.trim(),e.status,yD(e.error)??null,ar(e.metadata??{}),i.length,r,t,Math.max(0,Math.floor(n))]);for(let c of i){let o={...c,organizationId:e.organizationId,projectId:c.projectId??e.projectId,environmentId:c.environmentId??e.environmentId,resourceId:c.resourceId??e.resourceId,releaseId:c.releaseId??e.releaseId},g=o.fingerprint?.trim()||wD(e.scannerId,o);s.add(g);let h=this.controlPlane.database.query("SELECT * FROM security_findings WHERE fingerprint = ?").get(g),_=h?this.controlPlane.database.query("SELECT * FROM security_waivers WHERE finding_id = ? AND revoked_at IS NULL AND expires_at > ? ORDER BY expires_at DESC LIMIT 1").get(String(h.id),t):void 0;if(h){let R=String(h.status)==="resolved"?Number(h.recurrence_count)+1:Number(h.recurrence_count),E=_?"waived":String(h.status)==="acknowledged"?"acknowledged":"open";this.run(`UPDATE security_findings SET scan_run_id = ?, scanner_version = ?, severity = ?, title = ?, description = ?, evidence = ?, remediation = ?,
150
+ status = ?, recurrence_count = ?, last_seen_at = ?, resolved_at = NULL, updated_at = ? WHERE id = ?`,[a,e.scannerVersion,o.severity,o.title.trim(),o.description.trim(),ar(o.evidence??{}),o.remediation?.trim()||null,E,R,t,t,String(h.id)]),d.push(this.getFinding(String(h.id)))}else{let R=this.idFn();this.run(`INSERT INTO security_findings
151
+ (id, fingerprint, organization_id, project_id, environment_id, resource_id, release_id, scan_run_id, scanner_id, scanner_version, rule_id,
152
+ severity, title, description, evidence, remediation, subject, status, first_seen_at, last_seen_at, updated_at)
153
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'open', ?, ?, ?)`,[R,g,o.organizationId,o.projectId??null,o.environmentId??null,o.resourceId??null,o.releaseId??null,a,e.scannerId,e.scannerVersion,o.ruleId.trim(),o.severity,o.title.trim(),o.description.trim(),ar(o.evidence??{}),o.remediation?.trim()||null,o.subject.trim(),t,t,t]),d.push(this.getFinding(R))}}if(e.status==="passed"||e.status==="failed"){let c=this.controlPlane.database.query(`SELECT * FROM security_findings WHERE organization_id = ? AND scanner_id = ?
154
+ AND project_id IS ? AND environment_id IS ? AND resource_id IS ? AND release_id IS ? AND status != 'resolved'`).all(e.organizationId,e.scannerId,e.projectId??null,e.environmentId??null,e.resourceId??null,e.releaseId??null);for(let o of c){if(s.has(String(o.fingerprint)))continue;this.run("UPDATE security_findings SET status = 'resolved', resolved_at = ?, updated_at = ? WHERE id = ?",[t,t,String(o.id)]),this.controlPlane.appendEvent({organizationId:e.organizationId,projectId:e.projectId,resourceId:e.resourceId,type:"security.finding.resolved",payload:{findingId:String(o.id),scannerId:e.scannerId,reason:"not-observed"}})}}this.controlPlane.appendEvent({organizationId:e.organizationId,projectId:e.projectId,resourceId:e.resourceId,type:"security.scan.completed",level:e.status==="failed"||iR.has(e.status)?"warning":"info",payload:{scanRunId:a,scannerId:e.scannerId,scannerVersion:e.scannerVersion,status:e.status,findingsCount:i.length,durationMs:n}})}),{run:this.getScanRun(a),findings:d.map((c)=>this.getFinding(c.id))}}getScanRun(e){let t=this.controlPlane.database.query("SELECT * FROM security_scan_runs WHERE id = ?").get(e);return t?ql(t):void 0}listScanRuns(e){return this.controlPlane.database.query("SELECT * FROM security_scan_runs WHERE organization_id = ? AND project_id IS ? AND environment_id IS ? ORDER BY completed_at DESC, id DESC LIMIT ?").all(e.organizationId,e.projectId??null,e.environmentId??null,Math.min(500,Math.max(1,e.limit??100))).map(ql)}getFinding(e){let t=this.controlPlane.database.query("SELECT * FROM security_findings WHERE id = ?").get(e);return t?aR(t):void 0}listFindings(e){this.expireWaivers();let t=["organization_id = ?"],r=[e.organizationId];if(e.projectId)t.push("project_id = ?"),r.push(e.projectId);if(e.environmentId)t.push("environment_id = ?"),r.push(e.environmentId);if(e.status)t.push("status = ?"),r.push(e.status);if(e.severity)t.push("severity = ?"),r.push(e.severity);return r.push(Math.min(1000,Math.max(1,e.limit??250))),this.controlPlane.database.query(`SELECT * FROM security_findings WHERE ${t.join(" AND ")} ORDER BY CASE severity WHEN 'critical' THEN 4 WHEN 'high' THEN 3 WHEN 'medium' THEN 2 WHEN 'low' THEN 1 ELSE 0 END DESC, last_seen_at DESC LIMIT ?`).all(...r).map(aR)}assignFinding(e,t,r){let n=this.getFinding(e);if(!n)throw Error("Security finding was not found");if(t&&!this.controlPlane.getActor(t))throw Error("Finding owner was not found");return this.run("UPDATE security_findings SET owner_actor_id = ?, updated_at = ? WHERE id = ?",[t??null,this.now(),e]),this.controlPlane.appendEvent({organizationId:n.organizationId,projectId:n.projectId,resourceId:n.resourceId,actorId:r,type:"security.finding.assigned",payload:{findingId:e,ownerActorId:t??null}}),this.getFinding(e)}acknowledgeFinding(e,t){let r=this.getFinding(e);if(!r)throw Error("Security finding was not found");if(r.status==="resolved")throw Error("A resolved finding cannot be acknowledged");return this.run("UPDATE security_findings SET status = 'acknowledged', updated_at = ? WHERE id = ?",[this.now(),e]),this.controlPlane.appendEvent({organizationId:r.organizationId,projectId:r.projectId,resourceId:r.resourceId,actorId:t,type:"security.finding.acknowledged",payload:{findingId:e}}),this.getFinding(e)}addComment(e){let t=this.getFinding(e.findingId);if(!t)throw Error("Security finding was not found");let r=e.body.trim();if(r.length<2||r.length>4000)throw Error("Finding comments must contain 2-4,000 characters");let n=dR(e.referenceUrl),i=this.idFn(),a=this.now();return this.run("INSERT INTO security_finding_comments (id, finding_id, actor_id, body, reference_url, created_at) VALUES (?, ?, ?, ?, ?, ?)",[i,e.findingId,e.actorId,r,n??null,a]),this.controlPlane.appendEvent({organizationId:t.organizationId,projectId:t.projectId,resourceId:t.resourceId,actorId:e.actorId,type:"security.finding.commented",payload:{findingId:e.findingId,commentId:i,referenceUrl:n??null}}),{id:i,findingId:e.findingId,actorId:e.actorId,body:r,referenceUrl:n,createdAt:a}}listComments(e){return this.controlPlane.database.query("SELECT * FROM security_finding_comments WHERE finding_id = ? ORDER BY created_at, id").all(e).map((t)=>({id:String(t.id),findingId:String(t.finding_id),actorId:String(t.actor_id),body:String(t.body),referenceUrl:Ve(t.reference_url),createdAt:String(t.created_at)}))}createWaiver(e){let t=this.getFinding(e.findingId);if(!t)throw Error("Security finding was not found");let r=e.reason.trim();if(r.length<8||r.length>1000)throw Error("A waiver reason must contain 8-1,000 characters");let n=this.now(),i=new Date(e.expiresAt);if(!Number.isFinite(i.getTime())||i.toISOString()<=n)throw Error("A waiver must have a future expiry");if(i.getTime()-new Date(n).getTime()>31536000000)throw Error("A waiver cannot last longer than one year");let a=e.policyId?this.getPolicy(e.policyId):void 0;if(e.policyId&&(!a||a.organizationId!==t.organizationId))throw Error("Waiver policy does not match the finding organization");let s=this.idFn(),d=dR(e.referenceUrl);return this.controlPlane.transaction(()=>{this.run(`INSERT INTO security_waivers (id, finding_id, policy_id, reason, reference_url, created_by_actor_id, expires_at, created_at, updated_at)
155
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[s,t.id,e.policyId??null,r,d??null,e.actorId,i.toISOString(),n,n]),this.run("UPDATE security_findings SET status = 'waived', updated_at = ? WHERE id = ?",[n,t.id]),this.controlPlane.appendEvent({organizationId:t.organizationId,projectId:t.projectId,resourceId:t.resourceId,actorId:e.actorId,type:"security.waiver.created",level:"warning",payload:{waiverId:s,findingId:t.id,policyId:e.policyId??null,reason:r,expiresAt:i.toISOString(),referenceUrl:d??null}})}),this.getWaiver(s)}revokeWaiver(e,t){let r=this.getWaiver(e);if(!r)throw Error("Security waiver was not found");if(r.revokedAt)return r;let n=this.getFinding(r.findingId),i=this.now();return this.controlPlane.transaction(()=>{this.run("UPDATE security_waivers SET revoked_at = ?, updated_at = ? WHERE id = ?",[i,i,e]),this.run("UPDATE security_findings SET status = 'open', updated_at = ? WHERE id = ? AND status = 'waived'",[i,r.findingId]),this.controlPlane.appendEvent({organizationId:n.organizationId,projectId:n.projectId,resourceId:n.resourceId,actorId:t,type:"security.waiver.revoked",level:"warning",payload:{waiverId:e,findingId:r.findingId}})}),this.getWaiver(e)}getWaiver(e){let t=this.controlPlane.database.query("SELECT * FROM security_waivers WHERE id = ?").get(e);return t?sR(t,this.now()):void 0}listWaivers(e){return(e?this.controlPlane.database.query("SELECT * FROM security_waivers WHERE finding_id = ? ORDER BY created_at DESC").all(e):this.controlPlane.database.query("SELECT * FROM security_waivers ORDER BY created_at DESC").all()).map((r)=>sR(r,this.now()))}expireWaivers(){let e=this.now(),t=this.controlPlane.database.query(`SELECT w.id AS waiver_id, f.* FROM security_waivers w JOIN security_findings f ON f.id = w.finding_id
156
+ WHERE w.revoked_at IS NULL AND w.expires_at <= ? AND f.status = 'waived'`).all(e);for(let r of t)this.run("UPDATE security_findings SET status = 'open', updated_at = ? WHERE id = ?",[e,String(r.id)]),this.controlPlane.appendEvent({organizationId:String(r.organization_id),projectId:Ve(r.project_id),resourceId:Ve(r.resource_id),type:"security.waiver.expired",level:"warning",payload:{waiverId:String(r.waiver_id),findingId:String(r.id)}});return t.length}createPolicy(e){let t=e.name.trim();if(!t)throw Error("Security policy name is required");let r=cR(e.rules),n=this.idFn(),i=this.now(),a=[...new Set((e.requiredScanners??[]).map((s)=>s.trim()).filter(Boolean))].sort();return this.run(`INSERT INTO security_policies (id, organization_id, environment_id, name, rules, required_scanners, scanner_fail_mode, created_by_actor_id, created_at, updated_at)
157
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n,e.organizationId,e.environmentId??null,t,ar(r),ar(a),e.scannerFailMode,e.actorId??null,i,i]),this.controlPlane.appendEvent({organizationId:e.organizationId,actorId:e.actorId,type:"security.policy.created",payload:{policyId:n,environmentId:e.environmentId??null,scannerFailMode:e.scannerFailMode,requiredScanners:a,rules:Oe(r)}}),this.getPolicy(n)}updatePolicy(e,t,r){let n=this.getPolicy(e);if(!n||n.version!==t)throw Error(`Security policy ${e} changed since version ${t}`);let i=r.rules?cR(r.rules):n.rules,a=r.requiredScanners?[...new Set(r.requiredScanners.map((c)=>c.trim()).filter(Boolean))].sort():n.requiredScanners,s=this.now();if(this.controlPlane.database.run("UPDATE security_policies SET name = ?, rules = ?, required_scanners = ?, scanner_fail_mode = ?, enabled = ?, version = version + 1, updated_at = ? WHERE id = ? AND version = ?",[r.name?.trim()||n.name,ar(i),ar(a),r.scannerFailMode??n.scannerFailMode,r.enabled??n.enabled?1:0,s,e,t]).changes!==1)throw Error(`Security policy ${e} changed since version ${t}`);return this.controlPlane.appendEvent({organizationId:n.organizationId,actorId:r.actorId,type:"security.policy.updated",payload:{policyId:e,fromVersion:t,toVersion:t+1}}),this.getPolicy(e)}getPolicy(e){let t=this.controlPlane.database.query("SELECT * FROM security_policies WHERE id = ?").get(e);return t?eg(t):void 0}listPolicies(e){return this.controlPlane.database.query("SELECT * FROM security_policies WHERE organization_id = ? ORDER BY environment_id, name").all(e).map(eg)}evaluateGate(e){this.expireWaivers();let t=e.policyId?this.getPolicy(e.policyId):this.controlPlane.database.query(`SELECT * FROM security_policies WHERE organization_id = ? AND enabled = 1 AND (environment_id = ? OR environment_id IS NULL)
158
+ ORDER BY CASE WHEN environment_id = ? THEN 0 ELSE 1 END, updated_at DESC LIMIT 1`).get(e.organizationId,e.environmentId,e.environmentId),r=t&&"rules"in t&&Array.isArray(t.rules)?t:t?eg(t):void 0;if(!r||!r.enabled)throw Error("No enabled security policy applies to this environment");let n=this.listFindings({organizationId:e.organizationId,projectId:e.projectId,environmentId:e.environmentId,limit:1000}).filter((F)=>F.status!=="resolved"),i=new Map;for(let F of n){let J=this.listWaivers(F.id).find((Z)=>Z.state==="active"&&(!Z.policyId||Z.policyId===r.id));if(J)i.set(F.id,J)}let a=(F)=>r.rules.filter((J)=>(!J.scannerId||J.scannerId===F.scannerId)&&rg[F.severity]>=rg[J.minimumSeverity]).reduce((J,Z)=>ng[Z.action]>ng[J]?Z.action:J,"record"),s=n.filter((F)=>!i.has(F.id)&&a(F)==="block"),d=n.filter((F)=>!i.has(F.id)&&a(F)==="warn"),c=this.controlPlane.database.query(`SELECT run.* FROM security_scan_runs run
159
+ WHERE run.organization_id = ? AND run.project_id = ? AND run.environment_id = ?
160
+ AND run.id = (SELECT candidate.id FROM security_scan_runs candidate
161
+ WHERE candidate.organization_id = run.organization_id AND candidate.project_id = run.project_id
162
+ AND candidate.environment_id = run.environment_id AND candidate.scanner_id = run.scanner_id
163
+ ORDER BY candidate.completed_at DESC, candidate.rowid DESC LIMIT 1)`).all(e.organizationId,e.projectId,e.environmentId),o=e.staleAfterMs??86400000,g=this.nowFn().getTime(),h=c.map(ql).map((F)=>g-new Date(F.completedAt).getTime()>o?{...F,status:"stale"}:F),_=new Set(h.map((F)=>F.scannerId)),R=r.requiredScanners.filter((F)=>!_.has(F)).map((F)=>({id:`missing:${F}`,organizationId:e.organizationId,projectId:e.projectId,environmentId:e.environmentId,scannerId:F,scannerVersion:"unavailable",status:"unavailable",metadata:{},findingsCount:0,startedAt:this.now(),completedAt:this.now(),durationMs:0})),E=[...h,...R],y=E.filter((F)=>r.requiredScanners.includes(F.scannerId)&&iR.has(F.status)),$=Object.fromEntries(E.map((F)=>[F.scannerId,F.scannerVersion])),b=r.scannerFailMode==="closed"&&y.length>0,z=s.length||b?"block":d.length||y.length?"warn":"allow",C=[];if(s.length)C.push(`${s.length} finding${s.length===1?"":"s"} blocked by policy`);if(d.length)C.push(`${d.length} warning${d.length===1?"":"s"} require review`);if(y.length)C.push(`${y.length} scanner${y.length===1?"":"s"} ${r.scannerFailMode==="closed"?"failed closed":"failed open"}`);if(i.size)C.push(`${i.size} active time-limited waiver${i.size===1?"":"s"}`);if(!C.length)C.push("All recorded checks satisfy policy");let B=this.idFn(),N=this.now();return this.run(`INSERT INTO security_deploy_decisions
164
+ (id, organization_id, project_id, environment_id, operation_id, policy_id, policy_version, outcome, scanner_versions, finding_ids, waiver_ids, explanation, created_at)
165
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[B,e.organizationId,e.projectId,e.environmentId,e.operationId??null,r.id,r.version,z,ar($),ar([...s,...d].map((F)=>F.id)),ar([...i.values()].map((F)=>F.id)),C.join("; "),N]),this.controlPlane.appendEvent({organizationId:e.organizationId,projectId:e.projectId,operationId:e.operationId,type:"security.deploy.decision",level:z==="block"?"error":z==="warn"?"warning":"info",payload:{decisionId:B,outcome:z,policyId:r.id,policyVersion:r.version,scannerVersions:$,blockerIds:s.map((F)=>F.id),waiverIds:[...i.values()].map((F)=>F.id),explanation:C.join("; ")}}),this.getDecision(B)}getDecision(e){let t=this.controlPlane.database.query("SELECT * FROM security_deploy_decisions WHERE id = ?").get(e);return t?oR(t):void 0}listDecisions(e,t=100){return this.controlPlane.database.query("SELECT * FROM security_deploy_decisions WHERE environment_id = ? ORDER BY created_at DESC LIMIT ?").all(e,Math.min(500,Math.max(1,t))).map(oR)}addReleaseArtifact(e){let t=this.controlPlane.database.query("SELECT * FROM release_security_artifacts WHERE release_id = ? AND kind = ? AND digest = ?").get(e.releaseId,e.kind,e.digest);if(t)return tg(t);let r=this.idFn(),n=this.now();return this.run(`INSERT INTO release_security_artifacts
166
+ (id, organization_id, project_id, environment_id, release_id, kind, format, digest, summary, content, sensitive, created_at)
167
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[r,e.organizationId,e.projectId,e.environmentId??null,e.releaseId,e.kind,e.format,e.digest,ar(e.summary),e.content??null,e.sensitive?1:0,n]),this.controlPlane.appendEvent({organizationId:e.organizationId,projectId:e.projectId,type:"security.release_artifact.created",payload:{artifactId:r,releaseId:e.releaseId,kind:e.kind,format:e.format,digest:e.digest,sensitive:e.sensitive}}),tg(this.controlPlane.database.query("SELECT * FROM release_security_artifacts WHERE id = ?").get(r))}listReleaseArtifacts(e,t=!1){return this.controlPlane.database.query("SELECT * FROM release_security_artifacts WHERE release_id = ? ORDER BY created_at, kind").all(e).map(tg).map((r)=>r.sensitive&&!t?{...r,content:void 0}:r)}summary(e,t,r){let n=this.listFindings({organizationId:e,projectId:t,environmentId:r,limit:1000}),i=this.listScanRuns({organizationId:e,projectId:t,environmentId:r,limit:1000}),a={info:0,low:0,medium:0,high:0,critical:0};for(let d of n)if(d.status==="open"||d.status==="acknowledged")a[d.severity]++;let s={passed:0,failed:0,skipped:0,unavailable:0,unsupported:0,stale:0};for(let d of i)s[d.status]++;return{open:a,waived:n.filter((d)=>d.status==="waived").length,resolved:n.filter((d)=>d.status==="resolved").length,checks:s,lastScannedAt:i[0]?.completedAt}}exportPosture(e){let t=this.controlPlane.listProjects().filter((r)=>r.organizationId===e);return Oe({format:"ts-cloud-security-posture",version:1,exportedAt:this.now(),organizationId:e,policies:this.listPolicies(e),findings:this.listFindings({organizationId:e,limit:1000}),waivers:this.listWaivers().filter((r)=>this.getFinding(r.findingId)?.organizationId===e),scans:t.flatMap((r)=>this.listScanRuns({organizationId:e,projectId:r.id,limit:1000})),decisions:t.flatMap((r)=>this.controlPlane.listEnvironments(r.id).flatMap((n)=>this.listDecisions(n.id,1000)))})}}import{existsSync as AD,readdirSync as PD,readFileSync as DD,statSync as $D}from"node:fs";import{extname as CD,join as kD,relative as bD}from"node:path";var lR=[{name:"AWS Access Key ID",pattern:/(?:^|[^A-Z0-9])((AKIA|ABIA|ACCA|ASIA)[A-Z0-9]{16})(?:[^A-Z0-9]|$)/g,severity:"critical",description:"AWS Access Key ID detected"},{name:"AWS Secret Access Key",pattern:/(?:aws_secret_access_key|aws_secret_key|secret_access_key|secretAccessKey)['"]?\s*[=:]\s*['"]?([A-Za-z0-9/+=]{40})['"]?/gi,severity:"critical",description:"AWS Secret Access Key detected"},{name:"AWS Secret Key (Generic)",pattern:/(?:^|['"`:=\s])([A-Za-z0-9/+=]{40})(?:['"`\s]|$)/g,severity:"high",description:"Potential AWS Secret Key (40-char base64)"},{name:"Generic API Key",pattern:/(?:api[_-]?key|apikey|api[_-]?secret)\s*[=:]\s*['"]?([A-Za-z0-9_\-]{20,})['"]?/gi,severity:"high",description:"Generic API key detected"},{name:"RSA Private Key",pattern:/-----BEGIN RSA PRIVATE KEY-----/g,severity:"critical",description:"RSA private key detected"},{name:"OpenSSH Private Key",pattern:/-----BEGIN OPENSSH PRIVATE KEY-----/g,severity:"critical",description:"OpenSSH private key detected"},{name:"EC Private Key",pattern:/-----BEGIN EC PRIVATE KEY-----/g,severity:"critical",description:"EC private key detected"},{name:"PGP Private Key",pattern:/-----BEGIN PGP PRIVATE KEY BLOCK-----/g,severity:"critical",description:"PGP private key detected"},{name:"GitHub Token",pattern:/(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9_]{36,}/g,severity:"critical",description:"GitHub personal access token detected"},{name:"GitHub OAuth",pattern:/github[_-]?oauth[_-]?token\s*[=:]\s*['"]?([A-Za-z0-9_]{40})['"]?/gi,severity:"critical",description:"GitHub OAuth token detected"},{name:"Slack Token",pattern:/xox[baprs]-[0-9]{10,13}-[0-9]{10,13}[a-zA-Z0-9-]*/g,severity:"critical",description:"Slack token detected"},{name:"Slack Webhook",pattern:/https:\/\/hooks\.slack\.com\/services\/T[A-Z0-9]+\/B[A-Z0-9]+\/[A-Za-z0-9]+/g,severity:"high",description:"Slack webhook URL detected"},{name:"Discord Webhook",pattern:/https:\/\/discord(?:app)?\.com\/api\/webhooks\/[0-9]+\/[A-Za-z0-9_-]+/g,severity:"high",description:"Discord webhook URL detected"},{name:"JWT Token",pattern:/eyJ[A-Za-z0-9_-]*\.eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]*/g,severity:"high",description:"JWT token detected"},{name:"Google API Key",pattern:/AIza[0-9A-Za-z_-]{35}/g,severity:"critical",description:"Google API key detected"},{name:"Google OAuth ID",pattern:/[0-9]+-[A-Za-z0-9_]{32}\.apps\.googleusercontent\.com/g,severity:"high",description:"Google OAuth client ID detected"},{name:"Firebase API Key",pattern:/(?:firebase[_-]?api[_-]?key)\s*[=:]\s*['"]?([A-Za-z0-9_-]{39})['"]?/gi,severity:"critical",description:"Firebase API key detected"},{name:"Cloudflare API Token",pattern:/(?:cloudflare[_-]?api[_-]?token|cf[_-]?api[_-]?token)\s*[=:]\s*['"]?([A-Za-z0-9_-]{40})['"]?/gi,severity:"critical",description:"Cloudflare API token detected"},{name:"Azure Client Secret",pattern:/(?:azure[_-]?client[_-]?secret|client[_-]?secret)\s*[=:]\s*['"]?([A-Za-z0-9~._-]{34,})['"]?/gi,severity:"critical",description:"Azure client secret detected"},{name:"Heroku API Key",pattern:/(?:heroku[_-]?api[_-]?key)\s*[=:]\s*['"]?([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})['"]?/gi,severity:"critical",description:"Heroku API key detected"},{name:"Database Connection String",pattern:/(?:mysql|postgres|postgresql|mongodb|redis|mongodb\+srv):\/\/[^:]+:[^@]+@[^/\s]+/gi,severity:"critical",description:"Database connection string with credentials detected"},{name:"Database Password",pattern:/(?:db[_-]?password|database[_-]?password|mysql[_-]?password|postgres[_-]?password)\s*[=:]\s*['"]?([^'"\s]{8,})['"]?/gi,severity:"critical",description:"Database password detected"},{name:"Stripe API Key",pattern:/(?:sk|pk)_(?:test|live)_[0-9a-zA-Z]{24,}/g,severity:"critical",description:"Stripe API key detected"},{name:"PayPal Client ID",pattern:/(?:paypal[_-]?client[_-]?id)\s*[=:]\s*['"]?([A-Za-z0-9_-]{80})['"]?/gi,severity:"high",description:"PayPal client ID detected"},{name:"Square Access Token",pattern:/sq0[a-z]{3}-[0-9A-Za-z_-]{22,}/g,severity:"critical",description:"Square access token detected"},{name:"Twilio API Key",pattern:/SK[a-f0-9]{32}/g,severity:"critical",description:"Twilio API key detected"},{name:"SendGrid API Key",pattern:/SG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}/g,severity:"critical",description:"SendGrid API key detected"},{name:"Mailgun API Key",pattern:/key-[0-9a-zA-Z]{32}/g,severity:"critical",description:"Mailgun API key detected"},{name:"Password in Code",pattern:/(?:password|passwd|pwd)\s*[=:]\s*['"]([^'"]{8,})['"](?!\s*[,\]])/gi,severity:"high",description:"Hardcoded password detected"},{name:"Secret/Token Assignment",pattern:/(?:secret|token|auth[_-]?token|access[_-]?token)\s*[=:]\s*['"]([A-Za-z0-9_\-/+=]{16,})['"](?!\s*[,\]])/gi,severity:"high",description:"Hardcoded secret or token detected"},{name:"NPM Token",pattern:/(?:npm[_-]?token)\s*[=:]\s*['"]?([A-Za-z0-9_-]{36})['"]?/gi,severity:"critical",description:"NPM token detected"},{name:"SSH Private Key Path Exposed",pattern:/~\/\.ssh\/id_[a-z]+|\/home\/[^/]+\/\.ssh\/id_[a-z]+/g,severity:"medium",description:"SSH private key path exposed"},{name:"Env Variable with Secret",pattern:/(?:process\.env\.)((?=[A-Z_]*(?:SECRET|KEY|TOKEN|PASSWORD|CREDENTIAL|AUTH))[A-Z_]+)\s*(?:===?\s*['"]([^'"]+)['"])?/g,severity:"medium",description:"Environment variable containing secret may be exposed"}],vD=[".js",".jsx",".ts",".tsx",".mjs",".cjs",".vue",".svelte",".html",".htm",".css",".scss",".less",".json",".yaml",".yml",".toml",".xml",".env",".config",".conf"],OD=["node_modules",".git",".svn",".hg","dist","build","coverage",".nyc_output","__pycache__",".pytest_cache","vendor",".idea",".vscode",".turbo",".next",".nuxt","framework.bak","pantry",".pantry","tests","test","__tests__","spec","__mocks__",".github",".gitlab",".circleci"],BD=["package-lock.json","yarn.lock","pnpm-lock.yaml","bun.lockb","bun.lock","*.min.js","*.min.css","*.map","*.d.ts","*.test.ts","*.test.js","*.spec.ts","*.spec.js",".env",".env.*"];class ka{patterns;excludeDirs;excludeFiles;maxFileSize;constructor(e){this.patterns=[...lR,...e?.customPatterns||[]],this.excludeDirs=[...OD,...e?.excludeDirs||[]],this.excludeFiles=[...BD,...e?.excludeFiles||[]],this.maxFileSize=e?.maxFileSize||1048576}async scan(e){let t=Date.now(),r=[],n=0,{directory:i,exclude:a=[],include:s,skipPatterns:d=[]}=e,c=e.failOnSeverity||"critical";if(!AD(i))throw Error(`Directory not found: ${i}`);let o=this.getFilesToScan(i,[...this.excludeDirs,...a],s);for(let E of o){let y=bD(i,E);if(this.shouldExcludeFile(y))continue;try{if($D(E).size>this.maxFileSize)continue;let b=DD(E,"utf-8"),z=this.scanContent(b,y,d);r.push(...z),n++}catch{continue}}let g={critical:r.filter((E)=>E.pattern.severity==="critical").length,high:r.filter((E)=>E.pattern.severity==="high").length,medium:r.filter((E)=>E.pattern.severity==="medium").length,low:r.filter((E)=>E.pattern.severity==="low").length},h=["low","medium","high","critical"],_=h.indexOf(c),R=!0;for(let E=_;E<h.length;E++)if(g[h[E]]>0){R=!1;break}return{passed:R,findings:r,scannedFiles:n,duration:Date.now()-t,summary:g}}scanContent(e,t,r){let n=[],i=e.split(`
168
+ `);for(let a of this.patterns){if(r.includes(a.name))continue;a.pattern.lastIndex=0;let s;while((s=a.pattern.exec(e))!==null){let d=e.substring(0,s.index),c=d.split(`
169
+ `).length,o=d.lastIndexOf(`
170
+ `),g=s.index-o,h=i[c-1]||"";if(this.isLikelyPlaceholder(s[0],h))continue;let _=s[1]||s[0];if(a.name==="AWS Secret Key (Generic)"&&/^[a-f0-9]{40}$/i.test(_))continue;if(a.name==="AWS Secret Key (Generic)"&&!this.hasSecretCharacterDiversity(_))continue;if(a.name==="AWS Secret Key (Generic)"&&/^(?:Actions|Commands|Controllers|Handlers|Jobs|Listeners|Middleware|Models|Resources|Services)\//.test(_))continue;if(this.isLowEntropy(_))continue;n.push({file:t,line:c,column:g,match:this.maskSecret(s[0]),pattern:a,context:this.maskSecret(h.trim())})}}return n}isLikelyPlaceholder(e,t){let r=["example","placeholder","your_","YOUR_","xxx","XXX","***","test","TEST","dummy","DUMMY","fake","FAKE","sample","SAMPLE","<your","${","{{","process.env","import.meta.env","CHANGEME","TODO","FIXME"],n=e.toLowerCase(),i=t.toLowerCase();for(let s of r)if(n.includes(s.toLowerCase())||i.includes(s.toLowerCase()))return!0;let a=t.trim();if(a.startsWith("//")||a.startsWith("#")||a.startsWith("*")||a.startsWith("/*")){if(i.includes("example")||i.includes("format:")||i.includes("e.g."))return!0}return!1}isLowEntropy(e){if(e.length<8)return!1;if(new Set(e).size<8)return!0;if(/(.)\1{3,}/.test(e))return!0;return!1}hasSecretCharacterDiversity(e){let t=/[\d+=]/.test(e),r=[/[a-z]/.test(e),/[A-Z]/.test(e),/\d/.test(e),/[/+=]/.test(e)];return t&&r.filter(Boolean).length>=3}maskSecret(e){if(e.length<=8)return"*".repeat(e.length);let t=Math.min(4,Math.floor(e.length*0.2));return e.substring(0,t)+"*".repeat(e.length-t*2)+e.substring(e.length-t)}getFilesToScan(e,t,r){let n=[],i=r||vD,a=(s)=>{let d=PD(s,{withFileTypes:!0});for(let c of d){let o=kD(s,c.name);if(c.isDirectory()){if(!t.includes(c.name))a(o)}else if(c.isFile()){let g=CD(c.name).toLowerCase();if(i.includes(g)||c.name.startsWith(".env")||c.name.endsWith(".config"))n.push(o)}}};return a(e),n}shouldExcludeFile(e){let t=e.split("/").pop()||"";for(let r of this.excludeFiles)if(r.startsWith("*")){let n=r.substring(1);if(t.endsWith(n))return!0}else if(r.endsWith("*")){let n=r.substring(0,r.length-1);if(t.startsWith(n))return!0}else if(t===r)return!0;return!1}addPattern(e){this.patterns.push(e)}getPatterns(){return[...this.patterns]}}async function JD(e){return new ka().scan(e)}function TD(e){let t=[];if(t.push(`
171
+ Security Scan Results`),t.push("=".repeat(50)),t.push(`Files scanned: ${e.scannedFiles}`),t.push(`Duration: ${e.duration}ms`),t.push(""),t.push("Summary:"),t.push(` Critical: ${e.summary.critical}`),t.push(` High: ${e.summary.high}`),t.push(` Medium: ${e.summary.medium}`),t.push(` Low: ${e.summary.low}`),t.push(""),e.findings.length>0){t.push("Findings:"),t.push("-".repeat(50));for(let r of e.findings)t.push(`
172
+ [${r.pattern.severity.toUpperCase()}] ${r.pattern.name}`),t.push(` File: ${r.file}:${r.line}:${r.column}`),t.push(` Match: ${r.match}`),t.push(` Context: ${r.context}`),t.push(` Description: ${r.pattern.description}`)}return t.push(""),t.push(e.passed?"✓ Security scan passed":"✗ Security scan failed"),t.join(`
173
+ `)}function zD(e,t){return{status:"unavailable",findings:[],error:`${e.id} exceeded its ${t}ms timeout`,metadata:{timeoutMs:t}}}class Gn{posture;defaultTimeoutMs;nowFn;constructor(e,t={}){this.posture=e;this.defaultTimeoutMs=t.defaultTimeoutMs??60000,this.nowFn=t.now??(()=>new Date)}async run(e,t){let r=this.nowFn(),n=Math.max(100,e.timeoutMs??this.defaultTimeoutMs),i=new AbortController,a,s=new Promise((g)=>{a=setTimeout(()=>{i.abort(),g(zD(e,n))},n)}),d;try{d=await Promise.race([e.scan({...t,signal:i.signal}),s])}catch(g){d={status:"unavailable",findings:[],error:g instanceof Error?g.message:String(g)}}finally{if(a)clearTimeout(a)}let c=this.nowFn(),o={...t,scannerId:e.id,scannerVersion:e.version,status:d.status,findings:d.findings,metadata:d.metadata,error:d.error,startedAt:r.toISOString(),completedAt:c.toISOString(),durationMs:Math.max(0,c.getTime()-r.getTime())};return this.posture.recordScan(o)}async runAll(e,t){return Promise.all(e.map((r)=>this.run(r,t)))}}class ba{scanner;id="source-secrets";version="1.0.0";timeoutMs=30000;constructor(e=new ka){this.scanner=e}async scan(e){if(!e.artifactRoot)return{status:"skipped",findings:[],error:"No artifact root was supplied"};let t=await this.scanner.scan({directory:e.artifactRoot,failOnSeverity:"critical"});return{status:t.passed?"passed":"failed",findings:t.findings.map((r)=>({...e,ruleId:r.pattern.name.toLowerCase().replace(/[^a-z0-9]+/g,"-"),severity:r.pattern.severity,title:r.pattern.name,description:r.pattern.description,subject:`${r.file}:${r.line}`,evidence:{file:r.file,line:r.line,column:r.column,match:r.match,context:r.context},remediation:"Remove the credential, rotate it at its issuer, and use a managed secret or environment reference."})),metadata:{scannedFiles:t.scannedFiles,summary:t.summary}}}}function WD(e){let t=e?.toLowerCase();return t==="critical"||t==="high"||t==="medium"||t==="low"?t:"info"}class ig{id="trivy-image";version;timeoutMs;constructor(e={}){this.version=e.version??"local",this.timeoutMs=e.timeoutMs??120000,this.executable=e.executable??"trivy"}executable;async scan(e){if(!e.imageRef)return{status:"skipped",findings:[],error:"No image reference was supplied"};let t;try{t=Bun.spawn([this.executable,"image","--format","json","--quiet","--scanners","vuln",e.imageRef],{stdout:"pipe",stderr:"pipe",env:{PATH:process.env.PATH??"/usr/local/bin:/usr/bin:/bin",HOME:"/nonexistent",TRIVY_NO_PROGRESS:"true"}})}catch(c){return{status:"unsupported",findings:[],error:c instanceof Error?c.message:String(c)}}let r=()=>t.kill();e.signal.addEventListener("abort",r,{once:!0});let[n,i,a]=await Promise.all([t.exited,new Response(t.stdout).text(),new Response(t.stderr).text()]);if(e.signal.removeEventListener("abort",r),n!==0)return{status:/not found|enoent/i.test(a)?"unsupported":"unavailable",findings:[],error:a.slice(0,2000)||`Trivy exited with ${n}`};let s=JSON.parse(i),d=[];for(let c of s.Results??[])for(let o of c.Vulnerabilities??[]){let g=o.VulnerabilityID??"unknown-vulnerability";d.push({...e,ruleId:g,severity:WD(o.Severity),title:o.Title||g,description:o.Description||`${g} affects ${o.PkgName??"an image package"}.`,subject:`${e.imageRef}:${o.PkgName??"unknown"}:${o.InstalledVersion??"unknown"}`,evidence:{image:e.imageRef,target:c.Target??"",cve:g,package:o.PkgName??"",installedVersion:o.InstalledVersion??"",fixedVersion:o.FixedVersion??"",reference:o.PrimaryURL??""},remediation:o.FixedVersion?`Upgrade ${o.PkgName} to ${o.FixedVersion} or later.`:"Remove or replace the affected package and rescan the image."})}return{status:d.length?"failed":"passed",findings:d,metadata:{imageRef:e.imageRef,vulnerabilityCount:d.length,localOnly:!0}}}}class jD{actions;id="aws-iam-capabilities";version="1.0.0";timeoutMs=30000;client;constructor(e,t={}){this.actions=e;if(this.resourceArns=t.resourceArns??["*"],t.client)this.client=t.client;else{let r=new si(t.region),n=new Ya(t.region);this.client={getCallerIdentity:()=>r.getCallerIdentity(),simulatePrincipalPolicy:(i)=>n.simulatePrincipalPolicy(i)}}}resourceArns;async scan(e){let t=await this.client.getCallerIdentity();if(!t.Arn)return{status:"unavailable",findings:[],error:"AWS returned no caller ARN"};let r=t.Arn;if(r.includes(":assumed-role/"))return{status:"unsupported",findings:[],error:"AWS policy simulation requires the underlying IAM role ARN; use an IAM role/user ARN or provider-native access analysis.",metadata:{account:t.Account??"",principalType:"assumed-role"}};let a=(await this.client.simulatePrincipalPolicy({PolicySourceArn:r,ActionNames:this.actions,ResourceArns:this.resourceArns})).EvaluationResults.filter((s)=>s.EvalDecision!=="allowed").map((s)=>({...e,ruleId:`iam-${s.EvalActionName.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`,severity:"high",title:`Missing AWS capability: ${s.EvalActionName}`,description:`The active AWS principal is ${s.EvalDecision||"not allowed"} for this deployment action.`,subject:`${r}:${s.EvalActionName}`,evidence:{account:t.Account??"",principalArn:r,action:s.EvalActionName,decision:s.EvalDecision,missingContext:s.MissingContextValues??[]},remediation:"Grant the deployment principal the least-privilege action on the required resources, then rerun the capability check."}));return{status:a.length?"failed":"passed",findings:a,metadata:{account:t.Account??"",principalArn:r,evaluatedActions:this.actions.length}}}}import{createHash as UD,createVerify as HD}from"node:crypto";import{existsSync as ND,readFileSync as FD}from"node:fs";import{basename as VD,join as LD,resolve as gR}from"node:path";function Hi(e){return UD("sha256").update(e).digest("hex")}function xD(e){let t=[["dependencies","required"],["optionalDependencies","optional"],["devDependencies","excluded"],["peerDependencies","required"]],r=new Map;for(let[n,i]of t){let a=e[n];if(!a||typeof a!=="object"||Array.isArray(a))continue;for(let[s,d]of Object.entries(a)){let c=String(d).replace(/^[~^]/,""),o=`${s}@${c}`;if(!r.has(o))r.set(o,{type:"library",name:s,version:c,purl:`pkg:npm/${encodeURIComponent(s)}@${encodeURIComponent(c)}`,scope:i})}}return[...r.values()].sort((n,i)=>`${n.name}@${n.version}`.localeCompare(`${i.name}@${i.version}`))}function uR(e,t={}){let r=LD(gR(e),"package.json");if(!ND(r))throw Error(`Cannot generate an SBOM: ${r} was not found`);let n=FD(r,"utf8"),i=JSON.parse(n),a=String(i.name??VD(gR(e))),s=String(i.version??"0.0.0"),d=Hi(n);return{bomFormat:"CycloneDX",specVersion:"1.5",serialNumber:t.serial??`urn:uuid:${crypto.randomUUID()}`,version:1,metadata:{timestamp:(t.now??new Date).toISOString(),component:{type:"application",name:a,version:s,purl:`pkg:npm/${encodeURIComponent(a)}@${encodeURIComponent(s)}`,hashes:[{alg:"SHA-256",content:d}]},tools:[{vendor:"ts-cloud",name:"security-posture",version:"1.0.0"}]},components:xD(i)}}async function hR(e,t={}){let r=Bun.spawn([t.executable??"syft",e,"-o","cyclonedx-json"],{stdout:"pipe",stderr:"pipe",env:{PATH:process.env.PATH??"/usr/local/bin:/usr/bin:/bin",HOME:"/nonexistent",SYFT_CHECK_FOR_APP_UPDATE:"false"}}),n=()=>r.kill();t.signal?.addEventListener("abort",n,{once:!0});let[i,a,s]=await Promise.all([r.exited,new Response(r.stdout).text(),new Response(r.stderr).text()]);if(t.signal?.removeEventListener("abort",n),i!==0)throw Error(s.slice(0,2000)||`Syft exited with ${i}`);return JSON.parse(a)}function ag(e,t,r){let n=JSON.stringify(r);return e.addReleaseArtifact({...t,kind:"sbom",format:`cyclonedx-${r.specVersion}+json`,digest:`sha256:${Hi(n)}`,summary:{component:r.metadata.component.name,version:r.metadata.component.version,components:r.components.length},content:n,sensitive:!0})}function fR(e,t,r){let n={total:r.length,critical:0,high:0,medium:0,low:0,info:0,fixable:0};for(let a of r){n[a.severity]++;let s=a.evidence;if(typeof s.fixedVersion==="string"&&s.fixedVersion)n.fixable++}let i=JSON.stringify({releaseId:t.releaseId,generatedAt:new Date().toISOString(),findings:r.map((a)=>({id:a.id,ruleId:a.ruleId,severity:a.severity,subject:a.subject,remediation:a.remediation}))});return e.addReleaseArtifact({...t,kind:"vulnerability_summary",format:"ts-cloud-vulnerability-summary+json",digest:`sha256:${Hi(i)}`,summary:n,content:i,sensitive:!0})}function SR(e){if(!e.artifact&&!e.artifactSha256)throw Error("Release provenance requires artifact content or a SHA-256 digest");return{_type:"https://in-toto.io/Statement/v1",subject:[{name:e.artifactName,digest:{sha256:e.artifactSha256?.replace(/^sha256:/,"")??Hi(e.artifact)}}],predicateType:"https://slsa.dev/provenance/v1",predicate:{buildDefinition:{buildType:"https://ts-cloud.dev/build/v1",externalParameters:e.externalParameters??{},internalParameters:{},resolvedDependencies:e.resolvedDependencies??[]},runDetails:{builder:{id:"https://ts-cloud.dev/builders/local/v1"},metadata:{invocationId:e.invocationId,startedOn:e.startedAt,finishedOn:e.completedAt}}}}}function _R(e,t,r){let n=JSON.stringify(r);return e.addReleaseArtifact({...t,kind:"provenance",format:"in-toto+slsa-v1+json",digest:`sha256:${Hi(n)}`,summary:{subjects:r.subject.length,builder:r.predicate.runDetails.builder.id,buildType:r.predicate.buildDefinition.buildType},content:n,sensitive:!0})}function Nz(e){let t=e.expectedSha256.replace(/^sha256:/,"").toLowerCase(),r=Hi(e.artifact)===t;if(!e.signature||!e.publicKey)return{digestValid:r,signature:"not_configured"};try{let n=HD("SHA256");return n.update(e.artifact),n.end(),{digestValid:r,signature:n.verify(e.publicKey,Buffer.from(e.signature,"base64"))?"verified":"invalid"}}catch{return{digestValid:r,signature:"invalid"}}}function sr(e,t){let r=e.environments.get(t);if(!r)throw Error(`Security scope for environment '${t}' was not found`);return{organizationId:e.organization.id,projectId:e.project.id,environmentId:r.id}}function RR(e,t){let r=new Ca(e.store),n=r.listPolicies(e.organization.id);for(let[i,a]of e.environments){if(n.some((d)=>d.environmentId===a.id))continue;let s=i==="production"||a.kind==="production";n.push(r.createPolicy({organizationId:e.organization.id,environmentId:a.id,name:s?"Production baseline":"Environment baseline",scannerFailMode:s?"closed":"open",requiredScanners:["source-secrets"],rules:s?[{minimumSeverity:"critical",action:"block"},{minimumSeverity:"high",action:"block"},{minimumSeverity:"medium",action:"warn"},{minimumSeverity:"low",action:"record"}]:[{minimumSeverity:"critical",action:"warn"},{minimumSeverity:"high",action:"warn"},{minimumSeverity:"low",action:"record"}],actorId:t}))}return n}function Lz(e,t,r,n={}){let i=r.findings.map((a)=>({...t,ruleId:a.pattern.name.toLowerCase().replace(/[^a-z0-9]+/g,"-"),severity:a.pattern.severity,title:a.pattern.name,description:a.pattern.description,subject:`${a.file}:${a.line}`,evidence:{file:a.file,line:a.line,column:a.column,match:a.match,context:a.context},remediation:"Remove and rotate the credential, then reference it through a managed secret or environment variable."}));return e.recordScan({...t,scannerId:"source-secrets",scannerVersion:n.scannerVersion??"1.0.0",status:n.skipped?"skipped":r.passed?"passed":"failed",findings:n.skipped?[]:i,metadata:{scannedFiles:r.scannedFiles,durationMs:r.duration,summary:r.summary},durationMs:r.duration,error:n.skipped?"The operator explicitly skipped source-secret scanning.":void 0})}function xz(e,t,r="The operator explicitly skipped source-secret scanning."){return e.recordScan({...t,scannerId:"source-secrets",scannerVersion:"1.0.0",status:"skipped",findings:[],error:r})}function MD(e,t){let r=[],n=t.security;if(n?.firewall&&!["active","configured","ok"].includes(String(n.firewall.status)))r.push({...e,ruleId:"host-firewall-disabled",severity:"high",title:"Host firewall is not active",description:String(n.firewall.summary??"The host firewall did not report an active configuration."),subject:"host:firewall",evidence:{status:String(n.firewall.status??"unknown"),rules:Array.isArray(n.firewall.rules)?n.firewall.rules.length:0},remediation:"Apply the declarative firewall policy and confirm only required listeners are public."});for(let i of n?.ports??[]){let a=String(i.listen??""),s=Number(a.match(/:(\d+)$/)?.[1]);if(i.exposure==="public"&&Number.isFinite(s)&&![22,80,443].includes(s))r.push({...e,ruleId:"unexpected-public-listener",severity:"medium",title:`Unexpected public listener on port ${s}`,description:`${String(i.processName??"A process")} is listening publicly outside the standard SSH/HTTP/HTTPS ports.`,subject:`host:port:${s}`,evidence:{protocol:String(i.proto??""),listen:a,process:String(i.processName??"")},remediation:"Bind the service to loopback/private networking or explicitly document and firewall the required public port."})}for(let i of n?.tlsCertificates??[]){let a=Number(i.daysRemaining);if(Number.isFinite(a)&&a<30)r.push({...e,ruleId:"tls-certificate-expiry",severity:a<14?"high":"medium",title:`TLS certificate expires in ${a} days`,description:`${String(i.domain??"A configured domain")} needs renewal.`,subject:`tls:${String(i.domain??"unknown")}`,evidence:{domain:String(i.domain??""),daysRemaining:a,expires:String(i.expires??"")},remediation:"Renew the certificate and verify automatic renewal can complete before expiry."})}for(let i of t.diagnostics??[]){if(i.status==="pass"||i.status==="ok")continue;r.push({...e,ruleId:`diagnostic-${String(i.name??"unknown").toLowerCase().replace(/[^a-z0-9]+/g,"-")}`,severity:i.status==="fail"?"high":"medium",title:String(i.name??"Host security check"),description:String(i.detail??"The host security diagnostic did not pass."),subject:`diagnostic:${String(i.name??"unknown")}`,evidence:{status:String(i.status??"unknown")},remediation:"Follow the diagnostic guidance, rerun the check, and confirm the finding resolves."})}return r}function Bo(e,t,r){let n=!!r.security||Array.isArray(r.diagnostics),i=n?MD(t,r):[];return e.recordScan({...t,scannerId:"host-posture",scannerVersion:"1.0.0",status:!n?"unavailable":i.length?"failed":"passed",findings:i,metadata:{source:"dashboard-live-probe",checks:Array.isArray(r.diagnostics)?r.diagnostics.length:0},error:n?void 0:"Live host posture data was unavailable; source and provider checks remain usable."})}function Jo(e,t){let r=e.evaluateGate({...t.scope,operationId:t.operationId}),n=e.listFindings({...t.scope,limit:1000}).filter((i)=>i.status!=="resolved");return{decision:r,summary:{desiredConfigHash:t.desiredConfigHash??null,securityImpact:{critical:n.filter((i)=>i.severity==="critical").length,high:n.filter((i)=>i.severity==="high").length,waived:n.filter((i)=>i.status==="waived").length,assigned:n.filter((i)=>!!i.ownerActorId).length},blockingFindingIds:r.findingIds,policy:{id:r.policyId,version:r.policyVersion},scannerVersions:r.scannerVersions}}}async function Zz(e,t){let r=t.scanner??new ig({timeoutMs:t.scannerTimeoutMs}),i=await new Gn(e,{defaultTimeoutMs:t.scannerTimeoutMs??120000}).run(r,{...t.scope,releaseId:t.releaseId,imageRef:t.imageRef}),a={...t.scope,releaseId:t.releaseId};fR(e,a,i.findings);let s=t.generateImageSbom??hR,d=new AbortController,c=Math.max(100,t.sbomTimeoutMs??120000),o,g=new Promise((R,E)=>{o=setTimeout(()=>{d.abort(),E(Error(`syft-sbom exceeded its ${c}ms timeout`))},c)}),h="unavailable";try{let R=await Promise.race([s(t.imageRef,{signal:d.signal}),g]);ag(e,a,R),e.recordScan({...t.scope,releaseId:t.releaseId,scannerId:"syft-sbom",scannerVersion:"local",status:"passed",metadata:{imageRef:t.imageRef,format:`cyclonedx-${R.specVersion}+json`,components:R.components.length,localOnly:!0}}),h="image"}catch(R){let E=R instanceof Error?R.message:String(R);try{let y=uR(t.artifactRoot);ag(e,a,y),e.recordScan({...t.scope,releaseId:t.releaseId,scannerId:"syft-sbom",scannerVersion:"local",status:"unsupported",error:`Image inventory was unavailable; attached a package-manifest SBOM instead. ${E}`,metadata:{imageRef:t.imageRef,fallback:"package-manifest",components:y.components.length,localOnly:!0}}),h="manifest"}catch(y){e.recordScan({...t.scope,releaseId:t.releaseId,scannerId:"syft-sbom",scannerVersion:"local",status:"unavailable",error:`Image and manifest SBOM generation were unavailable. ${E}; ${y instanceof Error?y.message:String(y)}`,metadata:{imageRef:t.imageRef,localOnly:!0}})}}finally{if(o)clearTimeout(o)}let _=SR({artifactName:t.imageRef,artifact:t.imageSha256?void 0:t.imageRef,artifactSha256:t.imageSha256,invocationId:t.invocationId,startedAt:t.startedAt,completedAt:t.completedAt??new Date().toISOString(),externalParameters:t.externalParameters??{imageRef:t.imageRef}});return _R(e,a,_),{scan:i,sbomSource:h}}import{randomBytes as pR,scryptSync as IR,timingSafeEqual as QD}from"node:crypto";function cg(e,t){if(e.role==="admin")return[...t];return t.filter((r)=>!!e.sites?.[r])}var sg=32768,og=8,dg=1,GD=32,ZD=16;function fn(e){let t=pR(ZD),r=IR(e,t,GD,{N:sg,r:og,p:dg,maxmem:268435456});return`scrypt$${sg}$${og}$${dg}$${t.toString("base64url")}$${r.toString("base64url")}`}function or(e,t){try{let r=t.split("$");if(r.length!==6||r[0]!=="scrypt")return!1;let[,n,i,a,s,d]=r,c=Number(n),o=Number(i),g=Number(a);if(!Number.isFinite(c)||!Number.isFinite(o)||!Number.isFinite(g))return!1;let h=Buffer.from(s,"base64url"),_=Buffer.from(d,"base64url");if(h.length===0||_.length===0)return!1;let R=IR(e,h,_.length,{N:c,r:o,p:g,maxmem:268435456});return QD(R,_)}catch{return!1}}function mR(e){let[t,r,n,i]=e.split("$");return t!=="scrypt"||Number(r)!==sg||Number(n)!==og||Number(i)!==dg}function lg(){return pR(18).toString("base64url")}import{existsSync as n0,readFileSync as i0}from"node:fs";import{join as a0}from"node:path";import{createHash as KD}from"node:crypto";function yR(e){let t=gg(e.name),r=ug(e.publicKey),n=XD([...e.existingKeys??[],{name:t,publicKey:r}]);return AR(e.configText,n)}function wR(e){let t=gg(e.name),r=(e.existingKeys??[]).filter((n)=>n.name!==t);if((e.existingKeys??[]).length===r.length)throw Error(`SSH key '${t}' does not exist in compute.sshKeys`);return AR(e.configText,r)}function Sn(e=[]){return e.map((t)=>({name:t.name,publicKey:t.publicKey,type:qD(t.publicKey),fingerprint:e0(t.publicKey),added:"configured"}))}function AR(e,t){let r=t0(e,"compute"),n=YD(t),i=r0(e,r.start,r.end,"sshKeys");if(i){let c=i.propertyStart;while(c>0&&e[c-1]!==`
174
+ `&&/\s/.test(e[c-1]))c--;return`${e.slice(0,c)}${n}${e.slice(i.end+1)}`}let a=e.slice(0,r.end).trimEnd(),s=e.slice(r.end),d=a.endsWith(",")||a.endsWith("{")?"":",";return`${a}${d}
175
+ ${n},
176
+ ${s}`}function YD(e){if(e.length===0)return" sshKeys: []";return` sshKeys: [
177
+ ${e.map((r)=>[" {",` name: '${ER(r.name)}',`,` publicKey: '${ER(ug(r.publicKey))}',`," },"].join(`
178
+ `)).join(`
179
+ `)}
180
+ ]`}function XD(e){let t=new Map;for(let r of e){let n=gg(r.name);if(t.has(n))throw Error(`SSH key '${n}' already exists in compute.sshKeys`);t.set(n,{name:n,publicKey:ug(r.publicKey)})}return[...t.values()]}function gg(e){let t=e.trim();if(!/^[\w@.+-]{2,80}$/.test(t))throw Error("SSH key name must be 2-80 characters and use letters, numbers, @, ., +, _, or -.");return t}function ug(e){let t=e.trim().replace(/\s+/g," "),[r,n]=t.split(" ");if(!/^(?:ssh-(?:ed25519|rsa)|ecdsa-sha2-nistp(?:256|384|521))$/.test(r??"")||!n)throw Error("Public key must be an OpenSSH public key, e.g. ssh-ed25519 AAAA... name@host.");return t}function qD(e){return e.trim().split(/\s+/)[0]||"ssh"}function e0(e){let t=e.trim().split(/\s+/)[1];if(!t)return"-";try{return`SHA256:${KD("sha256").update(Buffer.from(t,"base64")).digest("base64").replace(/=+$/,"")}`}catch{return"-"}}function ER(e){return e.replace(/\\/g,"\\\\").replaceAll(String.fromCharCode(39),"\\'")}function t0(e,t){let r=new RegExp(`\\b${t}\\s*:\\s*{`,"g").exec(e);if(!r)throw Error(`Could not find ${t}: { ... } in cloud config.`);let n=e.indexOf("{",r.index);return{propertyStart:r.index,start:n,end:va(e,n,"{","}")}}function r0(e,t,r,n){let i=e.slice(t+1,r),a=new RegExp(`\\b${n}\\s*:\\s*\\[`,"g").exec(i);if(!a)return null;let s=t+1+a.index,d=e.indexOf("[",s);return{propertyStart:s,start:d,end:va(e,d,"[","]")}}function va(e,t,r,n){let i=0,a,s=!1,d=!1,c=!1;for(let o=t;o<e.length;o++){let g=e[o],h=e[o+1];if(d){if(g===`
181
+ `)d=!1;continue}if(c){if(g==="*"&&h==="/")c=!1,o++;continue}if(a){if(s){s=!1;continue}if(g==="\\"){s=!0;continue}if(g===a)a=void 0;continue}if(g==="/"&&h==="/"){d=!0,o++;continue}if(g==="/"&&h==="*"){c=!0,o++;continue}if(g==='"'||g==="'"||g==="`"){a=g;continue}if(g===r)i++;if(g===n){if(i--,i===0)return o}}throw Error(`Could not find matching ${n} in cloud config.`)}var s0=["rpx-gateway","nginx","php8.3-fpm","php8.2-fpm","mysql","mariadb","postgresql","redis","redis-server","meilisearch"],$t="-";function o0(e){let t=String.raw`
182
+ import { X509Certificate } from 'node:crypto'
183
+ import { existsSync, readdirSync, readFileSync, readlinkSync, statSync } from 'node:fs'
184
+ import { basename, join } from 'node:path'
185
+
186
+ const fragmentsRoot = '/etc/rpx/sites.d'
187
+ const certsRoot = '/etc/rpx/certs'
188
+ const projectFilter = ${JSON.stringify(e??"")}
189
+ const configuredRoutes = []
190
+ if (existsSync(fragmentsRoot)) {
191
+ for (const file of readdirSync(fragmentsRoot).filter(name => name.endsWith('.json')).sort()) {
192
+ try {
193
+ const fragment = JSON.parse(readFileSync(join(fragmentsRoot, file), 'utf8'))
194
+ const project = String(fragment.slug || basename(file, '.json'))
195
+ if (projectFilter && project !== projectFilter) continue
196
+ for (const route of Array.isArray(fragment.proxies) ? fragment.proxies : []) {
197
+ if (!route || !route.to) continue
198
+ const path = route.path || '/'
199
+ const staticRoot = typeof route.static === 'string' ? route.static : route.static?.dir
200
+ const kind = route.redirect ? 'redirect' : staticRoot ? 'static' : 'app'
201
+ const install = staticRoot || ''
202
+ const installName = install.match(/^\/var\/www\/(.+?)\/current(?:\/|$)/)?.[1]
203
+ const siteName = installName?.startsWith(project + '-') ? installName.slice(project.length + 1) : String(route.id || route.to)
204
+ const href = 'https://' + route.to + (path === '/' ? '' : path)
205
+ configuredRoutes.push({
206
+ name: siteName,
207
+ project,
208
+ route: path === '/' ? route.to : route.to + path,
209
+ href,
210
+ domain: route.to,
211
+ path,
212
+ kind,
213
+ runtime: kind === 'app' ? 'service' : kind,
214
+ deploy: kind === 'app' ? 'service' : kind === 'static' ? 'server static' : 'redirect',
215
+ tls: 'https',
216
+ root: install || (Array.isArray(route.from) ? route.from.join(', ') : route.from || 'gateway'),
217
+ branch: kind === 'static' ? 'build artifact' : 'main',
218
+ install,
219
+ })
220
+ }
221
+ }
222
+ catch {}
223
+ }
224
+ }
225
+
226
+ async function mapWithConcurrency(values, limit, mapper) {
227
+ const results = new Array(values.length)
228
+ let next = 0
229
+ const workers = Array.from({ length: Math.min(limit, values.length) }, async () => {
230
+ while (next < values.length) {
231
+ const index = next++
232
+ results[index] = await mapper(values[index])
233
+ }
234
+ })
235
+ await Promise.all(workers)
236
+ return results
237
+ }
238
+
239
+ const routes = await mapWithConcurrency(configuredRoutes, 8, async route => {
240
+ const started = performance.now()
241
+ let httpStatus = 0
242
+ const probe = async (href) => {
243
+ const response = await fetch(href, {
244
+ method: 'GET',
245
+ redirect: 'manual',
246
+ headers: { 'user-agent': 'ts-cloud-monitor/1.0' },
247
+ signal: AbortSignal.timeout(6000),
248
+ })
249
+ const status = response.status
250
+ await response.arrayBuffer()
251
+ return status
252
+ }
253
+ try {
254
+ httpStatus = await probe(route.href)
255
+ if (httpStatus === 404 && route.kind === 'app') {
256
+ const healthHref = route.href.replace(/\/$/, '') + '/health'
257
+ httpStatus = await probe(healthHref)
258
+ }
259
+ }
260
+ catch {}
261
+ const responseMs = Math.max(0, Math.round(performance.now() - started))
262
+ let tlsDaysRemaining
263
+ const cert = join(certsRoot, route.domain + '.crt')
264
+ if (existsSync(cert)) {
265
+ try {
266
+ const expiresAt = Date.parse(new X509Certificate(readFileSync(cert)).validTo)
267
+ if (Number.isFinite(expiresAt)) tlsDaysRemaining = Math.floor((expiresAt - Date.now()) / 86400000)
268
+ }
269
+ catch {}
270
+ }
271
+ let release
272
+ let deployedAt
273
+ if (route.install) {
274
+ try {
275
+ release = basename(readlinkSync(route.install))
276
+ deployedAt = statSync(route.install).mtime.toISOString()
277
+ }
278
+ catch {}
279
+ }
280
+ const status = httpStatus === 0 || httpStatus >= 500 ? 'failed' : httpStatus === 404 ? 'degraded' : 'live'
281
+ const { install, ...site } = route
282
+ return {
283
+ ...site,
284
+ status,
285
+ httpStatus,
286
+ responseMs,
287
+ tlsDaysRemaining,
288
+ checkedAt: new Date().toISOString(),
289
+ release,
290
+ deployedAt,
291
+ }
292
+ })
293
+ for (const route of routes) console.log('DISCOVERED_SITE=' + Buffer.from(JSON.stringify(route)).toString('base64'))
294
+
295
+ const serviceOutput = Bun.spawnSync([
296
+ 'systemctl', 'list-units', '--type=service', '--state=running', '--no-legend', '--plain',
297
+ ]).stdout.toString()
298
+ const runningUnits = serviceOutput
299
+ .split('\n')
300
+ .map(line => line.trim().split(/\s+/)[0])
301
+ .filter(Boolean)
302
+ if (runningUnits.length > 0) {
303
+ const propertiesOutput = Bun.spawnSync([
304
+ 'systemctl',
305
+ 'show',
306
+ ...runningUnits,
307
+ '--property=Id,WorkingDirectory,ExecStart,MemoryCurrent,UnitFileState,ActiveEnterTimestamp',
308
+ ]).stdout.toString()
309
+ for (const properties of propertiesOutput.split(/\n\n+/)) {
310
+ const values = Object.fromEntries(properties.split('\n').filter(Boolean).map(value => {
311
+ const separator = value.indexOf('=')
312
+ return separator < 0 ? [value, ''] : [value.slice(0, separator), value.slice(separator + 1)]
313
+ }))
314
+ const unit = values.Id
315
+ if (!unit) continue
316
+ if (!/^\/var\/www\/|^\/opt\/ts-cloud\//.test(values.WorkingDirectory || '') && !/\/var\/www\/|\/opt\/ts-cloud\//.test(values.ExecStart || '')) continue
317
+ console.log([
318
+ 'SVC',
319
+ unit,
320
+ 'active',
321
+ values.MemoryCurrent || '0',
322
+ values.UnitFileState || '-',
323
+ values.ActiveEnterTimestamp || '-',
324
+ ].join('='))
325
+ }
326
+ }
327
+ `;return`echo '${Buffer.from(t).toString("base64")}' | base64 -d | bun -`}function d0(e={}){let t=["set +e",'echo "CPUS=$(nproc 2>/dev/null || echo 1)"',`read TS_TOTAL_1 TS_IDLE_1 <<EOF
328
+ $(awk '/^cpu /{idle=$5+$6; total=0; for(i=2;i<=NF;i++) total+=$i; print total, idle; exit}' /proc/stat 2>/dev/null)
329
+ EOF`,"sleep 0.2",`read TS_TOTAL_2 TS_IDLE_2 <<EOF
330
+ $(awk '/^cpu /{idle=$5+$6; total=0; for(i=2;i<=NF;i++) total+=$i; print total, idle; exit}' /proc/stat 2>/dev/null)
331
+ EOF`,`echo "CPUUSED=$(awk -v t1="$TS_TOTAL_1" -v i1="$TS_IDLE_1" -v t2="$TS_TOTAL_2" -v i2="$TS_IDLE_2" 'BEGIN { dt=t2-t1; di=i2-i1; if (dt>0) printf "%.1f", 100*(dt-di)/dt; else print 0 }')"`,`echo "LOAD=$(cut -d' ' -f1 /proc/loadavg 2>/dev/null || echo 0)"`,`echo "LOAD5=$(cut -d' ' -f2 /proc/loadavg 2>/dev/null || echo 0)"`,`echo "LOAD15=$(cut -d' ' -f3 /proc/loadavg 2>/dev/null || echo 0)"`,`read MEMTOTAL MEMUSED MEMAVAILABLE MEMCACHE SWAPTOTAL SWAPUSED <<EOF
332
+ $(free -m 2>/dev/null | awk '/^Mem:/{total=$2; used=$3; available=$7; cache=$6} /^Swap:/{print total, used, available, cache, $2, $3}')
333
+ EOF`,'echo "MEMTOTAL=${MEMTOTAL:-0}"','echo "MEMUSED=${MEMUSED:-0}"','echo "MEMAVAILABLE=${MEMAVAILABLE:-0}"','echo "MEMCACHE=${MEMCACHE:-0}"','echo "SWAPTOTAL=${SWAPTOTAL:-0}"','echo "SWAPUSED=${SWAPUSED:-0}"',`read DISKTOTG DISKUSEDG DISKPCT <<EOF
334
+ $(df -BG -P / 2>/dev/null | awk 'NR==2{gsub("G","",$2); gsub("G","",$3); gsub("%","",$5); print $2, $3, $5}')
335
+ EOF`,'echo "DISKPCT=${DISKPCT:-0}"','echo "DISKUSEDG=${DISKUSEDG:-0}"','echo "DISKTOTG=${DISKTOTG:-0}"',`echo "INODEPCT=$(df -Pi / 2>/dev/null | awk 'NR==2{gsub("%","",$5);print $5}')"`,`echo "NETRX=$(awk -F'[: ]+' 'NR>2 && $2!="lo"{sum+=$3} END{print sum+0}' /proc/net/dev 2>/dev/null)"`,`echo "NETTX=$(awk -F'[: ]+' 'NR>2 && $2!="lo"{sum+=$11} END{print sum+0}' /proc/net/dev 2>/dev/null)"`,". /var/lib/ts-cloud/bandwidth-state 2>/dev/null || true",'echo "NETRXRATE=${RX_RATE:-0}"','echo "NETTXRATE=${TX_RATE:-0}"','echo "NETRXTODAY=${DAY_RX:-0}"','echo "NETTXTODAY=${DAY_TX:-0}"','echo "NETRXMONTH=${MONTH_RX:-0}"','echo "NETTXMONTH=${MONTH_TX:-0}"','echo "NETMONTHKEY=${MONTH_KEY:-}"',`echo "PROCESSES=$(ps -e --no-headers 2>/dev/null | awk 'END{print NR+0}')"`,`echo "UPTIME=$(uptime -p 2>/dev/null | sed 's/^up //' || echo unknown)"`,`echo "UPTIME_SECONDS=$(cut -d' ' -f1 /proc/uptime 2>/dev/null || echo 0)"`,'echo "OS=$(. /etc/os-release 2>/dev/null; echo "$PRETTY_NAME")"'];if(e.includeServices!==!1)t.push(`for s in ${s0.join(" ")}; do st=$(systemctl is-active "$s" 2>/dev/null); if [ -n "$st" ] && [ "$st" != "inactive" ] && [ "$st" != "unknown" ]; then mem=$(systemctl show "$s" -p MemoryCurrent --value 2>/dev/null); en=$(systemctl is-enabled "$s" 2>/dev/null); since=$(systemctl show "$s" -p ActiveEnterTimestamp --value 2>/dev/null); echo "SVC=$s=$st=$mem=$en=$since"; fi; done`);if(e.includeSites!==!1)t.push(o0(e.projectFilter));return t.push("true"),t}function c0(e){let t={services:[],discoveredSites:[]};for(let r of e.split(`
336
+ `)){let n=r.trim();if(n.startsWith("DISCOVERED_SITE="))try{let i=JSON.parse(Buffer.from(n.slice(16),"base64").toString("utf8"));if(i?.domain&&i?.route)t.discoveredSites.push(i)}catch{}else if(n.startsWith("SVC=")){let[,i,a,s,d,c]=/^SVC=([^=]+)=([^=]+)(?:=([^=]*)(?:=([^=]*)(?:=(.*))?)?)?$/.exec(n)??[];if(i)t.services.push({name:i,status:a,memBytes:Number(s||0),enabled:d||$t,since:c||$t})}else{let i=n.indexOf("=");if(i>0)t[n.slice(0,i)]=n.slice(i+1)}}return t}function $R(e){let t=e.infrastructure?.compute,r=[];if(t?.webServer==="rpx"||t?.proxy?.engine==="rpx")r.push({name:"rpx-gateway",status:"configured"});else if(t?.webServer==="nginx"||t?.webServer==null)r.push({name:"ts-cloud-nginx",status:"configured"});let n=t?.php?.versions??(t?.runtime==="php"?["8.3"]:[]);for(let s of n)r.push({name:`php${s}-fpm`,status:"configured"});let i=t?.managedServices??{},a=[["mysql","mysql"],["mariadb","mariadb"],["postgres","postgresql"],["redis","redis"],["memcached","memcached"],["meilisearch","meilisearch"]];for(let[s,d]of a)if(i[s])r.push({name:d,status:"configured"});return r}function l0(e){let t=e.infrastructure?.compute?.backups,r=!!t?.enabled,n=t?.schedule??"0 2 * * *";return{enabled:r,schedule:n,destination:r?t?.bucket??"local":"off",retention:r?t?.retentionCount??5:0,last:r?"pending first run":"not configured",size:r?$t:"0 MB"}}function CR(e){return e.infrastructure?.compute?.provider??e.cloud?.provider??e.provider??"aws"}function g0(e){if(CR(e)==="hetzner")return DR(e);return e.project.region??"us-east-1"}function u0(e){let t=e.infrastructure?.compute?.monitoring,r=Number(typeof t==="object"?t?.alerts?.bandwidthTb??0:0);return Number.isFinite(r)&&r>0?Math.round(r*1000000000000):0}function h0(e,t){let r=a0(process.cwd(),"storage","cloud","state",`${e.project.slug}-${t}.json`);if(!n0(r))return null;try{return JSON.parse(i0(r,"utf8"))}catch{return null}}function f0(e){let t=e.sites??{},r=[];for(let[n,i]of Object.entries(t)){let a=i.queues??i.workers;if(Array.isArray(a)){for(let s of a)if(typeof s==="string")r.push({name:`${n}:${s}`,site:n,processes:1,status:"configured"});else if(s?.name)r.push({name:`${n}:${s.name}`,site:n,processes:s.processes??1,status:"configured"})}}return r}function kR(e){if(!e||e==="")return"/";return e.startsWith("/")?e:`/${e}`}function S0(e){let t=kR(e.path);if(!e.domain)return{route:"internal"};return{route:t==="/"?e.domain:`${e.domain}${t}`,href:`https://${e.domain}${t==="/"?"":t}`}}function PR(e,t){let r=Hr(t);if(r==="redirect")return"redirect";if(r==="proxy")return"proxy";let n=String(t.build??"").toLowerCase(),i=String(t.start??"").toLowerCase();if(e==="main"||i.includes("buddy/src/cli.ts serve"))return"stacks";if(e==="api"||i.includes("/serve/api"))return"api";if(n.includes("buildblog"))return"bunpress blog";if(n.includes("bunpress"))return"bunpress";if(n.includes("site:build")||n.includes("stx"))return"stx static";if(r==="server-static")return t.spa?"spa":"static";if(r==="server-app")return"app";if(r==="server-php")return t.type??"php";return"bucket"}function _0(e){let t=Hr(e);if(t==="redirect"||t==="proxy")return"—";let r=`${e.start??""} ${e.build??""}`.toLowerCase();if(t==="server-static")return r.includes("bunpress")||r.includes("bun ")||r.includes("bunx ")?"static/bun":"static";if(t==="server-app")return r.includes("bun")?"bun":"node";if(t==="server-php")return`php ${e.php??e.phpVersion??"8.3"}`;return"static"}function R0(e){let t=Hr(e);if(t==="redirect")return"redirect";if(t==="proxy")return"proxy";if(t==="server-app")return"service";if(t==="server-static")return"server static";if(t==="server-php")return"php release";return"bucket"}function p0(e){let t=new Map;return Object.entries(e.sites??{}).map(([r,n])=>{let i=kR(n.path),{route:a,href:s}=S0(n),d=n.domain?`${n.domain}${i}`:"",c=d?t.get(d):void 0;if(d&&!c)t.set(d,r);return{name:r,route:a,href:s,domain:n.domain??"internal",path:i,kind:PR(r,n),type:PR(r,n),runtime:_0(n),deploy:R0(n),tls:n.domain?n.ssl===!1?"http":"https":"loopback",ssl:n.domain?n.ssl!==!1:!1,status:c?"shadowed":"live",shadowedBy:c,lastDeploy:$t}})}function I0(e,t,r){let n=new Map(e.map((i)=>[String(i.route),{...i,project:r,managedBy:"owner"}]));for(let i of t){let a=n.get(i.route),s=a?.name??`${i.project}:${i.name}`;n.set(i.route,{...a,...i,name:s,kind:a?.kind??i.kind,type:a?.type??i.kind,runtime:a?.runtime??i.runtime,deploy:a?.deploy??i.deploy,root:a?.root??i.root,branch:a?.branch??i.branch,managedBy:i.project===r?"owner":"attached"})}return[...n.values()].sort((i,a)=>{if(i.managedBy!==a.managedBy)return i.managedBy==="owner"?-1:1;return String(i.route).localeCompare(String(a.route))})}function hg(e){return`'${e.replaceAll("'","'\\''")}'`}function bR(e){return e.replace(/[\\&/]/g,"\\$&")}function m0(e,t){if(e.length===0)return["true"];return["set +e",...e.map((r)=>{let n=hg(`${_n(t,r)}/.ts-cloud/deploy-history.log`),i=bR(r);return`TS_CLOUD_HISTORY=${n}; { [ -f "$TS_CLOUD_HISTORY" ] && tail -n 24 "$TS_CLOUD_HISTORY" | sed "s/^/DEPLOY=${i}\\t/"; } || true`}),"true"]}function vR(e){return[...new Set(Object.values(e.sites??{}).map((t)=>t.domain).filter((t)=>typeof t==="string"&&t.length>0))]}function E0(e){return["set +e",'if command -v ss >/dev/null 2>&1; then ss -H -lntup 2>/dev/null | while read -r proto _state _recv _send local _peer rest; do [ -n "$proto" ] && [ -n "$local" ] && printf "PORT=%s\\t%s\\t%s\\n" "$proto" "$local" "$rest"; done; fi','if command -v ufw >/dev/null 2>&1; then ufw status numbered 2>/dev/null | sed "s/^/FIREWALL=/"; else echo "FIREWALL=ufw unavailable"; fi','journalctl _COMM=sshd --no-pager -n 30 -o short-iso 2>/dev/null | sed "s/^/AUTH=/" || true',...vR(e).map((r)=>{return`TS_CLOUD_DOMAIN=${hg(r)}; TS_CLOUD_EXPIRY=$(echo | timeout 8 openssl s_client -servername "$TS_CLOUD_DOMAIN" -connect "$TS_CLOUD_DOMAIN:443" 2>/dev/null | openssl x509 -noout -enddate 2>/dev/null | cut -d= -f2-); [ -n "$TS_CLOUD_EXPIRY" ] && printf "CERT=%s\\t%s\\n" "$TS_CLOUD_DOMAIN" "$TS_CLOUD_EXPIRY" || printf "CERT=%s\\tunavailable\\n" "$TS_CLOUD_DOMAIN"`}),"true"]}function y0(e){let t=new Map,r=(a,s)=>{if(a&&s&&!t.has(s))t.set(s,{pattern:a,label:s})},n=e.infrastructure?.compute,i=e.project.slug;if(n?.webServer==="rpx"||n?.proxy?.engine==="rpx")r("rpx-gateway","rpx-gateway");else r("nginx","nginx");for(let a of $R(e))r(a.name,a.name);for(let[a,s]of Object.entries(e.sites??{})){if(Hr(s)!=="server-app")continue;if(r(`${i}-${a}`,`${i}-${a}`),Array.isArray(s.queues??s.workers)&&(s.queues??s.workers).length)r(`${i}-${a}-queue-*`,`${i}-${a}-queues`);if(Array.isArray(s.daemons)&&s.daemons.length)r(`${i}-${a}-daemon-*`,`${i}-${a}-daemons`)}return[...t.values()]}function w0(e){let t=y0(e);if(t.length===0)return["true"];return["set +e",...t.map((r)=>{let n=hg(r.pattern),i=bR(r.label);return`journalctl -u ${n} --no-pager -n 150 -o short-iso 2>/dev/null | sed "s/^/LOG=${i}\\t/" || true`}),'[ -f /var/log/ts-cloud-backup.log ] && tail -n 60 /var/log/ts-cloud-backup.log 2>/dev/null | sed "s/^/LOG=backups\\t/" || true',"true"]}function fg(e){let t=new Date(e);if(Number.isNaN(t.getTime()))return e||$t;let r=Math.max(0,Math.round((Date.now()-t.getTime())/1000));if(r<60)return`${r}s ago`;let n=Math.round(r/60);if(n<60)return`${n}m ago`;let i=Math.round(n/60);if(i<48)return`${i}h ago`;return`${Math.round(i/24)}d ago`}function OR(e){if(/(?:error|failed|panic|fatal|exception|denied|unhealthy)/i.test(e))return"error";if(/(?:warn|warning|retry|restart|deprecated|timeout)/i.test(e))return"warn";return"info"}function A0(e){let t=[];for(let r of e.split(`
337
+ `)){let n=r.trim();if(!n.startsWith("LOG="))continue;let i=n.indexOf("\t");if(i<0)continue;let a=n.slice(4,i),s=n.slice(i+1),d=/^(\d{4}-\d{2}-\d{2}T[^\s]+)\s+(\S+)\s+(.*)$/.exec(s),c=d?.[1]??"",o=d?.[2]??"",g=(d?.[3]??s).trim();if(!g)continue;t.push({source:a,timestamp:c,when:c?fg(c):$t,host:o,message:g,level:OR(g)})}return t.sort((r,n)=>String(n.timestamp).localeCompare(String(r.timestamp))).slice(0,600)}function BR(e){if(/^(?:127\.|localhost:|\[?::1\]?)/.test(e))return"loopback";if(/^(?:10\.|192\.168\.|172\.(?:1[6-9]|2\d|3[01])\.|169\.254\.|\[?f[cd][0-9a-f:])/i.test(e))return"private";return"public"}function P0(e){if(BR(e)!=="public")return"ok";if(/:(?:22|80|443)$/.test(e)||/^\*:(?:22|80|443)$/.test(e))return"ok";return"warn"}function D0(e){if(e==null)return"warn";if(e<8)return"bad";if(e<30)return"warn";return"ok"}function $0(e){let t=[],r=[],n=[],i=[];for(let d of e.split(`
338
+ `)){let c=d.trim();if(c.startsWith("PORT=")){let[o="",g="",h=""]=c.slice(5).split("\t");if(o&&g)t.push({proto:o,listen:g,processName:h||$t,exposure:BR(g),tone:P0(g)})}else if(c.startsWith("FIREWALL=")){let o=c.slice(9).trim();if(o)r.push(o)}else if(c.startsWith("AUTH=")){let o=c.slice(5),g=/^(\d{4}-\d{2}-\d{2}T[^\s]+)\s+(\S+)\s+(.*)$/.exec(o),h=(g?.[3]??o).trim();if(h)n.push({timestamp:g?.[1]??"",when:g?.[1]?fg(g[1]):$t,host:g?.[2]??"",message:h,level:OR(h)})}else if(c.startsWith("CERT=")){let[o="",g=""]=c.slice(5).split("\t");if(!o)continue;let h=new Date(g),_=Number.isNaN(h.getTime())?null:Math.ceil((h.getTime()-Date.now())/86400000);i.push({domain:o,expires:Number.isNaN(h.getTime())?g||$t:h.toISOString().slice(0,10),daysRemaining:_,status:D0(_)})}}let a=r.some((d)=>/Status:\s*active/i.test(d)),s=r.some((d)=>/unavailable/i.test(d));return{ports:t.slice(0,80),firewall:{status:a?"active":s?"unavailable":"inactive",summary:a?"ufw active":s?"ufw unavailable":"ufw inactive or not configured",rules:r.filter((d)=>d&&!/^Status:/i.test(d)).slice(0,60)},tlsCertificates:i,authEvents:n.sort((d,c)=>String(c.timestamp).localeCompare(String(d.timestamp))).slice(0,30)}}function Sg(e){let r=e.infrastructure?.compute?.firewall??{},n=[...new Set([22,80,443,...r.allowedPorts??[]])],i=vR(e);return{ports:n.map((a)=>({proto:"tcp",listen:`0.0.0.0:${a}`,processName:"configured firewall",exposure:"public",tone:[22,80,443].includes(Number(a))?"ok":"warn"})),firewall:{status:r.enabled===!1?"disabled":"configured",summary:r.enabled===!1?"host firewall disabled in config":"host firewall configured declaratively",rules:n.map((a)=>`ALLOW ${a}/tcp`)},tlsCertificates:i.map((a)=>({domain:a,expires:$t,daysRemaining:null,status:"warn"})),authEvents:[]}}function JR(e,t){let r=t.security??Sg(e),n=!!t._serverReachable&&!t.metricsUnavailable,i=t.sites??[],a=i.filter((o)=>o.status==="shadowed"),s=(t.services??[]).filter((o)=>["failed","stopped"].includes(o.status)),d=(r.tlsCertificates??[]).filter((o)=>o.status!=="ok"),c=t.sshKeys??[];return[{name:"Live server probe",status:n?"pass":"warn",detail:n?"Metrics and remote checks are coming from the compute box.":"The dashboard is rendering config/state data until the box probe succeeds."},{name:"Managed services",status:s.length?"fail":"pass",detail:s.length?`${s.length} service(s) need attention.`:`${(t.services??[]).length} service(s) reported healthy or configured.`},{name:"Route conflicts",status:a.length?"warn":"pass",detail:a.length?`${a.map((o)=>o.name).join(", ")} is shadowed by an earlier route.`:`${i.length} site route(s) are unshadowed.`},{name:"SSH access",status:c.length?"pass":"warn",detail:c.length?`${c.length} declarative authorized key(s) configured.`:"No declarative SSH keys are configured."},{name:"Firewall",status:["active","configured"].includes(r.firewall?.status)?"pass":"warn",detail:r.firewall?.summary??"Firewall status unavailable."},{name:"TLS certificates",status:d.length?"warn":"pass",detail:d.length?`${d.length} certificate(s) need renewal visibility.`:`${(r.tlsCertificates??[]).length} certificate(s) look healthy.`}]}function TR(e){let t=[];for(let r of e.serverDeploymentsDetail??e.serverDeployments??[])t.push({type:"deploy",tone:r.status==="failed"?"bad":"ok",title:`${r.site} deployed ${r.sha}`,detail:`${r.branch} · ${r.status}`,when:r.when,timestamp:r.timestamp});for(let r of e.serverLogs??[])if(r.level==="error"||r.level==="warn")t.push({type:"log",tone:r.level==="error"?"bad":"warn",title:`${r.source} ${r.level}`,detail:r.message,when:r.when,timestamp:r.timestamp});for(let r of e.sshKeys??[])t.push({type:"ssh",tone:"ok",title:`${r.name} authorized`,detail:r.fingerprint,when:r.added??$t,timestamp:""});return t.sort((r,n)=>String(n.timestamp).localeCompare(String(r.timestamp))).slice(0,80)}function C0(e,t={}){let r=[];for(let n of e.split(`
339
+ `)){let i=n.trim();if(!i.startsWith("DEPLOY="))continue;let a=i.split("\t"),s=a[0]?.replace(/^DEPLOY=/,"")??"",[d,c,o,g,h]=a.slice(1);if(!s||!d||!c)continue;let _=t[s]??{},R=Hr(_),E=(o||c).slice(0,7);r.push({sha:E,release:c,commit:o||c,site:s,branch:_.branch??(R==="server-static"?"build artifact":"main"),status:g||"unknown",when:fg(d),timestamp:d,took:"-",by:"ts-cloud",rc:h?.replace(/^rc=/,"")??"",steps:R==="server-static"?["upload artifact","publish static files"]:["upload artifact","restart service"]})}return r.sort((n,i)=>String(i.timestamp).localeCompare(String(n.timestamp)))}function k0(e,t){let r=h0(e,t),n=$R(e),i=p0(e),a=Math.max(1,Number(e.infrastructure?.compute?.disk?.size??1)),s={server:{name:r?.serverName??`${e.project.slug}-${t}-app`,provider:r?.provider??CR(e),region:g0(e),ip:r?.publicIp??$t,os:"Linux",uptime:$t,probeStatus:"unavailable"},systemMetrics:{load:0,load5:0,load15:0,cpuUsedPct:0,cpus:Math.max(1,Number(e.infrastructure?.compute?.instances??1)),memUsedMb:0,memTotalMb:0,memAvailableMb:0,memCacheMb:0,swapUsedMb:0,swapTotalMb:0,diskUsedPct:0,diskUsedGb:0,diskTotalGb:a,inodeUsedPct:0,networkRxBytes:0,networkTxBytes:0,networkRxBytesPerSec:0,networkTxBytesPerSec:0,networkRxBytesToday:0,networkTxBytesToday:0,networkRxBytesMonth:0,networkTxBytesMonth:0,networkMonthKey:"",processes:0,uptimeSeconds:0},metricsUnavailable:!0,bandwidthBudgetBytes:u0(e),services:n,servicesDetail:n.map((d)=>({...d,since:$t,memMb:0,auto:!0})),backup:l0(e),backupHistory:[],workers:f0(e),serverScheduler:{enabled:!1,lastRun:"not configured"},serverDeployments:[],serverDeploymentsDetail:[],deploymentsEmptyReason:"No deployment history has been recorded yet. Future server deploys will write /var/www/<site>/.ts-cloud/deploy-history.log.",serverLogs:[],serverLogsEmptyReason:"Live server logs are unavailable until the dashboard can reach the compute box.",security:Sg(e),securityEmptyReason:"Live security checks are unavailable until the dashboard can reach the compute box.",sites:i,sitesDetail:i.map((d)=>{let c=e.sites?.[d.name]??{},o=Hr(c);return{...d,root:o==="server-static"?_n(e.project.slug,d.name):`${_n(e.project.slug,d.name)}/current`,branch:o==="server-static"?"build artifact":"main",build:c.build,php:c.php??c.phpVersion,aliases:Array.isArray(c.aliases)?c.aliases:[],redirects:c.redirects&&typeof c.redirects==="object"?c.redirects:{},envKeys:Object.keys(c.env??c.environment??{})}}),siteHealth:[],sshKeys:Sn(e.infrastructure?.compute?.sshKeys??[]),_serverReachable:!1,_metricsStatus:"unavailable"};return s.diagnostics=JR(e,s),s.activity=TR(s),s.topology=$n(s,{project:e.project.name,environment:t}),s}async function To(e,t,r={}){if(!e.infrastructure?.compute)return null;let n=null;try{n=nr({config:e})}catch{n=null}let i=null,a=0,s=[];if(n)try{if(s=await n.findComputeTargets({slug:e.project.slug,environment:t,role:"app"}),a=s.length,s.length){let h=(await n.runRemoteDeploy({targets:[s[0]],commands:d0({includeServices:!r.telemetryOnly,includeSites:r.includeSiteHealth!==!1,projectFilter:e.cloud?.attachTo?e.project.slug:void 0}),comment:`ts-cloud dashboard:build ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output;if(h)i=c0(h)}}catch{}let d=k0(e,t),c=(g,h=0)=>{let _=Number(g);return Number.isFinite(_)?_:h};if(d.server.os=i?.OS||d.server.os,d.server.uptime=i?.UPTIME||d.server.uptime,i){if(d.server.probeStatus="live",d.metricsUnavailable=!1,d._metricsStatus="live",d.systemMetrics={load:c(i.LOAD),load5:c(i.LOAD5),load15:c(i.LOAD15),cpuUsedPct:c(i.CPUUSED),cpus:c(i.CPUS,1),memUsedMb:c(i.MEMUSED),memTotalMb:c(i.MEMTOTAL,1),memAvailableMb:c(i.MEMAVAILABLE),memCacheMb:c(i.MEMCACHE),swapUsedMb:c(i.SWAPUSED),swapTotalMb:c(i.SWAPTOTAL),diskUsedPct:c(i.DISKPCT),diskUsedGb:c(i.DISKUSEDG),diskTotalGb:c(i.DISKTOTG,1),inodeUsedPct:c(i.INODEPCT),networkRxBytes:c(i.NETRX),networkTxBytes:c(i.NETTX),networkRxBytesPerSec:c(i.NETRXRATE),networkTxBytesPerSec:c(i.NETTXRATE),networkRxBytesToday:c(i.NETRXTODAY),networkTxBytesToday:c(i.NETTXTODAY),networkRxBytesMonth:c(i.NETRXMONTH),networkTxBytesMonth:c(i.NETTXMONTH),networkMonthKey:i.NETMONTHKEY||"",processes:c(i.PROCESSES),uptimeSeconds:c(i.UPTIME_SECONDS)},i.services.length){let g=[...new Map(i.services.map((h)=>[h.name,h])).values()];d.services=g.map((h)=>({name:h.name,status:h.status==="active"?"running":h.status})),d.servicesDetail=g.map((h)=>({name:h.name,status:h.status==="active"?"running":h.status,since:h.since&&h.since!==$t?h.since:d.server.uptime,memMb:Math.max(0,Math.round(Number(h.memBytes??0)/1024/1024)),auto:h.enabled?!["disabled","static","masked"].includes(h.enabled):!0}))}if(i.discoveredSites.length)d.sitesDetail=I0(d.sitesDetail,i.discoveredSites,e.project.slug),d.sites=d.sitesDetail.map((g)=>({name:g.name,project:g.project,managedBy:g.managedBy,route:g.route,href:g.href,domain:g.domain,path:g.path,kind:g.kind,type:g.type,runtime:g.runtime,deploy:g.deploy,tls:g.tls,status:g.status,httpStatus:g.httpStatus,responseMs:g.responseMs,tlsDaysRemaining:g.tlsDaysRemaining,checkedAt:g.checkedAt})),d.siteHealth=d.sitesDetail.map((g)=>({name:g.name,project:g.project,route:g.route,status:g.status,httpStatus:g.httpStatus,responseMs:g.responseMs,tlsDaysRemaining:g.tlsDaysRemaining,checkedAt:g.checkedAt}))}if(n&&s.length&&!r.telemetryOnly)await Promise.all([(async()=>{try{let g=Object.keys(e.sites??{}),_=(await n.runRemoteDeploy({targets:[s[0]],commands:m0(g,e.project.slug),comment:`ts-cloud dashboard:deploy-history ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",R=C0(_,e.sites);d.serverDeployments=R.slice(0,5),d.serverDeploymentsDetail=R.slice(0,50),d.deploymentsEmptyReason=R.length?void 0:"No deployment history was found on the server yet. Deploy again to populate this timeline."}catch{d.deploymentsEmptyReason="Deployment history could not be read from the server."}})(),(async()=>{try{let h=(await n.runRemoteDeploy({targets:[s[0]],commands:w0(e),comment:`ts-cloud dashboard:server-logs ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",_=A0(h);d.serverLogs=_,d.serverLogsEmptyReason=_.length?void 0:"No recent journal entries were found for the managed server units."}catch{d.serverLogsEmptyReason="Server logs could not be read from the box."}})(),(async()=>{try{let h=(await n.runRemoteDeploy({targets:[s[0]],commands:E0(e),comment:`ts-cloud dashboard:security ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",_=$0(h),R=Sg(e);if(!_.ports.length)_.ports=R.ports;if(!_.tlsCertificates.length)_.tlsCertificates=R.tlsCertificates;d.security=_,d.securityEmptyReason=void 0}catch{d.securityEmptyReason="Server security checks could not be read from the box."}})()]);else if(n&&a===0)d.deploymentsEmptyReason="No app server target was found for this environment.";let o=e.infrastructure?.compute?.sshKeys??e.infrastructure?.ssh?.keys??e.infrastructure?.sshKeys;if(Array.isArray(o)&&o.length)d.sshKeys=Sn(o);return d._serverReachable=a>0&&!!i,d.diagnostics=JR(e,d),d.activity=TR(d),d.topology=$n(d,{project:e.project.name,environment:t}),d}var b0=new Set(["singlestore","vitess"]);function jo(e){return b0.has(e)}var Wo={mysql:"/var/lib/pantry/mysql/mysqld.sock",mariadb:"/var/lib/pantry/mariadb/mariadbd.sock"};function Nr(e){return/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(e)}function v0(e){if(e==="postgres"||e==="pgsql")return"postgres";if(e==="mariadb")return"mariadb";if(e==="singlestore")return"singlestore";if(e==="vitess")return"vitess";return"mysql"}function Kn(e){let t=e.infrastructure?.compute,r=ht(e)?.engine;if(r)return v0(r);let n=t?.managedServices??{};if(n.postgres)return"postgres";if(n.mariadb)return"mariadb";return"mysql"}var _g=(e)=>e.replace(/`/g,"``"),Rr=(e)=>e.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),Zn=(e)=>`"${e.replace(/"/g,'""')}"`,zo=(e)=>`'${e.replace(/'/g,"''")}'`;function pg(e,t){return[`mysql --socket=${e==="mariadb"?Wo.mariadb:Wo.mysql} -u root <<'TS_CLOUD_SQL_EOF'`,...t,"TS_CLOUD_SQL_EOF"]}function Ig(e,t){return[`${Rg(t)} -tA <<'TS_CLOUD_PG_EOF'`,...e,"TS_CLOUD_PG_EOF"]}function O0(e,t){if(e==="vitess")return B0(t);if(e==="postgres")return Ig(["SELECT 'DB=' || datname FROM pg_database WHERE datistemplate = false;","SELECT 'USER=' || usename FROM pg_user;"],t);return pg(e,["SELECT CONCAT('DB=', schema_name) FROM information_schema.schemata WHERE schema_name NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys');","SELECT DISTINCT CONCAT('USER=', User) FROM mysql.user WHERE User NOT IN ('root', 'mysql.sys', 'mysql.session', 'mysql.infoschema', 'debian-sys-maint');"])}function Ni(e,t,r){let n=t?.host??"127.0.0.1",i=t?.username??"root",a=t?.password??"",s=t?.ssl===!1?"":" --ssl-mode=PREFERRED",d=(o)=>`'${String(o).replace(/'/g,"'\\''")}'`;return[`${a?`MYSQL_PWD=${d(a)} `:""}mysql -h ${d(n)} -P ${t?.port??r} -u ${d(i)}${s} --batch --skip-column-names <<'TS_CLOUD_SQL_EOF'`,...e,"TS_CLOUD_SQL_EOF"]}var Fi=15306;function B0(e){let t=Ni(["SHOW KEYSPACES;"],e,Fi);return t[0]=`${t[0]} | sed 's/^/DB=/'`,t}function J0(e){return Ni(["SHOW KEYSPACES;","SHOW VITESS_SHARDS;","SHOW VITESS_TABLETS;"],e,Fi)}function T0(e){let t=[],r=[],n=[];for(let i of e.split(`
340
+ `)){let a=i.trim();if(!a)continue;let s=a.split("\t").map((d)=>d.trim()).filter(Boolean);if(s.length>=6){let[d,c,o,g,h,_,R]=s;n.push({cell:d??"",keyspace:c??"",shard:o??"",type:g??"",state:h??"",alias:_??"",hostname:R??""});continue}if(s.length===1){let d=s[0];if(d.includes("/")){let[c,o]=d.split("/");if(c&&o)r.push({keyspace:c,shard:o})}else t.push(d)}}return{keyspaces:[...new Set(t)].filter(Boolean).sort(),shards:r,tablets:n}}function z0(e,t,r){if(e==="postgres")return Ig([`SELECT 'CREATE DATABASE ${Zn(t)}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = ${zo(t)})\\gexec`],r);return pg(e,[`CREATE DATABASE IF NOT EXISTS \`${_g(t)}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`])}function W0(e,t,r){let{username:n,password:i,database:a,access:s}=t;if(e==="postgres"){let o=["DO $$ BEGIN",` IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${zo(n)}) THEN CREATE ROLE ${Zn(n)} LOGIN PASSWORD ${zo(i)};`,` ELSE ALTER ROLE ${Zn(n)} LOGIN PASSWORD ${zo(i)}; END IF;`,"END $$;"];if(a)o.push(s==="readonly"?`GRANT CONNECT ON DATABASE ${Zn(a)} TO ${Zn(n)};`:`GRANT ALL PRIVILEGES ON DATABASE ${Zn(a)} TO ${Zn(n)};`);return Ig(o,r)}let d=s==="readonly"?"SELECT":"ALL PRIVILEGES",c=[`CREATE USER IF NOT EXISTS '${Rr(n)}'@'%' IDENTIFIED BY '${Rr(i)}';`,`CREATE USER IF NOT EXISTS '${Rr(n)}'@'localhost' IDENTIFIED BY '${Rr(i)}';`,`ALTER USER '${Rr(n)}'@'%' IDENTIFIED BY '${Rr(i)}';`,`ALTER USER '${Rr(n)}'@'localhost' IDENTIFIED BY '${Rr(i)}';`];if(a)c.push(`GRANT ${d} ON \`${_g(a)}\`.* TO '${Rr(n)}'@'%';`,`GRANT ${d} ON \`${_g(a)}\`.* TO '${Rr(n)}'@'localhost';`);return c.push("FLUSH PRIVILEGES;"),pg(e,c)}function j0(e){let t=[],r=[];for(let n of e.split(`
341
+ `)){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 Ct(e,t,r,n){let i;try{i=nr({config:e})}catch(c){return{ok:!1,error:`Could not initialize the cloud driver: ${c?.message??c}`}}let a=e.project.slug,s=await i.findComputeTargets({slug:a,environment:t,role:"app"});if(!s.length)return{ok:!1,error:"No app server target was found for this environment."};let d=await i.runRemoteDeploy({targets:[s[0]],commands:["set -uo pipefail",...r],comment:n,tags:{Project:a,Environment:t,Role:"app"}});return{ok:d.success,stdout:d.perInstance?.[0]?.output??"",stderr:d.perInstance?.[0]?.error??d.error??""}}function Uo(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 zR(e,t){let r=Kn(e);if(jo(r)&&r!=="vitess")return{...Uo(r,"Listing databases"),engine:r,databases:[],users:[]};let n=await Ct(e,t,O0(r,ht(e)),"ts-cloud db:list"),i=n.ok&&n.stdout?j0(n.stdout):{databases:[],users:[]};return{...n,engine:r,...i}}async function WR(e,t,r){let n=Kn(e);if(jo(n))return Uo(n,"Creating a database");return Ct(e,t,z0(n,r,ht(e)),`ts-cloud db:create ${r}`)}async function jR(e,t,r){let n=Kn(e);if(jo(n))return Uo(n,"Creating a database user");return Ct(e,t,W0(n,r,ht(e)),`ts-cloud db:user ${r.username}`)}var mg="/var/backups/ts-cloud/databases";function U0(e,t,r=mg,n){let i=`${r}/${t}-$(date +%Y%m%d-%H%M%S).sql.gz`,a=`mkdir -p ${r}`;if(e==="postgres")return[a,`${Rg(n,"pg_dump")} ${t} | gzip > "${i}"`,`echo "BACKUP=${i}"`,`ls -l "${i}"`];let s=e==="mariadb"?Wo.mariadb:Wo.mysql;return[a,`mysqldump --socket=${s} -u root ${t} | gzip > "${i}"`,`echo "BACKUP=${i}"`,`ls -l "${i}"`]}function H0(e=mg){return[`ls -1t ${e}/*.sql.gz 2>/dev/null | head -50 | sed 's|^|BACKUP=|' || true`]}function N0(e){let t=[];for(let r of e.split(`
342
+ `)){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 UR(e,t,r){if(!Nr(r))return{ok:!1,error:"Database name must be a valid identifier.",database:r};let n=Kn(e);if(jo(n))return{...Uo(n,"Backing up"),database:r};return{...await Ct(e,t,U0(n,r,mg,ht(e)),`ts-cloud db:backup ${r}`),database:r}}async function HR(e,t){let r=await Ct(e,t,H0(),"ts-cloud db:backups"),n=r.ok&&r.stdout?N0(r.stdout):[];return{...r,backups:n}}async function NR(e,t){let r=Kn(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 Ct(e,t,J0(ht(e)),"ts-cloud vitess:topology"),a=i.ok&&i.stdout?T0(i.stdout):n;return{...i,engine:r,...a}}function FR(e){return e.filter((t)=>t.state.toUpperCase()!=="SERVING")}function VR(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 Eg="/usr/local/bin/vtctldclient",F0="21.0.0";function No(e){return`'${String(e).split("'").join("'\\''")}'`}function Fo(e){return ht(e)?.vitess??{}}function LR(e){return/^[A-Za-z_][A-Za-z0-9_]{0,63}$/.test(e)}function V0(e){return/^[0-9a-f]{8}(?:_[0-9a-f]{4}){3}_[0-9a-f]{12}$/i.test(e)}function L0(e=F0){let t=No(e);return[`if ${Eg} --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" ${Eg}`,' rm -rf "$tmp"',` echo "installed vtctldclient ${e}"`,"fi"]}function xR(e){if(!e.vtctldAddr)return null;return`${Eg} --server ${No(e.vtctldAddr)}`}function x0(e,t,r={}){let n=xR(e);if(!n)return null;let i=r.sharded?" --sharded":"";return[`${n} CreateKeyspace${i} ${No(t)}`]}function M0(e,t,r){let n=xR(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" ${No(t)}`,'rm -f "$vschema_tmp"']}function Q0(e,t,r="vitess"){return Ni([`SET @@ddl_strategy='${r}';`,t.endsWith(";")?t:`${t};`],e,Fi)}function G0(e,t){let r=t?[`USE ${t.replace(/[^A-Z0-9_]/gi,"")};`,"SHOW VITESS_MIGRATIONS;"]:["SHOW VITESS_MIGRATIONS;"],n=Ni(r,e,Fi);return n[0]=n[0].replace(" --skip-column-names",""),n}function Z0(e){let t=e.split(`
343
+ `).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 a=[];for(let s of t.slice(1)){let d=s.split("\t"),c=(g)=>g>=0?(d[g]??"").trim():"",o=c(i.uuid);if(!o)continue;a.push({uuid:o,keyspace:c(i.keyspace),shard:c(i.shard),table:c(i.table),status:c(i.status),strategy:c(i.strategy),added:c(i.added),completed:c(i.completed),progress:c(i.progress)})}return a}function K0(e){return e.filter((t)=>t.status.toLowerCase()==="failed")}function Y0(e){return e.filter((t)=>["running","queued","ready"].includes(t.status.toLowerCase()))}function X0(e,t,r){let n=r.toUpperCase();return Ni([`ALTER VITESS_MIGRATION '${t}' ${n};`],e,Fi)}function Vi(e){if(Kn(e)!=="vitess")return{ok:!1,error:"The configured database engine is not Vitess."};return null}function Ho(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 MR(e,t){let r=Vi(e);if(r)return r;let n=Fo(e);return Ct(e,t,L0(n.clientVersion),"ts-cloud vitess:install-client")}async function QR(e,t,r,n={}){let i=Vi(e);if(i)return{...i,keyspace:r};if(!LR(r))return{ok:!1,error:"Keyspace name must be a valid identifier.",keyspace:r};let a=Fo(e),s=Ho(a);if(s)return{...s,keyspace:r};let d=x0(a,r,n);if(!d)return{...Ho({}),keyspace:r};return{...await Ct(e,t,d,`ts-cloud vitess:create-keyspace ${r}`),keyspace:r}}async function GR(e,t,r,n){let i=Vi(e);if(i)return{...i,keyspace:r};if(!LR(r))return{ok:!1,error:"Keyspace name must be a valid identifier.",keyspace:r};try{let o=JSON.parse(n);if(!o||typeof o!=="object")return{ok:!1,error:"The VSchema must be a JSON object.",keyspace:r}}catch(o){return{ok:!1,error:`The VSchema is not valid JSON: ${o?.message??o}`,keyspace:r}}let a=Fo(e),s=Ho(a);if(s)return{...s,keyspace:r};let d=M0(a,r,n);if(!d)return{...Ho({}),keyspace:r};return{...await Ct(e,t,d,`ts-cloud vitess:apply-vschema ${r}`),keyspace:r}}async function ZR(e,t,r){let n=Vi(e);if(n)return n;if(!r.trim())return{ok:!1,error:"No SQL was provided."};let i=Fo(e);return Ct(e,t,Q0(ht(e),r,i.ddlStrategy??"vitess"),"ts-cloud vitess:apply-schema")}async function KR(e,t,r){let n=Vi(e);if(n)return{...n,migrations:[],failed:[],running:[]};let i=await Ct(e,t,G0(ht(e),r),"ts-cloud vitess:migrations"),a=i.ok&&i.stdout?Z0(i.stdout):[];return{...i,migrations:a,failed:K0(a),running:Y0(a)}}async function YR(e,t,r,n){let i=Vi(e);if(i)return{...i,uuid:r};if(!V0(r))return{ok:!1,error:"Migration UUID is not in the expected format.",uuid:r};return{...await Ct(e,t,X0(ht(e),r,n),`ts-cloud vitess:migration ${n} ${r}`),uuid:r}}function q0(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 e$(e,t){let r=t.keyspace.trim(),n=t.username.trim(),i=t.password,a=q0(e);if(a)throw Error(a);if(!Nr(r))throw Error("Keyspace must contain letters, numbers, or underscores and cannot start with a number.");if(!Nr(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:[...XR(),...qR(s)]}}async function ep(e,t,r){let n=e$(e,r);return{...await Ct(e,t,n.commands,`ts-cloud vitess:provision ${n.appDatabase.name}`),database:n.appDatabase,service:Object.fromEntries(Object.entries(n.service).filter(([a])=>a!=="password"))}}var t$={capability:"runtime:terminal",scope:"organization"};var r$={"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 yg(e,t){return r$[`${e.toUpperCase()} ${t}`]??t$}import{createHmac as n$,randomBytes as i$,timingSafeEqual as a$}from"node:crypto";import{chmodSync as s$,existsSync as o$,mkdirSync as d$,readFileSync as c$,writeFileSync as l$}from"node:fs";import{dirname as g$}from"node:path";var Oa="ts_cloud_session";var u$=28800000;function tp(e){let t=process.env.TS_CLOUD_DASHBOARD_SECRET?.trim();if(t)return t;let r=_t(e,"dashboard-secret");try{if(o$(r)){let i=c$(r,"utf8").trim();if(i)return i}}catch{}let n=i$(32).toString("base64url");try{d$(g$(r),{recursive:!0}),l$(r,`${n}
344
+ `),s$(r,384)}catch{}return n}function h$(e,t){return n$("sha256",t).update(e).digest("base64url")}function rp(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),a=h$(n,t),s=Buffer.from(i),d=Buffer.from(a);if(s.length!==d.length||!a$(s,d))return null;try{let c=JSON.parse(Buffer.from(n,"base64url").toString("utf8"));if(typeof c?.u!=="string"||typeof c?.exp!=="number")return null;if(c.mv!==void 0&&(!c.mv||typeof c.mv!=="object"||Array.isArray(c.mv)||Object.values(c.mv).some((o)=>!Number.isInteger(o)||o<1)))return null;if(Date.now()>=c.exp)return null;return c}catch{return null}}function wg(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 Li(e,t={secure:!0}){let r=Math.floor((t.maxAgeMs??u$)/1000),n=[`${Oa}=${encodeURIComponent(e)}`,"Path=/","HttpOnly","SameSite=Lax",`Max-Age=${r}`];if(t.secure)n.push("Secure");return n.join("; ")}function Vo(e={secure:!0}){let t=[`${Oa}=`,"Path=/","HttpOnly","SameSite=Lax","Max-Age=0"];if(e.secure)t.push("Secure");return t.join("; ")}import{chmodSync as f$,existsSync as S$,mkdirSync as _$,readFileSync as R$,writeFileSync as p$}from"node:fs";import{dirname as I$}from"node:path";function np(){return fa("dashboard-users.json")}function Lo(e){return/^[a-z0-9][a-z0-9._-]{1,31}$/i.test(e)}function m$(e){if(!e||typeof e.username!=="string"||!Lo(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 E$(e){try{let t=JSON.parse(e);if(!Array.isArray(t?.users))return[];return t.users.map(m$).filter((r)=>r!==null)}catch{return[]}}function ip(e){return _t(e,"dashboard-users.json")}function kt(e){let t=ip(e);if(!S$(t))return[];try{return E$(R$(t,"utf8"))}catch{return[]}}function xo(e,t){let r=ip(e);_$(I$(r),{recursive:!0}),p$(r,`${JSON.stringify({users:t},null,2)}
345
+ `),f$(r,384)}function Zt(e,t){let r=t.trim().toLowerCase();return e.find((n)=>n.username.toLowerCase()===r)}function ap(e,t="admin"){let r=kt(e);if(r.some((s)=>s.role==="admin"))return{users:r};let n=process.env.TS_CLOUD_UI_PASSWORD?.trim()||lg(),i={username:t,passwordHash:fn(n),role:"admin",sites:{},name:"Administrator",createdAt:new Date().toISOString()},a=[...r,i];return xo(e,a),{users:a,generated:{username:t,password:n}}}function Ba(e,t){let r=kt(e),n=Zt(r,t.username),i=t.password?.trim()||(n?void 0:lg()),a={username:n?.username??t.username,passwordHash:i?fn(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((d)=>d.username.toLowerCase()===a.username.toLowerCase()?a:d):[...r,a];return xo(e,s),{user:a,password:i}}function Mo(e,t,r){let n=kt(e),i=Zt(n,t);if(!i)throw Error("Authentication user was not found");let a={...i,passwordHash:r};return xo(e,n.map((s)=>s.username.toLowerCase()===i.username.toLowerCase()?a:s)),a}function Ag(e,t){let r=kt(e),n=Zt(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 xo(e,r.filter((i)=>i.username.toLowerCase()!==n.username.toLowerCase())),{ok:!0}}function xi(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 y$={username:"local",passwordHash:"",role:"admin",sites:{},name:"Local (auth disabled)"};function sp(e){let{cwd:t,enabled:r,secret:n,authorization:i,authentication:a}=e,s=(c)=>{if(!a)return;let o=wg(c.headers.get("cookie"),Oa);return o?.startsWith("v2.")?a.verifySessionToken(o):void 0},d=(c)=>{let o=i.store.getActorByExternalId("user",`dashboard:${c.username.toLowerCase()}`),g=o?i.store.getMembershipForActor(i.organizationId,o.id):void 0;return{actor:o,membership:g}};return{enabled:r,resolveUser(c){if(!r)return y$;let o=wg(c.headers.get("cookie"),Oa),g=s(c),h=g?void 0:rp(o,n),_=g?.identity.username??h?.u;if(!_)return null;let R=Zt(kt(t),_);if(!R)return null;let{membership:E}=d(R);if(!E||E.status!=="active"||!g&&h?.mv?.[i.organizationId]!==E.sessionVersion)return null;if(!E.lastActiveAt||Date.now()-new Date(E.lastActiveAt).getTime()>300000)i.store.touchMembership(E.id);return R},resolveSession(c){return s(c)?.session??null},check(c,o,g,h){if(!r)return{ok:!0};if(!g)return{ok:!1,status:401,error:"Sign in to continue.",unauthenticated:!0};let _=yg(c.method,o);if(_.anyUser)return{ok:!0};if(_.siteFrom==="body"&&!h)return{ok:!1,status:400,error:"This request must name a site."};let{membership:R}=d(g);if(!R)return{ok:!1,status:401,error:"Sign in to continue.",unauthenticated:!0};let E=_.scope==="organization"?{organizationId:i.organizationId}:i.store.resolveAuthorizationTarget(i.organizationId,{type:"project",id:i.projectId});if(_.scope==="site"){let $=new URL(c.url).searchParams.get("env")??i.defaultEnvironment,b=i.store.getEnvironmentBySlug(i.projectId,$),z=i.store.listResources(i.projectId,b?.id).find((C)=>C.kind==="application"&&C.slug===h);E=z?i.store.resolveAuthorizationTarget(i.organizationId,{type:"resource",id:z.id}):void 0}if(!(E?qt({membership:R,grants:i.store.listGrants(R.id),capability:_.capability,target:E}):{allowed:!1}).allowed)return{ok:!1,status:403,error:"You do not have access to this."};return{ok:!0}}}}async function op(e,t){if(yg(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 w$}from"node:crypto";function dp(e,t,r){for(let n of r){let i=Ke(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 A$(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)&&!Zt(t,i))return i;let a=w$("sha256").update(r).digest("hex").slice(0,7);return`${i.slice(0,24)}-${a}`}function cp(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),a=i?e.getIdentity(i.identityId):e.getIdentityByEmail(n.email);if(a?.disabledAt)throw Error("OIDC identity is disabled");if(!i&&a&&!a.emailVerifiedAt)throw Error("OIDC cannot automatically link an unverified local email address");let s=kt(r),d=!1,c=a?Zt(s,a.username):void 0;if(a&&!c)throw Error("OIDC identity has no dashboard user");if(!a){let h=A$(e,s,n.email);c=Ba(r,{username:h,name:n.name,email:n.email,sites:{}}).user;let R=Ke(t.store,c);a=e.createIdentity({actorId:R.id,username:c.username,email:n.email,emailVerified:!0,passwordHash:c.passwordHash}),d=!0}else if(a.email!==n.email)a=e.setVerifiedEmail(a.id,n.email);let o=t.store.getActor(a.actorId);if(!o)throw Error("OIDC identity actor was not found");let g=t.store.getMembershipForActor(t.organization.id,o.id);if(g?.status==="revoked")throw Error("OIDC organization membership is revoked");if(!g)t.store.createMembership({organizationId:t.organization.id,actorId:o.id,roleTemplate:n.provider.defaultRole,scope:{type:"organization"},source:"manual"});return e.linkOidcSubject(n.provider.id,a.id,n.subject,n.email),{identity:a,user:c,provisioned:d}}function lp(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((a)=>a.enforceSso&&!!i&&a.allowedDomains.includes(i))}function P$(e){return e.replace(/[&<>"']/g,(t)=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}function gp(e=!1,t=[]){let r=e?"/serverless":"/",n=t.map((a)=>`<a class="sso-button" href="/auth/oidc/${encodeURIComponent(a.slug)}/start?return=${encodeURIComponent(r)}">Continue with ${P$(a.name)}</a>`).join("");return`<!doctype html>
346
+ <html lang="en">
347
+ <head>
348
+ <meta charset="UTF-8">
349
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
350
+ <title>Sign in · ts-cloud</title>
351
+ <link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect x='3' y='3' width='26' height='26' rx='8' fill='%235a8be0'/%3E%3C/svg%3E">
352
+ <link rel="preconnect" href="https://fonts.googleapis.com">
353
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
354
+ <style>${`
355
+ :root {
356
+ --bg: #0a0e15; --bg2: #0b0f18; --panel: rgba(255,255,255,0.03); --panel-br: rgba(255,255,255,0.072);
357
+ --txt: #e9edf5; --txt2: #94a1b8; --txt3: #5a6577;
358
+ --accent: #5a8be0; --accent-ink: #061019;
359
+ --bad: #f0736e; --badbg: rgba(240,115,110,0.11);
360
+ }
361
+ * { box-sizing: border-box; margin: 0; padding: 0; }
362
+ html { background: var(--bg); min-height: 100%; }
363
+ body {
364
+ font-family: 'Inter', system-ui, sans-serif; color: var(--txt); min-height: 100vh;
365
+ background:
366
+ radial-gradient(900px 460px at 88% -8%, rgba(90,139,224,0.06), transparent 62%),
367
+ linear-gradient(175deg, var(--bg), var(--bg2));
368
+ -webkit-font-smoothing: antialiased;
369
+ display: grid; place-items: center; padding: 24px;
370
+ }
371
+ .card {
372
+ width: 100%; max-width: 380px;
373
+ background: var(--panel); border: 1px solid var(--panel-br); border-radius: 16px;
374
+ padding: 32px; backdrop-filter: blur(6px);
375
+ animation: rise .5s cubic-bezier(0.16, 1, 0.3, 1) both;
376
+ }
377
+ @keyframes rise { from { opacity: 0; transform: translateY(8px) } to { opacity: 1; transform: none } }
378
+ @media (prefers-reduced-motion: reduce) { .card { animation: none } }
379
+ .brand { display: flex; align-items: center; gap: 10px; font-weight: 700; font-size: 17px; letter-spacing: -0.02em; }
380
+ .brand .dot { width: 20px; height: 20px; border-radius: 6px; background: var(--accent); box-shadow: inset 0 1px 0 rgba(255,255,255,0.35); }
381
+ h1 { font-size: 21px; font-weight: 800; letter-spacing: -0.02em; margin-top: 22px; }
382
+ .sub { color: var(--txt2); font-size: 13.5px; margin-top: 5px; line-height: 1.5; }
383
+ form { margin-top: 24px; display: grid; gap: 14px; }
384
+ .field { display: flex; flex-direction: column; gap: 7px; }
385
+ label { color: var(--txt3); font-size: 11px; font-weight: 800; text-transform: uppercase; letter-spacing: 0.07em; }
386
+ input {
387
+ width: 100%; background: rgba(255,255,255,0.05); border: 1px solid var(--panel-br); border-radius: 10px;
388
+ padding: 10px 12px; color: var(--txt); font-family: inherit; font-size: 14px;
389
+ }
390
+ input:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px rgba(90,139,224,0.12); }
391
+ button {
392
+ margin-top: 4px; background: var(--accent); color: var(--accent-ink); border: 0; border-radius: 10px;
393
+ padding: 11px 16px; font-weight: 700; font-size: 13.5px; cursor: pointer; font-family: inherit;
394
+ transition: filter .12s, transform .12s;
395
+ }
396
+ button:hover { filter: brightness(1.06); }
397
+ button:active { transform: translateY(1px); }
398
+ button[disabled] { opacity: 0.6; cursor: default; }
399
+ .msg {
400
+ display: none; margin-top: 14px; padding: 10px 12px; border-radius: 10px;
401
+ background: var(--badbg); border: 1px solid rgba(240,115,110,0.22); color: var(--bad);
402
+ font-size: 13px; line-height: 1.45;
403
+ }
404
+ .msg.shown { display: block; }
405
+ .hidden { display: none !important; }
406
+ .note { color: var(--txt3); font-size: 12px; margin-top: 20px; line-height: 1.5; }
407
+ .note code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; color: var(--txt2); }
408
+ a { color: var(--accent); text-decoration: none; }
409
+ a:hover { text-decoration: underline; }
410
+ .sso { display: grid; gap: 10px; margin-top: 22px; }
411
+ .sso-button { display: block; border: 1px solid var(--panel-br); border-radius: 10px; padding: 11px 14px; color: var(--txt); text-align: center; font-size: 13.5px; font-weight: 700; background: rgba(255,255,255,0.04); }
412
+ .sso-button:hover { border-color: var(--accent); text-decoration: none; }
413
+ .separator { display: flex; align-items: center; gap: 10px; margin: 18px 0 -6px; color: var(--txt3); font-size: 10px; font-weight: 800; text-transform: uppercase; letter-spacing: .06em; }
414
+ .separator::before, .separator::after { content: ''; height: 1px; flex: 1; background: var(--panel-br); }
415
+ `}</style>
416
+ </head>
417
+ <body>
418
+ <main class="card">
419
+ <div class="brand"><span class="dot"></span> ts-cloud</div>
420
+ <h1>Sign in</h1>
421
+ <p class="sub">Manage the sites you have been given access to.</p>
422
+
423
+ ${t.length>0?`<div class="sso" aria-label="Single sign-on">${n}</div><div class="separator"><span>or use local recovery</span></div>`:""}
424
+
425
+ <form id="login" autocomplete="on">
426
+ <div class="field">
427
+ <label for="username">Username</label>
428
+ <input id="username" name="username" autocomplete="username" required autofocus>
429
+ </div>
430
+ <div class="hidden field" id="mfa-field">
431
+ <label for="mfa-code">Authenticator or recovery code</label>
432
+ <input id="mfa-code" name="mfa-code" autocomplete="one-time-code">
433
+ </div>
434
+ <div class="field">
435
+ <label for="password">Password</label>
436
+ <input id="password" name="password" type="password" autocomplete="current-password" required>
437
+ </div>
438
+ <button type="submit" id="submit">Sign in</button>
439
+ </form>
440
+
441
+ <p class="msg" id="msg" role="alert" aria-live="polite"></p>
442
+ <p class="note"><a href="/forgot-password">Forgot your password?</a></p>
443
+ </main>
444
+
445
+ <script>
446
+ const form = document.getElementById('login')
447
+ const msg = document.getElementById('msg')
448
+ const submit = document.getElementById('submit')
449
+ const mfaField = document.getElementById('mfa-field')
450
+ const mfaCode = document.getElementById('mfa-code')
451
+ let challengeToken = ''
452
+
453
+ if (new URLSearchParams(location.search).has('sso_error')) {
454
+ msg.textContent = 'Single sign-on could not be completed. Try again or use the local recovery path.'
455
+ msg.classList.add('shown')
456
+ }
457
+
458
+ form.addEventListener('submit', async (event) => {
459
+ event.preventDefault()
460
+ msg.classList.remove('shown')
461
+ submit.disabled = true
462
+ submit.textContent = 'Signing in...'
463
+ try {
464
+ const res = await fetch(challengeToken ? '/api/auth/mfa/complete' : '/api/login', {
465
+ method: 'POST',
466
+ headers: { 'content-type': 'application/json' },
467
+ body: JSON.stringify(challengeToken
468
+ ? { challengeToken, code: mfaCode.value }
469
+ : { username: document.getElementById('username').value, password: document.getElementById('password').value }),
470
+ })
471
+ const body = await res.json().catch(() => ({}))
472
+ if (!res.ok || !body.ok) throw new Error(body.error || 'Could not sign in.')
473
+ if (body.mfaRequired) {
474
+ challengeToken = body.challengeToken
475
+ mfaField.classList.remove('hidden')
476
+ mfaCode.required = true
477
+ document.getElementById('username').readOnly = true
478
+ document.getElementById('password').readOnly = true
479
+ submit.disabled = false
480
+ submit.textContent = 'Verify and sign in'
481
+ mfaCode.focus()
482
+ return
483
+ }
484
+ location.href = ${JSON.stringify(r)}
485
+ } catch (error) {
486
+ msg.textContent = (error && error.message) || String(error)
487
+ msg.classList.add('shown')
488
+ submit.disabled = false
489
+ submit.textContent = 'Sign in'
490
+ if (challengeToken) {
491
+ mfaCode.value = ''
492
+ mfaCode.focus()
493
+ }
494
+ else {
495
+ document.getElementById('password').value = ''
496
+ document.getElementById('password').focus()
497
+ }
498
+ }
499
+ })
500
+ </script>
501
+ </body>
502
+ </html>`}function up(e){let t=e==="reset";return`<!doctype html>
503
+ <html lang="en">
504
+ <head>
505
+ <meta charset="UTF-8">
506
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
507
+ <title>${t?"Choose a new password":"Recover your account"} · ts-cloud</title>
508
+ <style>${`
509
+ :root {
510
+ --bg: #0a0e15; --bg2: #0b0f18; --panel: rgba(255,255,255,0.03); --panel-br: rgba(255,255,255,0.072);
511
+ --txt: #e9edf5; --txt2: #94a1b8; --txt3: #5a6577;
512
+ --accent: #5a8be0; --accent-ink: #061019;
513
+ --bad: #f0736e; --badbg: rgba(240,115,110,0.11);
514
+ }
515
+ * { box-sizing: border-box; margin: 0; padding: 0; }
516
+ html { background: var(--bg); min-height: 100%; }
517
+ body {
518
+ font-family: 'Inter', system-ui, sans-serif; color: var(--txt); min-height: 100vh;
519
+ background:
520
+ radial-gradient(900px 460px at 88% -8%, rgba(90,139,224,0.06), transparent 62%),
521
+ linear-gradient(175deg, var(--bg), var(--bg2));
522
+ -webkit-font-smoothing: antialiased;
523
+ display: grid; place-items: center; padding: 24px;
524
+ }
525
+ .card {
526
+ width: 100%; max-width: 380px;
527
+ background: var(--panel); border: 1px solid var(--panel-br); border-radius: 16px;
528
+ padding: 32px; backdrop-filter: blur(6px);
529
+ animation: rise .5s cubic-bezier(0.16, 1, 0.3, 1) both;
530
+ }
531
+ @keyframes rise { from { opacity: 0; transform: translateY(8px) } to { opacity: 1; transform: none } }
532
+ @media (prefers-reduced-motion: reduce) { .card { animation: none } }
533
+ .brand { display: flex; align-items: center; gap: 10px; font-weight: 700; font-size: 17px; letter-spacing: -0.02em; }
534
+ .brand .dot { width: 20px; height: 20px; border-radius: 6px; background: var(--accent); box-shadow: inset 0 1px 0 rgba(255,255,255,0.35); }
535
+ h1 { font-size: 21px; font-weight: 800; letter-spacing: -0.02em; margin-top: 22px; }
536
+ .sub { color: var(--txt2); font-size: 13.5px; margin-top: 5px; line-height: 1.5; }
537
+ form { margin-top: 24px; display: grid; gap: 14px; }
538
+ .field { display: flex; flex-direction: column; gap: 7px; }
539
+ label { color: var(--txt3); font-size: 11px; font-weight: 800; text-transform: uppercase; letter-spacing: 0.07em; }
540
+ input {
541
+ width: 100%; background: rgba(255,255,255,0.05); border: 1px solid var(--panel-br); border-radius: 10px;
542
+ padding: 10px 12px; color: var(--txt); font-family: inherit; font-size: 14px;
543
+ }
544
+ input:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px rgba(90,139,224,0.12); }
545
+ button {
546
+ margin-top: 4px; background: var(--accent); color: var(--accent-ink); border: 0; border-radius: 10px;
547
+ padding: 11px 16px; font-weight: 700; font-size: 13.5px; cursor: pointer; font-family: inherit;
548
+ transition: filter .12s, transform .12s;
549
+ }
550
+ button:hover { filter: brightness(1.06); }
551
+ button:active { transform: translateY(1px); }
552
+ button[disabled] { opacity: 0.6; cursor: default; }
553
+ .msg {
554
+ display: none; margin-top: 14px; padding: 10px 12px; border-radius: 10px;
555
+ background: var(--badbg); border: 1px solid rgba(240,115,110,0.22); color: var(--bad);
556
+ font-size: 13px; line-height: 1.45;
557
+ }
558
+ .msg.shown { display: block; }
559
+ .hidden { display: none !important; }
560
+ .note { color: var(--txt3); font-size: 12px; margin-top: 20px; line-height: 1.5; }
561
+ .note code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; color: var(--txt2); }
562
+ a { color: var(--accent); text-decoration: none; }
563
+ a:hover { text-decoration: underline; }
564
+ .sso { display: grid; gap: 10px; margin-top: 22px; }
565
+ .sso-button { display: block; border: 1px solid var(--panel-br); border-radius: 10px; padding: 11px 14px; color: var(--txt); text-align: center; font-size: 13.5px; font-weight: 700; background: rgba(255,255,255,0.04); }
566
+ .sso-button:hover { border-color: var(--accent); text-decoration: none; }
567
+ .separator { display: flex; align-items: center; gap: 10px; margin: 18px 0 -6px; color: var(--txt3); font-size: 10px; font-weight: 800; text-transform: uppercase; letter-spacing: .06em; }
568
+ .separator::before, .separator::after { content: ''; height: 1px; flex: 1; background: var(--panel-br); }
569
+ `}</style>
570
+ </head>
571
+ <body>
572
+ <main class="card">
573
+ <div class="brand"><span class="dot"></span> ts-cloud</div>
574
+ <h1>${t?"Choose a new password":"Recover your account"}</h1>
575
+ <p class="sub">${t?"This one-time link expires after one hour.":"Enter your username or verified email. The response is the same whether or not an account exists."}</p>
576
+ <form id="recovery" autocomplete="on">
577
+ ${t?'<div class="field"><label for="password">New password</label><input id="password" name="password" type="password" autocomplete="new-password" minlength="12" required></div><div class="field"><label for="confirmation">Confirm new password</label><input id="confirmation" name="confirmation" type="password" autocomplete="new-password" minlength="12" required></div>':'<div class="field"><label for="identifier">Username or email</label><input id="identifier" name="identifier" autocomplete="username" required autofocus></div>'}
578
+ <button type="submit" id="submit">${t?"Change password":"Send reset link"}</button>
579
+ </form>
580
+ <p class="msg" id="msg" role="status" aria-live="polite"></p>
581
+ <p class="note"><a href="/login">Return to sign in</a></p>
582
+ </main>
583
+ <script>
584
+ const form = document.getElementById('recovery')
585
+ const msg = document.getElementById('msg')
586
+ const submit = document.getElementById('submit')
587
+ const reset = ${JSON.stringify(t)}
588
+ const token = new URLSearchParams(location.search).get('token') || ''
589
+ if (reset && !token) {
590
+ msg.textContent = 'This reset link is missing its token. Request a new link.'
591
+ msg.classList.add('shown')
592
+ submit.disabled = true
593
+ }
594
+ form.addEventListener('submit', async (event) => {
595
+ event.preventDefault()
596
+ if (reset && document.getElementById('password').value !== document.getElementById('confirmation').value) {
597
+ msg.textContent = 'The passwords do not match.'
598
+ msg.classList.add('shown')
599
+ return
600
+ }
601
+ submit.disabled = true
602
+ msg.textContent = reset ? 'Changing password…' : 'Requesting reset link…'
603
+ msg.classList.add('shown')
604
+ const response = await fetch(reset ? '/api/auth/password-reset/complete' : '/api/auth/password-reset/request', {
605
+ method: 'POST',
606
+ headers: { 'content-type': 'application/json' },
607
+ body: JSON.stringify(reset
608
+ ? { token, password: document.getElementById('password').value }
609
+ : { identifier: document.getElementById('identifier').value }),
610
+ })
611
+ const result = await response.json().catch(() => ({}))
612
+ msg.textContent = result.message || result.error || 'The request could not be completed.'
613
+ if (!response.ok) {
614
+ submit.disabled = false
615
+ return
616
+ }
617
+ if (reset)
618
+ setTimeout(() => location.assign('/login'), 1200)
619
+ })
620
+ </script>
621
+ </body>
622
+ </html>`}var _p={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};async function Rp(e){return await e.driver.findComputeTargets({slug:e.slug,environment:e.environment,role:e.role||"app"})}async function pp(e,t){let r=e.logger||_p,n=await Rp(e);if(n.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};let i=_n(e.slug,t.siteName),a=fp(i,t.to||"unused"),s=["set -uo pipefail",...Sp(a,{...t.to?{to:t.to}:{},unitBase:`${e.slug}-${t.siteName}`}),`(cd ${Ja} && pantry restart php-fpm) 2>/dev/null || true`,`(cd ${a.current} && eval "$(cd ${Ja} && pantry env 2>/dev/null)" && php artisan queue:restart) 2>/dev/null || true`];r.step(`Rolling back ${t.siteName}${t.to?` to ${t.to}`:" to the previous release"} on ${n.length} server(s)...`);let d=await e.driver.runRemoteDeploy({targets:n,commands:s,comment:`ts-cloud rollback ${e.slug}/${t.siteName}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});if(!d.success)r.error(`Rollback failed: ${d.error||"unknown error"}`);else r.success(`Rolled back ${t.siteName}.`);return{success:d.success,error:d.error,perInstance:d.perInstance}}async function Ip(e,t){let r=e.logger||_p;if(!t.database?.name)return{success:!1,error:"No appDatabase configured to restore."};let n=await Rp(e);if(n.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};r.step(`Restoring database '${t.database.name}'${t.from?` from ${t.from}`:" from the latest backup"} on ${n.length} server(s)...`);let i=await e.driver.runRemoteDeploy({targets:n,commands:hp(t.database,{from:t.from}),comment:`ts-cloud db:restore ${e.slug}/${t.database.name}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});if(!i.success)r.error(`Restore failed: ${i.error||"unknown error"}`);else r.success(`Restored ${t.database.name}.`);return{success:i.success,error:i.error,perInstance:i.perInstance}}var D$=["restart","reload","start","stop","enable","disable"],mp=65536;function Mi(e){return e.length<=mp?e:`${e.slice(0,mp)}
623
+
624
+ [output truncated]`}function $$(e){return/^[A-Za-z0-9_.@:-]+$/.test(e)}function Pg(e){return/^[A-Za-z0-9_-]+$/.test(e)}function C$(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Go(e,t){let r=[],n=t.servicesDetail??t.services??[];for(let s of n){let d=String(s?.name??"");if(!d||!$$(d))continue;for(let c of D$)r.push({id:`${c}:${d}`,label:`${C$(c)} ${d}`,group:"service",target:d,mutates:!0,confirm:d,danger:c==="stop"||c==="disable"})}for(let[s,d]of Object.entries(e.sites??{})){if(!d||!Pg(s))continue;let c=Hr(d);if(c==="server-app"||c==="server-php")r.push({id:`rollback:${s}`,label:`Rollback ${s}`,group:"deploy",target:s,mutates:!0,confirm:s,danger:!0})}let i=new Set;for(let s of t.workers??[]){let d=String(s?.name??"").split(":")[0];if(d&&Pg(d))i.add(d)}for(let s of i)r.push({id:`worker:restart:${s}`,label:`Restart workers (${s})`,group:"worker",target:s,mutates:!0,confirm:s});for(let[s,d]of Object.entries(e.sites??{})){if(!d||!Pg(s))continue;if(d.scheduler||d.schedule){let c=Qo(d)==="laravel";r.push({id:`scheduler:run:${s}`,label:`${c?"Run":"Restart"} scheduler (${s})`,group:"scheduler",target:s,mutates:!0,confirm:s})}}if(e.infrastructure?.compute?.backups?.enabled){if(r.push({id:"backup:run",label:"Run backup now",group:"backup",target:"backup",mutates:!0,confirm:"backup"}),ht(e))r.push({id:"backup:restore",label:"Restore latest DB backup",group:"backup",target:"database",mutates:!0,confirm:"restore",danger:!0})}return r}function $g(e,t,r){return Go(t,r).find((n)=>n.id===e)}function k$(e,t){let r=e==="enable"||e==="disable"?`systemctl is-enabled ${t} 2>/dev/null || true`:`systemctl is-active ${t} 2>/dev/null || true`;return["set -o pipefail",`systemctl ${e} ${t}`,r]}function b$(){return`eval "$(cd ${Ja} && pantry env 2>/dev/null)"`}function yp(e,t,r){let n=`${_n(e,t)}/current`;return["set -uo pipefail",`[ -d ${n} ] || { echo "site ${t} has no current release" >&2; exit 1; }`,`cd ${n} && ${b$()} && php artisan ${r}`]}function v$(e,t,r){if(e==="laravel")return yp(t,r,"queue:restart");let n=`${t}-${r}-queue-*.service`;return["set -uo pipefail",`units=$(systemctl list-units --type=service --all --no-legend '${n}' 2>/dev/null | awk '{print $1}')`,`[ -n "$units" ] || { echo "no queue-worker units found for ${r} (${n})" >&2; exit 1; }`,"systemctl restart $units",`systemctl --no-legend --type=service list-units '${n}' 2>/dev/null || true`]}function O$(e,t,r){if(e==="laravel")return yp(t,r,"schedule:run");let n=`${t}-${r}-scheduler.service`;return["set -uo pipefail",`systemctl restart ${n}`,`systemctl is-active ${n} 2>/dev/null || true`]}function B$(){return["set -uo pipefail",`[ -x ${Dg} ] || { echo "scheduled backups are not provisioned on this server" >&2; exit 1; }`,Dg]}function Ep(e,t,r){return{operation:e,command:t,ok:r.success,stdout:Mi(r.perInstance?.[0]?.output??""),stderr:Mi(r.perInstance?.[0]?.error??r.error??"")}}async function Zo(e,t,r,n={}){let i=e.project.slug,a;try{a=nr({config:e})}catch(h){return{operation:r.id,ok:!1,error:`Could not initialize the cloud driver: ${h?.message??h}`}}let s={driver:a,slug:i,environment:t,role:"app"};if(r.group==="deploy"){let h=n.to&&/^[A-Za-z0-9._-]+$/.test(n.to)?n.to:void 0,_=await pp(s,{siteName:r.target,to:h});return Ep(r.id,`rollback ${r.target}${h?` → ${h}`:""}`,_)}if(r.id==="backup:restore"){let h=await Ip(s,{database:ht(e)});return Ep(r.id,"db restore",h)}let d=await a.findComputeTargets({slug:i,environment:t,role:"app"});if(!d.length)return{operation:r.id,ok:!1,error:"No app server target was found for this environment."};let c,o;if(r.group==="service"){let[h,..._]=r.id.split(":");c=k$(h,_.join(":")),o=`systemctl ${h} ${r.target}`}else if(r.group==="worker"){let h=Qo(e.sites?.[r.target]??{});c=v$(h,i,r.target),o=h==="laravel"?`queue:restart (${r.target})`:`restart queue units (${r.target})`}else if(r.group==="scheduler"){let h=Qo(e.sites?.[r.target]??{});c=O$(h,i,r.target),o=h==="laravel"?`schedule:run (${r.target})`:`restart scheduler (${r.target})`}else if(r.id==="backup:run")c=B$(),o="ts-cloud backup";else return{operation:r.id,ok:!1,error:"Unknown operation."};let g=await a.runRemoteDeploy({targets:[d[0]],commands:c,comment:`ts-cloud dashboard:${r.id}`,tags:{Project:i,Environment:t,Role:"app"}});return{operation:r.id,command:o,ok:g.success,stdout:Mi(g.perInstance?.[0]?.output??""),stderr:Mi(g.perInstance?.[0]?.error??g.error??"")}}async function Ta(e,t,r){let n=r.trim();if(!n)return{operation:"command",ok:!1,error:"A command is required."};let i;try{i=nr({config:e})}catch(c){return{operation:"command",ok:!1,error:`Could not initialize the cloud driver: ${c?.message??c}`}}let a=e.project.slug,s=await i.findComputeTargets({slug:a,environment:t,role:"app"});if(!s.length)return{operation:"command",ok:!1,error:"No app server target was found for this environment."};let d=await i.runRemoteDeploy({targets:[s[0]],commands:["set -o pipefail",n],comment:"ts-cloud dashboard:command",tags:{Project:a,Environment:t,Role:"app"}});return{operation:"command",command:n,ok:d.success,stdout:Mi(d.perInstance?.[0]?.output??""),stderr:Mi(d.perInstance?.[0]?.error??d.error??"")}}function J$(e,t){return[`${e}-${t}`,`${e}-${t}-queues`,`${e}-${t}-daemons`]}function wp(e,t,r){return r.some((n)=>J$(t,n).includes(e))}function Cg(e,t){let{user:r,slug:n}=t;if(r.role==="admin")return e;let i=(e.sites??[]).map((E)=>E.name).filter(Boolean),a=cg(r,i),s=new Set(a),d=(e.sites??[]).filter((E)=>s.has(E.name)),c=(e.sitesDetail??[]).filter((E)=>s.has(E.name)),o=new Set(c.map((E)=>E.domain).filter(Boolean)),g=(e.serverDeploymentsDetail??e.serverDeployments??[]).filter((E)=>s.has(E.site)),h=(e.serverLogs??[]).filter((E)=>wp(E.source,n,a)),_=(e.security?.tlsCertificates??[]).filter((E)=>o.has(E.domain)),R=(e.activity??[]).filter((E)=>{if(E.type==="deploy")return a.some((y)=>String(E.title??"").startsWith(`${y} `));if(E.type==="log")return wp(String(E.title??"").split(" ")[0],n,a);return!1});return{mode:e.mode,environment:e.environment,environments:e.environments,scoped:!0,server:{name:""},sites:d,sitesDetail:c,workers:(e.workers??[]).filter((E)=>s.has(E.site)),serverDeployments:g.slice(0,5),serverDeploymentsDetail:g.slice(0,50),deploymentsEmptyReason:g.length?void 0:"No deployments have been recorded for your sites yet.",serverLogs:h,serverLogsEmptyReason:h.length?void 0:"No recent log entries for your sites.",security:{tlsCertificates:_,ports:[],firewall:null,authEvents:[]},diagnostics:(e.diagnostics??[]).filter((E)=>["Route conflicts","TLS certificates"].includes(E.name)),activity:R}}function Ap(e,t){if(t.role==="admin")return e;let r=new Set(cg(t,Object.keys(e.sites??{})));return{project:{name:e.project?.name},environment:e.environment,environments:e.environments,sites:Object.fromEntries(Object.entries(e.sites??{}).filter(([n])=>r.has(n)))}}function Pp(e){let t=new RegExp("[\\u007F-\\uFFFF]","g");return JSON.stringify(e).replace(t,(r)=>`\\u${r.charCodeAt(0).toString(16).padStart(4,"0")}`)}var T$=new Set(["name","ssl","env","redirects","aliases","domain","path"]),Dp={build:"build runs as a shell command on the server",start:"start runs as a shell command on the server",root:"root is a filesystem path on the shared server",port:"ports are allocated by the server owner",type:"the deploy type is set by the server owner",php:"the PHP runtime is set by the server owner"};function Cp(e){let t=Object.keys(e).filter((i)=>e[i]!==void 0),r=t.filter((i)=>(i in Dp));if(r.length)return{ok:!1,error:`Only the server owner can change ${r.map((a)=>`${a} (${Dp[a]})`).join(", ")}.`};let n=t.filter((i)=>!T$.has(i));if(n.length)return{ok:!1,error:`Only the server owner can change ${n.join(", ")}.`};return{ok:!0}}function Ko(e){return String(e??"").trim().toLowerCase().replace(/\.$/,"")}function $p(e){let t=String(e??"/").trim();if(!t||t==="/")return"/";return(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")||"/"}function z$(e){let t=[Ko(e?.domain)];if(Array.isArray(e?.aliases))t.push(...e.aliases.map(Ko));return t.filter(Boolean)}function kp({siteName:e,body:t,sites:r,ownSites:n}){let i=r[e]??{},a=new Set(n),s=new Set;if(t.domain!==void 0)s.add(Ko(t.domain));if(Array.isArray(t.aliases))for(let c of t.aliases)s.add(Ko(c));if(s.delete(""),s.size===0)return{ok:!0};let d=$p(t.path!==void 0?t.path:i.path);for(let[c,o]of Object.entries(r)){if(c===e||a.has(c))continue;let g=$p(o?.path);for(let h of z$(o)){if(!s.has(h))continue;if(g===d)return{ok:!1,error:`${h}${d==="/"?"":d} is already served by another site on this server.`}}}return{ok:!0}}class za{maxAttempts;lockoutMs;windowMs;attempts=new Map;constructor(e=8,t=900000,r=900000){this.maxAttempts=e;this.lockoutMs=t;this.windowMs=r}key(e,t){return`${e.trim().toLowerCase()}\x00${t}`}check(e,t,r=Date.now()){let n=this.attempts.get(this.key(e,t));if(!n?.until)return{allowed:!0};if(r>=n.until)return this.attempts.delete(this.key(e,t)),{allowed:!0};return{allowed:!1,retryAfterSeconds:Math.ceil((n.until-r)/1000)}}recordFailure(e,t,r=Date.now()){let n=this.key(e,t),i=this.attempts.get(n),s=!i||r-i.last>this.windowMs?1:i.count+1,d={count:s,last:r};if(s>=this.maxAttempts)d.until=r+this.lockoutMs;this.attempts.set(n,d)}recordSuccess(e,t){this.attempts.delete(this.key(e,t))}prune(e=Date.now()){for(let[t,r]of this.attempts)if(r.until?e>=r.until:e-r.last>this.windowMs)this.attempts.delete(t)}get size(){return this.attempts.size}}var vp=new Set([22,80,443]);function Wa(e){return Number.isInteger(e)&&e>=1&&e<=65535}function Yn(e){return[...new Set(e.filter((t)=>Wa(t)&&!vp.has(t)))].sort((t,r)=>t-r)}function Op(e,t,r=[]){if(!Wa(t))throw Error("Port must be an integer between 1 and 65535.");if(vp.has(t))throw Error(`Port ${t} (SSH/HTTP/HTTPS) is always open and is not managed here.`);return Jp({configText:e,ports:Yn([...r,t])})}function Bp(e,t,r=[]){return Jp({configText:e,ports:Yn(r.filter((n)=>n!==t))})}function bp(e,t,r,n,i){let a=e.slice(t,r),s=new RegExp(`\\b${n}\\s*:\\s*\\${i}`).exec(a);if(!s)return null;let d=t+s.index,c=e.indexOf(i,d);return{propStart:d,open:c,close:va(e,c,i,i==="{"?"}":"]")}}function kg(e){return`allowedPorts: [${e.join(", ")}]`}function Jp(e){let{configText:t}=e,r=Yn(e.ports),n=/\bcompute\s*:\s*{/.exec(t);if(!n)throw Error("Could not find infrastructure.compute in the cloud config.");let i=t.indexOf("{",n.index),a=va(t,i,"{","}"),s=bp(t,i+1,a,"firewall","{");if(s){let g=bp(t,s.open+1,s.close,"allowedPorts","[");if(g){let E=g.propStart;while(E>0&&t[E-1]!==`
625
+ `&&/\s/.test(t[E-1]))E--;let y=t.slice(E,g.propStart);return`${t.slice(0,E)}${y}${kg(r)}${t.slice(g.close+1)}`}let h=t.slice(0,s.close).trimEnd(),_=t.slice(s.close),R=h.endsWith(",")||h.endsWith("{")?"":",";return`${h}${R}
626
+ ${kg(r)},
627
+ ${_}`}let d=t.slice(0,a).trimEnd(),c=t.slice(a),o=d.endsWith(",")||d.endsWith("{")?"":",";return`${d}${o}
628
+ firewall: {
629
+ enabled: true,
630
+ ${kg(r)},
631
+ },
632
+ ${c}`}class bg{client;region;constructor(e="us-east-1"){this.region=e,this.client=new gi}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 Tp=65536;function It(e){return e.length<=Tp?e:`${e.slice(0,Tp)}
633
+
634
+ [output truncated]`}function Og(e,t){return e.environments?.[t]?.app}function Bg(e,t,r){let n=[],i=Og(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 a=r.maintenance?.enabled;if(a!==!0)n.push({id:"maintenance:on",label:"Enable maintenance mode",group:"maintenance",target:"app",mutates:!0,confirm:"maintenance",danger:!0});if(a!==!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 d=String(s?.name??"").trim();if(d&&/^[A-Za-z0-9_-]+$/.test(d))n.push({id:`queue:purge:${d}`,label:`Purge queue (${d})`,group:"queue",target:d,mutates:!0,confirm:d,danger:!0})}return n}function Wp(e,t,r,n){return Bg(t,r,n).find((i)=>i.id===e)}async function W$(e,t,r){try{let n=new wr(r),{Stacks:i}=await n.describeStacks({stackName:ci(e,t)}),a={};for(let c of i?.[0]?.Outputs??[])if(c.OutputKey)a[c.OutputKey]=c.OutputValue??"";let s=a.AssetsCdnDomain;if(!s)return null;return(await new An(r).findDistributionByDomain(s))?.Id??null}catch{return null}}async function jp(e,t,r,n={}){try{if(r.id==="redeploy")return await fd(e,t),{operation:r.id,command:"serverless redeploy",ok:!0,stdout:"Redeploy complete."};if(r.id==="rollback")return await Sd(e,t),{operation:r.id,command:"serverless rollback",ok:!0,stdout:"Rollback complete."};if(r.id==="maintenance:on")return await ns(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 ns(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),a=Number(n.max);if(!Number.isFinite(i)||!Number.isFinite(a)||i<=0||a<i)return{operation:r.id,ok:!1,error:"Provide valid Aurora capacities (0 < min ≤ max)."};return await Qu(e,t,i,a),{operation:r.id,command:`db:scale ${i}-${a} ACU`,ok:!0,stdout:`Scaling applied (${i}-${a} ACUs); takes effect shortly.`}}if(r.id==="assets:invalidate"){let i=await rt(e,t),a=await W$(e,t,i.region);if(!a)return{operation:r.id,ok:!1,error:"Could not resolve the asset CloudFront distribution for this environment."};let d=await new An(i.region).invalidateAll(a);return{operation:r.id,command:`cloudfront invalidate ${a} /*`,ok:!0,stdout:`Invalidation ${d?.Id??"created"} for ${a} (/*).`}}if(r.group==="queue"&&r.id.startsWith("queue:purge:")){let i=r.target,a=await rt(e,t),s=new Cn(a.region),d=`${a.slug}-${t}-${i}`,{QueueUrl:c}=await s.getQueueUrl(d);return await s.purgeQueue(c),{operation:r.id,command:`sqs purge ${d}`,ok:!0,stdout:`Purged queue ${d}.`}}return{operation:r.id,ok:!1,error:"Unknown or unavailable serverless operation."}}catch(i){return{operation:r.id,ok:!1,error:It(i?.message??String(i))}}}async function Up(e,t,r){let n=r.trim();if(!n)return{operation:"command",ok:!1,error:"A command is required."};try{let i=await li(e,t,n);return{operation:"command",command:n,ok:!0,stdout:It(i||"(no output)")}}catch(i){return{operation:"command",command:n,ok:!1,error:It(i?.message??String(i))}}}var Jg="No dead-letter queue is provisioned for this environment.";async function Tg(e,t,r){try{let{QueueUrl:n}=await e.getQueueUrl(`${t}-${r}-dlq`);return n}catch{return null}}async function Hp(e,t,r=10){try{let n=await rt(e,t),i=new Cn(n.region),a=await Tg(i,n.slug,t);if(!a)return{ok:!1,messages:[],error:Jg};return{ok:!0,messages:((await i.receiveMessages({queueUrl:a,maxMessages:Math.min(10,Math.max(1,r)),waitTimeSeconds:1,visibilityTimeout:2})).Messages??[]).map((c)=>({id:c.MessageId,receiptHandle:c.ReceiptHandle,body:It(String(c.Body??""))}))}}catch(n){return{ok:!1,messages:[],error:It(n?.message??String(n))}}}async function Np(e,t,r={}){try{let n=await rt(e,t),i=Og(e,t),s=(i?as(i,n.slug,t):[]).map((R)=>R.name.replace(`${n.slug}-${t}-`,"")),d=r.targetQueue&&s.includes(r.targetQueue)?r.targetQueue:s[0];if(!d)return{operation:"dlq:redrive",ok:!1,error:"No source queue is configured to redrive into."};let c=new Cn(n.region),o=await Tg(c,n.slug,t);if(!o)return{operation:"dlq:redrive",ok:!1,error:Jg};let{QueueUrl:g}=await c.getQueueUrl(`${n.slug}-${t}-${d}`),h=Math.min(50,Math.max(1,r.max??10)),_=0;while(_<h){let E=(await c.receiveMessages({queueUrl:o,maxMessages:Math.min(10,h-_),waitTimeSeconds:1,visibilityTimeout:30})).Messages??[];if(!E.length)break;for(let y of E)await c.sendMessage({queueUrl:g,messageBody:String(y.Body??"")}),await c.deleteMessage(o,y.ReceiptHandle),_++}return{operation:"dlq:redrive",command:`redrive → ${d}`,ok:!0,stdout:`Moved ${_} message(s) from the DLQ to ${d}.`}}catch(n){return{operation:"dlq:redrive",ok:!1,error:It(n?.message??String(n))}}}async function Fp(e,t){try{let r=await rt(e,t),n=new Cn(r.region),i=await Tg(n,r.slug,t);if(!i)return{operation:"dlq:purge",ok:!1,error:Jg};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:It(r?.message??String(r))}}}function Vp(e,t){let r=Og(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 Lp(e,t,r,n){if(!r.trim())return{operation:"secret:set",ok:!1,error:"A secret id is required."};try{let i=await rt(e,t),a=new Kr(i.region);try{await a.putSecretValue({SecretId:r,SecretString:n})}catch{await a.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:It(i?.message??String(i))}}}async function xp(e,t,r){if(!r.trim())return{operation:"secret:delete",ok:!1,error:"A secret id is required."};try{let n=await rt(e,t);return await new Kr(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:It(n?.message??String(n))}}}var j$=new Set(["http","queue","cli"]);async function Mp(e,t,r,n){if(!j$.has(r))return{operation:"function:config",ok:!1,error:`Unknown function mode '${r}'.`};let i=n.memory==null?void 0:Number(n.memory),a=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(a!=null&&(!Number.isInteger(a)||a<1||a>900))return{operation:"function:config",ok:!1,error:"Timeout must be an integer between 1 and 900 seconds."};if(i==null&&a==null)return{operation:"function:config",ok:!1,error:"Provide a memory and/or timeout value."};try{let s=await rt(e,t),d=new Et(s.region),c=`${s.slug}-${t}-${r}`;await d.updateFunctionConfiguration({FunctionName:c,...i!=null?{MemorySize:i}:{},...a!=null?{Timeout:a}:{}});let o=[i!=null?`${i} MB`:"",a!=null?`${a}s`:""].filter(Boolean).join(", ");return{operation:"function:config",command:`update ${c} (${o})`,ok:!0,stdout:`Updated ${c}: ${o}.`}}catch(s){return{operation:"function:config",ok:!1,error:It(s?.message??String(s))}}}var vg=[{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 U$(e){return vg.find((t)=>t.key===e)}async function Qp(e,t){try{let r=await rt(e,t);return{ok:!0,alarms:await new Ar(r.region).describeAlarms({AlarmNamePrefix:`${r.slug}-${t}-`,MaxRecords:100}),presets:vg}}catch(r){return{ok:!1,alarms:[],presets:vg,error:It(r?.message??String(r))}}}async function Gp(e,t,r,n){let i=U$(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 a=await rt(e,t),s=new Ar(a.region),d=`${a.slug}-${t}-${i.key}`,c=i.fnMode?[{Name:"FunctionName",Value:`${a.slug}-${t}-${i.fnMode}`}]:[];return await s.putMetricAlarm({AlarmName:d,Namespace:i.namespace,MetricName:i.metricName,ComparisonOperator:i.comparison,Threshold:n,EvaluationPeriods:1,Period:300,Statistic:i.statistic,Dimensions:c,AlarmDescription:`ts-cloud: ${i.label} > ${n} ${i.unit}`}),{operation:"alarm:create",command:`alarm ${d}`,ok:!0,stdout:`Alarm ${d} armed at ${n} ${i.unit}.`}}catch(a){return{operation:"alarm:create",ok:!1,error:It(a?.message??String(a))}}}async function Zp(e,t,r){try{let n=await rt(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 Ar(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:It(n?.message??String(n))}}}function H$(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 Yo(e,t,r=30){try{let n=await rt(e,t),i=new bg(n.region),a=new Date,s=new Date(a.getTime()-Math.min(360,Math.max(1,r))*60000),d=`${n.slug}-${t}-http`,c=await i.getTraceSummaries({startTime:s,endTime:a,filterExpression:`service("${d}")`});if(!c.summaries.length)c=await i.getTraceSummaries({startTime:s,endTime:a});return{ok:!0,traces:c.summaries.slice(0,100).map(H$)}}catch(n){return{ok:!1,traces:[],error:It(n?.message??String(n))}}}async function zg(e,t,r){try{let n=await rt(e,t),i=`${n.slug}-${t}-scheduler`;if(r==="run"){let s=await li(e,t,"schedule:run");return{operation:"scheduler:run",command:"schedule:run",ok:!0,stdout:It(s||"Scheduler run triggered.")}}let a=new zp(n.region);if(r==="enable")await a.enableRule({Name:i});else await a.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:It(n?.message??String(n))}}}function Kp(e){let t=Xo(e.name),r=jg(e.configText);if(V$(e.configText,r.start,r.end,t))throw Error(`Site '${t}' already exists in cloud.config.ts`);let n=F$({...e,name:t}),i=e.configText.slice(0,r.end).trimEnd(),a=e.configText.slice(r.end),s=i.endsWith("{")?`
635
+ `:i.endsWith(",")?`
636
+
637
+ `:`,
638
+
639
+ `;return`${i}${s}${n}
640
+ ${a}`}function Yp(e){let t=Xo(e.name),r=jg(e.configText),n=iI(e.configText,r.start,r.end,t);if(!n)throw Error(`Site '${t}' does not exist in cloud.config.ts`);let i=e.configText,a=n.nameStart;while(a>0&&i[a-1]!==`
641
+ `&&/\s/.test(i[a-1]))a--;let s=n.end+1;if(i[s]===",")s++;while(s<i.length&&i[s]!==`
642
+ `&&/\s/.test(i[s]))s++;if(i[s]===`
643
+ `)s++;return i.slice(0,a)+i.slice(s)}function Xp(e){let t=Xo(e.siteName);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e.key))throw Error(`Invalid property key '${e.key}'`);let r=jg(e.configText),n=iI(e.configText,r.start,r.end,t);if(!n)throw Error(`Site '${t}' does not exist in cloud.config.ts`);let i=e.configText,a=i.indexOf("{",n.nameStart),s=n.end,d=i.slice(a+1,s),c=new RegExp(`(^|[\\s,{])(${Ug(e.key)})\\s*:`,"m").exec(d);if(c){let h=a+1+c.index+c[1].length,_=i.indexOf(":",h),R=N$(i,_+1,s);return`${i.slice(0,h)}${e.key}: ${e.valueText}${i.slice(R)}`}let o=i.slice(0,s).trimEnd(),g=o.endsWith("{")||o.endsWith(",")?"":",";return`${o}${g}
644
+ ${e.key}: ${e.valueText},
645
+ ${i.slice(s)}`}function qp(e){if(e===!1)return"false";if(e===!0)return"true";return`{ provider: '${pn(e.provider||"letsencrypt")}' }`}function eI(e){return`'${pn(e)}'`}function tI(e){let t=Object.entries(e).filter(([r])=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(r));if(t.length===0)return"{}";return`{
646
+ ${t.map(([r,n])=>` ${r}: '${pn(String(n))}',`).join(`
647
+ `)}
648
+ }`}function Wg(e){return/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/i.test(e.trim())}function rI(e){let t=[...new Set(e.map((r)=>r.trim().toLowerCase()).filter(Boolean))];for(let r of t)if(!Wg(r))throw Error(`Alias '${r}' is not a valid hostname.`);if(t.length===0)return"[]";return`[${t.map((r)=>`'${pn(r)}'`).join(", ")}]`}function nI(e){let t=Object.entries(e).map(([r,n])=>[r.trim(),String(n).trim()]).filter(([r,n])=>r&&n);if(t.length===0)return"{}";return`{
649
+ ${t.map(([r,n])=>` '${pn(r)}': '${pn(n)}',`).join(`
650
+ `)}
651
+ }`}function N$(e,t,r){let n=t;while(n<r&&/\s/.test(e[n]))n++;let i=0,a,s=!1;for(;n<r;n++){let d=e[n];if(a){if(s){s=!1;continue}if(d==="\\"){s=!0;continue}if(d===a)a=void 0;continue}if(d==='"'||d==="'"||d==="`"){a=d;continue}if(d==="{"||d==="["||d==="("){i++;continue}if(d==="}"||d==="]"||d===")"){if(i===0)return n;i--;continue}if(d===","&&i===0)return n}return r}function iI(e,t,r,n){let i=e.slice(t+1,r),a=new RegExp(`(^|[\\s,{])(${Ug(n)})\\s*:\\s*\\{`,"m").exec(i);if(!a)return null;let s=t+1+a.index+a[1].length,d=e.indexOf("{",s);return{nameStart:s,end:aI(e,d)}}function F$(e){let r=[` ${Xo(e.name)}: {`];if(Rn(r,"deploy",e.deploy),Rn(r,"root",e.root),Rn(r,"path",e.path),Rn(r,"domain",e.domain),Rn(r,"type",e.type),Rn(r,"build",e.build),Rn(r,"start",e.start),e.port!==void 0)r.push(` port: ${e.port},`);if(Rn(r,"pathRewriteStyle",e.pathRewriteStyle),e.ssl!==void 0)if(e.ssl===!1)r.push(" ssl: false,");else if(e.ssl===!0)r.push(" ssl: true,");else r.push(` ssl: { provider: '${pn(e.ssl.provider||"letsencrypt")}' },`);if(e.env&&Object.keys(e.env).length>0){r.push(" env: {");for(let[n,i]of Object.entries(e.env)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(n))continue;r.push(` ${n}: '${pn(String(i))}',`)}r.push(" },")}return r.push(" },"),r.join(`
652
+ `)}function pn(e){return e.replace(/\\/g,"\\\\").replaceAll(String.fromCharCode(39),"\\'").replace(/\r/g,"\\r").replace(/\n/g,"\\n")}function Xo(e){let t=e.trim();if(!/^[A-Za-z_$][\w$]*$/.test(t))throw Error(`Invalid site name '${e}'. Use a valid JavaScript object key, e.g. docs or marketingSite.`);return t}function Rn(e,t,r){if(r===void 0||r==="")return;let n=r.replace(/\\/g,"\\\\").replaceAll(String.fromCharCode(39),"\\'");e.push(` ${t}: '${n}',`)}function jg(e){let t=/\bsites\s*:\s*{/g.exec(e);if(!t)throw Error("Could not find a top-level sites: { ... } block in cloud.config.ts");let r=e.indexOf("{",t.index),n=aI(e,r);return{start:r,end:n}}function V$(e,t,r,n){let i=e.slice(t+1,r);return new RegExp(`(^|[\\s,{])${Ug(n)}\\s*:`,"m").test(i)}function Ug(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function aI(e,t){let r=0,n,i=!1,a=!1,s=!1;for(let d=t;d<e.length;d++){let c=e[d],o=e[d+1];if(a){if(c===`
653
+ `)a=!1;continue}if(s){if(c==="*"&&o==="/")s=!1,d++;continue}if(n){if(i){i=!1;continue}if(c==="\\"){i=!0;continue}if(c===n)n=void 0;continue}if(c==="/"&&o==="/"){a=!0,d++;continue}if(c==="/"&&o==="*"){s=!0,d++;continue}if(c==='"'||c==="'"||c==="`"){n=c;continue}if(c==="{")r++;if(c==="}"){if(r--,r===0)return d}}throw Error("Could not find the closing brace for sites: { ... } in cloud.config.ts")}function sI(e,t,r){let n=(Array.isArray(r)?r:String(r??"").split(",")).map(String).filter(Boolean);if(!n.length){if(t)return;let a=e.map((s)=>s.id);return a.length?a:["__no_authorized_telemetry_resources__"]}let i=n.map((a)=>e.find((s)=>s.id===a||s.slug===a)?.id).filter((a)=>!!a);if(i.length!==n.length)throw Error("One or more telemetry resources are outside your authorized scope.");return[...new Set(i)]}import{createHash as cI}from"node:crypto";class lI{now;entries=new Map;constructor(e=Date.now){this.now=e}async getOrCreate(e,t,r,n){let i=this.entries.get(e);if(!r&&i&&i.expiresAt>this.now())return{value:await i.promise,cached:!0};let a=n().catch((s)=>{throw this.entries.delete(e),s});return this.entries.set(e,{expiresAt:this.now()+t,promise:a}),{value:await a,cached:!1}}invalidate(e){for(let t of this.entries.keys())if(t.startsWith(e))this.entries.delete(t)}}class gI{now;lastRun=new Map;constructor(e=Date.now){this.now=e}shouldRun(e,t,r=!1){let n=this.now(),i=this.lastRun.get(e);if(!r&&i!=null&&n-i<t)return!1;return this.lastRun.set(e,n),!0}}var uI=new lI,L$=new gI,x$=2000,M$=3600000;function Q$(e,t){if(e.kind==="log"&&!t.collectLogs)return!1;if(e.kind==="trace"&&!t.collectTraces)return!1;if((e.kind==="request"||e.name.startsWith("request."))&&!t.collectRequestAnalytics)return!1;if(!["log","trace","request"].includes(e.kind)&&!e.name.startsWith("request."))return!0;let r=e.requestId??e.traceId??`${e.source}\x00${e.workloadId??""}\x00${e.timestamp}`;return Number.parseInt(cI("sha256").update(r).digest("hex").slice(0,8),16)/4294967295<=t.samplingRate}function mt(...e){return`telemetry:${cI("sha256").update(e.map((t)=>String(t??"")).join("\x00")).digest("hex").slice(0,40)}`}function ja(e,t,r,n){if(!n)return;return e.listResources(t,r).find((i)=>i.slug===n)?.id}function G$(e,t){let r=String(t??"").toLowerCase();if(["debug","info","warn","warning","error","fatal"].includes(r))return r==="fatal"?"error":r;return/fatal|panic|exception|error/i.test(e)?"error":/warn|timeout|throttl|retr(?:y|ies)/i.test(e)?"warning":"info"}function oI(e){let t=e.timestamp&&Number.isFinite(new Date(e.timestamp).getTime())?new Date(e.timestamp).toISOString():new Date().toISOString(),r={};try{let y=JSON.parse(e.message);if(y&&typeof y==="object"&&!Array.isArray(y))r=y}catch{}let n=Object.fromEntries(Object.entries(r).filter(([y])=>!/^(?:body|requestBody|responseBody|headers|authorization|cookie|cookies|query|queryString)$/i.test(y))),i=String(r.requestId??r.request_id??r["x-request-id"]??"")||void 0,a=String(r.traceId??r.trace_id??r["x-amzn-trace-id"]??"")||void 0,s=Number(r.durationMs??r.duration_ms??r.latencyMs??r.latency_ms),d=Number(r.statusCode??r.status_code??r.status),c=String(r.method??r.httpMethod??"")||void 0,o=dI(String(r.pathTemplate??r.path??r.url??"")||void 0),g=String(r.releaseId??r.release_id??"")||void 0,h=String(r.deploymentId??r.deployment_id??"")||void 0,_={projectId:e.projectId,environmentId:e.environmentId,resourceId:e.resourceId,source:e.source,timestamp:t,requestId:i,traceId:a,releaseId:g,deploymentId:h,workloadId:e.workloadId},R=Object.keys(r).length?JSON.stringify(n):e.message,E=[{..._,id:mt(e.source,e.name,t,R),kind:"log",name:e.name,level:G$(R,r.level),message:R,attributes:n}];if(c&&o&&Number.isFinite(d)){if(E.push({..._,id:mt("request",i,t,c,o,d),kind:"request",name:"http.request",method:c,pathTemplate:o,host:r.host,statusCode:d,durationMs:Number.isFinite(s)?s:void 0,bytesIn:Number(r.bytesIn)||void 0,bytesOut:Number(r.bytesOut)||void 0,region:r.region,cacheResult:r.cacheResult??r.cache,upstream:r.upstream,attributes:{userAgentFamily:r.userAgentFamily??"",protocol:r.protocol??""}}),Number.isFinite(s))E.push({..._,id:mt("request-duration",i,t),kind:"metric",name:"request.duration",value:s,unit:"ms",attributes:{method:c,pathTemplate:o,statusCode:d}});if(E.push({..._,id:mt("request-count",i,t),kind:"metric",name:"request.count",value:1,unit:"count",attributes:{method:c,pathTemplate:o,statusCode:d}}),d>=500)E.push({..._,id:mt("request-error",i,t),kind:"metric",name:"request.error",value:1,unit:"count",attributes:{method:c,pathTemplate:o,statusCode:d}})}return E}async function Z$(e){let t=new qo(e.controlPlane),r=Ua(e.controlPlane,e.projectId),n=new Date,i=[],a=[],s={projectId:e.projectId,environmentId:e.environmentId},d=Ur(e.config);try{let _=(d==="serverless"?await na(e.config,e.environment):await To(e.config,e.environment,{includeSiteHealth:e.includeSiteHealth,telemetryOnly:e.lightweight}))??{};if(d==="serverless"){for(let E of _.functionsDetail??[]){let y=ja(e.controlPlane,e.projectId,e.environmentId,E.key),$={...s,resourceId:y,source:"cloudwatch",timestamp:n.toISOString(),workloadId:E.name,attributes:{provider:"aws",functionName:E.name,aggregationWindow:"24h"}};for(let[b,z,C]of[["snapshot.traffic.requests_24h",E.invocations,"count"],["snapshot.errors.count_24h",E.errors,"count"],["snapshot.latency.p50_24h",E.p50,"ms"],["snapshot.latency.p95_24h",E.p95,"ms"],["snapshot.latency.p99_24h",E.p99,"ms"],["snapshot.saturation.throttles_24h",E.throttles,"count"],["snapshot.memory.max_24h",E.maxMem,"MB"]])if(Number.isFinite(Number(z)))i.push({...$,id:mt("cloudwatch",E.name,b,n.toISOString()),kind:"metric",name:b,value:Number(z),unit:C})}try{let E=await rt(e.config,e.environment),y=new Ar(E.region),$=new Date(n.getTime()-3600000),b=300;for(let z of E.functions){let C=[{Name:"FunctionName",Value:z.name}],[B,N,F,J,Z]=await Promise.all([y.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:C,StartTime:$,EndTime:n,Period:300,Statistics:["Sum"]}),y.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"Errors",Dimensions:C,StartTime:$,EndTime:n,Period:300,Statistics:["Sum"]}),y.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"Duration",Dimensions:C,StartTime:$,EndTime:n,Period:300,ExtendedStatistics:["p50","p95","p99"]}),y.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"Throttles",Dimensions:C,StartTime:$,EndTime:n,Period:300,Statistics:["Sum"]}),y.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"ConcurrentExecutions",Dimensions:C,StartTime:$,EndTime:n,Period:300,Statistics:["Maximum"]})]),O=ja(e.controlPlane,e.projectId,e.environmentId,z.mode),K=(ae,Se,Te,de)=>{for(let Ae of ae){let ze=Ae.Timestamp&&Number.isFinite(new Date(Ae.Timestamp).getTime())?new Date(Ae.Timestamp).toISOString():void 0,ue=Te(Ae);if(ze&&ue!=null&&Number.isFinite(ue))i.push({...s,resourceId:O,id:mt("cloudwatch-series",z.name,Se,ze),kind:"metric",source:"cloudwatch",name:Se,timestamp:ze,value:ue,unit:de,workloadId:z.name,region:E.region,attributes:{provider:"aws",functionName:z.name,aggregationWindow:"300s"}})}};K(B,"traffic.requests",(ae)=>ae.Sum,"count"),K(N,"errors.count",(ae)=>ae.Sum,"count"),K(F,"latency.p50",(ae)=>ae.Percentiles?.p50,"ms"),K(F,"latency.p95",(ae)=>ae.Percentiles?.p95,"ms"),K(F,"latency.p99",(ae)=>ae.Percentiles?.p99,"ms"),K(J,"saturation.throttles",(ae)=>ae.Sum,"count"),K(Z,"saturation.concurrency",(ae)=>ae.Maximum,"count")}}catch(E){a.push({source:"cloudwatch:series",message:E instanceof Error?E.message:String(E)})}for(let E of(_.serverlessLogs??[]).slice(0,x$))i.push(...oI({...s,source:`cloudwatch:${E.source}`,name:`${E.source}.log`,timestamp:E.timestamp,message:String(E.message),resourceId:ja(e.controlPlane,e.projectId,e.environmentId,E.source)}));for(let E of _.queuesDetail??[]){let y={...s,source:"cloudwatch",timestamp:n.toISOString(),attributes:{queue:E.name}};i.push({...y,id:mt("queue-depth",E.name,n.toISOString()),kind:"metric",name:"queue.depth",value:Number(E.visible??E.depth??0),unit:"count"}),i.push({...y,id:mt("queue-inflight",E.name,n.toISOString()),kind:"metric",name:"queue.inflight",value:Number(E.inFlight??0),unit:"count"})}let R=await Yo(e.config,e.environment,30);if(!R.ok)a.push({source:"xray",message:R.error??"X-Ray traces are unavailable."});for(let E of R.traces)i.push({...s,id:mt("xray",E.id),kind:"trace",source:"xray",name:"http.trace",timestamp:E.timestamp??n.toISOString(),traceId:E.id,durationMs:E.durationMs,statusCode:E.httpStatus,method:E.method,pathTemplate:E.url,attributes:{status:E.status,responseMs:E.responseMs}})}else{let R=_.systemMetrics;if(_.metricsUnavailable||!R)a.push({source:"host",message:"The host metrics probe is unavailable."});else{let E=Number(R.memTotalMb)>0?Number(R.memUsedMb)/Number(R.memTotalMb)*100:0,y=Number(R.swapTotalMb)>0?Number(R.swapUsedMb)/Number(R.swapTotalMb)*100:0,$=[["host.load",Number(R.load),"load"],["host.load.5m",Number(R.load5),"load"],["host.load.15m",Number(R.load15),"load"],["host.cpu.capacity",Number(R.cpus),"count"],["host.cpu.used_percent",Number(R.cpuUsedPct),"percent"],["host.memory.used",Number(R.memUsedMb)*1024*1024,"bytes"],["host.memory.total",Number(R.memTotalMb)*1024*1024,"bytes"],["host.memory.available",Number(R.memAvailableMb)*1024*1024,"bytes"],["host.memory.cache",Number(R.memCacheMb)*1024*1024,"bytes"],["host.memory.used_percent",E,"percent"],["host.swap.used",Number(R.swapUsedMb)*1024*1024,"bytes"],["host.swap.total",Number(R.swapTotalMb)*1024*1024,"bytes"],["host.swap.used_percent",y,"percent"],["host.disk.used_percent",Number(R.diskUsedPct),"percent"],["host.disk.used",Number(R.diskUsedGb)*1073741824,"bytes"],["host.disk.total",Number(R.diskTotalGb)*1073741824,"bytes"],["host.disk.inode_used_percent",Number(R.inodeUsedPct),"percent"],["host.network.rx",Number(R.networkRxBytes),"bytes"],["host.network.tx",Number(R.networkTxBytes),"bytes"],["host.network.rx_rate",Number(R.networkRxBytesPerSec),"bytes_per_second"],["host.network.tx_rate",Number(R.networkTxBytesPerSec),"bytes_per_second"],["host.network.rx_today",Number(R.networkRxBytesToday),"bytes"],["host.network.tx_today",Number(R.networkTxBytesToday),"bytes"],["host.network.rx_month",Number(R.networkRxBytesMonth),"bytes"],["host.network.tx_month",Number(R.networkTxBytesMonth),"bytes"],["host.processes",Number(R.processes),"count"],["host.uptime",Number(R.uptimeSeconds),"seconds"]];for(let[b,z,C]of $)if(Number.isFinite(z))i.push({...s,id:mt("host",b,n.toISOString()),kind:"metric",source:"host",name:b,timestamp:n.toISOString(),value:z,unit:C});for(let b of _.siteHealth??[]){let z=String(b.project??e.config.project.slug),C=String(b.name),B=C.startsWith(`${z}:`)?C.slice(z.length+1):C,N=`site:${z}:${B}`,F=ja(e.controlPlane,e.projectId,e.environmentId,C),J={...s,resourceId:F,source:N,timestamp:b.checkedAt||n.toISOString(),host:b.route,attributes:{project:z,site:B,route:String(b.route),status:String(b.status)}},Z=[["site.health.up",b.status==="live"?1:0,"boolean"],["site.http.status",Number(b.httpStatus),"status"],["site.response.time",Number(b.responseMs),"ms"]];if(b.tlsDaysRemaining!=null)Z.push(["site.tls.days_remaining",Number(b.tlsDaysRemaining),"days"]);for(let[O,K,ae]of Z)if(Number.isFinite(K))i.push({...J,id:mt(N,O,J.timestamp),kind:"metric",name:O,value:K,unit:ae})}}}}catch(_){a.push({source:d==="serverless"?"aws":"host",message:_ instanceof Error?_.message:String(_)})}{let _=e.config.infrastructure?.compute?.monitoring,R=typeof _==="object"?_?.egressEndpoints:void 0,E=await pd(R,{now:n.toISOString()});a.push(...E.errors);for(let y of E.metrics)i.push({...s,id:mt(y.attributes.source,y.name,y.timestamp),kind:"metric",source:`egress:${y.attributes.source}`,name:y.name,timestamp:y.timestamp,value:y.value,unit:y.unit,attributes:y.attributes})}if(!e.lightweight)try{let _=await ir(e.config,e.environment),R=new _r(e.config,e.environment,{inventory:async()=>_});for(let E of _.workloads){let y=ja(e.controlPlane,e.projectId,e.environmentId,E.links.service),$={...s,resourceId:y,source:`runtime:${E.provider}`,timestamp:n.toISOString(),workloadId:E.id,releaseId:E.links.release,attributes:{status:E.status,provider:E.provider,service:E.links.service??""}};if(i.push({...$,id:mt(E.id,"health",n.toISOString()),kind:"metric",name:"health.up",value:E.status==="running"?1:0,unit:"boolean"}),i.push({...$,id:mt(E.id,"restarts",n.toISOString()),kind:"metric",name:"saturation.restarts",value:E.restartCount??0,unit:"count"}),E.resources?.memoryBytes!=null)i.push({...$,id:mt(E.id,"memory",n.toISOString()),kind:"metric",name:"runtime.memory.used",value:E.resources.memoryBytes,unit:"bytes"});if(!E.capabilities.logs.supported)continue;try{let b=await R.logs(E.id,{limit:100,since:new Date(n.getTime()-300000)});for(let z of b.lines)i.push(...oI({...s,resourceId:y,source:`runtime:${E.provider}`,name:`${E.links.service??E.name}.log`,timestamp:z.timestamp,message:z.message,workloadId:E.id}))}catch(b){a.push({source:`runtime:${E.provider}`,message:b instanceof Error?b.message:String(b)})}}for(let E of _.sources.filter((y)=>y.status!=="fresh"))a.push({source:E.id,message:E.message??`Runtime source is ${E.status}.`})}catch(_){a.push({source:"runtime",message:_ instanceof Error?_.message:String(_)})}if(!e.lightweight)for(let _ of e.controlPlane.listEvents({projectId:e.projectId,limit:1000})){let R=_.payload;i.push({...s,id:`telemetry:event:${_.id}`,resourceId:_.resourceId,kind:"event",source:"control-plane",name:_.type,timestamp:_.createdAt,level:_.level,message:_.type,deploymentId:_.operationId,releaseId:typeof R.releaseId==="string"?R.releaseId:void 0,traceId:_.correlationId,attributes:R})}let c=i.filter((_)=>Q$(_,r)).map((_)=>({..._,sampled:r.samplingRate<1&&(_.kind==="log"||_.kind==="trace"||_.kind==="request"||_.name.startsWith("request."))})),o=t.appendMany(c).length;if(L$.shouldRun(e.projectId,M$,!e.lightweight))t.enforceRetention(r,e.projectId);let g=t.status(e.projectId,e.environmentId,r.rawDays,r.samplingRate);for(let _ of a)if(!g.some((R)=>R.source===_.source))g.push({source:_.source,freshness:"unavailable",samplingRate:r.samplingRate,retentionDays:r.rawDays,estimatedDailyBytes:0,message:_.message});let h=n.toISOString();return e.controlPlane.setSetting(`telemetry.collection:${e.projectId}:${e.environmentId??"all"}`,{generatedAt:h,errors:a,statuses:g,policy:r}),{collected:o,cached:!1,generatedAt:h,statuses:g,errors:a,policy:r}}async function Hg(e){let r=`${`${e.projectId}:${e.environmentId??"all"}:${e.environment}`}:${e.lightweight?"lightweight":"full"}`,n=Ur(e.config)==="serverless"?300000:60000,i=await uI.getOrCreate(r,n,!!e.force,()=>Z$(e));return{...i.value,cached:i.cached}}function hI(e){uI.invalidate(`${e}:`)}function fI(e,t={}){let r=t.shell||(process.platform==="win32"?"powershell.exe":"bash"),n=Bun.spawn([r,"-i"],{stdin:"pipe",stdout:"pipe",stderr:"pipe",cwd:t.cwd,env:{...process.env,TERM:"xterm-256color",PS1:"\\w $ "}}),i=new TextDecoder,a=async(s)=>{if(!s)return;let d=s.getReader();try{for(;;){let{done:c,value:o}=await d.read();if(c)break;if(o)e(i.decode(o))}}catch{}};if(a(n.stdout),a(n.stderr),t.onExit)n.exited.then((s)=>t.onExit(s)).catch(()=>{});return{write(s){try{n.stdin.write(s),n.stdin.flush()}catch{}},close(){try{n.stdin.end()}catch{}try{n.kill()}catch{}}}}var nC="127.0.0.1",iC=7676,_I=65536,LI="ts-cloud-dashboard-",Zi=Y$(rC(import.meta.url));function aC(e){try{return process.kill(e,0),!0}catch(t){return t?.code!=="ESRCH"}}function sC(e=rd(),t=aC){let r=0;for(let n of SI(e,{withFileTypes:!0})){if(!n.isDirectory()||!n.name.startsWith(LI))continue;let i=ke(e,n.name),a=n.name.match(/^ts-cloud-dashboard-(\d+)-/);if(a){let s=Number(a[1]);if(s===process.pid||t(s))continue}else if(SI(i).length>0)continue;ei(i,{recursive:!0,force:!0}),r+=1}return r}var oC={".html":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".js":"text/javascript; charset=utf-8",".json":"application/json; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".ico":"image/x-icon"};function f(e,t=200,r={}){return new Response(JSON.stringify(e,null,2),{status:t,headers:{"content-type":"application/json; charset=utf-8",...r}})}function dC(e,t,r,n){let i=new TextEncoder,a=Math.max(0,Math.floor(r)),s,d,c=!1,o=new ReadableStream({start(g){let h=()=>{if(c)return;if(c=!0,s?.(),d)clearInterval(d);n.removeEventListener("abort",h);try{g.close()}catch{}},_=(E)=>{if(c)return;if(E.reset)g.enqueue(i.encode(`event: reset
654
+ data: ${JSON.stringify({cursor:E.cursor,droppedBytes:E.droppedBytes})}
655
+
656
+ `));for(let y of E.chunks.filter(($)=>$.cursor>a))a=y.cursor,g.enqueue(i.encode(`id: ${y.cursor}
657
+ event: ${y.stream}
658
+ data: ${JSON.stringify(y)}
659
+
660
+ `));if(E.state!=="open")g.enqueue(i.encode(`event: state
661
+ data: ${JSON.stringify({state:E.state,error:E.error,cursor:E.cursor})}
662
+
663
+ `)),h()};s=e.subscribe(t.id,t.workloadId,(E)=>_(e.read(E.id,E.workloadId,a)??E));let R=e.read(t.id,t.workloadId,a);if(!R)return h();if(_(R),c)return;d=setInterval(()=>{if(!c)g.enqueue(i.encode(`event: heartbeat
664
+ data: ${JSON.stringify({cursor:a,at:new Date().toISOString()})}
665
+
666
+ `))},15000),d.unref?.(),n.addEventListener("abort",h,{once:!0})},cancel(){if(c=!0,s?.(),d)clearInterval(d)}});return new Response(o,{headers:{"cache-control":"no-cache, no-transform",connection:"keep-alive","content-type":"text/event-stream; charset=utf-8","x-accel-buffering":"no"}})}var cC=new Set(["action","operation","site","name","username","database","secretId","port","key","resourceId","environmentId"]);function lC(e,t,r,n,i){let a={};if(r&&typeof r==="object"&&!Array.isArray(r))for(let[d,c]of Object.entries(r)){if(!cC.has(d)||!["string","number","boolean"].includes(typeof c))continue;a[d]=typeof c==="string"?c.slice(0,256):c}let s=String(a.resourceId||a.site||a.secretId||a.database||a.name||t);return{method:e.toUpperCase(),path:t,target:s,status:n,outcome:n<400?"succeeded":"failed",durationMs:Math.max(0,Math.round(i)),input:a}}var gC=fn("ts-cloud-dummy-password");function nd(e,t=200){return new Response(e,{status:t,headers:{"content-type":"text/plain; charset=utf-8"}})}function uC(e,t,r=process.env){let n=r.TS_CLOUD_DASHBOARD_ORIGIN?.trim()||(r.TS_CLOUD_UI_DOMAIN?.trim()?`https://${r.TS_CLOUD_UI_DOMAIN.trim().replace(/^https?:\/\//,"")}`:""),i=["0.0.0.0","::"].includes(e)?void 0:e,a=n||(i&&["127.0.0.1","localhost","::1"].includes(i)?`http://${i.includes(":")?`[${i}]`:i}:${t}`:"");if(!a)return;try{let s=new URL(a),d=["127.0.0.1","localhost","::1"].includes(s.hostname);if(s.protocol!=="https:"&&!(s.protocol==="http:"&&d)||s.username||s.password||s.search||s.hash||s.pathname!=="/"&&s.pathname!=="")return;return s.origin}catch{return}}function hC(e,t){if(t&&Object.hasOwn(e.environments??{},t))return t;return Object.keys(e.environments??{})[0]??"production"}function fC(e,t,r){return r&&e.includes(r)?r:t}function RI(e,t,r){return e==null||t-e>=r}async function SC(e){let t=[ke(Zi,"..","..","..","..",".env"),ke(e,".env"),ke(e,".env.local"),ke(e,".env.production")];for(let r of t){if(!Fr(r))continue;let n=await pr(r,"utf8").catch(()=>"");for(let i of n.split(`
667
+ `)){let a=i.trim();if(!a||a.startsWith("#")||!a.includes("="))continue;let s=a.indexOf("="),d=a.slice(0,s).trim(),c=a.slice(s+1).trim();if(!/^[A-Z_][A-Z0-9_]*$/i.test(d)||process.env[d]!=null)continue;if(c.startsWith('"')&&c.endsWith('"')||c.startsWith("'")&&c.endsWith("'"))c=c.slice(1,-1);process.env[d]=c}}}function _C(e){return[ke(e,"config","cloud.ts"),ke(e,"config","cloud.js"),ke(e,"cloud.config.ts"),ke(e,"cloud.config.js")].find((r)=>Fr(r))??null}function Ki(e){return e.infrastructure?.compute?.sshKeys??[]}function pI(e,t){let r=e.infrastructure??(e.infrastructure={}),n=r.compute??(r.compute={});n.sshKeys=t}function RC(e,t,r){let n=e.sites??(e.sites={});n[t]=r}function Ng(e){return Yn(e.infrastructure?.compute?.firewall?.allowedPorts??[])}function II(e,t){let r=e.infrastructure??(e.infrastructure={}),n=r.compute??(r.compute={}),i=n.firewall??(n.firewall={});i.allowedPorts=t}async function v(e){return await e.json().catch(()=>({}))}function Qi(e,t){let r=String(e.scopeType??"environment");if(!["project","environment","service","function","preview"].includes(r))throw Error("Configuration scopeType must be project, environment, service, function, or preview.");let n=String(e.scopeId??(r==="project"?t.projectId:r==="environment"?t.environmentId??"":""));if(!n)throw Error("Configuration scopeId is required.");if(r==="project")return{type:r,id:n};if(r==="environment")return{type:r,id:n,environmentId:n};if(r==="service"||r==="function")return{type:r,id:n,environmentId:String(e.environmentId??t.environmentId??"")||void 0,resourceId:n};return{type:r,id:n,environmentId:String(e.environmentId??t.environmentId??"")||void 0,resourceId:String(e.resourceId??"")||void 0,previewId:n}}function pC(e){if(["GET","HEAD","OPTIONS"].includes(e.method.toUpperCase()))return!0;let t=e.headers.get("sec-fetch-site");if(t==="cross-site")return!1;let r=e.headers.get("origin");if(!r)return!0;let n=new URL(e.url);if(r===n.origin)return!0;if(t!=="same-origin")return!1;try{let i=new URL(r),a=(e.headers.get("x-forwarded-host")??e.headers.get("host")??n.host).split(",")[0].trim(),s=e.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();if(!/^[A-Za-z0-9.-]+(?::\d{1,5})?$/.test(a)||i.host!==a)return!1;return!s||i.protocol===`${s}:`}catch{return!1}}var IC=new Set(["owner","admin","deployer","operator","viewer","auditor"]),mC=new Set(["organization","project","environment","resource"]),EC=new Set(["POST /api/organization/invitations","DELETE /api/organization/invitations","POST /api/organization/invitations/resend","PATCH /api/organization/memberships","DELETE /api/organization/memberships","POST /api/organization/grants","DELETE /api/organization/grants","POST /api/auth/oidc/providers","PATCH /api/auth/oidc/providers","POST /api/automation/service-accounts","PATCH /api/automation/service-accounts","POST /api/automation/tokens","POST /api/automation/tokens/rotate","DELETE /api/automation/tokens","POST /api/security/policies","PATCH /api/security/policies","POST /api/security/waivers","DELETE /api/security/waivers","POST /api/sources/connections","PATCH /api/sources/connections","DELETE /api/sources/connections","POST /api/sources/deploy-keys","DELETE /api/sources/deploy-keys","PATCH /api/telemetry/settings","POST /api/health/checks","PATCH /api/health/checks","POST /api/alerts/rules","PATCH /api/alerts/rules","POST /api/alerts/silences","POST /api/spend/budgets","PATCH /api/spend/budgets","DELETE /api/spend/budgets","POST /api/spend/check","POST /api/spend/release","POST /api/spend/anomalies/acknowledge","POST /api/protection/attack-mode","POST /api/protection/pause","POST /api/protection/ip-rules","DELETE /api/protection/ip-rules","POST /api/notifications/channels","PATCH /api/notifications/channels","POST /api/notifications/routes","PATCH /api/notifications/routes","POST /api/jobs","PATCH /api/jobs","POST /api/jobs/reconcile","POST /api/workers/action","POST /api/data-services","POST /api/data-services/action","POST /api/data-services/dependencies","POST /api/data-services/management","POST /api/data-services/reveal","POST /api/backups/destinations","POST /api/backups/destinations/test","POST /api/backups/policies","POST /api/backups/run","POST /api/backups/verify","POST /api/backups/restore","POST /api/backups/recovery-points","POST /api/backups/retention","POST /api/configuration/reveal","POST /api/configuration/transfer","POST /api/configuration/bulk","DELETE /api/configuration","POST /api/volumes","POST /api/volumes/attach","POST /api/volumes/detach","POST /api/volumes/resize","POST /api/volumes/snapshot","POST /api/volumes/restore","POST /api/volumes/adopt","POST /api/volumes/discover","DELETE /api/volumes","POST /api/fleet","POST /api/fleet/action","POST /api/capacity","POST /api/capacity/member","POST /api/capacity/action","POST /api/capacity/explain","POST /api/regions","POST /api/regions/action","POST /api/maintenance/cleanup-preview","POST /api/maintenance/cleanup-apply","POST /api/maintenance/drill","POST /api/maintenance/drill-run","POST /api/sources/webhooks","PATCH /api/sources/webhooks","DELETE /api/sources/webhooks","POST /api/onboarding/registries","PATCH /api/onboarding/registries","DELETE /api/onboarding/registries","POST /api/runtime/exec-sessions","POST /api/runtime/files/read","POST /api/runtime/files/write","POST /api/onboarding/apply","PATCH /api/queue/settings","DELETE /api/queue/history","POST /api/serverless/secrets","DELETE /api/serverless/secrets"]);function ed(e){let t=String(e??"");return IC.has(t)?t:void 0}function Ha(e){let t=String(e.scopeType??"organization");if(!mC.has(t))return;if(t==="organization")return{type:"organization"};let r=String(e.scopeId??"").trim();return r?{type:t,id:r}:void 0}async function qn(e,t,r={}){let n=Ur(e),i={mode:n,environment:t,environments:Object.keys(e.environments??{}),project:{name:e.project.name,slug:e.project.slug,region:e.project.region}};try{return{...(n==="serverless"?await na(e,t):await To(e,t,{includeSiteHealth:r.includeSiteHealth}))??{},...i}}catch{return{...i}}}function yC(e,t){if(!e)return t;let r={...t,...Array.isArray(e.sites)?{sites:e.sites}:{},...Array.isArray(e.sitesDetail)?{sitesDetail:e.sitesDetail}:{},...Array.isArray(e.siteHealth)?{siteHealth:e.siteHealth}:{}};if(r.mode!=="serverless"&&Array.isArray(r.sites))r.topology=$n(r,{project:r.project?.name,environment:r.environment});return r}function wC(e){let t=[ke(e,"packages","ui"),ke(Zi,"..","..","..","ui"),ke(Zi,"..","..","ui"),ke(Zi,"..","ui-src"),ke(Zi,"..","..","ui-src"),ke(Zi,"..","..","dist","ui-src")];for(let r of t)if(Fr(ke(r,"pages"))&&Fr(ke(r,"package.json")))return r;return null}async function AC(e,t){let r=wC(e);if(!r)return null;let n;try{n=Vg(ke(rd(),`${LI}${process.pid}-`));let i=ke(r,"node_modules",".bin","stx"),a=Fr(i)?[i,"build","--pages","pages","--out",n,"--no-sitemap","--no-cache"]:["bunx","--bun","@stacksjs/stx","build","--pages","pages","--out",n,"--no-sitemap","--no-cache"],s=Bun.spawn(a,{cwd:r,stdout:"pipe",stderr:"pipe",env:{...process.env,TSCLOUD_DASHBOARD_DATA:Pp(t)}}),[d,c,o]=await Promise.all([new Response(s.stdout).text(),new Response(s.stderr).text(),s.exited]);if(o!==0){if(ei(n,{recursive:!0,force:!0}),process.env.TSCLOUD_DASHBOARD_VERBOSE)console.warn(`ts-cloud dashboard: live UI build failed; serving the pre-built UI.
668
+ ${d}
669
+ ${c}`);return null}return n}catch(i){if(n)ei(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 xI(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:Sn(Ki(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 xg(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 MI(e,t){return xg(t).find((r)=>r.id===e)}function mI(e){if(e.length<=_I)return e;return`${e.slice(0,_I)}
670
+
671
+ [output truncated]`}async function EI(e,t,r){let n=e.getReader(),i=new TextDecoder,a="";while(!0){let{done:d,value:c}=await n.read();if(d)break;let o=i.decode(c,{stream:!0});if(a+=o,o)r?.(t,o)}let s=i.decode();if(s)a+=s,r?.(t,s);return a}async function Fg(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,a,s]=await Promise.all([EI(r.stdout,"stdout",t.onOutput),EI(r.stderr,"stderr",t.onOutput),r.exited]);return{action:e.id,command:["cloud",...e.command].join(" "),exitCode:s,ok:s===0,stdout:mI(i),stderr:mI(a)}}finally{t.signal?.removeEventListener("abort",n)}}function PC(){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 DC=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 $C(e){let t=Fa(e);if(t&&t!==".html")return!1;let r=e.replace(/\.html$/,"").replace(/\/+$/,"")||"/";if(r==="/")return!1;return!DC.has(r)}var CC={"/":"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 yI(e,t){if(t.role==="admin")return!0;let r=Fa(e);if(r&&r!==".html")return!0;if(t.organizationSource==="legacy")return!$C(e);let n=e.replace(/\.html$/,"").replace(/\/+$/,"")||"/";if(n==="/access-denied")return!0;let i=CC[n];return!!i&&!!t.capabilities?.includes(i)}function kC(e,t){let r=decodeURIComponent(t).replace(/^\/+/,""),i=X$(r===""?"index.html":r);if(i.startsWith("..")||i.includes("/../"))return null;let a=ke(e,i);if(Fr(a)&&!VI(a).isDirectory())return a;if(!Fa(a)&&Fr(`${a}.html`))return`${a}.html`;if(!Fa(a)&&Fr(ke(a,"index.html")))return ke(a,"index.html");return null}async function wI(e,t){let r=kC(e,t);if(!r){let a=ke(e,"404.html");if(Fr(a))return new Response(await pr(a),{status:404,headers:{"content-type":"text/html; charset=utf-8"}});return nd("Not found",404)}if(VI(r).isDirectory())return nd("Not found",404);let n=await pr(r),i=oC[Fa(r)]??"application/octet-stream";return new Response(n,{headers:{"content-type":i}})}var td=["observe","backup","restore","restart","resize","version","rotate","expose","delete","logs","slow_queries","users","databases"],AI=new WeakMap;async function PI(e){let t=AI.get(e);if(t)return t;let r=await import("./spend/index.js"),n=new r.SpendStore(e),i={store:n,service:new r.SpendService(n),gate:new r.SpendGate(e)};return AI.set(e,i),i}async function bC(e={}){sC();let t=e.cwd??process.cwd(),r=e.host??nC,n=e.port??iC,i=e.cliEntry??process.argv[1];if(e.box)process.env.TS_CLOUD_DASHBOARD_BOX="1";await SC(t);let a=e.config??await __(),s=process.env.TS_CLOUD_DASHBOARD_DB_PASSWORD,d=ht(a);if(s&&d&&!d.password)d.password=s;let c=a.infrastructure?.compute?.managedServices?.vitess;if(s&&c&&typeof c==="object"&&!c.password)c.password=s;let o=_u(t,a);if(o.reconciliation.failed>0)console.warn(` ts-cloud dashboard: marked ${o.reconciliation.failed} orphaned operation(s) as failed after restart.`);let g=Object.keys(a.environments??{}),h=hC(a,e.environment),_=_C(t),R=await qn(a,h),E=new Map([[h,R]]),y=new Map([[h,Date.now()]]),$=new Map([[h,Date.now()]]),b=new Map,z=Math.min(300000,Math.max(5000,Number(process.env.TS_CLOUD_DASHBOARD_REFRESH_MS)||30000)),C=Math.min(1800000,Math.max(60000,Number(process.env.TS_CLOUD_DASHBOARD_SITE_REFRESH_MS)||300000)),B=Ur(a)!=="serverless",N=(S)=>{let X=E.get(S);if(X&&!RI(y.get(S),Date.now(),z))return Promise.resolve(X);let ee=b.get(S);if(ee)return ee;let Y=!B||RI($.get(S),Date.now(),C),se=qn(a,S,{includeSiteHealth:Y}).then((ye)=>{let m=E.get(S),St=Y?ye:yC(m,ye);if(E.set(S,St),y.set(S,Date.now()),Y)$.set(S,Date.now());if(m?._serverReachable!==St._serverReachable||m?._metricsStatus!==St._metricsStatus||(m?.sitesDetail?.length??0)!==(St.sitesDetail?.length??0))de();return St}).finally(()=>b.delete(S));return b.set(S,se),se},F=Lg(t),J=process.env.TS_CLOUD_DASHBOARD_TELEMETRY?.trim();if(e.box&&J!=="0"&&(J==="1"||!a.cloud?.attachTo)){let S=!1,X=Date.now()+300000,ee=async()=>{if(S)return;S=!0;try{let se=Date.now(),ye=se>=X;if(ye)X=se+300000;let m=o.environments.get(h);await Hg({controlPlane:o.store,projectId:o.project.id,environmentId:m?.id,config:a,environment:h,force:!0,lightweight:!0,includeSiteHealth:ye})}catch(se){if(e.verbose)console.warn(` ts-cloud dashboard: background telemetry collection failed: ${se instanceof Error?se.message:String(se)}`)}finally{S=!1}};ee(),setInterval(()=>void ee(),60000).unref?.()}let O=new Map,K=new Map,ae=new Set,Se=0;function Te(S,X){if(S.role==="admin"&&!o.store.getActorByExternalId("user",`dashboard:${S.username.toLowerCase()}`))return S;let ee=o.store.getActorByExternalId("user",`dashboard:${S.username.toLowerCase()}`),Y=ee?o.store.getMembershipForActor(o.organization.id,ee.id):void 0;if(!Y||Y.status!=="active")return{...S,role:"member",sites:{},capabilities:[]};let se=o.store.listGrants(Y.id),ye=o.store.resolveAuthorizationTarget(o.organization.id,Y.scope)??o.store.resolveAuthorizationTarget(o.organization.id,{type:"project",id:o.project.id}),m=Na({membership:Y,grants:se,target:ye});if(Y.roleTemplate==="owner"||Y.roleTemplate==="admin")return{...S,role:"admin",sites:{},organizationRole:Y.roleTemplate,organizationSource:Y.source,capabilities:m};let St=o.environments.get(X),Me={};for(let le of o.store.listResources(o.project.id,St?.id).filter((fe)=>fe.kind==="application")){let fe=o.store.resolveAuthorizationTarget(o.organization.id,{type:"resource",id:le.id});if(!fe||!qt({membership:Y,grants:se,capability:"project:read",target:fe}).allowed)continue;Me[le.slug]=qt({membership:Y,grants:se,capability:"config:write",target:fe}).allowed?"owner":"collaborator"}return{...S,role:"member",sites:Me,organizationRole:Y.roleTemplate,organizationSource:Y.source,capabilities:m}}function de(){Se+=1,O.clear();for(let S of ae)ei(S,{recursive:!0,force:!0});ae.clear()}let Ae=(S,X)=>`${X}:${S.role==="admin"?"admin":`member:${Object.entries(S.sites).sort(([ee],[Y])=>ee.localeCompare(Y)).map(([ee,Y])=>`${ee}=${Y}`).join(",")}`}:${[...S.capabilities??[]].sort().join(",")}`;async function ze(S,X){let ee=Te(S,X),Y=Ae(ee,X),se=O.get(Y);if(se)return se;let ye=K.get(Y);if(ye)return ye;let m=Se,St=(async()=>{let Me=E.get(X)??await qn(a,X);E.set(X,Me);let le={...Cg(Me,{user:ee,slug:a.project.slug}),viewer:{role:ee.role,organizationRole:ee.organizationRole,organizationSource:ee.organizationSource,capabilities:ee.capabilities??[]}},fe=await AC(t,le);if(fe&&m!==Se)return ei(fe,{recursive:!0,force:!0}),F?.uiRoot;if(fe)ae.add(fe);let st=fe??F?.uiRoot;if(st)O.set(Y,st);return st})();K.set(Y,St);try{return await St}finally{K.delete(Y)}}let ue=await ze({username:"",passwordHash:"",role:"admin",sites:{}},h);if(!ue)throw Error("ts-cloud dashboard UI not found. Run `bun run build` in ts-cloud or reinstall the package.");let P=new WeakMap,T=process.env.TS_CLOUD_DASHBOARD_TERMINAL!=="0",U=process.env.TS_CLOUD_DASHBOARD_AUTH==="0";if(U&&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 M=!U,_e=tp(t),Pe=M?ap(t,process.env.TS_CLOUD_UI_USERNAME?.trim()||"admin"):void 0,G=new ps(o.store,{encryptionKey:nn(t)}),pe=new Es(o.store),he=new Ca(o.store),ie=new Td(o.store,{encryptionKey:nn(t)}),ft=new wd(o.store),ti=new $d(o.store,{cwd:t}),dr=new Pd(o.store,{encryptionKey:nn(t)}),be=new Be(o.store,{workerId:`dashboard:${process.pid}`}),We=new Sc(o.store),Ir=new Pc(o.store,nn(t)),Vr=new $l(o.store),Va=new Os(We,be,Ir),Lr=a.project?.region??"us-east-1",Mg=nn(t),bt=new vl(Vr,{encryptionKey:Mg,backends:[new Aa(o.store,Mg),new Cl(new Kr(Lr),Lr),new kl(new FI(Lr),Lr),new bl]});await A_(bt,o,a);let id=new Un(Lr),QI={aws_rds:new _c(new yc(id)),aws_aurora:new Rc(new wc(id)),aws_elasticache:new pc(new Ac(new Ts(Lr))),server:new Ic(new yi),container:new mc(new yi)},Qg=(S)=>QI[S.provider],Qe=new gc(o.store),In=new ks(Qe,be),Gg=new hc(Ir),GI={managed_database:new fc(We,id),logical_database:new kc(We,Ir),volume:new vc,files:new Cc(t),control_plane:new Bc(o.store,t),infrastructure:new Tc(new Hs(Lr))},ZI=(S)=>GI[S.resourceKind],KI=(S)=>S.provider==="aws_backup"?void 0:Gg,ad=new TI(o.store),sd=[new BI,new JI(_t(t,"volumes"))],mr=new vI(ad,sd,be),Yi=new Bl(o.store),cr=new Jl(Yi,[new Pa("aws"),new Pa("hetzner"),new Pa("ssh")],be),xr=new Nl(o.store),Zg=new Fl(xr,Yi),mn=new Ml(o.store),Kg=new Ql(mn,be),Er=new Wl(o.store),od=new jl(Er,be),Yg=["releases","artifacts","operations","logs","previews","snapshots","orphaned_resources"].map((S)=>new Hl(S,o.store,o.project.id,o.organization.id)),it=new oc(o.store),Xg=new ac(it,{queue:be}),xe=new fs(o.store),Mr=new Ss(o.store),Ht=new vn(o.store),ce=new zI(o.store,{encryptionKey:nn(t)}),YI=()=>PI(o.store);for(let S of o.environments.values())ic(it,a,{organization:o.organization,project:o.project,environment:S,resources:o.store.listResources(o.project.id,S.id)});let Nt=new WI(ce,{emailImpl:async(S)=>{let{email:X}=await import("./chunk-0k1cs6pp.js");return X.send(S)}}),qg=async(S)=>{let X=NI(ce,o.project.id,S),ee=[];for(let Y of X.filter((se)=>se.notify&&se.alert))ee.push(...await Nt.deliverAll(Nt.enqueue(o.organization.id,Y.alert,Y.transition)));return ee.push(...await Nt.deliverAll(Nt.enqueueRemindersAndEscalations(o.organization.id,ce.listAlerts(o.project.id,{environmentId:S,states:["firing"]})))),ee.push(...await Nt.retryDue()),{evaluations:X,deliveries:ee}},dd=!1,XI=async()=>{if(dd)return;dd=!0;try{for(let S of o.environments.values())for(let X of ce.listHealthChecks(o.project.id,S.id).filter((ee)=>ee.enabled)){let ee=ce.listHealthResults(X.id,1)[0];if(ee&&Date.now()-new Date(ee.checkedAt).getTime()<X.intervalSeconds*1000)continue;let Y=await new Gi(ce).runAndEvaluate(X);for(let se of Y.evaluations.filter((ye)=>ye.notify&&ye.alert))await Nt.deliverAll(Nt.enqueue(o.organization.id,se.alert,se.transition))}}finally{dd=!1}},eu=setInterval(()=>{for(let S of o.environments.values())qg(S.id).catch((X)=>console.error("ts-cloud alert evaluation failed:",X))},60000);eu.unref?.();let tu=setInterval(()=>{XI().catch((S)=>console.error("ts-cloud health check evaluation failed:",S))},30000);tu.unref?.();let ru=setInterval(()=>{try{Xg.tick()}catch(S){console.error("ts-cloud scheduled job evaluation failed:",S)}},30000);ru.unref?.();let nu=setInterval(()=>{try{In.enqueueDue(),In.enqueueRetention()}catch(S){console.error("ts-cloud backup policy evaluation failed:",S)}},30000);nu.unref?.(),xe.cleanup();let iu=setInterval(()=>{try{xe.cleanup()}catch(S){console.error("ts-cloud preview cleanup failed:",S)}},3600000);iu.unref?.();let qI=e.queueWorker??!0,em=PC(),tm=async(S,X)=>{let Y=(S.environmentId?o.store.listEnvironments(S.projectId).find((se)=>se.id===S.environmentId):void 0)?.slug??String(h);if(X.kind==="dashboard_operation"&&X.operationId){let se=E.get(Y)??R,ye=$g(X.operationId,a,se);if(!ye||ye.danger||!["scheduler","backup","worker"].includes(ye.group))return{ok:!1,stderr:"The allowlisted dashboard operation is no longer available."};let m=await Zo(a,Y,ye);return{ok:m.ok,stdout:m.stdout,stderr:m.stderr??m.error,retryable:/temporar|unavailable|timeout|network/i.test(m.stderr??m.error??""),output:{command:m.command??null,operation:m.operation}}}if(X.kind==="serverless_scheduler"){let se=await zg(a,Y,"run");return{ok:se.ok,stdout:se.stdout,stderr:se.error,retryable:/temporar|unavailable|timeout|network/i.test(se.error??""),output:{command:se.command??null,operation:"serverless_scheduler"}}}return{ok:!1,stderr:`No safe executor is configured for ${X.kind}.`}},La=qI?new kI(be,{...bI({store:o.store,execute:async(S,X)=>{let ee=X.operation.input&&typeof X.operation.input==="object"&&!Array.isArray(X.operation.input)?X.operation.input:{},Y=ee.source&&typeof ee.source==="object"?ee.source:void 0,se=t,ye,m,St;try{if(Y?.bindingId&&Y?.connectionId&&Y?.commitSha){let le=ie.getBinding(String(Y.bindingId)),fe=ie.getConnection(String(Y.connectionId));if(!le||!fe||le.connectionId!==fe.id)throw Error("Queued source binding is no longer available");let et=(le.repositoryId?ie.getRepository(le.repositoryId):ie.listRepositories(fe.id).find((ii)=>ii.fullName.toLowerCase()===le.repositoryFullName.toLowerCase()))?.cloneUrl;if(!et&&fe.provider==="generic_ssh")et=`git@${new URL(fe.host).hostname}:${le.repositoryFullName}.git`;if(!et)et=new URL(`/${le.repositoryFullName}.git`,fe.host.endsWith("/")?fe.host:`${fe.host}/`).href;let V=le.deployKeyId?ie.getDeployKey(le.deployKeyId):void 0,je=V&&le.deployKeyId?{...V,privateKey:ie.getDeployPrivateKey(le.deployKeyId)}:void 0;if(["github","gitlab","bitbucket","gitea"].includes(fe.provider)&&S.target.previewId){let ii=en(fe,ie.getCredential(fe.id)),W=xe.previews.getInstance(S.target.previewId);St=async(Ft,Za)=>{try{await ii.setCommitStatus(le.repositoryFullName,String(Y.commitSha),{state:Ft,url:W?.url,description:Za})}catch(ai){X.log(`Could not publish source status: ${ai instanceof Error?ai.message:String(ai)}`,{stream:"stderr"})}},await St("pending",`Preview deployment started for ${String(Y.commitSha).slice(0,12)}`)}ye=Vg(ke(rd(),"ts-cloud-queued-source-")),X.log(`Checking out immutable source commit ${Y.commitSha}.`,{stream:"system"}),se=(await jd({remote:et,binding:le,destination:ke(ye,"checkout"),ref:String(Y.branch??le.defaultBranch),commitSha:String(Y.commitSha)},{credential:ie.getCredential(fe.id),deployKey:je})).directory}if(X.operation.kind!=="preview.destroy"){let le=S.target.previewId?xe.previews.getInstance(S.target.previewId):void 0,fe=le?xe.previews.getDefinition(le.definitionId):void 0,st=X.operation.resourceId?o.store.getResource(X.operation.resourceId):void 0;if(m=await bt.resolve({projectId:o.project.id,environmentId:X.operation.environmentId,resourceId:X.operation.resourceId,functionId:st?.kind==="function"?st.id:void 0,previewId:le?.id,trustedPreview:!!le&&!le.fork,allowedPreviewSecrets:fe?.inheritedSecrets}),m.warnings.some((et)=>et.code==="missing_required"))throw Error(`Required deployment configuration is unavailable: ${m.warnings.filter((et)=>et.code==="missing_required").map((et)=>et.key).join(", ")}`);if(X.operation.resourceId)for(let et of Object.values(m.entries))Vr.setDependency({entryId:et.id,resourceId:X.operation.resourceId,injectionTarget:"environment",required:et.required,requiresRedeploy:!0});X.log(`Resolved configuration ${m.configurationHash.slice(0,18)} for ${Object.keys(m.values).length} keys.`,{stream:"system"})}let Me=await Fg(S,{cwd:se,cliEntry:i,signal:X.signal,env:m?.values,onOutput:(le,fe)=>X.log(fe,{stream:le,step:"execute",secrets:[...em,...Object.entries(m?.entries??{}).filter(([,st])=>st.kind==="secret").map(([st])=>m.values[st]).filter(Boolean)]})});if(Me.ok&&X.operation.resourceId&&m)for(let le of Object.values(m.entries))Vr.setDependency({entryId:le.id,resourceId:X.operation.resourceId,injectionTarget:"environment",required:le.required,requiresRedeploy:!1,lastDeployedVersion:le.version});return await St?.(Me.ok?"success":"failure",Me.ok?`Preview is ready at ${String(Y?.commitSha).slice(0,12)}`:`Preview deployment failed at ${String(Y?.commitSha).slice(0,12)}`),Me}catch(Me){throw await St?.("error",`Preview deployment could not complete at ${String(Y?.commitSha).slice(0,12)}`),Me}finally{if(ye)ei(ye,{recursive:!0,force:!0})}}}),...mf({store:it,executor:tm}),...Of({store:We,secrets:Ir,resolveAdapter:Qg}),...$_(Yi,cr.drivers),...G_(mn,[new Gl("aws","AWS regional execution requires an injected AwsRegionalTransport; topology and plans were preserved without provider mutation.")]),...H_({store:Er,cleanup:Yg}),...OI(ad,sd),...Cf({store:Qe,queue:be,resolveSource:ZI,resolveDestination:KI,validateHealth:async(S,X)=>{if(!S.healthCheckId)return{healthy:!0,mode:"adapter"};let ee=ce.getHealthCheck(S.healthCheckId);if(!ee||ee.projectId!==S.projectId)return{healthy:!1,error:"Configured restore health check was not found."};let Y=await new Gi(ce).runAndEvaluate(ee);return{healthy:Y.result.status==="healthy",healthCheckId:ee.id,healthResultId:Y.result.id,target:X}}}),...yh({store:o.store,resolveDriver:e.releaseDriver??((S)=>({name:`${o.store.getResource(S.resourceId)?.provider??"provider"} release driver`,capability:()=>({strategy:S.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(S,X)=>{let ee=ce.listHealthChecks(X.projectId,X.environmentId).find((se)=>se.enabled&&se.name===S&&(!se.resourceId||se.resourceId===X.resourceId));if(!ee)return{healthy:!1,message:`Named health gate ${S} was not found for this release.`};let Y=await new Gi(ce).runAndEvaluate(ee);return{healthy:Y.result.status==="healthy",evidence:{healthCheckId:ee.id,healthResultId:Y.result.id,status:Y.result.status,timings:Y.result.timings},message:Y.result.message}}})},{parallelism:e.queueParallelism??(Number(process.env.TS_CLOUD_QUEUE_PARALLELISM)||8),onError:(S)=>console.error("ts-cloud deployment queue worker failed:",S)}):void 0;if(RR(o),Bo(he,sr(o,String(h)),R),Pe)Ka(o,Pe.users),dp(G,o,Pe.users);let He=sp({cwd:t,enabled:M,secret:_e,authentication:G,authorization:{store:o.store,organizationId:o.organization.id,projectId:o.project.id,defaultEnvironment:String(h)}}),Ge=new Xl,au=setInterval(()=>Ge.sweep(),60000);au.unref?.();let xa=new za,cd=new za(3,900000,900000),Ma=new za(8,900000,900000),su=setInterval(()=>xa.prune(),300000),ou=setInterval(()=>cd.prune(),300000),du=setInterval(()=>Ma.prune(),300000);if(su.unref?.(),ou.unref?.(),du.unref?.(),M){if(Pe?.generated)console.warn(`
672
+ ts-cloud dashboard: created the first admin.
673
+ username: ${Pe.generated.username}
674
+ password: ${Pe.generated.password}
675
+ Saved (hashed) to ${np()}. This password is shown once.
676
+ `)}else console.warn(" ts-cloud dashboard: authentication is DISABLED (TS_CLOUD_DASHBOARD_AUTH=0). Every request runs as an admin.");let Qr=r!=="127.0.0.1"&&r!=="localhost",ld=(S)=>K$("sha256").update(`${_e}:${S}`).digest("hex").slice(0,16),rm=Fd({controlPlane:o.store,identities:pe,sources:ie,applications:{drafts:ft,artifacts:ti,registries:dr}}),cu=(S)=>S.headers.get("user-agent")?.trim().slice(0,256)||void 0,Qa=(S,X,ee,Y="local")=>G.createSession({identityId:S,authMethod:Y,userAgent:cu(X),networkHint:ld(ee)}),te=(S)=>{let X=o.store.getActorByExternalId("user",`dashboard:${S.username.toLowerCase()}`),ee=X?o.store.getMembershipForActor(o.organization.id,X.id):void 0;return{actor:X,membership:ee,grants:ee?o.store.listGrants(ee.id):[]}},ri=(S,X,ee)=>{if(S.role==="admin")return!0;let Y=o.store.getOperation(X),se=te(S);if(!Y||!se.membership)return!1;let ye=Y.resourceId?{type:"resource",id:Y.resourceId}:Y.environmentId?{type:"environment",id:Y.environmentId}:Y.projectId?{type:"project",id:Y.projectId}:{type:"organization"},m=o.store.resolveAuthorizationTarget(o.organization.id,ye);return!!m&&qt({membership:se.membership,grants:se.grants,capability:ee,target:m}).allowed},at=(S,X,ee)=>{if(S.role==="admin")return!0;let Y=te(S);if(!Y.membership)return!1;let se=o.store.resolveAuthorizationTarget(o.organization.id,{type:"resource",id:X});return!!se&&qt({membership:Y.membership,grants:Y.grants,capability:ee,target:se}).allowed},Xi=(S,X,ee)=>{if(S.role==="admin")return!0;let Y=te(S);if(!Y.membership)return!1;let se=o.store.resolveAuthorizationTarget(o.organization.id,{type:"environment",id:X});return!!se&&qt({membership:Y.membership,grants:Y.grants,capability:ee,target:se}).allowed},Ga=(S,X)=>{if(S.role==="admin")return!0;let ee=te(S);if(!ee.membership)return!1;let Y=o.store.resolveAuthorizationTarget(o.organization.id,{type:"organization"});return!!Y&&qt({membership:ee.membership,grants:ee.grants,capability:X,target:Y}).allowed},ni=Bun.serve({hostname:r,port:n,idleTimeout:30,websocket:{open(S){if(!T){S.send(`The web terminal is disabled (TS_CLOUD_DASHBOARD_TERMINAL=0).\r
677
+ `),S.close();return}let X=fI((ee)=>S.send(ee),{cwd:t,onExit:()=>{try{S.close()}catch{}}});P.set(S,X),S.send(`Connected to ${r==="127.0.0.1"?"localhost":r} shell. This is a line-oriented shell (no full-screen apps).\r
678
+ `)},message(S,X){P.get(S)?.write(typeof X==="string"?X:new TextDecoder().decode(X))},close(S){P.get(S)?.close(),P.delete(S)}},async fetch(S,X){let ee=Date.now(),Y=S.clone(),se=S.headers.get("x-request-id")?.slice(0,128)||crypto.randomUUID(),ye=!["GET","HEAD","OPTIONS"].includes(S.method.toUpperCase()),m=new URL(S.url),Me=await(async()=>{let le=X??ni,fe=uC(r,le.port??n),st=await rm(S,ld(le.requestIP(S)?.address??"unknown"));if(st)return st;let et=m.searchParams.get("env"),V=fC(g,h,et),je=E.get(V);if(!je)je=await N(V);try{if(!pC(S))return f({ok:!1,error:"Cross-site requests are not allowed."},403);let En=/^\/api\/source\/webhooks\/([A-Za-z0-9_-]{16,200})$/.exec(m.pathname);if(En&&S.method==="POST"){let l=await jh({sources:ie,controlPlane:o.store,endpointToken:En[1],headers:S.headers,rawBody:new Uint8Array(await S.arrayBuffer())});return f({accepted:l.accepted,duplicate:l.duplicate,status:l.status,operationIds:l.operations.map((u)=>u.id),message:l.message},l.accepted?202:404)}let ii=/^\/auth\/oidc\/([a-z0-9-]+)\/(start|callback)$/.exec(m.pathname);if(ii&&S.method==="GET"){let[,l,u]=ii;if(!fe)return new Response(null,{status:302,headers:{location:"/login?sso_error=configuration"}});if(u==="start")try{let p=await qd(G,l,fe,m.searchParams.get("return")??void 0,e.oidcFetch);return new Response(null,{status:302,headers:{location:p.authorizationUrl,"cache-control":"no-store"}})}catch(p){return o.store.appendEvent({organizationId:o.organization.id,type:"auth.oidc.start_failed",level:"warning",payload:{provider:l,reason:p instanceof Error?p.message.slice(0,200):"unknown"}}),new Response(null,{status:302,headers:{location:"/login?sso_error=start","cache-control":"no-store"}})}try{if(m.searchParams.has("error")){let D=G.getOidcProviderBySlug(l),A=m.searchParams.get("state");if(D&&A)G.consumeOidcTransaction(D.id,A);throw Error("OIDC provider returned an authorization error")}let p=await ec(G,{providerSlug:l,state:m.searchParams.get("state")??"",code:m.searchParams.get("code")??"",origin:fe},e.oidcFetch),I=cp(G,o,t,p.identity);G.recordLogin(I.identity.id);let w=Qa(I.identity.id,S,le.requestIP(S)?.address??"unknown","oidc");return de(),o.store.appendEvent({organizationId:o.organization.id,actorId:I.identity.actorId,type:"auth.login.succeeded",payload:{method:"oidc",provider:l,provisioned:I.provisioned}}),new Response(null,{status:302,headers:{location:p.returnPath,"cache-control":"no-store","set-cookie":Li(w.token,{secure:Qr,maxAgeMs:rn})}})}catch(p){return o.store.appendEvent({organizationId:o.organization.id,type:"auth.oidc.callback_failed",level:"warning",payload:{provider:l,reason:p instanceof Error?p.message.slice(0,200):"unknown"}}),new Response(null,{status:302,headers:{location:"/login?sso_error=callback","cache-control":"no-store"}})}}if(m.pathname==="/api/invitations/accept"&&S.method==="POST"){let l=await v(S),u=String(l.token??"").trim(),p=String(l.username??"").trim(),I=String(l.password??"");if(!u||!Lo(p)||I.length<12)return f({ok:!1,error:"Invitation token, valid username, and a password of at least 12 characters are required."},422);let w=o.store.inspectInvitationToken(u);if(!w||w.state!=="pending")return f({ok:!1,error:w?`Invitation is ${w.state}`:"Invitation is invalid"},w?409:404);let D=Zt(kt(t),p),A=G.getIdentityByUsername(p);if(D&&!or(I,A?.passwordHash??D.passwordHash))return f({ok:!1,error:"That username already exists; enter its current password to continue."},401);let k=G.getIdentityByEmail(w.email);if(k&&k.id!==A?.id)return f({ok:!1,error:"This invitation belongs to an existing account. Sign in with that account or ask an owner to resend it."},409);let H=Ba(t,{username:p,password:D?void 0:I,name:typeof l.name==="string"?l.name:void 0,email:w.email,sites:D?.sites??{}}),j=Ke(o.store,H.user);try{let oe=o.store.acceptInvitation(u,j.id),L=A?G.setVerifiedEmail(A.id,oe.invitation.email):G.createIdentity({actorId:j.id,username:H.user.username,email:oe.invitation.email,emailVerified:!0,passwordHash:H.user.passwordHash}),re=Qa(L.id,S,le.requestIP(S)?.address??"unknown");return de(),f({ok:!0,user:xi(H.user),organization:o.organization,membership:oe.membership},200,{"set-cookie":Li(re.token,{secure:Qr,maxAgeMs:rn})})}catch(oe){if(!D)Ag(t,H.user.username);let L=oe instanceof Error?oe.message:"Invitation could not be accepted.";return f({ok:!1,error:L},L.includes("expired")||L.includes("revoked")||L.includes("accepted")?409:404)}}if(m.pathname==="/api/auth/password-reset/request"&&S.method==="POST"){let l=await v(S),u=String(l.identifier??"").trim().toLowerCase(),p=le.requestIP(S)?.address??"unknown",I=cd.check(u,p),w=u.includes("@")?G.getIdentityByEmail(u):G.getIdentityByUsername(u);if(I.allowed)cd.recordFailure(u,p);if(I.allowed&&w?.email&&w.emailVerifiedAt&&!w.disabledAt){G.revokeActionTokens(w.id,"password_reset");let D=G.createActionToken(w.id,"password_reset"),A=`${m.origin}/reset-password?token=${encodeURIComponent(D.token)}`,k=await ha(a,{to:w.email,subject:"Reset your ts-cloud password",text:`Reset your ts-cloud password: ${A}
679
+
680
+ This link expires in one hour and can be used once.`});o.store.appendEvent({organizationId:o.organization.id,actorId:w.actorId,type:"auth.password_reset.requested",payload:{delivered:k}})}return f({ok:!0,message:"If that account has a verified email, a reset link has been sent."},202)}if(m.pathname==="/api/auth/password-reset/complete"&&S.method==="POST"){let l=await v(S),u=String(l.token??"").trim(),p=String(l.password??"");if(!u||p.length<12)return f({ok:!1,error:"A valid reset token and password of at least 12 characters are required."},422);try{let I=G.consumeActionToken(u,"password_reset"),w=fn(p),D=G.updatePassword(I.identityId,w);return Mo(t,D.username,w),o.store.appendEvent({organizationId:o.organization.id,actorId:D.actorId,type:"auth.password_reset.completed"}),f({ok:!0,message:"Password changed. Sign in again."},200,{"set-cookie":Vo({secure:Qr})})}catch(I){let w=I instanceof Error?I.message:"Password reset failed.";return f({ok:!1,error:w.replace("Action token","Reset link")},w.includes("consumed")||w.includes("expired")?409:404)}}if(m.pathname==="/api/login"&&S.method==="POST"){let l=await v(S),u=String(l.username??"").trim(),p=String(l.password??""),I=le.requestIP(S)?.address??"unknown",w=xa.check(u,I);if(!w.allowed)return f({ok:!1,error:`Too many failed attempts. Try again in ${Math.ceil((w.retryAfterSeconds??0)/60)} minute(s).`},429,{"retry-after":String(w.retryAfterSeconds??60)});let D=Zt(kt(t),u),A=G.getIdentityByUsername(u),k=A?.passwordHash??D?.passwordHash??gC;if(!(or(p,k)&&!!D&&!!A&&!A.disabledAt))return xa.recordFailure(u,I),f({ok:!1,error:"Incorrect username or password."},401);if(lp(G,o,A))return f({ok:!1,error:"Single sign-on is required for this account."},403);xa.recordSuccess(u,I);let j=A,oe=j.requiresPasswordUpgrade||mR(j.passwordHash);if(oe){let re=fn(p);j=G.rehashPassword(j.id,re),Mo(t,j.username,re)}if(G.recordLogin(j.id),G.getMfaFactor(j.id)?.state==="active"){let re=G.createMfaChallenge(j.id,"login");return o.store.appendEvent({organizationId:o.organization.id,actorId:j.actorId,type:"auth.mfa.challenge.created",payload:{purpose:"login"}}),f({ok:!0,mfaRequired:!0,challengeToken:re.token,passwordUpgraded:oe})}let L=Qa(j.id,S,I);return o.store.appendEvent({organizationId:o.organization.id,actorId:j.actorId,type:"auth.login.succeeded",payload:{method:"local"}}),f({ok:!0,user:xi(D),passwordUpgraded:oe},200,{"set-cookie":Li(L.token,{secure:Qr,maxAgeMs:rn})})}if(m.pathname==="/api/auth/mfa/complete"&&S.method==="POST"){let l=await v(S),u=String(l.challengeToken??"").trim(),p=String(l.code??"").trim(),I=le.requestIP(S)?.address??"unknown",D=G.inspectMfaChallengeToken(u,"login")?.identityId??"unknown-mfa",A=Ma.check(D,I);if(!A.allowed)return f({ok:!1,error:"Too many MFA attempts. Try again later."},429,{"retry-after":String(A.retryAfterSeconds??60)});try{let k=G.completeMfaChallenge(u,p,"login");Ma.recordSuccess(D,I);let H=new Date().toISOString(),j=G.createSession({identityId:k.identity.id,userAgent:cu(S),networkHint:ld(I),mfaAt:H,recentAuthAt:H});return o.store.appendEvent({organizationId:o.organization.id,actorId:k.identity.actorId,type:"auth.mfa.succeeded",payload:{purpose:"login",method:k.method}}),f({ok:!0},200,{"set-cookie":Li(j.token,{secure:Qr,maxAgeMs:rn})})}catch{return Ma.recordFailure(D,I),f({ok:!1,error:"Authenticator or recovery code is incorrect."},401)}}if(m.pathname==="/api/logout"&&S.method==="POST"){let l=He.resolveSession(S);if(l)G.revokeSession(l.identityId,l.id);let u=Vo({secure:Qr});if(S.headers.get("accept")?.includes("text/html"))return new Response(null,{status:302,headers:{location:"/login","set-cookie":u}});return f({ok:!0},200,{"set-cookie":u})}if(m.pathname==="/login"){let l=G.listOidcProviders(o.organization.id).map((u)=>({slug:u.slug,name:u.name}));return new Response(gp(R?.mode==="serverless",l),{headers:{"content-type":"text/html; charset=utf-8"}})}if(m.pathname==="/forgot-password"||m.pathname==="/reset-password")return new Response(up(m.pathname==="/reset-password"?"reset":"request"),{headers:{"content-type":"text/html; charset=utf-8"}});if(m.pathname==="/accept-invitation")return wI(ue,m.pathname);let W=He.resolveUser(S);if(!W){if(!m.pathname.startsWith("/api/")&&S.headers.get("accept")?.includes("text/html"))return new Response(null,{status:302,headers:{location:"/login"}});return f({ok:!1,error:"Sign in to continue."},401)}let Ft=Te(W,V);if(m.pathname==="/api/me"){let l=o.store.getActorByExternalId("user",`dashboard:${W.username.toLowerCase()}`),u=l?o.store.getMembershipForActor(o.organization.id,l.id):void 0,p=o.store.resolveAuthorizationTarget(o.organization.id,u?.scope??{type:"project",id:o.project.id})??o.store.resolveAuthorizationTarget(o.organization.id,{type:"project",id:o.project.id});return f({ok:!0,user:xi(W),authEnabled:M,organization:o.organization,membership:u,capabilities:Na({membership:u,grants:u?o.store.listGrants(u.id):[],target:p})})}if(m.pathname.startsWith("/api/")){let l=await op(S,m.pathname),u=He.check(S,m.pathname,W,l);if(!u.ok)return f({ok:!1,error:u.error},u.status??403);if(M&&EC.has(`${S.method.toUpperCase()} ${m.pathname}`)){let p=He.resolveSession(S);if(!p||!G.isRecentlyAuthenticated(p))return f({ok:!1,error:"Recent authentication is required for this change.",stepUpRequired:!0},401)}}if(m.pathname==="/api/auth/security"&&S.method==="GET"){let l=te(W),u=l.actor?G.getIdentityByActor(l.actor.id):void 0,p=He.resolveSession(S);return f({identity:u?{username:u.username,email:u.email,emailVerifiedAt:u.emailVerifiedAt,requiresPasswordUpgrade:u.requiresPasswordUpgrade,lastLoginAt:u.lastLoginAt}:void 0,currentSessionId:p?.id,sessions:u?G.listSessions(u.id,{includeInactive:!0}):[],mfa:u?{factor:G.getMfaFactor(u.id),recoveryCodesRemaining:G.remainingRecoveryCodes(u.id)}:void 0})}if(m.pathname==="/api/auth/oidc/providers"&&S.method==="GET")return f({providers:G.listOidcProviders(o.organization.id,{includeDisabled:!0}),callbackOrigin:fe,callbackPattern:fe?`${fe}/auth/oidc/{slug}/callback`:void 0,localOwnerRecovery:!0});if(m.pathname==="/api/auth/oidc/providers"&&S.method==="POST"){let l=await v(S),u=te(W),p=u.actor?G.getIdentityByActor(u.actor.id):void 0,I=l.enforceSso===!0;if(I&&(!p?.emailVerifiedAt||G.remainingRecoveryCodes(p.id)<1))return f({ok:!1,error:"Verify the owner email and generate MFA recovery codes before enforcing SSO."},409);try{let w=ed(l.defaultRole),D=G.upsertOidcProvider({id:typeof l.id==="string"?l.id:void 0,organizationId:o.organization.id,slug:String(l.slug??""),name:String(l.name??""),issuer:String(l.issuer??""),clientId:String(l.clientId??""),clientSecret:typeof l.clientSecret==="string"&&l.clientSecret?l.clientSecret:void 0,scopes:Array.isArray(l.scopes)?l.scopes.map(String):void 0,allowedDomains:Array.isArray(l.allowedDomains)?l.allowedDomains.map(String):[],defaultRole:w&&w!=="owner"?w:void 0,enabled:l.enabled!==!1,enforceSso:I});return o.store.appendEvent({organizationId:o.organization.id,actorId:u.actor?.id,type:"auth.oidc.provider.configured",payload:{providerId:D.id,issuer:D.issuer,enabled:D.enabled,enforceSso:D.enforceSso}}),f({ok:!0,provider:D})}catch(w){return f({ok:!1,error:w instanceof Error?w.message:"OIDC provider could not be saved."},422)}}if(m.pathname==="/api/auth/oidc/providers"&&S.method==="PATCH"){let l=await v(S),u=G.getOidcProvider(String(l.id??""));if(!u||u.organizationId!==o.organization.id)return f({ok:!1,error:"OIDC provider was not found."},404);let p=te(W),I=G.setOidcProviderEnabled(u.id,l.enabled===!0);return o.store.appendEvent({organizationId:o.organization.id,actorId:p.actor?.id,type:I.enabled?"auth.oidc.provider.enabled":"auth.oidc.provider.disabled",payload:{providerId:u.id}}),f({ok:!0,provider:I})}if(m.pathname==="/api/automation"&&S.method==="GET"){let l=pe.listServiceAccounts(o.organization.id,{includeDisabled:!0}).map((u)=>{let p=o.store.getMembershipForActor(o.organization.id,u.actorId),I=u.createdByActorId?o.store.getActor(u.createdByActorId):void 0,w=pe.listTokens(u.id,{includeInactive:!0}).map((D)=>({...D,createdBy:D.createdByActorId?o.store.getActor(D.createdByActorId):void 0}));return{account:u,createdBy:I,membership:p,tokens:w}});return f({accounts:l,apiBaseUrl:`${m.origin}/api/v1`,openApiUrl:`${m.origin}/api/v1/openapi.json`,tokenEnvironmentVariable:"TS_CLOUD_API_TOKEN"})}if(m.pathname==="/api/automation/service-accounts"&&S.method==="POST"){let l=await v(S),u=te(W),p=ed(l.roleTemplate),I=Ha(l);if(!u.actor||!p||p==="owner"||!I)return f({ok:!1,error:"A non-owner role and valid organization scope are required."},422);try{let w=pe.createServiceAccount({organizationId:o.organization.id,slug:String(l.slug??""),name:String(l.name??""),description:typeof l.description==="string"?l.description:void 0,roleTemplate:p,scope:I,createdByActorId:u.actor.id});return f({ok:!0,...w},201)}catch(w){return f({ok:!1,error:w instanceof Error?w.message:"Service account could not be created."},422)}}if(m.pathname==="/api/automation/service-accounts"&&S.method==="PATCH"){let l=await v(S),u=te(W),p=pe.getServiceAccount(String(l.id??""));if(!p||p.organizationId!==o.organization.id)return f({ok:!1,error:"Service account was not found."},404);return f({ok:!0,account:pe.disableServiceAccount(p.id,u.actor?.id)})}if(m.pathname==="/api/automation/tokens"&&S.method==="POST"){let l=await v(S),u=te(W),p=pe.getServiceAccount(String(l.serviceAccountId??"")),I=Ha(l);if(!u.actor||!p||p.organizationId!==o.organization.id||!I||!Array.isArray(l.capabilities))return f({ok:!1,error:"Service account, explicit capabilities, and valid scope are required."},422);try{let w=pe.createToken({serviceAccountId:p.id,name:String(l.name??"API token"),capabilities:l.capabilities.map(String),scope:I,expiresAt:typeof l.expiresAt==="string"?l.expiresAt:void 0,createdByActorId:u.actor.id});return f({ok:!0,token:w.token,secret:w.secret,revealOnce:!0},201)}catch(w){return f({ok:!1,error:w instanceof Error?w.message:"API token could not be created."},422)}}if(m.pathname==="/api/automation/tokens/rotate"&&S.method==="POST"){let l=await v(S),u=te(W),p=pe.getToken(String(l.id??"")),I=p?pe.getServiceAccount(p.serviceAccountId):void 0;if(!u.actor||!p||I?.organizationId!==o.organization.id)return f({ok:!1,error:"API token was not found."},404);try{let w=pe.rotateToken(p.id,u.actor.id);return f({ok:!0,token:w.token,secret:w.secret,revealOnce:!0,overlap:!0},201)}catch(w){return f({ok:!1,error:w instanceof Error?w.message:"API token could not be rotated."},409)}}if(m.pathname==="/api/automation/tokens"&&S.method==="DELETE"){let l=await v(S),u=te(W),p=pe.getToken(String(l.id??"")),I=p?pe.getServiceAccount(p.serviceAccountId):void 0;if(!p||I?.organizationId!==o.organization.id)return f({ok:!1,error:"API token was not found."},404);return f({ok:!0,token:pe.revokeToken(p.id,u.actor?.id)})}if(m.pathname==="/api/onboarding"&&S.method==="GET"){let l=ie.listConnections(o.organization.id);return f({drafts:ft.list(o.project.id),artifacts:ti.list(o.project.id),registries:dr.list(o.organization.id),sourceConnections:l,repositories:l.flatMap((u)=>ie.listRepositories(u.id)),project:{id:o.project.id,slug:o.project.slug,name:o.project.name},environments:[...o.environments.values()].map((u)=>({id:u.id,slug:u.slug,name:u.name,kind:u.kind,region:u.region})),resources:o.store.listResources(o.project.id).filter((u)=>u.kind==="application").map((u)=>({id:u.id,slug:u.slug,name:u.name,environmentId:u.environmentId}))})}if(m.pathname==="/api/onboarding/detect"&&S.method==="POST"){let l=await v(S);try{if(l.source?.kind==="git"){let I=ie.getConnection(String(l.source.connectionId??"")),w=ie.getRepository(String(l.source.repositoryId??""));if(!I||I.organizationId!==o.organization.id||!w||w.connectionId!==I.id)throw Error("Authorized Git repository was not found");let D=typeof l.source.deployKeyId==="string"?ie.getDeployKey(l.source.deployKeyId):void 0;if(D&&D.connectionId!==I.id)throw Error("Deploy key does not belong to this connection");let A=Vg(ke(rd(),"ts-cloud-onboarding-git-"));try{let k=await jd({remote:w.cloneUrl,destination:ke(A,"checkout"),ref:String(l.source.ref??w.defaultBranch),sparsePaths:Array.isArray(l.source.sparsePaths)?l.source.sparsePaths.map(String):void 0,binding:{id:"detection",projectId:o.project.id,connectionId:I.id,repositoryId:w.id,repositoryFullName:w.fullName,defaultBranch:w.defaultBranch,monorepoRoot:String(l.source.monorepoRoot??"."),includePaths:[],excludePaths:[],submodules:l.source.submodules===!0,cloneDepth:1,deployKeyId:D?.id,autoDeploy:!1,pullRequestPreviews:!1,status:"active",version:1,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}},{credential:ie.getCredential(I.id),deployKey:D?{...D,privateKey:ie.getDeployPrivateKey(D.id)}:void 0,timeoutMs:120000});return f({ok:!0,commitSha:k.commitSha,candidates:fi(md(k.directory))})}finally{ei(A,{recursive:!0,force:!0})}}if(Array.isArray(l.files)){if(l.files.length>1e4)throw Error("Detection file-count limit exceeded");let I=l.files.map((w)=>({path:String(w.path??""),size:Number(w.size??0),content:typeof w.content==="string"?w.content.slice(0,262144):void 0}));return f({ok:!0,candidates:fi(I)})}let u=eC(t,String(l.root??".")),p=q$(t,u);if(p===".."||p.startsWith(`..${tC}`))throw Error("Detection root must stay inside the project");return f({ok:!0,candidates:fi(md(u))})}catch(u){return f({ok:!1,error:u instanceof Error?u.message:"Application detection failed."},422)}}if(m.pathname==="/api/onboarding/plan"&&S.method==="POST"){let l=await v(S);try{return f({ok:!0,plan:Yt(l.draft,Array.isArray(l.suppliedSecretNames)?l.suppliedSecretNames.map(String):[])})}catch(u){return f({ok:!1,error:u instanceof Error?u.message:"Application plan could not be generated."},422)}}if(m.pathname==="/api/onboarding/drafts"&&S.method==="POST"){let l=await v(S),u=te(W);try{return f({ok:!0,draft:ft.create({organizationId:o.organization.id,projectId:o.project.id,name:String(l.name??l.draft?.name??"Application draft"),draft:{...l.draft,projectId:o.project.id},step:l.step,suppliedSecretNames:Array.isArray(l.suppliedSecretNames)?l.suppliedSecretNames.map(String):[],actorId:u.actor?.id})},201)}catch(p){return f({ok:!1,error:p instanceof Error?p.message:"Application draft could not be saved."},422)}}if(m.pathname==="/api/onboarding/drafts"&&S.method==="PATCH"){let l=await v(S),u=te(W),p=ft.get(String(l.id??""));if(!p||p.projectId!==o.project.id)return f({ok:!1,error:"Application draft was not found."},404);try{return f({ok:!0,draft:ft.update(p.id,Number(l.version),{draft:{...l.draft,projectId:o.project.id},step:l.step,suppliedSecretNames:Array.isArray(l.suppliedSecretNames)?l.suppliedSecretNames.map(String):void 0,actorId:u.actor?.id})})}catch(I){return f({ok:!1,error:I instanceof Error?I.message:"Application draft could not be updated."},409)}}if(m.pathname==="/api/onboarding/artifacts"&&S.method==="POST"){let l=te(W);if(Number(S.headers.get("content-length")??0)>104857600)return f({ok:!1,error:"Artifact exceeds the 100 MB upload limit."},413);try{let p=new Uint8Array(await S.arrayBuffer());return f({ok:!0,artifact:ti.create({organizationId:o.organization.id,projectId:o.project.id,filename:S.headers.get("x-artifact-filename")??"application.zip",bytes:p,actorId:l.actor?.id})},201)}catch(p){return f({ok:!1,error:p instanceof Error?p.message:"Artifact could not be inspected."},422)}}if(m.pathname==="/api/onboarding/registries"&&S.method==="POST"){let l=await v(S),u=te(W);try{return f({ok:!0,registry:dr.create({organizationId:o.organization.id,provider:l.provider,name:String(l.name??"Container registry"),host:String(l.host??""),credential:l.token||l.password?{username:typeof l.username==="string"?l.username:void 0,password:typeof l.password==="string"?l.password:void 0,token:typeof l.token==="string"?l.token:void 0}:void 0,credentialExpiresAt:typeof l.credentialExpiresAt==="string"?l.credentialExpiresAt:void 0,actorId:u.actor?.id})},201)}catch(p){return f({ok:!1,error:p instanceof Error?p.message:"Registry connection could not be created."},422)}}if(m.pathname==="/api/onboarding/registries"&&S.method==="PATCH"){let l=await v(S),u=te(W),p=dr.get(String(l.id??""));if(!p||p.organizationId!==o.organization.id)return f({ok:!1,error:"Registry connection was not found."},404);try{if(l.action==="test")return f({ok:!0,registry:await dr.test(p.id,{image:typeof l.image==="string"?l.image:void 0})});if(l.action==="rotate")return f({ok:!0,registry:dr.rotate(p.id,{username:typeof l.username==="string"?l.username:void 0,password:typeof l.password==="string"?l.password:void 0,token:typeof l.token==="string"?l.token:void 0},{expiresAt:typeof l.expiresAt==="string"?l.expiresAt:void 0,actorId:u.actor?.id})});return f({ok:!1,error:"Registry action must be test or rotate."},422)}catch(I){return f({ok:!1,error:I instanceof Error?I.message:"Registry connection could not be updated."},422)}}if(m.pathname==="/api/onboarding/registries"&&S.method==="DELETE"){let l=await v(S),u=te(W),p=dr.get(String(l.id??""));if(!p||p.organizationId!==o.organization.id)return f({ok:!1,error:"Registry connection was not found."},404);let I=ft.list(o.project.id).filter((w)=>w.input.source.kind==="image"&&w.input.source.registryConnectionId===p.id||w.input.build.kind==="prebuilt_image"&&w.input.build.registryConnectionId===p.id);if(l.preview===!0)return f({ok:!0,preview:!0,affectedDrafts:I});return f({ok:!0,registry:dr.disconnect(p.id,u.actor?.id),affectedDrafts:I})}if(m.pathname==="/api/onboarding/apply"&&S.method==="POST"){let l=await v(S),u=te(W);try{let p=ss({controlPlane:o.store,drafts:ft,draftId:String(l.id??""),expectedVersion:Number(l.version),confirmEnvironment:String(l.confirmEnvironment??""),actorId:u.actor?.id});return f({ok:!0,resource:p.resource,operation:p.operation,plan:p.plan},202)}catch(p){return f({ok:!1,error:p instanceof Error?p.message:"Application plan could not be applied."},422)}}if(m.pathname==="/api/sources"&&S.method==="GET"){let l=ie.listConnections(o.organization.id);return f({connections:l,bindings:ie.listBindings({projectId:o.project.id}),repositories:l.flatMap((u)=>ie.listRepositories(u.id)),deployKeys:l.flatMap((u)=>ie.listDeployKeys(u.id)),webhooks:l.flatMap((u)=>ie.listWebhooks(u.id)).map((u)=>({...u,deliveries:ie.listDeliveries(u.id,20)})),project:{id:o.project.id,slug:o.project.slug},environment:sr(o,String(V)),resources:o.store.listResources(o.project.id,sr(o,String(V)).environmentId).filter((u)=>u.kind==="application").map((u)=>({id:u.id,slug:u.slug,name:u.name}))})}if(m.pathname==="/api/sources/connections"&&S.method==="POST"){let l=await v(S),u=te(W),p=String(l.provider??"");if(!["github","gitlab","bitbucket","gitea","generic_https","generic_ssh"].includes(p))return f({ok:!1,error:"A supported Git provider is required."},422);try{let I=p==="github"&&(l.privateKey||l.appId)?{appId:typeof l.appId==="string"?l.appId:void 0,installationId:typeof l.installationId==="string"?l.installationId:void 0,privateKey:typeof l.privateKey==="string"?l.privateKey:void 0}:p!=="generic_ssh"&&l.token?{token:typeof l.token==="string"?l.token:void 0,username:typeof l.username==="string"?l.username:void 0}:void 0,w={github:"https://github.com",gitlab:"https://gitlab.com",bitbucket:"https://bitbucket.org",gitea:"https://gitea.com"},D,A,k;if(o.store.database.transaction(()=>{if(D=ie.createConnection({organizationId:o.organization.id,provider:p,name:String(l.name??p),host:String(l.host??w[p]??""),owner:typeof l.owner==="string"?l.owner:void 0,authKind:l.authKind,credential:I,grantedScopes:Array.isArray(l.grantedScopes)?l.grantedScopes.map(String):[],credentialExpiresAt:typeof l.credentialExpiresAt==="string"?l.credentialExpiresAt:void 0,createdByActorId:u.actor?.id}),typeof l.repositoryUrl==="string"&&typeof l.repositoryFullName==="string")A=ie.upsertRepository({connectionId:D.id,providerRepositoryId:`manual:${l.repositoryFullName}`,fullName:l.repositoryFullName,cloneUrl:l.repositoryUrl,defaultBranch:String(l.defaultBranch??"main"),visibility:"unknown",archived:!1,metadata:{source:"manual"}});if(p==="generic_ssh")k=ie.createDeployKey({connectionId:D.id,name:String(l.deployKeyName??"Repository deploy key"),publicKey:String(l.publicKey??""),privateKey:String(l.deployPrivateKey??""),host:String(l.sshHost??""),hostKey:String(l.hostKey??""),actorId:u.actor?.id})})(),l.test===!0)D=await Ud(ie,D.id,A?.id);return f({ok:!0,connection:D,repository:A,deployKey:k},201)}catch(I){return f({ok:!1,error:I instanceof Error?I.message:"Source connection could not be created."},422)}}if(m.pathname==="/api/sources/connections"&&S.method==="PATCH"){let l=await v(S),u=te(W),p=ie.getConnection(String(l.id??""));if(!p||p.organizationId!==o.organization.id)return f({ok:!1,error:"Source connection was not found."},404);try{if(l.action==="test")return f({ok:!0,connection:await Ud(ie,p.id,typeof l.repositoryId==="string"?l.repositoryId:void 0)});if(l.action==="rotate")return f({ok:!0,connection:ie.rotateCredential(p.id,{token:typeof l.token==="string"?l.token:void 0,username:typeof l.username==="string"?l.username:void 0,appId:typeof l.appId==="string"?l.appId:void 0,installationId:typeof l.installationId==="string"?l.installationId:void 0,privateKey:typeof l.privateKey==="string"?l.privateKey:void 0},{expiresAt:typeof l.expiresAt==="string"?l.expiresAt:void 0,actorId:u.actor?.id})});return f({ok:!1,error:"Connection action must be test or rotate."},422)}catch(I){return f({ok:!1,error:I instanceof Error?I.message:"Source connection could not be updated."},422)}}if(m.pathname==="/api/sources/connections"&&S.method==="DELETE"){let l=await v(S),u=te(W),p=ie.getConnection(String(l.id??""));if(!p||p.organizationId!==o.organization.id)return f({ok:!1,error:"Source connection was not found."},404);let I=ie.listBindings({connectionId:p.id,status:"active"});if(l.preview===!0)return f({ok:!0,preview:!0,affectedBindings:I});return f({ok:!0,...ie.disconnectConnection(p.id,u.actor?.id)})}if(m.pathname==="/api/sources/deploy-keys"&&S.method==="POST"){let l=await v(S),u=te(W),p=ie.getConnection(String(l.connectionId??""));if(!p||p.organizationId!==o.organization.id)return f({ok:!1,error:"Source connection was not found."},404);try{return f({ok:!0,deployKey:ie.createDeployKey({connectionId:p.id,name:String(l.name??"Repository deploy key"),publicKey:String(l.publicKey??""),privateKey:String(l.privateKey??""),host:String(l.host??""),hostKey:String(l.hostKey??""),actorId:u.actor?.id})},201)}catch(I){return f({ok:!1,error:I instanceof Error?I.message:"Deploy key could not be stored."},422)}}if(m.pathname==="/api/sources/deploy-keys"&&S.method==="DELETE"){let l=await v(S),u=te(W),p=ie.getDeployKey(String(l.id??"")),I=p?ie.getConnection(p.connectionId):void 0;if(!p||!I||I.organizationId!==o.organization.id)return f({ok:!1,error:"Deploy key was not found."},404);let w=ie.listBindings({connectionId:I.id}).filter((D)=>D.deployKeyId===p.id);if(l.preview===!0)return f({ok:!0,preview:!0,affectedBindings:w});return f({ok:!0,...ie.revokeDeployKey(p.id,u.actor?.id)})}if(m.pathname==="/api/sources/repositories/sync"&&S.method==="POST"){let l=await v(S),u=ie.getConnection(String(l.connectionId??""));if(!u||u.organizationId!==o.organization.id)return f({ok:!1,error:"Source connection was not found."},404);try{return f({ok:!0,repositories:await ls(ie,String(l.connectionId??""),{search:typeof l.search==="string"?l.search:void 0})})}catch(p){return f({ok:!1,error:p instanceof Error?p.message:"Repositories could not be synchronized."},422)}}if(m.pathname==="/api/sources/references"&&S.method==="GET"){let l=ie.getConnection(String(m.searchParams.get("connectionId")??""));if(!l||l.organizationId!==o.organization.id)return f({ok:!1,error:"Source connection was not found."},404);try{return f(await gs(ie,{connectionId:String(m.searchParams.get("connectionId")??""),repository:String(m.searchParams.get("repository")??""),repositoryId:m.searchParams.get("repositoryId")??void 0,deployKeyId:m.searchParams.get("deployKeyId")??void 0,type:m.searchParams.get("type")==="tags"?"tags":"branches",cursor:m.searchParams.get("cursor")??void 0}))}catch(u){return f({ok:!1,error:u instanceof Error?u.message:"References could not be listed."},422)}}if(m.pathname==="/api/sources/bindings"&&S.method==="POST"){let l=await v(S),u=te(W),p=sr(o,String(V)),I=ie.getConnection(String(l.connectionId??""));if(!I||I.organizationId!==o.organization.id)return f({ok:!1,error:"Source connection was not found."},404);try{return f({ok:!0,binding:ie.createBinding({projectId:o.project.id,environmentId:p.environmentId,resourceId:typeof l.resourceId==="string"?l.resourceId:void 0,connectionId:String(l.connectionId??""),repositoryId:typeof l.repositoryId==="string"?l.repositoryId:void 0,repositoryFullName:String(l.repositoryFullName??""),defaultBranch:String(l.defaultBranch??"main"),branchRule:typeof l.branchRule==="string"?l.branchRule:void 0,tagRule:typeof l.tagRule==="string"?l.tagRule:void 0,monorepoRoot:String(l.monorepoRoot??"."),includePaths:Array.isArray(l.includePaths)?l.includePaths.map(String):[],excludePaths:Array.isArray(l.excludePaths)?l.excludePaths.map(String):[],submodules:l.submodules===!0,cloneDepth:l.cloneDepth?Number(l.cloneDepth):void 0,deployKeyId:typeof l.deployKeyId==="string"&&l.deployKeyId?l.deployKeyId:void 0,autoDeploy:l.autoDeploy!==!1,pullRequestPreviews:l.pullRequestPreviews!==!1,actorId:u.actor?.id})},201)}catch(w){return f({ok:!1,error:w instanceof Error?w.message:"Source binding could not be created."},422)}}if(m.pathname==="/api/sources/bindings"&&S.method==="PATCH"){let l=await v(S),u=te(W),p=ie.getBinding(String(l.id??""));if(!p||p.projectId!==o.project.id)return f({ok:!1,error:"Source binding was not found."},404);try{return f({ok:!0,binding:ie.updateBinding(p.id,Number(l.version),{defaultBranch:l.defaultBranch,branchRule:l.branchRule,tagRule:l.tagRule,monorepoRoot:l.monorepoRoot,includePaths:l.includePaths,excludePaths:l.excludePaths,submodules:l.submodules,cloneDepth:l.cloneDepth,deployKeyId:l.deployKeyId,autoDeploy:l.autoDeploy,pullRequestPreviews:l.pullRequestPreviews,status:l.status,disabledReason:l.disabledReason,actorId:u.actor?.id})})}catch(I){return f({ok:!1,error:I instanceof Error?I.message:"Source binding could not be updated."},409)}}if(m.pathname==="/api/sources/webhooks"&&S.method==="POST"){let l=await v(S),u=ie.getConnection(String(l.connectionId??""));if(!u||u.organizationId!==o.organization.id)return f({ok:!1,error:"Source connection was not found."},404);try{let p=ie.createWebhook({connectionId:String(l.connectionId??""),repositoryId:typeof l.repositoryId==="string"?l.repositoryId:void 0,repositoryFullName:String(l.repositoryFullName??""),events:Array.isArray(l.events)?l.events.map(String):void 0,secret:typeof l.secret==="string"?l.secret:void 0}),I=process.env.TS_CLOUD_WEBHOOK_BASE_URL?.trim()||fe,w=I?Ri(I,p.webhook):void 0,D=l.reconcile!==!1&&I?await la(ie,p.webhook.id,I):p.webhook;return f({ok:!0,webhook:D,endpoint:w,endpointRevealOnce:!0},201)}catch(p){return f({ok:!1,error:p instanceof Error?p.message:"Source webhook could not be created."},422)}}if(m.pathname==="/api/sources/webhooks"&&S.method==="PATCH"){let l=await v(S),u=process.env.TS_CLOUD_WEBHOOK_BASE_URL?.trim()||fe,p=ie.getWebhook(String(l.id??"")),I=p?ie.getConnection(p.connectionId):void 0;if(!p||!I||I.organizationId!==o.organization.id)return f({ok:!1,error:"Source webhook was not found."},404);if(!u)return f({ok:!1,error:"Set TS_CLOUD_WEBHOOK_BASE_URL to reconcile provider webhooks."},422);try{return f({ok:!0,webhook:await la(ie,String(l.id??""),u)})}catch(w){return f({ok:!1,error:w instanceof Error?w.message:"Source webhook could not be reconciled."},422)}}if(m.pathname==="/api/sources/webhooks"&&S.method==="DELETE"){let l=await v(S),u=ie.getWebhook(String(l.id??"")),p=u?ie.getConnection(u.connectionId):void 0;if(!u||!p||p.organizationId!==o.organization.id)return f({ok:!1,error:"Source webhook was not found."},404);try{return f({ok:!0,webhook:await Vh(ie,String(l.id??""))})}catch(I){return f({ok:!1,error:I instanceof Error?I.message:"Source webhook could not be removed."},422)}}if(m.pathname==="/api/security/posture"&&S.method==="GET"){let l=sr(o,String(V)),u=he.listFindings({...l,limit:500});return f({scope:l,summary:he.summary(l.organizationId,l.projectId,l.environmentId),findings:u,scans:he.listScanRuns({...l,limit:100}),policies:he.listPolicies(l.organizationId).filter((p)=>!p.environmentId||p.environmentId===l.environmentId),waivers:u.flatMap((p)=>he.listWaivers(p.id)),decisions:he.listDecisions(l.environmentId,50),actors:o.store.listMemberships(o.organization.id).map((p)=>o.store.getActor(p.actorId)).filter(Boolean)})}if(m.pathname==="/api/security/export"&&S.method==="GET")return f(he.exportPosture(o.organization.id));if(m.pathname==="/api/security/scan"&&S.method==="POST"){let l=sr(o,String(V)),u=await new Gn(he).run(new ba,{...l,artifactRoot:t}),p=Bo(he,l,je??{});return f({ok:!0,source:u,host:p,summary:he.summary(l.organizationId,l.projectId,l.environmentId)})}if(m.pathname==="/api/security/review"&&S.method==="POST")try{let l=sr(o,String(V));return f({ok:!0,...Jo(he,{scope:l,desiredConfigHash:o.project.desiredConfigHash})})}catch(l){return f({ok:!1,error:l instanceof Error?l.message:"Security change review failed."},409)}if(m.pathname==="/api/security/policies"&&S.method==="POST"){let l=await v(S),u=te(W);if(!u.actor)return f({ok:!1,error:"An organization actor is required."},403);try{let p=he.createPolicy({organizationId:o.organization.id,environmentId:l.environmentId===null?void 0:String(l.environmentId??sr(o,String(V)).environmentId),name:String(l.name??""),scannerFailMode:l.scannerFailMode==="open"?"open":"closed",requiredScanners:Array.isArray(l.requiredScanners)?l.requiredScanners.map(String):[],rules:Array.isArray(l.rules)?l.rules.map((I)=>({minimumSeverity:String(I.minimumSeverity),action:String(I.action),scannerId:I.scannerId?String(I.scannerId):void 0})):[],actorId:u.actor.id});return f({ok:!0,policy:p},201)}catch(p){return f({ok:!1,error:p instanceof Error?p.message:"Security policy could not be created."},422)}}if(m.pathname==="/api/security/policies"&&S.method==="PATCH"){let l=await v(S),u=te(W),p=he.getPolicy(String(l.id??""));if(!u.actor||!p||p.organizationId!==o.organization.id)return f({ok:!1,error:"Security policy was not found."},404);try{return f({ok:!0,policy:he.updatePolicy(p.id,Number(l.version),{name:typeof l.name==="string"?l.name:void 0,scannerFailMode:l.scannerFailMode==="open"||l.scannerFailMode==="closed"?l.scannerFailMode:void 0,requiredScanners:Array.isArray(l.requiredScanners)?l.requiredScanners.map(String):void 0,rules:Array.isArray(l.rules)?l.rules.map((I)=>({minimumSeverity:String(I.minimumSeverity),action:String(I.action),scannerId:I.scannerId?String(I.scannerId):void 0})):void 0,enabled:typeof l.enabled==="boolean"?l.enabled:void 0,actorId:u.actor.id})})}catch(I){return f({ok:!1,error:I instanceof Error?I.message:"Security policy could not be updated."},409)}}if(m.pathname==="/api/security/waivers"&&S.method==="POST"){let l=await v(S),u=te(W);if(!u.actor)return f({ok:!1,error:"An organization actor is required."},403);try{return f({ok:!0,waiver:he.createWaiver({findingId:String(l.findingId??""),policyId:typeof l.policyId==="string"?l.policyId:void 0,reason:String(l.reason??""),referenceUrl:typeof l.referenceUrl==="string"?l.referenceUrl:void 0,expiresAt:String(l.expiresAt??""),actorId:u.actor.id})},201)}catch(p){return f({ok:!1,error:p instanceof Error?p.message:"Security waiver could not be created."},422)}}if(m.pathname==="/api/security/waivers"&&S.method==="DELETE"){let l=await v(S),u=te(W);if(!u.actor)return f({ok:!1,error:"An organization actor is required."},403);try{return f({ok:!0,waiver:he.revokeWaiver(String(l.id??""),u.actor.id)})}catch(p){return f({ok:!1,error:p instanceof Error?p.message:"Security waiver could not be revoked."},404)}}if(m.pathname==="/api/security/findings"&&S.method==="PATCH"){let l=await v(S),u=te(W),p=he.getFinding(String(l.id??""));if(!u.actor||!p||p.organizationId!==o.organization.id)return f({ok:!1,error:"Security finding was not found."},404);try{let I=l.action==="acknowledge"?he.acknowledgeFinding(p.id,u.actor.id):he.assignFinding(p.id,typeof l.ownerActorId==="string"&&l.ownerActorId?l.ownerActorId:void 0,u.actor.id);return f({ok:!0,finding:I})}catch(I){return f({ok:!1,error:I instanceof Error?I.message:"Security finding could not be updated."},422)}}if(m.pathname==="/api/security/comments"&&S.method==="POST"){let l=await v(S),u=te(W);if(!u.actor)return f({ok:!1,error:"An organization actor is required."},403);try{return f({ok:!0,comment:he.addComment({findingId:String(l.findingId??""),actorId:u.actor.id,body:String(l.body??""),referenceUrl:typeof l.referenceUrl==="string"?l.referenceUrl:void 0})},201)}catch(p){return f({ok:!1,error:p instanceof Error?p.message:"Comment could not be saved."},422)}}if(m.pathname==="/api/auth/sessions"&&S.method==="GET"){let l=He.resolveSession(S);return f({currentSessionId:l?.id,sessions:l?G.listSessions(l.identityId,{includeInactive:!0}):[]})}if(m.pathname==="/api/auth/sessions"&&S.method==="DELETE"){let l=await v(S),u=He.resolveSession(S);if(!u)return f({ok:!1,error:"Sign in again to manage sessions."},401);let p=String(l.id??""),I=G.revokeSession(u.identityId,p),w=p===u.id&&I?{"set-cookie":Vo({secure:Qr})}:void 0;return f({ok:I,signedOut:p===u.id&&I},I?200:404,w)}if(m.pathname==="/api/auth/sessions/revoke-others"&&S.method==="POST"){let l=He.resolveSession(S);if(!l)return f({ok:!1,error:"Sign in again to manage sessions."},401);return f({ok:!0,revoked:G.revokeOtherSessions(l.identityId,l.id)})}if(m.pathname==="/api/auth/password/change"&&S.method==="POST"){let l=await v(S),u=String(l.currentPassword??""),p=String(l.password??""),I=te(W),w=I.actor?G.getIdentityByActor(I.actor.id):void 0;if(!w||!or(u,w.passwordHash))return f({ok:!1,error:"Current password is incorrect."},401);if(p.length<12)return f({ok:!1,error:"New password must be at least 12 characters."},422);if(or(p,w.passwordHash))return f({ok:!1,error:"Choose a different password."},409);let D=fn(p),A=G.updatePassword(w.id,D);Mo(t,A.username,D);let k=Qa(A.id,S,le.requestIP(S)?.address??"unknown");return o.store.appendEvent({organizationId:o.organization.id,actorId:A.actorId,type:"auth.password.changed"}),f({ok:!0,message:"Password changed and other sessions were signed out."},200,{"set-cookie":Li(k.token,{secure:Qr,maxAgeMs:rn})})}if(m.pathname==="/api/auth/mfa/enroll"&&S.method==="POST"){let l=await v(S),u=He.resolveSession(S),p=te(W),I=p.actor?G.getIdentityByActor(p.actor.id):void 0;if(!u||!I)return f({ok:!1,error:"Sign in again before enabling MFA."},401);if(!or(String(l.password??""),I.passwordHash))return f({ok:!1,error:"Current password is incorrect."},401);try{let w=G.beginTotpEnrollment(I.id,{issuer:o.organization.name});return o.store.appendEvent({organizationId:o.organization.id,actorId:I.actorId,type:"auth.mfa.enrollment.started"}),f({factor:w.factor,secret:w.secret,uri:w.uri})}catch(w){return f({ok:!1,error:w instanceof Error?w.message:"MFA enrollment failed."},409)}}if(m.pathname==="/api/auth/mfa/verify"&&S.method==="POST"){let l=await v(S),u=He.resolveSession(S),p=te(W),I=p.actor?G.getIdentityByActor(p.actor.id):void 0;if(!u||!I)return f({ok:!1,error:"Sign in again before enabling MFA."},401);try{let w=G.verifyTotpEnrollment(I.id,String(l.code??""));return G.markSessionStepUp(u.id,!0),o.store.appendEvent({organizationId:o.organization.id,actorId:I.actorId,type:"auth.mfa.enabled",payload:{recoveryCodeCount:w.recoveryCodes.length}}),f(w)}catch(w){return f({ok:!1,error:w instanceof Error?w.message:"MFA enrollment failed."},422)}}if(m.pathname==="/api/auth/mfa"&&S.method==="DELETE"){let l=await v(S),u=He.resolveSession(S),p=te(W),I=p.actor?G.getIdentityByActor(p.actor.id):void 0;if(!u||!I||!or(String(l.password??""),I.passwordHash))return f({ok:!1,error:"Current password is incorrect."},401);let w=G.verifyMfaCode(I.id,String(l.code??""));if(!w.valid||!w.method)return f({ok:!1,error:"Authenticator or recovery code is incorrect."},401);return G.disableMfa(I.id),G.revokeOtherSessions(I.id,u.id),G.markSessionStepUp(u.id),o.store.appendEvent({organizationId:o.organization.id,actorId:I.actorId,type:"auth.mfa.disabled",payload:{method:w.method}}),f({ok:!0})}if(m.pathname==="/api/auth/step-up"&&S.method==="POST"){let l=await v(S),u=He.resolveSession(S),p=te(W),I=p.actor?G.getIdentityByActor(p.actor.id):void 0;if(!u||!I||!or(String(l.password??""),I.passwordHash))return f({ok:!1,error:"Current password is incorrect."},401);let w=G.getMfaFactor(I.id);if(w?.state==="active"){if(!G.verifyMfaCode(I.id,String(l.code??"")).valid)return f({ok:!1,error:"Authenticator or recovery code is incorrect."},401)}let D=G.markSessionStepUp(u.id,w?.state==="active");return o.store.appendEvent({organizationId:o.organization.id,actorId:I.actorId,type:"auth.step_up.succeeded",payload:{mfa:w?.state==="active"}}),f({ok:!0,recentAuthAt:D.recentAuthAt})}if(m.pathname==="/api/terminal"){if(!T)return f({ok:!1,error:"The web terminal is disabled."},403);if(le.upgrade(S))return;return nd("WebSocket upgrade failed",400)}if(m.pathname==="/api/health"){let l=o.store.health();return f({ok:!0,cwd:t,environment:V,environments:g,uiRoot:await ze(W,V),liveData:O.size>0,terminal:T,localPackage:import.meta.url.includes("/Code/Libraries/ts-cloud/"),controlPlane:{schemaVersion:l.schemaVersion,supportedSchemaVersion:l.supportedSchemaVersion,integrity:l.integrity,pendingRetryableOperations:l.pendingRetryableOperations}})}if(m.pathname==="/api/control-plane/operations"){let l=m.searchParams.get("state"),u=l&&["queued","running","succeeded","failed","cancelled","timed_out"].includes(l)?l:void 0;return f({operations:o.store.listOperations({projectId:o.project.id,state:u,kind:m.searchParams.get("kind")??void 0,limit:Number(m.searchParams.get("limit"))||100})})}if(m.pathname==="/api/queue"&&S.method==="GET"){let l=m.searchParams.get("state"),u=l&&["queued","running","succeeded","failed","cancelled","timed_out"].includes(l)?l:void 0,p=be.list({projectId:o.project.id,state:u,limit:Number(m.searchParams.get("limit"))||250}).filter((I)=>ri(W,I.operation.id,"deployments:read")).map((I)=>{let w=I.operation.resourceId?o.store.getResource(I.operation.resourceId):void 0,D=I.operation.environmentId?o.store.listEnvironments(o.project.id).find((H)=>H.id===I.operation.environmentId):void 0,A=I.operation.actorId?o.store.getActor(I.operation.actorId):void 0,k=I.operation.input;return{...I,target:w?{id:w.id,name:w.name,slug:w.slug,kind:w.kind}:D?{id:D.id,name:D.name,slug:D.slug,kind:"environment"}:{id:o.project.id,name:o.project.name,slug:o.project.slug,kind:"project"},actor:A?{id:A.id,name:A.displayName,kind:A.kind}:void 0,commit:k.revision??k.source?.commitSha??null}});return f({operations:p,concurrency:be.limits})}if(m.pathname==="/api/queue/logs"&&S.method==="GET"){let l=String(m.searchParams.get("id")??"");if(!ri(W,l,"deployments:read"))return f({ok:!1,error:"Operation was not found in this scope."},404);let u=be.logs(l,{after:Number(m.searchParams.get("after"))||0,limit:Number(m.searchParams.get("limit"))||500});return f({entries:u,cursor:u.at(-1)?.sequence??(Number(m.searchParams.get("after"))||0),operation:o.store.getOperation(l)})}if(m.pathname==="/api/queue/stream"&&S.method==="GET"){let l=String(m.searchParams.get("id")??"");if(!ri(W,l,"deployments:read"))return f({ok:!1,error:"Operation was not found in this scope."},404);let u=S.headers.get("last-event-id")?.trim(),p=Number(u||m.searchParams.get("after")||0),I=new TextEncoder,w,D=!1,A=new ReadableStream({start(k){let H=()=>{if(D)return;let j=He.resolveUser(S);if(!j||!ri(j,l,"deployments:read")){if(D=!0,w)clearInterval(w);k.close();return}let oe=be.logs(l,{after:p,limit:500});for(let re of oe)p=re.sequence,k.enqueue(I.encode(`id: ${re.sequence}
681
+ event: log
682
+ data: ${JSON.stringify(re)}
683
+
684
+ `));let L=o.store.getOperation(l);if(L&&["succeeded","failed","cancelled","timed_out"].includes(L.state)&&be.logs(l,{after:p,limit:1}).length===0){if(D=!0,w)clearInterval(w);k.enqueue(I.encode(`event: complete
685
+ data: ${JSON.stringify({state:L.state,cursor:p})}
686
+
687
+ `)),k.close()}};if(H(),!D)w=setInterval(H,500);S.signal.addEventListener("abort",()=>{if(D=!0,w)clearInterval(w);try{k.close()}catch{}},{once:!0})},cancel(){if(D=!0,w)clearInterval(w)}});return new Response(A,{headers:{"content-type":"text/event-stream","cache-control":"no-store","x-accel-buffering":"no"}})}if(m.pathname==="/api/queue/cancel"&&S.method==="POST"){let l=await v(S),u=String(l.id??"");if(!ri(W,u,"deployments:cancel"))return f({ok:!1,error:"Operation was not found or cannot be cancelled in this scope."},404);let p=Ke(o.store,W);try{return f({ok:!0,operation:be.requestCancellation(u,p.id)})}catch(I){return f({ok:!1,error:I instanceof Error?I.message:"Cancellation failed."},409)}}if(m.pathname==="/api/queue/retry"&&S.method==="POST"){let l=await v(S),u=String(l.id??"");if(!ri(W,u,"deployments:create"))return f({ok:!1,error:"Operation was not found or cannot be retried in this scope."},404);let p=Ke(o.store,W);try{return f({ok:!0,operation:be.retry(u,String(l.errorClass??"manual"),{delayMs:Number(l.delayMs)||0,actorId:p.id})})}catch(I){return f({ok:!1,error:I instanceof Error?I.message:"Retry failed."},409)}}if(m.pathname==="/api/queue/settings"&&S.method==="GET")return f({concurrency:be.limits});if(m.pathname==="/api/queue/settings"&&S.method==="PATCH"){let l=await v(S);if(l.confirm!=="update queue limits")return f({ok:!1,error:'Type "update queue limits" to confirm production concurrency changes.'},409);let u=Ke(o.store,W);return f({ok:!0,concurrency:be.configureConcurrency(l.concurrency??{},{organizationId:o.organization.id,actorId:u.id})})}if(m.pathname==="/api/queue/history"&&S.method==="DELETE"){let l=await v(S);if(l.confirm!=="clear completed")return f({ok:!1,error:'Type "clear completed" to confirm retained history cleanup.'},409);let u=Ke(o.store,W);return f({ok:!0,deleted:be.clearCompleted({projectId:o.project.id,before:typeof l.before==="string"?l.before:void 0,actorId:u.id})})}if(m.pathname==="/api/previews"&&S.method==="GET"){let l=xe.previews.listInstances({projectId:o.project.id}).filter((I)=>at(W,I.resourceId,"deployments:read")),u=xe.previews.listDefinitions(o.project.id).filter((I)=>at(W,I.resourceId,"project:read")),p=o.store.listResources(o.project.id).filter((I)=>I.kind==="application"&&at(W,I.id,"project:read")).map((I)=>({id:I.id,slug:I.slug,name:I.name,environmentId:I.environmentId}));return f({previews:l,definitions:u,resources:p,environments:[...o.environments.values()]})}if(m.pathname==="/api/releases"&&S.method==="GET"){let l=[...o.environments.values()],u=o.store.listResources(o.project.id).filter((w)=>at(W,w.id,"deployments:read")),p=new Set(u.map((w)=>w.id)),I=Ht.releases.list({projectId:o.project.id}).filter((w)=>p.has(w.resourceId)).map((w)=>{let D=u.find((H)=>H.id===w.resourceId),A=l.find((H)=>H.id===w.environmentId),k=w.previousReleaseId?Ht.releases.get(w.previousReleaseId):void 0;return{...w,resource:D?{id:D.id,name:D.name,slug:D.slug,provider:D.provider}:void 0,environment:A?{id:A.id,name:A.name,slug:A.slug,kind:A.kind}:void 0,artifact:Ht.releases.getArtifact(w.artifactId),transitions:Ht.releases.transitions(w.id),approvals:Ht.releases.approvals(w.id),previous:k,comparison:k?Ht.releases.compare(k.id,w.id):void 0,capabilities:sa({kind:w.kind,provider:D?.provider,hasHealthGate:!!w.healthGate,replicas:Number(w.manifest?.replicas)||1})}});return f({releases:I,resources:u.map((w)=>({id:w.id,name:w.name,slug:w.slug,environmentId:w.environmentId,provider:w.provider})),environments:l})}if(m.pathname==="/api/releases/action"&&S.method==="POST"){let l=await v(S),u=Ht.releases.get(String(l.id??"")),p=String(l.action??"");if(!u||!at(W,u.resourceId,"deployments:create"))return f({ok:!1,error:"Release was not found in this scope."},404);let I=Ke(o.store,W);try{if(p==="activate")return f({ok:!0,operation:Ht.enqueueActivation(u,{actorId:I.id})});if(p==="rollback"){let w=o.store.getResource(u.resourceId);if(l.confirm!==w?.slug)return f({ok:!1,error:`Type "${w?.slug??""}" to confirm rollback.`},409);return f({ok:!0,operation:Ht.enqueueRollback(u,{actorId:I.id,targetReleaseId:typeof l.targetReleaseId==="string"?l.targetReleaseId:void 0})})}if(p==="approve"){let w=o.store.listEnvironments(u.projectId).find((D)=>D.id===u.environmentId);if(l.confirm!==w?.slug)return f({ok:!1,error:`Type "${w?.slug??""}" to confirm the environment gate.`},409);return f({ok:!0,release:Ht.releases.approve(u.id,{actorId:I.id,decision:l.decision==="rejected"?"rejected":"approved",comment:typeof l.comment==="string"?l.comment:void 0})})}if(p==="pin")return f({ok:!0,release:Ht.releases.pin(u.id,l.pinned!==!1,typeof l.reason==="string"?l.reason:void 0)});if(p==="promote"){let w=o.store.getResource(String(l.targetResourceId??"")),D=w?o.store.listEnvironments(u.projectId).find((A)=>A.id===w.environmentId):void 0;if(!w||!D||!at(W,w.id,"deployments:create"))return f({ok:!1,error:"Promotion target was not found in this scope."},404);if(l.confirm!==D.slug)return f({ok:!1,error:`Type "${D.slug}" to confirm promotion.`},409);return f({ok:!0,release:Ht.releases.promote(u.id,{targetEnvironmentId:D.id,targetResourceId:w.id,config:l.config&&typeof l.config==="object"?l.config:{},strategy:typeof l.strategy==="string"?l.strategy:void 0,actorId:I.id,approvalRequired:l.approvalRequired===!0})})}return f({ok:!1,error:"Unsupported release action."},422)}catch(w){return f({ok:!1,error:w instanceof Error?w.message:"Release action failed."},409)}}if(m.pathname==="/api/compose"&&S.method==="GET"){let l=Mr.applications.list({projectId:o.project.id}).filter((u)=>at(W,u.resourceId,"applications:read")).map((u)=>({...u,services:Mr.applications.services(u.id)}));return f({applications:l,templates:hs(),environments:[...o.environments.values()]})}if(m.pathname==="/api/compose/preview"&&S.method==="POST"){let l=await v(S),u=String(l.environmentId??"");if(!Xi(W,u,"applications:manage"))return f({ok:!1,error:"Environment was not found in this scope."},404);try{return f({ok:!0,result:Mr.applications.preview(String(l.source??""),{name:String(l.name??""),slug:typeof l.slug==="string"?l.slug:void 0,projectId:o.project.id,environmentId:u})})}catch(p){return f({ok:!1,error:p instanceof Error?p.message:"Compose could not be parsed."},422)}}if((m.pathname==="/api/compose/import"||m.pathname==="/api/compose/template")&&S.method==="POST"){let l=await v(S),u=String(l.environmentId??"");if(!Xi(W,u,"applications:manage"))return f({ok:!1,error:"Environment was not found in this scope."},404);let p=Ke(o.store,W);try{let I=m.pathname.endsWith("/template")?Mr.applications.fromTemplate(String(l.templateId??""),l.inputs&&typeof l.inputs==="object"?l.inputs:{},{name:String(l.name??""),projectId:o.project.id,environmentId:u,version:typeof l.templateVersion==="string"?l.templateVersion:void 0,createdByActorId:p.id}):Mr.applications.import(String(l.source??""),{name:String(l.name??""),slug:typeof l.slug==="string"?l.slug:void 0,projectId:o.project.id,environmentId:u,createdByActorId:p.id});return f({ok:!0,application:I.application,diagnostics:I.parsed.diagnostics})}catch(I){return f({ok:!1,error:I instanceof Error?I.message:"Compose application could not be saved."},422)}}if(m.pathname==="/api/compose/action"&&S.method==="POST"){let l=await v(S),u=Mr.applications.get(String(l.id??"")),p=String(l.action??""),I=p==="delete"||p==="stop"?"deployments:cancel":"deployments:create";if(!u||!at(W,u.resourceId,I))return f({ok:!1,error:"Compose application was not found in this scope."},404);try{let w=Ke(o.store,W);return f({ok:!0,operation:Mr.enqueue(u,p,{actorId:w.id,service:typeof l.service==="string"?l.service:void 0,replicas:Number.isFinite(Number(l.replicas))?Number(l.replicas):void 0,removeVolumes:l.removeVolumes===!0,confirmation:typeof l.confirm==="string"?l.confirm:void 0})})}catch(w){return f({ok:!1,error:w instanceof Error?w.message:"Compose operation could not be queued."},409)}}if((m.pathname==="/api/compose/logs"||m.pathname==="/api/compose/shell")&&S.method==="POST"){let l=await v(S),u=Mr.applications.get(String(l.id??"")),p=m.pathname.endsWith("/shell"),I=p?"runtime:terminal":"runtime:logs";if(!u||!at(W,u.resourceId,I))return f({ok:!1,error:"Compose service was not found in this scope."},404);let w=String(l.service??"");if(!u.manifest.spec.services[w])return f({ok:!1,error:"Compose service was not found."},404);if(p&&l.confirm!==w)return f({ok:!1,error:`Type "${w}" to run a service command.`},409);let D=o.store.listEnvironments(u.projectId).find((k)=>k.id===u.environmentId)?.slug;if(!D)return f({ok:!1,error:"Compose environment was not found."},404);let A=p?CI(u.manifest,w,Array.isArray(l.command)?l.command.map(String):["sh"]):$I(u.manifest,w,Number(l.lines)||200);return f(await Ta(a,D,A))}if(m.pathname==="/api/previews/definitions"&&S.method==="POST"){let l=await v(S),u=String(l.resourceId??"");if(!at(W,u,"config:write"))return f({ok:!1,error:"Application was not found in this scope."},404);let p=Ke(o.store,W);try{return f({ok:!0,definition:xe.previews.createDefinition({...l,projectId:o.project.id,resourceId:u,baseEnvironmentId:String(l.baseEnvironmentId??""),domainPattern:String(l.domainPattern??""),createdByActorId:p.id})})}catch(I){return f({ok:!1,error:I instanceof Error?I.message:"Preview policy could not be created."},409)}}if(m.pathname==="/api/previews/deploy"&&S.method==="POST"){let l=await v(S),u=xe.previews.getDefinition(String(l.definitionId??""));if(!u||!at(W,u.resourceId,"deployments:create"))return f({ok:!1,error:"Preview policy was not found in this scope."},404);let p=Ke(o.store,W);try{let I=xe.previews.upsert({definitionId:u.id,sourceProvider:"dashboard",repository:"dashboard",branch:String(l.branch??""),pullRequestNumber:Number(l.pullRequestNumber)||void 0,commitSha:String(l.commitSha??""),createdByActorId:p.id});return f({ok:!0,preview:I.preview,operation:xe.enqueueDeploy(I.preview,{created:I.created,actorId:p.id})})}catch(I){return f({ok:!1,error:I instanceof Error?I.message:"Preview could not be queued."},409)}}if(m.pathname==="/api/previews/destroy"&&S.method==="POST"){let l=await v(S),u=xe.previews.getInstance(String(l.id??""));if(!u||!at(W,u.resourceId,"deployments:cancel"))return f({ok:!1,error:"Preview was not found in this scope."},404);if(l.confirm!==u.name)return f({ok:!1,error:`Type "${u.name}" to confirm tagged teardown.`},409);let p=Ke(o.store,W);return f({ok:!0,operation:xe.enqueueDestroy(u,"dashboard",p.id)})}if(m.pathname==="/api/previews/extend"&&S.method==="POST"){let l=await v(S),u=xe.previews.getInstance(String(l.id??""));if(!u||!at(W,u.resourceId,"deployments:create"))return f({ok:!1,error:"Preview was not found in this scope."},404);return f({ok:!0,preview:xe.previews.extend(u.id,Number(l.hours))})}if(m.pathname==="/api/previews/rebuild"&&S.method==="POST"){let l=await v(S),u=xe.previews.getInstance(String(l.id??""));if(!u||!at(W,u.resourceId,"deployments:create"))return f({ok:!1,error:"Preview was not found in this scope."},404);let p=Ke(o.store,W);return f({ok:!0,operation:xe.enqueueDeploy(u,{actorId:p.id,reason:"manual_rebuild"})})}if(m.pathname==="/api/previews/cleanup"&&S.method==="POST"){let l=await v(S);if(!l.dryRun&&l.confirm!=="cleanup previews")return f({ok:!1,error:'Type "cleanup previews" to confirm teardown.'},409);let u=Ke(o.store,W);return f({ok:!0,...xe.cleanup({dryRun:l.dryRun===!0,maxAgeHours:Number(l.maxAgeHours)||void 0,keepCount:Number(l.keepCount)||void 0,actorId:u.id})})}if(m.pathname==="/api/control-plane/events")return f({events:o.store.listEvents({organizationId:o.organization.id,projectId:o.project.id,operationId:m.searchParams.get("operationId")??void 0,correlationId:m.searchParams.get("correlationId")??void 0,afterSequence:Number(m.searchParams.get("afterSequence"))||void 0,limit:Number(m.searchParams.get("limit"))||200})});if(m.pathname==="/api/search"){let l=String(m.searchParams.get("q")??"").trim().slice(0,128),u=Ft.role==="member"?new Set(Object.keys(Ft.sites)):void 0,p=l?DI(o.store,{projectId:o.project.id,query:l,allowedResourceSlugs:u,limit:Number(m.searchParams.get("limit"))||20}):[];return f({query:l,results:p,stale:!1})}if(m.pathname==="/api/search/preferences"&&S.method==="GET"){let l=`dashboard:${W.username.toLowerCase()}`;return f({savedFilters:o.store.listSavedFilters(l),navigation:o.store.listNavigation(l)})}if(m.pathname==="/api/search/preferences"&&S.method==="POST"){let l=`dashboard:${W.username.toLowerCase()}`,u=await v(S),p=String(u.action??"");if(p==="save-filter")return f({savedFilter:o.store.saveFilter(l,String(u.name??""),String(u.routeId??""),u.query??{})});if(p==="favorite")return f({navigation:o.store.setFavorite(l,String(u.entityType??""),String(u.entityId??""),u.favorite!==!1)});if(p==="visit")return f({navigation:o.store.recordNavigation(l,String(u.entityType??""),String(u.entityId??""))});return f({ok:!1,error:"Unknown search preference action."},422)}if(m.pathname==="/api/search/preferences"&&S.method==="DELETE"){let l=`dashboard:${W.username.toLowerCase()}`,u=await v(S);return f({ok:o.store.deleteSavedFilter(l,String(u.id??""))})}if(m.pathname==="/api/organization"&&S.method==="GET"){let l=o.store.listMemberships(o.organization.id,{includeRevoked:!0}).map((u)=>{let p=o.store.getActor(u.actorId);return{...u,actor:p?{id:p.id,displayName:p.displayName,externalId:p.externalId,disabledAt:p.disabledAt}:void 0,grants:o.store.listGrants(u.id)}});return f({organization:o.organization,project:o.project,environments:o.store.listEnvironments(o.project.id),resources:o.store.listResources(o.project.id).map((u)=>({id:u.id,environmentId:u.environmentId,kind:u.kind,slug:u.slug,name:u.name})),memberships:l,invitations:o.store.listInvitations(o.organization.id)})}if(m.pathname==="/api/organization/invitations"&&S.method==="GET")return f({invitations:o.store.listInvitations(o.organization.id)});if(m.pathname==="/api/organization/invitations"&&S.method==="POST"){let l=await v(S),u=ed(l.roleTemplate),p=Ha(l);if(!u||!p)return f({ok:!1,error:"Choose a valid role template and resource scope."},422);let I=te(W);if(!I.actor||!I.membership)return f({ok:!1,error:"Your organization membership is unavailable."},403);if(u==="owner"&&(!or(String(l.password??""),W.passwordHash)||I.membership.roleTemplate!=="owner"))return f({ok:!1,error:"Owner invitations require an owner to re-enter their password."},401);try{let w=o.store.createInvitation({organizationId:o.organization.id,email:String(l.email??""),roleTemplate:u,scope:p,invitedByActorId:I.actor.id,expiresInMs:Number(l.expiresInMs)||void 0}),D=`${m.origin}/accept-invitation?token=${encodeURIComponent(w.token)}`,A=await ha(a,{to:w.invitation.email,subject:"Your ts-cloud organization invitation",text:`Accept your ts-cloud invitation: ${D}
688
+
689
+ This link expires ${w.invitation.expiresAt} and can be used once.`});return f({invitation:w.invitation,token:w.token,acceptUrl:D,delivered:A},201)}catch(w){return f({ok:!1,error:w instanceof Error?w.message:"Invitation could not be created."},422)}}if(m.pathname==="/api/organization/invitations"&&S.method==="DELETE"){let l=await v(S),u=te(W);try{return f({invitation:o.store.revokeInvitation(String(l.id??""),u.actor?.id)})}catch(p){return f({ok:!1,error:p instanceof Error?p.message:"Invitation could not be revoked."},409)}}if(m.pathname==="/api/organization/invitations/resend"&&S.method==="POST"){let l=await v(S),u=te(W);try{let p=o.store.reissueInvitation(String(l.id??""),u.actor?.id),I=`${m.origin}/accept-invitation?token=${encodeURIComponent(p.token)}`,w=await ha(a,{to:p.invitation.email,subject:"Your ts-cloud organization invitation",text:`Accept your ts-cloud invitation: ${I}
690
+
691
+ This replacement link expires ${p.invitation.expiresAt} and can be used once.`});return f({invitation:p.invitation,token:p.token,acceptUrl:I,delivered:w})}catch(p){return f({ok:!1,error:p instanceof Error?p.message:"Invitation could not be resent."},409)}}if(m.pathname==="/api/organization/memberships"&&S.method==="PATCH"){let l=await v(S),u=o.store.getMembership(String(l.id??"")),p=ed(l.roleTemplate),I=Ha(l);if(!u||u.organizationId!==o.organization.id)return f({ok:!1,error:"Membership was not found."},404);if(!p||!I)return f({ok:!1,error:"Choose a valid role template and resource scope."},422);let w=te(W);if((u.roleTemplate==="owner"||p==="owner")&&(!or(String(l.password??""),W.passwordHash)||w.membership?.roleTemplate!=="owner"))return f({ok:!1,error:"Ownership changes require an owner to re-enter their password."},401);let A=o.store.resolveAuthorizationTarget(o.organization.id,I)??o.store.resolveAuthorizationTarget(o.organization.id,{type:"project",id:o.project.id}),k=o.store.listGrants(u.id),H=Na({membership:u,grants:k,target:A}),j={...u,roleTemplate:p,scope:I},oe=Na({membership:j,grants:k,target:A}),L={gained:oe.filter((re)=>!H.includes(re)),lost:H.filter((re)=>!oe.includes(re))};if(l.preview===!0)return f({membership:u,proposed:{roleTemplate:p,scope:I},accessDiff:L});if(String(l.confirm??"")!==u.id)return f({ok:!1,error:`Confirm this change with membership ID ${u.id}.`,accessDiff:L},409);try{return f({membership:o.store.updateMembership({id:u.id,roleTemplate:p,scope:I,actorId:w.actor?.id}),accessDiff:L})}catch(re){return f({ok:!1,error:re instanceof Error?re.message:"Membership could not be updated."},409)}}if(m.pathname==="/api/organization/memberships"&&S.method==="DELETE"){let l=await v(S),u=o.store.getMembership(String(l.id??""));if(!u||u.organizationId!==o.organization.id)return f({ok:!1,error:"Membership was not found."},404);if(String(l.confirm??"")!==u.id)return f({ok:!1,error:`Confirm removal with membership ID ${u.id}.`},409);let p=te(W);if(u.roleTemplate==="owner"&&(p.membership?.roleTemplate!=="owner"||!or(String(l.password??""),W.passwordHash)))return f({ok:!1,error:"Removing an owner requires an owner to re-enter their current password."},401);try{return f({membership:o.store.revokeMembership(u.id,p.actor?.id)})}catch(I){return f({ok:!1,error:I instanceof Error?I.message:"Membership could not be removed."},409)}}if(m.pathname==="/api/organization/grants"&&S.method==="POST"){let l=await v(S),u=String(l.capability??""),p=l.effect==="deny"?"deny":l.effect==="allow"?"allow":void 0,I=Ha(l),w=te(W);if(!p||!I||!ms.includes(u))return f({ok:!1,error:"Choose a valid capability, effect, and resource scope."},422);try{return f({grant:o.store.upsertGrant({organizationId:o.organization.id,membershipId:String(l.membershipId??""),effect:p,capability:u,scope:I,actorId:w.actor?.id})},201)}catch(D){return f({ok:!1,error:D instanceof Error?D.message:"Grant could not be created."},422)}}if(m.pathname==="/api/organization/grants"&&S.method==="DELETE"){let l=await v(S),u=te(W),p=o.store.getGrant(String(l.id??""));if(!p||p.organizationId!==o.organization.id)return f({ok:!1,error:"Grant was not found."},404);return f({ok:o.store.removeGrant(p.id,u.actor?.id)})}if(m.pathname==="/api/tags"&&S.method==="GET")return f({tags:o.store.listTags(o.project.id),assignments:o.store.listResourceTags(o.project.id)});if(m.pathname==="/api/tags"&&S.method==="POST"){let l=await v(S),u=o.store.upsertTag(o.project.id,String(l.name??""),String(l.color??"#5a8be0"));if(l.resourceId)o.store.assignTag(String(l.resourceId),u.id);return f({tag:u},201)}if(m.pathname==="/api/tags"&&S.method==="DELETE"){let l=await v(S);return o.store.removeTag(String(l.resourceId??""),String(l.tagId??"")),f({ok:!0})}if(m.pathname==="/"&&!yI(m.pathname,Ft))return new Response(null,{status:302,headers:{location:`/server/sites?env=${encodeURIComponent(V)}`}});if(m.pathname==="/"&&je?.mode==="serverless")return new Response(null,{status:302,headers:{location:`/serverless?env=${encodeURIComponent(V)}`}});let Za=pu(m.pathname);if(Za)return new Response(null,{status:308,headers:{location:`${Za}?env=${encodeURIComponent(V)}`}});if(m.pathname==="/api/env"&&S.method==="POST"){let l=await v(S),u=String(l.env??"");if(!g.includes(u))return f({ok:!1,error:`Unknown environment '${u}'.`,environments:g},404);return f({ok:!0,environment:u,environments:g,href:`?env=${encodeURIComponent(u)}`})}if(m.pathname==="/api/config"){let l={...xI(a),environment:V,environments:g};return f(Ap(l,Ft))}if(m.pathname==="/api/ssh-keys"&&S.method==="GET")return f({configPath:_,keys:Sn(Ki(a))});if(m.pathname==="/api/ssh-keys"&&S.method==="POST"){if(!_)return f({ok:!1,error:"No cloud config file was found in this checkout."},404);let l=await v(S),u=await pr(_,"utf8"),p=Ki(a),I=yR({configText:u,name:String(l.name??""),publicKey:String(l.publicKey??""),existingKeys:p});return await Xn(_,I),pI(a,[...p,{name:String(l.name??"").trim(),publicKey:String(l.publicKey??"").trim().replace(/\s+/g," ")}]),f({ok:!0,configPath:_,keys:Sn(Ki(a))})}if(m.pathname==="/api/ssh-keys"&&S.method==="DELETE"){if(!_)return f({ok:!1,error:"No cloud config file was found in this checkout."},404);let l=await v(S),u=String(l.name??m.searchParams.get("name")??""),p=await pr(_,"utf8"),I=Ki(a),w=wR({configText:p,name:u,existingKeys:I});return await Xn(_,w),pI(a,I.filter((D)=>D.name!==u.trim())),f({ok:!0,configPath:_,keys:Sn(Ki(a))})}if(m.pathname==="/api/firewall"&&S.method==="GET")return f({configPath:_,alwaysOpen:[22,80,443],ports:Ng(a)});if(m.pathname==="/api/firewall"&&S.method==="POST"){if(!_)return f({ok:!1,error:"No cloud config file was found in this checkout."},404);let l=await v(S),u=Number(l.port);if(!Wa(u))return f({ok:!1,error:"Port must be an integer between 1 and 65535."},422);let p=Ng(a),I=await pr(_,"utf8");try{await Xn(_,Op(I,u,p))}catch(A){return f({ok:!1,error:A?.message??String(A)},422)}let w=Yn([...p,u]);II(a,w);let D=l.apply===!1?null:await Ta(a,V,`ufw allow ${u}/tcp`).catch((A)=>({ok:!1,error:String(A?.message??A)}));return f({ok:!0,configPath:_,ports:w,apply:D})}if(m.pathname==="/api/firewall"&&S.method==="DELETE"){if(!_)return f({ok:!1,error:"No cloud config file was found in this checkout."},404);let l=await v(S),u=Number(l.port??m.searchParams.get("port"));if(!Wa(u))return f({ok:!1,error:"Port must be an integer between 1 and 65535."},422);let p=Ng(a),I=await pr(_,"utf8");await Xn(_,Bp(I,u,p));let w=Yn(p.filter((A)=>A!==u));II(a,w);let D=l.apply===!1?null:await Ta(a,V,`ufw delete allow ${u}/tcp`).catch((A)=>({ok:!1,error:String(A?.message??A)}));return f({ok:!0,configPath:_,ports:w,apply:D})}if(m.pathname==="/api/sites"&&S.method==="POST"){if(!_)return f({ok:!1,error:"No cloud config file was found in this checkout."},404);let l=await v(S),u=String(l.name??"").trim(),p=String(l.root??"").trim();if(!u||!p)return f({ok:!1,error:"Site name and root are required."},422);let I={deploy:l.deploy==="bucket"?"bucket":"server",root:p,path:String(l.path??"").trim()||void 0,domain:String(l.domain??"").trim()||void 0,build:String(l.build??"").trim()||void 0,start:String(l.start??"").trim()||void 0,port:l.port?Number(l.port):void 0,type:String(l.type??"").trim()||void 0};if(I.port!==void 0&&(!Number.isInteger(I.port)||I.port<1||I.port>65535))return f({ok:!1,error:"Port must be a number between 1 and 65535."},422);let w=await pr(_,"utf8"),D=Kp({configText:w,name:u,root:I.root,domain:I.domain,path:I.path,deploy:I.deploy,build:I.build,start:I.start,port:I.port,type:I.type});return await Xn(_,D),RC(a,u,Object.fromEntries(Object.entries(I).filter(([,A])=>A!==void 0))),je=await qn(a,V),E.set(V,je),f({ok:!0,configPath:_,site:u,data:je})}if(m.pathname==="/api/sites"&&S.method==="DELETE"){if(!_)return f({ok:!1,error:"No cloud config file was found in this checkout."},404);let l=await v(S),u=String(l.name??m.searchParams.get("name")??"").trim();if(!u||!a.sites?.[u])return f({ok:!1,error:`Site '${u}' was not found.`},404);let p=await pr(_,"utf8");return await Xn(_,Yp({configText:p,name:u})),delete a.sites[u],je=await qn(a,V),E.set(V,je),f({ok:!0,configPath:_,site:u,data:je})}if(m.pathname==="/api/sites"&&S.method==="PATCH"){if(!_)return f({ok:!1,error:"No cloud config file was found in this checkout."},404);let l=await v(S),u=String(l.name??"").trim(),p=a.sites?.[u];if(!u||!p)return f({ok:!1,error:`Site '${u}' was not found.`},404);if(Ft.role==="member"){let D=Cp(l);if(!D.ok)return f({ok:!1,error:D.error},403);let A=kp({siteName:u,body:l,sites:a.sites??{},ownSites:Object.keys(Ft.sites)});if(!A.ok)return f({ok:!1,error:A.error},409)}if(l.port!==void 0&&l.port!==null&&l.port!==""&&(!Number.isInteger(Number(l.port))||Number(l.port)<1||Number(l.port)>65535))return f({ok:!1,error:"Port must be a number between 1 and 65535."},422);if(typeof l.domain==="string"&&l.domain.trim()&&!Wg(l.domain.trim()))return f({ok:!1,error:`Domain '${l.domain.trim()}' is not a valid hostname.`},422);let I=await pr(_,"utf8"),w=(D,A)=>{I=Xp({configText:I,siteName:u,key:D,valueText:A})};if(l.ssl!==void 0)w("ssl",qp(l.ssl)),p.ssl=l.ssl;if(l.env!==void 0&&l.env&&typeof l.env==="object")w("env",tI(l.env)),p.env=l.env;if(l.aliases!==void 0&&Array.isArray(l.aliases)){let D=l.aliases.map((A)=>String(A));w("aliases",rI(D)),p.aliases=D.map((A)=>A.trim().toLowerCase()).filter(Boolean)}if(l.redirects!==void 0&&l.redirects&&typeof l.redirects==="object")w("redirects",nI(l.redirects)),p.redirects=l.redirects;for(let D of["domain","path","build","start","type","root","php"])if(typeof l[D]==="string"&&l[D].trim())w(D,eI(String(l[D]).trim())),p[D]=String(l[D]).trim();if(l.port!==void 0&&l.port!==null&&l.port!=="")w("port",String(Number(l.port))),p.port=Number(l.port);return await Xn(_,I),je=await qn(a,V),E.set(V,je),f({ok:!0,configPath:_,site:u,data:je})}if(m.pathname==="/api/sites/deploy"&&S.method==="POST"){let l=await v(S),u=String(l.name??"").trim();if(!u||!a.sites?.[u])return f({ok:!1,error:`Site '${u}' was not found.`},404);if(l.confirm!==u)return f({ok:!1,error:`Type "${u}" to deploy this site.`},409);let p=sr(o,String(V));await new Gn(he).run(new ba,{...p,artifactRoot:t}),Bo(he,p,je??{});let I=Jo(he,{scope:p,desiredConfigHash:o.project.desiredConfigHash});if(I.decision.outcome==="block")return f({ok:!1,error:`Deployment blocked by security policy: ${I.decision.explanation}`,securityReview:I},409);let w={id:`deploy:${u}`,label:`Deploy ${u}`,description:`Deploy the ${u} site for ${V}.`,command:["deploy","--env",V,"--site",u,"--yes"],mutates:!0},D=await yr({controlPlane:o,environment:V,actor:W,kind:"dashboard.site.deploy",resourceSlug:u,input:{site:u},execute:()=>Fg(w,{cwd:t,cliEntry:i})});return f({...D.result,controlPlaneOperation:D.operation,securityReview:I})}if(m.pathname==="/api/actions")return f(xg(V));if(m.pathname==="/api/server/operations")return f(Go(a,je));if(m.pathname==="/api/runtime/workloads"&&S.method==="GET"){let l=await ir(a,V);return f(l)}if(m.pathname==="/api/runtime/logs"&&S.method==="GET"){let l=String(m.searchParams.get("workload")??"");if(!l)return f({ok:!1,error:"A workload query parameter is required."},422);let u=Math.min(1000,Math.max(1,Number(m.searchParams.get("limit"))||200));try{return f(await new _r(a,V).logs(l,{limit:u}))}catch(p){return f({ok:!1,error:String(p?.message??p)},404)}}if(m.pathname==="/api/runtime/log-sessions"&&S.method==="POST"){let l=await v(S),u=String(l.workloadId??"");if(!u)return f({ok:!1,error:"A workloadId is required."},422);let p=await ir(a,V),I=p.workloads.find((A)=>A.id===u);if(!I)return f({ok:!1,error:"Workload was not found in the current project and environment."},404);if(!I.capabilities.logs.supported)return f({ok:!1,error:I.capabilities.logs.reason??"Logs are unsupported for this workload."},409);let w=new _r(a,V,{inventory:async()=>p}),D=Ge.create("logs",u);return(async()=>{let A=new Date(Date.now()-Math.min(3600000,Math.max(1000,Number(l.sinceMs)||60000)));try{for(let k=0;k<200&&!Ge.signal(D.id)?.aborted;k++){let H=await w.logs(u,{limit:Math.min(500,Math.max(1,Number(l.limit)||200)),since:A});for(let j of H.lines)if(Ge.append(D.id,`${j.timestamp?`${j.timestamp} `:""}${j.message}
692
+ `),j.timestamp)A=new Date(Math.max(A.getTime(),new Date(j.timestamp).getTime()+1));await Bun.sleep(3000)}if(!Ge.signal(D.id)?.aborted)Ge.close(D.id,"complete")}catch(k){Ge.append(D.id,k instanceof Error?k.message:String(k),"stderr"),Ge.close(D.id,"failed",k instanceof Error?k.message:String(k))}})(),f({ok:!0,session:D,streamUrl:`/api/runtime/log-stream?id=${encodeURIComponent(D.id)}&workload=${encodeURIComponent(u)}`},201)}if((m.pathname==="/api/runtime/log-stream"||m.pathname==="/api/runtime/exec-stream")&&S.method==="GET"){let l=String(m.searchParams.get("id")??""),u=String(m.searchParams.get("workload")??""),p=Number(S.headers.get("last-event-id")??m.searchParams.get("after")??0)||0,I=Ge.read(l,u,p),w=m.pathname.includes("exec")?"exec":"logs";if(!I||I.kind!==w)return f({ok:!1,error:"Runtime stream was not found in this workload scope."},404);return dC(Ge,I,p,S.signal)}if((m.pathname==="/api/runtime/log-sessions"||m.pathname==="/api/runtime/exec-sessions")&&S.method==="DELETE"){let l=await v(S),u=Ge.cancel(String(l.id??""),String(l.workloadId??""));if(!u)return f({ok:!1,error:"Runtime stream was not found in this workload scope."},404);return f({ok:!0,session:u})}if(m.pathname==="/api/runtime/exec-sessions"&&S.method==="POST"){let l=await v(S),u=String(l.workloadId??""),p=await ir(a,V),I=p.workloads.find((k)=>k.id===u);if(!I)return f({ok:!1,error:"Workload was not found in the current project and environment."},404);let w=He.resolveSession(S),D=new _r(a,V,{inventory:async()=>p}),A=Ge.create("exec",u);return yr({controlPlane:o,environment:V,actor:W,kind:"runtime.exec",resourceSlug:I.links.service,input:{workloadId:u,provider:I.provider,preset:l.preset?String(l.preset):null,freeForm:!!String(l.command??"").trim()},execute:()=>D.exec({workloadId:u,preset:["process","sockets","filesystem"].includes(String(l.preset))?String(l.preset):void 0,command:typeof l.command==="string"?l.command:void 0,confirm:String(l.confirm??""),recentAuth:!M||!!w&&G.isRecentlyAuthenticated(w)})}).then(({result:k,operation:H})=>{if(Ge.append(A.id,`operation ${H.id}
693
+ `,"system"),k.stdout)Ge.append(A.id,k.stdout,"stdout");if(k.stderr)Ge.append(A.id,k.stderr,"stderr");Ge.close(A.id,k.ok?"complete":"failed",k.error)}).catch((k)=>{let H=k instanceof Error?k.message:String(k);Ge.append(A.id,H,"stderr"),Ge.close(A.id,"failed",H)}),f({ok:!0,session:A,streamUrl:`/api/runtime/exec-stream?id=${encodeURIComponent(A.id)}&workload=${encodeURIComponent(u)}`},202)}if(m.pathname==="/api/runtime/files/read"&&S.method==="POST"){let l=await v(S),u=await ir(a,V),p=He.resolveSession(S),I=await new _r(a,V,{inventory:async()=>u}).readFile({workloadId:String(l.workloadId??""),path:String(l.path??""),confirm:String(l.confirm??""),recentAuth:!M||!!p&&G.isRecentlyAuthenticated(p)});return f(I,I.ok?200:409)}if(m.pathname==="/api/runtime/files/write"&&S.method==="POST"){let l=await v(S),u=await ir(a,V),p=String(l.workloadId??""),I=u.workloads.find((k)=>k.id===p);if(!I)return f({ok:!1,error:"Workload was not found in the current project and environment."},404);let w=He.resolveSession(S),D=new _r(a,V,{inventory:async()=>u}),A=await yr({controlPlane:o,environment:V,actor:W,kind:"runtime.file.write",resourceSlug:I.links.service,input:{workloadId:p,provider:I.provider,path:String(l.path??""),bytes:Buffer.from(String(l.contentBase64??""),"base64").byteLength},execute:()=>D.writeFile({workloadId:p,path:String(l.path??""),contentBase64:String(l.contentBase64??""),confirm:String(l.confirm??""),recentAuth:!M||!!w&&G.isRecentlyAuthenticated(w)})});return f({...A.result,controlPlaneOperation:A.operation},A.result.ok?200:409)}if(m.pathname==="/api/runtime/operations"&&S.method==="POST"){let l=await v(S),u=String(l.workloadId??""),p=String(l.action??"");if(!u||!["start","stop","restart","redeploy","scale","inspect"].includes(p))return f({ok:!1,error:"A valid workloadId and lifecycle action are required."},422);let I=await ir(a,V),w=I.workloads.find((H)=>H.id===u);if(!w)return f({ok:!1,error:"Workload was not found in the current project and environment."},404);let D=He.resolveSession(S),A=new _r(a,V,{inventory:async()=>I}),k=await yr({controlPlane:o,environment:V,actor:W,kind:`runtime.${p}`,resourceSlug:w.links.service,input:{workloadId:u,provider:w.provider,action:p,replicas:l.replicas==null?null:Number(l.replicas)},execute:()=>A.run({workloadId:u,action:p,replicas:l.replicas==null?void 0:Number(l.replicas),confirm:String(l.confirm??""),recentAuth:!M||!!D&&G.isRecentlyAuthenticated(D)})});return f({...k.result,controlPlaneOperation:k.operation},k.result.ok?200:409)}if(m.pathname.startsWith("/api/protection")){let l=W.role==="admin"||Ga(W,"security:read"),u=W.role==="admin"||Ga(W,"security:manage");if(!l)return f({ok:!1,error:"Protection controls require security:read."},403);let{ProtectionControlStore:p,describePosture:I}=await import("./protection/index.js"),w=new p(o.store),D=()=>{if(!u)throw Error("Changing protection controls requires security:manage.")};if(m.pathname==="/api/protection"&&S.method==="GET"){let A=w.current();return f({ok:!0,posture:I(A),controls:A,raw:w.raw()})}if(m.pathname==="/api/protection/attack-mode"&&S.method==="POST"){D();let A=await v(S);if(A.enabled===!1)return f({ok:!0,disabled:w.disableAttackMode()});return f({ok:!0,control:w.enableAttackMode({hours:A.hours==null?void 0:Number(A.hours),reason:String(A.reason??"Enabled from the dashboard."),actorId:te(W).actor?.id})})}if(m.pathname==="/api/protection/pause"&&S.method==="POST"){D();let A=await v(S);if(A.enabled===!1)return f({ok:!0,resumed:w.resumeMitigations()});return f({ok:!0,control:w.pauseMitigations({hours:A.hours==null?void 0:Number(A.hours),reason:String(A.reason??""),actorId:te(W).actor?.id})})}if(m.pathname==="/api/protection/ip-rules"&&S.method==="GET")return f({ok:!0,ipRules:w.current().ipRules});if(m.pathname==="/api/protection/ip-rules"&&(S.method==="POST"||S.method==="DELETE")){D();let A=await v(S),k=A.list==="allow"?"allow":"block",H=S.method==="POST"?w.addIpRule(k,String(A.cidr??"")):w.removeIpRule(k,String(A.cidr??""));return f({ok:!0,ipRules:H})}return f({ok:!1,error:"Protection endpoint was not found."},404)}if(m.pathname.startsWith("/api/spend/")||m.pathname==="/api/usage"){let l=await YI(),u=l.store,p=l.service,I=l.gate,w=W.role==="admin"||Ga(W,"billing:read"),D=W.role==="admin"||Ga(W,"billing:manage");if(!w)return f({ok:!1,error:"Spend data requires the billing:read capability."},403);let A=o.environments.get(V),k={organizationId:o.organization.id,projectId:o.project.id,environmentId:A?.id},H=()=>{if(!D)throw Error("Changing a budget requires the billing:manage capability.")};if(m.pathname==="/api/usage"&&S.method==="GET")return f({ok:!0,...p.usageReport({organizationId:k.organizationId,projectId:k.projectId,period:m.searchParams.get("period")??"monthly",timezone:m.searchParams.get("timezone")??void 0})});if(m.pathname==="/api/spend/budgets"&&S.method==="GET")return f({ok:!0,budgets:u.listBudgets({organizationId:k.organizationId,projectId:k.projectId}).map((j)=>({...j,status:p.status(j)}))});if(m.pathname==="/api/spend/budgets"&&S.method==="POST"){H();let j=await v(S),oe=String(j.scope??"project"),L=u.createBudget({organizationId:k.organizationId,projectId:oe==="organization"?void 0:k.projectId,environmentId:oe==="environment"?k.environmentId:void 0,name:String(j.name??"").trim(),period:j.period??"monthly",timezone:j.timezone?String(j.timezone):void 0,softLimitCents:j.softLimitCents==null?void 0:Math.round(Number(j.softLimitCents)),hardLimitCents:j.hardLimitCents==null?void 0:Math.round(Number(j.hardLimitCents)),graceSeconds:j.graceSeconds==null?void 0:Number(j.graceSeconds),dryRun:j.dryRun!==!1});return f({ok:!0,budget:L})}if(m.pathname==="/api/spend/budgets"&&S.method==="PATCH"){H();let j=await v(S),oe=String(j.id??""),L=u.getBudget(oe);if(!L||L.organizationId!==k.organizationId)return f({ok:!1,error:"Budget was not found."},404);return f({ok:!0,budget:u.updateBudget(oe,{softLimitCents:j.softLimitCents==null?L.softLimitCents:Math.round(Number(j.softLimitCents)),hardLimitCents:j.hardLimitCents==null?L.hardLimitCents:Math.round(Number(j.hardLimitCents)),enabled:j.enabled==null?L.enabled:j.enabled===!0,dryRun:j.dryRun==null?L.dryRun:j.dryRun===!0},j.expectedVersion==null?void 0:Number(j.expectedVersion))})}if(m.pathname==="/api/spend/budgets"&&S.method==="DELETE"){H();let j=await v(S),oe=String(j.id??""),L=u.getBudget(oe);if(!L||L.organizationId!==k.organizationId)return f({ok:!1,error:"Budget was not found."},404);let re=I.closeBudget(oe);return u.deleteBudget(oe),f({ok:!0,deleted:!0,lifted:re})}if(m.pathname==="/api/spend/check"&&S.method==="POST"){H();let j=await v(S),{SpendRunner:oe}=await import("./spend/index.js"),L=new oe({controlPlane:o.store,store:u,alerts:ce});if(j.apply!==!0){let x=u.budgetsForScope(k.organizationId,k.projectId,k.environmentId);return f({ok:!0,applied:!1,preview:x.map((q)=>p.status(q))})}let re=await L.run({...k,environmentKind:A?.kind});return f({ok:!0,applied:!0,result:re})}if(m.pathname==="/api/spend/enforcement"&&S.method==="GET")return f({ok:!0,enforcement:I.listUnder({organizationId:k.organizationId})});if(m.pathname==="/api/spend/release"&&S.method==="POST"){H();let j=await v(S),oe=I.close(String(j.budgetId??""),j.action);return f({ok:oe,released:oe,note:oe?"The next spend cycle re-applies this if spend is still over the threshold.":"That action was not in force."})}if(m.pathname==="/api/spend/anomalies"&&S.method==="GET")return f({ok:!0,anomalies:u.listAnomalies({organizationId:k.organizationId,projectId:k.projectId,unacknowledgedOnly:m.searchParams.get("unacknowledged")==="true"})});if(m.pathname==="/api/spend/anomalies/acknowledge"&&S.method==="POST"){H();let j=await v(S);return f({ok:!0,acknowledged:u.acknowledgeAnomaly(String(j.id??""))})}return f({ok:!1,error:"Spend endpoint was not found."},404)}if(m.pathname.startsWith("/api/health/")||m.pathname.startsWith("/api/alerts")||m.pathname.startsWith("/api/notifications/")){let l=o.environments.get(V),u=o.store.listResources(o.project.id,l?.id),p=W.role==="admin"||!!l&&Xi(W,l.id,"runtime:read")?u:u.filter((A)=>at(W,A.id,"runtime:read")),I=(A)=>!A||p.some((k)=>k.id===A),w=(A)=>{if(!A)return;let k=u.find((H)=>H.id===A||H.slug===A);if(!k)throw Error("Alert resource was not found.");if(!I(k.id))throw Error("Alert resource is outside your authorized scope.");return k.id},D=te(W).actor;if(m.pathname==="/api/health/checks"&&S.method==="GET")return f({ok:!0,checks:ce.listHealthChecks(o.project.id,l?.id).filter((A)=>I(A.resourceId)).map((A)=>({...A,results:ce.listHealthResults(A.id,20)}))});if(m.pathname==="/api/health/checks"&&S.method==="POST"){let A=await v(S),k=String(A.kind??"http");if(k==="command"&&W.role!=="admin")return f({ok:!1,error:"Command health checks require an administrator."},403);let H={method:String(A.config?.method??"GET").toUpperCase().slice(0,10),path:A.config?.path?String(A.config.path).slice(0,500):void 0,port:A.config?.port==null?void 0:Number(A.config.port),command:Array.isArray(A.config?.command)?A.config.command.map(String).slice(0,20):void 0,expectedStatuses:Array.isArray(A.config?.expectedStatuses)?A.config.expectedStatuses.map(Number).filter(Number.isInteger).slice(0,20):void 0,expectedBody:A.config?.expectedBody?String(A.config.expectedBody).slice(0,500):void 0};return f({ok:!0,check:ce.createHealthCheck({projectId:o.project.id,environmentId:l?.id,resourceId:w(A.resourceId??A.resource),name:String(A.name??""),kind:k,target:String(A.target??""),config:H,intervalSeconds:Number(A.intervalSeconds)||60,timeoutSeconds:Number(A.timeoutSeconds)||10,failureThreshold:Number(A.failureThreshold)||3,recoveryThreshold:Number(A.recoveryThreshold)||2,regions:Array.isArray(A.regions)?A.regions.map(String):["local"],enabled:A.enabled!==!1})},201)}if(m.pathname==="/api/health/checks"&&S.method==="PATCH"){let A=await v(S),k=ce.getHealthCheck(String(A.id??""));if(!k||!I(k.resourceId))return f({ok:!1,error:"Health check was not found."},404);return f({ok:!0,check:ce.setHealthCheckEnabled(k.id,A.enabled!==!1)})}if(m.pathname==="/api/health/checks/test"&&S.method==="POST"){let A=await v(S),k=ce.getHealthCheck(String(A.id??""));if(!k||!I(k.resourceId))return f({ok:!1,error:"Health check was not found."},404);return f({ok:!0,productionIncidentCreated:!1,result:await new Gi(ce).probe(k)})}if(m.pathname==="/api/health/checks/run"&&S.method==="POST"){let A=await v(S),k=ce.getHealthCheck(String(A.id??""));if(!k||!I(k.resourceId))return f({ok:!1,error:"Health check was not found."},404);let H=await new Gi(ce).runAndEvaluate(k),j=[];for(let oe of H.evaluations.filter((L)=>L.notify&&L.alert)){let L=Nt.enqueue(o.organization.id,oe.alert,oe.transition);j.push(...await Nt.deliverAll(L))}return f({ok:!0,...H,deliveries:j})}if(m.pathname==="/api/alerts/rules"&&S.method==="GET")return f({ok:!0,rules:ce.listRules(o.project.id,l?.id).filter((A)=>I(A.resourceId))});if(m.pathname==="/api/alerts/rules"&&S.method==="POST"){let A=await v(S),k=A.healthCheckId?ce.getHealthCheck(String(A.healthCheckId)):void 0;if(A.healthCheckId&&(!k||!I(k.resourceId)))return f({ok:!1,error:"Health check was not found."},404);return f({ok:!0,rule:ce.createRule({projectId:o.project.id,environmentId:l?.id,resourceId:w(A.resourceId??A.resource)??k?.resourceId,healthCheckId:k?.id,name:String(A.name??""),signal:String(A.signal??(k?"health":"")),operator:String(A.operator??(k?"unhealthy":"gt")),threshold:A.threshold==null?void 0:Number(A.threshold),recoveryThreshold:A.recoveryThreshold==null?void 0:Number(A.recoveryThreshold),windowMs:Number(A.windowMs)||300000,consecutive:Number(A.consecutive)||k?.failureThreshold||3,recoveryConsecutive:Number(A.recoveryConsecutive)||k?.recoveryThreshold||2,noDataPolicy:["ignore","pending","firing"].includes(String(A.noDataPolicy))?A.noDataPolicy:"pending",severity:["info","warning","critical"].includes(String(A.severity))?A.severity:"warning",groupBy:Array.isArray(A.groupBy)?A.groupBy.map(String):[],labels:A.labels&&typeof A.labels==="object"?A.labels:{},enabled:A.enabled!==!1})},201)}if(m.pathname==="/api/alerts/rules"&&S.method==="PATCH"){let A=await v(S),k=ce.getRule(String(A.id??""));if(!k||!I(k.resourceId))return f({ok:!1,error:"Alert rule was not found."},404);return f({ok:!0,rule:ce.setRuleEnabled(k.id,A.enabled!==!1)})}if(m.pathname==="/api/alerts/evaluate"&&S.method==="POST")return f({ok:!0,...await qg(l?.id)});if(m.pathname==="/api/alerts"&&S.method==="GET")return f({ok:!0,alerts:ce.listAlerts(o.project.id,{environmentId:l?.id,states:m.searchParams.getAll("state").length?m.searchParams.getAll("state"):void 0,limit:Number(m.searchParams.get("limit"))||200}).filter((A)=>I(A.resourceId)).map((A)=>({...A,deliveries:ce.listDeliveries({alertId:A.id,limit:50})}))});if(m.pathname==="/api/alerts/action"&&S.method==="POST"){let A=await v(S),k=ce.getAlert(String(A.id??""));if(!k||!I(k.resourceId))return f({ok:!1,error:"Alert was not found."},404);let H=String(A.action??"");if(H==="acknowledge")return f({ok:!0,alert:ce.acknowledge(k.id,D?.id??"")});if(H==="assign")return f({ok:!0,alert:ce.assign(k.id,A.ownerActorId==="me"?D?.id:A.ownerActorId?String(A.ownerActorId):void 0,D?.id)});if(H==="silence"){if(W.role!=="admin")return f({ok:!1,error:"Silencing production alerts requires an administrator."},403);let j=He.resolveSession(S);if(M&&(!j||!G.isRecentlyAuthenticated(j)))return f({ok:!1,error:"Recent authentication is required to silence alerts.",stepUpRequired:!0},401);return f({ok:!0,alert:ce.silenceAlert(k.id,String(A.until??""),D?.id)})}return f({ok:!1,error:"Action must be acknowledge, assign, or silence."},422)}if(m.pathname==="/api/alerts/silences"&&S.method==="POST"){let A=await v(S);return f({ok:!0,id:ce.createSilence({projectId:o.project.id,environmentId:l?.id,resourceId:w(A.resourceId??A.resource),matcher:A.matcher,reason:String(A.reason??""),startsAt:String(A.startsAt??new Date().toISOString()),endsAt:String(A.endsAt??""),timezone:String(A.timezone??"UTC"),actorId:D?.id})},201)}if(m.pathname==="/api/notifications/channels"&&S.method==="GET")return f({ok:!0,channels:ce.listChannels(o.organization.id)});if(m.pathname==="/api/notifications/channels"&&S.method==="POST"){let A=await v(S),k=String(A.kind??""),H=k==="email"?{to:A.config?.to,from:A.config?.from}:k==="telegram"?{chatId:String(A.config?.chatId??"")}:{};return f({ok:!0,channel:ce.createChannel({organizationId:o.organization.id,name:String(A.name??""),kind:k,config:H,credential:A.credential?String(A.credential):void 0,actorId:D?.id})},201)}if(m.pathname==="/api/notifications/channels"&&S.method==="PATCH"){let A=await v(S),k=String(A.id??"");if(A.credential)return f({ok:!0,channel:ce.rotateChannel(k,String(A.credential))});let H=String(A.status??"paused");if(!["active","paused","disabled"].includes(H))return f({ok:!1,error:"Channel status must be active, paused, or disabled."},422);return f({ok:!0,channel:ce.setChannelStatus(k,H)})}if(m.pathname==="/api/notifications/channels/test"&&S.method==="POST"){let A=await v(S);return f({ok:!0,productionIncidentCreated:!1,result:await Nt.testChannel(String(A.id??""))})}if(m.pathname==="/api/notifications/routes"&&S.method==="GET")return f({ok:!0,routes:ce.listRoutes(o.organization.id)});if(m.pathname==="/api/notifications/routes"&&S.method==="POST"){let A=await v(S),k=Array.isArray(A.channelIds)?A.channelIds.map(String):[];if(k.some((H)=>ce.getChannel(H)?.organizationId!==o.organization.id))return f({ok:!1,error:"Route contains an unavailable channel."},422);return f({ok:!0,route:ce.createRoute({organizationId:o.organization.id,name:String(A.name??""),priority:Number(A.priority)||0,matcher:A.matcher&&typeof A.matcher==="object"?A.matcher:{},channelIds:k,quietHours:A.quietHours,groupWaitSeconds:Number(A.groupWaitSeconds)||30,reminderSeconds:A.reminderSeconds==null?void 0:Number(A.reminderSeconds),escalation:Array.isArray(A.escalation)?A.escalation:[],template:A.template?String(A.template):void 0,rateLimitPerMinute:Number(A.rateLimitPerMinute)||60,enabled:A.enabled!==!1})},201)}if(m.pathname==="/api/notifications/routes"&&S.method==="PATCH"){let A=await v(S),k=ce.getRoute(String(A.id??""));if(!k||k.organizationId!==o.organization.id)return f({ok:!1,error:"Notification route was not found."},404);return f({ok:!0,route:ce.setRouteEnabled(k.id,A.enabled!==!1)})}if(m.pathname==="/api/notifications/routes/preview"&&S.method==="POST"){let A=await v(S),H=(A.alertId?ce.getAlert(String(A.alertId)):void 0)??{id:"preview",ruleId:"preview",projectId:o.project.id,environmentId:l?.id,resourceId:w(A.resourceId??A.resource),dedupKey:"preview",groupKey:String(A.groupKey??"default"),state:"firing",severity:["info","warning","critical"].includes(String(A.severity))?A.severity:"warning",title:String(A.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 f({ok:!0,productionIncidentCreated:!1,matches:Nt.preview(o.organization.id,H,String(A.eventType??"firing")).map((j)=>({route:j.route,channels:j.channels,quiet:j.quiet}))})}if(m.pathname==="/api/notifications/deliveries"&&S.method==="GET")return f({ok:!0,deliveries:ce.listDeliveries({alertId:m.searchParams.get("alertId")??void 0,states:m.searchParams.getAll("state"),limit:Number(m.searchParams.get("limit"))||200})});if(m.pathname==="/api/notifications/deliveries/retry"&&S.method==="POST"){let A=await v(S),k=ce.getDelivery(String(A.id??""));if(!k)return f({ok:!1,error:"Delivery was not found."},404);return ce.updateDelivery(k.id,{state:"retrying",attempt:Math.max(0,k.attempt-1),nextAttemptAt:new Date().toISOString()}),f({ok:!0,delivery:await Nt.deliver(k.id)})}}if(m.pathname.startsWith("/api/jobs")||m.pathname.startsWith("/api/workers")){let l=o.environments.get(V),u=o.store.listResources(o.project.id,l?.id),I=W.role==="admin"||!!l&&Xi(W,l.id,"automation:read")?u:u.filter((x)=>at(W,x.id,"automation:read")),w=(x)=>!x||I.some((q)=>q.id===x),D=te(W).actor,A=E.get(V)??R,k=Go(a,A),H=k.filter((x)=>!x.danger&&["scheduler","backup","worker"].includes(x.group)),j=Ur(a),oe=()=>{let x=He.resolveSession(S);return!M||!!x&&G.isRecentlyAuthenticated(x)},L=(x)=>{if(!x||typeof x!=="object"||Array.isArray(x))return{};let q=Object.entries(x).slice(0,50);if(q.some(([,ge])=>typeof ge!=="string"||!/^(?:secret|ssm|arn|env):\/\//.test(ge)))throw Error("Job payload values must be secret or environment references, never inline values.");return Object.fromEntries(q)},re=(x,q,ge)=>o.store.appendEvent({organizationId:o.organization.id,projectId:o.project.id,resourceId:ge,actorId:D?.id,type:`job.${x}`,payload:q});if(m.pathname==="/api/jobs/preview"&&S.method==="POST"){let x=await v(S);try{return f({ok:!0,productionExecutionCreated:!1,preview:Wn(String(x.expression??""),String(x.timezone??"UTC"),new Date(x.from?String(x.from):Date.now()),Number(x.count)||5)})}catch(q){return f({ok:!1,error:q instanceof Error?q.message:"Schedule preview could not be generated.",productionExecutionCreated:!1},422)}}if(m.pathname==="/api/jobs"&&S.method==="GET")return f({ok:!0,jobs:it.list(o.project.id,{environmentId:l?.id}).filter((x)=>w(x.resourceId)).map((x)=>({...x,preview:Wn(x.normalizedExpression,x.timezone,new Date,5),capability:Sa(x),lastExecution:it.listExecutions(x.id,1)[0]}))});if(m.pathname==="/api/jobs"&&S.method==="POST"){let x=await v(S),q=String(x.provider??(j==="serverless"?"eventbridge":"server")),ge=j==="serverless"?"eventbridge":"server";if(q!==ge)return f({ok:!1,error:`${j} environments accept ${ge} schedules through this adapter.`},422);let Re=x.operationId?String(x.operationId):void 0;if(q==="server"&&(!Re||!H.some((Ze)=>Ze.id===Re)))return f({ok:!1,error:"Server jobs require an allowlisted operation target."},422);let $e=Sa({provider:q,expression:String(x.expression??""),flexibleMinutes:Number(x.flexibleMinutes)||0,missedRunPolicy:x.missedRunPolicy==="catch_up"?"catch_up":"skip",overlapPolicy:["allow","forbid","replace"].includes(String(x.overlapPolicy))?x.overlapPolicy:"forbid"});if(!$e.supported)return f({ok:!1,error:$e.notes.join(" ")},422);let Tt=x.resourceId?u.find((Ze)=>Ze.id===x.resourceId||Ze.slug===x.resourceId):void 0;if(x.resourceId&&(!Tt||!w(Tt.id)))return f({ok:!1,error:"Job resource was not found."},404);try{let Ze=q==="server"?{kind:"dashboard_operation",operationId:Re}:{kind:"serverless_scheduler",action:"run"},Gr=it.create({organizationId:o.organization.id,projectId:o.project.id,environmentId:l?.id,resourceId:Tt?.id,name:String(x.name??""),provider:q,expression:String(x.expression??""),timezone:String(x.timezone??"UTC"),startsAt:x.startsAt?String(x.startsAt):void 0,endsAt:x.endsAt?String(x.endsAt):void 0,flexibleMinutes:Number(x.flexibleMinutes)||0,target:Ze,payloadRefs:L(x.payloadRefs),missedRunPolicy:x.missedRunPolicy==="catch_up"?"catch_up":"skip",overlapPolicy:["allow","forbid","replace"].includes(String(x.overlapPolicy))?x.overlapPolicy:"forbid",retryPolicy:{maxAttempts:Number(x.maxAttempts)||3,backoffSeconds:Number(x.backoffSeconds)||30,deadLetterRef:x.deadLetterRef?String(x.deadLetterRef):void 0},timeoutSeconds:Number(x.timeoutSeconds)||900,enabled:x.enabled!==!1,origin:"managed",ownerActorId:D?.id,observedState:{},reconciliationStatus:"pending"});return re("created",{jobId:Gr.id,provider:Gr.provider,expression:Gr.normalizedExpression},Gr.resourceId),f({ok:!0,job:Gr,capability:$e},201)}catch(Ze){return f({ok:!1,error:Ze instanceof Error?Ze.message:"Scheduled job could not be created."},422)}}if(m.pathname==="/api/jobs"&&S.method==="PATCH"){let x=await v(S),q=it.get(String(x.id??""));if(!q||!w(q.resourceId))return f({ok:!1,error:"Scheduled job was not found."},404);if(q.origin==="config")return f({ok:!1,error:"Config-defined schedules must be edited in cloud.config.ts and reconciled."},409);let ge=x.missedRunPolicy==null?void 0:String(x.missedRunPolicy),Re=x.overlapPolicy==null?void 0:String(x.overlapPolicy);if(ge&&!["skip","catch_up"].includes(ge))return f({ok:!1,error:"Missed-run policy must be skip or catch_up."},422);if(Re&&!["allow","forbid","replace"].includes(Re))return f({ok:!1,error:"Overlap policy must be allow, forbid, or replace."},422);try{let $e=it.updateSchedule(q.id,{expression:x.expression?String(x.expression):void 0,timezone:x.timezone?String(x.timezone):void 0,missedRunPolicy:ge,overlapPolicy:Re,timeoutSeconds:x.timeoutSeconds==null?void 0:Number(x.timeoutSeconds)});return re("updated",{jobId:$e.id,expression:$e.normalizedExpression,version:$e.version},$e.resourceId),f({ok:!0,job:$e})}catch($e){return f({ok:!1,error:$e instanceof Error?$e.message:"Scheduled job could not be updated."},422)}}if(m.pathname==="/api/jobs/action"&&S.method==="POST"){let x=await v(S),q=it.get(String(x.id??""));if(!q||!w(q.resourceId))return f({ok:!1,error:"Scheduled job was not found."},404);let ge=String(x.action??"");if(ge==="run"){let Re=Xg.enqueue(q,{trigger:"manual",actorId:D?.id});return re("run_queued",{jobId:q.id,executionId:Re.id},q.resourceId),f({ok:!0,execution:Re},202)}if(["disable","delete"].includes(ge)&&l?.kind==="production"){if(String(x.confirm??"")!==ge)return f({ok:!1,error:`Type "${ge}" to confirm this production change.`},409);if(!oe())return f({ok:!1,error:"Recent authentication is required for this production change.",stepUpRequired:!0},401)}if(ge==="enable"||ge==="disable"){let Re=it.setEnabled(q.id,ge==="enable");return re(ge==="enable"?"enabled":"disabled",{jobId:q.id},q.resourceId),f({ok:!0,job:Re})}if(ge==="delete")try{return it.remove(q.id),re("deleted",{jobId:q.id,name:q.name},q.resourceId),f({ok:!0,deleted:q.id})}catch(Re){return f({ok:!1,error:Re instanceof Error?Re.message:"Scheduled job could not be deleted."},409)}return f({ok:!1,error:"Action must be run, enable, disable, or delete."},422)}if(m.pathname==="/api/jobs/history"&&S.method==="GET"){let x=it.get(String(m.searchParams.get("jobId")??""));if(!x||!w(x.resourceId))return f({ok:!1,error:"Scheduled job was not found."},404);return f({ok:!0,executions:it.listExecutions(x.id,Number(m.searchParams.get("limit"))||100).map((q)=>({...q,logs:q.operationId?be.logs(q.operationId,{limit:500}):[]}))})}if(m.pathname==="/api/jobs/reconcile"&&S.method==="POST"){if(!l)return f({ok:!1,error:"Environment was not found."},404);let x=ic(it,a,{organization:o.organization,project:o.project,environment:l,resources:u});return re("reconciled",x),f({ok:!0,reconciliation:x})}if(m.pathname==="/api/workers"&&S.method==="GET"){let x=Array.isArray(A.workersDetail??A.workers)?A.workersDetail??A.workers:[];return f({ok:!0,workers:it.listWorkers(o.project.id,l?.id).filter((q)=>w(q.resourceId)).map((q)=>{let ge=x.find((Re)=>Re.name===q.name||Re.site===q.target.site);return ge?{...q,observedState:{...q.observedState,status:ge.status??"configured",currentJob:ge.currentJob??null,failures:Number(ge.failed??ge.failures)||0,processed:Number(ge.processed)||0}}:q})})}if(m.pathname==="/api/workers/action"&&S.method==="POST"){let x=await v(S),q=it.getWorker(String(x.id??""));if(!q||!w(q.resourceId))return f({ok:!1,error:"Worker was not found."},404);let ge=String(x.action??"");if(ge==="restart"){if(String(x.confirm??"")!==q.name)return f({ok:!1,error:`Type "${q.name}" to restart this worker.`},409);let Re=k.find((Ze)=>Ze.id===q.target.operationId);if(!Re)return f({ok:!1,error:"The allowlisted worker restart operation is unavailable."},409);let $e=await Zo(a,V,Re),Tt=it.reconcileWorker(q.id,$e.ok?"in_sync":"unavailable",{...q.observedState,lastRestartAt:new Date().toISOString(),command:$e.command??null,error:$e.error??$e.stderr??null});return re("worker_restarted",{workerId:q.id,ok:$e.ok},q.resourceId),f({...$e,worker:Tt},$e.ok?200:409)}if(ge==="scale")return f({ok:!1,error:q.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 f({ok:!1,error:"Action must be restart or scale."},422)}}if(m.pathname.startsWith("/api/telemetry/")){let l=o.environments.get(V),u=new qo(o.store),p=o.store.listResources(o.project.id,l?.id),I=["/api/telemetry/query","/api/telemetry/tail","/api/telemetry/export","/api/telemetry/saved-queries","/api/telemetry/refresh"].includes(m.pathname)?"runtime:logs":"runtime:read",w=W.role==="admin"||!!l&&Xi(W,l.id,I),D=w?p:p.filter((L)=>at(W,L.id,I)),A=(L)=>sI(D,w,L),k=(L)=>{let re=new Date,x={"1h":3600000,"6h":21600000,"24h":86400000,"7d":604800000,"30d":2592000000},q=String(L.to??re.toISOString()),ge=String(L.from??new Date(new Date(q).getTime()-(x[String(L.range??"1h")]??x["1h"])).toISOString()),Re=(Tt)=>{let Ze=(Array.isArray(Tt)?Tt:String(Tt??"").split(",")).map(String).filter(Boolean);return Ze.length?Ze:void 0},$e=Re(L.kinds)?.filter((Tt)=>["metric","log","trace","request","event"].includes(Tt));return{projectId:o.project.id,environmentId:l?.id,resourceIds:A(L.resources),kinds:$e,names:Re(L.names),sources:Re(L.sources),levels:Re(L.levels),from:ge,to:q,text:String(L.text??"")||void 0,traceId:String(L.traceId??"")||void 0,requestId:String(L.requestId??"")||void 0,deploymentId:String(L.deploymentId??"")||void 0,releaseId:String(L.releaseId??"")||void 0,workloadId:String(L.workloadId??"")||void 0,cursor:String(L.cursor??"")||void 0,limit:Number(L.limit)||void 0}},H=Object.fromEntries(m.searchParams.entries()),j=(L=!1)=>Hg({controlPlane:o.store,projectId:o.project.id,environmentId:l?.id,config:a,environment:V,force:L,lightweight:!L}),oe=()=>{let L=o.store.getSetting(`telemetry.collection:${o.project.id}:${l?.id??"all"}`)??{};return{generatedAt:String(L.generatedAt??new Date().toISOString()),cached:!0,statuses:Array.isArray(L.statuses)?L.statuses:[],errors:Array.isArray(L.errors)?L.errors:[],policy:L.policy??Ua(o.store,o.project.id)}};if(m.pathname==="/api/telemetry/status"&&S.method==="GET"){j(!1);let L=oe(),re=w?L.statuses:u.status(o.project.id,l?.id,L.policy.rawDays,L.policy.samplingRate,D.map((q)=>q.id)),x=re.reduce((q,ge)=>q+ge.estimatedDailyBytes*30,0);return f({ok:!0,generatedAt:L.generatedAt,cached:L.cached,sources:re,errors:w?L.errors:[],policy:L.policy,retention:{rawDays:L.policy.rawDays,downsampleAfterDays:L.policy.downsampleAfterDays,downsampleBucketMs:L.policy.downsampleBucketMs,maxRecords:L.policy.maxRecords},estimatedMonthlyBytes:x,estimatedMonthlyCostUsd:UI(x,L.policy),costEstimateConfigured:L.policy.estimatedStorageUsdPerGbMonth>0})}if(m.pathname==="/api/telemetry/settings"&&S.method==="GET")return f({ok:!0,policy:Ua(o.store,o.project.id)});if(m.pathname==="/api/telemetry/settings"&&S.method==="PATCH"){let L=jI(o.store,o.project.id,await v(S));return hI(o.project.id),f({ok:!0,policy:L})}if(m.pathname==="/api/telemetry/query"&&S.method==="GET"){j(!1);let L=oe();return f({ok:!0,collection:{generatedAt:L.generatedAt,cached:L.cached},...u.query(k(H))})}if(m.pathname==="/api/telemetry/tail"&&S.method==="GET"){j(!1);let L=new TextEncoder,re=new Date,x=k({...H,kinds:H.kinds||"log,request,event,trace",from:H.from||new Date(re.getTime()-120000).toISOString(),to:re.toISOString(),limit:Math.min(1000,Number(H.limit)||200),cursor:void 0}),q=S.headers.get("last-event-id")||String(H.cursor??"")||void 0,ge,Re=!1,$e=!1,Tt=new ReadableStream({start(Ze){let Gr=()=>{if(Re)return;if(Re=!0,ge)clearInterval(ge);S.signal.removeEventListener("abort",Gr);try{Ze.close()}catch{}},gu=async()=>{if(Re||$e)return;$e=!0;try{let yn=u.tail({...x,to:new Date(Date.now()+1000).toISOString()},q);for(let uu of yn.records)q=HI(uu)??q,Ze.enqueue(L.encode(`id: ${q??""}
694
+ event: record
695
+ data: ${JSON.stringify(uu)}
696
+
697
+ `));if(yn.cursor)q=yn.cursor}catch(yn){Ze.enqueue(L.encode(`event: error
698
+ data: ${JSON.stringify({message:yn instanceof Error?yn.message:String(yn)})}
699
+
700
+ `))}finally{$e=!1}};gu(),ge=setInterval(()=>{if(gu(),!Re)Ze.enqueue(L.encode(`event: heartbeat
701
+ data: ${JSON.stringify({cursor:q,at:new Date().toISOString()})}
702
+
703
+ `))},5000),ge.unref?.(),S.signal.addEventListener("abort",Gr,{once:!0})},cancel(){if(Re=!0,ge)clearInterval(ge)}});return new Response(Tt,{headers:{"cache-control":"no-cache, no-transform",connection:"keep-alive","content-type":"text/event-stream; charset=utf-8","x-accel-buffering":"no"}})}if(m.pathname==="/api/telemetry/series"&&S.method==="GET"){j(!1);let L=oe(),re=["sum","avg","min","max","count","p50","p90","p95","p99"].includes(String(H.aggregation))?H.aggregation:"avg",x=k({...H,kinds:"metric",limit:5000}),q=u.series({...x,bucketMs:Number(H.bucketMs)||60000,aggregation:re,timezone:String(H.timezone??"UTC"),compareFrom:H.compareFrom,compareTo:H.compareTo});return f({ok:!0,collection:{generatedAt:L.generatedAt,cached:L.cached},query:{aggregation:re,bucketMs:Number(H.bucketMs)||60000,timezone:String(H.timezone??"UTC")},series:q})}if(m.pathname==="/api/telemetry/refresh"&&S.method==="POST")return f({ok:!0,...await j(!0)});if(m.pathname==="/api/telemetry/export"&&S.method==="POST"){let L=await v(S);await j(!1);let re=u.query({...k(L),limit:Math.min(5000,Number(L.limit)||5000),cursor:void 0});if((L.format==="csv"?"csv":"json")==="json")return new Response(JSON.stringify({exportedAt:new Date().toISOString(),query:k(L),...re},null,2),{headers:{"content-disposition":'attachment; filename="ts-cloud-telemetry.json"',"content-type":"application/json; charset=utf-8"}});let q=["timestamp","kind","source","name","level","value","unit","message","traceId","requestId","deploymentId","releaseId","workloadId"],ge=[q.join(","),...re.records.map((Re)=>q.map(($e)=>`"${String(Re[$e]??"").replaceAll('"','""')}"`).join(","))].join(`
704
+ `);return new Response(ge,{headers:{"content-disposition":'attachment; filename="ts-cloud-telemetry.csv"',"content-type":"text/csv; charset=utf-8"}})}if(m.pathname==="/api/telemetry/saved-queries"&&S.method==="GET"){let L=te(W);return f({ok:!0,queries:u.listSavedQueries(o.project.id,L.actor?.id)})}if(m.pathname==="/api/telemetry/saved-queries"&&S.method==="POST"){let L=await v(S),re=te(W);return f({ok:!0,query:u.saveQuery(o.project.id,re.actor?.id,String(L.name??""),k(L.query??L))},201)}if(m.pathname==="/api/telemetry/saved-queries"&&S.method==="DELETE"){let L=await v(S),re=te(W),x=u.deleteSavedQuery(o.project.id,re.actor?.id,String(L.id??""));return f({ok:x},x?200:404)}}if(m.pathname.startsWith("/api/configuration")){let l=o.environments.get(V),u=W.role==="admin"||!!Ft.capabilities?.includes("secrets:read"),p=W.role==="admin"||!!Ft.capabilities?.includes("secrets:write"),I={projectId:o.project.id,environmentId:l?.id},w={"cache-control":"no-store"};if(m.pathname==="/api/configuration"&&S.method==="GET"){let D=Object.fromEntries(m.searchParams),A=D.scopeType||D.scopeId?Qi(D,I):void 0,k=["variable","secret"].includes(String(D.kind))?D.kind:void 0,H=A?.type==="preview"?xe.previews.getInstance(A.id):void 0,j=H?xe.previews.getDefinition(H.definitionId):void 0,oe=A?await bt.resolve({projectId:o.project.id,environmentId:A.environmentId,resourceId:A.resourceId,functionId:A.type==="function"?A.id:void 0,previewId:A.previewId,trustedPreview:!!H&&!H.fork,allowedPreviewSecrets:j?.inheritedSecrets,nativeReferences:!0,canReadSecretMetadata:u}):void 0,L=o.store.listResources(o.project.id);return f({ok:!0,entries:bt.list({projectId:o.project.id,scope:A,kind:k,search:D.search,canReadSecretMetadata:u}),effectiveEntries:oe?Object.values(oe.entries).filter((re)=>!k||re.kind===k).filter((re)=>!D.search||re.key.toLowerCase().includes(String(D.search).toLowerCase())):[],configurationHash:oe?.configurationHash,warnings:oe?.warnings??[],scopes:{project:o.project,environments:o.store.listEnvironments(o.project.id),resources:L.filter((re)=>re.kind!=="function"),functions:L.filter((re)=>re.kind==="function"),previews:xe.previews.listInstances({projectId:o.project.id}).filter((re)=>re.status!=="destroyed").map((re)=>({id:re.id,name:re.name,environmentId:re.baseEnvironmentId,resourceId:re.resourceId,fork:re.fork,status:re.status}))}},200,w)}if(m.pathname==="/api/configuration/export"&&S.method==="GET"){let D=Qi(Object.fromEntries(m.searchParams),I);return new Response(bt.exportVariables({projectId:o.project.id,scope:D}),{headers:{...w,"content-disposition":'attachment; filename="ts-cloud.env"',"content-type":"text/plain; charset=utf-8"}})}if(m.pathname==="/api/configuration/plan"&&S.method==="POST"){let D=await v(S),A=Qi(D,I),k=D.values&&typeof D.values==="object"&&!Array.isArray(D.values)?Object.fromEntries(Object.entries(D.values).map(([H,j])=>[H,String(j)])):{};return f({ok:!0,plan:bt.plan({projectId:o.project.id,scope:A,values:k,removeMissing:D.removeMissing===!0})},200,w)}if(m.pathname==="/api/configuration"&&S.method==="POST"){let D=await v(S),A=Qi(D,I),k=D.kind==="secret"?"secret":"variable",H=String(D.key??"");if(k==="secret"&&!p)return f({ok:!1,error:"Secret write permission is required."},403,w);try{let j=await bt.set({organizationId:o.organization.id,projectId:o.project.id,scope:A,key:H,kind:k,value:D.value==null?void 0:String(D.value),reference:D.reference==null?void 0:String(D.reference),backend:D.backend,required:D.required===!0,expectedVersion:D.expectedVersion==null?void 0:Number(D.expectedVersion),confirmed:String(D.confirm??"")===H,idempotencyKey:S.headers.get("idempotency-key")??D.idempotencyKey,actorId:te(W).actor?.id});return f({ok:!0,entry:bt.list({projectId:o.project.id,scope:A,canReadSecretMetadata:u}).find((oe)=>oe.id===j.entry.id),mutation:j.mutation,warnings:j.warnings},j.mutation.added.length?201:200,w)}catch(j){return f({ok:!1,error:j instanceof Error?j.message:String(j)},409,w)}}if(m.pathname==="/api/configuration/import"&&S.method==="POST"){let D=await v(S),A=Qi(D,I),k=Array.isArray(D.secretKeys)?D.secretKeys.map(String):[];if(k.length&&!p)return f({ok:!1,error:"Secret write permission is required."},403,w);try{let H=await bt.importDotenv({organizationId:o.organization.id,projectId:o.project.id,scope:A,source:String(D.source??""),secretKeys:k,backend:D.backend,confirmed:D.confirm==="import",idempotencyKey:S.headers.get("idempotency-key")??D.idempotencyKey,actorId:te(W).actor?.id});return f({ok:H.document.valid,diagnostics:H.document.diagnostics,mutation:H.mutation,warnings:H.warnings},H.document.valid?200:422,w)}catch(H){return f({ok:!1,error:H instanceof Error?H.message:String(H)},409,w)}}if(m.pathname==="/api/configuration/dependencies"&&S.method==="POST"){let D=await v(S),A=Vr.get(String(D.entryId??"")),k=o.store.getResource(String(D.resourceId??""));if(!A||A.projectId!==o.project.id||!k||k.projectId!==o.project.id)return f({ok:!1,error:"Configuration entry or dependent resource was not found."},404,w);return f({ok:!0,dependency:Vr.setDependency({entryId:A.id,resourceId:k.id,injectionTarget:["native_reference","file"].includes(String(D.injectionTarget))?D.injectionTarget:"environment",required:D.required!==!1,requiresRedeploy:D.requiresRedeploy!==!1,lastDeployedVersion:D.lastDeployedVersion==null?void 0:Number(D.lastDeployedVersion)})},200,w)}if(m.pathname==="/api/configuration/transfer"&&S.method==="POST"){let D=await v(S),A=Vr.get(String(D.id??"")),k=Qi({...D,scopeType:D.targetScopeType,scopeId:D.targetScopeId},I);if(!A||A.projectId!==o.project.id)return f({ok:!1,error:"Configuration entry was not found."},404,w);if(A.kind==="secret"&&!p)return f({ok:!1,error:"Secret write permission is required."},403,w);try{let H=await bt.transfer({entryId:A.id,targetScope:k,mode:D.mode==="move"?"move":"copy",confirmed:D.confirm===A.key,actorId:te(W).actor?.id,idempotencyKey:S.headers.get("idempotency-key")??D.idempotencyKey});return f({ok:!0,entry:bt.list({projectId:o.project.id,scope:k,canReadSecretMetadata:u}).find((j)=>j.id===H.entry.id),mutation:H.mutation},200,w)}catch(H){return f({ok:!1,error:H instanceof Error?H.message:String(H)},409,w)}}if(m.pathname==="/api/configuration/bulk"&&S.method==="POST"){let D=await v(S),A=Array.isArray(D.ids)?D.ids.map(String).slice(0,500):[],k=A.map((j)=>Vr.get(j)).filter((j)=>!!j&&j.projectId===o.project.id);if(k.length!==A.length)return f({ok:!1,error:"One or more configuration entries were not found."},404,w);if(k.some((j)=>j.kind==="secret")&&!p)return f({ok:!1,error:"Secret write permission is required."},403,w);if(D.action!=="delete"||D.confirm!=="bulk")return f({ok:!1,error:"Bulk deletion requires action delete and confirm bulk."},409,w);let H=[];try{for(let j of k)H.push(await bt.remove({entryId:j.id,expectedVersion:j.version,confirmed:!0,actorId:te(W).actor?.id}));return f({ok:!0,removed:H.flatMap((j)=>j.removed),affectedResourceIds:[...new Set(H.flatMap((j)=>j.affectedResourceIds))].sort()},200,w)}catch(j){return f({ok:!1,error:j instanceof Error?j.message:String(j),partial:H.flatMap((oe)=>oe.removed)},409,w)}}if(m.pathname==="/api/configuration/reveal"&&S.method==="POST"){let D=await v(S),A=He.resolveSession(S);try{return f({ok:!0,value:await bt.reveal({entryId:String(D.id??""),canRevealSecrets:u,recentlyAuthenticated:!M||!!A&&G.isRecentlyAuthenticated(A),actorId:te(W).actor?.id})},200,w)}catch(k){return f({ok:!1,error:k instanceof Error?k.message:String(k)},403,w)}}if(m.pathname==="/api/configuration"&&S.method==="DELETE"){let D=await v(S),A=Vr.get(String(D.id??""));if(A?.kind==="secret"&&!p)return f({ok:!1,error:"Secret write permission is required."},403,w);if(!A||A.projectId!==o.project.id)return f({ok:!1,error:"Configuration entry was not found."},404,w);try{return f({ok:!0,mutation:await bt.remove({entryId:A.id,expectedVersion:Number(D.expectedVersion),confirmed:String(D.confirm??"")===A.key,actorId:te(W).actor?.id})},200,w)}catch(k){return f({ok:!1,error:k instanceof Error?k.message:String(k)},409,w)}}}if(m.pathname.startsWith("/api/fleet")){let l=te(W).actor?.id,u=(p,I=409)=>f({ok:!1,error:p instanceof Error?p.message:String(p)},I,{"cache-control":"no-store"});if(m.pathname==="/api/fleet"&&S.method==="GET")return f({ok:!0,servers:Yi.list(o.project.id),resources:o.store.listResources(o.project.id),operations:be.list({projectId:o.project.id,limit:200}).filter((p)=>p.operation.kind.startsWith("fleet."))},200,{"cache-control":"no-store"});if(m.pathname==="/api/fleet"&&S.method==="POST"){let p=await v(S);try{return f({ok:!0,server:cr.enroll({organizationId:o.organization.id,projectId:o.project.id,name:String(p.name??""),provider:["aws","hetzner"].includes(String(p.provider))?p.provider:"ssh",providerId:p.providerId?String(p.providerId):void 0,region:p.region?String(p.region):void 0,zone:p.zone?String(p.zone):void 0,endpoint:String(p.endpoint??""),sshUser:String(p.sshUser??"deploy"),sshPort:p.sshPort?Number(p.sshPort):22,credentialRef:String(p.credentialRef??""),roles:Array.isArray(p.roles)?p.roles:[],labels:p.labels&&typeof p.labels==="object"?p.labels:{}})},201)}catch(I){return u(I,422)}}if(m.pathname==="/api/fleet/action"&&S.method==="POST"){let p=await v(S),I=String(p.id??""),w=String(p.action??"");try{if(w==="test")return f({ok:!0,server:await cr.test(I)});if(w==="validate")return f({ok:!0,server:await cr.validate(I)});if(w==="review_host_key")return f({ok:!0,server:cr.reviewHostKey(I,String(p.fingerprint??""))});if(w==="bootstrap")return f({ok:!0,...cr.bootstrap(I,p.confirmed===!0)},p.confirmed===!0?202:200);if(w==="heartbeat")return f({ok:!0,server:cr.heartbeat(I,{usage:p.usage&&typeof p.usage==="object"?p.usage:{}})});if(w==="drain")return f({ok:!0,server:cr.drain(I,p.completed===!0)});if(w==="uncordon")return f({ok:!0,server:cr.uncordon(I)});if(w==="archive")return f({ok:!0,server:cr.archive(I,String(p.confirmation??""))});return u("Unsupported fleet action.",422)}catch(D){return u(D)}}}if(m.pathname.startsWith("/api/capacity")){let l=(u,p=409)=>f({ok:!1,error:u instanceof Error?u.message:String(u)},p,{"cache-control":"no-store"});if(m.pathname==="/api/capacity"&&S.method==="GET")return f({ok:!0,pools:xr.listPools(o.project.id),placements:xr.listPlacements(o.project.id),servers:Yi.list(o.project.id)},200,{"cache-control":"no-store"});if(m.pathname==="/api/capacity"&&S.method==="POST"){let u=await v(S);try{return f({ok:!0,pool:xr.createPool({organizationId:o.organization.id,projectId:o.project.id,name:String(u.name??""),purpose:String(u.purpose??"application"),backend:String(u.backend??"server"),region:u.region?String(u.region):void 0,architecture:u.architecture?String(u.architecture):void 0,labels:u.labels&&typeof u.labels==="object"?u.labels:{},requiredServerLabels:u.requiredServerLabels&&typeof u.requiredServerLabels==="object"?u.requiredServerLabels:{},toleratedTaints:Array.isArray(u.toleratedTaints)?u.toleratedTaints.map(String):[],capacity:u.capacity&&typeof u.capacity==="object"?u.capacity:{},maxWorkloads:Number(u.maxWorkloads??10),costWeight:Number(u.costWeight??1),spreadKey:u.spreadKey?String(u.spreadKey):void 0,concurrency:Number(u.concurrency??1),ephemeralWorkspaces:!0,allowProductionSecrets:!1,status:"active"})},201)}catch(p){return l(p,422)}}if(m.pathname==="/api/capacity/member"&&S.method==="POST"){let u=await v(S);try{return xr.addMember(String(u.poolId??""),String(u.serverId??"")),f({ok:!0,pool:xr.getPool(String(u.poolId??""))})}catch(p){return l(p,422)}}if(m.pathname==="/api/capacity/explain"&&S.method==="POST"){let u=await v(S);try{return f({ok:!0,decisions:Zg.explain(o.project.id,{purpose:String(u.purpose??"application"),resources:u.resources&&typeof u.resources==="object"?u.resources:{},region:u.region?String(u.region):void 0,architecture:u.architecture?String(u.architecture):void 0,labels:u.labels&&typeof u.labels==="object"?u.labels:{}})})}catch(p){return l(p,422)}}if(m.pathname==="/api/capacity/action"&&S.method==="POST"){let u=await v(S);try{if(u.action==="drain")return f({ok:!0,...Zg.drainPool(String(u.poolId??""))});if(u.action==="enable")return f({ok:!0,pool:xr.updatePool(String(u.poolId??""),{status:"active"})});if(u.action==="disable")return f({ok:!0,pool:xr.updatePool(String(u.poolId??""),{status:"disabled"})});return l("Unsupported capacity action.",422)}catch(p){return l(p,422)}}}if(m.pathname.startsWith("/api/regions")){let l=(u,p=409)=>f({ok:!1,error:u instanceof Error?u.message:String(u)},p,{"cache-control":"no-store"});if(m.pathname==="/api/regions"&&S.method==="GET")return f({ok:!0,topologies:mn.list(o.project.id).map((u)=>({topology:u,targets:mn.targets(u.id),channels:mn.channels(u.id),route:mn.route(u.id),executions:mn.executions(u.id)}))},200,{"cache-control":"no-store"});if(m.pathname==="/api/regions"&&S.method==="POST"){let u=await v(S);try{return f({ok:!0,topology:Kg.create({organizationId:o.organization.id,projectId:o.project.id,environmentId:o.environments.get(V)?.id,name:String(u.name??""),hostname:String(u.hostname??""),regions:Array.isArray(u.regions)?u.regions:[],trafficPolicy:u.trafficPolicy==="weighted"||u.trafficPolicy==="latency"?u.trafficPolicy:"active_passive",dataPolicy:{replicate:Array.isArray(u.replicate)?u.replicate:["s3","dynamodb","secrets"],maxLagSeconds:Number(u.maxLagSeconds??30),retainOnDestroy:u.retainOnDestroy!==!1},dnsProvider:"route53",cdnEnabled:u.cdnEnabled===!0,wafEnabled:u.wafEnabled===!0})},201)}catch(p){return l(p,422)}}if(m.pathname==="/api/regions/action"&&S.method==="POST"){let u=await v(S);try{return f({ok:!0,...Kg.enqueue({topologyId:String(u.topologyId??""),kind:String(u.action??""),targetRegion:u.targetRegion?String(u.targetRegion):void 0,revision:u.revision?String(u.revision):void 0,manifest:u.manifest&&typeof u.manifest==="object"?u.manifest:{},confirmation:u.confirmation?String(u.confirmation):void 0,deleteData:u.deleteData===!0})},202)}catch(p){return l(p,422)}}}if(m.pathname.startsWith("/api/maintenance")){let l=(u,p=409)=>f({ok:!1,error:u instanceof Error?u.message:String(u)},p,{"cache-control":"no-store"});if(m.pathname==="/api/maintenance"&&S.method==="GET")return f({ok:!0,manifests:Er.manifests(o.organization.id),windows:Er.windows(o.project.id),campaigns:Er.campaigns(o.project.id).map((u)=>({campaign:u,targets:Er.targets(u.id)})),cleanups:Er.cleanups(o.project.id),drills:Er.drills(o.project.id)},200,{"cache-control":"no-store"});if(m.pathname==="/api/maintenance/cleanup-preview"&&S.method==="POST"){let u=await v(S);try{return f({ok:!0,plan:await od.previewCleanup({projectId:o.project.id,kind:String(u.kind??"operations"),criteria:{olderThanDays:Number(u.olderThanDays??30)}},Yg)},201)}catch(p){return l(p,422)}}if(m.pathname==="/api/maintenance/cleanup-apply"&&S.method==="POST"){let u=await v(S);try{return f({ok:!0,...od.enqueueCleanup(String(u.planId??""),String(u.confirmation??""))},202)}catch(p){return l(p,422)}}if(m.pathname==="/api/maintenance/drill"&&S.method==="POST"){let u=await v(S);try{return f({ok:!0,drill:Er.createDrill({projectId:o.project.id,scenario:String(u.scenario??"control_plane"),isolatedTarget:String(u.isolatedTarget??""),expectedRpoMinutes:Number(u.expectedRpoMinutes??60),expectedRtoMinutes:Number(u.expectedRtoMinutes??30),recoveryPointId:u.recoveryPointId?String(u.recoveryPointId):void 0,topologyId:u.topologyId?String(u.topologyId):void 0})},201)}catch(p){return l(p,422)}}if(m.pathname==="/api/maintenance/drill-run"&&S.method==="POST"){let u=await v(S);try{return f({ok:!0,...od.enqueueDrill(String(u.drillId??""))},202)}catch(p){return l(p,422)}}}if(m.pathname.startsWith("/api/volumes")){let l=o.environments.get(V),u=te(W).actor?.id,p=(I,w=409)=>f({ok:!1,error:I instanceof Error?I.message:String(I)},w,{"cache-control":"no-store"});if(m.pathname==="/api/volumes"&&S.method==="GET"){let I=ad.inventory(o.project.id,l?.id),w=o.store.listResources(o.project.id,l?.id).map((D)=>({id:D.id,name:D.name,slug:D.slug,kind:D.kind,provider:D.provider,providerId:D.providerId}));return f({ok:!0,volumes:I,resources:w,operations:be.list({projectId:o.project.id,limit:100}).filter((D)=>D.operation.kind.startsWith("volume.")),recoveryPoints:Qe.listRecoveryPoints(o.project.id).filter((D)=>D.kind==="volume"),providers:sd.map((D)=>({provider:D.provider,type:D.type,capabilities:D.capabilities()}))},200,{"cache-control":"no-store"})}if(m.pathname==="/api/volumes"&&S.method==="POST"){let I=await v(S);try{return f({ok:!0,...mr.create({organizationId:o.organization.id,projectId:o.project.id,environmentId:l?.id,resourceId:I.resourceId?String(I.resourceId):void 0,name:String(I.name??""),provider:String(I.provider??"docker"),type:I.type==="docker"?"docker":I.type,capacityBytes:I.capacityBytes==null?void 0:Number(I.capacityBytes),filesystem:I.filesystem?String(I.filesystem):void 0,encrypted:I.encrypted===!0,desiredState:I.desiredState&&typeof I.desiredState==="object"?I.desiredState:{},actorId:u})},202,{"cache-control":"no-store"})}catch(w){return p(w,422)}}if(m.pathname==="/api/volumes/attach"&&S.method==="POST"){let I=await v(S);try{return f({ok:!0,...mr.attach(String(I.volumeId??""),{resourceId:String(I.resourceId??""),targetPath:String(I.targetPath??""),readOnly:I.readOnly===!0,uid:I.uid==null?void 0:Number(I.uid),gid:I.gid==null?void 0:Number(I.gid),mode:I.mode?String(I.mode):void 0,propagation:I.propagation,driverOptions:I.driverOptions&&typeof I.driverOptions==="object"?I.driverOptions:{},actorId:u})},202)}catch(w){return p(w,422)}}if(m.pathname==="/api/volumes/detach"&&S.method==="POST"){let I=await v(S);try{return f({ok:!0,...mr.detach(String(I.volumeId??""),String(I.attachmentId??""),{force:I.force===!0,drained:I.drained===!0,unmounted:I.unmounted===!0,confirmation:I.confirmation?String(I.confirmation):void 0,actorId:u})},202)}catch(w){return p(w)}}if(m.pathname==="/api/volumes/resize"&&S.method==="POST"){let I=await v(S);try{return f({ok:!0,...mr.resize(String(I.volumeId??""),Number(I.capacityBytes),{drained:I.drained===!0,actorId:u})},202)}catch(w){return p(w,422)}}if(m.pathname==="/api/volumes/snapshot"&&S.method==="POST"){let I=await v(S);try{return f({ok:!0,...mr.snapshot(String(I.volumeId??""),{name:I.name?String(I.name):void 0,actorId:u})},202)}catch(w){return p(w,422)}}if(m.pathname==="/api/volumes/restore"&&S.method==="POST"){let I=await v(S);try{return f({ok:!0,...mr.restore(String(I.snapshotId??""),{name:String(I.name??""),actorId:u})},202)}catch(w){return p(w,422)}}if(m.pathname==="/api/volumes/discover"&&S.method==="POST")try{return f({ok:!0,volumes:await mr.discover({organizationId:o.organization.id,projectId:o.project.id,environmentId:l?.id,actorId:u})})}catch(I){return p(I,502)}if(m.pathname==="/api/volumes/adopt"&&S.method==="POST"){let I=await v(S);try{return f({ok:!0,volume:mr.adopt(String(I.volumeId??""),{name:String(I.name??""),actorId:u})})}catch(w){return p(w,422)}}if(m.pathname==="/api/volumes"&&S.method==="DELETE"){let I=await v(S),w=He.resolveSession(S);try{return f({ok:!0,...mr.delete(String(I.volumeId??""),{recentAuthAt:!M||w&&G.isRecentlyAuthenticated(w)?new Date().toISOString():void 0,confirmation:I.confirmation?String(I.confirmation):void 0,backupOverride:I.backupOverride===!0,backupOverrideConfirmation:I.backupOverrideConfirmation?String(I.backupOverrideConfirmation):void 0,actorId:u})},202)}catch(D){return p(D)}}}if(m.pathname==="/api/backups"&&S.method==="GET"){let l=o.environments.get(V),u=Qe.listPolicies(o.project.id,l?.id),p=new Set(u.map((k)=>k.id)),I=Qe.listRecoveryPoints(o.project.id).filter((k)=>!k.policyId||p.has(k.policyId)),w=Qe.listJobs(o.project.id).filter((k)=>!k.policyId||p.has(k.policyId)),D=(k)=>({...k,credentialRef:void 0,encryptionKeyRef:void 0,credentialsConfigured:!!k.credentialRef,clientEncryptionConfigured:!!k.encryptionKeyRef}),A=await Promise.all(Qe.listDestinations(o.project.id).map(async(k)=>({...D(k),credentialStatus:await $f(k,Ir)})));return f({ok:!0,destinations:A,policies:u,recoveryPoints:I,jobs:w,coverage:Qe.coverage(o.project.id).filter((k)=>p.has(k.policy.id)),resources:l?o.store.listResources(o.project.id,l.id).map((k)=>({id:k.id,name:k.name,slug:k.slug,kind:k.kind})):[]})}if(m.pathname==="/api/backups/destinations"&&S.method==="POST"){let l=await v(S),u=String(l.name??"").trim(),p=String(l.provider??""),I=String(l.encryption??"provider"),w=`secret://data-services/backups/${o.project.id}/${u}`,D=[];if(!["aws_s3","s3_compatible","aws_backup"].includes(p))return f({ok:!1,error:"A supported backup destination provider is required."},422);if(!["provider","client_side","both"].includes(I))return f({ok:!1,error:"Encryption must be provider, client_side, or both."},422);try{let A,k;if(l.credentials&&typeof l.credentials==="object"&&!Array.isArray(l.credentials))A=`${w}/credentials`,await Ir.put(A,JSON.stringify(l.credentials)),D.push(A);if(I!=="provider"){let j=String(l.encryptionKey??"");if(j.length<32)throw Error("Client-side encryption keys must contain at least 32 characters.");k=`${w}/encryption-key`,await Ir.put(k,j),D.push(k)}let H=Qe.createDestination({organizationId:o.organization.id,projectId:o.project.id,name:u,provider:p,endpoint:l.endpoint?String(l.endpoint):void 0,endpointPolicy:l.endpointPolicy==="allow_private"?"allow_private":"public_https",bucket:l.bucket?String(l.bucket):void 0,prefix:String(l.prefix??""),region:l.region?String(l.region):Lr,forcePathStyle:l.forcePathStyle===!0,credentialRef:A,encryption:I,encryptionKeyRef:k,immutability:l.immutability&&typeof l.immutability==="object"&&!Array.isArray(l.immutability)?l.immutability:{},status:"untested"});return f({ok:!0,destination:{...H,credentialRef:void 0,encryptionKeyRef:void 0,credentialsConfigured:!!A,clientEncryptionConfigured:!!k}},201)}catch(A){for(let k of D)await Ir.remove(k).catch(()=>{});return f({ok:!1,error:A instanceof Error?A.message:String(A)},422)}}if(m.pathname==="/api/backups/destinations/test"&&S.method==="POST"){let l=await v(S),u=Qe.getDestination(String(l.id??""));if(!u||u.projectId!==o.project.id)return f({ok:!1,error:"Backup destination was not found."},404);if(u.provider==="aws_backup")return f({ok:!1,error:"AWS Backup destinations are verified by creating a provider recovery point."},422);try{return await Gg.test(u),f({ok:!0,destination:Qe.recordDestinationTest(u.id,{ok:!0})})}catch(p){let I=p instanceof Error?p.message:String(p);return Qe.recordDestinationTest(u.id,{ok:!1,error:I}),f({ok:!1,error:I},502)}}if(m.pathname==="/api/backups/policies"&&S.method==="POST"){let l=await v(S),u=o.environments.get(V),p=Qe.getDestination(String(l.destinationId??"")),I=String(l.resourceKind??""),w=l.dataServiceId?String(l.dataServiceId):void 0,D=w?We.get(w):void 0,A=l.resourceId?String(l.resourceId):void 0,k=A?o.store.getResource(A):void 0;if(!u)return f({ok:!1,error:"Environment was not found."},404);if(!p||p.projectId!==o.project.id)return f({ok:!1,error:"Backup destination was not found."},404);if(!["managed_database","logical_database","volume","files","control_plane","infrastructure"].includes(I))return f({ok:!1,error:"A supported backup resource kind is required."},422);if(w&&(!D||D.projectId!==o.project.id||D.environmentId!==u.id))return f({ok:!1,error:"Data service was not found in this environment."},404);if(A&&(!k||k.projectId!==o.project.id||k.environmentId!==u.id))return f({ok:!1,error:"Resource was not found in this environment."},404);if(I==="managed_database"&&!D)return f({ok:!1,error:"Managed database policies require a data service."},422);if(I==="logical_database"&&(!D||!["container","server"].includes(D.provider)))return f({ok:!1,error:"Logical database policies require an on-box data service."},422);if(I==="volume"&&(!k||!/^[A-Za-z0-9][A-Za-z0-9_.-]{1,127}$/.test(String(l.volumeName??""))))return f({ok:!1,error:"Volume policies require a scoped resource and valid volumeName."},422);let H=Array.isArray(l.includePatterns)?l.includePatterns.map(String).filter(Boolean):[];if(I==="files"&&(!k||!H.length))return f({ok:!1,error:"File policies require a scoped resource and at least one project-relative include path."},422);if(I==="control_plane"&&p.encryption==="provider")return f({ok:!1,error:"Control-plane policies require a destination with client-side encryption."},422);if(I==="infrastructure"&&(p.provider!=="aws_backup"||!H.some((j)=>j.startsWith("resource:arn:"))||!H.some((j)=>j.startsWith("role:arn:"))))return f({ok:!1,error:"Infrastructure policies require an AWS Backup destination plus resource:<arn> and role:<arn> include values."},422);try{let j=Qe.createPolicy({organizationId:o.organization.id,projectId:o.project.id,environmentId:u.id,resourceId:A,dataServiceId:w,destinationId:p.id,name:String(l.name??"").trim(),resourceKind:I,schedule:String(l.schedule??"daily"),timezone:String(l.timezone??"UTC"),retention:l.retention&&typeof l.retention==="object"&&!Array.isArray(l.retention)?l.retention:{keepLast:7,expireAfterDays:30},compression:["none","gzip","zstd"].includes(String(l.compression))?l.compression:"gzip",encryption:["destination","client_side","both"].includes(String(l.encryption))?l.encryption:"destination",includePatterns:I==="volume"?[String(l.volumeName),...H]:H,excludePatterns:Array.isArray(l.excludePatterns)?l.excludePatterns.map(String):[],expectedRpoMinutes:Math.max(1,Number(l.expectedRpoMinutes)||1440),expectedRtoMinutes:Math.max(1,Number(l.expectedRtoMinutes)||120),healthCheckId:l.healthCheckId?String(l.healthCheckId):void 0,enabled:l.enabled!==!1});return f({ok:!0,policy:j},201)}catch(j){return f({ok:!1,error:j instanceof Error?j.message:String(j)},422)}}if(m.pathname==="/api/backups/run"&&S.method==="POST"){let l=await v(S),u=Qe.getPolicy(String(l.policyId??"")),p=o.environments.get(V);if(!u||u.projectId!==o.project.id||u.environmentId!==p?.id)return f({ok:!1,error:"Backup policy was not found in this environment."},404);try{let I=In.enqueueBackup(u,new Date().toISOString(),te(W).actor?.id);return f({ok:!0,job:I},202)}catch(I){return f({ok:!1,error:I instanceof Error?I.message:String(I)},409)}}if(m.pathname==="/api/backups/verify"&&S.method==="POST"){let l=await v(S),u=Qe.getRecoveryPoint(String(l.recoveryPointId??""));if(!u||u.projectId!==o.project.id)return f({ok:!1,error:"Recovery point was not found."},404);return f({ok:!0,job:In.enqueueVerification(u)},202)}if(m.pathname==="/api/backups/restore"&&S.method==="POST"){let l=await v(S),u=Qe.getRecoveryPoint(String(l.recoveryPointId??"")),p=l.mode==="in_place"?"in_place":"isolated",I=l.target&&typeof l.target==="object"&&!Array.isArray(l.target)?{...l.target,inPlace:p==="in_place"}:{inPlace:p==="in_place"},w=He.resolveSession(S),D={mode:p,target:I,targetName:String(l.targetName??""),confirm:l.confirm?String(l.confirm):void 0,recentAuth:!M||!!w&&G.isRecentlyAuthenticated(w),downtimeAcknowledged:l.downtimeAcknowledged===!0,safetyBackupId:l.safetyBackupId?String(l.safetyBackupId):void 0};if(!u||u.projectId!==o.project.id)return f({ok:!1,error:"Recovery point was not found."},404);if(l.drill===!0&&p!=="isolated")return f({ok:!1,error:"Recovery drills must use an isolated target."},422);try{let A=In.planRestore(u,D);if(l.execute!==!0)return f({ok:!0,plan:A,executionCreated:!1});let k=In.enqueueRestore(u,{...D,drill:l.drill===!0,actorId:te(W).actor?.id});return f({ok:!0,plan:A,job:k},202)}catch(A){return f({ok:!1,error:A instanceof Error?A.message:String(A)},409)}}if(m.pathname==="/api/backups/recovery-points"&&S.method==="POST"){let l=await v(S),u=Qe.getRecoveryPoint(String(l.id??""));if(!u||u.projectId!==o.project.id)return f({ok:!1,error:"Recovery point was not found."},404);if(l.held==null&&l.pinned==null)return f({ok:!1,error:"held or pinned must be provided."},422);return f({ok:!0,recoveryPoint:Qe.updateRecoveryPoint(u.id,{held:l.held==null?u.held:l.held===!0,pinned:l.pinned==null?u.pinned:l.pinned===!0})})}if(m.pathname==="/api/backups/retention"&&S.method==="POST")return f({ok:!0,jobs:In.enqueueRetention()},202);if(m.pathname==="/api/data-services/capabilities"&&S.method==="GET"){let l=String(m.searchParams.get("engine")??""),u=String(m.searchParams.get("provider")??"");if(!["postgres","mysql","mariadb","redis","mongodb","libsql"].includes(l)||!["aws_rds","aws_aurora","aws_elasticache","server","container","external"].includes(u))return f({ok:!1,error:"A supported engine and provider are required."},422);return f({ok:!0,engine:l,provider:u,capabilities:_a(l,u)})}if(m.pathname==="/api/data-services"&&S.method==="GET"){let l=o.environments.get(V),u=We.list(o.project.id,l?.id).map((p)=>{let I=We.credential(p.id);return{...p,credentialRef:void 0,credential:I?{configured:!0,username:I.username,version:I.version,rotatedAt:I.rotatedAt}:void 0,dependencies:We.dependencies(p.id).map((w)=>({resourceId:w.resourceId,requiresRedeploy:w.requiresRedeploy}))}});return f({ok:!0,services:u})}if(m.pathname==="/api/data-services/preview"&&S.method==="POST"){let l=await v(S);if(l.id){let I=We.get(String(l.id)),w=o.environments.get(V),D=String(l.action??"");if(!I||I.projectId!==o.project.id||I.environmentId!==w?.id)return f({ok:!1,error:"Data service was not found in this environment."},404);if(!td.includes(D))return f({ok:!1,error:`Action must be one of: ${td.join(", ")}.`},422);try{return f({ok:!0,plan:Va.plan(I,D,l.changes??{})})}catch(A){return f({ok:!1,error:A instanceof Error?A.message:String(A)},422)}}let u=String(l.engine??""),p=String(l.provider??"");if(!["postgres","mysql","mariadb","redis","mongodb","libsql"].includes(u)||!["aws_rds","aws_aurora","aws_elasticache","server","container","external"].includes(p))return f({ok:!1,error:"A supported engine and provider are required."},422);return f({ok:!0,capabilities:_a(u,p),defaults:{publicExposure:!1,backupRetentionDays:7,deletionProtection:!0},productionExecutionCreated:!1})}if(m.pathname==="/api/data-services"&&S.method==="POST"){let l=await v(S),u=String(l.engine??""),p=String(l.provider??""),I=o.environments.get(V),w=te(W);if(!I)return f({ok:!1,error:"Environment was not found."},404);if(!["postgres","mysql","mariadb","redis","mongodb","libsql"].includes(u)||!["aws_rds","aws_aurora","aws_elasticache","server","container","external"].includes(p))return f({ok:!1,error:"A supported engine and provider are required."},422);let D={organizationId:o.organization.id,projectId:o.project.id,environmentId:I.id,resourceId:l.resourceId?String(l.resourceId):void 0,name:String(l.name??"").trim(),engine:u,provider:p,placement:String(l.placement??l.name??"").trim(),engineVersion:l.engineVersion?String(l.engineVersion):void 0,plan:String(l.plan??(p==="aws_elasticache"?"cache.t4g.micro":p==="aws_aurora"?"db.serverless":"db.t4g.micro")),storageGb:l.storageGb==null?void 0:Number(l.storageGb),highAvailability:l.highAvailability===!0,publicExposure:l.publicExposure===!0,allowedCidrs:Array.isArray(l.allowedCidrs)?l.allowedCidrs.map(String):[],desiredState:l.desiredState&&typeof l.desiredState==="object"&&!Array.isArray(l.desiredState)?l.desiredState:{},observedState:{},origin:l.adopt===!0?"adopted":"managed",managementEnabled:l.adopt!==!0,ownerActorId:w.actor?.id,username:l.username?String(l.username):void 0};try{if(l.adopt===!0){let k=We.create({...D,status:"adopted",credentialRef:void 0});return f({ok:!0,service:k,readOnly:!0},201)}if(!Qg({provider:p,engine:u}))return f({ok:!1,error:`No ${p}/${u} provisioning adapter is configured; adopt it read-only or choose a supported provider.`},422);let A=await Va.create(D);return f({ok:!0,service:A.service,operationId:A.operationId,oneTimeCredential:A.credential},201)}catch(A){return f({ok:!1,error:A instanceof Error?A.message:String(A)},422)}}if(m.pathname==="/api/data-services/connections"&&S.method==="GET"){let l=We.get(String(m.searchParams.get("id")??"")),u=o.environments.get(V);if(!l||l.projectId!==o.project.id||l.environmentId!==u?.id)return f({ok:!1,error:"Data service was not found in this environment."},404);let p=typeof l.observedState.endpoint==="string"?l.observedState.endpoint:void 0,I=typeof l.observedState.readerEndpoint==="string"?l.observedState.readerEndpoint:void 0,w=Number(l.observedState.port)||(l.engine==="postgres"?5432:l.engine==="redis"?6379:l.engine==="mongodb"?27017:l.engine==="libsql"?8080:3306),D=typeof l.observedState.database==="string"?l.observedState.database:void 0,A=typeof l.observedState.tls==="boolean"?l.observedState.tls:l.provider.startsWith("aws_"),k=[...p?[{type:l.publicExposure?"external":"internal",host:p,port:w,database:D,tls:A}]:[],...I?[{type:"internal",host:I,port:w,database:D,tls:A}]:[],{type:"tunnel",host:p??l.placement,port:w,database:D,tls:A}];return f({ok:!0,serviceId:l.id,guidance:vf(l,k)})}if(m.pathname==="/api/data-services/action"&&S.method==="POST"){let l=await v(S),u=We.get(String(l.id??"")),p=o.environments.get(V),I=String(l.action??"");if(!u||u.projectId!==o.project.id||u.environmentId!==p?.id)return f({ok:!1,error:"Data service was not found in this environment."},404);if(!td.includes(I))return f({ok:!1,error:`Action must be one of: ${td.join(", ")}.`},422);let w=l.changes&&typeof l.changes==="object"&&!Array.isArray(l.changes)?l.changes:{};try{let D=Va.plan(u,I,w);if(l.execute!==!0)return f({ok:!0,plan:D,productionExecutionCreated:!1});let A=Va.enqueue(u,I,w,te(W).actor?.id);return f({ok:!0,plan:D,operationId:A},202)}catch(D){return f({ok:!1,error:D instanceof Error?D.message:String(D)},409)}}if(m.pathname==="/api/data-services/dependencies"&&S.method==="POST"){let l=await v(S),u=We.get(String(l.id??"")),p=o.environments.get(V),I=o.store.getResource(String(l.resourceId??""));if(!u||u.projectId!==o.project.id||u.environmentId!==p?.id)return f({ok:!1,error:"Data service was not found in this environment."},404);if(!I||I.projectId!==o.project.id||I.environmentId!==p?.id)return f({ok:!1,error:"Dependent resource was not found in this environment."},404);if(l.remove===!0)return f({ok:We.removeDependency(u.id,I.id)});return We.addDependency({serviceId:u.id,resourceId:I.id,secretRef:u.credentialRef??`secret://data-services/${u.projectId}/${u.name}`,requiresRedeploy:l.requiresRedeploy!==!1}),f({ok:!0,dependencies:We.dependencies(u.id).map((w)=>({resourceId:w.resourceId,requiresRedeploy:w.requiresRedeploy}))})}if(m.pathname==="/api/data-services/management"&&S.method==="POST"){let l=await v(S),u=We.get(String(l.id??"")),p=o.environments.get(V);if(!u||u.projectId!==o.project.id||u.environmentId!==p?.id)return f({ok:!1,error:"Data service was not found in this environment."},404);if(u.origin!=="adopted"||l.reviewed!==!0||l.confirm!==u.name)return f({ok:!1,error:`Enabling management requires reviewed=true and typing ${u.name}.`},409);return f({ok:!0,service:We.update(u.id,u.version,{managementEnabled:!0})})}if(m.pathname==="/api/data-services/reveal"&&S.method==="POST"){let l=await v(S),u=We.get(String(l.id??"")),p=o.environments.get(V),I=u?We.credential(u.id):void 0;if(!u||u.projectId!==o.project.id||u.environmentId!==p?.id)return f({ok:!1,error:"Data service was not found in this environment."},404);if(!I)return f({ok:!1,error:"No managed credential is configured."},404);return f({ok:!0,credential:{username:I.username,password:await Ir.resolve(I.secretRef),version:I.version}},200,{"cache-control":"no-store"})}if(m.pathname==="/api/databases"&&S.method==="GET")return f(await zR(a,V));if(m.pathname==="/api/databases"&&S.method==="POST"){let l=await v(S),u=String(l.name??"").trim();if(!Nr(u))return f({ok:!1,error:"Database name must be a valid identifier (letters, numbers, underscore; not starting with a digit)."},422);return f({...await WR(a,V,u),name:u})}if(m.pathname==="/api/databases/vitess"&&S.method==="GET"){let l=await NR(a,V);return f({...l,unhealthy:FR(l.tablets),missingPrimary:VR(l)})}if(m.pathname==="/api/databases/vitess/provision"&&S.method==="POST"){let l=await v(S);try{return f(await ep(a,V,{keyspace:String(l.keyspace??""),username:String(l.username??""),password:String(l.password??""),sharded:l.sharded===!0,confirm:String(l.confirm??"")}))}catch(u){return f({ok:!1,error:u instanceof Error?u.message:String(u)},422)}}if(m.pathname==="/api/databases/vitess/migrations"&&S.method==="GET"){let l=m.searchParams.get("keyspace")??void 0;return f(await KR(a,V,l))}if(m.pathname==="/api/databases/vitess/migrations/action"&&S.method==="POST"){let l=await v(S),u=String(l.uuid??"").trim(),p=String(l.action??"");if(!["retry","cancel","cleanup","complete"].includes(p))return f({ok:!1,error:"Unknown migration action."},422);return f(await YR(a,V,u,p))}if(m.pathname==="/api/databases/vitess/keyspaces"&&S.method==="POST"){let l=await v(S),u=String(l.name??"").trim(),p=l.sharded===!0;return f(await QR(a,V,u,{sharded:p}))}if(m.pathname==="/api/databases/vitess/vschema"&&S.method==="POST"){let l=await v(S),u=String(l.keyspace??"").trim(),p=typeof l.vschema==="string"?l.vschema:JSON.stringify(l.vschema??null);return f(await GR(a,V,u,p))}if(m.pathname==="/api/databases/vitess/schema"&&S.method==="POST"){let l=await v(S),u=String(l.sql??"");return f(await ZR(a,V,u))}if(m.pathname==="/api/databases/vitess/install-client"&&S.method==="POST")return f(await MR(a,V));if(m.pathname==="/api/databases/backups"&&S.method==="GET")return f(await HR(a,V));if(m.pathname==="/api/databases/backup"&&S.method==="POST"){let l=await v(S),u=String(l.database??"").trim();if(!Nr(u))return f({ok:!1,error:"Database name must be a valid identifier."},422);if(l.confirm!==u)return f({ok:!1,error:`Type "${u}" to back up this database.`},409);return f(await UR(a,V,u))}if(m.pathname==="/api/databases/users"&&S.method==="POST"){let l=await v(S),u=String(l.username??"").trim(),p=String(l.password??""),I=String(l.database??"").trim()||void 0,w=l.access==="readonly"?"readonly":"all";if(!Nr(u))return f({ok:!1,error:"Username must be a valid identifier."},422);if(!p)return f({ok:!1,error:"Password is required."},422);if(I&&!Nr(I))return f({ok:!1,error:"Database must be a valid identifier."},422);return f({...await jR(a,V,{username:u,password:p,database:I,access:w}),username:u})}if(m.pathname==="/api/dashboard-data")return je=E.get(V)??await N(V),N(V),f(Cg(je,{user:Ft,slug:a.project.slug}));if(m.pathname==="/api/users"&&S.method==="GET")return f({ok:!0,users:kt(t).map(xi)});if(m.pathname==="/api/users"&&S.method==="POST"){let l=await v(S),u=String(l.username??"").trim();if(!Lo(u))return f({ok:!1,error:"Username must be 2-32 characters: letters, numbers, dot, dash or underscore."},422);let p=l.sites&&typeof l.sites==="object"?l.sites:{},I=new Set(Object.keys(a.sites??{})),w={};for(let[k,H]of Object.entries(p)){if(!I.has(k))return f({ok:!1,error:`Site '${k}' was not found.`},404);if(H!=="owner"&&H!=="collaborator")return f({ok:!1,error:`Unknown site role '${H}'. Use 'owner' or 'collaborator'.`},422);w[k]=H}let D=typeof l.password==="string"&&l.password.trim()?l.password.trim():void 0;if(D&&D.length<12)return f({ok:!1,error:"Password must be at least 12 characters."},422);let A=Ba(t,{username:u,password:D,name:typeof l.name==="string"?l.name:void 0,sites:w});return Ka(o,kt(t)),de(),f({ok:!0,user:xi(A.user),password:A.password})}if(m.pathname==="/api/users"&&S.method==="DELETE"){let l=await v(S),u=String(l.username??"").trim();if(u.toLowerCase()===W.username.toLowerCase())return f({ok:!1,error:"You cannot remove your own account."},409);let p=Zt(kt(t),u),I=p?o.store.getActorByExternalId("user",`dashboard:${p.username.toLowerCase()}`):void 0,w=I?o.store.getMembershipForActor(o.organization.id,I.id):void 0;if(w&&w.source!=="legacy")return f({ok:!1,error:"Organization members must be removed from Organization access."},409);let D=Ag(t,u);if(!D.ok)return f(D,409);return Ka(o,kt(t)),O.clear(),f({ok:!0,username:u})}if(m.pathname==="/api/actions/run"&&S.method==="POST"){let l=await S.json().catch(()=>({})),u=l.action?MI(l.action,V):void 0;if(!u)return f({ok:!1,error:"Unknown dashboard action."},404);if(u.mutates&&l.confirm!==u.confirm)return f({ok:!1,error:`Type "${u.confirm}" to run this action.`},409);let p=await yr({controlPlane:o,environment:V,actor:W,kind:`dashboard.action.${u.id}`,input:{action:u.id},execute:()=>Fg(u,{cwd:t,cliEntry:i})});return f({...p.result,controlPlaneOperation:p.operation})}if(m.pathname==="/api/server/operations/run"&&S.method==="POST"){let l=await S.json().catch(()=>({})),u=l.operation?$g(l.operation,a,je):void 0;if(!u)return f({ok:!1,error:"Unknown or unavailable server operation."},404);if(u.mutates&&l.confirm!==u.confirm)return f({ok:!1,error:`Type "${u.confirm}" to run this operation.`},409);let p=sr(o,String(V));await new Gn(he).run(new ba,{...p,artifactRoot:t});let I=Jo(he,{scope:p,desiredConfigHash:o.project.desiredConfigHash});if(I.decision.outcome==="block")return f({ok:!1,error:`Operation blocked by security policy: ${I.decision.explanation}`,securityReview:I},409);let w=await yr({controlPlane:o,environment:V,actor:W,kind:`dashboard.server.${u.id}`,resourceSlug:u.target,input:{operation:u.id,target:u.target,to:l.to??null},execute:()=>Zo(a,V,u,{to:l.to})});return f({...w.result,controlPlaneOperation:w.operation,securityReview:I})}if(m.pathname==="/api/server/command"&&S.method==="POST"){let l=await S.json().catch(()=>({}));if(l.confirm!=="run")return f({ok:!1,error:'Type "run" to execute this command on the server.'},409);let u=await yr({controlPlane:o,environment:V,actor:W,kind:"dashboard.server.command",input:{source:"interactive-command"},execute:()=>Ta(a,V,String(l.command??""))});return f({...u.result,controlPlaneOperation:u.operation})}if(m.pathname==="/api/serverless/operations")return f(Bg(a,V,je));if(m.pathname==="/api/serverless/operations/run"&&S.method==="POST"){let l=await S.json().catch(()=>({})),u=l.operation?Wp(l.operation,a,V,je):void 0;if(!u)return f({ok:!1,error:"Unknown or unavailable serverless operation."},404);if(u.mutates&&l.confirm!==u.confirm)return f({ok:!1,error:`Type "${u.confirm}" to run this operation.`},409);let p=await yr({controlPlane:o,environment:V,actor:W,kind:`dashboard.serverless.${u.id}`,input:{operation:u.id,min:l.min??null,max:l.max??null},execute:()=>jp(a,V,u,{min:l.min,max:l.max})});return je=await qn(a,V),E.set(V,je),f({...p.result,controlPlaneOperation:p.operation})}if(m.pathname==="/api/serverless/command"&&S.method==="POST"){let l=await S.json().catch(()=>({}));if(l.confirm!=="run")return f({ok:!1,error:'Type "run" to execute this command.'},409);return f(await Up(a,V,String(l.command??"")))}if(m.pathname==="/api/serverless/dlq"&&S.method==="GET"){let l=Number(m.searchParams.get("max"))||10;return f(await Hp(a,V,l))}if(m.pathname==="/api/serverless/dlq/redrive"&&S.method==="POST"){let l=await S.json().catch(()=>({}));if(l.confirm!=="redrive")return f({ok:!1,error:'Type "redrive" to move messages back onto a source queue.'},409);return f(await Np(a,V,{max:l.max,targetQueue:l.targetQueue}))}if(m.pathname==="/api/serverless/dlq/purge"&&S.method==="POST"){if((await S.json().catch(()=>({}))).confirm!=="purge")return f({ok:!1,error:'Type "purge" to permanently discard every DLQ message.'},409);return f(await Fp(a,V))}if(m.pathname==="/api/serverless/secrets"&&S.method==="GET")return f({secrets:Vp(a,V)});if(m.pathname==="/api/serverless/secrets"&&S.method==="POST"){let l=await S.json().catch(()=>({})),u=String(l.secretId??"").trim();if(!u)return f({ok:!1,error:"A secret id is required."},422);if(typeof l.value!=="string"||l.value==="")return f({ok:!1,error:"A non-empty value is required."},422);return f(await Lp(a,V,u,l.value))}if(m.pathname==="/api/serverless/secrets"&&S.method==="DELETE"){let l=await S.json().catch(()=>({})),u=String(l.secretId??"").trim();if(!u)return f({ok:!1,error:"A secret id is required."},422);if(l.confirm!==u)return f({ok:!1,error:`Type "${u}" to delete this secret.`},409);return f(await xp(a,V,u))}if(m.pathname==="/api/serverless/functions/config"&&S.method==="POST"){let l=await S.json().catch(()=>({})),u=String(l.mode??"").trim();if(l.confirm!==u)return f({ok:!1,error:`Type "${u}" to update this function.`},409);return f(await Mp(a,V,u,{memory:l.memory,timeout:l.timeout}))}if(m.pathname==="/api/serverless/alarms"&&S.method==="GET")return f(await Qp(a,V));if(m.pathname==="/api/serverless/alarms"&&S.method==="POST"){let l=await S.json().catch(()=>({})),u=String(l.preset??"").trim(),p=Number(l.threshold);if(!u)return f({ok:!1,error:"An alarm metric is required."},422);if(!Number.isFinite(p))return f({ok:!1,error:"A numeric threshold is required."},422);return f(await Gp(a,V,u,p))}if(m.pathname==="/api/serverless/alarms"&&S.method==="DELETE"){let l=await S.json().catch(()=>({})),u=String(l.name??"").trim();if(!u)return f({ok:!1,error:"An alarm name is required."},422);if(l.confirm!==u)return f({ok:!1,error:`Type "${u}" to delete this alarm.`},409);return f(await Zp(a,V,u))}if(m.pathname==="/api/serverless/traces"&&S.method==="GET"){let l=Number(m.searchParams.get("minutes"))||30;return f(await Yo(a,V,l))}if(m.pathname==="/api/serverless/scheduler"&&S.method==="POST"){let l=await S.json().catch(()=>({})),u=String(l.action??"").trim();if(u!=="enable"&&u!=="disable"&&u!=="run")return f({ok:!1,error:"Unknown scheduler action."},422);if(l.confirm!==u)return f({ok:!1,error:`Type "${u}" to ${u} the scheduler.`},409);return f(await zg(a,V,u))}if(!yI(m.pathname,Ft))return new Response(null,{status:302,headers:{location:`/access-denied?env=${encodeURIComponent(V)}`}});let ai=await ze(W,V);if(!ai)return nd("ts-cloud dashboard UI is unavailable.",503);return wI(ai,m.pathname)}catch(En){if(e.verbose)console.error(En);return f({ok:!1,error:En?.message??String(En)},500)}})();if(!Me)return Me;if(ye&&(m.pathname.startsWith("/api/")||m.pathname.startsWith("/auth/"))){let le;if((Y.headers.get("content-type")||"").includes("application/json"))le=await Y.json().catch(()=>{return});let st=He.resolveUser(S),et=st?te(st).actor:void 0;o.store.appendEvent({organizationId:o.organization.id,projectId:o.project.id,actorId:et?.id,correlationId:se,type:Me.status<400?"dashboard.mutation.succeeded":"dashboard.mutation.failed",level:Me.status<400?"info":"warning",payload:lC(S.method,m.pathname,le,Me.status,Date.now()-ee)})}return Me.headers.set("x-request-id",se),Me}});La?.start();let nm=e.spendLoop??!0,lu;if(nm)(async()=>{let{SpendRunner:S,SpendLoopLease:X,startSpendLoop:ee}=await import("./spend/index.js"),{store:Y}=await PI(o.store),se=new S({controlPlane:o.store,store:Y,alerts:ce});lu=ee(se,{lease:new X(o.store,{owner:`dashboard:${process.pid}`}),onError:(ye)=>console.error(`[ts-cloud] spend cycle failed: ${ye instanceof Error?ye.message:String(ye)}`)})})();let im=ni.stop.bind(ni);return ni.stop=(S)=>{clearInterval(su),clearInterval(ou),clearInterval(du),clearInterval(au),clearInterval(iu),clearInterval(eu),clearInterval(tu),clearInterval(ru),clearInterval(nu),de(),Ge.clear(),La?.stop(),lu?.();let X=im(S);if(La)La.settled().finally(()=>o.store.close());else o.store.close();return X},{server:ni,url:`http://${r}:${ni.port}/`}}export{Al as a,CP as b,__ as c,$J as d,_s as e,Gh as f,Ld as g,ty as h,ry as i,ga as j,xd as k,ef as l,rn as m,tf as n,rf as o,nf as p,ps as q,ha as r,py as s,nn as t,cf as u,Xd as v,qd as w,ec as x,uf as y,hf as z,ff as A,Es as B,Id as C,th as D,sa as E,os as F,Cd as G,vn as H,$E as I,mh as J,Eh as K,CE as L,yh as M,Td as N,Si as O,vh as P,Oh as Q,Bh as R,Jh as S,en as T,NE as U,jh as V,Ri as W,Wd as X,jd as Y,Ud as Z,ls as _,gs as $,la as aa,Vh as ba,us as ca,Hd as da,Fd as ea,Ca as fa,lR as ga,ka as ha,JD as ia,TD as ja,Gn as ka,ba as la,ig as ma,jD as na,uR as oa,hR as pa,ag as qa,fR as ra,SR as sa,_R as ta,Nz as ua,sr as va,RR as wa,Lz as xa,xz as ya,Bo as za,Jo as Aa,Zz as Ba,Sr as Ca,eD as Da,Mn as Ea,jr as Fa,Wr as Ga,Qn as Ha,Z_ as Ia,K_ as Ja,Y_ as Ka,X_ as La,nD as Ma,sD as Na,Zl as Oa,oD as Pa,dD as Qa,Kl as Ra,eR as Sa,tR as Ta,uD as Ua,ir as Va,pD as Wa,nR as Xa,_r as Ya,Xl as Za,an as _a,zn as $a,Wn as ab,Sa as bb,ws as cb,If as db,oO as eb,zy as fb,Wy as gb,jy as hb,Uy as ib,ic as jb,ac as kb,mf as lb,oc as mb,_a as nb,Sc as ob,vf as pb,Os as qb,Of as rb,_c as sb,Rc as tb,pc as ub,Ic as vb,mc as wb,yc as xb,wc as yb,Ac as zb,Bf as Ab,yi as Bb,Pc as Cb,D_ as Db,Pa as Eb,$_ as Fb,Bl as Gb,Jl as Hb,L_ as Ib,Wi as Jb,Nl as Kb,Fl as Lb,ZP as Mb,ET as Nb,$o as Ob,wT as Pb,AT as Qb,PT as Rb,Ml as Sb,Ql as Tb,G_ as Ub,qP as Vb,Gl as Wb,Da as Xb,v_ as Yb,Po as Zb,O_ as _b,B_ as $b,J_ as ac,Wl as bc,FP as cc,jl as dc,H_ as ec,VP as fc,Hl as gc,LP as hc,Ke as ic,_u as jc,Ka as kc,yr as lc,Ru as mc,pu as nc,TC as oc,NC as pc,Rm as qc,ZC as rc,KC as sc,YC as tc,wm as uc,Am as vc,ik as wc,ak as xc,jm as yc,Um as zc,fk as Ac,xu as Bc,qa as Cc,Zm as Dc,fd as Ec,Sd as Fc,ns as Gc,li as Hc,$n as Ic,is as Jc,rE as Kc,na as Lc,qu as Mc,eh as Nc,pd as Oc,Fy as Pc,gc as Qc,xy as Rc,My as Sc,$f as Tc,hc as Uc,ks as Vc,Cf as Wc,fc as Xc,Nn as Yc,Cr as Zc,zf as _c,Cc as $c,kc as ad,Wf as bd,vc as cd,Bc as dd,Tc as ed,$l as fd,m_ as gd,E_ as hd,Aa as id,Cl as jd,kl as kd,bl as ld,vl as md,A_ as nd,xI as od,xg as pd,MI as qd,bC as rd};