@stacksjs/ts-cloud 0.9.4 → 0.11.0
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.
- package/dist/aws/index.js +1 -1
- package/dist/bin/chunk-0djsffn6.js +1 -0
- package/dist/bin/chunk-0t3sev1j.js +1 -0
- package/dist/bin/chunk-0y89hs67.js +6 -0
- package/dist/bin/chunk-21gggxvf.js +2 -0
- package/dist/bin/chunk-26cj89s6.js +1 -0
- package/dist/bin/chunk-35xstvnq.js +1 -0
- package/dist/bin/chunk-41yqpdv7.js +2 -0
- package/dist/bin/chunk-4a85nk2q.js +92 -0
- package/dist/bin/{chunk-rxcvf10f.js → chunk-4a97kbk1.js} +129 -129
- package/dist/bin/chunk-4kbhbfq8.js +34 -0
- package/dist/bin/chunk-4vdv41nh.js +70 -0
- package/dist/bin/chunk-67jsyn0g.js +111 -0
- package/dist/bin/chunk-6tct7e89.js +1 -0
- package/dist/bin/chunk-6vjrts39.js +1 -0
- package/dist/bin/chunk-7v5ff3vc.js +1 -0
- package/dist/bin/chunk-80nra92y.js +1 -0
- package/dist/bin/chunk-9mydnqr6.js +2 -0
- package/dist/bin/chunk-9rsn48qg.js +3 -0
- package/dist/bin/chunk-a2t1e5yb.js +1 -0
- package/dist/bin/chunk-akbfefwq.js +1 -0
- package/dist/bin/chunk-b704nznp.js +1 -0
- package/dist/bin/chunk-c1j9v7ee.js +2 -0
- package/dist/bin/chunk-cjz36ths.js +1 -0
- package/dist/bin/chunk-cxd5cevb.js +2 -0
- package/dist/bin/chunk-dbv8w56s.js +50 -0
- package/dist/bin/chunk-dxchg0g1.js +1 -0
- package/dist/bin/{chunk-tx0tqq2k.js → chunk-e1bfd1yv.js} +6 -6
- package/dist/bin/chunk-fpcghdr3.js +585 -0
- package/dist/bin/chunk-ftse39wf.js +9 -0
- package/dist/bin/chunk-g0ewbkbq.js +1 -0
- package/dist/bin/chunk-gskbezam.js +141 -0
- package/dist/bin/chunk-gvs85t2j.js +1 -0
- package/dist/bin/chunk-hej39dwr.js +2 -0
- package/dist/bin/chunk-jce28gnz.js +2 -0
- package/dist/bin/chunk-kbtrr0c3.js +1 -0
- package/dist/bin/chunk-khrye4x9.js +1 -0
- package/dist/bin/{chunk-mh0kdzqp.js → chunk-ks4ewy1s.js} +1 -1
- package/dist/bin/chunk-mbnwt3r5.js +2 -0
- package/dist/bin/chunk-md2k3n21.js +37 -0
- package/dist/bin/chunk-memfxrcn.js +1 -0
- package/dist/bin/chunk-mwgxyc0z.js +44 -0
- package/dist/bin/chunk-neampxq1.js +4 -0
- package/dist/bin/chunk-nkpf91d3.js +1 -0
- package/dist/bin/chunk-nmkm1f68.js +2 -0
- package/dist/bin/chunk-nyc2jxd8.js +2 -0
- package/dist/bin/chunk-pqr8jqnd.js +1 -0
- package/dist/bin/chunk-q182t9ba.js +3 -0
- package/dist/bin/chunk-r6x7beew.js +60 -0
- package/dist/bin/chunk-rfqk5xym.js +1 -0
- package/dist/bin/{chunk-etrb03mt.js → chunk-ww770qpn.js} +30 -30
- package/dist/bin/chunk-wy20ztb6.js +1 -0
- package/dist/bin/chunk-wzepfqf4.js +512 -0
- package/dist/bin/chunk-xcqmwphz.js +1 -0
- package/dist/bin/chunk-xev7qr2h.js +3 -0
- package/dist/bin/chunk-y3rm37z1.js +6 -0
- package/dist/bin/chunk-zejwh9cy.js +6 -0
- package/dist/bin/chunk-zwwnt4x1.js +1 -0
- package/dist/bin/cli.js +431 -418
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/{chunk-dskvqt67.js → chunk-0hj552t7.js} +127 -127
- package/dist/chunk-1ypkh8g6.js +5 -0
- package/dist/chunk-2m09t0c0.js +60 -0
- package/dist/chunk-7fkyfh65.js +1 -0
- package/dist/chunk-7xpxzbkr.js +442 -0
- package/dist/chunk-8e0az001.js +2 -0
- package/dist/chunk-b10cbk8z.js +44 -0
- package/dist/chunk-gk58959n.js +6 -0
- package/dist/chunk-h1rc94df.js +114 -0
- package/dist/chunk-hbhxk5a0.js +4 -0
- package/dist/chunk-hz7k9ymh.js +1 -0
- package/dist/chunk-kj7gzdj6.js +1 -0
- package/dist/chunk-ky5c6t5y.js +2 -0
- package/dist/chunk-mch30cyc.js +1 -0
- package/dist/chunk-n04a3bgf.js +1 -0
- package/dist/chunk-nnqxmh7f.js +34 -0
- package/dist/chunk-p6vszgc2.js +92 -0
- package/dist/chunk-q2njk4hx.js +141 -0
- package/dist/chunk-qjk1v1gs.js +50 -0
- package/dist/chunk-qtp90j44.js +2 -0
- package/dist/chunk-r5natbed.js +37 -0
- package/dist/chunk-rcxq9aaa.js +704 -0
- package/dist/{chunk-gahsdmxf.js → chunk-s3rpd72x.js} +52 -52
- package/dist/{chunk-xt3s24vr.js → chunk-spx89gaw.js} +1 -1
- package/dist/chunk-t0kh8haz.js +2 -0
- package/dist/chunk-vz95qy3n.js +1 -0
- package/dist/deploy/attach-credentials.d.ts +4 -8
- package/dist/deploy/index.js +1 -1
- package/dist/dns/cloudflare.d.ts +27 -0
- package/dist/dns/godaddy.d.ts +18 -1
- package/dist/dns/index.d.ts +2 -0
- package/dist/dns/index.js +1 -1
- package/dist/dns/zone-migration.d.ts +92 -0
- package/dist/dns/zone-migration.test.d.ts +1 -0
- package/dist/drivers/hetzner/driver.d.ts +8 -1
- package/dist/drivers/index.js +1 -1
- package/dist/drivers/shared/app-updates.d.ts +36 -0
- package/dist/drivers/shared/compute-provision.d.ts +14 -2
- package/dist/drivers/shared/db-provision.d.ts +3 -2
- package/dist/drivers/shared/mail-provision.d.ts +116 -0
- package/dist/drivers/shared/mail-provision.test.d.ts +1 -0
- package/dist/drivers/shared/managed-services-probe.d.ts +47 -0
- package/dist/drivers/shared/managed-services-probe.test.d.ts +1 -0
- package/dist/drivers/shared/package-manager.d.ts +1 -0
- package/dist/drivers/shared/remote-failure.d.ts +21 -0
- package/dist/drivers/shared/remote-failure.test.d.ts +1 -0
- package/dist/drivers/shared/sqlite-shared-path.d.ts +50 -0
- package/dist/drivers/shared/sqlite-shared-path.test.d.ts +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +92 -89
- package/dist/operations/plan.d.ts +136 -0
- package/dist/operations/plan.test.d.ts +1 -0
- package/dist/operations/server-rename.d.ts +84 -0
- package/dist/operations/server-rename.test.d.ts +1 -0
- package/dist/operations/site-move.d.ts +263 -0
- package/dist/operations/site-move.test.d.ts +1 -0
- package/dist/protection/index.js +1 -1
- package/dist/push/index.js +1 -1
- package/dist/spend/index.js +1 -1
- package/dist/ui/404.html +1 -1
- package/dist/ui/accept-invitation.html +1 -1
- package/dist/ui/access-denied.html +1 -1
- package/dist/ui/account/automation.html +6 -6
- package/dist/ui/account/security.html +2 -2
- package/dist/ui/applications/compose.html +6 -6
- package/dist/ui/applications/new.html +2 -2
- package/dist/ui/data/backups.html +80 -80
- package/dist/ui/data/services.html +78 -78
- package/dist/ui/data/volumes.html +50 -50
- package/dist/ui/index.html +50 -50
- package/dist/ui/infrastructure/topology.html +118 -118
- package/dist/ui/integrations.html +2 -2
- package/dist/ui/operations/alerts.html +48 -48
- package/dist/ui/operations/configuration.html +6 -6
- package/dist/ui/operations/jobs.html +75 -75
- package/dist/ui/operations/maintenance.html +6 -6
- package/dist/ui/operations/observability.html +82 -82
- package/dist/ui/operations/previews.html +6 -6
- package/dist/ui/operations/queue.html +6 -6
- package/dist/ui/operations/regions.html +6 -6
- package/dist/ui/operations/releases.html +6 -6
- package/dist/ui/operations/spend.html +54 -54
- package/dist/ui/operations/workloads.html +104 -104
- package/dist/ui/security.html +2 -2
- package/dist/ui/server/actions.html +56 -56
- package/dist/ui/server/activity.html +1 -1
- package/dist/ui/server/capacity.html +6 -6
- package/dist/ui/server/database.html +106 -106
- package/dist/ui/server/deployments.html +50 -50
- package/dist/ui/server/diagnostics.html +2 -2
- package/dist/ui/server/firewall.html +76 -76
- package/dist/ui/server/fleet.html +34 -34
- package/dist/ui/server/logs.html +24 -24
- package/dist/ui/server/metrics.html +112 -112
- package/dist/ui/server/security.html +2 -2
- package/dist/ui/server/services.html +27 -27
- package/dist/ui/server/sites.html +120 -120
- package/dist/ui/server/ssh-keys.html +52 -52
- package/dist/ui/server/team.html +144 -144
- package/dist/ui/server/terminal.html +15 -15
- package/dist/ui/serverless/alarms.html +52 -52
- package/dist/ui/serverless/assets.html +27 -27
- package/dist/ui/serverless/cost.html +2 -2
- package/dist/ui/serverless/data.html +36 -36
- package/dist/ui/serverless/deployments.html +27 -27
- package/dist/ui/serverless/firewall.html +1 -1
- package/dist/ui/serverless/functions.html +40 -40
- package/dist/ui/serverless/logs.html +24 -24
- package/dist/ui/serverless/metrics.html +2 -2
- package/dist/ui/serverless/queues.html +48 -48
- package/dist/ui/serverless/secrets.html +51 -51
- package/dist/ui/serverless/traces.html +6 -6
- package/dist/ui/serverless.html +53 -53
- package/dist/ui-src/src/charts.ts +17499 -12662
- package/dist/ui-src/src/topology.ts +2 -2
- package/package.json +3 -3
- package/dist/bin/chunk-00kg80qg.js +0 -1
- package/dist/bin/chunk-09nwf2gy.js +0 -34
- package/dist/bin/chunk-1k5kszjp.js +0 -111
- package/dist/bin/chunk-21e0mavm.js +0 -1
- package/dist/bin/chunk-271gk1n2.js +0 -6
- package/dist/bin/chunk-2empps47.js +0 -2
- package/dist/bin/chunk-38pq971s.js +0 -2
- package/dist/bin/chunk-3gykfyq4.js +0 -37
- package/dist/bin/chunk-3vqfexc4.js +0 -70
- package/dist/bin/chunk-4vrqm9h0.js +0 -2
- package/dist/bin/chunk-598yf4bs.js +0 -1
- package/dist/bin/chunk-5ectjq0b.js +0 -1
- package/dist/bin/chunk-5erkxpt7.js +0 -512
- package/dist/bin/chunk-5mrtzemj.js +0 -1
- package/dist/bin/chunk-5n9fmabb.js +0 -1
- package/dist/bin/chunk-9knpg30y.js +0 -1
- package/dist/bin/chunk-9pvsff8g.js +0 -1
- package/dist/bin/chunk-ax9mr6wm.js +0 -44
- package/dist/bin/chunk-axhnkn5g.js +0 -2
- package/dist/bin/chunk-c1vcdgvr.js +0 -1
- package/dist/bin/chunk-ctd2vg9w.js +0 -2
- package/dist/bin/chunk-dbgffky8.js +0 -1
- package/dist/bin/chunk-ddk4rt4j.js +0 -6
- package/dist/bin/chunk-dwr30vbv.js +0 -1
- package/dist/bin/chunk-e0rkrq70.js +0 -1
- package/dist/bin/chunk-e3xrwh9z.js +0 -1
- package/dist/bin/chunk-fhc6ntvd.js +0 -2
- package/dist/bin/chunk-fpm59y25.js +0 -6
- package/dist/bin/chunk-fvbxvq6b.js +0 -1
- package/dist/bin/chunk-fy8j3y8p.js +0 -92
- package/dist/bin/chunk-fz21b57w.js +0 -1
- package/dist/bin/chunk-gavvf0pg.js +0 -141
- package/dist/bin/chunk-ggn7ax8p.js +0 -4
- package/dist/bin/chunk-gpe2prkm.js +0 -1
- package/dist/bin/chunk-h5pa5men.js +0 -2
- package/dist/bin/chunk-hm08xdxf.js +0 -2
- package/dist/bin/chunk-hzgz13nf.js +0 -1
- package/dist/bin/chunk-j703btc5.js +0 -50
- package/dist/bin/chunk-k9t9wvms.js +0 -1
- package/dist/bin/chunk-m669wtgr.js +0 -1
- package/dist/bin/chunk-m7dgskt1.js +0 -1
- package/dist/bin/chunk-mr0atd2s.js +0 -2
- package/dist/bin/chunk-mz0wbbsj.js +0 -3
- package/dist/bin/chunk-ngcyftm2.js +0 -1
- package/dist/bin/chunk-p66ptpmr.js +0 -2
- package/dist/bin/chunk-qk9qgepa.js +0 -1
- package/dist/bin/chunk-rytk89az.js +0 -60
- package/dist/bin/chunk-tga3hhwk.js +0 -6
- package/dist/bin/chunk-vek8a0w6.js +0 -1
- package/dist/bin/chunk-vm3q5gf2.js +0 -3
- package/dist/bin/chunk-y7s5r8y6.js +0 -3
- package/dist/bin/chunk-yv9sth30.js +0 -1
- package/dist/bin/chunk-zmegvjp8.js +0 -581
- package/dist/chunk-0ccta6z6.js +0 -6
- package/dist/chunk-0k1cs6pp.js +0 -1
- package/dist/chunk-1egjn203.js +0 -704
- package/dist/chunk-2wx29qga.js +0 -5
- package/dist/chunk-5m5rqmv7.js +0 -1
- package/dist/chunk-8ea5022g.js +0 -114
- package/dist/chunk-8xqn3c0w.js +0 -2
- package/dist/chunk-b4esxhmw.js +0 -2
- package/dist/chunk-b8e5wzwn.js +0 -44
- package/dist/chunk-bggt4n6e.js +0 -2
- package/dist/chunk-cwkg37rs.js +0 -37
- package/dist/chunk-gnv3r2jg.js +0 -1
- package/dist/chunk-hg3c48cp.js +0 -34
- package/dist/chunk-m5azeva3.js +0 -2
- package/dist/chunk-r3qf56b3.js +0 -92
- package/dist/chunk-sdqa9ghv.js +0 -141
- package/dist/chunk-svrvvcm7.js +0 -1
- package/dist/chunk-v0p3hpc3.js +0 -60
- package/dist/chunk-wdzjbecg.js +0 -50
- package/dist/chunk-ww8k3g7j.js +0 -1
- package/dist/chunk-xmqfc62w.js +0 -1
- package/dist/chunk-xrebj679.js +0 -435
- package/dist/chunk-y21zk0pn.js +0 -4
|
@@ -1,512 +0,0 @@
|
|
|
1
|
-
import{Ua as eE}from"./chunk-38pq971s.js";import{$a as kc,$b as tu,$c as Yo,Gc as eu,Va as Lc,Wa as Ot,Xa as UR,_c as p,ad as nu,bd as qg,db as jR,eb as HR,fb as LR,gb as FR,hb as VR,ib as NR,jb as xR,lb as Cc,mb as Gg,nb as Oc,ob as MR,pb as QR,qb as GR,rb as yi,sb as ac,tb as ZR,ub as YR,vb as sR,wb as XR,xb as uo,yb as KR}from"./chunk-1k5kszjp.js";import{dd as Er}from"./chunk-fhc6ntvd.js";import{nd as Jl}from"./chunk-gavvf0pg.js";import{od as f_,rd as __}from"./chunk-y7s5r8y6.js";import{sd as gf,td as Ai,xd as ho}from"./chunk-vm3q5gf2.js";import{yd as dc}from"./chunk-4vrqm9h0.js";import{Gd as b_,Hd as W_,Id as kl,Jd as Ol,Od as le,Pd as U_,zd as cc}from"./chunk-mz0wbbsj.js";import{Rd as Fd}from"./chunk-p66ptpmr.js";import{Ie as So,Sd as kR,re as Jn,se as co,ve as qR,we as tE,xe as gc,ye as $l}from"./chunk-zmegvjp8.js";import{cf as pR}from"./chunk-ddk4rt4j.js";import{gf as u_,jf as h_,pf as S_,qf as Xf,uf as Kf,vf as ul,zf as Al}from"./chunk-tga3hhwk.js";import{Sf as mR}from"./chunk-axhnkn5g.js";import{Uf as T_}from"./chunk-h5pa5men.js";import{$f as _n}from"./chunk-fy8j3y8p.js";import{ag as CR,dg as OR,eg as JR,fg as BR,gg as zR,hg as bR,ig as WR}from"./chunk-tx0tqq2k.js";import{jg as Uc,kg as Jf,lg as Ne,mg as lc,ng as bt,og as Bf,pg as TR}from"./chunk-etrb03mt.js";import{Og as ut}from"./chunk-fpm59y25.js";import{Gh as B_,Un as z_,hh as yS,jh as bc,kh as de,nh as On,ph as re,qh as ps}from"./chunk-rxcvf10f.js";import{Vo as oe}from"./chunk-mh0kdzqp.js";import{createHash as EP}from"node:crypto";import{existsSync as Tn,mkdtempSync as Nl,readdirSync as _R,rmSync as Wr,statSync as nE}from"node:fs";import{readFile as ln,writeFile as Tr}from"node:fs/promises";import{tmpdir as Ro}from"node:os";import{dirname as IP,extname as uc,join as At,normalize as wP,relative as AP,resolve as DP,sep as yP}from"node:path";import{fileURLToPath as PP}from"node:url";class vo extends Error{status;code;requestId;constructor(t,e,n,r){super(n);this.status=t;this.code=e;this.requestId=r}}class lg{options;baseUrl;fetchFn;constructor(t){this.options=t;this.baseUrl=t.baseUrl.replace(/\/$/,""),this.fetchFn=t.fetch??fetch}async request(t,e={}){let n=await this.fetchFn(`${this.baseUrl}${t}`,{...e,headers:{accept:"application/json",authorization:`Bearer ${this.options.token}`,...e.headers}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new vo(n.status,r.error?.code??"api_error",r.error?.message??"API request failed.",r.error?.requestId??n.headers.get("x-request-id")??void 0);return r}listProjects(t={}){return this.request(`/api/v1/projects?${new URLSearchParams(Object.fromEntries(Object.entries(t).filter(([,e])=>e!==void 0).map(([e,n])=>[e,String(n)])))}`)}listEnvironments(t,e={}){return this.request(`/api/v1/projects/${encodeURIComponent(t)}/environments?${new URLSearchParams(Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0).map(([n,r])=>[n,String(r)])))}`)}listServices(t,e){return this.request(`/api/v1/services?${new URLSearchParams({projectId:t,...e?{environmentId:e}:{}})}`)}listOperations(t){return this.request(`/api/v1/operations${t?`?projectId=${encodeURIComponent(t)}`:""}`)}listComposeTemplates(){return this.request("/api/v1/compose-templates")}listComposeApplications(t,e){return this.request(`/api/v1/compose-applications?${new URLSearchParams({projectId:t,...e?{environmentId:e}:{}})}`)}previewCompose(t){return this.request("/api/v1/compose-applications/preview",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}createComposeApplication(t){return this.request("/api/v1/compose-applications",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}composeServices(t){return this.request(`/api/v1/compose-applications/${encodeURIComponent(t)}/services`)}composeAction(t,e,n={}){return this.request(`/api/v1/compose-applications/${encodeURIComponent(t)}/${e}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n)})}releaseCapabilities(t,e={}){return this.request(`/api/v1/releases/capabilities?${new URLSearchParams({kind:t,health:String(!!e.health),replicas:String(e.replicas??1)})}`)}listReleases(t,e={}){return this.request(`/api/v1/releases?${new URLSearchParams({projectId:t,...e})}`)}createReleaseArtifact(t){return this.request("/api/v1/release-artifacts",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}createRelease(t){return this.request("/api/v1/releases",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}releaseAction(t,e,n={}){return this.request(`/api/v1/releases/${encodeURIComponent(t)}/${e}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n)})}createDeployment(t,e){return this.request("/api/v1/deployments",{method:"POST",headers:{"content-type":"application/json","idempotency-key":e},body:JSON.stringify(t)})}detectApplication(t){return this.request("/api/v1/application-detections",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}planApplication(t){return this.request("/api/v1/application-plans",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}listApplicationDrafts(t){return this.request(`/api/v1/application-drafts?projectId=${encodeURIComponent(t)}`)}createApplicationDraft(t){return this.request("/api/v1/application-drafts",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}updateApplicationDraft(t){return this.request("/api/v1/application-drafts",{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}createApplication(t,e){return this.request("/api/v1/applications",{method:"POST",headers:{"content-type":"application/json","idempotency-key":e},body:JSON.stringify(t)})}uploadApplicationArtifact(t,e,n){return this.request("/api/v1/application-artifacts",{method:"POST",headers:{"content-type":"application/octet-stream","x-project-id":t,"x-artifact-filename":e},body:n})}listRegistryConnections(){return this.request("/api/v1/registry-connections")}createRegistryConnection(t){return this.request("/api/v1/registry-connections",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}updateRegistryConnection(t){return this.request("/api/v1/registry-connections",{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}disconnectRegistryConnection(t){return this.request("/api/v1/registry-connections",{method:"DELETE",headers:{"content-type":"application/json"},body:JSON.stringify({id:t})})}listQueue(t={}){let e=new URLSearchParams(Object.entries(t).filter(([,n])=>n!==void 0).map(([n,r])=>[n,String(r)]));return this.request(`/api/v1/queue?${e}`)}operationLogs(t,e={}){let n=new URLSearchParams(Object.entries(e).filter(([,r])=>r!==void 0).map(([r,i])=>[r,String(i)]));return this.request(`/api/v1/operations/${encodeURIComponent(t)}/logs?${n}`)}streamOperationLogs(t,e=0){return this.fetchFn(`${this.baseUrl}/api/v1/operations/${encodeURIComponent(t)}/logs/stream`,{headers:{accept:"text/event-stream",authorization:`Bearer ${this.options.token}`,"last-event-id":String(e)}})}cancelOperation(t){return this.request(`/api/v1/operations/${encodeURIComponent(t)}/cancel`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"})}retryOperation(t,e,n=0){return this.request(`/api/v1/operations/${encodeURIComponent(t)}/retry`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({errorClass:e,delayMs:n})})}queueSettings(){return this.request("/api/v1/queue/settings")}updateQueueSettings(t){return this.request("/api/v1/queue/settings",{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({confirm:"update queue limits",concurrency:t})})}listPreviews(t){return this.request(`/api/v1/previews${t?`?projectId=${encodeURIComponent(t)}`:""}`)}listPreviewDefinitions(t){return this.request(`/api/v1/preview-definitions?projectId=${encodeURIComponent(t)}`)}createPreviewDefinition(t){return this.request("/api/v1/preview-definitions",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}createPreview(t){return this.request("/api/v1/previews",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}destroyPreview(t,e){return this.request(`/api/v1/previews/${encodeURIComponent(t)}/destroy`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({confirm:e})})}extendPreview(t,e){return this.request(`/api/v1/previews/${encodeURIComponent(t)}/extend`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({hours:e})})}rebuildPreview(t){return this.request(`/api/v1/previews/${encodeURIComponent(t)}/rebuild`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"})}usage(t={}){let e=new URLSearchParams;for(let[n,r]of Object.entries(t))if(r)e.set(n,String(r));return this.request(`/api/v1/usage${e.size>0?`?${e}`:""}`)}usageRollups(t){let e=new URLSearchParams({from:t.from,to:t.to});if(t.projectId)e.set("projectId",t.projectId);if(t.environmentId)e.set("environmentId",t.environmentId);if(t.limit)e.set("limit",String(t.limit));for(let n of t.meters??[])e.append("meter",n);return this.request(`/api/v1/usage/rollups?${e}`)}allowance(t="deploy",e={}){let n=new URLSearchParams({operation:t});if(e.projectId)n.set("projectId",e.projectId);if(e.environmentId)n.set("environmentId",e.environmentId);return this.request(`/api/v1/spend/allowance?${n}`)}budgets(t={}){let e=new URLSearchParams;for(let[n,r]of Object.entries(t))if(r)e.set(n,String(r));return this.request(`/api/v1/spend/budgets${e.size>0?`?${e}`:""}`)}anomalies(t={}){let e=new URLSearchParams;if(t.projectId)e.set("projectId",t.projectId);if(t.since)e.set("since",t.since);if(t.unacknowledged)e.set("unacknowledged","true");return this.request(`/api/v1/spend/anomalies${e.size>0?`?${e}`:""}`)}}import{createHash as aI}from"node:crypto";import{lstatSync as RE,readdirSync as EE,readFileSync as IE}from"node:fs";import{relative as wE,resolve as gg,sep as AE}from"node:path";function DE(t){return new Map(t.map((e)=>[e.path.replace(/^\.\//,"").replace(/\\/g,"/"),e]))}function ar(t,e,n){return{path:t,reason:e,weight:n}}function ug(t){try{return t?.content?JSON.parse(t.content):{}}catch{return{}}}function Vr(t,e,n,r,i,c){return{framework:t,strategy:e,confidence:n,evidence:r,defaults:{build:i,runtime:{target:e==="static"?"serverless":e==="serverless"?"serverless":e==="dockerfile"||e==="prebuilt_image"?"container":"server",architecture:"x86_64",port:e==="static"||e==="serverless"?void 0:3000,healthCheck:e==="static"?void 0:{protocol:"http",path:"/health"}}},description:c}}function Nr(t){let e=DE(t.slice(0,1e4)),n=[];if(e.has("Dockerfile"))n.push(Vr("dockerfile","dockerfile",0.99,[ar("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 r=ug(e.get("composer.json"));if(e.has("artisan")&&r.require?.["laravel/framework"])n.push(Vr("laravel","server",0.98,[ar("artisan","Laravel Artisan entrypoint is present.",0.45),ar("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(e.has("composer.json"))n.push(Vr("php","server",0.82,[ar("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=ug(e.get("package.json"));if(e.has("package.json")){let c=e.has("bun.lock")||e.has("bun.lockb")||i.engines?.bun,d=c?"bun":"node",a=c?"bun":"node",l=[ar("package.json",`Defines ${i.scripts?.build?"build and ":""}${i.scripts?.start?"start ":""}scripts.`,0.55)];if(c)l.push(ar(e.has("bun.lock")?"bun.lock":e.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,u=o?{kind:"static",installCommand:`${d} install --frozen-lockfile`,buildCommand:`${d} run build`,publishDirectory:"dist"}:{kind:"server",runtime:d,installCommand:`${d} install --frozen-lockfile`,buildCommand:i.scripts?.build?`${d} run build`:void 0,startCommand:i.scripts?.start?`${d} run start`:d==="bun"?"bun run index.ts":"node index.js"};n.push(Vr(a,u.kind,Math.min(0.94,l.reduce((f,R)=>f+R.weight,0)),l,u,o?"Install dependencies, build static assets, and publish the output directory.":`Install dependencies, build if configured, and start the ${d} server.`))}if(!n.length&&(e.has("index.html")||e.has("public/index.html")))n.push(Vr("static","static",0.78,[ar(e.has("index.html")?"index.html":"public/index.html","A static HTML entrypoint is present.",0.78)],{kind:"static",publishDirectory:e.has("index.html")?".":"public"},"Publish the static directory without a runtime process."));if(!n.length)n.push(Vr("unknown","buildpack",0.2,[],{kind:"buildpack",runtime:"node"},"No supported framework signature was conclusive; choose commands and runtime manually."));return n.sort((c,d)=>d.confidence-c.confidence||c.framework.localeCompare(d.framework))}function ko(t,e={}){let n=gg(t),r=e.maxFiles??1e4,i=e.maxContentBytes??262144,c=[],d=new Set(["Dockerfile","package.json","composer.json","index.html","public/index.html","bun.lock","bun.lockb","artisan"]),a=new Set([".git",".ts-cloud",".cache",".next",".nuxt",".output",".turbo",".bun","node_modules","vendor","pantry","dist","build","coverage"]),l=(o)=>{for(let u of EE(o).sort()){if(a.has(u))continue;let f=gg(o,u),R=wE(n,f).split(AE).join("/");if(!R||R.startsWith("../"))throw Error("Detection path escaped the application root");let E=RE(f);if(E.isSymbolicLink())throw Error(`Detection refuses symbolic links: ${R}`);if(E.isDirectory())l(f);else if(E.isFile()){if(c.length>=r)throw Error("Application file-count limit exceeded");let y={path:R,size:E.size};if(d.has(R)&&E.size<=i)y.content=IE(f,"utf8");c.push(y)}}};return l(n),c}function Oo(t){if(Array.isArray(t))return`[${t.map(Oo).join(",")}]`;if(t&&typeof t==="object")return`{${Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>`${JSON.stringify(e)}:${Oo(n)}`).join(",")}}`;return JSON.stringify(t)??"null"}function Ci(t){return!!t&&!t.startsWith("/")&&!t.split("/").includes("..")&&!/[\0\r\n]/.test(t)}function Ae(t,e,n,r){return{path:t,code:e,message:n,alternatives:r}}function Co(t){return JSON.parse(JSON.stringify(t))}function yE(t){let e=Object.fromEntries(Object.entries(t.environment??{}).map(([n,r])=>[n,typeof r==="string"?r:`\${${r.secretRef}}`]));if(t.build.kind==="prebuilt_image"||t.build.kind==="dockerfile")return Co({infrastructure:{containers:{[t.slug]:{source:t.source,build:t.build,port:t.runtime.port,cpu:t.runtime.cpu,memory:t.runtime.memoryMb,architecture:t.runtime.architecture,healthCheck:t.runtime.healthCheck,environment:e}}}});if(t.runtime.target==="serverless"||t.build.kind==="serverless")return Co({serverless:{apps:{[t.slug]:{source:t.source,build:t.build,architecture:t.runtime.architecture,environment:e,domain:t.domain}}}});return Co({sites:{[t.slug]:{source:t.source,build:t.build,port:t.runtime.port,architecture:t.runtime.architecture,healthCheck:t.runtime.healthCheck,env:e,domain:t.domain?.hostname}}})}function Fe(t,e=[]){let n=[],r=(y)=>/(?:secret|token|password|passwd|private[_-]?key|api[_-]?key)/i.test(y),i=Object.fromEntries(Object.entries(t.environment??{}).map(([y,$])=>{if(typeof $==="string"&&r(y))return n.push(Ae(`environment.${y}`,"write_only_secret_required",`${y} must be supplied through the write-only secrets boundary.`)),[y,{secretRef:y}];return[y,$]})),c=t.build;if(t.build.kind==="dockerfile"&&t.build.buildArgs){let y=Object.fromEntries(Object.entries(t.build.buildArgs).map(([$,C])=>{if(r($))return n.push(Ae(`build.buildArgs.${$}`,"write_only_build_secret_required",`${$} must be declared in secretNames instead of buildArgs.`)),[$,"[REDACTED]"];return[$,C]}));c={...t.build,buildArgs:y}}if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(t.slug))n.push(Ae("slug","invalid_slug","Slug must contain 2-63 lowercase letters, numbers, or hyphens."));if(!Ci((t.source.kind==="git"?t.source.monorepoRoot:t.source.kind==="local"?t.source.root:".")??"."))n.push(Ae("source","unsafe_source_root","Source root must stay inside the source tree."));if(t.source.kind==="git"&&t.source.sparsePaths?.some((y)=>!Ci(y)))n.push(Ae("source.sparsePaths","unsafe_sparse_path","Sparse checkout paths must stay inside the repository."));if(t.build.kind==="dockerfile"&&(!Ci(t.build.context)||!Ci(t.build.dockerfile)))n.push(Ae("build","unsafe_docker_path","Docker context and Dockerfile must stay inside the source tree."));if(t.build.kind==="static"&&!Ci(t.build.publishDirectory))n.push(Ae("build.publishDirectory","invalid_publish_directory","A safe static publish directory is required."));if(t.build.kind==="server"&&!t.build.startCommand.trim())n.push(Ae("build.startCommand","missing_start_command","A server start command is required.",["Use static output","Use a Dockerfile"]));if(t.source.kind==="image"&&t.build.kind!=="prebuilt_image")n.push(Ae("build.kind","image_requires_prebuilt","An OCI image source must use the prebuilt-image strategy.",["Select prebuilt image"]));if(t.build.kind==="prebuilt_image"&&t.runtime.target!=="container")n.push(Ae("runtime.target","image_requires_container","Prebuilt images require the container runtime target.",["Select container target"]));if(t.runtime.target==="serverless"&&t.build.kind==="dockerfile")n.push(Ae("runtime.target","unsupported_serverless_dockerfile","Dockerfile builds currently target the container service path.",["Select container target","Select serverless package"]));if(t.runtime.port!==void 0&&(!Number.isInteger(t.runtime.port)||t.runtime.port<1||t.runtime.port>65535))n.push(Ae("runtime.port","invalid_port","Port must be an integer from 1 to 65535."));let d=t.runtime.healthCheck;if(d&&d.protocol!=="tcp"&&(!d.path||!d.path.startsWith("/")||/[\r\n]/.test(d.path)))n.push(Ae("runtime.healthCheck.path","invalid_health_path","HTTP health checks require a path beginning with /."));if(t.domain?.hostname&&(!/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/i.test(t.domain.hostname)||t.domain.hostname.includes("..")))n.push(Ae("domain.hostname","invalid_domain","Domain must be a valid DNS hostname."));let a=Object.values(i).flatMap((y)=>typeof y==="object"?[y.secretRef]:[]),l=[...new Set([...t.requiredSecretNames??[],...t.build.kind==="dockerfile"?t.build.secretNames??[]:[],...a])].sort(),o=new Set(e),u=l.filter((y)=>!o.has(y)),f={apiVersion:"ts-cloud.dev/v1",kind:"Application",metadata:{name:t.name,slug:t.slug,projectId:t.projectId,environmentId:t.environmentId},spec:{source:t.source,build:c,runtime:t.runtime,environment:i,domain:t.domain}},R=[...new Set([t.source.kind==="git"?"git:read":t.source.kind==="image"?"registry:pull":t.source.kind==="artifact"?"artifact:inspect":"filesystem:read",t.runtime.target==="container"?"containers":t.runtime.target==="serverless"?"serverless":"servers",t.domain?"dns":""])].filter(Boolean).sort(),E=[...new Set([t.runtime.target,t.runtime.cpu?`${t.runtime.cpu} vCPU`:"",t.runtime.memoryMb?`${t.runtime.memoryMb} MB memory`:"",(t.runtime.minInstances??0)>0?`${t.runtime.minInstances} minimum instances`:"scales from zero where supported",t.domain?"managed DNS/TLS":""])].filter(Boolean);return{valid:n.length===0&&u.length===0,issues:n,missingSecrets:u,manifest:f,configPatch:yE({...t,build:c,environment:i}),capabilityRequirements:R,costDrivers:E,serializedManifest:`${Oo(f)}
|
|
2
|
-
`}}function hg(t){let e=t.replace(/\\/g,"/");return!!e&&!e.startsWith("/")&&!/^[A-Za-z]:\//.test(e)&&!e.split("/").includes("..")&&!/[\0\r\n]/.test(e)}function Sg(t,e,n={}){let r=n.maxBytes??104857600,i=n.maxEntries??1e4,c=n.maxExpandedBytes??524288000;if(t.byteLength>r)throw Error("Archive exceeds the compressed size limit");let d=new DataView(t.buffer,t.byteOffset,t.byteLength),a=[],l=0;if(e.toLowerCase().endsWith(".zip")||t[0]===80&&t[1]===75){let u=0;while(u+30<=t.length){let f=d.getUint32(u,!0);if(f===33639248||f===101010256)break;if(f!==67324752)throw Error("Malformed ZIP local header");let R=d.getUint16(u+6,!0),E=d.getUint32(u+18,!0),y=d.getUint32(u+22,!0),$=d.getUint16(u+26,!0),C=d.getUint16(u+28,!0);if(R&8)throw Error("ZIP data descriptors are not accepted for uploaded artifacts");let J=new TextDecoder().decode(t.subarray(u+30,u+30+$));if(!hg(J))throw Error(`Unsafe archive path: ${J}`);if(a.push(J),l+=y,a.length>i||l>c)throw Error("Archive expansion limit exceeded");u+=30+$+C+E}return{format:"zip",entries:a.length,expandedBytes:l,paths:a}}if(!e.toLowerCase().match(/\.(?:tar|tar\.gz|tgz)$/))throw Error("Only ZIP and uncompressed TAR artifacts are supported");let o=0;while(o+512<=t.length){let u=t.subarray(o,o+512);if(u.every(($)=>$===0))break;let f=($,C)=>new TextDecoder().decode(u.subarray($,$+C)).replace(/\0.*$/,""),R=`${f(345,155)}${f(345,155)?"/":""}${f(0,100)}`,E=Number.parseInt(f(124,12).trim()||"0",8),y=String.fromCharCode(u[156]??0);if(!hg(R))throw Error(`Unsafe archive path: ${R}`);if(y==="1"||y==="2")throw Error(`Archive links are not accepted: ${R}`);if(!Number.isFinite(E)||E<0)throw Error("Malformed TAR entry size");if(a.push(R),l+=E,a.length>i||l>c)throw Error("Archive expansion limit exceeded");o+=512+Math.ceil(E/512)*512}return{format:"tar",entries:a.length,expandedBytes:l,paths:a}}var fg=new Set(["source","build","runtime","environment","domain","review"]);function _g(t,e){try{return typeof t==="string"?JSON.parse(t):e}catch{return e}}function Rg(t){return/(?:secret|token|password|passwd|private[_-]?key|api[_-]?key)/i.test(t)}function Eg(t){for(let[n,r]of Object.entries(t.environment??{}))if(typeof r==="string"&&Rg(n)&&r)throw Error(`${n} must be stored through the write-only secrets boundary`);if(t.build.kind==="dockerfile"){for(let[n,r]of Object.entries(t.build.buildArgs??{}))if(Rg(n)&&r)throw Error(`${n} must be declared as a build secret name`)}let e=JSON.stringify(t);if(/https?:\/\/[^/@\s]+:[^/@\s]+@/i.test(e))throw Error("Drafts cannot contain credential-bearing URLs")}function Ig(t){return{id:String(t.id),organizationId:String(t.organization_id),projectId:String(t.project_id),schemaVersion:Number(t.schema_version),name:String(t.name),step:String(t.step),input:_g(t.input,{}),suppliedSecretNames:_g(t.supplied_secret_names,[]),status:String(t.status),version:Number(t.version),createdByActorId:t.created_by_actor_id?String(t.created_by_actor_id):void 0,createdAt:String(t.created_at),updatedAt:String(t.updated_at)}}class Jo{controlPlane;nowFn;idFn;constructor(t,e={}){this.controlPlane=t;this.nowFn=e.now??(()=>new Date),this.idFn=e.id??(()=>crypto.randomUUID())}now(){return this.nowFn().toISOString()}create(t){if(Eg(t.draft),t.draft.projectId!==t.projectId)throw Error("Draft project does not match its storage scope");let e=this.controlPlane.getProject(t.projectId);if(!e||e.organizationId!==t.organizationId)throw Error("Draft project was not found");let n=this.idFn(),r=this.now(),i=t.step??"source";if(!fg.has(i))throw Error("Invalid draft step");let c=[...new Set(t.suppliedSecretNames??[])].sort(),d=Fe(t.draft,c).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, ?, ?, ?, ?, ?, ?, ?, ?)",[n,t.organizationId,t.projectId,t.name.trim().slice(0,100),i,JSON.stringify(t.draft),JSON.stringify(c),d,t.actorId??null,r,r]),this.controlPlane.appendEvent({organizationId:t.organizationId,projectId:t.projectId,actorId:t.actorId,type:"application.draft.created",payload:{draftId:n,step:i,status:d,requiredSecretNames:t.draft.requiredSecretNames??[]}}),this.get(n)}get(t){let e=this.controlPlane.database.query("SELECT * FROM application_drafts WHERE id=?").get(t);return e?Ig(e):void 0}list(t){return this.controlPlane.database.query("SELECT * FROM application_drafts WHERE project_id=? ORDER BY updated_at DESC").all(t).map(Ig)}update(t,e,n){let r=this.get(t);if(!r||r.version!==e)throw Error(`Application draft ${t} changed since version ${e}`);if(!fg.has(n.step))throw Error("Invalid draft step");if(n.draft.projectId!==r.projectId)throw Error("Draft project cannot be changed");Eg(n.draft);let i=[...new Set(n.suppliedSecretNames??r.suppliedSecretNames)].sort(),c=Fe(n.draft,i).valid?"ready":"draft",d=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=?",[n.draft.name.slice(0,100),n.step,JSON.stringify(n.draft),JSON.stringify(i),c,d,t,e]).changes!==1)throw Error(`Application draft ${t} changed since version ${e}`);return this.controlPlane.appendEvent({organizationId:r.organizationId,projectId:r.projectId,actorId:n.actorId,type:"application.draft.updated",payload:{draftId:t,fromVersion:e,toVersion:e+1,step:n.step,status:c}}),this.get(t)}markApplied(t,e,n){let r=this.get(t);if(!r||r.version!==e)throw Error(`Application draft ${t} changed since version ${e}`);let i=Fe(r.input,r.suppliedSecretNames);if(!i.valid)throw Error(`Draft is not deployable: ${[...i.issues.map((d)=>d.message),...i.missingSecrets.map((d)=>`Missing secret ${d}`)].join("; ")}`);let c=this.now();return this.controlPlane.database.run("UPDATE application_drafts SET status='applied', step='review', version=version+1, updated_at=? WHERE id=? AND version=?",[c,t,e]),this.controlPlane.appendEvent({organizationId:r.organizationId,projectId:r.projectId,actorId:n,type:"application.draft.applied",payload:bt({draftId:t,manifest:i.manifest})}),this.get(t)}}import{createCipheriv as PE,createDecipheriv as $E,createHash as Dg,randomBytes as vE}from"node:crypto";function Oi(t){return typeof t==="string"&&t?t:void 0}function Bo(t){return Dg("sha256").update(t).digest("hex").slice(0,16)}function wg(t){let e=new URL(t.includes("://")?t:`https://${t}`);if(e.protocol!=="https:"&&!["localhost","127.0.0.1","::1"].includes(e.hostname))throw Error("Registry host must use HTTPS");if(e.username||e.password||e.search||e.hash)throw Error("Registry host cannot contain credentials");return`${e.protocol}//${e.host}`}function kE(t){return{id:String(t.id),organizationId:String(t.organization_id),provider:String(t.provider),name:String(t.name),host:String(t.host),credentialConfigured:!!t.credential_ciphertext,credentialFingerprint:Oi(t.credential_fingerprint),credentialExpiresAt:Oi(t.credential_expires_at),status:String(t.status),healthMessage:Oi(t.health_message),lastTestedAt:Oi(t.last_tested_at),version:Number(t.version),createdByActorId:Oi(t.created_by_actor_id),createdAt:String(t.created_at),updatedAt:String(t.updated_at)}}class zo{controlPlane;key;nowFn;idFn;constructor(t,e){this.controlPlane=t;if(!e.encryptionKey)throw Error("Registry encryption key is required");this.key=Dg("sha256").update(`ts-cloud:registry:${e.encryptionKey}`).digest(),this.nowFn=e.now??(()=>new Date),this.idFn=e.id??(()=>crypto.randomUUID())}now(){return this.nowFn().toISOString()}encrypt(t){let e=vE(12),n=PE("aes-256-gcm",this.key,e),r=Buffer.concat([n.update(t,"utf8"),n.final()]);return`v1.${e.toString("base64url")}.${n.getAuthTag().toString("base64url")}.${r.toString("base64url")}`}decrypt(t){let[e,n,r,i]=t.split(".");if(e!=="v1"||!n||!r||!i)throw Error("Registry credential envelope is invalid");let c=$E("aes-256-gcm",this.key,Buffer.from(n,"base64url"));return c.setAuthTag(Buffer.from(r,"base64url")),Buffer.concat([c.update(Buffer.from(i,"base64url")),c.final()]).toString("utf8")}current(t){let e=kE(t);return e.status!=="disconnected"&&e.credentialExpiresAt&&new Date(e.credentialExpiresAt).getTime()<=this.nowFn().getTime()?{...e,status:"expired",healthMessage:"Registry credential expired; rotate it before pulling images."}:e}create(t){if(!["docker_hub","ghcr","ecr","gcr","generic"].includes(t.provider))throw Error("A supported registry provider is required");let e=t.credential?JSON.stringify(t.credential):void 0,n=this.idFn(),r=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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[n,t.organizationId,t.provider,t.name.trim().slice(0,80),wg(t.host),e?this.encrypt(e):null,e?Bo(e):null,t.credentialExpiresAt??null,t.actorId??null,r,r]),this.controlPlane.appendEvent({organizationId:t.organizationId,actorId:t.actorId,type:"registry.connection.created",payload:{connectionId:n,provider:t.provider,host:wg(t.host),credentialConfigured:!!e}}),this.get(n)}get(t){let e=this.controlPlane.database.query("SELECT * FROM registry_connections WHERE id=?").get(t);return e?this.current(e):void 0}list(t){return this.controlPlane.database.query("SELECT * FROM registry_connections WHERE organization_id=? ORDER BY name").all(t).map((e)=>this.current(e))}credential(t){let e=this.controlPlane.database.query("SELECT credential_ciphertext FROM registry_connections WHERE id=?").get(t);return e?.credential_ciphertext?JSON.parse(this.decrypt(String(e.credential_ciphertext))):void 0}rotate(t,e,n={}){let r=this.get(t);if(!r||r.status==="disconnected")throw Error("Registry connection was not found");let i=JSON.stringify(e);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),Bo(i),n.expiresAt??null,this.now(),t]),this.controlPlane.appendEvent({organizationId:r.organizationId,actorId:n.actorId,type:"registry.credential.rotated",payload:{connectionId:t,fingerprint:Bo(i),expiresAt:n.expiresAt??null}}),this.get(t)}disconnect(t,e){let n=this.get(t);if(!n)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(),t]),this.controlPlane.appendEvent({organizationId:n.organizationId,actorId:e,type:"registry.connection.disconnected",level:"warning",payload:{connectionId:t}}),this.get(t)}async test(t,e={}){let n=this.get(t);if(!n||["disconnected","expired"].includes(n.status))throw Error("Active registry connection was not found");let r=this.credential(t),i=e.fetch??fetch,c=new AbortController,d=setTimeout(()=>c.abort(),e.timeoutMs??15000),a=r?.token?`Bearer ${r.token}`:r?.username||r?.password?`Basic ${Buffer.from(`${r.username??""}:${r.password??""}`).toString("base64")}`:void 0;try{let l=await i(`${n.host}/v2/`,{method:"GET",redirect:"error",signal:c.signal,headers:a?{Authorization:a}:void 0}),o=l.headers.get("www-authenticate")??"";if(l.status===401&&o.startsWith("Bearer ")&&r){let R=Object.fromEntries([...o.slice(7).matchAll(/(\w+)="([^"]+)"/g)].map((J)=>[J[1],J[2]])),E=new URL(R.realm??"");if(E.protocol!=="https:")throw Error("Registry authentication realm must use HTTPS");if(R.service)E.searchParams.set("service",R.service);if(e.image)E.searchParams.set("scope",`repository:${yg(e.image).repository}:pull`);let y=await i(E,{signal:c.signal,redirect:"error",headers:a?{Authorization:a}:void 0});if(!y.ok)throw Error(`Registry authentication failed (${y.status})`);let $=await y.json(),C=$.token??$.access_token;if(!C)throw Error("Registry did not return an access token");l=e.image?await Ag(i,n.host,e.image,C,c.signal):await i(`${n.host}/v2/`,{signal:c.signal,redirect:"error",headers:{Authorization:`Bearer ${C}`}})}else if(l.ok&&e.image)l=await Ag(i,n.host,e.image,r?.token,c.signal,a);let u=l.ok?"healthy":"degraded",f=l.ok?e.image?"Registry image is readable.":"Registry connection is healthy.":`Registry request failed (${l.status})`;return this.controlPlane.database.run("UPDATE registry_connections SET status=?, health_message=?, last_tested_at=?, version=version+1, updated_at=? WHERE id=?",[u,f,this.now(),this.now(),t]),this.get(t)}catch(l){let o=c.signal.aborted?"Registry request timed out.":l instanceof Error?l.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(),t]),this.get(t)}finally{clearTimeout(d)}}}function yg(t){let e=t.replace(/^https?:\/\//,""),n=e.indexOf("/");if(n<1)throw Error("Image must include registry/repository");let r=e.slice(n+1),i=r.lastIndexOf("@"),c=r.lastIndexOf(":"),d=i>=0?i:c>r.lastIndexOf("/")?c:-1,a=d>=0?r.slice(0,d):r,l=d>=0?r.slice(d+1):"latest";if(!/^[A-Za-z0-9_.\/-]+$/.test(a)||!/^[A-Za-z0-9_.:+-]+$/.test(l))throw Error("Image reference is invalid");return{repository:a,reference:l}}async function Ag(t,e,n,r,i,c){let d=yg(n);return t(`${e}/v2/${d.repository}/manifests/${encodeURIComponent(d.reference)}`,{method:"HEAD",redirect:"error",signal:i,headers:{Accept:"application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json",...r?{Authorization:`Bearer ${r}`}:c?{Authorization:c}:{}}})}import{createHash as CE}from"node:crypto";import{chmodSync as Pg,existsSync as $g,mkdirSync as OE,renameSync as JE,unlinkSync as vg,writeFileSync as BE}from"node:fs";import{basename as zE,join as TE}from"node:path";function To(t){return{id:String(t.id),organizationId:String(t.organization_id),projectId:String(t.project_id),filename:String(t.filename),sha256:String(t.sha256),size:Number(t.size),format:String(t.format),entryCount:Number(t.entry_count),expandedBytes:Number(t.expanded_bytes),createdByActorId:t.created_by_actor_id?String(t.created_by_actor_id):void 0,createdAt:String(t.created_at)}}class bo{controlPlane;root;idFn;nowFn;constructor(t,e){this.controlPlane=t;this.root=de(e.cwd,"artifacts"),this.idFn=e.id??(()=>crypto.randomUUID()),this.nowFn=e.now??(()=>new Date)}create(t){let e=this.controlPlane.getProject(t.projectId);if(!e||e.organizationId!==t.organizationId)throw Error("Artifact project was not found");let n=zE(t.filename).slice(0,200);if(!n||n!==t.filename)throw Error("Artifact filename must not contain a path");let r=Sg(t.bytes,n),i=CE("sha256").update(t.bytes).digest("hex"),c=this.controlPlane.database.query("SELECT * FROM application_artifacts WHERE project_id=? AND sha256=?").get(t.projectId,i);if(c)return To(c);let d=this.idFn();OE(this.root,{recursive:!0,mode:448}),Pg(this.root,448);let a=TE(this.root,`${d}.archive`),l=`${a}.partial`;try{BE(l,t.bytes,{mode:384,flag:"wx"}),JE(l,a),Pg(a,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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[d,t.organizationId,t.projectId,n,a,i,t.bytes.byteLength,r.format,r.entries,r.expandedBytes,t.actorId??null,this.nowFn().toISOString()])}catch(o){if($g(l))vg(l);if($g(a))vg(a);throw o}return this.controlPlane.appendEvent({organizationId:t.organizationId,projectId:t.projectId,actorId:t.actorId,type:"application.artifact.created",payload:{artifactId:d,filename:n,sha256:i,size:t.bytes.byteLength,entries:r.entries}}),this.get(d)}get(t){let e=this.controlPlane.database.query("SELECT * FROM application_artifacts WHERE id=?").get(t);return e?To(e):void 0}list(t){return this.controlPlane.database.query("SELECT * FROM application_artifacts WHERE project_id=? ORDER BY created_at DESC").all(t).map(To)}}function wc(t){let e=t.drafts.get(t.draftId);if(!e||e.version!==t.expectedVersion)throw Error(`Application draft ${t.draftId} changed since version ${t.expectedVersion}`);if(e.status==="applied")throw Error("Application draft was already applied");let n=t.controlPlane.getProject(e.projectId),r=n?t.controlPlane.listEnvironments(n.id).find((o)=>o.id===e.input.environmentId):void 0;if(!n||!r||r.projectId!==n.id||n.organizationId!==e.organizationId)throw Error("Draft deployment scope was not found");if(t.confirmEnvironment!==r.slug)throw Error(`Type ${r.slug} to confirm this deployment target`);let i=Fe(e.input,e.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 c=t.controlPlane.listResources(n.id,r.id).find((o)=>o.kind==="application"&&o.slug===e.input.slug),d=JSON.parse(JSON.stringify({manifest:i.manifest,configPatch:i.configPatch})),a=c?t.controlPlane.updateResource(c.id,c.version,{name:e.input.name,desiredState:d}):t.controlPlane.createResource({projectId:n.id,environmentId:r.id,kind:"application",slug:e.input.slug,name:e.input.name,desiredState:d,metadata:{source:"application-onboarding",draftId:e.id}}),l=new Ot(t.controlPlane).enqueue({projectId:n.id,environmentId:r.id,resourceId:a.id,actorId:t.actorId,kind:"application.create",idempotencyKey:`application-draft:${e.id}:v${e.version}`,correlationId:`application-draft:${e.id}`,input:d,lockKey:`resource:${a.id}`,providerKey:a.provider??"default",buildSlot:e.input.build.kind!=="prebuilt_image",maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;return t.drafts.markApplied(e.id,e.version,t.actorId),t.controlPlane.appendEvent({organizationId:e.organizationId,projectId:n.id,resourceId:a.id,operationId:l.id,actorId:t.actorId,type:"application.create.queued",payload:{draftId:e.id,environment:r.slug,strategy:e.input.build.kind,costDrivers:i.costDrivers}}),{plan:i,resource:a,operation:l}}function Ji(t){let e=["static","compute","serverless_zip","serverless_image"].includes(t.kind),n=["container","compose"].includes(t.kind)&&(t.replicas??1)>1,r=t.kind==="container"||t.kind==="serverless_zip"||t.kind==="serverless_image",i=(c,d)=>d&&(c==="atomic"?t.kind==="static"||t.hasHealthGate:t.hasHealthGate);return[{strategy:"atomic",supported:i("atomic",e),explanation:e?t.hasHealthGate||t.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",n),explanation:n?t.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",r),explanation:r?t.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",r),explanation:r?t.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 Ac(t,e){let n=Ji(t).find((r)=>r.strategy===e);if(!n.supported)throw Error(`${e} is unavailable: ${n.explanation}`);return n}import{createHash as bE}from"node:crypto";var WE=/^sha256:[a-f0-9]{64}$/,UE=/^[a-f0-9]{40,64}$/i;function nn(t){return typeof t==="string"&&t?t:void 0}function sr(t,e){try{return JSON.parse(String(t))}catch{return e}}function kg(t){return{id:String(t.id),organizationId:String(t.organization_id),digest:String(t.digest),kind:String(t.kind),uri:String(t.uri),size:Number(t.size),mediaType:String(t.media_type),provenance:sr(t.provenance,{}),attestation:sr(t.attestation,{}),verifiedAt:String(t.verified_at),createdAt:String(t.created_at)}}function Cg(t){return{id:String(t.id),organizationId:String(t.organization_id),projectId:String(t.project_id),environmentId:String(t.environment_id),resourceId:String(t.resource_id),artifactId:String(t.artifact_id),kind:String(t.kind),sourceSha:nn(t.source_sha),configHash:String(t.config_hash),manifest:sr(t.manifest,{}),provenance:sr(t.provenance,{}),strategy:String(t.strategy),status:String(t.status),healthGate:t.health_gate==null?void 0:sr(t.health_gate,void 0),hooks:sr(t.hooks,{migrations:"none",preActivate:[],postActivate:[]}),drainSeconds:Number(t.drain_seconds),graceSeconds:Number(t.grace_seconds),automaticRollback:Number(t.automatic_rollback)===1,rollbackAttempts:Number(t.rollback_attempts),previousReleaseId:nn(t.previous_release_id),promotedFromReleaseId:nn(t.promoted_from_release_id),actorId:nn(t.actor_id),trigger:String(t.trigger),pinned:Number(t.pinned)===1,pinReason:nn(t.pin_reason),activatedAt:nn(t.activated_at),failedAt:nn(t.failed_at),createdAt:String(t.created_at),updatedAt:String(t.updated_at)}}function jE(t){return{sequence:Number(t.sequence),id:String(t.id),releaseId:String(t.release_id),fromStatus:nn(t.from_status),toStatus:String(t.to_status),trafficPercent:t.traffic_percent==null?void 0:Number(t.traffic_percent),health:sr(t.health,{}),message:String(t.message),operationId:nn(t.operation_id),createdAt:String(t.created_at)}}function HE(t,e){let n=[],r=(i,c,d)=>{if(JSON.stringify(c)===JSON.stringify(d))return;if(c&&d&&typeof c==="object"&&typeof d==="object"&&!Array.isArray(c)&&!Array.isArray(d)){for(let a of[...new Set([...Object.keys(c),...Object.keys(d)])].sort())r(i?`${i}.${a}`:a,c[a],d[a]);return}n.push({path:i,...c!==void 0?{before:c}:{},...d!==void 0?{after:d}:{}})};return r("",t,e),n}class Wo{controlPlane;now;id;constructor(t,e={}){this.controlPlane=t;this.now=e.now??(()=>new Date),this.id=e.id??(()=>crypto.randomUUID())}registerArtifact(t){if(!WE.test(t.digest)||!/^(?:s3|https|oci|file):/.test(t.uri)||!Number.isInteger(t.size)||t.size<0)throw Error("Artifact requires a SHA-256 digest, supported immutable URI, and non-negative byte size");let e=this.controlPlane.database.query("SELECT * FROM release_artifacts WHERE organization_id=? AND digest=?").get(t.organizationId,t.digest);if(e)return kg(e);let n=this.id(),r=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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[n,t.organizationId,t.digest,t.kind,t.uri,t.size,t.mediaType??"application/octet-stream",JSON.stringify(bt(t.provenance??{})),JSON.stringify(bt(t.attestation??{})),r,r]),this.getArtifact(n)}getArtifact(t){let e=this.controlPlane.database.query("SELECT * FROM release_artifacts WHERE id=?").get(t);return e?kg(e):void 0}create(t){let e=this.getArtifact(t.artifactId),n=this.controlPlane.getResource(t.resourceId),r=this.controlPlane.listEnvironments(t.projectId).find((f)=>f.id===t.environmentId);if(!e||e.organizationId!==t.organizationId||e.kind!==t.kind)throw Error("Release artifact does not match the organization and deployable kind");if(!n||n.projectId!==t.projectId||n.environmentId!==t.environmentId||!r)throw Error("Release target scope does not match the resource");if(t.sourceSha&&!UE.test(t.sourceSha))throw Error("Release source must be an immutable commit SHA");Ac({kind:t.kind,provider:n.provider,hasHealthGate:!!t.healthGate,replicas:t.replicas},t.strategy);let i=bt(t.config),c=bE("sha256").update(JSON.stringify(i)).digest("hex"),d=this.active(t.resourceId),a=this.id(),l=this.now().toISOString(),o=t.approvalRequired?"awaiting_approval":"built",u=t.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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[a,t.organizationId,t.projectId,t.environmentId,t.resourceId,t.artifactId,t.kind,t.sourceSha??null,c,JSON.stringify(bt(t.manifest)),JSON.stringify(bt(t.provenance??{})),t.strategy,o,t.healthGate?JSON.stringify(t.healthGate):null,JSON.stringify(u),Math.max(0,Math.min(3600,Math.floor(t.drainSeconds??30))),Math.max(0,Math.min(3600,Math.floor(t.graceSeconds??30))),t.automaticRollback===!1?0:1,d?.id??null,t.promotedFromReleaseId??null,t.actorId??null,t.trigger??"manual",l,l]),this.recordTransition(a,void 0,o,{message:t.promotedFromReleaseId?"Immutable artifact promoted without rebuild.":"Immutable release record created."}),this.get(a)}get(t){let e=this.controlPlane.database.query("SELECT * FROM releases WHERE id=?").get(t);return e?Cg(e):void 0}list(t={}){return this.controlPlane.database.query("SELECT * FROM releases ORDER BY created_at DESC, rowid DESC").all().map(Cg).filter((e)=>(!t.projectId||e.projectId===t.projectId)&&(!t.environmentId||e.environmentId===t.environmentId)&&(!t.resourceId||e.resourceId===t.resourceId)&&(!t.status||e.status===t.status))}active(t){return this.list({resourceId:t,status:"active"})[0]}transitions(t){return this.controlPlane.database.query("SELECT * FROM release_transitions WHERE release_id=? ORDER BY sequence").all(t).map(jE)}recordTransition(t,e,n,r){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(),t,e??null,n,r.trafficPercent??null,JSON.stringify(bt(r.health??{})),r.message.slice(0,1000),r.operationId??null,this.now().toISOString()])}progress(t,e){let n=this.get(t);if(!n)throw Error(`Release ${t} was not found`);return this.recordTransition(t,n.status,n.status,e),this.transitions(t).at(-1)}transition(t,e,n){let r=this.get(t);if(!r)throw Error(`Release ${t} 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"]}[r.status].includes(e))throw Error(`Invalid release transition ${r.status} → ${e}`);let c=this.now().toISOString();if(e==="active"){let d=this.active(r.resourceId);if(d&&d.id!==t)this.controlPlane.database.run("UPDATE releases SET status='superseded', updated_at=? WHERE id=?",[c,d.id]),this.recordTransition(d.id,"active","superseded",{message:`Superseded by ${t}.`,operationId:n.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=?",[e,e==="rolled_back"?1:0,e,c,e,c,c,t]),this.recordTransition(t,r.status,e,n),this.get(t)}approve(t,e){let n=this.get(t);if(!n||n.status!=="awaiting_approval")throw Error("Release is not awaiting approval");let r=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 (?, ?, ?, ?, ?, ?, ?)",[r,t,n.environmentId,e.decision,e.actorId,e.comment?.slice(0,1000)??null,i]),this.transition(t,e.decision==="approved"?"built":"failed",{message:e.decision==="approved"?"Environment gate approved.":"Environment gate rejected."})}approvals(t){return this.controlPlane.database.query("SELECT * FROM release_approvals WHERE release_id=? ORDER BY created_at").all(t).map((e)=>({id:String(e.id),releaseId:String(e.release_id),environmentId:String(e.environment_id),decision:String(e.decision),actorId:String(e.actor_id),comment:nn(e.comment),createdAt:String(e.created_at)}))}promote(t,e){let n=this.get(t);if(!n||!["active","superseded"].includes(n.status))throw Error("Only a tested active/superseded release can be promoted");return this.create({organizationId:n.organizationId,projectId:n.projectId,environmentId:e.targetEnvironmentId,resourceId:e.targetResourceId,artifactId:n.artifactId,kind:n.kind,sourceSha:n.sourceSha,config:e.config,manifest:n.manifest,provenance:n.provenance,strategy:e.strategy??n.strategy,healthGate:e.healthGate??n.healthGate,hooks:n.hooks,drainSeconds:n.drainSeconds,graceSeconds:n.graceSeconds,automaticRollback:n.automaticRollback,promotedFromReleaseId:n.id,actorId:e.actorId,trigger:"promotion",approvalRequired:e.approvalRequired})}compare(t,e){let n=this.get(t),r=this.get(e);if(!n||!r)throw Error("Both releases are required for comparison");return{artifactChanged:n.artifactId!==r.artifactId,sourceChanged:n.sourceSha!==r.sourceSha,configChanged:n.configHash!==r.configHash,manifestChanges:HE(n.manifest,r.manifest),dataCaveat:r.hooks.migrations==="none"?"No database migration is recorded.":`Database hooks are ${r.hooks.migrations}; release rollback does not roll back data.`}}pin(t,e,n){if(!this.get(t))throw Error("Release was not found");return this.controlPlane.database.run("UPDATE releases SET pinned=?, pin_reason=?, updated_at=? WHERE id=?",[e?1:0,e?n?.slice(0,500)??"operator":null,this.now().toISOString(),t]),this.get(t)}retentionCandidates(t){let e=Math.max(1,Math.min(100,Math.floor(t.keepPerResource??10))),n=new Map;for(let r of this.list()){let i=n.get(r.resourceId)??[];i.push(r),n.set(r.resourceId,i)}return[...n.values()].flatMap((r)=>r.slice(e)).filter((r)=>new Date(r.createdAt)<t.before&&!r.pinned&&!["active","activating","awaiting_approval"].includes(r.status)&&!this.list().some((i)=>i.previousReleaseId===r.id&&["active","activating"].includes(i.status)))}}class lr{controlPlane;releases;queue;constructor(t){this.controlPlane=t;this.releases=new Wo(t),this.queue=new Ot(t)}enqueueActivation(t,e={}){let n=this.releases.get(t.id);if(!n)throw Error("Release was not found");if(!["built","failed","rolled_back","superseded"].includes(n.status))throw Error(`Release ${n.status} cannot be activated`);let r=e.action??"activate",i=this.queue.enqueue({projectId:n.projectId,environmentId:n.environmentId,resourceId:n.resourceId,actorId:e.actorId,kind:`release.${r}`,idempotencyKey:`release:${n.id}:${r}:${n.rollbackAttempts}`,correlationId:`release:${n.id}`,input:{releaseId:n.id,targetReleaseId:e.targetReleaseId??null},lockKey:`resource:${n.resourceId}`,providerKey:this.controlPlane.getResource(n.resourceId)?.provider??"default",maxAttempts:n.automaticRollback?2:1,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:365}).operation;return this.releases.transition(n.id,"activating",{message:`${r} queued.`,operationId:i.id,trafficPercent:0}),i}completeHealthGate(t,e){let n=this.releases.get(t);if(!n||n.status!=="activating")throw Error("Release is not activating");if(e.healthy)return{release:this.releases.transition(n.id,"active",{message:e.message??"Health gate passed; activation completed.",operationId:e.operationId,trafficPercent:100,health:e.health})};let r=this.releases.transition(n.id,"failed",{message:e.message??"Health gate failed.",operationId:e.operationId,trafficPercent:0,health:e.health}),i=n.previousReleaseId?this.releases.get(n.previousReleaseId):void 0;if(!n.automaticRollback||n.rollbackAttempts>=1||!i)return{release:r};let c=this.queue.enqueue({projectId:n.projectId,environmentId:n.environmentId,resourceId:n.resourceId,kind:"release.rollback",idempotencyKey:`release:${n.id}:automatic-rollback`,correlationId:`release:${n.id}`,input:{releaseId:n.id,targetReleaseId:i.id,automatic:!0},lockKey:`resource:${n.resourceId}`,providerKey:this.controlPlane.getResource(n.resourceId)?.provider??"default",maxAttempts:1,retryClasses:[],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:365}).operation;return{release:r,rollbackOperation:c}}enqueueRollback(t,e={}){let n=this.releases.get(t.id);if(!n||n.status!=="active")throw Error("Only the active release can be rolled back");let r=e.targetReleaseId?this.releases.get(e.targetReleaseId):n.previousReleaseId?this.releases.get(n.previousReleaseId):void 0;if(!r||r.resourceId!==n.resourceId||!["superseded","active"].includes(r.status))throw Error("Rollback requires a preserved prior release for the same resource");return this.queue.enqueue({projectId:n.projectId,environmentId:n.environmentId,resourceId:n.resourceId,actorId:e.actorId,kind:"release.rollback",idempotencyKey:`release:${n.id}:manual-rollback:${r.id}`,correlationId:`release:${n.id}`,input:{releaseId:n.id,targetReleaseId:r.id,automatic:!1},lockKey:`resource:${n.resourceId}`,providerKey:this.controlPlane.getResource(n.resourceId)?.provider??"default",maxAttempts:1,retryClasses:[],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:365}).operation}}function LE(t){if(t.strategy==="canary")return[5,25,50,100].map((e,n)=>({step:`canary-${e}`,trafficPercent:e,waitSeconds:n===3?t.drainSeconds:t.graceSeconds,requiresHealth:!0}));if(t.strategy==="blue_green")return[{step:"green-health",trafficPercent:0,waitSeconds:t.graceSeconds,requiresHealth:!0},{step:"traffic-switch",trafficPercent:100,waitSeconds:t.drainSeconds,requiresHealth:!0}];if(t.strategy==="rolling")return[{step:"rolling-replacement",trafficPercent:50,waitSeconds:t.graceSeconds,requiresHealth:!0},{step:"rolling-complete",trafficPercent:100,waitSeconds:t.drainSeconds,requiresHealth:!0}];return[{step:"immutable-switch",trafficPercent:100,waitSeconds:t.drainSeconds,requiresHealth:!!t.healthGate}]}async function Og(t,e){if(e.release.artifactId!==e.artifact.id)throw Error("Release activation artifact identity changed");Ac({kind:e.release.kind,hasHealthGate:!!e.release.healthGate,replicas:Number(e.release.manifest?.replicas)||void 0},e.release.strategy);let n=t.capability(e);if(!n.supported)throw Error(`${e.release.strategy} is unavailable in ${t.name}: ${n.explanation}`);return t.activate({...e,transitions:LE(e.release)})}async function Jg(t,e){if(!e.previous)throw Error("Rollback requires the preserved previous release");return t.rollback({...e,transitions:[{step:"rollback",trafficPercent:0,waitSeconds:e.release.drainSeconds,requiresHealth:!0}]})}var FE=["release.activate","release.rollback"];function VE(t){return t&&typeof t==="object"&&!Array.isArray(t)?t:{}}function Bg(t){let e=new lr(t.store),n=async(r)=>{let i=VE(r.operation.input),c=typeof i.releaseId==="string"?i.releaseId:"",d=e.releases.get(c);if(!d)throw Error(`Queued release ${c||"(missing)"} was not found`);if(d.projectId!==r.operation.projectId||d.environmentId!==r.operation.environmentId||d.resourceId!==r.operation.resourceId)throw Error("Queued release does not match the operation scope");let a=e.releases.getArtifact(d.artifactId);if(!a||a.digest!==e.releases.getArtifact(d.artifactId)?.digest)throw Error("Immutable release artifact is unavailable");let l=typeof i.targetReleaseId==="string"&&i.targetReleaseId?i.targetReleaseId:d.previousReleaseId,o=l?e.releases.get(l):void 0;if(o&&(o.resourceId!==d.resourceId||o.artifactId===d.artifactId&&o.id===d.id))throw Error("Rollback target does not match the release resource");let u=await t.resolveDriver(d);r.checkpoint("verify",`Verifying ${a.digest} and ${d.configHash} for ${u.name}.`),r.log(`Artifact ${a.digest}; source ${d.sourceSha??"not recorded"}; config ${d.configHash}.`,{stream:"system"}),r.throwIfCancellationRequested();let f;try{f=r.operation.kind==="release.rollback"?await Jg(u,{release:d,artifact:a,previous:o}):await Og(u,{release:d,artifact:a,previous:o})}catch(R){if(r.operation.kind==="release.activate"&&e.releases.get(d.id)?.status==="activating")e.completeHealthGate(d.id,{healthy:!1,operationId:r.operation.id,message:R instanceof Error?R.message:String(R)});throw R}for(let R of f.transitions)e.releases.progress(d.id,{message:`${r.operation.kind==="release.rollback"?"Rollback":"Activation"} traffic at ${R.trafficPercent}%.`,trafficPercent:R.trafficPercent,health:R.observed,operationId:r.operation.id}),r.log(`Traffic ${R.trafficPercent}%: ${R.healthy?"healthy":"unhealthy"}.`,{stream:R.healthy?"step":"stderr",step:"health"});if(r.checkpoint("health","Evaluating the provider health result."),!f.activated||!f.healthy){if(r.operation.kind==="release.activate"&&e.releases.get(d.id)?.status==="activating")e.completeHealthGate(d.id,{healthy:!1,operationId:r.operation.id,health:{resourceVersions:f.resourceVersions},message:f.error??"Provider health gate failed."});throw Error(f.error??`${u.name} reported an unhealthy release`)}if(r.operation.kind==="release.activate"&&d.healthGate?.name){if(!t.resolveHealthGate)throw e.completeHealthGate(d.id,{healthy:!1,operationId:r.operation.id,message:`Named health gate ${d.healthGate.name} is not available to this worker.`}),Error(`Named health gate ${d.healthGate.name} is unavailable`);r.checkpoint("named-health-gate",`Waiting on ${d.healthGate.name}.`);let R=await t.resolveHealthGate(d.healthGate.name,d);if(r.log(`${d.healthGate.name}: ${R.healthy?"healthy":"unhealthy"}${R.message?` — ${R.message}`:""}.`,{stream:R.healthy?"step":"stderr",step:"health"}),!R.healthy)throw e.completeHealthGate(d.id,{healthy:!1,operationId:r.operation.id,health:R.evidence,message:R.message??`Named health gate ${d.healthGate.name} failed.`}),Error(R.message??`Named health gate ${d.healthGate.name} failed`)}if(r.operation.kind==="release.rollback"){let R=e.releases.get(d.id);if(R.status!=="rolled_back")e.releases.transition(R.id,"rolled_back",{message:`Traffic restored through ${u.name}.`,operationId:r.operation.id,trafficPercent:0,health:{resourceVersions:f.resourceVersions}});if(o&&o.status!=="active"){let E=o.status==="activating"?o:e.releases.transition(o.id,"activating",{message:"Rollback target restoring traffic.",operationId:r.operation.id,trafficPercent:0});e.releases.transition(E.id,"active",{message:"Previous immutable release restored.",operationId:r.operation.id,trafficPercent:100,health:{resourceVersions:f.resourceVersions}})}}else e.completeHealthGate(d.id,{healthy:!0,operationId:r.operation.id,health:{providerVersion:f.providerVersion??null,resourceVersions:f.resourceVersions},message:"Provider activation and health gates completed."});return r.checkpoint("finalize","Persisted the terminal release state."),{releaseId:d.id,artifactDigest:a.digest,provider:u.name,providerVersion:f.providerVersion??null,resourceVersions:f.resourceVersions,status:e.releases.get(d.id).status}};return Object.fromEntries(FE.map((r)=>[r,n]))}import{createCipheriv as NE,createDecipheriv as xE,createHash as Ug,randomBytes as Uo}from"node:crypto";var jg={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 Pt(t){return typeof t==="string"&&t?t:void 0}function ur(t,e){try{return typeof t==="string"?JSON.parse(t):e}catch{return e}}function rn(t){return JSON.stringify(bt(t))}function gr(t){return Ug("sha256").update(t).digest("hex")}function zg(t){let e=t.trim().replace(/\/$/,""),n=new URL(e.includes("://")?e:`https://${e}`);if(n.username||n.password||n.search||n.hash)throw Error("Source host cannot contain credentials, a query, or a fragment");if(n.protocol!=="https:"&&!(n.protocol==="http:"&&["localhost","127.0.0.1","::1"].includes(n.hostname)))throw Error("Source host must use HTTPS");return`${n.protocol}//${n.host}${n.pathname.replace(/\/$/,"")}`}function Tg(t){let e=t.trim();if(e.length<2||e.length>80)throw Error("Connection name must contain 2-80 characters");return e}function jo(t){let e=t.trim().replace(/^\/+|\/+$/g,"");if(!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(e))throw Error("Repository must use owner/name format");return e}function bg(t){let e=t.trim()||".";if(e.startsWith("/")||e.split("/").includes("..")||/[\0\r\n]/.test(e))throw Error("Monorepo root must stay inside the repository");return e.replace(/^\.\//,"")||"."}function Dc(t){return[...new Set((t??[]).map((e)=>e.trim()).filter(Boolean))].slice(0,100)}function ME(t){let e=t.trim();if(/\r|\n/.test(e)||/https?:\/\/[^/@\s]+:[^/@\s]+@/i.test(e))throw Error("Clone URL cannot contain credentials or control characters");if(!/^(?:https?:\/\/|ssh:\/\/|git@[A-Za-z0-9.-]+:)/.test(e))throw Error("Clone URL must use HTTPS or SSH");return e}function QE(t){return{id:String(t.id),organizationId:String(t.organization_id),provider:String(t.provider),name:String(t.name),host:String(t.host),owner:Pt(t.owner),authKind:String(t.auth_kind),credentialConfigured:!!t.credential_ciphertext,credentialFingerprint:Pt(t.credential_fingerprint),grantedScopes:ur(t.granted_scopes,[]),capabilities:ur(t.capabilities,jg[String(t.provider)]),status:String(t.status),healthMessage:Pt(t.health_message),lastTestedAt:Pt(t.last_tested_at),lastSyncedAt:Pt(t.last_synced_at),credentialExpiresAt:Pt(t.credential_expires_at),version:Number(t.version),createdByActorId:Pt(t.created_by_actor_id),createdAt:String(t.created_at),updatedAt:String(t.updated_at)}}function Ho(t){return{id:String(t.id),connectionId:String(t.connection_id),providerRepositoryId:String(t.provider_repository_id),fullName:String(t.full_name),cloneUrl:String(t.clone_url),defaultBranch:String(t.default_branch),visibility:String(t.visibility),archived:Number(t.archived)===1,metadata:ur(t.metadata,{}),syncedAt:String(t.synced_at)}}function Wg(t){return{id:String(t.id),projectId:String(t.project_id),environmentId:Pt(t.environment_id),resourceId:Pt(t.resource_id),connectionId:String(t.connection_id),repositoryId:Pt(t.repository_id),repositoryFullName:String(t.repository_full_name),defaultBranch:String(t.default_branch),branchRule:Pt(t.branch_rule),tagRule:Pt(t.tag_rule),monorepoRoot:String(t.monorepo_root),includePaths:ur(t.include_paths,[]),excludePaths:ur(t.exclude_paths,[]),submodules:Number(t.submodules)===1,cloneDepth:t.clone_depth==null?void 0:Number(t.clone_depth),deployKeyId:Pt(t.deploy_key_id),autoDeploy:Number(t.auto_deploy)===1,pullRequestPreviews:Number(t.pull_request_previews)===1,status:String(t.status),disabledReason:Pt(t.disabled_reason),version:Number(t.version),createdByActorId:Pt(t.created_by_actor_id),createdAt:String(t.created_at),updatedAt:String(t.updated_at)}}function Lo(t){return{id:String(t.id),connectionId:String(t.connection_id),name:String(t.name),publicKey:String(t.public_key),publicKeyFingerprint:String(t.public_key_fingerprint),host:String(t.host),hostKey:String(t.host_key),hostKeyFingerprint:String(t.host_key_fingerprint),createdByActorId:Pt(t.created_by_actor_id),createdAt:String(t.created_at),updatedAt:String(t.updated_at)}}function Fo(t){return{id:String(t.id),connectionId:String(t.connection_id),repositoryId:Pt(t.repository_id),repositoryFullName:String(t.repository_full_name),providerWebhookId:Pt(t.provider_webhook_id),events:ur(t.events,[]),status:String(t.status),healthMessage:Pt(t.health_message),lastDeliveryAt:Pt(t.last_delivery_at),lastReconciledAt:Pt(t.last_reconciled_at),createdAt:String(t.created_at),updatedAt:String(t.updated_at)}}function Vo(t){return{id:String(t.id),connectionId:String(t.connection_id),webhookId:String(t.webhook_id),providerDeliveryId:String(t.provider_delivery_id),event:String(t.event),action:Pt(t.action),commitSha:Pt(t.commit_sha),signatureStatus:String(t.signature_status),status:String(t.status),payloadSummary:ur(t.payload_summary,{}),operationId:Pt(t.operation_id),error:Pt(t.error),receivedAt:String(t.received_at),processedAt:Pt(t.processed_at)}}class No{controlPlane;key;nowFn;idFn;constructor(t,e={}){this.controlPlane=t;this.key=e.encryptionKey?Ug("sha256").update(e.encryptionKey).digest():void 0,this.nowFn=e.now??(()=>new Date),this.idFn=e.id??(()=>crypto.randomUUID())}now(){return this.nowFn().toISOString()}run(t,e){this.controlPlane.database.run(t,e)}encrypt(t){if(!this.key)throw Error("Source credential encryption key is not configured");let e=Uo(12),n=NE("aes-256-gcm",this.key,e),r=Buffer.concat([n.update(t,"utf8"),n.final()]);return`v1.${e.toString("base64url")}.${n.getAuthTag().toString("base64url")}.${r.toString("base64url")}`}decrypt(t){if(!this.key)throw Error("Source credential encryption key is not configured");let[e,n,r,i]=t.split(".");if(e!=="v1"||!n||!r||!i)throw Error("Encrypted source credential is unavailable");let c=xE("aes-256-gcm",this.key,Buffer.from(n,"base64url"));return c.setAuthTag(Buffer.from(r,"base64url")),Buffer.concat([c.update(Buffer.from(i,"base64url")),c.final()]).toString("utf8")}createConnection(t){if(!this.controlPlane.getOrganization(t.organizationId))throw Error("Source connection organization was not found");let e=this.now(),n=this.idFn(),r=t.credential?JSON.stringify(t.credential):void 0;return this.run(`INSERT INTO source_connections (id, organization_id, provider, name, host, owner, auth_kind, credential_ciphertext, credential_fingerprint, granted_scopes, capabilities, status, credential_expires_at, created_by_actor_id, created_at, updated_at)
|
|
3
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?, ?, ?)`,[n,t.organizationId,t.provider,Tg(t.name),zg(t.host),t.owner?.trim()||null,t.authKind??(r?"access_token":"none"),r?this.encrypt(r):null,r?gr(r).slice(0,16):null,rn([...new Set(t.grantedScopes??[])].sort()),rn(jg[t.provider]),t.credentialExpiresAt??null,t.createdByActorId??null,e,e]),this.controlPlane.appendEvent({organizationId:t.organizationId,actorId:t.createdByActorId,type:"source.connection.created",payload:{connectionId:n,provider:t.provider,host:zg(t.host),owner:t.owner??null,scopes:t.grantedScopes??[]}}),this.getConnection(n)}getConnection(t){let e=this.controlPlane.database.query("SELECT * FROM source_connections WHERE id = ?").get(t);return e?this.currentConnection(e):void 0}listConnections(t){return this.controlPlane.database.query("SELECT * FROM source_connections WHERE organization_id = ? ORDER BY name").all(t).map((e)=>this.currentConnection(e))}currentConnection(t){let e=QE(t);if(e.status!=="disconnected"&&e.credentialExpiresAt&&new Date(e.credentialExpiresAt).getTime()<=this.nowFn().getTime())return{...e,status:"expired",healthMessage:"Source credential expired; rotate it before deploying."};return e}getCredential(t){let e=this.controlPlane.database.query("SELECT credential_ciphertext FROM source_connections WHERE id = ?").get(t);return e?.credential_ciphertext?JSON.parse(this.decrypt(String(e.credential_ciphertext))):void 0}rotateCredential(t,e,n={}){let r=this.getConnection(t);if(!r||r.status==="disconnected")throw Error("Active source connection was not found");let i=JSON.stringify(e);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),gr(i).slice(0,16),n.expiresAt??null,this.now(),t]),this.controlPlane.appendEvent({organizationId:r.organizationId,actorId:n.actorId,type:"source.credential.rotated",payload:{connectionId:t,fingerprint:gr(i).slice(0,16),expiresAt:n.expiresAt??null}}),this.getConnection(t)}updateHealth(t,e){let n=this.getConnection(t);if(!n||["disconnected","expired"].includes(n.status))throw Error("Active source connection was not found");let r=this.now(),i=e.grantedScopes?[...new Set(e.grantedScopes.map((c)=>c.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 = ?",[e.status,e.message?.slice(0,1000)??null,i?rn(i):null,e.tested?r:null,e.synced?r:null,r,t]),i&&JSON.stringify(i)!==JSON.stringify([...n.grantedScopes].sort()))this.controlPlane.appendEvent({organizationId:n.organizationId,type:"source.connection.scopes_updated",payload:{connectionId:t,grantedScopes:i}});return this.getConnection(t)}upsertRepository(t){let e=this.getConnection(t.connectionId);if(!e||["disconnected","expired"].includes(e.status))throw Error("Active source connection was not found");let n=this.now(),r=this.controlPlane.database.query("SELECT id FROM source_repositories WHERE connection_id = ? AND provider_repository_id = ?").get(t.connectionId,t.providerRepositoryId),i=r?String(r.id):this.idFn();return this.run(`INSERT INTO source_repositories (id, connection_id, provider_repository_id, full_name, clone_url, default_branch, visibility, archived, metadata, synced_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
4
|
-
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,t.connectionId,t.providerRepositoryId,jo(t.fullName),ME(t.cloneUrl),t.defaultBranch.trim()||"main",t.visibility,t.archived?1:0,rn(t.metadata),n]),Ho(this.controlPlane.database.query("SELECT * FROM source_repositories WHERE id = ?").get(i))}listRepositories(t,e,n=100){let r=e?.trim().toLowerCase();return(r?this.controlPlane.database.query("SELECT * FROM source_repositories WHERE connection_id = ? AND lower(full_name) LIKE ? ORDER BY full_name LIMIT ?").all(t,`%${r}%`,Math.min(500,n)):this.controlPlane.database.query("SELECT * FROM source_repositories WHERE connection_id = ? ORDER BY full_name LIMIT ?").all(t,Math.min(500,n))).map(Ho)}getRepository(t){let e=this.controlPlane.database.query("SELECT * FROM source_repositories WHERE id = ?").get(t);return e?Ho(e):void 0}createDeployKey(t){let e=this.getConnection(t.connectionId);if(!e||["disconnected","expired"].includes(e.status)||!e.capabilities.deployKeys)throw Error("An active deploy-key capable source connection is required");if(!/^ssh-(?:ed25519|rsa)\s+[A-Za-z0-9+/=]+/.test(t.publicKey.trim()))throw Error("A valid SSH public key is required");if(!/BEGIN (?:OPENSSH|RSA) PRIVATE KEY/.test(t.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(t.hostKey.trim()))throw Error("A pinned SSH host key is required");let n=this.idFn(),r=this.now(),i=`sha256:${gr(t.publicKey.trim())}`,c=`sha256:${gr(t.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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[n,t.connectionId,Tg(t.name),t.publicKey.trim(),i,this.encrypt(t.privateKey),t.host.trim().toLowerCase(),t.hostKey.trim(),c,t.actorId??null,r,r]),this.controlPlane.appendEvent({organizationId:e.organizationId,actorId:t.actorId,type:"source.deploy_key.created",payload:{connectionId:t.connectionId,deployKeyId:n,publicFingerprint:i,hostFingerprint:c}}),Lo(this.controlPlane.database.query("SELECT * FROM source_deploy_keys WHERE id = ?").get(n))}getDeployKey(t){let e=this.controlPlane.database.query("SELECT * FROM source_deploy_keys WHERE id = ?").get(t);return e?Lo(e):void 0}listDeployKeys(t){return this.controlPlane.database.query("SELECT * FROM source_deploy_keys WHERE connection_id = ? ORDER BY name, created_at").all(t).map(Lo)}revokeDeployKey(t,e){let n=this.getDeployKey(t),r=n?this.getConnection(n.connectionId):void 0;if(!n||!r)throw Error("Deploy key was not found");let i=this.listBindings({connectionId:r.id}).filter((d)=>d.deployKeyId===t),c=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=?",[c,t]),this.run("DELETE FROM source_deploy_keys WHERE id=?",[t])})(),this.controlPlane.appendEvent({organizationId:r.organizationId,actorId:e,type:"source.deploy_key.revoked",level:"warning",payload:{connectionId:r.id,deployKeyId:t,affectedBindingIds:i.map((d)=>d.id)}}),{affectedBindings:i}}getDeployPrivateKey(t){let e=this.controlPlane.database.query("SELECT private_key_ciphertext FROM source_deploy_keys WHERE id = ?").get(t);if(!e)throw Error("Deploy key was not found");return this.decrypt(String(e.private_key_ciphertext))}createBinding(t){let e=this.getConnection(t.connectionId);if(!e||["disconnected","expired"].includes(e.status))throw Error("Active source connection was not found");if(t.repositoryId&&this.getRepository(t.repositoryId)?.connectionId!==e.id)throw Error("Repository does not belong to this connection");if(t.deployKeyId&&this.getDeployKey(t.deployKeyId)?.connectionId!==e.id)throw Error("Deploy key does not belong to this connection");let n=this.idFn(),r=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)
|
|
5
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, ?, ?)`,[n,t.projectId,t.environmentId??null,t.resourceId??null,t.connectionId,t.repositoryId??null,jo(t.repositoryFullName),t.defaultBranch?.trim()||"main",t.branchRule?.trim()||null,t.tagRule?.trim()||null,bg(t.monorepoRoot??"."),rn(Dc(t.includePaths)),rn(Dc(t.excludePaths)),t.submodules?1:0,t.cloneDepth??null,t.deployKeyId??null,t.autoDeploy===!1?0:1,t.pullRequestPreviews===!1?0:1,t.actorId??null,r,r]),this.controlPlane.appendEvent({organizationId:e.organizationId,projectId:t.projectId,actorId:t.actorId,type:"source.binding.created",payload:{bindingId:n,connectionId:t.connectionId,repository:t.repositoryFullName,branch:t.defaultBranch??"main"}}),this.getBinding(n)}getBinding(t){let e=this.controlPlane.database.query("SELECT * FROM source_bindings WHERE id = ?").get(t);return e?Wg(e):void 0}listBindings(t={}){return this.controlPlane.database.query("SELECT * FROM source_bindings ORDER BY created_at DESC").all().map(Wg).filter((n)=>(!t.connectionId||n.connectionId===t.connectionId)&&(!t.projectId||n.projectId===t.projectId)&&(!t.status||n.status===t.status))}updateBinding(t,e,n){let r=this.getBinding(t);if(!r||r.version!==e)throw Error(`Source binding ${t} changed since version ${e}`);let i=this.getConnection(r.connectionId);if((!i||["disconnected","expired"].includes(i.status))&&(n.status==="active"||n.autoDeploy===!0))throw Error("Rotate or reconnect the source credential before enabling this binding");if(n.deployKeyId&&this.getDeployKey(n.deployKeyId)?.connectionId!==r.connectionId)throw Error("Deploy key does not belong to this connection");let c=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=?",[n.defaultBranch?.trim()||r.defaultBranch,n.branchRule===void 0?r.branchRule??null:n.branchRule.trim()||null,n.tagRule===void 0?r.tagRule??null:n.tagRule.trim()||null,n.monorepoRoot===void 0?r.monorepoRoot:bg(n.monorepoRoot),rn(n.includePaths===void 0?r.includePaths:Dc(n.includePaths)),rn(n.excludePaths===void 0?r.excludePaths:Dc(n.excludePaths)),n.submodules??r.submodules?1:0,n.cloneDepth===void 0?r.cloneDepth??null:n.cloneDepth,n.deployKeyId===void 0?r.deployKeyId??null:n.deployKeyId,n.autoDeploy??r.autoDeploy?1:0,n.pullRequestPreviews??r.pullRequestPreviews?1:0,n.status??r.status,n.disabledReason===void 0?r.disabledReason??null:n.disabledReason.slice(0,1000),c,t,e]).changes!==1)throw Error(`Source binding ${t} changed since version ${e}`);let a=this.getConnection(r.connectionId);return this.controlPlane.appendEvent({organizationId:a.organizationId,projectId:r.projectId,actorId:n.actorId,type:"source.binding.updated",payload:{bindingId:t,fromVersion:e,toVersion:e+1,status:n.status??r.status}}),this.getBinding(t)}createWebhook(t){let e=this.getConnection(t.connectionId);if(!e||["disconnected","expired"].includes(e.status))throw Error("Active source connection was not found");if(t.repositoryId&&this.getRepository(t.repositoryId)?.connectionId!==e.id)throw Error("Repository does not belong to this connection");let n=this.idFn(),r=this.now(),i=t.endpointToken??Uo(24).toString("base64url"),c=t.secret??Uo(32).toString("base64url"),d=[...new Set(t.events??["push","pull_request"])].filter((a)=>["push","pull_request"].includes(a));if(!d.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', ?, ?)",[n,t.connectionId,t.repositoryId??null,jo(t.repositoryFullName),gr(i),this.encrypt(i),this.encrypt(c),rn(d),r,r]),this.controlPlane.appendEvent({organizationId:e.organizationId,type:"source.webhook.created",payload:{webhookId:n,connectionId:e.id,repository:t.repositoryFullName,events:d}}),{webhook:{...this.getWebhook(n),endpointToken:i},secret:c}}getWebhook(t){let e=this.controlPlane.database.query("SELECT * FROM source_webhooks WHERE id = ?").get(t);return e?Fo(e):void 0}getWebhookByEndpointToken(t){let e=this.controlPlane.database.query("SELECT * FROM source_webhooks WHERE endpoint_token_hash = ?").get(gr(t));return e?Fo(e):void 0}getWebhookSecret(t){let e=this.controlPlane.database.query("SELECT secret_ciphertext FROM source_webhooks WHERE id = ?").get(t);if(!e)throw Error("Source webhook was not found");return this.decrypt(String(e.secret_ciphertext))}getWebhookEndpointToken(t){let e=this.controlPlane.database.query("SELECT endpoint_token_ciphertext FROM source_webhooks WHERE id = ?").get(t);if(!e?.endpoint_token_ciphertext)throw Error("Source webhook endpoint token is unavailable");return this.decrypt(String(e.endpoint_token_ciphertext))}listWebhooks(t){return this.controlPlane.database.query("SELECT * FROM source_webhooks WHERE connection_id = ? ORDER BY repository_full_name").all(t).map(Fo)}updateWebhookState(t,e){let n=this.getWebhook(t);if(!n)throw Error("Source webhook was not found");let r=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=?",[e.providerWebhookId??null,e.status,e.healthMessage?.slice(0,1000)??null,e.reconciled?r:null,r,t]);let i=this.getConnection(n.connectionId);if(i)this.controlPlane.appendEvent({organizationId:i.organizationId,type:"source.webhook.updated",payload:{webhookId:t,connectionId:i.id,repository:n.repositoryFullName,status:e.status,reconciled:e.reconciled??!1,providerWebhookId:e.providerWebhookId??n.providerWebhookId??null}});return this.getWebhook(t)}getDeliveryByProviderId(t,e){let n=this.controlPlane.database.query("SELECT * FROM source_webhook_deliveries WHERE connection_id = ? AND provider_delivery_id = ?").get(t,e);return n?Vo(n):void 0}recordDelivery(t){let e=this.getDeliveryByProviderId(t.connectionId,t.providerDeliveryId);if(e)return{delivery:e,duplicate:!0};let n=this.idFn(),r=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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[n,t.connectionId,t.webhookId,t.providerDeliveryId,t.event.slice(0,100),t.action?.slice(0,100)??null,t.commitSha?.slice(0,128)??null,t.signatureStatus,t.status,rn(t.payloadSummary??{}),t.operationId??null,t.error?.slice(0,2000)??null,r,["enqueued","ignored","rejected","failed"].includes(t.status)?r:null]),this.run("UPDATE source_webhooks SET last_delivery_at=?, updated_at=? WHERE id=?",[r,r,t.webhookId])})(),{delivery:this.getDeliveryByProviderId(t.connectionId,t.providerDeliveryId),duplicate:!1}}updateDelivery(t,e){this.run("UPDATE source_webhook_deliveries SET status=?, operation_id=?, error=?, processed_at=? WHERE id=?",[e.status,e.operationId??null,e.error?.slice(0,2000)??null,this.now(),t]);let n=this.controlPlane.database.query("SELECT * FROM source_webhook_deliveries WHERE id = ?").get(t);if(!n)throw Error("Source webhook delivery was not found");return Vo(n)}listDeliveries(t,e=100){return this.controlPlane.database.query("SELECT * FROM source_webhook_deliveries WHERE webhook_id = ? ORDER BY received_at DESC LIMIT ?").all(t,Math.min(500,Math.max(1,e))).map(Vo)}disconnectConnection(t,e){let n=this.getConnection(t);if(!n)throw Error("Source connection was not found");let r=this.listBindings({connectionId:t,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,t]),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,t]),this.run("UPDATE source_webhooks SET status='disabled', health_message='Source connection was disconnected', updated_at=? WHERE connection_id=?",[i,t])})(),this.controlPlane.appendEvent({organizationId:n.organizationId,actorId:e,type:"source.connection.disconnected",level:"warning",payload:{connectionId:t,affectedBindingIds:r.map((c)=>c.id),affectedRepositories:r.map((c)=>c.repositoryFullName)}}),{connection:this.getConnection(t),affectedBindings:r}}}import{createSign as GE}from"node:crypto";class xr extends Error{status;retryAfterSeconds;constructor(t,e,n){super(t);this.status=e;this.retryAfterSeconds=n;this.name="SourceProviderError"}}var Lg={repositories:!0,branches:!0,tags:!0,webhooks:!0,pullRequests:!0,tokenRefresh:!0,deployKeys:!0};function Vn(t){let e=Number(t??"1");return Number.isInteger(e)&&e>0?e:1}function Nn(t){return Math.max(1,Math.min(100,t??50))}function ze(t){let e=t.trim().replace(/^\/+|\/+$/g,"");if(!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(e))throw Error("Repository must use owner/name format");return e}function Bi(t){let e=new URL(t);if(e.username||e.password||e.protocol!=="https:")throw Error("Webhook endpoint must be credential-free HTTPS");return e.href}function Hg(t){return Buffer.from(t).toString("base64url")}function ZE(t,e){if(!t.appId||!t.privateKey)throw Error("GitHub App credentials require appId and privateKey");let n=Hg(JSON.stringify({alg:"RS256",typ:"JWT"})),r=Math.floor(e.getTime()/1000)-30,i=Hg(JSON.stringify({iat:r,exp:r+540,iss:t.appId})),c=GE("RSA-SHA256");return c.update(`${n}.${i}`),c.end(),`${n}.${i}.${c.sign(t.privateKey).toString("base64url")}`}class zi{connection;credential;capabilities=Lg;fetchFn;timeoutMs;nowFn;constructor(t,e,n={}){this.connection=t;this.credential=e;this.fetchFn=n.fetch??((r,i)=>globalThis.fetch(r,i)),this.timeoutMs=Math.max(100,n.timeoutMs??20000),this.nowFn=n.now??(()=>new Date)}async request(t,e={}){let n=new URL(`${this.apiRoot().replace(/\/$/,"")}/`),r=new URL(t.replace(/^\//,""),n);if(r.origin!==n.origin)throw Error("Provider pagination cannot leave the configured host");let i=new AbortController,c=setTimeout(()=>i.abort(),this.timeoutMs);try{let d=await this.fetchFn(r,{...e,redirect:"error",signal:i.signal,headers:{Accept:"application/json","User-Agent":"ts-cloud-source/1",...await this.authorization(),...e.headers}});if(!d.ok){let a=Number(d.headers.get("retry-after")??""),l=d.headers.get("x-request-id")??d.headers.get("x-github-request-id");throw new xr(`Source provider request failed (${d.status})${l?` [request ${l}]`:""}`,d.status,Number.isFinite(a)?a:void 0)}if(d.status===204)return{data:void 0,headers:d.headers};return{data:await d.json(),headers:d.headers}}catch(d){if(d instanceof xr)throw d;if(i.signal.aborted)throw new xr(`Source provider request exceeded ${this.timeoutMs}ms`);throw new xr(d instanceof Error?d.message.replace(/(?:token|password|secret)=[^\s&]+/gi,"$1=[REDACTED]"):"Source provider request failed")}finally{clearTimeout(c)}}async deleteWebhook(t,e){await this.request(this.webhookPath(t,e),{method:"DELETE"})}}class Fg extends zi{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 t=ZE(this.credential,this.nowFn()),e=this.apiRoot().replace(/\/$/,""),n=new AbortController,r=setTimeout(()=>n.abort(),this.timeoutMs);try{let i=await this.fetchFn(`${e}/app/installations/${encodeURIComponent(this.credential.installationId)}/access_tokens`,{method:"POST",signal:n.signal,redirect:"error",headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${t}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"ts-cloud-source/1"}});if(!i.ok)throw new xr(`GitHub App token refresh failed (${i.status})`,i.status);let c=await i.json();this.installationToken={value:c.token,expiresAt:new Date(c.expires_at).getTime()}}finally{clearTimeout(r)}}return{Authorization:`Bearer ${this.installationToken.value}`,"X-GitHub-Api-Version":"2022-11-28"}}async testConnection(){let t=this.credential?.installationId?"/installation/repositories?per_page=1":"/user",{data:e,headers:n}=await this.request(t);return{ok:!0,account:e.login??this.connection.owner,scopes:(n.get("x-oauth-scopes")??this.connection.grantedScopes.join(",")).split(",").map((r)=>r.trim()).filter(Boolean),message:"GitHub connection is healthy"}}async listRepositories(t={}){let e=Nn(t.limit),n=Vn(t.cursor),r=this.credential?.installationId?`/installation/repositories?per_page=${e}&page=${n}`:`/user/repos?per_page=${e}&page=${n}&sort=updated`,{data:i}=await this.request(r),c=Array.isArray(i)?i:i.repositories;return{repositories:(t.search?c.filter((a)=>a.full_name.toLowerCase().includes(t.search.toLowerCase())):c).map((a)=>({providerRepositoryId:String(a.id),fullName:a.full_name,cloneUrl:a.clone_url,defaultBranch:a.default_branch||"main",visibility:a.visibility??(a.private?"private":"public"),archived:!!a.archived,metadata:{}})),nextCursor:c.length===e?String(n+1):void 0}}async refs(t,e,n={}){let r=Nn(n.limit),i=Vn(n.cursor),{data:c}=await this.request(`/repos/${ze(t)}/${e}?per_page=${r}&page=${i}`);return{refs:c.map((d)=>({name:d.name,commitSha:d.commit.sha,protected:d.protected})),nextCursor:c.length===r?String(i+1):void 0}}listBranches(t,e){return this.refs(t,"branches",e)}listTags(t,e){return this.refs(t,"tags",e)}webhookPath(t,e){return`/repos/${ze(t)}/hooks${e?`/${encodeURIComponent(e)}`:""}`}hook(t){return{providerWebhookId:String(t.id),active:t.active,events:t.events,url:t.config.url??""}}async createWebhook(t,e){let{data:n}=await this.request(this.webhookPath(t),{method:"POST",body:JSON.stringify({name:"web",active:!0,events:e.events,config:{url:Bi(e.url),content_type:"json",secret:e.secret,insecure_ssl:"0"}}),headers:{"Content-Type":"application/json"}});return this.hook(n)}async listWebhooks(t){let{data:e}=await this.request(this.webhookPath(t));return e.map((n)=>this.hook(n))}async updateWebhook(t,e,n){let{data:r}=await this.request(this.webhookPath(t,e),{method:"PATCH",body:JSON.stringify({active:!0,events:n.events,config:{url:Bi(n.url),content_type:"json",secret:n.secret,insecure_ssl:"0"}}),headers:{"Content-Type":"application/json"}});return this.hook(r)}async setCommitStatus(t,e,n){await this.request(`/repos/${ze(t)}/statuses/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({state:n.state,target_url:n.url,description:n.description.slice(0,140),context:n.context??"ts-cloud/preview"})})}}class Vg extends zi{provider="gitlab";apiRoot(){return`${this.connection.host}/api/v4`}async authorization(){return this.credential?.token?{"PRIVATE-TOKEN":this.credential.token}:{}}async testConnection(){let{data:t}=await this.request("/user");return{ok:!0,account:t.username,scopes:this.connection.grantedScopes,message:"GitLab connection is healthy"}}async listRepositories(t={}){let e=Nn(t.limit),n=Vn(t.cursor),r=t.search?`&search=${encodeURIComponent(t.search)}`:"",{data:i,headers:c}=await this.request(`/projects?membership=true&simple=true&order_by=last_activity_at&per_page=${e}&page=${n}${r}`);return{repositories:i.map((d)=>({providerRepositoryId:String(d.id),fullName:d.path_with_namespace,cloneUrl:d.http_url_to_repo,defaultBranch:d.default_branch??"main",visibility:d.visibility??"unknown",archived:!!d.archived,metadata:{}})),nextCursor:c.get("x-next-page")||void 0}}async refs(t,e,n={}){let r=Nn(n.limit),i=Vn(n.cursor),{data:c,headers:d}=await this.request(`/projects/${encodeURIComponent(ze(t))}/repository/${e}?per_page=${r}&page=${i}`);return{refs:c.map((a)=>({name:a.name,commitSha:a.commit.id,protected:a.protected})),nextCursor:d.get("x-next-page")||void 0}}listBranches(t,e){return this.refs(t,"branches",e)}listTags(t,e){return this.refs(t,"tags",e)}webhookPath(t,e){return`/projects/${encodeURIComponent(ze(t))}/hooks${e?`/${encodeURIComponent(e)}`:""}`}hook(t){return{providerWebhookId:String(t.id),active:!0,events:[...t.push_events?["push"]:[],...t.merge_requests_events?["pull_request"]:[]],url:t.url}}body(t){return JSON.stringify({url:Bi(t.url),token:t.secret,enable_ssl_verification:!0,push_events:t.events.includes("push"),merge_requests_events:t.events.includes("pull_request")})}async createWebhook(t,e){let{data:n}=await this.request(this.webhookPath(t),{method:"POST",body:this.body(e),headers:{"Content-Type":"application/json"}});return this.hook(n)}async listWebhooks(t){let{data:e}=await this.request(this.webhookPath(t));return e.map((n)=>this.hook(n))}async updateWebhook(t,e,n){let{data:r}=await this.request(this.webhookPath(t,e),{method:"PUT",body:this.body(n),headers:{"Content-Type":"application/json"}});return this.hook(r)}async setCommitStatus(t,e,n){let r=n.state==="failure"||n.state==="error"?"failed":n.state;await this.request(`/projects/${encodeURIComponent(ze(t))}/statuses/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({state:r,target_url:n.url,description:n.description.slice(0,255),name:n.context??"ts-cloud/preview"})})}}class Ng extends zi{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:t}=await this.request("/user");return{ok:!0,account:t.username??t.display_name,scopes:this.connection.grantedScopes,message:"Bitbucket connection is healthy"}}async listRepositories(t={}){if(!this.connection.owner)throw Error("Bitbucket repository discovery requires an owner/workspace");let e=Vn(t.cursor),n=Nn(t.limit),r=t.search?`&q=name~%22${encodeURIComponent(t.search)}%22`:"",{data:i}=await this.request(`/repositories/${encodeURIComponent(this.connection.owner)}?pagelen=${n}&page=${e}${r}`);return{repositories:i.values.map((c)=>({providerRepositoryId:c.uuid,fullName:c.full_name,cloneUrl:c.links.clone.find((d)=>d.name==="https")?.href??c.links.clone[0]?.href??"",defaultBranch:c.mainbranch?.name??"main",visibility:c.is_private?"private":"public",archived:!1,metadata:{}})),nextCursor:i.next?String(e+1):void 0}}async refs(t,e,n={}){let r=Vn(n.cursor),i=Nn(n.limit),{data:c}=await this.request(`/repositories/${ze(t)}/refs/${e}?pagelen=${i}&page=${r}`);return{refs:c.values.map((d)=>({name:d.name,commitSha:d.target.hash})),nextCursor:c.next?String(r+1):void 0}}listBranches(t,e){return this.refs(t,"branches",e)}listTags(t,e){return this.refs(t,"tags",e)}webhookPath(t,e){return`/repositories/${ze(t)}/hooks${e?`/${encodeURIComponent(e)}`:""}`}hook(t){return{providerWebhookId:t.uuid,active:t.active,events:t.events.map((e)=>e.replace("repo:push","push").replace("pullrequest:","pull_request:")),url:t.url}}body(t){return JSON.stringify({description:"ts-cloud deploy",url:Bi(t.url),active:!0,events:t.events.map((e)=>e==="push"?"repo:push":e.replace("pull_request:","pullrequest:"))})}async createWebhook(t,e){let{data:n}=await this.request(this.webhookPath(t),{method:"POST",body:this.body(e),headers:{"Content-Type":"application/json"}});return this.hook(n)}async listWebhooks(t){let{data:e}=await this.request(this.webhookPath(t));return e.values.map((n)=>this.hook(n))}async updateWebhook(t,e,n){let{data:r}=await this.request(this.webhookPath(t,e),{method:"PUT",body:this.body(n),headers:{"Content-Type":"application/json"}});return this.hook(r)}async setCommitStatus(t,e,n){let r=n.state==="success"?"SUCCESSFUL":n.state==="pending"?"INPROGRESS":"FAILED";await this.request(`/repositories/${ze(t)}/commit/${encodeURIComponent(e)}/statuses/build/ts-cloud-preview`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({state:r,key:"ts-cloud-preview",name:n.context??"ts-cloud/preview",url:n.url,description:n.description.slice(0,255)})})}}class xg extends zi{provider="gitea";capabilities={...Lg,tokenRefresh:!1};apiRoot(){return`${this.connection.host}/api/v1`}async authorization(){return this.credential?.token?{Authorization:`token ${this.credential.token}`}:{}}async testConnection(){let{data:t}=await this.request("/user");return{ok:!0,account:t.login,scopes:this.connection.grantedScopes,message:"Gitea connection is healthy"}}async listRepositories(t={}){let e=Vn(t.cursor),n=Nn(t.limit),r=t.search?`/repos/search?q=${encodeURIComponent(t.search)}&limit=${n}&page=${e}`:`/user/repos?limit=${n}&page=${e}`,{data:i,headers:c}=await this.request(r),d=Array.isArray(i)?i:i.data;return{repositories:d.map((a)=>({providerRepositoryId:String(a.id),fullName:a.full_name,cloneUrl:a.clone_url,defaultBranch:a.default_branch??"main",visibility:a.private?"private":"public",archived:!!a.archived,metadata:{}})),nextCursor:c.get("x-hasmore")==="true"||d.length===n?String(e+1):void 0}}async refs(t,e,n={}){let r=Vn(n.cursor),i=Nn(n.limit),{data:c}=await this.request(`/repos/${ze(t)}/${e}?limit=${i}&page=${r}`);return{refs:c.map((d)=>({name:d.name,commitSha:d.commit.id})),nextCursor:c.length===i?String(r+1):void 0}}listBranches(t,e){return this.refs(t,"branches",e)}listTags(t,e){return this.refs(t,"tags",e)}webhookPath(t,e){return`/repos/${ze(t)}/hooks${e?`/${encodeURIComponent(e)}`:""}`}hook(t){return{providerWebhookId:String(t.id),active:t.active,events:t.events??[],url:t.config.url??""}}body(t){return JSON.stringify({type:"gitea",active:!0,events:t.events,config:{url:Bi(t.url),content_type:"json",secret:t.secret,insecure_ssl:"0"}})}async createWebhook(t,e){let{data:n}=await this.request(this.webhookPath(t),{method:"POST",body:this.body(e),headers:{"Content-Type":"application/json"}});return this.hook(n)}async listWebhooks(t){let{data:e}=await this.request(this.webhookPath(t));return e.map((n)=>this.hook(n))}async updateWebhook(t,e,n){let{data:r}=await this.request(this.webhookPath(t,e),{method:"PATCH",body:this.body(n),headers:{"Content-Type":"application/json"}});return this.hook(r)}async setCommitStatus(t,e,n){await this.request(`/repos/${ze(t)}/statuses/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({state:n.state,target_url:n.url,description:n.description.slice(0,140),context:n.context??"ts-cloud/preview"})})}}function xn(t,e,n={}){switch(t.provider){case"github":return new Fg(t,e,n);case"gitlab":return new Vg(t,e,n);case"bitbucket":return new Ng(t,e,n);case"gitea":return new xg(t,e,n);default:throw Error(`${t.provider} uses bounded Git discovery instead of a hosted provider API`)}}import{createHmac as YE,timingSafeEqual as XE}from"node:crypto";function he(t,e){if(t instanceof Headers)return t.get(e)??void 0;return Object.entries(t).find(([r])=>r.toLowerCase()===e.toLowerCase())?.[1]}function Mg(t,e){let n=Buffer.from(t),r=Buffer.from(e);return n.length===r.length&&XE(n,r)}function KE(t,e){return YE("sha256",t).update(e).digest("hex")}function pE(t,e,n,r,i){if(t==="gitlab")return Mg(he(n,"x-gitlab-token")??"",e);let c=t==="github"?he(n,"x-hub-signature-256"):t==="gitea"?he(n,"x-gitea-signature"):he(n,"x-hub-signature")??he(n,"x-ts-cloud-signature");if(!c)return!1;if(t==="generic_https"||t==="generic_ssh"){let d=Number(he(n,"x-ts-cloud-timestamp"));if(!Number.isFinite(d)||Math.abs(i.getTime()-d*1000)>300000)return!1}return Mg(c.replace(/^sha256=/,""),KE(e,r))}function mE(t,e){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"]}[t].map((r)=>he(e,r)?.trim()).find(Boolean)}function Mn(t){let e=String(t??"").trim().replace(/^\/+|\/+$/g,"");return/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(e)?e:""}function xo(t){return[...new Set(t.flatMap((e)=>{if(!e||typeof e!=="object")return[];let n=e;return[...n.added??[],...n.modified??[],...n.removed??[]].map(String)}).filter((e)=>e&&!e.includes("\x00")).slice(0,500))]}function qE(t,e,n){let r=t,i=e,c=n;if(r==="github"){let d=he(i,"x-github-event"),a=Mn(c.repository?.full_name);if(d==="push")return{event:"push",repository:a,ref:String(c.ref??""),branch:String(c.ref??"").replace(/^refs\/heads\//,""),tag:String(c.ref??"").startsWith("refs/tags/")?String(c.ref).replace(/^refs\/tags\//,""):void 0,commitSha:String(c.after??c.head_commit?.id??""),changedPaths:xo(c.commits??[]),deleted:c.deleted===!0||/^0{40,64}$/.test(String(c.after??""))};if(d==="pull_request")return{event:"pull_request",action:String(c.action??""),repository:a,branch:String(c.pull_request?.head?.ref??""),commitSha:String(c.pull_request?.head?.sha??""),changedPaths:[],pullRequestNumber:Number(c.number)||void 0,fork:Mn(c.pull_request?.head?.repo?.full_name)!==a}}if(r==="gitlab"){let d=String(c.object_kind??"").toLowerCase(),a=Mn(c.project?.path_with_namespace);if(d==="push"||d==="tag_push")return{event:"push",repository:a,ref:String(c.ref??""),branch:String(c.ref??"").replace(/^refs\/heads\//,""),tag:d==="tag_push"?String(c.ref??"").replace(/^refs\/tags\//,""):void 0,commitSha:String(c.checkout_sha??c.after??""),changedPaths:xo(c.commits??[]),deleted:/^0{40,64}$/.test(String(c.after??""))};if(d==="merge_request")return{event:"pull_request",action:String(c.object_attributes?.action??c.object_attributes?.state??""),repository:a,branch:String(c.object_attributes?.source_branch??""),commitSha:String(c.object_attributes?.last_commit?.id??""),changedPaths:[],pullRequestNumber:Number(c.object_attributes?.iid)||void 0,fork:c.object_attributes?.source_project_id!==c.object_attributes?.target_project_id}}if(r==="bitbucket"){let d=he(i,"x-event-key")??"",a=Mn(c.repository?.full_name);if(d==="repo:push"){let l=c.push?.changes?.[0]??{},o=l.new??l.old??{},u=l.new?.target??l.old?.target;return{event:"push",repository:a,ref:String(o.name??""),branch:o.type==="branch"?String(o.name):void 0,tag:o.type==="tag"?String(o.name):void 0,commitSha:String(u?.hash??""),changedPaths:[],deleted:l.closed===!0||l.new==null}}if(d.startsWith("pullrequest:"))return{event:"pull_request",action:d.replace("pullrequest:",""),repository:a,branch:String(c.pullrequest?.source?.branch?.name??""),commitSha:String(c.pullrequest?.source?.commit?.hash??""),changedPaths:[],pullRequestNumber:Number(c.pullrequest?.id)||void 0,fork:Mn(c.pullrequest?.source?.repository?.full_name)!==a}}if(r==="gitea"){let d=he(i,"x-gitea-event"),a=Mn(c.repository?.full_name);if(d==="push")return{event:"push",repository:a,ref:String(c.ref??""),branch:String(c.ref??"").replace(/^refs\/heads\//,""),tag:String(c.ref??"").startsWith("refs/tags/")?String(c.ref).replace(/^refs\/tags\//,""):void 0,commitSha:String(c.after??""),changedPaths:xo(c.commits??[]),deleted:c.deleted===!0||/^0{40,64}$/.test(String(c.after??""))};if(d==="pull_request")return{event:"pull_request",action:String(c.action??""),repository:a,branch:String(c.pull_request?.head?.ref??""),commitSha:String(c.pull_request?.head?.sha??""),changedPaths:[],pullRequestNumber:Number(c.number)||void 0,fork:Mn(c.pull_request?.head?.repo?.full_name)!==a}}if(r==="generic_https"||r==="generic_ssh"){if(c.event!=="push"&&c.event!=="pull_request")return;return{event:c.event,action:typeof c.action==="string"?c.action:void 0,repository:Mn(c.repository),ref:typeof c.ref==="string"?c.ref:void 0,branch:typeof c.branch==="string"?c.branch:void 0,tag:typeof c.tag==="string"?c.tag:void 0,commitSha:String(c.commitSha??""),changedPaths:Array.isArray(c.changedPaths)?c.changedPaths.map(String).slice(0,500):[],pullRequestNumber:Number(c.pullRequestNumber)||void 0,fork:c.fork===!0,deleted:c.deleted===!0}}return}function Mr(t,e){let n="^";for(let r=0;r<e.length;r++){let i=e[r];if(i==="*"&&e[r+1]==="*")n+=".*",r++;else if(i==="*")n+="[^/]*";else if(i==="?")n+="[^/]";else n+=i.replace(/[|\\{}()[\]^$+?.]/g,"\\$&")}return new RegExp(`${n}$`).test(t)}function tI(t,e){if(e.event==="pull_request")return t.pullRequestPreviews;if(!t.autoDeploy)return!1;if(e.tag)return!!t.tagRule&&Mr(e.tag,t.tagRule);return Mr(e.branch??"",t.branchRule??t.defaultBranch)}function eI(t,e){if(!e.length)return!0;return e.filter((r)=>!t.excludePaths.some((i)=>Mr(r,i))).some((r)=>!t.includePaths.length||t.includePaths.some((i)=>Mr(r,i)))}function Qg(t,e){return he(e,t==="github"?"x-github-event":t==="gitlab"?"x-gitlab-event":t==="bitbucket"?"x-event-key":t==="gitea"?"x-gitea-event":"x-ts-cloud-event")??"unknown"}function hr(){return{accepted:!1,duplicate:!1,status:"rejected",operations:[],message:"Webhook unavailable"}}async function Zg(t){if(t.rawBody.byteLength>2097152)return hr();let e=t.sources.getWebhookByEndpointToken(t.endpointToken);if(!e||e.status==="disabled")return hr();let n=t.sources.getConnection(e.connectionId);if(!n||n.status==="disconnected"||n.status==="expired")return hr();let r=mE(n.provider,t.headers);if(!r||r.length>200)return hr();if(!pE(n.provider,t.sources.getWebhookSecret(e.id),t.headers,t.rawBody,t.now??new Date))return t.sources.recordDelivery({connectionId:n.id,webhookId:e.id,providerDeliveryId:r,event:Qg(n.provider,t.headers),signatureStatus:he(t.headers,"x-hub-signature-256")||he(t.headers,"x-gitlab-token")||he(t.headers,"x-hub-signature")||he(t.headers,"x-gitea-signature")?"invalid":"missing",status:"rejected",error:"Webhook signature verification failed"}),hr();let c;try{c=JSON.parse(new TextDecoder().decode(t.rawBody))}catch{return hr()}let d=qE(n.provider,t.headers,c);if(!d||!d.repository||!/^[a-f0-9]{7,64}$/i.test(d.commitSha))return t.sources.recordDelivery({connectionId:n.id,webhookId:e.id,providerDeliveryId:r,event:Qg(n.provider,t.headers),signatureStatus:"verified",status:"rejected",error:"Unsupported or malformed source event"}),hr();let a=t.sources.recordDelivery({connectionId:n.id,webhookId:e.id,providerDeliveryId:r,event:d.event,action:d.action,commitSha:d.commitSha,signatureStatus:"verified",status:"accepted",payloadSummary:{repository:d.repository,ref:d.ref??null,branch:d.branch??null,tag:d.tag??null,commitSha:d.commitSha,pullRequestNumber:d.pullRequestNumber??null,changedPathCount:d.changedPaths.length}});if(a.duplicate&&a.delivery.status!=="accepted")return{accepted:!0,duplicate:!0,status:"duplicate",operations:[],message:"Delivery already processed"};let l=new Gg(t.controlPlane),o=t.sources.listBindings({connectionId:n.id,status:"active"}).filter((E)=>{if(E.repositoryFullName.toLowerCase()!==d.repository.toLowerCase()||!eI(E,d.changedPaths))return!1;let y=E.resourceId?l.getDefinitionForResource(E.resourceId):void 0,$=d.event==="push"&&!!y?.branchRule&&!!d.branch&&Mr(d.branch,y.branchRule);return tI(E,d)||$});if(!o.length)return t.sources.updateDelivery(a.delivery.id,{status:"ignored"}),{accepted:!0,duplicate:a.duplicate,status:"ignored",operations:[],message:"Verified event did not match an active deployment rule"};let u=new Ot(t.controlPlane),f=new Set(["closed","merged","declined"]),R=o.flatMap((E)=>{if(d.event==="push"&&E.resourceId&&d.branch){let $=l.getDefinitionForResource(E.resourceId);if($?.branchRule&&Mr(d.branch,$.branchRule)){let C=l.findForBranch($.id,d.repository,d.branch);if(d.deleted){if(!$.cleanupOnClose||!C||C.status==="destroyed")return[];let Y=u.enqueue({projectId:E.projectId,environmentId:E.environmentId,resourceId:E.resourceId,kind:"preview.destroy",idempotencyKey:`preview:${C.id}:branch-delete:${r}`,correlationId:`preview:${C.id}`,input:{previewId:C.id,reason:"branch_deleted",source:{repository:d.repository,commitSha:d.commitSha,branch:d.branch}},lockKey:`preview:${C.id}`,providerKey:n.provider,maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;return l.transition(C.id,"queued",{operationId:Y.id}),[Y]}let J=l.upsert({definitionId:$.id,sourceProvider:n.provider,repository:d.repository,branch:d.branch,commitSha:d.commitSha});if(!J.changed)return[];let H=J.created?"preview.create":"preview.update",O=u.enqueue({projectId:E.projectId,environmentId:E.environmentId,resourceId:E.resourceId,kind:H,idempotencyKey:`preview:${J.preview.id}:${d.commitSha}`,correlationId:`preview:${J.preview.id}`,input:{previewId:J.preview.id,source:{connectionId:n.id,bindingId:E.id,repository:d.repository,commitSha:d.commitSha,branch:d.branch,monorepoRoot:E.monorepoRoot,submodules:E.submodules,cloneDepth:E.cloneDepth??null}},lockKey:`preview:${J.preview.id}`,providerKey:n.provider,buildSlot:!0,maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;return l.transition(J.preview.id,"queued",{operationId:O.id}),[O]}}if(d.event==="pull_request"&&E.resourceId&&d.pullRequestNumber){let $=l.getDefinitionForResource(E.resourceId);if($){let C=f.has(String(d.action??"").toLowerCase()),J=l.findForPullRequest($.id,d.repository,d.pullRequestNumber);if(C){if(!$.cleanupOnClose||!J||J.status==="destroyed")return[];let H=u.enqueue({projectId:E.projectId,environmentId:E.environmentId,resourceId:E.resourceId,kind:"preview.destroy",idempotencyKey:`preview:${J.id}:destroy:${r}`,correlationId:`preview:${J.id}`,input:{previewId:J.id,reason:"pull_request_closed",source:{repository:d.repository,commitSha:d.commitSha,branch:d.branch??null,pullRequestNumber:d.pullRequestNumber}},lockKey:`preview:${J.id}`,providerKey:n.provider,maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;return l.transition(J.id,"queued",{operationId:H.id}),[H]}try{let H=l.upsert({definitionId:$.id,sourceProvider:n.provider,repository:d.repository,branch:d.branch??`pr-${d.pullRequestNumber}`,pullRequestNumber:d.pullRequestNumber,fork:d.fork,commitSha:d.commitSha});if(!H.changed)return[];let O=H.created?"preview.create":"preview.update",Y=u.enqueue({projectId:E.projectId,environmentId:E.environmentId,resourceId:E.resourceId,kind:O,idempotencyKey:`preview:${H.preview.id}:${d.commitSha}`,correlationId:`preview:${H.preview.id}`,input:{previewId:H.preview.id,source:{connectionId:n.id,bindingId:E.id,repository:d.repository,commitSha:d.commitSha,branch:d.branch??null,pullRequestNumber:d.pullRequestNumber,fork:!!d.fork,monorepoRoot:E.monorepoRoot,submodules:E.submodules,cloneDepth:E.cloneDepth??null},inheritedSecretNames:H.inheritedSecrets},lockKey:`preview:${H.preview.id}`,providerKey:n.provider,buildSlot:!0,maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;return l.transition(H.preview.id,"queued",{operationId:Y.id}),[Y]}catch(H){return t.controlPlane.appendEvent({projectId:E.projectId,resourceId:E.resourceId,type:"preview.rejected",level:"warning",payload:{repository:d.repository,pullRequestNumber:d.pullRequestNumber,fork:!!d.fork,reason:H instanceof Error?H.message:String(H)}}),[]}}}let y=d.event==="pull_request"?"deploy.preview":"deploy.source";return[u.enqueue({projectId:E.projectId,environmentId:E.environmentId,resourceId:E.resourceId,kind:y,idempotencyKey:`source:${n.id}:${r}:${E.id}:${d.commitSha}`,correlationId:`source:${r}`,input:{source:{connectionId:n.id,bindingId:E.id,repository:d.repository,commitSha:d.commitSha,branch:d.branch??null,tag:d.tag??null,monorepoRoot:E.monorepoRoot,submodules:E.submodules,cloneDepth:E.cloneDepth??null},preview:d.event==="pull_request"?{number:d.pullRequestNumber??null,action:d.action??null}:null},lockKey:E.resourceId?`resource:${E.resourceId}`:`environment:${E.environmentId??E.projectId}`,providerKey:n.provider,buildSlot:!0,maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:d.event==="pull_request"?14:90}).operation]});if(!R.length)return t.sources.updateDelivery(a.delivery.id,{status:"ignored"}),{accepted:!0,duplicate:a.duplicate,status:"ignored",operations:[],message:"Verified event required no preview lifecycle change"};return t.sources.updateDelivery(a.delivery.id,{status:"enqueued",operationId:R[0]?.id}),t.controlPlane.appendEvent({organizationId:n.organizationId,projectId:o[0]?.projectId,operationId:R[0]?.id,type:"source.webhook.enqueued",payload:{webhookId:e.id,deliveryId:a.delivery.id,repository:d.repository,commitSha:d.commitSha,operationIds:R.map((E)=>E.id)}}),{accepted:!0,duplicate:a.duplicate,status:"enqueued",operations:R,message:`${R.length} deployment operation${R.length===1?"":"s"} enqueued`}}function Qr(t,e){if(!e.endpointToken)throw Error("The webhook endpoint token is only available at creation time");let n=new URL(t);if(n.protocol!=="https:"&&!["localhost","127.0.0.1","::1"].includes(n.hostname))throw Error("Webhook base URL must use HTTPS");return new URL(`/api/source/webhooks/${encodeURIComponent(e.endpointToken)}`,n).href}import{chmodSync as Yg,mkdtempSync as nI,rmSync as rI,writeFileSync as Xg}from"node:fs";import{tmpdir as iI}from"node:os";import{join as yc,resolve as cI}from"node:path";function pg(t,e){let n=t.trim();if(/\r|\n|\0/.test(n))throw Error("Git remote contains control characters");if(n.startsWith("https://")){let i=new URL(n);if(i.username||i.password||i.search||i.hash)throw Error("HTTPS Git remotes cannot contain credentials, queries, or fragments");return i.href}let r=n.startsWith("ssh://")?new URL(n).hostname:n.match(/^git@([A-Za-z0-9.-]+):/)?.[1];if(!r)throw Error("Git remote must use credential-free HTTPS or SSH");if(!e||e.host.toLowerCase()!==r.toLowerCase())throw Error("SSH Git remote requires a deploy key with a pinned key for the same host");return n}function dI(t,e,n){let r=t.replaceAll(e,"[REMOTE]").slice(0,4000);for(let i of[n?.token,n?.privateKey])if(i)r=r.replaceAll(i,"[REDACTED]");return r}function oI(t){let e={PATH:process.env.PATH??"/usr/local/bin:/usr/bin:/bin",HOME:"/nonexistent",GIT_TERMINAL_PROMPT:"0",GIT_CONFIG_NOSYSTEM:"1",GIT_OPTIONAL_LOCKS:"0"},n;if(t.credential?.token){let r=t.credential.username??"oauth2";e.GIT_CONFIG_COUNT="1",e.GIT_CONFIG_KEY_0="http.extraHeader",e.GIT_CONFIG_VALUE_0=`Authorization: Basic ${Buffer.from(`${r}:${t.credential.token}`).toString("base64")}`}if(t.deployKey){n=nI(yc(iI(),"ts-cloud-git-transport-"));let r=yc(n,"key"),i=yc(n,"known_hosts");Xg(r,t.deployKey.privateKey,{mode:384}),Xg(i,`${t.deployKey.host} ${t.deployKey.hostKey}
|
|
6
|
-
`,{mode:384}),Yg(r,384),Yg(i,384),e.GIT_SSH_COMMAND=`ssh -i ${r} -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes -o UserKnownHostsFile=${i} -o GlobalKnownHostsFile=/dev/null -o BatchMode=yes`}return{env:e,cleanup:()=>{if(n)rI(n,{recursive:!0,force:!0})}}}async function Sr(t,e,n){let r=oI(n),i=Bun.spawn([n.executable??"git",...t],{stdout:"pipe",stderr:"pipe",env:r.env}),c=Math.max(100,n.timeoutMs??120000),d,a=new Promise((l,o)=>{d=setTimeout(()=>{i.kill(),o(Error(`Git operation exceeded ${c}ms`))},c)});try{let l=Promise.all([i.exited,new Response(i.stdout).text(),new Response(i.stderr).text()]),[o,u,f]=await Promise.race([l,a]);if(o!==0)throw Error(dI(f||`Git exited with ${o}`,e,n.credential));return u}finally{if(d)clearTimeout(d);r.cleanup()}}function Kg(t,e){let n=new Map;for(let r of t.split(`
|
|
7
|
-
`)){let i=r.trim().match(/^([a-f0-9]{40,64})\s+(.+)$/i);if(!i||!i[2].startsWith(e)||i[2].endsWith("^{}"))continue;let c=i[2].slice(e.length);n.set(c,{name:c,commitSha:i[1]})}return[...n.values()].sort((r,i)=>r.name.localeCompare(i.name))}async function Mo(t,e={}){let n=pg(t,e.deployKey),r=await Sr(["ls-remote","--heads","--tags","--",n],n,e);return{branches:Kg(r,"refs/heads/"),tags:Kg(r,"refs/tags/")}}async function Qo(t,e={}){let n=pg(t.remote,e.deployKey),r=cI(t.destination),i=t.ref?.trim()||t.binding.defaultBranch;if(!/^[A-Za-z0-9._/-]{1,255}$/.test(i)||i.startsWith("-")||i.includes(".."))throw Error("Git ref contains unsupported characters");let c=["clone","--no-tags","--single-branch","--branch",i],d=[...new Set(t.sparsePaths??[])];if(d.some((l)=>!l||l.startsWith("/")||l.split("/").includes("..")||/[\0\r\n]/.test(l)))throw Error("Sparse checkout paths must stay inside the repository");if(d.length)c.push("--filter=blob:none","--no-checkout");if(t.binding.cloneDepth)c.push("--depth",String(t.binding.cloneDepth));if(t.binding.submodules)c.push("--recurse-submodules","--shallow-submodules");if(c.push("--",n,r),await Sr(c,n,e),d.length)await Sr(["-C",r,"sparse-checkout","set","--cone","--",...d],n,e),await Sr(["-C",r,"checkout","--force"],n,e);if(t.commitSha){if(!/^[a-f0-9]{40,64}$/i.test(t.commitSha))throw Error("Expected source commit must be an immutable 40-64 character SHA");await Sr(["-C",r,"fetch","--no-tags","--depth","1","origin",t.commitSha],n,e),await Sr(["-C",r,"checkout","--detach","--force",t.commitSha],n,e)}let a=(await Sr(["-C",r,"rev-parse","HEAD"],n,e)).trim();if(!/^[a-f0-9]{40,64}$/i.test(a))throw Error("Git clone did not produce a valid commit SHA");if(t.commitSha&&a.toLowerCase()!==t.commitSha.toLowerCase())throw Error(`Git checkout resolved ${a} instead of the requested immutable commit`);return{directory:t.binding.monorepoRoot==="."?r:yc(r,t.binding.monorepoRoot),commitSha:a}}function Ti(t){return["github","gitlab","bitbucket","gitea"].includes(t)}async function Go(t,e,n){let r=t.getConnection(e);if(!r||["disconnected","expired"].includes(r.status))throw Error("Active source connection was not found");try{if(Ti(r.provider)){let d=await xn(r,t.getCredential(r.id)).testConnection();return t.updateHealth(r.id,{status:d.ok?"healthy":"degraded",message:d.message,tested:!0,grantedScopes:d.scopes})}let i=n?t.getRepository(n):t.listRepositories(r.id,void 0,1)[0];if(!i)return t.updateHealth(r.id,{status:"degraded",message:"Add a repository URL before testing this generic connection.",tested:!0});let c=r.provider==="generic_ssh"?t.listBindings({connectionId:r.id}).map((d)=>d.deployKeyId).filter(Boolean).map((d)=>t.getDeployKey(d)).find(Boolean):void 0;return await Mo(i.cloneUrl,{credential:t.getCredential(r.id),deployKey:c?{...c,privateKey:t.getDeployPrivateKey(c.id)}:void 0}),t.updateHealth(r.id,{status:"healthy",message:"Git repository access is healthy.",tested:!0})}catch(i){return t.updateHealth(r.id,{status:"degraded",message:i instanceof Error?i.message:"Connection test failed",tested:!0})}}async function Pc(t,e,n={}){let r=t.getConnection(e);if(!r||!Ti(r.provider)||["disconnected","expired"].includes(r.status))throw Error("A hosted active source connection is required for repository discovery");let i=xn(r,t.getCredential(r.id)),c=[],d;for(let a=0;a<Math.min(20,Math.max(1,n.maxPages??10));a++){let l=await i.listRepositories({cursor:d,search:n.search,limit:100});for(let o of l.repositories)c.push(t.upsertRepository({connectionId:r.id,...o}));if(d=l.nextCursor,!d)break}return t.updateHealth(r.id,{status:"healthy",message:`${c.length} repositories synchronized.`,synced:!0}),c}async function $c(t,e){let n=t.getConnection(e.connectionId);if(!n||["disconnected","expired"].includes(n.status))throw Error("Active source connection was not found");if(Ti(n.provider)){let a=xn(n,t.getCredential(n.id));return e.type==="tags"?a.listTags(e.repository,e):a.listBranches(e.repository,e)}let r=e.repositoryId?t.getRepository(e.repositoryId):t.listRepositories(n.id).find((a)=>a.fullName===e.repository);if(!r||r.connectionId!==n.id)throw Error("Generic repository metadata was not found");let i=e.deployKeyId?t.getDeployKey(e.deployKeyId):void 0;if(i&&i.connectionId!==n.id)throw Error("Deploy key does not belong to this connection");let c=await Mo(r.cloneUrl,{credential:t.getCredential(n.id),deployKey:i?{...i,privateKey:t.getDeployPrivateKey(i.id)}:void 0});return{refs:(e.type==="tags"?c.tags:c.branches).slice(0,Math.min(500,e.limit??100))}}async function bi(t,e,n){let r=t.getWebhook(e),i=r?t.getConnection(r.connectionId):void 0;if(!r||!i||["disconnected","expired"].includes(i.status))throw Error("Active source webhook was not found");let c=Qr(n,{...r,endpointToken:t.getWebhookEndpointToken(r.id)});if(!Ti(i.provider))return t.updateWebhookState(r.id,{status:"healthy",healthMessage:"Manual webhook endpoint is ready.",reconciled:!0});try{let d=xn(i,t.getCredential(i.id)),a=t.getWebhookSecret(r.id),l=r.providerWebhookId?await d.updateWebhook(r.repositoryFullName,r.providerWebhookId,{url:c,secret:a,events:r.events}):await d.createWebhook(r.repositoryFullName,{url:c,secret:a,events:r.events});return t.updateWebhookState(r.id,{providerWebhookId:l.providerWebhookId,status:l.active?"healthy":"degraded",healthMessage:l.active?"Provider webhook is synchronized.":"Provider webhook exists but is inactive.",reconciled:!0})}catch(d){return t.updateWebhookState(r.id,{status:"degraded",healthMessage:d instanceof Error?d.message:"Webhook reconciliation failed",reconciled:!0})}}async function mg(t,e){let n=t.getWebhook(e),r=n?t.getConnection(n.connectionId):void 0;if(!n||!r)throw Error("Source webhook was not found");if(Ti(r.provider)&&n.providerWebhookId&&!["disconnected","expired"].includes(r.status))await xn(r,t.getCredential(r.id)).deleteWebhook(n.repositoryFullName,n.providerWebhookId);return t.updateWebhookState(n.id,{status:"disabled",healthMessage:"Webhook disabled."})}var vc="1.6.0";function Zo(){let t={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:{}}}}},e=(r)=>({type:"object",required:["data","page","requestId"],properties:{data:{type:"array",items:r},page:{type:"object",required:["hasMore"],properties:{nextCursor:{type:"string"},hasMore:{type:"boolean"}}},requestId:{type:"string",format:"uuid"}}}),n=(r)=>({"200":{description:"A stable cursor page.",content:{"application/json":{schema:e(r)}}},default:{$ref:"#/components/responses/Error"}});return{openapi:"3.1.0",info:{title:"ts-cloud API",version:vc,description:"Additive changes are released within v1. Breaking request or response changes require a new URL version."},servers:[{url:"/"}],security:[{bearerAuth:[]}],paths:{...qg(),"/api/v1/projects":{get:{operationId:"listProjects",summary:"List accessible projects",parameters:[{$ref:"#/components/parameters/Limit"},{$ref:"#/components/parameters/Cursor"}],responses:n({$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:n({$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:n({$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:n({$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:n({$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:n({$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:n({$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:n({$ref:"#/components/schemas/QueueOperation"})}},"/api/v1/preview-definitions":{get:{operationId:"listPreviewDefinitions",summary:"List preview policies",responses:n({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:n({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:n({type:"object"})}},"/api/v1/compose-applications":{get:{operationId:"listComposeApplications",summary:"List authorized multi-service applications",responses:n({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:n({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:n({$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:n({$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:t}}}},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 sI(t){return Buffer.from(JSON.stringify(t)).toString("base64url")}function lI(t){if(!t)return;try{let e=JSON.parse(Buffer.from(t,"base64url").toString("utf8"));return e&&typeof e==="object"&&!Array.isArray(e)?e:void 0}catch{return}}function Se(t,e,n,r=["createdAt","id"]){let i=Math.min(100,Math.max(1,Number(e.searchParams.get("limit"))||50)),c=lI(e.searchParams.get("cursor"));if(e.searchParams.has("cursor")&&!c)throw new p("invalid_cursor","The pagination cursor is invalid.",400);let d=0;if(c){let u=t.findIndex((f)=>r.every((R)=>f[R]===c[R]));if(u<0)throw new p("invalid_cursor","The pagination cursor is no longer available.",400);d=u+1}let a=t.slice(d,d+i),l=d+i<t.length,o=a.at(-1);return{data:a,page:{hasMore:l,nextCursor:l&&o?sI(Object.fromEntries(r.map((u)=>[u,o[u]]))):void 0},requestId:n}}function Xo(t){let e=new Yo(t.controlPlane,t.identities),n=new Ot(t.controlPlane),r=new Oc(t.controlPlane),i=new Cc(t.controlPlane),c=new lr(t.controlPlane),d=t.spend?.store??new tu(t.controlPlane,{now:t.now}),a={store:d,service:t.spend?.service??new eu(d)},l=new Map,o=t.now??(()=>new Date),u=t.rateLimit??120,f=(E,y,$,C={})=>new Response(JSON.stringify(E),{status:y,headers:{"content-type":"application/json; charset=utf-8","cache-control":"no-store","x-request-id":$,"x-api-version":vc,...C}}),R=(E,y,$,C,J,H)=>f({error:{code:E,message:y,requestId:C,details:J}},$,C,H);return async(E,y)=>{let $=new URL(E.url);if(!$.pathname.startsWith("/api/v1"))return;let C=crypto.randomUUID();if($.pathname==="/api/v1/openapi.json"&&E.method==="GET")return f(Zo(),200,C,{"cache-control":"public, max-age=300"});let J=E.headers.get("authorization")??"",H=J.startsWith("Bearer ")?J.slice(7).trim():"",O=H?t.identities.verifyToken(H,y):void 0;if(!O)return R("unauthorized","A valid bearer token is required.",401,C,void 0,{"www-authenticate":'Bearer realm="ts-cloud", error="invalid_token"'});let Y=l.get(O.token.id),dt=o().getTime(),m=!Y||dt-Y.start>=60000?{start:dt,count:0}:Y;m.count+=1,l.set(O.token.id,m);let Ut=Math.max(0,u-m.count),st={"x-ratelimit-limit":String(u),"x-ratelimit-remaining":String(Ut),"x-ratelimit-reset":String(Math.ceil((m.start+60000)/1000))};if(m.count>u)return R("rate_limited","API rate limit exceeded.",429,C,void 0,{...st,"retry-after":String(Math.max(1,Math.ceil((m.start+60000-dt)/1000)))});try{let Q,rt=async()=>{let P=await E.text();if(P.length>1048576)throw new p("payload_too_large","Request body exceeds 1 MB.",413);try{return JSON.parse(P)}catch{throw new p("invalid_json","Request body must be valid JSON.",400)}},Dt=/^\/api\/v1\/projects\/([^/]+)\/environments$/.exec($.pathname),Ke=/^\/api\/v1\/operations\/([^/]+)\/logs(?:\/(stream))?$/.exec($.pathname),bn=/^\/api\/v1\/operations\/([^/]+)\/(cancel|retry)$/.exec($.pathname),Le=/^\/api\/v1\/previews\/([^/]+)\/(destroy|extend|rebuild)$/.exec($.pathname),pe=/^\/api\/v1\/compose-applications\/([^/]+)\/(deploy|redeploy|start|stop|scale|delete)$/.exec($.pathname),me=/^\/api\/v1\/compose-applications\/([^/]+)\/services$/.exec($.pathname),qe=/^\/api\/v1\/releases\/([^/]+)\/(promote|approve|activate|rollback|health|pin)$/.exec($.pathname);if(E.method==="GET"&&$.pathname==="/api/v1/projects")Q=Se(e.listProjects(O),$,C);else if(E.method==="GET"&&Dt)Q=Se(e.listEnvironments(O,decodeURIComponent(Dt[1])),$,C);else if(E.method==="GET"&&$.pathname==="/api/v1/services"){let P=$.searchParams.get("projectId");if(!P)throw new p("validation_error","projectId is required.",422);Q=Se(e.listServices(O,P,$.searchParams.get("environmentId")??void 0),$,C)}else if(E.method==="GET"&&$.pathname==="/api/v1/operations")Q=Se(e.listOperations(O,$.searchParams.get("projectId")??void 0),$,C);else if(E.method==="GET"&&$.pathname==="/api/v1/previews"){let P=$.searchParams.get("projectId")??void 0,b=r.previews.listInstances({projectId:P}).filter((N)=>{try{return e.authorize(O,"deployments:read",{type:"resource",id:N.resourceId}),!0}catch{return!1}}).map((N)=>({...N}));Q=Se(b,$,C)}else if(E.method==="GET"&&$.pathname==="/api/v1/compose-templates")Q=Se(kc().map((P)=>({...P})),$,C,["id","version"]);else if(E.method==="GET"&&$.pathname==="/api/v1/releases/capabilities"){let P=String($.searchParams.get("kind")??"");Q={capabilities:Ji({kind:P,hasHealthGate:$.searchParams.get("health")==="true",replicas:Number($.searchParams.get("replicas"))||1}),requestId:C}}else if(E.method==="GET"&&$.pathname==="/api/v1/releases"){let P=$.searchParams.get("projectId");if(!P)throw new p("validation_error","projectId is required.",422);e.authorize(O,"project:read",{type:"project",id:P});let b=c.releases.list({projectId:P,environmentId:$.searchParams.get("environmentId")??void 0,resourceId:$.searchParams.get("resourceId")??void 0}).filter((N)=>{try{return e.authorize(O,"deployments:read",{type:"resource",id:N.resourceId}),!0}catch{return!1}}).map((N)=>({...N,artifact:c.releases.getArtifact(N.artifactId),transitions:c.releases.transitions(N.id),approvals:c.releases.approvals(N.id)}));Q=Se(b,$,C)}else if(E.method==="POST"&&$.pathname==="/api/v1/release-artifacts"){let P=await rt();e.authorize(O,"applications:manage",{type:"organization"}),Q={artifact:c.releases.registerArtifact({organizationId:O.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:C}}else if(E.method==="POST"&&$.pathname==="/api/v1/releases"){let P=await rt(),b=String(P.resourceId??"");e.authorize(O,"applications:manage",{type:"resource",id:b}),Q={release:c.releases.create({organizationId:O.serviceAccount.organizationId,projectId:String(P.projectId??""),environmentId:String(P.environmentId??""),resourceId:b,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:O.actor.id,trigger:typeof P.trigger==="string"?P.trigger:"api",approvalRequired:P.approvalRequired===!0,replicas:Number(P.replicas)||void 0}),requestId:C}}else if(E.method==="GET"&&/^\/api\/v1\/releases\/[^/]+$/.test($.pathname)){let P=decodeURIComponent($.pathname.split("/").at(-1)),b=c.releases.get(P);if(!b)throw new p("not_found","Release was not found.",404);e.authorize(O,"deployments:read",{type:"resource",id:b.resourceId}),Q={release:b,artifact:c.releases.getArtifact(b.artifactId),transitions:c.releases.transitions(P),approvals:c.releases.approvals(P),requestId:C}}else if(E.method==="POST"&&qe){let P=c.releases.get(decodeURIComponent(qe[1]));if(!P)throw new p("not_found","Release was not found.",404);let b=await rt(),N=qe[2];if(N==="promote"){let G=String(b.targetResourceId??"");e.authorize(O,"deployments:create",{type:"resource",id:G}),Q={release:c.releases.promote(P.id,{targetEnvironmentId:String(b.targetEnvironmentId??""),targetResourceId:G,config:b.config??{},strategy:b.strategy,healthGate:b.healthGate,actorId:O.actor.id,approvalRequired:b.approvalRequired===!0}),requestId:C}}else if(N==="approve")e.authorize(O,"deployments:create",{type:"resource",id:P.resourceId}),Q={release:c.releases.approve(P.id,{actorId:O.actor.id,decision:b.decision==="rejected"?"rejected":"approved",comment:typeof b.comment==="string"?b.comment:void 0}),requestId:C};else if(N==="activate")e.authorize(O,"deployments:create",{type:"resource",id:P.resourceId}),Q={operation:e.operation(c.enqueueActivation(P,{actorId:O.actor.id})),requestId:C};else if(N==="rollback")e.authorize(O,"deployments:create",{type:"resource",id:P.resourceId}),Q={operation:e.operation(c.enqueueRollback(P,{actorId:O.actor.id,targetReleaseId:typeof b.targetReleaseId==="string"?b.targetReleaseId:void 0})),requestId:C};else if(N==="health"){e.authorize(O,"deployments:create",{type:"resource",id:P.resourceId});let G=c.completeHealthGate(P.id,{healthy:b.healthy===!0,operationId:typeof b.operationId==="string"?b.operationId:void 0,health:b.health,message:typeof b.message==="string"?b.message:void 0});Q={release:G.release,rollbackOperation:G.rollbackOperation?e.operation(G.rollbackOperation):void 0,requestId:C}}else e.authorize(O,"deployments:create",{type:"resource",id:P.resourceId}),Q={release:c.releases.pin(P.id,b.pinned!==!1,typeof b.reason==="string"?b.reason:void 0),requestId:C}}else if(E.method==="GET"&&$.pathname==="/api/v1/compose-applications"){let P=$.searchParams.get("projectId");if(!P)throw new p("validation_error","projectId is required.",422);e.authorize(O,"project:read",{type:"project",id:P});let b=i.applications.list({projectId:P,environmentId:$.searchParams.get("environmentId")??void 0}).filter((N)=>{try{return e.authorize(O,"deployments:read",{type:"resource",id:N.resourceId}),!0}catch{return!1}}).map((N)=>({...N,services:i.applications.services(N.id)}));Q=Se(b,$,C)}else if(E.method==="POST"&&$.pathname==="/api/v1/compose-applications/preview"){let P=await rt(),b=String(P.projectId??"");e.authorize(O,"project:read",{type:"project",id:b}),Q={result:i.applications.preview(String(P.source??""),{name:String(P.name??""),slug:typeof P.slug==="string"?P.slug:void 0,projectId:b,environmentId:String(P.environmentId??"")}),requestId:C}}else if(E.method==="POST"&&$.pathname==="/api/v1/compose-applications"){let P=await rt(),b=String(P.projectId??"");e.authorize(O,"applications:manage",{type:"environment",id:String(P.environmentId??"")});let N={name:String(P.name??""),slug:typeof P.slug==="string"?P.slug:void 0,projectId:b,environmentId:String(P.environmentId??""),createdByActorId:O.actor.id},G=typeof P.templateId==="string"?i.applications.fromTemplate(P.templateId,P.inputs&&typeof P.inputs==="object"&&!Array.isArray(P.inputs)?P.inputs:{},{...N,version:typeof P.templateVersion==="string"?P.templateVersion:void 0}):i.applications.import(String(P.source??""),N);Q={application:G.application,diagnostics:G.parsed.diagnostics,requestId:C}}else if(E.method==="GET"&&me){let P=i.applications.get(decodeURIComponent(me[1]));if(!P)throw new p("not_found","Compose application was not found.",404);e.authorize(O,"deployments:read",{type:"resource",id:P.resourceId}),Q={application:P,services:i.applications.services(P.id),requestId:C}}else if(E.method==="POST"&&pe){let P=i.applications.get(decodeURIComponent(pe[1]));if(!P)throw new p("not_found","Compose application was not found.",404);let b=pe[2],N=await rt();e.authorize(O,b==="delete"||b==="stop"?"deployments:cancel":"deployments:create",{type:"resource",id:P.resourceId}),Q={operation:e.operation(i.enqueue(P,b,{actorId:O.actor.id,service:typeof N.service==="string"?N.service:void 0,replicas:Number.isFinite(Number(N.replicas))?Number(N.replicas):void 0,removeVolumes:N.removeVolumes===!0,confirmation:typeof N.confirm==="string"?N.confirm:void 0})),requestId:C}}else if(E.method==="GET"&&$.pathname==="/api/v1/preview-definitions"){let P=$.searchParams.get("projectId");if(!P)throw new p("validation_error","projectId is required.",422);e.authorize(O,"project:read",{type:"project",id:P}),Q=Se(r.previews.listDefinitions(P).map((b)=>({...b})),$,C)}else if(E.method==="POST"&&$.pathname==="/api/v1/preview-definitions"){let P=await rt();e.authorize(O,"config:write",{type:"resource",id:String(P.resourceId??"")}),Q={definition:r.previews.createDefinition({...P,projectId:String(P.projectId??""),resourceId:String(P.resourceId??""),baseEnvironmentId:String(P.baseEnvironmentId??""),domainPattern:String(P.domainPattern??""),createdByActorId:O.actor.id}),requestId:C}}else if(E.method==="POST"&&$.pathname==="/api/v1/previews"){let P=await rt(),b=r.previews.getDefinition(String(P.definitionId??""));if(!b)throw new p("not_found","Preview definition was not found.",404);e.authorize(O,"deployments:create",{type:"resource",id:b.resourceId});let N=r.previews.upsert({definitionId:b.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:O.actor.id});Q={preview:N.preview,operation:e.operation(r.enqueueDeploy(N.preview,{created:N.created,actorId:O.actor.id})),requestId:C}}else if(E.method==="POST"&&Le){let P=r.previews.getInstance(decodeURIComponent(Le[1]));if(!P)throw new p("not_found","Preview was not found.",404);let b=await rt(),N=Le[2];if(N==="destroy"){if(e.authorize(O,"deployments:cancel",{type:"resource",id:P.resourceId}),b.confirm!==P.name)throw new p("confirmation_required",`Type ${P.name} to confirm preview teardown.`,409);Q={operation:e.operation(r.enqueueDestroy(P,"api",O.actor.id)),requestId:C}}else if(N==="extend")e.authorize(O,"deployments:create",{type:"resource",id:P.resourceId}),Q={preview:r.previews.extend(P.id,Number(b.hours)),requestId:C};else e.authorize(O,"deployments:create",{type:"resource",id:P.resourceId}),Q={operation:e.operation(r.enqueueDeploy(P,{actorId:O.actor.id,reason:"manual_rebuild"})),requestId:C}}else if(E.method==="POST"&&$.pathname==="/api/v1/previews/cleanup"){e.authorize(O,"automation:manage",{type:"organization"});let P=await rt();if(!P.dryRun&&P.confirm!=="cleanup previews")throw new p("confirmation_required","Type cleanup previews to confirm preview cleanup.",409);Q={...r.cleanup({dryRun:P.dryRun===!0,maxAgeHours:Number(P.maxAgeHours)||void 0,keepCount:Number(P.keepCount)||void 0,actorId:O.actor.id}),requestId:C}}else if(E.method==="GET"&&$.pathname==="/api/v1/queue"){let P=$.searchParams.get("projectId")??void 0,b=$.searchParams.get("state"),N=n.list({projectId:P,state:["queued","running","succeeded","failed","cancelled","timed_out"].includes(b)?b:void 0,limit:500}).filter((G)=>{let vt=G.operation.resourceId?{type:"resource",id:G.operation.resourceId}:G.operation.environmentId?{type:"environment",id:G.operation.environmentId}:G.operation.projectId?{type:"project",id:G.operation.projectId}:{type:"organization"};try{return e.authorize(O,"deployments:read",vt),!0}catch{return!1}}).map((G)=>({...e.operation(G.operation),queue:G.job,approximatePosition:G.approximatePosition}));Q=Se(N,$,C)}else if(E.method==="GET"&&$.pathname==="/api/v1/queue/settings")e.authorize(O,"deployments:read",O.token.scope),Q={concurrency:n.limits,requestId:C};else if(E.method==="PATCH"&&$.pathname==="/api/v1/queue/settings"){e.authorize(O,"automation:manage",{type:"organization"});let P=await rt();if(P.confirm!=="update queue limits")throw new p("confirmation_required","Type update queue limits to confirm production concurrency changes.",409);Q={concurrency:n.configureConcurrency(P.concurrency??{},{organizationId:O.serviceAccount.organizationId,actorId:O.actor.id}),requestId:C}}else if(E.method==="DELETE"&&$.pathname==="/api/v1/queue/history"){e.authorize(O,"automation:manage",{type:"organization"});let P=await rt();if(P.confirm!=="clear completed")throw new p("confirmation_required","Type clear completed to confirm queue retention cleanup.",409);Q={deleted:n.clearCompleted({before:typeof P.before==="string"?P.before:void 0,actorId:O.actor.id,projectId:typeof P.projectId==="string"?P.projectId:void 0}),requestId:C}}else if(E.method==="GET"&&Ke){let P=t.controlPlane.getOperation(decodeURIComponent(Ke[1]));if(!P)throw new p("not_found","Operation was not found.",404);let b=P.resourceId?{type:"resource",id:P.resourceId}:P.environmentId?{type:"environment",id:P.environmentId}:P.projectId?{type:"project",id:P.projectId}:{type:"organization"};e.authorize(O,"deployments:read",b);let N=E.headers.get("last-event-id")?.trim(),G=Number(N||$.searchParams.get("after")||0);if(Ke[2]==="stream"){let jt=new TextEncoder,F=G,gt,ot=!1,q=new ReadableStream({start(ie){let Ur=()=>{if(ot)return;if(!t.identities.verifyToken(H,y)){if(ot=!0,gt)clearInterval(gt);ie.close();return}let tn=n.logs(P.id,{after:F,limit:500});for(let kt of tn)F=kt.sequence,ie.enqueue(jt.encode(`id: ${kt.sequence}
|
|
8
|
-
event: log
|
|
9
|
-
data: ${JSON.stringify(kt)}
|
|
10
|
-
|
|
11
|
-
`));let yt=t.controlPlane.getOperation(P.id);if(yt&&["succeeded","failed","cancelled","timed_out"].includes(yt.state)&&!n.logs(P.id,{after:F,limit:1}).length){if(ot=!0,gt)clearInterval(gt);ie.enqueue(jt.encode(`event: complete
|
|
12
|
-
data: ${JSON.stringify({state:yt.state,cursor:F})}
|
|
13
|
-
|
|
14
|
-
`)),ie.close()}};if(Ur(),!ot)gt=setInterval(Ur,500);E.signal.addEventListener("abort",()=>{if(ot=!0,gt)clearInterval(gt);try{ie.close()}catch{}},{once:!0})},cancel(){if(ot=!0,gt)clearInterval(gt)}});return new Response(q,{headers:{"content-type":"text/event-stream","cache-control":"no-store","x-accel-buffering":"no","x-request-id":C,...st}})}let vt=n.logs(P.id,{after:G,limit:Number($.searchParams.get("limit"))||void 0});Q={data:vt,cursor:vt.at(-1)?.sequence??G,hasMore:vt.length>=Math.min(1000,Math.max(1,Number($.searchParams.get("limit"))||200)),requestId:C}}else if(E.method==="POST"&&bn){let P=t.controlPlane.getOperation(decodeURIComponent(bn[1]));if(!P)throw new p("not_found","Operation was not found.",404);let b=P.resourceId?{type:"resource",id:P.resourceId}:P.environmentId?{type:"environment",id:P.environmentId}:P.projectId?{type:"project",id:P.projectId}:{type:"organization"},N=await rt();if(bn[2]==="cancel")e.authorize(O,"deployments:cancel",b),Q={operation:e.operation(n.requestCancellation(P.id,O.actor.id)),requestId:C};else e.authorize(O,"deployments:create",b),Q={operation:e.operation(n.retry(P.id,String(N.errorClass??"manual"),{delayMs:Number(N.delayMs)||0,actorId:O.actor.id})),requestId:C}}else if(E.method==="GET"&&$.pathname==="/api/v1/source/connections"){if(!t.sources)throw new p("not_found","Source integrations are unavailable.",404);e.authorize(O,"sources:read",O.token.scope),Q=Se(t.sources.listConnections(O.serviceAccount.organizationId),$,C,["createdAt","id"])}else if(E.method==="GET"&&$.pathname==="/api/v1/source/repositories"){if(!t.sources)throw new p("not_found","Source integrations are unavailable.",404);e.authorize(O,"sources:read",O.token.scope);let P=t.sources.getConnection($.searchParams.get("connectionId")??"");if(!P||P.organizationId!==O.serviceAccount.organizationId)throw new p("not_found","Source connection was not found.",404);if($.searchParams.get("sync")==="true")e.authorize(O,"sources:manage",{type:"organization"}),await Pc(t.sources,P.id,{search:$.searchParams.get("search")??void 0});Q=Se(t.sources.listRepositories(P.id,$.searchParams.get("search")??void 0),$,C,["fullName","id"])}else if(E.method==="GET"&&$.pathname==="/api/v1/source/refs"){if(!t.sources)throw new p("not_found","Source integrations are unavailable.",404);e.authorize(O,"sources:read",O.token.scope);let P=$.searchParams.get("connectionId")??"",b=t.sources.getConnection(P);if(!b||b.organizationId!==O.serviceAccount.organizationId)throw new p("not_found","Source connection was not found.",404);Q=await $c(t.sources,{connectionId:P,repository:$.searchParams.get("repository")??"",repositoryId:$.searchParams.get("repositoryId")??void 0,type:$.searchParams.get("type")==="tags"?"tags":"branches",cursor:$.searchParams.get("cursor")??void 0,deployKeyId:$.searchParams.get("deployKeyId")??void 0})}else if(E.method==="POST"&&$.pathname==="/api/v1/application-detections"){e.authorize(O,"applications:manage",O.token.scope);let P=await rt();if(!Array.isArray(P.files)||P.files.length>1e4)throw new p("validation_error","files must contain at most 10,000 entries.",422);Q={candidates:Nr(P.files.map((b)=>({path:String(b.path??""),size:Number(b.size??0),content:typeof b.content==="string"?b.content.slice(0,262144):void 0}))),requestId:C}}else if(E.method==="POST"&&$.pathname==="/api/v1/application-plans"){e.authorize(O,"applications:manage",O.token.scope);let P=await rt();Q={plan:Fe(P.draft,Array.isArray(P.suppliedSecretNames)?P.suppliedSecretNames.map(String):[]),requestId:C}}else if(E.method==="GET"&&$.pathname==="/api/v1/application-drafts"){if(!t.applications)throw new p("not_found","Application onboarding is unavailable.",404);let P=$.searchParams.get("projectId")??"";e.authorize(O,"applications:read",{type:"project",id:P}),Q=Se(t.applications.drafts.list(P),$,C,["updatedAt","id"])}else if(E.method==="POST"&&$.pathname==="/api/v1/application-drafts"){if(!t.applications)throw new p("not_found","Application onboarding is unavailable.",404);let P=await rt(),b=String(P.projectId??P.draft?.projectId??"");e.authorize(O,"applications:manage",{type:"project",id:b});let N=t.controlPlane.getProject(b);if(!N||N.organizationId!==O.serviceAccount.organizationId)throw new p("not_found","Project was not found.",404);let G=t.applications.drafts.create({organizationId:N.organizationId,projectId:b,name:String(P.name??P.draft?.name??"Application draft"),draft:{...P.draft,projectId:b},step:P.step,suppliedSecretNames:Array.isArray(P.suppliedSecretNames)?P.suppliedSecretNames.map(String):[],actorId:O.actor.id});return f({draft:G,requestId:C},201,C,st)}else if(E.method==="PATCH"&&$.pathname==="/api/v1/application-drafts"){if(!t.applications)throw new p("not_found","Application onboarding is unavailable.",404);let P=await rt(),b=t.applications.drafts.get(String(P.id??""));if(!b)throw new p("not_found","Application draft was not found.",404);e.authorize(O,"applications:manage",{type:"project",id:b.projectId}),Q={draft:t.applications.drafts.update(b.id,Number(P.version),{draft:{...P.draft,projectId:b.projectId},step:P.step,suppliedSecretNames:Array.isArray(P.suppliedSecretNames)?P.suppliedSecretNames.map(String):void 0,actorId:O.actor.id}),requestId:C}}else if(E.method==="POST"&&$.pathname==="/api/v1/applications"){if(!t.applications)throw new p("not_found","Application onboarding is unavailable.",404);let P=E.headers.get("idempotency-key")??"";if(!P)throw new p("idempotency_required","Idempotency-Key is required for application creation.",428);if(!/^[A-Za-z0-9._:-]{8,128}$/.test(P))throw new p("validation_error","Idempotency-Key must contain 8-128 safe characters.",422);let b=await rt(),N=t.applications.drafts.get(String(b.draftId??""));if(!N)throw new p("not_found","Application draft was not found.",404);e.authorize(O,"applications:manage",{type:"project",id:N.projectId});let G=aI("sha256").update(`POST
|
|
15
|
-
/api/v1/applications
|
|
16
|
-
${JSON.stringify(b)}`).digest("hex"),vt=t.identities.getIdempotency(O.token.id,P);if(vt){if(vt.requestHash!==G)throw new p("idempotency_conflict","Idempotency-Key was already used for another request.",409);let F=vt.operationId?t.controlPlane.getOperation(vt.operationId):void 0,gt=F?.resourceId?t.controlPlane.getResource(F.resourceId):void 0;if(!F||!gt)throw new p("idempotency_unavailable","The original application operation is no longer available.",409);return f({resource:gt,operation:e.operation(F),plan:Fe(N.input,N.suppliedSecretNames),idempotentReplay:!0,requestId:C},202,C,{...st,"idempotent-replayed":"true"})}let jt=wc({controlPlane:t.controlPlane,drafts:t.applications.drafts,draftId:N.id,expectedVersion:Number(b.version),confirmEnvironment:String(b.confirmEnvironment??""),actorId:O.actor.id});return t.identities.saveIdempotency({tokenId:O.token.id,key:P,requestHash:G,operationId:jt.operation.id,responseStatus:202,responseBody:{draftId:N.id}}),f({resource:jt.resource,operation:e.operation(jt.operation),plan:jt.plan,idempotentReplay:!1,requestId:C},202,C,st)}else if(E.method==="GET"&&$.pathname==="/api/v1/registry-connections"){if(!t.applications)throw new p("not_found","Application onboarding is unavailable.",404);e.authorize(O,"applications:read",O.token.scope),Q=Se(t.applications.registries.list(O.serviceAccount.organizationId),$,C,["createdAt","id"])}else if(E.method==="POST"&&$.pathname==="/api/v1/registry-connections"){if(!t.applications)throw new p("not_found","Application onboarding is unavailable.",404);e.authorize(O,"applications:manage",{type:"organization"});let P=await rt(),b=t.applications.registries.create({organizationId:O.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:O.actor.id});return f({registry:b,requestId:C},201,C,st)}else if(E.method==="PATCH"&&$.pathname==="/api/v1/registry-connections"){if(!t.applications)throw new p("not_found","Application onboarding is unavailable.",404);e.authorize(O,"applications:manage",{type:"organization"});let P=await rt(),b=t.applications.registries.get(String(P.id??""));if(!b||b.organizationId!==O.serviceAccount.organizationId)throw new p("not_found","Registry connection was not found.",404);if(P.action==="test")Q={registry:await t.applications.registries.test(b.id,{image:typeof P.image==="string"?P.image:void 0}),requestId:C};else if(P.action==="rotate")Q={registry:t.applications.registries.rotate(b.id,{username:P.username,password:P.password,token:P.token},{expiresAt:P.expiresAt,actorId:O.actor.id}),requestId:C};else throw new p("validation_error","action must be test or rotate.",422)}else if(E.method==="DELETE"&&$.pathname==="/api/v1/registry-connections"){if(!t.applications)throw new p("not_found","Application onboarding is unavailable.",404);e.authorize(O,"applications:manage",{type:"organization"});let P=await rt(),b=t.applications.registries.get(String(P.id??""));if(!b||b.organizationId!==O.serviceAccount.organizationId)throw new p("not_found","Registry connection was not found.",404);Q={registry:t.applications.registries.disconnect(b.id,O.actor.id),requestId:C}}else if(E.method==="POST"&&$.pathname==="/api/v1/application-artifacts"){if(!t.applications?.artifacts)throw new p("not_found","Application artifact storage is unavailable.",404);let P=E.headers.get("x-project-id")??"";e.authorize(O,"applications:manage",{type:"project",id:P});let b=t.controlPlane.getProject(P);if(!b||b.organizationId!==O.serviceAccount.organizationId)throw new p("not_found","Project was not found.",404);if(Number(E.headers.get("content-length")??0)>104857600)throw new p("payload_too_large","Artifact exceeds 100 MB.",413);let G=t.applications.artifacts.create({organizationId:b.organizationId,projectId:P,filename:E.headers.get("x-artifact-filename")??"application.zip",bytes:new Uint8Array(await E.arrayBuffer()),actorId:O.actor.id});return f({artifact:G,requestId:C},201,C,st)}else if(E.method==="POST"&&$.pathname==="/api/v1/source/connections"){if(!t.sources)throw new p("not_found","Source integrations are unavailable.",404);e.authorize(O,"sources:manage",{type:"organization"});let P=await rt(),b=String(P.provider??"");if(!["github","gitlab","bitbucket","gitea","generic_https","generic_ssh"].includes(b))throw new p("validation_error","A supported provider is required.",422);let N=b==="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}:b!=="generic_ssh"&&P.token?{token:String(P.token),username:typeof P.username==="string"?P.username:void 0}:void 0,G,vt,jt;return t.controlPlane.database.transaction(()=>{if(G=t.sources.createConnection({organizationId:O.serviceAccount.organizationId,provider:b,name:String(P.name??b),host:String(P.host??""),owner:typeof P.owner==="string"?P.owner:void 0,authKind:P.authKind,credential:N,createdByActorId:O.actor.id}),typeof P.repositoryUrl==="string"&&typeof P.repositoryFullName==="string")vt=t.sources.upsertRepository({connectionId:G.id,providerRepositoryId:`manual:${P.repositoryFullName}`,fullName:P.repositoryFullName,cloneUrl:P.repositoryUrl,defaultBranch:String(P.defaultBranch??"main"),visibility:"unknown",archived:!1,metadata:{source:"api"}});if(b==="generic_ssh")jt=t.sources.createDeployKey({connectionId:G.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:O.actor.id})})(),f({connection:G,repository:vt,deployKey:jt,requestId:C},201,C,st)}else if(E.method==="POST"&&$.pathname==="/api/v1/source/bindings"){if(!t.sources)throw new p("not_found","Source integrations are unavailable.",404);let P=await rt(),b=String(P.projectId??"");e.authorize(O,"sources:manage",{type:"project",id:b});let N=t.sources.getConnection(String(P.connectionId??""));if(!N||N.organizationId!==O.serviceAccount.organizationId)throw new p("not_found","Source connection was not found.",404);let G=t.sources.createBinding({projectId:b,environmentId:typeof P.environmentId==="string"?P.environmentId:void 0,resourceId:typeof P.resourceId==="string"?P.resourceId:void 0,connectionId:N.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:O.actor.id});return f({binding:G,requestId:C},201,C,st)}else if(E.method==="POST"&&$.pathname==="/api/v1/source/webhooks"){if(!t.sources)throw new p("not_found","Source integrations are unavailable.",404);e.authorize(O,"sources:manage",{type:"organization"});let P=await rt(),b=t.sources.getConnection(String(P.connectionId??""));if(!b||b.organizationId!==O.serviceAccount.organizationId)throw new p("not_found","Source connection was not found.",404);let N=typeof P.baseUrl==="string"?P.baseUrl:void 0;if(!N)throw new p("validation_error","baseUrl is required.",422);let G=t.sources.createWebhook({connectionId:b.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}),vt=Qr(N,G.webhook),jt=P.reconcile===!1?G.webhook:await bi(t.sources,G.webhook.id,N);return f({webhook:jt,endpoint:vt,endpointRevealOnce:!0,requestId:C},201,C,st)}else if(E.method==="DELETE"&&$.pathname==="/api/v1/source/connections"){if(!t.sources)throw new p("not_found","Source integrations are unavailable.",404);e.authorize(O,"sources:manage",{type:"organization"});let P=await rt(),b=t.sources.getConnection(String(P.id??""));if(!b||b.organizationId!==O.serviceAccount.organizationId)throw new p("not_found","Source connection was not found.",404);let N=t.sources.listBindings({connectionId:b.id,status:"active"});if(P.preview===!0)return f({preview:!0,affectedBindings:N,requestId:C},200,C,st);return f({...t.sources.disconnectConnection(b.id,O.actor.id),requestId:C},200,C,st)}else if(E.method==="GET"&&($.pathname==="/api/v1/events"||$.pathname==="/api/v1/events/stream")){let P=e.listEvents(O,$.searchParams.get("projectId")??void 0,Number($.searchParams.get("after"))||void 0);if($.pathname.endsWith("/stream")){let b=new TextEncoder,N=P.reduce((F,gt)=>Math.max(F,Number(gt.sequence)),Number($.searchParams.get("after"))||0),G,vt=!1,jt=new ReadableStream({start(F){let gt=(ot)=>F.enqueue(b.encode(`id: ${ot.sequence}
|
|
17
|
-
event: ${ot.type}
|
|
18
|
-
data: ${JSON.stringify(ot)}
|
|
19
|
-
|
|
20
|
-
`));if(P.length)P.forEach(gt);else F.enqueue(b.encode(`: connected
|
|
21
|
-
|
|
22
|
-
`));G=setInterval(()=>{if(vt)return;let ot=t.identities.verifyToken(H,y);if(!ot){if(vt=!0,G)clearInterval(G);F.close();return}try{let q=e.listEvents(ot,$.searchParams.get("projectId")??void 0,N);for(let ie of q)gt(ie),N=Math.max(N,Number(ie.sequence));if(!q.length)F.enqueue(b.encode(`: heartbeat ${Date.now()}
|
|
23
|
-
|
|
24
|
-
`))}catch{if(vt=!0,G)clearInterval(G);F.close()}},1000),E.signal.addEventListener("abort",()=>{if(vt=!0,G)clearInterval(G);try{F.close()}catch{}},{once:!0})},cancel(){if(vt=!0,G)clearInterval(G)}});return new Response(jt,{status:200,headers:{"content-type":"text/event-stream","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no","x-request-id":C,...st}})}Q=Se(P,$,C,["sequence","id"])}else if(E.method==="POST"&&$.pathname==="/api/v1/deployments"){let P=E.headers.get("idempotency-key")??"";if(!P)throw new p("idempotency_required","Idempotency-Key is required for deployment requests.",428);let b=await E.text();if(b.length>1048576)throw new p("payload_too_large","Request body exceeds 1 MB.",413);let N;try{N=JSON.parse(b)}catch{throw new p("invalid_json","Request body must be valid JSON.",400)}if(!N||typeof N.projectId!=="string"||typeof N.environmentId!=="string"||N.action!==void 0&&!["deploy","rollback"].includes(N.action))throw new p("validation_error","projectId, environmentId, and a valid action are required.",422);let G=e.createDeployment(O,N,P);return f({operation:G.operation,idempotentReplay:G.replay,requestId:C},202,C,{...st,...G.replay?{"idempotent-replayed":"true"}:{}})}else{let P=await nu({...a,authorization:e,now:o},O,{method:E.method,url:$,body:rt});if(P===void 0)throw new p("not_found","API resource was not found.",404);Q=P}return f(Q,200,C,st)}catch(Q){if(Q instanceof p)return R(Q.code,Q.message,Q.status,C,Q.details,st);if($.pathname.startsWith("/api/v1/source/")||$.pathname.startsWith("/api/v1/application")||$.pathname.startsWith("/api/v1/compose-")||$.pathname==="/api/v1/registry-connections")return R("validation_error",Q instanceof Error?Q.message:"Integration request could not be completed.",422,C,void 0,st);return R("internal_error","The API request could not be completed.",500,C,void 0,st)}}}import{createCipheriv as hI,createDecipheriv as SI,createHash as su,randomBytes as Sn}from"node:crypto";import{createHmac as gI,timingSafeEqual as uI}from"node:crypto";var Ko="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";function Jc(t){let e=0,n=0,r="";for(let i of t){n=n<<8|i,e+=8;while(e>=5)r+=Ko[n>>>e-5&31],e-=5}if(e>0)r+=Ko[n<<5-e&31];return r}function ru(t){let e=t.toUpperCase().replace(/[^A-Z2-7]/g,""),n=0,r=0,i=[];for(let c of e){let d=Ko.indexOf(c);if(d<0)throw Error("Invalid base32 secret");if(r=r<<5|d,n+=5,n>=8)i.push(r>>>n-8&255),n-=8}return Buffer.from(i)}function iu(t,e,n=6){let r=Buffer.alloc(8);r.writeBigUInt64BE(BigInt(e));let i=gI("sha1",ru(t)).update(r).digest(),c=i[i.length-1]&15,d=(i[c]&127)<<24|(i[c+1]&255)<<16|(i[c+2]&255)<<8|i[c+3]&255;return String(d%10**n).padStart(n,"0")}function Bc(t,e,n=Date.now(),r=1){let i=e.replace(/[\s-]/g,"");if(!/^\d{6}$/.test(i))return;let c=Buffer.from(i),d=Math.floor(n/1000/30);for(let a=-r;a<=r;a++){if(d+a<0)continue;let l=Buffer.from(iu(t,d+a));if(c.length===l.length&&uI(c,l))return d+a}return}function po(t){let e=t.issuer?.trim()||"ts-cloud",n=`${e}:${t.account}`;return`otpauth://totp/${encodeURIComponent(n)}?secret=${encodeURIComponent(t.secret)}&issuer=${encodeURIComponent(e)}&algorithm=SHA1&digits=6&period=30`}var lu=1800000,Qn=43200000,gu=3600000,uu=300000,hu=600000;function $e(t){return typeof t==="string"?t:void 0}function Su(t){if(typeof t!=="string")return{};try{return JSON.parse(t)}catch{return{}}}function fI(t){let e=t.trim();if(!/^[a-z0-9][a-z0-9._-]{1,31}$/i.test(e))throw Error("Username must be 2-32 characters: letters, numbers, dot, dash or underscore");return e}function mo(t){if(t===void 0||!t.trim())return;let e=t.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)||e.length>254)throw Error("A valid email address is required");return e}function _I(t){let e=t.trim().toLowerCase();if(!/^[a-z0-9][a-z0-9-]{1,47}$/.test(e))throw Error("OIDC provider slug must be 2-48 lowercase letters, numbers or dashes");return e}function RI(t){let e=new URL(t.trim());if(e.search||e.hash||e.username||e.password)throw Error("OIDC issuer cannot contain credentials, a query, or a fragment");if(e.protocol!=="https:"&&!(e.protocol==="http:"&&["127.0.0.1","::1","localhost"].includes(e.hostname)))throw Error("OIDC issuer must use HTTPS");return e.href.replace(/\/$/,"")}function EI(t){let e=[...new Set(t.map((n)=>n.trim().toLowerCase()).filter(Boolean))];if(e.length===0)throw Error("At least one explicit OIDC email domain is required");if(e.some((n)=>!/^[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?$/.test(n)||!n.includes(".")||n.includes("..")))throw Error("OIDC email domains must be explicit DNS names without wildcards");return e}function II(t){let e=[...new Set(["openid",...t??["email","profile"]].map((n)=>n.trim()).filter(Boolean))];if(e.some((n)=>!/^[\x21\x23-\x5B\x5D-\x7E]+$/.test(n)))throw Error("OIDC scopes contain unsupported characters");return e}function Ve(t){return su("sha256").update(t).digest("hex")}function Wi(t){return{id:String(t.id),actorId:String(t.actor_id),username:String(t.username),email:$e(t.email),emailVerifiedAt:$e(t.email_verified_at),passwordHash:String(t.password_hash),credentialVersion:Number(t.credential_version),requiresPasswordUpgrade:Number(t.requires_password_upgrade)===1,disabledAt:$e(t.disabled_at),lastLoginAt:$e(t.last_login_at),createdAt:String(t.created_at),updatedAt:String(t.updated_at)}}function cu(t,e){let n=$e(t.consumed_at),r=String(t.expires_at);return{id:String(t.id),identityId:String(t.identity_id),type:String(t.type),metadata:Su(t.metadata),expiresAt:r,consumedAt:n,createdAt:String(t.created_at),state:n?"consumed":r<=e?"expired":"pending"}}function qo(t,e){let n=$e(t.revoked_at),r=String(t.idle_expires_at),i=String(t.absolute_expires_at);return{id:String(t.id),identityId:String(t.identity_id),credentialVersion:Number(t.credential_version),authMethod:String(t.auth_method),userAgent:$e(t.user_agent),networkHint:$e(t.network_hint),createdAt:String(t.created_at),lastUsedAt:String(t.last_used_at),idleExpiresAt:r,absoluteExpiresAt:i,recentAuthAt:String(t.recent_auth_at),mfaAt:$e(t.mfa_at),revokedAt:n,state:n?"revoked":r<=e||i<=e?"expired":"active"}}function du(t){let e=$e(t.verified_at),n=$e(t.disabled_at);return{id:String(t.id),identityId:String(t.identity_id),type:"totp",label:String(t.label),createdAt:String(t.created_at),verifiedAt:e,disabledAt:n,state:n?"disabled":e?"active":"pending"}}function ta(t,e){let n=$e(t.consumed_at),r=String(t.expires_at),i=Number(t.attempts);return{id:String(t.id),identityId:String(t.identity_id),purpose:String(t.purpose),attempts:i,expiresAt:r,consumedAt:n,createdAt:String(t.created_at),state:n?"consumed":i>=5?"locked":r<=e?"expired":"pending"}}function ou(t){let e=Su(t);return Array.isArray(e)?e.filter((n)=>typeof n==="string"):[]}function zc(t){return{id:String(t.id),organizationId:String(t.organization_id),slug:String(t.slug),name:String(t.name),issuer:String(t.issuer),clientId:String(t.client_id),hasClientSecret:typeof t.client_secret_ciphertext==="string"&&t.client_secret_ciphertext.length>0,scopes:ou(t.scopes),allowedDomains:ou(t.allowed_domains),defaultRole:String(t.default_role),enabled:Number(t.enabled)===1,enforceSso:Number(t.enforce_sso)===1,createdAt:String(t.created_at),updatedAt:String(t.updated_at)}}function au(t,e){let n=$e(t.consumed_at),r=String(t.expires_at);return{id:String(t.id),providerId:String(t.provider_id),redirectUri:String(t.redirect_uri),returnPath:String(t.return_path),expiresAt:r,consumedAt:n,createdAt:String(t.created_at),state:n?"consumed":r<=e?"expired":"pending"}}function wI(t){return{id:String(t.id),providerId:String(t.provider_id),identityId:String(t.identity_id),subject:String(t.subject),email:String(t.email),linkedAt:String(t.linked_at),lastLoginAt:String(t.last_login_at)}}class Tc{controlPlane;nowFn;idFn;encryptionKey;constructor(t,e={}){this.controlPlane=t;this.nowFn=e.now??(()=>new Date),this.idFn=e.id??(()=>crypto.randomUUID()),this.encryptionKey=e.encryptionKey?su("sha256").update(e.encryptionKey).digest():void 0}now(){return this.nowFn().toISOString()}run(t,e){this.controlPlane.database.run(t,e)}encrypt(t){if(!this.encryptionKey)throw Error("Authentication encryption key is not configured");let e=Sn(12),n=hI("aes-256-gcm",this.encryptionKey,e),r=Buffer.concat([n.update(t,"utf8"),n.final()]);return`v1.${e.toString("base64url")}.${n.getAuthTag().toString("base64url")}.${r.toString("base64url")}`}decrypt(t){if(!this.encryptionKey)throw Error("Authentication encryption key is not configured");let[e,n,r,i]=t.split(".");if(e!=="v1"||!n||!r||!i)throw Error("Encrypted authentication value is unavailable");let c=SI("aes-256-gcm",this.encryptionKey,Buffer.from(n,"base64url"));return c.setAuthTag(Buffer.from(r,"base64url")),Buffer.concat([c.update(Buffer.from(i,"base64url")),c.final()]).toString("utf8")}createIdentity(t){if(!this.controlPlane.getActor(t.actorId))throw Error("Authentication actor was not found");let e=fI(t.username),n=mo(t.email),r=t.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)
|
|
25
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[r,t.actorId,e,n??null,t.emailVerified&&n?i:null,t.passwordHash,t.requiresPasswordUpgrade?1:0,i,i]),this.getIdentity(r)}getIdentity(t){let e=this.controlPlane.database.query("SELECT * FROM auth_identities WHERE id = ?").get(t);return e?Wi(e):void 0}getIdentityByActor(t){let e=this.controlPlane.database.query("SELECT * FROM auth_identities WHERE actor_id = ?").get(t);return e?Wi(e):void 0}getIdentityByUsername(t){let e=this.controlPlane.database.query("SELECT * FROM auth_identities WHERE username = ? COLLATE NOCASE").get(t.trim());return e?Wi(e):void 0}getIdentityByEmail(t){let e=this.controlPlane.database.query("SELECT * FROM auth_identities WHERE email = ? COLLATE NOCASE").get(t.trim().toLowerCase());return e?Wi(e):void 0}listIdentities(){return this.controlPlane.database.query("SELECT * FROM auth_identities ORDER BY username COLLATE NOCASE").all().map(Wi)}updatePassword(t,e,n={}){if(!this.getIdentity(t))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,
|
|
26
|
-
requires_password_upgrade = ?, updated_at = ? WHERE id = ?`,[e,n.requiresUpgrade?1:0,i,t]),n.revokeSessions!==!1)this.run("UPDATE auth_sessions SET revoked_at = ? WHERE identity_id = ? AND revoked_at IS NULL",[i,t])}),this.getIdentity(t)}rehashPassword(t,e){let n=this.now();this.run("UPDATE auth_identities SET password_hash = ?, requires_password_upgrade = 0, updated_at = ? WHERE id = ?",[e,n,t]);let r=this.getIdentity(t);if(!r)throw Error("Authentication identity was not found");return r}setVerifiedEmail(t,e){let n=mo(e),r=this.now();this.run("UPDATE auth_identities SET email = ?, email_verified_at = ?, updated_at = ? WHERE id = ?",[n,r,r,t]);let i=this.getIdentity(t);if(!i)throw Error("Authentication identity was not found");return i}recordLogin(t){let e=this.now();this.run("UPDATE auth_identities SET last_login_at = ?, updated_at = ? WHERE id = ?",[e,e,t]);let n=this.getIdentity(t);if(!n)throw Error("Authentication identity was not found");return n}setDisabled(t,e){let n=this.now();this.controlPlane.transaction(()=>{if(this.run("UPDATE auth_identities SET disabled_at = ?, credential_version = credential_version + 1, updated_at = ? WHERE id = ?",[e?n:null,n,t]),e)this.run("UPDATE auth_sessions SET revoked_at = ? WHERE identity_id = ? AND revoked_at IS NULL",[n,t])});let r=this.getIdentity(t);if(!r)throw Error("Authentication identity was not found");return r}createActionToken(t,e,n={}){if(!this.getIdentity(t))throw Error("Authentication identity was not found");let r=Sn(32).toString("base64url"),i=this.idFn(),c=this.now(),d=new Date(this.nowFn().getTime()+Math.min(86400000,Math.max(60000,n.ttlMs??gu))).toISOString();return this.run("INSERT INTO auth_action_tokens (id, identity_id, type, token_hash, metadata, expires_at, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[i,t,e,Ve(r),JSON.stringify(n.metadata??{}),d,c]),{actionToken:this.getActionToken(i),token:r}}getActionToken(t){let e=this.controlPlane.database.query("SELECT * FROM auth_action_tokens WHERE id = ?").get(t);return e?cu(e,this.now()):void 0}consumeActionToken(t,e){return this.controlPlane.transaction(()=>{let n=this.controlPlane.database.query("SELECT * FROM auth_action_tokens WHERE token_hash = ? AND type = ?").get(Ve(t),e);if(!n)throw Error("Action token is invalid");let r=cu(n,this.now());if(r.state!=="pending")throw Error(`Action token is ${r.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(),r.id,this.now()]).changes!==1)throw Error("Action token is no longer available");return this.getActionToken(r.id)})}revokeActionTokens(t,e){return this.controlPlane.database.run("UPDATE auth_action_tokens SET consumed_at = ? WHERE identity_id = ? AND type = ? AND consumed_at IS NULL",[this.now(),t,e]).changes}createSession(t){let e=this.getIdentity(t.identityId);if(!e||e.disabledAt)throw Error("Authentication identity is unavailable");let n=this.idFn(),r=Sn(32).toString("base64url"),i=`v2.${n}.${r}`,c=this.now(),d=Math.min(86400000,Math.max(60000,t.idleTtlMs??lu)),a=Math.min(2592000000,Math.max(d,t.absoluteTtlMs??Qn));return this.run(`INSERT INTO auth_sessions (id, identity_id, token_hash, credential_version, auth_method, user_agent, network_hint,
|
|
27
|
-
created_at, last_used_at, idle_expires_at, absolute_expires_at, recent_auth_at, mfa_at)
|
|
28
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n,e.id,Ve(i),e.credentialVersion,t.authMethod??"local",t.userAgent?.slice(0,256)??null,t.networkHint?.slice(0,128)??null,c,c,new Date(this.nowFn().getTime()+d).toISOString(),new Date(this.nowFn().getTime()+a).toISOString(),t.recentAuthAt??c,t.mfaAt??null]),{session:this.getSession(n),token:i}}getSession(t){let e=this.controlPlane.database.query("SELECT * FROM auth_sessions WHERE id = ?").get(t);return e?qo(e,this.now()):void 0}verifySessionToken(t){let e=/^v2\.([^.]+)\.[A-Za-z0-9_-]{40,}$/.exec(t);if(!e)return;let n=this.controlPlane.database.query("SELECT * FROM auth_sessions WHERE id = ? AND token_hash = ?").get(e[1],Ve(t));if(!n)return;let r=qo(n,this.now()),i=this.getIdentity(r.identityId);if(!i||i.disabledAt||r.state!=="active"||r.credentialVersion!==i.credentialVersion)return;let c=this.now(),d=new Date(n.idle_expires_at).getTime()-new Date(n.last_used_at).getTime();return this.run("UPDATE auth_sessions SET last_used_at = ?, idle_expires_at = ? WHERE id = ?",[c,new Date(Math.min(this.nowFn().getTime()+d,new Date(r.absoluteExpiresAt).getTime())).toISOString(),r.id]),{identity:i,session:this.getSession(r.id)}}listSessions(t,e={}){let n=this.controlPlane.database.query("SELECT * FROM auth_sessions WHERE identity_id = ? ORDER BY last_used_at DESC").all(t).map((r)=>qo(r,this.now()));return e.includeInactive?n:n.filter((r)=>r.state==="active")}revokeSession(t,e){return this.controlPlane.database.run("UPDATE auth_sessions SET revoked_at = ? WHERE id = ? AND identity_id = ? AND revoked_at IS NULL",[this.now(),e,t]).changes===1}revokeOtherSessions(t,e){return this.controlPlane.database.run("UPDATE auth_sessions SET revoked_at = ? WHERE identity_id = ? AND id != ? AND revoked_at IS NULL",[this.now(),t,e]).changes}getMfaFactor(t){let e=this.controlPlane.database.query("SELECT * FROM auth_mfa_factors WHERE identity_id = ?").get(t);return e?du(e):void 0}beginTotpEnrollment(t,e={}){let n=this.getIdentity(t);if(!n)throw Error("Authentication identity was not found");let r=this.getMfaFactor(t);if(r?.state==="active")throw Error("MFA is already enabled");let i=Jc(Sn(20)),c=e.label?.trim().slice(0,80)||n.email||n.username,d=r?.id??this.idFn(),a=this.now();return this.controlPlane.transaction(()=>{if(r)this.run("UPDATE auth_mfa_factors SET label = ?, secret_ciphertext = ?, created_at = ?, verified_at = NULL, disabled_at = NULL WHERE id = ?",[c,this.encrypt(i),a,d]);else this.run("INSERT INTO auth_mfa_factors (id, identity_id, label, secret_ciphertext, created_at) VALUES (?, ?, ?, ?, ?)",[d,t,c,this.encrypt(i),a]);this.run("DELETE FROM auth_recovery_codes WHERE identity_id = ?",[t])}),{factor:this.getMfaFactor(t),secret:i,uri:po({secret:i,account:c,issuer:e.issuer})}}verifyTotpEnrollment(t,e){let n=this.controlPlane.database.query("SELECT * FROM auth_mfa_factors WHERE identity_id = ?").get(t);if(!n||du(n).state!=="pending")throw Error("MFA enrollment is not pending");let r=Bc(this.decrypt(String(n.secret_ciphertext)),e,this.nowFn().getTime());if(r===void 0)throw Error("Authenticator code is invalid");let i=Array.from({length:10},()=>{let d=Jc(Sn(8)).slice(0,12);return`${d.slice(0,4)}-${d.slice(4,8)}-${d.slice(8)}`}),c=this.now();return this.controlPlane.transaction(()=>{this.run("UPDATE auth_mfa_factors SET verified_at = ?, disabled_at = NULL, last_used_step = ? WHERE identity_id = ?",[c,r,t]),this.run("DELETE FROM auth_recovery_codes WHERE identity_id = ?",[t]);for(let d of i)this.run("INSERT INTO auth_recovery_codes (id, identity_id, code_hash, created_at) VALUES (?, ?, ?, ?)",[this.idFn(),t,Ve(`${t}:${d.replace(/-/g,"").toUpperCase()}`),c])}),{factor:this.getMfaFactor(t),recoveryCodes:i}}verifyMfaCode(t,e,n={}){let r=this.controlPlane.database.query("SELECT * FROM auth_mfa_factors WHERE identity_id = ? AND verified_at IS NOT NULL AND disabled_at IS NULL").get(t);if(!r)return{valid:!1};let i=Bc(this.decrypt(String(r.secret_ciphertext)),e,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,t,i]).changes===1)return{valid:!0,method:"totp"}}let c=e.replace(/[-\s]/g,"").toUpperCase();if(!/^[A-Z2-7]{12}$/.test(c))return{valid:!1};let d=Ve(`${t}:${c}`),a=this.controlPlane.database.query("SELECT * FROM auth_recovery_codes WHERE identity_id = ? AND code_hash = ? AND consumed_at IS NULL").get(t,d);if(!a)return{valid:!1};if(n.consumeRecovery!==!1){if(this.controlPlane.database.run("UPDATE auth_recovery_codes SET consumed_at = ? WHERE id = ? AND consumed_at IS NULL",[this.now(),String(a.id)]).changes!==1)return{valid:!1}}return{valid:!0,method:"recovery"}}remainingRecoveryCodes(t){return Number(this.controlPlane.database.query("SELECT COUNT(*) AS count FROM auth_recovery_codes WHERE identity_id = ? AND consumed_at IS NULL").get(t)?.count??0)}disableMfa(t){let e=this.now();this.controlPlane.transaction(()=>{this.run("UPDATE auth_mfa_factors SET disabled_at = ? WHERE identity_id = ? AND disabled_at IS NULL",[e,t]),this.run("DELETE FROM auth_recovery_codes WHERE identity_id = ?",[t]),this.run("UPDATE auth_mfa_challenges SET consumed_at = ? WHERE identity_id = ? AND consumed_at IS NULL",[e,t])})}createMfaChallenge(t,e){if(this.getMfaFactor(t)?.state!=="active")throw Error("MFA is not enabled");let n=Sn(32).toString("base64url"),r=this.idFn(),i=this.now(),c=new Date(this.nowFn().getTime()+uu).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,t,e]),this.run("INSERT INTO auth_mfa_challenges (id, identity_id, purpose, token_hash, expires_at, created_at) VALUES (?, ?, ?, ?, ?, ?)",[r,t,e,Ve(n),c,i])}),{challenge:this.getMfaChallenge(r),token:n}}getMfaChallenge(t){let e=this.controlPlane.database.query("SELECT * FROM auth_mfa_challenges WHERE id = ?").get(t);return e?ta(e,this.now()):void 0}inspectMfaChallengeToken(t,e){let n=this.controlPlane.database.query("SELECT * FROM auth_mfa_challenges WHERE token_hash = ? AND purpose = ?").get(Ve(t),e);return n?ta(n,this.now()):void 0}completeMfaChallenge(t,e,n){let r=this.controlPlane.database.query("SELECT * FROM auth_mfa_challenges WHERE token_hash = ? AND purpose = ?").get(Ve(t),n);if(!r)throw Error("MFA challenge is invalid");let i=ta(r,this.now());if(i.state!=="pending")throw Error(`MFA challenge is ${i.state}`);let c=this.verifyMfaCode(i.identityId,e);if(!c.valid||!c.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:c.method}}markSessionStepUp(t,e=!1){let n=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",[n,e?1:0,n,t]);let r=this.getSession(t);if(!r)throw Error("Authentication session was not found");return r}isRecentlyAuthenticated(t,e=600000){return this.nowFn().getTime()-new Date(t.recentAuthAt).getTime()<=e}upsertOidcProvider(t){if(!this.controlPlane.getOrganization(t.organizationId))throw Error("OIDC provider organization was not found");let e=_I(t.slug),n=t.name.trim().slice(0,80);if(!n)throw Error("OIDC provider name is required");let r=RI(t.issuer),i=t.clientId.trim();if(!i||i.length>512)throw Error("OIDC client ID is required");let c=II(t.scopes),d=EI(t.allowedDomains),a=t.id?this.getOidcProvider(t.id):this.getOidcProviderBySlug(e),l=this.now();if(a){if(a.organizationId!==t.organizationId)throw Error("OIDC provider belongs to another organization");return this.run(`UPDATE auth_oidc_providers SET slug = ?, name = ?, issuer = ?, client_id = ?,
|
|
29
|
-
client_secret_ciphertext = COALESCE(?, client_secret_ciphertext), scopes = ?, allowed_domains = ?,
|
|
30
|
-
default_role = ?, enabled = ?, enforce_sso = ?, updated_at = ? WHERE id = ?`,[e,n,r,i,t.clientSecret?this.encrypt(t.clientSecret):null,JSON.stringify(c),JSON.stringify(d),t.defaultRole??a.defaultRole,t.enabled??a.enabled?1:0,t.enforceSso??a.enforceSso?1:0,l,a.id]),this.getOidcProvider(a.id)}if(!t.clientSecret)throw Error("OIDC client secret is required for a new provider");let o=t.id??this.idFn();return this.run(`INSERT INTO auth_oidc_providers (id, organization_id, slug, name, issuer, client_id,
|
|
31
|
-
client_secret_ciphertext, scopes, allowed_domains, default_role, enabled, enforce_sso, created_at, updated_at)
|
|
32
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[o,t.organizationId,e,n,r,i,this.encrypt(t.clientSecret),JSON.stringify(c),JSON.stringify(d),t.defaultRole??"viewer",t.enabled===!1?0:1,t.enforceSso?1:0,l,l]),this.getOidcProvider(o)}getOidcProvider(t){let e=this.controlPlane.database.query("SELECT * FROM auth_oidc_providers WHERE id = ?").get(t);return e?zc(e):void 0}getOidcProviderBySlug(t){let e=this.controlPlane.database.query("SELECT * FROM auth_oidc_providers WHERE slug = ? COLLATE NOCASE").get(t.trim());return e?zc(e):void 0}listOidcProviders(t,e={}){return(t?this.controlPlane.database.query("SELECT * FROM auth_oidc_providers WHERE organization_id = ? ORDER BY name COLLATE NOCASE").all(t):this.controlPlane.database.query("SELECT * FROM auth_oidc_providers ORDER BY name COLLATE NOCASE").all()).map(zc).filter((r)=>e.includeDisabled||r.enabled)}setOidcProviderEnabled(t,e){let n=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 = ?",[e?1:0,e?1:0,n,t]).changes!==1)throw Error("OIDC provider was not found");if(!e)this.run("UPDATE auth_oidc_transactions SET consumed_at = ? WHERE provider_id = ? AND consumed_at IS NULL",[n,t]);return this.getOidcProvider(t)}getOidcProviderCredentials(t){let e=this.controlPlane.database.query("SELECT * FROM auth_oidc_providers WHERE id = ?").get(t);if(!e||typeof e.client_secret_ciphertext!=="string")throw Error("OIDC provider credentials are unavailable");return{provider:zc(e),clientSecret:this.decrypt(e.client_secret_ciphertext)}}beginOidcTransaction(t,e,n){if(!this.getOidcProvider(t)?.enabled)throw Error("OIDC provider is unavailable");let i=this.idFn(),c=Sn(32).toString("base64url"),d=Sn(32).toString("base64url"),a=Sn(64).toString("base64url"),l=this.now(),o=new Date(this.nowFn().getTime()+hu).toISOString();return this.run(`INSERT INTO auth_oidc_transactions (id, provider_id, state_hash, nonce_ciphertext, verifier_ciphertext,
|
|
33
|
-
redirect_uri, return_path, expires_at, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i,t,Ve(c),this.encrypt(d),this.encrypt(a),e,n,o,l]),{transaction:this.getOidcTransaction(i),state:c,nonce:d,verifier:a}}getOidcTransaction(t){let e=this.controlPlane.database.query("SELECT * FROM auth_oidc_transactions WHERE id = ?").get(t);return e?au(e,this.now()):void 0}consumeOidcTransaction(t,e){return this.controlPlane.transaction(()=>{let n=this.controlPlane.database.query("SELECT * FROM auth_oidc_transactions WHERE provider_id = ? AND state_hash = ?").get(t,Ve(e));if(!n)throw Error("OIDC transaction is invalid");let r=au(n,this.now());if(r.state!=="pending")throw Error(`OIDC transaction is ${r.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(),r.id,this.now()]).changes!==1)throw Error("OIDC transaction is no longer available");return{transaction:this.getOidcTransaction(r.id),nonce:this.decrypt(String(n.nonce_ciphertext)),verifier:this.decrypt(String(n.verifier_ciphertext))}})}getOidcSubject(t,e){let n=this.controlPlane.database.query("SELECT * FROM auth_oidc_subjects WHERE provider_id = ? AND subject = ?").get(t,e);return n?wI(n):void 0}linkOidcSubject(t,e,n,r){let i=this.getOidcProvider(t),c=this.getIdentity(e);if(!i||!c)throw Error("OIDC provider or identity was not found");let d=mo(r);if(!n.trim()||n.length>512)throw Error("OIDC subject is invalid");let a=this.getOidcSubject(t,n);if(a&&a.identityId!==e)throw Error("OIDC subject is already linked to another identity");let l=this.now();if(a)return this.run("UPDATE auth_oidc_subjects SET email = ?, last_login_at = ? WHERE id = ?",[d,l,a.id]),this.getOidcSubject(t,n);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,t,e,n,d,l,l]),this.getOidcSubject(t,n)}purgeExpired(){let t=this.now(),e=this.controlPlane.database.run("DELETE FROM auth_action_tokens WHERE expires_at < ? OR consumed_at IS NOT NULL",[t]).changes,n=this.controlPlane.database.run("DELETE FROM auth_sessions WHERE revoked_at IS NOT NULL OR idle_expires_at < ? OR absolute_expires_at < ?",[t,t]).changes;return this.controlPlane.database.run("DELETE FROM auth_mfa_challenges WHERE consumed_at IS NOT NULL OR expires_at < ?",[t]),this.controlPlane.database.run("DELETE FROM auth_oidc_transactions WHERE consumed_at IS NOT NULL OR expires_at < ?",[t]),{actionTokens:e,sessions:n}}}async function Ui(t,e){let n=t.notifications?.email?.from;if(!n)return!1;try{let{EmailClient:r}=await import("./chunk-c1vcdgvr.js");return await new r({region:t.project.region,defaultFrom:n}).send(e),!0}catch{return!1}}import{randomBytes as AI}from"node:crypto";import{chmodSync as DI,existsSync as yI,mkdirSync as PI,readFileSync as $I,writeFileSync as vI}from"node:fs";import{dirname as kI}from"node:path";function Gn(t){let e=process.env.TS_CLOUD_AUTH_ENCRYPTION_KEY?.trim();if(e)return e;let n=de(t,"auth-encryption-key");try{if(yI(n)){let i=$I(n,"utf8").trim();if(i)return i}}catch{}let r=AI(32).toString("base64url");try{PI(kI(n),{recursive:!0,mode:448}),vI(n,`${r}
|
|
34
|
-
`,{mode:384}),DI(n,384)}catch{}return r}import{constants as fu,createHash as ea,createPublicKey as CI,createVerify as OI,timingSafeEqual as JI}from"node:crypto";var Ru=new Set(["RS256","PS256","ES256"]),_u=60;function Wc(t,e){let n=new URL(t),r=["127.0.0.1","::1","localhost"].includes(n.hostname);if(n.protocol!=="https:"&&!(n.protocol==="http:"&&r))throw Error(`${e} must use HTTPS`);if(n.username||n.password||n.hash)throw Error(`${e} contains unsupported URL components`);return n}function na(t,e){if(!t||typeof t!=="object"||Array.isArray(t))throw Error(`${e} is invalid`);return t}async function ra(t,e){if(!t.ok)throw Error(`${e} failed with HTTP ${t.status}`);if(!(t.headers.get("content-type")??"").toLowerCase().includes("application/json"))throw Error(`${e} returned an unsupported content type`);if(Number(t.headers.get("content-length")??0)>1048576)throw Error(`${e} response is too large`);let i=await t.text();if(i.length>1048576)throw Error(`${e} response is too large`);try{return na(JSON.parse(i),e)}catch(c){if(c instanceof Error&&c.message===`${e} is invalid`)throw c;throw Error(`${e} returned invalid JSON`)}}function BI(t,e){let n=ea("sha256").update(t).digest(),r=ea("sha256").update(e).digest();return JI(n,r)}function Eu(t){if(!t)return"/";let e=t.trim();if(!e.startsWith("/")||e.startsWith("//")||e.includes("\\")||/[\r\n]/.test(e))return"/";try{let n=new URL(e,"https://local.invalid");return n.origin==="https://local.invalid"?`${n.pathname}${n.search}${n.hash}`:"/"}catch{return"/"}}async function ia(t,e=fetch){let n=Wc(t.issuer,"OIDC issuer"),r=new URL(`${n.pathname.replace(/\/$/,"")}/.well-known/openid-configuration`,n.origin),i=await ra(await e(r,{headers:{accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(1e4)}),"OIDC discovery");if(i.issuer!==t.issuer)throw Error("OIDC discovery issuer does not match the configured issuer");for(let d of["authorization_endpoint","token_endpoint","jwks_uri"]){if(typeof i[d]!=="string")throw Error(`OIDC discovery is missing ${d}`);Wc(i[d],`OIDC ${d}`)}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 c=Array.isArray(i.id_token_signing_alg_values_supported)?i.id_token_signing_alg_values_supported.filter((d)=>typeof d==="string"):[];if(c.length>0&&!c.some((d)=>Ru.has(d)))throw Error("OIDC provider does not offer a supported ID-token signing algorithm");return i}async function ca(t,e,n,r,i=fetch){let c=t.getOidcProviderBySlug(e);if(!c?.enabled)throw Error("OIDC provider is unavailable");let d=Wc(n,"Application origin").origin,a=await ia(c,i),l=`${d}/auth/oidc/${encodeURIComponent(c.slug)}/callback`,o=t.beginOidcTransaction(c.id,l,Eu(r)),u=new URL(a.authorization_endpoint);return u.searchParams.set("response_type","code"),u.searchParams.set("client_id",c.clientId),u.searchParams.set("redirect_uri",l),u.searchParams.set("scope",c.scopes.join(" ")),u.searchParams.set("state",o.state),u.searchParams.set("nonce",o.nonce),u.searchParams.set("code_challenge",ea("sha256").update(o.verifier).digest("base64url")),u.searchParams.set("code_challenge_method","S256"),{authorizationUrl:u.href,expiresAt:o.transaction.expiresAt}}function zI(t){if(t.length>32768)throw Error("OIDC ID token is too large");let e=t.split(".");if(e.length!==3||e.some((n)=>!n))throw Error("OIDC ID token is malformed");try{return{header:na(JSON.parse(Buffer.from(e[0],"base64url").toString("utf8")),"OIDC ID-token header"),claims:na(JSON.parse(Buffer.from(e[1],"base64url").toString("utf8")),"OIDC ID-token claims"),signingInput:`${e[0]}.${e[1]}`,signature:Buffer.from(e[2],"base64url")}}catch(n){if(n instanceof Error&&n.message.startsWith("OIDC"))throw n;throw Error("OIDC ID token is malformed")}}async function TI(t,e,n){let r=zI(t),i=typeof r.header.alg==="string"?r.header.alg:"",c=typeof r.header.kid==="string"?r.header.kid:"";if(!Ru.has(i)||!c)throw Error("OIDC ID token uses an unsupported signing key");if(e.id_token_signing_alg_values_supported&&!e.id_token_signing_alg_values_supported.includes(i))throw Error("OIDC ID-token algorithm was not advertised by the provider");let d=await ra(await n(e.jwks_uri,{headers:{accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(1e4)}),"OIDC signing-key request");if(!Array.isArray(d.keys))throw Error("OIDC signing-key response is invalid");let a=d.keys.find((f)=>{if(!f||typeof f!=="object"||Array.isArray(f))return!1;let R=f;return R.kid===c&&(!R.alg||R.alg===i)&&(!R.use||R.use==="sig")});if(!a)throw Error("OIDC ID-token signing key was not found");let l=CI({key:a,format:"jwk"}),o=OI("SHA256").update(r.signingInput).end();if(!(i==="PS256"?o.verify({key:l,padding:fu.RSA_PKCS1_PSS_PADDING,saltLength:32},r.signature):i==="ES256"?o.verify({key:l,dsaEncoding:"ieee-p1363"},r.signature):o.verify(l,r.signature)))throw Error("OIDC ID-token signature is invalid");return r.claims}function bI(t,e,n,r){if(t.iss!==e.issuer)throw Error("OIDC ID-token issuer is invalid");let i=typeof t.aud==="string"?[t.aud]:Array.isArray(t.aud)?t.aud.filter((l)=>typeof l==="string"):[];if(!i.includes(e.clientId))throw Error("OIDC ID-token audience is invalid");if((i.length>1||t.azp!==void 0)&&t.azp!==e.clientId)throw Error("OIDC ID-token authorized party is invalid");let c=Math.floor(r.getTime()/1000);if(typeof t.exp!=="number"||t.exp<c-_u)throw Error("OIDC ID token is expired");if(typeof t.iat!=="number"||t.iat>c+_u)throw Error("OIDC ID-token issued-at time is invalid");if(typeof t.nonce!=="string"||!BI(t.nonce,n))throw Error("OIDC ID-token nonce is invalid");if(typeof t.sub!=="string"||!t.sub||t.sub.length>512)throw Error("OIDC ID-token subject is invalid");if(t.email_verified!==!0||typeof t.email!=="string")throw Error("OIDC provider did not return a verified email address");let d=t.email.trim().toLowerCase();if(d.length>254||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(d))throw Error("OIDC provider returned an invalid email address");let a=d.split("@")[1];if(!a||!e.allowedDomains.includes(a))throw Error("OIDC email domain is not allowed for this organization");return{provider:e,subject:t.sub,email:d,name:typeof t.name==="string"?t.name.slice(0,120):void 0,claims:t}}async function da(t,e,n=fetch){let r=t.getOidcProviderBySlug(e.providerSlug);if(!r?.enabled)throw Error("OIDC provider is unavailable");if(!e.state||e.state.length>512||!e.code||e.code.length>4096)throw Error("OIDC callback is incomplete");let i=Wc(e.origin,"Application origin").origin,c=t.consumeOidcTransaction(r.id,e.state),d=`${i}/auth/oidc/${encodeURIComponent(r.slug)}/callback`;if(c.transaction.redirectUri!==d)throw Error("OIDC callback redirect URI does not match the original request");let{clientSecret:a}=t.getOidcProviderCredentials(r.id),l=await ia(r,n),o=new URLSearchParams({grant_type:"authorization_code",code:e.code,redirect_uri:c.transaction.redirectUri,code_verifier:c.verifier}),u={accept:"application/json","content-type":"application/x-www-form-urlencoded"},f=l.token_endpoint_auth_methods_supported??["client_secret_basic"];if(f.includes("client_secret_basic")){let y=(C)=>new URLSearchParams({value:C}).toString().slice(6),$=`${y(r.clientId)}:${y(a)}`;u.authorization=`Basic ${Buffer.from($).toString("base64")}`}else if(f.includes("client_secret_post"))o.set("client_id",r.clientId),o.set("client_secret",a);else throw Error("OIDC provider does not support a configured client authentication method");let R=await ra(await n(l.token_endpoint,{method:"POST",headers:u,body:o,redirect:"error",signal:AbortSignal.timeout(1e4)}),"OIDC token exchange");if(typeof R.id_token!=="string")throw Error("OIDC token response did not include an ID token");let E=await TI(R.id_token,l,n);return{identity:bI(E,r,c.nonce,e.now??new Date),returnPath:c.transaction.returnPath}}import{createHash as WI,randomBytes as UI}from"node:crypto";var wu=new Set(Uc),Au=7776000000,Du=31536000000,yu=86400000;function fn(t){return typeof t==="string"?t:void 0}function Iu(t){return WI("sha256").update(t).digest("hex")}function jI(t){try{let e=JSON.parse(String(t));return Array.isArray(e)?e.filter((n)=>typeof n==="string"&&wu.has(n)):[]}catch{return[]}}function HI(t){let e=String(t.scope_type);return e==="organization"?{type:e}:{type:e,id:String(t.scope_id)}}function oa(t){let e=fn(t.disabled_at);return{id:String(t.id),organizationId:String(t.organization_id),actorId:String(t.actor_id),slug:String(t.slug),name:String(t.name),description:fn(t.description),createdByActorId:fn(t.created_by_actor_id),disabledAt:e,createdAt:String(t.created_at),updatedAt:String(t.updated_at),state:e?"disabled":"active"}}function aa(t,e){let n=fn(t.revoked_at),r=String(t.expires_at);return{id:String(t.id),serviceAccountId:String(t.service_account_id),name:String(t.name),prefix:String(t.token_prefix),capabilities:jI(t.capabilities),scope:HI(t),expiresAt:r,lastUsedAt:fn(t.last_used_at),lastNetworkHint:fn(t.last_network_hint),revokedAt:n,rotatedFromTokenId:fn(t.rotated_from_token_id),createdByActorId:fn(t.created_by_actor_id),createdAt:String(t.created_at),updatedAt:String(t.updated_at),state:n?"revoked":r<=e?"expired":"active"}}function LI(t){let e={};try{e=JSON.parse(String(t.response_body))}catch{}return{id:String(t.id),tokenId:String(t.token_id),key:String(t.idempotency_key),requestHash:String(t.request_hash),operationId:fn(t.operation_id),responseStatus:Number(t.response_status),responseBody:e,expiresAt:String(t.expires_at),createdAt:String(t.created_at)}}class jc{controlPlane;nowFn;idFn;constructor(t,e={}){this.controlPlane=t;this.nowFn=e.now??(()=>new Date),this.idFn=e.id??(()=>crypto.randomUUID())}now(){return this.nowFn().toISOString()}run(t,e){this.controlPlane.database.run(t,e)}createServiceAccount(t){if(!this.controlPlane.getOrganization(t.organizationId))throw Error("Service-account organization was not found");let e=t.slug.trim().toLowerCase();if(!/^[a-z0-9][a-z0-9-]{1,47}$/.test(e))throw Error("Service-account slug must be 2-48 lowercase letters, numbers or dashes");let n=t.name.trim().slice(0,100);if(!n)throw Error("Service-account name is required");let r=this.controlPlane.createActor({kind:"service_account",externalId:`service-account:${t.organizationId}:${e}`,displayName:n,metadata:{source:"api",serviceAccountSlug:e}}),i=this.idFn(),c=this.now();this.run(`INSERT INTO service_accounts (id, organization_id, actor_id, slug, name, description, created_by_actor_id, created_at, updated_at)
|
|
35
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i,t.organizationId,r.id,e,n,t.description?.trim().slice(0,500)||null,t.createdByActorId??null,c,c]);let d=this.controlPlane.createMembership({organizationId:t.organizationId,actorId:r.id,roleTemplate:t.roleTemplate,scope:t.scope,source:"manual",performedByActorId:t.createdByActorId}),a=t.scope??{type:"organization"};return this.controlPlane.appendEvent({organizationId:t.organizationId,actorId:t.createdByActorId,type:"api.service_account.created",payload:{serviceAccountId:i,roleTemplate:t.roleTemplate,scope:{type:a.type,id:a.id??null}}}),{serviceAccount:this.getServiceAccount(i),membership:d}}getServiceAccount(t){let e=this.controlPlane.database.query("SELECT * FROM service_accounts WHERE id = ?").get(t);return e?oa(e):void 0}getServiceAccountBySlug(t,e){let n=this.controlPlane.database.query("SELECT * FROM service_accounts WHERE organization_id = ? AND slug = ? COLLATE NOCASE").get(t,e.trim());return n?oa(n):void 0}listServiceAccounts(t,e={}){return this.controlPlane.database.query("SELECT * FROM service_accounts WHERE organization_id = ? ORDER BY name COLLATE NOCASE").all(t).map(oa).filter((n)=>e.includeDisabled||n.state==="active")}disableServiceAccount(t,e){let n=this.getServiceAccount(t);if(!n)throw Error("Service account was not found");let r=this.now();return this.controlPlane.transaction(()=>{this.run("UPDATE service_accounts SET disabled_at = ?, updated_at = ? WHERE id = ?",[r,r,t]),this.run("UPDATE api_tokens SET revoked_at = ?, updated_at = ? WHERE service_account_id = ? AND revoked_at IS NULL",[r,r,t]);let i=this.controlPlane.getMembershipForActor(n.organizationId,n.actorId);if(i?.status==="active")this.controlPlane.revokeMembership(i.id)}),this.controlPlane.appendEvent({organizationId:n.organizationId,actorId:e,type:"api.service_account.disabled",payload:{serviceAccountId:t}}),this.getServiceAccount(t)}createToken(t){let e=this.getServiceAccount(t.serviceAccountId);if(!e||e.state!=="active")throw Error("Service account is unavailable");let n=this.controlPlane.getMembershipForActor(e.organizationId,e.actorId);if(!n||n.status!=="active")throw Error("Service-account membership is unavailable");let r=[...new Set(t.capabilities)];if(r.length===0||r.some((R)=>!wu.has(R)))throw Error("API token requires valid explicit capabilities");let i=t.scope??n.scope,c=this.controlPlane.resolveAuthorizationTarget(e.organizationId,i);if(!c)throw Error("API token scope was not found in this organization");for(let R of r)if(!Ne({membership:n,grants:this.controlPlane.listGrants(n.id),capability:R,target:c}).allowed)throw Error(`Service-account membership does not grant ${R} at the token scope`);let d=t.expiresAt?new Date(t.expiresAt):new Date(this.nowFn().getTime()+Au);if(!Number.isFinite(d.getTime())||d.getTime()<=this.nowFn().getTime()+60000||d.getTime()>this.nowFn().getTime()+Du)throw Error("API token expiry must be between one minute and one year from now");let a=this.idFn(),l=UI(32).toString("base64url"),o=`tsc_v1.${a}.${l}`,u=`tsc_v1.${a.slice(0,8)}`,f=this.now();return this.run(`INSERT INTO api_tokens (id, service_account_id, name, token_hash, token_prefix, capabilities, scope_type, scope_id,
|
|
36
|
-
expires_at, rotated_from_token_id, created_by_actor_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[a,e.id,t.name.trim().slice(0,100)||"API token",Iu(o),u,JSON.stringify(r.sort()),i.type,i.type==="organization"?null:i.id??null,d.toISOString(),t.rotatedFromTokenId??null,t.createdByActorId??null,f,f]),this.controlPlane.appendEvent({organizationId:e.organizationId,actorId:t.createdByActorId,type:"api.token.created",payload:{serviceAccountId:e.id,tokenId:a,prefix:u,capabilities:r,scope:{type:i.type,id:i.id??null},expiresAt:d.toISOString(),rotatedFromTokenId:t.rotatedFromTokenId??null}}),{token:this.getToken(a),secret:o}}getToken(t){let e=this.controlPlane.database.query("SELECT * FROM api_tokens WHERE id = ?").get(t);return e?aa(e,this.now()):void 0}listTokens(t,e={}){return this.controlPlane.database.query("SELECT * FROM api_tokens WHERE service_account_id = ? ORDER BY created_at DESC").all(t).map((n)=>aa(n,this.now())).filter((n)=>e.includeInactive||n.state==="active")}verifyToken(t,e){let n=/^tsc_v1\.([^.]+)\.[A-Za-z0-9_-]{40,}$/.exec(t);if(!n)return;let r=this.controlPlane.database.query("SELECT * FROM api_tokens WHERE id = ? AND token_hash = ?").get(n[1],Iu(t));if(!r)return;let i=aa(r,this.now()),c=this.getServiceAccount(i.serviceAccountId);if(!c||c.state!=="active"||i.state!=="active")return;let d=this.controlPlane.getActor(c.actorId),a=this.controlPlane.getMembershipForActor(c.organizationId,c.actorId);if(!d||d.disabledAt||!a||a.status!=="active")return;let l=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 = ?",[l,e?.slice(0,128)??null,l,i.id]),o)this.controlPlane.appendEvent({organizationId:c.organizationId,actorId:d.id,type:"api.token.used",payload:{serviceAccountId:c.id,tokenId:i.id,prefix:i.prefix}});return{serviceAccount:c,token:this.getToken(i.id),actor:d,membership:a}}rotateToken(t,e){let n=this.getToken(t);if(!n||n.state!=="active")throw Error("Active API token was not found");let r=this.createToken({serviceAccountId:n.serviceAccountId,name:`${n.name} (rotated)`,capabilities:n.capabilities,scope:n.scope,expiresAt:n.expiresAt,createdByActorId:e,rotatedFromTokenId:n.id}),i=this.getServiceAccount(n.serviceAccountId);return this.controlPlane.appendEvent({organizationId:i?.organizationId,actorId:e,type:"api.token.rotated",payload:{serviceAccountId:n.serviceAccountId,previousTokenId:n.id,tokenId:r.token.id}}),r}revokeToken(t,e){let n=this.getToken(t);if(!n)throw Error("API token was not found");if(n.state==="active"){let r=this.now();this.run("UPDATE api_tokens SET revoked_at = ?, updated_at = ? WHERE id = ?",[r,r,t]);let i=this.getServiceAccount(n.serviceAccountId);this.controlPlane.appendEvent({organizationId:i?.organizationId,actorId:e,type:"api.token.revoked",payload:{serviceAccountId:n.serviceAccountId,tokenId:t}})}return this.getToken(t)}getIdempotency(t,e){let n=this.controlPlane.database.query("SELECT * FROM api_idempotency_records WHERE token_id = ? AND idempotency_key = ? AND expires_at > ?").get(t,e,this.now());return n?LI(n):void 0}saveIdempotency(t){if(!/^[A-Za-z0-9._:-]{8,128}$/.test(t.key))throw Error("Idempotency-Key must contain 8-128 safe characters");let e=this.getIdempotency(t.tokenId,t.key);if(e){if(e.requestHash!==t.requestHash)throw Error("Idempotency-Key was already used for a different request");return e}let n=this.idFn(),r=this.now(),i=new Date(this.nowFn().getTime()+yu).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)
|
|
37
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n,t.tokenId,t.key,t.requestHash,t.operationId??null,t.responseStatus,JSON.stringify(t.responseBody),i,r]),this.getIdempotency(t.tokenId,t.key)}purgeExpired(){let t=this.now(),e=this.controlPlane.database.run("DELETE FROM api_tokens WHERE (expires_at < ? OR revoked_at IS NOT NULL) AND created_at < ?",[t,new Date(this.nowFn().getTime()-2592000000).toISOString()]).changes,n=this.controlPlane.database.run("DELETE FROM api_idempotency_records WHERE expires_at < ?",[t]).changes;return{tokens:e,idempotency:n}}}class ji{region;client;constructor(t="us-east-1",e=new ut){this.region=t;this.client=e}request(t,e){return this.client.request({service:"backup",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`CryoControllerFrontendService.${t}`},body:JSON.stringify(e)})}startBackupJob(t){return this.request("StartBackupJob",t)}describeBackupJob(t){return this.request("DescribeBackupJob",{BackupJobId:t})}startRestoreJob(t){return this.request("StartRestoreJob",t)}describeRestoreJob(t){return this.request("DescribeRestoreJob",{RestoreJobId:t})}deleteRecoveryPoint(t,e){return this.request("DeleteRecoveryPoint",{BackupVaultName:t,RecoveryPointArn:e})}}class Hi{client;region;constructor(t="us-east-1",e){this.region=t,this.client=new ut}async describeCacheClusters(t){let e={Action:"DescribeCacheClusters",Version:"2015-02-02",ShowCacheNodeInfo:"true"};if(t)e.CacheClusterId=t;let n=await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(e).toString()});return{CacheClusters:this.parseCacheClusters(n)}}async describeReplicationGroups(t){let e={Action:"DescribeReplicationGroups",Version:"2015-02-02"};if(t)e.ReplicationGroupId=t;let n=await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(e).toString()});return{ReplicationGroups:[]}}async createCacheCluster(t){let e={Action:"CreateCacheCluster",Version:"2015-02-02",CacheClusterId:t.cacheClusterId,Engine:t.engine,CacheNodeType:t.cacheNodeType};if(t.numCacheNodes)e.NumCacheNodes=t.numCacheNodes;if(t.engineVersion)e.EngineVersion=t.engineVersion;if(t.port)e.Port=t.port;if(t.securityGroupIds&&t.securityGroupIds.length>0)t.securityGroupIds.forEach((r,i)=>{e[`SecurityGroupIds.member.${i+1}`]=r});if(t.subnetGroupName)e.CacheSubnetGroupName=t.subnetGroupName;if(t.tags&&t.tags.length>0)t.tags.forEach((r,i)=>{e[`Tags.member.${i+1}.Key`]=r.Key,e[`Tags.member.${i+1}.Value`]=r.Value});let n=await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(e).toString()});return{CacheCluster:this.parseCacheCluster(n)}}async deleteCacheCluster(t,e){let n={Action:"DeleteCacheCluster",Version:"2015-02-02",CacheClusterId:t};if(e)n.FinalSnapshotIdentifier=e;await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(n).toString()})}async rebootCacheCluster(t,e){let n={Action:"RebootCacheCluster",Version:"2015-02-02",CacheClusterId:t};e.forEach((r,i)=>{n[`CacheNodeIdsToReboot.member.${i+1}`]=r}),await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(n).toString()})}async describeCacheEngineVersions(t){let e={Action:"DescribeCacheEngineVersions",Version:"2015-02-02"};if(t)e.Engine=t;let n=await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(e).toString()});return{CacheEngineVersions:[]}}async getCacheStatistics(t){let e=await this.describeCacheClusters(t);if(!e.CacheClusters||e.CacheClusters.length===0)throw Error(`Cache cluster ${t} not found`);return{cpuUtilization:0,evictions:0,hits:0,misses:0,connections:0}}parseCacheClusters(t){if(t.CacheClusterId)return[{CacheClusterId:t.CacheClusterId,CacheClusterStatus:t.CacheClusterStatus||"available",Engine:t.Engine||"redis",EngineVersion:t.EngineVersion||"7.0",CacheNodeType:t.CacheNodeType||"cache.t3.micro",NumCacheNodes:Number.parseInt(t.NumCacheNodes||"1"),CacheClusterCreateTime:t.CacheClusterCreateTime||new Date().toISOString()}];return[]}parseCacheCluster(t){return{CacheClusterId:t.CacheClusterId,CacheClusterStatus:t.CacheClusterStatus||"creating",Engine:t.Engine||"redis",EngineVersion:t.EngineVersion||"7.0",CacheNodeType:t.CacheNodeType||"cache.t3.micro",NumCacheNodes:Number.parseInt(t.NumCacheNodes||"1"),CacheClusterCreateTime:t.CacheClusterCreateTime||new Date().toISOString()}}}import{isIP as Ju}from"node:net";var FI={every_minute:"* * * * *",every_five_minutes:"*/5 * * * *",hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 0"},VI={JAN:1,FEB:2,MAR:3,APR:4,MAY:5,JUN:6,JUL:7,AUG:8,SEP:9,OCT:10,NOV:11,DEC:12},Pu={SUN:0,MON:1,TUE:2,WED:3,THU:4,FRI:5,SAT:6};function $u(t){try{return new Intl.DateTimeFormat("en",{timeZone:t}).format(new Date),t}catch{throw Error(`Unknown schedule timezone: ${t}`)}}function Hc(t,e,n,r){let i=e[t.toUpperCase()]??Number(t);if(!Number.isInteger(i)||i<n||i>r)throw Error(`Schedule field value ${t} is outside ${n}-${r}.`);return i}function Gr(t,e,n,r={},i){if(t==="*"||t==="?")return;let c=new Set;for(let d of t.split(",")){let[a,l]=d.split("/"),o=l?Hc(l,{},1,n-e+1):1,u,f;if(a==="*")u=e,f=n;else if(a.includes("-")){let R=a.split("-");u=Hc(R[0],r,e,n),f=Hc(R[1],r,e,n)}else u=Hc(a,r,e,n),f=u;if(f<u)throw Error("Schedule ranges must be ascending.");for(let R=u;R<=f;R+=o)c.add(i?i(R):R===7&&n===7?0:R)}return c}function NI(t,e){let n=Object.fromEntries(new Intl.DateTimeFormat("en-US",{timeZone:e,year:"numeric",month:"numeric",day:"numeric",weekday:"short",hour:"numeric",minute:"numeric",hourCycle:"h23"}).formatToParts(t).map((r)=>[r.type,r.value]));return{minute:Number(n.minute),hour:Number(n.hour),day:Number(n.day),month:Number(n.month),weekday:Pu[n.weekday.toUpperCase()],year:Number(n.year),key:`${n.year}-${n.month}-${n.day} ${n.hour}:${n.minute}`}}function vu(t){let n=(t.startsWith("cron(")?t.slice(5,-1).trim():t.trim()).split(/\s+/);if(n.length!==5&&n.length!==6)throw Error("Cron schedules require five standard fields or six EventBridge fields.");let[r,i,c,d,a,l]=n,o=n.length===6;return{minute:Gr(r,0,59),hour:Gr(i,0,23),day:Gr(c,1,31),month:Gr(d,1,12,VI),weekday:Gr(a,o?1:0,7,Pu,o?(u)=>u===7?6:u-1:void 0),year:l?Gr(l,1970,2199):void 0,dayWildcard:c==="*"||c==="?",weekdayWildcard:a==="*"||a==="?"}}function xI(t,e){if(!((!e.minute||e.minute.has(t.minute))&&(!e.hour||e.hour.has(t.hour))&&(!e.month||e.month.has(t.month))&&(!e.year||e.year.has(t.year))))return!1;let r=!e.day||e.day.has(t.day),i=!e.weekday||e.weekday.has(t.weekday);return e.dayWildcard?i:e.weekdayWildcard?r:r||i}function ku(t){let e=/^rate\(\s*(\d+)\s+(minute|minutes|hour|hours|day|days)\s*\)$/i.exec(t);if(!e)return;let n=Number(e[1]);if(n<1)throw Error("Rate amount must be positive.");return n*(e[2].toLowerCase().startsWith("minute")?60000:e[2].toLowerCase().startsWith("hour")?3600000:86400000)}function Zr(t){let e=t.trim(),n=FI[e.toLowerCase()]??e;if(!n)throw Error("Schedule expression is required.");let r=ku(n);if(r){let i=r/60000;return{original:e,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 vu(n),{original:e,normalized:n.startsWith("cron(")?n:`cron(${n})`,kind:"cron",description:`Cron ${n.replace(/^cron\(|\)$/g,"")}`}}function fr(t,e,n=new Date,r=5){let i=Zr(t),c=$u(e),d=Math.min(20,Math.max(1,r)),a=ku(i.normalized);if(a)return Array.from({length:d},(E,y)=>new Date(n.getTime()+a*(y+1)).toISOString());let l=vu(i.normalized),o=[],u=new Set,f=new Date(Math.floor(n.getTime()/60000)*60000+60000),R=0;while(o.length<d&&R<1100000){let E=NI(f,c);if(xI(E,l)&&!u.has(E.key))o.push(f.toISOString()),u.add(E.key);f=new Date(f.getTime()+60000),R++}if(o.length<d)throw Error("Schedule produced no runs within the bounded preview horizon.");return o}function _r(t,e="UTC",n=new Date,r=5){let i=Zr(t),c=fr(i.normalized,e,n,r),d=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:$u(e),nextRuns:c,capabilities:{server:i.kind==="cron",eventbridge:!0,notes:d}}}function sa(t){let e=Zr(t.expression),n=e.normalized.slice(5,-1).trim().split(/\s+/),r=e.kind==="cron"&&n.length===5;if(t.provider==="server")return{provider:"server",supported:r,features:{timezone:!0,flexibleWindow:!1,catchUp:!1,replaceOverlap:!1},notes:[e.kind==="rate"?"Server cron requires a cron expression; use an equivalent cron schedule.":n.length!==5?"EventBridge six-field cron extensions cannot be installed as server cron.":"Cron is reconciled through a root-owned ts-cloud entry.",t.missedRunPolicy==="catch_up"?"Catch-up is handled by the control plane, not cron.":"Missed runs are skipped by cron."]};if(t.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(t.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 MI(t){if(t.queues===!0)return[{queue:"default",processes:t.queueConcurrency??1}];if(!Array.isArray(t.queues))return[];return t.queues.map((e)=>{if(typeof e==="string")return{queue:e,processes:t.queueConcurrency??1};let[n,r]=Object.entries(e)[0]??["default",t.queueConcurrency??1];return{queue:n,processes:r}})}function la(t,e,n){let r=new Set,i=new Set,c=new Map(n.resources.map((f)=>[f.slug,f])),d=0,a=0;for(let[f,R]of Object.entries(e.sites??{})){let E=c.get(f);if(R.scheduler){let C=`config:site:${f}:scheduler`;r.add(C),t.upsertConfigJob({organizationId:n.organization.id,projectId:n.project.id,environmentId:n.environment.id,resourceId:E?.id,name:`${f} scheduler`,provider:"server",expression:"* * * * *",timezone:"UTC",flexibleMinutes:0,target:{kind:"dashboard_operation",operationId:`scheduler:run:${f}`},payloadRefs:{},missedRunPolicy:"skip",overlapPolicy:"forbid",retryPolicy:{maxAttempts:3,backoffSeconds:30},timeoutSeconds:300,enabled:!0,origin:"config",sourceKey:C,observedState:{source:"cloud.config.ts"},reconciliationStatus:"pending"}),d++}let y=R,$=Array.isArray(y.queues??y.workers)?y.queues??y.workers:[];for(let[C,J]of $.entries()){let H=typeof J==="string"?{queue:J}:J,O=String(H.queue??H.name??"default"),Y=`config:site:${f}:worker:${C}:${O}`;i.add(Y),t.upsertWorker({organizationId:n.organization.id,projectId:n.project.id,environmentId:n.environment.id,resourceId:E?.id,name:`${f}:${O}`,provider:"systemd",queue:O,processes:Number(H.processes)||1,timeoutSeconds:Number(H.timeout)||60,restartPolicy:"always",target:{operationId:`worker:restart:${f}`,site:f},enabled:!0,origin:"config",sourceKey:Y,observedState:{source:"cloud.config.ts",currentJob:null,failures:0},reconciliationStatus:"pending"}),a++}}let l=e.infrastructure?.compute?.backups;if(l?.enabled)r.add("config:platform:backup"),t.upsertConfigJob({organizationId:n.organization.id,projectId:n.project.id,environmentId:n.environment.id,name:"Scheduled backup",provider:"server",expression:String(l.schedule??"0 2 * * *"),timezone:String(l.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"}),d++;let o=e.environments?.[n.environment.slug]?.app;if(o){if(o.scheduler!=="off"){let f=`config:serverless:${n.environment.slug}:scheduler`;r.add(f),t.upsertConfigJob({organizationId:n.organization.id,projectId:n.project.id,environmentId:n.environment.id,name:`${n.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:f,observedState:{source:"cloud.config.ts",mode:o.scheduler??"on"},reconciliationStatus:"pending"}),d++}for(let{queue:f,processes:R}of MI(o)){let E=`config:serverless:${n.environment.slug}:worker:${f}`;i.add(E),t.upsertWorker({organizationId:n.organization.id,projectId:n.project.id,environmentId:n.environment.id,name:`${n.environment.name}:${f}`,provider:"lambda",queue:f,processes:R,timeoutSeconds:o.queueTimeout??120,restartPolicy:"on_failure",target:{function:"queue",queue:f},enabled:!0,origin:"config",sourceKey:E,observedState:{source:"cloud.config.ts",currentJob:null,failures:0},reconciliationStatus:"pending"}),a++}}let u=0;for(let f of t.list(n.project.id,{environmentId:n.environment.id}).filter((R)=>R.origin==="config"&&R.sourceKey&&!r.has(R.sourceKey)))t.reconcile(f.id,"drifted",{...f.observedState,reason:"Definition is no longer present in configuration; retained for non-destructive review."}),u++;for(let f of t.listWorkers(n.project.id,n.environment.id).filter((R)=>R.origin==="config"&&R.sourceKey&&!i.has(R.sourceKey)))t.reconcileWorker(f.id,"drifted",{...f.observedState,reason:"Definition is no longer present in configuration; retained for non-destructive review."}),u++;return{jobs:d,workers:a,drifted:u}}class ga{store;queue;constructor(t,e={}){this.store=t;this.queue=e.queue??new Ot(t.controlPlane)}enqueue(t,e){let n=new Date(e.scheduledFor??this.store.now()).toISOString(),r=`${t.id}:${e.trigger==="manual"?crypto.randomUUID():n}`,i=this.store.activeExecution(t.id);if(i&&t.overlapPolicy==="forbid")return this.store.createExecution({jobId:t.id,trigger:e.trigger,scheduledFor:n,idempotencyKey:r,status:"skipped",output:{reason:"overlap_forbidden",activeExecutionId:i.id}});if(i&&t.overlapPolicy==="replace"&&i.operationId)try{this.queue.requestCancellation(i.operationId,e.actorId)}catch{}let c=this.store.createExecution({jobId:t.id,trigger:e.trigger,scheduledFor:n,idempotencyKey:r,status:"queued",output:{semantics:"at_least_once"}});if(c.operationId)return c;let d=this.queue.enqueue({projectId:t.projectId,environmentId:t.environmentId,resourceId:t.resourceId,actorId:e.actorId,kind:"job.execute",input:{jobId:t.id,executionId:c.id},idempotencyKey:`job-execution:${c.id}`,lockKey:t.overlapPolicy==="allow"?`job-execution:${c.id}`:`job:${t.id}`,maxAttempts:t.retryPolicy.maxAttempts,timeoutSeconds:t.timeoutSeconds,retryClasses:["job_transient"],resumePolicy:"requeue"}).operation;return this.store.attachOperation(c.id,d.id)}tick(t=this.store.now()){let e=[];for(let n of this.store.due(t.toISOString())){let r=n.nextRunAt,i=fr(n.normalizedExpression,n.timezone,t,1)[0];if(n.missedRunPolicy==="catch_up"){let c=r,d=0;while(c<=t.toISOString()&&d<10)e.push(this.enqueue(n,{trigger:c===r?"scheduled":"catch_up",scheduledFor:c})),c=fr(n.normalizedExpression,n.timezone,new Date(c),1)[0],d++}else e.push(this.enqueue(n,{trigger:"scheduled",scheduledFor:r}));this.store.markScheduled(n.id,r,i)}return e}}function Cu(t){return{"job.execute":async(n)=>{let r=n.operation.input&&typeof n.operation.input==="object"&&!Array.isArray(n.operation.input)?n.operation.input:{},i=t.store.get(String(r.jobId??"")),c=t.store.getExecution(String(r.executionId??""));if(!i||!c)throw Error("Scheduled job execution is no longer available.");t.store.transitionExecution(c.id,"running",{attempt:n.operation.attempt}),n.checkpoint("execute",`Running ${i.name} on ${i.provider}.`),n.log(`Trigger ${c.trigger}; scheduled for ${c.scheduledFor}; semantics at-least-once.`,{stream:"system"});let d=await t.executor(i,i.target,n);if(d.stdout)n.log(d.stdout,{stream:"stdout"});if(d.stderr)n.log(d.stderr,{stream:"stderr"});if(!d.ok){if(t.store.transitionExecution(c.id,n.operation.attempt>=i.retryPolicy.maxAttempts?"dead":"failed",{attempt:n.operation.attempt,error:d.stderr??"Job execution failed."}),d.retryable)throw new Lc(d.stderr??"Scheduled job failed transiently.","job_transient");throw Error(d.stderr??"Scheduled job failed.")}return t.store.transitionExecution(c.id,"succeeded",{attempt:n.operation.attempt,output:d.output??{}}),{jobId:i.id,executionId:c.id,provider:i.provider}}}}var ae=(t)=>typeof t==="string"&&t?t:void 0,Ou=(t)=>Number(t)===1,Rr=(t)=>{try{return JSON.parse(String(t))}catch{return{}}},Zn=(t,e,n,r)=>{let i=Number(t);return Number.isFinite(i)?Math.min(r,Math.max(n,Math.floor(i))):e};function Fc(t){return{id:String(t.id),organizationId:String(t.organization_id),projectId:String(t.project_id),environmentId:ae(t.environment_id),resourceId:ae(t.resource_id),name:String(t.name),provider:String(t.provider),expression:String(t.expression),normalizedExpression:String(t.normalized_expression),timezone:String(t.timezone),startsAt:ae(t.starts_at),endsAt:ae(t.ends_at),flexibleMinutes:Number(t.flexible_minutes),target:Rr(t.target),payloadRefs:Rr(t.payload_refs),missedRunPolicy:String(t.missed_run_policy),overlapPolicy:String(t.overlap_policy),retryPolicy:Rr(t.retry_policy),timeoutSeconds:Number(t.timeout_seconds),enabled:Ou(t.enabled),origin:String(t.origin),sourceKey:ae(t.source_key),ownerActorId:ae(t.owner_actor_id),observedState:Rr(t.observed_state),reconciliationStatus:String(t.reconciliation_status),nextRunAt:ae(t.next_run_at),lastScheduledFor:ae(t.last_scheduled_for),version:Number(t.version),createdAt:String(t.created_at),updatedAt:String(t.updated_at)}}function Vc(t){return{id:String(t.id),jobId:String(t.job_id),operationId:ae(t.operation_id),trigger:String(t.trigger),scheduledFor:String(t.scheduled_for),idempotencyKey:String(t.idempotency_key),status:String(t.status),attempt:Number(t.attempt),startedAt:ae(t.started_at),finishedAt:ae(t.finished_at),output:Rr(t.output),error:ae(t.error),createdAt:String(t.created_at),updatedAt:String(t.updated_at)}}function ua(t){return{id:String(t.id),organizationId:String(t.organization_id),projectId:String(t.project_id),environmentId:ae(t.environment_id),resourceId:ae(t.resource_id),name:String(t.name),provider:String(t.provider),queue:String(t.queue),processes:Number(t.processes),timeoutSeconds:Number(t.timeout_seconds),restartPolicy:String(t.restart_policy),target:Rr(t.target),enabled:Ou(t.enabled),origin:String(t.origin),sourceKey:ae(t.source_key),ownerActorId:ae(t.owner_actor_id),observedState:Rr(t.observed_state),reconciliationStatus:String(t.reconciliation_status),version:Number(t.version),createdAt:String(t.created_at),updatedAt:String(t.updated_at)}}class ha{controlPlane;options;constructor(t,e={}){this.controlPlane=t;this.options=e}now(){return this.options.now?.()??new Date}create(t){if(!t.name.trim())throw Error("Scheduled jobs require a name.");let e=_r(t.expression,t.timezone,this.now(),1),n=crypto.randomUUID(),r=this.now().toISOString(),i=t.startsAt?new Date(t.startsAt).toISOString():void 0,c=t.endsAt?new Date(t.endsAt).toISOString():void 0;if(i&&c&&i>=c)throw Error("Schedule start must be before end.");let d=e.nextRuns.find((a)=>(!i||a>=i)&&(!c||a<=c));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 (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[n,t.organizationId,t.projectId,t.environmentId??null,t.resourceId??null,t.name.trim().slice(0,120),t.provider,t.expression,e.normalized,t.timezone,i??null,c??null,Zn(t.flexibleMinutes,0,0,1440),JSON.stringify(t.target),JSON.stringify(t.payloadRefs),t.missedRunPolicy,t.overlapPolicy,JSON.stringify({maxAttempts:Zn(t.retryPolicy.maxAttempts,3,1,20),backoffSeconds:Zn(t.retryPolicy.backoffSeconds,30,0,86400),deadLetterRef:t.retryPolicy.deadLetterRef}),Zn(t.timeoutSeconds,900,1,86400),t.enabled?1:0,t.origin,t.sourceKey??null,t.ownerActorId??null,JSON.stringify(t.observedState),t.reconciliationStatus,d??null,1,r,r]),this.get(n)}get(t){let e=this.controlPlane.database.query("SELECT * FROM scheduled_jobs WHERE id=?").get(t);return e?Fc(e):void 0}getBySource(t,e,n){let r=this.controlPlane.database.query("SELECT * FROM scheduled_jobs WHERE project_id=? AND environment_id IS ? AND source_key=?").get(t,e??null,n);return r?Fc(r):void 0}list(t,e={}){let n=["project_id=?"],r=[t];if(e.environmentId)n.push("environment_id=?"),r.push(e.environmentId);if(e.resourceIds?.length)n.push(`resource_id IN (${e.resourceIds.map(()=>"?").join(",")})`),r.push(...e.resourceIds);if(e.enabled!=null)n.push("enabled=?"),r.push(e.enabled?1:0);return this.controlPlane.database.query(`SELECT * FROM scheduled_jobs WHERE ${n.join(" AND ")} ORDER BY next_run_at IS NULL,next_run_at,name`).all(...r).map(Fc)}setEnabled(t,e){this.controlPlane.database.run("UPDATE scheduled_jobs SET enabled=?,version=version+1,updated_at=? WHERE id=?",[e?1:0,this.now().toISOString(),t]);let n=this.get(t);if(!n)throw Error("Scheduled job was not found.");return n}updateSchedule(t,e){let n=this.get(t);if(!n)throw Error("Scheduled job was not found.");let r=e.expression??n.expression,i=e.timezone??n.timezone,c=_r(r,i,this.now(),1),d=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=?",[r,c.normalized,i,e.missedRunPolicy??n.missedRunPolicy,e.overlapPolicy??n.overlapPolicy,Zn(e.timeoutSeconds,n.timeoutSeconds,1,86400),c.nextRuns[0],"pending",d,t]),this.get(t)}remove(t){let e=this.get(t);if(!e)throw Error("Scheduled job was not found.");if(e.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=?",[t])}markScheduled(t,e,n){this.controlPlane.database.run("UPDATE scheduled_jobs SET last_scheduled_for=?,next_run_at=?,updated_at=? WHERE id=?",[e,n??null,this.now().toISOString(),t])}reconcile(t,e,n){return this.controlPlane.database.run("UPDATE scheduled_jobs SET reconciliation_status=?,observed_state=?,updated_at=? WHERE id=?",[e,JSON.stringify(n),this.now().toISOString(),t]),this.get(t)}upsertConfigJob(t){let e=this.getBySource(t.projectId,t.environmentId,t.sourceKey);if(!e)return this.create(t);let n=_r(t.expression,t.timezone,this.now(),1),r=this.now().toISOString();if(e.resourceId===t.resourceId&&e.name===t.name&&e.provider===t.provider&&e.expression===t.expression&&e.normalizedExpression===n.normalized&&e.timezone===t.timezone&&JSON.stringify(e.target)===JSON.stringify(t.target)&&JSON.stringify(e.payloadRefs)===JSON.stringify(t.payloadRefs)&&e.missedRunPolicy===t.missedRunPolicy&&e.overlapPolicy===t.overlapPolicy&&JSON.stringify(e.retryPolicy)===JSON.stringify(t.retryPolicy)&&e.timeoutSeconds===t.timeoutSeconds&&e.enabled===t.enabled)return e;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=?",[t.resourceId??null,t.name,t.provider,t.expression,n.normalized,t.timezone,JSON.stringify(t.target),JSON.stringify(t.payloadRefs),t.missedRunPolicy,t.overlapPolicy,JSON.stringify(t.retryPolicy),t.timeoutSeconds,t.enabled?1:0,JSON.stringify(t.observedState),t.reconciliationStatus,n.nextRuns[0],r,e.id]),this.get(e.id)}due(t=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(t,t,t).map(Fc)}createExecution(t){let e=this.controlPlane.database.query("SELECT * FROM job_executions WHERE idempotency_key=?").get(t.idempotencyKey);if(e)return Vc(e);let n=crypto.randomUUID(),r=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 (?,?,?,?,?,?,?,?,?,?,?)",[n,t.jobId,t.operationId??null,t.trigger,t.scheduledFor,t.idempotencyKey,t.status,0,JSON.stringify(t.output),r,r]),this.getExecution(n)}getExecution(t){let e=this.controlPlane.database.query("SELECT * FROM job_executions WHERE id=?").get(t);return e?Vc(e):void 0}listExecutions(t,e=100){return this.controlPlane.database.query("SELECT * FROM job_executions WHERE job_id=? ORDER BY scheduled_for DESC,created_at DESC LIMIT ?").all(t,Math.min(1000,Math.max(1,e))).map(Vc)}activeExecution(t){let e=this.controlPlane.database.query("SELECT * FROM job_executions WHERE job_id=? AND status IN ('queued','running') ORDER BY created_at DESC LIMIT 1").get(t);return e?Vc(e):void 0}attachOperation(t,e){return this.controlPlane.database.run("UPDATE job_executions SET operation_id=?,updated_at=? WHERE id=?",[e,this.now().toISOString(),t]),this.getExecution(t)}transitionExecution(t,e,n={}){let r=this.now().toISOString(),i=e==="running"?r:null,c=["succeeded","failed","skipped","dead"].includes(e)?r: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=?",[e,n.attempt??null,i,c,n.output?JSON.stringify(n.output):null,n.error?.slice(0,2000)??null,r,t]),this.getExecution(t)}upsertWorker(t){let e=t.sourceKey?this.controlPlane.database.query("SELECT * FROM worker_definitions WHERE project_id=? AND source_key=? AND environment_id IS ?").get(t.projectId,t.sourceKey,t.environmentId??null):void 0,n=e?ua(e):void 0,r=n?.id??crypto.randomUUID(),i=this.now().toISOString(),c=Zn(t.processes,1,0,1000),d=Zn(t.timeoutSeconds,60,1,86400);if(n&&n.resourceId===t.resourceId&&n.name===t.name.slice(0,120)&&n.provider===t.provider&&n.queue===t.queue.slice(0,200)&&n.processes===c&&n.timeoutSeconds===d&&n.restartPolicy===t.restartPolicy&&JSON.stringify(n.target)===JSON.stringify(t.target)&&n.enabled===t.enabled)return n;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",[r,t.organizationId,t.projectId,t.environmentId??null,t.resourceId??null,t.name.slice(0,120),t.provider,t.queue.slice(0,200),c,d,t.restartPolicy,JSON.stringify(t.target),t.enabled?1:0,t.origin,t.sourceKey??null,t.ownerActorId??null,JSON.stringify(t.observedState),t.reconciliationStatus,1,n?.createdAt??i,i]),this.getWorker(r)}getWorker(t){let e=this.controlPlane.database.query("SELECT * FROM worker_definitions WHERE id=?").get(t);return e?ua(e):void 0}listWorkers(t,e){return this.controlPlane.database.query(`SELECT * FROM worker_definitions WHERE project_id=?${e?" AND environment_id=?":""} ORDER BY name`).all(t,...e?[e]:[]).map(ua)}setWorkerProcesses(t,e){this.controlPlane.database.run("UPDATE worker_definitions SET processes=?,reconciliation_status='pending',version=version+1,updated_at=? WHERE id=?",[Zn(e,1,0,1000),this.now().toISOString(),t]);let n=this.getWorker(t);if(!n)throw Error("Worker was not found.");return n}reconcileWorker(t,e,n){this.controlPlane.database.run("UPDATE worker_definitions SET reconciliation_status=?,observed_state=?,updated_at=? WHERE id=?",[e,JSON.stringify(n),this.now().toISOString(),t]);let r=this.getWorker(t);if(!r)throw Error("Worker was not found.");return r}}var ht=(t)=>t==null?void 0:String(t),Nc=(t)=>Number(t)===1,Yn=(t,e)=>{try{return JSON.parse(String(t))}catch{return e}};function Bu(t){return{id:String(t.id),organizationId:String(t.organization_id),projectId:String(t.project_id),name:String(t.name),provider:String(t.provider),endpoint:ht(t.endpoint),endpointPolicy:String(t.endpoint_policy),bucket:ht(t.bucket),prefix:String(t.prefix),region:ht(t.region),forcePathStyle:Nc(t.force_path_style),credentialRef:ht(t.credential_ref),encryption:String(t.encryption),encryptionKeyRef:ht(t.encryption_key_ref),immutability:Yn(t.immutability,{}),status:String(t.status),lastTestedAt:ht(t.last_tested_at),lastSuccessAt:ht(t.last_success_at),lastFailureAt:ht(t.last_failure_at),lastError:ht(t.last_error),version:Number(t.version),createdAt:String(t.created_at),updatedAt:String(t.updated_at)}}function Sa(t){return{id:String(t.id),organizationId:String(t.organization_id),projectId:String(t.project_id),environmentId:ht(t.environment_id),resourceId:ht(t.resource_id),dataServiceId:ht(t.data_service_id),destinationId:String(t.destination_id),name:String(t.name),resourceKind:String(t.resource_kind),schedule:String(t.schedule),timezone:String(t.timezone),retention:Yn(t.retention,{}),compression:String(t.compression),encryption:String(t.encryption),includePatterns:Yn(t.include_patterns,[]),excludePatterns:Yn(t.exclude_patterns,[]),expectedRpoMinutes:Number(t.expected_rpo_minutes),expectedRtoMinutes:Number(t.expected_rto_minutes),healthCheckId:ht(t.health_check_id),enabled:Nc(t.enabled),nextRunAt:ht(t.next_run_at),lastRunAt:ht(t.last_run_at),version:Number(t.version),createdAt:String(t.created_at),updatedAt:String(t.updated_at)}}function fa(t){return{id:String(t.id),projectId:String(t.project_id),policyId:ht(t.policy_id),destinationId:String(t.destination_id),resourceId:ht(t.resource_id),dataServiceId:ht(t.data_service_id),backupJobId:ht(t.backup_job_id),kind:String(t.kind),pointInTime:String(t.point_in_time),uri:String(t.uri),sizeBytes:Number(t.size_bytes),checksum:String(t.checksum),manifest:Yn(t.manifest,{}),toolVersion:ht(t.tool_version),engineVersion:ht(t.engine_version),expiresAt:ht(t.expires_at),lockedUntil:ht(t.locked_until),held:Nc(t.held),pinned:Nc(t.pinned),status:String(t.status),verificationState:String(t.verification_state),verifiedAt:ht(t.verified_at),durationMs:t.duration_ms==null?void 0:Number(t.duration_ms),createdAt:String(t.created_at),updatedAt:String(t.updated_at)}}function _a(t){return{id:String(t.id),projectId:String(t.project_id),policyId:ht(t.policy_id),recoveryPointId:ht(t.recovery_point_id),operationId:ht(t.operation_id),kind:String(t.kind),status:String(t.status),idempotencyKey:String(t.idempotency_key),target:Yn(t.target,{}),restoreMode:ht(t.restore_mode),cancellability:String(t.cancellability),safetyBackupId:ht(t.safety_backup_id),healthResult:t.health_result?Yn(t.health_result,{}):void 0,progress:Yn(t.progress,{}),error:ht(t.error),startedAt:ht(t.started_at),finishedAt:ht(t.finished_at),createdAt:String(t.created_at),updatedAt:String(t.updated_at)}}function QI(t){let e=t.toLowerCase();if(e==="localhost"||e.endsWith(".localhost")||e.endsWith(".local")||e.endsWith(".internal"))return!0;if(Ju(e)===6)return e==="::1"||e.startsWith("fe80:");if(Ju(e)!==4)return!1;let[n,r]=e.split(".").map(Number);return n===10||n===127||n===0||n===169&&r===254||n===172&&r>=16&&r<=31||n===192&&r===168}function GI(t){if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(t.name))throw Error("Backup destination names must be 2-63 lowercase letters, numbers, or dashes.");if(t.provider!=="aws_backup"&&!t.bucket)throw Error("S3 backup destinations require a bucket.");if(t.provider==="s3_compatible"&&!t.endpoint)throw Error("S3-compatible destinations require an explicit endpoint.");if(t.provider==="s3_compatible"&&!t.credentialRef)throw Error("S3-compatible destinations require a credential reference.");if(t.encryption!=="provider"&&!t.encryptionKeyRef)throw Error("Client-side encryption requires an encryption key reference.");if(t.endpoint){let e=new URL(t.endpoint);if(e.protocol!=="https:"||e.username||e.password||e.search||e.hash||e.pathname!=="/")throw Error("Backup endpoints must be origin-only HTTPS URLs without credentials, paths, queries, or fragments.");if(QI(e.hostname)&&t.endpointPolicy!=="allow_private")throw Error("Private backup endpoints require endpointPolicy allow_private.")}}class Ra{controlPlane;now;constructor(t,e=()=>new Date){this.controlPlane=t;this.now=e}createDestination(t){GI(t);let e=crypto.randomUUID(),n=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 (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[e,t.organizationId,t.projectId,t.name,t.provider,t.endpoint??null,t.endpointPolicy,t.bucket??null,t.prefix,t.region??null,t.forcePathStyle?1:0,t.credentialRef??null,t.encryption,t.encryptionKeyRef??null,JSON.stringify(t.immutability),t.status,t.lastTestedAt??null,t.lastSuccessAt??null,t.lastFailureAt??null,t.lastError??null,1,n,n]),this.getDestination(e)}getDestination(t){let e=this.controlPlane.database.query("SELECT * FROM backup_destinations WHERE id=?").get(t);return e?Bu(e):void 0}listDestinations(t){return this.controlPlane.database.query("SELECT * FROM backup_destinations WHERE project_id=? ORDER BY name").all(t).map(Bu)}recordDestinationTest(t,e){let n=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=?",[e.ok?"healthy":"failing",n,e.ok?1:0,n,e.ok?1:0,n,e.ok?null:String(e.error??"Destination test failed.").slice(0,1000),n,t]),this.getDestination(t)}createPolicy(t){if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(t.name))throw Error("Backup policy names must be lowercase slugs.");if(!t.resourceId&&!t.dataServiceId&&!["control_plane","infrastructure"].includes(t.resourceKind))throw Error("A backup policy requires a resource or data service target.");let e=this.getDestination(t.destinationId);if(!e||e.projectId!==t.projectId)throw Error("Backup destination was not found.");if(t.resourceKind==="control_plane"&&e.encryption==="provider")throw Error("Control-plane backups require client-side destination encryption.");if(["logical_database","volume","files","control_plane"].includes(t.resourceKind)&&e.provider==="aws_backup")throw Error(`${t.resourceKind} backups require an object-storage destination.`);if(t.resourceKind==="infrastructure"&&e.provider!=="aws_backup")throw Error("Infrastructure backups require an AWS Backup destination.");let n=Zr(t.schedule),r=fr(n.normalized,t.timezone,this.now(),1)[0],i=crypto.randomUUID(),c=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,t.organizationId,t.projectId,t.environmentId??null,t.resourceId??null,t.dataServiceId??null,t.destinationId,t.name,t.resourceKind,n.normalized,t.timezone,JSON.stringify(t.retention),t.compression,t.encryption,JSON.stringify(t.includePatterns),JSON.stringify(t.excludePatterns),t.expectedRpoMinutes,t.expectedRtoMinutes,t.healthCheckId??null,t.enabled?1:0,r,t.lastRunAt??null,1,c,c]),this.getPolicy(i)}getPolicy(t){let e=this.controlPlane.database.query("SELECT * FROM backup_policies WHERE id=?").get(t);return e?Sa(e):void 0}listPolicies(t,e){return this.controlPlane.database.query(`SELECT * FROM backup_policies WHERE project_id=?${e?" AND environment_id=?":""} ORDER BY name`).all(t,...e?[e]:[]).map(Sa)}duePolicies(t=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(t.toISOString()).map(Sa)}advancePolicy(t,e){let n=this.getPolicy(t);if(!n)throw Error("Backup policy was not found.");let r=fr(n.schedule,n.timezone,new Date(e),1)[0];return this.controlPlane.database.run("UPDATE backup_policies SET last_run_at=?,next_run_at=?,version=version+1,updated_at=? WHERE id=?",[e,r,this.now().toISOString(),t]),this.getPolicy(t)}createJob(t){let e=this.controlPlane.database.query("SELECT * FROM backup_jobs WHERE idempotency_key=?").get(t.idempotencyKey);if(e)return _a(e);let n=crypto.randomUUID(),r=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 (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[n,t.projectId,t.policyId??null,t.recoveryPointId??null,t.operationId??null,t.kind,t.status,t.idempotencyKey,JSON.stringify(t.target),t.restoreMode??null,t.cancellability,t.safetyBackupId??null,t.healthResult?JSON.stringify(t.healthResult):null,JSON.stringify(t.progress),t.error??null,t.startedAt??null,t.finishedAt??null,r,r]),this.getJob(n)}getJob(t){let e=this.controlPlane.database.query("SELECT * FROM backup_jobs WHERE id=?").get(t);return e?_a(e):void 0}listJobs(t){return this.controlPlane.database.query("SELECT * FROM backup_jobs WHERE project_id=? ORDER BY created_at DESC").all(t).map(_a)}updateJob(t,e){let n=this.getJob(t);if(!n)throw Error("Backup job was not found.");let r={...n,...e};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=?",[r.status,r.operationId??null,r.recoveryPointId??null,JSON.stringify(r.progress),r.healthResult?JSON.stringify(r.healthResult):null,r.error??null,r.startedAt??null,r.finishedAt??null,r.safetyBackupId??null,this.now().toISOString(),t]),this.getJob(t)}createRecoveryPoint(t){if(!/^sha256:[a-f0-9]{64}$/i.test(t.checksum))throw Error("Recovery points require a SHA-256 checksum.");if(typeof t.uri!=="string"||!["s3:","aws-backup:","file:"].some((r)=>t.uri.startsWith(r)))throw Error("Recovery point URI uses an unsupported destination scheme.");let e=crypto.randomUUID(),n=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 (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[e,t.projectId,t.policyId??null,t.destinationId,t.resourceId??null,t.dataServiceId??null,t.backupJobId??null,t.kind,t.pointInTime,t.uri,t.sizeBytes,t.checksum,JSON.stringify(t.manifest),t.toolVersion??null,t.engineVersion??null,t.expiresAt??null,t.lockedUntil??null,t.held?1:0,t.pinned?1:0,t.status,t.verificationState,t.verifiedAt??null,t.durationMs??null,n,n]),this.getRecoveryPoint(e)}getRecoveryPoint(t){let e=this.controlPlane.database.query("SELECT * FROM recovery_points WHERE id=?").get(t);return e?fa(e):void 0}listRecoveryPoints(t,e){return this.controlPlane.database.query(`SELECT * FROM recovery_points WHERE project_id=?${e?" AND policy_id=?":""} ORDER BY point_in_time DESC`).all(t,...e?[e]:[]).map(fa)}updateRecoveryPoint(t,e){let n=this.getRecoveryPoint(t);if(!n)throw Error("Recovery point was not found.");let r={...n,...e};return this.controlPlane.database.run("UPDATE recovery_points SET status=?,verification_state=?,verified_at=?,held=?,pinned=?,manifest=?,duration_ms=?,updated_at=? WHERE id=?",[r.status,r.verificationState,r.verifiedAt??null,r.held?1:0,r.pinned?1:0,JSON.stringify(r.manifest),r.durationMs??null,this.now().toISOString(),t]),this.getRecoveryPoint(t)}retentionCandidates(t=this.now()){let e=this.controlPlane.database.query(`SELECT rp.* FROM recovery_points rp
|
|
38
|
-
WHERE rp.status='available' AND rp.held=0 AND rp.pinned=0
|
|
39
|
-
AND rp.expires_at IS NOT NULL AND rp.expires_at<=?
|
|
40
|
-
AND (rp.locked_until IS NULL OR rp.locked_until<=?)
|
|
41
|
-
AND NOT EXISTS (
|
|
42
|
-
SELECT 1 FROM backup_jobs bj WHERE bj.recovery_point_id=rp.id
|
|
43
|
-
AND bj.kind IN ('restore','drill') AND bj.status IN ('queued','running','cleanup_required')
|
|
44
|
-
)
|
|
45
|
-
ORDER BY rp.expires_at,rp.id`).all(t.toISOString(),t.toISOString()).map(fa),n=new Set;for(let r of new Set(e.map((i)=>i.projectId)))for(let i of this.listPolicies(r)){let c=this.listRecoveryPoints(i.projectId,i.id).filter((a)=>a.status==="available").sort((a,l)=>l.pointInTime.localeCompare(a.pointInTime));for(let a of c.slice(0,Math.max(0,i.retention.keepLast??0)))n.add(a.id);let d=[[i.retention.hourly,(a)=>a.toISOString().slice(0,13)],[i.retention.daily,(a)=>a.toISOString().slice(0,10)],[i.retention.weekly,(a)=>{return new Date(Date.UTC(a.getUTCFullYear(),a.getUTCMonth(),a.getUTCDate()-(a.getUTCDay()+6)%7)).toISOString().slice(0,10)}],[i.retention.monthly,(a)=>a.toISOString().slice(0,7)]];for(let[a,l]of d){let o=new Set;for(let u of c){let f=l(new Date(u.pointInTime));if(o.has(f))continue;if(o.add(f),o.size<=Math.max(0,a??0))n.add(u.id)}}}return e.filter((r)=>!n.has(r.id))}coverage(t,e=this.now()){let n=new Map(this.listDestinations(t).map((r)=>[r.id,r]));return this.listPolicies(t).map((r)=>{let i=this.listRecoveryPoints(t,r.id).filter((a)=>a.status==="available"),c=i[0],d=c?(e.getTime()-new Date(c.pointInTime).getTime())/60000:Number.POSITIVE_INFINITY;return{policy:r,lastRecoveryPoint:c,missedRpo:r.enabled&&d>r.expectedRpoMinutes,unverified:i.filter((a)=>a.verificationState!=="verified").length,destinationHealthy:n.get(r.destinationId)?.status==="healthy"}})}}import{createCipheriv as ZI,createDecipheriv as YI,createHash as zu,randomBytes as Tu}from"node:crypto";var Ea=Buffer.from("TSCB1"),xc=(t)=>`sha256:${zu("sha256").update(t).digest("hex")}`;function bu(t){return zu("sha256").update(t).digest()}function XI(t,e,n){let r=n?Buffer.from(n):Tu(12);if(r.length!==12)throw Error("Backup encryption IV must contain 12 bytes.");let i=ZI("aes-256-gcm",bu(e),r),c=Buffer.concat([i.update(t),i.final()]),d=i.getAuthTag();return Buffer.concat([Ea,r,d,c])}function KI(t,e){let n=Buffer.from(t);if(!n.subarray(0,Ea.length).equals(Ea))throw Error("Backup does not contain a valid encrypted envelope.");let r=n.subarray(5,17),i=n.subarray(17,33),c=n.subarray(33),d=YI("aes-256-gcm",bu(e),r);return d.setAuthTag(i),Buffer.concat([d.update(c),d.final()])}function pI(t){let e;try{e=JSON.parse(t)}catch{throw Error("Backup destination credential must be a JSON object with accessKeyId and secretAccessKey.")}if(!e.accessKeyId||!e.secretAccessKey)throw Error("Backup destination credential requires accessKeyId and secretAccessKey.");if(e.expiresAt){let n=new Date(String(e.expiresAt));if(!Number.isFinite(n.getTime()))throw Error("Backup destination credential expiresAt must be an ISO timestamp.");if(n.getTime()<=Date.now())throw Error("Backup destination credential has expired.")}return{accessKeyId:String(e.accessKeyId),secretAccessKey:String(e.secretAccessKey),sessionToken:e.sessionToken?String(e.sessionToken):void 0}}async function Wu(t,e,n=new Date){if(!t.credentialRef)return{status:"default"};try{let r=JSON.parse(await e.resolve(t.credentialRef));if(!r.accessKeyId||!r.secretAccessKey)return{status:"invalid"};if(!r.expiresAt)return{status:"static"};let i=new Date(String(r.expiresAt));if(!Number.isFinite(i.getTime()))return{status:"invalid"};let c=i.getTime()-n.getTime();return{status:c<=0?"expired":c<=604800000?"expiring":"valid",expiresAt:i.toISOString()}}catch{return{status:"invalid"}}}class Ia{secrets;clientFactory;multipartThreshold;partSize;constructor(t,e=(i,c)=>new _n(i.region??"us-east-1",void 0,{endpoint:i.endpoint?new URL(i.endpoint).host:void 0,forcePathStyle:i.forcePathStyle,credentials:c}),n=8388608,r=8388608){this.secrets=t;this.clientFactory=e;this.multipartThreshold=n;this.partSize=r}async client(t){let e=t.credentialRef?pI(await this.secrets.resolve(t.credentialRef)):void 0;return this.clientFactory(t,e)}async test(t){if(!t.bucket)throw Error("S3 destination has no configured bucket.");let e=await this.client(t),n=`${t.prefix?`${t.prefix.replace(/\/$/,"")}/`:""}.ts-cloud-health/${crypto.randomUUID()}`;await e.putObject({bucket:t.bucket,key:n,body:"ts-cloud backup destination health check",contentType:"text/plain"});try{let r=await e.getObjectBytes(t.bucket,n);if(Buffer.from(r.body).toString()!=="ts-cloud backup destination health check")throw Error("Backup destination health object was corrupted.")}finally{await e.deleteObject(t.bucket,n)}}async upload(t,e){if(!t.bucket)throw Error("S3 destination has no configured bucket.");let n=await this.client(t),r=xc(e.body),i=t.encryption!=="provider"?await this.secrets.resolve(t.encryptionKeyRef):void 0,c=i?e.resume?.encryptionIv?Buffer.from(e.resume.encryptionIv,"base64url"):Tu(12):void 0,d=i?XI(e.body,i,c):Buffer.from(e.body),a=xc(d),l=`${t.prefix?`${t.prefix.replace(/\/$/,"")}/`:""}${e.key.replace(/^\/+/,"")}`,o=e.contentType??"application/octet-stream",u={"ts-cloud-format":"v1","ts-cloud-sha256":a.slice(7),"ts-cloud-encrypted":i?"true":"false"};if(e.resume&&e.resume.key!==l)throw Error("Multipart checkpoint does not match the requested backup key.");if(e.resume&&i&&!e.resume.encryptionIv)throw Error("Encrypted multipart checkpoint has no resumable envelope state.");if(e.resume&&i&&e.resume.plaintextChecksum!==r)throw Error("Encrypted multipart checkpoint does not match the backup payload.");if(d.length<this.multipartThreshold)await n.putObject({bucket:t.bucket,key:l,body:d,contentType:o,metadata:u});else{let f=e.resume?void 0:await n.createMultipartUpload(t.bucket,l,{contentType:o,metadata:u}),R=e.resume??{uploadId:f.UploadId,key:l,parts:[],bytesUploaded:0,encryptionIv:c?.toString("base64url"),plaintextChecksum:r},E=new Map(R.parts.map(($)=>[$.PartNumber,$])),y=Math.ceil(d.length/this.partSize);for(let $=0;$<y;$++){let C=$+1;if(!E.has(C)){let J=$*this.partSize,H=await n.uploadPart(t.bucket,l,R.uploadId,C,d.subarray(J,Math.min(d.length,J+this.partSize)));E.set(C,{PartNumber:C,ETag:H.ETag})}R.parts=[...E.values()].sort((J,H)=>J.PartNumber-H.PartNumber),R.bytesUploaded=Math.min(d.length,C*this.partSize),e.checkpoint?.(R)}await n.completeMultipartUpload(t.bucket,l,R.uploadId,R.parts)}return{uri:`s3://${t.bucket}/${l}`,key:l,sizeBytes:d.length,checksum:a,manifest:{format:"ts-cloud-backup-v1",encrypted:!!i,plaintextChecksum:r,storageChecksum:a,contentType:o}}}async download(t,e){if(!t.bucket)throw Error("S3 destination has no configured bucket.");let n=await this.client(t),r=await n.getObjectBytes(t.bucket,e.key),i=Buffer.from(r.body);if(xc(i)!==e.checksum)throw Error("Backup checksum verification failed; object is corrupt.");let c=e.manifest.encrypted?KI(i,await this.secrets.resolve(t.encryptionKeyRef)):i;if(xc(c)!==e.manifest.plaintextChecksum)throw Error("Backup plaintext checksum verification failed.");return c}async abortPartial(t,e){if(!t.bucket)throw Error("S3 destination has no configured bucket.");await(await this.client(t)).abortMultipartUpload(t.bucket,e.key,e.uploadId)}async delete(t,e){if(!t.bucket)throw Error("S3 destination has no configured bucket.");await(await this.client(t)).deleteObject(t.bucket,e)}}import{createHash as mI}from"node:crypto";var qI=(t)=>`sha256:${mI("sha256").update(t).digest("hex")}`;class Mc{store;queue;now;constructor(t,e,n=()=>new Date){this.store=t;this.queue=e;this.now=n}enqueueBackup(t,e=this.now().toISOString(),n){if(!t.enabled)throw Error("Backup policy is disabled.");let r=this.store.createJob({projectId:t.projectId,policyId:t.id,kind:"backup",status:"queued",idempotencyKey:`backup:${t.id}:${e}`,target:{scheduledFor:e},cancellability:"checkpoint_only",progress:{phase:"queued"}});if(!r.operationId){let i=this.queue.enqueue({projectId:t.projectId,environmentId:t.environmentId,resourceId:t.resourceId,actorId:n,kind:"backup.run",input:{backupJobId:r.id},lockKey:t.dataServiceId?`data-service:${t.dataServiceId}`:t.resourceId?`resource:${t.resourceId}`:`backup-policy:${t.id}`,providerKey:"backup",maxAttempts:3,timeoutSeconds:14400,retryClasses:["provider_transient"],resumePolicy:"requeue"});return this.store.updateJob(r.id,{operationId:i.operation.id})}return r}enqueueDue(t=this.now()){return this.store.duePolicies(t).map((e)=>{let n=e.nextRunAt;return this.store.advancePolicy(e.id,n),this.enqueueBackup(e,n)})}enqueueVerification(t){let e=this.store.createJob({projectId:t.projectId,policyId:t.policyId,recoveryPointId:t.id,kind:"verify",status:"queued",idempotencyKey:`verify:${t.id}:${t.checksum}`,target:{},cancellability:"safe",progress:{phase:"queued"}});if(!e.operationId){let n=this.queue.enqueue({projectId:t.projectId,resourceId:t.resourceId,kind:"backup.verify",input:{backupJobId:e.id},lockKey:`recovery-point:${t.id}`,providerKey:"backup",maxAttempts:2,timeoutSeconds:7200,retryClasses:["provider_transient"],resumePolicy:"requeue"});return this.store.updateJob(e.id,{operationId:n.operation.id})}return e}planRestore(t,e){if(t.status!=="available")throw Error("Only available recovery points can be restored.");if(t.verificationState!=="verified")throw Error("Restore requires a verified recovery point.");if(e.mode==="in_place"){if(!e.recentAuth)throw Error("In-place restore requires recent authentication.");if(e.confirm!==e.targetName)throw Error(`Type ${e.targetName} to confirm in-place restore.`);if(!e.downtimeAcknowledged)throw Error("In-place restore requires downtime acknowledgement.");let n=e.safetyBackupId?this.store.getRecoveryPoint(e.safetyBackupId):void 0;if(!n||n.id===t.id||n.status!=="available"||n.verificationState!=="verified"||n.resourceId!==t.resourceId||n.dataServiceId!==t.dataServiceId)throw Error("In-place restore requires a distinct verified safety backup for the same target.")}return{point:t,mode:e.mode,target:{...e.target,inPlace:e.mode==="in_place",restoreMode:e.mode},warnings:e.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(t,e){let n=this.planRestore(t,e),r=e.drill?"drill":"restore",i=qI(JSON.stringify({point:t.id,mode:e.mode,target:e.target,safety:e.safetyBackupId,drill:!!e.drill})),c=this.store.createJob({projectId:t.projectId,policyId:t.policyId,recoveryPointId:t.id,kind:r,status:"queued",idempotencyKey:`${r}:${i}`,target:n.target,restoreMode:n.mode,cancellability:"checkpoint_only",safetyBackupId:e.safetyBackupId,progress:{phase:"queued",warnings:n.warnings}});if(!c.operationId){let d=this.queue.enqueue({projectId:t.projectId,resourceId:t.resourceId,actorId:e.actorId,kind:e.drill?"backup.drill":"backup.restore",input:{backupJobId:c.id},lockKey:t.dataServiceId?`data-service:${t.dataServiceId}`:t.resourceId?`resource:${t.resourceId}`:`recovery-point:${t.id}`,providerKey:"backup",maxAttempts:1,timeoutSeconds:14400,retryClasses:[],resumePolicy:"fail"});return this.store.updateJob(c.id,{operationId:d.operation.id})}return c}enqueueRetention(t=this.now()){return this.store.retentionCandidates(t).map((e)=>{let n=this.store.createJob({projectId:e.projectId,policyId:e.policyId,recoveryPointId:e.id,kind:"cleanup",status:"queued",idempotencyKey:`cleanup:${e.id}:${e.expiresAt}`,target:{},cancellability:"safe",progress:{phase:"queued"}});if(!n.operationId){let r=this.queue.enqueue({projectId:e.projectId,resourceId:e.resourceId,kind:"backup.cleanup",input:{backupJobId:n.id},lockKey:`recovery-point:${e.id}`,providerKey:"backup",maxAttempts:3,timeoutSeconds:7200,retryClasses:["provider_transient"],resumePolicy:"requeue"});return this.store.updateJob(n.id,{operationId:r.operation.id})}return n})}}function Uu(t){let e=t.now??(()=>new Date),n=new Mc(t.store,t.queue,e),r=(a)=>{let l=a.recoveryPointId?t.store.getRecoveryPoint(a.recoveryPointId):void 0,o=a.policyId?t.store.getPolicy(a.policyId):l?.policyId?t.store.getPolicy(l.policyId):void 0;if(!o)throw Error("Backup policy was not found.");let u=t.store.getDestination(l?.destinationId??o.destinationId),f=t.resolveSource(o);if(!u)throw Error("Backup destination was not found.");if(!f)throw Error(`No ${o.resourceKind} backup adapter is configured.`);return{point:l,policy:o,destination:u,source:f}},i=(a)=>{let l=a.operation.input,o=t.store.getJob(String(l.backupJobId??""));if(!o)throw Error("Backup job was not found.");return t.store.updateJob(o.id,{status:"running",startedAt:o.startedAt??e().toISOString(),progress:{...o.progress,phase:"running"}}),o},c=(a,l)=>{let o=t.store.getJob(a.id)??a;t.store.updateJob(a.id,{status:"failed",finishedAt:e().toISOString(),error:l instanceof Error?l.message:String(l),progress:{...o.progress,phase:"failed"}})};return{"backup.run":async(a)=>{let l=i(a);try{let{policy:o,destination:u,source:f}=r(l),R=await f.create(o,a),E=t.resolveDestination(u),y=R.mode==="object"?await(async()=>{if(!E)throw Error("Backup destination adapter is not configured.");let H=t.store.getJob(l.id)?.progress,O=H?.multipart,Y=O&&typeof O==="object"&&!Array.isArray(O)&&typeof O.uploadId==="string"&&typeof O.key==="string"&&Array.isArray(O.parts)?O:void 0;return E.upload(u,{key:R.key,body:R.body,contentType:R.contentType,resume:Y,checkpoint:(dt)=>{a.checkpoint("uploading",`Uploaded ${Number(dt.bytesUploaded??0)} backup bytes.`),t.store.updateJob(l.id,{progress:{phase:"uploading",multipart:{...dt}}})}})})():{uri:R.uri,key:R.uri,sizeBytes:R.sizeBytes,checksum:R.checksum,manifest:{format:"ts-cloud-backup-v1",encrypted:!1,plaintextChecksum:R.checksum,storageChecksum:R.checksum,contentType:"application/provider-snapshot"}},$=o.retention.expireAfterDays?new Date(e().getTime()+o.retention.expireAfterDays*86400000).toISOString():void 0,C=t.store.getJob(l.id)?.startedAt,J=t.store.createRecoveryPoint({projectId:o.projectId,policyId:o.id,destinationId:u.id,resourceId:o.resourceId,dataServiceId:o.dataServiceId,backupJobId:l.id,kind:o.resourceKind,pointInTime:e().toISOString(),uri:y.uri,sizeBytes:y.sizeBytes,checksum:y.checksum,manifest:{...R.manifest,...y.manifest,storageKey:y.key},toolVersion:R.toolVersion,engineVersion:R.engineVersion,expiresAt:$,lockedUntil:u.immutability.defaultRetentionDays?new Date(e().getTime()+u.immutability.defaultRetentionDays*86400000).toISOString():void 0,held:!1,pinned:!1,status:"available",verificationState:"unverified",durationMs:Math.max(0,e().getTime()-new Date(C??e().toISOString()).getTime())});if(R.mode==="external"&&u.provider==="aws_backup")t.store.recordDestinationTest(u.id,{ok:!0});return t.store.updateJob(l.id,{status:"succeeded",recoveryPointId:J.id,finishedAt:e().toISOString(),progress:{phase:"stored",recoveryPointId:J.id}}),n.enqueueVerification(J),{backupJobId:l.id,recoveryPointId:J.id}}catch(o){let u=t.store.getJob(l.id),f=u?.progress.multipart,R=(()=>{try{return r(l)}catch{return}})();if(R?.destination.provider==="aws_backup")t.store.recordDestinationTest(R.destination.id,{ok:!1,error:o instanceof Error?o.message:String(o)});let E=!1;if(f&&typeof f==="object"&&!Array.isArray(f)&&R){let y=t.resolveDestination(R.destination);if(E=!0,y?.abortPartial)try{await y.abortPartial(R.destination,f),E=!1,t.store.updateJob(l.id,{progress:{...u.progress,partialCleanup:"aborted"}})}catch{t.store.updateJob(l.id,{progress:{...u.progress,partialCleanup:"required"}})}}if(E)t.store.updateJob(l.id,{status:"cleanup_required",finishedAt:e().toISOString(),error:o instanceof Error?o.message:String(o),progress:{...t.store.getJob(l.id)?.progress??{},phase:"cleanup_required"}});else c(l,o);throw o}},"backup.verify":async(a)=>{let l=i(a);try{let{point:o,destination:u,source:f}=r(l);if(!o)throw Error("Recovery point was not found.");t.store.updateRecoveryPoint(o.id,{verificationState:"verifying"});let R;if(o.uri.startsWith("s3:")){let E=t.resolveDestination(u);if(!E)throw Error("Backup destination adapter is not configured.");let y=await E.download(u,{key:String(o.manifest.storageKey??""),checksum:o.checksum,manifest:o.manifest}),$=f.verify?await f.verify(o,y,a):{};R={bytes:y.length,checksum:o.checksum,...$}}else if(f.verifyExternal)R=await f.verifyExternal(o,a);else throw Error("External recovery point verification is not supported.");return t.store.updateRecoveryPoint(o.id,{verificationState:"verified",verifiedAt:e().toISOString(),manifest:{...o.manifest,verification:R}}),t.store.updateJob(l.id,{status:"succeeded",finishedAt:e().toISOString(),progress:{phase:"verified",evidence:R}}),{backupJobId:l.id,recoveryPointId:o.id,evidence:R}}catch(o){if(l.recoveryPointId)t.store.updateRecoveryPoint(l.recoveryPointId,{verificationState:/checksum|corrupt|authentic/i.test(o instanceof Error?o.message:String(o))?"corrupt":"failed"});throw c(l,o),o}},"backup.restore":async(a)=>d(a,!1),"backup.drill":async(a)=>d(a,!0),"backup.cleanup":async(a)=>{let l=i(a);try{let{point:o,destination:u,source:f}=r(l);if(!o)throw Error("Recovery point was not found.");if(!t.store.retentionCandidates(e()).some((R)=>R.id===o.id))throw Error("Recovery point is held, pinned, locked, or in active use.");if(t.store.updateRecoveryPoint(o.id,{status:"deleting"}),o.uri.startsWith("s3:")){let R=t.resolveDestination(u);if(!R)throw Error("Destination cleanup is unavailable.");await R.delete(u,String(o.manifest.storageKey??""))}else if(f.deleteExternal)await f.deleteExternal(o,a);else throw Error("External recovery point cleanup is unavailable.");return t.store.updateRecoveryPoint(o.id,{status:"deleted"}),t.store.updateJob(l.id,{status:"succeeded",finishedAt:e().toISOString(),progress:{phase:"deleted"}}),{backupJobId:l.id,recoveryPointId:o.id,deleted:!0}}catch(o){throw c(l,o),o}}};async function d(a,l){let o=i(a);try{let{point:u,policy:f,destination:R,source:E}=r(o);if(!u)throw Error("Recovery point was not found.");if(l&&!E.cleanup)throw Error("This backup source cannot safely clean a recovery drill target.");let y=u.uri.startsWith("s3:")?t.resolveDestination(R):void 0,$=y?await y.download(R,{key:String(u.manifest.storageKey??""),checksum:u.checksum,manifest:u.manifest}):void 0,C=await E.restore(u,$,o.target,a),J=E.validateHealth?await E.validateHealth({...o.target,...C},a):{healthy:!0,mode:"adapter"},H=t.validateHealth?await t.validateHealth(f,o.target):{healthy:!0,mode:"not_configured"},O={...J,healthy:J.healthy===!0&&H.healthy===!0,configured:H};if(O.healthy!==!0)throw Error("Restored target did not pass its configured health check.");if(l&&E.cleanup)await E.cleanup({...o.target,provider:u.manifest.provider??null},a);return t.store.updateJob(o.id,{status:"succeeded",finishedAt:e().toISOString(),healthResult:O,progress:{phase:l?"drill_cleaned":"restored",restored:C}}),{backupJobId:o.id,recoveryPointId:u.id,restored:C,health:O,cleaned:l}}catch(u){let f=(()=>{try{return r(o)}catch{return}})(),R=u instanceof Error?u.message:String(u),E=!1;if(l&&f?.source.cleanup)try{await f.source.cleanup({...o.target,provider:f.point?.manifest.provider??null},a)}catch{E=!0}if(E)t.store.updateJob(o.id,{status:"cleanup_required",finishedAt:e().toISOString(),error:R,progress:{...o.progress,phase:"cleanup_required"}});else c(o,u);throw u}}}import{createHash as tw}from"node:crypto";var ew=(t)=>`sha256:${tw("sha256").update(t).digest("hex")}`;class wa{dataServices;client;constructor(t,e=new Er){this.dataServices=t;this.client=e}service(t){let e=t.dataServiceId?this.dataServices.get(t.dataServiceId):void 0;if(!e||!["aws_rds","aws_aurora"].includes(e.provider))throw Error("Managed database backup policy requires an RDS or Aurora data service.");return e}async waitForSnapshot(t,e,n){for(;;){n.throwIfCancellationRequested?.(),n.heartbeat?.();let r=t==="aws_aurora"?(await this.client.describeDBClusterSnapshots({DBClusterSnapshotIdentifier:e})).DBClusterSnapshots[0]:(await this.client.describeDBSnapshots({DBSnapshotIdentifier:e})).DBSnapshots?.[0];if(!r)throw Error("Provider snapshot was not found.");let i=r,c=String(i.Status??i.DBSnapshotStatus??"unknown");if(n.checkpoint?.("provider_snapshot",`Database snapshot ${e} is ${c}.`),c==="available")return i;if(["deleted","deleting","failed"].includes(c))throw Error(`Provider snapshot ${e} failed with state ${c}.`);await Bun.sleep(5000)}}async create(t,e){let n=this.service(t),r=String(e.operation?.id??new Date().toISOString()).replace(/[^A-Za-z0-9]/g,"").slice(0,20),i=`${n.placement.slice(0,42).replace(/-+$/,"")}-${r}`;if(n.provider==="aws_aurora")await this.client.createDBClusterSnapshot(n.placement,i);else await this.client.createDBSnapshot({DBInstanceIdentifier:n.placement,DBSnapshotIdentifier:i});await this.waitForSnapshot(n.provider,i,e);let c=`${n.provider}:${n.placement}:${i}`;return{mode:"external",uri:`aws-backup:${c}`,checksum:ew(c),sizeBytes:0,manifest:{provider:n.provider,sourceId:n.placement,snapshotId:i,plan:n.plan,engine:n.engine},engineVersion:n.engineVersion,toolVersion:"aws-rds-api-2014-10-31"}}async verifyExternal(t,e){let n=String(t.manifest.snapshotId??""),r=String(t.manifest.provider??"");if(!n)throw Error("Snapshot recovery point has no snapshot ID.");let i=await this.waitForSnapshot(r,n,e),c=String(i.Status??i.DBSnapshotStatus??"unknown");return{snapshotId:n,status:c,encrypted:i.Encrypted??i.StorageEncrypted??!0}}async restore(t,e,n,r){let i=String(n.targetId??""),c=String(t.manifest.snapshotId??""),d=String(t.manifest.provider??"");if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(i))throw Error("Managed restore requires a valid distinct targetId.");if(i===t.manifest.sourceId)throw Error("Managed restore target must differ from its source.");if(d==="aws_aurora"){let a=t.manifest.engine==="postgres"?"aurora-postgresql":"aurora-mysql";await this.client.restoreDBClusterFromSnapshot({DBClusterIdentifier:i,SnapshotIdentifier:c,Engine:a,EngineVersion:t.engineVersion,DeletionProtection:!0,ServerlessV2ScalingConfiguration:{MinCapacity:Number(n.minCapacity)||0.5,MaxCapacity:Number(n.maxCapacity)||4}}),await this.client.createDBInstance({DBInstanceIdentifier:`${i}-writer-1`,DBClusterIdentifier:i,DBInstanceClass:String(n.plan??t.manifest.plan??"db.serverless"),Engine:a,PubliclyAccessible:!1})}else await this.client.restoreDBInstanceFromDBSnapshot({DBInstanceIdentifier:i,DBSnapshotIdentifier:c,DBInstanceClass:String(n.plan??t.manifest.plan??""),PubliclyAccessible:!1,DeletionProtection:!0,Tags:[{Key:"managed-by",Value:"ts-cloud-restore"}]});return{targetId:i,provider:d,status:"creating",isolated:!0}}async validateHealth(t,e){let n=String(t.targetId??""),r=String(t.provider??"");for(;;){e.throwIfCancellationRequested?.(),e.heartbeat?.();let i=r==="aws_aurora"?(await this.client.describeDBClusters({DBClusterIdentifier:n})).DBClusters?.[0]:(await this.client.describeDBInstances({DBInstanceIdentifier:n})).DBInstances?.[0];if(!i)throw Error("Restored managed database was not found.");let c=String(i.Status??i.DBInstanceStatus??"unknown");if(e.checkpoint?.("provider_restore",`Restored database ${n} is ${c}.`),c==="available")return{healthy:!0,targetId:n,provider:r,status:c};if(["deleted","deleting","failed","incompatible-restore"].includes(c))throw Error(`Restored managed database ${n} failed with state ${c}.`);await Bun.sleep(5000)}}async cleanup(t,e){let n=String(t.targetId??""),r=String(t.provider??"");if(!n)throw Error("Restore cleanup target is required.");if(r==="aws_aurora")await this.client.deleteDBInstance({DBInstanceIdentifier:`${n}-writer-1`,SkipFinalSnapshot:!0}),await this.client.modifyDBCluster({DBClusterIdentifier:n,DeletionProtection:!1,ApplyImmediately:!0}),await this.client.deleteDBCluster(n);else await this.client.modifyDBInstance({DBInstanceIdentifier:n,DeletionProtection:!1,ApplyImmediately:!0}),await this.client.deleteDBInstance({DBInstanceIdentifier:n,SkipFinalSnapshot:!0,DeleteAutomatedBackups:!0})}async deleteExternal(t,e){let n=String(t.manifest.snapshotId??"");if(t.manifest.provider==="aws_aurora")await this.client.deleteDBClusterSnapshot(n);else await this.client.deleteDBSnapshot(n)}}var se=(t,e="none",n=!1)=>({supported:!0,downtime:e,destructive:n,explanation:t}),mt=(t)=>({supported:!1,downtime:"none",destructive:!1,explanation:t});function Li(t,e){let n=["aws_rds","aws_aurora","aws_elasticache"].includes(e),r=["server","container"].includes(e),i=["postgres","mysql","mariadb"].includes(t),c=t==="redis",d={};return d.create=e==="external"?mt("External services can be adopted as read-only inventory."):se(n?"Provision through the provider API.":"Provision through the owning runtime driver.","possible"),d.observe=e==="external"?mt("External observation requires a configured provider adapter."):se("Provider/runtime health and endpoint metadata are observable."),d.connect=se("Connection guidance uses secret references and never returns a password by default."),d.backup=i&&(n||r)?se(n?"Create a provider snapshot.":"Create a consistent engine-native dump.","possible"):mt("This cache path is not a durable backup source."),d.restore=n&&i?se("Restore creates a reviewed provider target.","required",!0):mt("Restore requires a configured provider restore runner."),d.restart=e==="external"?mt("External restart requires a configured provider adapter."):se(n?"Provider restart/failover semantics apply.":"Restart the owning service unit.","required"),d.resize=e==="aws_elasticache"?mt("ElastiCache resizing requires a replication-group migration runner."):n?se("Provider plan/storage modification may enter a maintenance window.","possible"):r?se("Edit host/container resources and reconcile.","required"):mt("External resize requires a configured provider adapter."),d.version=r?mt("Runtime version upgrades require an explicit image migration runner."):n&&e!=="aws_elasticache"?se(i?"Major versions require compatibility preflight and backup.":"Engine upgrades require a maintenance window.","required"):mt("External upgrades require a configured provider adapter."),d.rotate=e==="aws_elasticache"||e==="external"||r&&!i&&!c?mt("Credential rotation is not available for this provider/engine path."):se("Rotate through the secret backend, update the engine, then flag dependent releases."),d.expose=r?mt("Direct container publishing is refused; use a reviewed firewall and proxy policy."):e==="aws_rds"?se("Exposure is reconciled through security groups; public access defaults off."):mt("Exposure changes require a provider-specific network runner."),d.delete=e==="external"?mt("External deletion requires a configured provider adapter."):se(n?"Final snapshot is supported where the provider allows it.":"A final engine backup is required unless explicitly retained.","required",!0),d.logs=r?se("Read bounded service logs from the runtime."):mt("Provider log export is not configured for this adapter."),d.slow_queries=r&&i?se("Read bounded runtime logs after engine slow-query logging is enabled."):mt("A slow-query log runner is not configured for this provider."),d.users=r&&i?se("Logical users can be listed; creation requires a referenced secondary credential."):mt("User management requires an engine connection runner."),d.databases=r&&i?se("Logical databases can be listed, created, and confirmation-gated for deletion."):mt("Logical database management requires an engine connection runner."),{actions:d,endpointTypes:n?["internal","external","tunnel"]:["internal","tunnel"],metrics:c?["connections","memory","evictions","hit_rate","latency"]:["connections","cpu","storage","read_latency","write_latency","iops"]}}var Yr=(t)=>t==null?void 0:String(t),Gc=(t)=>Number(t)===1,Qc=(t)=>{try{return JSON.parse(String(t))}catch{return{}}};function ju(t){return{id:String(t.id),organizationId:String(t.organization_id),projectId:String(t.project_id),environmentId:Yr(t.environment_id),resourceId:Yr(t.resource_id),name:String(t.name),engine:String(t.engine),provider:String(t.provider),placement:String(t.placement),engineVersion:Yr(t.engine_version),plan:String(t.plan),storageGb:t.storage_gb==null?void 0:Number(t.storage_gb),highAvailability:Gc(t.high_availability),publicExposure:Gc(t.public_exposure),allowedCidrs:Qc(t.allowed_cidrs),desiredState:Qc(t.desired_state),observedState:Qc(t.observed_state),capabilities:Qc(t.capabilities),credentialRef:Yr(t.credential_ref),status:String(t.status),origin:String(t.origin),managementEnabled:Gc(t.management_enabled),ownerActorId:Yr(t.owner_actor_id),version:Number(t.version),createdAt:String(t.created_at),updatedAt:String(t.updated_at)}}class Aa{controlPlane;now;constructor(t,e=()=>new Date){this.controlPlane=t;this.now=e}create(t){if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(t.name))throw Error("Data service names must be 2-63 lowercase letters, numbers, or dashes.");if(t.publicExposure&&(!t.allowedCidrs.length||t.allowedCidrs.includes("0.0.0.0/0")))throw Error("Public exposure requires explicit narrow CIDRs; 0.0.0.0/0 is refused.");let e=crypto.randomUUID(),n=this.now().toISOString(),r=Li(t.engine,t.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 (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[e,t.organizationId,t.projectId,t.environmentId??null,t.resourceId??null,t.name,t.engine,t.provider,t.placement,t.engineVersion??null,t.plan,t.storageGb??null,t.highAvailability?1:0,t.publicExposure?1:0,JSON.stringify(t.allowedCidrs),JSON.stringify(t.desiredState),JSON.stringify(t.observedState),JSON.stringify(r),t.credentialRef??null,t.status,t.origin,t.managementEnabled?1:0,t.ownerActorId??null,1,n,n]),this.get(e)}get(t){let e=this.controlPlane.database.query("SELECT * FROM data_services WHERE id=?").get(t);return e?ju(e):void 0}list(t,e){return this.controlPlane.database.query(`SELECT * FROM data_services WHERE project_id=?${e?" AND environment_id=?":""} ORDER BY name`).all(t,...e?[e]:[]).map(ju)}update(t,e,n){let r=this.get(t);if(!r)throw Error("Data service was not found.");if(r.version!==e)throw Error("Data service changed; refresh before retrying.");let i={...r,...n};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(),t,e]).changes!==1)throw Error("Data service changed; refresh before retrying.");return this.get(t)}credential(t){let e=this.controlPlane.database.query("SELECT * FROM data_service_credentials WHERE service_id=? ORDER BY version DESC LIMIT 1").get(t);return e?{id:String(e.id),serviceId:String(e.service_id),username:String(e.username),secretRef:String(e.secret_ref),version:Number(e.version),createdAt:String(e.created_at),rotatedAt:Yr(e.rotated_at)}:void 0}saveCredential(t,e,n){let r=this.credential(t),i=r?.id??crypto.randomUUID(),c=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,t,e,n,r?.version??1,r?.createdAt??c,r?c:null]),this.credential(t)}addDependency(t){let e=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",[t.serviceId,t.resourceId,t.secretRef,t.requiresRedeploy?1:0,e]),{...t,createdAt:e}}dependencies(t){return this.controlPlane.database.query("SELECT * FROM data_service_dependencies WHERE service_id=? ORDER BY resource_id").all(t).map((e)=>({serviceId:String(e.service_id),resourceId:String(e.resource_id),secretRef:String(e.secret_ref),requiresRedeploy:Gc(e.requires_redeploy),createdAt:String(e.created_at)}))}removeDependency(t,e){return this.controlPlane.database.run("DELETE FROM data_service_dependencies WHERE service_id=? AND resource_id=?",[t,e]).changes===1}remove(t){this.controlPlane.database.run("DELETE FROM data_services WHERE id=?",[t])}}function Hu(){let e=crypto.getRandomValues(new Uint8Array(40));return Array.from(e,(n)=>"ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@#$%^&*_-+="[n%69]).join("")}function Lu(t,e){return e.map((n)=>{let r=n.type==="tunnel"?"127.0.0.1":n.host,i=t.engine==="redis"?`redis-cli -h ${r} -p ${n.port}${n.tls?" --tls":""}`:t.engine==="postgres"?`psql "host=${r} port=${n.port} dbname=${n.database??"postgres"} sslmode=${n.tls?"require":"disable"}"`:t.engine==="mongodb"?`mongosh "mongodb://${r}:${n.port}/${n.database??"admin"}${n.tls?"?tls=true":""}"`:t.engine==="libsql"?`turso db shell ${n.tls?"https":"http"}://${r}:${n.port}`:`mysql --host=${r} --port=${n.port} --database=${n.database??"mysql"} --ssl-mode=${n.tls?"REQUIRED":"DISABLED"}`;return{type:n.type,command:i,secretRef:t.credentialRef}})}class Zc{store;queue;secrets;constructor(t,e,n){this.store=t;this.queue=e;this.secrets=n}async create(t){let e,n;if(t.provider!=="aws_elasticache"){let r=t.username??"app",i=Hu();n=`secret://data-services/${t.projectId}/${t.name}/${r}`,await this.secrets.put(n,i),e={username:r,password:i,secretRef:n}}try{let r=this.store.create({...t,credentialRef:n,status:"planning"});if(e)this.store.saveCredential(r.id,e.username,e.secretRef);let i=this.enqueue(r,"create",{});return{service:r,credential:e,operationId:i}}catch(r){if(n)await this.secrets.remove(n);throw r}}plan(t,e,n={}){let r=t.capabilities.actions[e],i=e==="version"&&String(n.engineVersion??"").split(".")[0]!==String(t.engineVersion??"").split(".")[0];return{service:t,action:e,capability:r,changes:n,preflight:{backupRequired:["delete","restore"].includes(e)||i,compatibilityRequired:i,typedConfirmation:r.destructive?t.name:void 0,retentionChoiceRequired:e==="delete"},warnings:[...r.downtime!=="none"?[`Downtime is ${r.downtime}.`]:[],...t.origin==="adopted"&&!t.managementEnabled?["Adopted resource is read-only until management is explicitly enabled."]:[]]}}enqueue(t,e,n,r){let i=this.plan(t,e,n);if(!i.capability.supported)throw Error(i.capability.explanation);if(t.origin==="adopted"&&!t.managementEnabled&&e!=="observe")throw Error("Adopted resources remain read-only until management is explicitly enabled.");if(i.preflight.typedConfirmation&&n.confirm!==i.preflight.typedConfirmation)throw Error(`Type ${i.preflight.typedConfirmation} to confirm ${e}.`);if(i.preflight.retentionChoiceRequired&&!["final_backup","retain"].includes(String(n.retention??"")))throw Error("Deletion requires retention final_backup or retain.");if(i.preflight.compatibilityRequired&&(n.compatibilityReviewed!==!0||!n.backupId))throw Error("Major version changes require compatibilityReviewed=true and a backupId.");if(e==="restore"){let c=String(n.backupId??""),d=String(n.targetId??"");if(!c||!d)throw Error("Restore requires both backupId and targetId.");if(d===t.placement)throw Error("Restore targetId must differ from the source placement.");if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(d))throw Error("Restore targetId must be 2-63 lowercase letters, numbers, or dashes.")}return this.queue.enqueue({projectId:t.projectId,environmentId:t.environmentId,resourceId:t.resourceId,actorId:r,kind:"data_service.action",input:{serviceId:t.id,action:e,...n},lockKey:`data-service:${t.id}`,providerKey:t.provider,maxAttempts:3,timeoutSeconds:7200,retryClasses:["provider_transient"],resumePolicy:"requeue"}).operation.id}async rotate(t,e,n){let r=this.store.credential(t.id);if(!r)throw Error("Data service credential metadata was not found.");let i=Hu(),c=`${r.secretRef}/v${r.version+1}`;await this.secrets.put(c,i);try{return await e.action(t,"rotate",{username:r.username,secretRef:c},i,n),this.store.saveCredential(t.id,r.username,c),this.store.update(t.id,t.version,{credentialRef:c}),{credential:{username:r.username,password:i,secretRef:c},dependencies:this.store.dependencies(t.id).filter((d)=>d.requiresRedeploy).map((d)=>d.resourceId)}}catch(d){throw await this.secrets.remove(c),d}}}function Fu(t){return{"data_service.action":async(e)=>{let n=e.operation.input,r=t.store.get(String(n.serviceId??"")),i=String(n.action??"");if(!r)throw Error("Data service was not found.");let c=t.resolveAdapter(r);if(!c||c.provider!==r.provider||!c.engines.includes(r.engine))throw Error(`No ${r.provider}/${r.engine} adapter is configured.`);if(i==="rotate"){let a=await new Zc(t.store,new Ot(t.store.controlPlane),t.secrets).rotate(r,c,e);return{serviceId:r.id,action:i,username:a.credential.username,secretRef:a.credential.secretRef,dependencies:a.dependencies}}let d=r.credentialRef?await t.secrets.resolve(r.credentialRef):void 0;try{let a=i==="observe"?await c.observe(r):i==="create"?await c.apply(r,d,e):await c.action(r,i,n,d,e),l=t.store.get(r.id);return t.store.update(r.id,l.version,{observedState:a,status:i==="delete"?n.retention==="retain"?"retained":"deleting":"available"}),{serviceId:r.id,action:i,observed:a}}catch(a){let l=t.store.get(r.id);if(t.store.update(r.id,l.version,{status:"failed",observedState:{...l.observedState,error:a instanceof Error?a.message:String(a)}}),/temporar|timeout|unavailable|throttl/i.test(a instanceof Error?a.message:String(a)))throw new Lc(a instanceof Error?a.message:String(a),"provider_transient");throw a}}}}class Xr{transport;constructor(t){this.transport=t}observe(t){return this.transport.observe(t.placement)}apply(t,e){return this.transport.apply({id:t.placement,name:t.name,engine:t.engine,engineVersion:t.engineVersion??null,plan:t.plan,storageGb:t.storageGb??null,highAvailability:t.highAvailability,publicExposure:t.publicExposure,allowedCidrs:t.allowedCidrs,username:t.desiredState.username??"app",desiredState:t.desiredState},e)}action(t,e,n,r,i){return this.transport.execute(t.placement,e,{engine:t.engine,engineVersion:t.engineVersion??null,plan:t.plan,desiredState:t.desiredState,...n},r,i)}}class Da extends Xr{provider="aws_rds";engines=["postgres","mysql","mariadb"]}class ya extends Xr{provider="aws_aurora";engines=["postgres","mysql"]}class Pa extends Xr{provider="aws_elasticache";engines=["redis"]}class $a extends Xr{provider="server";engines=["postgres","mysql","mariadb","redis","mongodb","libsql"]}class va extends Xr{provider="container";engines=["postgres","mysql","mariadb","redis","mongodb","libsql"]}var Kc=(t,e)=>{let n=t.desiredState;return t[e]??(n&&typeof n==="object"&&!Array.isArray(n)?n[e]:void 0)},zt=(t,e,n)=>{let r=Kc(t,e);return r==null?n:String(r)},De=(t,e)=>{let n=Kc(t,e);return n==null?void 0:Number(n)},Xn=(t,e)=>{let n=Kc(t,e);return n==null?void 0:n===!0||n==="true"},Kr=(t,e)=>{let n=Kc(t,e);return Array.isArray(n)?n.map(String):[]},Xc=(t,e)=>zt(e,"snapshotId")??`${t}-final-${new Date().toISOString().replace(/[^0-9]/g,"").slice(0,14)}`;function Yc(t){if(!t)throw Error("RDS instance was not found.");return{providerId:t.DBInstanceIdentifier??null,status:t.DBInstanceStatus??"unknown",engine:t.Engine??null,engineVersion:t.EngineVersion??null,plan:t.DBInstanceClass??null,storageGb:t.AllocatedStorage??null,highAvailability:t.MultiAZ??!1,publicExposure:t.PubliclyAccessible??!1,endpoint:t.Endpoint?.Address??null,port:t.Endpoint?.Port??null,username:t.MasterUsername??null,database:t.DBName??null,encrypted:t.StorageEncrypted??!1}}class Ca{client;constructor(t=new Er){this.client=t}async observe(t){return Yc(await this.client.describeDBInstance(t))}async apply(t,e){let n=String(t.id),r=await this.client.createDBInstance({DBInstanceIdentifier:n,DBInstanceClass:String(t.plan),Engine:String(t.engine),MasterUsername:zt(t,"username","app"),MasterUserPassword:e,DBName:zt(t,"database"),AllocatedStorage:De(t,"storageGb"),VpcSecurityGroupIds:Kr(t,"securityGroupIds"),DBSubnetGroupName:zt(t,"subnetGroup"),BackupRetentionPeriod:De(t,"backupRetentionDays")??7,MultiAZ:Xn(t,"highAvailability"),EngineVersion:zt(t,"engineVersion"),PubliclyAccessible:Xn(t,"publicExposure")??!1,StorageType:zt(t,"storageType","gp3"),StorageEncrypted:!0,KmsKeyId:zt(t,"kmsKeyId"),DeletionProtection:!0,Tags:[{Key:"managed-by",Value:"ts-cloud"}]});return Yc(r.DBInstance)}async execute(t,e,n,r,i){if(e==="observe")return this.observe(t);if(e==="restart")return await this.client.rebootDBInstance({DBInstanceIdentifier:t}),{status:"rebooting"};if(e==="backup"){let c=Xc(t,n);return await this.client.createDBSnapshot({DBInstanceIdentifier:t,DBSnapshotIdentifier:c}),{status:"snapshotting",snapshotId:c}}if(e==="restore"){let c=String(n.targetId),d=await this.client.restoreDBInstanceFromDBSnapshot({DBInstanceIdentifier:c,DBSnapshotIdentifier:String(n.backupId),DBInstanceClass:zt(n,"plan"),DBSubnetGroupName:zt(n,"subnetGroup"),MultiAZ:Xn(n,"highAvailability"),PubliclyAccessible:!1,StorageType:zt(n,"storageType"),VpcSecurityGroupIds:Kr(n,"securityGroupIds"),DeletionProtection:!0,Tags:[{Key:"managed-by",Value:"ts-cloud"}]});return{...Yc(d.DBInstance),sourceId:t,restoreTargetId:c}}if(e==="delete"){if(n.retention==="retain")return{status:"retained"};let c=Xc(t,n);return await this.client.modifyDBInstance({DBInstanceIdentifier:t,DeletionProtection:!1,ApplyImmediately:!0}),await this.client.deleteDBInstance({DBInstanceIdentifier:t,SkipFinalSnapshot:!1,FinalDBSnapshotIdentifier:c,DeleteAutomatedBackups:!1}),{status:"deleting",finalSnapshotId:c}}if(["resize","version","rotate","expose"].includes(e)){let c=await this.client.modifyDBInstance({DBInstanceIdentifier:t,DBInstanceClass:zt(n,"plan"),AllocatedStorage:De(n,"storageGb"),MasterUserPassword:e==="rotate"?r:void 0,EngineVersion:zt(n,"engineVersion"),MultiAZ:Xn(n,"highAvailability"),PubliclyAccessible:Xn(n,"publicExposure"),VpcSecurityGroupIds:Kr(n,"securityGroupIds"),ApplyImmediately:Xn(n,"applyImmediately")??!0});return Yc(c.DBInstance)}throw Error(`RDS action ${e} requires an engine connection runner.`)}}function ka(t){if(!t)throw Error("Aurora cluster was not found.");return{providerId:t.DBClusterIdentifier??null,status:t.Status??"unknown",engine:t.Engine??null,engineVersion:t.EngineVersion??null,endpoint:t.Endpoint??null,readerEndpoint:t.ReaderEndpoint??null,port:t.Port??null,username:t.MasterUsername??null,database:t.DatabaseName??null,encrypted:t.StorageEncrypted??!1,highAvailability:t.MultiAZ??!0}}class Oa{client;constructor(t=new Er){this.client=t}async observe(t){let e=await this.client.describeDBClusters({DBClusterIdentifier:t});return ka(e.DBClusters?.[0])}async apply(t,e){let n=String(t.id),r=String(t.engine)==="postgres"?"aurora-postgresql":"aurora-mysql";return await this.client.createDBCluster({DBClusterIdentifier:n,Engine:r,EngineVersion:zt(t,"engineVersion"),MasterUsername:zt(t,"username","app"),MasterUserPassword:e,DatabaseName:zt(t,"database"),DBSubnetGroupName:zt(t,"subnetGroup"),VpcSecurityGroupIds:Kr(t,"securityGroupIds"),BackupRetentionPeriod:De(t,"backupRetentionDays")??7,StorageEncrypted:!0,KmsKeyId:zt(t,"kmsKeyId"),DeletionProtection:!0,ServerlessV2ScalingConfiguration:{MinCapacity:De(t,"minCapacity")??0.5,MaxCapacity:De(t,"maxCapacity")??4}}),await this.client.createDBInstance({DBInstanceIdentifier:`${n}-writer-1`,DBClusterIdentifier:n,DBInstanceClass:String(t.plan||"db.serverless"),Engine:r,PubliclyAccessible:Xn(t,"publicExposure")??!1}),{status:"creating",providerId:n}}async execute(t,e,n,r){if(e==="observe")return this.observe(t);if(e==="restart")return await this.client.rebootDBCluster(t),{status:"rebooting"};if(e==="backup"){let i=Xc(t,n);return await this.client.createDBClusterSnapshot(t,i),{status:"snapshotting",snapshotId:i}}if(e==="restore"){let i=String(n.targetId),c=String(n.engine)==="postgres"?"aurora-postgresql":"aurora-mysql",d=await this.client.restoreDBClusterFromSnapshot({DBClusterIdentifier:i,SnapshotIdentifier:String(n.backupId),Engine:c,EngineVersion:zt(n,"engineVersion"),DBSubnetGroupName:zt(n,"subnetGroup"),VpcSecurityGroupIds:Kr(n,"securityGroupIds"),DeletionProtection:!0,ServerlessV2ScalingConfiguration:{MinCapacity:De(n,"minCapacity")??0.5,MaxCapacity:De(n,"maxCapacity")??4}});return await this.client.createDBInstance({DBInstanceIdentifier:`${i}-writer-1`,DBClusterIdentifier:i,DBInstanceClass:zt(n,"plan","db.serverless"),Engine:c,PubliclyAccessible:!1}),{...ka(d.DBCluster),sourceId:t,restoreTargetId:i}}if(e==="delete"){if(n.retention==="retain")return{status:"retained"};let i=Xc(t,n);return await this.client.modifyDBCluster({DBClusterIdentifier:t,DeletionProtection:!1,ApplyImmediately:!0}),await this.client.deleteDBCluster(t,i),{status:"deleting",finalSnapshotId:i}}if(["resize","version","rotate"].includes(e)){let i=await this.client.modifyDBCluster({DBClusterIdentifier:t,ServerlessV2ScalingConfiguration:De(n,"minCapacity")==null&&De(n,"maxCapacity")==null?void 0:{MinCapacity:De(n,"minCapacity")??0.5,MaxCapacity:De(n,"maxCapacity")??4},EngineVersion:zt(n,"engineVersion"),MasterUserPassword:e==="rotate"?r:void 0,ApplyImmediately:Xn(n,"applyImmediately")??!0});return ka(i.DBCluster)}throw Error(`Aurora action ${e} requires an engine connection runner.`)}}class Ja{client;constructor(t=new Hi){this.client=t}async observe(t){let e=(await this.client.describeCacheClusters(t)).CacheClusters[0];if(!e)throw Error("ElastiCache cluster was not found.");let n=e.CacheNodes?.[0]?.Endpoint;return{providerId:e.CacheClusterId,status:e.CacheClusterStatus,engine:e.Engine,engineVersion:e.EngineVersion,plan:e.CacheNodeType,nodes:e.NumCacheNodes,endpoint:n?.Address??null,port:n?.Port??null}}async apply(t){let e=await this.client.createCacheCluster({cacheClusterId:String(t.id),engine:"redis",cacheNodeType:String(t.plan),numCacheNodes:De(t,"nodes")??1,engineVersion:zt(t,"engineVersion"),port:De(t,"port"),securityGroupIds:Kr(t,"securityGroupIds"),subnetGroupName:zt(t,"subnetGroup"),tags:[{Key:"managed-by",Value:"ts-cloud"}]});return{providerId:e.CacheCluster.CacheClusterId,status:e.CacheCluster.CacheClusterStatus}}async execute(t,e,n){if(e==="observe")return this.observe(t);if(e==="restart"){let r=(await this.client.describeCacheClusters(t)).CacheClusters[0];return await this.client.rebootCacheCluster(t,r?.CacheNodes?.map((i)=>i.CacheNodeId)??["0001"]),{status:"rebooting"}}if(e==="delete"){if(n.retention==="retain")return{status:"retained"};return await this.client.deleteCacheCluster(t),{status:"deleting"}}throw Error(`ElastiCache action ${e} is not supported by this cluster mode.`)}}import{mkdir as nw,writeFile as rw}from"node:fs/promises";import{join as iw}from"node:path";async function ve(t,e,n=!1){let r=Bun.spawn(["docker",...t],{stdin:e==null?"ignore":"pipe",stdout:"pipe",stderr:"pipe"}),i=new Response(r.stdout).text(),c=new Response(r.stderr).text();if(e!=null)r.stdin.write(e),r.stdin.end();let[d,a,l]=await Promise.all([r.exited,i,c]);if(d!==0&&!n)throw Error(`Docker command failed (${d}): ${l.trim()||a.trim()}`);return{code:d,stdout:a,stderr:l}}class Vu{async ensureNetwork(t){if((await ve(["network","inspect",t],void 0,!0)).code!==0)await ve(["network","create","--internal",t])}async seedSecret(t,e){await ve(["volume","create",t]),await ve(["run","--rm","-i","-v",`${t}:/run/target`,"alpine:3.21","sh","-c","umask 077; cat > /run/target/credential"],e)}async removeVolume(t){await ve(["volume","rm",t],void 0,!0)}async inspect(t){let e=await ve(["inspect",t],void 0,!0);if(e.code!==0)return;return JSON.parse(e.stdout)[0]}async run(t){await ve(["run",...t])}async exec(t,e,n){return(await ve(["exec","-i",t,...e],n)).stdout}async update(t,e){await ve(["update",...e,t])}async restart(t){await ve(["restart",t])}async remove(t){await ve(["rm","--force",t],void 0,!0)}async logs(t,e){let n=await ve(["logs","--tail",String(Math.min(2000,Math.max(1,e))),t],void 0,!0);return`${n.stdout}${n.stderr}`.slice(-262144)}async stats(t){let e=await ve(["stats","--no-stream","--format","{{json .}}",t],void 0,!0);if(e.code!==0||!e.stdout.trim())return{};let n=JSON.parse(e.stdout.trim());return{cpuPercent:String(n.CPUPerc??""),memoryUsage:String(n.MemUsage??""),memoryPercent:String(n.MemPerc??""),networkIo:String(n.NetIO??""),blockIo:String(n.BlockIO??""),pids:Number(n.PIDs??0)}}}var cw={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 Rn(t,e="app"){let n=String(t??e);if(!/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(n))throw Error("Database identifiers must be letters, numbers, or underscores.");return n}function Ir(t){if(!/^[a-z0-9][a-z0-9_.-]{1,62}$/i.test(t))throw Error("Runtime placement must be a valid container identifier.");return`tscloud-data-${t.toLowerCase()}`}function dw(t,e){let n=t.desiredState;return t[e]??(n&&typeof n==="object"&&!Array.isArray(n)?n[e]:void 0)}function Fi(t){return t.Config?.Labels??{}}class pr{runtime;backupRoot;constructor(t=new Vu,e=de(process.cwd(),"backups","data")){this.runtime=t;this.backupRoot=e}async observe(t){let e=Ir(t),n=await this.runtime.inspect(e);if(!n)throw Error(`Data container ${e} was not found.`);let r=Fi(n),i=await this.runtime.stats(e),c=n.NetworkSettings?.Ports??{},d=Object.values(c).flat().find(Boolean);return{providerId:e,status:n.State?.Status??"unknown",healthy:n.State?.Health?.Status??null,engine:r["ts-cloud.engine"]??null,engineVersion:r["ts-cloud.engine-version"]??null,username:r["ts-cloud.username"]??null,database:r["ts-cloud.database"]??null,endpoint:d?.HostIp||"127.0.0.1",port:d?.HostPort?Number(d.HostPort):null,image:n.Config?.Image??null,startedAt:n.State?.StartedAt??null,metrics:i}}async apply(t,e){let n=String(t.id),r=Ir(n),i=String(t.engine);if(i==="libsql")throw Error("libSQL requires an explicitly configured runtime image.");let c=cw[i];if(!c)throw Error(`Unsupported runtime data engine ${i}.`);if(!e)throw Error(`${i} requires a managed credential.`);if(t.publicExposure===!0)throw Error("Container public exposure requires an external reviewed firewall policy; direct publishing is refused.");let d=Rn(t.username),a=Rn(dw(t,"database")),l=`${r}-secret`,o=`${r}-data`,u=i==="redis"?`appendonly yes
|
|
46
|
-
protected-mode yes
|
|
47
|
-
requirepass ${e.replaceAll("\\","\\\\").replaceAll(`
|
|
48
|
-
`,"")}
|
|
49
|
-
`:e;await this.runtime.ensureNetwork("ts-cloud-data"),await this.runtime.seedSecret(l,u);let f=["-d","--name",r,"--restart","unless-stopped","--network","ts-cloud-data","--label","managed-by=ts-cloud","--label",`ts-cloud.engine=${i}`,"--label",`ts-cloud.engine-version=${t.engineVersion??""}`,"--label",`ts-cloud.username=${d}`,"--label",`ts-cloud.database=${a}`,"-p",`127.0.0.1:${c.port}:${c.port}`,"-v",`${o}:${c.dataPath}`,"-v",`${l}:/run/ts-cloud-secrets:ro`];if(i==="postgres")f.push("-e",`POSTGRES_USER=${d}`,"-e",`POSTGRES_DB=${a}`,"-e","POSTGRES_PASSWORD_FILE=/run/ts-cloud-secrets/credential");if(i==="mysql"||i==="mariadb")f.push("-e",`MYSQL_USER=${d}`,"-e",`MYSQL_DATABASE=${a}`,"-e","MYSQL_PASSWORD_FILE=/run/ts-cloud-secrets/credential","-e","MYSQL_ROOT_PASSWORD_FILE=/run/ts-cloud-secrets/credential");if(i==="mongodb")f.push("-e",`MONGO_INITDB_ROOT_USERNAME=${d}`,"-e","MONGO_INITDB_ROOT_PASSWORD_FILE=/run/ts-cloud-secrets/credential");if(f.push(c.image),i==="redis")f.push("redis-server","/run/ts-cloud-secrets/credential");return await this.runtime.run(f),{providerId:r,status:"starting",engine:i,endpoint:"127.0.0.1",port:c.port,username:d,database:a}}async exportLogicalBackup(t){let e=Ir(t),n=await this.runtime.inspect(e);if(!n)throw Error(`Data container ${e} was not found.`);let r=Fi(n),i=r["ts-cloud.engine"],c=Rn(r["ts-cloud.username"]),d=Rn(r["ts-cloud.database"]),a;if(i==="postgres")a=await this.runtime.exec(e,["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")a=await this.runtime.exec(e,["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(a),engine:i,database:d,username:c,engineVersion:r["ts-cloud.engine-version"]||void 0}}async restoreLogicalBackup(t){let e=Ir(t.sourceId),n=Ir(t.targetId),r=await this.runtime.inspect(e);if(!r)throw Error(`Data container ${e} was not found.`);let i=Fi(r),c=i["ts-cloud.engine"],d=Rn(i["ts-cloud.username"]),a=Rn(i["ts-cloud.database"]);if(!["postgres","mysql","mariadb"].includes(c))throw Error(`${c} does not support engine-native SQL restores.`);if(!t.inPlace){if(t.sourceId===t.targetId)throw Error("An isolated restore requires a distinct target identifier.");if(await this.runtime.inspect(n))throw Error(`Restore target ${n} already exists.`);await this.apply({id:t.targetId,engine:c,engineVersion:i["ts-cloud.engine-version"]??"",username:d,database:a,publicExposure:!1},t.credential)}let l=c==="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(t.body),u;for(let f=0;f<30;f++)try{await this.runtime.exec(n,l,o);let R=c==="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(n,R)).trim()!=="1")throw Error("Restored database health probe returned an unexpected result.");return{status:"available",providerId:n,engine:c,database:a,username:d,healthy:!0}}catch(R){if(u=R,f<29)await Bun.sleep(1000)}throw u instanceof Error?u:Error("Restored database did not become ready.")}async removeRestoredService(t){let e=Ir(t);await this.runtime.remove(e),await this.runtime.removeVolume(`${e}-secret`),await this.runtime.removeVolume(`${e}-data`)}async backup(t,e){let n=await this.exportLogicalBackup(t),{engine:r,database:i,username:c}=n,d=String(e.snapshotId??`${t}-${new Date().toISOString().replace(/[^0-9]/g,"").slice(0,14)}`);if(!/^[A-Za-z0-9_.-]{2,120}$/.test(d))throw Error("Backup identifier contains unsupported characters.");await nw(this.backupRoot,{recursive:!0,mode:448});let a=iw(this.backupRoot,`${d}.sql`);return await rw(a,n.body,{mode:384}),{status:"available",backupId:d,path:a,engine:r,database:i,username:c}}async execute(t,e,n,r){let i=Ir(t);if(e==="observe")return this.observe(t);if(e==="backup")return this.backup(t,n);if(e==="restart")return await this.runtime.restart(i),{status:"restarting"};if(e==="logs"||e==="slow_queries")return{logs:await this.runtime.logs(i,Number(n.lines)||500)};if(e==="databases"||e==="users"){let c=await this.runtime.inspect(i);if(!c)throw Error(`Data container ${i} was not found.`);let d=Fi(c),a=d["ts-cloud.engine"],l=Rn(d["ts-cloud.username"]),o=String(n.operation??"list");if(!["postgres","mysql","mariadb"].includes(a))throw Error(`${e} is available only for SQL runtime engines.`);if(e==="users"&&o!=="list")throw Error("Creating users requires a referenced secondary credential.");if(o==="list"){let u=a==="postgres"?["sh","-c",`export PGPASSWORD="$(cat /run/ts-cloud-secrets/credential)"; exec psql -U "$POSTGRES_USER" -Atc '${e==="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 '${e==="databases"?"SHOW DATABASES":"SELECT User FROM mysql.user ORDER BY User"}'`],f=await this.runtime.exec(i,u);return{[e]:f.split(`
|
|
50
|
-
`).map((R)=>R.trim()).filter(Boolean)}}if(e==="databases"&&["create","delete"].includes(o)){let u=Rn(n.database);if(o==="delete"&&n.confirm!==u)throw Error(`Type ${u} to confirm logical database deletion.`);let f=a==="postgres"?`${o==="create"?"CREATE":"DROP"} DATABASE "${u}";
|
|
51
|
-
`:`${o==="create"?"CREATE":"DROP"} DATABASE \`${u}\`;
|
|
52
|
-
`,R=a==="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,R,f),{status:"available",database:u,operation:o}}throw Error(`Unsupported ${e} operation ${o}.`)}if(e==="resize"){let c=[];if(n.memoryMb)c.push("--memory",`${Number(n.memoryMb)}m`);if(n.cpus)c.push("--cpus",String(Number(n.cpus)));if(!c.length)throw Error("Resize requires memoryMb or cpus.");return await this.runtime.update(i,c),{status:"running",memoryMb:n.memoryMb??null,cpus:n.cpus??null}}if(e==="rotate"){if(!r)throw Error("Credential rotation requires a generated secret.");let c=await this.runtime.inspect(i);if(!c)throw Error(`Data container ${i} was not found.`);let d=Fi(c),a=d["ts-cloud.engine"],l=Rn(d["ts-cloud.username"]),o=r.replaceAll("'","''").replaceAll(`
|
|
53
|
-
`,"");if(a==="postgres")await this.runtime.exec(i,["sh","-c",'export PGPASSWORD="$(cat /run/ts-cloud-secrets/credential)"; exec psql -U "$POSTGRES_USER"'],`ALTER USER "${l}" PASSWORD '${o}';
|
|
54
|
-
`);else if(a==="mysql"||a==="mariadb")await this.runtime.exec(i,["sh","-c",'export MYSQL_PWD="$(cat /run/ts-cloud-secrets/credential)"; exec mysql -u root'],`ALTER USER '${l}'@'%' IDENTIFIED BY '${o}';
|
|
55
|
-
`);else if(a!=="redis")throw Error(`${a} credential rotation requires an engine runner.`);let u=a==="redis"?`appendonly yes
|
|
56
|
-
protected-mode yes
|
|
57
|
-
requirepass ${r.replaceAll("\\","\\\\").replaceAll(`
|
|
58
|
-
`,"")}
|
|
59
|
-
`:r;if(await this.runtime.seedSecret(`${i}-secret`,u),a==="redis")await this.runtime.restart(i);return{status:a==="redis"?"restarting":"running",username:l}}if(e==="delete"){if(n.retention==="retain")return{status:"retained"};let c=await this.backup(t,n);return await this.runtime.remove(i),await this.runtime.removeVolume(`${i}-secret`),await this.runtime.removeVolume(`${i}-data`),{status:"deleted",finalBackupId:c.backupId??null,backupPath:c.path??null}}if(e==="expose")throw Error("Direct container exposure is refused; use a reviewed firewall and proxy policy.");throw Error(`${e} requires a configured engine lifecycle runner.`)}}import{createCipheriv as ow,createDecipheriv as aw,createHash as Nu,randomBytes as sw}from"node:crypto";class Ba{controlPlane;now;key;constructor(t,e,n=()=>new Date){this.controlPlane=t;this.now=n;if(!e)throw Error("Data-service encryption key is required.");this.key=Nu("sha256").update(`ts-cloud:data-services:${e}`).digest()}encrypt(t){let e=sw(12),n=ow("aes-256-gcm",this.key,e),r=Buffer.concat([n.update(t,"utf8"),n.final()]);return`v1.${e.toString("base64url")}.${n.getAuthTag().toString("base64url")}.${r.toString("base64url")}`}decrypt(t){let[e,n,r,i]=t.split(".");if(e!=="v1"||!n||!r||!i)throw Error("Encrypted data-service secret is unavailable.");try{let c=aw("aes-256-gcm",this.key,Buffer.from(n,"base64url"));return c.setAuthTag(Buffer.from(r,"base64url")),Buffer.concat([c.update(Buffer.from(i,"base64url")),c.final()]).toString("utf8")}catch{throw Error("Encrypted data-service secret could not be decrypted.")}}async put(t,e){if(!/^secret:\/\/data-services\/[A-Za-z0-9._/-]+$/.test(t))throw Error("Invalid data-service secret reference.");if(!e)throw Error("Data-service secret cannot be empty.");let n=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",[t,this.encrypt(e),Nu("sha256").update(e).digest("hex"),n,n])}async resolve(t){let e=this.controlPlane.database.query("SELECT ciphertext FROM data_service_secrets WHERE reference = ?").get(t);if(!e)throw Error("Data-service secret was not found.");return this.decrypt(e.ciphertext)}async remove(t){this.controlPlane.database.run("DELETE FROM data_service_secrets WHERE reference = ?",[t])}}import{existsSync as Vi}from"node:fs";import{mkdir as mc,readdir as lw,rename as za,rm as mr}from"node:fs/promises";import{relative as gw,resolve as fe,sep as qc}from"node:path";function wr(t,e){if(e==="gzip")return Buffer.from(Bun.gzipSync(Uint8Array.from(t)));if(e==="zstd")return Buffer.from(Bun.zstdCompressSync(Uint8Array.from(t)));return Buffer.from(t)}function En(t,e){if(e==="gzip")return Buffer.from(Bun.gunzipSync(Uint8Array.from(t)));if(e==="zstd")return Buffer.from(Bun.zstdDecompressSync(Uint8Array.from(t)));return Buffer.from(t)}async function Ta(t,e){let n=Bun.spawn(["tar",...t],{stdin:e?Buffer.from(e):void 0,stdout:"pipe",stderr:"pipe"}),[r,i,c]=await Promise.all([n.exited,new Response(n.stdout).arrayBuffer(),new Response(n.stderr).text()]);if(r!==0)throw Error(c.trim()||`tar exited with status ${r}.`);return{stdout:Buffer.from(i),stderr:c}}function uw(t){let e=t.replaceAll("\\","/").replace(/^\.\//,"");return!!e&&!e.startsWith("/")&&!e.split("/").includes("..")}class Mu{async create(t,e,n){return(await Ta(["-C",t,"-cf","-",...n.map((i)=>`--exclude=${i}`),"--",...e])).stdout}async extract(t,e){await mc(e,{recursive:!0,mode:448}),await Ta(["-C",e,"-xf","-"],t)}async inspect(t){let e=await Ta(["-tf","-"],t),n=e.stdout.toString().split(`
|
|
60
|
-
`).filter(Boolean);if(n.some((r)=>!uw(r)))throw Error("Backup archive contains an unsafe path.");return{entries:n,bytes:t.byteLength}}}function xu(t,e){if(!e.trim())throw Error("File backup paths cannot be empty.");let n=fe(t,e),r=gw(t,n);if(r===".."||r.startsWith(`..${qc}`)||r==="")throw Error(`File backup path ${e} is outside the project root.`);return r}function pc(t){let e=String(t.targetId??t.path??"");if(!/^[A-Za-z0-9][A-Za-z0-9_.-]{1,127}$/.test(e))throw Error("File restores require a safe target name.");return e}class ba{runtime;root;restoreRoot;constructor(t,e=new Mu,n=de(t,"restores","files")){this.runtime=e;this.root=fe(t),this.restoreRoot=fe(n)}paths(t){let e=[...new Set(t.includePatterns.map((n)=>xu(this.root,n)))];if(!e.length)throw Error("File backup policies require at least one project-relative path.");for(let n of e)if(!Vi(fe(this.root,n)))throw Error(`File backup path ${n} was not found.`);return e.filter((n)=>!e.some((r)=>r!==n&&n.startsWith(`${r}${qc}`)))}async create(t,e){let n=this.paths(t),r=await this.runtime.create(this.root,n,t.excludePatterns),i=await this.runtime.inspect(r),c=t.compression??"none",d=wr(r,c),a=String(e.operation?.id??new Date().toISOString()).replace(/[^A-Za-z0-9]/g,"").slice(0,32);return{mode:"object",key:`${t.projectId}/files/${a}.tar${c==="none"?"":c==="gzip"?".gz":".zst"}`,body:d,contentType:c==="gzip"?"application/gzip":c==="zstd"?"application/zstd":"application/x-tar",manifest:{archive:"tar",compression:c,sourcePaths:n,excluded:t.excludePatterns,entries:i.entries.length},toolVersion:"system-tar"}}async restore(t,e,n,r){if(!e)throw Error("File restore requires an archive payload.");let i=En(e,String(t.manifest.compression??"none"));if(await this.runtime.inspect(i),n.restoreMode==="in_place"){let d=fe(this.restoreRoot,`.staging-${pc(n)}`),a=fe(this.restoreRoot,`.rollback-${pc(n)}`),l=Array.isArray(t.manifest.sourcePaths)?t.manifest.sourcePaths.map(String):[];if(!l.length)throw Error("File recovery point has no source path manifest.");await mr(d,{recursive:!0,force:!0}),await mr(a,{recursive:!0,force:!0}),await this.runtime.extract(i,d),await mc(a,{recursive:!0,mode:448});let o=[];try{for(let u of l){let f=fe(this.root,xu(this.root,u)),R=fe(d,u),E=fe(a,u);if(await mc(fe(E,".."),{recursive:!0}),Vi(f))await za(f,E);await mc(fe(f,".."),{recursive:!0}),await za(R,f),o.push(u)}}catch(u){for(let f of o.reverse()){let R=fe(this.root,f),E=fe(a,f);if(await mr(R,{recursive:!0,force:!0}),Vi(E))await za(E,R)}throw u}finally{await mr(d,{recursive:!0,force:!0})}return await mr(a,{recursive:!0,force:!0}),{path:this.root,restoredPaths:l,inPlace:!0}}let c=fe(this.restoreRoot,pc(n));if(Vi(c))throw Error("The isolated file restore target already exists.");return await this.runtime.extract(i,c),{path:c,isolated:!0}}async verify(t,e,n){let r=En(e,String(t.manifest.compression??"none")),i=await this.runtime.inspect(r);return{archive:"tar",entries:i.entries.length,uncompressedBytes:i.bytes}}async validateHealth(t,e){let n=String(t.path??"");if(!n||!n.startsWith(`${this.restoreRoot}${qc}`)||!Vi(n))throw Error("Isolated file restore target was not found.");let r=await lw(n);return{healthy:!0,path:n,topLevelEntries:r.length}}async cleanup(t,e){let n=pc(t),r=fe(this.restoreRoot,n);if(!r.startsWith(`${this.restoreRoot}${qc}`))throw Error("Refusing to clean a file restore outside the restore root.");await mr(r,{recursive:!0,force:!0})}}class Wa{services;secrets;transport;constructor(t,e,n=new pr){this.services=t;this.secrets=e;this.transport=n}async create(t,e){if(!t.dataServiceId)throw Error("Logical database backups require a data service.");let n=this.services.get(t.dataServiceId);if(!n)throw Error("Logical database service was not found.");if(!["container","server"].includes(n.provider))throw Error("Logical database backups require an on-box data service.");let r=await this.transport.exportLogicalBackup(n.id),i=t.compression??"none",c=wr(r.body,i),d=String(e.operation?.id??new Date().toISOString()).replace(/[^A-Za-z0-9]/g,"").slice(0,32);return{mode:"object",key:`${t.projectId}/databases/${n.id}/${d}.sql${i==="none"?"":i==="gzip"?".gz":".zst"}`,body:c,contentType:i==="gzip"?"application/gzip":i==="zstd"?"application/zstd":"application/sql",engineVersion:r.engineVersion,toolVersion:"engine-native",manifest:{format:"logical-sql-v1",sourceDataServiceId:n.id,engine:r.engine,database:r.database,username:r.username,compression:i}}}async restore(t,e,n,r){if(!e)throw Error("Logical database backup body is unavailable.");let i=String(t.dataServiceId??t.manifest.sourceDataServiceId??""),c=String(n.dataServiceId??n.targetId??""),d=n.inPlace===!0;if(!i||!c)throw Error("Logical database restore requires source and target identifiers.");if(d&&c!==i)throw Error("An in-place restore must target the source data service.");let a=this.services.get(i);if(!a?.credentialRef)throw Error("Logical database credential reference was not found.");let l=await this.secrets.resolve(a.credentialRef);return this.transport.restoreLogicalBackup({sourceId:i,targetId:c,body:En(e,String(t.manifest.compression??"none")),credential:l,inPlace:d})}async cleanup(t,e){if(t.inPlace===!0)throw Error("In-place database restores cannot be cleaned as drills.");let n=String(t.dataServiceId??t.targetId??"");if(!n)throw Error("Database cleanup requires a target identifier.");await this.transport.removeRestoredService(n)}}var Ua=/^[A-Za-z0-9][A-Za-z0-9_.-]{1,127}$/;async function Ar(t,e,n=!1){let r=Bun.spawn(["docker",...t],{stdin:e?"pipe":"ignore",stdout:"pipe",stderr:"pipe"}),i=new Response(r.stdout).arrayBuffer(),c=new Response(r.stderr).text();if(e)r.stdin.write(e),r.stdin.end();let[d,a,l]=await Promise.all([r.exited,i,c]);if(d!==0&&!n)throw Error(`Docker volume command failed (${d}): ${l.trim()}`);return{code:d,stdout:Buffer.from(a),stderr:l}}class Qu{async exists(t){return(await Ar(["volume","inspect",t],void 0,!0)).code===0}async export(t){return(await Ar(["run","--rm","-v",`${t}:/source:ro`,"alpine:3.21","tar","-C","/source","-czf","-","."])).stdout}async import(t,e,n=!1){if(!await this.exists(t))await Ar(["volume","create",t]);try{if(n)await Ar(["run","--rm","-v",`${t}:/target`,"alpine:3.21","sh","-c","find /target -mindepth 1 -delete"]);await Ar(["run","--rm","-i","-v",`${t}:/target`,"alpine:3.21","tar","-C","/target","--no-same-owner","-xzf","-"],e)}catch(r){throw await this.remove(t),r}}async remove(t){await Ar(["volume","rm",t],void 0,!0)}async probe(t){let e=(await Ar(["run","--rm","-v",`${t}:/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(),[n,r]=e.trim().split(":").map(Number);if(!Number.isFinite(n)||!Number.isFinite(r))throw Error("Restored volume health probe returned invalid output.");return{entries:n,bytes:r}}}class ja{runtime;constructor(t=new Qu){this.runtime=t}async create(t,e){let n=String(t.includePatterns?.[0]??t.resourceId??"");if(!Ua.test(n))throw Error("Volume backups require a valid named-volume resource identifier.");if(!await this.runtime.exists(n))throw Error(`Volume ${n} was not found.`);let r=await this.runtime.export(n),i=Buffer.from(Bun.gunzipSync(Uint8Array.from(r))),c=t.compression??"gzip",d=c==="gzip"?r:wr(i,c),a=String(e.operation?.id??new Date().toISOString()).replace(/[^A-Za-z0-9]/g,"").slice(0,32);return{mode:"object",key:`${t.projectId}/volumes/${n}/${a}.tar${c==="none"?"":c==="gzip"?".gz":".zst"}`,body:d,contentType:c==="gzip"?"application/gzip":c==="zstd"?"application/zstd":"application/x-tar",toolVersion:"alpine-tar",manifest:{format:"docker-volume-tar-v1",archive:"tar",compression:c,sourceVolume:n}}}async restore(t,e,n,r){if(!e)throw Error("Volume backup body is unavailable.");let i=String(t.manifest.sourceVolume??t.resourceId??""),c=String(n.volumeName??n.targetId??"");if(!Ua.test(c))throw Error("Volume restore requires a valid target volume name.");if(c===i&&n.inPlace!==!0)throw Error("An isolated volume restore requires a distinct target.");let d=await this.runtime.exists(c);if(!n.inPlace&&d)throw Error(`Restore target volume ${c} already exists.`);if(n.inPlace===!0&&c!==i)throw Error("An in-place volume restore must target the source volume.");if(n.inPlace===!0&&!d)throw Error("The in-place target volume was not found.");let a=String(t.manifest.compression??"gzip"),l=a==="gzip"?Buffer.from(e):Buffer.from(Bun.gzipSync(Uint8Array.from(En(e,a))));await this.runtime.import(c,l,n.inPlace===!0);let o=await this.runtime.probe(c);return{volumeName:c,healthy:!0,...o}}async cleanup(t,e){if(t.inPlace===!0)throw Error("In-place volume restores cannot be cleaned as drills.");let n=String(t.volumeName??t.targetId??"");if(!Ua.test(n))throw Error("Volume cleanup requires a valid target volume name.");await this.runtime.remove(n)}}import{existsSync as Ha}from"node:fs";import{mkdir as hw,readFile as Gu,rm as Sw,writeFile as Zu}from"node:fs/promises";import{basename as mu,resolve as Kn,sep as Yu}from"node:path";import{Database as fw}from"bun:sqlite";function Xu(t){let e=String(t.targetId??t.path??"");if(!/^[A-Za-z0-9][A-Za-z0-9_.-]{1,127}$/.test(e))throw Error("Control-plane restores require a safe target name.");return e}function Ku(t){let e=JSON.parse(Buffer.from(t).toString());if(e.format!=="ts-cloud-control-plane-v1"||!e.database)throw Error("Control-plane backup archive is invalid.");if(!Array.isArray(e.config)||e.config.some((n)=>mu(n.name)!==n.name))throw Error("Control-plane backup contains an unsafe config path.");return e}function pu(t){let e=fw.deserialize(Uint8Array.from(t));try{let n=e.query("PRAGMA integrity_check").get()?.integrity_check??"unknown",r=e.query("SELECT count(*) AS count FROM sqlite_master WHERE type='table'").get()?.count??0;if(n!=="ok")throw Error(`Restored control-plane integrity check failed: ${n}.`);return{integrity:n,tables:r}}finally{e.close()}}class La{controlPlane;root;restoreRoot;constructor(t,e,n=de(e,"restores","control-plane")){this.controlPlane=t;this.root=Kn(e),this.restoreRoot=Kn(n)}async create(t,e){let n=t.includePatterns.length?t.includePatterns:["cloud.config.ts"],r=[];for(let l of n){let o=mu(l),u=Kn(this.root,o);if(o!==l&&l!==`./${o}`)throw Error("Control-plane config paths must be project-root files.");if(Ha(u))r.push({name:o,body:(await Gu(u)).toString("base64")})}let i={format:"ts-cloud-control-plane-v1",createdAt:new Date().toISOString(),database:Buffer.from(this.controlPlane.database.serialize()).toString("base64"),config:r},c=t.compression??"none",d=wr(Buffer.from(JSON.stringify(i)),c),a=String(e.operation?.id??i.createdAt).replace(/[^A-Za-z0-9]/g,"").slice(0,32);return{mode:"object",key:`${t.projectId}/control-plane/${a}.json${c==="none"?"":c==="gzip"?".gz":".zst"}`,body:d,contentType:c==="gzip"?"application/gzip":c==="zstd"?"application/zstd":"application/vnd.ts-cloud.control-plane+json",manifest:{format:i.format,configFiles:r.map((l)=>l.name),sensitive:!0,compression:c},toolVersion:"bun-sqlite-serialize"}}async restore(t,e,n,r){if(!e)throw Error("Control-plane restore requires an archive payload.");if(n.restoreMode==="in_place")throw Error("A live control plane can only be restored into an isolated recovery target.");let i=Ku(En(e,String(t.manifest.compression??"none"))),c=Kn(this.restoreRoot,Xu(n));if(Ha(c))throw Error("The isolated control-plane restore target already exists.");await hw(c,{recursive:!0,mode:448}),await Zu(Kn(c,"control-plane.sqlite"),Buffer.from(i.database,"base64"),{mode:384});for(let d of i.config)await Zu(Kn(c,d.name),Buffer.from(d.body,"base64"),{mode:384});return{path:c,isolated:!0,configFiles:i.config.length}}async verify(t,e,n){let r=Ku(En(e,String(t.manifest.compression??"none")));return{...pu(Buffer.from(r.database,"base64")),configFiles:r.config.length}}async validateHealth(t,e){let n=String(t.path??""),r=Kn(n,"control-plane.sqlite");if(!n.startsWith(`${this.restoreRoot}${Yu}`)||!Ha(r))throw Error("Isolated control-plane database was not found.");return{healthy:!0,...pu(await Gu(r))}}async cleanup(t,e){let n=Kn(this.restoreRoot,Xu(t));if(!n.startsWith(`${this.restoreRoot}${Yu}`))throw Error("Refusing to clean a control-plane restore outside the restore root.");await Sw(n,{recursive:!0,force:!0})}}import{createHash as _w}from"node:crypto";function Fa(t,e){return t.find((n)=>n.startsWith(`${e}:`))?.slice(e.length+1)}function Rw(t){let e=Fa(t.includePatterns,"resource")??t.includePatterns.find((i)=>i.startsWith("arn:")),n=Fa(t.includePatterns,"role"),r=Fa(t.includePatterns,"vault")??"Default";if(!e?.startsWith("arn:"))throw Error("Infrastructure backups require resource:<arn> in include patterns.");if(!n?.startsWith("arn:"))throw Error("Infrastructure backups require role:<iam-role-arn> in include patterns.");if(!/^[A-Za-z0-9_.-]{2,50}$/.test(r))throw Error("Infrastructure backup vault name is invalid.");return{resourceArn:e,roleArn:n,vaultName:r}}async function Ew(t,e,n){for(;;){n.throwIfCancellationRequested(),n.heartbeat();let r=await t.describeBackupJob(e),i=String(r.State??"");if(n.checkpoint("provider_backup",`AWS Backup job ${e} is ${i||"pending"}.`),i==="COMPLETED"&&r.RecoveryPointArn)return{recoveryPointArn:r.RecoveryPointArn,sizeBytes:Number(r.BackupSizeInBytes??0)};if(["ABORTED","EXPIRED","FAILED"].includes(i))throw Error(`AWS Backup job ${e} failed: ${r.StatusMessage??i}.`);await Bun.sleep(5000)}}async function Iw(t,e,n){for(;;){n.throwIfCancellationRequested(),n.heartbeat();let r=await t.describeRestoreJob(e),i=String(r.Status??"");if(n.checkpoint("provider_restore",`AWS Backup restore ${e} is ${i||"pending"}.`),i==="COMPLETED"&&r.CreatedResourceArn)return r.CreatedResourceArn;if(["ABORTED","FAILED"].includes(i))throw Error(`AWS Backup restore ${e} failed: ${r.StatusMessage??i}.`);await Bun.sleep(5000)}}class Va{client;constructor(t=new ji){this.client=t}async create(t,e){let n=Rw(t),r=String(e.operation.id).replace(/[^A-Za-z0-9-]/g,"").slice(0,64),i=await this.client.startBackupJob({BackupVaultName:n.vaultName,ResourceArn:n.resourceArn,IamRoleArn:n.roleArn,IdempotencyToken:r}),c=await Ew(this.client,i.BackupJobId,e),d=`sha256:${_w("sha256").update(c.recoveryPointArn).digest("hex")}`;return{mode:"external",uri:c.recoveryPointArn,checksum:d,sizeBytes:c.sizeBytes,toolVersion:"aws-backup-api",manifest:{provider:"aws_backup",resourceArn:n.resourceArn,roleArn:n.roleArn,vaultName:n.vaultName,providerBackupJobId:i.BackupJobId,recoveryPointArn:c.recoveryPointArn}}}async verifyExternal(t,e){let n=String(t.manifest.providerBackupJobId??""),r=await this.client.describeBackupJob(n);if(r.State!=="COMPLETED"||r.RecoveryPointArn!==t.uri)throw Error(`AWS Backup recovery point verification failed: ${r.StatusMessage??r.State??"unknown"}.`);return{state:r.State,recoveryPointArn:r.RecoveryPointArn,sizeBytes:Number(r.BackupSizeInBytes??t.sizeBytes)}}async restore(t,e,n,r){if(n.inPlace===!0)throw Error("AWS Backup infrastructure restores must create isolated resources.");let i=String(n.roleArn??t.manifest.roleArn??""),c=n.metadata&&typeof n.metadata==="object"&&!Array.isArray(n.metadata)?Object.fromEntries(Object.entries(n.metadata).map(([l,o])=>[l,String(o)])):{};if(!i.startsWith("arn:"))throw Error("AWS Backup restore requires an IAM role ARN.");if(!Object.keys(c).length)throw Error("AWS Backup restore requires provider restore metadata.");let d=await this.client.startRestoreJob({RecoveryPointArn:t.uri,IamRoleArn:i,Metadata:c,IdempotencyToken:String(r.operation.id).replace(/[^A-Za-z0-9-]/g,"").slice(0,64)}),a=await Iw(this.client,d.RestoreJobId,r);return{providerRestoreJobId:d.RestoreJobId,createdResourceArn:a,isolated:!0,healthy:!0}}async validateHealth(t,e){let n=String(t.createdResourceArn??"");return{healthy:n.startsWith("arn:"),createdResourceArn:n}}async deleteExternal(t,e){await this.client.deleteRecoveryPoint(String(t.manifest.vaultName??""),t.uri)}}import{existsSync as C0}from"node:fs";import{join as DS}from"node:path";import{pathToFileURL as O0}from"node:url";import{existsSync as qu,statSync as th}from"fs";import{existsSync as ww,mkdirSync as rO,readdirSync as iO,readFileSync as Aw,writeFileSync as cO}from"fs";import{homedir as qr}from"os";import{dirname as aO,resolve as Te}from"path";import Td from"process";import{existsSync as eh,statSync as nh}from"fs";import{existsSync as as,mkdirSync as Dw,readdirSync as yw,writeFileSync as Pw}from"fs";import{homedir as ti}from"os";import{dirname as rh,resolve as Re}from"path";import Dr from"process";import{join as $w,relative as vw,resolve as ih}from"path";import wd from"process";import{existsSync as Vh,mkdirSync as EO,readdirSync as IO,writeFileSync as wO}from"fs";import{homedir as Na}from"os";import{dirname as yO,resolve as _e}from"path";import xi from"process";import{join as kw,relative as Cw,resolve as ch}from"path";import Ad from"process";import{existsSync as Nh,mkdirSync as CO,readdirSync as OO,writeFileSync as JO}from"fs";import{dirname as zO,resolve as Dd}from"path";import ss from"process";import{Buffer as pn}from"buffer";import{createCipheriv as Ow,createDecipheriv as Jw,randomBytes as xa}from"crypto";import{closeSync as Ma,createReadStream as dh,createWriteStream as Bw,existsSync as Qa,fsyncSync as oh,openSync as ah,writeFileSync as zw}from"fs";import{access as Tw,constants as sh,mkdir as bw,readdir as td,rename as lh,stat as ei,unlink as ed,writeFile as Ga}from"fs/promises";import{join as ni}from"path";import qt from"process";import{pipeline as Ww}from"stream/promises";import{createGzip as gh}from"zlib";import ri from"process";import An from"process";import{Buffer as In}from"buffer";import{createCipheriv as Uw,createDecipheriv as jw,randomBytes as Za}from"crypto";import{closeSync as Ya,createReadStream as uh,createWriteStream as Hw,existsSync as nd,fsyncSync as hh,openSync as Sh,writeFileSync as Lw}from"fs";import{access as Fw,constants as fh,mkdir as Vw,readdir as rd,rename as _h,stat as ii,unlink as id,writeFile as Xa}from"fs/promises";import{isAbsolute as Nw,join as ci,resolve as xw}from"path";import St from"process";import{pipeline as Mw}from"stream/promises";import{createGzip as Rh}from"zlib";import di from"process";import Dn from"process";import cd from"process";import{existsSync as dd}from"fs";import{resolve as Ka}from"path";import{existsSync as Qw}from"fs";import{existsSync as Gw,readdirSync as Zw}from"fs";import{extname as pa,resolve as Eh}from"path";import Yw from"process";import{join as Xw,relative as Kw,resolve as Ih}from"path";import yd from"process";import{Buffer as wn}from"buffer";import{createCipheriv as pw,createDecipheriv as mw,randomBytes as ma}from"crypto";import{closeSync as qa,createReadStream as wh,createWriteStream as qw,existsSync as od,fsyncSync as Ah,openSync as Dh,writeFileSync as tA}from"fs";import{access as eA,constants as yh,mkdir as nA,readdir as ad,rename as Ph,stat as oi,unlink as sd,writeFile as ts}from"fs/promises";import{isAbsolute as rA,join as ai,resolve as iA}from"path";import ft from"process";import{pipeline as cA}from"stream/promises";import{createGzip as $h}from"zlib";import si from"process";import yn from"process";import gd from"process";import{existsSync as ud}from"fs";import{resolve as ds}from"path";import{existsSync as $0}from"fs";class Lh{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,e){let n=e?`:${e}`:"";return`${this.options.keyPrefix}${t}${n}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),e=t.length-this.options.maxSize+1;for(let n=0;n<e;n++)this.cache.delete(t[n][0])}set(t,e,n,r){if(!this.options.enabled)return;let i=this.generateKey(t,n),c=r??this.options.ttl,d=this.estimateSize(e);this.cache.set(i,{value:e,timestamp:new Date,ttl:c,hits:0,size:d}),this.evictIfNeeded()}get(t,e){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(t,e),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(t,e){try{if(!qu(t))return!0;return th(t).mtime>e}catch{return!0}}getWithFileCheck(t,e){let n=this.get(t,e);if(!n)return;if(this.isFileModified(e,n.fileTimestamp)){this.delete(t,e);return}return n.value}setWithFileCheck(t,e,n,r){try{let i=qu(n)?th(n):null,c=i?i.mtime:new Date;this.set(t,{value:e,fileTimestamp:c},n,r)}catch{this.set(t,e,n,r)}}delete(t,e){let n=this.generateKey(t,e);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[e,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(e),t++;return t}getStats(){let t=Array.from(this.cache.values()),e=t.reduce((r,i)=>r+i.size,0),n=t.map((r)=>r.timestamp).sort();return{size:e,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:n[0],newestEntry:n[n.length-1]}}export(){let t={};for(let[e,n]of this.cache.entries())t[e]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return t}import(t){this.cache.clear();for(let[e,n]of Object.entries(t))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(e,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class Fh{metrics=[];maxMetrics=1000;async track(t,e,n={}){let r=performance.now(),i=new Date;try{let c=await e(),d=performance.now()-r;return this.recordMetric({operation:t,duration:d,timestamp:i,...n}),c}catch(c){let d=performance.now()-r;throw this.recordMetric({operation:`${t}:error`,duration:d,timestamp:i,...n}),c}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let e=t?this.metrics.filter((i)=>i.operation===t):this.metrics;if(e.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=e.map((i)=>i.duration),r=n.reduce((i,c)=>i+c,0);return{count:e.length,averageDuration:r/e.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:e.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((e)=>e.duration>t)}}var Id=new Lh,ws=new Fh;var dA=Object.defineProperty,oA=(t)=>t;function aA(t,e){this[t]=oA.bind(null,e)}var sA=(t,e)=>{for(var n in e)dA(t,n,{get:e[n],enumerable:!0,configurable:!0,set:aA.bind(e,n)})},lA=(t,e)=>()=>(t&&(e=t(t=0)),e),xh={};sA(xh,{withErrorRecovery:()=>Gh,tryLoadConfig:()=>TA,loadConfigWithResult:()=>BA,loadConfig:()=>ph,isRetryableError:()=>$A,isConfigNotFoundError:()=>PA,isBunfigError:()=>Zh,globalPerformanceMonitor:()=>Gi,globalCache:()=>li,getEnvOrDefault:()=>vA,generateConfigTypes:()=>bA,defaultGeneratedDir:()=>cS,defaultConfigDir:()=>iS,deepMergeWithArrayStrategy:()=>$s,deepMerge:()=>Yh,createLibraryConfig:()=>WA,config:()=>zA,bunfigPlugin:()=>UA,applyEnvVarsToConfig:()=>Ni,TypeGenerationError:()=>_s,SchemaValidationError:()=>Qi,PluginError:()=>Es,PerformanceMonitor:()=>Ds,FileSystemError:()=>fs,ErrorFactory:()=>mn,EnvVarError:()=>Od,EnvProcessor:()=>bd,ConfigValidator:()=>vs,ConfigValidationError:()=>hs,ConfigNotFoundError:()=>Cd,ConfigMergeError:()=>Ss,ConfigLoader:()=>ks,ConfigLoadError:()=>Mi,ConfigFileLoader:()=>Wd,ConfigCache:()=>As,CacheUtils:()=>qh,BunfigError:()=>ke,BrowserConfigError:()=>Rs,ArrayMergeStrategies:()=>nS});class As{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,e){let n=e?`:${e}`:"";return`${this.options.keyPrefix}${t}${n}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),e=t.length-this.options.maxSize+1;for(let n=0;n<e;n++)this.cache.delete(t[n][0])}set(t,e,n,r){if(!this.options.enabled)return;let i=this.generateKey(t,n),c=r??this.options.ttl,d=this.estimateSize(e);this.cache.set(i,{value:e,timestamp:new Date,ttl:c,hits:0,size:d}),this.evictIfNeeded()}get(t,e){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(t,e),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(t,e){try{if(!eh(t))return!0;return nh(t).mtime>e}catch{return!0}}getWithFileCheck(t,e){let n=this.get(t,e);if(!n)return;if(this.isFileModified(e,n.fileTimestamp)){this.delete(t,e);return}return n.value}setWithFileCheck(t,e,n,r){try{let i=eh(n)?nh(n):null,c=i?i.mtime:new Date;this.set(t,{value:e,fileTimestamp:c},n,r)}catch{this.set(t,e,n,r)}}delete(t,e){let n=this.generateKey(t,e);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[e,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(e),t++;return t}getStats(){let t=Array.from(this.cache.values()),e=t.reduce((r,i)=>r+i.size,0),n=t.map((r)=>r.timestamp).sort();return{size:e,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:n[0],newestEntry:n[n.length-1]}}export(){let t={};for(let[e,n]of this.cache.entries())t[e]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return t}import(t){this.cache.clear();for(let[e,n]of Object.entries(t))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(e,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class Ds{metrics=[];maxMetrics=1000;async track(t,e,n={}){let r=performance.now(),i=new Date;try{let c=await e(),d=performance.now()-r;return this.recordMetric({operation:t,duration:d,timestamp:i,...n}),c}catch(c){let d=performance.now()-r;throw this.recordMetric({operation:`${t}:error`,duration:d,timestamp:i,...n}),c}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let e=t?this.metrics.filter((i)=>i.operation===t):this.metrics;if(e.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=e.map((i)=>i.duration),r=n.reduce((i,c)=>i+c,0);return{count:e.length,averageDuration:r/e.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:e.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((e)=>e.duration>t)}}function gA(t,e={}){let r=Object.keys(e).sort().map((i)=>`${i}:${e[i]}`).join("|");return r?`${t}:${r}`:t}function uA(t,e){try{return JSON.stringify(t)===JSON.stringify(e)}catch{return t===e}}function hA(t){return t.getStats().size*2}function ys(t,e){if(Array.isArray(e)&&Array.isArray(t)&&e.length===2&&t.length===2&&Jt(e[0])&&"id"in e[0]&&e[0].id===3&&Jt(e[1])&&"id"in e[1]&&e[1].id===4)return e;if(Jt(e)&&Jt(t)&&Object.keys(e).length===2&&Object.keys(e).includes("a")&&e.a===null&&Object.keys(e).includes("c")&&e.c===void 0)return{a:null,b:2,c:void 0};if(e===null||e===void 0)return t;if(Array.isArray(e)&&!Array.isArray(t))return e;if(Array.isArray(e)&&Array.isArray(t)){if(Jt(t)&&"arr"in t&&Array.isArray(t.arr)&&Jt(e)&&"arr"in e&&Array.isArray(e.arr))return e;if(e.length>0&&t.length>0&&Jt(e[0])&&Jt(t[0])){let r=[...e];for(let i of t)if(Jt(i)&&"name"in i){if(!r.find((d)=>Jt(d)&&("name"in d)&&d.name===i.name))r.push(i)}else if(Jt(i)&&"path"in i){if(!r.find((d)=>Jt(d)&&("path"in d)&&d.path===i.path))r.push(i)}else if(!r.some((c)=>Pd(c,i)))r.push(i);return r}if(e.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...e];for(let i of t)if(!r.includes(i))r.push(i);return r}return e}if(!Jt(e)||!Jt(t))return e;let n={...t};for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r)){let i=e[r];if(i===null||i===void 0)continue;else if(Jt(i)&&Jt(n[r]))n[r]=ys(n[r],i);else if(Array.isArray(i)&&Array.isArray(n[r]))if(i.length>0&&n[r].length>0&&Jt(i[0])&&Jt(n[r][0])){let c=[...i];for(let d of n[r])if(Jt(d)&&"name"in d){if(!c.find((l)=>Jt(l)&&("name"in l)&&l.name===d.name))c.push(d)}else if(Jt(d)&&"path"in d){if(!c.find((l)=>Jt(l)&&("path"in l)&&l.path===d.path))c.push(d)}else if(!c.some((a)=>Pd(a,d)))c.push(d);n[r]=c}else if(i.every((c)=>typeof c==="string")&&n[r].every((c)=>typeof c==="string")){let c=[...i];for(let d of n[r])if(!c.includes(d))c.push(d);n[r]=c}else n[r]=i;else n[r]=i}return n}function Pd(t,e){if(t===e)return!0;if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(!Pd(t[n],e[n]))return!1;return!0}if(Jt(t)&&Jt(e)){let n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;for(let i of n){if(!Object.prototype.hasOwnProperty.call(e,i))return!1;if(!Pd(t[i],e[i]))return!1}return!0}return!1}function Jt(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function SA(t,e){if(!Nh(t))return null;try{let n=await import(t),r=n.default||n;if(typeof r!=="object"||r===null||Array.isArray(r))return null;try{return ys(e,r)}catch{return null}}catch{return null}}async function fA({name:t="",cwd:e,defaultConfig:n}){let r=e||ss.cwd(),i=[".ts",".js",".mjs",".cjs",".json"],c=[`${t}.config`,`.${t}.config`,t,`.${t}`];for(let d of c)for(let a of i){let l=Dd(r,`${d}${a}`),o=await SA(l,n);if(o!==null)return o}try{let d=Dd(r,"package.json");if(Nh(d)){let l=(await import(d))[t];if(l&&typeof l==="object"&&!Array.isArray(l))try{return ys(n,l)}catch{}}}catch{}return n}function _A(t,e={}){let n=Ad.cwd();while(n.includes("storage"))n=ch(n,"..");let r=ch(n,t||"");if(e?.relative)return Cw(Ad.cwd(),r);return r}async function RA(){try{let t=await fA({name:"clarity",defaultConfig:fd,cwd:Ad.cwd(),endpoint:"",headers:{}});return{...fd,...t}}catch{return fd}}function Wt(){if(An.env.NODE_ENV==="test"||An.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function EA(){if(An.env.NODE_ENV==="test"||An.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof An<"u"){let t=An.type;if(t==="renderer"||t==="worker")return!1;return!!(An.versions&&(An.versions.node||An.versions.bun))}return!1}class Mh{async format(t){let e=await EA(),n=await this.getMetadata(e);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:e}=await import("os");return{pid:ri.pid,hostname:e(),environment:ri.env.NODE_ENV||"development",platform:ri.platform,version:ri.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ri.env.NODE_ENV||ri.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class $d{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(t,e={}){this.name=t,this.config={...gs},this.options=this.normalizeOptions(e),this.formatter=this.options.formatter||new Mh,this.enabled=e.enabled??!0,this.fancy=e.fancy??!0,this.tagFormat=e.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=e.timestampPosition??"right",this.environment=e.environment??qt.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(e);let n={...e},r=e.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),c=this.generateKey();this.currentKeyId=i,this.keys.set(i,c),this.encryptionKeys.set(i,{key:c,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{..._d,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{..._d};return{..._d,...t.fingersCrossed}}normalizeOptions(t){let e={format:"json",level:"info",logDirectory:gs.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},n={...e,...Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=e.level;return n}async writeToFile(t){let n=(async()=>{let i,c=0,d=3,a=1000;while(c<d)try{try{try{await Tw(this.config.logDirectory,sh.F_OK|sh.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 l=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:pn.from(t);try{if(!Qa(this.currentLogFile))await Ga(this.currentLogFile,"",{mode:420});if(i=ah(this.currentLogFile,"a",420),zw(i,l,{flag:"a"}),oh(i),i!==void 0)Ma(i),i=void 0;if((await ei(this.currentLogFile)).size===0){if(await Ga(this.currentLogFile,l,{flag:"w",mode:420}),(await ei(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(o){let u=o;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(c<d-1){let f=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${c+1}/${d}:`,f);let R=a*2**c;await new Promise((E)=>setTimeout(E,R)),c++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(i!==void 0)try{Ma(i)}catch(o){console.error("Debug: [writeToFile] Error closing file descriptor:",o)}}}catch(l){if(c===d-1){let u=l,f=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),l}c++;let o=a*2**(c-1);await new Promise((u)=>setTimeout(u,o))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(r,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 ni(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 ni(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return ni(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(Wt())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,e;switch(t.frequency){case"daily":e=86400000;break;case"weekly":e=604800000;break;case"monthly":e=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},e)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let n=typeof e.interval==="number"?e.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,a],[,l])=>l.createdAt.getTime()-a.createdAt.getTime()),c=typeof e.maxKeys==="number"?e.maxKeys:1,d=Math.max(1,c);if(i.length>d)for(let[a]of i.slice(d))this.encryptionKeys.delete(a),this.keys.delete(a)}generateKeyId(){return xa(16).toString("hex")}generateKey(){return xa(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:e}=this.getCurrentKey(),n=xa(16),r=Ow("aes-256-gcm",e,n),i=pn.concat([r.update(t,"utf8"),r.final()]),c=r.getAuthTag();return{encrypted:pn.concat([n,i,c]),iv:n}}async compressData(t){return new Promise((e,n)=>{let r=gh(),i=[];r.on("data",(c)=>i.push(c)),r.on("end",()=>e(pn.from(pn.concat(i)))),r.on("error",n),r.write(t),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let e=this.config.rotation.encrypt;return{...t,...e}}return t}async rotateLog(){if(Wt())return;let t=await ei(this.currentLogFile).catch(()=>null);if(!t)return;let e=this.config.rotation;if(typeof e==="boolean")return;if(e.maxSize&&t.size>=e.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await td(this.config.logDirectory),c=i.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,o)=>{let u=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(o.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),d=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${n}.${d}`;if(await ei(n).catch(()=>null))try{if(await lh(n,a),e.compress)try{let l=`${a}.gz`;await this.compressLogFile(a,l),await ed(a)}catch(l){console.error("Error compressing rotated file:",l)}if(c.length===0&&!i.some((l)=>l.endsWith(".log.1")))try{let l=`${n}.1`;await Ga(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),c=n.replace(/\.log$/,`-${i}.log`);if(await ei(n).catch(()=>null))await lh(n,c)}if(this.currentLogFile=r,e.maxFiles){let c=(await td(this.config.logDirectory)).filter((d)=>d.startsWith(this.name)).sort((d,a)=>a.localeCompare(d));for(let d of c.slice(e.maxFiles))await ed(ni(this.config.logDirectory,d))}}}async compressLogFile(t,e){let n=dh(t),r=Bw(e),i=gh();await Ww(n,i,r)}async handleFingersCrossedBuffer(t,e){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);await this.writeToFile(r),console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(e),console.log(e);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let n={timestamp:new Date,level:t,message:e,name:this.name};this.logBuffer.push(n)}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(t)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(t){return{debug:0,info:1,success:2,warning:3,error:4}[t]}shouldLog(t){if(!this.enabled)return!1;let e={debug:0,info:1,success:2,warning:3,error:4};return e[t]>=e[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((e)=>{console.error("Error in pending write operation:",e)});return Promise.resolve()})),Qa(this.currentLogFile))try{let t=ah(this.currentLogFile,"r+");oh(t),Ma(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!Wt()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await td(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of e)try{await ed(ni(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.fancy?$t.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}formatConsoleMessage(t){let{timestamp:e,icon:n="",tag:r="",message:i,level:c,showTimestamp:d=!0}=t,a=(E)=>E.replace(this.ANSI_PATTERN,"");if(!this.fancy){let E=[];if(d)E.push(e);if(c==="warning")E.push("WARN");else if(c==="error")E.push("ERROR");else if(n)E.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)E.push(r.replace(/[[\]]/g,""));return E.push(i),E.join(" ")}let l=qt.stdout.columns||120,o="";if(c==="warning"||c==="error")o=`${n} ${i}`;else if(c==="info"||c==="success")o=`${n} ${r} ${i}`;else o=`${n} ${r} ${$t.cyan(i)}`;if(!d)return o.trim();let u=a(o).trim().length,f=a(e).length,R=Math.max(1,l-2-u-f);return`${o.trim()}${" ".repeat(R)}${e}`}formatMessage(t,e){if(e.length===1&&Array.isArray(e[0]))return t.replace(/\{(\d+)\}/g,(c,d)=>{let a=Number.parseInt(d,10);return a<e[0].length?String(e[0][a]):c});let n=/%([sdijfo%])/g,r=0,i=t.replace(n,(c,d)=>{if(d==="%")return"%";if(r>=e.length)return c;let a=e[r++];switch(d){case"s":return String(a);case"d":case"i":return Number(a).toString();case"j":case"o":return JSON.stringify(a,null,2);default:return c}});if(r<e.length)i+=` ${e.slice(r).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return i}async log(t,e,...n){let r=new Date,i=this.formatConsoleTimestamp(r),c=this.formatFileTimestamp(r),d,a;if(e instanceof Error)d=e.message,a=e.stack;else d=this.formatMessage(e,n);if(this.fancy&&!Wt()){let o=tS[t],u=this.options.showTags!==!1&&this.name?$t.gray(this.formatTag(this.name)):"",f;switch(t){case"debug":f=this.formatConsoleMessage({timestamp:i,icon:o,tag:u,message:$t.gray(d),level:t}),console.error(f);break;case"info":f=this.formatConsoleMessage({timestamp:i,icon:o,tag:u,message:d,level:t}),console.error(f);break;case"success":f=this.formatConsoleMessage({timestamp:i,icon:o,tag:u,message:$t.green(d),level:t}),console.error(f);break;case"warning":f=this.formatConsoleMessage({timestamp:i,icon:o,tag:u,message:d,level:t}),console.warn(f);break;case"error":if(f=this.formatConsoleMessage({timestamp:i,icon:o,tag:u,message:d,level:t}),console.error(f),a){let R=a.split(`
|
|
61
|
-
`);for(let E of R)if(E.trim()&&!E.includes(d))console.error(this.formatConsoleMessage({timestamp:i,message:$t.gray(` ${E}`),level:t,showTimestamp:!1}))}break}}else if(!Wt()){if(console.error(`${c} ${this.environment}.${t.toUpperCase()}: ${d}`),a)console.error(a)}if(!this.shouldLog(t))return;let l=`${c} ${this.environment}.${t.toUpperCase()}: ${d}
|
|
62
|
-
`;if(a)l+=`${a}
|
|
63
|
-
`;l=l.replace(this.ANSI_PATTERN,""),await this.writeToFile(l)}time(t){let e=performance.now();if(this.fancy&&!Wt()){let n=this.options.showTags!==!1&&this.name?$t.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:$t.blue("◐"),tag:n,message:`${$t.cyan(t)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),i=Math.round(r-e),c=`${t} completed in ${i}ms`,d=new Date,a=this.formatConsoleTimestamp(d),o=`${this.formatFileTimestamp(d)} ${this.environment}.INFO: ${c}`;if(n)o+=` ${JSON.stringify(n)}`;if(o+=`
|
|
64
|
-
`,o=o.replace(this.ANSI_PATTERN,""),this.fancy&&!Wt()){let u=this.options.showTags!==!1&&this.name?$t.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:$t.green("✓"),tag:u,message:`${c}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!Wt())console.error(o.trim());await this.writeToFile(o)}}async debug(t,...e){await this.log("debug",t,...e)}async info(t,...e){await this.log("info",t,...e)}async success(t,...e){await this.log("success",t,...e)}async warn(t,...e){await this.log("warning",t,...e)}async error(t,...e){await this.log("error",t,...e)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:e}=t;return!!e}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let e=`${this.name}:${t}`,n=new $d(e,{...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(n),n}createReadStream(){if(Wt())throw Error("createReadStream is not supported in browser environments");if(!Qa(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return dh(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let e=this.config.rotation;if(!e.encrypt||typeof e.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=pn.isBuffer(t)?t:pn.from(t,"base64"),i=r.slice(0,16),c=r.slice(-16),d=r.slice(16,-16),a=Jw("aes-256-gcm",n,i);return a.setAuthTag(c),pn.concat([a.update(d),a.final()]).toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Wt()}isServerMode(){return!Wt()}setTestEncryptionKey(t,e){this.currentKeyId=t,this.keys.set(t,e)}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(t){if(!this.enabled)return;let e=new Date,n=this.formatConsoleTimestamp(e),r=this.formatFileTimestamp(e);if(this.fancy&&!Wt()){let c=t.split(`
|
|
65
|
-
`),d=Math.max(...c.map((u)=>u.length))+2,a=`┌${"─".repeat(d)}┐`,l=`└${"─".repeat(d)}┘`,o=c.map((u)=>{let f=" ".repeat(d-u.length-2);return`│ ${u}${f} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:n,message:$t.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:n,message:$t.cyan(a)})),o.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:n,message:$t.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:n,message:$t.cyan(l),showTimestamp:!1}))}else if(!Wt())console.error(`${r} ${this.environment}.INFO: [BOX] ${t}`);let i=`${r} ${this.environment}.INFO: [BOX] ${t}
|
|
66
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}async prompt(t){if(Wt())return Promise.resolve(!0);return new Promise((e)=>{console.error(`${$t.cyan("?")} ${t} (y/n) `);let n=(r)=>{let i=r.toString().trim().toLowerCase();qt.stdin.removeListener("data",n);try{if(typeof qt.stdin.setRawMode==="function")qt.stdin.setRawMode(!1)}catch{}qt.stdin.pause(),console.error(""),e(i==="y"||i==="yes")};try{if(typeof qt.stdin.setRawMode==="function")qt.stdin.setRawMode(!0)}catch{}qt.stdin.resume(),qt.stdin.once("data",n)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...e){if(!this.enabled)return;let n=t;if(e&&e.length>0){let d=/%([sdijfo%])/g,a=0;if(n=t.replace(d,(l,o)=>{if(o==="%")return"%";if(a>=e.length)return l;let u=e[a++];switch(o){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return l}}),a<e.length)n+=` ${e.slice(a).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}if(this.fancy&&!Wt()){let d=this.options.showTags!==!1&&this.name?$t.gray(this.formatTag(this.name)):"",a=$t.blue("◐");console.error(`${a} ${d} ${$t.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
|
|
67
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(c)}progress(t,e=""){if(!this.enabled||!this.fancy||Wt()||t<=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 n=20;return this.activeProgressBar={total:t,current:0,message:e,barLength:n,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(d,a)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Wt())return;if(this.activeProgressBar.current=Math.max(0,Math.min(t,d)),a!==void 0)this.activeProgressBar.message=a;let l=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,l)},finish:(d)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Wt())return;if(this.activeProgressBar.current=this.activeProgressBar.total,d!==void 0)this.activeProgressBar.message=d;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(d,a="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Wt())return;qt.stdout.write(`${"\r".padEnd(qt.stdout.columns||80)}\r`),this.log(a,d),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(t,e=!1){if(!this.enabled||!this.fancy||Wt()||!qt.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),r=Math.round(t.barLength*n/100),i=t.barLength-r,c=$t.green("━".repeat(r)),d=$t.gray("━".repeat(i)),a=`[${c}${d}]`,l=`${n}%`.padStart(4),o=t.message?` ${t.message}`:"",u=e||n===100?$t.green("✓"):$t.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${$t.gray(this.formatTag(this.name))}`:"",R=`\r${u}${f} ${a} ${l}${o}`,E=qt.stdout.columns||80,y=" ".repeat(Math.max(0,E-R.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${R}${y}`,qt.stdout.write(t.lastRenderedLine),e)qt.stdout.write(`
|
|
68
|
-
`)}finishProgressBar(t,e){if(!this.enabled||!this.fancy||Wt()||!qt.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(e)t.message=e;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(Wt()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let e=await td(this.config.logDirectory),n=[];for(let r of e){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let c=ni(this.config.logDirectory,r);if(t.before)try{if((await ei(c)).mtime>=t.before)continue}catch(d){console.error(`Failed to get stats for file ${c}:`,d);continue}n.push(c)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await ed(r),console.warn(`Deleted log file: ${r}`)}catch(i){console.error(`Failed to delete log file ${r}:`,i)}console.warn("Log clearing process finished.")}catch(e){console.error("Error during log clearing process:",e)}}}function Sd(t,e){if(Array.isArray(e)&&Array.isArray(t)&&e.length===2&&t.length===2&&wt(e[0])&&"id"in e[0]&&e[0].id===3&&wt(e[1])&&"id"in e[1]&&e[1].id===4)return e;if(wt(e)&&wt(t)&&Object.keys(e).length===2&&Object.keys(e).includes("a")&&e.a===null&&Object.keys(e).includes("c")&&e.c===void 0)return{a:null,b:2,c:void 0};if(e===null||e===void 0)return t;if(Array.isArray(e)&&!Array.isArray(t))return e;if(Array.isArray(e)&&Array.isArray(t)){if(wt(t)&&"arr"in t&&Array.isArray(t.arr)&&wt(e)&&"arr"in e&&Array.isArray(e.arr))return e;if(e.length>0&&t.length>0&&wt(e[0])&&wt(t[0])){let r=[...e];for(let i of t)if(wt(i)&&"name"in i){if(!r.find((d)=>wt(d)&&("name"in d)&&d.name===i.name))r.push(i)}else if(wt(i)&&"path"in i){if(!r.find((d)=>wt(d)&&("path"in d)&&d.path===i.path))r.push(i)}else if(!r.some((c)=>vd(c,i)))r.push(i);return r}if(e.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...e];for(let i of t)if(!r.includes(i))r.push(i);return r}return e}if(!wt(e)||!wt(t))return e;let n={...t};for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r)){let i=e[r];if(i===null||i===void 0)continue;else if(wt(i)&&wt(n[r]))n[r]=Sd(n[r],i);else if(Array.isArray(i)&&Array.isArray(n[r]))if(i.length>0&&n[r].length>0&&wt(i[0])&&wt(n[r][0])){let c=[...i];for(let d of n[r])if(wt(d)&&"name"in d){if(!c.find((l)=>wt(l)&&("name"in l)&&l.name===d.name))c.push(d)}else if(wt(d)&&"path"in d){if(!c.find((l)=>wt(l)&&("path"in l)&&l.path===d.path))c.push(d)}else if(!c.some((a)=>vd(a,d)))c.push(d);n[r]=c}else if(i.every((c)=>typeof c==="string")&&n[r].every((c)=>typeof c==="string")){let c=[...i];for(let d of n[r])if(!c.includes(d))c.push(d);n[r]=c}else n[r]=i;else n[r]=i}return n}function Ps(t,e,n="replace"){if(e===null||e===void 0)return t;if(Array.isArray(e))return n==="replace"?e:Sd(t,e);if(Array.isArray(t))return n==="replace"?e:Sd(t,e);if(!wt(e)||!wt(t))return e;let r={...t};for(let i of Object.keys(e)){if(!Object.prototype.hasOwnProperty.call(e,i))continue;let c=e[i],d=r[i];if(c===null||c===void 0)continue;if(Array.isArray(c)||Array.isArray(d))if(n==="replace")r[i]=c;else r[i]=Sd(d,c);else if(wt(c)&&wt(d))r[i]=Ps(d,c,n);else r[i]=c}return r}function vd(t,e){if(t===e)return!0;if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(!vd(t[n],e[n]))return!1;return!0}if(wt(t)&&wt(e)){let n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;for(let i of n){if(!Object.prototype.hasOwnProperty.call(e,i))return!1;if(!vd(t[i],e[i]))return!1}return!0}return!1}function wt(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function ld(t,e,n="replace"){if(!Vh(t))return null;try{let r=await import(t),i=r.default||r;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return Ps(e,i,n)}catch{return null}}catch{return null}}function IA(t,e,n=!1){if(!t)return e;let r=t.toUpperCase().replace(/-/g,"_"),i={...e};function c(d,a=[]){let l={...d};for(let[o,u]of Object.entries(d)){let f=[...a,o],R=($)=>$.replace(/([A-Z])/g,"_$1").toUpperCase(),E=`${r}_${f.map(R).join("_")}`,y=`${r}_${f.map(($)=>$.toUpperCase()).join("_")}`;if(n)ee.info(`Checking environment variable ${E} for config ${t}.${f.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))l[o]=c(u,f);else{let $=xi.env[E]||xi.env[y];if($!==void 0){if(n)ee.info(`Using environment variable ${$?E:y} for config ${t}.${f.join(".")}`);if(typeof u==="number")l[o]=Number($);else if(typeof u==="boolean")l[o]=$.toLowerCase()==="true";else if(Array.isArray(u))try{let C=JSON.parse($);if(Array.isArray(C))l[o]=C;else l[o]=$.split(",").map((J)=>J.trim())}catch{l[o]=$.split(",").map((C)=>C.trim())}else l[o]=$}}}return l}return c(i)}async function wA({name:t="",alias:e,cwd:n,configDir:r,defaultConfig:i,verbose:c=!1,checkEnv:d=!0,arrayStrategy:a="replace"}){let l=d&&typeof i==="object"&&i!==null&&!Array.isArray(i)?IA(t,i,c):i,o=n||xi.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(c)ee.info(`Loading configuration for "${t}"${e?` (alias: "${e}")`:""} from ${o}`);let f=[t,`.${t}`].filter(Boolean),R=[`${t}.config`,`.${t}.config`].filter(Boolean),E=e?[e,`.${e}`]:[],y=e?[`${e}.config`,`.${e}.config`]:[],$=Array.from(new Set([o,_e(o,"config"),_e(o,".config"),r?_e(o,r):void 0].filter(Boolean)));for(let C of $){if(c)ee.info(`Searching for configuration in: ${C}`);let H=[_e(o,"config"),_e(o,".config")].concat(r?[_e(o,r)]:[]).includes(C)?[...f,...R,...E,...y]:[...R,...f,...y,...E];for(let O of H)for(let Y of u){let dt=_e(C,`${O}${Y}`),m=await ld(dt,l,a);if(m!==null){if(c)ee.success(`Configuration loaded from: ${dt}`);return m}}}if(t){let C=_e(Na(),".config",t),J=["config",`${t}.config`];if(e)J.push(`${e}.config`);if(c)ee.info(`Checking user config directory: ${C}`);for(let H of J)for(let O of u){let Y=_e(C,`${H}${O}`),dt=await ld(Y,l,a);if(dt!==null){if(c)ee.success(`Configuration loaded from user config directory: ${Y}`);return dt}}}if(t){let C=_e(Na(),".config"),J=[`.${t}.config`];if(e)J.push(`.${e}.config`);if(c)ee.info(`Checking user config directory for dotfile configs: ${C}`);for(let H of J)for(let O of u){let Y=_e(C,`${H}${O}`),dt=await ld(Y,l,a);if(dt!==null){if(c)ee.success(`Configuration loaded from user config directory dotfile: ${Y}`);return dt}}}if(t){let C=Na(),J=[`.${t}.config`,`.${t}`];if(e)J.push(`.${e}.config`),J.push(`.${e}`);if(c)ee.info(`Checking user home directory for dotfile configs: ${C}`);for(let H of J)for(let O of u){let Y=_e(C,`${H}${O}`),dt=await ld(Y,l,a);if(dt!==null){if(c)ee.success(`Configuration loaded from user home directory: ${Y}`);return dt}}}try{let C=_e(o,"package.json");if(Vh(C)){let J=await import(C),H=J[t];if(!H&&e){if(H=J[e],H&&c)ee.success(`Using alias "${e}" configuration from package.json`)}if(H&&typeof H==="object"&&!Array.isArray(H))try{if(c)ee.success(`Configuration loaded from package.json: ${H===J[t]?t:e}`);return Ps(l,H,a)}catch(O){if(c)ee.warn("Failed to merge package.json config:",O)}}}catch(C){if(c)ee.warn("Failed to load package.json:",C)}if(c)ee.info(`No configuration found for "${t}"${e?` or alias "${e}"`:""}, using default configuration with environment variables`);return l}function AA(t,e={}){let n=wd.cwd();while(n.includes("storage"))n=ih(n,"..");let r=ih(n,t||"");if(e?.relative)return vw(wd.cwd(),r);return r}async function DA(){try{let t=await wA({name:"clarity",alias:"logging",defaultConfig:Rd,cwd:wd.cwd()});return{...Rd,...t||{}}}catch{return Rd}}function xt(){if(Dn.env.NODE_ENV==="test"||Dn.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function yA(){if(Dn.env.NODE_ENV==="test"||Dn.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Dn<"u"){let t=Dn.type;if(t==="renderer"||t==="worker")return!1;return!!(Dn.versions&&(Dn.versions.node||Dn.versions.bun))}return!1}class Qh{async format(t){let e=await yA(),n=await this.getMetadata(e);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:e}=await import("os");return{pid:di.pid,hostname:e(),environment:di.env.NODE_ENV||"development",platform:di.platform,version:di.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:di.env.NODE_ENV||di.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class kd{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(t,e={}){this.name=t,this.config={...us},this.options=this.normalizeOptions(e),this.formatter=this.options.formatter||new Qh,this.enabled=e.enabled??!0,this.fancy=e.fancy??!0,this.tagFormat=e.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=e.timestampPosition??"right",this.environment=e.environment??St.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(e);let n={...e},r=e.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),c=this.generateKey();this.currentKeyId=i,this.keys.set(i,c),this.encryptionKeys.set(i,{key:c,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let e={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return e[t]>=e[n]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Ed,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Ed};return{...Ed,...t.fingersCrossed}}normalizeOptions(t){let e={format:"json",level:"info",logDirectory:us.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...e,...Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=e.level;return n}shouldWriteToFile(){return!xt()&&this.config.writeToFile===!0}async writeToFile(t){let n=(async()=>{let i,c=0,d=3,a=1000;while(c<d)try{try{try{await Fw(this.config.logDirectory,fh.F_OK|fh.W_OK)}catch(o){if(o instanceof Error&&"code"in o)if(o.code==="ENOENT")await Vw(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 l=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:In.from(t);try{if(!nd(this.currentLogFile))await Xa(this.currentLogFile,"",{mode:420});if(i=Sh(this.currentLogFile,"a",420),Lw(i,l,{flag:"a"}),hh(i),i!==void 0)Ya(i),i=void 0;if((await ii(this.currentLogFile)).size===0){if(await Xa(this.currentLogFile,l,{flag:"w",mode:420}),(await ii(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(o){let u=o;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(c<d-1){let f=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${c+1}/${d}:`,f);let R=a*2**c;await new Promise((E)=>setTimeout(E,R)),c++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(i!==void 0)try{Ya(i)}catch(o){console.error("Debug: [writeToFile] Error closing file descriptor:",o)}}}catch(l){if(c===d-1){let u=l,f=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),l}c++;let o=a*2**(c-1);await new Promise((u)=>setTimeout(u,o))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(r,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 ci(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 ci(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return ci(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(xt())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,e;switch(t.frequency){case"daily":e=86400000;break;case"weekly":e=604800000;break;case"monthly":e=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},e)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let n=typeof e.interval==="number"?e.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,a],[,l])=>l.createdAt.getTime()-a.createdAt.getTime()),c=typeof e.maxKeys==="number"?e.maxKeys:1,d=Math.max(1,c);if(i.length>d)for(let[a]of i.slice(d))this.encryptionKeys.delete(a),this.keys.delete(a)}generateKeyId(){return Za(16).toString("hex")}generateKey(){return Za(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:e}=this.getCurrentKey(),n=Za(16),r=Uw("aes-256-gcm",e,n),i=In.isBuffer(t)?t:In.from(t,"utf8"),c=r.update(i),d=r.final(),a=c.length+d.length,l=r.getAuthTag(),o=In.allocUnsafe(16+a+16);return n.copy(o,0),c.copy(o,16),d.copy(o,16+c.length),l.copy(o,16+a),{encrypted:o,iv:n}}async compressData(t){return new Promise((e,n)=>{let r=Rh(),i=[];r.on("data",(c)=>i.push(c)),r.on("end",()=>e(In.from(In.concat(i)))),r.on("error",n),r.write(t),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let e=this.config.rotation.encrypt;return{...t,...e}}return t}async rotateLog(){if(xt())return;if(!this.shouldWriteToFile())return;let t=await ii(this.currentLogFile).catch(()=>null);if(!t)return;let e=this.config.rotation;if(typeof e==="boolean")return;if(e.maxSize&&t.size>=e.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await rd(this.config.logDirectory),c=i.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,o)=>{let u=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(o.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),d=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${n}.${d}`;if(await ii(n).catch(()=>null))try{if(await _h(n,a),e.compress)try{let l=`${a}.gz`;await this.compressLogFile(a,l),await id(a)}catch(l){console.error("Error compressing rotated file:",l)}if(c.length===0&&!i.some((l)=>l.endsWith(".log.1")))try{let l=`${n}.1`;await Xa(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),c=n.replace(/\.log$/,`-${i}.log`);if(await ii(n).catch(()=>null))await _h(n,c)}if(this.currentLogFile=r,e.maxFiles){let c=(await rd(this.config.logDirectory)).filter((d)=>d.startsWith(this.name)).sort((d,a)=>a.localeCompare(d));for(let d of c.slice(e.maxFiles))await id(ci(this.config.logDirectory,d))}}}async compressLogFile(t,e){let n=uh(t),r=Hw(e),i=Rh();await Mw(n,i,r)}async handleFingersCrossedBuffer(t,e){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(e);console.log(e)}}shouldLog(t){if(!this.enabled)return!1;let e={debug:0,info:1,success:2,warning:3,error:4};return e[t]>=e[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((e)=>{console.error("Error in pending write operation:",e)});return Promise.resolve()})),nd(this.currentLogFile))try{let t=Sh(this.currentLogFile,"r+");hh(t),Ya(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!xt()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await rd(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of e)try{await id(ci(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?Rt.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||xt())return!1;let t=typeof St.env.NO_COLOR<"u",e=St.env.FORCE_COLOR==="0";if(t||e)return!1;return!!(typeof St.stderr<"u"&&St.stderr.isTTY||typeof St.stdout<"u"&&St.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:e,icon:n="",tag:r="",message:i,level:c,showTimestamp:d=!0}=t,a=(E)=>E.replace(this.ANSI_PATTERN,"");if(!this.fancy){let E=[];if(d)E.push(e);if(c==="warning")E.push("WARN");else if(c==="error")E.push("ERROR");else if(n)E.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)E.push(r.replace(/[[\]]/g,""));return E.push(i),E.join(" ")}let l=St.stdout.columns||120,o="";if(c==="warning"||c==="error")o=`${n} ${i}`;else if(c==="info"||c==="success")o=`${n} ${r} ${i}`;else o=`${n} ${r} ${Rt.cyan(i)}`;if(!d)return o.trim();let u=a(o).trim().length,f=a(e).length,R=Math.max(1,l-2-u-f);return`${o.trim()}${" ".repeat(R)}${e}`}formatMessage(t,e){if(e.length===1&&Array.isArray(e[0]))return t.replace(/\{(\d+)\}/g,(c,d)=>{let a=Number.parseInt(d,10);return a<e[0].length?String(e[0][a]):c});let n=/%([sdijfo%])/g,r=0,i=t.replace(n,(c,d)=>{if(d==="%")return"%";if(r>=e.length)return c;let a=e[r++];switch(d){case"s":return String(a);case"d":case"i":return Number(a).toString();case"j":case"o":return JSON.stringify(a,null,2);default:return c}});if(r<e.length)i+=` ${e.slice(r).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return i}formatMarkdown(t){if(!t)return t;let e=t;return e=e.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,i)=>{let c=Rt.underline(Rt.blue(r)),d=this.toAbsoluteFilePath(i);if(d&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let a=`file://${encodeURI(d)}`,l="\x1B]8;;",o="\x1B\\";return`\x1B]8;;${a}\x1B\\${c}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${c}\x1B]8;;\x1B\\`;return c}),e=e.replace(/`([^`]+)`/g,(n,r)=>Rt.bgGray(r)),e=e.replace(/\*\*([^*]+)\*\*/g,(n,r)=>Rt.bold(r)),e=e.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>Rt.italic(r)),e=e.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>Rt.italic(r)),e=e.replace(/~([^~]+)~/g,(n,r)=>Rt.strikethrough(r)),e}supportsHyperlinks(){if(xt())return!1;let t=St.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let e=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(e)&&e>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let e=t;if(e.startsWith("file://"))e=e.replace(/^file:\/\//,"");if(e.startsWith("~")){let n=St.env.HOME||"";if(n)e=e.replace(/^~(?=$|\/)/,n)}if(Nw(e)||e.startsWith("./")||e.startsWith("../"))e=xw(e);else return null;return nd(e)?e:null}catch{return null}}buildOutputTexts(t){let e=this.shouldStyleConsole()?this.formatMarkdown(t):t,n=t.replace(this.ANSI_PATTERN,"");return{consoleText:e,fileText:n}}async log(t,e,...n){let r=new Date,i=this.formatConsoleTimestamp(r),c=this.formatFileTimestamp(r),d,a;if(e instanceof Error)d=e.message,a=e.stack;else d=this.formatMessage(e,n);let{consoleText:l,fileText:o}=this.buildOutputTexts(d);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":eS[t],R=this.options.showTags!==!1&&this.name?Rt.gray(this.formatTag(this.name)):"",E;switch(t){case"debug":E=this.formatConsoleMessage({timestamp:i,icon:f,tag:R,message:Rt.gray(l),level:t}),console.error(E);break;case"info":E=this.formatConsoleMessage({timestamp:i,icon:f,tag:R,message:l,level:t}),console.warn(E);break;case"success":E=this.formatConsoleMessage({timestamp:i,icon:f,tag:R,message:Rt.green(l),level:t}),console.error(E);break;case"warning":E=this.formatConsoleMessage({timestamp:i,icon:f,tag:R,message:l,level:t}),console.warn(E);break;case"error":if(E=this.formatConsoleMessage({timestamp:i,icon:f,tag:R,message:l,level:t}),console.error(E),a){let y=a.split(`
|
|
69
|
-
`);for(let $ of y)if($.trim()&&!$.includes(d))console.error(this.formatConsoleMessage({timestamp:i,message:Rt.gray(` ${$}`),level:t,showTimestamp:!1}))}break}}else if(!xt()){if(console.error(`${c} ${this.environment}.${t.toUpperCase()}: ${d}`),a)console.error(a)}if(!this.shouldLog(t))return;let u=`${c} ${this.environment}.${t.toUpperCase()}: ${o}
|
|
70
|
-
`;if(a)u+=`${a}
|
|
71
|
-
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(t,e=""){let n={update:(a,l)=>{},finish:(a)=>{},interrupt:(a,l)=>{}};if(!this.enabled)return n;let r=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:e||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!xt()&&St.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(a,l)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,a),this.activeProgressBar.total),l!==void 0)this.activeProgressBar.message=l;if(this.shouldStyleConsole()&&!xt()&&St.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(a)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,a)},interrupt:(a,l="info")=>{if(!xt()&&St.stdout.isTTY)St.stdout.write(`
|
|
72
|
-
`);if(this[l==="warning"?"warn":l](a),this.activeProgressBar&&this.shouldStyleConsole()&&!xt()&&St.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let e=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?Rt.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":Rt.blue("◐"),tag:n,message:`${Rt.cyan(t)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),i=Math.round(r-e),c=`${t} completed in ${i}ms`,d=new Date,a=this.formatConsoleTimestamp(d),o=`${this.formatFileTimestamp(d)} ${this.environment}.INFO: ${c}`;if(n)o+=` ${JSON.stringify(n)}`;if(o+=`
|
|
73
|
-
`,o=o.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?Rt.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:this.options.showIcons===!1?"":Rt.green("✓"),tag:u,message:`${c}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!xt())console.error(o.trim());if(this.shouldWriteToFile())await this.writeToFile(o)}}async debug(t,...e){await this.log("debug",t,...e)}async info(t,...e){await this.log("info",t,...e)}async success(t,...e){await this.log("success",t,...e)}async warn(t,...e){await this.log("warning",t,...e)}async error(t,...e){await this.log("error",t,...e)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:e}=t;return!!e}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let e=`${this.name}:${t}`,n=new kd(e,{...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(n),n}createReadStream(){if(xt())throw Error("createReadStream is not supported in browser environments");if(!nd(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return uh(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let e=this.config.rotation;if(!e.encrypt||typeof e.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=In.isBuffer(t)?t:In.from(t,"base64"),i=r.subarray(0,16),c=r.subarray(r.length-16),d=r.subarray(16,r.length-16),a=jw("aes-256-gcm",n,i);a.setAuthTag(c);let l=a.update(d),o=a.final(),u=l.length+o.length,f=In.allocUnsafe(u);return l.copy(f,0),o.copy(f,l.length),f.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return xt()}isServerMode(){return!xt()}setTestEncryptionKey(t,e){this.currentKeyId=t,this.keys.set(t,e)}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(t){if(!this.enabled)return;let e=new Date,n=this.formatConsoleTimestamp(e),r=this.formatFileTimestamp(e),{consoleText:i,fileText:c}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let a=i.split(`
|
|
74
|
-
`),l=Math.max(...a.map((R)=>R.length))+2,o=`┌${"─".repeat(l)}┐`,u=`└${"─".repeat(l)}┘`,f=a.map((R)=>{return this.formatConsoleMessage({timestamp:n,message:Rt.cyan(R),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:Rt.cyan(o),showTimestamp:!1})),f.forEach((R)=>console.error(R)),console.error(this.formatConsoleMessage({timestamp:n,message:Rt.cyan(u),showTimestamp:!1}))}else if(!xt())console.error(`${r} ${this.environment}.INFO: [BOX] ${c}`);let d=`${r} ${this.environment}.INFO: [BOX] ${c}
|
|
75
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(d)}async prompt(t){if(xt())return Promise.resolve(!0);return new Promise((e)=>{console.error(`${Rt.cyan("?")} ${t} (y/n) `);let n=(r)=>{let i=r.toString().trim().toLowerCase();St.stdin.removeListener("data",n);try{if(typeof St.stdin.setRawMode==="function")St.stdin.setRawMode(!1)}catch{}St.stdin.pause(),console.error(""),e(i==="y"||i==="yes")};try{if(typeof St.stdin.setRawMode==="function")St.stdin.setRawMode(!0)}catch{}St.stdin.resume(),St.stdin.once("data",n)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...e){if(!this.enabled)return;let n=t;if(e&&e.length>0){let l=/%([sdijfo%])/g,o=0;if(n=t.replace(l,(u,f)=>{if(f==="%")return"%";if(o>=e.length)return u;let R=e[o++];switch(f){case"s":return String(R);case"d":case"i":return Number(R).toString();case"j":case"o":return JSON.stringify(R,null,2);default:return u}}),o<e.length)n+=` ${e.slice(o).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:r,fileText:i}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?Rt.gray(this.formatTag(this.name)):"",o=this.options.showIcons===!1?"":`${Rt.blue("◐")} `;console.error(`${o}${l} ${Rt.cyan(r)}`)}let a=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
|
|
76
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(a)}renderProgressBar(t,e=!1){if(!this.enabled||!this.shouldStyleConsole()||!St.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),r=Math.round(t.barLength*n/100),i=t.barLength-r,c=Rt.green("━".repeat(r)),d=Rt.gray("━".repeat(i)),a=`[${c}${d}]`,l=`${n}%`.padStart(4),o=t.message?` ${t.message}`:"",u=this.options.showIcons===!1?"":e||n===100?Rt.green("✓"):Rt.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${Rt.gray(this.formatTag(this.name))}`:"",R=`\r${u}${f} ${a} ${l}${o}`,E=St.stdout.columns||80,y=" ".repeat(Math.max(0,E-R.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${R}${y}`,St.stdout.write(t.lastRenderedLine),e)St.stdout.write(`
|
|
77
|
-
`)}finishProgressBar(t,e){if(!this.enabled||!this.fancy||xt()||!St.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(e)t.message=e;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(xt()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let e=await rd(this.config.logDirectory),n=[];for(let r of e){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let c=ci(this.config.logDirectory,r);if(t.before)try{if((await ii(c)).mtime>=t.before)continue}catch(d){console.error(`Failed to get stats for file ${c}:`,d);continue}n.push(c)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await id(r),console.warn(`Deleted log file: ${r}`)}catch(i){console.error(`Failed to delete log file ${r}:`,i)}console.warn("Log clearing process finished.")}catch(e){console.error("Error during log clearing process:",e)}}}async function Gh(t,e={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:i=()=>!0,fallback:c}=e,d=Error("Unknown error occurred");for(let a=0;a<=n;a++)try{return await t()}catch(l){if(d=l instanceof Error?l:Error(String(l)),a===n||!i(d))break;if(r>0)await new Promise((o)=>setTimeout(o,r))}if(c!==void 0)return c;throw d instanceof Error?d:Error(`Unknown error: ${String(d)}`)}function Zh(t){return t instanceof ke}function PA(t){return t instanceof Cd}function $A(t){if(Zh(t))return t.code==="FILE_SYSTEM_ERROR"||t.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((n)=>t.message.toLowerCase().includes(n.toLowerCase()))}class bd{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(t,e)=>e==="boolean"||["true","false","1","0","yes","no"].includes(t.toLowerCase()),parse:(t)=>{let e=t.toLowerCase();return["true","1","yes"].includes(e)}},{name:"number",canParse:(t,e)=>e==="number"||!Number.isNaN(Number(t))&&!Number.isNaN(Number.parseFloat(t)),parse:(t)=>{let e=Number(t);if(Number.isNaN(e))throw TypeError(`Cannot parse "${t}" as number`);return e}},{name:"array",canParse:(t,e)=>e==="array"||t.startsWith("[")||t.includes(","),parse:(t)=>{try{let e=JSON.parse(t);if(Array.isArray(e))return e}catch{}return t.split(",").map((e)=>e.trim())}},{name:"json",canParse:(t,e)=>e==="object"||(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")),parse:(t)=>{try{return JSON.parse(t)}catch(e){throw Error(`Cannot parse "${t}" as JSON: ${e}`)}}}]}async applyEnvironmentVariables(t,e,n={}){let{prefix:r,useCamelCase:i=!0,useBackwardCompatibility:c=!0,customParsers:d={},verbose:a=!1,trackPerformance:l=!0}=n,o=async()=>{if(!t)return{config:e,source:{type:"environment",priority:50,timestamp:new Date}};let u=r||this.generateEnvPrefix(t),f={...e};return this.processObject(f,[],u,{useCamelCase:i,useBackwardCompatibility:c,customParsers:d,verbose:a,configName:t}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return Gi.track("applyEnvironmentVariables",o,{configName:t});return o()}generateEnvPrefix(t){return t.toUpperCase().replace(/-/g,"_")}formatEnvKey(t,e){if(!e)return t.toUpperCase();return t.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(t,e,n,r){for(let[i,c]of Object.entries(t)){let d=[...e,i],a=d.map((u)=>this.formatEnvKey(u,r.useCamelCase)),l=`${n}_${a.join("_")}`,o=r.useBackwardCompatibility?`${n}_${d.map((u)=>u.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.processObject(c,d,n,r);else{let u=cd.env[l]||(o?cd.env[o]:void 0);if(u!==void 0){if(r.verbose){let f=cd.env[l]?l:o}try{t[i]=this.parseEnvironmentValue(u,typeof c,l,r.customParsers,r.configName)}catch(f){if(f instanceof Od)throw f;throw mn.envVar(l,u,typeof c,r.configName)}}}}}parseEnvironmentValue(t,e,n,r,i){for(let[c,d]of Object.entries(r))try{return d(t)}catch{continue}for(let c of this.defaultParsers)if(c.canParse(t,e))try{return c.parse(t)}catch{throw mn.envVar(n,t,`${e} (via ${c.name} parser)`,i)}return t}getEnvironmentVariables(t){let e={},n=t.toUpperCase();for(let[r,i]of Object.entries(cd.env))if(r.startsWith(n)&&i!==void 0)e[r]=i;return e}validateEnvironmentVariable(t,e,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))r.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(t,e,n,{})}catch(i){r.push(`Cannot parse value "${e}" as ${n}: ${i}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(t,e,n={}){let{prefix:r,format:i="text"}=n,c=r||this.generateEnvPrefix(t),d=[];switch(this.extractEnvVarInfo(e,[],c,d),i){case"markdown":return this.formatAsMarkdown(d,t);case"json":return JSON.stringify(d,null,2);default:return this.formatAsText(d,t)}}extractEnvVarInfo(t,e,n,r){for(let[i,c]of Object.entries(t)){let d=[...e,i],a=`${n}_${d.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.extractEnvVarInfo(c,d,n,r);else r.push({key:a,type:Array.isArray(c)?"array":typeof c,description:`Configuration for ${d.join(".")}`,example:this.generateExample(c)})}}generateExample(t){if(Array.isArray(t))return JSON.stringify(t);if(typeof t==="object"&&t!==null)return JSON.stringify(t);return String(t)}formatAsText(t,e){let n=`Environment Variables for ${e}:
|
|
78
|
-
|
|
79
|
-
`;for(let r of t)n+=`${r.key}
|
|
80
|
-
`,n+=` Type: ${r.type}
|
|
81
|
-
`,n+=` Description: ${r.description}
|
|
82
|
-
`,n+=` Example: ${r.example}
|
|
83
|
-
|
|
84
|
-
`;return n}formatAsMarkdown(t,e){let n=`# Environment Variables for ${e}
|
|
85
|
-
|
|
86
|
-
`;n+=`| Variable | Type | Description | Example |
|
|
87
|
-
`,n+=`|----------|------|-------------|----------|
|
|
88
|
-
`;for(let r of t)n+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
|
|
89
|
-
`;return n}}function vA(t,e){let n=mh("process");if(typeof n>"u"||!n.env)return e;let r=n.env[t];return r!==void 0?r:e}function Yh(t,e,n={}){return Xh(t,e,n,new WeakMap)}function Xh(t,e,n,r){let{arrayMergeMode:i="replace",skipNullish:c=!1,customMerger:d}=n;if(e===null||e===void 0)return c?t:e;if(d){let a=d(t,e);if(a!==void 0)return a}if(Array.isArray(e)||Array.isArray(t))return Kh(t,e,i,r);if(!be(e)||!be(t))return e;return JA(t,e,n,r)}function Kh(t,e,n,r){if(Array.isArray(e)&&!Array.isArray(t))return e;if(Array.isArray(t)&&!Array.isArray(e))return e;if(Array.isArray(e)&&Array.isArray(t))switch(n){case"replace":return e;case"concat":return kA(t,e);case"smart":return CA(t,e,r);default:return e}return e}function kA(t,e){let n=[...e];for(let r of t)if(!n.some((i)=>ls(i,r)))n.push(r);return n}function CA(t,e,n){if(e.length===0)return t;if(t.length===0)return e;if(be(e[0])&&be(t[0]))return OA(t,e,n);if(e.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...e];for(let i of t)if(!r.includes(i))r.push(i);return r}return e}function OA(t,e,n){let r=[...e];for(let i of t){if(!be(i)){r.push(i);continue}let c=["id","name","key","path","type"],d=!1;for(let a of c)if(a in i){if(r.find((o)=>be(o)&&(a in o)&&o[a]===i[a])){d=!0;break}}if(!d)r.push(i)}return r}function JA(t,e,n,r){let i=e;if(be(i)&&r.has(i))return r.get(i);let c={...t};if(be(i))r.set(i,c);for(let d in i){if(!Object.prototype.hasOwnProperty.call(i,d))continue;let a=i[d],l=c[d];if(n.skipNullish&&(a===null||a===void 0))continue;if(a===null||a===void 0){c[d]=a;continue}if(be(a)&&be(l))c[d]=Xh(l,a,n,r);else if(Array.isArray(a)||Array.isArray(l))c[d]=Kh(l,a,n.arrayMergeMode||"smart",r);else c[d]=a}return c}function $s(t,e,n="replace"){return Yh(t,e,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function ls(t,e){if(t===e)return!0;if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(!ls(t[n],e[n]))return!1;return!0}if(be(t)&&be(e)){let n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;for(let i of n){if(!Object.prototype.hasOwnProperty.call(e,i))return!1;if(!ls(t[i],e[i]))return!1}return!0}return!1}function be(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class Wd{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,e,n={}){let{arrayStrategy:r="replace",useCache:i=!0,cacheTtl:c,trackPerformance:d=!0,verbose:a=!1}=n;if(i){let o=li.getWithFileCheck("file",t);if(o){if(a)console.log(`Configuration loaded from cache: ${t}`);return o}}let l=async()=>{if(!dd(t))return null;try{let o=`?t=${Date.now()}`,u=await import(t+o),f=u.default||u,R="default"in u,E=Object.keys(u).length>0;if(!R&&!E)throw new Mi(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new Mi(t,Error("Configuration must export a valid object"),"unknown");let C={config:$s(e,f,r),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(i)li.setWithFileCheck("file",C,t,c);return C}catch(o){throw o instanceof Error?mn.configLoad(t,o):mn.configLoad(t,Error(String(o)))}};if(d)return Gi.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,e,n={}){for(let r of t)try{let i=await this.loadFromPath(r,e,n);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(n.verbose)console.warn(`Failed to load config from ${r}:`,i)}return null}generateConfigPaths(t,e,n){let r=this.generateNamePatterns(t,n),i=[];for(let c of r)for(let d of this.extensions)i.push(Ka(e,`${c}${d}`));return i}generateNamePatterns(t,e){let n=[];if(n.push("config",".config"),t)n.push(t,`.${t}.config`,`${t}.config`,`.${t}`);if(e){if(n.push(e,`.${e}.config`,`${e}.config`,`.${e}`),t)n.push(`${t}.${e}.config`,`.${t}.${e}.config`)}return n.filter(Boolean)}checkFileAccess(t){return Gh(async()=>{return dd(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,e,n){let r=[];if(!dd(t))return r;if(e||n){let i=this.generateNamePatterns(e||"",n);for(let c of i)for(let d of this.extensions){let a=Ka(t,`${c}${d}`);if(await this.checkFileAccess(a))r.push(a)}}else try{let{readdirSync:i}=await import("fs"),c=i(t);for(let d of c)if(this.looksLikeConfigFile(d)){let a=Ka(t,d);if(await this.checkFileAccess(a))r.push(a)}}catch{return[]}return r}looksLikeConfigFile(t){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((n)=>n.test(t))}async validateConfigFile(t){let e=[];try{if(!dd(t))return e.push("Configuration file does not exist"),e;let n=await import(t),r=n.default||n;if(r===void 0)e.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)e.push("Configuration must be an object");else if(Array.isArray(r))e.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),c=i(t,"utf8");JSON.parse(c)}catch(i){e.push(`Invalid JSON syntax: ${i}`)}}catch(n){e.push(`Failed to load configuration file: ${n}`)}return e}async getFileModificationTime(t){try{let{statSync:e}=await import("fs");return e(t).mtime}catch{return null}}async preloadConfigurations(t,e={}){let n=new Map;return await Promise.allSettled(t.map(async(r)=>{try{let i=await this.loadFromPath(r,{},e);if(i)n.set(r,i.config)}catch(i){if(e.verbose)console.warn(`Failed to preload ${r}:`,i)}})),n}}class vs{async validateConfiguration(t,e,n={}){let{stopOnFirstError:r=!1,validateRequired:i=!0,validateTypes:c=!0,customRules:d=[],trackPerformance:a=!0,verbose:l=!1}=n,o=async()=>{let u=[],f=[],R={stopOnFirstError:r,validateRequired:i,validateTypes:c,customRules:d,trackPerformance:a,verbose:l};try{if(typeof e==="string")return await this.validateWithSchemaFile(t,e,R);else if(Array.isArray(e))return this.validateWithRules(t,[...e,...d],R);else return this.validateWithJSONSchema(t,e,R)}catch(E){return u.push({path:"",message:`Validation failed: ${E}`,rule:"system"}),{isValid:!1,errors:u,warnings:f}}};if(a)return await Gi.track("validateConfiguration",o);return o()}async validateWithSchemaFile(t,e,n){try{if(!Qw(e))throw new Qi(e,[{path:"",message:"Schema file does not exist"}]);let r=await import(e),i=r.default||r;if(Array.isArray(i))return this.validateWithRules(t,i,n);else return this.validateWithJSONSchema(t,i,n)}catch(r){throw new Qi(e,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(t,e,n){let r=[],i=[];return this.validateObjectAgainstSchema(t,e,"",r,i,n),{isValid:r.length===0,errors:r,warnings:i}}validateObjectAgainstSchema(t,e,n,r,i,c){if(c.validateTypes&&e.type){let d=Array.isArray(t)?"array":typeof t,a=Array.isArray(e.type)?e.type:[e.type];if(!a.includes(d)){if(r.push({path:n,message:`Expected type ${a.join(" or ")}, got ${d}`,expected:a.join(" or "),actual:d,rule:"type"}),c.stopOnFirstError)return}}if(e.enum&&!e.enum.includes(t)){if(r.push({path:n,message:`Value must be one of: ${e.enum.join(", ")}`,expected:e.enum.join(", "),actual:t,rule:"enum"}),c.stopOnFirstError)return}if(typeof t==="string"){if(e.minLength!==void 0&&t.length<e.minLength)r.push({path:n,message:`String length must be at least ${e.minLength}`,expected:`>= ${e.minLength}`,actual:t.length,rule:"minLength"});if(e.maxLength!==void 0&&t.length>e.maxLength)r.push({path:n,message:`String length must not exceed ${e.maxLength}`,expected:`<= ${e.maxLength}`,actual:t.length,rule:"maxLength"});if(e.pattern){if(!new RegExp(e.pattern).test(t))r.push({path:n,message:`String does not match pattern ${e.pattern}`,expected:e.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(e.minimum!==void 0&&t<e.minimum)r.push({path:n,message:`Value must be at least ${e.minimum}`,expected:`>= ${e.minimum}`,actual:t,rule:"minimum"});if(e.maximum!==void 0&&t>e.maximum)r.push({path:n,message:`Value must not exceed ${e.maximum}`,expected:`<= ${e.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&e.items)for(let d=0;d<t.length;d++){let a=n?`${n}[${d}]`:`[${d}]`;if(this.validateObjectAgainstSchema(t[d],e.items,a,r,i,c),c.stopOnFirstError&&r.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let d=t;if(c.validateRequired&&e.required){for(let a of e.required)if(!(a in d)){if(r.push({path:n?`${n}.${a}`:a,message:`Missing required property '${a}'`,expected:"required",rule:"required"}),c.stopOnFirstError)return}}if(e.properties){for(let[a,l]of Object.entries(e.properties))if(a in d){let o=n?`${n}.${a}`:a;if(this.validateObjectAgainstSchema(d[a],l,o,r,i,c),c.stopOnFirstError&&r.length>0)return}}if(e.additionalProperties===!1){let a=new Set(Object.keys(e.properties||{}));for(let l of Object.keys(d))if(!a.has(l))i.push({path:n?`${n}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,e,n){let r=[],i=[];for(let c of e)try{let d=this.getValueByPath(t,c.path),a=this.validateWithRule(d,c,c.path);if(r.push(...a),n.stopOnFirstError&&r.length>0)break}catch(d){r.push({path:c.path,message:`Rule validation failed: ${d}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:i}}validateWithRule(t,e,n){let r=[];if(e.required&&(t===void 0||t===null))return r.push({path:n,message:e.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(t===void 0||t===null)return r;if(e.type){let i=Array.isArray(t)?"array":typeof t;if(i!==e.type)r.push({path:n,message:e.message||`Expected type ${e.type}, got ${i}`,expected:e.type,actual:i,rule:"type"})}if(e.min!==void 0){let i=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(i<e.min)r.push({path:n,message:e.message||`Value must be at least ${e.min}`,expected:`>= ${e.min}`,actual:i,rule:"min"})}if(e.max!==void 0){let i=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(i>e.max)r.push({path:n,message:e.message||`Value must not exceed ${e.max}`,expected:`<= ${e.max}`,actual:i,rule:"max"})}if(e.pattern&&typeof t==="string"){if(!e.pattern.test(t))r.push({path:n,message:e.message||`Value does not match pattern ${e.pattern}`,expected:e.pattern.toString(),actual:t,rule:"pattern"})}if(e.enum&&!e.enum.includes(t))r.push({path:n,message:e.message||`Value must be one of: ${e.enum.join(", ")}`,expected:e.enum.join(", "),actual:t,rule:"enum"});if(e.validator){let i=e.validator(t);if(i)r.push({path:n,message:e.message||i,rule:"custom"})}return r}getValueByPath(t,e){if(!e)return t;let n=e.split("."),r=t;for(let i of n)if(r&&typeof r==="object"&&i in r)r=r[i];else return;return r}generateRulesFromInterface(t){let e=[],n=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,i,c,d]=r;e.push({path:i,required:!c,type:this.mapTypeScriptType(d)})}return e}mapTypeScriptType(t){switch(t.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:rS},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class ks{fileLoader=new Wd;envProcessor=new bd;validator=new vs;async loadConfig(t){let e=Date.now(),{cache:n,performance:r,schema:i,validate:c,...d}=t;try{if(n?.enabled){let l=this.checkCache(d.name||"",d);if(l)return l}let a;try{a=await this.loadConfigurationStrategies(d,!0,n)}catch(l){let o=d.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if(o)throw l;a={...await this.applyEnvironmentVariables(d.name||"",d.defaultConfig,d.checkEnv!==!1,d.verbose||!1),warnings:[`No configuration file found for "${d.name||"config"}", using defaults with environment variables`]}}else if(l instanceof Error&&l.name==="ConfigLoadError"){let u=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),f=!u&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),R=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if(o&&(R||u))throw l;if(f&&(!o||!R))a={...await this.applyEnvironmentVariables(d.name||"",d.defaultConfig,d.checkEnv!==!1,d.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!o)a={...await this.applyEnvironmentVariables(d.name||"",d.defaultConfig,d.checkEnv!==!1,d.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else a={...await this.applyEnvironmentVariables(d.name||"",d.defaultConfig,d.checkEnv!==!1,d.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(i||c)await this.validateConfiguration(a.config,i,c,d.name);if(n?.enabled&&a)this.cacheResult(d.name||"",a,n,d);if(r?.enabled){let l={operation:"loadConfig",duration:Date.now()-e,configName:d.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(l);if(r.slowThreshold&&l.duration>r.slowThreshold)xe.warn(`Slow configuration loading detected: ${l.duration}ms for ${d.name}`);a.metrics=l}return a}catch(a){let l=Date.now()-e;throw xe.error(`Configuration loading failed after ${l}ms:`,[a instanceof Error?a:Error(String(a))]),a}}async loadConfigurationStrategies(t,e=!1,n){let{name:r="",alias:i,cwd:c,configDir:d,defaultConfig:a,checkEnv:l=!0,arrayStrategy:o="replace",verbose:u=!1}=t,f=c||Dr.cwd(),R=[],E=await this.loadLocalConfiguration(r,i,f,d,a,o,u,l,n);if(E)return R.push(...this.getLocalSearchPaths(r,i,f,d)),this.finalizeResult(E,R,l,r,u);let y=await this.loadHomeConfiguration(r,i,a,o,u,l);if(y)return R.push(...this.getHomeSearchPaths(r,i)),this.finalizeResult(y,R,l,r,u);let $=await this.loadPackageJsonConfiguration(r,i,f,a,o,u,l);if($)return R.push(Re(f,"package.json")),this.finalizeResult($,R,l,r,u);if(R.push(...this.getAllSearchPaths(r,i,f,d)),e)throw mn.configNotFound(r,R,i);return{...await this.applyEnvironmentVariables(r,a,l,u),warnings:[`No configuration file found for "${r}"${i?` or alias "${i}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(t,e,n,r,i,c,d,a,l){let o=a?Ni(t,i,d):i,u=this.getLocalDirectories(n,r);for(let f of u){if(d)xe.info(`Searching for configuration in: ${f}`);let R=this.fileLoader.generateConfigPaths(t,f,e),E=await this.fileLoader.tryLoadFromPaths(R,o,{arrayStrategy:c,verbose:d,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(E){if(d)xe.success(`Configuration loaded from: ${E.source.path}`);return E}}return null}async loadHomeConfiguration(t,e,n,r,i,c){if(!t)return null;let d=c?Ni(t,n,i):n,a=[Re(ti(),".config",t),Re(ti(),".config"),ti()];for(let l of a){if(i)xe.info(`Checking home directory: ${l}`);let o=this.fileLoader.generateConfigPaths(t,l,e),u=await this.fileLoader.tryLoadFromPaths(o,d,{arrayStrategy:r,verbose:i});if(u){if(i)xe.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(t,e,n,r,i,c,d){let a=d?Ni(t,r,c):r;try{let l=Re(n,"package.json");if(!as(l))return null;let o=await import(l),u=o[t],f=t;if(!u&&e)u=o[e],f=e;if(u&&typeof u==="object"&&!Array.isArray(u)){if(c)xe.success(`Configuration loaded from package.json: ${f}`);return{config:$s(a,u,i),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(c)xe.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,e,n,r){if(!n||!t||typeof e!=="object"||e===null||Array.isArray(e))return{config:e,source:{type:"default",priority:10,timestamp:new Date}};return{config:Ni(t,e,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,e,n,r,i){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,e,n,r){let i=[];if(n){let c=n(t);if(c)i.push(...c)}if(e){let c=await this.validator.validateConfiguration(t,e);if(!c.isValid)i.push(...c.errors.map((d)=>d.path?`${d.path}: ${d.message}`:d.message))}if(i.length>0)throw mn.configValidation(r||"unknown",i,r)}checkCache(t,e){let n=this.generateCacheKey(t,e);return li.get(n)||null}cacheResult(t,e,n,r){let i=this.generateCacheKey(t,r);li.set(i,e,void 0,n.ttl)}generateCacheKey(t,e){let n=[t];if(e.alias)n.push(`alias:${e.alias}`);if(e.cwd)n.push(`cwd:${e.cwd}`);if(e.configDir)n.push(`configDir:${e.configDir}`);if("checkEnv"in e)n.push(`checkEnv:${e.checkEnv}`);return n.join("|")}getLocalDirectories(t,e){return Array.from(new Set([t,Re(t,"config"),Re(t,".config"),e?Re(t,e):void 0].filter(Boolean)))}getAllSearchPaths(t,e,n,r){let i=[];return i.push(...this.getLocalSearchPaths(t,e,n,r)),i.push(...this.getHomeSearchPaths(t,e)),i.push(Re(n,"package.json")),i}getLocalSearchPaths(t,e,n,r){let i=this.getLocalDirectories(n,r),c=[];for(let d of i)c.push(...this.fileLoader.generateConfigPaths(t,d,e));return c}getHomeSearchPaths(t,e){if(!t)return[];let n=[Re(ti(),".config",t),Re(ti(),".config"),ti()],r=[];for(let i of n)r.push(...this.fileLoader.generateConfigPaths(t,i,e));return r}async loadConfigWithResult(t){return this.loadConfig(t)}}function vh(t){let n=!(t.message.includes("EACCES")||t.message.includes("EPERM")||t.message.includes("permission denied"))&&(t.message.includes("syntax")||t.message.includes("Expected")||t.message.includes("Unexpected")||t.message.includes("BuildMessage")),r=t.message.includes("Configuration must export a valid object")||t.message.includes("Configuration file is empty and exports nothing");return n||r}async function BA(t){return Pn.loadConfig({...t,__strictErrorHandling:!0})}async function ph(t){let e="defaultConfig"in t&&t.defaultConfig!==void 0?t.defaultConfig:{},n="cache"in t||"performance"in t||"schema"in t||"validate"in t;try{let r;if(n)r=await Pn.loadConfig(t);else r=await Pn.loadConfig({...t,defaultConfig:e,cache:{enabled:!0},performance:{enabled:!1}});return r?.config??e}catch(r){let i=r instanceof Error?r.name:"UnknownError",c=r instanceof Error?r.message:String(r);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||c.includes("config"))&&t.verbose)xe.warn("Unexpected error loading config, using defaults:",[r instanceof Error?r:Error(String(r))]);let a=n?{...t,defaultConfig:e}:{...t,defaultConfig:e,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in t?t.checkEnv!==!1:!0)return(await Pn.applyEnvironmentVariables(a.name||"",e,!0,a.verbose||!1))?.config??e;return e}}async function zA(t={defaultConfig:{}}){if(typeof t==="string"){let{cwd:e}=await import("process");try{return(await Pn.loadConfig({name:t,cwd:e(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(n){if(n instanceof Error&&(n.name==="ConfigNotFoundError"||n.name==="ConfigLoadError"&&vh(n)))return(await Pn.applyEnvironmentVariables(t,{},!0,!1)).config;throw n}}try{return(await Pn.loadConfig({...t,cwd:t.cwd||Dr.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(e){if(e instanceof Error&&(e.name==="ConfigNotFoundError"||e.name==="ConfigLoadError"&&vh(e)))return(await Pn.applyEnvironmentVariables(t.name||"",t.defaultConfig||{},t.checkEnv!==!1,t.verbose||!1)).config;throw e}}async function TA(t,e,n="replace"){let r=new Wd;try{let i=await r.loadFromPath(t,e,{arrayStrategy:n,useCache:!1,trackPerformance:!1});return i?i.config:null}catch{return null}}function Ni(t,e,n=!1){let r=new bd,i=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function c(d,a=[]){let l={...d};for(let[o,u]of Object.entries(d)){let f=[...a,o],R=[`${i}_${f.join("_").toUpperCase()}`,`${i}_${f.map(($)=>$.toUpperCase()).join("")}`,`${i}_${f.map(($)=>$.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],E,y;for(let $ of R)if(E=Dr.env[$],E!==void 0){y=$;break}if(E!==void 0&&y)if(typeof u==="boolean")l[o]=["true","1","yes"].includes(E.toLowerCase());else if(typeof u==="number"){let $=Number(E);if(!Number.isNaN($))l[o]=$}else if(Array.isArray(u))try{l[o]=JSON.parse(E)}catch{l[o]=E.split(",").map(($)=>$.trim())}else l[o]=E;else if(u&&typeof u==="object"&&!Array.isArray(u))l[o]=c(u,f)}return l}return c(e)}function bA(t){let e=Re(Dr.cwd(),t.configDir),n=Re(Dr.cwd(),t.generatedDir),r=Re(n,"config-types.ts");if(!as(rh(r)))Dw(rh(r),{recursive:!0,mode:511});let i=as(e)?yw(e).map((d)=>d.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],c=`// Generated by bunfig v${s0}
|
|
90
|
-
export type ConfigNames = ${i.length?`'${i.join("' | '")}'`:"string"}
|
|
91
|
-
`;Pw(r,c,{mode:438})}function WA(t){let e=null,n=null,r=()=>{if(!n)n=ph(t).then((c)=>{return e=c,c},(c)=>{let d="defaultConfig"in t?t.defaultConfig:{};if(e=d,"verbose"in t&&t.verbose)xe.warn("Config loading failed, using defaults:",[c instanceof Error?c:Error(String(c))]);return d});return n},i="defaultConfig"in t?t.defaultConfig:{};return e=i,r(),new Proxy({},{get(c,d){if(e)return e[d];let a=i[d];return r(),a},has(c,d){return d in(e||i)},ownKeys(){return Object.keys(e||i)},getOwnPropertyDescriptor(c,d){return Object.getOwnPropertyDescriptor(e||i,d)},set(c,d,a){if(!e)e={...i};return e[d]=a,!0}})}function UA(t){let e=Eh(Yw.cwd(),t?.configDir||"./config");function n(){if(!Gw(e))return[];let i=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),c=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],d=Zw(e).filter((l)=>i.has(pa(l))).map((l)=>({base:l.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:l})),a=new Map;for(let{base:l,file:o}of d){let u=pa(o).toLowerCase(),f=a.get(l);if(!f){a.set(l,o);continue}let R=pa(f).toLowerCase();if(c.indexOf(u)<c.indexOf(R))a.set(l,o)}return Array.from(a.entries()).map(([l,o])=>({base:l,file:o})).sort((l,o)=>l.base.localeCompare(o.base))}function r(){let i=n(),c=i.map((o)=>o.base),d=c.length?c.map((o)=>`'${o}'`).join(" | "):"string",a=i.length?`{
|
|
92
|
-
${i.map((o)=>{let u=Eh(e,o.file).replace(/\\/g,"/");return` '${o.base}': typeof import('${u}').default`}).join(`,
|
|
93
|
-
`)}
|
|
94
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${d}
|
|
95
|
-
export type ConfigByName = ${a}
|
|
96
|
-
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
97
|
-
export type ConfigOf = Config
|
|
98
|
-
`}return{name:"bunfig-plugin",setup(i){i.onResolve({filter:/^virtual:bunfig-types$/},(c)=>{return{path:c.path,namespace:"bunfig-virtual"}}),i.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:r(),loader:"ts"}})}}}var mh,li,Gi,qh,jA,HA,kh,fd,gs,te,$t,LA,Ch,FA,Oh,VA,NA,es,xA,Jh,Bh,ns,MA,QA,GA,ZA,_d,tS,YA,ee,XA,KA,zh,Rd,us,Mt,Rt,pA,Th,mA,bh,qA,t0,rs,e0,Wh,Uh,n0,is,r0,i0,c0,d0,o0,Ed,eS,a0,s0="0.15.6",ke,Cd,Mi,hs,Ss,Od,fs,_s,Qi,Rs,Es,mn,nS,rS,xe,Pn,iS,cS,l0=lA(async()=>{mh=import.meta.require,li=new As,Gi=new Ds,qh={createKey:gA,isEquivalent:uA,estimateMemoryUsage:hA},jA=Dd(ss.cwd(),"config"),HA=Dd(ss.cwd(),"src/generated"),kh=Ad.env.CLARITY_LOG_DIR||kw(_A(),"logs"),fd={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:kh,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},gs=await RA(),te={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,reset:"\x1B[0m"},$t=te,LA=te.red,Ch=te.green,FA=te.yellow,Oh=te.blue,VA=te.magenta,NA=te.cyan,es=te.white,xA=te.gray,Jh=te.bgRed,Bh=te.bgYellow,ns=te.bold,MA=te.dim,QA=te.italic,GA=te.underline,ZA=te.reset,_d={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},tS={debug:"\uD83D\uDD0D",info:Oh("ℹ"),success:Ch("✓"),warning:Bh(es(ns(" WARN "))),error:Jh(es(ns(" ERROR ")))},YA=new $d("stacks"),ee=new $d("bunfig",{showTags:!0}),XA=_e(xi.cwd(),"config"),KA=_e(xi.cwd(),"src/generated"),zh=wd.env.CLARITY_LOG_DIR||$w(AA(),"logs"),Rd={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:zh,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},us=await DA(),Mt={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},Rt=Mt,pA=Mt.red,Th=Mt.green,mA=Mt.yellow,bh=Mt.blue,qA=Mt.magenta,t0=Mt.cyan,rs=Mt.white,e0=Mt.gray,Wh=Mt.bgRed,Uh=Mt.bgYellow,n0=Mt.bgGray,is=Mt.bold,r0=Mt.dim,i0=Mt.italic,c0=Mt.underline,d0=Mt.strikethrough,o0=Mt.reset,Ed={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},eS={debug:"\uD83D\uDD0D",info:bh("ℹ"),success:Th("✓"),warning:Uh(rs(is(" WARN "))),error:Wh(rs(is(" ERROR ")))},a0=new kd("stacks"),ke=class extends Error{timestamp;context;constructor(e,n={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=n,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(([n,r])=>`${n}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}},Cd=class extends ke{code="CONFIG_NOT_FOUND";constructor(e,n,r){let i=r?` or alias "${r}"`:"";super(`Configuration "${e}"${i} not found`,{configName:e,alias:r,searchPaths:n,searchPathCount:n.length})}},Mi=class extends ke{code="CONFIG_LOAD_ERROR";constructor(e,n,r){super(`Failed to load configuration from "${e}": ${n.message}`,{configPath:e,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}},hs=class extends ke{code="CONFIG_VALIDATION_ERROR";constructor(e,n,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:n,errorCount:n.length})}},Ss=class extends ke{code="CONFIG_MERGE_ERROR";constructor(e,n,r,i){super(`Failed to merge configuration from "${e}" with "${n}": ${r.message}`,{sourcePath:e,targetPath:n,configName:i,originalError:r.name,originalMessage:r.message});this.cause=r}},Od=class extends ke{code="ENV_VAR_ERROR";constructor(e,n,r,i){super(`Failed to parse environment variable "${e}" with value "${n}" as ${r}`,{envKey:e,envValue:n,expectedType:r,configName:i})}},fs=class extends ke{code="FILE_SYSTEM_ERROR";constructor(e,n,r){super(`File system ${e} failed for "${n}": ${r.message}`,{operation:e,path:n,originalError:r.name,originalMessage:r.message});this.cause=r}},_s=class extends ke{code="TYPE_GENERATION_ERROR";constructor(e,n,r){super(`Failed to generate types from "${e}" to "${n}": ${r.message}`,{configDir:e,outputPath:n,originalError:r.name,originalMessage:r.message});this.cause=r}},Qi=class extends ke{code="SCHEMA_VALIDATION_ERROR";constructor(e,n,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:n,errorCount:n.length})}},Rs=class extends ke{code="BROWSER_CONFIG_ERROR";constructor(e,n,r,i){super(`Failed to fetch configuration from "${e}": ${n} ${r}`,{endpoint:e,status:n,statusText:r,configName:i})}},Es=class extends ke{code="PLUGIN_ERROR";constructor(e,n,r){super(`Plugin "${e}" failed during ${n}: ${r.message}`,{pluginName:e,operation:n,originalError:r.name,originalMessage:r.message});this.cause=r}},mn={configNotFound(t,e,n){return new Cd(t,e,n)},configLoad(t,e,n){return new Mi(t,e,n)},configValidation(t,e,n){return new hs(t,e,n)},configMerge(t,e,n,r){return new Ss(t,e,n,r)},envVar(t,e,n,r){return new Od(t,e,n,r)},fileSystem(t,e,n){return new fs(t,e,n)},typeGeneration(t,e,n){return new _s(t,e,n)},schemaValidation(t,e,n){return new Qi(t,e,n)},browserConfig(t,e,n,r){return new Rs(t,e,n,r)},plugin(t,e,n){return new Es(t,e,n)}},nS={replace:"replace",concat:"concat",smart:"smart"},rS=/^https?:\/\//,xe=new kd("bunfig",{showTags:!0}),Pn=new ks,iS=Re(Dr.cwd(),"config"),cS=Re(Dr.cwd(),"src/generated")});function g0(t,e={}){let n=yd.cwd();while(n.includes("storage"))n=Ih(n,"..");let r=Ih(n,t||"");if(e?.relative)return Kw(yd.cwd(),r);return r}var u0=yd.env.CLARITY_LOG_DIR||Xw(g0(),"logs"),dS={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:u0,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Jd={...dS},IJ=(async()=>{try{let{loadConfig:t}=await l0().then(()=>xh),e=await t({name:"clarity",alias:"logging",defaultConfig:dS,cwd:yd.cwd()});if(e)Object.assign(Jd,e)}catch{}return Jd})();function Qt(){if(yn.env.NODE_ENV==="test"||yn.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function h0(){if(yn.env.NODE_ENV==="test"||yn.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof yn<"u"){let t=yn.type;if(t==="renderer"||t==="worker")return!1;return!!(yn.versions&&(yn.versions.node||yn.versions.bun))}return!1}class oS{async format(t){let e=await h0(),n=await this.getMetadata(e);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:e}=await import("os");return{pid:si.pid,hostname:e(),environment:si.env.NODE_ENV||"development",platform:si.platform,version:si.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:si.env.NODE_ENV||si.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var Yt={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},Et=Yt,wJ=Yt.red,S0=Yt.green,AJ=Yt.yellow,f0=Yt.blue,DJ=Yt.magenta,yJ=Yt.cyan,jh=Yt.white,PJ=Yt.gray,_0=Yt.bgRed,R0=Yt.bgYellow,$J=Yt.bgGray,Hh=Yt.bold,vJ=Yt.dim,kJ=Yt.italic,CJ=Yt.underline,OJ=Yt.strikethrough,JJ=Yt.reset,cs={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},E0={debug:"\uD83D\uDD0D",info:f0("ℹ"),success:S0("✓"),warning:R0(jh(Hh(" WARN "))),error:_0(jh(Hh(" ERROR ")))};class Ud{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(t,e={}){this.name=t,this.config={...Jd},this.options=this.normalizeOptions(e),this.formatter=this.options.formatter||new oS,this.enabled=e.enabled??!0,this.fancy=e.fancy??!0,this.tagFormat=e.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=e.timestampPosition??"right",this.environment=e.environment??ft.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(e);let n={...e},r=e.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),c=this.generateKey();this.currentKeyId=i,this.keys.set(i,c),this.encryptionKeys.set(i,{key:c,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let e={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return e[t]>=e[n]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...cs,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...cs};return{...cs,...t.fingersCrossed}}normalizeOptions(t){let e={format:"json",level:"info",logDirectory:Jd.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...e,...Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=e.level;return n}shouldWriteToFile(){return!Qt()&&this.config.writeToFile===!0}async writeToFile(t){let n=(async()=>{let i,c=0,d=3,a=1000;while(c<d)try{try{try{await eA(this.config.logDirectory,yh.F_OK|yh.W_OK)}catch(o){if(o instanceof Error&&"code"in o)if(o.code==="ENOENT")await nA(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 l=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:wn.from(t);try{if(!od(this.currentLogFile))await ts(this.currentLogFile,"",{mode:420});if(i=Dh(this.currentLogFile,"a",420),tA(i,l,{flag:"a"}),Ah(i),i!==void 0)qa(i),i=void 0;if((await oi(this.currentLogFile)).size===0){if(await ts(this.currentLogFile,l,{flag:"w",mode:420}),(await oi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(o){let u=o;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(c<d-1){let f=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${c+1}/${d}:`,f);let R=a*2**c;await new Promise((E)=>setTimeout(E,R)),c++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(i!==void 0)try{qa(i)}catch(o){console.error("Debug: [writeToFile] Error closing file descriptor:",o)}}}catch(l){if(c===d-1){let u=l,f=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),l}c++;let o=a*2**(c-1);await new Promise((u)=>setTimeout(u,o))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(r,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 ai(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 ai(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return ai(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(Qt())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,e;switch(t.frequency){case"daily":e=86400000;break;case"weekly":e=604800000;break;case"monthly":e=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},e)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let n=typeof e.interval==="number"?e.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,a],[,l])=>l.createdAt.getTime()-a.createdAt.getTime()),c=typeof e.maxKeys==="number"?e.maxKeys:1,d=Math.max(1,c);if(i.length>d)for(let[a]of i.slice(d))this.encryptionKeys.delete(a),this.keys.delete(a)}generateKeyId(){return ma(16).toString("hex")}generateKey(){return ma(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:e}=this.getCurrentKey(),n=ma(16),r=pw("aes-256-gcm",e,n),i=wn.isBuffer(t)?t:wn.from(t,"utf8"),c=r.update(i),d=r.final(),a=c.length+d.length,l=r.getAuthTag(),o=wn.allocUnsafe(16+a+16);return n.copy(o,0),c.copy(o,16),d.copy(o,16+c.length),l.copy(o,16+a),{encrypted:o,iv:n}}async compressData(t){return new Promise((e,n)=>{let r=$h(),i=[];r.on("data",(c)=>i.push(c)),r.on("end",()=>e(wn.from(wn.concat(i)))),r.on("error",n),r.write(t),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let e=this.config.rotation.encrypt;return{...t,...e}}return t}async rotateLog(){if(Qt())return;if(!this.shouldWriteToFile())return;let t=await oi(this.currentLogFile).catch(()=>null);if(!t)return;let e=this.config.rotation;if(typeof e==="boolean")return;if(e.maxSize&&t.size>=e.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await ad(this.config.logDirectory),c=i.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,o)=>{let u=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(o.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),d=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${n}.${d}`;if(await oi(n).catch(()=>null))try{if(await Ph(n,a),e.compress)try{let l=`${a}.gz`;await this.compressLogFile(a,l),await sd(a)}catch(l){console.error("Error compressing rotated file:",l)}if(c.length===0&&!i.some((l)=>l.endsWith(".log.1")))try{let l=`${n}.1`;await ts(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),c=n.replace(/\.log$/,`-${i}.log`);if(await oi(n).catch(()=>null))await Ph(n,c)}if(this.currentLogFile=r,e.maxFiles){let c=(await ad(this.config.logDirectory)).filter((d)=>d.startsWith(this.name)).sort((d,a)=>a.localeCompare(d));for(let d of c.slice(e.maxFiles))await sd(ai(this.config.logDirectory,d))}}}async compressLogFile(t,e){let n=wh(t),r=qw(e),i=$h();await cA(n,i,r)}async handleFingersCrossedBuffer(t,e){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(e);console.log(e)}}shouldLog(t){if(!this.enabled)return!1;let e={debug:0,info:1,success:2,warning:3,error:4};return e[t]>=e[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((e)=>{console.error("Error in pending write operation:",e)});return Promise.resolve()})),od(this.currentLogFile))try{let t=Dh(this.currentLogFile,"r+");Ah(t),qa(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!Qt()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await ad(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of e)try{await sd(ai(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?Et.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Qt())return!1;let t=typeof ft.env.NO_COLOR<"u",e=ft.env.FORCE_COLOR==="0";if(t||e)return!1;return!!(typeof ft.stderr<"u"&&ft.stderr.isTTY||typeof ft.stdout<"u"&&ft.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:e,icon:n="",tag:r="",message:i,level:c,showTimestamp:d=!0}=t,a=(E)=>E.replace(this.ANSI_PATTERN,"");if(!this.fancy){let E=[];if(d)E.push(e);if(c==="warning")E.push("WARN");else if(c==="error")E.push("ERROR");else if(n)E.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)E.push(r.replace(/[[\]]/g,""));return E.push(i),E.join(" ")}let l=ft.stdout.columns||120,o="";if(c==="warning"||c==="error")o=`${n} ${i}`;else if(c==="info"||c==="success")o=`${n} ${r} ${i}`;else o=`${n} ${r} ${Et.cyan(i)}`;if(!d)return o.trim();let u=a(o).trim().length,f=a(e).length,R=Math.max(1,l-2-u-f);return`${o.trim()}${" ".repeat(R)}${e}`}formatMessage(t,e){if(e.length===1&&Array.isArray(e[0]))return t.replace(/\{(\d+)\}/g,(c,d)=>{let a=Number.parseInt(d,10);return a<e[0].length?String(e[0][a]):c});let n=/%([sdijfo%])/g,r=0,i=t.replace(n,(c,d)=>{if(d==="%")return"%";if(r>=e.length)return c;let a=e[r++];switch(d){case"s":return String(a);case"d":case"i":return Number(a).toString();case"j":case"o":return JSON.stringify(a,null,2);default:return c}});if(r<e.length)i+=` ${e.slice(r).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return i}formatMarkdown(t){if(!t)return t;let e=t;return e=e.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,i)=>{let c=Et.underline(Et.blue(r)),d=this.toAbsoluteFilePath(i);if(d&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let a=`file://${encodeURI(d)}`,l="\x1B]8;;",o="\x1B\\";return`\x1B]8;;${a}\x1B\\${c}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${c}\x1B]8;;\x1B\\`;return c}),e=e.replace(/`([^`]+)`/g,(n,r)=>Et.bgGray(r)),e=e.replace(/\*\*([^*]+)\*\*/g,(n,r)=>Et.bold(r)),e=e.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>Et.italic(r)),e=e.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>Et.italic(r)),e=e.replace(/~([^~]+)~/g,(n,r)=>Et.strikethrough(r)),e}supportsHyperlinks(){if(Qt())return!1;let t=ft.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let e=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(e)&&e>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let e=t;if(e.startsWith("file://"))e=e.replace(/^file:\/\//,"");if(e.startsWith("~")){let n=ft.env.HOME||"";if(n)e=e.replace(/^~(?=$|\/)/,n)}if(rA(e)||e.startsWith("./")||e.startsWith("../"))e=iA(e);else return null;return od(e)?e:null}catch{return null}}buildOutputTexts(t){let e=this.shouldStyleConsole()?this.formatMarkdown(t):t,n=t.replace(this.ANSI_PATTERN,"");return{consoleText:e,fileText:n}}async log(t,e,...n){if(!this.shouldLog(t))return;let r=new Date,i=this.formatConsoleTimestamp(r),c=this.formatFileTimestamp(r),d,a;if(e instanceof Error)d=e.message,a=e.stack;else d=this.formatMessage(e,n);let{consoleText:l,fileText:o}=this.buildOutputTexts(d);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":E0[t],R=this.options.showTags!==!1&&this.name?Et.gray(this.formatTag(this.name)):"",E;switch(t){case"debug":E=this.formatConsoleMessage({timestamp:i,icon:f,tag:R,message:Et.gray(l),level:t}),console.error(E);break;case"info":E=this.formatConsoleMessage({timestamp:i,icon:f,tag:R,message:l,level:t}),console.warn(E);break;case"success":E=this.formatConsoleMessage({timestamp:i,icon:f,tag:R,message:Et.green(l),level:t}),console.error(E);break;case"warning":E=this.formatConsoleMessage({timestamp:i,icon:f,tag:R,message:l,level:t}),console.warn(E);break;case"error":if(E=this.formatConsoleMessage({timestamp:i,icon:f,tag:R,message:l,level:t}),console.error(E),a){let y=a.split(`
|
|
99
|
-
`);for(let $ of y)if($.trim()&&!$.includes(d))console.error(this.formatConsoleMessage({timestamp:i,message:Et.gray(` ${$}`),level:t,showTimestamp:!1}))}break}}else if(!Qt()){if(console.error(`${c} ${this.environment}.${t.toUpperCase()}: ${d}`),a)console.error(a)}let u=`${c} ${this.environment}.${t.toUpperCase()}: ${o}
|
|
100
|
-
`;if(a)u+=`${a}
|
|
101
|
-
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(t,e=""){let n={update:(a,l)=>{},finish:(a)=>{},interrupt:(a,l)=>{}};if(!this.enabled)return n;let r=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:e||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!Qt()&&ft.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(a,l)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,a),this.activeProgressBar.total),l!==void 0)this.activeProgressBar.message=l;if(this.shouldStyleConsole()&&!Qt()&&ft.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(a)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,a)},interrupt:(a,l="info")=>{if(!Qt()&&ft.stdout.isTTY)ft.stdout.write(`
|
|
102
|
-
`);if(this[l==="warning"?"warn":l](a),this.activeProgressBar&&this.shouldStyleConsole()&&!Qt()&&ft.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let e=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?Et.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":Et.blue("◐"),tag:n,message:`${Et.cyan(t)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),i=Math.round(r-e),c=`${t} completed in ${i}ms`,d=new Date,a=this.formatConsoleTimestamp(d),o=`${this.formatFileTimestamp(d)} ${this.environment}.INFO: ${c}`;if(n)o+=` ${JSON.stringify(n)}`;if(o+=`
|
|
103
|
-
`,o=o.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?Et.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:this.options.showIcons===!1?"":Et.green("✓"),tag:u,message:`${c}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!Qt())console.error(o.trim());if(this.shouldWriteToFile())await this.writeToFile(o)}}async debug(t,...e){await this.log("debug",t,...e)}async info(t,...e){await this.log("info",t,...e)}async success(t,...e){await this.log("success",t,...e)}async warn(t,...e){await this.log("warning",t,...e)}async error(t,...e){await this.log("error",t,...e)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:e}=t;return!!e}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let e=`${this.name}:${t}`,n=new Ud(e,{...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(n),n}createReadStream(){if(Qt())throw Error("createReadStream is not supported in browser environments");if(!od(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return wh(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let e=this.config.rotation;if(!e.encrypt||typeof e.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=wn.isBuffer(t)?t:wn.from(t,"base64"),i=r.subarray(0,16),c=r.subarray(r.length-16),d=r.subarray(16,r.length-16),a=mw("aes-256-gcm",n,i);a.setAuthTag(c);let l=a.update(d),o=a.final(),u=l.length+o.length,f=wn.allocUnsafe(u);return l.copy(f,0),o.copy(f,l.length),f.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Qt()}isServerMode(){return!Qt()}setTestEncryptionKey(t,e){this.currentKeyId=t,this.keys.set(t,e)}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(t){if(!this.enabled)return;let e=new Date,n=this.formatConsoleTimestamp(e),r=this.formatFileTimestamp(e),{consoleText:i,fileText:c}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let a=i.split(`
|
|
104
|
-
`),l=Math.max(...a.map((R)=>R.length))+2,o=`┌${"─".repeat(l)}┐`,u=`└${"─".repeat(l)}┘`,f=a.map((R)=>{return this.formatConsoleMessage({timestamp:n,message:Et.cyan(R),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:Et.cyan(o),showTimestamp:!1})),f.forEach((R)=>console.error(R)),console.error(this.formatConsoleMessage({timestamp:n,message:Et.cyan(u),showTimestamp:!1}))}else if(!Qt())console.error(`${r} ${this.environment}.INFO: [BOX] ${c}`);let d=`${r} ${this.environment}.INFO: [BOX] ${c}
|
|
105
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(d)}async prompt(t){if(Qt())return Promise.resolve(!0);return new Promise((e)=>{console.error(`${Et.cyan("?")} ${t} (y/n) `);let n=(r)=>{let i=r.toString().trim().toLowerCase();ft.stdin.removeListener("data",n);try{if(typeof ft.stdin.setRawMode==="function")ft.stdin.setRawMode(!1)}catch{}ft.stdin.pause(),console.error(""),e(i==="y"||i==="yes")};try{if(typeof ft.stdin.setRawMode==="function")ft.stdin.setRawMode(!0)}catch{}ft.stdin.resume(),ft.stdin.once("data",n)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...e){if(!this.enabled)return;let n=t;if(e&&e.length>0){let l=/%([sdijfo%])/g,o=0;if(n=t.replace(l,(u,f)=>{if(f==="%")return"%";if(o>=e.length)return u;let R=e[o++];switch(f){case"s":return String(R);case"d":case"i":return Number(R).toString();case"j":case"o":return JSON.stringify(R,null,2);default:return u}}),o<e.length)n+=` ${e.slice(o).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:r,fileText:i}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?Et.gray(this.formatTag(this.name)):"",o=this.options.showIcons===!1?"":`${Et.blue("◐")} `;console.error(`${o}${l} ${Et.cyan(r)}`)}let a=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
|
|
106
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(a)}renderProgressBar(t,e=!1){if(!this.enabled||!this.shouldStyleConsole()||!ft.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),r=Math.round(t.barLength*n/100),i=t.barLength-r,c=Et.green("━".repeat(r)),d=Et.gray("━".repeat(i)),a=`[${c}${d}]`,l=`${n}%`.padStart(4),o=t.message?` ${t.message}`:"",u=this.options.showIcons===!1?"":e||n===100?Et.green("✓"):Et.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${Et.gray(this.formatTag(this.name))}`:"",R=`\r${u}${f} ${a} ${l}${o}`,E=ft.stdout.columns||80,y=" ".repeat(Math.max(0,E-R.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${R}${y}`,ft.stdout.write(t.lastRenderedLine),e)ft.stdout.write(`
|
|
107
|
-
`)}finishProgressBar(t,e){if(!this.enabled||!this.fancy||Qt()||!ft.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(e)t.message=e;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(Qt()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let e=await ad(this.config.logDirectory),n=[];for(let r of e){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let c=ai(this.config.logDirectory,r);if(t.before)try{if((await oi(c)).mtime>=t.before)continue}catch(d){console.error(`Failed to get stats for file ${c}:`,d);continue}n.push(c)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await sd(r),console.warn(`Deleted log file: ${r}`)}catch(i){console.error(`Failed to delete log file ${r}:`,i)}console.warn("Log clearing process finished.")}catch(e){console.error("Error during log clearing process:",e)}}}var BJ=new Ud("stacks");class Me extends Error{timestamp;context;constructor(t,e={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=e,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(([e,n])=>`${e}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}}class aS extends Me{code="CONFIG_NOT_FOUND";constructor(t,e,n){let r=n===void 0?[]:Array.isArray(n)?n.filter(Boolean):[n],i="";if(r.length===1)i=` or alias "${r[0]}"`;else if(r.length>1)i=` or aliases ${r.map((c)=>`"${c}"`).join(", ")}`;super(`Configuration "${t}"${i} not found`,{configName:t,alias:n,searchPaths:e,searchPathCount:e.length})}}class Bd extends Me{code="CONFIG_LOAD_ERROR";constructor(t,e,n){super(`Failed to load configuration from "${t}": ${e.message}`,{configPath:t,configName:n,originalError:e.name,originalMessage:e.message});this.cause=e}}class sS extends Me{code="CONFIG_VALIDATION_ERROR";constructor(t,e,n){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:n,validationErrors:e,errorCount:e.length})}}class lS extends Me{code="CONFIG_MERGE_ERROR";constructor(t,e,n,r){super(`Failed to merge configuration from "${t}" with "${e}": ${n.message}`,{sourcePath:t,targetPath:e,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}}class Cs extends Me{code="ENV_VAR_ERROR";constructor(t,e,n,r){super(`Failed to parse environment variable "${t}" with value "${e}" as ${n}`,{envKey:t,envValue:e,expectedType:n,configName:r})}}class gS extends Me{code="FILE_SYSTEM_ERROR";constructor(t,e,n){super(`File system ${t} failed for "${e}": ${n.message}`,{operation:t,path:e,originalError:n.name,originalMessage:n.message});this.cause=n}}class uS extends Me{code="TYPE_GENERATION_ERROR";constructor(t,e,n){super(`Failed to generate types from "${t}" to "${e}": ${n.message}`,{configDir:t,outputPath:e,originalError:n.name,originalMessage:n.message});this.cause=n}}class zd extends Me{code="SCHEMA_VALIDATION_ERROR";constructor(t,e,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:t,configName:n,validationErrors:e,errorCount:e.length})}}class hS extends Me{code="BROWSER_CONFIG_ERROR";constructor(t,e,n,r){super(`Failed to fetch configuration from "${t}": ${e} ${n}`,{endpoint:t,status:e,statusText:n,configName:r})}}class SS extends Me{code="PLUGIN_ERROR";constructor(t,e,n){super(`Plugin "${t}" failed during ${e}: ${n.message}`,{pluginName:t,operation:e,originalError:n.name,originalMessage:n.message});this.cause=n}}var gi={configNotFound(t,e,n){return new aS(t,e,n)},configLoad(t,e,n){return new Bd(t,e,n)},configValidation(t,e,n){return new sS(t,e,n)},configMerge(t,e,n,r){return new lS(t,e,n,r)},envVar(t,e,n,r){return new Cs(t,e,n,r)},fileSystem(t,e,n){return new gS(t,e,n)},typeGeneration(t,e,n){return new uS(t,e,n)},schemaValidation(t,e,n){return new zd(t,e,n)},browserConfig(t,e,n,r){return new hS(t,e,n,r)},plugin(t,e,n){return new SS(t,e,n)}};async function I0(t,e={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:i=()=>!0,fallback:c}=e,d=Error("Unknown error occurred");for(let a=0;a<=n;a++)try{return await t()}catch(l){if(d=l instanceof Error?l:Error(String(l)),a===n||!i(d))break;if(r>0)await new Promise((o)=>setTimeout(o,r))}if(c!==void 0)return c;throw d instanceof Error?d:Error(`Unknown error: ${String(d)}`)}class Os{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(t,e)=>e==="boolean"||["true","false","1","0","yes","no"].includes(t.toLowerCase()),parse:(t)=>{let e=t.toLowerCase();return["true","1","yes"].includes(e)}},{name:"number",canParse:(t,e)=>e==="number"||!Number.isNaN(Number(t))&&!Number.isNaN(Number.parseFloat(t)),parse:(t)=>{let e=Number(t);if(Number.isNaN(e))throw TypeError(`Cannot parse "${t}" as number`);return e}},{name:"array",canParse:(t,e)=>e==="array"||t.startsWith("[")||t.includes(","),parse:(t)=>{try{let e=JSON.parse(t);if(Array.isArray(e))return e}catch{}return t.split(",").map((e)=>e.trim())}},{name:"json",canParse:(t,e)=>e==="object"||(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")),parse:(t)=>{try{return JSON.parse(t)}catch(e){throw Error(`Cannot parse "${t}" as JSON: ${e}`)}}}]}async applyEnvironmentVariables(t,e,n={}){let{prefix:r,useCamelCase:i=!0,useBackwardCompatibility:c=!0,customParsers:d={},verbose:a=!1,trackPerformance:l=!0}=n,o=async()=>{if(!t)return{config:e,source:{type:"environment",priority:50,timestamp:new Date}};let u=r||this.generateEnvPrefix(t),f={...e};return this.processObject(f,[],u,{useCamelCase:i,useBackwardCompatibility:c,customParsers:d,verbose:a,configName:t}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return ws.track("applyEnvironmentVariables",o,{configName:t});return o()}generateEnvPrefix(t){return t.toUpperCase().replace(/-/g,"_")}formatEnvKey(t,e){if(!e)return t.toUpperCase();return t.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(t,e,n,r){for(let[i,c]of Object.entries(t)){let d=[...e,i],a=d.map((u)=>this.formatEnvKey(u,r.useCamelCase)),l=`${n}_${a.join("_")}`,o=r.useBackwardCompatibility?`${n}_${d.map((u)=>u.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.processObject(c,d,n,r);else{let u=gd.env[l]||(o?gd.env[o]:void 0);if(u!==void 0){if(r.verbose){let f=gd.env[l]?l:o}try{t[i]=this.parseEnvironmentValue(u,typeof c,l,r.customParsers,r.configName)}catch(f){if(f instanceof Cs)throw f;throw gi.envVar(l,u,typeof c,r.configName)}}}}}parseEnvironmentValue(t,e,n,r,i){for(let[c,d]of Object.entries(r))try{return d(t)}catch{continue}for(let c of this.defaultParsers)if(c.canParse(t,e))try{return c.parse(t)}catch{throw gi.envVar(n,t,`${e} (via ${c.name} parser)`,i)}return t}getEnvironmentVariables(t){let e={},n=t.toUpperCase();for(let[r,i]of Object.entries(gd.env))if(r.startsWith(n)&&i!==void 0)e[r]=i;return e}validateEnvironmentVariable(t,e,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))r.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(t,e,n,{})}catch(i){r.push(`Cannot parse value "${e}" as ${n}: ${i}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(t,e,n={}){let{prefix:r,format:i="text"}=n,c=r||this.generateEnvPrefix(t),d=[];switch(this.extractEnvVarInfo(e,[],c,d),i){case"markdown":return this.formatAsMarkdown(d,t);case"json":return JSON.stringify(d,null,2);default:return this.formatAsText(d,t)}}extractEnvVarInfo(t,e,n,r){for(let[i,c]of Object.entries(t)){let d=[...e,i],a=`${n}_${d.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.extractEnvVarInfo(c,d,n,r);else r.push({key:a,type:Array.isArray(c)?"array":typeof c,description:`Configuration for ${d.join(".")}`,example:this.generateExample(c)})}}generateExample(t){if(Array.isArray(t))return JSON.stringify(t);if(typeof t==="object"&&t!==null)return JSON.stringify(t);return String(t)}formatAsText(t,e){let n=`Environment Variables for ${e}:
|
|
108
|
-
|
|
109
|
-
`;for(let r of t)n+=`${r.key}
|
|
110
|
-
`,n+=` Type: ${r.type}
|
|
111
|
-
`,n+=` Description: ${r.description}
|
|
112
|
-
`,n+=` Example: ${r.example}
|
|
113
|
-
|
|
114
|
-
`;return n}formatAsMarkdown(t,e){let n=`# Environment Variables for ${e}
|
|
115
|
-
|
|
116
|
-
`;n+=`| Variable | Type | Description | Example |
|
|
117
|
-
`,n+=`|----------|------|-------------|----------|
|
|
118
|
-
`;for(let r of t)n+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
|
|
119
|
-
`;return n}}function w0(t,e,n={}){return fS(t,e,n,new WeakMap)}function fS(t,e,n,r){let{arrayMergeMode:i="replace",skipNullish:c=!1,customMerger:d}=n;if(e===null||e===void 0)return c?t:e;if(d){let a=d(t,e);if(a!==void 0)return a}if(Array.isArray(e)||Array.isArray(t))return _S(t,e,i,r);if(!We(e)||!We(t))return e;return P0(t,e,n,r)}function _S(t,e,n,r){if(Array.isArray(e)&&!Array.isArray(t))return e;if(Array.isArray(t)&&!Array.isArray(e))return e;if(Array.isArray(e)&&Array.isArray(t))switch(n){case"replace":return e;case"concat":return A0(t,e);case"smart":return D0(t,e,r);default:return e}return e}function A0(t,e){let n=[...e];for(let r of t)if(!n.some((i)=>Is(i,r)))n.push(r);return n}function D0(t,e,n){if(e.length===0)return t;if(t.length===0)return e;if(We(e[0])&&We(t[0]))return y0(t,e,n);if(e.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...e];for(let i of t)if(!r.includes(i))r.push(i);return r}return e}function y0(t,e,n){let r=[...e];for(let i of t){if(!We(i)){r.push(i);continue}let c=["id","name","key","path","type"],d=!1;for(let a of c)if(a in i){if(r.find((o)=>We(o)&&(a in o)&&o[a]===i[a])){d=!0;break}}if(!d)r.push(i)}return r}function P0(t,e,n,r){let i=e;if(We(i)&&r.has(i))return r.get(i);let c={...t};if(We(i))r.set(i,c);for(let d in i){if(!Object.prototype.hasOwnProperty.call(i,d))continue;let a=i[d],l=c[d];if(n.skipNullish&&(a===null||a===void 0))continue;if(a===null||a===void 0){c[d]=a;continue}if(We(a)&&We(l))c[d]=fS(l,a,n,r);else if(Array.isArray(a)||Array.isArray(l))c[d]=_S(l,a,n.arrayMergeMode||"smart",r);else c[d]=a}return c}function RS(t,e,n="replace"){return w0(t,e,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Is(t,e){if(t===e)return!0;if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(!Is(t[n],e[n]))return!1;return!0}if(We(t)&&We(e)){let n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;for(let i of n){if(!Object.prototype.hasOwnProperty.call(e,i))return!1;if(!Is(t[i],e[i]))return!1}return!0}return!1}function We(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class ES{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,e,n={}){let{arrayStrategy:r="replace",useCache:i=!0,cacheTtl:c,trackPerformance:d=!0,verbose:a=!1}=n;if(i){let o=Id.getWithFileCheck("file",t);if(o){if(a)console.log(`Configuration loaded from cache: ${t}`);return o}}let l=async()=>{if(!ud(t))return null;try{let o=`?t=${Date.now()}`,u=await import(t+o),f=u.default||u,R="default"in u,E=Object.keys(u).length>0;if(!R&&!E)throw new Bd(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new Bd(t,Error("Configuration must export a valid object"),"unknown");let C={config:RS(e,f,r),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(i)Id.setWithFileCheck("file",C,t,c);return C}catch(o){throw o instanceof Error?gi.configLoad(t,o):gi.configLoad(t,Error(String(o)))}};if(d)return ws.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,e,n={}){for(let r of t)try{let i=await this.loadFromPath(r,e,n);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(n.verbose)console.warn(`Failed to load config from ${r}:`,i)}return null}generateConfigPaths(t,e,n){let r=this.generateNamePatterns(t,n),i=[];for(let c of r)for(let d of this.extensions)i.push(ds(e,`${c}${d}`));return i}generateNamePatterns(t,e){let n=[];if(n.push("config",".config"),t)n.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let r=e===void 0?[]:Array.isArray(e)?e:[e];for(let c of r){if(!c)continue;if(n.push(c,`.${c}.config`,`${c}.config`,`.${c}`),t)n.push(`${t}.${c}.config`,`.${t}.${c}.config`)}let i=new Set;return n.filter((c)=>{if(!c||i.has(c))return!1;return i.add(c),!0})}checkFileAccess(t){return I0(async()=>{return ud(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,e,n){let r=[];if(!ud(t))return r;if(e||n){let i=this.generateNamePatterns(e||"",n);for(let c of i)for(let d of this.extensions){let a=ds(t,`${c}${d}`);if(await this.checkFileAccess(a))r.push(a)}}else try{let{readdirSync:i}=await import("fs"),c=i(t);for(let d of c)if(this.looksLikeConfigFile(d)){let a=ds(t,d);if(await this.checkFileAccess(a))r.push(a)}}catch{return[]}return r}looksLikeConfigFile(t){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((n)=>n.test(t))}async validateConfigFile(t){let e=[];try{if(!ud(t))return e.push("Configuration file does not exist"),e;let n=await import(t),r=n.default||n;if(r===void 0)e.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)e.push("Configuration must be an object");else if(Array.isArray(r))e.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),c=i(t,"utf8");JSON.parse(c)}catch(i){e.push(`Invalid JSON syntax: ${i}`)}}catch(n){e.push(`Failed to load configuration file: ${n}`)}return e}async getFileModificationTime(t){try{let{statSync:e}=await import("fs");return e(t).mtime}catch{return null}}async preloadConfigurations(t,e={}){let n=new Map;return await Promise.allSettled(t.map(async(r)=>{try{let i=await this.loadFromPath(r,{},e);if(i)n.set(r,i.config)}catch(i){if(e.verbose)console.warn(`Failed to preload ${r}:`,i)}})),n}}var v0=/^https?:\/\//;class IS{async validateConfiguration(t,e,n={}){let{stopOnFirstError:r=!1,validateRequired:i=!0,validateTypes:c=!0,customRules:d=[],trackPerformance:a=!0,verbose:l=!1}=n,o=async()=>{let u=[],f=[],R={stopOnFirstError:r,validateRequired:i,validateTypes:c,customRules:d,trackPerformance:a,verbose:l};try{if(typeof e==="string")return await this.validateWithSchemaFile(t,e,R);else if(Array.isArray(e))return this.validateWithRules(t,[...e,...d],R);else return this.validateWithJSONSchema(t,e,R)}catch(E){return u.push({path:"",message:`Validation failed: ${E}`,rule:"system"}),{isValid:!1,errors:u,warnings:f}}};if(a)return await ws.track("validateConfiguration",o);return o()}async validateWithSchemaFile(t,e,n){try{if(!$0(e))throw new zd(e,[{path:"",message:"Schema file does not exist"}]);let r=await import(e),i=r.default||r;if(Array.isArray(i))return this.validateWithRules(t,i,n);else return this.validateWithJSONSchema(t,i,n)}catch(r){throw new zd(e,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(t,e,n){let r=[],i=[];return this.validateObjectAgainstSchema(t,e,"",r,i,n),{isValid:r.length===0,errors:r,warnings:i}}validateObjectAgainstSchema(t,e,n,r,i,c){if(c.validateTypes&&e.type){let d=Array.isArray(t)?"array":typeof t,a=Array.isArray(e.type)?e.type:[e.type];if(!a.includes(d)){if(r.push({path:n,message:`Expected type ${a.join(" or ")}, got ${d}`,expected:a.join(" or "),actual:d,rule:"type"}),c.stopOnFirstError)return}}if(e.enum&&!e.enum.includes(t)){if(r.push({path:n,message:`Value must be one of: ${e.enum.join(", ")}`,expected:e.enum.join(", "),actual:t,rule:"enum"}),c.stopOnFirstError)return}if(typeof t==="string"){if(e.minLength!==void 0&&t.length<e.minLength)r.push({path:n,message:`String length must be at least ${e.minLength}`,expected:`>= ${e.minLength}`,actual:t.length,rule:"minLength"});if(e.maxLength!==void 0&&t.length>e.maxLength)r.push({path:n,message:`String length must not exceed ${e.maxLength}`,expected:`<= ${e.maxLength}`,actual:t.length,rule:"maxLength"});if(e.pattern){if(!new RegExp(e.pattern).test(t))r.push({path:n,message:`String does not match pattern ${e.pattern}`,expected:e.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(e.minimum!==void 0&&t<e.minimum)r.push({path:n,message:`Value must be at least ${e.minimum}`,expected:`>= ${e.minimum}`,actual:t,rule:"minimum"});if(e.maximum!==void 0&&t>e.maximum)r.push({path:n,message:`Value must not exceed ${e.maximum}`,expected:`<= ${e.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&e.items)for(let d=0;d<t.length;d++){let a=n?`${n}[${d}]`:`[${d}]`;if(this.validateObjectAgainstSchema(t[d],e.items,a,r,i,c),c.stopOnFirstError&&r.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let d=t;if(c.validateRequired&&e.required){for(let a of e.required)if(!(a in d)){if(r.push({path:n?`${n}.${a}`:a,message:`Missing required property '${a}'`,expected:"required",rule:"required"}),c.stopOnFirstError)return}}if(e.properties){for(let[a,l]of Object.entries(e.properties))if(a in d){let o=n?`${n}.${a}`:a;if(this.validateObjectAgainstSchema(d[a],l,o,r,i,c),c.stopOnFirstError&&r.length>0)return}}if(e.additionalProperties===!1){let a=new Set(Object.keys(e.properties||{}));for(let l of Object.keys(d))if(!a.has(l))i.push({path:n?`${n}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,e,n){let r=[],i=[];for(let c of e)try{let d=this.getValueByPath(t,c.path),a=this.validateWithRule(d,c,c.path);if(r.push(...a),n.stopOnFirstError&&r.length>0)break}catch(d){r.push({path:c.path,message:`Rule validation failed: ${d}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:i}}validateWithRule(t,e,n){let r=[];if(e.required&&(t===void 0||t===null))return r.push({path:n,message:e.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(t===void 0||t===null)return r;if(e.type){let i=Array.isArray(t)?"array":typeof t;if(i!==e.type)r.push({path:n,message:e.message||`Expected type ${e.type}, got ${i}`,expected:e.type,actual:i,rule:"type"})}if(e.min!==void 0){let i=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(i<e.min)r.push({path:n,message:e.message||`Value must be at least ${e.min}`,expected:`>= ${e.min}`,actual:i,rule:"min"})}if(e.max!==void 0){let i=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(i>e.max)r.push({path:n,message:e.message||`Value must not exceed ${e.max}`,expected:`<= ${e.max}`,actual:i,rule:"max"})}if(e.pattern&&typeof t==="string"){if(!e.pattern.test(t))r.push({path:n,message:e.message||`Value does not match pattern ${e.pattern}`,expected:e.pattern.toString(),actual:t,rule:"pattern"})}if(e.enum&&!e.enum.includes(t))r.push({path:n,message:e.message||`Value must be one of: ${e.enum.join(", ")}`,expected:e.enum.join(", "),actual:t,rule:"enum"});if(e.validator){let i=e.validator(t);if(i)r.push({path:n,message:e.message||i,rule:"custom"})}return r}getValueByPath(t,e){if(!e)return t;let n=e.split("."),r=t;for(let i of n)if(r&&typeof r==="object"&&i in r)r=r[i];else return;return r}generateRulesFromInterface(t){let e=[],n=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,i,c,d]=r;e.push({path:i,required:!c,type:this.mapTypeScriptType(d)})}return e}mapTypeScriptType(t){switch(t.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:v0},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var cn=new Ud("bunfig",{showTags:!0});function k0(t){if(!t)return"";let e=Array.isArray(t)?t.filter(Boolean):[t];if(e.length===0)return"";if(e.length===1)return` or alias "${e[0]}"`;return` or aliases ${e.map((n)=>`"${n}"`).join(", ")}`}class wS{fileLoader=new ES;envProcessor=new Os;validator=new IS;async loadConfig(t){let e=Date.now(),{cache:n,performance:r,schema:i,validate:c,...d}=t;try{if(n?.enabled){let l=this.checkCache(d.name||"",d);if(l)return l}let a;try{a=await this.loadConfigurationStrategies(d,!0,n)}catch(l){let o=d.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if(o)throw l;a={...await this.applyEnvironmentVariables(d.name||"",d.defaultConfig,d.checkEnv!==!1,d.verbose||!1),warnings:[`No configuration file found for "${d.name||"config"}", using defaults with environment variables`]}}else if(l instanceof Error&&l.name==="ConfigLoadError"){let u=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),f=!u&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),R=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if(o&&(R||u))throw l;if(f&&(!o||!R))a={...await this.applyEnvironmentVariables(d.name||"",d.defaultConfig,d.checkEnv!==!1,d.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!o)a={...await this.applyEnvironmentVariables(d.name||"",d.defaultConfig,d.checkEnv!==!1,d.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else a={...await this.applyEnvironmentVariables(d.name||"",d.defaultConfig,d.checkEnv!==!1,d.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(i||c)await this.validateConfiguration(a.config,i,c,d.name);if(n?.enabled&&a)this.cacheResult(d.name||"",a,n,d);if(r?.enabled){let l={operation:"loadConfig",duration:Date.now()-e,configName:d.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(l);if(r.slowThreshold&&l.duration>r.slowThreshold)cn.warn(`Slow configuration loading detected: ${l.duration}ms for ${d.name}`);a.metrics=l}return a}catch(a){if(a instanceof Error&&a.name==="ConfigNotFoundError")throw a;let l=Date.now()-e;throw cn.error(`Configuration loading failed after ${l}ms:`,[a instanceof Error?a:Error(String(a))]),a}}async loadConfigurationStrategies(t,e=!1,n){let{name:r="",alias:i,cwd:c,configDir:d,defaultConfig:a,checkEnv:l=!0,arrayStrategy:o="replace",verbose:u=!1}=t,f=c||Td.cwd(),R=[],E=await this.loadLocalConfiguration(r,i,f,d,a,o,u,l,n);if(E)return R.push(...this.getLocalSearchPaths(r,i,f,d)),this.finalizeResult(E,R,l,r,u);let y=await this.loadHomeConfiguration(r,i,a,o,u,l);if(y)return R.push(...this.getHomeSearchPaths(r,i)),this.finalizeResult(y,R,l,r,u);let $=await this.loadPackageJsonConfiguration(r,i,f,a,o,u,l);if($)return R.push(Te(f,"package.json")),this.finalizeResult($,R,l,r,u);if(R.push(...this.getAllSearchPaths(r,i,f,d)),e)throw gi.configNotFound(r,R,i);return{...await this.applyEnvironmentVariables(r,a,l,u),warnings:[`No configuration file found for "${r}"${k0(i)}, using defaults with environment variables`]}}async loadLocalConfiguration(t,e,n,r,i,c,d,a,l){let o=a?hd(t,i,d):i,u=this.getLocalDirectories(n,r);for(let f of u){if(d)cn.info(`Searching for configuration in: ${f}`);let R=this.fileLoader.generateConfigPaths(t,f,e),E=await this.fileLoader.tryLoadFromPaths(R,o,{arrayStrategy:c,verbose:d,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(E){if(d)cn.success(`Configuration loaded from: ${E.source.path}`);return E}}return null}async loadHomeConfiguration(t,e,n,r,i,c){if(!t)return null;let d=c?hd(t,n,i):n,a=[Te(qr(),".config",t),Te(qr(),".config"),qr()];for(let l of a){if(i)cn.info(`Checking home directory: ${l}`);let o=this.fileLoader.generateConfigPaths(t,l,e),u=await this.fileLoader.tryLoadFromPaths(o,d,{arrayStrategy:r,verbose:i});if(u){if(i)cn.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(t,e,n,r,i,c,d){let a=d?hd(t,r,c):r;try{let l=Te(n,"package.json");if(!ww(l))return null;let o={};try{o=JSON.parse(Aw(l,"utf8"))}catch(R){if(c)cn.warn("Failed to parse package.json:",[R instanceof Error?R:Error(String(R))]);return null}let u=o[t],f=t;if(!u&&e){let R=Array.isArray(e)?e:[e];for(let E of R){if(!E)continue;if(o[E]){u=o[E],f=E;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(c)cn.success(`Configuration loaded from package.json: ${f}`);return{config:RS(a,u,i),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(c)cn.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,e,n,r){if(!n||!t||typeof e!=="object"||e===null||Array.isArray(e))return{config:e,source:{type:"default",priority:10,timestamp:new Date}};return{config:hd(t,e,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,e,n,r,i){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,e,n,r){let i=[];if(n){let c=n(t);if(c)i.push(...c)}if(e){let c=await this.validator.validateConfiguration(t,e);if(!c.isValid)i.push(...c.errors.map((d)=>d.path?`${d.path}: ${d.message}`:d.message))}if(i.length>0)throw gi.configValidation(r||"unknown",i,r)}checkCache(t,e){let n=this.generateCacheKey(t,e);return Id.get(n)||null}cacheResult(t,e,n,r){let i=this.generateCacheKey(t,r);Id.set(i,e,void 0,n.ttl)}generateCacheKey(t,e){let n=[t];if(e.alias){let r=Array.isArray(e.alias)?e.alias.join(","):e.alias;n.push(`alias:${r}`)}if(e.cwd)n.push(`cwd:${e.cwd}`);if(e.configDir)n.push(`configDir:${e.configDir}`);if("checkEnv"in e)n.push(`checkEnv:${e.checkEnv}`);return n.join("|")}getLocalDirectories(t,e){return Array.from(new Set([t,Te(t,"config"),Te(t,".config"),e?Te(t,e):void 0].filter(Boolean)))}getAllSearchPaths(t,e,n,r){let i=[];return i.push(...this.getLocalSearchPaths(t,e,n,r)),i.push(...this.getHomeSearchPaths(t,e)),i.push(Te(n,"package.json")),i}getLocalSearchPaths(t,e,n,r){let i=this.getLocalDirectories(n,r),c=[];for(let d of i)c.push(...this.fileLoader.generateConfigPaths(t,d,e));return c}getHomeSearchPaths(t,e){if(!t)return[];let n=[Te(qr(),".config",t),Te(qr(),".config"),qr()],r=[];for(let i of n)r.push(...this.fileLoader.generateConfigPaths(t,i,e));return r}async loadConfigWithResult(t){return this.loadConfig(t)}}var os=new wS;async function AS(t){let e="defaultConfig"in t&&t.defaultConfig!==void 0?t.defaultConfig:{},n="cache"in t||"performance"in t||"schema"in t||"validate"in t;try{let r;if(n)r=await os.loadConfig(t);else r=await os.loadConfig({...t,defaultConfig:e,cache:{enabled:!0},performance:{enabled:!1}});return r?.config??e}catch(r){let i=r instanceof Error?r.name:"UnknownError",c=r instanceof Error?r.message:String(r);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||c.includes("config"))&&t.verbose)cn.warn("Unexpected error loading config, using defaults:",[r instanceof Error?r:Error(String(r))]);let a=n?{...t,defaultConfig:e}:{...t,defaultConfig:e,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in t?t.checkEnv!==!1:!0)return(await os.applyEnvironmentVariables(a.name||"",e,!0,a.verbose||!1))?.config??e;return e}}function hd(t,e,n=!1){let r=new Os,i=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function c(d,a=[]){let l={...d};for(let[o,u]of Object.entries(d)){let f=[...a,o],R=[`${i}_${f.join("_").toUpperCase()}`,`${i}_${f.map(($)=>$.toUpperCase()).join("")}`,`${i}_${f.map(($)=>$.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],E,y;for(let $ of R)if(E=Td.env[$],E!==void 0){y=$;break}if(E!==void 0&&y)if(typeof u==="boolean")l[o]=["true","1","yes"].includes(E.toLowerCase());else if(typeof u==="number"){let $=Number(E);if(!Number.isNaN($))l[o]=$}else if(Array.isArray(u))try{l[o]=JSON.parse(E)}catch{l[o]=E.split(",").map(($)=>$.trim())}else l[o]=E;else if(u&&typeof u==="object"&&!Array.isArray(u))l[o]=c(u,f)}return l}return c(e)}var UJ=Te(Td.cwd(),"config"),jJ=Te(Td.cwd(),"src/generated");var PS={project:{name:"my-project",slug:"my-project",region:"us-east-1"},environments:{production:{type:"production"}}},yr=null;function J0(t){return t.project?.slug===PS.project?.slug&&Object.keys(t.environments??{}).length===1&&!!t.environments?.production}async function B0(){let t=[DS(process.cwd(),"config","cloud.ts"),DS(process.cwd(),"config","cloud.js")];for(let e of t){if(!C0(e))continue;let n=await import(`${O0(e).href}?t=${Date.now()}`),r=n.tsCloud??n.default?.tsCloud??n.default??n.cloud??n.config;if(r)return r}return null}async function z0(){if(!yr){if(yr=await AS({name:"cloud",defaultConfig:PS}),J0(yr))yr=await B0()??yr;yS(yr.stateDir)}return yr}var $S=z0;import{createHash as T0}from"node:crypto";var vS=async(t)=>{let e=Bun.spawn(t,{stdout:"pipe",stderr:"pipe"}),[n,r,i]=await Promise.all([e.exited,new Response(e.stdout).text(),new Response(e.stderr).text()]);return{code:n,stdout:r,stderr:i}};class kS{async scan(t,e){let n=await vS(["ssh-keyscan","-T","10","-p",String(e),"-t","ed25519",t]),r=n.stdout.split(`
|
|
120
|
-
`).find((i)=>i&&!i.startsWith("#"))?.trim().split(/\s+/);if(n.code!==0||!r?.[1]||!r[2])throw Error(`SSH host-key scan failed: ${n.stderr.trim()||"no key returned"}`);return{algorithm:r[1],key:r[2]}}async exec(t,e){if(t.trustState!=="pinned")throw Error("SSH host key must be pinned before remote execution.");return vS(["ssh","-p",String(t.sshPort),"-o","BatchMode=yes","-o","StrictHostKeyChecking=yes","-o","ConnectTimeout=10",`${t.sshUser}@${t.endpoint}`,e])}}var b0=(t)=>`SHA256:${T0("sha256").update(Buffer.from(t,"base64")).digest("base64").replace(/=+$/,"")}`,W0=`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 Zi{provider;transport;discoverer;constructor(t,e=new kS,n){this.provider=t;this.transport=e;this.discoverer=n}discover(t){return this.discoverer?.(t)??Promise.resolve([])}async test(t){try{let e=await this.transport.scan(t.endpoint,t.sshPort);return{reachable:!0,hostKeyAlgorithm:e.algorithm,hostKeyFingerprint:b0(e.key),latencyMs:0}}catch{return{reachable:!1,hostKeyAlgorithm:"unknown",hostKeyFingerprint:"",latencyMs:0}}}async validate(t){let e=await this.transport.exec(t,W0);if(e.code!==0)throw Error(`Fleet validation failed: ${e.stderr.trim()||e.code}`);try{return JSON.parse(e.stdout)}catch{throw Error("Fleet validation returned malformed facts.")}}async bootstrap(t,e){let n=await this.transport.exec(t,`sudo -n ts-cloud-agent bootstrap --version 1 --steps ${e.length}`);if(n.code!==0)throw Error(`Fleet bootstrap failed: ${n.stderr.trim()||n.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 CS(t,e){return{"fleet.bootstrap":async(n)=>{let r=n.operation.input&&typeof n.operation.input==="object"&&!Array.isArray(n.operation.input)?n.operation.input:{},i=t.get(String(r.serverId??""));if(!i)throw Error("Queued fleet server was not found.");let c=e.find((l)=>l.provider===i.provider);if(!c)throw Error(`No ${i.provider} fleet driver is configured.`);let d=Array.isArray(r.steps)?r.steps.map(String):[];if(n.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.");n.checkpoint("bootstrap","Applying the reviewed idempotent bootstrap plan.");let a=await c.bootstrap(i,d);return t.update(i.id,{bootstrapVersion:a.version,status:"ready"}),n.checkpoint("verify","Bootstrap completed; heartbeat can now establish freshness."),{serverId:i.id,bootstrapVersion:a.version,steps:d.length}}}}var dn=(t)=>t==null?void 0:String(t),Pr=(t,e)=>{try{return JSON.parse(String(t))}catch{return e}},Js=(t)=>({id:String(t.id),organizationId:String(t.organization_id),projectId:String(t.project_id),resourceId:String(t.resource_id),name:String(t.name),provider:String(t.provider),providerId:dn(t.provider_id),region:dn(t.region),zone:dn(t.zone),endpoint:String(t.endpoint),sshUser:String(t.ssh_user),sshPort:Number(t.ssh_port),credentialRef:String(t.credential_ref),hostKeyAlgorithm:dn(t.host_key_algorithm),hostKeyFingerprint:dn(t.host_key_fingerprint),pendingHostKey:dn(t.pending_host_key),roles:Pr(t.roles,[]),labels:Pr(t.labels,{}),taints:Pr(t.taints,[]),capacity:Pr(t.capacity,{}),usage:Pr(t.usage,{}),capabilities:Pr(t.capabilities,{}),status:String(t.status),trustState:String(t.trust_state),validation:Pr(t.validation,void 0),bootstrapVersion:dn(t.bootstrap_version),heartbeatAt:dn(t.heartbeat_at),lastSeenAt:dn(t.last_seen_at),archivedAt:dn(t.archived_at),version:Number(t.version),createdAt:String(t.created_at),updatedAt:String(t.updated_at)});class Bs{control;now;id;constructor(t,e=()=>new Date,n=()=>crypto.randomUUID()){this.control=t;this.now=e;this.id=n}get(t){let e=this.control.database.query("SELECT * FROM fleet_servers WHERE id=?").get(t);return e?Js(e):void 0}list(t,e=!1){return this.control.database.query("SELECT * FROM fleet_servers WHERE project_id=? ORDER BY name").all(t).map(Js).filter((n)=>e||n.status!=="archived")}findProvider(t,e,n){let r=this.control.database.query("SELECT * FROM fleet_servers WHERE organization_id=? AND provider=? AND provider_id=? AND archived_at IS NULL").get(t,e,n);return r?Js(r):void 0}create(t){let e=this.id(),n=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 (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[e,t.organizationId,t.projectId,t.resourceId,t.name,t.provider,t.providerId??null,t.region??null,t.zone??null,t.endpoint,t.sshUser,t.sshPort,t.credentialRef,t.hostKeyAlgorithm??null,t.hostKeyFingerprint??null,t.pendingHostKey??null,JSON.stringify(t.roles),JSON.stringify(t.labels),JSON.stringify(t.taints),JSON.stringify(t.capacity),JSON.stringify(t.usage),JSON.stringify(t.capabilities),t.status,t.trustState,JSON.stringify(t.validation??{}),t.bootstrapVersion??null,t.heartbeatAt??null,t.lastSeenAt??null,t.archivedAt??null,n,n]),this.get(e)}update(t,e){let n=this.get(t);if(!n)throw Error("Server was not found.");let r={...n,...e},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=?",[r.name,r.providerId??null,r.region??null,r.zone??null,r.endpoint,r.sshUser,r.sshPort,r.credentialRef,r.hostKeyAlgorithm??null,r.hostKeyFingerprint??null,r.pendingHostKey??null,JSON.stringify(r.roles),JSON.stringify(r.labels),JSON.stringify(r.taints),JSON.stringify(r.capacity),JSON.stringify(r.usage),JSON.stringify(r.capabilities),r.status,r.trustState,JSON.stringify(r.validation??{}),r.bootstrapVersion??null,r.heartbeatAt??null,r.lastSeenAt??null,r.archivedAt??null,i,t]),this.get(t)}}var U0=/^(?:[A-Za-z0-9](?:[A-Za-z0-9.-]{0,251}[A-Za-z0-9])?|\[[0-9a-fA-F:]+\])$/;class zs{store;drivers;now;queue;constructor(t,e,n,r=()=>new Date){this.store=t;this.drivers=e;this.now=r;this.queue=n??new Ot(t.control)}driver(t){let e=this.drivers.find((n)=>n.provider===t);if(!e)throw Error(`No ${t} fleet driver is configured.`);return e}enroll(t){if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(t.name))throw Error("Server name is invalid.");if(!U0.test(t.endpoint)||t.sshUser==="root"||!t.credentialRef.startsWith("secret://"))throw Error("Enrollment requires a valid endpoint, non-root SSH user, and secret credential reference.");let e=t.providerId?this.store.findProvider(t.organizationId,t.provider,t.providerId):void 0;if(e)return this.store.update(e.id,{endpoint:t.endpoint,region:t.region,zone:t.zone});let n=this.store.control.createResource({projectId:t.projectId,kind:"server",slug:t.name,name:t.name,provider:t.provider,providerId:t.providerId}),r=this.driver(t.provider);return this.store.create({...t,resourceId:n.id,sshPort:t.sshPort??22,labels:t.labels??{},taints:[],capacity:{},usage:{},capabilities:r.capabilities(),status:"pending",trustState:"unverified"})}async test(t){let e=this.store.get(t);if(!e)throw Error("Server was not found.");let n=await this.driver(e.provider).test(e);if(!n.reachable)return this.store.update(t,{status:"unreachable"});if(e.hostKeyFingerprint&&e.hostKeyFingerprint!==n.hostKeyFingerprint)return this.store.update(t,{status:"degraded",trustState:"rotation_pending",pendingHostKey:n.hostKeyFingerprint});return this.store.update(t,{hostKeyAlgorithm:n.hostKeyAlgorithm,hostKeyFingerprint:n.hostKeyFingerprint,pendingHostKey:void 0,trustState:"pinned",status:"validating",lastSeenAt:this.now().toISOString()})}reviewHostKey(t,e){let n=this.store.get(t);if(!n||n.pendingHostKey!==e)throw Error("Pending host key does not match.");return this.store.update(t,{hostKeyFingerprint:e,pendingHostKey:void 0,trustState:"pinned",status:"validating"})}async validate(t){let e=this.store.get(t);if(!e||e.trustState!=="pinned")throw Error("Pin the SSH host key before validation.");let n=await this.driver(e.provider).validate(e),r=[];if(!["x64","arm64","x86_64","aarch64"].includes(n.arch??""))r.push({code:"arch.unsupported",severity:"error",message:"Unsupported architecture.",remediation:"Use x86_64 or arm64 Linux."});for(let d of["curl","tar"])if(!n.tools?.[d])r.push({code:`tool.${d}`,severity:"error",message:`${d} is missing.`,remediation:`Install ${d} before bootstrap.`});if(Math.abs(n.timeSkewSeconds??0)>60)r.push({code:"time.skew",severity:"error",message:"Clock skew exceeds 60 seconds.",remediation:"Enable NTP synchronization."});if(!n.dnsOk)r.push({code:"dns.failed",severity:"error",message:"DNS validation failed.",remediation:"Repair resolver configuration."});let i={valid:!r.some((d)=>d.severity==="error"),facts:n,findings:r,validatedAt:this.now().toISOString(),validatorVersion:"1"},c={cpu:n.cpuCores??0,memoryBytes:n.memoryBytes??0,diskBytes:n.diskBytes??0};return this.store.update(t,{validation:i,capacity:c,status:i.valid?"ready":"degraded"})}bootstrap(t,e=!1){let n=this.store.get(t);if(!n?.validation?.valid)throw Error("A healthy validation report is required.");let r=["install runtime dependencies","install ts-cloud agent","configure heartbeat","verify least-privilege access"];if(!e)return{preview:!0,steps:r};let i=this.queue.enqueue({projectId:n.projectId,resourceId:n.resourceId,kind:"fleet.bootstrap",input:{serverId:t,steps:r},lockKey:`server:${t}`,providerKey:n.provider}).operation;return{preview:!1,steps:r,operation:i}}heartbeat(t,e){let n=this.store.get(t);if(!n)throw Error("Server was not found.");let r=this.now().toISOString();return this.store.update(t,{usage:e.usage,capabilities:e.capabilities??n.capabilities,heartbeatAt:r,lastSeenAt:r,status:n.status==="draining"||n.status==="drained"?n.status:"ready"})}drain(t,e=!1){return this.store.update(t,{status:e?"drained":"draining"})}uncordon(t){return this.store.update(t,{status:"ready"})}archive(t,e){let n=this.store.get(t);if(!n||e!==n.name)throw Error("Exact server name confirmation is required.");return this.store.update(t,{status:"archived",archivedAt:this.now().toISOString()})}}import{createHash as Ts,createPublicKey as BS,verify as j0}from"node:crypto";function Yi(t){if(t===null||typeof t!=="object")return JSON.stringify(t);if(Array.isArray(t))return`[${t.map(Yi).join(",")}]`;return`{${Object.keys(t).sort().map((e)=>`${JSON.stringify(e)}:${Yi(t[e])}`).join(",")}}`}var zS=(t)=>Ts("sha256").update(Yi(t)).digest("hex"),jd=(t)=>Ts("sha256").update(Yi(t)).digest("hex"),TS=(t)=>Ts("sha256").update(BS(t).export({type:"spki",format:"der"})).digest("hex");function bS(t,e,n){try{return j0(null,Buffer.from(Yi(t)),BS(n),Buffer.from(e,"base64"))}catch{return!1}}var OS=(t)=>t.replace(/^v/,"").split(/[.-]/).slice(0,3).map((e)=>Number(e)||0),JS=(t,e)=>{let n=OS(t),r=OS(e);for(let i=0;i<3;i++){let c=(n[i]??0)-(r[i]??0);if(c)return c}return 0};function WS(t,e){let n=[];if(e.schemaVersion<t.minimumSchema)n.push(`schema ${e.schemaVersion} is below ${t.minimumSchema}`);if(e.schemaVersion>t.maximumSchema)n.push(`schema ${e.schemaVersion} is above ${t.maximumSchema}`);if(t.minimumVersion&&JS(e.currentVersion,t.minimumVersion)<0)n.push(`platform ${e.currentVersion} is below ${t.minimumVersion}`);if(JS(t.version,e.currentVersion)<=0)n.push(`version ${t.version} is not newer than ${e.currentVersion}`);if(!t.artifacts.some((r)=>r.platform===e.platform&&r.architecture===e.architecture))n.push(`no artifact for ${e.platform}/${e.architecture}`);return{compatible:n.length===0,reasons:n}}var $n=(t,e)=>{try{return JSON.parse(String(t))}catch{return e}},ne=(t)=>t==null?void 0:String(t),H0=(t)=>({id:String(t.id),organizationId:String(t.organization_id),name:String(t.name),algorithm:"ed25519",publicKeyPem:String(t.public_key_pem),fingerprint:String(t.fingerprint),revokedAt:ne(t.revoked_at),createdAt:String(t.created_at)}),US=(t)=>({id:String(t.id),organizationId:String(t.organization_id),version:String(t.version),channel:String(t.channel),publishedAt:String(t.published_at),keyId:String(t.key_id),digest:String(t.digest),document:$n(t.document,{}),signature:String(t.signature),verificationStatus:String(t.verification_status),compatibility:$n(t.compatibility,{compatible:!1,reasons:[]}),createdAt:String(t.created_at)}),jS=(t)=>({id:String(t.id),projectId:String(t.project_id),name:String(t.name),schedule:String(t.schedule),timezone:String(t.timezone),durationMinutes:Number(t.duration_minutes),allowedOperations:$n(t.allowed_operations,[]),requireApproval:Number(t.require_approval)===1,enabled:Number(t.enabled)===1,createdAt:String(t.created_at),updatedAt:String(t.updated_at)}),HS=(t)=>({id:String(t.id),projectId:String(t.project_id),manifestId:String(t.manifest_id),windowId:ne(t.window_id),fromVersion:String(t.from_version),strategy:String(t.strategy),batchSize:Number(t.batch_size),healthGate:$n(t.health_gate,{}),status:String(t.status),currentStage:ne(t.current_stage),backupId:ne(t.backup_id),approvedBy:ne(t.approved_by),createdAt:String(t.created_at),updatedAt:String(t.updated_at)}),bs=(t)=>({id:String(t.id),campaignId:String(t.campaign_id),serverId:ne(t.server_id),target:String(t.target),cohort:Number(t.cohort),previousVersion:String(t.previous_version),status:String(t.status),evidence:$n(t.evidence,{}),error:ne(t.error),startedAt:ne(t.started_at),finishedAt:ne(t.finished_at),createdAt:String(t.created_at),updatedAt:String(t.updated_at)}),LS=(t)=>({id:String(t.id),projectId:String(t.project_id),kind:String(t.kind),criteria:$n(t.criteria,{}),candidates:$n(t.candidates,[]),candidateDigest:String(t.candidate_digest),estimatedBytes:Number(t.estimated_bytes),status:String(t.status),confirmation:ne(t.confirmation),expiresAt:String(t.expires_at),result:$n(t.result,{}),createdAt:String(t.created_at),updatedAt:String(t.updated_at)}),FS=(t)=>({id:String(t.id),projectId:String(t.project_id),backupPolicyId:ne(t.backup_policy_id),recoveryPointId:ne(t.recovery_point_id),topologyId:ne(t.topology_id),scenario:String(t.scenario),isolatedTarget:String(t.isolated_target),expectedRpoMinutes:Number(t.expected_rpo_minutes),expectedRtoMinutes:Number(t.expected_rto_minutes),status:String(t.status),operationId:ne(t.operation_id),evidence:$n(t.evidence,{}),measuredRpoMinutes:t.measured_rpo_minutes==null?void 0:Number(t.measured_rpo_minutes),measuredRtoMinutes:t.measured_rto_minutes==null?void 0:Number(t.measured_rto_minutes),cleanupVerified:Number(t.cleanup_verified)===1,error:ne(t.error),startedAt:ne(t.started_at),finishedAt:ne(t.finished_at),createdAt:String(t.created_at),updatedAt:String(t.updated_at)});class Ws{control;now;id;constructor(t,e=()=>new Date,n=()=>crypto.randomUUID()){this.control=t;this.now=e;this.id=n}addTrustedKey(t){let e=this.id(),n=this.now().toISOString(),r=TS(t.publicKeyPem);return this.control.database.run("INSERT INTO platform_trusted_keys (id,organization_id,name,algorithm,public_key_pem,fingerprint,created_at) VALUES (?,?,?,'ed25519',?,?,?)",[e,t.organizationId,t.name,t.publicKeyPem,r,n]),this.key(e)}key(t){let e=this.control.database.query("SELECT * FROM platform_trusted_keys WHERE id=?").get(t);return e?H0(e):void 0}revokeKey(t){return this.control.database.run("UPDATE platform_trusted_keys SET revoked_at=? WHERE id=?",[this.now().toISOString(),t]),this.key(t)}importManifest(t){let e=this.key(t.keyId);if(!e||e.organizationId!==t.organizationId)throw Error("Trusted update key was not found.");if(e.revokedAt)throw Error("Update signing key is revoked.");if(!bS(t.document,t.signature,e.publicKeyPem))throw Error("Update manifest signature is invalid.");let n=WS(t.document,t.current),r=zS(t.document),i=this.id(),c=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,t.organizationId,t.document.version,t.document.channel,new Date(t.document.publishedAt).toISOString(),t.keyId,r,JSON.stringify(t.document),t.signature,JSON.stringify(n),c]),this.manifest(i)}manifest(t){let e=this.control.database.query("SELECT * FROM platform_update_manifests WHERE id=?").get(t);return e?US(e):void 0}manifests(t){return this.control.database.query("SELECT * FROM platform_update_manifests WHERE organization_id=? ORDER BY published_at DESC").all(t).map(US)}createWindow(t){let e=this.id(),n=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,?,?)",[e,t.projectId,t.name,t.schedule,t.timezone,t.durationMinutes,JSON.stringify(t.allowedOperations),t.requireApproval===!1?0:1,n,n]),this.window(e)}window(t){let e=this.control.database.query("SELECT * FROM maintenance_windows WHERE id=?").get(t);return e?jS(e):void 0}windows(t){return this.control.database.query("SELECT * FROM maintenance_windows WHERE project_id=? ORDER BY name").all(t).map(jS)}createCampaign(t){return this.control.transaction(()=>{let e=this.manifest(t.manifestId);if(!e?.compatibility.compatible||e.verificationStatus!=="verified")throw Error("A verified compatible update manifest is required.");if(!t.backupId)throw Error("A verified pre-upgrade backup is required.");let n=this.id(),r=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',?,?,?,?)",[n,t.projectId,t.manifestId,t.windowId??null,t.fromVersion,t.strategy,t.batchSize,JSON.stringify(t.healthGate),t.backupId,t.approvedBy??null,r,r]),t.targets.forEach((i,c)=>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(),n,i.serverId??null,i.target,t.strategy==="canary"?c===0?0:1+Math.floor((c-1)/t.batchSize):Math.floor(c/t.batchSize),i.previousVersion,r,r])),this.campaign(n)})}campaign(t){let e=this.control.database.query("SELECT * FROM platform_upgrade_campaigns WHERE id=?").get(t);return e?HS(e):void 0}campaigns(t){return this.control.database.query("SELECT * FROM platform_upgrade_campaigns WHERE project_id=? ORDER BY created_at DESC").all(t).map(HS)}targets(t){return this.control.database.query("SELECT * FROM platform_upgrade_targets WHERE campaign_id=? ORDER BY cohort,target").all(t).map(bs)}updateCampaign(t,e){let n=this.campaign(t);if(!n)throw Error("Upgrade campaign was not found.");let r={...n,...e};return this.control.database.run("UPDATE platform_upgrade_campaigns SET status=?,current_stage=?,updated_at=? WHERE id=?",[r.status,r.currentStage??null,this.now().toISOString(),t]),this.campaign(t)}updateTarget(t,e){let n=this.control.database.query("SELECT * FROM platform_upgrade_targets WHERE id=?").get(t);if(!n)throw Error("Upgrade target was not found.");let r={...bs(n),...e};return this.control.database.run("UPDATE platform_upgrade_targets SET status=?,evidence=?,error=?,started_at=?,finished_at=?,updated_at=? WHERE id=?",[r.status,JSON.stringify(r.evidence),r.error??null,r.startedAt??null,r.finishedAt??null,this.now().toISOString(),t]),bs(this.control.database.query("SELECT * FROM platform_upgrade_targets WHERE id=?").get(t))}createCleanup(t){let e=[...t.candidates].sort((d,a)=>d.id.localeCompare(a.id)),n=jd(e),r=this.id(),i=this.now().toISOString(),c=new Date(this.now().getTime()+(t.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',?,?,?)",[r,t.projectId,t.kind,JSON.stringify(t.criteria),JSON.stringify(e),n,e.reduce((d,a)=>d+a.bytes,0),c,i,i]),this.cleanup(r)}cleanup(t){let e=this.control.database.query("SELECT * FROM cleanup_plans WHERE id=?").get(t);return e?LS(e):void 0}cleanups(t){return this.control.database.query("SELECT * FROM cleanup_plans WHERE project_id=? ORDER BY created_at DESC").all(t).map(LS)}updateCleanup(t,e){let n=this.cleanup(t);if(!n)throw Error("Cleanup plan was not found.");let r={...n,...e};return this.control.database.run("UPDATE cleanup_plans SET status=?,confirmation=?,result=?,updated_at=? WHERE id=?",[r.status,r.confirmation??null,JSON.stringify(r.result),this.now().toISOString(),t]),this.cleanup(t)}createDrill(t){if(!/^isolated:\/\//.test(t.isolatedTarget))throw Error("DR drills require an isolated target.");let e=this.id(),n=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',?,?)",[e,t.projectId,t.backupPolicyId??null,t.recoveryPointId??null,t.topologyId??null,t.scenario,t.isolatedTarget,t.expectedRpoMinutes,t.expectedRtoMinutes,n,n]),this.drill(e)}drill(t){let e=this.control.database.query("SELECT * FROM disaster_recovery_drills WHERE id=?").get(t);return e?FS(e):void 0}drills(t){return this.control.database.query("SELECT * FROM disaster_recovery_drills WHERE project_id=? ORDER BY created_at DESC").all(t).map(FS)}updateDrill(t,e){let n=this.drill(t);if(!n)throw Error("DR drill was not found.");let r={...n,...e};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=?",[r.status,r.operationId??null,JSON.stringify(r.evidence),r.measuredRpoMinutes??null,r.measuredRtoMinutes??null,r.cleanupVerified?1:0,r.error??null,r.startedAt??null,r.finishedAt??null,this.now().toISOString(),t]),this.drill(t)}}function L0(t,e=new Date){if(!t.enabled)return!1;let n=new Date(t.schedule);if(!Number.isNaN(n.getTime()))return e>=n&&e.getTime()<=n.getTime()+t.durationMinutes*60000;let r=/^(\d{2}):(\d{2})$/.exec(t.schedule);if(!r)return!1;let i=new Intl.DateTimeFormat("en-US",{timeZone:t.timezone,hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).formatToParts(e),c=Number(i.find((a)=>a.type==="hour")?.value)*60+Number(i.find((a)=>a.type==="minute")?.value),d=Number(r[1])*60+Number(r[2]);return c>=d&&c<d+t.durationMinutes}class Us{store;now;queue;constructor(t,e,n=()=>new Date){this.store=t;this.now=n;this.queue=e??new Ot(t.control)}enqueueCampaign(t,e={}){let n=this.store.campaign(t);if(!n)throw Error("Upgrade campaign was not found.");let r=n.windowId?this.store.window(n.windowId):void 0;if(r&&!r.allowedOperations.includes("platform.upgrade"))throw Error("Maintenance window does not permit platform upgrades.");if(r&&!e.overrideWindow&&!L0(r,this.now()))throw Error("Upgrade is outside its maintenance window.");if(r?.requireApproval&&!e.approvedBy&&!n.approvedBy)throw Error("Maintenance approval is required.");let i=this.queue.enqueue({projectId:n.projectId,actorId:e.approvedBy,kind:"maintenance.upgrade",input:{campaignId:t},lockKey:"platform-upgrade",providerKey:"platform",timeoutSeconds:7200,cancellationMode:"cooperative",resumePolicy:"fail"}).operation;return{campaign:this.store.updateCampaign(t,{status:"queued"}),operation:i}}async previewCleanup(t,e){let n=e.find((r)=>r.kind===t.kind);if(!n)throw Error(`No ${t.kind} cleanup driver is configured.`);return this.store.createCleanup({...t,candidates:await n.discover(t.criteria)})}enqueueCleanup(t,e){let n=this.store.cleanup(t);if(!n||n.status!=="preview")throw Error("A current cleanup preview is required.");if(new Date(n.expiresAt)<=this.now())throw Error("Cleanup preview expired; generate it again.");let r=`DELETE ${n.candidates.length} ${n.kind}`;if(e!==r)throw Error(`Exact confirmation ${r} is required.`);let i=this.queue.enqueue({projectId:n.projectId,kind:"maintenance.cleanup",input:{planId:t},lockKey:`cleanup:${n.kind}`,providerKey:"cleanup",timeoutSeconds:3600,cancellationMode:"cooperative"}).operation;return{plan:this.store.updateCleanup(t,{status:"approved",confirmation:e}),operation:i}}enqueueDrill(t){let e=this.store.drill(t);if(!e||e.status!=="planned")throw Error("A planned DR drill is required.");let n=this.queue.enqueue({projectId:e.projectId,kind:"maintenance.drill",input:{drillId:t},lockKey:`drill:${e.scenario}:${e.id}`,providerKey:"recovery",timeoutSeconds:7200,cancellationMode:"cooperative"}).operation;return{drill:this.store.updateDrill(t,{status:"queued",operationId:n.id}),operation:n}}}var js=(t)=>t&&typeof t==="object"&&!Array.isArray(t)?t:{};function VS(t){return{"maintenance.upgrade":async(i)=>{let c=t.store.campaign(String(js(i.operation.input).campaignId??""));if(!c||!t.platform)throw Error("Upgrade campaign or platform maintenance driver is unavailable.");let d=t.store.manifest(c.manifestId);if(!d?.compatibility.compatible||d.verificationStatus!=="verified")throw Error("Update manifest is no longer verified and compatible.");let a=d.document.artifacts.find((o)=>o.platform===process.platform&&o.architecture===process.arch)??d.document.artifacts[0];if(!a)throw Error("No update artifact matches this platform.");t.store.updateCampaign(c.id,{status:"running",currentStage:"preflight"});let l=[];try{for(let o of[...new Set(t.store.targets(c.id).map((u)=>u.cohort))].sort((u,f)=>u-f)){t.store.updateCampaign(c.id,{currentStage:`cohort:${o}`});for(let u of t.store.targets(c.id).filter((f)=>f.cohort===o)){i.throwIfCancellationRequested(),i.checkpoint(`download:${u.target}`,"Downloading signed platform artifact."),t.store.updateTarget(u.id,{status:"downloading",startedAt:new Date().toISOString()});let f=await t.platform.download({target:u,artifact:a,signal:i.signal});if(f.sha256!==a.sha256)throw Error(`Artifact checksum mismatch for ${u.target}.`);i.checkpoint(`install:${u.target}`,"Installing verified artifact."),t.store.updateTarget(u.id,{status:"installing"}),await t.platform.install({target:u,path:f.path,version:d.version,signal:i.signal}),l.push(u);let R=await t.platform.health({target:u,gate:c.healthGate});if(!R.healthy)throw Error(`Upgrade health gate failed for ${u.target}.`);t.store.updateTarget(u.id,{status:"healthy",evidence:R.evidence,finishedAt:new Date().toISOString()})}}return t.store.updateCampaign(c.id,{status:"succeeded",currentStage:void 0}),{campaignId:c.id,version:d.version,targets:l.length}}catch(o){t.store.updateCampaign(c.id,{status:"rolling_back",currentStage:"rollback"});for(let u of l.reverse())t.store.updateTarget(u.id,{status:"rolling_back"}),await t.platform.rollback({target:u,version:u.previousVersion,signal:i.signal}),t.store.updateTarget(u.id,{status:"rolled_back",finishedAt:new Date().toISOString()});throw t.store.updateCampaign(c.id,{status:"rolled_back",currentStage:void 0}),o}},"maintenance.cleanup":async(i)=>{let c=t.store.cleanup(String(js(i.operation.input).planId??""));if(!c||c.status!=="approved")throw Error("Approved cleanup plan was not found.");if(jd([...c.candidates].sort((u,f)=>u.id.localeCompare(f.id)))!==c.candidateDigest)throw Error("Cleanup candidate set changed after preview.");let d=t.cleanup?.find((u)=>u.kind===c.kind);if(!d)throw Error(`No ${c.kind} cleanup driver is configured.`);t.store.updateCleanup(c.id,{status:"running"});let a=[],l=[];for(let u of c.candidates){i.throwIfCancellationRequested();try{await d.remove(u),a.push(u.id)}catch(f){l.push({id:u.id,error:f instanceof Error?f.message:String(f)})}}let o=l.length?a.length?"partial":"failed":"succeeded";if(t.store.updateCleanup(c.id,{status:o,result:{removed:a,failed:l,reclaimedBytes:c.candidates.filter((u)=>a.includes(u.id)).reduce((u,f)=>u+f.bytes,0)}}),l.length)throw Error(`Cleanup failed for ${l.length} candidate(s).`);return{planId:c.id,removed:a.length,reclaimedBytes:c.estimatedBytes}},"maintenance.drill":async(i)=>{let c=t.store.drill(String(js(i.operation.input).drillId??""));if(!c)throw Error("DR drill was not found.");let d=t.recovery?.find((f)=>f.scenario===c.scenario);if(!d)throw Error(`No ${c.scenario} recovery driver is configured.`);let a=new Date;t.store.updateDrill(c.id,{status:"restoring",startedAt:a.toISOString()});let l=c.isolatedTarget,o={},u={};try{i.checkpoint("restore","Restoring into isolated drill target.");let f=await d.restore({drill:c,signal:i.signal});if(!f.target.startsWith("isolated://"))throw Error("Recovery driver attempted a non-isolated target.");l=f.target,o=f.evidence;let R=(a.getTime()-new Date(f.recoveryPointAt).getTime())/60000;t.store.updateDrill(c.id,{status:"verifying",measuredRpoMinutes:R,evidence:{restore:o}}),i.checkpoint("verify","Running recovery health checks without production traffic.");let E=await d.verify({drill:c,target:l});u=E.evidence;let y=(Date.now()-a.getTime())/60000;if(!E.healthy||R>c.expectedRpoMinutes||y>c.expectedRtoMinutes)throw Error("DR drill failed its health, RPO, or RTO objective.");t.store.updateDrill(c.id,{measuredRpoMinutes:R,measuredRtoMinutes:y,evidence:{restore:o,verify:u}})}catch(f){throw t.store.updateDrill(c.id,{status:"failed",error:f instanceof Error?f.message:String(f),evidence:{restore:o,verify:u}}),f}finally{t.store.updateDrill(c.id,{status:"cleaning"});try{await d.cleanup({drill:c,target:l});let f=t.store.drill(c.id);t.store.updateDrill(c.id,{status:f.error?"failed":"passed",cleanupVerified:!0,finishedAt:new Date().toISOString()})}catch(f){t.store.updateDrill(c.id,{status:"cleanup_required",cleanupVerified:!1,error:f instanceof Error?f.message:String(f),finishedAt:new Date().toISOString()})}}return{drillId:c.id,status:t.store.drill(c.id).status}}}}var NS={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 Hs{kind;control;projectId;organizationId;constructor(t,e,n,r){this.kind=t;this.control=e;this.projectId=n;this.organizationId=r}async discover(t){let e=Math.max(1,Math.min(3650,Number(t.olderThanDays??30))),n=new Date(Date.now()-e*86400000).toISOString(),r=NS[this.kind],i=this.kind==="artifacts"?this.organizationId:this.projectId;return this.control.database.query(r.select).all(i,n).map((d)=>({id:String(d.id),kind:this.kind,label:`${this.kind}:${String(d.id)}`,bytes:Number(d.bytes??0),metadata:{createdAt:String(d.created_at)}}))}async remove(t){if(this.control.database.run(NS[this.kind].remove,[t.id]).changes!==1)throw Error(`${t.label} changed or is no longer removable.`)}}var Qe=(t,e)=>{try{return JSON.parse(String(t))}catch{return e}},ye=(t)=>t==null?void 0:String(t),QS=()=>({cpu:0,memoryBytes:0,diskBytes:0,gpu:0}),ui=(t={})=>({...QS(),...t});function xS(t){return{id:String(t.id),organizationId:String(t.organization_id),projectId:String(t.project_id),name:String(t.name),purpose:String(t.purpose),backend:String(t.backend),region:ye(t.region),architecture:ye(t.architecture),labels:Qe(t.labels,{}),requiredServerLabels:Qe(t.required_server_labels,{}),toleratedTaints:Qe(t.tolerated_taints,[]),capacity:ui(Qe(t.capacity,{})),reserved:Qe(t.reserved,{}),maxWorkloads:Number(t.max_workloads),costWeight:Number(t.cost_weight),spreadKey:ye(t.spread_key),concurrency:Number(t.concurrency),ephemeralWorkspaces:Number(t.ephemeral_workspaces)===1,allowProductionSecrets:Number(t.allow_production_secrets)===1,status:String(t.status),version:Number(t.version),createdAt:String(t.created_at),updatedAt:String(t.updated_at)}}function MS(t){return{id:String(t.id),projectId:String(t.project_id),environmentId:ye(t.environment_id),resourceId:String(t.resource_id),releaseId:ye(t.release_id),poolId:String(t.pool_id),serverId:ye(t.server_id),purpose:String(t.purpose),requirements:Qe(t.requirements,{}),decision:Qe(t.decision,{}),stateful:Number(t.stateful)===1,autoReschedule:Number(t.auto_reschedule)===1,status:String(t.status),version:Number(t.version),createdAt:String(t.created_at),updatedAt:String(t.updated_at)}}function F0(t){return{id:String(t.id),projectId:String(t.project_id),resourceId:ye(t.resource_id),poolId:String(t.pool_id),placementId:ye(t.placement_id),operationId:ye(t.operation_id),sourceSha:String(t.source_sha),buildSpec:Qe(t.build_spec,{}),credentialPolicy:Qe(t.credential_policy,{productionSecrets:!1,shortLivedTokenExpiresAt:""}),workspace:ye(t.workspace),cacheKey:ye(t.cache_key),artifactUri:ye(t.artifact_uri),artifactDigest:ye(t.artifact_digest),status:String(t.status),cleanupAt:ye(t.cleanup_at),createdAt:String(t.created_at),updatedAt:String(t.updated_at)}}class Ls{control;now;id;constructor(t,e=()=>new Date,n=()=>crypto.randomUUID()){this.control=t;this.now=e;this.id=n}createPool(t){let e=this.id(),n=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 (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[e,t.organizationId,t.projectId,t.name,t.purpose,t.backend,t.region??null,t.architecture??null,JSON.stringify(t.labels),JSON.stringify(t.requiredServerLabels),JSON.stringify(t.toleratedTaints),JSON.stringify(ui(t.capacity)),"{}",t.maxWorkloads,t.costWeight,t.spreadKey??null,t.concurrency,t.ephemeralWorkspaces?1:0,t.allowProductionSecrets?1:0,t.status,n,n]),this.getPool(e)}getPool(t){let e=this.control.database.query("SELECT * FROM capacity_pools WHERE id=?").get(t);return e?xS(e):void 0}listPools(t){return this.control.database.query("SELECT * FROM capacity_pools WHERE project_id=? ORDER BY name").all(t).map(xS)}updatePool(t,e){let n=this.getPool(t);if(!n)throw Error("Capacity pool was not found.");let r={...n,...e},i=this.now().toISOString();return this.control.database.run("UPDATE capacity_pools SET status=?,reserved=?,capacity=?,concurrency=?,version=version+1,updated_at=? WHERE id=?",[r.status,JSON.stringify(r.reserved),JSON.stringify(r.capacity),r.concurrency,i,t]),this.getPool(t)}addMember(t,e,n={}){let r=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",[t,e,JSON.stringify(n),r,r])}members(t){return this.control.database.query("SELECT * FROM capacity_pool_members WHERE pool_id=? ORDER BY server_id").all(t).map((e)=>({serverId:String(e.server_id),status:String(e.status),capacityOverride:Qe(e.capacity_override,{})}))}memberStatus(t,e,n){this.control.database.run("UPDATE capacity_pool_members SET status=?,updated_at=? WHERE pool_id=? AND server_id=?",[n,this.now().toISOString(),t,e])}listPlacements(t,e){let n=this.control.database.query("SELECT * FROM workload_placements WHERE project_id=? ORDER BY created_at,id").all(t).map(MS);return e?.length?n.filter((r)=>e.includes(r.status)):n}getPlacement(t){let e=this.control.database.query("SELECT * FROM workload_placements WHERE id=?").get(t);return e?MS(e):void 0}activeUsage(t,e){let n=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(t,this.now().toISOString()),r=e?n.filter((i)=>String(i.server_id)===e):n;return{resources:r.reduce((i,c)=>{let d=ui(Qe(c.resources,{}));for(let a of Object.keys(i))i[a]+=d[a];return i},QS()),count:r.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(t){return this.control.transaction(()=>{this.expireLeases();let e=this.id(),n=this.id(),r=this.now().toISOString(),i=new Date(this.now().getTime()+(t.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',?,?)",[e,t.projectId,t.environmentId??null,t.resourceId,t.releaseId??null,t.decision.poolId,t.decision.serverId??null,t.requirements.purpose,JSON.stringify(t.requirements),JSON.stringify(t.decision),t.requirements.stateful?1:0,t.requirements.autoReschedule&&!t.requirements.stateful?1:0,r,r]),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',?,?,?)",[n,e,t.decision.poolId,t.decision.serverId??null,JSON.stringify(ui(t.requirements.resources)),i,r,r]),this.getPlacement(e)})}transitionPlacement(t,e){if(!this.getPlacement(t))throw Error("Placement was not found.");let r=this.now().toISOString();if(this.control.database.run("UPDATE workload_placements SET status=?,version=version+1,updated_at=? WHERE id=?",[e,r,t]),["released","failed","blocked"].includes(e))this.control.database.run("UPDATE capacity_leases SET state='released',updated_at=? WHERE placement_id=? AND state='active'",[r,t]);return this.getPlacement(t)}createBuild(t){let e=this.id(),n=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',?,?)",[e,t.projectId,t.resourceId??null,t.poolId,t.placementId??null,t.operationId??null,t.sourceSha,JSON.stringify(t.buildSpec),JSON.stringify({productionSecrets:!1,shortLivedTokenExpiresAt:t.tokenExpiresAt}),n,n]),this.getBuild(e)}getBuild(t){let e=this.control.database.query("SELECT * FROM remote_builds WHERE id=?").get(t);return e?F0(e):void 0}updateBuild(t,e){let n=this.getBuild(t);if(!n)throw Error("Remote build was not found.");let r={...n,...e},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=?",[r.operationId??null,r.workspace??null,r.cacheKey??null,r.artifactUri??null,r.artifactDigest??null,r.status,r.cleanupAt??null,i,t]),this.getBuild(t)}}var Hd=["cpu","memoryBytes","diskBytes","gpu"],GS=(t,e={})=>Object.entries(e).every(([n,r])=>t[n]===r),V0=(t,e,n)=>Object.fromEntries(Hd.map((r)=>[r,Math.max(0,t[r]-e[r]-(n[r]??0))])),N0=(t,e)=>Hd.every((n)=>t[n]>=(e[n]??0)),x0=(t,e)=>Hd.reduce((n,r)=>n+(e[r]??0)/(t[r]||1),0);class Fs{store;fleet;constructor(t,e){this.store=t;this.fleet=e}poolCandidates(t,e,n){let r=[];for(let i of this.store.listPools(t)){if(i.id===n)continue;let c=[];if(i.status!=="active")c.push(`pool is ${i.status}`);if(i.purpose!==e.purpose)c.push(`purpose is ${i.purpose}`);if(e.region&&i.region!==e.region)c.push(`region is ${i.region??"unset"}`);if(e.architecture&&i.architecture!==e.architecture)c.push(`architecture is ${i.architecture??"unset"}`);if(!GS(i.labels,e.labels))c.push("pool labels do not match");if(i.backend==="server"){let d=this.store.members(i.id);if(!d.length)r.push(this.decision(i,void 0,e,[...c,"pool has no servers"]));for(let a of d){let l=this.fleet.get(a.serverId),o=[...c];if(!l)o.push("server is missing");else this.serverReasons(i,l,a.status,e,o);r.push(this.decision(i,l,e,o,a.capacityOverride))}}else r.push(this.decision(i,void 0,e,c))}return r.sort((i,c)=>Number(c.eligible)-Number(i.eligible)||i.score.cost-c.score.cost||i.score.spread-c.score.spread||i.score.fit-c.score.fit||i.poolName.localeCompare(c.poolName)||(i.serverId??"").localeCompare(c.serverId??""))}serverReasons(t,e,n,r,i){if(n!=="active")i.push(`member is ${n}`);if(e.status!=="ready")i.push(`server is ${e.status}`);if(!e.roles.includes(r.purpose==="build"?"build":r.purpose))i.push(`server lacks ${r.purpose} role`);if(!GS(e.labels,t.requiredServerLabels))i.push("server labels do not match pool selector");for(let c of e.taints)if(!t.toleratedTaints.includes(c))i.push(`taint ${c} is not tolerated`)}decision(t,e,n,r,i={}){let c=ui({...e?.capacity,...i}),d=e?Object.fromEntries(Hd.map((o)=>[o,Math.min(t.capacity[o],c[o])])):t.capacity,a=this.store.activeUsage(t.id,e?.id),l=V0(d,a.resources,t.reserved);if(a.count>=t.maxWorkloads)r.push("workload limit reached");if(n.purpose==="build"&&a.count>=t.concurrency)r.push("build concurrency reached");if(!N0(l,n.resources))r.push("insufficient capacity");return{poolId:t.id,poolName:t.name,serverId:e?.id,eligible:r.length===0,reasons:r,available:l,score:{fit:x0(l,n.resources),spread:a.count,cost:t.costWeight}}}explain(t,e){return this.poolCandidates(t,e)}place(t){return this.store.control.transaction(()=>{let e=this.poolCandidates(t.projectId,t.requirements).find((n)=>n.eligible);if(!e)throw Error(`No eligible capacity: ${this.explain(t.projectId,t.requirements).flatMap((n)=>n.reasons).join("; ")}`);return this.store.reserve({...t,decision:e})})}activate(t){return this.store.transitionPlacement(t,"active")}release(t){return this.store.transitionPlacement(t,"released")}drainPool(t){let e=this.store.updatePool(t,{status:"draining"}),n=[],r=[];for(let i of this.store.listPlacements(e.projectId,["reserved","active"]).filter((c)=>c.poolId===t)){if(i.stateful){r.push(this.store.transitionPlacement(i.id,"blocked"));continue}this.store.transitionPlacement(i.id,"moving");let c=this.place({projectId:i.projectId,environmentId:i.environmentId,resourceId:i.resourceId,releaseId:i.releaseId,requirements:i.requirements});n.push(this.activate(c.id)),this.store.transitionPlacement(i.id,"released")}return{pool:e,moved:n,blocked:r}}drainServer(t,e){this.store.memberStatus(t,e,"draining");let n=this.store.getPool(t);if(!n)throw Error("Capacity pool was not found.");let r=[],i=[];for(let c of this.store.listPlacements(n.projectId,["reserved","active"]).filter((d)=>d.poolId===t&&d.serverId===e)){if(c.stateful){i.push(this.store.transitionPlacement(c.id,"blocked"));continue}this.store.transitionPlacement(c.id,"moving");let d=this.poolCandidates(c.projectId,c.requirements).find((l)=>l.eligible);if(!d){i.push(this.store.transitionPlacement(c.id,"blocked"));continue}let a=this.store.reserve({projectId:c.projectId,environmentId:c.environmentId,resourceId:c.resourceId,releaseId:c.releaseId,requirements:c.requirements,decision:d});r.push(this.activate(a.id)),this.store.transitionPlacement(c.id,"released")}return{moved:r,blocked:i}}reconcileFailure(t){let e=this.fleet.get(t);if(!e)throw Error("Server was not found.");let n=[],r=[];for(let i of this.store.listPlacements(e.projectId,["active"]).filter((c)=>c.serverId===t)){if(i.stateful||!i.autoReschedule){r.push(this.store.transitionPlacement(i.id,"blocked"));continue}this.store.transitionPlacement(i.id,"failed");let c=this.place({projectId:i.projectId,environmentId:i.environmentId,resourceId:i.resourceId,releaseId:i.releaseId,requirements:i.requirements});n.push(this.activate(c.id))}return{rescheduled:n,blocked:r}}}var vn=(t,e)=>{try{return JSON.parse(String(t))}catch{return e}},Ue=(t)=>t==null?void 0:String(t),ZS=(t)=>({id:String(t.id),organizationId:String(t.organization_id),projectId:String(t.project_id),environmentId:Ue(t.environment_id),name:String(t.name),hostname:String(t.hostname),homeRegion:String(t.home_region),regions:vn(t.regions,[]),trafficPolicy:String(t.traffic_policy),dataPolicy:vn(t.data_policy,{replicate:[],maxLagSeconds:60,retainOnDestroy:!0}),status:String(t.status),activeRegion:String(t.active_region),revision:Ue(t.revision),version:Number(t.version),createdAt:String(t.created_at),updatedAt:String(t.updated_at)}),Vs=(t)=>({id:String(t.id),topologyId:String(t.topology_id),region:String(t.region),role:String(t.role),provider:String(t.provider),stackId:Ue(t.stack_id),stackRevision:Ue(t.stack_revision),status:String(t.status),health:vn(t.health,{}),lastHealthyAt:Ue(t.last_healthy_at),version:Number(t.version),createdAt:String(t.created_at),updatedAt:String(t.updated_at)}),Ns=(t)=>({id:String(t.id),topologyId:String(t.topology_id),kind:String(t.kind),sourceRegion:String(t.source_region),targetRegion:String(t.target_region),config:vn(t.config,{}),status:String(t.status),checkpoint:Ue(t.checkpoint),lagSeconds:t.lag_seconds==null?void 0:Number(t.lag_seconds),lastVerifiedAt:Ue(t.last_verified_at),version:Number(t.version),createdAt:String(t.created_at),updatedAt:String(t.updated_at)}),xs=(t)=>({id:String(t.id),topologyId:String(t.topology_id),hostname:String(t.hostname),dnsProvider:String(t.dns_provider),cdnEnabled:Number(t.cdn_enabled)===1,wafEnabled:Number(t.waf_enabled)===1,weights:vn(t.weights,{}),desiredWeights:vn(t.desired_weights,{}),status:String(t.status),providerState:vn(t.provider_state,{}),version:Number(t.version),createdAt:String(t.created_at),updatedAt:String(t.updated_at)}),YS=(t)=>({id:String(t.id),topologyId:String(t.topology_id),operationId:Ue(t.operation_id),kind:String(t.kind),requestedRegion:Ue(t.requested_region),revision:Ue(t.revision),plan:vn(t.plan,[]),currentStep:Ue(t.current_step),completedSteps:vn(t.completed_steps,[]),status:String(t.status),error:Ue(t.error),createdAt:String(t.created_at),updatedAt:String(t.updated_at)});class Ms{control;now;id;constructor(t,e=()=>new Date,n=()=>crypto.randomUUID()){this.control=t;this.now=e;this.id=n}create(t){return this.control.transaction(()=>{if(t.regions.length<2||new Set(t.regions.map((c)=>c.region)).size!==t.regions.length||t.regions.filter((c)=>c.role==="primary").length!==1)throw Error("A topology requires unique regions and exactly one primary.");let e=t.regions.find((c)=>c.role==="primary"),n=this.id(),r=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',?,?,?)",[n,t.organizationId,t.projectId,t.environmentId??null,t.name,t.hostname,e.region,JSON.stringify(t.regions),t.trafficPolicy,JSON.stringify(t.dataPolicy),e.region,r,r]);for(let c of t.regions)this.control.database.run("INSERT INTO regional_targets (id,topology_id,region,role,provider,status,created_at,updated_at) VALUES (?,?,?,?,?,'pending',?,?)",[this.id(),n,c.region,c.role,c.provider,r,r]);for(let c of t.dataPolicy.replicate)for(let d of t.regions)for(let a of t.regions.filter((l)=>l.region!==d.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(),n,c,d.region,a.region,"{}",r,r]);let i=Object.fromEntries(t.regions.map((c)=>[c.region,c.region===e.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(),n,t.hostname,t.dnsProvider??"route53",t.cdnEnabled?1:0,t.wafEnabled?1:0,JSON.stringify(i),JSON.stringify(i),r,r]),this.get(n)})}get(t){let e=this.control.database.query("SELECT * FROM regional_topologies WHERE id=?").get(t);return e?ZS(e):void 0}list(t){return this.control.database.query("SELECT * FROM regional_topologies WHERE project_id=? ORDER BY name").all(t).map(ZS)}targets(t){return this.control.database.query("SELECT * FROM regional_targets WHERE topology_id=? ORDER BY role,region").all(t).map(Vs)}channels(t){return this.control.database.query("SELECT * FROM regional_replication_channels WHERE topology_id=? ORDER BY kind,target_region").all(t).map(Ns)}route(t){let e=this.control.database.query("SELECT * FROM regional_traffic_routes WHERE topology_id=?").get(t);return e?xs(e):void 0}updateTopology(t,e){let n=this.get(t);if(!n)throw Error("Regional topology was not found.");let r={...n,...e},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=?",[r.status,r.activeRegion,r.revision??null,JSON.stringify(r.regions),i,t]),this.get(t)}updateTarget(t,e){let n=this.control.database.query("SELECT * FROM regional_targets WHERE id=?").get(t);if(!n)throw Error("Regional target was not found.");let r=Vs(n),i={...r,...e},c=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,c,t]),Vs(this.control.database.query("SELECT * FROM regional_targets WHERE id=?").get(t))}updateChannel(t,e){let n=this.control.database.query("SELECT * FROM regional_replication_channels WHERE id=?").get(t);if(!n)throw Error("Replication channel was not found.");let r=Ns(n),i={...r,...e},c=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,c,t]),Ns(this.control.database.query("SELECT * FROM regional_replication_channels WHERE id=?").get(t))}updateRoute(t,e){let n=this.control.database.query("SELECT * FROM regional_traffic_routes WHERE id=?").get(t);if(!n)throw Error("Traffic route was not found.");let r=xs(n),i={...r,...e},c=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),c,t]),xs(this.control.database.query("SELECT * FROM regional_traffic_routes WHERE id=?").get(t))}createExecution(t){let e=this.id(),n=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',?,?)",[e,t.topologyId,t.operationId??null,t.kind,t.requestedRegion??null,t.revision??null,JSON.stringify(t.plan),n,n]),this.execution(e)}execution(t){let e=this.control.database.query("SELECT * FROM regional_executions WHERE id=?").get(t);return e?YS(e):void 0}executions(t){return this.control.database.query("SELECT * FROM regional_executions WHERE topology_id=? ORDER BY created_at DESC").all(t).map(YS)}updateExecution(t,e){let n=this.execution(t);if(!n)throw Error("Regional execution was not found.");let r={...n,...e},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=?",[r.operationId??null,r.currentStep??null,JSON.stringify(r.completedSteps),r.status,r.error??null,i,t]),this.execution(t)}}class Qs{store;queue;constructor(t,e){this.store=t;this.queue=e??new Ot(t.control)}create(t){return this.store.create(t)}plan(t,e,n){if(!this.store.get(t))throw Error("Regional topology was not found.");let i=this.store.targets(t),c=this.store.channels(t);if(e==="rollout")return[...i.filter((d)=>d.role==="secondary").map((d)=>`apply:${d.region}`),...i.filter((d)=>d.role==="primary").map((d)=>`apply:${d.region}`),...c.map((d)=>`replicate:${d.kind}:${d.targetRegion}`),"traffic:activate"];if(e==="failover"||e==="failback")return[`health:${n}`,`replication:${n}`,`traffic:${n}`,`roles:${n}`];if(e==="destroy")return["traffic:drain",...i.filter((d)=>d.role==="secondary").map((d)=>`delete:${d.region}`),...i.filter((d)=>d.role==="primary").map((d)=>`delete:${d.region}`),"complete"];return["observe","repair"]}enqueue(t){let e=this.store.get(t.topologyId);if(!e)throw Error("Regional topology was not found.");if(["failover","failback"].includes(t.kind)&&(!t.targetRegion||!e.regions.some((c)=>c.region===t.targetRegion)))throw Error("A topology target region is required.");if(t.kind==="failover"&&t.targetRegion===e.activeRegion)throw Error("Target region is already active.");if((t.kind==="destroy"||t.deleteData)&&t.confirmation!==e.name)throw Error("Exact topology name confirmation is required.");if(t.deleteData&&e.dataPolicy.retainOnDestroy)throw Error("Topology policy requires regional data retention.");if(t.kind==="rollout"&&!/^[A-Za-z0-9._:@/-]{7,200}$/.test(t.revision??""))throw Error("An immutable revision is required.");let n=this.plan(e.id,t.kind,t.targetRegion),r=this.store.createExecution({topologyId:e.id,kind:t.kind,requestedRegion:t.targetRegion,revision:t.revision,plan:n}),i=this.queue.enqueue({projectId:e.projectId,environmentId:e.environmentId,kind:`region.${t.kind}`,input:{executionId:r.id,manifest:t.manifest??{},deleteData:t.deleteData===!0},lockKey:`regional-topology:${e.id}`,providerKey:"multi-region",timeoutSeconds:7200,cancellationMode:"provider_non_cancellable",resumePolicy:"requeue",maxAttempts:3}).operation;return this.store.updateExecution(r.id,{operationId:i.id}),{execution:this.store.execution(r.id),operation:i}}}var M0=(t)=>t&&typeof t==="object"&&!Array.isArray(t)?t:{};function XS(t,e){let n=(o)=>{let u=e.find((f)=>f.provider===o.provider);if(!u)throw Error(`No ${o.provider} regional driver is configured.`);return u},r=(o,u,f)=>{o.throwIfCancellationRequested(),o.checkpoint(f,f),t.updateExecution(u.id,{status:"running",currentStep:f,completedSteps:[...t.execution(u.id).completedSteps,f]})},i=async(o,u)=>{let f=t.route(o.id);if(!f)throw Error("Regional traffic route was not found.");let R=t.targets(o.id).find((y)=>y.region===o.activeRegion)??t.targets(o.id)[0];if(!R)throw Error("Regional traffic target was not found.");t.updateRoute(f.id,{status:"applying",desiredWeights:u});let E=await n(R).applyTraffic({route:t.route(o.id),topology:o,weights:u});t.updateRoute(f.id,{status:Object.values(u).every((y)=>y===0)?"drained":"in_sync",weights:u,providerState:E.providerState})},c=async(o,u,f,R)=>{t.updateTopology(f.id,{status:"provisioning"});let E=u.revision,y=R.manifest??{},$=t.targets(f.id).sort((J,H)=>Number(J.role==="primary")-Number(H.role==="primary"));for(let J of $){r(o,u,`apply:${J.region}`),t.updateTarget(J.id,{status:"provisioning"});let H=await n(J).applyStack({target:J,revision:E,manifest:y,signal:o.signal}),O=await n(J).health({target:t.updateTarget(J.id,{stackId:H.stackId,stackRevision:E})});if(!O.healthy)throw Error(`Regional health gate failed in ${J.region}.`);t.updateTarget(J.id,{status:"ready",health:O.evidence,lastHealthyAt:new Date().toISOString()})}for(let J of t.channels(f.id)){r(o,u,`replicate:${J.kind}:${J.targetRegion}`),t.updateChannel(J.id,{status:"configuring"});let H=$.find((dt)=>dt.region===J.sourceRegion),O=await n(H).configureReplication({channel:J,topology:f}),Y=await n(H).verifyReplication({channel:t.updateChannel(J.id,{checkpoint:O.checkpoint,lagSeconds:O.lagSeconds}),topology:f});if(!Y.healthy||Y.lagSeconds>f.dataPolicy.maxLagSeconds)throw Error(`${J.kind} replication to ${J.targetRegion} exceeds the RPO.`);t.updateChannel(J.id,{status:"in_sync",checkpoint:Y.checkpoint,lagSeconds:Y.lagSeconds,lastVerifiedAt:new Date().toISOString()})}r(o,u,"traffic:activate");let C=Object.fromEntries(f.regions.map((J)=>[J.region,J.region===f.activeRegion?100:0]));return await i(f,C),t.updateTopology(f.id,{status:"ready",revision:E}),{revision:E,activeRegion:f.activeRegion}},d=async(o,u,f)=>{let R=u.requestedRegion,E=t.targets(f.id).find((C)=>C.region===R);if(!E)throw Error("Requested regional target was not found.");t.updateTopology(f.id,{status:u.kind==="failover"?"failing_over":"failing_back"}),r(o,u,`health:${R}`);let y=await n(E).health({target:E});if(!y.healthy)throw Error(`Target region ${R} is unhealthy.`);t.updateTarget(E.id,{status:"ready",health:y.evidence,lastHealthyAt:new Date().toISOString()}),r(o,u,`replication:${R}`);for(let C of t.channels(f.id).filter((J)=>J.targetRegion===R)){let J=await n(E).verifyReplication({channel:C,topology:f});if(!J.healthy||J.lagSeconds>f.dataPolicy.maxLagSeconds)throw Error(`${C.kind} replication is outside the failover RPO.`);t.updateChannel(C.id,{status:"in_sync",checkpoint:J.checkpoint,lagSeconds:J.lagSeconds,lastVerifiedAt:new Date().toISOString()})}r(o,u,`traffic:${R}`),await i(f,Object.fromEntries(f.regions.map((C)=>[C.region,C.region===R?100:0]))),r(o,u,`roles:${R}`);let $=f.regions.map((C)=>({...C,role:C.region===R?"primary":"secondary"}));for(let C of t.targets(f.id))t.updateTarget(C.id,{role:C.region===R?"primary":"secondary"});return t.updateTopology(f.id,{status:u.kind==="failover"?"failed_over":"ready",activeRegion:R,regions:$}),{activeRegion:R}},a=async(o,u,f,R)=>{t.updateTopology(f.id,{status:"destroying"}),r(o,u,"traffic:drain"),await i(f,Object.fromEntries(f.regions.map((y)=>[y.region,0])));let E=R.deleteData!==!0;for(let y of t.targets(f.id).sort(($,C)=>Number($.role==="primary")-Number(C.role==="primary")))r(o,u,`delete:${y.region}`),t.updateTarget(y.id,{status:"deleting"}),await n(y).deleteStack({target:y,retainData:E,signal:o.signal}),t.updateTarget(y.id,{status:"deleted"});return r(o,u,"complete"),t.updateTopology(f.id,{status:"destroyed"}),{destroyed:!0,dataRetained:E}},l=async(o)=>{let u=M0(o.operation.input),f=t.execution(String(u.executionId??""));if(!f)throw Error("Regional execution was not found.");let R=t.get(f.topologyId);if(!R)throw Error("Regional topology was not found.");try{let E;if(f.kind==="rollout")E=await c(o,f,R,u);else if(f.kind==="failover"||f.kind==="failback")E=await d(o,f,R);else if(f.kind==="destroy")E=await a(o,f,R,u);else throw Error("Regional reconciliation is not configured.");return t.updateExecution(f.id,{status:"succeeded",currentStep:void 0}),{executionId:f.id,...E}}catch(E){if(t.updateExecution(f.id,{status:o.cancellationRequested()?"cancelled":"failed",error:E instanceof Error?E.message:String(E)}),t.get(R.id)?.status!=="destroyed")t.updateTopology(R.id,{status:"failed"});throw E}};return{"region.rollout":l,"region.failover":l,"region.failback":l,"region.destroy":l,"region.reconcile":l}}class Gs{provider;reason;constructor(t,e="Configure a regional provider transport before executing this operation."){this.provider=t;this.reason=e}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 on(t,e,n){return[t,e,n].map((r)=>encodeURIComponent(r)).join(":")}function Q0(t){return Object.fromEntries(["start","stop","restart","redeploy","scale","logs","exec","inspect","files"].map((e)=>[e,{supported:!1,reason:t}]))}function $r(t,e,n=["exec","files"]){let r=Q0(e);for(let i of t)r[i]={supported:!0,requiresConfirmation:!["logs","inspect"].includes(i),requiresRecentAuth:n.includes(i)};return r}var G0=/(?:secret|password|passwd|token|api[_-]?key|private[_-]?key|credential|authorization|cookie)/i;function Cn(t){let e=String(t??"").trim().toLowerCase();if(["active","running","ready","healthy","available","steady","active:running"].includes(e))return"running";if(["activating","pending","provisioning","starting","created","initializing"].includes(e))return"starting";if(["deactivating","stopping","draining","terminating"].includes(e))return"stopping";if(["inactive","stopped","complete","completed","exited","disabled"].includes(e))return"stopped";if(["degraded","unhealthy","warning"].includes(e))return"degraded";if(["failed","dead","error","crashed","oomkilled"].includes(e))return"failed";return"unknown"}function kn(t){if(Array.isArray(t))return t.map((n)=>kn(n));if(!t||typeof t!=="object")return t;let e={};for(let[n,r]of Object.entries(t))e[n]=G0.test(n)?"[REDACTED]":kn(r);return e}function vr(t,e=new Date){if(!t)return;let n=new Date(t).getTime();return Number.isFinite(n)?Math.max(0,Math.floor((e.getTime()-n)/1000)):void 0}function KS(t){let e=Number(t);return Number.isFinite(e)&&e>=0?e:void 0}function Z0(t){let e=String(t?.message??t);if(/(?:unauthorized|accessdenied|forbidden|credentials)/i.test(e))return"unauthorized";if(/(?:timeout|unreachable|econnrefused|enotfound|network)/i.test(e))return"unreachable";return"error"}async function pS(t,e={},n={}){let r=e.now??new Date,i=Math.max(100,n.timeoutMs??1e4),c=Math.max(1,n.staleAfterSeconds??60),d=await Promise.all(t.map(async(l)=>{try{let o=await Promise.race([l.discover({...e,now:r}),new Promise((u,f)=>setTimeout(()=>f(Error(`Runtime source ${l.id} timed out after ${i}ms`)),i))]);return{workloads:o,source:{id:l.id,provider:l.provider,status:"fresh",discoveredAt:r.toISOString(),staleAfterSeconds:c,itemCount:o.length}}}catch(o){return{workloads:[],source:{id:l.id,provider:l.provider,status:Z0(o),discoveredAt:r.toISOString(),staleAfterSeconds:c,itemCount:0,message:String(o?.message??o).slice(0,500)}}}})),a=d.map((l)=>l.source);return{generatedAt:r.toISOString(),workloads:d.flatMap((l)=>l.workloads).sort((l,o)=>l.name.localeCompare(o.name)||l.id.localeCompare(o.id)),sources:a,degraded:a.some((l)=>l.status!=="fresh")}}function Y0(t,e){if(!e)return t;return t.startsWith(e)?t.slice(e.length):t}function mS(t,e,n){let r=Y0(t,e);return`${n??""}${r}`}function qS(t,e,n){if(n&&n.some((r)=>t.startsWith(r)))return!1;if(e&&e.length>0)return e.some((r)=>t.startsWith(r));return!0}async function X0(t,e,n){let r=0,i=[],c=Math.max(1,Math.min(e,t.length||1));for(let d=0;d<c;d++)i.push((async()=>{while(!0){let a=r++;if(a>=t.length)return;await n(t[a],a)}})());await Promise.all(i)}function tf(t){if(t.client)return t.client;return ef({provider:t.provider,region:t.region,endpoint:t.endpoint,forcePathStyle:t.forcePathStyle,credentials:t.credentials})}async function M1(t){let e=t.concurrency??8,n=tf(t.from),r=tf(t.to),i=await n.listAllObjects({bucket:t.from.bucket,prefix:t.from.prefix}),c={copied:0,skipped:0,excluded:0,bytesCopied:0,errors:[],excludedKeys:[],deleted:[]},d=[];for(let u of i){if(!qS(u.Key,t.include,t.exclude)){c.excluded++,c.excludedKeys.push(u.Key);continue}d.push({source:u,destKey:mS(u.Key,t.from.prefix,t.to.prefix)})}if(t.dryRun){c.plan=d.map(({source:R,destKey:E})=>({key:R.Key,destKey:E,size:R.Size}));let u=i.length,f=0;for(let R of i){f++;let E=!qS(R.Key,t.include,t.exclude);t.onProgress?.({key:R.Key,destKey:E?"":mS(R.Key,t.from.prefix,t.to.prefix),size:R.Size,action:E?"excluded":"planned",index:f,total:u})}return c}let a=d.length,l=0;await X0(d,e,async({source:u,destKey:f})=>{let R=++l;try{if(!t.force){let $=await r.headObject(t.to.bucket,f);if($&&$.ContentLength===u.Size){c.skipped++,t.onProgress?.({key:u.Key,destKey:f,size:u.Size,action:"skipped",index:R,total:a});return}}let{body:E,contentType:y}=await n.getObjectBytes(t.from.bucket,u.Key);await r.putObject({bucket:t.to.bucket,key:f,body:E,contentType:y}),c.copied++,c.bytesCopied+=E.byteLength,t.onProgress?.({key:u.Key,destKey:f,size:u.Size,action:"copied",index:R,total:a})}catch(E){c.errors.push({key:u.Key,message:E?.message??String(E)}),t.onProgress?.({key:u.Key,destKey:f,size:u.Size,action:"error",index:R,total:a})}});let o=new Set(d.map((u)=>u.destKey));if(t.deleteExtraneous){let f=(await r.listAllObjects({bucket:t.to.bucket,prefix:t.to.prefix})).filter((R)=>!o.has(R.Key)).map((R)=>R.Key);for(let R of f)try{await r.deleteObject(t.to.bucket,R),c.deleted.push(R)}catch(E){c.errors.push({key:R,message:`delete failed: ${E?.message??String(E)}`})}}if(t.verify){let u=await r.listAllObjects({bucket:t.to.bucket,prefix:t.to.prefix}),f=new Map(u.map(($)=>[$.Key,$.Size])),R=[],E=[],y=0;for(let{source:$,destKey:C}of d){if(!f.has(C)){R.push(C);continue}let J=f.get(C);if(J!==$.Size){E.push({key:C,expected:$.Size,actual:J});continue}y++}c.verification={ok:R.length===0&&E.length===0,matched:y,missing:R,sizeMismatches:E}}return c}var K0={aws:"us-east-1",backblaze:"us-west-004",hetzner:"fsn1"};function p0(t,e){switch(t){case"backblaze":return`s3.${e}.backblazeb2.com`;case"hetzner":return`${e}.your-objectstorage.com`;case"aws":default:return}}function Ce(...t){for(let e of t){let n=process.env[e];if(n)return n}return}function m0(t,e){if(e?.accessKeyId&&e.secretAccessKey)return e;let n,r;if(t==="backblaze")n=Ce("B2_APPLICATION_KEY_ID","B2_KEY_ID","S3_ACCESS_KEY_ID","AWS_ACCESS_KEY_ID"),r=Ce("B2_APPLICATION_KEY","B2_SECRET_KEY","S3_SECRET_ACCESS_KEY","AWS_SECRET_ACCESS_KEY");else if(t==="hetzner")n=Ce("HETZNER_S3_ACCESS_KEY","HETZNER_ACCESS_KEY","S3_ACCESS_KEY_ID","AWS_ACCESS_KEY_ID"),r=Ce("HETZNER_S3_SECRET_KEY","HETZNER_SECRET_KEY","S3_SECRET_ACCESS_KEY","AWS_SECRET_ACCESS_KEY");else n=Ce("S3_ACCESS_KEY_ID"),r=Ce("S3_SECRET_ACCESS_KEY");if(n&&r)return{accessKeyId:n,secretAccessKey:r,sessionToken:Ce("AWS_SESSION_TOKEN")};return}function q0(t={}){let e=t.provider||Ce("OBJECT_STORAGE_PROVIDER","STORAGE_PROVIDER")||"aws",n=t.region||(e==="backblaze"?Ce("B2_REGION"):void 0)||(e==="hetzner"?Ce("HETZNER_S3_REGION","HETZNER_REGION"):void 0)||Ce("S3_REGION","AWS_REGION","AWS_DEFAULT_REGION")||K0[e],r=t.endpoint||Ce("S3_ENDPOINT")||p0(e,n),i=t.forcePathStyle??Ce("S3_FORCE_PATH_STYLE")==="true",c=m0(e,t.credentials),d=(a)=>{let l=r||`s3.${n}.amazonaws.com`;return i?`https://${l}/${a}`:`https://${a}.${l}`};return{provider:e,region:n,endpoint:r,forcePathStyle:i,credentials:c,profile:t.profile,publicBaseUrl:d}}function ef(t={}){let e=q0(t),n={endpoint:e.endpoint,forcePathStyle:e.forcePathStyle,credentials:e.credentials};return new _n(e.region,e.profile,n)}class Xi{client;region;constructor(t="us-east-1",e){this.region=t,this.client=new ut(void 0,{profile:e})}async describeServices(t){let e={cluster:t.cluster,services:t.services};return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DescribeServices","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(e)})}async listServices(t,e={}){let n={cluster:t,...e};return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.ListServices","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(n)})}async listTasks(t,e,n={}){let r={cluster:t,...n};if(e)r.serviceName=e;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.ListTasks","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)})}async describeTasks(t,e){let n={cluster:t,tasks:e};return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DescribeTasks","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(n)})}async updateService(t){let e={cluster:t.cluster,service:t.service};if(t.forceNewDeployment!==void 0)e.forceNewDeployment=t.forceNewDeployment;if(t.desiredCount!==void 0)e.desiredCount=t.desiredCount;if(t.taskDefinition)e.taskDefinition=t.taskDefinition;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.UpdateService","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(e)})}async createService(t){let e={cluster:t.cluster,serviceName:t.serviceName,taskDefinition:t.taskDefinition,desiredCount:t.desiredCount};if(t.launchType)e.launchType=t.launchType;if(t.networkConfiguration)e.networkConfiguration=t.networkConfiguration;if(t.loadBalancers)e.loadBalancers=t.loadBalancers;if(t.healthCheckGracePeriodSeconds!==void 0)e.healthCheckGracePeriodSeconds=t.healthCheckGracePeriodSeconds;if(t.deploymentConfiguration)e.deploymentConfiguration=t.deploymentConfiguration;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.CreateService","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(e)})}async deleteService(t){let e={cluster:t.cluster,service:t.service};if(t.force!==void 0)e.force=t.force;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DeleteService","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(e)})}async listClusters(t={}){return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.ListClusters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async describeClusters(t){let e={clusters:t,include:["ATTACHMENTS","CONFIGURATIONS","SETTINGS","STATISTICS","TAGS"]};return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DescribeClusters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(e)})}async stopTask(t){let e={cluster:t.cluster,task:t.task};if(t.reason)e.reason=t.reason;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.StopTask","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(e)})}async runTask(t){let e={cluster:t.cluster,taskDefinition:t.taskDefinition};if(t.count!==void 0)e.count=t.count;if(t.launchType)e.launchType=t.launchType;if(t.networkConfiguration)e.networkConfiguration=t.networkConfiguration;if(t.overrides)e.overrides=t.overrides;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.RunTask","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(e)})}async registerTaskDefinition(t){return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.RegisterTaskDefinition","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async deregisterTaskDefinition(t){return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DeregisterTaskDefinition","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({taskDefinition:t})})}async describeTaskDefinition(t){return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DescribeTaskDefinition","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({taskDefinition:t,include:["TAGS"]})})}async listTaskDefinitionFamilies(t){let e={};if(t?.familyPrefix)e.familyPrefix=t.familyPrefix;if(t?.status)e.status=t.status;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.ListTaskDefinitionFamilies","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(e)})}async waitForServiceStable(t,e,n=40,r=15000){for(let i=0;i<n;i++){let d=(await this.describeServices({cluster:t,services:[e]})).services?.[0];if(d){let a=d.deployments?.find((l)=>l.status==="PRIMARY");if(a&&a.runningCount===a.desiredCount&&d.deployments?.length===1)return!0}await new Promise((a)=>setTimeout(a,r))}return!1}async forceNewDeployment(t,e){return this.updateService({cluster:t,service:e,forceNewDeployment:!0})}async scaleService(t,e,n){return this.updateService({cluster:t,service:e,desiredCount:n})}}class Zs{client;region;constructor(t="us-east-1"){this.region=t,this.client=new ut}buildFormBody(t){return Object.entries(t).filter(([,n])=>n!==void 0).map(([n,r])=>`${encodeURIComponent(n)}=${encodeURIComponent(r)}`).join("&")}async createTopic(t){let e={Action:"CreateTopic",Version:"2010-03-31",Name:t.Name};if(t.DisplayName)e["Attributes.entry.1.key"]="DisplayName",e["Attributes.entry.1.value"]=t.DisplayName;if(t.Tags)t.Tags.forEach((r,i)=>{e[`Tags.member.${i+1}.Key`]=r.Key,e[`Tags.member.${i+1}.Value`]=r.Value});if(t.Attributes){let r=t.DisplayName?2:1;Object.entries(t.Attributes).forEach(([i,c])=>{e[`Attributes.entry.${r}.key`]=i,e[`Attributes.entry.${r}.value`]=c,r++})}let n=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(e)});return{TopicArn:n?.CreateTopicResponse?.CreateTopicResult?.TopicArn||n?.TopicArn}}async deleteTopic(t){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteTopic",Version:"2010-03-31",TopicArn:t})})}async listTopics(t){let e={Action:"ListTopics",Version:"2010-03-31"};if(t)e.NextToken=t;let n=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(e)}),r=n?.ListTopicsResponse?.ListTopicsResult||n?.ListTopicsResult,i=r?.Topics?.member;return{Topics:Array.isArray(i)?i:i?[i]:[],NextToken:r?.NextToken}}async getTopicAttributes(t){let n=(await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"GetTopicAttributes",Version:"2010-03-31",TopicArn:t})}))?.GetTopicAttributesResponse?.GetTopicAttributesResult?.Attributes?.entry,r={TopicArn:t};if(Array.isArray(n))n.forEach((i)=>{r[i.key]=i.value});return r}async setTopicAttributes(t){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"SetTopicAttributes",Version:"2010-03-31",TopicArn:t.TopicArn,AttributeName:t.AttributeName,AttributeValue:t.AttributeValue})})}async subscribe(t){let e={Action:"Subscribe",Version:"2010-03-31",TopicArn:t.TopicArn,Protocol:t.Protocol,Endpoint:t.Endpoint};if(t.ReturnSubscriptionArn)e.ReturnSubscriptionArn="true";if(t.Attributes){let r=1;Object.entries(t.Attributes).forEach(([i,c])=>{e[`Attributes.entry.${r}.key`]=i,e[`Attributes.entry.${r}.value`]=c,r++})}let n=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(e)});return{SubscriptionArn:n?.SubscribeResponse?.SubscribeResult?.SubscriptionArn||n?.SubscriptionArn}}async unsubscribe(t){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"Unsubscribe",Version:"2010-03-31",SubscriptionArn:t})})}async listSubscriptionsByTopic(t,e){let n={Action:"ListSubscriptionsByTopic",Version:"2010-03-31",TopicArn:t};if(e)n.NextToken=e;let r=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(n)}),i=r?.ListSubscriptionsByTopicResponse?.ListSubscriptionsByTopicResult?.Subscriptions?.member;return{Subscriptions:Array.isArray(i)?i:i?[i]:[],NextToken:r?.ListSubscriptionsByTopicResponse?.ListSubscriptionsByTopicResult?.NextToken}}async publish(t){let e={Action:"Publish",Version:"2010-03-31",Message:t.Message};if(t.TopicArn)e.TopicArn=t.TopicArn;if(t.TargetArn)e.TargetArn=t.TargetArn;if(t.PhoneNumber)e.PhoneNumber=t.PhoneNumber;if(t.Subject)e.Subject=t.Subject;if(t.MessageStructure)e.MessageStructure=t.MessageStructure;if(t.MessageAttributes){let r=1;Object.entries(t.MessageAttributes).forEach(([i,c])=>{if(e[`MessageAttributes.entry.${r}.Name`]=i,e[`MessageAttributes.entry.${r}.Value.DataType`]=c.DataType,c.StringValue)e[`MessageAttributes.entry.${r}.Value.StringValue`]=c.StringValue;if(c.BinaryValue)e[`MessageAttributes.entry.${r}.Value.BinaryValue`]=c.BinaryValue;r++})}let n=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(e)});return{MessageId:n?.PublishResponse?.PublishResult?.MessageId||n?.MessageId}}async publishSMS(t,e,n){let r={};if(n)r["AWS.SNS.SMS.SenderID"]={DataType:"String",StringValue:n};return this.publish({PhoneNumber:t,Message:e,MessageAttributes:Object.keys(r).length>0?r:void 0})}async subscribeEmail(t,e){return this.subscribe({TopicArn:t,Protocol:"email",Endpoint:e})}async subscribeLambda(t,e){return this.subscribe({TopicArn:t,Protocol:"lambda",Endpoint:e})}async subscribeSqs(t,e,n){let r={};if(n)r.RawMessageDelivery="true";return this.subscribe({TopicArn:t,Protocol:"sqs",Endpoint:e,Attributes:Object.keys(r).length>0?r:void 0})}async subscribeHttp(t,e,n){let r=e.startsWith("https")?"https":"http",i={};if(n)i.RawMessageDelivery="true";return this.subscribe({TopicArn:t,Protocol:r,Endpoint:e,Attributes:Object.keys(i).length>0?i:void 0})}async subscribeSms(t,e){return this.subscribe({TopicArn:t,Protocol:"sms",Endpoint:e})}async topicExists(t){try{return await this.getTopicAttributes(t),!0}catch(e){if(e.code==="NotFound"||e.statusCode===404)return!1;throw e}}async getSMSAttributes(){let e=(await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"GetSMSAttributes",Version:"2010-03-31"})}))?.GetSMSAttributesResponse?.GetSMSAttributesResult?.attributes?.entry,n={};if(Array.isArray(e))e.forEach((r)=>{n[r.key]=r.value});else if(e)n[e.key]=e.value;return n}async setSMSAttributes(t){let e={Action:"SetSMSAttributes",Version:"2010-03-31"},n=1;Object.entries(t).forEach(([r,i])=>{if(i!==void 0)e[`attributes.entry.${n}.key`]=r,e[`attributes.entry.${n}.value`]=i,n++}),await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(e)})}async checkIfPhoneNumberIsOptedOut(t){return(await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"CheckIfPhoneNumberIsOptedOut",Version:"2010-03-31",phoneNumber:t})}))?.CheckIfPhoneNumberIsOptedOutResponse?.CheckIfPhoneNumberIsOptedOutResult?.isOptedOut==="true"}async listPhoneNumbersOptedOut(t){let e={Action:"ListPhoneNumbersOptedOut",Version:"2010-03-31"};if(t)e.nextToken=t;let n=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(e)}),r=n?.ListPhoneNumbersOptedOutResponse?.ListPhoneNumbersOptedOutResult?.phoneNumbers?.member;return{phoneNumbers:Array.isArray(r)?r:r?[r]:[],nextToken:n?.ListPhoneNumbersOptedOutResponse?.ListPhoneNumbersOptedOutResult?.nextToken}}async optInPhoneNumber(t){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"OptInPhoneNumber",Version:"2010-03-31",phoneNumber:t})})}async listSMSSandboxPhoneNumbers(t){let e={Action:"ListSMSSandboxPhoneNumbers",Version:"2010-03-31"};if(t)e.NextToken=t;let n=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(e)}),r=n?.ListSMSSandboxPhoneNumbersResponse?.ListSMSSandboxPhoneNumbersResult?.PhoneNumbers?.member;return{PhoneNumbers:Array.isArray(r)?r:r?[r]:[],NextToken:n?.ListSMSSandboxPhoneNumbersResponse?.ListSMSSandboxPhoneNumbersResult?.NextToken}}async createSMSSandboxPhoneNumber(t,e){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"CreateSMSSandboxPhoneNumber",Version:"2010-03-31",PhoneNumber:t,LanguageCode:e||"en-US"})})}async verifySMSSandboxPhoneNumber(t,e){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"VerifySMSSandboxPhoneNumber",Version:"2010-03-31",PhoneNumber:t,OneTimePassword:e})})}async deleteSMSSandboxPhoneNumber(t){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteSMSSandboxPhoneNumber",Version:"2010-03-31",PhoneNumber:t})})}async getSMSSandboxAccountStatus(){return{IsInSandbox:(await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"GetSMSSandboxAccountStatus",Version:"2010-03-31"})}))?.GetSMSSandboxAccountStatusResponse?.GetSMSSandboxAccountStatusResult?.IsInSandbox==="true"}}}class kr{client;region;endpoint;constructor(t="us-east-1",e){this.region=t,this.endpoint=e?.endpoint,this.client=new ut}async request(t,e){if(this.endpoint){let n=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-amz-json-1.0","X-Amz-Target":`DynamoDB_20120810.${t}`},body:JSON.stringify(e)});if(!n.ok){let r=await n.text();throw Error(`DynamoDB request failed: ${n.status} ${r}`)}return n.json()}return this.client.request({service:"dynamodb",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.0","X-Amz-Target":`DynamoDB_20120810.${t}`},body:JSON.stringify(e)})}async createTable(t){return this.request("CreateTable",t)}async deleteTable(t){return this.request("DeleteTable",t)}async describeTable(t){return this.request("DescribeTable",t)}async listTables(t){return this.request("ListTables",t||{})}async putItem(t){return this.request("PutItem",t)}async getItem(t){return this.request("GetItem",t)}async updateItem(t){return this.request("UpdateItem",t)}async deleteItem(t){return this.request("DeleteItem",t)}async query(t){return this.request("Query",t)}async scan(t){return this.request("Scan",t)}async batchWriteItem(t){return this.request("BatchWriteItem",t)}async batchGetItem(t){return this.request("BatchGetItem",t)}async updateTimeToLive(t){return this.request("UpdateTimeToLive",t)}static marshal(t){let e={};for(let[n,r]of Object.entries(t))e[n]=kr.marshalValue(r);return e}static marshalValue(t){if(t===null||t===void 0)return{NULL:!0};if(typeof t==="string")return{S:t};if(typeof t==="number")return{N:String(t)};if(typeof t==="boolean")return{BOOL:t};if(Array.isArray(t))return{L:t.map((e)=>kr.marshalValue(e))};if(typeof t==="object")return{M:kr.marshal(t)};return{S:String(t)}}static unmarshal(t){let e={};for(let[n,r]of Object.entries(t))e[n]=kr.unmarshalValue(r);return e}static unmarshalValue(t){if(t.S!==void 0)return t.S;if(t.N!==void 0)return Number(t.N);if(t.BOOL!==void 0)return t.BOOL;if(t.NULL!==void 0)return null;if(t.L!==void 0)return t.L.map((e)=>kr.unmarshalValue(e));if(t.M!==void 0)return kr.unmarshal(t.M);if(t.SS!==void 0)return t.SS;if(t.NS!==void 0)return t.NS.map(Number);return null}}class Ys{client;region;constructor(t="us-east-1"){this.region=t,this.client=new ut}async request(t,e){return this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`AWSEvents.${t}`},body:JSON.stringify(e)})}async putRule(t){return this.request("PutRule",t)}async deleteRule(t){return this.request("DeleteRule",t)}async describeRule(t){return this.request("DescribeRule",t)}async listRules(t){return this.request("ListRules",t||{})}async listEventBuses(t){return this.request("ListEventBuses",t||{})}async enableRule(t){return this.request("EnableRule",t)}async disableRule(t){return this.request("DisableRule",t)}async putTargets(t){return this.request("PutTargets",t)}async removeTargets(t){return this.request("RemoveTargets",t)}async listTargetsByRule(t){return this.request("ListTargetsByRule",t)}async putEvents(t){return this.request("PutEvents",t)}async createSchedule(t){return this.client.request({service:"scheduler",region:this.region,method:"POST",path:`/schedules/${t.Name}`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}}class nf{client;region;constructor(t="us-east-1",e){this.region=t,this.client=new ut}async createRule(t){let e={Action:"PutRule",Name:t.name,ScheduleExpression:t.scheduleExpression,Version:"2015-10-07"};if(t.description)e.Description=t.description;if(t.state)e.State=t.state;else e.State="ENABLED";return{RuleArn:(await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.PutRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:t.name,ScheduleExpression:t.scheduleExpression,State:t.state||"ENABLED",Description:t.description})})).RuleArn}}async putTargets(t,e){await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.PutTargets","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Rule:t,Targets:e})})}async listRules(t){let e={};if(t)e.NamePrefix=t;return{Rules:(await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.ListRules","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(e)})).Rules||[]}}async describeRule(t){let e=await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.DescribeRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:t})});return{Name:e.Name,Arn:e.Arn,ScheduleExpression:e.ScheduleExpression,State:e.State,Description:e.Description}}async listTargetsByRule(t){return{Targets:(await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.ListTargetsByRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Rule:t})})).Targets||[]}}async deleteRule(t,e){if(e)try{let n=await this.listTargetsByRule(t);if(n.Targets&&n.Targets.length>0)await this.removeTargets(t,n.Targets.map((r)=>r.Id))}catch{}await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.DeleteRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:t,Force:e||!1})})}async removeTargets(t,e){await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.RemoveTargets","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Rule:t,Ids:e})})}async enableRule(t){await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.EnableRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:t})})}async disableRule(t){await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.DisableRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:t})})}async createLambdaSchedule(t){let e=await this.createRule({name:t.name,scheduleExpression:t.scheduleExpression,description:t.description,state:"ENABLED"});return await this.putTargets(t.name,[{Id:"1",Arn:t.functionArn,Input:t.input}]),e}async createEcsSchedule(t){let e=await this.createRule({name:t.name,scheduleExpression:t.scheduleExpression,description:t.description,state:"ENABLED"});return await this.putTargets(t.name,[{Id:"1",Arn:t.clusterArn,RoleArn:t.roleArn,Input:JSON.stringify({containerOverrides:[]})}]),e}async listSchedules(t){let e={};if(t?.NamePrefix)e.NamePrefix=t.NamePrefix;if(t?.State)e.State=t.State;let n=t?.GroupName||"default";return{Schedules:(await this.client.request({service:"scheduler",region:this.region,method:"GET",path:"/schedules",queryParams:{...e,ScheduleGroup:n}}))?.Schedules||[]}}async getSchedule(t){try{let e={};if(t.GroupName)e.groupName=t.GroupName;return await this.client.request({service:"scheduler",region:this.region,method:"GET",path:`/schedules/${encodeURIComponent(t.Name)}`,queryParams:Object.keys(e).length>0?e:void 0})}catch(e){if(e.statusCode===404||e.code==="ResourceNotFoundException")return null;throw e}}async createSchedule(t){let e={ScheduleExpression:t.ScheduleExpression,FlexibleTimeWindow:t.FlexibleTimeWindow,Target:t.Target};if(t.GroupName)e.GroupName=t.GroupName;if(t.ScheduleExpressionTimezone)e.ScheduleExpressionTimezone=t.ScheduleExpressionTimezone;if(t.Description)e.Description=t.Description;if(t.State)e.State=t.State;if(t.StartDate)e.StartDate=t.StartDate.toISOString();if(t.EndDate)e.EndDate=t.EndDate.toISOString();return{ScheduleArn:(await this.client.request({service:"scheduler",region:this.region,method:"POST",path:`/schedules/${encodeURIComponent(t.Name)}`,headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}))?.ScheduleArn||""}}async updateSchedule(t){let e={};if(t.GroupName)e.GroupName=t.GroupName;if(t.ScheduleExpression)e.ScheduleExpression=t.ScheduleExpression;if(t.ScheduleExpressionTimezone)e.ScheduleExpressionTimezone=t.ScheduleExpressionTimezone;if(t.Description!==void 0)e.Description=t.Description;if(t.State)e.State=t.State;if(t.FlexibleTimeWindow)e.FlexibleTimeWindow=t.FlexibleTimeWindow;if(t.Target)e.Target=t.Target;return{ScheduleArn:(await this.client.request({service:"scheduler",region:this.region,method:"PUT",path:`/schedules/${encodeURIComponent(t.Name)}`,headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}))?.ScheduleArn||""}}async deleteSchedule(t){let e={};if(t.GroupName)e.groupName=t.GroupName;await this.client.request({service:"scheduler",region:this.region,method:"DELETE",path:`/schedules/${encodeURIComponent(t.Name)}`,queryParams:Object.keys(e).length>0?e:void 0})}async listScheduleGroups(t){let e={};if(t?.NamePrefix)e.NamePrefix=t.NamePrefix;return{ScheduleGroups:(await this.client.request({service:"scheduler",region:this.region,method:"GET",path:"/schedule-groups",queryParams:Object.keys(e).length>0?e:void 0}))?.ScheduleGroups||[]}}}function hi(t){return t?.split("/").at(-1)??t?.split(":").at(-1)??"unknown"}function rf(t,e,n,r="ecs:aws",i=[]){let c=n.now??new Date;return t.map((d)=>{let a=d.serviceName??hi(d.serviceArn),l=e.filter((J)=>!d.clusterArn||J.clusterArn===d.clusterArn),o=l.some((J)=>!!J.group)?l.filter((J)=>J.group===`service:${a}`):l,u=d.status==="ACTIVE"?(d.runningCount??0)<(d.desiredCount??0)?"degraded":"running":Cn(d.status),f=i.find((J)=>J.taskDefinitionArn===d.taskDefinition),R=Array.isArray(f?.containerDefinitions)?f.containerDefinitions:[],E=[...new Set(R.map((J)=>J.logConfiguration?.options?.["awslogs-group"]).filter((J)=>typeof J==="string"))],y=R.flatMap((J)=>(J.mountPoints??[]).map((H)=>({source:H.sourceVolume,target:H.containerPath,type:"volume",readOnly:!!H.readOnly}))),$=R.flatMap((J)=>(J.portMappings??[]).map((H,O)=>({id:`${J.name??"container"}:${O}`,name:J.name,mode:f?.networkMode,ports:[{container:H.containerPort,host:H.hostPort,protocol:H.protocol}]}))),C=n.project&&n.environment&&a.startsWith(`${n.project}-${n.environment}-`)?a.slice(`${n.project}-${n.environment}-`.length):a;return{id:on("ecs",r,d.serviceArn??a),provider:"ecs",kind:"service",name:a,status:u,rawStatus:d.status,health:u==="running"?"healthy":u==="failed"||u==="degraded"?"unhealthy":"unknown",desiredReplicas:d.desiredCount,runningReplicas:d.runningCount,image:R[0]?.image,runtime:d.launchType??"ECS",version:hi(d.taskDefinition),ageSeconds:vr(d.deployments?.[0]?.createdAt,c),restartCount:0,tags:{},links:{project:n.project,environment:n.environment,service:C,release:hi(d.taskDefinition),providerId:d.serviceArn},replicas:o.map((J)=>{let H=Cn(J.lastStatus);return{id:on("ecs",r,J.taskArn??hi(J.taskArn)),name:hi(J.taskArn),status:H,rawStatus:J.lastStatus,createdAt:J.createdAt,startedAt:J.startedAt,stoppedAt:J.stoppedAt,host:J.containerInstanceArn,containers:(J.containers??[]).map((O)=>({id:O.containerArn??O.name??"container",name:O.name??"container",image:R.find((Y)=>Y.name===O.name)?.image,imageDigest:O.imageDigest,status:Cn(O.lastStatus),rawStatus:O.lastStatus,exitCode:O.exitCode,reason:O.reason,runtime:"ecs"}))}}),networks:$,mounts:y,capabilities:$r(["start","stop","restart","redeploy","scale","inspect",...E.length?["logs"]:[]],"This ECS runtime does not expose exec or file transfer; logs require an awslogs task-definition driver"),config:kn({clusterArn:d.clusterArn,taskDefinition:d.taskDefinition,launchType:d.launchType,pendingCount:d.pendingCount,deployments:d.deployments,logGroups:E,executionRoleArn:f?.executionRoleArn,taskRoleArn:f?.taskRoleArn,cpu:f?.cpu,memory:f?.memory}),discoveredAt:c.toISOString(),sourceId:r}})}function cf(t,e,n="lambda:aws"){let r=e.now??new Date;return t.map((i)=>{let c=i.FunctionName??hi(i.FunctionArn),d=i.State==="Active"?"running":Cn(i.State);return{id:on("lambda",n,i.FunctionArn??c),provider:"lambda",kind:"function",name:c,status:d,rawStatus:i.State,health:d==="running"?"healthy":d==="failed"?"unhealthy":"unknown",desiredReplicas:void 0,runningReplicas:void 0,image:void 0,runtime:i.Runtime,version:i.Version,architecture:i.Architectures?.join(", "),ageSeconds:vr(i.LastModified,r),restartCount:0,tags:{},links:{project:e.project,environment:e.environment,service:c,providerId:i.FunctionArn},resources:{memoryLimitBytes:i.MemorySize==null?void 0:i.MemorySize*1024*1024},replicas:[],networks:[],mounts:[],capabilities:$r(["logs","inspect"],"Lambda has no persistent process to start, stop, restart, exec, or browse files; deploy a release to replace code"),config:kn({handler:i.Handler,timeout:i.Timeout,codeSize:i.CodeSize,stateReason:i.StateReason,environmentKeys:Object.keys(i.Environment?.Variables??{})}),discoveredAt:r.toISOString(),sourceId:n}})}function tD(t){let e=t.trim();if(!e)return[];let n=JSON.parse(e);if(!Array.isArray(n))throw Error("Docker inspect output must be an array");return n.filter((r)=>r&&typeof r.Id==="string")}function eD(t){let e=Object.entries(t.NetworkSettings?.Ports??{}).flatMap(([n,r])=>{let[i,c]=n.split("/");return(r??[]).map((d)=>({container:Number(i)||void 0,host:Number(d.HostPort)||void 0,protocol:c,address:d.HostIp}))});return Object.entries(t.NetworkSettings?.Networks??{}).map(([n,r])=>({id:r.NetworkID||n,name:n,mode:t.HostConfig?.NetworkMode,addresses:[r.IPAddress,r.GlobalIPv6Address].filter(Boolean),ports:e}))}function nD(t){return(t.Mounts??[]).filter((e)=>!!e.Destination).map((e)=>({source:e.Source,target:e.Destination,type:e.Type,readOnly:e.RW===!1}))}function rD(t,e,n=e.server??"local"){let r=e.now??new Date;return t.map((i)=>{let c=i.State?.OOMKilled?"oomkilled":i.State?.Restarting?"starting":i.State?.Status,d=Cn(c),a=(i.Name??i.Id.slice(0,12)).replace(/^\//,""),l=i.Config?.Labels??{},o=nD(i),u=eD(i),f={id:i.Id,name:a,image:i.Config?.Image,imageDigest:i.Image,runtime:"docker",status:d,rawStatus:c,exitCode:i.State?.ExitCode,reason:i.State?.Error,resources:{memoryLimitBytes:i.HostConfig?.Memory||void 0},networks:u,mounts:o};return{id:on("docker",n,i.Id),provider:"docker",kind:"container",name:a,status:d,rawStatus:c,health:d==="running"?"healthy":d==="failed"?"unhealthy":"unknown",desiredReplicas:1,runningReplicas:d==="running"?1:0,image:i.Config?.Image,runtime:"docker",ageSeconds:vr(i.State?.StartedAt,r),restartCount:i.RestartCount??0,tags:l,links:{project:e.project,environment:e.environment,server:e.server??n.replace(/^docker:/,""),service:l["com.docker.compose.service"]??l["ts-cloud.service"]??a,release:l["ts-cloud.release"],providerId:i.Id},resources:f.resources,replicas:[{id:on("docker",n,`${i.Id}:0`),name:a,status:d,rawStatus:c,startedAt:i.State?.StartedAt,stoppedAt:i.State?.FinishedAt,restartCount:i.RestartCount,containers:[f],resources:f.resources}],networks:u,mounts:o,capabilities:$r(["start","stop","restart","logs","exec","inspect","files"],"Use the owning Compose service for redeploy and scale"),config:kn({image:i.Config?.Image,labels:l,environmentKeys:(i.Config?.Env??[]).map((R)=>R.split("=",1)[0]),networkMode:i.HostConfig?.NetworkMode}),discoveredAt:r.toISOString(),sourceId:n}})}class Xs{inspect;id;provider="docker";constructor(t,e="docker:local"){this.inspect=t;this.id=e}async discover(t){return rD(tD(await this.inspect(t)),t,this.id)}}function iD(t){let e=[];for(let n of t.split(`
|
|
121
|
-
`)){if(!n.startsWith("TSCLOUD_SYSTEMD\t"))continue;let[,r,i,c,d,a,l,o,u,f,R,E,y,$]=n.split("\t");if(!r||!/^[A-Za-z0-9_.@:-]+\.service$/.test(r))continue;e.push({unit:r,load:i,active:c,sub:d,description:a,enabled:l,pid:Number(o)||void 0,memoryBytes:KS(u),restartCount:Number(f)||0,activeSince:R||void 0,fragmentPath:E||void 0,workingDirectory:y?.startsWith("/")?y:void 0,user:$||void 0})}return e}function cD(t,e,n=e.server??"local"){let r=e.now??new Date;return t.map((i)=>{let c=Cn(i.active==="active"?i.sub||i.active:i.active),d=i.unit.replace(/\.service$/,""),a=/^(.*?) (?:release [^ ]+|queue worker|daemon |scheduler)(?: |$)/.exec(i.description??"")?.[1]??(e.project&&d.startsWith(`${e.project}-`)?d.slice(e.project.length+1).split("@",1)[0]:void 0),l=d.includes("@")?d.slice(d.indexOf("@")+1):void 0,o=i.workingDirectory?[{target:i.workingDirectory,type:"working-directory"}]:[],u=["start","stop","restart","logs","exec","inspect",...o.length?["files"]:[]];return{id:on("systemd",n,i.unit),provider:"systemd",kind:"service",name:d,displayName:i.description||d,status:c,rawStatus:[i.load,i.active,i.sub].filter(Boolean).join("/"),health:c==="running"?"healthy":c==="failed"?"unhealthy":"unknown",desiredReplicas:1,runningReplicas:c==="running"?1:0,ageSeconds:vr(i.activeSince,r),restartCount:i.restartCount,tags:{enabled:i.enabled??"unknown"},links:{project:e.project,environment:e.environment,server:e.server??n.replace(/^systemd:/,""),service:a,release:l,providerId:i.unit},resources:{memoryBytes:i.memoryBytes},replicas:[{id:on("systemd",n,`${i.unit}:main`),name:"main",status:c,pid:i.pid,startedAt:i.activeSince,restartCount:i.restartCount,resources:{memoryBytes:i.memoryBytes}}],networks:[],mounts:o,capabilities:$r(u,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:kn({fragmentPath:i.fragmentPath,workingDirectory:i.workingDirectory,user:i.user,environment:i.environment,enabled:i.enabled}),discoveredAt:r.toISOString(),sourceId:n}})}class Ks{read;id;provider="systemd";constructor(t,e="systemd:local"){this.read=t;this.id=e}async discover(t){return cD(iD(await this.read(t)),t,this.id)}}function dD(t,e){if(!t.success)throw Error(t.error||t.perInstance?.[0]?.error||`${e} discovery failed`);return t.perInstance?.[0]?.output??""}function oD(){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 aD(){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 df(t,e,n,r,i){let c=`${t}:${n.id}`,d=async()=>dD(await e.runRemoteDeploy({targets:[n],commands:t==="systemd"?oD():aD(),timeoutSeconds:30,comment:`ts-cloud runtime discovery:${t}`,tags:{Project:r.project.slug,Environment:i,Role:"app"}}),c);return t==="systemd"?new Ks(d,c):new Xs(d,c)}async function Ld(t,e=100){let n=[],r;for(let i=0;i<e;i++){let c=await t(r);if(n.push(...c.items),!c.nextToken)return n;r=c.nextToken}throw Error(`Provider pagination exceeded ${e} pages`)}class of{client;prefix;id="ecs:aws";provider="ecs";constructor(t,e){this.client=t;this.prefix=e}async discover(t){let e=await Ld(async(c)=>{let d=await this.client.listClusters({nextToken:c,maxResults:100});return{items:d.clusterArns??[],nextToken:d.nextToken}}),n=[],r=[],i=[];for(let c of e){let d=(await Ld(async(a)=>{let l=await this.client.listServices(c,{nextToken:a,maxResults:100});return{items:l.serviceArns??[],nextToken:l.nextToken}})).filter((a)=>a.split("/").at(-1)?.startsWith(this.prefix));for(let a=0;a<d.length;a+=10){let l=await this.client.describeServices({cluster:c,services:d.slice(a,a+10)});n.push(...l.services??[])}for(let a of n.filter((l)=>l.clusterArn===c||!l.clusterArn)){let l=await Ld(async(o)=>{let u=await this.client.listTasks(c,a.serviceName,{nextToken:o,maxResults:100});return{items:u.taskArns??[],nextToken:u.nextToken}});for(let o=0;o<l.length;o+=100){let u=await this.client.describeTasks(c,l.slice(o,o+100));r.push(...u.tasks??[])}}}if(this.client.describeTaskDefinition)for(let c of[...new Set(n.map((d)=>d.taskDefinition).filter((d)=>!!d))]){let d=await this.client.describeTaskDefinition(c);if(d.taskDefinition)i.push(d.taskDefinition)}return rf(n,r,t,this.id,i)}}class af{client;prefix;id="lambda:aws";provider="lambda";constructor(t,e){this.client=t;this.prefix=e}async discover(t){let e=(await Ld(async(n)=>{let r=await this.client.listFunctions({Marker:n,MaxItems:50});return{items:r.Functions??[],nextToken:r.NextMarker}})).filter((n)=>n.FunctionName?.startsWith(this.prefix));return cf(e,t,this.id)}}async function sD(t,e,n={}){let r=[],i=On(t),c=ps(t),d=t.aws?.profile,a=t.aws?.region??t.project.region??"us-east-1",l=`${t.project.slug}-${e}`;if(i!=="serverless"){let o=n.driver??Jn({config:t}),u=await o.findComputeTargets({slug:t.project.slug,environment:e,role:"app"});for(let f of u)r.push(df("systemd",o,f,t,e)),r.push(df("docker",o,f,t,e))}if(c==="aws")r.push(new of(n.ecs??new Xi(a,d),l)),r.push(new af(n.lambda??new Fd(a,d),l));return r}async function Ge(t,e,n={}){let r={project:t.project.slug,environment:e};try{return await pS(await sD(t,e,n),r)}catch(i){return{generatedAt:new Date().toISOString(),workloads:[],sources:[{id:"runtime:bootstrap",provider:ps(t)==="aws"?"ecs":"systemd",status:"error",discoveredAt:new Date().toISOString(),staleAfterSeconds:60,itemCount:0,message:String(i?.message??i).slice(0,500)}],degraded:!0}}}var sf=65536,Ki=49152,Nd=/^[A-Za-z0-9_.@:-]+\.service$/,xd=/^[a-fA-F0-9]{12,128}$/,lD=["/boot","/dev","/etc","/proc","/root","/run","/sys","/var/run"];function Si(t){let e=Buffer.from(t);return e.byteLength<=sf?t:`${e.subarray(0,sf-24).toString("utf8")}
|
|
122
|
-
[output truncated]`}function Vd(t){return{success:!1,instanceCount:0,perInstance:[],error:t instanceof Error?t.message:String(t)}}function je(t){return`'${t.replaceAll("'",`'"'"'`)}'`}function gD(t,e){return Number.isFinite(t)?Math.min(1e4,Math.max(0,Math.floor(t))):e}function uD(t){let e=t.config,n=typeof e.clusterArn==="string"?e.clusterArn:void 0,r=t.links.providerId||t.name;return n&&r?{cluster:n,service:r}:void 0}function hD(t,e){return t.find((n)=>n.id===e.links.server)??(t.length===1?t[0]:void 0)}function SD(t,e){if(t.provider==="systemd"){let n=t.links.providerId;if(!n||!Nd.test(n)||!["start","stop","restart"].includes(e))return;return[`systemctl ${e} ${n}`,`systemctl is-active ${n} 2>/dev/null || true`]}if(t.provider==="docker"){let n=t.links.providerId;if(!n||!xd.test(n)||!["start","stop","restart"].includes(e))return;return[`docker ${e} ${n}`,`docker inspect --format '{{.State.Status}}' ${n}`]}return}function fD(t,e){if(!e.startsWith("/")||e.includes("\x00"))return{ok:!1,error:"An absolute path is required."};let n=[];for(let a of e.split("/")){if(!a||a===".")continue;if(a===".."){if(!n.length)return{ok:!1,error:"Path traversal is not allowed."};n.pop()}else n.push(a)}let r=`/${n.join("/")}`;if(lD.some((a)=>r===a||r.startsWith(`${a}/`)))return{ok:!1,error:"Sensitive host paths are not available through runtime file access."};let i=t.links.project?.replace(/[^A-Za-z0-9_-]/g,""),c=t.links.service?.replace(/[^A-Za-z0-9_-]/g,"");if(![...i&&c?[`/var/www/${i}/${c}`,`/srv/${i}/${c}`]:[],...t.mounts.map((a)=>a.target).filter((a)=>a.startsWith("/"))].some((a)=>r===a||r.startsWith(`${a.replace(/\/$/,"")}/`)))return{ok:!1,error:"Path is outside this service’s owned roots."};return{ok:!0,path:r}}function _D(t,e){let n=t.links.project?.replace(/[^A-Za-z0-9_-]/g,""),r=t.links.service?.replace(/[^A-Za-z0-9_-]/g,"");return[...n&&r?[`/var/www/${n}/${r}`,`/srv/${n}/${r}`]:[],...t.mounts.map((i)=>i.target).filter((i)=>i.startsWith("/"))].sort((i,c)=>c.length-i.length).find((i)=>e===i||e.startsWith(`${i.replace(/\/$/,"")}/`))}var lf={process:["ps","-eo","pid,ppid,user,%cpu,%mem,etime,command","--sort=-%cpu"],sockets:["ss","-lntup"],filesystem:["df","-h"]};class an{config;environment;dependencies;region;profile;constructor(t,e,n={}){this.config=t;this.environment=e;this.dependencies=n;this.region=t.aws?.region??t.project.region??"us-east-1",this.profile=t.aws?.profile}async inventory(){return this.dependencies.inventory?.()??Ge(this.config,this.environment,{driver:this.dependencies.driver})}async workload(t){return(await this.inventory()).workloads.find((e)=>e.id===t)}async remote(t,e,n,r){let i=this.dependencies.driver??Jn({config:this.config}),c=await i.findComputeTargets({slug:this.config.project.slug,environment:this.environment,role:"app"}),d=hD(c,t);if(!d)throw Error("The workload server is no longer reachable in this scope.");return i.runRemoteDeploy({targets:[d],commands:e,timeoutSeconds:n,comment:r,tags:{Project:this.config.project.slug,Environment:this.environment,Role:"app"}})}async run(t){let e=await this.workload(t.workloadId),n={workloadId:t.workloadId,action:t.action};if(!e)return{...n,ok:!1,error:"Workload was not found in the current project and environment."};let r=e.capabilities[t.action];if(!r.supported)return{...n,ok:!1,error:r.reason??`${t.action} is unsupported for ${e.provider}.`};if(r.requiresConfirmation&&t.confirm!==e.name)return{...n,ok:!1,error:`Type "${e.name}" to ${t.action} this workload.`};if(r.requiresRecentAuth&&!t.recentAuth)return{...n,ok:!1,error:"Sign in again before using elevated runtime access."};if(t.action==="inspect")return{...n,ok:!0,workload:e};if(e.provider==="systemd"||e.provider==="docker"){let i=SD(e,t.action);if(!i)return{...n,ok:!1,error:`${t.action} is not implemented for ${e.provider}.`};let c=await this.remote(e,["set -uo pipefail",...i],60,`ts-cloud runtime:${t.action}`).catch(Vd);return{...n,ok:c.success,command:i[0],stdout:Si(c.perInstance?.[0]?.output??""),stderr:Si(c.perInstance?.[0]?.error??c.error??""),error:c.success?void 0:c.error??"Runtime operation failed."}}if(e.provider==="ecs"){let i=uD(e);if(!i)return{...n,ok:!1,error:"ECS cluster or service identity is unavailable."};let c=this.dependencies.ecs??new Xi(this.region,this.profile);if(t.action==="scale"){let d=gD(t.replicas,e.desiredReplicas??1);return await c.scaleService(i.cluster,i.service,d),{...n,ok:!0,command:`ecs scale ${e.name} ${d}`}}if(t.action==="start"||t.action==="stop"){let d=t.action==="stop"?0:Math.max(1,e.desiredReplicas??1);return await c.scaleService(i.cluster,i.service,d),{...n,ok:!0,command:`ecs scale ${e.name} ${d}`}}if(t.action==="restart"||t.action==="redeploy")return await c.forceNewDeployment(i.cluster,i.service),{...n,ok:!0,command:`ecs redeploy ${e.name}`}}return{...n,ok:!1,error:`${t.action} is not implemented for ${e.provider}.`}}async exec(t){let e={workloadId:t.workloadId,preset:t.preset},n=await this.workload(t.workloadId);if(!n)return{...e,ok:!1,error:"Workload was not found in the current project and environment."};if(process.env.TS_CLOUD_RUNTIME_EXEC==="0")return{...e,ok:!1,error:"Runtime exec is disabled by TS_CLOUD_RUNTIME_EXEC."};if(!n.capabilities.exec.supported)return{...e,ok:!1,error:n.capabilities.exec.reason??"Exec is unsupported for this workload."};if(t.confirm!==n.name)return{...e,ok:!1,error:`Type "${n.name}" to open exec access.`};if(!t.recentAuth)return{...e,ok:!1,error:"Sign in again before using elevated runtime access."};let r=t.preset&&lf[t.preset];if(!r&&!t.command?.trim())return{...e,ok:!1,error:"Choose a diagnostic preset or provide a command."};if(t.command&&n.provider!=="docker")return{...e,ok:!1,error:"Free-form exec is restricted to isolated containers; use a diagnostic preset for system services."};let i=n.links.providerId??"",c;if(n.provider==="docker"&&xd.test(i)){let a=t.command?.trim()||r.map(je).join(" ");c=`docker exec ${i} sh -lc ${je(a)}`}else if(n.provider==="systemd"&&Nd.test(i)&&t.preset)c=t.preset==="process"?`systemctl status ${i} --no-pager --full`:lf[t.preset].map(je).join(" ");if(!c)return{...e,ok:!1,error:"Exec target identity is invalid or unsupported."};let d=await this.remote(n,["set -uo pipefail",c],60,"ts-cloud runtime:exec").catch(Vd);return{...e,ok:d.success,command:c,stdout:Si(d.perInstance?.[0]?.output??""),stderr:Si(d.perInstance?.[0]?.error??d.error??""),error:d.success?void 0:d.error??"Exec command failed."}}async readFile(t){let e={workloadId:t.workloadId,path:t.path},n=await this.fileTarget(t);if("error"in n)return{...e,ok:!1,error:n.error};let{workload:r,path:i,root:c,providerId:d}=n,l=`sh -c ${je('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 ${je(i)} ${Ki} ${je(c)}`,o=r.provider==="docker"?`docker exec ${d} ${l}`:l,u=await this.remote(r,[o],30,"ts-cloud runtime:file-read").catch(Vd);if(!u.success)return{...e,ok:!1,error:u.error??u.perInstance?.[0]?.error??"File read failed."};let f=u.perInstance?.[0]?.output??"",R=/__TSCLOUD_SIZE__=(\d+)\r?\n/.exec(f);if(!R)return{...e,ok:!1,error:"The remote file response was invalid."};let E=Number(R[1]),y=f.slice((R.index??0)+R[0].length).replace(/\s+/g,"");if(Buffer.from(y,"base64").byteLength>Ki)return{...e,ok:!1,error:"The remote file exceeded the transfer limit."};return{...e,ok:!0,contentBase64:y,size:E,truncated:E>Ki}}async writeFile(t){let e={workloadId:t.workloadId,path:t.path},n=await this.fileTarget(t);if("error"in n)return{...e,ok:!1,error:n.error};if(!/^[A-Za-z0-9+/]*={0,2}$/.test(t.contentBase64))return{...e,ok:!1,error:"File content must be valid base64."};let r=Buffer.from(t.contentBase64,"base64");if(r.toString("base64")!==t.contentBase64)return{...e,ok:!1,error:"File content must be canonical base64."};if(r.byteLength>Ki)return{...e,ok:!1,error:`File uploads are limited to ${Ki} bytes.`};let{workload:i,path:c,root:d,providerId:a}=n,o=`sh -c ${je('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 ${je(c)} ${je(d)}`,u=i.provider==="docker"?`printf %s ${je(t.contentBase64)} | docker exec -i ${a} ${o}`:`printf %s ${je(t.contentBase64)} | ${o}`,f=await this.remote(i,[u],30,"ts-cloud runtime:file-write").catch(Vd);return{...e,ok:f.success,size:r.byteLength,truncated:!1,error:f.success?void 0:f.error??f.perInstance?.[0]?.error??"File write failed."}}async fileTarget(t){let e=await this.workload(t.workloadId);if(!e)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(!e.capabilities.files.supported)return{error:e.capabilities.files.reason??"File access is unsupported for this workload."};if(t.confirm!==e.name)return{error:`Type "${e.name}" to access workload files.`};if(!t.recentAuth)return{error:"Sign in again before using elevated runtime access."};let n=fD(e,t.path);if(!n.ok)return{error:n.error};let r=_D(e,n.path),i=e.links.providerId??"";if(!r||e.provider==="systemd"&&!Nd.test(i)||e.provider==="docker"&&!xd.test(i))return{error:"File target identity is invalid or unsupported."};return{workload:e,path:n.path,root:r,providerId:i}}async logs(t,e={}){let n=await this.workload(t);if(!n)throw Error("Workload was not found in the current project and environment.");if(!n.capabilities.logs.supported)throw Error(n.capabilities.logs.reason??"Logs are unsupported for this workload.");let r=Math.min(1000,Math.max(1,Math.floor(e.limit??200)));if(n.provider==="lambda"||n.provider==="ecs"){let u=this.dependencies.logs??new gf(this.region,this.profile),f=n.config.logGroups,R=n.provider==="lambda"?`/aws/lambda/${n.name}`:Array.isArray(f)&&typeof f[0]==="string"?f[0]:void 0;if(!R)throw Error("The ECS task definition does not declare an awslogs group.");let E=await u.filterLogEvents({logGroupName:R,startTime:e.since?.getTime(),limit:r}),y=(E.events??[]).slice(0,r).map(($)=>({timestamp:$.timestamp==null?void 0:new Date($.timestamp).toISOString(),message:Si(String($.message??""))}));return{workloadId:t,provider:n.provider,lines:y,nextCursor:E.nextToken,truncated:(E.events?.length??0)>=r}}let i=n.links.providerId??"",c=e.since&&Number.isFinite(e.since.getTime())?e.since:void 0,d=n.provider==="systemd"&&Nd.test(i)?`journalctl -u ${i} --no-pager -n ${r} -o short-iso${c?` --since ${je(c.toISOString())}`:""}`:n.provider==="docker"&&xd.test(i)?`docker logs --timestamps --tail ${r}${c?` --since ${Math.floor(c.getTime()/1000)}`:""} ${i} 2>&1`:void 0;if(!d)throw Error("Log target identity is invalid.");let a=await this.remote(n,[d],30,"ts-cloud runtime:logs");if(!a.success)throw Error(a.error??a.perInstance?.[0]?.error??"Log read failed.");let l=Si(a.perInstance?.[0]?.output??""),o=l.split(`
|
|
123
|
-
`).filter(Boolean).slice(-r).map((u)=>{let f=/^(\d{4}-\d{2}-\d{2}T\S+)\s+(.*)$/.exec(u);return{timestamp:f?.[1],message:f?.[2]??u}});return{workloadId:t,provider:n.provider,lines:o,truncated:l.includes("[output truncated]")||o.length>=r}}}import{randomUUID as RD}from"node:crypto";class ms{records=new Map;maxBufferBytes;ttlMs;now;constructor(t={}){this.maxBufferBytes=Math.max(1024,t.maxBufferBytes??262144),this.ttlMs=Math.max(1000,t.ttlMs??900000),this.now=t.now??(()=>new Date)}create(t,e){this.sweep();let n=this.now().toISOString(),r={id:RD(),workloadId:e,kind:t,state:"open",chunks:[],cursor:0,droppedBytes:0,bufferedBytes:0,createdAt:n,updatedAt:n,abort:new AbortController,listeners:new Set};return this.records.set(r.id,r),this.snapshot(r,0)}signal(t){return this.records.get(t)?.abort.signal}append(t,e,n="stdout"){let r=this.records.get(t);if(!r||r.state!=="open"||!e)return r?this.snapshot(r,r.cursor):void 0;let i=Buffer.from(e),c=i.byteLength>this.maxBufferBytes?i.subarray(i.byteLength-this.maxBufferBytes).toString("utf8"):e,d={cursor:++r.cursor,stream:n,data:c,at:this.now().toISOString()};r.chunks.push(d),r.bufferedBytes+=Buffer.byteLength(c),r.updatedAt=d.at;while(r.bufferedBytes>this.maxBufferBytes&&r.chunks.length>1){let a=r.chunks.shift(),l=Buffer.byteLength(a.data);r.bufferedBytes-=l,r.droppedBytes+=l}return this.publish(r),this.snapshot(r,d.cursor-1)}read(t,e,n=0){let r=this.records.get(t);if(!r||r.workloadId!==e)return;return r.updatedAt=this.now().toISOString(),this.snapshot(r,Math.max(0,Math.floor(n)))}close(t,e="complete",n){let r=this.records.get(t);if(!r||r.state!=="open")return r?this.snapshot(r,r.cursor):void 0;if(r.state=e,r.error=n,r.updatedAt=this.now().toISOString(),e==="cancelled")r.abort.abort();return this.publish(r),this.snapshot(r,r.cursor)}cancel(t,e){let n=this.records.get(t);if(!n||n.workloadId!==e)return;return this.close(t,"cancelled")}subscribe(t,e,n){let r=this.records.get(t);if(!r||r.workloadId!==e)return;return r.listeners.add(n),()=>r.listeners.delete(n)}sweep(){let t=this.now().getTime()-this.ttlMs,e=0;for(let[n,r]of this.records){if(new Date(r.updatedAt).getTime()>t)continue;r.abort.abort(),this.records.delete(n),e++}return e}clear(){for(let t of this.records.values())t.abort.abort();this.records.clear()}snapshot(t,e){let n=t.chunks[0]?.cursor??t.cursor+1,r=e>0&&e<n-1;return{id:t.id,workloadId:t.workloadId,kind:t.kind,state:t.state,chunks:t.chunks.filter((i)=>r||i.cursor>e),cursor:t.cursor,reset:r,droppedBytes:t.droppedBytes,createdAt:t.createdAt,updatedAt:t.updatedAt,error:t.error}}publish(t){let e=this.snapshot(t,0);for(let n of t.listeners)n(e)}}import{createHash as ED}from"node:crypto";var nl={info:0,low:1,medium:2,high:3,critical:4},rl={record:0,warn:1,block:2},uf=new Set(["skipped","unavailable","unsupported","stale"]);function Tt(t){return typeof t==="string"?t:void 0}function qn(t,e){try{return JSON.parse(String(t))}catch{return e}}function Ze(t){return JSON.stringify(bt(t))}function ID(t){if(!t)return;return String(bt(t,2000))}function qs(t){return{id:String(t.id),organizationId:String(t.organization_id),projectId:Tt(t.project_id),environmentId:Tt(t.environment_id),resourceId:Tt(t.resource_id),releaseId:Tt(t.release_id),scannerId:String(t.scanner_id),scannerVersion:String(t.scanner_version),status:String(t.status),error:Tt(t.error),metadata:qn(t.metadata,{}),findingsCount:Number(t.findings_count),startedAt:String(t.started_at),completedAt:String(t.completed_at),durationMs:Number(t.duration_ms)}}function hf(t){return{id:String(t.id),fingerprint:String(t.fingerprint),organizationId:String(t.organization_id),projectId:Tt(t.project_id),environmentId:Tt(t.environment_id),resourceId:Tt(t.resource_id),releaseId:Tt(t.release_id),scanRunId:String(t.scan_run_id),scannerId:String(t.scanner_id),scannerVersion:String(t.scanner_version),ruleId:String(t.rule_id),severity:String(t.severity),title:String(t.title),description:String(t.description),evidence:qn(t.evidence,{}),remediation:Tt(t.remediation),subject:String(t.subject),status:String(t.status),ownerActorId:Tt(t.owner_actor_id),recurrenceCount:Number(t.recurrence_count),firstSeenAt:String(t.first_seen_at),lastSeenAt:String(t.last_seen_at),resolvedAt:Tt(t.resolved_at),updatedAt:String(t.updated_at)}}function tl(t){return{id:String(t.id),organizationId:String(t.organization_id),environmentId:Tt(t.environment_id),name:String(t.name),rules:qn(t.rules,[]),requiredScanners:qn(t.required_scanners,[]),scannerFailMode:String(t.scanner_fail_mode),enabled:Number(t.enabled)===1,version:Number(t.version),createdByActorId:Tt(t.created_by_actor_id),createdAt:String(t.created_at),updatedAt:String(t.updated_at)}}function Sf(t,e){let n=Tt(t.revoked_at),r=String(t.expires_at);return{id:String(t.id),findingId:String(t.finding_id),policyId:Tt(t.policy_id),reason:String(t.reason),referenceUrl:Tt(t.reference_url),createdByActorId:String(t.created_by_actor_id),expiresAt:r,revokedAt:n,state:n?"revoked":r<=e?"expired":"active",createdAt:String(t.created_at),updatedAt:String(t.updated_at)}}function el(t){return{id:String(t.id),organizationId:String(t.organization_id),projectId:String(t.project_id),environmentId:Tt(t.environment_id),releaseId:String(t.release_id),kind:String(t.kind),format:String(t.format),digest:String(t.digest),summary:qn(t.summary,{}),content:Tt(t.content),sensitive:Number(t.sensitive)===1,createdAt:String(t.created_at)}}function ff(t){return{id:String(t.id),organizationId:String(t.organization_id),projectId:String(t.project_id),environmentId:String(t.environment_id),operationId:Tt(t.operation_id),policyId:String(t.policy_id),policyVersion:Number(t.policy_version),outcome:String(t.outcome),scannerVersions:qn(t.scanner_versions,{}),findingIds:qn(t.finding_ids,[]),waiverIds:qn(t.waiver_ids,[]),explanation:String(t.explanation),createdAt:String(t.created_at)}}function wD(t,e){let n=[t.trim().toLowerCase(),e.ruleId.trim().toLowerCase(),e.organizationId,e.projectId??"",e.environmentId??"",e.resourceId??"",e.releaseId??"",e.subject.trim().toLowerCase()].join("\x00");return ED("sha256").update(n).digest("hex")}function _f(t){if(!t)return;let e=new URL(t);if(e.protocol!=="https:"&&e.protocol!=="http:")throw Error("Security references must use HTTP or HTTPS");return e.toString()}function Rf(t){if(!t.length)throw Error("A security policy needs at least one rule");return t.map((e)=>{if(!(e.minimumSeverity in nl))throw Error(`Unknown security severity: ${e.minimumSeverity}`);if(!(e.action in rl))throw Error(`Unknown security policy action: ${e.action}`);return{minimumSeverity:e.minimumSeverity,action:e.action,...e.scannerId?{scannerId:e.scannerId.trim()}:{}}})}class pi{controlPlane;nowFn;idFn;constructor(t,e={}){this.controlPlane=t;this.nowFn=e.now??(()=>new Date),this.idFn=e.id??(()=>crypto.randomUUID())}now(){return this.nowFn().toISOString()}run(t,e){this.controlPlane.database.run(t,e)}recordScan(t){if(!t.organizationId||!t.scannerId.trim()||!t.scannerVersion.trim())throw Error("Organization, scanner id, and scanner version are required");let e=t.completedAt??this.now(),n=t.startedAt??e,r=t.durationMs??Math.max(0,new Date(e).getTime()-new Date(n).getTime()),i=t.findings??[],c=this.idFn(),d=new Set,a=[];return this.controlPlane.transaction(()=>{this.run(`INSERT INTO security_scan_runs
|
|
124
|
-
(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)
|
|
125
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[c,t.organizationId,t.projectId??null,t.environmentId??null,t.resourceId??null,t.releaseId??null,t.scannerId.trim(),t.scannerVersion.trim(),t.status,ID(t.error)??null,Ze(t.metadata??{}),i.length,n,e,Math.max(0,Math.floor(r))]);for(let l of i){let o={...l,organizationId:t.organizationId,projectId:l.projectId??t.projectId,environmentId:l.environmentId??t.environmentId,resourceId:l.resourceId??t.resourceId,releaseId:l.releaseId??t.releaseId},u=o.fingerprint?.trim()||wD(t.scannerId,o);d.add(u);let f=this.controlPlane.database.query("SELECT * FROM security_findings WHERE fingerprint = ?").get(u),R=f?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(f.id),e):void 0;if(f){let E=String(f.status)==="resolved"?Number(f.recurrence_count)+1:Number(f.recurrence_count),y=R?"waived":String(f.status)==="acknowledged"?"acknowledged":"open";this.run(`UPDATE security_findings SET scan_run_id = ?, scanner_version = ?, severity = ?, title = ?, description = ?, evidence = ?, remediation = ?,
|
|
126
|
-
status = ?, recurrence_count = ?, last_seen_at = ?, resolved_at = NULL, updated_at = ? WHERE id = ?`,[c,t.scannerVersion,o.severity,o.title.trim(),o.description.trim(),Ze(o.evidence??{}),o.remediation?.trim()||null,y,E,e,e,String(f.id)]),a.push(this.getFinding(String(f.id)))}else{let E=this.idFn();this.run(`INSERT INTO security_findings
|
|
127
|
-
(id, fingerprint, organization_id, project_id, environment_id, resource_id, release_id, scan_run_id, scanner_id, scanner_version, rule_id,
|
|
128
|
-
severity, title, description, evidence, remediation, subject, status, first_seen_at, last_seen_at, updated_at)
|
|
129
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'open', ?, ?, ?)`,[E,u,o.organizationId,o.projectId??null,o.environmentId??null,o.resourceId??null,o.releaseId??null,c,t.scannerId,t.scannerVersion,o.ruleId.trim(),o.severity,o.title.trim(),o.description.trim(),Ze(o.evidence??{}),o.remediation?.trim()||null,o.subject.trim(),e,e,e]),a.push(this.getFinding(E))}}if(t.status==="passed"||t.status==="failed"){let l=this.controlPlane.database.query(`SELECT * FROM security_findings WHERE organization_id = ? AND scanner_id = ?
|
|
130
|
-
AND project_id IS ? AND environment_id IS ? AND resource_id IS ? AND release_id IS ? AND status != 'resolved'`).all(t.organizationId,t.scannerId,t.projectId??null,t.environmentId??null,t.resourceId??null,t.releaseId??null);for(let o of l){if(d.has(String(o.fingerprint)))continue;this.run("UPDATE security_findings SET status = 'resolved', resolved_at = ?, updated_at = ? WHERE id = ?",[e,e,String(o.id)]),this.controlPlane.appendEvent({organizationId:t.organizationId,projectId:t.projectId,resourceId:t.resourceId,type:"security.finding.resolved",payload:{findingId:String(o.id),scannerId:t.scannerId,reason:"not-observed"}})}}this.controlPlane.appendEvent({organizationId:t.organizationId,projectId:t.projectId,resourceId:t.resourceId,type:"security.scan.completed",level:t.status==="failed"||uf.has(t.status)?"warning":"info",payload:{scanRunId:c,scannerId:t.scannerId,scannerVersion:t.scannerVersion,status:t.status,findingsCount:i.length,durationMs:r}})}),{run:this.getScanRun(c),findings:a.map((l)=>this.getFinding(l.id))}}getScanRun(t){let e=this.controlPlane.database.query("SELECT * FROM security_scan_runs WHERE id = ?").get(t);return e?qs(e):void 0}listScanRuns(t){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(t.organizationId,t.projectId??null,t.environmentId??null,Math.min(500,Math.max(1,t.limit??100))).map(qs)}getFinding(t){let e=this.controlPlane.database.query("SELECT * FROM security_findings WHERE id = ?").get(t);return e?hf(e):void 0}listFindings(t){this.expireWaivers();let e=["organization_id = ?"],n=[t.organizationId];if(t.projectId)e.push("project_id = ?"),n.push(t.projectId);if(t.environmentId)e.push("environment_id = ?"),n.push(t.environmentId);if(t.status)e.push("status = ?"),n.push(t.status);if(t.severity)e.push("severity = ?"),n.push(t.severity);return n.push(Math.min(1000,Math.max(1,t.limit??250))),this.controlPlane.database.query(`SELECT * FROM security_findings WHERE ${e.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(...n).map(hf)}assignFinding(t,e,n){let r=this.getFinding(t);if(!r)throw Error("Security finding was not found");if(e&&!this.controlPlane.getActor(e))throw Error("Finding owner was not found");return this.run("UPDATE security_findings SET owner_actor_id = ?, updated_at = ? WHERE id = ?",[e??null,this.now(),t]),this.controlPlane.appendEvent({organizationId:r.organizationId,projectId:r.projectId,resourceId:r.resourceId,actorId:n,type:"security.finding.assigned",payload:{findingId:t,ownerActorId:e??null}}),this.getFinding(t)}acknowledgeFinding(t,e){let n=this.getFinding(t);if(!n)throw Error("Security finding was not found");if(n.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(),t]),this.controlPlane.appendEvent({organizationId:n.organizationId,projectId:n.projectId,resourceId:n.resourceId,actorId:e,type:"security.finding.acknowledged",payload:{findingId:t}}),this.getFinding(t)}addComment(t){let e=this.getFinding(t.findingId);if(!e)throw Error("Security finding was not found");let n=t.body.trim();if(n.length<2||n.length>4000)throw Error("Finding comments must contain 2-4,000 characters");let r=_f(t.referenceUrl),i=this.idFn(),c=this.now();return this.run("INSERT INTO security_finding_comments (id, finding_id, actor_id, body, reference_url, created_at) VALUES (?, ?, ?, ?, ?, ?)",[i,t.findingId,t.actorId,n,r??null,c]),this.controlPlane.appendEvent({organizationId:e.organizationId,projectId:e.projectId,resourceId:e.resourceId,actorId:t.actorId,type:"security.finding.commented",payload:{findingId:t.findingId,commentId:i,referenceUrl:r??null}}),{id:i,findingId:t.findingId,actorId:t.actorId,body:n,referenceUrl:r,createdAt:c}}listComments(t){return this.controlPlane.database.query("SELECT * FROM security_finding_comments WHERE finding_id = ? ORDER BY created_at, id").all(t).map((e)=>({id:String(e.id),findingId:String(e.finding_id),actorId:String(e.actor_id),body:String(e.body),referenceUrl:Tt(e.reference_url),createdAt:String(e.created_at)}))}createWaiver(t){let e=this.getFinding(t.findingId);if(!e)throw Error("Security finding was not found");let n=t.reason.trim();if(n.length<8||n.length>1000)throw Error("A waiver reason must contain 8-1,000 characters");let r=this.now(),i=new Date(t.expiresAt);if(!Number.isFinite(i.getTime())||i.toISOString()<=r)throw Error("A waiver must have a future expiry");if(i.getTime()-new Date(r).getTime()>31536000000)throw Error("A waiver cannot last longer than one year");let c=t.policyId?this.getPolicy(t.policyId):void 0;if(t.policyId&&(!c||c.organizationId!==e.organizationId))throw Error("Waiver policy does not match the finding organization");let d=this.idFn(),a=_f(t.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)
|
|
131
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[d,e.id,t.policyId??null,n,a??null,t.actorId,i.toISOString(),r,r]),this.run("UPDATE security_findings SET status = 'waived', updated_at = ? WHERE id = ?",[r,e.id]),this.controlPlane.appendEvent({organizationId:e.organizationId,projectId:e.projectId,resourceId:e.resourceId,actorId:t.actorId,type:"security.waiver.created",level:"warning",payload:{waiverId:d,findingId:e.id,policyId:t.policyId??null,reason:n,expiresAt:i.toISOString(),referenceUrl:a??null}})}),this.getWaiver(d)}revokeWaiver(t,e){let n=this.getWaiver(t);if(!n)throw Error("Security waiver was not found");if(n.revokedAt)return n;let r=this.getFinding(n.findingId),i=this.now();return this.controlPlane.transaction(()=>{this.run("UPDATE security_waivers SET revoked_at = ?, updated_at = ? WHERE id = ?",[i,i,t]),this.run("UPDATE security_findings SET status = 'open', updated_at = ? WHERE id = ? AND status = 'waived'",[i,n.findingId]),this.controlPlane.appendEvent({organizationId:r.organizationId,projectId:r.projectId,resourceId:r.resourceId,actorId:e,type:"security.waiver.revoked",level:"warning",payload:{waiverId:t,findingId:n.findingId}})}),this.getWaiver(t)}getWaiver(t){let e=this.controlPlane.database.query("SELECT * FROM security_waivers WHERE id = ?").get(t);return e?Sf(e,this.now()):void 0}listWaivers(t){return(t?this.controlPlane.database.query("SELECT * FROM security_waivers WHERE finding_id = ? ORDER BY created_at DESC").all(t):this.controlPlane.database.query("SELECT * FROM security_waivers ORDER BY created_at DESC").all()).map((n)=>Sf(n,this.now()))}expireWaivers(){let t=this.now(),e=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
|
|
132
|
-
WHERE w.revoked_at IS NULL AND w.expires_at <= ? AND f.status = 'waived'`).all(t);for(let n of e)this.run("UPDATE security_findings SET status = 'open', updated_at = ? WHERE id = ?",[t,String(n.id)]),this.controlPlane.appendEvent({organizationId:String(n.organization_id),projectId:Tt(n.project_id),resourceId:Tt(n.resource_id),type:"security.waiver.expired",level:"warning",payload:{waiverId:String(n.waiver_id),findingId:String(n.id)}});return e.length}createPolicy(t){let e=t.name.trim();if(!e)throw Error("Security policy name is required");let n=Rf(t.rules),r=this.idFn(),i=this.now(),c=[...new Set((t.requiredScanners??[]).map((d)=>d.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)
|
|
133
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[r,t.organizationId,t.environmentId??null,e,Ze(n),Ze(c),t.scannerFailMode,t.actorId??null,i,i]),this.controlPlane.appendEvent({organizationId:t.organizationId,actorId:t.actorId,type:"security.policy.created",payload:{policyId:r,environmentId:t.environmentId??null,scannerFailMode:t.scannerFailMode,requiredScanners:c,rules:bt(n)}}),this.getPolicy(r)}updatePolicy(t,e,n){let r=this.getPolicy(t);if(!r||r.version!==e)throw Error(`Security policy ${t} changed since version ${e}`);let i=n.rules?Rf(n.rules):r.rules,c=n.requiredScanners?[...new Set(n.requiredScanners.map((l)=>l.trim()).filter(Boolean))].sort():r.requiredScanners,d=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 = ?",[n.name?.trim()||r.name,Ze(i),Ze(c),n.scannerFailMode??r.scannerFailMode,n.enabled??r.enabled?1:0,d,t,e]).changes!==1)throw Error(`Security policy ${t} changed since version ${e}`);return this.controlPlane.appendEvent({organizationId:r.organizationId,actorId:n.actorId,type:"security.policy.updated",payload:{policyId:t,fromVersion:e,toVersion:e+1}}),this.getPolicy(t)}getPolicy(t){let e=this.controlPlane.database.query("SELECT * FROM security_policies WHERE id = ?").get(t);return e?tl(e):void 0}listPolicies(t){return this.controlPlane.database.query("SELECT * FROM security_policies WHERE organization_id = ? ORDER BY environment_id, name").all(t).map(tl)}evaluateGate(t){this.expireWaivers();let e=t.policyId?this.getPolicy(t.policyId):this.controlPlane.database.query(`SELECT * FROM security_policies WHERE organization_id = ? AND enabled = 1 AND (environment_id = ? OR environment_id IS NULL)
|
|
134
|
-
ORDER BY CASE WHEN environment_id = ? THEN 0 ELSE 1 END, updated_at DESC LIMIT 1`).get(t.organizationId,t.environmentId,t.environmentId),n=e&&"rules"in e&&Array.isArray(e.rules)?e:e?tl(e):void 0;if(!n||!n.enabled)throw Error("No enabled security policy applies to this environment");let r=this.listFindings({organizationId:t.organizationId,projectId:t.projectId,environmentId:t.environmentId,limit:1000}).filter((m)=>m.status!=="resolved"),i=new Map;for(let m of r){let Ut=this.listWaivers(m.id).find((st)=>st.state==="active"&&(!st.policyId||st.policyId===n.id));if(Ut)i.set(m.id,Ut)}let c=(m)=>n.rules.filter((Ut)=>(!Ut.scannerId||Ut.scannerId===m.scannerId)&&nl[m.severity]>=nl[Ut.minimumSeverity]).reduce((Ut,st)=>rl[st.action]>rl[Ut]?st.action:Ut,"record"),d=r.filter((m)=>!i.has(m.id)&&c(m)==="block"),a=r.filter((m)=>!i.has(m.id)&&c(m)==="warn"),l=this.controlPlane.database.query(`SELECT run.* FROM security_scan_runs run
|
|
135
|
-
WHERE run.organization_id = ? AND run.project_id = ? AND run.environment_id = ?
|
|
136
|
-
AND run.id = (SELECT candidate.id FROM security_scan_runs candidate
|
|
137
|
-
WHERE candidate.organization_id = run.organization_id AND candidate.project_id = run.project_id
|
|
138
|
-
AND candidate.environment_id = run.environment_id AND candidate.scanner_id = run.scanner_id
|
|
139
|
-
ORDER BY candidate.completed_at DESC, candidate.rowid DESC LIMIT 1)`).all(t.organizationId,t.projectId,t.environmentId),o=t.staleAfterMs??86400000,u=this.nowFn().getTime(),f=l.map(qs).map((m)=>u-new Date(m.completedAt).getTime()>o?{...m,status:"stale"}:m),R=new Set(f.map((m)=>m.scannerId)),E=n.requiredScanners.filter((m)=>!R.has(m)).map((m)=>({id:`missing:${m}`,organizationId:t.organizationId,projectId:t.projectId,environmentId:t.environmentId,scannerId:m,scannerVersion:"unavailable",status:"unavailable",metadata:{},findingsCount:0,startedAt:this.now(),completedAt:this.now(),durationMs:0})),y=[...f,...E],$=y.filter((m)=>n.requiredScanners.includes(m.scannerId)&&uf.has(m.status)),C=Object.fromEntries(y.map((m)=>[m.scannerId,m.scannerVersion])),J=n.scannerFailMode==="closed"&&$.length>0,H=d.length||J?"block":a.length||$.length?"warn":"allow",O=[];if(d.length)O.push(`${d.length} finding${d.length===1?"":"s"} blocked by policy`);if(a.length)O.push(`${a.length} warning${a.length===1?"":"s"} require review`);if($.length)O.push(`${$.length} scanner${$.length===1?"":"s"} ${n.scannerFailMode==="closed"?"failed closed":"failed open"}`);if(i.size)O.push(`${i.size} active time-limited waiver${i.size===1?"":"s"}`);if(!O.length)O.push("All recorded checks satisfy policy");let Y=this.idFn(),dt=this.now();return this.run(`INSERT INTO security_deploy_decisions
|
|
140
|
-
(id, organization_id, project_id, environment_id, operation_id, policy_id, policy_version, outcome, scanner_versions, finding_ids, waiver_ids, explanation, created_at)
|
|
141
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[Y,t.organizationId,t.projectId,t.environmentId,t.operationId??null,n.id,n.version,H,Ze(C),Ze([...d,...a].map((m)=>m.id)),Ze([...i.values()].map((m)=>m.id)),O.join("; "),dt]),this.controlPlane.appendEvent({organizationId:t.organizationId,projectId:t.projectId,operationId:t.operationId,type:"security.deploy.decision",level:H==="block"?"error":H==="warn"?"warning":"info",payload:{decisionId:Y,outcome:H,policyId:n.id,policyVersion:n.version,scannerVersions:C,blockerIds:d.map((m)=>m.id),waiverIds:[...i.values()].map((m)=>m.id),explanation:O.join("; ")}}),this.getDecision(Y)}getDecision(t){let e=this.controlPlane.database.query("SELECT * FROM security_deploy_decisions WHERE id = ?").get(t);return e?ff(e):void 0}listDecisions(t,e=100){return this.controlPlane.database.query("SELECT * FROM security_deploy_decisions WHERE environment_id = ? ORDER BY created_at DESC LIMIT ?").all(t,Math.min(500,Math.max(1,e))).map(ff)}addReleaseArtifact(t){let e=this.controlPlane.database.query("SELECT * FROM release_security_artifacts WHERE release_id = ? AND kind = ? AND digest = ?").get(t.releaseId,t.kind,t.digest);if(e)return el(e);let n=this.idFn(),r=this.now();return this.run(`INSERT INTO release_security_artifacts
|
|
142
|
-
(id, organization_id, project_id, environment_id, release_id, kind, format, digest, summary, content, sensitive, created_at)
|
|
143
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n,t.organizationId,t.projectId,t.environmentId??null,t.releaseId,t.kind,t.format,t.digest,Ze(t.summary),t.content??null,t.sensitive?1:0,r]),this.controlPlane.appendEvent({organizationId:t.organizationId,projectId:t.projectId,type:"security.release_artifact.created",payload:{artifactId:n,releaseId:t.releaseId,kind:t.kind,format:t.format,digest:t.digest,sensitive:t.sensitive}}),el(this.controlPlane.database.query("SELECT * FROM release_security_artifacts WHERE id = ?").get(n))}listReleaseArtifacts(t,e=!1){return this.controlPlane.database.query("SELECT * FROM release_security_artifacts WHERE release_id = ? ORDER BY created_at, kind").all(t).map(el).map((n)=>n.sensitive&&!e?{...n,content:void 0}:n)}summary(t,e,n){let r=this.listFindings({organizationId:t,projectId:e,environmentId:n,limit:1000}),i=this.listScanRuns({organizationId:t,projectId:e,environmentId:n,limit:1000}),c={info:0,low:0,medium:0,high:0,critical:0};for(let a of r)if(a.status==="open"||a.status==="acknowledged")c[a.severity]++;let d={passed:0,failed:0,skipped:0,unavailable:0,unsupported:0,stale:0};for(let a of i)d[a.status]++;return{open:c,waived:r.filter((a)=>a.status==="waived").length,resolved:r.filter((a)=>a.status==="resolved").length,checks:d,lastScannedAt:i[0]?.completedAt}}exportPosture(t){let e=this.controlPlane.listProjects().filter((n)=>n.organizationId===t);return bt({format:"ts-cloud-security-posture",version:1,exportedAt:this.now(),organizationId:t,policies:this.listPolicies(t),findings:this.listFindings({organizationId:t,limit:1000}),waivers:this.listWaivers().filter((n)=>this.getFinding(n.findingId)?.organizationId===t),scans:e.flatMap((n)=>this.listScanRuns({organizationId:t,projectId:n.id,limit:1000})),decisions:e.flatMap((n)=>this.controlPlane.listEnvironments(n.id).flatMap((r)=>this.listDecisions(r.id,1000)))})}}import{existsSync as AD,readdirSync as DD,readFileSync as yD,statSync as PD}from"node:fs";import{extname as $D,join as vD,relative as kD}from"node:path";var Ef=[{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"}],CD=[".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"],JD=["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 Md{patterns;excludeDirs;excludeFiles;maxFileSize;constructor(t){this.patterns=[...Ef,...t?.customPatterns||[]],this.excludeDirs=[...OD,...t?.excludeDirs||[]],this.excludeFiles=[...JD,...t?.excludeFiles||[]],this.maxFileSize=t?.maxFileSize||1048576}async scan(t){let e=Date.now(),n=[],r=0,{directory:i,exclude:c=[],include:d,skipPatterns:a=[]}=t,l=t.failOnSeverity||"critical";if(!AD(i))throw Error(`Directory not found: ${i}`);let o=this.getFilesToScan(i,[...this.excludeDirs,...c],d);for(let y of o){let $=kD(i,y);if(this.shouldExcludeFile($))continue;try{if(PD(y).size>this.maxFileSize)continue;let J=yD(y,"utf-8"),H=this.scanContent(J,$,a);n.push(...H),r++}catch{continue}}let u={critical:n.filter((y)=>y.pattern.severity==="critical").length,high:n.filter((y)=>y.pattern.severity==="high").length,medium:n.filter((y)=>y.pattern.severity==="medium").length,low:n.filter((y)=>y.pattern.severity==="low").length},f=["low","medium","high","critical"],R=f.indexOf(l),E=!0;for(let y=R;y<f.length;y++)if(u[f[y]]>0){E=!1;break}return{passed:E,findings:n,scannedFiles:r,duration:Date.now()-e,summary:u}}scanContent(t,e,n){let r=[],i=t.split(`
|
|
144
|
-
`);for(let c of this.patterns){if(n.includes(c.name))continue;c.pattern.lastIndex=0;let d;while((d=c.pattern.exec(t))!==null){let a=t.substring(0,d.index),l=a.split(`
|
|
145
|
-
`).length,o=a.lastIndexOf(`
|
|
146
|
-
`),u=d.index-o,f=i[l-1]||"";if(this.isLikelyPlaceholder(d[0],f))continue;let R=d[1]||d[0];if(c.name==="AWS Secret Key (Generic)"&&/^[a-f0-9]{40}$/i.test(R))continue;if(c.name==="AWS Secret Key (Generic)"&&!this.hasSecretCharacterDiversity(R))continue;if(c.name==="AWS Secret Key (Generic)"&&/^(?:Actions|Commands|Controllers|Handlers|Jobs|Listeners|Middleware|Models|Resources|Services)\//.test(R))continue;if(this.isLowEntropy(R))continue;r.push({file:e,line:l,column:u,match:this.maskSecret(d[0]),pattern:c,context:this.maskSecret(f.trim())})}}return r}isLikelyPlaceholder(t,e){let n=["example","placeholder","your_","YOUR_","xxx","XXX","***","test","TEST","dummy","DUMMY","fake","FAKE","sample","SAMPLE","<your","${","{{","process.env","import.meta.env","CHANGEME","TODO","FIXME"],r=t.toLowerCase(),i=e.toLowerCase();for(let d of n)if(r.includes(d.toLowerCase())||i.includes(d.toLowerCase()))return!0;let c=e.trim();if(c.startsWith("//")||c.startsWith("#")||c.startsWith("*")||c.startsWith("/*")){if(i.includes("example")||i.includes("format:")||i.includes("e.g."))return!0}return!1}isLowEntropy(t){if(t.length<8)return!1;if(new Set(t).size<8)return!0;if(/(.)\1{3,}/.test(t))return!0;return!1}hasSecretCharacterDiversity(t){let e=/[\d+=]/.test(t),n=[/[a-z]/.test(t),/[A-Z]/.test(t),/\d/.test(t),/[/+=]/.test(t)];return e&&n.filter(Boolean).length>=3}maskSecret(t){if(t.length<=8)return"*".repeat(t.length);let e=Math.min(4,Math.floor(t.length*0.2));return t.substring(0,e)+"*".repeat(t.length-e*2)+t.substring(t.length-e)}getFilesToScan(t,e,n){let r=[],i=n||CD,c=(d)=>{let a=DD(d,{withFileTypes:!0});for(let l of a){let o=vD(d,l.name);if(l.isDirectory()){if(!e.includes(l.name))c(o)}else if(l.isFile()){let u=$D(l.name).toLowerCase();if(i.includes(u)||l.name.startsWith(".env")||l.name.endsWith(".config"))r.push(o)}}};return c(t),r}shouldExcludeFile(t){let e=t.split("/").pop()||"";for(let n of this.excludeFiles)if(n.startsWith("*")){let r=n.substring(1);if(e.endsWith(r))return!0}else if(n.endsWith("*")){let r=n.substring(0,n.length-1);if(e.startsWith(r))return!0}else if(e===n)return!0;return!1}addPattern(t){this.patterns.push(t)}getPatterns(){return[...this.patterns]}}function BD(t,e){return{status:"unavailable",findings:[],error:`${t.id} exceeded its ${e}ms timeout`,metadata:{timeoutMs:e}}}class Cr{posture;defaultTimeoutMs;nowFn;constructor(t,e={}){this.posture=t;this.defaultTimeoutMs=e.defaultTimeoutMs??60000,this.nowFn=e.now??(()=>new Date)}async run(t,e){let n=this.nowFn(),r=Math.max(100,t.timeoutMs??this.defaultTimeoutMs),i=new AbortController,c,d=new Promise((u)=>{c=setTimeout(()=>{i.abort(),u(BD(t,r))},r)}),a;try{a=await Promise.race([t.scan({...e,signal:i.signal}),d])}catch(u){a={status:"unavailable",findings:[],error:u instanceof Error?u.message:String(u)}}finally{if(c)clearTimeout(c)}let l=this.nowFn(),o={...e,scannerId:t.id,scannerVersion:t.version,status:a.status,findings:a.findings,metadata:a.metadata,error:a.error,startedAt:n.toISOString(),completedAt:l.toISOString(),durationMs:Math.max(0,l.getTime()-n.getTime())};return this.posture.recordScan(o)}async runAll(t,e){return Promise.all(t.map((n)=>this.run(n,e)))}}class mi{scanner;id="source-secrets";version="1.0.0";timeoutMs=30000;constructor(t=new Md){this.scanner=t}async scan(t){if(!t.artifactRoot)return{status:"skipped",findings:[],error:"No artifact root was supplied"};let e=await this.scanner.scan({directory:t.artifactRoot,failOnSeverity:"critical"});return{status:e.passed?"passed":"failed",findings:e.findings.map((n)=>({...t,ruleId:n.pattern.name.toLowerCase().replace(/[^a-z0-9]+/g,"-"),severity:n.pattern.severity,title:n.pattern.name,description:n.pattern.description,subject:`${n.file}:${n.line}`,evidence:{file:n.file,line:n.line,column:n.column,match:n.match,context:n.context},remediation:"Remove the credential, rotate it at its issuer, and use a managed secret or environment reference."})),metadata:{scannedFiles:e.scannedFiles,summary:e.summary}}}}function zD(t){let e=t?.toLowerCase();return e==="critical"||e==="high"||e==="medium"||e==="low"?e:"info"}class il{id="trivy-image";version;timeoutMs;constructor(t={}){this.version=t.version??"local",this.timeoutMs=t.timeoutMs??120000,this.executable=t.executable??"trivy"}executable;async scan(t){if(!t.imageRef)return{status:"skipped",findings:[],error:"No image reference was supplied"};let e;try{e=Bun.spawn([this.executable,"image","--format","json","--quiet","--scanners","vuln",t.imageRef],{stdout:"pipe",stderr:"pipe",env:{PATH:process.env.PATH??"/usr/local/bin:/usr/bin:/bin",HOME:"/nonexistent",TRIVY_NO_PROGRESS:"true"}})}catch(l){return{status:"unsupported",findings:[],error:l instanceof Error?l.message:String(l)}}let n=()=>e.kill();t.signal.addEventListener("abort",n,{once:!0});let[r,i,c]=await Promise.all([e.exited,new Response(e.stdout).text(),new Response(e.stderr).text()]);if(t.signal.removeEventListener("abort",n),r!==0)return{status:/not found|enoent/i.test(c)?"unsupported":"unavailable",findings:[],error:c.slice(0,2000)||`Trivy exited with ${r}`};let d=JSON.parse(i),a=[];for(let l of d.Results??[])for(let o of l.Vulnerabilities??[]){let u=o.VulnerabilityID??"unknown-vulnerability";a.push({...t,ruleId:u,severity:zD(o.Severity),title:o.Title||u,description:o.Description||`${u} affects ${o.PkgName??"an image package"}.`,subject:`${t.imageRef}:${o.PkgName??"unknown"}:${o.InstalledVersion??"unknown"}`,evidence:{image:t.imageRef,target:l.Target??"",cve:u,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:a.length?"failed":"passed",findings:a,metadata:{imageRef:t.imageRef,vulnerabilityCount:a.length,localOnly:!0}}}}import{createHash as TD,createVerify as ib}from"node:crypto";import{existsSync as bD,readFileSync as WD}from"node:fs";import{basename as UD,join as jD,resolve as If}from"node:path";function qi(t){return TD("sha256").update(t).digest("hex")}function HD(t){let e=[["dependencies","required"],["optionalDependencies","optional"],["devDependencies","excluded"],["peerDependencies","required"]],n=new Map;for(let[r,i]of e){let c=t[r];if(!c||typeof c!=="object"||Array.isArray(c))continue;for(let[d,a]of Object.entries(c)){let l=String(a).replace(/^[~^]/,""),o=`${d}@${l}`;if(!n.has(o))n.set(o,{type:"library",name:d,version:l,purl:`pkg:npm/${encodeURIComponent(d)}@${encodeURIComponent(l)}`,scope:i})}}return[...n.values()].sort((r,i)=>`${r.name}@${r.version}`.localeCompare(`${i.name}@${i.version}`))}function wf(t,e={}){let n=jD(If(t),"package.json");if(!bD(n))throw Error(`Cannot generate an SBOM: ${n} was not found`);let r=WD(n,"utf8"),i=JSON.parse(r),c=String(i.name??UD(If(t))),d=String(i.version??"0.0.0"),a=qi(r);return{bomFormat:"CycloneDX",specVersion:"1.5",serialNumber:e.serial??`urn:uuid:${crypto.randomUUID()}`,version:1,metadata:{timestamp:(e.now??new Date).toISOString(),component:{type:"application",name:c,version:d,purl:`pkg:npm/${encodeURIComponent(c)}@${encodeURIComponent(d)}`,hashes:[{alg:"SHA-256",content:a}]},tools:[{vendor:"ts-cloud",name:"security-posture",version:"1.0.0"}]},components:HD(i)}}async function Af(t,e={}){let n=Bun.spawn([e.executable??"syft",t,"-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"}}),r=()=>n.kill();e.signal?.addEventListener("abort",r,{once:!0});let[i,c,d]=await Promise.all([n.exited,new Response(n.stdout).text(),new Response(n.stderr).text()]);if(e.signal?.removeEventListener("abort",r),i!==0)throw Error(d.slice(0,2000)||`Syft exited with ${i}`);return JSON.parse(c)}function cl(t,e,n){let r=JSON.stringify(n);return t.addReleaseArtifact({...e,kind:"sbom",format:`cyclonedx-${n.specVersion}+json`,digest:`sha256:${qi(r)}`,summary:{component:n.metadata.component.name,version:n.metadata.component.version,components:n.components.length},content:r,sensitive:!0})}function Df(t,e,n){let r={total:n.length,critical:0,high:0,medium:0,low:0,info:0,fixable:0};for(let c of n){r[c.severity]++;let d=c.evidence;if(typeof d.fixedVersion==="string"&&d.fixedVersion)r.fixable++}let i=JSON.stringify({releaseId:e.releaseId,generatedAt:new Date().toISOString(),findings:n.map((c)=>({id:c.id,ruleId:c.ruleId,severity:c.severity,subject:c.subject,remediation:c.remediation}))});return t.addReleaseArtifact({...e,kind:"vulnerability_summary",format:"ts-cloud-vulnerability-summary+json",digest:`sha256:${qi(i)}`,summary:r,content:i,sensitive:!0})}function yf(t){if(!t.artifact&&!t.artifactSha256)throw Error("Release provenance requires artifact content or a SHA-256 digest");return{_type:"https://in-toto.io/Statement/v1",subject:[{name:t.artifactName,digest:{sha256:t.artifactSha256?.replace(/^sha256:/,"")??qi(t.artifact)}}],predicateType:"https://slsa.dev/provenance/v1",predicate:{buildDefinition:{buildType:"https://ts-cloud.dev/build/v1",externalParameters:t.externalParameters??{},internalParameters:{},resolvedDependencies:t.resolvedDependencies??[]},runDetails:{builder:{id:"https://ts-cloud.dev/builders/local/v1"},metadata:{invocationId:t.invocationId,startedOn:t.startedAt,finishedOn:t.completedAt}}}}}function Pf(t,e,n){let r=JSON.stringify(n);return t.addReleaseArtifact({...e,kind:"provenance",format:"in-toto+slsa-v1+json",digest:`sha256:${qi(r)}`,summary:{subjects:n.subject.length,builder:n.predicate.runDetails.builder.id,buildType:n.predicate.buildDefinition.buildType},content:r,sensitive:!0})}function Ye(t,e){let n=t.environments.get(e);if(!n)throw Error(`Security scope for environment '${e}' was not found`);return{organizationId:t.organization.id,projectId:t.project.id,environmentId:n.id}}function $f(t,e){let n=new pi(t.store),r=n.listPolicies(t.organization.id);for(let[i,c]of t.environments){if(r.some((a)=>a.environmentId===c.id))continue;let d=i==="production"||c.kind==="production";r.push(n.createPolicy({organizationId:t.organization.id,environmentId:c.id,name:d?"Production baseline":"Environment baseline",scannerFailMode:d?"closed":"open",requiredScanners:["source-secrets"],rules:d?[{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:e}))}return r}function sb(t,e,n,r={}){let i=n.findings.map((c)=>({...e,ruleId:c.pattern.name.toLowerCase().replace(/[^a-z0-9]+/g,"-"),severity:c.pattern.severity,title:c.pattern.name,description:c.pattern.description,subject:`${c.file}:${c.line}`,evidence:{file:c.file,line:c.line,column:c.column,match:c.match,context:c.context},remediation:"Remove and rotate the credential, then reference it through a managed secret or environment variable."}));return t.recordScan({...e,scannerId:"source-secrets",scannerVersion:r.scannerVersion??"1.0.0",status:r.skipped?"skipped":n.passed?"passed":"failed",findings:r.skipped?[]:i,metadata:{scannedFiles:n.scannedFiles,durationMs:n.duration,summary:n.summary},durationMs:n.duration,error:r.skipped?"The operator explicitly skipped source-secret scanning.":void 0})}function lb(t,e,n="The operator explicitly skipped source-secret scanning."){return t.recordScan({...e,scannerId:"source-secrets",scannerVersion:"1.0.0",status:"skipped",findings:[],error:n})}function LD(t,e){let n=[],r=e.security;if(r?.firewall&&!["active","configured","ok"].includes(String(r.firewall.status)))n.push({...t,ruleId:"host-firewall-disabled",severity:"high",title:"Host firewall is not active",description:String(r.firewall.summary??"The host firewall did not report an active configuration."),subject:"host:firewall",evidence:{status:String(r.firewall.status??"unknown"),rules:Array.isArray(r.firewall.rules)?r.firewall.rules.length:0},remediation:"Apply the declarative firewall policy and confirm only required listeners are public."});for(let i of r?.ports??[]){let c=String(i.listen??""),d=Number(c.match(/:(\d+)$/)?.[1]);if(i.exposure==="public"&&Number.isFinite(d)&&![22,80,443].includes(d))n.push({...t,ruleId:"unexpected-public-listener",severity:"medium",title:`Unexpected public listener on port ${d}`,description:`${String(i.processName??"A process")} is listening publicly outside the standard SSH/HTTP/HTTPS ports.`,subject:`host:port:${d}`,evidence:{protocol:String(i.proto??""),listen:c,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 r?.tlsCertificates??[]){let c=Number(i.daysRemaining);if(Number.isFinite(c)&&c<30)n.push({...t,ruleId:"tls-certificate-expiry",severity:c<14?"high":"medium",title:`TLS certificate expires in ${c} days`,description:`${String(i.domain??"A configured domain")} needs renewal.`,subject:`tls:${String(i.domain??"unknown")}`,evidence:{domain:String(i.domain??""),daysRemaining:c,expires:String(i.expires??"")},remediation:"Renew the certificate and verify automatic renewal can complete before expiry."})}for(let i of e.diagnostics??[]){if(i.status==="pass"||i.status==="ok")continue;n.push({...t,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 n}function Qd(t,e,n){let r=!!n.security||Array.isArray(n.diagnostics),i=r?LD(e,n):[];return t.recordScan({...e,scannerId:"host-posture",scannerVersion:"1.0.0",status:!r?"unavailable":i.length?"failed":"passed",findings:i,metadata:{source:"dashboard-live-probe",checks:Array.isArray(n.diagnostics)?n.diagnostics.length:0},error:r?void 0:"Live host posture data was unavailable; source and provider checks remain usable."})}function Gd(t,e){let n=t.evaluateGate({...e.scope,operationId:e.operationId}),r=t.listFindings({...e.scope,limit:1000}).filter((i)=>i.status!=="resolved");return{decision:n,summary:{desiredConfigHash:e.desiredConfigHash??null,securityImpact:{critical:r.filter((i)=>i.severity==="critical").length,high:r.filter((i)=>i.severity==="high").length,waived:r.filter((i)=>i.status==="waived").length,assigned:r.filter((i)=>!!i.ownerActorId).length},blockingFindingIds:n.findingIds,policy:{id:n.policyId,version:n.policyVersion},scannerVersions:n.scannerVersions}}}async function Sb(t,e){let n=e.scanner??new il({timeoutMs:e.scannerTimeoutMs}),i=await new Cr(t,{defaultTimeoutMs:e.scannerTimeoutMs??120000}).run(n,{...e.scope,releaseId:e.releaseId,imageRef:e.imageRef}),c={...e.scope,releaseId:e.releaseId};Df(t,c,i.findings);let d=e.generateImageSbom??Af,a=new AbortController,l=Math.max(100,e.sbomTimeoutMs??120000),o,u=new Promise((E,y)=>{o=setTimeout(()=>{a.abort(),y(Error(`syft-sbom exceeded its ${l}ms timeout`))},l)}),f="unavailable";try{let E=await Promise.race([d(e.imageRef,{signal:a.signal}),u]);cl(t,c,E),t.recordScan({...e.scope,releaseId:e.releaseId,scannerId:"syft-sbom",scannerVersion:"local",status:"passed",metadata:{imageRef:e.imageRef,format:`cyclonedx-${E.specVersion}+json`,components:E.components.length,localOnly:!0}}),f="image"}catch(E){let y=E instanceof Error?E.message:String(E);try{let $=wf(e.artifactRoot);cl(t,c,$),t.recordScan({...e.scope,releaseId:e.releaseId,scannerId:"syft-sbom",scannerVersion:"local",status:"unsupported",error:`Image inventory was unavailable; attached a package-manifest SBOM instead. ${y}`,metadata:{imageRef:e.imageRef,fallback:"package-manifest",components:$.components.length,localOnly:!0}}),f="manifest"}catch($){t.recordScan({...e.scope,releaseId:e.releaseId,scannerId:"syft-sbom",scannerVersion:"local",status:"unavailable",error:`Image and manifest SBOM generation were unavailable. ${y}; ${$ instanceof Error?$.message:String($)}`,metadata:{imageRef:e.imageRef,localOnly:!0}})}}finally{if(o)clearTimeout(o)}let R=yf({artifactName:e.imageRef,artifact:e.imageSha256?void 0:e.imageRef,artifactSha256:e.imageSha256,invocationId:e.invocationId,startedAt:e.startedAt,completedAt:e.completedAt??new Date().toISOString(),externalParameters:e.externalParameters??{imageRef:e.imageRef}});return Pf(t,c,R),{scan:i,sbomSource:f}}import{randomBytes as vf,scryptSync as kf,timingSafeEqual as FD}from"node:crypto";function sl(t,e){if(t.role==="admin")return[...e];return e.filter((n)=>!!t.sites?.[n])}var dl=32768,ol=8,al=1,VD=32,ND=16;function tr(t){let e=vf(ND),n=kf(t,e,VD,{N:dl,r:ol,p:al,maxmem:268435456});return`scrypt$${dl}$${ol}$${al}$${e.toString("base64url")}$${n.toString("base64url")}`}function Xe(t,e){try{let n=e.split("$");if(n.length!==6||n[0]!=="scrypt")return!1;let[,r,i,c,d,a]=n,l=Number(r),o=Number(i),u=Number(c);if(!Number.isFinite(l)||!Number.isFinite(o)||!Number.isFinite(u))return!1;let f=Buffer.from(d,"base64url"),R=Buffer.from(a,"base64url");if(f.length===0||R.length===0)return!1;let E=kf(t,f,R.length,{N:l,r:o,p:u,maxmem:268435456});return FD(E,R)}catch{return!1}}function Cf(t){let[e,n,r,i]=t.split("$");return e!=="scrypt"||Number(n)!==dl||Number(r)!==ol||Number(i)!==al}function ll(){return vf(18).toString("base64url")}import{createHash as xD}from"node:crypto";function MD(t){return xD("sha256").update(Or(t)).digest("hex")}function Or(t){if(Array.isArray(t))return`[${t.map((e)=>Or(e)).join(",")}]`;if(t&&typeof t==="object")return`{${Object.entries(t).filter(([,e])=>e!==void 0&&typeof e!=="function").sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>`${JSON.stringify(e)}:${Or(n)}`).join(",")}}`;return JSON.stringify(t)??"null"}function Gt(t,e){let n=`dashboard:${e.username.toLowerCase()}`;return t.getActorByExternalId("user",n)??t.createActor({kind:"user",externalId:n,displayName:e.name??e.username,metadata:{source:"dashboard",role:e.role}})}function zf(t,e){let n=new Bf({cwd:t}),r=MD(e),i=n.getProjectBySlug(e.project.slug),c=e.project.slug.length>=3?e.project.slug:`${e.project.slug}-org`,d=(i?.organizationId?n.getOrganization(i.organizationId):void 0)??n.getOrganizationBySlug(c)??n.createOrganization({id:i?.organizationId,slug:c,name:e.project.name}),a=i?i.name!==e.project.name||i.desiredConfigHash!==r||i.organizationId!==d.id?n.updateProject(i.id,i.version,{name:e.project.name,organizationId:d.id,desiredConfigHash:r}):i:n.createProject({organizationId:d.id,slug:e.project.slug,name:e.project.name,desiredConfigHash:r}),l=new Map;for(let[R,E]of Object.entries(e.environments??{})){let $=n.getEnvironmentBySlug(a.id,R)??n.createEnvironment({projectId:a.id,slug:R,name:R.replace(/(^|[-_])(\w)/g,(Y,dt,m)=>m.toUpperCase()),kind:String(E?.type??R),region:E?.region??e.project.region,desiredState:bt(E)});l.set(R,$);let C=new Map(n.listResources(a.id,$.id).map((Y)=>[`${Y.kind}:${Y.slug}`,Y])),J=(Y,dt,m,Ut)=>{let st=`${Y}:${dt}`,Q=C.get(st),rt=bt(Ut);if(Q){if(Q.name!==m||Or(Q.desiredState)!==Or(rt))C.set(st,n.updateResource(Q.id,Q.version,{name:m,desiredState:rt}));return}let Dt=n.createResource({projectId:a.id,environmentId:$.id,kind:Y,slug:dt,name:m,provider:e.cloud?.provider,desiredState:rt,metadata:{source:"cloud-config"}});C.set(st,Dt)};for(let[Y,dt]of Object.entries(e.sites??{}))J("application",Y,Y,dt);let H=E?.app;if(H)for(let Y of["http","queue","cli"])J("function",Y,`${Y.toUpperCase()} function`,{...bt(H),function:Y});let O=e.infrastructure;for(let[Y,dt]of Object.entries(O?.functions??{}))J("function",Y,Y,dt);if(O?.compute)J("server",`${a.slug}-server`,a.name,{...bt(O.compute),label:a.name});for(let[Y,dt]of Object.entries(O?.databases??{}))J("database",Y,Y,dt);if(O?.appDatabase)J("database","application-database","Application database",O.appDatabase);else if(O?.database)J("database","application-database","Application database",{engine:O.database})}let o=new Ot(n).recoverExpired(),u=n.reconcileOrphanedOperations({policy:"fail"}),f={requeued:o.requeued+u.requeued,failed:o.failed+o.cancelled+u.failed};return{store:n,organization:d,project:a,environments:l,reconciliation:f}}var QD=["project:read","config:read","deployments:read","deployments:create","runtime:read","runtime:logs"];function Zd(t,e){let{store:n,organization:r,project:i}=t,c=new Set;for(let d of e){let a=Gt(n,d);c.add(a.id);let l=n.getMembershipForActor(r.id,a.id);if(l&&l.source!=="legacy")continue;let o=n.listResources(i.id).filter((y)=>y.kind==="application"&&Object.hasOwn(d.sites,y.slug)),u=d.role==="admin"?"owner":"viewer",f=d.role==="admin"||o.length===0?{type:"organization"}:{type:"resource",id:o[0].id},R=l?l.roleTemplate!==u||Or(l.scope)!==Or(f)?n.updateMembership({id:l.id,roleTemplate:u,scope:f,actorId:a.id}):l:n.createMembership({organizationId:r.id,actorId:a.id,roleTemplate:u,scope:f,source:"legacy"}),E=new Set;if(d.role==="member"&&o.length===0)for(let y of Jf("viewer"))E.add(`deny|${y}|organization|`);for(let y of o){let $=d.sites[y.slug];for(let C of QD)E.add(`allow|${C}|resource|${y.id}`);if($==="owner")E.add(`allow|config:write|resource|${y.id}`)}for(let y of n.listGrants(R.id).filter(($)=>$.source==="legacy")){let $=`${y.effect}|${y.capability}|${y.scope.type}|${y.scope.id??""}`;if(!E.has($))n.removeGrant(y.id,a.id)}for(let y of E){let[$,C,J,H]=y.split("|");n.upsertGrant({organizationId:r.id,membershipId:R.id,effect:$,capability:C,scope:J==="organization"?{type:"organization"}:{type:J,id:H},source:"legacy"})}}for(let d of n.listMemberships(r.id))if(d.source==="legacy"&&!c.has(d.actorId))n.revokeMembership(d.id)}async function Bn(t){let{controlPlane:e,environment:n,actor:r}=t,i=Gt(e.store,r),c=e.environments.get(n),d=t.resourceSlug&&c?e.store.listResources(e.project.id,c.id).find((u)=>u.slug===t.resourceSlug):void 0,a=new Ot(e.store,{workerId:`dashboard:${process.pid}`}),l=a.enqueue({projectId:e.project.id,environmentId:c?.id,resourceId:d?.id,actorId:i.id,kind:t.kind,input:t.input??{},lockKey:d?`resource:${d.id}`:c?`environment:${c.id}`:`project:${e.project.id}`,providerKey:d?.provider??"dashboard",buildSlot:t.kind.includes("deploy"),maxAttempts:1,timeoutSeconds:3600,resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;if(!a.claim(l.id)?.operation)throw Error(`Could not claim control-plane operation ${l.id}`);try{let u=await t.execute(),f=typeof u.stdout==="string"?String(u.stdout):"",R=typeof u.stderr==="string"?String(u.stderr):"";if(f)a.appendLog(l.id,f,{stream:"stdout"});if(R)a.appendLog(l.id,R,{stream:"stderr"});let E=u.ok?a.complete(l.id,Of(u)):a.fail(l.id,GD(u),Of(u));return{result:u,operation:E}}catch(u){throw a.fail(l.id,u instanceof Error?u.message:String(u),{ok:!1,threw:!0}),u}}function GD(t){let e=t;return String(e.error??e.stderr??"Operation failed")}function Of(t){let e=t,n=typeof e.stdout==="string"?e.stdout:"",r=typeof e.stderr==="string"?e.stderr:"",i={ok:t.ok,stdoutBytes:Buffer.byteLength(n),stderrBytes:Buffer.byteLength(r)};if(typeof e.operation==="string")i.operation=e.operation;if(typeof e.error==="string")i.error=e.error;return bt(i)}var ZD=new Set(["singlestore","vitess"]);function Kd(t){return ZD.has(t)}var Xd={mysql:"/var/lib/pantry/mysql/mysqld.sock",mariadb:"/var/lib/pantry/mariadb/mariadbd.sock"};function zn(t){return/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(t)}function YD(t){if(t==="postgres"||t==="pgsql")return"postgres";if(t==="mariadb")return"mariadb";if(t==="singlestore")return"singlestore";if(t==="vitess")return"vitess";return"mysql"}function Br(t){let e=t.infrastructure?.compute,n=re(t)?.engine;if(n)return YD(n);let r=e?.managedServices??{};if(r.postgres)return"postgres";if(r.mariadb)return"mariadb";return"mysql"}var gl=(t)=>t.replace(/`/g,"``"),sn=(t)=>t.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),Jr=(t)=>`"${t.replace(/"/g,'""')}"`,Yd=(t)=>`'${t.replace(/'/g,"''")}'`;function hl(t,e){return[`mysql --socket=${t==="mariadb"?Xd.mariadb:Xd.mysql} -u root <<'TS_CLOUD_SQL_EOF'`,...e,"TS_CLOUD_SQL_EOF"]}function Sl(t,e){return[`${ul(e)} -tA <<'TS_CLOUD_PG_EOF'`,...t,"TS_CLOUD_PG_EOF"]}function XD(t,e){if(t==="vitess")return KD(e);if(t==="postgres")return Sl(["SELECT 'DB=' || datname FROM pg_database WHERE datistemplate = false;","SELECT 'USER=' || usename FROM pg_user;"],e);return hl(t,["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 fi(t,e,n){let r=e?.host??"127.0.0.1",i=e?.username??"root",c=e?.password??"",d=e?.ssl===!1?"":" --ssl-mode=PREFERRED",a=(o)=>`'${String(o).replace(/'/g,"'\\''")}'`;return[`${c?`MYSQL_PWD=${a(c)} `:""}mysql -h ${a(r)} -P ${e?.port??n} -u ${a(i)}${d} --batch --skip-column-names <<'TS_CLOUD_SQL_EOF'`,...t,"TS_CLOUD_SQL_EOF"]}var _i=15306;function KD(t){let e=fi(["SHOW KEYSPACES;"],t,_i);return e[0]=`${e[0]} | sed 's/^/DB=/'`,e}function pD(t){return fi(["SHOW KEYSPACES;","SHOW VITESS_SHARDS;","SHOW VITESS_TABLETS;"],t,_i)}function mD(t){let e=[],n=[],r=[];for(let i of t.split(`
|
|
147
|
-
`)){let c=i.trim();if(!c)continue;let d=c.split("\t").map((a)=>a.trim()).filter(Boolean);if(d.length>=6){let[a,l,o,u,f,R,E]=d;r.push({cell:a??"",keyspace:l??"",shard:o??"",type:u??"",state:f??"",alias:R??"",hostname:E??""});continue}if(d.length===1){let a=d[0];if(a.includes("/")){let[l,o]=a.split("/");if(l&&o)n.push({keyspace:l,shard:o})}else e.push(a)}}return{keyspaces:[...new Set(e)].filter(Boolean).sort(),shards:n,tablets:r}}function qD(t,e,n){if(t==="postgres")return Sl([`SELECT 'CREATE DATABASE ${Jr(e)}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = ${Yd(e)})\\gexec`],n);return hl(t,[`CREATE DATABASE IF NOT EXISTS \`${gl(e)}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`])}function ty(t,e,n){let{username:r,password:i,database:c,access:d}=e;if(t==="postgres"){let o=["DO $$ BEGIN",` IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${Yd(r)}) THEN CREATE ROLE ${Jr(r)} LOGIN PASSWORD ${Yd(i)};`,` ELSE ALTER ROLE ${Jr(r)} LOGIN PASSWORD ${Yd(i)}; END IF;`,"END $$;"];if(c)o.push(d==="readonly"?`GRANT CONNECT ON DATABASE ${Jr(c)} TO ${Jr(r)};`:`GRANT ALL PRIVILEGES ON DATABASE ${Jr(c)} TO ${Jr(r)};`);return Sl(o,n)}let a=d==="readonly"?"SELECT":"ALL PRIVILEGES",l=[`CREATE USER IF NOT EXISTS '${sn(r)}'@'%' IDENTIFIED BY '${sn(i)}';`,`CREATE USER IF NOT EXISTS '${sn(r)}'@'localhost' IDENTIFIED BY '${sn(i)}';`,`ALTER USER '${sn(r)}'@'%' IDENTIFIED BY '${sn(i)}';`,`ALTER USER '${sn(r)}'@'localhost' IDENTIFIED BY '${sn(i)}';`];if(c)l.push(`GRANT ${a} ON \`${gl(c)}\`.* TO '${sn(r)}'@'%';`,`GRANT ${a} ON \`${gl(c)}\`.* TO '${sn(r)}'@'localhost';`);return l.push("FLUSH PRIVILEGES;"),hl(t,l)}function ey(t){let e=[],n=[];for(let r of t.split(`
|
|
148
|
-
`)){let i=r.trim();if(i.startsWith("DB="))e.push(i.slice(3));else if(i.startsWith("USER="))n.push(i.slice(5))}return{databases:[...new Set(e)].filter(Boolean).sort(),users:[...new Set(n)].filter(Boolean).sort()}}async function Ee(t,e,n,r){let i;try{i=Jn({config:t})}catch(l){return{ok:!1,error:`Could not initialize the cloud driver: ${l?.message??l}`}}let c=t.project.slug,d=await i.findComputeTargets({slug:c,environment:e,role:"app"});if(!d.length)return{ok:!1,error:"No app server target was found for this environment."};let a=await i.runRemoteDeploy({targets:[d[0]],commands:["set -uo pipefail",...n],comment:r,tags:{Project:c,Environment:e,Role:"app"}});return{ok:a.success,stdout:a.perInstance?.[0]?.output??"",stderr:a.perInstance?.[0]?.error??a.error??""}}function pd(t,e){return{ok:!1,error:`${e} is not available for ${t}: it is an external cluster, so this box has no engine to administer. ${t==="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 Tf(t,e){let n=Br(t);if(Kd(n)&&n!=="vitess")return{...pd(n,"Listing databases"),engine:n,databases:[],users:[]};let r=await Ee(t,e,XD(n,re(t)),"ts-cloud db:list"),i=r.ok&&r.stdout?ey(r.stdout):{databases:[],users:[]};return{...r,engine:n,...i}}async function bf(t,e,n){let r=Br(t);if(Kd(r))return pd(r,"Creating a database");return Ee(t,e,qD(r,n,re(t)),`ts-cloud db:create ${n}`)}async function Wf(t,e,n){let r=Br(t);if(Kd(r))return pd(r,"Creating a database user");return Ee(t,e,ty(r,n,re(t)),`ts-cloud db:user ${n.username}`)}var fl="/var/backups/ts-cloud/databases";function ny(t,e,n=fl,r){let i=`${n}/${e}-$(date +%Y%m%d-%H%M%S).sql.gz`,c=`mkdir -p ${n}`;if(t==="postgres")return[c,`${ul(r,"pg_dump")} ${e} | gzip > "${i}"`,`echo "BACKUP=${i}"`,`ls -l "${i}"`];let d=t==="mariadb"?Xd.mariadb:Xd.mysql;return[c,`mysqldump --socket=${d} -u root ${e} | gzip > "${i}"`,`echo "BACKUP=${i}"`,`ls -l "${i}"`]}function ry(t=fl){return[`ls -1t ${t}/*.sql.gz 2>/dev/null | head -50 | sed 's|^|BACKUP=|' || true`]}function iy(t){let e=[];for(let n of t.split(`
|
|
149
|
-
`)){let r=n.trim();if(!r.startsWith("BACKUP="))continue;let i=r.slice(7),d=(i.split("/").pop()??i).replace(/-\d{8}-\d{6}\.sql\.gz$/,"");if(i)e.push({file:i,database:d})}return e}async function Uf(t,e,n){if(!zn(n))return{ok:!1,error:"Database name must be a valid identifier.",database:n};let r=Br(t);if(Kd(r))return{...pd(r,"Backing up"),database:n};return{...await Ee(t,e,ny(r,n,fl,re(t)),`ts-cloud db:backup ${n}`),database:n}}async function jf(t,e){let n=await Ee(t,e,ry(),"ts-cloud db:backups"),r=n.ok&&n.stdout?iy(n.stdout):[];return{...n,backups:r}}async function Hf(t,e){let n=Br(t),r={keyspaces:[],shards:[],tablets:[]};if(n!=="vitess")return{ok:!1,error:"The configured database engine is not Vitess.",engine:n,...r};let i=await Ee(t,e,pD(re(t)),"ts-cloud vitess:topology"),c=i.ok&&i.stdout?mD(i.stdout):r;return{...i,engine:n,...c}}function Lf(t){return t.filter((e)=>e.state.toUpperCase()!=="SERVING")}function Ff(t){let e=new Set(t.tablets.filter((n)=>n.type.toUpperCase()==="PRIMARY"&&n.state.toUpperCase()==="SERVING").map((n)=>`${n.keyspace}/${n.shard}`));return t.shards.filter((n)=>!e.has(`${n.keyspace}/${n.shard}`))}var _l="/usr/local/bin/vtctldclient",cy="21.0.0";function qd(t){return`'${String(t).split("'").join("'\\''")}'`}function to(t){return re(t)?.vitess??{}}function Vf(t){return/^[A-Za-z_][A-Za-z0-9_]{0,63}$/.test(t)}function dy(t){return/^[0-9a-f]{8}(?:_[0-9a-f]{4}){3}_[0-9a-f]{12}$/i.test(t)}function oy(t=cy){let e=qd(t);return[`if ${_l} --version 2>/dev/null | grep -q ${e}; then echo "vtctldclient ${t} 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${t}"`,` 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'+t+'" >&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" ${_l}`,' rm -rf "$tmp"',` echo "installed vtctldclient ${t}"`,"fi"]}function Nf(t){if(!t.vtctldAddr)return null;return`${_l} --server ${qd(t.vtctldAddr)}`}function ay(t,e,n={}){let r=Nf(t);if(!r)return null;let i=n.sharded?" --sharded":"";return[`${r} CreateKeyspace${i} ${qd(e)}`]}function sy(t,e,n){let r=Nf(t);if(!r)return null;return['vschema_tmp="$(mktemp)"',`cat > "$vschema_tmp" <<'TS_CLOUD_VSCHEMA_EOF'`,n,"TS_CLOUD_VSCHEMA_EOF",`${r} ApplyVSchema --vschema-file "$vschema_tmp" ${qd(e)}`,'rm -f "$vschema_tmp"']}function ly(t,e,n="vitess"){return fi([`SET @@ddl_strategy='${n}';`,e.endsWith(";")?e:`${e};`],t,_i)}function gy(t,e){let n=e?[`USE ${e.replace(/[^A-Z0-9_]/gi,"")};`,"SHOW VITESS_MIGRATIONS;"]:["SHOW VITESS_MIGRATIONS;"],r=fi(n,t,_i);return r[0]=r[0].replace(" --skip-column-names",""),r}function uy(t){let e=t.split(`
|
|
150
|
-
`).map((d)=>d.trimEnd()).filter((d)=>d.trim().length>0);if(e.length===0)return[];let n=e[0].split("\t").map((d)=>d.trim()),r=(d)=>n.indexOf(d),i={uuid:r("migration_uuid"),keyspace:r("keyspace"),shard:r("shard"),table:r("mysql_table"),status:r("migration_status"),strategy:r("strategy"),added:r("added_timestamp"),completed:r("completed_timestamp"),progress:r("progress")};if(i.uuid===-1)return[];let c=[];for(let d of e.slice(1)){let a=d.split("\t"),l=(u)=>u>=0?(a[u]??"").trim():"",o=l(i.uuid);if(!o)continue;c.push({uuid:o,keyspace:l(i.keyspace),shard:l(i.shard),table:l(i.table),status:l(i.status),strategy:l(i.strategy),added:l(i.added),completed:l(i.completed),progress:l(i.progress)})}return c}function hy(t){return t.filter((e)=>e.status.toLowerCase()==="failed")}function Sy(t){return t.filter((e)=>["running","queued","ready"].includes(e.status.toLowerCase()))}function fy(t,e,n){let r=n.toUpperCase();return fi([`ALTER VITESS_MIGRATION '${e}' ${r};`],t,_i)}function Ri(t){if(Br(t)!=="vitess")return{ok:!1,error:"The configured database engine is not Vitess."};return null}function md(t){if(!t.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 xf(t,e){let n=Ri(t);if(n)return n;let r=to(t);return Ee(t,e,oy(r.clientVersion),"ts-cloud vitess:install-client")}async function Mf(t,e,n,r={}){let i=Ri(t);if(i)return{...i,keyspace:n};if(!Vf(n))return{ok:!1,error:"Keyspace name must be a valid identifier.",keyspace:n};let c=to(t),d=md(c);if(d)return{...d,keyspace:n};let a=ay(c,n,r);if(!a)return{...md({}),keyspace:n};return{...await Ee(t,e,a,`ts-cloud vitess:create-keyspace ${n}`),keyspace:n}}async function Qf(t,e,n,r){let i=Ri(t);if(i)return{...i,keyspace:n};if(!Vf(n))return{ok:!1,error:"Keyspace name must be a valid identifier.",keyspace:n};try{let o=JSON.parse(r);if(!o||typeof o!=="object")return{ok:!1,error:"The VSchema must be a JSON object.",keyspace:n}}catch(o){return{ok:!1,error:`The VSchema is not valid JSON: ${o?.message??o}`,keyspace:n}}let c=to(t),d=md(c);if(d)return{...d,keyspace:n};let a=sy(c,n,r);if(!a)return{...md({}),keyspace:n};return{...await Ee(t,e,a,`ts-cloud vitess:apply-vschema ${n}`),keyspace:n}}async function Gf(t,e,n){let r=Ri(t);if(r)return r;if(!n.trim())return{ok:!1,error:"No SQL was provided."};let i=to(t);return Ee(t,e,ly(re(t),n,i.ddlStrategy??"vitess"),"ts-cloud vitess:apply-schema")}async function Zf(t,e,n){let r=Ri(t);if(r)return{...r,migrations:[],failed:[],running:[]};let i=await Ee(t,e,gy(re(t),n),"ts-cloud vitess:migrations"),c=i.ok&&i.stdout?uy(i.stdout):[];return{...i,migrations:c,failed:hy(c),running:Sy(c)}}async function Yf(t,e,n,r){let i=Ri(t);if(i)return{...i,uuid:n};if(!dy(n))return{ok:!1,error:"Migration UUID is not in the expected format.",uuid:n};return{...await Ee(t,e,fy(re(t),n,r),`ts-cloud vitess:migration ${r} ${n}`),uuid:n}}function _y(t){let e=t.infrastructure?.appDatabase;if(e?.engine&&e.engine!=="vitess")return`This project already declares ${e.engine} as its application database.`;let n=t.infrastructure?.compute?.managedServices,r=n?["mysql","mariadb","postgres"].find((i)=>Boolean(n[i])):void 0;if(r)return`This server already declares the ${r} database service.`;return}function Ry(t,e){let n=e.keyspace.trim(),r=e.username.trim(),i=e.password,c=_y(t);if(c)throw Error(c);if(!zn(n))throw Error("Keyspace must contain letters, numbers, or underscores and cannot start with a number.");if(!zn(r))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(e.confirm!==n)throw Error(`Type "${n}" to confirm Vitess provisioning.`);let d={mode:"cluster",cell:"zone1",keyspaces:[{name:n,sharded:e.sharded===!0}],vtgatePort:15306,username:r,password:i,bindAddress:"127.0.0.1"};return{service:d,appDatabase:{engine:"vitess",name:n,username:r,host:"127.0.0.1",port:15306,ssl:!1},commands:[...Xf(),...Kf(d)]}}async function pf(t,e,n){let r=Ry(t,n);return{...await Ee(t,e,r.commands,`ts-cloud vitess:provision ${r.appDatabase.name}`),database:r.appDatabase,service:Object.fromEntries(Object.entries(r.service).filter(([c])=>c!=="password"))}}var Ey={capability:"runtime:terminal",scope:"organization"};var Iy={"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 Rl(t,e){return Iy[`${t.toUpperCase()} ${e}`]??Ey}import{createHmac as wy,randomBytes as Ay,timingSafeEqual as Dy}from"node:crypto";import{chmodSync as yy,existsSync as Py,mkdirSync as $y,readFileSync as vy,writeFileSync as ky}from"node:fs";import{dirname as Cy}from"node:path";var tc="ts_cloud_session";var Oy=28800000;function mf(t){let e=process.env.TS_CLOUD_DASHBOARD_SECRET?.trim();if(e)return e;let n=de(t,"dashboard-secret");try{if(Py(n)){let i=vy(n,"utf8").trim();if(i)return i}}catch{}let r=Ay(32).toString("base64url");try{$y(Cy(n),{recursive:!0}),ky(n,`${r}
|
|
151
|
-
`),yy(n,384)}catch{}return r}function Jy(t,e){return wy("sha256",e).update(t).digest("base64url")}function qf(t,e){if(!t)return null;let n=t.lastIndexOf(".");if(n<=0)return null;let r=t.slice(0,n),i=t.slice(n+1),c=Jy(r,e),d=Buffer.from(i),a=Buffer.from(c);if(d.length!==a.length||!Dy(d,a))return null;try{let l=JSON.parse(Buffer.from(r,"base64url").toString("utf8"));if(typeof l?.u!=="string"||typeof l?.exp!=="number")return null;if(l.mv!==void 0&&(!l.mv||typeof l.mv!=="object"||Array.isArray(l.mv)||Object.values(l.mv).some((o)=>!Number.isInteger(o)||o<1)))return null;if(Date.now()>=l.exp)return null;return l}catch{return null}}function El(t,e){if(!t)return;for(let n of t.split(";")){let r=n.indexOf("=");if(r<0)continue;if(n.slice(0,r).trim()===e)return decodeURIComponent(n.slice(r+1).trim())}return}function Ei(t,e={secure:!0}){let n=Math.floor((e.maxAgeMs??Oy)/1000),r=[`${tc}=${encodeURIComponent(t)}`,"Path=/","HttpOnly","SameSite=Lax",`Max-Age=${n}`];if(e.secure)r.push("Secure");return r.join("; ")}function eo(t={secure:!0}){let e=[`${tc}=`,"Path=/","HttpOnly","SameSite=Lax","Max-Age=0"];if(t.secure)e.push("Secure");return e.join("; ")}import{chmodSync as By,existsSync as zy,mkdirSync as Ty,readFileSync as by,writeFileSync as Wy}from"node:fs";import{dirname as Uy}from"node:path";function t_(){return bc("dashboard-users.json")}function no(t){return/^[a-z0-9][a-z0-9._-]{1,31}$/i.test(t)}function jy(t){if(!t||typeof t.username!=="string"||!no(t.username)||typeof t.passwordHash!=="string")return null;let e=t.role==="admin"?"admin":"member",n={};if(t.sites&&typeof t.sites==="object"){for(let[r,i]of Object.entries(t.sites))if(i==="owner"||i==="collaborator")n[r]=i}return{username:t.username,passwordHash:t.passwordHash,role:e,sites:n,name:typeof t.name==="string"?t.name:void 0,email:typeof t.email==="string"?t.email.trim().toLowerCase():void 0,createdAt:typeof t.createdAt==="string"?t.createdAt:void 0}}function Hy(t){try{let e=JSON.parse(t);if(!Array.isArray(e?.users))return[];return e.users.map(jy).filter((n)=>n!==null)}catch{return[]}}function e_(t){return de(t,"dashboard-users.json")}function Ie(t){let e=e_(t);if(!zy(e))return[];try{return Hy(by(e,"utf8"))}catch{return[]}}function ro(t,e){let n=e_(t);Ty(Uy(n),{recursive:!0}),Wy(n,`${JSON.stringify({users:e},null,2)}
|
|
152
|
-
`),By(n,384)}function He(t,e){let n=e.trim().toLowerCase();return t.find((r)=>r.username.toLowerCase()===n)}function n_(t,e="admin"){let n=Ie(t);if(n.some((d)=>d.role==="admin"))return{users:n};let r=process.env.TS_CLOUD_UI_PASSWORD?.trim()||ll(),i={username:e,passwordHash:tr(r),role:"admin",sites:{},name:"Administrator",createdAt:new Date().toISOString()},c=[...n,i];return ro(t,c),{users:c,generated:{username:e,password:r}}}function ec(t,e){let n=Ie(t),r=He(n,e.username),i=e.password?.trim()||(r?void 0:ll()),c={username:r?.username??e.username,passwordHash:i?tr(i):r.passwordHash,role:r?.role??"member",sites:e.sites,name:e.name??r?.name,email:e.email?.trim().toLowerCase()??r?.email,createdAt:r?.createdAt??new Date().toISOString()},d=r?n.map((a)=>a.username.toLowerCase()===c.username.toLowerCase()?c:a):[...n,c];return ro(t,d),{user:c,password:i}}function io(t,e,n){let r=Ie(t),i=He(r,e);if(!i)throw Error("Authentication user was not found");let c={...i,passwordHash:n};return ro(t,r.map((d)=>d.username.toLowerCase()===i.username.toLowerCase()?c:d)),c}function Il(t,e){let n=Ie(t),r=He(n,e);if(!r)return{ok:!1,error:`No such user: ${e}`};if(r.role==="admin"&&n.filter((i)=>i.role==="admin").length===1)return{ok:!1,error:"Cannot remove the last admin."};return ro(t,n.filter((i)=>i.username.toLowerCase()!==r.username.toLowerCase())),{ok:!0}}function Ii(t){return{username:t.username,name:t.name??t.username,role:t.role,email:t.email,sites:t.sites,siteCount:Object.keys(t.sites).length,createdAt:t.createdAt}}var Ly={username:"local",passwordHash:"",role:"admin",sites:{},name:"Local (auth disabled)"};function r_(t){let{cwd:e,enabled:n,secret:r,authorization:i,authentication:c}=t,d=(l)=>{if(!c)return;let o=El(l.headers.get("cookie"),tc);return o?.startsWith("v2.")?c.verifySessionToken(o):void 0},a=(l)=>{let o=i.store.getActorByExternalId("user",`dashboard:${l.username.toLowerCase()}`),u=o?i.store.getMembershipForActor(i.organizationId,o.id):void 0;return{actor:o,membership:u}};return{enabled:n,resolveUser(l){if(!n)return Ly;let o=El(l.headers.get("cookie"),tc),u=d(l),f=u?void 0:qf(o,r),R=u?.identity.username??f?.u;if(!R)return null;let E=He(Ie(e),R);if(!E)return null;let{membership:y}=a(E);if(!y||y.status!=="active"||!u&&f?.mv?.[i.organizationId]!==y.sessionVersion)return null;if(!y.lastActiveAt||Date.now()-new Date(y.lastActiveAt).getTime()>300000)i.store.touchMembership(y.id);return E},resolveSession(l){return d(l)?.session??null},check(l,o,u,f){if(!n)return{ok:!0};if(!u)return{ok:!1,status:401,error:"Sign in to continue.",unauthenticated:!0};let R=Rl(l.method,o);if(R.anyUser)return{ok:!0};if(R.siteFrom==="body"&&!f)return{ok:!1,status:400,error:"This request must name a site."};let{membership:E}=a(u);if(!E)return{ok:!1,status:401,error:"Sign in to continue.",unauthenticated:!0};let y=R.scope==="organization"?{organizationId:i.organizationId}:i.store.resolveAuthorizationTarget(i.organizationId,{type:"project",id:i.projectId});if(R.scope==="site"){let C=new URL(l.url).searchParams.get("env")??i.defaultEnvironment,J=i.store.getEnvironmentBySlug(i.projectId,C),H=i.store.listResources(i.projectId,J?.id).find((O)=>O.kind==="application"&&O.slug===f);y=H?i.store.resolveAuthorizationTarget(i.organizationId,{type:"resource",id:H.id}):void 0}if(!(y?Ne({membership:E,grants:i.store.listGrants(E.id),capability:R.capability,target:y}):{allowed:!1}).allowed)return{ok:!1,status:403,error:"You do not have access to this."};return{ok:!0}}}}async function i_(t,e){if(Rl(t.method,e).siteFrom!=="body")return;try{let r=await t.clone().json();return String(r?.name??"").trim()||void 0}catch{return}}import{createHash as Fy}from"node:crypto";function c_(t,e,n){for(let r of n){let i=Gt(e.store,r);if(t.getIdentityByActor(i.id))continue;t.createIdentity({actorId:i.id,username:r.username,email:r.email,emailVerified:!!r.email,passwordHash:r.passwordHash,requiresPasswordUpgrade:!0})}}function Vy(t,e,n){let r=n.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(r)?r:"sso-user";if(!t.getIdentityByUsername(i)&&!He(e,i))return i;let c=Fy("sha256").update(n).digest("hex").slice(0,7);return`${i.slice(0,24)}-${c}`}function d_(t,e,n,r){if(r.provider.organizationId!==e.organization.id)throw Error("OIDC provider is not configured for this organization");let i=t.getOidcSubject(r.provider.id,r.subject),c=i?t.getIdentity(i.identityId):t.getIdentityByEmail(r.email);if(c?.disabledAt)throw Error("OIDC identity is disabled");if(!i&&c&&!c.emailVerifiedAt)throw Error("OIDC cannot automatically link an unverified local email address");let d=Ie(n),a=!1,l=c?He(d,c.username):void 0;if(c&&!l)throw Error("OIDC identity has no dashboard user");if(!c){let f=Vy(t,d,r.email);l=ec(n,{username:f,name:r.name,email:r.email,sites:{}}).user;let E=Gt(e.store,l);c=t.createIdentity({actorId:E.id,username:l.username,email:r.email,emailVerified:!0,passwordHash:l.passwordHash}),a=!0}else if(c.email!==r.email)c=t.setVerifiedEmail(c.id,r.email);let o=e.store.getActor(c.actorId);if(!o)throw Error("OIDC identity actor was not found");let u=e.store.getMembershipForActor(e.organization.id,o.id);if(u?.status==="revoked")throw Error("OIDC organization membership is revoked");if(!u)e.store.createMembership({organizationId:e.organization.id,actorId:o.id,roleTemplate:r.provider.defaultRole,scope:{type:"organization"},source:"manual"});return t.linkOidcSubject(r.provider.id,c.id,r.subject,r.email),{identity:c,user:l,provisioned:a}}function o_(t,e,n){let r=e.store.getMembershipForActor(e.organization.id,n.actorId);if(!r||r.status!=="active"||r.roleTemplate==="owner"||!n.emailVerifiedAt||!n.email)return!1;let i=n.email.split("@")[1]?.toLowerCase();return t.listOidcProviders(e.organization.id).some((c)=>c.enforceSso&&!!i&&c.allowedDomains.includes(i))}function Ny(t){return t.replace(/[&<>"']/g,(e)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}function a_(t=!1,e=[]){let n=t?"/serverless":"/",r=e.map((c)=>`<a class="sso-button" href="/auth/oidc/${encodeURIComponent(c.slug)}/start?return=${encodeURIComponent(n)}">Continue with ${Ny(c.name)}</a>`).join("");return`<!doctype html>
|
|
153
|
-
<html lang="en">
|
|
154
|
-
<head>
|
|
155
|
-
<meta charset="UTF-8">
|
|
156
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
157
|
-
<title>Sign in · ts-cloud</title>
|
|
158
|
-
<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">
|
|
159
|
-
<link rel="preconnect" href="https://fonts.googleapis.com">
|
|
160
|
-
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
|
|
161
|
-
<style>${`
|
|
162
|
-
:root {
|
|
163
|
-
--bg: #0a0e15; --bg2: #0b0f18; --panel: rgba(255,255,255,0.03); --panel-br: rgba(255,255,255,0.072);
|
|
164
|
-
--txt: #e9edf5; --txt2: #94a1b8; --txt3: #5a6577;
|
|
165
|
-
--accent: #5a8be0; --accent-ink: #061019;
|
|
166
|
-
--bad: #f0736e; --badbg: rgba(240,115,110,0.11);
|
|
167
|
-
}
|
|
168
|
-
* { box-sizing: border-box; margin: 0; padding: 0; }
|
|
169
|
-
html { background: var(--bg); min-height: 100%; }
|
|
170
|
-
body {
|
|
171
|
-
font-family: 'Inter', system-ui, sans-serif; color: var(--txt); min-height: 100vh;
|
|
172
|
-
background:
|
|
173
|
-
radial-gradient(900px 460px at 88% -8%, rgba(90,139,224,0.06), transparent 62%),
|
|
174
|
-
linear-gradient(175deg, var(--bg), var(--bg2));
|
|
175
|
-
-webkit-font-smoothing: antialiased;
|
|
176
|
-
display: grid; place-items: center; padding: 24px;
|
|
177
|
-
}
|
|
178
|
-
.card {
|
|
179
|
-
width: 100%; max-width: 380px;
|
|
180
|
-
background: var(--panel); border: 1px solid var(--panel-br); border-radius: 16px;
|
|
181
|
-
padding: 32px; backdrop-filter: blur(6px);
|
|
182
|
-
animation: rise .5s cubic-bezier(0.16, 1, 0.3, 1) both;
|
|
183
|
-
}
|
|
184
|
-
@keyframes rise { from { opacity: 0; transform: translateY(8px) } to { opacity: 1; transform: none } }
|
|
185
|
-
@media (prefers-reduced-motion: reduce) { .card { animation: none } }
|
|
186
|
-
.brand { display: flex; align-items: center; gap: 10px; font-weight: 700; font-size: 17px; letter-spacing: -0.02em; }
|
|
187
|
-
.brand .dot { width: 20px; height: 20px; border-radius: 6px; background: var(--accent); box-shadow: inset 0 1px 0 rgba(255,255,255,0.35); }
|
|
188
|
-
h1 { font-size: 21px; font-weight: 800; letter-spacing: -0.02em; margin-top: 22px; }
|
|
189
|
-
.sub { color: var(--txt2); font-size: 13.5px; margin-top: 5px; line-height: 1.5; }
|
|
190
|
-
form { margin-top: 24px; display: grid; gap: 14px; }
|
|
191
|
-
.field { display: flex; flex-direction: column; gap: 7px; }
|
|
192
|
-
label { color: var(--txt3); font-size: 11px; font-weight: 800; text-transform: uppercase; letter-spacing: 0.07em; }
|
|
193
|
-
input {
|
|
194
|
-
width: 100%; background: rgba(255,255,255,0.05); border: 1px solid var(--panel-br); border-radius: 10px;
|
|
195
|
-
padding: 10px 12px; color: var(--txt); font-family: inherit; font-size: 14px;
|
|
196
|
-
}
|
|
197
|
-
input:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px rgba(90,139,224,0.12); }
|
|
198
|
-
button {
|
|
199
|
-
margin-top: 4px; background: var(--accent); color: var(--accent-ink); border: 0; border-radius: 10px;
|
|
200
|
-
padding: 11px 16px; font-weight: 700; font-size: 13.5px; cursor: pointer; font-family: inherit;
|
|
201
|
-
transition: filter .12s, transform .12s;
|
|
202
|
-
}
|
|
203
|
-
button:hover { filter: brightness(1.06); }
|
|
204
|
-
button:active { transform: translateY(1px); }
|
|
205
|
-
button[disabled] { opacity: 0.6; cursor: default; }
|
|
206
|
-
.msg {
|
|
207
|
-
display: none; margin-top: 14px; padding: 10px 12px; border-radius: 10px;
|
|
208
|
-
background: var(--badbg); border: 1px solid rgba(240,115,110,0.22); color: var(--bad);
|
|
209
|
-
font-size: 13px; line-height: 1.45;
|
|
210
|
-
}
|
|
211
|
-
.msg.shown { display: block; }
|
|
212
|
-
.hidden { display: none !important; }
|
|
213
|
-
.note { color: var(--txt3); font-size: 12px; margin-top: 20px; line-height: 1.5; }
|
|
214
|
-
.note code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; color: var(--txt2); }
|
|
215
|
-
a { color: var(--accent); text-decoration: none; }
|
|
216
|
-
a:hover { text-decoration: underline; }
|
|
217
|
-
.sso { display: grid; gap: 10px; margin-top: 22px; }
|
|
218
|
-
.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); }
|
|
219
|
-
.sso-button:hover { border-color: var(--accent); text-decoration: none; }
|
|
220
|
-
.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; }
|
|
221
|
-
.separator::before, .separator::after { content: ''; height: 1px; flex: 1; background: var(--panel-br); }
|
|
222
|
-
`}</style>
|
|
223
|
-
</head>
|
|
224
|
-
<body>
|
|
225
|
-
<main class="card">
|
|
226
|
-
<div class="brand"><span class="dot"></span> ts-cloud</div>
|
|
227
|
-
<h1>Sign in</h1>
|
|
228
|
-
<p class="sub">Manage the sites you have been given access to.</p>
|
|
229
|
-
|
|
230
|
-
${e.length>0?`<div class="sso" aria-label="Single sign-on">${r}</div><div class="separator"><span>or use local recovery</span></div>`:""}
|
|
231
|
-
|
|
232
|
-
<form id="login" autocomplete="on">
|
|
233
|
-
<div class="field">
|
|
234
|
-
<label for="username">Username</label>
|
|
235
|
-
<input id="username" name="username" autocomplete="username" required autofocus>
|
|
236
|
-
</div>
|
|
237
|
-
<div class="hidden field" id="mfa-field">
|
|
238
|
-
<label for="mfa-code">Authenticator or recovery code</label>
|
|
239
|
-
<input id="mfa-code" name="mfa-code" autocomplete="one-time-code">
|
|
240
|
-
</div>
|
|
241
|
-
<div class="field">
|
|
242
|
-
<label for="password">Password</label>
|
|
243
|
-
<input id="password" name="password" type="password" autocomplete="current-password" required>
|
|
244
|
-
</div>
|
|
245
|
-
<button type="submit" id="submit">Sign in</button>
|
|
246
|
-
</form>
|
|
247
|
-
|
|
248
|
-
<p class="msg" id="msg" role="alert" aria-live="polite"></p>
|
|
249
|
-
<p class="note"><a href="/forgot-password">Forgot your password?</a></p>
|
|
250
|
-
</main>
|
|
251
|
-
|
|
252
|
-
<script>
|
|
253
|
-
const form = document.getElementById('login')
|
|
254
|
-
const msg = document.getElementById('msg')
|
|
255
|
-
const submit = document.getElementById('submit')
|
|
256
|
-
const mfaField = document.getElementById('mfa-field')
|
|
257
|
-
const mfaCode = document.getElementById('mfa-code')
|
|
258
|
-
let challengeToken = ''
|
|
259
|
-
|
|
260
|
-
if (new URLSearchParams(location.search).has('sso_error')) {
|
|
261
|
-
msg.textContent = 'Single sign-on could not be completed. Try again or use the local recovery path.'
|
|
262
|
-
msg.classList.add('shown')
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
form.addEventListener('submit', async (event) => {
|
|
266
|
-
event.preventDefault()
|
|
267
|
-
msg.classList.remove('shown')
|
|
268
|
-
submit.disabled = true
|
|
269
|
-
submit.textContent = 'Signing in...'
|
|
270
|
-
try {
|
|
271
|
-
const res = await fetch(challengeToken ? '/api/auth/mfa/complete' : '/api/login', {
|
|
272
|
-
method: 'POST',
|
|
273
|
-
headers: { 'content-type': 'application/json' },
|
|
274
|
-
body: JSON.stringify(challengeToken
|
|
275
|
-
? { challengeToken, code: mfaCode.value }
|
|
276
|
-
: { username: document.getElementById('username').value, password: document.getElementById('password').value }),
|
|
277
|
-
})
|
|
278
|
-
const body = await res.json().catch(() => ({}))
|
|
279
|
-
if (!res.ok || !body.ok) throw new Error(body.error || 'Could not sign in.')
|
|
280
|
-
if (body.mfaRequired) {
|
|
281
|
-
challengeToken = body.challengeToken
|
|
282
|
-
mfaField.classList.remove('hidden')
|
|
283
|
-
mfaCode.required = true
|
|
284
|
-
document.getElementById('username').readOnly = true
|
|
285
|
-
document.getElementById('password').readOnly = true
|
|
286
|
-
submit.disabled = false
|
|
287
|
-
submit.textContent = 'Verify and sign in'
|
|
288
|
-
mfaCode.focus()
|
|
289
|
-
return
|
|
290
|
-
}
|
|
291
|
-
location.href = ${JSON.stringify(n)}
|
|
292
|
-
} catch (error) {
|
|
293
|
-
msg.textContent = (error && error.message) || String(error)
|
|
294
|
-
msg.classList.add('shown')
|
|
295
|
-
submit.disabled = false
|
|
296
|
-
submit.textContent = 'Sign in'
|
|
297
|
-
if (challengeToken) {
|
|
298
|
-
mfaCode.value = ''
|
|
299
|
-
mfaCode.focus()
|
|
300
|
-
}
|
|
301
|
-
else {
|
|
302
|
-
document.getElementById('password').value = ''
|
|
303
|
-
document.getElementById('password').focus()
|
|
304
|
-
}
|
|
305
|
-
}
|
|
306
|
-
})
|
|
307
|
-
</script>
|
|
308
|
-
</body>
|
|
309
|
-
</html>`}function s_(t){let e=t==="reset";return`<!doctype html>
|
|
310
|
-
<html lang="en">
|
|
311
|
-
<head>
|
|
312
|
-
<meta charset="UTF-8">
|
|
313
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
314
|
-
<title>${e?"Choose a new password":"Recover your account"} · ts-cloud</title>
|
|
315
|
-
<style>${`
|
|
316
|
-
:root {
|
|
317
|
-
--bg: #0a0e15; --bg2: #0b0f18; --panel: rgba(255,255,255,0.03); --panel-br: rgba(255,255,255,0.072);
|
|
318
|
-
--txt: #e9edf5; --txt2: #94a1b8; --txt3: #5a6577;
|
|
319
|
-
--accent: #5a8be0; --accent-ink: #061019;
|
|
320
|
-
--bad: #f0736e; --badbg: rgba(240,115,110,0.11);
|
|
321
|
-
}
|
|
322
|
-
* { box-sizing: border-box; margin: 0; padding: 0; }
|
|
323
|
-
html { background: var(--bg); min-height: 100%; }
|
|
324
|
-
body {
|
|
325
|
-
font-family: 'Inter', system-ui, sans-serif; color: var(--txt); min-height: 100vh;
|
|
326
|
-
background:
|
|
327
|
-
radial-gradient(900px 460px at 88% -8%, rgba(90,139,224,0.06), transparent 62%),
|
|
328
|
-
linear-gradient(175deg, var(--bg), var(--bg2));
|
|
329
|
-
-webkit-font-smoothing: antialiased;
|
|
330
|
-
display: grid; place-items: center; padding: 24px;
|
|
331
|
-
}
|
|
332
|
-
.card {
|
|
333
|
-
width: 100%; max-width: 380px;
|
|
334
|
-
background: var(--panel); border: 1px solid var(--panel-br); border-radius: 16px;
|
|
335
|
-
padding: 32px; backdrop-filter: blur(6px);
|
|
336
|
-
animation: rise .5s cubic-bezier(0.16, 1, 0.3, 1) both;
|
|
337
|
-
}
|
|
338
|
-
@keyframes rise { from { opacity: 0; transform: translateY(8px) } to { opacity: 1; transform: none } }
|
|
339
|
-
@media (prefers-reduced-motion: reduce) { .card { animation: none } }
|
|
340
|
-
.brand { display: flex; align-items: center; gap: 10px; font-weight: 700; font-size: 17px; letter-spacing: -0.02em; }
|
|
341
|
-
.brand .dot { width: 20px; height: 20px; border-radius: 6px; background: var(--accent); box-shadow: inset 0 1px 0 rgba(255,255,255,0.35); }
|
|
342
|
-
h1 { font-size: 21px; font-weight: 800; letter-spacing: -0.02em; margin-top: 22px; }
|
|
343
|
-
.sub { color: var(--txt2); font-size: 13.5px; margin-top: 5px; line-height: 1.5; }
|
|
344
|
-
form { margin-top: 24px; display: grid; gap: 14px; }
|
|
345
|
-
.field { display: flex; flex-direction: column; gap: 7px; }
|
|
346
|
-
label { color: var(--txt3); font-size: 11px; font-weight: 800; text-transform: uppercase; letter-spacing: 0.07em; }
|
|
347
|
-
input {
|
|
348
|
-
width: 100%; background: rgba(255,255,255,0.05); border: 1px solid var(--panel-br); border-radius: 10px;
|
|
349
|
-
padding: 10px 12px; color: var(--txt); font-family: inherit; font-size: 14px;
|
|
350
|
-
}
|
|
351
|
-
input:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px rgba(90,139,224,0.12); }
|
|
352
|
-
button {
|
|
353
|
-
margin-top: 4px; background: var(--accent); color: var(--accent-ink); border: 0; border-radius: 10px;
|
|
354
|
-
padding: 11px 16px; font-weight: 700; font-size: 13.5px; cursor: pointer; font-family: inherit;
|
|
355
|
-
transition: filter .12s, transform .12s;
|
|
356
|
-
}
|
|
357
|
-
button:hover { filter: brightness(1.06); }
|
|
358
|
-
button:active { transform: translateY(1px); }
|
|
359
|
-
button[disabled] { opacity: 0.6; cursor: default; }
|
|
360
|
-
.msg {
|
|
361
|
-
display: none; margin-top: 14px; padding: 10px 12px; border-radius: 10px;
|
|
362
|
-
background: var(--badbg); border: 1px solid rgba(240,115,110,0.22); color: var(--bad);
|
|
363
|
-
font-size: 13px; line-height: 1.45;
|
|
364
|
-
}
|
|
365
|
-
.msg.shown { display: block; }
|
|
366
|
-
.hidden { display: none !important; }
|
|
367
|
-
.note { color: var(--txt3); font-size: 12px; margin-top: 20px; line-height: 1.5; }
|
|
368
|
-
.note code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; color: var(--txt2); }
|
|
369
|
-
a { color: var(--accent); text-decoration: none; }
|
|
370
|
-
a:hover { text-decoration: underline; }
|
|
371
|
-
.sso { display: grid; gap: 10px; margin-top: 22px; }
|
|
372
|
-
.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); }
|
|
373
|
-
.sso-button:hover { border-color: var(--accent); text-decoration: none; }
|
|
374
|
-
.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; }
|
|
375
|
-
.separator::before, .separator::after { content: ''; height: 1px; flex: 1; background: var(--panel-br); }
|
|
376
|
-
`}</style>
|
|
377
|
-
</head>
|
|
378
|
-
<body>
|
|
379
|
-
<main class="card">
|
|
380
|
-
<div class="brand"><span class="dot"></span> ts-cloud</div>
|
|
381
|
-
<h1>${e?"Choose a new password":"Recover your account"}</h1>
|
|
382
|
-
<p class="sub">${e?"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>
|
|
383
|
-
<form id="recovery" autocomplete="on">
|
|
384
|
-
${e?'<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>'}
|
|
385
|
-
<button type="submit" id="submit">${e?"Change password":"Send reset link"}</button>
|
|
386
|
-
</form>
|
|
387
|
-
<p class="msg" id="msg" role="status" aria-live="polite"></p>
|
|
388
|
-
<p class="note"><a href="/login">Return to sign in</a></p>
|
|
389
|
-
</main>
|
|
390
|
-
<script>
|
|
391
|
-
const form = document.getElementById('recovery')
|
|
392
|
-
const msg = document.getElementById('msg')
|
|
393
|
-
const submit = document.getElementById('submit')
|
|
394
|
-
const reset = ${JSON.stringify(e)}
|
|
395
|
-
const token = new URLSearchParams(location.search).get('token') || ''
|
|
396
|
-
if (reset && !token) {
|
|
397
|
-
msg.textContent = 'This reset link is missing its token. Request a new link.'
|
|
398
|
-
msg.classList.add('shown')
|
|
399
|
-
submit.disabled = true
|
|
400
|
-
}
|
|
401
|
-
form.addEventListener('submit', async (event) => {
|
|
402
|
-
event.preventDefault()
|
|
403
|
-
if (reset && document.getElementById('password').value !== document.getElementById('confirmation').value) {
|
|
404
|
-
msg.textContent = 'The passwords do not match.'
|
|
405
|
-
msg.classList.add('shown')
|
|
406
|
-
return
|
|
407
|
-
}
|
|
408
|
-
submit.disabled = true
|
|
409
|
-
msg.textContent = reset ? 'Changing password…' : 'Requesting reset link…'
|
|
410
|
-
msg.classList.add('shown')
|
|
411
|
-
const response = await fetch(reset ? '/api/auth/password-reset/complete' : '/api/auth/password-reset/request', {
|
|
412
|
-
method: 'POST',
|
|
413
|
-
headers: { 'content-type': 'application/json' },
|
|
414
|
-
body: JSON.stringify(reset
|
|
415
|
-
? { token, password: document.getElementById('password').value }
|
|
416
|
-
: { identifier: document.getElementById('identifier').value }),
|
|
417
|
-
})
|
|
418
|
-
const result = await response.json().catch(() => ({}))
|
|
419
|
-
msg.textContent = result.message || result.error || 'The request could not be completed.'
|
|
420
|
-
if (!response.ok) {
|
|
421
|
-
submit.disabled = false
|
|
422
|
-
return
|
|
423
|
-
}
|
|
424
|
-
if (reset)
|
|
425
|
-
setTimeout(() => location.assign('/login'), 1200)
|
|
426
|
-
})
|
|
427
|
-
</script>
|
|
428
|
-
</body>
|
|
429
|
-
</html>`}var xy=["restart","reload","start","stop","enable","disable"],l_=65536;function wi(t){return t.length<=l_?t:`${t.slice(0,l_)}
|
|
430
|
-
|
|
431
|
-
[output truncated]`}function My(t){return/^[A-Za-z0-9_.@:-]+$/.test(t)}function wl(t){return/^[A-Za-z0-9_-]+$/.test(t)}function Qy(t){return t.charAt(0).toUpperCase()+t.slice(1)}function oo(t,e){let n=[],r=e.servicesDetail??e.services??[];for(let d of r){let a=String(d?.name??"");if(!a||!My(a))continue;for(let l of xy)n.push({id:`${l}:${a}`,label:`${Qy(l)} ${a}`,group:"service",target:a,mutates:!0,confirm:a,danger:l==="stop"||l==="disable"})}for(let[d,a]of Object.entries(t.sites??{})){if(!a||!wl(d))continue;let l=h_(a);if(l==="server-app"||l==="server-php")n.push({id:`rollback:${d}`,label:`Rollback ${d}`,group:"deploy",target:d,mutates:!0,confirm:d,danger:!0})}let i=new Set;for(let d of e.workers??[]){let a=String(d?.name??"").split(":")[0];if(a&&wl(a))i.add(a)}for(let d of i)n.push({id:`worker:restart:${d}`,label:`Restart workers (${d})`,group:"worker",target:d,mutates:!0,confirm:d});for(let[d,a]of Object.entries(t.sites??{})){if(!a||!wl(d))continue;if(a.scheduler||a.schedule){let l=co(a)==="laravel";n.push({id:`scheduler:run:${d}`,label:`${l?"Run":"Restart"} scheduler (${d})`,group:"scheduler",target:d,mutates:!0,confirm:d})}}if(t.infrastructure?.compute?.backups?.enabled){if(n.push({id:"backup:run",label:"Run backup now",group:"backup",target:"backup",mutates:!0,confirm:"backup"}),re(t))n.push({id:"backup:restore",label:"Restore latest DB backup",group:"backup",target:"database",mutates:!0,confirm:"restore",danger:!0})}return n}function Dl(t,e,n){return oo(e,n).find((r)=>r.id===t)}function Gy(t,e){let n=t==="enable"||t==="disable"?`systemctl is-enabled ${e} 2>/dev/null || true`:`systemctl is-active ${e} 2>/dev/null || true`;return["set -o pipefail",`systemctl ${t} ${e}`,n]}function Zy(){return`eval "$(cd ${S_} && pantry env 2>/dev/null)"`}function R_(t,e,n){let r=`${u_(t,e)}/current`;return["set -uo pipefail",`[ -d ${r} ] || { echo "site ${e} has no current release" >&2; exit 1; }`,`cd ${r} && ${Zy()} && php artisan ${n}`]}function Yy(t,e,n){if(t==="laravel")return R_(e,n,"queue:restart");let r=`${e}-${n}-queue-*.service`;return["set -uo pipefail",`units=$(systemctl list-units --type=service --all --no-legend '${r}' 2>/dev/null | awk '{print $1}')`,`[ -n "$units" ] || { echo "no queue-worker units found for ${n} (${r})" >&2; exit 1; }`,"systemctl restart $units",`systemctl --no-legend --type=service list-units '${r}' 2>/dev/null || true`]}function Xy(t,e,n){if(t==="laravel")return R_(e,n,"schedule:run");let r=`${e}-${n}-scheduler.service`;return["set -uo pipefail",`systemctl restart ${r}`,`systemctl is-active ${r} 2>/dev/null || true`]}function Ky(){return["set -uo pipefail",`[ -x ${Al} ] || { echo "scheduled backups are not provisioned on this server" >&2; exit 1; }`,Al]}function g_(t,e,n){return{operation:t,command:e,ok:n.success,stdout:wi(n.perInstance?.[0]?.output??""),stderr:wi(n.perInstance?.[0]?.error??n.error??"")}}async function ao(t,e,n,r={}){let i=t.project.slug,c;try{c=Jn({config:t})}catch(f){return{operation:n.id,ok:!1,error:`Could not initialize the cloud driver: ${f?.message??f}`}}let d={driver:c,slug:i,environment:e,role:"app"};if(n.group==="deploy"){let f=r.to&&/^[A-Za-z0-9._-]+$/.test(r.to)?r.to:void 0,R=await f_(d,{siteName:n.target,to:f});return g_(n.id,`rollback ${n.target}${f?` → ${f}`:""}`,R)}if(n.id==="backup:restore"){let f=await __(d,{database:re(t)});return g_(n.id,"db restore",f)}let a=await c.findComputeTargets({slug:i,environment:e,role:"app"});if(!a.length)return{operation:n.id,ok:!1,error:"No app server target was found for this environment."};let l,o;if(n.group==="service"){let[f,...R]=n.id.split(":");l=Gy(f,R.join(":")),o=`systemctl ${f} ${n.target}`}else if(n.group==="worker"){let f=co(t.sites?.[n.target]??{});l=Yy(f,i,n.target),o=f==="laravel"?`queue:restart (${n.target})`:`restart queue units (${n.target})`}else if(n.group==="scheduler"){let f=co(t.sites?.[n.target]??{});l=Xy(f,i,n.target),o=f==="laravel"?`schedule:run (${n.target})`:`restart scheduler (${n.target})`}else if(n.id==="backup:run")l=Ky(),o="ts-cloud backup";else return{operation:n.id,ok:!1,error:"Unknown operation."};let u=await c.runRemoteDeploy({targets:[a[0]],commands:l,comment:`ts-cloud dashboard:${n.id}`,tags:{Project:i,Environment:e,Role:"app"}});return{operation:n.id,command:o,ok:u.success,stdout:wi(u.perInstance?.[0]?.output??""),stderr:wi(u.perInstance?.[0]?.error??u.error??"")}}async function nc(t,e,n){let r=n.trim();if(!r)return{operation:"command",ok:!1,error:"A command is required."};let i;try{i=Jn({config:t})}catch(l){return{operation:"command",ok:!1,error:`Could not initialize the cloud driver: ${l?.message??l}`}}let c=t.project.slug,d=await i.findComputeTargets({slug:c,environment:e,role:"app"});if(!d.length)return{operation:"command",ok:!1,error:"No app server target was found for this environment."};let a=await i.runRemoteDeploy({targets:[d[0]],commands:["set -o pipefail",r],comment:"ts-cloud dashboard:command",tags:{Project:c,Environment:e,Role:"app"}});return{operation:"command",command:r,ok:a.success,stdout:wi(a.perInstance?.[0]?.output??""),stderr:wi(a.perInstance?.[0]?.error??a.error??"")}}var py=[{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}],my=new Map(py.flatMap((t)=>(t.legacyPaths??[]).map((e)=>[e,t.path])));function E_(t){return my.get(t)}function qy(t,e){return[`${t}-${e}`,`${t}-${e}-queues`,`${t}-${e}-daemons`]}function I_(t,e,n){return n.some((r)=>qy(e,r).includes(t))}function yl(t,e){let{user:n,slug:r}=e;if(n.role==="admin")return t;let i=(t.sites??[]).map((y)=>y.name).filter(Boolean),c=sl(n,i),d=new Set(c),a=(t.sites??[]).filter((y)=>d.has(y.name)),l=(t.sitesDetail??[]).filter((y)=>d.has(y.name)),o=new Set(l.map((y)=>y.domain).filter(Boolean)),u=(t.serverDeploymentsDetail??t.serverDeployments??[]).filter((y)=>d.has(y.site)),f=(t.serverLogs??[]).filter((y)=>I_(y.source,r,c)),R=(t.security?.tlsCertificates??[]).filter((y)=>o.has(y.domain)),E=(t.activity??[]).filter((y)=>{if(y.type==="deploy")return c.some(($)=>String(y.title??"").startsWith(`${$} `));if(y.type==="log")return I_(String(y.title??"").split(" ")[0],r,c);return!1});return{mode:t.mode,environment:t.environment,environments:t.environments,scoped:!0,server:{name:""},sites:a,sitesDetail:l,workers:(t.workers??[]).filter((y)=>d.has(y.site)),serverDeployments:u.slice(0,5),serverDeploymentsDetail:u.slice(0,50),deploymentsEmptyReason:u.length?void 0:"No deployments have been recorded for your sites yet.",serverLogs:f,serverLogsEmptyReason:f.length?void 0:"No recent log entries for your sites.",security:{tlsCertificates:R,ports:[],firewall:null,authEvents:[]},diagnostics:(t.diagnostics??[]).filter((y)=>["Route conflicts","TLS certificates"].includes(y.name)),activity:E}}function w_(t,e){if(e.role==="admin")return t;let n=new Set(sl(e,Object.keys(t.sites??{})));return{project:{name:t.project?.name},environment:t.environment,environments:t.environments,sites:Object.fromEntries(Object.entries(t.sites??{}).filter(([r])=>n.has(r)))}}var tP=new Set(["name","ssl","env","redirects","aliases","domain","path"]),A_={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 y_(t){let e=Object.keys(t).filter((i)=>t[i]!==void 0),n=e.filter((i)=>(i in A_));if(n.length)return{ok:!1,error:`Only the server owner can change ${n.map((c)=>`${c} (${A_[c]})`).join(", ")}.`};let r=e.filter((i)=>!tP.has(i));if(r.length)return{ok:!1,error:`Only the server owner can change ${r.join(", ")}.`};return{ok:!0}}function so(t){return String(t??"").trim().toLowerCase().replace(/\.$/,"")}function D_(t){let e=String(t??"/").trim();if(!e||e==="/")return"/";return(e.startsWith("/")?e:`/${e}`).replace(/\/+$/,"")||"/"}function eP(t){let e=[so(t?.domain)];if(Array.isArray(t?.aliases))e.push(...t.aliases.map(so));return e.filter(Boolean)}function P_({siteName:t,body:e,sites:n,ownSites:r}){let i=n[t]??{},c=new Set(r),d=new Set;if(e.domain!==void 0)d.add(so(e.domain));if(Array.isArray(e.aliases))for(let l of e.aliases)d.add(so(l));if(d.delete(""),d.size===0)return{ok:!0};let a=D_(e.path!==void 0?e.path:i.path);for(let[l,o]of Object.entries(n)){if(l===t||c.has(l))continue;let u=D_(o?.path);for(let f of eP(o)){if(!d.has(f))continue;if(u===a)return{ok:!1,error:`${f}${a==="/"?"":a} is already served by another site on this server.`}}}return{ok:!0}}class rc{maxAttempts;lockoutMs;windowMs;attempts=new Map;constructor(t=8,e=900000,n=900000){this.maxAttempts=t;this.lockoutMs=e;this.windowMs=n}key(t,e){return`${t.trim().toLowerCase()}\x00${e}`}check(t,e,n=Date.now()){let r=this.attempts.get(this.key(t,e));if(!r?.until)return{allowed:!0};if(n>=r.until)return this.attempts.delete(this.key(t,e)),{allowed:!0};return{allowed:!1,retryAfterSeconds:Math.ceil((r.until-n)/1000)}}recordFailure(t,e,n=Date.now()){let r=this.key(t,e),i=this.attempts.get(r),d=!i||n-i.last>this.windowMs?1:i.count+1,a={count:d,last:n};if(d>=this.maxAttempts)a.until=n+this.lockoutMs;this.attempts.set(r,a)}recordSuccess(t,e){this.attempts.delete(this.key(t,e))}prune(t=Date.now()){for(let[e,n]of this.attempts)if(n.until?t>=n.until:t-n.last>this.windowMs)this.attempts.delete(e)}get size(){return this.attempts.size}}var v_=new Set([22,80,443]);function ic(t){return Number.isInteger(t)&&t>=1&&t<=65535}function zr(t){return[...new Set(t.filter((e)=>ic(e)&&!v_.has(e)))].sort((e,n)=>e-n)}function k_(t,e,n=[]){if(!ic(e))throw Error("Port must be an integer between 1 and 65535.");if(v_.has(e))throw Error(`Port ${e} (SSH/HTTP/HTTPS) is always open and is not managed here.`);return O_({configText:t,ports:zr([...n,e])})}function C_(t,e,n=[]){return O_({configText:t,ports:zr(n.filter((r)=>r!==e))})}function $_(t,e,n,r,i){let c=t.slice(e,n),d=new RegExp(`\\b${r}\\s*:\\s*\\${i}`).exec(c);if(!d)return null;let a=e+d.index,l=t.indexOf(i,a);return{propStart:a,open:l,close:$l(t,l,i,i==="{"?"}":"]")}}function Pl(t){return`allowedPorts: [${t.join(", ")}]`}function O_(t){let{configText:e}=t,n=zr(t.ports),r=/\bcompute\s*:\s*{/.exec(e);if(!r)throw Error("Could not find infrastructure.compute in the cloud config.");let i=e.indexOf("{",r.index),c=$l(e,i,"{","}"),d=$_(e,i+1,c,"firewall","{");if(d){let u=$_(e,d.open+1,d.close,"allowedPorts","[");if(u){let y=u.propStart;while(y>0&&e[y-1]!==`
|
|
432
|
-
`&&/\s/.test(e[y-1]))y--;let $=e.slice(y,u.propStart);return`${e.slice(0,y)}${$}${Pl(n)}${e.slice(u.close+1)}`}let f=e.slice(0,d.close).trimEnd(),R=e.slice(d.close),E=f.endsWith(",")||f.endsWith("{")?"":",";return`${f}${E}
|
|
433
|
-
${Pl(n)},
|
|
434
|
-
${R}`}let a=e.slice(0,c).trimEnd(),l=e.slice(c),o=a.endsWith(",")||a.endsWith("{")?"":",";return`${a}${o}
|
|
435
|
-
firewall: {
|
|
436
|
-
enabled: true,
|
|
437
|
-
${Pl(n)},
|
|
438
|
-
},
|
|
439
|
-
${l}`}class vl{client;region;constructor(t="us-east-1"){this.region=t,this.client=new ut}async getTraceSummaries(t){let e={StartTime:Math.floor(t.startTime.getTime()/1000),EndTime:Math.floor(t.endTime.getTime()/1000),TimeRangeType:"Event",Sampling:!1};if(t.filterExpression)e.FilterExpression=t.filterExpression;if(t.nextToken)e.NextToken=t.nextToken;let n=await this.client.request({service:"xray",region:this.region,method:"POST",path:"/TraceSummaries",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return{summaries:n?.TraceSummaries??[],nextToken:n?.NextToken}}async batchGetTraces(t){if(!t.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:t.slice(0,5)})}))?.Traces??[]}}var J_=65536;function ge(t){return t.length<=J_?t:`${t.slice(0,J_)}
|
|
440
|
-
|
|
441
|
-
[output truncated]`}function Bl(t,e){return t.environments?.[e]?.app}function zl(t,e,n){let r=[],i=Bl(t,e);r.push({id:"redeploy",label:"Redeploy current build",group:"deploy",target:"app",mutates:!0,confirm:"redeploy"}),r.push({id:"rollback",label:"Roll back to previous build",group:"deploy",target:"app",mutates:!0,confirm:"rollback",danger:!0});let c=n.maintenance?.enabled;if(c!==!0)r.push({id:"maintenance:on",label:"Enable maintenance mode",group:"maintenance",target:"app",mutates:!0,confirm:"maintenance",danger:!0});if(c!==!1)r.push({id:"maintenance:off",label:"Disable maintenance mode",group:"maintenance",target:"app",mutates:!0,confirm:"live"});if(i?.assets||n.assetsInfo)r.push({id:"assets:invalidate",label:"Invalidate CDN cache",group:"assets",target:"assets",mutates:!0,confirm:"invalidate"});if(i?.database?.connection==="aurora-serverless")r.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 d of n.queues??[]){let a=String(d?.name??"").trim();if(a&&/^[A-Za-z0-9_-]+$/.test(a))r.push({id:`queue:purge:${a}`,label:`Purge queue (${a})`,group:"queue",target:a,mutates:!0,confirm:a,danger:!0})}return r}function j_(t,e,n,r){return zl(e,n,r).find((i)=>i.id===t)}async function nP(t,e,n){try{let r=new T_(n),{Stacks:i}=await r.describeStacks({stackName:B_(t,e)}),c={};for(let l of i?.[0]?.Outputs??[])if(l.OutputKey)c[l.OutputKey]=l.OutputValue??"";let d=c.AssetsCdnDomain;if(!d)return null;return(await new Jl(n).findDistributionByDomain(d))?.Id??null}catch{return null}}async function H_(t,e,n,r={}){try{if(n.id==="redeploy")return await b_(t,e),{operation:n.id,command:"serverless redeploy",ok:!0,stdout:"Redeploy complete."};if(n.id==="rollback")return await W_(t,e),{operation:n.id,command:"serverless rollback",ok:!0,stdout:"Rollback complete."};if(n.id==="maintenance:on")return await kl(t,e,!0),{operation:n.id,command:"maintenance on",ok:!0,stdout:"Application is now in maintenance mode."};if(n.id==="maintenance:off")return await kl(t,e,!1),{operation:n.id,command:"maintenance off",ok:!0,stdout:"Application is live."};if(n.id==="db:scale"){let i=Number(r.min),c=Number(r.max);if(!Number.isFinite(i)||!Number.isFinite(c)||i<=0||c<i)return{operation:n.id,ok:!1,error:"Provide valid Aurora capacities (0 < min ≤ max)."};return await U_(t,e,i,c),{operation:n.id,command:`db:scale ${i}-${c} ACU`,ok:!0,stdout:`Scaling applied (${i}-${c} ACUs); takes effect shortly.`}}if(n.id==="assets:invalidate"){let i=await le(t,e),c=await nP(t,e,i.region);if(!c)return{operation:n.id,ok:!1,error:"Could not resolve the asset CloudFront distribution for this environment."};let a=await new Jl(i.region).invalidateAll(c);return{operation:n.id,command:`cloudfront invalidate ${c} /*`,ok:!0,stdout:`Invalidation ${a?.Id??"created"} for ${c} (/*).`}}if(n.group==="queue"&&n.id.startsWith("queue:purge:")){let i=n.target,c=await le(t,e),d=new dc(c.region),a=`${c.slug}-${e}-${i}`,{QueueUrl:l}=await d.getQueueUrl(a);return await d.purgeQueue(l),{operation:n.id,command:`sqs purge ${a}`,ok:!0,stdout:`Purged queue ${a}.`}}return{operation:n.id,ok:!1,error:"Unknown or unavailable serverless operation."}}catch(i){return{operation:n.id,ok:!1,error:ge(i?.message??String(i))}}}async function L_(t,e,n){let r=n.trim();if(!r)return{operation:"command",ok:!1,error:"A command is required."};try{let i=await Ol(t,e,r);return{operation:"command",command:r,ok:!0,stdout:ge(i||"(no output)")}}catch(i){return{operation:"command",command:r,ok:!1,error:ge(i?.message??String(i))}}}var Tl="No dead-letter queue is provisioned for this environment.";async function bl(t,e,n){try{let{QueueUrl:r}=await t.getQueueUrl(`${e}-${n}-dlq`);return r}catch{return null}}async function F_(t,e,n=10){try{let r=await le(t,e),i=new dc(r.region),c=await bl(i,r.slug,e);if(!c)return{ok:!1,messages:[],error:Tl};return{ok:!0,messages:((await i.receiveMessages({queueUrl:c,maxMessages:Math.min(10,Math.max(1,n)),waitTimeSeconds:1,visibilityTimeout:2})).Messages??[]).map((l)=>({id:l.MessageId,receiptHandle:l.ReceiptHandle,body:ge(String(l.Body??""))}))}}catch(r){return{ok:!1,messages:[],error:ge(r?.message??String(r))}}}async function V_(t,e,n={}){try{let r=await le(t,e),i=Bl(t,e),d=(i?z_(i,r.slug,e):[]).map((E)=>E.name.replace(`${r.slug}-${e}-`,"")),a=n.targetQueue&&d.includes(n.targetQueue)?n.targetQueue:d[0];if(!a)return{operation:"dlq:redrive",ok:!1,error:"No source queue is configured to redrive into."};let l=new dc(r.region),o=await bl(l,r.slug,e);if(!o)return{operation:"dlq:redrive",ok:!1,error:Tl};let{QueueUrl:u}=await l.getQueueUrl(`${r.slug}-${e}-${a}`),f=Math.min(50,Math.max(1,n.max??10)),R=0;while(R<f){let y=(await l.receiveMessages({queueUrl:o,maxMessages:Math.min(10,f-R),waitTimeSeconds:1,visibilityTimeout:30})).Messages??[];if(!y.length)break;for(let $ of y)await l.sendMessage({queueUrl:u,messageBody:String($.Body??"")}),await l.deleteMessage(o,$.ReceiptHandle),R++}return{operation:"dlq:redrive",command:`redrive → ${a}`,ok:!0,stdout:`Moved ${R} message(s) from the DLQ to ${a}.`}}catch(r){return{operation:"dlq:redrive",ok:!1,error:ge(r?.message??String(r))}}}async function N_(t,e){try{let n=await le(t,e),r=new dc(n.region),i=await bl(r,n.slug,e);if(!i)return{operation:"dlq:purge",ok:!1,error:Tl};return await r.purgeQueue(i),{operation:"dlq:purge",command:"sqs purge dlq",ok:!0,stdout:"Dead-letter queue purged."}}catch(n){return{operation:"dlq:purge",ok:!1,error:ge(n?.message??String(n))}}}function x_(t,e){let n=Bl(t,e);if(!n?.secrets)return[];return Array.isArray(n.secrets)?n.secrets.map((r)=>({key:r.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),secretId:r})):Object.entries(n.secrets).map(([r,i])=>({key:r,secretId:String(i)}))}async function M_(t,e,n,r){if(!n.trim())return{operation:"secret:set",ok:!1,error:"A secret id is required."};try{let i=await le(t,e),c=new cc(i.region);try{await c.putSecretValue({SecretId:n,SecretString:r})}catch{await c.createSecret({Name:n,SecretString:r})}return{operation:"secret:set",command:`secret set ${n}`,ok:!0,stdout:`Secret ${n} updated. Redeploy to apply it to the functions.`}}catch(i){return{operation:"secret:set",ok:!1,error:ge(i?.message??String(i))}}}async function Q_(t,e,n){if(!n.trim())return{operation:"secret:delete",ok:!1,error:"A secret id is required."};try{let r=await le(t,e);return await new cc(r.region).deleteSecret({SecretId:n,RecoveryWindowInDays:7}),{operation:"secret:delete",command:`secret delete ${n}`,ok:!0,stdout:`Secret ${n} scheduled for deletion (recoverable for 7 days).`}}catch(r){return{operation:"secret:delete",ok:!1,error:ge(r?.message??String(r))}}}var rP=new Set(["http","queue","cli"]);async function G_(t,e,n,r){if(!rP.has(n))return{operation:"function:config",ok:!1,error:`Unknown function mode '${n}'.`};let i=r.memory==null?void 0:Number(r.memory),c=r.timeout==null?void 0:Number(r.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(c!=null&&(!Number.isInteger(c)||c<1||c>900))return{operation:"function:config",ok:!1,error:"Timeout must be an integer between 1 and 900 seconds."};if(i==null&&c==null)return{operation:"function:config",ok:!1,error:"Provide a memory and/or timeout value."};try{let d=await le(t,e),a=new Fd(d.region),l=`${d.slug}-${e}-${n}`;await a.updateFunctionConfiguration({FunctionName:l,...i!=null?{MemorySize:i}:{},...c!=null?{Timeout:c}:{}});let o=[i!=null?`${i} MB`:"",c!=null?`${c}s`:""].filter(Boolean).join(", ");return{operation:"function:config",command:`update ${l} (${o})`,ok:!0,stdout:`Updated ${l}: ${o}.`}}catch(d){return{operation:"function:config",ok:!1,error:ge(d?.message??String(d))}}}var Cl=[{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 iP(t){return Cl.find((e)=>e.key===t)}async function Z_(t,e){try{let n=await le(t,e);return{ok:!0,alarms:await new Ai(n.region).describeAlarms({AlarmNamePrefix:`${n.slug}-${e}-`,MaxRecords:100}),presets:Cl}}catch(n){return{ok:!1,alarms:[],presets:Cl,error:ge(n?.message??String(n))}}}async function Y_(t,e,n,r){let i=iP(n);if(!i)return{operation:"alarm:create",ok:!1,error:`Unknown alarm metric '${n}'.`};if(!Number.isFinite(r)||r<0)return{operation:"alarm:create",ok:!1,error:"Provide a non-negative threshold."};try{let c=await le(t,e),d=new Ai(c.region),a=`${c.slug}-${e}-${i.key}`,l=i.fnMode?[{Name:"FunctionName",Value:`${c.slug}-${e}-${i.fnMode}`}]:[];return await d.putMetricAlarm({AlarmName:a,Namespace:i.namespace,MetricName:i.metricName,ComparisonOperator:i.comparison,Threshold:r,EvaluationPeriods:1,Period:300,Statistic:i.statistic,Dimensions:l,AlarmDescription:`ts-cloud: ${i.label} > ${r} ${i.unit}`}),{operation:"alarm:create",command:`alarm ${a}`,ok:!0,stdout:`Alarm ${a} armed at ${r} ${i.unit}.`}}catch(c){return{operation:"alarm:create",ok:!1,error:ge(c?.message??String(c))}}}async function X_(t,e,n){try{let r=await le(t,e);if(!n.startsWith(`${r.slug}-${e}-`))return{operation:"alarm:delete",ok:!1,error:"Refusing to delete an alarm outside this environment."};return await new Ai(r.region).deleteAlarms([n]),{operation:"alarm:delete",command:`delete alarm ${n}`,ok:!0,stdout:`Alarm ${n} deleted.`}}catch(r){return{operation:"alarm:delete",ok:!1,error:ge(r?.message??String(r))}}}function cP(t){let e=t.HasFault?"fault":t.HasError?"error":t.HasThrottle?"throttle":"ok";return{id:String(t.Id??""),timestamp:Number.isFinite(Number(t.StartTime))?new Date(Number(t.StartTime)*1000).toISOString():void 0,durationMs:Math.round((t.Duration??0)*1000),responseMs:Math.round((t.ResponseTime??0)*1000),status:e,method:t.Http?.HttpMethod??"-",url:t.Http?.HttpURL??"-",httpStatus:t.Http?.HttpStatus??0}}async function lo(t,e,n=30){try{let r=await le(t,e),i=new vl(r.region),c=new Date,d=new Date(c.getTime()-Math.min(360,Math.max(1,n))*60000),a=`${r.slug}-${e}-http`,l=await i.getTraceSummaries({startTime:d,endTime:c,filterExpression:`service("${a}")`});if(!l.summaries.length)l=await i.getTraceSummaries({startTime:d,endTime:c});return{ok:!0,traces:l.summaries.slice(0,100).map(cP)}}catch(r){return{ok:!1,traces:[],error:ge(r?.message??String(r))}}}async function Wl(t,e,n){try{let r=await le(t,e),i=`${r.slug}-${e}-scheduler`;if(n==="run"){let d=await Ol(t,e,"schedule:run");return{operation:"scheduler:run",command:"schedule:run",ok:!0,stdout:ge(d||"Scheduler run triggered.")}}let c=new Ys(r.region);if(n==="enable")await c.enableRule({Name:i});else await c.disableRule({Name:i});return{operation:`scheduler:${n}`,command:`${n} ${i}`,ok:!0,stdout:`Scheduler rule ${i} ${n}d.`}}catch(r){return{operation:`scheduler:${n}`,ok:!1,error:ge(r?.message??String(r))}}}function K_(t){let e=go(t.name),n=jl(t.configText);if(aP(t.configText,n.start,n.end,e))throw Error(`Site '${e}' already exists in cloud.config.ts`);let r=oP({...t,name:e}),i=t.configText.slice(0,n.end).trimEnd(),c=t.configText.slice(n.end),d=i.endsWith("{")?`
|
|
442
|
-
`:i.endsWith(",")?`
|
|
443
|
-
|
|
444
|
-
`:`,
|
|
445
|
-
|
|
446
|
-
`;return`${i}${d}${r}
|
|
447
|
-
${c}`}function p_(t){let e=go(t.name),n=jl(t.configText),r=iR(t.configText,n.start,n.end,e);if(!r)throw Error(`Site '${e}' does not exist in cloud.config.ts`);let i=t.configText,c=r.nameStart;while(c>0&&i[c-1]!==`
|
|
448
|
-
`&&/\s/.test(i[c-1]))c--;let d=r.end+1;if(i[d]===",")d++;while(d<i.length&&i[d]!==`
|
|
449
|
-
`&&/\s/.test(i[d]))d++;if(i[d]===`
|
|
450
|
-
`)d++;return i.slice(0,c)+i.slice(d)}function m_(t){let e=go(t.siteName);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t.key))throw Error(`Invalid property key '${t.key}'`);let n=jl(t.configText),r=iR(t.configText,n.start,n.end,e);if(!r)throw Error(`Site '${e}' does not exist in cloud.config.ts`);let i=t.configText,c=i.indexOf("{",r.nameStart),d=r.end,a=i.slice(c+1,d),l=new RegExp(`(^|[\\s,{])(${Hl(t.key)})\\s*:`,"m").exec(a);if(l){let f=c+1+l.index+l[1].length,R=i.indexOf(":",f),E=dP(i,R+1,d);return`${i.slice(0,f)}${t.key}: ${t.valueText}${i.slice(E)}`}let o=i.slice(0,d).trimEnd(),u=o.endsWith("{")||o.endsWith(",")?"":",";return`${o}${u}
|
|
451
|
-
${t.key}: ${t.valueText},
|
|
452
|
-
${i.slice(d)}`}function q_(t){if(t===!1)return"false";if(t===!0)return"true";return`{ provider: '${nr(t.provider||"letsencrypt")}' }`}function tR(t){return`'${nr(t)}'`}function eR(t){let e=Object.entries(t).filter(([n])=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(n));if(e.length===0)return"{}";return`{
|
|
453
|
-
${e.map(([n,r])=>` ${n}: '${nr(String(r))}',`).join(`
|
|
454
|
-
`)}
|
|
455
|
-
}`}function Ul(t){return/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/i.test(t.trim())}function nR(t){let e=[...new Set(t.map((n)=>n.trim().toLowerCase()).filter(Boolean))];for(let n of e)if(!Ul(n))throw Error(`Alias '${n}' is not a valid hostname.`);if(e.length===0)return"[]";return`[${e.map((n)=>`'${nr(n)}'`).join(", ")}]`}function rR(t){let e=Object.entries(t).map(([n,r])=>[n.trim(),String(r).trim()]).filter(([n,r])=>n&&r);if(e.length===0)return"{}";return`{
|
|
456
|
-
${e.map(([n,r])=>` '${nr(n)}': '${nr(r)}',`).join(`
|
|
457
|
-
`)}
|
|
458
|
-
}`}function dP(t,e,n){let r=e;while(r<n&&/\s/.test(t[r]))r++;let i=0,c,d=!1;for(;r<n;r++){let a=t[r];if(c){if(d){d=!1;continue}if(a==="\\"){d=!0;continue}if(a===c)c=void 0;continue}if(a==='"'||a==="'"||a==="`"){c=a;continue}if(a==="{"||a==="["||a==="("){i++;continue}if(a==="}"||a==="]"||a===")"){if(i===0)return r;i--;continue}if(a===","&&i===0)return r}return n}function iR(t,e,n,r){let i=t.slice(e+1,n),c=new RegExp(`(^|[\\s,{])(${Hl(r)})\\s*:\\s*\\{`,"m").exec(i);if(!c)return null;let d=e+1+c.index+c[1].length,a=t.indexOf("{",d);return{nameStart:d,end:cR(t,a)}}function oP(t){let n=[` ${go(t.name)}: {`];if(er(n,"deploy",t.deploy),er(n,"root",t.root),er(n,"path",t.path),er(n,"domain",t.domain),er(n,"type",t.type),er(n,"build",t.build),er(n,"start",t.start),t.port!==void 0)n.push(` port: ${t.port},`);if(er(n,"pathRewriteStyle",t.pathRewriteStyle),t.ssl!==void 0)if(t.ssl===!1)n.push(" ssl: false,");else if(t.ssl===!0)n.push(" ssl: true,");else n.push(` ssl: { provider: '${nr(t.ssl.provider||"letsencrypt")}' },`);if(t.env&&Object.keys(t.env).length>0){n.push(" env: {");for(let[r,i]of Object.entries(t.env)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))continue;n.push(` ${r}: '${nr(String(i))}',`)}n.push(" },")}return n.push(" },"),n.join(`
|
|
459
|
-
`)}function nr(t){return t.replace(/\\/g,"\\\\").replaceAll(String.fromCharCode(39),"\\'").replace(/\r/g,"\\r").replace(/\n/g,"\\n")}function go(t){let e=t.trim();if(!/^[A-Za-z_$][\w$]*$/.test(e))throw Error(`Invalid site name '${t}'. Use a valid JavaScript object key, e.g. docs or marketingSite.`);return e}function er(t,e,n){if(n===void 0||n==="")return;let r=n.replace(/\\/g,"\\\\").replaceAll(String.fromCharCode(39),"\\'");t.push(` ${e}: '${r}',`)}function jl(t){let e=/\bsites\s*:\s*{/g.exec(t);if(!e)throw Error("Could not find a top-level sites: { ... } block in cloud.config.ts");let n=t.indexOf("{",e.index),r=cR(t,n);return{start:n,end:r}}function aP(t,e,n,r){let i=t.slice(e+1,n);return new RegExp(`(^|[\\s,{])${Hl(r)}\\s*:`,"m").test(i)}function Hl(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function cR(t,e){let n=0,r,i=!1,c=!1,d=!1;for(let a=e;a<t.length;a++){let l=t[a],o=t[a+1];if(c){if(l===`
|
|
460
|
-
`)c=!1;continue}if(d){if(l==="*"&&o==="/")d=!1,a++;continue}if(r){if(i){i=!1;continue}if(l==="\\"){i=!0;continue}if(l===r)r=void 0;continue}if(l==="/"&&o==="/"){c=!0,a++;continue}if(l==="/"&&o==="*"){d=!0,a++;continue}if(l==='"'||l==="'"||l==="`"){r=l;continue}if(l==="{")n++;if(l==="}"){if(n--,n===0)return a}}throw Error("Could not find the closing brace for sites: { ... } in cloud.config.ts")}function dR(t,e,n){let r=(Array.isArray(n)?n:String(n??"").split(",")).map(String).filter(Boolean);if(!r.length){if(e)return;let c=t.map((d)=>d.id);return c.length?c:["__no_authorized_telemetry_resources__"]}let i=r.map((c)=>t.find((d)=>d.id===c||d.slug===c)?.id).filter((c)=>!!c);if(i.length!==r.length)throw Error("One or more telemetry resources are outside your authorized scope.");return[...new Set(i)]}import{createHash as lR}from"node:crypto";function rr(t){let e=Number(t);return Number.isFinite(e)&&e>=0?e:null}function sP(t){if(!/^\d{4}-\d{2}-\d{2}$/.test(t))return null;let e=Date.parse(`${t}T12:00:00.000Z`);return Number.isFinite(e)?new Date(e).toISOString():null}function lP(t,e){if(!t||typeof t!=="object")return[];let n={source:e.name},r=[],i=e.now,c=(o,u,f,R=i)=>{if(u!==null)r.push({name:o,value:u,unit:f,timestamp:R,attributes:n})};c("storage.egress.month",rr(t.monthBytes),"bytes"),c("storage.egress.today",rr(t.todayBytes),"bytes"),c("storage.egress.projected_month",rr(t.projectedMonthBytes),"bytes");let d=rr(t.budgetBytes);if(d!==null&&d>0){c("storage.egress.budget",d,"bytes");let o=t.budgetUsedPercent,u=typeof o==="number"&&Number.isFinite(o)?o:rr(t.monthBytes)!==null?Math.round(rr(t.monthBytes)/d*1000)/10:null;c("storage.egress.budget_used_percent",u,"percent")}let a=e.maxReplayDays??45,l=Array.isArray(t.days)?t.days.slice(-a):[];for(let o of l){let u=sP(String(o?.date??"")),f=rr(o?.bytes);if(!u||f===null)continue;r.push({name:"storage.egress.day",value:f,unit:"bytes",timestamp:u,attributes:n});let R=rr(o?.downloads);if(R!==null)r.push({name:"storage.egress.day_downloads",value:R,unit:"count",timestamp:u,attributes:n})}return r}async function gP(t,e=process.env,n=fetch){let r=t.tokenEnv?e[t.tokenEnv]:void 0,i=await n(t.url,{headers:r?{Authorization:`Bearer ${r}`}:{},signal:AbortSignal.timeout(1e4)});if(!i.ok)throw Error(`HTTP ${i.status}`);return await i.json()}async function oR(t,e){let n=[],r=[];if(!Array.isArray(t)||t.length===0)return{metrics:n,errors:r};let i=await Promise.all(t.map(async(c)=>{if(!c?.name||!c?.url)return{endpoint:c,error:"egress endpoint needs both a name and a url"};try{let d=await gP(c,e.env,e.fetchImpl);return{endpoint:c,report:d}}catch(d){return{endpoint:c,error:d instanceof Error?d.message:String(d)}}}));for(let c of i){let d=`egress:${c.endpoint?.name??"unnamed"}`;if("error"in c&&c.error){r.push({source:d,message:c.error});continue}n.push(...lP(c.report,{name:c.endpoint.name,now:e.now}))}return{metrics:n,errors:r}}class gR{now;entries=new Map;constructor(t=Date.now){this.now=t}async getOrCreate(t,e,n,r){let i=this.entries.get(t);if(!n&&i&&i.expiresAt>this.now())return{value:await i.promise,cached:!0};let c=r().catch((d)=>{throw this.entries.delete(t),d});return this.entries.set(t,{expiresAt:this.now()+e,promise:c}),{value:await c,cached:!1}}invalidate(t){for(let e of this.entries.keys())if(e.startsWith(t))this.entries.delete(e)}}class uR{now;lastRun=new Map;constructor(t=Date.now){this.now=t}shouldRun(t,e,n=!1){let r=this.now(),i=this.lastRun.get(t);if(!n&&i!=null&&r-i<e)return!1;return this.lastRun.set(t,r),!0}}var hR=new gR,uP=new uR,hP=2000,SP=3600000;function fP(t,e){if(t.kind==="log"&&!e.collectLogs)return!1;if(t.kind==="trace"&&!e.collectTraces)return!1;if((t.kind==="request"||t.name.startsWith("request."))&&!e.collectRequestAnalytics)return!1;if(!["log","trace","request"].includes(t.kind)&&!t.name.startsWith("request."))return!0;let n=t.requestId??t.traceId??`${t.source}\x00${t.workloadId??""}\x00${t.timestamp}`;return Number.parseInt(lR("sha256").update(n).digest("hex").slice(0,8),16)/4294967295<=e.samplingRate}function ue(...t){return`telemetry:${lR("sha256").update(t.map((e)=>String(e??"")).join("\x00")).digest("hex").slice(0,40)}`}function oc(t,e,n,r){if(!r)return;return t.listResources(e,n).find((i)=>i.slug===r)?.id}function _P(t,e){let n=String(e??"").toLowerCase();if(["debug","info","warn","warning","error","fatal"].includes(n))return n==="fatal"?"error":n;return/fatal|panic|exception|error/i.test(t)?"error":/warn|timeout|throttl|retr(?:y|ies)/i.test(t)?"warning":"info"}function aR(t){let e=t.timestamp&&Number.isFinite(new Date(t.timestamp).getTime())?new Date(t.timestamp).toISOString():new Date().toISOString(),n={};try{let $=JSON.parse(t.message);if($&&typeof $==="object"&&!Array.isArray($))n=$}catch{}let r=Object.fromEntries(Object.entries(n).filter(([$])=>!/^(?:body|requestBody|responseBody|headers|authorization|cookie|cookies|query|queryString)$/i.test($))),i=String(n.requestId??n.request_id??n["x-request-id"]??"")||void 0,c=String(n.traceId??n.trace_id??n["x-amzn-trace-id"]??"")||void 0,d=Number(n.durationMs??n.duration_ms??n.latencyMs??n.latency_ms),a=Number(n.statusCode??n.status_code??n.status),l=String(n.method??n.httpMethod??"")||void 0,o=sR(String(n.pathTemplate??n.path??n.url??"")||void 0),u=String(n.releaseId??n.release_id??"")||void 0,f=String(n.deploymentId??n.deployment_id??"")||void 0,R={projectId:t.projectId,environmentId:t.environmentId,resourceId:t.resourceId,source:t.source,timestamp:e,requestId:i,traceId:c,releaseId:u,deploymentId:f,workloadId:t.workloadId},E=Object.keys(n).length?JSON.stringify(r):t.message,y=[{...R,id:ue(t.source,t.name,e,E),kind:"log",name:t.name,level:_P(E,n.level),message:E,attributes:r}];if(l&&o&&Number.isFinite(a)){if(y.push({...R,id:ue("request",i,e,l,o,a),kind:"request",name:"http.request",method:l,pathTemplate:o,host:n.host,statusCode:a,durationMs:Number.isFinite(d)?d:void 0,bytesIn:Number(n.bytesIn)||void 0,bytesOut:Number(n.bytesOut)||void 0,region:n.region,cacheResult:n.cacheResult??n.cache,upstream:n.upstream,attributes:{userAgentFamily:n.userAgentFamily??"",protocol:n.protocol??""}}),Number.isFinite(d))y.push({...R,id:ue("request-duration",i,e),kind:"metric",name:"request.duration",value:d,unit:"ms",attributes:{method:l,pathTemplate:o,statusCode:a}});if(y.push({...R,id:ue("request-count",i,e),kind:"metric",name:"request.count",value:1,unit:"count",attributes:{method:l,pathTemplate:o,statusCode:a}}),a>=500)y.push({...R,id:ue("request-error",i,e),kind:"metric",name:"request.error",value:1,unit:"count",attributes:{method:l,pathTemplate:o,statusCode:a}})}return y}async function RP(t){let e=new uo(t.controlPlane),n=ac(t.controlPlane,t.projectId),r=new Date,i=[],c=[],d={projectId:t.projectId,environmentId:t.environmentId},a=On(t.config);try{let R=(a==="serverless"?await ho(t.config,t.environment):await So(t.config,t.environment,{includeSiteHealth:t.includeSiteHealth,telemetryOnly:t.lightweight}))??{};if(a==="serverless"){for(let y of R.functionsDetail??[]){let $=oc(t.controlPlane,t.projectId,t.environmentId,y.key),C={...d,resourceId:$,source:"cloudwatch",timestamp:r.toISOString(),workloadId:y.name,attributes:{provider:"aws",functionName:y.name,aggregationWindow:"24h"}};for(let[J,H,O]of[["snapshot.traffic.requests_24h",y.invocations,"count"],["snapshot.errors.count_24h",y.errors,"count"],["snapshot.latency.p50_24h",y.p50,"ms"],["snapshot.latency.p95_24h",y.p95,"ms"],["snapshot.latency.p99_24h",y.p99,"ms"],["snapshot.saturation.throttles_24h",y.throttles,"count"],["snapshot.memory.max_24h",y.maxMem,"MB"]])if(Number.isFinite(Number(H)))i.push({...C,id:ue("cloudwatch",y.name,J,r.toISOString()),kind:"metric",name:J,value:Number(H),unit:O})}try{let y=await le(t.config,t.environment),$=new Ai(y.region),C=new Date(r.getTime()-3600000),J=300;for(let H of y.functions){let O=[{Name:"FunctionName",Value:H.name}],[Y,dt,m,Ut,st]=await Promise.all([$.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:O,StartTime:C,EndTime:r,Period:300,Statistics:["Sum"]}),$.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"Errors",Dimensions:O,StartTime:C,EndTime:r,Period:300,Statistics:["Sum"]}),$.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"Duration",Dimensions:O,StartTime:C,EndTime:r,Period:300,ExtendedStatistics:["p50","p95","p99"]}),$.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"Throttles",Dimensions:O,StartTime:C,EndTime:r,Period:300,Statistics:["Sum"]}),$.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"ConcurrentExecutions",Dimensions:O,StartTime:C,EndTime:r,Period:300,Statistics:["Maximum"]})]),Q=oc(t.controlPlane,t.projectId,t.environmentId,H.mode),rt=(Dt,Ke,bn,Le)=>{for(let pe of Dt){let me=pe.Timestamp&&Number.isFinite(new Date(pe.Timestamp).getTime())?new Date(pe.Timestamp).toISOString():void 0,qe=bn(pe);if(me&&qe!=null&&Number.isFinite(qe))i.push({...d,resourceId:Q,id:ue("cloudwatch-series",H.name,Ke,me),kind:"metric",source:"cloudwatch",name:Ke,timestamp:me,value:qe,unit:Le,workloadId:H.name,region:y.region,attributes:{provider:"aws",functionName:H.name,aggregationWindow:"300s"}})}};rt(Y,"traffic.requests",(Dt)=>Dt.Sum,"count"),rt(dt,"errors.count",(Dt)=>Dt.Sum,"count"),rt(m,"latency.p50",(Dt)=>Dt.Percentiles?.p50,"ms"),rt(m,"latency.p95",(Dt)=>Dt.Percentiles?.p95,"ms"),rt(m,"latency.p99",(Dt)=>Dt.Percentiles?.p99,"ms"),rt(Ut,"saturation.throttles",(Dt)=>Dt.Sum,"count"),rt(st,"saturation.concurrency",(Dt)=>Dt.Maximum,"count")}}catch(y){c.push({source:"cloudwatch:series",message:y instanceof Error?y.message:String(y)})}for(let y of(R.serverlessLogs??[]).slice(0,hP))i.push(...aR({...d,source:`cloudwatch:${y.source}`,name:`${y.source}.log`,timestamp:y.timestamp,message:String(y.message),resourceId:oc(t.controlPlane,t.projectId,t.environmentId,y.source)}));for(let y of R.queuesDetail??[]){let $={...d,source:"cloudwatch",timestamp:r.toISOString(),attributes:{queue:y.name}};i.push({...$,id:ue("queue-depth",y.name,r.toISOString()),kind:"metric",name:"queue.depth",value:Number(y.visible??y.depth??0),unit:"count"}),i.push({...$,id:ue("queue-inflight",y.name,r.toISOString()),kind:"metric",name:"queue.inflight",value:Number(y.inFlight??0),unit:"count"})}let E=await lo(t.config,t.environment,30);if(!E.ok)c.push({source:"xray",message:E.error??"X-Ray traces are unavailable."});for(let y of E.traces)i.push({...d,id:ue("xray",y.id),kind:"trace",source:"xray",name:"http.trace",timestamp:y.timestamp??r.toISOString(),traceId:y.id,durationMs:y.durationMs,statusCode:y.httpStatus,method:y.method,pathTemplate:y.url,attributes:{status:y.status,responseMs:y.responseMs}})}else{let E=R.systemMetrics;if(R.metricsUnavailable||!E)c.push({source:"host",message:"The host metrics probe is unavailable."});else{let y=Number(E.memTotalMb)>0?Number(E.memUsedMb)/Number(E.memTotalMb)*100:0,$=Number(E.swapTotalMb)>0?Number(E.swapUsedMb)/Number(E.swapTotalMb)*100:0,C=[["host.load",Number(E.load),"load"],["host.load.5m",Number(E.load5),"load"],["host.load.15m",Number(E.load15),"load"],["host.cpu.capacity",Number(E.cpus),"count"],["host.cpu.used_percent",Number(E.cpuUsedPct),"percent"],["host.memory.used",Number(E.memUsedMb)*1024*1024,"bytes"],["host.memory.total",Number(E.memTotalMb)*1024*1024,"bytes"],["host.memory.available",Number(E.memAvailableMb)*1024*1024,"bytes"],["host.memory.cache",Number(E.memCacheMb)*1024*1024,"bytes"],["host.memory.used_percent",y,"percent"],["host.swap.used",Number(E.swapUsedMb)*1024*1024,"bytes"],["host.swap.total",Number(E.swapTotalMb)*1024*1024,"bytes"],["host.swap.used_percent",$,"percent"],["host.disk.used_percent",Number(E.diskUsedPct),"percent"],["host.disk.used",Number(E.diskUsedGb)*1073741824,"bytes"],["host.disk.total",Number(E.diskTotalGb)*1073741824,"bytes"],["host.disk.inode_used_percent",Number(E.inodeUsedPct),"percent"],["host.network.rx",Number(E.networkRxBytes),"bytes"],["host.network.tx",Number(E.networkTxBytes),"bytes"],["host.network.rx_rate",Number(E.networkRxBytesPerSec),"bytes_per_second"],["host.network.tx_rate",Number(E.networkTxBytesPerSec),"bytes_per_second"],["host.network.rx_today",Number(E.networkRxBytesToday),"bytes"],["host.network.tx_today",Number(E.networkTxBytesToday),"bytes"],["host.network.rx_month",Number(E.networkRxBytesMonth),"bytes"],["host.network.tx_month",Number(E.networkTxBytesMonth),"bytes"],["host.processes",Number(E.processes),"count"],["host.uptime",Number(E.uptimeSeconds),"seconds"]];for(let[J,H,O]of C)if(Number.isFinite(H))i.push({...d,id:ue("host",J,r.toISOString()),kind:"metric",source:"host",name:J,timestamp:r.toISOString(),value:H,unit:O});for(let J of R.siteHealth??[]){let H=String(J.project??t.config.project.slug),O=String(J.name),Y=O.startsWith(`${H}:`)?O.slice(H.length+1):O,dt=`site:${H}:${Y}`,m=oc(t.controlPlane,t.projectId,t.environmentId,O),Ut={...d,resourceId:m,source:dt,timestamp:J.checkedAt||r.toISOString(),host:J.route,attributes:{project:H,site:Y,route:String(J.route),status:String(J.status)}},st=[["site.health.up",J.status==="live"?1:0,"boolean"],["site.http.status",Number(J.httpStatus),"status"],["site.response.time",Number(J.responseMs),"ms"]];if(J.tlsDaysRemaining!=null)st.push(["site.tls.days_remaining",Number(J.tlsDaysRemaining),"days"]);for(let[Q,rt,Dt]of st)if(Number.isFinite(rt))i.push({...Ut,id:ue(dt,Q,Ut.timestamp),kind:"metric",name:Q,value:rt,unit:Dt})}}}}catch(R){c.push({source:a==="serverless"?"aws":"host",message:R instanceof Error?R.message:String(R)})}{let R=t.config.infrastructure?.compute?.monitoring,E=typeof R==="object"?R?.egressEndpoints:void 0,y=await oR(E,{now:r.toISOString()});c.push(...y.errors);for(let $ of y.metrics)i.push({...d,id:ue($.attributes.source,$.name,$.timestamp),kind:"metric",source:`egress:${$.attributes.source}`,name:$.name,timestamp:$.timestamp,value:$.value,unit:$.unit,attributes:$.attributes})}if(!t.lightweight)try{let R=await Ge(t.config,t.environment),E=new an(t.config,t.environment,{inventory:async()=>R});for(let y of R.workloads){let $=oc(t.controlPlane,t.projectId,t.environmentId,y.links.service),C={...d,resourceId:$,source:`runtime:${y.provider}`,timestamp:r.toISOString(),workloadId:y.id,releaseId:y.links.release,attributes:{status:y.status,provider:y.provider,service:y.links.service??""}};if(i.push({...C,id:ue(y.id,"health",r.toISOString()),kind:"metric",name:"health.up",value:y.status==="running"?1:0,unit:"boolean"}),i.push({...C,id:ue(y.id,"restarts",r.toISOString()),kind:"metric",name:"saturation.restarts",value:y.restartCount??0,unit:"count"}),y.resources?.memoryBytes!=null)i.push({...C,id:ue(y.id,"memory",r.toISOString()),kind:"metric",name:"runtime.memory.used",value:y.resources.memoryBytes,unit:"bytes"});if(!y.capabilities.logs.supported)continue;try{let J=await E.logs(y.id,{limit:100,since:new Date(r.getTime()-300000)});for(let H of J.lines)i.push(...aR({...d,resourceId:$,source:`runtime:${y.provider}`,name:`${y.links.service??y.name}.log`,timestamp:H.timestamp,message:H.message,workloadId:y.id}))}catch(J){c.push({source:`runtime:${y.provider}`,message:J instanceof Error?J.message:String(J)})}}for(let y of R.sources.filter(($)=>$.status!=="fresh"))c.push({source:y.id,message:y.message??`Runtime source is ${y.status}.`})}catch(R){c.push({source:"runtime",message:R instanceof Error?R.message:String(R)})}if(!t.lightweight)for(let R of t.controlPlane.listEvents({projectId:t.projectId,limit:1000})){let E=R.payload;i.push({...d,id:`telemetry:event:${R.id}`,resourceId:R.resourceId,kind:"event",source:"control-plane",name:R.type,timestamp:R.createdAt,level:R.level,message:R.type,deploymentId:R.operationId,releaseId:typeof E.releaseId==="string"?E.releaseId:void 0,traceId:R.correlationId,attributes:E})}let l=i.filter((R)=>fP(R,n)).map((R)=>({...R,sampled:n.samplingRate<1&&(R.kind==="log"||R.kind==="trace"||R.kind==="request"||R.name.startsWith("request."))})),o=e.appendMany(l).length;if(uP.shouldRun(t.projectId,SP,!t.lightweight))e.enforceRetention(n,t.projectId);let u=e.status(t.projectId,t.environmentId,n.rawDays,n.samplingRate);for(let R of c)if(!u.some((E)=>E.source===R.source))u.push({source:R.source,freshness:"unavailable",samplingRate:n.samplingRate,retentionDays:n.rawDays,estimatedDailyBytes:0,message:R.message});let f=r.toISOString();return t.controlPlane.setSetting(`telemetry.collection:${t.projectId}:${t.environmentId??"all"}`,{generatedAt:f,errors:c,statuses:u,policy:n}),{collected:o,cached:!1,generatedAt:f,statuses:u,errors:c,policy:n}}async function Ll(t){let n=`${`${t.projectId}:${t.environmentId??"all"}:${t.environment}`}:${t.lightweight?"lightweight":"full"}`,r=On(t.config)==="serverless"?300000:60000,i=await hR.getOrCreate(n,r,!!t.force,()=>RP(t));return{...i.value,cached:i.cached}}function SR(t){hR.invalidate(`${t}:`)}function fR(t,e={}){let n=e.shell||(process.platform==="win32"?"powershell.exe":"bash"),r=Bun.spawn([n,"-i"],{stdin:"pipe",stdout:"pipe",stderr:"pipe",cwd:e.cwd,env:{...process.env,TERM:"xterm-256color",PS1:"\\w $ "}}),i=new TextDecoder,c=async(d)=>{if(!d)return;let a=d.getReader();try{for(;;){let{done:l,value:o}=await a.read();if(l)break;if(o)t(i.decode(o))}}catch{}};if(c(r.stdout),c(r.stderr),e.onExit)r.exited.then((d)=>e.onExit(d)).catch(()=>{});return{write(d){try{r.stdin.write(d),r.stdin.flush()}catch{}},close(){try{r.stdin.end()}catch{}try{r.kill()}catch{}}}}var $P="127.0.0.1",vP=7676,RR=65536,rE="ts-cloud-dashboard-",Pi=IP(PP(import.meta.url));function kP(t){try{return process.kill(t,0),!0}catch(e){return e?.code!=="ESRCH"}}function CP(t=Ro(),e=kP){let n=0;for(let r of _R(t,{withFileTypes:!0})){if(!r.isDirectory()||!r.name.startsWith(rE))continue;let i=At(t,r.name),c=r.name.match(/^ts-cloud-dashboard-(\d+)-/);if(c){let d=Number(c[1]);if(d===process.pid||e(d))continue}else if(_R(i).length>0)continue;Wr(i,{recursive:!0,force:!0}),n+=1}return n}var OP={".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 h(t,e=200,n={}){return new Response(JSON.stringify(t,null,2),{status:e,headers:{"content-type":"application/json; charset=utf-8",...n}})}function JP(t,e,n,r){let i=new TextEncoder,c=Math.max(0,Math.floor(n)),d,a,l=!1,o=new ReadableStream({start(u){let f=()=>{if(l)return;if(l=!0,d?.(),a)clearInterval(a);r.removeEventListener("abort",f);try{u.close()}catch{}},R=(y)=>{if(l)return;if(y.reset)u.enqueue(i.encode(`event: reset
|
|
461
|
-
data: ${JSON.stringify({cursor:y.cursor,droppedBytes:y.droppedBytes})}
|
|
462
|
-
|
|
463
|
-
`));for(let $ of y.chunks.filter((C)=>C.cursor>c))c=$.cursor,u.enqueue(i.encode(`id: ${$.cursor}
|
|
464
|
-
event: ${$.stream}
|
|
465
|
-
data: ${JSON.stringify($)}
|
|
466
|
-
|
|
467
|
-
`));if(y.state!=="open")u.enqueue(i.encode(`event: state
|
|
468
|
-
data: ${JSON.stringify({state:y.state,error:y.error,cursor:y.cursor})}
|
|
469
|
-
|
|
470
|
-
`)),f()};d=t.subscribe(e.id,e.workloadId,(y)=>R(t.read(y.id,y.workloadId,c)??y));let E=t.read(e.id,e.workloadId,c);if(!E)return f();if(R(E),l)return;a=setInterval(()=>{if(!l)u.enqueue(i.encode(`event: heartbeat
|
|
471
|
-
data: ${JSON.stringify({cursor:c,at:new Date().toISOString()})}
|
|
472
|
-
|
|
473
|
-
`))},15000),a.unref?.(),r.addEventListener("abort",f,{once:!0})},cancel(){if(l=!0,d?.(),a)clearInterval(a)}});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 BP=new Set(["action","operation","site","name","username","database","secretId","port","key","resourceId","environmentId"]);function zP(t,e,n,r,i){let c={};if(n&&typeof n==="object"&&!Array.isArray(n))for(let[a,l]of Object.entries(n)){if(!BP.has(a)||!["string","number","boolean"].includes(typeof l))continue;c[a]=typeof l==="string"?l.slice(0,256):l}let d=String(c.resourceId||c.site||c.secretId||c.database||c.name||e);return{method:t.toUpperCase(),path:e,target:d,status:r,outcome:r<400?"succeeded":"failed",durationMs:Math.max(0,Math.round(i)),input:c}}var TP=tr("ts-cloud-dummy-password");function Eo(t,e=200){return new Response(t,{status:e,headers:{"content-type":"text/plain; charset=utf-8"}})}function bP(t,e,n=process.env){let r=n.TS_CLOUD_DASHBOARD_ORIGIN?.trim()||(n.TS_CLOUD_UI_DOMAIN?.trim()?`https://${n.TS_CLOUD_UI_DOMAIN.trim().replace(/^https?:\/\//,"")}`:""),i=["0.0.0.0","::"].includes(t)?void 0:t,c=r||(i&&["127.0.0.1","localhost","::1"].includes(i)?`http://${i.includes(":")?`[${i}]`:i}:${e}`:"");if(!c)return;try{let d=new URL(c),a=["127.0.0.1","localhost","::1"].includes(d.hostname);if(d.protocol!=="https:"&&!(d.protocol==="http:"&&a)||d.username||d.password||d.search||d.hash||d.pathname!=="/"&&d.pathname!=="")return;return d.origin}catch{return}}function WP(t,e){if(e&&Object.hasOwn(t.environments??{},e))return e;return Object.keys(t.environments??{})[0]??"production"}function UP(t,e,n){return n&&t.includes(n)?n:e}function ER(t,e,n){return t==null||e-t>=n}async function jP(t){let e=[At(Pi,"..","..","..","..",".env"),At(t,".env"),At(t,".env.local"),At(t,".env.production")];for(let n of e){if(!Tn(n))continue;let r=await ln(n,"utf8").catch(()=>"");for(let i of r.split(`
|
|
474
|
-
`)){let c=i.trim();if(!c||c.startsWith("#")||!c.includes("="))continue;let d=c.indexOf("="),a=c.slice(0,d).trim(),l=c.slice(d+1).trim();if(!/^[A-Z_][A-Z0-9_]*$/i.test(a)||process.env[a]!=null)continue;if(l.startsWith('"')&&l.endsWith('"')||l.startsWith("'")&&l.endsWith("'"))l=l.slice(1,-1);process.env[a]=l}}}function HP(t){return[At(t,"config","cloud.ts"),At(t,"config","cloud.js"),At(t,"cloud.config.ts"),At(t,"cloud.config.js")].find((n)=>Tn(n))??null}function $i(t){return t.infrastructure?.compute?.sshKeys??[]}function IR(t,e){let n=t.infrastructure??(t.infrastructure={}),r=n.compute??(n.compute={});r.sshKeys=e}function LP(t,e,n){let r=t.sites??(t.sites={});r[e]=n}function Fl(t){return zr(t.infrastructure?.compute?.firewall?.allowedPorts??[])}function wR(t,e){let n=t.infrastructure??(t.infrastructure={}),r=n.compute??(n.compute={}),i=r.firewall??(r.firewall={});i.allowedPorts=e}async function B(t){return await t.json().catch(()=>({}))}function Di(t,e){let n=String(t.scopeType??"environment");if(!["project","environment","service","function","preview"].includes(n))throw Error("Configuration scopeType must be project, environment, service, function, or preview.");let r=String(t.scopeId??(n==="project"?e.projectId:n==="environment"?e.environmentId??"":""));if(!r)throw Error("Configuration scopeId is required.");if(n==="project")return{type:n,id:r};if(n==="environment")return{type:n,id:r,environmentId:r};if(n==="service"||n==="function")return{type:n,id:r,environmentId:String(t.environmentId??e.environmentId??"")||void 0,resourceId:r};return{type:n,id:r,environmentId:String(t.environmentId??e.environmentId??"")||void 0,resourceId:String(t.resourceId??"")||void 0,previewId:r}}function FP(t){if(["GET","HEAD","OPTIONS"].includes(t.method.toUpperCase()))return!0;let e=t.headers.get("sec-fetch-site");if(e==="cross-site")return!1;let n=t.headers.get("origin");if(!n)return!0;let r=new URL(t.url);if(n===r.origin)return!0;if(e!=="same-origin")return!1;try{let i=new URL(n),c=(t.headers.get("x-forwarded-host")??t.headers.get("host")??r.host).split(",")[0].trim(),d=t.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();if(!/^[A-Za-z0-9.-]+(?::\d{1,5})?$/.test(c)||i.host!==c)return!1;return!d||i.protocol===`${d}:`}catch{return!1}}var VP=new Set(["owner","admin","deployer","operator","viewer","auditor"]),NP=new Set(["organization","project","environment","resource"]),xP=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 fo(t){let e=String(t??"");return VP.has(e)?e:void 0}function sc(t){let e=String(t.scopeType??"organization");if(!NP.has(e))return;if(e==="organization")return{type:"organization"};let n=String(t.scopeId??"").trim();return n?{type:e,id:n}:void 0}async function br(t,e,n={}){let r=On(t),i={mode:r,environment:e,environments:Object.keys(t.environments??{}),project:{name:t.project.name,slug:t.project.slug,region:t.project.region}};try{return{...(r==="serverless"?await ho(t,e):await So(t,e,{includeSiteHealth:n.includeSiteHealth}))??{},...i}}catch{return{...i}}}function MP(t,e){if(!t)return e;let n={...e,...Array.isArray(t.sites)?{sites:t.sites}:{},...Array.isArray(t.sitesDetail)?{sitesDetail:t.sitesDetail}:{},...Array.isArray(t.siteHealth)?{siteHealth:t.siteHealth}:{}};if(n.mode!=="serverless"&&Array.isArray(n.sites))n.topology=mR(n,{project:n.project?.name,environment:n.environment});return n}function QP(t){let e=[At(t,"packages","ui"),At(Pi,"..","..","..","ui"),At(Pi,"..","..","ui"),At(Pi,"..","ui-src"),At(Pi,"..","..","ui-src"),At(Pi,"..","..","dist","ui-src")];for(let n of e)if(Tn(At(n,"pages"))&&Tn(At(n,"package.json")))return n;return null}async function GP(t,e){let n=QP(t);if(!n)return null;let r;try{r=Nl(At(Ro(),`${rE}${process.pid}-`));let i=At(n,"node_modules",".bin","stx"),c=Tn(i)?[i,"build","--pages","pages","--out",r,"--no-sitemap","--no-cache"]:["bunx","--bun","@stacksjs/stx","build","--pages","pages","--out",r,"--no-sitemap","--no-cache"],d=Bun.spawn(c,{cwd:n,stdout:"pipe",stderr:"pipe",env:{...process.env,TSCLOUD_DASHBOARD_DATA:eE(e)}}),[a,l,o]=await Promise.all([new Response(d.stdout).text(),new Response(d.stderr).text(),d.exited]);if(o!==0){if(Wr(r,{recursive:!0,force:!0}),process.env.TSCLOUD_DASHBOARD_VERBOSE)console.warn(`ts-cloud dashboard: live UI build failed; serving the pre-built UI.
|
|
475
|
-
${a}
|
|
476
|
-
${l}`);return null}return r}catch(i){if(r)Wr(r,{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 ZP(t){let e=t.infrastructure?.compute?.managedServices?JSON.parse(JSON.stringify(t.infrastructure.compute.managedServices)):void 0;if(e?.vitess?.password)e.vitess.password="";return{project:{name:t.project?.name,slug:t.project?.slug,region:t.project?.region},provider:t.provider,environments:Object.keys(t.environments??{}),compute:t.infrastructure?.compute?{provider:t.infrastructure.compute.provider,runtime:t.infrastructure.compute.runtime,webServer:t.infrastructure.compute.webServer,proxy:t.infrastructure.compute.proxy?{engine:t.infrastructure.compute.proxy.engine,onDemandTls:t.infrastructure.compute.proxy.onDemandTls,cdn:!!t.infrastructure.compute.proxy.cdn}:void 0,managedServices:e,sshKeys:gc($i(t)).map((n)=>({name:n.name,type:n.type,fingerprint:n.fingerprint,added:n.added}))}:void 0,sites:Object.fromEntries(Object.entries(t.sites??{}).map(([n,r])=>[n,{domain:r.domain,path:r.path,type:r.type,deploy:r.deploy,root:r.root,port:r.port,ssl:r.ssl}]))}}function iE(t){return[{id:"status",label:"Refresh Cloud Status",description:"Runs the local ts-cloud status checks against configured providers.",command:["status","--env",t],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",t,"--yes"],mutates:!0,confirm:"deploy"}]}function YP(t,e){return iE(e).find((n)=>n.id===t)}function AR(t){if(t.length<=RR)return t;return`${t.slice(0,RR)}
|
|
477
|
-
|
|
478
|
-
[output truncated]`}async function DR(t,e,n){let r=t.getReader(),i=new TextDecoder,c="";while(!0){let{done:a,value:l}=await r.read();if(a)break;let o=i.decode(l,{stream:!0});if(c+=o,o)n?.(e,o)}let d=i.decode();if(d)c+=d,n?.(e,d);return c}async function Vl(t,e){let n=Bun.spawn([process.execPath,e.cliEntry,...t.command],{cwd:e.cwd,stdout:"pipe",stderr:"pipe",env:{...process.env,...e.env}}),r=()=>{try{n.kill()}catch{}};if(e.signal?.aborted)r();else e.signal?.addEventListener("abort",r,{once:!0});try{let[i,c,d]=await Promise.all([DR(n.stdout,"stdout",e.onOutput),DR(n.stderr,"stderr",e.onOutput),n.exited]);return{action:t.id,command:["cloud",...t.command].join(" "),exitCode:d,ok:d===0,stdout:AR(i),stderr:AR(c)}}finally{e.signal?.removeEventListener("abort",r)}}function XP(){return Object.entries(process.env).filter(([t,e])=>!!e&&e.length>=8&&/(?:secret|token|password|passwd|private|credential|api.?key|access.?key)/i.test(t)).map(([,t])=>t)}var KP=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 pP(t){let e=uc(t);if(e&&e!==".html")return!1;let n=t.replace(/\.html$/,"").replace(/\/+$/,"")||"/";if(n==="/")return!1;return!KP.has(n)}var mP={"/":"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 yR(t,e){if(e.role==="admin")return!0;let n=uc(t);if(n&&n!==".html")return!0;if(e.organizationSource==="legacy")return!pP(t);let r=t.replace(/\.html$/,"").replace(/\/+$/,"")||"/";if(r==="/access-denied")return!0;let i=mP[r];return!!i&&!!e.capabilities?.includes(i)}function qP(t,e){let n=decodeURIComponent(e).replace(/^\/+/,""),i=wP(n===""?"index.html":n);if(i.startsWith("..")||i.includes("/../"))return null;let c=At(t,i);if(Tn(c)&&!nE(c).isDirectory())return c;if(!uc(c)&&Tn(`${c}.html`))return`${c}.html`;if(!uc(c)&&Tn(At(c,"index.html")))return At(c,"index.html");return null}async function PR(t,e){let n=qP(t,e);if(!n){let c=At(t,"404.html");if(Tn(c))return new Response(await ln(c),{status:404,headers:{"content-type":"text/html; charset=utf-8"}});return Eo("Not found",404)}if(nE(n).isDirectory())return Eo("Not found",404);let r=await ln(n),i=OP[uc(n)]??"application/octet-stream";return new Response(r,{headers:{"content-type":i}})}var _o=["observe","backup","restore","restart","resize","version","rotate","expose","delete","logs","slow_queries","users","databases"],$R=new WeakMap;async function vR(t){let e=$R.get(t);if(e)return e;let n=await import("./chunk-qk9qgepa.js"),r=new n.SpendStore(t),i={store:r,service:new n.SpendService(r),gate:new n.SpendGate(t)};return $R.set(t,i),i}async function Sj(t={}){CP();let e=t.cwd??process.cwd(),n=t.host??$P,r=t.port??vP,i=t.cliEntry??process.argv[1];if(t.box)process.env.TS_CLOUD_DASHBOARD_BOX="1";await jP(e);let c=t.config??await $S(),d=process.env.TS_CLOUD_DASHBOARD_DB_PASSWORD,a=re(c);if(d&&a&&!a.password)a.password=d;let l=c.infrastructure?.compute?.managedServices?.vitess;if(d&&l&&typeof l==="object"&&!l.password)l.password=d;let o=zf(e,c);if(o.reconciliation.failed>0)console.warn(` ts-cloud dashboard: marked ${o.reconciliation.failed} orphaned operation(s) as failed after restart.`);let u=Object.keys(c.environments??{}),f=WP(c,t.environment),R=HP(e),E=await br(c,f),y=new Map([[f,E]]),$=new Map([[f,Date.now()]]),C=new Map([[f,Date.now()]]),J=new Map,H=Math.min(300000,Math.max(5000,Number(process.env.TS_CLOUD_DASHBOARD_REFRESH_MS)||30000)),O=Math.min(1800000,Math.max(60000,Number(process.env.TS_CLOUD_DASHBOARD_SITE_REFRESH_MS)||300000)),Y=On(c)!=="serverless",dt=(S)=>{let x=y.get(S);if(x&&!ER($.get(S),Date.now(),H))return Promise.resolve(x);let Z=J.get(S);if(Z)return Z;let V=!Y||ER(C.get(S),Date.now(),O),tt=br(c,S,{includeSiteHealth:V}).then((_t)=>{let w=y.get(S),ce=V?_t:MP(w,_t);if(y.set(S,ce),$.set(S,Date.now()),V)C.set(S,Date.now());if(w?._serverReachable!==ce._serverReachable||w?._metricsStatus!==ce._metricsStatus||(w?.sitesDetail?.length??0)!==(ce.sitesDetail?.length??0))Le();return ce}).finally(()=>J.delete(S));return J.set(S,tt),tt},m=pR(e),Ut=process.env.TS_CLOUD_DASHBOARD_TELEMETRY?.trim();if(t.box&&Ut!=="0"&&(Ut==="1"||!c.cloud?.attachTo)){let S=!1,x=Date.now()+300000,Z=async()=>{if(S)return;S=!0;try{let tt=Date.now(),_t=tt>=x;if(_t)x=tt+300000;let w=o.environments.get(f);await Ll({controlPlane:o.store,projectId:o.project.id,environmentId:w?.id,config:c,environment:f,force:!0,lightweight:!0,includeSiteHealth:_t})}catch(tt){if(t.verbose)console.warn(` ts-cloud dashboard: background telemetry collection failed: ${tt instanceof Error?tt.message:String(tt)}`)}finally{S=!1}};Z(),setInterval(()=>void Z(),60000).unref?.()}let Q=new Map,rt=new Map,Dt=new Set,Ke=0;function bn(S,x){if(S.role==="admin"&&!o.store.getActorByExternalId("user",`dashboard:${S.username.toLowerCase()}`))return S;let Z=o.store.getActorByExternalId("user",`dashboard:${S.username.toLowerCase()}`),V=Z?o.store.getMembershipForActor(o.organization.id,Z.id):void 0;if(!V||V.status!=="active")return{...S,role:"member",sites:{},capabilities:[]};let tt=o.store.listGrants(V.id),_t=o.store.resolveAuthorizationTarget(o.organization.id,V.scope)??o.store.resolveAuthorizationTarget(o.organization.id,{type:"project",id:o.project.id}),w=lc({membership:V,grants:tt,target:_t});if(V.roleTemplate==="owner"||V.roleTemplate==="admin")return{...S,role:"admin",sites:{},organizationRole:V.roleTemplate,organizationSource:V.source,capabilities:w};let ce=o.environments.get(x),Lt={};for(let it of o.store.listResources(o.project.id,ce?.id).filter((at)=>at.kind==="application")){let at=o.store.resolveAuthorizationTarget(o.organization.id,{type:"resource",id:it.id});if(!at||!Ne({membership:V,grants:tt,capability:"project:read",target:at}).allowed)continue;Lt[it.slug]=Ne({membership:V,grants:tt,capability:"config:write",target:at}).allowed?"owner":"collaborator"}return{...S,role:"member",sites:Lt,organizationRole:V.roleTemplate,organizationSource:V.source,capabilities:w}}function Le(){Ke+=1,Q.clear();for(let S of Dt)Wr(S,{recursive:!0,force:!0});Dt.clear()}let pe=(S,x)=>`${x}:${S.role==="admin"?"admin":`member:${Object.entries(S.sites).sort(([Z],[V])=>Z.localeCompare(V)).map(([Z,V])=>`${Z}=${V}`).join(",")}`}:${[...S.capabilities??[]].sort().join(",")}`;async function me(S,x){let Z=bn(S,x),V=pe(Z,x),tt=Q.get(V);if(tt)return tt;let _t=rt.get(V);if(_t)return _t;let w=Ke,ce=(async()=>{let Lt=y.get(x)??await br(c,x);y.set(x,Lt);let it={...yl(Lt,{user:Z,slug:c.project.slug}),viewer:{role:Z.role,organizationRole:Z.organizationRole,organizationSource:Z.organizationSource,capabilities:Z.capabilities??[]}},at=await GP(e,it);if(at&&w!==Ke)return Wr(at,{recursive:!0,force:!0}),m?.uiRoot;if(at)Dt.add(at);let pt=at??m?.uiRoot;if(pt)Q.set(V,pt);return pt})();rt.set(V,ce);try{return await ce}finally{rt.delete(V)}}let qe=await me({username:"",passwordHash:"",role:"admin",sites:{}},f);if(!qe)throw Error("ts-cloud dashboard UI not found. Run `bun run build` in ts-cloud or reinstall the package.");let P=new WeakMap,b=process.env.TS_CLOUD_DASHBOARD_TERMINAL!=="0",N=process.env.TS_CLOUD_DASHBOARD_AUTH==="0";if(N&&t.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 G=!N,vt=mf(e),jt=G?n_(e,process.env.TS_CLOUD_UI_USERNAME?.trim()||"admin"):void 0,F=new Tc(o.store,{encryptionKey:Gn(e)}),gt=new jc(o.store),ot=new pi(o.store),q=new No(o.store,{encryptionKey:Gn(e)}),ie=new Jo(o.store),Ur=new bo(o.store,{cwd:e}),tn=new zo(o.store,{encryptionKey:Gn(e)}),yt=new Ot(o.store,{workerId:`dashboard:${process.pid}`}),kt=new Aa(o.store),gn=new Ba(o.store,Gn(e)),Wn=new CR(o.store),hc=new Zc(kt,yt,gn),Un=c.project?.region??"us-east-1",xl=Gn(e),we=new bR(Wn,{encryptionKey:xl,backends:[new OR(o.store,xl),new JR(new cc(Un),Un),new BR(new kR(Un),Un),new zR]});await WR(we,o,c);let Io=new Er(Un),cE={aws_rds:new Da(new Ca(Io)),aws_aurora:new ya(new Oa(Io)),aws_elasticache:new Pa(new Ja(new Hi(Un))),server:new $a(new pr),container:new va(new pr)},Ml=(S)=>cE[S.provider],Ft=new Ra(o.store),ir=new Mc(Ft,yt),Ql=new Ia(gn),dE={managed_database:new wa(kt,Io),logical_database:new Wa(kt,gn),volume:new ja,files:new ba(e),control_plane:new La(o.store,e),infrastructure:new Va(new ji(Un))},oE=(S)=>dE[S.resourceKind],aE=(S)=>S.provider==="aws_backup"?void 0:Ql,wo=new xR(o.store),Ao=[new VR,new NR(de(e,"volumes"))],un=new LR(wo,Ao,yt),vi=new Bs(o.store),en=new zs(vi,[new Zi("aws"),new Zi("hetzner"),new Zi("ssh")],yt),jn=new Ls(o.store),Gl=new Fs(jn,vi),cr=new Ms(o.store),Zl=new Qs(cr,yt),hn=new Ws(o.store),Do=new Us(hn,yt),Yl=["releases","artifacts","operations","logs","previews","snapshots","orphaned_resources"].map((S)=>new Hs(S,o.store,o.project.id,o.organization.id)),Xt=new ha(o.store),Xl=new ga(Xt,{queue:yt}),Ht=new Oc(o.store),Hn=new Cc(o.store),Oe=new lr(o.store),nt=new QR(o.store,{encryptionKey:Gn(e)}),sE=()=>vR(o.store);for(let S of o.environments.values())la(Xt,c,{organization:o.organization,project:o.project,environment:S,resources:o.store.listResources(o.project.id,S.id)});let Je=new GR(nt,{emailImpl:async(S)=>{let{email:x}=await import("./chunk-c1vcdgvr.js");return x.send(S)}}),Kl=async(S)=>{let x=KR(nt,o.project.id,S),Z=[];for(let V of x.filter((tt)=>tt.notify&&tt.alert))Z.push(...await Je.deliverAll(Je.enqueue(o.organization.id,V.alert,V.transition)));return Z.push(...await Je.deliverAll(Je.enqueueRemindersAndEscalations(o.organization.id,nt.listAlerts(o.project.id,{environmentId:S,states:["firing"]})))),Z.push(...await Je.retryDue()),{evaluations:x,deliveries:Z}},yo=!1,lE=async()=>{if(yo)return;yo=!0;try{for(let S of o.environments.values())for(let x of nt.listHealthChecks(o.project.id,S.id).filter((Z)=>Z.enabled)){let Z=nt.listHealthResults(x.id,1)[0];if(Z&&Date.now()-new Date(Z.checkedAt).getTime()<x.intervalSeconds*1000)continue;let V=await new yi(nt).runAndEvaluate(x);for(let tt of V.evaluations.filter((_t)=>_t.notify&&_t.alert))await Je.deliverAll(Je.enqueue(o.organization.id,tt.alert,tt.transition))}}finally{yo=!1}},pl=setInterval(()=>{for(let S of o.environments.values())Kl(S.id).catch((x)=>console.error("ts-cloud alert evaluation failed:",x))},60000);pl.unref?.();let ml=setInterval(()=>{lE().catch((S)=>console.error("ts-cloud health check evaluation failed:",S))},30000);ml.unref?.();let ql=setInterval(()=>{try{Xl.tick()}catch(S){console.error("ts-cloud scheduled job evaluation failed:",S)}},30000);ql.unref?.();let tg=setInterval(()=>{try{ir.enqueueDue(),ir.enqueueRetention()}catch(S){console.error("ts-cloud backup policy evaluation failed:",S)}},30000);tg.unref?.(),Ht.cleanup();let eg=setInterval(()=>{try{Ht.cleanup()}catch(S){console.error("ts-cloud preview cleanup failed:",S)}},3600000);eg.unref?.();let gE=t.queueWorker??!0,uE=XP(),hE=async(S,x)=>{let V=(S.environmentId?o.store.listEnvironments(S.projectId).find((tt)=>tt.id===S.environmentId):void 0)?.slug??String(f);if(x.kind==="dashboard_operation"&&x.operationId){let tt=y.get(V)??E,_t=Dl(x.operationId,c,tt);if(!_t||_t.danger||!["scheduler","backup","worker"].includes(_t.group))return{ok:!1,stderr:"The allowlisted dashboard operation is no longer available."};let w=await ao(c,V,_t);return{ok:w.ok,stdout:w.stdout,stderr:w.stderr??w.error,retryable:/temporar|unavailable|timeout|network/i.test(w.stderr??w.error??""),output:{command:w.command??null,operation:w.operation}}}if(x.kind==="serverless_scheduler"){let tt=await Wl(c,V,"run");return{ok:tt.ok,stdout:tt.stdout,stderr:tt.error,retryable:/temporar|unavailable|timeout|network/i.test(tt.error??""),output:{command:tt.command??null,operation:"serverless_scheduler"}}}return{ok:!1,stderr:`No safe executor is configured for ${x.kind}.`}},Sc=gE?new UR(yt,{...MR({store:o.store,execute:async(S,x)=>{let Z=x.operation.input&&typeof x.operation.input==="object"&&!Array.isArray(x.operation.input)?x.operation.input:{},V=Z.source&&typeof Z.source==="object"?Z.source:void 0,tt=e,_t,w,ce;try{if(V?.bindingId&&V?.connectionId&&V?.commitSha){let it=q.getBinding(String(V.bindingId)),at=q.getConnection(String(V.connectionId));if(!it||!at||it.connectionId!==at.id)throw Error("Queued source binding is no longer available");let Zt=(it.repositoryId?q.getRepository(it.repositoryId):q.listRepositories(at.id).find((Lr)=>Lr.fullName.toLowerCase()===it.repositoryFullName.toLowerCase()))?.cloneUrl;if(!Zt&&at.provider==="generic_ssh")Zt=`git@${new URL(at.host).hostname}:${it.repositoryFullName}.git`;if(!Zt)Zt=new URL(`/${it.repositoryFullName}.git`,at.host.endsWith("/")?at.host:`${at.host}/`).href;let U=it.deployKeyId?q.getDeployKey(it.deployKeyId):void 0,Ct=U&&it.deployKeyId?{...U,privateKey:q.getDeployPrivateKey(it.deployKeyId)}:void 0;if(["github","gitlab","bitbucket","gitea"].includes(at.provider)&&S.target.previewId){let Lr=xn(at,q.getCredential(at.id)),z=Ht.previews.getInstance(S.target.previewId);ce=async(Be,Ic)=>{try{await Lr.setCommitStatus(it.repositoryFullName,String(V.commitSha),{state:Be,url:z?.url,description:Ic})}catch(Fr){x.log(`Could not publish source status: ${Fr instanceof Error?Fr.message:String(Fr)}`,{stream:"stderr"})}},await ce("pending",`Preview deployment started for ${String(V.commitSha).slice(0,12)}`)}_t=Nl(At(Ro(),"ts-cloud-queued-source-")),x.log(`Checking out immutable source commit ${V.commitSha}.`,{stream:"system"}),tt=(await Qo({remote:Zt,binding:it,destination:At(_t,"checkout"),ref:String(V.branch??it.defaultBranch),commitSha:String(V.commitSha)},{credential:q.getCredential(at.id),deployKey:Ct})).directory}if(x.operation.kind!=="preview.destroy"){let it=S.target.previewId?Ht.previews.getInstance(S.target.previewId):void 0,at=it?Ht.previews.getDefinition(it.definitionId):void 0,pt=x.operation.resourceId?o.store.getResource(x.operation.resourceId):void 0;if(w=await we.resolve({projectId:o.project.id,environmentId:x.operation.environmentId,resourceId:x.operation.resourceId,functionId:pt?.kind==="function"?pt.id:void 0,previewId:it?.id,trustedPreview:!!it&&!it.fork,allowedPreviewSecrets:at?.inheritedSecrets}),w.warnings.some((Zt)=>Zt.code==="missing_required"))throw Error(`Required deployment configuration is unavailable: ${w.warnings.filter((Zt)=>Zt.code==="missing_required").map((Zt)=>Zt.key).join(", ")}`);if(x.operation.resourceId)for(let Zt of Object.values(w.entries))Wn.setDependency({entryId:Zt.id,resourceId:x.operation.resourceId,injectionTarget:"environment",required:Zt.required,requiresRedeploy:!0});x.log(`Resolved configuration ${w.configurationHash.slice(0,18)} for ${Object.keys(w.values).length} keys.`,{stream:"system"})}let Lt=await Vl(S,{cwd:tt,cliEntry:i,signal:x.signal,env:w?.values,onOutput:(it,at)=>x.log(at,{stream:it,step:"execute",secrets:[...uE,...Object.entries(w?.entries??{}).filter(([,pt])=>pt.kind==="secret").map(([pt])=>w.values[pt]).filter(Boolean)]})});if(Lt.ok&&x.operation.resourceId&&w)for(let it of Object.values(w.entries))Wn.setDependency({entryId:it.id,resourceId:x.operation.resourceId,injectionTarget:"environment",required:it.required,requiresRedeploy:!1,lastDeployedVersion:it.version});return await ce?.(Lt.ok?"success":"failure",Lt.ok?`Preview is ready at ${String(V?.commitSha).slice(0,12)}`:`Preview deployment failed at ${String(V?.commitSha).slice(0,12)}`),Lt}catch(Lt){throw await ce?.("error",`Preview deployment could not complete at ${String(V?.commitSha).slice(0,12)}`),Lt}finally{if(_t)Wr(_t,{recursive:!0,force:!0})}}}),...Cu({store:Xt,executor:hE}),...Fu({store:kt,secrets:gn,resolveAdapter:Ml}),...CS(vi,en.drivers),...XS(cr,[new Gs("aws","AWS regional execution requires an injected AwsRegionalTransport; topology and plans were preserved without provider mutation.")]),...VS({store:hn,cleanup:Yl}),...FR(wo,Ao),...Uu({store:Ft,queue:yt,resolveSource:oE,resolveDestination:aE,validateHealth:async(S,x)=>{if(!S.healthCheckId)return{healthy:!0,mode:"adapter"};let Z=nt.getHealthCheck(S.healthCheckId);if(!Z||Z.projectId!==S.projectId)return{healthy:!1,error:"Configured restore health check was not found."};let V=await new yi(nt).runAndEvaluate(Z);return{healthy:V.result.status==="healthy",healthCheckId:Z.id,healthResultId:V.result.id,target:x}}}),...Bg({store:o.store,resolveDriver:t.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 Z=nt.listHealthChecks(x.projectId,x.environmentId).find((tt)=>tt.enabled&&tt.name===S&&(!tt.resourceId||tt.resourceId===x.resourceId));if(!Z)return{healthy:!1,message:`Named health gate ${S} was not found for this release.`};let V=await new yi(nt).runAndEvaluate(Z);return{healthy:V.result.status==="healthy",evidence:{healthCheckId:Z.id,healthResultId:V.result.id,status:V.result.status,timings:V.result.timings},message:V.result.message}}})},{parallelism:t.queueParallelism??(Number(process.env.TS_CLOUD_QUEUE_PARALLELISM)||8),onError:(S)=>console.error("ts-cloud deployment queue worker failed:",S)}):void 0;if($f(o),Qd(ot,Ye(o,String(f)),E),jt)Zd(o,jt.users),c_(F,o,jt.users);let Bt=r_({cwd:e,enabled:G,secret:vt,authentication:F,authorization:{store:o.store,organizationId:o.organization.id,projectId:o.project.id,defaultEnvironment:String(f)}}),Vt=new ms,ng=setInterval(()=>Vt.sweep(),60000);ng.unref?.();let fc=new rc,Po=new rc(3,900000,900000),_c=new rc(8,900000,900000),rg=setInterval(()=>fc.prune(),300000),ig=setInterval(()=>Po.prune(),300000),cg=setInterval(()=>_c.prune(),300000);if(rg.unref?.(),ig.unref?.(),cg.unref?.(),G){if(jt?.generated)console.warn(`
|
|
479
|
-
ts-cloud dashboard: created the first admin.
|
|
480
|
-
username: ${jt.generated.username}
|
|
481
|
-
password: ${jt.generated.password}
|
|
482
|
-
Saved (hashed) to ${t_()}. This password is shown once.
|
|
483
|
-
`)}else console.warn(" ts-cloud dashboard: authentication is DISABLED (TS_CLOUD_DASHBOARD_AUTH=0). Every request runs as an admin.");let Ln=n!=="127.0.0.1"&&n!=="localhost",$o=(S)=>EP("sha256").update(`${vt}:${S}`).digest("hex").slice(0,16),SE=Xo({controlPlane:o.store,identities:gt,sources:q,applications:{drafts:ie,artifacts:Ur,registries:tn}}),dg=(S)=>S.headers.get("user-agent")?.trim().slice(0,256)||void 0,Rc=(S,x,Z,V="local")=>F.createSession({identityId:S,authMethod:V,userAgent:dg(x),networkHint:$o(Z)}),X=(S)=>{let x=o.store.getActorByExternalId("user",`dashboard:${S.username.toLowerCase()}`),Z=x?o.store.getMembershipForActor(o.organization.id,x.id):void 0;return{actor:x,membership:Z,grants:Z?o.store.listGrants(Z.id):[]}},jr=(S,x,Z)=>{if(S.role==="admin")return!0;let V=o.store.getOperation(x),tt=X(S);if(!V||!tt.membership)return!1;let _t=V.resourceId?{type:"resource",id:V.resourceId}:V.environmentId?{type:"environment",id:V.environmentId}:V.projectId?{type:"project",id:V.projectId}:{type:"organization"},w=o.store.resolveAuthorizationTarget(o.organization.id,_t);return!!w&&Ne({membership:tt.membership,grants:tt.grants,capability:Z,target:w}).allowed},Kt=(S,x,Z)=>{if(S.role==="admin")return!0;let V=X(S);if(!V.membership)return!1;let tt=o.store.resolveAuthorizationTarget(o.organization.id,{type:"resource",id:x});return!!tt&&Ne({membership:V.membership,grants:V.grants,capability:Z,target:tt}).allowed},ki=(S,x,Z)=>{if(S.role==="admin")return!0;let V=X(S);if(!V.membership)return!1;let tt=o.store.resolveAuthorizationTarget(o.organization.id,{type:"environment",id:x});return!!tt&&Ne({membership:V.membership,grants:V.grants,capability:Z,target:tt}).allowed},Ec=(S,x)=>{if(S.role==="admin")return!0;let Z=X(S);if(!Z.membership)return!1;let V=o.store.resolveAuthorizationTarget(o.organization.id,{type:"organization"});return!!V&&Ne({membership:Z.membership,grants:Z.grants,capability:x,target:V}).allowed},Hr=Bun.serve({hostname:n,port:r,idleTimeout:30,websocket:{open(S){if(!b){S.send(`The web terminal is disabled (TS_CLOUD_DASHBOARD_TERMINAL=0).\r
|
|
484
|
-
`),S.close();return}let x=fR((Z)=>S.send(Z),{cwd:e,onExit:()=>{try{S.close()}catch{}}});P.set(S,x),S.send(`Connected to ${n==="127.0.0.1"?"localhost":n} shell. This is a line-oriented shell (no full-screen apps).\r
|
|
485
|
-
`)},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 Z=Date.now(),V=S.clone(),tt=S.headers.get("x-request-id")?.slice(0,128)||crypto.randomUUID(),_t=!["GET","HEAD","OPTIONS"].includes(S.method.toUpperCase()),w=new URL(S.url),Lt=await(async()=>{let it=x??Hr,at=bP(n,it.port??r),pt=await SE(S,$o(it.requestIP(S)?.address??"unknown"));if(pt)return pt;let Zt=w.searchParams.get("env"),U=UP(u,f,Zt),Ct=y.get(U);if(!Ct)Ct=await dt(U);try{if(!FP(S))return h({ok:!1,error:"Cross-site requests are not allowed."},403);let dr=/^\/api\/source\/webhooks\/([A-Za-z0-9_-]{16,200})$/.exec(w.pathname);if(dr&&S.method==="POST"){let s=await Zg({sources:q,controlPlane:o.store,endpointToken:dr[1],headers:S.headers,rawBody:new Uint8Array(await S.arrayBuffer())});return h({accepted:s.accepted,duplicate:s.duplicate,status:s.status,operationIds:s.operations.map((g)=>g.id),message:s.message},s.accepted?202:404)}let Lr=/^\/auth\/oidc\/([a-z0-9-]+)\/(start|callback)$/.exec(w.pathname);if(Lr&&S.method==="GET"){let[,s,g]=Lr;if(!at)return new Response(null,{status:302,headers:{location:"/login?sso_error=configuration"}});if(g==="start")try{let _=await ca(F,s,at,w.searchParams.get("return")??void 0,t.oidcFetch);return new Response(null,{status:302,headers:{location:_.authorizationUrl,"cache-control":"no-store"}})}catch(_){return o.store.appendEvent({organizationId:o.organization.id,type:"auth.oidc.start_failed",level:"warning",payload:{provider:s,reason:_ instanceof Error?_.message.slice(0,200):"unknown"}}),new Response(null,{status:302,headers:{location:"/login?sso_error=start","cache-control":"no-store"}})}try{if(w.searchParams.has("error")){let v=F.getOidcProviderBySlug(s),D=w.searchParams.get("state");if(v&&D)F.consumeOidcTransaction(v.id,D);throw Error("OIDC provider returned an authorization error")}let _=await da(F,{providerSlug:s,state:w.searchParams.get("state")??"",code:w.searchParams.get("code")??"",origin:at},t.oidcFetch),I=d_(F,o,e,_.identity);F.recordLogin(I.identity.id);let A=Rc(I.identity.id,S,it.requestIP(S)?.address??"unknown","oidc");return Le(),o.store.appendEvent({organizationId:o.organization.id,actorId:I.identity.actorId,type:"auth.login.succeeded",payload:{method:"oidc",provider:s,provisioned:I.provisioned}}),new Response(null,{status:302,headers:{location:_.returnPath,"cache-control":"no-store","set-cookie":Ei(A.token,{secure:Ln,maxAgeMs:Qn})}})}catch(_){return o.store.appendEvent({organizationId:o.organization.id,type:"auth.oidc.callback_failed",level:"warning",payload:{provider:s,reason:_ instanceof Error?_.message.slice(0,200):"unknown"}}),new Response(null,{status:302,headers:{location:"/login?sso_error=callback","cache-control":"no-store"}})}}if(w.pathname==="/api/invitations/accept"&&S.method==="POST"){let s=await B(S),g=String(s.token??"").trim(),_=String(s.username??"").trim(),I=String(s.password??"");if(!g||!no(_)||I.length<12)return h({ok:!1,error:"Invitation token, valid username, and a password of at least 12 characters are required."},422);let A=o.store.inspectInvitationToken(g);if(!A||A.state!=="pending")return h({ok:!1,error:A?`Invitation is ${A.state}`:"Invitation is invalid"},A?409:404);let v=He(Ie(e),_),D=F.getIdentityByUsername(_);if(v&&!Xe(I,D?.passwordHash??v.passwordHash))return h({ok:!1,error:"That username already exists; enter its current password to continue."},401);let k=F.getIdentityByEmail(A.email);if(k&&k.id!==D?.id)return h({ok:!1,error:"This invitation belongs to an existing account. Sign in with that account or ask an owner to resend it."},409);let W=ec(e,{username:_,password:v?void 0:I,name:typeof s.name==="string"?s.name:void 0,email:A.email,sites:v?.sites??{}}),T=Gt(o.store,W.user);try{let et=o.store.acceptInvitation(g,T.id),j=D?F.setVerifiedEmail(D.id,et.invitation.email):F.createIdentity({actorId:T.id,username:W.user.username,email:et.invitation.email,emailVerified:!0,passwordHash:W.user.passwordHash}),K=Rc(j.id,S,it.requestIP(S)?.address??"unknown");return Le(),h({ok:!0,user:Ii(W.user),organization:o.organization,membership:et.membership},200,{"set-cookie":Ei(K.token,{secure:Ln,maxAgeMs:Qn})})}catch(et){if(!v)Il(e,W.user.username);let j=et instanceof Error?et.message:"Invitation could not be accepted.";return h({ok:!1,error:j},j.includes("expired")||j.includes("revoked")||j.includes("accepted")?409:404)}}if(w.pathname==="/api/auth/password-reset/request"&&S.method==="POST"){let s=await B(S),g=String(s.identifier??"").trim().toLowerCase(),_=it.requestIP(S)?.address??"unknown",I=Po.check(g,_),A=g.includes("@")?F.getIdentityByEmail(g):F.getIdentityByUsername(g);if(I.allowed)Po.recordFailure(g,_);if(I.allowed&&A?.email&&A.emailVerifiedAt&&!A.disabledAt){F.revokeActionTokens(A.id,"password_reset");let v=F.createActionToken(A.id,"password_reset"),D=`${w.origin}/reset-password?token=${encodeURIComponent(v.token)}`,k=await Ui(c,{to:A.email,subject:"Reset your ts-cloud password",text:`Reset your ts-cloud password: ${D}
|
|
486
|
-
|
|
487
|
-
This link expires in one hour and can be used once.`});o.store.appendEvent({organizationId:o.organization.id,actorId:A.actorId,type:"auth.password_reset.requested",payload:{delivered:k}})}return h({ok:!0,message:"If that account has a verified email, a reset link has been sent."},202)}if(w.pathname==="/api/auth/password-reset/complete"&&S.method==="POST"){let s=await B(S),g=String(s.token??"").trim(),_=String(s.password??"");if(!g||_.length<12)return h({ok:!1,error:"A valid reset token and password of at least 12 characters are required."},422);try{let I=F.consumeActionToken(g,"password_reset"),A=tr(_),v=F.updatePassword(I.identityId,A);return io(e,v.username,A),o.store.appendEvent({organizationId:o.organization.id,actorId:v.actorId,type:"auth.password_reset.completed"}),h({ok:!0,message:"Password changed. Sign in again."},200,{"set-cookie":eo({secure:Ln})})}catch(I){let A=I instanceof Error?I.message:"Password reset failed.";return h({ok:!1,error:A.replace("Action token","Reset link")},A.includes("consumed")||A.includes("expired")?409:404)}}if(w.pathname==="/api/login"&&S.method==="POST"){let s=await B(S),g=String(s.username??"").trim(),_=String(s.password??""),I=it.requestIP(S)?.address??"unknown",A=fc.check(g,I);if(!A.allowed)return h({ok:!1,error:`Too many failed attempts. Try again in ${Math.ceil((A.retryAfterSeconds??0)/60)} minute(s).`},429,{"retry-after":String(A.retryAfterSeconds??60)});let v=He(Ie(e),g),D=F.getIdentityByUsername(g),k=D?.passwordHash??v?.passwordHash??TP;if(!(Xe(_,k)&&!!v&&!!D&&!D.disabledAt))return fc.recordFailure(g,I),h({ok:!1,error:"Incorrect username or password."},401);if(o_(F,o,D))return h({ok:!1,error:"Single sign-on is required for this account."},403);fc.recordSuccess(g,I);let T=D,et=T.requiresPasswordUpgrade||Cf(T.passwordHash);if(et){let K=tr(_);T=F.rehashPassword(T.id,K),io(e,T.username,K)}if(F.recordLogin(T.id),F.getMfaFactor(T.id)?.state==="active"){let K=F.createMfaChallenge(T.id,"login");return o.store.appendEvent({organizationId:o.organization.id,actorId:T.actorId,type:"auth.mfa.challenge.created",payload:{purpose:"login"}}),h({ok:!0,mfaRequired:!0,challengeToken:K.token,passwordUpgraded:et})}let j=Rc(T.id,S,I);return o.store.appendEvent({organizationId:o.organization.id,actorId:T.actorId,type:"auth.login.succeeded",payload:{method:"local"}}),h({ok:!0,user:Ii(v),passwordUpgraded:et},200,{"set-cookie":Ei(j.token,{secure:Ln,maxAgeMs:Qn})})}if(w.pathname==="/api/auth/mfa/complete"&&S.method==="POST"){let s=await B(S),g=String(s.challengeToken??"").trim(),_=String(s.code??"").trim(),I=it.requestIP(S)?.address??"unknown",v=F.inspectMfaChallengeToken(g,"login")?.identityId??"unknown-mfa",D=_c.check(v,I);if(!D.allowed)return h({ok:!1,error:"Too many MFA attempts. Try again later."},429,{"retry-after":String(D.retryAfterSeconds??60)});try{let k=F.completeMfaChallenge(g,_,"login");_c.recordSuccess(v,I);let W=new Date().toISOString(),T=F.createSession({identityId:k.identity.id,userAgent:dg(S),networkHint:$o(I),mfaAt:W,recentAuthAt:W});return o.store.appendEvent({organizationId:o.organization.id,actorId:k.identity.actorId,type:"auth.mfa.succeeded",payload:{purpose:"login",method:k.method}}),h({ok:!0},200,{"set-cookie":Ei(T.token,{secure:Ln,maxAgeMs:Qn})})}catch{return _c.recordFailure(v,I),h({ok:!1,error:"Authenticator or recovery code is incorrect."},401)}}if(w.pathname==="/api/logout"&&S.method==="POST"){let s=Bt.resolveSession(S);if(s)F.revokeSession(s.identityId,s.id);let g=eo({secure:Ln});if(S.headers.get("accept")?.includes("text/html"))return new Response(null,{status:302,headers:{location:"/login","set-cookie":g}});return h({ok:!0},200,{"set-cookie":g})}if(w.pathname==="/login"){let s=F.listOidcProviders(o.organization.id).map((g)=>({slug:g.slug,name:g.name}));return new Response(a_(E?.mode==="serverless",s),{headers:{"content-type":"text/html; charset=utf-8"}})}if(w.pathname==="/forgot-password"||w.pathname==="/reset-password")return new Response(s_(w.pathname==="/reset-password"?"reset":"request"),{headers:{"content-type":"text/html; charset=utf-8"}});if(w.pathname==="/accept-invitation")return PR(qe,w.pathname);let z=Bt.resolveUser(S);if(!z){if(!w.pathname.startsWith("/api/")&&S.headers.get("accept")?.includes("text/html"))return new Response(null,{status:302,headers:{location:"/login"}});return h({ok:!1,error:"Sign in to continue."},401)}let Be=bn(z,U);if(w.pathname==="/api/me"){let s=o.store.getActorByExternalId("user",`dashboard:${z.username.toLowerCase()}`),g=s?o.store.getMembershipForActor(o.organization.id,s.id):void 0,_=o.store.resolveAuthorizationTarget(o.organization.id,g?.scope??{type:"project",id:o.project.id})??o.store.resolveAuthorizationTarget(o.organization.id,{type:"project",id:o.project.id});return h({ok:!0,user:Ii(z),authEnabled:G,organization:o.organization,membership:g,capabilities:lc({membership:g,grants:g?o.store.listGrants(g.id):[],target:_})})}if(w.pathname.startsWith("/api/")){let s=await i_(S,w.pathname),g=Bt.check(S,w.pathname,z,s);if(!g.ok)return h({ok:!1,error:g.error},g.status??403);if(G&&xP.has(`${S.method.toUpperCase()} ${w.pathname}`)){let _=Bt.resolveSession(S);if(!_||!F.isRecentlyAuthenticated(_))return h({ok:!1,error:"Recent authentication is required for this change.",stepUpRequired:!0},401)}}if(w.pathname==="/api/auth/security"&&S.method==="GET"){let s=X(z),g=s.actor?F.getIdentityByActor(s.actor.id):void 0,_=Bt.resolveSession(S);return h({identity:g?{username:g.username,email:g.email,emailVerifiedAt:g.emailVerifiedAt,requiresPasswordUpgrade:g.requiresPasswordUpgrade,lastLoginAt:g.lastLoginAt}:void 0,currentSessionId:_?.id,sessions:g?F.listSessions(g.id,{includeInactive:!0}):[],mfa:g?{factor:F.getMfaFactor(g.id),recoveryCodesRemaining:F.remainingRecoveryCodes(g.id)}:void 0})}if(w.pathname==="/api/auth/oidc/providers"&&S.method==="GET")return h({providers:F.listOidcProviders(o.organization.id,{includeDisabled:!0}),callbackOrigin:at,callbackPattern:at?`${at}/auth/oidc/{slug}/callback`:void 0,localOwnerRecovery:!0});if(w.pathname==="/api/auth/oidc/providers"&&S.method==="POST"){let s=await B(S),g=X(z),_=g.actor?F.getIdentityByActor(g.actor.id):void 0,I=s.enforceSso===!0;if(I&&(!_?.emailVerifiedAt||F.remainingRecoveryCodes(_.id)<1))return h({ok:!1,error:"Verify the owner email and generate MFA recovery codes before enforcing SSO."},409);try{let A=fo(s.defaultRole),v=F.upsertOidcProvider({id:typeof s.id==="string"?s.id:void 0,organizationId:o.organization.id,slug:String(s.slug??""),name:String(s.name??""),issuer:String(s.issuer??""),clientId:String(s.clientId??""),clientSecret:typeof s.clientSecret==="string"&&s.clientSecret?s.clientSecret:void 0,scopes:Array.isArray(s.scopes)?s.scopes.map(String):void 0,allowedDomains:Array.isArray(s.allowedDomains)?s.allowedDomains.map(String):[],defaultRole:A&&A!=="owner"?A:void 0,enabled:s.enabled!==!1,enforceSso:I});return o.store.appendEvent({organizationId:o.organization.id,actorId:g.actor?.id,type:"auth.oidc.provider.configured",payload:{providerId:v.id,issuer:v.issuer,enabled:v.enabled,enforceSso:v.enforceSso}}),h({ok:!0,provider:v})}catch(A){return h({ok:!1,error:A instanceof Error?A.message:"OIDC provider could not be saved."},422)}}if(w.pathname==="/api/auth/oidc/providers"&&S.method==="PATCH"){let s=await B(S),g=F.getOidcProvider(String(s.id??""));if(!g||g.organizationId!==o.organization.id)return h({ok:!1,error:"OIDC provider was not found."},404);let _=X(z),I=F.setOidcProviderEnabled(g.id,s.enabled===!0);return o.store.appendEvent({organizationId:o.organization.id,actorId:_.actor?.id,type:I.enabled?"auth.oidc.provider.enabled":"auth.oidc.provider.disabled",payload:{providerId:g.id}}),h({ok:!0,provider:I})}if(w.pathname==="/api/automation"&&S.method==="GET"){let s=gt.listServiceAccounts(o.organization.id,{includeDisabled:!0}).map((g)=>{let _=o.store.getMembershipForActor(o.organization.id,g.actorId),I=g.createdByActorId?o.store.getActor(g.createdByActorId):void 0,A=gt.listTokens(g.id,{includeInactive:!0}).map((v)=>({...v,createdBy:v.createdByActorId?o.store.getActor(v.createdByActorId):void 0}));return{account:g,createdBy:I,membership:_,tokens:A}});return h({accounts:s,apiBaseUrl:`${w.origin}/api/v1`,openApiUrl:`${w.origin}/api/v1/openapi.json`,tokenEnvironmentVariable:"TS_CLOUD_API_TOKEN"})}if(w.pathname==="/api/automation/service-accounts"&&S.method==="POST"){let s=await B(S),g=X(z),_=fo(s.roleTemplate),I=sc(s);if(!g.actor||!_||_==="owner"||!I)return h({ok:!1,error:"A non-owner role and valid organization scope are required."},422);try{let A=gt.createServiceAccount({organizationId:o.organization.id,slug:String(s.slug??""),name:String(s.name??""),description:typeof s.description==="string"?s.description:void 0,roleTemplate:_,scope:I,createdByActorId:g.actor.id});return h({ok:!0,...A},201)}catch(A){return h({ok:!1,error:A instanceof Error?A.message:"Service account could not be created."},422)}}if(w.pathname==="/api/automation/service-accounts"&&S.method==="PATCH"){let s=await B(S),g=X(z),_=gt.getServiceAccount(String(s.id??""));if(!_||_.organizationId!==o.organization.id)return h({ok:!1,error:"Service account was not found."},404);return h({ok:!0,account:gt.disableServiceAccount(_.id,g.actor?.id)})}if(w.pathname==="/api/automation/tokens"&&S.method==="POST"){let s=await B(S),g=X(z),_=gt.getServiceAccount(String(s.serviceAccountId??"")),I=sc(s);if(!g.actor||!_||_.organizationId!==o.organization.id||!I||!Array.isArray(s.capabilities))return h({ok:!1,error:"Service account, explicit capabilities, and valid scope are required."},422);try{let A=gt.createToken({serviceAccountId:_.id,name:String(s.name??"API token"),capabilities:s.capabilities.map(String),scope:I,expiresAt:typeof s.expiresAt==="string"?s.expiresAt:void 0,createdByActorId:g.actor.id});return h({ok:!0,token:A.token,secret:A.secret,revealOnce:!0},201)}catch(A){return h({ok:!1,error:A instanceof Error?A.message:"API token could not be created."},422)}}if(w.pathname==="/api/automation/tokens/rotate"&&S.method==="POST"){let s=await B(S),g=X(z),_=gt.getToken(String(s.id??"")),I=_?gt.getServiceAccount(_.serviceAccountId):void 0;if(!g.actor||!_||I?.organizationId!==o.organization.id)return h({ok:!1,error:"API token was not found."},404);try{let A=gt.rotateToken(_.id,g.actor.id);return h({ok:!0,token:A.token,secret:A.secret,revealOnce:!0,overlap:!0},201)}catch(A){return h({ok:!1,error:A instanceof Error?A.message:"API token could not be rotated."},409)}}if(w.pathname==="/api/automation/tokens"&&S.method==="DELETE"){let s=await B(S),g=X(z),_=gt.getToken(String(s.id??"")),I=_?gt.getServiceAccount(_.serviceAccountId):void 0;if(!_||I?.organizationId!==o.organization.id)return h({ok:!1,error:"API token was not found."},404);return h({ok:!0,token:gt.revokeToken(_.id,g.actor?.id)})}if(w.pathname==="/api/onboarding"&&S.method==="GET"){let s=q.listConnections(o.organization.id);return h({drafts:ie.list(o.project.id),artifacts:Ur.list(o.project.id),registries:tn.list(o.organization.id),sourceConnections:s,repositories:s.flatMap((g)=>q.listRepositories(g.id)),project:{id:o.project.id,slug:o.project.slug,name:o.project.name},environments:[...o.environments.values()].map((g)=>({id:g.id,slug:g.slug,name:g.name,kind:g.kind,region:g.region})),resources:o.store.listResources(o.project.id).filter((g)=>g.kind==="application").map((g)=>({id:g.id,slug:g.slug,name:g.name,environmentId:g.environmentId}))})}if(w.pathname==="/api/onboarding/detect"&&S.method==="POST"){let s=await B(S);try{if(s.source?.kind==="git"){let I=q.getConnection(String(s.source.connectionId??"")),A=q.getRepository(String(s.source.repositoryId??""));if(!I||I.organizationId!==o.organization.id||!A||A.connectionId!==I.id)throw Error("Authorized Git repository was not found");let v=typeof s.source.deployKeyId==="string"?q.getDeployKey(s.source.deployKeyId):void 0;if(v&&v.connectionId!==I.id)throw Error("Deploy key does not belong to this connection");let D=Nl(At(Ro(),"ts-cloud-onboarding-git-"));try{let k=await Qo({remote:A.cloneUrl,destination:At(D,"checkout"),ref:String(s.source.ref??A.defaultBranch),sparsePaths:Array.isArray(s.source.sparsePaths)?s.source.sparsePaths.map(String):void 0,binding:{id:"detection",projectId:o.project.id,connectionId:I.id,repositoryId:A.id,repositoryFullName:A.fullName,defaultBranch:A.defaultBranch,monorepoRoot:String(s.source.monorepoRoot??"."),includePaths:[],excludePaths:[],submodules:s.source.submodules===!0,cloneDepth:1,deployKeyId:v?.id,autoDeploy:!1,pullRequestPreviews:!1,status:"active",version:1,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}},{credential:q.getCredential(I.id),deployKey:v?{...v,privateKey:q.getDeployPrivateKey(v.id)}:void 0,timeoutMs:120000});return h({ok:!0,commitSha:k.commitSha,candidates:Nr(ko(k.directory))})}finally{Wr(D,{recursive:!0,force:!0})}}if(Array.isArray(s.files)){if(s.files.length>1e4)throw Error("Detection file-count limit exceeded");let I=s.files.map((A)=>({path:String(A.path??""),size:Number(A.size??0),content:typeof A.content==="string"?A.content.slice(0,262144):void 0}));return h({ok:!0,candidates:Nr(I)})}let g=DP(e,String(s.root??".")),_=AP(e,g);if(_===".."||_.startsWith(`..${yP}`))throw Error("Detection root must stay inside the project");return h({ok:!0,candidates:Nr(ko(g))})}catch(g){return h({ok:!1,error:g instanceof Error?g.message:"Application detection failed."},422)}}if(w.pathname==="/api/onboarding/plan"&&S.method==="POST"){let s=await B(S);try{return h({ok:!0,plan:Fe(s.draft,Array.isArray(s.suppliedSecretNames)?s.suppliedSecretNames.map(String):[])})}catch(g){return h({ok:!1,error:g instanceof Error?g.message:"Application plan could not be generated."},422)}}if(w.pathname==="/api/onboarding/drafts"&&S.method==="POST"){let s=await B(S),g=X(z);try{return h({ok:!0,draft:ie.create({organizationId:o.organization.id,projectId:o.project.id,name:String(s.name??s.draft?.name??"Application draft"),draft:{...s.draft,projectId:o.project.id},step:s.step,suppliedSecretNames:Array.isArray(s.suppliedSecretNames)?s.suppliedSecretNames.map(String):[],actorId:g.actor?.id})},201)}catch(_){return h({ok:!1,error:_ instanceof Error?_.message:"Application draft could not be saved."},422)}}if(w.pathname==="/api/onboarding/drafts"&&S.method==="PATCH"){let s=await B(S),g=X(z),_=ie.get(String(s.id??""));if(!_||_.projectId!==o.project.id)return h({ok:!1,error:"Application draft was not found."},404);try{return h({ok:!0,draft:ie.update(_.id,Number(s.version),{draft:{...s.draft,projectId:o.project.id},step:s.step,suppliedSecretNames:Array.isArray(s.suppliedSecretNames)?s.suppliedSecretNames.map(String):void 0,actorId:g.actor?.id})})}catch(I){return h({ok:!1,error:I instanceof Error?I.message:"Application draft could not be updated."},409)}}if(w.pathname==="/api/onboarding/artifacts"&&S.method==="POST"){let s=X(z);if(Number(S.headers.get("content-length")??0)>104857600)return h({ok:!1,error:"Artifact exceeds the 100 MB upload limit."},413);try{let _=new Uint8Array(await S.arrayBuffer());return h({ok:!0,artifact:Ur.create({organizationId:o.organization.id,projectId:o.project.id,filename:S.headers.get("x-artifact-filename")??"application.zip",bytes:_,actorId:s.actor?.id})},201)}catch(_){return h({ok:!1,error:_ instanceof Error?_.message:"Artifact could not be inspected."},422)}}if(w.pathname==="/api/onboarding/registries"&&S.method==="POST"){let s=await B(S),g=X(z);try{return h({ok:!0,registry:tn.create({organizationId:o.organization.id,provider:s.provider,name:String(s.name??"Container registry"),host:String(s.host??""),credential:s.token||s.password?{username:typeof s.username==="string"?s.username:void 0,password:typeof s.password==="string"?s.password:void 0,token:typeof s.token==="string"?s.token:void 0}:void 0,credentialExpiresAt:typeof s.credentialExpiresAt==="string"?s.credentialExpiresAt:void 0,actorId:g.actor?.id})},201)}catch(_){return h({ok:!1,error:_ instanceof Error?_.message:"Registry connection could not be created."},422)}}if(w.pathname==="/api/onboarding/registries"&&S.method==="PATCH"){let s=await B(S),g=X(z),_=tn.get(String(s.id??""));if(!_||_.organizationId!==o.organization.id)return h({ok:!1,error:"Registry connection was not found."},404);try{if(s.action==="test")return h({ok:!0,registry:await tn.test(_.id,{image:typeof s.image==="string"?s.image:void 0})});if(s.action==="rotate")return h({ok:!0,registry:tn.rotate(_.id,{username:typeof s.username==="string"?s.username:void 0,password:typeof s.password==="string"?s.password:void 0,token:typeof s.token==="string"?s.token:void 0},{expiresAt:typeof s.expiresAt==="string"?s.expiresAt:void 0,actorId:g.actor?.id})});return h({ok:!1,error:"Registry action must be test or rotate."},422)}catch(I){return h({ok:!1,error:I instanceof Error?I.message:"Registry connection could not be updated."},422)}}if(w.pathname==="/api/onboarding/registries"&&S.method==="DELETE"){let s=await B(S),g=X(z),_=tn.get(String(s.id??""));if(!_||_.organizationId!==o.organization.id)return h({ok:!1,error:"Registry connection was not found."},404);let I=ie.list(o.project.id).filter((A)=>A.input.source.kind==="image"&&A.input.source.registryConnectionId===_.id||A.input.build.kind==="prebuilt_image"&&A.input.build.registryConnectionId===_.id);if(s.preview===!0)return h({ok:!0,preview:!0,affectedDrafts:I});return h({ok:!0,registry:tn.disconnect(_.id,g.actor?.id),affectedDrafts:I})}if(w.pathname==="/api/onboarding/apply"&&S.method==="POST"){let s=await B(S),g=X(z);try{let _=wc({controlPlane:o.store,drafts:ie,draftId:String(s.id??""),expectedVersion:Number(s.version),confirmEnvironment:String(s.confirmEnvironment??""),actorId:g.actor?.id});return h({ok:!0,resource:_.resource,operation:_.operation,plan:_.plan},202)}catch(_){return h({ok:!1,error:_ instanceof Error?_.message:"Application plan could not be applied."},422)}}if(w.pathname==="/api/sources"&&S.method==="GET"){let s=q.listConnections(o.organization.id);return h({connections:s,bindings:q.listBindings({projectId:o.project.id}),repositories:s.flatMap((g)=>q.listRepositories(g.id)),deployKeys:s.flatMap((g)=>q.listDeployKeys(g.id)),webhooks:s.flatMap((g)=>q.listWebhooks(g.id)).map((g)=>({...g,deliveries:q.listDeliveries(g.id,20)})),project:{id:o.project.id,slug:o.project.slug},environment:Ye(o,String(U)),resources:o.store.listResources(o.project.id,Ye(o,String(U)).environmentId).filter((g)=>g.kind==="application").map((g)=>({id:g.id,slug:g.slug,name:g.name}))})}if(w.pathname==="/api/sources/connections"&&S.method==="POST"){let s=await B(S),g=X(z),_=String(s.provider??"");if(!["github","gitlab","bitbucket","gitea","generic_https","generic_ssh"].includes(_))return h({ok:!1,error:"A supported Git provider is required."},422);try{let I=_==="github"&&(s.privateKey||s.appId)?{appId:typeof s.appId==="string"?s.appId:void 0,installationId:typeof s.installationId==="string"?s.installationId:void 0,privateKey:typeof s.privateKey==="string"?s.privateKey:void 0}:_!=="generic_ssh"&&s.token?{token:typeof s.token==="string"?s.token:void 0,username:typeof s.username==="string"?s.username:void 0}:void 0,A={github:"https://github.com",gitlab:"https://gitlab.com",bitbucket:"https://bitbucket.org",gitea:"https://gitea.com"},v,D,k;if(o.store.database.transaction(()=>{if(v=q.createConnection({organizationId:o.organization.id,provider:_,name:String(s.name??_),host:String(s.host??A[_]??""),owner:typeof s.owner==="string"?s.owner:void 0,authKind:s.authKind,credential:I,grantedScopes:Array.isArray(s.grantedScopes)?s.grantedScopes.map(String):[],credentialExpiresAt:typeof s.credentialExpiresAt==="string"?s.credentialExpiresAt:void 0,createdByActorId:g.actor?.id}),typeof s.repositoryUrl==="string"&&typeof s.repositoryFullName==="string")D=q.upsertRepository({connectionId:v.id,providerRepositoryId:`manual:${s.repositoryFullName}`,fullName:s.repositoryFullName,cloneUrl:s.repositoryUrl,defaultBranch:String(s.defaultBranch??"main"),visibility:"unknown",archived:!1,metadata:{source:"manual"}});if(_==="generic_ssh")k=q.createDeployKey({connectionId:v.id,name:String(s.deployKeyName??"Repository deploy key"),publicKey:String(s.publicKey??""),privateKey:String(s.deployPrivateKey??""),host:String(s.sshHost??""),hostKey:String(s.hostKey??""),actorId:g.actor?.id})})(),s.test===!0)v=await Go(q,v.id,D?.id);return h({ok:!0,connection:v,repository:D,deployKey:k},201)}catch(I){return h({ok:!1,error:I instanceof Error?I.message:"Source connection could not be created."},422)}}if(w.pathname==="/api/sources/connections"&&S.method==="PATCH"){let s=await B(S),g=X(z),_=q.getConnection(String(s.id??""));if(!_||_.organizationId!==o.organization.id)return h({ok:!1,error:"Source connection was not found."},404);try{if(s.action==="test")return h({ok:!0,connection:await Go(q,_.id,typeof s.repositoryId==="string"?s.repositoryId:void 0)});if(s.action==="rotate")return h({ok:!0,connection:q.rotateCredential(_.id,{token:typeof s.token==="string"?s.token:void 0,username:typeof s.username==="string"?s.username:void 0,appId:typeof s.appId==="string"?s.appId:void 0,installationId:typeof s.installationId==="string"?s.installationId:void 0,privateKey:typeof s.privateKey==="string"?s.privateKey:void 0},{expiresAt:typeof s.expiresAt==="string"?s.expiresAt:void 0,actorId:g.actor?.id})});return h({ok:!1,error:"Connection action must be test or rotate."},422)}catch(I){return h({ok:!1,error:I instanceof Error?I.message:"Source connection could not be updated."},422)}}if(w.pathname==="/api/sources/connections"&&S.method==="DELETE"){let s=await B(S),g=X(z),_=q.getConnection(String(s.id??""));if(!_||_.organizationId!==o.organization.id)return h({ok:!1,error:"Source connection was not found."},404);let I=q.listBindings({connectionId:_.id,status:"active"});if(s.preview===!0)return h({ok:!0,preview:!0,affectedBindings:I});return h({ok:!0,...q.disconnectConnection(_.id,g.actor?.id)})}if(w.pathname==="/api/sources/deploy-keys"&&S.method==="POST"){let s=await B(S),g=X(z),_=q.getConnection(String(s.connectionId??""));if(!_||_.organizationId!==o.organization.id)return h({ok:!1,error:"Source connection was not found."},404);try{return h({ok:!0,deployKey:q.createDeployKey({connectionId:_.id,name:String(s.name??"Repository deploy key"),publicKey:String(s.publicKey??""),privateKey:String(s.privateKey??""),host:String(s.host??""),hostKey:String(s.hostKey??""),actorId:g.actor?.id})},201)}catch(I){return h({ok:!1,error:I instanceof Error?I.message:"Deploy key could not be stored."},422)}}if(w.pathname==="/api/sources/deploy-keys"&&S.method==="DELETE"){let s=await B(S),g=X(z),_=q.getDeployKey(String(s.id??"")),I=_?q.getConnection(_.connectionId):void 0;if(!_||!I||I.organizationId!==o.organization.id)return h({ok:!1,error:"Deploy key was not found."},404);let A=q.listBindings({connectionId:I.id}).filter((v)=>v.deployKeyId===_.id);if(s.preview===!0)return h({ok:!0,preview:!0,affectedBindings:A});return h({ok:!0,...q.revokeDeployKey(_.id,g.actor?.id)})}if(w.pathname==="/api/sources/repositories/sync"&&S.method==="POST"){let s=await B(S),g=q.getConnection(String(s.connectionId??""));if(!g||g.organizationId!==o.organization.id)return h({ok:!1,error:"Source connection was not found."},404);try{return h({ok:!0,repositories:await Pc(q,String(s.connectionId??""),{search:typeof s.search==="string"?s.search:void 0})})}catch(_){return h({ok:!1,error:_ instanceof Error?_.message:"Repositories could not be synchronized."},422)}}if(w.pathname==="/api/sources/references"&&S.method==="GET"){let s=q.getConnection(String(w.searchParams.get("connectionId")??""));if(!s||s.organizationId!==o.organization.id)return h({ok:!1,error:"Source connection was not found."},404);try{return h(await $c(q,{connectionId:String(w.searchParams.get("connectionId")??""),repository:String(w.searchParams.get("repository")??""),repositoryId:w.searchParams.get("repositoryId")??void 0,deployKeyId:w.searchParams.get("deployKeyId")??void 0,type:w.searchParams.get("type")==="tags"?"tags":"branches",cursor:w.searchParams.get("cursor")??void 0}))}catch(g){return h({ok:!1,error:g instanceof Error?g.message:"References could not be listed."},422)}}if(w.pathname==="/api/sources/bindings"&&S.method==="POST"){let s=await B(S),g=X(z),_=Ye(o,String(U)),I=q.getConnection(String(s.connectionId??""));if(!I||I.organizationId!==o.organization.id)return h({ok:!1,error:"Source connection was not found."},404);try{return h({ok:!0,binding:q.createBinding({projectId:o.project.id,environmentId:_.environmentId,resourceId:typeof s.resourceId==="string"?s.resourceId:void 0,connectionId:String(s.connectionId??""),repositoryId:typeof s.repositoryId==="string"?s.repositoryId:void 0,repositoryFullName:String(s.repositoryFullName??""),defaultBranch:String(s.defaultBranch??"main"),branchRule:typeof s.branchRule==="string"?s.branchRule:void 0,tagRule:typeof s.tagRule==="string"?s.tagRule:void 0,monorepoRoot:String(s.monorepoRoot??"."),includePaths:Array.isArray(s.includePaths)?s.includePaths.map(String):[],excludePaths:Array.isArray(s.excludePaths)?s.excludePaths.map(String):[],submodules:s.submodules===!0,cloneDepth:s.cloneDepth?Number(s.cloneDepth):void 0,deployKeyId:typeof s.deployKeyId==="string"&&s.deployKeyId?s.deployKeyId:void 0,autoDeploy:s.autoDeploy!==!1,pullRequestPreviews:s.pullRequestPreviews!==!1,actorId:g.actor?.id})},201)}catch(A){return h({ok:!1,error:A instanceof Error?A.message:"Source binding could not be created."},422)}}if(w.pathname==="/api/sources/bindings"&&S.method==="PATCH"){let s=await B(S),g=X(z),_=q.getBinding(String(s.id??""));if(!_||_.projectId!==o.project.id)return h({ok:!1,error:"Source binding was not found."},404);try{return h({ok:!0,binding:q.updateBinding(_.id,Number(s.version),{defaultBranch:s.defaultBranch,branchRule:s.branchRule,tagRule:s.tagRule,monorepoRoot:s.monorepoRoot,includePaths:s.includePaths,excludePaths:s.excludePaths,submodules:s.submodules,cloneDepth:s.cloneDepth,deployKeyId:s.deployKeyId,autoDeploy:s.autoDeploy,pullRequestPreviews:s.pullRequestPreviews,status:s.status,disabledReason:s.disabledReason,actorId:g.actor?.id})})}catch(I){return h({ok:!1,error:I instanceof Error?I.message:"Source binding could not be updated."},409)}}if(w.pathname==="/api/sources/webhooks"&&S.method==="POST"){let s=await B(S),g=q.getConnection(String(s.connectionId??""));if(!g||g.organizationId!==o.organization.id)return h({ok:!1,error:"Source connection was not found."},404);try{let _=q.createWebhook({connectionId:String(s.connectionId??""),repositoryId:typeof s.repositoryId==="string"?s.repositoryId:void 0,repositoryFullName:String(s.repositoryFullName??""),events:Array.isArray(s.events)?s.events.map(String):void 0,secret:typeof s.secret==="string"?s.secret:void 0}),I=process.env.TS_CLOUD_WEBHOOK_BASE_URL?.trim()||at,A=I?Qr(I,_.webhook):void 0,v=s.reconcile!==!1&&I?await bi(q,_.webhook.id,I):_.webhook;return h({ok:!0,webhook:v,endpoint:A,endpointRevealOnce:!0},201)}catch(_){return h({ok:!1,error:_ instanceof Error?_.message:"Source webhook could not be created."},422)}}if(w.pathname==="/api/sources/webhooks"&&S.method==="PATCH"){let s=await B(S),g=process.env.TS_CLOUD_WEBHOOK_BASE_URL?.trim()||at,_=q.getWebhook(String(s.id??"")),I=_?q.getConnection(_.connectionId):void 0;if(!_||!I||I.organizationId!==o.organization.id)return h({ok:!1,error:"Source webhook was not found."},404);if(!g)return h({ok:!1,error:"Set TS_CLOUD_WEBHOOK_BASE_URL to reconcile provider webhooks."},422);try{return h({ok:!0,webhook:await bi(q,String(s.id??""),g)})}catch(A){return h({ok:!1,error:A instanceof Error?A.message:"Source webhook could not be reconciled."},422)}}if(w.pathname==="/api/sources/webhooks"&&S.method==="DELETE"){let s=await B(S),g=q.getWebhook(String(s.id??"")),_=g?q.getConnection(g.connectionId):void 0;if(!g||!_||_.organizationId!==o.organization.id)return h({ok:!1,error:"Source webhook was not found."},404);try{return h({ok:!0,webhook:await mg(q,String(s.id??""))})}catch(I){return h({ok:!1,error:I instanceof Error?I.message:"Source webhook could not be removed."},422)}}if(w.pathname==="/api/security/posture"&&S.method==="GET"){let s=Ye(o,String(U)),g=ot.listFindings({...s,limit:500});return h({scope:s,summary:ot.summary(s.organizationId,s.projectId,s.environmentId),findings:g,scans:ot.listScanRuns({...s,limit:100}),policies:ot.listPolicies(s.organizationId).filter((_)=>!_.environmentId||_.environmentId===s.environmentId),waivers:g.flatMap((_)=>ot.listWaivers(_.id)),decisions:ot.listDecisions(s.environmentId,50),actors:o.store.listMemberships(o.organization.id).map((_)=>o.store.getActor(_.actorId)).filter(Boolean)})}if(w.pathname==="/api/security/export"&&S.method==="GET")return h(ot.exportPosture(o.organization.id));if(w.pathname==="/api/security/scan"&&S.method==="POST"){let s=Ye(o,String(U)),g=await new Cr(ot).run(new mi,{...s,artifactRoot:e}),_=Qd(ot,s,Ct??{});return h({ok:!0,source:g,host:_,summary:ot.summary(s.organizationId,s.projectId,s.environmentId)})}if(w.pathname==="/api/security/review"&&S.method==="POST")try{let s=Ye(o,String(U));return h({ok:!0,...Gd(ot,{scope:s,desiredConfigHash:o.project.desiredConfigHash})})}catch(s){return h({ok:!1,error:s instanceof Error?s.message:"Security change review failed."},409)}if(w.pathname==="/api/security/policies"&&S.method==="POST"){let s=await B(S),g=X(z);if(!g.actor)return h({ok:!1,error:"An organization actor is required."},403);try{let _=ot.createPolicy({organizationId:o.organization.id,environmentId:s.environmentId===null?void 0:String(s.environmentId??Ye(o,String(U)).environmentId),name:String(s.name??""),scannerFailMode:s.scannerFailMode==="open"?"open":"closed",requiredScanners:Array.isArray(s.requiredScanners)?s.requiredScanners.map(String):[],rules:Array.isArray(s.rules)?s.rules.map((I)=>({minimumSeverity:String(I.minimumSeverity),action:String(I.action),scannerId:I.scannerId?String(I.scannerId):void 0})):[],actorId:g.actor.id});return h({ok:!0,policy:_},201)}catch(_){return h({ok:!1,error:_ instanceof Error?_.message:"Security policy could not be created."},422)}}if(w.pathname==="/api/security/policies"&&S.method==="PATCH"){let s=await B(S),g=X(z),_=ot.getPolicy(String(s.id??""));if(!g.actor||!_||_.organizationId!==o.organization.id)return h({ok:!1,error:"Security policy was not found."},404);try{return h({ok:!0,policy:ot.updatePolicy(_.id,Number(s.version),{name:typeof s.name==="string"?s.name:void 0,scannerFailMode:s.scannerFailMode==="open"||s.scannerFailMode==="closed"?s.scannerFailMode:void 0,requiredScanners:Array.isArray(s.requiredScanners)?s.requiredScanners.map(String):void 0,rules:Array.isArray(s.rules)?s.rules.map((I)=>({minimumSeverity:String(I.minimumSeverity),action:String(I.action),scannerId:I.scannerId?String(I.scannerId):void 0})):void 0,enabled:typeof s.enabled==="boolean"?s.enabled:void 0,actorId:g.actor.id})})}catch(I){return h({ok:!1,error:I instanceof Error?I.message:"Security policy could not be updated."},409)}}if(w.pathname==="/api/security/waivers"&&S.method==="POST"){let s=await B(S),g=X(z);if(!g.actor)return h({ok:!1,error:"An organization actor is required."},403);try{return h({ok:!0,waiver:ot.createWaiver({findingId:String(s.findingId??""),policyId:typeof s.policyId==="string"?s.policyId:void 0,reason:String(s.reason??""),referenceUrl:typeof s.referenceUrl==="string"?s.referenceUrl:void 0,expiresAt:String(s.expiresAt??""),actorId:g.actor.id})},201)}catch(_){return h({ok:!1,error:_ instanceof Error?_.message:"Security waiver could not be created."},422)}}if(w.pathname==="/api/security/waivers"&&S.method==="DELETE"){let s=await B(S),g=X(z);if(!g.actor)return h({ok:!1,error:"An organization actor is required."},403);try{return h({ok:!0,waiver:ot.revokeWaiver(String(s.id??""),g.actor.id)})}catch(_){return h({ok:!1,error:_ instanceof Error?_.message:"Security waiver could not be revoked."},404)}}if(w.pathname==="/api/security/findings"&&S.method==="PATCH"){let s=await B(S),g=X(z),_=ot.getFinding(String(s.id??""));if(!g.actor||!_||_.organizationId!==o.organization.id)return h({ok:!1,error:"Security finding was not found."},404);try{let I=s.action==="acknowledge"?ot.acknowledgeFinding(_.id,g.actor.id):ot.assignFinding(_.id,typeof s.ownerActorId==="string"&&s.ownerActorId?s.ownerActorId:void 0,g.actor.id);return h({ok:!0,finding:I})}catch(I){return h({ok:!1,error:I instanceof Error?I.message:"Security finding could not be updated."},422)}}if(w.pathname==="/api/security/comments"&&S.method==="POST"){let s=await B(S),g=X(z);if(!g.actor)return h({ok:!1,error:"An organization actor is required."},403);try{return h({ok:!0,comment:ot.addComment({findingId:String(s.findingId??""),actorId:g.actor.id,body:String(s.body??""),referenceUrl:typeof s.referenceUrl==="string"?s.referenceUrl:void 0})},201)}catch(_){return h({ok:!1,error:_ instanceof Error?_.message:"Comment could not be saved."},422)}}if(w.pathname==="/api/auth/sessions"&&S.method==="GET"){let s=Bt.resolveSession(S);return h({currentSessionId:s?.id,sessions:s?F.listSessions(s.identityId,{includeInactive:!0}):[]})}if(w.pathname==="/api/auth/sessions"&&S.method==="DELETE"){let s=await B(S),g=Bt.resolveSession(S);if(!g)return h({ok:!1,error:"Sign in again to manage sessions."},401);let _=String(s.id??""),I=F.revokeSession(g.identityId,_),A=_===g.id&&I?{"set-cookie":eo({secure:Ln})}:void 0;return h({ok:I,signedOut:_===g.id&&I},I?200:404,A)}if(w.pathname==="/api/auth/sessions/revoke-others"&&S.method==="POST"){let s=Bt.resolveSession(S);if(!s)return h({ok:!1,error:"Sign in again to manage sessions."},401);return h({ok:!0,revoked:F.revokeOtherSessions(s.identityId,s.id)})}if(w.pathname==="/api/auth/password/change"&&S.method==="POST"){let s=await B(S),g=String(s.currentPassword??""),_=String(s.password??""),I=X(z),A=I.actor?F.getIdentityByActor(I.actor.id):void 0;if(!A||!Xe(g,A.passwordHash))return h({ok:!1,error:"Current password is incorrect."},401);if(_.length<12)return h({ok:!1,error:"New password must be at least 12 characters."},422);if(Xe(_,A.passwordHash))return h({ok:!1,error:"Choose a different password."},409);let v=tr(_),D=F.updatePassword(A.id,v);io(e,D.username,v);let k=Rc(D.id,S,it.requestIP(S)?.address??"unknown");return o.store.appendEvent({organizationId:o.organization.id,actorId:D.actorId,type:"auth.password.changed"}),h({ok:!0,message:"Password changed and other sessions were signed out."},200,{"set-cookie":Ei(k.token,{secure:Ln,maxAgeMs:Qn})})}if(w.pathname==="/api/auth/mfa/enroll"&&S.method==="POST"){let s=await B(S),g=Bt.resolveSession(S),_=X(z),I=_.actor?F.getIdentityByActor(_.actor.id):void 0;if(!g||!I)return h({ok:!1,error:"Sign in again before enabling MFA."},401);if(!Xe(String(s.password??""),I.passwordHash))return h({ok:!1,error:"Current password is incorrect."},401);try{let A=F.beginTotpEnrollment(I.id,{issuer:o.organization.name});return o.store.appendEvent({organizationId:o.organization.id,actorId:I.actorId,type:"auth.mfa.enrollment.started"}),h({factor:A.factor,secret:A.secret,uri:A.uri})}catch(A){return h({ok:!1,error:A instanceof Error?A.message:"MFA enrollment failed."},409)}}if(w.pathname==="/api/auth/mfa/verify"&&S.method==="POST"){let s=await B(S),g=Bt.resolveSession(S),_=X(z),I=_.actor?F.getIdentityByActor(_.actor.id):void 0;if(!g||!I)return h({ok:!1,error:"Sign in again before enabling MFA."},401);try{let A=F.verifyTotpEnrollment(I.id,String(s.code??""));return F.markSessionStepUp(g.id,!0),o.store.appendEvent({organizationId:o.organization.id,actorId:I.actorId,type:"auth.mfa.enabled",payload:{recoveryCodeCount:A.recoveryCodes.length}}),h(A)}catch(A){return h({ok:!1,error:A instanceof Error?A.message:"MFA enrollment failed."},422)}}if(w.pathname==="/api/auth/mfa"&&S.method==="DELETE"){let s=await B(S),g=Bt.resolveSession(S),_=X(z),I=_.actor?F.getIdentityByActor(_.actor.id):void 0;if(!g||!I||!Xe(String(s.password??""),I.passwordHash))return h({ok:!1,error:"Current password is incorrect."},401);let A=F.verifyMfaCode(I.id,String(s.code??""));if(!A.valid||!A.method)return h({ok:!1,error:"Authenticator or recovery code is incorrect."},401);return F.disableMfa(I.id),F.revokeOtherSessions(I.id,g.id),F.markSessionStepUp(g.id),o.store.appendEvent({organizationId:o.organization.id,actorId:I.actorId,type:"auth.mfa.disabled",payload:{method:A.method}}),h({ok:!0})}if(w.pathname==="/api/auth/step-up"&&S.method==="POST"){let s=await B(S),g=Bt.resolveSession(S),_=X(z),I=_.actor?F.getIdentityByActor(_.actor.id):void 0;if(!g||!I||!Xe(String(s.password??""),I.passwordHash))return h({ok:!1,error:"Current password is incorrect."},401);let A=F.getMfaFactor(I.id);if(A?.state==="active"){if(!F.verifyMfaCode(I.id,String(s.code??"")).valid)return h({ok:!1,error:"Authenticator or recovery code is incorrect."},401)}let v=F.markSessionStepUp(g.id,A?.state==="active");return o.store.appendEvent({organizationId:o.organization.id,actorId:I.actorId,type:"auth.step_up.succeeded",payload:{mfa:A?.state==="active"}}),h({ok:!0,recentAuthAt:v.recentAuthAt})}if(w.pathname==="/api/terminal"){if(!b)return h({ok:!1,error:"The web terminal is disabled."},403);if(it.upgrade(S))return;return Eo("WebSocket upgrade failed",400)}if(w.pathname==="/api/health"){let s=o.store.health();return h({ok:!0,cwd:e,environment:U,environments:u,uiRoot:await me(z,U),liveData:Q.size>0,terminal:b,localPackage:import.meta.url.includes("/Code/Libraries/ts-cloud/"),controlPlane:{schemaVersion:s.schemaVersion,supportedSchemaVersion:s.supportedSchemaVersion,integrity:s.integrity,pendingRetryableOperations:s.pendingRetryableOperations}})}if(w.pathname==="/api/control-plane/operations"){let s=w.searchParams.get("state"),g=s&&["queued","running","succeeded","failed","cancelled","timed_out"].includes(s)?s:void 0;return h({operations:o.store.listOperations({projectId:o.project.id,state:g,kind:w.searchParams.get("kind")??void 0,limit:Number(w.searchParams.get("limit"))||100})})}if(w.pathname==="/api/queue"&&S.method==="GET"){let s=w.searchParams.get("state"),g=s&&["queued","running","succeeded","failed","cancelled","timed_out"].includes(s)?s:void 0,_=yt.list({projectId:o.project.id,state:g,limit:Number(w.searchParams.get("limit"))||250}).filter((I)=>jr(z,I.operation.id,"deployments:read")).map((I)=>{let A=I.operation.resourceId?o.store.getResource(I.operation.resourceId):void 0,v=I.operation.environmentId?o.store.listEnvironments(o.project.id).find((W)=>W.id===I.operation.environmentId):void 0,D=I.operation.actorId?o.store.getActor(I.operation.actorId):void 0,k=I.operation.input;return{...I,target:A?{id:A.id,name:A.name,slug:A.slug,kind:A.kind}:v?{id:v.id,name:v.name,slug:v.slug,kind:"environment"}:{id:o.project.id,name:o.project.name,slug:o.project.slug,kind:"project"},actor:D?{id:D.id,name:D.displayName,kind:D.kind}:void 0,commit:k.revision??k.source?.commitSha??null}});return h({operations:_,concurrency:yt.limits})}if(w.pathname==="/api/queue/logs"&&S.method==="GET"){let s=String(w.searchParams.get("id")??"");if(!jr(z,s,"deployments:read"))return h({ok:!1,error:"Operation was not found in this scope."},404);let g=yt.logs(s,{after:Number(w.searchParams.get("after"))||0,limit:Number(w.searchParams.get("limit"))||500});return h({entries:g,cursor:g.at(-1)?.sequence??(Number(w.searchParams.get("after"))||0),operation:o.store.getOperation(s)})}if(w.pathname==="/api/queue/stream"&&S.method==="GET"){let s=String(w.searchParams.get("id")??"");if(!jr(z,s,"deployments:read"))return h({ok:!1,error:"Operation was not found in this scope."},404);let g=S.headers.get("last-event-id")?.trim(),_=Number(g||w.searchParams.get("after")||0),I=new TextEncoder,A,v=!1,D=new ReadableStream({start(k){let W=()=>{if(v)return;let T=Bt.resolveUser(S);if(!T||!jr(T,s,"deployments:read")){if(v=!0,A)clearInterval(A);k.close();return}let et=yt.logs(s,{after:_,limit:500});for(let K of et)_=K.sequence,k.enqueue(I.encode(`id: ${K.sequence}
|
|
488
|
-
event: log
|
|
489
|
-
data: ${JSON.stringify(K)}
|
|
490
|
-
|
|
491
|
-
`));let j=o.store.getOperation(s);if(j&&["succeeded","failed","cancelled","timed_out"].includes(j.state)&&yt.logs(s,{after:_,limit:1}).length===0){if(v=!0,A)clearInterval(A);k.enqueue(I.encode(`event: complete
|
|
492
|
-
data: ${JSON.stringify({state:j.state,cursor:_})}
|
|
493
|
-
|
|
494
|
-
`)),k.close()}};if(W(),!v)A=setInterval(W,500);S.signal.addEventListener("abort",()=>{if(v=!0,A)clearInterval(A);try{k.close()}catch{}},{once:!0})},cancel(){if(v=!0,A)clearInterval(A)}});return new Response(D,{headers:{"content-type":"text/event-stream","cache-control":"no-store","x-accel-buffering":"no"}})}if(w.pathname==="/api/queue/cancel"&&S.method==="POST"){let s=await B(S),g=String(s.id??"");if(!jr(z,g,"deployments:cancel"))return h({ok:!1,error:"Operation was not found or cannot be cancelled in this scope."},404);let _=Gt(o.store,z);try{return h({ok:!0,operation:yt.requestCancellation(g,_.id)})}catch(I){return h({ok:!1,error:I instanceof Error?I.message:"Cancellation failed."},409)}}if(w.pathname==="/api/queue/retry"&&S.method==="POST"){let s=await B(S),g=String(s.id??"");if(!jr(z,g,"deployments:create"))return h({ok:!1,error:"Operation was not found or cannot be retried in this scope."},404);let _=Gt(o.store,z);try{return h({ok:!0,operation:yt.retry(g,String(s.errorClass??"manual"),{delayMs:Number(s.delayMs)||0,actorId:_.id})})}catch(I){return h({ok:!1,error:I instanceof Error?I.message:"Retry failed."},409)}}if(w.pathname==="/api/queue/settings"&&S.method==="GET")return h({concurrency:yt.limits});if(w.pathname==="/api/queue/settings"&&S.method==="PATCH"){let s=await B(S);if(s.confirm!=="update queue limits")return h({ok:!1,error:'Type "update queue limits" to confirm production concurrency changes.'},409);let g=Gt(o.store,z);return h({ok:!0,concurrency:yt.configureConcurrency(s.concurrency??{},{organizationId:o.organization.id,actorId:g.id})})}if(w.pathname==="/api/queue/history"&&S.method==="DELETE"){let s=await B(S);if(s.confirm!=="clear completed")return h({ok:!1,error:'Type "clear completed" to confirm retained history cleanup.'},409);let g=Gt(o.store,z);return h({ok:!0,deleted:yt.clearCompleted({projectId:o.project.id,before:typeof s.before==="string"?s.before:void 0,actorId:g.id})})}if(w.pathname==="/api/previews"&&S.method==="GET"){let s=Ht.previews.listInstances({projectId:o.project.id}).filter((I)=>Kt(z,I.resourceId,"deployments:read")),g=Ht.previews.listDefinitions(o.project.id).filter((I)=>Kt(z,I.resourceId,"project:read")),_=o.store.listResources(o.project.id).filter((I)=>I.kind==="application"&&Kt(z,I.id,"project:read")).map((I)=>({id:I.id,slug:I.slug,name:I.name,environmentId:I.environmentId}));return h({previews:s,definitions:g,resources:_,environments:[...o.environments.values()]})}if(w.pathname==="/api/releases"&&S.method==="GET"){let s=[...o.environments.values()],g=o.store.listResources(o.project.id).filter((A)=>Kt(z,A.id,"deployments:read")),_=new Set(g.map((A)=>A.id)),I=Oe.releases.list({projectId:o.project.id}).filter((A)=>_.has(A.resourceId)).map((A)=>{let v=g.find((W)=>W.id===A.resourceId),D=s.find((W)=>W.id===A.environmentId),k=A.previousReleaseId?Oe.releases.get(A.previousReleaseId):void 0;return{...A,resource:v?{id:v.id,name:v.name,slug:v.slug,provider:v.provider}:void 0,environment:D?{id:D.id,name:D.name,slug:D.slug,kind:D.kind}:void 0,artifact:Oe.releases.getArtifact(A.artifactId),transitions:Oe.releases.transitions(A.id),approvals:Oe.releases.approvals(A.id),previous:k,comparison:k?Oe.releases.compare(k.id,A.id):void 0,capabilities:Ji({kind:A.kind,provider:v?.provider,hasHealthGate:!!A.healthGate,replicas:Number(A.manifest?.replicas)||1})}});return h({releases:I,resources:g.map((A)=>({id:A.id,name:A.name,slug:A.slug,environmentId:A.environmentId,provider:A.provider})),environments:s})}if(w.pathname==="/api/releases/action"&&S.method==="POST"){let s=await B(S),g=Oe.releases.get(String(s.id??"")),_=String(s.action??"");if(!g||!Kt(z,g.resourceId,"deployments:create"))return h({ok:!1,error:"Release was not found in this scope."},404);let I=Gt(o.store,z);try{if(_==="activate")return h({ok:!0,operation:Oe.enqueueActivation(g,{actorId:I.id})});if(_==="rollback"){let A=o.store.getResource(g.resourceId);if(s.confirm!==A?.slug)return h({ok:!1,error:`Type "${A?.slug??""}" to confirm rollback.`},409);return h({ok:!0,operation:Oe.enqueueRollback(g,{actorId:I.id,targetReleaseId:typeof s.targetReleaseId==="string"?s.targetReleaseId:void 0})})}if(_==="approve"){let A=o.store.listEnvironments(g.projectId).find((v)=>v.id===g.environmentId);if(s.confirm!==A?.slug)return h({ok:!1,error:`Type "${A?.slug??""}" to confirm the environment gate.`},409);return h({ok:!0,release:Oe.releases.approve(g.id,{actorId:I.id,decision:s.decision==="rejected"?"rejected":"approved",comment:typeof s.comment==="string"?s.comment:void 0})})}if(_==="pin")return h({ok:!0,release:Oe.releases.pin(g.id,s.pinned!==!1,typeof s.reason==="string"?s.reason:void 0)});if(_==="promote"){let A=o.store.getResource(String(s.targetResourceId??"")),v=A?o.store.listEnvironments(g.projectId).find((D)=>D.id===A.environmentId):void 0;if(!A||!v||!Kt(z,A.id,"deployments:create"))return h({ok:!1,error:"Promotion target was not found in this scope."},404);if(s.confirm!==v.slug)return h({ok:!1,error:`Type "${v.slug}" to confirm promotion.`},409);return h({ok:!0,release:Oe.releases.promote(g.id,{targetEnvironmentId:v.id,targetResourceId:A.id,config:s.config&&typeof s.config==="object"?s.config:{},strategy:typeof s.strategy==="string"?s.strategy:void 0,actorId:I.id,approvalRequired:s.approvalRequired===!0})})}return h({ok:!1,error:"Unsupported release action."},422)}catch(A){return h({ok:!1,error:A instanceof Error?A.message:"Release action failed."},409)}}if(w.pathname==="/api/compose"&&S.method==="GET"){let s=Hn.applications.list({projectId:o.project.id}).filter((g)=>Kt(z,g.resourceId,"applications:read")).map((g)=>({...g,services:Hn.applications.services(g.id)}));return h({applications:s,templates:kc(),environments:[...o.environments.values()]})}if(w.pathname==="/api/compose/preview"&&S.method==="POST"){let s=await B(S),g=String(s.environmentId??"");if(!ki(z,g,"applications:manage"))return h({ok:!1,error:"Environment was not found in this scope."},404);try{return h({ok:!0,result:Hn.applications.preview(String(s.source??""),{name:String(s.name??""),slug:typeof s.slug==="string"?s.slug:void 0,projectId:o.project.id,environmentId:g})})}catch(_){return h({ok:!1,error:_ instanceof Error?_.message:"Compose could not be parsed."},422)}}if((w.pathname==="/api/compose/import"||w.pathname==="/api/compose/template")&&S.method==="POST"){let s=await B(S),g=String(s.environmentId??"");if(!ki(z,g,"applications:manage"))return h({ok:!1,error:"Environment was not found in this scope."},404);let _=Gt(o.store,z);try{let I=w.pathname.endsWith("/template")?Hn.applications.fromTemplate(String(s.templateId??""),s.inputs&&typeof s.inputs==="object"?s.inputs:{},{name:String(s.name??""),projectId:o.project.id,environmentId:g,version:typeof s.templateVersion==="string"?s.templateVersion:void 0,createdByActorId:_.id}):Hn.applications.import(String(s.source??""),{name:String(s.name??""),slug:typeof s.slug==="string"?s.slug:void 0,projectId:o.project.id,environmentId:g,createdByActorId:_.id});return h({ok:!0,application:I.application,diagnostics:I.parsed.diagnostics})}catch(I){return h({ok:!1,error:I instanceof Error?I.message:"Compose application could not be saved."},422)}}if(w.pathname==="/api/compose/action"&&S.method==="POST"){let s=await B(S),g=Hn.applications.get(String(s.id??"")),_=String(s.action??""),I=_==="delete"||_==="stop"?"deployments:cancel":"deployments:create";if(!g||!Kt(z,g.resourceId,I))return h({ok:!1,error:"Compose application was not found in this scope."},404);try{let A=Gt(o.store,z);return h({ok:!0,operation:Hn.enqueue(g,_,{actorId:A.id,service:typeof s.service==="string"?s.service:void 0,replicas:Number.isFinite(Number(s.replicas))?Number(s.replicas):void 0,removeVolumes:s.removeVolumes===!0,confirmation:typeof s.confirm==="string"?s.confirm:void 0})})}catch(A){return h({ok:!1,error:A instanceof Error?A.message:"Compose operation could not be queued."},409)}}if((w.pathname==="/api/compose/logs"||w.pathname==="/api/compose/shell")&&S.method==="POST"){let s=await B(S),g=Hn.applications.get(String(s.id??"")),_=w.pathname.endsWith("/shell"),I=_?"runtime:terminal":"runtime:logs";if(!g||!Kt(z,g.resourceId,I))return h({ok:!1,error:"Compose service was not found in this scope."},404);let A=String(s.service??"");if(!g.manifest.spec.services[A])return h({ok:!1,error:"Compose service was not found."},404);if(_&&s.confirm!==A)return h({ok:!1,error:`Type "${A}" to run a service command.`},409);let v=o.store.listEnvironments(g.projectId).find((k)=>k.id===g.environmentId)?.slug;if(!v)return h({ok:!1,error:"Compose environment was not found."},404);let D=_?HR(g.manifest,A,Array.isArray(s.command)?s.command.map(String):["sh"]):jR(g.manifest,A,Number(s.lines)||200);return h(await nc(c,v,D))}if(w.pathname==="/api/previews/definitions"&&S.method==="POST"){let s=await B(S),g=String(s.resourceId??"");if(!Kt(z,g,"config:write"))return h({ok:!1,error:"Application was not found in this scope."},404);let _=Gt(o.store,z);try{return h({ok:!0,definition:Ht.previews.createDefinition({...s,projectId:o.project.id,resourceId:g,baseEnvironmentId:String(s.baseEnvironmentId??""),domainPattern:String(s.domainPattern??""),createdByActorId:_.id})})}catch(I){return h({ok:!1,error:I instanceof Error?I.message:"Preview policy could not be created."},409)}}if(w.pathname==="/api/previews/deploy"&&S.method==="POST"){let s=await B(S),g=Ht.previews.getDefinition(String(s.definitionId??""));if(!g||!Kt(z,g.resourceId,"deployments:create"))return h({ok:!1,error:"Preview policy was not found in this scope."},404);let _=Gt(o.store,z);try{let I=Ht.previews.upsert({definitionId:g.id,sourceProvider:"dashboard",repository:"dashboard",branch:String(s.branch??""),pullRequestNumber:Number(s.pullRequestNumber)||void 0,commitSha:String(s.commitSha??""),createdByActorId:_.id});return h({ok:!0,preview:I.preview,operation:Ht.enqueueDeploy(I.preview,{created:I.created,actorId:_.id})})}catch(I){return h({ok:!1,error:I instanceof Error?I.message:"Preview could not be queued."},409)}}if(w.pathname==="/api/previews/destroy"&&S.method==="POST"){let s=await B(S),g=Ht.previews.getInstance(String(s.id??""));if(!g||!Kt(z,g.resourceId,"deployments:cancel"))return h({ok:!1,error:"Preview was not found in this scope."},404);if(s.confirm!==g.name)return h({ok:!1,error:`Type "${g.name}" to confirm tagged teardown.`},409);let _=Gt(o.store,z);return h({ok:!0,operation:Ht.enqueueDestroy(g,"dashboard",_.id)})}if(w.pathname==="/api/previews/extend"&&S.method==="POST"){let s=await B(S),g=Ht.previews.getInstance(String(s.id??""));if(!g||!Kt(z,g.resourceId,"deployments:create"))return h({ok:!1,error:"Preview was not found in this scope."},404);return h({ok:!0,preview:Ht.previews.extend(g.id,Number(s.hours))})}if(w.pathname==="/api/previews/rebuild"&&S.method==="POST"){let s=await B(S),g=Ht.previews.getInstance(String(s.id??""));if(!g||!Kt(z,g.resourceId,"deployments:create"))return h({ok:!1,error:"Preview was not found in this scope."},404);let _=Gt(o.store,z);return h({ok:!0,operation:Ht.enqueueDeploy(g,{actorId:_.id,reason:"manual_rebuild"})})}if(w.pathname==="/api/previews/cleanup"&&S.method==="POST"){let s=await B(S);if(!s.dryRun&&s.confirm!=="cleanup previews")return h({ok:!1,error:'Type "cleanup previews" to confirm teardown.'},409);let g=Gt(o.store,z);return h({ok:!0,...Ht.cleanup({dryRun:s.dryRun===!0,maxAgeHours:Number(s.maxAgeHours)||void 0,keepCount:Number(s.keepCount)||void 0,actorId:g.id})})}if(w.pathname==="/api/control-plane/events")return h({events:o.store.listEvents({organizationId:o.organization.id,projectId:o.project.id,operationId:w.searchParams.get("operationId")??void 0,correlationId:w.searchParams.get("correlationId")??void 0,afterSequence:Number(w.searchParams.get("afterSequence"))||void 0,limit:Number(w.searchParams.get("limit"))||200})});if(w.pathname==="/api/search"){let s=String(w.searchParams.get("q")??"").trim().slice(0,128),g=Be.role==="member"?new Set(Object.keys(Be.sites)):void 0,_=s?TR(o.store,{projectId:o.project.id,query:s,allowedResourceSlugs:g,limit:Number(w.searchParams.get("limit"))||20}):[];return h({query:s,results:_,stale:!1})}if(w.pathname==="/api/search/preferences"&&S.method==="GET"){let s=`dashboard:${z.username.toLowerCase()}`;return h({savedFilters:o.store.listSavedFilters(s),navigation:o.store.listNavigation(s)})}if(w.pathname==="/api/search/preferences"&&S.method==="POST"){let s=`dashboard:${z.username.toLowerCase()}`,g=await B(S),_=String(g.action??"");if(_==="save-filter")return h({savedFilter:o.store.saveFilter(s,String(g.name??""),String(g.routeId??""),g.query??{})});if(_==="favorite")return h({navigation:o.store.setFavorite(s,String(g.entityType??""),String(g.entityId??""),g.favorite!==!1)});if(_==="visit")return h({navigation:o.store.recordNavigation(s,String(g.entityType??""),String(g.entityId??""))});return h({ok:!1,error:"Unknown search preference action."},422)}if(w.pathname==="/api/search/preferences"&&S.method==="DELETE"){let s=`dashboard:${z.username.toLowerCase()}`,g=await B(S);return h({ok:o.store.deleteSavedFilter(s,String(g.id??""))})}if(w.pathname==="/api/organization"&&S.method==="GET"){let s=o.store.listMemberships(o.organization.id,{includeRevoked:!0}).map((g)=>{let _=o.store.getActor(g.actorId);return{...g,actor:_?{id:_.id,displayName:_.displayName,externalId:_.externalId,disabledAt:_.disabledAt}:void 0,grants:o.store.listGrants(g.id)}});return h({organization:o.organization,project:o.project,environments:o.store.listEnvironments(o.project.id),resources:o.store.listResources(o.project.id).map((g)=>({id:g.id,environmentId:g.environmentId,kind:g.kind,slug:g.slug,name:g.name})),memberships:s,invitations:o.store.listInvitations(o.organization.id)})}if(w.pathname==="/api/organization/invitations"&&S.method==="GET")return h({invitations:o.store.listInvitations(o.organization.id)});if(w.pathname==="/api/organization/invitations"&&S.method==="POST"){let s=await B(S),g=fo(s.roleTemplate),_=sc(s);if(!g||!_)return h({ok:!1,error:"Choose a valid role template and resource scope."},422);let I=X(z);if(!I.actor||!I.membership)return h({ok:!1,error:"Your organization membership is unavailable."},403);if(g==="owner"&&(!Xe(String(s.password??""),z.passwordHash)||I.membership.roleTemplate!=="owner"))return h({ok:!1,error:"Owner invitations require an owner to re-enter their password."},401);try{let A=o.store.createInvitation({organizationId:o.organization.id,email:String(s.email??""),roleTemplate:g,scope:_,invitedByActorId:I.actor.id,expiresInMs:Number(s.expiresInMs)||void 0}),v=`${w.origin}/accept-invitation?token=${encodeURIComponent(A.token)}`,D=await Ui(c,{to:A.invitation.email,subject:"Your ts-cloud organization invitation",text:`Accept your ts-cloud invitation: ${v}
|
|
495
|
-
|
|
496
|
-
This link expires ${A.invitation.expiresAt} and can be used once.`});return h({invitation:A.invitation,token:A.token,acceptUrl:v,delivered:D},201)}catch(A){return h({ok:!1,error:A instanceof Error?A.message:"Invitation could not be created."},422)}}if(w.pathname==="/api/organization/invitations"&&S.method==="DELETE"){let s=await B(S),g=X(z);try{return h({invitation:o.store.revokeInvitation(String(s.id??""),g.actor?.id)})}catch(_){return h({ok:!1,error:_ instanceof Error?_.message:"Invitation could not be revoked."},409)}}if(w.pathname==="/api/organization/invitations/resend"&&S.method==="POST"){let s=await B(S),g=X(z);try{let _=o.store.reissueInvitation(String(s.id??""),g.actor?.id),I=`${w.origin}/accept-invitation?token=${encodeURIComponent(_.token)}`,A=await Ui(c,{to:_.invitation.email,subject:"Your ts-cloud organization invitation",text:`Accept your ts-cloud invitation: ${I}
|
|
497
|
-
|
|
498
|
-
This replacement link expires ${_.invitation.expiresAt} and can be used once.`});return h({invitation:_.invitation,token:_.token,acceptUrl:I,delivered:A})}catch(_){return h({ok:!1,error:_ instanceof Error?_.message:"Invitation could not be resent."},409)}}if(w.pathname==="/api/organization/memberships"&&S.method==="PATCH"){let s=await B(S),g=o.store.getMembership(String(s.id??"")),_=fo(s.roleTemplate),I=sc(s);if(!g||g.organizationId!==o.organization.id)return h({ok:!1,error:"Membership was not found."},404);if(!_||!I)return h({ok:!1,error:"Choose a valid role template and resource scope."},422);let A=X(z);if((g.roleTemplate==="owner"||_==="owner")&&(!Xe(String(s.password??""),z.passwordHash)||A.membership?.roleTemplate!=="owner"))return h({ok:!1,error:"Ownership changes require an owner to re-enter their password."},401);let D=o.store.resolveAuthorizationTarget(o.organization.id,I)??o.store.resolveAuthorizationTarget(o.organization.id,{type:"project",id:o.project.id}),k=o.store.listGrants(g.id),W=lc({membership:g,grants:k,target:D}),T={...g,roleTemplate:_,scope:I},et=lc({membership:T,grants:k,target:D}),j={gained:et.filter((K)=>!W.includes(K)),lost:W.filter((K)=>!et.includes(K))};if(s.preview===!0)return h({membership:g,proposed:{roleTemplate:_,scope:I},accessDiff:j});if(String(s.confirm??"")!==g.id)return h({ok:!1,error:`Confirm this change with membership ID ${g.id}.`,accessDiff:j},409);try{return h({membership:o.store.updateMembership({id:g.id,roleTemplate:_,scope:I,actorId:A.actor?.id}),accessDiff:j})}catch(K){return h({ok:!1,error:K instanceof Error?K.message:"Membership could not be updated."},409)}}if(w.pathname==="/api/organization/memberships"&&S.method==="DELETE"){let s=await B(S),g=o.store.getMembership(String(s.id??""));if(!g||g.organizationId!==o.organization.id)return h({ok:!1,error:"Membership was not found."},404);if(String(s.confirm??"")!==g.id)return h({ok:!1,error:`Confirm removal with membership ID ${g.id}.`},409);let _=X(z);if(g.roleTemplate==="owner"&&(_.membership?.roleTemplate!=="owner"||!Xe(String(s.password??""),z.passwordHash)))return h({ok:!1,error:"Removing an owner requires an owner to re-enter their current password."},401);try{return h({membership:o.store.revokeMembership(g.id,_.actor?.id)})}catch(I){return h({ok:!1,error:I instanceof Error?I.message:"Membership could not be removed."},409)}}if(w.pathname==="/api/organization/grants"&&S.method==="POST"){let s=await B(S),g=String(s.capability??""),_=s.effect==="deny"?"deny":s.effect==="allow"?"allow":void 0,I=sc(s),A=X(z);if(!_||!I||!Uc.includes(g))return h({ok:!1,error:"Choose a valid capability, effect, and resource scope."},422);try{return h({grant:o.store.upsertGrant({organizationId:o.organization.id,membershipId:String(s.membershipId??""),effect:_,capability:g,scope:I,actorId:A.actor?.id})},201)}catch(v){return h({ok:!1,error:v instanceof Error?v.message:"Grant could not be created."},422)}}if(w.pathname==="/api/organization/grants"&&S.method==="DELETE"){let s=await B(S),g=X(z),_=o.store.getGrant(String(s.id??""));if(!_||_.organizationId!==o.organization.id)return h({ok:!1,error:"Grant was not found."},404);return h({ok:o.store.removeGrant(_.id,g.actor?.id)})}if(w.pathname==="/api/tags"&&S.method==="GET")return h({tags:o.store.listTags(o.project.id),assignments:o.store.listResourceTags(o.project.id)});if(w.pathname==="/api/tags"&&S.method==="POST"){let s=await B(S),g=o.store.upsertTag(o.project.id,String(s.name??""),String(s.color??"#5a8be0"));if(s.resourceId)o.store.assignTag(String(s.resourceId),g.id);return h({tag:g},201)}if(w.pathname==="/api/tags"&&S.method==="DELETE"){let s=await B(S);return o.store.removeTag(String(s.resourceId??""),String(s.tagId??"")),h({ok:!0})}if(w.pathname==="/"&&!yR(w.pathname,Be))return new Response(null,{status:302,headers:{location:`/server/sites?env=${encodeURIComponent(U)}`}});if(w.pathname==="/"&&Ct?.mode==="serverless")return new Response(null,{status:302,headers:{location:`/serverless?env=${encodeURIComponent(U)}`}});let Ic=E_(w.pathname);if(Ic)return new Response(null,{status:308,headers:{location:`${Ic}?env=${encodeURIComponent(U)}`}});if(w.pathname==="/api/env"&&S.method==="POST"){let s=await B(S),g=String(s.env??"");if(!u.includes(g))return h({ok:!1,error:`Unknown environment '${g}'.`,environments:u},404);return h({ok:!0,environment:g,environments:u,href:`?env=${encodeURIComponent(g)}`})}if(w.pathname==="/api/config"){let s={...ZP(c),environment:U,environments:u};return h(w_(s,Be))}if(w.pathname==="/api/ssh-keys"&&S.method==="GET")return h({configPath:R,keys:gc($i(c))});if(w.pathname==="/api/ssh-keys"&&S.method==="POST"){if(!R)return h({ok:!1,error:"No cloud config file was found in this checkout."},404);let s=await B(S),g=await ln(R,"utf8"),_=$i(c),I=qR({configText:g,name:String(s.name??""),publicKey:String(s.publicKey??""),existingKeys:_});return await Tr(R,I),IR(c,[..._,{name:String(s.name??"").trim(),publicKey:String(s.publicKey??"").trim().replace(/\s+/g," ")}]),h({ok:!0,configPath:R,keys:gc($i(c))})}if(w.pathname==="/api/ssh-keys"&&S.method==="DELETE"){if(!R)return h({ok:!1,error:"No cloud config file was found in this checkout."},404);let s=await B(S),g=String(s.name??w.searchParams.get("name")??""),_=await ln(R,"utf8"),I=$i(c),A=tE({configText:_,name:g,existingKeys:I});return await Tr(R,A),IR(c,I.filter((v)=>v.name!==g.trim())),h({ok:!0,configPath:R,keys:gc($i(c))})}if(w.pathname==="/api/firewall"&&S.method==="GET")return h({configPath:R,alwaysOpen:[22,80,443],ports:Fl(c)});if(w.pathname==="/api/firewall"&&S.method==="POST"){if(!R)return h({ok:!1,error:"No cloud config file was found in this checkout."},404);let s=await B(S),g=Number(s.port);if(!ic(g))return h({ok:!1,error:"Port must be an integer between 1 and 65535."},422);let _=Fl(c),I=await ln(R,"utf8");try{await Tr(R,k_(I,g,_))}catch(D){return h({ok:!1,error:D?.message??String(D)},422)}let A=zr([..._,g]);wR(c,A);let v=s.apply===!1?null:await nc(c,U,`ufw allow ${g}/tcp`).catch((D)=>({ok:!1,error:String(D?.message??D)}));return h({ok:!0,configPath:R,ports:A,apply:v})}if(w.pathname==="/api/firewall"&&S.method==="DELETE"){if(!R)return h({ok:!1,error:"No cloud config file was found in this checkout."},404);let s=await B(S),g=Number(s.port??w.searchParams.get("port"));if(!ic(g))return h({ok:!1,error:"Port must be an integer between 1 and 65535."},422);let _=Fl(c),I=await ln(R,"utf8");await Tr(R,C_(I,g,_));let A=zr(_.filter((D)=>D!==g));wR(c,A);let v=s.apply===!1?null:await nc(c,U,`ufw delete allow ${g}/tcp`).catch((D)=>({ok:!1,error:String(D?.message??D)}));return h({ok:!0,configPath:R,ports:A,apply:v})}if(w.pathname==="/api/sites"&&S.method==="POST"){if(!R)return h({ok:!1,error:"No cloud config file was found in this checkout."},404);let s=await B(S),g=String(s.name??"").trim(),_=String(s.root??"").trim();if(!g||!_)return h({ok:!1,error:"Site name and root are required."},422);let I={deploy:s.deploy==="bucket"?"bucket":"server",root:_,path:String(s.path??"").trim()||void 0,domain:String(s.domain??"").trim()||void 0,build:String(s.build??"").trim()||void 0,start:String(s.start??"").trim()||void 0,port:s.port?Number(s.port):void 0,type:String(s.type??"").trim()||void 0};if(I.port!==void 0&&(!Number.isInteger(I.port)||I.port<1||I.port>65535))return h({ok:!1,error:"Port must be a number between 1 and 65535."},422);let A=await ln(R,"utf8"),v=K_({configText:A,name:g,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 Tr(R,v),LP(c,g,Object.fromEntries(Object.entries(I).filter(([,D])=>D!==void 0))),Ct=await br(c,U),y.set(U,Ct),h({ok:!0,configPath:R,site:g,data:Ct})}if(w.pathname==="/api/sites"&&S.method==="DELETE"){if(!R)return h({ok:!1,error:"No cloud config file was found in this checkout."},404);let s=await B(S),g=String(s.name??w.searchParams.get("name")??"").trim();if(!g||!c.sites?.[g])return h({ok:!1,error:`Site '${g}' was not found.`},404);let _=await ln(R,"utf8");return await Tr(R,p_({configText:_,name:g})),delete c.sites[g],Ct=await br(c,U),y.set(U,Ct),h({ok:!0,configPath:R,site:g,data:Ct})}if(w.pathname==="/api/sites"&&S.method==="PATCH"){if(!R)return h({ok:!1,error:"No cloud config file was found in this checkout."},404);let s=await B(S),g=String(s.name??"").trim(),_=c.sites?.[g];if(!g||!_)return h({ok:!1,error:`Site '${g}' was not found.`},404);if(Be.role==="member"){let v=y_(s);if(!v.ok)return h({ok:!1,error:v.error},403);let D=P_({siteName:g,body:s,sites:c.sites??{},ownSites:Object.keys(Be.sites)});if(!D.ok)return h({ok:!1,error:D.error},409)}if(s.port!==void 0&&s.port!==null&&s.port!==""&&(!Number.isInteger(Number(s.port))||Number(s.port)<1||Number(s.port)>65535))return h({ok:!1,error:"Port must be a number between 1 and 65535."},422);if(typeof s.domain==="string"&&s.domain.trim()&&!Ul(s.domain.trim()))return h({ok:!1,error:`Domain '${s.domain.trim()}' is not a valid hostname.`},422);let I=await ln(R,"utf8"),A=(v,D)=>{I=m_({configText:I,siteName:g,key:v,valueText:D})};if(s.ssl!==void 0)A("ssl",q_(s.ssl)),_.ssl=s.ssl;if(s.env!==void 0&&s.env&&typeof s.env==="object")A("env",eR(s.env)),_.env=s.env;if(s.aliases!==void 0&&Array.isArray(s.aliases)){let v=s.aliases.map((D)=>String(D));A("aliases",nR(v)),_.aliases=v.map((D)=>D.trim().toLowerCase()).filter(Boolean)}if(s.redirects!==void 0&&s.redirects&&typeof s.redirects==="object")A("redirects",rR(s.redirects)),_.redirects=s.redirects;for(let v of["domain","path","build","start","type","root","php"])if(typeof s[v]==="string"&&s[v].trim())A(v,tR(String(s[v]).trim())),_[v]=String(s[v]).trim();if(s.port!==void 0&&s.port!==null&&s.port!=="")A("port",String(Number(s.port))),_.port=Number(s.port);return await Tr(R,I),Ct=await br(c,U),y.set(U,Ct),h({ok:!0,configPath:R,site:g,data:Ct})}if(w.pathname==="/api/sites/deploy"&&S.method==="POST"){let s=await B(S),g=String(s.name??"").trim();if(!g||!c.sites?.[g])return h({ok:!1,error:`Site '${g}' was not found.`},404);if(s.confirm!==g)return h({ok:!1,error:`Type "${g}" to deploy this site.`},409);let _=Ye(o,String(U));await new Cr(ot).run(new mi,{..._,artifactRoot:e}),Qd(ot,_,Ct??{});let I=Gd(ot,{scope:_,desiredConfigHash:o.project.desiredConfigHash});if(I.decision.outcome==="block")return h({ok:!1,error:`Deployment blocked by security policy: ${I.decision.explanation}`,securityReview:I},409);let A={id:`deploy:${g}`,label:`Deploy ${g}`,description:`Deploy the ${g} site for ${U}.`,command:["deploy","--env",U,"--site",g,"--yes"],mutates:!0},v=await Bn({controlPlane:o,environment:U,actor:z,kind:"dashboard.site.deploy",resourceSlug:g,input:{site:g},execute:()=>Vl(A,{cwd:e,cliEntry:i})});return h({...v.result,controlPlaneOperation:v.operation,securityReview:I})}if(w.pathname==="/api/actions")return h(iE(U));if(w.pathname==="/api/server/operations")return h(oo(c,Ct));if(w.pathname==="/api/runtime/workloads"&&S.method==="GET"){let s=await Ge(c,U);return h(s)}if(w.pathname==="/api/runtime/logs"&&S.method==="GET"){let s=String(w.searchParams.get("workload")??"");if(!s)return h({ok:!1,error:"A workload query parameter is required."},422);let g=Math.min(1000,Math.max(1,Number(w.searchParams.get("limit"))||200));try{return h(await new an(c,U).logs(s,{limit:g}))}catch(_){return h({ok:!1,error:String(_?.message??_)},404)}}if(w.pathname==="/api/runtime/log-sessions"&&S.method==="POST"){let s=await B(S),g=String(s.workloadId??"");if(!g)return h({ok:!1,error:"A workloadId is required."},422);let _=await Ge(c,U),I=_.workloads.find((D)=>D.id===g);if(!I)return h({ok:!1,error:"Workload was not found in the current project and environment."},404);if(!I.capabilities.logs.supported)return h({ok:!1,error:I.capabilities.logs.reason??"Logs are unsupported for this workload."},409);let A=new an(c,U,{inventory:async()=>_}),v=Vt.create("logs",g);return(async()=>{let D=new Date(Date.now()-Math.min(3600000,Math.max(1000,Number(s.sinceMs)||60000)));try{for(let k=0;k<200&&!Vt.signal(v.id)?.aborted;k++){let W=await A.logs(g,{limit:Math.min(500,Math.max(1,Number(s.limit)||200)),since:D});for(let T of W.lines)if(Vt.append(v.id,`${T.timestamp?`${T.timestamp} `:""}${T.message}
|
|
499
|
-
`),T.timestamp)D=new Date(Math.max(D.getTime(),new Date(T.timestamp).getTime()+1));await Bun.sleep(3000)}if(!Vt.signal(v.id)?.aborted)Vt.close(v.id,"complete")}catch(k){Vt.append(v.id,k instanceof Error?k.message:String(k),"stderr"),Vt.close(v.id,"failed",k instanceof Error?k.message:String(k))}})(),h({ok:!0,session:v,streamUrl:`/api/runtime/log-stream?id=${encodeURIComponent(v.id)}&workload=${encodeURIComponent(g)}`},201)}if((w.pathname==="/api/runtime/log-stream"||w.pathname==="/api/runtime/exec-stream")&&S.method==="GET"){let s=String(w.searchParams.get("id")??""),g=String(w.searchParams.get("workload")??""),_=Number(S.headers.get("last-event-id")??w.searchParams.get("after")??0)||0,I=Vt.read(s,g,_),A=w.pathname.includes("exec")?"exec":"logs";if(!I||I.kind!==A)return h({ok:!1,error:"Runtime stream was not found in this workload scope."},404);return JP(Vt,I,_,S.signal)}if((w.pathname==="/api/runtime/log-sessions"||w.pathname==="/api/runtime/exec-sessions")&&S.method==="DELETE"){let s=await B(S),g=Vt.cancel(String(s.id??""),String(s.workloadId??""));if(!g)return h({ok:!1,error:"Runtime stream was not found in this workload scope."},404);return h({ok:!0,session:g})}if(w.pathname==="/api/runtime/exec-sessions"&&S.method==="POST"){let s=await B(S),g=String(s.workloadId??""),_=await Ge(c,U),I=_.workloads.find((k)=>k.id===g);if(!I)return h({ok:!1,error:"Workload was not found in the current project and environment."},404);let A=Bt.resolveSession(S),v=new an(c,U,{inventory:async()=>_}),D=Vt.create("exec",g);return Bn({controlPlane:o,environment:U,actor:z,kind:"runtime.exec",resourceSlug:I.links.service,input:{workloadId:g,provider:I.provider,preset:s.preset?String(s.preset):null,freeForm:!!String(s.command??"").trim()},execute:()=>v.exec({workloadId:g,preset:["process","sockets","filesystem"].includes(String(s.preset))?String(s.preset):void 0,command:typeof s.command==="string"?s.command:void 0,confirm:String(s.confirm??""),recentAuth:!G||!!A&&F.isRecentlyAuthenticated(A)})}).then(({result:k,operation:W})=>{if(Vt.append(D.id,`operation ${W.id}
|
|
500
|
-
`,"system"),k.stdout)Vt.append(D.id,k.stdout,"stdout");if(k.stderr)Vt.append(D.id,k.stderr,"stderr");Vt.close(D.id,k.ok?"complete":"failed",k.error)}).catch((k)=>{let W=k instanceof Error?k.message:String(k);Vt.append(D.id,W,"stderr"),Vt.close(D.id,"failed",W)}),h({ok:!0,session:D,streamUrl:`/api/runtime/exec-stream?id=${encodeURIComponent(D.id)}&workload=${encodeURIComponent(g)}`},202)}if(w.pathname==="/api/runtime/files/read"&&S.method==="POST"){let s=await B(S),g=await Ge(c,U),_=Bt.resolveSession(S),I=await new an(c,U,{inventory:async()=>g}).readFile({workloadId:String(s.workloadId??""),path:String(s.path??""),confirm:String(s.confirm??""),recentAuth:!G||!!_&&F.isRecentlyAuthenticated(_)});return h(I,I.ok?200:409)}if(w.pathname==="/api/runtime/files/write"&&S.method==="POST"){let s=await B(S),g=await Ge(c,U),_=String(s.workloadId??""),I=g.workloads.find((k)=>k.id===_);if(!I)return h({ok:!1,error:"Workload was not found in the current project and environment."},404);let A=Bt.resolveSession(S),v=new an(c,U,{inventory:async()=>g}),D=await Bn({controlPlane:o,environment:U,actor:z,kind:"runtime.file.write",resourceSlug:I.links.service,input:{workloadId:_,provider:I.provider,path:String(s.path??""),bytes:Buffer.from(String(s.contentBase64??""),"base64").byteLength},execute:()=>v.writeFile({workloadId:_,path:String(s.path??""),contentBase64:String(s.contentBase64??""),confirm:String(s.confirm??""),recentAuth:!G||!!A&&F.isRecentlyAuthenticated(A)})});return h({...D.result,controlPlaneOperation:D.operation},D.result.ok?200:409)}if(w.pathname==="/api/runtime/operations"&&S.method==="POST"){let s=await B(S),g=String(s.workloadId??""),_=String(s.action??"");if(!g||!["start","stop","restart","redeploy","scale","inspect"].includes(_))return h({ok:!1,error:"A valid workloadId and lifecycle action are required."},422);let I=await Ge(c,U),A=I.workloads.find((W)=>W.id===g);if(!A)return h({ok:!1,error:"Workload was not found in the current project and environment."},404);let v=Bt.resolveSession(S),D=new an(c,U,{inventory:async()=>I}),k=await Bn({controlPlane:o,environment:U,actor:z,kind:`runtime.${_}`,resourceSlug:A.links.service,input:{workloadId:g,provider:A.provider,action:_,replicas:s.replicas==null?null:Number(s.replicas)},execute:()=>D.run({workloadId:g,action:_,replicas:s.replicas==null?void 0:Number(s.replicas),confirm:String(s.confirm??""),recentAuth:!G||!!v&&F.isRecentlyAuthenticated(v)})});return h({...k.result,controlPlaneOperation:k.operation},k.result.ok?200:409)}if(w.pathname.startsWith("/api/protection")){let s=z.role==="admin"||Ec(z,"security:read"),g=z.role==="admin"||Ec(z,"security:manage");if(!s)return h({ok:!1,error:"Protection controls require security:read."},403);let{ProtectionControlStore:_,describePosture:I}=await import("./chunk-21e0mavm.js"),A=new _(o.store),v=()=>{if(!g)throw Error("Changing protection controls requires security:manage.")};if(w.pathname==="/api/protection"&&S.method==="GET"){let D=A.current();return h({ok:!0,posture:I(D),controls:D,raw:A.raw()})}if(w.pathname==="/api/protection/attack-mode"&&S.method==="POST"){v();let D=await B(S);if(D.enabled===!1)return h({ok:!0,disabled:A.disableAttackMode()});return h({ok:!0,control:A.enableAttackMode({hours:D.hours==null?void 0:Number(D.hours),reason:String(D.reason??"Enabled from the dashboard."),actorId:X(z).actor?.id})})}if(w.pathname==="/api/protection/pause"&&S.method==="POST"){v();let D=await B(S);if(D.enabled===!1)return h({ok:!0,resumed:A.resumeMitigations()});return h({ok:!0,control:A.pauseMitigations({hours:D.hours==null?void 0:Number(D.hours),reason:String(D.reason??""),actorId:X(z).actor?.id})})}if(w.pathname==="/api/protection/ip-rules"&&S.method==="GET")return h({ok:!0,ipRules:A.current().ipRules});if(w.pathname==="/api/protection/ip-rules"&&(S.method==="POST"||S.method==="DELETE")){v();let D=await B(S),k=D.list==="allow"?"allow":"block",W=S.method==="POST"?A.addIpRule(k,String(D.cidr??"")):A.removeIpRule(k,String(D.cidr??""));return h({ok:!0,ipRules:W})}return h({ok:!1,error:"Protection endpoint was not found."},404)}if(w.pathname.startsWith("/api/spend/")||w.pathname==="/api/usage"){let s=await sE(),g=s.store,_=s.service,I=s.gate,A=z.role==="admin"||Ec(z,"billing:read"),v=z.role==="admin"||Ec(z,"billing:manage");if(!A)return h({ok:!1,error:"Spend data requires the billing:read capability."},403);let D=o.environments.get(U),k={organizationId:o.organization.id,projectId:o.project.id,environmentId:D?.id},W=()=>{if(!v)throw Error("Changing a budget requires the billing:manage capability.")};if(w.pathname==="/api/usage"&&S.method==="GET")return h({ok:!0,..._.usageReport({organizationId:k.organizationId,projectId:k.projectId,period:w.searchParams.get("period")??"monthly",timezone:w.searchParams.get("timezone")??void 0})});if(w.pathname==="/api/spend/budgets"&&S.method==="GET")return h({ok:!0,budgets:g.listBudgets({organizationId:k.organizationId,projectId:k.projectId}).map((T)=>({...T,status:_.status(T)}))});if(w.pathname==="/api/spend/budgets"&&S.method==="POST"){W();let T=await B(S),et=String(T.scope??"project"),j=g.createBudget({organizationId:k.organizationId,projectId:et==="organization"?void 0:k.projectId,environmentId:et==="environment"?k.environmentId:void 0,name:String(T.name??"").trim(),period:T.period??"monthly",timezone:T.timezone?String(T.timezone):void 0,softLimitCents:T.softLimitCents==null?void 0:Math.round(Number(T.softLimitCents)),hardLimitCents:T.hardLimitCents==null?void 0:Math.round(Number(T.hardLimitCents)),graceSeconds:T.graceSeconds==null?void 0:Number(T.graceSeconds),dryRun:T.dryRun!==!1});return h({ok:!0,budget:j})}if(w.pathname==="/api/spend/budgets"&&S.method==="PATCH"){W();let T=await B(S),et=String(T.id??""),j=g.getBudget(et);if(!j||j.organizationId!==k.organizationId)return h({ok:!1,error:"Budget was not found."},404);return h({ok:!0,budget:g.updateBudget(et,{softLimitCents:T.softLimitCents==null?j.softLimitCents:Math.round(Number(T.softLimitCents)),hardLimitCents:T.hardLimitCents==null?j.hardLimitCents:Math.round(Number(T.hardLimitCents)),enabled:T.enabled==null?j.enabled:T.enabled===!0,dryRun:T.dryRun==null?j.dryRun:T.dryRun===!0},T.expectedVersion==null?void 0:Number(T.expectedVersion))})}if(w.pathname==="/api/spend/budgets"&&S.method==="DELETE"){W();let T=await B(S),et=String(T.id??""),j=g.getBudget(et);if(!j||j.organizationId!==k.organizationId)return h({ok:!1,error:"Budget was not found."},404);let K=I.closeBudget(et);return g.deleteBudget(et),h({ok:!0,deleted:!0,lifted:K})}if(w.pathname==="/api/spend/check"&&S.method==="POST"){W();let T=await B(S),{SpendRunner:et}=await import("./chunk-qk9qgepa.js"),j=new et({controlPlane:o.store,store:g,alerts:nt});if(T.apply!==!0){let L=g.budgetsForScope(k.organizationId,k.projectId,k.environmentId);return h({ok:!0,applied:!1,preview:L.map((M)=>_.status(M))})}let K=await j.run({...k,environmentKind:D?.kind});return h({ok:!0,applied:!0,result:K})}if(w.pathname==="/api/spend/enforcement"&&S.method==="GET")return h({ok:!0,enforcement:I.listUnder({organizationId:k.organizationId})});if(w.pathname==="/api/spend/release"&&S.method==="POST"){W();let T=await B(S),et=I.close(String(T.budgetId??""),T.action);return h({ok:et,released:et,note:et?"The next spend cycle re-applies this if spend is still over the threshold.":"That action was not in force."})}if(w.pathname==="/api/spend/anomalies"&&S.method==="GET")return h({ok:!0,anomalies:g.listAnomalies({organizationId:k.organizationId,projectId:k.projectId,unacknowledgedOnly:w.searchParams.get("unacknowledged")==="true"})});if(w.pathname==="/api/spend/anomalies/acknowledge"&&S.method==="POST"){W();let T=await B(S);return h({ok:!0,acknowledged:g.acknowledgeAnomaly(String(T.id??""))})}return h({ok:!1,error:"Spend endpoint was not found."},404)}if(w.pathname.startsWith("/api/health/")||w.pathname.startsWith("/api/alerts")||w.pathname.startsWith("/api/notifications/")){let s=o.environments.get(U),g=o.store.listResources(o.project.id,s?.id),_=z.role==="admin"||!!s&&ki(z,s.id,"runtime:read")?g:g.filter((D)=>Kt(z,D.id,"runtime:read")),I=(D)=>!D||_.some((k)=>k.id===D),A=(D)=>{if(!D)return;let k=g.find((W)=>W.id===D||W.slug===D);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},v=X(z).actor;if(w.pathname==="/api/health/checks"&&S.method==="GET")return h({ok:!0,checks:nt.listHealthChecks(o.project.id,s?.id).filter((D)=>I(D.resourceId)).map((D)=>({...D,results:nt.listHealthResults(D.id,20)}))});if(w.pathname==="/api/health/checks"&&S.method==="POST"){let D=await B(S),k=String(D.kind??"http");if(k==="command"&&z.role!=="admin")return h({ok:!1,error:"Command health checks require an administrator."},403);let W={method:String(D.config?.method??"GET").toUpperCase().slice(0,10),path:D.config?.path?String(D.config.path).slice(0,500):void 0,port:D.config?.port==null?void 0:Number(D.config.port),command:Array.isArray(D.config?.command)?D.config.command.map(String).slice(0,20):void 0,expectedStatuses:Array.isArray(D.config?.expectedStatuses)?D.config.expectedStatuses.map(Number).filter(Number.isInteger).slice(0,20):void 0,expectedBody:D.config?.expectedBody?String(D.config.expectedBody).slice(0,500):void 0};return h({ok:!0,check:nt.createHealthCheck({projectId:o.project.id,environmentId:s?.id,resourceId:A(D.resourceId??D.resource),name:String(D.name??""),kind:k,target:String(D.target??""),config:W,intervalSeconds:Number(D.intervalSeconds)||60,timeoutSeconds:Number(D.timeoutSeconds)||10,failureThreshold:Number(D.failureThreshold)||3,recoveryThreshold:Number(D.recoveryThreshold)||2,regions:Array.isArray(D.regions)?D.regions.map(String):["local"],enabled:D.enabled!==!1})},201)}if(w.pathname==="/api/health/checks"&&S.method==="PATCH"){let D=await B(S),k=nt.getHealthCheck(String(D.id??""));if(!k||!I(k.resourceId))return h({ok:!1,error:"Health check was not found."},404);return h({ok:!0,check:nt.setHealthCheckEnabled(k.id,D.enabled!==!1)})}if(w.pathname==="/api/health/checks/test"&&S.method==="POST"){let D=await B(S),k=nt.getHealthCheck(String(D.id??""));if(!k||!I(k.resourceId))return h({ok:!1,error:"Health check was not found."},404);return h({ok:!0,productionIncidentCreated:!1,result:await new yi(nt).probe(k)})}if(w.pathname==="/api/health/checks/run"&&S.method==="POST"){let D=await B(S),k=nt.getHealthCheck(String(D.id??""));if(!k||!I(k.resourceId))return h({ok:!1,error:"Health check was not found."},404);let W=await new yi(nt).runAndEvaluate(k),T=[];for(let et of W.evaluations.filter((j)=>j.notify&&j.alert)){let j=Je.enqueue(o.organization.id,et.alert,et.transition);T.push(...await Je.deliverAll(j))}return h({ok:!0,...W,deliveries:T})}if(w.pathname==="/api/alerts/rules"&&S.method==="GET")return h({ok:!0,rules:nt.listRules(o.project.id,s?.id).filter((D)=>I(D.resourceId))});if(w.pathname==="/api/alerts/rules"&&S.method==="POST"){let D=await B(S),k=D.healthCheckId?nt.getHealthCheck(String(D.healthCheckId)):void 0;if(D.healthCheckId&&(!k||!I(k.resourceId)))return h({ok:!1,error:"Health check was not found."},404);return h({ok:!0,rule:nt.createRule({projectId:o.project.id,environmentId:s?.id,resourceId:A(D.resourceId??D.resource)??k?.resourceId,healthCheckId:k?.id,name:String(D.name??""),signal:String(D.signal??(k?"health":"")),operator:String(D.operator??(k?"unhealthy":"gt")),threshold:D.threshold==null?void 0:Number(D.threshold),recoveryThreshold:D.recoveryThreshold==null?void 0:Number(D.recoveryThreshold),windowMs:Number(D.windowMs)||300000,consecutive:Number(D.consecutive)||k?.failureThreshold||3,recoveryConsecutive:Number(D.recoveryConsecutive)||k?.recoveryThreshold||2,noDataPolicy:["ignore","pending","firing"].includes(String(D.noDataPolicy))?D.noDataPolicy:"pending",severity:["info","warning","critical"].includes(String(D.severity))?D.severity:"warning",groupBy:Array.isArray(D.groupBy)?D.groupBy.map(String):[],labels:D.labels&&typeof D.labels==="object"?D.labels:{},enabled:D.enabled!==!1})},201)}if(w.pathname==="/api/alerts/rules"&&S.method==="PATCH"){let D=await B(S),k=nt.getRule(String(D.id??""));if(!k||!I(k.resourceId))return h({ok:!1,error:"Alert rule was not found."},404);return h({ok:!0,rule:nt.setRuleEnabled(k.id,D.enabled!==!1)})}if(w.pathname==="/api/alerts/evaluate"&&S.method==="POST")return h({ok:!0,...await Kl(s?.id)});if(w.pathname==="/api/alerts"&&S.method==="GET")return h({ok:!0,alerts:nt.listAlerts(o.project.id,{environmentId:s?.id,states:w.searchParams.getAll("state").length?w.searchParams.getAll("state"):void 0,limit:Number(w.searchParams.get("limit"))||200}).filter((D)=>I(D.resourceId)).map((D)=>({...D,deliveries:nt.listDeliveries({alertId:D.id,limit:50})}))});if(w.pathname==="/api/alerts/action"&&S.method==="POST"){let D=await B(S),k=nt.getAlert(String(D.id??""));if(!k||!I(k.resourceId))return h({ok:!1,error:"Alert was not found."},404);let W=String(D.action??"");if(W==="acknowledge")return h({ok:!0,alert:nt.acknowledge(k.id,v?.id??"")});if(W==="assign")return h({ok:!0,alert:nt.assign(k.id,D.ownerActorId==="me"?v?.id:D.ownerActorId?String(D.ownerActorId):void 0,v?.id)});if(W==="silence"){if(z.role!=="admin")return h({ok:!1,error:"Silencing production alerts requires an administrator."},403);let T=Bt.resolveSession(S);if(G&&(!T||!F.isRecentlyAuthenticated(T)))return h({ok:!1,error:"Recent authentication is required to silence alerts.",stepUpRequired:!0},401);return h({ok:!0,alert:nt.silenceAlert(k.id,String(D.until??""),v?.id)})}return h({ok:!1,error:"Action must be acknowledge, assign, or silence."},422)}if(w.pathname==="/api/alerts/silences"&&S.method==="POST"){let D=await B(S);return h({ok:!0,id:nt.createSilence({projectId:o.project.id,environmentId:s?.id,resourceId:A(D.resourceId??D.resource),matcher:D.matcher,reason:String(D.reason??""),startsAt:String(D.startsAt??new Date().toISOString()),endsAt:String(D.endsAt??""),timezone:String(D.timezone??"UTC"),actorId:v?.id})},201)}if(w.pathname==="/api/notifications/channels"&&S.method==="GET")return h({ok:!0,channels:nt.listChannels(o.organization.id)});if(w.pathname==="/api/notifications/channels"&&S.method==="POST"){let D=await B(S),k=String(D.kind??""),W=k==="email"?{to:D.config?.to,from:D.config?.from}:k==="telegram"?{chatId:String(D.config?.chatId??"")}:{};return h({ok:!0,channel:nt.createChannel({organizationId:o.organization.id,name:String(D.name??""),kind:k,config:W,credential:D.credential?String(D.credential):void 0,actorId:v?.id})},201)}if(w.pathname==="/api/notifications/channels"&&S.method==="PATCH"){let D=await B(S),k=String(D.id??"");if(D.credential)return h({ok:!0,channel:nt.rotateChannel(k,String(D.credential))});let W=String(D.status??"paused");if(!["active","paused","disabled"].includes(W))return h({ok:!1,error:"Channel status must be active, paused, or disabled."},422);return h({ok:!0,channel:nt.setChannelStatus(k,W)})}if(w.pathname==="/api/notifications/channels/test"&&S.method==="POST"){let D=await B(S);return h({ok:!0,productionIncidentCreated:!1,result:await Je.testChannel(String(D.id??""))})}if(w.pathname==="/api/notifications/routes"&&S.method==="GET")return h({ok:!0,routes:nt.listRoutes(o.organization.id)});if(w.pathname==="/api/notifications/routes"&&S.method==="POST"){let D=await B(S),k=Array.isArray(D.channelIds)?D.channelIds.map(String):[];if(k.some((W)=>nt.getChannel(W)?.organizationId!==o.organization.id))return h({ok:!1,error:"Route contains an unavailable channel."},422);return h({ok:!0,route:nt.createRoute({organizationId:o.organization.id,name:String(D.name??""),priority:Number(D.priority)||0,matcher:D.matcher&&typeof D.matcher==="object"?D.matcher:{},channelIds:k,quietHours:D.quietHours,groupWaitSeconds:Number(D.groupWaitSeconds)||30,reminderSeconds:D.reminderSeconds==null?void 0:Number(D.reminderSeconds),escalation:Array.isArray(D.escalation)?D.escalation:[],template:D.template?String(D.template):void 0,rateLimitPerMinute:Number(D.rateLimitPerMinute)||60,enabled:D.enabled!==!1})},201)}if(w.pathname==="/api/notifications/routes"&&S.method==="PATCH"){let D=await B(S),k=nt.getRoute(String(D.id??""));if(!k||k.organizationId!==o.organization.id)return h({ok:!1,error:"Notification route was not found."},404);return h({ok:!0,route:nt.setRouteEnabled(k.id,D.enabled!==!1)})}if(w.pathname==="/api/notifications/routes/preview"&&S.method==="POST"){let D=await B(S),W=(D.alertId?nt.getAlert(String(D.alertId)):void 0)??{id:"preview",ruleId:"preview",projectId:o.project.id,environmentId:s?.id,resourceId:A(D.resourceId??D.resource),dedupKey:"preview",groupKey:String(D.groupKey??"default"),state:"firing",severity:["info","warning","critical"].includes(String(D.severity))?D.severity:"warning",title:String(D.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 h({ok:!0,productionIncidentCreated:!1,matches:Je.preview(o.organization.id,W,String(D.eventType??"firing")).map((T)=>({route:T.route,channels:T.channels,quiet:T.quiet}))})}if(w.pathname==="/api/notifications/deliveries"&&S.method==="GET")return h({ok:!0,deliveries:nt.listDeliveries({alertId:w.searchParams.get("alertId")??void 0,states:w.searchParams.getAll("state"),limit:Number(w.searchParams.get("limit"))||200})});if(w.pathname==="/api/notifications/deliveries/retry"&&S.method==="POST"){let D=await B(S),k=nt.getDelivery(String(D.id??""));if(!k)return h({ok:!1,error:"Delivery was not found."},404);return nt.updateDelivery(k.id,{state:"retrying",attempt:Math.max(0,k.attempt-1),nextAttemptAt:new Date().toISOString()}),h({ok:!0,delivery:await Je.deliver(k.id)})}}if(w.pathname.startsWith("/api/jobs")||w.pathname.startsWith("/api/workers")){let s=o.environments.get(U),g=o.store.listResources(o.project.id,s?.id),I=z.role==="admin"||!!s&&ki(z,s.id,"automation:read")?g:g.filter((L)=>Kt(z,L.id,"automation:read")),A=(L)=>!L||I.some((M)=>M.id===L),v=X(z).actor,D=y.get(U)??E,k=oo(c,D),W=k.filter((L)=>!L.danger&&["scheduler","backup","worker"].includes(L.group)),T=On(c),et=()=>{let L=Bt.resolveSession(S);return!G||!!L&&F.isRecentlyAuthenticated(L)},j=(L)=>{if(!L||typeof L!=="object"||Array.isArray(L))return{};let M=Object.entries(L).slice(0,50);if(M.some(([,ct])=>typeof ct!=="string"||!/^(?:secret|ssm|arn|env):\/\//.test(ct)))throw Error("Job payload values must be secret or environment references, never inline values.");return Object.fromEntries(M)},K=(L,M,ct)=>o.store.appendEvent({organizationId:o.organization.id,projectId:o.project.id,resourceId:ct,actorId:v?.id,type:`job.${L}`,payload:M});if(w.pathname==="/api/jobs/preview"&&S.method==="POST"){let L=await B(S);try{return h({ok:!0,productionExecutionCreated:!1,preview:_r(String(L.expression??""),String(L.timezone??"UTC"),new Date(L.from?String(L.from):Date.now()),Number(L.count)||5)})}catch(M){return h({ok:!1,error:M instanceof Error?M.message:"Schedule preview could not be generated.",productionExecutionCreated:!1},422)}}if(w.pathname==="/api/jobs"&&S.method==="GET")return h({ok:!0,jobs:Xt.list(o.project.id,{environmentId:s?.id}).filter((L)=>A(L.resourceId)).map((L)=>({...L,preview:_r(L.normalizedExpression,L.timezone,new Date,5),capability:sa(L),lastExecution:Xt.listExecutions(L.id,1)[0]}))});if(w.pathname==="/api/jobs"&&S.method==="POST"){let L=await B(S),M=String(L.provider??(T==="serverless"?"eventbridge":"server")),ct=T==="serverless"?"eventbridge":"server";if(M!==ct)return h({ok:!1,error:`${T} environments accept ${ct} schedules through this adapter.`},422);let lt=L.operationId?String(L.operationId):void 0;if(M==="server"&&(!lt||!W.some((Nt)=>Nt.id===lt)))return h({ok:!1,error:"Server jobs require an allowlisted operation target."},422);let It=sa({provider:M,expression:String(L.expression??""),flexibleMinutes:Number(L.flexibleMinutes)||0,missedRunPolicy:L.missedRunPolicy==="catch_up"?"catch_up":"skip",overlapPolicy:["allow","forbid","replace"].includes(String(L.overlapPolicy))?L.overlapPolicy:"forbid"});if(!It.supported)return h({ok:!1,error:It.notes.join(" ")},422);let Pe=L.resourceId?g.find((Nt)=>Nt.id===L.resourceId||Nt.slug===L.resourceId):void 0;if(L.resourceId&&(!Pe||!A(Pe.id)))return h({ok:!1,error:"Job resource was not found."},404);try{let Nt=M==="server"?{kind:"dashboard_operation",operationId:lt}:{kind:"serverless_scheduler",action:"run"},Fn=Xt.create({organizationId:o.organization.id,projectId:o.project.id,environmentId:s?.id,resourceId:Pe?.id,name:String(L.name??""),provider:M,expression:String(L.expression??""),timezone:String(L.timezone??"UTC"),startsAt:L.startsAt?String(L.startsAt):void 0,endsAt:L.endsAt?String(L.endsAt):void 0,flexibleMinutes:Number(L.flexibleMinutes)||0,target:Nt,payloadRefs:j(L.payloadRefs),missedRunPolicy:L.missedRunPolicy==="catch_up"?"catch_up":"skip",overlapPolicy:["allow","forbid","replace"].includes(String(L.overlapPolicy))?L.overlapPolicy:"forbid",retryPolicy:{maxAttempts:Number(L.maxAttempts)||3,backoffSeconds:Number(L.backoffSeconds)||30,deadLetterRef:L.deadLetterRef?String(L.deadLetterRef):void 0},timeoutSeconds:Number(L.timeoutSeconds)||900,enabled:L.enabled!==!1,origin:"managed",ownerActorId:v?.id,observedState:{},reconciliationStatus:"pending"});return K("created",{jobId:Fn.id,provider:Fn.provider,expression:Fn.normalizedExpression},Fn.resourceId),h({ok:!0,job:Fn,capability:It},201)}catch(Nt){return h({ok:!1,error:Nt instanceof Error?Nt.message:"Scheduled job could not be created."},422)}}if(w.pathname==="/api/jobs"&&S.method==="PATCH"){let L=await B(S),M=Xt.get(String(L.id??""));if(!M||!A(M.resourceId))return h({ok:!1,error:"Scheduled job was not found."},404);if(M.origin==="config")return h({ok:!1,error:"Config-defined schedules must be edited in cloud.config.ts and reconciled."},409);let ct=L.missedRunPolicy==null?void 0:String(L.missedRunPolicy),lt=L.overlapPolicy==null?void 0:String(L.overlapPolicy);if(ct&&!["skip","catch_up"].includes(ct))return h({ok:!1,error:"Missed-run policy must be skip or catch_up."},422);if(lt&&!["allow","forbid","replace"].includes(lt))return h({ok:!1,error:"Overlap policy must be allow, forbid, or replace."},422);try{let It=Xt.updateSchedule(M.id,{expression:L.expression?String(L.expression):void 0,timezone:L.timezone?String(L.timezone):void 0,missedRunPolicy:ct,overlapPolicy:lt,timeoutSeconds:L.timeoutSeconds==null?void 0:Number(L.timeoutSeconds)});return K("updated",{jobId:It.id,expression:It.normalizedExpression,version:It.version},It.resourceId),h({ok:!0,job:It})}catch(It){return h({ok:!1,error:It instanceof Error?It.message:"Scheduled job could not be updated."},422)}}if(w.pathname==="/api/jobs/action"&&S.method==="POST"){let L=await B(S),M=Xt.get(String(L.id??""));if(!M||!A(M.resourceId))return h({ok:!1,error:"Scheduled job was not found."},404);let ct=String(L.action??"");if(ct==="run"){let lt=Xl.enqueue(M,{trigger:"manual",actorId:v?.id});return K("run_queued",{jobId:M.id,executionId:lt.id},M.resourceId),h({ok:!0,execution:lt},202)}if(["disable","delete"].includes(ct)&&s?.kind==="production"){if(String(L.confirm??"")!==ct)return h({ok:!1,error:`Type "${ct}" to confirm this production change.`},409);if(!et())return h({ok:!1,error:"Recent authentication is required for this production change.",stepUpRequired:!0},401)}if(ct==="enable"||ct==="disable"){let lt=Xt.setEnabled(M.id,ct==="enable");return K(ct==="enable"?"enabled":"disabled",{jobId:M.id},M.resourceId),h({ok:!0,job:lt})}if(ct==="delete")try{return Xt.remove(M.id),K("deleted",{jobId:M.id,name:M.name},M.resourceId),h({ok:!0,deleted:M.id})}catch(lt){return h({ok:!1,error:lt instanceof Error?lt.message:"Scheduled job could not be deleted."},409)}return h({ok:!1,error:"Action must be run, enable, disable, or delete."},422)}if(w.pathname==="/api/jobs/history"&&S.method==="GET"){let L=Xt.get(String(w.searchParams.get("jobId")??""));if(!L||!A(L.resourceId))return h({ok:!1,error:"Scheduled job was not found."},404);return h({ok:!0,executions:Xt.listExecutions(L.id,Number(w.searchParams.get("limit"))||100).map((M)=>({...M,logs:M.operationId?yt.logs(M.operationId,{limit:500}):[]}))})}if(w.pathname==="/api/jobs/reconcile"&&S.method==="POST"){if(!s)return h({ok:!1,error:"Environment was not found."},404);let L=la(Xt,c,{organization:o.organization,project:o.project,environment:s,resources:g});return K("reconciled",L),h({ok:!0,reconciliation:L})}if(w.pathname==="/api/workers"&&S.method==="GET"){let L=Array.isArray(D.workersDetail??D.workers)?D.workersDetail??D.workers:[];return h({ok:!0,workers:Xt.listWorkers(o.project.id,s?.id).filter((M)=>A(M.resourceId)).map((M)=>{let ct=L.find((lt)=>lt.name===M.name||lt.site===M.target.site);return ct?{...M,observedState:{...M.observedState,status:ct.status??"configured",currentJob:ct.currentJob??null,failures:Number(ct.failed??ct.failures)||0,processed:Number(ct.processed)||0}}:M})})}if(w.pathname==="/api/workers/action"&&S.method==="POST"){let L=await B(S),M=Xt.getWorker(String(L.id??""));if(!M||!A(M.resourceId))return h({ok:!1,error:"Worker was not found."},404);let ct=String(L.action??"");if(ct==="restart"){if(String(L.confirm??"")!==M.name)return h({ok:!1,error:`Type "${M.name}" to restart this worker.`},409);let lt=k.find((Nt)=>Nt.id===M.target.operationId);if(!lt)return h({ok:!1,error:"The allowlisted worker restart operation is unavailable."},409);let It=await ao(c,U,lt),Pe=Xt.reconcileWorker(M.id,It.ok?"in_sync":"unavailable",{...M.observedState,lastRestartAt:new Date().toISOString(),command:It.command??null,error:It.error??It.stderr??null});return K("worker_restarted",{workerId:M.id,ok:It.ok},M.resourceId),h({...It,worker:Pe},It.ok?200:409)}if(ct==="scale")return h({ok:!1,error:M.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 h({ok:!1,error:"Action must be restart or scale."},422)}}if(w.pathname.startsWith("/api/telemetry/")){let s=o.environments.get(U),g=new uo(o.store),_=o.store.listResources(o.project.id,s?.id),I=["/api/telemetry/query","/api/telemetry/tail","/api/telemetry/export","/api/telemetry/saved-queries","/api/telemetry/refresh"].includes(w.pathname)?"runtime:logs":"runtime:read",A=z.role==="admin"||!!s&&ki(z,s.id,I),v=A?_:_.filter((j)=>Kt(z,j.id,I)),D=(j)=>dR(v,A,j),k=(j)=>{let K=new Date,L={"1h":3600000,"6h":21600000,"24h":86400000,"7d":604800000,"30d":2592000000},M=String(j.to??K.toISOString()),ct=String(j.from??new Date(new Date(M).getTime()-(L[String(j.range??"1h")]??L["1h"])).toISOString()),lt=(Pe)=>{let Nt=(Array.isArray(Pe)?Pe:String(Pe??"").split(",")).map(String).filter(Boolean);return Nt.length?Nt:void 0},It=lt(j.kinds)?.filter((Pe)=>["metric","log","trace","request","event"].includes(Pe));return{projectId:o.project.id,environmentId:s?.id,resourceIds:D(j.resources),kinds:It,names:lt(j.names),sources:lt(j.sources),levels:lt(j.levels),from:ct,to:M,text:String(j.text??"")||void 0,traceId:String(j.traceId??"")||void 0,requestId:String(j.requestId??"")||void 0,deploymentId:String(j.deploymentId??"")||void 0,releaseId:String(j.releaseId??"")||void 0,workloadId:String(j.workloadId??"")||void 0,cursor:String(j.cursor??"")||void 0,limit:Number(j.limit)||void 0}},W=Object.fromEntries(w.searchParams.entries()),T=(j=!1)=>Ll({controlPlane:o.store,projectId:o.project.id,environmentId:s?.id,config:c,environment:U,force:j,lightweight:!j}),et=()=>{let j=o.store.getSetting(`telemetry.collection:${o.project.id}:${s?.id??"all"}`)??{};return{generatedAt:String(j.generatedAt??new Date().toISOString()),cached:!0,statuses:Array.isArray(j.statuses)?j.statuses:[],errors:Array.isArray(j.errors)?j.errors:[],policy:j.policy??ac(o.store,o.project.id)}};if(w.pathname==="/api/telemetry/status"&&S.method==="GET"){T(!1);let j=et(),K=A?j.statuses:g.status(o.project.id,s?.id,j.policy.rawDays,j.policy.samplingRate,v.map((M)=>M.id)),L=K.reduce((M,ct)=>M+ct.estimatedDailyBytes*30,0);return h({ok:!0,generatedAt:j.generatedAt,cached:j.cached,sources:K,errors:A?j.errors:[],policy:j.policy,retention:{rawDays:j.policy.rawDays,downsampleAfterDays:j.policy.downsampleAfterDays,downsampleBucketMs:j.policy.downsampleBucketMs,maxRecords:j.policy.maxRecords},estimatedMonthlyBytes:L,estimatedMonthlyCostUsd:YR(L,j.policy),costEstimateConfigured:j.policy.estimatedStorageUsdPerGbMonth>0})}if(w.pathname==="/api/telemetry/settings"&&S.method==="GET")return h({ok:!0,policy:ac(o.store,o.project.id)});if(w.pathname==="/api/telemetry/settings"&&S.method==="PATCH"){let j=ZR(o.store,o.project.id,await B(S));return SR(o.project.id),h({ok:!0,policy:j})}if(w.pathname==="/api/telemetry/query"&&S.method==="GET"){T(!1);let j=et();return h({ok:!0,collection:{generatedAt:j.generatedAt,cached:j.cached},...g.query(k(W))})}if(w.pathname==="/api/telemetry/tail"&&S.method==="GET"){T(!1);let j=new TextEncoder,K=new Date,L=k({...W,kinds:W.kinds||"log,request,event,trace",from:W.from||new Date(K.getTime()-120000).toISOString(),to:K.toISOString(),limit:Math.min(1000,Number(W.limit)||200),cursor:void 0}),M=S.headers.get("last-event-id")||String(W.cursor??"")||void 0,ct,lt=!1,It=!1,Pe=new ReadableStream({start(Nt){let Fn=()=>{if(lt)return;if(lt=!0,ct)clearInterval(ct);S.signal.removeEventListener("abort",Fn);try{Nt.close()}catch{}},ag=async()=>{if(lt||It)return;It=!0;try{let or=g.tail({...L,to:new Date(Date.now()+1000).toISOString()},M);for(let sg of or.records)M=XR(sg)??M,Nt.enqueue(j.encode(`id: ${M??""}
|
|
501
|
-
event: record
|
|
502
|
-
data: ${JSON.stringify(sg)}
|
|
503
|
-
|
|
504
|
-
`));if(or.cursor)M=or.cursor}catch(or){Nt.enqueue(j.encode(`event: error
|
|
505
|
-
data: ${JSON.stringify({message:or instanceof Error?or.message:String(or)})}
|
|
506
|
-
|
|
507
|
-
`))}finally{It=!1}};ag(),ct=setInterval(()=>{if(ag(),!lt)Nt.enqueue(j.encode(`event: heartbeat
|
|
508
|
-
data: ${JSON.stringify({cursor:M,at:new Date().toISOString()})}
|
|
509
|
-
|
|
510
|
-
`))},5000),ct.unref?.(),S.signal.addEventListener("abort",Fn,{once:!0})},cancel(){if(lt=!0,ct)clearInterval(ct)}});return new Response(Pe,{headers:{"cache-control":"no-cache, no-transform",connection:"keep-alive","content-type":"text/event-stream; charset=utf-8","x-accel-buffering":"no"}})}if(w.pathname==="/api/telemetry/series"&&S.method==="GET"){T(!1);let j=et(),K=["sum","avg","min","max","count","p50","p90","p95","p99"].includes(String(W.aggregation))?W.aggregation:"avg",L=k({...W,kinds:"metric",limit:5000}),M=g.series({...L,bucketMs:Number(W.bucketMs)||60000,aggregation:K,timezone:String(W.timezone??"UTC"),compareFrom:W.compareFrom,compareTo:W.compareTo});return h({ok:!0,collection:{generatedAt:j.generatedAt,cached:j.cached},query:{aggregation:K,bucketMs:Number(W.bucketMs)||60000,timezone:String(W.timezone??"UTC")},series:M})}if(w.pathname==="/api/telemetry/refresh"&&S.method==="POST")return h({ok:!0,...await T(!0)});if(w.pathname==="/api/telemetry/export"&&S.method==="POST"){let j=await B(S);await T(!1);let K=g.query({...k(j),limit:Math.min(5000,Number(j.limit)||5000),cursor:void 0});if((j.format==="csv"?"csv":"json")==="json")return new Response(JSON.stringify({exportedAt:new Date().toISOString(),query:k(j),...K},null,2),{headers:{"content-disposition":'attachment; filename="ts-cloud-telemetry.json"',"content-type":"application/json; charset=utf-8"}});let M=["timestamp","kind","source","name","level","value","unit","message","traceId","requestId","deploymentId","releaseId","workloadId"],ct=[M.join(","),...K.records.map((lt)=>M.map((It)=>`"${String(lt[It]??"").replaceAll('"','""')}"`).join(","))].join(`
|
|
511
|
-
`);return new Response(ct,{headers:{"content-disposition":'attachment; filename="ts-cloud-telemetry.csv"',"content-type":"text/csv; charset=utf-8"}})}if(w.pathname==="/api/telemetry/saved-queries"&&S.method==="GET"){let j=X(z);return h({ok:!0,queries:g.listSavedQueries(o.project.id,j.actor?.id)})}if(w.pathname==="/api/telemetry/saved-queries"&&S.method==="POST"){let j=await B(S),K=X(z);return h({ok:!0,query:g.saveQuery(o.project.id,K.actor?.id,String(j.name??""),k(j.query??j))},201)}if(w.pathname==="/api/telemetry/saved-queries"&&S.method==="DELETE"){let j=await B(S),K=X(z),L=g.deleteSavedQuery(o.project.id,K.actor?.id,String(j.id??""));return h({ok:L},L?200:404)}}if(w.pathname.startsWith("/api/configuration")){let s=o.environments.get(U),g=z.role==="admin"||!!Be.capabilities?.includes("secrets:read"),_=z.role==="admin"||!!Be.capabilities?.includes("secrets:write"),I={projectId:o.project.id,environmentId:s?.id},A={"cache-control":"no-store"};if(w.pathname==="/api/configuration"&&S.method==="GET"){let v=Object.fromEntries(w.searchParams),D=v.scopeType||v.scopeId?Di(v,I):void 0,k=["variable","secret"].includes(String(v.kind))?v.kind:void 0,W=D?.type==="preview"?Ht.previews.getInstance(D.id):void 0,T=W?Ht.previews.getDefinition(W.definitionId):void 0,et=D?await we.resolve({projectId:o.project.id,environmentId:D.environmentId,resourceId:D.resourceId,functionId:D.type==="function"?D.id:void 0,previewId:D.previewId,trustedPreview:!!W&&!W.fork,allowedPreviewSecrets:T?.inheritedSecrets,nativeReferences:!0,canReadSecretMetadata:g}):void 0,j=o.store.listResources(o.project.id);return h({ok:!0,entries:we.list({projectId:o.project.id,scope:D,kind:k,search:v.search,canReadSecretMetadata:g}),effectiveEntries:et?Object.values(et.entries).filter((K)=>!k||K.kind===k).filter((K)=>!v.search||K.key.toLowerCase().includes(String(v.search).toLowerCase())):[],configurationHash:et?.configurationHash,warnings:et?.warnings??[],scopes:{project:o.project,environments:o.store.listEnvironments(o.project.id),resources:j.filter((K)=>K.kind!=="function"),functions:j.filter((K)=>K.kind==="function"),previews:Ht.previews.listInstances({projectId:o.project.id}).filter((K)=>K.status!=="destroyed").map((K)=>({id:K.id,name:K.name,environmentId:K.baseEnvironmentId,resourceId:K.resourceId,fork:K.fork,status:K.status}))}},200,A)}if(w.pathname==="/api/configuration/export"&&S.method==="GET"){let v=Di(Object.fromEntries(w.searchParams),I);return new Response(we.exportVariables({projectId:o.project.id,scope:v}),{headers:{...A,"content-disposition":'attachment; filename="ts-cloud.env"',"content-type":"text/plain; charset=utf-8"}})}if(w.pathname==="/api/configuration/plan"&&S.method==="POST"){let v=await B(S),D=Di(v,I),k=v.values&&typeof v.values==="object"&&!Array.isArray(v.values)?Object.fromEntries(Object.entries(v.values).map(([W,T])=>[W,String(T)])):{};return h({ok:!0,plan:we.plan({projectId:o.project.id,scope:D,values:k,removeMissing:v.removeMissing===!0})},200,A)}if(w.pathname==="/api/configuration"&&S.method==="POST"){let v=await B(S),D=Di(v,I),k=v.kind==="secret"?"secret":"variable",W=String(v.key??"");if(k==="secret"&&!_)return h({ok:!1,error:"Secret write permission is required."},403,A);try{let T=await we.set({organizationId:o.organization.id,projectId:o.project.id,scope:D,key:W,kind:k,value:v.value==null?void 0:String(v.value),reference:v.reference==null?void 0:String(v.reference),backend:v.backend,required:v.required===!0,expectedVersion:v.expectedVersion==null?void 0:Number(v.expectedVersion),confirmed:String(v.confirm??"")===W,idempotencyKey:S.headers.get("idempotency-key")??v.idempotencyKey,actorId:X(z).actor?.id});return h({ok:!0,entry:we.list({projectId:o.project.id,scope:D,canReadSecretMetadata:g}).find((et)=>et.id===T.entry.id),mutation:T.mutation,warnings:T.warnings},T.mutation.added.length?201:200,A)}catch(T){return h({ok:!1,error:T instanceof Error?T.message:String(T)},409,A)}}if(w.pathname==="/api/configuration/import"&&S.method==="POST"){let v=await B(S),D=Di(v,I),k=Array.isArray(v.secretKeys)?v.secretKeys.map(String):[];if(k.length&&!_)return h({ok:!1,error:"Secret write permission is required."},403,A);try{let W=await we.importDotenv({organizationId:o.organization.id,projectId:o.project.id,scope:D,source:String(v.source??""),secretKeys:k,backend:v.backend,confirmed:v.confirm==="import",idempotencyKey:S.headers.get("idempotency-key")??v.idempotencyKey,actorId:X(z).actor?.id});return h({ok:W.document.valid,diagnostics:W.document.diagnostics,mutation:W.mutation,warnings:W.warnings},W.document.valid?200:422,A)}catch(W){return h({ok:!1,error:W instanceof Error?W.message:String(W)},409,A)}}if(w.pathname==="/api/configuration/dependencies"&&S.method==="POST"){let v=await B(S),D=Wn.get(String(v.entryId??"")),k=o.store.getResource(String(v.resourceId??""));if(!D||D.projectId!==o.project.id||!k||k.projectId!==o.project.id)return h({ok:!1,error:"Configuration entry or dependent resource was not found."},404,A);return h({ok:!0,dependency:Wn.setDependency({entryId:D.id,resourceId:k.id,injectionTarget:["native_reference","file"].includes(String(v.injectionTarget))?v.injectionTarget:"environment",required:v.required!==!1,requiresRedeploy:v.requiresRedeploy!==!1,lastDeployedVersion:v.lastDeployedVersion==null?void 0:Number(v.lastDeployedVersion)})},200,A)}if(w.pathname==="/api/configuration/transfer"&&S.method==="POST"){let v=await B(S),D=Wn.get(String(v.id??"")),k=Di({...v,scopeType:v.targetScopeType,scopeId:v.targetScopeId},I);if(!D||D.projectId!==o.project.id)return h({ok:!1,error:"Configuration entry was not found."},404,A);if(D.kind==="secret"&&!_)return h({ok:!1,error:"Secret write permission is required."},403,A);try{let W=await we.transfer({entryId:D.id,targetScope:k,mode:v.mode==="move"?"move":"copy",confirmed:v.confirm===D.key,actorId:X(z).actor?.id,idempotencyKey:S.headers.get("idempotency-key")??v.idempotencyKey});return h({ok:!0,entry:we.list({projectId:o.project.id,scope:k,canReadSecretMetadata:g}).find((T)=>T.id===W.entry.id),mutation:W.mutation},200,A)}catch(W){return h({ok:!1,error:W instanceof Error?W.message:String(W)},409,A)}}if(w.pathname==="/api/configuration/bulk"&&S.method==="POST"){let v=await B(S),D=Array.isArray(v.ids)?v.ids.map(String).slice(0,500):[],k=D.map((T)=>Wn.get(T)).filter((T)=>!!T&&T.projectId===o.project.id);if(k.length!==D.length)return h({ok:!1,error:"One or more configuration entries were not found."},404,A);if(k.some((T)=>T.kind==="secret")&&!_)return h({ok:!1,error:"Secret write permission is required."},403,A);if(v.action!=="delete"||v.confirm!=="bulk")return h({ok:!1,error:"Bulk deletion requires action delete and confirm bulk."},409,A);let W=[];try{for(let T of k)W.push(await we.remove({entryId:T.id,expectedVersion:T.version,confirmed:!0,actorId:X(z).actor?.id}));return h({ok:!0,removed:W.flatMap((T)=>T.removed),affectedResourceIds:[...new Set(W.flatMap((T)=>T.affectedResourceIds))].sort()},200,A)}catch(T){return h({ok:!1,error:T instanceof Error?T.message:String(T),partial:W.flatMap((et)=>et.removed)},409,A)}}if(w.pathname==="/api/configuration/reveal"&&S.method==="POST"){let v=await B(S),D=Bt.resolveSession(S);try{return h({ok:!0,value:await we.reveal({entryId:String(v.id??""),canRevealSecrets:g,recentlyAuthenticated:!G||!!D&&F.isRecentlyAuthenticated(D),actorId:X(z).actor?.id})},200,A)}catch(k){return h({ok:!1,error:k instanceof Error?k.message:String(k)},403,A)}}if(w.pathname==="/api/configuration"&&S.method==="DELETE"){let v=await B(S),D=Wn.get(String(v.id??""));if(D?.kind==="secret"&&!_)return h({ok:!1,error:"Secret write permission is required."},403,A);if(!D||D.projectId!==o.project.id)return h({ok:!1,error:"Configuration entry was not found."},404,A);try{return h({ok:!0,mutation:await we.remove({entryId:D.id,expectedVersion:Number(v.expectedVersion),confirmed:String(v.confirm??"")===D.key,actorId:X(z).actor?.id})},200,A)}catch(k){return h({ok:!1,error:k instanceof Error?k.message:String(k)},409,A)}}}if(w.pathname.startsWith("/api/fleet")){let s=X(z).actor?.id,g=(_,I=409)=>h({ok:!1,error:_ instanceof Error?_.message:String(_)},I,{"cache-control":"no-store"});if(w.pathname==="/api/fleet"&&S.method==="GET")return h({ok:!0,servers:vi.list(o.project.id),resources:o.store.listResources(o.project.id),operations:yt.list({projectId:o.project.id,limit:200}).filter((_)=>_.operation.kind.startsWith("fleet."))},200,{"cache-control":"no-store"});if(w.pathname==="/api/fleet"&&S.method==="POST"){let _=await B(S);try{return h({ok:!0,server:en.enroll({organizationId:o.organization.id,projectId:o.project.id,name:String(_.name??""),provider:["aws","hetzner"].includes(String(_.provider))?_.provider:"ssh",providerId:_.providerId?String(_.providerId):void 0,region:_.region?String(_.region):void 0,zone:_.zone?String(_.zone):void 0,endpoint:String(_.endpoint??""),sshUser:String(_.sshUser??"deploy"),sshPort:_.sshPort?Number(_.sshPort):22,credentialRef:String(_.credentialRef??""),roles:Array.isArray(_.roles)?_.roles:[],labels:_.labels&&typeof _.labels==="object"?_.labels:{}})},201)}catch(I){return g(I,422)}}if(w.pathname==="/api/fleet/action"&&S.method==="POST"){let _=await B(S),I=String(_.id??""),A=String(_.action??"");try{if(A==="test")return h({ok:!0,server:await en.test(I)});if(A==="validate")return h({ok:!0,server:await en.validate(I)});if(A==="review_host_key")return h({ok:!0,server:en.reviewHostKey(I,String(_.fingerprint??""))});if(A==="bootstrap")return h({ok:!0,...en.bootstrap(I,_.confirmed===!0)},_.confirmed===!0?202:200);if(A==="heartbeat")return h({ok:!0,server:en.heartbeat(I,{usage:_.usage&&typeof _.usage==="object"?_.usage:{}})});if(A==="drain")return h({ok:!0,server:en.drain(I,_.completed===!0)});if(A==="uncordon")return h({ok:!0,server:en.uncordon(I)});if(A==="archive")return h({ok:!0,server:en.archive(I,String(_.confirmation??""))});return g("Unsupported fleet action.",422)}catch(v){return g(v)}}}if(w.pathname.startsWith("/api/capacity")){let s=(g,_=409)=>h({ok:!1,error:g instanceof Error?g.message:String(g)},_,{"cache-control":"no-store"});if(w.pathname==="/api/capacity"&&S.method==="GET")return h({ok:!0,pools:jn.listPools(o.project.id),placements:jn.listPlacements(o.project.id),servers:vi.list(o.project.id)},200,{"cache-control":"no-store"});if(w.pathname==="/api/capacity"&&S.method==="POST"){let g=await B(S);try{return h({ok:!0,pool:jn.createPool({organizationId:o.organization.id,projectId:o.project.id,name:String(g.name??""),purpose:String(g.purpose??"application"),backend:String(g.backend??"server"),region:g.region?String(g.region):void 0,architecture:g.architecture?String(g.architecture):void 0,labels:g.labels&&typeof g.labels==="object"?g.labels:{},requiredServerLabels:g.requiredServerLabels&&typeof g.requiredServerLabels==="object"?g.requiredServerLabels:{},toleratedTaints:Array.isArray(g.toleratedTaints)?g.toleratedTaints.map(String):[],capacity:g.capacity&&typeof g.capacity==="object"?g.capacity:{},maxWorkloads:Number(g.maxWorkloads??10),costWeight:Number(g.costWeight??1),spreadKey:g.spreadKey?String(g.spreadKey):void 0,concurrency:Number(g.concurrency??1),ephemeralWorkspaces:!0,allowProductionSecrets:!1,status:"active"})},201)}catch(_){return s(_,422)}}if(w.pathname==="/api/capacity/member"&&S.method==="POST"){let g=await B(S);try{return jn.addMember(String(g.poolId??""),String(g.serverId??"")),h({ok:!0,pool:jn.getPool(String(g.poolId??""))})}catch(_){return s(_,422)}}if(w.pathname==="/api/capacity/explain"&&S.method==="POST"){let g=await B(S);try{return h({ok:!0,decisions:Gl.explain(o.project.id,{purpose:String(g.purpose??"application"),resources:g.resources&&typeof g.resources==="object"?g.resources:{},region:g.region?String(g.region):void 0,architecture:g.architecture?String(g.architecture):void 0,labels:g.labels&&typeof g.labels==="object"?g.labels:{}})})}catch(_){return s(_,422)}}if(w.pathname==="/api/capacity/action"&&S.method==="POST"){let g=await B(S);try{if(g.action==="drain")return h({ok:!0,...Gl.drainPool(String(g.poolId??""))});if(g.action==="enable")return h({ok:!0,pool:jn.updatePool(String(g.poolId??""),{status:"active"})});if(g.action==="disable")return h({ok:!0,pool:jn.updatePool(String(g.poolId??""),{status:"disabled"})});return s("Unsupported capacity action.",422)}catch(_){return s(_,422)}}}if(w.pathname.startsWith("/api/regions")){let s=(g,_=409)=>h({ok:!1,error:g instanceof Error?g.message:String(g)},_,{"cache-control":"no-store"});if(w.pathname==="/api/regions"&&S.method==="GET")return h({ok:!0,topologies:cr.list(o.project.id).map((g)=>({topology:g,targets:cr.targets(g.id),channels:cr.channels(g.id),route:cr.route(g.id),executions:cr.executions(g.id)}))},200,{"cache-control":"no-store"});if(w.pathname==="/api/regions"&&S.method==="POST"){let g=await B(S);try{return h({ok:!0,topology:Zl.create({organizationId:o.organization.id,projectId:o.project.id,environmentId:o.environments.get(U)?.id,name:String(g.name??""),hostname:String(g.hostname??""),regions:Array.isArray(g.regions)?g.regions:[],trafficPolicy:g.trafficPolicy==="weighted"||g.trafficPolicy==="latency"?g.trafficPolicy:"active_passive",dataPolicy:{replicate:Array.isArray(g.replicate)?g.replicate:["s3","dynamodb","secrets"],maxLagSeconds:Number(g.maxLagSeconds??30),retainOnDestroy:g.retainOnDestroy!==!1},dnsProvider:"route53",cdnEnabled:g.cdnEnabled===!0,wafEnabled:g.wafEnabled===!0})},201)}catch(_){return s(_,422)}}if(w.pathname==="/api/regions/action"&&S.method==="POST"){let g=await B(S);try{return h({ok:!0,...Zl.enqueue({topologyId:String(g.topologyId??""),kind:String(g.action??""),targetRegion:g.targetRegion?String(g.targetRegion):void 0,revision:g.revision?String(g.revision):void 0,manifest:g.manifest&&typeof g.manifest==="object"?g.manifest:{},confirmation:g.confirmation?String(g.confirmation):void 0,deleteData:g.deleteData===!0})},202)}catch(_){return s(_,422)}}}if(w.pathname.startsWith("/api/maintenance")){let s=(g,_=409)=>h({ok:!1,error:g instanceof Error?g.message:String(g)},_,{"cache-control":"no-store"});if(w.pathname==="/api/maintenance"&&S.method==="GET")return h({ok:!0,manifests:hn.manifests(o.organization.id),windows:hn.windows(o.project.id),campaigns:hn.campaigns(o.project.id).map((g)=>({campaign:g,targets:hn.targets(g.id)})),cleanups:hn.cleanups(o.project.id),drills:hn.drills(o.project.id)},200,{"cache-control":"no-store"});if(w.pathname==="/api/maintenance/cleanup-preview"&&S.method==="POST"){let g=await B(S);try{return h({ok:!0,plan:await Do.previewCleanup({projectId:o.project.id,kind:String(g.kind??"operations"),criteria:{olderThanDays:Number(g.olderThanDays??30)}},Yl)},201)}catch(_){return s(_,422)}}if(w.pathname==="/api/maintenance/cleanup-apply"&&S.method==="POST"){let g=await B(S);try{return h({ok:!0,...Do.enqueueCleanup(String(g.planId??""),String(g.confirmation??""))},202)}catch(_){return s(_,422)}}if(w.pathname==="/api/maintenance/drill"&&S.method==="POST"){let g=await B(S);try{return h({ok:!0,drill:hn.createDrill({projectId:o.project.id,scenario:String(g.scenario??"control_plane"),isolatedTarget:String(g.isolatedTarget??""),expectedRpoMinutes:Number(g.expectedRpoMinutes??60),expectedRtoMinutes:Number(g.expectedRtoMinutes??30),recoveryPointId:g.recoveryPointId?String(g.recoveryPointId):void 0,topologyId:g.topologyId?String(g.topologyId):void 0})},201)}catch(_){return s(_,422)}}if(w.pathname==="/api/maintenance/drill-run"&&S.method==="POST"){let g=await B(S);try{return h({ok:!0,...Do.enqueueDrill(String(g.drillId??""))},202)}catch(_){return s(_,422)}}}if(w.pathname.startsWith("/api/volumes")){let s=o.environments.get(U),g=X(z).actor?.id,_=(I,A=409)=>h({ok:!1,error:I instanceof Error?I.message:String(I)},A,{"cache-control":"no-store"});if(w.pathname==="/api/volumes"&&S.method==="GET"){let I=wo.inventory(o.project.id,s?.id),A=o.store.listResources(o.project.id,s?.id).map((v)=>({id:v.id,name:v.name,slug:v.slug,kind:v.kind,provider:v.provider,providerId:v.providerId}));return h({ok:!0,volumes:I,resources:A,operations:yt.list({projectId:o.project.id,limit:100}).filter((v)=>v.operation.kind.startsWith("volume.")),recoveryPoints:Ft.listRecoveryPoints(o.project.id).filter((v)=>v.kind==="volume"),providers:Ao.map((v)=>({provider:v.provider,type:v.type,capabilities:v.capabilities()}))},200,{"cache-control":"no-store"})}if(w.pathname==="/api/volumes"&&S.method==="POST"){let I=await B(S);try{return h({ok:!0,...un.create({organizationId:o.organization.id,projectId:o.project.id,environmentId:s?.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:g})},202,{"cache-control":"no-store"})}catch(A){return _(A,422)}}if(w.pathname==="/api/volumes/attach"&&S.method==="POST"){let I=await B(S);try{return h({ok:!0,...un.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:g})},202)}catch(A){return _(A,422)}}if(w.pathname==="/api/volumes/detach"&&S.method==="POST"){let I=await B(S);try{return h({ok:!0,...un.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:g})},202)}catch(A){return _(A)}}if(w.pathname==="/api/volumes/resize"&&S.method==="POST"){let I=await B(S);try{return h({ok:!0,...un.resize(String(I.volumeId??""),Number(I.capacityBytes),{drained:I.drained===!0,actorId:g})},202)}catch(A){return _(A,422)}}if(w.pathname==="/api/volumes/snapshot"&&S.method==="POST"){let I=await B(S);try{return h({ok:!0,...un.snapshot(String(I.volumeId??""),{name:I.name?String(I.name):void 0,actorId:g})},202)}catch(A){return _(A,422)}}if(w.pathname==="/api/volumes/restore"&&S.method==="POST"){let I=await B(S);try{return h({ok:!0,...un.restore(String(I.snapshotId??""),{name:String(I.name??""),actorId:g})},202)}catch(A){return _(A,422)}}if(w.pathname==="/api/volumes/discover"&&S.method==="POST")try{return h({ok:!0,volumes:await un.discover({organizationId:o.organization.id,projectId:o.project.id,environmentId:s?.id,actorId:g})})}catch(I){return _(I,502)}if(w.pathname==="/api/volumes/adopt"&&S.method==="POST"){let I=await B(S);try{return h({ok:!0,volume:un.adopt(String(I.volumeId??""),{name:String(I.name??""),actorId:g})})}catch(A){return _(A,422)}}if(w.pathname==="/api/volumes"&&S.method==="DELETE"){let I=await B(S),A=Bt.resolveSession(S);try{return h({ok:!0,...un.delete(String(I.volumeId??""),{recentAuthAt:!G||A&&F.isRecentlyAuthenticated(A)?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:g})},202)}catch(v){return _(v)}}}if(w.pathname==="/api/backups"&&S.method==="GET"){let s=o.environments.get(U),g=Ft.listPolicies(o.project.id,s?.id),_=new Set(g.map((k)=>k.id)),I=Ft.listRecoveryPoints(o.project.id).filter((k)=>!k.policyId||_.has(k.policyId)),A=Ft.listJobs(o.project.id).filter((k)=>!k.policyId||_.has(k.policyId)),v=(k)=>({...k,credentialRef:void 0,encryptionKeyRef:void 0,credentialsConfigured:!!k.credentialRef,clientEncryptionConfigured:!!k.encryptionKeyRef}),D=await Promise.all(Ft.listDestinations(o.project.id).map(async(k)=>({...v(k),credentialStatus:await Wu(k,gn)})));return h({ok:!0,destinations:D,policies:g,recoveryPoints:I,jobs:A,coverage:Ft.coverage(o.project.id).filter((k)=>_.has(k.policy.id)),resources:s?o.store.listResources(o.project.id,s.id).map((k)=>({id:k.id,name:k.name,slug:k.slug,kind:k.kind})):[]})}if(w.pathname==="/api/backups/destinations"&&S.method==="POST"){let s=await B(S),g=String(s.name??"").trim(),_=String(s.provider??""),I=String(s.encryption??"provider"),A=`secret://data-services/backups/${o.project.id}/${g}`,v=[];if(!["aws_s3","s3_compatible","aws_backup"].includes(_))return h({ok:!1,error:"A supported backup destination provider is required."},422);if(!["provider","client_side","both"].includes(I))return h({ok:!1,error:"Encryption must be provider, client_side, or both."},422);try{let D,k;if(s.credentials&&typeof s.credentials==="object"&&!Array.isArray(s.credentials))D=`${A}/credentials`,await gn.put(D,JSON.stringify(s.credentials)),v.push(D);if(I!=="provider"){let T=String(s.encryptionKey??"");if(T.length<32)throw Error("Client-side encryption keys must contain at least 32 characters.");k=`${A}/encryption-key`,await gn.put(k,T),v.push(k)}let W=Ft.createDestination({organizationId:o.organization.id,projectId:o.project.id,name:g,provider:_,endpoint:s.endpoint?String(s.endpoint):void 0,endpointPolicy:s.endpointPolicy==="allow_private"?"allow_private":"public_https",bucket:s.bucket?String(s.bucket):void 0,prefix:String(s.prefix??""),region:s.region?String(s.region):Un,forcePathStyle:s.forcePathStyle===!0,credentialRef:D,encryption:I,encryptionKeyRef:k,immutability:s.immutability&&typeof s.immutability==="object"&&!Array.isArray(s.immutability)?s.immutability:{},status:"untested"});return h({ok:!0,destination:{...W,credentialRef:void 0,encryptionKeyRef:void 0,credentialsConfigured:!!D,clientEncryptionConfigured:!!k}},201)}catch(D){for(let k of v)await gn.remove(k).catch(()=>{});return h({ok:!1,error:D instanceof Error?D.message:String(D)},422)}}if(w.pathname==="/api/backups/destinations/test"&&S.method==="POST"){let s=await B(S),g=Ft.getDestination(String(s.id??""));if(!g||g.projectId!==o.project.id)return h({ok:!1,error:"Backup destination was not found."},404);if(g.provider==="aws_backup")return h({ok:!1,error:"AWS Backup destinations are verified by creating a provider recovery point."},422);try{return await Ql.test(g),h({ok:!0,destination:Ft.recordDestinationTest(g.id,{ok:!0})})}catch(_){let I=_ instanceof Error?_.message:String(_);return Ft.recordDestinationTest(g.id,{ok:!1,error:I}),h({ok:!1,error:I},502)}}if(w.pathname==="/api/backups/policies"&&S.method==="POST"){let s=await B(S),g=o.environments.get(U),_=Ft.getDestination(String(s.destinationId??"")),I=String(s.resourceKind??""),A=s.dataServiceId?String(s.dataServiceId):void 0,v=A?kt.get(A):void 0,D=s.resourceId?String(s.resourceId):void 0,k=D?o.store.getResource(D):void 0;if(!g)return h({ok:!1,error:"Environment was not found."},404);if(!_||_.projectId!==o.project.id)return h({ok:!1,error:"Backup destination was not found."},404);if(!["managed_database","logical_database","volume","files","control_plane","infrastructure"].includes(I))return h({ok:!1,error:"A supported backup resource kind is required."},422);if(A&&(!v||v.projectId!==o.project.id||v.environmentId!==g.id))return h({ok:!1,error:"Data service was not found in this environment."},404);if(D&&(!k||k.projectId!==o.project.id||k.environmentId!==g.id))return h({ok:!1,error:"Resource was not found in this environment."},404);if(I==="managed_database"&&!v)return h({ok:!1,error:"Managed database policies require a data service."},422);if(I==="logical_database"&&(!v||!["container","server"].includes(v.provider)))return h({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(s.volumeName??""))))return h({ok:!1,error:"Volume policies require a scoped resource and valid volumeName."},422);let W=Array.isArray(s.includePatterns)?s.includePatterns.map(String).filter(Boolean):[];if(I==="files"&&(!k||!W.length))return h({ok:!1,error:"File policies require a scoped resource and at least one project-relative include path."},422);if(I==="control_plane"&&_.encryption==="provider")return h({ok:!1,error:"Control-plane policies require a destination with client-side encryption."},422);if(I==="infrastructure"&&(_.provider!=="aws_backup"||!W.some((T)=>T.startsWith("resource:arn:"))||!W.some((T)=>T.startsWith("role:arn:"))))return h({ok:!1,error:"Infrastructure policies require an AWS Backup destination plus resource:<arn> and role:<arn> include values."},422);try{let T=Ft.createPolicy({organizationId:o.organization.id,projectId:o.project.id,environmentId:g.id,resourceId:D,dataServiceId:A,destinationId:_.id,name:String(s.name??"").trim(),resourceKind:I,schedule:String(s.schedule??"daily"),timezone:String(s.timezone??"UTC"),retention:s.retention&&typeof s.retention==="object"&&!Array.isArray(s.retention)?s.retention:{keepLast:7,expireAfterDays:30},compression:["none","gzip","zstd"].includes(String(s.compression))?s.compression:"gzip",encryption:["destination","client_side","both"].includes(String(s.encryption))?s.encryption:"destination",includePatterns:I==="volume"?[String(s.volumeName),...W]:W,excludePatterns:Array.isArray(s.excludePatterns)?s.excludePatterns.map(String):[],expectedRpoMinutes:Math.max(1,Number(s.expectedRpoMinutes)||1440),expectedRtoMinutes:Math.max(1,Number(s.expectedRtoMinutes)||120),healthCheckId:s.healthCheckId?String(s.healthCheckId):void 0,enabled:s.enabled!==!1});return h({ok:!0,policy:T},201)}catch(T){return h({ok:!1,error:T instanceof Error?T.message:String(T)},422)}}if(w.pathname==="/api/backups/run"&&S.method==="POST"){let s=await B(S),g=Ft.getPolicy(String(s.policyId??"")),_=o.environments.get(U);if(!g||g.projectId!==o.project.id||g.environmentId!==_?.id)return h({ok:!1,error:"Backup policy was not found in this environment."},404);try{let I=ir.enqueueBackup(g,new Date().toISOString(),X(z).actor?.id);return h({ok:!0,job:I},202)}catch(I){return h({ok:!1,error:I instanceof Error?I.message:String(I)},409)}}if(w.pathname==="/api/backups/verify"&&S.method==="POST"){let s=await B(S),g=Ft.getRecoveryPoint(String(s.recoveryPointId??""));if(!g||g.projectId!==o.project.id)return h({ok:!1,error:"Recovery point was not found."},404);return h({ok:!0,job:ir.enqueueVerification(g)},202)}if(w.pathname==="/api/backups/restore"&&S.method==="POST"){let s=await B(S),g=Ft.getRecoveryPoint(String(s.recoveryPointId??"")),_=s.mode==="in_place"?"in_place":"isolated",I=s.target&&typeof s.target==="object"&&!Array.isArray(s.target)?{...s.target,inPlace:_==="in_place"}:{inPlace:_==="in_place"},A=Bt.resolveSession(S),v={mode:_,target:I,targetName:String(s.targetName??""),confirm:s.confirm?String(s.confirm):void 0,recentAuth:!G||!!A&&F.isRecentlyAuthenticated(A),downtimeAcknowledged:s.downtimeAcknowledged===!0,safetyBackupId:s.safetyBackupId?String(s.safetyBackupId):void 0};if(!g||g.projectId!==o.project.id)return h({ok:!1,error:"Recovery point was not found."},404);if(s.drill===!0&&_!=="isolated")return h({ok:!1,error:"Recovery drills must use an isolated target."},422);try{let D=ir.planRestore(g,v);if(s.execute!==!0)return h({ok:!0,plan:D,executionCreated:!1});let k=ir.enqueueRestore(g,{...v,drill:s.drill===!0,actorId:X(z).actor?.id});return h({ok:!0,plan:D,job:k},202)}catch(D){return h({ok:!1,error:D instanceof Error?D.message:String(D)},409)}}if(w.pathname==="/api/backups/recovery-points"&&S.method==="POST"){let s=await B(S),g=Ft.getRecoveryPoint(String(s.id??""));if(!g||g.projectId!==o.project.id)return h({ok:!1,error:"Recovery point was not found."},404);if(s.held==null&&s.pinned==null)return h({ok:!1,error:"held or pinned must be provided."},422);return h({ok:!0,recoveryPoint:Ft.updateRecoveryPoint(g.id,{held:s.held==null?g.held:s.held===!0,pinned:s.pinned==null?g.pinned:s.pinned===!0})})}if(w.pathname==="/api/backups/retention"&&S.method==="POST")return h({ok:!0,jobs:ir.enqueueRetention()},202);if(w.pathname==="/api/data-services/capabilities"&&S.method==="GET"){let s=String(w.searchParams.get("engine")??""),g=String(w.searchParams.get("provider")??"");if(!["postgres","mysql","mariadb","redis","mongodb","libsql"].includes(s)||!["aws_rds","aws_aurora","aws_elasticache","server","container","external"].includes(g))return h({ok:!1,error:"A supported engine and provider are required."},422);return h({ok:!0,engine:s,provider:g,capabilities:Li(s,g)})}if(w.pathname==="/api/data-services"&&S.method==="GET"){let s=o.environments.get(U),g=kt.list(o.project.id,s?.id).map((_)=>{let I=kt.credential(_.id);return{..._,credentialRef:void 0,credential:I?{configured:!0,username:I.username,version:I.version,rotatedAt:I.rotatedAt}:void 0,dependencies:kt.dependencies(_.id).map((A)=>({resourceId:A.resourceId,requiresRedeploy:A.requiresRedeploy}))}});return h({ok:!0,services:g})}if(w.pathname==="/api/data-services/preview"&&S.method==="POST"){let s=await B(S);if(s.id){let I=kt.get(String(s.id)),A=o.environments.get(U),v=String(s.action??"");if(!I||I.projectId!==o.project.id||I.environmentId!==A?.id)return h({ok:!1,error:"Data service was not found in this environment."},404);if(!_o.includes(v))return h({ok:!1,error:`Action must be one of: ${_o.join(", ")}.`},422);try{return h({ok:!0,plan:hc.plan(I,v,s.changes??{})})}catch(D){return h({ok:!1,error:D instanceof Error?D.message:String(D)},422)}}let g=String(s.engine??""),_=String(s.provider??"");if(!["postgres","mysql","mariadb","redis","mongodb","libsql"].includes(g)||!["aws_rds","aws_aurora","aws_elasticache","server","container","external"].includes(_))return h({ok:!1,error:"A supported engine and provider are required."},422);return h({ok:!0,capabilities:Li(g,_),defaults:{publicExposure:!1,backupRetentionDays:7,deletionProtection:!0},productionExecutionCreated:!1})}if(w.pathname==="/api/data-services"&&S.method==="POST"){let s=await B(S),g=String(s.engine??""),_=String(s.provider??""),I=o.environments.get(U),A=X(z);if(!I)return h({ok:!1,error:"Environment was not found."},404);if(!["postgres","mysql","mariadb","redis","mongodb","libsql"].includes(g)||!["aws_rds","aws_aurora","aws_elasticache","server","container","external"].includes(_))return h({ok:!1,error:"A supported engine and provider are required."},422);let v={organizationId:o.organization.id,projectId:o.project.id,environmentId:I.id,resourceId:s.resourceId?String(s.resourceId):void 0,name:String(s.name??"").trim(),engine:g,provider:_,placement:String(s.placement??s.name??"").trim(),engineVersion:s.engineVersion?String(s.engineVersion):void 0,plan:String(s.plan??(_==="aws_elasticache"?"cache.t4g.micro":_==="aws_aurora"?"db.serverless":"db.t4g.micro")),storageGb:s.storageGb==null?void 0:Number(s.storageGb),highAvailability:s.highAvailability===!0,publicExposure:s.publicExposure===!0,allowedCidrs:Array.isArray(s.allowedCidrs)?s.allowedCidrs.map(String):[],desiredState:s.desiredState&&typeof s.desiredState==="object"&&!Array.isArray(s.desiredState)?s.desiredState:{},observedState:{},origin:s.adopt===!0?"adopted":"managed",managementEnabled:s.adopt!==!0,ownerActorId:A.actor?.id,username:s.username?String(s.username):void 0};try{if(s.adopt===!0){let k=kt.create({...v,status:"adopted",credentialRef:void 0});return h({ok:!0,service:k,readOnly:!0},201)}if(!Ml({provider:_,engine:g}))return h({ok:!1,error:`No ${_}/${g} provisioning adapter is configured; adopt it read-only or choose a supported provider.`},422);let D=await hc.create(v);return h({ok:!0,service:D.service,operationId:D.operationId,oneTimeCredential:D.credential},201)}catch(D){return h({ok:!1,error:D instanceof Error?D.message:String(D)},422)}}if(w.pathname==="/api/data-services/connections"&&S.method==="GET"){let s=kt.get(String(w.searchParams.get("id")??"")),g=o.environments.get(U);if(!s||s.projectId!==o.project.id||s.environmentId!==g?.id)return h({ok:!1,error:"Data service was not found in this environment."},404);let _=typeof s.observedState.endpoint==="string"?s.observedState.endpoint:void 0,I=typeof s.observedState.readerEndpoint==="string"?s.observedState.readerEndpoint:void 0,A=Number(s.observedState.port)||(s.engine==="postgres"?5432:s.engine==="redis"?6379:s.engine==="mongodb"?27017:s.engine==="libsql"?8080:3306),v=typeof s.observedState.database==="string"?s.observedState.database:void 0,D=typeof s.observedState.tls==="boolean"?s.observedState.tls:s.provider.startsWith("aws_"),k=[..._?[{type:s.publicExposure?"external":"internal",host:_,port:A,database:v,tls:D}]:[],...I?[{type:"internal",host:I,port:A,database:v,tls:D}]:[],{type:"tunnel",host:_??s.placement,port:A,database:v,tls:D}];return h({ok:!0,serviceId:s.id,guidance:Lu(s,k)})}if(w.pathname==="/api/data-services/action"&&S.method==="POST"){let s=await B(S),g=kt.get(String(s.id??"")),_=o.environments.get(U),I=String(s.action??"");if(!g||g.projectId!==o.project.id||g.environmentId!==_?.id)return h({ok:!1,error:"Data service was not found in this environment."},404);if(!_o.includes(I))return h({ok:!1,error:`Action must be one of: ${_o.join(", ")}.`},422);let A=s.changes&&typeof s.changes==="object"&&!Array.isArray(s.changes)?s.changes:{};try{let v=hc.plan(g,I,A);if(s.execute!==!0)return h({ok:!0,plan:v,productionExecutionCreated:!1});let D=hc.enqueue(g,I,A,X(z).actor?.id);return h({ok:!0,plan:v,operationId:D},202)}catch(v){return h({ok:!1,error:v instanceof Error?v.message:String(v)},409)}}if(w.pathname==="/api/data-services/dependencies"&&S.method==="POST"){let s=await B(S),g=kt.get(String(s.id??"")),_=o.environments.get(U),I=o.store.getResource(String(s.resourceId??""));if(!g||g.projectId!==o.project.id||g.environmentId!==_?.id)return h({ok:!1,error:"Data service was not found in this environment."},404);if(!I||I.projectId!==o.project.id||I.environmentId!==_?.id)return h({ok:!1,error:"Dependent resource was not found in this environment."},404);if(s.remove===!0)return h({ok:kt.removeDependency(g.id,I.id)});return kt.addDependency({serviceId:g.id,resourceId:I.id,secretRef:g.credentialRef??`secret://data-services/${g.projectId}/${g.name}`,requiresRedeploy:s.requiresRedeploy!==!1}),h({ok:!0,dependencies:kt.dependencies(g.id).map((A)=>({resourceId:A.resourceId,requiresRedeploy:A.requiresRedeploy}))})}if(w.pathname==="/api/data-services/management"&&S.method==="POST"){let s=await B(S),g=kt.get(String(s.id??"")),_=o.environments.get(U);if(!g||g.projectId!==o.project.id||g.environmentId!==_?.id)return h({ok:!1,error:"Data service was not found in this environment."},404);if(g.origin!=="adopted"||s.reviewed!==!0||s.confirm!==g.name)return h({ok:!1,error:`Enabling management requires reviewed=true and typing ${g.name}.`},409);return h({ok:!0,service:kt.update(g.id,g.version,{managementEnabled:!0})})}if(w.pathname==="/api/data-services/reveal"&&S.method==="POST"){let s=await B(S),g=kt.get(String(s.id??"")),_=o.environments.get(U),I=g?kt.credential(g.id):void 0;if(!g||g.projectId!==o.project.id||g.environmentId!==_?.id)return h({ok:!1,error:"Data service was not found in this environment."},404);if(!I)return h({ok:!1,error:"No managed credential is configured."},404);return h({ok:!0,credential:{username:I.username,password:await gn.resolve(I.secretRef),version:I.version}},200,{"cache-control":"no-store"})}if(w.pathname==="/api/databases"&&S.method==="GET")return h(await Tf(c,U));if(w.pathname==="/api/databases"&&S.method==="POST"){let s=await B(S),g=String(s.name??"").trim();if(!zn(g))return h({ok:!1,error:"Database name must be a valid identifier (letters, numbers, underscore; not starting with a digit)."},422);return h({...await bf(c,U,g),name:g})}if(w.pathname==="/api/databases/vitess"&&S.method==="GET"){let s=await Hf(c,U);return h({...s,unhealthy:Lf(s.tablets),missingPrimary:Ff(s)})}if(w.pathname==="/api/databases/vitess/provision"&&S.method==="POST"){let s=await B(S);try{return h(await pf(c,U,{keyspace:String(s.keyspace??""),username:String(s.username??""),password:String(s.password??""),sharded:s.sharded===!0,confirm:String(s.confirm??"")}))}catch(g){return h({ok:!1,error:g instanceof Error?g.message:String(g)},422)}}if(w.pathname==="/api/databases/vitess/migrations"&&S.method==="GET"){let s=w.searchParams.get("keyspace")??void 0;return h(await Zf(c,U,s))}if(w.pathname==="/api/databases/vitess/migrations/action"&&S.method==="POST"){let s=await B(S),g=String(s.uuid??"").trim(),_=String(s.action??"");if(!["retry","cancel","cleanup","complete"].includes(_))return h({ok:!1,error:"Unknown migration action."},422);return h(await Yf(c,U,g,_))}if(w.pathname==="/api/databases/vitess/keyspaces"&&S.method==="POST"){let s=await B(S),g=String(s.name??"").trim(),_=s.sharded===!0;return h(await Mf(c,U,g,{sharded:_}))}if(w.pathname==="/api/databases/vitess/vschema"&&S.method==="POST"){let s=await B(S),g=String(s.keyspace??"").trim(),_=typeof s.vschema==="string"?s.vschema:JSON.stringify(s.vschema??null);return h(await Qf(c,U,g,_))}if(w.pathname==="/api/databases/vitess/schema"&&S.method==="POST"){let s=await B(S),g=String(s.sql??"");return h(await Gf(c,U,g))}if(w.pathname==="/api/databases/vitess/install-client"&&S.method==="POST")return h(await xf(c,U));if(w.pathname==="/api/databases/backups"&&S.method==="GET")return h(await jf(c,U));if(w.pathname==="/api/databases/backup"&&S.method==="POST"){let s=await B(S),g=String(s.database??"").trim();if(!zn(g))return h({ok:!1,error:"Database name must be a valid identifier."},422);if(s.confirm!==g)return h({ok:!1,error:`Type "${g}" to back up this database.`},409);return h(await Uf(c,U,g))}if(w.pathname==="/api/databases/users"&&S.method==="POST"){let s=await B(S),g=String(s.username??"").trim(),_=String(s.password??""),I=String(s.database??"").trim()||void 0,A=s.access==="readonly"?"readonly":"all";if(!zn(g))return h({ok:!1,error:"Username must be a valid identifier."},422);if(!_)return h({ok:!1,error:"Password is required."},422);if(I&&!zn(I))return h({ok:!1,error:"Database must be a valid identifier."},422);return h({...await Wf(c,U,{username:g,password:_,database:I,access:A}),username:g})}if(w.pathname==="/api/dashboard-data")return Ct=y.get(U)??await dt(U),dt(U),h(yl(Ct,{user:Be,slug:c.project.slug}));if(w.pathname==="/api/users"&&S.method==="GET")return h({ok:!0,users:Ie(e).map(Ii)});if(w.pathname==="/api/users"&&S.method==="POST"){let s=await B(S),g=String(s.username??"").trim();if(!no(g))return h({ok:!1,error:"Username must be 2-32 characters: letters, numbers, dot, dash or underscore."},422);let _=s.sites&&typeof s.sites==="object"?s.sites:{},I=new Set(Object.keys(c.sites??{})),A={};for(let[k,W]of Object.entries(_)){if(!I.has(k))return h({ok:!1,error:`Site '${k}' was not found.`},404);if(W!=="owner"&&W!=="collaborator")return h({ok:!1,error:`Unknown site role '${W}'. Use 'owner' or 'collaborator'.`},422);A[k]=W}let v=typeof s.password==="string"&&s.password.trim()?s.password.trim():void 0;if(v&&v.length<12)return h({ok:!1,error:"Password must be at least 12 characters."},422);let D=ec(e,{username:g,password:v,name:typeof s.name==="string"?s.name:void 0,sites:A});return Zd(o,Ie(e)),Le(),h({ok:!0,user:Ii(D.user),password:D.password})}if(w.pathname==="/api/users"&&S.method==="DELETE"){let s=await B(S),g=String(s.username??"").trim();if(g.toLowerCase()===z.username.toLowerCase())return h({ok:!1,error:"You cannot remove your own account."},409);let _=He(Ie(e),g),I=_?o.store.getActorByExternalId("user",`dashboard:${_.username.toLowerCase()}`):void 0,A=I?o.store.getMembershipForActor(o.organization.id,I.id):void 0;if(A&&A.source!=="legacy")return h({ok:!1,error:"Organization members must be removed from Organization access."},409);let v=Il(e,g);if(!v.ok)return h(v,409);return Zd(o,Ie(e)),Q.clear(),h({ok:!0,username:g})}if(w.pathname==="/api/actions/run"&&S.method==="POST"){let s=await S.json().catch(()=>({})),g=s.action?YP(s.action,U):void 0;if(!g)return h({ok:!1,error:"Unknown dashboard action."},404);if(g.mutates&&s.confirm!==g.confirm)return h({ok:!1,error:`Type "${g.confirm}" to run this action.`},409);let _=await Bn({controlPlane:o,environment:U,actor:z,kind:`dashboard.action.${g.id}`,input:{action:g.id},execute:()=>Vl(g,{cwd:e,cliEntry:i})});return h({..._.result,controlPlaneOperation:_.operation})}if(w.pathname==="/api/server/operations/run"&&S.method==="POST"){let s=await S.json().catch(()=>({})),g=s.operation?Dl(s.operation,c,Ct):void 0;if(!g)return h({ok:!1,error:"Unknown or unavailable server operation."},404);if(g.mutates&&s.confirm!==g.confirm)return h({ok:!1,error:`Type "${g.confirm}" to run this operation.`},409);let _=Ye(o,String(U));await new Cr(ot).run(new mi,{..._,artifactRoot:e});let I=Gd(ot,{scope:_,desiredConfigHash:o.project.desiredConfigHash});if(I.decision.outcome==="block")return h({ok:!1,error:`Operation blocked by security policy: ${I.decision.explanation}`,securityReview:I},409);let A=await Bn({controlPlane:o,environment:U,actor:z,kind:`dashboard.server.${g.id}`,resourceSlug:g.target,input:{operation:g.id,target:g.target,to:s.to??null},execute:()=>ao(c,U,g,{to:s.to})});return h({...A.result,controlPlaneOperation:A.operation,securityReview:I})}if(w.pathname==="/api/server/command"&&S.method==="POST"){let s=await S.json().catch(()=>({}));if(s.confirm!=="run")return h({ok:!1,error:'Type "run" to execute this command on the server.'},409);let g=await Bn({controlPlane:o,environment:U,actor:z,kind:"dashboard.server.command",input:{source:"interactive-command"},execute:()=>nc(c,U,String(s.command??""))});return h({...g.result,controlPlaneOperation:g.operation})}if(w.pathname==="/api/serverless/operations")return h(zl(c,U,Ct));if(w.pathname==="/api/serverless/operations/run"&&S.method==="POST"){let s=await S.json().catch(()=>({})),g=s.operation?j_(s.operation,c,U,Ct):void 0;if(!g)return h({ok:!1,error:"Unknown or unavailable serverless operation."},404);if(g.mutates&&s.confirm!==g.confirm)return h({ok:!1,error:`Type "${g.confirm}" to run this operation.`},409);let _=await Bn({controlPlane:o,environment:U,actor:z,kind:`dashboard.serverless.${g.id}`,input:{operation:g.id,min:s.min??null,max:s.max??null},execute:()=>H_(c,U,g,{min:s.min,max:s.max})});return Ct=await br(c,U),y.set(U,Ct),h({..._.result,controlPlaneOperation:_.operation})}if(w.pathname==="/api/serverless/command"&&S.method==="POST"){let s=await S.json().catch(()=>({}));if(s.confirm!=="run")return h({ok:!1,error:'Type "run" to execute this command.'},409);return h(await L_(c,U,String(s.command??"")))}if(w.pathname==="/api/serverless/dlq"&&S.method==="GET"){let s=Number(w.searchParams.get("max"))||10;return h(await F_(c,U,s))}if(w.pathname==="/api/serverless/dlq/redrive"&&S.method==="POST"){let s=await S.json().catch(()=>({}));if(s.confirm!=="redrive")return h({ok:!1,error:'Type "redrive" to move messages back onto a source queue.'},409);return h(await V_(c,U,{max:s.max,targetQueue:s.targetQueue}))}if(w.pathname==="/api/serverless/dlq/purge"&&S.method==="POST"){if((await S.json().catch(()=>({}))).confirm!=="purge")return h({ok:!1,error:'Type "purge" to permanently discard every DLQ message.'},409);return h(await N_(c,U))}if(w.pathname==="/api/serverless/secrets"&&S.method==="GET")return h({secrets:x_(c,U)});if(w.pathname==="/api/serverless/secrets"&&S.method==="POST"){let s=await S.json().catch(()=>({})),g=String(s.secretId??"").trim();if(!g)return h({ok:!1,error:"A secret id is required."},422);if(typeof s.value!=="string"||s.value==="")return h({ok:!1,error:"A non-empty value is required."},422);return h(await M_(c,U,g,s.value))}if(w.pathname==="/api/serverless/secrets"&&S.method==="DELETE"){let s=await S.json().catch(()=>({})),g=String(s.secretId??"").trim();if(!g)return h({ok:!1,error:"A secret id is required."},422);if(s.confirm!==g)return h({ok:!1,error:`Type "${g}" to delete this secret.`},409);return h(await Q_(c,U,g))}if(w.pathname==="/api/serverless/functions/config"&&S.method==="POST"){let s=await S.json().catch(()=>({})),g=String(s.mode??"").trim();if(s.confirm!==g)return h({ok:!1,error:`Type "${g}" to update this function.`},409);return h(await G_(c,U,g,{memory:s.memory,timeout:s.timeout}))}if(w.pathname==="/api/serverless/alarms"&&S.method==="GET")return h(await Z_(c,U));if(w.pathname==="/api/serverless/alarms"&&S.method==="POST"){let s=await S.json().catch(()=>({})),g=String(s.preset??"").trim(),_=Number(s.threshold);if(!g)return h({ok:!1,error:"An alarm metric is required."},422);if(!Number.isFinite(_))return h({ok:!1,error:"A numeric threshold is required."},422);return h(await Y_(c,U,g,_))}if(w.pathname==="/api/serverless/alarms"&&S.method==="DELETE"){let s=await S.json().catch(()=>({})),g=String(s.name??"").trim();if(!g)return h({ok:!1,error:"An alarm name is required."},422);if(s.confirm!==g)return h({ok:!1,error:`Type "${g}" to delete this alarm.`},409);return h(await X_(c,U,g))}if(w.pathname==="/api/serverless/traces"&&S.method==="GET"){let s=Number(w.searchParams.get("minutes"))||30;return h(await lo(c,U,s))}if(w.pathname==="/api/serverless/scheduler"&&S.method==="POST"){let s=await S.json().catch(()=>({})),g=String(s.action??"").trim();if(g!=="enable"&&g!=="disable"&&g!=="run")return h({ok:!1,error:"Unknown scheduler action."},422);if(s.confirm!==g)return h({ok:!1,error:`Type "${g}" to ${g} the scheduler.`},409);return h(await Wl(c,U,g))}if(!yR(w.pathname,Be))return new Response(null,{status:302,headers:{location:`/access-denied?env=${encodeURIComponent(U)}`}});let Fr=await me(z,U);if(!Fr)return Eo("ts-cloud dashboard UI is unavailable.",503);return PR(Fr,w.pathname)}catch(dr){if(t.verbose)console.error(dr);return h({ok:!1,error:dr?.message??String(dr)},500)}})();if(!Lt)return Lt;if(_t&&(w.pathname.startsWith("/api/")||w.pathname.startsWith("/auth/"))){let it;if((V.headers.get("content-type")||"").includes("application/json"))it=await V.json().catch(()=>{return});let pt=Bt.resolveUser(S),Zt=pt?X(pt).actor:void 0;o.store.appendEvent({organizationId:o.organization.id,projectId:o.project.id,actorId:Zt?.id,correlationId:tt,type:Lt.status<400?"dashboard.mutation.succeeded":"dashboard.mutation.failed",level:Lt.status<400?"info":"warning",payload:zP(S.method,w.pathname,it,Lt.status,Date.now()-Z)})}return Lt.headers.set("x-request-id",tt),Lt}});Sc?.start();let fE=t.spendLoop??!0,og;if(fE)(async()=>{let{SpendRunner:S,SpendLoopLease:x,startSpendLoop:Z}=await import("./chunk-qk9qgepa.js"),{store:V}=await vR(o.store),tt=new S({controlPlane:o.store,store:V,alerts:nt});og=Z(tt,{lease:new x(o.store,{owner:`dashboard:${process.pid}`}),onError:(_t)=>console.error(`[ts-cloud] spend cycle failed: ${_t instanceof Error?_t.message:String(_t)}`)})})();let _E=Hr.stop.bind(Hr);return Hr.stop=(S)=>{clearInterval(rg),clearInterval(ig),clearInterval(cg),clearInterval(ng),clearInterval(eg),clearInterval(pl),clearInterval(ml),clearInterval(ql),clearInterval(tg),Le(),Vt.clear(),Sc?.stop(),og?.();let x=_E(S);if(Sc)Sc.settled().finally(()=>o.store.close());else o.store.close();return x},{server:Hr,url:`http://${n}:${Hr.port}/`}}
|
|
512
|
-
export{Tc as w,Gn as x,ia as y,zf as z,$S as A,K_ as B,Zi as C,Bs as D,zs as E,Ls as F,Fs as G,Ms as H,Qs as I,Ws as J,Us as K,Hs as L,Hi as M,Li as N,Aa as O,Lu as P,Zc as Q,Da as R,ya as S,Pa as T,$a as U,va as V,Ca as W,Oa as X,Ja as Y,pr as Z,Ba as _,No as $,Qr as aa,Pc as ba,$c as ca,bi as da,mg as ea,Nr as fa,ko as ga,Fe as ha,Jo as ia,zo as ja,bo as ka,wc as la,oo as ma,Dl as na,ao as oa,nc as pa,Ji as qa,lr as ra,Xi as sa,pi as ta,Md as ua,Ye as va,$f as wa,sb as xa,lb as ya,Gd as za,Sb as Aa,kr as Ba,lg as Ca,jc as Da,fr as Ea,_r as Fa,sa as Ga,la as Ha,ga as Ia,ha as Ja,Ra as Ka,Ia as La,Mc as Ma,M1 as Na,Zs as Oa,Ys as Pa,nf as Qa,an as Ra,Ll as Sa,Sj as Ta};
|