@stacksjs/ts-cloud 0.12.1 → 0.12.3
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-0zwknfwp.js +1 -0
- package/dist/bin/chunk-3aph4c1w.js +2 -0
- package/dist/bin/{chunk-5bhx3bsa.js → chunk-4q6tad44.js} +121 -121
- package/dist/bin/chunk-5nkqza92.js +1 -0
- package/dist/bin/chunk-64vczwwt.js +1 -0
- package/dist/bin/chunk-6tfwm33r.js +6 -0
- package/dist/bin/chunk-71t1gmsq.js +1 -0
- package/dist/bin/chunk-7g2ahkse.js +1 -0
- package/dist/bin/chunk-7zhgmp1s.js +3 -0
- package/dist/bin/chunk-82mj52xr.js +141 -0
- package/dist/bin/chunk-8ewncfce.js +37 -0
- package/dist/bin/chunk-9a88fp00.js +2 -0
- package/dist/bin/chunk-9kf0np8j.js +44 -0
- package/dist/bin/chunk-9rb23kz9.js +1 -0
- package/dist/bin/chunk-a7w13qfm.js +2 -0
- package/dist/bin/chunk-b4wt9jcg.js +60 -0
- package/dist/bin/chunk-btsyjhk7.js +92 -0
- package/dist/bin/chunk-c0bdafbx.js +2 -0
- package/dist/bin/chunk-cd0ps58j.js +1 -0
- package/dist/bin/chunk-cxt74wsj.js +1 -0
- package/dist/bin/chunk-d7ke90zt.js +2 -0
- package/dist/bin/chunk-djg4zyqk.js +1 -0
- package/dist/bin/chunk-dkaz333b.js +1 -0
- package/dist/bin/chunk-dkf4qsp2.js +1 -0
- package/dist/bin/{chunk-scqmd4qv.js → chunk-dz1ec589.js} +30 -30
- package/dist/bin/chunk-e2bybahr.js +3 -0
- package/dist/bin/chunk-e5ab5twy.js +50 -0
- package/dist/bin/chunk-edvvx3hg.js +1 -0
- package/dist/bin/chunk-ehc63fvs.js +2 -0
- package/dist/bin/chunk-f06c5np9.js +1 -0
- package/dist/bin/chunk-gq8794k6.js +1 -0
- package/dist/bin/chunk-hq9x489e.js +70 -0
- package/dist/bin/chunk-ja1vjdn1.js +6 -0
- package/dist/bin/chunk-k3120rx6.js +1 -0
- package/dist/bin/chunk-kg61p5hw.js +3 -0
- package/dist/bin/chunk-mcr0r4at.js +2 -0
- package/dist/bin/chunk-mfrf9q4b.js +2 -0
- package/dist/bin/chunk-my3ewh3a.js +34 -0
- package/dist/bin/chunk-nw3d4k52.js +1 -0
- package/dist/bin/chunk-p70bc9yr.js +1 -0
- package/dist/bin/chunk-pp2m8q55.js +512 -0
- package/dist/bin/chunk-q5cmfpzt.js +1 -0
- package/dist/bin/chunk-rtecnmts.js +4 -0
- package/dist/bin/chunk-s2grgcpy.js +590 -0
- package/dist/bin/chunk-s4yzes15.js +2 -0
- package/dist/bin/chunk-sj5csg49.js +2 -0
- package/dist/bin/chunk-tfbs8k8v.js +111 -0
- package/dist/bin/chunk-tvz9c388.js +1 -0
- package/dist/bin/{chunk-9vdc7adf.js → chunk-w32xv8n4.js} +6 -6
- package/dist/bin/chunk-x6f61g36.js +9 -0
- package/dist/bin/chunk-xhwqpgwq.js +2 -0
- package/dist/bin/chunk-xk08030d.js +6 -0
- package/dist/bin/chunk-xkfrqqcs.js +1 -0
- package/dist/bin/chunk-y1h63vpm.js +1 -0
- package/dist/bin/chunk-zdt2rjk6.js +1 -0
- package/dist/bin/chunk-zh2d4704.js +1 -0
- package/dist/bin/chunk-zpe64t4r.js +1 -0
- package/dist/bin/cli.js +435 -444
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/{chunk-rr1yaj55.js → chunk-13qjvbqh.js} +1 -1
- package/dist/chunk-152he7m3.js +92 -0
- package/dist/chunk-1qdne0bf.js +1 -0
- package/dist/chunk-3mgj3hrh.js +5 -0
- package/dist/chunk-3nmm7cap.js +704 -0
- package/dist/chunk-6kpbveb8.js +5 -0
- package/dist/chunk-73ztr55z.js +2 -0
- package/dist/{chunk-y1dh3znq.js → chunk-86ss83s2.js} +52 -52
- package/dist/chunk-a84gmpyh.js +1 -0
- package/dist/chunk-aj025v2s.js +4 -0
- package/dist/chunk-by2bwzk6.js +141 -0
- package/dist/chunk-h42zck7h.js +60 -0
- package/dist/chunk-hn40z11p.js +37 -0
- package/dist/{chunk-6xcbfs2r.js → chunk-jm5mg890.js} +111 -111
- package/dist/chunk-m8fs0233.js +34 -0
- package/dist/chunk-mz0dk78z.js +6 -0
- package/dist/chunk-n514hj0z.js +450 -0
- package/dist/chunk-nms5q44e.js +1 -0
- package/dist/chunk-qm32ytbr.js +1 -0
- package/dist/chunk-t0xgmhd6.js +114 -0
- package/dist/chunk-t3t9ymec.js +1 -0
- package/dist/chunk-tz9myq9a.js +2 -0
- package/dist/chunk-wavjkdb8.js +2 -0
- package/dist/chunk-x3hay61c.js +44 -0
- package/dist/chunk-xcj8zfmg.js +2 -0
- package/dist/chunk-y2v22hkv.js +1 -0
- package/dist/chunk-y4xkj2f1.js +50 -0
- package/dist/deploy/index.js +1 -1
- package/dist/dns/index.js +1 -1
- package/dist/drivers/index.js +1 -1
- package/dist/drivers/shared/deploy-script.d.ts +85 -0
- package/dist/index.js +90 -90
- 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 +2 -2
- package/dist/ui/_stx/{router.fa5bc4dc.js → router.229f89ab.js} +1 -1
- package/dist/ui/_stx/runtime.dbee66d1.js +1 -0
- package/dist/ui/accept-invitation.html +2 -2
- 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 +1 -1
- package/dist/ui/operations/alerts.html +48 -48
- package/dist/ui/operations/configuration.html +5 -5
- 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 +1 -1
- package/dist/ui/server/actions.html +56 -56
- package/dist/ui/server/activity.html +2 -2
- package/dist/ui/server/capacity.html +6 -6
- package/dist/ui/server/database.html +105 -105
- 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 +28 -28
- package/dist/ui/serverless/cost.html +2 -2
- package/dist/ui/serverless/data.html +36 -36
- package/dist/ui/serverless/deployments.html +28 -28
- package/dist/ui/serverless/firewall.html +2 -2
- package/dist/ui/serverless/functions.html +40 -40
- package/dist/ui/serverless/logs.html +23 -23
- package/dist/ui/serverless/metrics.html +2 -2
- package/dist/ui/serverless/queues.html +48 -48
- package/dist/ui/serverless/secrets.html +52 -52
- package/dist/ui/serverless/traces.html +6 -6
- package/dist/ui/serverless.html +53 -53
- package/dist/ui-src/src/charts.ts +4644 -16118
- package/dist/ui-src/src/topology.ts +2 -2
- package/package.json +6 -6
- package/dist/bin/chunk-0rtn6q5x.js +0 -3
- package/dist/bin/chunk-258ehp9s.js +0 -1
- package/dist/bin/chunk-2yctv06c.js +0 -1
- package/dist/bin/chunk-3276rveh.js +0 -37
- package/dist/bin/chunk-3m665jwp.js +0 -70
- package/dist/bin/chunk-3s2p9vxj.js +0 -1
- package/dist/bin/chunk-4esma5m9.js +0 -1
- package/dist/bin/chunk-4n0j3n3b.js +0 -2
- package/dist/bin/chunk-54bqchag.js +0 -92
- package/dist/bin/chunk-5zagqd20.js +0 -1
- package/dist/bin/chunk-7hw2js5h.js +0 -512
- package/dist/bin/chunk-8h1qr6x4.js +0 -50
- package/dist/bin/chunk-a1dd6sby.js +0 -1
- package/dist/bin/chunk-a4dw35gs.js +0 -1
- package/dist/bin/chunk-a9d55ker.js +0 -1
- package/dist/bin/chunk-awa1qade.js +0 -9
- package/dist/bin/chunk-b6by94pk.js +0 -2
- package/dist/bin/chunk-c8sypnbe.js +0 -2
- package/dist/bin/chunk-cx4e3d4w.js +0 -1
- package/dist/bin/chunk-d5a3vheh.js +0 -2
- package/dist/bin/chunk-e1fym2bd.js +0 -1
- package/dist/bin/chunk-ej4h0q2y.js +0 -1
- package/dist/bin/chunk-ett305ym.js +0 -4
- package/dist/bin/chunk-f11xf3n6.js +0 -2
- package/dist/bin/chunk-fq7ktvgy.js +0 -3
- package/dist/bin/chunk-fyq4th2m.js +0 -1
- package/dist/bin/chunk-g67qr8yf.js +0 -1
- package/dist/bin/chunk-gc82cx4h.js +0 -1
- package/dist/bin/chunk-hchtvpr9.js +0 -1
- package/dist/bin/chunk-hpe4jjce.js +0 -1
- package/dist/bin/chunk-k5vprsef.js +0 -6
- package/dist/bin/chunk-m22krd4z.js +0 -3
- package/dist/bin/chunk-mkppcwz8.js +0 -1
- package/dist/bin/chunk-mpjg0kc7.js +0 -2
- package/dist/bin/chunk-mrm4m4dk.js +0 -2
- package/dist/bin/chunk-nff46rxd.js +0 -1
- package/dist/bin/chunk-np1z3bgt.js +0 -1
- package/dist/bin/chunk-nskxkk6r.js +0 -1
- package/dist/bin/chunk-pez932b1.js +0 -111
- package/dist/bin/chunk-qsdf5kzk.js +0 -2
- package/dist/bin/chunk-r61qmhv1.js +0 -2
- package/dist/bin/chunk-r6gdcz5c.js +0 -1
- package/dist/bin/chunk-satwnr42.js +0 -2
- package/dist/bin/chunk-smbycpt5.js +0 -44
- package/dist/bin/chunk-sn7e0sn7.js +0 -2
- package/dist/bin/chunk-ss574pka.js +0 -1
- package/dist/bin/chunk-tj0xb2d8.js +0 -585
- package/dist/bin/chunk-v3rzf9d0.js +0 -141
- package/dist/bin/chunk-wnpma6t3.js +0 -34
- package/dist/bin/chunk-xan0e052.js +0 -5
- package/dist/bin/chunk-xbk2y43r.js +0 -60
- package/dist/bin/chunk-xjp3v95e.js +0 -6
- package/dist/bin/chunk-xyt490vp.js +0 -6
- package/dist/bin/chunk-yn9r02gy.js +0 -1
- package/dist/bin/chunk-zhkhn9cc.js +0 -1
- package/dist/chunk-0zf72ngj.js +0 -1
- package/dist/chunk-2hpjte1d.js +0 -704
- package/dist/chunk-4m6gwhwr.js +0 -5
- package/dist/chunk-5m29dhke.js +0 -34
- package/dist/chunk-6fzeemcs.js +0 -114
- package/dist/chunk-bpnhqb70.js +0 -6
- package/dist/chunk-ead1nkbr.js +0 -60
- package/dist/chunk-fea461tj.js +0 -141
- package/dist/chunk-fvjczc73.js +0 -1
- package/dist/chunk-gearw6rk.js +0 -4
- package/dist/chunk-j60hesb3.js +0 -2
- package/dist/chunk-pmgtmt3d.js +0 -1
- package/dist/chunk-prf2pkvq.js +0 -5
- package/dist/chunk-q0wffgw5.js +0 -37
- package/dist/chunk-qcemnt35.js +0 -50
- package/dist/chunk-qvbwsaay.js +0 -1
- package/dist/chunk-r2pbqcnz.js +0 -2
- package/dist/chunk-r6110zv2.js +0 -1
- package/dist/chunk-wcrj06cg.js +0 -44
- package/dist/chunk-wte9mh18.js +0 -92
- package/dist/chunk-y6e86wjs.js +0 -445
- package/dist/chunk-y8b7ht4v.js +0 -1
- package/dist/chunk-yf487g6e.js +0 -2
- package/dist/chunk-zmmc9j5f.js +0 -2
- package/dist/ui/_stx/runtime.c696d17a.js +0 -1
|
@@ -0,0 +1,704 @@
|
|
|
1
|
+
import{ud as Sp}from"./chunk-h42zck7h.js";import{Bd as to,Cd as zp,Dd as rs,Ed as Mt,Fd as ct,Gd as os,Hd as Up}from"./chunk-3mgj3hrh.js";import{Jd as ci,Kd as Vs,Oe as Fv,Pe as Ls,Rd as Zp,Td as xa,Ud as Yr,Wd as _n,Xd as kt,Yd as di,nf as Xp}from"./chunk-t0xgmhd6.js";import{of as ts}from"./chunk-m8fs0233.js";import{sf as Rn}from"./chunk-by2bwzk6.js";import{tf as Pp}from"./chunk-73ztr55z.js";import{uf as Fn}from"./chunk-xcj8zfmg.js";import{Jg as Ty,Jh as Wu,Mh as Ga,Rg as ir,cg as Bo,dg as rv,eg as nv,fg as vu,gg as Cu,hg as yv,jg as yn,og as zr,xh as vv,yh as bv}from"./chunk-n514hj0z.js";import{Wh as Hb}from"./chunk-aj025v2s.js";import{Xh as Er}from"./chunk-wavjkdb8.js";import{Yh as Qp,Zh as ur}from"./chunk-152he7m3.js";import{$h as mi,ai as Gp}from"./chunk-mz0dk78z.js";import{Ak as qb,Di as xb,Dj as Hm,Dk as pb,Ei as Db,Ek as Vb,Hi as Ps,Hk as tc,Ii as $e,Ik as Wb,Ji as Ob,Ki as Bm,Li as vs,Oi as $b,Pi as Nb,Ui as jb,Vi as Mb,Vk as ie,Wi as Bb,Xi as Lb,Xk as qc,Yk as Jm,Zk as Wm,aj as bs,ei as Es,fi as fp,hi as Xt,ii as Wo,ik as Km,pi as Oe,qi as hp,qk as Fb,ri as Tb,tk as zb,uk as Gi,vi as ys,yk as qo,zk as Ub}from"./chunk-86ss83s2.js";import{$l as gt,Bs as jp,Cs as ds,Ds as Mp,Es as Bp,Tl as bh,Vl as ho,Wl as yt,Xl as Cp,Zl as Fr,em as Zl,gn as Ep,ln as Rp,lt as Lp,rm as ui,rt as Fp,sm as Dp,tm as Op,ys as $p,zs as Np}from"./chunk-jm5mg890.js";import{Et as rt}from"./chunk-13qjvbqh.js";import{createHash as dS}from"node:crypto";function lS(e){return dS("sha256").update(En(e)).digest("hex")}function En(e){if(Array.isArray(e))return`[${e.map((t)=>En(t)).join(",")}]`;if(e&&typeof e==="object")return`{${Object.entries(e).filter(([,t])=>t!==void 0&&typeof t!=="function").sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>`${JSON.stringify(t)}:${En(r)}`).join(",")}}`;return JSON.stringify(e)??"null"}function Ye(e,t){let r=`dashboard:${t.username.toLowerCase()}`;return e.getActorByExternalId("user",r)??e.createActor({kind:"user",externalId:r,displayName:t.name??t.username,metadata:{source:"dashboard",role:t.role}})}function yp(e,t){let r=new hp({cwd:e}),n=lS(t),i=r.getProjectBySlug(t.project.slug),o=t.project.slug.length>=3?t.project.slug:`${t.project.slug}-org`,s=(i?.organizationId?r.getOrganization(i.organizationId):void 0)??r.getOrganizationBySlug(o)??r.createOrganization({id:i?.organizationId,slug:o,name:t.project.name}),c=i?i.name!==t.project.name||i.desiredConfigHash!==n||i.organizationId!==s.id?r.updateProject(i.id,i.version,{name:t.project.name,organizationId:s.id,desiredConfigHash:n}):i:r.createProject({organizationId:s.id,slug:t.project.slug,name:t.project.name,desiredConfigHash:n}),d=new Map;for(let[h,y]of Object.entries(t.environments??{})){let k=r.getEnvironmentBySlug(c.id,h)??r.createEnvironment({projectId:c.id,slug:h,name:h.replace(/(^|[-_])(\w)/g,(O,U,q)=>q.toUpperCase()),kind:String(y?.type??h),region:y?.region??t.project.region,desiredState:Oe(y)});d.set(h,k);let C=new Map(r.listResources(c.id,k.id).map((O)=>[`${O.kind}:${O.slug}`,O])),T=(O,U,q,N)=>{let Q=`${O}:${U}`,D=C.get(Q),Y=Oe(N);if(D){if(D.name!==q||En(D.desiredState)!==En(Y))C.set(Q,r.updateResource(D.id,D.version,{name:q,desiredState:Y}));return}let se=r.createResource({projectId:c.id,environmentId:k.id,kind:O,slug:U,name:q,provider:t.cloud?.provider,desiredState:Y,metadata:{source:"cloud-config"}});C.set(Q,se)};for(let[O,U]of Object.entries(t.sites??{}))T("application",O,O,U);let j=y?.app;if(j)for(let O of["http","queue","cli"])T("function",O,`${O.toUpperCase()} function`,{...Oe(j),function:O});let P=t.infrastructure;for(let[O,U]of Object.entries(P?.functions??{}))T("function",O,O,U);if(P?.compute)T("server",`${c.slug}-server`,c.name,{...Oe(P.compute),label:c.name});for(let[O,U]of Object.entries(P?.databases??{}))T("database",O,O,U);if(P?.appDatabase)T("database","application-database","Application database",P.appDatabase);else if(P?.database)T("database","application-database","Application database",{engine:P.database})}let a=new $e(r).recoverExpired(),u=r.reconcileOrphanedOperations({policy:"fail"}),m={requeued:a.requeued+u.requeued,failed:a.failed+a.cancelled+u.failed};return{store:r,organization:s,project:c,environments:d,reconciliation:m}}var uS=["project:read","config:read","deployments:read","deployments:create","runtime:read","runtime:logs"];function es(e,t){let{store:r,organization:n,project:i}=e,o=new Set;for(let s of t){let c=Ye(r,s);o.add(c.id);let d=r.getMembershipForActor(n.id,c.id);if(d&&d.source!=="legacy")continue;let a=r.listResources(i.id).filter((w)=>w.kind==="application"&&Object.hasOwn(s.sites,w.slug)),u=s.role==="admin"?"owner":"viewer",m=s.role==="admin"||a.length===0?{type:"organization"}:{type:"resource",id:a[0].id},h=d?d.roleTemplate!==u||En(d.scope)!==En(m)?r.updateMembership({id:d.id,roleTemplate:u,scope:m,actorId:c.id}):d:r.createMembership({organizationId:n.id,actorId:c.id,roleTemplate:u,scope:m,source:"legacy"}),y=new Set;if(s.role==="member"&&a.length===0)for(let w of fp("viewer"))y.add(`deny|${w}|organization|`);for(let w of a){let k=s.sites[w.slug];for(let C of uS)y.add(`allow|${C}|resource|${w.id}`);if(k==="owner")y.add(`allow|config:write|resource|${w.id}`)}for(let w of r.listGrants(h.id).filter((k)=>k.source==="legacy")){let k=`${w.effect}|${w.capability}|${w.scope.type}|${w.scope.id??""}`;if(!y.has(k))r.removeGrant(w.id,c.id)}for(let w of y){let[k,C,T,j]=w.split("|");r.upsertGrant({organizationId:n.id,membershipId:h.id,effect:k,capability:C,scope:T==="organization"?{type:"organization"}:{type:T,id:j},source:"legacy"})}}for(let s of r.listMemberships(n.id))if(s.source==="legacy"&&!o.has(s.actorId))r.revokeMembership(s.id)}async function Ir(e){let{controlPlane:t,environment:r,actor:n}=e,i=Ye(t.store,n),o=t.environments.get(r),s=e.resourceSlug&&o?t.store.listResources(t.project.id,o.id).find((u)=>u.slug===e.resourceSlug):void 0,c=new $e(t.store,{workerId:`dashboard:${process.pid}`}),d=c.enqueue({projectId:t.project.id,environmentId:o?.id,resourceId:s?.id,actorId:i.id,kind:e.kind,input:e.input??{},lockKey:s?`resource:${s.id}`:o?`environment:${o.id}`:`project:${t.project.id}`,providerKey:s?.provider??"dashboard",buildSlot:e.kind.includes("deploy"),maxAttempts:1,timeoutSeconds:3600,resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;if(!c.claim(d.id)?.operation)throw Error(`Could not claim control-plane operation ${d.id}`);try{let u=await e.execute(),m=typeof u.stdout==="string"?String(u.stdout):"",h=typeof u.stderr==="string"?String(u.stderr):"";if(m)c.appendLog(d.id,m,{stream:"stdout"});if(h)c.appendLog(d.id,h,{stream:"stderr"});let y=u.ok?c.complete(d.id,gp(u)):c.fail(d.id,pS(u),gp(u));return{result:u,operation:y}}catch(u){throw c.fail(d.id,u instanceof Error?u.message:String(u),{ok:!1,threw:!0}),u}}function pS(e){let t=e;return String(t.error??t.stderr??"Operation failed")}function gp(e){let t=e,r=typeof t.stdout==="string"?t.stdout:"",n=typeof t.stderr==="string"?t.stderr:"",i={ok:e.ok,stdoutBytes:Buffer.byteLength(r),stderrBytes:Buffer.byteLength(n)};if(typeof t.operation==="string")i.operation=t.operation;if(typeof t.error==="string")i.error=t.error;return Oe(i)}var vp=[{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}],mS=new Map(vp.flatMap((e)=>(e.legacyPaths??[]).map((t)=>[t,e.path])));function bp(e){return mS.get(e)}function U_(e,t){return vp.filter((r)=>r.modes.includes(e)&&(!t||!r.adminOnly))}import Qr from"node:process";import{existsSync as gS}from"node:fs";import{join as fS}from"node:path";async function J_(e){let t=Date.now(),r=e.sourceDir??"dist";if(!gS(fS(r,"index.html")))return mc(t,`${r}/ has no index.html — build first.`);if(!Qr.env.AWS_ACCESS_KEY_ID||!Qr.env.AWS_SECRET_ACCESS_KEY)return mc(t,"Missing AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY in env.");let n=hS(e.dnsProvider);if("error"in n)return mc(t,n.error);let i=await Sp({siteName:e.siteName,region:e.region??"us-east-1",domain:e.domain,bucket:e.bucket,stackName:e.stackName,certificateArn:e.certificateArn,defaultRootObject:e.defaultRootObject??"index.html",errorDocument:e.errorDocument??"404.html",cacheControl:e.cacheControl??"max-age=3600, public",sourceDir:r,cleanBucket:e.cleanBucket??!1,singlePageApp:e.singlePageApp??!1,dnsProvider:n,tags:{ManagedBy:"ts-cloud",Application:e.siteName,...e.tags},onProgress:e.onProgress});return{success:!!i.success,domain:i.domain,url:i.domain?`https://${i.domain}`:i.distributionDomain?`https://${i.distributionDomain}`:void 0,bucket:i.bucket,distributionId:i.distributionId,distributionDomain:i.distributionDomain,certificateArn:i.certificateArn,filesUploaded:i.filesUploaded,filesSkipped:i.filesSkipped,message:i.message,durationMs:Date.now()-t}}function hS(e){let t=typeof e==="string"?{provider:e}:e??{provider:"porkbun"};if(t.provider==="porkbun"){let r=t,n=r?.apiKey??Qr.env.PORKBUN_API_KEY,i=r?.secretKey??Qr.env.PORKBUN_SECRET_KEY??Qr.env.PORKBUN_SECRET_API_KEY;if(!n||!i)return{error:"Missing PORKBUN_API_KEY / PORKBUN_SECRET_KEY in env."};return{provider:"porkbun",apiKey:n,secretKey:i}}if(t.provider==="godaddy"){let r=t,n=r?.apiKey??Qr.env.GODADDY_API_KEY,i=r?.secretKey??Qr.env.GODADDY_API_SECRET,o=r?.environment??Qr.env.GODADDY_ENVIRONMENT;if(!n||!i)return{error:"Missing GODADDY_API_KEY / GODADDY_API_SECRET in env."};return{provider:"godaddy",apiKey:n,apiSecret:i,environment:o}}return{error:`Unsupported DNS provider: ${t.provider}`}}function mc(e,t){return{success:!1,message:t,durationMs:Date.now()-e}}import{createHash as yS}from"node:crypto";var vS=`let coldStart = true
|
|
2
|
+
const initializedAt = new Date().toISOString()
|
|
3
|
+
export const handler = async (event) => {
|
|
4
|
+
const currentColdStart = coldStart
|
|
5
|
+
coldStart = false
|
|
6
|
+
const path = event.rawPath || event.requestContext?.http?.path || '/'
|
|
7
|
+
const statusCode = path === '/api/health' || path === '/health' ? 200 : 404
|
|
8
|
+
return {
|
|
9
|
+
statusCode,
|
|
10
|
+
headers: { 'content-type': 'application/json', 'cache-control': 'no-store' },
|
|
11
|
+
body: JSON.stringify({ ok: statusCode === 200, service: 'ts-cloud-static-api', path, coldStart: currentColdStart, initializedAt })
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
`;function Ip(e){let t=e;return String(t?.code||t?.name||t?.statusCode||"")}function bS(e){return["NoSuchEntity","ResourceNotFoundException","404"].includes(Ip(e))}function wp(e){return["EntityAlreadyExists","ResourceAlreadyExistsException","ResourceConflictException","409"].includes(Ip(e))}function kp(e,t){let r=e?.Items;if(!r)return[];if(Array.isArray(r))return r;let n=r[t];if(n===void 0)return[];return Array.isArray(n)?n:[n]}function gc(e){let t=e?.Aliases?.Items;if(Array.isArray(t))return t.map(String);if(typeof t==="string")return[t];return[]}function SS(e){if(!/^[A-Z0-9]{8,32}$/.test(e.distributionId))throw Error("CloudFront distribution ID is invalid");if(!/^(?=.{1,253}$)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z0-9-]{2,63}$/.test(e.expectedAlias))throw Error("Expected CloudFront alias is invalid");if(!/^[A-Za-z0-9-_]{1,64}$/.test(e.functionName))throw Error("Lambda function name is invalid");let t=e.pathPattern?.startsWith("/")?e.pathPattern:`/${e.pathPattern||"api/*"}`;if(t==="/"||t==="/*"||!t.endsWith("*"))throw Error("API path must be a non-default wildcard pattern such as /api/*");let r=e.originId||`${e.functionName}-url`,n=e.roleName||`${e.functionName}-execution`;if(!/^[A-Za-z0-9_.-]{1,64}$/.test(n))throw Error("IAM role name is invalid");let i=e.memorySize??256,o=e.timeout??10,s=e.logRetentionDays??14;if(i<128||i>10240)throw Error("Lambda memory must be between 128 and 10240 MB");if(o<1||o>900)throw Error("Lambda timeout must be between 1 and 900 seconds");return{region:e.region||"us-east-1",pathPattern:t,originId:r,roleName:n,memorySize:i,timeout:o,logRetentionDays:s}}function wS(e){let t=e.region||"us-east-1";return{cloudfront:new Rn(e.profile),iam:new ts(t,e.profile),lambda:new kt(t,e.profile),logs:new di(t,e.profile),sts:new ci(t,e.profile),sleep:(r)=>new Promise((n)=>setTimeout(n,r))}}async function rT(e,t){let r=SS(e),n=t||wS({profile:e.profile,region:r.region}),[i,o,s]=await Promise.all([n.sts.getCallerIdentity(),n.cloudfront.getDistribution(e.distributionId),n.cloudfront.getDistributionConfig(e.distributionId)]);if(!i.Account)throw Error("AWS identity did not return an account ID");if(!o.Enabled)throw Error(`CloudFront distribution ${e.distributionId} is disabled`);if(!(gc(o).length?gc(o):gc(s.DistributionConfig)).includes(e.expectedAlias))throw Error(`Distribution ${e.distributionId} does not contain expected alias ${e.expectedAlias}`);let d,a=!0;try{d=await n.iam.getRole({RoleName:r.roleName})}catch(de){if(!bS(de))throw de;a=!1}let u=d?.Arn||`arn:aws:iam::${i.Account}:role/${r.roleName}`,m=await n.lambda.functionExists(e.functionName),h=m?await n.lambda.getFunctionUrl(e.functionName):null,y=await n.cloudfront.listOriginAccessControls(),w=`${e.functionName}-lambda-url`,k=y.some((de)=>de.Name===w&&de.OriginAccessControlOriginType==="lambda"),C=kp(s.DistributionConfig.Origins,"Origin"),T=kp(s.DistributionConfig.CacheBehaviors,"CacheBehavior"),j=C.some((de)=>String(de.Id)===r.originId),P=T.some((de)=>String(de.PathPattern)===r.pathPattern),O=[...!a?[`create IAM execution role ${r.roleName}`]:[`reconcile IAM execution policy ${r.roleName}`],...m?[`update Lambda ${e.functionName} code and configuration`]:[`create Lambda ${e.functionName}`],...!h?["create private AWS_IAM function URL"]:[],...!k?[`create Lambda origin access control ${w}`]:[],"grant CloudFront function-URL and invocation permissions",`${P?"reconcile":"add"} ${r.pathPattern} behavior without changing the default behavior`],U={command:`cloud cdn:origin:remove ${e.distributionId} FUNCTION_URL_HOST --id ${r.originId} --path '${r.pathPattern}' --apply --confirm 'remove:${e.distributionId}:${r.pathPattern}'`,removeFunction:!m,removeRole:!a},q={mode:e.apply?"apply":"plan",accountId:i.Account,identityArn:i.Arn,distribution:{id:o.Id,arn:o.ARN,alias:e.expectedAlias,domainName:o.DomainName,status:o.Status},function:{name:e.functionName,existed:m,runtime:"nodejs22.x",urlExisted:!!h,url:h?.FunctionUrl},role:{name:r.roleName,existed:a,arn:u},origin:{id:r.originId,pathPattern:r.pathPattern,existed:j,behaviorExisted:P,accessControlExisted:k},changes:O,rollback:U,applied:!1};if(!e.apply)return q;let N=`${e.distributionId}:${r.pathPattern}`;if(e.confirm!==N)throw Error(`Pass exact confirmation token ${N} to mutate the live distribution`);if(!d)d=await n.iam.createRole({RoleName:r.roleName,Description:`Execution role for ${e.functionName}`,AssumeRolePolicyDocument:JSON.stringify({Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]}),Tags:[{Key:"ManagedBy",Value:"ts-cloud"}]});await n.iam.putRolePolicy({RoleName:r.roleName,PolicyName:"lambda-logs",PolicyDocument:JSON.stringify({Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["logs:CreateLogStream","logs:PutLogEvents"],Resource:`arn:aws:logs:${r.region}:${i.Account}:log-group:/aws/lambda/${e.functionName}:*`}]})});try{await n.logs.createLogGroup(`/aws/lambda/${e.functionName}`,{ManagedBy:"ts-cloud"})}catch(de){if(!wp(de))throw de}await n.logs.putRetentionPolicy(`/aws/lambda/${e.functionName}`,r.logRetentionDays);let Q=e.code||vS;if(m)await n.lambda.updateFunctionCodeInline(e.functionName,Q,"index.mjs"),await n.lambda.waitForFunctionActive(e.functionName),await n.lambda.updateFunctionConfiguration({FunctionName:e.functionName,Runtime:"nodejs22.x",Role:d.Arn,Handler:"index.handler",Description:`Private API origin for ${e.expectedAlias}`,Timeout:r.timeout,MemorySize:r.memorySize});else{let de;for(let Re=0;Re<8;Re++)try{await n.lambda.createFunctionWithCode({FunctionName:e.functionName,Runtime:"nodejs22.x",Role:d.Arn,Handler:"index.handler",Code:Q,Filename:"index.mjs",Description:`Private API origin for ${e.expectedAlias}`,Timeout:r.timeout,MemorySize:r.memorySize}),de=void 0;break}catch(Me){if(de=Me,!String(Me.message).toLowerCase().includes("role"))throw Me;await n.sleep(1000)}if(de)throw de}await n.lambda.waitForFunctionActive(e.functionName);let D=h||await n.lambda.createFunctionUrl({FunctionName:e.functionName,AuthType:"AWS_IAM",InvokeMode:"BUFFERED"});if(!D.FunctionUrl)throw Error("Lambda did not return a function URL");let Y=new URL(D.FunctionUrl).hostname,se=await n.cloudfront.findOrCreateOriginAccessControl(w,"lambda"),he=o.ARN||`arn:aws:cloudfront::${i.Account}:distribution/${e.distributionId}`,je=[{FunctionName:e.functionName,StatementId:"AllowCloudFrontFunctionUrl",Action:"lambda:InvokeFunctionUrl",Principal:"cloudfront.amazonaws.com",SourceArn:he,FunctionUrlAuthType:"AWS_IAM"},{FunctionName:e.functionName,StatementId:"AllowCloudFrontInvoke",Action:"lambda:InvokeFunction",Principal:"cloudfront.amazonaws.com",SourceArn:he,InvokedViaFunctionUrl:!0}];for(let de of je)try{await n.lambda.addPermission(de)}catch(Re){if(!wp(Re))throw Re}return await n.cloudfront.upsertExistingDistributionOrigin(e.distributionId,{id:r.originId,domainName:Y,pathPattern:r.pathPattern,originAccessControlId:se.Id}),{...q,function:{...q.function,url:D.FunctionUrl},applied:!0}}async function nT(e){let t=`https://${e.alias}/`,r=`https://${e.alias}/api/health`,n=await fetch(t,{redirect:"follow",headers:{"cache-control":"no-cache"}}),i=new Uint8Array(await n.arrayBuffer()),o=yS("sha256").update(i).digest("hex"),s=Date.now(),c=await fetch(r,{redirect:"follow",headers:{"cache-control":"no-cache"}}),d=Date.now()-s,a=await c.text(),u=a;try{u=JSON.parse(a)}catch{}let m;if(e.logs&&e.functionName){let h=await e.logs.filterLogEvents({logGroupName:`/aws/lambda/${e.functionName}`,startTime:s-60000,filterPattern:'"Init Duration"',limit:25});for(let y of h.events||[]){let w=y.message?.match(/Init Duration:\s*([0-9.]+)\s*ms/i);if(w)m=Number(w[1])}}return{frontend:{url:t,status:n.status,sha256:o,unchanged:e.expectedFrontendSha256?o===e.expectedFrontendSha256:void 0,bytes:i.byteLength},api:{url:r,status:c.status,latencyMs:d,healthy:c.ok&&!!u?.ok,body:u},coldStart:{observed:m!==void 0,initDurationMs:m},verifiedAt:(e.now?.()||new Date).toISOString()}}function iT(e){let t=(e.memoryMb||256)/1024,r=Math.max(0,e.requests-(e.includeFreeTier===!1?0:1e6)),n=Math.max(0,e.requests*(e.averageDurationMs/1000)*t-(e.includeFreeTier===!1?0:400000)),i=r/1e6*0.2+n*0.0000166667,o=9.010025,s=16.425;return{lambdaUsd:Number(i.toFixed(2)),alwaysOnFargateAndAlbUsd:Number(25.435025000000003 .toFixed(2)),assumptions:["us-east-1 public list rates snapshot, July 2026","Lambda x86 request and duration pricing with optional monthly free tier","Fargate comparison uses one always-on 0.25 vCPU/0.5 GB task plus one ALB before LCU charges","excludes CloudFront, data transfer, logs, taxes, and application data services"]}}import{createHash as kS}from"node:crypto";function IS(e){let t=e;return String(t?.code||t?.name||t?.statusCode||"")}function ES(e){return IS(e)==="ValidationError"&&String(e.message).includes("does not exist")}function RS(e){return Object.fromEntries((e||[]).map((t)=>[t.OutputKey,t.OutputValue]))}function AS(e){let t=e?.Aliases?.Items??e?.Aliases;if(Array.isArray(t))return t.map(String);if(typeof t==="string")return[t];return[]}function Ap(e){if(!/^[a-z][a-z0-9-]{1,62}$/.test(e.slug))throw Error("Slug must be a lowercase DNS-safe identifier");if(!/^[A-Z0-9]{8,32}$/.test(e.distributionId))throw Error("CloudFront distribution ID is invalid");if(!/^(?=.{1,253}$)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z0-9-]{2,63}$/.test(e.expectedAlias))throw Error("Expected distribution alias is invalid");let t=e.imageUri.match(/@((?:sha256:)[a-f0-9]{64})$/i)?.[1];if(!t)throw Error("Container image must use an immutable ECR digest URI ending in @sha256:<64 hex>");let r=e.stackName||`${e.slug}-backend`;if(!/^[A-Za-z][A-Za-z0-9-]{0,127}$/.test(r))throw Error("CloudFormation stack name is invalid");let n=e.pathPattern||"/api/*";if(!/^\/[A-Za-z0-9_.*?~!$&'()+,;=:@%/-]+\*$/.test(n)||n==="/*")throw Error("Backend path must be a non-default wildcard pattern");let i=e.originId||`${e.slug}-backend`;if(!/^[A-Za-z0-9_.-]{1,128}$/.test(i))throw Error("CloudFront origin ID is invalid");if(e.originVerifySecret&&e.originVerifySecret.length<24)throw Error("Origin verification secret must contain at least 24 characters");if(!!e.originDomain!==!!e.certificateArn)throw Error("A custom origin domain and matching ACM certificate ARN must be provided together");return{stackName:r,region:e.region||"us-east-1",pathPattern:n,originId:i,digest:t}}function CS(e){let t=e.region||"us-east-1";return{cloudformation:new Er(t,e.profile),cloudfront:new Rn(e.profile),sts:new ci(t,e.profile),fetch,sleep:(r)=>new Promise((n)=>setTimeout(n,r))}}function PS(e){let t=Ap(e),r=Rp({name:e.name,slug:e.slug,domain:e.originDomain||e.expectedAlias,imageUri:e.imageUri,certificateArn:e.certificateArn,originVerifySecret:e.originVerifySecret,desiredCount:e.desiredCount,database:e.database,cache:e.cache,queue:e.queue}),n=Ep(r);return n.Description=`Managed backend for existing static frontend ${e.expectedAlias}`,n.Metadata={ManagedBy:"ts-cloud",ExistingDistributionId:e.distributionId,ExistingDistributionAlias:e.expectedAlias,BackendPathPattern:t.pathPattern,ContainerDigest:t.digest},n}async function _S(e,t,r){let n;for(let i=0;i<30;i++){let o=Date.now();try{let s=await e.fetch(t,{redirect:"manual",headers:r?{"x-origin-verify":r}:void 0}),c=Date.now()-o,d=await s.text(),a=d;try{a=JSON.parse(d)}catch{}if(s.ok)return{url:t,status:s.status,latencyMs:c,body:a};n=Error(`origin returned ${s.status}`)}catch(s){n=s}if(i<29)await e.sleep(1e4)}throw Error(`Backend origin did not become healthy: ${n instanceof Error?n.message:String(n)}`)}async function uT(e,t){let r=Ap(e),n=t||CS({region:r.region,profile:e.profile}),[i,o]=await Promise.all([n.sts.getCallerIdentity(),n.cloudfront.getDistribution(e.distributionId)]);if(!i.Account)throw Error("AWS identity did not return an account ID");if(!o.Enabled)throw Error(`CloudFront distribution ${e.distributionId} is disabled`);if(!AS(o).includes(e.expectedAlias))throw Error(`Distribution ${e.distributionId} does not contain expected alias ${e.expectedAlias}`);let s;try{s=(await n.cloudformation.describeStacks({stackName:r.stackName})).Stacks[0]}catch(O){if(!ES(O))throw O}let c=PS(e),d=JSON.stringify(c);if(Buffer.byteLength(d)>51200)throw Error("Generated template exceeds the direct CloudFormation template body limit");let a=Object.values(c.Resources||{}).reduce((O,U)=>(O[U.Type]=(O[U.Type]||0)+1,O),{}),u=[`cloud cdn:origin:remove ${e.distributionId} ${e.originDomain||"ALB_HOST"} --id ${r.originId} --path '${r.pathPattern}' --profile ${e.profile||"default"} --apply --confirm 'remove:${e.distributionId}:${r.pathPattern}'`,`After CloudFront is deployed, restore external DNS if changed and delete stack ${r.stackName} only with an approved data-retention decision.`],m={mode:e.apply?"apply":"plan",accountId:i.Account,stack:{name:r.stackName,existed:!!s,status:s?.StackStatus,templateSha256:kS("sha256").update(d).digest("hex"),resourceCount:Object.keys(c.Resources||{}).length,resourceTypes:a},distribution:{id:o.Id,alias:e.expectedAlias,domainName:o.DomainName,status:o.Status,pathPattern:r.pathPattern,originId:r.originId},artifact:{imageUri:e.imageUri,digest:r.digest},services:{database:e.database!==!1,cache:e.cache!==!1,queue:e.queue!==!1,mail:"ses",desiredCount:e.desiredCount||1},cloudFrontApplied:!1,dnsApplied:!1,applied:!1,rollback:u};if(!e.apply)return m;let h=`${e.distributionId}:${r.pathPattern}:${r.stackName}`;if(e.confirm!==h)throw Error(`Pass exact confirmation token ${h} to provision the backend and change live routing`);if(s)try{await n.cloudformation.updateStack({stackName:r.stackName,templateBody:d,capabilities:["CAPABILITY_NAMED_IAM"],tags:[{Key:"ManagedBy",Value:"ts-cloud"},{Key:"Application",Value:e.slug}]}),await n.cloudformation.waitForStack(r.stackName,"stack-update-complete")}catch(O){if(!String(O.message).includes("No updates are to be performed"))throw O}else await n.cloudformation.createStack({stackName:r.stackName,templateBody:d,capabilities:["CAPABILITY_NAMED_IAM"],onFailure:"ROLLBACK",tags:[{Key:"ManagedBy",Value:"ts-cloud"},{Key:"Application",Value:e.slug}]}),await n.cloudformation.waitForStack(r.stackName,"stack-create-complete");let y=(await n.cloudformation.describeStacks({stackName:r.stackName})).Stacks[0],w=RS(y?.Outputs),k=w.AppLoadBalancerDnsName;if(!k)throw Error("Backend stack did not return AppLoadBalancerDnsName");let C=!1;if(e.originDomain&&e.originDomain!==k){if(!n.dns)throw Error(`External DNS provider is required to map ${e.originDomain} to ${k}`);let O=await n.dns.upsertRecord(e.originDomain,{name:e.originDomain,type:"CNAME",content:k,ttl:300});if(!O.success)throw Error(O.message||"External DNS update failed");C=!0}let T=e.originDomain||k,j=e.certificateArn?"https-only":"http-only",P=e.skipHealthCheck?void 0:await _S(n,`${j==="https-only"?"https":"http"}://${T}/api/health`,e.originVerifySecret);return await n.cloudfront.upsertExistingDistributionOrigin(e.distributionId,{id:r.originId,domainName:T,pathPattern:r.pathPattern,protocolPolicy:j,customHeaders:e.originVerifySecret?{"X-Origin-Verify":e.originVerifySecret}:void 0}),{...m,outputs:w,health:P,cloudFrontApplied:!0,dnsApplied:C,applied:!0}}function pT(e={}){let r={fargate:730*(e.desiredCount||1)*0.012342500000000001,applicationLoadBalancer:16.425,natGateway:32.85,postgres:730*(e.multiAzDatabase?0.032:0.016),redis:23.36};return{monthlyUsd:Number(Object.values(r).reduce((n,i)=>n+i,0).toFixed(2)),components:Object.fromEntries(Object.entries(r).map(([n,i])=>[n,Number(i.toFixed(2))])),assumptions:["us-east-1 public on-demand rate snapshot, July 2026","one 0.25 vCPU/0.5 GB Linux Fargate task unless desiredCount is changed","one ALB before LCU charges and one NAT gateway before data processing","single-AZ db.t4g.micro PostgreSQL by default and two cache.t4g.micro Redis nodes","excludes storage, backups, CloudFront, data transfer, public IPv4, logs, email, queue requests, taxes, and free-tier credits"]}}import{execFileSync as TS}from"node:child_process";import{createHash as xS}from"node:crypto";import{existsSync as _p,mkdirSync as DS,mkdtempSync as OS,readdirSync as $S,readFileSync as NS,rmSync as jS,statSync as Tp,writeFileSync as MS}from"node:fs";import{tmpdir as BS}from"node:os";import{basename as LS,join as li,relative as FS,resolve as fc}from"node:path";var zS=new Set([".git","node_modules","dist","coverage"]);function xp(e,t=e){let r=[];for(let n of $S(e).sort()){if(zS.has(n))continue;let i=li(e,n);if(Cp(i,t))continue;let o=Tp(i);if(o.isDirectory())r.push(...xp(i,t));else if(o.isFile())r.push(FS(t,i))}return r}function US(e){let t=fc(e);if(!_p(t)||!Tp(t).isDirectory())throw Error(`Container context does not exist: ${t}`);let r=xS("sha256");for(let n of xp(t))r.update(n),r.update("\x00"),r.update(NS(li(t,n))),r.update("\x00");return r.digest("hex")}function qS(e){return{ecr:new Pp(e.region||"us-east-1",e.profile),run:(t,r,n)=>{TS(t,r,{cwd:n?.cwd,env:n?.env,stdio:n?.stdio||"inherit"})}}}async function wT(e,t){let r=fc(e.context),n=fc(e.dockerfile||li(r,"Dockerfile"));if(!_p(n))throw Error(`Dockerfile does not exist: ${n}`);if(!e.repository.split("/").every((w)=>/^[a-z0-9][a-z0-9._-]*$/.test(w)&&!/[._-]$/.test(w)&&!/[._-]{2}/.test(w)))throw Error("ECR repository name is invalid");let s=t||qS(e),c=US(r),d=`sha-${c.slice(0,20)}`,a="";try{a=(await s.ecr.describeRepositories({repositoryNames:[e.repository]})).repositories?.[0]?.repositoryUri||""}catch{}if(!a)a=(await s.ecr.createRepository({repositoryName:e.repository,imageTagMutability:"IMMUTABLE",imageScanningConfiguration:{scanOnPush:!0},tags:[{Key:"ManagedBy",Value:"ts-cloud"}]})).repository?.repositoryUri||"";if(!a)throw Error(`Could not resolve ECR repository URI for ${e.repository}`);await s.ecr.putLifecyclePolicy({repositoryName:e.repository,lifecyclePolicyText:JSON.stringify({rules:[{rulePriority:1,description:"Retain the newest 25 release images",selection:{tagStatus:"any",countType:"imageCountMoreThan",countNumber:25},action:{type:"expire"}}]})});let u=`${a}:${d}`,m=OS(li(BS(),"ts-cloud-container-"));try{s.run("docker",["version"],{stdio:"ignore"}),s.run("docker",["build","--platform",e.platform||"linux/amd64","--provenance=false","--sbom=false","--file",n,"--tag",u,r],{cwd:r});let w=(await s.ecr.getAuthorizationToken()).authorizationData?.[0];if(!w?.authorizationToken||!w.proxyEndpoint)throw Error("ECR did not return Docker authorization data");let k=w.proxyEndpoint.replace(/^https?:\/\//,""),C=li(m,"docker");DS(C,{recursive:!0}),MS(li(C,"config.json"),JSON.stringify({auths:{[k]:{auth:w.authorizationToken}}}),{mode:384}),s.run("docker",["push",u],{env:{...process.env,DOCKER_CONFIG:C}})}finally{jS(m,{recursive:!0,force:!0})}let y=(await s.ecr.describeImages({repositoryName:e.repository,imageIds:[{imageTag:d}]})).imageDetails?.[0]?.imageDigest;if(!y||!/^sha256:[a-f0-9]{64}$/i.test(y))throw Error(`ECR did not return an immutable digest for ${LS(u)}`);return{repository:e.repository,tag:d,imageUri:u,digest:y,digestUri:`${a}@${y}`,contextSha256:c}}import{existsSync as VS,readdirSync as WS,readFileSync as HS,statSync as KS}from"node:fs";import{join as qp,relative as JS}from"node:path";function Cn(e,t){let r=e.environments?.[t]?.app;if(!r)throw Error(`No serverless app configured for environment '${t}'. Add environments.${t}.app to your config.`);let n=e.project.slug,i=e.environments?.[t]?.region||e.project.region||"us-east-1";return{app:r,slug:n,region:i,stackName:ui(e,t),artifactBucket:Dp(n,t),assetsBucket:Op(n,t)}}async function An(e,t=8){let r;for(let n=0;n<t;n++)try{return await e()}catch(i){let o=i?.code||i?.name||"",s=String(i?.message||"");if(o==="ResourceConflictException"||/update is in progress|currently in the following state/i.test(s)){r=i,await new Promise((c)=>setTimeout(c,3000));continue}throw i}throw r}var Vp=(e,t)=>`releases/${e}/${t}/current.json`;async function ss(e,t,r,n){try{return await e.getObjectJson(t,Vp(r,n))}catch{return null}}async function Wp(e,t,r,n,i){await e.putObjectJson(t,Vp(r,n),i)}async function GS(e,t){if(!e.secrets)return{};let r=new Yr(t),n={},i=Array.isArray(e.secrets)?e.secrets.map((o)=>({envName:o.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),secretId:o})):Object.entries(e.secrets).map(([o,s])=>({envName:o,secretId:s}));if(Array.isArray(e.secrets)){let o=new Map;for(let{envName:c,secretId:d}of i)o.set(c,[...o.get(c)??[],d]);let s=[...o.entries()].filter(([,c])=>c.length>1);if(s.length){let c=s.map(([d,a])=>`${d} ← ${a.join(", ")}`).join("; ");throw Error(`serverless secrets: multiple secrets map to the same env var (${c}). Use the map form { ENV_NAME: 'secret/id' } to disambiguate.`)}}for(let{envName:o,secretId:s}of i){let d=(await r.getSecretValue({SecretId:s})).SecretString??"";try{let a=JSON.parse(d);if(a&&typeof a==="object"&&!Array.isArray(a)){for(let[u,m]of Object.entries(a))n[u]=String(m);continue}}catch{}n[o]=d}return n}function Hp(e,t){let r={},n=t.DbProxyEndpoint||t.DbEndpoint;if(n)r.DB_CONNECTION="mysql",r.DB_HOST=n,r.DB_PORT="3306",r.DB_DATABASE=r.DB_DATABASE||"app";if(t.CacheEndpoint){if(r.REDIS_HOST=t.CacheEndpoint,r.REDIS_PORT="6379",e.cache?.driver==="elasticache")r.CACHE_STORE="redis",r.CACHE_DRIVER="redis",r.SESSION_DRIVER="redis"}return r}function ns(e,t,r,n,i,o,s,c={}){let d=e.kind==="php"?Lp({cacheDriver:e.cache?.driver==="elasticache"?"redis":"dynamodb"}):{};return{TSCLOUD_LAMBDA_MODE:n,TSCLOUD_ENV:r,MAINTENANCE_MODE:"0",...e.octane?{TSCLOUD_OCTANE:"1"}:{},...e.serveAssets?{TSCLOUD_SERVE_ASSETS:"1"}:{},...e.redirectRobotsTxt===!1?{TSCLOUD_REDIRECT_ROBOTS_TXT:"0"}:{},...d,...c,...t.app.cache?.driver!=="elasticache"?{TSCLOUD_CACHE_TABLE:`${t.slug}-${r}-cache`}:{},...s?{TSCLOUD_QUEUE:s,SQS_QUEUE:s}:{},...o?{ASSET_URL:o}:{},...e.env??{},...i}}function QS(e){let t=e.slice(e.lastIndexOf(".")).toLowerCase();return{".html":"text/html",".css":"text/css",".js":"text/javascript",".mjs":"text/javascript",".json":"application/json",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".txt":"text/plain",".map":"application/json"}[t]??"application/octet-stream"}function*Kp(e){for(let t of WS(e)){let r=qp(e,t);if(KS(r).isDirectory())yield*Kp(r);else yield r}}async function YS(e,t,r,n,i=!1){let o=0;for(let s of Kp(r)){let c=JS(r,s).replace(/\\/g,"/");if(!i&&c.split("/").some((d)=>d.startsWith(".")))continue;await e.putObject({bucket:t,key:`${n}/${c}`,body:HS(s),contentType:QS(s),cacheControl:"public, max-age=31536000, immutable"}),o++}return o}function ZS(e,t){let r=Object.entries(t).reduce((n,[i,o])=>n+Buffer.byteLength(`${i}=${o}`,"utf8"),0);if(r>4096){let n=Object.entries(t).map(([i,o])=>[i,Buffer.byteLength(`${i}=${o}`,"utf8")]).sort((i,o)=>o[1]-i[1]).slice(0,5).map(([i,o])=>`${i} (${o}B)`).join(", ");throw Error(`${e}: environment variables total ${r}B, over AWS's 4096B limit (${r-4096}B too large). Largest: ${n}. Move large/secret values out of env — store them in Secrets Manager and fetch at cold start.`)}}async function eo(e,t,r,n){ZS(t,r),await An(()=>e.updateFunctionConfiguration({FunctionName:t,Environment:{Variables:r}})),await e.waitForFunctionActive(t,120);let i=n.kind==="image"?{FunctionName:t,ImageUri:n.imageUri}:{FunctionName:t,S3Bucket:n.bucket,S3Key:n.key};await An(()=>e.updateFunctionCode(i)),await e.waitForFunctionActive(t,120)}async function is(e,t){let n=(await An(()=>e.publishVersion({FunctionName:t}))).Version;if(!n)throw Error(`publishVersion returned no version for ${t}`);return await An(()=>e.updateAlias({FunctionName:t,Name:"live",FunctionVersion:n})),n}async function XS(e,t,r={}){let n=Cn(e,t),{app:i,slug:o,region:s,stackName:c,artifactBucket:d}=n,a=r.projectRoot??process.cwd();os(`Deploying serverless app: ${o} (${t})`),Mt(`Stack: ${c}`),Mt(`Region: ${s}`);let u=new ur(s),m=new Er(s),h=new kt(s),y=i.kind==="php",w=i.packaging==="image",k=jp(i),C,T,j,P,O=[];if(w&&k.usesLayer&&k.layerKind!=="php")throw Error(`packaging: 'image' currently supports PHP and managed Node runtimes. ${k.kind}${k.kind==="node"?` ${k.version}`:""} uses a custom runtime — `+"use the default zip packaging (the runtime layer is built + attached automatically).");if(w){ct("Building + pushing container image");let{buildAndPushServerlessImage:F}=await import("./chunk-nms5q44e.js"),K=await F({app:i,projectRoot:a,region:s,repository:`${o}-${t}`,skipBuild:r.skipBuild,onStep:(ye)=>Mt(` ${ye}`)});C=K.handlers,T={kind:"image",imageUri:K.imageUri},j=K.tag,O.push({ParameterKey:"ImageUri",ParameterValue:K.imageUri})}else{ct("Packaging application");let F=y?Fp({projectRoot:a,app:i,skipBuild:r.skipBuild,onStep:(Ae)=>Mt(` ${Ae}`)}):await Np({projectRoot:a,app:i,skipBuild:r.skipBuild,onStep:(Ae)=>Mt(` ${Ae}`)}),K=$p(o,t,F.sha256);if(Mt(`Artifact: ${F.sha256.slice(0,12)} (${(F.zip.length/1024).toFixed(0)} KB)`),C=F.handlers,j=F.sha256,k.usesLayer){let Ae=k.layerEnvVar?process.env[k.layerEnvVar]:void 0;if(P=i.layers??(Ae?[Ae]:void 0),!P?.length){let G=k.layerKind==="php"?"serverless:build-php-layer":k.layerKind==="bun"?"serverless:build-bun-layer":"serverless:build-node-layer";throw Error(`${k.kind} apps on provided.al2023 need a runtime layer. Set environments.<env>.app.layers or the ${k.layerEnvVar} env var (build one with \`cloud ${G}\`)${k.kind==="node"?", or use a managed Node version (18/20/22)":""}.`)}}if(!await u.bucketExists(d))ct(`Creating artifact bucket ${d}`),await u.createBucket(d);if(await u.headObject(d,K).then((Ae)=>Ae!==null).catch(()=>!1))Mt("Artifact already uploaded — reusing");else ct("Uploading artifact"),await u.putObject({bucket:d,key:K,body:F.zip,contentType:"application/zip"});T={kind:"zip",bucket:d,key:K},O.push({ParameterKey:"ArtifactBucket",ParameterValue:d},{ParameterKey:"ArtifactKey",ParameterValue:K})}let U=Bp({config:e,environment:t,app:i,handlers:C,runtimeLayers:P}),q=JSON.stringify(U.template),N=["CAPABILITY_NAMED_IAM"],Q=await m.describeStacks({stackName:c}).then((F)=>F.Stacks[0]?.StackStatus).catch(()=>{return}),D=Q!==void 0;if(Q&&/DELETE_IN_PROGRESS/.test(Q))ct("Waiting for an in-progress stack delete to finish"),await m.waitForStack(c,"stack-delete-complete").catch(()=>{}),D=!1;else if(Q&&/(?:ROLLBACK_COMPLETE|REVIEW_IN_PROGRESS|CREATE_FAILED)/.test(Q))ct(`Deleting unusable stack (status ${Q}) before recreate`),await m.deleteStack(c),await m.waitForStack(c,"stack-delete-complete").catch(()=>{}),D=!1;ct(D?"Updating infrastructure stack":"Creating infrastructure stack");try{if(D)await m.updateStack({stackName:c,templateBody:q,parameters:O,capabilities:N}),await m.waitForStack(c,"stack-update-complete");else await m.createStack({stackName:c,templateBody:q,parameters:O,capabilities:N,onFailure:"DELETE"}),await m.waitForStack(c,"stack-create-complete")}catch(F){if(/No updates are to be performed/i.test(String(F?.message)))Mt("No infrastructure changes");else throw F}let Y=await m.getStackOutputs(c).catch(()=>({})),se;if(i.assets){let F=qp(a,i.assets);if(VS(F)){let K=i.assetDomain||Y.AssetsCdnDomain;se=K?`https://${K}/${j}`:void 0,ct(`Syncing assets from ${i.assets}`);let ye=await YS(u,n.assetsBucket,F,j,i.dotFilesAsAssets);Mt(`Uploaded ${ye} asset(s)${se?` → ${se}`:""}`)}else rs(`Assets directory not found: ${F}`)}ct("Resolving secrets");let he=await GS(i,s);if(i.database?.connection==="aurora-serverless")try{let K=await new Yr(s).getSecretValue({SecretId:`${o}/${t}/db`}),ye=JSON.parse(K.SecretString??"{}");if(ye.username)he.DB_USERNAME=ye.username;if(ye.password)he.DB_PASSWORD=ye.password}catch(F){rs(`Could not resolve Aurora DB credentials: ${F.message}`)}if(!await u.bucketExists(d))await u.createBucket(d);let je=await ss(u,d,o,t),de={},Re=U.queueNames[0],Me=Hp(i,Y);if(ct("Activating functions"),de.http=ns(i,n,t,"http",he,se,Re,Me),await eo(h,U.functionNames.http,de.http,T),de.cli=ns(i,n,t,"cli",he,se,Re,Me),await eo(h,U.functionNames.cli,de.cli,T),U.queueNames.length)de.queue=ns(i,n,t,"queue",he,se,Re,Me),await eo(h,U.functionNames.queue,de.queue,T);let me=(i.provisionedConcurrency??0)>0,R={};if(me){if(ct("Publishing versions + flipping live alias"),R.http=await is(h,U.functionNames.http),R.cli=await is(h,U.functionNames.cli),U.queueNames.length)R.queue=await is(h,U.functionNames.queue)}if(await Wp(u,d,o,t,{sha:j,code:T,previousSha:je?.sha,previousCode:je?.code,previousFunctionEnv:je?.functionEnv,...me?{functionVersions:R,previousFunctionVersions:je?.functionVersions}:{},functionEnv:de,functionNames:{http:U.functionNames.http,cli:U.functionNames.cli,...U.queueNames.length?{queue:U.functionNames.queue}:{}},assetUrl:se,timestamp:new Date().toISOString()}),!r.skipDeployHooks&&i.deploy?.length){ct("Running deploy hooks");for(let F of i.deploy){Mt(` deploy: ${F}`);let K=await h.invoke({FunctionName:U.functionNames.cli,InvocationType:"RequestResponse",Payload:{command:F},LogType:"Tail"});if(K.FunctionError)throw zp("Deploy hook failed — the new build is ALREADY LIVE."),Mt(` Roll back with: cloud serverless:rollback --env ${t}`),Error(`Deploy hook failed (${F}): ${K.Payload}`)}}let M=Y.HttpApiEndpoint;if(!r.skipHealthCheck&&M){ct("Health check");try{let F=await fetch(M,{method:"GET"});Mt(`GET ${M} → ${F.status}`)}catch(F){rs(`Health check could not reach ${M}: ${F.message}`)}}Up(["Serverless deploy complete","",M?`URL: ${M}`:"",`Stack: ${c}`,`Build: ${j.slice(0,12)}`].filter(Boolean).join(`
|
|
15
|
+
`),"green")}async function hc(e,t){let r=Cn(e,t),n=new ur(r.region),i=new kt(r.region),o=await ss(n,r.artifactBucket,r.slug,t);if(!o)throw Error("No previous release to redeploy. Run a full deploy first.");os(`Redeploying ${r.slug} (${t}) — build ${o.sha.slice(0,12)}`);for(let[s,c]of Object.entries(o.functionNames)){if(!c)continue;ct(`Re-activating ${s} (${c})`),await eo(i,c,o.functionEnv[s]??{},o.code);let d=o.functionVersions?.[s];if(d)await An(()=>i.updateAlias({FunctionName:c,Name:"live",FunctionVersion:d}))}to("Redeploy complete")}async function yc(e,t){let r=Cn(e,t),n=new ur(r.region),i=new kt(r.region),o=await ss(n,r.artifactBucket,r.slug,t);if(!o?.previousCode)throw Error("No previous release to roll back to.");os(`Rolling back ${r.slug} (${t}) → ${o.previousSha?.slice(0,12)}`);for(let[s,c]of Object.entries(o.functionNames)){if(!c)continue;ct(`Restoring ${s} (${c})`);let d=o.previousFunctionEnv?.[s]??o.functionEnv[s]??{};await eo(i,c,d,o.previousCode);let a=o.previousFunctionVersions?.[s];if(a)await An(()=>i.updateAlias({FunctionName:c,Name:"live",FunctionVersion:a}))}await Wp(n,r.artifactBucket,r.slug,t,{...o,sha:o.previousSha??o.sha,code:o.previousCode,functionEnv:o.previousFunctionEnv??o.functionEnv,functionVersions:o.previousFunctionVersions??o.functionVersions,previousSha:void 0,previousCode:void 0,previousFunctionEnv:void 0,previousFunctionVersions:void 0,timestamp:new Date().toISOString()}),to("Rollback complete")}async function as(e,t,r,n){let i=Cn(e,t),o=new kt(i.region),s=`${i.slug}-${t}-http`,d={...(await o.getFunction(s)).Configuration?.Environment?.Variables??{}};if(d.MAINTENANCE_MODE=r?"1":"0",r&&n)d.MAINTENANCE_BYPASS_SECRET=n;if(!r)delete d.MAINTENANCE_BYPASS_SECRET;if(await An(()=>o.updateFunctionConfiguration({FunctionName:s,Environment:{Variables:d}})),(i.app.provisionedConcurrency??0)>0)await o.waitForFunctionActive(s,120),await is(o,s);to(r?"Application is now in maintenance mode (503)":"Application is live")}async function pi(e,t,r){let n=Cn(e,t),i=new kt(n.region),o=`${n.slug}-${t}-cli`,s=await i.invoke({FunctionName:o,InvocationType:"RequestResponse",Payload:{command:r},LogType:"Tail"});if(s.FunctionError)throw Error(`Command failed: ${s.Payload}`);return s.Payload??""}async function nt(e,t){let r=Cn(e,t),n=new Er(r.region),i=new kt(r.region),o=new ur(r.region),s="not deployed",c={};try{let{Stacks:w}=await n.describeStacks({stackName:r.stackName});s=w?.[0]?.StackStatus??s;for(let k of w?.[0]?.Outputs??[])if(k.OutputKey)c[k.OutputKey]=k.OutputValue??""}catch{}let d=Mp(r.app,r.slug,t),a=r.app.provisionedConcurrency??0,u=["http","cli",...d.length?["queue"]:[]],m=`${r.slug}-${t}`,h=[];for(let w of u){let k=`${m}-${w}`,C={mode:w,name:k,version:"$LATEST"};if(a>0){let T=await i.getAlias(k,"live").catch(()=>null);if(T?.FunctionVersion){C.version=T.FunctionVersion;let j=await i.getProvisionedConcurrencyConfig(k,"live").catch(()=>null);if(j)C.provisioned={status:j.Status??"-",allocated:j.AllocatedProvisionedConcurrentExecutions??0,requested:j.RequestedProvisionedConcurrentExecutions??0}}}h.push(C)}let y=await ss(o,r.artifactBucket,r.slug,t).catch(()=>null);return{slug:r.slug,environment:t,region:r.region,stackStatus:s,endpoint:c.HttpApiEndpoint,assetUrl:y?.assetUrl,scheduler:r.app.scheduler??"on",queues:d,provisionedConcurrency:a,functions:h,lastRelease:y?{sha:y.sha,timestamp:y.timestamp}:void 0}}function ew(e,t){return`${e}-${t}-db`}async function Jp(e,t,r,n){let i=Cn(e,t);if(i.app.database?.connection!=="aurora-serverless")throw Error("No Aurora Serverless v2 database is configured for this environment.");let{RDSClient:o}=await import("./chunk-t3t9ymec.js"),s=new o(i.region),c=ew(i.slug,t);ct(`Scaling ${c} → ${r}–${n} ACUs`),await s.modifyDBCluster({DBClusterIdentifier:c,ServerlessV2ScalingConfiguration:{MinCapacity:r,MaxCapacity:n},ApplyImmediately:!0}),to(`Scaling applied to ${c} (takes effect shortly).`)}class Rr{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new mi(Qp(t))}async query(e){let t=new URLSearchParams(Gp({Version:"2010-08-01",...e})).toString();return this.client.request({service:"monitoring",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t})}async getMetricStatistics(e){let t={Action:"GetMetricStatistics",Namespace:e.Namespace,MetricName:e.MetricName,StartTime:e.StartTime.toISOString(),EndTime:e.EndTime.toISOString(),Period:e.Period};(e.Statistics??[]).forEach((o,s)=>{t[`Statistics.member.${s+1}`]=o}),(e.ExtendedStatistics??[]).forEach((o,s)=>{t[`ExtendedStatistics.member.${s+1}`]=o}),(e.Dimensions??[]).forEach((o,s)=>{t[`Dimensions.member.${s+1}.Name`]=o.Name,t[`Dimensions.member.${s+1}.Value`]=o.Value});let r=await this.query(t),i=(r.GetMetricStatisticsResult||r)?.Datapoints?.member??[];if(!Array.isArray(i))i=i?[i]:[];return i.map((o)=>{let s={},c=o.ExtendedStatistics?.entry;if(c){if(!Array.isArray(c))c=[c];for(let d of c)if(d?.key!=null)s[d.key]=Number(d.value)}return{Timestamp:o.Timestamp,Sum:o.Sum!=null?Number(o.Sum):void 0,Average:o.Average!=null?Number(o.Average):void 0,Maximum:o.Maximum!=null?Number(o.Maximum):void 0,Minimum:o.Minimum!=null?Number(o.Minimum):void 0,Percentiles:Object.keys(s).length?s:void 0,Unit:o.Unit}})}async getMetricSeries(e){let t=/^p\d/.test(e.Stat);return(await this.getMetricStatistics({Namespace:e.Namespace,MetricName:e.MetricName,Dimensions:e.Dimensions,StartTime:e.StartTime,EndTime:e.EndTime,Period:e.Period,Statistics:t?[]:[e.Stat],ExtendedStatistics:t?[e.Stat]:[]})).slice().sort((n,i)=>new Date(n.Timestamp??0).getTime()-new Date(i.Timestamp??0).getTime()).map((n)=>t?n.Percentiles?.[e.Stat]??0:n[e.Stat]??0)}async describeAlarms(e){let t={Action:"DescribeAlarms"};if(e?.AlarmNamePrefix)t.AlarmNamePrefix=e.AlarmNamePrefix;if(e?.MaxRecords)t.MaxRecords=e.MaxRecords;let r=await this.query(t),i=(r.DescribeAlarmsResult||r)?.MetricAlarms?.member??[];if(!Array.isArray(i))i=i?[i]:[];return i.map((o)=>({AlarmName:o.AlarmName,StateValue:o.StateValue,MetricName:o.MetricName,ComparisonOperator:o.ComparisonOperator,Threshold:o.Threshold!=null?Number(o.Threshold):void 0,Namespace:o.Namespace}))}async putMetricAlarm(e){let t={Action:"PutMetricAlarm",AlarmName:e.AlarmName,Namespace:e.Namespace,MetricName:e.MetricName,ComparisonOperator:e.ComparisonOperator,Threshold:e.Threshold,EvaluationPeriods:e.EvaluationPeriods,Period:e.Period,Statistic:e.Statistic};if(e.AlarmDescription)t.AlarmDescription=e.AlarmDescription;(e.Dimensions??[]).forEach((r,n)=>{t[`Dimensions.member.${n+1}.Name`]=r.Name,t[`Dimensions.member.${n+1}.Value`]=r.Value}),(e.AlarmActions??[]).forEach((r,n)=>{t[`AlarmActions.member.${n+1}`]=r}),await this.query(t)}async deleteAlarms(e){if(!e.length)return;let t={Action:"DeleteAlarms"};e.forEach((r,n)=>{t[`AlarmNames.member.${n+1}`]=r}),await this.query(t)}}class vc{client;region;constructor(e="us-east-1"){this.region=e,this.client=new mi}async call(e,t){return this.client.request({service:"wafv2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`AWSWAF_20190729.${e}`},body:JSON.stringify(t)})}async listWebACLs(e="REGIONAL"){return(await this.call("ListWebACLs",{Scope:e,Limit:100}))?.WebACLs??[]}async getWebACLRules(e,t,r="REGIONAL"){return((await this.call("GetWebACL",{Name:e,Id:t,Scope:r}))?.WebACL?.Rules??[]).map((o)=>({Name:o.Name,Priority:o.Priority,Action:o.Action?Object.keys(o.Action)[0]:o.OverrideAction?Object.keys(o.OverrideAction)[0]:"count"}))}}var tw=[{index:0,id:"clients",label:"Clients"},{index:1,id:"dns",label:"DNS & TLS"},{index:2,id:"edge",label:"Edge"},{index:3,id:"routing",label:"Routing"},{index:4,id:"apps",label:"Applications"},{index:5,id:"runtime",label:"Background runtime"},{index:6,id:"data",label:"Data services"},{index:7,id:"durability",label:"Durability"}],rw=[{index:0,id:"clients",label:"Clients"},{index:1,id:"dns",label:"DNS & TLS"},{index:2,id:"edge",label:"Edge"},{index:3,id:"entry",label:"Entry points"},{index:4,id:"compute",label:"Compute"},{index:5,id:"messaging",label:"Messaging & pooling"},{index:6,id:"data",label:"Data services"},{index:7,id:"durability",label:"Durability"}],nw=[{match:/^redis/,kind:"cache",label:"Redis"},{match:/^(?:mysql|mariadb)/,kind:"database",label:"MySQL"},{match:/^postgres/,kind:"database",label:"PostgreSQL"},{match:/^meilisearch/,kind:"database",label:"Meilisearch"},{match:/^vitess|^vtgate/,kind:"database",label:"Vitess"},{match:/^memcached/,kind:"cache",label:"Memcached"}],iw=/^(?:rpx-gateway|nginx|caddy|traefik|haproxy)$/;function J(e,t=""){let r=e==null?"":String(e).trim();return r&&r!=="-"&&r!=="—"?r:t}function ow(e){return Array.isArray(e)?e.length:0}function Qt(e){let t=J(e).toLowerCase();if(!t)return"unknown";if(["running","live","active","available","success","ok","healthy","enabled"].includes(t))return"ok";if(["failed","stopped","unreachable","error","critical","disabled"].includes(t))return"bad";if(["configured","creating","pending","degraded","shadowed","warn","unknown"].includes(t))return"warn";return"warn"}function Ue(e,t,r){if(r.has(t.source)&&r.has(t.target))e.push(t)}function Pn(e,t={}){let r=[],n=[],i=[],o=e.server??{},s=Array.isArray(e.sites)?e.sites:[],c=Array.isArray(e.services)?e.services:[],d=Array.isArray(e.workers)?e.workers:[],a=e.security??{},u=!!e._serverReachable&&!e.metricsUnavailable,m="box";if(!u)i.push("The compute box could not be probed, so live service state is missing; the shape comes from your cloud config.");r.push({id:"internet",label:"Internet",kind:"internet",layer:0,status:"ok",sub:"Public traffic",facts:[],external:!0});let h=[...new Set(s.map((N)=>J(N.domain)||J(N.route).split("/")[0]).filter((N)=>N&&N!=="internal"&&N!=="loopback"))],y=Array.isArray(a.tlsCertificates)?a.tlsCertificates:[],w=y.filter((N)=>Number(N?.daysRemaining??999)<21).length;r.push({id:"dns",label:h.length===1?h[0]:"Public domains",kind:"dns",layer:1,status:w?"warn":h.length?"ok":"unknown",sub:h.length>1?`${h.length} domains`:"DNS & certificates",facts:[{label:"Domains",value:h.length?h.slice(0,6).join(", "):"none resolved"},{label:"Certificates",value:y.length?`${y.length} issued`:"none reported"},...w?[{label:"Expiring",value:`${w} within 21 days`}]:[]],href:"/server/security",external:!0});let k=a.firewall??{},C=Array.isArray(a.ports)?a.ports:[];r.push({id:"firewall",label:"Host firewall",kind:"firewall",layer:2,status:Qt(k.status),sub:J(k.summary,"Inbound filtering"),facts:[{label:"State",value:J(k.status,"unknown")},{label:"Open ports",value:C.length?C.map((N)=>J(N.listen)).join(", "):"not reported"}],href:"/server/firewall",group:"box"});let T=c.find((N)=>iw.test(J(N.name)));r.push({id:"proxy",label:J(T?.name,"Reverse proxy"),kind:"proxy",layer:3,status:T?Qt(T.status):"unknown",sub:"TLS termination & routing",facts:[{label:"Service",value:J(T?.name,"not detected")},{label:"State",value:J(T?.status,u?"not running":"not probed")},{label:"Routes",value:`${s.length} site${s.length===1?"":"s"}`}],href:"/server/services",group:"box"});for(let N of s){let Q=`site:${J(N.name)}`;if(!J(N.name))continue;r.push({id:Q,label:J(N.name),kind:"site",layer:4,status:Qt(N.status),sub:J(N.runtime,"runtime"),facts:[{label:"Route",value:J(N.route,"internal")},{label:"Runtime",value:J(N.runtime,"unknown")},{label:"Delivery",value:J(N.deploy,"unknown")},{label:"TLS",value:J(N.tls,"unknown")},...N.responseMs!=null?[{label:"Response",value:`${Math.round(Number(N.responseMs))} ms`}]:[],...N.httpStatus!=null?[{label:"HTTP",value:String(N.httpStatus)}]:[]],href:"/server/sites",group:"box"})}for(let N of d){let Q=`worker:${J(N.name)}`;if(!J(N.name))continue;r.push({id:Q,label:J(N.name),kind:"worker",layer:5,status:Qt(N.status),sub:`${Number(N.processes??1)} process${Number(N.processes??1)===1?"":"es"}`,facts:[{label:"Processes",value:String(N.processes??1)},{label:"State",value:J(N.status,"unknown")},...J(N.site)?[{label:"Site",value:J(N.site)}]:[]],href:"/operations/jobs",group:"box"})}let j=e.serverScheduler??{};if(j.enabled)r.push({id:"scheduler",label:"Scheduler",kind:"scheduler",layer:5,status:"ok",sub:"Cron dispatch",facts:[{label:"Last run",value:J(j.lastRun,"unknown")}],href:"/operations/jobs",group:"box"});let P=c.map((N)=>{let Q=J(N.name),D=nw.find((Y)=>Y.match.test(Q));return D?{service:N,name:Q,...D}:null}).filter((N)=>!!N);for(let N of P)r.push({id:`data:${N.name}`,label:N.label,kind:N.kind,layer:6,status:Qt(N.service.status),sub:N.name,facts:[{label:"Unit",value:N.name},{label:"State",value:J(N.service.status,"unknown")}],href:"/data/services",group:"box"});let O=e.backup??{};if(O.enabled)r.push({id:"backup",label:"Backups",kind:"backup",layer:7,status:"ok",sub:J(O.destination,"destination"),facts:[{label:"Destination",value:J(O.destination,"unknown")},{label:"Schedule",value:J(O.schedule,"unknown")},{label:"Retention",value:`${O.retention??0} copies`},{label:"Last run",value:J(O.last,"unknown")}],href:"/data/backups"});let U=new Set(r.map((N)=>N.id));Ue(n,{source:"internet",target:"dns",flow:"request",label:"https"},U),Ue(n,{source:"dns",target:"firewall",flow:"request",label:"443/80"},U),Ue(n,{source:"firewall",target:"proxy",flow:"request"},U);for(let N of s){let Q=`site:${J(N.name)}`;Ue(n,{source:"proxy",target:Q,flow:"request",label:J(N.path)||void 0,status:Qt(N.status)},U)}for(let N of d){let Q=`worker:${J(N.name)}`,D=`site:${J(N.site)}`;if(U.has(D))Ue(n,{source:D,target:Q,flow:"async",label:"queue"},U);else Ue(n,{source:"proxy",target:Q,flow:"async",label:"queue"},U)}for(let N of d)Ue(n,{source:"scheduler",target:`worker:${J(N.name)}`,flow:"async",label:"dispatch"},U);let q=[...s.map((N)=>`site:${J(N.name)}`),...d.map((N)=>`worker:${J(N.name)}`)];for(let N of P)for(let Q of q)Ue(n,{source:Q,target:`data:${N.name}`,flow:"data",label:"localhost"},U);if(P.length&&q.length)i.push("Data-service edges show co-location on the box: every process on it can reach localhost. They are not a declared per-site binding.");for(let N of P)Ue(n,{source:`data:${N.name}`,target:"backup",flow:"backup",label:"snapshot"},U);for(let N of s)Ue(n,{source:`site:${J(N.name)}`,target:"backup",flow:"backup"},U);return{mode:"server",project:J(t.project)||J(e.project?.name)||J(o.name,"project"),environment:J(t.environment)||J(e.environment,"production"),provider:J(o.provider,"unknown"),region:J(o.region,"unknown"),generatedAt:new Date().toISOString(),layers:tw,groups:[{id:"box",label:J(o.name,"App server"),sub:[J(o.provider),J(o.region),J(o.ip)].filter(Boolean).join(" · ")}],nodes:r,links:n,notes:i}}function cs(e,t={}){let r=[],n=[],i=[],o=e.app??{},s=Array.isArray(e.functions)?e.functions:[],c=Array.isArray(e.queues)?e.queues:[],d=e.metrics??{};if(!s.length)i.push("No Lambda functions were read for this environment, so the compute layer is empty rather than assumed.");r.push({id:"internet",label:"Internet",kind:"internet",layer:0,status:"ok",sub:"Public traffic",facts:[],external:!0});let a=J(o.url),u=a.replace(/^https?:\/\//,"").split("/")[0];r.push({id:"dns",label:u||"Application domain",kind:"dns",layer:1,status:u?"ok":"unknown",sub:"DNS & certificates",facts:[{label:"Endpoint",value:a||"not resolved"}],external:!0});let m=e.waf;if(m)r.push({id:"waf",label:"WAF",kind:"waf",layer:2,status:Qt(m.status??"active"),sub:J(m.scope,"Managed rules"),facts:[{label:"Web ACL",value:J(m.name,"unnamed")},...m.blocked!=null?[{label:"Blocked (24h)",value:String(m.blocked)}]:[],{label:"Rules",value:String(ow(e.wafRules))}],href:"/serverless/firewall"});let h=e.assetsInfo;if(h)r.push({id:"cdn",label:"Asset CDN",kind:"cdn",layer:2,status:"ok",sub:J(h.cdn,"CloudFront"),facts:[{label:"Distribution",value:J(h.cdn,"unknown")},{label:"Custom domain",value:J(h.customDomain,"none")}],href:"/serverless/assets"}),r.push({id:"assets",label:"Asset bucket",kind:"storage",layer:6,status:"ok",sub:J(h.bucket,"S3"),facts:[{label:"Bucket",value:J(h.bucket,"unknown")},...h.files?[{label:"Objects",value:String(h.files)}]:[],...h.sizeMb?[{label:"Size",value:`${h.sizeMb} MB`}]:[]],href:"/serverless/assets"});let y=s.find((D)=>J(D.key).startsWith("http"));r.push({id:"gateway",label:"HTTP entry point",kind:"gateway",layer:3,status:y?"ok":"unknown",sub:"Function URL / API Gateway",facts:[{label:"Endpoint",value:a||"not resolved"},{label:"Invocations (24h)",value:String(d.invocations??0)},...d.errorRatePct!=null?[{label:"Error rate",value:`${d.errorRatePct}%`}]:[]],href:"/serverless/metrics"});for(let D of s){let Y=`fn:${J(D.name)}`;if(!J(D.name))continue;let se=Number(D.errors??0),he=Number(D.invocations??0);r.push({id:Y,label:J(D.key,J(D.name)),kind:"function",layer:4,status:se>0?he&&se/he>0.02?"bad":"warn":he?"ok":"idle",sub:J(D.runtime,"lambda"),facts:[{label:"Function",value:J(D.name)},{label:"Memory",value:`${D.memory??0} MB`},{label:"Timeout",value:`${D.timeout??0}s`},{label:"Invocations (24h)",value:String(he)},{label:"Errors (24h)",value:String(se)},{label:"p95",value:`${D.p95??0} ms`},...D.provisioned?[{label:"Provisioned",value:J(D.provisioned)}]:[]],href:"/serverless/functions"})}for(let D of c){let Y=`queue:${J(D.name)}`;if(!J(D.name))continue;let se=Number(D.dlq??0);r.push({id:Y,label:J(D.name),kind:"queue",layer:5,status:se>0?"bad":Number(D.visible??0)>0?"warn":"ok",sub:"SQS",facts:[{label:"Visible",value:String(D.visible??0)},{label:"In flight",value:String(D.inFlight??0)},{label:"Processed (24h)",value:String(D.processed??0)},{label:"Dead letter",value:String(se)}],href:"/serverless/queues"})}let w=e.aurora;if(w)r.push({id:"database",label:"Aurora Serverless",kind:"database",layer:6,status:Qt(w.status),sub:J(w.engine,"aurora"),facts:[{label:"Cluster",value:J(w.id,"unknown")},{label:"Capacity",value:`${w.currentAcu??0} ACU (${w.minAcu??0}–${w.maxAcu??0})`},{label:"Connections",value:String(w.connections??0)}],href:"/serverless/data"});let k=e.proxy;if(k)r.push({id:"rds-proxy",label:"RDS Proxy",kind:"database",layer:5,status:Qt(k.status),sub:"Connection pooling",facts:[{label:"Proxy",value:J(k.name,"unknown")},{label:"Endpoint",value:J(k.endpoint,"unknown")},{label:"Pooled",value:String(k.pooledConns??0)}],href:"/serverless/data"});let C=e.redis;if(C)r.push({id:"cache",label:"ElastiCache",kind:"cache",layer:6,status:Qt(C.status),sub:J(C.node,"redis"),facts:[{label:"Group",value:J(C.id,"unknown")},{label:"Hit rate",value:`${C.hitRate??0}%`}],href:"/serverless/data"});let T=e.efs;if(T)r.push({id:"efs",label:"EFS",kind:"filesystem",layer:6,status:Qt(T.status),sub:J(T.mount,"/mnt/local"),facts:[{label:"File system",value:J(T.id,"unknown")},{label:"Mount",value:J(T.mount,"unknown")},{label:"Size",value:`${T.sizeMb??0} MB`}],href:"/data/volumes"});let j=e.scheduler??{};if(j.enabled)r.push({id:"scheduler",label:"Scheduler",kind:"scheduler",layer:3,status:"ok",sub:J(j.expression,"rate(1 minute)"),facts:[{label:"Expression",value:J(j.expression,"unknown")},{label:"Last run",value:J(j.lastRun,"unknown")}],href:"/operations/jobs"});let P=new Set(r.map((D)=>D.id)),O=P.has("waf")?"waf":"gateway";Ue(n,{source:"internet",target:"dns",flow:"request",label:"https"},P),Ue(n,{source:"dns",target:O,flow:"request"},P),Ue(n,{source:"dns",target:"cdn",flow:"request",label:"assets"},P),Ue(n,{source:"waf",target:"gateway",flow:"request",label:"allowed"},P),Ue(n,{source:"cdn",target:"assets",flow:"data",label:"origin"},P);let U=s.filter((D)=>J(D.key).startsWith("http")),q=s.filter((D)=>J(D.key).startsWith("queue")),N=s.filter((D)=>J(D.key).startsWith("cli"));for(let D of U)Ue(n,{source:"gateway",target:`fn:${J(D.name)}`,flow:"request",label:"invoke"},P);for(let D of N)Ue(n,{source:"scheduler",target:`fn:${J(D.name)}`,flow:"async",label:"schedule"},P);for(let D of c){for(let Y of U)Ue(n,{source:`fn:${J(Y.name)}`,target:`queue:${J(D.name)}`,flow:"async",label:"publish"},P);for(let Y of q)Ue(n,{source:`queue:${J(D.name)}`,target:`fn:${J(Y.name)}`,flow:"async",label:"consume"},P)}let Q=["rds-proxy","database","cache","efs","assets"];for(let D of s){let Y=`fn:${J(D.name)}`;if(P.has("rds-proxy"))Ue(n,{source:Y,target:"rds-proxy",flow:"data",label:"pooled"},P);else Ue(n,{source:Y,target:"database",flow:"data",label:"sql"},P);for(let se of Q.filter((he)=>he!=="rds-proxy"&&he!=="database"))Ue(n,{source:Y,target:se,flow:"data"},P)}return Ue(n,{source:"rds-proxy",target:"database",flow:"data",label:"sql"},P),{mode:"serverless",project:J(t.project)||J(o.name,"application"),environment:J(t.environment)||J(o.env,"production"),provider:"aws",region:J(o.region,"unknown"),generatedAt:new Date().toISOString(),layers:rw,groups:[],nodes:r,links:n,notes:i}}function sw(e,t,r={}){return e==="serverless"?cs(t,r):Pn(t,r)}function Yp(e){return String(e).padStart(2,"0")}function gi(e){return`${e.getUTCFullYear()}-${Yp(e.getUTCMonth()+1)}-${Yp(e.getUTCDate())}`}function aw(e){let t=Math.max(0,Math.round((Date.now()-e)/1000));if(t<60)return`${t}s ago`;let r=Math.round(t/60);if(r<60)return`${r}m ago`;let n=Math.round(r/60);if(n<48)return`${n}h ago`;return`${Math.round(n/24)}d ago`}async function ro(e,t,r,n,i,o){let s=await e.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:r,Dimensions:[{Name:"FunctionName",Value:t}],StartTime:i,EndTime:o,Period:86400,Statistics:[n]}).catch(()=>[]);if(!s.length)return 0;if(n==="Sum")return s.reduce((c,d)=>c+(d.Sum??0),0);if(n==="Maximum")return Math.max(...s.map((c)=>c.Maximum??0));return s.reduce((c,d)=>c+(d.Average??0),0)/s.length}async function no(e,t,r,n,i,o,s){let c=await e.getMetricStatistics({Namespace:t,MetricName:r,Dimensions:n,StartTime:o,EndTime:s,Period:86400,Statistics:[i]}).catch(()=>[]);if(!c.length)return 0;if(i==="Sum")return c.reduce((d,a)=>d+(a.Sum??0),0);if(i==="Maximum")return Math.max(...c.map((d)=>d.Maximum??0));return c.reduce((d,a)=>d+(a.Average??0),0)/c.length}async function bc(e,t,r,n,i){let o=await e.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"Duration",Dimensions:[{Name:"FunctionName",Value:t}],StartTime:n,EndTime:i,Period:86400,ExtendedStatistics:[r]}).catch(()=>[]);return Math.round(o.reduce((s,c)=>s+(c.Percentiles?.[r]??0),0))}async function io(e,t){let r=await nt(e,t),n=r.region,i=new Rr(n),o=new kt(n),s=new di(n),c=new Date,d=new Date(c.getTime()-86400000),a=e.environments?.[t]?.app,u={};u.app={name:r.slug,env:t,region:n,runtime:a?.kind==="php"?`php-${a?.phpVersion??"8.3"} (fpm)`:a?.kind??"node",url:r.endpoint??"",build:r.lastRelease?.sha?.slice(0,7)??"—",deployedAt:r.lastRelease?.timestamp??"—"},u.maintenance={enabled:!1},u.scheduler={enabled:r.scheduler!=="off",expression:r.scheduler==="sub-minute"?"rate(1 minute) · sub-minute":"rate(1 minute)",lastRun:"—"};let m=0,h=0,y=0,w=[],k=[],C=[];for(let O of r.functions){let[U,q,N,Q,D,Y,se,he,je]=await Promise.all([ro(i,O.name,"Invocations","Sum",d,c),ro(i,O.name,"Errors","Sum",d,c),ro(i,O.name,"Throttles","Sum",d,c),ro(i,O.name,"Duration","Average",d,c),o.getFunction(O.name).catch(()=>null),bc(i,O.name,"p50",d,c),bc(i,O.name,"p95",d,c),bc(i,O.name,"p99",d,c),i.getMetricSeries({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:[{Name:"FunctionName",Value:O.name}],StartTime:new Date(c.getTime()-43200000),EndTime:c,Period:3600,Stat:"Sum"}).catch(()=>[])]);m+=U,h+=q,y=Math.max(y,Q);let de=D?.Configuration?.MemorySize??0,Re=Object.keys(D?.Configuration?.Environment?.Variables??{}),Me=[],me=0;try{let{events:M=[]}=await s.filterLogEvents({logGroupName:`/aws/lambda/${O.name}`,startTime:d.getTime(),limit:120});for(let F of M){let K=(F.message??"").trim(),ye=/Max Memory Used:\s*(\d+)\s*MB/.exec(K);if(ye)me=Math.max(me,Number(ye[1]));if(K&&!/^(?:START|END|REPORT|INIT_START)/.test(K))C.push({source:O.mode||O.name,timestamp:new Date(F.timestamp??0).toISOString(),when:aw(F.timestamp??0),message:K.slice(0,400),level:/error|exception|fatal|panic|traceback/i.test(K)?"error":/warn|warning|timeout|retr(?:y|ies)|throttl/i.test(K)?"warn":"info"})}Me=M.filter((F)=>!/^(?:START|END|REPORT|INIT_START)/.test((F.message??"").trim())).slice(-6).map((F)=>({ts:new Date(F.timestamp??0).toISOString().slice(11,19),msg:(F.message??"").trim().slice(0,120),err:/error|exception|fatal/i.test(F.message??"")}))}catch{}let R=Math.max(1,...je);w.push({key:O.mode,name:O.name,version:O.version,memory:de,timeout:D?.Configuration?.Timeout??0,runtime:D?.Configuration?.Runtime??"provided.al2023",invocations:Math.round(U),errors:Math.round(q),p95:se||Math.round(Q),status:"active",provisioned:O.provisioned?`${O.provisioned.allocated}/${O.provisioned.requested}`:void 0}),k.push({key:O.mode,name:O.name,runtime:D?.Configuration?.Runtime??"provided.al2023",arch:D?.Configuration?.Architectures?.[0]??"x86_64",memory:de,timeout:D?.Configuration?.Timeout??0,ephemeral:D?.Configuration?.EphemeralStorage?.Size??512,version:O.version,concurrency:a?.concurrency??"—",invocations:Math.round(U),errors:Math.round(q),throttles:Math.round(N),p50:Y||Math.round(Q),p95:se||Math.round(Q),p99:he||Math.round(Q),maxMem:me,spark:je.length?je.map((M)=>Math.round(M/R*100)):[0],env:Re.length?Re:["(none)"],recent:Me.length?Me:[{ts:"—",msg:"no recent events",err:!1}]})}u.functions=w,u.functionsDetail=k,u.serverlessLogs=C.sort((O,U)=>String(U.timestamp).localeCompare(String(O.timestamp))).slice(0,600),u.serverlessLogsEmptyReason=C.length?void 0:"No recent function logs were found in CloudWatch for this environment.";let T=m?Number((h/m*100).toFixed(2)):0,j=Math.round(await ro(i,r.functions[0]?.name??"","ConcurrentExecutions","Maximum",d,c));u.metrics={invocations:Math.round(m),errorRatePct:T,p95Ms:Math.round(y),coldStartPct:void 0,concurrency:j,estCostUsd:void 0};try{let O=new _n(n),U=[],q=[],N=0;try{let{QueueUrl:D}=await O.getQueueUrl(`${r.slug}-${t}-dlq`),{Attributes:Y}=await O.getQueueAttributes(D);N=Number(Y.ApproximateNumberOfMessages??0)}catch{}let Q=a?ds(a,r.slug,t):[];for(let D of Q){let Y=D.name.replace(`${r.slug}-${t}-`,""),se=0,he=0;try{let{QueueUrl:de}=await O.getQueueUrl(D.name),{Attributes:Re}=await O.getQueueAttributes(de);se=Number(Re.ApproximateNumberOfMessages??0),he=Number(Re.ApproximateNumberOfMessagesNotVisible??0)}catch{}let je=Math.round(await no(i,"AWS/SQS","NumberOfMessagesDeleted",[{Name:"QueueName",Value:D.name}],"Sum",d,c));U.push({name:Y,visible:se,inFlight:he,processed:je,dlq:N}),q.push({name:D.name,short:Y,visible:se,inFlight:he,delayed:0,processed:je,oldestSec:0,concurrency:D.concurrency??a?.queueConcurrency??"—",tries:a?.queueTries??3,visTimeout:(a?.queueTimeout??120)*6,dlq:N})}if(U.length)u.queues=U;if(q.length)u.queuesDetail=q;u.dlqItems=[]}catch{}try{let O=new Er(n),{Stacks:U}=await O.describeStacks({stackName:ui(e,t)}),q={};for(let N of U?.[0]?.Outputs??[])if(N.OutputKey)q[N.OutputKey]=N.OutputValue??"";if(a?.database?.connection==="aurora-serverless"){let N=`${r.slug}-${t}-db`,Q=[{Name:"DBClusterIdentifier",Value:N}],[D,Y]=await Promise.all([no(i,"AWS/RDS","ServerlessDatabaseCapacity",Q,"Average",d,c),no(i,"AWS/RDS","DatabaseConnections",Q,"Maximum",d,c)]);if(u.aurora={id:N,engine:"aurora-mysql",minAcu:a?.database?.minCapacity??0.5,maxAcu:a?.database?.maxCapacity??4,currentAcu:D?Number(D.toFixed(1)):a?.database?.minCapacity??0.5,database:"app",connections:Math.round(Y),status:q.DbEndpoint?"available":"creating"},a?.rdsProxy)u.proxy={name:`${r.slug}-${t}-proxy`,endpoint:q.DbProxyEndpoint??"—",pooledConns:Math.round(Y),status:"available"}}if(a?.cache?.driver==="elasticache"){let N=`${r.slug}-${t}-cache`,Q=[{Name:"CacheClusterId",Value:`${N}-001`}],[D,Y]=await Promise.all([no(i,"AWS/ElastiCache","CacheHits",Q,"Sum",d,c),no(i,"AWS/ElastiCache","CacheMisses",Q,"Sum",d,c)]),se=D+Y>0?Number((D/(D+Y)*100).toFixed(1)):0;u.redis={id:N,node:"cache.t4g.micro",engine:"redis",hitRate:se,status:q.CacheEndpoint?"available":"creating"}}if(a?.efs){let N=0;try{if(q.EfsFileSystemId){let Q=new Xp(n),{FileSystems:D}=await Q.describeFileSystems({FileSystemId:q.EfsFileSystemId});N=Number(((D?.[0]?.SizeInBytes?.Value??0)/1048576).toFixed(1))}}catch{}u.efs={id:q.EfsFileSystemId??"efs",mount:"/mnt/local",sizeMb:N,status:"available"}}u.assetsInfo=q.AssetsCdnDomain?{bucket:q.AssetsBucketName??`${r.slug}-${t}-assets`,cdn:q.AssetsCdnDomain,customDomain:a?.assetDomain??"—",assetUrl:r.assetUrl??"—",files:0,sizeMb:0,cacheHitPct:0,build:u.app.build}:void 0}catch{}if(u.assetsInfo)try{let U=await new ur(n).list({bucket:u.assetsInfo.bucket,maxKeys:1000});u.assetsInfo.files=U.length,u.assetsInfo.sizeMb=Number((U.reduce((q,N)=>q+(N.Size??0),0)/1048576).toFixed(1)),u.assetsRecent=U.slice(0,8).map((q)=>({path:`/${q.Key}`,size:`${Math.max(1,Math.round((q.Size??0)/1024))} KB`,type:q.Key.split(".").pop()??""}))}catch{}try{if(a?.secrets){let O=Array.isArray(a.secrets)?a.secrets.map((U)=>({key:U.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),source:U})):Object.entries(a.secrets).map(([U,q])=>({key:U,source:String(q)}));u.secretsList=O.map((U)=>({...U,updated:"—"}))}}catch{}try{let O=new ur(n),U=`${r.slug}-${t}-deployments`,q=await O.getObjectJson(U,`deployments/${r.slug}/${t}/history.json`).catch(()=>null);if(q?.records?.length)u.deploymentsDetail=q.records.slice(-12).reverse().map((N)=>({sha:(N.sha??"").slice(0,7),status:N.status??"success",when:N.timestamp??"—",took:N.took??"—",by:N.by??"—",version:N.version??"—",hooks:N.hooks??[]}))}catch{}u.metricsTotals={invocations:u.metrics.invocations,errors:Math.round(h),errorRatePct:T,p95Ms:u.metrics.p95Ms,throttles:k.reduce((O,U)=>O+U.throttles,0),coldStartPct:void 0,estCostUsd:void 0,concurrency:j},u.metricsPerFn=k.map((O)=>({key:O.key,invocations:O.invocations,errors:O.errors,throttles:O.throttles,avgMs:O.p50,maxMs:O.p99,costUsd:void 0}));try{u.invSpark=await i.getMetricSeries({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:[{Name:"FunctionName",Value:r.functions.find((O)=>O.mode==="http")?.name??""}],StartTime:new Date(c.getTime()-86400000),EndTime:c,Period:3600,Stat:"Sum"})}catch{}try{let O=new Zp,U=c,q=new Date(Date.UTC(U.getUTCFullYear(),U.getUTCMonth(),1)),N=new Date(Date.UTC(U.getUTCFullYear(),U.getUTCMonth()-1,1)),[Q,D]=await Promise.all([O.getCostByService({start:gi(q),end:gi(U),granularity:"MONTHLY"}).catch(()=>[]),O.getCostByService({start:gi(N),end:gi(q),granularity:"MONTHLY"}).catch(()=>[])]);if(Q.length){let Y=Q.reduce((me,R)=>me+R.amount,0),se=D.reduce((me,R)=>me+R.amount,0),he=U.getUTCDate(),je=new Date(Date.UTC(U.getUTCFullYear(),U.getUTCMonth()+1,0)).getUTCDate();u.costSummary={monthToDateUsd:Number(Y.toFixed(2)),projectedUsd:Number((Y/he*je).toFixed(2)),lastMonthUsd:Number(se.toFixed(2)),dailyAvgUsd:Number((Y/he).toFixed(2))},u.costServices=Q.filter((me)=>me.amount>0).sort((me,R)=>R.amount-me.amount).slice(0,12).map((me)=>({name:me.service,usd:Number(me.amount.toFixed(2)),note:""})),u.metrics.estCostUsd=Number((Y/he).toFixed(2)),u.metricsTotals.estCostUsd=u.metrics.estCostUsd,u.costTrend=await O.getDailyTotals({start:gi(q),end:gi(U)}).catch(()=>[]);let de=Q.find((me)=>/lambda/i.test(me.service))?.amount??0,Re=(me)=>me.invocations*(me.p50/1000)*(me.memory/1024),Me=k.reduce((me,R)=>me+Re(R),0)||1;u.costPerFn=k.map((me)=>({key:me.key,requests:me.invocations,gbSec:Math.round(Re(me)),usd:Number((de*(Re(me)/Me)).toFixed(2))}))}}catch{}if(a?.firewall)try{let O=await i.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"BlockedRequests",StartTime:d,EndTime:c,Period:86400,Statistics:["Sum"]}).catch(()=>[]),U=await i.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"AllowedRequests",StartTime:d,EndTime:c,Period:86400,Statistics:["Sum"]}).catch(()=>[]);u.waf={enabled:!0,scope:"REGIONAL",acl:`${r.slug}-${t}-waf`,allowed24h:Math.round(U.reduce((q,N)=>q+(N.Sum??0),0)),blocked24h:Math.round(O.reduce((q,N)=>q+(N.Sum??0),0))};try{let q=new vc(n),N=await q.listWebACLs("REGIONAL"),Q=N.find((D)=>D.Name?.includes(`${r.slug}-${t}`))??N[0];if(Q?.Name&&Q.Id){u.waf.acl=Q.Name;let D=await q.getWebACLRules(Q.Name,Q.Id,"REGIONAL");if(D.length)u.wafRules=D.map((Y)=>({name:Y.Name??"—",detail:`priority ${Y.Priority??0}`,action:Y.Action??"count",blocked24h:0}))}}catch{}}catch{}let P=[];if(u.aurora)P.push({name:"Aurora Serverless v2",detail:`${u.aurora.id} · ${u.aurora.minAcu}-${u.aurora.maxAcu} ACU`,status:u.aurora.status});if(u.proxy)P.push({name:"RDS Proxy",detail:u.proxy.name,status:u.proxy.status});if(u.redis)P.push({name:`ElastiCache (${u.redis.engine})`,detail:`${u.redis.node} · ${u.redis.hitRate}% hit rate`,status:u.redis.status});if(u.efs)P.push({name:"EFS",detail:`${u.efs.mount} · ${u.efs.sizeMb} MB`,status:u.efs.status});if(P.length)u.dataServices=P;if(r.scheduler!=="off"&&a?.kind==="php")try{let O=await pi(e,t,"schedule:list"),U=[];for(let q of(O||"").split(`
|
|
16
|
+
`)){let N=/^\s*([\d*/,\-\s]+?)\s{2,}(.+?)(?:\s{2,}Next Due.*)?$/.exec(q);if(N&&/[*\d]/.test(N[1])&&N[1].trim().split(/\s+/).length===5)U.push({command:N[2].trim().replace(/^php artisan /,""),cron:N[1].trim(),desc:"",lastRun:"—",lastStatus:"ok"})}if(U.length)u.schedulerTasks=U}catch{}return u.topology=cs(u,{project:e.project.name,environment:t}),u}function Zr(e){let t=Number(e);return Number.isFinite(t)&&t>=0?t:null}function cw(e){if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return null;let t=Date.parse(`${e}T12:00:00.000Z`);return Number.isFinite(t)?new Date(t).toISOString():null}function em(e,t){if(!e||typeof e!=="object")return[];let r={source:t.name},n=[],i=t.now,o=(a,u,m,h=i)=>{if(u!==null)n.push({name:a,value:u,unit:m,timestamp:h,attributes:r})};o("storage.egress.month",Zr(e.monthBytes),"bytes"),o("storage.egress.today",Zr(e.todayBytes),"bytes"),o("storage.egress.projected_month",Zr(e.projectedMonthBytes),"bytes");let s=Zr(e.budgetBytes);if(s!==null&&s>0){o("storage.egress.budget",s,"bytes");let a=e.budgetUsedPercent,u=typeof a==="number"&&Number.isFinite(a)?a:Zr(e.monthBytes)!==null?Math.round(Zr(e.monthBytes)/s*1000)/10:null;o("storage.egress.budget_used_percent",u,"percent")}let c=t.maxReplayDays??45,d=Array.isArray(e.days)?e.days.slice(-c):[];for(let a of d){let u=cw(String(a?.date??"")),m=Zr(a?.bytes);if(!u||m===null)continue;n.push({name:"storage.egress.day",value:m,unit:"bytes",timestamp:u,attributes:r});let h=Zr(a?.downloads);if(h!==null)n.push({name:"storage.egress.day_downloads",value:h,unit:"count",timestamp:u,attributes:r})}return n}async function tm(e,t=process.env,r=fetch){let n=e.tokenEnv?t[e.tokenEnv]:void 0,i=await r(e.url,{headers:n?{Authorization:`Bearer ${n}`}:{},signal:AbortSignal.timeout(1e4)});if(!i.ok)throw Error(`HTTP ${i.status}`);return await i.json()}async function Sc(e,t){let r=[],n=[];if(!Array.isArray(e)||e.length===0)return{metrics:r,errors:n};let i=await Promise.all(e.map(async(o)=>{if(!o?.name||!o?.url)return{endpoint:o,error:"egress endpoint needs both a name and a url"};try{let s=await tm(o,t.env,t.fetchImpl);return{endpoint:o,report:s}}catch(s){return{endpoint:o,error:s instanceof Error?s.message:String(s)}}}));for(let o of i){let s=`egress:${o.endpoint?.name??"unnamed"}`;if("error"in o&&o.error){n.push({source:s,message:o.error});continue}r.push(...em(o.report,{name:o.endpoint.name,now:t.now}))}return{metrics:r,errors:n}}import{createHash as n_}from"node:crypto";import{existsSync as qr,mkdtempSync as Vu,readdirSync as bb,rmSync as ri,statSync as Kb}from"node:fs";import{readFile as br,writeFile as ei}from"node:fs/promises";import{tmpdir as ic}from"node:os";import{dirname as i_,extname as Ho,join as Te,normalize as o_,relative as s_,resolve as a_,sep as c_}from"node:path";import{fileURLToPath as d_}from"node:url";class wc extends Error{status;code;requestId;constructor(e,t,r,n){super(r);this.status=e;this.code=t;this.requestId=n}}class rm{options;baseUrl;fetchFn;constructor(e){this.options=e;this.baseUrl=e.baseUrl.replace(/\/$/,""),this.fetchFn=e.fetch??fetch}async request(e,t={}){let r=await this.fetchFn(`${this.baseUrl}${e}`,{...t,headers:{accept:"application/json",authorization:`Bearer ${this.options.token}`,...t.headers}}),n=await r.json().catch(()=>({}));if(!r.ok)throw new wc(r.status,n.error?.code??"api_error",n.error?.message??"API request failed.",n.error?.requestId??r.headers.get("x-request-id")??void 0);return n}listProjects(e={}){return this.request(`/api/v1/projects?${new URLSearchParams(Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).map(([t,r])=>[t,String(r)])))}`)}listEnvironments(e,t={}){return this.request(`/api/v1/projects/${encodeURIComponent(e)}/environments?${new URLSearchParams(Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0).map(([r,n])=>[r,String(n)])))}`)}listServices(e,t){return this.request(`/api/v1/services?${new URLSearchParams({projectId:e,...t?{environmentId:t}:{}})}`)}listOperations(e){return this.request(`/api/v1/operations${e?`?projectId=${encodeURIComponent(e)}`:""}`)}listComposeTemplates(){return this.request("/api/v1/compose-templates")}listComposeApplications(e,t){return this.request(`/api/v1/compose-applications?${new URLSearchParams({projectId:e,...t?{environmentId:t}:{}})}`)}previewCompose(e){return this.request("/api/v1/compose-applications/preview",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}createComposeApplication(e){return this.request("/api/v1/compose-applications",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}composeServices(e){return this.request(`/api/v1/compose-applications/${encodeURIComponent(e)}/services`)}composeAction(e,t,r={}){return this.request(`/api/v1/compose-applications/${encodeURIComponent(e)}/${t}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r)})}releaseCapabilities(e,t={}){return this.request(`/api/v1/releases/capabilities?${new URLSearchParams({kind:e,health:String(!!t.health),replicas:String(t.replicas??1)})}`)}listReleases(e,t={}){return this.request(`/api/v1/releases?${new URLSearchParams({projectId:e,...t})}`)}createReleaseArtifact(e){return this.request("/api/v1/release-artifacts",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}createRelease(e){return this.request("/api/v1/releases",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}releaseAction(e,t,r={}){return this.request(`/api/v1/releases/${encodeURIComponent(e)}/${t}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r)})}createDeployment(e,t){return this.request("/api/v1/deployments",{method:"POST",headers:{"content-type":"application/json","idempotency-key":t},body:JSON.stringify(e)})}detectApplication(e){return this.request("/api/v1/application-detections",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}planApplication(e){return this.request("/api/v1/application-plans",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}listApplicationDrafts(e){return this.request(`/api/v1/application-drafts?projectId=${encodeURIComponent(e)}`)}createApplicationDraft(e){return this.request("/api/v1/application-drafts",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}updateApplicationDraft(e){return this.request("/api/v1/application-drafts",{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}createApplication(e,t){return this.request("/api/v1/applications",{method:"POST",headers:{"content-type":"application/json","idempotency-key":t},body:JSON.stringify(e)})}uploadApplicationArtifact(e,t,r){return this.request("/api/v1/application-artifacts",{method:"POST",headers:{"content-type":"application/octet-stream","x-project-id":e,"x-artifact-filename":t},body:r})}listRegistryConnections(){return this.request("/api/v1/registry-connections")}createRegistryConnection(e){return this.request("/api/v1/registry-connections",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}updateRegistryConnection(e){return this.request("/api/v1/registry-connections",{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}disconnectRegistryConnection(e){return this.request("/api/v1/registry-connections",{method:"DELETE",headers:{"content-type":"application/json"},body:JSON.stringify({id:e})})}listQueue(e={}){let t=new URLSearchParams(Object.entries(e).filter(([,r])=>r!==void 0).map(([r,n])=>[r,String(n)]));return this.request(`/api/v1/queue?${t}`)}operationLogs(e,t={}){let r=new URLSearchParams(Object.entries(t).filter(([,n])=>n!==void 0).map(([n,i])=>[n,String(i)]));return this.request(`/api/v1/operations/${encodeURIComponent(e)}/logs?${r}`)}streamOperationLogs(e,t=0){return this.fetchFn(`${this.baseUrl}/api/v1/operations/${encodeURIComponent(e)}/logs/stream`,{headers:{accept:"text/event-stream",authorization:`Bearer ${this.options.token}`,"last-event-id":String(t)}})}cancelOperation(e){return this.request(`/api/v1/operations/${encodeURIComponent(e)}/cancel`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"})}retryOperation(e,t,r=0){return this.request(`/api/v1/operations/${encodeURIComponent(e)}/retry`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({errorClass:t,delayMs:r})})}queueSettings(){return this.request("/api/v1/queue/settings")}updateQueueSettings(e){return this.request("/api/v1/queue/settings",{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({confirm:"update queue limits",concurrency:e})})}listPreviews(e){return this.request(`/api/v1/previews${e?`?projectId=${encodeURIComponent(e)}`:""}`)}listPreviewDefinitions(e){return this.request(`/api/v1/preview-definitions?projectId=${encodeURIComponent(e)}`)}createPreviewDefinition(e){return this.request("/api/v1/preview-definitions",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}createPreview(e){return this.request("/api/v1/previews",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}destroyPreview(e,t){return this.request(`/api/v1/previews/${encodeURIComponent(e)}/destroy`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({confirm:t})})}extendPreview(e,t){return this.request(`/api/v1/previews/${encodeURIComponent(e)}/extend`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({hours:t})})}rebuildPreview(e){return this.request(`/api/v1/previews/${encodeURIComponent(e)}/rebuild`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"})}usage(e={}){let t=new URLSearchParams;for(let[r,n]of Object.entries(e))if(n)t.set(r,String(n));return this.request(`/api/v1/usage${t.size>0?`?${t}`:""}`)}usageRollups(e){let t=new URLSearchParams({from:e.from,to:e.to});if(e.projectId)t.set("projectId",e.projectId);if(e.environmentId)t.set("environmentId",e.environmentId);if(e.limit)t.set("limit",String(e.limit));for(let r of e.meters??[])t.append("meter",r);return this.request(`/api/v1/usage/rollups?${t}`)}allowance(e="deploy",t={}){let r=new URLSearchParams({operation:e});if(t.projectId)r.set("projectId",t.projectId);if(t.environmentId)r.set("environmentId",t.environmentId);return this.request(`/api/v1/spend/allowance?${r}`)}budgets(e={}){let t=new URLSearchParams;for(let[r,n]of Object.entries(e))if(n)t.set(r,String(n));return this.request(`/api/v1/spend/budgets${t.size>0?`?${t}`:""}`)}anomalies(e={}){let t=new URLSearchParams;if(e.projectId)t.set("projectId",e.projectId);if(e.since)t.set("since",e.since);if(e.unacknowledged)t.set("unacknowledged","true");return this.request(`/api/v1/spend/anomalies${t.size>0?`?${t}`:""}`)}}import{createHash as ek}from"node:crypto";import{lstatSync as dw,readdirSync as lw,readFileSync as uw}from"node:fs";import{relative as pw,resolve as nm,sep as mw}from"node:path";function gw(e){return new Map(e.map((t)=>[t.path.replace(/^\.\//,"").replace(/\\/g,"/"),t]))}function Tn(e,t,r){return{path:e,reason:t,weight:r}}function im(e){try{return e?.content?JSON.parse(e.content):{}}catch{return{}}}function fi(e,t,r,n,i,o){return{framework:e,strategy:t,confidence:r,evidence:n,defaults:{build:i,runtime:{target:t==="static"?"serverless":t==="serverless"?"serverless":t==="dockerfile"||t==="prebuilt_image"?"container":"server",architecture:"x86_64",port:t==="static"||t==="serverless"?void 0:3000,healthCheck:t==="static"?void 0:{protocol:"http",path:"/health"}}},description:o}}function hi(e){let t=gw(e.slice(0,1e4)),r=[];if(t.has("Dockerfile"))r.push(fi("dockerfile","dockerfile",0.99,[Tn("Dockerfile","A root Dockerfile defines an explicit reproducible build.",1)],{kind:"dockerfile",context:".",dockerfile:"Dockerfile"},"Build the repository with its Dockerfile and run the resulting OCI image."));let n=im(t.get("composer.json"));if(t.has("artisan")&&n.require?.["laravel/framework"])r.push(fi("laravel","server",0.98,[Tn("artisan","Laravel Artisan entrypoint is present.",0.45),Tn("composer.json","Requires laravel/framework.",0.55)],{kind:"server",runtime:"php",runtimeVersion:"8.3",installCommand:"composer install --no-dev --prefer-dist --optimize-autoloader",buildCommand:"php artisan config:cache && php artisan route:cache && php artisan view:cache",startCommand:"php artisan serve --host=0.0.0.0 --port=$PORT"},"Install a production Composer tree, warm Laravel caches, and run the HTTP application."));else if(t.has("composer.json"))r.push(fi("php","server",0.82,[Tn("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=im(t.get("package.json"));if(t.has("package.json")){let o=t.has("bun.lock")||t.has("bun.lockb")||i.engines?.bun,s=o?"bun":"node",c=o?"bun":"node",d=[Tn("package.json",`Defines ${i.scripts?.build?"build and ":""}${i.scripts?.start?"start ":""}scripts.`,0.55)];if(o)d.push(Tn(t.has("bun.lock")?"bun.lock":t.has("bun.lockb")?"bun.lockb":"package.json","Pins the Bun package manager/runtime.",0.35));let a=!!(i.dependencies?.vite||i.devDependencies?.vite||i.dependencies?.["@stacksjs/bunpress"]||i.devDependencies?.["@stacksjs/bunpress"])&&!i.scripts?.start,u=a?{kind:"static",installCommand:`${s} install --frozen-lockfile`,buildCommand:`${s} run build`,publishDirectory:"dist"}:{kind:"server",runtime:s,installCommand:`${s} install --frozen-lockfile`,buildCommand:i.scripts?.build?`${s} run build`:void 0,startCommand:i.scripts?.start?`${s} run start`:s==="bun"?"bun run index.ts":"node index.js"};r.push(fi(c,u.kind,Math.min(0.94,d.reduce((m,h)=>m+h.weight,0)),d,u,a?"Install dependencies, build static assets, and publish the output directory.":`Install dependencies, build if configured, and start the ${s} server.`))}if(!r.length&&(t.has("index.html")||t.has("public/index.html")))r.push(fi("static","static",0.78,[Tn(t.has("index.html")?"index.html":"public/index.html","A static HTML entrypoint is present.",0.78)],{kind:"static",publishDirectory:t.has("index.html")?".":"public"},"Publish the static directory without a runtime process."));if(!r.length)r.push(fi("unknown","buildpack",0.2,[],{kind:"buildpack",runtime:"node"},"No supported framework signature was conclusive; choose commands and runtime manually."));return r.sort((o,s)=>s.confidence-o.confidence||o.framework.localeCompare(s.framework))}function kc(e,t={}){let r=nm(e),n=t.maxFiles??1e4,i=t.maxContentBytes??262144,o=[],s=new Set(["Dockerfile","package.json","composer.json","index.html","public/index.html","bun.lock","bun.lockb","artisan"]),c=new Set([".git",".ts-cloud",".cache",".next",".nuxt",".output",".turbo",".bun","node_modules","vendor","pantry","dist","build","coverage"]),d=(a)=>{for(let u of lw(a).sort()){if(c.has(u))continue;let m=nm(a,u),h=pw(r,m).split(mw).join("/");if(!h||h.startsWith("../"))throw Error("Detection path escaped the application root");let y=dw(m);if(y.isSymbolicLink())throw Error(`Detection refuses symbolic links: ${h}`);if(y.isDirectory())d(m);else if(y.isFile()){if(o.length>=n)throw Error("Application file-count limit exceeded");let w={path:h,size:y.size};if(s.has(h)&&y.size<=i)w.content=uw(m,"utf8");o.push(w)}}};return d(r),o}function Ec(e){if(Array.isArray(e))return`[${e.map(Ec).join(",")}]`;if(e&&typeof e==="object")return`{${Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>`${JSON.stringify(t)}:${Ec(r)}`).join(",")}}`;return JSON.stringify(e)??"null"}function oo(e){return!!e&&!e.startsWith("/")&&!e.split("/").includes("..")&&!/[\0\r\n]/.test(e)}function Dt(e,t,r,n){return{path:e,code:t,message:r,alternatives:n}}function Ic(e){return JSON.parse(JSON.stringify(e))}function fw(e){let t=Object.fromEntries(Object.entries(e.environment??{}).map(([r,n])=>[r,typeof n==="string"?n:`\${${n.secretRef}}`]));if(e.build.kind==="prebuilt_image"||e.build.kind==="dockerfile")return Ic({infrastructure:{containers:{[e.slug]:{source:e.source,build:e.build,port:e.runtime.port,cpu:e.runtime.cpu,memory:e.runtime.memoryMb,architecture:e.runtime.architecture,healthCheck:e.runtime.healthCheck,environment:t}}}});if(e.runtime.target==="serverless"||e.build.kind==="serverless")return Ic({serverless:{apps:{[e.slug]:{source:e.source,build:e.build,architecture:e.runtime.architecture,environment:t,domain:e.domain}}}});return Ic({sites:{[e.slug]:{source:e.source,build:e.build,port:e.runtime.port,architecture:e.runtime.architecture,healthCheck:e.runtime.healthCheck,env:t,domain:e.domain?.hostname}}})}function Yt(e,t=[]){let r=[],n=(w)=>/(?:secret|token|password|passwd|private[_-]?key|api[_-]?key)/i.test(w),i=Object.fromEntries(Object.entries(e.environment??{}).map(([w,k])=>{if(typeof k==="string"&&n(w))return r.push(Dt(`environment.${w}`,"write_only_secret_required",`${w} must be supplied through the write-only secrets boundary.`)),[w,{secretRef:w}];return[w,k]})),o=e.build;if(e.build.kind==="dockerfile"&&e.build.buildArgs){let w=Object.fromEntries(Object.entries(e.build.buildArgs).map(([k,C])=>{if(n(k))return r.push(Dt(`build.buildArgs.${k}`,"write_only_build_secret_required",`${k} must be declared in secretNames instead of buildArgs.`)),[k,"[REDACTED]"];return[k,C]}));o={...e.build,buildArgs:w}}if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(e.slug))r.push(Dt("slug","invalid_slug","Slug must contain 2-63 lowercase letters, numbers, or hyphens."));if(!oo((e.source.kind==="git"?e.source.monorepoRoot:e.source.kind==="local"?e.source.root:".")??"."))r.push(Dt("source","unsafe_source_root","Source root must stay inside the source tree."));if(e.source.kind==="git"&&e.source.sparsePaths?.some((w)=>!oo(w)))r.push(Dt("source.sparsePaths","unsafe_sparse_path","Sparse checkout paths must stay inside the repository."));if(e.build.kind==="dockerfile"&&(!oo(e.build.context)||!oo(e.build.dockerfile)))r.push(Dt("build","unsafe_docker_path","Docker context and Dockerfile must stay inside the source tree."));if(e.build.kind==="static"&&!oo(e.build.publishDirectory))r.push(Dt("build.publishDirectory","invalid_publish_directory","A safe static publish directory is required."));if(e.build.kind==="server"&&!e.build.startCommand.trim())r.push(Dt("build.startCommand","missing_start_command","A server start command is required.",["Use static output","Use a Dockerfile"]));if(e.source.kind==="image"&&e.build.kind!=="prebuilt_image")r.push(Dt("build.kind","image_requires_prebuilt","An OCI image source must use the prebuilt-image strategy.",["Select prebuilt image"]));if(e.build.kind==="prebuilt_image"&&e.runtime.target!=="container")r.push(Dt("runtime.target","image_requires_container","Prebuilt images require the container runtime target.",["Select container target"]));if(e.runtime.target==="serverless"&&e.build.kind==="dockerfile")r.push(Dt("runtime.target","unsupported_serverless_dockerfile","Dockerfile builds currently target the container service path.",["Select container target","Select serverless package"]));if(e.runtime.port!==void 0&&(!Number.isInteger(e.runtime.port)||e.runtime.port<1||e.runtime.port>65535))r.push(Dt("runtime.port","invalid_port","Port must be an integer from 1 to 65535."));let s=e.runtime.healthCheck;if(s&&s.protocol!=="tcp"&&(!s.path||!s.path.startsWith("/")||/[\r\n]/.test(s.path)))r.push(Dt("runtime.healthCheck.path","invalid_health_path","HTTP health checks require a path beginning with /."));if(e.domain?.hostname&&(!/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/i.test(e.domain.hostname)||e.domain.hostname.includes("..")))r.push(Dt("domain.hostname","invalid_domain","Domain must be a valid DNS hostname."));let c=Object.values(i).flatMap((w)=>typeof w==="object"?[w.secretRef]:[]),d=[...new Set([...e.requiredSecretNames??[],...e.build.kind==="dockerfile"?e.build.secretNames??[]:[],...c])].sort(),a=new Set(t),u=d.filter((w)=>!a.has(w)),m={apiVersion:"ts-cloud.dev/v1",kind:"Application",metadata:{name:e.name,slug:e.slug,projectId:e.projectId,environmentId:e.environmentId},spec:{source:e.source,build:o,runtime:e.runtime,environment:i,domain:e.domain}},h=[...new Set([e.source.kind==="git"?"git:read":e.source.kind==="image"?"registry:pull":e.source.kind==="artifact"?"artifact:inspect":"filesystem:read",e.runtime.target==="container"?"containers":e.runtime.target==="serverless"?"serverless":"servers",e.domain?"dns":""])].filter(Boolean).sort(),y=[...new Set([e.runtime.target,e.runtime.cpu?`${e.runtime.cpu} vCPU`:"",e.runtime.memoryMb?`${e.runtime.memoryMb} MB memory`:"",(e.runtime.minInstances??0)>0?`${e.runtime.minInstances} minimum instances`:"scales from zero where supported",e.domain?"managed DNS/TLS":""])].filter(Boolean);return{valid:r.length===0&&u.length===0,issues:r,missingSecrets:u,manifest:m,configPatch:fw({...e,build:o,environment:i}),capabilityRequirements:h,costDrivers:y,serializedManifest:`${Ec(m)}
|
|
17
|
+
`}}function om(e){let t=e.replace(/\\/g,"/");return!!t&&!t.startsWith("/")&&!/^[A-Za-z]:\//.test(t)&&!t.split("/").includes("..")&&!/[\0\r\n]/.test(t)}function sm(e,t,r={}){let n=r.maxBytes??104857600,i=r.maxEntries??1e4,o=r.maxExpandedBytes??524288000;if(e.byteLength>n)throw Error("Archive exceeds the compressed size limit");let s=new DataView(e.buffer,e.byteOffset,e.byteLength),c=[],d=0;if(t.toLowerCase().endsWith(".zip")||e[0]===80&&e[1]===75){let u=0;while(u+30<=e.length){let m=s.getUint32(u,!0);if(m===33639248||m===101010256)break;if(m!==67324752)throw Error("Malformed ZIP local header");let h=s.getUint16(u+6,!0),y=s.getUint32(u+18,!0),w=s.getUint32(u+22,!0),k=s.getUint16(u+26,!0),C=s.getUint16(u+28,!0);if(h&8)throw Error("ZIP data descriptors are not accepted for uploaded artifacts");let T=new TextDecoder().decode(e.subarray(u+30,u+30+k));if(!om(T))throw Error(`Unsafe archive path: ${T}`);if(c.push(T),d+=w,c.length>i||d>o)throw Error("Archive expansion limit exceeded");u+=30+k+C+y}return{format:"zip",entries:c.length,expandedBytes:d,paths:c}}if(!t.toLowerCase().match(/\.(?:tar|tar\.gz|tgz)$/))throw Error("Only ZIP and uncompressed TAR artifacts are supported");let a=0;while(a+512<=e.length){let u=e.subarray(a,a+512);if(u.every((k)=>k===0))break;let m=(k,C)=>new TextDecoder().decode(u.subarray(k,k+C)).replace(/\0.*$/,""),h=`${m(345,155)}${m(345,155)?"/":""}${m(0,100)}`,y=Number.parseInt(m(124,12).trim()||"0",8),w=String.fromCharCode(u[156]??0);if(!om(h))throw Error(`Unsafe archive path: ${h}`);if(w==="1"||w==="2")throw Error(`Archive links are not accepted: ${h}`);if(!Number.isFinite(y)||y<0)throw Error("Malformed TAR entry size");if(c.push(h),d+=y,c.length>i||d>o)throw Error("Archive expansion limit exceeded");a+=512+Math.ceil(y/512)*512}return{format:"tar",entries:c.length,expandedBytes:d,paths:c}}var am=new Set(["source","build","runtime","environment","domain","review"]);function cm(e,t){try{return typeof e==="string"?JSON.parse(e):t}catch{return t}}function dm(e){return/(?:secret|token|password|passwd|private[_-]?key|api[_-]?key)/i.test(e)}function lm(e){for(let[r,n]of Object.entries(e.environment??{}))if(typeof n==="string"&&dm(r)&&n)throw Error(`${r} must be stored through the write-only secrets boundary`);if(e.build.kind==="dockerfile"){for(let[r,n]of Object.entries(e.build.buildArgs??{}))if(dm(r)&&n)throw Error(`${r} must be declared as a build secret name`)}let t=JSON.stringify(e);if(/https?:\/\/[^/@\s]+:[^/@\s]+@/i.test(t))throw Error("Drafts cannot contain credential-bearing URLs")}function um(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),schemaVersion:Number(e.schema_version),name:String(e.name),step:String(e.step),input:cm(e.input,{}),suppliedSecretNames:cm(e.supplied_secret_names,[]),status:String(e.status),version:Number(e.version),createdByActorId:e.created_by_actor_id?String(e.created_by_actor_id):void 0,createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}class Rc{controlPlane;nowFn;idFn;constructor(e,t={}){this.controlPlane=e;this.nowFn=t.now??(()=>new Date),this.idFn=t.id??(()=>crypto.randomUUID())}now(){return this.nowFn().toISOString()}create(e){if(lm(e.draft),e.draft.projectId!==e.projectId)throw Error("Draft project does not match its storage scope");let t=this.controlPlane.getProject(e.projectId);if(!t||t.organizationId!==e.organizationId)throw Error("Draft project was not found");let r=this.idFn(),n=this.now(),i=e.step??"source";if(!am.has(i))throw Error("Invalid draft step");let o=[...new Set(e.suppliedSecretNames??[])].sort(),s=Yt(e.draft,o).valid?"ready":"draft";return this.controlPlane.database.run("INSERT INTO application_drafts (id, organization_id, project_id, schema_version, name, step, input, supplied_secret_names, status, created_by_actor_id, created_at, updated_at) VALUES (?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?)",[r,e.organizationId,e.projectId,e.name.trim().slice(0,100),i,JSON.stringify(e.draft),JSON.stringify(o),s,e.actorId??null,n,n]),this.controlPlane.appendEvent({organizationId:e.organizationId,projectId:e.projectId,actorId:e.actorId,type:"application.draft.created",payload:{draftId:r,step:i,status:s,requiredSecretNames:e.draft.requiredSecretNames??[]}}),this.get(r)}get(e){let t=this.controlPlane.database.query("SELECT * FROM application_drafts WHERE id=?").get(e);return t?um(t):void 0}list(e){return this.controlPlane.database.query("SELECT * FROM application_drafts WHERE project_id=? ORDER BY updated_at DESC").all(e).map(um)}update(e,t,r){let n=this.get(e);if(!n||n.version!==t)throw Error(`Application draft ${e} changed since version ${t}`);if(!am.has(r.step))throw Error("Invalid draft step");if(r.draft.projectId!==n.projectId)throw Error("Draft project cannot be changed");lm(r.draft);let i=[...new Set(r.suppliedSecretNames??n.suppliedSecretNames)].sort(),o=Yt(r.draft,i).valid?"ready":"draft",s=this.now();if(this.controlPlane.database.run("UPDATE application_drafts SET name=?, step=?, input=?, supplied_secret_names=?, status=?, version=version+1, updated_at=? WHERE id=? AND version=?",[r.draft.name.slice(0,100),r.step,JSON.stringify(r.draft),JSON.stringify(i),o,s,e,t]).changes!==1)throw Error(`Application draft ${e} changed since version ${t}`);return this.controlPlane.appendEvent({organizationId:n.organizationId,projectId:n.projectId,actorId:r.actorId,type:"application.draft.updated",payload:{draftId:e,fromVersion:t,toVersion:t+1,step:r.step,status:o}}),this.get(e)}markApplied(e,t,r){let n=this.get(e);if(!n||n.version!==t)throw Error(`Application draft ${e} changed since version ${t}`);let i=Yt(n.input,n.suppliedSecretNames);if(!i.valid)throw Error(`Draft is not deployable: ${[...i.issues.map((s)=>s.message),...i.missingSecrets.map((s)=>`Missing secret ${s}`)].join("; ")}`);let o=this.now();return this.controlPlane.database.run("UPDATE application_drafts SET status='applied', step='review', version=version+1, updated_at=? WHERE id=? AND version=?",[o,e,t]),this.controlPlane.appendEvent({organizationId:n.organizationId,projectId:n.projectId,actorId:r,type:"application.draft.applied",payload:Oe({draftId:e,manifest:i.manifest})}),this.get(e)}}import{createCipheriv as hw,createDecipheriv as yw,createHash as gm,randomBytes as vw}from"node:crypto";function so(e){return typeof e==="string"&&e?e:void 0}function Ac(e){return gm("sha256").update(e).digest("hex").slice(0,16)}function pm(e){let t=new URL(e.includes("://")?e:`https://${e}`);if(t.protocol!=="https:"&&!["localhost","127.0.0.1","::1"].includes(t.hostname))throw Error("Registry host must use HTTPS");if(t.username||t.password||t.search||t.hash)throw Error("Registry host cannot contain credentials");return`${t.protocol}//${t.host}`}function bw(e){return{id:String(e.id),organizationId:String(e.organization_id),provider:String(e.provider),name:String(e.name),host:String(e.host),credentialConfigured:!!e.credential_ciphertext,credentialFingerprint:so(e.credential_fingerprint),credentialExpiresAt:so(e.credential_expires_at),status:String(e.status),healthMessage:so(e.health_message),lastTestedAt:so(e.last_tested_at),version:Number(e.version),createdByActorId:so(e.created_by_actor_id),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}class Cc{controlPlane;key;nowFn;idFn;constructor(e,t){this.controlPlane=e;if(!t.encryptionKey)throw Error("Registry encryption key is required");this.key=gm("sha256").update(`ts-cloud:registry:${t.encryptionKey}`).digest(),this.nowFn=t.now??(()=>new Date),this.idFn=t.id??(()=>crypto.randomUUID())}now(){return this.nowFn().toISOString()}encrypt(e){let t=vw(12),r=hw("aes-256-gcm",this.key,t),n=Buffer.concat([r.update(e,"utf8"),r.final()]);return`v1.${t.toString("base64url")}.${r.getAuthTag().toString("base64url")}.${n.toString("base64url")}`}decrypt(e){let[t,r,n,i]=e.split(".");if(t!=="v1"||!r||!n||!i)throw Error("Registry credential envelope is invalid");let o=yw("aes-256-gcm",this.key,Buffer.from(r,"base64url"));return o.setAuthTag(Buffer.from(n,"base64url")),Buffer.concat([o.update(Buffer.from(i,"base64url")),o.final()]).toString("utf8")}current(e){let t=bw(e);return t.status!=="disconnected"&&t.credentialExpiresAt&&new Date(t.credentialExpiresAt).getTime()<=this.nowFn().getTime()?{...t,status:"expired",healthMessage:"Registry credential expired; rotate it before pulling images."}:t}create(e){if(!["docker_hub","ghcr","ecr","gcr","generic"].includes(e.provider))throw Error("A supported registry provider is required");let t=e.credential?JSON.stringify(e.credential):void 0,r=this.idFn(),n=this.now();return this.controlPlane.database.run("INSERT INTO registry_connections (id, organization_id, provider, name, host, credential_ciphertext, credential_fingerprint, credential_expires_at, created_by_actor_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[r,e.organizationId,e.provider,e.name.trim().slice(0,80),pm(e.host),t?this.encrypt(t):null,t?Ac(t):null,e.credentialExpiresAt??null,e.actorId??null,n,n]),this.controlPlane.appendEvent({organizationId:e.organizationId,actorId:e.actorId,type:"registry.connection.created",payload:{connectionId:r,provider:e.provider,host:pm(e.host),credentialConfigured:!!t}}),this.get(r)}get(e){let t=this.controlPlane.database.query("SELECT * FROM registry_connections WHERE id=?").get(e);return t?this.current(t):void 0}list(e){return this.controlPlane.database.query("SELECT * FROM registry_connections WHERE organization_id=? ORDER BY name").all(e).map((t)=>this.current(t))}credential(e){let t=this.controlPlane.database.query("SELECT credential_ciphertext FROM registry_connections WHERE id=?").get(e);return t?.credential_ciphertext?JSON.parse(this.decrypt(String(t.credential_ciphertext))):void 0}rotate(e,t,r={}){let n=this.get(e);if(!n||n.status==="disconnected")throw Error("Registry connection was not found");let i=JSON.stringify(t);return this.controlPlane.database.run("UPDATE registry_connections SET credential_ciphertext=?, credential_fingerprint=?, credential_expires_at=?, status='pending', health_message=NULL, version=version+1, updated_at=? WHERE id=?",[this.encrypt(i),Ac(i),r.expiresAt??null,this.now(),e]),this.controlPlane.appendEvent({organizationId:n.organizationId,actorId:r.actorId,type:"registry.credential.rotated",payload:{connectionId:e,fingerprint:Ac(i),expiresAt:r.expiresAt??null}}),this.get(e)}disconnect(e,t){let r=this.get(e);if(!r)throw Error("Registry connection was not found");return this.controlPlane.database.run("UPDATE registry_connections SET credential_ciphertext=NULL, credential_fingerprint=NULL, status='disconnected', health_message='Disconnected by an administrator', version=version+1, updated_at=? WHERE id=?",[this.now(),e]),this.controlPlane.appendEvent({organizationId:r.organizationId,actorId:t,type:"registry.connection.disconnected",level:"warning",payload:{connectionId:e}}),this.get(e)}async test(e,t={}){let r=this.get(e);if(!r||["disconnected","expired"].includes(r.status))throw Error("Active registry connection was not found");let n=this.credential(e),i=t.fetch??fetch,o=new AbortController,s=setTimeout(()=>o.abort(),t.timeoutMs??15000),c=n?.token?`Bearer ${n.token}`:n?.username||n?.password?`Basic ${Buffer.from(`${n.username??""}:${n.password??""}`).toString("base64")}`:void 0;try{let d=await i(`${r.host}/v2/`,{method:"GET",redirect:"error",signal:o.signal,headers:c?{Authorization:c}:void 0}),a=d.headers.get("www-authenticate")??"";if(d.status===401&&a.startsWith("Bearer ")&&n){let h=Object.fromEntries([...a.slice(7).matchAll(/(\w+)="([^"]+)"/g)].map((T)=>[T[1],T[2]])),y=new URL(h.realm??"");if(y.protocol!=="https:")throw Error("Registry authentication realm must use HTTPS");if(h.service)y.searchParams.set("service",h.service);if(t.image)y.searchParams.set("scope",`repository:${fm(t.image).repository}:pull`);let w=await i(y,{signal:o.signal,redirect:"error",headers:c?{Authorization:c}:void 0});if(!w.ok)throw Error(`Registry authentication failed (${w.status})`);let k=await w.json(),C=k.token??k.access_token;if(!C)throw Error("Registry did not return an access token");d=t.image?await mm(i,r.host,t.image,C,o.signal):await i(`${r.host}/v2/`,{signal:o.signal,redirect:"error",headers:{Authorization:`Bearer ${C}`}})}else if(d.ok&&t.image)d=await mm(i,r.host,t.image,n?.token,o.signal,c);let u=d.ok?"healthy":"degraded",m=d.ok?t.image?"Registry image is readable.":"Registry connection is healthy.":`Registry request failed (${d.status})`;return this.controlPlane.database.run("UPDATE registry_connections SET status=?, health_message=?, last_tested_at=?, version=version+1, updated_at=? WHERE id=?",[u,m,this.now(),this.now(),e]),this.get(e)}catch(d){let a=o.signal.aborted?"Registry request timed out.":d instanceof Error?d.message:"Registry test failed";return this.controlPlane.database.run("UPDATE registry_connections SET status='degraded', health_message=?, last_tested_at=?, version=version+1, updated_at=? WHERE id=?",[a.slice(0,1000),this.now(),this.now(),e]),this.get(e)}finally{clearTimeout(s)}}}function fm(e){let t=e.replace(/^https?:\/\//,""),r=t.indexOf("/");if(r<1)throw Error("Image must include registry/repository");let n=t.slice(r+1),i=n.lastIndexOf("@"),o=n.lastIndexOf(":"),s=i>=0?i:o>n.lastIndexOf("/")?o:-1,c=s>=0?n.slice(0,s):n,d=s>=0?n.slice(s+1):"latest";if(!/^[A-Za-z0-9_.\/-]+$/.test(c)||!/^[A-Za-z0-9_.:+-]+$/.test(d))throw Error("Image reference is invalid");return{repository:c,reference:d}}async function mm(e,t,r,n,i,o){let s=fm(r);return e(`${t}/v2/${s.repository}/manifests/${encodeURIComponent(s.reference)}`,{method:"HEAD",redirect:"error",signal:i,headers:{Accept:"application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json",...n?{Authorization:`Bearer ${n}`}:o?{Authorization:o}:{}}})}import{createHash as Sw}from"node:crypto";import{chmodSync as hm,existsSync as ym,mkdirSync as ww,renameSync as kw,unlinkSync as vm,writeFileSync as Iw}from"node:fs";import{basename as Ew,join as Rw}from"node:path";function Pc(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),filename:String(e.filename),sha256:String(e.sha256),size:Number(e.size),format:String(e.format),entryCount:Number(e.entry_count),expandedBytes:Number(e.expanded_bytes),createdByActorId:e.created_by_actor_id?String(e.created_by_actor_id):void 0,createdAt:String(e.created_at)}}class _c{controlPlane;root;idFn;nowFn;constructor(e,t){this.controlPlane=e;this.root=yt(t.cwd,"artifacts"),this.idFn=t.id??(()=>crypto.randomUUID()),this.nowFn=t.now??(()=>new Date)}create(e){let t=this.controlPlane.getProject(e.projectId);if(!t||t.organizationId!==e.organizationId)throw Error("Artifact project was not found");let r=Ew(e.filename).slice(0,200);if(!r||r!==e.filename)throw Error("Artifact filename must not contain a path");let n=sm(e.bytes,r),i=Sw("sha256").update(e.bytes).digest("hex"),o=this.controlPlane.database.query("SELECT * FROM application_artifacts WHERE project_id=? AND sha256=?").get(e.projectId,i);if(o)return Pc(o);let s=this.idFn();ww(this.root,{recursive:!0,mode:448}),hm(this.root,448);let c=Rw(this.root,`${s}.archive`),d=`${c}.partial`;try{Iw(d,e.bytes,{mode:384,flag:"wx"}),kw(d,c),hm(c,384),this.controlPlane.database.run("INSERT INTO application_artifacts (id, organization_id, project_id, filename, storage_path, sha256, size, format, entry_count, expanded_bytes, created_by_actor_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[s,e.organizationId,e.projectId,r,c,i,e.bytes.byteLength,n.format,n.entries,n.expandedBytes,e.actorId??null,this.nowFn().toISOString()])}catch(a){if(ym(d))vm(d);if(ym(c))vm(c);throw a}return this.controlPlane.appendEvent({organizationId:e.organizationId,projectId:e.projectId,actorId:e.actorId,type:"application.artifact.created",payload:{artifactId:s,filename:r,sha256:i,size:e.bytes.byteLength,entries:n.entries}}),this.get(s)}get(e){let t=this.controlPlane.database.query("SELECT * FROM application_artifacts WHERE id=?").get(e);return t?Pc(t):void 0}list(e){return this.controlPlane.database.query("SELECT * FROM application_artifacts WHERE project_id=? ORDER BY created_at DESC").all(e).map(Pc)}}function ls(e){let t=e.drafts.get(e.draftId);if(!t||t.version!==e.expectedVersion)throw Error(`Application draft ${e.draftId} changed since version ${e.expectedVersion}`);if(t.status==="applied")throw Error("Application draft was already applied");let r=e.controlPlane.getProject(t.projectId),n=r?e.controlPlane.listEnvironments(r.id).find((a)=>a.id===t.input.environmentId):void 0;if(!r||!n||n.projectId!==r.id||r.organizationId!==t.organizationId)throw Error("Draft deployment scope was not found");if(e.confirmEnvironment!==n.slug)throw Error(`Type ${n.slug} to confirm this deployment target`);let i=Yt(t.input,t.suppliedSecretNames);if(!i.valid)throw Error(`Application plan is invalid: ${[...i.issues.map((a)=>a.message),...i.missingSecrets.map((a)=>`Missing secret ${a}`)].join("; ")}`);let o=e.controlPlane.listResources(r.id,n.id).find((a)=>a.kind==="application"&&a.slug===t.input.slug),s=JSON.parse(JSON.stringify({manifest:i.manifest,configPatch:i.configPatch})),c=o?e.controlPlane.updateResource(o.id,o.version,{name:t.input.name,desiredState:s}):e.controlPlane.createResource({projectId:r.id,environmentId:n.id,kind:"application",slug:t.input.slug,name:t.input.name,desiredState:s,metadata:{source:"application-onboarding",draftId:t.id}}),d=new $e(e.controlPlane).enqueue({projectId:r.id,environmentId:n.id,resourceId:c.id,actorId:e.actorId,kind:"application.create",idempotencyKey:`application-draft:${t.id}:v${t.version}`,correlationId:`application-draft:${t.id}`,input:s,lockKey:`resource:${c.id}`,providerKey:c.provider??"default",buildSlot:t.input.build.kind!=="prebuilt_image",maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;return e.drafts.markApplied(t.id,t.version,e.actorId),e.controlPlane.appendEvent({organizationId:t.organizationId,projectId:r.id,resourceId:c.id,operationId:d.id,actorId:e.actorId,type:"application.create.queued",payload:{draftId:t.id,environment:n.slug,strategy:t.input.build.kind,costDrivers:i.costDrivers}}),{plan:i,resource:c,operation:d}}function ao(e){let t=["static","compute","serverless_zip","serverless_image"].includes(e.kind),r=["container","compose"].includes(e.kind)&&(e.replicas??1)>1,n=e.kind==="container"||e.kind==="serverless_zip"||e.kind==="serverless_image",i=(o,s)=>s&&(o==="atomic"?e.kind==="static"||e.hasHealthGate:e.hasHealthGate);return[{strategy:"atomic",supported:i("atomic",t),explanation:t?e.hasHealthGate||e.kind==="static"?"Activate an immutable version with an atomic pointer/alias switch.":"Atomic activation needs a readiness gate for this runtime.":"This driver has no atomic pointer or alias primitive.",capacityMultiplier:1,costImpact:"none",rollback:"Switch the pointer/alias back to the previous immutable release."},{strategy:"rolling",supported:i("rolling",r),explanation:r?e.hasHealthGate?"Replace healthy replicas within the configured capacity envelope.":"Rolling activation requires a health/readiness gate.":"Rolling activation requires a capable container/Compose driver and at least two replicas.",capacityMultiplier:1.5,costImpact:"temporary",rollback:"Stop replacement and restore the prior task/service definition."},{strategy:"blue_green",supported:i("blue_green",n),explanation:n?e.hasHealthGate?"Provision a complete green target and switch traffic after health passes.":"Blue-green requires a health gate before traffic can switch.":"The provider does not expose two traffic-addressable revisions.",capacityMultiplier:2,costImpact:"temporary",rollback:"Return all traffic to the preserved blue target."},{strategy:"canary",supported:i("canary",n),explanation:n?e.hasHealthGate?"Shift bounded traffic steps while evaluating health.":"Canary requires a health gate and measurable traffic target.":"The provider does not expose weighted traffic primitives.",capacityMultiplier:1.25,costImpact:"temporary",rollback:"Set canary weight to zero and preserve its diagnostics."}]}function us(e,t){let r=ao(e).find((n)=>n.strategy===t);if(!r.supported)throw Error(`${t} is unavailable: ${r.explanation}`);return r}import{createHash as Aw}from"node:crypto";var Cw=/^sha256:[a-f0-9]{64}$/,Pw=/^[a-f0-9]{40,64}$/i;function pr(e){return typeof e==="string"&&e?e:void 0}function xn(e,t){try{return JSON.parse(String(e))}catch{return t}}function bm(e){return{id:String(e.id),organizationId:String(e.organization_id),digest:String(e.digest),kind:String(e.kind),uri:String(e.uri),size:Number(e.size),mediaType:String(e.media_type),provenance:xn(e.provenance,{}),attestation:xn(e.attestation,{}),verifiedAt:String(e.verified_at),createdAt:String(e.created_at)}}function Sm(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:String(e.environment_id),resourceId:String(e.resource_id),artifactId:String(e.artifact_id),kind:String(e.kind),sourceSha:pr(e.source_sha),configHash:String(e.config_hash),manifest:xn(e.manifest,{}),provenance:xn(e.provenance,{}),strategy:String(e.strategy),status:String(e.status),healthGate:e.health_gate==null?void 0:xn(e.health_gate,void 0),hooks:xn(e.hooks,{migrations:"none",preActivate:[],postActivate:[]}),drainSeconds:Number(e.drain_seconds),graceSeconds:Number(e.grace_seconds),automaticRollback:Number(e.automatic_rollback)===1,rollbackAttempts:Number(e.rollback_attempts),previousReleaseId:pr(e.previous_release_id),promotedFromReleaseId:pr(e.promoted_from_release_id),actorId:pr(e.actor_id),trigger:String(e.trigger),pinned:Number(e.pinned)===1,pinReason:pr(e.pin_reason),activatedAt:pr(e.activated_at),failedAt:pr(e.failed_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function _w(e){return{sequence:Number(e.sequence),id:String(e.id),releaseId:String(e.release_id),fromStatus:pr(e.from_status),toStatus:String(e.to_status),trafficPercent:e.traffic_percent==null?void 0:Number(e.traffic_percent),health:xn(e.health,{}),message:String(e.message),operationId:pr(e.operation_id),createdAt:String(e.created_at)}}function Tw(e,t){let r=[],n=(i,o,s)=>{if(JSON.stringify(o)===JSON.stringify(s))return;if(o&&s&&typeof o==="object"&&typeof s==="object"&&!Array.isArray(o)&&!Array.isArray(s)){for(let c of[...new Set([...Object.keys(o),...Object.keys(s)])].sort())n(i?`${i}.${c}`:c,o[c],s[c]);return}r.push({path:i,...o!==void 0?{before:o}:{},...s!==void 0?{after:s}:{}})};return n("",e,t),r}class Tc{controlPlane;now;id;constructor(e,t={}){this.controlPlane=e;this.now=t.now??(()=>new Date),this.id=t.id??(()=>crypto.randomUUID())}registerArtifact(e){if(!Cw.test(e.digest)||!/^(?:s3|https|oci|file):/.test(e.uri)||!Number.isInteger(e.size)||e.size<0)throw Error("Artifact requires a SHA-256 digest, supported immutable URI, and non-negative byte size");let t=this.controlPlane.database.query("SELECT * FROM release_artifacts WHERE organization_id=? AND digest=?").get(e.organizationId,e.digest);if(t)return bm(t);let r=this.id(),n=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO release_artifacts (id, organization_id, digest, kind, uri, size, media_type, provenance, attestation, verified_at, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[r,e.organizationId,e.digest,e.kind,e.uri,e.size,e.mediaType??"application/octet-stream",JSON.stringify(Oe(e.provenance??{})),JSON.stringify(Oe(e.attestation??{})),n,n]),this.getArtifact(r)}getArtifact(e){let t=this.controlPlane.database.query("SELECT * FROM release_artifacts WHERE id=?").get(e);return t?bm(t):void 0}create(e){let t=this.getArtifact(e.artifactId),r=this.controlPlane.getResource(e.resourceId),n=this.controlPlane.listEnvironments(e.projectId).find((m)=>m.id===e.environmentId);if(!t||t.organizationId!==e.organizationId||t.kind!==e.kind)throw Error("Release artifact does not match the organization and deployable kind");if(!r||r.projectId!==e.projectId||r.environmentId!==e.environmentId||!n)throw Error("Release target scope does not match the resource");if(e.sourceSha&&!Pw.test(e.sourceSha))throw Error("Release source must be an immutable commit SHA");us({kind:e.kind,provider:r.provider,hasHealthGate:!!e.healthGate,replicas:e.replicas},e.strategy);let i=Oe(e.config),o=Aw("sha256").update(JSON.stringify(i)).digest("hex"),s=this.active(e.resourceId),c=this.id(),d=this.now().toISOString(),a=e.approvalRequired?"awaiting_approval":"built",u=e.hooks??{migrations:"none",preActivate:[],postActivate:[]};return this.controlPlane.database.run("INSERT INTO releases (id, organization_id, project_id, environment_id, resource_id, artifact_id, kind, source_sha, config_hash, manifest, provenance, strategy, status, health_gate, hooks, drain_seconds, grace_seconds, automatic_rollback, previous_release_id, promoted_from_release_id, actor_id, trigger, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[c,e.organizationId,e.projectId,e.environmentId,e.resourceId,e.artifactId,e.kind,e.sourceSha??null,o,JSON.stringify(Oe(e.manifest)),JSON.stringify(Oe(e.provenance??{})),e.strategy,a,e.healthGate?JSON.stringify(e.healthGate):null,JSON.stringify(u),Math.max(0,Math.min(3600,Math.floor(e.drainSeconds??30))),Math.max(0,Math.min(3600,Math.floor(e.graceSeconds??30))),e.automaticRollback===!1?0:1,s?.id??null,e.promotedFromReleaseId??null,e.actorId??null,e.trigger??"manual",d,d]),this.recordTransition(c,void 0,a,{message:e.promotedFromReleaseId?"Immutable artifact promoted without rebuild.":"Immutable release record created."}),this.get(c)}get(e){let t=this.controlPlane.database.query("SELECT * FROM releases WHERE id=?").get(e);return t?Sm(t):void 0}list(e={}){return this.controlPlane.database.query("SELECT * FROM releases ORDER BY created_at DESC, rowid DESC").all().map(Sm).filter((t)=>(!e.projectId||t.projectId===e.projectId)&&(!e.environmentId||t.environmentId===e.environmentId)&&(!e.resourceId||t.resourceId===e.resourceId)&&(!e.status||t.status===e.status))}active(e){return this.list({resourceId:e,status:"active"})[0]}transitions(e){return this.controlPlane.database.query("SELECT * FROM release_transitions WHERE release_id=? ORDER BY sequence").all(e).map(_w)}recordTransition(e,t,r,n){this.controlPlane.database.run("INSERT INTO release_transitions (id, release_id, from_status, to_status, traffic_percent, health, message, operation_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",[this.id(),e,t??null,r,n.trafficPercent??null,JSON.stringify(Oe(n.health??{})),n.message.slice(0,1000),n.operationId??null,this.now().toISOString()])}progress(e,t){let r=this.get(e);if(!r)throw Error(`Release ${e} was not found`);return this.recordTransition(e,r.status,r.status,t),this.transitions(e).at(-1)}transition(e,t,r){let n=this.get(e);if(!n)throw Error(`Release ${e} was not found`);if(!{built:["awaiting_approval","activating","failed"],awaiting_approval:["built","failed"],activating:["active","failed","rolled_back"],active:["superseded","failed","rolled_back"],failed:["activating","rolled_back"],rolled_back:["activating"],superseded:["activating"]}[n.status].includes(t))throw Error(`Invalid release transition ${n.status} → ${t}`);let o=this.now().toISOString();if(t==="active"){let s=this.active(n.resourceId);if(s&&s.id!==e)this.controlPlane.database.run("UPDATE releases SET status='superseded', updated_at=? WHERE id=?",[o,s.id]),this.recordTransition(s.id,"active","superseded",{message:`Superseded by ${e}.`,operationId:r.operationId})}return this.controlPlane.database.run("UPDATE releases SET status=?, rollback_attempts=rollback_attempts+?, activated_at=CASE WHEN ?='active' THEN ? ELSE activated_at END, failed_at=CASE WHEN ?='failed' THEN ? ELSE failed_at END, updated_at=? WHERE id=?",[t,t==="rolled_back"?1:0,t,o,t,o,o,e]),this.recordTransition(e,n.status,t,r),this.get(e)}approve(e,t){let r=this.get(e);if(!r||r.status!=="awaiting_approval")throw Error("Release is not awaiting approval");let n=this.id(),i=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO release_approvals (id, release_id, environment_id, decision, actor_id, comment, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[n,e,r.environmentId,t.decision,t.actorId,t.comment?.slice(0,1000)??null,i]),this.transition(e,t.decision==="approved"?"built":"failed",{message:t.decision==="approved"?"Environment gate approved.":"Environment gate rejected."})}approvals(e){return this.controlPlane.database.query("SELECT * FROM release_approvals WHERE release_id=? ORDER BY created_at").all(e).map((t)=>({id:String(t.id),releaseId:String(t.release_id),environmentId:String(t.environment_id),decision:String(t.decision),actorId:String(t.actor_id),comment:pr(t.comment),createdAt:String(t.created_at)}))}promote(e,t){let r=this.get(e);if(!r||!["active","superseded"].includes(r.status))throw Error("Only a tested active/superseded release can be promoted");return this.create({organizationId:r.organizationId,projectId:r.projectId,environmentId:t.targetEnvironmentId,resourceId:t.targetResourceId,artifactId:r.artifactId,kind:r.kind,sourceSha:r.sourceSha,config:t.config,manifest:r.manifest,provenance:r.provenance,strategy:t.strategy??r.strategy,healthGate:t.healthGate??r.healthGate,hooks:r.hooks,drainSeconds:r.drainSeconds,graceSeconds:r.graceSeconds,automaticRollback:r.automaticRollback,promotedFromReleaseId:r.id,actorId:t.actorId,trigger:"promotion",approvalRequired:t.approvalRequired})}compare(e,t){let r=this.get(e),n=this.get(t);if(!r||!n)throw Error("Both releases are required for comparison");return{artifactChanged:r.artifactId!==n.artifactId,sourceChanged:r.sourceSha!==n.sourceSha,configChanged:r.configHash!==n.configHash,manifestChanges:Tw(r.manifest,n.manifest),dataCaveat:n.hooks.migrations==="none"?"No database migration is recorded.":`Database hooks are ${n.hooks.migrations}; release rollback does not roll back data.`}}pin(e,t,r){if(!this.get(e))throw Error("Release was not found");return this.controlPlane.database.run("UPDATE releases SET pinned=?, pin_reason=?, updated_at=? WHERE id=?",[t?1:0,t?r?.slice(0,500)??"operator":null,this.now().toISOString(),e]),this.get(e)}retentionCandidates(e){let t=Math.max(1,Math.min(100,Math.floor(e.keepPerResource??10))),r=new Map;for(let n of this.list()){let i=r.get(n.resourceId)??[];i.push(n),r.set(n.resourceId,i)}return[...r.values()].flatMap((n)=>n.slice(t)).filter((n)=>new Date(n.createdAt)<e.before&&!n.pinned&&!["active","activating","awaiting_approval"].includes(n.status)&&!this.list().some((i)=>i.previousReleaseId===n.id&&["active","activating"].includes(i.status)))}}class Dn{controlPlane;releases;queue;constructor(e){this.controlPlane=e;this.releases=new Tc(e),this.queue=new $e(e)}enqueueActivation(e,t={}){let r=this.releases.get(e.id);if(!r)throw Error("Release was not found");if(!["built","failed","rolled_back","superseded"].includes(r.status))throw Error(`Release ${r.status} cannot be activated`);let n=t.action??"activate",i=this.queue.enqueue({projectId:r.projectId,environmentId:r.environmentId,resourceId:r.resourceId,actorId:t.actorId,kind:`release.${n}`,idempotencyKey:`release:${r.id}:${n}:${r.rollbackAttempts}`,correlationId:`release:${r.id}`,input:{releaseId:r.id,targetReleaseId:t.targetReleaseId??null},lockKey:`resource:${r.resourceId}`,providerKey:this.controlPlane.getResource(r.resourceId)?.provider??"default",maxAttempts:r.automaticRollback?2:1,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:365}).operation;return this.releases.transition(r.id,"activating",{message:`${n} queued.`,operationId:i.id,trafficPercent:0}),i}completeHealthGate(e,t){let r=this.releases.get(e);if(!r||r.status!=="activating")throw Error("Release is not activating");if(t.healthy)return{release:this.releases.transition(r.id,"active",{message:t.message??"Health gate passed; activation completed.",operationId:t.operationId,trafficPercent:100,health:t.health})};let n=this.releases.transition(r.id,"failed",{message:t.message??"Health gate failed.",operationId:t.operationId,trafficPercent:0,health:t.health}),i=r.previousReleaseId?this.releases.get(r.previousReleaseId):void 0;if(!r.automaticRollback||r.rollbackAttempts>=1||!i)return{release:n};let o=this.queue.enqueue({projectId:r.projectId,environmentId:r.environmentId,resourceId:r.resourceId,kind:"release.rollback",idempotencyKey:`release:${r.id}:automatic-rollback`,correlationId:`release:${r.id}`,input:{releaseId:r.id,targetReleaseId:i.id,automatic:!0},lockKey:`resource:${r.resourceId}`,providerKey:this.controlPlane.getResource(r.resourceId)?.provider??"default",maxAttempts:1,retryClasses:[],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:365}).operation;return{release:n,rollbackOperation:o}}enqueueRollback(e,t={}){let r=this.releases.get(e.id);if(!r||r.status!=="active")throw Error("Only the active release can be rolled back");let n=t.targetReleaseId?this.releases.get(t.targetReleaseId):r.previousReleaseId?this.releases.get(r.previousReleaseId):void 0;if(!n||n.resourceId!==r.resourceId||!["superseded","active"].includes(n.status))throw Error("Rollback requires a preserved prior release for the same resource");return this.queue.enqueue({projectId:r.projectId,environmentId:r.environmentId,resourceId:r.resourceId,actorId:t.actorId,kind:"release.rollback",idempotencyKey:`release:${r.id}:manual-rollback:${n.id}`,correlationId:`release:${r.id}`,input:{releaseId:r.id,targetReleaseId:n.id,automatic:!1},lockKey:`resource:${r.resourceId}`,providerKey:this.controlPlane.getResource(r.resourceId)?.provider??"default",maxAttempts:1,retryClasses:[],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:365}).operation}}function xw(e){if(e.strategy==="canary")return[5,25,50,100].map((t,r)=>({step:`canary-${t}`,trafficPercent:t,waitSeconds:r===3?e.drainSeconds:e.graceSeconds,requiresHealth:!0}));if(e.strategy==="blue_green")return[{step:"green-health",trafficPercent:0,waitSeconds:e.graceSeconds,requiresHealth:!0},{step:"traffic-switch",trafficPercent:100,waitSeconds:e.drainSeconds,requiresHealth:!0}];if(e.strategy==="rolling")return[{step:"rolling-replacement",trafficPercent:50,waitSeconds:e.graceSeconds,requiresHealth:!0},{step:"rolling-complete",trafficPercent:100,waitSeconds:e.drainSeconds,requiresHealth:!0}];return[{step:"immutable-switch",trafficPercent:100,waitSeconds:e.drainSeconds,requiresHealth:!!e.healthGate}]}async function wm(e,t){if(t.release.artifactId!==t.artifact.id)throw Error("Release activation artifact identity changed");us({kind:t.release.kind,hasHealthGate:!!t.release.healthGate,replicas:Number(t.release.manifest?.replicas)||void 0},t.release.strategy);let r=e.capability(t);if(!r.supported)throw Error(`${t.release.strategy} is unavailable in ${e.name}: ${r.explanation}`);return e.activate({...t,transitions:xw(t.release)})}async function km(e,t){if(!t.previous)throw Error("Rollback requires the preserved previous release");return e.rollback({...t,transitions:[{step:"rollback",trafficPercent:0,waitSeconds:t.release.drainSeconds,requiresHealth:!0}]})}var Dw=["release.activate","release.rollback"];function Ow(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function Im(e){let t=new Dn(e.store),r=async(n)=>{let i=Ow(n.operation.input),o=typeof i.releaseId==="string"?i.releaseId:"",s=t.releases.get(o);if(!s)throw Error(`Queued release ${o||"(missing)"} was not found`);if(s.projectId!==n.operation.projectId||s.environmentId!==n.operation.environmentId||s.resourceId!==n.operation.resourceId)throw Error("Queued release does not match the operation scope");let c=t.releases.getArtifact(s.artifactId);if(!c||c.digest!==t.releases.getArtifact(s.artifactId)?.digest)throw Error("Immutable release artifact is unavailable");let d=typeof i.targetReleaseId==="string"&&i.targetReleaseId?i.targetReleaseId:s.previousReleaseId,a=d?t.releases.get(d):void 0;if(a&&(a.resourceId!==s.resourceId||a.artifactId===s.artifactId&&a.id===s.id))throw Error("Rollback target does not match the release resource");let u=await e.resolveDriver(s);n.checkpoint("verify",`Verifying ${c.digest} and ${s.configHash} for ${u.name}.`),n.log(`Artifact ${c.digest}; source ${s.sourceSha??"not recorded"}; config ${s.configHash}.`,{stream:"system"}),n.throwIfCancellationRequested();let m;try{m=n.operation.kind==="release.rollback"?await km(u,{release:s,artifact:c,previous:a}):await wm(u,{release:s,artifact:c,previous:a})}catch(h){if(n.operation.kind==="release.activate"&&t.releases.get(s.id)?.status==="activating")t.completeHealthGate(s.id,{healthy:!1,operationId:n.operation.id,message:h instanceof Error?h.message:String(h)});throw h}for(let h of m.transitions)t.releases.progress(s.id,{message:`${n.operation.kind==="release.rollback"?"Rollback":"Activation"} traffic at ${h.trafficPercent}%.`,trafficPercent:h.trafficPercent,health:h.observed,operationId:n.operation.id}),n.log(`Traffic ${h.trafficPercent}%: ${h.healthy?"healthy":"unhealthy"}.`,{stream:h.healthy?"step":"stderr",step:"health"});if(n.checkpoint("health","Evaluating the provider health result."),!m.activated||!m.healthy){if(n.operation.kind==="release.activate"&&t.releases.get(s.id)?.status==="activating")t.completeHealthGate(s.id,{healthy:!1,operationId:n.operation.id,health:{resourceVersions:m.resourceVersions},message:m.error??"Provider health gate failed."});throw Error(m.error??`${u.name} reported an unhealthy release`)}if(n.operation.kind==="release.activate"&&s.healthGate?.name){if(!e.resolveHealthGate)throw t.completeHealthGate(s.id,{healthy:!1,operationId:n.operation.id,message:`Named health gate ${s.healthGate.name} is not available to this worker.`}),Error(`Named health gate ${s.healthGate.name} is unavailable`);n.checkpoint("named-health-gate",`Waiting on ${s.healthGate.name}.`);let h=await e.resolveHealthGate(s.healthGate.name,s);if(n.log(`${s.healthGate.name}: ${h.healthy?"healthy":"unhealthy"}${h.message?` — ${h.message}`:""}.`,{stream:h.healthy?"step":"stderr",step:"health"}),!h.healthy)throw t.completeHealthGate(s.id,{healthy:!1,operationId:n.operation.id,health:h.evidence,message:h.message??`Named health gate ${s.healthGate.name} failed.`}),Error(h.message??`Named health gate ${s.healthGate.name} failed`)}if(n.operation.kind==="release.rollback"){let h=t.releases.get(s.id);if(h.status!=="rolled_back")t.releases.transition(h.id,"rolled_back",{message:`Traffic restored through ${u.name}.`,operationId:n.operation.id,trafficPercent:0,health:{resourceVersions:m.resourceVersions}});if(a&&a.status!=="active"){let y=a.status==="activating"?a:t.releases.transition(a.id,"activating",{message:"Rollback target restoring traffic.",operationId:n.operation.id,trafficPercent:0});t.releases.transition(y.id,"active",{message:"Previous immutable release restored.",operationId:n.operation.id,trafficPercent:100,health:{resourceVersions:m.resourceVersions}})}}else t.completeHealthGate(s.id,{healthy:!0,operationId:n.operation.id,health:{providerVersion:m.providerVersion??null,resourceVersions:m.resourceVersions},message:"Provider activation and health gates completed."});return n.checkpoint("finalize","Persisted the terminal release state."),{releaseId:s.id,artifactDigest:c.digest,provider:u.name,providerVersion:m.providerVersion??null,resourceVersions:m.resourceVersions,status:t.releases.get(s.id).status}};return Object.fromEntries(Dw.map((n)=>[n,r]))}import{createCipheriv as $w,createDecipheriv as Nw,createHash as Pm,randomBytes as xc}from"node:crypto";var _m={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 De(e){return typeof e==="string"&&e?e:void 0}function $n(e,t){try{return typeof e==="string"?JSON.parse(e):t}catch{return t}}function mr(e){return JSON.stringify(Oe(e))}function On(e){return Pm("sha256").update(e).digest("hex")}function Em(e){let t=e.trim().replace(/\/$/,""),r=new URL(t.includes("://")?t:`https://${t}`);if(r.username||r.password||r.search||r.hash)throw Error("Source host cannot contain credentials, a query, or a fragment");if(r.protocol!=="https:"&&!(r.protocol==="http:"&&["localhost","127.0.0.1","::1"].includes(r.hostname)))throw Error("Source host must use HTTPS");return`${r.protocol}//${r.host}${r.pathname.replace(/\/$/,"")}`}function Rm(e){let t=e.trim();if(t.length<2||t.length>80)throw Error("Connection name must contain 2-80 characters");return t}function Dc(e){let t=e.trim().replace(/^\/+|\/+$/g,"");if(!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(t))throw Error("Repository must use owner/name format");return t}function Am(e){let t=e.trim()||".";if(t.startsWith("/")||t.split("/").includes("..")||/[\0\r\n]/.test(t))throw Error("Monorepo root must stay inside the repository");return t.replace(/^\.\//,"")||"."}function ps(e){return[...new Set((e??[]).map((t)=>t.trim()).filter(Boolean))].slice(0,100)}function jw(e){let t=e.trim();if(/\r|\n/.test(t)||/https?:\/\/[^/@\s]+:[^/@\s]+@/i.test(t))throw Error("Clone URL cannot contain credentials or control characters");if(!/^(?:https?:\/\/|ssh:\/\/|git@[A-Za-z0-9.-]+:)/.test(t))throw Error("Clone URL must use HTTPS or SSH");return t}function Mw(e){return{id:String(e.id),organizationId:String(e.organization_id),provider:String(e.provider),name:String(e.name),host:String(e.host),owner:De(e.owner),authKind:String(e.auth_kind),credentialConfigured:!!e.credential_ciphertext,credentialFingerprint:De(e.credential_fingerprint),grantedScopes:$n(e.granted_scopes,[]),capabilities:$n(e.capabilities,_m[String(e.provider)]),status:String(e.status),healthMessage:De(e.health_message),lastTestedAt:De(e.last_tested_at),lastSyncedAt:De(e.last_synced_at),credentialExpiresAt:De(e.credential_expires_at),version:Number(e.version),createdByActorId:De(e.created_by_actor_id),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Oc(e){return{id:String(e.id),connectionId:String(e.connection_id),providerRepositoryId:String(e.provider_repository_id),fullName:String(e.full_name),cloneUrl:String(e.clone_url),defaultBranch:String(e.default_branch),visibility:String(e.visibility),archived:Number(e.archived)===1,metadata:$n(e.metadata,{}),syncedAt:String(e.synced_at)}}function Cm(e){return{id:String(e.id),projectId:String(e.project_id),environmentId:De(e.environment_id),resourceId:De(e.resource_id),connectionId:String(e.connection_id),repositoryId:De(e.repository_id),repositoryFullName:String(e.repository_full_name),defaultBranch:String(e.default_branch),branchRule:De(e.branch_rule),tagRule:De(e.tag_rule),monorepoRoot:String(e.monorepo_root),includePaths:$n(e.include_paths,[]),excludePaths:$n(e.exclude_paths,[]),submodules:Number(e.submodules)===1,cloneDepth:e.clone_depth==null?void 0:Number(e.clone_depth),deployKeyId:De(e.deploy_key_id),autoDeploy:Number(e.auto_deploy)===1,pullRequestPreviews:Number(e.pull_request_previews)===1,status:String(e.status),disabledReason:De(e.disabled_reason),version:Number(e.version),createdByActorId:De(e.created_by_actor_id),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function $c(e){return{id:String(e.id),connectionId:String(e.connection_id),name:String(e.name),publicKey:String(e.public_key),publicKeyFingerprint:String(e.public_key_fingerprint),host:String(e.host),hostKey:String(e.host_key),hostKeyFingerprint:String(e.host_key_fingerprint),createdByActorId:De(e.created_by_actor_id),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Nc(e){return{id:String(e.id),connectionId:String(e.connection_id),repositoryId:De(e.repository_id),repositoryFullName:String(e.repository_full_name),providerWebhookId:De(e.provider_webhook_id),events:$n(e.events,[]),status:String(e.status),healthMessage:De(e.health_message),lastDeliveryAt:De(e.last_delivery_at),lastReconciledAt:De(e.last_reconciled_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function jc(e){return{id:String(e.id),connectionId:String(e.connection_id),webhookId:String(e.webhook_id),providerDeliveryId:String(e.provider_delivery_id),event:String(e.event),action:De(e.action),commitSha:De(e.commit_sha),signatureStatus:String(e.signature_status),status:String(e.status),payloadSummary:$n(e.payload_summary,{}),operationId:De(e.operation_id),error:De(e.error),receivedAt:String(e.received_at),processedAt:De(e.processed_at)}}class Mc{controlPlane;key;nowFn;idFn;constructor(e,t={}){this.controlPlane=e;this.key=t.encryptionKey?Pm("sha256").update(t.encryptionKey).digest():void 0,this.nowFn=t.now??(()=>new Date),this.idFn=t.id??(()=>crypto.randomUUID())}now(){return this.nowFn().toISOString()}run(e,t){this.controlPlane.database.run(e,t)}encrypt(e){if(!this.key)throw Error("Source credential encryption key is not configured");let t=xc(12),r=$w("aes-256-gcm",this.key,t),n=Buffer.concat([r.update(e,"utf8"),r.final()]);return`v1.${t.toString("base64url")}.${r.getAuthTag().toString("base64url")}.${n.toString("base64url")}`}decrypt(e){if(!this.key)throw Error("Source credential encryption key is not configured");let[t,r,n,i]=e.split(".");if(t!=="v1"||!r||!n||!i)throw Error("Encrypted source credential is unavailable");let o=Nw("aes-256-gcm",this.key,Buffer.from(r,"base64url"));return o.setAuthTag(Buffer.from(n,"base64url")),Buffer.concat([o.update(Buffer.from(i,"base64url")),o.final()]).toString("utf8")}createConnection(e){if(!this.controlPlane.getOrganization(e.organizationId))throw Error("Source connection organization was not found");let t=this.now(),r=this.idFn(),n=e.credential?JSON.stringify(e.credential):void 0;return this.run(`INSERT INTO source_connections (id, organization_id, provider, name, host, owner, auth_kind, credential_ciphertext, credential_fingerprint, granted_scopes, capabilities, status, credential_expires_at, created_by_actor_id, created_at, updated_at)
|
|
18
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?, ?, ?)`,[r,e.organizationId,e.provider,Rm(e.name),Em(e.host),e.owner?.trim()||null,e.authKind??(n?"access_token":"none"),n?this.encrypt(n):null,n?On(n).slice(0,16):null,mr([...new Set(e.grantedScopes??[])].sort()),mr(_m[e.provider]),e.credentialExpiresAt??null,e.createdByActorId??null,t,t]),this.controlPlane.appendEvent({organizationId:e.organizationId,actorId:e.createdByActorId,type:"source.connection.created",payload:{connectionId:r,provider:e.provider,host:Em(e.host),owner:e.owner??null,scopes:e.grantedScopes??[]}}),this.getConnection(r)}getConnection(e){let t=this.controlPlane.database.query("SELECT * FROM source_connections WHERE id = ?").get(e);return t?this.currentConnection(t):void 0}listConnections(e){return this.controlPlane.database.query("SELECT * FROM source_connections WHERE organization_id = ? ORDER BY name").all(e).map((t)=>this.currentConnection(t))}currentConnection(e){let t=Mw(e);if(t.status!=="disconnected"&&t.credentialExpiresAt&&new Date(t.credentialExpiresAt).getTime()<=this.nowFn().getTime())return{...t,status:"expired",healthMessage:"Source credential expired; rotate it before deploying."};return t}getCredential(e){let t=this.controlPlane.database.query("SELECT credential_ciphertext FROM source_connections WHERE id = ?").get(e);return t?.credential_ciphertext?JSON.parse(this.decrypt(String(t.credential_ciphertext))):void 0}rotateCredential(e,t,r={}){let n=this.getConnection(e);if(!n||n.status==="disconnected")throw Error("Active source connection was not found");let i=JSON.stringify(t);return this.run("UPDATE source_connections SET credential_ciphertext = ?, credential_fingerprint = ?, credential_expires_at = ?, status = 'pending', health_message = NULL, version = version + 1, updated_at = ? WHERE id = ?",[this.encrypt(i),On(i).slice(0,16),r.expiresAt??null,this.now(),e]),this.controlPlane.appendEvent({organizationId:n.organizationId,actorId:r.actorId,type:"source.credential.rotated",payload:{connectionId:e,fingerprint:On(i).slice(0,16),expiresAt:r.expiresAt??null}}),this.getConnection(e)}updateHealth(e,t){let r=this.getConnection(e);if(!r||["disconnected","expired"].includes(r.status))throw Error("Active source connection was not found");let n=this.now(),i=t.grantedScopes?[...new Set(t.grantedScopes.map((o)=>o.trim()).filter(Boolean))].sort():void 0;if(this.run("UPDATE source_connections SET status = ?, health_message = ?, granted_scopes = COALESCE(?, granted_scopes), last_tested_at = COALESCE(?, last_tested_at), last_synced_at = COALESCE(?, last_synced_at), version = version + 1, updated_at = ? WHERE id = ?",[t.status,t.message?.slice(0,1000)??null,i?mr(i):null,t.tested?n:null,t.synced?n:null,n,e]),i&&JSON.stringify(i)!==JSON.stringify([...r.grantedScopes].sort()))this.controlPlane.appendEvent({organizationId:r.organizationId,type:"source.connection.scopes_updated",payload:{connectionId:e,grantedScopes:i}});return this.getConnection(e)}upsertRepository(e){let t=this.getConnection(e.connectionId);if(!t||["disconnected","expired"].includes(t.status))throw Error("Active source connection was not found");let r=this.now(),n=this.controlPlane.database.query("SELECT id FROM source_repositories WHERE connection_id = ? AND provider_repository_id = ?").get(e.connectionId,e.providerRepositoryId),i=n?String(n.id):this.idFn();return this.run(`INSERT INTO source_repositories (id, connection_id, provider_repository_id, full_name, clone_url, default_branch, visibility, archived, metadata, synced_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
19
|
+
ON CONFLICT(connection_id, provider_repository_id) DO UPDATE SET full_name=excluded.full_name, clone_url=excluded.clone_url, default_branch=excluded.default_branch, visibility=excluded.visibility, archived=excluded.archived, metadata=excluded.metadata, synced_at=excluded.synced_at`,[i,e.connectionId,e.providerRepositoryId,Dc(e.fullName),jw(e.cloneUrl),e.defaultBranch.trim()||"main",e.visibility,e.archived?1:0,mr(e.metadata),r]),Oc(this.controlPlane.database.query("SELECT * FROM source_repositories WHERE id = ?").get(i))}listRepositories(e,t,r=100){let n=t?.trim().toLowerCase();return(n?this.controlPlane.database.query("SELECT * FROM source_repositories WHERE connection_id = ? AND lower(full_name) LIKE ? ORDER BY full_name LIMIT ?").all(e,`%${n}%`,Math.min(500,r)):this.controlPlane.database.query("SELECT * FROM source_repositories WHERE connection_id = ? ORDER BY full_name LIMIT ?").all(e,Math.min(500,r))).map(Oc)}getRepository(e){let t=this.controlPlane.database.query("SELECT * FROM source_repositories WHERE id = ?").get(e);return t?Oc(t):void 0}createDeployKey(e){let t=this.getConnection(e.connectionId);if(!t||["disconnected","expired"].includes(t.status)||!t.capabilities.deployKeys)throw Error("An active deploy-key capable source connection is required");if(!/^ssh-(?:ed25519|rsa)\s+[A-Za-z0-9+/=]+/.test(e.publicKey.trim()))throw Error("A valid SSH public key is required");if(!/BEGIN (?:OPENSSH|RSA) PRIVATE KEY/.test(e.privateKey))throw Error("A valid SSH private key is required");if(!/^(?:ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp\d+)\s+[A-Za-z0-9+/=]+/.test(e.hostKey.trim()))throw Error("A pinned SSH host key is required");let r=this.idFn(),n=this.now(),i=`sha256:${On(e.publicKey.trim())}`,o=`sha256:${On(e.hostKey.trim())}`;return this.run("INSERT INTO source_deploy_keys (id, connection_id, name, public_key, public_key_fingerprint, private_key_ciphertext, host, host_key, host_key_fingerprint, created_by_actor_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[r,e.connectionId,Rm(e.name),e.publicKey.trim(),i,this.encrypt(e.privateKey),e.host.trim().toLowerCase(),e.hostKey.trim(),o,e.actorId??null,n,n]),this.controlPlane.appendEvent({organizationId:t.organizationId,actorId:e.actorId,type:"source.deploy_key.created",payload:{connectionId:e.connectionId,deployKeyId:r,publicFingerprint:i,hostFingerprint:o}}),$c(this.controlPlane.database.query("SELECT * FROM source_deploy_keys WHERE id = ?").get(r))}getDeployKey(e){let t=this.controlPlane.database.query("SELECT * FROM source_deploy_keys WHERE id = ?").get(e);return t?$c(t):void 0}listDeployKeys(e){return this.controlPlane.database.query("SELECT * FROM source_deploy_keys WHERE connection_id = ? ORDER BY name, created_at").all(e).map($c)}revokeDeployKey(e,t){let r=this.getDeployKey(e),n=r?this.getConnection(r.connectionId):void 0;if(!r||!n)throw Error("Deploy key was not found");let i=this.listBindings({connectionId:n.id}).filter((s)=>s.deployKeyId===e),o=this.now();return this.controlPlane.database.transaction(()=>{this.run("UPDATE source_bindings SET deploy_key_id=NULL, status='disabled', auto_deploy=0, disabled_reason='Source deploy key was revoked', version=version+1, updated_at=? WHERE deploy_key_id=?",[o,e]),this.run("DELETE FROM source_deploy_keys WHERE id=?",[e])})(),this.controlPlane.appendEvent({organizationId:n.organizationId,actorId:t,type:"source.deploy_key.revoked",level:"warning",payload:{connectionId:n.id,deployKeyId:e,affectedBindingIds:i.map((s)=>s.id)}}),{affectedBindings:i}}getDeployPrivateKey(e){let t=this.controlPlane.database.query("SELECT private_key_ciphertext FROM source_deploy_keys WHERE id = ?").get(e);if(!t)throw Error("Deploy key was not found");return this.decrypt(String(t.private_key_ciphertext))}createBinding(e){let t=this.getConnection(e.connectionId);if(!t||["disconnected","expired"].includes(t.status))throw Error("Active source connection was not found");if(e.repositoryId&&this.getRepository(e.repositoryId)?.connectionId!==t.id)throw Error("Repository does not belong to this connection");if(e.deployKeyId&&this.getDeployKey(e.deployKeyId)?.connectionId!==t.id)throw Error("Deploy key does not belong to this connection");let r=this.idFn(),n=this.now();return this.run(`INSERT INTO source_bindings (id, project_id, environment_id, resource_id, connection_id, repository_id, repository_full_name, default_branch, branch_rule, tag_rule, monorepo_root, include_paths, exclude_paths, submodules, clone_depth, deploy_key_id, auto_deploy, pull_request_previews, status, created_by_actor_id, created_at, updated_at)
|
|
20
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, ?, ?)`,[r,e.projectId,e.environmentId??null,e.resourceId??null,e.connectionId,e.repositoryId??null,Dc(e.repositoryFullName),e.defaultBranch?.trim()||"main",e.branchRule?.trim()||null,e.tagRule?.trim()||null,Am(e.monorepoRoot??"."),mr(ps(e.includePaths)),mr(ps(e.excludePaths)),e.submodules?1:0,e.cloneDepth??null,e.deployKeyId??null,e.autoDeploy===!1?0:1,e.pullRequestPreviews===!1?0:1,e.actorId??null,n,n]),this.controlPlane.appendEvent({organizationId:t.organizationId,projectId:e.projectId,actorId:e.actorId,type:"source.binding.created",payload:{bindingId:r,connectionId:e.connectionId,repository:e.repositoryFullName,branch:e.defaultBranch??"main"}}),this.getBinding(r)}getBinding(e){let t=this.controlPlane.database.query("SELECT * FROM source_bindings WHERE id = ?").get(e);return t?Cm(t):void 0}listBindings(e={}){return this.controlPlane.database.query("SELECT * FROM source_bindings ORDER BY created_at DESC").all().map(Cm).filter((r)=>(!e.connectionId||r.connectionId===e.connectionId)&&(!e.projectId||r.projectId===e.projectId)&&(!e.status||r.status===e.status))}updateBinding(e,t,r){let n=this.getBinding(e);if(!n||n.version!==t)throw Error(`Source binding ${e} changed since version ${t}`);let i=this.getConnection(n.connectionId);if((!i||["disconnected","expired"].includes(i.status))&&(r.status==="active"||r.autoDeploy===!0))throw Error("Rotate or reconnect the source credential before enabling this binding");if(r.deployKeyId&&this.getDeployKey(r.deployKeyId)?.connectionId!==n.connectionId)throw Error("Deploy key does not belong to this connection");let o=this.now();if(this.controlPlane.database.run("UPDATE source_bindings SET default_branch=?, branch_rule=?, tag_rule=?, monorepo_root=?, include_paths=?, exclude_paths=?, submodules=?, clone_depth=?, deploy_key_id=?, auto_deploy=?, pull_request_previews=?, status=?, disabled_reason=?, version=version+1, updated_at=? WHERE id=? AND version=?",[r.defaultBranch?.trim()||n.defaultBranch,r.branchRule===void 0?n.branchRule??null:r.branchRule.trim()||null,r.tagRule===void 0?n.tagRule??null:r.tagRule.trim()||null,r.monorepoRoot===void 0?n.monorepoRoot:Am(r.monorepoRoot),mr(r.includePaths===void 0?n.includePaths:ps(r.includePaths)),mr(r.excludePaths===void 0?n.excludePaths:ps(r.excludePaths)),r.submodules??n.submodules?1:0,r.cloneDepth===void 0?n.cloneDepth??null:r.cloneDepth,r.deployKeyId===void 0?n.deployKeyId??null:r.deployKeyId,r.autoDeploy??n.autoDeploy?1:0,r.pullRequestPreviews??n.pullRequestPreviews?1:0,r.status??n.status,r.disabledReason===void 0?n.disabledReason??null:r.disabledReason.slice(0,1000),o,e,t]).changes!==1)throw Error(`Source binding ${e} changed since version ${t}`);let c=this.getConnection(n.connectionId);return this.controlPlane.appendEvent({organizationId:c.organizationId,projectId:n.projectId,actorId:r.actorId,type:"source.binding.updated",payload:{bindingId:e,fromVersion:t,toVersion:t+1,status:r.status??n.status}}),this.getBinding(e)}createWebhook(e){let t=this.getConnection(e.connectionId);if(!t||["disconnected","expired"].includes(t.status))throw Error("Active source connection was not found");if(e.repositoryId&&this.getRepository(e.repositoryId)?.connectionId!==t.id)throw Error("Repository does not belong to this connection");let r=this.idFn(),n=this.now(),i=e.endpointToken??xc(24).toString("base64url"),o=e.secret??xc(32).toString("base64url"),s=[...new Set(e.events??["push","pull_request"])].filter((c)=>["push","pull_request"].includes(c));if(!s.length)throw Error("At least one supported webhook event is required");return this.run("INSERT INTO source_webhooks (id, connection_id, repository_id, repository_full_name, endpoint_token_hash, endpoint_token_ciphertext, secret_ciphertext, events, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?)",[r,e.connectionId,e.repositoryId??null,Dc(e.repositoryFullName),On(i),this.encrypt(i),this.encrypt(o),mr(s),n,n]),this.controlPlane.appendEvent({organizationId:t.organizationId,type:"source.webhook.created",payload:{webhookId:r,connectionId:t.id,repository:e.repositoryFullName,events:s}}),{webhook:{...this.getWebhook(r),endpointToken:i},secret:o}}getWebhook(e){let t=this.controlPlane.database.query("SELECT * FROM source_webhooks WHERE id = ?").get(e);return t?Nc(t):void 0}getWebhookByEndpointToken(e){let t=this.controlPlane.database.query("SELECT * FROM source_webhooks WHERE endpoint_token_hash = ?").get(On(e));return t?Nc(t):void 0}getWebhookSecret(e){let t=this.controlPlane.database.query("SELECT secret_ciphertext FROM source_webhooks WHERE id = ?").get(e);if(!t)throw Error("Source webhook was not found");return this.decrypt(String(t.secret_ciphertext))}getWebhookEndpointToken(e){let t=this.controlPlane.database.query("SELECT endpoint_token_ciphertext FROM source_webhooks WHERE id = ?").get(e);if(!t?.endpoint_token_ciphertext)throw Error("Source webhook endpoint token is unavailable");return this.decrypt(String(t.endpoint_token_ciphertext))}listWebhooks(e){return this.controlPlane.database.query("SELECT * FROM source_webhooks WHERE connection_id = ? ORDER BY repository_full_name").all(e).map(Nc)}updateWebhookState(e,t){let r=this.getWebhook(e);if(!r)throw Error("Source webhook was not found");let n=this.now();this.run("UPDATE source_webhooks SET provider_webhook_id=COALESCE(?, provider_webhook_id), status=?, health_message=?, last_reconciled_at=COALESCE(?, last_reconciled_at), updated_at=? WHERE id=?",[t.providerWebhookId??null,t.status,t.healthMessage?.slice(0,1000)??null,t.reconciled?n:null,n,e]);let i=this.getConnection(r.connectionId);if(i)this.controlPlane.appendEvent({organizationId:i.organizationId,type:"source.webhook.updated",payload:{webhookId:e,connectionId:i.id,repository:r.repositoryFullName,status:t.status,reconciled:t.reconciled??!1,providerWebhookId:t.providerWebhookId??r.providerWebhookId??null}});return this.getWebhook(e)}getDeliveryByProviderId(e,t){let r=this.controlPlane.database.query("SELECT * FROM source_webhook_deliveries WHERE connection_id = ? AND provider_delivery_id = ?").get(e,t);return r?jc(r):void 0}recordDelivery(e){let t=this.getDeliveryByProviderId(e.connectionId,e.providerDeliveryId);if(t)return{delivery:t,duplicate:!0};let r=this.idFn(),n=this.now();return this.controlPlane.database.transaction(()=>{this.run("INSERT INTO source_webhook_deliveries (id, connection_id, webhook_id, provider_delivery_id, event, action, commit_sha, signature_status, status, payload_summary, operation_id, error, received_at, processed_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[r,e.connectionId,e.webhookId,e.providerDeliveryId,e.event.slice(0,100),e.action?.slice(0,100)??null,e.commitSha?.slice(0,128)??null,e.signatureStatus,e.status,mr(e.payloadSummary??{}),e.operationId??null,e.error?.slice(0,2000)??null,n,["enqueued","ignored","rejected","failed"].includes(e.status)?n:null]),this.run("UPDATE source_webhooks SET last_delivery_at=?, updated_at=? WHERE id=?",[n,n,e.webhookId])})(),{delivery:this.getDeliveryByProviderId(e.connectionId,e.providerDeliveryId),duplicate:!1}}updateDelivery(e,t){this.run("UPDATE source_webhook_deliveries SET status=?, operation_id=?, error=?, processed_at=? WHERE id=?",[t.status,t.operationId??null,t.error?.slice(0,2000)??null,this.now(),e]);let r=this.controlPlane.database.query("SELECT * FROM source_webhook_deliveries WHERE id = ?").get(e);if(!r)throw Error("Source webhook delivery was not found");return jc(r)}listDeliveries(e,t=100){return this.controlPlane.database.query("SELECT * FROM source_webhook_deliveries WHERE webhook_id = ? ORDER BY received_at DESC LIMIT ?").all(e,Math.min(500,Math.max(1,t))).map(jc)}disconnectConnection(e,t){let r=this.getConnection(e);if(!r)throw Error("Source connection was not found");let n=this.listBindings({connectionId:e,status:"active"}),i=this.now();return this.controlPlane.database.transaction(()=>{this.run("UPDATE source_connections SET status='disconnected', credential_ciphertext=NULL, health_message='Disconnected by an administrator', version=version+1, updated_at=? WHERE id=?",[i,e]),this.run("UPDATE source_bindings SET status='disabled', auto_deploy=0, disabled_reason='Source connection was disconnected', version=version+1, updated_at=? WHERE connection_id=? AND status='active'",[i,e]),this.run("UPDATE source_webhooks SET status='disabled', health_message='Source connection was disconnected', updated_at=? WHERE connection_id=?",[i,e])})(),this.controlPlane.appendEvent({organizationId:r.organizationId,actorId:t,type:"source.connection.disconnected",level:"warning",payload:{connectionId:e,affectedBindingIds:n.map((o)=>o.id),affectedRepositories:n.map((o)=>o.repositoryFullName)}}),{connection:this.getConnection(e),affectedBindings:n}}}import{createSign as Bw}from"node:crypto";class yi extends Error{status;retryAfterSeconds;constructor(e,t,r){super(e);this.status=t;this.retryAfterSeconds=r;this.name="SourceProviderError"}}var xm={repositories:!0,branches:!0,tags:!0,webhooks:!0,pullRequests:!0,tokenRefresh:!0,deployKeys:!0};function Xr(e){let t=Number(e??"1");return Number.isInteger(t)&&t>0?t:1}function en(e){return Math.max(1,Math.min(100,e??50))}function Vt(e){let t=e.trim().replace(/^\/+|\/+$/g,"");if(!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(t))throw Error("Repository must use owner/name format");return t}function co(e){let t=new URL(e);if(t.username||t.password||t.protocol!=="https:")throw Error("Webhook endpoint must be credential-free HTTPS");return t.href}function Tm(e){return Buffer.from(e).toString("base64url")}function Lw(e,t){if(!e.appId||!e.privateKey)throw Error("GitHub App credentials require appId and privateKey");let r=Tm(JSON.stringify({alg:"RS256",typ:"JWT"})),n=Math.floor(t.getTime()/1000)-30,i=Tm(JSON.stringify({iat:n,exp:n+540,iss:e.appId})),o=Bw("RSA-SHA256");return o.update(`${r}.${i}`),o.end(),`${r}.${i}.${o.sign(e.privateKey).toString("base64url")}`}class lo{connection;credential;capabilities=xm;fetchFn;timeoutMs;nowFn;constructor(e,t,r={}){this.connection=e;this.credential=t;this.fetchFn=r.fetch??((n,i)=>globalThis.fetch(n,i)),this.timeoutMs=Math.max(100,r.timeoutMs??20000),this.nowFn=r.now??(()=>new Date)}async request(e,t={}){let r=new URL(`${this.apiRoot().replace(/\/$/,"")}/`),n=new URL(e.replace(/^\//,""),r);if(n.origin!==r.origin)throw Error("Provider pagination cannot leave the configured host");let i=new AbortController,o=setTimeout(()=>i.abort(),this.timeoutMs);try{let s=await this.fetchFn(n,{...t,redirect:"error",signal:i.signal,headers:{Accept:"application/json","User-Agent":"ts-cloud-source/1",...await this.authorization(),...t.headers}});if(!s.ok){let c=Number(s.headers.get("retry-after")??""),d=s.headers.get("x-request-id")??s.headers.get("x-github-request-id");throw new yi(`Source provider request failed (${s.status})${d?` [request ${d}]`:""}`,s.status,Number.isFinite(c)?c:void 0)}if(s.status===204)return{data:void 0,headers:s.headers};return{data:await s.json(),headers:s.headers}}catch(s){if(s instanceof yi)throw s;if(i.signal.aborted)throw new yi(`Source provider request exceeded ${this.timeoutMs}ms`);throw new yi(s instanceof Error?s.message.replace(/(?:token|password|secret)=[^\s&]+/gi,"$1=[REDACTED]"):"Source provider request failed")}finally{clearTimeout(o)}}async deleteWebhook(e,t){await this.request(this.webhookPath(e,t),{method:"DELETE"})}}class Dm extends lo{provider="github";installationToken;apiRoot(){return this.connection.host==="https://github.com"?"https://api.github.com":`${this.connection.host}/api/v3`}async authorization(){if(this.credential?.token)return{Authorization:`Bearer ${this.credential.token}`,"X-GitHub-Api-Version":"2022-11-28"};if(!this.credential?.installationId)return{};if(!this.installationToken||this.installationToken.expiresAt<this.nowFn().getTime()+60000){let e=Lw(this.credential,this.nowFn()),t=this.apiRoot().replace(/\/$/,""),r=new AbortController,n=setTimeout(()=>r.abort(),this.timeoutMs);try{let i=await this.fetchFn(`${t}/app/installations/${encodeURIComponent(this.credential.installationId)}/access_tokens`,{method:"POST",signal:r.signal,redirect:"error",headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${e}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"ts-cloud-source/1"}});if(!i.ok)throw new yi(`GitHub App token refresh failed (${i.status})`,i.status);let o=await i.json();this.installationToken={value:o.token,expiresAt:new Date(o.expires_at).getTime()}}finally{clearTimeout(n)}}return{Authorization:`Bearer ${this.installationToken.value}`,"X-GitHub-Api-Version":"2022-11-28"}}async testConnection(){let e=this.credential?.installationId?"/installation/repositories?per_page=1":"/user",{data:t,headers:r}=await this.request(e);return{ok:!0,account:t.login??this.connection.owner,scopes:(r.get("x-oauth-scopes")??this.connection.grantedScopes.join(",")).split(",").map((n)=>n.trim()).filter(Boolean),message:"GitHub connection is healthy"}}async listRepositories(e={}){let t=en(e.limit),r=Xr(e.cursor),n=this.credential?.installationId?`/installation/repositories?per_page=${t}&page=${r}`:`/user/repos?per_page=${t}&page=${r}&sort=updated`,{data:i}=await this.request(n),o=Array.isArray(i)?i:i.repositories;return{repositories:(e.search?o.filter((c)=>c.full_name.toLowerCase().includes(e.search.toLowerCase())):o).map((c)=>({providerRepositoryId:String(c.id),fullName:c.full_name,cloneUrl:c.clone_url,defaultBranch:c.default_branch||"main",visibility:c.visibility??(c.private?"private":"public"),archived:!!c.archived,metadata:{}})),nextCursor:o.length===t?String(r+1):void 0}}async refs(e,t,r={}){let n=en(r.limit),i=Xr(r.cursor),{data:o}=await this.request(`/repos/${Vt(e)}/${t}?per_page=${n}&page=${i}`);return{refs:o.map((s)=>({name:s.name,commitSha:s.commit.sha,protected:s.protected})),nextCursor:o.length===n?String(i+1):void 0}}listBranches(e,t){return this.refs(e,"branches",t)}listTags(e,t){return this.refs(e,"tags",t)}webhookPath(e,t){return`/repos/${Vt(e)}/hooks${t?`/${encodeURIComponent(t)}`:""}`}hook(e){return{providerWebhookId:String(e.id),active:e.active,events:e.events,url:e.config.url??""}}async createWebhook(e,t){let{data:r}=await this.request(this.webhookPath(e),{method:"POST",body:JSON.stringify({name:"web",active:!0,events:t.events,config:{url:co(t.url),content_type:"json",secret:t.secret,insecure_ssl:"0"}}),headers:{"Content-Type":"application/json"}});return this.hook(r)}async listWebhooks(e){let{data:t}=await this.request(this.webhookPath(e));return t.map((r)=>this.hook(r))}async updateWebhook(e,t,r){let{data:n}=await this.request(this.webhookPath(e,t),{method:"PATCH",body:JSON.stringify({active:!0,events:r.events,config:{url:co(r.url),content_type:"json",secret:r.secret,insecure_ssl:"0"}}),headers:{"Content-Type":"application/json"}});return this.hook(n)}async setCommitStatus(e,t,r){await this.request(`/repos/${Vt(e)}/statuses/${encodeURIComponent(t)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({state:r.state,target_url:r.url,description:r.description.slice(0,140),context:r.context??"ts-cloud/preview"})})}}class Om extends lo{provider="gitlab";apiRoot(){return`${this.connection.host}/api/v4`}async authorization(){return this.credential?.token?{"PRIVATE-TOKEN":this.credential.token}:{}}async testConnection(){let{data:e}=await this.request("/user");return{ok:!0,account:e.username,scopes:this.connection.grantedScopes,message:"GitLab connection is healthy"}}async listRepositories(e={}){let t=en(e.limit),r=Xr(e.cursor),n=e.search?`&search=${encodeURIComponent(e.search)}`:"",{data:i,headers:o}=await this.request(`/projects?membership=true&simple=true&order_by=last_activity_at&per_page=${t}&page=${r}${n}`);return{repositories:i.map((s)=>({providerRepositoryId:String(s.id),fullName:s.path_with_namespace,cloneUrl:s.http_url_to_repo,defaultBranch:s.default_branch??"main",visibility:s.visibility??"unknown",archived:!!s.archived,metadata:{}})),nextCursor:o.get("x-next-page")||void 0}}async refs(e,t,r={}){let n=en(r.limit),i=Xr(r.cursor),{data:o,headers:s}=await this.request(`/projects/${encodeURIComponent(Vt(e))}/repository/${t}?per_page=${n}&page=${i}`);return{refs:o.map((c)=>({name:c.name,commitSha:c.commit.id,protected:c.protected})),nextCursor:s.get("x-next-page")||void 0}}listBranches(e,t){return this.refs(e,"branches",t)}listTags(e,t){return this.refs(e,"tags",t)}webhookPath(e,t){return`/projects/${encodeURIComponent(Vt(e))}/hooks${t?`/${encodeURIComponent(t)}`:""}`}hook(e){return{providerWebhookId:String(e.id),active:!0,events:[...e.push_events?["push"]:[],...e.merge_requests_events?["pull_request"]:[]],url:e.url}}body(e){return JSON.stringify({url:co(e.url),token:e.secret,enable_ssl_verification:!0,push_events:e.events.includes("push"),merge_requests_events:e.events.includes("pull_request")})}async createWebhook(e,t){let{data:r}=await this.request(this.webhookPath(e),{method:"POST",body:this.body(t),headers:{"Content-Type":"application/json"}});return this.hook(r)}async listWebhooks(e){let{data:t}=await this.request(this.webhookPath(e));return t.map((r)=>this.hook(r))}async updateWebhook(e,t,r){let{data:n}=await this.request(this.webhookPath(e,t),{method:"PUT",body:this.body(r),headers:{"Content-Type":"application/json"}});return this.hook(n)}async setCommitStatus(e,t,r){let n=r.state==="failure"||r.state==="error"?"failed":r.state;await this.request(`/projects/${encodeURIComponent(Vt(e))}/statuses/${encodeURIComponent(t)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({state:n,target_url:r.url,description:r.description.slice(0,255),name:r.context??"ts-cloud/preview"})})}}class $m extends lo{provider="bitbucket";apiRoot(){return this.connection.host==="https://bitbucket.org"?"https://api.bitbucket.org/2.0":`${this.connection.host}/2.0`}async authorization(){return this.credential?.token?{Authorization:`Bearer ${this.credential.token}`}:{}}async testConnection(){let{data:e}=await this.request("/user");return{ok:!0,account:e.username??e.display_name,scopes:this.connection.grantedScopes,message:"Bitbucket connection is healthy"}}async listRepositories(e={}){if(!this.connection.owner)throw Error("Bitbucket repository discovery requires an owner/workspace");let t=Xr(e.cursor),r=en(e.limit),n=e.search?`&q=name~%22${encodeURIComponent(e.search)}%22`:"",{data:i}=await this.request(`/repositories/${encodeURIComponent(this.connection.owner)}?pagelen=${r}&page=${t}${n}`);return{repositories:i.values.map((o)=>({providerRepositoryId:o.uuid,fullName:o.full_name,cloneUrl:o.links.clone.find((s)=>s.name==="https")?.href??o.links.clone[0]?.href??"",defaultBranch:o.mainbranch?.name??"main",visibility:o.is_private?"private":"public",archived:!1,metadata:{}})),nextCursor:i.next?String(t+1):void 0}}async refs(e,t,r={}){let n=Xr(r.cursor),i=en(r.limit),{data:o}=await this.request(`/repositories/${Vt(e)}/refs/${t}?pagelen=${i}&page=${n}`);return{refs:o.values.map((s)=>({name:s.name,commitSha:s.target.hash})),nextCursor:o.next?String(n+1):void 0}}listBranches(e,t){return this.refs(e,"branches",t)}listTags(e,t){return this.refs(e,"tags",t)}webhookPath(e,t){return`/repositories/${Vt(e)}/hooks${t?`/${encodeURIComponent(t)}`:""}`}hook(e){return{providerWebhookId:e.uuid,active:e.active,events:e.events.map((t)=>t.replace("repo:push","push").replace("pullrequest:","pull_request:")),url:e.url}}body(e){return JSON.stringify({description:"ts-cloud deploy",url:co(e.url),active:!0,events:e.events.map((t)=>t==="push"?"repo:push":t.replace("pull_request:","pullrequest:"))})}async createWebhook(e,t){let{data:r}=await this.request(this.webhookPath(e),{method:"POST",body:this.body(t),headers:{"Content-Type":"application/json"}});return this.hook(r)}async listWebhooks(e){let{data:t}=await this.request(this.webhookPath(e));return t.values.map((r)=>this.hook(r))}async updateWebhook(e,t,r){let{data:n}=await this.request(this.webhookPath(e,t),{method:"PUT",body:this.body(r),headers:{"Content-Type":"application/json"}});return this.hook(n)}async setCommitStatus(e,t,r){let n=r.state==="success"?"SUCCESSFUL":r.state==="pending"?"INPROGRESS":"FAILED";await this.request(`/repositories/${Vt(e)}/commit/${encodeURIComponent(t)}/statuses/build/ts-cloud-preview`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({state:n,key:"ts-cloud-preview",name:r.context??"ts-cloud/preview",url:r.url,description:r.description.slice(0,255)})})}}class Nm extends lo{provider="gitea";capabilities={...xm,tokenRefresh:!1};apiRoot(){return`${this.connection.host}/api/v1`}async authorization(){return this.credential?.token?{Authorization:`token ${this.credential.token}`}:{}}async testConnection(){let{data:e}=await this.request("/user");return{ok:!0,account:e.login,scopes:this.connection.grantedScopes,message:"Gitea connection is healthy"}}async listRepositories(e={}){let t=Xr(e.cursor),r=en(e.limit),n=e.search?`/repos/search?q=${encodeURIComponent(e.search)}&limit=${r}&page=${t}`:`/user/repos?limit=${r}&page=${t}`,{data:i,headers:o}=await this.request(n),s=Array.isArray(i)?i:i.data;return{repositories:s.map((c)=>({providerRepositoryId:String(c.id),fullName:c.full_name,cloneUrl:c.clone_url,defaultBranch:c.default_branch??"main",visibility:c.private?"private":"public",archived:!!c.archived,metadata:{}})),nextCursor:o.get("x-hasmore")==="true"||s.length===r?String(t+1):void 0}}async refs(e,t,r={}){let n=Xr(r.cursor),i=en(r.limit),{data:o}=await this.request(`/repos/${Vt(e)}/${t}?limit=${i}&page=${n}`);return{refs:o.map((s)=>({name:s.name,commitSha:s.commit.id})),nextCursor:o.length===i?String(n+1):void 0}}listBranches(e,t){return this.refs(e,"branches",t)}listTags(e,t){return this.refs(e,"tags",t)}webhookPath(e,t){return`/repos/${Vt(e)}/hooks${t?`/${encodeURIComponent(t)}`:""}`}hook(e){return{providerWebhookId:String(e.id),active:e.active,events:e.events??[],url:e.config.url??""}}body(e){return JSON.stringify({type:"gitea",active:!0,events:e.events,config:{url:co(e.url),content_type:"json",secret:e.secret,insecure_ssl:"0"}})}async createWebhook(e,t){let{data:r}=await this.request(this.webhookPath(e),{method:"POST",body:this.body(t),headers:{"Content-Type":"application/json"}});return this.hook(r)}async listWebhooks(e){let{data:t}=await this.request(this.webhookPath(e));return t.map((r)=>this.hook(r))}async updateWebhook(e,t,r){let{data:n}=await this.request(this.webhookPath(e,t),{method:"PATCH",body:this.body(r),headers:{"Content-Type":"application/json"}});return this.hook(n)}async setCommitStatus(e,t,r){await this.request(`/repos/${Vt(e)}/statuses/${encodeURIComponent(t)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({state:r.state,target_url:r.url,description:r.description.slice(0,140),context:r.context??"ts-cloud/preview"})})}}function tn(e,t,r={}){switch(e.provider){case"github":return new Dm(e,t,r);case"gitlab":return new Om(e,t,r);case"bitbucket":return new $m(e,t,r);case"gitea":return new Nm(e,t,r);default:throw Error(`${e.provider} uses bounded Git discovery instead of a hosted provider API`)}}import{createHmac as Fw,timingSafeEqual as zw}from"node:crypto";function It(e,t){if(e instanceof Headers)return e.get(t)??void 0;return Object.entries(e).find(([n])=>n.toLowerCase()===t.toLowerCase())?.[1]}function jm(e,t){let r=Buffer.from(e),n=Buffer.from(t);return r.length===n.length&&zw(r,n)}function Uw(e,t){return Fw("sha256",e).update(t).digest("hex")}function qw(e,t,r,n,i){if(e==="gitlab")return jm(It(r,"x-gitlab-token")??"",t);let o=e==="github"?It(r,"x-hub-signature-256"):e==="gitea"?It(r,"x-gitea-signature"):It(r,"x-hub-signature")??It(r,"x-ts-cloud-signature");if(!o)return!1;if(e==="generic_https"||e==="generic_ssh"){let s=Number(It(r,"x-ts-cloud-timestamp"));if(!Number.isFinite(s)||Math.abs(i.getTime()-s*1000)>300000)return!1}return jm(o.replace(/^sha256=/,""),Uw(t,n))}function Vw(e,t){return{github:["x-github-delivery"],gitlab:["x-gitlab-event-uuid","x-request-id"],bitbucket:["x-request-uuid"],gitea:["x-gitea-delivery"],generic_https:["x-ts-cloud-delivery"],generic_ssh:["x-ts-cloud-delivery"]}[e].map((n)=>It(t,n)?.trim()).find(Boolean)}function rn(e){let t=String(e??"").trim().replace(/^\/+|\/+$/g,"");return/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(t)?t:""}function Bc(e){return[...new Set(e.flatMap((t)=>{if(!t||typeof t!=="object")return[];let r=t;return[...r.added??[],...r.modified??[],...r.removed??[]].map(String)}).filter((t)=>t&&!t.includes("\x00")).slice(0,500))]}function Ww(e,t,r){let n=e,i=t,o=r;if(n==="github"){let s=It(i,"x-github-event"),c=rn(o.repository?.full_name);if(s==="push")return{event:"push",repository:c,ref:String(o.ref??""),branch:String(o.ref??"").replace(/^refs\/heads\//,""),tag:String(o.ref??"").startsWith("refs/tags/")?String(o.ref).replace(/^refs\/tags\//,""):void 0,commitSha:String(o.after??o.head_commit?.id??""),changedPaths:Bc(o.commits??[]),deleted:o.deleted===!0||/^0{40,64}$/.test(String(o.after??""))};if(s==="pull_request")return{event:"pull_request",action:String(o.action??""),repository:c,branch:String(o.pull_request?.head?.ref??""),commitSha:String(o.pull_request?.head?.sha??""),changedPaths:[],pullRequestNumber:Number(o.number)||void 0,fork:rn(o.pull_request?.head?.repo?.full_name)!==c}}if(n==="gitlab"){let s=String(o.object_kind??"").toLowerCase(),c=rn(o.project?.path_with_namespace);if(s==="push"||s==="tag_push")return{event:"push",repository:c,ref:String(o.ref??""),branch:String(o.ref??"").replace(/^refs\/heads\//,""),tag:s==="tag_push"?String(o.ref??"").replace(/^refs\/tags\//,""):void 0,commitSha:String(o.checkout_sha??o.after??""),changedPaths:Bc(o.commits??[]),deleted:/^0{40,64}$/.test(String(o.after??""))};if(s==="merge_request")return{event:"pull_request",action:String(o.object_attributes?.action??o.object_attributes?.state??""),repository:c,branch:String(o.object_attributes?.source_branch??""),commitSha:String(o.object_attributes?.last_commit?.id??""),changedPaths:[],pullRequestNumber:Number(o.object_attributes?.iid)||void 0,fork:o.object_attributes?.source_project_id!==o.object_attributes?.target_project_id}}if(n==="bitbucket"){let s=It(i,"x-event-key")??"",c=rn(o.repository?.full_name);if(s==="repo:push"){let d=o.push?.changes?.[0]??{},a=d.new??d.old??{},u=d.new?.target??d.old?.target;return{event:"push",repository:c,ref:String(a.name??""),branch:a.type==="branch"?String(a.name):void 0,tag:a.type==="tag"?String(a.name):void 0,commitSha:String(u?.hash??""),changedPaths:[],deleted:d.closed===!0||d.new==null}}if(s.startsWith("pullrequest:"))return{event:"pull_request",action:s.replace("pullrequest:",""),repository:c,branch:String(o.pullrequest?.source?.branch?.name??""),commitSha:String(o.pullrequest?.source?.commit?.hash??""),changedPaths:[],pullRequestNumber:Number(o.pullrequest?.id)||void 0,fork:rn(o.pullrequest?.source?.repository?.full_name)!==c}}if(n==="gitea"){let s=It(i,"x-gitea-event"),c=rn(o.repository?.full_name);if(s==="push")return{event:"push",repository:c,ref:String(o.ref??""),branch:String(o.ref??"").replace(/^refs\/heads\//,""),tag:String(o.ref??"").startsWith("refs/tags/")?String(o.ref).replace(/^refs\/tags\//,""):void 0,commitSha:String(o.after??""),changedPaths:Bc(o.commits??[]),deleted:o.deleted===!0||/^0{40,64}$/.test(String(o.after??""))};if(s==="pull_request")return{event:"pull_request",action:String(o.action??""),repository:c,branch:String(o.pull_request?.head?.ref??""),commitSha:String(o.pull_request?.head?.sha??""),changedPaths:[],pullRequestNumber:Number(o.number)||void 0,fork:rn(o.pull_request?.head?.repo?.full_name)!==c}}if(n==="generic_https"||n==="generic_ssh"){if(o.event!=="push"&&o.event!=="pull_request")return;return{event:o.event,action:typeof o.action==="string"?o.action:void 0,repository:rn(o.repository),ref:typeof o.ref==="string"?o.ref:void 0,branch:typeof o.branch==="string"?o.branch:void 0,tag:typeof o.tag==="string"?o.tag:void 0,commitSha:String(o.commitSha??""),changedPaths:Array.isArray(o.changedPaths)?o.changedPaths.map(String).slice(0,500):[],pullRequestNumber:Number(o.pullRequestNumber)||void 0,fork:o.fork===!0,deleted:o.deleted===!0}}return}function vi(e,t){let r="^";for(let n=0;n<t.length;n++){let i=t[n];if(i==="*"&&t[n+1]==="*")r+=".*",n++;else if(i==="*")r+="[^/]*";else if(i==="?")r+="[^/]";else r+=i.replace(/[|\\{}()[\]^$+?.]/g,"\\$&")}return new RegExp(`${r}$`).test(e)}function Hw(e,t){if(t.event==="pull_request")return e.pullRequestPreviews;if(!e.autoDeploy)return!1;if(t.tag)return!!e.tagRule&&vi(t.tag,e.tagRule);return vi(t.branch??"",e.branchRule??e.defaultBranch)}function Kw(e,t){if(!t.length)return!0;return t.filter((n)=>!e.excludePaths.some((i)=>vi(n,i))).some((n)=>!e.includePaths.length||e.includePaths.some((i)=>vi(n,i)))}function Mm(e,t){return It(t,e==="github"?"x-github-event":e==="gitlab"?"x-gitlab-event":e==="bitbucket"?"x-event-key":e==="gitea"?"x-gitea-event":"x-ts-cloud-event")??"unknown"}function Nn(){return{accepted:!1,duplicate:!1,status:"rejected",operations:[],message:"Webhook unavailable"}}async function Lm(e){if(e.rawBody.byteLength>2097152)return Nn();let t=e.sources.getWebhookByEndpointToken(e.endpointToken);if(!t||t.status==="disabled")return Nn();let r=e.sources.getConnection(t.connectionId);if(!r||r.status==="disconnected"||r.status==="expired")return Nn();let n=Vw(r.provider,e.headers);if(!n||n.length>200)return Nn();if(!qw(r.provider,e.sources.getWebhookSecret(t.id),e.headers,e.rawBody,e.now??new Date))return e.sources.recordDelivery({connectionId:r.id,webhookId:t.id,providerDeliveryId:n,event:Mm(r.provider,e.headers),signatureStatus:It(e.headers,"x-hub-signature-256")||It(e.headers,"x-gitlab-token")||It(e.headers,"x-hub-signature")||It(e.headers,"x-gitea-signature")?"invalid":"missing",status:"rejected",error:"Webhook signature verification failed"}),Nn();let o;try{o=JSON.parse(new TextDecoder().decode(e.rawBody))}catch{return Nn()}let s=Ww(r.provider,e.headers,o);if(!s||!s.repository||!/^[a-f0-9]{7,64}$/i.test(s.commitSha))return e.sources.recordDelivery({connectionId:r.id,webhookId:t.id,providerDeliveryId:n,event:Mm(r.provider,e.headers),signatureStatus:"verified",status:"rejected",error:"Unsupported or malformed source event"}),Nn();let c=e.sources.recordDelivery({connectionId:r.id,webhookId:t.id,providerDeliveryId:n,event:s.event,action:s.action,commitSha:s.commitSha,signatureStatus:"verified",status:"accepted",payloadSummary:{repository:s.repository,ref:s.ref??null,branch:s.branch??null,tag:s.tag??null,commitSha:s.commitSha,pullRequestNumber:s.pullRequestNumber??null,changedPathCount:s.changedPaths.length}});if(c.duplicate&&c.delivery.status!=="accepted")return{accepted:!0,duplicate:!0,status:"duplicate",operations:[],message:"Delivery already processed"};let d=new Bm(e.controlPlane),a=e.sources.listBindings({connectionId:r.id,status:"active"}).filter((y)=>{if(y.repositoryFullName.toLowerCase()!==s.repository.toLowerCase()||!Kw(y,s.changedPaths))return!1;let w=y.resourceId?d.getDefinitionForResource(y.resourceId):void 0,k=s.event==="push"&&!!w?.branchRule&&!!s.branch&&vi(s.branch,w.branchRule);return Hw(y,s)||k});if(!a.length)return e.sources.updateDelivery(c.delivery.id,{status:"ignored"}),{accepted:!0,duplicate:c.duplicate,status:"ignored",operations:[],message:"Verified event did not match an active deployment rule"};let u=new $e(e.controlPlane),m=new Set(["closed","merged","declined"]),h=a.flatMap((y)=>{if(s.event==="push"&&y.resourceId&&s.branch){let k=d.getDefinitionForResource(y.resourceId);if(k?.branchRule&&vi(s.branch,k.branchRule)){let C=d.findForBranch(k.id,s.repository,s.branch);if(s.deleted){if(!k.cleanupOnClose||!C||C.status==="destroyed")return[];let O=u.enqueue({projectId:y.projectId,environmentId:y.environmentId,resourceId:y.resourceId,kind:"preview.destroy",idempotencyKey:`preview:${C.id}:branch-delete:${n}`,correlationId:`preview:${C.id}`,input:{previewId:C.id,reason:"branch_deleted",source:{repository:s.repository,commitSha:s.commitSha,branch:s.branch}},lockKey:`preview:${C.id}`,providerKey:r.provider,maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;return d.transition(C.id,"queued",{operationId:O.id}),[O]}let T=d.upsert({definitionId:k.id,sourceProvider:r.provider,repository:s.repository,branch:s.branch,commitSha:s.commitSha});if(!T.changed)return[];let j=T.created?"preview.create":"preview.update",P=u.enqueue({projectId:y.projectId,environmentId:y.environmentId,resourceId:y.resourceId,kind:j,idempotencyKey:`preview:${T.preview.id}:${s.commitSha}`,correlationId:`preview:${T.preview.id}`,input:{previewId:T.preview.id,source:{connectionId:r.id,bindingId:y.id,repository:s.repository,commitSha:s.commitSha,branch:s.branch,monorepoRoot:y.monorepoRoot,submodules:y.submodules,cloneDepth:y.cloneDepth??null}},lockKey:`preview:${T.preview.id}`,providerKey:r.provider,buildSlot:!0,maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;return d.transition(T.preview.id,"queued",{operationId:P.id}),[P]}}if(s.event==="pull_request"&&y.resourceId&&s.pullRequestNumber){let k=d.getDefinitionForResource(y.resourceId);if(k){let C=m.has(String(s.action??"").toLowerCase()),T=d.findForPullRequest(k.id,s.repository,s.pullRequestNumber);if(C){if(!k.cleanupOnClose||!T||T.status==="destroyed")return[];let j=u.enqueue({projectId:y.projectId,environmentId:y.environmentId,resourceId:y.resourceId,kind:"preview.destroy",idempotencyKey:`preview:${T.id}:destroy:${n}`,correlationId:`preview:${T.id}`,input:{previewId:T.id,reason:"pull_request_closed",source:{repository:s.repository,commitSha:s.commitSha,branch:s.branch??null,pullRequestNumber:s.pullRequestNumber}},lockKey:`preview:${T.id}`,providerKey:r.provider,maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;return d.transition(T.id,"queued",{operationId:j.id}),[j]}try{let j=d.upsert({definitionId:k.id,sourceProvider:r.provider,repository:s.repository,branch:s.branch??`pr-${s.pullRequestNumber}`,pullRequestNumber:s.pullRequestNumber,fork:s.fork,commitSha:s.commitSha});if(!j.changed)return[];let P=j.created?"preview.create":"preview.update",O=u.enqueue({projectId:y.projectId,environmentId:y.environmentId,resourceId:y.resourceId,kind:P,idempotencyKey:`preview:${j.preview.id}:${s.commitSha}`,correlationId:`preview:${j.preview.id}`,input:{previewId:j.preview.id,source:{connectionId:r.id,bindingId:y.id,repository:s.repository,commitSha:s.commitSha,branch:s.branch??null,pullRequestNumber:s.pullRequestNumber,fork:!!s.fork,monorepoRoot:y.monorepoRoot,submodules:y.submodules,cloneDepth:y.cloneDepth??null},inheritedSecretNames:j.inheritedSecrets},lockKey:`preview:${j.preview.id}`,providerKey:r.provider,buildSlot:!0,maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;return d.transition(j.preview.id,"queued",{operationId:O.id}),[O]}catch(j){return e.controlPlane.appendEvent({projectId:y.projectId,resourceId:y.resourceId,type:"preview.rejected",level:"warning",payload:{repository:s.repository,pullRequestNumber:s.pullRequestNumber,fork:!!s.fork,reason:j instanceof Error?j.message:String(j)}}),[]}}}let w=s.event==="pull_request"?"deploy.preview":"deploy.source";return[u.enqueue({projectId:y.projectId,environmentId:y.environmentId,resourceId:y.resourceId,kind:w,idempotencyKey:`source:${r.id}:${n}:${y.id}:${s.commitSha}`,correlationId:`source:${n}`,input:{source:{connectionId:r.id,bindingId:y.id,repository:s.repository,commitSha:s.commitSha,branch:s.branch??null,tag:s.tag??null,monorepoRoot:y.monorepoRoot,submodules:y.submodules,cloneDepth:y.cloneDepth??null},preview:s.event==="pull_request"?{number:s.pullRequestNumber??null,action:s.action??null}:null},lockKey:y.resourceId?`resource:${y.resourceId}`:`environment:${y.environmentId??y.projectId}`,providerKey:r.provider,buildSlot:!0,maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:s.event==="pull_request"?14:90}).operation]});if(!h.length)return e.sources.updateDelivery(c.delivery.id,{status:"ignored"}),{accepted:!0,duplicate:c.duplicate,status:"ignored",operations:[],message:"Verified event required no preview lifecycle change"};return e.sources.updateDelivery(c.delivery.id,{status:"enqueued",operationId:h[0]?.id}),e.controlPlane.appendEvent({organizationId:r.organizationId,projectId:a[0]?.projectId,operationId:h[0]?.id,type:"source.webhook.enqueued",payload:{webhookId:t.id,deliveryId:c.delivery.id,repository:s.repository,commitSha:s.commitSha,operationIds:h.map((y)=>y.id)}}),{accepted:!0,duplicate:c.duplicate,status:"enqueued",operations:h,message:`${h.length} deployment operation${h.length===1?"":"s"} enqueued`}}function bi(e,t){if(!t.endpointToken)throw Error("The webhook endpoint token is only available at creation time");let r=new URL(e);if(r.protocol!=="https:"&&!["localhost","127.0.0.1","::1"].includes(r.hostname))throw Error("Webhook base URL must use HTTPS");return new URL(`/api/source/webhooks/${encodeURIComponent(t.endpointToken)}`,r).href}import{chmodSync as Fm,mkdtempSync as Jw,rmSync as Gw,writeFileSync as zm}from"node:fs";import{tmpdir as Qw}from"node:os";import{join as ms,resolve as Yw}from"node:path";function qm(e,t){let r=e.trim();if(/\r|\n|\0/.test(r))throw Error("Git remote contains control characters");if(r.startsWith("https://")){let i=new URL(r);if(i.username||i.password||i.search||i.hash)throw Error("HTTPS Git remotes cannot contain credentials, queries, or fragments");return i.href}let n=r.startsWith("ssh://")?new URL(r).hostname:r.match(/^git@([A-Za-z0-9.-]+):/)?.[1];if(!n)throw Error("Git remote must use credential-free HTTPS or SSH");if(!t||t.host.toLowerCase()!==n.toLowerCase())throw Error("SSH Git remote requires a deploy key with a pinned key for the same host");return r}function Zw(e,t,r){let n=e.replaceAll(t,"[REMOTE]").slice(0,4000);for(let i of[r?.token,r?.privateKey])if(i)n=n.replaceAll(i,"[REDACTED]");return n}function Xw(e){let t={PATH:process.env.PATH??"/usr/local/bin:/usr/bin:/bin",HOME:"/nonexistent",GIT_TERMINAL_PROMPT:"0",GIT_CONFIG_NOSYSTEM:"1",GIT_OPTIONAL_LOCKS:"0"},r;if(e.credential?.token){let n=e.credential.username??"oauth2";t.GIT_CONFIG_COUNT="1",t.GIT_CONFIG_KEY_0="http.extraHeader",t.GIT_CONFIG_VALUE_0=`Authorization: Basic ${Buffer.from(`${n}:${e.credential.token}`).toString("base64")}`}if(e.deployKey){r=Jw(ms(Qw(),"ts-cloud-git-transport-"));let n=ms(r,"key"),i=ms(r,"known_hosts");zm(n,e.deployKey.privateKey,{mode:384}),zm(i,`${e.deployKey.host} ${e.deployKey.hostKey}
|
|
21
|
+
`,{mode:384}),Fm(n,384),Fm(i,384),t.GIT_SSH_COMMAND=`ssh -i ${n} -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes -o UserKnownHostsFile=${i} -o GlobalKnownHostsFile=/dev/null -o BatchMode=yes`}return{env:t,cleanup:()=>{if(r)Gw(r,{recursive:!0,force:!0})}}}async function jn(e,t,r){let n=Xw(r),i=Bun.spawn([r.executable??"git",...e],{stdout:"pipe",stderr:"pipe",env:n.env}),o=Math.max(100,r.timeoutMs??120000),s,c=new Promise((d,a)=>{s=setTimeout(()=>{i.kill(),a(Error(`Git operation exceeded ${o}ms`))},o)});try{let d=Promise.all([i.exited,new Response(i.stdout).text(),new Response(i.stderr).text()]),[a,u,m]=await Promise.race([d,c]);if(a!==0)throw Error(Zw(m||`Git exited with ${a}`,t,r.credential));return u}finally{if(s)clearTimeout(s);n.cleanup()}}function Um(e,t){let r=new Map;for(let n of e.split(`
|
|
22
|
+
`)){let i=n.trim().match(/^([a-f0-9]{40,64})\s+(.+)$/i);if(!i||!i[2].startsWith(t)||i[2].endsWith("^{}"))continue;let o=i[2].slice(t.length);r.set(o,{name:o,commitSha:i[1]})}return[...r.values()].sort((n,i)=>n.name.localeCompare(i.name))}async function Lc(e,t={}){let r=qm(e,t.deployKey),n=await jn(["ls-remote","--heads","--tags","--",r],r,t);return{branches:Um(n,"refs/heads/"),tags:Um(n,"refs/tags/")}}async function Fc(e,t={}){let r=qm(e.remote,t.deployKey),n=Yw(e.destination),i=e.ref?.trim()||e.binding.defaultBranch;if(!/^[A-Za-z0-9._/-]{1,255}$/.test(i)||i.startsWith("-")||i.includes(".."))throw Error("Git ref contains unsupported characters");let o=["clone","--no-tags","--single-branch","--branch",i],s=[...new Set(e.sparsePaths??[])];if(s.some((d)=>!d||d.startsWith("/")||d.split("/").includes("..")||/[\0\r\n]/.test(d)))throw Error("Sparse checkout paths must stay inside the repository");if(s.length)o.push("--filter=blob:none","--no-checkout");if(e.binding.cloneDepth)o.push("--depth",String(e.binding.cloneDepth));if(e.binding.submodules)o.push("--recurse-submodules","--shallow-submodules");if(o.push("--",r,n),await jn(o,r,t),s.length)await jn(["-C",n,"sparse-checkout","set","--cone","--",...s],r,t),await jn(["-C",n,"checkout","--force"],r,t);if(e.commitSha){if(!/^[a-f0-9]{40,64}$/i.test(e.commitSha))throw Error("Expected source commit must be an immutable 40-64 character SHA");await jn(["-C",n,"fetch","--no-tags","--depth","1","origin",e.commitSha],r,t),await jn(["-C",n,"checkout","--detach","--force",e.commitSha],r,t)}let c=(await jn(["-C",n,"rev-parse","HEAD"],r,t)).trim();if(!/^[a-f0-9]{40,64}$/i.test(c))throw Error("Git clone did not produce a valid commit SHA");if(e.commitSha&&c.toLowerCase()!==e.commitSha.toLowerCase())throw Error(`Git checkout resolved ${c} instead of the requested immutable commit`);return{directory:e.binding.monorepoRoot==="."?n:ms(n,e.binding.monorepoRoot),commitSha:c}}function uo(e){return["github","gitlab","bitbucket","gitea"].includes(e)}async function zc(e,t,r){let n=e.getConnection(t);if(!n||["disconnected","expired"].includes(n.status))throw Error("Active source connection was not found");try{if(uo(n.provider)){let s=await tn(n,e.getCredential(n.id)).testConnection();return e.updateHealth(n.id,{status:s.ok?"healthy":"degraded",message:s.message,tested:!0,grantedScopes:s.scopes})}let i=r?e.getRepository(r):e.listRepositories(n.id,void 0,1)[0];if(!i)return e.updateHealth(n.id,{status:"degraded",message:"Add a repository URL before testing this generic connection.",tested:!0});let o=n.provider==="generic_ssh"?e.listBindings({connectionId:n.id}).map((s)=>s.deployKeyId).filter(Boolean).map((s)=>e.getDeployKey(s)).find(Boolean):void 0;return await Lc(i.cloneUrl,{credential:e.getCredential(n.id),deployKey:o?{...o,privateKey:e.getDeployPrivateKey(o.id)}:void 0}),e.updateHealth(n.id,{status:"healthy",message:"Git repository access is healthy.",tested:!0})}catch(i){return e.updateHealth(n.id,{status:"degraded",message:i instanceof Error?i.message:"Connection test failed",tested:!0})}}async function gs(e,t,r={}){let n=e.getConnection(t);if(!n||!uo(n.provider)||["disconnected","expired"].includes(n.status))throw Error("A hosted active source connection is required for repository discovery");let i=tn(n,e.getCredential(n.id)),o=[],s;for(let c=0;c<Math.min(20,Math.max(1,r.maxPages??10));c++){let d=await i.listRepositories({cursor:s,search:r.search,limit:100});for(let a of d.repositories)o.push(e.upsertRepository({connectionId:n.id,...a}));if(s=d.nextCursor,!s)break}return e.updateHealth(n.id,{status:"healthy",message:`${o.length} repositories synchronized.`,synced:!0}),o}async function fs(e,t){let r=e.getConnection(t.connectionId);if(!r||["disconnected","expired"].includes(r.status))throw Error("Active source connection was not found");if(uo(r.provider)){let c=tn(r,e.getCredential(r.id));return t.type==="tags"?c.listTags(t.repository,t):c.listBranches(t.repository,t)}let n=t.repositoryId?e.getRepository(t.repositoryId):e.listRepositories(r.id).find((c)=>c.fullName===t.repository);if(!n||n.connectionId!==r.id)throw Error("Generic repository metadata was not found");let i=t.deployKeyId?e.getDeployKey(t.deployKeyId):void 0;if(i&&i.connectionId!==r.id)throw Error("Deploy key does not belong to this connection");let o=await Lc(n.cloneUrl,{credential:e.getCredential(r.id),deployKey:i?{...i,privateKey:e.getDeployPrivateKey(i.id)}:void 0});return{refs:(t.type==="tags"?o.tags:o.branches).slice(0,Math.min(500,t.limit??100))}}async function po(e,t,r){let n=e.getWebhook(t),i=n?e.getConnection(n.connectionId):void 0;if(!n||!i||["disconnected","expired"].includes(i.status))throw Error("Active source webhook was not found");let o=bi(r,{...n,endpointToken:e.getWebhookEndpointToken(n.id)});if(!uo(i.provider))return e.updateWebhookState(n.id,{status:"healthy",healthMessage:"Manual webhook endpoint is ready.",reconciled:!0});try{let s=tn(i,e.getCredential(i.id)),c=e.getWebhookSecret(n.id),d=n.providerWebhookId?await s.updateWebhook(n.repositoryFullName,n.providerWebhookId,{url:o,secret:c,events:n.events}):await s.createWebhook(n.repositoryFullName,{url:o,secret:c,events:n.events});return e.updateWebhookState(n.id,{providerWebhookId:d.providerWebhookId,status:d.active?"healthy":"degraded",healthMessage:d.active?"Provider webhook is synchronized.":"Provider webhook exists but is inactive.",reconciled:!0})}catch(s){return e.updateWebhookState(n.id,{status:"degraded",healthMessage:s instanceof Error?s.message:"Webhook reconciliation failed",reconciled:!0})}}async function Vm(e,t){let r=e.getWebhook(t),n=r?e.getConnection(r.connectionId):void 0;if(!r||!n)throw Error("Source webhook was not found");if(uo(n.provider)&&r.providerWebhookId&&!["disconnected","expired"].includes(n.status))await tn(n,e.getCredential(n.id)).deleteWebhook(r.repositoryFullName,r.providerWebhookId);return e.updateWebhookState(r.id,{status:"disabled",healthMessage:"Webhook disabled."})}var hs="1.6.0";function Uc(){let e={type:"object",required:["error"],properties:{error:{type:"object",required:["code","message","requestId"],properties:{code:{type:"string"},message:{type:"string"},requestId:{type:"string",format:"uuid"},details:{}}}}},t=(n)=>({type:"object",required:["data","page","requestId"],properties:{data:{type:"array",items:n},page:{type:"object",required:["hasMore"],properties:{nextCursor:{type:"string"},hasMore:{type:"boolean"}}},requestId:{type:"string",format:"uuid"}}}),r=(n)=>({"200":{description:"A stable cursor page.",content:{"application/json":{schema:t(n)}}},default:{$ref:"#/components/responses/Error"}});return{openapi:"3.1.0",info:{title:"ts-cloud API",version:hs,description:"Additive changes are released within v1. Breaking request or response changes require a new URL version."},servers:[{url:"/"}],security:[{bearerAuth:[]}],paths:{...Wm(),"/api/v1/projects":{get:{operationId:"listProjects",summary:"List accessible projects",parameters:[{$ref:"#/components/parameters/Limit"},{$ref:"#/components/parameters/Cursor"}],responses:r({$ref:"#/components/schemas/Project"})}},"/api/v1/projects/{projectId}/environments":{get:{operationId:"listEnvironments",summary:"List accessible project environments",parameters:[{$ref:"#/components/parameters/ProjectId"},{$ref:"#/components/parameters/Limit"},{$ref:"#/components/parameters/Cursor"}],responses:r({$ref:"#/components/schemas/Environment"})}},"/api/v1/services":{get:{operationId:"listServices",summary:"List accessible services",parameters:[{name:"projectId",in:"query",required:!0,schema:{type:"string"}},{name:"environmentId",in:"query",schema:{type:"string"}},{$ref:"#/components/parameters/Limit"},{$ref:"#/components/parameters/Cursor"}],responses:r({$ref:"#/components/schemas/Service"})}},"/api/v1/source/connections":{get:{operationId:"listSourceConnections",summary:"List safe Git connection metadata",parameters:[{$ref:"#/components/parameters/Limit"},{$ref:"#/components/parameters/Cursor"}],responses:r({$ref:"#/components/schemas/SourceConnection"})},post:{operationId:"createSourceConnection",summary:"Create an encrypted Git connection",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["provider","name","host"],properties:{provider:{type:"string",enum:["github","gitlab","bitbucket","gitea","generic_https","generic_ssh"]},name:{type:"string"},host:{type:"string",format:"uri"},token:{type:"string",writeOnly:!0},repositoryFullName:{type:"string"},repositoryUrl:{type:"string"}}}}}},responses:{"201":{description:"Encrypted connection created."},default:{$ref:"#/components/responses/Error"}}},delete:{operationId:"disconnectSourceConnection",summary:"Preview or safely disconnect a Git connection",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["id"],properties:{id:{type:"string"},preview:{type:"boolean"}}}}}},responses:{"200":{description:"Impact preview or disconnected connection."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/source/repositories":{get:{operationId:"listSourceRepositories",summary:"List or synchronize granted repositories",parameters:[{name:"connectionId",in:"query",required:!0,schema:{type:"string"}},{name:"sync",in:"query",schema:{type:"boolean"}},{name:"search",in:"query",schema:{type:"string"}},{$ref:"#/components/parameters/Limit"},{$ref:"#/components/parameters/Cursor"}],responses:r({$ref:"#/components/schemas/SourceRepository"})}},"/api/v1/source/refs":{get:{operationId:"listSourceRefs",summary:"List repository branches or tags",parameters:[{name:"connectionId",in:"query",required:!0,schema:{type:"string"}},{name:"repository",in:"query",required:!0,schema:{type:"string"}},{name:"repositoryId",in:"query",schema:{type:"string"}},{name:"type",in:"query",schema:{type:"string",enum:["branches","tags"]}}],responses:{"200":{description:"Provider reference page."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/source/bindings":{post:{operationId:"createSourceBinding",summary:"Bind a repository to an application",requestBody:{required:!0,content:{"application/json":{schema:{$ref:"#/components/schemas/SourceBindingRequest"}}}},responses:{"201":{description:"Source binding created."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/source/webhooks":{post:{operationId:"createSourceWebhook",summary:"Create and optionally reconcile a signed webhook",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["connectionId","repositoryFullName","baseUrl"],properties:{connectionId:{type:"string"},repositoryId:{type:"string"},repositoryFullName:{type:"string"},baseUrl:{type:"string",format:"uri"},events:{type:"array",items:{type:"string",enum:["push","pull_request"]}},reconcile:{type:"boolean"}}}}}},responses:{"201":{description:"Webhook endpoint created; endpoint is revealed once."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/application-detections":{post:{operationId:"detectApplication",summary:"Detect bounded application build candidates",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["files"],properties:{files:{type:"array",maxItems:1e4,items:{$ref:"#/components/schemas/DetectionFile"}}}}}}},responses:{"200":{description:"Ranked detection candidates with evidence."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/application-plans":{post:{operationId:"planApplication",summary:"Validate and normalize an application manifest",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["draft"],properties:{draft:{$ref:"#/components/schemas/ApplicationInput"},suppliedSecretNames:{type:"array",uniqueItems:!0,items:{type:"string"}}}}}}},responses:{"200":{description:"Validated plan, config patch, capabilities, costs, and missing secret names."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/application-drafts":{get:{operationId:"listApplicationDrafts",summary:"List resumable secret-free drafts",parameters:[{name:"projectId",in:"query",required:!0,schema:{type:"string"}},{$ref:"#/components/parameters/Limit"},{$ref:"#/components/parameters/Cursor"}],responses:r({$ref:"#/components/schemas/ApplicationDraft"})},post:{operationId:"createApplicationDraft",summary:"Create a resumable application draft",requestBody:{required:!0,content:{"application/json":{schema:{$ref:"#/components/schemas/ApplicationDraftCreateRequest"}}}},responses:{"201":{description:"Draft created."},default:{$ref:"#/components/responses/Error"}}},patch:{operationId:"updateApplicationDraft",summary:"Optimistically update a draft",requestBody:{required:!0,content:{"application/json":{schema:{allOf:[{$ref:"#/components/schemas/ApplicationDraftCreateRequest"},{type:"object",required:["id","version","step"],properties:{id:{type:"string"},version:{type:"integer",minimum:1}}}]}}}},responses:{"200":{description:"Updated draft."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/applications":{post:{operationId:"createApplication",summary:"Confirm and queue an application plan",parameters:[{name:"Idempotency-Key",in:"header",required:!0,schema:{type:"string",minLength:8,maxLength:128}}],requestBody:{required:!0,content:{"application/json":{schema:{type:"object",additionalProperties:!1,required:["draftId","version","confirmEnvironment"],properties:{draftId:{type:"string"},version:{type:"integer",minimum:1},confirmEnvironment:{type:"string",description:"Exact target environment slug."}}}}}},responses:{"202":{description:"Application operation queued; identical requests replay safely."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/application-artifacts":{post:{operationId:"uploadApplicationArtifact",summary:"Inspect and store a bounded ZIP or TAR source artifact",parameters:[{name:"X-Project-Id",in:"header",required:!0,schema:{type:"string"}},{name:"X-Artifact-Filename",in:"header",required:!0,schema:{type:"string"}}],requestBody:{required:!0,content:{"application/octet-stream":{schema:{type:"string",format:"binary",maxLength:104857600}}}},responses:{"201":{description:"Deduplicated artifact metadata; archive contents are never executed."},"413":{$ref:"#/components/responses/Error"},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/registry-connections":{get:{operationId:"listRegistryConnections",summary:"List safe private-registry metadata",parameters:[{$ref:"#/components/parameters/Limit"},{$ref:"#/components/parameters/Cursor"}],responses:r({$ref:"#/components/schemas/RegistryConnection"})},post:{operationId:"createRegistryConnection",summary:"Create an encrypted private-registry connection",requestBody:{required:!0,content:{"application/json":{schema:{$ref:"#/components/schemas/RegistryConnectionRequest"}}}},responses:{"201":{description:"Encrypted registry connection created."},default:{$ref:"#/components/responses/Error"}}},patch:{operationId:"updateRegistryConnection",summary:"Test access or rotate write-only credentials",requestBody:{required:!0,content:{"application/json":{schema:{allOf:[{$ref:"#/components/schemas/RegistryConnectionRequest"},{type:"object",required:["id","action"],properties:{id:{type:"string"},action:{type:"string",enum:["test","rotate"]},image:{type:"string"}}}]}}}},responses:{"200":{description:"Safe connection health metadata."},default:{$ref:"#/components/responses/Error"}}},delete:{operationId:"disconnectRegistryConnection",summary:"Disconnect and erase registry credentials",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",additionalProperties:!1,required:["id"],properties:{id:{type:"string"}}}}}},responses:{"200":{description:"Credentials erased and connection disconnected."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/queue":{get:{operationId:"listQueue",summary:"List authorized durable operations and blocking metadata",parameters:[{name:"projectId",in:"query",schema:{type:"string"}},{name:"state",in:"query",schema:{type:"string",enum:["queued","running","succeeded","failed","cancelled","timed_out"]}},{$ref:"#/components/parameters/Limit"},{$ref:"#/components/parameters/Cursor"}],responses:r({$ref:"#/components/schemas/QueueOperation"})}},"/api/v1/preview-definitions":{get:{operationId:"listPreviewDefinitions",summary:"List preview policies",responses:r({type:"object"})},post:{operationId:"createPreviewDefinition",summary:"Configure bounded preview policy",responses:{"200":{description:"Preview definition created."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/previews":{get:{operationId:"listPreviews",summary:"List authorized persistent previews",responses:r({type:"object"})},post:{operationId:"createPreview",summary:"Create or update one immutable preview identity",responses:{"200":{description:"Preview deployment queued."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/previews/{previewId}/destroy":{post:{operationId:"destroyPreview",summary:"Confirm tagged preview teardown",responses:{"200":{description:"Teardown queued."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/previews/{previewId}/extend":{post:{operationId:"extendPreview",summary:"Extend preview TTL",responses:{"200":{description:"Expiry extended."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/previews/{previewId}/rebuild":{post:{operationId:"rebuildPreview",summary:"Rebuild the exact recorded commit",responses:{"200":{description:"Rebuild queued."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/previews/cleanup":{post:{operationId:"cleanupPreviews",summary:"Dry-run or queue TTL/keep-count teardown",responses:{"200":{description:"Cleanup plan or operations."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/compose-templates":{get:{operationId:"listComposeTemplates",summary:"List pinned verified application templates",responses:r({type:"object"})}},"/api/v1/compose-applications":{get:{operationId:"listComposeApplications",summary:"List authorized multi-service applications",responses:r({type:"object"})},post:{operationId:"createComposeApplication",summary:"Import Compose or materialize a template",responses:{"200":{description:"Editable normalized application."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/compose-applications/preview":{post:{operationId:"previewComposeApplication",summary:"Parse and diagnose Compose without mutation",responses:{"200":{description:"Normalized preview and actionable diagnostics."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/compose-applications/{applicationId}/services":{get:{operationId:"listComposeServices",summary:"Inspect per-service desired and observed state",responses:{"200":{description:"Service topology and status."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/compose-applications/{applicationId}/{action}":{post:{operationId:"operateComposeApplication",summary:"Deploy, redeploy, start, stop, scale, or delete through the durable queue",responses:{"200":{description:"Scoped operation queued."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/release-artifacts":{post:{operationId:"createReleaseArtifact",summary:"Register a verified content-addressed artifact",responses:{"200":{description:"Artifact identity registered."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/releases":{get:{operationId:"listReleases",summary:"List unified authorized release history",responses:r({type:"object"})},post:{operationId:"createRelease",summary:"Create an immutable release from an existing artifact",responses:{"200":{description:"Release record created."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/releases/capabilities":{get:{operationId:"getReleaseCapabilities",summary:"Explain supported strategies, capacity, cost, and rollback",responses:{"200":{description:"Provider-aware strategy capabilities."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/releases/{releaseId}":{get:{operationId:"getRelease",summary:"Inspect provenance, approvals, health, and transitions",responses:{"200":{description:"Release detail."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/releases/{releaseId}/{action}":{post:{operationId:"operateRelease",summary:"Promote, approve, activate, roll back, report health, or pin",responses:{"200":{description:"Release lifecycle updated."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/queue/settings":{get:{operationId:"getQueueSettings",summary:"Get effective concurrency limits",responses:{"200":{description:"Queue concurrency settings."},default:{$ref:"#/components/responses/Error"}}},patch:{operationId:"updateQueueSettings",summary:"Confirm and audit production concurrency changes",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",additionalProperties:!1,required:["confirm","concurrency"],properties:{confirm:{const:"update queue limits"},concurrency:{$ref:"#/components/schemas/QueueConcurrency"}}}}}},responses:{"200":{description:"Updated effective limits."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/queue/history":{delete:{operationId:"clearQueueHistory",summary:"Clear terminal jobs whose retention has elapsed",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",additionalProperties:!1,required:["confirm"],properties:{confirm:{const:"clear completed"},before:{type:"string",format:"date-time"},projectId:{type:"string"}}}}}},responses:{"200":{description:"Eligible history cleared with an audit event."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/operations/{operationId}/logs":{get:{operationId:"listOperationLogs",summary:"Resume ordered sanitized operation logs from a cursor",parameters:[{$ref:"#/components/parameters/OperationId"},{name:"after",in:"query",schema:{type:"integer",minimum:0}},{$ref:"#/components/parameters/Limit"}],responses:{"200":{description:"Ordered log chunks and next cursor."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/operations/{operationId}/logs/stream":{get:{operationId:"streamOperationLogs",summary:"Stream authorized operation logs with Last-Event-ID resume",parameters:[{$ref:"#/components/parameters/OperationId"},{name:"Last-Event-ID",in:"header",schema:{type:"integer",minimum:0}}],responses:{"200":{description:"Server-sent log and completion events.",content:{"text/event-stream":{schema:{type:"string"}}}},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/operations/{operationId}/cancel":{post:{operationId:"cancelOperation",summary:"Cancel queued work or request cooperative running cancellation",parameters:[{$ref:"#/components/parameters/OperationId"}],requestBody:{content:{"application/json":{schema:{type:"object"}}}},responses:{"200":{description:"Cancellation state recorded."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/operations/{operationId}/retry":{post:{operationId:"retryOperation",summary:"Retry an allow-listed failure class within the attempt limit",parameters:[{$ref:"#/components/parameters/OperationId"}],requestBody:{required:!0,content:{"application/json":{schema:{type:"object",additionalProperties:!1,required:["errorClass"],properties:{errorClass:{type:"string"},delayMs:{type:"integer",minimum:0}}}}}},responses:{"200":{description:"Retry queued."},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/deployments":{post:{operationId:"createDeployment",summary:"Queue a deployment",parameters:[{name:"Idempotency-Key",in:"header",required:!0,schema:{type:"string",minLength:8,maxLength:128}}],requestBody:{required:!0,content:{"application/json":{schema:{$ref:"#/components/schemas/DeploymentRequest"}}}},responses:{"202":{description:"Queued operation.",content:{"application/json":{schema:{$ref:"#/components/schemas/OperationResponse"}}}},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/operations":{get:{operationId:"listOperations",summary:"List scoped operations",parameters:[{name:"projectId",in:"query",schema:{type:"string"}},{$ref:"#/components/parameters/Limit"},{$ref:"#/components/parameters/Cursor"}],responses:r({$ref:"#/components/schemas/Operation"})}},"/api/v1/events":{get:{operationId:"listEvents",summary:"List scoped audit events",parameters:[{name:"projectId",in:"query",schema:{type:"string"}},{name:"after",in:"query",schema:{type:"integer",minimum:0}},{$ref:"#/components/parameters/Limit"}],responses:r({$ref:"#/components/schemas/Event"})}},"/api/v1/events/stream":{get:{operationId:"streamEvents",summary:"Stream scoped audit events",responses:{"200":{description:"Authenticated server-sent event stream.",content:{"text/event-stream":{schema:{type:"string"}}}},default:{$ref:"#/components/responses/Error"}}}},"/api/v1/openapi.json":{get:{operationId:"getOpenApi",summary:"Get the OpenAPI contract",security:[],responses:{"200":{description:"OpenAPI 3.1 contract."}}}}},components:{securitySchemes:{bearerAuth:{type:"http",scheme:"bearer",bearerFormat:"tsc_v1"}},parameters:{Limit:{name:"limit",in:"query",schema:{type:"integer",minimum:1,maximum:100,default:50}},Cursor:{name:"cursor",in:"query",schema:{type:"string"}},ProjectId:{name:"projectId",in:"path",required:!0,schema:{type:"string"}},OperationId:{name:"operationId",in:"path",required:!0,schema:{type:"string"}}},responses:{Error:{description:"Stable error envelope.",content:{"application/json":{schema:e}}}},schemas:{Project:{type:"object",required:["id","slug","name"],properties:{id:{type:"string"},slug:{type:"string"},name:{type:"string"},description:{type:"string"}}},Environment:{type:"object",required:["id","projectId","slug","name","kind"],properties:{id:{type:"string"},projectId:{type:"string"},slug:{type:"string"},name:{type:"string"},kind:{type:"string"},region:{type:"string"}}},Service:{type:"object",required:["id","projectId","kind","slug","name"],properties:{id:{type:"string"},projectId:{type:"string"},environmentId:{type:"string"},kind:{type:"string"},slug:{type:"string"},name:{type:"string"},metadata:{type:"object",additionalProperties:!0}}},SourceConnection:{type:"object",required:["id","provider","name","host","status","credentialConfigured"],properties:{id:{type:"string"},provider:{type:"string"},name:{type:"string"},host:{type:"string"},status:{type:"string"},credentialConfigured:{type:"boolean"},credentialFingerprint:{type:"string"},grantedScopes:{type:"array",items:{type:"string"}}}},SourceRepository:{type:"object",required:["id","connectionId","fullName","cloneUrl","defaultBranch"],properties:{id:{type:"string"},connectionId:{type:"string"},fullName:{type:"string"},cloneUrl:{type:"string"},defaultBranch:{type:"string"},visibility:{type:"string"},archived:{type:"boolean"}}},SourceBindingRequest:{type:"object",additionalProperties:!1,required:["projectId","connectionId","repositoryFullName"],properties:{projectId:{type:"string"},environmentId:{type:"string"},resourceId:{type:"string"},connectionId:{type:"string"},repositoryId:{type:"string"},repositoryFullName:{type:"string"},defaultBranch:{type:"string"},branchRule:{type:"string"},tagRule:{type:"string"},monorepoRoot:{type:"string"},includePaths:{type:"array",items:{type:"string"}},excludePaths:{type:"array",items:{type:"string"}},submodules:{type:"boolean"},cloneDepth:{type:"integer",minimum:1},deployKeyId:{type:"string"},autoDeploy:{type:"boolean"},pullRequestPreviews:{type:"boolean"}}},DetectionFile:{type:"object",additionalProperties:!1,required:["path"],properties:{path:{type:"string"},size:{type:"integer",minimum:0},content:{type:"string",maxLength:262144}}},ApplicationInput:{type:"object",additionalProperties:!1,required:["schemaVersion","name","slug","projectId","environmentId","source","build","runtime"],properties:{schemaVersion:{const:1},name:{type:"string"},slug:{type:"string"},projectId:{type:"string"},environmentId:{type:"string"},source:{type:"object",required:["kind"],properties:{kind:{type:"string",enum:["git","local","artifact","image"]}},additionalProperties:!0},build:{type:"object",required:["kind"],properties:{kind:{type:"string",enum:["dockerfile","buildpack","static","server","serverless","prebuilt_image"]},secretNames:{type:"array",uniqueItems:!0,items:{type:"string"}}},additionalProperties:!0},runtime:{type:"object",required:["architecture","target"],properties:{architecture:{type:"string",enum:["x86_64","arm64"]},target:{type:"string",enum:["server","serverless","container"]},port:{type:"integer",minimum:1,maximum:65535},healthCheck:{type:"object",additionalProperties:!0}},additionalProperties:!0},environment:{type:"object",additionalProperties:{oneOf:[{type:"string"},{type:"object",additionalProperties:!1,required:["secretRef"],properties:{secretRef:{type:"string"}}}]}},requiredSecretNames:{type:"array",uniqueItems:!0,items:{type:"string"}},domain:{type:"object",properties:{hostname:{type:"string"},path:{type:"string"},tls:{type:"boolean"}}}}},ApplicationDraftCreateRequest:{type:"object",additionalProperties:!1,required:["projectId","draft"],properties:{projectId:{type:"string"},name:{type:"string"},draft:{$ref:"#/components/schemas/ApplicationInput"},step:{type:"string",enum:["source","build","runtime","environment","domain","review"]},suppliedSecretNames:{type:"array",uniqueItems:!0,description:"Names only; values must use the secrets boundary.",items:{type:"string"}}}},ApplicationDraft:{type:"object",required:["id","projectId","input","step","status","version"],properties:{id:{type:"string"},projectId:{type:"string"},input:{$ref:"#/components/schemas/ApplicationInput"},step:{type:"string"},suppliedSecretNames:{type:"array",items:{type:"string"}},status:{type:"string",enum:["draft","ready","applied"]},version:{type:"integer"},createdAt:{type:"string",format:"date-time"},updatedAt:{type:"string",format:"date-time"}}},RegistryConnectionRequest:{type:"object",properties:{provider:{type:"string",enum:["docker_hub","ghcr","ecr","gcr","generic"]},name:{type:"string"},host:{type:"string"},username:{type:"string",writeOnly:!0},password:{type:"string",writeOnly:!0},token:{type:"string",writeOnly:!0},credentialExpiresAt:{type:"string",format:"date-time"},expiresAt:{type:"string",format:"date-time"}}},RegistryConnection:{type:"object",required:["id","provider","name","host","credentialConfigured","status","version"],properties:{id:{type:"string"},provider:{type:"string"},name:{type:"string"},host:{type:"string"},credentialConfigured:{type:"boolean"},credentialFingerprint:{type:"string"},credentialExpiresAt:{type:"string",format:"date-time"},status:{type:"string",enum:["pending","healthy","degraded","expired","disconnected"]},healthMessage:{type:"string"},lastTestedAt:{type:"string",format:"date-time"},version:{type:"integer"}}},QueueConcurrency:{type:"object",additionalProperties:!1,properties:{project:{type:"integer",minimum:1,maximum:100},environment:{type:"integer",minimum:1,maximum:100},provider:{type:"integer",minimum:1,maximum:100},builds:{type:"integer",minimum:1,maximum:100}}},QueueOperation:{allOf:[{$ref:"#/components/schemas/Operation"},{type:"object",required:["queue"],properties:{queue:{type:"object",required:["maxAttempts","availableAt","timeoutSeconds","retryClasses","resumePolicy","cancellationMode","retentionUntil"],properties:{lockKey:{type:"string"},providerKey:{type:"string"},buildSlot:{type:"boolean"},maxAttempts:{type:"integer"},availableAt:{type:"string",format:"date-time"},timeoutSeconds:{type:"integer"},heartbeatAt:{type:"string",format:"date-time"},currentStep:{type:"string"},blockedReason:{type:"string"},retryClasses:{type:"array",items:{type:"string"}},resumePolicy:{type:"string",enum:["fail","requeue"]},cancellationMode:{type:"string",enum:["cooperative","provider_non_cancellable"]},retentionUntil:{type:"string",format:"date-time"}}},approximatePosition:{type:"object",properties:{ahead:{type:"integer"},precision:{const:"bounded"}}}}}]},DeploymentRequest:{type:"object",additionalProperties:!1,required:["projectId","environmentId"],properties:{projectId:{type:"string"},environmentId:{type:"string"},serviceId:{type:"string"},action:{type:"string",enum:["deploy","rollback"],default:"deploy"},revision:{type:"string"}}},Operation:{type:"object",required:["id","state","kind","correlationId","createdAt"],properties:{id:{type:"string"},state:{type:"string"},kind:{type:"string"},correlationId:{type:"string"},createdAt:{type:"string",format:"date-time"}}},OperationResponse:{type:"object",required:["operation","idempotentReplay","requestId"],properties:{operation:{$ref:"#/components/schemas/Operation"},idempotentReplay:{type:"boolean"},requestId:{type:"string",format:"uuid"}}},Event:{type:"object",required:["id","sequence","type","level","correlationId","createdAt"],properties:{id:{type:"string"},sequence:{type:"integer"},type:{type:"string"},level:{type:"string"},correlationId:{type:"string"},payload:{},createdAt:{type:"string",format:"date-time"}}}}}}}function tk(e){return Buffer.from(JSON.stringify(e)).toString("base64url")}function rk(e){if(!e)return;try{let t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return t&&typeof t==="object"&&!Array.isArray(t)?t:void 0}catch{return}}function Et(e,t,r,n=["createdAt","id"]){let i=Math.min(100,Math.max(1,Number(t.searchParams.get("limit"))||50)),o=rk(t.searchParams.get("cursor"));if(t.searchParams.has("cursor")&&!o)throw new ie("invalid_cursor","The pagination cursor is invalid.",400);let s=0;if(o){let u=e.findIndex((m)=>n.every((h)=>m[h]===o[h]));if(u<0)throw new ie("invalid_cursor","The pagination cursor is no longer available.",400);s=u+1}let c=e.slice(s,s+i),d=s+i<e.length,a=c.at(-1);return{data:c,page:{hasMore:d,nextCursor:d&&a?tk(Object.fromEntries(n.map((u)=>[u,a[u]]))):void 0},requestId:r}}function Vc(e){let t=new qc(e.controlPlane,e.identities),r=new $e(e.controlPlane),n=new vs(e.controlPlane),i=new bs(e.controlPlane),o=new Dn(e.controlPlane),s=e.spend?.store??new Hm(e.controlPlane,{now:e.now}),c={store:s,service:e.spend?.service??new Km(s)},d=new Map,a=e.now??(()=>new Date),u=e.rateLimit??120,m=(y,w,k,C={})=>new Response(JSON.stringify(y),{status:w,headers:{"content-type":"application/json; charset=utf-8","cache-control":"no-store","x-request-id":k,"x-api-version":hs,...C}}),h=(y,w,k,C,T,j)=>m({error:{code:y,message:w,requestId:C,details:T}},k,C,j);return async(y,w)=>{let k=new URL(y.url);if(!k.pathname.startsWith("/api/v1"))return;let C=crypto.randomUUID();if(k.pathname==="/api/v1/openapi.json"&&y.method==="GET")return m(Uc(),200,C,{"cache-control":"public, max-age=300"});let T=y.headers.get("authorization")??"",j=T.startsWith("Bearer ")?T.slice(7).trim():"",P=j?e.identities.verifyToken(j,w):void 0;if(!P)return h("unauthorized","A valid bearer token is required.",401,C,void 0,{"www-authenticate":'Bearer realm="ts-cloud", error="invalid_token"'});let O=d.get(P.token.id),U=a().getTime(),q=!O||U-O.start>=60000?{start:U,count:0}:O;q.count+=1,d.set(P.token.id,q);let N=Math.max(0,u-q.count),Q={"x-ratelimit-limit":String(u),"x-ratelimit-remaining":String(N),"x-ratelimit-reset":String(Math.ceil((q.start+60000)/1000))};if(q.count>u)return h("rate_limited","API rate limit exceeded.",429,C,void 0,{...Q,"retry-after":String(Math.max(1,Math.ceil((q.start+60000-U)/1000)))});try{let D,Y=async()=>{let R=await y.text();if(R.length>1048576)throw new ie("payload_too_large","Request body exceeds 1 MB.",413);try{return JSON.parse(R)}catch{throw new ie("invalid_json","Request body must be valid JSON.",400)}},se=/^\/api\/v1\/projects\/([^/]+)\/environments$/.exec(k.pathname),he=/^\/api\/v1\/operations\/([^/]+)\/logs(?:\/(stream))?$/.exec(k.pathname),je=/^\/api\/v1\/operations\/([^/]+)\/(cancel|retry)$/.exec(k.pathname),de=/^\/api\/v1\/previews\/([^/]+)\/(destroy|extend|rebuild)$/.exec(k.pathname),Re=/^\/api\/v1\/compose-applications\/([^/]+)\/(deploy|redeploy|start|stop|scale|delete)$/.exec(k.pathname),Me=/^\/api\/v1\/compose-applications\/([^/]+)\/services$/.exec(k.pathname),me=/^\/api\/v1\/releases\/([^/]+)\/(promote|approve|activate|rollback|health|pin)$/.exec(k.pathname);if(y.method==="GET"&&k.pathname==="/api/v1/projects")D=Et(t.listProjects(P),k,C);else if(y.method==="GET"&&se)D=Et(t.listEnvironments(P,decodeURIComponent(se[1])),k,C);else if(y.method==="GET"&&k.pathname==="/api/v1/services"){let R=k.searchParams.get("projectId");if(!R)throw new ie("validation_error","projectId is required.",422);D=Et(t.listServices(P,R,k.searchParams.get("environmentId")??void 0),k,C)}else if(y.method==="GET"&&k.pathname==="/api/v1/operations")D=Et(t.listOperations(P,k.searchParams.get("projectId")??void 0),k,C);else if(y.method==="GET"&&k.pathname==="/api/v1/previews"){let R=k.searchParams.get("projectId")??void 0,M=n.previews.listInstances({projectId:R}).filter((F)=>{try{return t.authorize(P,"deployments:read",{type:"resource",id:F.resourceId}),!0}catch{return!1}}).map((F)=>({...F}));D=Et(M,k,C)}else if(y.method==="GET"&&k.pathname==="/api/v1/compose-templates")D=Et(ys().map((R)=>({...R})),k,C,["id","version"]);else if(y.method==="GET"&&k.pathname==="/api/v1/releases/capabilities"){let R=String(k.searchParams.get("kind")??"");D={capabilities:ao({kind:R,hasHealthGate:k.searchParams.get("health")==="true",replicas:Number(k.searchParams.get("replicas"))||1}),requestId:C}}else if(y.method==="GET"&&k.pathname==="/api/v1/releases"){let R=k.searchParams.get("projectId");if(!R)throw new ie("validation_error","projectId is required.",422);t.authorize(P,"project:read",{type:"project",id:R});let M=o.releases.list({projectId:R,environmentId:k.searchParams.get("environmentId")??void 0,resourceId:k.searchParams.get("resourceId")??void 0}).filter((F)=>{try{return t.authorize(P,"deployments:read",{type:"resource",id:F.resourceId}),!0}catch{return!1}}).map((F)=>({...F,artifact:o.releases.getArtifact(F.artifactId),transitions:o.releases.transitions(F.id),approvals:o.releases.approvals(F.id)}));D=Et(M,k,C)}else if(y.method==="POST"&&k.pathname==="/api/v1/release-artifacts"){let R=await Y();t.authorize(P,"applications:manage",{type:"organization"}),D={artifact:o.releases.registerArtifact({organizationId:P.serviceAccount.organizationId,digest:String(R.digest??""),kind:String(R.kind??""),uri:String(R.uri??""),size:Number(R.size),mediaType:typeof R.mediaType==="string"?R.mediaType:void 0,provenance:R.provenance,attestation:R.attestation}),requestId:C}}else if(y.method==="POST"&&k.pathname==="/api/v1/releases"){let R=await Y(),M=String(R.resourceId??"");t.authorize(P,"applications:manage",{type:"resource",id:M}),D={release:o.releases.create({organizationId:P.serviceAccount.organizationId,projectId:String(R.projectId??""),environmentId:String(R.environmentId??""),resourceId:M,artifactId:String(R.artifactId??""),kind:String(R.kind??""),sourceSha:typeof R.sourceSha==="string"?R.sourceSha:void 0,config:R.config??{},manifest:R.manifest??{},provenance:R.provenance,strategy:String(R.strategy??"atomic"),healthGate:R.healthGate,hooks:R.hooks,drainSeconds:Number(R.drainSeconds)||void 0,graceSeconds:Number(R.graceSeconds)||void 0,automaticRollback:R.automaticRollback!==!1,actorId:P.actor.id,trigger:typeof R.trigger==="string"?R.trigger:"api",approvalRequired:R.approvalRequired===!0,replicas:Number(R.replicas)||void 0}),requestId:C}}else if(y.method==="GET"&&/^\/api\/v1\/releases\/[^/]+$/.test(k.pathname)){let R=decodeURIComponent(k.pathname.split("/").at(-1)),M=o.releases.get(R);if(!M)throw new ie("not_found","Release was not found.",404);t.authorize(P,"deployments:read",{type:"resource",id:M.resourceId}),D={release:M,artifact:o.releases.getArtifact(M.artifactId),transitions:o.releases.transitions(R),approvals:o.releases.approvals(R),requestId:C}}else if(y.method==="POST"&&me){let R=o.releases.get(decodeURIComponent(me[1]));if(!R)throw new ie("not_found","Release was not found.",404);let M=await Y(),F=me[2];if(F==="promote"){let K=String(M.targetResourceId??"");t.authorize(P,"deployments:create",{type:"resource",id:K}),D={release:o.releases.promote(R.id,{targetEnvironmentId:String(M.targetEnvironmentId??""),targetResourceId:K,config:M.config??{},strategy:M.strategy,healthGate:M.healthGate,actorId:P.actor.id,approvalRequired:M.approvalRequired===!0}),requestId:C}}else if(F==="approve")t.authorize(P,"deployments:create",{type:"resource",id:R.resourceId}),D={release:o.releases.approve(R.id,{actorId:P.actor.id,decision:M.decision==="rejected"?"rejected":"approved",comment:typeof M.comment==="string"?M.comment:void 0}),requestId:C};else if(F==="activate")t.authorize(P,"deployments:create",{type:"resource",id:R.resourceId}),D={operation:t.operation(o.enqueueActivation(R,{actorId:P.actor.id})),requestId:C};else if(F==="rollback")t.authorize(P,"deployments:create",{type:"resource",id:R.resourceId}),D={operation:t.operation(o.enqueueRollback(R,{actorId:P.actor.id,targetReleaseId:typeof M.targetReleaseId==="string"?M.targetReleaseId:void 0})),requestId:C};else if(F==="health"){t.authorize(P,"deployments:create",{type:"resource",id:R.resourceId});let K=o.completeHealthGate(R.id,{healthy:M.healthy===!0,operationId:typeof M.operationId==="string"?M.operationId:void 0,health:M.health,message:typeof M.message==="string"?M.message:void 0});D={release:K.release,rollbackOperation:K.rollbackOperation?t.operation(K.rollbackOperation):void 0,requestId:C}}else t.authorize(P,"deployments:create",{type:"resource",id:R.resourceId}),D={release:o.releases.pin(R.id,M.pinned!==!1,typeof M.reason==="string"?M.reason:void 0),requestId:C}}else if(y.method==="GET"&&k.pathname==="/api/v1/compose-applications"){let R=k.searchParams.get("projectId");if(!R)throw new ie("validation_error","projectId is required.",422);t.authorize(P,"project:read",{type:"project",id:R});let M=i.applications.list({projectId:R,environmentId:k.searchParams.get("environmentId")??void 0}).filter((F)=>{try{return t.authorize(P,"deployments:read",{type:"resource",id:F.resourceId}),!0}catch{return!1}}).map((F)=>({...F,services:i.applications.services(F.id)}));D=Et(M,k,C)}else if(y.method==="POST"&&k.pathname==="/api/v1/compose-applications/preview"){let R=await Y(),M=String(R.projectId??"");t.authorize(P,"project:read",{type:"project",id:M}),D={result:i.applications.preview(String(R.source??""),{name:String(R.name??""),slug:typeof R.slug==="string"?R.slug:void 0,projectId:M,environmentId:String(R.environmentId??"")}),requestId:C}}else if(y.method==="POST"&&k.pathname==="/api/v1/compose-applications"){let R=await Y(),M=String(R.projectId??"");t.authorize(P,"applications:manage",{type:"environment",id:String(R.environmentId??"")});let F={name:String(R.name??""),slug:typeof R.slug==="string"?R.slug:void 0,projectId:M,environmentId:String(R.environmentId??""),createdByActorId:P.actor.id},K=typeof R.templateId==="string"?i.applications.fromTemplate(R.templateId,R.inputs&&typeof R.inputs==="object"&&!Array.isArray(R.inputs)?R.inputs:{},{...F,version:typeof R.templateVersion==="string"?R.templateVersion:void 0}):i.applications.import(String(R.source??""),F);D={application:K.application,diagnostics:K.parsed.diagnostics,requestId:C}}else if(y.method==="GET"&&Me){let R=i.applications.get(decodeURIComponent(Me[1]));if(!R)throw new ie("not_found","Compose application was not found.",404);t.authorize(P,"deployments:read",{type:"resource",id:R.resourceId}),D={application:R,services:i.applications.services(R.id),requestId:C}}else if(y.method==="POST"&&Re){let R=i.applications.get(decodeURIComponent(Re[1]));if(!R)throw new ie("not_found","Compose application was not found.",404);let M=Re[2],F=await Y();t.authorize(P,M==="delete"||M==="stop"?"deployments:cancel":"deployments:create",{type:"resource",id:R.resourceId}),D={operation:t.operation(i.enqueue(R,M,{actorId:P.actor.id,service:typeof F.service==="string"?F.service:void 0,replicas:Number.isFinite(Number(F.replicas))?Number(F.replicas):void 0,removeVolumes:F.removeVolumes===!0,confirmation:typeof F.confirm==="string"?F.confirm:void 0})),requestId:C}}else if(y.method==="GET"&&k.pathname==="/api/v1/preview-definitions"){let R=k.searchParams.get("projectId");if(!R)throw new ie("validation_error","projectId is required.",422);t.authorize(P,"project:read",{type:"project",id:R}),D=Et(n.previews.listDefinitions(R).map((M)=>({...M})),k,C)}else if(y.method==="POST"&&k.pathname==="/api/v1/preview-definitions"){let R=await Y();t.authorize(P,"config:write",{type:"resource",id:String(R.resourceId??"")}),D={definition:n.previews.createDefinition({...R,projectId:String(R.projectId??""),resourceId:String(R.resourceId??""),baseEnvironmentId:String(R.baseEnvironmentId??""),domainPattern:String(R.domainPattern??""),createdByActorId:P.actor.id}),requestId:C}}else if(y.method==="POST"&&k.pathname==="/api/v1/previews"){let R=await Y(),M=n.previews.getDefinition(String(R.definitionId??""));if(!M)throw new ie("not_found","Preview definition was not found.",404);t.authorize(P,"deployments:create",{type:"resource",id:M.resourceId});let F=n.previews.upsert({definitionId:M.id,sourceProvider:"api",repository:typeof R.repository==="string"?R.repository:"api",branch:String(R.branch??""),pullRequestNumber:Number(R.pullRequestNumber)||void 0,fork:R.fork===!0,commitSha:String(R.commitSha??""),createdByActorId:P.actor.id});D={preview:F.preview,operation:t.operation(n.enqueueDeploy(F.preview,{created:F.created,actorId:P.actor.id})),requestId:C}}else if(y.method==="POST"&&de){let R=n.previews.getInstance(decodeURIComponent(de[1]));if(!R)throw new ie("not_found","Preview was not found.",404);let M=await Y(),F=de[2];if(F==="destroy"){if(t.authorize(P,"deployments:cancel",{type:"resource",id:R.resourceId}),M.confirm!==R.name)throw new ie("confirmation_required",`Type ${R.name} to confirm preview teardown.`,409);D={operation:t.operation(n.enqueueDestroy(R,"api",P.actor.id)),requestId:C}}else if(F==="extend")t.authorize(P,"deployments:create",{type:"resource",id:R.resourceId}),D={preview:n.previews.extend(R.id,Number(M.hours)),requestId:C};else t.authorize(P,"deployments:create",{type:"resource",id:R.resourceId}),D={operation:t.operation(n.enqueueDeploy(R,{actorId:P.actor.id,reason:"manual_rebuild"})),requestId:C}}else if(y.method==="POST"&&k.pathname==="/api/v1/previews/cleanup"){t.authorize(P,"automation:manage",{type:"organization"});let R=await Y();if(!R.dryRun&&R.confirm!=="cleanup previews")throw new ie("confirmation_required","Type cleanup previews to confirm preview cleanup.",409);D={...n.cleanup({dryRun:R.dryRun===!0,maxAgeHours:Number(R.maxAgeHours)||void 0,keepCount:Number(R.keepCount)||void 0,actorId:P.actor.id}),requestId:C}}else if(y.method==="GET"&&k.pathname==="/api/v1/queue"){let R=k.searchParams.get("projectId")??void 0,M=k.searchParams.get("state"),F=r.list({projectId:R,state:["queued","running","succeeded","failed","cancelled","timed_out"].includes(M)?M:void 0,limit:500}).filter((K)=>{let ye=K.operation.resourceId?{type:"resource",id:K.operation.resourceId}:K.operation.environmentId?{type:"environment",id:K.operation.environmentId}:K.operation.projectId?{type:"project",id:K.operation.projectId}:{type:"organization"};try{return t.authorize(P,"deployments:read",ye),!0}catch{return!1}}).map((K)=>({...t.operation(K.operation),queue:K.job,approximatePosition:K.approximatePosition}));D=Et(F,k,C)}else if(y.method==="GET"&&k.pathname==="/api/v1/queue/settings")t.authorize(P,"deployments:read",P.token.scope),D={concurrency:r.limits,requestId:C};else if(y.method==="PATCH"&&k.pathname==="/api/v1/queue/settings"){t.authorize(P,"automation:manage",{type:"organization"});let R=await Y();if(R.confirm!=="update queue limits")throw new ie("confirmation_required","Type update queue limits to confirm production concurrency changes.",409);D={concurrency:r.configureConcurrency(R.concurrency??{},{organizationId:P.serviceAccount.organizationId,actorId:P.actor.id}),requestId:C}}else if(y.method==="DELETE"&&k.pathname==="/api/v1/queue/history"){t.authorize(P,"automation:manage",{type:"organization"});let R=await Y();if(R.confirm!=="clear completed")throw new ie("confirmation_required","Type clear completed to confirm queue retention cleanup.",409);D={deleted:r.clearCompleted({before:typeof R.before==="string"?R.before:void 0,actorId:P.actor.id,projectId:typeof R.projectId==="string"?R.projectId:void 0}),requestId:C}}else if(y.method==="GET"&&he){let R=e.controlPlane.getOperation(decodeURIComponent(he[1]));if(!R)throw new ie("not_found","Operation was not found.",404);let M=R.resourceId?{type:"resource",id:R.resourceId}:R.environmentId?{type:"environment",id:R.environmentId}:R.projectId?{type:"project",id:R.projectId}:{type:"organization"};t.authorize(P,"deployments:read",M);let F=y.headers.get("last-event-id")?.trim(),K=Number(F||k.searchParams.get("after")||0);if(he[2]==="stream"){let Ae=new TextEncoder,G=K,be,ge=!1,oe=new ReadableStream({start(ft){let ni=()=>{if(ge)return;if(!e.identities.verifyToken(j,w)){if(ge=!0,be)clearInterval(be);ft.close();return}let dr=r.logs(R.id,{after:G,limit:500});for(let Be of dr)G=Be.sequence,ft.enqueue(Ae.encode(`id: ${Be.sequence}
|
|
23
|
+
event: log
|
|
24
|
+
data: ${JSON.stringify(Be)}
|
|
25
|
+
|
|
26
|
+
`));let xe=e.controlPlane.getOperation(R.id);if(xe&&["succeeded","failed","cancelled","timed_out"].includes(xe.state)&&!r.logs(R.id,{after:G,limit:1}).length){if(ge=!0,be)clearInterval(be);ft.enqueue(Ae.encode(`event: complete
|
|
27
|
+
data: ${JSON.stringify({state:xe.state,cursor:G})}
|
|
28
|
+
|
|
29
|
+
`)),ft.close()}};if(ni(),!ge)be=setInterval(ni,500);y.signal.addEventListener("abort",()=>{if(ge=!0,be)clearInterval(be);try{ft.close()}catch{}},{once:!0})},cancel(){if(ge=!0,be)clearInterval(be)}});return new Response(oe,{headers:{"content-type":"text/event-stream","cache-control":"no-store","x-accel-buffering":"no","x-request-id":C,...Q}})}let ye=r.logs(R.id,{after:K,limit:Number(k.searchParams.get("limit"))||void 0});D={data:ye,cursor:ye.at(-1)?.sequence??K,hasMore:ye.length>=Math.min(1000,Math.max(1,Number(k.searchParams.get("limit"))||200)),requestId:C}}else if(y.method==="POST"&&je){let R=e.controlPlane.getOperation(decodeURIComponent(je[1]));if(!R)throw new ie("not_found","Operation was not found.",404);let M=R.resourceId?{type:"resource",id:R.resourceId}:R.environmentId?{type:"environment",id:R.environmentId}:R.projectId?{type:"project",id:R.projectId}:{type:"organization"},F=await Y();if(je[2]==="cancel")t.authorize(P,"deployments:cancel",M),D={operation:t.operation(r.requestCancellation(R.id,P.actor.id)),requestId:C};else t.authorize(P,"deployments:create",M),D={operation:t.operation(r.retry(R.id,String(F.errorClass??"manual"),{delayMs:Number(F.delayMs)||0,actorId:P.actor.id})),requestId:C}}else if(y.method==="GET"&&k.pathname==="/api/v1/source/connections"){if(!e.sources)throw new ie("not_found","Source integrations are unavailable.",404);t.authorize(P,"sources:read",P.token.scope),D=Et(e.sources.listConnections(P.serviceAccount.organizationId),k,C,["createdAt","id"])}else if(y.method==="GET"&&k.pathname==="/api/v1/source/repositories"){if(!e.sources)throw new ie("not_found","Source integrations are unavailable.",404);t.authorize(P,"sources:read",P.token.scope);let R=e.sources.getConnection(k.searchParams.get("connectionId")??"");if(!R||R.organizationId!==P.serviceAccount.organizationId)throw new ie("not_found","Source connection was not found.",404);if(k.searchParams.get("sync")==="true")t.authorize(P,"sources:manage",{type:"organization"}),await gs(e.sources,R.id,{search:k.searchParams.get("search")??void 0});D=Et(e.sources.listRepositories(R.id,k.searchParams.get("search")??void 0),k,C,["fullName","id"])}else if(y.method==="GET"&&k.pathname==="/api/v1/source/refs"){if(!e.sources)throw new ie("not_found","Source integrations are unavailable.",404);t.authorize(P,"sources:read",P.token.scope);let R=k.searchParams.get("connectionId")??"",M=e.sources.getConnection(R);if(!M||M.organizationId!==P.serviceAccount.organizationId)throw new ie("not_found","Source connection was not found.",404);D=await fs(e.sources,{connectionId:R,repository:k.searchParams.get("repository")??"",repositoryId:k.searchParams.get("repositoryId")??void 0,type:k.searchParams.get("type")==="tags"?"tags":"branches",cursor:k.searchParams.get("cursor")??void 0,deployKeyId:k.searchParams.get("deployKeyId")??void 0})}else if(y.method==="POST"&&k.pathname==="/api/v1/application-detections"){t.authorize(P,"applications:manage",P.token.scope);let R=await Y();if(!Array.isArray(R.files)||R.files.length>1e4)throw new ie("validation_error","files must contain at most 10,000 entries.",422);D={candidates:hi(R.files.map((M)=>({path:String(M.path??""),size:Number(M.size??0),content:typeof M.content==="string"?M.content.slice(0,262144):void 0}))),requestId:C}}else if(y.method==="POST"&&k.pathname==="/api/v1/application-plans"){t.authorize(P,"applications:manage",P.token.scope);let R=await Y();D={plan:Yt(R.draft,Array.isArray(R.suppliedSecretNames)?R.suppliedSecretNames.map(String):[]),requestId:C}}else if(y.method==="GET"&&k.pathname==="/api/v1/application-drafts"){if(!e.applications)throw new ie("not_found","Application onboarding is unavailable.",404);let R=k.searchParams.get("projectId")??"";t.authorize(P,"applications:read",{type:"project",id:R}),D=Et(e.applications.drafts.list(R),k,C,["updatedAt","id"])}else if(y.method==="POST"&&k.pathname==="/api/v1/application-drafts"){if(!e.applications)throw new ie("not_found","Application onboarding is unavailable.",404);let R=await Y(),M=String(R.projectId??R.draft?.projectId??"");t.authorize(P,"applications:manage",{type:"project",id:M});let F=e.controlPlane.getProject(M);if(!F||F.organizationId!==P.serviceAccount.organizationId)throw new ie("not_found","Project was not found.",404);let K=e.applications.drafts.create({organizationId:F.organizationId,projectId:M,name:String(R.name??R.draft?.name??"Application draft"),draft:{...R.draft,projectId:M},step:R.step,suppliedSecretNames:Array.isArray(R.suppliedSecretNames)?R.suppliedSecretNames.map(String):[],actorId:P.actor.id});return m({draft:K,requestId:C},201,C,Q)}else if(y.method==="PATCH"&&k.pathname==="/api/v1/application-drafts"){if(!e.applications)throw new ie("not_found","Application onboarding is unavailable.",404);let R=await Y(),M=e.applications.drafts.get(String(R.id??""));if(!M)throw new ie("not_found","Application draft was not found.",404);t.authorize(P,"applications:manage",{type:"project",id:M.projectId}),D={draft:e.applications.drafts.update(M.id,Number(R.version),{draft:{...R.draft,projectId:M.projectId},step:R.step,suppliedSecretNames:Array.isArray(R.suppliedSecretNames)?R.suppliedSecretNames.map(String):void 0,actorId:P.actor.id}),requestId:C}}else if(y.method==="POST"&&k.pathname==="/api/v1/applications"){if(!e.applications)throw new ie("not_found","Application onboarding is unavailable.",404);let R=y.headers.get("idempotency-key")??"";if(!R)throw new ie("idempotency_required","Idempotency-Key is required for application creation.",428);if(!/^[A-Za-z0-9._:-]{8,128}$/.test(R))throw new ie("validation_error","Idempotency-Key must contain 8-128 safe characters.",422);let M=await Y(),F=e.applications.drafts.get(String(M.draftId??""));if(!F)throw new ie("not_found","Application draft was not found.",404);t.authorize(P,"applications:manage",{type:"project",id:F.projectId});let K=ek("sha256").update(`POST
|
|
30
|
+
/api/v1/applications
|
|
31
|
+
${JSON.stringify(M)}`).digest("hex"),ye=e.identities.getIdempotency(P.token.id,R);if(ye){if(ye.requestHash!==K)throw new ie("idempotency_conflict","Idempotency-Key was already used for another request.",409);let G=ye.operationId?e.controlPlane.getOperation(ye.operationId):void 0,be=G?.resourceId?e.controlPlane.getResource(G.resourceId):void 0;if(!G||!be)throw new ie("idempotency_unavailable","The original application operation is no longer available.",409);return m({resource:be,operation:t.operation(G),plan:Yt(F.input,F.suppliedSecretNames),idempotentReplay:!0,requestId:C},202,C,{...Q,"idempotent-replayed":"true"})}let Ae=ls({controlPlane:e.controlPlane,drafts:e.applications.drafts,draftId:F.id,expectedVersion:Number(M.version),confirmEnvironment:String(M.confirmEnvironment??""),actorId:P.actor.id});return e.identities.saveIdempotency({tokenId:P.token.id,key:R,requestHash:K,operationId:Ae.operation.id,responseStatus:202,responseBody:{draftId:F.id}}),m({resource:Ae.resource,operation:t.operation(Ae.operation),plan:Ae.plan,idempotentReplay:!1,requestId:C},202,C,Q)}else if(y.method==="GET"&&k.pathname==="/api/v1/registry-connections"){if(!e.applications)throw new ie("not_found","Application onboarding is unavailable.",404);t.authorize(P,"applications:read",P.token.scope),D=Et(e.applications.registries.list(P.serviceAccount.organizationId),k,C,["createdAt","id"])}else if(y.method==="POST"&&k.pathname==="/api/v1/registry-connections"){if(!e.applications)throw new ie("not_found","Application onboarding is unavailable.",404);t.authorize(P,"applications:manage",{type:"organization"});let R=await Y(),M=e.applications.registries.create({organizationId:P.serviceAccount.organizationId,provider:R.provider,name:String(R.name??"Container registry"),host:String(R.host??""),credential:R.token||R.password?{username:typeof R.username==="string"?R.username:void 0,password:typeof R.password==="string"?R.password:void 0,token:typeof R.token==="string"?R.token:void 0}:void 0,credentialExpiresAt:typeof R.credentialExpiresAt==="string"?R.credentialExpiresAt:void 0,actorId:P.actor.id});return m({registry:M,requestId:C},201,C,Q)}else if(y.method==="PATCH"&&k.pathname==="/api/v1/registry-connections"){if(!e.applications)throw new ie("not_found","Application onboarding is unavailable.",404);t.authorize(P,"applications:manage",{type:"organization"});let R=await Y(),M=e.applications.registries.get(String(R.id??""));if(!M||M.organizationId!==P.serviceAccount.organizationId)throw new ie("not_found","Registry connection was not found.",404);if(R.action==="test")D={registry:await e.applications.registries.test(M.id,{image:typeof R.image==="string"?R.image:void 0}),requestId:C};else if(R.action==="rotate")D={registry:e.applications.registries.rotate(M.id,{username:R.username,password:R.password,token:R.token},{expiresAt:R.expiresAt,actorId:P.actor.id}),requestId:C};else throw new ie("validation_error","action must be test or rotate.",422)}else if(y.method==="DELETE"&&k.pathname==="/api/v1/registry-connections"){if(!e.applications)throw new ie("not_found","Application onboarding is unavailable.",404);t.authorize(P,"applications:manage",{type:"organization"});let R=await Y(),M=e.applications.registries.get(String(R.id??""));if(!M||M.organizationId!==P.serviceAccount.organizationId)throw new ie("not_found","Registry connection was not found.",404);D={registry:e.applications.registries.disconnect(M.id,P.actor.id),requestId:C}}else if(y.method==="POST"&&k.pathname==="/api/v1/application-artifacts"){if(!e.applications?.artifacts)throw new ie("not_found","Application artifact storage is unavailable.",404);let R=y.headers.get("x-project-id")??"";t.authorize(P,"applications:manage",{type:"project",id:R});let M=e.controlPlane.getProject(R);if(!M||M.organizationId!==P.serviceAccount.organizationId)throw new ie("not_found","Project was not found.",404);if(Number(y.headers.get("content-length")??0)>104857600)throw new ie("payload_too_large","Artifact exceeds 100 MB.",413);let K=e.applications.artifacts.create({organizationId:M.organizationId,projectId:R,filename:y.headers.get("x-artifact-filename")??"application.zip",bytes:new Uint8Array(await y.arrayBuffer()),actorId:P.actor.id});return m({artifact:K,requestId:C},201,C,Q)}else if(y.method==="POST"&&k.pathname==="/api/v1/source/connections"){if(!e.sources)throw new ie("not_found","Source integrations are unavailable.",404);t.authorize(P,"sources:manage",{type:"organization"});let R=await Y(),M=String(R.provider??"");if(!["github","gitlab","bitbucket","gitea","generic_https","generic_ssh"].includes(M))throw new ie("validation_error","A supported provider is required.",422);let F=M==="github"&&(R.privateKey||R.appId)?{appId:typeof R.appId==="string"?R.appId:void 0,installationId:typeof R.installationId==="string"?R.installationId:void 0,privateKey:typeof R.privateKey==="string"?R.privateKey:void 0}:M!=="generic_ssh"&&R.token?{token:String(R.token),username:typeof R.username==="string"?R.username:void 0}:void 0,K,ye,Ae;return e.controlPlane.database.transaction(()=>{if(K=e.sources.createConnection({organizationId:P.serviceAccount.organizationId,provider:M,name:String(R.name??M),host:String(R.host??""),owner:typeof R.owner==="string"?R.owner:void 0,authKind:R.authKind,credential:F,createdByActorId:P.actor.id}),typeof R.repositoryUrl==="string"&&typeof R.repositoryFullName==="string")ye=e.sources.upsertRepository({connectionId:K.id,providerRepositoryId:`manual:${R.repositoryFullName}`,fullName:R.repositoryFullName,cloneUrl:R.repositoryUrl,defaultBranch:String(R.defaultBranch??"main"),visibility:"unknown",archived:!1,metadata:{source:"api"}});if(M==="generic_ssh")Ae=e.sources.createDeployKey({connectionId:K.id,name:String(R.deployKeyName??"Repository deploy key"),publicKey:String(R.publicKey??""),privateKey:String(R.deployPrivateKey??""),host:String(R.sshHost??""),hostKey:String(R.hostKey??""),actorId:P.actor.id})})(),m({connection:K,repository:ye,deployKey:Ae,requestId:C},201,C,Q)}else if(y.method==="POST"&&k.pathname==="/api/v1/source/bindings"){if(!e.sources)throw new ie("not_found","Source integrations are unavailable.",404);let R=await Y(),M=String(R.projectId??"");t.authorize(P,"sources:manage",{type:"project",id:M});let F=e.sources.getConnection(String(R.connectionId??""));if(!F||F.organizationId!==P.serviceAccount.organizationId)throw new ie("not_found","Source connection was not found.",404);let K=e.sources.createBinding({projectId:M,environmentId:typeof R.environmentId==="string"?R.environmentId:void 0,resourceId:typeof R.resourceId==="string"?R.resourceId:void 0,connectionId:F.id,repositoryId:typeof R.repositoryId==="string"?R.repositoryId:void 0,repositoryFullName:String(R.repositoryFullName??""),defaultBranch:String(R.defaultBranch??"main"),branchRule:typeof R.branchRule==="string"?R.branchRule:void 0,tagRule:typeof R.tagRule==="string"?R.tagRule:void 0,monorepoRoot:String(R.monorepoRoot??"."),includePaths:Array.isArray(R.includePaths)?R.includePaths.map(String):[],excludePaths:Array.isArray(R.excludePaths)?R.excludePaths.map(String):[],submodules:R.submodules===!0,cloneDepth:typeof R.cloneDepth==="number"?R.cloneDepth:void 0,deployKeyId:typeof R.deployKeyId==="string"&&R.deployKeyId?R.deployKeyId:void 0,autoDeploy:R.autoDeploy!==!1,pullRequestPreviews:R.pullRequestPreviews!==!1,actorId:P.actor.id});return m({binding:K,requestId:C},201,C,Q)}else if(y.method==="POST"&&k.pathname==="/api/v1/source/webhooks"){if(!e.sources)throw new ie("not_found","Source integrations are unavailable.",404);t.authorize(P,"sources:manage",{type:"organization"});let R=await Y(),M=e.sources.getConnection(String(R.connectionId??""));if(!M||M.organizationId!==P.serviceAccount.organizationId)throw new ie("not_found","Source connection was not found.",404);let F=typeof R.baseUrl==="string"?R.baseUrl:void 0;if(!F)throw new ie("validation_error","baseUrl is required.",422);let K=e.sources.createWebhook({connectionId:M.id,repositoryId:typeof R.repositoryId==="string"?R.repositoryId:void 0,repositoryFullName:String(R.repositoryFullName??""),events:Array.isArray(R.events)?R.events.map(String):void 0}),ye=bi(F,K.webhook),Ae=R.reconcile===!1?K.webhook:await po(e.sources,K.webhook.id,F);return m({webhook:Ae,endpoint:ye,endpointRevealOnce:!0,requestId:C},201,C,Q)}else if(y.method==="DELETE"&&k.pathname==="/api/v1/source/connections"){if(!e.sources)throw new ie("not_found","Source integrations are unavailable.",404);t.authorize(P,"sources:manage",{type:"organization"});let R=await Y(),M=e.sources.getConnection(String(R.id??""));if(!M||M.organizationId!==P.serviceAccount.organizationId)throw new ie("not_found","Source connection was not found.",404);let F=e.sources.listBindings({connectionId:M.id,status:"active"});if(R.preview===!0)return m({preview:!0,affectedBindings:F,requestId:C},200,C,Q);return m({...e.sources.disconnectConnection(M.id,P.actor.id),requestId:C},200,C,Q)}else if(y.method==="GET"&&(k.pathname==="/api/v1/events"||k.pathname==="/api/v1/events/stream")){let R=t.listEvents(P,k.searchParams.get("projectId")??void 0,Number(k.searchParams.get("after"))||void 0);if(k.pathname.endsWith("/stream")){let M=new TextEncoder,F=R.reduce((G,be)=>Math.max(G,Number(be.sequence)),Number(k.searchParams.get("after"))||0),K,ye=!1,Ae=new ReadableStream({start(G){let be=(ge)=>G.enqueue(M.encode(`id: ${ge.sequence}
|
|
32
|
+
event: ${ge.type}
|
|
33
|
+
data: ${JSON.stringify(ge)}
|
|
34
|
+
|
|
35
|
+
`));if(R.length)R.forEach(be);else G.enqueue(M.encode(`: connected
|
|
36
|
+
|
|
37
|
+
`));K=setInterval(()=>{if(ye)return;let ge=e.identities.verifyToken(j,w);if(!ge){if(ye=!0,K)clearInterval(K);G.close();return}try{let oe=t.listEvents(ge,k.searchParams.get("projectId")??void 0,F);for(let ft of oe)be(ft),F=Math.max(F,Number(ft.sequence));if(!oe.length)G.enqueue(M.encode(`: heartbeat ${Date.now()}
|
|
38
|
+
|
|
39
|
+
`))}catch{if(ye=!0,K)clearInterval(K);G.close()}},1000),y.signal.addEventListener("abort",()=>{if(ye=!0,K)clearInterval(K);try{G.close()}catch{}},{once:!0})},cancel(){if(ye=!0,K)clearInterval(K)}});return new Response(Ae,{status:200,headers:{"content-type":"text/event-stream","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no","x-request-id":C,...Q}})}D=Et(R,k,C,["sequence","id"])}else if(y.method==="POST"&&k.pathname==="/api/v1/deployments"){let R=y.headers.get("idempotency-key")??"";if(!R)throw new ie("idempotency_required","Idempotency-Key is required for deployment requests.",428);let M=await y.text();if(M.length>1048576)throw new ie("payload_too_large","Request body exceeds 1 MB.",413);let F;try{F=JSON.parse(M)}catch{throw new ie("invalid_json","Request body must be valid JSON.",400)}if(!F||typeof F.projectId!=="string"||typeof F.environmentId!=="string"||F.action!==void 0&&!["deploy","rollback"].includes(F.action))throw new ie("validation_error","projectId, environmentId, and a valid action are required.",422);let K=t.createDeployment(P,F,R);return m({operation:K.operation,idempotentReplay:K.replay,requestId:C},202,C,{...Q,...K.replay?{"idempotent-replayed":"true"}:{}})}else{let R=await Jm({...c,authorization:t,now:a},P,{method:y.method,url:k,body:Y});if(R===void 0)throw new ie("not_found","API resource was not found.",404);D=R}return m(D,200,C,Q)}catch(D){if(D instanceof ie)return h(D.code,D.message,D.status,C,D.details,Q);if(k.pathname.startsWith("/api/v1/source/")||k.pathname.startsWith("/api/v1/application")||k.pathname.startsWith("/api/v1/compose-")||k.pathname==="/api/v1/registry-connections")return h("validation_error",D instanceof Error?D.message:"Integration request could not be completed.",422,C,void 0,Q);return h("internal_error","The API request could not be completed.",500,C,void 0,Q)}}}import{createCipheriv as ak,createDecipheriv as ck,createHash as eg,randomBytes as Ar}from"node:crypto";import{createHmac as nk,timingSafeEqual as ik}from"node:crypto";var Wc="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";function Ss(e){let t=0,r=0,n="";for(let i of e){r=r<<8|i,t+=8;while(t>=5)n+=Wc[r>>>t-5&31],t-=5}if(t>0)n+=Wc[r<<5-t&31];return n}function Gm(e){let t=e.toUpperCase().replace(/[^A-Z2-7]/g,""),r=0,n=0,i=[];for(let o of t){let s=Wc.indexOf(o);if(s<0)throw Error("Invalid base32 secret");if(n=n<<5|s,r+=5,r>=8)i.push(n>>>r-8&255),r-=8}return Buffer.from(i)}function Hc(e,t,r=6){let n=Buffer.alloc(8);n.writeBigUInt64BE(BigInt(t));let i=nk("sha1",Gm(e)).update(n).digest(),o=i[i.length-1]&15,s=(i[o]&127)<<24|(i[o+1]&255)<<16|(i[o+2]&255)<<8|i[o+3]&255;return String(s%10**r).padStart(r,"0")}function ok(e,t=Date.now(),r=30){return Hc(e,Math.floor(t/1000/r))}function sk(e,t,r=Date.now(),n=1){return mo(e,t,r,n)!==void 0}function mo(e,t,r=Date.now(),n=1){let i=t.replace(/[\s-]/g,"");if(!/^\d{6}$/.test(i))return;let o=Buffer.from(i),s=Math.floor(r/1000/30);for(let c=-n;c<=n;c++){if(s+c<0)continue;let d=Buffer.from(Hc(e,s+c));if(o.length===d.length&&ik(o,d))return s+c}return}function Kc(e){let t=e.issuer?.trim()||"ts-cloud",r=`${t}:${e.account}`;return`otpauth://totp/${encodeURIComponent(r)}?secret=${encodeURIComponent(e.secret)}&issuer=${encodeURIComponent(t)}&algorithm=SHA1&digits=6&period=30`}var tg=1800000,nn=43200000,rg=3600000,ng=300000,ig=600000;function Bt(e){return typeof e==="string"?e:void 0}function og(e){if(typeof e!=="string")return{};try{return JSON.parse(e)}catch{return{}}}function dk(e){let t=e.trim();if(!/^[a-z0-9][a-z0-9._-]{1,31}$/i.test(t))throw Error("Username must be 2-32 characters: letters, numbers, dot, dash or underscore");return t}function Jc(e){if(e===void 0||!e.trim())return;let t=e.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)||t.length>254)throw Error("A valid email address is required");return t}function lk(e){let t=e.trim().toLowerCase();if(!/^[a-z0-9][a-z0-9-]{1,47}$/.test(t))throw Error("OIDC provider slug must be 2-48 lowercase letters, numbers or dashes");return t}function uk(e){let t=new URL(e.trim());if(t.search||t.hash||t.username||t.password)throw Error("OIDC issuer cannot contain credentials, a query, or a fragment");if(t.protocol!=="https:"&&!(t.protocol==="http:"&&["127.0.0.1","::1","localhost"].includes(t.hostname)))throw Error("OIDC issuer must use HTTPS");return t.href.replace(/\/$/,"")}function pk(e){let t=[...new Set(e.map((r)=>r.trim().toLowerCase()).filter(Boolean))];if(t.length===0)throw Error("At least one explicit OIDC email domain is required");if(t.some((r)=>!/^[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?$/.test(r)||!r.includes(".")||r.includes("..")))throw Error("OIDC email domains must be explicit DNS names without wildcards");return t}function mk(e){let t=[...new Set(["openid",...e??["email","profile"]].map((r)=>r.trim()).filter(Boolean))];if(t.some((r)=>!/^[\x21\x23-\x5B\x5D-\x7E]+$/.test(r)))throw Error("OIDC scopes contain unsupported characters");return t}function Zt(e){return eg("sha256").update(e).digest("hex")}function go(e){return{id:String(e.id),actorId:String(e.actor_id),username:String(e.username),email:Bt(e.email),emailVerifiedAt:Bt(e.email_verified_at),passwordHash:String(e.password_hash),credentialVersion:Number(e.credential_version),requiresPasswordUpgrade:Number(e.requires_password_upgrade)===1,disabledAt:Bt(e.disabled_at),lastLoginAt:Bt(e.last_login_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Qm(e,t){let r=Bt(e.consumed_at),n=String(e.expires_at);return{id:String(e.id),identityId:String(e.identity_id),type:String(e.type),metadata:og(e.metadata),expiresAt:n,consumedAt:r,createdAt:String(e.created_at),state:r?"consumed":n<=t?"expired":"pending"}}function Gc(e,t){let r=Bt(e.revoked_at),n=String(e.idle_expires_at),i=String(e.absolute_expires_at);return{id:String(e.id),identityId:String(e.identity_id),credentialVersion:Number(e.credential_version),authMethod:String(e.auth_method),userAgent:Bt(e.user_agent),networkHint:Bt(e.network_hint),createdAt:String(e.created_at),lastUsedAt:String(e.last_used_at),idleExpiresAt:n,absoluteExpiresAt:i,recentAuthAt:String(e.recent_auth_at),mfaAt:Bt(e.mfa_at),revokedAt:r,state:r?"revoked":n<=t||i<=t?"expired":"active"}}function Ym(e){let t=Bt(e.verified_at),r=Bt(e.disabled_at);return{id:String(e.id),identityId:String(e.identity_id),type:"totp",label:String(e.label),createdAt:String(e.created_at),verifiedAt:t,disabledAt:r,state:r?"disabled":t?"active":"pending"}}function Qc(e,t){let r=Bt(e.consumed_at),n=String(e.expires_at),i=Number(e.attempts);return{id:String(e.id),identityId:String(e.identity_id),purpose:String(e.purpose),attempts:i,expiresAt:n,consumedAt:r,createdAt:String(e.created_at),state:r?"consumed":i>=5?"locked":n<=t?"expired":"pending"}}function Zm(e){let t=og(e);return Array.isArray(t)?t.filter((r)=>typeof r==="string"):[]}function ws(e){return{id:String(e.id),organizationId:String(e.organization_id),slug:String(e.slug),name:String(e.name),issuer:String(e.issuer),clientId:String(e.client_id),hasClientSecret:typeof e.client_secret_ciphertext==="string"&&e.client_secret_ciphertext.length>0,scopes:Zm(e.scopes),allowedDomains:Zm(e.allowed_domains),defaultRole:String(e.default_role),enabled:Number(e.enabled)===1,enforceSso:Number(e.enforce_sso)===1,createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Xm(e,t){let r=Bt(e.consumed_at),n=String(e.expires_at);return{id:String(e.id),providerId:String(e.provider_id),redirectUri:String(e.redirect_uri),returnPath:String(e.return_path),expiresAt:n,consumedAt:r,createdAt:String(e.created_at),state:r?"consumed":n<=t?"expired":"pending"}}function gk(e){return{id:String(e.id),providerId:String(e.provider_id),identityId:String(e.identity_id),subject:String(e.subject),email:String(e.email),linkedAt:String(e.linked_at),lastLoginAt:String(e.last_login_at)}}class ks{controlPlane;nowFn;idFn;encryptionKey;constructor(e,t={}){this.controlPlane=e;this.nowFn=t.now??(()=>new Date),this.idFn=t.id??(()=>crypto.randomUUID()),this.encryptionKey=t.encryptionKey?eg("sha256").update(t.encryptionKey).digest():void 0}now(){return this.nowFn().toISOString()}run(e,t){this.controlPlane.database.run(e,t)}encrypt(e){if(!this.encryptionKey)throw Error("Authentication encryption key is not configured");let t=Ar(12),r=ak("aes-256-gcm",this.encryptionKey,t),n=Buffer.concat([r.update(e,"utf8"),r.final()]);return`v1.${t.toString("base64url")}.${r.getAuthTag().toString("base64url")}.${n.toString("base64url")}`}decrypt(e){if(!this.encryptionKey)throw Error("Authentication encryption key is not configured");let[t,r,n,i]=e.split(".");if(t!=="v1"||!r||!n||!i)throw Error("Encrypted authentication value is unavailable");let o=ck("aes-256-gcm",this.encryptionKey,Buffer.from(r,"base64url"));return o.setAuthTag(Buffer.from(n,"base64url")),Buffer.concat([o.update(Buffer.from(i,"base64url")),o.final()]).toString("utf8")}createIdentity(e){if(!this.controlPlane.getActor(e.actorId))throw Error("Authentication actor was not found");let t=dk(e.username),r=Jc(e.email),n=e.id??this.idFn(),i=this.now();return this.run(`INSERT INTO auth_identities (id, actor_id, username, email, email_verified_at, password_hash, requires_password_upgrade, created_at, updated_at)
|
|
40
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n,e.actorId,t,r??null,e.emailVerified&&r?i:null,e.passwordHash,e.requiresPasswordUpgrade?1:0,i,i]),this.getIdentity(n)}getIdentity(e){let t=this.controlPlane.database.query("SELECT * FROM auth_identities WHERE id = ?").get(e);return t?go(t):void 0}getIdentityByActor(e){let t=this.controlPlane.database.query("SELECT * FROM auth_identities WHERE actor_id = ?").get(e);return t?go(t):void 0}getIdentityByUsername(e){let t=this.controlPlane.database.query("SELECT * FROM auth_identities WHERE username = ? COLLATE NOCASE").get(e.trim());return t?go(t):void 0}getIdentityByEmail(e){let t=this.controlPlane.database.query("SELECT * FROM auth_identities WHERE email = ? COLLATE NOCASE").get(e.trim().toLowerCase());return t?go(t):void 0}listIdentities(){return this.controlPlane.database.query("SELECT * FROM auth_identities ORDER BY username COLLATE NOCASE").all().map(go)}updatePassword(e,t,r={}){if(!this.getIdentity(e))throw Error("Authentication identity was not found");let i=this.now();return this.controlPlane.transaction(()=>{if(this.run(`UPDATE auth_identities SET password_hash = ?, credential_version = credential_version + 1,
|
|
41
|
+
requires_password_upgrade = ?, updated_at = ? WHERE id = ?`,[t,r.requiresUpgrade?1:0,i,e]),r.revokeSessions!==!1)this.run("UPDATE auth_sessions SET revoked_at = ? WHERE identity_id = ? AND revoked_at IS NULL",[i,e])}),this.getIdentity(e)}rehashPassword(e,t){let r=this.now();this.run("UPDATE auth_identities SET password_hash = ?, requires_password_upgrade = 0, updated_at = ? WHERE id = ?",[t,r,e]);let n=this.getIdentity(e);if(!n)throw Error("Authentication identity was not found");return n}setVerifiedEmail(e,t){let r=Jc(t),n=this.now();this.run("UPDATE auth_identities SET email = ?, email_verified_at = ?, updated_at = ? WHERE id = ?",[r,n,n,e]);let i=this.getIdentity(e);if(!i)throw Error("Authentication identity was not found");return i}recordLogin(e){let t=this.now();this.run("UPDATE auth_identities SET last_login_at = ?, updated_at = ? WHERE id = ?",[t,t,e]);let r=this.getIdentity(e);if(!r)throw Error("Authentication identity was not found");return r}setDisabled(e,t){let r=this.now();this.controlPlane.transaction(()=>{if(this.run("UPDATE auth_identities SET disabled_at = ?, credential_version = credential_version + 1, updated_at = ? WHERE id = ?",[t?r:null,r,e]),t)this.run("UPDATE auth_sessions SET revoked_at = ? WHERE identity_id = ? AND revoked_at IS NULL",[r,e])});let n=this.getIdentity(e);if(!n)throw Error("Authentication identity was not found");return n}createActionToken(e,t,r={}){if(!this.getIdentity(e))throw Error("Authentication identity was not found");let n=Ar(32).toString("base64url"),i=this.idFn(),o=this.now(),s=new Date(this.nowFn().getTime()+Math.min(86400000,Math.max(60000,r.ttlMs??rg))).toISOString();return this.run("INSERT INTO auth_action_tokens (id, identity_id, type, token_hash, metadata, expires_at, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[i,e,t,Zt(n),JSON.stringify(r.metadata??{}),s,o]),{actionToken:this.getActionToken(i),token:n}}getActionToken(e){let t=this.controlPlane.database.query("SELECT * FROM auth_action_tokens WHERE id = ?").get(e);return t?Qm(t,this.now()):void 0}consumeActionToken(e,t){return this.controlPlane.transaction(()=>{let r=this.controlPlane.database.query("SELECT * FROM auth_action_tokens WHERE token_hash = ? AND type = ?").get(Zt(e),t);if(!r)throw Error("Action token is invalid");let n=Qm(r,this.now());if(n.state!=="pending")throw Error(`Action token is ${n.state}`);if(this.controlPlane.database.run("UPDATE auth_action_tokens SET consumed_at = ? WHERE id = ? AND consumed_at IS NULL AND expires_at > ?",[this.now(),n.id,this.now()]).changes!==1)throw Error("Action token is no longer available");return this.getActionToken(n.id)})}revokeActionTokens(e,t){return this.controlPlane.database.run("UPDATE auth_action_tokens SET consumed_at = ? WHERE identity_id = ? AND type = ? AND consumed_at IS NULL",[this.now(),e,t]).changes}createSession(e){let t=this.getIdentity(e.identityId);if(!t||t.disabledAt)throw Error("Authentication identity is unavailable");let r=this.idFn(),n=Ar(32).toString("base64url"),i=`v2.${r}.${n}`,o=this.now(),s=Math.min(86400000,Math.max(60000,e.idleTtlMs??tg)),c=Math.min(2592000000,Math.max(s,e.absoluteTtlMs??nn));return this.run(`INSERT INTO auth_sessions (id, identity_id, token_hash, credential_version, auth_method, user_agent, network_hint,
|
|
42
|
+
created_at, last_used_at, idle_expires_at, absolute_expires_at, recent_auth_at, mfa_at)
|
|
43
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[r,t.id,Zt(i),t.credentialVersion,e.authMethod??"local",e.userAgent?.slice(0,256)??null,e.networkHint?.slice(0,128)??null,o,o,new Date(this.nowFn().getTime()+s).toISOString(),new Date(this.nowFn().getTime()+c).toISOString(),e.recentAuthAt??o,e.mfaAt??null]),{session:this.getSession(r),token:i}}getSession(e){let t=this.controlPlane.database.query("SELECT * FROM auth_sessions WHERE id = ?").get(e);return t?Gc(t,this.now()):void 0}verifySessionToken(e){let t=/^v2\.([^.]+)\.[A-Za-z0-9_-]{40,}$/.exec(e);if(!t)return;let r=this.controlPlane.database.query("SELECT * FROM auth_sessions WHERE id = ? AND token_hash = ?").get(t[1],Zt(e));if(!r)return;let n=Gc(r,this.now()),i=this.getIdentity(n.identityId);if(!i||i.disabledAt||n.state!=="active"||n.credentialVersion!==i.credentialVersion)return;let o=this.now(),s=new Date(r.idle_expires_at).getTime()-new Date(r.last_used_at).getTime();return this.run("UPDATE auth_sessions SET last_used_at = ?, idle_expires_at = ? WHERE id = ?",[o,new Date(Math.min(this.nowFn().getTime()+s,new Date(n.absoluteExpiresAt).getTime())).toISOString(),n.id]),{identity:i,session:this.getSession(n.id)}}listSessions(e,t={}){let r=this.controlPlane.database.query("SELECT * FROM auth_sessions WHERE identity_id = ? ORDER BY last_used_at DESC").all(e).map((n)=>Gc(n,this.now()));return t.includeInactive?r:r.filter((n)=>n.state==="active")}revokeSession(e,t){return this.controlPlane.database.run("UPDATE auth_sessions SET revoked_at = ? WHERE id = ? AND identity_id = ? AND revoked_at IS NULL",[this.now(),t,e]).changes===1}revokeOtherSessions(e,t){return this.controlPlane.database.run("UPDATE auth_sessions SET revoked_at = ? WHERE identity_id = ? AND id != ? AND revoked_at IS NULL",[this.now(),e,t]).changes}getMfaFactor(e){let t=this.controlPlane.database.query("SELECT * FROM auth_mfa_factors WHERE identity_id = ?").get(e);return t?Ym(t):void 0}beginTotpEnrollment(e,t={}){let r=this.getIdentity(e);if(!r)throw Error("Authentication identity was not found");let n=this.getMfaFactor(e);if(n?.state==="active")throw Error("MFA is already enabled");let i=Ss(Ar(20)),o=t.label?.trim().slice(0,80)||r.email||r.username,s=n?.id??this.idFn(),c=this.now();return this.controlPlane.transaction(()=>{if(n)this.run("UPDATE auth_mfa_factors SET label = ?, secret_ciphertext = ?, created_at = ?, verified_at = NULL, disabled_at = NULL WHERE id = ?",[o,this.encrypt(i),c,s]);else this.run("INSERT INTO auth_mfa_factors (id, identity_id, label, secret_ciphertext, created_at) VALUES (?, ?, ?, ?, ?)",[s,e,o,this.encrypt(i),c]);this.run("DELETE FROM auth_recovery_codes WHERE identity_id = ?",[e])}),{factor:this.getMfaFactor(e),secret:i,uri:Kc({secret:i,account:o,issuer:t.issuer})}}verifyTotpEnrollment(e,t){let r=this.controlPlane.database.query("SELECT * FROM auth_mfa_factors WHERE identity_id = ?").get(e);if(!r||Ym(r).state!=="pending")throw Error("MFA enrollment is not pending");let n=mo(this.decrypt(String(r.secret_ciphertext)),t,this.nowFn().getTime());if(n===void 0)throw Error("Authenticator code is invalid");let i=Array.from({length:10},()=>{let s=Ss(Ar(8)).slice(0,12);return`${s.slice(0,4)}-${s.slice(4,8)}-${s.slice(8)}`}),o=this.now();return this.controlPlane.transaction(()=>{this.run("UPDATE auth_mfa_factors SET verified_at = ?, disabled_at = NULL, last_used_step = ? WHERE identity_id = ?",[o,n,e]),this.run("DELETE FROM auth_recovery_codes WHERE identity_id = ?",[e]);for(let s of i)this.run("INSERT INTO auth_recovery_codes (id, identity_id, code_hash, created_at) VALUES (?, ?, ?, ?)",[this.idFn(),e,Zt(`${e}:${s.replace(/-/g,"").toUpperCase()}`),o])}),{factor:this.getMfaFactor(e),recoveryCodes:i}}verifyMfaCode(e,t,r={}){let n=this.controlPlane.database.query("SELECT * FROM auth_mfa_factors WHERE identity_id = ? AND verified_at IS NOT NULL AND disabled_at IS NULL").get(e);if(!n)return{valid:!1};let i=mo(this.decrypt(String(n.secret_ciphertext)),t,this.nowFn().getTime());if(i!==void 0){if(this.controlPlane.database.run("UPDATE auth_mfa_factors SET last_used_step = ? WHERE identity_id = ? AND (last_used_step IS NULL OR last_used_step < ?)",[i,e,i]).changes===1)return{valid:!0,method:"totp"}}let o=t.replace(/[-\s]/g,"").toUpperCase();if(!/^[A-Z2-7]{12}$/.test(o))return{valid:!1};let s=Zt(`${e}:${o}`),c=this.controlPlane.database.query("SELECT * FROM auth_recovery_codes WHERE identity_id = ? AND code_hash = ? AND consumed_at IS NULL").get(e,s);if(!c)return{valid:!1};if(r.consumeRecovery!==!1){if(this.controlPlane.database.run("UPDATE auth_recovery_codes SET consumed_at = ? WHERE id = ? AND consumed_at IS NULL",[this.now(),String(c.id)]).changes!==1)return{valid:!1}}return{valid:!0,method:"recovery"}}remainingRecoveryCodes(e){return Number(this.controlPlane.database.query("SELECT COUNT(*) AS count FROM auth_recovery_codes WHERE identity_id = ? AND consumed_at IS NULL").get(e)?.count??0)}disableMfa(e){let t=this.now();this.controlPlane.transaction(()=>{this.run("UPDATE auth_mfa_factors SET disabled_at = ? WHERE identity_id = ? AND disabled_at IS NULL",[t,e]),this.run("DELETE FROM auth_recovery_codes WHERE identity_id = ?",[e]),this.run("UPDATE auth_mfa_challenges SET consumed_at = ? WHERE identity_id = ? AND consumed_at IS NULL",[t,e])})}createMfaChallenge(e,t){if(this.getMfaFactor(e)?.state!=="active")throw Error("MFA is not enabled");let r=Ar(32).toString("base64url"),n=this.idFn(),i=this.now(),o=new Date(this.nowFn().getTime()+ng).toISOString();return this.controlPlane.transaction(()=>{this.run("UPDATE auth_mfa_challenges SET consumed_at = ? WHERE identity_id = ? AND purpose = ? AND consumed_at IS NULL",[i,e,t]),this.run("INSERT INTO auth_mfa_challenges (id, identity_id, purpose, token_hash, expires_at, created_at) VALUES (?, ?, ?, ?, ?, ?)",[n,e,t,Zt(r),o,i])}),{challenge:this.getMfaChallenge(n),token:r}}getMfaChallenge(e){let t=this.controlPlane.database.query("SELECT * FROM auth_mfa_challenges WHERE id = ?").get(e);return t?Qc(t,this.now()):void 0}inspectMfaChallengeToken(e,t){let r=this.controlPlane.database.query("SELECT * FROM auth_mfa_challenges WHERE token_hash = ? AND purpose = ?").get(Zt(e),t);return r?Qc(r,this.now()):void 0}completeMfaChallenge(e,t,r){let n=this.controlPlane.database.query("SELECT * FROM auth_mfa_challenges WHERE token_hash = ? AND purpose = ?").get(Zt(e),r);if(!n)throw Error("MFA challenge is invalid");let i=Qc(n,this.now());if(i.state!=="pending")throw Error(`MFA challenge is ${i.state}`);let o=this.verifyMfaCode(i.identityId,t);if(!o.valid||!o.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:o.method}}markSessionStepUp(e,t=!1){let r=this.now();this.run("UPDATE auth_sessions SET recent_auth_at = ?, mfa_at = CASE WHEN ? = 1 THEN ? ELSE mfa_at END WHERE id = ? AND revoked_at IS NULL",[r,t?1:0,r,e]);let n=this.getSession(e);if(!n)throw Error("Authentication session was not found");return n}isRecentlyAuthenticated(e,t=600000){return this.nowFn().getTime()-new Date(e.recentAuthAt).getTime()<=t}upsertOidcProvider(e){if(!this.controlPlane.getOrganization(e.organizationId))throw Error("OIDC provider organization was not found");let t=lk(e.slug),r=e.name.trim().slice(0,80);if(!r)throw Error("OIDC provider name is required");let n=uk(e.issuer),i=e.clientId.trim();if(!i||i.length>512)throw Error("OIDC client ID is required");let o=mk(e.scopes),s=pk(e.allowedDomains),c=e.id?this.getOidcProvider(e.id):this.getOidcProviderBySlug(t),d=this.now();if(c){if(c.organizationId!==e.organizationId)throw Error("OIDC provider belongs to another organization");return this.run(`UPDATE auth_oidc_providers SET slug = ?, name = ?, issuer = ?, client_id = ?,
|
|
44
|
+
client_secret_ciphertext = COALESCE(?, client_secret_ciphertext), scopes = ?, allowed_domains = ?,
|
|
45
|
+
default_role = ?, enabled = ?, enforce_sso = ?, updated_at = ? WHERE id = ?`,[t,r,n,i,e.clientSecret?this.encrypt(e.clientSecret):null,JSON.stringify(o),JSON.stringify(s),e.defaultRole??c.defaultRole,e.enabled??c.enabled?1:0,e.enforceSso??c.enforceSso?1:0,d,c.id]),this.getOidcProvider(c.id)}if(!e.clientSecret)throw Error("OIDC client secret is required for a new provider");let a=e.id??this.idFn();return this.run(`INSERT INTO auth_oidc_providers (id, organization_id, slug, name, issuer, client_id,
|
|
46
|
+
client_secret_ciphertext, scopes, allowed_domains, default_role, enabled, enforce_sso, created_at, updated_at)
|
|
47
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[a,e.organizationId,t,r,n,i,this.encrypt(e.clientSecret),JSON.stringify(o),JSON.stringify(s),e.defaultRole??"viewer",e.enabled===!1?0:1,e.enforceSso?1:0,d,d]),this.getOidcProvider(a)}getOidcProvider(e){let t=this.controlPlane.database.query("SELECT * FROM auth_oidc_providers WHERE id = ?").get(e);return t?ws(t):void 0}getOidcProviderBySlug(e){let t=this.controlPlane.database.query("SELECT * FROM auth_oidc_providers WHERE slug = ? COLLATE NOCASE").get(e.trim());return t?ws(t):void 0}listOidcProviders(e,t={}){return(e?this.controlPlane.database.query("SELECT * FROM auth_oidc_providers WHERE organization_id = ? ORDER BY name COLLATE NOCASE").all(e):this.controlPlane.database.query("SELECT * FROM auth_oidc_providers ORDER BY name COLLATE NOCASE").all()).map(ws).filter((n)=>t.includeDisabled||n.enabled)}setOidcProviderEnabled(e,t){let r=this.now();if(this.controlPlane.database.run("UPDATE auth_oidc_providers SET enabled = ?, enforce_sso = CASE WHEN ? = 0 THEN 0 ELSE enforce_sso END, updated_at = ? WHERE id = ?",[t?1:0,t?1:0,r,e]).changes!==1)throw Error("OIDC provider was not found");if(!t)this.run("UPDATE auth_oidc_transactions SET consumed_at = ? WHERE provider_id = ? AND consumed_at IS NULL",[r,e]);return this.getOidcProvider(e)}getOidcProviderCredentials(e){let t=this.controlPlane.database.query("SELECT * FROM auth_oidc_providers WHERE id = ?").get(e);if(!t||typeof t.client_secret_ciphertext!=="string")throw Error("OIDC provider credentials are unavailable");return{provider:ws(t),clientSecret:this.decrypt(t.client_secret_ciphertext)}}beginOidcTransaction(e,t,r){if(!this.getOidcProvider(e)?.enabled)throw Error("OIDC provider is unavailable");let i=this.idFn(),o=Ar(32).toString("base64url"),s=Ar(32).toString("base64url"),c=Ar(64).toString("base64url"),d=this.now(),a=new Date(this.nowFn().getTime()+ig).toISOString();return this.run(`INSERT INTO auth_oidc_transactions (id, provider_id, state_hash, nonce_ciphertext, verifier_ciphertext,
|
|
48
|
+
redirect_uri, return_path, expires_at, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i,e,Zt(o),this.encrypt(s),this.encrypt(c),t,r,a,d]),{transaction:this.getOidcTransaction(i),state:o,nonce:s,verifier:c}}getOidcTransaction(e){let t=this.controlPlane.database.query("SELECT * FROM auth_oidc_transactions WHERE id = ?").get(e);return t?Xm(t,this.now()):void 0}consumeOidcTransaction(e,t){return this.controlPlane.transaction(()=>{let r=this.controlPlane.database.query("SELECT * FROM auth_oidc_transactions WHERE provider_id = ? AND state_hash = ?").get(e,Zt(t));if(!r)throw Error("OIDC transaction is invalid");let n=Xm(r,this.now());if(n.state!=="pending")throw Error(`OIDC transaction is ${n.state}`);if(this.controlPlane.database.run("UPDATE auth_oidc_transactions SET consumed_at = ? WHERE id = ? AND consumed_at IS NULL AND expires_at > ?",[this.now(),n.id,this.now()]).changes!==1)throw Error("OIDC transaction is no longer available");return{transaction:this.getOidcTransaction(n.id),nonce:this.decrypt(String(r.nonce_ciphertext)),verifier:this.decrypt(String(r.verifier_ciphertext))}})}getOidcSubject(e,t){let r=this.controlPlane.database.query("SELECT * FROM auth_oidc_subjects WHERE provider_id = ? AND subject = ?").get(e,t);return r?gk(r):void 0}linkOidcSubject(e,t,r,n){let i=this.getOidcProvider(e),o=this.getIdentity(t);if(!i||!o)throw Error("OIDC provider or identity was not found");let s=Jc(n);if(!r.trim()||r.length>512)throw Error("OIDC subject is invalid");let c=this.getOidcSubject(e,r);if(c&&c.identityId!==t)throw Error("OIDC subject is already linked to another identity");let d=this.now();if(c)return this.run("UPDATE auth_oidc_subjects SET email = ?, last_login_at = ? WHERE id = ?",[s,d,c.id]),this.getOidcSubject(e,r);let a=this.idFn();return this.run("INSERT INTO auth_oidc_subjects (id, provider_id, identity_id, subject, email, linked_at, last_login_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[a,e,t,r,s,d,d]),this.getOidcSubject(e,r)}purgeExpired(){let e=this.now(),t=this.controlPlane.database.run("DELETE FROM auth_action_tokens WHERE expires_at < ? OR consumed_at IS NOT NULL",[e]).changes,r=this.controlPlane.database.run("DELETE FROM auth_sessions WHERE revoked_at IS NOT NULL OR idle_expires_at < ? OR absolute_expires_at < ?",[e,e]).changes;return this.controlPlane.database.run("DELETE FROM auth_mfa_challenges WHERE consumed_at IS NOT NULL OR expires_at < ?",[e]),this.controlPlane.database.run("DELETE FROM auth_oidc_transactions WHERE consumed_at IS NOT NULL OR expires_at < ?",[e]),{actionTokens:t,sessions:r}}}async function fo(e,t){let r=e.notifications?.email?.from;if(!r)return!1;try{let{EmailClient:n}=await import("./chunk-a84gmpyh.js");return await new n({region:e.project.region,defaultFrom:r}).send(t),!0}catch{return!1}}import{randomBytes as fk}from"node:crypto";import{chmodSync as hk,existsSync as yk,mkdirSync as vk,readFileSync as bk,writeFileSync as Sk}from"node:fs";import{dirname as wk}from"node:path";function kk(){return ho("auth-encryption-key")}function on(e){let t=process.env.TS_CLOUD_AUTH_ENCRYPTION_KEY?.trim();if(t)return t;let r=yt(e,"auth-encryption-key");try{if(yk(r)){let i=bk(r,"utf8").trim();if(i)return i}}catch{}let n=fk(32).toString("base64url");try{vk(wk(r),{recursive:!0,mode:448}),Sk(r,`${n}
|
|
49
|
+
`,{mode:384}),hk(r,384)}catch{}return n}import{constants as sg,createHash as Yc,createPublicKey as Ik,createVerify as Ek,timingSafeEqual as Rk}from"node:crypto";var cg=new Set(["RS256","PS256","ES256"]),ag=60;function Is(e,t){let r=new URL(e),n=["127.0.0.1","::1","localhost"].includes(r.hostname);if(r.protocol!=="https:"&&!(r.protocol==="http:"&&n))throw Error(`${t} must use HTTPS`);if(r.username||r.password||r.hash)throw Error(`${t} contains unsupported URL components`);return r}function Zc(e,t){if(!e||typeof e!=="object"||Array.isArray(e))throw Error(`${t} is invalid`);return e}async function Xc(e,t){if(!e.ok)throw Error(`${t} failed with HTTP ${e.status}`);if(!(e.headers.get("content-type")??"").toLowerCase().includes("application/json"))throw Error(`${t} returned an unsupported content type`);if(Number(e.headers.get("content-length")??0)>1048576)throw Error(`${t} response is too large`);let i=await e.text();if(i.length>1048576)throw Error(`${t} response is too large`);try{return Zc(JSON.parse(i),t)}catch(o){if(o instanceof Error&&o.message===`${t} is invalid`)throw o;throw Error(`${t} returned invalid JSON`)}}function Ak(e,t){let r=Yc("sha256").update(e).digest(),n=Yc("sha256").update(t).digest();return Rk(r,n)}function dg(e){if(!e)return"/";let t=e.trim();if(!t.startsWith("/")||t.startsWith("//")||t.includes("\\")||/[\r\n]/.test(t))return"/";try{let r=new URL(t,"https://local.invalid");return r.origin==="https://local.invalid"?`${r.pathname}${r.search}${r.hash}`:"/"}catch{return"/"}}async function ed(e,t=fetch){let r=Is(e.issuer,"OIDC issuer"),n=new URL(`${r.pathname.replace(/\/$/,"")}/.well-known/openid-configuration`,r.origin),i=await Xc(await t(n,{headers:{accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(1e4)}),"OIDC discovery");if(i.issuer!==e.issuer)throw Error("OIDC discovery issuer does not match the configured issuer");for(let s of["authorization_endpoint","token_endpoint","jwks_uri"]){if(typeof i[s]!=="string")throw Error(`OIDC discovery is missing ${s}`);Is(i[s],`OIDC ${s}`)}if(Array.isArray(i.response_types_supported)&&!i.response_types_supported.includes("code"))throw Error("OIDC provider does not support authorization code flow");if(Array.isArray(i.code_challenge_methods_supported)&&!i.code_challenge_methods_supported.includes("S256"))throw Error("OIDC provider does not support PKCE S256");let o=Array.isArray(i.id_token_signing_alg_values_supported)?i.id_token_signing_alg_values_supported.filter((s)=>typeof s==="string"):[];if(o.length>0&&!o.some((s)=>cg.has(s)))throw Error("OIDC provider does not offer a supported ID-token signing algorithm");return i}async function td(e,t,r,n,i=fetch){let o=e.getOidcProviderBySlug(t);if(!o?.enabled)throw Error("OIDC provider is unavailable");let s=Is(r,"Application origin").origin,c=await ed(o,i),d=`${s}/auth/oidc/${encodeURIComponent(o.slug)}/callback`,a=e.beginOidcTransaction(o.id,d,dg(n)),u=new URL(c.authorization_endpoint);return u.searchParams.set("response_type","code"),u.searchParams.set("client_id",o.clientId),u.searchParams.set("redirect_uri",d),u.searchParams.set("scope",o.scopes.join(" ")),u.searchParams.set("state",a.state),u.searchParams.set("nonce",a.nonce),u.searchParams.set("code_challenge",Yc("sha256").update(a.verifier).digest("base64url")),u.searchParams.set("code_challenge_method","S256"),{authorizationUrl:u.href,expiresAt:a.transaction.expiresAt}}function Ck(e){if(e.length>32768)throw Error("OIDC ID token is too large");let t=e.split(".");if(t.length!==3||t.some((r)=>!r))throw Error("OIDC ID token is malformed");try{return{header:Zc(JSON.parse(Buffer.from(t[0],"base64url").toString("utf8")),"OIDC ID-token header"),claims:Zc(JSON.parse(Buffer.from(t[1],"base64url").toString("utf8")),"OIDC ID-token claims"),signingInput:`${t[0]}.${t[1]}`,signature:Buffer.from(t[2],"base64url")}}catch(r){if(r instanceof Error&&r.message.startsWith("OIDC"))throw r;throw Error("OIDC ID token is malformed")}}async function Pk(e,t,r){let n=Ck(e),i=typeof n.header.alg==="string"?n.header.alg:"",o=typeof n.header.kid==="string"?n.header.kid:"";if(!cg.has(i)||!o)throw Error("OIDC ID token uses an unsupported signing key");if(t.id_token_signing_alg_values_supported&&!t.id_token_signing_alg_values_supported.includes(i))throw Error("OIDC ID-token algorithm was not advertised by the provider");let s=await Xc(await r(t.jwks_uri,{headers:{accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(1e4)}),"OIDC signing-key request");if(!Array.isArray(s.keys))throw Error("OIDC signing-key response is invalid");let c=s.keys.find((m)=>{if(!m||typeof m!=="object"||Array.isArray(m))return!1;let h=m;return h.kid===o&&(!h.alg||h.alg===i)&&(!h.use||h.use==="sig")});if(!c)throw Error("OIDC ID-token signing key was not found");let d=Ik({key:c,format:"jwk"}),a=Ek("SHA256").update(n.signingInput).end();if(!(i==="PS256"?a.verify({key:d,padding:sg.RSA_PKCS1_PSS_PADDING,saltLength:32},n.signature):i==="ES256"?a.verify({key:d,dsaEncoding:"ieee-p1363"},n.signature):a.verify(d,n.signature)))throw Error("OIDC ID-token signature is invalid");return n.claims}function _k(e,t,r,n){if(e.iss!==t.issuer)throw Error("OIDC ID-token issuer is invalid");let i=typeof e.aud==="string"?[e.aud]:Array.isArray(e.aud)?e.aud.filter((d)=>typeof d==="string"):[];if(!i.includes(t.clientId))throw Error("OIDC ID-token audience is invalid");if((i.length>1||e.azp!==void 0)&&e.azp!==t.clientId)throw Error("OIDC ID-token authorized party is invalid");let o=Math.floor(n.getTime()/1000);if(typeof e.exp!=="number"||e.exp<o-ag)throw Error("OIDC ID token is expired");if(typeof e.iat!=="number"||e.iat>o+ag)throw Error("OIDC ID-token issued-at time is invalid");if(typeof e.nonce!=="string"||!Ak(e.nonce,r))throw Error("OIDC ID-token nonce is invalid");if(typeof e.sub!=="string"||!e.sub||e.sub.length>512)throw Error("OIDC ID-token subject is invalid");if(e.email_verified!==!0||typeof e.email!=="string")throw Error("OIDC provider did not return a verified email address");let s=e.email.trim().toLowerCase();if(s.length>254||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s))throw Error("OIDC provider returned an invalid email address");let c=s.split("@")[1];if(!c||!t.allowedDomains.includes(c))throw Error("OIDC email domain is not allowed for this organization");return{provider:t,subject:e.sub,email:s,name:typeof e.name==="string"?e.name.slice(0,120):void 0,claims:e}}async function rd(e,t,r=fetch){let n=e.getOidcProviderBySlug(t.providerSlug);if(!n?.enabled)throw Error("OIDC provider is unavailable");if(!t.state||t.state.length>512||!t.code||t.code.length>4096)throw Error("OIDC callback is incomplete");let i=Is(t.origin,"Application origin").origin,o=e.consumeOidcTransaction(n.id,t.state),s=`${i}/auth/oidc/${encodeURIComponent(n.slug)}/callback`;if(o.transaction.redirectUri!==s)throw Error("OIDC callback redirect URI does not match the original request");let{clientSecret:c}=e.getOidcProviderCredentials(n.id),d=await ed(n,r),a=new URLSearchParams({grant_type:"authorization_code",code:t.code,redirect_uri:o.transaction.redirectUri,code_verifier:o.verifier}),u={accept:"application/json","content-type":"application/x-www-form-urlencoded"},m=d.token_endpoint_auth_methods_supported??["client_secret_basic"];if(m.includes("client_secret_basic")){let w=(C)=>new URLSearchParams({value:C}).toString().slice(6),k=`${w(n.clientId)}:${w(c)}`;u.authorization=`Basic ${Buffer.from(k).toString("base64")}`}else if(m.includes("client_secret_post"))a.set("client_id",n.clientId),a.set("client_secret",c);else throw Error("OIDC provider does not support a configured client authentication method");let h=await Xc(await r(d.token_endpoint,{method:"POST",headers:u,body:a,redirect:"error",signal:AbortSignal.timeout(1e4)}),"OIDC token exchange");if(typeof h.id_token!=="string")throw Error("OIDC token response did not include an ID token");let y=await Pk(h.id_token,d,r);return{identity:_k(y,n,o.nonce,t.now??new Date),returnPath:o.transaction.returnPath}}import{createHash as Tk,randomBytes as xk}from"node:crypto";var ug=new Set(Es),pg=7776000000,mg=31536000000,gg=86400000;function Cr(e){return typeof e==="string"?e:void 0}function lg(e){return Tk("sha256").update(e).digest("hex")}function Dk(e){try{let t=JSON.parse(String(e));return Array.isArray(t)?t.filter((r)=>typeof r==="string"&&ug.has(r)):[]}catch{return[]}}function Ok(e){let t=String(e.scope_type);return t==="organization"?{type:t}:{type:t,id:String(e.scope_id)}}function nd(e){let t=Cr(e.disabled_at);return{id:String(e.id),organizationId:String(e.organization_id),actorId:String(e.actor_id),slug:String(e.slug),name:String(e.name),description:Cr(e.description),createdByActorId:Cr(e.created_by_actor_id),disabledAt:t,createdAt:String(e.created_at),updatedAt:String(e.updated_at),state:t?"disabled":"active"}}function id(e,t){let r=Cr(e.revoked_at),n=String(e.expires_at);return{id:String(e.id),serviceAccountId:String(e.service_account_id),name:String(e.name),prefix:String(e.token_prefix),capabilities:Dk(e.capabilities),scope:Ok(e),expiresAt:n,lastUsedAt:Cr(e.last_used_at),lastNetworkHint:Cr(e.last_network_hint),revokedAt:r,rotatedFromTokenId:Cr(e.rotated_from_token_id),createdByActorId:Cr(e.created_by_actor_id),createdAt:String(e.created_at),updatedAt:String(e.updated_at),state:r?"revoked":n<=t?"expired":"active"}}function $k(e){let t={};try{t=JSON.parse(String(e.response_body))}catch{}return{id:String(e.id),tokenId:String(e.token_id),key:String(e.idempotency_key),requestHash:String(e.request_hash),operationId:Cr(e.operation_id),responseStatus:Number(e.response_status),responseBody:t,expiresAt:String(e.expires_at),createdAt:String(e.created_at)}}class Rs{controlPlane;nowFn;idFn;constructor(e,t={}){this.controlPlane=e;this.nowFn=t.now??(()=>new Date),this.idFn=t.id??(()=>crypto.randomUUID())}now(){return this.nowFn().toISOString()}run(e,t){this.controlPlane.database.run(e,t)}createServiceAccount(e){if(!this.controlPlane.getOrganization(e.organizationId))throw Error("Service-account organization was not found");let t=e.slug.trim().toLowerCase();if(!/^[a-z0-9][a-z0-9-]{1,47}$/.test(t))throw Error("Service-account slug must be 2-48 lowercase letters, numbers or dashes");let r=e.name.trim().slice(0,100);if(!r)throw Error("Service-account name is required");let n=this.controlPlane.createActor({kind:"service_account",externalId:`service-account:${e.organizationId}:${t}`,displayName:r,metadata:{source:"api",serviceAccountSlug:t}}),i=this.idFn(),o=this.now();this.run(`INSERT INTO service_accounts (id, organization_id, actor_id, slug, name, description, created_by_actor_id, created_at, updated_at)
|
|
50
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i,e.organizationId,n.id,t,r,e.description?.trim().slice(0,500)||null,e.createdByActorId??null,o,o]);let s=this.controlPlane.createMembership({organizationId:e.organizationId,actorId:n.id,roleTemplate:e.roleTemplate,scope:e.scope,source:"manual",performedByActorId:e.createdByActorId}),c=e.scope??{type:"organization"};return this.controlPlane.appendEvent({organizationId:e.organizationId,actorId:e.createdByActorId,type:"api.service_account.created",payload:{serviceAccountId:i,roleTemplate:e.roleTemplate,scope:{type:c.type,id:c.id??null}}}),{serviceAccount:this.getServiceAccount(i),membership:s}}getServiceAccount(e){let t=this.controlPlane.database.query("SELECT * FROM service_accounts WHERE id = ?").get(e);return t?nd(t):void 0}getServiceAccountBySlug(e,t){let r=this.controlPlane.database.query("SELECT * FROM service_accounts WHERE organization_id = ? AND slug = ? COLLATE NOCASE").get(e,t.trim());return r?nd(r):void 0}listServiceAccounts(e,t={}){return this.controlPlane.database.query("SELECT * FROM service_accounts WHERE organization_id = ? ORDER BY name COLLATE NOCASE").all(e).map(nd).filter((r)=>t.includeDisabled||r.state==="active")}disableServiceAccount(e,t){let r=this.getServiceAccount(e);if(!r)throw Error("Service account was not found");let n=this.now();return this.controlPlane.transaction(()=>{this.run("UPDATE service_accounts SET disabled_at = ?, updated_at = ? WHERE id = ?",[n,n,e]),this.run("UPDATE api_tokens SET revoked_at = ?, updated_at = ? WHERE service_account_id = ? AND revoked_at IS NULL",[n,n,e]);let i=this.controlPlane.getMembershipForActor(r.organizationId,r.actorId);if(i?.status==="active")this.controlPlane.revokeMembership(i.id)}),this.controlPlane.appendEvent({organizationId:r.organizationId,actorId:t,type:"api.service_account.disabled",payload:{serviceAccountId:e}}),this.getServiceAccount(e)}createToken(e){let t=this.getServiceAccount(e.serviceAccountId);if(!t||t.state!=="active")throw Error("Service account is unavailable");let r=this.controlPlane.getMembershipForActor(t.organizationId,t.actorId);if(!r||r.status!=="active")throw Error("Service-account membership is unavailable");let n=[...new Set(e.capabilities)];if(n.length===0||n.some((h)=>!ug.has(h)))throw Error("API token requires valid explicit capabilities");let i=e.scope??r.scope,o=this.controlPlane.resolveAuthorizationTarget(t.organizationId,i);if(!o)throw Error("API token scope was not found in this organization");for(let h of n)if(!Xt({membership:r,grants:this.controlPlane.listGrants(r.id),capability:h,target:o}).allowed)throw Error(`Service-account membership does not grant ${h} at the token scope`);let s=e.expiresAt?new Date(e.expiresAt):new Date(this.nowFn().getTime()+pg);if(!Number.isFinite(s.getTime())||s.getTime()<=this.nowFn().getTime()+60000||s.getTime()>this.nowFn().getTime()+mg)throw Error("API token expiry must be between one minute and one year from now");let c=this.idFn(),d=xk(32).toString("base64url"),a=`tsc_v1.${c}.${d}`,u=`tsc_v1.${c.slice(0,8)}`,m=this.now();return this.run(`INSERT INTO api_tokens (id, service_account_id, name, token_hash, token_prefix, capabilities, scope_type, scope_id,
|
|
51
|
+
expires_at, rotated_from_token_id, created_by_actor_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[c,t.id,e.name.trim().slice(0,100)||"API token",lg(a),u,JSON.stringify(n.sort()),i.type,i.type==="organization"?null:i.id??null,s.toISOString(),e.rotatedFromTokenId??null,e.createdByActorId??null,m,m]),this.controlPlane.appendEvent({organizationId:t.organizationId,actorId:e.createdByActorId,type:"api.token.created",payload:{serviceAccountId:t.id,tokenId:c,prefix:u,capabilities:n,scope:{type:i.type,id:i.id??null},expiresAt:s.toISOString(),rotatedFromTokenId:e.rotatedFromTokenId??null}}),{token:this.getToken(c),secret:a}}getToken(e){let t=this.controlPlane.database.query("SELECT * FROM api_tokens WHERE id = ?").get(e);return t?id(t,this.now()):void 0}listTokens(e,t={}){return this.controlPlane.database.query("SELECT * FROM api_tokens WHERE service_account_id = ? ORDER BY created_at DESC").all(e).map((r)=>id(r,this.now())).filter((r)=>t.includeInactive||r.state==="active")}verifyToken(e,t){let r=/^tsc_v1\.([^.]+)\.[A-Za-z0-9_-]{40,}$/.exec(e);if(!r)return;let n=this.controlPlane.database.query("SELECT * FROM api_tokens WHERE id = ? AND token_hash = ?").get(r[1],lg(e));if(!n)return;let i=id(n,this.now()),o=this.getServiceAccount(i.serviceAccountId);if(!o||o.state!=="active"||i.state!=="active")return;let s=this.controlPlane.getActor(o.actorId),c=this.controlPlane.getMembershipForActor(o.organizationId,o.actorId);if(!s||s.disabledAt||!c||c.status!=="active")return;let d=this.now(),a=!i.lastUsedAt||this.nowFn().getTime()-new Date(i.lastUsedAt).getTime()>=3600000;if(this.run("UPDATE api_tokens SET last_used_at = ?, last_network_hint = ?, updated_at = ? WHERE id = ?",[d,t?.slice(0,128)??null,d,i.id]),a)this.controlPlane.appendEvent({organizationId:o.organizationId,actorId:s.id,type:"api.token.used",payload:{serviceAccountId:o.id,tokenId:i.id,prefix:i.prefix}});return{serviceAccount:o,token:this.getToken(i.id),actor:s,membership:c}}rotateToken(e,t){let r=this.getToken(e);if(!r||r.state!=="active")throw Error("Active API token was not found");let n=this.createToken({serviceAccountId:r.serviceAccountId,name:`${r.name} (rotated)`,capabilities:r.capabilities,scope:r.scope,expiresAt:r.expiresAt,createdByActorId:t,rotatedFromTokenId:r.id}),i=this.getServiceAccount(r.serviceAccountId);return this.controlPlane.appendEvent({organizationId:i?.organizationId,actorId:t,type:"api.token.rotated",payload:{serviceAccountId:r.serviceAccountId,previousTokenId:r.id,tokenId:n.token.id}}),n}revokeToken(e,t){let r=this.getToken(e);if(!r)throw Error("API token was not found");if(r.state==="active"){let n=this.now();this.run("UPDATE api_tokens SET revoked_at = ?, updated_at = ? WHERE id = ?",[n,n,e]);let i=this.getServiceAccount(r.serviceAccountId);this.controlPlane.appendEvent({organizationId:i?.organizationId,actorId:t,type:"api.token.revoked",payload:{serviceAccountId:r.serviceAccountId,tokenId:e}})}return this.getToken(e)}getIdempotency(e,t){let r=this.controlPlane.database.query("SELECT * FROM api_idempotency_records WHERE token_id = ? AND idempotency_key = ? AND expires_at > ?").get(e,t,this.now());return r?$k(r):void 0}saveIdempotency(e){if(!/^[A-Za-z0-9._:-]{8,128}$/.test(e.key))throw Error("Idempotency-Key must contain 8-128 safe characters");let t=this.getIdempotency(e.tokenId,e.key);if(t){if(t.requestHash!==e.requestHash)throw Error("Idempotency-Key was already used for a different request");return t}let r=this.idFn(),n=this.now(),i=new Date(this.nowFn().getTime()+gg).toISOString();return this.run(`INSERT INTO api_idempotency_records (id, token_id, idempotency_key, request_hash, operation_id, response_status, response_body, expires_at, created_at)
|
|
52
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[r,e.tokenId,e.key,e.requestHash,e.operationId??null,e.responseStatus,JSON.stringify(e.responseBody),i,n]),this.getIdempotency(e.tokenId,e.key)}purgeExpired(){let e=this.now(),t=this.controlPlane.database.run("DELETE FROM api_tokens WHERE (expires_at < ? OR revoked_at IS NOT NULL) AND created_at < ?",[e,new Date(this.nowFn().getTime()-2592000000).toISOString()]).changes,r=this.controlPlane.database.run("DELETE FROM api_idempotency_records WHERE expires_at < ?",[e]).changes;return{tokens:t,idempotency:r}}}import{isIP as kg}from"node:net";var Nk={every_minute:"* * * * *",every_five_minutes:"*/5 * * * *",hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 0"},jk={JAN:1,FEB:2,MAR:3,APR:4,MAY:5,JUN:6,JUL:7,AUG:8,SEP:9,OCT:10,NOV:11,DEC:12},fg={SUN:0,MON:1,TUE:2,WED:3,THU:4,FRI:5,SAT:6};function hg(e){try{return new Intl.DateTimeFormat("en",{timeZone:e}).format(new Date),e}catch{throw Error(`Unknown schedule timezone: ${e}`)}}function As(e,t,r,n){let i=t[e.toUpperCase()]??Number(e);if(!Number.isInteger(i)||i<r||i>n)throw Error(`Schedule field value ${e} is outside ${r}-${n}.`);return i}function Si(e,t,r,n={},i){if(e==="*"||e==="?")return;let o=new Set;for(let s of e.split(",")){let[c,d]=s.split("/"),a=d?As(d,{},1,r-t+1):1,u,m;if(c==="*")u=t,m=r;else if(c.includes("-")){let h=c.split("-");u=As(h[0],n,t,r),m=As(h[1],n,t,r)}else u=As(c,n,t,r),m=u;if(m<u)throw Error("Schedule ranges must be ascending.");for(let h=u;h<=m;h+=a)o.add(i?i(h):h===7&&r===7?0:h)}return o}function Mk(e,t){let r=Object.fromEntries(new Intl.DateTimeFormat("en-US",{timeZone:t,year:"numeric",month:"numeric",day:"numeric",weekday:"short",hour:"numeric",minute:"numeric",hourCycle:"h23"}).formatToParts(e).map((n)=>[n.type,n.value]));return{minute:Number(r.minute),hour:Number(r.hour),day:Number(r.day),month:Number(r.month),weekday:fg[r.weekday.toUpperCase()],year:Number(r.year),key:`${r.year}-${r.month}-${r.day} ${r.hour}:${r.minute}`}}function yg(e){let r=(e.startsWith("cron(")?e.slice(5,-1).trim():e.trim()).split(/\s+/);if(r.length!==5&&r.length!==6)throw Error("Cron schedules require five standard fields or six EventBridge fields.");let[n,i,o,s,c,d]=r,a=r.length===6;return{minute:Si(n,0,59),hour:Si(i,0,23),day:Si(o,1,31),month:Si(s,1,12,jk),weekday:Si(c,a?1:0,7,fg,a?(u)=>u===7?6:u-1:void 0),year:d?Si(d,1970,2199):void 0,dayWildcard:o==="*"||o==="?",weekdayWildcard:c==="*"||c==="?"}}function Bk(e,t){if(!((!t.minute||t.minute.has(e.minute))&&(!t.hour||t.hour.has(e.hour))&&(!t.month||t.month.has(e.month))&&(!t.year||t.year.has(e.year))))return!1;let n=!t.day||t.day.has(e.day),i=!t.weekday||t.weekday.has(e.weekday);return t.dayWildcard?i:t.weekdayWildcard?n:n||i}function vg(e){let t=/^rate\(\s*(\d+)\s+(minute|minutes|hour|hours|day|days)\s*\)$/i.exec(e);if(!t)return;let r=Number(t[1]);if(r<1)throw Error("Rate amount must be positive.");return r*(t[2].toLowerCase().startsWith("minute")?60000:t[2].toLowerCase().startsWith("hour")?3600000:86400000)}function sn(e){let t=e.trim(),r=Nk[t.toLowerCase()]??t;if(!r)throw Error("Schedule expression is required.");let n=vg(r);if(n){let i=n/60000;return{original:t,normalized:`rate(${i} minutes)`,kind:"rate",description:i%1440===0?`Every ${i/1440} day(s)`:i%60===0?`Every ${i/60} hour(s)`:`Every ${i} minute(s)`}}return yg(r),{original:t,normalized:r.startsWith("cron(")?r:`cron(${r})`,kind:"cron",description:`Cron ${r.replace(/^cron\(|\)$/g,"")}`}}function Mn(e,t,r=new Date,n=5){let i=sn(e),o=hg(t),s=Math.min(20,Math.max(1,n)),c=vg(i.normalized);if(c)return Array.from({length:s},(y,w)=>new Date(r.getTime()+c*(w+1)).toISOString());let d=yg(i.normalized),a=[],u=new Set,m=new Date(Math.floor(r.getTime()/60000)*60000+60000),h=0;while(a.length<s&&h<1100000){let y=Mk(m,o);if(Bk(y,d)&&!u.has(y.key))a.push(m.toISOString()),u.add(y.key);m=new Date(m.getTime()+60000),h++}if(a.length<s)throw Error("Schedule produced no runs within the bounded preview horizon.");return a}function Bn(e,t="UTC",r=new Date,n=5){let i=sn(e),o=Mn(i.normalized,t,r,n),s=i.kind==="cron"?["Server cron and EventBridge use the same wall-clock preview; provider-specific extensions are retained only when supported."]:["Rate schedules use elapsed-time intervals and are not shifted by DST."];return{...i,timezone:hg(t),nextRuns:o,capabilities:{server:i.kind==="cron",eventbridge:!0,notes:s}}}function yo(e){let t=sn(e.expression),r=t.normalized.slice(5,-1).trim().split(/\s+/),n=t.kind==="cron"&&r.length===5;if(e.provider==="server")return{provider:"server",supported:n,features:{timezone:!0,flexibleWindow:!1,catchUp:!1,replaceOverlap:!1},notes:[t.kind==="rate"?"Server cron requires a cron expression; use an equivalent cron schedule.":r.length!==5?"EventBridge six-field cron extensions cannot be installed as server cron.":"Cron is reconciled through a root-owned ts-cloud entry.",e.missedRunPolicy==="catch_up"?"Catch-up is handled by the control plane, not cron.":"Missed runs are skipped by cron."]};if(e.provider==="eventbridge")return{provider:"eventbridge",supported:!0,features:{timezone:!0,flexibleWindow:!0,catchUp:!1,replaceOverlap:!1},notes:["Five-field cron is translated explicitly to EventBridge six-field syntax. Flexible windows are provider-native; overlap and catch-up remain control-plane policies."]};if(e.provider==="lambda")return{provider:"lambda",supported:!0,features:{timezone:!0,flexibleWindow:!0,catchUp:!1,replaceOverlap:!1},notes:["The schedule invokes one immutable Lambda target."]};return{provider:"platform",supported:!0,features:{timezone:!0,flexibleWindow:!0,catchUp:!0,replaceOverlap:!0},notes:["The durable control-plane worker enforces all configured policies."]}}function Cs(e){let t=yo({...e,provider:"server"});if(!t.supported)throw Error(t.notes.join(" "));let n=sn(e.expression).normalized.slice(5,-1);return{path:`/etc/cron.d/ts-cloud-${e.id}`,content:`CRON_TZ=${e.timezone}
|
|
53
|
+
${n} root /usr/local/bin/cloud jobs:dispatch ${e.id} --scheduled >/dev/null 2>&1
|
|
54
|
+
`}}function Lk(e){let t=sn(e);if(t.kind==="rate")return e;let r=t.normalized.slice(5,-1).trim().split(/\s+/);if(r.length===6)return t.normalized;let[n,i,o,s,c]=r,d=c==="*"?"?":c.replace(/(^|[,-])0(?=$|[,-])/g,(a,u)=>`${u}1`);return o==="*"&&c!=="*"?`cron(${n} ${i} ? ${s} ${d} *)`:`cron(${n} ${i} ${o} ${s} ? *)`}function bg(e){let t=yo(e);if(!t.supported)throw Error(t.notes.join(" "));return{Name:`ts-cloud-${e.id}`,ScheduleExpression:Lk(e.expression),ScheduleExpressionTimezone:e.timezone,State:e.enabled?"ENABLED":"DISABLED",FlexibleTimeWindow:e.flexibleMinutes?{Mode:"FLEXIBLE",MaximumWindowInMinutes:e.flexibleMinutes}:{Mode:"OFF"},Target:{kind:e.target.kind,functionName:e.target.functionName??null,payloadRefs:e.payloadRefs},RetryPolicy:{MaximumRetryAttempts:e.retryPolicy.maxAttempts,MaximumEventAgeInSeconds:e.timeoutSeconds},DeadLetterRef:e.retryPolicy.deadLetterRef??null}}function gD(e,t){if(!t)return{status:"unavailable",observedState:{message:"Provider observation is unavailable."}};let r=String(t.expression??""),n=t.enabled;return{status:r&&r!==e.normalizedExpression||typeof n==="boolean"&&n!==e.enabled?"drifted":"in_sync",observedState:t}}function Fk(e){if(e.provider==="server"){let t=Cs(e);return{path:t.path,content:t.content,enabled:e.enabled}}if(e.provider==="eventbridge")return bg(e);throw Error(`No reconciliation adapter is configured for ${e.provider} schedules.`)}function od(e,t){if(Array.isArray(e))return Array.isArray(t)&&e.length===t.length&&e.every((r,n)=>od(r,t[n]));if(e&&typeof e==="object"){if(!t||typeof t!=="object"||Array.isArray(t))return!1;return Object.entries(e).every(([r,n])=>od(n,t[r]))}return e===t}class zk{transport;provider="server";constructor(e){this.transport=e}async observe(e){let t=Cs(e),r=await this.transport.read(t.path);return r==null?void 0:{path:t.path,content:r,enabled:!0}}async apply(e,t){let r=String(t.path??"");if(!e.enabled){await this.transport.removeRootOwned(r);return}await this.transport.writeRootOwned(r,String(t.content??""))}async remove(e){await this.transport.removeRootOwned(Cs(e).path)}matches(e,t){if(e.enabled===!1)return!1;return e.path===t.path&&e.content===t.content}}class Uk{transport;provider="eventbridge";constructor(e){this.transport=e}observe(e){return this.transport.get(`ts-cloud-${e.id}`)}apply(e,t){return this.transport.put(t)}remove(e){return this.transport.remove(`ts-cloud-${e.id}`)}matches(e,t){return od(e,t)}}class qk{store;constructor(e){this.store=e}async reconcile(e,t,r={}){if(t.provider!==e.provider)return this.store.reconcile(e.id,"unsupported",{provider:t.provider,message:`Adapter ${t.provider} cannot reconcile ${e.provider}.`});try{let n=Fk(e),i=await t.observe(e);if(i&&t.matches(n,i))return this.store.reconcile(e.id,"in_sync",{provider:t.provider,observed:i});if(r.apply===!1)return this.store.reconcile(e.id,i?"drifted":"unavailable",{provider:t.provider,observed:i??null,applyRequired:!0});if(await t.apply(e,n),!e.enabled)return this.store.reconcile(e.id,"in_sync",{provider:t.provider,observed:null,disabled:!0});let o=await t.observe(e);return this.store.reconcile(e.id,o&&t.matches(n,o)?"in_sync":"drifted",{provider:t.provider,observed:o??null,applied:!0})}catch(n){return this.store.reconcile(e.id,"unavailable",{provider:t.provider,error:n instanceof Error?n.message:String(n)})}}async remove(e,t){if(e.origin==="config")throw Error("Config-defined jobs must be removed from configuration, not destructively deleted.");if(t.provider!==e.provider)throw Error(`Adapter ${t.provider} cannot remove ${e.provider}.`);await t.remove(e),this.store.remove(e.id)}}function Vk(e){if(e.queues===!0)return[{queue:"default",processes:e.queueConcurrency??1}];if(!Array.isArray(e.queues))return[];return e.queues.map((t)=>{if(typeof t==="string")return{queue:t,processes:e.queueConcurrency??1};let[r,n]=Object.entries(t)[0]??["default",e.queueConcurrency??1];return{queue:r,processes:n}})}function sd(e,t,r){let n=new Set,i=new Set,o=new Map(r.resources.map((m)=>[m.slug,m])),s=0,c=0;for(let[m,h]of Object.entries(t.sites??{})){let y=o.get(m);if(h.scheduler){let C=`config:site:${m}:scheduler`;n.add(C),e.upsertConfigJob({organizationId:r.organization.id,projectId:r.project.id,environmentId:r.environment.id,resourceId:y?.id,name:`${m} scheduler`,provider:"server",expression:"* * * * *",timezone:"UTC",flexibleMinutes:0,target:{kind:"dashboard_operation",operationId:`scheduler:run:${m}`},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"}),s++}let w=h,k=Array.isArray(w.queues??w.workers)?w.queues??w.workers:[];for(let[C,T]of k.entries()){let j=typeof T==="string"?{queue:T}:T,P=String(j.queue??j.name??"default"),O=`config:site:${m}:worker:${C}:${P}`;i.add(O),e.upsertWorker({organizationId:r.organization.id,projectId:r.project.id,environmentId:r.environment.id,resourceId:y?.id,name:`${m}:${P}`,provider:"systemd",queue:P,processes:Number(j.processes)||1,timeoutSeconds:Number(j.timeout)||60,restartPolicy:"always",target:{operationId:`worker:restart:${m}`,site:m},enabled:!0,origin:"config",sourceKey:O,observedState:{source:"cloud.config.ts",currentJob:null,failures:0},reconciliationStatus:"pending"}),c++}}let d=t.infrastructure?.compute?.backups;if(d?.enabled)n.add("config:platform:backup"),e.upsertConfigJob({organizationId:r.organization.id,projectId:r.project.id,environmentId:r.environment.id,name:"Scheduled backup",provider:"server",expression:String(d.schedule??"0 2 * * *"),timezone:String(d.timezone??"UTC"),flexibleMinutes:0,target:{kind:"dashboard_operation",operationId:"backup:run"},payloadRefs:{},missedRunPolicy:"skip",overlapPolicy:"forbid",retryPolicy:{maxAttempts:3,backoffSeconds:60},timeoutSeconds:3600,enabled:!0,origin:"config",sourceKey:"config:platform:backup",observedState:{source:"cloud.config.ts"},reconciliationStatus:"pending"}),s++;let a=t.environments?.[r.environment.slug]?.app;if(a){if(a.scheduler!=="off"){let m=`config:serverless:${r.environment.slug}:scheduler`;n.add(m),e.upsertConfigJob({organizationId:r.organization.id,projectId:r.project.id,environmentId:r.environment.id,name:`${r.environment.name} serverless scheduler`,provider:"eventbridge",expression:"rate(1 minute)",timezone:"UTC",flexibleMinutes:0,target:{kind:"serverless_scheduler",action:"schedule:run"},payloadRefs:{},missedRunPolicy:a.scheduler==="sub-minute"?"catch_up":"skip",overlapPolicy:"forbid",retryPolicy:{maxAttempts:3,backoffSeconds:30},timeoutSeconds:a.cliTimeout??900,enabled:!0,origin:"config",sourceKey:m,observedState:{source:"cloud.config.ts",mode:a.scheduler??"on"},reconciliationStatus:"pending"}),s++}for(let{queue:m,processes:h}of Vk(a)){let y=`config:serverless:${r.environment.slug}:worker:${m}`;i.add(y),e.upsertWorker({organizationId:r.organization.id,projectId:r.project.id,environmentId:r.environment.id,name:`${r.environment.name}:${m}`,provider:"lambda",queue:m,processes:h,timeoutSeconds:a.queueTimeout??120,restartPolicy:"on_failure",target:{function:"queue",queue:m},enabled:!0,origin:"config",sourceKey:y,observedState:{source:"cloud.config.ts",currentJob:null,failures:0},reconciliationStatus:"pending"}),c++}}let u=0;for(let m of e.list(r.project.id,{environmentId:r.environment.id}).filter((h)=>h.origin==="config"&&h.sourceKey&&!n.has(h.sourceKey)))e.reconcile(m.id,"drifted",{...m.observedState,reason:"Definition is no longer present in configuration; retained for non-destructive review."}),u++;for(let m of e.listWorkers(r.project.id,r.environment.id).filter((h)=>h.origin==="config"&&h.sourceKey&&!i.has(h.sourceKey)))e.reconcileWorker(m.id,"drifted",{...m.observedState,reason:"Definition is no longer present in configuration; retained for non-destructive review."}),u++;return{jobs:s,workers:c,drifted:u}}class ad{store;queue;constructor(e,t={}){this.store=e;this.queue=t.queue??new $e(e.controlPlane)}enqueue(e,t){let r=new Date(t.scheduledFor??this.store.now()).toISOString(),n=`${e.id}:${t.trigger==="manual"?crypto.randomUUID():r}`,i=this.store.activeExecution(e.id);if(i&&e.overlapPolicy==="forbid")return this.store.createExecution({jobId:e.id,trigger:t.trigger,scheduledFor:r,idempotencyKey:n,status:"skipped",output:{reason:"overlap_forbidden",activeExecutionId:i.id}});if(i&&e.overlapPolicy==="replace"&&i.operationId)try{this.queue.requestCancellation(i.operationId,t.actorId)}catch{}let o=this.store.createExecution({jobId:e.id,trigger:t.trigger,scheduledFor:r,idempotencyKey:n,status:"queued",output:{semantics:"at_least_once"}});if(o.operationId)return o;let s=this.queue.enqueue({projectId:e.projectId,environmentId:e.environmentId,resourceId:e.resourceId,actorId:t.actorId,kind:"job.execute",input:{jobId:e.id,executionId:o.id},idempotencyKey:`job-execution:${o.id}`,lockKey:e.overlapPolicy==="allow"?`job-execution:${o.id}`:`job:${e.id}`,maxAttempts:e.retryPolicy.maxAttempts,timeoutSeconds:e.timeoutSeconds,retryClasses:["job_transient"],resumePolicy:"requeue"}).operation;return this.store.attachOperation(o.id,s.id)}tick(e=this.store.now()){let t=[];for(let r of this.store.due(e.toISOString())){let n=r.nextRunAt,i=Mn(r.normalizedExpression,r.timezone,e,1)[0];if(r.missedRunPolicy==="catch_up"){let o=n,s=0;while(o<=e.toISOString()&&s<10)t.push(this.enqueue(r,{trigger:o===n?"scheduled":"catch_up",scheduledFor:o})),o=Mn(r.normalizedExpression,r.timezone,new Date(o),1)[0],s++}else t.push(this.enqueue(r,{trigger:"scheduled",scheduledFor:n}));this.store.markScheduled(r.id,n,i)}return t}}function Sg(e){return{"job.execute":async(r)=>{let n=r.operation.input&&typeof r.operation.input==="object"&&!Array.isArray(r.operation.input)?r.operation.input:{},i=e.store.get(String(n.jobId??"")),o=e.store.getExecution(String(n.executionId??""));if(!i||!o)throw Error("Scheduled job execution is no longer available.");e.store.transitionExecution(o.id,"running",{attempt:r.operation.attempt}),r.checkpoint("execute",`Running ${i.name} on ${i.provider}.`),r.log(`Trigger ${o.trigger}; scheduled for ${o.scheduledFor}; semantics at-least-once.`,{stream:"system"});let s=await e.executor(i,i.target,r);if(s.stdout)r.log(s.stdout,{stream:"stdout"});if(s.stderr)r.log(s.stderr,{stream:"stderr"});if(!s.ok){if(e.store.transitionExecution(o.id,r.operation.attempt>=i.retryPolicy.maxAttempts?"dead":"failed",{attempt:r.operation.attempt,error:s.stderr??"Job execution failed."}),s.retryable)throw new Ps(s.stderr??"Scheduled job failed transiently.","job_transient");throw Error(s.stderr??"Scheduled job failed.")}return e.store.transitionExecution(o.id,"succeeded",{attempt:r.operation.attempt,output:s.output??{}}),{jobId:i.id,executionId:o.id,provider:i.provider}}}}var vt=(e)=>typeof e==="string"&&e?e:void 0,wg=(e)=>Number(e)===1,Ln=(e)=>{try{return JSON.parse(String(e))}catch{return{}}},an=(e,t,r,n)=>{let i=Number(e);return Number.isFinite(i)?Math.min(n,Math.max(r,Math.floor(i))):t};function _s(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:vt(e.environment_id),resourceId:vt(e.resource_id),name:String(e.name),provider:String(e.provider),expression:String(e.expression),normalizedExpression:String(e.normalized_expression),timezone:String(e.timezone),startsAt:vt(e.starts_at),endsAt:vt(e.ends_at),flexibleMinutes:Number(e.flexible_minutes),target:Ln(e.target),payloadRefs:Ln(e.payload_refs),missedRunPolicy:String(e.missed_run_policy),overlapPolicy:String(e.overlap_policy),retryPolicy:Ln(e.retry_policy),timeoutSeconds:Number(e.timeout_seconds),enabled:wg(e.enabled),origin:String(e.origin),sourceKey:vt(e.source_key),ownerActorId:vt(e.owner_actor_id),observedState:Ln(e.observed_state),reconciliationStatus:String(e.reconciliation_status),nextRunAt:vt(e.next_run_at),lastScheduledFor:vt(e.last_scheduled_for),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Ts(e){return{id:String(e.id),jobId:String(e.job_id),operationId:vt(e.operation_id),trigger:String(e.trigger),scheduledFor:String(e.scheduled_for),idempotencyKey:String(e.idempotency_key),status:String(e.status),attempt:Number(e.attempt),startedAt:vt(e.started_at),finishedAt:vt(e.finished_at),output:Ln(e.output),error:vt(e.error),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function cd(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:vt(e.environment_id),resourceId:vt(e.resource_id),name:String(e.name),provider:String(e.provider),queue:String(e.queue),processes:Number(e.processes),timeoutSeconds:Number(e.timeout_seconds),restartPolicy:String(e.restart_policy),target:Ln(e.target),enabled:wg(e.enabled),origin:String(e.origin),sourceKey:vt(e.source_key),ownerActorId:vt(e.owner_actor_id),observedState:Ln(e.observed_state),reconciliationStatus:String(e.reconciliation_status),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}class dd{controlPlane;options;constructor(e,t={}){this.controlPlane=e;this.options=t}now(){return this.options.now?.()??new Date}create(e){if(!e.name.trim())throw Error("Scheduled jobs require a name.");let t=Bn(e.expression,e.timezone,this.now(),1),r=crypto.randomUUID(),n=this.now().toISOString(),i=e.startsAt?new Date(e.startsAt).toISOString():void 0,o=e.endsAt?new Date(e.endsAt).toISOString():void 0;if(i&&o&&i>=o)throw Error("Schedule start must be before end.");let s=t.nextRuns.find((c)=>(!i||c>=i)&&(!o||c<=o));return this.controlPlane.database.run("INSERT INTO scheduled_jobs (id,organization_id,project_id,environment_id,resource_id,name,provider,expression,normalized_expression,timezone,starts_at,ends_at,flexible_minutes,target,payload_refs,missed_run_policy,overlap_policy,retry_policy,timeout_seconds,enabled,origin,source_key,owner_actor_id,observed_state,reconciliation_status,next_run_at,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[r,e.organizationId,e.projectId,e.environmentId??null,e.resourceId??null,e.name.trim().slice(0,120),e.provider,e.expression,t.normalized,e.timezone,i??null,o??null,an(e.flexibleMinutes,0,0,1440),JSON.stringify(e.target),JSON.stringify(e.payloadRefs),e.missedRunPolicy,e.overlapPolicy,JSON.stringify({maxAttempts:an(e.retryPolicy.maxAttempts,3,1,20),backoffSeconds:an(e.retryPolicy.backoffSeconds,30,0,86400),deadLetterRef:e.retryPolicy.deadLetterRef}),an(e.timeoutSeconds,900,1,86400),e.enabled?1:0,e.origin,e.sourceKey??null,e.ownerActorId??null,JSON.stringify(e.observedState),e.reconciliationStatus,s??null,1,n,n]),this.get(r)}get(e){let t=this.controlPlane.database.query("SELECT * FROM scheduled_jobs WHERE id=?").get(e);return t?_s(t):void 0}getBySource(e,t,r){let n=this.controlPlane.database.query("SELECT * FROM scheduled_jobs WHERE project_id=? AND environment_id IS ? AND source_key=?").get(e,t??null,r);return n?_s(n):void 0}list(e,t={}){let r=["project_id=?"],n=[e];if(t.environmentId)r.push("environment_id=?"),n.push(t.environmentId);if(t.resourceIds?.length)r.push(`resource_id IN (${t.resourceIds.map(()=>"?").join(",")})`),n.push(...t.resourceIds);if(t.enabled!=null)r.push("enabled=?"),n.push(t.enabled?1:0);return this.controlPlane.database.query(`SELECT * FROM scheduled_jobs WHERE ${r.join(" AND ")} ORDER BY next_run_at IS NULL,next_run_at,name`).all(...n).map(_s)}setEnabled(e,t){this.controlPlane.database.run("UPDATE scheduled_jobs SET enabled=?,version=version+1,updated_at=? WHERE id=?",[t?1:0,this.now().toISOString(),e]);let r=this.get(e);if(!r)throw Error("Scheduled job was not found.");return r}updateSchedule(e,t){let r=this.get(e);if(!r)throw Error("Scheduled job was not found.");let n=t.expression??r.expression,i=t.timezone??r.timezone,o=Bn(n,i,this.now(),1),s=this.now().toISOString();return this.controlPlane.database.run("UPDATE scheduled_jobs SET expression=?,normalized_expression=?,timezone=?,missed_run_policy=?,overlap_policy=?,timeout_seconds=?,next_run_at=?,reconciliation_status=?,version=version+1,updated_at=? WHERE id=?",[n,o.normalized,i,t.missedRunPolicy??r.missedRunPolicy,t.overlapPolicy??r.overlapPolicy,an(t.timeoutSeconds,r.timeoutSeconds,1,86400),o.nextRuns[0],"pending",s,e]),this.get(e)}remove(e){let t=this.get(e);if(!t)throw Error("Scheduled job was not found.");if(t.origin==="config")throw Error("Config-defined jobs must be removed from configuration, not destructively deleted.");this.controlPlane.database.run("DELETE FROM scheduled_jobs WHERE id=?",[e])}markScheduled(e,t,r){this.controlPlane.database.run("UPDATE scheduled_jobs SET last_scheduled_for=?,next_run_at=?,updated_at=? WHERE id=?",[t,r??null,this.now().toISOString(),e])}reconcile(e,t,r){return this.controlPlane.database.run("UPDATE scheduled_jobs SET reconciliation_status=?,observed_state=?,updated_at=? WHERE id=?",[t,JSON.stringify(r),this.now().toISOString(),e]),this.get(e)}upsertConfigJob(e){let t=this.getBySource(e.projectId,e.environmentId,e.sourceKey);if(!t)return this.create(e);let r=Bn(e.expression,e.timezone,this.now(),1),n=this.now().toISOString();if(t.resourceId===e.resourceId&&t.name===e.name&&t.provider===e.provider&&t.expression===e.expression&&t.normalizedExpression===r.normalized&&t.timezone===e.timezone&&JSON.stringify(t.target)===JSON.stringify(e.target)&&JSON.stringify(t.payloadRefs)===JSON.stringify(e.payloadRefs)&&t.missedRunPolicy===e.missedRunPolicy&&t.overlapPolicy===e.overlapPolicy&&JSON.stringify(t.retryPolicy)===JSON.stringify(e.retryPolicy)&&t.timeoutSeconds===e.timeoutSeconds&&t.enabled===e.enabled)return t;return this.controlPlane.database.run("UPDATE scheduled_jobs SET resource_id=?,name=?,provider=?,expression=?,normalized_expression=?,timezone=?,target=?,payload_refs=?,missed_run_policy=?,overlap_policy=?,retry_policy=?,timeout_seconds=?,enabled=?,observed_state=?,reconciliation_status=?,next_run_at=COALESCE(next_run_at,?),version=version+1,updated_at=? WHERE id=?",[e.resourceId??null,e.name,e.provider,e.expression,r.normalized,e.timezone,JSON.stringify(e.target),JSON.stringify(e.payloadRefs),e.missedRunPolicy,e.overlapPolicy,JSON.stringify(e.retryPolicy),e.timeoutSeconds,e.enabled?1:0,JSON.stringify(e.observedState),e.reconciliationStatus,r.nextRuns[0],n,t.id]),this.get(t.id)}due(e=this.now().toISOString()){return this.controlPlane.database.query("SELECT * FROM scheduled_jobs WHERE enabled=1 AND next_run_at IS NOT NULL AND next_run_at<=? AND (starts_at IS NULL OR starts_at<=?) AND (ends_at IS NULL OR ends_at>=?) ORDER BY next_run_at LIMIT 200").all(e,e,e).map(_s)}createExecution(e){let t=this.controlPlane.database.query("SELECT * FROM job_executions WHERE idempotency_key=?").get(e.idempotencyKey);if(t)return Ts(t);let r=crypto.randomUUID(),n=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO job_executions (id,job_id,operation_id,trigger,scheduled_for,idempotency_key,status,attempt,output,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?)",[r,e.jobId,e.operationId??null,e.trigger,e.scheduledFor,e.idempotencyKey,e.status,0,JSON.stringify(e.output),n,n]),this.getExecution(r)}getExecution(e){let t=this.controlPlane.database.query("SELECT * FROM job_executions WHERE id=?").get(e);return t?Ts(t):void 0}listExecutions(e,t=100){return this.controlPlane.database.query("SELECT * FROM job_executions WHERE job_id=? ORDER BY scheduled_for DESC,created_at DESC LIMIT ?").all(e,Math.min(1000,Math.max(1,t))).map(Ts)}activeExecution(e){let t=this.controlPlane.database.query("SELECT * FROM job_executions WHERE job_id=? AND status IN ('queued','running') ORDER BY created_at DESC LIMIT 1").get(e);return t?Ts(t):void 0}attachOperation(e,t){return this.controlPlane.database.run("UPDATE job_executions SET operation_id=?,updated_at=? WHERE id=?",[t,this.now().toISOString(),e]),this.getExecution(e)}transitionExecution(e,t,r={}){let n=this.now().toISOString(),i=t==="running"?n:null,o=["succeeded","failed","skipped","dead"].includes(t)?n:null;return this.controlPlane.database.run("UPDATE job_executions SET status=?,attempt=COALESCE(?,attempt),started_at=COALESCE(started_at,?),finished_at=?,output=COALESCE(?,output),error=?,updated_at=? WHERE id=?",[t,r.attempt??null,i,o,r.output?JSON.stringify(r.output):null,r.error?.slice(0,2000)??null,n,e]),this.getExecution(e)}upsertWorker(e){let t=e.sourceKey?this.controlPlane.database.query("SELECT * FROM worker_definitions WHERE project_id=? AND source_key=? AND environment_id IS ?").get(e.projectId,e.sourceKey,e.environmentId??null):void 0,r=t?cd(t):void 0,n=r?.id??crypto.randomUUID(),i=this.now().toISOString(),o=an(e.processes,1,0,1000),s=an(e.timeoutSeconds,60,1,86400);if(r&&r.resourceId===e.resourceId&&r.name===e.name.slice(0,120)&&r.provider===e.provider&&r.queue===e.queue.slice(0,200)&&r.processes===o&&r.timeoutSeconds===s&&r.restartPolicy===e.restartPolicy&&JSON.stringify(r.target)===JSON.stringify(e.target)&&r.enabled===e.enabled)return r;return this.controlPlane.database.run("INSERT INTO worker_definitions (id,organization_id,project_id,environment_id,resource_id,name,provider,queue,processes,timeout_seconds,restart_policy,target,enabled,origin,source_key,owner_actor_id,observed_state,reconciliation_status,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET name=excluded.name,resource_id=excluded.resource_id,provider=excluded.provider,queue=excluded.queue,processes=excluded.processes,timeout_seconds=excluded.timeout_seconds,restart_policy=excluded.restart_policy,target=excluded.target,enabled=excluded.enabled,observed_state=excluded.observed_state,reconciliation_status=excluded.reconciliation_status,version=worker_definitions.version+1,updated_at=excluded.updated_at",[n,e.organizationId,e.projectId,e.environmentId??null,e.resourceId??null,e.name.slice(0,120),e.provider,e.queue.slice(0,200),o,s,e.restartPolicy,JSON.stringify(e.target),e.enabled?1:0,e.origin,e.sourceKey??null,e.ownerActorId??null,JSON.stringify(e.observedState),e.reconciliationStatus,1,r?.createdAt??i,i]),this.getWorker(n)}getWorker(e){let t=this.controlPlane.database.query("SELECT * FROM worker_definitions WHERE id=?").get(e);return t?cd(t):void 0}listWorkers(e,t){return this.controlPlane.database.query(`SELECT * FROM worker_definitions WHERE project_id=?${t?" AND environment_id=?":""} ORDER BY name`).all(e,...t?[t]:[]).map(cd)}setWorkerProcesses(e,t){this.controlPlane.database.run("UPDATE worker_definitions SET processes=?,reconciliation_status='pending',version=version+1,updated_at=? WHERE id=?",[an(t,1,0,1000),this.now().toISOString(),e]);let r=this.getWorker(e);if(!r)throw Error("Worker was not found.");return r}reconcileWorker(e,t,r){this.controlPlane.database.run("UPDATE worker_definitions SET reconciliation_status=?,observed_state=?,updated_at=? WHERE id=?",[t,JSON.stringify(r),this.now().toISOString(),e]);let n=this.getWorker(e);if(!n)throw Error("Worker was not found.");return n}}var Se=(e)=>e==null?void 0:String(e),xs=(e)=>Number(e)===1,cn=(e,t)=>{try{return JSON.parse(String(e))}catch{return t}};function Ig(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),name:String(e.name),provider:String(e.provider),endpoint:Se(e.endpoint),endpointPolicy:String(e.endpoint_policy),bucket:Se(e.bucket),prefix:String(e.prefix),region:Se(e.region),forcePathStyle:xs(e.force_path_style),credentialRef:Se(e.credential_ref),encryption:String(e.encryption),encryptionKeyRef:Se(e.encryption_key_ref),immutability:cn(e.immutability,{}),status:String(e.status),lastTestedAt:Se(e.last_tested_at),lastSuccessAt:Se(e.last_success_at),lastFailureAt:Se(e.last_failure_at),lastError:Se(e.last_error),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function ld(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:Se(e.environment_id),resourceId:Se(e.resource_id),dataServiceId:Se(e.data_service_id),destinationId:String(e.destination_id),name:String(e.name),resourceKind:String(e.resource_kind),schedule:String(e.schedule),timezone:String(e.timezone),retention:cn(e.retention,{}),compression:String(e.compression),encryption:String(e.encryption),includePatterns:cn(e.include_patterns,[]),excludePatterns:cn(e.exclude_patterns,[]),expectedRpoMinutes:Number(e.expected_rpo_minutes),expectedRtoMinutes:Number(e.expected_rto_minutes),healthCheckId:Se(e.health_check_id),enabled:xs(e.enabled),nextRunAt:Se(e.next_run_at),lastRunAt:Se(e.last_run_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function ud(e){return{id:String(e.id),projectId:String(e.project_id),policyId:Se(e.policy_id),destinationId:String(e.destination_id),resourceId:Se(e.resource_id),dataServiceId:Se(e.data_service_id),backupJobId:Se(e.backup_job_id),kind:String(e.kind),pointInTime:String(e.point_in_time),uri:String(e.uri),sizeBytes:Number(e.size_bytes),checksum:String(e.checksum),manifest:cn(e.manifest,{}),toolVersion:Se(e.tool_version),engineVersion:Se(e.engine_version),expiresAt:Se(e.expires_at),lockedUntil:Se(e.locked_until),held:xs(e.held),pinned:xs(e.pinned),status:String(e.status),verificationState:String(e.verification_state),verifiedAt:Se(e.verified_at),durationMs:e.duration_ms==null?void 0:Number(e.duration_ms),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function pd(e){return{id:String(e.id),projectId:String(e.project_id),policyId:Se(e.policy_id),recoveryPointId:Se(e.recovery_point_id),operationId:Se(e.operation_id),kind:String(e.kind),status:String(e.status),idempotencyKey:String(e.idempotency_key),target:cn(e.target,{}),restoreMode:Se(e.restore_mode),cancellability:String(e.cancellability),safetyBackupId:Se(e.safety_backup_id),healthResult:e.health_result?cn(e.health_result,{}):void 0,progress:cn(e.progress,{}),error:Se(e.error),startedAt:Se(e.started_at),finishedAt:Se(e.finished_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Wk(e){let t=e.toLowerCase();if(t==="localhost"||t.endsWith(".localhost")||t.endsWith(".local")||t.endsWith(".internal"))return!0;if(kg(t)===6)return t==="::1"||t.startsWith("fe80:");if(kg(t)!==4)return!1;let[r,n]=t.split(".").map(Number);return r===10||r===127||r===0||r===169&&n===254||r===172&&n>=16&&n<=31||r===192&&n===168}function Hk(e){if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(e.name))throw Error("Backup destination names must be 2-63 lowercase letters, numbers, or dashes.");if(e.provider!=="aws_backup"&&!e.bucket)throw Error("S3 backup destinations require a bucket.");if(e.provider==="s3_compatible"&&!e.endpoint)throw Error("S3-compatible destinations require an explicit endpoint.");if(e.provider==="s3_compatible"&&!e.credentialRef)throw Error("S3-compatible destinations require a credential reference.");if(e.encryption!=="provider"&&!e.encryptionKeyRef)throw Error("Client-side encryption requires an encryption key reference.");if(e.endpoint){let t=new URL(e.endpoint);if(t.protocol!=="https:"||t.username||t.password||t.search||t.hash||t.pathname!=="/")throw Error("Backup endpoints must be origin-only HTTPS URLs without credentials, paths, queries, or fragments.");if(Wk(t.hostname)&&e.endpointPolicy!=="allow_private")throw Error("Private backup endpoints require endpointPolicy allow_private.")}}class md{controlPlane;now;constructor(e,t=()=>new Date){this.controlPlane=e;this.now=t}createDestination(e){Hk(e);let t=crypto.randomUUID(),r=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO backup_destinations (id,organization_id,project_id,name,provider,endpoint,endpoint_policy,bucket,prefix,region,force_path_style,credential_ref,encryption,encryption_key_ref,immutability,status,last_tested_at,last_success_at,last_failure_at,last_error,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.organizationId,e.projectId,e.name,e.provider,e.endpoint??null,e.endpointPolicy,e.bucket??null,e.prefix,e.region??null,e.forcePathStyle?1:0,e.credentialRef??null,e.encryption,e.encryptionKeyRef??null,JSON.stringify(e.immutability),e.status,e.lastTestedAt??null,e.lastSuccessAt??null,e.lastFailureAt??null,e.lastError??null,1,r,r]),this.getDestination(t)}getDestination(e){let t=this.controlPlane.database.query("SELECT * FROM backup_destinations WHERE id=?").get(e);return t?Ig(t):void 0}listDestinations(e){return this.controlPlane.database.query("SELECT * FROM backup_destinations WHERE project_id=? ORDER BY name").all(e).map(Ig)}recordDestinationTest(e,t){let r=this.now().toISOString();return this.controlPlane.database.run("UPDATE backup_destinations SET status=?,last_tested_at=?,last_success_at=CASE WHEN ? THEN ? ELSE last_success_at END,last_failure_at=CASE WHEN ? THEN last_failure_at ELSE ? END,last_error=?,version=version+1,updated_at=? WHERE id=?",[t.ok?"healthy":"failing",r,t.ok?1:0,r,t.ok?1:0,r,t.ok?null:String(t.error??"Destination test failed.").slice(0,1000),r,e]),this.getDestination(e)}createPolicy(e){if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(e.name))throw Error("Backup policy names must be lowercase slugs.");if(!e.resourceId&&!e.dataServiceId&&!["control_plane","infrastructure"].includes(e.resourceKind))throw Error("A backup policy requires a resource or data service target.");let t=this.getDestination(e.destinationId);if(!t||t.projectId!==e.projectId)throw Error("Backup destination was not found.");if(e.resourceKind==="control_plane"&&t.encryption==="provider")throw Error("Control-plane backups require client-side destination encryption.");if(["logical_database","volume","files","control_plane"].includes(e.resourceKind)&&t.provider==="aws_backup")throw Error(`${e.resourceKind} backups require an object-storage destination.`);if(e.resourceKind==="infrastructure"&&t.provider!=="aws_backup")throw Error("Infrastructure backups require an AWS Backup destination.");let r=sn(e.schedule),n=Mn(r.normalized,e.timezone,this.now(),1)[0],i=crypto.randomUUID(),o=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO backup_policies (id,organization_id,project_id,environment_id,resource_id,data_service_id,destination_id,name,resource_kind,schedule,timezone,retention,compression,encryption,include_patterns,exclude_patterns,expected_rpo_minutes,expected_rto_minutes,health_check_id,enabled,next_run_at,last_run_at,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[i,e.organizationId,e.projectId,e.environmentId??null,e.resourceId??null,e.dataServiceId??null,e.destinationId,e.name,e.resourceKind,r.normalized,e.timezone,JSON.stringify(e.retention),e.compression,e.encryption,JSON.stringify(e.includePatterns),JSON.stringify(e.excludePatterns),e.expectedRpoMinutes,e.expectedRtoMinutes,e.healthCheckId??null,e.enabled?1:0,n,e.lastRunAt??null,1,o,o]),this.getPolicy(i)}getPolicy(e){let t=this.controlPlane.database.query("SELECT * FROM backup_policies WHERE id=?").get(e);return t?ld(t):void 0}listPolicies(e,t){return this.controlPlane.database.query(`SELECT * FROM backup_policies WHERE project_id=?${t?" AND environment_id=?":""} ORDER BY name`).all(e,...t?[t]:[]).map(ld)}duePolicies(e=this.now()){return this.controlPlane.database.query("SELECT * FROM backup_policies WHERE enabled=1 AND next_run_at<=? ORDER BY next_run_at,id").all(e.toISOString()).map(ld)}advancePolicy(e,t){let r=this.getPolicy(e);if(!r)throw Error("Backup policy was not found.");let n=Mn(r.schedule,r.timezone,new Date(t),1)[0];return this.controlPlane.database.run("UPDATE backup_policies SET last_run_at=?,next_run_at=?,version=version+1,updated_at=? WHERE id=?",[t,n,this.now().toISOString(),e]),this.getPolicy(e)}createJob(e){let t=this.controlPlane.database.query("SELECT * FROM backup_jobs WHERE idempotency_key=?").get(e.idempotencyKey);if(t)return pd(t);let r=crypto.randomUUID(),n=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO backup_jobs (id,project_id,policy_id,recovery_point_id,operation_id,kind,status,idempotency_key,target,restore_mode,cancellability,safety_backup_id,health_result,progress,error,started_at,finished_at,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[r,e.projectId,e.policyId??null,e.recoveryPointId??null,e.operationId??null,e.kind,e.status,e.idempotencyKey,JSON.stringify(e.target),e.restoreMode??null,e.cancellability,e.safetyBackupId??null,e.healthResult?JSON.stringify(e.healthResult):null,JSON.stringify(e.progress),e.error??null,e.startedAt??null,e.finishedAt??null,n,n]),this.getJob(r)}getJob(e){let t=this.controlPlane.database.query("SELECT * FROM backup_jobs WHERE id=?").get(e);return t?pd(t):void 0}listJobs(e){return this.controlPlane.database.query("SELECT * FROM backup_jobs WHERE project_id=? ORDER BY created_at DESC").all(e).map(pd)}updateJob(e,t){let r=this.getJob(e);if(!r)throw Error("Backup job was not found.");let n={...r,...t};return this.controlPlane.database.run("UPDATE backup_jobs SET status=?,operation_id=?,recovery_point_id=?,progress=?,health_result=?,error=?,started_at=?,finished_at=?,safety_backup_id=?,updated_at=? WHERE id=?",[n.status,n.operationId??null,n.recoveryPointId??null,JSON.stringify(n.progress),n.healthResult?JSON.stringify(n.healthResult):null,n.error??null,n.startedAt??null,n.finishedAt??null,n.safetyBackupId??null,this.now().toISOString(),e]),this.getJob(e)}createRecoveryPoint(e){if(!/^sha256:[a-f0-9]{64}$/i.test(e.checksum))throw Error("Recovery points require a SHA-256 checksum.");if(typeof e.uri!=="string"||!["s3:","aws-backup:","file:"].some((n)=>e.uri.startsWith(n)))throw Error("Recovery point URI uses an unsupported destination scheme.");let t=crypto.randomUUID(),r=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO recovery_points (id,project_id,policy_id,destination_id,resource_id,data_service_id,backup_job_id,kind,point_in_time,uri,size_bytes,checksum,manifest,tool_version,engine_version,expires_at,locked_until,held,pinned,status,verification_state,verified_at,duration_ms,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.projectId,e.policyId??null,e.destinationId,e.resourceId??null,e.dataServiceId??null,e.backupJobId??null,e.kind,e.pointInTime,e.uri,e.sizeBytes,e.checksum,JSON.stringify(e.manifest),e.toolVersion??null,e.engineVersion??null,e.expiresAt??null,e.lockedUntil??null,e.held?1:0,e.pinned?1:0,e.status,e.verificationState,e.verifiedAt??null,e.durationMs??null,r,r]),this.getRecoveryPoint(t)}getRecoveryPoint(e){let t=this.controlPlane.database.query("SELECT * FROM recovery_points WHERE id=?").get(e);return t?ud(t):void 0}listRecoveryPoints(e,t){return this.controlPlane.database.query(`SELECT * FROM recovery_points WHERE project_id=?${t?" AND policy_id=?":""} ORDER BY point_in_time DESC`).all(e,...t?[t]:[]).map(ud)}updateRecoveryPoint(e,t){let r=this.getRecoveryPoint(e);if(!r)throw Error("Recovery point was not found.");let n={...r,...t};return this.controlPlane.database.run("UPDATE recovery_points SET status=?,verification_state=?,verified_at=?,held=?,pinned=?,manifest=?,duration_ms=?,updated_at=? WHERE id=?",[n.status,n.verificationState,n.verifiedAt??null,n.held?1:0,n.pinned?1:0,JSON.stringify(n.manifest),n.durationMs??null,this.now().toISOString(),e]),this.getRecoveryPoint(e)}retentionCandidates(e=this.now()){let t=this.controlPlane.database.query(`SELECT rp.* FROM recovery_points rp
|
|
55
|
+
WHERE rp.status='available' AND rp.held=0 AND rp.pinned=0
|
|
56
|
+
AND rp.expires_at IS NOT NULL AND rp.expires_at<=?
|
|
57
|
+
AND (rp.locked_until IS NULL OR rp.locked_until<=?)
|
|
58
|
+
AND NOT EXISTS (
|
|
59
|
+
SELECT 1 FROM backup_jobs bj WHERE bj.recovery_point_id=rp.id
|
|
60
|
+
AND bj.kind IN ('restore','drill') AND bj.status IN ('queued','running','cleanup_required')
|
|
61
|
+
)
|
|
62
|
+
ORDER BY rp.expires_at,rp.id`).all(e.toISOString(),e.toISOString()).map(ud),r=new Set;for(let n of new Set(t.map((i)=>i.projectId)))for(let i of this.listPolicies(n)){let o=this.listRecoveryPoints(i.projectId,i.id).filter((c)=>c.status==="available").sort((c,d)=>d.pointInTime.localeCompare(c.pointInTime));for(let c of o.slice(0,Math.max(0,i.retention.keepLast??0)))r.add(c.id);let s=[[i.retention.hourly,(c)=>c.toISOString().slice(0,13)],[i.retention.daily,(c)=>c.toISOString().slice(0,10)],[i.retention.weekly,(c)=>new Date(Date.UTC(c.getUTCFullYear(),c.getUTCMonth(),c.getUTCDate()-(c.getUTCDay()+6)%7)).toISOString().slice(0,10)],[i.retention.monthly,(c)=>c.toISOString().slice(0,7)]];for(let[c,d]of s){let a=new Set;for(let u of o){let m=d(new Date(u.pointInTime));if(a.has(m))continue;if(a.add(m),a.size<=Math.max(0,c??0))r.add(u.id)}}}return t.filter((n)=>!r.has(n.id))}coverage(e,t=this.now()){let r=new Map(this.listDestinations(e).map((n)=>[n.id,n]));return this.listPolicies(e).map((n)=>{let i=this.listRecoveryPoints(e,n.id).filter((c)=>c.status==="available"),o=i[0],s=o?(t.getTime()-new Date(o.pointInTime).getTime())/60000:Number.POSITIVE_INFINITY;return{policy:n,lastRecoveryPoint:o,missedRpo:n.enabled&&s>n.expectedRpoMinutes,unverified:i.filter((c)=>c.verificationState!=="verified").length,destinationHealthy:r.get(n.destinationId)?.status==="healthy"}})}}import{createCipheriv as Kk,createDecipheriv as Jk,createHash as Eg,randomBytes as Rg}from"node:crypto";var gd=Buffer.from("TSCB1"),Ds=(e)=>`sha256:${Eg("sha256").update(e).digest("hex")}`;function Ag(e){return Eg("sha256").update(e).digest()}function Gk(e,t,r){let n=r?Buffer.from(r):Rg(12);if(n.length!==12)throw Error("Backup encryption IV must contain 12 bytes.");let i=Kk("aes-256-gcm",Ag(t),n),o=Buffer.concat([i.update(e),i.final()]),s=i.getAuthTag();return Buffer.concat([gd,n,s,o])}function Qk(e,t){let r=Buffer.from(e);if(!r.subarray(0,gd.length).equals(gd))throw Error("Backup does not contain a valid encrypted envelope.");let n=r.subarray(5,17),i=r.subarray(17,33),o=r.subarray(33),s=Jk("aes-256-gcm",Ag(t),n);return s.setAuthTag(i),Buffer.concat([s.update(o),s.final()])}function Yk(e){let t;try{t=JSON.parse(e)}catch{throw Error("Backup destination credential must be a JSON object with accessKeyId and secretAccessKey.")}if(!t.accessKeyId||!t.secretAccessKey)throw Error("Backup destination credential requires accessKeyId and secretAccessKey.");if(t.expiresAt){let r=new Date(String(t.expiresAt));if(!Number.isFinite(r.getTime()))throw Error("Backup destination credential expiresAt must be an ISO timestamp.");if(r.getTime()<=Date.now())throw Error("Backup destination credential has expired.")}return{accessKeyId:String(t.accessKeyId),secretAccessKey:String(t.secretAccessKey),sessionToken:t.sessionToken?String(t.sessionToken):void 0}}async function Cg(e,t,r=new Date){if(!e.credentialRef)return{status:"default"};try{let n=JSON.parse(await t.resolve(e.credentialRef));if(!n.accessKeyId||!n.secretAccessKey)return{status:"invalid"};if(!n.expiresAt)return{status:"static"};let i=new Date(String(n.expiresAt));if(!Number.isFinite(i.getTime()))return{status:"invalid"};let o=i.getTime()-r.getTime();return{status:o<=0?"expired":o<=604800000?"expiring":"valid",expiresAt:i.toISOString()}}catch{return{status:"invalid"}}}class fd{secrets;clientFactory;multipartThreshold;partSize;constructor(e,t=(i,o)=>new ur(i.region??"us-east-1",void 0,{endpoint:i.endpoint?new URL(i.endpoint).host:void 0,forcePathStyle:i.forcePathStyle,credentials:o}),r=8388608,n=8388608){this.secrets=e;this.clientFactory=t;this.multipartThreshold=r;this.partSize=n}async client(e){let t=e.credentialRef?Yk(await this.secrets.resolve(e.credentialRef)):void 0;return this.clientFactory(e,t)}async test(e){if(!e.bucket)throw Error("S3 destination has no configured bucket.");let t=await this.client(e),r=`${e.prefix?`${e.prefix.replace(/\/$/,"")}/`:""}.ts-cloud-health/${crypto.randomUUID()}`;await t.putObject({bucket:e.bucket,key:r,body:"ts-cloud backup destination health check",contentType:"text/plain"});try{let n=await t.getObjectBytes(e.bucket,r);if(Buffer.from(n.body).toString()!=="ts-cloud backup destination health check")throw Error("Backup destination health object was corrupted.")}finally{await t.deleteObject(e.bucket,r)}}async upload(e,t){if(!e.bucket)throw Error("S3 destination has no configured bucket.");let r=await this.client(e),n=Ds(t.body),i=e.encryption!=="provider"?await this.secrets.resolve(e.encryptionKeyRef):void 0,o=i?t.resume?.encryptionIv?Buffer.from(t.resume.encryptionIv,"base64url"):Rg(12):void 0,s=i?Gk(t.body,i,o):Buffer.from(t.body),c=Ds(s),d=`${e.prefix?`${e.prefix.replace(/\/$/,"")}/`:""}${t.key.replace(/^\/+/,"")}`,a=t.contentType??"application/octet-stream",u={"ts-cloud-format":"v1","ts-cloud-sha256":c.slice(7),"ts-cloud-encrypted":i?"true":"false"};if(t.resume&&t.resume.key!==d)throw Error("Multipart checkpoint does not match the requested backup key.");if(t.resume&&i&&!t.resume.encryptionIv)throw Error("Encrypted multipart checkpoint has no resumable envelope state.");if(t.resume&&i&&t.resume.plaintextChecksum!==n)throw Error("Encrypted multipart checkpoint does not match the backup payload.");if(s.length<this.multipartThreshold)await r.putObject({bucket:e.bucket,key:d,body:s,contentType:a,metadata:u});else{let m=t.resume?void 0:await r.createMultipartUpload(e.bucket,d,{contentType:a,metadata:u}),h=t.resume??{uploadId:m.UploadId,key:d,parts:[],bytesUploaded:0,encryptionIv:o?.toString("base64url"),plaintextChecksum:n},y=new Map(h.parts.map((k)=>[k.PartNumber,k])),w=Math.ceil(s.length/this.partSize);for(let k=0;k<w;k++){let C=k+1;if(!y.has(C)){let T=k*this.partSize,j=await r.uploadPart(e.bucket,d,h.uploadId,C,s.subarray(T,Math.min(s.length,T+this.partSize)));y.set(C,{PartNumber:C,ETag:j.ETag})}h.parts=[...y.values()].sort((T,j)=>T.PartNumber-j.PartNumber),h.bytesUploaded=Math.min(s.length,C*this.partSize),t.checkpoint?.(h)}await r.completeMultipartUpload(e.bucket,d,h.uploadId,h.parts)}return{uri:`s3://${e.bucket}/${d}`,key:d,sizeBytes:s.length,checksum:c,manifest:{format:"ts-cloud-backup-v1",encrypted:!!i,plaintextChecksum:n,storageChecksum:c,contentType:a}}}async download(e,t){if(!e.bucket)throw Error("S3 destination has no configured bucket.");let r=await this.client(e),n=await r.getObjectBytes(e.bucket,t.key),i=Buffer.from(n.body);if(Ds(i)!==t.checksum)throw Error("Backup checksum verification failed; object is corrupt.");let o=t.manifest.encrypted?Qk(i,await this.secrets.resolve(e.encryptionKeyRef)):i;if(Ds(o)!==t.manifest.plaintextChecksum)throw Error("Backup plaintext checksum verification failed.");return o}async abortPartial(e,t){if(!e.bucket)throw Error("S3 destination has no configured bucket.");await(await this.client(e)).abortMultipartUpload(e.bucket,t.key,t.uploadId)}async delete(e,t){if(!e.bucket)throw Error("S3 destination has no configured bucket.");await(await this.client(e)).deleteObject(e.bucket,t)}}import{createHash as Zk}from"node:crypto";var Xk=(e)=>`sha256:${Zk("sha256").update(e).digest("hex")}`;class Os{store;queue;now;constructor(e,t,r=()=>new Date){this.store=e;this.queue=t;this.now=r}enqueueBackup(e,t=this.now().toISOString(),r){if(!e.enabled)throw Error("Backup policy is disabled.");let n=this.store.createJob({projectId:e.projectId,policyId:e.id,kind:"backup",status:"queued",idempotencyKey:`backup:${e.id}:${t}`,target:{scheduledFor:t},cancellability:"checkpoint_only",progress:{phase:"queued"}});if(!n.operationId){let i=this.queue.enqueue({projectId:e.projectId,environmentId:e.environmentId,resourceId:e.resourceId,actorId:r,kind:"backup.run",input:{backupJobId:n.id},lockKey:e.dataServiceId?`data-service:${e.dataServiceId}`:e.resourceId?`resource:${e.resourceId}`:`backup-policy:${e.id}`,providerKey:"backup",maxAttempts:3,timeoutSeconds:14400,retryClasses:["provider_transient"],resumePolicy:"requeue"});return this.store.updateJob(n.id,{operationId:i.operation.id})}return n}enqueueDue(e=this.now()){return this.store.duePolicies(e).map((t)=>{let r=t.nextRunAt;return this.store.advancePolicy(t.id,r),this.enqueueBackup(t,r)})}enqueueVerification(e){let t=this.store.createJob({projectId:e.projectId,policyId:e.policyId,recoveryPointId:e.id,kind:"verify",status:"queued",idempotencyKey:`verify:${e.id}:${e.checksum}`,target:{},cancellability:"safe",progress:{phase:"queued"}});if(!t.operationId){let r=this.queue.enqueue({projectId:e.projectId,resourceId:e.resourceId,kind:"backup.verify",input:{backupJobId:t.id},lockKey:`recovery-point:${e.id}`,providerKey:"backup",maxAttempts:2,timeoutSeconds:7200,retryClasses:["provider_transient"],resumePolicy:"requeue"});return this.store.updateJob(t.id,{operationId:r.operation.id})}return t}planRestore(e,t){if(e.status!=="available")throw Error("Only available recovery points can be restored.");if(e.verificationState!=="verified")throw Error("Restore requires a verified recovery point.");if(t.mode==="in_place"){if(!t.recentAuth)throw Error("In-place restore requires recent authentication.");if(t.confirm!==t.targetName)throw Error(`Type ${t.targetName} to confirm in-place restore.`);if(!t.downtimeAcknowledged)throw Error("In-place restore requires downtime acknowledgement.");let r=t.safetyBackupId?this.store.getRecoveryPoint(t.safetyBackupId):void 0;if(!r||r.id===e.id||r.status!=="available"||r.verificationState!=="verified"||r.resourceId!==e.resourceId||r.dataServiceId!==e.dataServiceId)throw Error("In-place restore requires a distinct verified safety backup for the same target.")}return{point:e,mode:t.mode,target:{...t.target,inPlace:t.mode==="in_place",restoreMode:t.mode},warnings:t.mode==="in_place"?["The target is locked against deployments and backup work.","Downtime and data replacement are expected.","Provider cancellation may stop only at a checkpoint."]:["An isolated target is created and health-validated before cleanup."]}}enqueueRestore(e,t){let r=this.planRestore(e,t),n=t.drill?"drill":"restore",i=Xk(JSON.stringify({point:e.id,mode:t.mode,target:t.target,safety:t.safetyBackupId,drill:!!t.drill})),o=this.store.createJob({projectId:e.projectId,policyId:e.policyId,recoveryPointId:e.id,kind:n,status:"queued",idempotencyKey:`${n}:${i}`,target:r.target,restoreMode:r.mode,cancellability:"checkpoint_only",safetyBackupId:t.safetyBackupId,progress:{phase:"queued",warnings:r.warnings}});if(!o.operationId){let s=this.queue.enqueue({projectId:e.projectId,resourceId:e.resourceId,actorId:t.actorId,kind:t.drill?"backup.drill":"backup.restore",input:{backupJobId:o.id},lockKey:e.dataServiceId?`data-service:${e.dataServiceId}`:e.resourceId?`resource:${e.resourceId}`:`recovery-point:${e.id}`,providerKey:"backup",maxAttempts:1,timeoutSeconds:14400,retryClasses:[],resumePolicy:"fail"});return this.store.updateJob(o.id,{operationId:s.operation.id})}return o}enqueueRetention(e=this.now()){return this.store.retentionCandidates(e).map((t)=>{let r=this.store.createJob({projectId:t.projectId,policyId:t.policyId,recoveryPointId:t.id,kind:"cleanup",status:"queued",idempotencyKey:`cleanup:${t.id}:${t.expiresAt}`,target:{},cancellability:"safe",progress:{phase:"queued"}});if(!r.operationId){let n=this.queue.enqueue({projectId:t.projectId,resourceId:t.resourceId,kind:"backup.cleanup",input:{backupJobId:r.id},lockKey:`recovery-point:${t.id}`,providerKey:"backup",maxAttempts:3,timeoutSeconds:7200,retryClasses:["provider_transient"],resumePolicy:"requeue"});return this.store.updateJob(r.id,{operationId:n.operation.id})}return r})}}function Pg(e){let t=e.now??(()=>new Date),r=new Os(e.store,e.queue,t),n=(c)=>{let d=c.recoveryPointId?e.store.getRecoveryPoint(c.recoveryPointId):void 0,a=c.policyId?e.store.getPolicy(c.policyId):d?.policyId?e.store.getPolicy(d.policyId):void 0;if(!a)throw Error("Backup policy was not found.");let u=e.store.getDestination(d?.destinationId??a.destinationId),m=e.resolveSource(a);if(!u)throw Error("Backup destination was not found.");if(!m)throw Error(`No ${a.resourceKind} backup adapter is configured.`);return{point:d,policy:a,destination:u,source:m}},i=(c)=>{let d=c.operation.input,a=e.store.getJob(String(d.backupJobId??""));if(!a)throw Error("Backup job was not found.");return e.store.updateJob(a.id,{status:"running",startedAt:a.startedAt??t().toISOString(),progress:{...a.progress,phase:"running"}}),a},o=(c,d)=>{let a=e.store.getJob(c.id)??c;e.store.updateJob(c.id,{status:"failed",finishedAt:t().toISOString(),error:d instanceof Error?d.message:String(d),progress:{...a.progress,phase:"failed"}})};return{"backup.run":async(c)=>{let d=i(c);try{let{policy:a,destination:u,source:m}=n(d),h=await m.create(a,c),y=e.resolveDestination(u),w=h.mode==="object"?await(async()=>{if(!y)throw Error("Backup destination adapter is not configured.");let j=e.store.getJob(d.id)?.progress,P=j?.multipart,O=P&&typeof P==="object"&&!Array.isArray(P)&&typeof P.uploadId==="string"&&typeof P.key==="string"&&Array.isArray(P.parts)?P:void 0;return y.upload(u,{key:h.key,body:h.body,contentType:h.contentType,resume:O,checkpoint:(U)=>{c.checkpoint("uploading",`Uploaded ${Number(U.bytesUploaded??0)} backup bytes.`),e.store.updateJob(d.id,{progress:{phase:"uploading",multipart:{...U}}})}})})():{uri:h.uri,key:h.uri,sizeBytes:h.sizeBytes,checksum:h.checksum,manifest:{format:"ts-cloud-backup-v1",encrypted:!1,plaintextChecksum:h.checksum,storageChecksum:h.checksum,contentType:"application/provider-snapshot"}},k=a.retention.expireAfterDays?new Date(t().getTime()+a.retention.expireAfterDays*86400000).toISOString():void 0,C=e.store.getJob(d.id)?.startedAt,T=e.store.createRecoveryPoint({projectId:a.projectId,policyId:a.id,destinationId:u.id,resourceId:a.resourceId,dataServiceId:a.dataServiceId,backupJobId:d.id,kind:a.resourceKind,pointInTime:t().toISOString(),uri:w.uri,sizeBytes:w.sizeBytes,checksum:w.checksum,manifest:{...h.manifest,...w.manifest,storageKey:w.key},toolVersion:h.toolVersion,engineVersion:h.engineVersion,expiresAt:k,lockedUntil:u.immutability.defaultRetentionDays?new Date(t().getTime()+u.immutability.defaultRetentionDays*86400000).toISOString():void 0,held:!1,pinned:!1,status:"available",verificationState:"unverified",durationMs:Math.max(0,t().getTime()-new Date(C??t().toISOString()).getTime())});if(h.mode==="external"&&u.provider==="aws_backup")e.store.recordDestinationTest(u.id,{ok:!0});return e.store.updateJob(d.id,{status:"succeeded",recoveryPointId:T.id,finishedAt:t().toISOString(),progress:{phase:"stored",recoveryPointId:T.id}}),r.enqueueVerification(T),{backupJobId:d.id,recoveryPointId:T.id}}catch(a){let u=e.store.getJob(d.id),m=u?.progress.multipart,h=(()=>{try{return n(d)}catch{return}})();if(h?.destination.provider==="aws_backup")e.store.recordDestinationTest(h.destination.id,{ok:!1,error:a instanceof Error?a.message:String(a)});let y=!1;if(m&&typeof m==="object"&&!Array.isArray(m)&&h){let w=e.resolveDestination(h.destination);if(y=!0,w?.abortPartial)try{await w.abortPartial(h.destination,m),y=!1,e.store.updateJob(d.id,{progress:{...u.progress,partialCleanup:"aborted"}})}catch{e.store.updateJob(d.id,{progress:{...u.progress,partialCleanup:"required"}})}}if(y)e.store.updateJob(d.id,{status:"cleanup_required",finishedAt:t().toISOString(),error:a instanceof Error?a.message:String(a),progress:{...e.store.getJob(d.id)?.progress??{},phase:"cleanup_required"}});else o(d,a);throw a}},"backup.verify":async(c)=>{let d=i(c);try{let{point:a,destination:u,source:m}=n(d);if(!a)throw Error("Recovery point was not found.");e.store.updateRecoveryPoint(a.id,{verificationState:"verifying"});let h;if(a.uri.startsWith("s3:")){let y=e.resolveDestination(u);if(!y)throw Error("Backup destination adapter is not configured.");let w=await y.download(u,{key:String(a.manifest.storageKey??""),checksum:a.checksum,manifest:a.manifest}),k=m.verify?await m.verify(a,w,c):{};h={bytes:w.length,checksum:a.checksum,...k}}else if(m.verifyExternal)h=await m.verifyExternal(a,c);else throw Error("External recovery point verification is not supported.");return e.store.updateRecoveryPoint(a.id,{verificationState:"verified",verifiedAt:t().toISOString(),manifest:{...a.manifest,verification:h}}),e.store.updateJob(d.id,{status:"succeeded",finishedAt:t().toISOString(),progress:{phase:"verified",evidence:h}}),{backupJobId:d.id,recoveryPointId:a.id,evidence:h}}catch(a){if(d.recoveryPointId)e.store.updateRecoveryPoint(d.recoveryPointId,{verificationState:/checksum|corrupt|authentic/i.test(a instanceof Error?a.message:String(a))?"corrupt":"failed"});throw o(d,a),a}},"backup.restore":async(c)=>s(c,!1),"backup.drill":async(c)=>s(c,!0),"backup.cleanup":async(c)=>{let d=i(c);try{let{point:a,destination:u,source:m}=n(d);if(!a)throw Error("Recovery point was not found.");if(!e.store.retentionCandidates(t()).some((h)=>h.id===a.id))throw Error("Recovery point is held, pinned, locked, or in active use.");if(e.store.updateRecoveryPoint(a.id,{status:"deleting"}),a.uri.startsWith("s3:")){let h=e.resolveDestination(u);if(!h)throw Error("Destination cleanup is unavailable.");await h.delete(u,String(a.manifest.storageKey??""))}else if(m.deleteExternal)await m.deleteExternal(a,c);else throw Error("External recovery point cleanup is unavailable.");return e.store.updateRecoveryPoint(a.id,{status:"deleted"}),e.store.updateJob(d.id,{status:"succeeded",finishedAt:t().toISOString(),progress:{phase:"deleted"}}),{backupJobId:d.id,recoveryPointId:a.id,deleted:!0}}catch(a){throw o(d,a),a}}};async function s(c,d){let a=i(c);try{let{point:u,policy:m,destination:h,source:y}=n(a);if(!u)throw Error("Recovery point was not found.");if(d&&!y.cleanup)throw Error("This backup source cannot safely clean a recovery drill target.");let w=u.uri.startsWith("s3:")?e.resolveDestination(h):void 0,k=w?await w.download(h,{key:String(u.manifest.storageKey??""),checksum:u.checksum,manifest:u.manifest}):void 0,C=await y.restore(u,k,a.target,c),T=y.validateHealth?await y.validateHealth({...a.target,...C},c):{healthy:!0,mode:"adapter"},j=e.validateHealth?await e.validateHealth(m,a.target):{healthy:!0,mode:"not_configured"},P={...T,healthy:T.healthy===!0&&j.healthy===!0,configured:j};if(P.healthy!==!0)throw Error("Restored target did not pass its configured health check.");if(d&&y.cleanup)await y.cleanup({...a.target,provider:u.manifest.provider??null},c);return e.store.updateJob(a.id,{status:"succeeded",finishedAt:t().toISOString(),healthResult:P,progress:{phase:d?"drill_cleaned":"restored",restored:C}}),{backupJobId:a.id,recoveryPointId:u.id,restored:C,health:P,cleaned:d}}catch(u){let m=(()=>{try{return n(a)}catch{return}})(),h=u instanceof Error?u.message:String(u),y=!1;if(d&&m?.source.cleanup)try{await m.source.cleanup({...a.target,provider:m.point?.manifest.provider??null},c)}catch{y=!0}if(y)e.store.updateJob(a.id,{status:"cleanup_required",finishedAt:t().toISOString(),error:h,progress:{...a.progress,phase:"cleanup_required"}});else o(a,u);throw u}}}import{createHash as eI}from"node:crypto";var tI=(e)=>`sha256:${eI("sha256").update(e).digest("hex")}`;class hd{dataServices;client;constructor(e,t=new Fn){this.dataServices=e;this.client=t}service(e){let t=e.dataServiceId?this.dataServices.get(e.dataServiceId):void 0;if(!t||!["aws_rds","aws_aurora"].includes(t.provider))throw Error("Managed database backup policy requires an RDS or Aurora data service.");return t}async waitForSnapshot(e,t,r){for(;;){r.throwIfCancellationRequested?.(),r.heartbeat?.();let n=e==="aws_aurora"?(await this.client.describeDBClusterSnapshots({DBClusterSnapshotIdentifier:t})).DBClusterSnapshots[0]:(await this.client.describeDBSnapshots({DBSnapshotIdentifier:t})).DBSnapshots?.[0];if(!n)throw Error("Provider snapshot was not found.");let i=n,o=String(i.Status??i.DBSnapshotStatus??"unknown");if(r.checkpoint?.("provider_snapshot",`Database snapshot ${t} is ${o}.`),o==="available")return i;if(["deleted","deleting","failed"].includes(o))throw Error(`Provider snapshot ${t} failed with state ${o}.`);await Bun.sleep(5000)}}async create(e,t){let r=this.service(e),n=String(t.operation?.id??new Date().toISOString()).replace(/[^A-Za-z0-9]/g,"").slice(0,20),i=`${r.placement.slice(0,42).replace(/-+$/,"")}-${n}`;if(r.provider==="aws_aurora")await this.client.createDBClusterSnapshot(r.placement,i);else await this.client.createDBSnapshot({DBInstanceIdentifier:r.placement,DBSnapshotIdentifier:i});await this.waitForSnapshot(r.provider,i,t);let o=`${r.provider}:${r.placement}:${i}`;return{mode:"external",uri:`aws-backup:${o}`,checksum:tI(o),sizeBytes:0,manifest:{provider:r.provider,sourceId:r.placement,snapshotId:i,plan:r.plan,engine:r.engine},engineVersion:r.engineVersion,toolVersion:"aws-rds-api-2014-10-31"}}async verifyExternal(e,t){let r=String(e.manifest.snapshotId??""),n=String(e.manifest.provider??"");if(!r)throw Error("Snapshot recovery point has no snapshot ID.");let i=await this.waitForSnapshot(n,r,t),o=String(i.Status??i.DBSnapshotStatus??"unknown");return{snapshotId:r,status:o,encrypted:i.Encrypted??i.StorageEncrypted??!0}}async restore(e,t,r,n){let i=String(r.targetId??""),o=String(e.manifest.snapshotId??""),s=String(e.manifest.provider??"");if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(i))throw Error("Managed restore requires a valid distinct targetId.");if(i===e.manifest.sourceId)throw Error("Managed restore target must differ from its source.");if(s==="aws_aurora"){let c=e.manifest.engine==="postgres"?"aurora-postgresql":"aurora-mysql";await this.client.restoreDBClusterFromSnapshot({DBClusterIdentifier:i,SnapshotIdentifier:o,Engine:c,EngineVersion:e.engineVersion,DeletionProtection:!0,ServerlessV2ScalingConfiguration:{MinCapacity:Number(r.minCapacity)||0.5,MaxCapacity:Number(r.maxCapacity)||4}}),await this.client.createDBInstance({DBInstanceIdentifier:`${i}-writer-1`,DBClusterIdentifier:i,DBInstanceClass:String(r.plan??e.manifest.plan??"db.serverless"),Engine:c,PubliclyAccessible:!1})}else await this.client.restoreDBInstanceFromDBSnapshot({DBInstanceIdentifier:i,DBSnapshotIdentifier:o,DBInstanceClass:String(r.plan??e.manifest.plan??""),PubliclyAccessible:!1,DeletionProtection:!0,Tags:[{Key:"managed-by",Value:"ts-cloud-restore"}]});return{targetId:i,provider:s,status:"creating",isolated:!0}}async validateHealth(e,t){let r=String(e.targetId??""),n=String(e.provider??"");for(;;){t.throwIfCancellationRequested?.(),t.heartbeat?.();let i=n==="aws_aurora"?(await this.client.describeDBClusters({DBClusterIdentifier:r})).DBClusters?.[0]:(await this.client.describeDBInstances({DBInstanceIdentifier:r})).DBInstances?.[0];if(!i)throw Error("Restored managed database was not found.");let o=String(i.Status??i.DBInstanceStatus??"unknown");if(t.checkpoint?.("provider_restore",`Restored database ${r} is ${o}.`),o==="available")return{healthy:!0,targetId:r,provider:n,status:o};if(["deleted","deleting","failed","incompatible-restore"].includes(o))throw Error(`Restored managed database ${r} failed with state ${o}.`);await Bun.sleep(5000)}}async cleanup(e,t){let r=String(e.targetId??""),n=String(e.provider??"");if(!r)throw Error("Restore cleanup target is required.");if(n==="aws_aurora")await this.client.deleteDBInstance({DBInstanceIdentifier:`${r}-writer-1`,SkipFinalSnapshot:!0}),await this.client.modifyDBCluster({DBClusterIdentifier:r,DeletionProtection:!1,ApplyImmediately:!0}),await this.client.deleteDBCluster(r);else await this.client.modifyDBInstance({DBInstanceIdentifier:r,DeletionProtection:!1,ApplyImmediately:!0}),await this.client.deleteDBInstance({DBInstanceIdentifier:r,SkipFinalSnapshot:!0,DeleteAutomatedBackups:!0})}async deleteExternal(e,t){let r=String(e.manifest.snapshotId??"");if(e.manifest.provider==="aws_aurora")await this.client.deleteDBClusterSnapshot(r);else await this.client.deleteDBSnapshot(r)}}var bt=(e,t="none",r=!1)=>({supported:!0,downtime:t,destructive:r,explanation:e}),dt=(e)=>({supported:!1,downtime:"none",destructive:!1,explanation:e});function vo(e,t){let r=["aws_rds","aws_aurora","aws_elasticache"].includes(t),n=["server","container"].includes(t),i=["postgres","mysql","mariadb"].includes(e),o=e==="redis",s={};return s.create=t==="external"?dt("External services can be adopted as read-only inventory."):bt(r?"Provision through the provider API.":"Provision through the owning runtime driver.","possible"),s.observe=t==="external"?dt("External observation requires a configured provider adapter."):bt("Provider/runtime health and endpoint metadata are observable."),s.connect=bt("Connection guidance uses secret references and never returns a password by default."),s.backup=i&&(r||n)?bt(r?"Create a provider snapshot.":"Create a consistent engine-native dump.","possible"):dt("This cache path is not a durable backup source."),s.restore=r&&i?bt("Restore creates a reviewed provider target.","required",!0):dt("Restore requires a configured provider restore runner."),s.restart=t==="external"?dt("External restart requires a configured provider adapter."):bt(r?"Provider restart/failover semantics apply.":"Restart the owning service unit.","required"),s.resize=t==="aws_elasticache"?dt("ElastiCache resizing requires a replication-group migration runner."):r?bt("Provider plan/storage modification may enter a maintenance window.","possible"):n?bt("Edit host/container resources and reconcile.","required"):dt("External resize requires a configured provider adapter."),s.version=n?dt("Runtime version upgrades require an explicit image migration runner."):r&&t!=="aws_elasticache"?bt(i?"Major versions require compatibility preflight and backup.":"Engine upgrades require a maintenance window.","required"):dt("External upgrades require a configured provider adapter."),s.rotate=t==="aws_elasticache"||t==="external"||n&&!i&&!o?dt("Credential rotation is not available for this provider/engine path."):bt("Rotate through the secret backend, update the engine, then flag dependent releases."),s.expose=n?dt("Direct container publishing is refused; use a reviewed firewall and proxy policy."):t==="aws_rds"?bt("Exposure is reconciled through security groups; public access defaults off."):dt("Exposure changes require a provider-specific network runner."),s.delete=t==="external"?dt("External deletion requires a configured provider adapter."):bt(r?"Final snapshot is supported where the provider allows it.":"A final engine backup is required unless explicitly retained.","required",!0),s.logs=n?bt("Read bounded service logs from the runtime."):dt("Provider log export is not configured for this adapter."),s.slow_queries=n&&i?bt("Read bounded runtime logs after engine slow-query logging is enabled."):dt("A slow-query log runner is not configured for this provider."),s.users=n&&i?bt("Logical users can be listed; creation requires a referenced secondary credential."):dt("User management requires an engine connection runner."),s.databases=n&&i?bt("Logical databases can be listed, created, and confirmation-gated for deletion."):dt("Logical database management requires an engine connection runner."),{actions:s,endpointTypes:r?["internal","external","tunnel"]:["internal","tunnel"],metrics:o?["connections","memory","evictions","hit_rate","latency"]:["connections","cpu","storage","read_latency","write_latency","iops"]}}var wi=(e)=>e==null?void 0:String(e),Ns=(e)=>Number(e)===1,$s=(e)=>{try{return JSON.parse(String(e))}catch{return{}}};function _g(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:wi(e.environment_id),resourceId:wi(e.resource_id),name:String(e.name),engine:String(e.engine),provider:String(e.provider),placement:String(e.placement),engineVersion:wi(e.engine_version),plan:String(e.plan),storageGb:e.storage_gb==null?void 0:Number(e.storage_gb),highAvailability:Ns(e.high_availability),publicExposure:Ns(e.public_exposure),allowedCidrs:$s(e.allowed_cidrs),desiredState:$s(e.desired_state),observedState:$s(e.observed_state),capabilities:$s(e.capabilities),credentialRef:wi(e.credential_ref),status:String(e.status),origin:String(e.origin),managementEnabled:Ns(e.management_enabled),ownerActorId:wi(e.owner_actor_id),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}class yd{controlPlane;now;constructor(e,t=()=>new Date){this.controlPlane=e;this.now=t}create(e){if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(e.name))throw Error("Data service names must be 2-63 lowercase letters, numbers, or dashes.");if(e.publicExposure&&(!e.allowedCidrs.length||e.allowedCidrs.includes("0.0.0.0/0")))throw Error("Public exposure requires explicit narrow CIDRs; 0.0.0.0/0 is refused.");let t=crypto.randomUUID(),r=this.now().toISOString(),n=vo(e.engine,e.provider);return this.controlPlane.database.run("INSERT INTO data_services (id,organization_id,project_id,environment_id,resource_id,name,engine,provider,placement,engine_version,plan,storage_gb,high_availability,public_exposure,allowed_cidrs,desired_state,observed_state,capabilities,credential_ref,status,origin,management_enabled,owner_actor_id,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.organizationId,e.projectId,e.environmentId??null,e.resourceId??null,e.name,e.engine,e.provider,e.placement,e.engineVersion??null,e.plan,e.storageGb??null,e.highAvailability?1:0,e.publicExposure?1:0,JSON.stringify(e.allowedCidrs),JSON.stringify(e.desiredState),JSON.stringify(e.observedState),JSON.stringify(n),e.credentialRef??null,e.status,e.origin,e.managementEnabled?1:0,e.ownerActorId??null,1,r,r]),this.get(t)}get(e){let t=this.controlPlane.database.query("SELECT * FROM data_services WHERE id=?").get(e);return t?_g(t):void 0}list(e,t){return this.controlPlane.database.query(`SELECT * FROM data_services WHERE project_id=?${t?" AND environment_id=?":""} ORDER BY name`).all(e,...t?[t]:[]).map(_g)}update(e,t,r){let n=this.get(e);if(!n)throw Error("Data service was not found.");if(n.version!==t)throw Error("Data service changed; refresh before retrying.");let i={...n,...r};if(i.publicExposure&&(!i.allowedCidrs.length||i.allowedCidrs.includes("0.0.0.0/0")))throw Error("Public exposure requires explicit narrow CIDRs; 0.0.0.0/0 is refused.");if(this.controlPlane.database.run("UPDATE data_services SET plan=?,storage_gb=?,engine_version=?,high_availability=?,public_exposure=?,allowed_cidrs=?,desired_state=?,observed_state=?,status=?,management_enabled=?,credential_ref=?,version=version+1,updated_at=? WHERE id=? AND version=?",[i.plan,i.storageGb??null,i.engineVersion??null,i.highAvailability?1:0,i.publicExposure?1:0,JSON.stringify(i.allowedCidrs),JSON.stringify(i.desiredState),JSON.stringify(i.observedState),i.status,i.managementEnabled?1:0,i.credentialRef??null,this.now().toISOString(),e,t]).changes!==1)throw Error("Data service changed; refresh before retrying.");return this.get(e)}credential(e){let t=this.controlPlane.database.query("SELECT * FROM data_service_credentials WHERE service_id=? ORDER BY version DESC LIMIT 1").get(e);return t?{id:String(t.id),serviceId:String(t.service_id),username:String(t.username),secretRef:String(t.secret_ref),version:Number(t.version),createdAt:String(t.created_at),rotatedAt:wi(t.rotated_at)}:void 0}saveCredential(e,t,r){let n=this.credential(e),i=n?.id??crypto.randomUUID(),o=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO data_service_credentials (id,service_id,username,secret_ref,version,created_at,rotated_at) VALUES (?,?,?,?,?,?,?) ON CONFLICT(service_id,username) DO UPDATE SET secret_ref=excluded.secret_ref,version=data_service_credentials.version+1,rotated_at=excluded.rotated_at",[i,e,t,r,n?.version??1,n?.createdAt??o,n?o:null]),this.credential(e)}addDependency(e){let t=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO data_service_dependencies (service_id,resource_id,secret_ref,requires_redeploy,created_at) VALUES (?,?,?,?,?) ON CONFLICT(service_id,resource_id) DO UPDATE SET secret_ref=excluded.secret_ref,requires_redeploy=excluded.requires_redeploy",[e.serviceId,e.resourceId,e.secretRef,e.requiresRedeploy?1:0,t]),{...e,createdAt:t}}dependencies(e){return this.controlPlane.database.query("SELECT * FROM data_service_dependencies WHERE service_id=? ORDER BY resource_id").all(e).map((t)=>({serviceId:String(t.service_id),resourceId:String(t.resource_id),secretRef:String(t.secret_ref),requiresRedeploy:Ns(t.requires_redeploy),createdAt:String(t.created_at)}))}removeDependency(e,t){return this.controlPlane.database.run("DELETE FROM data_service_dependencies WHERE service_id=? AND resource_id=?",[e,t]).changes===1}remove(e){this.controlPlane.database.run("DELETE FROM data_services WHERE id=?",[e])}}function Tg(){let t=crypto.getRandomValues(new Uint8Array(40));return Array.from(t,(r)=>"ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@#$%^&*_-+="[r%69]).join("")}function xg(e,t){return t.map((r)=>{let n=r.type==="tunnel"?"127.0.0.1":r.host,i=e.engine==="redis"?`redis-cli -h ${n} -p ${r.port}${r.tls?" --tls":""}`:e.engine==="postgres"?`psql "host=${n} port=${r.port} dbname=${r.database??"postgres"} sslmode=${r.tls?"require":"disable"}"`:e.engine==="mongodb"?`mongosh "mongodb://${n}:${r.port}/${r.database??"admin"}${r.tls?"?tls=true":""}"`:e.engine==="libsql"?`turso db shell ${r.tls?"https":"http"}://${n}:${r.port}`:`mysql --host=${n} --port=${r.port} --database=${r.database??"mysql"} --ssl-mode=${r.tls?"REQUIRED":"DISABLED"}`;return{type:r.type,command:i,secretRef:e.credentialRef}})}class js{store;queue;secrets;constructor(e,t,r){this.store=e;this.queue=t;this.secrets=r}async create(e){let t,r;if(e.provider!=="aws_elasticache"){let n=e.username??"app",i=Tg();r=`secret://data-services/${e.projectId}/${e.name}/${n}`,await this.secrets.put(r,i),t={username:n,password:i,secretRef:r}}try{let n=this.store.create({...e,credentialRef:r,status:"planning"});if(t)this.store.saveCredential(n.id,t.username,t.secretRef);let i=this.enqueue(n,"create",{});return{service:n,credential:t,operationId:i}}catch(n){if(r)await this.secrets.remove(r);throw n}}plan(e,t,r={}){let n=e.capabilities.actions[t],i=t==="version"&&String(r.engineVersion??"").split(".")[0]!==String(e.engineVersion??"").split(".")[0];return{service:e,action:t,capability:n,changes:r,preflight:{backupRequired:["delete","restore"].includes(t)||i,compatibilityRequired:i,typedConfirmation:n.destructive?e.name:void 0,retentionChoiceRequired:t==="delete"},warnings:[...n.downtime!=="none"?[`Downtime is ${n.downtime}.`]:[],...e.origin==="adopted"&&!e.managementEnabled?["Adopted resource is read-only until management is explicitly enabled."]:[]]}}enqueue(e,t,r,n){let i=this.plan(e,t,r);if(!i.capability.supported)throw Error(i.capability.explanation);if(e.origin==="adopted"&&!e.managementEnabled&&t!=="observe")throw Error("Adopted resources remain read-only until management is explicitly enabled.");if(i.preflight.typedConfirmation&&r.confirm!==i.preflight.typedConfirmation)throw Error(`Type ${i.preflight.typedConfirmation} to confirm ${t}.`);if(i.preflight.retentionChoiceRequired&&!["final_backup","retain"].includes(String(r.retention??"")))throw Error("Deletion requires retention final_backup or retain.");if(i.preflight.compatibilityRequired&&(r.compatibilityReviewed!==!0||!r.backupId))throw Error("Major version changes require compatibilityReviewed=true and a backupId.");if(t==="restore"){let o=String(r.backupId??""),s=String(r.targetId??"");if(!o||!s)throw Error("Restore requires both backupId and targetId.");if(s===e.placement)throw Error("Restore targetId must differ from the source placement.");if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(s))throw Error("Restore targetId must be 2-63 lowercase letters, numbers, or dashes.")}return this.queue.enqueue({projectId:e.projectId,environmentId:e.environmentId,resourceId:e.resourceId,actorId:n,kind:"data_service.action",input:{serviceId:e.id,action:t,...r},lockKey:`data-service:${e.id}`,providerKey:e.provider,maxAttempts:3,timeoutSeconds:7200,retryClasses:["provider_transient"],resumePolicy:"requeue"}).operation.id}async rotate(e,t,r){let n=this.store.credential(e.id);if(!n)throw Error("Data service credential metadata was not found.");let i=Tg(),o=`${n.secretRef}/v${n.version+1}`;await this.secrets.put(o,i);try{return await t.action(e,"rotate",{username:n.username,secretRef:o},i,r),this.store.saveCredential(e.id,n.username,o),this.store.update(e.id,e.version,{credentialRef:o}),{credential:{username:n.username,password:i,secretRef:o},dependencies:this.store.dependencies(e.id).filter((s)=>s.requiresRedeploy).map((s)=>s.resourceId)}}catch(s){throw await this.secrets.remove(o),s}}}function Dg(e){return{"data_service.action":async(t)=>{let r=t.operation.input,n=e.store.get(String(r.serviceId??"")),i=String(r.action??"");if(!n)throw Error("Data service was not found.");let o=e.resolveAdapter(n);if(!o||o.provider!==n.provider||!o.engines.includes(n.engine))throw Error(`No ${n.provider}/${n.engine} adapter is configured.`);if(i==="rotate"){let c=await new js(e.store,new $e(e.store.controlPlane),e.secrets).rotate(n,o,t);return{serviceId:n.id,action:i,username:c.credential.username,secretRef:c.credential.secretRef,dependencies:c.dependencies}}let s=n.credentialRef?await e.secrets.resolve(n.credentialRef):void 0;try{let c=i==="observe"?await o.observe(n):i==="create"?await o.apply(n,s,t):await o.action(n,i,r,s,t),d=e.store.get(n.id);return e.store.update(n.id,d.version,{observedState:c,status:i==="delete"?r.retention==="retain"?"retained":"deleting":"available"}),{serviceId:n.id,action:i,observed:c}}catch(c){let d=e.store.get(n.id);if(e.store.update(n.id,d.version,{status:"failed",observedState:{...d.observedState,error:c instanceof Error?c.message:String(c)}}),/temporar|timeout|unavailable|throttl/i.test(c instanceof Error?c.message:String(c)))throw new Ps(c instanceof Error?c.message:String(c),"provider_transient");throw c}}}}class ki{transport;constructor(e){this.transport=e}observe(e){return this.transport.observe(e.placement)}apply(e,t){return this.transport.apply({id:e.placement,name:e.name,engine:e.engine,engineVersion:e.engineVersion??null,plan:e.plan,storageGb:e.storageGb??null,highAvailability:e.highAvailability,publicExposure:e.publicExposure,allowedCidrs:e.allowedCidrs,username:e.desiredState.username??"app",desiredState:e.desiredState},t)}action(e,t,r,n,i){return this.transport.execute(e.placement,t,{engine:e.engine,engineVersion:e.engineVersion??null,plan:e.plan,desiredState:e.desiredState,...r},n,i)}}class vd extends ki{provider="aws_rds";engines=["postgres","mysql","mariadb"]}class bd extends ki{provider="aws_aurora";engines=["postgres","mysql"]}class Sd extends ki{provider="aws_elasticache";engines=["redis"]}class wd extends ki{provider="server";engines=["postgres","mysql","mariadb","redis","mongodb","libsql"]}class kd extends ki{provider="container";engines=["postgres","mysql","mariadb","redis","mongodb","libsql"]}var Fs=(e,t)=>{let r=e.desiredState;return e[t]??(r&&typeof r==="object"&&!Array.isArray(r)?r[t]:void 0)},qe=(e,t,r)=>{let n=Fs(e,t);return n==null?r:String(n)},Ot=(e,t)=>{let r=Fs(e,t);return r==null?void 0:Number(r)},dn=(e,t)=>{let r=Fs(e,t);return r==null?void 0:r===!0||r==="true"},Ii=(e,t)=>{let r=Fs(e,t);return Array.isArray(r)?r.map(String):[]},Bs=(e,t)=>qe(t,"snapshotId")??`${e}-final-${new Date().toISOString().replace(/[^0-9]/g,"").slice(0,14)}`;function Ms(e){if(!e)throw Error("RDS instance was not found.");return{providerId:e.DBInstanceIdentifier??null,status:e.DBInstanceStatus??"unknown",engine:e.Engine??null,engineVersion:e.EngineVersion??null,plan:e.DBInstanceClass??null,storageGb:e.AllocatedStorage??null,highAvailability:e.MultiAZ??!1,publicExposure:e.PubliclyAccessible??!1,endpoint:e.Endpoint?.Address??null,port:e.Endpoint?.Port??null,username:e.MasterUsername??null,database:e.DBName??null,encrypted:e.StorageEncrypted??!1}}class Ed{client;constructor(e=new Fn){this.client=e}async observe(e){return Ms(await this.client.describeDBInstance(e))}async apply(e,t){let r=String(e.id),n=await this.client.createDBInstance({DBInstanceIdentifier:r,DBInstanceClass:String(e.plan),Engine:String(e.engine),MasterUsername:qe(e,"username","app"),MasterUserPassword:t,DBName:qe(e,"database"),AllocatedStorage:Ot(e,"storageGb"),VpcSecurityGroupIds:Ii(e,"securityGroupIds"),DBSubnetGroupName:qe(e,"subnetGroup"),BackupRetentionPeriod:Ot(e,"backupRetentionDays")??7,MultiAZ:dn(e,"highAvailability"),EngineVersion:qe(e,"engineVersion"),PubliclyAccessible:dn(e,"publicExposure")??!1,StorageType:qe(e,"storageType","gp3"),StorageEncrypted:!0,KmsKeyId:qe(e,"kmsKeyId"),DeletionProtection:!0,Tags:[{Key:"managed-by",Value:"ts-cloud"}]});return Ms(n.DBInstance)}async execute(e,t,r,n,i){if(t==="observe")return this.observe(e);if(t==="restart")return await this.client.rebootDBInstance({DBInstanceIdentifier:e}),{status:"rebooting"};if(t==="backup"){let o=Bs(e,r);return await this.client.createDBSnapshot({DBInstanceIdentifier:e,DBSnapshotIdentifier:o}),{status:"snapshotting",snapshotId:o}}if(t==="restore"){let o=String(r.targetId),s=await this.client.restoreDBInstanceFromDBSnapshot({DBInstanceIdentifier:o,DBSnapshotIdentifier:String(r.backupId),DBInstanceClass:qe(r,"plan"),DBSubnetGroupName:qe(r,"subnetGroup"),MultiAZ:dn(r,"highAvailability"),PubliclyAccessible:!1,StorageType:qe(r,"storageType"),VpcSecurityGroupIds:Ii(r,"securityGroupIds"),DeletionProtection:!0,Tags:[{Key:"managed-by",Value:"ts-cloud"}]});return{...Ms(s.DBInstance),sourceId:e,restoreTargetId:o}}if(t==="delete"){if(r.retention==="retain")return{status:"retained"};let o=Bs(e,r);return await this.client.modifyDBInstance({DBInstanceIdentifier:e,DeletionProtection:!1,ApplyImmediately:!0}),await this.client.deleteDBInstance({DBInstanceIdentifier:e,SkipFinalSnapshot:!1,FinalDBSnapshotIdentifier:o,DeleteAutomatedBackups:!1}),{status:"deleting",finalSnapshotId:o}}if(["resize","version","rotate","expose"].includes(t)){let o=await this.client.modifyDBInstance({DBInstanceIdentifier:e,DBInstanceClass:qe(r,"plan"),AllocatedStorage:Ot(r,"storageGb"),MasterUserPassword:t==="rotate"?n:void 0,EngineVersion:qe(r,"engineVersion"),MultiAZ:dn(r,"highAvailability"),PubliclyAccessible:dn(r,"publicExposure"),VpcSecurityGroupIds:Ii(r,"securityGroupIds"),ApplyImmediately:dn(r,"applyImmediately")??!0});return Ms(o.DBInstance)}throw Error(`RDS action ${t} requires an engine connection runner.`)}}function Id(e){if(!e)throw Error("Aurora cluster was not found.");return{providerId:e.DBClusterIdentifier??null,status:e.Status??"unknown",engine:e.Engine??null,engineVersion:e.EngineVersion??null,endpoint:e.Endpoint??null,readerEndpoint:e.ReaderEndpoint??null,port:e.Port??null,username:e.MasterUsername??null,database:e.DatabaseName??null,encrypted:e.StorageEncrypted??!1,highAvailability:e.MultiAZ??!0}}class Rd{client;constructor(e=new Fn){this.client=e}async observe(e){let t=await this.client.describeDBClusters({DBClusterIdentifier:e});return Id(t.DBClusters?.[0])}async apply(e,t){let r=String(e.id),n=String(e.engine)==="postgres"?"aurora-postgresql":"aurora-mysql";return await this.client.createDBCluster({DBClusterIdentifier:r,Engine:n,EngineVersion:qe(e,"engineVersion"),MasterUsername:qe(e,"username","app"),MasterUserPassword:t,DatabaseName:qe(e,"database"),DBSubnetGroupName:qe(e,"subnetGroup"),VpcSecurityGroupIds:Ii(e,"securityGroupIds"),BackupRetentionPeriod:Ot(e,"backupRetentionDays")??7,StorageEncrypted:!0,KmsKeyId:qe(e,"kmsKeyId"),DeletionProtection:!0,ServerlessV2ScalingConfiguration:{MinCapacity:Ot(e,"minCapacity")??0.5,MaxCapacity:Ot(e,"maxCapacity")??4}}),await this.client.createDBInstance({DBInstanceIdentifier:`${r}-writer-1`,DBClusterIdentifier:r,DBInstanceClass:String(e.plan||"db.serverless"),Engine:n,PubliclyAccessible:dn(e,"publicExposure")??!1}),{status:"creating",providerId:r}}async execute(e,t,r,n){if(t==="observe")return this.observe(e);if(t==="restart")return await this.client.rebootDBCluster(e),{status:"rebooting"};if(t==="backup"){let i=Bs(e,r);return await this.client.createDBClusterSnapshot(e,i),{status:"snapshotting",snapshotId:i}}if(t==="restore"){let i=String(r.targetId),o=String(r.engine)==="postgres"?"aurora-postgresql":"aurora-mysql",s=await this.client.restoreDBClusterFromSnapshot({DBClusterIdentifier:i,SnapshotIdentifier:String(r.backupId),Engine:o,EngineVersion:qe(r,"engineVersion"),DBSubnetGroupName:qe(r,"subnetGroup"),VpcSecurityGroupIds:Ii(r,"securityGroupIds"),DeletionProtection:!0,ServerlessV2ScalingConfiguration:{MinCapacity:Ot(r,"minCapacity")??0.5,MaxCapacity:Ot(r,"maxCapacity")??4}});return await this.client.createDBInstance({DBInstanceIdentifier:`${i}-writer-1`,DBClusterIdentifier:i,DBInstanceClass:qe(r,"plan","db.serverless"),Engine:o,PubliclyAccessible:!1}),{...Id(s.DBCluster),sourceId:e,restoreTargetId:i}}if(t==="delete"){if(r.retention==="retain")return{status:"retained"};let i=Bs(e,r);return await this.client.modifyDBCluster({DBClusterIdentifier:e,DeletionProtection:!1,ApplyImmediately:!0}),await this.client.deleteDBCluster(e,i),{status:"deleting",finalSnapshotId:i}}if(["resize","version","rotate"].includes(t)){let i=await this.client.modifyDBCluster({DBClusterIdentifier:e,ServerlessV2ScalingConfiguration:Ot(r,"minCapacity")==null&&Ot(r,"maxCapacity")==null?void 0:{MinCapacity:Ot(r,"minCapacity")??0.5,MaxCapacity:Ot(r,"maxCapacity")??4},EngineVersion:qe(r,"engineVersion"),MasterUserPassword:t==="rotate"?n:void 0,ApplyImmediately:dn(r,"applyImmediately")??!0});return Id(i.DBCluster)}throw Error(`Aurora action ${t} requires an engine connection runner.`)}}class Ad{client;constructor(e=new Ls){this.client=e}async observe(e){let t=(await this.client.describeCacheClusters(e)).CacheClusters[0];if(!t)throw Error("ElastiCache cluster was not found.");let r=t.CacheNodes?.[0]?.Endpoint;return{providerId:t.CacheClusterId,status:t.CacheClusterStatus,engine:t.Engine,engineVersion:t.EngineVersion,plan:t.CacheNodeType,nodes:t.NumCacheNodes,endpoint:r?.Address??null,port:r?.Port??null}}async apply(e){let t=await this.client.createCacheCluster({cacheClusterId:String(e.id),engine:"redis",cacheNodeType:String(e.plan),numCacheNodes:Ot(e,"nodes")??1,engineVersion:qe(e,"engineVersion"),port:Ot(e,"port"),securityGroupIds:Ii(e,"securityGroupIds"),subnetGroupName:qe(e,"subnetGroup"),tags:[{Key:"managed-by",Value:"ts-cloud"}]});return{providerId:t.CacheCluster.CacheClusterId,status:t.CacheCluster.CacheClusterStatus}}async execute(e,t,r){if(t==="observe")return this.observe(e);if(t==="restart"){let n=(await this.client.describeCacheClusters(e)).CacheClusters[0];return await this.client.rebootCacheCluster(e,n?.CacheNodes?.map((i)=>i.CacheNodeId)??["0001"]),{status:"rebooting"}}if(t==="delete"){if(r.retention==="retain")return{status:"retained"};return await this.client.deleteCacheCluster(e),{status:"deleting"}}throw Error(`ElastiCache action ${t} is not supported by this cluster mode.`)}}import{mkdir as rI,writeFile as nI}from"node:fs/promises";import{join as iI}from"node:path";async function Lt(e,t,r=!1){let n=Bun.spawn(["docker",...e],{stdin:t==null?"ignore":"pipe",stdout:"pipe",stderr:"pipe"}),i=new Response(n.stdout).text(),o=new Response(n.stderr).text();if(t!=null)n.stdin.write(t),n.stdin.end();let[s,c,d]=await Promise.all([n.exited,i,o]);if(s!==0&&!r)throw Error(`Docker command failed (${s}): ${d.trim()||c.trim()}`);return{code:s,stdout:c,stderr:d}}class Og{async ensureNetwork(e){if((await Lt(["network","inspect",e],void 0,!0)).code!==0)await Lt(["network","create","--internal",e])}async seedSecret(e,t){await Lt(["volume","create",e]),await Lt(["run","--rm","-i","-v",`${e}:/run/target`,"alpine:3.21","sh","-c","umask 077; cat > /run/target/credential"],t)}async removeVolume(e){await Lt(["volume","rm",e],void 0,!0)}async inspect(e){let t=await Lt(["inspect",e],void 0,!0);if(t.code!==0)return;return JSON.parse(t.stdout)[0]}async run(e){await Lt(["run",...e])}async exec(e,t,r){return(await Lt(["exec","-i",e,...t],r)).stdout}async update(e,t){await Lt(["update",...t,e])}async restart(e){await Lt(["restart",e])}async remove(e){await Lt(["rm","--force",e],void 0,!0)}async logs(e,t){let r=await Lt(["logs","--tail",String(Math.min(2000,Math.max(1,t))),e],void 0,!0);return`${r.stdout}${r.stderr}`.slice(-262144)}async stats(e){let t=await Lt(["stats","--no-stream","--format","{{json .}}",e],void 0,!0);if(t.code!==0||!t.stdout.trim())return{};let r=JSON.parse(t.stdout.trim());return{cpuPercent:String(r.CPUPerc??""),memoryUsage:String(r.MemUsage??""),memoryPercent:String(r.MemPerc??""),networkIo:String(r.NetIO??""),blockIo:String(r.BlockIO??""),pids:Number(r.PIDs??0)}}}var oI={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 Pr(e,t="app"){let r=String(e??t);if(!/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(r))throw Error("Database identifiers must be letters, numbers, or underscores.");return r}function zn(e){if(!/^[a-z0-9][a-z0-9_.-]{1,62}$/i.test(e))throw Error("Runtime placement must be a valid container identifier.");return`tscloud-data-${e.toLowerCase()}`}function sI(e,t){let r=e.desiredState;return e[t]??(r&&typeof r==="object"&&!Array.isArray(r)?r[t]:void 0)}function bo(e){return e.Config?.Labels??{}}class Ei{runtime;backupRoot;constructor(e=new Og,t=yt(process.cwd(),"backups","data")){this.runtime=e;this.backupRoot=t}async observe(e){let t=zn(e),r=await this.runtime.inspect(t);if(!r)throw Error(`Data container ${t} was not found.`);let n=bo(r),i=await this.runtime.stats(t),o=r.NetworkSettings?.Ports??{},s=Object.values(o).flat().find(Boolean);return{providerId:t,status:r.State?.Status??"unknown",healthy:r.State?.Health?.Status??null,engine:n["ts-cloud.engine"]??null,engineVersion:n["ts-cloud.engine-version"]??null,username:n["ts-cloud.username"]??null,database:n["ts-cloud.database"]??null,endpoint:s?.HostIp||"127.0.0.1",port:s?.HostPort?Number(s.HostPort):null,image:r.Config?.Image??null,startedAt:r.State?.StartedAt??null,metrics:i}}async apply(e,t){let r=String(e.id),n=zn(r),i=String(e.engine);if(i==="libsql")throw Error("libSQL requires an explicitly configured runtime image.");let o=oI[i];if(!o)throw Error(`Unsupported runtime data engine ${i}.`);if(!t)throw Error(`${i} requires a managed credential.`);if(e.publicExposure===!0)throw Error("Container public exposure requires an external reviewed firewall policy; direct publishing is refused.");let s=Pr(e.username),c=Pr(sI(e,"database")),d=`${n}-secret`,a=`${n}-data`,u=i==="redis"?`appendonly yes
|
|
63
|
+
protected-mode yes
|
|
64
|
+
requirepass ${t.replaceAll("\\","\\\\").replaceAll(`
|
|
65
|
+
`,"")}
|
|
66
|
+
`:t;await this.runtime.ensureNetwork("ts-cloud-data"),await this.runtime.seedSecret(d,u);let m=["-d","--name",n,"--restart","unless-stopped","--network","ts-cloud-data","--label","managed-by=ts-cloud","--label",`ts-cloud.engine=${i}`,"--label",`ts-cloud.engine-version=${e.engineVersion??""}`,"--label",`ts-cloud.username=${s}`,"--label",`ts-cloud.database=${c}`,"-p",`127.0.0.1:${o.port}:${o.port}`,"-v",`${a}:${o.dataPath}`,"-v",`${d}:/run/ts-cloud-secrets:ro`];if(i==="postgres")m.push("-e",`POSTGRES_USER=${s}`,"-e",`POSTGRES_DB=${c}`,"-e","POSTGRES_PASSWORD_FILE=/run/ts-cloud-secrets/credential");if(i==="mysql"||i==="mariadb")m.push("-e",`MYSQL_USER=${s}`,"-e",`MYSQL_DATABASE=${c}`,"-e","MYSQL_PASSWORD_FILE=/run/ts-cloud-secrets/credential","-e","MYSQL_ROOT_PASSWORD_FILE=/run/ts-cloud-secrets/credential");if(i==="mongodb")m.push("-e",`MONGO_INITDB_ROOT_USERNAME=${s}`,"-e","MONGO_INITDB_ROOT_PASSWORD_FILE=/run/ts-cloud-secrets/credential");if(m.push(o.image),i==="redis")m.push("redis-server","/run/ts-cloud-secrets/credential");return await this.runtime.run(m),{providerId:n,status:"starting",engine:i,endpoint:"127.0.0.1",port:o.port,username:s,database:c}}async exportLogicalBackup(e){let t=zn(e),r=await this.runtime.inspect(t);if(!r)throw Error(`Data container ${t} was not found.`);let n=bo(r),i=n["ts-cloud.engine"],o=Pr(n["ts-cloud.username"]),s=Pr(n["ts-cloud.database"]),c;if(i==="postgres")c=await this.runtime.exec(t,["sh","-c",'export PGPASSWORD="$(cat /run/ts-cloud-secrets/credential)"; exec pg_dumpall --clean --if-exists -U "$POSTGRES_USER"']);else if(i==="mysql"||i==="mariadb")c=await this.runtime.exec(t,["sh","-c",'export MYSQL_PWD="$(cat /run/ts-cloud-secrets/credential)"; exec mysqldump -u root --all-databases --single-transaction --add-drop-database --routines --events --triggers']);else throw Error(`${i} does not support engine-native SQL backups.`);return{body:new TextEncoder().encode(c),engine:i,database:s,username:o,engineVersion:n["ts-cloud.engine-version"]||void 0}}async restoreLogicalBackup(e){let t=zn(e.sourceId),r=zn(e.targetId),n=await this.runtime.inspect(t);if(!n)throw Error(`Data container ${t} was not found.`);let i=bo(n),o=i["ts-cloud.engine"],s=Pr(i["ts-cloud.username"]),c=Pr(i["ts-cloud.database"]);if(!["postgres","mysql","mariadb"].includes(o))throw Error(`${o} does not support engine-native SQL restores.`);if(!e.inPlace){if(e.sourceId===e.targetId)throw Error("An isolated restore requires a distinct target identifier.");if(await this.runtime.inspect(r))throw Error(`Restore target ${r} already exists.`);await this.apply({id:e.targetId,engine:o,engineVersion:i["ts-cloud.engine-version"]??"",username:s,database:c,publicExposure:!1},e.credential)}let d=o==="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'],a=new TextDecoder("utf-8",{fatal:!0}).decode(e.body),u;for(let m=0;m<30;m++)try{await this.runtime.exec(r,d,a);let h=o==="postgres"?["sh","-c",'export PGPASSWORD="$(cat /run/ts-cloud-secrets/credential)"; exec psql -U "$POSTGRES_USER" -Atc "SELECT 1"']:["sh","-c",'export MYSQL_PWD="$(cat /run/ts-cloud-secrets/credential)"; exec mysql -u root -N -e "SELECT 1"'];if((await this.runtime.exec(r,h)).trim()!=="1")throw Error("Restored database health probe returned an unexpected result.");return{status:"available",providerId:r,engine:o,database:c,username:s,healthy:!0}}catch(h){if(u=h,m<29)await Bun.sleep(1000)}throw u instanceof Error?u:Error("Restored database did not become ready.")}async removeRestoredService(e){let t=zn(e);await this.runtime.remove(t),await this.runtime.removeVolume(`${t}-secret`),await this.runtime.removeVolume(`${t}-data`)}async backup(e,t){let r=await this.exportLogicalBackup(e),{engine:n,database:i,username:o}=r,s=String(t.snapshotId??`${e}-${new Date().toISOString().replace(/[^0-9]/g,"").slice(0,14)}`);if(!/^[A-Za-z0-9_.-]{2,120}$/.test(s))throw Error("Backup identifier contains unsupported characters.");await rI(this.backupRoot,{recursive:!0,mode:448});let c=iI(this.backupRoot,`${s}.sql`);return await nI(c,r.body,{mode:384}),{status:"available",backupId:s,path:c,engine:n,database:i,username:o}}async execute(e,t,r,n){let i=zn(e);if(t==="observe")return this.observe(e);if(t==="backup")return this.backup(e,r);if(t==="restart")return await this.runtime.restart(i),{status:"restarting"};if(t==="logs"||t==="slow_queries")return{logs:await this.runtime.logs(i,Number(r.lines)||500)};if(t==="databases"||t==="users"){let o=await this.runtime.inspect(i);if(!o)throw Error(`Data container ${i} was not found.`);let s=bo(o),c=s["ts-cloud.engine"],d=Pr(s["ts-cloud.username"]),a=String(r.operation??"list");if(!["postgres","mysql","mariadb"].includes(c))throw Error(`${t} is available only for SQL runtime engines.`);if(t==="users"&&a!=="list")throw Error("Creating users requires a referenced secondary credential.");if(a==="list"){let u=c==="postgres"?["sh","-c",`export PGPASSWORD="$(cat /run/ts-cloud-secrets/credential)"; exec psql -U "$POSTGRES_USER" -Atc '${t==="databases"?"SELECT datname FROM pg_database WHERE datistemplate = false ORDER BY datname":"SELECT usename FROM pg_user ORDER BY usename"}'`]:["sh","-c",`export MYSQL_PWD="$(cat /run/ts-cloud-secrets/credential)"; exec mysql -u root -N -e '${t==="databases"?"SHOW DATABASES":"SELECT User FROM mysql.user ORDER BY User"}'`],m=await this.runtime.exec(i,u);return{[t]:m.split(`
|
|
67
|
+
`).map((h)=>h.trim()).filter(Boolean)}}if(t==="databases"&&["create","delete"].includes(a)){let u=Pr(r.database);if(a==="delete"&&r.confirm!==u)throw Error(`Type ${u} to confirm logical database deletion.`);let m=c==="postgres"?`${a==="create"?"CREATE":"DROP"} DATABASE "${u}";
|
|
68
|
+
`:`${a==="create"?"CREATE":"DROP"} DATABASE \`${u}\`;
|
|
69
|
+
`,h=c==="postgres"?["sh","-c",'export PGPASSWORD="$(cat /run/ts-cloud-secrets/credential)"; exec psql -U "$POSTGRES_USER"']:["sh","-c",'export MYSQL_PWD="$(cat /run/ts-cloud-secrets/credential)"; exec mysql -u root'];return await this.runtime.exec(i,h,m),{status:"available",database:u,operation:a}}throw Error(`Unsupported ${t} operation ${a}.`)}if(t==="resize"){let o=[];if(r.memoryMb)o.push("--memory",`${Number(r.memoryMb)}m`);if(r.cpus)o.push("--cpus",String(Number(r.cpus)));if(!o.length)throw Error("Resize requires memoryMb or cpus.");return await this.runtime.update(i,o),{status:"running",memoryMb:r.memoryMb??null,cpus:r.cpus??null}}if(t==="rotate"){if(!n)throw Error("Credential rotation requires a generated secret.");let o=await this.runtime.inspect(i);if(!o)throw Error(`Data container ${i} was not found.`);let s=bo(o),c=s["ts-cloud.engine"],d=Pr(s["ts-cloud.username"]),a=n.replaceAll("'","''").replaceAll(`
|
|
70
|
+
`,"");if(c==="postgres")await this.runtime.exec(i,["sh","-c",'export PGPASSWORD="$(cat /run/ts-cloud-secrets/credential)"; exec psql -U "$POSTGRES_USER"'],`ALTER USER "${d}" PASSWORD '${a}';
|
|
71
|
+
`);else if(c==="mysql"||c==="mariadb")await this.runtime.exec(i,["sh","-c",'export MYSQL_PWD="$(cat /run/ts-cloud-secrets/credential)"; exec mysql -u root'],`ALTER USER '${d}'@'%' IDENTIFIED BY '${a}';
|
|
72
|
+
`);else if(c!=="redis")throw Error(`${c} credential rotation requires an engine runner.`);let u=c==="redis"?`appendonly yes
|
|
73
|
+
protected-mode yes
|
|
74
|
+
requirepass ${n.replaceAll("\\","\\\\").replaceAll(`
|
|
75
|
+
`,"")}
|
|
76
|
+
`:n;if(await this.runtime.seedSecret(`${i}-secret`,u),c==="redis")await this.runtime.restart(i);return{status:c==="redis"?"restarting":"running",username:d}}if(t==="delete"){if(r.retention==="retain")return{status:"retained"};let o=await this.backup(e,r);return await this.runtime.remove(i),await this.runtime.removeVolume(`${i}-secret`),await this.runtime.removeVolume(`${i}-data`),{status:"deleted",finalBackupId:o.backupId??null,backupPath:o.path??null}}if(t==="expose")throw Error("Direct container exposure is refused; use a reviewed firewall and proxy policy.");throw Error(`${t} requires a configured engine lifecycle runner.`)}}import{createCipheriv as aI,createDecipheriv as cI,createHash as $g,randomBytes as dI}from"node:crypto";class Cd{controlPlane;now;key;constructor(e,t,r=()=>new Date){this.controlPlane=e;this.now=r;if(!t)throw Error("Data-service encryption key is required.");this.key=$g("sha256").update(`ts-cloud:data-services:${t}`).digest()}encrypt(e){let t=dI(12),r=aI("aes-256-gcm",this.key,t),n=Buffer.concat([r.update(e,"utf8"),r.final()]);return`v1.${t.toString("base64url")}.${r.getAuthTag().toString("base64url")}.${n.toString("base64url")}`}decrypt(e){let[t,r,n,i]=e.split(".");if(t!=="v1"||!r||!n||!i)throw Error("Encrypted data-service secret is unavailable.");try{let o=cI("aes-256-gcm",this.key,Buffer.from(r,"base64url"));return o.setAuthTag(Buffer.from(n,"base64url")),Buffer.concat([o.update(Buffer.from(i,"base64url")),o.final()]).toString("utf8")}catch{throw Error("Encrypted data-service secret could not be decrypted.")}}async put(e,t){if(!/^secret:\/\/data-services\/[A-Za-z0-9._/-]+$/.test(e))throw Error("Invalid data-service secret reference.");if(!t)throw Error("Data-service secret cannot be empty.");let r=this.now().toISOString();this.controlPlane.database.run("INSERT INTO data_service_secrets (reference,ciphertext,fingerprint,created_at,updated_at) VALUES (?,?,?,?,?) ON CONFLICT(reference) DO UPDATE SET ciphertext=excluded.ciphertext,fingerprint=excluded.fingerprint,updated_at=excluded.updated_at",[e,this.encrypt(t),$g("sha256").update(t).digest("hex"),r,r])}async resolve(e){let t=this.controlPlane.database.query("SELECT ciphertext FROM data_service_secrets WHERE reference = ?").get(e);if(!t)throw Error("Data-service secret was not found.");return this.decrypt(t.ciphertext)}async remove(e){this.controlPlane.database.run("DELETE FROM data_service_secrets WHERE reference = ?",[e])}}import{existsSync as So}from"node:fs";import{mkdir as Us,readdir as lI,rename as Pd,rm as Ri}from"node:fs/promises";import{relative as uI,resolve as Rt,sep as qs}from"node:path";function Un(e,t){if(t==="gzip")return Buffer.from(Bun.gzipSync(Uint8Array.from(e)));if(t==="zstd")return Buffer.from(Bun.zstdCompressSync(Uint8Array.from(e)));return Buffer.from(e)}function _r(e,t){if(t==="gzip")return Buffer.from(Bun.gunzipSync(Uint8Array.from(e)));if(t==="zstd")return Buffer.from(Bun.zstdDecompressSync(Uint8Array.from(e)));return Buffer.from(e)}async function _d(e,t){let r=Bun.spawn(["tar",...e],{stdin:t?Buffer.from(t):void 0,stdout:"pipe",stderr:"pipe"}),[n,i,o]=await Promise.all([r.exited,new Response(r.stdout).arrayBuffer(),new Response(r.stderr).text()]);if(n!==0)throw Error(o.trim()||`tar exited with status ${n}.`);return{stdout:Buffer.from(i),stderr:o}}function pI(e){let t=e.replaceAll("\\","/").replace(/^\.\//,"");return!!t&&!t.startsWith("/")&&!t.split("/").includes("..")}class jg{async create(e,t,r){return(await _d(["-C",e,"-cf","-",...r.map((i)=>`--exclude=${i}`),"--",...t])).stdout}async extract(e,t){await Us(t,{recursive:!0,mode:448}),await _d(["-C",t,"-xf","-"],e)}async inspect(e){let t=await _d(["-tf","-"],e),r=t.stdout.toString().split(`
|
|
77
|
+
`).filter(Boolean);if(r.some((n)=>!pI(n)))throw Error("Backup archive contains an unsafe path.");return{entries:r,bytes:e.byteLength}}}function Ng(e,t){if(!t.trim())throw Error("File backup paths cannot be empty.");let r=Rt(e,t),n=uI(e,r);if(n===".."||n.startsWith(`..${qs}`)||n==="")throw Error(`File backup path ${t} is outside the project root.`);return n}function zs(e){let t=String(e.targetId??e.path??"");if(!/^[A-Za-z0-9][A-Za-z0-9_.-]{1,127}$/.test(t))throw Error("File restores require a safe target name.");return t}class Td{runtime;root;restoreRoot;constructor(e,t=new jg,r=yt(e,"restores","files")){this.runtime=t;this.root=Rt(e),this.restoreRoot=Rt(r)}paths(e){let t=[...new Set(e.includePatterns.map((r)=>Ng(this.root,r)))];if(!t.length)throw Error("File backup policies require at least one project-relative path.");for(let r of t)if(!So(Rt(this.root,r)))throw Error(`File backup path ${r} was not found.`);return t.filter((r)=>!t.some((n)=>n!==r&&r.startsWith(`${n}${qs}`)))}async create(e,t){let r=this.paths(e),n=await this.runtime.create(this.root,r,e.excludePatterns),i=await this.runtime.inspect(n),o=e.compression??"none",s=Un(n,o),c=String(t.operation?.id??new Date().toISOString()).replace(/[^A-Za-z0-9]/g,"").slice(0,32);return{mode:"object",key:`${e.projectId}/files/${c}.tar${o==="none"?"":o==="gzip"?".gz":".zst"}`,body:s,contentType:o==="gzip"?"application/gzip":o==="zstd"?"application/zstd":"application/x-tar",manifest:{archive:"tar",compression:o,sourcePaths:r,excluded:e.excludePatterns,entries:i.entries.length},toolVersion:"system-tar"}}async restore(e,t,r,n){if(!t)throw Error("File restore requires an archive payload.");let i=_r(t,String(e.manifest.compression??"none"));if(await this.runtime.inspect(i),r.restoreMode==="in_place"){let s=Rt(this.restoreRoot,`.staging-${zs(r)}`),c=Rt(this.restoreRoot,`.rollback-${zs(r)}`),d=Array.isArray(e.manifest.sourcePaths)?e.manifest.sourcePaths.map(String):[];if(!d.length)throw Error("File recovery point has no source path manifest.");await Ri(s,{recursive:!0,force:!0}),await Ri(c,{recursive:!0,force:!0}),await this.runtime.extract(i,s),await Us(c,{recursive:!0,mode:448});let a=[];try{for(let u of d){let m=Rt(this.root,Ng(this.root,u)),h=Rt(s,u),y=Rt(c,u);if(await Us(Rt(y,".."),{recursive:!0}),So(m))await Pd(m,y);await Us(Rt(m,".."),{recursive:!0}),await Pd(h,m),a.push(u)}}catch(u){for(let m of a.reverse()){let h=Rt(this.root,m),y=Rt(c,m);if(await Ri(h,{recursive:!0,force:!0}),So(y))await Pd(y,h)}throw u}finally{await Ri(s,{recursive:!0,force:!0})}return await Ri(c,{recursive:!0,force:!0}),{path:this.root,restoredPaths:d,inPlace:!0}}let o=Rt(this.restoreRoot,zs(r));if(So(o))throw Error("The isolated file restore target already exists.");return await this.runtime.extract(i,o),{path:o,isolated:!0}}async verify(e,t,r){let n=_r(t,String(e.manifest.compression??"none")),i=await this.runtime.inspect(n);return{archive:"tar",entries:i.entries.length,uncompressedBytes:i.bytes}}async validateHealth(e,t){let r=String(e.path??"");if(!r||!r.startsWith(`${this.restoreRoot}${qs}`)||!So(r))throw Error("Isolated file restore target was not found.");let n=await lI(r);return{healthy:!0,path:r,topLevelEntries:n.length}}async cleanup(e,t){let r=zs(e),n=Rt(this.restoreRoot,r);if(!n.startsWith(`${this.restoreRoot}${qs}`))throw Error("Refusing to clean a file restore outside the restore root.");await Ri(n,{recursive:!0,force:!0})}}class xd{services;secrets;transport;constructor(e,t,r=new Ei){this.services=e;this.secrets=t;this.transport=r}async create(e,t){if(!e.dataServiceId)throw Error("Logical database backups require a data service.");let r=this.services.get(e.dataServiceId);if(!r)throw Error("Logical database service was not found.");if(!["container","server"].includes(r.provider))throw Error("Logical database backups require an on-box data service.");let n=await this.transport.exportLogicalBackup(r.id),i=e.compression??"none",o=Un(n.body,i),s=String(t.operation?.id??new Date().toISOString()).replace(/[^A-Za-z0-9]/g,"").slice(0,32);return{mode:"object",key:`${e.projectId}/databases/${r.id}/${s}.sql${i==="none"?"":i==="gzip"?".gz":".zst"}`,body:o,contentType:i==="gzip"?"application/gzip":i==="zstd"?"application/zstd":"application/sql",engineVersion:n.engineVersion,toolVersion:"engine-native",manifest:{format:"logical-sql-v1",sourceDataServiceId:r.id,engine:n.engine,database:n.database,username:n.username,compression:i}}}async restore(e,t,r,n){if(!t)throw Error("Logical database backup body is unavailable.");let i=String(e.dataServiceId??e.manifest.sourceDataServiceId??""),o=String(r.dataServiceId??r.targetId??""),s=r.inPlace===!0;if(!i||!o)throw Error("Logical database restore requires source and target identifiers.");if(s&&o!==i)throw Error("An in-place restore must target the source data service.");let c=this.services.get(i);if(!c?.credentialRef)throw Error("Logical database credential reference was not found.");let d=await this.secrets.resolve(c.credentialRef);return this.transport.restoreLogicalBackup({sourceId:i,targetId:o,body:_r(t,String(e.manifest.compression??"none")),credential:d,inPlace:s})}async cleanup(e,t){if(e.inPlace===!0)throw Error("In-place database restores cannot be cleaned as drills.");let r=String(e.dataServiceId??e.targetId??"");if(!r)throw Error("Database cleanup requires a target identifier.");await this.transport.removeRestoredService(r)}}var Dd=/^[A-Za-z0-9][A-Za-z0-9_.-]{1,127}$/;async function qn(e,t,r=!1){let n=Bun.spawn(["docker",...e],{stdin:t?"pipe":"ignore",stdout:"pipe",stderr:"pipe"}),i=new Response(n.stdout).arrayBuffer(),o=new Response(n.stderr).text();if(t)n.stdin.write(t),n.stdin.end();let[s,c,d]=await Promise.all([n.exited,i,o]);if(s!==0&&!r)throw Error(`Docker volume command failed (${s}): ${d.trim()}`);return{code:s,stdout:Buffer.from(c),stderr:d}}class Mg{async exists(e){return(await qn(["volume","inspect",e],void 0,!0)).code===0}async export(e){return(await qn(["run","--rm","-v",`${e}:/source:ro`,"alpine:3.21","tar","-C","/source","-czf","-","."])).stdout}async import(e,t,r=!1){if(!await this.exists(e))await qn(["volume","create",e]);try{if(r)await qn(["run","--rm","-v",`${e}:/target`,"alpine:3.21","sh","-c","find /target -mindepth 1 -delete"]);await qn(["run","--rm","-i","-v",`${e}:/target`,"alpine:3.21","tar","-C","/target","--no-same-owner","-xzf","-"],t)}catch(n){throw await this.remove(e),n}}async remove(e){await qn(["volume","rm",e],void 0,!0)}async probe(e){let t=(await qn(["run","--rm","-v",`${e}:/target:ro`,"alpine:3.21","sh","-c",`find /target -mindepth 1 -printf '%s\\n' | awk '{n+=1;b+=$1} END {print n ":" b}'`])).stdout.toString(),[r,n]=t.trim().split(":").map(Number);if(!Number.isFinite(r)||!Number.isFinite(n))throw Error("Restored volume health probe returned invalid output.");return{entries:r,bytes:n}}}class Od{runtime;constructor(e=new Mg){this.runtime=e}async create(e,t){let r=String(e.includePatterns?.[0]??e.resourceId??"");if(!Dd.test(r))throw Error("Volume backups require a valid named-volume resource identifier.");if(!await this.runtime.exists(r))throw Error(`Volume ${r} was not found.`);let n=await this.runtime.export(r),i=Buffer.from(Bun.gunzipSync(Uint8Array.from(n))),o=e.compression??"gzip",s=o==="gzip"?n:Un(i,o),c=String(t.operation?.id??new Date().toISOString()).replace(/[^A-Za-z0-9]/g,"").slice(0,32);return{mode:"object",key:`${e.projectId}/volumes/${r}/${c}.tar${o==="none"?"":o==="gzip"?".gz":".zst"}`,body:s,contentType:o==="gzip"?"application/gzip":o==="zstd"?"application/zstd":"application/x-tar",toolVersion:"alpine-tar",manifest:{format:"docker-volume-tar-v1",archive:"tar",compression:o,sourceVolume:r}}}async restore(e,t,r,n){if(!t)throw Error("Volume backup body is unavailable.");let i=String(e.manifest.sourceVolume??e.resourceId??""),o=String(r.volumeName??r.targetId??"");if(!Dd.test(o))throw Error("Volume restore requires a valid target volume name.");if(o===i&&r.inPlace!==!0)throw Error("An isolated volume restore requires a distinct target.");let s=await this.runtime.exists(o);if(!r.inPlace&&s)throw Error(`Restore target volume ${o} already exists.`);if(r.inPlace===!0&&o!==i)throw Error("An in-place volume restore must target the source volume.");if(r.inPlace===!0&&!s)throw Error("The in-place target volume was not found.");let c=String(e.manifest.compression??"gzip"),d=c==="gzip"?Buffer.from(t):Buffer.from(Bun.gzipSync(Uint8Array.from(_r(t,c))));await this.runtime.import(o,d,r.inPlace===!0);let a=await this.runtime.probe(o);return{volumeName:o,healthy:!0,...a}}async cleanup(e,t){if(e.inPlace===!0)throw Error("In-place volume restores cannot be cleaned as drills.");let r=String(e.volumeName??e.targetId??"");if(!Dd.test(r))throw Error("Volume cleanup requires a valid target volume name.");await this.runtime.remove(r)}}import{existsSync as $d}from"node:fs";import{mkdir as mI,readFile as Bg,rm as gI,writeFile as Lg}from"node:fs/promises";import{basename as Vg,resolve as ln,sep as Fg}from"node:path";import{Database as fI}from"bun:sqlite";function zg(e){let t=String(e.targetId??e.path??"");if(!/^[A-Za-z0-9][A-Za-z0-9_.-]{1,127}$/.test(t))throw Error("Control-plane restores require a safe target name.");return t}function Ug(e){let t=JSON.parse(Buffer.from(e).toString());if(t.format!=="ts-cloud-control-plane-v1"||!t.database)throw Error("Control-plane backup archive is invalid.");if(!Array.isArray(t.config)||t.config.some((r)=>Vg(r.name)!==r.name))throw Error("Control-plane backup contains an unsafe config path.");return t}function qg(e){let t=fI.deserialize(Uint8Array.from(e));try{let r=t.query("PRAGMA integrity_check").get()?.integrity_check??"unknown",n=t.query("SELECT count(*) AS count FROM sqlite_master WHERE type='table'").get()?.count??0;if(r!=="ok")throw Error(`Restored control-plane integrity check failed: ${r}.`);return{integrity:r,tables:n}}finally{t.close()}}class Nd{controlPlane;root;restoreRoot;constructor(e,t,r=yt(t,"restores","control-plane")){this.controlPlane=e;this.root=ln(t),this.restoreRoot=ln(r)}async create(e,t){let r=e.includePatterns.length?e.includePatterns:["cloud.config.ts"],n=[];for(let d of r){let a=Vg(d),u=ln(this.root,a);if(a!==d&&d!==`./${a}`)throw Error("Control-plane config paths must be project-root files.");if($d(u))n.push({name:a,body:(await Bg(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:n},o=e.compression??"none",s=Un(Buffer.from(JSON.stringify(i)),o),c=String(t.operation?.id??i.createdAt).replace(/[^A-Za-z0-9]/g,"").slice(0,32);return{mode:"object",key:`${e.projectId}/control-plane/${c}.json${o==="none"?"":o==="gzip"?".gz":".zst"}`,body:s,contentType:o==="gzip"?"application/gzip":o==="zstd"?"application/zstd":"application/vnd.ts-cloud.control-plane+json",manifest:{format:i.format,configFiles:n.map((d)=>d.name),sensitive:!0,compression:o},toolVersion:"bun-sqlite-serialize"}}async restore(e,t,r,n){if(!t)throw Error("Control-plane restore requires an archive payload.");if(r.restoreMode==="in_place")throw Error("A live control plane can only be restored into an isolated recovery target.");let i=Ug(_r(t,String(e.manifest.compression??"none"))),o=ln(this.restoreRoot,zg(r));if($d(o))throw Error("The isolated control-plane restore target already exists.");await mI(o,{recursive:!0,mode:448}),await Lg(ln(o,"control-plane.sqlite"),Buffer.from(i.database,"base64"),{mode:384});for(let s of i.config)await Lg(ln(o,s.name),Buffer.from(s.body,"base64"),{mode:384});return{path:o,isolated:!0,configFiles:i.config.length}}async verify(e,t,r){let n=Ug(_r(t,String(e.manifest.compression??"none")));return{...qg(Buffer.from(n.database,"base64")),configFiles:n.config.length}}async validateHealth(e,t){let r=String(e.path??""),n=ln(r,"control-plane.sqlite");if(!r.startsWith(`${this.restoreRoot}${Fg}`)||!$d(n))throw Error("Isolated control-plane database was not found.");return{healthy:!0,...qg(await Bg(n))}}async cleanup(e,t){let r=ln(this.restoreRoot,zg(e));if(!r.startsWith(`${this.restoreRoot}${Fg}`))throw Error("Refusing to clean a control-plane restore outside the restore root.");await gI(r,{recursive:!0,force:!0})}}import{createHash as hI}from"node:crypto";function jd(e,t){return e.find((r)=>r.startsWith(`${t}:`))?.slice(t.length+1)}function yI(e){let t=jd(e.includePatterns,"resource")??e.includePatterns.find((i)=>i.startsWith("arn:")),r=jd(e.includePatterns,"role"),n=jd(e.includePatterns,"vault")??"Default";if(!t?.startsWith("arn:"))throw Error("Infrastructure backups require resource:<arn> in include patterns.");if(!r?.startsWith("arn:"))throw Error("Infrastructure backups require role:<iam-role-arn> in include patterns.");if(!/^[A-Za-z0-9_.-]{2,50}$/.test(n))throw Error("Infrastructure backup vault name is invalid.");return{resourceArn:t,roleArn:r,vaultName:n}}async function vI(e,t,r){for(;;){r.throwIfCancellationRequested(),r.heartbeat();let n=await e.describeBackupJob(t),i=String(n.State??"");if(r.checkpoint("provider_backup",`AWS Backup job ${t} is ${i||"pending"}.`),i==="COMPLETED"&&n.RecoveryPointArn)return{recoveryPointArn:n.RecoveryPointArn,sizeBytes:Number(n.BackupSizeInBytes??0)};if(["ABORTED","EXPIRED","FAILED"].includes(i))throw Error(`AWS Backup job ${t} failed: ${n.StatusMessage??i}.`);await Bun.sleep(5000)}}async function bI(e,t,r){for(;;){r.throwIfCancellationRequested(),r.heartbeat();let n=await e.describeRestoreJob(t),i=String(n.Status??"");if(r.checkpoint("provider_restore",`AWS Backup restore ${t} is ${i||"pending"}.`),i==="COMPLETED"&&n.CreatedResourceArn)return n.CreatedResourceArn;if(["ABORTED","FAILED"].includes(i))throw Error(`AWS Backup restore ${t} failed: ${n.StatusMessage??i}.`);await Bun.sleep(5000)}}class Md{client;constructor(e=new Vs){this.client=e}async create(e,t){let r=yI(e),n=String(t.operation.id).replace(/[^A-Za-z0-9-]/g,"").slice(0,64),i=await this.client.startBackupJob({BackupVaultName:r.vaultName,ResourceArn:r.resourceArn,IamRoleArn:r.roleArn,IdempotencyToken:n}),o=await vI(this.client,i.BackupJobId,t),s=`sha256:${hI("sha256").update(o.recoveryPointArn).digest("hex")}`;return{mode:"external",uri:o.recoveryPointArn,checksum:s,sizeBytes:o.sizeBytes,toolVersion:"aws-backup-api",manifest:{provider:"aws_backup",resourceArn:r.resourceArn,roleArn:r.roleArn,vaultName:r.vaultName,providerBackupJobId:i.BackupJobId,recoveryPointArn:o.recoveryPointArn}}}async verifyExternal(e,t){let r=String(e.manifest.providerBackupJobId??""),n=await this.client.describeBackupJob(r);if(n.State!=="COMPLETED"||n.RecoveryPointArn!==e.uri)throw Error(`AWS Backup recovery point verification failed: ${n.StatusMessage??n.State??"unknown"}.`);return{state:n.State,recoveryPointArn:n.RecoveryPointArn,sizeBytes:Number(n.BackupSizeInBytes??e.sizeBytes)}}async restore(e,t,r,n){if(r.inPlace===!0)throw Error("AWS Backup infrastructure restores must create isolated resources.");let i=String(r.roleArn??e.manifest.roleArn??""),o=r.metadata&&typeof r.metadata==="object"&&!Array.isArray(r.metadata)?Object.fromEntries(Object.entries(r.metadata).map(([d,a])=>[d,String(a)])):{};if(!i.startsWith("arn:"))throw Error("AWS Backup restore requires an IAM role ARN.");if(!Object.keys(o).length)throw Error("AWS Backup restore requires provider restore metadata.");let s=await this.client.startRestoreJob({RecoveryPointArn:e.uri,IamRoleArn:i,Metadata:o,IdempotencyToken:String(n.operation.id).replace(/[^A-Za-z0-9-]/g,"").slice(0,64)}),c=await bI(this.client,s.RestoreJobId,n);return{providerRestoreJobId:s.RestoreJobId,createdResourceArn:c,isolated:!0,healthy:!0}}async validateHealth(e,t){let r=String(e.createdResourceArn??"");return{healthy:r.startsWith("arn:"),createdResourceArn:r}}async deleteExternal(e,t){await this.client.deleteRecoveryPoint(String(e.manifest.vaultName??""),e.uri)}}import{existsSync as xR}from"node:fs";import{join as vh}from"node:path";import{pathToFileURL as DR}from"node:url";import{existsSync as Wg,statSync as Hg}from"fs";import{resolve as ko}from"path";import SI from"process";import{existsSync as II,mkdirSync as GO,readdirSync as QO,readFileSync as EI,writeFileSync as YO}from"fs";import{homedir as Ai}from"os";import{dirname as e$,resolve as gr}from"path";import Ia from"process";import{existsSync as Kg,statSync as Jg}from"fs";import{existsSync as nl,mkdirSync as RI,readdirSync as AI,writeFileSync as CI}from"fs";import{homedir as Ci}from"os";import{dirname as Gg,resolve as Ct}from"path";import Wn from"process";import{join as PI,relative as _I,resolve as Qg}from"path";import la from"process";import{existsSync as Mf,mkdirSync as l$,readdirSync as u$,writeFileSync as p$}from"fs";import{homedir as Bd}from"os";import{dirname as f$,resolve as At}from"path";import Eo from"process";import{join as TI,relative as xI,resolve as Yg}from"path";import ua from"process";import{existsSync as Bf,mkdirSync as S$,readdirSync as w$,writeFileSync as k$}from"fs";import{dirname as E$,resolve as pa}from"path";import il from"process";import{Buffer as un}from"buffer";import{createCipheriv as DI,createDecipheriv as OI,randomBytes as Ld}from"crypto";import{closeSync as Fd,createReadStream as Zg,createWriteStream as $I,existsSync as zd,fsyncSync as Xg,openSync as ef,writeFileSync as NI}from"fs";import{access as jI,constants as tf,mkdir as MI,readdir as Ws,rename as rf,stat as Pi,unlink as Hs,writeFile as Ud}from"fs/promises";import{join as _i}from"path";import lt from"process";import{pipeline as BI}from"stream/promises";import{createGzip as nf}from"zlib";import Ti from"process";import Dr from"process";import{Buffer as Tr}from"buffer";import{createCipheriv as LI,createDecipheriv as FI,randomBytes as qd}from"crypto";import{closeSync as Vd,createReadStream as of,createWriteStream as zI,existsSync as Ks,fsyncSync as sf,openSync as af,writeFileSync as UI}from"fs";import{access as qI,constants as cf,mkdir as VI,readdir as Js,rename as df,stat as xi,unlink as Gs,writeFile as Wd}from"fs/promises";import{isAbsolute as WI,join as Di,resolve as HI}from"path";import we from"process";import{pipeline as KI}from"stream/promises";import{createGzip as lf}from"zlib";import Oi from"process";import Or from"process";import Qs from"process";import{existsSync as Ys}from"fs";import{resolve as Hd}from"path";import{existsSync as JI}from"fs";import{existsSync as GI,readdirSync as QI}from"fs";import{extname as Kd,resolve as uf}from"path";import YI from"process";import{join as ZI,relative as XI,resolve as pf}from"path";import ma from"process";import{Buffer as xr}from"buffer";import{createCipheriv as eE,createDecipheriv as tE,randomBytes as Jd}from"crypto";import{closeSync as Gd,createReadStream as mf,createWriteStream as rE,existsSync as Zs,fsyncSync as gf,openSync as ff,writeFileSync as nE}from"fs";import{access as iE,constants as hf,mkdir as oE,readdir as Xs,rename as yf,stat as $i,unlink as ea,writeFile as Qd}from"fs/promises";import{isAbsolute as sE,join as Ni,resolve as aE}from"path";import ke from"process";import{pipeline as cE}from"stream/promises";import{createGzip as vf}from"zlib";import ji from"process";import $r from"process";import ra from"process";import{existsSync as na}from"fs";import{resolve as Df}from"path";import{existsSync as PR}from"fs";class Of{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),o=n??this.options.ttl,s=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:o,hits:0,size:s}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!Wg(e))return!0;return Hg(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,n){try{let i=Wg(r)?Hg(r):null,o=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:o},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class $f{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let o=await t(),s=performance.now()-n;return this.recordMetric({operation:e,duration:s,timestamp:i,...r}),o}catch(o){let s=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:s,timestamp:i,...r}),o}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,o)=>i+o,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}var da=new Of,fl=new $f;var Nf=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function jf(e={}){let{name:t="",alias:r}=e,n=["config",".config"];if(t)n.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let i=r===void 0?[]:Array.isArray(r)?r:[r];for(let o of i){if(!o)continue;if(n.push(o,`.${o}.config`,`${o}.config`,`.${o}`),t)n.push(`${t}.${o}.config`,`.${t}.${o}.config`)}return Array.from(new Set(n.filter(Boolean)))}function wI(e){return jf(e).flatMap((r)=>Nf.map((n)=>ko(e.directory,`${r}${n}`)))}function kI(e={}){let t=ko(e.cwd||SI.cwd());return Array.from(new Set([t,ko(t,"config"),ko(t,".config"),e.configDir?ko(t,e.configDir):void 0].filter((r)=>Boolean(r))))}var dE=Object.defineProperty,lE=(e)=>e;function uE(e,t){this[e]=lE.bind(null,t)}var pE=(e,t)=>{for(var r in t)dE(e,r,{get:t[r],enumerable:!0,configurable:!0,set:uE.bind(t,r)})},mE=(e,t)=>()=>(e&&(t=e(e=0)),t),Lf={};pE(Lf,{withErrorRecovery:()=>Uf,tryLoadConfig:()=>jE,loadConfigWithResult:()=>$E,loadConfig:()=>Kf,isRetryableError:()=>PE,isConfigNotFoundError:()=>CE,isBunfigError:()=>qf,globalPerformanceMonitor:()=>Co,globalCache:()=>Mi,getEnvOrDefault:()=>_E,generateConfigTypes:()=>ME,defaultGeneratedDir:()=>th,defaultConfigDir:()=>eh,deepMergeWithArrayStrategy:()=>Sl,deepMerge:()=>Vf,createLibraryConfig:()=>BE,config:()=>NE,bunfigPlugin:()=>LE,applyEnvVarsToConfig:()=>Io,TypeGenerationError:()=>ul,SchemaValidationError:()=>Ao,PluginError:()=>ml,PerformanceMonitor:()=>yl,FileSystemError:()=>ll,ErrorFactory:()=>pn,EnvVarError:()=>ba,EnvProcessor:()=>Ea,ConfigValidator:()=>wl,ConfigValidationError:()=>cl,ConfigNotFoundError:()=>va,ConfigMergeError:()=>dl,ConfigLoader:()=>kl,ConfigLoadError:()=>Ro,ConfigFileLoader:()=>Ra,ConfigCache:()=>hl,CacheUtils:()=>Gf,BunfigError:()=>Ft,BrowserConfigError:()=>pl,ArrayMergeStrategies:()=>Zf});class hl{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),o=n??this.options.ttl,s=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:o,hits:0,size:s}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!Kg(e))return!0;return Jg(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,n){try{let i=Kg(r)?Jg(r):null,o=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:o},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class yl{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let o=await t(),s=performance.now()-n;return this.recordMetric({operation:e,duration:s,timestamp:i,...r}),o}catch(o){let s=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:s,timestamp:i,...r}),o}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,o)=>i+o,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function gE(e,t={}){let n=Object.keys(t).sort().map((i)=>`${i}:${t[i]}`).join("|");return n?`${e}:${n}`:e}function fE(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function hE(e){return e.getStats().size*2}function vl(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Fe(t[0])&&"id"in t[0]&&t[0].id===3&&Fe(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Fe(t)&&Fe(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(Fe(e)&&"arr"in e&&Array.isArray(e.arr)&&Fe(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Fe(t[0])&&Fe(e[0])){let n=[...t];for(let i of e)if(Fe(i)&&"name"in i){if(!n.find((s)=>Fe(s)&&("name"in s)&&s.name===i.name))n.push(i)}else if(Fe(i)&&"path"in i){if(!n.find((s)=>Fe(s)&&("path"in s)&&s.path===i.path))n.push(i)}else if(!n.some((o)=>ga(o,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!Fe(t)||!Fe(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(Fe(i)&&Fe(r[n]))r[n]=vl(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&Fe(i[0])&&Fe(r[n][0])){let o=[...i];for(let s of r[n])if(Fe(s)&&"name"in s){if(!o.find((d)=>Fe(d)&&("name"in d)&&d.name===s.name))o.push(s)}else if(Fe(s)&&"path"in s){if(!o.find((d)=>Fe(d)&&("path"in d)&&d.path===s.path))o.push(s)}else if(!o.some((c)=>ga(c,s)))o.push(s);r[n]=o}else if(i.every((o)=>typeof o==="string")&&r[n].every((o)=>typeof o==="string")){let o=[...i];for(let s of r[n])if(!o.includes(s))o.push(s);r[n]=o}else r[n]=i;else r[n]=i}return r}function ga(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!ga(e[r],t[r]))return!1;return!0}if(Fe(e)&&Fe(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!ga(e[i],t[i]))return!1}return!0}return!1}function Fe(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function yE(e,t){if(!Bf(e))return null;try{let r=await import(e),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return vl(t,n)}catch{return null}}catch{return null}}async function vE({name:e="",cwd:t,defaultConfig:r}){let n=t||il.cwd(),i=[".ts",".js",".mjs",".cjs",".json"],o=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let s of o)for(let c of i){let d=pa(n,`${s}${c}`),a=await yE(d,r);if(a!==null)return a}try{let s=pa(n,"package.json");if(Bf(s)){let d=(await import(s))[e];if(d&&typeof d==="object"&&!Array.isArray(d))try{return vl(r,d)}catch{}}}catch{}return r}function bE(e,t={}){let r=ua.cwd();while(r.includes("storage"))r=Yg(r,"..");let n=Yg(r,e||"");if(t?.relative)return xI(ua.cwd(),n);return n}async function SE(){try{let e=await vE({name:"clarity",defaultConfig:oa,cwd:ua.cwd(),endpoint:"",headers:{}});return{...oa,...e}}catch{return oa}}function We(){if(Dr.env.NODE_ENV==="test"||Dr.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function wE(){if(Dr.env.NODE_ENV==="test"||Dr.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Dr<"u"){let e=Dr.type;if(e==="renderer"||e==="worker")return!1;return!!(Dr.versions&&(Dr.versions.node||Dr.versions.bun))}return!1}class Ff{async format(e){let t=await wE(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Ti.pid,hostname:t(),environment:Ti.env.NODE_ENV||"development",platform:Ti.platform,version:Ti.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Ti.env.NODE_ENV||Ti.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class fa{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...sl},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Ff,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??lt.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),o=this.generateKey();this.currentKeyId=i,this.keys.set(i,o),this.encryptionKeys.set(i,{key:o,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...sa,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...sa};return{...sa,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:sl.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let r=(async()=>{let i,o=0,s=3,c=1000;while(o<s)try{try{try{await jI(this.config.logDirectory,tf.F_OK|tf.W_OK)}catch(a){if(a instanceof Error&&"code"in a)if(a.code==="ENOENT")await MI(this.config.logDirectory,{recursive:!0,mode:493});else if(a.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw a;else throw a}}catch(a){throw console.error("Debug: [writeToFile] Failed to create log directory:",a),a}let d=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:un.from(e);try{if(!zd(this.currentLogFile))await Ud(this.currentLogFile,"",{mode:420});if(i=ef(this.currentLogFile,"a",420),NI(i,d,{flag:"a"}),Xg(i),i!==void 0)Fd(i),i=void 0;if((await Pi(this.currentLogFile)).size===0){if(await Ud(this.currentLogFile,d,{flag:"w",mode:420}),(await Pi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(a){let u=a;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(o<s-1){let m=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${o+1}/${s}:`,m);let h=c*2**o;await new Promise((y)=>setTimeout(y,h)),o++;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{Fd(i)}catch(a){console.error("Debug: [writeToFile] Error closing file descriptor:",a)}}}catch(d){if(o===s-1){let u=d,m=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",m),d}o++;let a=c*2**(o-1);await new Promise((u)=>setTimeout(u,a))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return _i(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return _i(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return _i(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(We())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,c],[,d])=>d.createdAt.getTime()-c.createdAt.getTime()),o=typeof t.maxKeys==="number"?t.maxKeys:1,s=Math.max(1,o);if(i.length>s)for(let[c]of i.slice(s))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return Ld(16).toString("hex")}generateKey(){return Ld(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=Ld(16),n=DI("aes-256-gcm",t,r),i=un.concat([n.update(e,"utf8"),n.final()]),o=n.getAuthTag();return{encrypted:un.concat([r,i,o]),iv:r}}async compressData(e){return new Promise((t,r)=>{let n=nf(),i=[];n.on("data",(o)=>i.push(o)),n.on("end",()=>t(un.from(un.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(We())return;let e=await Pi(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await Ws(this.config.logDirectory),o=i.filter((d)=>d.startsWith(this.name)&&/\.log\.\d+$/.test(d)).sort((d,a)=>{let u=Number.parseInt(d.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),s=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await Pi(r).catch(()=>null))try{if(await rf(r,c),t.compress)try{let d=`${c}.gz`;await this.compressLogFile(c,d),await Hs(c)}catch(d){console.error("Error compressing rotated file:",d)}if(o.length===0&&!i.some((d)=>d.endsWith(".log.1")))try{let d=`${r}.1`;await Ud(d,"")}catch(d){console.error("Error creating backup file:",d)}}catch(d){console.error(`Error during rotation: ${d instanceof Error?d.message:String(d)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),o=r.replace(/\.log$/,`-${i}.log`);if(await Pi(r).catch(()=>null))await rf(r,o)}if(this.currentLogFile=n,t.maxFiles){let o=(await Ws(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,c)=>c.localeCompare(s));for(let s of o.slice(t.maxFiles))await Hs(_i(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=Zg(e),n=$I(t),i=nf();await BI(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),zd(this.currentLogFile))try{let e=ef(this.currentLogFile,"r+");Xg(e),Fd(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!We()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Ws(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Hs(_i(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?Ne.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:o,showTimestamp:s=!0}=e,c=(y)=>y.replace(this.ANSI_PATTERN,"");if(!this.fancy){let y=[];if(s)y.push(t);if(o==="warning")y.push("WARN");else if(o==="error")y.push("ERROR");else if(r)y.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)y.push(n.replace(/[[\]]/g,""));return y.push(i),y.join(" ")}let d=lt.stdout.columns||120,a="";if(o==="warning"||o==="error")a=`${r} ${i}`;else if(o==="info"||o==="success")a=`${r} ${n} ${i}`;else a=`${r} ${n} ${Ne.cyan(i)}`;if(!s)return a.trim();let u=c(a).trim().length,m=c(t).length,h=Math.max(1,d-2-u-m);return`${a.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(o,s)=>{let c=Number.parseInt(s,10);return c<t[0].length?String(t[0][c]):o});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(o,s)=>{if(s==="%")return"%";if(n>=t.length)return o;let c=t[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return o}});if(n<t.length)i+=` ${t.slice(n).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return i}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),o=this.formatFileTimestamp(n),s,c;if(t instanceof Error)s=t.message,c=t.stack;else s=this.formatMessage(t,r);if(this.fancy&&!We()){let a=Qf[e],u=this.options.showTags!==!1&&this.name?Ne.gray(this.formatTag(this.name)):"",m;switch(e){case"debug":m=this.formatConsoleMessage({timestamp:i,icon:a,tag:u,message:Ne.gray(s),level:e}),console.error(m);break;case"info":m=this.formatConsoleMessage({timestamp:i,icon:a,tag:u,message:s,level:e}),console.error(m);break;case"success":m=this.formatConsoleMessage({timestamp:i,icon:a,tag:u,message:Ne.green(s),level:e}),console.error(m);break;case"warning":m=this.formatConsoleMessage({timestamp:i,icon:a,tag:u,message:s,level:e}),console.warn(m);break;case"error":if(m=this.formatConsoleMessage({timestamp:i,icon:a,tag:u,message:s,level:e}),console.error(m),c){let h=c.split(`
|
|
78
|
+
`);for(let y of h)if(y.trim()&&!y.includes(s))console.error(this.formatConsoleMessage({timestamp:i,message:Ne.gray(` ${y}`),level:e,showTimestamp:!1}))}break}}else if(!We()){if(console.error(`${o} ${this.environment}.${e.toUpperCase()}: ${s}`),c)console.error(c)}if(!this.shouldLog(e))return;let d=`${o} ${this.environment}.${e.toUpperCase()}: ${s}
|
|
79
|
+
`;if(c)d+=`${c}
|
|
80
|
+
`;d=d.replace(this.ANSI_PATTERN,""),await this.writeToFile(d)}time(e){let t=performance.now();if(this.fancy&&!We()){let r=this.options.showTags!==!1&&this.name?Ne.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:Ne.blue("◐"),tag:r,message:`${Ne.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),o=`${e} completed in ${i}ms`,s=new Date,c=this.formatConsoleTimestamp(s),a=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${o}`;if(r)a+=` ${JSON.stringify(r)}`;if(a+=`
|
|
81
|
+
`,a=a.replace(this.ANSI_PATTERN,""),this.fancy&&!We()){let u=this.options.showTags!==!1&&this.name?Ne.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:Ne.green("✓"),tag:u,message:`${o}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!We())console.error(a.trim());await this.writeToFile(a)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new fa(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(We())throw Error("createReadStream is not supported in browser environments");if(!zd(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Zg(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=un.isBuffer(e)?e:un.from(e,"base64"),i=n.slice(0,16),o=n.slice(-16),s=n.slice(16,-16),c=OI("aes-256-gcm",r,i);return c.setAuthTag(o),un.concat([c.update(s),c.final()]).toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return We()}isServerMode(){return!We()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t);if(this.fancy&&!We()){let o=e.split(`
|
|
82
|
+
`),s=Math.max(...o.map((u)=>u.length))+2,c=`┌${"─".repeat(s)}┐`,d=`└${"─".repeat(s)}┘`,a=o.map((u)=>{let m=" ".repeat(s-u.length-2);return`│ ${u}${m} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:Ne.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:Ne.cyan(c)})),a.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:r,message:Ne.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:Ne.cyan(d),showTimestamp:!1}))}else if(!We())console.error(`${n} ${this.environment}.INFO: [BOX] ${e}`);let i=`${n} ${this.environment}.INFO: [BOX] ${e}
|
|
83
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}async prompt(e){if(We())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${Ne.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();lt.stdin.removeListener("data",r);try{if(typeof lt.stdin.setRawMode==="function")lt.stdin.setRawMode(!1)}catch{}lt.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof lt.stdin.setRawMode==="function")lt.stdin.setRawMode(!0)}catch{}lt.stdin.resume(),lt.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let s=/%([sdijfo%])/g,c=0;if(r=e.replace(s,(d,a)=>{if(a==="%")return"%";if(c>=t.length)return d;let u=t[c++];switch(a){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 d}}),c<t.length)r+=` ${t.slice(c).map((d)=>typeof d==="object"?JSON.stringify(d,null,2):String(d)).join(" ")}`}if(this.fancy&&!We()){let s=this.options.showTags!==!1&&this.name?Ne.gray(this.formatTag(this.name)):"",c=Ne.blue("◐");console.error(`${c} ${s} ${Ne.cyan(r)}`)}let o=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
|
|
84
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(o)}progress(e,t=""){if(!this.enabled||!this.fancy||We()||e<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let r=20;return this.activeProgressBar={total:e,current:0,message:t,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(s,c)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||We())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,s)),c!==void 0)this.activeProgressBar.message=c;let d=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,d)},finish:(s)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||We())return;if(this.activeProgressBar.current=this.activeProgressBar.total,s!==void 0)this.activeProgressBar.message=s;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(s,c="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||We())return;lt.stdout.write(`${"\r".padEnd(lt.stdout.columns||80)}\r`),this.log(c,s),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(e,t=!1){if(!this.enabled||!this.fancy||We()||!lt.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,o=Ne.green("━".repeat(n)),s=Ne.gray("━".repeat(i)),c=`[${o}${s}]`,d=`${r}%`.padStart(4),a=e.message?` ${e.message}`:"",u=t||r===100?Ne.green("✓"):Ne.blue("▶"),m=this.options.showTags!==!1&&this.name?` ${Ne.gray(this.formatTag(this.name))}`:"",h=`\r${u}${m} ${c} ${d}${a}`,y=lt.stdout.columns||80,w=" ".repeat(Math.max(0,y-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${w}`,lt.stdout.write(e.lastRenderedLine),t)lt.stdout.write(`
|
|
85
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||We()||!lt.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(We()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Ws(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let o=_i(this.config.logDirectory,n);if(e.before)try{if((await Pi(o)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${o}:`,s);continue}r.push(o)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Hs(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function ia(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&_e(t[0])&&"id"in t[0]&&t[0].id===3&&_e(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(_e(t)&&_e(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(_e(e)&&"arr"in e&&Array.isArray(e.arr)&&_e(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&_e(t[0])&&_e(e[0])){let n=[...t];for(let i of e)if(_e(i)&&"name"in i){if(!n.find((s)=>_e(s)&&("name"in s)&&s.name===i.name))n.push(i)}else if(_e(i)&&"path"in i){if(!n.find((s)=>_e(s)&&("path"in s)&&s.path===i.path))n.push(i)}else if(!n.some((o)=>ha(o,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!_e(t)||!_e(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(_e(i)&&_e(r[n]))r[n]=ia(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&_e(i[0])&&_e(r[n][0])){let o=[...i];for(let s of r[n])if(_e(s)&&"name"in s){if(!o.find((d)=>_e(d)&&("name"in d)&&d.name===s.name))o.push(s)}else if(_e(s)&&"path"in s){if(!o.find((d)=>_e(d)&&("path"in d)&&d.path===s.path))o.push(s)}else if(!o.some((c)=>ha(c,s)))o.push(s);r[n]=o}else if(i.every((o)=>typeof o==="string")&&r[n].every((o)=>typeof o==="string")){let o=[...i];for(let s of r[n])if(!o.includes(s))o.push(s);r[n]=o}else r[n]=i;else r[n]=i}return r}function bl(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:ia(e,t);if(Array.isArray(e))return r==="replace"?t:ia(e,t);if(!_e(t)||!_e(e))return t;let n={...e};for(let i of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,i))continue;let o=t[i],s=n[i];if(o===null||o===void 0)continue;if(Array.isArray(o)||Array.isArray(s))if(r==="replace")n[i]=o;else n[i]=ia(s,o);else if(_e(o)&&_e(s))n[i]=bl(s,o,r);else n[i]=o}return n}function ha(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!ha(e[r],t[r]))return!1;return!0}if(_e(e)&&_e(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!ha(e[i],t[i]))return!1}return!0}return!1}function _e(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function ta(e,t,r="replace"){if(!Mf(e))return null;try{let n=await import(e),i=n.default||n;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return bl(t,i,r)}catch{return null}}catch{return null}}function kE(e,t,r=!1){if(!e)return t;let n=e.toUpperCase().replace(/-/g,"_"),i={...t};function o(s,c=[]){let d={...s};for(let[a,u]of Object.entries(s)){let m=[...c,a],h=(k)=>k.replace(/([A-Z])/g,"_$1").toUpperCase(),y=`${n}_${m.map(h).join("_")}`,w=`${n}_${m.map((k)=>k.toUpperCase()).join("_")}`;if(r)pt.info(`Checking environment variable ${y} for config ${e}.${m.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))d[a]=o(u,m);else{let k=Eo.env[y]||Eo.env[w];if(k!==void 0){if(r)pt.info(`Using environment variable ${k?y:w} for config ${e}.${m.join(".")}`);if(typeof u==="number")d[a]=Number(k);else if(typeof u==="boolean")d[a]=k.toLowerCase()==="true";else if(Array.isArray(u))try{let C=JSON.parse(k);if(Array.isArray(C))d[a]=C;else d[a]=k.split(",").map((T)=>T.trim())}catch{d[a]=k.split(",").map((C)=>C.trim())}else d[a]=k}}}return d}return o(i)}async function IE({name:e="",alias:t,cwd:r,configDir:n,defaultConfig:i,verbose:o=!1,checkEnv:s=!0,arrayStrategy:c="replace"}){let d=s&&typeof i==="object"&&i!==null&&!Array.isArray(i)?kE(e,i,o):i,a=r||Eo.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(o)pt.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${a}`);let m=[e,`.${e}`].filter(Boolean),h=[`${e}.config`,`.${e}.config`].filter(Boolean),y=t?[t,`.${t}`]:[],w=t?[`${t}.config`,`.${t}.config`]:[],k=Array.from(new Set([a,At(a,"config"),At(a,".config"),n?At(a,n):void 0].filter(Boolean)));for(let C of k){if(o)pt.info(`Searching for configuration in: ${C}`);let j=[At(a,"config"),At(a,".config")].concat(n?[At(a,n)]:[]).includes(C)?[...m,...h,...y,...w]:[...h,...m,...w,...y];for(let P of j)for(let O of u){let U=At(C,`${P}${O}`),q=await ta(U,d,c);if(q!==null){if(o)pt.success(`Configuration loaded from: ${U}`);return q}}}if(e){let C=At(Bd(),".config",e),T=["config",`${e}.config`];if(t)T.push(`${t}.config`);if(o)pt.info(`Checking user config directory: ${C}`);for(let j of T)for(let P of u){let O=At(C,`${j}${P}`),U=await ta(O,d,c);if(U!==null){if(o)pt.success(`Configuration loaded from user config directory: ${O}`);return U}}}if(e){let C=At(Bd(),".config"),T=[`.${e}.config`];if(t)T.push(`.${t}.config`);if(o)pt.info(`Checking user config directory for dotfile configs: ${C}`);for(let j of T)for(let P of u){let O=At(C,`${j}${P}`),U=await ta(O,d,c);if(U!==null){if(o)pt.success(`Configuration loaded from user config directory dotfile: ${O}`);return U}}}if(e){let C=Bd(),T=[`.${e}.config`,`.${e}`];if(t)T.push(`.${t}.config`),T.push(`.${t}`);if(o)pt.info(`Checking user home directory for dotfile configs: ${C}`);for(let j of T)for(let P of u){let O=At(C,`${j}${P}`),U=await ta(O,d,c);if(U!==null){if(o)pt.success(`Configuration loaded from user home directory: ${O}`);return U}}}try{let C=At(a,"package.json");if(Mf(C)){let T=await import(C),j=T[e];if(!j&&t){if(j=T[t],j&&o)pt.success(`Using alias "${t}" configuration from package.json`)}if(j&&typeof j==="object"&&!Array.isArray(j))try{if(o)pt.success(`Configuration loaded from package.json: ${j===T[e]?e:t}`);return bl(d,j,c)}catch(P){if(o)pt.warn("Failed to merge package.json config:",P)}}}catch(C){if(o)pt.warn("Failed to load package.json:",C)}if(o)pt.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return d}function EE(e,t={}){let r=la.cwd();while(r.includes("storage"))r=Qg(r,"..");let n=Qg(r,e||"");if(t?.relative)return _I(la.cwd(),n);return n}async function RE(){try{let e=await IE({name:"clarity",alias:"logging",defaultConfig:aa,cwd:la.cwd()});return{...aa,...e||{}}}catch{return aa}}function Ze(){if(Or.env.NODE_ENV==="test"||Or.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function AE(){if(Or.env.NODE_ENV==="test"||Or.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Or<"u"){let e=Or.type;if(e==="renderer"||e==="worker")return!1;return!!(Or.versions&&(Or.versions.node||Or.versions.bun))}return!1}class zf{async format(e){let t=await AE(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Oi.pid,hostname:t(),environment:Oi.env.NODE_ENV||"development",platform:Oi.platform,version:Oi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Oi.env.NODE_ENV||Oi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class ya{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...al},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new zf,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??we.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),o=this.generateKey();this.currentKeyId=i,this.keys.set(i,o),this.encryptionKeys.set(i,{key:o,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...ca,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...ca};return{...ca,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:al.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!Ze()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let i,o=0,s=3,c=1000;while(o<s)try{try{try{await qI(this.config.logDirectory,cf.F_OK|cf.W_OK)}catch(a){if(a instanceof Error&&"code"in a)if(a.code==="ENOENT")await VI(this.config.logDirectory,{recursive:!0,mode:493});else if(a.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw a;else throw a}}catch(a){throw console.error("Debug: [writeToFile] Failed to create log directory:",a),a}let d=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Tr.from(e);try{if(!Ks(this.currentLogFile))await Wd(this.currentLogFile,"",{mode:420});if(i=af(this.currentLogFile,"a",420),UI(i,d,{flag:"a"}),sf(i),i!==void 0)Vd(i),i=void 0;if((await xi(this.currentLogFile)).size===0){if(await Wd(this.currentLogFile,d,{flag:"w",mode:420}),(await xi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(a){let u=a;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(o<s-1){let m=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${o+1}/${s}:`,m);let h=c*2**o;await new Promise((y)=>setTimeout(y,h)),o++;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{Vd(i)}catch(a){console.error("Debug: [writeToFile] Error closing file descriptor:",a)}}}catch(d){if(o===s-1){let u=d,m=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",m),d}o++;let a=c*2**(o-1);await new Promise((u)=>setTimeout(u,a))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Di(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 Di(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Di(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Ze())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,c],[,d])=>d.createdAt.getTime()-c.createdAt.getTime()),o=typeof t.maxKeys==="number"?t.maxKeys:1,s=Math.max(1,o);if(i.length>s)for(let[c]of i.slice(s))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return qd(16).toString("hex")}generateKey(){return qd(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=qd(16),n=LI("aes-256-gcm",t,r),i=Tr.isBuffer(e)?e:Tr.from(e,"utf8"),o=n.update(i),s=n.final(),c=o.length+s.length,d=n.getAuthTag(),a=Tr.allocUnsafe(16+c+16);return r.copy(a,0),o.copy(a,16),s.copy(a,16+o.length),d.copy(a,16+c),{encrypted:a,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=lf(),i=[];n.on("data",(o)=>i.push(o)),n.on("end",()=>t(Tr.from(Tr.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(Ze())return;if(!this.shouldWriteToFile())return;let e=await xi(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await Js(this.config.logDirectory),o=i.filter((d)=>d.startsWith(this.name)&&/\.log\.\d+$/.test(d)).sort((d,a)=>{let u=Number.parseInt(d.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),s=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await xi(r).catch(()=>null))try{if(await df(r,c),t.compress)try{let d=`${c}.gz`;await this.compressLogFile(c,d),await Gs(c)}catch(d){console.error("Error compressing rotated file:",d)}if(o.length===0&&!i.some((d)=>d.endsWith(".log.1")))try{let d=`${r}.1`;await Wd(d,"")}catch(d){console.error("Error creating backup file:",d)}}catch(d){console.error(`Error during rotation: ${d instanceof Error?d.message:String(d)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),o=r.replace(/\.log$/,`-${i}.log`);if(await xi(r).catch(()=>null))await df(r,o)}if(this.currentLogFile=n,t.maxFiles){let o=(await Js(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,c)=>c.localeCompare(s));for(let s of o.slice(t.maxFiles))await Gs(Di(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=of(e),n=zI(t),i=lf();await KI(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Ks(this.currentLogFile))try{let e=af(this.currentLogFile,"r+");sf(e),Vd(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!Ze()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Js(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Gs(Di(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?Ee.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Ze())return!1;let e=typeof we.env.NO_COLOR<"u",t=we.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof we.stderr<"u"&&we.stderr.isTTY||typeof we.stdout<"u"&&we.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:o,showTimestamp:s=!0}=e,c=(y)=>y.replace(this.ANSI_PATTERN,"");if(!this.fancy){let y=[];if(s)y.push(t);if(o==="warning")y.push("WARN");else if(o==="error")y.push("ERROR");else if(r)y.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)y.push(n.replace(/[[\]]/g,""));return y.push(i),y.join(" ")}let d=we.stdout.columns||120,a="";if(o==="warning"||o==="error")a=`${r} ${i}`;else if(o==="info"||o==="success")a=`${r} ${n} ${i}`;else a=`${r} ${n} ${Ee.cyan(i)}`;if(!s)return a.trim();let u=c(a).trim().length,m=c(t).length,h=Math.max(1,d-2-u-m);return`${a.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(o,s)=>{let c=Number.parseInt(s,10);return c<t[0].length?String(t[0][c]):o});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(o,s)=>{if(s==="%")return"%";if(n>=t.length)return o;let c=t[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return o}});if(n<t.length)i+=` ${t.slice(n).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let o=Ee.underline(Ee.blue(n)),s=this.toAbsoluteFilePath(i);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(s)}`,d="\x1B]8;;",a="\x1B\\";return`\x1B]8;;${c}\x1B\\${o}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${o}\x1B]8;;\x1B\\`;return o}),t=t.replace(/`([^`]+)`/g,(r,n)=>Ee.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>Ee.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>Ee.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>Ee.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>Ee.strikethrough(n)),t}supportsHyperlinks(){if(Ze())return!1;let e=we.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=we.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(WI(t)||t.startsWith("./")||t.startsWith("../"))t=HI(t);else return null;return Ks(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),o=this.formatFileTimestamp(n),s,c;if(t instanceof Error)s=t.message,c=t.stack;else s=this.formatMessage(t,r);let{consoleText:d,fileText:a}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let m=this.options.showIcons===!1?"":Yf[e],h=this.options.showTags!==!1&&this.name?Ee.gray(this.formatTag(this.name)):"",y;switch(e){case"debug":y=this.formatConsoleMessage({timestamp:i,icon:m,tag:h,message:Ee.gray(d),level:e}),console.error(y);break;case"info":y=this.formatConsoleMessage({timestamp:i,icon:m,tag:h,message:d,level:e}),console.warn(y);break;case"success":y=this.formatConsoleMessage({timestamp:i,icon:m,tag:h,message:Ee.green(d),level:e}),console.error(y);break;case"warning":y=this.formatConsoleMessage({timestamp:i,icon:m,tag:h,message:d,level:e}),console.warn(y);break;case"error":if(y=this.formatConsoleMessage({timestamp:i,icon:m,tag:h,message:d,level:e}),console.error(y),c){let w=c.split(`
|
|
86
|
+
`);for(let k of w)if(k.trim()&&!k.includes(s))console.error(this.formatConsoleMessage({timestamp:i,message:Ee.gray(` ${k}`),level:e,showTimestamp:!1}))}break}}else if(!Ze()){if(console.error(`${o} ${this.environment}.${e.toUpperCase()}: ${s}`),c)console.error(c)}if(!this.shouldLog(e))return;let u=`${o} ${this.environment}.${e.toUpperCase()}: ${a}
|
|
87
|
+
`;if(c)u+=`${c}
|
|
88
|
+
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(c,d)=>{},finish:(c)=>{},interrupt:(c,d)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!Ze()&&we.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,d)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),d!==void 0)this.activeProgressBar.message=d;if(this.shouldStyleConsole()&&!Ze()&&we.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,d="info")=>{if(!Ze()&&we.stdout.isTTY)we.stdout.write(`
|
|
89
|
+
`);if(this[d==="warning"?"warn":d](c),this.activeProgressBar&&this.shouldStyleConsole()&&!Ze()&&we.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?Ee.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":Ee.blue("◐"),tag:r,message:`${Ee.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),o=`${e} completed in ${i}ms`,s=new Date,c=this.formatConsoleTimestamp(s),a=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${o}`;if(r)a+=` ${JSON.stringify(r)}`;if(a+=`
|
|
90
|
+
`,a=a.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?Ee.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":Ee.green("✓"),tag:u,message:`${o}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Ze())console.error(a.trim());if(this.shouldWriteToFile())await this.writeToFile(a)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new ya(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(Ze())throw Error("createReadStream is not supported in browser environments");if(!Ks(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return of(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=Tr.isBuffer(e)?e:Tr.from(e,"base64"),i=n.subarray(0,16),o=n.subarray(n.length-16),s=n.subarray(16,n.length-16),c=FI("aes-256-gcm",r,i);c.setAuthTag(o);let d=c.update(s),a=c.final(),u=d.length+a.length,m=Tr.allocUnsafe(u);return d.copy(m,0),a.copy(m,d.length),m.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Ze()}isServerMode(){return!Ze()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:i,fileText:o}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=i.split(`
|
|
91
|
+
`),d=Math.max(...c.map((h)=>h.length))+2,a=`┌${"─".repeat(d)}┐`,u=`└${"─".repeat(d)}┘`,m=c.map((h)=>this.formatConsoleMessage({timestamp:r,message:Ee.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:Ee.cyan(a),showTimestamp:!1})),m.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:Ee.cyan(u),showTimestamp:!1}))}else if(!Ze())console.error(`${n} ${this.environment}.INFO: [BOX] ${o}`);let s=`${n} ${this.environment}.INFO: [BOX] ${o}
|
|
92
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(e){if(Ze())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${Ee.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();we.stdin.removeListener("data",r);try{if(typeof we.stdin.setRawMode==="function")we.stdin.setRawMode(!1)}catch{}we.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof we.stdin.setRawMode==="function")we.stdin.setRawMode(!0)}catch{}we.stdin.resume(),we.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let d=/%([sdijfo%])/g,a=0;if(r=e.replace(d,(u,m)=>{if(m==="%")return"%";if(a>=t.length)return u;let h=t[a++];switch(m){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return u}}),a<t.length)r+=` ${t.slice(a).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let d=this.options.showTags!==!1&&this.name?Ee.gray(this.formatTag(this.name)):"",a=this.options.showIcons===!1?"":`${Ee.blue("◐")} `;console.error(`${a}${d} ${Ee.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
|
|
93
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!we.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,o=Ee.green("━".repeat(n)),s=Ee.gray("━".repeat(i)),c=`[${o}${s}]`,d=`${r}%`.padStart(4),a=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?Ee.green("✓"):Ee.blue("▶"),m=this.options.showTags!==!1&&this.name?` ${Ee.gray(this.formatTag(this.name))}`:"",h=`\r${u}${m} ${c} ${d}${a}`,y=we.stdout.columns||80,w=" ".repeat(Math.max(0,y-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${w}`,we.stdout.write(e.lastRenderedLine),t)we.stdout.write(`
|
|
94
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Ze()||!we.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(Ze()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Js(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let o=Di(this.config.logDirectory,n);if(e.before)try{if((await xi(o)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${o}:`,s);continue}r.push(o)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Gs(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function Uf(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:o}=t,s=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await e()}catch(d){if(s=d instanceof Error?d:Error(String(d)),c===r||!i(s))break;if(n>0)await new Promise((a)=>setTimeout(a,n))}if(o!==void 0)return o;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}function qf(e){return e instanceof Ft}function CE(e){return e instanceof va}function PE(e){if(qf(e))return e.code==="FILE_SYSTEM_ERROR"||e.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((r)=>e.message.toLowerCase().includes(r.toLowerCase()))}class Ea{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:n,useCamelCase:i=!0,useBackwardCompatibility:o=!0,customParsers:s={},verbose:c=!1,trackPerformance:d=!0}=r,a=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=n||this.generateEnvPrefix(e),m={...t};return this.processObject(m,[],u,{useCamelCase:i,useBackwardCompatibility:o,customParsers:s,verbose:c,configName:e}),{config:m,source:{type:"environment",priority:50,timestamp:new Date}}};if(d)return Co.track("applyEnvironmentVariables",a,{configName:e});return a()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,n){for(let[i,o]of Object.entries(e)){let s=[...t,i],c=s.map((u)=>this.formatEnvKey(u,n.useCamelCase)),d=`${r}_${c.join("_")}`,a=n.useBackwardCompatibility?`${r}_${s.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.processObject(o,s,r,n);else{let u=Qs.env[d]||(a?Qs.env[a]:void 0);if(u!==void 0){if(n.verbose){let m=Qs.env[d]?d:a}try{e[i]=this.parseEnvironmentValue(u,typeof o,d,n.customParsers,n.configName)}catch(m){if(m instanceof ba)throw m;throw pn.envVar(d,u,typeof o,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[o,s]of Object.entries(n))try{return s(e)}catch{continue}for(let o of this.defaultParsers)if(o.canParse(e,t))try{return o.parse(e)}catch{throw pn.envVar(r,e,`${t} (via ${o.name} parser)`,i)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,i]of Object.entries(Qs.env))if(n.startsWith(r)&&i!==void 0)t[n]=i;return t}validateEnvironmentVariable(e,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))n.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(i){n.push(`Cannot parse value "${t}" as ${r}: ${i}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(e,t,r={}){let{prefix:n,format:i="text"}=r,o=n||this.generateEnvPrefix(e),s=[];switch(this.extractEnvVarInfo(t,[],o,s),i){case"markdown":return this.formatAsMarkdown(s,e);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,e)}}extractEnvVarInfo(e,t,r,n){for(let[i,o]of Object.entries(e)){let s=[...t,i],c=`${r}_${s.map((d)=>this.formatEnvKey(d,!0)).join("_")}`;if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.extractEnvVarInfo(o,s,r,n);else n.push({key:c,type:Array.isArray(o)?"array":typeof o,description:`Configuration for ${s.join(".")}`,example:this.generateExample(o)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
|
|
95
|
+
|
|
96
|
+
`;for(let n of e)r+=`${n.key}
|
|
97
|
+
`,r+=` Type: ${n.type}
|
|
98
|
+
`,r+=` Description: ${n.description}
|
|
99
|
+
`,r+=` Example: ${n.example}
|
|
100
|
+
|
|
101
|
+
`;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
|
|
102
|
+
|
|
103
|
+
`;r+=`| Variable | Type | Description | Example |
|
|
104
|
+
`,r+=`|----------|------|-------------|----------|
|
|
105
|
+
`;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
106
|
+
`;return r}}function _E(e,t){let r=Jf("process");if(typeof r>"u"||!r.env)return t;let n=r.env[e];return n!==void 0?n:t}function Vf(e,t,r={}){return Wf(e,t,r,new WeakMap)}function Wf(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:o=!1,customMerger:s}=r;if(t===null||t===void 0)return o?e:t;if(s){let c=s(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return Hf(e,t,i,n);if(!Wt(t)||!Wt(e))return t;return OE(e,t,r,n)}function Hf(e,t,r,n){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return TE(e,t);case"smart":return xE(e,t,n);default:return t}return t}function TE(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>ol(i,n)))r.push(n);return r}function xE(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(Wt(t[0])&&Wt(e[0]))return DE(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}function DE(e,t,r){let n=[...t];for(let i of e){if(!Wt(i)){n.push(i);continue}let o=["id","name","key","path","type"],s=!1;for(let c of o)if(c in i){if(n.find((a)=>Wt(a)&&(c in a)&&a[c]===i[c])){s=!0;break}}if(!s)n.push(i)}return n}function OE(e,t,r,n){let i=t;if(Wt(i)&&n.has(i))return n.get(i);let o={...e};if(Wt(i))n.set(i,o);for(let s in i){if(!Object.prototype.hasOwnProperty.call(i,s))continue;let c=i[s],d=o[s];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){o[s]=c;continue}if(Wt(c)&&Wt(d))o[s]=Wf(d,c,r,n);else if(Array.isArray(c)||Array.isArray(d))o[s]=Hf(d,c,r.arrayMergeMode||"smart",n);else o[s]=c}return o}function Sl(e,t,r="replace"){return Vf(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function ol(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!ol(e[r],t[r]))return!1;return!0}if(Wt(e)&&Wt(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!ol(e[i],t[i]))return!1}return!0}return!1}function Wt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Ra{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:o,trackPerformance:s=!0,verbose:c=!1}=r;if(i){let a=Mi.getWithFileCheck("file",e);if(a){if(c)console.log(`Configuration loaded from cache: ${e}`);return a}}let d=async()=>{if(!Ys(e))return null;try{let a=`?t=${Date.now()}`,u=await import(e+a),m=u.default||u,h="default"in u,y=Object.keys(u).length>0;if(!h&&!y)throw new Ro(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof m!=="object"||m===null||Array.isArray(m))throw new Ro(e,Error("Configuration must export a valid object"),"unknown");let C={config:Sl(t,m,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)Mi.setWithFileCheck("file",C,e,o);return C}catch(a){throw a instanceof Error?pn.configLoad(e,a):pn.configLoad(e,Error(String(a)))}};if(s)return Co.track("loadFromPath",d,{path:e});return d()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let o of n)for(let s of this.extensions)i.push(Hd(t,`${o}${s}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return Uf(async()=>Ys(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!Ys(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let o of i)for(let s of this.extensions){let c=Hd(e,`${o}${s}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:i}=await import("fs"),o=i(e);for(let s of o)if(this.looksLikeConfigFile(s)){let c=Hd(e,s);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(e))}async validateConfigFile(e){let t=[];try{if(!Ys(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),o=i(e,"utf8");JSON.parse(o)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}class wl{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:o=!0,customRules:s=[],trackPerformance:c=!0,verbose:d=!1}=r,a=async()=>{let u=[],m=[],h={stopOnFirstError:n,validateRequired:i,validateTypes:o,customRules:s,trackPerformance:c,verbose:d};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...s],h);else return this.validateWithJSONSchema(e,t,h)}catch(y){return u.push({path:"",message:`Validation failed: ${y}`,rule:"system"}),{isValid:!1,errors:u,warnings:m}}};if(c)return await Co.track("validateConfiguration",a);return a()}async validateWithSchemaFile(e,t,r){try{if(!JI(t))throw new Ao(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),i=n.default||n;if(Array.isArray(i))return this.validateWithRules(e,i,r);else return this.validateWithJSONSchema(e,i,r)}catch(n){throw new Ao(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,o){if(o.validateTypes&&t.type){let s=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(s)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${s}`,expected:c.join(" or "),actual:s,rule:"type"}),o.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),o.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let s=0;s<e.length;s++){let c=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(e[s],t.items,c,n,i,o),o.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let s=e;if(o.validateRequired&&t.required){for(let c of t.required)if(!(c in s)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),o.stopOnFirstError)return}}if(t.properties){for(let[c,d]of Object.entries(t.properties))if(c in s){let a=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(s[c],d,a,n,i,o),o.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let d of Object.keys(s))if(!c.has(d))i.push({path:r?`${r}.${d}`:d,message:`Additional property '${d}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let o of t)try{let s=this.getValueByPath(e,o.path),c=this.validateWithRule(s,o,o.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:o.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,o,s]=n;t.push({path:i,required:!o,type:this.mapTypeScriptType(s)})}return t}mapTypeScriptType(e){switch(e.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:Xf},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class kl{fileLoader=new Ra;envProcessor=new Ea;validator=new wl;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:o,...s}=e;try{if(r?.enabled){let d=this.checkCache(s.name||"",s);if(d)return d}let c;try{c=await this.loadConfigurationStrategies(s,!0,r)}catch(d){let a=s.__strictErrorHandling;if(d instanceof Error&&d.name==="ConfigNotFoundError"){if(a)throw d;c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(d instanceof Error&&d.name==="ConfigLoadError"){let u=d.message.includes("EACCES")||d.message.includes("EPERM")||d.message.includes("permission denied"),m=!u&&(d.message.includes("syntax")||d.message.includes("Expected")||d.message.includes("Unexpected")||d.message.includes("BuildMessage")||d.message.includes("errors building")),h=d.message.includes("Configuration must export a valid object")||d.message.includes("Configuration file is empty and exports nothing");if(a&&(h||u))throw d;if(m&&(!a||!h))c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!a)c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${d.message}`]};else throw d}else c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${d instanceof Error?d.message:String(d)}`]}}if(i||o)await this.validateConfiguration(c.config,i,o,s.name);if(r?.enabled&&c)this.cacheResult(s.name||"",c,r,s);if(n?.enabled){let d={operation:"loadConfig",duration:Date.now()-t,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(d);if(n.slowThreshold&&d.duration>n.slowThreshold)tr.warn(`Slow configuration loading detected: ${d.duration}ms for ${s.name}`);c.metrics=d}return c}catch(c){let d=Date.now()-t;throw tr.error(`Configuration loading failed after ${d}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:o,configDir:s,defaultConfig:c,checkEnv:d=!0,arrayStrategy:a="replace",verbose:u=!1}=e,m=o||Wn.cwd(),h=[],y=await this.loadLocalConfiguration(n,i,m,s,c,a,u,d,r);if(y)return h.push(...this.getLocalSearchPaths(n,i,m,s)),this.finalizeResult(y,h,d,n,u);let w=await this.loadHomeConfiguration(n,i,c,a,u,d);if(w)return h.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(w,h,d,n,u);let k=await this.loadPackageJsonConfiguration(n,i,m,c,a,u,d);if(k)return h.push(Ct(m,"package.json")),this.finalizeResult(k,h,d,n,u);if(h.push(...this.getAllSearchPaths(n,i,m,s)),t)throw pn.configNotFound(n,h,i);return{...await this.applyEnvironmentVariables(n,c,d,u),warnings:[`No configuration file found for "${n}"${i?` or alias "${i}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,o,s,c,d){let a=c?Io(e,i,s):i,u=this.getLocalDirectories(r,n);for(let m of u){if(s)tr.info(`Searching for configuration in: ${m}`);let h=this.fileLoader.generateConfigPaths(e,m,t),y=await this.fileLoader.tryLoadFromPaths(h,a,{arrayStrategy:o,verbose:s,cacheTtl:d?.ttl,useCache:!d?.ttl||d.ttl>100});if(y){if(s)tr.success(`Configuration loaded from: ${y.source.path}`);return y}}return null}async loadHomeConfiguration(e,t,r,n,i,o){if(!e)return null;let s=o?Io(e,r,i):r,c=[Ct(Ci(),".config",e),Ct(Ci(),".config"),Ci()];for(let d of c){if(i)tr.info(`Checking home directory: ${d}`);let a=this.fileLoader.generateConfigPaths(e,d,t),u=await this.fileLoader.tryLoadFromPaths(a,s,{arrayStrategy:n,verbose:i});if(u){if(i)tr.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,o,s){let c=s?Io(e,n,o):n;try{let d=Ct(r,"package.json");if(!nl(d))return null;let a=await import(d),u=a[e],m=e;if(!u&&t)u=a[t],m=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(o)tr.success(`Configuration loaded from package.json: ${m}`);return{config:Sl(c,u,i),source:{type:"package.json",path:d,priority:30,timestamp:new Date}}}}catch(d){if(o)tr.warn("Failed to load package.json:",[d instanceof Error?d:Error(String(d))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Io(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let o=r(e);if(o)i.push(...o)}if(t){let o=await this.validator.validateConfiguration(e,t);if(!o.isValid)i.push(...o.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(i.length>0)throw pn.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return Mi.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);Mi.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,Ct(e,"config"),Ct(e,".config"),t?Ct(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(Ct(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),o=[];for(let s of i)o.push(...this.fileLoader.generateConfigPaths(e,s,t));return o}getHomeSearchPaths(e,t){if(!e)return[];let r=[Ct(Ci(),".config",e),Ct(Ci(),".config"),Ci()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function bf(e){let r=!(e.message.includes("EACCES")||e.message.includes("EPERM")||e.message.includes("permission denied"))&&(e.message.includes("syntax")||e.message.includes("Expected")||e.message.includes("Unexpected")||e.message.includes("BuildMessage")),n=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return r||n}async function $E(e){return Nr.loadConfig({...e,__strictErrorHandling:!0})}async function Kf(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let n;if(r)n=await Nr.loadConfig(e);else n=await Nr.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let i=n instanceof Error?n.name:"UnknownError",o=n instanceof Error?n.message:String(n);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||o.includes("config"))&&e.verbose)tr.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let c=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await Nr.applyEnvironmentVariables(c.name||"",t,!0,c.verbose||!1))?.config??t;return t}}async function NE(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await Nr.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&bf(r)))return(await Nr.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await Nr.loadConfig({...e,cwd:e.cwd||Wn.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&bf(t)))return(await Nr.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function jE(e,t,r="replace"){let n=new Ra;try{let i=await n.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return i?i.config:null}catch{return null}}function Io(e,t,r=!1){let n=new Ea,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function o(s,c=[]){let d={...s};for(let[a,u]of Object.entries(s)){let m=[...c,a],h=[`${i}_${m.join("_").toUpperCase()}`,`${i}_${m.map((k)=>k.toUpperCase()).join("")}`,`${i}_${m.map((k)=>k.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],y,w;for(let k of h)if(y=Wn.env[k],y!==void 0){w=k;break}if(y!==void 0&&w)if(typeof u==="boolean")d[a]=["true","1","yes"].includes(y.toLowerCase());else if(typeof u==="number"){let k=Number(y);if(!Number.isNaN(k))d[a]=k}else if(Array.isArray(u))try{d[a]=JSON.parse(y)}catch{d[a]=y.split(",").map((k)=>k.trim())}else d[a]=y;else if(u&&typeof u==="object"&&!Array.isArray(u))d[a]=o(u,m)}return d}return o(t)}function ME(e){let t=Ct(Wn.cwd(),e.configDir),r=Ct(Wn.cwd(),e.generatedDir),n=Ct(r,"config-types.ts");if(!nl(Gg(n)))RI(Gg(n),{recursive:!0,mode:511});let i=nl(t)?AI(t).map((s)=>s.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],o=`// Generated by bunfig v${pR}
|
|
107
|
+
export type ConfigNames = ${i.length?`'${i.join("' | '")}'`:"string"}
|
|
108
|
+
`;CI(n,o,{mode:438})}function BE(e){let t=null,r=null,n=()=>{if(!r)r=Kf(e).then((o)=>(t=o,o),(o)=>{let s="defaultConfig"in e?e.defaultConfig:{};if(t=s,"verbose"in e&&e.verbose)tr.warn("Config loading failed, using defaults:",[o instanceof Error?o:Error(String(o))]);return s});return r},i="defaultConfig"in e?e.defaultConfig:{};return t=i,n(),new Proxy({},{get(o,s){if(t)return t[s];let c=i[s];return n(),c},has(o,s){return s in(t||i)},ownKeys(){return Object.keys(t||i)},getOwnPropertyDescriptor(o,s){return Object.getOwnPropertyDescriptor(t||i,s)},set(o,s,c){if(!t)t={...i};return t[s]=c,!0}})}function LE(e){let t=uf(YI.cwd(),e?.configDir||"./config");function r(){if(!GI(t))return[];let i=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),o=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],s=QI(t).filter((d)=>i.has(Kd(d))).map((d)=>({base:d.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:d})),c=new Map;for(let{base:d,file:a}of s){let u=Kd(a).toLowerCase(),m=c.get(d);if(!m){c.set(d,a);continue}let h=Kd(m).toLowerCase();if(o.indexOf(u)<o.indexOf(h))c.set(d,a)}return Array.from(c.entries()).map(([d,a])=>({base:d,file:a})).sort((d,a)=>d.base.localeCompare(a.base))}function n(){let i=r(),o=i.map((a)=>a.base),s=o.length?o.map((a)=>`'${a}'`).join(" | "):"string",c=i.length?`{
|
|
109
|
+
${i.map((a)=>{let u=uf(t,a.file).replace(/\\/g,"/");return` '${a.base}': typeof import('${u}').default`}).join(`,
|
|
110
|
+
`)}
|
|
111
|
+
}`:"Record<string, any>";return`export type ConfigNames = ${s}
|
|
112
|
+
export type ConfigByName = ${c}
|
|
113
|
+
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
114
|
+
export type ConfigOf = Config
|
|
115
|
+
`}return{name:"bunfig-plugin",setup(i){i.onResolve({filter:/^virtual:bunfig-types$/},(o)=>({path:o.path,namespace:"bunfig-virtual"})),i.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:n(),loader:"ts"}))}}}var Jf,Mi,Co,Gf,FE,zE,Sf,oa,sl,ut,Ne,UE,wf,qE,kf,VE,WE,Yd,HE,If,Ef,Zd,KE,JE,GE,QE,sa,Qf,YE,pt,ZE,XE,Rf,aa,al,Xe,Ee,eR,Af,tR,Cf,rR,nR,Xd,iR,Pf,_f,oR,el,sR,aR,cR,dR,lR,ca,Yf,uR,pR="0.15.6",Ft,va,Ro,cl,dl,ba,ll,ul,Ao,pl,ml,pn,Zf,Xf,tr,Nr,eh,th,mR=mE(async()=>{Jf=import.meta.require,Mi=new hl,Co=new yl,Gf={createKey:gE,isEquivalent:fE,estimateMemoryUsage:hE},FE=pa(il.cwd(),"config"),zE=pa(il.cwd(),"src/generated"),Sf=ua.env.CLARITY_LOG_DIR||TI(bE(),"logs"),oa={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Sf,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},sl=await SE(),ut={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,reset:"\x1B[0m"},Ne=ut,UE=ut.red,wf=ut.green,qE=ut.yellow,kf=ut.blue,VE=ut.magenta,WE=ut.cyan,Yd=ut.white,HE=ut.gray,If=ut.bgRed,Ef=ut.bgYellow,Zd=ut.bold,KE=ut.dim,JE=ut.italic,GE=ut.underline,QE=ut.reset,sa={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Qf={debug:"\uD83D\uDD0D",info:kf("ℹ"),success:wf("✓"),warning:Ef(Yd(Zd(" WARN "))),error:If(Yd(Zd(" ERROR ")))},YE=new fa("stacks"),pt=new fa("bunfig",{showTags:!0}),ZE=At(Eo.cwd(),"config"),XE=At(Eo.cwd(),"src/generated"),Rf=la.env.CLARITY_LOG_DIR||PI(EE(),"logs"),aa={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Rf,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},al=await RE(),Xe={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},Ee=Xe,eR=Xe.red,Af=Xe.green,tR=Xe.yellow,Cf=Xe.blue,rR=Xe.magenta,nR=Xe.cyan,Xd=Xe.white,iR=Xe.gray,Pf=Xe.bgRed,_f=Xe.bgYellow,oR=Xe.bgGray,el=Xe.bold,sR=Xe.dim,aR=Xe.italic,cR=Xe.underline,dR=Xe.strikethrough,lR=Xe.reset,ca={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Yf={debug:"\uD83D\uDD0D",info:Cf("ℹ"),success:Af("✓"),warning:_f(Xd(el(" WARN "))),error:Pf(Xd(el(" ERROR ")))},uR=new ya("stacks"),Ft=class extends Error{timestamp;context;constructor(t,r={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=r,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([r,n])=>`${r}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},va=class extends Ft{code="CONFIG_NOT_FOUND";constructor(t,r,n){let i=n?` or alias "${n}"`:"";super(`Configuration "${t}"${i} not found`,{configName:t,alias:n,searchPaths:r,searchPathCount:r.length})}},Ro=class extends Ft{code="CONFIG_LOAD_ERROR";constructor(t,r,n){super(`Failed to load configuration from "${t}": ${r.message}`,{configPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},cl=class extends Ft{code="CONFIG_VALIDATION_ERROR";constructor(t,r,n){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:n,validationErrors:r,errorCount:r.length})}},dl=class extends Ft{code="CONFIG_MERGE_ERROR";constructor(t,r,n,i){super(`Failed to merge configuration from "${t}" with "${r}": ${n.message}`,{sourcePath:t,targetPath:r,configName:i,originalError:n.name,originalMessage:n.message});this.cause=n}},ba=class extends Ft{code="ENV_VAR_ERROR";constructor(t,r,n,i){super(`Failed to parse environment variable "${t}" with value "${r}" as ${n}`,{envKey:t,envValue:r,expectedType:n,configName:i})}},ll=class extends Ft{code="FILE_SYSTEM_ERROR";constructor(t,r,n){super(`File system ${t} failed for "${r}": ${n.message}`,{operation:t,path:r,originalError:n.name,originalMessage:n.message});this.cause=n}},ul=class extends Ft{code="TYPE_GENERATION_ERROR";constructor(t,r,n){super(`Failed to generate types from "${t}" to "${r}": ${n.message}`,{configDir:t,outputPath:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Ao=class extends Ft{code="SCHEMA_VALIDATION_ERROR";constructor(t,r,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:t,configName:n,validationErrors:r,errorCount:r.length})}},pl=class extends Ft{code="BROWSER_CONFIG_ERROR";constructor(t,r,n,i){super(`Failed to fetch configuration from "${t}": ${r} ${n}`,{endpoint:t,status:r,statusText:n,configName:i})}},ml=class extends Ft{code="PLUGIN_ERROR";constructor(t,r,n){super(`Plugin "${t}" failed during ${r}: ${n.message}`,{pluginName:t,operation:r,originalError:n.name,originalMessage:n.message});this.cause=n}},pn={configNotFound(e,t,r){return new va(e,t,r)},configLoad(e,t,r){return new Ro(e,t,r)},configValidation(e,t,r){return new cl(e,t,r)},configMerge(e,t,r,n){return new dl(e,t,r,n)},envVar(e,t,r,n){return new ba(e,t,r,n)},fileSystem(e,t,r){return new ll(e,t,r)},typeGeneration(e,t,r){return new ul(e,t,r)},schemaValidation(e,t,r){return new Ao(e,t,r)},browserConfig(e,t,r,n){return new pl(e,t,r,n)},plugin(e,t,r){return new ml(e,t,r)}},Zf={replace:"replace",concat:"concat",smart:"smart"},Xf=/^https?:\/\//,tr=new ya("bunfig",{showTags:!0}),Nr=new kl,eh=Ct(Wn.cwd(),"config"),th=Ct(Wn.cwd(),"src/generated")});function gR(e,t={}){let r=ma.cwd();while(r.includes("storage"))r=pf(r,"..");let n=pf(r,e||"");if(t?.relative)return XI(ma.cwd(),n);return n}var fR=ma.env.CLARITY_LOG_DIR||ZI(gR(),"logs"),rh={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:fR,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Sa={...rh},uN=(async()=>{try{let{loadConfig:e}=await mR().then(()=>Lf),t=await e({name:"clarity",alias:"logging",defaultConfig:rh,cwd:ma.cwd()});if(t)Object.assign(Sa,t)}catch{}return Sa})();function et(){if($r.env.NODE_ENV==="test"||$r.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function hR(){if($r.env.NODE_ENV==="test"||$r.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof $r<"u"){let e=$r.type;if(e==="renderer"||e==="worker")return!1;return!!($r.versions&&($r.versions.node||$r.versions.bun))}return!1}class nh{async format(e){let t=await hR(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:ji.pid,hostname:t(),environment:ji.env.NODE_ENV||"development",platform:ji.platform,version:ji.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ji.env.NODE_ENV||ji.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var it={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},Ce=it,pN=it.red,yR=it.green,mN=it.yellow,vR=it.blue,gN=it.magenta,fN=it.cyan,Tf=it.white,hN=it.gray,bR=it.bgRed,SR=it.bgYellow,yN=it.bgGray,xf=it.bold,vN=it.dim,bN=it.italic,SN=it.underline,wN=it.strikethrough,kN=it.reset,tl={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},wR={debug:"\uD83D\uDD0D",info:vR("ℹ"),success:yR("✓"),warning:SR(Tf(xf(" WARN "))),error:bR(Tf(xf(" ERROR ")))};class Aa{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...Sa},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new nh,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??ke.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),o=this.generateKey();this.currentKeyId=i,this.keys.set(i,o),this.encryptionKeys.set(i,{key:o,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...tl,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...tl};return{...tl,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Sa.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!et()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let i,o=0,s=3,c=1000;while(o<s)try{try{try{await iE(this.config.logDirectory,hf.F_OK|hf.W_OK)}catch(a){if(a instanceof Error&&"code"in a)if(a.code==="ENOENT")await oE(this.config.logDirectory,{recursive:!0,mode:493});else if(a.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw a;else throw a}}catch(a){throw console.error("Debug: [writeToFile] Failed to create log directory:",a),a}let d=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:xr.from(e);try{if(!Zs(this.currentLogFile))await Qd(this.currentLogFile,"",{mode:420});if(i=ff(this.currentLogFile,"a",420),nE(i,d,{flag:"a"}),gf(i),i!==void 0)Gd(i),i=void 0;if((await $i(this.currentLogFile)).size===0){if(await Qd(this.currentLogFile,d,{flag:"w",mode:420}),(await $i(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(a){let u=a;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(o<s-1){let m=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${o+1}/${s}:`,m);let h=c*2**o;await new Promise((y)=>setTimeout(y,h)),o++;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{Gd(i)}catch(a){console.error("Debug: [writeToFile] Error closing file descriptor:",a)}}}catch(d){if(o===s-1){let u=d,m=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",m),d}o++;let a=c*2**(o-1);await new Promise((u)=>setTimeout(u,a))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return 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 e=new Date().toISOString().split("T")[0];return Ni(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(et())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,c],[,d])=>d.createdAt.getTime()-c.createdAt.getTime()),o=typeof t.maxKeys==="number"?t.maxKeys:1,s=Math.max(1,o);if(i.length>s)for(let[c]of i.slice(s))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return Jd(16).toString("hex")}generateKey(){return Jd(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=Jd(16),n=eE("aes-256-gcm",t,r),i=xr.isBuffer(e)?e:xr.from(e,"utf8"),o=n.update(i),s=n.final(),c=o.length+s.length,d=n.getAuthTag(),a=xr.allocUnsafe(16+c+16);return r.copy(a,0),o.copy(a,16),s.copy(a,16+o.length),d.copy(a,16+c),{encrypted:a,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=vf(),i=[];n.on("data",(o)=>i.push(o)),n.on("end",()=>t(xr.from(xr.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(et())return;if(!this.shouldWriteToFile())return;let e=await $i(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await Xs(this.config.logDirectory),o=i.filter((d)=>d.startsWith(this.name)&&/\.log\.\d+$/.test(d)).sort((d,a)=>{let u=Number.parseInt(d.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),s=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await $i(r).catch(()=>null))try{if(await yf(r,c),t.compress)try{let d=`${c}.gz`;await this.compressLogFile(c,d),await ea(c)}catch(d){console.error("Error compressing rotated file:",d)}if(o.length===0&&!i.some((d)=>d.endsWith(".log.1")))try{let d=`${r}.1`;await Qd(d,"")}catch(d){console.error("Error creating backup file:",d)}}catch(d){console.error(`Error during rotation: ${d instanceof Error?d.message:String(d)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),o=r.replace(/\.log$/,`-${i}.log`);if(await $i(r).catch(()=>null))await yf(r,o)}if(this.currentLogFile=n,t.maxFiles){let o=(await Xs(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,c)=>c.localeCompare(s));for(let s of o.slice(t.maxFiles))await ea(Ni(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=mf(e),n=rE(t),i=vf();await cE(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Zs(this.currentLogFile))try{let e=ff(this.currentLogFile,"r+");gf(e),Gd(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!et()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Xs(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await ea(Ni(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?Ce.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||et())return!1;let e=typeof ke.env.NO_COLOR<"u",t=ke.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof ke.stderr<"u"&&ke.stderr.isTTY||typeof ke.stdout<"u"&&ke.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:o,showTimestamp:s=!0}=e,c=(y)=>y.replace(this.ANSI_PATTERN,"");if(!this.fancy){let y=[];if(s)y.push(t);if(o==="warning")y.push("WARN");else if(o==="error")y.push("ERROR");else if(r)y.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)y.push(n.replace(/[[\]]/g,""));return y.push(i),y.join(" ")}let d=ke.stdout.columns||120,a="";if(o==="warning"||o==="error")a=`${r} ${i}`;else if(o==="info"||o==="success")a=`${r} ${n} ${i}`;else a=`${r} ${n} ${Ce.cyan(i)}`;if(!s)return a.trim();let u=c(a).trim().length,m=c(t).length,h=Math.max(1,d-2-u-m);return`${a.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(o,s)=>{let c=Number.parseInt(s,10);return c<t[0].length?String(t[0][c]):o});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(o,s)=>{if(s==="%")return"%";if(n>=t.length)return o;let c=t[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return o}});if(n<t.length)i+=` ${t.slice(n).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let o=Ce.underline(Ce.blue(n)),s=this.toAbsoluteFilePath(i);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(s)}`,d="\x1B]8;;",a="\x1B\\";return`\x1B]8;;${c}\x1B\\${o}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${o}\x1B]8;;\x1B\\`;return o}),t=t.replace(/`([^`]+)`/g,(r,n)=>Ce.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>Ce.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>Ce.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>Ce.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>Ce.strikethrough(n)),t}supportsHyperlinks(){if(et())return!1;let e=ke.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=ke.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(sE(t)||t.startsWith("./")||t.startsWith("../"))t=aE(t);else return null;return Zs(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let n=new Date,i=this.formatConsoleTimestamp(n),o=this.formatFileTimestamp(n),s,c;if(t instanceof Error)s=t.message,c=t.stack;else s=this.formatMessage(t,r);let{consoleText:d,fileText:a}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let m=this.options.showIcons===!1?"":wR[e],h=this.options.showTags!==!1&&this.name?Ce.gray(this.formatTag(this.name)):"",y;switch(e){case"debug":y=this.formatConsoleMessage({timestamp:i,icon:m,tag:h,message:Ce.gray(d),level:e}),console.error(y);break;case"info":y=this.formatConsoleMessage({timestamp:i,icon:m,tag:h,message:d,level:e}),console.warn(y);break;case"success":y=this.formatConsoleMessage({timestamp:i,icon:m,tag:h,message:Ce.green(d),level:e}),console.error(y);break;case"warning":y=this.formatConsoleMessage({timestamp:i,icon:m,tag:h,message:d,level:e}),console.warn(y);break;case"error":if(y=this.formatConsoleMessage({timestamp:i,icon:m,tag:h,message:d,level:e}),console.error(y),c){let w=c.split(`
|
|
116
|
+
`);for(let k of w)if(k.trim()&&!k.includes(s))console.error(this.formatConsoleMessage({timestamp:i,message:Ce.gray(` ${k}`),level:e,showTimestamp:!1}))}break}}else if(!et()){if(console.error(`${o} ${this.environment}.${e.toUpperCase()}: ${s}`),c)console.error(c)}let u=`${o} ${this.environment}.${e.toUpperCase()}: ${a}
|
|
117
|
+
`;if(c)u+=`${c}
|
|
118
|
+
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(c,d)=>{},finish:(c)=>{},interrupt:(c,d)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!et()&&ke.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,d)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),d!==void 0)this.activeProgressBar.message=d;if(this.shouldStyleConsole()&&!et()&&ke.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,d="info")=>{if(!et()&&ke.stdout.isTTY)ke.stdout.write(`
|
|
119
|
+
`);if(this[d==="warning"?"warn":d](c),this.activeProgressBar&&this.shouldStyleConsole()&&!et()&&ke.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?Ce.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":Ce.blue("◐"),tag:r,message:`${Ce.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),o=`${e} completed in ${i}ms`,s=new Date,c=this.formatConsoleTimestamp(s),a=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${o}`;if(r)a+=` ${JSON.stringify(r)}`;if(a+=`
|
|
120
|
+
`,a=a.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?Ce.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":Ce.green("✓"),tag:u,message:`${o}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!et())console.error(a.trim());if(this.shouldWriteToFile())await this.writeToFile(a)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new Aa(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(et())throw Error("createReadStream is not supported in browser environments");if(!Zs(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return mf(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=xr.isBuffer(e)?e:xr.from(e,"base64"),i=n.subarray(0,16),o=n.subarray(n.length-16),s=n.subarray(16,n.length-16),c=tE("aes-256-gcm",r,i);c.setAuthTag(o);let d=c.update(s),a=c.final(),u=d.length+a.length,m=xr.allocUnsafe(u);return d.copy(m,0),a.copy(m,d.length),m.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return et()}isServerMode(){return!et()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:i,fileText:o}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=i.split(`
|
|
121
|
+
`),d=Math.max(...c.map((h)=>h.length))+2,a=`┌${"─".repeat(d)}┐`,u=`└${"─".repeat(d)}┘`,m=c.map((h)=>this.formatConsoleMessage({timestamp:r,message:Ce.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:Ce.cyan(a),showTimestamp:!1})),m.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:Ce.cyan(u),showTimestamp:!1}))}else if(!et())console.error(`${n} ${this.environment}.INFO: [BOX] ${o}`);let s=`${n} ${this.environment}.INFO: [BOX] ${o}
|
|
122
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(e){if(et())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${Ce.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();ke.stdin.removeListener("data",r);try{if(typeof ke.stdin.setRawMode==="function")ke.stdin.setRawMode(!1)}catch{}ke.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof ke.stdin.setRawMode==="function")ke.stdin.setRawMode(!0)}catch{}ke.stdin.resume(),ke.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let d=/%([sdijfo%])/g,a=0;if(r=e.replace(d,(u,m)=>{if(m==="%")return"%";if(a>=t.length)return u;let h=t[a++];switch(m){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return u}}),a<t.length)r+=` ${t.slice(a).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let d=this.options.showTags!==!1&&this.name?Ce.gray(this.formatTag(this.name)):"",a=this.options.showIcons===!1?"":`${Ce.blue("◐")} `;console.error(`${a}${d} ${Ce.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
|
|
123
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!ke.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,o=Ce.green("━".repeat(n)),s=Ce.gray("━".repeat(i)),c=`[${o}${s}]`,d=`${r}%`.padStart(4),a=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?Ce.green("✓"):Ce.blue("▶"),m=this.options.showTags!==!1&&this.name?` ${Ce.gray(this.formatTag(this.name))}`:"",h=`\r${u}${m} ${c} ${d}${a}`,y=ke.stdout.columns||80,w=" ".repeat(Math.max(0,y-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${w}`,ke.stdout.write(e.lastRenderedLine),t)ke.stdout.write(`
|
|
124
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||et()||!ke.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(et()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Xs(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let o=Ni(this.config.logDirectory,n);if(e.before)try{if((await $i(o)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${o}:`,s);continue}r.push(o)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await ea(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var IN=new Aa("stacks");class rr extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}}class ih extends rr{code="CONFIG_NOT_FOUND";constructor(e,t,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],i="";if(n.length===1)i=` or alias "${n[0]}"`;else if(n.length>1)i=` or aliases ${n.map((o)=>`"${o}"`).join(", ")}`;super(`Configuration "${e}"${i} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}}class wa extends rr{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}}class oh extends rr{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}}class sh extends rr{code="CONFIG_MERGE_ERROR";constructor(e,t,r,n){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}}class Il extends rr{code="ENV_VAR_ERROR";constructor(e,t,r,n){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:n})}}class ah extends rr{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class ch extends rr{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class ka extends rr{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}}class dh extends rr{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,n){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:n})}}class lh extends rr{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}}var Vn={configNotFound(e,t,r){return new ih(e,t,r)},configLoad(e,t,r){return new wa(e,t,r)},configValidation(e,t,r){return new oh(e,t,r)},configMerge(e,t,r,n){return new sh(e,t,r,n)},envVar(e,t,r,n){return new Il(e,t,r,n)},fileSystem(e,t,r){return new ah(e,t,r)},typeGeneration(e,t,r){return new ch(e,t,r)},schemaValidation(e,t,r){return new ka(e,t,r)},browserConfig(e,t,r,n){return new dh(e,t,r,n)},plugin(e,t,r){return new lh(e,t,r)}};async function kR(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:o}=t,s=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await e()}catch(d){if(s=d instanceof Error?d:Error(String(d)),c===r||!i(s))break;if(n>0)await new Promise((a)=>setTimeout(a,n))}if(o!==void 0)return o;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}class El{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:n,useCamelCase:i=!0,useBackwardCompatibility:o=!0,customParsers:s={},verbose:c=!1,trackPerformance:d=!0}=r,a=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=n||this.generateEnvPrefix(e),m={...t};return this.processObject(m,[],u,{useCamelCase:i,useBackwardCompatibility:o,customParsers:s,verbose:c,configName:e}),{config:m,source:{type:"environment",priority:50,timestamp:new Date}}};if(d)return fl.track("applyEnvironmentVariables",a,{configName:e});return a()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,n){for(let[i,o]of Object.entries(e)){let s=[...t,i],c=s.map((u)=>this.formatEnvKey(u,n.useCamelCase)),d=`${r}_${c.join("_")}`,a=n.useBackwardCompatibility?`${r}_${s.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.processObject(o,s,r,n);else{let u=ra.env[d]||(a?ra.env[a]:void 0);if(u!==void 0){if(n.verbose){let m=ra.env[d]?d:a}try{e[i]=this.parseEnvironmentValue(u,typeof o,d,n.customParsers,n.configName)}catch(m){if(m instanceof Il)throw m;throw Vn.envVar(d,u,typeof o,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[o,s]of Object.entries(n))try{return s(e)}catch{continue}for(let o of this.defaultParsers)if(o.canParse(e,t))try{return o.parse(e)}catch{throw Vn.envVar(r,e,`${t} (via ${o.name} parser)`,i)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,i]of Object.entries(ra.env))if(n.startsWith(r)&&i!==void 0)t[n]=i;return t}validateEnvironmentVariable(e,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))n.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(i){n.push(`Cannot parse value "${t}" as ${r}: ${i}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(e,t,r={}){let{prefix:n,format:i="text"}=r,o=n||this.generateEnvPrefix(e),s=[];switch(this.extractEnvVarInfo(t,[],o,s),i){case"markdown":return this.formatAsMarkdown(s,e);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,e)}}extractEnvVarInfo(e,t,r,n){for(let[i,o]of Object.entries(e)){let s=[...t,i],c=`${r}_${s.map((d)=>this.formatEnvKey(d,!0)).join("_")}`;if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.extractEnvVarInfo(o,s,r,n);else n.push({key:c,type:Array.isArray(o)?"array":typeof o,description:`Configuration for ${s.join(".")}`,example:this.generateExample(o)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
|
|
125
|
+
|
|
126
|
+
`;for(let n of e)r+=`${n.key}
|
|
127
|
+
`,r+=` Type: ${n.type}
|
|
128
|
+
`,r+=` Description: ${n.description}
|
|
129
|
+
`,r+=` Example: ${n.example}
|
|
130
|
+
|
|
131
|
+
`;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
|
|
132
|
+
|
|
133
|
+
`;r+=`| Variable | Type | Description | Example |
|
|
134
|
+
`,r+=`|----------|------|-------------|----------|
|
|
135
|
+
`;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
136
|
+
`;return r}}function IR(e,t,r={}){return uh(e,t,r,new WeakMap)}function uh(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:o=!1,customMerger:s}=r;if(t===null||t===void 0)return o?e:t;if(s){let c=s(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return ph(e,t,i,n);if(!Ht(t)||!Ht(e))return t;return CR(e,t,r,n)}function ph(e,t,r,n){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return ER(e,t);case"smart":return RR(e,t,n);default:return t}return t}function ER(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>gl(i,n)))r.push(n);return r}function RR(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(Ht(t[0])&&Ht(e[0]))return AR(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}function AR(e,t,r){let n=[...t];for(let i of e){if(!Ht(i)){n.push(i);continue}let o=["id","name","key","path","type"],s=!1;for(let c of o)if(c in i){if(n.find((a)=>Ht(a)&&(c in a)&&a[c]===i[c])){s=!0;break}}if(!s)n.push(i)}return n}function CR(e,t,r,n){let i=t;if(Ht(i)&&n.has(i))return n.get(i);let o={...e};if(Ht(i))n.set(i,o);for(let s in i){if(!Object.prototype.hasOwnProperty.call(i,s))continue;let c=i[s],d=o[s];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){o[s]=c;continue}if(Ht(c)&&Ht(d))o[s]=uh(d,c,r,n);else if(Array.isArray(c)||Array.isArray(d))o[s]=ph(d,c,r.arrayMergeMode||"smart",n);else o[s]=c}return o}function mh(e,t,r="replace"){return IR(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function gl(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!gl(e[r],t[r]))return!1;return!0}if(Ht(e)&&Ht(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!gl(e[i],t[i]))return!1}return!0}return!1}function Ht(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class gh{extensions=Nf;async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:o,trackPerformance:s=!0,verbose:c=!1}=r;if(i){let a=da.getWithFileCheck("file",e);if(a){if(c)console.log(`Configuration loaded from cache: ${e}`);return a}}let d=async()=>{if(!na(e))return null;try{let a=`?t=${Date.now()}`,u=await import(e+a),m=u.default||u,h="default"in u,y=Object.keys(u).length>0;if(!h&&!y)throw new wa(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof m!=="object"||m===null||Array.isArray(m))throw new wa(e,Error("Configuration must export a valid object"),"unknown");let C={config:mh(t,m,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)da.setWithFileCheck("file",C,e,o);return C}catch(a){throw a instanceof Error?Vn.configLoad(e,a):Vn.configLoad(e,Error(String(a)))}};if(s)return fl.track("loadFromPath",d,{path:e});return d()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){return wI({name:e,directory:t,alias:r})}generateNamePatterns(e,t){return jf({name:e,alias:t})}checkFileAccess(e){return kR(async()=>na(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!na(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let o of i)for(let s of this.extensions){let c=Df(e,`${o}${s}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:i}=await import("fs"),o=i(e);for(let s of o)if(this.looksLikeConfigFile(s)){let c=Df(e,s);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(e))}async validateConfigFile(e){let t=[];try{if(!na(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),o=i(e,"utf8");JSON.parse(o)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}var _R=/^https?:\/\//;class fh{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:o=!0,customRules:s=[],trackPerformance:c=!0,verbose:d=!1}=r,a=async()=>{let u=[],m=[],h={stopOnFirstError:n,validateRequired:i,validateTypes:o,customRules:s,trackPerformance:c,verbose:d};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...s],h);else return this.validateWithJSONSchema(e,t,h)}catch(y){return u.push({path:"",message:`Validation failed: ${y}`,rule:"system"}),{isValid:!1,errors:u,warnings:m}}};if(c)return await fl.track("validateConfiguration",a);return a()}async validateWithSchemaFile(e,t,r){try{if(!PR(t))throw new ka(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),i=n.default||n;if(Array.isArray(i))return this.validateWithRules(e,i,r);else return this.validateWithJSONSchema(e,i,r)}catch(n){throw new ka(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,o){if(o.validateTypes&&t.type){let s=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(s)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${s}`,expected:c.join(" or "),actual:s,rule:"type"}),o.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),o.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let s=0;s<e.length;s++){let c=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(e[s],t.items,c,n,i,o),o.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let s=e;if(o.validateRequired&&t.required){for(let c of t.required)if(!(c in s)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),o.stopOnFirstError)return}}if(t.properties){for(let[c,d]of Object.entries(t.properties))if(c in s){let a=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(s[c],d,a,n,i,o),o.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let d of Object.keys(s))if(!c.has(d))i.push({path:r?`${r}.${d}`:d,message:`Additional property '${d}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let o of t)try{let s=this.getValueByPath(e,o.path),c=this.validateWithRule(s,o,o.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:o.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,o,s]=n;t.push({path:i,required:!o,type:this.mapTypeScriptType(s)})}return t}mapTypeScriptType(e){switch(e.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:_R},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var er=new Aa("bunfig",{showTags:!0});function TR(e){if(!e)return"";let t=Array.isArray(e)?e.filter(Boolean):[e];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class hh{fileLoader=new gh;envProcessor=new El;validator=new fh;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:o,...s}=e;try{if(r?.enabled){let d=this.checkCache(s.name||"",s);if(d)return d}let c;try{c=await this.loadConfigurationStrategies(s,!0,r)}catch(d){if(s.configFile)throw d;let a=s.__strictErrorHandling;if(d instanceof Error&&d.name==="ConfigNotFoundError"){if(a)throw d;c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(d instanceof Error&&d.name==="ConfigLoadError"){let u=d.message.includes("EACCES")||d.message.includes("EPERM")||d.message.includes("permission denied"),m=!u&&(d.message.includes("syntax")||d.message.includes("Expected")||d.message.includes("Unexpected")||d.message.includes("BuildMessage")||d.message.includes("errors building")),h=d.message.includes("Configuration must export a valid object")||d.message.includes("Configuration file is empty and exports nothing");if(a&&(h||u))throw d;if(m&&(!a||!h))c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!a)c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${d.message}`]};else throw d}else c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${d instanceof Error?d.message:String(d)}`]}}if(i||o)await this.validateConfiguration(c.config,i,o,s.name);if(r?.enabled&&c)this.cacheResult(s.name||"",c,r,s);if(n?.enabled){let d={operation:"loadConfig",duration:Date.now()-t,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(d);if(n.slowThreshold&&d.duration>n.slowThreshold)er.warn(`Slow configuration loading detected: ${d.duration}ms for ${s.name}`);c.metrics=d}return c}catch(c){if(c instanceof Error&&c.name==="ConfigNotFoundError")throw c;let d=Date.now()-t;throw er.error(`Configuration loading failed after ${d}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,configFile:o,cwd:s,configDir:c,defaultConfig:d,checkEnv:a=!0,arrayStrategy:u="replace",verbose:m=!1}=e,h=s||Ia.cwd(),y=[];if(o){let j=gr(h,o);y.push(j);let P=a?wo(n,d,m):d,O=await this.fileLoader.tryLoadFromPaths([j],P,{arrayStrategy:u,verbose:m,cacheTtl:r?.ttl,useCache:!r?.ttl||r.ttl>100});if(!O)throw Vn.configNotFound(n||o,y,i);if(m)er.success(`Configuration loaded from explicit path: ${j}`);return this.finalizeResult(O,y,a,n,m)}let w=await this.loadLocalConfiguration(n,i,h,c,d,u,m,a,r);if(w)return y.push(...this.getLocalSearchPaths(n,i,h,c)),this.finalizeResult(w,y,a,n,m);let k=await this.loadHomeConfiguration(n,i,d,u,m,a);if(k)return y.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(k,y,a,n,m);let C=await this.loadPackageJsonConfiguration(n,i,h,d,u,m,a);if(C)return y.push(gr(h,"package.json")),this.finalizeResult(C,y,a,n,m);if(y.push(...this.getAllSearchPaths(n,i,h,c)),t)throw Vn.configNotFound(n,y,i);return{...await this.applyEnvironmentVariables(n,d,a,m),warnings:[`No configuration file found for "${n}"${TR(i)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,o,s,c,d){let a=c?wo(e,i,s):i,u=this.getLocalDirectories(r,n);for(let m of u){if(s)er.info(`Searching for configuration in: ${m}`);let h=this.fileLoader.generateConfigPaths(e,m,t),y=await this.fileLoader.tryLoadFromPaths(h,a,{arrayStrategy:o,verbose:s,cacheTtl:d?.ttl,useCache:!d?.ttl||d.ttl>100});if(y){if(s)er.success(`Configuration loaded from: ${y.source.path}`);return y}}return null}async loadHomeConfiguration(e,t,r,n,i,o){if(!e)return null;let s=o?wo(e,r,i):r,c=[gr(Ai(),".config",e),gr(Ai(),".config"),Ai()];for(let d of c){if(i)er.info(`Checking home directory: ${d}`);let a=this.fileLoader.generateConfigPaths(e,d,t),u=await this.fileLoader.tryLoadFromPaths(a,s,{arrayStrategy:n,verbose:i});if(u){if(i)er.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,o,s){let c=s?wo(e,n,o):n;try{let d=gr(r,"package.json");if(!II(d))return null;let a={};try{a=JSON.parse(EI(d,"utf8"))}catch(h){if(o)er.warn("Failed to parse package.json:",[h instanceof Error?h:Error(String(h))]);return null}let u=a[e],m=e;if(!u&&t){let h=Array.isArray(t)?t:[t];for(let y of h){if(!y)continue;if(a[y]){u=a[y],m=y;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(o)er.success(`Configuration loaded from package.json: ${m}`);return{config:mh(c,u,i),source:{type:"package.json",path:d,priority:30,timestamp:new Date}}}}catch(d){if(o)er.warn("Failed to load package.json:",[d instanceof Error?d:Error(String(d))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:wo(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let o=r(e);if(o)i.push(...o)}if(t){let o=await this.validator.validateConfiguration(e,t);if(!o.isValid)i.push(...o.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(i.length>0)throw Vn.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return da.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);da.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let n=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${n}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configFile)r.push(`configFile:${t.configFile}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return kI({cwd:e,configDir:t})}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(gr(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),o=[];for(let s of i)o.push(...this.fileLoader.generateConfigPaths(e,s,t));return o}getHomeSearchPaths(e,t){if(!e)return[];let r=[gr(Ai(),".config",e),gr(Ai(),".config"),Ai()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}var rl=new hh;async function yh(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let n;if(r)n=await rl.loadConfig(e);else n=await rl.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){if(e.configFile)throw n;let i=n instanceof Error?n.name:"UnknownError",o=n instanceof Error?n.message:String(n);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||o.includes("config"))&&e.verbose)er.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let c=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await rl.applyEnvironmentVariables(c.name||"",t,!0,c.verbose||!1))?.config??t;return t}}function wo(e,t,r=!1){let n=new El,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function o(s,c=[]){let d={...s};for(let[a,u]of Object.entries(s)){let m=[...c,a],h=[`${i}_${m.join("_").toUpperCase()}`,`${i}_${m.map((k)=>k.toUpperCase()).join("")}`,`${i}_${m.map((k)=>k.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],y,w;for(let k of h)if(y=Ia.env[k],y!==void 0){w=k;break}if(y!==void 0&&w)if(typeof u==="boolean")d[a]=["true","1","yes"].includes(y.toLowerCase());else if(typeof u==="number"){let k=Number(y);if(!Number.isNaN(k))d[a]=k}else if(Array.isArray(u))try{d[a]=JSON.parse(y)}catch{d[a]=y.split(",").map((k)=>k.trim())}else d[a]=y;else if(u&&typeof u==="object"&&!Array.isArray(u))d[a]=o(u,m)}return d}return o(t)}var PN=gr(Ia.cwd(),"config"),_N=gr(Ia.cwd(),"src/generated");var Rl={project:{name:"my-project",slug:"my-project",region:"us-east-1"},environments:{production:{type:"production"}}},Hn=null;function OR(e){return e.project?.slug===Rl.project?.slug&&Object.keys(e.environments??{}).length===1&&!!e.environments?.production}async function $R(){let e=[vh(process.cwd(),"config","cloud.ts"),vh(process.cwd(),"config","cloud.js")];for(let t of e){if(!xR(t))continue;let r=await import(`${DR(t).href}?t=${Date.now()}`),n=r.tsCloud??r.default?.tsCloud??r.default??r.cloud??r.config;if(n)return n}return null}async function NR(){if(!Hn){if(Hn=await yh({name:"cloud",defaultConfig:Rl}),OR(Hn))Hn=await $R()??Hn;bh(Hn.stateDir)}return Hn}var Sh=NR,jN=Rl;var mn=(e)=>e==null?void 0:String(e),Cl=(e)=>Number(e)===1,kh=(e,t)=>{try{return e==null?t:JSON.parse(String(e))}catch{return t}};function Al(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),scope:{type:String(e.scope_type),id:String(e.scope_id),environmentId:mn(e.environment_id),resourceId:mn(e.resource_id),previewId:mn(e.preview_id)},key:String(e.key),kind:String(e.kind),value:mn(e.value),valueFingerprint:String(e.value_fingerprint),secretRef:mn(e.secret_ref),backend:String(e.backend),backendVersion:mn(e.backend_version),origin:String(e.origin),required:Cl(e.required),metadata:kh(e.metadata,{}),lastUsedAt:mn(e.last_used_at),rotatedAt:mn(e.rotated_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function wh(e){return{entryId:String(e.entry_id),resourceId:String(e.resource_id),injectionTarget:String(e.injection_target),required:Cl(e.required),requiresRedeploy:Cl(e.requires_redeploy),lastDeployedVersion:e.last_deployed_version==null?void 0:Number(e.last_deployed_version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}class Pl{controlPlane;now;constructor(e,t=()=>new Date){this.controlPlane=e;this.now=t}get(e){let t=this.controlPlane.database.query("SELECT * FROM configuration_entries WHERE id=?").get(e);return t?Al(t):void 0}find(e,t,r){let n=this.controlPlane.database.query("SELECT * FROM configuration_entries WHERE project_id=? AND scope_type=? AND scope_id=? AND key=?").get(e,t.type,t.id,r);return n?Al(n):void 0}list(e){let t=["project_id=?"],r=[e.projectId];if(e.scope)t.push("scope_type=?","scope_id=?"),r.push(e.scope.type,e.scope.id);if(e.kind)t.push("kind=?"),r.push(e.kind);return this.controlPlane.database.query(`SELECT * FROM configuration_entries WHERE ${t.join(" AND ")} ORDER BY key,scope_type,scope_id`).all(...r).map(Al)}create(e){this.validateScope(e),this.validateEntry(e);let t=crypto.randomUUID(),r=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO configuration_entries (id,organization_id,project_id,scope_type,scope_id,environment_id,resource_id,preview_id,key,kind,value,value_fingerprint,secret_ref,backend,backend_version,origin,required,metadata,last_used_at,rotated_at,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.organizationId,e.projectId,e.scope.type,e.scope.id,e.scope.environmentId??null,e.scope.resourceId??null,e.scope.previewId??null,e.key,e.kind,e.value??null,e.valueFingerprint,e.secretRef??null,e.backend,e.backendVersion??null,e.origin,e.required?1:0,JSON.stringify(e.metadata),e.lastUsedAt??null,e.rotatedAt??null,1,r,r]),this.get(t)}update(e,t,r){let n=this.get(e);if(!n)throw Error("Configuration entry was not found.");if(this.validateEntry({...n,...r}),this.controlPlane.database.run("UPDATE configuration_entries SET value=?,value_fingerprint=?,secret_ref=?,backend=?,backend_version=?,required=?,metadata=?,rotated_at=?,version=version+1,updated_at=? WHERE id=? AND version=?",[r.value??null,r.valueFingerprint,r.secretRef??null,r.backend,r.backendVersion??null,r.required?1:0,JSON.stringify(r.metadata),r.rotatedAt??null,this.now().toISOString(),e,t]).changes!==1)throw Error("Configuration entry changed; refresh and retry.");return this.get(e)}remove(e,t){let r=this.get(e);if(!r)throw Error("Configuration entry was not found.");if(r.version!==t)throw Error("Configuration entry changed; refresh and retry.");if(this.controlPlane.database.run("DELETE FROM configuration_entries WHERE id=? AND version=?",[e,t]).changes<1)throw Error("Configuration entry changed; refresh and retry.");return r}setDependency(e){let t=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO configuration_dependencies (entry_id,resource_id,injection_target,required,requires_redeploy,last_deployed_version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?) ON CONFLICT(entry_id,resource_id) DO UPDATE SET injection_target=excluded.injection_target,required=excluded.required,requires_redeploy=excluded.requires_redeploy,last_deployed_version=excluded.last_deployed_version,updated_at=excluded.updated_at",[e.entryId,e.resourceId,e.injectionTarget,e.required?1:0,e.requiresRedeploy?1:0,e.lastDeployedVersion??null,t,t]),this.dependencies(e.entryId).find((r)=>r.resourceId===e.resourceId)}dependencies(e){return this.controlPlane.database.query("SELECT * FROM configuration_dependencies WHERE entry_id=? ORDER BY resource_id").all(e).map(wh)}dependenciesForResource(e){return this.controlPlane.database.query("SELECT * FROM configuration_dependencies WHERE resource_id=? ORDER BY entry_id").all(e).map(wh)}mutation(e){let t=this.controlPlane.database.query("SELECT request_hash,result FROM configuration_mutations WHERE idempotency_key=?").get(e);return t?{requestHash:t.request_hash,result:kh(t.result,{})}:void 0}recordMutation(e){this.controlPlane.database.run("INSERT INTO configuration_mutations (id,project_id,idempotency_key,request_hash,result,actor_id,created_at) VALUES (?,?,?,?,?,?,?)",[crypto.randomUUID(),e.projectId,e.idempotencyKey,e.requestHash,JSON.stringify(e.result),e.actorId??null,this.now().toISOString()])}validateEntry(e){if(!/^[A-Za-z_][A-Za-z0-9_]{0,255}$/.test(e.key))throw Error(`Invalid configuration key: ${e.key}`);if(e.kind==="variable"&&(e.value==null||e.secretRef||e.backend!=="plaintext"))throw Error("Variables require a plaintext value and cannot use a secret backend.");if(e.kind==="secret"&&(e.value!=null||!e.secretRef||e.backend==="plaintext"))throw Error("Secrets require a non-plaintext backend reference and cannot store a plaintext value.")}validateScope(e){let t=this.controlPlane.getProject(e.projectId);if(!t||t.organizationId!==e.organizationId)throw Error("Configuration project does not belong to the organization.");let r=e.scope;if(r.type==="project"){if(r.id!==e.projectId||r.environmentId||r.resourceId||r.previewId)throw Error("Project configuration scope must reference only its project.");return}if(r.type==="environment"){let i=this.controlPlane.database.query("SELECT project_id FROM environments WHERE id=?").get(r.id);if(!i||i.project_id!==e.projectId||r.environmentId&&r.environmentId!==r.id||r.resourceId||r.previewId)throw Error("Environment configuration scope does not belong to the project.");return}if(r.type==="service"||r.type==="function"){let i=this.controlPlane.getResource(r.id);if(!i||i.projectId!==e.projectId||r.type==="function"&&i.kind!=="function"||r.resourceId&&r.resourceId!==r.id||r.environmentId&&i.environmentId!==r.environmentId||r.previewId)throw Error(`${r.type==="function"?"Function":"Service"} configuration scope does not belong to the project.`);return}let n=this.controlPlane.database.query("SELECT project_id,base_environment_id,resource_id FROM preview_instances WHERE id=?").get(r.id);if(!n||n.project_id!==e.projectId||r.previewId&&r.previewId!==r.id||r.environmentId&&r.environmentId!==n.base_environment_id||r.resourceId&&r.resourceId!==n.resource_id)throw Error("Preview configuration scope does not belong to the project.")}}var Ih=/^[A-Za-z_][A-Za-z0-9_]{0,255}$/;function jR(e){let t={n:`
|
|
137
|
+
`,r:"\r",t:"\t","\\":"\\",'"':'"',$:"$"};return e.replace(/\\(n|r|t|\\|"|\$)/g,(r,n)=>t[n])}function Eh(e){let t={},r=[],n=e.replace(/\r\n?/g,`
|
|
138
|
+
`).split(`
|
|
139
|
+
`);for(let i=0;i<n.length;i++){let o=i+1,s=n[i];if(!s.trim()||s.trimStart().startsWith("#"))continue;if(/^\s*export\s+/.test(s))s=s.replace(/^\s*export\s+/,"");let c=s.match(/^\s*([^=\s]+)\s*=\s*(.*)$/);if(!c){r.push({line:o,severity:"error",code:"invalid_line",message:"Expected KEY=VALUE."});continue}let d=c[1],a=c[2];if(!Ih.test(d)){r.push({line:o,key:d,severity:"error",code:"invalid_key",message:`Invalid environment variable name: ${d}`});continue}let u=a;if(a.startsWith('"')||a.startsWith("'")){let m=a[0],h=[a.slice(1)],y=!1;while(!0){let w=h[h.length-1],k=!1,C=-1;for(let T=0;T<w.length;T++){if(m==='"'&&w[T]==="\\"&&!k){k=!0;continue}if(w[T]===m&&!k){C=T;break}k=!1}if(C>=0){h[h.length-1]=w.slice(0,C),y=!0;break}if(++i>=n.length)break;h.push(n[i])}if(!y){r.push({line:o,key:d,severity:"error",code:"unterminated_quote",message:`Unterminated quoted value for ${d}.`});continue}if(u=h.join(`
|
|
140
|
+
`),m==='"')u=jR(u)}else u=a.replace(/\s+#.*$/,"").trim();if(Object.hasOwn(t,d)){let m=t[d]!==u;if(r.push({line:o,key:d,severity:m?"error":"warning",code:m?"conflict":"duplicate",message:m?`${d} has conflicting values.`:`${d} is duplicated with the same value.`}),m)continue}t[d]=u}return{values:t,diagnostics:r,valid:!r.some((i)=>i.severity==="error")}}function Rh(e){return Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>{if(!Ih.test(t))throw Error(`Invalid environment variable name: ${t}`);return`${t}=${JSON.stringify(r)}`}).join(`
|
|
141
|
+
`)+(Object.keys(e).length?`
|
|
142
|
+
`:"")}import{createCipheriv as MR,createDecipheriv as BR,createHash as Ah,randomBytes as LR}from"node:crypto";class Po{controlPlane;now;kind="local_encrypted";key;constructor(e,t,r=()=>new Date){this.controlPlane=e;this.now=r;if(!t)throw Error("Configuration encryption key is required.");this.key=Ah("sha256").update(`ts-cloud:configuration:${t}`).digest()}encrypt(e){let t=LR(12),r=MR("aes-256-gcm",this.key,t),n=Buffer.concat([r.update(e,"utf8"),r.final()]);return`v1.${t.toString("base64url")}.${r.getAuthTag().toString("base64url")}.${n.toString("base64url")}`}decrypt(e){let[t,r,n,i]=e.split(".");if(t!=="v1"||!r||!n||!i)throw Error("Encrypted configuration secret is unavailable.");try{let o=BR("aes-256-gcm",this.key,Buffer.from(r,"base64url"));return o.setAuthTag(Buffer.from(n,"base64url")),Buffer.concat([o.update(Buffer.from(i,"base64url")),o.final()]).toString("utf8")}catch{throw Error("Encrypted configuration secret could not be decrypted.")}}async put(e){if(!e.value)throw Error("Configuration secrets cannot be empty.");let t=e.reference??`secret://configuration/${e.name}/${crypto.randomUUID()}`;if(!/^secret:\/\/configuration\/[A-Za-z0-9._/-]+$/.test(t))throw Error("Invalid local configuration secret reference.");let n=(this.controlPlane.database.query("SELECT version FROM configuration_secret_values WHERE reference=?").get(t)?.version??0)+1,i=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO configuration_secret_values (reference,ciphertext,fingerprint,version,created_at,updated_at) VALUES (?,?,?,?,?,?) ON CONFLICT(reference) DO UPDATE SET ciphertext=excluded.ciphertext,fingerprint=excluded.fingerprint,version=excluded.version,updated_at=excluded.updated_at",[t,this.encrypt(e.value),Ah("sha256").update(e.value).digest("hex"),n,i,i]),{reference:t,version:String(n)}}async resolve(e){let t=this.controlPlane.database.query("SELECT ciphertext FROM configuration_secret_values WHERE reference=?").get(e);if(!t)throw Error("Configuration secret was not found.");return this.decrypt(t.ciphertext)}async remove(e){this.controlPlane.database.run("DELETE FROM configuration_secret_values WHERE reference=?",[e])}async validate(e){return!!this.controlPlane.database.query("SELECT 1 AS found FROM configuration_secret_values WHERE reference=?").get(e)}}class _l{client;region;kind="aws_secrets_manager";constructor(e,t){this.client=e;this.region=t}async put(e){if(e.reference){let r=this.id(e.reference),n=await this.client.putSecretValue({SecretId:r,SecretString:e.value,ClientRequestToken:e.idempotencyKey});return{reference:e.reference,version:n.VersionId??e.idempotencyKey}}let t=await this.client.createSecret({Name:e.name,SecretString:e.value,ClientRequestToken:e.idempotencyKey,Tags:[{Key:"managed-by",Value:"ts-cloud"}]});return{reference:`aws-sm://${this.region}/${encodeURIComponent(t.ARN??t.Name??e.name)}`,version:t.VersionId??e.idempotencyKey}}async resolve(e){let t=await this.client.getSecretValue({SecretId:this.id(e)});if(t.SecretString==null)throw Error("AWS Secrets Manager value is unavailable.");return t.SecretString}async remove(e){await this.client.deleteSecret({SecretId:this.id(e),RecoveryWindowInDays:7})}async validate(e){try{return await this.client.describeSecret(this.id(e)),!0}catch{return!1}}id(e){let t=new URL(e);if(t.protocol!=="aws-sm:"||t.hostname!==this.region)throw Error("Invalid AWS Secrets Manager reference.");return decodeURIComponent(t.pathname.slice(1))}}class Tl{client;region;kind="aws_ssm";constructor(e,t){this.client=e;this.region=t}async put(e){let t=e.reference?this.name(e.reference):`/${e.name.replace(/^\/+/,"")}`,r=await this.client.putParameter({Name:t,Value:e.value,Type:"SecureString",Overwrite:!!e.reference,Description:"Managed by ts-cloud"});return{reference:`aws-ssm://${this.region}${t}`,version:String(r.Version??1)}}async resolve(e){let t=await this.client.getParameter({Name:this.name(e),WithDecryption:!0});if(t.Parameter?.Value==null)throw Error("AWS SSM parameter value is unavailable.");return t.Parameter.Value}async remove(e){await this.client.deleteParameter({Name:this.name(e)})}async validate(e){try{return!!(await this.client.getParameter({Name:this.name(e),WithDecryption:!1})).Parameter}catch{return!1}}name(e){let t=new URL(e);if(t.protocol!=="aws-ssm:"||t.hostname!==this.region||!t.pathname.startsWith("/"))throw Error("Invalid AWS SSM reference.");return t.pathname}}class xl{kind="external";async put(){throw Error("External secret references cannot be written by ts-cloud.")}async resolve(){throw Error("External secrets must be resolved by the deployment provider.")}async remove(){}async validate(e){return/^(?:vault|doppler|op|external):\/\//.test(e)}}import{createHmac as FR}from"node:crypto";var zR=/^(?:secret|aws-sm|aws-ssm|vault|doppler|op|external):\/\//,UR=/^(?:AWS_|TS_CLOUD_|PORT$|HOST$)/;function $t(e){return[...new Set(e)].sort()}function Ch(e,t={}){let r=e.kind==="secret";return{id:e.id,key:e.key,kind:e.kind,scope:e.scope,inherited:!!t.inherited,overridden:!!t.overridden,required:e.required,backend:!r||t.canReadSecretMetadata?e.backend:void 0,backendVersion:!r||t.canReadSecretMetadata?e.backendVersion:void 0,reference:r&&t.canReadSecretMetadata?e.secretRef:void 0,value:!r?e.value:void 0,lastUsedAt:e.lastUsedAt,rotatedAt:e.rotatedAt,version:e.version,updatedAt:e.updatedAt}}class Dl{store;backends=new Map;fingerprintKey;now;constructor(e,t){if(this.store=e,this.fingerprintKey=t.fingerprintKey??t.encryptionKey,this.now=t.now??(()=>new Date),!this.fingerprintKey)throw Error("Configuration fingerprint key is required.");let r=t.backends??[new Po(e.controlPlane,t.encryptionKey,this.now)];for(let n of r)this.backends.set(n.kind,n)}list(e){let t=e.search?.toLowerCase();return this.store.list(e).filter((r)=>!t||r.key.toLowerCase().includes(t)).map((r)=>Ch(r,{canReadSecretMetadata:e.canReadSecretMetadata}))}plan(e){let t=this.store.list({projectId:e.projectId,scope:e.scope}),r=new Map(t.map((d)=>[d.key,d])),n=[],i=[],o=[],s=[];for(let[d,a]of Object.entries(e.values)){n.push(...this.warnings(d,a));let u=r.get(d);if(!u)i.push(d);else if(u.valueFingerprint!==this.fingerprint(a))o.push(d);else s.push(d)}let c=e.removeMissing?t.filter((d)=>!Object.hasOwn(e.values,d.key)).map((d)=>d.key):[];return{added:$t(i),changed:$t(o),removed:$t(c),unchanged:$t(s),affectedResourceIds:this.affectedResources(e.projectId,e.scope,[...i,...o,...c]),warnings:n}}async set(e){let t=this.requestHash(e),r=e.idempotencyKey;if(r){let w=this.store.mutation(r);if(w){if(w.requestHash!==t)throw Error("Idempotency key was already used for a different configuration mutation.");let k=this.store.get(String(w.result.entryId??""));if(!k)throw Error("Idempotent configuration result is no longer available.");return{entry:k,mutation:w.result.mutation,warnings:[]}}}if(e.value!=null&&zR.test(e.value))throw Error("Secret references must use the reference field, not a plaintext value field.");let n=this.store.find(e.projectId,e.scope,e.key),i=this.fingerprint(e.value??e.reference??"");if(n&&e.expectedVersion!=null&&n.version!==e.expectedVersion)throw Error("Configuration entry changed; refresh and retry.");if(n&&n.kind!==e.kind)throw Error("Delete the existing entry before changing between variable and secret kinds.");let o=e.kind==="variable"?"plaintext":e.backend??(e.reference?"external":"local_encrypted");if(!!n&&(n.valueFingerprint!==i||n.backend!==o||n.required!==!!e.required)&&(this.isProduction(n)||this.store.dependencies(n.id).length>0)&&!e.confirmed)throw Error("Confirmation is required because this replacement affects production or dependent services.");let c=e.reference,d;if(e.kind==="secret"){let w=this.backend(o);if(e.reference&&e.value==null){if(!await w.validate(e.reference))throw Error("Secret backend reference is unavailable or invalid.");d=n?.backendVersion??"external"}else{if(e.value==null)throw Error("A secret value or external reference is required.");let k=await w.put({reference:n?.backend===o?n.secretRef:void 0,name:this.backendName(e),value:e.value,idempotencyKey:r??crypto.randomUUID()});c=k.reference,d=k.version}}let a=e.kind==="variable"?e.value:void 0;if(e.kind==="variable"&&a==null)throw Error("A variable value is required.");let u=!n||n.valueFingerprint!==i||n.backend!==o||n.secretRef!==c||n.backendVersion!==d||n.required!==!!e.required,m=n?u?this.store.update(n.id,n.version,{value:a,valueFingerprint:i,secretRef:c,backend:o,backendVersion:d,required:!!e.required,metadata:Oe(e.metadata??n.metadata),rotatedAt:e.kind==="secret"?this.now().toISOString():n.rotatedAt}):n:this.store.create({organizationId:e.organizationId,projectId:e.projectId,scope:e.scope,key:e.key,kind:e.kind,value:a,valueFingerprint:i,secretRef:c,backend:o,backendVersion:d,origin:e.origin??"managed",required:!!e.required,metadata:Oe(e.metadata??{}),rotatedAt:e.kind==="secret"?this.now().toISOString():void 0}),h=this.affectedResources(e.projectId,e.scope,[e.key]),y={added:n?[]:[e.key],changed:n&&u?[e.key]:[],removed:[],unchanged:n&&!u?[e.key]:[],affectedResourceIds:h,versions:{[e.key]:m.version}};if(r)this.store.recordMutation({projectId:e.projectId,idempotencyKey:r,requestHash:t,actorId:e.actorId,result:{entryId:m.id,mutation:y}});return this.audit(e.projectId,e.actorId,n&&u?"configuration.updated":n?"configuration.unchanged":"configuration.created",m,h),{entry:m,mutation:y,warnings:this.warnings(e.key,e.value??"")}}async importDotenv(e){let t=Eh(e.source);if(!t.valid)return{document:t,warnings:[]};let r=new Set(e.secretKeys??[]),n={added:[],changed:[],removed:[],unchanged:[],affectedResourceIds:[],versions:{}},i=[];for(let[o,s]of Object.entries(t.values)){let c=await this.set({...e,source:void 0,key:o,value:s,kind:r.has(o)?"secret":"variable",idempotencyKey:e.idempotencyKey?`${e.idempotencyKey}:${o}`:void 0});n.added.push(...c.mutation.added),n.changed.push(...c.mutation.changed),n.unchanged.push(...c.mutation.unchanged),n.affectedResourceIds.push(...c.mutation.affectedResourceIds),Object.assign(n.versions,c.mutation.versions),i.push(...c.warnings)}return n.added=$t(n.added),n.changed=$t(n.changed),n.unchanged=$t(n.unchanged),n.affectedResourceIds=$t(n.affectedResourceIds),{document:t,mutation:n,warnings:i}}exportVariables(e){return Rh(Object.fromEntries(this.store.list({projectId:e.projectId,scope:e.scope,kind:"variable"}).map((t)=>[t.key,t.value??""])))}async transfer(e){let t=this.store.get(e.entryId);if(!t)throw Error("Configuration entry was not found.");if(t.scope.type===e.targetScope.type&&t.scope.id===e.targetScope.id)throw Error("Choose a different destination scope.");let r=t.kind==="variable"?t.value:t.backend==="external"?void 0:await this.backend(t.backend).resolve(t.secretRef),n=t.kind==="secret"?t.backend:void 0,i=await this.set({organizationId:t.organizationId,projectId:t.projectId,scope:e.targetScope,key:t.key,kind:t.kind,value:r,reference:t.backend==="external"?t.secretRef:void 0,backend:n,required:t.required,metadata:t.metadata,confirmed:e.confirmed,actorId:e.actorId,idempotencyKey:e.idempotencyKey?`${e.idempotencyKey}:copy`:void 0,origin:t.origin});if(e.mode==="move")await this.remove({entryId:t.id,expectedVersion:t.version,confirmed:e.confirmed,actorId:e.actorId});let o={added:i.mutation.added,changed:i.mutation.changed,removed:e.mode==="move"?[t.key]:[],unchanged:i.mutation.unchanged,affectedResourceIds:$t([...i.mutation.affectedResourceIds,...this.affectedResources(t.projectId,t.scope,[t.key])]),versions:i.mutation.versions};return{entry:i.entry,mutation:o}}async resolve(e){let t=this.store.list({projectId:e.projectId}),r=t.filter((a)=>this.applies(a,e)).sort((a,u)=>this.rank(a.scope.type)-this.rank(u.scope.type)),n=new Map,i=new Set;for(let a of r){if(n.has(a.key))i.add(a.key);n.set(a.key,a)}let o={},s={},c=[],d=new Set(e.allowedPreviewSecrets??[]);for(let[a,u]of n){if(e.previewId&&u.kind==="secret"&&u.scope.type!=="preview"&&(!e.trustedPreview||!d.has(a)))continue;if(u.kind==="variable")o[a]=u.value??"";else if(e.nativeReferences)o[a]=u.secretRef;else{let m=this.backend(u.backend);if(!await m.validate(u.secretRef)){if(c.push({key:a,code:"stale_reference",message:`${a} points to an unavailable secret.`}),u.required)c.push({key:a,code:"missing_required",message:`${a} is required but unavailable.`});continue}o[a]=await m.resolve(u.secretRef)}s[a]=Ch(u,{inherited:u.scope.type!==(e.previewId?"preview":e.functionId?"function":e.resourceId?"service":e.environmentId?"environment":"project"),overridden:i.has(a),canReadSecretMetadata:e.canReadSecretMetadata}),this.store.controlPlane.database.run("UPDATE configuration_entries SET last_used_at=? WHERE id=?",[this.now().toISOString(),u.id])}return{values:o,entries:s,warnings:c,configurationHash:this.fingerprint([...n.values()].map((a)=>`${a.key}:${a.valueFingerprint}:${a.version}`).sort().join(`
|
|
143
|
+
`))}}async reveal(e){let t=this.store.get(e.entryId);if(!t||t.kind!=="secret")throw Error("Configuration secret was not found.");if(!e.canRevealSecrets)throw Error("Secret reveal permission is required.");if(!e.recentlyAuthenticated)throw Error("Recent authentication is required to reveal a secret.");let r=await this.backend(t.backend).resolve(t.secretRef);return this.audit(t.projectId,e.actorId,"configuration.secret.revealed",t,[]),r}async remove(e){let t=this.store.get(e.entryId);if(!t)throw Error("Configuration entry was not found.");let r=this.store.dependencies(t.id);if(((t.scope.environmentId?this.store.controlPlane.listEnvironments(t.projectId).some((s)=>s.id===t.scope.environmentId&&s.kind==="production"):t.scope.type==="project")||r.length)&&!e.confirmed)throw Error("Confirmation is required because this configuration affects production or dependent services.");if(t.kind==="secret"&&t.backend!=="external")await this.backend(t.backend).remove(t.secretRef);this.store.remove(t.id,e.expectedVersion);let i=$t(r.map((s)=>s.resourceId)),o={added:[],changed:[],removed:[t.key],unchanged:[],affectedResourceIds:i,versions:{}};return this.audit(t.projectId,e.actorId,"configuration.deleted",t,i),o}applies(e,t){if(e.scope.type==="project")return!0;if(e.scope.type==="environment")return e.scope.id===t.environmentId;if(e.scope.type==="service")return e.scope.id===t.resourceId;if(e.scope.type==="function")return e.scope.id===t.functionId;return e.scope.id===t.previewId}rank(e){return{project:0,environment:1,service:2,function:3,preview:4}[e]}fingerprint(e){return`hmac-sha256:${FR("sha256",this.fingerprintKey).update(e).digest("hex")}`}requestHash(e){return this.fingerprint(JSON.stringify({...e,idempotencyKey:void 0,actorId:void 0}))}backend(e){let t=this.backends.get(e);if(!t)throw Error(`Configuration secret backend is not configured: ${e}`);return t}backendName(e){return`ts-cloud/${e.projectId}/${e.scope.type}/${e.scope.id}/${e.key}`.replace(/[^A-Za-z0-9/_+=.@-]/g,"-")}isProduction(e){return e.scope.type==="project"||!!e.scope.environmentId&&this.store.controlPlane.listEnvironments(e.projectId).some((t)=>t.id===e.scope.environmentId&&t.kind==="production")}warnings(e,t){let r=[];if(UR.test(e))r.push({key:e,code:"reserved",message:`${e} may be reserved by the runtime or provider.`});if(Buffer.byteLength(t)>65536)r.push({key:e,code:"limit",message:`${e} exceeds the portable 64 KiB value limit.`});return r}affectedResources(e,t,r){let n=this.store.list({projectId:e,scope:t}).filter((i)=>r.includes(i.key)).flatMap((i)=>this.store.dependencies(i.id).map((o)=>o.resourceId));if(t.type==="service"||t.type==="function")return $t([...n,t.id]);if(t.type==="environment")return $t([...n,...this.store.controlPlane.listResources(e,t.id).map((i)=>i.id)]);if(t.type==="preview"){let i=this.store.controlPlane.database.query("SELECT resource_id FROM preview_instances WHERE id=?").get(t.id);return $t([...n,...i?[i.resource_id]:[]])}return $t([...n,...this.store.controlPlane.listResources(e).map((i)=>i.id)])}audit(e,t,r,n,i){this.store.controlPlane.appendEvent({projectId:e,actorId:t,type:r,payload:{entryId:n.id,key:n.key,kind:n.kind,scopeType:n.scope.type,scopeId:n.scope.id,backend:n.backend,version:n.version,affectedResourceIds:i}})}}async function Ph(e,t,r,n){let i={added:0,changed:0,removed:0,overridden:0},o=async(s,c)=>{let d=e.store.list({projectId:t.project.id,scope:s,kind:"variable"}),a=new Set(Object.keys(c));for(let u of d.filter((m)=>m.origin==="config"&&!a.has(m.key)))await e.remove({entryId:u.id,expectedVersion:u.version,confirmed:!0,actorId:n}),i.removed++;for(let[u,m]of Object.entries(c)){let h=e.store.find(t.project.id,s,u);if(h?.origin!=="config"){if(h)i.overridden++;else await e.set({organizationId:t.organization.id,projectId:t.project.id,scope:s,key:u,kind:"variable",value:String(m),origin:"config",confirmed:!0,actorId:n}),i.added++;continue}if(h.value===String(m))continue;await e.set({organizationId:t.organization.id,projectId:t.project.id,scope:s,key:u,kind:"variable",value:String(m),origin:"config",confirmed:!0,actorId:n,expectedVersion:h.version}),i.changed++}};for(let[s,c]of Object.entries(r.environments??{})){let d=t.environments.get(s);if(!d)continue;let a=c,u={...a.variables??{},...a.app?.env??{}};await o({type:"environment",id:d.id,environmentId:d.id},u);for(let[m,h]of Object.entries(r.sites??{})){let y=t.store.listResources(t.project.id,d.id).find((w)=>w.kind==="application"&&w.slug===m);if(y)await o({type:"service",id:y.id,environmentId:d.id,resourceId:y.id},{...h.env??{}})}for(let[m,h]of Object.entries(r.infrastructure?.functions??{})){let y=t.store.listResources(t.project.id,d.id).find((w)=>w.kind==="function"&&w.slug===m);if(y)await o({type:"function",id:y.id,environmentId:d.id,resourceId:y.id},{...h.environment??{}})}}return i}import{createHash as qR}from"node:crypto";var _h=async(e)=>{let t=Bun.spawn(e,{stdout:"pipe",stderr:"pipe"}),[r,n,i]=await Promise.all([t.exited,new Response(t.stdout).text(),new Response(t.stderr).text()]);return{code:r,stdout:n,stderr:i}};class Th{async scan(e,t){let r=await _h(["ssh-keyscan","-T","10","-p",String(t),"-t","ed25519",e]),n=r.stdout.split(`
|
|
144
|
+
`).find((i)=>i&&!i.startsWith("#"))?.trim().split(/\s+/);if(r.code!==0||!n?.[1]||!n[2])throw Error(`SSH host-key scan failed: ${r.stderr.trim()||"no key returned"}`);return{algorithm:n[1],key:n[2]}}async exec(e,t){if(e.trustState!=="pinned")throw Error("SSH host key must be pinned before remote execution.");return _h(["ssh","-p",String(e.sshPort),"-o","BatchMode=yes","-o","StrictHostKeyChecking=yes","-o","ConnectTimeout=10",`${e.sshUser}@${e.endpoint}`,t])}}var VR=(e)=>`SHA256:${qR("sha256").update(Buffer.from(e,"base64")).digest("base64").replace(/=+$/,"")}`,WR=`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 _o{provider;transport;discoverer;constructor(e,t=new Th,r){this.provider=e;this.transport=t;this.discoverer=r}discover(e){return this.discoverer?.(e)??Promise.resolve([])}async test(e){try{let t=await this.transport.scan(e.endpoint,e.sshPort);return{reachable:!0,hostKeyAlgorithm:t.algorithm,hostKeyFingerprint:VR(t.key),latencyMs:0}}catch{return{reachable:!1,hostKeyAlgorithm:"unknown",hostKeyFingerprint:"",latencyMs:0}}}async validate(e){let t=await this.transport.exec(e,WR);if(t.code!==0)throw Error(`Fleet validation failed: ${t.stderr.trim()||t.code}`);try{return JSON.parse(t.stdout)}catch{throw Error("Fleet validation returned malformed facts.")}}async bootstrap(e,t){let r=await this.transport.exec(e,`sudo -n ts-cloud-agent bootstrap --version 1 --steps ${t.length}`);if(r.code!==0)throw Error(`Fleet bootstrap failed: ${r.stderr.trim()||r.code}`);return{version:"1"}}capabilities(){return{document:{supported:!0,reason:"fleet-capabilities/v1; sha256:driver-contract"},validate:{supported:!0},bootstrap:{supported:!0},heartbeat:{supported:!0},drain:{supported:!0},archive:{supported:!0},terminate:{supported:!1,reason:"Inventory removal never terminates provider infrastructure."}}}}function xh(e,t){return{"fleet.bootstrap":async(r)=>{let n=r.operation.input&&typeof r.operation.input==="object"&&!Array.isArray(r.operation.input)?r.operation.input:{},i=e.get(String(n.serverId??""));if(!i)throw Error("Queued fleet server was not found.");let o=t.find((d)=>d.provider===i.provider);if(!o)throw Error(`No ${i.provider} fleet driver is configured.`);let s=Array.isArray(n.steps)?n.steps.map(String):[];if(r.checkpoint("preflight","Rechecking pinned trust and healthy validation."),i.trustState!=="pinned"||!i.validation?.valid)throw Error("Fleet bootstrap requires pinned trust and a healthy validation report.");r.checkpoint("bootstrap","Applying the reviewed idempotent bootstrap plan.");let c=await o.bootstrap(i,s);return e.update(i.id,{bootstrapVersion:c.version,status:"ready"}),r.checkpoint("verify","Bootstrap completed; heartbeat can now establish freshness."),{serverId:i.id,bootstrapVersion:c.version,steps:s.length}}}}var fr=(e)=>e==null?void 0:String(e),Kn=(e,t)=>{try{return JSON.parse(String(e))}catch{return t}},Ol=(e)=>({id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),resourceId:String(e.resource_id),name:String(e.name),provider:String(e.provider),providerId:fr(e.provider_id),region:fr(e.region),zone:fr(e.zone),endpoint:String(e.endpoint),sshUser:String(e.ssh_user),sshPort:Number(e.ssh_port),credentialRef:String(e.credential_ref),hostKeyAlgorithm:fr(e.host_key_algorithm),hostKeyFingerprint:fr(e.host_key_fingerprint),pendingHostKey:fr(e.pending_host_key),roles:Kn(e.roles,[]),labels:Kn(e.labels,{}),taints:Kn(e.taints,[]),capacity:Kn(e.capacity,{}),usage:Kn(e.usage,{}),capabilities:Kn(e.capabilities,{}),status:String(e.status),trustState:String(e.trust_state),validation:Kn(e.validation,void 0),bootstrapVersion:fr(e.bootstrap_version),heartbeatAt:fr(e.heartbeat_at),lastSeenAt:fr(e.last_seen_at),archivedAt:fr(e.archived_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)});class $l{control;now;id;constructor(e,t=()=>new Date,r=()=>crypto.randomUUID()){this.control=e;this.now=t;this.id=r}get(e){let t=this.control.database.query("SELECT * FROM fleet_servers WHERE id=?").get(e);return t?Ol(t):void 0}list(e,t=!1){return this.control.database.query("SELECT * FROM fleet_servers WHERE project_id=? ORDER BY name").all(e).map(Ol).filter((r)=>t||r.status!=="archived")}findProvider(e,t,r){let n=this.control.database.query("SELECT * FROM fleet_servers WHERE organization_id=? AND provider=? AND provider_id=? AND archived_at IS NULL").get(e,t,r);return n?Ol(n):void 0}create(e){let t=this.id(),r=this.now().toISOString();return this.control.database.run("INSERT INTO fleet_servers (id,organization_id,project_id,resource_id,name,provider,provider_id,region,zone,endpoint,ssh_user,ssh_port,credential_ref,host_key_algorithm,host_key_fingerprint,pending_host_key,roles,labels,taints,capacity,usage,capabilities,status,trust_state,validation,bootstrap_version,heartbeat_at,last_seen_at,archived_at,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.organizationId,e.projectId,e.resourceId,e.name,e.provider,e.providerId??null,e.region??null,e.zone??null,e.endpoint,e.sshUser,e.sshPort,e.credentialRef,e.hostKeyAlgorithm??null,e.hostKeyFingerprint??null,e.pendingHostKey??null,JSON.stringify(e.roles),JSON.stringify(e.labels),JSON.stringify(e.taints),JSON.stringify(e.capacity),JSON.stringify(e.usage),JSON.stringify(e.capabilities),e.status,e.trustState,JSON.stringify(e.validation??{}),e.bootstrapVersion??null,e.heartbeatAt??null,e.lastSeenAt??null,e.archivedAt??null,r,r]),this.get(t)}update(e,t){let r=this.get(e);if(!r)throw Error("Server was not found.");let n={...r,...t},i=this.now().toISOString();return this.control.database.run("UPDATE fleet_servers SET name=?,provider_id=?,region=?,zone=?,endpoint=?,ssh_user=?,ssh_port=?,credential_ref=?,host_key_algorithm=?,host_key_fingerprint=?,pending_host_key=?,roles=?,labels=?,taints=?,capacity=?,usage=?,capabilities=?,status=?,trust_state=?,validation=?,bootstrap_version=?,heartbeat_at=?,last_seen_at=?,archived_at=?,version=version+1,updated_at=? WHERE id=?",[n.name,n.providerId??null,n.region??null,n.zone??null,n.endpoint,n.sshUser,n.sshPort,n.credentialRef,n.hostKeyAlgorithm??null,n.hostKeyFingerprint??null,n.pendingHostKey??null,JSON.stringify(n.roles),JSON.stringify(n.labels),JSON.stringify(n.taints),JSON.stringify(n.capacity),JSON.stringify(n.usage),JSON.stringify(n.capabilities),n.status,n.trustState,JSON.stringify(n.validation??{}),n.bootstrapVersion??null,n.heartbeatAt??null,n.lastSeenAt??null,n.archivedAt??null,i,e]),this.get(e)}}var HR=/^(?:[A-Za-z0-9](?:[A-Za-z0-9.-]{0,251}[A-Za-z0-9])?|\[[0-9a-fA-F:]+\])$/;class Nl{store;drivers;now;queue;constructor(e,t,r,n=()=>new Date){this.store=e;this.drivers=t;this.now=n;this.queue=r??new $e(e.control)}driver(e){let t=this.drivers.find((r)=>r.provider===e);if(!t)throw Error(`No ${e} fleet driver is configured.`);return t}enroll(e){if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(e.name))throw Error("Server name is invalid.");if(!HR.test(e.endpoint)||e.sshUser==="root"||!e.credentialRef.startsWith("secret://"))throw Error("Enrollment requires a valid endpoint, non-root SSH user, and secret credential reference.");let t=e.providerId?this.store.findProvider(e.organizationId,e.provider,e.providerId):void 0;if(t)return this.store.update(t.id,{endpoint:e.endpoint,region:e.region,zone:e.zone});let r=this.store.control.createResource({projectId:e.projectId,kind:"server",slug:e.name,name:e.name,provider:e.provider,providerId:e.providerId}),n=this.driver(e.provider);return this.store.create({...e,resourceId:r.id,sshPort:e.sshPort??22,labels:e.labels??{},taints:[],capacity:{},usage:{},capabilities:n.capabilities(),status:"pending",trustState:"unverified"})}async test(e){let t=this.store.get(e);if(!t)throw Error("Server was not found.");let r=await this.driver(t.provider).test(t);if(!r.reachable)return this.store.update(e,{status:"unreachable"});if(t.hostKeyFingerprint&&t.hostKeyFingerprint!==r.hostKeyFingerprint)return this.store.update(e,{status:"degraded",trustState:"rotation_pending",pendingHostKey:r.hostKeyFingerprint});return this.store.update(e,{hostKeyAlgorithm:r.hostKeyAlgorithm,hostKeyFingerprint:r.hostKeyFingerprint,pendingHostKey:void 0,trustState:"pinned",status:"validating",lastSeenAt:this.now().toISOString()})}reviewHostKey(e,t){let r=this.store.get(e);if(!r||r.pendingHostKey!==t)throw Error("Pending host key does not match.");return this.store.update(e,{hostKeyFingerprint:t,pendingHostKey:void 0,trustState:"pinned",status:"validating"})}async validate(e){let t=this.store.get(e);if(!t||t.trustState!=="pinned")throw Error("Pin the SSH host key before validation.");let r=await this.driver(t.provider).validate(t),n=[];if(!["x64","arm64","x86_64","aarch64"].includes(r.arch??""))n.push({code:"arch.unsupported",severity:"error",message:"Unsupported architecture.",remediation:"Use x86_64 or arm64 Linux."});for(let s of["curl","tar"])if(!r.tools?.[s])n.push({code:`tool.${s}`,severity:"error",message:`${s} is missing.`,remediation:`Install ${s} before bootstrap.`});if(Math.abs(r.timeSkewSeconds??0)>60)n.push({code:"time.skew",severity:"error",message:"Clock skew exceeds 60 seconds.",remediation:"Enable NTP synchronization."});if(!r.dnsOk)n.push({code:"dns.failed",severity:"error",message:"DNS validation failed.",remediation:"Repair resolver configuration."});let i={valid:!n.some((s)=>s.severity==="error"),facts:r,findings:n,validatedAt:this.now().toISOString(),validatorVersion:"1"},o={cpu:r.cpuCores??0,memoryBytes:r.memoryBytes??0,diskBytes:r.diskBytes??0};return this.store.update(e,{validation:i,capacity:o,status:i.valid?"ready":"degraded"})}bootstrap(e,t=!1){let r=this.store.get(e);if(!r?.validation?.valid)throw Error("A healthy validation report is required.");let n=["install runtime dependencies","install ts-cloud agent","configure heartbeat","verify least-privilege access"];if(!t)return{preview:!0,steps:n};let i=this.queue.enqueue({projectId:r.projectId,resourceId:r.resourceId,kind:"fleet.bootstrap",input:{serverId:e,steps:n},lockKey:`server:${e}`,providerKey:r.provider}).operation;return{preview:!1,steps:n,operation:i}}heartbeat(e,t){let r=this.store.get(e);if(!r)throw Error("Server was not found.");let n=this.now().toISOString();return this.store.update(e,{usage:t.usage,capabilities:t.capabilities??r.capabilities,heartbeatAt:n,lastSeenAt:n,status:r.status==="draining"||r.status==="drained"?r.status:"ready"})}drain(e,t=!1){return this.store.update(e,{status:t?"drained":"draining"})}uncordon(e){return this.store.update(e,{status:"ready"})}archive(e,t){let r=this.store.get(e);if(!r||t!==r.name)throw Error("Exact server name confirmation is required.");return this.store.update(e,{status:"archived",archivedAt:this.now().toISOString()})}}import{createHash as jl,createPublicKey as $h,verify as KR}from"node:crypto";function To(e){if(e===null||typeof e!=="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(To).join(",")}]`;return`{${Object.keys(e).sort().map((t)=>`${JSON.stringify(t)}:${To(e[t])}`).join(",")}}`}var Nh=(e)=>jl("sha256").update(To(e)).digest("hex"),Ca=(e)=>jl("sha256").update(To(e)).digest("hex"),jh=(e)=>jl("sha256").update($h(e).export({type:"spki",format:"der"})).digest("hex");function Mh(e,t,r){try{return KR(null,Buffer.from(To(e)),$h(r),Buffer.from(t,"base64"))}catch{return!1}}var Dh=(e)=>e.replace(/^v/,"").split(/[.-]/).slice(0,3).map((t)=>Number(t)||0),Oh=(e,t)=>{let r=Dh(e),n=Dh(t);for(let i=0;i<3;i++){let o=(r[i]??0)-(n[i]??0);if(o)return o}return 0};function Bh(e,t){let r=[];if(t.schemaVersion<e.minimumSchema)r.push(`schema ${t.schemaVersion} is below ${e.minimumSchema}`);if(t.schemaVersion>e.maximumSchema)r.push(`schema ${t.schemaVersion} is above ${e.maximumSchema}`);if(e.minimumVersion&&Oh(t.currentVersion,e.minimumVersion)<0)r.push(`platform ${t.currentVersion} is below ${e.minimumVersion}`);if(Oh(e.version,t.currentVersion)<=0)r.push(`version ${e.version} is not newer than ${t.currentVersion}`);if(!e.artifacts.some((n)=>n.platform===t.platform&&n.architecture===t.architecture))r.push(`no artifact for ${t.platform}/${t.architecture}`);return{compatible:r.length===0,reasons:r}}var jr=(e,t)=>{try{return JSON.parse(String(e))}catch{return t}},mt=(e)=>e==null?void 0:String(e),JR=(e)=>({id:String(e.id),organizationId:String(e.organization_id),name:String(e.name),algorithm:"ed25519",publicKeyPem:String(e.public_key_pem),fingerprint:String(e.fingerprint),revokedAt:mt(e.revoked_at),createdAt:String(e.created_at)}),Lh=(e)=>({id:String(e.id),organizationId:String(e.organization_id),version:String(e.version),channel:String(e.channel),publishedAt:String(e.published_at),keyId:String(e.key_id),digest:String(e.digest),document:jr(e.document,{}),signature:String(e.signature),verificationStatus:String(e.verification_status),compatibility:jr(e.compatibility,{compatible:!1,reasons:[]}),createdAt:String(e.created_at)}),Fh=(e)=>({id:String(e.id),projectId:String(e.project_id),name:String(e.name),schedule:String(e.schedule),timezone:String(e.timezone),durationMinutes:Number(e.duration_minutes),allowedOperations:jr(e.allowed_operations,[]),requireApproval:Number(e.require_approval)===1,enabled:Number(e.enabled)===1,createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),zh=(e)=>({id:String(e.id),projectId:String(e.project_id),manifestId:String(e.manifest_id),windowId:mt(e.window_id),fromVersion:String(e.from_version),strategy:String(e.strategy),batchSize:Number(e.batch_size),healthGate:jr(e.health_gate,{}),status:String(e.status),currentStage:mt(e.current_stage),backupId:mt(e.backup_id),approvedBy:mt(e.approved_by),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),Ml=(e)=>({id:String(e.id),campaignId:String(e.campaign_id),serverId:mt(e.server_id),target:String(e.target),cohort:Number(e.cohort),previousVersion:String(e.previous_version),status:String(e.status),evidence:jr(e.evidence,{}),error:mt(e.error),startedAt:mt(e.started_at),finishedAt:mt(e.finished_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),Uh=(e)=>({id:String(e.id),projectId:String(e.project_id),kind:String(e.kind),criteria:jr(e.criteria,{}),candidates:jr(e.candidates,[]),candidateDigest:String(e.candidate_digest),estimatedBytes:Number(e.estimated_bytes),status:String(e.status),confirmation:mt(e.confirmation),expiresAt:String(e.expires_at),result:jr(e.result,{}),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),qh=(e)=>({id:String(e.id),projectId:String(e.project_id),backupPolicyId:mt(e.backup_policy_id),recoveryPointId:mt(e.recovery_point_id),topologyId:mt(e.topology_id),scenario:String(e.scenario),isolatedTarget:String(e.isolated_target),expectedRpoMinutes:Number(e.expected_rpo_minutes),expectedRtoMinutes:Number(e.expected_rto_minutes),status:String(e.status),operationId:mt(e.operation_id),evidence:jr(e.evidence,{}),measuredRpoMinutes:e.measured_rpo_minutes==null?void 0:Number(e.measured_rpo_minutes),measuredRtoMinutes:e.measured_rto_minutes==null?void 0:Number(e.measured_rto_minutes),cleanupVerified:Number(e.cleanup_verified)===1,error:mt(e.error),startedAt:mt(e.started_at),finishedAt:mt(e.finished_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)});class Bl{control;now;id;constructor(e,t=()=>new Date,r=()=>crypto.randomUUID()){this.control=e;this.now=t;this.id=r}addTrustedKey(e){let t=this.id(),r=this.now().toISOString(),n=jh(e.publicKeyPem);return this.control.database.run("INSERT INTO platform_trusted_keys (id,organization_id,name,algorithm,public_key_pem,fingerprint,created_at) VALUES (?,?,?,'ed25519',?,?,?)",[t,e.organizationId,e.name,e.publicKeyPem,n,r]),this.key(t)}key(e){let t=this.control.database.query("SELECT * FROM platform_trusted_keys WHERE id=?").get(e);return t?JR(t):void 0}revokeKey(e){return this.control.database.run("UPDATE platform_trusted_keys SET revoked_at=? WHERE id=?",[this.now().toISOString(),e]),this.key(e)}importManifest(e){let t=this.key(e.keyId);if(!t||t.organizationId!==e.organizationId)throw Error("Trusted update key was not found.");if(t.revokedAt)throw Error("Update signing key is revoked.");if(!Mh(e.document,e.signature,t.publicKeyPem))throw Error("Update manifest signature is invalid.");let r=Bh(e.document,e.current),n=Nh(e.document),i=this.id(),o=this.now().toISOString();return this.control.database.run("INSERT INTO platform_update_manifests (id,organization_id,version,channel,published_at,key_id,digest,document,signature,verification_status,compatibility,created_at) VALUES (?,?,?,?,?,?,?,?,?,'verified',?,?)",[i,e.organizationId,e.document.version,e.document.channel,new Date(e.document.publishedAt).toISOString(),e.keyId,n,JSON.stringify(e.document),e.signature,JSON.stringify(r),o]),this.manifest(i)}manifest(e){let t=this.control.database.query("SELECT * FROM platform_update_manifests WHERE id=?").get(e);return t?Lh(t):void 0}manifests(e){return this.control.database.query("SELECT * FROM platform_update_manifests WHERE organization_id=? ORDER BY published_at DESC").all(e).map(Lh)}createWindow(e){let t=this.id(),r=this.now().toISOString();return this.control.database.run("INSERT INTO maintenance_windows (id,project_id,name,schedule,timezone,duration_minutes,allowed_operations,require_approval,enabled,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,1,?,?)",[t,e.projectId,e.name,e.schedule,e.timezone,e.durationMinutes,JSON.stringify(e.allowedOperations),e.requireApproval===!1?0:1,r,r]),this.window(t)}window(e){let t=this.control.database.query("SELECT * FROM maintenance_windows WHERE id=?").get(e);return t?Fh(t):void 0}windows(e){return this.control.database.query("SELECT * FROM maintenance_windows WHERE project_id=? ORDER BY name").all(e).map(Fh)}createCampaign(e){return this.control.transaction(()=>{let t=this.manifest(e.manifestId);if(!t?.compatibility.compatible||t.verificationStatus!=="verified")throw Error("A verified compatible update manifest is required.");if(!e.backupId)throw Error("A verified pre-upgrade backup is required.");let r=this.id(),n=this.now().toISOString();return this.control.database.run("INSERT INTO platform_upgrade_campaigns (id,project_id,manifest_id,window_id,from_version,strategy,batch_size,health_gate,status,backup_id,approved_by,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?, 'planned',?,?,?,?)",[r,e.projectId,e.manifestId,e.windowId??null,e.fromVersion,e.strategy,e.batchSize,JSON.stringify(e.healthGate),e.backupId,e.approvedBy??null,n,n]),e.targets.forEach((i,o)=>this.control.database.run("INSERT INTO platform_upgrade_targets (id,campaign_id,server_id,target,cohort,previous_version,status,created_at,updated_at) VALUES (?,?,?,?,?,?,'pending',?,?)",[this.id(),r,i.serverId??null,i.target,e.strategy==="canary"?o===0?0:1+Math.floor((o-1)/e.batchSize):Math.floor(o/e.batchSize),i.previousVersion,n,n])),this.campaign(r)})}campaign(e){let t=this.control.database.query("SELECT * FROM platform_upgrade_campaigns WHERE id=?").get(e);return t?zh(t):void 0}campaigns(e){return this.control.database.query("SELECT * FROM platform_upgrade_campaigns WHERE project_id=? ORDER BY created_at DESC").all(e).map(zh)}targets(e){return this.control.database.query("SELECT * FROM platform_upgrade_targets WHERE campaign_id=? ORDER BY cohort,target").all(e).map(Ml)}updateCampaign(e,t){let r=this.campaign(e);if(!r)throw Error("Upgrade campaign was not found.");let n={...r,...t};return this.control.database.run("UPDATE platform_upgrade_campaigns SET status=?,current_stage=?,updated_at=? WHERE id=?",[n.status,n.currentStage??null,this.now().toISOString(),e]),this.campaign(e)}updateTarget(e,t){let r=this.control.database.query("SELECT * FROM platform_upgrade_targets WHERE id=?").get(e);if(!r)throw Error("Upgrade target was not found.");let n={...Ml(r),...t};return this.control.database.run("UPDATE platform_upgrade_targets SET status=?,evidence=?,error=?,started_at=?,finished_at=?,updated_at=? WHERE id=?",[n.status,JSON.stringify(n.evidence),n.error??null,n.startedAt??null,n.finishedAt??null,this.now().toISOString(),e]),Ml(this.control.database.query("SELECT * FROM platform_upgrade_targets WHERE id=?").get(e))}createCleanup(e){let t=[...e.candidates].sort((s,c)=>s.id.localeCompare(c.id)),r=Ca(t),n=this.id(),i=this.now().toISOString(),o=new Date(this.now().getTime()+(e.ttlMinutes??60)*60000).toISOString();return this.control.database.run("INSERT INTO cleanup_plans (id,project_id,kind,criteria,candidates,candidate_digest,estimated_bytes,status,expires_at,created_at,updated_at) VALUES (?,?,?,?,?,?,?,'preview',?,?,?)",[n,e.projectId,e.kind,JSON.stringify(e.criteria),JSON.stringify(t),r,t.reduce((s,c)=>s+c.bytes,0),o,i,i]),this.cleanup(n)}cleanup(e){let t=this.control.database.query("SELECT * FROM cleanup_plans WHERE id=?").get(e);return t?Uh(t):void 0}cleanups(e){return this.control.database.query("SELECT * FROM cleanup_plans WHERE project_id=? ORDER BY created_at DESC").all(e).map(Uh)}updateCleanup(e,t){let r=this.cleanup(e);if(!r)throw Error("Cleanup plan was not found.");let n={...r,...t};return this.control.database.run("UPDATE cleanup_plans SET status=?,confirmation=?,result=?,updated_at=? WHERE id=?",[n.status,n.confirmation??null,JSON.stringify(n.result),this.now().toISOString(),e]),this.cleanup(e)}createDrill(e){if(!/^isolated:\/\//.test(e.isolatedTarget))throw Error("DR drills require an isolated target.");let t=this.id(),r=this.now().toISOString();return this.control.database.run("INSERT INTO disaster_recovery_drills (id,project_id,backup_policy_id,recovery_point_id,topology_id,scenario,isolated_target,expected_rpo_minutes,expected_rto_minutes,status,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,'planned',?,?)",[t,e.projectId,e.backupPolicyId??null,e.recoveryPointId??null,e.topologyId??null,e.scenario,e.isolatedTarget,e.expectedRpoMinutes,e.expectedRtoMinutes,r,r]),this.drill(t)}drill(e){let t=this.control.database.query("SELECT * FROM disaster_recovery_drills WHERE id=?").get(e);return t?qh(t):void 0}drills(e){return this.control.database.query("SELECT * FROM disaster_recovery_drills WHERE project_id=? ORDER BY created_at DESC").all(e).map(qh)}updateDrill(e,t){let r=this.drill(e);if(!r)throw Error("DR drill was not found.");let n={...r,...t};return this.control.database.run("UPDATE disaster_recovery_drills SET status=?,operation_id=?,evidence=?,measured_rpo_minutes=?,measured_rto_minutes=?,cleanup_verified=?,error=?,started_at=?,finished_at=?,updated_at=? WHERE id=?",[n.status,n.operationId??null,JSON.stringify(n.evidence),n.measuredRpoMinutes??null,n.measuredRtoMinutes??null,n.cleanupVerified?1:0,n.error??null,n.startedAt??null,n.finishedAt??null,this.now().toISOString(),e]),this.drill(e)}}function GR(e,t=new Date){if(!e.enabled)return!1;let r=new Date(e.schedule);if(!Number.isNaN(r.getTime()))return t>=r&&t.getTime()<=r.getTime()+e.durationMinutes*60000;let n=/^(\d{2}):(\d{2})$/.exec(e.schedule);if(!n)return!1;let i=new Intl.DateTimeFormat("en-US",{timeZone:e.timezone,hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).formatToParts(t),o=Number(i.find((c)=>c.type==="hour")?.value)*60+Number(i.find((c)=>c.type==="minute")?.value),s=Number(n[1])*60+Number(n[2]);return o>=s&&o<s+e.durationMinutes}class Ll{store;now;queue;constructor(e,t,r=()=>new Date){this.store=e;this.now=r;this.queue=t??new $e(e.control)}enqueueCampaign(e,t={}){let r=this.store.campaign(e);if(!r)throw Error("Upgrade campaign was not found.");let n=r.windowId?this.store.window(r.windowId):void 0;if(n&&!n.allowedOperations.includes("platform.upgrade"))throw Error("Maintenance window does not permit platform upgrades.");if(n&&!t.overrideWindow&&!GR(n,this.now()))throw Error("Upgrade is outside its maintenance window.");if(n?.requireApproval&&!t.approvedBy&&!r.approvedBy)throw Error("Maintenance approval is required.");let i=this.queue.enqueue({projectId:r.projectId,actorId:t.approvedBy,kind:"maintenance.upgrade",input:{campaignId:e},lockKey:"platform-upgrade",providerKey:"platform",timeoutSeconds:7200,cancellationMode:"cooperative",resumePolicy:"fail"}).operation;return{campaign:this.store.updateCampaign(e,{status:"queued"}),operation:i}}async previewCleanup(e,t){let r=t.find((n)=>n.kind===e.kind);if(!r)throw Error(`No ${e.kind} cleanup driver is configured.`);return this.store.createCleanup({...e,candidates:await r.discover(e.criteria)})}enqueueCleanup(e,t){let r=this.store.cleanup(e);if(!r||r.status!=="preview")throw Error("A current cleanup preview is required.");if(new Date(r.expiresAt)<=this.now())throw Error("Cleanup preview expired; generate it again.");let n=`DELETE ${r.candidates.length} ${r.kind}`;if(t!==n)throw Error(`Exact confirmation ${n} is required.`);let i=this.queue.enqueue({projectId:r.projectId,kind:"maintenance.cleanup",input:{planId:e},lockKey:`cleanup:${r.kind}`,providerKey:"cleanup",timeoutSeconds:3600,cancellationMode:"cooperative"}).operation;return{plan:this.store.updateCleanup(e,{status:"approved",confirmation:t}),operation:i}}enqueueDrill(e){let t=this.store.drill(e);if(!t||t.status!=="planned")throw Error("A planned DR drill is required.");let r=this.queue.enqueue({projectId:t.projectId,kind:"maintenance.drill",input:{drillId:e},lockKey:`drill:${t.scenario}:${t.id}`,providerKey:"recovery",timeoutSeconds:7200,cancellationMode:"cooperative"}).operation;return{drill:this.store.updateDrill(e,{status:"queued",operationId:r.id}),operation:r}}}var Fl=(e)=>e&&typeof e==="object"&&!Array.isArray(e)?e:{};function Vh(e){return{"maintenance.upgrade":async(i)=>{let o=e.store.campaign(String(Fl(i.operation.input).campaignId??""));if(!o||!e.platform)throw Error("Upgrade campaign or platform maintenance driver is unavailable.");let s=e.store.manifest(o.manifestId);if(!s?.compatibility.compatible||s.verificationStatus!=="verified")throw Error("Update manifest is no longer verified and compatible.");let c=s.document.artifacts.find((a)=>a.platform===process.platform&&a.architecture===process.arch)??s.document.artifacts[0];if(!c)throw Error("No update artifact matches this platform.");e.store.updateCampaign(o.id,{status:"running",currentStage:"preflight"});let d=[];try{for(let a of[...new Set(e.store.targets(o.id).map((u)=>u.cohort))].sort((u,m)=>u-m)){e.store.updateCampaign(o.id,{currentStage:`cohort:${a}`});for(let u of e.store.targets(o.id).filter((m)=>m.cohort===a)){i.throwIfCancellationRequested(),i.checkpoint(`download:${u.target}`,"Downloading signed platform artifact."),e.store.updateTarget(u.id,{status:"downloading",startedAt:new Date().toISOString()});let m=await e.platform.download({target:u,artifact:c,signal:i.signal});if(m.sha256!==c.sha256)throw Error(`Artifact checksum mismatch for ${u.target}.`);i.checkpoint(`install:${u.target}`,"Installing verified artifact."),e.store.updateTarget(u.id,{status:"installing"}),await e.platform.install({target:u,path:m.path,version:s.version,signal:i.signal}),d.push(u);let h=await e.platform.health({target:u,gate:o.healthGate});if(!h.healthy)throw Error(`Upgrade health gate failed for ${u.target}.`);e.store.updateTarget(u.id,{status:"healthy",evidence:h.evidence,finishedAt:new Date().toISOString()})}}return e.store.updateCampaign(o.id,{status:"succeeded",currentStage:void 0}),{campaignId:o.id,version:s.version,targets:d.length}}catch(a){e.store.updateCampaign(o.id,{status:"rolling_back",currentStage:"rollback"});for(let u of d.reverse())e.store.updateTarget(u.id,{status:"rolling_back"}),await e.platform.rollback({target:u,version:u.previousVersion,signal:i.signal}),e.store.updateTarget(u.id,{status:"rolled_back",finishedAt:new Date().toISOString()});throw e.store.updateCampaign(o.id,{status:"rolled_back",currentStage:void 0}),a}},"maintenance.cleanup":async(i)=>{let o=e.store.cleanup(String(Fl(i.operation.input).planId??""));if(!o||o.status!=="approved")throw Error("Approved cleanup plan was not found.");if(Ca([...o.candidates].sort((u,m)=>u.id.localeCompare(m.id)))!==o.candidateDigest)throw Error("Cleanup candidate set changed after preview.");let s=e.cleanup?.find((u)=>u.kind===o.kind);if(!s)throw Error(`No ${o.kind} cleanup driver is configured.`);e.store.updateCleanup(o.id,{status:"running"});let c=[],d=[];for(let u of o.candidates){i.throwIfCancellationRequested();try{await s.remove(u),c.push(u.id)}catch(m){d.push({id:u.id,error:m instanceof Error?m.message:String(m)})}}let a=d.length?c.length?"partial":"failed":"succeeded";if(e.store.updateCleanup(o.id,{status:a,result:{removed:c,failed:d,reclaimedBytes:o.candidates.filter((u)=>c.includes(u.id)).reduce((u,m)=>u+m.bytes,0)}}),d.length)throw Error(`Cleanup failed for ${d.length} candidate(s).`);return{planId:o.id,removed:c.length,reclaimedBytes:o.estimatedBytes}},"maintenance.drill":async(i)=>{let o=e.store.drill(String(Fl(i.operation.input).drillId??""));if(!o)throw Error("DR drill was not found.");let s=e.recovery?.find((m)=>m.scenario===o.scenario);if(!s)throw Error(`No ${o.scenario} recovery driver is configured.`);let c=new Date;e.store.updateDrill(o.id,{status:"restoring",startedAt:c.toISOString()});let d=o.isolatedTarget,a={},u={};try{i.checkpoint("restore","Restoring into isolated drill target.");let m=await s.restore({drill:o,signal:i.signal});if(!m.target.startsWith("isolated://"))throw Error("Recovery driver attempted a non-isolated target.");d=m.target,a=m.evidence;let h=(c.getTime()-new Date(m.recoveryPointAt).getTime())/60000;e.store.updateDrill(o.id,{status:"verifying",measuredRpoMinutes:h,evidence:{restore:a}}),i.checkpoint("verify","Running recovery health checks without production traffic.");let y=await s.verify({drill:o,target:d});u=y.evidence;let w=(Date.now()-c.getTime())/60000;if(!y.healthy||h>o.expectedRpoMinutes||w>o.expectedRtoMinutes)throw Error("DR drill failed its health, RPO, or RTO objective.");e.store.updateDrill(o.id,{measuredRpoMinutes:h,measuredRtoMinutes:w,evidence:{restore:a,verify:u}})}catch(m){throw e.store.updateDrill(o.id,{status:"failed",error:m instanceof Error?m.message:String(m),evidence:{restore:a,verify:u}}),m}finally{e.store.updateDrill(o.id,{status:"cleaning"});try{await s.cleanup({drill:o,target:d});let m=e.store.drill(o.id);e.store.updateDrill(o.id,{status:m.error?"failed":"passed",cleanupVerified:!0,finishedAt:new Date().toISOString()})}catch(m){e.store.updateDrill(o.id,{status:"cleanup_required",cleanupVerified:!1,error:m instanceof Error?m.message:String(m),finishedAt:new Date().toISOString()})}}return{drillId:o.id,status:e.store.drill(o.id).status}}}}class QR{transport;constructor(e){this.transport=e}download(e){return this.transport.download({target:e.target.target,url:e.artifact.url,signal:e.signal})}install(e){return this.transport.install({target:e.target.target,path:e.path,version:e.version,signal:e.signal})}health(e){return this.transport.health({target:e.target.target,gate:e.gate})}rollback(e){return this.transport.rollback({target:e.target.target,version:e.version,signal:e.signal})}}var Wh={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 zl{kind;control;projectId;organizationId;constructor(e,t,r,n){this.kind=e;this.control=t;this.projectId=r;this.organizationId=n}async discover(e){let t=Math.max(1,Math.min(3650,Number(e.olderThanDays??30))),r=new Date(Date.now()-t*86400000).toISOString(),n=Wh[this.kind],i=this.kind==="artifacts"?this.organizationId:this.projectId;return this.control.database.query(n.select).all(i,r).map((s)=>({id:String(s.id),kind:this.kind,label:`${this.kind}:${String(s.id)}`,bytes:Number(s.bytes??0),metadata:{createdAt:String(s.created_at)}}))}async remove(e){if(this.control.database.run(Wh[this.kind].remove,[e.id]).changes!==1)throw Error(`${e.label} changed or is no longer removable.`)}}class YR{scenario;transport;constructor(e,t){this.scenario=e;this.transport=t}restore(e){return this.transport.restore({scenario:this.scenario,...e})}verify(e){return this.transport.verify({scenario:this.scenario,...e})}cleanup(e){return this.transport.cleanup({scenario:this.scenario,...e})}}var nr=(e,t)=>{try{return JSON.parse(String(e))}catch{return t}},Nt=(e)=>e==null?void 0:String(e),Jh=()=>({cpu:0,memoryBytes:0,diskBytes:0,gpu:0}),Bi=(e={})=>({...Jh(),...e});function Hh(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),name:String(e.name),purpose:String(e.purpose),backend:String(e.backend),region:Nt(e.region),architecture:Nt(e.architecture),labels:nr(e.labels,{}),requiredServerLabels:nr(e.required_server_labels,{}),toleratedTaints:nr(e.tolerated_taints,[]),capacity:Bi(nr(e.capacity,{})),reserved:nr(e.reserved,{}),maxWorkloads:Number(e.max_workloads),costWeight:Number(e.cost_weight),spreadKey:Nt(e.spread_key),concurrency:Number(e.concurrency),ephemeralWorkspaces:Number(e.ephemeral_workspaces)===1,allowProductionSecrets:Number(e.allow_production_secrets)===1,status:String(e.status),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Kh(e){return{id:String(e.id),projectId:String(e.project_id),environmentId:Nt(e.environment_id),resourceId:String(e.resource_id),releaseId:Nt(e.release_id),poolId:String(e.pool_id),serverId:Nt(e.server_id),purpose:String(e.purpose),requirements:nr(e.requirements,{}),decision:nr(e.decision,{}),stateful:Number(e.stateful)===1,autoReschedule:Number(e.auto_reschedule)===1,status:String(e.status),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function ZR(e){return{id:String(e.id),projectId:String(e.project_id),resourceId:Nt(e.resource_id),poolId:String(e.pool_id),placementId:Nt(e.placement_id),operationId:Nt(e.operation_id),sourceSha:String(e.source_sha),buildSpec:nr(e.build_spec,{}),credentialPolicy:nr(e.credential_policy,{productionSecrets:!1,shortLivedTokenExpiresAt:""}),workspace:Nt(e.workspace),cacheKey:Nt(e.cache_key),artifactUri:Nt(e.artifact_uri),artifactDigest:Nt(e.artifact_digest),status:String(e.status),cleanupAt:Nt(e.cleanup_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}class Ul{control;now;id;constructor(e,t=()=>new Date,r=()=>crypto.randomUUID()){this.control=e;this.now=t;this.id=r}createPool(e){let t=this.id(),r=this.now().toISOString();return this.control.database.run("INSERT INTO capacity_pools (id,organization_id,project_id,name,purpose,backend,region,architecture,labels,required_server_labels,tolerated_taints,capacity,reserved,max_workloads,cost_weight,spread_key,concurrency,ephemeral_workspaces,allow_production_secrets,status,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.organizationId,e.projectId,e.name,e.purpose,e.backend,e.region??null,e.architecture??null,JSON.stringify(e.labels),JSON.stringify(e.requiredServerLabels),JSON.stringify(e.toleratedTaints),JSON.stringify(Bi(e.capacity)),"{}",e.maxWorkloads,e.costWeight,e.spreadKey??null,e.concurrency,e.ephemeralWorkspaces?1:0,e.allowProductionSecrets?1:0,e.status,r,r]),this.getPool(t)}getPool(e){let t=this.control.database.query("SELECT * FROM capacity_pools WHERE id=?").get(e);return t?Hh(t):void 0}listPools(e){return this.control.database.query("SELECT * FROM capacity_pools WHERE project_id=? ORDER BY name").all(e).map(Hh)}updatePool(e,t){let r=this.getPool(e);if(!r)throw Error("Capacity pool was not found.");let n={...r,...t},i=this.now().toISOString();return this.control.database.run("UPDATE capacity_pools SET status=?,reserved=?,capacity=?,concurrency=?,version=version+1,updated_at=? WHERE id=?",[n.status,JSON.stringify(n.reserved),JSON.stringify(n.capacity),n.concurrency,i,e]),this.getPool(e)}addMember(e,t,r={}){let n=this.now().toISOString();this.control.database.run("INSERT INTO capacity_pool_members (pool_id,server_id,capacity_override,status,created_at,updated_at) VALUES (?,?,?,'active',?,?) ON CONFLICT(pool_id,server_id) DO UPDATE SET capacity_override=excluded.capacity_override,status='active',updated_at=excluded.updated_at",[e,t,JSON.stringify(r),n,n])}members(e){return this.control.database.query("SELECT * FROM capacity_pool_members WHERE pool_id=? ORDER BY server_id").all(e).map((t)=>({serverId:String(t.server_id),status:String(t.status),capacityOverride:nr(t.capacity_override,{})}))}memberStatus(e,t,r){this.control.database.run("UPDATE capacity_pool_members SET status=?,updated_at=? WHERE pool_id=? AND server_id=?",[r,this.now().toISOString(),e,t])}listPlacements(e,t){let r=this.control.database.query("SELECT * FROM workload_placements WHERE project_id=? ORDER BY created_at,id").all(e).map(Kh);return t?.length?r.filter((n)=>t.includes(n.status)):r}getPlacement(e){let t=this.control.database.query("SELECT * FROM workload_placements WHERE id=?").get(e);return t?Kh(t):void 0}activeUsage(e,t){let r=this.control.database.query("SELECT l.resources,l.server_id FROM capacity_leases l WHERE l.pool_id=? AND l.state='active' AND l.expires_at>?").all(e,this.now().toISOString()),n=t?r.filter((i)=>String(i.server_id)===t):r;return{resources:n.reduce((i,o)=>{let s=Bi(nr(o.resources,{}));for(let c of Object.keys(i))i[c]+=s[c];return i},Jh()),count:n.length}}expireLeases(){return this.control.database.run("UPDATE capacity_leases SET state='expired',updated_at=? WHERE state='active' AND expires_at<=?",[this.now().toISOString(),this.now().toISOString()]).changes}reserve(e){return this.control.transaction(()=>{this.expireLeases();let t=this.id(),r=this.id(),n=this.now().toISOString(),i=new Date(this.now().getTime()+(e.requirements.leaseSeconds??300)*1000).toISOString();return this.control.database.run("INSERT INTO workload_placements (id,project_id,environment_id,resource_id,release_id,pool_id,server_id,purpose,requirements,decision,stateful,auto_reschedule,status,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,'reserved',?,?)",[t,e.projectId,e.environmentId??null,e.resourceId,e.releaseId??null,e.decision.poolId,e.decision.serverId??null,e.requirements.purpose,JSON.stringify(e.requirements),JSON.stringify(e.decision),e.requirements.stateful?1:0,e.requirements.autoReschedule&&!e.requirements.stateful?1:0,n,n]),this.control.database.run("INSERT INTO capacity_leases (id,placement_id,pool_id,server_id,resources,state,expires_at,created_at,updated_at) VALUES (?,?,?,?,?,'active',?,?,?)",[r,t,e.decision.poolId,e.decision.serverId??null,JSON.stringify(Bi(e.requirements.resources)),i,n,n]),this.getPlacement(t)})}transitionPlacement(e,t){if(!this.getPlacement(e))throw Error("Placement was not found.");let n=this.now().toISOString();if(this.control.database.run("UPDATE workload_placements SET status=?,version=version+1,updated_at=? WHERE id=?",[t,n,e]),["released","failed","blocked"].includes(t))this.control.database.run("UPDATE capacity_leases SET state='released',updated_at=? WHERE placement_id=? AND state='active'",[n,e]);return this.getPlacement(e)}createBuild(e){let t=this.id(),r=this.now().toISOString();return this.control.database.run("INSERT INTO remote_builds (id,project_id,resource_id,pool_id,placement_id,operation_id,source_sha,build_spec,credential_policy,status,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,'queued',?,?)",[t,e.projectId,e.resourceId??null,e.poolId,e.placementId??null,e.operationId??null,e.sourceSha,JSON.stringify(e.buildSpec),JSON.stringify({productionSecrets:!1,shortLivedTokenExpiresAt:e.tokenExpiresAt}),r,r]),this.getBuild(t)}getBuild(e){let t=this.control.database.query("SELECT * FROM remote_builds WHERE id=?").get(e);return t?ZR(t):void 0}updateBuild(e,t){let r=this.getBuild(e);if(!r)throw Error("Remote build was not found.");let n={...r,...t},i=this.now().toISOString();return this.control.database.run("UPDATE remote_builds SET operation_id=?,workspace=?,cache_key=?,artifact_uri=?,artifact_digest=?,status=?,cleanup_at=?,updated_at=? WHERE id=?",[n.operationId??null,n.workspace??null,n.cacheKey??null,n.artifactUri??null,n.artifactDigest??null,n.status,n.cleanupAt??null,i,e]),this.getBuild(e)}}var Pa=["cpu","memoryBytes","diskBytes","gpu"],Gh=(e,t={})=>Object.entries(t).every(([r,n])=>e[r]===n),XR=(e,t,r)=>Object.fromEntries(Pa.map((n)=>[n,Math.max(0,e[n]-t[n]-(r[n]??0))])),eA=(e,t)=>Pa.every((r)=>e[r]>=(t[r]??0)),tA=(e,t)=>Pa.reduce((r,n)=>r+(t[n]??0)/(e[n]||1),0);class ql{store;fleet;constructor(e,t){this.store=e;this.fleet=t}poolCandidates(e,t,r){let n=[];for(let i of this.store.listPools(e)){if(i.id===r)continue;let o=[];if(i.status!=="active")o.push(`pool is ${i.status}`);if(i.purpose!==t.purpose)o.push(`purpose is ${i.purpose}`);if(t.region&&i.region!==t.region)o.push(`region is ${i.region??"unset"}`);if(t.architecture&&i.architecture!==t.architecture)o.push(`architecture is ${i.architecture??"unset"}`);if(!Gh(i.labels,t.labels))o.push("pool labels do not match");if(i.backend==="server"){let s=this.store.members(i.id);if(!s.length)n.push(this.decision(i,void 0,t,[...o,"pool has no servers"]));for(let c of s){let d=this.fleet.get(c.serverId),a=[...o];if(!d)a.push("server is missing");else this.serverReasons(i,d,c.status,t,a);n.push(this.decision(i,d,t,a,c.capacityOverride))}}else n.push(this.decision(i,void 0,t,o))}return n.sort((i,o)=>Number(o.eligible)-Number(i.eligible)||i.score.cost-o.score.cost||i.score.spread-o.score.spread||i.score.fit-o.score.fit||i.poolName.localeCompare(o.poolName)||(i.serverId??"").localeCompare(o.serverId??""))}serverReasons(e,t,r,n,i){if(r!=="active")i.push(`member is ${r}`);if(t.status!=="ready")i.push(`server is ${t.status}`);if(!t.roles.includes(n.purpose==="build"?"build":n.purpose))i.push(`server lacks ${n.purpose} role`);if(!Gh(t.labels,e.requiredServerLabels))i.push("server labels do not match pool selector");for(let o of t.taints)if(!e.toleratedTaints.includes(o))i.push(`taint ${o} is not tolerated`)}decision(e,t,r,n,i={}){let o=Bi({...t?.capacity,...i}),s=t?Object.fromEntries(Pa.map((a)=>[a,Math.min(e.capacity[a],o[a])])):e.capacity,c=this.store.activeUsage(e.id,t?.id),d=XR(s,c.resources,e.reserved);if(c.count>=e.maxWorkloads)n.push("workload limit reached");if(r.purpose==="build"&&c.count>=e.concurrency)n.push("build concurrency reached");if(!eA(d,r.resources))n.push("insufficient capacity");return{poolId:e.id,poolName:e.name,serverId:t?.id,eligible:n.length===0,reasons:n,available:d,score:{fit:tA(d,r.resources),spread:c.count,cost:e.costWeight}}}explain(e,t){return this.poolCandidates(e,t)}place(e){return this.store.control.transaction(()=>{let t=this.poolCandidates(e.projectId,e.requirements).find((r)=>r.eligible);if(!t)throw Error(`No eligible capacity: ${this.explain(e.projectId,e.requirements).flatMap((r)=>r.reasons).join("; ")}`);return this.store.reserve({...e,decision:t})})}activate(e){return this.store.transitionPlacement(e,"active")}release(e){return this.store.transitionPlacement(e,"released")}drainPool(e){let t=this.store.updatePool(e,{status:"draining"}),r=[],n=[];for(let i of this.store.listPlacements(t.projectId,["reserved","active"]).filter((o)=>o.poolId===e)){if(i.stateful){n.push(this.store.transitionPlacement(i.id,"blocked"));continue}this.store.transitionPlacement(i.id,"moving");let o=this.place({projectId:i.projectId,environmentId:i.environmentId,resourceId:i.resourceId,releaseId:i.releaseId,requirements:i.requirements});r.push(this.activate(o.id)),this.store.transitionPlacement(i.id,"released")}return{pool:t,moved:r,blocked:n}}drainServer(e,t){this.store.memberStatus(e,t,"draining");let r=this.store.getPool(e);if(!r)throw Error("Capacity pool was not found.");let n=[],i=[];for(let o of this.store.listPlacements(r.projectId,["reserved","active"]).filter((s)=>s.poolId===e&&s.serverId===t)){if(o.stateful){i.push(this.store.transitionPlacement(o.id,"blocked"));continue}this.store.transitionPlacement(o.id,"moving");let s=this.poolCandidates(o.projectId,o.requirements).find((d)=>d.eligible);if(!s){i.push(this.store.transitionPlacement(o.id,"blocked"));continue}let c=this.store.reserve({projectId:o.projectId,environmentId:o.environmentId,resourceId:o.resourceId,releaseId:o.releaseId,requirements:o.requirements,decision:s});n.push(this.activate(c.id)),this.store.transitionPlacement(o.id,"released")}return{moved:n,blocked:i}}reconcileFailure(e){let t=this.fleet.get(e);if(!t)throw Error("Server was not found.");let r=[],n=[];for(let i of this.store.listPlacements(t.projectId,["active"]).filter((o)=>o.serverId===e)){if(i.stateful||!i.autoReschedule){n.push(this.store.transitionPlacement(i.id,"blocked"));continue}this.store.transitionPlacement(i.id,"failed");let o=this.place({projectId:i.projectId,environmentId:i.environmentId,resourceId:i.resourceId,releaseId:i.releaseId,requirements:i.requirements});r.push(this.activate(o.id))}return{rescheduled:r,blocked:n}}}class rA{store;placement;now;queue;constructor(e,t,r,n=()=>new Date){this.store=e;this.placement=t;this.now=n;this.queue=r??new $e(e.control)}enqueue(e){if(!/^[a-f0-9]{7,64}$/i.test(e.sourceSha))throw Error("A pinned source commit SHA is required.");let t={purpose:"build",resources:{cpu:1,memoryBytes:1073741824,diskBytes:5368709120},leaseSeconds:3600,...e.requirements},r=this.placement.place({projectId:e.projectId,resourceId:e.resourceId,requirements:t}),n=new Date(this.now().getTime()+900000).toISOString(),i=this.store.createBuild({projectId:e.projectId,resourceId:e.resourceId,poolId:r.poolId,placementId:r.id,sourceSha:e.sourceSha,buildSpec:e.buildSpec,tokenExpiresAt:n}),o=this.queue.enqueue({projectId:e.projectId,resourceId:e.resourceId,kind:"build.remote",input:{buildId:i.id},lockKey:`build:${i.id}`,providerKey:`pool:${r.poolId}`,buildSlot:!0,timeoutSeconds:3600,cancellationMode:"cooperative",resumePolicy:"fail"}).operation;return i=this.store.updateBuild(i.id,{operationId:o.id}),i}cancel(e){let t=this.store.getBuild(e);if(!t)throw Error("Remote build was not found.");if(t.operationId)this.queue.requestCancellation(t.operationId);return this.store.updateBuild(e,{status:"cancelled"})}}var nA=/^sha256:[a-f0-9]{64}$/,iA=/^(?:s3|https|oci):\/\//;function Tj(e,t){return{"build.remote":async(r)=>{let n=r.operation.input&&typeof r.operation.input==="object"&&!Array.isArray(r.operation.input)?r.operation.input:{},i=e.getBuild(String(n.buildId??""));if(!i)throw Error("Queued remote build was not found.");let o=e.getPool(i.poolId);if(!o||o.purpose!=="build"||o.status!=="active")throw Error("The selected build pool is unavailable.");if(!o.ephemeralWorkspaces)throw Error("Remote builds require an ephemeral workspace pool.");if(i.credentialPolicy.productionSecrets||o.allowProductionSecrets)throw Error("Production secrets are forbidden in remote build workers.");if(new Date(i.credentialPolicy.shortLivedTokenExpiresAt)<=new Date)throw Error("The short-lived build credential has expired.");let s=t.find((d)=>d.backend===o.backend);if(!s)throw Error(`No ${o.backend} remote build driver is configured.`);let c=`build://${o.id}/${i.id}`;e.updateBuild(i.id,{status:"running",workspace:c}),r.checkpoint("checkout",`Preparing isolated workspace for ${i.sourceSha}.`);try{r.throwIfCancellationRequested(),r.checkpoint("build","Executing resource-limited build.");let d=await s.run({build:e.getBuild(i.id),pool:o,signal:r.signal,log:(a)=>r.log(a,{stream:"stdout"})});if(r.throwIfCancellationRequested(),!nA.test(d.artifactDigest)||!iA.test(d.artifactUri))throw Error("Builder returned an unverified artifact reference.");return e.updateBuild(i.id,{status:"uploading",cacheKey:d.cacheKey,artifactUri:d.artifactUri,artifactDigest:d.artifactDigest}),r.checkpoint("verify","Verified content-addressed artifact upload."),await s.cleanup({build:e.getBuild(i.id),pool:o}),e.updateBuild(i.id,{status:"succeeded",workspace:void 0,cleanupAt:new Date().toISOString()}),{buildId:i.id,artifactUri:d.artifactUri,artifactDigest:d.artifactDigest,cacheKey:d.cacheKey??null}}catch(d){try{await s.cleanup({build:e.getBuild(i.id),pool:o}),e.updateBuild(i.id,{status:r.cancellationRequested()?"cancelled":"failed",workspace:void 0,cleanupAt:new Date().toISOString()})}catch{e.updateBuild(i.id,{status:"cleanup_required"})}throw d}}}}class _a{backend;transport;handles=new Map;constructor(e,t){this.backend=e;this.transport=t}async run({build:e,pool:t,signal:r,log:n}){let i=await this.transport.provision({backend:this.backend,pool:t,build:e,tokenExpiresAt:e.credentialPolicy.shortLivedTokenExpiresAt});return this.handles.set(e.id,i.handle),n(`${this.backend} builder provisioned`),await this.transport.execute({handle:i.handle,spec:e.buildSpec,sourceSha:e.sourceSha,signal:r,onLog:n}),this.transport.publish({handle:i.handle,sourceSha:e.sourceSha})}async cleanup({build:e}){let t=this.handles.get(e.id);if(!t)return;await this.transport.destroy({handle:t}),this.handles.delete(e.id)}}var Dj=(e)=>new _a("server",e),Oj=(e)=>new _a("ecs",e),$j=(e)=>new _a("asg",e);var Mr=(e,t)=>{try{return JSON.parse(String(e))}catch{return t}},Kt=(e)=>e==null?void 0:String(e),Qh=(e)=>({id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:Kt(e.environment_id),name:String(e.name),hostname:String(e.hostname),homeRegion:String(e.home_region),regions:Mr(e.regions,[]),trafficPolicy:String(e.traffic_policy),dataPolicy:Mr(e.data_policy,{replicate:[],maxLagSeconds:60,retainOnDestroy:!0}),status:String(e.status),activeRegion:String(e.active_region),revision:Kt(e.revision),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),Vl=(e)=>({id:String(e.id),topologyId:String(e.topology_id),region:String(e.region),role:String(e.role),provider:String(e.provider),stackId:Kt(e.stack_id),stackRevision:Kt(e.stack_revision),status:String(e.status),health:Mr(e.health,{}),lastHealthyAt:Kt(e.last_healthy_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),Wl=(e)=>({id:String(e.id),topologyId:String(e.topology_id),kind:String(e.kind),sourceRegion:String(e.source_region),targetRegion:String(e.target_region),config:Mr(e.config,{}),status:String(e.status),checkpoint:Kt(e.checkpoint),lagSeconds:e.lag_seconds==null?void 0:Number(e.lag_seconds),lastVerifiedAt:Kt(e.last_verified_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),Hl=(e)=>({id:String(e.id),topologyId:String(e.topology_id),hostname:String(e.hostname),dnsProvider:String(e.dns_provider),cdnEnabled:Number(e.cdn_enabled)===1,wafEnabled:Number(e.waf_enabled)===1,weights:Mr(e.weights,{}),desiredWeights:Mr(e.desired_weights,{}),status:String(e.status),providerState:Mr(e.provider_state,{}),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}),Yh=(e)=>({id:String(e.id),topologyId:String(e.topology_id),operationId:Kt(e.operation_id),kind:String(e.kind),requestedRegion:Kt(e.requested_region),revision:Kt(e.revision),plan:Mr(e.plan,[]),currentStep:Kt(e.current_step),completedSteps:Mr(e.completed_steps,[]),status:String(e.status),error:Kt(e.error),createdAt:String(e.created_at),updatedAt:String(e.updated_at)});class Kl{control;now;id;constructor(e,t=()=>new Date,r=()=>crypto.randomUUID()){this.control=e;this.now=t;this.id=r}create(e){return this.control.transaction(()=>{if(e.regions.length<2||new Set(e.regions.map((o)=>o.region)).size!==e.regions.length||e.regions.filter((o)=>o.role==="primary").length!==1)throw Error("A topology requires unique regions and exactly one primary.");let t=e.regions.find((o)=>o.role==="primary"),r=this.id(),n=this.now().toISOString();this.control.database.run("INSERT INTO regional_topologies (id,organization_id,project_id,environment_id,name,hostname,home_region,regions,traffic_policy,data_policy,status,active_region,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,'draft',?,?,?)",[r,e.organizationId,e.projectId,e.environmentId??null,e.name,e.hostname,t.region,JSON.stringify(e.regions),e.trafficPolicy,JSON.stringify(e.dataPolicy),t.region,n,n]);for(let o of e.regions)this.control.database.run("INSERT INTO regional_targets (id,topology_id,region,role,provider,status,created_at,updated_at) VALUES (?,?,?,?,?,'pending',?,?)",[this.id(),r,o.region,o.role,o.provider,n,n]);for(let o of e.dataPolicy.replicate)for(let s of e.regions)for(let c of e.regions.filter((d)=>d.region!==s.region))this.control.database.run("INSERT INTO regional_replication_channels (id,topology_id,kind,source_region,target_region,config,status,created_at,updated_at) VALUES (?,?,?,?,?,?,'pending',?,?)",[this.id(),r,o,s.region,c.region,"{}",n,n]);let i=Object.fromEntries(e.regions.map((o)=>[o.region,o.region===t.region?100:0]));return this.control.database.run("INSERT INTO regional_traffic_routes (id,topology_id,hostname,dns_provider,cdn_enabled,waf_enabled,weights,desired_weights,status,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?, 'pending',?,?)",[this.id(),r,e.hostname,e.dnsProvider??"route53",e.cdnEnabled?1:0,e.wafEnabled?1:0,JSON.stringify(i),JSON.stringify(i),n,n]),this.get(r)})}get(e){let t=this.control.database.query("SELECT * FROM regional_topologies WHERE id=?").get(e);return t?Qh(t):void 0}list(e){return this.control.database.query("SELECT * FROM regional_topologies WHERE project_id=? ORDER BY name").all(e).map(Qh)}targets(e){return this.control.database.query("SELECT * FROM regional_targets WHERE topology_id=? ORDER BY role,region").all(e).map(Vl)}channels(e){return this.control.database.query("SELECT * FROM regional_replication_channels WHERE topology_id=? ORDER BY kind,target_region").all(e).map(Wl)}route(e){let t=this.control.database.query("SELECT * FROM regional_traffic_routes WHERE topology_id=?").get(e);return t?Hl(t):void 0}updateTopology(e,t){let r=this.get(e);if(!r)throw Error("Regional topology was not found.");let n={...r,...t},i=this.now().toISOString();return this.control.database.run("UPDATE regional_topologies SET status=?,active_region=?,revision=?,regions=?,version=version+1,updated_at=? WHERE id=?",[n.status,n.activeRegion,n.revision??null,JSON.stringify(n.regions),i,e]),this.get(e)}updateTarget(e,t){let r=this.control.database.query("SELECT * FROM regional_targets WHERE id=?").get(e);if(!r)throw Error("Regional target was not found.");let n=Vl(r),i={...n,...t},o=this.now().toISOString();return this.control.database.run("UPDATE regional_targets SET role=?,stack_id=?,stack_revision=?,status=?,health=?,last_healthy_at=?,version=version+1,updated_at=? WHERE id=?",[i.role,i.stackId??null,i.stackRevision??null,i.status,JSON.stringify(i.health),i.lastHealthyAt??null,o,e]),Vl(this.control.database.query("SELECT * FROM regional_targets WHERE id=?").get(e))}updateChannel(e,t){let r=this.control.database.query("SELECT * FROM regional_replication_channels WHERE id=?").get(e);if(!r)throw Error("Replication channel was not found.");let n=Wl(r),i={...n,...t},o=this.now().toISOString();return this.control.database.run("UPDATE regional_replication_channels SET status=?,checkpoint=?,lag_seconds=?,last_verified_at=?,version=version+1,updated_at=? WHERE id=?",[i.status,i.checkpoint??null,i.lagSeconds??null,i.lastVerifiedAt??null,o,e]),Wl(this.control.database.query("SELECT * FROM regional_replication_channels WHERE id=?").get(e))}updateRoute(e,t){let r=this.control.database.query("SELECT * FROM regional_traffic_routes WHERE id=?").get(e);if(!r)throw Error("Traffic route was not found.");let n=Hl(r),i={...n,...t},o=this.now().toISOString();return this.control.database.run("UPDATE regional_traffic_routes SET weights=?,desired_weights=?,status=?,provider_state=?,version=version+1,updated_at=? WHERE id=?",[JSON.stringify(i.weights),JSON.stringify(i.desiredWeights),i.status,JSON.stringify(i.providerState),o,e]),Hl(this.control.database.query("SELECT * FROM regional_traffic_routes WHERE id=?").get(e))}createExecution(e){let t=this.id(),r=this.now().toISOString();return this.control.database.run("INSERT INTO regional_executions (id,topology_id,operation_id,kind,requested_region,revision,plan,status,created_at,updated_at) VALUES (?,?,?,?,?,?,?,'queued',?,?)",[t,e.topologyId,e.operationId??null,e.kind,e.requestedRegion??null,e.revision??null,JSON.stringify(e.plan),r,r]),this.execution(t)}execution(e){let t=this.control.database.query("SELECT * FROM regional_executions WHERE id=?").get(e);return t?Yh(t):void 0}executions(e){return this.control.database.query("SELECT * FROM regional_executions WHERE topology_id=? ORDER BY created_at DESC").all(e).map(Yh)}updateExecution(e,t){let r=this.execution(e);if(!r)throw Error("Regional execution was not found.");let n={...r,...t},i=this.now().toISOString();return this.control.database.run("UPDATE regional_executions SET operation_id=?,current_step=?,completed_steps=?,status=?,error=?,updated_at=? WHERE id=?",[n.operationId??null,n.currentStep??null,JSON.stringify(n.completedSteps),n.status,n.error??null,i,e]),this.execution(e)}}class Jl{store;queue;constructor(e,t){this.store=e;this.queue=t??new $e(e.control)}create(e){return this.store.create(e)}plan(e,t,r){if(!this.store.get(e))throw Error("Regional topology was not found.");let i=this.store.targets(e),o=this.store.channels(e);if(t==="rollout")return[...i.filter((s)=>s.role==="secondary").map((s)=>`apply:${s.region}`),...i.filter((s)=>s.role==="primary").map((s)=>`apply:${s.region}`),...o.map((s)=>`replicate:${s.kind}:${s.targetRegion}`),"traffic:activate"];if(t==="failover"||t==="failback")return[`health:${r}`,`replication:${r}`,`traffic:${r}`,`roles:${r}`];if(t==="destroy")return["traffic:drain",...i.filter((s)=>s.role==="secondary").map((s)=>`delete:${s.region}`),...i.filter((s)=>s.role==="primary").map((s)=>`delete:${s.region}`),"complete"];return["observe","repair"]}enqueue(e){let t=this.store.get(e.topologyId);if(!t)throw Error("Regional topology was not found.");if(["failover","failback"].includes(e.kind)&&(!e.targetRegion||!t.regions.some((o)=>o.region===e.targetRegion)))throw Error("A topology target region is required.");if(e.kind==="failover"&&e.targetRegion===t.activeRegion)throw Error("Target region is already active.");if((e.kind==="destroy"||e.deleteData)&&e.confirmation!==t.name)throw Error("Exact topology name confirmation is required.");if(e.deleteData&&t.dataPolicy.retainOnDestroy)throw Error("Topology policy requires regional data retention.");if(e.kind==="rollout"&&!/^[A-Za-z0-9._:@/-]{7,200}$/.test(e.revision??""))throw Error("An immutable revision is required.");let r=this.plan(t.id,e.kind,e.targetRegion),n=this.store.createExecution({topologyId:t.id,kind:e.kind,requestedRegion:e.targetRegion,revision:e.revision,plan:r}),i=this.queue.enqueue({projectId:t.projectId,environmentId:t.environmentId,kind:`region.${e.kind}`,input:{executionId:n.id,manifest:e.manifest??{},deleteData:e.deleteData===!0},lockKey:`regional-topology:${t.id}`,providerKey:"multi-region",timeoutSeconds:7200,cancellationMode:"provider_non_cancellable",resumePolicy:"requeue",maxAttempts:3}).operation;return this.store.updateExecution(n.id,{operationId:i.id}),{execution:this.store.execution(n.id),operation:i}}}var oA=(e)=>e&&typeof e==="object"&&!Array.isArray(e)?e:{};function Zh(e,t){let r=(a)=>{let u=t.find((m)=>m.provider===a.provider);if(!u)throw Error(`No ${a.provider} regional driver is configured.`);return u},n=(a,u,m)=>{a.throwIfCancellationRequested(),a.checkpoint(m,m),e.updateExecution(u.id,{status:"running",currentStep:m,completedSteps:[...e.execution(u.id).completedSteps,m]})},i=async(a,u)=>{let m=e.route(a.id);if(!m)throw Error("Regional traffic route was not found.");let h=e.targets(a.id).find((w)=>w.region===a.activeRegion)??e.targets(a.id)[0];if(!h)throw Error("Regional traffic target was not found.");e.updateRoute(m.id,{status:"applying",desiredWeights:u});let y=await r(h).applyTraffic({route:e.route(a.id),topology:a,weights:u});e.updateRoute(m.id,{status:Object.values(u).every((w)=>w===0)?"drained":"in_sync",weights:u,providerState:y.providerState})},o=async(a,u,m,h)=>{e.updateTopology(m.id,{status:"provisioning"});let y=u.revision,w=h.manifest??{},k=e.targets(m.id).sort((T,j)=>Number(T.role==="primary")-Number(j.role==="primary"));for(let T of k){n(a,u,`apply:${T.region}`),e.updateTarget(T.id,{status:"provisioning"});let j=await r(T).applyStack({target:T,revision:y,manifest:w,signal:a.signal}),P=await r(T).health({target:e.updateTarget(T.id,{stackId:j.stackId,stackRevision:y})});if(!P.healthy)throw Error(`Regional health gate failed in ${T.region}.`);e.updateTarget(T.id,{status:"ready",health:P.evidence,lastHealthyAt:new Date().toISOString()})}for(let T of e.channels(m.id)){n(a,u,`replicate:${T.kind}:${T.targetRegion}`),e.updateChannel(T.id,{status:"configuring"});let j=k.find((U)=>U.region===T.sourceRegion),P=await r(j).configureReplication({channel:T,topology:m}),O=await r(j).verifyReplication({channel:e.updateChannel(T.id,{checkpoint:P.checkpoint,lagSeconds:P.lagSeconds}),topology:m});if(!O.healthy||O.lagSeconds>m.dataPolicy.maxLagSeconds)throw Error(`${T.kind} replication to ${T.targetRegion} exceeds the RPO.`);e.updateChannel(T.id,{status:"in_sync",checkpoint:O.checkpoint,lagSeconds:O.lagSeconds,lastVerifiedAt:new Date().toISOString()})}n(a,u,"traffic:activate");let C=Object.fromEntries(m.regions.map((T)=>[T.region,T.region===m.activeRegion?100:0]));return await i(m,C),e.updateTopology(m.id,{status:"ready",revision:y}),{revision:y,activeRegion:m.activeRegion}},s=async(a,u,m)=>{let h=u.requestedRegion,y=e.targets(m.id).find((C)=>C.region===h);if(!y)throw Error("Requested regional target was not found.");e.updateTopology(m.id,{status:u.kind==="failover"?"failing_over":"failing_back"}),n(a,u,`health:${h}`);let w=await r(y).health({target:y});if(!w.healthy)throw Error(`Target region ${h} is unhealthy.`);e.updateTarget(y.id,{status:"ready",health:w.evidence,lastHealthyAt:new Date().toISOString()}),n(a,u,`replication:${h}`);for(let C of e.channels(m.id).filter((T)=>T.targetRegion===h)){let T=await r(y).verifyReplication({channel:C,topology:m});if(!T.healthy||T.lagSeconds>m.dataPolicy.maxLagSeconds)throw Error(`${C.kind} replication is outside the failover RPO.`);e.updateChannel(C.id,{status:"in_sync",checkpoint:T.checkpoint,lagSeconds:T.lagSeconds,lastVerifiedAt:new Date().toISOString()})}n(a,u,`traffic:${h}`),await i(m,Object.fromEntries(m.regions.map((C)=>[C.region,C.region===h?100:0]))),n(a,u,`roles:${h}`);let k=m.regions.map((C)=>({...C,role:C.region===h?"primary":"secondary"}));for(let C of e.targets(m.id))e.updateTarget(C.id,{role:C.region===h?"primary":"secondary"});return e.updateTopology(m.id,{status:u.kind==="failover"?"failed_over":"ready",activeRegion:h,regions:k}),{activeRegion:h}},c=async(a,u,m,h)=>{e.updateTopology(m.id,{status:"destroying"}),n(a,u,"traffic:drain"),await i(m,Object.fromEntries(m.regions.map((w)=>[w.region,0])));let y=h.deleteData!==!0;for(let w of e.targets(m.id).sort((k,C)=>Number(k.role==="primary")-Number(C.role==="primary")))n(a,u,`delete:${w.region}`),e.updateTarget(w.id,{status:"deleting"}),await r(w).deleteStack({target:w,retainData:y,signal:a.signal}),e.updateTarget(w.id,{status:"deleted"});return n(a,u,"complete"),e.updateTopology(m.id,{status:"destroyed"}),{destroyed:!0,dataRetained:y}},d=async(a)=>{let u=oA(a.operation.input),m=e.execution(String(u.executionId??""));if(!m)throw Error("Regional execution was not found.");let h=e.get(m.topologyId);if(!h)throw Error("Regional topology was not found.");try{let y;if(m.kind==="rollout")y=await o(a,m,h,u);else if(m.kind==="failover"||m.kind==="failback")y=await s(a,m,h);else if(m.kind==="destroy")y=await c(a,m,h,u);else throw Error("Regional reconciliation is not configured.");return e.updateExecution(m.id,{status:"succeeded",currentStep:void 0}),{executionId:m.id,...y}}catch(y){if(e.updateExecution(m.id,{status:a.cancellationRequested()?"cancelled":"failed",error:y instanceof Error?y.message:String(y)}),e.get(h.id)?.status!=="destroyed")e.updateTopology(h.id,{status:"failed"});throw y}};return{"region.rollout":d,"region.failover":d,"region.failback":d,"region.destroy":d,"region.reconcile":d}}class sA{transport;provider="aws";constructor(e){this.transport=e}async applyStack({target:e,revision:t,manifest:r}){return this.transport.applyCloudFormation({region:e.region,stackId:e.stackId,revision:t,manifest:r})}async deleteStack({target:e,retainData:t}){if(!e.stackId)return;await this.transport.deleteCloudFormation({region:e.region,stackId:e.stackId,retainData:t})}async health({target:e}){if(!e.stackId)return{healthy:!1,evidence:{reason:"stack is not provisioned"}};return this.transport.stackHealth({region:e.region,stackId:e.stackId})}async configureReplication({channel:e}){let t={sourceRegion:e.sourceRegion,targetRegion:e.targetRegion,config:e.config};if(e.kind==="s3")return this.transport.configureS3Replication(t);if(e.kind==="dynamodb")return this.transport.configureDynamoGlobalTable(t);return this.transport.replicateSecrets(t)}async verifyReplication({channel:e}){return this.transport.verifyReplication({kind:e.kind,sourceRegion:e.sourceRegion,targetRegion:e.targetRegion,checkpoint:e.checkpoint})}async applyTraffic({route:e,weights:t}){return this.transport.applyEdge({hostname:e.hostname,weights:t,route53:e.dnsProvider==="route53",cloudFront:e.cdnEnabled,waf:e.wafEnabled})}}class Gl{provider;reason;constructor(e,t="Configure a regional provider transport before executing this operation."){this.provider=e;this.reason=t}fail(){throw Error(this.reason)}async applyStack(){return this.fail()}async deleteStack(){this.fail()}async health(){return this.fail()}async configureReplication(){return this.fail()}async verifyReplication(){return this.fail()}async applyTraffic(){return this.fail()}}function hr(e,t,r){return[e,t,r].map((n)=>encodeURIComponent(n)).join(":")}function aA(e){return Object.fromEntries(["start","stop","restart","redeploy","scale","logs","exec","inspect","files"].map((t)=>[t,{supported:!1,reason:e}]))}function Jn(e,t,r=["exec","files"]){let n=aA(t);for(let i of e)n[i]={supported:!0,requiresConfirmation:!["logs","inspect"].includes(i),requiresRecentAuth:r.includes(i)};return n}var cA=/(?:secret|password|passwd|token|api[_-]?key|private[_-]?key|credential|authorization|cookie)/i;function Lr(e){let t=String(e??"").trim().toLowerCase();if(["active","running","ready","healthy","available","steady","active:running"].includes(t))return"running";if(["activating","pending","provisioning","starting","created","initializing"].includes(t))return"starting";if(["deactivating","stopping","draining","terminating"].includes(t))return"stopping";if(["inactive","stopped","complete","completed","exited","disabled"].includes(t))return"stopped";if(["degraded","unhealthy","warning"].includes(t))return"degraded";if(["failed","dead","error","crashed","oomkilled"].includes(t))return"failed";return"unknown"}function Br(e){if(Array.isArray(e))return e.map((r)=>Br(r));if(!e||typeof e!=="object")return e;let t={};for(let[r,n]of Object.entries(e))t[r]=cA.test(r)?"[REDACTED]":Br(n);return t}function Gn(e,t=new Date){if(!e)return;let r=new Date(e).getTime();return Number.isFinite(r)?Math.max(0,Math.floor((t.getTime()-r)/1000)):void 0}function Xh(e){let t=Number(e);return Number.isFinite(t)&&t>=0?t:void 0}function dA(e){let t=String(e?.message??e);if(/(?:unauthorized|accessdenied|forbidden|credentials)/i.test(t))return"unauthorized";if(/(?:timeout|unreachable|econnrefused|enotfound|network)/i.test(t))return"unreachable";return"error"}async function ey(e,t={},r={}){let n=t.now??new Date,i=Math.max(100,r.timeoutMs??1e4),o=Math.max(1,r.staleAfterSeconds??60),s=await Promise.all(e.map(async(d)=>{try{let a=await Promise.race([d.discover({...t,now:n}),new Promise((u,m)=>setTimeout(()=>m(Error(`Runtime source ${d.id} timed out after ${i}ms`)),i))]);return{workloads:a,source:{id:d.id,provider:d.provider,status:"fresh",discoveredAt:n.toISOString(),staleAfterSeconds:o,itemCount:a.length}}}catch(a){return{workloads:[],source:{id:d.id,provider:d.provider,status:dA(a),discoveredAt:n.toISOString(),staleAfterSeconds:o,itemCount:0,message:String(a?.message??a).slice(0,500)}}}})),c=s.map((d)=>d.source);return{generatedAt:n.toISOString(),workloads:s.flatMap((d)=>d.workloads).sort((d,a)=>d.name.localeCompare(a.name)||d.id.localeCompare(a.id)),sources:c,degraded:c.some((d)=>d.status!=="fresh")}}function Li(e){return e?.split("/").at(-1)??e?.split(":").at(-1)??"unknown"}function ty(e,t,r,n="ecs:aws",i=[]){let o=r.now??new Date;return e.map((s)=>{let c=s.serviceName??Li(s.serviceArn),d=t.filter((T)=>!s.clusterArn||T.clusterArn===s.clusterArn),a=d.some((T)=>!!T.group)?d.filter((T)=>T.group===`service:${c}`):d,u=s.status==="ACTIVE"?(s.runningCount??0)<(s.desiredCount??0)?"degraded":"running":Lr(s.status),m=i.find((T)=>T.taskDefinitionArn===s.taskDefinition),h=Array.isArray(m?.containerDefinitions)?m.containerDefinitions:[],y=[...new Set(h.map((T)=>T.logConfiguration?.options?.["awslogs-group"]).filter((T)=>typeof T==="string"))],w=h.flatMap((T)=>(T.mountPoints??[]).map((j)=>({source:j.sourceVolume,target:j.containerPath,type:"volume",readOnly:!!j.readOnly}))),k=h.flatMap((T)=>(T.portMappings??[]).map((j,P)=>({id:`${T.name??"container"}:${P}`,name:T.name,mode:m?.networkMode,ports:[{container:j.containerPort,host:j.hostPort,protocol:j.protocol}]}))),C=r.project&&r.environment&&c.startsWith(`${r.project}-${r.environment}-`)?c.slice(`${r.project}-${r.environment}-`.length):c;return{id:hr("ecs",n,s.serviceArn??c),provider:"ecs",kind:"service",name:c,status:u,rawStatus:s.status,health:u==="running"?"healthy":u==="failed"||u==="degraded"?"unhealthy":"unknown",desiredReplicas:s.desiredCount,runningReplicas:s.runningCount,image:h[0]?.image,runtime:s.launchType??"ECS",version:Li(s.taskDefinition),ageSeconds:Gn(s.deployments?.[0]?.createdAt,o),restartCount:0,tags:{},links:{project:r.project,environment:r.environment,service:C,release:Li(s.taskDefinition),providerId:s.serviceArn},replicas:a.map((T)=>{let j=Lr(T.lastStatus);return{id:hr("ecs",n,T.taskArn??Li(T.taskArn)),name:Li(T.taskArn),status:j,rawStatus:T.lastStatus,createdAt:T.createdAt,startedAt:T.startedAt,stoppedAt:T.stoppedAt,host:T.containerInstanceArn,containers:(T.containers??[]).map((P)=>({id:P.containerArn??P.name??"container",name:P.name??"container",image:h.find((O)=>O.name===P.name)?.image,imageDigest:P.imageDigest,status:Lr(P.lastStatus),rawStatus:P.lastStatus,exitCode:P.exitCode,reason:P.reason,runtime:"ecs"}))}}),networks:k,mounts:w,capabilities:Jn(["start","stop","restart","redeploy","scale","inspect",...y.length?["logs"]:[]],"This ECS runtime does not expose exec or file transfer; logs require an awslogs task-definition driver"),config:Br({clusterArn:s.clusterArn,taskDefinition:s.taskDefinition,launchType:s.launchType,pendingCount:s.pendingCount,deployments:s.deployments,logGroups:y,executionRoleArn:m?.executionRoleArn,taskRoleArn:m?.taskRoleArn,cpu:m?.cpu,memory:m?.memory}),discoveredAt:o.toISOString(),sourceId:n}})}function ry(e,t,r="lambda:aws"){let n=t.now??new Date;return e.map((i)=>{let o=i.FunctionName??Li(i.FunctionArn),s=i.State==="Active"?"running":Lr(i.State);return{id:hr("lambda",r,i.FunctionArn??o),provider:"lambda",kind:"function",name:o,status:s,rawStatus:i.State,health:s==="running"?"healthy":s==="failed"?"unhealthy":"unknown",desiredReplicas:void 0,runningReplicas:void 0,image:void 0,runtime:i.Runtime,version:i.Version,architecture:i.Architectures?.join(", "),ageSeconds:Gn(i.LastModified,n),restartCount:0,tags:{},links:{project:t.project,environment:t.environment,service:o,providerId:i.FunctionArn},resources:{memoryLimitBytes:i.MemorySize==null?void 0:i.MemorySize*1024*1024},replicas:[],networks:[],mounts:[],capabilities:Jn(["logs","inspect"],"Lambda has no persistent process to start, stop, restart, exec, or browse files; deploy a release to replace code"),config:Br({handler:i.Handler,timeout:i.Timeout,codeSize:i.CodeSize,stateReason:i.StateReason,environmentKeys:Object.keys(i.Environment?.Variables??{})}),discoveredAt:n.toISOString(),sourceId:r}})}function lA(e){let t=e.trim();if(!t)return[];let r=JSON.parse(t);if(!Array.isArray(r))throw Error("Docker inspect output must be an array");return r.filter((n)=>n&&typeof n.Id==="string")}function uA(e){let t=Object.entries(e.NetworkSettings?.Ports??{}).flatMap(([r,n])=>{let[i,o]=r.split("/");return(n??[]).map((s)=>({container:Number(i)||void 0,host:Number(s.HostPort)||void 0,protocol:o,address:s.HostIp}))});return Object.entries(e.NetworkSettings?.Networks??{}).map(([r,n])=>({id:n.NetworkID||r,name:r,mode:e.HostConfig?.NetworkMode,addresses:[n.IPAddress,n.GlobalIPv6Address].filter(Boolean),ports:t}))}function pA(e){return(e.Mounts??[]).filter((t)=>!!t.Destination).map((t)=>({source:t.Source,target:t.Destination,type:t.Type,readOnly:t.RW===!1}))}function mA(e,t,r=t.server??"local"){let n=t.now??new Date;return e.map((i)=>{let o=i.State?.OOMKilled?"oomkilled":i.State?.Restarting?"starting":i.State?.Status,s=Lr(o),c=(i.Name??i.Id.slice(0,12)).replace(/^\//,""),d=i.Config?.Labels??{},a=pA(i),u=uA(i),m={id:i.Id,name:c,image:i.Config?.Image,imageDigest:i.Image,runtime:"docker",status:s,rawStatus:o,exitCode:i.State?.ExitCode,reason:i.State?.Error,resources:{memoryLimitBytes:i.HostConfig?.Memory||void 0},networks:u,mounts:a};return{id:hr("docker",r,i.Id),provider:"docker",kind:"container",name:c,status:s,rawStatus:o,health:s==="running"?"healthy":s==="failed"?"unhealthy":"unknown",desiredReplicas:1,runningReplicas:s==="running"?1:0,image:i.Config?.Image,runtime:"docker",ageSeconds:Gn(i.State?.StartedAt,n),restartCount:i.RestartCount??0,tags:d,links:{project:t.project,environment:t.environment,server:t.server??r.replace(/^docker:/,""),service:d["com.docker.compose.service"]??d["ts-cloud.service"]??c,release:d["ts-cloud.release"],providerId:i.Id},resources:m.resources,replicas:[{id:hr("docker",r,`${i.Id}:0`),name:c,status:s,rawStatus:o,startedAt:i.State?.StartedAt,stoppedAt:i.State?.FinishedAt,restartCount:i.RestartCount,containers:[m],resources:m.resources}],networks:u,mounts:a,capabilities:Jn(["start","stop","restart","logs","exec","inspect","files"],"Use the owning Compose service for redeploy and scale"),config:Br({image:i.Config?.Image,labels:d,environmentKeys:(i.Config?.Env??[]).map((h)=>h.split("=",1)[0]),networkMode:i.HostConfig?.NetworkMode}),discoveredAt:n.toISOString(),sourceId:r}})}class Ql{inspect;id;provider="docker";constructor(e,t="docker:local"){this.inspect=e;this.id=t}async discover(e){return mA(lA(await this.inspect(e)),e,this.id)}}function gA(e){let t=[];for(let r of e.split(`
|
|
145
|
+
`)){if(!r.startsWith("TSCLOUD_SYSTEMD\t"))continue;let[,n,i,o,s,c,d,a,u,m,h,y,w,k]=r.split("\t");if(!n||!/^[A-Za-z0-9_.@:-]+\.service$/.test(n))continue;t.push({unit:n,load:i,active:o,sub:s,description:c,enabled:d,pid:Number(a)||void 0,memoryBytes:Xh(u),restartCount:Number(m)||0,activeSince:h||void 0,fragmentPath:y||void 0,workingDirectory:w?.startsWith("/")?w:void 0,user:k||void 0})}return t}function fA(e,t,r=t.server??"local"){let n=t.now??new Date;return e.map((i)=>{let o=Lr(i.active==="active"?i.sub||i.active:i.active),s=i.unit.replace(/\.service$/,""),c=/^(.*?) (?:release [^ ]+|queue worker|daemon |scheduler)(?: |$)/.exec(i.description??"")?.[1]??(t.project&&s.startsWith(`${t.project}-`)?s.slice(t.project.length+1).split("@",1)[0]:void 0),d=s.includes("@")?s.slice(s.indexOf("@")+1):void 0,a=i.workingDirectory?[{target:i.workingDirectory,type:"working-directory"}]:[],u=["start","stop","restart","logs","exec","inspect",...a.length?["files"]:[]];return{id:hr("systemd",r,i.unit),provider:"systemd",kind:"service",name:s,displayName:i.description||s,status:o,rawStatus:[i.load,i.active,i.sub].filter(Boolean).join("/"),health:o==="running"?"healthy":o==="failed"?"unhealthy":"unknown",desiredReplicas:1,runningReplicas:o==="running"?1:0,ageSeconds:Gn(i.activeSince,n),restartCount:i.restartCount,tags:{enabled:i.enabled??"unknown"},links:{project:t.project,environment:t.environment,server:t.server??r.replace(/^systemd:/,""),service:c,release:d,providerId:i.unit},resources:{memoryBytes:i.memoryBytes},replicas:[{id:hr("systemd",r,`${i.unit}:main`),name:"main",status:o,pid:i.pid,startedAt:i.activeSince,restartCount:i.restartCount,resources:{memoryBytes:i.memoryBytes}}],networks:[],mounts:a,capabilities:Jn(u,a.length?"This systemd runtime does not support redeploy or replica scaling through the scoped explorer":"File transfer requires a provider-reported service working directory; redeploy and scaling are unavailable"),config:Br({fragmentPath:i.fragmentPath,workingDirectory:i.workingDirectory,user:i.user,environment:i.environment,enabled:i.enabled}),discoveredAt:n.toISOString(),sourceId:r}})}class Yl{read;id;provider="systemd";constructor(e,t="systemd:local"){this.read=e;this.id=t}async discover(e){return fA(gA(await this.read(e)),e,this.id)}}function hA(e,t){if(!e.success)throw Error(e.error||e.perInstance?.[0]?.error||`${t} discovery failed`);return e.perInstance?.[0]?.output??""}function yA(){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 vA(){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 ny(e,t,r,n,i){let o=`${e}:${r.id}`,s=async()=>hA(await t.runRemoteDeploy({targets:[r],commands:e==="systemd"?yA():vA(),timeoutSeconds:30,comment:`ts-cloud runtime discovery:${e}`,tags:{Project:n.project.slug,Environment:i,Role:"app"}}),o);return e==="systemd"?new Yl(s,o):new Ql(s,o)}async function Ta(e,t=100){let r=[],n;for(let i=0;i<t;i++){let o=await e(n);if(r.push(...o.items),!o.nextToken)return r;n=o.nextToken}throw Error(`Provider pagination exceeded ${t} pages`)}class iy{client;prefix;id="ecs:aws";provider="ecs";constructor(e,t){this.client=e;this.prefix=t}async discover(e){let t=await Ta(async(o)=>{let s=await this.client.listClusters({nextToken:o,maxResults:100});return{items:s.clusterArns??[],nextToken:s.nextToken}}),r=[],n=[],i=[];for(let o of t){let s=(await Ta(async(c)=>{let d=await this.client.listServices(o,{nextToken:c,maxResults:100});return{items:d.serviceArns??[],nextToken:d.nextToken}})).filter((c)=>c.split("/").at(-1)?.startsWith(this.prefix));for(let c=0;c<s.length;c+=10){let d=await this.client.describeServices({cluster:o,services:s.slice(c,c+10)});r.push(...d.services??[])}for(let c of r.filter((d)=>d.clusterArn===o||!d.clusterArn)){let d=await Ta(async(a)=>{let u=await this.client.listTasks(o,c.serviceName,{nextToken:a,maxResults:100});return{items:u.taskArns??[],nextToken:u.nextToken}});for(let a=0;a<d.length;a+=100){let u=await this.client.describeTasks(o,d.slice(a,a+100));n.push(...u.tasks??[])}}}if(this.client.describeTaskDefinition)for(let o of[...new Set(r.map((s)=>s.taskDefinition).filter((s)=>!!s))]){let s=await this.client.describeTaskDefinition(o);if(s.taskDefinition)i.push(s.taskDefinition)}return ty(r,n,e,this.id,i)}}class oy{client;prefix;id="lambda:aws";provider="lambda";constructor(e,t){this.client=e;this.prefix=t}async discover(e){let t=(await Ta(async(r)=>{let n=await this.client.listFunctions({Marker:r,MaxItems:50});return{items:n.Functions??[],nextToken:n.NextMarker}})).filter((r)=>r.FunctionName?.startsWith(this.prefix));return ry(t,e,this.id)}}async function bA(e,t,r={}){let n=[],i=Fr(e),o=Zl(e),s=e.aws?.profile,c=e.aws?.region??e.project.region??"us-east-1",d=`${e.project.slug}-${t}`;if(i!=="serverless"){let a=r.driver??ir({config:e}),u=await a.findComputeTargets({slug:e.project.slug,environment:t,role:"app"});for(let m of u)n.push(ny("systemd",a,m,e,t)),n.push(ny("docker",a,m,e,t))}if(o==="aws")n.push(new iy(r.ecs??new xa(c,s),d)),n.push(new oy(r.lambda??new kt(c,s),d));return n}async function or(e,t,r={}){let n={project:e.project.slug,environment:t};try{return await ey(await bA(e,t,r),n)}catch(i){return{generatedAt:new Date().toISOString(),workloads:[],sources:[{id:"runtime:bootstrap",provider:Zl(e)==="aws"?"ecs":"systemd",status:"error",discoveredAt:new Date().toISOString(),staleAfterSeconds:60,itemCount:0,message:String(i?.message??i).slice(0,500)}],degraded:!0}}}var sy=65536,xo=49152,Oa=/^[A-Za-z0-9_.@:-]+\.service$/,$a=/^[a-fA-F0-9]{12,128}$/,SA=["/boot","/dev","/etc","/proc","/root","/run","/sys","/var/run"];function Fi(e){let t=Buffer.from(e);return t.byteLength<=sy?e:`${t.subarray(0,sy-24).toString("utf8")}
|
|
146
|
+
[output truncated]`}function Da(e){return{success:!1,instanceCount:0,perInstance:[],error:e instanceof Error?e.message:String(e)}}function Jt(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function wA(e,t){return Number.isFinite(e)?Math.min(1e4,Math.max(0,Math.floor(e))):t}function kA(e){let t=e.config,r=typeof t.clusterArn==="string"?t.clusterArn:void 0,n=e.links.providerId||e.name;return r&&n?{cluster:r,service:n}:void 0}function IA(e,t){return e.find((r)=>r.id===t.links.server)??(e.length===1?e[0]:void 0)}function EA(e,t){if(e.provider==="systemd"){let r=e.links.providerId;if(!r||!Oa.test(r)||!["start","stop","restart"].includes(t))return;return[`systemctl ${t} ${r}`,`systemctl is-active ${r} 2>/dev/null || true`]}if(e.provider==="docker"){let r=e.links.providerId;if(!r||!$a.test(r)||!["start","stop","restart"].includes(t))return;return[`docker ${t} ${r}`,`docker inspect --format '{{.State.Status}}' ${r}`]}return}function RA(e,t){if(!t.startsWith("/")||t.includes("\x00"))return{ok:!1,error:"An absolute path is required."};let r=[];for(let c of t.split("/")){if(!c||c===".")continue;if(c===".."){if(!r.length)return{ok:!1,error:"Path traversal is not allowed."};r.pop()}else r.push(c)}let n=`/${r.join("/")}`;if(SA.some((c)=>n===c||n.startsWith(`${c}/`)))return{ok:!1,error:"Sensitive host paths are not available through runtime file access."};let i=e.links.project?.replace(/[^A-Za-z0-9_-]/g,""),o=e.links.service?.replace(/[^A-Za-z0-9_-]/g,"");if(![...i&&o?[`/var/www/${i}/${o}`,`/srv/${i}/${o}`]:[],...e.mounts.map((c)=>c.target).filter((c)=>c.startsWith("/"))].some((c)=>n===c||n.startsWith(`${c.replace(/\/$/,"")}/`)))return{ok:!1,error:"Path is outside this service’s owned roots."};return{ok:!0,path:n}}function AA(e,t){let r=e.links.project?.replace(/[^A-Za-z0-9_-]/g,""),n=e.links.service?.replace(/[^A-Za-z0-9_-]/g,"");return[...r&&n?[`/var/www/${r}/${n}`,`/srv/${r}/${n}`]:[],...e.mounts.map((i)=>i.target).filter((i)=>i.startsWith("/"))].sort((i,o)=>o.length-i.length).find((i)=>t===i||t.startsWith(`${i.replace(/\/$/,"")}/`))}var ay={process:["ps","-eo","pid,ppid,user,%cpu,%mem,etime,command","--sort=-%cpu"],sockets:["ss","-lntup"],filesystem:["df","-h"]};class yr{config;environment;dependencies;region;profile;constructor(e,t,r={}){this.config=e;this.environment=t;this.dependencies=r;this.region=e.aws?.region??e.project.region??"us-east-1",this.profile=e.aws?.profile}async inventory(){return this.dependencies.inventory?.()??or(this.config,this.environment,{driver:this.dependencies.driver})}async workload(e){return(await this.inventory()).workloads.find((t)=>t.id===e)}async remote(e,t,r,n){let i=this.dependencies.driver??ir({config:this.config}),o=await i.findComputeTargets({slug:this.config.project.slug,environment:this.environment,role:"app"}),s=IA(o,e);if(!s)throw Error("The workload server is no longer reachable in this scope.");return i.runRemoteDeploy({targets:[s],commands:t,timeoutSeconds:r,comment:n,tags:{Project:this.config.project.slug,Environment:this.environment,Role:"app"}})}async run(e){let t=await this.workload(e.workloadId),r={workloadId:e.workloadId,action:e.action};if(!t)return{...r,ok:!1,error:"Workload was not found in the current project and environment."};let n=t.capabilities[e.action];if(!n.supported)return{...r,ok:!1,error:n.reason??`${e.action} is unsupported for ${t.provider}.`};if(n.requiresConfirmation&&e.confirm!==t.name)return{...r,ok:!1,error:`Type "${t.name}" to ${e.action} this workload.`};if(n.requiresRecentAuth&&!e.recentAuth)return{...r,ok:!1,error:"Sign in again before using elevated runtime access."};if(e.action==="inspect")return{...r,ok:!0,workload:t};if(t.provider==="systemd"||t.provider==="docker"){let i=EA(t,e.action);if(!i)return{...r,ok:!1,error:`${e.action} is not implemented for ${t.provider}.`};let o=await this.remote(t,["set -uo pipefail",...i],60,`ts-cloud runtime:${e.action}`).catch(Da);return{...r,ok:o.success,command:i[0],stdout:Fi(o.perInstance?.[0]?.output??""),stderr:Fi(o.perInstance?.[0]?.error??o.error??""),error:o.success?void 0:o.error??"Runtime operation failed."}}if(t.provider==="ecs"){let i=kA(t);if(!i)return{...r,ok:!1,error:"ECS cluster or service identity is unavailable."};let o=this.dependencies.ecs??new xa(this.region,this.profile);if(e.action==="scale"){let s=wA(e.replicas,t.desiredReplicas??1);return await o.scaleService(i.cluster,i.service,s),{...r,ok:!0,command:`ecs scale ${t.name} ${s}`}}if(e.action==="start"||e.action==="stop"){let s=e.action==="stop"?0:Math.max(1,t.desiredReplicas??1);return await o.scaleService(i.cluster,i.service,s),{...r,ok:!0,command:`ecs scale ${t.name} ${s}`}}if(e.action==="restart"||e.action==="redeploy")return await o.forceNewDeployment(i.cluster,i.service),{...r,ok:!0,command:`ecs redeploy ${t.name}`}}return{...r,ok:!1,error:`${e.action} is not implemented for ${t.provider}.`}}async exec(e){let t={workloadId:e.workloadId,preset:e.preset},r=await this.workload(e.workloadId);if(!r)return{...t,ok:!1,error:"Workload was not found in the current project and environment."};if(process.env.TS_CLOUD_RUNTIME_EXEC==="0")return{...t,ok:!1,error:"Runtime exec is disabled by TS_CLOUD_RUNTIME_EXEC."};if(!r.capabilities.exec.supported)return{...t,ok:!1,error:r.capabilities.exec.reason??"Exec is unsupported for this workload."};if(e.confirm!==r.name)return{...t,ok:!1,error:`Type "${r.name}" to open exec access.`};if(!e.recentAuth)return{...t,ok:!1,error:"Sign in again before using elevated runtime access."};let n=e.preset&&ay[e.preset];if(!n&&!e.command?.trim())return{...t,ok:!1,error:"Choose a diagnostic preset or provide a command."};if(e.command&&r.provider!=="docker")return{...t,ok:!1,error:"Free-form exec is restricted to isolated containers; use a diagnostic preset for system services."};let i=r.links.providerId??"",o;if(r.provider==="docker"&&$a.test(i)){let c=e.command?.trim()||n.map(Jt).join(" ");o=`docker exec ${i} sh -lc ${Jt(c)}`}else if(r.provider==="systemd"&&Oa.test(i)&&e.preset)o=e.preset==="process"?`systemctl status ${i} --no-pager --full`:ay[e.preset].map(Jt).join(" ");if(!o)return{...t,ok:!1,error:"Exec target identity is invalid or unsupported."};let s=await this.remote(r,["set -uo pipefail",o],60,"ts-cloud runtime:exec").catch(Da);return{...t,ok:s.success,command:o,stdout:Fi(s.perInstance?.[0]?.output??""),stderr:Fi(s.perInstance?.[0]?.error??s.error??""),error:s.success?void 0:s.error??"Exec command failed."}}async readFile(e){let t={workloadId:e.workloadId,path:e.path},r=await this.fileTarget(e);if("error"in r)return{...t,ok:!1,error:r.error};let{workload:n,path:i,root:o,providerId:s}=r,d=`sh -c ${Jt('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 ${Jt(i)} ${xo} ${Jt(o)}`,a=n.provider==="docker"?`docker exec ${s} ${d}`:d,u=await this.remote(n,[a],30,"ts-cloud runtime:file-read").catch(Da);if(!u.success)return{...t,ok:!1,error:u.error??u.perInstance?.[0]?.error??"File read failed."};let m=u.perInstance?.[0]?.output??"",h=/__TSCLOUD_SIZE__=(\d+)\r?\n/.exec(m);if(!h)return{...t,ok:!1,error:"The remote file response was invalid."};let y=Number(h[1]),w=m.slice((h.index??0)+h[0].length).replace(/\s+/g,"");if(Buffer.from(w,"base64").byteLength>xo)return{...t,ok:!1,error:"The remote file exceeded the transfer limit."};return{...t,ok:!0,contentBase64:w,size:y,truncated:y>xo}}async writeFile(e){let t={workloadId:e.workloadId,path:e.path},r=await this.fileTarget(e);if("error"in r)return{...t,ok:!1,error:r.error};if(!/^[A-Za-z0-9+/]*={0,2}$/.test(e.contentBase64))return{...t,ok:!1,error:"File content must be valid base64."};let n=Buffer.from(e.contentBase64,"base64");if(n.toString("base64")!==e.contentBase64)return{...t,ok:!1,error:"File content must be canonical base64."};if(n.byteLength>xo)return{...t,ok:!1,error:`File uploads are limited to ${xo} bytes.`};let{workload:i,path:o,root:s,providerId:c}=r,a=`sh -c ${Jt('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 ${Jt(o)} ${Jt(s)}`,u=i.provider==="docker"?`printf %s ${Jt(e.contentBase64)} | docker exec -i ${c} ${a}`:`printf %s ${Jt(e.contentBase64)} | ${a}`,m=await this.remote(i,[u],30,"ts-cloud runtime:file-write").catch(Da);return{...t,ok:m.success,size:n.byteLength,truncated:!1,error:m.success?void 0:m.error??m.perInstance?.[0]?.error??"File write failed."}}async fileTarget(e){let t=await this.workload(e.workloadId);if(!t)return{error:"Workload was not found in the current project and environment."};if(process.env.TS_CLOUD_RUNTIME_FILE_ACCESS==="0")return{error:"Runtime file access is disabled by TS_CLOUD_RUNTIME_FILE_ACCESS."};if(!t.capabilities.files.supported)return{error:t.capabilities.files.reason??"File access is unsupported for this workload."};if(e.confirm!==t.name)return{error:`Type "${t.name}" to access workload files.`};if(!e.recentAuth)return{error:"Sign in again before using elevated runtime access."};let r=RA(t,e.path);if(!r.ok)return{error:r.error};let n=AA(t,r.path),i=t.links.providerId??"";if(!n||t.provider==="systemd"&&!Oa.test(i)||t.provider==="docker"&&!$a.test(i))return{error:"File target identity is invalid or unsupported."};return{workload:t,path:r.path,root:n,providerId:i}}async logs(e,t={}){let r=await this.workload(e);if(!r)throw Error("Workload was not found in the current project and environment.");if(!r.capabilities.logs.supported)throw Error(r.capabilities.logs.reason??"Logs are unsupported for this workload.");let n=Math.min(1000,Math.max(1,Math.floor(t.limit??200)));if(r.provider==="lambda"||r.provider==="ecs"){let u=this.dependencies.logs??new di(this.region,this.profile),m=r.config.logGroups,h=r.provider==="lambda"?`/aws/lambda/${r.name}`:Array.isArray(m)&&typeof m[0]==="string"?m[0]:void 0;if(!h)throw Error("The ECS task definition does not declare an awslogs group.");let y=await u.filterLogEvents({logGroupName:h,startTime:t.since?.getTime(),limit:n}),w=(y.events??[]).slice(0,n).map((k)=>({timestamp:k.timestamp==null?void 0:new Date(k.timestamp).toISOString(),message:Fi(String(k.message??""))}));return{workloadId:e,provider:r.provider,lines:w,nextCursor:y.nextToken,truncated:(y.events?.length??0)>=n}}let i=r.links.providerId??"",o=t.since&&Number.isFinite(t.since.getTime())?t.since:void 0,s=r.provider==="systemd"&&Oa.test(i)?`journalctl -u ${i} --no-pager -n ${n} -o short-iso${o?` --since ${Jt(o.toISOString())}`:""}`:r.provider==="docker"&&$a.test(i)?`docker logs --timestamps --tail ${n}${o?` --since ${Math.floor(o.getTime()/1000)}`:""} ${i} 2>&1`:void 0;if(!s)throw Error("Log target identity is invalid.");let c=await this.remote(r,[s],30,"ts-cloud runtime:logs");if(!c.success)throw Error(c.error??c.perInstance?.[0]?.error??"Log read failed.");let d=Fi(c.perInstance?.[0]?.output??""),a=d.split(`
|
|
147
|
+
`).filter(Boolean).slice(-n).map((u)=>{let m=/^(\d{4}-\d{2}-\d{2}T\S+)\s+(.*)$/.exec(u);return{timestamp:m?.[1],message:m?.[2]??u}});return{workloadId:e,provider:r.provider,lines:a,truncated:d.includes("[output truncated]")||a.length>=n}}}import{randomUUID as CA}from"node:crypto";class Xl{records=new Map;maxBufferBytes;ttlMs;now;constructor(e={}){this.maxBufferBytes=Math.max(1024,e.maxBufferBytes??262144),this.ttlMs=Math.max(1000,e.ttlMs??900000),this.now=e.now??(()=>new Date)}create(e,t){this.sweep();let r=this.now().toISOString(),n={id:CA(),workloadId:t,kind:e,state:"open",chunks:[],cursor:0,droppedBytes:0,bufferedBytes:0,createdAt:r,updatedAt:r,abort:new AbortController,listeners:new Set};return this.records.set(n.id,n),this.snapshot(n,0)}signal(e){return this.records.get(e)?.abort.signal}append(e,t,r="stdout"){let n=this.records.get(e);if(!n||n.state!=="open"||!t)return n?this.snapshot(n,n.cursor):void 0;let i=Buffer.from(t),o=i.byteLength>this.maxBufferBytes?i.subarray(i.byteLength-this.maxBufferBytes).toString("utf8"):t,s={cursor:++n.cursor,stream:r,data:o,at:this.now().toISOString()};n.chunks.push(s),n.bufferedBytes+=Buffer.byteLength(o),n.updatedAt=s.at;while(n.bufferedBytes>this.maxBufferBytes&&n.chunks.length>1){let c=n.chunks.shift(),d=Buffer.byteLength(c.data);n.bufferedBytes-=d,n.droppedBytes+=d}return this.publish(n),this.snapshot(n,s.cursor-1)}read(e,t,r=0){let n=this.records.get(e);if(!n||n.workloadId!==t)return;return n.updatedAt=this.now().toISOString(),this.snapshot(n,Math.max(0,Math.floor(r)))}close(e,t="complete",r){let n=this.records.get(e);if(!n||n.state!=="open")return n?this.snapshot(n,n.cursor):void 0;if(n.state=t,n.error=r,n.updatedAt=this.now().toISOString(),t==="cancelled")n.abort.abort();return this.publish(n),this.snapshot(n,n.cursor)}cancel(e,t){let r=this.records.get(e);if(!r||r.workloadId!==t)return;return this.close(e,"cancelled")}subscribe(e,t,r){let n=this.records.get(e);if(!n||n.workloadId!==t)return;return n.listeners.add(r),()=>n.listeners.delete(r)}sweep(){let e=this.now().getTime()-this.ttlMs,t=0;for(let[r,n]of this.records){if(new Date(n.updatedAt).getTime()>e)continue;n.abort.abort(),this.records.delete(r),t++}return t}clear(){for(let e of this.records.values())e.abort.abort();this.records.clear()}snapshot(e,t){let r=e.chunks[0]?.cursor??e.cursor+1,n=t>0&&t<r-1;return{id:e.id,workloadId:e.workloadId,kind:e.kind,state:e.state,chunks:e.chunks.filter((i)=>n||i.cursor>t),cursor:e.cursor,reset:n,droppedBytes:e.droppedBytes,createdAt:e.createdAt,updatedAt:e.updatedAt,error:e.error}}publish(e){let t=this.snapshot(e,0);for(let r of e.listeners)r(t)}}import{createHash as PA}from"node:crypto";var nu={info:0,low:1,medium:2,high:3,critical:4},iu={record:0,warn:1,block:2},cy=new Set(["skipped","unavailable","unsupported","stale"]);function Ve(e){return typeof e==="string"?e:void 0}function gn(e,t){try{return JSON.parse(String(e))}catch{return t}}function sr(e){return JSON.stringify(Oe(e))}function _A(e){if(!e)return;return String(Oe(e,2000))}function eu(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:Ve(e.project_id),environmentId:Ve(e.environment_id),resourceId:Ve(e.resource_id),releaseId:Ve(e.release_id),scannerId:String(e.scanner_id),scannerVersion:String(e.scanner_version),status:String(e.status),error:Ve(e.error),metadata:gn(e.metadata,{}),findingsCount:Number(e.findings_count),startedAt:String(e.started_at),completedAt:String(e.completed_at),durationMs:Number(e.duration_ms)}}function dy(e){return{id:String(e.id),fingerprint:String(e.fingerprint),organizationId:String(e.organization_id),projectId:Ve(e.project_id),environmentId:Ve(e.environment_id),resourceId:Ve(e.resource_id),releaseId:Ve(e.release_id),scanRunId:String(e.scan_run_id),scannerId:String(e.scanner_id),scannerVersion:String(e.scanner_version),ruleId:String(e.rule_id),severity:String(e.severity),title:String(e.title),description:String(e.description),evidence:gn(e.evidence,{}),remediation:Ve(e.remediation),subject:String(e.subject),status:String(e.status),ownerActorId:Ve(e.owner_actor_id),recurrenceCount:Number(e.recurrence_count),firstSeenAt:String(e.first_seen_at),lastSeenAt:String(e.last_seen_at),resolvedAt:Ve(e.resolved_at),updatedAt:String(e.updated_at)}}function tu(e){return{id:String(e.id),organizationId:String(e.organization_id),environmentId:Ve(e.environment_id),name:String(e.name),rules:gn(e.rules,[]),requiredScanners:gn(e.required_scanners,[]),scannerFailMode:String(e.scanner_fail_mode),enabled:Number(e.enabled)===1,version:Number(e.version),createdByActorId:Ve(e.created_by_actor_id),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function ly(e,t){let r=Ve(e.revoked_at),n=String(e.expires_at);return{id:String(e.id),findingId:String(e.finding_id),policyId:Ve(e.policy_id),reason:String(e.reason),referenceUrl:Ve(e.reference_url),createdByActorId:String(e.created_by_actor_id),expiresAt:n,revokedAt:r,state:r?"revoked":n<=t?"expired":"active",createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function ru(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:Ve(e.environment_id),releaseId:String(e.release_id),kind:String(e.kind),format:String(e.format),digest:String(e.digest),summary:gn(e.summary,{}),content:Ve(e.content),sensitive:Number(e.sensitive)===1,createdAt:String(e.created_at)}}function uy(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:String(e.environment_id),operationId:Ve(e.operation_id),policyId:String(e.policy_id),policyVersion:Number(e.policy_version),outcome:String(e.outcome),scannerVersions:gn(e.scanner_versions,{}),findingIds:gn(e.finding_ids,[]),waiverIds:gn(e.waiver_ids,[]),explanation:String(e.explanation),createdAt:String(e.created_at)}}function TA(e,t){let r=[e.trim().toLowerCase(),t.ruleId.trim().toLowerCase(),t.organizationId,t.projectId??"",t.environmentId??"",t.resourceId??"",t.releaseId??"",t.subject.trim().toLowerCase()].join("\x00");return PA("sha256").update(r).digest("hex")}function py(e){if(!e)return;let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")throw Error("Security references must use HTTP or HTTPS");return t.toString()}function my(e){if(!e.length)throw Error("A security policy needs at least one rule");return e.map((t)=>{if(!(t.minimumSeverity in nu))throw Error(`Unknown security severity: ${t.minimumSeverity}`);if(!(t.action in iu))throw Error(`Unknown security policy action: ${t.action}`);return{minimumSeverity:t.minimumSeverity,action:t.action,...t.scannerId?{scannerId:t.scannerId.trim()}:{}}})}class Do{controlPlane;nowFn;idFn;constructor(e,t={}){this.controlPlane=e;this.nowFn=t.now??(()=>new Date),this.idFn=t.id??(()=>crypto.randomUUID())}now(){return this.nowFn().toISOString()}run(e,t){this.controlPlane.database.run(e,t)}recordScan(e){if(!e.organizationId||!e.scannerId.trim()||!e.scannerVersion.trim())throw Error("Organization, scanner id, and scanner version are required");let t=e.completedAt??this.now(),r=e.startedAt??t,n=e.durationMs??Math.max(0,new Date(t).getTime()-new Date(r).getTime()),i=e.findings??[],o=this.idFn(),s=new Set,c=[];return this.controlPlane.transaction(()=>{this.run(`INSERT INTO security_scan_runs
|
|
148
|
+
(id, organization_id, project_id, environment_id, resource_id, release_id, scanner_id, scanner_version, status, error, metadata, findings_count, started_at, completed_at, duration_ms)
|
|
149
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[o,e.organizationId,e.projectId??null,e.environmentId??null,e.resourceId??null,e.releaseId??null,e.scannerId.trim(),e.scannerVersion.trim(),e.status,_A(e.error)??null,sr(e.metadata??{}),i.length,r,t,Math.max(0,Math.floor(n))]);for(let d of i){let a={...d,organizationId:e.organizationId,projectId:d.projectId??e.projectId,environmentId:d.environmentId??e.environmentId,resourceId:d.resourceId??e.resourceId,releaseId:d.releaseId??e.releaseId},u=a.fingerprint?.trim()||TA(e.scannerId,a);s.add(u);let m=this.controlPlane.database.query("SELECT * FROM security_findings WHERE fingerprint = ?").get(u),h=m?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(m.id),t):void 0;if(m){let y=String(m.status)==="resolved"?Number(m.recurrence_count)+1:Number(m.recurrence_count),w=h?"waived":String(m.status)==="acknowledged"?"acknowledged":"open";this.run(`UPDATE security_findings SET scan_run_id = ?, scanner_version = ?, severity = ?, title = ?, description = ?, evidence = ?, remediation = ?,
|
|
150
|
+
status = ?, recurrence_count = ?, last_seen_at = ?, resolved_at = NULL, updated_at = ? WHERE id = ?`,[o,e.scannerVersion,a.severity,a.title.trim(),a.description.trim(),sr(a.evidence??{}),a.remediation?.trim()||null,w,y,t,t,String(m.id)]),c.push(this.getFinding(String(m.id)))}else{let y=this.idFn();this.run(`INSERT INTO security_findings
|
|
151
|
+
(id, fingerprint, organization_id, project_id, environment_id, resource_id, release_id, scan_run_id, scanner_id, scanner_version, rule_id,
|
|
152
|
+
severity, title, description, evidence, remediation, subject, status, first_seen_at, last_seen_at, updated_at)
|
|
153
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'open', ?, ?, ?)`,[y,u,a.organizationId,a.projectId??null,a.environmentId??null,a.resourceId??null,a.releaseId??null,o,e.scannerId,e.scannerVersion,a.ruleId.trim(),a.severity,a.title.trim(),a.description.trim(),sr(a.evidence??{}),a.remediation?.trim()||null,a.subject.trim(),t,t,t]),c.push(this.getFinding(y))}}if(e.status==="passed"||e.status==="failed"){let d=this.controlPlane.database.query(`SELECT * FROM security_findings WHERE organization_id = ? AND scanner_id = ?
|
|
154
|
+
AND project_id IS ? AND environment_id IS ? AND resource_id IS ? AND release_id IS ? AND status != 'resolved'`).all(e.organizationId,e.scannerId,e.projectId??null,e.environmentId??null,e.resourceId??null,e.releaseId??null);for(let a of d){if(s.has(String(a.fingerprint)))continue;this.run("UPDATE security_findings SET status = 'resolved', resolved_at = ?, updated_at = ? WHERE id = ?",[t,t,String(a.id)]),this.controlPlane.appendEvent({organizationId:e.organizationId,projectId:e.projectId,resourceId:e.resourceId,type:"security.finding.resolved",payload:{findingId:String(a.id),scannerId:e.scannerId,reason:"not-observed"}})}}this.controlPlane.appendEvent({organizationId:e.organizationId,projectId:e.projectId,resourceId:e.resourceId,type:"security.scan.completed",level:e.status==="failed"||cy.has(e.status)?"warning":"info",payload:{scanRunId:o,scannerId:e.scannerId,scannerVersion:e.scannerVersion,status:e.status,findingsCount:i.length,durationMs:n}})}),{run:this.getScanRun(o),findings:c.map((d)=>this.getFinding(d.id))}}getScanRun(e){let t=this.controlPlane.database.query("SELECT * FROM security_scan_runs WHERE id = ?").get(e);return t?eu(t):void 0}listScanRuns(e){return this.controlPlane.database.query("SELECT * FROM security_scan_runs WHERE organization_id = ? AND project_id IS ? AND environment_id IS ? ORDER BY completed_at DESC, id DESC LIMIT ?").all(e.organizationId,e.projectId??null,e.environmentId??null,Math.min(500,Math.max(1,e.limit??100))).map(eu)}getFinding(e){let t=this.controlPlane.database.query("SELECT * FROM security_findings WHERE id = ?").get(e);return t?dy(t):void 0}listFindings(e){this.expireWaivers();let t=["organization_id = ?"],r=[e.organizationId];if(e.projectId)t.push("project_id = ?"),r.push(e.projectId);if(e.environmentId)t.push("environment_id = ?"),r.push(e.environmentId);if(e.status)t.push("status = ?"),r.push(e.status);if(e.severity)t.push("severity = ?"),r.push(e.severity);return r.push(Math.min(1000,Math.max(1,e.limit??250))),this.controlPlane.database.query(`SELECT * FROM security_findings WHERE ${t.join(" AND ")} ORDER BY CASE severity WHEN 'critical' THEN 4 WHEN 'high' THEN 3 WHEN 'medium' THEN 2 WHEN 'low' THEN 1 ELSE 0 END DESC, last_seen_at DESC LIMIT ?`).all(...r).map(dy)}assignFinding(e,t,r){let n=this.getFinding(e);if(!n)throw Error("Security finding was not found");if(t&&!this.controlPlane.getActor(t))throw Error("Finding owner was not found");return this.run("UPDATE security_findings SET owner_actor_id = ?, updated_at = ? WHERE id = ?",[t??null,this.now(),e]),this.controlPlane.appendEvent({organizationId:n.organizationId,projectId:n.projectId,resourceId:n.resourceId,actorId:r,type:"security.finding.assigned",payload:{findingId:e,ownerActorId:t??null}}),this.getFinding(e)}acknowledgeFinding(e,t){let r=this.getFinding(e);if(!r)throw Error("Security finding was not found");if(r.status==="resolved")throw Error("A resolved finding cannot be acknowledged");return this.run("UPDATE security_findings SET status = 'acknowledged', updated_at = ? WHERE id = ?",[this.now(),e]),this.controlPlane.appendEvent({organizationId:r.organizationId,projectId:r.projectId,resourceId:r.resourceId,actorId:t,type:"security.finding.acknowledged",payload:{findingId:e}}),this.getFinding(e)}addComment(e){let t=this.getFinding(e.findingId);if(!t)throw Error("Security finding was not found");let r=e.body.trim();if(r.length<2||r.length>4000)throw Error("Finding comments must contain 2-4,000 characters");let n=py(e.referenceUrl),i=this.idFn(),o=this.now();return this.run("INSERT INTO security_finding_comments (id, finding_id, actor_id, body, reference_url, created_at) VALUES (?, ?, ?, ?, ?, ?)",[i,e.findingId,e.actorId,r,n??null,o]),this.controlPlane.appendEvent({organizationId:t.organizationId,projectId:t.projectId,resourceId:t.resourceId,actorId:e.actorId,type:"security.finding.commented",payload:{findingId:e.findingId,commentId:i,referenceUrl:n??null}}),{id:i,findingId:e.findingId,actorId:e.actorId,body:r,referenceUrl:n,createdAt:o}}listComments(e){return this.controlPlane.database.query("SELECT * FROM security_finding_comments WHERE finding_id = ? ORDER BY created_at, id").all(e).map((t)=>({id:String(t.id),findingId:String(t.finding_id),actorId:String(t.actor_id),body:String(t.body),referenceUrl:Ve(t.reference_url),createdAt:String(t.created_at)}))}createWaiver(e){let t=this.getFinding(e.findingId);if(!t)throw Error("Security finding was not found");let r=e.reason.trim();if(r.length<8||r.length>1000)throw Error("A waiver reason must contain 8-1,000 characters");let n=this.now(),i=new Date(e.expiresAt);if(!Number.isFinite(i.getTime())||i.toISOString()<=n)throw Error("A waiver must have a future expiry");if(i.getTime()-new Date(n).getTime()>31536000000)throw Error("A waiver cannot last longer than one year");let o=e.policyId?this.getPolicy(e.policyId):void 0;if(e.policyId&&(!o||o.organizationId!==t.organizationId))throw Error("Waiver policy does not match the finding organization");let s=this.idFn(),c=py(e.referenceUrl);return this.controlPlane.transaction(()=>{this.run(`INSERT INTO security_waivers (id, finding_id, policy_id, reason, reference_url, created_by_actor_id, expires_at, created_at, updated_at)
|
|
155
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[s,t.id,e.policyId??null,r,c??null,e.actorId,i.toISOString(),n,n]),this.run("UPDATE security_findings SET status = 'waived', updated_at = ? WHERE id = ?",[n,t.id]),this.controlPlane.appendEvent({organizationId:t.organizationId,projectId:t.projectId,resourceId:t.resourceId,actorId:e.actorId,type:"security.waiver.created",level:"warning",payload:{waiverId:s,findingId:t.id,policyId:e.policyId??null,reason:r,expiresAt:i.toISOString(),referenceUrl:c??null}})}),this.getWaiver(s)}revokeWaiver(e,t){let r=this.getWaiver(e);if(!r)throw Error("Security waiver was not found");if(r.revokedAt)return r;let n=this.getFinding(r.findingId),i=this.now();return this.controlPlane.transaction(()=>{this.run("UPDATE security_waivers SET revoked_at = ?, updated_at = ? WHERE id = ?",[i,i,e]),this.run("UPDATE security_findings SET status = 'open', updated_at = ? WHERE id = ? AND status = 'waived'",[i,r.findingId]),this.controlPlane.appendEvent({organizationId:n.organizationId,projectId:n.projectId,resourceId:n.resourceId,actorId:t,type:"security.waiver.revoked",level:"warning",payload:{waiverId:e,findingId:r.findingId}})}),this.getWaiver(e)}getWaiver(e){let t=this.controlPlane.database.query("SELECT * FROM security_waivers WHERE id = ?").get(e);return t?ly(t,this.now()):void 0}listWaivers(e){return(e?this.controlPlane.database.query("SELECT * FROM security_waivers WHERE finding_id = ? ORDER BY created_at DESC").all(e):this.controlPlane.database.query("SELECT * FROM security_waivers ORDER BY created_at DESC").all()).map((r)=>ly(r,this.now()))}expireWaivers(){let e=this.now(),t=this.controlPlane.database.query(`SELECT w.id AS waiver_id, f.* FROM security_waivers w JOIN security_findings f ON f.id = w.finding_id
|
|
156
|
+
WHERE w.revoked_at IS NULL AND w.expires_at <= ? AND f.status = 'waived'`).all(e);for(let r of t)this.run("UPDATE security_findings SET status = 'open', updated_at = ? WHERE id = ?",[e,String(r.id)]),this.controlPlane.appendEvent({organizationId:String(r.organization_id),projectId:Ve(r.project_id),resourceId:Ve(r.resource_id),type:"security.waiver.expired",level:"warning",payload:{waiverId:String(r.waiver_id),findingId:String(r.id)}});return t.length}createPolicy(e){let t=e.name.trim();if(!t)throw Error("Security policy name is required");let r=my(e.rules),n=this.idFn(),i=this.now(),o=[...new Set((e.requiredScanners??[]).map((s)=>s.trim()).filter(Boolean))].sort();return this.run(`INSERT INTO security_policies (id, organization_id, environment_id, name, rules, required_scanners, scanner_fail_mode, created_by_actor_id, created_at, updated_at)
|
|
157
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n,e.organizationId,e.environmentId??null,t,sr(r),sr(o),e.scannerFailMode,e.actorId??null,i,i]),this.controlPlane.appendEvent({organizationId:e.organizationId,actorId:e.actorId,type:"security.policy.created",payload:{policyId:n,environmentId:e.environmentId??null,scannerFailMode:e.scannerFailMode,requiredScanners:o,rules:Oe(r)}}),this.getPolicy(n)}updatePolicy(e,t,r){let n=this.getPolicy(e);if(!n||n.version!==t)throw Error(`Security policy ${e} changed since version ${t}`);let i=r.rules?my(r.rules):n.rules,o=r.requiredScanners?[...new Set(r.requiredScanners.map((d)=>d.trim()).filter(Boolean))].sort():n.requiredScanners,s=this.now();if(this.controlPlane.database.run("UPDATE security_policies SET name = ?, rules = ?, required_scanners = ?, scanner_fail_mode = ?, enabled = ?, version = version + 1, updated_at = ? WHERE id = ? AND version = ?",[r.name?.trim()||n.name,sr(i),sr(o),r.scannerFailMode??n.scannerFailMode,r.enabled??n.enabled?1:0,s,e,t]).changes!==1)throw Error(`Security policy ${e} changed since version ${t}`);return this.controlPlane.appendEvent({organizationId:n.organizationId,actorId:r.actorId,type:"security.policy.updated",payload:{policyId:e,fromVersion:t,toVersion:t+1}}),this.getPolicy(e)}getPolicy(e){let t=this.controlPlane.database.query("SELECT * FROM security_policies WHERE id = ?").get(e);return t?tu(t):void 0}listPolicies(e){return this.controlPlane.database.query("SELECT * FROM security_policies WHERE organization_id = ? ORDER BY environment_id, name").all(e).map(tu)}evaluateGate(e){this.expireWaivers();let t=e.policyId?this.getPolicy(e.policyId):this.controlPlane.database.query(`SELECT * FROM security_policies WHERE organization_id = ? AND enabled = 1 AND (environment_id = ? OR environment_id IS NULL)
|
|
158
|
+
ORDER BY CASE WHEN environment_id = ? THEN 0 ELSE 1 END, updated_at DESC LIMIT 1`).get(e.organizationId,e.environmentId,e.environmentId),r=t&&"rules"in t&&Array.isArray(t.rules)?t:t?tu(t):void 0;if(!r||!r.enabled)throw Error("No enabled security policy applies to this environment");let n=this.listFindings({organizationId:e.organizationId,projectId:e.projectId,environmentId:e.environmentId,limit:1000}).filter((q)=>q.status!=="resolved"),i=new Map;for(let q of n){let N=this.listWaivers(q.id).find((Q)=>Q.state==="active"&&(!Q.policyId||Q.policyId===r.id));if(N)i.set(q.id,N)}let o=(q)=>r.rules.filter((N)=>(!N.scannerId||N.scannerId===q.scannerId)&&nu[q.severity]>=nu[N.minimumSeverity]).reduce((N,Q)=>iu[Q.action]>iu[N]?Q.action:N,"record"),s=n.filter((q)=>!i.has(q.id)&&o(q)==="block"),c=n.filter((q)=>!i.has(q.id)&&o(q)==="warn"),d=this.controlPlane.database.query(`SELECT run.* FROM security_scan_runs run
|
|
159
|
+
WHERE run.organization_id = ? AND run.project_id = ? AND run.environment_id = ?
|
|
160
|
+
AND run.id = (SELECT candidate.id FROM security_scan_runs candidate
|
|
161
|
+
WHERE candidate.organization_id = run.organization_id AND candidate.project_id = run.project_id
|
|
162
|
+
AND candidate.environment_id = run.environment_id AND candidate.scanner_id = run.scanner_id
|
|
163
|
+
ORDER BY candidate.completed_at DESC, candidate.rowid DESC LIMIT 1)`).all(e.organizationId,e.projectId,e.environmentId),a=e.staleAfterMs??86400000,u=this.nowFn().getTime(),m=d.map(eu).map((q)=>u-new Date(q.completedAt).getTime()>a?{...q,status:"stale"}:q),h=new Set(m.map((q)=>q.scannerId)),y=r.requiredScanners.filter((q)=>!h.has(q)).map((q)=>({id:`missing:${q}`,organizationId:e.organizationId,projectId:e.projectId,environmentId:e.environmentId,scannerId:q,scannerVersion:"unavailable",status:"unavailable",metadata:{},findingsCount:0,startedAt:this.now(),completedAt:this.now(),durationMs:0})),w=[...m,...y],k=w.filter((q)=>r.requiredScanners.includes(q.scannerId)&&cy.has(q.status)),C=Object.fromEntries(w.map((q)=>[q.scannerId,q.scannerVersion])),T=r.scannerFailMode==="closed"&&k.length>0,j=s.length||T?"block":c.length||k.length?"warn":"allow",P=[];if(s.length)P.push(`${s.length} finding${s.length===1?"":"s"} blocked by policy`);if(c.length)P.push(`${c.length} warning${c.length===1?"":"s"} require review`);if(k.length)P.push(`${k.length} scanner${k.length===1?"":"s"} ${r.scannerFailMode==="closed"?"failed closed":"failed open"}`);if(i.size)P.push(`${i.size} active time-limited waiver${i.size===1?"":"s"}`);if(!P.length)P.push("All recorded checks satisfy policy");let O=this.idFn(),U=this.now();return this.run(`INSERT INTO security_deploy_decisions
|
|
164
|
+
(id, organization_id, project_id, environment_id, operation_id, policy_id, policy_version, outcome, scanner_versions, finding_ids, waiver_ids, explanation, created_at)
|
|
165
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[O,e.organizationId,e.projectId,e.environmentId,e.operationId??null,r.id,r.version,j,sr(C),sr([...s,...c].map((q)=>q.id)),sr([...i.values()].map((q)=>q.id)),P.join("; "),U]),this.controlPlane.appendEvent({organizationId:e.organizationId,projectId:e.projectId,operationId:e.operationId,type:"security.deploy.decision",level:j==="block"?"error":j==="warn"?"warning":"info",payload:{decisionId:O,outcome:j,policyId:r.id,policyVersion:r.version,scannerVersions:C,blockerIds:s.map((q)=>q.id),waiverIds:[...i.values()].map((q)=>q.id),explanation:P.join("; ")}}),this.getDecision(O)}getDecision(e){let t=this.controlPlane.database.query("SELECT * FROM security_deploy_decisions WHERE id = ?").get(e);return t?uy(t):void 0}listDecisions(e,t=100){return this.controlPlane.database.query("SELECT * FROM security_deploy_decisions WHERE environment_id = ? ORDER BY created_at DESC LIMIT ?").all(e,Math.min(500,Math.max(1,t))).map(uy)}addReleaseArtifact(e){let t=this.controlPlane.database.query("SELECT * FROM release_security_artifacts WHERE release_id = ? AND kind = ? AND digest = ?").get(e.releaseId,e.kind,e.digest);if(t)return ru(t);let r=this.idFn(),n=this.now();return this.run(`INSERT INTO release_security_artifacts
|
|
166
|
+
(id, organization_id, project_id, environment_id, release_id, kind, format, digest, summary, content, sensitive, created_at)
|
|
167
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[r,e.organizationId,e.projectId,e.environmentId??null,e.releaseId,e.kind,e.format,e.digest,sr(e.summary),e.content??null,e.sensitive?1:0,n]),this.controlPlane.appendEvent({organizationId:e.organizationId,projectId:e.projectId,type:"security.release_artifact.created",payload:{artifactId:r,releaseId:e.releaseId,kind:e.kind,format:e.format,digest:e.digest,sensitive:e.sensitive}}),ru(this.controlPlane.database.query("SELECT * FROM release_security_artifacts WHERE id = ?").get(r))}listReleaseArtifacts(e,t=!1){return this.controlPlane.database.query("SELECT * FROM release_security_artifacts WHERE release_id = ? ORDER BY created_at, kind").all(e).map(ru).map((r)=>r.sensitive&&!t?{...r,content:void 0}:r)}summary(e,t,r){let n=this.listFindings({organizationId:e,projectId:t,environmentId:r,limit:1000}),i=this.listScanRuns({organizationId:e,projectId:t,environmentId:r,limit:1000}),o={info:0,low:0,medium:0,high:0,critical:0};for(let c of n)if(c.status==="open"||c.status==="acknowledged")o[c.severity]++;let s={passed:0,failed:0,skipped:0,unavailable:0,unsupported:0,stale:0};for(let c of i)s[c.status]++;return{open:o,waived:n.filter((c)=>c.status==="waived").length,resolved:n.filter((c)=>c.status==="resolved").length,checks:s,lastScannedAt:i[0]?.completedAt}}exportPosture(e){let t=this.controlPlane.listProjects().filter((r)=>r.organizationId===e);return Oe({format:"ts-cloud-security-posture",version:1,exportedAt:this.now(),organizationId:e,policies:this.listPolicies(e),findings:this.listFindings({organizationId:e,limit:1000}),waivers:this.listWaivers().filter((r)=>this.getFinding(r.findingId)?.organizationId===e),scans:t.flatMap((r)=>this.listScanRuns({organizationId:e,projectId:r.id,limit:1000})),decisions:t.flatMap((r)=>this.controlPlane.listEnvironments(r.id).flatMap((n)=>this.listDecisions(n.id,1000)))})}}import{existsSync as xA,readdirSync as DA,readFileSync as OA,statSync as $A}from"node:fs";import{extname as NA,join as jA,relative as MA}from"node:path";var gy=[{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"}],BA=[".js",".jsx",".ts",".tsx",".mjs",".cjs",".vue",".svelte",".html",".htm",".css",".scss",".less",".json",".yaml",".yml",".toml",".xml",".env",".config",".conf"],LA=["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"],FA=["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 Oo{patterns;excludeDirs;excludeFiles;maxFileSize;constructor(e){this.patterns=[...gy,...e?.customPatterns||[]],this.excludeDirs=[...LA,...e?.excludeDirs||[]],this.excludeFiles=[...FA,...e?.excludeFiles||[]],this.maxFileSize=e?.maxFileSize||1048576}async scan(e){let t=Date.now(),r=[],n=0,{directory:i,exclude:o=[],include:s,skipPatterns:c=[]}=e,d=e.failOnSeverity||"critical";if(!xA(i))throw Error(`Directory not found: ${i}`);let a=this.getFilesToScan(i,[...this.excludeDirs,...o],s);for(let w of a){let k=MA(i,w);if(this.shouldExcludeFile(k))continue;try{if($A(w).size>this.maxFileSize)continue;let T=OA(w,"utf-8"),j=this.scanContent(T,k,c);r.push(...j),n++}catch{continue}}let u={critical:r.filter((w)=>w.pattern.severity==="critical").length,high:r.filter((w)=>w.pattern.severity==="high").length,medium:r.filter((w)=>w.pattern.severity==="medium").length,low:r.filter((w)=>w.pattern.severity==="low").length},m=["low","medium","high","critical"],h=m.indexOf(d),y=!0;for(let w=h;w<m.length;w++)if(u[m[w]]>0){y=!1;break}return{passed:y,findings:r,scannedFiles:n,duration:Date.now()-t,summary:u}}scanContent(e,t,r){let n=[],i=e.split(`
|
|
168
|
+
`);for(let o of this.patterns){if(r.includes(o.name))continue;o.pattern.lastIndex=0;let s;while((s=o.pattern.exec(e))!==null){let c=e.substring(0,s.index),d=c.split(`
|
|
169
|
+
`).length,a=c.lastIndexOf(`
|
|
170
|
+
`),u=s.index-a,m=i[d-1]||"";if(this.isLikelyPlaceholder(s[0],m))continue;let h=s[1]||s[0];if(o.name==="AWS Secret Key (Generic)"&&/^[a-f0-9]{40}$/i.test(h))continue;if(o.name==="AWS Secret Key (Generic)"&&!this.hasSecretCharacterDiversity(h))continue;if(o.name==="AWS Secret Key (Generic)"&&/^(?:Actions|Commands|Controllers|Handlers|Jobs|Listeners|Middleware|Models|Resources|Services)\//.test(h))continue;if(this.isLowEntropy(h))continue;n.push({file:t,line:d,column:u,match:this.maskSecret(s[0]),pattern:o,context:this.maskSecret(m.trim())})}}return n}isLikelyPlaceholder(e,t){let r=["example","placeholder","your_","YOUR_","xxx","XXX","***","test","TEST","dummy","DUMMY","fake","FAKE","sample","SAMPLE","<your","${","{{","process.env","import.meta.env","CHANGEME","TODO","FIXME"],n=e.toLowerCase(),i=t.toLowerCase();for(let s of r)if(n.includes(s.toLowerCase())||i.includes(s.toLowerCase()))return!0;let o=t.trim();if(o.startsWith("//")||o.startsWith("#")||o.startsWith("*")||o.startsWith("/*")){if(i.includes("example")||i.includes("format:")||i.includes("e.g."))return!0}return!1}isLowEntropy(e){if(e.length<8)return!1;if(new Set(e).size<8)return!0;if(/(.)\1{3,}/.test(e))return!0;return!1}hasSecretCharacterDiversity(e){let t=/[\d+=]/.test(e),r=[/[a-z]/.test(e),/[A-Z]/.test(e),/\d/.test(e),/[/+=]/.test(e)];return t&&r.filter(Boolean).length>=3}maskSecret(e){if(e.length<=8)return"*".repeat(e.length);let t=Math.min(4,Math.floor(e.length*0.2));return e.substring(0,t)+"*".repeat(e.length-t*2)+e.substring(e.length-t)}getFilesToScan(e,t,r){let n=[],i=r||BA,o=(s)=>{let c=DA(s,{withFileTypes:!0});for(let d of c){let a=jA(s,d.name);if(d.isDirectory()){if(!t.includes(d.name))o(a)}else if(d.isFile()){let u=NA(d.name).toLowerCase();if(i.includes(u)||d.name.startsWith(".env")||d.name.endsWith(".config"))n.push(a)}}};return o(e),n}shouldExcludeFile(e){let t=e.split("/").pop()||"";for(let r of this.excludeFiles)if(r.startsWith("*")){let n=r.substring(1);if(t.endsWith(n))return!0}else if(r.endsWith("*")){let n=r.substring(0,r.length-1);if(t.startsWith(n))return!0}else if(t===r)return!0;return!1}addPattern(e){this.patterns.push(e)}getPatterns(){return[...this.patterns]}}async function zA(e){return new Oo().scan(e)}function UA(e){let t=[];if(t.push(`
|
|
171
|
+
Security Scan Results`),t.push("=".repeat(50)),t.push(`Files scanned: ${e.scannedFiles}`),t.push(`Duration: ${e.duration}ms`),t.push(""),t.push("Summary:"),t.push(` Critical: ${e.summary.critical}`),t.push(` High: ${e.summary.high}`),t.push(` Medium: ${e.summary.medium}`),t.push(` Low: ${e.summary.low}`),t.push(""),e.findings.length>0){t.push("Findings:"),t.push("-".repeat(50));for(let r of e.findings)t.push(`
|
|
172
|
+
[${r.pattern.severity.toUpperCase()}] ${r.pattern.name}`),t.push(` File: ${r.file}:${r.line}:${r.column}`),t.push(` Match: ${r.match}`),t.push(` Context: ${r.context}`),t.push(` Description: ${r.pattern.description}`)}return t.push(""),t.push(e.passed?"✓ Security scan passed":"✗ Security scan failed"),t.join(`
|
|
173
|
+
`)}function qA(e,t){return{status:"unavailable",findings:[],error:`${e.id} exceeded its ${t}ms timeout`,metadata:{timeoutMs:t}}}class Qn{posture;defaultTimeoutMs;nowFn;constructor(e,t={}){this.posture=e;this.defaultTimeoutMs=t.defaultTimeoutMs??60000,this.nowFn=t.now??(()=>new Date)}async run(e,t){let r=this.nowFn(),n=Math.max(100,e.timeoutMs??this.defaultTimeoutMs),i=new AbortController,o,s=new Promise((u)=>{o=setTimeout(()=>{i.abort(),u(qA(e,n))},n)}),c;try{c=await Promise.race([e.scan({...t,signal:i.signal}),s])}catch(u){c={status:"unavailable",findings:[],error:u instanceof Error?u.message:String(u)}}finally{if(o)clearTimeout(o)}let d=this.nowFn(),a={...t,scannerId:e.id,scannerVersion:e.version,status:c.status,findings:c.findings,metadata:c.metadata,error:c.error,startedAt:r.toISOString(),completedAt:d.toISOString(),durationMs:Math.max(0,d.getTime()-r.getTime())};return this.posture.recordScan(a)}async runAll(e,t){return Promise.all(e.map((r)=>this.run(r,t)))}}class $o{scanner;id="source-secrets";version="1.0.0";timeoutMs=30000;constructor(e=new Oo){this.scanner=e}async scan(e){if(!e.artifactRoot)return{status:"skipped",findings:[],error:"No artifact root was supplied"};let t=await this.scanner.scan({directory:e.artifactRoot,failOnSeverity:"critical"});return{status:t.passed?"passed":"failed",findings:t.findings.map((r)=>({...e,ruleId:r.pattern.name.toLowerCase().replace(/[^a-z0-9]+/g,"-"),severity:r.pattern.severity,title:r.pattern.name,description:r.pattern.description,subject:`${r.file}:${r.line}`,evidence:{file:r.file,line:r.line,column:r.column,match:r.match,context:r.context},remediation:"Remove the credential, rotate it at its issuer, and use a managed secret or environment reference."})),metadata:{scannedFiles:t.scannedFiles,summary:t.summary}}}}function VA(e){let t=e?.toLowerCase();return t==="critical"||t==="high"||t==="medium"||t==="low"?t:"info"}class ou{id="trivy-image";version;timeoutMs;constructor(e={}){this.version=e.version??"local",this.timeoutMs=e.timeoutMs??120000,this.executable=e.executable??"trivy"}executable;async scan(e){if(!e.imageRef)return{status:"skipped",findings:[],error:"No image reference was supplied"};let t;try{t=Bun.spawn([this.executable,"image","--format","json","--quiet","--scanners","vuln",e.imageRef],{stdout:"pipe",stderr:"pipe",env:{PATH:process.env.PATH??"/usr/local/bin:/usr/bin:/bin",HOME:"/nonexistent",TRIVY_NO_PROGRESS:"true"}})}catch(d){return{status:"unsupported",findings:[],error:d instanceof Error?d.message:String(d)}}let r=()=>t.kill();e.signal.addEventListener("abort",r,{once:!0});let[n,i,o]=await Promise.all([t.exited,new Response(t.stdout).text(),new Response(t.stderr).text()]);if(e.signal.removeEventListener("abort",r),n!==0)return{status:/not found|enoent/i.test(o)?"unsupported":"unavailable",findings:[],error:o.slice(0,2000)||`Trivy exited with ${n}`};let s=JSON.parse(i),c=[];for(let d of s.Results??[])for(let a of d.Vulnerabilities??[]){let u=a.VulnerabilityID??"unknown-vulnerability";c.push({...e,ruleId:u,severity:VA(a.Severity),title:a.Title||u,description:a.Description||`${u} affects ${a.PkgName??"an image package"}.`,subject:`${e.imageRef}:${a.PkgName??"unknown"}:${a.InstalledVersion??"unknown"}`,evidence:{image:e.imageRef,target:d.Target??"",cve:u,package:a.PkgName??"",installedVersion:a.InstalledVersion??"",fixedVersion:a.FixedVersion??"",reference:a.PrimaryURL??""},remediation:a.FixedVersion?`Upgrade ${a.PkgName} to ${a.FixedVersion} or later.`:"Remove or replace the affected package and rescan the image."})}return{status:c.length?"failed":"passed",findings:c,metadata:{imageRef:e.imageRef,vulnerabilityCount:c.length,localOnly:!0}}}}class WA{actions;id="aws-iam-capabilities";version="1.0.0";timeoutMs=30000;client;constructor(e,t={}){this.actions=e;if(this.resourceArns=t.resourceArns??["*"],t.client)this.client=t.client;else{let r=new ci(t.region),n=new ts(t.region);this.client={getCallerIdentity:()=>r.getCallerIdentity(),simulatePrincipalPolicy:(i)=>n.simulatePrincipalPolicy(i)}}}resourceArns;async scan(e){let t=await this.client.getCallerIdentity();if(!t.Arn)return{status:"unavailable",findings:[],error:"AWS returned no caller ARN"};let r=t.Arn;if(r.includes(":assumed-role/"))return{status:"unsupported",findings:[],error:"AWS policy simulation requires the underlying IAM role ARN; use an IAM role/user ARN or provider-native access analysis.",metadata:{account:t.Account??"",principalType:"assumed-role"}};let o=(await this.client.simulatePrincipalPolicy({PolicySourceArn:r,ActionNames:this.actions,ResourceArns:this.resourceArns})).EvaluationResults.filter((s)=>s.EvalDecision!=="allowed").map((s)=>({...e,ruleId:`iam-${s.EvalActionName.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`,severity:"high",title:`Missing AWS capability: ${s.EvalActionName}`,description:`The active AWS principal is ${s.EvalDecision||"not allowed"} for this deployment action.`,subject:`${r}:${s.EvalActionName}`,evidence:{account:t.Account??"",principalArn:r,action:s.EvalActionName,decision:s.EvalDecision,missingContext:s.MissingContextValues??[]},remediation:"Grant the deployment principal the least-privilege action on the required resources, then rerun the capability check."}));return{status:o.length?"failed":"passed",findings:o,metadata:{account:t.Account??"",principalArn:r,evaluatedActions:this.actions.length}}}}import{createHash as HA,createVerify as KA}from"node:crypto";import{existsSync as JA,readFileSync as GA}from"node:fs";import{basename as QA,join as YA,resolve as fy}from"node:path";function zi(e){return HA("sha256").update(e).digest("hex")}function ZA(e){let t=[["dependencies","required"],["optionalDependencies","optional"],["devDependencies","excluded"],["peerDependencies","required"]],r=new Map;for(let[n,i]of t){let o=e[n];if(!o||typeof o!=="object"||Array.isArray(o))continue;for(let[s,c]of Object.entries(o)){let d=String(c).replace(/^[~^]/,""),a=`${s}@${d}`;if(!r.has(a))r.set(a,{type:"library",name:s,version:d,purl:`pkg:npm/${encodeURIComponent(s)}@${encodeURIComponent(d)}`,scope:i})}}return[...r.values()].sort((n,i)=>`${n.name}@${n.version}`.localeCompare(`${i.name}@${i.version}`))}function hy(e,t={}){let r=YA(fy(e),"package.json");if(!JA(r))throw Error(`Cannot generate an SBOM: ${r} was not found`);let n=GA(r,"utf8"),i=JSON.parse(n),o=String(i.name??QA(fy(e))),s=String(i.version??"0.0.0"),c=zi(n);return{bomFormat:"CycloneDX",specVersion:"1.5",serialNumber:t.serial??`urn:uuid:${crypto.randomUUID()}`,version:1,metadata:{timestamp:(t.now??new Date).toISOString(),component:{type:"application",name:o,version:s,purl:`pkg:npm/${encodeURIComponent(o)}@${encodeURIComponent(s)}`,hashes:[{alg:"SHA-256",content:c}]},tools:[{vendor:"ts-cloud",name:"security-posture",version:"1.0.0"}]},components:ZA(i)}}async function yy(e,t={}){let r=Bun.spawn([t.executable??"syft",e,"-o","cyclonedx-json"],{stdout:"pipe",stderr:"pipe",env:{PATH:process.env.PATH??"/usr/local/bin:/usr/bin:/bin",HOME:"/nonexistent",SYFT_CHECK_FOR_APP_UPDATE:"false"}}),n=()=>r.kill();t.signal?.addEventListener("abort",n,{once:!0});let[i,o,s]=await Promise.all([r.exited,new Response(r.stdout).text(),new Response(r.stderr).text()]);if(t.signal?.removeEventListener("abort",n),i!==0)throw Error(s.slice(0,2000)||`Syft exited with ${i}`);return JSON.parse(o)}function su(e,t,r){let n=JSON.stringify(r);return e.addReleaseArtifact({...t,kind:"sbom",format:`cyclonedx-${r.specVersion}+json`,digest:`sha256:${zi(n)}`,summary:{component:r.metadata.component.name,version:r.metadata.component.version,components:r.components.length},content:n,sensitive:!0})}function vy(e,t,r){let n={total:r.length,critical:0,high:0,medium:0,low:0,info:0,fixable:0};for(let o of r){n[o.severity]++;let s=o.evidence;if(typeof s.fixedVersion==="string"&&s.fixedVersion)n.fixable++}let i=JSON.stringify({releaseId:t.releaseId,generatedAt:new Date().toISOString(),findings:r.map((o)=>({id:o.id,ruleId:o.ruleId,severity:o.severity,subject:o.subject,remediation:o.remediation}))});return e.addReleaseArtifact({...t,kind:"vulnerability_summary",format:"ts-cloud-vulnerability-summary+json",digest:`sha256:${zi(i)}`,summary:n,content:i,sensitive:!0})}function by(e){if(!e.artifact&&!e.artifactSha256)throw Error("Release provenance requires artifact content or a SHA-256 digest");return{_type:"https://in-toto.io/Statement/v1",subject:[{name:e.artifactName,digest:{sha256:e.artifactSha256?.replace(/^sha256:/,"")??zi(e.artifact)}}],predicateType:"https://slsa.dev/provenance/v1",predicate:{buildDefinition:{buildType:"https://ts-cloud.dev/build/v1",externalParameters:e.externalParameters??{},internalParameters:{},resolvedDependencies:e.resolvedDependencies??[]},runDetails:{builder:{id:"https://ts-cloud.dev/builders/local/v1"},metadata:{invocationId:e.invocationId,startedOn:e.startedAt,finishedOn:e.completedAt}}}}}function Sy(e,t,r){let n=JSON.stringify(r);return e.addReleaseArtifact({...t,kind:"provenance",format:"in-toto+slsa-v1+json",digest:`sha256:${zi(n)}`,summary:{subjects:r.subject.length,builder:r.predicate.runDetails.builder.id,buildType:r.predicate.buildDefinition.buildType},content:n,sensitive:!0})}function QM(e){let t=e.expectedSha256.replace(/^sha256:/,"").toLowerCase(),r=zi(e.artifact)===t;if(!e.signature||!e.publicKey)return{digestValid:r,signature:"not_configured"};try{let n=KA("SHA256");return n.update(e.artifact),n.end(),{digestValid:r,signature:n.verify(e.publicKey,Buffer.from(e.signature,"base64"))?"verified":"invalid"}}catch{return{digestValid:r,signature:"invalid"}}}function ar(e,t){let r=e.environments.get(t);if(!r)throw Error(`Security scope for environment '${t}' was not found`);return{organizationId:e.organization.id,projectId:e.project.id,environmentId:r.id}}function wy(e,t){let r=new Do(e.store),n=r.listPolicies(e.organization.id);for(let[i,o]of e.environments){if(n.some((c)=>c.environmentId===o.id))continue;let s=i==="production"||o.kind==="production";n.push(r.createPolicy({organizationId:e.organization.id,environmentId:o.id,name:s?"Production baseline":"Environment baseline",scannerFailMode:s?"closed":"open",requiredScanners:["source-secrets"],rules:s?[{minimumSeverity:"critical",action:"block"},{minimumSeverity:"high",action:"block"},{minimumSeverity:"medium",action:"warn"},{minimumSeverity:"low",action:"record"}]:[{minimumSeverity:"critical",action:"warn"},{minimumSeverity:"high",action:"warn"},{minimumSeverity:"low",action:"record"}],actorId:t}))}return n}function XM(e,t,r,n={}){let i=r.findings.map((o)=>({...t,ruleId:o.pattern.name.toLowerCase().replace(/[^a-z0-9]+/g,"-"),severity:o.pattern.severity,title:o.pattern.name,description:o.pattern.description,subject:`${o.file}:${o.line}`,evidence:{file:o.file,line:o.line,column:o.column,match:o.match,context:o.context},remediation:"Remove and rotate the credential, then reference it through a managed secret or environment variable."}));return e.recordScan({...t,scannerId:"source-secrets",scannerVersion:n.scannerVersion??"1.0.0",status:n.skipped?"skipped":r.passed?"passed":"failed",findings:n.skipped?[]:i,metadata:{scannedFiles:r.scannedFiles,durationMs:r.duration,summary:r.summary},durationMs:r.duration,error:n.skipped?"The operator explicitly skipped source-secret scanning.":void 0})}function e1(e,t,r="The operator explicitly skipped source-secret scanning."){return e.recordScan({...t,scannerId:"source-secrets",scannerVersion:"1.0.0",status:"skipped",findings:[],error:r})}function XA(e,t){let r=[],n=t.security;if(n?.firewall&&!["active","configured","ok"].includes(String(n.firewall.status)))r.push({...e,ruleId:"host-firewall-disabled",severity:"high",title:"Host firewall is not active",description:String(n.firewall.summary??"The host firewall did not report an active configuration."),subject:"host:firewall",evidence:{status:String(n.firewall.status??"unknown"),rules:Array.isArray(n.firewall.rules)?n.firewall.rules.length:0},remediation:"Apply the declarative firewall policy and confirm only required listeners are public."});for(let i of n?.ports??[]){let o=String(i.listen??""),s=Number(o.match(/:(\d+)$/)?.[1]);if(i.exposure==="public"&&Number.isFinite(s)&&![22,80,443].includes(s))r.push({...e,ruleId:"unexpected-public-listener",severity:"medium",title:`Unexpected public listener on port ${s}`,description:`${String(i.processName??"A process")} is listening publicly outside the standard SSH/HTTP/HTTPS ports.`,subject:`host:port:${s}`,evidence:{protocol:String(i.proto??""),listen:o,process:String(i.processName??"")},remediation:"Bind the service to loopback/private networking or explicitly document and firewall the required public port."})}for(let i of n?.tlsCertificates??[]){let o=Number(i.daysRemaining);if(Number.isFinite(o)&&o<30)r.push({...e,ruleId:"tls-certificate-expiry",severity:o<14?"high":"medium",title:`TLS certificate expires in ${o} days`,description:`${String(i.domain??"A configured domain")} needs renewal.`,subject:`tls:${String(i.domain??"unknown")}`,evidence:{domain:String(i.domain??""),daysRemaining:o,expires:String(i.expires??"")},remediation:"Renew the certificate and verify automatic renewal can complete before expiry."})}for(let i of t.diagnostics??[]){if(i.status==="pass"||i.status==="ok")continue;r.push({...e,ruleId:`diagnostic-${String(i.name??"unknown").toLowerCase().replace(/[^a-z0-9]+/g,"-")}`,severity:i.status==="fail"?"high":"medium",title:String(i.name??"Host security check"),description:String(i.detail??"The host security diagnostic did not pass."),subject:`diagnostic:${String(i.name??"unknown")}`,evidence:{status:String(i.status??"unknown")},remediation:"Follow the diagnostic guidance, rerun the check, and confirm the finding resolves."})}return r}function Na(e,t,r){let n=!!r.security||Array.isArray(r.diagnostics),i=n?XA(t,r):[];return e.recordScan({...t,scannerId:"host-posture",scannerVersion:"1.0.0",status:!n?"unavailable":i.length?"failed":"passed",findings:i,metadata:{source:"dashboard-live-probe",checks:Array.isArray(r.diagnostics)?r.diagnostics.length:0},error:n?void 0:"Live host posture data was unavailable; source and provider checks remain usable."})}function ja(e,t){let r=e.evaluateGate({...t.scope,operationId:t.operationId}),n=e.listFindings({...t.scope,limit:1000}).filter((i)=>i.status!=="resolved");return{decision:r,summary:{desiredConfigHash:t.desiredConfigHash??null,securityImpact:{critical:n.filter((i)=>i.severity==="critical").length,high:n.filter((i)=>i.severity==="high").length,waived:n.filter((i)=>i.status==="waived").length,assigned:n.filter((i)=>!!i.ownerActorId).length},blockingFindingIds:r.findingIds,policy:{id:r.policyId,version:r.policyVersion},scannerVersions:r.scannerVersions}}}async function i1(e,t){let r=t.scanner??new ou({timeoutMs:t.scannerTimeoutMs}),i=await new Qn(e,{defaultTimeoutMs:t.scannerTimeoutMs??120000}).run(r,{...t.scope,releaseId:t.releaseId,imageRef:t.imageRef}),o={...t.scope,releaseId:t.releaseId};vy(e,o,i.findings);let s=t.generateImageSbom??yy,c=new AbortController,d=Math.max(100,t.sbomTimeoutMs??120000),a,u=new Promise((y,w)=>{a=setTimeout(()=>{c.abort(),w(Error(`syft-sbom exceeded its ${d}ms timeout`))},d)}),m="unavailable";try{let y=await Promise.race([s(t.imageRef,{signal:c.signal}),u]);su(e,o,y),e.recordScan({...t.scope,releaseId:t.releaseId,scannerId:"syft-sbom",scannerVersion:"local",status:"passed",metadata:{imageRef:t.imageRef,format:`cyclonedx-${y.specVersion}+json`,components:y.components.length,localOnly:!0}}),m="image"}catch(y){let w=y instanceof Error?y.message:String(y);try{let k=hy(t.artifactRoot);su(e,o,k),e.recordScan({...t.scope,releaseId:t.releaseId,scannerId:"syft-sbom",scannerVersion:"local",status:"unsupported",error:`Image inventory was unavailable; attached a package-manifest SBOM instead. ${w}`,metadata:{imageRef:t.imageRef,fallback:"package-manifest",components:k.components.length,localOnly:!0}}),m="manifest"}catch(k){e.recordScan({...t.scope,releaseId:t.releaseId,scannerId:"syft-sbom",scannerVersion:"local",status:"unavailable",error:`Image and manifest SBOM generation were unavailable. ${w}; ${k instanceof Error?k.message:String(k)}`,metadata:{imageRef:t.imageRef,localOnly:!0}})}}finally{if(a)clearTimeout(a)}let h=by({artifactName:t.imageRef,artifact:t.imageSha256?void 0:t.imageRef,artifactSha256:t.imageSha256,invocationId:t.invocationId,startedAt:t.startedAt,completedAt:t.completedAt??new Date().toISOString(),externalParameters:t.externalParameters??{imageRef:t.imageRef}});return Sy(e,o,h),{scan:i,sbomSource:m}}import{randomBytes as ky,scryptSync as Iy,timingSafeEqual as eC}from"node:crypto";function lu(e,t){if(e.role==="admin")return[...t];return t.filter((r)=>!!e.sites?.[r])}var au=32768,cu=8,du=1,tC=32,rC=16;function fn(e){let t=ky(rC),r=Iy(e,t,tC,{N:au,r:cu,p:du,maxmem:268435456});return`scrypt$${au}$${cu}$${du}$${t.toString("base64url")}$${r.toString("base64url")}`}function cr(e,t){try{let r=t.split("$");if(r.length!==6||r[0]!=="scrypt")return!1;let[,n,i,o,s,c]=r,d=Number(n),a=Number(i),u=Number(o);if(!Number.isFinite(d)||!Number.isFinite(a)||!Number.isFinite(u))return!1;let m=Buffer.from(s,"base64url"),h=Buffer.from(c,"base64url");if(m.length===0||h.length===0)return!1;let y=Iy(e,m,h.length,{N:d,r:a,p:u,maxmem:268435456});return eC(y,h)}catch{return!1}}function Ey(e){let[t,r,n,i]=e.split("$");return t!=="scrypt"||Number(r)!==au||Number(n)!==cu||Number(i)!==du}function uu(){return ky(18).toString("base64url")}import{existsSync as lC,readFileSync as uC}from"node:fs";import{join as pC}from"node:path";import{createHash as nC}from"node:crypto";function Ay(e){let t=pu(e.name),r=mu(e.publicKey),n=oC([...e.existingKeys??[],{name:t,publicKey:r}]);return Py(e.configText,n)}function Cy(e){let t=pu(e.name),r=(e.existingKeys??[]).filter((n)=>n.name!==t);if((e.existingKeys??[]).length===r.length)throw Error(`SSH key '${t}' does not exist in compute.sshKeys`);return Py(e.configText,r)}function hn(e=[]){return e.map((t)=>({name:t.name,publicKey:t.publicKey,type:sC(t.publicKey),fingerprint:aC(t.publicKey),added:"configured"}))}function Py(e,t){let r=cC(e,"compute"),n=iC(t),i=dC(e,r.start,r.end,"sshKeys");if(i){let d=i.propertyStart;while(d>0&&e[d-1]!==`
|
|
174
|
+
`&&/\s/.test(e[d-1]))d--;return`${e.slice(0,d)}${n}${e.slice(i.end+1)}`}let o=e.slice(0,r.end).trimEnd(),s=e.slice(r.end),c=o.endsWith(",")||o.endsWith("{")?"":",";return`${o}${c}
|
|
175
|
+
${n},
|
|
176
|
+
${s}`}function iC(e){if(e.length===0)return" sshKeys: []";return` sshKeys: [
|
|
177
|
+
${e.map((r)=>[" {",` name: '${Ry(r.name)}',`,` publicKey: '${Ry(mu(r.publicKey))}',`," },"].join(`
|
|
178
|
+
`)).join(`
|
|
179
|
+
`)}
|
|
180
|
+
]`}function oC(e){let t=new Map;for(let r of e){let n=pu(r.name);if(t.has(n))throw Error(`SSH key '${n}' already exists in compute.sshKeys`);t.set(n,{name:n,publicKey:mu(r.publicKey)})}return[...t.values()]}function pu(e){let t=e.trim();if(!/^[\w@.+-]{2,80}$/.test(t))throw Error("SSH key name must be 2-80 characters and use letters, numbers, @, ., +, _, or -.");return t}function mu(e){let t=e.trim().replace(/\s+/g," "),[r,n]=t.split(" ");if(!/^(?:ssh-(?:ed25519|rsa)|ecdsa-sha2-nistp(?:256|384|521))$/.test(r??"")||!n)throw Error("Public key must be an OpenSSH public key, e.g. ssh-ed25519 AAAA... name@host.");return t}function sC(e){return e.trim().split(/\s+/)[0]||"ssh"}function aC(e){let t=e.trim().split(/\s+/)[1];if(!t)return"-";try{return`SHA256:${nC("sha256").update(Buffer.from(t,"base64")).digest("base64").replace(/=+$/,"")}`}catch{return"-"}}function Ry(e){return e.replace(/\\/g,"\\\\").replaceAll(String.fromCharCode(39),"\\'")}function cC(e,t){let r=new RegExp(`\\b${t}\\s*:\\s*{`,"g").exec(e);if(!r)throw Error(`Could not find ${t}: { ... } in cloud config.`);let n=e.indexOf("{",r.index);return{propertyStart:r.index,start:n,end:No(e,n,"{","}")}}function dC(e,t,r,n){let i=e.slice(t+1,r),o=new RegExp(`\\b${n}\\s*:\\s*\\[`,"g").exec(i);if(!o)return null;let s=t+1+o.index,c=e.indexOf("[",s);return{propertyStart:s,start:c,end:No(e,c,"[","]")}}function No(e,t,r,n){let i=0,o,s=!1,c=!1,d=!1;for(let a=t;a<e.length;a++){let u=e[a],m=e[a+1];if(c){if(u===`
|
|
181
|
+
`)c=!1;continue}if(d){if(u==="*"&&m==="/")d=!1,a++;continue}if(o){if(s){s=!1;continue}if(u==="\\"){s=!0;continue}if(u===o)o=void 0;continue}if(u==="/"&&m==="/"){c=!0,a++;continue}if(u==="/"&&m==="*"){d=!0,a++;continue}if(u==='"'||u==="'"||u==="`"){o=u;continue}if(u===r)i++;if(u===n){if(i--,i===0)return a}}throw Error(`Could not find matching ${n} in cloud config.`)}var mC=["rpx-gateway","nginx","php8.3-fpm","php8.2-fpm","mysql","mariadb","postgresql","redis","redis-server","meilisearch"],Pt="-";function gC(e){let t=String.raw`
|
|
182
|
+
import { X509Certificate } from 'node:crypto'
|
|
183
|
+
import { existsSync, readdirSync, readFileSync, readlinkSync, statSync } from 'node:fs'
|
|
184
|
+
import { basename, join } from 'node:path'
|
|
185
|
+
|
|
186
|
+
const fragmentsRoot = '/etc/rpx/sites.d'
|
|
187
|
+
const certsRoot = '/etc/rpx/certs'
|
|
188
|
+
const projectFilter = ${JSON.stringify(e??"")}
|
|
189
|
+
const configuredRoutes = []
|
|
190
|
+
if (existsSync(fragmentsRoot)) {
|
|
191
|
+
for (const file of readdirSync(fragmentsRoot).filter(name => name.endsWith('.json')).sort()) {
|
|
192
|
+
try {
|
|
193
|
+
const fragment = JSON.parse(readFileSync(join(fragmentsRoot, file), 'utf8'))
|
|
194
|
+
const project = String(fragment.slug || basename(file, '.json'))
|
|
195
|
+
if (projectFilter && project !== projectFilter) continue
|
|
196
|
+
for (const route of Array.isArray(fragment.proxies) ? fragment.proxies : []) {
|
|
197
|
+
if (!route || !route.to) continue
|
|
198
|
+
const path = route.path || '/'
|
|
199
|
+
const staticRoot = typeof route.static === 'string' ? route.static : route.static?.dir
|
|
200
|
+
const kind = route.redirect ? 'redirect' : staticRoot ? 'static' : 'app'
|
|
201
|
+
const install = staticRoot || ''
|
|
202
|
+
const installName = install.match(/^\/var\/www\/(.+?)\/current(?:\/|$)/)?.[1]
|
|
203
|
+
const siteName = installName?.startsWith(project + '-') ? installName.slice(project.length + 1) : String(route.id || route.to)
|
|
204
|
+
const href = 'https://' + route.to + (path === '/' ? '' : path)
|
|
205
|
+
configuredRoutes.push({
|
|
206
|
+
name: siteName,
|
|
207
|
+
project,
|
|
208
|
+
route: path === '/' ? route.to : route.to + path,
|
|
209
|
+
href,
|
|
210
|
+
domain: route.to,
|
|
211
|
+
path,
|
|
212
|
+
kind,
|
|
213
|
+
runtime: kind === 'app' ? 'service' : kind,
|
|
214
|
+
deploy: kind === 'app' ? 'service' : kind === 'static' ? 'server static' : 'redirect',
|
|
215
|
+
tls: 'https',
|
|
216
|
+
root: install || (Array.isArray(route.from) ? route.from.join(', ') : route.from || 'gateway'),
|
|
217
|
+
branch: kind === 'static' ? 'build artifact' : 'main',
|
|
218
|
+
install,
|
|
219
|
+
})
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
catch {}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
async function mapWithConcurrency(values, limit, mapper) {
|
|
227
|
+
const results = new Array(values.length)
|
|
228
|
+
let next = 0
|
|
229
|
+
const workers = Array.from({ length: Math.min(limit, values.length) }, async () => {
|
|
230
|
+
while (next < values.length) {
|
|
231
|
+
const index = next++
|
|
232
|
+
results[index] = await mapper(values[index])
|
|
233
|
+
}
|
|
234
|
+
})
|
|
235
|
+
await Promise.all(workers)
|
|
236
|
+
return results
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
const routes = await mapWithConcurrency(configuredRoutes, 8, async route => {
|
|
240
|
+
const started = performance.now()
|
|
241
|
+
let httpStatus = 0
|
|
242
|
+
const probe = async (href) => {
|
|
243
|
+
const response = await fetch(href, {
|
|
244
|
+
method: 'GET',
|
|
245
|
+
redirect: 'manual',
|
|
246
|
+
headers: { 'user-agent': 'ts-cloud-monitor/1.0' },
|
|
247
|
+
signal: AbortSignal.timeout(6000),
|
|
248
|
+
})
|
|
249
|
+
const status = response.status
|
|
250
|
+
await response.arrayBuffer()
|
|
251
|
+
return status
|
|
252
|
+
}
|
|
253
|
+
try {
|
|
254
|
+
httpStatus = await probe(route.href)
|
|
255
|
+
if (httpStatus === 404 && route.kind === 'app') {
|
|
256
|
+
const healthHref = route.href.replace(/\/$/, '') + '/health'
|
|
257
|
+
httpStatus = await probe(healthHref)
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
catch {}
|
|
261
|
+
const responseMs = Math.max(0, Math.round(performance.now() - started))
|
|
262
|
+
let tlsDaysRemaining
|
|
263
|
+
const cert = join(certsRoot, route.domain + '.crt')
|
|
264
|
+
if (existsSync(cert)) {
|
|
265
|
+
try {
|
|
266
|
+
const expiresAt = Date.parse(new X509Certificate(readFileSync(cert)).validTo)
|
|
267
|
+
if (Number.isFinite(expiresAt)) tlsDaysRemaining = Math.floor((expiresAt - Date.now()) / 86400000)
|
|
268
|
+
}
|
|
269
|
+
catch {}
|
|
270
|
+
}
|
|
271
|
+
let release
|
|
272
|
+
let deployedAt
|
|
273
|
+
if (route.install) {
|
|
274
|
+
try {
|
|
275
|
+
release = basename(readlinkSync(route.install))
|
|
276
|
+
deployedAt = statSync(route.install).mtime.toISOString()
|
|
277
|
+
}
|
|
278
|
+
catch {}
|
|
279
|
+
}
|
|
280
|
+
const status = httpStatus === 0 || httpStatus >= 500 ? 'failed' : httpStatus === 404 ? 'degraded' : 'live'
|
|
281
|
+
const { install, ...site } = route
|
|
282
|
+
return {
|
|
283
|
+
...site,
|
|
284
|
+
status,
|
|
285
|
+
httpStatus,
|
|
286
|
+
responseMs,
|
|
287
|
+
tlsDaysRemaining,
|
|
288
|
+
checkedAt: new Date().toISOString(),
|
|
289
|
+
release,
|
|
290
|
+
deployedAt,
|
|
291
|
+
}
|
|
292
|
+
})
|
|
293
|
+
for (const route of routes) console.log('DISCOVERED_SITE=' + Buffer.from(JSON.stringify(route)).toString('base64'))
|
|
294
|
+
|
|
295
|
+
const serviceOutput = Bun.spawnSync([
|
|
296
|
+
'systemctl', 'list-units', '--type=service', '--state=running', '--no-legend', '--plain',
|
|
297
|
+
]).stdout.toString()
|
|
298
|
+
const runningUnits = serviceOutput
|
|
299
|
+
.split('\n')
|
|
300
|
+
.map(line => line.trim().split(/\s+/)[0])
|
|
301
|
+
.filter(Boolean)
|
|
302
|
+
if (runningUnits.length > 0) {
|
|
303
|
+
const propertiesOutput = Bun.spawnSync([
|
|
304
|
+
'systemctl',
|
|
305
|
+
'show',
|
|
306
|
+
...runningUnits,
|
|
307
|
+
'--property=Id,WorkingDirectory,ExecStart,MemoryCurrent,UnitFileState,ActiveEnterTimestamp',
|
|
308
|
+
]).stdout.toString()
|
|
309
|
+
for (const properties of propertiesOutput.split(/\n\n+/)) {
|
|
310
|
+
const values = Object.fromEntries(properties.split('\n').filter(Boolean).map(value => {
|
|
311
|
+
const separator = value.indexOf('=')
|
|
312
|
+
return separator < 0 ? [value, ''] : [value.slice(0, separator), value.slice(separator + 1)]
|
|
313
|
+
}))
|
|
314
|
+
const unit = values.Id
|
|
315
|
+
if (!unit) continue
|
|
316
|
+
if (!/^\/var\/www\/|^\/opt\/ts-cloud\//.test(values.WorkingDirectory || '') && !/\/var\/www\/|\/opt\/ts-cloud\//.test(values.ExecStart || '')) continue
|
|
317
|
+
console.log([
|
|
318
|
+
'SVC',
|
|
319
|
+
unit,
|
|
320
|
+
'active',
|
|
321
|
+
values.MemoryCurrent || '0',
|
|
322
|
+
values.UnitFileState || '-',
|
|
323
|
+
values.ActiveEnterTimestamp || '-',
|
|
324
|
+
].join('='))
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
`;return`echo '${Buffer.from(t).toString("base64")}' | base64 -d | bun -`}function fC(e={}){let t=["set +e",'echo "CPUS=$(nproc 2>/dev/null || echo 1)"',`read TS_TOTAL_1 TS_IDLE_1 <<EOF
|
|
328
|
+
$(awk '/^cpu /{idle=$5+$6; total=0; for(i=2;i<=NF;i++) total+=$i; print total, idle; exit}' /proc/stat 2>/dev/null)
|
|
329
|
+
EOF`,"sleep 0.2",`read TS_TOTAL_2 TS_IDLE_2 <<EOF
|
|
330
|
+
$(awk '/^cpu /{idle=$5+$6; total=0; for(i=2;i<=NF;i++) total+=$i; print total, idle; exit}' /proc/stat 2>/dev/null)
|
|
331
|
+
EOF`,`echo "CPUUSED=$(awk -v t1="$TS_TOTAL_1" -v i1="$TS_IDLE_1" -v t2="$TS_TOTAL_2" -v i2="$TS_IDLE_2" 'BEGIN { dt=t2-t1; di=i2-i1; if (dt>0) printf "%.1f", 100*(dt-di)/dt; else print 0 }')"`,`echo "LOAD=$(cut -d' ' -f1 /proc/loadavg 2>/dev/null || echo 0)"`,`echo "LOAD5=$(cut -d' ' -f2 /proc/loadavg 2>/dev/null || echo 0)"`,`echo "LOAD15=$(cut -d' ' -f3 /proc/loadavg 2>/dev/null || echo 0)"`,`read MEMTOTAL MEMUSED MEMAVAILABLE MEMCACHE SWAPTOTAL SWAPUSED <<EOF
|
|
332
|
+
$(free -m 2>/dev/null | awk '/^Mem:/{total=$2; used=$3; available=$7; cache=$6} /^Swap:/{print total, used, available, cache, $2, $3}')
|
|
333
|
+
EOF`,'echo "MEMTOTAL=${MEMTOTAL:-0}"','echo "MEMUSED=${MEMUSED:-0}"','echo "MEMAVAILABLE=${MEMAVAILABLE:-0}"','echo "MEMCACHE=${MEMCACHE:-0}"','echo "SWAPTOTAL=${SWAPTOTAL:-0}"','echo "SWAPUSED=${SWAPUSED:-0}"',`read DISKTOTG DISKUSEDG DISKPCT <<EOF
|
|
334
|
+
$(df -BG -P / 2>/dev/null | awk 'NR==2{gsub("G","",$2); gsub("G","",$3); gsub("%","",$5); print $2, $3, $5}')
|
|
335
|
+
EOF`,'echo "DISKPCT=${DISKPCT:-0}"','echo "DISKUSEDG=${DISKUSEDG:-0}"','echo "DISKTOTG=${DISKTOTG:-0}"',`echo "INODEPCT=$(df -Pi / 2>/dev/null | awk 'NR==2{gsub("%","",$5);print $5}')"`,`echo "NETRX=$(awk -F'[: ]+' 'NR>2 && $2!="lo"{sum+=$3} END{print sum+0}' /proc/net/dev 2>/dev/null)"`,`echo "NETTX=$(awk -F'[: ]+' 'NR>2 && $2!="lo"{sum+=$11} END{print sum+0}' /proc/net/dev 2>/dev/null)"`,". /var/lib/ts-cloud/bandwidth-state 2>/dev/null || true",'echo "NETRXRATE=${RX_RATE:-0}"','echo "NETTXRATE=${TX_RATE:-0}"','echo "NETRXTODAY=${DAY_RX:-0}"','echo "NETTXTODAY=${DAY_TX:-0}"','echo "NETRXMONTH=${MONTH_RX:-0}"','echo "NETTXMONTH=${MONTH_TX:-0}"','echo "NETMONTHKEY=${MONTH_KEY:-}"',`echo "PROCESSES=$(ps -e --no-headers 2>/dev/null | awk 'END{print NR+0}')"`,`echo "UPTIME=$(uptime -p 2>/dev/null | sed 's/^up //' || echo unknown)"`,`echo "UPTIME_SECONDS=$(cut -d' ' -f1 /proc/uptime 2>/dev/null || echo 0)"`,'echo "OS=$(. /etc/os-release 2>/dev/null; echo "$PRETTY_NAME")"'];if(e.includeServices!==!1)t.push(`for s in ${mC.join(" ")}; do st=$(systemctl is-active "$s" 2>/dev/null); if [ -n "$st" ] && [ "$st" != "inactive" ] && [ "$st" != "unknown" ]; then mem=$(systemctl show "$s" -p MemoryCurrent --value 2>/dev/null); en=$(systemctl is-enabled "$s" 2>/dev/null); since=$(systemctl show "$s" -p ActiveEnterTimestamp --value 2>/dev/null); echo "SVC=$s=$st=$mem=$en=$since"; fi; done`);if(e.includeSites!==!1)t.push(gC(e.projectFilter));return t.push("true"),t}function hC(e){let t={services:[],discoveredSites:[]};for(let r of e.split(`
|
|
336
|
+
`)){let n=r.trim();if(n.startsWith("DISCOVERED_SITE="))try{let i=JSON.parse(Buffer.from(n.slice(16),"base64").toString("utf8"));if(i?.domain&&i?.route)t.discoveredSites.push(i)}catch{}else if(n.startsWith("SVC=")){let[,i,o,s,c,d]=/^SVC=([^=]+)=([^=]+)(?:=([^=]*)(?:=([^=]*)(?:=(.*))?)?)?$/.exec(n)??[];if(i)t.services.push({name:i,status:o,memBytes:Number(s||0),enabled:c||Pt,since:d||Pt})}else{let i=n.indexOf("=");if(i>0)t[n.slice(0,i)]=n.slice(i+1)}}return t}function xy(e){let t=e.infrastructure?.compute,r=[];if(t?.webServer==="rpx"||t?.proxy?.engine==="rpx")r.push({name:"rpx-gateway",status:"configured"});else if(t?.webServer==="nginx"||t?.webServer==null)r.push({name:"ts-cloud-nginx",status:"configured"});let n=t?.php?.versions??(t?.runtime==="php"?["8.3"]:[]);for(let s of n)r.push({name:`php${s}-fpm`,status:"configured"});let i=t?.managedServices??{},o=[["mysql","mysql"],["mariadb","mariadb"],["postgres","postgresql"],["redis","redis"],["memcached","memcached"],["meilisearch","meilisearch"]];for(let[s,c]of o)if(i[s])r.push({name:c,status:"configured"});return r}function yC(e){let t=e.infrastructure?.compute?.backups,r=!!t?.enabled,n=t?.schedule??"0 2 * * *";return{enabled:r,schedule:n,destination:r?t?.bucket??"local":"off",retention:r?t?.retentionCount??5:0,last:r?"pending first run":"not configured",size:r?Pt:"0 MB"}}function Dy(e){return e.infrastructure?.compute?.provider??e.cloud?.provider??e.provider??"aws"}function vC(e){if(Dy(e)==="hetzner")return Ty(e);return e.project.region??"us-east-1"}function bC(e){let t=e.infrastructure?.compute?.monitoring,r=Number(typeof t==="object"?t?.alerts?.bandwidthTb??0:0);return Number.isFinite(r)&&r>0?Math.round(r*1000000000000):0}function SC(e,t){let r=pC(process.cwd(),"storage","cloud","state",`${e.project.slug}-${t}.json`);if(!lC(r))return null;try{return JSON.parse(uC(r,"utf8"))}catch{return null}}function wC(e){let t=e.sites??{},r=[];for(let[n,i]of Object.entries(t)){let o=i.queues??i.workers;if(Array.isArray(o)){for(let s of o)if(typeof s==="string")r.push({name:`${n}:${s}`,site:n,processes:1,status:"configured"});else if(s?.name)r.push({name:`${n}:${s.name}`,site:n,processes:s.processes??1,status:"configured"})}}return r}function Oy(e){if(!e||e==="")return"/";return e.startsWith("/")?e:`/${e}`}function kC(e){let t=Oy(e.path);if(!e.domain)return{route:"internal"};return{route:t==="/"?e.domain:`${e.domain}${t}`,href:`https://${e.domain}${t==="/"?"":t}`}}function _y(e,t){let r=zr(t);if(r==="redirect")return"redirect";if(r==="proxy")return"proxy";let n=String(t.build??"").toLowerCase(),i=String(t.start??"").toLowerCase();if(e==="main"||i.includes("buddy/src/cli.ts serve"))return"stacks";if(e==="api"||i.includes("/serve/api"))return"api";if(n.includes("buildblog"))return"bunpress blog";if(n.includes("bunpress"))return"bunpress";if(n.includes("site:build")||n.includes("stx"))return"stx static";if(r==="server-static")return t.spa?"spa":"static";if(r==="server-app")return"app";if(r==="server-php")return t.type??"php";return"bucket"}function IC(e){let t=zr(e);if(t==="redirect"||t==="proxy")return"—";let r=`${e.start??""} ${e.build??""}`.toLowerCase();if(t==="server-static")return r.includes("bunpress")||r.includes("bun ")||r.includes("bunx ")?"static/bun":"static";if(t==="server-app")return r.includes("bun")?"bun":"node";if(t==="server-php")return`php ${e.php??e.phpVersion??"8.3"}`;return"static"}function EC(e){let t=zr(e);if(t==="redirect")return"redirect";if(t==="proxy")return"proxy";if(t==="server-app")return"service";if(t==="server-static")return"server static";if(t==="server-php")return"php release";return"bucket"}function RC(e){let t=new Map;return Object.entries(e.sites??{}).map(([r,n])=>{let i=Oy(n.path),{route:o,href:s}=kC(n),c=n.domain?`${n.domain}${i}`:"",d=c?t.get(c):void 0;if(c&&!d)t.set(c,r);return{name:r,route:o,href:s,domain:n.domain??"internal",path:i,kind:_y(r,n),type:_y(r,n),runtime:IC(n),deploy:EC(n),tls:n.domain?n.ssl===!1?"http":"https":"loopback",ssl:n.domain?n.ssl!==!1:!1,status:d?"shadowed":"live",shadowedBy:d,lastDeploy:Pt}})}function AC(e,t,r){let n=new Map(e.map((i)=>[String(i.route),{...i,project:r,managedBy:"owner"}]));for(let i of t){let o=n.get(i.route),s=o?.name??`${i.project}:${i.name}`;n.set(i.route,{...o,...i,name:s,kind:o?.kind??i.kind,type:o?.type??i.kind,runtime:o?.runtime??i.runtime,deploy:o?.deploy??i.deploy,root:o?.root??i.root,branch:o?.branch??i.branch,managedBy:i.project===r?"owner":"attached"})}return[...n.values()].sort((i,o)=>{if(i.managedBy!==o.managedBy)return i.managedBy==="owner"?-1:1;return String(i.route).localeCompare(String(o.route))})}function gu(e){return`'${e.replaceAll("'","'\\''")}'`}function $y(e){return e.replace(/[\\&/]/g,"\\$&")}function CC(e,t){if(e.length===0)return["true"];return["set +e",...e.map((r)=>{let n=gu(`${yn(t,r)}/.ts-cloud/deploy-history.log`),i=$y(r);return`TS_CLOUD_HISTORY=${n}; { [ -f "$TS_CLOUD_HISTORY" ] && tail -n 24 "$TS_CLOUD_HISTORY" | sed "s/^/DEPLOY=${i}\\t/"; } || true`}),"true"]}function Ny(e){return[...new Set(Object.values(e.sites??{}).map((t)=>t.domain).filter((t)=>typeof t==="string"&&t.length>0))]}function PC(e){return["set +e",'if command -v ss >/dev/null 2>&1; then ss -H -lntup 2>/dev/null | while read -r proto _state _recv _send local _peer rest; do [ -n "$proto" ] && [ -n "$local" ] && printf "PORT=%s\\t%s\\t%s\\n" "$proto" "$local" "$rest"; done; fi','if command -v ufw >/dev/null 2>&1; then ufw status numbered 2>/dev/null | sed "s/^/FIREWALL=/"; else echo "FIREWALL=ufw unavailable"; fi','journalctl _COMM=sshd --no-pager -n 30 -o short-iso 2>/dev/null | sed "s/^/AUTH=/" || true',...Ny(e).map((r)=>`TS_CLOUD_DOMAIN=${gu(r)}; TS_CLOUD_EXPIRY=$(echo | timeout 8 openssl s_client -servername "$TS_CLOUD_DOMAIN" -connect "$TS_CLOUD_DOMAIN:443" 2>/dev/null | openssl x509 -noout -enddate 2>/dev/null | cut -d= -f2-); [ -n "$TS_CLOUD_EXPIRY" ] && printf "CERT=%s\\t%s\\n" "$TS_CLOUD_DOMAIN" "$TS_CLOUD_EXPIRY" || printf "CERT=%s\\tunavailable\\n" "$TS_CLOUD_DOMAIN"`),"true"]}function _C(e){let t=new Map,r=(o,s)=>{if(o&&s&&!t.has(s))t.set(s,{pattern:o,label:s})},n=e.infrastructure?.compute,i=e.project.slug;if(n?.webServer==="rpx"||n?.proxy?.engine==="rpx")r("rpx-gateway","rpx-gateway");else r("nginx","nginx");for(let o of xy(e))r(o.name,o.name);for(let[o,s]of Object.entries(e.sites??{})){if(zr(s)!=="server-app")continue;if(r(`${i}-${o}`,`${i}-${o}`),Array.isArray(s.queues??s.workers)&&(s.queues??s.workers).length)r(`${i}-${o}-queue-*`,`${i}-${o}-queues`);if(Array.isArray(s.daemons)&&s.daemons.length)r(`${i}-${o}-daemon-*`,`${i}-${o}-daemons`)}return[...t.values()]}function TC(e){let t=_C(e);if(t.length===0)return["true"];return["set +e",...t.map((r)=>{let n=gu(r.pattern),i=$y(r.label);return`journalctl -u ${n} --no-pager -n 150 -o short-iso 2>/dev/null | sed "s/^/LOG=${i}\\t/" || true`}),'[ -f /var/log/ts-cloud-backup.log ] && tail -n 60 /var/log/ts-cloud-backup.log 2>/dev/null | sed "s/^/LOG=backups\\t/" || true',"true"]}function fu(e){let t=new Date(e);if(Number.isNaN(t.getTime()))return e||Pt;let r=Math.max(0,Math.round((Date.now()-t.getTime())/1000));if(r<60)return`${r}s ago`;let n=Math.round(r/60);if(n<60)return`${n}m ago`;let i=Math.round(n/60);if(i<48)return`${i}h ago`;return`${Math.round(i/24)}d ago`}function jy(e){if(/(?:error|failed|panic|fatal|exception|denied|unhealthy)/i.test(e))return"error";if(/(?:warn|warning|retry|restart|deprecated|timeout)/i.test(e))return"warn";return"info"}function xC(e){let t=[];for(let r of e.split(`
|
|
337
|
+
`)){let n=r.trim();if(!n.startsWith("LOG="))continue;let i=n.indexOf("\t");if(i<0)continue;let o=n.slice(4,i),s=n.slice(i+1),c=/^(\d{4}-\d{2}-\d{2}T[^\s]+)\s+(\S+)\s+(.*)$/.exec(s),d=c?.[1]??"",a=c?.[2]??"",u=(c?.[3]??s).trim();if(!u)continue;t.push({source:o,timestamp:d,when:d?fu(d):Pt,host:a,message:u,level:jy(u)})}return t.sort((r,n)=>String(n.timestamp).localeCompare(String(r.timestamp))).slice(0,600)}function My(e){if(/^(?:127\.|localhost:|\[?::1\]?)/.test(e))return"loopback";if(/^(?:10\.|192\.168\.|172\.(?:1[6-9]|2\d|3[01])\.|169\.254\.|\[?f[cd][0-9a-f:])/i.test(e))return"private";return"public"}function DC(e){if(My(e)!=="public")return"ok";if(/:(?:22|80|443)$/.test(e)||/^\*:(?:22|80|443)$/.test(e))return"ok";return"warn"}function OC(e){if(e==null)return"warn";if(e<8)return"bad";if(e<30)return"warn";return"ok"}function $C(e){let t=[],r=[],n=[],i=[];for(let c of e.split(`
|
|
338
|
+
`)){let d=c.trim();if(d.startsWith("PORT=")){let[a="",u="",m=""]=d.slice(5).split("\t");if(a&&u)t.push({proto:a,listen:u,processName:m||Pt,exposure:My(u),tone:DC(u)})}else if(d.startsWith("FIREWALL=")){let a=d.slice(9).trim();if(a)r.push(a)}else if(d.startsWith("AUTH=")){let a=d.slice(5),u=/^(\d{4}-\d{2}-\d{2}T[^\s]+)\s+(\S+)\s+(.*)$/.exec(a),m=(u?.[3]??a).trim();if(m)n.push({timestamp:u?.[1]??"",when:u?.[1]?fu(u[1]):Pt,host:u?.[2]??"",message:m,level:jy(m)})}else if(d.startsWith("CERT=")){let[a="",u=""]=d.slice(5).split("\t");if(!a)continue;let m=new Date(u),h=Number.isNaN(m.getTime())?null:Math.ceil((m.getTime()-Date.now())/86400000);i.push({domain:a,expires:Number.isNaN(m.getTime())?u||Pt:m.toISOString().slice(0,10),daysRemaining:h,status:OC(h)})}}let o=r.some((c)=>/Status:\s*active/i.test(c)),s=r.some((c)=>/unavailable/i.test(c));return{ports:t.slice(0,80),firewall:{status:o?"active":s?"unavailable":"inactive",summary:o?"ufw active":s?"ufw unavailable":"ufw inactive or not configured",rules:r.filter((c)=>c&&!/^Status:/i.test(c)).slice(0,60)},tlsCertificates:i,authEvents:n.sort((c,d)=>String(d.timestamp).localeCompare(String(c.timestamp))).slice(0,30)}}function hu(e){let r=e.infrastructure?.compute?.firewall??{},n=[...new Set([22,80,443,...r.allowedPorts??[]])],i=Ny(e);return{ports:n.map((o)=>({proto:"tcp",listen:`0.0.0.0:${o}`,processName:"configured firewall",exposure:"public",tone:[22,80,443].includes(Number(o))?"ok":"warn"})),firewall:{status:r.enabled===!1?"disabled":"configured",summary:r.enabled===!1?"host firewall disabled in config":"host firewall configured declaratively",rules:n.map((o)=>`ALLOW ${o}/tcp`)},tlsCertificates:i.map((o)=>({domain:o,expires:Pt,daysRemaining:null,status:"warn"})),authEvents:[]}}function By(e,t){let r=t.security??hu(e),n=!!t._serverReachable&&!t.metricsUnavailable,i=t.sites??[],o=i.filter((a)=>a.status==="shadowed"),s=(t.services??[]).filter((a)=>["failed","stopped"].includes(a.status)),c=(r.tlsCertificates??[]).filter((a)=>a.status!=="ok"),d=t.sshKeys??[];return[{name:"Live server probe",status:n?"pass":"warn",detail:n?"Metrics and remote checks are coming from the compute box.":"The dashboard is rendering config/state data until the box probe succeeds."},{name:"Managed services",status:s.length?"fail":"pass",detail:s.length?`${s.length} service(s) need attention.`:`${(t.services??[]).length} service(s) reported healthy or configured.`},{name:"Route conflicts",status:o.length?"warn":"pass",detail:o.length?`${o.map((a)=>a.name).join(", ")} is shadowed by an earlier route.`:`${i.length} site route(s) are unshadowed.`},{name:"SSH access",status:d.length?"pass":"warn",detail:d.length?`${d.length} declarative authorized key(s) configured.`:"No declarative SSH keys are configured."},{name:"Firewall",status:["active","configured"].includes(r.firewall?.status)?"pass":"warn",detail:r.firewall?.summary??"Firewall status unavailable."},{name:"TLS certificates",status:c.length?"warn":"pass",detail:c.length?`${c.length} certificate(s) need renewal visibility.`:`${(r.tlsCertificates??[]).length} certificate(s) look healthy.`}]}function Ly(e){let t=[];for(let r of e.serverDeploymentsDetail??e.serverDeployments??[])t.push({type:"deploy",tone:r.status==="failed"?"bad":"ok",title:`${r.site} deployed ${r.sha}`,detail:`${r.branch} · ${r.status}`,when:r.when,timestamp:r.timestamp});for(let r of e.serverLogs??[])if(r.level==="error"||r.level==="warn")t.push({type:"log",tone:r.level==="error"?"bad":"warn",title:`${r.source} ${r.level}`,detail:r.message,when:r.when,timestamp:r.timestamp});for(let r of e.sshKeys??[])t.push({type:"ssh",tone:"ok",title:`${r.name} authorized`,detail:r.fingerprint,when:r.added??Pt,timestamp:""});return t.sort((r,n)=>String(n.timestamp).localeCompare(String(r.timestamp))).slice(0,80)}function NC(e,t={}){let r=[];for(let n of e.split(`
|
|
339
|
+
`)){let i=n.trim();if(!i.startsWith("DEPLOY="))continue;let o=i.split("\t"),s=o[0]?.replace(/^DEPLOY=/,"")??"",[c,d,a,u,m]=o.slice(1);if(!s||!c||!d)continue;let h=t[s]??{},y=zr(h),w=(a||d).slice(0,7);r.push({sha:w,release:d,commit:a||d,site:s,branch:h.branch??(y==="server-static"?"build artifact":"main"),status:u||"unknown",when:fu(c),timestamp:c,took:"-",by:"ts-cloud",rc:m?.replace(/^rc=/,"")??"",steps:y==="server-static"?["upload artifact","publish static files"]:["upload artifact","restart service"]})}return r.sort((n,i)=>String(i.timestamp).localeCompare(String(n.timestamp)))}function jC(e,t){let r=SC(e,t),n=xy(e),i=RC(e),o=Math.max(1,Number(e.infrastructure?.compute?.disk?.size??1)),s={server:{name:r?.serverName??`${e.project.slug}-${t}-app`,provider:r?.provider??Dy(e),region:vC(e),ip:r?.publicIp??Pt,os:"Linux",uptime:Pt,probeStatus:"unavailable"},systemMetrics:{load:0,load5:0,load15:0,cpuUsedPct:0,cpus:Math.max(1,Number(e.infrastructure?.compute?.instances??1)),memUsedMb:0,memTotalMb:0,memAvailableMb:0,memCacheMb:0,swapUsedMb:0,swapTotalMb:0,diskUsedPct:0,diskUsedGb:0,diskTotalGb:o,inodeUsedPct:0,networkRxBytes:0,networkTxBytes:0,networkRxBytesPerSec:0,networkTxBytesPerSec:0,networkRxBytesToday:0,networkTxBytesToday:0,networkRxBytesMonth:0,networkTxBytesMonth:0,networkMonthKey:"",processes:0,uptimeSeconds:0},metricsUnavailable:!0,bandwidthBudgetBytes:bC(e),services:n,servicesDetail:n.map((c)=>({...c,since:Pt,memMb:0,auto:!0})),backup:yC(e),backupHistory:[],workers:wC(e),serverScheduler:{enabled:!1,lastRun:"not configured"},serverDeployments:[],serverDeploymentsDetail:[],deploymentsEmptyReason:"No deployment history has been recorded yet. Future server deploys will write /var/www/<site>/.ts-cloud/deploy-history.log.",serverLogs:[],serverLogsEmptyReason:"Live server logs are unavailable until the dashboard can reach the compute box.",security:hu(e),securityEmptyReason:"Live security checks are unavailable until the dashboard can reach the compute box.",sites:i,sitesDetail:i.map((c)=>{let d=e.sites?.[c.name]??{},a=zr(d);return{...c,root:a==="server-static"?yn(e.project.slug,c.name):`${yn(e.project.slug,c.name)}/current`,branch:a==="server-static"?"build artifact":"main",build:d.build,php:d.php??d.phpVersion,aliases:Array.isArray(d.aliases)?d.aliases:[],redirects:d.redirects&&typeof d.redirects==="object"?d.redirects:{},envKeys:Object.keys(d.env??d.environment??{})}}),siteHealth:[],sshKeys:hn(e.infrastructure?.compute?.sshKeys??[]),_serverReachable:!1,_metricsStatus:"unavailable"};return s.diagnostics=By(e,s),s.activity=Ly(s),s.topology=Pn(s,{project:e.project.name,environment:t}),s}async function Ma(e,t,r={}){if(!e.infrastructure?.compute)return null;let n=null;try{n=ir({config:e})}catch{n=null}let i=null,o=0,s=[];if(n)try{if(s=await n.findComputeTargets({slug:e.project.slug,environment:t,role:"app"}),o=s.length,s.length){let m=(await n.runRemoteDeploy({targets:[s[0]],commands:fC({includeServices:!r.telemetryOnly,includeSites:r.includeSiteHealth!==!1,projectFilter:e.cloud?.attachTo?e.project.slug:void 0}),comment:`ts-cloud dashboard:build ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output;if(m)i=hC(m)}}catch{}let c=jC(e,t),d=(u,m=0)=>{let h=Number(u);return Number.isFinite(h)?h:m};if(c.server.os=i?.OS||c.server.os,c.server.uptime=i?.UPTIME||c.server.uptime,i){if(c.server.probeStatus="live",c.metricsUnavailable=!1,c._metricsStatus="live",c.systemMetrics={load:d(i.LOAD),load5:d(i.LOAD5),load15:d(i.LOAD15),cpuUsedPct:d(i.CPUUSED),cpus:d(i.CPUS,1),memUsedMb:d(i.MEMUSED),memTotalMb:d(i.MEMTOTAL,1),memAvailableMb:d(i.MEMAVAILABLE),memCacheMb:d(i.MEMCACHE),swapUsedMb:d(i.SWAPUSED),swapTotalMb:d(i.SWAPTOTAL),diskUsedPct:d(i.DISKPCT),diskUsedGb:d(i.DISKUSEDG),diskTotalGb:d(i.DISKTOTG,1),inodeUsedPct:d(i.INODEPCT),networkRxBytes:d(i.NETRX),networkTxBytes:d(i.NETTX),networkRxBytesPerSec:d(i.NETRXRATE),networkTxBytesPerSec:d(i.NETTXRATE),networkRxBytesToday:d(i.NETRXTODAY),networkTxBytesToday:d(i.NETTXTODAY),networkRxBytesMonth:d(i.NETRXMONTH),networkTxBytesMonth:d(i.NETTXMONTH),networkMonthKey:i.NETMONTHKEY||"",processes:d(i.PROCESSES),uptimeSeconds:d(i.UPTIME_SECONDS)},i.services.length){let u=[...new Map(i.services.map((m)=>[m.name,m])).values()];c.services=u.map((m)=>({name:m.name,status:m.status==="active"?"running":m.status})),c.servicesDetail=u.map((m)=>({name:m.name,status:m.status==="active"?"running":m.status,since:m.since&&m.since!==Pt?m.since:c.server.uptime,memMb:Math.max(0,Math.round(Number(m.memBytes??0)/1024/1024)),auto:m.enabled?!["disabled","static","masked"].includes(m.enabled):!0}))}if(i.discoveredSites.length)c.sitesDetail=AC(c.sitesDetail,i.discoveredSites,e.project.slug),c.sites=c.sitesDetail.map((u)=>({name:u.name,project:u.project,managedBy:u.managedBy,route:u.route,href:u.href,domain:u.domain,path:u.path,kind:u.kind,type:u.type,runtime:u.runtime,deploy:u.deploy,tls:u.tls,status:u.status,httpStatus:u.httpStatus,responseMs:u.responseMs,tlsDaysRemaining:u.tlsDaysRemaining,checkedAt:u.checkedAt})),c.siteHealth=c.sitesDetail.map((u)=>({name:u.name,project:u.project,route:u.route,status:u.status,httpStatus:u.httpStatus,responseMs:u.responseMs,tlsDaysRemaining:u.tlsDaysRemaining,checkedAt:u.checkedAt}))}if(n&&s.length&&!r.telemetryOnly)await Promise.all([(async()=>{try{let u=Object.keys(e.sites??{}),h=(await n.runRemoteDeploy({targets:[s[0]],commands:CC(u,e.project.slug),comment:`ts-cloud dashboard:deploy-history ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",y=NC(h,e.sites);c.serverDeployments=y.slice(0,5),c.serverDeploymentsDetail=y.slice(0,50),c.deploymentsEmptyReason=y.length?void 0:"No deployment history was found on the server yet. Deploy again to populate this timeline."}catch{c.deploymentsEmptyReason="Deployment history could not be read from the server."}})(),(async()=>{try{let m=(await n.runRemoteDeploy({targets:[s[0]],commands:TC(e),comment:`ts-cloud dashboard:server-logs ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",h=xC(m);c.serverLogs=h,c.serverLogsEmptyReason=h.length?void 0:"No recent journal entries were found for the managed server units."}catch{c.serverLogsEmptyReason="Server logs could not be read from the box."}})(),(async()=>{try{let m=(await n.runRemoteDeploy({targets:[s[0]],commands:PC(e),comment:`ts-cloud dashboard:security ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",h=$C(m),y=hu(e);if(!h.ports.length)h.ports=y.ports;if(!h.tlsCertificates.length)h.tlsCertificates=y.tlsCertificates;c.security=h,c.securityEmptyReason=void 0}catch{c.securityEmptyReason="Server security checks could not be read from the box."}})()]);else if(n&&o===0)c.deploymentsEmptyReason="No app server target was found for this environment.";let a=e.infrastructure?.compute?.sshKeys??e.infrastructure?.ssh?.keys??e.infrastructure?.sshKeys;if(Array.isArray(a)&&a.length)c.sshKeys=hn(a);return c._serverReachable=o>0&&!!i,c.diagnostics=By(e,c),c.activity=Ly(c),c.topology=Pn(c,{project:e.project.name,environment:t}),c}var MC=new Set(["singlestore","vitess"]);function Fa(e){return MC.has(e)}var La={mysql:"/var/lib/pantry/mysql/mysqld.sock",mariadb:"/var/lib/pantry/mariadb/mariadbd.sock"};function Ur(e){return/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(e)}function BC(e){if(e==="postgres"||e==="pgsql")return"postgres";if(e==="mariadb")return"mariadb";if(e==="singlestore")return"singlestore";if(e==="vitess")return"vitess";return"mysql"}function Zn(e){let t=e.infrastructure?.compute,r=gt(e)?.engine;if(r)return BC(r);let n=t?.managedServices??{};if(n.postgres)return"postgres";if(n.mariadb)return"mariadb";return"mysql"}var yu=(e)=>e.replace(/`/g,"``"),vr=(e)=>e.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),Yn=(e)=>`"${e.replace(/"/g,'""')}"`,Ba=(e)=>`'${e.replace(/'/g,"''")}'`;function bu(e,t){return[`mysql --socket=${e==="mariadb"?La.mariadb:La.mysql} -u root <<'TS_CLOUD_SQL_EOF'`,...t,"TS_CLOUD_SQL_EOF"]}function Su(e,t){return[`${vu(t)} -tA <<'TS_CLOUD_PG_EOF'`,...e,"TS_CLOUD_PG_EOF"]}function LC(e,t){if(e==="vitess")return FC(t);if(e==="postgres")return Su(["SELECT 'DB=' || datname FROM pg_database WHERE datistemplate = false;","SELECT 'USER=' || usename FROM pg_user;"],t);return bu(e,["SELECT CONCAT('DB=', schema_name) FROM information_schema.schemata WHERE schema_name NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys');","SELECT DISTINCT CONCAT('USER=', User) FROM mysql.user WHERE User NOT IN ('root', 'mysql.sys', 'mysql.session', 'mysql.infoschema', 'debian-sys-maint');"])}function Ui(e,t,r){let n=t?.host??"127.0.0.1",i=t?.username??"root",o=t?.password??"",s=t?.ssl===!1?"":" --ssl-mode=PREFERRED",c=(a)=>`'${String(a).replace(/'/g,"'\\''")}'`;return[`${o?`MYSQL_PWD=${c(o)} `:""}mysql -h ${c(n)} -P ${t?.port??r} -u ${c(i)}${s} --batch --skip-column-names <<'TS_CLOUD_SQL_EOF'`,...e,"TS_CLOUD_SQL_EOF"]}var qi=15306;function FC(e){let t=Ui(["SHOW KEYSPACES;"],e,qi);return t[0]=`${t[0]} | sed 's/^/DB=/'`,t}function zC(e){return Ui(["SHOW KEYSPACES;","SHOW VITESS_SHARDS;","SHOW VITESS_TABLETS;"],e,qi)}function UC(e){let t=[],r=[],n=[];for(let i of e.split(`
|
|
340
|
+
`)){let o=i.trim();if(!o)continue;let s=o.split("\t").map((c)=>c.trim()).filter(Boolean);if(s.length>=6){let[c,d,a,u,m,h,y]=s;n.push({cell:c??"",keyspace:d??"",shard:a??"",type:u??"",state:m??"",alias:h??"",hostname:y??""});continue}if(s.length===1){let c=s[0];if(c.includes("/")){let[d,a]=c.split("/");if(d&&a)r.push({keyspace:d,shard:a})}else t.push(c)}}return{keyspaces:[...new Set(t)].filter(Boolean).sort(),shards:r,tablets:n}}function qC(e,t,r){if(e==="postgres")return Su([`SELECT 'CREATE DATABASE ${Yn(t)}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = ${Ba(t)})\\gexec`],r);return bu(e,[`CREATE DATABASE IF NOT EXISTS \`${yu(t)}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`])}function VC(e,t,r){let{username:n,password:i,database:o,access:s}=t;if(e==="postgres"){let a=["DO $$ BEGIN",` IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${Ba(n)}) THEN CREATE ROLE ${Yn(n)} LOGIN PASSWORD ${Ba(i)};`,` ELSE ALTER ROLE ${Yn(n)} LOGIN PASSWORD ${Ba(i)}; END IF;`,"END $$;"];if(o)a.push(s==="readonly"?`GRANT CONNECT ON DATABASE ${Yn(o)} TO ${Yn(n)};`:`GRANT ALL PRIVILEGES ON DATABASE ${Yn(o)} TO ${Yn(n)};`);return Su(a,r)}let c=s==="readonly"?"SELECT":"ALL PRIVILEGES",d=[`CREATE USER IF NOT EXISTS '${vr(n)}'@'%' IDENTIFIED BY '${vr(i)}';`,`CREATE USER IF NOT EXISTS '${vr(n)}'@'localhost' IDENTIFIED BY '${vr(i)}';`,`ALTER USER '${vr(n)}'@'%' IDENTIFIED BY '${vr(i)}';`,`ALTER USER '${vr(n)}'@'localhost' IDENTIFIED BY '${vr(i)}';`];if(o)d.push(`GRANT ${c} ON \`${yu(o)}\`.* TO '${vr(n)}'@'%';`,`GRANT ${c} ON \`${yu(o)}\`.* TO '${vr(n)}'@'localhost';`);return d.push("FLUSH PRIVILEGES;"),bu(e,d)}function WC(e){let t=[],r=[];for(let n of e.split(`
|
|
341
|
+
`)){let i=n.trim();if(i.startsWith("DB="))t.push(i.slice(3));else if(i.startsWith("USER="))r.push(i.slice(5))}return{databases:[...new Set(t)].filter(Boolean).sort(),users:[...new Set(r)].filter(Boolean).sort()}}async function _t(e,t,r,n){let i;try{i=ir({config:e})}catch(d){return{ok:!1,error:`Could not initialize the cloud driver: ${d?.message??d}`}}let o=e.project.slug,s=await i.findComputeTargets({slug:o,environment:t,role:"app"});if(!s.length)return{ok:!1,error:"No app server target was found for this environment."};let c=await i.runRemoteDeploy({targets:[s[0]],commands:["set -uo pipefail",...r],comment:n,tags:{Project:o,Environment:t,Role:"app"}});return{ok:c.success,stdout:c.perInstance?.[0]?.output??"",stderr:c.perInstance?.[0]?.error??c.error??""}}function za(e,t){return{ok:!1,error:`${t} is not available for ${e}: it is an external cluster, so this box has no engine to administer. ${e==="vitess"?"Create a keyspace with `vtctldclient CreateKeyspace`, and manage vtgate credentials on the cluster.":"Use the provider console or the cluster's own admin connection."}`}}async function Fy(e,t){let r=Zn(e);if(Fa(r)&&r!=="vitess")return{...za(r,"Listing databases"),engine:r,databases:[],users:[]};let n=await _t(e,t,LC(r,gt(e)),"ts-cloud db:list"),i=n.ok&&n.stdout?WC(n.stdout):{databases:[],users:[]};return{...n,engine:r,...i}}async function zy(e,t,r){let n=Zn(e);if(Fa(n))return za(n,"Creating a database");return _t(e,t,qC(n,r,gt(e)),`ts-cloud db:create ${r}`)}async function Uy(e,t,r){let n=Zn(e);if(Fa(n))return za(n,"Creating a database user");return _t(e,t,VC(n,r,gt(e)),`ts-cloud db:user ${r.username}`)}var wu="/var/backups/ts-cloud/databases";function HC(e,t,r=wu,n){let o=`${r}/${t}-$TS_CLOUD_BACKUP_STAMP.sql.gz`,s=`mkdir -p ${r}`;if(e==="postgres")return[s,'TS_CLOUD_BACKUP_STAMP="$(date +%Y%m%d-%H%M%S)"',`${vu(n,"pg_dump")} ${t} | gzip > "${o}"`,`echo "BACKUP=${o}"`,`ls -l "${o}"`];let c=e==="mariadb"?La.mariadb:La.mysql;return[s,'TS_CLOUD_BACKUP_STAMP="$(date +%Y%m%d-%H%M%S)"',`mysqldump --socket=${c} -u root ${t} | gzip > "${o}"`,`echo "BACKUP=${o}"`,`ls -l "${o}"`]}function KC(e=wu){return[`ls -1t ${e}/*.sql.gz 2>/dev/null | head -50 | sed 's|^|BACKUP=|' || true`]}function JC(e){let t=[];for(let r of e.split(`
|
|
342
|
+
`)){let n=r.trim();if(!n.startsWith("BACKUP="))continue;let i=n.slice(7),s=(i.split("/").pop()??i).replace(/-\d{8}-\d{6}\.sql\.gz$/,"");if(i)t.push({file:i,database:s})}return t}async function qy(e,t,r){if(!Ur(r))return{ok:!1,error:"Database name must be a valid identifier.",database:r};let n=Zn(e);if(Fa(n))return{...za(n,"Backing up"),database:r};return{...await _t(e,t,HC(n,r,wu,gt(e)),`ts-cloud db:backup ${r}`),database:r}}async function Vy(e,t){let r=await _t(e,t,KC(),"ts-cloud db:backups"),n=r.ok&&r.stdout?JC(r.stdout):[];return{...r,backups:n}}async function Wy(e,t){let r=Zn(e),n={keyspaces:[],shards:[],tablets:[]};if(r!=="vitess")return{ok:!1,error:"The configured database engine is not Vitess.",engine:r,...n};let i=await _t(e,t,zC(gt(e)),"ts-cloud vitess:topology"),o=i.ok&&i.stdout?UC(i.stdout):n;return{...i,engine:r,...o}}function Hy(e){return e.filter((t)=>t.state.toUpperCase()!=="SERVING")}function Ky(e){let t=new Set(e.tablets.filter((r)=>r.type.toUpperCase()==="PRIMARY"&&r.state.toUpperCase()==="SERVING").map((r)=>`${r.keyspace}/${r.shard}`));return e.shards.filter((r)=>!t.has(`${r.keyspace}/${r.shard}`))}var ku="/usr/local/bin/vtctldclient",GC="21.0.0";function qa(e){return`'${String(e).split("'").join("'\\''")}'`}function Va(e){return gt(e)?.vitess??{}}function Jy(e){return/^[A-Za-z_][A-Za-z0-9_]{0,63}$/.test(e)}function QC(e){return/^[0-9a-f]{8}(?:_[0-9a-f]{4}){3}_[0-9a-f]{12}$/i.test(e)}function YC(e=GC){let t=qa(e);return[`if ${ku} --version 2>/dev/null | grep -q ${t}; then echo "vtctldclient ${e} already installed"; else`," command -v curl >/dev/null 2>&1 || (apt-get update -y && apt-get install -y curl ca-certificates)",' if [ "$(uname -m)" != "x86_64" ]; then',' echo "vtctldclient: Vitess publishes only an x86_64 release tarball; this box is $(uname -m). Build from source or install via pantry." >&2'," exit 1"," fi",' tmp="$(mktemp -d)"',` api="https://api.github.com/repos/vitessio/vitess/releases/tags/v${e}"`,` url="$(curl -fsSL "$api" | grep -oE '"browser_download_url"[[:space:]]*:[[:space:]]*"[^"]+vitess-[0-9][^"]*\\.tar\\.gz"' | head -1 | sed -E 's/.*"(https[^"]+)"/\\1/')"`,' if [ -z "$url" ]; then echo "vtctldclient: no release tarball found for v'+e+'" >&2; rm -rf "$tmp"; exit 1; fi',` curl -fsSL "$url" | tar -xz -C "$tmp" --strip-components=2 --wildcards --occurrence=1 '*/bin/vtctldclient' || true`,' if [ ! -s "$tmp/vtctldclient" ]; then',' echo "vtctldclient: could not extract the binary from $url" >&2',' rm -rf "$tmp"; exit 1'," fi",` install -m 0755 "$tmp/vtctldclient" ${ku}`,' rm -rf "$tmp"',` echo "installed vtctldclient ${e}"`,"fi"]}function Gy(e){if(!e.vtctldAddr)return null;return`${ku} --server ${qa(e.vtctldAddr)}`}function ZC(e,t,r={}){let n=Gy(e);if(!n)return null;let i=r.sharded?" --sharded":"";return[`${n} CreateKeyspace${i} ${qa(t)}`]}function XC(e,t,r){let n=Gy(e);if(!n)return null;return['vschema_tmp="$(mktemp)"',`cat > "$vschema_tmp" <<'TS_CLOUD_VSCHEMA_EOF'`,r,"TS_CLOUD_VSCHEMA_EOF",`${n} ApplyVSchema --vschema-file "$vschema_tmp" ${qa(t)}`,'rm -f "$vschema_tmp"']}function eP(e,t,r="vitess"){return Ui([`SET @@ddl_strategy='${r}';`,t.endsWith(";")?t:`${t};`],e,qi)}function tP(e,t){let r=t?[`USE ${t.replace(/[^A-Z0-9_]/gi,"")};`,"SHOW VITESS_MIGRATIONS;"]:["SHOW VITESS_MIGRATIONS;"],n=Ui(r,e,qi);return n[0]=n[0].replace(" --skip-column-names",""),n}function rP(e){let t=e.split(`
|
|
343
|
+
`).map((s)=>s.trimEnd()).filter((s)=>s.trim().length>0);if(t.length===0)return[];let r=t[0].split("\t").map((s)=>s.trim()),n=(s)=>r.indexOf(s),i={uuid:n("migration_uuid"),keyspace:n("keyspace"),shard:n("shard"),table:n("mysql_table"),status:n("migration_status"),strategy:n("strategy"),added:n("added_timestamp"),completed:n("completed_timestamp"),progress:n("progress")};if(i.uuid===-1)return[];let o=[];for(let s of t.slice(1)){let c=s.split("\t"),d=(u)=>u>=0?(c[u]??"").trim():"",a=d(i.uuid);if(!a)continue;o.push({uuid:a,keyspace:d(i.keyspace),shard:d(i.shard),table:d(i.table),status:d(i.status),strategy:d(i.strategy),added:d(i.added),completed:d(i.completed),progress:d(i.progress)})}return o}function nP(e){return e.filter((t)=>t.status.toLowerCase()==="failed")}function iP(e){return e.filter((t)=>["running","queued","ready"].includes(t.status.toLowerCase()))}function oP(e,t,r){let n=r.toUpperCase();return Ui([`ALTER VITESS_MIGRATION '${t}' ${n};`],e,qi)}function Vi(e){if(Zn(e)!=="vitess")return{ok:!1,error:"The configured database engine is not Vitess."};return null}function Ua(e){if(!e.vtctldAddr)return{ok:!1,error:"No vtctld address is configured. Creating keyspaces and applying a VSchema are topology operations that vtgate cannot perform. Set `infrastructure.appDatabase.vitess.vtctldAddr` (for example `vtctld.internal:15999`) and redeploy."};return null}async function Qy(e,t){let r=Vi(e);if(r)return r;let n=Va(e);return _t(e,t,YC(n.clientVersion),"ts-cloud vitess:install-client")}async function Yy(e,t,r,n={}){let i=Vi(e);if(i)return{...i,keyspace:r};if(!Jy(r))return{ok:!1,error:"Keyspace name must be a valid identifier.",keyspace:r};let o=Va(e),s=Ua(o);if(s)return{...s,keyspace:r};let c=ZC(o,r,n);if(!c)return{...Ua({}),keyspace:r};return{...await _t(e,t,c,`ts-cloud vitess:create-keyspace ${r}`),keyspace:r}}async function Zy(e,t,r,n){let i=Vi(e);if(i)return{...i,keyspace:r};if(!Jy(r))return{ok:!1,error:"Keyspace name must be a valid identifier.",keyspace:r};try{let a=JSON.parse(n);if(!a||typeof a!=="object")return{ok:!1,error:"The VSchema must be a JSON object.",keyspace:r}}catch(a){return{ok:!1,error:`The VSchema is not valid JSON: ${a?.message??a}`,keyspace:r}}let o=Va(e),s=Ua(o);if(s)return{...s,keyspace:r};let c=XC(o,r,n);if(!c)return{...Ua({}),keyspace:r};return{...await _t(e,t,c,`ts-cloud vitess:apply-vschema ${r}`),keyspace:r}}async function Xy(e,t,r){let n=Vi(e);if(n)return n;if(!r.trim())return{ok:!1,error:"No SQL was provided."};let i=Va(e);return _t(e,t,eP(gt(e),r,i.ddlStrategy??"vitess"),"ts-cloud vitess:apply-schema")}async function ev(e,t,r){let n=Vi(e);if(n)return{...n,migrations:[],failed:[],running:[]};let i=await _t(e,t,tP(gt(e),r),"ts-cloud vitess:migrations"),o=i.ok&&i.stdout?rP(i.stdout):[];return{...i,migrations:o,failed:nP(o),running:iP(o)}}async function tv(e,t,r,n){let i=Vi(e);if(i)return{...i,uuid:r};if(!QC(r))return{ok:!1,error:"Migration UUID is not in the expected format.",uuid:r};return{...await _t(e,t,oP(gt(e),r,n),`ts-cloud vitess:migration ${n} ${r}`),uuid:r}}function sP(e){let t=e.infrastructure?.appDatabase;if(t?.engine&&t.engine!=="vitess")return`This project already declares ${t.engine} as its application database.`;let r=e.infrastructure?.compute?.managedServices,n=r?["mysql","mariadb","postgres"].find((i)=>Boolean(r[i])):void 0;if(n)return`This server already declares the ${n} database service.`;return}function aP(e,t){let r=t.keyspace.trim(),n=t.username.trim(),i=t.password,o=sP(e);if(o)throw Error(o);if(!Ur(r))throw Error("Keyspace must contain letters, numbers, or underscores and cannot start with a number.");if(!Ur(n))throw Error("Username must contain letters, numbers, or underscores and cannot start with a number.");if(i.length<16)throw Error("Password must contain at least 16 characters.");if(t.confirm!==r)throw Error(`Type "${r}" to confirm Vitess provisioning.`);let s={mode:"cluster",cell:"zone1",keyspaces:[{name:r,sharded:t.sharded===!0}],vtgatePort:15306,username:n,password:i,bindAddress:"127.0.0.1"};return{service:s,appDatabase:{engine:"vitess",name:r,username:n,host:"127.0.0.1",port:15306,ssl:!1},commands:[...rv(),...nv(s)]}}async function iv(e,t,r){let n=aP(e,r);return{...await _t(e,t,n.commands,`ts-cloud vitess:provision ${n.appDatabase.name}`),database:n.appDatabase,service:Object.fromEntries(Object.entries(n.service).filter(([o])=>o!=="password"))}}var cP={capability:"runtime:terminal",scope:"organization"};var dP={"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 Iu(e,t){return dP[`${e.toUpperCase()} ${t}`]??cP}import{createHmac as lP,randomBytes as uP,timingSafeEqual as pP}from"node:crypto";import{chmodSync as mP,existsSync as gP,mkdirSync as fP,readFileSync as hP,writeFileSync as yP}from"node:fs";import{dirname as vP}from"node:path";var jo="ts_cloud_session";var bP=28800000;function ov(e){let t=process.env.TS_CLOUD_DASHBOARD_SECRET?.trim();if(t)return t;let r=yt(e,"dashboard-secret");try{if(gP(r)){let i=hP(r,"utf8").trim();if(i)return i}}catch{}let n=uP(32).toString("base64url");try{fP(vP(r),{recursive:!0}),yP(r,`${n}
|
|
344
|
+
`),mP(r,384)}catch{}return n}function SP(e,t){return lP("sha256",t).update(e).digest("base64url")}function sv(e,t){if(!e)return null;let r=e.lastIndexOf(".");if(r<=0)return null;let n=e.slice(0,r),i=e.slice(r+1),o=SP(n,t),s=Buffer.from(i),c=Buffer.from(o);if(s.length!==c.length||!pP(s,c))return null;try{let d=JSON.parse(Buffer.from(n,"base64url").toString("utf8"));if(typeof d?.u!=="string"||typeof d?.exp!=="number")return null;if(d.mv!==void 0&&(!d.mv||typeof d.mv!=="object"||Array.isArray(d.mv)||Object.values(d.mv).some((a)=>!Number.isInteger(a)||a<1)))return null;if(Date.now()>=d.exp)return null;return d}catch{return null}}function Eu(e,t){if(!e)return;for(let r of e.split(";")){let n=r.indexOf("=");if(n<0)continue;if(r.slice(0,n).trim()===t)return decodeURIComponent(r.slice(n+1).trim())}return}function Wi(e,t={secure:!0}){let r=Math.floor((t.maxAgeMs??bP)/1000),n=[`${jo}=${encodeURIComponent(e)}`,"Path=/","HttpOnly","SameSite=Lax",`Max-Age=${r}`];if(t.secure)n.push("Secure");return n.join("; ")}function Wa(e={secure:!0}){let t=[`${jo}=`,"Path=/","HttpOnly","SameSite=Lax","Max-Age=0"];if(e.secure)t.push("Secure");return t.join("; ")}import{chmodSync as wP,existsSync as kP,mkdirSync as IP,readFileSync as EP,writeFileSync as RP}from"node:fs";import{dirname as AP}from"node:path";function av(){return ho("dashboard-users.json")}function Ha(e){return/^[a-z0-9][a-z0-9._-]{1,31}$/i.test(e)}function CP(e){if(!e||typeof e.username!=="string"||!Ha(e.username)||typeof e.passwordHash!=="string")return null;let t=e.role==="admin"?"admin":"member",r={};if(e.sites&&typeof e.sites==="object"){for(let[n,i]of Object.entries(e.sites))if(i==="owner"||i==="collaborator")r[n]=i}return{username:e.username,passwordHash:e.passwordHash,role:t,sites:r,name:typeof e.name==="string"?e.name:void 0,email:typeof e.email==="string"?e.email.trim().toLowerCase():void 0,createdAt:typeof e.createdAt==="string"?e.createdAt:void 0}}function PP(e){try{let t=JSON.parse(e);if(!Array.isArray(t?.users))return[];return t.users.map(CP).filter((r)=>r!==null)}catch{return[]}}function cv(e){return yt(e,"dashboard-users.json")}function Tt(e){let t=cv(e);if(!kP(t))return[];try{return PP(EP(t,"utf8"))}catch{return[]}}function Ka(e,t){let r=cv(e);IP(AP(r),{recursive:!0}),RP(r,`${JSON.stringify({users:t},null,2)}
|
|
345
|
+
`),wP(r,384)}function Gt(e,t){let r=t.trim().toLowerCase();return e.find((n)=>n.username.toLowerCase()===r)}function dv(e,t="admin"){let r=Tt(e);if(r.some((s)=>s.role==="admin"))return{users:r};let n=process.env.TS_CLOUD_UI_PASSWORD?.trim()||uu(),i={username:t,passwordHash:fn(n),role:"admin",sites:{},name:"Administrator",createdAt:new Date().toISOString()},o=[...r,i];return Ka(e,o),{users:o,generated:{username:t,password:n}}}function Mo(e,t){let r=Tt(e),n=Gt(r,t.username),i=t.password?.trim()||(n?void 0:uu()),o={username:n?.username??t.username,passwordHash:i?fn(i):n.passwordHash,role:n?.role??"member",sites:t.sites,name:t.name??n?.name,email:t.email?.trim().toLowerCase()??n?.email,createdAt:n?.createdAt??new Date().toISOString()},s=n?r.map((c)=>c.username.toLowerCase()===o.username.toLowerCase()?o:c):[...r,o];return Ka(e,s),{user:o,password:i}}function Ja(e,t,r){let n=Tt(e),i=Gt(n,t);if(!i)throw Error("Authentication user was not found");let o={...i,passwordHash:r};return Ka(e,n.map((s)=>s.username.toLowerCase()===i.username.toLowerCase()?o:s)),o}function Ru(e,t){let r=Tt(e),n=Gt(r,t);if(!n)return{ok:!1,error:`No such user: ${t}`};if(n.role==="admin"&&r.filter((i)=>i.role==="admin").length===1)return{ok:!1,error:"Cannot remove the last admin."};return Ka(e,r.filter((i)=>i.username.toLowerCase()!==n.username.toLowerCase())),{ok:!0}}function Hi(e){return{username:e.username,name:e.name??e.username,role:e.role,email:e.email,sites:e.sites,siteCount:Object.keys(e.sites).length,createdAt:e.createdAt}}var _P={username:"local",passwordHash:"",role:"admin",sites:{},name:"Local (auth disabled)"};function lv(e){let{cwd:t,enabled:r,secret:n,authorization:i,authentication:o}=e,s=(d)=>{if(!o)return;let a=Eu(d.headers.get("cookie"),jo);return a?.startsWith("v2.")?o.verifySessionToken(a):void 0},c=(d)=>{let a=i.store.getActorByExternalId("user",`dashboard:${d.username.toLowerCase()}`),u=a?i.store.getMembershipForActor(i.organizationId,a.id):void 0;return{actor:a,membership:u}};return{enabled:r,resolveUser(d){if(!r)return _P;let a=Eu(d.headers.get("cookie"),jo),u=s(d),m=u?void 0:sv(a,n),h=u?.identity.username??m?.u;if(!h)return null;let y=Gt(Tt(t),h);if(!y)return null;let{membership:w}=c(y);if(!w||w.status!=="active"||!u&&m?.mv?.[i.organizationId]!==w.sessionVersion)return null;if(!w.lastActiveAt||Date.now()-new Date(w.lastActiveAt).getTime()>300000)i.store.touchMembership(w.id);return y},resolveSession(d){return s(d)?.session??null},check(d,a,u,m){if(!r)return{ok:!0};if(!u)return{ok:!1,status:401,error:"Sign in to continue.",unauthenticated:!0};let h=Iu(d.method,a);if(h.anyUser)return{ok:!0};if(h.siteFrom==="body"&&!m)return{ok:!1,status:400,error:"This request must name a site."};let{membership:y}=c(u);if(!y)return{ok:!1,status:401,error:"Sign in to continue.",unauthenticated:!0};let w=h.scope==="organization"?{organizationId:i.organizationId}:i.store.resolveAuthorizationTarget(i.organizationId,{type:"project",id:i.projectId});if(h.scope==="site"){let C=new URL(d.url).searchParams.get("env")??i.defaultEnvironment,T=i.store.getEnvironmentBySlug(i.projectId,C),j=i.store.listResources(i.projectId,T?.id).find((P)=>P.kind==="application"&&P.slug===m);w=j?i.store.resolveAuthorizationTarget(i.organizationId,{type:"resource",id:j.id}):void 0}if(!(w?Xt({membership:y,grants:i.store.listGrants(y.id),capability:h.capability,target:w}):{allowed:!1}).allowed)return{ok:!1,status:403,error:"You do not have access to this."};return{ok:!0}}}}async function uv(e,t){if(Iu(e.method,t).siteFrom!=="body")return;try{let n=await e.clone().json();return String(n?.name??"").trim()||void 0}catch{return}}import{createHash as TP}from"node:crypto";function pv(e,t,r){for(let n of r){let i=Ye(t.store,n);if(e.getIdentityByActor(i.id))continue;e.createIdentity({actorId:i.id,username:n.username,email:n.email,emailVerified:!!n.email,passwordHash:n.passwordHash,requiresPasswordUpgrade:!0})}}function xP(e,t,r){let n=r.split("@")[0].toLowerCase().replace(/[^a-z0-9._-]/g,"-").replace(/^[^a-z0-9]+/,"").slice(0,24),i=/^[a-z0-9][a-z0-9._-]{1,31}$/.test(n)?n:"sso-user";if(!e.getIdentityByUsername(i)&&!Gt(t,i))return i;let o=TP("sha256").update(r).digest("hex").slice(0,7);return`${i.slice(0,24)}-${o}`}function mv(e,t,r,n){if(n.provider.organizationId!==t.organization.id)throw Error("OIDC provider is not configured for this organization");let i=e.getOidcSubject(n.provider.id,n.subject),o=i?e.getIdentity(i.identityId):e.getIdentityByEmail(n.email);if(o?.disabledAt)throw Error("OIDC identity is disabled");if(!i&&o&&!o.emailVerifiedAt)throw Error("OIDC cannot automatically link an unverified local email address");let s=Tt(r),c=!1,d=o?Gt(s,o.username):void 0;if(o&&!d)throw Error("OIDC identity has no dashboard user");if(!o){let m=xP(e,s,n.email);d=Mo(r,{username:m,name:n.name,email:n.email,sites:{}}).user;let y=Ye(t.store,d);o=e.createIdentity({actorId:y.id,username:d.username,email:n.email,emailVerified:!0,passwordHash:d.passwordHash}),c=!0}else if(o.email!==n.email)o=e.setVerifiedEmail(o.id,n.email);let a=t.store.getActor(o.actorId);if(!a)throw Error("OIDC identity actor was not found");let u=t.store.getMembershipForActor(t.organization.id,a.id);if(u?.status==="revoked")throw Error("OIDC organization membership is revoked");if(!u)t.store.createMembership({organizationId:t.organization.id,actorId:a.id,roleTemplate:n.provider.defaultRole,scope:{type:"organization"},source:"manual"});return e.linkOidcSubject(n.provider.id,o.id,n.subject,n.email),{identity:o,user:d,provisioned:c}}function gv(e,t,r){let n=t.store.getMembershipForActor(t.organization.id,r.actorId);if(!n||n.status!=="active"||n.roleTemplate==="owner"||!r.emailVerifiedAt||!r.email)return!1;let i=r.email.split("@")[1]?.toLowerCase();return e.listOidcProviders(t.organization.id).some((o)=>o.enforceSso&&!!i&&o.allowedDomains.includes(i))}function DP(e){return e.replace(/[&<>"']/g,(t)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t])}function fv(e=!1,t=[]){let r=e?"/serverless":"/",n=t.map((o)=>`<a class="sso-button" href="/auth/oidc/${encodeURIComponent(o.slug)}/start?return=${encodeURIComponent(r)}">Continue with ${DP(o.name)}</a>`).join("");return`<!doctype html>
|
|
346
|
+
<html lang="en">
|
|
347
|
+
<head>
|
|
348
|
+
<meta charset="UTF-8">
|
|
349
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
350
|
+
<title>Sign in · ts-cloud</title>
|
|
351
|
+
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect x='3' y='3' width='26' height='26' rx='8' fill='%235a8be0'/%3E%3C/svg%3E">
|
|
352
|
+
<link rel="preconnect" href="https://fonts.googleapis.com">
|
|
353
|
+
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
|
|
354
|
+
<style>${`
|
|
355
|
+
:root {
|
|
356
|
+
--bg: #0a0e15; --bg2: #0b0f18; --panel: rgba(255,255,255,0.03); --panel-br: rgba(255,255,255,0.072);
|
|
357
|
+
--txt: #e9edf5; --txt2: #94a1b8; --txt3: #5a6577;
|
|
358
|
+
--accent: #5a8be0; --accent-ink: #061019;
|
|
359
|
+
--bad: #f0736e; --badbg: rgba(240,115,110,0.11);
|
|
360
|
+
}
|
|
361
|
+
* { box-sizing: border-box; margin: 0; padding: 0; }
|
|
362
|
+
html { background: var(--bg); min-height: 100%; }
|
|
363
|
+
body {
|
|
364
|
+
font-family: 'Inter', system-ui, sans-serif; color: var(--txt); min-height: 100vh;
|
|
365
|
+
background:
|
|
366
|
+
radial-gradient(900px 460px at 88% -8%, rgba(90,139,224,0.06), transparent 62%),
|
|
367
|
+
linear-gradient(175deg, var(--bg), var(--bg2));
|
|
368
|
+
-webkit-font-smoothing: antialiased;
|
|
369
|
+
display: grid; place-items: center; padding: 24px;
|
|
370
|
+
}
|
|
371
|
+
.card {
|
|
372
|
+
width: 100%; max-width: 380px;
|
|
373
|
+
background: var(--panel); border: 1px solid var(--panel-br); border-radius: 16px;
|
|
374
|
+
padding: 32px; backdrop-filter: blur(6px);
|
|
375
|
+
animation: rise .5s cubic-bezier(0.16, 1, 0.3, 1) both;
|
|
376
|
+
}
|
|
377
|
+
@keyframes rise { from { opacity: 0; transform: translateY(8px) } to { opacity: 1; transform: none } }
|
|
378
|
+
@media (prefers-reduced-motion: reduce) { .card { animation: none } }
|
|
379
|
+
.brand { display: flex; align-items: center; gap: 10px; font-weight: 700; font-size: 17px; letter-spacing: -0.02em; }
|
|
380
|
+
.brand .dot { width: 20px; height: 20px; border-radius: 6px; background: var(--accent); box-shadow: inset 0 1px 0 rgba(255,255,255,0.35); }
|
|
381
|
+
h1 { font-size: 21px; font-weight: 800; letter-spacing: -0.02em; margin-top: 22px; }
|
|
382
|
+
.sub { color: var(--txt2); font-size: 13.5px; margin-top: 5px; line-height: 1.5; }
|
|
383
|
+
form { margin-top: 24px; display: grid; gap: 14px; }
|
|
384
|
+
.field { display: flex; flex-direction: column; gap: 7px; }
|
|
385
|
+
label { color: var(--txt3); font-size: 11px; font-weight: 800; text-transform: uppercase; letter-spacing: 0.07em; }
|
|
386
|
+
input {
|
|
387
|
+
width: 100%; background: rgba(255,255,255,0.05); border: 1px solid var(--panel-br); border-radius: 10px;
|
|
388
|
+
padding: 10px 12px; color: var(--txt); font-family: inherit; font-size: 14px;
|
|
389
|
+
}
|
|
390
|
+
input:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px rgba(90,139,224,0.12); }
|
|
391
|
+
button {
|
|
392
|
+
margin-top: 4px; background: var(--accent); color: var(--accent-ink); border: 0; border-radius: 10px;
|
|
393
|
+
padding: 11px 16px; font-weight: 700; font-size: 13.5px; cursor: pointer; font-family: inherit;
|
|
394
|
+
transition: filter .12s, transform .12s;
|
|
395
|
+
}
|
|
396
|
+
button:hover { filter: brightness(1.06); }
|
|
397
|
+
button:active { transform: translateY(1px); }
|
|
398
|
+
button[disabled] { opacity: 0.6; cursor: default; }
|
|
399
|
+
.msg {
|
|
400
|
+
display: none; margin-top: 14px; padding: 10px 12px; border-radius: 10px;
|
|
401
|
+
background: var(--badbg); border: 1px solid rgba(240,115,110,0.22); color: var(--bad);
|
|
402
|
+
font-size: 13px; line-height: 1.45;
|
|
403
|
+
}
|
|
404
|
+
.msg.shown { display: block; }
|
|
405
|
+
.hidden { display: none !important; }
|
|
406
|
+
.note { color: var(--txt3); font-size: 12px; margin-top: 20px; line-height: 1.5; }
|
|
407
|
+
.note code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; color: var(--txt2); }
|
|
408
|
+
a { color: var(--accent); text-decoration: none; }
|
|
409
|
+
a:hover { text-decoration: underline; }
|
|
410
|
+
.sso { display: grid; gap: 10px; margin-top: 22px; }
|
|
411
|
+
.sso-button { display: block; border: 1px solid var(--panel-br); border-radius: 10px; padding: 11px 14px; color: var(--txt); text-align: center; font-size: 13.5px; font-weight: 700; background: rgba(255,255,255,0.04); }
|
|
412
|
+
.sso-button:hover { border-color: var(--accent); text-decoration: none; }
|
|
413
|
+
.separator { display: flex; align-items: center; gap: 10px; margin: 18px 0 -6px; color: var(--txt3); font-size: 10px; font-weight: 800; text-transform: uppercase; letter-spacing: .06em; }
|
|
414
|
+
.separator::before, .separator::after { content: ''; height: 1px; flex: 1; background: var(--panel-br); }
|
|
415
|
+
`}</style>
|
|
416
|
+
</head>
|
|
417
|
+
<body>
|
|
418
|
+
<main class="card">
|
|
419
|
+
<div class="brand"><span class="dot"></span> ts-cloud</div>
|
|
420
|
+
<h1>Sign in</h1>
|
|
421
|
+
<p class="sub">Manage the sites you have been given access to.</p>
|
|
422
|
+
|
|
423
|
+
${t.length>0?`<div class="sso" aria-label="Single sign-on">${n}</div><div class="separator"><span>or use local recovery</span></div>`:""}
|
|
424
|
+
|
|
425
|
+
<form id="login" autocomplete="on">
|
|
426
|
+
<div class="field">
|
|
427
|
+
<label for="username">Username</label>
|
|
428
|
+
<input id="username" name="username" autocomplete="username" required autofocus>
|
|
429
|
+
</div>
|
|
430
|
+
<div class="hidden field" id="mfa-field">
|
|
431
|
+
<label for="mfa-code">Authenticator or recovery code</label>
|
|
432
|
+
<input id="mfa-code" name="mfa-code" autocomplete="one-time-code">
|
|
433
|
+
</div>
|
|
434
|
+
<div class="field">
|
|
435
|
+
<label for="password">Password</label>
|
|
436
|
+
<input id="password" name="password" type="password" autocomplete="current-password" required>
|
|
437
|
+
</div>
|
|
438
|
+
<button type="submit" id="submit">Sign in</button>
|
|
439
|
+
</form>
|
|
440
|
+
|
|
441
|
+
<p class="msg" id="msg" role="alert" aria-live="polite"></p>
|
|
442
|
+
<p class="note"><a href="/forgot-password">Forgot your password?</a></p>
|
|
443
|
+
</main>
|
|
444
|
+
|
|
445
|
+
<script>
|
|
446
|
+
const form = document.getElementById('login')
|
|
447
|
+
const msg = document.getElementById('msg')
|
|
448
|
+
const submit = document.getElementById('submit')
|
|
449
|
+
const mfaField = document.getElementById('mfa-field')
|
|
450
|
+
const mfaCode = document.getElementById('mfa-code')
|
|
451
|
+
let challengeToken = ''
|
|
452
|
+
|
|
453
|
+
if (new URLSearchParams(location.search).has('sso_error')) {
|
|
454
|
+
msg.textContent = 'Single sign-on could not be completed. Try again or use the local recovery path.'
|
|
455
|
+
msg.classList.add('shown')
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
form.addEventListener('submit', async (event) => {
|
|
459
|
+
event.preventDefault()
|
|
460
|
+
msg.classList.remove('shown')
|
|
461
|
+
submit.disabled = true
|
|
462
|
+
submit.textContent = 'Signing in...'
|
|
463
|
+
try {
|
|
464
|
+
const res = await fetch(challengeToken ? '/api/auth/mfa/complete' : '/api/login', {
|
|
465
|
+
method: 'POST',
|
|
466
|
+
headers: { 'content-type': 'application/json' },
|
|
467
|
+
body: JSON.stringify(challengeToken
|
|
468
|
+
? { challengeToken, code: mfaCode.value }
|
|
469
|
+
: { username: document.getElementById('username').value, password: document.getElementById('password').value }),
|
|
470
|
+
})
|
|
471
|
+
const body = await res.json().catch(() => ({}))
|
|
472
|
+
if (!res.ok || !body.ok) throw new Error(body.error || 'Could not sign in.')
|
|
473
|
+
if (body.mfaRequired) {
|
|
474
|
+
challengeToken = body.challengeToken
|
|
475
|
+
mfaField.classList.remove('hidden')
|
|
476
|
+
mfaCode.required = true
|
|
477
|
+
document.getElementById('username').readOnly = true
|
|
478
|
+
document.getElementById('password').readOnly = true
|
|
479
|
+
submit.disabled = false
|
|
480
|
+
submit.textContent = 'Verify and sign in'
|
|
481
|
+
mfaCode.focus()
|
|
482
|
+
return
|
|
483
|
+
}
|
|
484
|
+
location.href = ${JSON.stringify(r)}
|
|
485
|
+
} catch (error) {
|
|
486
|
+
msg.textContent = (error && error.message) || String(error)
|
|
487
|
+
msg.classList.add('shown')
|
|
488
|
+
submit.disabled = false
|
|
489
|
+
submit.textContent = 'Sign in'
|
|
490
|
+
if (challengeToken) {
|
|
491
|
+
mfaCode.value = ''
|
|
492
|
+
mfaCode.focus()
|
|
493
|
+
}
|
|
494
|
+
else {
|
|
495
|
+
document.getElementById('password').value = ''
|
|
496
|
+
document.getElementById('password').focus()
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
})
|
|
500
|
+
</script>
|
|
501
|
+
</body>
|
|
502
|
+
</html>`}function hv(e){let t=e==="reset";return`<!doctype html>
|
|
503
|
+
<html lang="en">
|
|
504
|
+
<head>
|
|
505
|
+
<meta charset="UTF-8">
|
|
506
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
507
|
+
<title>${t?"Choose a new password":"Recover your account"} · ts-cloud</title>
|
|
508
|
+
<style>${`
|
|
509
|
+
:root {
|
|
510
|
+
--bg: #0a0e15; --bg2: #0b0f18; --panel: rgba(255,255,255,0.03); --panel-br: rgba(255,255,255,0.072);
|
|
511
|
+
--txt: #e9edf5; --txt2: #94a1b8; --txt3: #5a6577;
|
|
512
|
+
--accent: #5a8be0; --accent-ink: #061019;
|
|
513
|
+
--bad: #f0736e; --badbg: rgba(240,115,110,0.11);
|
|
514
|
+
}
|
|
515
|
+
* { box-sizing: border-box; margin: 0; padding: 0; }
|
|
516
|
+
html { background: var(--bg); min-height: 100%; }
|
|
517
|
+
body {
|
|
518
|
+
font-family: 'Inter', system-ui, sans-serif; color: var(--txt); min-height: 100vh;
|
|
519
|
+
background:
|
|
520
|
+
radial-gradient(900px 460px at 88% -8%, rgba(90,139,224,0.06), transparent 62%),
|
|
521
|
+
linear-gradient(175deg, var(--bg), var(--bg2));
|
|
522
|
+
-webkit-font-smoothing: antialiased;
|
|
523
|
+
display: grid; place-items: center; padding: 24px;
|
|
524
|
+
}
|
|
525
|
+
.card {
|
|
526
|
+
width: 100%; max-width: 380px;
|
|
527
|
+
background: var(--panel); border: 1px solid var(--panel-br); border-radius: 16px;
|
|
528
|
+
padding: 32px; backdrop-filter: blur(6px);
|
|
529
|
+
animation: rise .5s cubic-bezier(0.16, 1, 0.3, 1) both;
|
|
530
|
+
}
|
|
531
|
+
@keyframes rise { from { opacity: 0; transform: translateY(8px) } to { opacity: 1; transform: none } }
|
|
532
|
+
@media (prefers-reduced-motion: reduce) { .card { animation: none } }
|
|
533
|
+
.brand { display: flex; align-items: center; gap: 10px; font-weight: 700; font-size: 17px; letter-spacing: -0.02em; }
|
|
534
|
+
.brand .dot { width: 20px; height: 20px; border-radius: 6px; background: var(--accent); box-shadow: inset 0 1px 0 rgba(255,255,255,0.35); }
|
|
535
|
+
h1 { font-size: 21px; font-weight: 800; letter-spacing: -0.02em; margin-top: 22px; }
|
|
536
|
+
.sub { color: var(--txt2); font-size: 13.5px; margin-top: 5px; line-height: 1.5; }
|
|
537
|
+
form { margin-top: 24px; display: grid; gap: 14px; }
|
|
538
|
+
.field { display: flex; flex-direction: column; gap: 7px; }
|
|
539
|
+
label { color: var(--txt3); font-size: 11px; font-weight: 800; text-transform: uppercase; letter-spacing: 0.07em; }
|
|
540
|
+
input {
|
|
541
|
+
width: 100%; background: rgba(255,255,255,0.05); border: 1px solid var(--panel-br); border-radius: 10px;
|
|
542
|
+
padding: 10px 12px; color: var(--txt); font-family: inherit; font-size: 14px;
|
|
543
|
+
}
|
|
544
|
+
input:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px rgba(90,139,224,0.12); }
|
|
545
|
+
button {
|
|
546
|
+
margin-top: 4px; background: var(--accent); color: var(--accent-ink); border: 0; border-radius: 10px;
|
|
547
|
+
padding: 11px 16px; font-weight: 700; font-size: 13.5px; cursor: pointer; font-family: inherit;
|
|
548
|
+
transition: filter .12s, transform .12s;
|
|
549
|
+
}
|
|
550
|
+
button:hover { filter: brightness(1.06); }
|
|
551
|
+
button:active { transform: translateY(1px); }
|
|
552
|
+
button[disabled] { opacity: 0.6; cursor: default; }
|
|
553
|
+
.msg {
|
|
554
|
+
display: none; margin-top: 14px; padding: 10px 12px; border-radius: 10px;
|
|
555
|
+
background: var(--badbg); border: 1px solid rgba(240,115,110,0.22); color: var(--bad);
|
|
556
|
+
font-size: 13px; line-height: 1.45;
|
|
557
|
+
}
|
|
558
|
+
.msg.shown { display: block; }
|
|
559
|
+
.hidden { display: none !important; }
|
|
560
|
+
.note { color: var(--txt3); font-size: 12px; margin-top: 20px; line-height: 1.5; }
|
|
561
|
+
.note code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; color: var(--txt2); }
|
|
562
|
+
a { color: var(--accent); text-decoration: none; }
|
|
563
|
+
a:hover { text-decoration: underline; }
|
|
564
|
+
.sso { display: grid; gap: 10px; margin-top: 22px; }
|
|
565
|
+
.sso-button { display: block; border: 1px solid var(--panel-br); border-radius: 10px; padding: 11px 14px; color: var(--txt); text-align: center; font-size: 13.5px; font-weight: 700; background: rgba(255,255,255,0.04); }
|
|
566
|
+
.sso-button:hover { border-color: var(--accent); text-decoration: none; }
|
|
567
|
+
.separator { display: flex; align-items: center; gap: 10px; margin: 18px 0 -6px; color: var(--txt3); font-size: 10px; font-weight: 800; text-transform: uppercase; letter-spacing: .06em; }
|
|
568
|
+
.separator::before, .separator::after { content: ''; height: 1px; flex: 1; background: var(--panel-br); }
|
|
569
|
+
`}</style>
|
|
570
|
+
</head>
|
|
571
|
+
<body>
|
|
572
|
+
<main class="card">
|
|
573
|
+
<div class="brand"><span class="dot"></span> ts-cloud</div>
|
|
574
|
+
<h1>${t?"Choose a new password":"Recover your account"}</h1>
|
|
575
|
+
<p class="sub">${t?"This one-time link expires after one hour.":"Enter your username or verified email. The response is the same whether or not an account exists."}</p>
|
|
576
|
+
<form id="recovery" autocomplete="on">
|
|
577
|
+
${t?'<div class="field"><label for="password">New password</label><input id="password" name="password" type="password" autocomplete="new-password" minlength="12" required></div><div class="field"><label for="confirmation">Confirm new password</label><input id="confirmation" name="confirmation" type="password" autocomplete="new-password" minlength="12" required></div>':'<div class="field"><label for="identifier">Username or email</label><input id="identifier" name="identifier" autocomplete="username" required autofocus></div>'}
|
|
578
|
+
<button type="submit" id="submit">${t?"Change password":"Send reset link"}</button>
|
|
579
|
+
</form>
|
|
580
|
+
<p class="msg" id="msg" role="status" aria-live="polite"></p>
|
|
581
|
+
<p class="note"><a href="/login">Return to sign in</a></p>
|
|
582
|
+
</main>
|
|
583
|
+
<script>
|
|
584
|
+
const form = document.getElementById('recovery')
|
|
585
|
+
const msg = document.getElementById('msg')
|
|
586
|
+
const submit = document.getElementById('submit')
|
|
587
|
+
const reset = ${JSON.stringify(t)}
|
|
588
|
+
const token = new URLSearchParams(location.search).get('token') || ''
|
|
589
|
+
if (reset && !token) {
|
|
590
|
+
msg.textContent = 'This reset link is missing its token. Request a new link.'
|
|
591
|
+
msg.classList.add('shown')
|
|
592
|
+
submit.disabled = true
|
|
593
|
+
}
|
|
594
|
+
form.addEventListener('submit', async (event) => {
|
|
595
|
+
event.preventDefault()
|
|
596
|
+
if (reset && document.getElementById('password').value !== document.getElementById('confirmation').value) {
|
|
597
|
+
msg.textContent = 'The passwords do not match.'
|
|
598
|
+
msg.classList.add('shown')
|
|
599
|
+
return
|
|
600
|
+
}
|
|
601
|
+
submit.disabled = true
|
|
602
|
+
msg.textContent = reset ? 'Changing password…' : 'Requesting reset link…'
|
|
603
|
+
msg.classList.add('shown')
|
|
604
|
+
const response = await fetch(reset ? '/api/auth/password-reset/complete' : '/api/auth/password-reset/request', {
|
|
605
|
+
method: 'POST',
|
|
606
|
+
headers: { 'content-type': 'application/json' },
|
|
607
|
+
body: JSON.stringify(reset
|
|
608
|
+
? { token, password: document.getElementById('password').value }
|
|
609
|
+
: { identifier: document.getElementById('identifier').value }),
|
|
610
|
+
})
|
|
611
|
+
const result = await response.json().catch(() => ({}))
|
|
612
|
+
msg.textContent = result.message || result.error || 'The request could not be completed.'
|
|
613
|
+
if (!response.ok) {
|
|
614
|
+
submit.disabled = false
|
|
615
|
+
return
|
|
616
|
+
}
|
|
617
|
+
if (reset)
|
|
618
|
+
setTimeout(() => location.assign('/login'), 1200)
|
|
619
|
+
})
|
|
620
|
+
</script>
|
|
621
|
+
</body>
|
|
622
|
+
</html>`}var Sv={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};async function wv(e){return await e.driver.findComputeTargets({slug:e.slug,environment:e.environment,role:e.role||"app"})}async function kv(e,t){let r=e.logger||Sv,n=await wv(e);if(n.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};let i=yn(e.slug,t.siteName),o=vv(i,t.to||"unused"),s=["set -uo pipefail",...bv(o,{...t.to?{to:t.to}:{},unitBase:`${e.slug}-${t.siteName}`}),`(cd ${Bo} && pantry restart php-fpm) 2>/dev/null || true`,`(cd ${o.current} && eval "$(cd ${Bo} && pantry env 2>/dev/null)" && php artisan queue:restart) 2>/dev/null || true`];r.step(`Rolling back ${t.siteName}${t.to?` to ${t.to}`:" to the previous release"} on ${n.length} server(s)...`);let c=await e.driver.runRemoteDeploy({targets:n,commands:s,comment:`ts-cloud rollback ${e.slug}/${t.siteName}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});if(!c.success)r.error(`Rollback failed: ${c.error||"unknown error"}`);else r.success(`Rolled back ${t.siteName}.`);return{success:c.success,error:c.error,perInstance:c.perInstance}}async function Iv(e,t){let r=e.logger||Sv;if(!t.database?.name)return{success:!1,error:"No appDatabase configured to restore."};let n=await wv(e);if(n.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};r.step(`Restoring database '${t.database.name}'${t.from?` from ${t.from}`:" from the latest backup"} on ${n.length} server(s)...`);let i=await e.driver.runRemoteDeploy({targets:n,commands:yv(t.database,{from:t.from}),comment:`ts-cloud db:restore ${e.slug}/${t.database.name}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});if(!i.success)r.error(`Restore failed: ${i.error||"unknown error"}`);else r.success(`Restored ${t.database.name}.`);return{success:i.success,error:i.error,perInstance:i.perInstance}}var OP=["restart","reload","start","stop","enable","disable"],Ev=65536;function Ki(e){return e.length<=Ev?e:`${e.slice(0,Ev)}
|
|
623
|
+
|
|
624
|
+
[output truncated]`}function $P(e){return/^[A-Za-z0-9_.@:-]+$/.test(e)}function Au(e){return/^[A-Za-z0-9_-]+$/.test(e)}function NP(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Qa(e,t){let r=[],n=t.servicesDetail??t.services??[];for(let s of n){let c=String(s?.name??"");if(!c||!$P(c))continue;for(let d of OP)r.push({id:`${d}:${c}`,label:`${NP(d)} ${c}`,group:"service",target:c,mutates:!0,confirm:c,danger:d==="stop"||d==="disable"})}for(let[s,c]of Object.entries(e.sites??{})){if(!c||!Au(s))continue;let d=zr(c);if(d==="server-app"||d==="server-php")r.push({id:`rollback:${s}`,label:`Rollback ${s}`,group:"deploy",target:s,mutates:!0,confirm:s,danger:!0})}let i=new Set;for(let s of t.workers??[]){let c=String(s?.name??"").split(":")[0];if(c&&Au(c))i.add(c)}for(let s of i)r.push({id:`worker:restart:${s}`,label:`Restart workers (${s})`,group:"worker",target:s,mutates:!0,confirm:s});for(let[s,c]of Object.entries(e.sites??{})){if(!c||!Au(s))continue;if(c.scheduler||c.schedule){let d=Ga(c)==="laravel";r.push({id:`scheduler:run:${s}`,label:`${d?"Run":"Restart"} scheduler (${s})`,group:"scheduler",target:s,mutates:!0,confirm:s})}}if(e.infrastructure?.compute?.backups?.enabled){if(r.push({id:"backup:run",label:"Run backup now",group:"backup",target:"backup",mutates:!0,confirm:"backup"}),gt(e))r.push({id:"backup:restore",label:"Restore latest DB backup",group:"backup",target:"database",mutates:!0,confirm:"restore",danger:!0})}return r}function Pu(e,t,r){return Qa(t,r).find((n)=>n.id===e)}function jP(e,t){let r=e==="enable"||e==="disable"?`systemctl is-enabled ${t} 2>/dev/null || true`:`systemctl is-active ${t} 2>/dev/null || true`;return["set -o pipefail",`systemctl ${e} ${t}`,r]}function MP(){return`eval "$(cd ${Bo} && pantry env 2>/dev/null)"`}function Av(e,t,r){let n=`${yn(e,t)}/current`;return["set -uo pipefail",`[ -d ${n} ] || { echo "site ${t} has no current release" >&2; exit 1; }`,`cd ${n} && ${MP()} && php artisan ${r}`]}function BP(e,t,r){if(e==="laravel")return Av(t,r,"queue:restart");let n=`${t}-${r}-queue-*.service`;return["set -uo pipefail",`units=$(systemctl list-units --type=service --all --no-legend '${n}' 2>/dev/null | awk '{print $1}')`,`[ -n "$units" ] || { echo "no queue-worker units found for ${r} (${n})" >&2; exit 1; }`,"systemctl restart $units",`systemctl --no-legend --type=service list-units '${n}' 2>/dev/null || true`]}function LP(e,t,r){if(e==="laravel")return Av(t,r,"schedule:run");let n=`${t}-${r}-scheduler.service`;return["set -uo pipefail",`systemctl restart ${n}`,`systemctl is-active ${n} 2>/dev/null || true`]}function FP(){return["set -uo pipefail",`[ -x ${Cu} ] || { echo "scheduled backups are not provisioned on this server" >&2; exit 1; }`,Cu]}function Rv(e,t,r){return{operation:e,command:t,ok:r.success,stdout:Ki(r.perInstance?.[0]?.output??""),stderr:Ki(r.perInstance?.[0]?.error??r.error??"")}}async function Ya(e,t,r,n={}){let i=e.project.slug,o;try{o=ir({config:e})}catch(m){return{operation:r.id,ok:!1,error:`Could not initialize the cloud driver: ${m?.message??m}`}}let s={driver:o,slug:i,environment:t,role:"app"};if(r.group==="deploy"){let m=n.to&&/^[A-Za-z0-9._-]+$/.test(n.to)?n.to:void 0,h=await kv(s,{siteName:r.target,to:m});return Rv(r.id,`rollback ${r.target}${m?` → ${m}`:""}`,h)}if(r.id==="backup:restore"){let m=await Iv(s,{database:gt(e)});return Rv(r.id,"db restore",m)}let c=await o.findComputeTargets({slug:i,environment:t,role:"app"});if(!c.length)return{operation:r.id,ok:!1,error:"No app server target was found for this environment."};let d,a;if(r.group==="service"){let[m,...h]=r.id.split(":");d=jP(m,h.join(":")),a=`systemctl ${m} ${r.target}`}else if(r.group==="worker"){let m=Ga(e.sites?.[r.target]??{});d=BP(m,i,r.target),a=m==="laravel"?`queue:restart (${r.target})`:`restart queue units (${r.target})`}else if(r.group==="scheduler"){let m=Ga(e.sites?.[r.target]??{});d=LP(m,i,r.target),a=m==="laravel"?`schedule:run (${r.target})`:`restart scheduler (${r.target})`}else if(r.id==="backup:run")d=FP(),a="ts-cloud backup";else return{operation:r.id,ok:!1,error:"Unknown operation."};let u=await o.runRemoteDeploy({targets:[c[0]],commands:d,comment:`ts-cloud dashboard:${r.id}`,tags:{Project:i,Environment:t,Role:"app"}});return{operation:r.id,command:a,ok:u.success,stdout:Ki(u.perInstance?.[0]?.output??""),stderr:Ki(u.perInstance?.[0]?.error??u.error??"")}}async function Lo(e,t,r){let n=r.trim();if(!n)return{operation:"command",ok:!1,error:"A command is required."};let i;try{i=ir({config:e})}catch(d){return{operation:"command",ok:!1,error:`Could not initialize the cloud driver: ${d?.message??d}`}}let o=e.project.slug,s=await i.findComputeTargets({slug:o,environment:t,role:"app"});if(!s.length)return{operation:"command",ok:!1,error:"No app server target was found for this environment."};let c=await i.runRemoteDeploy({targets:[s[0]],commands:["set -o pipefail",n],comment:"ts-cloud dashboard:command",tags:{Project:o,Environment:t,Role:"app"}});return{operation:"command",command:n,ok:c.success,stdout:Ki(c.perInstance?.[0]?.output??""),stderr:Ki(c.perInstance?.[0]?.error??c.error??"")}}function zP(e,t){return[`${e}-${t}`,`${e}-${t}-queues`,`${e}-${t}-daemons`]}function Cv(e,t,r){return r.some((n)=>zP(t,n).includes(e))}function _u(e,t){let{user:r,slug:n}=t;if(r.role==="admin")return e;let i=(e.sites??[]).map((w)=>w.name).filter(Boolean),o=lu(r,i),s=new Set(o),c=(e.sites??[]).filter((w)=>s.has(w.name)),d=(e.sitesDetail??[]).filter((w)=>s.has(w.name)),a=new Set(d.map((w)=>w.domain).filter(Boolean)),u=(e.serverDeploymentsDetail??e.serverDeployments??[]).filter((w)=>s.has(w.site)),m=(e.serverLogs??[]).filter((w)=>Cv(w.source,n,o)),h=(e.security?.tlsCertificates??[]).filter((w)=>a.has(w.domain)),y=(e.activity??[]).filter((w)=>{if(w.type==="deploy")return o.some((k)=>String(w.title??"").startsWith(`${k} `));if(w.type==="log")return Cv(String(w.title??"").split(" ")[0],n,o);return!1});return{mode:e.mode,environment:e.environment,environments:e.environments,scoped:!0,server:{name:""},sites:c,sitesDetail:d,workers:(e.workers??[]).filter((w)=>s.has(w.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:m,serverLogsEmptyReason:m.length?void 0:"No recent log entries for your sites.",security:{tlsCertificates:h,ports:[],firewall:null,authEvents:[]},diagnostics:(e.diagnostics??[]).filter((w)=>["Route conflicts","TLS certificates"].includes(w.name)),activity:y}}function Pv(e,t){if(t.role==="admin")return e;let r=new Set(lu(t,Object.keys(e.sites??{})));return{project:{name:e.project?.name},environment:e.environment,environments:e.environments,sites:Object.fromEntries(Object.entries(e.sites??{}).filter(([n])=>r.has(n)))}}function _v(e){let t=new RegExp("[\\u007F-\\uFFFF]","g");return JSON.stringify(e).replace(t,(r)=>`\\u${r.charCodeAt(0).toString(16).padStart(4,"0")}`)}var UP=new Set(["name","ssl","env","redirects","aliases","domain","path"]),Tv={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 Dv(e){let t=Object.keys(e).filter((i)=>e[i]!==void 0),r=t.filter((i)=>(i in Tv));if(r.length)return{ok:!1,error:`Only the server owner can change ${r.map((o)=>`${o} (${Tv[o]})`).join(", ")}.`};let n=t.filter((i)=>!UP.has(i));if(n.length)return{ok:!1,error:`Only the server owner can change ${n.join(", ")}.`};return{ok:!0}}function Za(e){return String(e??"").trim().toLowerCase().replace(/\.$/,"")}function xv(e){let t=String(e??"/").trim();if(!t||t==="/")return"/";return(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")||"/"}function qP(e){let t=[Za(e?.domain)];if(Array.isArray(e?.aliases))t.push(...e.aliases.map(Za));return t.filter(Boolean)}function Ov({siteName:e,body:t,sites:r,ownSites:n}){let i=r[e]??{},o=new Set(n),s=new Set;if(t.domain!==void 0)s.add(Za(t.domain));if(Array.isArray(t.aliases))for(let d of t.aliases)s.add(Za(d));if(s.delete(""),s.size===0)return{ok:!0};let c=xv(t.path!==void 0?t.path:i.path);for(let[d,a]of Object.entries(r)){if(d===e||o.has(d))continue;let u=xv(a?.path);for(let m of qP(a)){if(!s.has(m))continue;if(u===c)return{ok:!1,error:`${m}${c==="/"?"":c} is already served by another site on this server.`}}}return{ok:!0}}class Fo{maxAttempts;lockoutMs;windowMs;attempts=new Map;constructor(e=8,t=900000,r=900000){this.maxAttempts=e;this.lockoutMs=t;this.windowMs=r}key(e,t){return`${e.trim().toLowerCase()}\x00${t}`}check(e,t,r=Date.now()){let n=this.attempts.get(this.key(e,t));if(!n?.until)return{allowed:!0};if(r>=n.until)return this.attempts.delete(this.key(e,t)),{allowed:!0};return{allowed:!1,retryAfterSeconds:Math.ceil((n.until-r)/1000)}}recordFailure(e,t,r=Date.now()){let n=this.key(e,t),i=this.attempts.get(n),s=!i||r-i.last>this.windowMs?1:i.count+1,c={count:s,last:r};if(s>=this.maxAttempts)c.until=r+this.lockoutMs;this.attempts.set(n,c)}recordSuccess(e,t){this.attempts.delete(this.key(e,t))}prune(e=Date.now()){for(let[t,r]of this.attempts)if(r.until?e>=r.until:e-r.last>this.windowMs)this.attempts.delete(t)}get size(){return this.attempts.size}}var Nv=new Set([22,80,443]);function zo(e){return Number.isInteger(e)&&e>=1&&e<=65535}function Xn(e){return[...new Set(e.filter((t)=>zo(t)&&!Nv.has(t)))].sort((t,r)=>t-r)}function jv(e,t,r=[]){if(!zo(t))throw Error("Port must be an integer between 1 and 65535.");if(Nv.has(t))throw Error(`Port ${t} (SSH/HTTP/HTTPS) is always open and is not managed here.`);return Bv({configText:e,ports:Xn([...r,t])})}function Mv(e,t,r=[]){return Bv({configText:e,ports:Xn(r.filter((n)=>n!==t))})}function $v(e,t,r,n,i){let o=e.slice(t,r),s=new RegExp(`\\b${n}\\s*:\\s*\\${i}`).exec(o);if(!s)return null;let c=t+s.index,d=e.indexOf(i,c);return{propStart:c,open:d,close:No(e,d,i,i==="{"?"}":"]")}}function Tu(e){return`allowedPorts: [${e.join(", ")}]`}function Bv(e){let{configText:t}=e,r=Xn(e.ports),n=/\bcompute\s*:\s*{/.exec(t);if(!n)throw Error("Could not find infrastructure.compute in the cloud config.");let i=t.indexOf("{",n.index),o=No(t,i,"{","}"),s=$v(t,i+1,o,"firewall","{");if(s){let u=$v(t,s.open+1,s.close,"allowedPorts","[");if(u){let w=u.propStart;while(w>0&&t[w-1]!==`
|
|
625
|
+
`&&/\s/.test(t[w-1]))w--;let k=t.slice(w,u.propStart);return`${t.slice(0,w)}${k}${Tu(r)}${t.slice(u.close+1)}`}let m=t.slice(0,s.close).trimEnd(),h=t.slice(s.close),y=m.endsWith(",")||m.endsWith("{")?"":",";return`${m}${y}
|
|
626
|
+
${Tu(r)},
|
|
627
|
+
${h}`}let c=t.slice(0,o).trimEnd(),d=t.slice(o),a=c.endsWith(",")||c.endsWith("{")?"":",";return`${c}${a}
|
|
628
|
+
firewall: {
|
|
629
|
+
enabled: true,
|
|
630
|
+
${Tu(r)},
|
|
631
|
+
},
|
|
632
|
+
${d}`}class xu{client;region;constructor(e="us-east-1"){this.region=e,this.client=new mi}async getTraceSummaries(e){let t={StartTime:Math.floor(e.startTime.getTime()/1000),EndTime:Math.floor(e.endTime.getTime()/1000),TimeRangeType:"Event",Sampling:!1};if(e.filterExpression)t.FilterExpression=e.filterExpression;if(e.nextToken)t.NextToken=e.nextToken;let r=await this.client.request({service:"xray",region:this.region,method:"POST",path:"/TraceSummaries",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});return{summaries:r?.TraceSummaries??[],nextToken:r?.NextToken}}async batchGetTraces(e){if(!e.length)return[];return(await this.client.request({service:"xray",region:this.region,method:"POST",path:"/Traces",headers:{"Content-Type":"application/json"},body:JSON.stringify({TraceIds:e.slice(0,5)})}))?.Traces??[]}}var Lv=65536;function St(e){return e.length<=Lv?e:`${e.slice(0,Lv)}
|
|
633
|
+
|
|
634
|
+
[output truncated]`}function Ou(e,t){return e.environments?.[t]?.app}function $u(e,t,r){let n=[],i=Ou(e,t);n.push({id:"redeploy",label:"Redeploy current build",group:"deploy",target:"app",mutates:!0,confirm:"redeploy"}),n.push({id:"rollback",label:"Roll back to previous build",group:"deploy",target:"app",mutates:!0,confirm:"rollback",danger:!0});let o=r.maintenance?.enabled;if(o!==!0)n.push({id:"maintenance:on",label:"Enable maintenance mode",group:"maintenance",target:"app",mutates:!0,confirm:"maintenance",danger:!0});if(o!==!1)n.push({id:"maintenance:off",label:"Disable maintenance mode",group:"maintenance",target:"app",mutates:!0,confirm:"live"});if(i?.assets||r.assetsInfo)n.push({id:"assets:invalidate",label:"Invalidate CDN cache",group:"assets",target:"assets",mutates:!0,confirm:"invalidate"});if(i?.database?.connection==="aurora-serverless")n.push({id:"db:scale",label:"Scale Aurora capacity",group:"database",target:"database",mutates:!0,confirm:"scale",inputs:[{name:"min",label:"Min ACUs",placeholder:String(i.database.minCapacity??0.5)},{name:"max",label:"Max ACUs",placeholder:String(i.database.maxCapacity??4)}]});for(let s of r.queues??[]){let c=String(s?.name??"").trim();if(c&&/^[A-Za-z0-9_-]+$/.test(c))n.push({id:`queue:purge:${c}`,label:`Purge queue (${c})`,group:"queue",target:c,mutates:!0,confirm:c,danger:!0})}return n}function zv(e,t,r,n){return $u(t,r,n).find((i)=>i.id===e)}async function VP(e,t,r){try{let n=new Er(r),{Stacks:i}=await n.describeStacks({stackName:ui(e,t)}),o={};for(let d of i?.[0]?.Outputs??[])if(d.OutputKey)o[d.OutputKey]=d.OutputValue??"";let s=o.AssetsCdnDomain;if(!s)return null;return(await new Rn(r).findDistributionByDomain(s))?.Id??null}catch{return null}}async function Uv(e,t,r,n={}){try{if(r.id==="redeploy")return await hc(e,t),{operation:r.id,command:"serverless redeploy",ok:!0,stdout:"Redeploy complete."};if(r.id==="rollback")return await yc(e,t),{operation:r.id,command:"serverless rollback",ok:!0,stdout:"Rollback complete."};if(r.id==="maintenance:on")return await as(e,t,!0),{operation:r.id,command:"maintenance on",ok:!0,stdout:"Application is now in maintenance mode."};if(r.id==="maintenance:off")return await as(e,t,!1),{operation:r.id,command:"maintenance off",ok:!0,stdout:"Application is live."};if(r.id==="db:scale"){let i=Number(n.min),o=Number(n.max);if(!Number.isFinite(i)||!Number.isFinite(o)||i<=0||o<i)return{operation:r.id,ok:!1,error:"Provide valid Aurora capacities (0 < min ≤ max)."};return await Jp(e,t,i,o),{operation:r.id,command:`db:scale ${i}-${o} ACU`,ok:!0,stdout:`Scaling applied (${i}-${o} ACUs); takes effect shortly.`}}if(r.id==="assets:invalidate"){let i=await nt(e,t),o=await VP(e,t,i.region);if(!o)return{operation:r.id,ok:!1,error:"Could not resolve the asset CloudFront distribution for this environment."};let c=await new Rn(i.region).invalidateAll(o);return{operation:r.id,command:`cloudfront invalidate ${o} /*`,ok:!0,stdout:`Invalidation ${c?.Id??"created"} for ${o} (/*).`}}if(r.group==="queue"&&r.id.startsWith("queue:purge:")){let i=r.target,o=await nt(e,t),s=new _n(o.region),c=`${o.slug}-${t}-${i}`,{QueueUrl:d}=await s.getQueueUrl(c);return await s.purgeQueue(d),{operation:r.id,command:`sqs purge ${c}`,ok:!0,stdout:`Purged queue ${c}.`}}return{operation:r.id,ok:!1,error:"Unknown or unavailable serverless operation."}}catch(i){return{operation:r.id,ok:!1,error:St(i?.message??String(i))}}}async function qv(e,t,r){let n=r.trim();if(!n)return{operation:"command",ok:!1,error:"A command is required."};try{let i=await pi(e,t,n);return{operation:"command",command:n,ok:!0,stdout:St(i||"(no output)")}}catch(i){return{operation:"command",command:n,ok:!1,error:St(i?.message??String(i))}}}var Nu="No dead-letter queue is provisioned for this environment.";async function ju(e,t,r){try{let{QueueUrl:n}=await e.getQueueUrl(`${t}-${r}-dlq`);return n}catch{return null}}async function Vv(e,t,r=10){try{let n=await nt(e,t),i=new _n(n.region),o=await ju(i,n.slug,t);if(!o)return{ok:!1,messages:[],error:Nu};return{ok:!0,messages:((await i.receiveMessages({queueUrl:o,maxMessages:Math.min(10,Math.max(1,r)),waitTimeSeconds:1,visibilityTimeout:2})).Messages??[]).map((d)=>({id:d.MessageId,receiptHandle:d.ReceiptHandle,body:St(String(d.Body??""))}))}}catch(n){return{ok:!1,messages:[],error:St(n?.message??String(n))}}}async function Wv(e,t,r={}){try{let n=await nt(e,t),i=Ou(e,t),s=(i?ds(i,n.slug,t):[]).map((y)=>y.name.replace(`${n.slug}-${t}-`,"")),c=r.targetQueue&&s.includes(r.targetQueue)?r.targetQueue:s[0];if(!c)return{operation:"dlq:redrive",ok:!1,error:"No source queue is configured to redrive into."};let d=new _n(n.region),a=await ju(d,n.slug,t);if(!a)return{operation:"dlq:redrive",ok:!1,error:Nu};let{QueueUrl:u}=await d.getQueueUrl(`${n.slug}-${t}-${c}`),m=Math.min(50,Math.max(1,r.max??10)),h=0;while(h<m){let w=(await d.receiveMessages({queueUrl:a,maxMessages:Math.min(10,m-h),waitTimeSeconds:1,visibilityTimeout:30})).Messages??[];if(!w.length)break;for(let k of w)await d.sendMessage({queueUrl:u,messageBody:String(k.Body??"")}),await d.deleteMessage(a,k.ReceiptHandle),h++}return{operation:"dlq:redrive",command:`redrive → ${c}`,ok:!0,stdout:`Moved ${h} message(s) from the DLQ to ${c}.`}}catch(n){return{operation:"dlq:redrive",ok:!1,error:St(n?.message??String(n))}}}async function Hv(e,t){try{let r=await nt(e,t),n=new _n(r.region),i=await ju(n,r.slug,t);if(!i)return{operation:"dlq:purge",ok:!1,error:Nu};return await n.purgeQueue(i),{operation:"dlq:purge",command:"sqs purge dlq",ok:!0,stdout:"Dead-letter queue purged."}}catch(r){return{operation:"dlq:purge",ok:!1,error:St(r?.message??String(r))}}}function Kv(e,t){let r=Ou(e,t);if(!r?.secrets)return[];return Array.isArray(r.secrets)?r.secrets.map((n)=>({key:n.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),secretId:n})):Object.entries(r.secrets).map(([n,i])=>({key:n,secretId:String(i)}))}async function Jv(e,t,r,n){if(!r.trim())return{operation:"secret:set",ok:!1,error:"A secret id is required."};try{let i=await nt(e,t),o=new Yr(i.region);try{await o.putSecretValue({SecretId:r,SecretString:n})}catch{await o.createSecret({Name:r,SecretString:n})}return{operation:"secret:set",command:`secret set ${r}`,ok:!0,stdout:`Secret ${r} updated. Redeploy to apply it to the functions.`}}catch(i){return{operation:"secret:set",ok:!1,error:St(i?.message??String(i))}}}async function Gv(e,t,r){if(!r.trim())return{operation:"secret:delete",ok:!1,error:"A secret id is required."};try{let n=await nt(e,t);return await new Yr(n.region).deleteSecret({SecretId:r,RecoveryWindowInDays:7}),{operation:"secret:delete",command:`secret delete ${r}`,ok:!0,stdout:`Secret ${r} scheduled for deletion (recoverable for 7 days).`}}catch(n){return{operation:"secret:delete",ok:!1,error:St(n?.message??String(n))}}}var WP=new Set(["http","queue","cli"]);async function Qv(e,t,r,n){if(!WP.has(r))return{operation:"function:config",ok:!1,error:`Unknown function mode '${r}'.`};let i=n.memory==null?void 0:Number(n.memory),o=n.timeout==null?void 0:Number(n.timeout);if(i!=null&&(!Number.isInteger(i)||i<128||i>10240))return{operation:"function:config",ok:!1,error:"Memory must be an integer between 128 and 10240 MB."};if(o!=null&&(!Number.isInteger(o)||o<1||o>900))return{operation:"function:config",ok:!1,error:"Timeout must be an integer between 1 and 900 seconds."};if(i==null&&o==null)return{operation:"function:config",ok:!1,error:"Provide a memory and/or timeout value."};try{let s=await nt(e,t),c=new kt(s.region),d=`${s.slug}-${t}-${r}`;await c.updateFunctionConfiguration({FunctionName:d,...i!=null?{MemorySize:i}:{},...o!=null?{Timeout:o}:{}});let a=[i!=null?`${i} MB`:"",o!=null?`${o}s`:""].filter(Boolean).join(", ");return{operation:"function:config",command:`update ${d} (${a})`,ok:!0,stdout:`Updated ${d}: ${a}.`}}catch(s){return{operation:"function:config",ok:!1,error:St(s?.message??String(s))}}}var Du=[{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 HP(e){return Du.find((t)=>t.key===e)}async function Yv(e,t){try{let r=await nt(e,t);return{ok:!0,alarms:await new Rr(r.region).describeAlarms({AlarmNamePrefix:`${r.slug}-${t}-`,MaxRecords:100}),presets:Du}}catch(r){return{ok:!1,alarms:[],presets:Du,error:St(r?.message??String(r))}}}async function Zv(e,t,r,n){let i=HP(r);if(!i)return{operation:"alarm:create",ok:!1,error:`Unknown alarm metric '${r}'.`};if(!Number.isFinite(n)||n<0)return{operation:"alarm:create",ok:!1,error:"Provide a non-negative threshold."};try{let o=await nt(e,t),s=new Rr(o.region),c=`${o.slug}-${t}-${i.key}`,d=i.fnMode?[{Name:"FunctionName",Value:`${o.slug}-${t}-${i.fnMode}`}]:[];return await s.putMetricAlarm({AlarmName:c,Namespace:i.namespace,MetricName:i.metricName,ComparisonOperator:i.comparison,Threshold:n,EvaluationPeriods:1,Period:300,Statistic:i.statistic,Dimensions:d,AlarmDescription:`ts-cloud: ${i.label} > ${n} ${i.unit}`}),{operation:"alarm:create",command:`alarm ${c}`,ok:!0,stdout:`Alarm ${c} armed at ${n} ${i.unit}.`}}catch(o){return{operation:"alarm:create",ok:!1,error:St(o?.message??String(o))}}}async function Xv(e,t,r){try{let n=await nt(e,t);if(!r.startsWith(`${n.slug}-${t}-`))return{operation:"alarm:delete",ok:!1,error:"Refusing to delete an alarm outside this environment."};return await new Rr(n.region).deleteAlarms([r]),{operation:"alarm:delete",command:`delete alarm ${r}`,ok:!0,stdout:`Alarm ${r} deleted.`}}catch(n){return{operation:"alarm:delete",ok:!1,error:St(n?.message??String(n))}}}function KP(e){let t=e.HasFault?"fault":e.HasError?"error":e.HasThrottle?"throttle":"ok";return{id:String(e.Id??""),timestamp:Number.isFinite(Number(e.StartTime))?new Date(Number(e.StartTime)*1000).toISOString():void 0,durationMs:Math.round((e.Duration??0)*1000),responseMs:Math.round((e.ResponseTime??0)*1000),status:t,method:e.Http?.HttpMethod??"-",url:e.Http?.HttpURL??"-",httpStatus:e.Http?.HttpStatus??0}}async function Xa(e,t,r=30){try{let n=await nt(e,t),i=new xu(n.region),o=new Date,s=new Date(o.getTime()-Math.min(360,Math.max(1,r))*60000),c=`${n.slug}-${t}-http`,d=await i.getTraceSummaries({startTime:s,endTime:o,filterExpression:`service("${c}")`});if(!d.summaries.length)d=await i.getTraceSummaries({startTime:s,endTime:o});return{ok:!0,traces:d.summaries.slice(0,100).map(KP)}}catch(n){return{ok:!1,traces:[],error:St(n?.message??String(n))}}}async function Mu(e,t,r){try{let n=await nt(e,t),i=`${n.slug}-${t}-scheduler`;if(r==="run"){let s=await pi(e,t,"schedule:run");return{operation:"scheduler:run",command:"schedule:run",ok:!0,stdout:St(s||"Scheduler run triggered.")}}let o=new Fv(n.region);if(r==="enable")await o.enableRule({Name:i});else await o.disableRule({Name:i});return{operation:`scheduler:${r}`,command:`${r} ${i}`,ok:!0,stdout:`Scheduler rule ${i} ${r}d.`}}catch(n){return{operation:`scheduler:${r}`,ok:!1,error:St(n?.message??String(n))}}}function eb(e){let t=ec(e.name),r=Lu(e.configText);if(QP(e.configText,r.start,r.end,t))throw Error(`Site '${t}' already exists in cloud.config.ts`);let n=GP({...e,name:t}),i=e.configText.slice(0,r.end).trimEnd(),o=e.configText.slice(r.end),s=i.endsWith("{")?`
|
|
635
|
+
`:i.endsWith(",")?`
|
|
636
|
+
|
|
637
|
+
`:`,
|
|
638
|
+
|
|
639
|
+
`;return`${i}${s}${n}
|
|
640
|
+
${o}`}function tb(e){let t=ec(e.name),r=Lu(e.configText),n=cb(e.configText,r.start,r.end,t);if(!n)throw Error(`Site '${t}' does not exist in cloud.config.ts`);let i=e.configText,o=n.nameStart;while(o>0&&i[o-1]!==`
|
|
641
|
+
`&&/\s/.test(i[o-1]))o--;let s=n.end+1;if(i[s]===",")s++;while(s<i.length&&i[s]!==`
|
|
642
|
+
`&&/\s/.test(i[s]))s++;if(i[s]===`
|
|
643
|
+
`)s++;return i.slice(0,o)+i.slice(s)}function rb(e){let t=ec(e.siteName);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e.key))throw Error(`Invalid property key '${e.key}'`);let r=Lu(e.configText),n=cb(e.configText,r.start,r.end,t);if(!n)throw Error(`Site '${t}' does not exist in cloud.config.ts`);let i=e.configText,o=i.indexOf("{",n.nameStart),s=n.end,c=i.slice(o+1,s),d=new RegExp(`(^|[\\s,{])(${Fu(e.key)})\\s*:`,"m").exec(c);if(d){let m=o+1+d.index+d[1].length,h=i.indexOf(":",m),y=JP(i,h+1,s);return`${i.slice(0,m)}${e.key}: ${e.valueText}${i.slice(y)}`}let a=i.slice(0,s).trimEnd(),u=a.endsWith("{")||a.endsWith(",")?"":",";return`${a}${u}
|
|
644
|
+
${e.key}: ${e.valueText},
|
|
645
|
+
${i.slice(s)}`}function nb(e){if(e===!1)return"false";if(e===!0)return"true";return`{ provider: '${bn(e.provider||"letsencrypt")}' }`}function ib(e){return`'${bn(e)}'`}function ob(e){let t=Object.entries(e).filter(([r])=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(r));if(t.length===0)return"{}";return`{
|
|
646
|
+
${t.map(([r,n])=>` ${r}: '${bn(String(n))}',`).join(`
|
|
647
|
+
`)}
|
|
648
|
+
}`}function Bu(e){return/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/i.test(e.trim())}function sb(e){let t=[...new Set(e.map((r)=>r.trim().toLowerCase()).filter(Boolean))];for(let r of t)if(!Bu(r))throw Error(`Alias '${r}' is not a valid hostname.`);if(t.length===0)return"[]";return`[${t.map((r)=>`'${bn(r)}'`).join(", ")}]`}function ab(e){let t=Object.entries(e).map(([r,n])=>[r.trim(),String(n).trim()]).filter(([r,n])=>r&&n);if(t.length===0)return"{}";return`{
|
|
649
|
+
${t.map(([r,n])=>` '${bn(r)}': '${bn(n)}',`).join(`
|
|
650
|
+
`)}
|
|
651
|
+
}`}function JP(e,t,r){let n=t;while(n<r&&/\s/.test(e[n]))n++;let i=0,o,s=!1;for(;n<r;n++){let c=e[n];if(o){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}if(c===o)o=void 0;continue}if(c==='"'||c==="'"||c==="`"){o=c;continue}if(c==="{"||c==="["||c==="("){i++;continue}if(c==="}"||c==="]"||c===")"){if(i===0)return n;i--;continue}if(c===","&&i===0)return n}return r}function cb(e,t,r,n){let i=e.slice(t+1,r),o=new RegExp(`(^|[\\s,{])(${Fu(n)})\\s*:\\s*\\{`,"m").exec(i);if(!o)return null;let s=t+1+o.index+o[1].length,c=e.indexOf("{",s);return{nameStart:s,end:db(e,c)}}function GP(e){let r=[` ${ec(e.name)}: {`];if(vn(r,"deploy",e.deploy),vn(r,"root",e.root),vn(r,"path",e.path),vn(r,"domain",e.domain),vn(r,"type",e.type),vn(r,"build",e.build),vn(r,"start",e.start),e.port!==void 0)r.push(` port: ${e.port},`);if(vn(r,"pathRewriteStyle",e.pathRewriteStyle),e.ssl!==void 0)if(e.ssl===!1)r.push(" ssl: false,");else if(e.ssl===!0)r.push(" ssl: true,");else r.push(` ssl: { provider: '${bn(e.ssl.provider||"letsencrypt")}' },`);if(e.env&&Object.keys(e.env).length>0){r.push(" env: {");for(let[n,i]of Object.entries(e.env)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(n))continue;r.push(` ${n}: '${bn(String(i))}',`)}r.push(" },")}return r.push(" },"),r.join(`
|
|
652
|
+
`)}function bn(e){return e.replace(/\\/g,"\\\\").replaceAll(String.fromCharCode(39),"\\'").replace(/\r/g,"\\r").replace(/\n/g,"\\n")}function ec(e){let t=e.trim();if(!/^[A-Za-z_$][\w$]*$/.test(t))throw Error(`Invalid site name '${e}'. Use a valid JavaScript object key, e.g. docs or marketingSite.`);return t}function vn(e,t,r){if(r===void 0||r==="")return;let n=r.replace(/\\/g,"\\\\").replaceAll(String.fromCharCode(39),"\\'");e.push(` ${t}: '${n}',`)}function Lu(e){let t=/\bsites\s*:\s*{/g.exec(e);if(!t)throw Error("Could not find a top-level sites: { ... } block in cloud.config.ts");let r=e.indexOf("{",t.index),n=db(e,r);return{start:r,end:n}}function QP(e,t,r,n){let i=e.slice(t+1,r);return new RegExp(`(^|[\\s,{])${Fu(n)}\\s*:`,"m").test(i)}function Fu(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function db(e,t){let r=0,n,i=!1,o=!1,s=!1;for(let c=t;c<e.length;c++){let d=e[c],a=e[c+1];if(o){if(d===`
|
|
653
|
+
`)o=!1;continue}if(s){if(d==="*"&&a==="/")s=!1,c++;continue}if(n){if(i){i=!1;continue}if(d==="\\"){i=!0;continue}if(d===n)n=void 0;continue}if(d==="/"&&a==="/"){o=!0,c++;continue}if(d==="/"&&a==="*"){s=!0,c++;continue}if(d==='"'||d==="'"||d==="`"){n=d;continue}if(d==="{")r++;if(d==="}"){if(r--,r===0)return c}}throw Error("Could not find the closing brace for sites: { ... } in cloud.config.ts")}function lb(e,t,r){let n=(Array.isArray(r)?r:String(r??"").split(",")).map(String).filter(Boolean);if(!n.length){if(t)return;let o=e.map((s)=>s.id);return o.length?o:["__no_authorized_telemetry_resources__"]}let i=n.map((o)=>e.find((s)=>s.id===o||s.slug===o)?.id).filter((o)=>!!o);if(i.length!==n.length)throw Error("One or more telemetry resources are outside your authorized scope.");return[...new Set(i)]}import{createHash as mb}from"node:crypto";class gb{now;entries=new Map;constructor(e=Date.now){this.now=e}async getOrCreate(e,t,r,n){let i=this.entries.get(e);if(!r&&i&&i.expiresAt>this.now())return{value:await i.promise,cached:!0};let o=n().catch((s)=>{throw this.entries.delete(e),s});return this.entries.set(e,{expiresAt:this.now()+t,promise:o}),{value:await o,cached:!1}}invalidate(e){for(let t of this.entries.keys())if(t.startsWith(e))this.entries.delete(t)}}class fb{now;lastRun=new Map;constructor(e=Date.now){this.now=e}shouldRun(e,t,r=!1){let n=this.now(),i=this.lastRun.get(e);if(!r&&i!=null&&n-i<t)return!1;return this.lastRun.set(e,n),!0}}var hb=new gb,YP=new fb,ZP=2000,XP=3600000;function e_(e,t){if(e.kind==="log"&&!t.collectLogs)return!1;if(e.kind==="trace"&&!t.collectTraces)return!1;if((e.kind==="request"||e.name.startsWith("request."))&&!t.collectRequestAnalytics)return!1;if(!["log","trace","request"].includes(e.kind)&&!e.name.startsWith("request."))return!0;let r=e.requestId??e.traceId??`${e.source}\x00${e.workloadId??""}\x00${e.timestamp}`;return Number.parseInt(mb("sha256").update(r).digest("hex").slice(0,8),16)/4294967295<=t.samplingRate}function wt(...e){return`telemetry:${mb("sha256").update(e.map((t)=>String(t??"")).join("\x00")).digest("hex").slice(0,40)}`}function Uo(e,t,r,n){if(!n)return;return e.listResources(t,r).find((i)=>i.slug===n)?.id}function t_(e,t){let r=String(t??"").toLowerCase();if(["debug","info","warn","warning","error","fatal"].includes(r))return r==="fatal"?"error":r;return/fatal|panic|exception|error/i.test(e)?"error":/warn|timeout|throttl|retr(?:y|ies)/i.test(e)?"warning":"info"}function ub(e){let t=e.timestamp&&Number.isFinite(new Date(e.timestamp).getTime())?new Date(e.timestamp).toISOString():new Date().toISOString(),r={};try{let k=JSON.parse(e.message);if(k&&typeof k==="object"&&!Array.isArray(k))r=k}catch{}let n=Object.fromEntries(Object.entries(r).filter(([k])=>!/^(?:body|requestBody|responseBody|headers|authorization|cookie|cookies|query|queryString)$/i.test(k))),i=String(r.requestId??r.request_id??r["x-request-id"]??"")||void 0,o=String(r.traceId??r.trace_id??r["x-amzn-trace-id"]??"")||void 0,s=Number(r.durationMs??r.duration_ms??r.latencyMs??r.latency_ms),c=Number(r.statusCode??r.status_code??r.status),d=String(r.method??r.httpMethod??"")||void 0,a=pb(String(r.pathTemplate??r.path??r.url??"")||void 0),u=String(r.releaseId??r.release_id??"")||void 0,m=String(r.deploymentId??r.deployment_id??"")||void 0,h={projectId:e.projectId,environmentId:e.environmentId,resourceId:e.resourceId,source:e.source,timestamp:t,requestId:i,traceId:o,releaseId:u,deploymentId:m,workloadId:e.workloadId},y=Object.keys(r).length?JSON.stringify(n):e.message,w=[{...h,id:wt(e.source,e.name,t,y),kind:"log",name:e.name,level:t_(y,r.level),message:y,attributes:n}];if(d&&a&&Number.isFinite(c)){if(w.push({...h,id:wt("request",i,t,d,a,c),kind:"request",name:"http.request",method:d,pathTemplate:a,host:r.host,statusCode:c,durationMs:Number.isFinite(s)?s:void 0,bytesIn:Number(r.bytesIn)||void 0,bytesOut:Number(r.bytesOut)||void 0,region:r.region,cacheResult:r.cacheResult??r.cache,upstream:r.upstream,attributes:{userAgentFamily:r.userAgentFamily??"",protocol:r.protocol??""}}),Number.isFinite(s))w.push({...h,id:wt("request-duration",i,t),kind:"metric",name:"request.duration",value:s,unit:"ms",attributes:{method:d,pathTemplate:a,statusCode:c}});if(w.push({...h,id:wt("request-count",i,t),kind:"metric",name:"request.count",value:1,unit:"count",attributes:{method:d,pathTemplate:a,statusCode:c}}),c>=500)w.push({...h,id:wt("request-error",i,t),kind:"metric",name:"request.error",value:1,unit:"count",attributes:{method:d,pathTemplate:a,statusCode:c}})}return w}async function r_(e){let t=new tc(e.controlPlane),r=qo(e.controlPlane,e.projectId),n=new Date,i=[],o=[],s={projectId:e.projectId,environmentId:e.environmentId},c=Fr(e.config);try{let h=(c==="serverless"?await io(e.config,e.environment):await Ma(e.config,e.environment,{includeSiteHealth:e.includeSiteHealth,telemetryOnly:e.lightweight}))??{};if(c==="serverless"){for(let w of h.functionsDetail??[]){let k=Uo(e.controlPlane,e.projectId,e.environmentId,w.key),C={...s,resourceId:k,source:"cloudwatch",timestamp:n.toISOString(),workloadId:w.name,attributes:{provider:"aws",functionName:w.name,aggregationWindow:"24h"}};for(let[T,j,P]of[["snapshot.traffic.requests_24h",w.invocations,"count"],["snapshot.errors.count_24h",w.errors,"count"],["snapshot.latency.p50_24h",w.p50,"ms"],["snapshot.latency.p95_24h",w.p95,"ms"],["snapshot.latency.p99_24h",w.p99,"ms"],["snapshot.saturation.throttles_24h",w.throttles,"count"],["snapshot.memory.max_24h",w.maxMem,"MB"]])if(Number.isFinite(Number(j)))i.push({...C,id:wt("cloudwatch",w.name,T,n.toISOString()),kind:"metric",name:T,value:Number(j),unit:P})}try{let w=await nt(e.config,e.environment),k=new Rr(w.region),C=new Date(n.getTime()-3600000),T=300;for(let j of w.functions){let P=[{Name:"FunctionName",Value:j.name}],[O,U,q,N,Q]=await Promise.all([k.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:P,StartTime:C,EndTime:n,Period:300,Statistics:["Sum"]}),k.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"Errors",Dimensions:P,StartTime:C,EndTime:n,Period:300,Statistics:["Sum"]}),k.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"Duration",Dimensions:P,StartTime:C,EndTime:n,Period:300,ExtendedStatistics:["p50","p95","p99"]}),k.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"Throttles",Dimensions:P,StartTime:C,EndTime:n,Period:300,Statistics:["Sum"]}),k.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"ConcurrentExecutions",Dimensions:P,StartTime:C,EndTime:n,Period:300,Statistics:["Maximum"]})]),D=Uo(e.controlPlane,e.projectId,e.environmentId,j.mode),Y=(se,he,je,de)=>{for(let Re of se){let Me=Re.Timestamp&&Number.isFinite(new Date(Re.Timestamp).getTime())?new Date(Re.Timestamp).toISOString():void 0,me=je(Re);if(Me&&me!=null&&Number.isFinite(me))i.push({...s,resourceId:D,id:wt("cloudwatch-series",j.name,he,Me),kind:"metric",source:"cloudwatch",name:he,timestamp:Me,value:me,unit:de,workloadId:j.name,region:w.region,attributes:{provider:"aws",functionName:j.name,aggregationWindow:"300s"}})}};Y(O,"traffic.requests",(se)=>se.Sum,"count"),Y(U,"errors.count",(se)=>se.Sum,"count"),Y(q,"latency.p50",(se)=>se.Percentiles?.p50,"ms"),Y(q,"latency.p95",(se)=>se.Percentiles?.p95,"ms"),Y(q,"latency.p99",(se)=>se.Percentiles?.p99,"ms"),Y(N,"saturation.throttles",(se)=>se.Sum,"count"),Y(Q,"saturation.concurrency",(se)=>se.Maximum,"count")}}catch(w){o.push({source:"cloudwatch:series",message:w instanceof Error?w.message:String(w)})}for(let w of(h.serverlessLogs??[]).slice(0,ZP))i.push(...ub({...s,source:`cloudwatch:${w.source}`,name:`${w.source}.log`,timestamp:w.timestamp,message:String(w.message),resourceId:Uo(e.controlPlane,e.projectId,e.environmentId,w.source)}));for(let w of h.queuesDetail??[]){let k={...s,source:"cloudwatch",timestamp:n.toISOString(),attributes:{queue:w.name}};i.push({...k,id:wt("queue-depth",w.name,n.toISOString()),kind:"metric",name:"queue.depth",value:Number(w.visible??w.depth??0),unit:"count"}),i.push({...k,id:wt("queue-inflight",w.name,n.toISOString()),kind:"metric",name:"queue.inflight",value:Number(w.inFlight??0),unit:"count"})}let y=await Xa(e.config,e.environment,30);if(!y.ok)o.push({source:"xray",message:y.error??"X-Ray traces are unavailable."});for(let w of y.traces)i.push({...s,id:wt("xray",w.id),kind:"trace",source:"xray",name:"http.trace",timestamp:w.timestamp??n.toISOString(),traceId:w.id,durationMs:w.durationMs,statusCode:w.httpStatus,method:w.method,pathTemplate:w.url,attributes:{status:w.status,responseMs:w.responseMs}})}else{let y=h.systemMetrics;if(h.metricsUnavailable||!y)o.push({source:"host",message:"The host metrics probe is unavailable."});else{let w=Number(y.memTotalMb)>0?Number(y.memUsedMb)/Number(y.memTotalMb)*100:0,k=Number(y.swapTotalMb)>0?Number(y.swapUsedMb)/Number(y.swapTotalMb)*100:0,C=[["host.load",Number(y.load),"load"],["host.load.5m",Number(y.load5),"load"],["host.load.15m",Number(y.load15),"load"],["host.cpu.capacity",Number(y.cpus),"count"],["host.cpu.used_percent",Number(y.cpuUsedPct),"percent"],["host.memory.used",Number(y.memUsedMb)*1024*1024,"bytes"],["host.memory.total",Number(y.memTotalMb)*1024*1024,"bytes"],["host.memory.available",Number(y.memAvailableMb)*1024*1024,"bytes"],["host.memory.cache",Number(y.memCacheMb)*1024*1024,"bytes"],["host.memory.used_percent",w,"percent"],["host.swap.used",Number(y.swapUsedMb)*1024*1024,"bytes"],["host.swap.total",Number(y.swapTotalMb)*1024*1024,"bytes"],["host.swap.used_percent",k,"percent"],["host.disk.used_percent",Number(y.diskUsedPct),"percent"],["host.disk.used",Number(y.diskUsedGb)*1073741824,"bytes"],["host.disk.total",Number(y.diskTotalGb)*1073741824,"bytes"],["host.disk.inode_used_percent",Number(y.inodeUsedPct),"percent"],["host.network.rx",Number(y.networkRxBytes),"bytes"],["host.network.tx",Number(y.networkTxBytes),"bytes"],["host.network.rx_rate",Number(y.networkRxBytesPerSec),"bytes_per_second"],["host.network.tx_rate",Number(y.networkTxBytesPerSec),"bytes_per_second"],["host.network.rx_today",Number(y.networkRxBytesToday),"bytes"],["host.network.tx_today",Number(y.networkTxBytesToday),"bytes"],["host.network.rx_month",Number(y.networkRxBytesMonth),"bytes"],["host.network.tx_month",Number(y.networkTxBytesMonth),"bytes"],["host.processes",Number(y.processes),"count"],["host.uptime",Number(y.uptimeSeconds),"seconds"]];for(let[T,j,P]of C)if(Number.isFinite(j))i.push({...s,id:wt("host",T,n.toISOString()),kind:"metric",source:"host",name:T,timestamp:n.toISOString(),value:j,unit:P});for(let T of h.siteHealth??[]){let j=String(T.project??e.config.project.slug),P=String(T.name),O=P.startsWith(`${j}:`)?P.slice(j.length+1):P,U=`site:${j}:${O}`,q=Uo(e.controlPlane,e.projectId,e.environmentId,P),N={...s,resourceId:q,source:U,timestamp:T.checkedAt||n.toISOString(),host:T.route,attributes:{project:j,site:O,route:String(T.route),status:String(T.status)}},Q=[["site.health.up",T.status==="live"?1:0,"boolean"],["site.http.status",Number(T.httpStatus),"status"],["site.response.time",Number(T.responseMs),"ms"]];if(T.tlsDaysRemaining!=null)Q.push(["site.tls.days_remaining",Number(T.tlsDaysRemaining),"days"]);for(let[D,Y,se]of Q)if(Number.isFinite(Y))i.push({...N,id:wt(U,D,N.timestamp),kind:"metric",name:D,value:Y,unit:se})}}}}catch(h){o.push({source:c==="serverless"?"aws":"host",message:h instanceof Error?h.message:String(h)})}{let h=e.config.infrastructure?.compute?.monitoring,y=typeof h==="object"?h?.egressEndpoints:void 0,w=await Sc(y,{now:n.toISOString()});o.push(...w.errors);for(let k of w.metrics)i.push({...s,id:wt(k.attributes.source,k.name,k.timestamp),kind:"metric",source:`egress:${k.attributes.source}`,name:k.name,timestamp:k.timestamp,value:k.value,unit:k.unit,attributes:k.attributes})}if(!e.lightweight)try{let h=await or(e.config,e.environment),y=new yr(e.config,e.environment,{inventory:async()=>h});for(let w of h.workloads){let k=Uo(e.controlPlane,e.projectId,e.environmentId,w.links.service),C={...s,resourceId:k,source:`runtime:${w.provider}`,timestamp:n.toISOString(),workloadId:w.id,releaseId:w.links.release,attributes:{status:w.status,provider:w.provider,service:w.links.service??""}};if(i.push({...C,id:wt(w.id,"health",n.toISOString()),kind:"metric",name:"health.up",value:w.status==="running"?1:0,unit:"boolean"}),i.push({...C,id:wt(w.id,"restarts",n.toISOString()),kind:"metric",name:"saturation.restarts",value:w.restartCount??0,unit:"count"}),w.resources?.memoryBytes!=null)i.push({...C,id:wt(w.id,"memory",n.toISOString()),kind:"metric",name:"runtime.memory.used",value:w.resources.memoryBytes,unit:"bytes"});if(!w.capabilities.logs.supported)continue;try{let T=await y.logs(w.id,{limit:100,since:new Date(n.getTime()-300000)});for(let j of T.lines)i.push(...ub({...s,resourceId:k,source:`runtime:${w.provider}`,name:`${w.links.service??w.name}.log`,timestamp:j.timestamp,message:j.message,workloadId:w.id}))}catch(T){o.push({source:`runtime:${w.provider}`,message:T instanceof Error?T.message:String(T)})}}for(let w of h.sources.filter((k)=>k.status!=="fresh"))o.push({source:w.id,message:w.message??`Runtime source is ${w.status}.`})}catch(h){o.push({source:"runtime",message:h instanceof Error?h.message:String(h)})}if(!e.lightweight)for(let h of e.controlPlane.listEvents({projectId:e.projectId,limit:1000})){let y=h.payload;i.push({...s,id:`telemetry:event:${h.id}`,resourceId:h.resourceId,kind:"event",source:"control-plane",name:h.type,timestamp:h.createdAt,level:h.level,message:h.type,deploymentId:h.operationId,releaseId:typeof y.releaseId==="string"?y.releaseId:void 0,traceId:h.correlationId,attributes:y})}let d=i.filter((h)=>e_(h,r)).map((h)=>({...h,sampled:r.samplingRate<1&&(h.kind==="log"||h.kind==="trace"||h.kind==="request"||h.name.startsWith("request."))})),a=t.appendMany(d).length;if(YP.shouldRun(e.projectId,XP,!e.lightweight))t.enforceRetention(r,e.projectId);let u=t.status(e.projectId,e.environmentId,r.rawDays,r.samplingRate);for(let h of o)if(!u.some((y)=>y.source===h.source))u.push({source:h.source,freshness:"unavailable",samplingRate:r.samplingRate,retentionDays:r.rawDays,estimatedDailyBytes:0,message:h.message});let m=n.toISOString();return e.controlPlane.setSetting(`telemetry.collection:${e.projectId}:${e.environmentId??"all"}`,{generatedAt:m,errors:o,statuses:u,policy:r}),{collected:a,cached:!1,generatedAt:m,statuses:u,errors:o,policy:r}}async function zu(e){let r=`${`${e.projectId}:${e.environmentId??"all"}:${e.environment}`}:${e.lightweight?"lightweight":"full"}`,n=Fr(e.config)==="serverless"?300000:60000,i=await hb.getOrCreate(r,n,!!e.force,()=>r_(e));return{...i.value,cached:i.cached}}function yb(e){hb.invalidate(`${e}:`)}function vb(e,t={}){let r=t.shell||(process.platform==="win32"?"powershell.exe":"bash"),n=Bun.spawn([r,"-i"],{stdin:"pipe",stdout:"pipe",stderr:"pipe",cwd:t.cwd,env:{...process.env,TERM:"xterm-256color",PS1:"\\w $ "}}),i=new TextDecoder,o=async(s)=>{if(!s)return;let c=s.getReader();try{for(;;){let{done:d,value:a}=await c.read();if(d)break;if(a)e(i.decode(a))}}catch{}};if(o(n.stdout),o(n.stderr),t.onExit)n.exited.then((s)=>t.onExit(s)).catch(()=>{});return{write(s){try{n.stdin.write(s),n.stdin.flush()}catch{}},close(){try{n.stdin.end()}catch{}try{n.kill()}catch{}}}}var l_="127.0.0.1",u_=7676,Sb=65536,Jb="ts-cloud-dashboard-",Qi=i_(d_(import.meta.url));function p_(e){try{return process.kill(e,0),!0}catch(t){return t?.code!=="ESRCH"}}function m_(e=ic(),t=p_){let r=0;for(let n of bb(e,{withFileTypes:!0})){if(!n.isDirectory()||!n.name.startsWith(Jb))continue;let i=Te(e,n.name),o=n.name.match(/^ts-cloud-dashboard-(\d+)-/);if(o){let s=Number(o[1]);if(s===process.pid||t(s))continue}else if(bb(i).length>0)continue;ri(i,{recursive:!0,force:!0}),r+=1}return r}var g_={".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 g(e,t=200,r={}){return new Response(JSON.stringify(e,null,2),{status:t,headers:{"content-type":"application/json; charset=utf-8",...r}})}function f_(e,t,r,n){let i=new TextEncoder,o=Math.max(0,Math.floor(r)),s,c,d=!1,a=new ReadableStream({start(u){let m=()=>{if(d)return;if(d=!0,s?.(),c)clearInterval(c);n.removeEventListener("abort",m);try{u.close()}catch{}},h=(w)=>{if(d)return;if(w.reset)u.enqueue(i.encode(`event: reset
|
|
654
|
+
data: ${JSON.stringify({cursor:w.cursor,droppedBytes:w.droppedBytes})}
|
|
655
|
+
|
|
656
|
+
`));for(let k of w.chunks.filter((C)=>C.cursor>o))o=k.cursor,u.enqueue(i.encode(`id: ${k.cursor}
|
|
657
|
+
event: ${k.stream}
|
|
658
|
+
data: ${JSON.stringify(k)}
|
|
659
|
+
|
|
660
|
+
`));if(w.state!=="open")u.enqueue(i.encode(`event: state
|
|
661
|
+
data: ${JSON.stringify({state:w.state,error:w.error,cursor:w.cursor})}
|
|
662
|
+
|
|
663
|
+
`)),m()};s=e.subscribe(t.id,t.workloadId,(w)=>h(e.read(w.id,w.workloadId,o)??w));let y=e.read(t.id,t.workloadId,o);if(!y)return m();if(h(y),d)return;c=setInterval(()=>{if(!d)u.enqueue(i.encode(`event: heartbeat
|
|
664
|
+
data: ${JSON.stringify({cursor:o,at:new Date().toISOString()})}
|
|
665
|
+
|
|
666
|
+
`))},15000),c.unref?.(),n.addEventListener("abort",m,{once:!0})},cancel(){if(d=!0,s?.(),c)clearInterval(c)}});return new Response(a,{headers:{"cache-control":"no-cache, no-transform",connection:"keep-alive","content-type":"text/event-stream; charset=utf-8","x-accel-buffering":"no"}})}var h_=new Set(["action","operation","site","name","username","database","secretId","port","key","resourceId","environmentId"]);function y_(e,t,r,n,i){let o={};if(r&&typeof r==="object"&&!Array.isArray(r))for(let[c,d]of Object.entries(r)){if(!h_.has(c)||!["string","number","boolean"].includes(typeof d))continue;o[c]=typeof d==="string"?d.slice(0,256):d}let s=String(o.resourceId||o.site||o.secretId||o.database||o.name||t);return{method:e.toUpperCase(),path:t,target:s,status:n,outcome:n<400?"succeeded":"failed",durationMs:Math.max(0,Math.round(i)),input:o}}var v_=fn("ts-cloud-dummy-password");function oc(e,t=200){return new Response(e,{status:t,headers:{"content-type":"text/plain; charset=utf-8"}})}function b_(e,t,r=process.env){let n=r.TS_CLOUD_DASHBOARD_ORIGIN?.trim()||(r.TS_CLOUD_UI_DOMAIN?.trim()?`https://${r.TS_CLOUD_UI_DOMAIN.trim().replace(/^https?:\/\//,"")}`:""),i=["0.0.0.0","::"].includes(e)?void 0:e,o=n||(i&&["127.0.0.1","localhost","::1"].includes(i)?`http://${i.includes(":")?`[${i}]`:i}:${t}`:"");if(!o)return;try{let s=new URL(o),c=["127.0.0.1","localhost","::1"].includes(s.hostname);if(s.protocol!=="https:"&&!(s.protocol==="http:"&&c)||s.username||s.password||s.search||s.hash||s.pathname!=="/"&&s.pathname!=="")return;return s.origin}catch{return}}function S_(e,t){if(t&&Object.hasOwn(e.environments??{},t))return t;return Object.keys(e.environments??{})[0]??"production"}function w_(e,t,r){return r&&e.includes(r)?r:t}function wb(e,t,r){return e==null||t-e>=r}async function k_(e){let t=[Te(Qi,"..","..","..","..",".env"),Te(e,".env"),Te(e,".env.local"),Te(e,".env.production")];for(let r of t){if(!qr(r))continue;let n=await br(r,"utf8").catch(()=>"");for(let i of n.split(`
|
|
667
|
+
`)){let o=i.trim();if(!o||o.startsWith("#")||!o.includes("="))continue;let s=o.indexOf("="),c=o.slice(0,s).trim(),d=o.slice(s+1).trim();if(!/^[A-Z_][A-Z0-9_]*$/i.test(c)||process.env[c]!=null)continue;if(d.startsWith('"')&&d.endsWith('"')||d.startsWith("'")&&d.endsWith("'"))d=d.slice(1,-1);process.env[c]=d}}}function I_(e){return[Te(e,"config","cloud.ts"),Te(e,"config","cloud.js"),Te(e,"cloud.config.ts"),Te(e,"cloud.config.js")].find((r)=>qr(r))??null}function Yi(e){return e.infrastructure?.compute?.sshKeys??[]}function kb(e,t){let r=e.infrastructure??(e.infrastructure={}),n=r.compute??(r.compute={});n.sshKeys=t}function E_(e,t,r){let n=e.sites??(e.sites={});n[t]=r}function Uu(e){return Xn(e.infrastructure?.compute?.firewall?.allowedPorts??[])}function Ib(e,t){let r=e.infrastructure??(e.infrastructure={}),n=r.compute??(r.compute={}),i=n.firewall??(n.firewall={});i.allowedPorts=t}async function x(e){return await e.json().catch(()=>({}))}function Ji(e,t){let r=String(e.scopeType??"environment");if(!["project","environment","service","function","preview"].includes(r))throw Error("Configuration scopeType must be project, environment, service, function, or preview.");let n=String(e.scopeId??(r==="project"?t.projectId:r==="environment"?t.environmentId??"":""));if(!n)throw Error("Configuration scopeId is required.");if(r==="project")return{type:r,id:n};if(r==="environment")return{type:r,id:n,environmentId:n};if(r==="service"||r==="function")return{type:r,id:n,environmentId:String(e.environmentId??t.environmentId??"")||void 0,resourceId:n};return{type:r,id:n,environmentId:String(e.environmentId??t.environmentId??"")||void 0,resourceId:String(e.resourceId??"")||void 0,previewId:n}}function R_(e){if(["GET","HEAD","OPTIONS"].includes(e.method.toUpperCase()))return!0;let t=e.headers.get("sec-fetch-site");if(t==="cross-site")return!1;let r=e.headers.get("origin");if(!r)return!0;let n=new URL(e.url);if(r===n.origin)return!0;if(t!=="same-origin")return!1;try{let i=new URL(r),o=(e.headers.get("x-forwarded-host")??e.headers.get("host")??n.host).split(",")[0].trim(),s=e.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();if(!/^[A-Za-z0-9.-]+(?::\d{1,5})?$/.test(o)||i.host!==o)return!1;return!s||i.protocol===`${s}:`}catch{return!1}}var A_=new Set(["owner","admin","deployer","operator","viewer","auditor"]),C_=new Set(["organization","project","environment","resource"]),P_=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 rc(e){let t=String(e??"");return A_.has(t)?t:void 0}function Vo(e){let t=String(e.scopeType??"organization");if(!C_.has(t))return;if(t==="organization")return{type:"organization"};let r=String(e.scopeId??"").trim();return r?{type:t,id:r}:void 0}async function ti(e,t,r={}){let n=Fr(e),i={mode:n,environment:t,environments:Object.keys(e.environments??{}),project:{name:e.project.name,slug:e.project.slug,region:e.project.region}};try{return{...(n==="serverless"?await io(e,t):await Ma(e,t,{includeSiteHealth:r.includeSiteHealth}))??{},...i}}catch{return{...i}}}function __(e,t){if(!e)return t;let r={...t,...Array.isArray(e.sites)?{sites:e.sites}:{},...Array.isArray(e.sitesDetail)?{sitesDetail:e.sitesDetail}:{},...Array.isArray(e.siteHealth)?{siteHealth:e.siteHealth}:{}};if(r.mode!=="serverless"&&Array.isArray(r.sites))r.topology=Pn(r,{project:r.project?.name,environment:r.environment});return r}function T_(e){let t=[Te(e,"packages","ui"),Te(Qi,"..","..","..","ui"),Te(Qi,"..","..","ui"),Te(Qi,"..","ui-src"),Te(Qi,"..","..","ui-src"),Te(Qi,"..","..","dist","ui-src")];for(let r of t)if(qr(Te(r,"pages"))&&qr(Te(r,"package.json")))return r;return null}async function x_(e,t){let r=T_(e);if(!r)return null;let n;try{n=Vu(Te(ic(),`${Jb}${process.pid}-`));let i=Te(r,"node_modules",".bin","stx"),o=qr(i)?[i,"build","--pages","pages","--out",n,"--no-sitemap","--no-cache"]:["bunx","--bun","@stacksjs/stx","build","--pages","pages","--out",n,"--no-sitemap","--no-cache"],s=Bun.spawn(o,{cwd:r,stdout:"pipe",stderr:"pipe",env:{...process.env,TSCLOUD_DASHBOARD_DATA:_v(t)}}),[c,d,a]=await Promise.all([new Response(s.stdout).text(),new Response(s.stderr).text(),s.exited]);if(a!==0){if(ri(n,{recursive:!0,force:!0}),process.env.TSCLOUD_DASHBOARD_VERBOSE)console.warn(`ts-cloud dashboard: live UI build failed; serving the pre-built UI.
|
|
668
|
+
${c}
|
|
669
|
+
${d}`);return null}return n}catch(i){if(n)ri(n,{recursive:!0,force:!0});if(process.env.TSCLOUD_DASHBOARD_VERBOSE)console.warn(`ts-cloud dashboard: live UI build errored; serving the pre-built UI. ${i.message}`);return null}}function Gb(e){let t=e.infrastructure?.compute?.managedServices?JSON.parse(JSON.stringify(e.infrastructure.compute.managedServices)):void 0;if(t?.vitess?.password)t.vitess.password="";return{project:{name:e.project?.name,slug:e.project?.slug,region:e.project?.region},provider:e.provider,environments:Object.keys(e.environments??{}),compute:e.infrastructure?.compute?{provider:e.infrastructure.compute.provider,runtime:e.infrastructure.compute.runtime,webServer:e.infrastructure.compute.webServer,proxy:e.infrastructure.compute.proxy?{engine:e.infrastructure.compute.proxy.engine,onDemandTls:e.infrastructure.compute.proxy.onDemandTls,cdn:!!e.infrastructure.compute.proxy.cdn}:void 0,managedServices:t,sshKeys:hn(Yi(e)).map((r)=>({name:r.name,type:r.type,fingerprint:r.fingerprint,added:r.added}))}:void 0,sites:Object.fromEntries(Object.entries(e.sites??{}).map(([r,n])=>[r,{domain:n.domain,path:n.path,type:n.type,deploy:n.deploy,root:n.root,port:n.port,ssl:n.ssl}]))}}function Hu(e){return[{id:"status",label:"Refresh Cloud Status",description:"Runs the local ts-cloud status checks against configured providers.",command:["status","--env",e],mutates:!1},{id:"doctor",label:"Run Doctor",description:"Checks local tooling, credentials, and provider access.",command:["doctor"],mutates:!1},{id:"security-scan",label:"Security Scan",description:"Runs the pre-deploy scanner from this checkout.",command:["deploy:security-scan","--source",".","--fail-on","critical"],mutates:!1},{id:"deploy",label:"Deploy Environment",description:"Deploys the selected environment from the local checkout.",command:["deploy","--env",e,"--yes"],mutates:!0,confirm:"deploy"}]}function Qb(e,t){return Hu(t).find((r)=>r.id===e)}function Eb(e){if(e.length<=Sb)return e;return`${e.slice(0,Sb)}
|
|
670
|
+
|
|
671
|
+
[output truncated]`}async function Rb(e,t,r){let n=e.getReader(),i=new TextDecoder,o="";while(!0){let{done:c,value:d}=await n.read();if(c)break;let a=i.decode(d,{stream:!0});if(o+=a,a)r?.(t,a)}let s=i.decode();if(s)o+=s,r?.(t,s);return o}async function qu(e,t){let r=Bun.spawn([process.execPath,t.cliEntry,...e.command],{cwd:t.cwd,stdout:"pipe",stderr:"pipe",env:{...process.env,...t.env}}),n=()=>{try{r.kill()}catch{}};if(t.signal?.aborted)n();else t.signal?.addEventListener("abort",n,{once:!0});try{let[i,o,s]=await Promise.all([Rb(r.stdout,"stdout",t.onOutput),Rb(r.stderr,"stderr",t.onOutput),r.exited]);return{action:e.id,command:["cloud",...e.command].join(" "),exitCode:s,ok:s===0,stdout:Eb(i),stderr:Eb(o)}}finally{t.signal?.removeEventListener("abort",n)}}function D_(){return Object.entries(process.env).filter(([e,t])=>!!t&&t.length>=8&&/(?:secret|token|password|passwd|private|credential|api.?key|access.?key)/i.test(e)).map(([,e])=>e)}var O_=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 $_(e){let t=Ho(e);if(t&&t!==".html")return!1;let r=e.replace(/\.html$/,"").replace(/\/+$/,"")||"/";if(r==="/")return!1;return!O_.has(r)}var N_={"/":"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 Ab(e,t){if(t.role==="admin")return!0;let r=Ho(e);if(r&&r!==".html")return!0;if(t.organizationSource==="legacy")return!$_(e);let n=e.replace(/\.html$/,"").replace(/\/+$/,"")||"/";if(n==="/access-denied")return!0;let i=N_[n];return!!i&&!!t.capabilities?.includes(i)}function j_(e,t){let r=decodeURIComponent(t).replace(/^\/+/,""),i=o_(r===""?"index.html":r);if(i.startsWith("..")||i.includes("/../"))return null;let o=Te(e,i);if(qr(o)&&!Kb(o).isDirectory())return o;if(!Ho(o)&&qr(`${o}.html`))return`${o}.html`;if(!Ho(o)&&qr(Te(o,"index.html")))return Te(o,"index.html");return null}async function Cb(e,t){let r=j_(e,t);if(!r){let o=Te(e,"404.html");if(qr(o))return new Response(await br(o),{status:404,headers:{"content-type":"text/html; charset=utf-8"}});return oc("Not found",404)}if(Kb(r).isDirectory())return oc("Not found",404);let n=await br(r),i=g_[Ho(r)]??"application/octet-stream";return new Response(n,{headers:{"content-type":i}})}var nc=["observe","backup","restore","restart","resize","version","rotate","expose","delete","logs","slow_queries","users","databases"],Pb=new WeakMap;async function _b(e){let t=Pb.get(e);if(t)return t;let r=await import("./spend/index.js"),n=new r.SpendStore(e),i={store:n,service:new r.SpendService(n),gate:new r.SpendGate(e)};return Pb.set(e,i),i}async function M_(e={}){m_();let t=e.cwd??process.cwd(),r=e.host??l_,n=e.port??u_,i=e.cliEntry??process.argv[1];if(e.box)process.env.TS_CLOUD_DASHBOARD_BOX="1";await k_(t);let o=e.config??await Sh(),s=process.env.TS_CLOUD_DASHBOARD_DB_PASSWORD,c=gt(o);if(s&&c&&!c.password)c.password=s;let d=o.infrastructure?.compute?.managedServices?.vitess;if(s&&d&&typeof d==="object"&&!d.password)d.password=s;let a=yp(t,o);if(a.reconciliation.failed>0)console.warn(` ts-cloud dashboard: marked ${a.reconciliation.failed} orphaned operation(s) as failed after restart.`);let u=Object.keys(o.environments??{}),m=S_(o,e.environment),h=I_(t),y=await ti(o,m),w=new Map([[m,y]]),k=new Map([[m,Date.now()]]),C=new Map([[m,Date.now()]]),T=new Map,j=Math.min(300000,Math.max(5000,Number(process.env.TS_CLOUD_DASHBOARD_REFRESH_MS)||30000)),P=Math.min(1800000,Math.max(60000,Number(process.env.TS_CLOUD_DASHBOARD_SITE_REFRESH_MS)||300000)),O=Fr(o)!=="serverless",U=(f)=>{let X=w.get(f);if(X&&!wb(k.get(f),Date.now(),j))return Promise.resolve(X);let te=T.get(f);if(te)return te;let Z=!O||wb(C.get(f),Date.now(),P),ae=ti(o,f,{includeSiteHealth:Z}).then((Ie)=>{let S=w.get(f),ht=Z?Ie:__(S,Ie);if(w.set(f,ht),k.set(f,Date.now()),Z)C.set(f,Date.now());if(S?._serverReachable!==ht._serverReachable||S?._metricsStatus!==ht._metricsStatus||(S?.sitesDetail?.length??0)!==(ht.sitesDetail?.length??0))de();return ht}).finally(()=>T.delete(f));return T.set(f,ae),ae},q=Wu(t),N=process.env.TS_CLOUD_DASHBOARD_TELEMETRY?.trim();if(e.box&&N!=="0"&&(N==="1"||!o.cloud?.attachTo)){let f=!1,X=Date.now()+300000,te=async()=>{if(f)return;f=!0;try{let ae=Date.now(),Ie=ae>=X;if(Ie)X=ae+300000;let S=a.environments.get(m);await zu({controlPlane:a.store,projectId:a.project.id,environmentId:S?.id,config:o,environment:m,force:!0,lightweight:!0,includeSiteHealth:Ie})}catch(ae){if(e.verbose)console.warn(` ts-cloud dashboard: background telemetry collection failed: ${ae instanceof Error?ae.message:String(ae)}`)}finally{f=!1}};te(),setInterval(()=>void te(),60000).unref?.()}let D=new Map,Y=new Map,se=new Set,he=0;function je(f,X){if(f.role==="admin"&&!a.store.getActorByExternalId("user",`dashboard:${f.username.toLowerCase()}`))return f;let te=a.store.getActorByExternalId("user",`dashboard:${f.username.toLowerCase()}`),Z=te?a.store.getMembershipForActor(a.organization.id,te.id):void 0;if(!Z||Z.status!=="active")return{...f,role:"member",sites:{},capabilities:[]};let ae=a.store.listGrants(Z.id),Ie=a.store.resolveAuthorizationTarget(a.organization.id,Z.scope)??a.store.resolveAuthorizationTarget(a.organization.id,{type:"project",id:a.project.id}),S=Wo({membership:Z,grants:ae,target:Ie});if(Z.roleTemplate==="owner"||Z.roleTemplate==="admin")return{...f,role:"admin",sites:{},organizationRole:Z.roleTemplate,organizationSource:Z.source,capabilities:S};let ht=a.environments.get(X),Ke={};for(let ue of a.store.listResources(a.project.id,ht?.id).filter((fe)=>fe.kind==="application")){let fe=a.store.resolveAuthorizationTarget(a.organization.id,{type:"resource",id:ue.id});if(!fe||!Xt({membership:Z,grants:ae,capability:"project:read",target:fe}).allowed)continue;Ke[ue.slug]=Xt({membership:Z,grants:ae,capability:"config:write",target:fe}).allowed?"owner":"collaborator"}return{...f,role:"member",sites:Ke,organizationRole:Z.roleTemplate,organizationSource:Z.source,capabilities:S}}function de(){he+=1,D.clear();for(let f of se)ri(f,{recursive:!0,force:!0});se.clear()}let Re=(f,X)=>`${X}:${f.role==="admin"?"admin":`member:${Object.entries(f.sites).sort(([te],[Z])=>te.localeCompare(Z)).map(([te,Z])=>`${te}=${Z}`).join(",")}`}:${[...f.capabilities??[]].sort().join(",")}`;async function Me(f,X){let te=je(f,X),Z=Re(te,X),ae=D.get(Z);if(ae)return ae;let Ie=Y.get(Z);if(Ie)return Ie;let S=he,ht=(async()=>{let Ke=w.get(X)??await ti(o,X);w.set(X,Ke);let ue={..._u(Ke,{user:te,slug:o.project.slug}),viewer:{role:te.role,organizationRole:te.organizationRole,organizationSource:te.organizationSource,capabilities:te.capabilities??[]}},fe=await x_(t,ue);if(fe&&S!==he)return ri(fe,{recursive:!0,force:!0}),q?.uiRoot;if(fe)se.add(fe);let at=fe??q?.uiRoot;if(at)D.set(Z,at);return at})();Y.set(Z,ht);try{return await ht}finally{Y.delete(Z)}}let me=await Me({username:"",passwordHash:"",role:"admin",sites:{}},m);if(!me)throw Error("ts-cloud dashboard UI not found. Run `bun run build` in ts-cloud or reinstall the package.");let R=new WeakMap,M=process.env.TS_CLOUD_DASHBOARD_TERMINAL!=="0",F=process.env.TS_CLOUD_DASHBOARD_AUTH==="0";if(F&&e.box)throw Error("TS_CLOUD_DASHBOARD_AUTH=0 is refused in box mode: the dashboard is internet-facing there, and disabling auth would expose a root shell.");let K=!F,ye=ov(t),Ae=K?dv(t,process.env.TS_CLOUD_UI_USERNAME?.trim()||"admin"):void 0,G=new ks(a.store,{encryptionKey:on(t)}),be=new Rs(a.store),ge=new Do(a.store),oe=new Mc(a.store,{encryptionKey:on(t)}),ft=new Rc(a.store),ni=new _c(a.store,{cwd:t}),dr=new Cc(a.store,{encryptionKey:on(t)}),xe=new $e(a.store,{workerId:`dashboard:${process.pid}`}),Be=new yd(a.store),Sr=new Cd(a.store,on(t)),Vr=new Pl(a.store),Ko=new js(Be,xe,Sr),Wr=o.project?.region??"us-east-1",Ku=on(t),xt=new Dl(Vr,{encryptionKey:Ku,backends:[new Po(a.store,Ku),new _l(new Yr(Wr),Wr),new Tl(new Hb(Wr),Wr),new xl]});await Ph(xt,a,o);let sc=new Fn(Wr),Yb={aws_rds:new vd(new Ed(sc)),aws_aurora:new bd(new Rd(sc)),aws_elasticache:new Sd(new Ad(new Ls(Wr))),server:new wd(new Ei),container:new kd(new Ei)},Ju=(f)=>Yb[f.provider],Je=new md(a.store),Sn=new Os(Je,xe),Gu=new fd(Sr),Zb={managed_database:new hd(Be,sc),logical_database:new xd(Be,Sr),volume:new Od,files:new Td(t),control_plane:new Nd(a.store,t),infrastructure:new Md(new Vs(Wr))},Xb=(f)=>Zb[f.resourceKind],eS=(f)=>f.provider==="aws_backup"?void 0:Gu,ac=new Nb(a.store),cc=[new Bb,new Lb(yt(t,"volumes"))],wr=new jb(ac,cc,xe),Zi=new $l(a.store),lr=new Nl(Zi,[new _o("aws"),new _o("hetzner"),new _o("ssh")],xe),Hr=new Ul(a.store),Qu=new ql(Hr,Zi),wn=new Kl(a.store),Yu=new Jl(wn,xe),kr=new Bl(a.store),dc=new Ll(kr,xe),Zu=["releases","artifacts","operations","logs","previews","snapshots","orphaned_resources"].map((f)=>new zl(f,a.store,a.project.id,a.organization.id)),ot=new dd(a.store),Xu=new ad(ot,{queue:xe}),He=new vs(a.store),Kr=new bs(a.store),zt=new Dn(a.store),le=new Fb(a.store,{encryptionKey:on(t)}),tS=()=>_b(a.store);for(let f of a.environments.values())sd(ot,o,{organization:a.organization,project:a.project,environment:f,resources:a.store.listResources(a.project.id,f.id)});let Ut=new zb(le,{emailImpl:async(f)=>{let{email:X}=await import("./chunk-a84gmpyh.js");return X.send(f)}}),ep=async(f)=>{let X=Wb(le,a.project.id,f),te=[];for(let Z of X.filter((ae)=>ae.notify&&ae.alert))te.push(...await Ut.deliverAll(Ut.enqueue(a.organization.id,Z.alert,Z.transition)));return te.push(...await Ut.deliverAll(Ut.enqueueRemindersAndEscalations(a.organization.id,le.listAlerts(a.project.id,{environmentId:f,states:["firing"]})))),te.push(...await Ut.retryDue()),{evaluations:X,deliveries:te}},lc=!1,rS=async()=>{if(lc)return;lc=!0;try{for(let f of a.environments.values())for(let X of le.listHealthChecks(a.project.id,f.id).filter((te)=>te.enabled)){let te=le.listHealthResults(X.id,1)[0];if(te&&Date.now()-new Date(te.checkedAt).getTime()<X.intervalSeconds*1000)continue;let Z=await new Gi(le).runAndEvaluate(X);for(let ae of Z.evaluations.filter((Ie)=>Ie.notify&&Ie.alert))await Ut.deliverAll(Ut.enqueue(a.organization.id,ae.alert,ae.transition))}}finally{lc=!1}},tp=setInterval(()=>{for(let f of a.environments.values())ep(f.id).catch((X)=>console.error("ts-cloud alert evaluation failed:",X))},60000);tp.unref?.();let rp=setInterval(()=>{rS().catch((f)=>console.error("ts-cloud health check evaluation failed:",f))},30000);rp.unref?.();let np=setInterval(()=>{try{Xu.tick()}catch(f){console.error("ts-cloud scheduled job evaluation failed:",f)}},30000);np.unref?.();let ip=setInterval(()=>{try{Sn.enqueueDue(),Sn.enqueueRetention()}catch(f){console.error("ts-cloud backup policy evaluation failed:",f)}},30000);ip.unref?.(),He.cleanup();let op=setInterval(()=>{try{He.cleanup()}catch(f){console.error("ts-cloud preview cleanup failed:",f)}},3600000);op.unref?.();let nS=e.queueWorker??!0,iS=D_(),oS=async(f,X)=>{let Z=(f.environmentId?a.store.listEnvironments(f.projectId).find((ae)=>ae.id===f.environmentId):void 0)?.slug??String(m);if(X.kind==="dashboard_operation"&&X.operationId){let ae=w.get(Z)??y,Ie=Pu(X.operationId,o,ae);if(!Ie||Ie.danger||!["scheduler","backup","worker"].includes(Ie.group))return{ok:!1,stderr:"The allowlisted dashboard operation is no longer available."};let S=await Ya(o,Z,Ie);return{ok:S.ok,stdout:S.stdout,stderr:S.stderr??S.error,retryable:/temporar|unavailable|timeout|network/i.test(S.stderr??S.error??""),output:{command:S.command??null,operation:S.operation}}}if(X.kind==="serverless_scheduler"){let ae=await Mu(o,Z,"run");return{ok:ae.ok,stdout:ae.stdout,stderr:ae.error,retryable:/temporar|unavailable|timeout|network/i.test(ae.error??""),output:{command:ae.command??null,operation:"serverless_scheduler"}}}return{ok:!1,stderr:`No safe executor is configured for ${X.kind}.`}},Jo=nS?new Ob(xe,{...$b({store:a.store,execute:async(f,X)=>{let te=X.operation.input&&typeof X.operation.input==="object"&&!Array.isArray(X.operation.input)?X.operation.input:{},Z=te.source&&typeof te.source==="object"?te.source:void 0,ae=t,Ie,S,ht;try{if(Z?.bindingId&&Z?.connectionId&&Z?.commitSha){let ue=oe.getBinding(String(Z.bindingId)),fe=oe.getConnection(String(Z.connectionId));if(!ue||!fe||ue.connectionId!==fe.id)throw Error("Queued source binding is no longer available");let tt=(ue.repositoryId?oe.getRepository(ue.repositoryId):oe.listRepositories(fe.id).find((si)=>si.fullName.toLowerCase()===ue.repositoryFullName.toLowerCase()))?.cloneUrl;if(!tt&&fe.provider==="generic_ssh")tt=`git@${new URL(fe.host).hostname}:${ue.repositoryFullName}.git`;if(!tt)tt=new URL(`/${ue.repositoryFullName}.git`,fe.host.endsWith("/")?fe.host:`${fe.host}/`).href;let V=ue.deployKeyId?oe.getDeployKey(ue.deployKeyId):void 0,Le=V&&ue.deployKeyId?{...V,privateKey:oe.getDeployPrivateKey(ue.deployKeyId)}:void 0;if(["github","gitlab","bitbucket","gitea"].includes(fe.provider)&&f.target.previewId){let si=tn(fe,oe.getCredential(fe.id)),B=He.previews.getInstance(f.target.previewId);ht=async(qt,Xo)=>{try{await si.setCommitStatus(ue.repositoryFullName,String(Z.commitSha),{state:qt,url:B?.url,description:Xo})}catch(ai){X.log(`Could not publish source status: ${ai instanceof Error?ai.message:String(ai)}`,{stream:"stderr"})}},await ht("pending",`Preview deployment started for ${String(Z.commitSha).slice(0,12)}`)}Ie=Vu(Te(ic(),"ts-cloud-queued-source-")),X.log(`Checking out immutable source commit ${Z.commitSha}.`,{stream:"system"}),ae=(await Fc({remote:tt,binding:ue,destination:Te(Ie,"checkout"),ref:String(Z.branch??ue.defaultBranch),commitSha:String(Z.commitSha)},{credential:oe.getCredential(fe.id),deployKey:Le})).directory}if(X.operation.kind!=="preview.destroy"){let ue=f.target.previewId?He.previews.getInstance(f.target.previewId):void 0,fe=ue?He.previews.getDefinition(ue.definitionId):void 0,at=X.operation.resourceId?a.store.getResource(X.operation.resourceId):void 0;if(S=await xt.resolve({projectId:a.project.id,environmentId:X.operation.environmentId,resourceId:X.operation.resourceId,functionId:at?.kind==="function"?at.id:void 0,previewId:ue?.id,trustedPreview:!!ue&&!ue.fork,allowedPreviewSecrets:fe?.inheritedSecrets}),S.warnings.some((tt)=>tt.code==="missing_required"))throw Error(`Required deployment configuration is unavailable: ${S.warnings.filter((tt)=>tt.code==="missing_required").map((tt)=>tt.key).join(", ")}`);if(X.operation.resourceId)for(let tt of Object.values(S.entries))Vr.setDependency({entryId:tt.id,resourceId:X.operation.resourceId,injectionTarget:"environment",required:tt.required,requiresRedeploy:!0});X.log(`Resolved configuration ${S.configurationHash.slice(0,18)} for ${Object.keys(S.values).length} keys.`,{stream:"system"})}let Ke=await qu(f,{cwd:ae,cliEntry:i,signal:X.signal,env:S?.values,onOutput:(ue,fe)=>X.log(fe,{stream:ue,step:"execute",secrets:[...iS,...Object.entries(S?.entries??{}).filter(([,at])=>at.kind==="secret").map(([at])=>S.values[at]).filter(Boolean)]})});if(Ke.ok&&X.operation.resourceId&&S)for(let ue of Object.values(S.entries))Vr.setDependency({entryId:ue.id,resourceId:X.operation.resourceId,injectionTarget:"environment",required:ue.required,requiresRedeploy:!1,lastDeployedVersion:ue.version});return await ht?.(Ke.ok?"success":"failure",Ke.ok?`Preview is ready at ${String(Z?.commitSha).slice(0,12)}`:`Preview deployment failed at ${String(Z?.commitSha).slice(0,12)}`),Ke}catch(Ke){throw await ht?.("error",`Preview deployment could not complete at ${String(Z?.commitSha).slice(0,12)}`),Ke}finally{if(Ie)ri(Ie,{recursive:!0,force:!0})}}}),...Sg({store:ot,executor:oS}),...Dg({store:Be,secrets:Sr,resolveAdapter:Ju}),...xh(Zi,lr.drivers),...Zh(wn,[new Gl("aws","AWS regional execution requires an injected AwsRegionalTransport; topology and plans were preserved without provider mutation.")]),...Vh({store:kr,cleanup:Zu}),...Mb(ac,cc),...Pg({store:Je,queue:xe,resolveSource:Xb,resolveDestination:eS,validateHealth:async(f,X)=>{if(!f.healthCheckId)return{healthy:!0,mode:"adapter"};let te=le.getHealthCheck(f.healthCheckId);if(!te||te.projectId!==f.projectId)return{healthy:!1,error:"Configured restore health check was not found."};let Z=await new Gi(le).runAndEvaluate(te);return{healthy:Z.result.status==="healthy",healthCheckId:te.id,healthResultId:Z.result.id,target:X}}}),...Im({store:a.store,resolveDriver:e.releaseDriver??((f)=>({name:`${a.store.getResource(f.resourceId)?.provider??"provider"} release driver`,capability:()=>({strategy:f.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(f,X)=>{let te=le.listHealthChecks(X.projectId,X.environmentId).find((ae)=>ae.enabled&&ae.name===f&&(!ae.resourceId||ae.resourceId===X.resourceId));if(!te)return{healthy:!1,message:`Named health gate ${f} was not found for this release.`};let Z=await new Gi(le).runAndEvaluate(te);return{healthy:Z.result.status==="healthy",evidence:{healthCheckId:te.id,healthResultId:Z.result.id,status:Z.result.status,timings:Z.result.timings},message:Z.result.message}}})},{parallelism:e.queueParallelism??(Number(process.env.TS_CLOUD_QUEUE_PARALLELISM)||8),onError:(f)=>console.error("ts-cloud deployment queue worker failed:",f)}):void 0;if(wy(a),Na(ge,ar(a,String(m)),y),Ae)es(a,Ae.users),pv(G,a,Ae.users);let ze=lv({cwd:t,enabled:K,secret:ye,authentication:G,authorization:{store:a.store,organizationId:a.organization.id,projectId:a.project.id,defaultEnvironment:String(m)}}),Ge=new Xl,sp=setInterval(()=>Ge.sweep(),60000);sp.unref?.();let Go=new Fo,uc=new Fo(3,900000,900000),Qo=new Fo(8,900000,900000),ap=setInterval(()=>Go.prune(),300000),cp=setInterval(()=>uc.prune(),300000),dp=setInterval(()=>Qo.prune(),300000);if(ap.unref?.(),cp.unref?.(),dp.unref?.(),K){if(Ae?.generated)console.warn(`
|
|
672
|
+
ts-cloud dashboard: created the first admin.
|
|
673
|
+
username: ${Ae.generated.username}
|
|
674
|
+
password: ${Ae.generated.password}
|
|
675
|
+
Saved (hashed) to ${av()}. This password is shown once.
|
|
676
|
+
`)}else console.warn(" ts-cloud dashboard: authentication is DISABLED (TS_CLOUD_DASHBOARD_AUTH=0). Every request runs as an admin.");let Jr=r!=="127.0.0.1"&&r!=="localhost",pc=(f)=>n_("sha256").update(`${ye}:${f}`).digest("hex").slice(0,16),sS=Vc({controlPlane:a.store,identities:be,sources:oe,applications:{drafts:ft,artifacts:ni,registries:dr}}),lp=(f)=>f.headers.get("user-agent")?.trim().slice(0,256)||void 0,Yo=(f,X,te,Z="local")=>G.createSession({identityId:f,authMethod:Z,userAgent:lp(X),networkHint:pc(te)}),re=(f)=>{let X=a.store.getActorByExternalId("user",`dashboard:${f.username.toLowerCase()}`),te=X?a.store.getMembershipForActor(a.organization.id,X.id):void 0;return{actor:X,membership:te,grants:te?a.store.listGrants(te.id):[]}},ii=(f,X,te)=>{if(f.role==="admin")return!0;let Z=a.store.getOperation(X),ae=re(f);if(!Z||!ae.membership)return!1;let Ie=Z.resourceId?{type:"resource",id:Z.resourceId}:Z.environmentId?{type:"environment",id:Z.environmentId}:Z.projectId?{type:"project",id:Z.projectId}:{type:"organization"},S=a.store.resolveAuthorizationTarget(a.organization.id,Ie);return!!S&&Xt({membership:ae.membership,grants:ae.grants,capability:te,target:S}).allowed},st=(f,X,te)=>{if(f.role==="admin")return!0;let Z=re(f);if(!Z.membership)return!1;let ae=a.store.resolveAuthorizationTarget(a.organization.id,{type:"resource",id:X});return!!ae&&Xt({membership:Z.membership,grants:Z.grants,capability:te,target:ae}).allowed},Xi=(f,X,te)=>{if(f.role==="admin")return!0;let Z=re(f);if(!Z.membership)return!1;let ae=a.store.resolveAuthorizationTarget(a.organization.id,{type:"environment",id:X});return!!ae&&Xt({membership:Z.membership,grants:Z.grants,capability:te,target:ae}).allowed},Zo=(f,X)=>{if(f.role==="admin")return!0;let te=re(f);if(!te.membership)return!1;let Z=a.store.resolveAuthorizationTarget(a.organization.id,{type:"organization"});return!!Z&&Xt({membership:te.membership,grants:te.grants,capability:X,target:Z}).allowed},oi=Bun.serve({hostname:r,port:n,idleTimeout:30,websocket:{open(f){if(!M){f.send(`The web terminal is disabled (TS_CLOUD_DASHBOARD_TERMINAL=0).\r
|
|
677
|
+
`),f.close();return}let X=vb((te)=>f.send(te),{cwd:t,onExit:()=>{try{f.close()}catch{}}});R.set(f,X),f.send(`Connected to ${r==="127.0.0.1"?"localhost":r} shell. This is a line-oriented shell (no full-screen apps).\r
|
|
678
|
+
`)},message(f,X){R.get(f)?.write(typeof X==="string"?X:new TextDecoder().decode(X))},close(f){R.get(f)?.close(),R.delete(f)}},async fetch(f,X){let te=Date.now(),Z=f.clone(),ae=f.headers.get("x-request-id")?.slice(0,128)||crypto.randomUUID(),Ie=!["GET","HEAD","OPTIONS"].includes(f.method.toUpperCase()),S=new URL(f.url),Ke=await(async()=>{let ue=X??oi,fe=b_(r,ue.port??n),at=await sS(f,pc(ue.requestIP(f)?.address??"unknown"));if(at)return at;let tt=S.searchParams.get("env"),V=w_(u,m,tt),Le=w.get(V);if(!Le)Le=await U(V);try{if(!R_(f))return g({ok:!1,error:"Cross-site requests are not allowed."},403);let kn=/^\/api\/source\/webhooks\/([A-Za-z0-9_-]{16,200})$/.exec(S.pathname);if(kn&&f.method==="POST"){let l=await Lm({sources:oe,controlPlane:a.store,endpointToken:kn[1],headers:f.headers,rawBody:new Uint8Array(await f.arrayBuffer())});return g({accepted:l.accepted,duplicate:l.duplicate,status:l.status,operationIds:l.operations.map((p)=>p.id),message:l.message},l.accepted?202:404)}let si=/^\/auth\/oidc\/([a-z0-9-]+)\/(start|callback)$/.exec(S.pathname);if(si&&f.method==="GET"){let[,l,p]=si;if(!fe)return new Response(null,{status:302,headers:{location:"/login?sso_error=configuration"}});if(p==="start")try{let v=await td(G,l,fe,S.searchParams.get("return")??void 0,e.oidcFetch);return new Response(null,{status:302,headers:{location:v.authorizationUrl,"cache-control":"no-store"}})}catch(v){return a.store.appendEvent({organizationId:a.organization.id,type:"auth.oidc.start_failed",level:"warning",payload:{provider:l,reason:v instanceof Error?v.message.slice(0,200):"unknown"}}),new Response(null,{status:302,headers:{location:"/login?sso_error=start","cache-control":"no-store"}})}try{if(S.searchParams.has("error")){let A=G.getOidcProviderBySlug(l),E=S.searchParams.get("state");if(A&&E)G.consumeOidcTransaction(A.id,E);throw Error("OIDC provider returned an authorization error")}let v=await rd(G,{providerSlug:l,state:S.searchParams.get("state")??"",code:S.searchParams.get("code")??"",origin:fe},e.oidcFetch),b=mv(G,a,t,v.identity);G.recordLogin(b.identity.id);let I=Yo(b.identity.id,f,ue.requestIP(f)?.address??"unknown","oidc");return de(),a.store.appendEvent({organizationId:a.organization.id,actorId:b.identity.actorId,type:"auth.login.succeeded",payload:{method:"oidc",provider:l,provisioned:b.provisioned}}),new Response(null,{status:302,headers:{location:v.returnPath,"cache-control":"no-store","set-cookie":Wi(I.token,{secure:Jr,maxAgeMs:nn})}})}catch(v){return a.store.appendEvent({organizationId:a.organization.id,type:"auth.oidc.callback_failed",level:"warning",payload:{provider:l,reason:v instanceof Error?v.message.slice(0,200):"unknown"}}),new Response(null,{status:302,headers:{location:"/login?sso_error=callback","cache-control":"no-store"}})}}if(S.pathname==="/api/invitations/accept"&&f.method==="POST"){let l=await x(f),p=String(l.token??"").trim(),v=String(l.username??"").trim(),b=String(l.password??"");if(!p||!Ha(v)||b.length<12)return g({ok:!1,error:"Invitation token, valid username, and a password of at least 12 characters are required."},422);let I=a.store.inspectInvitationToken(p);if(!I||I.state!=="pending")return g({ok:!1,error:I?`Invitation is ${I.state}`:"Invitation is invalid"},I?409:404);let A=Gt(Tt(t),v),E=G.getIdentityByUsername(v);if(A&&!cr(b,E?.passwordHash??A.passwordHash))return g({ok:!1,error:"That username already exists; enter its current password to continue."},401);let _=G.getIdentityByEmail(I.email);if(_&&_.id!==E?.id)return g({ok:!1,error:"This invitation belongs to an existing account. Sign in with that account or ask an owner to resend it."},409);let z=Mo(t,{username:v,password:A?void 0:b,name:typeof l.name==="string"?l.name:void 0,email:I.email,sites:A?.sites??{}}),L=Ye(a.store,z.user);try{let ce=a.store.acceptInvitation(p,L.id),W=E?G.setVerifiedEmail(E.id,ce.invitation.email):G.createIdentity({actorId:L.id,username:z.user.username,email:ce.invitation.email,emailVerified:!0,passwordHash:z.user.passwordHash}),ne=Yo(W.id,f,ue.requestIP(f)?.address??"unknown");return de(),g({ok:!0,user:Hi(z.user),organization:a.organization,membership:ce.membership},200,{"set-cookie":Wi(ne.token,{secure:Jr,maxAgeMs:nn})})}catch(ce){if(!A)Ru(t,z.user.username);let W=ce instanceof Error?ce.message:"Invitation could not be accepted.";return g({ok:!1,error:W},W.includes("expired")||W.includes("revoked")||W.includes("accepted")?409:404)}}if(S.pathname==="/api/auth/password-reset/request"&&f.method==="POST"){let l=await x(f),p=String(l.identifier??"").trim().toLowerCase(),v=ue.requestIP(f)?.address??"unknown",b=uc.check(p,v),I=p.includes("@")?G.getIdentityByEmail(p):G.getIdentityByUsername(p);if(b.allowed)uc.recordFailure(p,v);if(b.allowed&&I?.email&&I.emailVerifiedAt&&!I.disabledAt){G.revokeActionTokens(I.id,"password_reset");let A=G.createActionToken(I.id,"password_reset"),E=`${S.origin}/reset-password?token=${encodeURIComponent(A.token)}`,_=await fo(o,{to:I.email,subject:"Reset your ts-cloud password",text:`Reset your ts-cloud password: ${E}
|
|
679
|
+
|
|
680
|
+
This link expires in one hour and can be used once.`});a.store.appendEvent({organizationId:a.organization.id,actorId:I.actorId,type:"auth.password_reset.requested",payload:{delivered:_}})}return g({ok:!0,message:"If that account has a verified email, a reset link has been sent."},202)}if(S.pathname==="/api/auth/password-reset/complete"&&f.method==="POST"){let l=await x(f),p=String(l.token??"").trim(),v=String(l.password??"");if(!p||v.length<12)return g({ok:!1,error:"A valid reset token and password of at least 12 characters are required."},422);try{let b=G.consumeActionToken(p,"password_reset"),I=fn(v),A=G.updatePassword(b.identityId,I);return Ja(t,A.username,I),a.store.appendEvent({organizationId:a.organization.id,actorId:A.actorId,type:"auth.password_reset.completed"}),g({ok:!0,message:"Password changed. Sign in again."},200,{"set-cookie":Wa({secure:Jr})})}catch(b){let I=b instanceof Error?b.message:"Password reset failed.";return g({ok:!1,error:I.replace("Action token","Reset link")},I.includes("consumed")||I.includes("expired")?409:404)}}if(S.pathname==="/api/login"&&f.method==="POST"){let l=await x(f),p=String(l.username??"").trim(),v=String(l.password??""),b=ue.requestIP(f)?.address??"unknown",I=Go.check(p,b);if(!I.allowed)return g({ok:!1,error:`Too many failed attempts. Try again in ${Math.ceil((I.retryAfterSeconds??0)/60)} minute(s).`},429,{"retry-after":String(I.retryAfterSeconds??60)});let A=Gt(Tt(t),p),E=G.getIdentityByUsername(p),_=E?.passwordHash??A?.passwordHash??v_;if(!(cr(v,_)&&!!A&&!!E&&!E.disabledAt))return Go.recordFailure(p,b),g({ok:!1,error:"Incorrect username or password."},401);if(gv(G,a,E))return g({ok:!1,error:"Single sign-on is required for this account."},403);Go.recordSuccess(p,b);let L=E,ce=L.requiresPasswordUpgrade||Ey(L.passwordHash);if(ce){let ne=fn(v);L=G.rehashPassword(L.id,ne),Ja(t,L.username,ne)}if(G.recordLogin(L.id),G.getMfaFactor(L.id)?.state==="active"){let ne=G.createMfaChallenge(L.id,"login");return a.store.appendEvent({organizationId:a.organization.id,actorId:L.actorId,type:"auth.mfa.challenge.created",payload:{purpose:"login"}}),g({ok:!0,mfaRequired:!0,challengeToken:ne.token,passwordUpgraded:ce})}let W=Yo(L.id,f,b);return a.store.appendEvent({organizationId:a.organization.id,actorId:L.actorId,type:"auth.login.succeeded",payload:{method:"local"}}),g({ok:!0,user:Hi(A),passwordUpgraded:ce},200,{"set-cookie":Wi(W.token,{secure:Jr,maxAgeMs:nn})})}if(S.pathname==="/api/auth/mfa/complete"&&f.method==="POST"){let l=await x(f),p=String(l.challengeToken??"").trim(),v=String(l.code??"").trim(),b=ue.requestIP(f)?.address??"unknown",A=G.inspectMfaChallengeToken(p,"login")?.identityId??"unknown-mfa",E=Qo.check(A,b);if(!E.allowed)return g({ok:!1,error:"Too many MFA attempts. Try again later."},429,{"retry-after":String(E.retryAfterSeconds??60)});try{let _=G.completeMfaChallenge(p,v,"login");Qo.recordSuccess(A,b);let z=new Date().toISOString(),L=G.createSession({identityId:_.identity.id,userAgent:lp(f),networkHint:pc(b),mfaAt:z,recentAuthAt:z});return a.store.appendEvent({organizationId:a.organization.id,actorId:_.identity.actorId,type:"auth.mfa.succeeded",payload:{purpose:"login",method:_.method}}),g({ok:!0},200,{"set-cookie":Wi(L.token,{secure:Jr,maxAgeMs:nn})})}catch{return Qo.recordFailure(A,b),g({ok:!1,error:"Authenticator or recovery code is incorrect."},401)}}if(S.pathname==="/api/logout"&&f.method==="POST"){let l=ze.resolveSession(f);if(l)G.revokeSession(l.identityId,l.id);let p=Wa({secure:Jr});if(f.headers.get("accept")?.includes("text/html"))return new Response(null,{status:302,headers:{location:"/login","set-cookie":p}});return g({ok:!0},200,{"set-cookie":p})}if(S.pathname==="/login"){let l=G.listOidcProviders(a.organization.id).map((p)=>({slug:p.slug,name:p.name}));return new Response(fv(y?.mode==="serverless",l),{headers:{"content-type":"text/html; charset=utf-8"}})}if(S.pathname==="/forgot-password"||S.pathname==="/reset-password")return new Response(hv(S.pathname==="/reset-password"?"reset":"request"),{headers:{"content-type":"text/html; charset=utf-8"}});if(S.pathname==="/accept-invitation")return Cb(me,S.pathname);let B=ze.resolveUser(f);if(!B){if(!S.pathname.startsWith("/api/")&&f.headers.get("accept")?.includes("text/html"))return new Response(null,{status:302,headers:{location:"/login"}});return g({ok:!1,error:"Sign in to continue."},401)}let qt=je(B,V);if(S.pathname==="/api/me"){let l=a.store.getActorByExternalId("user",`dashboard:${B.username.toLowerCase()}`),p=l?a.store.getMembershipForActor(a.organization.id,l.id):void 0,v=a.store.resolveAuthorizationTarget(a.organization.id,p?.scope??{type:"project",id:a.project.id})??a.store.resolveAuthorizationTarget(a.organization.id,{type:"project",id:a.project.id});return g({ok:!0,user:Hi(B),authEnabled:K,organization:a.organization,membership:p,capabilities:Wo({membership:p,grants:p?a.store.listGrants(p.id):[],target:v})})}if(S.pathname.startsWith("/api/")){let l=await uv(f,S.pathname),p=ze.check(f,S.pathname,B,l);if(!p.ok)return g({ok:!1,error:p.error},p.status??403);if(K&&P_.has(`${f.method.toUpperCase()} ${S.pathname}`)){let v=ze.resolveSession(f);if(!v||!G.isRecentlyAuthenticated(v))return g({ok:!1,error:"Recent authentication is required for this change.",stepUpRequired:!0},401)}}if(S.pathname==="/api/auth/security"&&f.method==="GET"){let l=re(B),p=l.actor?G.getIdentityByActor(l.actor.id):void 0,v=ze.resolveSession(f);return g({identity:p?{username:p.username,email:p.email,emailVerifiedAt:p.emailVerifiedAt,requiresPasswordUpgrade:p.requiresPasswordUpgrade,lastLoginAt:p.lastLoginAt}:void 0,currentSessionId:v?.id,sessions:p?G.listSessions(p.id,{includeInactive:!0}):[],mfa:p?{factor:G.getMfaFactor(p.id),recoveryCodesRemaining:G.remainingRecoveryCodes(p.id)}:void 0})}if(S.pathname==="/api/auth/oidc/providers"&&f.method==="GET")return g({providers:G.listOidcProviders(a.organization.id,{includeDisabled:!0}),callbackOrigin:fe,callbackPattern:fe?`${fe}/auth/oidc/{slug}/callback`:void 0,localOwnerRecovery:!0});if(S.pathname==="/api/auth/oidc/providers"&&f.method==="POST"){let l=await x(f),p=re(B),v=p.actor?G.getIdentityByActor(p.actor.id):void 0,b=l.enforceSso===!0;if(b&&(!v?.emailVerifiedAt||G.remainingRecoveryCodes(v.id)<1))return g({ok:!1,error:"Verify the owner email and generate MFA recovery codes before enforcing SSO."},409);try{let I=rc(l.defaultRole),A=G.upsertOidcProvider({id:typeof l.id==="string"?l.id:void 0,organizationId:a.organization.id,slug:String(l.slug??""),name:String(l.name??""),issuer:String(l.issuer??""),clientId:String(l.clientId??""),clientSecret:typeof l.clientSecret==="string"&&l.clientSecret?l.clientSecret:void 0,scopes:Array.isArray(l.scopes)?l.scopes.map(String):void 0,allowedDomains:Array.isArray(l.allowedDomains)?l.allowedDomains.map(String):[],defaultRole:I&&I!=="owner"?I:void 0,enabled:l.enabled!==!1,enforceSso:b});return a.store.appendEvent({organizationId:a.organization.id,actorId:p.actor?.id,type:"auth.oidc.provider.configured",payload:{providerId:A.id,issuer:A.issuer,enabled:A.enabled,enforceSso:A.enforceSso}}),g({ok:!0,provider:A})}catch(I){return g({ok:!1,error:I instanceof Error?I.message:"OIDC provider could not be saved."},422)}}if(S.pathname==="/api/auth/oidc/providers"&&f.method==="PATCH"){let l=await x(f),p=G.getOidcProvider(String(l.id??""));if(!p||p.organizationId!==a.organization.id)return g({ok:!1,error:"OIDC provider was not found."},404);let v=re(B),b=G.setOidcProviderEnabled(p.id,l.enabled===!0);return a.store.appendEvent({organizationId:a.organization.id,actorId:v.actor?.id,type:b.enabled?"auth.oidc.provider.enabled":"auth.oidc.provider.disabled",payload:{providerId:p.id}}),g({ok:!0,provider:b})}if(S.pathname==="/api/automation"&&f.method==="GET"){let l=be.listServiceAccounts(a.organization.id,{includeDisabled:!0}).map((p)=>{let v=a.store.getMembershipForActor(a.organization.id,p.actorId),b=p.createdByActorId?a.store.getActor(p.createdByActorId):void 0,I=be.listTokens(p.id,{includeInactive:!0}).map((A)=>({...A,createdBy:A.createdByActorId?a.store.getActor(A.createdByActorId):void 0}));return{account:p,createdBy:b,membership:v,tokens:I}});return g({accounts:l,apiBaseUrl:`${S.origin}/api/v1`,openApiUrl:`${S.origin}/api/v1/openapi.json`,tokenEnvironmentVariable:"TS_CLOUD_API_TOKEN"})}if(S.pathname==="/api/automation/service-accounts"&&f.method==="POST"){let l=await x(f),p=re(B),v=rc(l.roleTemplate),b=Vo(l);if(!p.actor||!v||v==="owner"||!b)return g({ok:!1,error:"A non-owner role and valid organization scope are required."},422);try{let I=be.createServiceAccount({organizationId:a.organization.id,slug:String(l.slug??""),name:String(l.name??""),description:typeof l.description==="string"?l.description:void 0,roleTemplate:v,scope:b,createdByActorId:p.actor.id});return g({ok:!0,...I},201)}catch(I){return g({ok:!1,error:I instanceof Error?I.message:"Service account could not be created."},422)}}if(S.pathname==="/api/automation/service-accounts"&&f.method==="PATCH"){let l=await x(f),p=re(B),v=be.getServiceAccount(String(l.id??""));if(!v||v.organizationId!==a.organization.id)return g({ok:!1,error:"Service account was not found."},404);return g({ok:!0,account:be.disableServiceAccount(v.id,p.actor?.id)})}if(S.pathname==="/api/automation/tokens"&&f.method==="POST"){let l=await x(f),p=re(B),v=be.getServiceAccount(String(l.serviceAccountId??"")),b=Vo(l);if(!p.actor||!v||v.organizationId!==a.organization.id||!b||!Array.isArray(l.capabilities))return g({ok:!1,error:"Service account, explicit capabilities, and valid scope are required."},422);try{let I=be.createToken({serviceAccountId:v.id,name:String(l.name??"API token"),capabilities:l.capabilities.map(String),scope:b,expiresAt:typeof l.expiresAt==="string"?l.expiresAt:void 0,createdByActorId:p.actor.id});return g({ok:!0,token:I.token,secret:I.secret,revealOnce:!0},201)}catch(I){return g({ok:!1,error:I instanceof Error?I.message:"API token could not be created."},422)}}if(S.pathname==="/api/automation/tokens/rotate"&&f.method==="POST"){let l=await x(f),p=re(B),v=be.getToken(String(l.id??"")),b=v?be.getServiceAccount(v.serviceAccountId):void 0;if(!p.actor||!v||b?.organizationId!==a.organization.id)return g({ok:!1,error:"API token was not found."},404);try{let I=be.rotateToken(v.id,p.actor.id);return g({ok:!0,token:I.token,secret:I.secret,revealOnce:!0,overlap:!0},201)}catch(I){return g({ok:!1,error:I instanceof Error?I.message:"API token could not be rotated."},409)}}if(S.pathname==="/api/automation/tokens"&&f.method==="DELETE"){let l=await x(f),p=re(B),v=be.getToken(String(l.id??"")),b=v?be.getServiceAccount(v.serviceAccountId):void 0;if(!v||b?.organizationId!==a.organization.id)return g({ok:!1,error:"API token was not found."},404);return g({ok:!0,token:be.revokeToken(v.id,p.actor?.id)})}if(S.pathname==="/api/onboarding"&&f.method==="GET"){let l=oe.listConnections(a.organization.id);return g({drafts:ft.list(a.project.id),artifacts:ni.list(a.project.id),registries:dr.list(a.organization.id),sourceConnections:l,repositories:l.flatMap((p)=>oe.listRepositories(p.id)),project:{id:a.project.id,slug:a.project.slug,name:a.project.name},environments:[...a.environments.values()].map((p)=>({id:p.id,slug:p.slug,name:p.name,kind:p.kind,region:p.region})),resources:a.store.listResources(a.project.id).filter((p)=>p.kind==="application").map((p)=>({id:p.id,slug:p.slug,name:p.name,environmentId:p.environmentId}))})}if(S.pathname==="/api/onboarding/detect"&&f.method==="POST"){let l=await x(f);try{if(l.source?.kind==="git"){let b=oe.getConnection(String(l.source.connectionId??"")),I=oe.getRepository(String(l.source.repositoryId??""));if(!b||b.organizationId!==a.organization.id||!I||I.connectionId!==b.id)throw Error("Authorized Git repository was not found");let A=typeof l.source.deployKeyId==="string"?oe.getDeployKey(l.source.deployKeyId):void 0;if(A&&A.connectionId!==b.id)throw Error("Deploy key does not belong to this connection");let E=Vu(Te(ic(),"ts-cloud-onboarding-git-"));try{let _=await Fc({remote:I.cloneUrl,destination:Te(E,"checkout"),ref:String(l.source.ref??I.defaultBranch),sparsePaths:Array.isArray(l.source.sparsePaths)?l.source.sparsePaths.map(String):void 0,binding:{id:"detection",projectId:a.project.id,connectionId:b.id,repositoryId:I.id,repositoryFullName:I.fullName,defaultBranch:I.defaultBranch,monorepoRoot:String(l.source.monorepoRoot??"."),includePaths:[],excludePaths:[],submodules:l.source.submodules===!0,cloneDepth:1,deployKeyId:A?.id,autoDeploy:!1,pullRequestPreviews:!1,status:"active",version:1,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}},{credential:oe.getCredential(b.id),deployKey:A?{...A,privateKey:oe.getDeployPrivateKey(A.id)}:void 0,timeoutMs:120000});return g({ok:!0,commitSha:_.commitSha,candidates:hi(kc(_.directory))})}finally{ri(E,{recursive:!0,force:!0})}}if(Array.isArray(l.files)){if(l.files.length>1e4)throw Error("Detection file-count limit exceeded");let b=l.files.map((I)=>({path:String(I.path??""),size:Number(I.size??0),content:typeof I.content==="string"?I.content.slice(0,262144):void 0}));return g({ok:!0,candidates:hi(b)})}let p=a_(t,String(l.root??".")),v=s_(t,p);if(v===".."||v.startsWith(`..${c_}`))throw Error("Detection root must stay inside the project");return g({ok:!0,candidates:hi(kc(p))})}catch(p){return g({ok:!1,error:p instanceof Error?p.message:"Application detection failed."},422)}}if(S.pathname==="/api/onboarding/plan"&&f.method==="POST"){let l=await x(f);try{return g({ok:!0,plan:Yt(l.draft,Array.isArray(l.suppliedSecretNames)?l.suppliedSecretNames.map(String):[])})}catch(p){return g({ok:!1,error:p instanceof Error?p.message:"Application plan could not be generated."},422)}}if(S.pathname==="/api/onboarding/drafts"&&f.method==="POST"){let l=await x(f),p=re(B);try{return g({ok:!0,draft:ft.create({organizationId:a.organization.id,projectId:a.project.id,name:String(l.name??l.draft?.name??"Application draft"),draft:{...l.draft,projectId:a.project.id},step:l.step,suppliedSecretNames:Array.isArray(l.suppliedSecretNames)?l.suppliedSecretNames.map(String):[],actorId:p.actor?.id})},201)}catch(v){return g({ok:!1,error:v instanceof Error?v.message:"Application draft could not be saved."},422)}}if(S.pathname==="/api/onboarding/drafts"&&f.method==="PATCH"){let l=await x(f),p=re(B),v=ft.get(String(l.id??""));if(!v||v.projectId!==a.project.id)return g({ok:!1,error:"Application draft was not found."},404);try{return g({ok:!0,draft:ft.update(v.id,Number(l.version),{draft:{...l.draft,projectId:a.project.id},step:l.step,suppliedSecretNames:Array.isArray(l.suppliedSecretNames)?l.suppliedSecretNames.map(String):void 0,actorId:p.actor?.id})})}catch(b){return g({ok:!1,error:b instanceof Error?b.message:"Application draft could not be updated."},409)}}if(S.pathname==="/api/onboarding/artifacts"&&f.method==="POST"){let l=re(B);if(Number(f.headers.get("content-length")??0)>104857600)return g({ok:!1,error:"Artifact exceeds the 100 MB upload limit."},413);try{let v=new Uint8Array(await f.arrayBuffer());return g({ok:!0,artifact:ni.create({organizationId:a.organization.id,projectId:a.project.id,filename:f.headers.get("x-artifact-filename")??"application.zip",bytes:v,actorId:l.actor?.id})},201)}catch(v){return g({ok:!1,error:v instanceof Error?v.message:"Artifact could not be inspected."},422)}}if(S.pathname==="/api/onboarding/registries"&&f.method==="POST"){let l=await x(f),p=re(B);try{return g({ok:!0,registry:dr.create({organizationId:a.organization.id,provider:l.provider,name:String(l.name??"Container registry"),host:String(l.host??""),credential:l.token||l.password?{username:typeof l.username==="string"?l.username:void 0,password:typeof l.password==="string"?l.password:void 0,token:typeof l.token==="string"?l.token:void 0}:void 0,credentialExpiresAt:typeof l.credentialExpiresAt==="string"?l.credentialExpiresAt:void 0,actorId:p.actor?.id})},201)}catch(v){return g({ok:!1,error:v instanceof Error?v.message:"Registry connection could not be created."},422)}}if(S.pathname==="/api/onboarding/registries"&&f.method==="PATCH"){let l=await x(f),p=re(B),v=dr.get(String(l.id??""));if(!v||v.organizationId!==a.organization.id)return g({ok:!1,error:"Registry connection was not found."},404);try{if(l.action==="test")return g({ok:!0,registry:await dr.test(v.id,{image:typeof l.image==="string"?l.image:void 0})});if(l.action==="rotate")return g({ok:!0,registry:dr.rotate(v.id,{username:typeof l.username==="string"?l.username:void 0,password:typeof l.password==="string"?l.password:void 0,token:typeof l.token==="string"?l.token:void 0},{expiresAt:typeof l.expiresAt==="string"?l.expiresAt:void 0,actorId:p.actor?.id})});return g({ok:!1,error:"Registry action must be test or rotate."},422)}catch(b){return g({ok:!1,error:b instanceof Error?b.message:"Registry connection could not be updated."},422)}}if(S.pathname==="/api/onboarding/registries"&&f.method==="DELETE"){let l=await x(f),p=re(B),v=dr.get(String(l.id??""));if(!v||v.organizationId!==a.organization.id)return g({ok:!1,error:"Registry connection was not found."},404);let b=ft.list(a.project.id).filter((I)=>I.input.source.kind==="image"&&I.input.source.registryConnectionId===v.id||I.input.build.kind==="prebuilt_image"&&I.input.build.registryConnectionId===v.id);if(l.preview===!0)return g({ok:!0,preview:!0,affectedDrafts:b});return g({ok:!0,registry:dr.disconnect(v.id,p.actor?.id),affectedDrafts:b})}if(S.pathname==="/api/onboarding/apply"&&f.method==="POST"){let l=await x(f),p=re(B);try{let v=ls({controlPlane:a.store,drafts:ft,draftId:String(l.id??""),expectedVersion:Number(l.version),confirmEnvironment:String(l.confirmEnvironment??""),actorId:p.actor?.id});return g({ok:!0,resource:v.resource,operation:v.operation,plan:v.plan},202)}catch(v){return g({ok:!1,error:v instanceof Error?v.message:"Application plan could not be applied."},422)}}if(S.pathname==="/api/sources"&&f.method==="GET"){let l=oe.listConnections(a.organization.id);return g({connections:l,bindings:oe.listBindings({projectId:a.project.id}),repositories:l.flatMap((p)=>oe.listRepositories(p.id)),deployKeys:l.flatMap((p)=>oe.listDeployKeys(p.id)),webhooks:l.flatMap((p)=>oe.listWebhooks(p.id)).map((p)=>({...p,deliveries:oe.listDeliveries(p.id,20)})),project:{id:a.project.id,slug:a.project.slug},environment:ar(a,String(V)),resources:a.store.listResources(a.project.id,ar(a,String(V)).environmentId).filter((p)=>p.kind==="application").map((p)=>({id:p.id,slug:p.slug,name:p.name}))})}if(S.pathname==="/api/sources/connections"&&f.method==="POST"){let l=await x(f),p=re(B),v=String(l.provider??"");if(!["github","gitlab","bitbucket","gitea","generic_https","generic_ssh"].includes(v))return g({ok:!1,error:"A supported Git provider is required."},422);try{let b=v==="github"&&(l.privateKey||l.appId)?{appId:typeof l.appId==="string"?l.appId:void 0,installationId:typeof l.installationId==="string"?l.installationId:void 0,privateKey:typeof l.privateKey==="string"?l.privateKey:void 0}:v!=="generic_ssh"&&l.token?{token:typeof l.token==="string"?l.token:void 0,username:typeof l.username==="string"?l.username:void 0}:void 0,I={github:"https://github.com",gitlab:"https://gitlab.com",bitbucket:"https://bitbucket.org",gitea:"https://gitea.com"},A,E,_;if(a.store.database.transaction(()=>{if(A=oe.createConnection({organizationId:a.organization.id,provider:v,name:String(l.name??v),host:String(l.host??I[v]??""),owner:typeof l.owner==="string"?l.owner:void 0,authKind:l.authKind,credential:b,grantedScopes:Array.isArray(l.grantedScopes)?l.grantedScopes.map(String):[],credentialExpiresAt:typeof l.credentialExpiresAt==="string"?l.credentialExpiresAt:void 0,createdByActorId:p.actor?.id}),typeof l.repositoryUrl==="string"&&typeof l.repositoryFullName==="string")E=oe.upsertRepository({connectionId:A.id,providerRepositoryId:`manual:${l.repositoryFullName}`,fullName:l.repositoryFullName,cloneUrl:l.repositoryUrl,defaultBranch:String(l.defaultBranch??"main"),visibility:"unknown",archived:!1,metadata:{source:"manual"}});if(v==="generic_ssh")_=oe.createDeployKey({connectionId:A.id,name:String(l.deployKeyName??"Repository deploy key"),publicKey:String(l.publicKey??""),privateKey:String(l.deployPrivateKey??""),host:String(l.sshHost??""),hostKey:String(l.hostKey??""),actorId:p.actor?.id})})(),l.test===!0)A=await zc(oe,A.id,E?.id);return g({ok:!0,connection:A,repository:E,deployKey:_},201)}catch(b){return g({ok:!1,error:b instanceof Error?b.message:"Source connection could not be created."},422)}}if(S.pathname==="/api/sources/connections"&&f.method==="PATCH"){let l=await x(f),p=re(B),v=oe.getConnection(String(l.id??""));if(!v||v.organizationId!==a.organization.id)return g({ok:!1,error:"Source connection was not found."},404);try{if(l.action==="test")return g({ok:!0,connection:await zc(oe,v.id,typeof l.repositoryId==="string"?l.repositoryId:void 0)});if(l.action==="rotate")return g({ok:!0,connection:oe.rotateCredential(v.id,{token:typeof l.token==="string"?l.token:void 0,username:typeof l.username==="string"?l.username:void 0,appId:typeof l.appId==="string"?l.appId:void 0,installationId:typeof l.installationId==="string"?l.installationId:void 0,privateKey:typeof l.privateKey==="string"?l.privateKey:void 0},{expiresAt:typeof l.expiresAt==="string"?l.expiresAt:void 0,actorId:p.actor?.id})});return g({ok:!1,error:"Connection action must be test or rotate."},422)}catch(b){return g({ok:!1,error:b instanceof Error?b.message:"Source connection could not be updated."},422)}}if(S.pathname==="/api/sources/connections"&&f.method==="DELETE"){let l=await x(f),p=re(B),v=oe.getConnection(String(l.id??""));if(!v||v.organizationId!==a.organization.id)return g({ok:!1,error:"Source connection was not found."},404);let b=oe.listBindings({connectionId:v.id,status:"active"});if(l.preview===!0)return g({ok:!0,preview:!0,affectedBindings:b});return g({ok:!0,...oe.disconnectConnection(v.id,p.actor?.id)})}if(S.pathname==="/api/sources/deploy-keys"&&f.method==="POST"){let l=await x(f),p=re(B),v=oe.getConnection(String(l.connectionId??""));if(!v||v.organizationId!==a.organization.id)return g({ok:!1,error:"Source connection was not found."},404);try{return g({ok:!0,deployKey:oe.createDeployKey({connectionId:v.id,name:String(l.name??"Repository deploy key"),publicKey:String(l.publicKey??""),privateKey:String(l.privateKey??""),host:String(l.host??""),hostKey:String(l.hostKey??""),actorId:p.actor?.id})},201)}catch(b){return g({ok:!1,error:b instanceof Error?b.message:"Deploy key could not be stored."},422)}}if(S.pathname==="/api/sources/deploy-keys"&&f.method==="DELETE"){let l=await x(f),p=re(B),v=oe.getDeployKey(String(l.id??"")),b=v?oe.getConnection(v.connectionId):void 0;if(!v||!b||b.organizationId!==a.organization.id)return g({ok:!1,error:"Deploy key was not found."},404);let I=oe.listBindings({connectionId:b.id}).filter((A)=>A.deployKeyId===v.id);if(l.preview===!0)return g({ok:!0,preview:!0,affectedBindings:I});return g({ok:!0,...oe.revokeDeployKey(v.id,p.actor?.id)})}if(S.pathname==="/api/sources/repositories/sync"&&f.method==="POST"){let l=await x(f),p=oe.getConnection(String(l.connectionId??""));if(!p||p.organizationId!==a.organization.id)return g({ok:!1,error:"Source connection was not found."},404);try{return g({ok:!0,repositories:await gs(oe,String(l.connectionId??""),{search:typeof l.search==="string"?l.search:void 0})})}catch(v){return g({ok:!1,error:v instanceof Error?v.message:"Repositories could not be synchronized."},422)}}if(S.pathname==="/api/sources/references"&&f.method==="GET"){let l=oe.getConnection(String(S.searchParams.get("connectionId")??""));if(!l||l.organizationId!==a.organization.id)return g({ok:!1,error:"Source connection was not found."},404);try{return g(await fs(oe,{connectionId:String(S.searchParams.get("connectionId")??""),repository:String(S.searchParams.get("repository")??""),repositoryId:S.searchParams.get("repositoryId")??void 0,deployKeyId:S.searchParams.get("deployKeyId")??void 0,type:S.searchParams.get("type")==="tags"?"tags":"branches",cursor:S.searchParams.get("cursor")??void 0}))}catch(p){return g({ok:!1,error:p instanceof Error?p.message:"References could not be listed."},422)}}if(S.pathname==="/api/sources/bindings"&&f.method==="POST"){let l=await x(f),p=re(B),v=ar(a,String(V)),b=oe.getConnection(String(l.connectionId??""));if(!b||b.organizationId!==a.organization.id)return g({ok:!1,error:"Source connection was not found."},404);try{return g({ok:!0,binding:oe.createBinding({projectId:a.project.id,environmentId:v.environmentId,resourceId:typeof l.resourceId==="string"?l.resourceId:void 0,connectionId:String(l.connectionId??""),repositoryId:typeof l.repositoryId==="string"?l.repositoryId:void 0,repositoryFullName:String(l.repositoryFullName??""),defaultBranch:String(l.defaultBranch??"main"),branchRule:typeof l.branchRule==="string"?l.branchRule:void 0,tagRule:typeof l.tagRule==="string"?l.tagRule:void 0,monorepoRoot:String(l.monorepoRoot??"."),includePaths:Array.isArray(l.includePaths)?l.includePaths.map(String):[],excludePaths:Array.isArray(l.excludePaths)?l.excludePaths.map(String):[],submodules:l.submodules===!0,cloneDepth:l.cloneDepth?Number(l.cloneDepth):void 0,deployKeyId:typeof l.deployKeyId==="string"&&l.deployKeyId?l.deployKeyId:void 0,autoDeploy:l.autoDeploy!==!1,pullRequestPreviews:l.pullRequestPreviews!==!1,actorId:p.actor?.id})},201)}catch(I){return g({ok:!1,error:I instanceof Error?I.message:"Source binding could not be created."},422)}}if(S.pathname==="/api/sources/bindings"&&f.method==="PATCH"){let l=await x(f),p=re(B),v=oe.getBinding(String(l.id??""));if(!v||v.projectId!==a.project.id)return g({ok:!1,error:"Source binding was not found."},404);try{return g({ok:!0,binding:oe.updateBinding(v.id,Number(l.version),{defaultBranch:l.defaultBranch,branchRule:l.branchRule,tagRule:l.tagRule,monorepoRoot:l.monorepoRoot,includePaths:l.includePaths,excludePaths:l.excludePaths,submodules:l.submodules,cloneDepth:l.cloneDepth,deployKeyId:l.deployKeyId,autoDeploy:l.autoDeploy,pullRequestPreviews:l.pullRequestPreviews,status:l.status,disabledReason:l.disabledReason,actorId:p.actor?.id})})}catch(b){return g({ok:!1,error:b instanceof Error?b.message:"Source binding could not be updated."},409)}}if(S.pathname==="/api/sources/webhooks"&&f.method==="POST"){let l=await x(f),p=oe.getConnection(String(l.connectionId??""));if(!p||p.organizationId!==a.organization.id)return g({ok:!1,error:"Source connection was not found."},404);try{let v=oe.createWebhook({connectionId:String(l.connectionId??""),repositoryId:typeof l.repositoryId==="string"?l.repositoryId:void 0,repositoryFullName:String(l.repositoryFullName??""),events:Array.isArray(l.events)?l.events.map(String):void 0,secret:typeof l.secret==="string"?l.secret:void 0}),b=process.env.TS_CLOUD_WEBHOOK_BASE_URL?.trim()||fe,I=b?bi(b,v.webhook):void 0,A=l.reconcile!==!1&&b?await po(oe,v.webhook.id,b):v.webhook;return g({ok:!0,webhook:A,endpoint:I,endpointRevealOnce:!0},201)}catch(v){return g({ok:!1,error:v instanceof Error?v.message:"Source webhook could not be created."},422)}}if(S.pathname==="/api/sources/webhooks"&&f.method==="PATCH"){let l=await x(f),p=process.env.TS_CLOUD_WEBHOOK_BASE_URL?.trim()||fe,v=oe.getWebhook(String(l.id??"")),b=v?oe.getConnection(v.connectionId):void 0;if(!v||!b||b.organizationId!==a.organization.id)return g({ok:!1,error:"Source webhook was not found."},404);if(!p)return g({ok:!1,error:"Set TS_CLOUD_WEBHOOK_BASE_URL to reconcile provider webhooks."},422);try{return g({ok:!0,webhook:await po(oe,String(l.id??""),p)})}catch(I){return g({ok:!1,error:I instanceof Error?I.message:"Source webhook could not be reconciled."},422)}}if(S.pathname==="/api/sources/webhooks"&&f.method==="DELETE"){let l=await x(f),p=oe.getWebhook(String(l.id??"")),v=p?oe.getConnection(p.connectionId):void 0;if(!p||!v||v.organizationId!==a.organization.id)return g({ok:!1,error:"Source webhook was not found."},404);try{return g({ok:!0,webhook:await Vm(oe,String(l.id??""))})}catch(b){return g({ok:!1,error:b instanceof Error?b.message:"Source webhook could not be removed."},422)}}if(S.pathname==="/api/security/posture"&&f.method==="GET"){let l=ar(a,String(V)),p=ge.listFindings({...l,limit:500});return g({scope:l,summary:ge.summary(l.organizationId,l.projectId,l.environmentId),findings:p,scans:ge.listScanRuns({...l,limit:100}),policies:ge.listPolicies(l.organizationId).filter((v)=>!v.environmentId||v.environmentId===l.environmentId),waivers:p.flatMap((v)=>ge.listWaivers(v.id)),decisions:ge.listDecisions(l.environmentId,50),actors:a.store.listMemberships(a.organization.id).map((v)=>a.store.getActor(v.actorId)).filter(Boolean)})}if(S.pathname==="/api/security/export"&&f.method==="GET")return g(ge.exportPosture(a.organization.id));if(S.pathname==="/api/security/scan"&&f.method==="POST"){let l=ar(a,String(V)),p=await new Qn(ge).run(new $o,{...l,artifactRoot:t}),v=Na(ge,l,Le??{});return g({ok:!0,source:p,host:v,summary:ge.summary(l.organizationId,l.projectId,l.environmentId)})}if(S.pathname==="/api/security/review"&&f.method==="POST")try{let l=ar(a,String(V));return g({ok:!0,...ja(ge,{scope:l,desiredConfigHash:a.project.desiredConfigHash})})}catch(l){return g({ok:!1,error:l instanceof Error?l.message:"Security change review failed."},409)}if(S.pathname==="/api/security/policies"&&f.method==="POST"){let l=await x(f),p=re(B);if(!p.actor)return g({ok:!1,error:"An organization actor is required."},403);try{let v=ge.createPolicy({organizationId:a.organization.id,environmentId:l.environmentId===null?void 0:String(l.environmentId??ar(a,String(V)).environmentId),name:String(l.name??""),scannerFailMode:l.scannerFailMode==="open"?"open":"closed",requiredScanners:Array.isArray(l.requiredScanners)?l.requiredScanners.map(String):[],rules:Array.isArray(l.rules)?l.rules.map((b)=>({minimumSeverity:String(b.minimumSeverity),action:String(b.action),scannerId:b.scannerId?String(b.scannerId):void 0})):[],actorId:p.actor.id});return g({ok:!0,policy:v},201)}catch(v){return g({ok:!1,error:v instanceof Error?v.message:"Security policy could not be created."},422)}}if(S.pathname==="/api/security/policies"&&f.method==="PATCH"){let l=await x(f),p=re(B),v=ge.getPolicy(String(l.id??""));if(!p.actor||!v||v.organizationId!==a.organization.id)return g({ok:!1,error:"Security policy was not found."},404);try{return g({ok:!0,policy:ge.updatePolicy(v.id,Number(l.version),{name:typeof l.name==="string"?l.name:void 0,scannerFailMode:l.scannerFailMode==="open"||l.scannerFailMode==="closed"?l.scannerFailMode:void 0,requiredScanners:Array.isArray(l.requiredScanners)?l.requiredScanners.map(String):void 0,rules:Array.isArray(l.rules)?l.rules.map((b)=>({minimumSeverity:String(b.minimumSeverity),action:String(b.action),scannerId:b.scannerId?String(b.scannerId):void 0})):void 0,enabled:typeof l.enabled==="boolean"?l.enabled:void 0,actorId:p.actor.id})})}catch(b){return g({ok:!1,error:b instanceof Error?b.message:"Security policy could not be updated."},409)}}if(S.pathname==="/api/security/waivers"&&f.method==="POST"){let l=await x(f),p=re(B);if(!p.actor)return g({ok:!1,error:"An organization actor is required."},403);try{return g({ok:!0,waiver:ge.createWaiver({findingId:String(l.findingId??""),policyId:typeof l.policyId==="string"?l.policyId:void 0,reason:String(l.reason??""),referenceUrl:typeof l.referenceUrl==="string"?l.referenceUrl:void 0,expiresAt:String(l.expiresAt??""),actorId:p.actor.id})},201)}catch(v){return g({ok:!1,error:v instanceof Error?v.message:"Security waiver could not be created."},422)}}if(S.pathname==="/api/security/waivers"&&f.method==="DELETE"){let l=await x(f),p=re(B);if(!p.actor)return g({ok:!1,error:"An organization actor is required."},403);try{return g({ok:!0,waiver:ge.revokeWaiver(String(l.id??""),p.actor.id)})}catch(v){return g({ok:!1,error:v instanceof Error?v.message:"Security waiver could not be revoked."},404)}}if(S.pathname==="/api/security/findings"&&f.method==="PATCH"){let l=await x(f),p=re(B),v=ge.getFinding(String(l.id??""));if(!p.actor||!v||v.organizationId!==a.organization.id)return g({ok:!1,error:"Security finding was not found."},404);try{let b=l.action==="acknowledge"?ge.acknowledgeFinding(v.id,p.actor.id):ge.assignFinding(v.id,typeof l.ownerActorId==="string"&&l.ownerActorId?l.ownerActorId:void 0,p.actor.id);return g({ok:!0,finding:b})}catch(b){return g({ok:!1,error:b instanceof Error?b.message:"Security finding could not be updated."},422)}}if(S.pathname==="/api/security/comments"&&f.method==="POST"){let l=await x(f),p=re(B);if(!p.actor)return g({ok:!1,error:"An organization actor is required."},403);try{return g({ok:!0,comment:ge.addComment({findingId:String(l.findingId??""),actorId:p.actor.id,body:String(l.body??""),referenceUrl:typeof l.referenceUrl==="string"?l.referenceUrl:void 0})},201)}catch(v){return g({ok:!1,error:v instanceof Error?v.message:"Comment could not be saved."},422)}}if(S.pathname==="/api/auth/sessions"&&f.method==="GET"){let l=ze.resolveSession(f);return g({currentSessionId:l?.id,sessions:l?G.listSessions(l.identityId,{includeInactive:!0}):[]})}if(S.pathname==="/api/auth/sessions"&&f.method==="DELETE"){let l=await x(f),p=ze.resolveSession(f);if(!p)return g({ok:!1,error:"Sign in again to manage sessions."},401);let v=String(l.id??""),b=G.revokeSession(p.identityId,v),I=v===p.id&&b?{"set-cookie":Wa({secure:Jr})}:void 0;return g({ok:b,signedOut:v===p.id&&b},b?200:404,I)}if(S.pathname==="/api/auth/sessions/revoke-others"&&f.method==="POST"){let l=ze.resolveSession(f);if(!l)return g({ok:!1,error:"Sign in again to manage sessions."},401);return g({ok:!0,revoked:G.revokeOtherSessions(l.identityId,l.id)})}if(S.pathname==="/api/auth/password/change"&&f.method==="POST"){let l=await x(f),p=String(l.currentPassword??""),v=String(l.password??""),b=re(B),I=b.actor?G.getIdentityByActor(b.actor.id):void 0;if(!I||!cr(p,I.passwordHash))return g({ok:!1,error:"Current password is incorrect."},401);if(v.length<12)return g({ok:!1,error:"New password must be at least 12 characters."},422);if(cr(v,I.passwordHash))return g({ok:!1,error:"Choose a different password."},409);let A=fn(v),E=G.updatePassword(I.id,A);Ja(t,E.username,A);let _=Yo(E.id,f,ue.requestIP(f)?.address??"unknown");return a.store.appendEvent({organizationId:a.organization.id,actorId:E.actorId,type:"auth.password.changed"}),g({ok:!0,message:"Password changed and other sessions were signed out."},200,{"set-cookie":Wi(_.token,{secure:Jr,maxAgeMs:nn})})}if(S.pathname==="/api/auth/mfa/enroll"&&f.method==="POST"){let l=await x(f),p=ze.resolveSession(f),v=re(B),b=v.actor?G.getIdentityByActor(v.actor.id):void 0;if(!p||!b)return g({ok:!1,error:"Sign in again before enabling MFA."},401);if(!cr(String(l.password??""),b.passwordHash))return g({ok:!1,error:"Current password is incorrect."},401);try{let I=G.beginTotpEnrollment(b.id,{issuer:a.organization.name});return a.store.appendEvent({organizationId:a.organization.id,actorId:b.actorId,type:"auth.mfa.enrollment.started"}),g({factor:I.factor,secret:I.secret,uri:I.uri})}catch(I){return g({ok:!1,error:I instanceof Error?I.message:"MFA enrollment failed."},409)}}if(S.pathname==="/api/auth/mfa/verify"&&f.method==="POST"){let l=await x(f),p=ze.resolveSession(f),v=re(B),b=v.actor?G.getIdentityByActor(v.actor.id):void 0;if(!p||!b)return g({ok:!1,error:"Sign in again before enabling MFA."},401);try{let I=G.verifyTotpEnrollment(b.id,String(l.code??""));return G.markSessionStepUp(p.id,!0),a.store.appendEvent({organizationId:a.organization.id,actorId:b.actorId,type:"auth.mfa.enabled",payload:{recoveryCodeCount:I.recoveryCodes.length}}),g(I)}catch(I){return g({ok:!1,error:I instanceof Error?I.message:"MFA enrollment failed."},422)}}if(S.pathname==="/api/auth/mfa"&&f.method==="DELETE"){let l=await x(f),p=ze.resolveSession(f),v=re(B),b=v.actor?G.getIdentityByActor(v.actor.id):void 0;if(!p||!b||!cr(String(l.password??""),b.passwordHash))return g({ok:!1,error:"Current password is incorrect."},401);let I=G.verifyMfaCode(b.id,String(l.code??""));if(!I.valid||!I.method)return g({ok:!1,error:"Authenticator or recovery code is incorrect."},401);return G.disableMfa(b.id),G.revokeOtherSessions(b.id,p.id),G.markSessionStepUp(p.id),a.store.appendEvent({organizationId:a.organization.id,actorId:b.actorId,type:"auth.mfa.disabled",payload:{method:I.method}}),g({ok:!0})}if(S.pathname==="/api/auth/step-up"&&f.method==="POST"){let l=await x(f),p=ze.resolveSession(f),v=re(B),b=v.actor?G.getIdentityByActor(v.actor.id):void 0;if(!p||!b||!cr(String(l.password??""),b.passwordHash))return g({ok:!1,error:"Current password is incorrect."},401);let I=G.getMfaFactor(b.id);if(I?.state==="active"){if(!G.verifyMfaCode(b.id,String(l.code??"")).valid)return g({ok:!1,error:"Authenticator or recovery code is incorrect."},401)}let A=G.markSessionStepUp(p.id,I?.state==="active");return a.store.appendEvent({organizationId:a.organization.id,actorId:b.actorId,type:"auth.step_up.succeeded",payload:{mfa:I?.state==="active"}}),g({ok:!0,recentAuthAt:A.recentAuthAt})}if(S.pathname==="/api/terminal"){if(!M)return g({ok:!1,error:"The web terminal is disabled."},403);if(ue.upgrade(f))return;return oc("WebSocket upgrade failed",400)}if(S.pathname==="/api/health"){let l=a.store.health();return g({ok:!0,cwd:t,environment:V,environments:u,uiRoot:await Me(B,V),liveData:D.size>0,terminal:M,localPackage:import.meta.url.includes("/Code/Libraries/ts-cloud/"),controlPlane:{schemaVersion:l.schemaVersion,supportedSchemaVersion:l.supportedSchemaVersion,integrity:l.integrity,pendingRetryableOperations:l.pendingRetryableOperations}})}if(S.pathname==="/api/control-plane/operations"){let l=S.searchParams.get("state"),p=l&&["queued","running","succeeded","failed","cancelled","timed_out"].includes(l)?l:void 0;return g({operations:a.store.listOperations({projectId:a.project.id,state:p,kind:S.searchParams.get("kind")??void 0,limit:Number(S.searchParams.get("limit"))||100})})}if(S.pathname==="/api/queue"&&f.method==="GET"){let l=S.searchParams.get("state"),p=l&&["queued","running","succeeded","failed","cancelled","timed_out"].includes(l)?l:void 0,v=xe.list({projectId:a.project.id,state:p,limit:Number(S.searchParams.get("limit"))||250}).filter((b)=>ii(B,b.operation.id,"deployments:read")).map((b)=>{let I=b.operation.resourceId?a.store.getResource(b.operation.resourceId):void 0,A=b.operation.environmentId?a.store.listEnvironments(a.project.id).find((z)=>z.id===b.operation.environmentId):void 0,E=b.operation.actorId?a.store.getActor(b.operation.actorId):void 0,_=b.operation.input;return{...b,target:I?{id:I.id,name:I.name,slug:I.slug,kind:I.kind}:A?{id:A.id,name:A.name,slug:A.slug,kind:"environment"}:{id:a.project.id,name:a.project.name,slug:a.project.slug,kind:"project"},actor:E?{id:E.id,name:E.displayName,kind:E.kind}:void 0,commit:_.revision??_.source?.commitSha??null}});return g({operations:v,concurrency:xe.limits})}if(S.pathname==="/api/queue/logs"&&f.method==="GET"){let l=String(S.searchParams.get("id")??"");if(!ii(B,l,"deployments:read"))return g({ok:!1,error:"Operation was not found in this scope."},404);let p=xe.logs(l,{after:Number(S.searchParams.get("after"))||0,limit:Number(S.searchParams.get("limit"))||500});return g({entries:p,cursor:p.at(-1)?.sequence??(Number(S.searchParams.get("after"))||0),operation:a.store.getOperation(l)})}if(S.pathname==="/api/queue/stream"&&f.method==="GET"){let l=String(S.searchParams.get("id")??"");if(!ii(B,l,"deployments:read"))return g({ok:!1,error:"Operation was not found in this scope."},404);let p=f.headers.get("last-event-id")?.trim(),v=Number(p||S.searchParams.get("after")||0),b=new TextEncoder,I,A=!1,E=new ReadableStream({start(_){let z=()=>{if(A)return;let L=ze.resolveUser(f);if(!L||!ii(L,l,"deployments:read")){if(A=!0,I)clearInterval(I);_.close();return}let ce=xe.logs(l,{after:v,limit:500});for(let ne of ce)v=ne.sequence,_.enqueue(b.encode(`id: ${ne.sequence}
|
|
681
|
+
event: log
|
|
682
|
+
data: ${JSON.stringify(ne)}
|
|
683
|
+
|
|
684
|
+
`));let W=a.store.getOperation(l);if(W&&["succeeded","failed","cancelled","timed_out"].includes(W.state)&&xe.logs(l,{after:v,limit:1}).length===0){if(A=!0,I)clearInterval(I);_.enqueue(b.encode(`event: complete
|
|
685
|
+
data: ${JSON.stringify({state:W.state,cursor:v})}
|
|
686
|
+
|
|
687
|
+
`)),_.close()}};if(z(),!A)I=setInterval(z,500);f.signal.addEventListener("abort",()=>{if(A=!0,I)clearInterval(I);try{_.close()}catch{}},{once:!0})},cancel(){if(A=!0,I)clearInterval(I)}});return new Response(E,{headers:{"content-type":"text/event-stream","cache-control":"no-store","x-accel-buffering":"no"}})}if(S.pathname==="/api/queue/cancel"&&f.method==="POST"){let l=await x(f),p=String(l.id??"");if(!ii(B,p,"deployments:cancel"))return g({ok:!1,error:"Operation was not found or cannot be cancelled in this scope."},404);let v=Ye(a.store,B);try{return g({ok:!0,operation:xe.requestCancellation(p,v.id)})}catch(b){return g({ok:!1,error:b instanceof Error?b.message:"Cancellation failed."},409)}}if(S.pathname==="/api/queue/retry"&&f.method==="POST"){let l=await x(f),p=String(l.id??"");if(!ii(B,p,"deployments:create"))return g({ok:!1,error:"Operation was not found or cannot be retried in this scope."},404);let v=Ye(a.store,B);try{return g({ok:!0,operation:xe.retry(p,String(l.errorClass??"manual"),{delayMs:Number(l.delayMs)||0,actorId:v.id})})}catch(b){return g({ok:!1,error:b instanceof Error?b.message:"Retry failed."},409)}}if(S.pathname==="/api/queue/settings"&&f.method==="GET")return g({concurrency:xe.limits});if(S.pathname==="/api/queue/settings"&&f.method==="PATCH"){let l=await x(f);if(l.confirm!=="update queue limits")return g({ok:!1,error:'Type "update queue limits" to confirm production concurrency changes.'},409);let p=Ye(a.store,B);return g({ok:!0,concurrency:xe.configureConcurrency(l.concurrency??{},{organizationId:a.organization.id,actorId:p.id})})}if(S.pathname==="/api/queue/history"&&f.method==="DELETE"){let l=await x(f);if(l.confirm!=="clear completed")return g({ok:!1,error:'Type "clear completed" to confirm retained history cleanup.'},409);let p=Ye(a.store,B);return g({ok:!0,deleted:xe.clearCompleted({projectId:a.project.id,before:typeof l.before==="string"?l.before:void 0,actorId:p.id})})}if(S.pathname==="/api/previews"&&f.method==="GET"){let l=He.previews.listInstances({projectId:a.project.id}).filter((b)=>st(B,b.resourceId,"deployments:read")),p=He.previews.listDefinitions(a.project.id).filter((b)=>st(B,b.resourceId,"project:read")),v=a.store.listResources(a.project.id).filter((b)=>b.kind==="application"&&st(B,b.id,"project:read")).map((b)=>({id:b.id,slug:b.slug,name:b.name,environmentId:b.environmentId}));return g({previews:l,definitions:p,resources:v,environments:[...a.environments.values()]})}if(S.pathname==="/api/releases"&&f.method==="GET"){let l=[...a.environments.values()],p=a.store.listResources(a.project.id).filter((I)=>st(B,I.id,"deployments:read")),v=new Set(p.map((I)=>I.id)),b=zt.releases.list({projectId:a.project.id}).filter((I)=>v.has(I.resourceId)).map((I)=>{let A=p.find((z)=>z.id===I.resourceId),E=l.find((z)=>z.id===I.environmentId),_=I.previousReleaseId?zt.releases.get(I.previousReleaseId):void 0;return{...I,resource:A?{id:A.id,name:A.name,slug:A.slug,provider:A.provider}:void 0,environment:E?{id:E.id,name:E.name,slug:E.slug,kind:E.kind}:void 0,artifact:zt.releases.getArtifact(I.artifactId),transitions:zt.releases.transitions(I.id),approvals:zt.releases.approvals(I.id),previous:_,comparison:_?zt.releases.compare(_.id,I.id):void 0,capabilities:ao({kind:I.kind,provider:A?.provider,hasHealthGate:!!I.healthGate,replicas:Number(I.manifest?.replicas)||1})}});return g({releases:b,resources:p.map((I)=>({id:I.id,name:I.name,slug:I.slug,environmentId:I.environmentId,provider:I.provider})),environments:l})}if(S.pathname==="/api/releases/action"&&f.method==="POST"){let l=await x(f),p=zt.releases.get(String(l.id??"")),v=String(l.action??"");if(!p||!st(B,p.resourceId,"deployments:create"))return g({ok:!1,error:"Release was not found in this scope."},404);let b=Ye(a.store,B);try{if(v==="activate")return g({ok:!0,operation:zt.enqueueActivation(p,{actorId:b.id})});if(v==="rollback"){let I=a.store.getResource(p.resourceId);if(l.confirm!==I?.slug)return g({ok:!1,error:`Type "${I?.slug??""}" to confirm rollback.`},409);return g({ok:!0,operation:zt.enqueueRollback(p,{actorId:b.id,targetReleaseId:typeof l.targetReleaseId==="string"?l.targetReleaseId:void 0})})}if(v==="approve"){let I=a.store.listEnvironments(p.projectId).find((A)=>A.id===p.environmentId);if(l.confirm!==I?.slug)return g({ok:!1,error:`Type "${I?.slug??""}" to confirm the environment gate.`},409);return g({ok:!0,release:zt.releases.approve(p.id,{actorId:b.id,decision:l.decision==="rejected"?"rejected":"approved",comment:typeof l.comment==="string"?l.comment:void 0})})}if(v==="pin")return g({ok:!0,release:zt.releases.pin(p.id,l.pinned!==!1,typeof l.reason==="string"?l.reason:void 0)});if(v==="promote"){let I=a.store.getResource(String(l.targetResourceId??"")),A=I?a.store.listEnvironments(p.projectId).find((E)=>E.id===I.environmentId):void 0;if(!I||!A||!st(B,I.id,"deployments:create"))return g({ok:!1,error:"Promotion target was not found in this scope."},404);if(l.confirm!==A.slug)return g({ok:!1,error:`Type "${A.slug}" to confirm promotion.`},409);return g({ok:!0,release:zt.releases.promote(p.id,{targetEnvironmentId:A.id,targetResourceId:I.id,config:l.config&&typeof l.config==="object"?l.config:{},strategy:typeof l.strategy==="string"?l.strategy:void 0,actorId:b.id,approvalRequired:l.approvalRequired===!0})})}return g({ok:!1,error:"Unsupported release action."},422)}catch(I){return g({ok:!1,error:I instanceof Error?I.message:"Release action failed."},409)}}if(S.pathname==="/api/compose"&&f.method==="GET"){let l=Kr.applications.list({projectId:a.project.id}).filter((p)=>st(B,p.resourceId,"applications:read")).map((p)=>({...p,services:Kr.applications.services(p.id)}));return g({applications:l,templates:ys(),environments:[...a.environments.values()]})}if(S.pathname==="/api/compose/preview"&&f.method==="POST"){let l=await x(f),p=String(l.environmentId??"");if(!Xi(B,p,"applications:manage"))return g({ok:!1,error:"Environment was not found in this scope."},404);try{return g({ok:!0,result:Kr.applications.preview(String(l.source??""),{name:String(l.name??""),slug:typeof l.slug==="string"?l.slug:void 0,projectId:a.project.id,environmentId:p})})}catch(v){return g({ok:!1,error:v instanceof Error?v.message:"Compose could not be parsed."},422)}}if((S.pathname==="/api/compose/import"||S.pathname==="/api/compose/template")&&f.method==="POST"){let l=await x(f),p=String(l.environmentId??"");if(!Xi(B,p,"applications:manage"))return g({ok:!1,error:"Environment was not found in this scope."},404);let v=Ye(a.store,B);try{let b=S.pathname.endsWith("/template")?Kr.applications.fromTemplate(String(l.templateId??""),l.inputs&&typeof l.inputs==="object"?l.inputs:{},{name:String(l.name??""),projectId:a.project.id,environmentId:p,version:typeof l.templateVersion==="string"?l.templateVersion:void 0,createdByActorId:v.id}):Kr.applications.import(String(l.source??""),{name:String(l.name??""),slug:typeof l.slug==="string"?l.slug:void 0,projectId:a.project.id,environmentId:p,createdByActorId:v.id});return g({ok:!0,application:b.application,diagnostics:b.parsed.diagnostics})}catch(b){return g({ok:!1,error:b instanceof Error?b.message:"Compose application could not be saved."},422)}}if(S.pathname==="/api/compose/action"&&f.method==="POST"){let l=await x(f),p=Kr.applications.get(String(l.id??"")),v=String(l.action??""),b=v==="delete"||v==="stop"?"deployments:cancel":"deployments:create";if(!p||!st(B,p.resourceId,b))return g({ok:!1,error:"Compose application was not found in this scope."},404);try{let I=Ye(a.store,B);return g({ok:!0,operation:Kr.enqueue(p,v,{actorId:I.id,service:typeof l.service==="string"?l.service:void 0,replicas:Number.isFinite(Number(l.replicas))?Number(l.replicas):void 0,removeVolumes:l.removeVolumes===!0,confirmation:typeof l.confirm==="string"?l.confirm:void 0})})}catch(I){return g({ok:!1,error:I instanceof Error?I.message:"Compose operation could not be queued."},409)}}if((S.pathname==="/api/compose/logs"||S.pathname==="/api/compose/shell")&&f.method==="POST"){let l=await x(f),p=Kr.applications.get(String(l.id??"")),v=S.pathname.endsWith("/shell"),b=v?"runtime:terminal":"runtime:logs";if(!p||!st(B,p.resourceId,b))return g({ok:!1,error:"Compose service was not found in this scope."},404);let I=String(l.service??"");if(!p.manifest.spec.services[I])return g({ok:!1,error:"Compose service was not found."},404);if(v&&l.confirm!==I)return g({ok:!1,error:`Type "${I}" to run a service command.`},409);let A=a.store.listEnvironments(p.projectId).find((_)=>_.id===p.environmentId)?.slug;if(!A)return g({ok:!1,error:"Compose environment was not found."},404);let E=v?Db(p.manifest,I,Array.isArray(l.command)?l.command.map(String):["sh"]):xb(p.manifest,I,Number(l.lines)||200);return g(await Lo(o,A,E))}if(S.pathname==="/api/previews/definitions"&&f.method==="POST"){let l=await x(f),p=String(l.resourceId??"");if(!st(B,p,"config:write"))return g({ok:!1,error:"Application was not found in this scope."},404);let v=Ye(a.store,B);try{return g({ok:!0,definition:He.previews.createDefinition({...l,projectId:a.project.id,resourceId:p,baseEnvironmentId:String(l.baseEnvironmentId??""),domainPattern:String(l.domainPattern??""),createdByActorId:v.id})})}catch(b){return g({ok:!1,error:b instanceof Error?b.message:"Preview policy could not be created."},409)}}if(S.pathname==="/api/previews/deploy"&&f.method==="POST"){let l=await x(f),p=He.previews.getDefinition(String(l.definitionId??""));if(!p||!st(B,p.resourceId,"deployments:create"))return g({ok:!1,error:"Preview policy was not found in this scope."},404);let v=Ye(a.store,B);try{let b=He.previews.upsert({definitionId:p.id,sourceProvider:"dashboard",repository:"dashboard",branch:String(l.branch??""),pullRequestNumber:Number(l.pullRequestNumber)||void 0,commitSha:String(l.commitSha??""),createdByActorId:v.id});return g({ok:!0,preview:b.preview,operation:He.enqueueDeploy(b.preview,{created:b.created,actorId:v.id})})}catch(b){return g({ok:!1,error:b instanceof Error?b.message:"Preview could not be queued."},409)}}if(S.pathname==="/api/previews/destroy"&&f.method==="POST"){let l=await x(f),p=He.previews.getInstance(String(l.id??""));if(!p||!st(B,p.resourceId,"deployments:cancel"))return g({ok:!1,error:"Preview was not found in this scope."},404);if(l.confirm!==p.name)return g({ok:!1,error:`Type "${p.name}" to confirm tagged teardown.`},409);let v=Ye(a.store,B);return g({ok:!0,operation:He.enqueueDestroy(p,"dashboard",v.id)})}if(S.pathname==="/api/previews/extend"&&f.method==="POST"){let l=await x(f),p=He.previews.getInstance(String(l.id??""));if(!p||!st(B,p.resourceId,"deployments:create"))return g({ok:!1,error:"Preview was not found in this scope."},404);return g({ok:!0,preview:He.previews.extend(p.id,Number(l.hours))})}if(S.pathname==="/api/previews/rebuild"&&f.method==="POST"){let l=await x(f),p=He.previews.getInstance(String(l.id??""));if(!p||!st(B,p.resourceId,"deployments:create"))return g({ok:!1,error:"Preview was not found in this scope."},404);let v=Ye(a.store,B);return g({ok:!0,operation:He.enqueueDeploy(p,{actorId:v.id,reason:"manual_rebuild"})})}if(S.pathname==="/api/previews/cleanup"&&f.method==="POST"){let l=await x(f);if(!l.dryRun&&l.confirm!=="cleanup previews")return g({ok:!1,error:'Type "cleanup previews" to confirm teardown.'},409);let p=Ye(a.store,B);return g({ok:!0,...He.cleanup({dryRun:l.dryRun===!0,maxAgeHours:Number(l.maxAgeHours)||void 0,keepCount:Number(l.keepCount)||void 0,actorId:p.id})})}if(S.pathname==="/api/control-plane/events")return g({events:a.store.listEvents({organizationId:a.organization.id,projectId:a.project.id,operationId:S.searchParams.get("operationId")??void 0,correlationId:S.searchParams.get("correlationId")??void 0,afterSequence:Number(S.searchParams.get("afterSequence"))||void 0,limit:Number(S.searchParams.get("limit"))||200})});if(S.pathname==="/api/search"){let l=String(S.searchParams.get("q")??"").trim().slice(0,128),p=qt.role==="member"?new Set(Object.keys(qt.sites)):void 0,v=l?Tb(a.store,{projectId:a.project.id,query:l,allowedResourceSlugs:p,limit:Number(S.searchParams.get("limit"))||20}):[];return g({query:l,results:v,stale:!1})}if(S.pathname==="/api/search/preferences"&&f.method==="GET"){let l=`dashboard:${B.username.toLowerCase()}`;return g({savedFilters:a.store.listSavedFilters(l),navigation:a.store.listNavigation(l)})}if(S.pathname==="/api/search/preferences"&&f.method==="POST"){let l=`dashboard:${B.username.toLowerCase()}`,p=await x(f),v=String(p.action??"");if(v==="save-filter")return g({savedFilter:a.store.saveFilter(l,String(p.name??""),String(p.routeId??""),p.query??{})});if(v==="favorite")return g({navigation:a.store.setFavorite(l,String(p.entityType??""),String(p.entityId??""),p.favorite!==!1)});if(v==="visit")return g({navigation:a.store.recordNavigation(l,String(p.entityType??""),String(p.entityId??""))});return g({ok:!1,error:"Unknown search preference action."},422)}if(S.pathname==="/api/search/preferences"&&f.method==="DELETE"){let l=`dashboard:${B.username.toLowerCase()}`,p=await x(f);return g({ok:a.store.deleteSavedFilter(l,String(p.id??""))})}if(S.pathname==="/api/organization"&&f.method==="GET"){let l=a.store.listMemberships(a.organization.id,{includeRevoked:!0}).map((p)=>{let v=a.store.getActor(p.actorId);return{...p,actor:v?{id:v.id,displayName:v.displayName,externalId:v.externalId,disabledAt:v.disabledAt}:void 0,grants:a.store.listGrants(p.id)}});return g({organization:a.organization,project:a.project,environments:a.store.listEnvironments(a.project.id),resources:a.store.listResources(a.project.id).map((p)=>({id:p.id,environmentId:p.environmentId,kind:p.kind,slug:p.slug,name:p.name})),memberships:l,invitations:a.store.listInvitations(a.organization.id)})}if(S.pathname==="/api/organization/invitations"&&f.method==="GET")return g({invitations:a.store.listInvitations(a.organization.id)});if(S.pathname==="/api/organization/invitations"&&f.method==="POST"){let l=await x(f),p=rc(l.roleTemplate),v=Vo(l);if(!p||!v)return g({ok:!1,error:"Choose a valid role template and resource scope."},422);let b=re(B);if(!b.actor||!b.membership)return g({ok:!1,error:"Your organization membership is unavailable."},403);if(p==="owner"&&(!cr(String(l.password??""),B.passwordHash)||b.membership.roleTemplate!=="owner"))return g({ok:!1,error:"Owner invitations require an owner to re-enter their password."},401);try{let I=a.store.createInvitation({organizationId:a.organization.id,email:String(l.email??""),roleTemplate:p,scope:v,invitedByActorId:b.actor.id,expiresInMs:Number(l.expiresInMs)||void 0}),A=`${S.origin}/accept-invitation?token=${encodeURIComponent(I.token)}`,E=await fo(o,{to:I.invitation.email,subject:"Your ts-cloud organization invitation",text:`Accept your ts-cloud invitation: ${A}
|
|
688
|
+
|
|
689
|
+
This link expires ${I.invitation.expiresAt} and can be used once.`});return g({invitation:I.invitation,token:I.token,acceptUrl:A,delivered:E},201)}catch(I){return g({ok:!1,error:I instanceof Error?I.message:"Invitation could not be created."},422)}}if(S.pathname==="/api/organization/invitations"&&f.method==="DELETE"){let l=await x(f),p=re(B);try{return g({invitation:a.store.revokeInvitation(String(l.id??""),p.actor?.id)})}catch(v){return g({ok:!1,error:v instanceof Error?v.message:"Invitation could not be revoked."},409)}}if(S.pathname==="/api/organization/invitations/resend"&&f.method==="POST"){let l=await x(f),p=re(B);try{let v=a.store.reissueInvitation(String(l.id??""),p.actor?.id),b=`${S.origin}/accept-invitation?token=${encodeURIComponent(v.token)}`,I=await fo(o,{to:v.invitation.email,subject:"Your ts-cloud organization invitation",text:`Accept your ts-cloud invitation: ${b}
|
|
690
|
+
|
|
691
|
+
This replacement link expires ${v.invitation.expiresAt} and can be used once.`});return g({invitation:v.invitation,token:v.token,acceptUrl:b,delivered:I})}catch(v){return g({ok:!1,error:v instanceof Error?v.message:"Invitation could not be resent."},409)}}if(S.pathname==="/api/organization/memberships"&&f.method==="PATCH"){let l=await x(f),p=a.store.getMembership(String(l.id??"")),v=rc(l.roleTemplate),b=Vo(l);if(!p||p.organizationId!==a.organization.id)return g({ok:!1,error:"Membership was not found."},404);if(!v||!b)return g({ok:!1,error:"Choose a valid role template and resource scope."},422);let I=re(B);if((p.roleTemplate==="owner"||v==="owner")&&(!cr(String(l.password??""),B.passwordHash)||I.membership?.roleTemplate!=="owner"))return g({ok:!1,error:"Ownership changes require an owner to re-enter their password."},401);let E=a.store.resolveAuthorizationTarget(a.organization.id,b)??a.store.resolveAuthorizationTarget(a.organization.id,{type:"project",id:a.project.id}),_=a.store.listGrants(p.id),z=Wo({membership:p,grants:_,target:E}),L={...p,roleTemplate:v,scope:b},ce=Wo({membership:L,grants:_,target:E}),W={gained:ce.filter((ne)=>!z.includes(ne)),lost:z.filter((ne)=>!ce.includes(ne))};if(l.preview===!0)return g({membership:p,proposed:{roleTemplate:v,scope:b},accessDiff:W});if(String(l.confirm??"")!==p.id)return g({ok:!1,error:`Confirm this change with membership ID ${p.id}.`,accessDiff:W},409);try{return g({membership:a.store.updateMembership({id:p.id,roleTemplate:v,scope:b,actorId:I.actor?.id}),accessDiff:W})}catch(ne){return g({ok:!1,error:ne instanceof Error?ne.message:"Membership could not be updated."},409)}}if(S.pathname==="/api/organization/memberships"&&f.method==="DELETE"){let l=await x(f),p=a.store.getMembership(String(l.id??""));if(!p||p.organizationId!==a.organization.id)return g({ok:!1,error:"Membership was not found."},404);if(String(l.confirm??"")!==p.id)return g({ok:!1,error:`Confirm removal with membership ID ${p.id}.`},409);let v=re(B);if(p.roleTemplate==="owner"&&(v.membership?.roleTemplate!=="owner"||!cr(String(l.password??""),B.passwordHash)))return g({ok:!1,error:"Removing an owner requires an owner to re-enter their current password."},401);try{return g({membership:a.store.revokeMembership(p.id,v.actor?.id)})}catch(b){return g({ok:!1,error:b instanceof Error?b.message:"Membership could not be removed."},409)}}if(S.pathname==="/api/organization/grants"&&f.method==="POST"){let l=await x(f),p=String(l.capability??""),v=l.effect==="deny"?"deny":l.effect==="allow"?"allow":void 0,b=Vo(l),I=re(B);if(!v||!b||!Es.includes(p))return g({ok:!1,error:"Choose a valid capability, effect, and resource scope."},422);try{return g({grant:a.store.upsertGrant({organizationId:a.organization.id,membershipId:String(l.membershipId??""),effect:v,capability:p,scope:b,actorId:I.actor?.id})},201)}catch(A){return g({ok:!1,error:A instanceof Error?A.message:"Grant could not be created."},422)}}if(S.pathname==="/api/organization/grants"&&f.method==="DELETE"){let l=await x(f),p=re(B),v=a.store.getGrant(String(l.id??""));if(!v||v.organizationId!==a.organization.id)return g({ok:!1,error:"Grant was not found."},404);return g({ok:a.store.removeGrant(v.id,p.actor?.id)})}if(S.pathname==="/api/tags"&&f.method==="GET")return g({tags:a.store.listTags(a.project.id),assignments:a.store.listResourceTags(a.project.id)});if(S.pathname==="/api/tags"&&f.method==="POST"){let l=await x(f),p=a.store.upsertTag(a.project.id,String(l.name??""),String(l.color??"#5a8be0"));if(l.resourceId)a.store.assignTag(String(l.resourceId),p.id);return g({tag:p},201)}if(S.pathname==="/api/tags"&&f.method==="DELETE"){let l=await x(f);return a.store.removeTag(String(l.resourceId??""),String(l.tagId??"")),g({ok:!0})}if(S.pathname==="/"&&!Ab(S.pathname,qt))return new Response(null,{status:302,headers:{location:`/server/sites?env=${encodeURIComponent(V)}`}});if(S.pathname==="/"&&Le?.mode==="serverless")return new Response(null,{status:302,headers:{location:`/serverless?env=${encodeURIComponent(V)}`}});let Xo=bp(S.pathname);if(Xo)return new Response(null,{status:308,headers:{location:`${Xo}?env=${encodeURIComponent(V)}`}});if(S.pathname==="/api/env"&&f.method==="POST"){let l=await x(f),p=String(l.env??"");if(!u.includes(p))return g({ok:!1,error:`Unknown environment '${p}'.`,environments:u},404);return g({ok:!0,environment:p,environments:u,href:`?env=${encodeURIComponent(p)}`})}if(S.pathname==="/api/config"){let l={...Gb(o),environment:V,environments:u};return g(Pv(l,qt))}if(S.pathname==="/api/ssh-keys"&&f.method==="GET")return g({configPath:h,keys:hn(Yi(o))});if(S.pathname==="/api/ssh-keys"&&f.method==="POST"){if(!h)return g({ok:!1,error:"No cloud config file was found in this checkout."},404);let l=await x(f),p=await br(h,"utf8"),v=Yi(o),b=Ay({configText:p,name:String(l.name??""),publicKey:String(l.publicKey??""),existingKeys:v});return await ei(h,b),kb(o,[...v,{name:String(l.name??"").trim(),publicKey:String(l.publicKey??"").trim().replace(/\s+/g," ")}]),g({ok:!0,configPath:h,keys:hn(Yi(o))})}if(S.pathname==="/api/ssh-keys"&&f.method==="DELETE"){if(!h)return g({ok:!1,error:"No cloud config file was found in this checkout."},404);let l=await x(f),p=String(l.name??S.searchParams.get("name")??""),v=await br(h,"utf8"),b=Yi(o),I=Cy({configText:v,name:p,existingKeys:b});return await ei(h,I),kb(o,b.filter((A)=>A.name!==p.trim())),g({ok:!0,configPath:h,keys:hn(Yi(o))})}if(S.pathname==="/api/firewall"&&f.method==="GET")return g({configPath:h,alwaysOpen:[22,80,443],ports:Uu(o)});if(S.pathname==="/api/firewall"&&f.method==="POST"){if(!h)return g({ok:!1,error:"No cloud config file was found in this checkout."},404);let l=await x(f),p=Number(l.port);if(!zo(p))return g({ok:!1,error:"Port must be an integer between 1 and 65535."},422);let v=Uu(o),b=await br(h,"utf8");try{await ei(h,jv(b,p,v))}catch(E){return g({ok:!1,error:E?.message??String(E)},422)}let I=Xn([...v,p]);Ib(o,I);let A=l.apply===!1?null:await Lo(o,V,`ufw allow ${p}/tcp`).catch((E)=>({ok:!1,error:String(E?.message??E)}));return g({ok:!0,configPath:h,ports:I,apply:A})}if(S.pathname==="/api/firewall"&&f.method==="DELETE"){if(!h)return g({ok:!1,error:"No cloud config file was found in this checkout."},404);let l=await x(f),p=Number(l.port??S.searchParams.get("port"));if(!zo(p))return g({ok:!1,error:"Port must be an integer between 1 and 65535."},422);let v=Uu(o),b=await br(h,"utf8");await ei(h,Mv(b,p,v));let I=Xn(v.filter((E)=>E!==p));Ib(o,I);let A=l.apply===!1?null:await Lo(o,V,`ufw delete allow ${p}/tcp`).catch((E)=>({ok:!1,error:String(E?.message??E)}));return g({ok:!0,configPath:h,ports:I,apply:A})}if(S.pathname==="/api/sites"&&f.method==="POST"){if(!h)return g({ok:!1,error:"No cloud config file was found in this checkout."},404);let l=await x(f),p=String(l.name??"").trim(),v=String(l.root??"").trim();if(!p||!v)return g({ok:!1,error:"Site name and root are required."},422);let b={deploy:l.deploy==="bucket"?"bucket":"server",root:v,path:String(l.path??"").trim()||void 0,domain:String(l.domain??"").trim()||void 0,build:String(l.build??"").trim()||void 0,start:String(l.start??"").trim()||void 0,port:l.port?Number(l.port):void 0,type:String(l.type??"").trim()||void 0};if(b.port!==void 0&&(!Number.isInteger(b.port)||b.port<1||b.port>65535))return g({ok:!1,error:"Port must be a number between 1 and 65535."},422);let I=await br(h,"utf8"),A=eb({configText:I,name:p,root:b.root,domain:b.domain,path:b.path,deploy:b.deploy,build:b.build,start:b.start,port:b.port,type:b.type});return await ei(h,A),E_(o,p,Object.fromEntries(Object.entries(b).filter(([,E])=>E!==void 0))),Le=await ti(o,V),w.set(V,Le),g({ok:!0,configPath:h,site:p,data:Le})}if(S.pathname==="/api/sites"&&f.method==="DELETE"){if(!h)return g({ok:!1,error:"No cloud config file was found in this checkout."},404);let l=await x(f),p=String(l.name??S.searchParams.get("name")??"").trim();if(!p||!o.sites?.[p])return g({ok:!1,error:`Site '${p}' was not found.`},404);let v=await br(h,"utf8");return await ei(h,tb({configText:v,name:p})),delete o.sites[p],Le=await ti(o,V),w.set(V,Le),g({ok:!0,configPath:h,site:p,data:Le})}if(S.pathname==="/api/sites"&&f.method==="PATCH"){if(!h)return g({ok:!1,error:"No cloud config file was found in this checkout."},404);let l=await x(f),p=String(l.name??"").trim(),v=o.sites?.[p];if(!p||!v)return g({ok:!1,error:`Site '${p}' was not found.`},404);if(qt.role==="member"){let A=Dv(l);if(!A.ok)return g({ok:!1,error:A.error},403);let E=Ov({siteName:p,body:l,sites:o.sites??{},ownSites:Object.keys(qt.sites)});if(!E.ok)return g({ok:!1,error:E.error},409)}if(l.port!==void 0&&l.port!==null&&l.port!==""&&(!Number.isInteger(Number(l.port))||Number(l.port)<1||Number(l.port)>65535))return g({ok:!1,error:"Port must be a number between 1 and 65535."},422);if(typeof l.domain==="string"&&l.domain.trim()&&!Bu(l.domain.trim()))return g({ok:!1,error:`Domain '${l.domain.trim()}' is not a valid hostname.`},422);let b=await br(h,"utf8"),I=(A,E)=>{b=rb({configText:b,siteName:p,key:A,valueText:E})};if(l.ssl!==void 0)I("ssl",nb(l.ssl)),v.ssl=l.ssl;if(l.env!==void 0&&l.env&&typeof l.env==="object")I("env",ob(l.env)),v.env=l.env;if(l.aliases!==void 0&&Array.isArray(l.aliases)){let A=l.aliases.map((E)=>String(E));I("aliases",sb(A)),v.aliases=A.map((E)=>E.trim().toLowerCase()).filter(Boolean)}if(l.redirects!==void 0&&l.redirects&&typeof l.redirects==="object")I("redirects",ab(l.redirects)),v.redirects=l.redirects;for(let A of["domain","path","build","start","type","root","php"])if(typeof l[A]==="string"&&l[A].trim())I(A,ib(String(l[A]).trim())),v[A]=String(l[A]).trim();if(l.port!==void 0&&l.port!==null&&l.port!=="")I("port",String(Number(l.port))),v.port=Number(l.port);return await ei(h,b),Le=await ti(o,V),w.set(V,Le),g({ok:!0,configPath:h,site:p,data:Le})}if(S.pathname==="/api/sites/deploy"&&f.method==="POST"){let l=await x(f),p=String(l.name??"").trim();if(!p||!o.sites?.[p])return g({ok:!1,error:`Site '${p}' was not found.`},404);if(l.confirm!==p)return g({ok:!1,error:`Type "${p}" to deploy this site.`},409);let v=ar(a,String(V));await new Qn(ge).run(new $o,{...v,artifactRoot:t}),Na(ge,v,Le??{});let b=ja(ge,{scope:v,desiredConfigHash:a.project.desiredConfigHash});if(b.decision.outcome==="block")return g({ok:!1,error:`Deployment blocked by security policy: ${b.decision.explanation}`,securityReview:b},409);let I={id:`deploy:${p}`,label:`Deploy ${p}`,description:`Deploy the ${p} site for ${V}.`,command:["deploy","--env",V,"--site",p,"--yes"],mutates:!0},A=await Ir({controlPlane:a,environment:V,actor:B,kind:"dashboard.site.deploy",resourceSlug:p,input:{site:p},execute:()=>qu(I,{cwd:t,cliEntry:i})});return g({...A.result,controlPlaneOperation:A.operation,securityReview:b})}if(S.pathname==="/api/actions")return g(Hu(V));if(S.pathname==="/api/server/operations")return g(Qa(o,Le));if(S.pathname==="/api/runtime/workloads"&&f.method==="GET"){let l=await or(o,V);return g(l)}if(S.pathname==="/api/runtime/logs"&&f.method==="GET"){let l=String(S.searchParams.get("workload")??"");if(!l)return g({ok:!1,error:"A workload query parameter is required."},422);let p=Math.min(1000,Math.max(1,Number(S.searchParams.get("limit"))||200));try{return g(await new yr(o,V).logs(l,{limit:p}))}catch(v){return g({ok:!1,error:String(v?.message??v)},404)}}if(S.pathname==="/api/runtime/log-sessions"&&f.method==="POST"){let l=await x(f),p=String(l.workloadId??"");if(!p)return g({ok:!1,error:"A workloadId is required."},422);let v=await or(o,V),b=v.workloads.find((E)=>E.id===p);if(!b)return g({ok:!1,error:"Workload was not found in the current project and environment."},404);if(!b.capabilities.logs.supported)return g({ok:!1,error:b.capabilities.logs.reason??"Logs are unsupported for this workload."},409);let I=new yr(o,V,{inventory:async()=>v}),A=Ge.create("logs",p);return(async()=>{let E=new Date(Date.now()-Math.min(3600000,Math.max(1000,Number(l.sinceMs)||60000)));try{for(let _=0;_<200&&!Ge.signal(A.id)?.aborted;_++){let z=await I.logs(p,{limit:Math.min(500,Math.max(1,Number(l.limit)||200)),since:E});for(let L of z.lines)if(Ge.append(A.id,`${L.timestamp?`${L.timestamp} `:""}${L.message}
|
|
692
|
+
`),L.timestamp)E=new Date(Math.max(E.getTime(),new Date(L.timestamp).getTime()+1));await Bun.sleep(3000)}if(!Ge.signal(A.id)?.aborted)Ge.close(A.id,"complete")}catch(_){Ge.append(A.id,_ instanceof Error?_.message:String(_),"stderr"),Ge.close(A.id,"failed",_ instanceof Error?_.message:String(_))}})(),g({ok:!0,session:A,streamUrl:`/api/runtime/log-stream?id=${encodeURIComponent(A.id)}&workload=${encodeURIComponent(p)}`},201)}if((S.pathname==="/api/runtime/log-stream"||S.pathname==="/api/runtime/exec-stream")&&f.method==="GET"){let l=String(S.searchParams.get("id")??""),p=String(S.searchParams.get("workload")??""),v=Number(f.headers.get("last-event-id")??S.searchParams.get("after")??0)||0,b=Ge.read(l,p,v),I=S.pathname.includes("exec")?"exec":"logs";if(!b||b.kind!==I)return g({ok:!1,error:"Runtime stream was not found in this workload scope."},404);return f_(Ge,b,v,f.signal)}if((S.pathname==="/api/runtime/log-sessions"||S.pathname==="/api/runtime/exec-sessions")&&f.method==="DELETE"){let l=await x(f),p=Ge.cancel(String(l.id??""),String(l.workloadId??""));if(!p)return g({ok:!1,error:"Runtime stream was not found in this workload scope."},404);return g({ok:!0,session:p})}if(S.pathname==="/api/runtime/exec-sessions"&&f.method==="POST"){let l=await x(f),p=String(l.workloadId??""),v=await or(o,V),b=v.workloads.find((_)=>_.id===p);if(!b)return g({ok:!1,error:"Workload was not found in the current project and environment."},404);let I=ze.resolveSession(f),A=new yr(o,V,{inventory:async()=>v}),E=Ge.create("exec",p);return Ir({controlPlane:a,environment:V,actor:B,kind:"runtime.exec",resourceSlug:b.links.service,input:{workloadId:p,provider:b.provider,preset:l.preset?String(l.preset):null,freeForm:!!String(l.command??"").trim()},execute:()=>A.exec({workloadId:p,preset:["process","sockets","filesystem"].includes(String(l.preset))?String(l.preset):void 0,command:typeof l.command==="string"?l.command:void 0,confirm:String(l.confirm??""),recentAuth:!K||!!I&&G.isRecentlyAuthenticated(I)})}).then(({result:_,operation:z})=>{if(Ge.append(E.id,`operation ${z.id}
|
|
693
|
+
`,"system"),_.stdout)Ge.append(E.id,_.stdout,"stdout");if(_.stderr)Ge.append(E.id,_.stderr,"stderr");Ge.close(E.id,_.ok?"complete":"failed",_.error)}).catch((_)=>{let z=_ instanceof Error?_.message:String(_);Ge.append(E.id,z,"stderr"),Ge.close(E.id,"failed",z)}),g({ok:!0,session:E,streamUrl:`/api/runtime/exec-stream?id=${encodeURIComponent(E.id)}&workload=${encodeURIComponent(p)}`},202)}if(S.pathname==="/api/runtime/files/read"&&f.method==="POST"){let l=await x(f),p=await or(o,V),v=ze.resolveSession(f),b=await new yr(o,V,{inventory:async()=>p}).readFile({workloadId:String(l.workloadId??""),path:String(l.path??""),confirm:String(l.confirm??""),recentAuth:!K||!!v&&G.isRecentlyAuthenticated(v)});return g(b,b.ok?200:409)}if(S.pathname==="/api/runtime/files/write"&&f.method==="POST"){let l=await x(f),p=await or(o,V),v=String(l.workloadId??""),b=p.workloads.find((_)=>_.id===v);if(!b)return g({ok:!1,error:"Workload was not found in the current project and environment."},404);let I=ze.resolveSession(f),A=new yr(o,V,{inventory:async()=>p}),E=await Ir({controlPlane:a,environment:V,actor:B,kind:"runtime.file.write",resourceSlug:b.links.service,input:{workloadId:v,provider:b.provider,path:String(l.path??""),bytes:Buffer.from(String(l.contentBase64??""),"base64").byteLength},execute:()=>A.writeFile({workloadId:v,path:String(l.path??""),contentBase64:String(l.contentBase64??""),confirm:String(l.confirm??""),recentAuth:!K||!!I&&G.isRecentlyAuthenticated(I)})});return g({...E.result,controlPlaneOperation:E.operation},E.result.ok?200:409)}if(S.pathname==="/api/runtime/operations"&&f.method==="POST"){let l=await x(f),p=String(l.workloadId??""),v=String(l.action??"");if(!p||!["start","stop","restart","redeploy","scale","inspect"].includes(v))return g({ok:!1,error:"A valid workloadId and lifecycle action are required."},422);let b=await or(o,V),I=b.workloads.find((z)=>z.id===p);if(!I)return g({ok:!1,error:"Workload was not found in the current project and environment."},404);let A=ze.resolveSession(f),E=new yr(o,V,{inventory:async()=>b}),_=await Ir({controlPlane:a,environment:V,actor:B,kind:`runtime.${v}`,resourceSlug:I.links.service,input:{workloadId:p,provider:I.provider,action:v,replicas:l.replicas==null?null:Number(l.replicas)},execute:()=>E.run({workloadId:p,action:v,replicas:l.replicas==null?void 0:Number(l.replicas),confirm:String(l.confirm??""),recentAuth:!K||!!A&&G.isRecentlyAuthenticated(A)})});return g({..._.result,controlPlaneOperation:_.operation},_.result.ok?200:409)}if(S.pathname.startsWith("/api/protection")){let l=B.role==="admin"||Zo(B,"security:read"),p=B.role==="admin"||Zo(B,"security:manage");if(!l)return g({ok:!1,error:"Protection controls require security:read."},403);let{ProtectionControlStore:v,describePosture:b}=await import("./protection/index.js"),I=new v(a.store),A=()=>{if(!p)throw Error("Changing protection controls requires security:manage.")};if(S.pathname==="/api/protection"&&f.method==="GET"){let E=I.current();return g({ok:!0,posture:b(E),controls:E,raw:I.raw()})}if(S.pathname==="/api/protection/attack-mode"&&f.method==="POST"){A();let E=await x(f);if(E.enabled===!1)return g({ok:!0,disabled:I.disableAttackMode()});return g({ok:!0,control:I.enableAttackMode({hours:E.hours==null?void 0:Number(E.hours),reason:String(E.reason??"Enabled from the dashboard."),actorId:re(B).actor?.id})})}if(S.pathname==="/api/protection/pause"&&f.method==="POST"){A();let E=await x(f);if(E.enabled===!1)return g({ok:!0,resumed:I.resumeMitigations()});return g({ok:!0,control:I.pauseMitigations({hours:E.hours==null?void 0:Number(E.hours),reason:String(E.reason??""),actorId:re(B).actor?.id})})}if(S.pathname==="/api/protection/ip-rules"&&f.method==="GET")return g({ok:!0,ipRules:I.current().ipRules});if(S.pathname==="/api/protection/ip-rules"&&(f.method==="POST"||f.method==="DELETE")){A();let E=await x(f),_=E.list==="allow"?"allow":"block",z=f.method==="POST"?I.addIpRule(_,String(E.cidr??"")):I.removeIpRule(_,String(E.cidr??""));return g({ok:!0,ipRules:z})}return g({ok:!1,error:"Protection endpoint was not found."},404)}if(S.pathname.startsWith("/api/spend/")||S.pathname==="/api/usage"){let l=await tS(),p=l.store,v=l.service,b=l.gate,I=B.role==="admin"||Zo(B,"billing:read"),A=B.role==="admin"||Zo(B,"billing:manage");if(!I)return g({ok:!1,error:"Spend data requires the billing:read capability."},403);let E=a.environments.get(V),_={organizationId:a.organization.id,projectId:a.project.id,environmentId:E?.id},z=()=>{if(!A)throw Error("Changing a budget requires the billing:manage capability.")};if(S.pathname==="/api/usage"&&f.method==="GET")return g({ok:!0,...v.usageReport({organizationId:_.organizationId,projectId:_.projectId,period:S.searchParams.get("period")??"monthly",timezone:S.searchParams.get("timezone")??void 0})});if(S.pathname==="/api/spend/budgets"&&f.method==="GET")return g({ok:!0,budgets:p.listBudgets({organizationId:_.organizationId,projectId:_.projectId}).map((L)=>({...L,status:v.status(L)}))});if(S.pathname==="/api/spend/budgets"&&f.method==="POST"){z();let L=await x(f),ce=String(L.scope??"project"),W=p.createBudget({organizationId:_.organizationId,projectId:ce==="organization"?void 0:_.projectId,environmentId:ce==="environment"?_.environmentId:void 0,name:String(L.name??"").trim(),period:L.period??"monthly",timezone:L.timezone?String(L.timezone):void 0,softLimitCents:L.softLimitCents==null?void 0:Math.round(Number(L.softLimitCents)),hardLimitCents:L.hardLimitCents==null?void 0:Math.round(Number(L.hardLimitCents)),graceSeconds:L.graceSeconds==null?void 0:Number(L.graceSeconds),dryRun:L.dryRun!==!1});return g({ok:!0,budget:W})}if(S.pathname==="/api/spend/budgets"&&f.method==="PATCH"){z();let L=await x(f),ce=String(L.id??""),W=p.getBudget(ce);if(!W||W.organizationId!==_.organizationId)return g({ok:!1,error:"Budget was not found."},404);return g({ok:!0,budget:p.updateBudget(ce,{softLimitCents:L.softLimitCents==null?W.softLimitCents:Math.round(Number(L.softLimitCents)),hardLimitCents:L.hardLimitCents==null?W.hardLimitCents:Math.round(Number(L.hardLimitCents)),enabled:L.enabled==null?W.enabled:L.enabled===!0,dryRun:L.dryRun==null?W.dryRun:L.dryRun===!0},L.expectedVersion==null?void 0:Number(L.expectedVersion))})}if(S.pathname==="/api/spend/budgets"&&f.method==="DELETE"){z();let L=await x(f),ce=String(L.id??""),W=p.getBudget(ce);if(!W||W.organizationId!==_.organizationId)return g({ok:!1,error:"Budget was not found."},404);let ne=b.closeBudget(ce);return p.deleteBudget(ce),g({ok:!0,deleted:!0,lifted:ne})}if(S.pathname==="/api/spend/check"&&f.method==="POST"){z();let L=await x(f),{SpendRunner:ce}=await import("./spend/index.js"),W=new ce({controlPlane:a.store,store:p,alerts:le});if(L.apply!==!0){let H=p.budgetsForScope(_.organizationId,_.projectId,_.environmentId);return g({ok:!0,applied:!1,preview:H.map((ee)=>v.status(ee))})}let ne=await W.run({..._,environmentKind:E?.kind});return g({ok:!0,applied:!0,result:ne})}if(S.pathname==="/api/spend/enforcement"&&f.method==="GET")return g({ok:!0,enforcement:b.listUnder({organizationId:_.organizationId})});if(S.pathname==="/api/spend/release"&&f.method==="POST"){z();let L=await x(f),ce=b.close(String(L.budgetId??""),L.action);return g({ok:ce,released:ce,note:ce?"The next spend cycle re-applies this if spend is still over the threshold.":"That action was not in force."})}if(S.pathname==="/api/spend/anomalies"&&f.method==="GET")return g({ok:!0,anomalies:p.listAnomalies({organizationId:_.organizationId,projectId:_.projectId,unacknowledgedOnly:S.searchParams.get("unacknowledged")==="true"})});if(S.pathname==="/api/spend/anomalies/acknowledge"&&f.method==="POST"){z();let L=await x(f);return g({ok:!0,acknowledged:p.acknowledgeAnomaly(String(L.id??""))})}return g({ok:!1,error:"Spend endpoint was not found."},404)}if(S.pathname.startsWith("/api/health/")||S.pathname.startsWith("/api/alerts")||S.pathname.startsWith("/api/notifications/")){let l=a.environments.get(V),p=a.store.listResources(a.project.id,l?.id),v=B.role==="admin"||!!l&&Xi(B,l.id,"runtime:read")?p:p.filter((E)=>st(B,E.id,"runtime:read")),b=(E)=>!E||v.some((_)=>_.id===E),I=(E)=>{if(!E)return;let _=p.find((z)=>z.id===E||z.slug===E);if(!_)throw Error("Alert resource was not found.");if(!b(_.id))throw Error("Alert resource is outside your authorized scope.");return _.id},A=re(B).actor;if(S.pathname==="/api/health/checks"&&f.method==="GET")return g({ok:!0,checks:le.listHealthChecks(a.project.id,l?.id).filter((E)=>b(E.resourceId)).map((E)=>({...E,results:le.listHealthResults(E.id,20)}))});if(S.pathname==="/api/health/checks"&&f.method==="POST"){let E=await x(f),_=String(E.kind??"http");if(_==="command"&&B.role!=="admin")return g({ok:!1,error:"Command health checks require an administrator."},403);let z={method:String(E.config?.method??"GET").toUpperCase().slice(0,10),path:E.config?.path?String(E.config.path).slice(0,500):void 0,port:E.config?.port==null?void 0:Number(E.config.port),command:Array.isArray(E.config?.command)?E.config.command.map(String).slice(0,20):void 0,expectedStatuses:Array.isArray(E.config?.expectedStatuses)?E.config.expectedStatuses.map(Number).filter(Number.isInteger).slice(0,20):void 0,expectedBody:E.config?.expectedBody?String(E.config.expectedBody).slice(0,500):void 0};return g({ok:!0,check:le.createHealthCheck({projectId:a.project.id,environmentId:l?.id,resourceId:I(E.resourceId??E.resource),name:String(E.name??""),kind:_,target:String(E.target??""),config:z,intervalSeconds:Number(E.intervalSeconds)||60,timeoutSeconds:Number(E.timeoutSeconds)||10,failureThreshold:Number(E.failureThreshold)||3,recoveryThreshold:Number(E.recoveryThreshold)||2,regions:Array.isArray(E.regions)?E.regions.map(String):["local"],enabled:E.enabled!==!1})},201)}if(S.pathname==="/api/health/checks"&&f.method==="PATCH"){let E=await x(f),_=le.getHealthCheck(String(E.id??""));if(!_||!b(_.resourceId))return g({ok:!1,error:"Health check was not found."},404);return g({ok:!0,check:le.setHealthCheckEnabled(_.id,E.enabled!==!1)})}if(S.pathname==="/api/health/checks/test"&&f.method==="POST"){let E=await x(f),_=le.getHealthCheck(String(E.id??""));if(!_||!b(_.resourceId))return g({ok:!1,error:"Health check was not found."},404);return g({ok:!0,productionIncidentCreated:!1,result:await new Gi(le).probe(_)})}if(S.pathname==="/api/health/checks/run"&&f.method==="POST"){let E=await x(f),_=le.getHealthCheck(String(E.id??""));if(!_||!b(_.resourceId))return g({ok:!1,error:"Health check was not found."},404);let z=await new Gi(le).runAndEvaluate(_),L=[];for(let ce of z.evaluations.filter((W)=>W.notify&&W.alert)){let W=Ut.enqueue(a.organization.id,ce.alert,ce.transition);L.push(...await Ut.deliverAll(W))}return g({ok:!0,...z,deliveries:L})}if(S.pathname==="/api/alerts/rules"&&f.method==="GET")return g({ok:!0,rules:le.listRules(a.project.id,l?.id).filter((E)=>b(E.resourceId))});if(S.pathname==="/api/alerts/rules"&&f.method==="POST"){let E=await x(f),_=E.healthCheckId?le.getHealthCheck(String(E.healthCheckId)):void 0;if(E.healthCheckId&&(!_||!b(_.resourceId)))return g({ok:!1,error:"Health check was not found."},404);return g({ok:!0,rule:le.createRule({projectId:a.project.id,environmentId:l?.id,resourceId:I(E.resourceId??E.resource)??_?.resourceId,healthCheckId:_?.id,name:String(E.name??""),signal:String(E.signal??(_?"health":"")),operator:String(E.operator??(_?"unhealthy":"gt")),threshold:E.threshold==null?void 0:Number(E.threshold),recoveryThreshold:E.recoveryThreshold==null?void 0:Number(E.recoveryThreshold),windowMs:Number(E.windowMs)||300000,consecutive:Number(E.consecutive)||_?.failureThreshold||3,recoveryConsecutive:Number(E.recoveryConsecutive)||_?.recoveryThreshold||2,noDataPolicy:["ignore","pending","firing"].includes(String(E.noDataPolicy))?E.noDataPolicy:"pending",severity:["info","warning","critical"].includes(String(E.severity))?E.severity:"warning",groupBy:Array.isArray(E.groupBy)?E.groupBy.map(String):[],labels:E.labels&&typeof E.labels==="object"?E.labels:{},enabled:E.enabled!==!1})},201)}if(S.pathname==="/api/alerts/rules"&&f.method==="PATCH"){let E=await x(f),_=le.getRule(String(E.id??""));if(!_||!b(_.resourceId))return g({ok:!1,error:"Alert rule was not found."},404);return g({ok:!0,rule:le.setRuleEnabled(_.id,E.enabled!==!1)})}if(S.pathname==="/api/alerts/evaluate"&&f.method==="POST")return g({ok:!0,...await ep(l?.id)});if(S.pathname==="/api/alerts"&&f.method==="GET")return g({ok:!0,alerts:le.listAlerts(a.project.id,{environmentId:l?.id,states:S.searchParams.getAll("state").length?S.searchParams.getAll("state"):void 0,limit:Number(S.searchParams.get("limit"))||200}).filter((E)=>b(E.resourceId)).map((E)=>({...E,deliveries:le.listDeliveries({alertId:E.id,limit:50})}))});if(S.pathname==="/api/alerts/action"&&f.method==="POST"){let E=await x(f),_=le.getAlert(String(E.id??""));if(!_||!b(_.resourceId))return g({ok:!1,error:"Alert was not found."},404);let z=String(E.action??"");if(z==="acknowledge")return g({ok:!0,alert:le.acknowledge(_.id,A?.id??"")});if(z==="assign")return g({ok:!0,alert:le.assign(_.id,E.ownerActorId==="me"?A?.id:E.ownerActorId?String(E.ownerActorId):void 0,A?.id)});if(z==="silence"){if(B.role!=="admin")return g({ok:!1,error:"Silencing production alerts requires an administrator."},403);let L=ze.resolveSession(f);if(K&&(!L||!G.isRecentlyAuthenticated(L)))return g({ok:!1,error:"Recent authentication is required to silence alerts.",stepUpRequired:!0},401);return g({ok:!0,alert:le.silenceAlert(_.id,String(E.until??""),A?.id)})}return g({ok:!1,error:"Action must be acknowledge, assign, or silence."},422)}if(S.pathname==="/api/alerts/silences"&&f.method==="POST"){let E=await x(f);return g({ok:!0,id:le.createSilence({projectId:a.project.id,environmentId:l?.id,resourceId:I(E.resourceId??E.resource),matcher:E.matcher,reason:String(E.reason??""),startsAt:String(E.startsAt??new Date().toISOString()),endsAt:String(E.endsAt??""),timezone:String(E.timezone??"UTC"),actorId:A?.id})},201)}if(S.pathname==="/api/notifications/channels"&&f.method==="GET")return g({ok:!0,channels:le.listChannels(a.organization.id)});if(S.pathname==="/api/notifications/channels"&&f.method==="POST"){let E=await x(f),_=String(E.kind??""),z=_==="email"?{to:E.config?.to,from:E.config?.from}:_==="telegram"?{chatId:String(E.config?.chatId??"")}:{};return g({ok:!0,channel:le.createChannel({organizationId:a.organization.id,name:String(E.name??""),kind:_,config:z,credential:E.credential?String(E.credential):void 0,actorId:A?.id})},201)}if(S.pathname==="/api/notifications/channels"&&f.method==="PATCH"){let E=await x(f),_=String(E.id??"");if(E.credential)return g({ok:!0,channel:le.rotateChannel(_,String(E.credential))});let z=String(E.status??"paused");if(!["active","paused","disabled"].includes(z))return g({ok:!1,error:"Channel status must be active, paused, or disabled."},422);return g({ok:!0,channel:le.setChannelStatus(_,z)})}if(S.pathname==="/api/notifications/channels/test"&&f.method==="POST"){let E=await x(f);return g({ok:!0,productionIncidentCreated:!1,result:await Ut.testChannel(String(E.id??""))})}if(S.pathname==="/api/notifications/routes"&&f.method==="GET")return g({ok:!0,routes:le.listRoutes(a.organization.id)});if(S.pathname==="/api/notifications/routes"&&f.method==="POST"){let E=await x(f),_=Array.isArray(E.channelIds)?E.channelIds.map(String):[];if(_.some((z)=>le.getChannel(z)?.organizationId!==a.organization.id))return g({ok:!1,error:"Route contains an unavailable channel."},422);return g({ok:!0,route:le.createRoute({organizationId:a.organization.id,name:String(E.name??""),priority:Number(E.priority)||0,matcher:E.matcher&&typeof E.matcher==="object"?E.matcher:{},channelIds:_,quietHours:E.quietHours,groupWaitSeconds:Number(E.groupWaitSeconds)||30,reminderSeconds:E.reminderSeconds==null?void 0:Number(E.reminderSeconds),escalation:Array.isArray(E.escalation)?E.escalation:[],template:E.template?String(E.template):void 0,rateLimitPerMinute:Number(E.rateLimitPerMinute)||60,enabled:E.enabled!==!1})},201)}if(S.pathname==="/api/notifications/routes"&&f.method==="PATCH"){let E=await x(f),_=le.getRoute(String(E.id??""));if(!_||_.organizationId!==a.organization.id)return g({ok:!1,error:"Notification route was not found."},404);return g({ok:!0,route:le.setRouteEnabled(_.id,E.enabled!==!1)})}if(S.pathname==="/api/notifications/routes/preview"&&f.method==="POST"){let E=await x(f),z=(E.alertId?le.getAlert(String(E.alertId)):void 0)??{id:"preview",ruleId:"preview",projectId:a.project.id,environmentId:l?.id,resourceId:I(E.resourceId??E.resource),dedupKey:"preview",groupKey:String(E.groupKey??"default"),state:"firing",severity:["info","warning","critical"].includes(String(E.severity))?E.severity:"warning",title:String(E.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 g({ok:!0,productionIncidentCreated:!1,matches:Ut.preview(a.organization.id,z,String(E.eventType??"firing")).map((L)=>({route:L.route,channels:L.channels,quiet:L.quiet}))})}if(S.pathname==="/api/notifications/deliveries"&&f.method==="GET")return g({ok:!0,deliveries:le.listDeliveries({alertId:S.searchParams.get("alertId")??void 0,states:S.searchParams.getAll("state"),limit:Number(S.searchParams.get("limit"))||200})});if(S.pathname==="/api/notifications/deliveries/retry"&&f.method==="POST"){let E=await x(f),_=le.getDelivery(String(E.id??""));if(!_)return g({ok:!1,error:"Delivery was not found."},404);return le.updateDelivery(_.id,{state:"retrying",attempt:Math.max(0,_.attempt-1),nextAttemptAt:new Date().toISOString()}),g({ok:!0,delivery:await Ut.deliver(_.id)})}}if(S.pathname.startsWith("/api/jobs")||S.pathname.startsWith("/api/workers")){let l=a.environments.get(V),p=a.store.listResources(a.project.id,l?.id),b=B.role==="admin"||!!l&&Xi(B,l.id,"automation:read")?p:p.filter((H)=>st(B,H.id,"automation:read")),I=(H)=>!H||b.some((ee)=>ee.id===H),A=re(B).actor,E=w.get(V)??y,_=Qa(o,E),z=_.filter((H)=>!H.danger&&["scheduler","backup","worker"].includes(H.group)),L=Fr(o),ce=()=>{let H=ze.resolveSession(f);return!K||!!H&&G.isRecentlyAuthenticated(H)},W=(H)=>{if(!H||typeof H!=="object"||Array.isArray(H))return{};let ee=Object.entries(H).slice(0,50);if(ee.some(([,pe])=>typeof pe!=="string"||!/^(?:secret|ssm|arn|env):\/\//.test(pe)))throw Error("Job payload values must be secret or environment references, never inline values.");return Object.fromEntries(ee)},ne=(H,ee,pe)=>a.store.appendEvent({organizationId:a.organization.id,projectId:a.project.id,resourceId:pe,actorId:A?.id,type:`job.${H}`,payload:ee});if(S.pathname==="/api/jobs/preview"&&f.method==="POST"){let H=await x(f);try{return g({ok:!0,productionExecutionCreated:!1,preview:Bn(String(H.expression??""),String(H.timezone??"UTC"),new Date(H.from?String(H.from):Date.now()),Number(H.count)||5)})}catch(ee){return g({ok:!1,error:ee instanceof Error?ee.message:"Schedule preview could not be generated.",productionExecutionCreated:!1},422)}}if(S.pathname==="/api/jobs"&&f.method==="GET")return g({ok:!0,jobs:ot.list(a.project.id,{environmentId:l?.id}).filter((H)=>I(H.resourceId)).map((H)=>({...H,preview:Bn(H.normalizedExpression,H.timezone,new Date,5),capability:yo(H),lastExecution:ot.listExecutions(H.id,1)[0]}))});if(S.pathname==="/api/jobs"&&f.method==="POST"){let H=await x(f),ee=String(H.provider??(L==="serverless"?"eventbridge":"server")),pe=L==="serverless"?"eventbridge":"server";if(ee!==pe)return g({ok:!1,error:`${L} environments accept ${pe} schedules through this adapter.`},422);let ve=H.operationId?String(H.operationId):void 0;if(ee==="server"&&(!ve||!z.some((Qe)=>Qe.id===ve)))return g({ok:!1,error:"Server jobs require an allowlisted operation target."},422);let Pe=yo({provider:ee,expression:String(H.expression??""),flexibleMinutes:Number(H.flexibleMinutes)||0,missedRunPolicy:H.missedRunPolicy==="catch_up"?"catch_up":"skip",overlapPolicy:["allow","forbid","replace"].includes(String(H.overlapPolicy))?H.overlapPolicy:"forbid"});if(!Pe.supported)return g({ok:!1,error:Pe.notes.join(" ")},422);let jt=H.resourceId?p.find((Qe)=>Qe.id===H.resourceId||Qe.slug===H.resourceId):void 0;if(H.resourceId&&(!jt||!I(jt.id)))return g({ok:!1,error:"Job resource was not found."},404);try{let Qe=ee==="server"?{kind:"dashboard_operation",operationId:ve}:{kind:"serverless_scheduler",action:"run"},Gr=ot.create({organizationId:a.organization.id,projectId:a.project.id,environmentId:l?.id,resourceId:jt?.id,name:String(H.name??""),provider:ee,expression:String(H.expression??""),timezone:String(H.timezone??"UTC"),startsAt:H.startsAt?String(H.startsAt):void 0,endsAt:H.endsAt?String(H.endsAt):void 0,flexibleMinutes:Number(H.flexibleMinutes)||0,target:Qe,payloadRefs:W(H.payloadRefs),missedRunPolicy:H.missedRunPolicy==="catch_up"?"catch_up":"skip",overlapPolicy:["allow","forbid","replace"].includes(String(H.overlapPolicy))?H.overlapPolicy:"forbid",retryPolicy:{maxAttempts:Number(H.maxAttempts)||3,backoffSeconds:Number(H.backoffSeconds)||30,deadLetterRef:H.deadLetterRef?String(H.deadLetterRef):void 0},timeoutSeconds:Number(H.timeoutSeconds)||900,enabled:H.enabled!==!1,origin:"managed",ownerActorId:A?.id,observedState:{},reconciliationStatus:"pending"});return ne("created",{jobId:Gr.id,provider:Gr.provider,expression:Gr.normalizedExpression},Gr.resourceId),g({ok:!0,job:Gr,capability:Pe},201)}catch(Qe){return g({ok:!1,error:Qe instanceof Error?Qe.message:"Scheduled job could not be created."},422)}}if(S.pathname==="/api/jobs"&&f.method==="PATCH"){let H=await x(f),ee=ot.get(String(H.id??""));if(!ee||!I(ee.resourceId))return g({ok:!1,error:"Scheduled job was not found."},404);if(ee.origin==="config")return g({ok:!1,error:"Config-defined schedules must be edited in cloud.config.ts and reconciled."},409);let pe=H.missedRunPolicy==null?void 0:String(H.missedRunPolicy),ve=H.overlapPolicy==null?void 0:String(H.overlapPolicy);if(pe&&!["skip","catch_up"].includes(pe))return g({ok:!1,error:"Missed-run policy must be skip or catch_up."},422);if(ve&&!["allow","forbid","replace"].includes(ve))return g({ok:!1,error:"Overlap policy must be allow, forbid, or replace."},422);try{let Pe=ot.updateSchedule(ee.id,{expression:H.expression?String(H.expression):void 0,timezone:H.timezone?String(H.timezone):void 0,missedRunPolicy:pe,overlapPolicy:ve,timeoutSeconds:H.timeoutSeconds==null?void 0:Number(H.timeoutSeconds)});return ne("updated",{jobId:Pe.id,expression:Pe.normalizedExpression,version:Pe.version},Pe.resourceId),g({ok:!0,job:Pe})}catch(Pe){return g({ok:!1,error:Pe instanceof Error?Pe.message:"Scheduled job could not be updated."},422)}}if(S.pathname==="/api/jobs/action"&&f.method==="POST"){let H=await x(f),ee=ot.get(String(H.id??""));if(!ee||!I(ee.resourceId))return g({ok:!1,error:"Scheduled job was not found."},404);let pe=String(H.action??"");if(pe==="run"){let ve=Xu.enqueue(ee,{trigger:"manual",actorId:A?.id});return ne("run_queued",{jobId:ee.id,executionId:ve.id},ee.resourceId),g({ok:!0,execution:ve},202)}if(["disable","delete"].includes(pe)&&l?.kind==="production"){if(String(H.confirm??"")!==pe)return g({ok:!1,error:`Type "${pe}" to confirm this production change.`},409);if(!ce())return g({ok:!1,error:"Recent authentication is required for this production change.",stepUpRequired:!0},401)}if(pe==="enable"||pe==="disable"){let ve=ot.setEnabled(ee.id,pe==="enable");return ne(pe==="enable"?"enabled":"disabled",{jobId:ee.id},ee.resourceId),g({ok:!0,job:ve})}if(pe==="delete")try{return ot.remove(ee.id),ne("deleted",{jobId:ee.id,name:ee.name},ee.resourceId),g({ok:!0,deleted:ee.id})}catch(ve){return g({ok:!1,error:ve instanceof Error?ve.message:"Scheduled job could not be deleted."},409)}return g({ok:!1,error:"Action must be run, enable, disable, or delete."},422)}if(S.pathname==="/api/jobs/history"&&f.method==="GET"){let H=ot.get(String(S.searchParams.get("jobId")??""));if(!H||!I(H.resourceId))return g({ok:!1,error:"Scheduled job was not found."},404);return g({ok:!0,executions:ot.listExecutions(H.id,Number(S.searchParams.get("limit"))||100).map((ee)=>({...ee,logs:ee.operationId?xe.logs(ee.operationId,{limit:500}):[]}))})}if(S.pathname==="/api/jobs/reconcile"&&f.method==="POST"){if(!l)return g({ok:!1,error:"Environment was not found."},404);let H=sd(ot,o,{organization:a.organization,project:a.project,environment:l,resources:p});return ne("reconciled",H),g({ok:!0,reconciliation:H})}if(S.pathname==="/api/workers"&&f.method==="GET"){let H=Array.isArray(E.workersDetail??E.workers)?E.workersDetail??E.workers:[];return g({ok:!0,workers:ot.listWorkers(a.project.id,l?.id).filter((ee)=>I(ee.resourceId)).map((ee)=>{let pe=H.find((ve)=>ve.name===ee.name||ve.site===ee.target.site);return pe?{...ee,observedState:{...ee.observedState,status:pe.status??"configured",currentJob:pe.currentJob??null,failures:Number(pe.failed??pe.failures)||0,processed:Number(pe.processed)||0}}:ee})})}if(S.pathname==="/api/workers/action"&&f.method==="POST"){let H=await x(f),ee=ot.getWorker(String(H.id??""));if(!ee||!I(ee.resourceId))return g({ok:!1,error:"Worker was not found."},404);let pe=String(H.action??"");if(pe==="restart"){if(String(H.confirm??"")!==ee.name)return g({ok:!1,error:`Type "${ee.name}" to restart this worker.`},409);let ve=_.find((Qe)=>Qe.id===ee.target.operationId);if(!ve)return g({ok:!1,error:"The allowlisted worker restart operation is unavailable."},409);let Pe=await Ya(o,V,ve),jt=ot.reconcileWorker(ee.id,Pe.ok?"in_sync":"unavailable",{...ee.observedState,lastRestartAt:new Date().toISOString(),command:Pe.command??null,error:Pe.error??Pe.stderr??null});return ne("worker_restarted",{workerId:ee.id,ok:Pe.ok},ee.resourceId),g({...Pe,worker:jt},Pe.ok?200:409)}if(pe==="scale")return g({ok:!1,error:ee.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 g({ok:!1,error:"Action must be restart or scale."},422)}}if(S.pathname.startsWith("/api/telemetry/")){let l=a.environments.get(V),p=new tc(a.store),v=a.store.listResources(a.project.id,l?.id),b=["/api/telemetry/query","/api/telemetry/tail","/api/telemetry/export","/api/telemetry/saved-queries","/api/telemetry/refresh"].includes(S.pathname)?"runtime:logs":"runtime:read",I=B.role==="admin"||!!l&&Xi(B,l.id,b),A=I?v:v.filter((W)=>st(B,W.id,b)),E=(W)=>lb(A,I,W),_=(W)=>{let ne=new Date,H={"1h":3600000,"6h":21600000,"24h":86400000,"7d":604800000,"30d":2592000000},ee=String(W.to??ne.toISOString()),pe=String(W.from??new Date(new Date(ee).getTime()-(H[String(W.range??"1h")]??H["1h"])).toISOString()),ve=(jt)=>{let Qe=(Array.isArray(jt)?jt:String(jt??"").split(",")).map(String).filter(Boolean);return Qe.length?Qe:void 0},Pe=ve(W.kinds)?.filter((jt)=>["metric","log","trace","request","event"].includes(jt));return{projectId:a.project.id,environmentId:l?.id,resourceIds:E(W.resources),kinds:Pe,names:ve(W.names),sources:ve(W.sources),levels:ve(W.levels),from:pe,to:ee,text:String(W.text??"")||void 0,traceId:String(W.traceId??"")||void 0,requestId:String(W.requestId??"")||void 0,deploymentId:String(W.deploymentId??"")||void 0,releaseId:String(W.releaseId??"")||void 0,workloadId:String(W.workloadId??"")||void 0,cursor:String(W.cursor??"")||void 0,limit:Number(W.limit)||void 0}},z=Object.fromEntries(S.searchParams.entries()),L=(W=!1)=>zu({controlPlane:a.store,projectId:a.project.id,environmentId:l?.id,config:o,environment:V,force:W,lightweight:!W}),ce=()=>{let W=a.store.getSetting(`telemetry.collection:${a.project.id}:${l?.id??"all"}`)??{};return{generatedAt:String(W.generatedAt??new Date().toISOString()),cached:!0,statuses:Array.isArray(W.statuses)?W.statuses:[],errors:Array.isArray(W.errors)?W.errors:[],policy:W.policy??qo(a.store,a.project.id)}};if(S.pathname==="/api/telemetry/status"&&f.method==="GET"){L(!1);let W=ce(),ne=I?W.statuses:p.status(a.project.id,l?.id,W.policy.rawDays,W.policy.samplingRate,A.map((ee)=>ee.id)),H=ne.reduce((ee,pe)=>ee+pe.estimatedDailyBytes*30,0);return g({ok:!0,generatedAt:W.generatedAt,cached:W.cached,sources:ne,errors:I?W.errors:[],policy:W.policy,retention:{rawDays:W.policy.rawDays,downsampleAfterDays:W.policy.downsampleAfterDays,downsampleBucketMs:W.policy.downsampleBucketMs,maxRecords:W.policy.maxRecords},estimatedMonthlyBytes:H,estimatedMonthlyCostUsd:qb(H,W.policy),costEstimateConfigured:W.policy.estimatedStorageUsdPerGbMonth>0})}if(S.pathname==="/api/telemetry/settings"&&f.method==="GET")return g({ok:!0,policy:qo(a.store,a.project.id)});if(S.pathname==="/api/telemetry/settings"&&f.method==="PATCH"){let W=Ub(a.store,a.project.id,await x(f));return yb(a.project.id),g({ok:!0,policy:W})}if(S.pathname==="/api/telemetry/query"&&f.method==="GET"){L(!1);let W=ce();return g({ok:!0,collection:{generatedAt:W.generatedAt,cached:W.cached},...p.query(_(z))})}if(S.pathname==="/api/telemetry/tail"&&f.method==="GET"){L(!1);let W=new TextEncoder,ne=new Date,H=_({...z,kinds:z.kinds||"log,request,event,trace",from:z.from||new Date(ne.getTime()-120000).toISOString(),to:ne.toISOString(),limit:Math.min(1000,Number(z.limit)||200),cursor:void 0}),ee=f.headers.get("last-event-id")||String(z.cursor??"")||void 0,pe,ve=!1,Pe=!1,jt=new ReadableStream({start(Qe){let Gr=()=>{if(ve)return;if(ve=!0,pe)clearInterval(pe);f.signal.removeEventListener("abort",Gr);try{Qe.close()}catch{}},pp=async()=>{if(ve||Pe)return;Pe=!0;try{let In=p.tail({...H,to:new Date(Date.now()+1000).toISOString()},ee);for(let mp of In.records)ee=Vb(mp)??ee,Qe.enqueue(W.encode(`id: ${ee??""}
|
|
694
|
+
event: record
|
|
695
|
+
data: ${JSON.stringify(mp)}
|
|
696
|
+
|
|
697
|
+
`));if(In.cursor)ee=In.cursor}catch(In){Qe.enqueue(W.encode(`event: error
|
|
698
|
+
data: ${JSON.stringify({message:In instanceof Error?In.message:String(In)})}
|
|
699
|
+
|
|
700
|
+
`))}finally{Pe=!1}};pp(),pe=setInterval(()=>{if(pp(),!ve)Qe.enqueue(W.encode(`event: heartbeat
|
|
701
|
+
data: ${JSON.stringify({cursor:ee,at:new Date().toISOString()})}
|
|
702
|
+
|
|
703
|
+
`))},5000),pe.unref?.(),f.signal.addEventListener("abort",Gr,{once:!0})},cancel(){if(ve=!0,pe)clearInterval(pe)}});return new Response(jt,{headers:{"cache-control":"no-cache, no-transform",connection:"keep-alive","content-type":"text/event-stream; charset=utf-8","x-accel-buffering":"no"}})}if(S.pathname==="/api/telemetry/series"&&f.method==="GET"){L(!1);let W=ce(),ne=["sum","avg","min","max","count","p50","p90","p95","p99"].includes(String(z.aggregation))?z.aggregation:"avg",H=_({...z,kinds:"metric",limit:5000}),ee=p.series({...H,bucketMs:Number(z.bucketMs)||60000,aggregation:ne,timezone:String(z.timezone??"UTC"),compareFrom:z.compareFrom,compareTo:z.compareTo});return g({ok:!0,collection:{generatedAt:W.generatedAt,cached:W.cached},query:{aggregation:ne,bucketMs:Number(z.bucketMs)||60000,timezone:String(z.timezone??"UTC")},series:ee})}if(S.pathname==="/api/telemetry/refresh"&&f.method==="POST")return g({ok:!0,...await L(!0)});if(S.pathname==="/api/telemetry/export"&&f.method==="POST"){let W=await x(f);await L(!1);let ne=p.query({..._(W),limit:Math.min(5000,Number(W.limit)||5000),cursor:void 0});if((W.format==="csv"?"csv":"json")==="json")return new Response(JSON.stringify({exportedAt:new Date().toISOString(),query:_(W),...ne},null,2),{headers:{"content-disposition":'attachment; filename="ts-cloud-telemetry.json"',"content-type":"application/json; charset=utf-8"}});let ee=["timestamp","kind","source","name","level","value","unit","message","traceId","requestId","deploymentId","releaseId","workloadId"],pe=[ee.join(","),...ne.records.map((ve)=>ee.map((Pe)=>`"${String(ve[Pe]??"").replaceAll('"','""')}"`).join(","))].join(`
|
|
704
|
+
`);return new Response(pe,{headers:{"content-disposition":'attachment; filename="ts-cloud-telemetry.csv"',"content-type":"text/csv; charset=utf-8"}})}if(S.pathname==="/api/telemetry/saved-queries"&&f.method==="GET"){let W=re(B);return g({ok:!0,queries:p.listSavedQueries(a.project.id,W.actor?.id)})}if(S.pathname==="/api/telemetry/saved-queries"&&f.method==="POST"){let W=await x(f),ne=re(B);return g({ok:!0,query:p.saveQuery(a.project.id,ne.actor?.id,String(W.name??""),_(W.query??W))},201)}if(S.pathname==="/api/telemetry/saved-queries"&&f.method==="DELETE"){let W=await x(f),ne=re(B),H=p.deleteSavedQuery(a.project.id,ne.actor?.id,String(W.id??""));return g({ok:H},H?200:404)}}if(S.pathname.startsWith("/api/configuration")){let l=a.environments.get(V),p=B.role==="admin"||!!qt.capabilities?.includes("secrets:read"),v=B.role==="admin"||!!qt.capabilities?.includes("secrets:write"),b={projectId:a.project.id,environmentId:l?.id},I={"cache-control":"no-store"};if(S.pathname==="/api/configuration"&&f.method==="GET"){let A=Object.fromEntries(S.searchParams),E=A.scopeType||A.scopeId?Ji(A,b):void 0,_=["variable","secret"].includes(String(A.kind))?A.kind:void 0,z=E?.type==="preview"?He.previews.getInstance(E.id):void 0,L=z?He.previews.getDefinition(z.definitionId):void 0,ce=E?await xt.resolve({projectId:a.project.id,environmentId:E.environmentId,resourceId:E.resourceId,functionId:E.type==="function"?E.id:void 0,previewId:E.previewId,trustedPreview:!!z&&!z.fork,allowedPreviewSecrets:L?.inheritedSecrets,nativeReferences:!0,canReadSecretMetadata:p}):void 0,W=a.store.listResources(a.project.id);return g({ok:!0,entries:xt.list({projectId:a.project.id,scope:E,kind:_,search:A.search,canReadSecretMetadata:p}),effectiveEntries:ce?Object.values(ce.entries).filter((ne)=>!_||ne.kind===_).filter((ne)=>!A.search||ne.key.toLowerCase().includes(String(A.search).toLowerCase())):[],configurationHash:ce?.configurationHash,warnings:ce?.warnings??[],scopes:{project:a.project,environments:a.store.listEnvironments(a.project.id),resources:W.filter((ne)=>ne.kind!=="function"),functions:W.filter((ne)=>ne.kind==="function"),previews:He.previews.listInstances({projectId:a.project.id}).filter((ne)=>ne.status!=="destroyed").map((ne)=>({id:ne.id,name:ne.name,environmentId:ne.baseEnvironmentId,resourceId:ne.resourceId,fork:ne.fork,status:ne.status}))}},200,I)}if(S.pathname==="/api/configuration/export"&&f.method==="GET"){let A=Ji(Object.fromEntries(S.searchParams),b);return new Response(xt.exportVariables({projectId:a.project.id,scope:A}),{headers:{...I,"content-disposition":'attachment; filename="ts-cloud.env"',"content-type":"text/plain; charset=utf-8"}})}if(S.pathname==="/api/configuration/plan"&&f.method==="POST"){let A=await x(f),E=Ji(A,b),_=A.values&&typeof A.values==="object"&&!Array.isArray(A.values)?Object.fromEntries(Object.entries(A.values).map(([z,L])=>[z,String(L)])):{};return g({ok:!0,plan:xt.plan({projectId:a.project.id,scope:E,values:_,removeMissing:A.removeMissing===!0})},200,I)}if(S.pathname==="/api/configuration"&&f.method==="POST"){let A=await x(f),E=Ji(A,b),_=A.kind==="secret"?"secret":"variable",z=String(A.key??"");if(_==="secret"&&!v)return g({ok:!1,error:"Secret write permission is required."},403,I);try{let L=await xt.set({organizationId:a.organization.id,projectId:a.project.id,scope:E,key:z,kind:_,value:A.value==null?void 0:String(A.value),reference:A.reference==null?void 0:String(A.reference),backend:A.backend,required:A.required===!0,expectedVersion:A.expectedVersion==null?void 0:Number(A.expectedVersion),confirmed:String(A.confirm??"")===z,idempotencyKey:f.headers.get("idempotency-key")??A.idempotencyKey,actorId:re(B).actor?.id});return g({ok:!0,entry:xt.list({projectId:a.project.id,scope:E,canReadSecretMetadata:p}).find((ce)=>ce.id===L.entry.id),mutation:L.mutation,warnings:L.warnings},L.mutation.added.length?201:200,I)}catch(L){return g({ok:!1,error:L instanceof Error?L.message:String(L)},409,I)}}if(S.pathname==="/api/configuration/import"&&f.method==="POST"){let A=await x(f),E=Ji(A,b),_=Array.isArray(A.secretKeys)?A.secretKeys.map(String):[];if(_.length&&!v)return g({ok:!1,error:"Secret write permission is required."},403,I);try{let z=await xt.importDotenv({organizationId:a.organization.id,projectId:a.project.id,scope:E,source:String(A.source??""),secretKeys:_,backend:A.backend,confirmed:A.confirm==="import",idempotencyKey:f.headers.get("idempotency-key")??A.idempotencyKey,actorId:re(B).actor?.id});return g({ok:z.document.valid,diagnostics:z.document.diagnostics,mutation:z.mutation,warnings:z.warnings},z.document.valid?200:422,I)}catch(z){return g({ok:!1,error:z instanceof Error?z.message:String(z)},409,I)}}if(S.pathname==="/api/configuration/dependencies"&&f.method==="POST"){let A=await x(f),E=Vr.get(String(A.entryId??"")),_=a.store.getResource(String(A.resourceId??""));if(!E||E.projectId!==a.project.id||!_||_.projectId!==a.project.id)return g({ok:!1,error:"Configuration entry or dependent resource was not found."},404,I);return g({ok:!0,dependency:Vr.setDependency({entryId:E.id,resourceId:_.id,injectionTarget:["native_reference","file"].includes(String(A.injectionTarget))?A.injectionTarget:"environment",required:A.required!==!1,requiresRedeploy:A.requiresRedeploy!==!1,lastDeployedVersion:A.lastDeployedVersion==null?void 0:Number(A.lastDeployedVersion)})},200,I)}if(S.pathname==="/api/configuration/transfer"&&f.method==="POST"){let A=await x(f),E=Vr.get(String(A.id??"")),_=Ji({...A,scopeType:A.targetScopeType,scopeId:A.targetScopeId},b);if(!E||E.projectId!==a.project.id)return g({ok:!1,error:"Configuration entry was not found."},404,I);if(E.kind==="secret"&&!v)return g({ok:!1,error:"Secret write permission is required."},403,I);try{let z=await xt.transfer({entryId:E.id,targetScope:_,mode:A.mode==="move"?"move":"copy",confirmed:A.confirm===E.key,actorId:re(B).actor?.id,idempotencyKey:f.headers.get("idempotency-key")??A.idempotencyKey});return g({ok:!0,entry:xt.list({projectId:a.project.id,scope:_,canReadSecretMetadata:p}).find((L)=>L.id===z.entry.id),mutation:z.mutation},200,I)}catch(z){return g({ok:!1,error:z instanceof Error?z.message:String(z)},409,I)}}if(S.pathname==="/api/configuration/bulk"&&f.method==="POST"){let A=await x(f),E=Array.isArray(A.ids)?A.ids.map(String).slice(0,500):[],_=E.map((L)=>Vr.get(L)).filter((L)=>!!L&&L.projectId===a.project.id);if(_.length!==E.length)return g({ok:!1,error:"One or more configuration entries were not found."},404,I);if(_.some((L)=>L.kind==="secret")&&!v)return g({ok:!1,error:"Secret write permission is required."},403,I);if(A.action!=="delete"||A.confirm!=="bulk")return g({ok:!1,error:"Bulk deletion requires action delete and confirm bulk."},409,I);let z=[];try{for(let L of _)z.push(await xt.remove({entryId:L.id,expectedVersion:L.version,confirmed:!0,actorId:re(B).actor?.id}));return g({ok:!0,removed:z.flatMap((L)=>L.removed),affectedResourceIds:[...new Set(z.flatMap((L)=>L.affectedResourceIds))].sort()},200,I)}catch(L){return g({ok:!1,error:L instanceof Error?L.message:String(L),partial:z.flatMap((ce)=>ce.removed)},409,I)}}if(S.pathname==="/api/configuration/reveal"&&f.method==="POST"){let A=await x(f),E=ze.resolveSession(f);try{return g({ok:!0,value:await xt.reveal({entryId:String(A.id??""),canRevealSecrets:p,recentlyAuthenticated:!K||!!E&&G.isRecentlyAuthenticated(E),actorId:re(B).actor?.id})},200,I)}catch(_){return g({ok:!1,error:_ instanceof Error?_.message:String(_)},403,I)}}if(S.pathname==="/api/configuration"&&f.method==="DELETE"){let A=await x(f),E=Vr.get(String(A.id??""));if(E?.kind==="secret"&&!v)return g({ok:!1,error:"Secret write permission is required."},403,I);if(!E||E.projectId!==a.project.id)return g({ok:!1,error:"Configuration entry was not found."},404,I);try{return g({ok:!0,mutation:await xt.remove({entryId:E.id,expectedVersion:Number(A.expectedVersion),confirmed:String(A.confirm??"")===E.key,actorId:re(B).actor?.id})},200,I)}catch(_){return g({ok:!1,error:_ instanceof Error?_.message:String(_)},409,I)}}}if(S.pathname.startsWith("/api/fleet")){let l=re(B).actor?.id,p=(v,b=409)=>g({ok:!1,error:v instanceof Error?v.message:String(v)},b,{"cache-control":"no-store"});if(S.pathname==="/api/fleet"&&f.method==="GET")return g({ok:!0,servers:Zi.list(a.project.id),resources:a.store.listResources(a.project.id),operations:xe.list({projectId:a.project.id,limit:200}).filter((v)=>v.operation.kind.startsWith("fleet."))},200,{"cache-control":"no-store"});if(S.pathname==="/api/fleet"&&f.method==="POST"){let v=await x(f);try{return g({ok:!0,server:lr.enroll({organizationId:a.organization.id,projectId:a.project.id,name:String(v.name??""),provider:["aws","hetzner"].includes(String(v.provider))?v.provider:"ssh",providerId:v.providerId?String(v.providerId):void 0,region:v.region?String(v.region):void 0,zone:v.zone?String(v.zone):void 0,endpoint:String(v.endpoint??""),sshUser:String(v.sshUser??"deploy"),sshPort:v.sshPort?Number(v.sshPort):22,credentialRef:String(v.credentialRef??""),roles:Array.isArray(v.roles)?v.roles:[],labels:v.labels&&typeof v.labels==="object"?v.labels:{}})},201)}catch(b){return p(b,422)}}if(S.pathname==="/api/fleet/action"&&f.method==="POST"){let v=await x(f),b=String(v.id??""),I=String(v.action??"");try{if(I==="test")return g({ok:!0,server:await lr.test(b)});if(I==="validate")return g({ok:!0,server:await lr.validate(b)});if(I==="review_host_key")return g({ok:!0,server:lr.reviewHostKey(b,String(v.fingerprint??""))});if(I==="bootstrap")return g({ok:!0,...lr.bootstrap(b,v.confirmed===!0)},v.confirmed===!0?202:200);if(I==="heartbeat")return g({ok:!0,server:lr.heartbeat(b,{usage:v.usage&&typeof v.usage==="object"?v.usage:{}})});if(I==="drain")return g({ok:!0,server:lr.drain(b,v.completed===!0)});if(I==="uncordon")return g({ok:!0,server:lr.uncordon(b)});if(I==="archive")return g({ok:!0,server:lr.archive(b,String(v.confirmation??""))});return p("Unsupported fleet action.",422)}catch(A){return p(A)}}}if(S.pathname.startsWith("/api/capacity")){let l=(p,v=409)=>g({ok:!1,error:p instanceof Error?p.message:String(p)},v,{"cache-control":"no-store"});if(S.pathname==="/api/capacity"&&f.method==="GET")return g({ok:!0,pools:Hr.listPools(a.project.id),placements:Hr.listPlacements(a.project.id),servers:Zi.list(a.project.id)},200,{"cache-control":"no-store"});if(S.pathname==="/api/capacity"&&f.method==="POST"){let p=await x(f);try{return g({ok:!0,pool:Hr.createPool({organizationId:a.organization.id,projectId:a.project.id,name:String(p.name??""),purpose:String(p.purpose??"application"),backend:String(p.backend??"server"),region:p.region?String(p.region):void 0,architecture:p.architecture?String(p.architecture):void 0,labels:p.labels&&typeof p.labels==="object"?p.labels:{},requiredServerLabels:p.requiredServerLabels&&typeof p.requiredServerLabels==="object"?p.requiredServerLabels:{},toleratedTaints:Array.isArray(p.toleratedTaints)?p.toleratedTaints.map(String):[],capacity:p.capacity&&typeof p.capacity==="object"?p.capacity:{},maxWorkloads:Number(p.maxWorkloads??10),costWeight:Number(p.costWeight??1),spreadKey:p.spreadKey?String(p.spreadKey):void 0,concurrency:Number(p.concurrency??1),ephemeralWorkspaces:!0,allowProductionSecrets:!1,status:"active"})},201)}catch(v){return l(v,422)}}if(S.pathname==="/api/capacity/member"&&f.method==="POST"){let p=await x(f);try{return Hr.addMember(String(p.poolId??""),String(p.serverId??"")),g({ok:!0,pool:Hr.getPool(String(p.poolId??""))})}catch(v){return l(v,422)}}if(S.pathname==="/api/capacity/explain"&&f.method==="POST"){let p=await x(f);try{return g({ok:!0,decisions:Qu.explain(a.project.id,{purpose:String(p.purpose??"application"),resources:p.resources&&typeof p.resources==="object"?p.resources:{},region:p.region?String(p.region):void 0,architecture:p.architecture?String(p.architecture):void 0,labels:p.labels&&typeof p.labels==="object"?p.labels:{}})})}catch(v){return l(v,422)}}if(S.pathname==="/api/capacity/action"&&f.method==="POST"){let p=await x(f);try{if(p.action==="drain")return g({ok:!0,...Qu.drainPool(String(p.poolId??""))});if(p.action==="enable")return g({ok:!0,pool:Hr.updatePool(String(p.poolId??""),{status:"active"})});if(p.action==="disable")return g({ok:!0,pool:Hr.updatePool(String(p.poolId??""),{status:"disabled"})});return l("Unsupported capacity action.",422)}catch(v){return l(v,422)}}}if(S.pathname.startsWith("/api/regions")){let l=(p,v=409)=>g({ok:!1,error:p instanceof Error?p.message:String(p)},v,{"cache-control":"no-store"});if(S.pathname==="/api/regions"&&f.method==="GET")return g({ok:!0,topologies:wn.list(a.project.id).map((p)=>({topology:p,targets:wn.targets(p.id),channels:wn.channels(p.id),route:wn.route(p.id),executions:wn.executions(p.id)}))},200,{"cache-control":"no-store"});if(S.pathname==="/api/regions"&&f.method==="POST"){let p=await x(f);try{return g({ok:!0,topology:Yu.create({organizationId:a.organization.id,projectId:a.project.id,environmentId:a.environments.get(V)?.id,name:String(p.name??""),hostname:String(p.hostname??""),regions:Array.isArray(p.regions)?p.regions:[],trafficPolicy:p.trafficPolicy==="weighted"||p.trafficPolicy==="latency"?p.trafficPolicy:"active_passive",dataPolicy:{replicate:Array.isArray(p.replicate)?p.replicate:["s3","dynamodb","secrets"],maxLagSeconds:Number(p.maxLagSeconds??30),retainOnDestroy:p.retainOnDestroy!==!1},dnsProvider:"route53",cdnEnabled:p.cdnEnabled===!0,wafEnabled:p.wafEnabled===!0})},201)}catch(v){return l(v,422)}}if(S.pathname==="/api/regions/action"&&f.method==="POST"){let p=await x(f);try{return g({ok:!0,...Yu.enqueue({topologyId:String(p.topologyId??""),kind:String(p.action??""),targetRegion:p.targetRegion?String(p.targetRegion):void 0,revision:p.revision?String(p.revision):void 0,manifest:p.manifest&&typeof p.manifest==="object"?p.manifest:{},confirmation:p.confirmation?String(p.confirmation):void 0,deleteData:p.deleteData===!0})},202)}catch(v){return l(v,422)}}}if(S.pathname.startsWith("/api/maintenance")){let l=(p,v=409)=>g({ok:!1,error:p instanceof Error?p.message:String(p)},v,{"cache-control":"no-store"});if(S.pathname==="/api/maintenance"&&f.method==="GET")return g({ok:!0,manifests:kr.manifests(a.organization.id),windows:kr.windows(a.project.id),campaigns:kr.campaigns(a.project.id).map((p)=>({campaign:p,targets:kr.targets(p.id)})),cleanups:kr.cleanups(a.project.id),drills:kr.drills(a.project.id)},200,{"cache-control":"no-store"});if(S.pathname==="/api/maintenance/cleanup-preview"&&f.method==="POST"){let p=await x(f);try{return g({ok:!0,plan:await dc.previewCleanup({projectId:a.project.id,kind:String(p.kind??"operations"),criteria:{olderThanDays:Number(p.olderThanDays??30)}},Zu)},201)}catch(v){return l(v,422)}}if(S.pathname==="/api/maintenance/cleanup-apply"&&f.method==="POST"){let p=await x(f);try{return g({ok:!0,...dc.enqueueCleanup(String(p.planId??""),String(p.confirmation??""))},202)}catch(v){return l(v,422)}}if(S.pathname==="/api/maintenance/drill"&&f.method==="POST"){let p=await x(f);try{return g({ok:!0,drill:kr.createDrill({projectId:a.project.id,scenario:String(p.scenario??"control_plane"),isolatedTarget:String(p.isolatedTarget??""),expectedRpoMinutes:Number(p.expectedRpoMinutes??60),expectedRtoMinutes:Number(p.expectedRtoMinutes??30),recoveryPointId:p.recoveryPointId?String(p.recoveryPointId):void 0,topologyId:p.topologyId?String(p.topologyId):void 0})},201)}catch(v){return l(v,422)}}if(S.pathname==="/api/maintenance/drill-run"&&f.method==="POST"){let p=await x(f);try{return g({ok:!0,...dc.enqueueDrill(String(p.drillId??""))},202)}catch(v){return l(v,422)}}}if(S.pathname.startsWith("/api/volumes")){let l=a.environments.get(V),p=re(B).actor?.id,v=(b,I=409)=>g({ok:!1,error:b instanceof Error?b.message:String(b)},I,{"cache-control":"no-store"});if(S.pathname==="/api/volumes"&&f.method==="GET"){let b=ac.inventory(a.project.id,l?.id),I=a.store.listResources(a.project.id,l?.id).map((A)=>({id:A.id,name:A.name,slug:A.slug,kind:A.kind,provider:A.provider,providerId:A.providerId}));return g({ok:!0,volumes:b,resources:I,operations:xe.list({projectId:a.project.id,limit:100}).filter((A)=>A.operation.kind.startsWith("volume.")),recoveryPoints:Je.listRecoveryPoints(a.project.id).filter((A)=>A.kind==="volume"),providers:cc.map((A)=>({provider:A.provider,type:A.type,capabilities:A.capabilities()}))},200,{"cache-control":"no-store"})}if(S.pathname==="/api/volumes"&&f.method==="POST"){let b=await x(f);try{return g({ok:!0,...wr.create({organizationId:a.organization.id,projectId:a.project.id,environmentId:l?.id,resourceId:b.resourceId?String(b.resourceId):void 0,name:String(b.name??""),provider:String(b.provider??"docker"),type:b.type==="docker"?"docker":b.type,capacityBytes:b.capacityBytes==null?void 0:Number(b.capacityBytes),filesystem:b.filesystem?String(b.filesystem):void 0,encrypted:b.encrypted===!0,desiredState:b.desiredState&&typeof b.desiredState==="object"?b.desiredState:{},actorId:p})},202,{"cache-control":"no-store"})}catch(I){return v(I,422)}}if(S.pathname==="/api/volumes/attach"&&f.method==="POST"){let b=await x(f);try{return g({ok:!0,...wr.attach(String(b.volumeId??""),{resourceId:String(b.resourceId??""),targetPath:String(b.targetPath??""),readOnly:b.readOnly===!0,uid:b.uid==null?void 0:Number(b.uid),gid:b.gid==null?void 0:Number(b.gid),mode:b.mode?String(b.mode):void 0,propagation:b.propagation,driverOptions:b.driverOptions&&typeof b.driverOptions==="object"?b.driverOptions:{},actorId:p})},202)}catch(I){return v(I,422)}}if(S.pathname==="/api/volumes/detach"&&f.method==="POST"){let b=await x(f);try{return g({ok:!0,...wr.detach(String(b.volumeId??""),String(b.attachmentId??""),{force:b.force===!0,drained:b.drained===!0,unmounted:b.unmounted===!0,confirmation:b.confirmation?String(b.confirmation):void 0,actorId:p})},202)}catch(I){return v(I)}}if(S.pathname==="/api/volumes/resize"&&f.method==="POST"){let b=await x(f);try{return g({ok:!0,...wr.resize(String(b.volumeId??""),Number(b.capacityBytes),{drained:b.drained===!0,actorId:p})},202)}catch(I){return v(I,422)}}if(S.pathname==="/api/volumes/snapshot"&&f.method==="POST"){let b=await x(f);try{return g({ok:!0,...wr.snapshot(String(b.volumeId??""),{name:b.name?String(b.name):void 0,actorId:p})},202)}catch(I){return v(I,422)}}if(S.pathname==="/api/volumes/restore"&&f.method==="POST"){let b=await x(f);try{return g({ok:!0,...wr.restore(String(b.snapshotId??""),{name:String(b.name??""),actorId:p})},202)}catch(I){return v(I,422)}}if(S.pathname==="/api/volumes/discover"&&f.method==="POST")try{return g({ok:!0,volumes:await wr.discover({organizationId:a.organization.id,projectId:a.project.id,environmentId:l?.id,actorId:p})})}catch(b){return v(b,502)}if(S.pathname==="/api/volumes/adopt"&&f.method==="POST"){let b=await x(f);try{return g({ok:!0,volume:wr.adopt(String(b.volumeId??""),{name:String(b.name??""),actorId:p})})}catch(I){return v(I,422)}}if(S.pathname==="/api/volumes"&&f.method==="DELETE"){let b=await x(f),I=ze.resolveSession(f);try{return g({ok:!0,...wr.delete(String(b.volumeId??""),{recentAuthAt:!K||I&&G.isRecentlyAuthenticated(I)?new Date().toISOString():void 0,confirmation:b.confirmation?String(b.confirmation):void 0,backupOverride:b.backupOverride===!0,backupOverrideConfirmation:b.backupOverrideConfirmation?String(b.backupOverrideConfirmation):void 0,actorId:p})},202)}catch(A){return v(A)}}}if(S.pathname==="/api/backups"&&f.method==="GET"){let l=a.environments.get(V),p=Je.listPolicies(a.project.id,l?.id),v=new Set(p.map((_)=>_.id)),b=Je.listRecoveryPoints(a.project.id).filter((_)=>!_.policyId||v.has(_.policyId)),I=Je.listJobs(a.project.id).filter((_)=>!_.policyId||v.has(_.policyId)),A=(_)=>({..._,credentialRef:void 0,encryptionKeyRef:void 0,credentialsConfigured:!!_.credentialRef,clientEncryptionConfigured:!!_.encryptionKeyRef}),E=await Promise.all(Je.listDestinations(a.project.id).map(async(_)=>({...A(_),credentialStatus:await Cg(_,Sr)})));return g({ok:!0,destinations:E,policies:p,recoveryPoints:b,jobs:I,coverage:Je.coverage(a.project.id).filter((_)=>v.has(_.policy.id)),resources:l?a.store.listResources(a.project.id,l.id).map((_)=>({id:_.id,name:_.name,slug:_.slug,kind:_.kind})):[]})}if(S.pathname==="/api/backups/destinations"&&f.method==="POST"){let l=await x(f),p=String(l.name??"").trim(),v=String(l.provider??""),b=String(l.encryption??"provider"),I=`secret://data-services/backups/${a.project.id}/${p}`,A=[];if(!["aws_s3","s3_compatible","aws_backup"].includes(v))return g({ok:!1,error:"A supported backup destination provider is required."},422);if(!["provider","client_side","both"].includes(b))return g({ok:!1,error:"Encryption must be provider, client_side, or both."},422);try{let E,_;if(l.credentials&&typeof l.credentials==="object"&&!Array.isArray(l.credentials))E=`${I}/credentials`,await Sr.put(E,JSON.stringify(l.credentials)),A.push(E);if(b!=="provider"){let L=String(l.encryptionKey??"");if(L.length<32)throw Error("Client-side encryption keys must contain at least 32 characters.");_=`${I}/encryption-key`,await Sr.put(_,L),A.push(_)}let z=Je.createDestination({organizationId:a.organization.id,projectId:a.project.id,name:p,provider:v,endpoint:l.endpoint?String(l.endpoint):void 0,endpointPolicy:l.endpointPolicy==="allow_private"?"allow_private":"public_https",bucket:l.bucket?String(l.bucket):void 0,prefix:String(l.prefix??""),region:l.region?String(l.region):Wr,forcePathStyle:l.forcePathStyle===!0,credentialRef:E,encryption:b,encryptionKeyRef:_,immutability:l.immutability&&typeof l.immutability==="object"&&!Array.isArray(l.immutability)?l.immutability:{},status:"untested"});return g({ok:!0,destination:{...z,credentialRef:void 0,encryptionKeyRef:void 0,credentialsConfigured:!!E,clientEncryptionConfigured:!!_}},201)}catch(E){for(let _ of A)await Sr.remove(_).catch(()=>{});return g({ok:!1,error:E instanceof Error?E.message:String(E)},422)}}if(S.pathname==="/api/backups/destinations/test"&&f.method==="POST"){let l=await x(f),p=Je.getDestination(String(l.id??""));if(!p||p.projectId!==a.project.id)return g({ok:!1,error:"Backup destination was not found."},404);if(p.provider==="aws_backup")return g({ok:!1,error:"AWS Backup destinations are verified by creating a provider recovery point."},422);try{return await Gu.test(p),g({ok:!0,destination:Je.recordDestinationTest(p.id,{ok:!0})})}catch(v){let b=v instanceof Error?v.message:String(v);return Je.recordDestinationTest(p.id,{ok:!1,error:b}),g({ok:!1,error:b},502)}}if(S.pathname==="/api/backups/policies"&&f.method==="POST"){let l=await x(f),p=a.environments.get(V),v=Je.getDestination(String(l.destinationId??"")),b=String(l.resourceKind??""),I=l.dataServiceId?String(l.dataServiceId):void 0,A=I?Be.get(I):void 0,E=l.resourceId?String(l.resourceId):void 0,_=E?a.store.getResource(E):void 0;if(!p)return g({ok:!1,error:"Environment was not found."},404);if(!v||v.projectId!==a.project.id)return g({ok:!1,error:"Backup destination was not found."},404);if(!["managed_database","logical_database","volume","files","control_plane","infrastructure"].includes(b))return g({ok:!1,error:"A supported backup resource kind is required."},422);if(I&&(!A||A.projectId!==a.project.id||A.environmentId!==p.id))return g({ok:!1,error:"Data service was not found in this environment."},404);if(E&&(!_||_.projectId!==a.project.id||_.environmentId!==p.id))return g({ok:!1,error:"Resource was not found in this environment."},404);if(b==="managed_database"&&!A)return g({ok:!1,error:"Managed database policies require a data service."},422);if(b==="logical_database"&&(!A||!["container","server"].includes(A.provider)))return g({ok:!1,error:"Logical database policies require an on-box data service."},422);if(b==="volume"&&(!_||!/^[A-Za-z0-9][A-Za-z0-9_.-]{1,127}$/.test(String(l.volumeName??""))))return g({ok:!1,error:"Volume policies require a scoped resource and valid volumeName."},422);let z=Array.isArray(l.includePatterns)?l.includePatterns.map(String).filter(Boolean):[];if(b==="files"&&(!_||!z.length))return g({ok:!1,error:"File policies require a scoped resource and at least one project-relative include path."},422);if(b==="control_plane"&&v.encryption==="provider")return g({ok:!1,error:"Control-plane policies require a destination with client-side encryption."},422);if(b==="infrastructure"&&(v.provider!=="aws_backup"||!z.some((L)=>L.startsWith("resource:arn:"))||!z.some((L)=>L.startsWith("role:arn:"))))return g({ok:!1,error:"Infrastructure policies require an AWS Backup destination plus resource:<arn> and role:<arn> include values."},422);try{let L=Je.createPolicy({organizationId:a.organization.id,projectId:a.project.id,environmentId:p.id,resourceId:E,dataServiceId:I,destinationId:v.id,name:String(l.name??"").trim(),resourceKind:b,schedule:String(l.schedule??"daily"),timezone:String(l.timezone??"UTC"),retention:l.retention&&typeof l.retention==="object"&&!Array.isArray(l.retention)?l.retention:{keepLast:7,expireAfterDays:30},compression:["none","gzip","zstd"].includes(String(l.compression))?l.compression:"gzip",encryption:["destination","client_side","both"].includes(String(l.encryption))?l.encryption:"destination",includePatterns:b==="volume"?[String(l.volumeName),...z]:z,excludePatterns:Array.isArray(l.excludePatterns)?l.excludePatterns.map(String):[],expectedRpoMinutes:Math.max(1,Number(l.expectedRpoMinutes)||1440),expectedRtoMinutes:Math.max(1,Number(l.expectedRtoMinutes)||120),healthCheckId:l.healthCheckId?String(l.healthCheckId):void 0,enabled:l.enabled!==!1});return g({ok:!0,policy:L},201)}catch(L){return g({ok:!1,error:L instanceof Error?L.message:String(L)},422)}}if(S.pathname==="/api/backups/run"&&f.method==="POST"){let l=await x(f),p=Je.getPolicy(String(l.policyId??"")),v=a.environments.get(V);if(!p||p.projectId!==a.project.id||p.environmentId!==v?.id)return g({ok:!1,error:"Backup policy was not found in this environment."},404);try{let b=Sn.enqueueBackup(p,new Date().toISOString(),re(B).actor?.id);return g({ok:!0,job:b},202)}catch(b){return g({ok:!1,error:b instanceof Error?b.message:String(b)},409)}}if(S.pathname==="/api/backups/verify"&&f.method==="POST"){let l=await x(f),p=Je.getRecoveryPoint(String(l.recoveryPointId??""));if(!p||p.projectId!==a.project.id)return g({ok:!1,error:"Recovery point was not found."},404);return g({ok:!0,job:Sn.enqueueVerification(p)},202)}if(S.pathname==="/api/backups/restore"&&f.method==="POST"){let l=await x(f),p=Je.getRecoveryPoint(String(l.recoveryPointId??"")),v=l.mode==="in_place"?"in_place":"isolated",b=l.target&&typeof l.target==="object"&&!Array.isArray(l.target)?{...l.target,inPlace:v==="in_place"}:{inPlace:v==="in_place"},I=ze.resolveSession(f),A={mode:v,target:b,targetName:String(l.targetName??""),confirm:l.confirm?String(l.confirm):void 0,recentAuth:!K||!!I&&G.isRecentlyAuthenticated(I),downtimeAcknowledged:l.downtimeAcknowledged===!0,safetyBackupId:l.safetyBackupId?String(l.safetyBackupId):void 0};if(!p||p.projectId!==a.project.id)return g({ok:!1,error:"Recovery point was not found."},404);if(l.drill===!0&&v!=="isolated")return g({ok:!1,error:"Recovery drills must use an isolated target."},422);try{let E=Sn.planRestore(p,A);if(l.execute!==!0)return g({ok:!0,plan:E,executionCreated:!1});let _=Sn.enqueueRestore(p,{...A,drill:l.drill===!0,actorId:re(B).actor?.id});return g({ok:!0,plan:E,job:_},202)}catch(E){return g({ok:!1,error:E instanceof Error?E.message:String(E)},409)}}if(S.pathname==="/api/backups/recovery-points"&&f.method==="POST"){let l=await x(f),p=Je.getRecoveryPoint(String(l.id??""));if(!p||p.projectId!==a.project.id)return g({ok:!1,error:"Recovery point was not found."},404);if(l.held==null&&l.pinned==null)return g({ok:!1,error:"held or pinned must be provided."},422);return g({ok:!0,recoveryPoint:Je.updateRecoveryPoint(p.id,{held:l.held==null?p.held:l.held===!0,pinned:l.pinned==null?p.pinned:l.pinned===!0})})}if(S.pathname==="/api/backups/retention"&&f.method==="POST")return g({ok:!0,jobs:Sn.enqueueRetention()},202);if(S.pathname==="/api/data-services/capabilities"&&f.method==="GET"){let l=String(S.searchParams.get("engine")??""),p=String(S.searchParams.get("provider")??"");if(!["postgres","mysql","mariadb","redis","mongodb","libsql"].includes(l)||!["aws_rds","aws_aurora","aws_elasticache","server","container","external"].includes(p))return g({ok:!1,error:"A supported engine and provider are required."},422);return g({ok:!0,engine:l,provider:p,capabilities:vo(l,p)})}if(S.pathname==="/api/data-services"&&f.method==="GET"){let l=a.environments.get(V),p=Be.list(a.project.id,l?.id).map((v)=>{let b=Be.credential(v.id);return{...v,credentialRef:void 0,credential:b?{configured:!0,username:b.username,version:b.version,rotatedAt:b.rotatedAt}:void 0,dependencies:Be.dependencies(v.id).map((I)=>({resourceId:I.resourceId,requiresRedeploy:I.requiresRedeploy}))}});return g({ok:!0,services:p})}if(S.pathname==="/api/data-services/preview"&&f.method==="POST"){let l=await x(f);if(l.id){let b=Be.get(String(l.id)),I=a.environments.get(V),A=String(l.action??"");if(!b||b.projectId!==a.project.id||b.environmentId!==I?.id)return g({ok:!1,error:"Data service was not found in this environment."},404);if(!nc.includes(A))return g({ok:!1,error:`Action must be one of: ${nc.join(", ")}.`},422);try{return g({ok:!0,plan:Ko.plan(b,A,l.changes??{})})}catch(E){return g({ok:!1,error:E instanceof Error?E.message:String(E)},422)}}let p=String(l.engine??""),v=String(l.provider??"");if(!["postgres","mysql","mariadb","redis","mongodb","libsql"].includes(p)||!["aws_rds","aws_aurora","aws_elasticache","server","container","external"].includes(v))return g({ok:!1,error:"A supported engine and provider are required."},422);return g({ok:!0,capabilities:vo(p,v),defaults:{publicExposure:!1,backupRetentionDays:7,deletionProtection:!0},productionExecutionCreated:!1})}if(S.pathname==="/api/data-services"&&f.method==="POST"){let l=await x(f),p=String(l.engine??""),v=String(l.provider??""),b=a.environments.get(V),I=re(B);if(!b)return g({ok:!1,error:"Environment was not found."},404);if(!["postgres","mysql","mariadb","redis","mongodb","libsql"].includes(p)||!["aws_rds","aws_aurora","aws_elasticache","server","container","external"].includes(v))return g({ok:!1,error:"A supported engine and provider are required."},422);let A={organizationId:a.organization.id,projectId:a.project.id,environmentId:b.id,resourceId:l.resourceId?String(l.resourceId):void 0,name:String(l.name??"").trim(),engine:p,provider:v,placement:String(l.placement??l.name??"").trim(),engineVersion:l.engineVersion?String(l.engineVersion):void 0,plan:String(l.plan??(v==="aws_elasticache"?"cache.t4g.micro":v==="aws_aurora"?"db.serverless":"db.t4g.micro")),storageGb:l.storageGb==null?void 0:Number(l.storageGb),highAvailability:l.highAvailability===!0,publicExposure:l.publicExposure===!0,allowedCidrs:Array.isArray(l.allowedCidrs)?l.allowedCidrs.map(String):[],desiredState:l.desiredState&&typeof l.desiredState==="object"&&!Array.isArray(l.desiredState)?l.desiredState:{},observedState:{},origin:l.adopt===!0?"adopted":"managed",managementEnabled:l.adopt!==!0,ownerActorId:I.actor?.id,username:l.username?String(l.username):void 0};try{if(l.adopt===!0){let _=Be.create({...A,status:"adopted",credentialRef:void 0});return g({ok:!0,service:_,readOnly:!0},201)}if(!Ju({provider:v,engine:p}))return g({ok:!1,error:`No ${v}/${p} provisioning adapter is configured; adopt it read-only or choose a supported provider.`},422);let E=await Ko.create(A);return g({ok:!0,service:E.service,operationId:E.operationId,oneTimeCredential:E.credential},201)}catch(E){return g({ok:!1,error:E instanceof Error?E.message:String(E)},422)}}if(S.pathname==="/api/data-services/connections"&&f.method==="GET"){let l=Be.get(String(S.searchParams.get("id")??"")),p=a.environments.get(V);if(!l||l.projectId!==a.project.id||l.environmentId!==p?.id)return g({ok:!1,error:"Data service was not found in this environment."},404);let v=typeof l.observedState.endpoint==="string"?l.observedState.endpoint:void 0,b=typeof l.observedState.readerEndpoint==="string"?l.observedState.readerEndpoint:void 0,I=Number(l.observedState.port)||(l.engine==="postgres"?5432:l.engine==="redis"?6379:l.engine==="mongodb"?27017:l.engine==="libsql"?8080:3306),A=typeof l.observedState.database==="string"?l.observedState.database:void 0,E=typeof l.observedState.tls==="boolean"?l.observedState.tls:l.provider.startsWith("aws_"),_=[...v?[{type:l.publicExposure?"external":"internal",host:v,port:I,database:A,tls:E}]:[],...b?[{type:"internal",host:b,port:I,database:A,tls:E}]:[],{type:"tunnel",host:v??l.placement,port:I,database:A,tls:E}];return g({ok:!0,serviceId:l.id,guidance:xg(l,_)})}if(S.pathname==="/api/data-services/action"&&f.method==="POST"){let l=await x(f),p=Be.get(String(l.id??"")),v=a.environments.get(V),b=String(l.action??"");if(!p||p.projectId!==a.project.id||p.environmentId!==v?.id)return g({ok:!1,error:"Data service was not found in this environment."},404);if(!nc.includes(b))return g({ok:!1,error:`Action must be one of: ${nc.join(", ")}.`},422);let I=l.changes&&typeof l.changes==="object"&&!Array.isArray(l.changes)?l.changes:{};try{let A=Ko.plan(p,b,I);if(l.execute!==!0)return g({ok:!0,plan:A,productionExecutionCreated:!1});let E=Ko.enqueue(p,b,I,re(B).actor?.id);return g({ok:!0,plan:A,operationId:E},202)}catch(A){return g({ok:!1,error:A instanceof Error?A.message:String(A)},409)}}if(S.pathname==="/api/data-services/dependencies"&&f.method==="POST"){let l=await x(f),p=Be.get(String(l.id??"")),v=a.environments.get(V),b=a.store.getResource(String(l.resourceId??""));if(!p||p.projectId!==a.project.id||p.environmentId!==v?.id)return g({ok:!1,error:"Data service was not found in this environment."},404);if(!b||b.projectId!==a.project.id||b.environmentId!==v?.id)return g({ok:!1,error:"Dependent resource was not found in this environment."},404);if(l.remove===!0)return g({ok:Be.removeDependency(p.id,b.id)});return Be.addDependency({serviceId:p.id,resourceId:b.id,secretRef:p.credentialRef??`secret://data-services/${p.projectId}/${p.name}`,requiresRedeploy:l.requiresRedeploy!==!1}),g({ok:!0,dependencies:Be.dependencies(p.id).map((I)=>({resourceId:I.resourceId,requiresRedeploy:I.requiresRedeploy}))})}if(S.pathname==="/api/data-services/management"&&f.method==="POST"){let l=await x(f),p=Be.get(String(l.id??"")),v=a.environments.get(V);if(!p||p.projectId!==a.project.id||p.environmentId!==v?.id)return g({ok:!1,error:"Data service was not found in this environment."},404);if(p.origin!=="adopted"||l.reviewed!==!0||l.confirm!==p.name)return g({ok:!1,error:`Enabling management requires reviewed=true and typing ${p.name}.`},409);return g({ok:!0,service:Be.update(p.id,p.version,{managementEnabled:!0})})}if(S.pathname==="/api/data-services/reveal"&&f.method==="POST"){let l=await x(f),p=Be.get(String(l.id??"")),v=a.environments.get(V),b=p?Be.credential(p.id):void 0;if(!p||p.projectId!==a.project.id||p.environmentId!==v?.id)return g({ok:!1,error:"Data service was not found in this environment."},404);if(!b)return g({ok:!1,error:"No managed credential is configured."},404);return g({ok:!0,credential:{username:b.username,password:await Sr.resolve(b.secretRef),version:b.version}},200,{"cache-control":"no-store"})}if(S.pathname==="/api/databases"&&f.method==="GET")return g(await Fy(o,V));if(S.pathname==="/api/databases"&&f.method==="POST"){let l=await x(f),p=String(l.name??"").trim();if(!Ur(p))return g({ok:!1,error:"Database name must be a valid identifier (letters, numbers, underscore; not starting with a digit)."},422);return g({...await zy(o,V,p),name:p})}if(S.pathname==="/api/databases/vitess"&&f.method==="GET"){let l=await Wy(o,V);return g({...l,unhealthy:Hy(l.tablets),missingPrimary:Ky(l)})}if(S.pathname==="/api/databases/vitess/provision"&&f.method==="POST"){let l=await x(f);try{return g(await iv(o,V,{keyspace:String(l.keyspace??""),username:String(l.username??""),password:String(l.password??""),sharded:l.sharded===!0,confirm:String(l.confirm??"")}))}catch(p){return g({ok:!1,error:p instanceof Error?p.message:String(p)},422)}}if(S.pathname==="/api/databases/vitess/migrations"&&f.method==="GET"){let l=S.searchParams.get("keyspace")??void 0;return g(await ev(o,V,l))}if(S.pathname==="/api/databases/vitess/migrations/action"&&f.method==="POST"){let l=await x(f),p=String(l.uuid??"").trim(),v=String(l.action??"");if(!["retry","cancel","cleanup","complete"].includes(v))return g({ok:!1,error:"Unknown migration action."},422);return g(await tv(o,V,p,v))}if(S.pathname==="/api/databases/vitess/keyspaces"&&f.method==="POST"){let l=await x(f),p=String(l.name??"").trim(),v=l.sharded===!0;return g(await Yy(o,V,p,{sharded:v}))}if(S.pathname==="/api/databases/vitess/vschema"&&f.method==="POST"){let l=await x(f),p=String(l.keyspace??"").trim(),v=typeof l.vschema==="string"?l.vschema:JSON.stringify(l.vschema??null);return g(await Zy(o,V,p,v))}if(S.pathname==="/api/databases/vitess/schema"&&f.method==="POST"){let l=await x(f),p=String(l.sql??"");return g(await Xy(o,V,p))}if(S.pathname==="/api/databases/vitess/install-client"&&f.method==="POST")return g(await Qy(o,V));if(S.pathname==="/api/databases/backups"&&f.method==="GET")return g(await Vy(o,V));if(S.pathname==="/api/databases/backup"&&f.method==="POST"){let l=await x(f),p=String(l.database??"").trim();if(!Ur(p))return g({ok:!1,error:"Database name must be a valid identifier."},422);if(l.confirm!==p)return g({ok:!1,error:`Type "${p}" to back up this database.`},409);return g(await qy(o,V,p))}if(S.pathname==="/api/databases/users"&&f.method==="POST"){let l=await x(f),p=String(l.username??"").trim(),v=String(l.password??""),b=String(l.database??"").trim()||void 0,I=l.access==="readonly"?"readonly":"all";if(!Ur(p))return g({ok:!1,error:"Username must be a valid identifier."},422);if(!v)return g({ok:!1,error:"Password is required."},422);if(b&&!Ur(b))return g({ok:!1,error:"Database must be a valid identifier."},422);return g({...await Uy(o,V,{username:p,password:v,database:b,access:I}),username:p})}if(S.pathname==="/api/dashboard-data")return Le=w.get(V)??await U(V),U(V),g(_u(Le,{user:qt,slug:o.project.slug}));if(S.pathname==="/api/users"&&f.method==="GET")return g({ok:!0,users:Tt(t).map(Hi)});if(S.pathname==="/api/users"&&f.method==="POST"){let l=await x(f),p=String(l.username??"").trim();if(!Ha(p))return g({ok:!1,error:"Username must be 2-32 characters: letters, numbers, dot, dash or underscore."},422);let v=l.sites&&typeof l.sites==="object"?l.sites:{},b=new Set(Object.keys(o.sites??{})),I={};for(let[_,z]of Object.entries(v)){if(!b.has(_))return g({ok:!1,error:`Site '${_}' was not found.`},404);if(z!=="owner"&&z!=="collaborator")return g({ok:!1,error:`Unknown site role '${z}'. Use 'owner' or 'collaborator'.`},422);I[_]=z}let A=typeof l.password==="string"&&l.password.trim()?l.password.trim():void 0;if(A&&A.length<12)return g({ok:!1,error:"Password must be at least 12 characters."},422);let E=Mo(t,{username:p,password:A,name:typeof l.name==="string"?l.name:void 0,sites:I});return es(a,Tt(t)),de(),g({ok:!0,user:Hi(E.user),password:E.password})}if(S.pathname==="/api/users"&&f.method==="DELETE"){let l=await x(f),p=String(l.username??"").trim();if(p.toLowerCase()===B.username.toLowerCase())return g({ok:!1,error:"You cannot remove your own account."},409);let v=Gt(Tt(t),p),b=v?a.store.getActorByExternalId("user",`dashboard:${v.username.toLowerCase()}`):void 0,I=b?a.store.getMembershipForActor(a.organization.id,b.id):void 0;if(I&&I.source!=="legacy")return g({ok:!1,error:"Organization members must be removed from Organization access."},409);let A=Ru(t,p);if(!A.ok)return g(A,409);return es(a,Tt(t)),D.clear(),g({ok:!0,username:p})}if(S.pathname==="/api/actions/run"&&f.method==="POST"){let l=await f.json().catch(()=>({})),p=l.action?Qb(l.action,V):void 0;if(!p)return g({ok:!1,error:"Unknown dashboard action."},404);if(p.mutates&&l.confirm!==p.confirm)return g({ok:!1,error:`Type "${p.confirm}" to run this action.`},409);let v=await Ir({controlPlane:a,environment:V,actor:B,kind:`dashboard.action.${p.id}`,input:{action:p.id},execute:()=>qu(p,{cwd:t,cliEntry:i})});return g({...v.result,controlPlaneOperation:v.operation})}if(S.pathname==="/api/server/operations/run"&&f.method==="POST"){let l=await f.json().catch(()=>({})),p=l.operation?Pu(l.operation,o,Le):void 0;if(!p)return g({ok:!1,error:"Unknown or unavailable server operation."},404);if(p.mutates&&l.confirm!==p.confirm)return g({ok:!1,error:`Type "${p.confirm}" to run this operation.`},409);let v=ar(a,String(V));await new Qn(ge).run(new $o,{...v,artifactRoot:t});let b=ja(ge,{scope:v,desiredConfigHash:a.project.desiredConfigHash});if(b.decision.outcome==="block")return g({ok:!1,error:`Operation blocked by security policy: ${b.decision.explanation}`,securityReview:b},409);let I=await Ir({controlPlane:a,environment:V,actor:B,kind:`dashboard.server.${p.id}`,resourceSlug:p.target,input:{operation:p.id,target:p.target,to:l.to??null},execute:()=>Ya(o,V,p,{to:l.to})});return g({...I.result,controlPlaneOperation:I.operation,securityReview:b})}if(S.pathname==="/api/server/command"&&f.method==="POST"){let l=await f.json().catch(()=>({}));if(l.confirm!=="run")return g({ok:!1,error:'Type "run" to execute this command on the server.'},409);let p=await Ir({controlPlane:a,environment:V,actor:B,kind:"dashboard.server.command",input:{source:"interactive-command"},execute:()=>Lo(o,V,String(l.command??""))});return g({...p.result,controlPlaneOperation:p.operation})}if(S.pathname==="/api/serverless/operations")return g($u(o,V,Le));if(S.pathname==="/api/serverless/operations/run"&&f.method==="POST"){let l=await f.json().catch(()=>({})),p=l.operation?zv(l.operation,o,V,Le):void 0;if(!p)return g({ok:!1,error:"Unknown or unavailable serverless operation."},404);if(p.mutates&&l.confirm!==p.confirm)return g({ok:!1,error:`Type "${p.confirm}" to run this operation.`},409);let v=await Ir({controlPlane:a,environment:V,actor:B,kind:`dashboard.serverless.${p.id}`,input:{operation:p.id,min:l.min??null,max:l.max??null},execute:()=>Uv(o,V,p,{min:l.min,max:l.max})});return Le=await ti(o,V),w.set(V,Le),g({...v.result,controlPlaneOperation:v.operation})}if(S.pathname==="/api/serverless/command"&&f.method==="POST"){let l=await f.json().catch(()=>({}));if(l.confirm!=="run")return g({ok:!1,error:'Type "run" to execute this command.'},409);return g(await qv(o,V,String(l.command??"")))}if(S.pathname==="/api/serverless/dlq"&&f.method==="GET"){let l=Number(S.searchParams.get("max"))||10;return g(await Vv(o,V,l))}if(S.pathname==="/api/serverless/dlq/redrive"&&f.method==="POST"){let l=await f.json().catch(()=>({}));if(l.confirm!=="redrive")return g({ok:!1,error:'Type "redrive" to move messages back onto a source queue.'},409);return g(await Wv(o,V,{max:l.max,targetQueue:l.targetQueue}))}if(S.pathname==="/api/serverless/dlq/purge"&&f.method==="POST"){if((await f.json().catch(()=>({}))).confirm!=="purge")return g({ok:!1,error:'Type "purge" to permanently discard every DLQ message.'},409);return g(await Hv(o,V))}if(S.pathname==="/api/serverless/secrets"&&f.method==="GET")return g({secrets:Kv(o,V)});if(S.pathname==="/api/serverless/secrets"&&f.method==="POST"){let l=await f.json().catch(()=>({})),p=String(l.secretId??"").trim();if(!p)return g({ok:!1,error:"A secret id is required."},422);if(typeof l.value!=="string"||l.value==="")return g({ok:!1,error:"A non-empty value is required."},422);return g(await Jv(o,V,p,l.value))}if(S.pathname==="/api/serverless/secrets"&&f.method==="DELETE"){let l=await f.json().catch(()=>({})),p=String(l.secretId??"").trim();if(!p)return g({ok:!1,error:"A secret id is required."},422);if(l.confirm!==p)return g({ok:!1,error:`Type "${p}" to delete this secret.`},409);return g(await Gv(o,V,p))}if(S.pathname==="/api/serverless/functions/config"&&f.method==="POST"){let l=await f.json().catch(()=>({})),p=String(l.mode??"").trim();if(l.confirm!==p)return g({ok:!1,error:`Type "${p}" to update this function.`},409);return g(await Qv(o,V,p,{memory:l.memory,timeout:l.timeout}))}if(S.pathname==="/api/serverless/alarms"&&f.method==="GET")return g(await Yv(o,V));if(S.pathname==="/api/serverless/alarms"&&f.method==="POST"){let l=await f.json().catch(()=>({})),p=String(l.preset??"").trim(),v=Number(l.threshold);if(!p)return g({ok:!1,error:"An alarm metric is required."},422);if(!Number.isFinite(v))return g({ok:!1,error:"A numeric threshold is required."},422);return g(await Zv(o,V,p,v))}if(S.pathname==="/api/serverless/alarms"&&f.method==="DELETE"){let l=await f.json().catch(()=>({})),p=String(l.name??"").trim();if(!p)return g({ok:!1,error:"An alarm name is required."},422);if(l.confirm!==p)return g({ok:!1,error:`Type "${p}" to delete this alarm.`},409);return g(await Xv(o,V,p))}if(S.pathname==="/api/serverless/traces"&&f.method==="GET"){let l=Number(S.searchParams.get("minutes"))||30;return g(await Xa(o,V,l))}if(S.pathname==="/api/serverless/scheduler"&&f.method==="POST"){let l=await f.json().catch(()=>({})),p=String(l.action??"").trim();if(p!=="enable"&&p!=="disable"&&p!=="run")return g({ok:!1,error:"Unknown scheduler action."},422);if(l.confirm!==p)return g({ok:!1,error:`Type "${p}" to ${p} the scheduler.`},409);return g(await Mu(o,V,p))}if(!Ab(S.pathname,qt))return new Response(null,{status:302,headers:{location:`/access-denied?env=${encodeURIComponent(V)}`}});let ai=await Me(B,V);if(!ai)return oc("ts-cloud dashboard UI is unavailable.",503);return Cb(ai,S.pathname)}catch(kn){if(e.verbose)console.error(kn);return g({ok:!1,error:kn?.message??String(kn)},500)}})();if(!Ke)return Ke;if(Ie&&(S.pathname.startsWith("/api/")||S.pathname.startsWith("/auth/"))){let ue;if((Z.headers.get("content-type")||"").includes("application/json"))ue=await Z.json().catch(()=>{return});let at=ze.resolveUser(f),tt=at?re(at).actor:void 0;a.store.appendEvent({organizationId:a.organization.id,projectId:a.project.id,actorId:tt?.id,correlationId:ae,type:Ke.status<400?"dashboard.mutation.succeeded":"dashboard.mutation.failed",level:Ke.status<400?"info":"warning",payload:y_(f.method,S.pathname,ue,Ke.status,Date.now()-te)})}return Ke.headers.set("x-request-id",ae),Ke}});Jo?.start();let aS=e.spendLoop??!0,up;if(aS)(async()=>{let{SpendRunner:f,SpendLoopLease:X,startSpendLoop:te}=await import("./spend/index.js"),{store:Z}=await _b(a.store),ae=new f({controlPlane:a.store,store:Z,alerts:le});up=te(ae,{lease:new X(a.store,{owner:`dashboard:${process.pid}`}),onError:(Ie)=>console.error(`[ts-cloud] spend cycle failed: ${Ie instanceof Error?Ie.message:String(Ie)}`)})})();let cS=oi.stop.bind(oi);return oi.stop=(f)=>{clearInterval(ap),clearInterval(cp),clearInterval(dp),clearInterval(sp),clearInterval(op),clearInterval(tp),clearInterval(rp),clearInterval(np),clearInterval(ip),de(),Ge.clear(),Jo?.stop(),up?.();let X=cS(f);if(Jo)Jo.settled().finally(()=>a.store.close());else a.store.close();return X},{server:oi,url:`http://${r}:${oi.port}/`}}export{Rl as a,NR as b,Sh as c,jN as d,Ss as e,Gm as f,Hc as g,ok as h,sk as i,mo as j,Kc as k,tg as l,nn as m,rg as n,ng as o,ig as p,ks as q,fo as r,kk as s,on as t,dg as u,ed as v,td as w,rd as x,pg as y,mg as z,gg as A,Rs as B,wc as C,rm as D,ao as E,us as F,Tc as G,Dn as H,xw as I,wm as J,km as K,Dw as L,Im as M,Mc as N,yi as O,Dm as P,Om as Q,$m as R,Nm as S,tn as T,Ww as U,Lm as V,bi as W,Lc as X,Fc as Y,zc as Z,gs as _,fs as $,po as aa,Vm as ba,hs as ca,Uc as da,Vc as ea,Do as fa,gy as ga,Oo as ha,zA as ia,UA as ja,Qn as ka,$o as la,ou as ma,WA as na,hy as oa,yy as pa,su as qa,vy as ra,by as sa,Sy as ta,QM as ua,ar as va,wy as wa,XM as xa,e1 as ya,Na as za,ja as Aa,i1 as Ba,hr as Ca,aA as Da,Jn as Ea,Lr as Fa,Br as Ga,Gn as Ha,Xh as Ia,ey as Ja,ty as Ka,ry as La,lA as Ma,mA as Na,Ql as Oa,gA as Pa,fA as Qa,Yl as Ra,iy as Sa,oy as Ta,bA as Ua,or as Va,RA as Wa,ay as Xa,yr as Ya,Xl as Za,sn as _a,Mn as $a,Bn as ab,yo as bb,Cs as cb,bg as db,gD as eb,dd as fb,Fk as gb,zk as hb,Uk as ib,qk as jb,sd as kb,ad as lb,Sg as mb,vo as nb,yd as ob,xg as pb,js as qb,Dg as rb,vd as sb,bd as tb,Sd as ub,wd as vb,kd as wb,Ed as xb,Rd as yb,Ad as zb,Og as Ab,Ei as Bb,Cd as Cb,Th as Db,_o as Eb,xh as Fb,$l as Gb,Nl as Hb,Jh as Ib,Bi as Jb,Ul as Kb,ql as Lb,rA as Mb,Tj as Nb,_a as Ob,Dj as Pb,Oj as Qb,$j as Rb,Kl as Sb,Jl as Tb,Zh as Ub,sA as Vb,Gl as Wb,To as Xb,Nh as Yb,Ca as Zb,jh as _b,Mh as $b,Bh as ac,Bl as bc,GR as cc,Ll as dc,Vh as ec,QR as fc,zl as gc,YR as hc,Ye as ic,yp as jc,es as kc,Ir as lc,vp as mc,bp as nc,U_ as oc,J_ as pc,wS as qc,rT as rc,nT as sc,iT as tc,CS as uc,PS as vc,uT as wc,pT as xc,US as yc,qS as zc,wT as Ac,Hp as Bc,ns as Cc,XS as Dc,hc as Ec,yc as Fc,as as Gc,pi as Hc,Pn as Ic,cs as Jc,sw as Kc,io as Lc,em as Mc,tm as Nc,Sc as Oc,Hk as Pc,md as Qc,Gk as Rc,Qk as Sc,Cg as Tc,fd as Uc,Os as Vc,Pg as Wc,hd as Xc,Un as Yc,_r as Zc,jg as _c,Td as $c,xd as ad,Mg as bd,Od as cd,Nd as dd,Md as ed,Pl as fd,Eh as gd,Rh as hd,Po as id,_l as jd,Tl as kd,xl as ld,Dl as md,Ph as nd,Gb as od,Hu as pd,Qb as qd,M_ as rd};
|