@stacksjs/ts-cloud 0.16.14 → 0.16.16
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-r7k2mkn7.js → chunk-0znhykt9.js} +5 -5
- package/dist/bin/{chunk-23nxkj19.js → chunk-1baj8p0r.js} +1 -1
- package/dist/bin/{chunk-9j7qhwe0.js → chunk-2943bszc.js} +1 -1
- package/dist/bin/chunk-2tn43y0d.js +1 -0
- package/dist/bin/{chunk-b7b87gxb.js → chunk-2v91xnqx.js} +2 -2
- package/dist/bin/{chunk-gwpmn3a3.js → chunk-2w591cvg.js} +1 -1
- package/dist/bin/{chunk-5jf6veax.js → chunk-3qfd0vnc.js} +3 -3
- package/dist/bin/{chunk-489c9r4g.js → chunk-3x4p2s2r.js} +3 -3
- package/dist/bin/chunk-4v6f496n.js +1 -0
- package/dist/bin/chunk-64cdtvar.js +1 -0
- package/dist/bin/chunk-66egshmp.js +1 -0
- package/dist/bin/chunk-7raskz63.js +1 -0
- package/dist/bin/{chunk-zm95j24a.js → chunk-80295akq.js} +3 -3
- package/dist/bin/{chunk-fjd8tw77.js → chunk-90c3rkd8.js} +4 -4
- package/dist/bin/chunk-9bxyy4th.js +1 -0
- package/dist/bin/{chunk-pm2vz6zp.js → chunk-b3yp7bak.js} +3 -3
- package/dist/bin/chunk-bbt0vyzj.js +1 -0
- package/dist/bin/{chunk-tb4ek3s5.js → chunk-bhay1f8a.js} +1 -1
- package/dist/bin/chunk-cpcae7e2.js +1 -0
- package/dist/bin/{chunk-cb47f0pb.js → chunk-cs6a98r1.js} +2 -2
- package/dist/bin/{chunk-3eht1tp2.js → chunk-dczw0nxw.js} +5 -5
- package/dist/bin/{chunk-3z65v87m.js → chunk-dp2fsnpe.js} +6 -6
- package/dist/bin/chunk-dsc7ef1w.js +1 -0
- package/dist/bin/{chunk-21am8b1b.js → chunk-edfh9ts2.js} +1 -1
- package/dist/bin/chunk-f2wn46nw.js +1 -0
- package/dist/bin/chunk-fddwwac7.js +1 -0
- package/dist/bin/chunk-ffcyj2jj.js +1 -0
- package/dist/bin/{chunk-2cyhks5n.js → chunk-fjz07v7g.js} +1 -1
- package/dist/bin/chunk-gbejgj71.js +1 -0
- package/dist/bin/{chunk-58phgtc8.js → chunk-grs2cwm7.js} +2 -2
- package/dist/bin/{chunk-p0vyt3fq.js → chunk-gv9deppc.js} +2 -2
- package/dist/bin/{chunk-5ffj7508.js → chunk-j0wfftk1.js} +1 -1
- package/dist/bin/{chunk-yas09vmt.js → chunk-j76935z3.js} +3 -3
- package/dist/bin/{chunk-0y4a84jm.js → chunk-khta83xb.js} +12 -12
- package/dist/bin/chunk-kjbkwzxd.js +1 -0
- package/dist/bin/chunk-knthwdhz.js +1 -0
- package/dist/bin/{chunk-31tmm8kx.js → chunk-m2kr333s.js} +2 -2
- package/dist/bin/chunk-m5wc1ent.js +1 -0
- package/dist/bin/{chunk-s4z1knq4.js → chunk-n02421y9.js} +1 -1
- package/dist/bin/{chunk-9bshng4v.js → chunk-nm000jpj.js} +81 -81
- package/dist/bin/{chunk-kft7wdhy.js → chunk-pd8tk3z5.js} +1 -1
- package/dist/bin/chunk-pjgbnk3q.js +1 -0
- package/dist/bin/chunk-rn0pgnt4.js +1 -0
- package/dist/bin/{chunk-hdr0q89a.js → chunk-tc24txss.js} +5 -5
- package/dist/bin/{chunk-nazx54p5.js → chunk-tfasfg4a.js} +2 -2
- package/dist/bin/{chunk-r0qynqff.js → chunk-tvv6vdx6.js} +5 -5
- package/dist/bin/chunk-v93xyx1p.js +1 -0
- package/dist/bin/chunk-vx9mmpaz.js +1 -0
- package/dist/bin/{chunk-me81g606.js → chunk-vx9qk1g1.js} +1 -1
- package/dist/bin/{chunk-0ed5yh3v.js → chunk-whww424p.js} +47 -47
- package/dist/bin/chunk-xtzy90zh.js +1 -0
- package/dist/bin/{chunk-4nbq68h4.js → chunk-xxf1vhfr.js} +1 -1
- package/dist/bin/{chunk-2a8twtvv.js → chunk-y4c26gaf.js} +1 -1
- package/dist/bin/{chunk-9gcmpcmq.js → chunk-yk4p2k8w.js} +1 -1
- package/dist/bin/chunk-z6mnhd0j.js +1 -0
- package/dist/bin/{chunk-4mpfdw94.js → chunk-zacbzz1w.js} +2 -2
- package/dist/bin/{chunk-3d8y4a6d.js → chunk-zzmk290g.js} +109 -109
- package/dist/bin/cli.js +150 -150
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/chunk-051jwkd2.js +1 -0
- package/dist/{chunk-tgzp1h6j.js → chunk-0bbrbzf9.js} +4 -4
- package/dist/chunk-1gne7rkf.js +1 -0
- package/dist/chunk-38c310s1.js +1 -0
- package/dist/{chunk-80vxhxt5.js → chunk-4twnkjyq.js} +2 -2
- package/dist/{chunk-dns94gs7.js → chunk-4xta1s4z.js} +1 -1
- package/dist/{chunk-dxcwfj3h.js → chunk-6eq5xfcx.js} +1 -1
- package/dist/{chunk-g8tp1zj4.js → chunk-a21phhyj.js} +3 -3
- package/dist/{chunk-55cmjg49.js → chunk-a6aw2jtz.js} +6 -6
- package/dist/{chunk-bpvpq6w6.js → chunk-acpxtkfy.js} +90 -90
- package/dist/chunk-dk3t3hgq.js +1 -0
- package/dist/{chunk-21b8nage.js → chunk-emx1j2yt.js} +1 -1
- package/dist/{chunk-4yb7hf91.js → chunk-fdn4wnd8.js} +7 -7
- package/dist/{chunk-aesvajfc.js → chunk-fz70vxrk.js} +1 -1
- package/dist/{chunk-22ybphxa.js → chunk-g0yyw5k8.js} +1 -1
- package/dist/{chunk-pwpd6jt2.js → chunk-gn42mekr.js} +1 -1
- package/dist/{chunk-0hf0rdze.js → chunk-gstz8w2d.js} +2 -2
- package/dist/{chunk-mmdd5thg.js → chunk-jgv0x24e.js} +1 -1
- package/dist/{chunk-d72ddm5x.js → chunk-jncbm332.js} +130 -130
- package/dist/{chunk-9be2pb0b.js → chunk-pekptc1b.js} +5 -5
- package/dist/chunk-qc2v4h2q.js +1 -0
- package/dist/{chunk-kt6qnc6f.js → chunk-rgw06xbk.js} +4 -4
- package/dist/{chunk-7pk6cctr.js → chunk-rmn71xjb.js} +41 -41
- package/dist/{chunk-2jgx2s5y.js → chunk-sm5rn3db.js} +19 -19
- package/dist/{chunk-8a02v9gs.js → chunk-ss4q8kge.js} +2 -2
- package/dist/{chunk-s40cx3fh.js → chunk-v9t92ak2.js} +2 -2
- package/dist/{chunk-ffjc6gev.js → chunk-wdrqt329.js} +135 -135
- package/dist/{chunk-nw5yqgtn.js → chunk-whwg2nzb.js} +5 -5
- package/dist/{chunk-sw1p9qge.js → chunk-yxn6tpbg.js} +1 -1
- package/dist/{chunk-3bz7xz2d.js → chunk-z87dekhm.js} +1 -1
- 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/cloudfront-origin.d.ts +15 -26
- package/dist/drivers/shared/deploy-script.d.ts +62 -29
- package/dist/index.js +39 -39
- package/dist/operations/index.js +1 -1
- package/dist/protection/index.js +1 -1
- package/dist/spend/index.js +1 -1
- package/dist/ui/404.html +1 -1
- package/dist/ui/accept-invitation.html +1 -1
- package/dist/ui/access-denied.html +1 -1
- package/dist/ui/account/automation.html +6 -6
- package/dist/ui/account/security.html +2 -2
- package/dist/ui/applications/compose.html +5 -5
- package/dist/ui/applications/new.html +2 -2
- package/dist/ui/data/backups.html +6 -6
- package/dist/ui/data/services.html +5 -5
- package/dist/ui/data/volumes.html +6 -6
- package/dist/ui/index.html +6 -6
- package/dist/ui/infrastructure/topology.html +6 -6
- package/dist/ui/integrations.html +1 -1
- package/dist/ui/operations/alerts.html +6 -6
- package/dist/ui/operations/configuration.html +6 -6
- package/dist/ui/operations/jobs.html +5 -5
- package/dist/ui/operations/maintenance.html +5 -5
- package/dist/ui/operations/observability.html +6 -6
- package/dist/ui/operations/previews.html +6 -6
- package/dist/ui/operations/queue.html +6 -6
- package/dist/ui/operations/regions.html +5 -5
- package/dist/ui/operations/releases.html +5 -5
- package/dist/ui/operations/spend.html +6 -6
- package/dist/ui/operations/workloads.html +6 -6
- package/dist/ui/security.html +1 -1
- package/dist/ui/server/actions.html +6 -6
- package/dist/ui/server/activity.html +2 -2
- package/dist/ui/server/capacity.html +6 -6
- package/dist/ui/server/database.html +6 -6
- package/dist/ui/server/deployments.html +5 -5
- package/dist/ui/server/diagnostics.html +2 -2
- package/dist/ui/server/firewall.html +5 -5
- package/dist/ui/server/fleet.html +6 -6
- package/dist/ui/server/logs.html +6 -6
- package/dist/ui/server/metrics.html +5 -5
- package/dist/ui/server/security.html +2 -2
- package/dist/ui/server/services.html +2 -2
- package/dist/ui/server/sites.html +6 -6
- package/dist/ui/server/ssh-keys.html +6 -6
- package/dist/ui/server/team.html +6 -6
- package/dist/ui/server/terminal.html +2 -2
- package/dist/ui/serverless/alarms.html +6 -6
- package/dist/ui/serverless/assets.html +1 -1
- package/dist/ui/serverless/cost.html +1 -1
- package/dist/ui/serverless/data.html +6 -6
- package/dist/ui/serverless/deployments.html +2 -2
- package/dist/ui/serverless/firewall.html +2 -2
- package/dist/ui/serverless/functions.html +6 -6
- package/dist/ui/serverless/logs.html +6 -6
- package/dist/ui/serverless/metrics.html +2 -2
- package/dist/ui/serverless/queues.html +5 -5
- package/dist/ui/serverless/secrets.html +6 -6
- package/dist/ui/serverless/traces.html +6 -6
- package/dist/ui/serverless.html +5 -5
- package/package.json +3 -3
- package/dist/bin/chunk-01tmdqe3.js +0 -1
- package/dist/bin/chunk-3bwy7atq.js +0 -1
- package/dist/bin/chunk-3rsvrp09.js +0 -1
- package/dist/bin/chunk-4gf4mk0b.js +0 -1
- package/dist/bin/chunk-5wms0mx3.js +0 -1
- package/dist/bin/chunk-c7sqa85j.js +0 -1
- package/dist/bin/chunk-cejjg0ts.js +0 -1
- package/dist/bin/chunk-e3hn6atg.js +0 -1
- package/dist/bin/chunk-e4gqzp7n.js +0 -1
- package/dist/bin/chunk-fbq61aj0.js +0 -1
- package/dist/bin/chunk-g4dytx12.js +0 -1
- package/dist/bin/chunk-hssaw82j.js +0 -1
- package/dist/bin/chunk-k4x1pq4t.js +0 -1
- package/dist/bin/chunk-kcvvpvte.js +0 -1
- package/dist/bin/chunk-n8a76gys.js +0 -1
- package/dist/bin/chunk-p1k08e45.js +0 -1
- package/dist/bin/chunk-ps8ev3tq.js +0 -1
- package/dist/bin/chunk-q8s9v9hv.js +0 -1
- package/dist/bin/chunk-qcvmyfp7.js +0 -1
- package/dist/bin/chunk-qncvqmzy.js +0 -1
- package/dist/bin/chunk-rt9nbrwd.js +0 -1
- package/dist/bin/chunk-xhwjntw1.js +0 -1
- package/dist/chunk-29xhksd3.js +0 -1
- package/dist/chunk-67wrhk75.js +0 -1
- package/dist/chunk-6n5wgv3d.js +0 -1
- package/dist/chunk-7nq2rwjs.js +0 -1
- package/dist/chunk-xdsaxgny.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{_,d}from"./chunk-d72ddm5x.js";import{xr}from"./chunk-4yb7hf91.js";var Kh=["edge.requests","edge.egress_gb","function.invocations","function.gb_seconds","build.minutes","compute.instance_hours","storage.gb_hours","object.egress_gb","object.requests","database.gb_hours","database.io_requests","telemetry.ingest_gb","image.transformations"],_s={"edge.requests":{key:"edge.requests",unit:"requests",label:"Edge requests",precision:0},"edge.egress_gb":{key:"edge.egress_gb",unit:"gb",label:"Edge egress",precision:3},"function.invocations":{key:"function.invocations",unit:"invocations",label:"Function invocations",precision:0},"function.gb_seconds":{key:"function.gb_seconds",unit:"gb_seconds",label:"Function compute",precision:2},"build.minutes":{key:"build.minutes",unit:"minutes",label:"Build minutes",precision:2},"compute.instance_hours":{key:"compute.instance_hours",unit:"hours",label:"Instance hours",precision:2},"storage.gb_hours":{key:"storage.gb_hours",unit:"gb_hours",label:"Block storage",precision:2},"object.egress_gb":{key:"object.egress_gb",unit:"gb",label:"Object storage egress",precision:3},"object.requests":{key:"object.requests",unit:"requests",label:"Object storage requests",precision:0},"database.gb_hours":{key:"database.gb_hours",unit:"gb_hours",label:"Database storage",precision:2},"database.io_requests":{key:"database.io_requests",unit:"requests",label:"Database I/O",precision:0},"telemetry.ingest_gb":{key:"telemetry.ingest_gb",unit:"gb",label:"Telemetry ingest",precision:3},"image.transformations":{key:"image.transformations",unit:"count",label:"Image transformations",precision:0}},Wh=["notify","block_builds","block_deployments","throttle_requests","suspend_functions","serve_static","suspend_project"],R={notify:0,block_builds:1,block_deployments:2,throttle_requests:3,suspend_functions:4,serve_static:5,suspend_project:6};var Jh=1e6;function Ir(e){if(e.tiers&&e.tiers.length>0)return e.tiers;return[{upToQuantity:null,microCentsPerUnit:e.microCentsPerUnit??0}]}function _c(e,t){if(!(e>0))return 0;let r=[...t].sort((l,u)=>{if(l.upToQuantity===null)return 1;if(u.upToQuantity===null)return-1;return l.upToQuantity-u.upToQuantity}),n=e,o=0,a=0;for(let l of r){if(n<=0)break;let p=(l.upToQuantity===null?1/0:l.upToQuantity)-o;if(p<=0)continue;let E=Math.min(n,p);a+=E*l.microCentsPerUnit,n-=E,o+=E}if(n>0){let l=r.reduce((u,p)=>Math.max(u,p.microCentsPerUnit),0);a+=n*l}return a}function lp(e,t,r,n){let o=e.entries.filter((u)=>u.meter===t);if(o.length===0)return;let a=o.filter((u)=>u.provider===r),l=a.length>0?a:o.filter((u)=>u.provider==="*");return l.find((u)=>u.region===n)??l.find((u)=>u.region==null)}function Os(e,t,r=0){let n=lp(e,t.meter,t.provider,t.region),o=Math.max(0,t.quantity);if(!n)return{meter:t.meter,provider:t.provider??"unknown",region:t.region,quantity:o,includedQuantity:0,billableQuantity:o,costCents:0,unpriced:!0};let a=Math.max(0,n.includedQuantity??0),l=Math.max(0,r-a),u=Math.max(0,a-Math.max(0,r)),p=Math.min(o,u),E=o-p,g=Ir(n),m=_c(l+E,g)-_c(l,g);return{meter:t.meter,provider:n.provider,region:n.region??t.region,quantity:o,includedQuantity:p,billableQuantity:E,costCents:m/1e6,unpriced:!1}}function Xh(e,t){let r=new Map,n=[];for(let o of t){let a=`${o.meter}\x00${o.provider??""}\x00${o.region??""}`,l=r.get(a)??0,u=Os(e,o,l);r.set(a,l+u.quantity),n.push(u)}return{currency:e.currency,totalCents:n.reduce((o,a)=>o+a.costCents,0),lines:n,unpricedMeters:[...new Set(n.filter((o)=>o.unpriced).map((o)=>String(o.meter)))]}}function Yh(e){return Math.round(e*100)/100}function Zh(e,...t){let r=new Map,n=(a)=>`${a.meter}\x00${a.provider}\x00${a.region??""}`;for(let a of e.entries)r.set(n(a),a);let o=e.currency;for(let a of t){o=a.currency||o;for(let l of a.entries)r.set(n(l),l)}return{currency:o,entries:[...r.values()]}}var Y=(e)=>Math.round(e*1e6),H=(e)=>Math.round(e*1e6),Oc={currency:"USD",entries:[{meter:"edge.requests",provider:"aws",microCentsPerUnit:H(0.00075)},{meter:"edge.egress_gb",provider:"aws",includedQuantity:100,tiers:[{upToQuantity:10240,microCentsPerUnit:Y(8.5)},{upToQuantity:51200,microCentsPerUnit:Y(8)},{upToQuantity:null,microCentsPerUnit:Y(6)}]},{meter:"function.invocations",provider:"aws",includedQuantity:1e6,microCentsPerUnit:H(0.002)},{meter:"function.gb_seconds",provider:"aws",includedQuantity:400000,microCentsPerUnit:H(0.00166667)},{meter:"storage.gb_hours",provider:"aws",microCentsPerUnit:H(0.010958904109589041)},{meter:"object.egress_gb",provider:"aws",includedQuantity:100,microCentsPerUnit:Y(9)},{meter:"object.requests",provider:"aws",microCentsPerUnit:H(0.000039999999999999996)},{meter:"database.gb_hours",provider:"aws",microCentsPerUnit:H(0.015753424657534248)},{meter:"compute.instance_hours",provider:"aws",microCentsPerUnit:H(4.16)},{meter:"edge.egress_gb",provider:"hetzner",includedQuantity:20480,microCentsPerUnit:Y(0.108)},{meter:"object.egress_gb",provider:"hetzner",includedQuantity:1024,microCentsPerUnit:Y(0.108)},{meter:"compute.instance_hours",provider:"hetzner",microCentsPerUnit:H(0.95)},{meter:"storage.gb_hours",provider:"hetzner",microCentsPerUnit:H(0.006027397260273972)},{meter:"edge.requests",provider:"hetzner",microCentsPerUnit:0},{meter:"edge.requests",provider:"local",microCentsPerUnit:0},{meter:"edge.egress_gb",provider:"local",microCentsPerUnit:0},{meter:"function.invocations",provider:"local",microCentsPerUnit:0},{meter:"function.gb_seconds",provider:"local",microCentsPerUnit:0},{meter:"build.minutes",provider:"*",includedQuantity:6000,microCentsPerUnit:H(0.8)},{meter:"telemetry.ingest_gb",provider:"*",includedQuantity:5,microCentsPerUnit:Y(50)},{meter:"image.transformations",provider:"*",includedQuantity:5000,microCentsPerUnit:H(0.05)}]};var vt=new Map;function It(e){let t=vt.get(e);if(!t)t=new Intl.DateTimeFormat("en-US",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",weekday:"short",hourCycle:"h23"}),vt.set(e,t);return t}var Sr={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6};function ii(e){try{return It(e),!0}catch{return!1}}function Ls(e,t){let r=It(t).formatToParts(e),n=(o)=>r.find((a)=>a.type===o)?.value??"0";return{year:Number(n("year")),month:Number(n("month")),day:Number(n("day")),hour:Number(n("hour")),minute:Number(n("minute")),second:Number(n("second")),weekday:Sr[n("weekday")]??0}}function Lc(e,t){let r=Ls(e,t);return Date.UTC(r.year,r.month-1,r.day,r.hour,r.minute,r.second)-Math.floor(e.getTime()/1000)*1000}function Lt(e,t,r,n,o=0){let a=Date.UTC(t,r-1,n,o),l=new Date(a-Lc(new Date(a),e));return new Date(a-Lc(l,e))}function Ar(e,t){return new Date(Date.UTC(e,t-1,1)).toLocaleString("en-US",{month:"long",year:"numeric",timeZone:"UTC"})}function ct(e,t,r=new Date){let n=ii(t)?t:"UTC",o=Ls(r,n),a,l,u;if(e==="daily")a=Lt(n,o.year,o.month,o.day),l=Lt(n,o.year,o.month,o.day+1),u=`${o.year}-${String(o.month).padStart(2,"0")}-${String(o.day).padStart(2,"0")}`;else if(e==="weekly"){let g=(o.weekday+6)%7;a=Lt(n,o.year,o.month,o.day-g),l=Lt(n,o.year,o.month,o.day-g+7);let m=Ls(a,n);u=`week of ${m.year}-${String(m.month).padStart(2,"0")}-${String(m.day).padStart(2,"0")}`}else a=Lt(n,o.year,o.month,1),l=Lt(n,o.year,o.month+1,1),u=Ar(o.year,o.month);let p=l.getTime()-a.getTime(),E=Math.max(0,Math.min(p,r.getTime()-a.getTime()));return{start:a.toISOString(),end:l.toISOString(),elapsedMs:E,totalMs:p,label:u}}function ef(e,t,r=new Date){let n=ct(e,t,r),o=new Date(new Date(n.start).getTime()-1),a=ct(e,t,o);return{...a,elapsedMs:a.totalMs}}function wr(e){let r=(typeof e==="string"?new Date(e):e).getTime();if(!Number.isFinite(r))throw Error("hourBucket requires a valid date");return new Date(Math.floor(r/3600000)*3600000).toISOString()}function tf(e,t,r=9600){let n=Math.floor(new Date(e).getTime()/3600000)*3600000,o=new Date(t).getTime();if(!Number.isFinite(n)||!Number.isFinite(o))throw Error("hourBucketsBetween requires valid dates");let a=[];for(let l=n;l<o&&a.length<r;l+=3600000)a.push(new Date(l).toISOString());return a}import{createHash as Or}from"node:crypto";var he=1073741824,$c=[{match:"request.count",meter:"edge.requests"},{match:"traffic.requests",meter:"edge.requests"},{match:"http.request",meter:"edge.requests",field:"count"},{match:"traffic.bytes_out",meter:"edge.egress_gb",scale:1/he},{match:"storage.egress.day",meter:"object.egress_gb",scale:1/he},{match:"storage.egress.month",meter:"object.egress_gb",scale:1/he,cumulative:!0},{match:"storage.egress.day_downloads",meter:"object.requests"},{match:"function.invocation",meter:"function.invocations",field:"count"},{match:"function.duration_ms",meter:"function.gb_seconds",scale:0.001},{match:"build.duration_ms",meter:"build.minutes",scale:0.000016666666666666667},{match:"telemetry.ingest_bytes",meter:"telemetry.ingest_gb",scale:1/he},{match:"image.transform",meter:"image.transformations",field:"count"}];function Ur(e,t){return e.match.endsWith("*")?t.startsWith(e.match.slice(0,-1)):e.match===t}function up(e,t=$c){return t.find((r)=>!r.match.endsWith("*")&&r.match===e)??t.find((r)=>Ur(r,e))}function Xr(e,t){let r=t.field??"value",n=r==="count"?1:r==="bytesOut"?e.bytesOut:r==="bytesIn"?e.bytesIn:r==="durationMs"?e.durationMs:e.value;if(n==null||!Number.isFinite(n))return;return n*(t.scale??1)}function pp(e,t){return Or("sha256").update([t,e.meter,e.organizationId,e.projectId??"",e.environmentId??"",e.resourceId??"",e.timestamp].join("\x00")).digest("hex").slice(0,32)}class $s{resetToleranceRatio;last=new Map;constructor(e=0.999){this.resetToleranceRatio=e}delta(e,t,r=new Date){if(!Number.isFinite(t)||t<0)return;let n=new Date(r).getTime(),o=this.last.get(e);if(!o)return this.last.set(e,{value:t,at:n}),t>0?t:void 0;if(n<o.at)return;if(t<o.value&&t>=o.value*this.resetToleranceRatio)return;if(this.last.set(e,{value:t,at:n}),t>=o.value){let a=t-o.value;return a>0?a:void 0}return t>0?t:void 0}prune(e){let t=e.getTime(),r=0;for(let[n,o]of this.last)if(o.at<t)this.last.delete(n),r++;return r}get size(){return this.last.size}}function St(e,t){let r=e[t];return typeof r==="string"&&r.length>0?r:void 0}function Mc(e,t,r={}){let n=r.mappings??$c,o=r.counters,a=[];for(let l of t){let u=up(l.name,n);if(!u)continue;let p=Xr(l,u);if(p==null)continue;if(u.cumulative){if(!o)continue;let g=[l.projectId,l.environmentId??"",l.resourceId??"",l.name,l.source].join("\x00"),m=o.delta(g,p,l.timestamp);if(m==null)continue;p=m}if(!(p>0))continue;let E={organizationId:e,projectId:l.projectId,environmentId:l.environmentId,resourceId:l.resourceId,provider:St(l.attributes,"provider")??r.defaultProvider,region:l.region??St(l.attributes,"region"),meter:u.meter,quantity:p,timestamp:l.timestamp,attributes:{source:l.source,signal:l.name}};a.push({...E,key:pp(E,l.id)})}return a}function Fc(e){let t=new Map;for(let r of e){let n=new Date(Math.floor(new Date(r.timestamp).getTime()/3600000)*3600000).toISOString(),o=[r.organizationId,r.projectId??"",r.environmentId??"",r.resourceId??"",r.provider??"",r.region??"",r.meter,n].join("\x00"),a=t.get(o);if(a)a.quantity+=r.quantity;else t.set(o,{...r,timestamp:n})}return[...t.values()]}import{createHash as Gr}from"node:crypto";var Fe=40,bc=[{version:1,name:"core_control_plane",sql:`
|
|
1
|
+
import{x,d}from"./chunk-jncbm332.js";import{_r}from"./chunk-fdn4wnd8.js";var tf=["edge.requests","edge.egress_gb","function.invocations","function.gb_seconds","build.minutes","compute.instance_hours","storage.gb_hours","object.egress_gb","object.requests","database.gb_hours","database.io_requests","telemetry.ingest_gb","image.transformations"],Ls={"edge.requests":{key:"edge.requests",unit:"requests",label:"Edge requests",precision:0},"edge.egress_gb":{key:"edge.egress_gb",unit:"gb",label:"Edge egress",precision:3},"function.invocations":{key:"function.invocations",unit:"invocations",label:"Function invocations",precision:0},"function.gb_seconds":{key:"function.gb_seconds",unit:"gb_seconds",label:"Function compute",precision:2},"build.minutes":{key:"build.minutes",unit:"minutes",label:"Build minutes",precision:2},"compute.instance_hours":{key:"compute.instance_hours",unit:"hours",label:"Instance hours",precision:2},"storage.gb_hours":{key:"storage.gb_hours",unit:"gb_hours",label:"Block storage",precision:2},"object.egress_gb":{key:"object.egress_gb",unit:"gb",label:"Object storage egress",precision:3},"object.requests":{key:"object.requests",unit:"requests",label:"Object storage requests",precision:0},"database.gb_hours":{key:"database.gb_hours",unit:"gb_hours",label:"Database storage",precision:2},"database.io_requests":{key:"database.io_requests",unit:"requests",label:"Database I/O",precision:0},"telemetry.ingest_gb":{key:"telemetry.ingest_gb",unit:"gb",label:"Telemetry ingest",precision:3},"image.transformations":{key:"image.transformations",unit:"count",label:"Image transformations",precision:0}},rf=["notify","block_builds","block_deployments","throttle_requests","suspend_functions","serve_static","suspend_project"],R={notify:0,block_builds:1,block_deployments:2,throttle_requests:3,suspend_functions:4,serve_static:5,suspend_project:6};var nf=1e6;function Sr(e){if(e.tiers&&e.tiers.length>0)return e.tiers;return[{upToQuantity:null,microCentsPerUnit:e.microCentsPerUnit??0}]}function Lc(e,t){if(!(e>0))return 0;let r=[...t].sort((l,u)=>{if(l.upToQuantity===null)return 1;if(u.upToQuantity===null)return-1;return l.upToQuantity-u.upToQuantity}),n=e,o=0,a=0;for(let l of r){if(n<=0)break;let p=(l.upToQuantity===null?1/0:l.upToQuantity)-o;if(p<=0)continue;let E=Math.min(n,p);a+=E*l.microCentsPerUnit,n-=E,o+=E}if(n>0){let l=r.reduce((u,p)=>Math.max(u,p.microCentsPerUnit),0);a+=n*l}return a}function Ap(e,t,r,n){let o=e.entries.filter((u)=>u.meter===t);if(o.length===0)return;let a=o.filter((u)=>u.provider===r),l=a.length>0?a:o.filter((u)=>u.provider==="*");return l.find((u)=>u.region===n)??l.find((u)=>u.region==null)}function $s(e,t,r=0){let n=Ap(e,t.meter,t.provider,t.region),o=Math.max(0,t.quantity);if(!n)return{meter:t.meter,provider:t.provider??"unknown",region:t.region,quantity:o,includedQuantity:0,billableQuantity:o,costCents:0,unpriced:!0};let a=Math.max(0,n.includedQuantity??0),l=Math.max(0,r-a),u=Math.max(0,a-Math.max(0,r)),p=Math.min(o,u),E=o-p,g=Sr(n),m=Lc(l+E,g)-Lc(l,g);return{meter:t.meter,provider:n.provider,region:n.region??t.region,quantity:o,includedQuantity:p,billableQuantity:E,costCents:m/1e6,unpriced:!1}}function sf(e,t){let r=new Map,n=[];for(let o of t){let a=`${o.meter}\x00${o.provider??""}\x00${o.region??""}`,l=r.get(a)??0,u=$s(e,o,l);r.set(a,l+u.quantity),n.push(u)}return{currency:e.currency,totalCents:n.reduce((o,a)=>o+a.costCents,0),lines:n,unpricedMeters:[...new Set(n.filter((o)=>o.unpriced).map((o)=>String(o.meter)))]}}function of(e){return Math.round(e*100)/100}function af(e,...t){let r=new Map,n=(a)=>`${a.meter}\x00${a.provider}\x00${a.region??""}`;for(let a of e.entries)r.set(n(a),a);let o=e.currency;for(let a of t){o=a.currency||o;for(let l of a.entries)r.set(n(l),l)}return{currency:o,entries:[...r.values()]}}var Y=(e)=>Math.round(e*1e6),H=(e)=>Math.round(e*1e6),$c={currency:"USD",entries:[{meter:"edge.requests",provider:"aws",microCentsPerUnit:H(0.00075)},{meter:"edge.egress_gb",provider:"aws",includedQuantity:100,tiers:[{upToQuantity:10240,microCentsPerUnit:Y(8.5)},{upToQuantity:51200,microCentsPerUnit:Y(8)},{upToQuantity:null,microCentsPerUnit:Y(6)}]},{meter:"function.invocations",provider:"aws",includedQuantity:1e6,microCentsPerUnit:H(0.002)},{meter:"function.gb_seconds",provider:"aws",includedQuantity:400000,microCentsPerUnit:H(0.00166667)},{meter:"storage.gb_hours",provider:"aws",microCentsPerUnit:H(0.010958904109589041)},{meter:"object.egress_gb",provider:"aws",includedQuantity:100,microCentsPerUnit:Y(9)},{meter:"object.requests",provider:"aws",microCentsPerUnit:H(0.000039999999999999996)},{meter:"database.gb_hours",provider:"aws",microCentsPerUnit:H(0.015753424657534248)},{meter:"compute.instance_hours",provider:"aws",microCentsPerUnit:H(4.16)},{meter:"edge.egress_gb",provider:"hetzner",includedQuantity:20480,microCentsPerUnit:Y(0.108)},{meter:"object.egress_gb",provider:"hetzner",includedQuantity:1024,microCentsPerUnit:Y(0.108)},{meter:"compute.instance_hours",provider:"hetzner",microCentsPerUnit:H(0.95)},{meter:"storage.gb_hours",provider:"hetzner",microCentsPerUnit:H(0.006027397260273972)},{meter:"edge.requests",provider:"hetzner",microCentsPerUnit:0},{meter:"edge.requests",provider:"local",microCentsPerUnit:0},{meter:"edge.egress_gb",provider:"local",microCentsPerUnit:0},{meter:"function.invocations",provider:"local",microCentsPerUnit:0},{meter:"function.gb_seconds",provider:"local",microCentsPerUnit:0},{meter:"build.minutes",provider:"*",includedQuantity:6000,microCentsPerUnit:H(0.8)},{meter:"telemetry.ingest_gb",provider:"*",includedQuantity:5,microCentsPerUnit:Y(50)},{meter:"image.transformations",provider:"*",includedQuantity:5000,microCentsPerUnit:H(0.05)}]};var vt=new Map;function It(e){let t=vt.get(e);if(!t)t=new Intl.DateTimeFormat("en-US",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",weekday:"short",hourCycle:"h23"}),vt.set(e,t);return t}var Ar={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6};function si(e){try{return It(e),!0}catch{return!1}}function Ms(e,t){let r=It(t).formatToParts(e),n=(o)=>r.find((a)=>a.type===o)?.value??"0";return{year:Number(n("year")),month:Number(n("month")),day:Number(n("day")),hour:Number(n("hour")),minute:Number(n("minute")),second:Number(n("second")),weekday:Ar[n("weekday")]??0}}function Mc(e,t){let r=Ms(e,t);return Date.UTC(r.year,r.month-1,r.day,r.hour,r.minute,r.second)-Math.floor(e.getTime()/1000)*1000}function Lt(e,t,r,n,o=0){let a=Date.UTC(t,r-1,n,o),l=new Date(a-Mc(new Date(a),e));return new Date(a-Mc(l,e))}function Or(e,t){return new Date(Date.UTC(e,t-1,1)).toLocaleString("en-US",{month:"long",year:"numeric",timeZone:"UTC"})}function ct(e,t,r=new Date){let n=si(t)?t:"UTC",o=Ms(r,n),a,l,u;if(e==="daily")a=Lt(n,o.year,o.month,o.day),l=Lt(n,o.year,o.month,o.day+1),u=`${o.year}-${String(o.month).padStart(2,"0")}-${String(o.day).padStart(2,"0")}`;else if(e==="weekly"){let g=(o.weekday+6)%7;a=Lt(n,o.year,o.month,o.day-g),l=Lt(n,o.year,o.month,o.day-g+7);let m=Ms(a,n);u=`week of ${m.year}-${String(m.month).padStart(2,"0")}-${String(m.day).padStart(2,"0")}`}else a=Lt(n,o.year,o.month,1),l=Lt(n,o.year,o.month+1,1),u=Or(o.year,o.month);let p=l.getTime()-a.getTime(),E=Math.max(0,Math.min(p,r.getTime()-a.getTime()));return{start:a.toISOString(),end:l.toISOString(),elapsedMs:E,totalMs:p,label:u}}function cf(e,t,r=new Date){let n=ct(e,t,r),o=new Date(new Date(n.start).getTime()-1),a=ct(e,t,o);return{...a,elapsedMs:a.totalMs}}function wr(e){let r=(typeof e==="string"?new Date(e):e).getTime();if(!Number.isFinite(r))throw Error("hourBucket requires a valid date");return new Date(Math.floor(r/3600000)*3600000).toISOString()}function df(e,t,r=9600){let n=Math.floor(new Date(e).getTime()/3600000)*3600000,o=new Date(t).getTime();if(!Number.isFinite(n)||!Number.isFinite(o))throw Error("hourBucketsBetween requires valid dates");let a=[];for(let l=n;l<o&&a.length<r;l+=3600000)a.push(new Date(l).toISOString());return a}import{createHash as Ur}from"node:crypto";var he=1073741824,Fc=[{match:"request.count",meter:"edge.requests"},{match:"traffic.requests",meter:"edge.requests"},{match:"http.request",meter:"edge.requests",field:"count"},{match:"traffic.bytes_out",meter:"edge.egress_gb",scale:1/he},{match:"storage.egress.day",meter:"object.egress_gb",scale:1/he},{match:"storage.egress.month",meter:"object.egress_gb",scale:1/he,cumulative:!0},{match:"storage.egress.day_downloads",meter:"object.requests"},{match:"function.invocation",meter:"function.invocations",field:"count"},{match:"function.duration_ms",meter:"function.gb_seconds",scale:0.001},{match:"build.duration_ms",meter:"build.minutes",scale:0.000016666666666666667},{match:"telemetry.ingest_bytes",meter:"telemetry.ingest_gb",scale:1/he},{match:"image.transform",meter:"image.transformations",field:"count"}];function Xr(e,t){return e.match.endsWith("*")?t.startsWith(e.match.slice(0,-1)):e.match===t}function yp(e,t=Fc){return t.find((r)=>!r.match.endsWith("*")&&r.match===e)??t.find((r)=>Xr(r,e))}function xr(e,t){let r=t.field??"value",n=r==="count"?1:r==="bytesOut"?e.bytesOut:r==="bytesIn"?e.bytesIn:r==="durationMs"?e.durationMs:e.value;if(n==null||!Number.isFinite(n))return;return n*(t.scale??1)}function Ip(e,t){return Ur("sha256").update([t,e.meter,e.organizationId,e.projectId??"",e.environmentId??"",e.resourceId??"",e.timestamp].join("\x00")).digest("hex").slice(0,32)}class Fs{resetToleranceRatio;last=new Map;constructor(e=0.999){this.resetToleranceRatio=e}delta(e,t,r=new Date){if(!Number.isFinite(t)||t<0)return;let n=new Date(r).getTime(),o=this.last.get(e);if(!o)return this.last.set(e,{value:t,at:n}),t>0?t:void 0;if(n<o.at)return;if(t<o.value&&t>=o.value*this.resetToleranceRatio)return;if(this.last.set(e,{value:t,at:n}),t>=o.value){let a=t-o.value;return a>0?a:void 0}return t>0?t:void 0}prune(e){let t=e.getTime(),r=0;for(let[n,o]of this.last)if(o.at<t)this.last.delete(n),r++;return r}get size(){return this.last.size}}function St(e,t){let r=e[t];return typeof r==="string"&&r.length>0?r:void 0}function Uc(e,t,r={}){let n=r.mappings??Fc,o=r.counters,a=[];for(let l of t){let u=yp(l.name,n);if(!u)continue;let p=xr(l,u);if(p==null)continue;if(u.cumulative){if(!o)continue;let g=[l.projectId,l.environmentId??"",l.resourceId??"",l.name,l.source].join("\x00"),m=o.delta(g,p,l.timestamp);if(m==null)continue;p=m}if(!(p>0))continue;let E={organizationId:e,projectId:l.projectId,environmentId:l.environmentId,resourceId:l.resourceId,provider:St(l.attributes,"provider")??r.defaultProvider,region:l.region??St(l.attributes,"region"),meter:u.meter,quantity:p,timestamp:l.timestamp,attributes:{source:l.source,signal:l.name}};a.push({...E,key:Ip(E,l.id)})}return a}function Qc(e){let t=new Map;for(let r of e){let n=new Date(Math.floor(new Date(r.timestamp).getTime()/3600000)*3600000).toISOString(),o=[r.organizationId,r.projectId??"",r.environmentId??"",r.resourceId??"",r.provider??"",r.region??"",r.meter,n].join("\x00"),a=t.get(o);if(a)a.quantity+=r.quantity;else t.set(o,{...r,timestamp:n})}return[...t.values()]}import{createHash as Gr}from"node:crypto";var Fe=40,vc=[{version:1,name:"core_control_plane",sql:`
|
|
2
2
|
CREATE TABLE projects (
|
|
3
3
|
id TEXT PRIMARY KEY,
|
|
4
4
|
slug TEXT NOT NULL UNIQUE,
|
|
@@ -1475,36 +1475,36 @@ import{_,d}from"./chunk-d72ddm5x.js";import{xr}from"./chunk-4yb7hf91.js";var Kh=
|
|
|
1475
1475
|
-- once a minute, forever.
|
|
1476
1476
|
CREATE INDEX telemetry_kind_scope_time_idx
|
|
1477
1477
|
ON telemetry_records(project_id, kind, timestamp);
|
|
1478
|
-
`}];import{createHash as Ne,randomBytes as Fr}from"node:crypto";import{chmodSync as Be,existsSync as bt,mkdirSync as Mr,statSync as zr}from"node:fs";import{dirname as Rt}from"node:path";import{Database as qr}from"bun:sqlite";var de=["project:read","config:read","config:write","deployments:read","deployments:create","deployments:cancel","deployments:rollback","runtime:read","runtime:restart","runtime:logs","runtime:terminal","data:read","data:write","data:admin","backups:read","backups:create","backups:restore","secrets:read","secrets:write","fleet:read","fleet:manage","users:read","users:manage","users:transfer-ownership","audit:read","billing:read","billing:manage","security:read","security:manage","security:waive","sources:read","sources:manage","applications:read","applications:manage","automation:read","automation:manage","tags:manage"],He=["project:read","config:read","deployments:read","runtime:read","runtime:logs","data:read","backups:read","security:read","sources:read","applications:read","billing:read"],jr={owner:new Set(de),admin:new Set(de.filter((e)=>e!=="users:transfer-ownership")),deployer:new Set([...He,"deployments:create","deployments:cancel","deployments:rollback","sources:manage","applications:manage"]),operator:new Set([...He,"runtime:restart","backups:create","security:manage","sources:manage","applications:manage"]),viewer:new Set(He),auditor:new Set(["project:read","config:read","deployments:read","runtime:read","data:read","backups:read","audit:read","security:read","sources:read","applications:read"])};function Bt(e){return jr[e]}function
|
|
1479
|
-
[output truncated]`}function fe(e){return{id:String(e.id),slug:String(e.slug),name:String(e.name),description:
|
|
1480
|
-
WHERE id = ? AND version = ?`,[r.name??n.name,r.description===null?null:r.description??n.description??null,r.organizationId===null?null:r.organizationId??n.organizationId??null,r.desiredConfigHash===null?null:r.desiredConfigHash??n.desiredConfigHash??null,this.now(),e,t]).changes!==1)throw new at("Project",e,t);return this.getProject(e)}createEnvironment(e){let t=e.id??this.idFn(),r=this.now();return
|
|
1481
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[t,e.projectId,e.slug,e.name,e.kind,e.region??null,
|
|
1482
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[t,e.projectId,e.environmentId??null,e.kind,e.slug,e.name,e.provider??null,e.providerId??null,
|
|
1483
|
-
version = version + 1, updated_at = ? WHERE id = ? AND version = ?`,[r.name??n.name,r.provider===null?null:r.provider??n.provider??null,r.providerId===null?null:r.providerId??n.providerId??null,
|
|
1478
|
+
`}];import{createHash as Ne,randomBytes as Fr}from"node:crypto";import{chmodSync as Be,existsSync as bt,mkdirSync as Mr,statSync as zr}from"node:fs";import{dirname as Rt}from"node:path";import{Database as qr}from"bun:sqlite";var de=["project:read","config:read","config:write","deployments:read","deployments:create","deployments:cancel","deployments:rollback","runtime:read","runtime:restart","runtime:logs","runtime:terminal","data:read","data:write","data:admin","backups:read","backups:create","backups:restore","secrets:read","secrets:write","fleet:read","fleet:manage","users:read","users:manage","users:transfer-ownership","audit:read","billing:read","billing:manage","security:read","security:manage","security:waive","sources:read","sources:manage","applications:read","applications:manage","automation:read","automation:manage","tags:manage"],He=["project:read","config:read","deployments:read","runtime:read","runtime:logs","data:read","backups:read","security:read","sources:read","applications:read","billing:read"],jr={owner:new Set(de),admin:new Set(de.filter((e)=>e!=="users:transfer-ownership")),deployer:new Set([...He,"deployments:create","deployments:cancel","deployments:rollback","sources:manage","applications:manage"]),operator:new Set([...He,"runtime:restart","backups:create","security:manage","sources:manage","applications:manage"]),viewer:new Set(He),auditor:new Set(["project:read","config:read","deployments:read","runtime:read","data:read","backups:read","audit:read","security:read","sources:read","applications:read"])};function Bt(e){return jr[e]}function Tc(e,t){if(e.type==="organization")return e.id===void 0||e.id===t.organizationId;if(!e.id)return!1;if(e.type==="project")return e.id===t.projectId;if(e.type==="environment")return e.id===t.environmentId;return e.id===t.resourceId}function w(e){let{membership:t,capability:r,target:n}=e;if(!t||t.status!=="active"||t.organizationId!==n.organizationId)return{allowed:!1,reason:"inactive-membership"};let o=e.grants.filter((u)=>u.organizationId===n.organizationId&&u.membershipId===t.id&&u.capability===r&&Tc(u.scope,n)),a=o.find((u)=>u.effect==="deny");if(a)return{allowed:!1,reason:"explicit-deny",inheritedFrom:{kind:"grant",id:a.id,scope:a.scope}};let l=o.find((u)=>u.effect==="allow");if(l)return{allowed:!0,reason:"explicit-allow",inheritedFrom:{kind:"grant",id:l.id,scope:l.scope}};if(!Tc(t.scope,n))return{allowed:!1,reason:"scope-mismatch"};if(Bt(t.roleTemplate).has(r))return{allowed:!0,reason:"role-template",inheritedFrom:{kind:"membership",id:t.id,scope:t.scope}};return{allowed:!1,reason:"missing-capability"}}function _t(e){return de.filter((t)=>w({...e,capability:t}).allowed)}class at extends Error{constructor(e,t,r){super(`${e} ${t} changed since version ${r}`);this.name="OptimisticConcurrencyError"}}class wc extends Error{constructor(e,t){super(`Operation cannot transition from ${e} to ${t}`);this.name="InvalidOperationTransitionError"}}class Ds extends Error{constructor(e,t){super(`Control-plane schema version ${e} is newer than supported version ${t}`);this.name="UnsupportedSchemaVersionError"}}function zh(){return x("control-plane.sqlite")}var hp=65536,Rc=16384,Hr=["succeeded","failed","cancelled","timed_out"],Br={queued:["running","cancelled","timed_out"],running:["queued","succeeded","failed","cancelled","timed_out"],succeeded:[],failed:["queued"],cancelled:["queued"],timed_out:["queued"]},Vr=/(?:^|_)(?:authorization|cookie|credential|password|passwd|secret|token|api_?key|private_?key|access_?key)(?:$|_)/i,Ct=/(?:authorization|password|secret|token|api[_-]?key|private[_-]?key|access[_-]?key)\s*[=:]\s*[^\s,;]+/gi;function z(e){if(typeof e!=="string")return{};try{return JSON.parse(e)}catch{return{}}}function S(e){return typeof e==="string"?e:void 0}function $e(e,t){if(t&&Vr.test(t))return"[REDACTED]";if(e===null||typeof e==="boolean"||typeof e==="number")return e;if(typeof e==="string")return e.replace(Ct,"[REDACTED]");if(Array.isArray(e))return e.map((r)=>$e(r));if(e&&typeof e==="object"){let r={};for(let[n,o]of Object.entries(e))r[n]=$e(o,n);return r}return String(e??"")}function s(e,t=hp){let r=$e(e),n=JSON.stringify(r);if(Buffer.byteLength(n)<=t)return r;return{truncated:!0,originalBytes:Buffer.byteLength(n),preview:n.slice(0,Math.max(0,t-128))}}function b(e){return JSON.stringify(s(e))}function Ve(e){if(!e)return;let t=e.replace(Ct,"[REDACTED]");return Buffer.byteLength(t)<=Rc?t:`${t.slice(0,Rc-24)}
|
|
1479
|
+
[output truncated]`}function fe(e){return{id:String(e.id),slug:String(e.slug),name:String(e.name),description:S(e.description),organizationId:S(e.organization_id),desiredConfigHash:S(e.desired_config_hash),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function ye(e){return{id:String(e.id),projectId:String(e.project_id),slug:String(e.slug),name:String(e.name),kind:String(e.kind),region:S(e.region),desiredState:z(e.desired_state),discoveredState:z(e.discovered_state),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Le(e){return{id:String(e.id),projectId:String(e.project_id),environmentId:S(e.environment_id),kind:String(e.kind),slug:String(e.slug),name:String(e.name),provider:S(e.provider),providerId:S(e.provider_id),desiredState:z(e.desired_state),discoveredState:z(e.discovered_state),metadata:z(e.metadata),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function ve(e){return{id:String(e.id),kind:String(e.kind),externalId:S(e.external_id),displayName:String(e.display_name),metadata:z(e.metadata),disabledAt:S(e.disabled_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function G(e){return{id:String(e.id),projectId:S(e.project_id),environmentId:S(e.environment_id),resourceId:S(e.resource_id),actorId:S(e.actor_id),kind:String(e.kind),state:String(e.state),correlationId:String(e.correlation_id),idempotencyKey:S(e.idempotency_key),input:z(e.input),output:z(e.output),error:S(e.error),attempt:Number(e.attempt),priority:Number(e.priority),leaseOwner:S(e.lease_owner),leaseExpiresAt:S(e.lease_expires_at),cancelRequestedAt:S(e.cancel_requested_at),startedAt:S(e.started_at),finishedAt:S(e.finished_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Ke(e){return{id:String(e.id),sequence:Number(e.sequence),organizationId:S(e.organization_id),projectId:S(e.project_id),operationId:S(e.operation_id),resourceId:S(e.resource_id),actorId:S(e.actor_id),correlationId:String(e.correlation_id),type:String(e.type),level:String(e.level),payload:z(e.payload),createdAt:String(e.created_at)}}function oe(e){return{id:String(e.id),projectId:String(e.project_id),name:String(e.name),normalizedName:String(e.normalized_name),color:String(e.color),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Ie(e){return{id:String(e.id),actorKey:String(e.actor_key),name:String(e.name),routeId:String(e.route_id),query:z(e.query),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Se(e){return{actorKey:String(e.actor_key),entityType:String(e.entity_type),entityId:String(e.entity_id),favorite:Number(e.favorite)===1,lastVisitedAt:String(e.last_visited_at),visitCount:Number(e.visit_count)}}function be(e){return{id:String(e.id),slug:String(e.slug),name:String(e.name),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Ye(e){let t=String(e.scope_type);return{type:t,...t==="organization"?{}:{id:String(e.scope_id)}}}function Re(e){return{id:String(e.id),organizationId:String(e.organization_id),actorId:String(e.actor_id),roleTemplate:String(e.role_template),scope:Ye(e),source:String(e.source??"manual"),status:String(e.status),sessionVersion:Number(e.session_version),lastActiveAt:S(e.last_active_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function se(e,t){let r=S(e.accepted_at),n=S(e.revoked_at),o=String(e.expires_at),a=n?"revoked":r?"accepted":o<=t?"expired":"pending";return{id:String(e.id),organizationId:String(e.organization_id),email:String(e.email),roleTemplate:String(e.role_template),scope:Ye(e),invitedByActorId:S(e.invited_by_actor_id),acceptedByActorId:S(e.accepted_by_actor_id),expiresAt:o,acceptedAt:r,revokedAt:n,state:a,createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Ce(e){return{id:String(e.id),organizationId:String(e.organization_id),membershipId:String(e.membership_id),effect:String(e.effect),capability:String(e.capability),scope:Ye(e),source:String(e.source??"manual"),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function ae(e){return{type:e.type,id:e.id??null}}function Kr(e){return Array.from({length:e},()=>"?").join(", ")}function f(e,t,r){return e.run(t,r)}class ni{path;database;nowFn;idFn;constructor(e={}){this.path=e.path??d(e.cwd??process.cwd(),"control-plane.sqlite"),this.nowFn=e.now??(()=>new Date),this.idFn=e.id??(()=>crypto.randomUUID());let t=this.path===":memory:";if(!t){Mr(Rt(this.path),{recursive:!0,mode:448});try{Be(Rt(this.path),448)}catch{}}if(this.database=new qr(this.path,{create:!0,strict:!0}),this.database.run("PRAGMA foreign_keys = ON"),this.database.run(`PRAGMA busy_timeout = ${Math.max(100,e.busyTimeoutMs??5000)}`),!t)this.database.run("PRAGMA journal_mode = WAL"),this.database.run("PRAGMA synchronous = NORMAL");if(this.migrate(),!t)this.secureDatabaseFiles()}now(){return this.nowFn().toISOString()}secureDatabaseFiles(){for(let e of[this.path,`${this.path}-wal`,`${this.path}-shm`]){if(!bt(e))continue;try{Be(e,384)}catch{}}}backupTo(e){this.database.run("VACUUM INTO ?",[e]);try{Be(e,384)}catch{}}migrate(){let e=this.database.query("PRAGMA user_version").get(),t=Number(e?.user_version??0);if(t>Fe)throw new Ds(t,Fe);if(t===Fe)return;let r;if(t>0&&this.path!==":memory:")r=`${this.path}.v${t}.${Date.now()}.bak`,this.backupTo(r);try{if(this.database.transaction(()=>{for(let o of vc){if(o.version<=t)continue;this.database.run(o.sql),f(this.database,"INSERT INTO schema_migrations (version, name, applied_at) VALUES (?, ?, ?)",[o.version,o.name,this.now()]),this.database.run(`PRAGMA user_version = ${o.version}`)}}).exclusive(),r)this.setSetting("storage.last_backup",{path:r,createdAt:this.now(),reason:"pre-migration"})}catch(n){let o=r?` Restore from ${r}.`:"";throw Error(`Control-plane migration from schema ${t} failed.${o} ${n instanceof Error?n.message:String(n)}`)}}close(){if(this.path!==":memory:")this.secureDatabaseFiles();this.database.close()}transaction(e){return this.database.transaction(e).immediate()}createProject(e){let t=e.id??this.idFn(),r=this.now();return f(this.database,"INSERT INTO projects (id, slug, name, description, organization_id, desired_config_hash, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",[t,e.slug,e.name,e.description??null,e.organizationId??null,e.desiredConfigHash??null,r,r]),this.getProject(t)}getProject(e){let t=this.database.query("SELECT * FROM projects WHERE id = ?").get(e);return t?fe(t):void 0}getProjectBySlug(e){let t=this.database.query("SELECT * FROM projects WHERE slug = ?").get(e);return t?fe(t):void 0}listProjects(){return this.database.query("SELECT * FROM projects ORDER BY name COLLATE NOCASE, id").all().map(fe)}updateProject(e,t,r){let n=this.getProject(e);if(!n||n.version!==t)throw new at("Project",e,t);if(f(this.database,`UPDATE projects SET name = ?, description = ?, organization_id = ?, desired_config_hash = ?, version = version + 1, updated_at = ?
|
|
1480
|
+
WHERE id = ? AND version = ?`,[r.name??n.name,r.description===null?null:r.description??n.description??null,r.organizationId===null?null:r.organizationId??n.organizationId??null,r.desiredConfigHash===null?null:r.desiredConfigHash??n.desiredConfigHash??null,this.now(),e,t]).changes!==1)throw new at("Project",e,t);return this.getProject(e)}createEnvironment(e){let t=e.id??this.idFn(),r=this.now();return f(this.database,`INSERT INTO environments (id, project_id, slug, name, kind, region, desired_state, discovered_state, created_at, updated_at)
|
|
1481
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[t,e.projectId,e.slug,e.name,e.kind,e.region??null,b(e.desiredState??{}),b(e.discoveredState??{}),r,r]),ye(this.database.query("SELECT * FROM environments WHERE id = ?").get(t))}listEnvironments(e){return this.database.query("SELECT * FROM environments WHERE project_id = ? ORDER BY name COLLATE NOCASE, id").all(e).map(ye)}getEnvironmentBySlug(e,t){let r=this.database.query("SELECT * FROM environments WHERE project_id = ? AND slug = ?").get(e,t);return r?ye(r):void 0}createResource(e){let t=e.id??this.idFn(),r=this.now();return f(this.database,`INSERT INTO resources (id, project_id, environment_id, kind, slug, name, provider, provider_id, desired_state, discovered_state, metadata, created_at, updated_at)
|
|
1482
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[t,e.projectId,e.environmentId??null,e.kind,e.slug,e.name,e.provider??null,e.providerId??null,b(e.desiredState??{}),b(e.discoveredState??{}),b(e.metadata??{}),r,r]),Le(this.database.query("SELECT * FROM resources WHERE id = ?").get(t))}listResources(e,t){return(t?this.database.query("SELECT * FROM resources WHERE project_id = ? AND environment_id = ? ORDER BY kind, name COLLATE NOCASE").all(e,t):this.database.query("SELECT * FROM resources WHERE project_id = ? ORDER BY kind, name COLLATE NOCASE").all(e)).map(Le)}getResource(e){let t=this.database.query("SELECT * FROM resources WHERE id = ?").get(e);return t?Le(t):void 0}updateResource(e,t,r){let n=this.getResource(e);if(!n||n.version!==t)throw new at("Resource",e,t);if(f(this.database,`UPDATE resources SET name = ?, provider = ?, provider_id = ?, desired_state = ?, discovered_state = ?, metadata = ?,
|
|
1483
|
+
version = version + 1, updated_at = ? WHERE id = ? AND version = ?`,[r.name??n.name,r.provider===null?null:r.provider??n.provider??null,r.providerId===null?null:r.providerId??n.providerId??null,b(r.desiredState??n.desiredState),b(r.discoveredState??n.discoveredState),b(r.metadata??n.metadata),this.now(),e,t]).changes!==1)throw new at("Resource",e,t);return this.getResource(e)}createActor(e){let t=e.id??this.idFn(),r=this.now();return f(this.database,"INSERT INTO actors (id, kind, external_id, display_name, metadata, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[t,e.kind,e.externalId??null,e.displayName,b(e.metadata??{}),r,r]),ve(this.database.query("SELECT * FROM actors WHERE id = ?").get(t))}getActorByExternalId(e,t){let r=this.database.query("SELECT * FROM actors WHERE kind = ? AND external_id = ?").get(e,t);return r?ve(r):void 0}getActor(e){let t=this.database.query("SELECT * FROM actors WHERE id = ?").get(e);return t?ve(t):void 0}createOrganization(e){let t=e.slug.trim().toLowerCase();if(!/^[a-z0-9][a-z0-9-]{1,62}[a-z0-9]$/.test(t))throw Error("Organization slugs must contain 3-64 lowercase letters, numbers, or dashes");let r=e.name.trim();if(!r||r.length>100)throw Error("Organization names must contain 1-100 characters");let n=e.id??this.idFn(),o=this.now();return f(this.database,"INSERT INTO organizations (id, slug, name, created_at, updated_at) VALUES (?, ?, ?, ?, ?)",[n,t,r,o,o]),this.getOrganization(n)}getOrganization(e){let t=this.database.query("SELECT * FROM organizations WHERE id = ?").get(e);return t?be(t):void 0}getOrganizationBySlug(e){let t=this.database.query("SELECT * FROM organizations WHERE slug = ?").get(e.trim().toLowerCase());return t?be(t):void 0}listOrganizations(e){return(e?this.database.query(`SELECT organizations.* FROM organizations JOIN organization_memberships ON organization_memberships.organization_id = organizations.id
|
|
1484
1484
|
WHERE organization_memberships.actor_id = ? AND organization_memberships.status = 'active' ORDER BY organizations.name COLLATE NOCASE`).all(e):this.database.query("SELECT * FROM organizations ORDER BY name COLLATE NOCASE").all()).map(be)}normalizeAuthorizationScope(e,t={type:"organization"}){if(t.type==="organization"){if(t.id&&t.id!==e)throw Error("Organization scope does not match the requested organization");return{type:"organization"}}if(!t.id)throw Error(`${t.type} scopes require an ID`);if(!this.resolveAuthorizationTarget(e,t))throw Error("Authorization scope was not found in this organization");return{type:t.type,id:t.id}}resolveAuthorizationTarget(e,t){if(!this.getOrganization(e))return;if(t.type==="organization")return{organizationId:e};if(!t.id)return;if(t.type==="project"){let n=this.database.query("SELECT id FROM projects WHERE id = ? AND organization_id = ?").get(t.id,e);return n?{organizationId:e,projectId:String(n.id)}:void 0}if(t.type==="environment"){let n=this.database.query("SELECT environments.id, environments.project_id FROM environments JOIN projects ON projects.id = environments.project_id WHERE environments.id = ? AND projects.organization_id = ?").get(t.id,e);return n?{organizationId:e,projectId:String(n.project_id),environmentId:String(n.id)}:void 0}let r=this.database.query(`SELECT resources.id, resources.project_id, resources.environment_id FROM resources
|
|
1485
|
-
JOIN projects ON projects.id = resources.project_id WHERE resources.id = ? AND projects.organization_id = ?`).get(t.id,e);return r?{organizationId:e,projectId:String(r.project_id),environmentId:
|
|
1486
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[r,e.organizationId,e.actorId,e.roleTemplate,t.type,t.id??null,e.source??"manual",n,n]);let o=this.getMembership(r);return this.appendEvent({organizationId:e.organizationId,actorId:e.performedByActorId,type:"organization.membership.created",payload:{membershipId:r,actorId:e.actorId,roleTemplate:e.roleTemplate,scope:ae(t)}}),o}getMembership(e){let t=this.database.query("SELECT * FROM organization_memberships WHERE id = ?").get(e);return t?Re(t):void 0}getMembershipForActor(e,t){let r=this.database.query("SELECT * FROM organization_memberships WHERE organization_id = ? AND actor_id = ?").get(e,t);return r?Re(r):void 0}listMemberships(e,t={}){let r=t.includeRevoked?"":"AND status = 'active'";return this.database.query(`SELECT * FROM organization_memberships WHERE organization_id = ? ${r} ORDER BY created_at, id`).all(e).map(Re)}updateMembership(e){let t=this.getMembership(e.id);if(!t)throw Error("Membership was not found");let r=this.normalizeAuthorizationScope(t.organizationId,e.scope??t.scope);if(e.roleTemplate==="owner"&&r.type!=="organization")throw Error("Owners must be scoped to the organization");if(t.roleTemplate==="owner"&&t.status==="active"&&(e.roleTemplate!=="owner"||r.type!=="organization"))this.assertAnotherOwner(t);return
|
|
1487
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[a,e.organizationId,t,e.roleTemplate,r.type,r.id??null,o,e.invitedByActorId??null,u,l,l]),this.appendEvent({organizationId:e.organizationId,actorId:e.invitedByActorId,type:"organization.invitation.created",payload:{invitationId:a,email:t,roleTemplate:e.roleTemplate,scope:ae(r),expiresAt:u}}),{invitation:this.getInvitation(a),token:n}}getInvitation(e){let t=this.database.query("SELECT * FROM organization_invitations WHERE id = ?").get(e);return t?se(t,this.now()):void 0}listInvitations(e){return this.database.query("SELECT * FROM organization_invitations WHERE organization_id = ? ORDER BY created_at DESC").all(e).map((t)=>se(t,this.now()))}inspectInvitationToken(e){let t=Ne("sha256").update(e).digest("hex"),r=this.database.query("SELECT * FROM organization_invitations WHERE token_hash = ?").get(t);return r?se(r,this.now()):void 0}acceptInvitation(e,t){let r=Ne("sha256").update(e).digest("hex");return this.transaction(()=>{let n=this.database.query("SELECT * FROM organization_invitations WHERE token_hash = ?").get(r);if(!n)throw Error("Invitation is invalid");let o=se(n,this.now());if(o.state!=="pending")throw Error(`Invitation is ${o.state}`);if(!this.getActor(t))throw Error("Invitation actor was not found");if(
|
|
1488
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[a,e.organizationId,e.membershipId,e.effect,e.capability,r.type,r.id??null,e.source??"manual",n,n]),
|
|
1489
|
-
VALUES (?, ?, ?, ?, ?, ?, 'queued', ?, ?, ?, '{}', ?, ?, ?)`,[t,e.projectId??null,e.environmentId??null,e.resourceId??null,e.actorId??null,e.kind,r,e.idempotencyKey??null,
|
|
1490
|
-
started_at = COALESCE(started_at, ?), updated_at = ?, version = version + 1 WHERE id = ? AND state = 'queued' AND version = ?`,[e,o,n,n,p.id,p.version]).changes!==1)return;return this.appendEvent({projectId:p.projectId,operationId:p.id,resourceId:p.resourceId,actorId:p.actorId,correlationId:p.correlationId,type:"operation.running",payload:{attempt:p.attempt+1,workerId:e}}),this.getOperation(p.id)})}claimOperation(e,t,r=60000){let n=this.now(),o=new Date(this.nowFn().getTime()+r).toISOString();return this.transaction(()=>{let a=this.getOperation(e);if(!a||a.state!=="queued")return;if(
|
|
1491
|
-
started_at = COALESCE(started_at, ?), updated_at = ?, version = version + 1 WHERE id = ? AND state = 'queued' AND version = ?`,[t,o,n,n,a.id,a.version]).changes!==1)return;return this.appendEvent({projectId:a.projectId,operationId:a.id,resourceId:a.resourceId,actorId:a.actorId,correlationId:a.correlationId,type:"operation.running",payload:{attempt:a.attempt+1,workerId:t}}),this.getOperation(a.id)})}transitionOperation(e,t){return this.transaction(()=>{let r=this.getOperation(e);if(!r)throw Error(`Operation ${e} was not found`);let n=t.expectedVersion??r.version;if(r.version!==n)throw new at("Operation",e,n);if(!Br[r.state].includes(t.to))throw new
|
|
1492
|
-
finished_at = ?, updated_at = ?, version = version + 1 WHERE id = ? AND version = ?`,[t.to,
|
|
1493
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[t,n??null,e.projectId??null,e.operationId??null,e.resourceId??null,e.actorId??null,r,e.type,e.level??"info",
|
|
1494
|
-
ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`,[e,
|
|
1495
|
-
WHERE tags.project_id = ? ORDER BY tags.normalized_name`).all(e).map((r)=>({resourceId:String(r.resource_id),tag:oe(r)}))}saveFilter(e,t,r,n){let o=t.trim();if(!o||o.length>64)throw Error("Saved filter names must contain 1-64 characters");if(!r||r.length>160||/^[a-z][a-z0-9+.-]*:|^\/\//i.test(r))throw Error("Saved filter routes must be local route IDs or paths");let a=
|
|
1496
|
-
ON CONFLICT(actor_key, entity_type, entity_id) DO UPDATE SET last_visited_at = excluded.last_visited_at, visit_count = visit_count + 1`,[e,t,r,n]),Se(this.database.query("SELECT * FROM navigation_items WHERE actor_key = ? AND entity_type = ? AND entity_id = ?").get(e,t,r))}setFavorite(e,t,r,n){let o=this.now();return
|
|
1497
|
-
ON CONFLICT(actor_key, entity_type, entity_id) DO UPDATE SET favorite = excluded.favorite`,[e,t,r,n?1:0,o]),Se(this.database.query("SELECT * FROM navigation_items WHERE actor_key = ? AND entity_type = ? AND entity_id = ?").get(e,t,r))}listNavigation(e,t={}){let r=t.favoritesOnly?"AND favorite = 1":"",n=Math.min(100,Math.max(1,t.limit??20));return this.database.query(`SELECT * FROM navigation_items WHERE actor_key = ? ${r} ORDER BY favorite DESC, last_visited_at DESC LIMIT ?`).all(e,n).map(Se)}compact(e={}){let t=new Date(this.nowFn().getTime()-(e.eventRetentionDays??90)*86400000).toISOString(),r=new Date(this.nowFn().getTime()-(e.operationRetentionDays??365)*86400000).toISOString(),n=this.transaction(()=>{let o=
|
|
1498
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n.id,n.slug,n.name,n.description??null,n.organizationId??null,n.desiredConfigHash??null,n.version,n.createdAt,n.updatedAt]);for(let n of e.environments)
|
|
1499
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n.id,n.projectId,n.slug,n.name,n.kind,n.region??null,
|
|
1500
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n.id,n.projectId,n.environmentId??null,n.kind,n.slug,n.name,n.provider??null,n.providerId??null,
|
|
1501
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n.id,n.kind,n.externalId??null,n.displayName,
|
|
1502
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n.id,n.organizationId,n.actorId,n.roleTemplate,n.scope.type,n.scope.id??null,n.status,n.sessionVersion,n.lastActiveAt??null,n.source??"manual",n.createdAt,n.updatedAt]);for(let n of e.invitations??[]){let o=n.tokenHash??Ne("sha256").update(`revoked:${n.id}:${this.idFn()}`).digest("hex");
|
|
1503
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n.id,n.organizationId,n.email,n.roleTemplate,n.scope.type,n.scope.id??null,o,n.invitedByActorId??null,n.acceptedByActorId??null,n.expiresAt,n.acceptedAt??null,n.tokenHash?n.revokedAt??null:n.revokedAt??this.now(),n.createdAt,n.updatedAt])}for(let n of e.grants??[])
|
|
1504
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n.id,n.organizationId,n.membershipId,n.effect,n.capability,n.scope.type,n.scope.id??null,n.source??"manual",n.createdAt,n.updatedAt]);for(let n of e.operations)
|
|
1485
|
+
JOIN projects ON projects.id = resources.project_id WHERE resources.id = ? AND projects.organization_id = ?`).get(t.id,e);return r?{organizationId:e,projectId:String(r.project_id),environmentId:S(r.environment_id),resourceId:String(r.id)}:void 0}createMembership(e){if(!this.getActor(e.actorId))throw Error("Membership actor was not found");let t=this.normalizeAuthorizationScope(e.organizationId,e.scope);if(e.roleTemplate==="owner"&&t.type!=="organization")throw Error("Owners must be scoped to the organization");let r=e.id??this.idFn(),n=this.now();f(this.database,`INSERT INTO organization_memberships (id, organization_id, actor_id, role_template, scope_type, scope_id, source, created_at, updated_at)
|
|
1486
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[r,e.organizationId,e.actorId,e.roleTemplate,t.type,t.id??null,e.source??"manual",n,n]);let o=this.getMembership(r);return this.appendEvent({organizationId:e.organizationId,actorId:e.performedByActorId,type:"organization.membership.created",payload:{membershipId:r,actorId:e.actorId,roleTemplate:e.roleTemplate,scope:ae(t)}}),o}getMembership(e){let t=this.database.query("SELECT * FROM organization_memberships WHERE id = ?").get(e);return t?Re(t):void 0}getMembershipForActor(e,t){let r=this.database.query("SELECT * FROM organization_memberships WHERE organization_id = ? AND actor_id = ?").get(e,t);return r?Re(r):void 0}listMemberships(e,t={}){let r=t.includeRevoked?"":"AND status = 'active'";return this.database.query(`SELECT * FROM organization_memberships WHERE organization_id = ? ${r} ORDER BY created_at, id`).all(e).map(Re)}updateMembership(e){let t=this.getMembership(e.id);if(!t)throw Error("Membership was not found");let r=this.normalizeAuthorizationScope(t.organizationId,e.scope??t.scope);if(e.roleTemplate==="owner"&&r.type!=="organization")throw Error("Owners must be scoped to the organization");if(t.roleTemplate==="owner"&&t.status==="active"&&(e.roleTemplate!=="owner"||r.type!=="organization"))this.assertAnotherOwner(t);return f(this.database,"UPDATE organization_memberships SET role_template = ?, scope_type = ?, scope_id = ?, session_version = session_version + 1, updated_at = ? WHERE id = ?",[e.roleTemplate,r.type,r.id??null,this.now(),t.id]),this.appendEvent({organizationId:t.organizationId,actorId:e.actorId,type:"organization.membership.updated",payload:{membershipId:t.id,from:{roleTemplate:t.roleTemplate,scope:ae(t.scope)},to:{roleTemplate:e.roleTemplate,scope:ae(r)}}}),this.getMembership(t.id)}revokeMembership(e,t){let r=this.getMembership(e);if(!r)throw Error("Membership was not found");if(r.status==="revoked")return r;if(r.roleTemplate==="owner")this.assertAnotherOwner(r);return f(this.database,"UPDATE organization_memberships SET status = 'revoked', session_version = session_version + 1, updated_at = ? WHERE id = ?",[this.now(),e]),this.appendEvent({organizationId:r.organizationId,actorId:t,type:"organization.membership.revoked",payload:{membershipId:e}}),this.getMembership(e)}touchMembership(e){let t=this.now();f(this.database,"UPDATE organization_memberships SET last_active_at = ?, updated_at = ? WHERE id = ? AND status = ?",[t,t,e,"active"]);let r=this.getMembership(e);if(!r)throw Error("Membership was not found");return r}assertAnotherOwner(e){if(Number(this.database.query("SELECT COUNT(*) AS count FROM organization_memberships WHERE organization_id = ? AND status = ? AND role_template = 'owner'").get(e.organizationId,"active")?.count??0)<=1)throw Error("Cannot remove or demote the last organization owner")}createInvitation(e){let t=e.email.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)||t.length>254)throw Error("A valid invitation email is required");let r=this.normalizeAuthorizationScope(e.organizationId,e.scope);if(e.roleTemplate==="owner"&&r.type!=="organization")throw Error("Owners must be scoped to the organization");let n=Fr(32).toString("base64url"),o=Ne("sha256").update(n).digest("hex"),a=e.id??this.idFn(),l=this.now(),u=new Date(this.nowFn().getTime()+Math.min(2592000000,Math.max(60000,e.expiresInMs??604800000))).toISOString();return f(this.database,`INSERT INTO organization_invitations (id, organization_id, email, role_template, scope_type, scope_id, token_hash, invited_by_actor_id, expires_at, created_at, updated_at)
|
|
1487
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[a,e.organizationId,t,e.roleTemplate,r.type,r.id??null,o,e.invitedByActorId??null,u,l,l]),this.appendEvent({organizationId:e.organizationId,actorId:e.invitedByActorId,type:"organization.invitation.created",payload:{invitationId:a,email:t,roleTemplate:e.roleTemplate,scope:ae(r),expiresAt:u}}),{invitation:this.getInvitation(a),token:n}}getInvitation(e){let t=this.database.query("SELECT * FROM organization_invitations WHERE id = ?").get(e);return t?se(t,this.now()):void 0}listInvitations(e){return this.database.query("SELECT * FROM organization_invitations WHERE organization_id = ? ORDER BY created_at DESC").all(e).map((t)=>se(t,this.now()))}inspectInvitationToken(e){let t=Ne("sha256").update(e).digest("hex"),r=this.database.query("SELECT * FROM organization_invitations WHERE token_hash = ?").get(t);return r?se(r,this.now()):void 0}acceptInvitation(e,t){let r=Ne("sha256").update(e).digest("hex");return this.transaction(()=>{let n=this.database.query("SELECT * FROM organization_invitations WHERE token_hash = ?").get(r);if(!n)throw Error("Invitation is invalid");let o=se(n,this.now());if(o.state!=="pending")throw Error(`Invitation is ${o.state}`);if(!this.getActor(t))throw Error("Invitation actor was not found");if(f(this.database,"UPDATE organization_invitations SET accepted_by_actor_id = ?, accepted_at = ?, updated_at = ? WHERE id = ? AND accepted_at IS NULL AND revoked_at IS NULL AND expires_at > ?",[t,this.now(),this.now(),o.id,this.now()]).changes!==1)throw Error("Invitation is no longer available");let l=this.getMembershipForActor(o.organizationId,t),u=l??this.createMembership({organizationId:o.organizationId,actorId:t,roleTemplate:o.roleTemplate,scope:o.scope,source:"invitation"});if(l&&o.roleTemplate==="owner"&&l.roleTemplate!=="owner")u=this.updateMembership({id:l.id,roleTemplate:"owner",scope:{type:"organization"},actorId:t});else if(l)for(let p of Bt(o.roleTemplate))this.upsertGrant({organizationId:o.organizationId,membershipId:l.id,effect:"allow",capability:p,scope:o.scope,source:"invitation"});return this.appendEvent({organizationId:o.organizationId,actorId:t,type:"organization.invitation.accepted",payload:{invitationId:o.id,membershipId:u.id}}),{invitation:this.getInvitation(o.id),membership:this.getMembership(u.id)}})}revokeInvitation(e,t){let r=this.getInvitation(e);if(!r)throw Error("Invitation was not found");if(r.acceptedAt)throw Error("Accepted invitations cannot be revoked");if(!r.revokedAt)f(this.database,"UPDATE organization_invitations SET revoked_at = ?, updated_at = ? WHERE id = ?",[this.now(),this.now(),e]);return this.appendEvent({organizationId:r.organizationId,actorId:t,type:"organization.invitation.revoked",payload:{invitationId:e}}),this.getInvitation(e)}reissueInvitation(e,t){let r=this.getInvitation(e);if(!r)throw Error("Invitation was not found");if(r.state==="accepted")throw Error("Accepted invitations cannot be reissued");return this.revokeInvitation(e,t),this.createInvitation({organizationId:r.organizationId,email:r.email,roleTemplate:r.roleTemplate,scope:r.scope,invitedByActorId:t})}upsertGrant(e){if(!de.includes(e.capability))throw Error("Unknown authorization capability");let t=this.getMembership(e.membershipId);if(!t||t.organizationId!==e.organizationId)throw Error("Grant membership was not found in this organization");let r=this.normalizeAuthorizationScope(e.organizationId,e.scope),n=this.now(),o=this.database.query("SELECT * FROM authorization_grants WHERE membership_id = ? AND effect = ? AND capability = ? AND scope_type = ? AND scope_id IS ?").get(e.membershipId,e.effect,e.capability,r.type,r.id??null);if(o)return Ce(o);let a=e.id??this.idFn();return f(this.database,`INSERT INTO authorization_grants (id, organization_id, membership_id, effect, capability, scope_type, scope_id, source, created_at, updated_at)
|
|
1488
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[a,e.organizationId,e.membershipId,e.effect,e.capability,r.type,r.id??null,e.source??"manual",n,n]),f(this.database,"UPDATE organization_memberships SET session_version = session_version + 1, updated_at = ? WHERE id = ?",[n,e.membershipId]),this.appendEvent({organizationId:e.organizationId,actorId:e.actorId,type:"organization.grant.created",payload:{grantId:a,membershipId:e.membershipId,effect:e.effect,capability:e.capability,scope:ae(r)}}),this.getGrant(a)}getGrant(e){let t=this.database.query("SELECT * FROM authorization_grants WHERE id = ?").get(e);return t?Ce(t):void 0}listGrants(e){return this.database.query("SELECT * FROM authorization_grants WHERE membership_id = ? ORDER BY effect DESC, capability, scope_type, scope_id").all(e).map(Ce)}removeGrant(e,t){let r=this.getGrant(e);if(!r)return!1;let n=f(this.database,"DELETE FROM authorization_grants WHERE id = ?",[e]).changes===1;if(n)f(this.database,"UPDATE organization_memberships SET session_version = session_version + 1, updated_at = ? WHERE id = ?",[this.now(),r.membershipId]),this.appendEvent({organizationId:r.organizationId,actorId:t,type:"organization.grant.removed",payload:{grantId:e,membershipId:r.membershipId}});return n}createOperation(e){if(e.idempotencyKey){let o=this.database.query("SELECT * FROM operations WHERE idempotency_key = ?").get(e.idempotencyKey);if(o)return G(o)}let t=e.id??this.idFn(),r=e.correlationId??this.idFn(),n=this.now();try{return this.transaction(()=>(f(this.database,`INSERT INTO operations (id, project_id, environment_id, resource_id, actor_id, kind, state, correlation_id, idempotency_key, input, output, priority, created_at, updated_at)
|
|
1489
|
+
VALUES (?, ?, ?, ?, ?, ?, 'queued', ?, ?, ?, '{}', ?, ?, ?)`,[t,e.projectId??null,e.environmentId??null,e.resourceId??null,e.actorId??null,e.kind,r,e.idempotencyKey??null,b(e.input??{}),e.priority??0,n,n]),this.appendEvent({projectId:e.projectId,operationId:t,resourceId:e.resourceId,actorId:e.actorId,correlationId:r,type:"operation.queued",payload:{kind:e.kind}}),this.getOperation(t)))}catch(o){if(e.idempotencyKey){let a=this.database.query("SELECT * FROM operations WHERE idempotency_key = ?").get(e.idempotencyKey);if(a)return G(a)}throw o}}getOperation(e){let t=this.database.query("SELECT * FROM operations WHERE id = ?").get(e);return t?G(t):void 0}listOperations(e={}){let t=[],r=[];if(e.projectId)t.push("project_id = ?"),r.push(e.projectId);if(e.state)t.push("state = ?"),r.push(e.state);if(e.kind)t.push("kind = ?"),r.push(e.kind);if(e.before)t.push("created_at < ?"),r.push(e.before);let n=Math.min(500,Math.max(1,e.limit??100));r.push(n);let o=t.length?`WHERE ${t.join(" AND ")}`:"";return this.database.query(`SELECT * FROM operations ${o} ORDER BY created_at DESC, id DESC LIMIT ?`).all(...r).map(G)}claimNextOperation(e,t=60000,r){let n=this.now(),o=new Date(this.nowFn().getTime()+t).toISOString();return this.transaction(()=>{let a=r?.length?`AND kind IN (${Kr(r.length)})`:"",l=r?[...r]:[],u=this.database.query(`SELECT * FROM operations WHERE state = 'queued' ${a} ORDER BY priority DESC, created_at ASC, id ASC LIMIT 1`).get(...l);if(!u)return;let p=G(u);if(f(this.database,`UPDATE operations SET state = 'running', attempt = attempt + 1, lease_owner = ?, lease_expires_at = ?,
|
|
1490
|
+
started_at = COALESCE(started_at, ?), updated_at = ?, version = version + 1 WHERE id = ? AND state = 'queued' AND version = ?`,[e,o,n,n,p.id,p.version]).changes!==1)return;return this.appendEvent({projectId:p.projectId,operationId:p.id,resourceId:p.resourceId,actorId:p.actorId,correlationId:p.correlationId,type:"operation.running",payload:{attempt:p.attempt+1,workerId:e}}),this.getOperation(p.id)})}claimOperation(e,t,r=60000){let n=this.now(),o=new Date(this.nowFn().getTime()+r).toISOString();return this.transaction(()=>{let a=this.getOperation(e);if(!a||a.state!=="queued")return;if(f(this.database,`UPDATE operations SET state = 'running', attempt = attempt + 1, lease_owner = ?, lease_expires_at = ?,
|
|
1491
|
+
started_at = COALESCE(started_at, ?), updated_at = ?, version = version + 1 WHERE id = ? AND state = 'queued' AND version = ?`,[t,o,n,n,a.id,a.version]).changes!==1)return;return this.appendEvent({projectId:a.projectId,operationId:a.id,resourceId:a.resourceId,actorId:a.actorId,correlationId:a.correlationId,type:"operation.running",payload:{attempt:a.attempt+1,workerId:t}}),this.getOperation(a.id)})}transitionOperation(e,t){return this.transaction(()=>{let r=this.getOperation(e);if(!r)throw Error(`Operation ${e} was not found`);let n=t.expectedVersion??r.version;if(r.version!==n)throw new at("Operation",e,n);if(!Br[r.state].includes(t.to))throw new wc(r.state,t.to);let o=this.now(),a=Hr.includes(t.to),l=t.to==="queued";if(f(this.database,`UPDATE operations SET state = ?, output = ?, error = ?, lease_owner = ?, lease_expires_at = ?,
|
|
1492
|
+
finished_at = ?, updated_at = ?, version = version + 1 WHERE id = ? AND version = ?`,[t.to,b(t.output??r.output),Ve(t.error)??null,l||a?null:t.leaseOwner??r.leaseOwner??null,l||a?null:t.leaseExpiresAt??r.leaseExpiresAt??null,a?o:null,o,e,n]).changes!==1)throw new at("Operation",e,n);return this.appendEvent({projectId:r.projectId,operationId:e,resourceId:r.resourceId,actorId:r.actorId,correlationId:r.correlationId,type:`operation.${t.to}`,level:t.to==="failed"?"error":"info",payload:{from:r.state,to:t.to,error:Ve(t.error)??null}}),this.getOperation(e)})}requestCancellation(e){let t=this.now();f(this.database,"UPDATE operations SET cancel_requested_at = ?, updated_at = ?, version = version + 1 WHERE id = ? AND state IN ('queued', 'running')",[t,t,e]);let r=this.getOperation(e);if(!r)throw Error(`Operation ${e} was not found`);return r}reconcileOrphanedOperations(e={}){let t=(e.now??this.nowFn()).toISOString(),r=e.policy??"fail",n=this.database.query("SELECT * FROM operations WHERE state = 'running' AND (lease_expires_at IS NULL OR lease_expires_at <= ?)").all(t).map(G),o=0,a=0;for(let l of n)if(r==="requeue")this.transitionOperation(l.id,{to:"queued",expectedVersion:l.version,error:"Worker lease expired; operation requeued after restart."}),o++;else this.transitionOperation(l.id,{to:"failed",expectedVersion:l.version,error:"Worker lease expired or dashboard restarted before completion."}),a++;return{requeued:o,failed:a}}appendEvent(e){let t=e.id??this.idFn(),r=e.correlationId??this.idFn(),n=e.organizationId??(e.projectId?S(this.database.query("SELECT organization_id FROM projects WHERE id = ?").get(e.projectId)?.organization_id):void 0);return f(this.database,`INSERT INTO events (id, organization_id, project_id, operation_id, resource_id, actor_id, correlation_id, type, level, payload, created_at)
|
|
1493
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[t,n??null,e.projectId??null,e.operationId??null,e.resourceId??null,e.actorId??null,r,e.type,e.level??"info",b(e.payload??{}),this.now()]),Ke(this.database.query("SELECT * FROM events WHERE id = ?").get(t))}listEvents(e={}){let t=[],r=[];if(e.organizationId)t.push("organization_id = ?"),r.push(e.organizationId);if(e.projectId)t.push("project_id = ?"),r.push(e.projectId);if(e.operationId)t.push("operation_id = ?"),r.push(e.operationId);if(e.resourceId)t.push("resource_id = ?"),r.push(e.resourceId);if(e.correlationId)t.push("correlation_id = ?"),r.push(e.correlationId);if(e.afterSequence!==void 0)t.push("sequence > ?"),r.push(e.afterSequence);let n=Math.min(1000,Math.max(1,e.limit??200));r.push(n);let o=t.length?`WHERE ${t.join(" AND ")}`:"";return this.database.query(`SELECT * FROM events ${o} ORDER BY sequence ASC LIMIT ?`).all(...r).map(Ke)}setSetting(e,t){f(this.database,`INSERT INTO settings (key, value, updated_at) VALUES (?, ?, ?)
|
|
1494
|
+
ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`,[e,b(t),this.now()])}getSetting(e){let t=this.database.query("SELECT value FROM settings WHERE key = ?").get(e);return t?z(t.value):void 0}upsertTag(e,t,r="#5a8be0"){let n=t.trim().toLowerCase().replace(/\s+/g,"-");if(!/^[a-z0-9][a-z0-9-]{0,31}$/.test(n))throw Error("Tag names must contain 1-32 letters, numbers, or dashes");if(!/^#[0-9a-f]{6}$/i.test(r))throw Error("Tag colors must be six-digit hex colors");let o=this.now(),a=this.database.query("SELECT * FROM tags WHERE project_id = ? AND normalized_name = ?").get(e,n);if(a)return f(this.database,"UPDATE tags SET name = ?, color = ?, updated_at = ? WHERE id = ?",[t.trim(),r.toLowerCase(),o,String(a.id)]),oe(this.database.query("SELECT * FROM tags WHERE id = ?").get(String(a.id)));let l=this.idFn();return f(this.database,"INSERT INTO tags (id, project_id, name, normalized_name, color, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[l,e,t.trim(),n,r.toLowerCase(),o,o]),oe(this.database.query("SELECT * FROM tags WHERE id = ?").get(l))}listTags(e){return this.database.query("SELECT * FROM tags WHERE project_id = ? ORDER BY normalized_name").all(e).map(oe)}assignTag(e,t){if(!this.database.query("SELECT tags.id FROM tags JOIN resources ON resources.project_id = tags.project_id WHERE tags.id = ? AND resources.id = ?").get(t,e))throw Error("The tag and resource must belong to the same project");f(this.database,"INSERT OR IGNORE INTO resource_tags (resource_id, tag_id, created_at) VALUES (?, ?, ?)",[e,t,this.now()])}removeTag(e,t){f(this.database,"DELETE FROM resource_tags WHERE resource_id = ? AND tag_id = ?",[e,t])}listResourceTags(e){return this.database.query(`SELECT resource_tags.resource_id, tags.* FROM resource_tags JOIN tags ON tags.id = resource_tags.tag_id
|
|
1495
|
+
WHERE tags.project_id = ? ORDER BY tags.normalized_name`).all(e).map((r)=>({resourceId:String(r.resource_id),tag:oe(r)}))}saveFilter(e,t,r,n){let o=t.trim();if(!o||o.length>64)throw Error("Saved filter names must contain 1-64 characters");if(!r||r.length>160||/^[a-z][a-z0-9+.-]*:|^\/\//i.test(r))throw Error("Saved filter routes must be local route IDs or paths");let a=b(n);if(a.length>8192)throw Error("Saved filter queries must be smaller than 8 KB");let l=this.database.query("SELECT * FROM saved_filters WHERE actor_key = ? AND name = ?").get(e,o),u=this.now();if(l)return f(this.database,"UPDATE saved_filters SET route_id = ?, query = ?, updated_at = ? WHERE id = ?",[r,a,u,String(l.id)]),Ie(this.database.query("SELECT * FROM saved_filters WHERE id = ?").get(String(l.id)));let p=this.idFn();return f(this.database,"INSERT INTO saved_filters (id, actor_key, name, route_id, query, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[p,e,o,r,a,u,u]),Ie(this.database.query("SELECT * FROM saved_filters WHERE id = ?").get(p))}listSavedFilters(e){return this.database.query("SELECT * FROM saved_filters WHERE actor_key = ? ORDER BY updated_at DESC, name").all(e).map(Ie)}deleteSavedFilter(e,t){return f(this.database,"DELETE FROM saved_filters WHERE actor_key = ? AND id = ?",[e,t]).changes===1}recordNavigation(e,t,r){let n=this.now();return f(this.database,`INSERT INTO navigation_items (actor_key, entity_type, entity_id, last_visited_at) VALUES (?, ?, ?, ?)
|
|
1496
|
+
ON CONFLICT(actor_key, entity_type, entity_id) DO UPDATE SET last_visited_at = excluded.last_visited_at, visit_count = visit_count + 1`,[e,t,r,n]),Se(this.database.query("SELECT * FROM navigation_items WHERE actor_key = ? AND entity_type = ? AND entity_id = ?").get(e,t,r))}setFavorite(e,t,r,n){let o=this.now();return f(this.database,`INSERT INTO navigation_items (actor_key, entity_type, entity_id, favorite, last_visited_at) VALUES (?, ?, ?, ?, ?)
|
|
1497
|
+
ON CONFLICT(actor_key, entity_type, entity_id) DO UPDATE SET favorite = excluded.favorite`,[e,t,r,n?1:0,o]),Se(this.database.query("SELECT * FROM navigation_items WHERE actor_key = ? AND entity_type = ? AND entity_id = ?").get(e,t,r))}listNavigation(e,t={}){let r=t.favoritesOnly?"AND favorite = 1":"",n=Math.min(100,Math.max(1,t.limit??20));return this.database.query(`SELECT * FROM navigation_items WHERE actor_key = ? ${r} ORDER BY favorite DESC, last_visited_at DESC LIMIT ?`).all(e,n).map(Se)}compact(e={}){let t=new Date(this.nowFn().getTime()-(e.eventRetentionDays??90)*86400000).toISOString(),r=new Date(this.nowFn().getTime()-(e.operationRetentionDays??365)*86400000).toISOString(),n=this.transaction(()=>{let o=f(this.database,"DELETE FROM events WHERE created_at < ?",[t]).changes,a=f(this.database,"DELETE FROM operations WHERE created_at < ? AND state IN ('succeeded', 'failed', 'cancelled', 'timed_out')",[r]).changes;return{events:o,operations:a}});if(e.vacuum!==!1)this.database.run("VACUUM");return{deletedEvents:n.events,deletedOperations:n.operations,vacuumed:e.vacuum!==!1}}createBackup(e="manual"){if(this.path===":memory:")throw Error("Cannot create a filesystem backup for an in-memory control plane");let t=`${this.path}.${Date.now()}.bak`;return this.backupTo(t),this.setSetting("storage.last_backup",{path:t,createdAt:this.now(),reason:e}),t}integrityCheck(){let e=this.database.query("PRAGMA integrity_check").all();return e.length===1&&Object.values(e[0])[0]==="ok"?"ok":"corrupt"}health(){let e=Object.fromEntries(["queued","running","succeeded","failed","cancelled","timed_out"].map((o)=>[o,0]));for(let o of this.database.query("SELECT state, COUNT(*) AS count FROM operations GROUP BY state").all())e[String(o.state)]=Number(o.count);let t=this.database.query("PRAGMA journal_mode").get(),r=this.getSetting("storage.last_backup"),n=r&&!Array.isArray(r)&&typeof r==="object"&&typeof r.createdAt==="string"?r.createdAt:void 0;return{path:this.path,schemaVersion:Number(this.database.query("PRAGMA user_version").get()?.user_version??0),supportedSchemaVersion:Fe,integrity:this.integrityCheck(),journalMode:String(t?.journal_mode??"unknown"),databaseBytes:this.path!==":memory:"&&bt(this.path)?zr(this.path).size:this.database.serialize().byteLength,lastBackupAt:n,operations:e,pendingRetryableOperations:e.queued+e.failed+e.timed_out}}exportSnapshot(){let e={};for(let t of this.database.query("SELECT key, value FROM settings ORDER BY key").all())e[String(t.key)]=z(t.value);return{format:"ts-cloud-control-plane",schemaVersion:Fe,exportedAt:this.now(),organizations:this.database.query("SELECT * FROM organizations ORDER BY id").all().map(be),memberships:this.database.query("SELECT * FROM organization_memberships ORDER BY id").all().map(Re),invitations:this.database.query("SELECT * FROM organization_invitations ORDER BY id").all().map((t)=>({...se(t,this.now()),tokenHash:String(t.token_hash)})),grants:this.database.query("SELECT * FROM authorization_grants ORDER BY id").all().map(Ce),projects:this.database.query("SELECT * FROM projects ORDER BY id").all().map(fe),environments:this.database.query("SELECT * FROM environments ORDER BY id").all().map(ye),resources:this.database.query("SELECT * FROM resources ORDER BY id").all().map(Le),actors:this.database.query("SELECT * FROM actors ORDER BY id").all().map(ve),operations:this.database.query("SELECT * FROM operations ORDER BY id").all().map(G),events:this.database.query("SELECT * FROM events ORDER BY sequence").all().map(Ke),settings:e,tags:this.database.query("SELECT * FROM tags ORDER BY id").all().map(oe),resourceTags:this.database.query("SELECT * FROM resource_tags ORDER BY resource_id, tag_id").all().map((t)=>({resourceId:String(t.resource_id),tagId:String(t.tag_id),createdAt:String(t.created_at)})),savedFilters:this.database.query("SELECT * FROM saved_filters ORDER BY id").all().map(Ie),navigationItems:this.database.query("SELECT * FROM navigation_items ORDER BY actor_key, entity_type, entity_id").all().map(Se)}}importSnapshot(e,t={}){if(e.format!=="ts-cloud-control-plane")throw Error("Unsupported control-plane snapshot format");if(e.schemaVersion>Fe)throw new Ds(e.schemaVersion,Fe);this.transaction(()=>{if((Number(this.database.query("SELECT COUNT(*) AS count FROM projects").get()?.count??0)>0||Number(this.database.query("SELECT COUNT(*) AS count FROM operations").get()?.count??0)>0)&&!t.replace)throw Error("Control plane is not empty; pass replace: true to import this snapshot");if(t.replace)this.database.run("DELETE FROM authorization_grants"),this.database.run("DELETE FROM organization_invitations"),this.database.run("DELETE FROM organization_memberships"),this.database.run("DELETE FROM resource_tags"),this.database.run("DELETE FROM tags"),this.database.run("DELETE FROM saved_filters"),this.database.run("DELETE FROM navigation_items"),this.database.run("DELETE FROM events"),this.database.run("DELETE FROM operations"),this.database.run("DELETE FROM resources"),this.database.run("DELETE FROM environments"),this.database.run("DELETE FROM projects"),this.database.run("DELETE FROM actors"),this.database.run("DELETE FROM organizations"),this.database.run("DELETE FROM settings");for(let n of e.organizations??[])f(this.database,"INSERT INTO organizations (id, slug, name, created_at, updated_at) VALUES (?, ?, ?, ?, ?)",[n.id,n.slug,n.name,n.createdAt,n.updatedAt]);for(let n of e.projects)f(this.database,`INSERT INTO projects (id, slug, name, description, organization_id, desired_config_hash, version, created_at, updated_at)
|
|
1498
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n.id,n.slug,n.name,n.description??null,n.organizationId??null,n.desiredConfigHash??null,n.version,n.createdAt,n.updatedAt]);for(let n of e.environments)f(this.database,`INSERT INTO environments (id, project_id, slug, name, kind, region, desired_state, discovered_state, version, created_at, updated_at)
|
|
1499
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n.id,n.projectId,n.slug,n.name,n.kind,n.region??null,b(n.desiredState),b(n.discoveredState),n.version,n.createdAt,n.updatedAt]);for(let n of e.resources)f(this.database,`INSERT INTO resources (id, project_id, environment_id, kind, slug, name, provider, provider_id, desired_state, discovered_state, metadata, version, created_at, updated_at)
|
|
1500
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n.id,n.projectId,n.environmentId??null,n.kind,n.slug,n.name,n.provider??null,n.providerId??null,b(n.desiredState),b(n.discoveredState),b(n.metadata),n.version,n.createdAt,n.updatedAt]);for(let n of e.actors)f(this.database,`INSERT INTO actors (id, kind, external_id, display_name, metadata, disabled_at, version, created_at, updated_at)
|
|
1501
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n.id,n.kind,n.externalId??null,n.displayName,b(n.metadata),n.disabledAt??null,n.version,n.createdAt,n.updatedAt]);for(let n of e.memberships??[])f(this.database,`INSERT INTO organization_memberships (id, organization_id, actor_id, role_template, scope_type, scope_id, status, session_version, last_active_at, source, created_at, updated_at)
|
|
1502
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n.id,n.organizationId,n.actorId,n.roleTemplate,n.scope.type,n.scope.id??null,n.status,n.sessionVersion,n.lastActiveAt??null,n.source??"manual",n.createdAt,n.updatedAt]);for(let n of e.invitations??[]){let o=n.tokenHash??Ne("sha256").update(`revoked:${n.id}:${this.idFn()}`).digest("hex");f(this.database,`INSERT INTO organization_invitations (id, organization_id, email, role_template, scope_type, scope_id, token_hash, invited_by_actor_id, accepted_by_actor_id, expires_at, accepted_at, revoked_at, created_at, updated_at)
|
|
1503
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n.id,n.organizationId,n.email,n.roleTemplate,n.scope.type,n.scope.id??null,o,n.invitedByActorId??null,n.acceptedByActorId??null,n.expiresAt,n.acceptedAt??null,n.tokenHash?n.revokedAt??null:n.revokedAt??this.now(),n.createdAt,n.updatedAt])}for(let n of e.grants??[])f(this.database,`INSERT INTO authorization_grants (id, organization_id, membership_id, effect, capability, scope_type, scope_id, source, created_at, updated_at)
|
|
1504
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n.id,n.organizationId,n.membershipId,n.effect,n.capability,n.scope.type,n.scope.id??null,n.source??"manual",n.createdAt,n.updatedAt]);for(let n of e.operations)f(this.database,`INSERT INTO operations (id, project_id, environment_id, resource_id, actor_id, kind, state, correlation_id, idempotency_key,
|
|
1505
1505
|
input, output, error, attempt, priority, lease_owner, lease_expires_at, cancel_requested_at, started_at, finished_at, version, created_at, updated_at)
|
|
1506
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n.id,n.projectId??null,n.environmentId??null,n.resourceId??null,n.actorId??null,n.kind,n.state,n.correlationId,n.idempotencyKey??null,
|
|
1507
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n.sequence,n.id,n.organizationId??null,n.projectId??null,n.operationId??null,n.resourceId??null,n.actorId??null,n.correlationId,n.type,n.level,C(n.payload),n.createdAt]);for(let[n,o]of Object.entries(e.settings))y(this.database,"INSERT INTO settings (key, value, updated_at) VALUES (?, ?, ?)",[n,C(o),this.now()]);for(let n of e.tags??[])y(this.database,"INSERT INTO tags (id, project_id, name, normalized_name, color, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[n.id,n.projectId,n.name,n.normalizedName,n.color,n.createdAt,n.updatedAt]);for(let n of e.resourceTags??[])y(this.database,"INSERT INTO resource_tags (resource_id, tag_id, created_at) VALUES (?, ?, ?)",[n.resourceId,n.tagId,n.createdAt]);for(let n of e.savedFilters??[])y(this.database,"INSERT INTO saved_filters (id, actor_key, name, route_id, query, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[n.id,n.actorKey,n.name,n.routeId,C(n.query),n.createdAt,n.updatedAt]);for(let n of e.navigationItems??[])y(this.database,"INSERT INTO navigation_items (actor_key, entity_type, entity_id, favorite, last_visited_at, visit_count) VALUES (?, ?, ?, ?, ?, ?)",[n.actorKey,n.entityType,n.entityId,n.favorite?1:0,n.lastVisitedAt,n.visitCount])})}}var $r=new Set(["domain","domains","hostname","hostnames","url","repository","repo","image","label","labels"]),Qr=new Set(["sha","commit","commitsha","release","releaseid"]);function At(e,t){if(!e||typeof e!=="object"||Array.isArray(e))return[];let r=[];for(let[n,o]of Object.entries(e)){if(!t.has(n.toLowerCase()))continue;if(typeof o==="string")r.push(o);else if(Array.isArray(o))r.push(...o.filter((a)=>typeof a==="string"))}return r}function Ge(e){return e.toLowerCase().trim().replace(/[^a-z0-9._:/@-]+/g," ")}function We(e,t,r){let n=Ge(e),o=Ge(t),a=Ge(r);if(!n)return 0;if(o===n)return 1000;if(o.startsWith(n))return 800-Math.min(100,o.length-n.length);if(o.includes(n))return 650-Math.min(100,o.indexOf(n));let l=n.split(/\s+/).filter(Boolean);if(l.every((p)=>a.includes(p)))return 400+l.length*10;let u=0;for(let p of n){if(u=a.indexOf(p,u),u<0)return 0;u++}return Math.max(1,180-Math.floor(a.length/20))}function Yr(e,t){let r=e.kind.toLowerCase();if(r==="server"||r==="compute")return{type:"server",href:`/server/metrics?env=${encodeURIComponent(t)}`};if(r.includes("database")||["mysql","postgres","postgresql","sqlite","redis"].includes(r))return{type:"database",href:`/server/database?env=${encodeURIComponent(t)}&database=${encodeURIComponent(e.slug)}`};return{type:"service",href:`/server/sites?env=${encodeURIComponent(t)}&service=${encodeURIComponent(e.slug)}`}}function Rs(e,t){let r=e.getProject(t.projectId);if(!r)return[];let n=e.listEnvironments(r.id),o=new Map(n.map((m)=>[m.id,m])),a=e.listResourceTags(r.id),l=new Map;for(let m of a){let T=l.get(m.resourceId)??[];T.push({id:m.tag.id,name:m.tag.name,color:m.tag.color}),l.set(m.resourceId,T)}let u=[],p=t.allowedResourceSlugs!==void 0;if(!p){u.push({type:"project",id:r.id,title:r.name,subtitle:r.slug,href:`/?project=${encodeURIComponent(r.slug)}`,tags:[],score:0});for(let m of n)u.push({type:"environment",id:m.id,title:m.name,subtitle:`${r.name} · ${m.kind}`,href:`/?env=${encodeURIComponent(m.slug)}`,environment:m.slug,tags:[],score:0})}let E=e.listResources(r.id).filter((m)=>!t.allowedResourceSlugs||t.allowedResourceSlugs.has(m.slug));for(let m of E){let T=m.environmentId?o.get(m.environmentId):void 0,N=l.get(m.id)??[],h=At(m.desiredState,$r),f=[m.name,m.slug,m.kind,m.provider,m.providerId,T?.slug,...h,...N.map((v)=>v.name)].filter(Boolean).join(" "),L=Yr(m,T?.slug??n[0]?.slug??"");u.push({type:L.type,id:m.id,title:m.name,subtitle:[m.kind,...h.slice(0,2)].join(" · "),href:L.href,environment:T?.slug,provider:m.provider,tags:N,score:We(t.query,m.name,f)})}if(!p)for(let m of e.listOperations({projectId:r.id,limit:500})){let T=m.environmentId?o.get(m.environmentId):void 0,N=At(m.input,Qr),h=m.kind.includes("deploy"),f=N[0]??m.kind,L=[m.kind,m.id,m.correlationId,m.state,...N].join(" ");u.push({type:h?"deployment":"operation",id:m.id,title:f,subtitle:`${m.kind} · ${m.state}`,href:`/server/activity?env=${encodeURIComponent(T?.slug??n[0]?.slug??"")}&operation=${encodeURIComponent(m.id)}`,environment:T?.slug,status:m.state,tags:[],score:We(t.query,f,L)})}for(let m of u)if(m.score===0)m.score=We(t.query,m.title,`${m.title} ${m.subtitle} ${m.environment??""} ${m.provider??""}`);let g={service:0,server:1,database:2,deployment:3,environment:4,project:5,operation:6};return u.filter((m)=>m.score>0).sort((m,T)=>T.score-m.score||g[m.type]-g[T.type]||m.title.localeCompare(T.title)||m.id.localeCompare(T.id)).slice(0,Math.min(50,Math.max(1,t.limit??20)))}var ce=(e)=>{if(typeof e!=="string")return{};try{return JSON.parse(e)}catch{return{}}},B=(e)=>typeof e==="string"&&e!==""?e:void 0,Ae=(e)=>Number(e)===1,Ut=(e)=>e==null?void 0:Number(e);function Dt(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:B(e.project_id),environmentId:B(e.environment_id),name:String(e.name),period:String(e.period),timezone:String(e.timezone),currency:String(e.currency),softLimitCents:Ut(e.soft_limit_cents),hardLimitCents:Ut(e.hard_limit_cents),thresholds:ce(e.thresholds),meters:ce(e.meters),graceSeconds:Number(e.grace_seconds),hysteresisPercent:Number(e.hysteresis_percent),dryRun:Ae(e.dry_run),enabled:Ae(e.enabled),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Je(e){return{id:String(e.id),budgetId:String(e.budget_id),organizationId:String(e.organization_id),projectId:B(e.project_id),environmentId:B(e.environment_id),action:String(e.action),state:String(e.state),reason:String(e.reason),restore:ce(e.restore),triggeredAtPercent:Number(e.triggered_at_percent),simulated:Ae(e.simulated),appliedAt:B(e.applied_at),releasedAt:B(e.released_at),error:B(e.error),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function wt(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:B(e.project_id),environmentId:B(e.environment_id),signal:String(e.signal),direction:String(e.direction),observed:Number(e.observed),expected:Number(e.expected),score:Number(e.score),deltaPercent:Number(e.delta_percent),severity:String(e.severity),bucketStart:String(e.bucket_start),evidence:ce(e.evidence),acknowledgedAt:B(e.acknowledged_at),createdAt:String(e.created_at)}}function Wr(e){return{organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:String(e.environment_id),resourceId:String(e.resource_id),provider:String(e.provider),region:String(e.region),meter:String(e.meter),bucketStart:String(e.bucket_start),quantity:Number(e.quantity),costCents:Number(e.cost_cents),sampleCount:Number(e.sample_count),updatedAt:String(e.updated_at)}}function dt(e,t,r){return[e,t??"",r??""].join("/")}var gp=[{atPercent:50,actions:["notify"]},{atPercent:80,actions:["notify"]},{atPercent:100,actions:["notify"],onProjection:!0},{atPercent:100,actions:["notify","block_builds","block_deployments"]},{atPercent:115,actions:["notify","block_builds","block_deployments","throttle_requests"]}];class si{controlPlane;options;constructor(e,t={}){this.controlPlane=e;this.options=t}now(){return(this.options.now?.()??new Date).toISOString()}get priceBook(){return this.options.priceBook??Oc}query(e,t=[]){return this.controlPlane.database.query(e).all(...t)}createBudget(e){let t=e.name.trim();if(!t)throw Error("Budgets require a name.");if(e.softLimitCents==null&&e.hardLimitCents==null)throw Error("A budget needs a soft limit, a hard limit, or both.");if(e.softLimitCents!=null&&e.hardLimitCents!=null&&e.softLimitCents>e.hardLimitCents)throw Error("The soft limit must not exceed the hard limit.");let r=e.timezone??"UTC";if(!ii(r))throw Error(`Unknown timezone: ${r}`);let n=(e.thresholds??[...gp]).filter((l)=>Number.isFinite(l.atPercent)&&l.atPercent>=0);if(e.environmentId&&!e.projectId)throw Error("An environment-scoped budget must also name its project.");let o=crypto.randomUUID(),a=this.now();return this.controlPlane.database.run("INSERT INTO spend_budgets (id,organization_id,project_id,environment_id,name,period,timezone,currency,soft_limit_cents,hard_limit_cents,thresholds,meters,grace_seconds,hysteresis_percent,dry_run,enabled,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,1,?,?)",[o,e.organizationId,e.projectId??null,e.environmentId??null,t,e.period,r,e.currency??"USD",e.softLimitCents??null,e.hardLimitCents??null,JSON.stringify(n),JSON.stringify(e.meters??[]),Math.max(0,Math.floor(e.graceSeconds??0)),Math.max(0,e.hysteresisPercent??5),e.dryRun?1:0,e.enabled===!1?0:1,a,a]),this.getBudget(o)}getBudget(e){let t=this.query("SELECT * FROM spend_budgets WHERE id = ?",[e])[0];return t?Dt(t):void 0}listBudgets(e){let t=["organization_id = ?"],r=[e.organizationId];if(e.projectId)t.push("(project_id IS NULL OR project_id = ?)"),r.push(e.projectId);if(e.enabledOnly)t.push("enabled = 1");return this.query(`SELECT * FROM spend_budgets WHERE ${t.join(" AND ")} ORDER BY created_at`,r).map(Dt)}budgetsForScope(e,t,r){return this.listBudgets({organizationId:e,enabledOnly:!0}).filter((n)=>{if(n.projectId&&n.projectId!==t)return!1;if(n.environmentId&&n.environmentId!==r)return!1;return!0}).sort((n,o)=>Number(!!n.projectId)-Number(!!o.projectId)||Number(!!n.environmentId)-Number(!!o.environmentId))}updateBudget(e,t,r){let n=this.getBudget(e);if(!n)throw Error("Budget was not found.");if(r!=null&&r!==n.version)throw Error(`Budget was modified concurrently (expected version ${r}, found ${n.version}).`);let o={...n,...t};if(o.softLimitCents==null&&o.hardLimitCents==null)throw Error("A budget needs a soft limit, a hard limit, or both.");if(o.softLimitCents!=null&&o.hardLimitCents!=null&&o.softLimitCents>o.hardLimitCents)throw Error("The soft limit must not exceed the hard limit.");if(t.timezone&&!ii(t.timezone))throw Error(`Unknown timezone: ${t.timezone}`);return this.controlPlane.database.run("UPDATE spend_budgets SET name=?,period=?,timezone=?,currency=?,soft_limit_cents=?,hard_limit_cents=?,thresholds=?,meters=?,grace_seconds=?,hysteresis_percent=?,dry_run=?,enabled=?,version=version+1,updated_at=? WHERE id=?",[o.name,o.period,o.timezone,o.currency??"USD",o.softLimitCents??null,o.hardLimitCents??null,JSON.stringify(o.thresholds??[]),JSON.stringify(o.meters??[]),Math.max(0,Math.floor(o.graceSeconds??0)),Math.max(0,o.hysteresisPercent??5),o.dryRun?1:0,o.enabled===!1?0:1,this.now(),e]),this.getBudget(e)}deleteBudget(e){return this.controlPlane.database.run("DELETE FROM spend_budgets WHERE id = ?",[e]).changes>0}ingestUsage(e){let t={applied:0,duplicates:0,costCents:0,unpricedMeters:[]},r=new Set,n=this.now();return this.controlPlane.database.transaction((a)=>{for(let l of a){if(!(l.quantity>0)||!Number.isFinite(l.quantity))continue;let u=l.key??this.deltaFallbackKey(l);if(this.controlPlane.database.run("INSERT OR IGNORE INTO spend_usage_receipts (key,organization_id,bucket_start,created_at) VALUES (?,?,?,?)",[u,l.organizationId,wr(l.timestamp),n]).changes===0){t.duplicates++;continue}let E={projectId:l.projectId??"",environmentId:l.environmentId??"",resourceId:l.resourceId??"",provider:l.provider??"",region:l.region??""},g=this.periodQuantity(l),m=Os(this.priceBook,{meter:l.meter,quantity:l.quantity,provider:l.provider,region:l.region},g);if(m.unpriced)r.add(String(l.meter));this.controlPlane.database.run(`INSERT INTO spend_usage (organization_id,project_id,environment_id,resource_id,provider,region,meter,bucket_start,quantity,cost_cents,sample_count,updated_at)
|
|
1506
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n.id,n.projectId??null,n.environmentId??null,n.resourceId??null,n.actorId??null,n.kind,n.state,n.correlationId,n.idempotencyKey??null,b(n.input),b(n.output),Ve(n.error)??null,n.attempt,n.priority,n.leaseOwner??null,n.leaseExpiresAt??null,n.cancelRequestedAt??null,n.startedAt??null,n.finishedAt??null,n.version,n.createdAt,n.updatedAt]);for(let n of e.events)f(this.database,`INSERT INTO events (sequence, id, organization_id, project_id, operation_id, resource_id, actor_id, correlation_id, type, level, payload, created_at)
|
|
1507
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n.sequence,n.id,n.organizationId??null,n.projectId??null,n.operationId??null,n.resourceId??null,n.actorId??null,n.correlationId,n.type,n.level,b(n.payload),n.createdAt]);for(let[n,o]of Object.entries(e.settings))f(this.database,"INSERT INTO settings (key, value, updated_at) VALUES (?, ?, ?)",[n,b(o),this.now()]);for(let n of e.tags??[])f(this.database,"INSERT INTO tags (id, project_id, name, normalized_name, color, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[n.id,n.projectId,n.name,n.normalizedName,n.color,n.createdAt,n.updatedAt]);for(let n of e.resourceTags??[])f(this.database,"INSERT INTO resource_tags (resource_id, tag_id, created_at) VALUES (?, ?, ?)",[n.resourceId,n.tagId,n.createdAt]);for(let n of e.savedFilters??[])f(this.database,"INSERT INTO saved_filters (id, actor_key, name, route_id, query, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[n.id,n.actorKey,n.name,n.routeId,b(n.query),n.createdAt,n.updatedAt]);for(let n of e.navigationItems??[])f(this.database,"INSERT INTO navigation_items (actor_key, entity_type, entity_id, favorite, last_visited_at, visit_count) VALUES (?, ?, ?, ?, ?, ?)",[n.actorKey,n.entityType,n.entityId,n.favorite?1:0,n.lastVisitedAt,n.visitCount])})}}var $r=new Set(["domain","domains","hostname","hostnames","url","repository","repo","image","label","labels"]),Qr=new Set(["sha","commit","commitsha","release","releaseid"]);function At(e,t){if(!e||typeof e!=="object"||Array.isArray(e))return[];let r=[];for(let[n,o]of Object.entries(e)){if(!t.has(n.toLowerCase()))continue;if(typeof o==="string")r.push(o);else if(Array.isArray(o))r.push(...o.filter((a)=>typeof a==="string"))}return r}function Ge(e){return e.toLowerCase().trim().replace(/[^a-z0-9._:/@-]+/g," ")}function We(e,t,r){let n=Ge(e),o=Ge(t),a=Ge(r);if(!n)return 0;if(o===n)return 1000;if(o.startsWith(n))return 800-Math.min(100,o.length-n.length);if(o.includes(n))return 650-Math.min(100,o.indexOf(n));let l=n.split(/\s+/).filter(Boolean);if(l.every((p)=>a.includes(p)))return 400+l.length*10;let u=0;for(let p of n){if(u=a.indexOf(p,u),u<0)return 0;u++}return Math.max(1,180-Math.floor(a.length/20))}function Yr(e,t){let r=e.kind.toLowerCase();if(r==="server"||r==="compute")return{type:"server",href:`/server/metrics?env=${encodeURIComponent(t)}`};if(r.includes("database")||["mysql","postgres","postgresql","sqlite","redis"].includes(r))return{type:"database",href:`/server/database?env=${encodeURIComponent(t)}&database=${encodeURIComponent(e.slug)}`};return{type:"service",href:`/server/sites?env=${encodeURIComponent(t)}&service=${encodeURIComponent(e.slug)}`}}function Ps(e,t){let r=e.getProject(t.projectId);if(!r)return[];let n=e.listEnvironments(r.id),o=new Map(n.map((m)=>[m.id,m])),a=e.listResourceTags(r.id),l=new Map;for(let m of a){let T=l.get(m.resourceId)??[];T.push({id:m.tag.id,name:m.tag.name,color:m.tag.color}),l.set(m.resourceId,T)}let u=[],p=t.allowedResourceSlugs!==void 0;if(!p){u.push({type:"project",id:r.id,title:r.name,subtitle:r.slug,href:`/?project=${encodeURIComponent(r.slug)}`,tags:[],score:0});for(let m of n)u.push({type:"environment",id:m.id,title:m.name,subtitle:`${r.name} · ${m.kind}`,href:`/?env=${encodeURIComponent(m.slug)}`,environment:m.slug,tags:[],score:0})}let E=e.listResources(r.id).filter((m)=>!t.allowedResourceSlugs||t.allowedResourceSlugs.has(m.slug));for(let m of E){let T=m.environmentId?o.get(m.environmentId):void 0,h=l.get(m.id)??[],_=At(m.desiredState,$r),N=[m.name,m.slug,m.kind,m.provider,m.providerId,T?.slug,..._,...h.map((L)=>L.name)].filter(Boolean).join(" "),y=Yr(m,T?.slug??n[0]?.slug??"");u.push({type:y.type,id:m.id,title:m.name,subtitle:[m.kind,..._.slice(0,2)].join(" · "),href:y.href,environment:T?.slug,provider:m.provider,tags:h,score:We(t.query,m.name,N)})}if(!p)for(let m of e.listOperations({projectId:r.id,limit:500})){let T=m.environmentId?o.get(m.environmentId):void 0,h=At(m.input,Qr),_=m.kind.includes("deploy"),N=h[0]??m.kind,y=[m.kind,m.id,m.correlationId,m.state,...h].join(" ");u.push({type:_?"deployment":"operation",id:m.id,title:N,subtitle:`${m.kind} · ${m.state}`,href:`/server/activity?env=${encodeURIComponent(T?.slug??n[0]?.slug??"")}&operation=${encodeURIComponent(m.id)}`,environment:T?.slug,status:m.state,tags:[],score:We(t.query,N,y)})}for(let m of u)if(m.score===0)m.score=We(t.query,m.title,`${m.title} ${m.subtitle} ${m.environment??""} ${m.provider??""}`);let g={service:0,server:1,database:2,deployment:3,environment:4,project:5,operation:6};return u.filter((m)=>m.score>0).sort((m,T)=>T.score-m.score||g[m.type]-g[T.type]||m.title.localeCompare(T.title)||m.id.localeCompare(T.id)).slice(0,Math.min(50,Math.max(1,t.limit??20)))}var ce=(e)=>{if(typeof e!=="string")return{};try{return JSON.parse(e)}catch{return{}}},B=(e)=>typeof e==="string"&&e!==""?e:void 0,Ae=(e)=>Number(e)===1,Ut=(e)=>e==null?void 0:Number(e);function Dt(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:B(e.project_id),environmentId:B(e.environment_id),name:String(e.name),period:String(e.period),timezone:String(e.timezone),currency:String(e.currency),softLimitCents:Ut(e.soft_limit_cents),hardLimitCents:Ut(e.hard_limit_cents),thresholds:ce(e.thresholds),meters:ce(e.meters),graceSeconds:Number(e.grace_seconds),hysteresisPercent:Number(e.hysteresis_percent),dryRun:Ae(e.dry_run),enabled:Ae(e.enabled),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Je(e){return{id:String(e.id),budgetId:String(e.budget_id),organizationId:String(e.organization_id),projectId:B(e.project_id),environmentId:B(e.environment_id),action:String(e.action),state:String(e.state),reason:String(e.reason),restore:ce(e.restore),triggeredAtPercent:Number(e.triggered_at_percent),simulated:Ae(e.simulated),appliedAt:B(e.applied_at),releasedAt:B(e.released_at),error:B(e.error),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function wt(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:B(e.project_id),environmentId:B(e.environment_id),signal:String(e.signal),direction:String(e.direction),observed:Number(e.observed),expected:Number(e.expected),score:Number(e.score),deltaPercent:Number(e.delta_percent),severity:String(e.severity),bucketStart:String(e.bucket_start),evidence:ce(e.evidence),acknowledgedAt:B(e.acknowledged_at),createdAt:String(e.created_at)}}function Wr(e){return{organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:String(e.environment_id),resourceId:String(e.resource_id),provider:String(e.provider),region:String(e.region),meter:String(e.meter),bucketStart:String(e.bucket_start),quantity:Number(e.quantity),costCents:Number(e.cost_cents),sampleCount:Number(e.sample_count),updatedAt:String(e.updated_at)}}function dt(e,t,r){return[e,t??"",r??""].join("/")}var Sp=[{atPercent:50,actions:["notify"]},{atPercent:80,actions:["notify"]},{atPercent:100,actions:["notify"],onProjection:!0},{atPercent:100,actions:["notify","block_builds","block_deployments"]},{atPercent:115,actions:["notify","block_builds","block_deployments","throttle_requests"]}];class oi{controlPlane;options;constructor(e,t={}){this.controlPlane=e;this.options=t}now(){return(this.options.now?.()??new Date).toISOString()}get priceBook(){return this.options.priceBook??$c}query(e,t=[]){return this.controlPlane.database.query(e).all(...t)}createBudget(e){let t=e.name.trim();if(!t)throw Error("Budgets require a name.");if(e.softLimitCents==null&&e.hardLimitCents==null)throw Error("A budget needs a soft limit, a hard limit, or both.");if(e.softLimitCents!=null&&e.hardLimitCents!=null&&e.softLimitCents>e.hardLimitCents)throw Error("The soft limit must not exceed the hard limit.");let r=e.timezone??"UTC";if(!si(r))throw Error(`Unknown timezone: ${r}`);let n=(e.thresholds??[...Sp]).filter((l)=>Number.isFinite(l.atPercent)&&l.atPercent>=0);if(e.environmentId&&!e.projectId)throw Error("An environment-scoped budget must also name its project.");let o=crypto.randomUUID(),a=this.now();return this.controlPlane.database.run("INSERT INTO spend_budgets (id,organization_id,project_id,environment_id,name,period,timezone,currency,soft_limit_cents,hard_limit_cents,thresholds,meters,grace_seconds,hysteresis_percent,dry_run,enabled,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,1,?,?)",[o,e.organizationId,e.projectId??null,e.environmentId??null,t,e.period,r,e.currency??"USD",e.softLimitCents??null,e.hardLimitCents??null,JSON.stringify(n),JSON.stringify(e.meters??[]),Math.max(0,Math.floor(e.graceSeconds??0)),Math.max(0,e.hysteresisPercent??5),e.dryRun?1:0,e.enabled===!1?0:1,a,a]),this.getBudget(o)}getBudget(e){let t=this.query("SELECT * FROM spend_budgets WHERE id = ?",[e])[0];return t?Dt(t):void 0}listBudgets(e){let t=["organization_id = ?"],r=[e.organizationId];if(e.projectId)t.push("(project_id IS NULL OR project_id = ?)"),r.push(e.projectId);if(e.enabledOnly)t.push("enabled = 1");return this.query(`SELECT * FROM spend_budgets WHERE ${t.join(" AND ")} ORDER BY created_at`,r).map(Dt)}budgetsForScope(e,t,r){return this.listBudgets({organizationId:e,enabledOnly:!0}).filter((n)=>{if(n.projectId&&n.projectId!==t)return!1;if(n.environmentId&&n.environmentId!==r)return!1;return!0}).sort((n,o)=>Number(!!n.projectId)-Number(!!o.projectId)||Number(!!n.environmentId)-Number(!!o.environmentId))}updateBudget(e,t,r){let n=this.getBudget(e);if(!n)throw Error("Budget was not found.");if(r!=null&&r!==n.version)throw Error(`Budget was modified concurrently (expected version ${r}, found ${n.version}).`);let o={...n,...t};if(o.softLimitCents==null&&o.hardLimitCents==null)throw Error("A budget needs a soft limit, a hard limit, or both.");if(o.softLimitCents!=null&&o.hardLimitCents!=null&&o.softLimitCents>o.hardLimitCents)throw Error("The soft limit must not exceed the hard limit.");if(t.timezone&&!si(t.timezone))throw Error(`Unknown timezone: ${t.timezone}`);return this.controlPlane.database.run("UPDATE spend_budgets SET name=?,period=?,timezone=?,currency=?,soft_limit_cents=?,hard_limit_cents=?,thresholds=?,meters=?,grace_seconds=?,hysteresis_percent=?,dry_run=?,enabled=?,version=version+1,updated_at=? WHERE id=?",[o.name,o.period,o.timezone,o.currency??"USD",o.softLimitCents??null,o.hardLimitCents??null,JSON.stringify(o.thresholds??[]),JSON.stringify(o.meters??[]),Math.max(0,Math.floor(o.graceSeconds??0)),Math.max(0,o.hysteresisPercent??5),o.dryRun?1:0,o.enabled===!1?0:1,this.now(),e]),this.getBudget(e)}deleteBudget(e){return this.controlPlane.database.run("DELETE FROM spend_budgets WHERE id = ?",[e]).changes>0}ingestUsage(e){let t={applied:0,duplicates:0,costCents:0,unpricedMeters:[]},r=new Set,n=this.now();return this.controlPlane.database.transaction((a)=>{for(let l of a){if(!(l.quantity>0)||!Number.isFinite(l.quantity))continue;let u=l.key??this.deltaFallbackKey(l);if(this.controlPlane.database.run("INSERT OR IGNORE INTO spend_usage_receipts (key,organization_id,bucket_start,created_at) VALUES (?,?,?,?)",[u,l.organizationId,wr(l.timestamp),n]).changes===0){t.duplicates++;continue}let E={projectId:l.projectId??"",environmentId:l.environmentId??"",resourceId:l.resourceId??"",provider:l.provider??"",region:l.region??""},g=this.periodQuantity(l),m=$s(this.priceBook,{meter:l.meter,quantity:l.quantity,provider:l.provider,region:l.region},g);if(m.unpriced)r.add(String(l.meter));this.controlPlane.database.run(`INSERT INTO spend_usage (organization_id,project_id,environment_id,resource_id,provider,region,meter,bucket_start,quantity,cost_cents,sample_count,updated_at)
|
|
1508
1508
|
VALUES (?,?,?,?,?,?,?,?,?,?,1,?)
|
|
1509
1509
|
ON CONFLICT(organization_id,project_id,environment_id,resource_id,provider,region,meter,bucket_start) DO UPDATE SET
|
|
1510
1510
|
quantity = quantity + excluded.quantity,
|
|
@@ -1512,7 +1512,7 @@ import{_,d}from"./chunk-d72ddm5x.js";import{xr}from"./chunk-4yb7hf91.js";var Kh=
|
|
|
1512
1512
|
sample_count = sample_count + 1,
|
|
1513
1513
|
updated_at = excluded.updated_at`,[l.organizationId,E.projectId,E.environmentId,E.resourceId,E.provider,E.region,l.meter,wr(l.timestamp),l.quantity,m.costCents,n]),t.applied++,t.costCents+=m.costCents}})(e),t.unpricedMeters=[...r],t}deltaFallbackKey(e){return Gr("sha256").update([e.organizationId,e.projectId??"",e.environmentId??"",e.resourceId??"",e.provider??"",e.region??"",e.meter,e.timestamp,String(e.quantity)].join("\x00")).digest("hex").slice(0,32)}periodQuantity(e){let t=ct("monthly","UTC",new Date(e.timestamp)),r=this.query("SELECT COALESCE(SUM(quantity), 0) AS total FROM spend_usage WHERE organization_id = ? AND meter = ? AND provider = ? AND region = ? AND bucket_start >= ? AND bucket_start < ?",[e.organizationId,e.meter,e.provider??"",e.region??"",t.start,t.end])[0];return Number(r?.total??0)}usageClauses(e){let t=["organization_id = ?","bucket_start >= ?","bucket_start < ?"],r=[e.organizationId,e.from,e.to];if(e.projectId)t.push("project_id = ?"),r.push(e.projectId);if(e.environmentId)t.push("environment_id = ?"),r.push(e.environmentId);if(e.resourceId)t.push("resource_id = ?"),r.push(e.resourceId);if(e.meters?.length)t.push(`meter IN (${e.meters.map(()=>"?").join(",")})`),r.push(...e.meters.map(String));if(e.providers?.length)t.push(`provider IN (${e.providers.map(()=>"?").join(",")})`),r.push(...e.providers);return{where:t.join(" AND "),bindings:r}}summarizeUsage(e){let{where:t,bindings:r}=this.usageClauses(e),n=this.query(`SELECT meter, provider, SUM(quantity) AS quantity, SUM(cost_cents) AS cost_cents, SUM(sample_count) AS sample_count
|
|
1514
1514
|
FROM spend_usage WHERE ${t} GROUP BY meter, provider ORDER BY SUM(cost_cents) DESC, meter`,r).map((a)=>({meter:String(a.meter),provider:String(a.provider),quantity:Number(a.quantity),costCents:Number(a.cost_cents),sampleCount:Number(a.sample_count)})),o=this.query(`SELECT bucket_start, SUM(cost_cents) AS cost_cents, SUM(quantity) AS quantity
|
|
1515
|
-
FROM spend_usage WHERE ${t} GROUP BY bucket_start ORDER BY bucket_start`,r).map((a)=>({bucketStart:String(a.bucket_start),costCents:Number(a.cost_cents),quantity:Number(a.quantity)}));return{from:e.from,to:e.to,totalCents:n.reduce((a,l)=>a+l.costCents,0),byMeter:n,series:o}}listRollups(e,t=1000){let{where:r,bindings:n}=this.usageClauses(e);return this.query(`SELECT * FROM spend_usage WHERE ${r} ORDER BY bucket_start DESC LIMIT ?`,[...n,Math.max(1,Math.min(1e4,t))]).map(Wr)}budgetSpendCents(e,t=new Date){let r=ct(e.period,e.timezone,t),n=this.summarizeUsage({organizationId:e.organizationId,projectId:e.projectId,environmentId:e.environmentId,meters:e.meters.length>0?e.meters:void 0,from:r.start,to:r.end});return{window:r,summary:n}}pruneUsage(e,t=new Date){let r=new Date(t.getTime()-Math.max(1,e)*86400000).toISOString(),n=this.controlPlane.database.run("DELETE FROM spend_usage WHERE bucket_start < ?",[r]).changes,o=new Date(t.getTime()-604800000).toISOString(),a=this.controlPlane.database.run("DELETE FROM spend_usage_receipts WHERE created_at < ?",[o]).changes;return{rollups:n,receipts:a}}recordDecision(e){this.controlPlane.database.run("INSERT INTO spend_decisions (id,budget_id,level,window_start,window_end,used_percent,projected_percent,actual_cents,projected_cents,actions,simulated,reason,evaluated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",[crypto.randomUUID(),e.budgetId,e.level,e.window.start,e.window.end,e.usedPercent,e.projectedPercent,e.projection.actualCents,e.projection.projectedCents,JSON.stringify(e.actions),e.simulated?1:0,e.reason,e.evaluatedAt])}listDecisions(e,t=50){return this.query("SELECT * FROM spend_decisions WHERE budget_id = ? ORDER BY evaluated_at DESC LIMIT ?",[e,Math.max(1,Math.min(500,t))]).map((r)=>({id:r.id,budgetId:r.budget_id,level:r.level,window:{start:r.window_start,end:r.window_end},usedPercent:Number(r.used_percent),projectedPercent:Number(r.projected_percent),actualCents:Number(r.actual_cents),projectedCents:Number(r.projected_cents),actions:ce(r.actions),simulated:Ae(r.simulated),reason:r.reason,evaluatedAt:r.evaluated_at}))}openEnforcement(e){let t=this.activeEnforcement(e.budget.id,e.action);if(t)return t;let r=crypto.randomUUID(),n=this.now();return this.controlPlane.database.run("INSERT INTO spend_enforcements (id,budget_id,organization_id,project_id,environment_id,action,state,reason,restore,triggered_at_percent,simulated,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",[r,e.budget.id,e.budget.organizationId,e.budget.projectId??null,e.budget.environmentId??null,e.action,"pending",e.reason,JSON.stringify(s(e.restore??{})),e.triggeredAtPercent,e.simulated?1:0,n,n]),this.getEnforcement(r)}getEnforcement(e){let t=this.query("SELECT * FROM spend_enforcements WHERE id = ?",[e])[0];return t?Je(t):void 0}activeEnforcement(e,t){let r=this.query("SELECT * FROM spend_enforcements WHERE budget_id = ? AND action = ? AND state IN ('pending','active','releasing')",[e,t])[0];return r?Je(r):void 0}listEnforcements(e){let t=["organization_id = ?"],r=[e.organizationId];if(e.budgetId)t.push("budget_id = ?"),r.push(e.budgetId);if(e.activeOnly)t.push("state IN ('pending','active','releasing')");return this.query(`SELECT * FROM spend_enforcements WHERE ${t.join(" AND ")} ORDER BY created_at DESC`,r).map(Je)}transitionEnforcement(e,t,r={}){let n=this.getEnforcement(e);if(!n)throw Error("Enforcement was not found.");let o=this.now();return this.controlPlane.database.run("UPDATE spend_enforcements SET state=?, error=?, restore=?, applied_at=?, released_at=?, updated_at=? WHERE id=?",[t,r.error??null,JSON.stringify(s(r.restore??n.restore)),t==="active"?n.appliedAt??o:n.appliedAt??null,t==="released"?o:n.releasedAt??null,o,e]),this.getEnforcement(e)}recordAnomaly(e){let t=crypto.randomUUID();return this.controlPlane.database.run("INSERT OR IGNORE INTO spend_anomalies (id,organization_id,project_id,environment_id,scope_key,signal,direction,observed,expected,score,delta_percent,severity,bucket_start,evidence,created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.organizationId,e.projectId??null,e.environmentId??null,dt(e.organizationId,e.projectId,e.environmentId),e.signal,e.direction,e.observed,e.expected,e.score,e.deltaPercent,e.severity,e.bucketStart,JSON.stringify(s(e.evidence??{})),this.now()]).changes>0?this.getAnomaly(t):void 0}getAnomaly(e){let t=this.query("SELECT * FROM spend_anomalies WHERE id = ?",[e])[0];return t?wt(t):void 0}listAnomalies(e){let t=["organization_id = ?"],r=[e.organizationId];if(e.projectId)t.push("project_id = ?"),r.push(e.projectId);if(e.since)t.push("bucket_start >= ?"),r.push(e.since);if(e.unacknowledgedOnly)t.push("acknowledged_at IS NULL");return this.query(`SELECT * FROM spend_anomalies WHERE ${t.join(" AND ")} ORDER BY bucket_start DESC LIMIT ?`,[...r,Math.max(1,Math.min(1000,e.limit??100))]).map(wt)}acknowledgeAnomaly(e){return this.controlPlane.database.run("UPDATE spend_anomalies SET acknowledged_at = ? WHERE id = ? AND acknowledged_at IS NULL",[this.now(),e]).changes>0}}function kt(e){if(!(e.totalMs>0))return 1;return Math.min(1,Math.max(0,e.elapsedMs/e.totalMs))}function Jr(e){let t=e.window,r=Math.max(1,t.elapsedMs),n=e.actualCents/r,o=e.series??[],a=Math.min(1,Math.max(0,e.recencyWeight??0.6));if(o.length<2||a===0)return n;let l=0.3,u=o[0].costCents;for(let E=1;E<o.length;E++)u=l*o[E].costCents+(1-l)*u;let p=u/3600000;return n*(1-a)+p*a}function Zr(e,t){let r=kt(e),n=1-Math.exp(-3*r),o=Math.min(1,t/6);return Math.round(n*o*100)/100}function Uc(e){let t=e.window,r=kt(t),n=Math.max(0,e.actualCents),o=Jr(e),a=Math.max(0,t.totalMs-t.elapsedMs),l=n+o*a,u=(e.series??[]).filter((E)=>E.costCents>0).length,p={actualCents:n,burnRateCentsPerMs:o,projectedCents:l,elapsedFraction:r,confidence:Zr(t,u)};if(e.limitCents!=null&&e.limitCents>0&&o>0){let E=e.limitCents-n;if(E<=0)p.timeToExhaustionMs=0,p.exhaustionAt=new Date(new Date(t.start).getTime()+t.elapsedMs).toISOString();else{let g=E/o;if(g<=a)p.timeToExhaustionMs=g,p.exhaustionAt=new Date(new Date(t.start).getTime()+t.elapsedMs+g).toISOString()}}return p}function Ms(e,t){if(t==null)return 0;if(t<=0)return e>0?1/0:0;return e/t*100}function Rr(e){if(e==null)return"";if(e<=0)return"now";let t=Math.floor(e/3600000),r=Math.floor(t/24);if(r>0)return`${r}d ${t%24}h`;if(t>0)return`${t}h ${Math.floor(e%3600000/60000)}m`;return`${Math.max(1,Math.floor(e/60000))}m`}var mp=0.35;function oi(e){return e.hardLimitCents??e.softLimitCents}function en(e,t,r){if(r.some((l)=>l!=="notify"))return"hard_capped";let o=oi(e),a=e.softLimitCents;if(a!=null&&o!=null&&o>0&&t>=a/o*100)return"soft_capped";if(t>=50)return"warning";return"ok"}function Oe(e){return[...new Set(e)].sort((t,r)=>R[t]-R[r])}function tn(e,t,r,n,o){if(o.length===0)return`Spend is at ${r.toFixed(1)}% of the ${t.period} budget.`;let a=o[o.length-1];if(a.projected)return`Projected spend for this ${t.period} window reaches ${a.observedPercent.toFixed(1)}% of the budget (${n.confidence.toFixed(2)} confidence), crossing the ${a.atPercent}% threshold.`;return`Spend reached ${r.toFixed(1)}% of the ${t.period} budget, crossing the ${a.atPercent}% threshold${e==="hard_capped"?" and triggering enforcement":""}.`}function Qc(e){let{budget:t,window:r}=e,n=e.now??new Date,o=oi(t),a=Uc({window:r,actualCents:e.actualCents,series:e.series,limitCents:o}),l=Ms(e.actualCents,o),u=Ms(a.projectedCents,o),p=t.graceSeconds*1000,E=p===0||e.breachingSince!=null&&n.getTime()-new Date(e.breachingSince).getTime()>=p,g=a.confidence>=mp,m=[],T=new Set;for(let v of[...t.thresholds].sort((I,S)=>I.atPercent-S.atPercent)){let I=v.onProjection===!0,S=I?u:l;if(!(S>=v.atPercent))continue;let O=v.actions.filter((P)=>P!=="notify");if(I&&!g&&O.length>0)continue;m.push({atPercent:v.atPercent,actions:v.actions,projected:I,observedPercent:S});for(let P of v.actions){if(P!=="notify"&&!E)continue;T.add(P)}}let N=Oe(T),h=100-t.hysteresisPercent,f=Oe((e.activeActions??[]).filter((v)=>{if(T.has(v))return!1;let I=t.thresholds.filter((O)=>O.actions.includes(v)).reduce((O,P)=>O==null?P.atPercent:Math.min(O,P.atPercent),void 0);if(I==null)return!0;return Math.max(l,g?u:0)<=I*(h/100)})),L=en(t,l,N);return{budgetId:t.id,level:L,window:r,projection:a,usedPercent:l,projectedPercent:u,breaches:m,actions:t.dryRun?N.filter((v)=>v==="notify"):N,releases:f,simulated:t.dryRun,reason:tn(L,t,l,a,m),evaluatedAt:n.toISOString()}}function Hc(e){let t=new Set;for(let a of e)for(let l of a.actions)t.add(l);let r=new Set;for(let a of e)for(let l of a.releases)if(!t.has(l))r.add(l);let n={ok:0,warning:1,soft_capped:2,hard_capped:3},o=e.reduce((a,l)=>n[l.level]>n[a]?l.level:a,"ok");return{actions:Oe(t),releases:Oe(r),level:o}}var ai={notify:"Send the configured spend notifications.",block_builds:"Refuse new builds. Running builds finish.",block_deployments:"Refuse new deployments. The running release keeps serving.",throttle_requests:"Rate-limit inbound requests at the edge to cap egress and compute.",suspend_functions:"Stop invoking serverless functions; static and cached responses still serve.",serve_static:"Serve the last built static output only; dynamic rendering is off.",suspend_project:"Park all inbound traffic behind a 503. No data is removed."},hp=["throttle_requests","suspend_functions","serve_static","suspend_project"],rn=["production"];function Xt(e,t,r){let n=hp.includes(e),o=r.approvalRequiredFor??rn,a=r.environmentKind!=null&&o.includes(r.environmentKind),l=r.maxAutomaticAction!=null&&R[e]>R[r.maxAutomaticAction];return{action:e,description:ai[e],userVisible:n,requiresApproval:l||n&&a,reason:t}}function Gc(e,t={}){let r=e.actions.map((o)=>Xt(o,e.reason,t)),n=[...e.releases].sort((o,a)=>R[a]-R[o]).map((o)=>Xt(o,"Spend fell back below the threshold that armed this action.",t));return{budgetId:e.budgetId,simulated:e.simulated,apply:r.filter((o)=>!o.requiresApproval),release:n.map((o)=>({...o,requiresApproval:!1})),withheld:r.filter((o)=>o.requiresApproval)}}async function qc(e,t,r,n,o){let a={applied:[],released:[],failed:[],withheld:n.withheld,simulated:n.simulated};for(let l of n.apply){let u=e.openEnforcement({budget:t,action:l.action,reason:l.reason,triggeredAtPercent:r.usedPercent,simulated:n.simulated});if(u.state==="active")continue;if(n.simulated){a.applied.push(e.transitionEnforcement(u.id,"active",{restore:{simulated:!0}}));continue}try{let p=await o.apply(l.action,{budget:t,decision:r,record:u});a.applied.push(e.transitionEnforcement(u.id,"active",{restore:p}))}catch(p){let E=p instanceof Error?p.message:String(p);e.transitionEnforcement(u.id,"failed",{error:E}),a.failed.push({action:l.action,error:E})}}for(let l of n.release){let u=e.activeEnforcement(t.id,l.action);if(!u)continue;if(n.simulated||u.simulated){a.released.push(e.transitionEnforcement(u.id,"released"));continue}e.transitionEnforcement(u.id,"releasing");try{await o.release(l.action,{budget:t,record:u,restore:u.restore}),a.released.push(e.transitionEnforcement(u.id,"released"))}catch(p){let E=p instanceof Error?p.message:String(p);e.transitionEnforcement(u.id,"releasing",{error:E}),a.failed.push({action:l.action,error:E})}}return a}function Vc(e){return e.filter((t)=>t.state==="active").map((t)=>t.action).sort((t,r)=>R[r]-R[t])[0]}function jc(e,t){let r=new Set(t.filter((o)=>o.state==="active"&&!o.simulated).map((o)=>o.action)),n={build:["block_builds","suspend_project"],deploy:["block_deployments","suspend_project"],function_invoke:["suspend_functions","serve_static","suspend_project"],request:["suspend_project"]};for(let o of n[e]??[])if(r.has(o))return{allowed:!1,blockedBy:o,reason:ai[o]};return{allowed:!0}}function Fs(e){if(e.length===0)return 0;let t=[...e].sort((n,o)=>n-o),r=t.length>>1;return t.length%2===0?(t[r-1]+t[r])/2:t[r]}function fp(e,t){if(e.length===0)return 0;let r=t??Fs(e);return 1.4826*Fs(e.map((n)=>Math.abs(n-r)))}function Ap(e,t){let r=Fs(t),n=fp(t,r);if(n===0)n=Math.max(Math.abs(r)*0.1,Number.EPSILON);return{score:(e-r)/n,center:r,deviation:n}}function rf(e,t=0.3){let r=[],n=e[0]??0;for(let o of e)n=t*o+(1-t)*n,r.push(n);return r}function nn(e,t,r){let n=[];for(let o=t-r;o>=0;o-=r)if(Number.isFinite(e[o]))n.push(e[o]);return n}function yp(e,t={}){let r=Math.max(1,Math.floor(t.seasonLength??24)),n=t.threshold??3.5,o=t.criticalThreshold??n*2,a=Math.max(2,Math.floor(t.minHistory??3)),l=Math.max(0,t.minAbsoluteDelta??0),u=e.map((g)=>g.value),p=[],E=0;for(let g=0;g<e.length;g++){let m=nn(u,g,r);if(m.length<a)continue;let T=u[g];if(!Number.isFinite(T))continue;E++;let{score:N,center:h,deviation:f}=Ap(T,m),L=N>=0?"spike":"drop";if(L==="drop"&&t.detectDrops!==!0)continue;if(Math.abs(N)<n)continue;if(Math.abs(T-h)<l)continue;p.push({bucketStart:e[g].bucketStart,observed:T,expected:h,score:N,direction:L,deltaPercent:h===0?T===0?0:1/0:(T-h)/h*100,severity:Math.abs(N)>=o?"critical":"warning",historySize:m.length,deviation:f})}return{anomalies:p,warmingUp:E===0,evaluated:E}}function zc(e,t={}){if(e.length===0)return;let r=yp(e,t),n=e[e.length-1].bucketStart;return r.anomalies.find((o)=>o.bucketStart===n)}function ci(e){if(e==="cost")return{seasonLength:24,threshold:3.5,minHistory:3,minAbsoluteDelta:25};if(e.startsWith("edge.")||e.startsWith("function."))return{seasonLength:168,threshold:4,minHistory:3,minAbsoluteDelta:1000};return{seasonLength:24,threshold:3.5,minHistory:3}}var Ip={low:6,medium:3.5,high:2.5},W=(e)=>typeof e==="string"&&e!==""?e:void 0;function Ze(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:W(e.project_id),environmentId:W(e.environment_id),signal:String(e.signal),enabled:Number(e.enabled)===1,sensitivity:String(e.sensitivity),seasonLength:Number(e.season_length),minAbsoluteDelta:Number(e.min_absolute_delta),detectDrops:Number(e.detect_drops)===1,severity:String(e.severity),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function on(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:W(e.project_id),signal:W(e.signal),routePattern:W(e.route_pattern),statusCode:e.status_code==null?void 0:Number(e.status_code),reason:String(e.reason),actorId:W(e.actor_id),expiresAt:W(e.expires_at),createdAt:String(e.created_at)}}function Sp(e,t){if(e==="*"||e==="**")return!0;let r=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*");return new RegExp(`^${r}$`).test(t)}class Us{controlPlane;options;constructor(e,t={}){this.controlPlane=e;this.options=t}now(){return(this.options.now?.()??new Date).toISOString()}query(e,t=[]){return this.controlPlane.database.query(e).all(...t)}upsert(e){let t=e.signal.trim();if(!t)throw Error("An anomaly config needs a signal.");if(e.seasonLength!=null&&(!Number.isInteger(e.seasonLength)||e.seasonLength<1))throw Error("seasonLength must be a positive integer.");let r=dt(e.organizationId,e.projectId,e.environmentId),n=this.now(),o=this.query("SELECT * FROM anomaly_configs WHERE scope_key = ? AND signal = ?",[r,t])[0],a=ci(t);if(o)return this.controlPlane.database.run("UPDATE anomaly_configs SET enabled=?,sensitivity=?,season_length=?,min_absolute_delta=?,detect_drops=?,severity=?,version=version+1,updated_at=? WHERE id=?",[e.enabled===!1?0:1,e.sensitivity??String(o.sensitivity),e.seasonLength??Number(o.season_length),e.minAbsoluteDelta??Number(o.min_absolute_delta),e.detectDrops==null?Number(o.detect_drops):e.detectDrops?1:0,e.severity??String(o.severity),n,String(o.id)]),this.get(String(o.id));let l=crypto.randomUUID();return this.controlPlane.database.run("INSERT INTO anomaly_configs (id,organization_id,project_id,environment_id,scope_key,signal,enabled,sensitivity,season_length,min_absolute_delta,detect_drops,severity,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,1,?,?)",[l,e.organizationId,e.projectId??null,e.environmentId??null,r,t,e.enabled===!1?0:1,e.sensitivity??"medium",e.seasonLength??a.seasonLength??24,e.minAbsoluteDelta??a.minAbsoluteDelta??0,e.detectDrops?1:0,e.severity??"warning",n,n]),this.get(l)}get(e){let t=this.query("SELECT * FROM anomaly_configs WHERE id = ?",[e])[0];return t?Ze(t):void 0}list(e){let t=["organization_id = ?"],r=[e.organizationId];if(e.projectId)t.push("(project_id IS NULL OR project_id = ?)"),r.push(e.projectId);return this.query(`SELECT * FROM anomaly_configs WHERE ${t.join(" AND ")} ORDER BY signal`,r).map(Ze)}delete(e){return this.controlPlane.database.run("DELETE FROM anomaly_configs WHERE id = ?",[e]).changes>0}optionsFor(e,t){let r=[dt(e.organizationId,e.projectId,e.environmentId),dt(e.organizationId,e.projectId),dt(e.organizationId)];for(let n of r){let o=this.query("SELECT * FROM anomaly_configs WHERE scope_key = ? AND signal = ?",[n,t])[0];if(!o)continue;let a=Ze(o);return{config:a,enabled:a.enabled,options:{...ci(t),threshold:Ip[a.sensitivity],seasonLength:a.seasonLength,minAbsoluteDelta:a.minAbsoluteDelta,detectDrops:a.detectDrops}}}return{options:ci(t),enabled:!0}}silence(e){let t=e.reason.trim();if(!t)throw Error("A silence needs a reason: someone will ask why this stopped alerting.");if(!e.signal&&!e.routePattern&&e.statusCode==null)throw Error("A silence needs at least one of signal, routePattern, or statusCode.");let r=crypto.randomUUID();return this.controlPlane.database.run("INSERT INTO anomaly_silences (id,organization_id,project_id,scope_key,signal,route_pattern,status_code,reason,actor_id,expires_at,created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?)",[r,e.organizationId,e.projectId??null,dt(e.organizationId,e.projectId),e.signal??null,e.routePattern??null,e.statusCode??null,t,e.actorId??null,e.expiresAt??null,this.now()]),this.listSilences({organizationId:e.organizationId}).find((n)=>n.id===r)}listSilences(e){let t=["organization_id = ?"],r=[e.organizationId];if(e.projectId)t.push("(project_id IS NULL OR project_id = ?)"),r.push(e.projectId);if(!e.includeExpired)t.push("(expires_at IS NULL OR expires_at > ?)"),r.push(this.now());return this.query(`SELECT * FROM anomaly_silences WHERE ${t.join(" AND ")} ORDER BY created_at DESC`,r).map(on)}removeSilence(e){return this.controlPlane.database.run("DELETE FROM anomaly_silences WHERE id = ?",[e]).changes>0}isSilenced(e,t){return this.listSilences(e).find((r)=>{if(r.signal&&r.signal!==t.signal)return!1;if(r.statusCode!=null&&r.statusCode!==t.statusCode)return!1;if(r.routePattern){if(!t.route)return!1;if(!Sp(r.routePattern,t.route))return!1}return!0})}}var Dr=[{key:"cost",routeAware:!1,label:"Cost",source:"usage",gapPolicy:"zero",minSamples:0,unit:"cents"},{key:"edge.requests",routeAware:!1,label:"Edge requests",source:"usage",gapPolicy:"zero",minSamples:0,unit:"requests"},{key:"edge.egress_gb",routeAware:!1,label:"Edge egress",source:"usage",gapPolicy:"zero",minSamples:0,unit:"GB"},{key:"function.invocations",routeAware:!1,label:"Function invocations",source:"usage",gapPolicy:"zero",minSamples:0,unit:"invocations"},{key:"http.requests",routeAware:!0,label:"HTTP requests",source:"telemetry",gapPolicy:"zero",minSamples:0,unit:"requests"},{key:"http.errors",routeAware:!0,label:"HTTP 5xx",source:"telemetry",gapPolicy:"zero",minSamples:0,unit:"responses"},{key:"http.error_rate",routeAware:!0,label:"HTTP error rate",source:"telemetry",gapPolicy:"gap",minSamples:20,unit:"ratio",ratio:!0},{key:"http.client_error_rate",routeAware:!0,label:"HTTP 4xx rate",source:"telemetry",gapPolicy:"gap",minSamples:20,unit:"ratio",ratio:!0},{key:"http.latency_p95",routeAware:!0,label:"Latency p95",source:"telemetry",gapPolicy:"gap",minSamples:20,unit:"ms"}];function Qs(e){return Dr.find((t)=>t.key===e)}var le=3600000;function sn(e,t=960){let r=Math.floor(new Date(e.from).getTime()/le)*le,n=new Date(e.to).getTime(),o=[];for(let a=r;a<n&&o.length<t;a+=le)o.push(a);return o}function et(e,t,r){let n=[],o=0,a=0;for(let l of sn(t)){let u=r.get(l),p=new Date(l).toISOString();if(!u){n.push({bucketStart:p,value:e.gapPolicy==="zero"?0:Number.NaN});continue}if(u.samples<e.minSamples){n.push({bucketStart:p,value:Number.NaN}),a++;continue}n.push({bucketStart:p,value:u.value}),o++}return{signal:e.key,points:n,populated:o,suppressed:a,unit:e.unit}}class Hs{controlPlane;spend;counterCache=new Map;constructor(e,t){this.controlPlane=e;this.spend=t}query(e,t){return this.controlPlane.database.query(e).all(...t)}usageSeries(e,t,r){let n=this.spend.summarizeUsage({organizationId:t.organizationId,projectId:t.projectId,environmentId:t.environmentId,meters:e.key==="cost"?void 0:[e.key],from:r.from,to:r.to}),o=new Map;for(let a of n.series)o.set(new Date(a.bucketStart).getTime(),{value:e.key==="cost"?a.costCents:a.quantity,samples:1});return et(e,r,o)}requestFilter(e,t){let r=["project_id = ?","kind = 'request'","timestamp >= ?","timestamp < ?"],n=[e.projectId,t.from,t.to];if(e.environmentId)r.push("environment_id = ?"),n.push(e.environmentId);if(e.route)r.push("path_template = ?"),n.push(e.route);return{clauses:r,bindings:n}}counters(e,t){let r=[e.projectId,e.environmentId??"",e.route??"",t.from,t.to].join("\x00"),n=this.counterCache.get(r);if(n)return n;let{clauses:o,bindings:a}=this.requestFilter(e,t),l=this.query(`SELECT
|
|
1515
|
+
FROM spend_usage WHERE ${t} GROUP BY bucket_start ORDER BY bucket_start`,r).map((a)=>({bucketStart:String(a.bucket_start),costCents:Number(a.cost_cents),quantity:Number(a.quantity)}));return{from:e.from,to:e.to,totalCents:n.reduce((a,l)=>a+l.costCents,0),byMeter:n,series:o}}listRollups(e,t=1000){let{where:r,bindings:n}=this.usageClauses(e);return this.query(`SELECT * FROM spend_usage WHERE ${r} ORDER BY bucket_start DESC LIMIT ?`,[...n,Math.max(1,Math.min(1e4,t))]).map(Wr)}budgetSpendCents(e,t=new Date){let r=ct(e.period,e.timezone,t),n=this.summarizeUsage({organizationId:e.organizationId,projectId:e.projectId,environmentId:e.environmentId,meters:e.meters.length>0?e.meters:void 0,from:r.start,to:r.end});return{window:r,summary:n}}pruneUsage(e,t=new Date){let r=new Date(t.getTime()-Math.max(1,e)*86400000).toISOString(),n=this.controlPlane.database.run("DELETE FROM spend_usage WHERE bucket_start < ?",[r]).changes,o=new Date(t.getTime()-604800000).toISOString(),a=this.controlPlane.database.run("DELETE FROM spend_usage_receipts WHERE created_at < ?",[o]).changes;return{rollups:n,receipts:a}}recordDecision(e){this.controlPlane.database.run("INSERT INTO spend_decisions (id,budget_id,level,window_start,window_end,used_percent,projected_percent,actual_cents,projected_cents,actions,simulated,reason,evaluated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",[crypto.randomUUID(),e.budgetId,e.level,e.window.start,e.window.end,e.usedPercent,e.projectedPercent,e.projection.actualCents,e.projection.projectedCents,JSON.stringify(e.actions),e.simulated?1:0,e.reason,e.evaluatedAt])}listDecisions(e,t=50){return this.query("SELECT * FROM spend_decisions WHERE budget_id = ? ORDER BY evaluated_at DESC LIMIT ?",[e,Math.max(1,Math.min(500,t))]).map((r)=>({id:r.id,budgetId:r.budget_id,level:r.level,window:{start:r.window_start,end:r.window_end},usedPercent:Number(r.used_percent),projectedPercent:Number(r.projected_percent),actualCents:Number(r.actual_cents),projectedCents:Number(r.projected_cents),actions:ce(r.actions),simulated:Ae(r.simulated),reason:r.reason,evaluatedAt:r.evaluated_at}))}openEnforcement(e){let t=this.activeEnforcement(e.budget.id,e.action);if(t)return t;let r=crypto.randomUUID(),n=this.now();return this.controlPlane.database.run("INSERT INTO spend_enforcements (id,budget_id,organization_id,project_id,environment_id,action,state,reason,restore,triggered_at_percent,simulated,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",[r,e.budget.id,e.budget.organizationId,e.budget.projectId??null,e.budget.environmentId??null,e.action,"pending",e.reason,JSON.stringify(s(e.restore??{})),e.triggeredAtPercent,e.simulated?1:0,n,n]),this.getEnforcement(r)}getEnforcement(e){let t=this.query("SELECT * FROM spend_enforcements WHERE id = ?",[e])[0];return t?Je(t):void 0}activeEnforcement(e,t){let r=this.query("SELECT * FROM spend_enforcements WHERE budget_id = ? AND action = ? AND state IN ('pending','active','releasing')",[e,t])[0];return r?Je(r):void 0}listEnforcements(e){let t=["organization_id = ?"],r=[e.organizationId];if(e.budgetId)t.push("budget_id = ?"),r.push(e.budgetId);if(e.activeOnly)t.push("state IN ('pending','active','releasing')");return this.query(`SELECT * FROM spend_enforcements WHERE ${t.join(" AND ")} ORDER BY created_at DESC`,r).map(Je)}transitionEnforcement(e,t,r={}){let n=this.getEnforcement(e);if(!n)throw Error("Enforcement was not found.");let o=this.now();return this.controlPlane.database.run("UPDATE spend_enforcements SET state=?, error=?, restore=?, applied_at=?, released_at=?, updated_at=? WHERE id=?",[t,r.error??null,JSON.stringify(s(r.restore??n.restore)),t==="active"?n.appliedAt??o:n.appliedAt??null,t==="released"?o:n.releasedAt??null,o,e]),this.getEnforcement(e)}recordAnomaly(e){let t=crypto.randomUUID();return this.controlPlane.database.run("INSERT OR IGNORE INTO spend_anomalies (id,organization_id,project_id,environment_id,scope_key,signal,direction,observed,expected,score,delta_percent,severity,bucket_start,evidence,created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.organizationId,e.projectId??null,e.environmentId??null,dt(e.organizationId,e.projectId,e.environmentId),e.signal,e.direction,e.observed,e.expected,e.score,e.deltaPercent,e.severity,e.bucketStart,JSON.stringify(s(e.evidence??{})),this.now()]).changes>0?this.getAnomaly(t):void 0}getAnomaly(e){let t=this.query("SELECT * FROM spend_anomalies WHERE id = ?",[e])[0];return t?wt(t):void 0}listAnomalies(e){let t=["organization_id = ?"],r=[e.organizationId];if(e.projectId)t.push("project_id = ?"),r.push(e.projectId);if(e.since)t.push("bucket_start >= ?"),r.push(e.since);if(e.unacknowledgedOnly)t.push("acknowledged_at IS NULL");return this.query(`SELECT * FROM spend_anomalies WHERE ${t.join(" AND ")} ORDER BY bucket_start DESC LIMIT ?`,[...r,Math.max(1,Math.min(1000,e.limit??100))]).map(wt)}acknowledgeAnomaly(e){return this.controlPlane.database.run("UPDATE spend_anomalies SET acknowledged_at = ? WHERE id = ? AND acknowledged_at IS NULL",[this.now(),e]).changes>0}}function kt(e){if(!(e.totalMs>0))return 1;return Math.min(1,Math.max(0,e.elapsedMs/e.totalMs))}function Jr(e){let t=e.window,r=Math.max(1,t.elapsedMs),n=e.actualCents/r,o=e.series??[],a=Math.min(1,Math.max(0,e.recencyWeight??0.6));if(o.length<2||a===0)return n;let l=0.3,u=o[0].costCents;for(let E=1;E<o.length;E++)u=l*o[E].costCents+(1-l)*u;let p=u/3600000;return n*(1-a)+p*a}function Zr(e,t){let r=kt(e),n=1-Math.exp(-3*r),o=Math.min(1,t/6);return Math.round(n*o*100)/100}function Hc(e){let t=e.window,r=kt(t),n=Math.max(0,e.actualCents),o=Jr(e),a=Math.max(0,t.totalMs-t.elapsedMs),l=n+o*a,u=(e.series??[]).filter((E)=>E.costCents>0).length,p={actualCents:n,burnRateCentsPerMs:o,projectedCents:l,elapsedFraction:r,confidence:Zr(t,u)};if(e.limitCents!=null&&e.limitCents>0&&o>0){let E=e.limitCents-n;if(E<=0)p.timeToExhaustionMs=0,p.exhaustionAt=new Date(new Date(t.start).getTime()+t.elapsedMs).toISOString();else{let g=E/o;if(g<=a)p.timeToExhaustionMs=g,p.exhaustionAt=new Date(new Date(t.start).getTime()+t.elapsedMs+g).toISOString()}}return p}function Us(e,t){if(t==null)return 0;if(t<=0)return e>0?1/0:0;return e/t*100}function Rr(e){if(e==null)return"";if(e<=0)return"now";let t=Math.floor(e/3600000),r=Math.floor(t/24);if(r>0)return`${r}d ${t%24}h`;if(t>0)return`${t}h ${Math.floor(e%3600000/60000)}m`;return`${Math.max(1,Math.floor(e/60000))}m`}var Cp=0.35;function ai(e){return e.hardLimitCents??e.softLimitCents}function en(e,t,r){if(r.some((l)=>l!=="notify"))return"hard_capped";let o=ai(e),a=e.softLimitCents;if(a!=null&&o!=null&&o>0&&t>=a/o*100)return"soft_capped";if(t>=50)return"warning";return"ok"}function Oe(e){return[...new Set(e)].sort((t,r)=>R[t]-R[r])}function tn(e,t,r,n,o){if(o.length===0)return`Spend is at ${r.toFixed(1)}% of the ${t.period} budget.`;let a=o[o.length-1];if(a.projected)return`Projected spend for this ${t.period} window reaches ${a.observedPercent.toFixed(1)}% of the budget (${n.confidence.toFixed(2)} confidence), crossing the ${a.atPercent}% threshold.`;return`Spend reached ${r.toFixed(1)}% of the ${t.period} budget, crossing the ${a.atPercent}% threshold${e==="hard_capped"?" and triggering enforcement":""}.`}function Gc(e){let{budget:t,window:r}=e,n=e.now??new Date,o=ai(t),a=Hc({window:r,actualCents:e.actualCents,series:e.series,limitCents:o}),l=Us(e.actualCents,o),u=Us(a.projectedCents,o),p=t.graceSeconds*1000,E=p===0||e.breachingSince!=null&&n.getTime()-new Date(e.breachingSince).getTime()>=p,g=a.confidence>=Cp,m=[],T=new Set;for(let L of[...t.thresholds].sort((v,I)=>v.atPercent-I.atPercent)){let v=L.onProjection===!0,I=v?u:l;if(!(I>=L.atPercent))continue;let A=L.actions.filter((k)=>k!=="notify");if(v&&!g&&A.length>0)continue;m.push({atPercent:L.atPercent,actions:L.actions,projected:v,observedPercent:I});for(let k of L.actions){if(k!=="notify"&&!E)continue;T.add(k)}}let h=Oe(T),_=100-t.hysteresisPercent,N=Oe((e.activeActions??[]).filter((L)=>{if(T.has(L))return!1;let v=t.thresholds.filter((A)=>A.actions.includes(L)).reduce((A,k)=>A==null?k.atPercent:Math.min(A,k.atPercent),void 0);if(v==null)return!0;return Math.max(l,g?u:0)<=v*(_/100)})),y=en(t,l,h);return{budgetId:t.id,level:y,window:r,projection:a,usedPercent:l,projectedPercent:u,breaches:m,actions:t.dryRun?h.filter((L)=>L==="notify"):h,releases:N,simulated:t.dryRun,reason:tn(y,t,l,a,m),evaluatedAt:n.toISOString()}}function qc(e){let t=new Set;for(let a of e)for(let l of a.actions)t.add(l);let r=new Set;for(let a of e)for(let l of a.releases)if(!t.has(l))r.add(l);let n={ok:0,warning:1,soft_capped:2,hard_capped:3},o=e.reduce((a,l)=>n[l.level]>n[a]?l.level:a,"ok");return{actions:Oe(t),releases:Oe(r),level:o}}var ci={notify:"Send the configured spend notifications.",block_builds:"Refuse new builds. Running builds finish.",block_deployments:"Refuse new deployments. The running release keeps serving.",throttle_requests:"Rate-limit inbound requests at the edge to cap egress and compute.",suspend_functions:"Stop invoking serverless functions; static and cached responses still serve.",serve_static:"Serve the last built static output only; dynamic rendering is off.",suspend_project:"Park all inbound traffic behind a 503. No data is removed."},Ep=["throttle_requests","suspend_functions","serve_static","suspend_project"],rn=["production"];function Xt(e,t,r){let n=Ep.includes(e),o=r.approvalRequiredFor??rn,a=r.environmentKind!=null&&o.includes(r.environmentKind),l=r.maxAutomaticAction!=null&&R[e]>R[r.maxAutomaticAction];return{action:e,description:ci[e],userVisible:n,requiresApproval:l||n&&a,reason:t}}function Vc(e,t={}){let r=e.actions.map((o)=>Xt(o,e.reason,t)),n=[...e.releases].sort((o,a)=>R[a]-R[o]).map((o)=>Xt(o,"Spend fell back below the threshold that armed this action.",t));return{budgetId:e.budgetId,simulated:e.simulated,apply:r.filter((o)=>!o.requiresApproval),release:n.map((o)=>({...o,requiresApproval:!1})),withheld:r.filter((o)=>o.requiresApproval)}}async function jc(e,t,r,n,o){let a={applied:[],released:[],failed:[],withheld:n.withheld,simulated:n.simulated};for(let l of n.apply){let u=e.openEnforcement({budget:t,action:l.action,reason:l.reason,triggeredAtPercent:r.usedPercent,simulated:n.simulated});if(u.state==="active")continue;if(n.simulated){a.applied.push(e.transitionEnforcement(u.id,"active",{restore:{simulated:!0}}));continue}try{let p=await o.apply(l.action,{budget:t,decision:r,record:u});a.applied.push(e.transitionEnforcement(u.id,"active",{restore:p}))}catch(p){let E=p instanceof Error?p.message:String(p);e.transitionEnforcement(u.id,"failed",{error:E}),a.failed.push({action:l.action,error:E})}}for(let l of n.release){let u=e.activeEnforcement(t.id,l.action);if(!u)continue;if(n.simulated||u.simulated){a.released.push(e.transitionEnforcement(u.id,"released"));continue}e.transitionEnforcement(u.id,"releasing");try{await o.release(l.action,{budget:t,record:u,restore:u.restore}),a.released.push(e.transitionEnforcement(u.id,"released"))}catch(p){let E=p instanceof Error?p.message:String(p);e.transitionEnforcement(u.id,"releasing",{error:E}),a.failed.push({action:l.action,error:E})}}return a}function zc(e){return e.filter((t)=>t.state==="active").map((t)=>t.action).sort((t,r)=>R[r]-R[t])[0]}function Kc(e,t){let r=new Set(t.filter((o)=>o.state==="active"&&!o.simulated).map((o)=>o.action)),n={build:["block_builds","suspend_project"],deploy:["block_deployments","suspend_project"],function_invoke:["suspend_functions","serve_static","suspend_project"],request:["suspend_project"]};for(let o of n[e]??[])if(r.has(o))return{allowed:!1,blockedBy:o,reason:ci[o]};return{allowed:!0}}function Qs(e){if(e.length===0)return 0;let t=[...e].sort((n,o)=>n-o),r=t.length>>1;return t.length%2===0?(t[r-1]+t[r])/2:t[r]}function bp(e,t){if(e.length===0)return 0;let r=t??Qs(e);return 1.4826*Qs(e.map((n)=>Math.abs(n-r)))}function vp(e,t){let r=Qs(t),n=bp(t,r);if(n===0)n=Math.max(Math.abs(r)*0.1,Number.EPSILON);return{score:(e-r)/n,center:r,deviation:n}}function lf(e,t=0.3){let r=[],n=e[0]??0;for(let o of e)n=t*o+(1-t)*n,r.push(n);return r}function nn(e,t,r){let n=[];for(let o=t-r;o>=0;o-=r)if(Number.isFinite(e[o]))n.push(e[o]);return n}function Tp(e,t={}){let r=Math.max(1,Math.floor(t.seasonLength??24)),n=t.threshold??3.5,o=t.criticalThreshold??n*2,a=Math.max(2,Math.floor(t.minHistory??3)),l=Math.max(0,t.minAbsoluteDelta??0),u=e.map((g)=>g.value),p=[],E=0;for(let g=0;g<e.length;g++){let m=nn(u,g,r);if(m.length<a)continue;let T=u[g];if(!Number.isFinite(T))continue;E++;let{score:h,center:_,deviation:N}=vp(T,m),y=h>=0?"spike":"drop";if(y==="drop"&&t.detectDrops!==!0)continue;if(Math.abs(h)<n)continue;if(Math.abs(T-_)<l)continue;p.push({bucketStart:e[g].bucketStart,observed:T,expected:_,score:h,direction:y,deltaPercent:_===0?T===0?0:1/0:(T-_)/_*100,severity:Math.abs(h)>=o?"critical":"warning",historySize:m.length,deviation:N})}return{anomalies:p,warmingUp:E===0,evaluated:E}}function Wc(e,t={}){if(e.length===0)return;let r=Tp(e,t),n=e[e.length-1].bucketStart;return r.anomalies.find((o)=>o.bucketStart===n)}function di(e){if(e==="cost")return{seasonLength:24,threshold:3.5,minHistory:3,minAbsoluteDelta:25};if(e.startsWith("edge.")||e.startsWith("function."))return{seasonLength:168,threshold:4,minHistory:3,minAbsoluteDelta:1000};return{seasonLength:24,threshold:3.5,minHistory:3}}var wp={low:6,medium:3.5,high:2.5},W=(e)=>typeof e==="string"&&e!==""?e:void 0;function Ze(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:W(e.project_id),environmentId:W(e.environment_id),signal:String(e.signal),enabled:Number(e.enabled)===1,sensitivity:String(e.sensitivity),seasonLength:Number(e.season_length),minAbsoluteDelta:Number(e.min_absolute_delta),detectDrops:Number(e.detect_drops)===1,severity:String(e.severity),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function on(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:W(e.project_id),signal:W(e.signal),routePattern:W(e.route_pattern),statusCode:e.status_code==null?void 0:Number(e.status_code),reason:String(e.reason),actorId:W(e.actor_id),expiresAt:W(e.expires_at),createdAt:String(e.created_at)}}function Rp(e,t){if(e==="*"||e==="**")return!0;let r=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*");return new RegExp(`^${r}$`).test(t)}class Hs{controlPlane;options;constructor(e,t={}){this.controlPlane=e;this.options=t}now(){return(this.options.now?.()??new Date).toISOString()}query(e,t=[]){return this.controlPlane.database.query(e).all(...t)}upsert(e){let t=e.signal.trim();if(!t)throw Error("An anomaly config needs a signal.");if(e.seasonLength!=null&&(!Number.isInteger(e.seasonLength)||e.seasonLength<1))throw Error("seasonLength must be a positive integer.");let r=dt(e.organizationId,e.projectId,e.environmentId),n=this.now(),o=this.query("SELECT * FROM anomaly_configs WHERE scope_key = ? AND signal = ?",[r,t])[0],a=di(t);if(o)return this.controlPlane.database.run("UPDATE anomaly_configs SET enabled=?,sensitivity=?,season_length=?,min_absolute_delta=?,detect_drops=?,severity=?,version=version+1,updated_at=? WHERE id=?",[e.enabled===!1?0:1,e.sensitivity??String(o.sensitivity),e.seasonLength??Number(o.season_length),e.minAbsoluteDelta??Number(o.min_absolute_delta),e.detectDrops==null?Number(o.detect_drops):e.detectDrops?1:0,e.severity??String(o.severity),n,String(o.id)]),this.get(String(o.id));let l=crypto.randomUUID();return this.controlPlane.database.run("INSERT INTO anomaly_configs (id,organization_id,project_id,environment_id,scope_key,signal,enabled,sensitivity,season_length,min_absolute_delta,detect_drops,severity,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,1,?,?)",[l,e.organizationId,e.projectId??null,e.environmentId??null,r,t,e.enabled===!1?0:1,e.sensitivity??"medium",e.seasonLength??a.seasonLength??24,e.minAbsoluteDelta??a.minAbsoluteDelta??0,e.detectDrops?1:0,e.severity??"warning",n,n]),this.get(l)}get(e){let t=this.query("SELECT * FROM anomaly_configs WHERE id = ?",[e])[0];return t?Ze(t):void 0}list(e){let t=["organization_id = ?"],r=[e.organizationId];if(e.projectId)t.push("(project_id IS NULL OR project_id = ?)"),r.push(e.projectId);return this.query(`SELECT * FROM anomaly_configs WHERE ${t.join(" AND ")} ORDER BY signal`,r).map(Ze)}delete(e){return this.controlPlane.database.run("DELETE FROM anomaly_configs WHERE id = ?",[e]).changes>0}optionsFor(e,t){let r=[dt(e.organizationId,e.projectId,e.environmentId),dt(e.organizationId,e.projectId),dt(e.organizationId)];for(let n of r){let o=this.query("SELECT * FROM anomaly_configs WHERE scope_key = ? AND signal = ?",[n,t])[0];if(!o)continue;let a=Ze(o);return{config:a,enabled:a.enabled,options:{...di(t),threshold:wp[a.sensitivity],seasonLength:a.seasonLength,minAbsoluteDelta:a.minAbsoluteDelta,detectDrops:a.detectDrops}}}return{options:di(t),enabled:!0}}silence(e){let t=e.reason.trim();if(!t)throw Error("A silence needs a reason: someone will ask why this stopped alerting.");if(!e.signal&&!e.routePattern&&e.statusCode==null)throw Error("A silence needs at least one of signal, routePattern, or statusCode.");let r=crypto.randomUUID();return this.controlPlane.database.run("INSERT INTO anomaly_silences (id,organization_id,project_id,scope_key,signal,route_pattern,status_code,reason,actor_id,expires_at,created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?)",[r,e.organizationId,e.projectId??null,dt(e.organizationId,e.projectId),e.signal??null,e.routePattern??null,e.statusCode??null,t,e.actorId??null,e.expiresAt??null,this.now()]),this.listSilences({organizationId:e.organizationId}).find((n)=>n.id===r)}listSilences(e){let t=["organization_id = ?"],r=[e.organizationId];if(e.projectId)t.push("(project_id IS NULL OR project_id = ?)"),r.push(e.projectId);if(!e.includeExpired)t.push("(expires_at IS NULL OR expires_at > ?)"),r.push(this.now());return this.query(`SELECT * FROM anomaly_silences WHERE ${t.join(" AND ")} ORDER BY created_at DESC`,r).map(on)}removeSilence(e){return this.controlPlane.database.run("DELETE FROM anomaly_silences WHERE id = ?",[e]).changes>0}isSilenced(e,t){return this.listSilences(e).find((r)=>{if(r.signal&&r.signal!==t.signal)return!1;if(r.statusCode!=null&&r.statusCode!==t.statusCode)return!1;if(r.routePattern){if(!t.route)return!1;if(!Rp(r.routePattern,t.route))return!1}return!0})}}var Dr=[{key:"cost",routeAware:!1,label:"Cost",source:"usage",gapPolicy:"zero",minSamples:0,unit:"cents"},{key:"edge.requests",routeAware:!1,label:"Edge requests",source:"usage",gapPolicy:"zero",minSamples:0,unit:"requests"},{key:"edge.egress_gb",routeAware:!1,label:"Edge egress",source:"usage",gapPolicy:"zero",minSamples:0,unit:"GB"},{key:"function.invocations",routeAware:!1,label:"Function invocations",source:"usage",gapPolicy:"zero",minSamples:0,unit:"invocations"},{key:"http.requests",routeAware:!0,label:"HTTP requests",source:"telemetry",gapPolicy:"zero",minSamples:0,unit:"requests"},{key:"http.errors",routeAware:!0,label:"HTTP 5xx",source:"telemetry",gapPolicy:"zero",minSamples:0,unit:"responses"},{key:"http.error_rate",routeAware:!0,label:"HTTP error rate",source:"telemetry",gapPolicy:"gap",minSamples:20,unit:"ratio",ratio:!0},{key:"http.client_error_rate",routeAware:!0,label:"HTTP 4xx rate",source:"telemetry",gapPolicy:"gap",minSamples:20,unit:"ratio",ratio:!0},{key:"http.latency_p95",routeAware:!0,label:"Latency p95",source:"telemetry",gapPolicy:"gap",minSamples:20,unit:"ms"}];function Gs(e){return Dr.find((t)=>t.key===e)}var le=3600000;function sn(e,t=960){let r=Math.floor(new Date(e.from).getTime()/le)*le,n=new Date(e.to).getTime(),o=[];for(let a=r;a<n&&o.length<t;a+=le)o.push(a);return o}function et(e,t,r){let n=[],o=0,a=0;for(let l of sn(t)){let u=r.get(l),p=new Date(l).toISOString();if(!u){n.push({bucketStart:p,value:e.gapPolicy==="zero"?0:Number.NaN});continue}if(u.samples<e.minSamples){n.push({bucketStart:p,value:Number.NaN}),a++;continue}n.push({bucketStart:p,value:u.value}),o++}return{signal:e.key,points:n,populated:o,suppressed:a,unit:e.unit}}class qs{controlPlane;spend;counterCache=new Map;constructor(e,t){this.controlPlane=e;this.spend=t}query(e,t){return this.controlPlane.database.query(e).all(...t)}usageSeries(e,t,r){let n=this.spend.summarizeUsage({organizationId:t.organizationId,projectId:t.projectId,environmentId:t.environmentId,meters:e.key==="cost"?void 0:[e.key],from:r.from,to:r.to}),o=new Map;for(let a of n.series)o.set(new Date(a.bucketStart).getTime(),{value:e.key==="cost"?a.costCents:a.quantity,samples:1});return et(e,r,o)}requestFilter(e,t){let r=["project_id = ?","kind = 'request'","timestamp >= ?","timestamp < ?"],n=[e.projectId,t.from,t.to];if(e.environmentId)r.push("environment_id = ?"),n.push(e.environmentId);if(e.route)r.push("path_template = ?"),n.push(e.route);return{clauses:r,bindings:n}}counters(e,t){let r=[e.projectId,e.environmentId??"",e.route??"",t.from,t.to].join("\x00"),n=this.counterCache.get(r);if(n)return n;let{clauses:o,bindings:a}=this.requestFilter(e,t),l=this.query(`SELECT
|
|
1516
1516
|
CAST(strftime('%s', timestamp) AS INTEGER) / 3600 AS bucket,
|
|
1517
1517
|
COUNT(*) AS total,
|
|
1518
1518
|
SUM(CASE WHEN status_code >= 500 THEN 1 ELSE 0 END) AS server_errors,
|
|
@@ -1533,13 +1533,13 @@ import{_,d}from"./chunk-d72ddm5x.js";import{xr}from"./chunk-4yb7hf91.js";var Kh=
|
|
|
1533
1533
|
FROM ranked
|
|
1534
1534
|
WHERE position >= CAST(samples * 0.95 AS INTEGER)
|
|
1535
1535
|
GROUP BY bucket
|
|
1536
|
-
ORDER BY bucket`,o),l=new Map;for(let u of a)l.set(Number(u.bucket)*le,{value:Number(u.value),samples:Number(u.samples)});return et(e,r,l)}series(e,t,r){let n=
|
|
1536
|
+
ORDER BY bucket`,o),l=new Map;for(let u of a)l.set(Number(u.bucket)*le,{value:Number(u.value),samples:Number(u.samples)});return et(e,r,l)}series(e,t,r){let n=Gs(e);if(!n)return{signal:e,points:[],populated:0,suppressed:0,unit:""};return n.source==="usage"?this.usageSeries(n,t,r):this.telemetrySeries(n,t,r)}busiestRoutes(e,t,r=10,n=500){if(!e.projectId)return[];let o=["kind = 'request'","project_id = ?","timestamp >= ?","timestamp < ?","path_template IS NOT NULL"],a=[e.projectId,t.from,t.to];if(e.environmentId)o.push("environment_id = ?"),a.push(e.environmentId);return this.query(`SELECT path_template, COUNT(*) AS total FROM telemetry_records
|
|
1537
1537
|
WHERE ${o.join(" AND ")}
|
|
1538
|
-
GROUP BY path_template HAVING total >= ? ORDER BY total DESC LIMIT ?`,[...a,n,Math.max(1,Math.min(50,r))]).map((l)=>String(l.path_template))}}function
|
|
1538
|
+
GROUP BY path_template HAVING total >= ? ORDER BY total DESC LIMIT ?`,[...a,n,Math.max(1,Math.min(50,r))]).map((l)=>String(l.path_template))}}function Vs(e){let t={seasonLength:24,threshold:3.5,minHistory:3,minAbsoluteDelta:0,detectDrops:!1};if(e==="cost")return{...t,minAbsoluteDelta:25};if(e==="edge.requests"||e==="http.requests")return{...t,seasonLength:168,threshold:4,minAbsoluteDelta:1000,detectDrops:!0};if(e==="edge.egress_gb")return{...t,seasonLength:168,threshold:4,minAbsoluteDelta:5};if(e==="function.invocations")return{...t,seasonLength:168,threshold:4,minAbsoluteDelta:1000};if(e==="http.errors")return{...t,seasonLength:168,threshold:4,minAbsoluteDelta:25};if(e==="http.error_rate"||e==="http.client_error_rate")return{...t,seasonLength:168,threshold:3.5,minAbsoluteDelta:0.02};if(e==="http.latency_p95")return{...t,seasonLength:168,threshold:4,minAbsoluteDelta:100};return t}function Jc(e){let t=Vs(e),r=t.seasonLength*(t.minHistory+1);return Math.min(960,Math.max(336,r))}var Dp="1.3";function an(e){if(e.startsWith("edge.")||e.startsWith("object.egress"))return"Networking";if(e.startsWith("function.")||e.startsWith("compute.")||e.startsWith("build."))return"Compute";if(e.startsWith("storage.")||e.startsWith("object."))return"Storage";if(e.startsWith("database."))return"Databases";if(e.startsWith("telemetry."))return"Management and Governance";return"Other"}function Pt(e){return Ls[e]?.label??e}function jt(e){let t=Ls[e]?.unit;if(t==="gb")return"GB";if(t==="gb_hours")return"GB-Hours";if(t==="gb_seconds")return"GB-Seconds";if(t==="hours")return"Hours";if(t==="minutes")return"Minutes";if(t==="requests")return"Requests";if(t==="invocations")return"Invocations";return"Count"}function dn(e){return`${e.slice(0,10)}T00:00:00.000Z`}function cn(e){return new Date(new Date(e).getTime()+86400000).toISOString()}function ln(e){return new Date(new Date(e).getTime()+3600000).toISOString()}function Xc(e,t){let r=t.currency??"USD",n=(t.granularity??"daily")==="daily",o=new Map;for(let a of e){let l=n?dn(a.bucketStart):a.bucketStart,u=[l,a.meter,a.provider,a.region,a.projectId,a.resourceId].join("\x00"),p=o.get(u);if(p)p.quantity+=a.quantity,p.costCents+=a.costCents;else o.set(u,{rollup:a,quantity:a.quantity,costCents:a.costCents,start:l})}return[...o.values()].sort((a,l)=>a.start.localeCompare(l.start)||String(a.rollup.meter).localeCompare(String(l.rollup.meter))).map(({rollup:a,quantity:l,costCents:u,start:p})=>{let E=Math.round(u)/100,g=a.provider||"ts-cloud";return{FocusVersion:Dp,ChargePeriodStart:p,ChargePeriodEnd:n?cn(p):ln(p),BillingPeriodStart:t.billingPeriodStart,BillingPeriodEnd:t.billingPeriodEnd,BillingCurrency:r,BilledCost:E,EffectiveCost:E,ListCost:E,ChargeCategory:"Usage",ChargeDescription:`${Pt(a.meter)} on ${g}`,ProviderName:g,PublisherName:g,InvoiceIssuerName:g,ServiceName:Pt(a.meter),ServiceCategory:an(String(a.meter)),SkuId:String(a.meter),PricingUnit:jt(String(a.meter)),PricingQuantity:l,ConsumedQuantity:l,ConsumedUnit:jt(String(a.meter)),RegionId:a.region||void 0,ResourceId:a.resourceId||void 0,SubAccountId:a.projectId||void 0,SubAccountName:a.projectId?t.projectNames?.[a.projectId]??a.projectId:void 0,Tags:{...a.environmentId?{environment:a.environmentId}:{},...a.projectId?{project:a.projectId}:{}}}})}function js(e){return e.map((t)=>JSON.stringify(t)).join(`
|
|
1539
1539
|
`)+(e.length>0?`
|
|
1540
|
-
`:"")}function*nf(e,t=500){for(let r=0;r<e.length;r+=t)yield qs(e.slice(r,r+t))}class $t{store;counters=new $s;breaching=new Map;anomalyConfigs;signals;constructor(e){this.store=e;this.anomalyConfigs=new Us(e.controlPlane),this.signals=new Hs(e.controlPlane,e)}ingestTelemetry(e,t,r){let n=Mc(e,t,{counters:this.counters,defaultProvider:r});return this.store.ingestUsage(n)}ingestUsage(e,t=!0){return this.store.ingestUsage(t?Fc(e):[...e])}status(e,t=new Date){let{window:r,summary:n}=this.store.budgetSpendCents(e,t),a=this.store.listEnforcements({organizationId:e.organizationId,budgetId:e.id,activeOnly:!0}).filter((u)=>u.state==="active").map((u)=>u.action),l=Qc({budget:e,window:r,actualCents:n.totalCents,series:n.series,activeActions:a,breachingSince:this.breaching.get(e.id),now:t});return{budget:e,decision:l,summary:n,activeActions:a,timeToCap:Rr(l.projection.timeToExhaustionMs)}}async runCycle(e){let t=e.now??new Date,r=this.store.budgetsForScope(e.organizationId,e.projectId,e.environmentId),n=[],o=[];for(let l of r){let u=this.status(l,t);this.trackBreach(l,u.decision,t),this.store.recordDecision(u.decision),n.push(u)}let a=Hc(n.map((l)=>l.decision));if(e.handlers){let l={environmentKind:e.environmentKind,...e.policy};for(let u of n){let p=Gc(u.decision,l);if(p.apply.length===0&&p.release.length===0&&p.withheld.length===0)continue;o.push(await qc(this.store,u.budget,u.decision,p,e.handlers))}}return{organizationId:e.organizationId,statuses:n,level:a.level,actions:a.actions,releases:a.releases,enforcement:o,anomalies:this.detectAnomalies(e,t),evaluatedAt:t.toISOString()}}trackBreach(e,t,r){if(!t.breaches.some((o)=>o.actions.some((a)=>a!=="notify"))){this.breaching.delete(e.id);return}if(!this.breaching.has(e.id))this.breaching.set(e.id,r.toISOString())}detectAnomalies(e,t=new Date,r={}){let n=new Date(Math.floor(t.getTime()/3600000)*3600000).toISOString(),o={organizationId:e.organizationId,projectId:e.projectId,environmentId:e.environmentId},a=e.signals??Dr.map((p)=>p.key),l=[],u;for(let p of a){let E=r.seasonLength?Math.max(336,r.seasonLength*((r.minHistory??3)+1)):Kc(p),g={from:new Date(new Date(n).getTime()-E*3600000).toISOString(),to:n};if(l.push(...this.detectSignal(p,o,g,r)),!e.routes)continue;if(!Qs(p)?.routeAware)continue;u??=this.signals.busiestRoutes(o,g);for(let m of u){if(this.anomalyConfigs.isSilenced(o,{signal:p,route:m}))continue;l.push(...this.detectSignal(p,{...o,route:m},g,r,m))}}return this.signals.resetCache(),l}detectSignal(e,t,r,n,o){let a=this.anomalyConfigs.optionsFor(t,e);if(!a.enabled)return[];if(!o&&this.anomalyConfigs.isSilenced(t,{signal:e}))return[];let l=this.signals.series(e,t,r);if(l.points.length===0)return[];let u=zc(l.points,{...Gs(e),...a.options,...n});if(!u)return[];let p=this.store.recordAnomaly({organizationId:t.organizationId,projectId:t.projectId,environmentId:t.environmentId,signal:o?`${e}@${o}`:e,direction:u.direction,observed:u.observed,expected:u.expected,score:u.score,deltaPercent:Number.isFinite(u.deltaPercent)?u.deltaPercent:0,severity:a.config?.severity??u.severity,bucketStart:u.bucketStart,evidence:{historySize:u.historySize,deviation:u.deviation,unit:l.unit,populatedBuckets:l.populated,suppressedBuckets:l.suppressed,route:o??null,lookbackFrom:r.from,lookbackTo:r.to}});return p?[p]:[]}usageReport(e){let t=e.now??new Date,r=ct(e.period??"monthly",e.timezone??"UTC",t),n=this.store.summarizeUsage({organizationId:e.organizationId,projectId:e.projectId,environmentId:e.environmentId,from:r.start,to:r.end}),o=this.store.budgetsForScope(e.organizationId,e.projectId,e.environmentId).map((l)=>{let u=this.status(l,t),p=oi(l);return{id:l.id,name:l.name,period:l.period,limitCents:p,softLimitCents:l.softLimitCents,hardLimitCents:l.hardLimitCents,spentCents:u.decision.projection.actualCents,remainingCents:p==null?null:Math.max(0,p-u.decision.projection.actualCents),usedPercent:u.decision.usedPercent,projectedCents:u.decision.projection.projectedCents,projectedPercent:u.decision.projectedPercent,projectionConfidence:u.decision.projection.confidence,level:u.decision.level,timeToCap:u.timeToCap,activeActions:u.activeActions,dryRun:l.dryRun}}),a=this.store.listEnforcements({organizationId:e.organizationId,activeOnly:!0});return{organizationId:e.organizationId,projectId:e.projectId??null,environmentId:e.environmentId??null,window:{start:r.start,end:r.end,label:r.label},currency:this.store.priceBook.currency,totalCents:n.totalCents,byMeter:n.byMeter,series:n.series,budgets:o,enforcement:{strongestAction:Vc(a)??null,active:a.map((l)=>({id:l.id,budgetId:l.budgetId,action:l.action,state:l.state,reason:l.reason,simulated:l.simulated,appliedAt:l.appliedAt}))},generatedAt:t.toISOString(),currentBucket:wr(t)}}}function sf(e,t,r,n=1440){let o=new Map(e.map((p)=>[p.bucketStart,p.value])),a=Math.floor(new Date(t).getTime()/3600000)*3600000,l=new Date(r).getTime(),u=[];for(let p=a;p<l&&u.length<n;p+=3600000){let E=new Date(p).toISOString();u.push({bucketStart:E,value:o.get(E)??0})}return u}var Jc="spend.gates",un={build:["block_builds","suspend_project"],deploy:["block_deployments","suspend_project"],function_invoke:["suspend_functions","serve_static","suspend_project"],request:["suspend_project"]};function De(e){return`${e.budgetId}:${e.action}`}function pn(e,t){if(e.organizationId!==t.organizationId)return!1;if(e.projectId&&e.projectId!==t.projectId)return!1;if(e.environmentId&&e.environmentId!==t.environmentId)return!1;return!0}function En(e,t){if(e.organizationId!==t.organizationId)return!1;if(t.projectId&&e.projectId!==t.projectId)return!1;if(t.environmentId&&e.environmentId!==t.environmentId)return!1;return!0}function mn(e){let t={...e};for(let r of["projectId","environmentId"])if(t[r]==null)delete t[r];return t}class Pr{controlPlane;options;constructor(e,t={}){this.controlPlane=e;this.options=t}read(){let e=this.controlPlane.getSetting(Jc);return Array.isArray(e)?e:[]}write(e){this.controlPlane.setSetting(Jc,e)}list(e){return this.read().filter((t)=>!e||pn(t,e)).sort((t,r)=>R[r.action]-R[t.action])}listUnder(e){return this.read().filter((t)=>En(t,e)).sort((t,r)=>R[r.action]-R[t.action])}open(e){let t=e.appliedAt??(this.options.now?.()??new Date).toISOString(),r=mn({...e,appliedAt:t}),n=this.read().filter((o)=>De(o)!==De(r));return n.push(r),this.write(n),r}close(e,t){let r=this.read(),n=r.filter((o)=>De(o)!==De({budgetId:e,action:t}));if(n.length===r.length)return!1;return this.write(n),!0}closeBudget(e){let t=this.read(),r=t.filter((n)=>n.budgetId!==e);return this.write(r),t.length-r.length}check(e,t){let r=un[e]??[];for(let n of this.list(t)){if(n.simulated)continue;if(!r.includes(n.action))continue;return{allowed:!1,action:n.action,budgetId:n.budgetId,reason:`${n.reason} ${ai[n.action]}`}}return{allowed:!0}}strongest(e){return this.list(e).find((t)=>!t.simulated)?.action}}class Xc extends Error{operation;verdict;code="spend_cap_exceeded";status=402;constructor(e,t){super(t.reason??`A spend cap is blocking this ${e}.`);this.operation=e;this.verdict=t}}function of(e,t,r){let n=e.check(t,r);if(!n.allowed)throw new Xc(t,n)}var Ft=["notify","block_builds","block_deployments"];function Yc(e){let t=e.throttleFactor??0.5;return{apply:async(o,a)=>{let{budget:l,record:u,decision:p}=a;e.gate.open({budgetId:l.id,action:o,organizationId:l.organizationId,projectId:l.projectId,environmentId:l.environmentId,reason:p.reason,simulated:u.simulated});let E={gated:!0};if(!u.simulated&&!Ft.includes(o)){let g={projectId:l.projectId,environmentId:l.environmentId},m=e.transport;if(o==="throttle_requests"&&m?.throttleRequests)E={...await m.throttleRequests({...g,factor:t}),gated:!0};else if(o==="suspend_functions"&&m?.suspendFunctions)E={...await m.suspendFunctions(g),gated:!0};else if(o==="serve_static"&&m?.serveStatic)E={...await m.serveStatic(g),gated:!0};else if(o==="suspend_project"&&m?.suspendProject)E={...await m.suspendProject(g),gated:!0};else E={gated:!0,unsupported:!0}}return await e.notify?.({action:o,budgetId:l.id,reason:p.reason,simulated:u.simulated,released:!1}),E},release:async(o,a)=>{let{budget:l,record:u,restore:p}=a,E=e.transport;if(!u.simulated&&!Ft.includes(o)&&p.unsupported!==!0){if(o==="throttle_requests"&&E?.restoreRequests)await E.restoreRequests(p);else if(o==="suspend_functions"&&E?.resumeFunctions)await E.resumeFunctions(p);else if(o==="serve_static"&&E?.restoreDynamic)await E.restoreDynamic(p);else if(o==="suspend_project"&&E?.resumeProject)await E.resumeProject(p)}e.gate.close(l.id,o),await e.notify?.({action:o,budgetId:l.id,reason:u.reason,simulated:u.simulated,released:!0})}}}class bp{calls=[];record(e,t){return this.calls.push({method:e,input:t}),{recorded:e}}throttleRequests(e){return this.record("throttleRequests",e)}restoreRequests(e){this.record("restoreRequests",e)}suspendFunctions(e){return this.record("suspendFunctions",e)}resumeFunctions(e){this.record("resumeFunctions",e)}serveStatic(e){return this.record("serveStatic",e)}restoreDynamic(e){this.record("restoreDynamic",e)}suspendProject(e){return this.record("suspendProject",e)}resumeProject(e){this.record("resumeProject",e)}}import{createCipheriv as Tn,createDecipheriv as gn,createHash as Yt,randomBytes as _n}from"node:crypto";var M=(e)=>{if(typeof e!=="string")return{};try{return JSON.parse(e)}catch{return{}}},A=(e)=>typeof e==="string"?e:void 0,nt=(e)=>Number(e)===1,V=(e,t,r,n)=>{let o=Number(e);return Number.isFinite(o)?Math.min(n,Math.max(r,Math.floor(o))):t},zt=(e)=>Yt("sha256").update(e).digest("hex").slice(0,16);function qt(e){return{id:String(e.id),projectId:String(e.project_id),environmentId:A(e.environment_id),resourceId:A(e.resource_id),name:String(e.name),kind:String(e.kind),target:String(e.target),config:M(e.config),intervalSeconds:Number(e.interval_seconds),timeoutSeconds:Number(e.timeout_seconds),failureThreshold:Number(e.failure_threshold),recoveryThreshold:Number(e.recovery_threshold),regions:M(e.regions),enabled:nt(e.enabled),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Ht(e){return{id:String(e.id),checkId:String(e.check_id),status:String(e.status),agent:String(e.agent),region:A(e.region),statusCode:e.status_code==null?void 0:Number(e.status_code),message:A(e.message),timings:M(e.timings),checkedAt:String(e.checked_at)}}function Vt(e){return{id:String(e.id),projectId:String(e.project_id),environmentId:A(e.environment_id),resourceId:A(e.resource_id),healthCheckId:A(e.health_check_id),name:String(e.name),signal:String(e.signal),operator:String(e.operator),threshold:e.threshold==null?void 0:Number(e.threshold),recoveryThreshold:e.recovery_threshold==null?void 0:Number(e.recovery_threshold),windowMs:Number(e.window_ms),consecutive:Number(e.consecutive),recoveryConsecutive:Number(e.recovery_consecutive),noDataPolicy:String(e.no_data_policy),severity:String(e.severity),groupBy:M(e.group_by),labels:M(e.labels),enabled:nt(e.enabled),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function tt(e){return{id:String(e.id),ruleId:String(e.rule_id),projectId:String(e.project_id),environmentId:A(e.environment_id),resourceId:A(e.resource_id),dedupKey:String(e.dedup_key),groupKey:String(e.group_key),state:String(e.state),severity:String(e.severity),title:String(e.title),evidence:M(e.evidence),failureCount:Number(e.failure_count),recoveryCount:Number(e.recovery_count),occurrenceCount:Number(e.occurrence_count),ownerActorId:A(e.owner_actor_id),acknowledgedByActorId:A(e.acknowledged_by_actor_id),acknowledgedAt:A(e.acknowledged_at),firstSeenAt:String(e.first_seen_at),lastSeenAt:String(e.last_seen_at),firingAt:A(e.firing_at),resolvedAt:A(e.resolved_at),silencedUntil:A(e.silenced_until),updatedAt:String(e.updated_at)}}function Kt(e){return{id:String(e.id),organizationId:String(e.organization_id),name:String(e.name),kind:String(e.kind),config:M(e.config),credentialFingerprint:A(e.credential_fingerprint),hasCredential:!!e.credential_ciphertext,status:String(e.status),version:Number(e.version),lastTestedAt:A(e.last_tested_at),lastError:A(e.last_error),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Qt(e){return{id:String(e.id),organizationId:String(e.organization_id),name:String(e.name),priority:Number(e.priority),matcher:M(e.matcher),channelIds:M(e.channel_ids),quietHours:e.quiet_hours?M(e.quiet_hours):void 0,groupWaitSeconds:Number(e.group_wait_seconds),reminderSeconds:e.reminder_seconds==null?void 0:Number(e.reminder_seconds),escalation:M(e.escalation),template:A(e.template),rateLimitPerMinute:Number(e.rate_limit_per_minute),enabled:nt(e.enabled),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function rt(e){return{id:String(e.id),alertId:A(e.alert_id),channelId:String(e.channel_id),routeId:A(e.route_id),eventType:String(e.event_type),idempotencyKey:String(e.idempotency_key),state:String(e.state),attempt:Number(e.attempt),maxAttempts:Number(e.max_attempts),nextAttemptAt:A(e.next_attempt_at),responseStatus:e.response_status==null?void 0:Number(e.response_status),error:A(e.error),payload:M(e.payload),createdAt:String(e.created_at),updatedAt:String(e.updated_at),deliveredAt:A(e.delivered_at)}}class di{controlPlane;options;key;constructor(e,t){this.controlPlane=e;this.options=t;this.key=Yt("sha256").update(t.encryptionKey).digest()}now(){return(this.options.now?.()??new Date).toISOString()}encrypt(e){let t=_n(12),r=Tn("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]=e.split("."),o=gn("aes-256-gcm",this.key,Buffer.from(t,"base64url"));return o.setAuthTag(Buffer.from(r,"base64url")),Buffer.concat([o.update(Buffer.from(n,"base64url")),o.final()]).toString("utf8")}createHealthCheck(e){if(!e.name.trim())throw Error("Health checks require a name.");if(!["http","tcp","command"].includes(e.kind))throw Error("Unsupported health check kind.");if(e.kind==="http"&&!/^https?:\/\//.test(e.target)||e.kind==="tcp"&&!/^[a-zA-Z0-9.-]+$/.test(e.target)||e.kind==="command"&&!e.config.command?.length)throw Error("Health check target is invalid.");let t=crypto.randomUUID(),r=this.now();return this.controlPlane.database.run("INSERT INTO health_checks (id,project_id,environment_id,resource_id,name,kind,target,config,interval_seconds,timeout_seconds,failure_threshold,recovery_threshold,regions,enabled,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.projectId,e.environmentId??null,e.resourceId??null,e.name.trim().slice(0,100),e.kind,e.target,JSON.stringify(e.config),V(e.intervalSeconds,60,10,86400),V(e.timeoutSeconds,10,1,300),V(e.failureThreshold,3,1,100),V(e.recoveryThreshold,2,1,100),JSON.stringify(e.regions.slice(0,20)),e.enabled?1:0,1,r,r]),this.getHealthCheck(t)}getHealthCheck(e){let t=this.controlPlane.database.query("SELECT * FROM health_checks WHERE id=?").get(e);return t?qt(t):void 0}listHealthChecks(e,t){return this.controlPlane.database.query(`SELECT * FROM health_checks WHERE project_id=?${t?" AND environment_id=?":""} ORDER BY updated_at DESC`).all(e,...t?[t]:[]).map(qt)}setHealthCheckEnabled(e,t){this.controlPlane.database.run("UPDATE health_checks SET enabled=?,version=version+1,updated_at=? WHERE id=?",[t?1:0,this.now(),e]);let r=this.getHealthCheck(e);if(!r)throw Error("Health check was not found.");return r}appendHealthResult(e){let t=crypto.randomUUID();return this.controlPlane.database.run("INSERT INTO health_results (id,check_id,status,agent,region,status_code,message,timings,checked_at) VALUES (?,?,?,?,?,?,?,?,?)",[t,e.checkId,e.status,e.agent.slice(0,100),e.region??null,e.statusCode??null,e.message?.slice(0,1000)??null,JSON.stringify(e.timings),e.checkedAt]),Ht(this.controlPlane.database.query("SELECT * FROM health_results WHERE id=?").get(t))}listHealthResults(e,t=100){return this.controlPlane.database.query("SELECT * FROM health_results WHERE check_id=? ORDER BY checked_at DESC LIMIT ?").all(e,Math.min(1000,Math.max(1,t))).map(Ht)}createRule(e){if(!e.name.trim())throw Error("Alert rules require a name.");if(e.operator!=="unhealthy"&&e.threshold==null)throw Error("Metric alert rules require a threshold.");let t=crypto.randomUUID(),r=this.now();return this.controlPlane.database.run("INSERT INTO alert_rules (id,project_id,environment_id,resource_id,health_check_id,name,signal,operator,threshold,recovery_threshold,window_ms,consecutive,recovery_consecutive,no_data_policy,severity,group_by,labels,enabled,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.projectId,e.environmentId??null,e.resourceId??null,e.healthCheckId??null,e.name.trim().slice(0,120),e.signal,e.operator,e.threshold??null,e.recoveryThreshold??null,V(e.windowMs,300000,1e4,2678400000),V(e.consecutive,3,1,100),V(e.recoveryConsecutive,2,1,100),e.noDataPolicy,e.severity,JSON.stringify(e.groupBy.slice(0,20)),JSON.stringify(e.labels),e.enabled?1:0,1,r,r]),this.getRule(t)}getRule(e){let t=this.controlPlane.database.query("SELECT * FROM alert_rules WHERE id=?").get(e);return t?Vt(t):void 0}listRules(e,t){return this.controlPlane.database.query(`SELECT * FROM alert_rules WHERE project_id=?${t?" AND environment_id=?":""} ORDER BY updated_at DESC`).all(e,...t?[t]:[]).map(Vt)}setRuleEnabled(e,t){this.controlPlane.database.run("UPDATE alert_rules SET enabled=?,version=version+1,updated_at=? WHERE id=?",[t?1:0,this.now(),e]);let r=this.getRule(e);if(!r)throw Error("Alert rule was not found.");return r}getAlertByDedup(e){let t=this.controlPlane.database.query("SELECT * FROM alerts WHERE dedup_key=?").get(e);return t?tt(t):void 0}getAlert(e){let t=this.controlPlane.database.query("SELECT * FROM alerts WHERE id=?").get(e);return t?tt(t):void 0}listAlerts(e,t={}){let r=["project_id=?"],n=[e];if(t.environmentId)r.push("environment_id=?"),n.push(t.environmentId);if(t.states?.length)r.push(`state IN (${t.states.map(()=>"?").join(",")})`),n.push(...t.states);return this.controlPlane.database.query(`SELECT * FROM alerts WHERE ${r.join(" AND ")} ORDER BY updated_at DESC LIMIT ?`).all(...n,Math.min(1000,t.limit??200)).map(tt)}saveAlert(e,t,r){return this.controlPlane.database.run("INSERT INTO alerts (id,rule_id,project_id,environment_id,resource_id,dedup_key,group_key,state,severity,title,evidence,failure_count,recovery_count,occurrence_count,owner_actor_id,acknowledged_by_actor_id,acknowledged_at,first_seen_at,last_seen_at,firing_at,resolved_at,silenced_until,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET state=excluded.state,severity=excluded.severity,title=excluded.title,evidence=excluded.evidence,failure_count=excluded.failure_count,recovery_count=excluded.recovery_count,occurrence_count=excluded.occurrence_count,owner_actor_id=excluded.owner_actor_id,acknowledged_by_actor_id=excluded.acknowledged_by_actor_id,acknowledged_at=excluded.acknowledged_at,last_seen_at=excluded.last_seen_at,firing_at=excluded.firing_at,resolved_at=excluded.resolved_at,silenced_until=excluded.silenced_until,updated_at=excluded.updated_at",[e.id,e.ruleId,e.projectId,e.environmentId??null,e.resourceId??null,e.dedupKey,e.groupKey,e.state,e.severity,e.title,JSON.stringify(e.evidence),e.failureCount,e.recoveryCount,e.occurrenceCount,e.ownerActorId??null,e.acknowledgedByActorId??null,e.acknowledgedAt??null,e.firstSeenAt,e.lastSeenAt,e.firingAt??null,e.resolvedAt??null,e.silencedUntil??null,e.updatedAt]),this.controlPlane.database.run("INSERT INTO alert_events (id,alert_id,type,actor_id,payload,created_at) VALUES (?,?,?,?,?,?)",[crypto.randomUUID(),e.id,t,r??null,JSON.stringify({state:e.state,severity:e.severity,evidence:e.evidence}),e.updatedAt]),this.getAlert(e.id)}acknowledge(e,t){let r=this.getAlert(e);if(!r)throw Error("Alert was not found.");let n=this.now();return this.saveAlert({...r,acknowledgedByActorId:t,acknowledgedAt:n,updatedAt:n},"acknowledged",t)}assign(e,t,r){let n=this.getAlert(e);if(!n)throw Error("Alert was not found.");let o=this.now();return this.saveAlert({...n,ownerActorId:t,updatedAt:o},"assigned",r)}silenceAlert(e,t,r){let n=this.getAlert(e);if(!n)throw Error("Alert was not found.");let o=new Date(t);if(!Number.isFinite(o.getTime())||o<=new Date)throw Error("Silence end must be in the future.");let a=this.now();return this.saveAlert({...n,state:"silenced",silencedUntil:o.toISOString(),updatedAt:a},"silenced",r)}createSilence(e){let t=new Date(e.startsAt),r=new Date(e.endsAt);if(!Number.isFinite(t.getTime())||!Number.isFinite(r.getTime())||t>=r)throw Error("Silence window is invalid.");try{new Intl.DateTimeFormat("en",{timeZone:e.timezone}).format(t)}catch{throw Error("Silence timezone is invalid.")}let n=crypto.randomUUID();return this.controlPlane.database.run("INSERT INTO alert_silences (id,project_id,environment_id,resource_id,matcher,reason,starts_at,ends_at,timezone,created_by_actor_id,created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?)",[n,e.projectId,e.environmentId??null,e.resourceId??null,JSON.stringify(e.matcher??{}),e.reason.slice(0,500),t.toISOString(),r.toISOString(),e.timezone,e.actorId??null,this.now()]),n}isSilenced(e,t,r){return this.controlPlane.database.query("SELECT * FROM alert_silences WHERE project_id=? AND starts_at<=? AND ends_at>?").all(e.projectId,r,r).some((o)=>{if(o.environment_id&&o.environment_id!==e.environmentId)return!1;if(o.resource_id&&o.resource_id!==e.resourceId)return!1;let a=M(o.matcher);return Object.entries(a).every(([l,u])=>t[l]===u)})}createChannel(e){if(!e.name.trim())throw Error("Notification channels require a name.");let t=crypto.randomUUID(),r=this.now(),n=e.credential?.trim();return this.controlPlane.database.run("INSERT INTO notification_channels (id,organization_id,name,kind,config,credential_ciphertext,credential_fingerprint,status,version,created_by_actor_id,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.organizationId,e.name.trim().slice(0,100),e.kind,JSON.stringify(e.config??{}),n?this.encrypt(n):null,n?zt(n):null,"active",1,e.actorId??null,r,r]),this.getChannel(t)}getChannel(e){let t=this.controlPlane.database.query("SELECT * FROM notification_channels WHERE id=?").get(e);return t?Kt(t):void 0}channelCredential(e){let t=this.controlPlane.database.query("SELECT credential_ciphertext FROM notification_channels WHERE id=?").get(e);return t?.credential_ciphertext?this.decrypt(String(t.credential_ciphertext)):void 0}listChannels(e){return this.controlPlane.database.query("SELECT * FROM notification_channels WHERE organization_id=? ORDER BY updated_at DESC").all(e).map(Kt)}rotateChannel(e,t){let r=this.now();this.controlPlane.database.run("UPDATE notification_channels SET credential_ciphertext=?,credential_fingerprint=?,status='active',last_error=NULL,version=version+1,updated_at=? WHERE id=?",[this.encrypt(t),zt(t),r,e]);let n=this.getChannel(e);if(!n)throw Error("Notification channel was not found.");return n}setChannelStatus(e,t,r){this.controlPlane.database.run("UPDATE notification_channels SET status=?,last_error=?,updated_at=? WHERE id=?",[t,r?.slice(0,1000)??null,this.now(),e]);let n=this.getChannel(e);if(!n)throw Error("Notification channel was not found.");return n}markChannelTest(e,t,r){let n=this.now();return this.controlPlane.database.run("UPDATE notification_channels SET status=?,last_tested_at=?,last_error=?,updated_at=? WHERE id=?",[t?"active":"failing",n,r?.slice(0,1000)??null,n,e]),this.getChannel(e)}createRoute(e){let t=crypto.randomUUID(),r=this.now();return this.controlPlane.database.run("INSERT INTO notification_routes (id,organization_id,name,priority,matcher,channel_ids,quiet_hours,group_wait_seconds,reminder_seconds,escalation,template,rate_limit_per_minute,enabled,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.organizationId,e.name.trim().slice(0,100),e.priority,JSON.stringify(e.matcher),JSON.stringify(e.channelIds),e.quietHours?JSON.stringify(e.quietHours):null,V(e.groupWaitSeconds,30,0,86400),e.reminderSeconds??null,JSON.stringify(e.escalation),e.template?.trim().slice(0,2000)??null,V(e.rateLimitPerMinute,60,1,1e4),e.enabled?1:0,1,r,r]),this.getRoute(t)}getRoute(e){let t=this.controlPlane.database.query("SELECT * FROM notification_routes WHERE id=?").get(e);return t?Qt(t):void 0}listRoutes(e){return this.controlPlane.database.query("SELECT * FROM notification_routes WHERE organization_id=? ORDER BY priority DESC,created_at ASC").all(e).map(Qt)}countRouteDeliveries(e,t){return Number(this.controlPlane.database.query("SELECT COUNT(*) count FROM notification_deliveries WHERE route_id=? AND created_at>=?").get(e,t)?.count??0)}setRouteEnabled(e,t){this.controlPlane.database.run("UPDATE notification_routes SET enabled=?,version=version+1,updated_at=? WHERE id=?",[t?1:0,this.now(),e]);let r=this.getRoute(e);if(!r)throw Error("Notification route was not found.");return r}createDelivery(e){let t=this.controlPlane.database.query("SELECT * FROM notification_deliveries WHERE idempotency_key=?").get(e.idempotencyKey);if(t)return rt(t);let r=crypto.randomUUID(),n=this.now();return this.controlPlane.database.run("INSERT INTO notification_deliveries (id,alert_id,channel_id,route_id,event_type,idempotency_key,state,attempt,max_attempts,next_attempt_at,payload,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",[r,e.alertId??null,e.channelId,e.routeId??null,e.eventType,e.idempotencyKey,"pending",0,V(e.maxAttempts,3,1,10),e.nextAttemptAt??null,JSON.stringify(e.payload),n,n]),this.getDelivery(r)}getDelivery(e){let t=this.controlPlane.database.query("SELECT * FROM notification_deliveries WHERE id=?").get(e);return t?rt(t):void 0}listDeliveries(e={}){let t=[],r=[];if(e.alertId)t.push("alert_id=?"),r.push(e.alertId);if(e.states?.length)t.push(`state IN (${e.states.map(()=>"?").join(",")})`),r.push(...e.states);return this.controlPlane.database.query(`SELECT * FROM notification_deliveries${t.length?" WHERE "+t.join(" AND "):""} ORDER BY updated_at DESC LIMIT ?`).all(...r,Math.min(1000,e.limit??200)).map(rt)}updateDelivery(e,t){return this.controlPlane.database.run("UPDATE notification_deliveries SET state=?,attempt=?,next_attempt_at=?,response_status=?,error=?,delivered_at=?,updated_at=? WHERE id=?",[t.state,t.attempt,t.nextAttemptAt??null,t.responseStatus??null,t.error?.slice(0,1000)??null,t.deliveredAt??null,this.now(),e]),this.getDelivery(e)}}import{createHash as hn}from"node:crypto";function Nn(e,t,r){if(e==="gt")return t>r;if(e==="gte")return t>=r;if(e==="lt")return t<r;if(e==="lte")return t<=r;return t===r}function fn(e,t,r){if(t.status==="no_data"||t.status==null&&t.value==null)return;if(e.operator==="unhealthy")return t.status==="unhealthy";if(t.value==null||e.threshold==null)return;return Nn(e.operator,t.value,r&&e.recoveryThreshold!=null?e.recoveryThreshold:e.threshold)}function yn(e,t){let r=Object.fromEntries(e.groupBy.flatMap((o)=>t.group?.[o]==null?[]:[[o,String(t.group[o])]]));return{key:Object.entries(r).sort(([o],[a])=>o.localeCompare(a)).map(([o,a])=>`${o}=${a}`).join(",")||"default",values:r}}function Ln(e,t){return hn("sha256").update(`${e}\x00${t}`).digest("hex")}class Nr{store;constructor(e){this.store=e}evaluate(e,t){if(!e.enabled)return{transition:"ignored",notify:!1};let r=yn(e,t),n=Ln(e.id,r.key),o=this.store.getAlertByDedup(n),a=o?.state==="firing"||o?.state==="silenced",l=fn(e,t,a);if(l==null&&e.noDataPolicy==="ignore")return{alert:o,transition:"ignored",notify:!1};let u=l??e.noDataPolicy==="firing",p=l==null&&e.noDataPolicy==="pending",E=new Date(t.timestamp).toISOString(),g=s({...t.evidence??{},...t.value==null?{}:{value:t.value},...t.status?{healthStatus:t.status}:{},group:r.values}),m;if(!o){let f=u||p?1:0,L=u&&f>=e.consecutive?"firing":"pending";m={id:crypto.randomUUID(),ruleId:e.id,projectId:e.projectId,environmentId:e.environmentId,resourceId:e.resourceId,dedupKey:n,groupKey:r.key,state:L,severity:e.severity,title:e.name,evidence:g,failureCount:f,recoveryCount:0,occurrenceCount:1,firstSeenAt:E,lastSeenAt:E,firingAt:L==="firing"?E:void 0,updatedAt:E}}else if(u||p){let f=o.state==="resolved",L=(f?0:o.failureCount)+1,v=o.silencedUntil&&new Date(o.silencedUntil)>new Date(E),I=p?"pending":L>=e.consecutive?"firing":"pending";if((v||this.store.isSilenced(e,r.values,E))&&I==="firing")I="silenced";m={...o,state:I,severity:e.severity,title:e.name,evidence:g,failureCount:L,recoveryCount:0,occurrenceCount:o.occurrenceCount+1,firstSeenAt:f?E:o.firstSeenAt,lastSeenAt:E,firingAt:I==="firing"||I==="silenced"?o.firingAt??E:void 0,resolvedAt:void 0,updatedAt:E}}else{let f=o.recoveryCount+1,L=f>=e.recoveryConsecutive;m={...o,state:L?"resolved":o.state,evidence:g,failureCount:L?0:o.failureCount,recoveryCount:f,lastSeenAt:E,resolvedAt:L?E:o.resolvedAt,silencedUntil:L?void 0:o.silencedUntil,updatedAt:E}}let T=o?.state!==m.state,N=m.state==="pending"?"pending":m.state==="firing"?T?"firing":"updated":m.state==="silenced"?"silenced":T?"resolved":"updated";return{alert:this.store.saveAlert(m,T||!o?N:"observed"),transition:N,notify:N==="firing"||N==="resolved"}}}import{createHmac as vn}from"node:crypto";function In(e,t){let r=Object.fromEntries(new Intl.DateTimeFormat("en-US",{timeZone:t,weekday:"short",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).formatToParts(e).map((o)=>[o.type,o.value])),n=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];return{minute:Number(r.hour)*60+Number(r.minute),weekday:n.indexOf(r.weekday)}}function Gt(e){let t=/^(\d{2}):(\d{2})$/.exec(e);if(!t)throw Error("Quiet hours require HH:MM times.");let r=Number(t[1])*60+Number(t[2]);if(Number(t[1])>23||Number(t[2])>59)throw Error("Quiet hours require valid HH:MM times.");return r}function Vs(e,t){if(!e.quietHours)return!1;let r=In(t,e.quietHours.timezone),n=Gt(e.quietHours.start),o=Gt(e.quietHours.end);if(e.quietHours.weekdays?.length&&!e.quietHours.weekdays.includes(r.weekday))return!1;return n<=o?r.minute>=n&&r.minute<o:r.minute>=n||r.minute<o}function Sn(e,t,r){let n=e.matcher;return(!n.projectIds?.length||n.projectIds.includes(t.projectId))&&(!n.environmentIds?.length||!!t.environmentId&&n.environmentIds.includes(t.environmentId))&&(!n.resourceIds?.length||!!t.resourceId&&n.resourceIds.includes(t.resourceId))&&(!n.severities?.length||n.severities.includes(t.severity))&&(!n.eventTypes?.length||n.eventTypes.includes(r))}function bn(e){if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t==="object"?t:{value:e}}catch{return{value:e}}}function Rn(e,t,r){let n={severity:e.severity.toUpperCase(),title:e.title,state:e.state,event:t,projectId:e.projectId,environmentId:e.environmentId??"",resourceId:e.resourceId??"",groupKey:e.groupKey};return(r?.trim()||"[{{severity}}] {{title}} · {{state}}").replace(/\{\{(severity|title|state|event|projectId|environmentId|resourceId|groupKey)\}\}/g,(o,a)=>n[a]).slice(0,2000)}function it(e,t,r){return{schemaVersion:1,event:t,notificationText:Rn(e,t,r),alert:{id:e.id,state:e.state,severity:e.severity,title:e.title,projectId:e.projectId,environmentId:e.environmentId??null,resourceId:e.resourceId??null,groupKey:e.groupKey,firstSeenAt:e.firstSeenAt,lastSeenAt:e.lastSeenAt,firingAt:e.firingAt??null,resolvedAt:e.resolvedAt??null,evidence:e.evidence}}}class li{store;options;fetchImpl;constructor(e,t={}){this.store=e;this.options=t;this.fetchImpl=t.fetchImpl??globalThis.fetch}now(){return this.options.now?.()??new Date}preview(e,t,r){let n=[];for(let o of this.store.listRoutes(e)){if(!o.enabled||!Sn(o,t,r))continue;let a=[];for(let l of o.channelIds){let u=this.store.getChannel(l);if(u?.status==="active")a.push(u)}n.push({route:o,channels:a,quiet:Vs(o,this.now())})}return n}enqueue(e,t,r){let n=r==="resolved"?t.resolvedAt:r==="firing"?t.firingAt:t.updatedAt,o=[];for(let a of this.preview(e,t,r)){if(a.quiet&&r!=="resolved")continue;let l=r==="resolved"||a.route.groupWaitSeconds===0?void 0:new Date(this.now().getTime()+a.route.groupWaitSeconds*1000).toISOString(),u=r==="resolved"?Number.POSITIVE_INFINITY:Math.max(0,a.route.rateLimitPerMinute-this.store.countRouteDeliveries(a.route.id,new Date(this.now().getTime()-60000).toISOString()));for(let p of a.channels){if(u<=0)break;o.push(this.store.createDelivery({alertId:t.id,channelId:p.id,routeId:a.route.id,eventType:r,idempotencyKey:`${t.id}:${r}:${n}:${p.id}`,payload:it(t,r,a.route.template),nextAttemptAt:l})),u--}}return o}enqueueRemindersAndEscalations(e,t){let r=this.now(),n=[];for(let o of t.filter((a)=>a.state==="firing"&&!a.acknowledgedAt&&a.firingAt)){let a=Math.max(0,(r.getTime()-new Date(o.firingAt).getTime())/1000);for(let l of this.preview(e,o,"reminder")){if(l.quiet)continue;if(l.route.reminderSeconds&&a>=l.route.reminderSeconds){let u=Math.floor(a/l.route.reminderSeconds);for(let p of l.channels)n.push(this.store.createDelivery({alertId:o.id,channelId:p.id,routeId:l.route.id,eventType:"reminder",idempotencyKey:`${o.id}:reminder:${l.route.id}:${u}:${p.id}`,payload:it(o,"reminder")}))}for(let[u,p]of l.route.escalation.entries())if(a>=p.afterSeconds){for(let E of p.channelIds)if(this.store.getChannel(E)?.status==="active")n.push(this.store.createDelivery({alertId:o.id,channelId:E,routeId:l.route.id,eventType:"escalation",idempotencyKey:`${o.id}:escalation:${l.route.id}:${u}:${E}`,payload:it(o,"escalation")}))}}}return n}async send(e,t){let r=bn(this.store.channelCredential(e.id)),n=typeof t.notificationText==="string"?t.notificationText:`[${String(t.alert?.severity??"info").toUpperCase()}] ${String(t.alert?.title??"ts-cloud alert")} · ${String(t.alert?.state??t.event)}`;try{if(e.kind==="email"){if(!this.options.emailImpl)return{ok:!1,error:"Email adapter is not configured."};return await this.options.emailImpl({to:e.config.to,from:e.config.from,subject:`[ts-cloud] ${String(t.alert?.title??t.event)}`,text:`${n}
|
|
1540
|
+
`:"")}function*uf(e,t=500){for(let r=0;r<e.length;r+=t)yield js(e.slice(r,r+t))}class $t{store;counters=new Fs;breaching=new Map;anomalyConfigs;signals;constructor(e){this.store=e;this.anomalyConfigs=new Hs(e.controlPlane),this.signals=new qs(e.controlPlane,e)}ingestTelemetry(e,t,r){let n=Uc(e,t,{counters:this.counters,defaultProvider:r});return this.store.ingestUsage(n)}ingestUsage(e,t=!0){return this.store.ingestUsage(t?Qc(e):[...e])}status(e,t=new Date){let{window:r,summary:n}=this.store.budgetSpendCents(e,t),a=this.store.listEnforcements({organizationId:e.organizationId,budgetId:e.id,activeOnly:!0}).filter((u)=>u.state==="active").map((u)=>u.action),l=Gc({budget:e,window:r,actualCents:n.totalCents,series:n.series,activeActions:a,breachingSince:this.breaching.get(e.id),now:t});return{budget:e,decision:l,summary:n,activeActions:a,timeToCap:Rr(l.projection.timeToExhaustionMs)}}async runCycle(e){let t=e.now??new Date,r=this.store.budgetsForScope(e.organizationId,e.projectId,e.environmentId),n=[],o=[];for(let l of r){let u=this.status(l,t);this.trackBreach(l,u.decision,t),this.store.recordDecision(u.decision),n.push(u)}let a=qc(n.map((l)=>l.decision));if(e.handlers){let l={environmentKind:e.environmentKind,...e.policy};for(let u of n){let p=Vc(u.decision,l);if(p.apply.length===0&&p.release.length===0&&p.withheld.length===0)continue;o.push(await jc(this.store,u.budget,u.decision,p,e.handlers))}}return{organizationId:e.organizationId,statuses:n,level:a.level,actions:a.actions,releases:a.releases,enforcement:o,anomalies:this.detectAnomalies(e,t),evaluatedAt:t.toISOString()}}trackBreach(e,t,r){if(!t.breaches.some((o)=>o.actions.some((a)=>a!=="notify"))){this.breaching.delete(e.id);return}if(!this.breaching.has(e.id))this.breaching.set(e.id,r.toISOString())}detectAnomalies(e,t=new Date,r={}){let n=new Date(Math.floor(t.getTime()/3600000)*3600000).toISOString(),o={organizationId:e.organizationId,projectId:e.projectId,environmentId:e.environmentId},a=e.signals??Dr.map((p)=>p.key),l=[],u;for(let p of a){let E=r.seasonLength?Math.max(336,r.seasonLength*((r.minHistory??3)+1)):Jc(p),g={from:new Date(new Date(n).getTime()-E*3600000).toISOString(),to:n};if(l.push(...this.detectSignal(p,o,g,r)),!e.routes)continue;if(!Gs(p)?.routeAware)continue;u??=this.signals.busiestRoutes(o,g);for(let m of u){if(this.anomalyConfigs.isSilenced(o,{signal:p,route:m}))continue;l.push(...this.detectSignal(p,{...o,route:m},g,r,m))}}return this.signals.resetCache(),l}detectSignal(e,t,r,n,o){let a=this.anomalyConfigs.optionsFor(t,e);if(!a.enabled)return[];if(!o&&this.anomalyConfigs.isSilenced(t,{signal:e}))return[];let l=this.signals.series(e,t,r);if(l.points.length===0)return[];let u=Wc(l.points,{...Vs(e),...a.options,...n});if(!u)return[];let p=this.store.recordAnomaly({organizationId:t.organizationId,projectId:t.projectId,environmentId:t.environmentId,signal:o?`${e}@${o}`:e,direction:u.direction,observed:u.observed,expected:u.expected,score:u.score,deltaPercent:Number.isFinite(u.deltaPercent)?u.deltaPercent:0,severity:a.config?.severity??u.severity,bucketStart:u.bucketStart,evidence:{historySize:u.historySize,deviation:u.deviation,unit:l.unit,populatedBuckets:l.populated,suppressedBuckets:l.suppressed,route:o??null,lookbackFrom:r.from,lookbackTo:r.to}});return p?[p]:[]}usageReport(e){let t=e.now??new Date,r=ct(e.period??"monthly",e.timezone??"UTC",t),n=this.store.summarizeUsage({organizationId:e.organizationId,projectId:e.projectId,environmentId:e.environmentId,from:r.start,to:r.end}),o=this.store.budgetsForScope(e.organizationId,e.projectId,e.environmentId).map((l)=>{let u=this.status(l,t),p=ai(l);return{id:l.id,name:l.name,period:l.period,limitCents:p,softLimitCents:l.softLimitCents,hardLimitCents:l.hardLimitCents,spentCents:u.decision.projection.actualCents,remainingCents:p==null?null:Math.max(0,p-u.decision.projection.actualCents),usedPercent:u.decision.usedPercent,projectedCents:u.decision.projection.projectedCents,projectedPercent:u.decision.projectedPercent,projectionConfidence:u.decision.projection.confidence,level:u.decision.level,timeToCap:u.timeToCap,activeActions:u.activeActions,dryRun:l.dryRun}}),a=this.store.listEnforcements({organizationId:e.organizationId,activeOnly:!0});return{organizationId:e.organizationId,projectId:e.projectId??null,environmentId:e.environmentId??null,window:{start:r.start,end:r.end,label:r.label},currency:this.store.priceBook.currency,totalCents:n.totalCents,byMeter:n.byMeter,series:n.series,budgets:o,enforcement:{strongestAction:zc(a)??null,active:a.map((l)=>({id:l.id,budgetId:l.budgetId,action:l.action,state:l.state,reason:l.reason,simulated:l.simulated,appliedAt:l.appliedAt}))},generatedAt:t.toISOString(),currentBucket:wr(t)}}}function pf(e,t,r,n=1440){let o=new Map(e.map((p)=>[p.bucketStart,p.value])),a=Math.floor(new Date(t).getTime()/3600000)*3600000,l=new Date(r).getTime(),u=[];for(let p=a;p<l&&u.length<n;p+=3600000){let E=new Date(p).toISOString();u.push({bucketStart:E,value:o.get(E)??0})}return u}var Yc="spend.gates",un={build:["block_builds","suspend_project"],deploy:["block_deployments","suspend_project"],function_invoke:["suspend_functions","serve_static","suspend_project"],request:["suspend_project"]};function De(e){return`${e.budgetId}:${e.action}`}function pn(e,t){if(e.organizationId!==t.organizationId)return!1;if(e.projectId&&e.projectId!==t.projectId)return!1;if(e.environmentId&&e.environmentId!==t.environmentId)return!1;return!0}function En(e,t){if(e.organizationId!==t.organizationId)return!1;if(t.projectId&&e.projectId!==t.projectId)return!1;if(t.environmentId&&e.environmentId!==t.environmentId)return!1;return!0}function mn(e){let t={...e};for(let r of["projectId","environmentId"])if(t[r]==null)delete t[r];return t}class Pr{controlPlane;options;constructor(e,t={}){this.controlPlane=e;this.options=t}read(){let e=this.controlPlane.getSetting(Yc);return Array.isArray(e)?e:[]}write(e){this.controlPlane.setSetting(Yc,e)}list(e){return this.read().filter((t)=>!e||pn(t,e)).sort((t,r)=>R[r.action]-R[t.action])}listUnder(e){return this.read().filter((t)=>En(t,e)).sort((t,r)=>R[r.action]-R[t.action])}open(e){let t=e.appliedAt??(this.options.now?.()??new Date).toISOString(),r=mn({...e,appliedAt:t}),n=this.read().filter((o)=>De(o)!==De(r));return n.push(r),this.write(n),r}close(e,t){let r=this.read(),n=r.filter((o)=>De(o)!==De({budgetId:e,action:t}));if(n.length===r.length)return!1;return this.write(n),!0}closeBudget(e){let t=this.read(),r=t.filter((n)=>n.budgetId!==e);return this.write(r),t.length-r.length}check(e,t){let r=un[e]??[];for(let n of this.list(t)){if(n.simulated)continue;if(!r.includes(n.action))continue;return{allowed:!1,action:n.action,budgetId:n.budgetId,reason:`${n.reason} ${ci[n.action]}`}}return{allowed:!0}}strongest(e){return this.list(e).find((t)=>!t.simulated)?.action}}class Zc extends Error{operation;verdict;code="spend_cap_exceeded";status=402;constructor(e,t){super(t.reason??`A spend cap is blocking this ${e}.`);this.operation=e;this.verdict=t}}function gf(e,t,r){let n=e.check(t,r);if(!n.allowed)throw new Zc(t,n)}var Ft=["notify","block_builds","block_deployments"];function ed(e){let t=e.throttleFactor??0.5;return{apply:async(o,a)=>{let{budget:l,record:u,decision:p}=a;e.gate.open({budgetId:l.id,action:o,organizationId:l.organizationId,projectId:l.projectId,environmentId:l.environmentId,reason:p.reason,simulated:u.simulated});let E={gated:!0};if(!u.simulated&&!Ft.includes(o)){let g={projectId:l.projectId,environmentId:l.environmentId},m=e.transport;if(o==="throttle_requests"&&m?.throttleRequests)E={...await m.throttleRequests({...g,factor:t}),gated:!0};else if(o==="suspend_functions"&&m?.suspendFunctions)E={...await m.suspendFunctions(g),gated:!0};else if(o==="serve_static"&&m?.serveStatic)E={...await m.serveStatic(g),gated:!0};else if(o==="suspend_project"&&m?.suspendProject)E={...await m.suspendProject(g),gated:!0};else E={gated:!0,unsupported:!0}}return await e.notify?.({action:o,budgetId:l.id,reason:p.reason,simulated:u.simulated,released:!1}),E},release:async(o,a)=>{let{budget:l,record:u,restore:p}=a,E=e.transport;if(!u.simulated&&!Ft.includes(o)&&p.unsupported!==!0){if(o==="throttle_requests"&&E?.restoreRequests)await E.restoreRequests(p);else if(o==="suspend_functions"&&E?.resumeFunctions)await E.resumeFunctions(p);else if(o==="serve_static"&&E?.restoreDynamic)await E.restoreDynamic(p);else if(o==="suspend_project"&&E?.resumeProject)await E.resumeProject(p)}e.gate.close(l.id,o),await e.notify?.({action:o,budgetId:l.id,reason:u.reason,simulated:u.simulated,released:!0})}}}class Pp{calls=[];record(e,t){return this.calls.push({method:e,input:t}),{recorded:e}}throttleRequests(e){return this.record("throttleRequests",e)}restoreRequests(e){this.record("restoreRequests",e)}suspendFunctions(e){return this.record("suspendFunctions",e)}resumeFunctions(e){this.record("resumeFunctions",e)}serveStatic(e){return this.record("serveStatic",e)}restoreDynamic(e){this.record("restoreDynamic",e)}suspendProject(e){return this.record("suspendProject",e)}resumeProject(e){this.record("resumeProject",e)}}import{createCipheriv as Tn,createDecipheriv as gn,createHash as Yt,randomBytes as _n}from"node:crypto";var M=(e)=>{if(typeof e!=="string")return{};try{return JSON.parse(e)}catch{return{}}},C=(e)=>typeof e==="string"?e:void 0,nt=(e)=>Number(e)===1,V=(e,t,r,n)=>{let o=Number(e);return Number.isFinite(o)?Math.min(n,Math.max(r,Math.floor(o))):t},zt=(e)=>Yt("sha256").update(e).digest("hex").slice(0,16);function qt(e){return{id:String(e.id),projectId:String(e.project_id),environmentId:C(e.environment_id),resourceId:C(e.resource_id),name:String(e.name),kind:String(e.kind),target:String(e.target),config:M(e.config),intervalSeconds:Number(e.interval_seconds),timeoutSeconds:Number(e.timeout_seconds),failureThreshold:Number(e.failure_threshold),recoveryThreshold:Number(e.recovery_threshold),regions:M(e.regions),enabled:nt(e.enabled),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Ht(e){return{id:String(e.id),checkId:String(e.check_id),status:String(e.status),agent:String(e.agent),region:C(e.region),statusCode:e.status_code==null?void 0:Number(e.status_code),message:C(e.message),timings:M(e.timings),checkedAt:String(e.checked_at)}}function Vt(e){return{id:String(e.id),projectId:String(e.project_id),environmentId:C(e.environment_id),resourceId:C(e.resource_id),healthCheckId:C(e.health_check_id),name:String(e.name),signal:String(e.signal),operator:String(e.operator),threshold:e.threshold==null?void 0:Number(e.threshold),recoveryThreshold:e.recovery_threshold==null?void 0:Number(e.recovery_threshold),windowMs:Number(e.window_ms),consecutive:Number(e.consecutive),recoveryConsecutive:Number(e.recovery_consecutive),noDataPolicy:String(e.no_data_policy),severity:String(e.severity),groupBy:M(e.group_by),labels:M(e.labels),enabled:nt(e.enabled),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function tt(e){return{id:String(e.id),ruleId:String(e.rule_id),projectId:String(e.project_id),environmentId:C(e.environment_id),resourceId:C(e.resource_id),dedupKey:String(e.dedup_key),groupKey:String(e.group_key),state:String(e.state),severity:String(e.severity),title:String(e.title),evidence:M(e.evidence),failureCount:Number(e.failure_count),recoveryCount:Number(e.recovery_count),occurrenceCount:Number(e.occurrence_count),ownerActorId:C(e.owner_actor_id),acknowledgedByActorId:C(e.acknowledged_by_actor_id),acknowledgedAt:C(e.acknowledged_at),firstSeenAt:String(e.first_seen_at),lastSeenAt:String(e.last_seen_at),firingAt:C(e.firing_at),resolvedAt:C(e.resolved_at),silencedUntil:C(e.silenced_until),updatedAt:String(e.updated_at)}}function Kt(e){return{id:String(e.id),organizationId:String(e.organization_id),name:String(e.name),kind:String(e.kind),config:M(e.config),credentialFingerprint:C(e.credential_fingerprint),hasCredential:!!e.credential_ciphertext,status:String(e.status),version:Number(e.version),lastTestedAt:C(e.last_tested_at),lastError:C(e.last_error),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Qt(e){return{id:String(e.id),organizationId:String(e.organization_id),name:String(e.name),priority:Number(e.priority),matcher:M(e.matcher),channelIds:M(e.channel_ids),quietHours:e.quiet_hours?M(e.quiet_hours):void 0,groupWaitSeconds:Number(e.group_wait_seconds),reminderSeconds:e.reminder_seconds==null?void 0:Number(e.reminder_seconds),escalation:M(e.escalation),template:C(e.template),rateLimitPerMinute:Number(e.rate_limit_per_minute),enabled:nt(e.enabled),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function rt(e){return{id:String(e.id),alertId:C(e.alert_id),channelId:String(e.channel_id),routeId:C(e.route_id),eventType:String(e.event_type),idempotencyKey:String(e.idempotency_key),state:String(e.state),attempt:Number(e.attempt),maxAttempts:Number(e.max_attempts),nextAttemptAt:C(e.next_attempt_at),responseStatus:e.response_status==null?void 0:Number(e.response_status),error:C(e.error),payload:M(e.payload),createdAt:String(e.created_at),updatedAt:String(e.updated_at),deliveredAt:C(e.delivered_at)}}class li{controlPlane;options;key;constructor(e,t){this.controlPlane=e;this.options=t;this.key=Yt("sha256").update(t.encryptionKey).digest()}now(){return(this.options.now?.()??new Date).toISOString()}encrypt(e){let t=_n(12),r=Tn("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]=e.split("."),o=gn("aes-256-gcm",this.key,Buffer.from(t,"base64url"));return o.setAuthTag(Buffer.from(r,"base64url")),Buffer.concat([o.update(Buffer.from(n,"base64url")),o.final()]).toString("utf8")}createHealthCheck(e){if(!e.name.trim())throw Error("Health checks require a name.");if(!["http","tcp","command"].includes(e.kind))throw Error("Unsupported health check kind.");if(e.kind==="http"&&!/^https?:\/\//.test(e.target)||e.kind==="tcp"&&!/^[a-zA-Z0-9.-]+$/.test(e.target)||e.kind==="command"&&!e.config.command?.length)throw Error("Health check target is invalid.");let t=crypto.randomUUID(),r=this.now();return this.controlPlane.database.run("INSERT INTO health_checks (id,project_id,environment_id,resource_id,name,kind,target,config,interval_seconds,timeout_seconds,failure_threshold,recovery_threshold,regions,enabled,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.projectId,e.environmentId??null,e.resourceId??null,e.name.trim().slice(0,100),e.kind,e.target,JSON.stringify(e.config),V(e.intervalSeconds,60,10,86400),V(e.timeoutSeconds,10,1,300),V(e.failureThreshold,3,1,100),V(e.recoveryThreshold,2,1,100),JSON.stringify(e.regions.slice(0,20)),e.enabled?1:0,1,r,r]),this.getHealthCheck(t)}getHealthCheck(e){let t=this.controlPlane.database.query("SELECT * FROM health_checks WHERE id=?").get(e);return t?qt(t):void 0}listHealthChecks(e,t){return this.controlPlane.database.query(`SELECT * FROM health_checks WHERE project_id=?${t?" AND environment_id=?":""} ORDER BY updated_at DESC`).all(e,...t?[t]:[]).map(qt)}setHealthCheckEnabled(e,t){this.controlPlane.database.run("UPDATE health_checks SET enabled=?,version=version+1,updated_at=? WHERE id=?",[t?1:0,this.now(),e]);let r=this.getHealthCheck(e);if(!r)throw Error("Health check was not found.");return r}appendHealthResult(e){let t=crypto.randomUUID();return this.controlPlane.database.run("INSERT INTO health_results (id,check_id,status,agent,region,status_code,message,timings,checked_at) VALUES (?,?,?,?,?,?,?,?,?)",[t,e.checkId,e.status,e.agent.slice(0,100),e.region??null,e.statusCode??null,e.message?.slice(0,1000)??null,JSON.stringify(e.timings),e.checkedAt]),Ht(this.controlPlane.database.query("SELECT * FROM health_results WHERE id=?").get(t))}listHealthResults(e,t=100){return this.controlPlane.database.query("SELECT * FROM health_results WHERE check_id=? ORDER BY checked_at DESC LIMIT ?").all(e,Math.min(1000,Math.max(1,t))).map(Ht)}createRule(e){if(!e.name.trim())throw Error("Alert rules require a name.");if(e.operator!=="unhealthy"&&e.threshold==null)throw Error("Metric alert rules require a threshold.");let t=crypto.randomUUID(),r=this.now();return this.controlPlane.database.run("INSERT INTO alert_rules (id,project_id,environment_id,resource_id,health_check_id,name,signal,operator,threshold,recovery_threshold,window_ms,consecutive,recovery_consecutive,no_data_policy,severity,group_by,labels,enabled,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.projectId,e.environmentId??null,e.resourceId??null,e.healthCheckId??null,e.name.trim().slice(0,120),e.signal,e.operator,e.threshold??null,e.recoveryThreshold??null,V(e.windowMs,300000,1e4,2678400000),V(e.consecutive,3,1,100),V(e.recoveryConsecutive,2,1,100),e.noDataPolicy,e.severity,JSON.stringify(e.groupBy.slice(0,20)),JSON.stringify(e.labels),e.enabled?1:0,1,r,r]),this.getRule(t)}getRule(e){let t=this.controlPlane.database.query("SELECT * FROM alert_rules WHERE id=?").get(e);return t?Vt(t):void 0}listRules(e,t){return this.controlPlane.database.query(`SELECT * FROM alert_rules WHERE project_id=?${t?" AND environment_id=?":""} ORDER BY updated_at DESC`).all(e,...t?[t]:[]).map(Vt)}setRuleEnabled(e,t){this.controlPlane.database.run("UPDATE alert_rules SET enabled=?,version=version+1,updated_at=? WHERE id=?",[t?1:0,this.now(),e]);let r=this.getRule(e);if(!r)throw Error("Alert rule was not found.");return r}getAlertByDedup(e){let t=this.controlPlane.database.query("SELECT * FROM alerts WHERE dedup_key=?").get(e);return t?tt(t):void 0}getAlert(e){let t=this.controlPlane.database.query("SELECT * FROM alerts WHERE id=?").get(e);return t?tt(t):void 0}listAlerts(e,t={}){let r=["project_id=?"],n=[e];if(t.environmentId)r.push("environment_id=?"),n.push(t.environmentId);if(t.states?.length)r.push(`state IN (${t.states.map(()=>"?").join(",")})`),n.push(...t.states);return this.controlPlane.database.query(`SELECT * FROM alerts WHERE ${r.join(" AND ")} ORDER BY updated_at DESC LIMIT ?`).all(...n,Math.min(1000,t.limit??200)).map(tt)}saveAlert(e,t,r){return this.controlPlane.database.run("INSERT INTO alerts (id,rule_id,project_id,environment_id,resource_id,dedup_key,group_key,state,severity,title,evidence,failure_count,recovery_count,occurrence_count,owner_actor_id,acknowledged_by_actor_id,acknowledged_at,first_seen_at,last_seen_at,firing_at,resolved_at,silenced_until,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET state=excluded.state,severity=excluded.severity,title=excluded.title,evidence=excluded.evidence,failure_count=excluded.failure_count,recovery_count=excluded.recovery_count,occurrence_count=excluded.occurrence_count,owner_actor_id=excluded.owner_actor_id,acknowledged_by_actor_id=excluded.acknowledged_by_actor_id,acknowledged_at=excluded.acknowledged_at,last_seen_at=excluded.last_seen_at,firing_at=excluded.firing_at,resolved_at=excluded.resolved_at,silenced_until=excluded.silenced_until,updated_at=excluded.updated_at",[e.id,e.ruleId,e.projectId,e.environmentId??null,e.resourceId??null,e.dedupKey,e.groupKey,e.state,e.severity,e.title,JSON.stringify(e.evidence),e.failureCount,e.recoveryCount,e.occurrenceCount,e.ownerActorId??null,e.acknowledgedByActorId??null,e.acknowledgedAt??null,e.firstSeenAt,e.lastSeenAt,e.firingAt??null,e.resolvedAt??null,e.silencedUntil??null,e.updatedAt]),this.controlPlane.database.run("INSERT INTO alert_events (id,alert_id,type,actor_id,payload,created_at) VALUES (?,?,?,?,?,?)",[crypto.randomUUID(),e.id,t,r??null,JSON.stringify({state:e.state,severity:e.severity,evidence:e.evidence}),e.updatedAt]),this.getAlert(e.id)}acknowledge(e,t){let r=this.getAlert(e);if(!r)throw Error("Alert was not found.");let n=this.now();return this.saveAlert({...r,acknowledgedByActorId:t,acknowledgedAt:n,updatedAt:n},"acknowledged",t)}assign(e,t,r){let n=this.getAlert(e);if(!n)throw Error("Alert was not found.");let o=this.now();return this.saveAlert({...n,ownerActorId:t,updatedAt:o},"assigned",r)}silenceAlert(e,t,r){let n=this.getAlert(e);if(!n)throw Error("Alert was not found.");let o=new Date(t);if(!Number.isFinite(o.getTime())||o<=new Date)throw Error("Silence end must be in the future.");let a=this.now();return this.saveAlert({...n,state:"silenced",silencedUntil:o.toISOString(),updatedAt:a},"silenced",r)}createSilence(e){let t=new Date(e.startsAt),r=new Date(e.endsAt);if(!Number.isFinite(t.getTime())||!Number.isFinite(r.getTime())||t>=r)throw Error("Silence window is invalid.");try{new Intl.DateTimeFormat("en",{timeZone:e.timezone}).format(t)}catch{throw Error("Silence timezone is invalid.")}let n=crypto.randomUUID();return this.controlPlane.database.run("INSERT INTO alert_silences (id,project_id,environment_id,resource_id,matcher,reason,starts_at,ends_at,timezone,created_by_actor_id,created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?)",[n,e.projectId,e.environmentId??null,e.resourceId??null,JSON.stringify(e.matcher??{}),e.reason.slice(0,500),t.toISOString(),r.toISOString(),e.timezone,e.actorId??null,this.now()]),n}isSilenced(e,t,r){return this.controlPlane.database.query("SELECT * FROM alert_silences WHERE project_id=? AND starts_at<=? AND ends_at>?").all(e.projectId,r,r).some((o)=>{if(o.environment_id&&o.environment_id!==e.environmentId)return!1;if(o.resource_id&&o.resource_id!==e.resourceId)return!1;let a=M(o.matcher);return Object.entries(a).every(([l,u])=>t[l]===u)})}createChannel(e){if(!e.name.trim())throw Error("Notification channels require a name.");let t=crypto.randomUUID(),r=this.now(),n=e.credential?.trim();return this.controlPlane.database.run("INSERT INTO notification_channels (id,organization_id,name,kind,config,credential_ciphertext,credential_fingerprint,status,version,created_by_actor_id,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.organizationId,e.name.trim().slice(0,100),e.kind,JSON.stringify(e.config??{}),n?this.encrypt(n):null,n?zt(n):null,"active",1,e.actorId??null,r,r]),this.getChannel(t)}getChannel(e){let t=this.controlPlane.database.query("SELECT * FROM notification_channels WHERE id=?").get(e);return t?Kt(t):void 0}channelCredential(e){let t=this.controlPlane.database.query("SELECT credential_ciphertext FROM notification_channels WHERE id=?").get(e);return t?.credential_ciphertext?this.decrypt(String(t.credential_ciphertext)):void 0}listChannels(e){return this.controlPlane.database.query("SELECT * FROM notification_channels WHERE organization_id=? ORDER BY updated_at DESC").all(e).map(Kt)}rotateChannel(e,t){let r=this.now();this.controlPlane.database.run("UPDATE notification_channels SET credential_ciphertext=?,credential_fingerprint=?,status='active',last_error=NULL,version=version+1,updated_at=? WHERE id=?",[this.encrypt(t),zt(t),r,e]);let n=this.getChannel(e);if(!n)throw Error("Notification channel was not found.");return n}setChannelStatus(e,t,r){this.controlPlane.database.run("UPDATE notification_channels SET status=?,last_error=?,updated_at=? WHERE id=?",[t,r?.slice(0,1000)??null,this.now(),e]);let n=this.getChannel(e);if(!n)throw Error("Notification channel was not found.");return n}markChannelTest(e,t,r){let n=this.now();return this.controlPlane.database.run("UPDATE notification_channels SET status=?,last_tested_at=?,last_error=?,updated_at=? WHERE id=?",[t?"active":"failing",n,r?.slice(0,1000)??null,n,e]),this.getChannel(e)}createRoute(e){let t=crypto.randomUUID(),r=this.now();return this.controlPlane.database.run("INSERT INTO notification_routes (id,organization_id,name,priority,matcher,channel_ids,quiet_hours,group_wait_seconds,reminder_seconds,escalation,template,rate_limit_per_minute,enabled,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.organizationId,e.name.trim().slice(0,100),e.priority,JSON.stringify(e.matcher),JSON.stringify(e.channelIds),e.quietHours?JSON.stringify(e.quietHours):null,V(e.groupWaitSeconds,30,0,86400),e.reminderSeconds??null,JSON.stringify(e.escalation),e.template?.trim().slice(0,2000)??null,V(e.rateLimitPerMinute,60,1,1e4),e.enabled?1:0,1,r,r]),this.getRoute(t)}getRoute(e){let t=this.controlPlane.database.query("SELECT * FROM notification_routes WHERE id=?").get(e);return t?Qt(t):void 0}listRoutes(e){return this.controlPlane.database.query("SELECT * FROM notification_routes WHERE organization_id=? ORDER BY priority DESC,created_at ASC").all(e).map(Qt)}countRouteDeliveries(e,t){return Number(this.controlPlane.database.query("SELECT COUNT(*) count FROM notification_deliveries WHERE route_id=? AND created_at>=?").get(e,t)?.count??0)}setRouteEnabled(e,t){this.controlPlane.database.run("UPDATE notification_routes SET enabled=?,version=version+1,updated_at=? WHERE id=?",[t?1:0,this.now(),e]);let r=this.getRoute(e);if(!r)throw Error("Notification route was not found.");return r}createDelivery(e){let t=this.controlPlane.database.query("SELECT * FROM notification_deliveries WHERE idempotency_key=?").get(e.idempotencyKey);if(t)return rt(t);let r=crypto.randomUUID(),n=this.now();return this.controlPlane.database.run("INSERT INTO notification_deliveries (id,alert_id,channel_id,route_id,event_type,idempotency_key,state,attempt,max_attempts,next_attempt_at,payload,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",[r,e.alertId??null,e.channelId,e.routeId??null,e.eventType,e.idempotencyKey,"pending",0,V(e.maxAttempts,3,1,10),e.nextAttemptAt??null,JSON.stringify(e.payload),n,n]),this.getDelivery(r)}getDelivery(e){let t=this.controlPlane.database.query("SELECT * FROM notification_deliveries WHERE id=?").get(e);return t?rt(t):void 0}listDeliveries(e={}){let t=[],r=[];if(e.alertId)t.push("alert_id=?"),r.push(e.alertId);if(e.states?.length)t.push(`state IN (${e.states.map(()=>"?").join(",")})`),r.push(...e.states);return this.controlPlane.database.query(`SELECT * FROM notification_deliveries${t.length?" WHERE "+t.join(" AND "):""} ORDER BY updated_at DESC LIMIT ?`).all(...r,Math.min(1000,e.limit??200)).map(rt)}updateDelivery(e,t){return this.controlPlane.database.run("UPDATE notification_deliveries SET state=?,attempt=?,next_attempt_at=?,response_status=?,error=?,delivered_at=?,updated_at=? WHERE id=?",[t.state,t.attempt,t.nextAttemptAt??null,t.responseStatus??null,t.error?.slice(0,1000)??null,t.deliveredAt??null,this.now(),e]),this.getDelivery(e)}}import{createHash as hn}from"node:crypto";function Nn(e,t,r){if(e==="gt")return t>r;if(e==="gte")return t>=r;if(e==="lt")return t<r;if(e==="lte")return t<=r;return t===r}function fn(e,t,r){if(t.status==="no_data"||t.status==null&&t.value==null)return;if(e.operator==="unhealthy")return t.status==="unhealthy";if(t.value==null||e.threshold==null)return;return Nn(e.operator,t.value,r&&e.recoveryThreshold!=null?e.recoveryThreshold:e.threshold)}function yn(e,t){let r=Object.fromEntries(e.groupBy.flatMap((o)=>t.group?.[o]==null?[]:[[o,String(t.group[o])]]));return{key:Object.entries(r).sort(([o],[a])=>o.localeCompare(a)).map(([o,a])=>`${o}=${a}`).join(",")||"default",values:r}}function Ln(e,t){return hn("sha256").update(`${e}\x00${t}`).digest("hex")}class Nr{store;constructor(e){this.store=e}evaluate(e,t){if(!e.enabled)return{transition:"ignored",notify:!1};let r=yn(e,t),n=Ln(e.id,r.key),o=this.store.getAlertByDedup(n),a=o?.state==="firing"||o?.state==="silenced",l=fn(e,t,a);if(l==null&&e.noDataPolicy==="ignore")return{alert:o,transition:"ignored",notify:!1};let u=l??e.noDataPolicy==="firing",p=l==null&&e.noDataPolicy==="pending",E=new Date(t.timestamp).toISOString(),g=s({...t.evidence??{},...t.value==null?{}:{value:t.value},...t.status?{healthStatus:t.status}:{},group:r.values}),m;if(!o){let N=u||p?1:0,y=u&&N>=e.consecutive?"firing":"pending";m={id:crypto.randomUUID(),ruleId:e.id,projectId:e.projectId,environmentId:e.environmentId,resourceId:e.resourceId,dedupKey:n,groupKey:r.key,state:y,severity:e.severity,title:e.name,evidence:g,failureCount:N,recoveryCount:0,occurrenceCount:1,firstSeenAt:E,lastSeenAt:E,firingAt:y==="firing"?E:void 0,updatedAt:E}}else if(u||p){let N=o.state==="resolved",y=(N?0:o.failureCount)+1,L=o.silencedUntil&&new Date(o.silencedUntil)>new Date(E),v=p?"pending":y>=e.consecutive?"firing":"pending";if((L||this.store.isSilenced(e,r.values,E))&&v==="firing")v="silenced";m={...o,state:v,severity:e.severity,title:e.name,evidence:g,failureCount:y,recoveryCount:0,occurrenceCount:o.occurrenceCount+1,firstSeenAt:N?E:o.firstSeenAt,lastSeenAt:E,firingAt:v==="firing"||v==="silenced"?o.firingAt??E:void 0,resolvedAt:void 0,updatedAt:E}}else{let N=o.recoveryCount+1,y=N>=e.recoveryConsecutive;m={...o,state:y?"resolved":o.state,evidence:g,failureCount:y?0:o.failureCount,recoveryCount:N,lastSeenAt:E,resolvedAt:y?E:o.resolvedAt,silencedUntil:y?void 0:o.silencedUntil,updatedAt:E}}let T=o?.state!==m.state,h=m.state==="pending"?"pending":m.state==="firing"?T?"firing":"updated":m.state==="silenced"?"silenced":T?"resolved":"updated";return{alert:this.store.saveAlert(m,T||!o?h:"observed"),transition:h,notify:h==="firing"||h==="resolved"}}}import{createHmac as vn}from"node:crypto";function In(e,t){let r=Object.fromEntries(new Intl.DateTimeFormat("en-US",{timeZone:t,weekday:"short",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).formatToParts(e).map((o)=>[o.type,o.value])),n=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];return{minute:Number(r.hour)*60+Number(r.minute),weekday:n.indexOf(r.weekday)}}function Gt(e){let t=/^(\d{2}):(\d{2})$/.exec(e);if(!t)throw Error("Quiet hours require HH:MM times.");let r=Number(t[1])*60+Number(t[2]);if(Number(t[1])>23||Number(t[2])>59)throw Error("Quiet hours require valid HH:MM times.");return r}function zs(e,t){if(!e.quietHours)return!1;let r=In(t,e.quietHours.timezone),n=Gt(e.quietHours.start),o=Gt(e.quietHours.end);if(e.quietHours.weekdays?.length&&!e.quietHours.weekdays.includes(r.weekday))return!1;return n<=o?r.minute>=n&&r.minute<o:r.minute>=n||r.minute<o}function Sn(e,t,r){let n=e.matcher;return(!n.projectIds?.length||n.projectIds.includes(t.projectId))&&(!n.environmentIds?.length||!!t.environmentId&&n.environmentIds.includes(t.environmentId))&&(!n.resourceIds?.length||!!t.resourceId&&n.resourceIds.includes(t.resourceId))&&(!n.severities?.length||n.severities.includes(t.severity))&&(!n.eventTypes?.length||n.eventTypes.includes(r))}function bn(e){if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t==="object"?t:{value:e}}catch{return{value:e}}}function Rn(e,t,r){let n={severity:e.severity.toUpperCase(),title:e.title,state:e.state,event:t,projectId:e.projectId,environmentId:e.environmentId??"",resourceId:e.resourceId??"",groupKey:e.groupKey};return(r?.trim()||"[{{severity}}] {{title}} · {{state}}").replace(/\{\{(severity|title|state|event|projectId|environmentId|resourceId|groupKey)\}\}/g,(o,a)=>n[a]).slice(0,2000)}function it(e,t,r){return{schemaVersion:1,event:t,notificationText:Rn(e,t,r),alert:{id:e.id,state:e.state,severity:e.severity,title:e.title,projectId:e.projectId,environmentId:e.environmentId??null,resourceId:e.resourceId??null,groupKey:e.groupKey,firstSeenAt:e.firstSeenAt,lastSeenAt:e.lastSeenAt,firingAt:e.firingAt??null,resolvedAt:e.resolvedAt??null,evidence:e.evidence}}}class ui{store;options;fetchImpl;constructor(e,t={}){this.store=e;this.options=t;this.fetchImpl=t.fetchImpl??globalThis.fetch}now(){return this.options.now?.()??new Date}preview(e,t,r){let n=[];for(let o of this.store.listRoutes(e)){if(!o.enabled||!Sn(o,t,r))continue;let a=[];for(let l of o.channelIds){let u=this.store.getChannel(l);if(u?.status==="active")a.push(u)}n.push({route:o,channels:a,quiet:zs(o,this.now())})}return n}enqueue(e,t,r){let n=r==="resolved"?t.resolvedAt:r==="firing"?t.firingAt:t.updatedAt,o=[];for(let a of this.preview(e,t,r)){if(a.quiet&&r!=="resolved")continue;let l=r==="resolved"||a.route.groupWaitSeconds===0?void 0:new Date(this.now().getTime()+a.route.groupWaitSeconds*1000).toISOString(),u=r==="resolved"?Number.POSITIVE_INFINITY:Math.max(0,a.route.rateLimitPerMinute-this.store.countRouteDeliveries(a.route.id,new Date(this.now().getTime()-60000).toISOString()));for(let p of a.channels){if(u<=0)break;o.push(this.store.createDelivery({alertId:t.id,channelId:p.id,routeId:a.route.id,eventType:r,idempotencyKey:`${t.id}:${r}:${n}:${p.id}`,payload:it(t,r,a.route.template),nextAttemptAt:l})),u--}}return o}enqueueRemindersAndEscalations(e,t){let r=this.now(),n=[];for(let o of t.filter((a)=>a.state==="firing"&&!a.acknowledgedAt&&a.firingAt)){let a=Math.max(0,(r.getTime()-new Date(o.firingAt).getTime())/1000);for(let l of this.preview(e,o,"reminder")){if(l.quiet)continue;if(l.route.reminderSeconds&&a>=l.route.reminderSeconds){let u=Math.floor(a/l.route.reminderSeconds);for(let p of l.channels)n.push(this.store.createDelivery({alertId:o.id,channelId:p.id,routeId:l.route.id,eventType:"reminder",idempotencyKey:`${o.id}:reminder:${l.route.id}:${u}:${p.id}`,payload:it(o,"reminder")}))}for(let[u,p]of l.route.escalation.entries())if(a>=p.afterSeconds){for(let E of p.channelIds)if(this.store.getChannel(E)?.status==="active")n.push(this.store.createDelivery({alertId:o.id,channelId:E,routeId:l.route.id,eventType:"escalation",idempotencyKey:`${o.id}:escalation:${l.route.id}:${u}:${E}`,payload:it(o,"escalation")}))}}}return n}async send(e,t){let r=bn(this.store.channelCredential(e.id)),n=typeof t.notificationText==="string"?t.notificationText:`[${String(t.alert?.severity??"info").toUpperCase()}] ${String(t.alert?.title??"ts-cloud alert")} · ${String(t.alert?.state??t.event)}`;try{if(e.kind==="email"){if(!this.options.emailImpl)return{ok:!1,error:"Email adapter is not configured."};return await this.options.emailImpl({to:e.config.to,from:e.config.from,subject:`[ts-cloud] ${String(t.alert?.title??t.event)}`,text:`${n}
|
|
1541
1541
|
|
|
1542
|
-
${JSON.stringify(t,null,2)}`}),{ok:!0,status:202}}if(e.kind==="sms"){if(!this.options.smsImpl)return{ok:!1,error:"SMS adapter is not configured."};let g=e.config.to;if(typeof g!=="string"||!g.trim())return{ok:!1,error:"SMS channels need a `to` number."};return await this.options.smsImpl({to:g,from:e.config.from,text:n.slice(0,300)}),{ok:!0,status:202}}let o=r.url??r.value,a=t,l={"content-type":"application/json"};if(e.kind==="slack")a={text:n};if(e.kind==="discord")a={content:n};if(e.kind==="teams")a={text:n};if(e.kind==="telegram")o=`https://api.telegram.org/bot${r.botToken??r.value}/sendMessage`,a={chat_id:e.config.chatId,text:n};if(!o||!/^https:\/\//.test(o))return{ok:!1,error:"Channel endpoint is unavailable or not HTTPS."};let u=JSON.stringify(a);if(e.kind==="webhook"&&r.signingSecret){let g=Math.floor(this.now().getTime()/1000).toString();l["x-ts-cloud-timestamp"]=g,l["x-ts-cloud-signature"]=`v1=${vn("sha256",r.signingSecret).update(`${g}.${u}`).digest("hex")}`}let p=new AbortController,E=setTimeout(()=>p.abort(),1e4);try{let g=await this.fetchImpl(o,{method:"POST",headers:l,body:u,signal:p.signal});return g.ok?{ok:!0,status:g.status}:{ok:!1,status:g.status,error:`Channel returned HTTP ${g.status}.`}}finally{clearTimeout(E)}}catch(o){return{ok:!1,error:o instanceof Error?o.message:String(o)}}}async deliver(e){let t=this.store.getDelivery(e);if(!t)throw Error("Notification delivery was not found.");if(t.state==="delivered"||t.state==="dead"||t.nextAttemptAt&&t.nextAttemptAt>this.now().toISOString())return t;let r=this.store.getChannel(t.channelId);if(!r||r.status==="disabled"||r.status==="paused")return this.store.updateDelivery(e,{state:"failed",attempt:t.attempt+1,error:"Notification channel is unavailable."});let n=t.attempt+1,o=await this.send(r,t.payload);if(o.ok)return this.store.setChannelStatus(r.id,"active"),this.store.updateDelivery(e,{state:"delivered",attempt:n,responseStatus:o.status,deliveredAt:this.now().toISOString()});let l=!(!o.status||o.status===429||o.status>=500)||n>=t.maxAttempts,u=l?void 0:new Date(this.now().getTime()+Math.min(3600000,30000*2**(n-1))).toISOString();return this.store.setChannelStatus(r.id,"failing",o.error),this.store.updateDelivery(e,{state:l?"dead":"retrying",attempt:n,nextAttemptAt:u,responseStatus:o.status,error:o.error})}async deliverAll(e){return Promise.all(e.map((t)=>this.deliver(t.id)))}async retryDue(){let e=this.now().toISOString(),t=this.store.listDeliveries({states:["pending","retrying"]}).filter((r)=>!r.nextAttemptAt||r.nextAttemptAt<=e);return this.deliverAll(t)}async testChannel(e){let t=this.store.getChannel(e);if(!t)throw Error("Notification channel was not found.");let r=await this.send(t,{schemaVersion:1,event:"test",message:"ts-cloud notification channel test. No incident was created."});return this.store.markChannelTest(e,r.ok,r.error),r}}import{lookup as Cn}from"node:dns/promises";import{connect as An}from"node:net";async function On(e,t){let r=Bun.spawn(e,{stdout:"pipe",stderr:"pipe"}),n=setTimeout(()=>r.kill(),t);try{return{exitCode:await r.exited,stdout:await new Response(r.stdout).text(),stderr:await new Response(r.stderr).text()}}finally{clearTimeout(n)}}class Qe{store;options;constructor(e,t={}){this.store=e;this.options=t}now(){return this.options.now?.()??new Date}async probe(e){let t=performance.now(),r=this.now().toISOString(),n=this.options.agent??"local";try{if(e.kind==="http"){let l=new URL(e.target),u=performance.now();await(this.options.lookupImpl??Cn)(l.hostname);let p=performance.now()-u,E=new AbortController,g=setTimeout(()=>E.abort(),e.timeoutSeconds*1000);try{let m=performance.now(),T=await(this.options.fetchImpl??fetch)(l.toString(),{method:e.config.method??"GET",headers:e.config.headers,signal:E.signal,redirect:"manual"}),N=performance.now()-m,h=e.config.expectedBody?await T.text():"",f=e.config.expectedStatuses??[200,201,202,204],L=f.includes(T.status)&&(!e.config.expectedBody||h.includes(e.config.expectedBody));return{checkId:e.id,status:L?"healthy":"unhealthy",agent:n,region:this.options.region,statusCode:T.status,message:L?void 0:`Expected ${f.join("/")} and configured body match.`,timings:{dnsMs:p,ttfbMs:N,totalMs:performance.now()-t},checkedAt:r}}finally{clearTimeout(g)}}if(e.kind==="tcp"){let l=Number(e.config.port);if(!Number.isInteger(l)||l<1||l>65535)throw Error("TCP health check requires a valid port.");let u=performance.now();return await new Promise((p,E)=>{let g=An({host:e.target,port:l}),m=setTimeout(()=>{g.destroy(),E(Error("TCP health check timed out."))},e.timeoutSeconds*1000);g.once("connect",()=>{clearTimeout(m),g.destroy(),p()}),g.once("error",(T)=>{clearTimeout(m),E(T)})}),{checkId:e.id,status:"healthy",agent:n,region:this.options.region,timings:{connectMs:performance.now()-u,totalMs:performance.now()-t},checkedAt:r}}let o=e.config.command??[];if(!o.length)throw Error("Command health check is not configured.");let a=await(this.options.commandImpl??On)(o,e.timeoutSeconds*1000);return{checkId:e.id,status:a.exitCode===0?"healthy":"unhealthy",agent:n,region:this.options.region,message:a.exitCode===0?void 0:(a.stderr||a.stdout||`Command exited ${a.exitCode}`).slice(0,1000),timings:{totalMs:performance.now()-t},checkedAt:r}}catch(o){return{checkId:e.id,status:"unhealthy",agent:n,region:this.options.region,message:(o instanceof Error?o.message:String(o)).slice(0,1000),timings:{totalMs:performance.now()-t},checkedAt:r}}}async run(e){return this.store.appendHealthResult(await this.probe(e))}async runAndEvaluate(e){let t=await this.run(e),r=new Nr(this.store),n=this.store.listRules(e.projectId,e.environmentId).filter((o)=>o.healthCheckId===e.id);return{result:t,evaluations:n.map((o)=>r.evaluate(o,{status:t.status,timestamp:t.checkedAt,group:{agent:t.agent,region:t.region??""},evidence:{healthResultId:t.id,statusCode:t.statusCode??null,message:t.message??null,timings:t.timings}}))}}}var af=Object.freeze({rawDays:30,downsampleAfterDays:7,downsampleBucketMs:3600000,maxRecords:1e6,samplingRate:1,collectLogs:!0,collectTraces:!0,collectRequestAnalytics:!0,estimatedStorageUsdPerGbMonth:0});function we(e,t,r,n){let o=Number(e);return Number.isFinite(o)?Math.min(n,Math.max(r,Math.floor(o))):t}function Wt(e,t,r,n){let o=Number(e);return Number.isFinite(o)?Math.min(n,Math.max(r,o)):t}function ot(e,t){return typeof e==="boolean"?e:t}function Ep(e,t={...af}){let r=e&&typeof e==="object"&&!Array.isArray(e)?e:{},n=we(r.rawDays,t.rawDays,1,3650),o=we(r.downsampleAfterDays,t.downsampleAfterDays,1,n);return{rawDays:n,downsampleAfterDays:o,downsampleBucketMs:we(r.downsampleBucketMs,t.downsampleBucketMs,60000,86400000),maxRecords:we(r.maxRecords,t.maxRecords,1000,1e8),samplingRate:Wt(r.samplingRate,t.samplingRate,0.01,1),collectLogs:ot(r.collectLogs,t.collectLogs),collectTraces:ot(r.collectTraces,t.collectTraces),collectRequestAnalytics:ot(r.collectRequestAnalytics,t.collectRequestAnalytics),estimatedStorageUsdPerGbMonth:Wt(r.estimatedStorageUsdPerGbMonth,t.estimatedStorageUsdPerGbMonth,0,1e4)}}function vp(e){return`telemetry.policy:${e}`}function Mt(e,t){return Ep(e.getSetting(vp(t)))}function Zc(e,t,r){let n=Ep(r,Mt(e,t));return e.setSetting(vp(t),n),n}function ed(e,t){return Number((Math.max(0,e)/1073741824*t.estimatedStorageUsdPerGbMonth).toFixed(4))}var Un=/(?:authorization|cookie|password|passwd|secret|token|api[_-]?key|private[_-]?key|access[_-]?key|session)/i,Dn=/\b(?:authorization|cookie|password|passwd|secret|token|api[_-]?key|private[_-]?key|access[_-]?key)\s*[=:]\s*[^\s,;&\[]+/gi,wn=/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi,kn=/\b(?:\d{1,3}\.){3}\d{1,3}\b/g;function td(e,t={}){let r=e.replace(/([?&][^=&#\s]+)=([^&#\s]*)/g,"$1=[REDACTED]").replace(Dn,"[REDACTED]");if(t.redactEmail!==!1)r=r.replace(wn,"[EMAIL]");if(t.redactIp)r=r.replace(kn,"[IP]");for(let n of t.patterns??[])r=r.replace(n,"[REDACTED]");return r}function ui(e,t={},r){if(r&&Un.test(r))return"[REDACTED]";if(e===null||typeof e==="boolean"||typeof e==="number")return e;if(typeof e==="string")return td(e,t);if(Array.isArray(e))return e.map((n)=>ui(n,t));if(e&&typeof e==="object"){let n={};for(let[o,a]of Object.entries(e))n[o]=ui(a,t,o);return n}return String(e??"")}function pi(e){if(!e)return;return e.split("?",1)[0].replace(/\b[0-9a-f]{8}-[0-9a-f-]{27,}\b/gi,":id").replace(/\/(?:(?:\d{4,})|(?:[0-9a-f]{16,}))(?:\/|$)/gi,(r)=>r.endsWith("/")?"/:id/":"/:id").slice(0,512)}var Jt=65536,Xn=2678400000,Pn=new Set(["metric","log","trace","request","event"]);function x(e){return typeof e==="string"?e:void 0}function ue(e){return e==null?void 0:Number(e)}function xn(e){if(typeof e!=="string")return{};try{return JSON.parse(e)}catch{return{}}}function ke(e){return{id:String(e.id),projectId:String(e.project_id),environmentId:x(e.environment_id),resourceId:x(e.resource_id),kind:String(e.kind),source:String(e.source),name:String(e.name),timestamp:String(e.timestamp),observedAt:String(e.observed_at),value:ue(e.value),unit:x(e.unit),level:x(e.level),message:x(e.message),durationMs:ue(e.duration_ms),statusCode:ue(e.status_code),method:x(e.method),host:x(e.host),pathTemplate:x(e.path_template),bytesIn:ue(e.bytes_in),bytesOut:ue(e.bytes_out),region:x(e.region),cacheResult:x(e.cache_result),upstream:x(e.upstream),traceId:x(e.trace_id),requestId:x(e.request_id),deploymentId:x(e.deployment_id),releaseId:x(e.release_id),workloadId:x(e.workload_id),sampled:Number(e.sampled)===1,attributes:xn(e.attributes),ingestedBytes:Number(e.ingested_bytes)}}function Z(e,t){let r=new Date(e);if(!e||!Number.isFinite(r.getTime()))throw Error(`${t} must be a valid ISO-8601 instant.`);return r}function Xe(e){let t=Z(e.from,"from"),r=Z(e.to,"to");if(t>=r)throw Error("Telemetry from must be earlier than to.");if(r.getTime()-t.getTime()>Xn)throw Error("Telemetry queries are limited to 31 days.");return{from:t,to:r}}function Zt(e){if(!e)return;try{let t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));if(typeof t?.timestamp!=="string"||typeof t?.id!=="string")throw Error();return t}catch{throw Error("Telemetry cursor is invalid.")}}function gi(e){return e?Buffer.from(JSON.stringify({timestamp:e.timestamp,id:e.id})).toString("base64url"):void 0}function cf(e,t){if(!e.length)return;let r=[...e].sort((o,a)=>o-a),n=Math.max(0,Math.min(r.length-1,Math.ceil(t/100*r.length)-1));return r[n]}function pe(e,t){if(t==="count")return e.length;if(!e.length)return;if(t==="sum")return e.reduce((r,n)=>r+n,0);if(t==="avg")return e.reduce((r,n)=>r+n,0)/e.length;if(t==="min")return Math.min(...e);if(t==="max")return Math.max(...e);return cf(e,Number(t.slice(1)))}function df(e,t="UTC"){try{return new Intl.DateTimeFormat("en-US",{timeZone:t,month:"short",day:"2-digit",hour:"2-digit",minute:"2-digit",hourCycle:"h23",timeZoneName:"short"}).format(e)}catch{throw Error(`Unknown telemetry timezone: ${t}`)}}class lt{controlPlane;options;constructor(e,t={}){this.controlPlane=e;this.options=t}now(){return this.options.now?.()??new Date}append(e){if(!Pn.has(e.kind))throw Error(`Unsupported telemetry kind: ${e.kind}`);let t=Z(e.timestamp,"timestamp").toISOString(),r=e.observedAt?Z(e.observedAt,"observedAt").toISOString():this.now().toISOString(),n=ui(e.attributes??{},this.options.redaction),o=e.message?td(e.message,this.options.redaction).slice(0,32768):void 0,a=pi(e.pathTemplate),l=e.id??crypto.randomUUID(),u=JSON.stringify({...e,id:l,timestamp:t,observedAt:r,attributes:n,message:o,pathTemplate:a}),p=Buffer.byteLength(u);if(p>Jt)throw Error(`Telemetry records are limited to ${Jt} bytes.`);return this.controlPlane.database.run("INSERT OR IGNORE INTO telemetry_records (id, project_id, environment_id, resource_id, kind, source, name, timestamp, observed_at, value, unit, level, message, duration_ms, status_code, method, host, path_template, bytes_in, bytes_out, region, cache_result, upstream, trace_id, request_id, deployment_id, release_id, workload_id, sampled, attributes, ingested_bytes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[l,e.projectId,e.environmentId??null,e.resourceId??null,e.kind,e.source.slice(0,128),e.name.slice(0,256),t,r,e.value??null,e.unit??null,e.level??null,o??null,e.durationMs??null,e.statusCode??null,e.method?.slice(0,16)??null,e.host?.slice(0,256)??null,a??null,e.bytesIn??null,e.bytesOut??null,e.region?.slice(0,64)??null,e.cacheResult?.slice(0,64)??null,e.upstream?.slice(0,256)??null,e.traceId?.slice(0,256)??null,e.requestId?.slice(0,256)??null,e.deploymentId?.slice(0,256)??null,e.releaseId?.slice(0,256)??null,e.workloadId?.slice(0,512)??null,e.sampled===!1?0:1,JSON.stringify(n),p]),this.get(l)}appendMany(e){if(e.length>1e4)throw Error("Telemetry batches are limited to 10,000 records.");return this.controlPlane.database.transaction((r)=>r.map((n)=>this.append(n)))(e)}get(e){let t=this.controlPlane.database.query("SELECT * FROM telemetry_records WHERE id=?").get(e);return t?ke(t):void 0}query(e){let{from:t,to:r}=Xe(e),n=Math.min(5000,Math.max(1,Math.floor(e.limit??500))),o=["project_id=?","timestamp>=?","timestamp<?"],a=[e.projectId,t.toISOString(),r.toISOString()],l=(v,I)=>{if(I)o.push(`${v}=?`),a.push(I)},u=(v,I)=>{let S=[...new Set(I??[])].slice(0,100);if(S.length)o.push(`${v} IN (${S.map(()=>"?").join(",")})`),a.push(...S)};if(l("environment_id",e.environmentId),u("resource_id",e.resourceIds),u("kind",e.kinds),u("name",e.names),u("source",e.sources),u("level",e.levels),l("trace_id",e.traceId),l("request_id",e.requestId),l("deployment_id",e.deploymentId),l("release_id",e.releaseId),l("workload_id",e.workloadId),e.text)o.push("(message LIKE ? OR name LIKE ?)"),a.push(`%${e.text.slice(0,256)}%`,`%${e.text.slice(0,256)}%`);let p=Zt(e.cursor);if(p)o.push("(timestamp<? OR (timestamp=? AND id<?))"),a.push(p.timestamp,p.timestamp,p.id);let E=this.controlPlane.database.query(`SELECT * FROM telemetry_records WHERE ${o.join(" AND ")} ORDER BY timestamp DESC, id DESC LIMIT ?`).all(...a,n+1),g=E.slice(0,n).map(ke),m=E.length>n,T=new Map;for(let v of g)T.set(v.source,[...T.get(v.source)??[],v]);let N=this.now().getTime(),h=[...T].map(([v,I])=>{let S=I.reduce((P,U)=>U.observedAt>P?U.observedAt:P,I[0].observedAt),O=N-new Date(S).getTime();return{source:v,latestAt:S,freshness:O<=120000?"live":O<=600000?"stale":"unavailable",count:I.length}}),f=Math.max(60000,(r.getTime()-t.getTime())/100),L=[...T].flatMap(([v,I])=>{let S=[...new Set(I.map((O)=>new Date(O.timestamp).getTime()))].sort((O,P)=>O-P);return S.slice(1).flatMap((O,P)=>O-S[P]>f?[{from:new Date(S[P]).toISOString(),to:new Date(O).toISOString(),source:v}]:[])});return{records:g,nextCursor:m?gi(g.at(-1)):void 0,truncated:m,scannedRange:{from:t.toISOString(),to:r.toISOString()},sources:h,gaps:L}}tail(e,t){let{from:r,to:n}=Xe(e),o=Math.min(1000,Math.max(1,Math.floor(e.limit??200))),a=["project_id=?","timestamp>=?","timestamp<?"],l=[e.projectId,r.toISOString(),n.toISOString()],u=(T,N)=>{if(N)a.push(`${T}=?`),l.push(N)},p=(T,N)=>{let h=[...new Set(N??[])].slice(0,100);if(h.length)a.push(`${T} IN (${h.map(()=>"?").join(",")})`),l.push(...h)};if(u("environment_id",e.environmentId),p("resource_id",e.resourceIds),p("kind",e.kinds),p("name",e.names),p("source",e.sources),p("level",e.levels),u("trace_id",e.traceId),u("request_id",e.requestId),u("deployment_id",e.deploymentId),u("release_id",e.releaseId),u("workload_id",e.workloadId),e.text)a.push("(message LIKE ? OR name LIKE ?)"),l.push(`%${e.text.slice(0,256)}%`,`%${e.text.slice(0,256)}%`);let E=Zt(t);if(E)a.push("(timestamp>? OR (timestamp=? AND id>?))"),l.push(E.timestamp,E.timestamp,E.id);let g=this.controlPlane.database.query(`SELECT * FROM telemetry_records WHERE ${a.join(" AND ")} ORDER BY timestamp ASC, id ASC LIMIT ?`).all(...l,o+1),m=g.slice(0,o).map(ke);return{records:m,cursor:gi(m.at(-1))??t,truncated:g.length>o}}series(e){let{from:t,to:r}=Xe(e),n=Math.min(86400000,Math.max(1000,Math.floor(e.bucketMs)));if((r.getTime()-t.getTime())/n>2000)throw Error("Telemetry series are limited to 2,000 buckets.");let o=this.query({...e,kinds:["metric"],limit:5000,cursor:void 0}),a=new Map;for(let u of o.records)a.set(`${u.source}\x00${u.name}`,[...a.get(`${u.source}\x00${u.name}`)??[],u]);let l=(u,p,E)=>{let g=new Map;for(let T of u){let N=p.getTime()+Math.floor((new Date(T.timestamp).getTime()-p.getTime())/n)*n;if(N>=p.getTime()&&N<E.getTime()&&T.value!=null)g.set(N,[...g.get(N)??[],T.value])}let m=[];for(let T=p.getTime();T<E.getTime();T+=n){let N=g.get(T)??[],h=pe(N,e.aggregation);m.push({timestamp:new Date(T).toISOString(),label:df(new Date(T),e.timezone),value:h,count:N.length,gap:h==null})}return m};return[...a].map(([u,p])=>{let[E,g]=u.split("\x00"),m={name:g,source:E,unit:p.find((T)=>T.unit)?.unit,aggregation:e.aggregation,bucketMs:n,points:l(p,t,r)};if(e.compareFrom&&e.compareTo){let T=this.query({...e,from:e.compareFrom,to:e.compareTo,kinds:["metric"],limit:5000,cursor:void 0}).records.filter((N)=>N.source===E&&N.name===g);m.comparison=l(T,Z(e.compareFrom,"compareFrom"),Z(e.compareTo,"compareTo"))}return m})}status(e,t,r=30,n=1,o){let a=[e],l=t?" AND environment_id=?":"";if(t)a.push(t);let u=[...new Set(o??[])].slice(0,100);if(o&&u.length===0)return[];let p=o?` AND resource_id IN (${u.map(()=>"?").join(",")||"''"})`:"";a.push(...u);let E=this.controlPlane.database.query(`SELECT source, MAX(latest_observed_at) latest, SUM(ingested_bytes) bytes, SUM(record_count) count, MIN(first_observed_at) first FROM telemetry_source_rollups WHERE project_id=?${l}${p} GROUP BY source`).all(...a),g=this.now().getTime();return E.map((m)=>{let T=String(m.latest),N=Math.max(0,Math.floor((g-new Date(T).getTime())/1000)),h=Math.max(1,(new Date(T).getTime()-new Date(String(m.first)).getTime())/86400000);return{source:String(m.source),freshness:N<=120?"live":N<=600?"stale":"unavailable",lastObservedAt:T,lagSeconds:N,samplingRate:n,retentionDays:r,estimatedDailyBytes:Math.round(Number(m.bytes)/h)}})}saveQuery(e,t,r,n){let o=r.trim().slice(0,80);if(!o)throw Error("Saved telemetry queries require a name.");if(Xe(n),n.projectId!==e)throw Error("Saved telemetry queries cannot cross project scope.");let a=this.now().toISOString(),l=JSON.stringify(ui(n,this.options.redaction));if(Buffer.byteLength(l)>16384)throw Error("Saved telemetry queries are limited to 16 KB.");let u=this.controlPlane.database.query("SELECT * FROM telemetry_saved_queries WHERE project_id=? AND actor_id IS ? AND name=?").get(e,t??null,o),p=u?String(u.id):crypto.randomUUID();return this.controlPlane.database.run("INSERT INTO telemetry_saved_queries (id, project_id, actor_id, name, query, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(project_id, actor_id, name) DO UPDATE SET query=excluded.query, updated_at=excluded.updated_at",[p,e,t??null,o,l,u?String(u.created_at):a,a]),{id:p,projectId:e,actorId:t,name:o,query:JSON.parse(l),createdAt:u?String(u.created_at):a,updatedAt:a}}listSavedQueries(e,t){return this.controlPlane.database.query("SELECT * FROM telemetry_saved_queries WHERE project_id=? AND actor_id IS ? ORDER BY updated_at DESC").all(e,t??null).map((r)=>({id:String(r.id),projectId:String(r.project_id),actorId:x(r.actor_id),name:String(r.name),query:JSON.parse(String(r.query)),createdAt:String(r.created_at),updatedAt:String(r.updated_at)}))}deleteSavedQuery(e,t,r){return this.controlPlane.database.run("DELETE FROM telemetry_saved_queries WHERE id=? AND project_id=? AND actor_id IS ?",[r,e,t??null]).changes>0}downsample(e,t){let r=Math.min(86400000,Math.max(60000,Math.floor(e.downsampleBucketMs))),n=new Date(this.now().getTime()-Math.max(1,e.downsampleAfterDays)*86400000).toISOString(),o=new Date(this.now().getTime()-Math.max(1,e.rawDays)*86400000).toISOString(),a=this.controlPlane.database.query(`SELECT * FROM telemetry_records WHERE kind='metric' AND source NOT LIKE '%:rollup' AND timestamp>=? AND timestamp<?${t?" AND project_id=?":""} ORDER BY timestamp ASC LIMIT 50001`).all(o,n,...t?[t]:[]);if(a.length>50000)throw Error("Telemetry downsampling is limited to 50,000 raw points per pass; run compaction more frequently.");let l=a.map(ke),u=new Map;for(let E of l){let g=Math.floor(new Date(E.timestamp).getTime()/r)*r,m=JSON.stringify([E.projectId,E.environmentId??"",E.resourceId??"",E.source,E.name,E.unit??"",g]);u.set(m,[...u.get(m)??[],E])}return this.controlPlane.database.transaction(()=>{for(let E=0;E<l.length;E+=500){let g=l.slice(E,E+500).map((m)=>m.id);if(g.length)this.controlPlane.database.run(`DELETE FROM telemetry_records WHERE id IN (${g.map(()=>"?").join(",")})`,g)}for(let[E,g]of u){let[m,T,N,h,f,L,v]=JSON.parse(E),I=g.flatMap((S)=>S.value==null?[]:[S.value]);this.append({projectId:m,environmentId:T||void 0,resourceId:N||void 0,kind:"metric",source:`${h}:rollup`,name:f,unit:L||void 0,timestamp:new Date(v).toISOString(),value:pe(I,"avg"),attributes:{downsampled:!0,count:I.length,min:pe(I,"min"),max:pe(I,"max"),p95:pe(I,"p95"),bucketMs:r}})}})(),{compacted:l.length,rollups:u.size}}enforceRetention(e,t){let r=this.downsample(e,t),n=Math.min(3650,Math.max(1,Math.floor(e.rawDays))),o=new Date(this.now().getTime()-n*86400000).toISOString(),a=t?" AND project_id=?":"",l=this.controlPlane.database.run(`DELETE FROM telemetry_records WHERE timestamp<?${a}`,t?[o,t]:[o]).changes,u=Number(this.controlPlane.database.query(`SELECT MAX(0, COUNT(*)-?) excess FROM telemetry_records${t?" WHERE project_id=?":""}`).get(e.maxRecords,...t?[t]:[])?.excess??0);if(u>0)this.controlPlane.database.run(`DELETE FROM telemetry_records WHERE id IN (SELECT id FROM telemetry_records${t?" WHERE project_id=?":""} ORDER BY timestamp ASC LIMIT ?)`,t?[t,u]:[u]);return this.rebuildStatusRollups(t),{deleted:l+u,...r}}rebuildStatusRollups(e){let t=e?" WHERE project_id=?":"",r=e?[e]:[];this.controlPlane.database.transaction(()=>{this.controlPlane.database.run(`DELETE FROM telemetry_source_rollups${t}`,r),this.controlPlane.database.run(`INSERT INTO telemetry_source_rollups (
|
|
1542
|
+
${JSON.stringify(t,null,2)}`}),{ok:!0,status:202}}if(e.kind==="sms"){if(!this.options.smsImpl)return{ok:!1,error:"SMS adapter is not configured."};let g=e.config.to;if(typeof g!=="string"||!g.trim())return{ok:!1,error:"SMS channels need a `to` number."};return await this.options.smsImpl({to:g,from:e.config.from,text:n.slice(0,300)}),{ok:!0,status:202}}let o=r.url??r.value,a=t,l={"content-type":"application/json"};if(e.kind==="slack")a={text:n};if(e.kind==="discord")a={content:n};if(e.kind==="teams")a={text:n};if(e.kind==="telegram")o=`https://api.telegram.org/bot${r.botToken??r.value}/sendMessage`,a={chat_id:e.config.chatId,text:n};if(!o||!/^https:\/\//.test(o))return{ok:!1,error:"Channel endpoint is unavailable or not HTTPS."};let u=JSON.stringify(a);if(e.kind==="webhook"&&r.signingSecret){let g=Math.floor(this.now().getTime()/1000).toString();l["x-ts-cloud-timestamp"]=g,l["x-ts-cloud-signature"]=`v1=${vn("sha256",r.signingSecret).update(`${g}.${u}`).digest("hex")}`}let p=new AbortController,E=setTimeout(()=>p.abort(),1e4);try{let g=await this.fetchImpl(o,{method:"POST",headers:l,body:u,signal:p.signal});return g.ok?{ok:!0,status:g.status}:{ok:!1,status:g.status,error:`Channel returned HTTP ${g.status}.`}}finally{clearTimeout(E)}}catch(o){return{ok:!1,error:o instanceof Error?o.message:String(o)}}}async deliver(e){let t=this.store.getDelivery(e);if(!t)throw Error("Notification delivery was not found.");if(t.state==="delivered"||t.state==="dead"||t.nextAttemptAt&&t.nextAttemptAt>this.now().toISOString())return t;let r=this.store.getChannel(t.channelId);if(!r||r.status==="disabled"||r.status==="paused")return this.store.updateDelivery(e,{state:"failed",attempt:t.attempt+1,error:"Notification channel is unavailable."});let n=t.attempt+1,o=await this.send(r,t.payload);if(o.ok)return this.store.setChannelStatus(r.id,"active"),this.store.updateDelivery(e,{state:"delivered",attempt:n,responseStatus:o.status,deliveredAt:this.now().toISOString()});let l=!(!o.status||o.status===429||o.status>=500)||n>=t.maxAttempts,u=l?void 0:new Date(this.now().getTime()+Math.min(3600000,30000*2**(n-1))).toISOString();return this.store.setChannelStatus(r.id,"failing",o.error),this.store.updateDelivery(e,{state:l?"dead":"retrying",attempt:n,nextAttemptAt:u,responseStatus:o.status,error:o.error})}async deliverAll(e){return Promise.all(e.map((t)=>this.deliver(t.id)))}async retryDue(){let e=this.now().toISOString(),t=this.store.listDeliveries({states:["pending","retrying"]}).filter((r)=>!r.nextAttemptAt||r.nextAttemptAt<=e);return this.deliverAll(t)}async testChannel(e){let t=this.store.getChannel(e);if(!t)throw Error("Notification channel was not found.");let r=await this.send(t,{schemaVersion:1,event:"test",message:"ts-cloud notification channel test. No incident was created."});return this.store.markChannelTest(e,r.ok,r.error),r}}import{lookup as Cn}from"node:dns/promises";import{connect as An}from"node:net";async function On(e,t){let r=Bun.spawn(e,{stdout:"pipe",stderr:"pipe"}),n=setTimeout(()=>r.kill(),t);try{return{exitCode:await r.exited,stdout:await new Response(r.stdout).text(),stderr:await new Response(r.stderr).text()}}finally{clearTimeout(n)}}class Qe{store;options;constructor(e,t={}){this.store=e;this.options=t}now(){return this.options.now?.()??new Date}async probe(e){let t=performance.now(),r=this.now().toISOString(),n=this.options.agent??"local";try{if(e.kind==="http"){let l=new URL(e.target),u=performance.now();await(this.options.lookupImpl??Cn)(l.hostname);let p=performance.now()-u,E=new AbortController,g=setTimeout(()=>E.abort(),e.timeoutSeconds*1000);try{let m=performance.now(),T=await(this.options.fetchImpl??fetch)(l.toString(),{method:e.config.method??"GET",headers:e.config.headers,signal:E.signal,redirect:"manual"}),h=performance.now()-m,_=e.config.expectedBody?await T.text():"",N=e.config.expectedStatuses??[200,201,202,204],y=N.includes(T.status)&&(!e.config.expectedBody||_.includes(e.config.expectedBody));return{checkId:e.id,status:y?"healthy":"unhealthy",agent:n,region:this.options.region,statusCode:T.status,message:y?void 0:`Expected ${N.join("/")} and configured body match.`,timings:{dnsMs:p,ttfbMs:h,totalMs:performance.now()-t},checkedAt:r}}finally{clearTimeout(g)}}if(e.kind==="tcp"){let l=Number(e.config.port);if(!Number.isInteger(l)||l<1||l>65535)throw Error("TCP health check requires a valid port.");let u=performance.now();return await new Promise((p,E)=>{let g=An({host:e.target,port:l}),m=setTimeout(()=>{g.destroy(),E(Error("TCP health check timed out."))},e.timeoutSeconds*1000);g.once("connect",()=>{clearTimeout(m),g.destroy(),p()}),g.once("error",(T)=>{clearTimeout(m),E(T)})}),{checkId:e.id,status:"healthy",agent:n,region:this.options.region,timings:{connectMs:performance.now()-u,totalMs:performance.now()-t},checkedAt:r}}let o=e.config.command??[];if(!o.length)throw Error("Command health check is not configured.");let a=await(this.options.commandImpl??On)(o,e.timeoutSeconds*1000);return{checkId:e.id,status:a.exitCode===0?"healthy":"unhealthy",agent:n,region:this.options.region,message:a.exitCode===0?void 0:(a.stderr||a.stdout||`Command exited ${a.exitCode}`).slice(0,1000),timings:{totalMs:performance.now()-t},checkedAt:r}}catch(o){return{checkId:e.id,status:"unhealthy",agent:n,region:this.options.region,message:(o instanceof Error?o.message:String(o)).slice(0,1000),timings:{totalMs:performance.now()-t},checkedAt:r}}}async run(e){return this.store.appendHealthResult(await this.probe(e))}async runAndEvaluate(e){let t=await this.run(e),r=new Nr(this.store),n=this.store.listRules(e.projectId,e.environmentId).filter((o)=>o.healthCheckId===e.id);return{result:t,evaluations:n.map((o)=>r.evaluate(o,{status:t.status,timestamp:t.checkedAt,group:{agent:t.agent,region:t.region??""},evidence:{healthResultId:t.id,statusCode:t.statusCode??null,message:t.message??null,timings:t.timings}}))}}}var mf=Object.freeze({rawDays:30,downsampleAfterDays:7,downsampleBucketMs:3600000,maxRecords:1e6,samplingRate:1,collectLogs:!0,collectTraces:!0,collectRequestAnalytics:!0,estimatedStorageUsdPerGbMonth:0});function we(e,t,r,n){let o=Number(e);return Number.isFinite(o)?Math.min(n,Math.max(r,Math.floor(o))):t}function Wt(e,t,r,n){let o=Number(e);return Number.isFinite(o)?Math.min(n,Math.max(r,o)):t}function ot(e,t){return typeof e==="boolean"?e:t}function Np(e,t={...mf}){let r=e&&typeof e==="object"&&!Array.isArray(e)?e:{},n=we(r.rawDays,t.rawDays,1,3650),o=we(r.downsampleAfterDays,t.downsampleAfterDays,1,n);return{rawDays:n,downsampleAfterDays:o,downsampleBucketMs:we(r.downsampleBucketMs,t.downsampleBucketMs,60000,86400000),maxRecords:we(r.maxRecords,t.maxRecords,1000,1e8),samplingRate:Wt(r.samplingRate,t.samplingRate,0.01,1),collectLogs:ot(r.collectLogs,t.collectLogs),collectTraces:ot(r.collectTraces,t.collectTraces),collectRequestAnalytics:ot(r.collectRequestAnalytics,t.collectRequestAnalytics),estimatedStorageUsdPerGbMonth:Wt(r.estimatedStorageUsdPerGbMonth,t.estimatedStorageUsdPerGbMonth,0,1e4)}}function kp(e){return`telemetry.policy:${e}`}function Mt(e,t){return Np(e.getSetting(kp(t)))}function td(e,t,r){let n=Np(r,Mt(e,t));return e.setSetting(kp(t),n),n}function rd(e,t){return Number((Math.max(0,e)/1073741824*t.estimatedStorageUsdPerGbMonth).toFixed(4))}var Un=/(?:authorization|cookie|password|passwd|secret|token|api[_-]?key|private[_-]?key|access[_-]?key|session)/i,Dn=/\b(?:authorization|cookie|password|passwd|secret|token|api[_-]?key|private[_-]?key|access[_-]?key)\s*[=:]\s*[^\s,;&\[]+/gi,wn=/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi,kn=/\b(?:\d{1,3}\.){3}\d{1,3}\b/g;function nd(e,t={}){let r=e.replace(/([?&][^=&#\s]+)=([^&#\s]*)/g,"$1=[REDACTED]").replace(Dn,"[REDACTED]");if(t.redactEmail!==!1)r=r.replace(wn,"[EMAIL]");if(t.redactIp)r=r.replace(kn,"[IP]");for(let n of t.patterns??[])r=r.replace(n,"[REDACTED]");return r}function pi(e,t={},r){if(r&&Un.test(r))return"[REDACTED]";if(e===null||typeof e==="boolean"||typeof e==="number")return e;if(typeof e==="string")return nd(e,t);if(Array.isArray(e))return e.map((n)=>pi(n,t));if(e&&typeof e==="object"){let n={};for(let[o,a]of Object.entries(e))n[o]=pi(a,t,o);return n}return String(e??"")}function gi(e){if(!e)return;return e.split("?",1)[0].replace(/\b[0-9a-f]{8}-[0-9a-f-]{27,}\b/gi,":id").replace(/\/(?:(?:\d{4,})|(?:[0-9a-f]{16,}))(?:\/|$)/gi,(r)=>r.endsWith("/")?"/:id/":"/:id").slice(0,512)}var Jt=65536,Xn=2678400000,Pn=new Set(["metric","log","trace","request","event"]);function P(e){return typeof e==="string"?e:void 0}function ue(e){return e==null?void 0:Number(e)}function xn(e){if(typeof e!=="string")return{};try{return JSON.parse(e)}catch{return{}}}function ke(e){return{id:String(e.id),projectId:String(e.project_id),environmentId:P(e.environment_id),resourceId:P(e.resource_id),kind:String(e.kind),source:String(e.source),name:String(e.name),timestamp:String(e.timestamp),observedAt:String(e.observed_at),value:ue(e.value),unit:P(e.unit),level:P(e.level),message:P(e.message),durationMs:ue(e.duration_ms),statusCode:ue(e.status_code),method:P(e.method),host:P(e.host),pathTemplate:P(e.path_template),bytesIn:ue(e.bytes_in),bytesOut:ue(e.bytes_out),region:P(e.region),cacheResult:P(e.cache_result),upstream:P(e.upstream),traceId:P(e.trace_id),requestId:P(e.request_id),deploymentId:P(e.deployment_id),releaseId:P(e.release_id),workloadId:P(e.workload_id),sampled:Number(e.sampled)===1,attributes:xn(e.attributes),ingestedBytes:Number(e.ingested_bytes)}}function Z(e,t){let r=new Date(e);if(!e||!Number.isFinite(r.getTime()))throw Error(`${t} must be a valid ISO-8601 instant.`);return r}function Xe(e){let t=Z(e.from,"from"),r=Z(e.to,"to");if(t>=r)throw Error("Telemetry from must be earlier than to.");if(r.getTime()-t.getTime()>Xn)throw Error("Telemetry queries are limited to 31 days.");return{from:t,to:r}}function Zt(e){if(!e)return;try{let t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));if(typeof t?.timestamp!=="string"||typeof t?.id!=="string")throw Error();return t}catch{throw Error("Telemetry cursor is invalid.")}}function mi(e){return e?Buffer.from(JSON.stringify({timestamp:e.timestamp,id:e.id})).toString("base64url"):void 0}function hf(e,t){if(!e.length)return;let r=[...e].sort((o,a)=>o-a),n=Math.max(0,Math.min(r.length-1,Math.ceil(t/100*r.length)-1));return r[n]}function pe(e,t){if(t==="count")return e.length;if(!e.length)return;if(t==="sum")return e.reduce((r,n)=>r+n,0);if(t==="avg")return e.reduce((r,n)=>r+n,0)/e.length;if(t==="min")return Math.min(...e);if(t==="max")return Math.max(...e);return hf(e,Number(t.slice(1)))}function ff(e,t="UTC"){try{return new Intl.DateTimeFormat("en-US",{timeZone:t,month:"short",day:"2-digit",hour:"2-digit",minute:"2-digit",hourCycle:"h23",timeZoneName:"short"}).format(e)}catch{throw Error(`Unknown telemetry timezone: ${t}`)}}class lt{controlPlane;options;constructor(e,t={}){this.controlPlane=e;this.options=t}now(){return this.options.now?.()??new Date}append(e){if(!Pn.has(e.kind))throw Error(`Unsupported telemetry kind: ${e.kind}`);let t=Z(e.timestamp,"timestamp").toISOString(),r=e.observedAt?Z(e.observedAt,"observedAt").toISOString():this.now().toISOString(),n=pi(e.attributes??{},this.options.redaction),o=e.message?nd(e.message,this.options.redaction).slice(0,32768):void 0,a=gi(e.pathTemplate),l=e.id??crypto.randomUUID(),u=JSON.stringify({...e,id:l,timestamp:t,observedAt:r,attributes:n,message:o,pathTemplate:a}),p=Buffer.byteLength(u);if(p>Jt)throw Error(`Telemetry records are limited to ${Jt} bytes.`);return this.controlPlane.database.run("INSERT OR IGNORE INTO telemetry_records (id, project_id, environment_id, resource_id, kind, source, name, timestamp, observed_at, value, unit, level, message, duration_ms, status_code, method, host, path_template, bytes_in, bytes_out, region, cache_result, upstream, trace_id, request_id, deployment_id, release_id, workload_id, sampled, attributes, ingested_bytes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[l,e.projectId,e.environmentId??null,e.resourceId??null,e.kind,e.source.slice(0,128),e.name.slice(0,256),t,r,e.value??null,e.unit??null,e.level??null,o??null,e.durationMs??null,e.statusCode??null,e.method?.slice(0,16)??null,e.host?.slice(0,256)??null,a??null,e.bytesIn??null,e.bytesOut??null,e.region?.slice(0,64)??null,e.cacheResult?.slice(0,64)??null,e.upstream?.slice(0,256)??null,e.traceId?.slice(0,256)??null,e.requestId?.slice(0,256)??null,e.deploymentId?.slice(0,256)??null,e.releaseId?.slice(0,256)??null,e.workloadId?.slice(0,512)??null,e.sampled===!1?0:1,JSON.stringify(n),p]),this.get(l)}appendMany(e){if(e.length>1e4)throw Error("Telemetry batches are limited to 10,000 records.");return this.controlPlane.database.transaction((r)=>r.map((n)=>this.append(n)))(e)}get(e){let t=this.controlPlane.database.query("SELECT * FROM telemetry_records WHERE id=?").get(e);return t?ke(t):void 0}query(e){let{from:t,to:r}=Xe(e),n=Math.min(5000,Math.max(1,Math.floor(e.limit??500))),o=["project_id=?","timestamp>=?","timestamp<?"],a=[e.projectId,t.toISOString(),r.toISOString()],l=(L,v)=>{if(v)o.push(`${L}=?`),a.push(v)},u=(L,v)=>{let I=[...new Set(v??[])].slice(0,100);if(I.length)o.push(`${L} IN (${I.map(()=>"?").join(",")})`),a.push(...I)};if(l("environment_id",e.environmentId),u("resource_id",e.resourceIds),u("kind",e.kinds),u("name",e.names),u("source",e.sources),u("level",e.levels),l("trace_id",e.traceId),l("request_id",e.requestId),l("deployment_id",e.deploymentId),l("release_id",e.releaseId),l("workload_id",e.workloadId),e.text)o.push("(message LIKE ? OR name LIKE ?)"),a.push(`%${e.text.slice(0,256)}%`,`%${e.text.slice(0,256)}%`);let p=Zt(e.cursor);if(p)o.push("(timestamp<? OR (timestamp=? AND id<?))"),a.push(p.timestamp,p.timestamp,p.id);let E=this.controlPlane.database.query(`SELECT * FROM telemetry_records WHERE ${o.join(" AND ")} ORDER BY timestamp DESC, id DESC LIMIT ?`).all(...a,n+1),g=E.slice(0,n).map(ke),m=E.length>n,T=new Map;for(let L of g)T.set(L.source,[...T.get(L.source)??[],L]);let h=this.now().getTime(),_=[...T].map(([L,v])=>{let I=v.reduce((k,O)=>O.observedAt>k?O.observedAt:k,v[0].observedAt),A=h-new Date(I).getTime();return{source:L,latestAt:I,freshness:A<=120000?"live":A<=600000?"stale":"unavailable",count:v.length}}),N=Math.max(60000,(r.getTime()-t.getTime())/100),y=[...T].flatMap(([L,v])=>{let I=[...new Set(v.map((A)=>new Date(A.timestamp).getTime()))].sort((A,k)=>A-k);return I.slice(1).flatMap((A,k)=>A-I[k]>N?[{from:new Date(I[k]).toISOString(),to:new Date(A).toISOString(),source:L}]:[])});return{records:g,nextCursor:m?mi(g.at(-1)):void 0,truncated:m,scannedRange:{from:t.toISOString(),to:r.toISOString()},sources:_,gaps:y}}tail(e,t){let{from:r,to:n}=Xe(e),o=Math.min(1000,Math.max(1,Math.floor(e.limit??200))),a=["project_id=?","timestamp>=?","timestamp<?"],l=[e.projectId,r.toISOString(),n.toISOString()],u=(T,h)=>{if(h)a.push(`${T}=?`),l.push(h)},p=(T,h)=>{let _=[...new Set(h??[])].slice(0,100);if(_.length)a.push(`${T} IN (${_.map(()=>"?").join(",")})`),l.push(..._)};if(u("environment_id",e.environmentId),p("resource_id",e.resourceIds),p("kind",e.kinds),p("name",e.names),p("source",e.sources),p("level",e.levels),u("trace_id",e.traceId),u("request_id",e.requestId),u("deployment_id",e.deploymentId),u("release_id",e.releaseId),u("workload_id",e.workloadId),e.text)a.push("(message LIKE ? OR name LIKE ?)"),l.push(`%${e.text.slice(0,256)}%`,`%${e.text.slice(0,256)}%`);let E=Zt(t);if(E)a.push("(timestamp>? OR (timestamp=? AND id>?))"),l.push(E.timestamp,E.timestamp,E.id);let g=this.controlPlane.database.query(`SELECT * FROM telemetry_records WHERE ${a.join(" AND ")} ORDER BY timestamp ASC, id ASC LIMIT ?`).all(...l,o+1),m=g.slice(0,o).map(ke);return{records:m,cursor:mi(m.at(-1))??t,truncated:g.length>o}}series(e){let{from:t,to:r}=Xe(e),n=Math.min(86400000,Math.max(1000,Math.floor(e.bucketMs)));if((r.getTime()-t.getTime())/n>2000)throw Error("Telemetry series are limited to 2,000 buckets.");let o=this.query({...e,kinds:["metric"],limit:5000,cursor:void 0}),a=new Map;for(let u of o.records)a.set(`${u.source}\x00${u.name}`,[...a.get(`${u.source}\x00${u.name}`)??[],u]);let l=(u,p,E)=>{let g=new Map;for(let T of u){let h=p.getTime()+Math.floor((new Date(T.timestamp).getTime()-p.getTime())/n)*n;if(h>=p.getTime()&&h<E.getTime()&&T.value!=null)g.set(h,[...g.get(h)??[],T.value])}let m=[];for(let T=p.getTime();T<E.getTime();T+=n){let h=g.get(T)??[],_=pe(h,e.aggregation);m.push({timestamp:new Date(T).toISOString(),label:ff(new Date(T),e.timezone),value:_,count:h.length,gap:_==null})}return m};return[...a].map(([u,p])=>{let[E,g]=u.split("\x00"),m={name:g,source:E,unit:p.find((T)=>T.unit)?.unit,aggregation:e.aggregation,bucketMs:n,points:l(p,t,r)};if(e.compareFrom&&e.compareTo){let T=this.query({...e,from:e.compareFrom,to:e.compareTo,kinds:["metric"],limit:5000,cursor:void 0}).records.filter((h)=>h.source===E&&h.name===g);m.comparison=l(T,Z(e.compareFrom,"compareFrom"),Z(e.compareTo,"compareTo"))}return m})}status(e,t,r=30,n=1,o){let a=[e],l=t?" AND environment_id=?":"";if(t)a.push(t);let u=[...new Set(o??[])].slice(0,100);if(o&&u.length===0)return[];let p=o?` AND resource_id IN (${u.map(()=>"?").join(",")||"''"})`:"";a.push(...u);let E=this.controlPlane.database.query(`SELECT source, MAX(latest_observed_at) latest, SUM(ingested_bytes) bytes, SUM(record_count) count, MIN(first_observed_at) first FROM telemetry_source_rollups WHERE project_id=?${l}${p} GROUP BY source`).all(...a),g=this.now().getTime();return E.map((m)=>{let T=String(m.latest),h=Math.max(0,Math.floor((g-new Date(T).getTime())/1000)),_=Math.max(1,(new Date(T).getTime()-new Date(String(m.first)).getTime())/86400000);return{source:String(m.source),freshness:h<=120?"live":h<=600?"stale":"unavailable",lastObservedAt:T,lagSeconds:h,samplingRate:n,retentionDays:r,estimatedDailyBytes:Math.round(Number(m.bytes)/_)}})}saveQuery(e,t,r,n){let o=r.trim().slice(0,80);if(!o)throw Error("Saved telemetry queries require a name.");if(Xe(n),n.projectId!==e)throw Error("Saved telemetry queries cannot cross project scope.");let a=this.now().toISOString(),l=JSON.stringify(pi(n,this.options.redaction));if(Buffer.byteLength(l)>16384)throw Error("Saved telemetry queries are limited to 16 KB.");let u=this.controlPlane.database.query("SELECT * FROM telemetry_saved_queries WHERE project_id=? AND actor_id IS ? AND name=?").get(e,t??null,o),p=u?String(u.id):crypto.randomUUID();return this.controlPlane.database.run("INSERT INTO telemetry_saved_queries (id, project_id, actor_id, name, query, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(project_id, actor_id, name) DO UPDATE SET query=excluded.query, updated_at=excluded.updated_at",[p,e,t??null,o,l,u?String(u.created_at):a,a]),{id:p,projectId:e,actorId:t,name:o,query:JSON.parse(l),createdAt:u?String(u.created_at):a,updatedAt:a}}listSavedQueries(e,t){return this.controlPlane.database.query("SELECT * FROM telemetry_saved_queries WHERE project_id=? AND actor_id IS ? ORDER BY updated_at DESC").all(e,t??null).map((r)=>({id:String(r.id),projectId:String(r.project_id),actorId:P(r.actor_id),name:String(r.name),query:JSON.parse(String(r.query)),createdAt:String(r.created_at),updatedAt:String(r.updated_at)}))}deleteSavedQuery(e,t,r){return this.controlPlane.database.run("DELETE FROM telemetry_saved_queries WHERE id=? AND project_id=? AND actor_id IS ?",[r,e,t??null]).changes>0}downsample(e,t){let r=Math.min(86400000,Math.max(60000,Math.floor(e.downsampleBucketMs))),n=new Date(this.now().getTime()-Math.max(1,e.downsampleAfterDays)*86400000).toISOString(),o=new Date(this.now().getTime()-Math.max(1,e.rawDays)*86400000).toISOString(),a=this.controlPlane.database.query(`SELECT * FROM telemetry_records WHERE kind='metric' AND source NOT LIKE '%:rollup' AND timestamp>=? AND timestamp<?${t?" AND project_id=?":""} ORDER BY timestamp ASC LIMIT 50001`).all(o,n,...t?[t]:[]);if(a.length>50000)throw Error("Telemetry downsampling is limited to 50,000 raw points per pass; run compaction more frequently.");let l=a.map(ke),u=new Map;for(let E of l){let g=Math.floor(new Date(E.timestamp).getTime()/r)*r,m=JSON.stringify([E.projectId,E.environmentId??"",E.resourceId??"",E.source,E.name,E.unit??"",g]);u.set(m,[...u.get(m)??[],E])}return this.controlPlane.database.transaction(()=>{for(let E=0;E<l.length;E+=500){let g=l.slice(E,E+500).map((m)=>m.id);if(g.length)this.controlPlane.database.run(`DELETE FROM telemetry_records WHERE id IN (${g.map(()=>"?").join(",")})`,g)}for(let[E,g]of u){let[m,T,h,_,N,y,L]=JSON.parse(E),v=g.flatMap((I)=>I.value==null?[]:[I.value]);this.append({projectId:m,environmentId:T||void 0,resourceId:h||void 0,kind:"metric",source:`${_}:rollup`,name:N,unit:y||void 0,timestamp:new Date(L).toISOString(),value:pe(v,"avg"),attributes:{downsampled:!0,count:v.length,min:pe(v,"min"),max:pe(v,"max"),p95:pe(v,"p95"),bucketMs:r}})}})(),{compacted:l.length,rollups:u.size}}enforceRetention(e,t){let r=this.downsample(e,t),n=Math.min(3650,Math.max(1,Math.floor(e.rawDays))),o=new Date(this.now().getTime()-n*86400000).toISOString(),a=t?" AND project_id=?":"",l=this.controlPlane.database.run(`DELETE FROM telemetry_records WHERE timestamp<?${a}`,t?[o,t]:[o]).changes,u=Number(this.controlPlane.database.query(`SELECT MAX(0, COUNT(*)-?) excess FROM telemetry_records${t?" WHERE project_id=?":""}`).get(e.maxRecords,...t?[t]:[])?.excess??0);if(u>0)this.controlPlane.database.run(`DELETE FROM telemetry_records WHERE id IN (SELECT id FROM telemetry_records${t?" WHERE project_id=?":""} ORDER BY timestamp ASC LIMIT ?)`,t?[t,u]:[u]);return this.rebuildStatusRollups(t),{deleted:l+u,...r}}rebuildStatusRollups(e){let t=e?" WHERE project_id=?":"",r=e?[e]:[];this.controlPlane.database.transaction(()=>{this.controlPlane.database.run(`DELETE FROM telemetry_source_rollups${t}`,r),this.controlPlane.database.run(`INSERT INTO telemetry_source_rollups (
|
|
1543
1543
|
project_id, environment_id, resource_id, source,
|
|
1544
1544
|
first_observed_at, latest_observed_at, ingested_bytes, record_count
|
|
1545
1545
|
)
|
|
@@ -1547,14 +1547,14 @@ ${JSON.stringify(t,null,2)}`}),{ok:!0,status:202}}if(e.kind==="sms"){if(!this.op
|
|
|
1547
1547
|
project_id, COALESCE(environment_id, ''), COALESCE(resource_id, ''), source,
|
|
1548
1548
|
MIN(observed_at), MAX(observed_at), SUM(ingested_bytes), COUNT(*)
|
|
1549
1549
|
FROM telemetry_records${t}
|
|
1550
|
-
GROUP BY project_id, COALESCE(environment_id, ''), COALESCE(resource_id, ''), source`,r)})()}}function js(e,t,r,n=new Date){let o=new lt(e.controlPlane,{now:()=>n}),a=new Nr(e);return e.listRules(t,r).filter((l)=>l.enabled&&!l.healthCheckId).map((l)=>{let u=new Date(n.getTime()-l.windowMs).toISOString(),p=o.query({projectId:t,environmentId:r,resourceIds:l.resourceId?[l.resourceId]:void 0,kinds:["metric"],names:[l.signal],from:u,to:new Date(n.getTime()+1).toISOString(),limit:5000}),E=p.records.flatMap((m)=>m.value==null?[]:[m.value]),g=E.length?l.operator==="gt"||l.operator==="gte"?Math.max(...E):l.operator==="lt"||l.operator==="lte"?Math.min(...E):E.at(0):void 0;return a.evaluate(l,{value:g,status:g==null?"no_data":void 0,timestamp:n.toISOString(),group:{resourceId:l.resourceId??"",source:p.records[0]?.source??""},evidence:{signal:l.signal,windowMs:l.windowMs,sampleCount:E.length,source:p.records[0]?.source??null}})})}var lf=["spend.enforced"];function jn(e){if(e.level==="hard_capped")return"critical";if(e.level==="soft_capped")return"warning";return"info"}function kr(e,t="USD"){let r=e/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:t}).format(r)}catch{return`${r.toFixed(2)} ${t}`}}function Tp(e,t,r){let n=kr(t.projection.actualCents,e.currency),o=e.hardLimitCents??e.softLimitCents,a=o==null?"":` of ${kr(o,e.currency)}`,l=t.simulated?" [dry run]":"";if(r==="spend.released")return`[RESOLVED] ${e.name}: spend fell back to ${n}${a}.${l}`;if(r==="spend.enforced"){let E=t.actions.filter((g)=>g!=="notify").join(", ");return`[CAP] ${e.name}: ${n}${a} (${t.usedPercent.toFixed(0)}%). Enforcing ${E||"notifications only"}.${l}`}let u=Rr(t.projection.timeToExhaustionMs),p=u?` Projected to reach the limit in ${u}.`:` Projected ${kr(t.projection.projectedCents,e.currency)} by period end.`;return`[SPEND] ${e.name}: ${n}${a} (${t.usedPercent.toFixed(0)}%).${p}${l}`}function er(e,t,r){return{schemaVersion:1,event:r,notificationText:Tp(e,t,r),spend:{budgetId:e.id,budgetName:e.name,organizationId:e.organizationId,projectId:e.projectId??null,environmentId:e.environmentId??null,period:e.period,currency:e.currency,level:t.level,simulated:t.simulated,usedPercent:Math.round(t.usedPercent*10)/10,projectedPercent:Math.round(t.projectedPercent*10)/10,actualCents:Math.round(t.projection.actualCents),projectedCents:Math.round(t.projection.projectedCents),projectionConfidence:t.projection.confidence,softLimitCents:e.softLimitCents??null,hardLimitCents:e.hardLimitCents??null,timeToCap:Rr(t.projection.timeToExhaustionMs),actions:t.actions,window:{start:t.window.start,end:t.window.end,label:t.window.label},reason:t.reason}}}function Fn(e,t){return{schemaVersion:1,event:"spend.anomaly",notificationText:`[ANOMALY] Hourly spend ${Number.isFinite(e.deltaPercent)?`${e.deltaPercent>0?"+":""}${e.deltaPercent.toFixed(0)}%`:"new"} vs the usual ${kr(e.expected,t)} for this hour (observed ${kr(e.observed,t)}).`,spend:{anomalyId:e.id,organizationId:e.organizationId,projectId:e.projectId??null,environmentId:e.environmentId??null,signal:e.signal,direction:e.direction,severity:e.severity,observedCents:Math.round(e.observed),expectedCents:Math.round(e.expected),score:Math.round(e.score*10)/10,bucketStart:e.bucketStart}}}function Mn(e,t,r,n){let o=e.matcher;if(o.projectIds?.length&&(!t.projectId||!o.projectIds.includes(t.projectId)))return!1;if(o.environmentIds?.length&&(!t.environmentId||!o.environmentIds.includes(t.environmentId)))return!1;if(o.severities?.length&&!o.severities.includes(r))return!1;if(o.eventTypes?.length&&!o.eventTypes.includes(n))return!1;return!0}class zs{store;options;constructor(e,t={}){this.store=e;this.options=t}now(){return this.options.now?.()??new Date}channelsFor(e,t,r,n){let o=[];for(let a of this.store.listRoutes(e)){if(!a.enabled||!Mn(a,t,r,n))continue;let l=a.channelIds.map((u)=>this.store.getChannel(u)).filter((u)=>u?.status==="active");o.push({route:a,channels:l,quiet:Vs(a,this.now())})}return o}dispatch(e,t,r,n,o,a){let l=[],u=[];for(let p of this.channelsFor(e,t,r,n)){if(p.quiet&&n!=="spend.released"){u.push(p.route.id);continue}let E=this.store.countRouteDeliveries(p.route.id,new Date(this.now().getTime()-60000).toISOString()),g=Math.max(0,p.route.rateLimitPerMinute-E);for(let m of p.channels){if(g<=0)break;l.push(this.store.createDelivery({channelId:m.id,routeId:p.route.id,eventType:n,idempotencyKey:`spend:${n}:${a}:${m.id}`,payload:o,nextAttemptAt:p.route.groupWaitSeconds===0?void 0:new Date(this.now().getTime()+p.route.groupWaitSeconds*1000).toISOString()})),g--}}return{deliveries:l,suppressed:u}}notifyDecision(e,t){if(t.breaches.length===0)return{deliveries:[],suppressed:[]};let n=t.actions.some((a)=>a!=="notify")?"spend.enforced":"spend.threshold",o=t.breaches[t.breaches.length-1].atPercent;return this.dispatch(e.organizationId,{projectId:e.projectId,environmentId:e.environmentId},jn(t),n,er(e,t,n),`${e.id}:${t.window.start}:${o}`)}notifyRelease(e,t,r){if(r.length===0)return{deliveries:[],suppressed:[]};return this.dispatch(e.organizationId,{projectId:e.projectId,environmentId:e.environmentId},"info","spend.released",{...er(e,t,"spend.released"),released:[...r]},`${e.id}:${t.window.start}:${[...r].sort().join("+")}`)}notifyAnomaly(e,t="USD"){return this.dispatch(e.organizationId,{projectId:e.projectId,environmentId:e.environmentId},e.severity,"spend.anomaly",Fn(e,t),e.id)}}var uf="spend.loop.lease";function zn(){return`${typeof process>"u"?"unknown":String(process.pid)}:${crypto.randomUUID().slice(0,8)}`}class wp{controlPlane;owner;ttlMs;constructor(e,t={}){this.controlPlane=e;this.owner=t.owner??zn(),this.ttlMs=Math.max(5000,(t.ttlSeconds??120)*1000),this.nowFn=t.now??(()=>new Date)}nowFn;read(){let e=this.controlPlane.getSetting("spend.loop.lease");if(!e||typeof e!=="object"||Array.isArray(e))return;let t=e;if(typeof t.owner!=="string"||typeof t.expiresAt!=="string")return;return t}current(){let e=this.read();if(!e)return;return new Date(e.expiresAt).getTime()>this.nowFn().getTime()?e:void 0}acquire(){let e=this.nowFn();return this.controlPlane.database.transaction(()=>{let r=this.read(),n=r&&new Date(r.expiresAt).getTime()>e.getTime();if(n&&r.owner!==this.owner)return!1;let o={owner:this.owner,acquiredAt:n?r.acquiredAt:e.toISOString(),expiresAt:new Date(e.getTime()+this.ttlMs).toISOString()};return this.controlPlane.setSetting("spend.loop.lease",o),!0})()}release(){return this.controlPlane.database.transaction(()=>{let t=this.read();if(!t||t.owner!==this.owner)return!1;return this.controlPlane.setSetting("spend.loop.lease",null),!0})()}held(){return this.current()?.owner===this.owner}}var tr={applied:0,duplicates:0,costCents:0,unpricedMeters:[]};class Rp{options;gate;service;notifications;constructor(e){this.options=e;this.gate=new Pr(e.controlPlane,{now:e.now}),this.service=new $t(e.store),this.notifications=e.alerts?new zs(e.alerts,{now:e.now}):void 0}now(){return this.options.now?.()??new Date}ingest(e,t,r){if(t.length===0)return{...tr};return this.service.ingestTelemetry(e,t,r)}async run(e,t=[]){let r=this.now(),n=[],o={scope:e,ingested:{...tr},decisions:[],applied:[],released:[],failed:[],withheld:[],anomalies:[],notificationsSent:0,ranAt:r.toISOString(),durationMs:0,warnings:n};try{if(o.ingested=this.ingest(e.organizationId,t),o.ingested.unpricedMeters.length>0)n.push(`No price entry for ${o.ingested.unpricedMeters.join(", ")}; that usage is metered but counts as zero against every budget.`)}catch(u){n.push(`Usage ingest failed: ${Ee(u)}`)}let a=Yc({gate:this.gate,transport:this.options.transport}),l;try{l=await this.service.runCycle({organizationId:e.organizationId,projectId:e.projectId,environmentId:e.environmentId,environmentKind:e.environmentKind,policy:this.options.policy,now:r,handlers:a})}catch(u){return n.push(`Spend evaluation failed: ${Ee(u)}`),o.durationMs=this.now().getTime()-r.getTime(),o}o.decisions=l.statuses.map((u)=>u.decision),o.anomalies=l.anomalies;for(let u of l.enforcement)o.applied.push(...u.applied.map((p)=>p.action)),o.released.push(...u.released.map((p)=>p.action)),o.failed.push(...u.failed),o.withheld.push(...u.withheld.map((p)=>p.action));for(let u of o.failed)n.push(`Enforcement for ${u.action} did not complete: ${u.error}`);if(o.withheld.length>0)n.push(`${o.withheld.join(", ")} require approval on this environment and were not applied automatically.`);try{o.released.push(...this.reconcileGate(e))}catch(u){n.push(`Gate reconciliation failed: ${Ee(u)}`)}if(this.notifications)try{for(let u of l.statuses)if(o.notificationsSent+=this.notifications.notifyDecision(u.budget,u.decision).deliveries.length,u.decision.releases.length>0)o.notificationsSent+=this.notifications.notifyRelease(u.budget,u.decision,u.decision.releases).deliveries.length;for(let u of l.anomalies)o.notificationsSent+=this.notifications.notifyAnomaly(u,this.options.store.priceBook.currency).deliveries.length}catch(u){n.push(`Spend notifications failed: ${Ee(u)}`)}try{this.options.store.pruneUsage(this.options.retentionDays??400,r)}catch(u){n.push(`Usage pruning failed: ${Ee(u)}`)}return o.durationMs=this.now().getTime()-r.getTime(),o}reconcileGate(e){let t=new Map(this.options.store.listBudgets({organizationId:e.organizationId}).filter((n)=>n.enabled).map((n)=>[n.id,n])),r=[];for(let n of this.gate.listUnder({organizationId:e.organizationId})){if(t.has(n.budgetId))continue;this.gate.close(n.budgetId,n.action),r.push(n.action)}return r}async runAll(e=[]){let t=[];for(let r of this.options.controlPlane.listOrganizations()){t.push(await this.run({organizationId:r.id},e));for(let n of this.options.controlPlane.listProjects().filter((o)=>o.organizationId===r.id))for(let o of this.options.controlPlane.listEnvironments(n.id))t.push(await this.run({organizationId:r.id,projectId:n.id,environmentId:o.id,environmentKind:o.kind}))}return t}}function Ee(e){return e instanceof Error?e.message:String(e)}var Dp=60;function pf(e,t={}){let r=Math.max(10,t.intervalSeconds??Dp)*1000,n=!1,o=!1,a=async()=>{if(n||o)return;if(t.lease&&!t.lease.acquire()){t.onSkip?.(t.lease.current()?.owner??"another process");return}n=!0;try{let u=await e.runAll();t.onResult?.(u)}catch(u){t.onError?.(u)}finally{n=!1}},l=setInterval(()=>void a(),r);if(l.unref?.(),t.immediate)a();return()=>{o=!0,clearInterval(l),t.lease?.release()}}function me(e,t){if(t.code!==0)throw Error(`${e} failed (exit ${t.code}): ${t.stderr.trim().slice(0,400)}`)}class Pp{options;constructor(e){this.options=e}async targets(e){let t=await this.options.functions(e);if(t.length===0)throw Error("No Lambda functions were resolved for this scope.");return t}async suspendFunctions(e){let t=await this.targets(e),r={};for(let n of t)r[n]=await this.options.lambda.getFunctionConcurrency(n),await this.options.lambda.putFunctionConcurrency(n,0);return{kind:"lambda_reserved_concurrency",previous:r}}async resumeFunctions(e){let t=e.previous??{};for(let[r,n]of Object.entries(t))if(typeof n==="number")await this.options.lambda.putFunctionConcurrency(r,n);else await this.options.lambda.deleteFunctionConcurrency(r)}async serveStatic(e){return{...await this.suspendFunctions(e),via:"serve_static"}}async restoreDynamic(e){await this.resumeFunctions(e)}async suspendProject(e){let t=await this.targets(e),r={};for(let n of t){let a={...(await this.options.lambda.getFunction(n)).Configuration?.Environment?.Variables??{}};r[n]=a.MAINTENANCE_MODE??null,await this.options.lambda.updateFunctionConfiguration({FunctionName:n,Environment:{Variables:{...a,MAINTENANCE_MODE:"1"}}}),await this.options.republish?.(n)}return{kind:"lambda_maintenance_mode",previous:r}}async resumeProject(e){let t=e.previous??{};for(let r of Object.keys(t)){let o={...(await this.options.lambda.getFunction(r)).Configuration?.Environment?.Variables??{}};o.MAINTENANCE_MODE=typeof t[r]==="string"?t[r]:"0",await this.options.lambda.updateFunctionConfiguration({FunctionName:r,Environment:{Variables:o}}),await this.options.republish?.(r)}}}class Np{options;constructor(e){this.options=e}async unitsFor(e){let t=await this.options.units(e);if(t.length===0)throw Error("No systemd units were resolved for this scope.");for(let r of t)if(!/^[A-Za-z0-9@._-]+$/.test(r))throw Error(`Refusing to act on an unsafe unit name: ${r}`);return t}async stopUnits(e,t){let r=await this.unitsFor(e),n=[];for(let o of r){let a=await this.options.exec(this.options.host,`systemctl list-units --plain --no-legend --state=active --type=service '${o}@*.service' '${o}.service' 2>/dev/null | awk '{print $1}'`);me(`listing units for ${o}`,a);let l=a.stdout.split(`
|
|
1551
|
-
`).map((u)=>u.trim()).filter((u)=>/^[A-Za-z0-9@._-]+\.service$/.test(u));for(let u of l){let p=await this.options.exec(this.options.host,`systemctl stop '${u}'`);me(`stopping ${u}`,p),n.push(u)}}return{kind:"systemd_units",via:t,stopped:n}}async startUnits(e){let t=Array.isArray(e.stopped)?e.stopped:[];for(let r of t){if(!/^[A-Za-z0-9@._-]+$/.test(r))continue;let n=await this.options.exec(this.options.host,`systemctl start '${r}'`);me(`starting ${r}`,n)}}async suspendFunctions(e){return this.stopUnits(e,"suspend_functions")}async resumeFunctions(e){await this.startUnits(e)}async serveStatic(e){return this.stopUnits(e,"serve_static")}async restoreDynamic(e){await this.startUnits(e)}async suspendProject(e){return this.stopUnits(e,"suspend_project")}async resumeProject(e){await this.startUnits(e)}async throttleRequests(e){let t=this.options.renderDdos,r=this.options.ddos;if(!t||!r)throw Error("Request throttling needs a DDoS config and renderer on this transport.");let n={rateLimitFactor:e.factor},o={...r.thresholds,newConnectionsPerSecond:
|
|
1550
|
+
GROUP BY project_id, COALESCE(environment_id, ''), COALESCE(resource_id, ''), source`,r)})()}}function Ks(e,t,r,n=new Date){let o=new lt(e.controlPlane,{now:()=>n}),a=new Nr(e);return e.listRules(t,r).filter((l)=>l.enabled&&!l.healthCheckId).map((l)=>{let u=new Date(n.getTime()-l.windowMs).toISOString(),p=o.query({projectId:t,environmentId:r,resourceIds:l.resourceId?[l.resourceId]:void 0,kinds:["metric"],names:[l.signal],from:u,to:new Date(n.getTime()+1).toISOString(),limit:5000}),E=p.records.flatMap((m)=>m.value==null?[]:[m.value]),g=E.length?l.operator==="gt"||l.operator==="gte"?Math.max(...E):l.operator==="lt"||l.operator==="lte"?Math.min(...E):E.at(0):void 0;return a.evaluate(l,{value:g,status:g==null?"no_data":void 0,timestamp:n.toISOString(),group:{resourceId:l.resourceId??"",source:p.records[0]?.source??""},evidence:{signal:l.signal,windowMs:l.windowMs,sampleCount:E.length,source:p.records[0]?.source??null}})})}var Af=["spend.enforced"];function jn(e){if(e.level==="hard_capped")return"critical";if(e.level==="soft_capped")return"warning";return"info"}function kr(e,t="USD"){let r=e/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:t}).format(r)}catch{return`${r.toFixed(2)} ${t}`}}function Bp(e,t,r){let n=kr(t.projection.actualCents,e.currency),o=e.hardLimitCents??e.softLimitCents,a=o==null?"":` of ${kr(o,e.currency)}`,l=t.simulated?" [dry run]":"";if(r==="spend.released")return`[RESOLVED] ${e.name}: spend fell back to ${n}${a}.${l}`;if(r==="spend.enforced"){let E=t.actions.filter((g)=>g!=="notify").join(", ");return`[CAP] ${e.name}: ${n}${a} (${t.usedPercent.toFixed(0)}%). Enforcing ${E||"notifications only"}.${l}`}let u=Rr(t.projection.timeToExhaustionMs),p=u?` Projected to reach the limit in ${u}.`:` Projected ${kr(t.projection.projectedCents,e.currency)} by period end.`;return`[SPEND] ${e.name}: ${n}${a} (${t.usedPercent.toFixed(0)}%).${p}${l}`}function er(e,t,r){return{schemaVersion:1,event:r,notificationText:Bp(e,t,r),spend:{budgetId:e.id,budgetName:e.name,organizationId:e.organizationId,projectId:e.projectId??null,environmentId:e.environmentId??null,period:e.period,currency:e.currency,level:t.level,simulated:t.simulated,usedPercent:Math.round(t.usedPercent*10)/10,projectedPercent:Math.round(t.projectedPercent*10)/10,actualCents:Math.round(t.projection.actualCents),projectedCents:Math.round(t.projection.projectedCents),projectionConfidence:t.projection.confidence,softLimitCents:e.softLimitCents??null,hardLimitCents:e.hardLimitCents??null,timeToCap:Rr(t.projection.timeToExhaustionMs),actions:t.actions,window:{start:t.window.start,end:t.window.end,label:t.window.label},reason:t.reason}}}function Fn(e,t){return{schemaVersion:1,event:"spend.anomaly",notificationText:`[ANOMALY] Hourly spend ${Number.isFinite(e.deltaPercent)?`${e.deltaPercent>0?"+":""}${e.deltaPercent.toFixed(0)}%`:"new"} vs the usual ${kr(e.expected,t)} for this hour (observed ${kr(e.observed,t)}).`,spend:{anomalyId:e.id,organizationId:e.organizationId,projectId:e.projectId??null,environmentId:e.environmentId??null,signal:e.signal,direction:e.direction,severity:e.severity,observedCents:Math.round(e.observed),expectedCents:Math.round(e.expected),score:Math.round(e.score*10)/10,bucketStart:e.bucketStart}}}function Mn(e,t,r,n){let o=e.matcher;if(o.projectIds?.length&&(!t.projectId||!o.projectIds.includes(t.projectId)))return!1;if(o.environmentIds?.length&&(!t.environmentId||!o.environmentIds.includes(t.environmentId)))return!1;if(o.severities?.length&&!o.severities.includes(r))return!1;if(o.eventTypes?.length&&!o.eventTypes.includes(n))return!1;return!0}class Ws{store;options;constructor(e,t={}){this.store=e;this.options=t}now(){return this.options.now?.()??new Date}channelsFor(e,t,r,n){let o=[];for(let a of this.store.listRoutes(e)){if(!a.enabled||!Mn(a,t,r,n))continue;let l=a.channelIds.map((u)=>this.store.getChannel(u)).filter((u)=>u?.status==="active");o.push({route:a,channels:l,quiet:zs(a,this.now())})}return o}dispatch(e,t,r,n,o,a){let l=[],u=[];for(let p of this.channelsFor(e,t,r,n)){if(p.quiet&&n!=="spend.released"){u.push(p.route.id);continue}let E=this.store.countRouteDeliveries(p.route.id,new Date(this.now().getTime()-60000).toISOString()),g=Math.max(0,p.route.rateLimitPerMinute-E);for(let m of p.channels){if(g<=0)break;l.push(this.store.createDelivery({channelId:m.id,routeId:p.route.id,eventType:n,idempotencyKey:`spend:${n}:${a}:${m.id}`,payload:o,nextAttemptAt:p.route.groupWaitSeconds===0?void 0:new Date(this.now().getTime()+p.route.groupWaitSeconds*1000).toISOString()})),g--}}return{deliveries:l,suppressed:u}}notifyDecision(e,t){if(t.breaches.length===0)return{deliveries:[],suppressed:[]};let n=t.actions.some((a)=>a!=="notify")?"spend.enforced":"spend.threshold",o=t.breaches[t.breaches.length-1].atPercent;return this.dispatch(e.organizationId,{projectId:e.projectId,environmentId:e.environmentId},jn(t),n,er(e,t,n),`${e.id}:${t.window.start}:${o}`)}notifyRelease(e,t,r){if(r.length===0)return{deliveries:[],suppressed:[]};return this.dispatch(e.organizationId,{projectId:e.projectId,environmentId:e.environmentId},"info","spend.released",{...er(e,t,"spend.released"),released:[...r]},`${e.id}:${t.window.start}:${[...r].sort().join("+")}`)}notifyAnomaly(e,t="USD"){return this.dispatch(e.organizationId,{projectId:e.projectId,environmentId:e.environmentId},e.severity,"spend.anomaly",Fn(e,t),e.id)}}var yf="spend.loop.lease";function zn(){return`${typeof process>"u"?"unknown":String(process.pid)}:${crypto.randomUUID().slice(0,8)}`}class _p{controlPlane;owner;ttlMs;constructor(e,t={}){this.controlPlane=e;this.owner=t.owner??zn(),this.ttlMs=Math.max(5000,(t.ttlSeconds??120)*1000),this.nowFn=t.now??(()=>new Date)}nowFn;read(){let e=this.controlPlane.getSetting("spend.loop.lease");if(!e||typeof e!=="object"||Array.isArray(e))return;let t=e;if(typeof t.owner!=="string"||typeof t.expiresAt!=="string")return;return t}current(){let e=this.read();if(!e)return;return new Date(e.expiresAt).getTime()>this.nowFn().getTime()?e:void 0}acquire(){let e=this.nowFn();return this.controlPlane.database.transaction(()=>{let r=this.read(),n=r&&new Date(r.expiresAt).getTime()>e.getTime();if(n&&r.owner!==this.owner)return!1;let o={owner:this.owner,acquiredAt:n?r.acquiredAt:e.toISOString(),expiresAt:new Date(e.getTime()+this.ttlMs).toISOString()};return this.controlPlane.setSetting("spend.loop.lease",o),!0})()}release(){return this.controlPlane.database.transaction(()=>{let t=this.read();if(!t||t.owner!==this.owner)return!1;return this.controlPlane.setSetting("spend.loop.lease",null),!0})()}held(){return this.current()?.owner===this.owner}}var tr={applied:0,duplicates:0,costCents:0,unpricedMeters:[]};class xp{options;gate;service;notifications;constructor(e){this.options=e;this.gate=new Pr(e.controlPlane,{now:e.now}),this.service=new $t(e.store),this.notifications=e.alerts?new Ws(e.alerts,{now:e.now}):void 0}now(){return this.options.now?.()??new Date}ingest(e,t,r){if(t.length===0)return{...tr};return this.service.ingestTelemetry(e,t,r)}async run(e,t=[]){let r=this.now(),n=[],o={scope:e,ingested:{...tr},decisions:[],applied:[],released:[],failed:[],withheld:[],anomalies:[],notificationsSent:0,ranAt:r.toISOString(),durationMs:0,warnings:n};try{if(o.ingested=this.ingest(e.organizationId,t),o.ingested.unpricedMeters.length>0)n.push(`No price entry for ${o.ingested.unpricedMeters.join(", ")}; that usage is metered but counts as zero against every budget.`)}catch(u){n.push(`Usage ingest failed: ${Ee(u)}`)}let a=ed({gate:this.gate,transport:this.options.transport}),l;try{l=await this.service.runCycle({organizationId:e.organizationId,projectId:e.projectId,environmentId:e.environmentId,environmentKind:e.environmentKind,policy:this.options.policy,now:r,handlers:a})}catch(u){return n.push(`Spend evaluation failed: ${Ee(u)}`),o.durationMs=this.now().getTime()-r.getTime(),o}o.decisions=l.statuses.map((u)=>u.decision),o.anomalies=l.anomalies;for(let u of l.enforcement)o.applied.push(...u.applied.map((p)=>p.action)),o.released.push(...u.released.map((p)=>p.action)),o.failed.push(...u.failed),o.withheld.push(...u.withheld.map((p)=>p.action));for(let u of o.failed)n.push(`Enforcement for ${u.action} did not complete: ${u.error}`);if(o.withheld.length>0)n.push(`${o.withheld.join(", ")} require approval on this environment and were not applied automatically.`);try{o.released.push(...this.reconcileGate(e))}catch(u){n.push(`Gate reconciliation failed: ${Ee(u)}`)}if(this.notifications)try{for(let u of l.statuses)if(o.notificationsSent+=this.notifications.notifyDecision(u.budget,u.decision).deliveries.length,u.decision.releases.length>0)o.notificationsSent+=this.notifications.notifyRelease(u.budget,u.decision,u.decision.releases).deliveries.length;for(let u of l.anomalies)o.notificationsSent+=this.notifications.notifyAnomaly(u,this.options.store.priceBook.currency).deliveries.length}catch(u){n.push(`Spend notifications failed: ${Ee(u)}`)}try{this.options.store.pruneUsage(this.options.retentionDays??400,r)}catch(u){n.push(`Usage pruning failed: ${Ee(u)}`)}return o.durationMs=this.now().getTime()-r.getTime(),o}reconcileGate(e){let t=new Map(this.options.store.listBudgets({organizationId:e.organizationId}).filter((n)=>n.enabled).map((n)=>[n.id,n])),r=[];for(let n of this.gate.listUnder({organizationId:e.organizationId})){if(t.has(n.budgetId))continue;this.gate.close(n.budgetId,n.action),r.push(n.action)}return r}async runAll(e=[]){let t=[];for(let r of this.options.controlPlane.listOrganizations()){t.push(await this.run({organizationId:r.id},e));for(let n of this.options.controlPlane.listProjects().filter((o)=>o.organizationId===r.id))for(let o of this.options.controlPlane.listEnvironments(n.id))t.push(await this.run({organizationId:r.id,projectId:n.id,environmentId:o.id,environmentKind:o.kind}))}return t}}function Ee(e){return e instanceof Error?e.message:String(e)}var Op=60;function If(e,t={}){let r=Math.max(10,t.intervalSeconds??Op)*1000,n=!1,o=!1,a=async()=>{if(n||o)return;if(t.lease&&!t.lease.acquire()){t.onSkip?.(t.lease.current()?.owner??"another process");return}n=!0;try{let u=await e.runAll();t.onResult?.(u)}catch(u){t.onError?.(u)}finally{n=!1}},l=setInterval(()=>void a(),r);if(l.unref?.(),t.immediate)a();return()=>{o=!0,clearInterval(l),t.lease?.release()}}function me(e,t){if(t.code!==0)throw Error(`${e} failed (exit ${t.code}): ${t.stderr.trim().slice(0,400)}`)}class Lp{options;constructor(e){this.options=e}async targets(e){let t=await this.options.functions(e);if(t.length===0)throw Error("No Lambda functions were resolved for this scope.");return t}async suspendFunctions(e){let t=await this.targets(e),r={};for(let n of t)r[n]=await this.options.lambda.getFunctionConcurrency(n),await this.options.lambda.putFunctionConcurrency(n,0);return{kind:"lambda_reserved_concurrency",previous:r}}async resumeFunctions(e){let t=e.previous??{};for(let[r,n]of Object.entries(t))if(typeof n==="number")await this.options.lambda.putFunctionConcurrency(r,n);else await this.options.lambda.deleteFunctionConcurrency(r)}async serveStatic(e){return{...await this.suspendFunctions(e),via:"serve_static"}}async restoreDynamic(e){await this.resumeFunctions(e)}async suspendProject(e){let t=await this.targets(e),r={};for(let n of t){let a={...(await this.options.lambda.getFunction(n)).Configuration?.Environment?.Variables??{}};r[n]=a.MAINTENANCE_MODE??null,await this.options.lambda.updateFunctionConfiguration({FunctionName:n,Environment:{Variables:{...a,MAINTENANCE_MODE:"1"}}}),await this.options.republish?.(n)}return{kind:"lambda_maintenance_mode",previous:r}}async resumeProject(e){let t=e.previous??{};for(let r of Object.keys(t)){let o={...(await this.options.lambda.getFunction(r)).Configuration?.Environment?.Variables??{}};o.MAINTENANCE_MODE=typeof t[r]==="string"?t[r]:"0",await this.options.lambda.updateFunctionConfiguration({FunctionName:r,Environment:{Variables:o}}),await this.options.republish?.(r)}}}class $p{options;constructor(e){this.options=e}async unitsFor(e){let t=await this.options.units(e);if(t.length===0)throw Error("No systemd units were resolved for this scope.");for(let r of t)if(!/^[A-Za-z0-9@._-]+$/.test(r))throw Error(`Refusing to act on an unsafe unit name: ${r}`);return t}async stopUnits(e,t){let r=await this.unitsFor(e),n=[];for(let o of r){let a=await this.options.exec(this.options.host,`systemctl list-units --plain --no-legend --state=active --type=service '${o}@*.service' '${o}.service' 2>/dev/null | awk '{print $1}'`);me(`listing units for ${o}`,a);let l=a.stdout.split(`
|
|
1551
|
+
`).map((u)=>u.trim()).filter((u)=>/^[A-Za-z0-9@._-]+\.service$/.test(u));for(let u of l){let p=await this.options.exec(this.options.host,`systemctl stop '${u}'`);me(`stopping ${u}`,p),n.push(u)}}return{kind:"systemd_units",via:t,stopped:n}}async startUnits(e){let t=Array.isArray(e.stopped)?e.stopped:[];for(let r of t){if(!/^[A-Za-z0-9@._-]+$/.test(r))continue;let n=await this.options.exec(this.options.host,`systemctl start '${r}'`);me(`starting ${r}`,n)}}async suspendFunctions(e){return this.stopUnits(e,"suspend_functions")}async resumeFunctions(e){await this.startUnits(e)}async serveStatic(e){return this.stopUnits(e,"serve_static")}async restoreDynamic(e){await this.startUnits(e)}async suspendProject(e){return this.stopUnits(e,"suspend_project")}async resumeProject(e){await this.startUnits(e)}async throttleRequests(e){let t=this.options.renderDdos,r=this.options.ddos;if(!t||!r)throw Error("Request throttling needs a DDoS config and renderer on this transport.");let n={rateLimitFactor:e.factor},o={...r.thresholds,newConnectionsPerSecond:_r(r.thresholds?.newConnectionsPerSecond??50,n),concurrentPerSource:_r(r.thresholds?.concurrentPerSource??100,n)},a=t({...r,thresholds:o}),l=await this.options.exec(this.options.host,`bash -s <<'TS_CLOUD_THROTTLE_EOF'
|
|
1552
1552
|
${a}
|
|
1553
1553
|
TS_CLOUD_THROTTLE_EOF`);return me("applying the throttled firewall ruleset",l),{kind:"nftables_throttle",factor:e.factor,previousThresholds:r.thresholds??{}}}async restoreRequests(e){let t=this.options.renderDdos,r=this.options.ddos;if(!t||!r)return;let n=e.previousThresholds??{},o=t({...r,thresholds:n}),a=await this.options.exec(this.options.host,`bash -s <<'TS_CLOUD_THROTTLE_EOF'
|
|
1554
1554
|
${o}
|
|
1555
|
-
TS_CLOUD_THROTTLE_EOF`);me("restoring the firewall ruleset",a)}}function
|
|
1555
|
+
TS_CLOUD_THROTTLE_EOF`);me("restoring the firewall ruleset",a)}}function Sf(e){let t=async(n,o)=>{let a={},l,u=0;for(let[p,E]of e.entries()){let g=E[n];if(!g)continue;u++;try{a[String(p)]=await g.call(E,o)}catch(m){a[String(p)]={error:m instanceof Error?m.message:String(m)},l??=m}}if(u===0)throw Error(`No transport implements ${n}.`);if(l)throw l;return{kind:"composite",legs:a}},r=async(n,o)=>{let a=o.legs??{},l;for(let[u,p]of e.entries()){let E=p[n];if(!E)continue;let g=a[String(u)];if(!g||typeof g!=="object"||Array.isArray(g)||"error"in g)continue;try{await E.call(p,g)}catch(m){l??=m}}if(l)throw l};return{throttleRequests:(n)=>t("throttleRequests",n),restoreRequests:(n)=>r("restoreRequests",n),suspendFunctions:(n)=>t("suspendFunctions",n),resumeFunctions:(n)=>r("resumeFunctions",n),serveStatic:(n)=>t("serveStatic",n),restoreDynamic:(n)=>r("restoreDynamic",n),suspendProject:(n)=>t("suspendProject",n),resumeProject:(n)=>r("resumeProject",n)}}import{createHash as Xi}from"node:crypto";class ii extends Error{constructor(){super("Operation cancellation was requested")}}class ks extends Error{timeoutSeconds;constructor(e){super(`Operation exceeded its ${e}s timeout`);this.timeoutSeconds=e}}class X extends Error{errorClass;constructor(e,t){super(e);this.errorClass=t}}var Pe={project:2,environment:1,provider:2,builds:1},qn=30,rr=16384,Hn=["succeeded","failed","cancelled","timed_out"],st=new Map,nr=new WeakMap;function ir(e){if(e.path===":memory:"){let n=nr.get(e);if(n)return n;let o=new Set;return nr.set(e,o),o}let t=st.get(e.path);if(t)return t;let r=new Set;return st.set(e.path,r),r}function J(e){return typeof e==="string"&&e?e:void 0}function Bn(e){try{let t=JSON.parse(String(e));return Array.isArray(t)?t.map(String):[]}catch{return[]}}function Vn(e){return{operationId:String(e.operation_id),lockKey:J(e.lock_key),providerKey:J(e.provider_key),buildSlot:Number(e.build_slot)===1,maxAttempts:Number(e.max_attempts),availableAt:String(e.available_at),timeoutSeconds:Number(e.timeout_seconds),heartbeatAt:J(e.heartbeat_at),currentStep:J(e.current_step),blockedReason:J(e.blocked_reason),retryClasses:Bn(e.retry_classes),resumePolicy:String(e.resume_policy),cancellationMode:String(e.cancellation_mode),retentionUntil:String(e.retention_until),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function or(e){return{sequence:Number(e.sequence),id:String(e.id),operationId:String(e.operation_id),stream:String(e.stream),step:J(e.step),message:String(e.message),redacted:Number(e.redacted)===1,truncated:Number(e.truncated)===1,createdAt:String(e.created_at)}}function q(e,t,r){return Number.isFinite(e)?Math.min(r,Math.max(1,Math.floor(e))):t}class c{controlPlane;nowFn;idFn;workerId;leaseMs;limits;constructor(e,t={}){this.controlPlane=e;this.workerId=t.workerId??`worker:${process.pid}:${crypto.randomUUID()}`,this.leaseMs=q(t.leaseMs,60000,3600000),this.nowFn=t.now??(()=>new Date),this.idFn=t.id??(()=>crypto.randomUUID());let r=e.getSetting("queue.concurrency");this.limits={project:q(t.limits?.project??r?.project,Pe.project,100),environment:q(t.limits?.environment??r?.environment,Pe.environment,100),provider:q(t.limits?.provider??r?.provider,Pe.provider,100),builds:q(t.limits?.builds??r?.builds,Pe.builds,100)}}now(){return this.nowFn().toISOString()}leaseExpiry(){return new Date(this.nowFn().getTime()+this.leaseMs).toISOString()}enqueue(e){let t=this.controlPlane.createOperation(e);if(this.getJob(t.id))return this.view(t.id);let n=this.now(),o=q(e.maxAttempts,1,20),a=q(e.timeoutSeconds,1800,86400),l=q(e.retentionDays,qn,3650),u=e.availableAt?new Date(e.availableAt).toISOString():n,p=new Date(this.nowFn().getTime()+l*24*60*60*1000).toISOString();this.controlPlane.database.run(`INSERT OR IGNORE INTO operation_jobs (operation_id, lock_key, provider_key, build_slot, max_attempts, available_at, timeout_seconds, retry_classes, resume_policy, cancellation_mode, retention_until, created_at, updated_at)
|
|
1556
1556
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[t.id,e.lockKey??e.resourceId??null,e.providerKey??null,e.buildSlot?1:0,o,u,a,JSON.stringify([...new Set(e.retryClasses??[])]),e.resumePolicy??"fail",e.cancellationMode??"cooperative",p,n,n]),this.appendLog(t.id,"Queued for durable execution.",{stream:"system"});let E=this.view(t.id);return this.notifyAvailable(),E}onAvailable(e){let t=ir(this.controlPlane);return t.add(e),()=>{if(t.delete(e),t.size===0&&this.controlPlane.path!==":memory:")st.delete(this.controlPlane.path)}}notifyAvailable(){for(let e of ir(this.controlPlane))e()}getJob(e){let t=this.controlPlane.database.query("SELECT * FROM operation_jobs WHERE operation_id=?").get(e);return t?Vn(t):void 0}view(e){let t=this.controlPlane.getOperation(e),r=this.getJob(e);if(!t||!r)return;let n;if(t.state==="queued")n={ahead:Number(this.controlPlane.database.query("SELECT COUNT(*) AS count FROM operations o JOIN operation_jobs j ON j.operation_id=o.id WHERE o.state='queued' AND j.available_at<=? AND (o.priority>? OR (o.priority=? AND o.created_at<?))").get(this.now(),t.priority,t.priority,t.createdAt)?.count??0),precision:"bounded"};return{operation:t,job:r,approximatePosition:n}}list(e={}){return this.controlPlane.listOperations({projectId:e.projectId,state:e.state,limit:e.limit??200}).map((t)=>this.view(t.id)).filter((t)=>!!t)}configureConcurrency(e,t={}){let r={project:q(e.project,this.limits.project,100),environment:q(e.environment,this.limits.environment,100),provider:q(e.provider,this.limits.provider,100),builds:q(e.builds,this.limits.builds,100)};return Object.assign(this.limits,r),this.controlPlane.setSetting("queue.concurrency",r),this.controlPlane.appendEvent({organizationId:t.organizationId,actorId:t.actorId,type:"queue.concurrency.updated",level:"warning",payload:r}),r}runningCount(e,t){return Number(this.controlPlane.database.query(e).get(...t)?.count??0)}blockReason(e,t){if(t.lockKey){if(this.controlPlane.database.query("SELECT * FROM operation_locks WHERE lock_key=? AND operation_id!=? AND lease_expires_at>?").get(t.lockKey,e.id,this.now()))return`resource_lock:${t.lockKey}`}if(e.projectId&&this.runningCount("SELECT COUNT(*) AS count FROM operations WHERE state='running' AND project_id=?",[e.projectId])>=this.limits.project)return"project_concurrency";if(e.environmentId&&this.runningCount("SELECT COUNT(*) AS count FROM operations WHERE state='running' AND environment_id=?",[e.environmentId])>=this.limits.environment)return"environment_concurrency";if(t.providerKey&&this.runningCount("SELECT COUNT(*) AS count FROM operations o JOIN operation_jobs j ON j.operation_id=o.id WHERE o.state='running' AND j.provider_key=?",[t.providerKey])>=this.limits.provider)return"provider_concurrency";if(t.buildSlot&&this.runningCount("SELECT COUNT(*) AS count FROM operations o JOIN operation_jobs j ON j.operation_id=o.id WHERE o.state='running' AND j.build_slot=1",[])>=this.limits.builds)return"build_concurrency";return}claim(e){return this.controlPlane.transaction(()=>{let t=this.now();this.controlPlane.database.run("DELETE FROM operation_locks WHERE lease_expires_at<=?",[t]);let r=this.controlPlane.getOperation(e),n=r?this.getJob(r.id):void 0;if(!r||!n||r.state!=="queued"||n.availableAt>t)return;if(r.cancelRequestedAt){this.controlPlane.transitionOperation(r.id,{to:"cancelled",expectedVersion:r.version,output:{cancelledBeforeStart:!0}}),this.appendLog(r.id,"Cancelled before execution began.",{stream:"system"});return}let o=this.blockReason(r,n);if(o){this.controlPlane.database.run("UPDATE operation_jobs SET blocked_reason=?, updated_at=? WHERE operation_id=?",[o,t,r.id]);return}let a=this.controlPlane.claimOperation(r.id,this.workerId,this.leaseMs);if(!a)return;let l=a.leaseExpiresAt??this.leaseExpiry();if(n.lockKey)this.controlPlane.database.run("INSERT INTO operation_locks (lock_key, operation_id, lease_owner, lease_expires_at, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)",[n.lockKey,r.id,this.workerId,l,t,t]);return this.controlPlane.database.run("UPDATE operation_jobs SET heartbeat_at=?, blocked_reason=NULL, updated_at=? WHERE operation_id=?",[t,t,r.id]),this.appendLog(r.id,`Claimed by ${this.workerId}; attempt ${a.attempt}.`,{stream:"system"}),this.view(r.id)})}claimNext(e){let t=this.now(),r=e?.length?`AND o.kind IN (${e.map(()=>"?").join(",")})`:"",n=this.controlPlane.database.query(`SELECT o.id FROM operations o JOIN operation_jobs j ON j.operation_id=o.id WHERE o.state='queued' AND j.available_at<=? ${r} ORDER BY o.priority DESC, o.created_at ASC, o.rowid ASC LIMIT 100`).all(t,...e??[]);for(let o of n){let a=this.claim(String(o.id));if(a)return a}return}heartbeat(e,t){let r=this.controlPlane.getOperation(e);if(!r||r.state!=="running"||r.leaseOwner!==this.workerId)throw Error("Operation lease is not owned by this worker");let n=this.now(),o=this.leaseExpiry(),a=this.getJob(e);if(this.controlPlane.database.run("UPDATE operations SET lease_expires_at=?, updated_at=?, version=version+1 WHERE id=? AND state='running' AND lease_owner=? AND version=?",[o,n,e,this.workerId,r.version]).changes!==1)throw Error("Operation lease changed before heartbeat");if(this.controlPlane.database.run("UPDATE operation_jobs SET heartbeat_at=?, current_step=COALESCE(?, current_step), updated_at=? WHERE operation_id=?",[n,t??null,n,e]),a?.lockKey)this.controlPlane.database.run("UPDATE operation_locks SET lease_expires_at=?, updated_at=? WHERE lock_key=? AND operation_id=? AND lease_owner=?",[o,n,a.lockKey,e,this.workerId]);if(t&&t!==a?.currentStep)this.controlPlane.appendEvent({projectId:r.projectId,operationId:e,resourceId:r.resourceId,actorId:r.actorId,correlationId:r.correlationId,type:"operation.step",payload:{step:t}})}appendLog(e,t,r={}){if(!this.getJob(e))throw Error(`Queue job ${e} was not found`);let n=t,o=!1;for(let g of r.secrets??[])if(g&&n.includes(g))n=n.split(g).join("[REDACTED]"),o=!0;let a=s({message:n});if(a.message!==n)o=!0;n=a.message??"[output unavailable]";let l=Buffer.from(n),u=l.byteLength>rr;if(u)n=`${l.subarray(0,rr-32).toString("utf8")}
|
|
1557
|
-
[output truncated]`;let p=this.idFn(),E=this.now();return this.controlPlane.database.run("INSERT INTO operation_logs (id, operation_id, stream, step, message, redacted, truncated, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",[p,e,r.stream??"stdout",r.step??null,n,o?1:0,u?1:0,E]),or(this.controlPlane.database.query("SELECT * FROM operation_logs WHERE id=?").get(p))}logs(e,t={}){let r=Math.min(1000,Math.max(1,t.limit??200));return this.controlPlane.database.query("SELECT * FROM operation_logs WHERE operation_id=? AND sequence>? ORDER BY sequence ASC LIMIT ?").all(e,t.after??0,r).map(or)}requestCancellation(e,t){let r=this.controlPlane.getOperation(e);if(!r||Hn.includes(r.state))throw Error("Only queued or running operations can be cancelled");let n=this.controlPlane.requestCancellation(e);if(this.controlPlane.appendEvent({projectId:r.projectId,operationId:e,resourceId:r.resourceId,actorId:t,correlationId:r.correlationId,type:"operation.cancellation_requested",level:"warning",payload:{state:r.state}}),this.appendLog(e,r.state==="queued"?"Cancellation accepted before execution.":"Cancellation requested; waiting for the current provider step.",{stream:"system"}),n.state==="queued")return this.finish(e,"cancelled",{cancelledBeforeStart:!0});return n}retry(e,t,r={}){let n=this.controlPlane.getOperation(e),o=this.getJob(e);if(!n||!o||!["failed","cancelled","timed_out"].includes(n.state))throw Error("Only failed, cancelled, or timed-out queue jobs can be retried");if(n.attempt>=o.maxAttempts)throw Error(`Operation reached its ${o.maxAttempts}-attempt limit`);if(!o.retryClasses.includes(t))throw Error(`Retry class ${t} is not allowed for this operation`);let a=this.controlPlane.transitionOperation(e,{to:"queued",expectedVersion:n.version,error:`Retry requested after ${t}`}),l=new Date(this.nowFn().getTime()+Math.max(0,r.delayMs??0)).toISOString();this.controlPlane.database.run("UPDATE operations SET cancel_requested_at=NULL, finished_at=NULL WHERE id=?",[e]),this.controlPlane.database.run("UPDATE operation_jobs SET available_at=?, blocked_reason=NULL, updated_at=? WHERE operation_id=?",[l,this.now(),e]),this.controlPlane.appendEvent({projectId:n.projectId,operationId:e,resourceId:n.resourceId,actorId:r.actorId,correlationId:n.correlationId,type:"operation.retry_requested",payload:{errorClass:t,availableAt:l,nextAttempt:n.attempt+1}}),this.appendLog(e,`Retry queued for error class ${t}.`,{stream:"system"});let u=this.controlPlane.getOperation(a.id);return this.notifyAvailable(),u}release(e){this.controlPlane.database.run("DELETE FROM operation_locks WHERE operation_id=?",[e])}finish(e,t,r={},n){let o=this.controlPlane.getOperation(e);if(!o)throw Error(`Operation ${e} was not found`);let a=this.controlPlane.transitionOperation(e,{to:t,expectedVersion:o.version,output:r,error:n});return this.release(e),a}complete(e,t={}){let r=this.controlPlane.getOperation(e);if(!r||r.state!=="running"||r.leaseOwner!==this.workerId)throw Error("Only the lease owner can complete a running operation");return this.appendLog(e,"Operation completed successfully.",{stream:"system"}),this.finish(e,"succeeded",t)}fail(e,t,r={}){let n=this.controlPlane.getOperation(e);if(!n||n.state!=="running"||n.leaseOwner!==this.workerId)throw Error("Only the lease owner can fail a running operation");return this.appendLog(e,t,{stream:"stderr"}),this.finish(e,"failed",r,t)}async runOne(e){let t=this.claimNext(Object.keys(e));if(!t)return{handled:!1};let{operation:r,job:n}=t,o=e[r.kind];if(!o)return{handled:!1};let a=new AbortController,l=!1,u=setTimeout(()=>{l=!0,a.abort(new Ps(n.timeoutSeconds))},n.timeoutSeconds*1000),p=setInterval(()=>{try{this.heartbeat(r.id)}catch{}},Math.max(250,Math.floor(this.leaseMs/3))),E=setInterval(()=>{if(this.controlPlane.getOperation(r.id)?.cancelRequestedAt)a.abort(new ni)},100),g={operation:r,signal:a.signal,log:(m,T)=>this.appendLog(r.id,m,T),checkpoint:(m,T)=>{this.heartbeat(r.id,m),this.appendLog(r.id,T??m,{stream:"step",step:m})},heartbeat:()=>this.heartbeat(r.id),cancellationRequested:()=>!!this.controlPlane.getOperation(r.id)?.cancelRequestedAt,throwIfCancellationRequested:()=>{if(this.controlPlane.getOperation(r.id)?.cancelRequestedAt)throw new ni}};try{let m=await Promise.race([o(g),new Promise((h,f)=>a.signal.addEventListener("abort",()=>f(a.signal.reason),{once:!0}))]);if(this.controlPlane.getOperation(r.id).cancelRequestedAt){let h=n.cancellationMode==="provider_non_cancellable";return this.appendLog(r.id,h?"Provider step completed after cancellation was requested; reconciliation is required.":"Operation cancelled cooperatively.",{stream:"system"}),{handled:!0,operation:this.finish(r.id,"cancelled",{providerCompleted:h,reconciliationRequired:h}),terminalState:"cancelled"}}return{handled:!0,operation:this.complete(r.id,m??{}),terminalState:"succeeded"}}catch(m){if(l||m instanceof Ps)return this.appendLog(r.id,`Timed out after ${n.timeoutSeconds}s.`,{stream:"system"}),{handled:!0,operation:this.finish(r.id,"timed_out",{reconciliationRequired:n.cancellationMode==="provider_non_cancellable"},m instanceof Error?m.message:String(m)),terminalState:"timed_out"};if(m instanceof ni||this.controlPlane.getOperation(r.id)?.cancelRequestedAt)return{handled:!0,operation:this.finish(r.id,"cancelled",{cooperativelyCancelled:!0}),terminalState:"cancelled"};if(m instanceof X&&n.retryClasses.includes(m.errorClass)&&r.attempt<n.maxAttempts){let h=this.controlPlane.getOperation(r.id);this.controlPlane.transitionOperation(r.id,{to:"queued",expectedVersion:h.version,error:m.message});let f=Math.min(60000,1000*2**Math.max(0,r.attempt-1)),L=new Date(this.nowFn().getTime()+f).toISOString();return this.controlPlane.database.run("UPDATE operation_jobs SET available_at=?, blocked_reason=?, updated_at=? WHERE operation_id=?",[L,`retry_backoff:${m.errorClass}`,this.now(),r.id]),this.release(r.id),this.appendLog(r.id,`Retryable ${m.errorClass} failure; next attempt is delayed.`,{stream:"system"}),{handled:!0,operation:this.controlPlane.getOperation(r.id),requeued:!0}}let T=m instanceof Error?m.message:String(m);return this.appendLog(r.id,T,{stream:"stderr"}),{handled:!0,operation:this.finish(r.id,"failed",{},T),terminalState:"failed"}}finally{clearTimeout(u),clearInterval(p),clearInterval(E)}}recoverExpired(){let e=this.controlPlane.database.query("SELECT o.id FROM operations o JOIN operation_jobs j ON j.operation_id=o.id WHERE o.state='running' AND (o.lease_expires_at IS NULL OR o.lease_expires_at<=?)").all(this.now()),t={requeued:0,failed:0,cancelled:0};for(let r of e){let n=this.controlPlane.getOperation(String(r.id)),o=this.getJob(n.id);if(this.release(n.id),n.cancelRequestedAt){this.finish(n.id,"cancelled",{recoveredAfterWorkerLoss:!0}),t.cancelled++;continue}if(o.resumePolicy==="requeue"&&n.attempt<o.maxAttempts)this.controlPlane.transitionOperation(n.id,{to:"queued",expectedVersion:n.version,error:"Worker lease expired; safely requeued from the last checkpoint."}),this.controlPlane.database.run("UPDATE operation_jobs SET available_at=?, blocked_reason='worker_restart', updated_at=? WHERE operation_id=?",[this.now(),this.now(),n.id]),this.appendLog(n.id,"Worker lease expired; operation requeued from its persisted checkpoint.",{stream:"system"}),t.requeued++;else this.finish(n.id,"failed",{recoverable:!0,lastCheckpoint:o.currentStep??null},"Worker lease expired; retry explicitly after reconciling provider state."),t.failed++}return t}clearCompleted(e={}){let t=this.now(),r=[t],n=e.projectId?"AND o.project_id=?":"";if(e.projectId)r.push(e.projectId);let o=e.before?"AND o.finished_at<=?":"";if(e.before)r.push(new Date(e.before).toISOString());let a=this.controlPlane.database.query(`SELECT o.id, o.project_id, o.correlation_id FROM operations o JOIN operation_jobs j ON j.operation_id=o.id WHERE o.state IN ('succeeded','failed','cancelled','timed_out') AND j.retention_until<=? ${n} ${o}`).all(...r);for(let l of a)this.controlPlane.appendEvent({projectId:J(l.project_id),actorId:e.actorId,correlationId:String(l.correlation_id),type:"queue.history.cleared",level:"warning",payload:{operationId:String(l.id),retentionCutoff:t}}),this.controlPlane.database.run("DELETE FROM operations WHERE id=?",[String(l.id)]);return a.length}}function sr(e,t,r){if(!Number.isFinite(e))return t;return Math.min(r,Math.max(1,Math.floor(e)))}class Ns{queue;handlers;parallelism;pollIntervalMs;onResult;onError;waits=new Map;nextWaitId=0;lanes=[];running=!1;unsubscribeAvailability;constructor(e,t,r={}){this.queue=e;this.handlers=t;this.parallelism=sr(r.parallelism,4,100),this.pollIntervalMs=sr(r.pollIntervalMs,5000,60000),this.onResult=r.onResult,this.onError=r.onError}get active(){return this.running}start(){if(this.running)return this;return this.running=!0,this.unsubscribeAvailability=this.queue.onAvailable(()=>this.wake()),this.lanes=Array.from({length:this.parallelism},(e,t)=>this.runLane(t)),this}stop(){this.running=!1,this.unsubscribeAvailability?.(),this.unsubscribeAvailability=void 0,this.wake()}wake(){for(let{resolve:e,timer:t}of this.waits.values()){if(t)clearTimeout(t);e()}this.waits.clear()}async settled(){await Promise.allSettled(this.lanes)}async drain(){let e=[];while(!0){let t=await Promise.all(Array.from({length:this.parallelism},()=>this.queue.runOne(this.handlers)));if(e.push(...t.filter((r)=>r.handled)),!t.some((r)=>r.handled))return e}}wait(e){return new Promise((t)=>{let r=++this.nextWaitId,n=e?setTimeout(()=>{this.waits.delete(r),t()},this.pollIntervalMs):void 0;n?.unref?.(),this.waits.set(r,{resolve:t,timer:n})})}async runLane(e){while(this.running){try{let t=await this.queue.runOne(this.handlers);if(!this.running)break;if(t.handled){this.onResult?.(t),this.wake();continue}}catch(t){this.onError?.(t)}await this.wait(e===0)}}}import{createHash as Kn}from"node:crypto";var lr=/^[a-z0-9](?:[a-z0-9_.-]{0,62})$/,$n=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,Qn=/(?:secret|token|password|passwd|private.?key|api.?key|credential)/i,Yn=new Set(["image","build","command","entrypoint","environment","ports","volumes","networks","depends_on","healthcheck","restart","deploy","labels"]),ar=new Map([["privileged","Privileged containers are blocked."],["network_mode","Host/custom network modes are blocked."],["pid","Host PID namespaces are blocked."],["ipc","Host IPC namespaces are blocked."],["devices","Device access is blocked."],["cap_add","Additional Linux capabilities require an external policy exception."],["security_opt","Custom security options require an external policy exception."]]);function D(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function pt(e){return Array.isArray(e)?e:e==null?[]:[e]}function Gn(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,63)||"compose-app"}function Te(e){if(Array.isArray(e))return e.map(String);if(typeof e==="string"&&e.trim())return["sh","-c",e];return}function ut(e,t){let r=String(e??""),n=/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/.exec(r);if(!n)return t;let o=Number(n[1]);return Math.max(0,Math.round(o*(n[2]==="ms"?0.001:n[2]==="m"?60:n[2]==="h"?3600:1)))}function dr(e){let t=/^(\d+(?:\.\d+)?)\s*(b|k|kb|kib|m|mb|mib|g|gb|gib)?$/i.exec(String(e??""));if(!t)return;let r=Number(t[1]),n=String(t[2]??"b").toLowerCase(),o=r*(n.startsWith("g")?1073741824:n.startsWith("m")?1048576:n.startsWith("k")?1024:1);return Math.max(1,Math.round(o/1024/1024))}function Wn(e){if(e==null)return"";return/^\$\{([A-Za-z_][A-Za-z0-9_]*)(?::[-?][^}]*)?\}$/.exec(String(e))?.[1]}function ur(e,t,r){let n={},o=Array.isArray(e)?e.map((a)=>{let[l,...u]=String(a).split("=");return[l,u.length?u.join("="):null]}):Object.entries(D(e));for(let[a,l]of o){let u=String(a);if(!$n.test(u)){r.push({severity:"error",path:`${t}.${u}`,code:"environment.name",message:"Environment variable names must use portable shell identifiers."});continue}let p=Wn(l);if(p!==void 0){n[u]={secretRef:p||u};continue}if(Qn.test(u)){r.push({severity:"error",path:`${t}.${u}`,code:"secret.literal",message:"Literal secret-like environment values are not stored.",alternative:`Use \${${u}} and supply ${u} through the secret store.`}),n[u]={secretRef:u};continue}n[u]=String(l??"")}return n}function Jn(e,t,r){let n=[];for(let[o,a]of pt(e).entries()){let l,u,p="tcp";if(typeof a==="number")l=a;else if(typeof a==="string"){let[E,g]=a.split("/");p=g==="udp"?"udp":"tcp";let m=E.split(":");l=Number(m.at(-1)),u=m.length>1?Number(m.at(-2)):void 0}else{let E=D(a);l=Number(E.target),u=E.published==null?void 0:Number(E.published),p=E.protocol==="udp"?"udp":"tcp"}if(!Number.isInteger(l)||l<1||l>65535||u!=null&&(!Number.isInteger(u)||u<1||u>65535))r.push({severity:"error",path:`${t}[${o}]`,code:"port.invalid",message:"Ports must be integers from 1 through 65535."});else n.push({target:l,...u?{published:u}:{},protocol:p})}return n}function Zn(e,t,r,n){let o=[];for(let[a,l]of pt(e).entries()){let u="",p="",E=!1,g="volume";if(typeof l==="string"){let m=l.split(":");u=m[0]??"",p=m[1]??"",E=m.slice(2).includes("ro"),g=u.startsWith("/")||u.startsWith(".")?"bind":"volume"}else{let m=D(l);u=String(m.source??""),p=String(m.target??""),E=m.read_only===!0,g=String(m.type??"volume")}if(g!=="volume"||u.startsWith("/")||u.startsWith(".")){n.push({severity:"error",path:`${r}[${a}]`,code:"volume.host_mount",message:"Host and bind mounts are blocked; use a named volume.",alternative:"Declare the volume at the top level and mount it by name."});continue}if(!lr.test(u)||!p.startsWith("/")){n.push({severity:"error",path:`${r}[${a}]`,code:"volume.invalid",message:"A named source and absolute container target are required."});continue}if(!t.has(u))n.push({severity:"warning",path:`${r}[${a}]`,code:"volume.implicit",message:`Named volume ${u} is implicit and will be declared on export.`});t.add(u),o.push({source:u,target:p,readOnly:E})}return o}function ei(e){return Array.isArray(e)?e.map((t)=>({service:String(t),condition:"service_started"})):Object.entries(D(e)).map(([t,r])=>({service:t,condition:["service_started","service_healthy","service_completed_successfully"].includes(String(D(r).condition))?String(D(r).condition):"service_started"}))}function cr(e){let t=D(e);if(!Object.keys(t).length||t.disable===!0)return;let r=Te(t.test);return r?{test:r,intervalSeconds:ut(t.interval,30),timeoutSeconds:ut(t.timeout,5),retries:Math.max(1,Number(t.retries)||3),...t.start_period?{startPeriodSeconds:ut(t.start_period,0)}:{}}:void 0}function ti(e,t,r){if(!e)return;let n=typeof e==="string"?{context:e}:D(e),o=String(n.context??"."),a=String(n.dockerfile??"Dockerfile");if(o.startsWith("/")||o.split("/").includes("..")||a.startsWith("/")||a.split("/").includes(".."))r.push({severity:"error",path:t,code:"build.traversal",message:"Build context and Dockerfile must stay inside the repository."});return{context:o,dockerfile:a,...n.target?{target:String(n.target)}:{},args:ur(n.args,`${t}.args`,r)}}function Ei(e,t,r){let n=Array.isArray(e)?Object.fromEntries(e.map((a)=>String(a).split("=",2))):D(e),o=String(n["ts-cloud.domains"]??n["ts-cloud.domain"]??"").split(",").map((a)=>a.trim()).filter(Boolean);for(let a of o)if(!/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/i.test(a))r.push({severity:"error",path:t,code:"domain.invalid",message:`Invalid service domain ${a}.`});return o.filter((a)=>/\./.test(a))}function Ti(e,t){let r=[],n=new Set,o=new Set,a=(l)=>{if(o.has(l))return;if(n.has(l)){t.push({severity:"error",path:`services.${l}.depends_on`,code:"dependency.cycle",message:"Service dependencies contain a cycle."});return}n.add(l);for(let u of e[l]?.dependsOn??[])if(!e[u.service])t.push({severity:"error",path:`services.${l}.depends_on.${u.service}`,code:"dependency.missing",message:`Dependency ${u.service} does not exist.`});else a(u.service);n.delete(l),o.add(l),r.push(l)};return Object.keys(e).sort().forEach(a),r}function Cr(e,t){if(Buffer.byteLength(e)>524288)throw Error("Compose source exceeds the 512 KiB limit");let r;try{r=D(Bun.YAML.parse(e))}catch(T){throw Error(`Compose YAML could not be parsed: ${T instanceof Error?T.message:String(T)}`)}let n=[],o=D(r.services),a=Object.keys(o);if(!a.length)n.push({severity:"error",path:"services",code:"services.required",message:"At least one service is required."});if(a.length>64)n.push({severity:"error",path:"services",code:"services.limit",message:"A Compose application may contain at most 64 services."});let l=new Set(Object.keys(D(r.volumes))),u=new Set(Object.keys(D(r.networks))),p={};for(let T of a.sort()){let N=`services.${T}`,h=D(o[T]);if(!lr.test(T)){n.push({severity:"error",path:N,code:"service.name",message:"Service names must be portable lowercase identifiers."});continue}for(let[U,Lr]of ar)if(h[U]!=null&&h[U]!==!1&&(!Array.isArray(h[U])||h[U].length))n.push({severity:"error",path:`${N}.${U}`,code:`unsafe.${U}`,message:Lr});for(let U of Object.keys(h))if(!Yn.has(U)&&!ar.has(U))n.push({severity:"warning",path:`${N}.${U}`,code:"field.unsupported",message:`Compose field ${U} is not in the supported subset and will not be deployed.`});let f=h.image?String(h.image):void 0,L=ti(h.build,`${N}.build`,n);if(!f&&!L)n.push({severity:"error",path:N,code:"service.source",message:"Each service requires image or build."});if(f&&!f.includes("@sha256:")&&(!f.includes(":")||f.endsWith(":latest")))n.push({severity:"warning",path:`${N}.image`,code:"image.floating",message:`Image ${f} is not pinned to a digest or explicit tag.`});let v=pt(h.networks).map((U)=>typeof U==="string"?U:String(D(U).name??"")).filter(Boolean);v.forEach((U)=>u.add(U));let I=D(h.deploy),S=D(I.resources),O=D(S.limits),P=["no","always","on-failure","unless-stopped"].includes(String(h.restart))?String(h.restart):"unless-stopped";p[T]={name:T,...f?{image:f}:{},...L?{build:L}:{},...Te(h.command)?{command:Te(h.command)}:{},...Te(h.entrypoint)?{entrypoint:Te(h.entrypoint)}:{},environment:ur(h.environment,`${N}.environment`,n),ports:Jn(h.ports,`${N}.ports`,n),volumes:Zn(h.volumes,l,`${N}.volumes`,n),networks:v,dependsOn:ei(h.depends_on),...cr(h.healthcheck)?{healthCheck:cr(h.healthcheck)}:{},restart:P,...Number(O.cpus)>0?{cpu:Number(O.cpus)}:{},...dr(O.memory)?{memoryMb:dr(O.memory)}:{},replicas:Math.max(1,Math.min(100,Number(I.replicas)||1)),domains:Ei(h.labels,`${N}.labels`,n)}}let E=Ti(p,n),g={apiVersion:"ts-cloud.dev/v1",kind:"ComposeApplication",metadata:{name:t.name.trim(),slug:Gn(t.slug??t.name),projectId:t.projectId,environmentId:t.environmentId},spec:{services:p,networks:[...u].sort(),volumes:[...l].sort(),dependencyOrder:E}},m=wc(g);return{valid:!n.some((T)=>T.severity==="error"),manifest:g,diagnostics:n,redactedSource:m,sourceHash:Kn("sha256").update(e).digest("hex")}}function wc(e){let t=Object.fromEntries(Object.entries(e.spec.services).map(([r,n])=>[r,{...n.image?{image:n.image}:{},...n.build?{build:{context:n.build.context,dockerfile:n.build.dockerfile,...n.build.target?{target:n.build.target}:{},...Object.keys(n.build.args).length?{args:Object.fromEntries(Object.entries(n.build.args).map(([o,a])=>[o,typeof a==="string"?a:`\${${a.secretRef}:?required secret ${a.secretRef}}`]))}:{}}}:{},...n.command?{command:n.command}:{},...n.entrypoint?{entrypoint:n.entrypoint}:{},...Object.keys(n.environment).length?{environment:Object.fromEntries(Object.entries(n.environment).map(([o,a])=>[o,typeof a==="string"?a:`\${${a.secretRef}:?required secret ${a.secretRef}}`]))}:{},...n.ports.length?{ports:n.ports.map((o)=>`${o.published?`${o.published}:`:""}${o.target}${o.protocol==="udp"?"/udp":""}`)}:{},...n.volumes.length?{volumes:n.volumes.map((o)=>`${o.source}:${o.target}${o.readOnly?":ro":""}`)}:{},...n.networks.length?{networks:n.networks}:{},...n.dependsOn.length?{depends_on:Object.fromEntries(n.dependsOn.map((o)=>[o.service,{condition:o.condition}]))}:{},...n.healthCheck?{healthcheck:{test:n.healthCheck.test,interval:`${n.healthCheck.intervalSeconds}s`,timeout:`${n.healthCheck.timeoutSeconds}s`,retries:n.healthCheck.retries,...n.healthCheck.startPeriodSeconds!=null?{start_period:`${n.healthCheck.startPeriodSeconds}s`}:{}}}:{},restart:n.restart,...n.cpu||n.memoryMb||n.replicas!==1?{deploy:{replicas:n.replicas,resources:{limits:{...n.cpu?{cpus:String(n.cpu)}:{},...n.memoryMb?{memory:`${n.memoryMb}M`}:{}}}}}:{},...n.domains.length?{labels:{"ts-cloud.domains":n.domains.join(",")}}:{}}]));return Bun.YAML.stringify({services:t,...e.spec.networks.length?{networks:Object.fromEntries(e.spec.networks.map((r)=>[r,{}]))}:{},...e.spec.volumes.length?{volumes:Object.fromEntries(e.spec.volumes.map((r)=>[r,{}]))}:{}})}function Rc(e,t){let r=[],n=(o,a,l)=>{if(JSON.stringify(a)===JSON.stringify(l))return;if(a&&l&&typeof a==="object"&&typeof l==="object"&&!Array.isArray(a)&&!Array.isArray(l)){for(let u of[...new Set([...Object.keys(a),...Object.keys(l)])].sort())n(o?`${o}.${u}`:u,a[u],l[u]);return}r.push({path:o,...a!==void 0?{before:a}:{},...l!==void 0?{after:l}:{}})};return n("",e,t),r}import{createHash as pr}from"node:crypto";var _i="2026-07-21T00:00:00.000Z",mr=[{id:"bun-postgres-redis",name:"Bun + Postgres + Redis",description:"Web and worker services with durable Postgres and Redis dependencies.",category:"application",version:"1.0.0",sourceVersion:"oven/bun:1.2.21,postgres:17.5,redis:8.0.3",architecture:"web → Postgres + Redis; worker → Postgres + Redis",minimumResources:{cpu:2,memoryMb:3072},exposedServices:["web"],maintenanceNotes:"Back up the Postgres volume before major upgrades.",inputs:[{name:"domain",label:"Web domain",required:!0,secret:!1}],source:`services:
|
|
1557
|
+
[output truncated]`;let p=this.idFn(),E=this.now();return this.controlPlane.database.run("INSERT INTO operation_logs (id, operation_id, stream, step, message, redacted, truncated, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",[p,e,r.stream??"stdout",r.step??null,n,o?1:0,u?1:0,E]),or(this.controlPlane.database.query("SELECT * FROM operation_logs WHERE id=?").get(p))}logs(e,t={}){let r=Math.min(1000,Math.max(1,t.limit??200));return this.controlPlane.database.query("SELECT * FROM operation_logs WHERE operation_id=? AND sequence>? ORDER BY sequence ASC LIMIT ?").all(e,t.after??0,r).map(or)}requestCancellation(e,t){let r=this.controlPlane.getOperation(e);if(!r||Hn.includes(r.state))throw Error("Only queued or running operations can be cancelled");let n=this.controlPlane.requestCancellation(e);if(this.controlPlane.appendEvent({projectId:r.projectId,operationId:e,resourceId:r.resourceId,actorId:t,correlationId:r.correlationId,type:"operation.cancellation_requested",level:"warning",payload:{state:r.state}}),this.appendLog(e,r.state==="queued"?"Cancellation accepted before execution.":"Cancellation requested; waiting for the current provider step.",{stream:"system"}),n.state==="queued")return this.finish(e,"cancelled",{cancelledBeforeStart:!0});return n}retry(e,t,r={}){let n=this.controlPlane.getOperation(e),o=this.getJob(e);if(!n||!o||!["failed","cancelled","timed_out"].includes(n.state))throw Error("Only failed, cancelled, or timed-out queue jobs can be retried");if(n.attempt>=o.maxAttempts)throw Error(`Operation reached its ${o.maxAttempts}-attempt limit`);if(!o.retryClasses.includes(t))throw Error(`Retry class ${t} is not allowed for this operation`);let a=this.controlPlane.transitionOperation(e,{to:"queued",expectedVersion:n.version,error:`Retry requested after ${t}`}),l=new Date(this.nowFn().getTime()+Math.max(0,r.delayMs??0)).toISOString();this.controlPlane.database.run("UPDATE operations SET cancel_requested_at=NULL, finished_at=NULL WHERE id=?",[e]),this.controlPlane.database.run("UPDATE operation_jobs SET available_at=?, blocked_reason=NULL, updated_at=? WHERE operation_id=?",[l,this.now(),e]),this.controlPlane.appendEvent({projectId:n.projectId,operationId:e,resourceId:n.resourceId,actorId:r.actorId,correlationId:n.correlationId,type:"operation.retry_requested",payload:{errorClass:t,availableAt:l,nextAttempt:n.attempt+1}}),this.appendLog(e,`Retry queued for error class ${t}.`,{stream:"system"});let u=this.controlPlane.getOperation(a.id);return this.notifyAvailable(),u}release(e){this.controlPlane.database.run("DELETE FROM operation_locks WHERE operation_id=?",[e])}finish(e,t,r={},n){let o=this.controlPlane.getOperation(e);if(!o)throw Error(`Operation ${e} was not found`);let a=this.controlPlane.transitionOperation(e,{to:t,expectedVersion:o.version,output:r,error:n});return this.release(e),a}complete(e,t={}){let r=this.controlPlane.getOperation(e);if(!r||r.state!=="running"||r.leaseOwner!==this.workerId)throw Error("Only the lease owner can complete a running operation");return this.appendLog(e,"Operation completed successfully.",{stream:"system"}),this.finish(e,"succeeded",t)}fail(e,t,r={}){let n=this.controlPlane.getOperation(e);if(!n||n.state!=="running"||n.leaseOwner!==this.workerId)throw Error("Only the lease owner can fail a running operation");return this.appendLog(e,t,{stream:"stderr"}),this.finish(e,"failed",r,t)}async runOne(e){let t=this.claimNext(Object.keys(e));if(!t)return{handled:!1};let{operation:r,job:n}=t,o=e[r.kind];if(!o)return{handled:!1};let a=new AbortController,l=!1,u=setTimeout(()=>{l=!0,a.abort(new ks(n.timeoutSeconds))},n.timeoutSeconds*1000),p=setInterval(()=>{try{this.heartbeat(r.id)}catch{}},Math.max(250,Math.floor(this.leaseMs/3))),E=setInterval(()=>{if(this.controlPlane.getOperation(r.id)?.cancelRequestedAt)a.abort(new ii)},100),g={operation:r,signal:a.signal,log:(m,T)=>this.appendLog(r.id,m,T),checkpoint:(m,T)=>{this.heartbeat(r.id,m),this.appendLog(r.id,T??m,{stream:"step",step:m})},heartbeat:()=>this.heartbeat(r.id),cancellationRequested:()=>!!this.controlPlane.getOperation(r.id)?.cancelRequestedAt,throwIfCancellationRequested:()=>{if(this.controlPlane.getOperation(r.id)?.cancelRequestedAt)throw new ii}};try{let m=await Promise.race([o(g),new Promise((_,N)=>a.signal.addEventListener("abort",()=>N(a.signal.reason),{once:!0}))]);if(this.controlPlane.getOperation(r.id).cancelRequestedAt){let _=n.cancellationMode==="provider_non_cancellable";return this.appendLog(r.id,_?"Provider step completed after cancellation was requested; reconciliation is required.":"Operation cancelled cooperatively.",{stream:"system"}),{handled:!0,operation:this.finish(r.id,"cancelled",{providerCompleted:_,reconciliationRequired:_}),terminalState:"cancelled"}}return{handled:!0,operation:this.complete(r.id,m??{}),terminalState:"succeeded"}}catch(m){if(l||m instanceof ks)return this.appendLog(r.id,`Timed out after ${n.timeoutSeconds}s.`,{stream:"system"}),{handled:!0,operation:this.finish(r.id,"timed_out",{reconciliationRequired:n.cancellationMode==="provider_non_cancellable"},m instanceof Error?m.message:String(m)),terminalState:"timed_out"};if(m instanceof ii||this.controlPlane.getOperation(r.id)?.cancelRequestedAt)return{handled:!0,operation:this.finish(r.id,"cancelled",{cooperativelyCancelled:!0}),terminalState:"cancelled"};if(m instanceof X&&n.retryClasses.includes(m.errorClass)&&r.attempt<n.maxAttempts){let _=this.controlPlane.getOperation(r.id);this.controlPlane.transitionOperation(r.id,{to:"queued",expectedVersion:_.version,error:m.message});let N=Math.min(60000,1000*2**Math.max(0,r.attempt-1)),y=new Date(this.nowFn().getTime()+N).toISOString();return this.controlPlane.database.run("UPDATE operation_jobs SET available_at=?, blocked_reason=?, updated_at=? WHERE operation_id=?",[y,`retry_backoff:${m.errorClass}`,this.now(),r.id]),this.release(r.id),this.appendLog(r.id,`Retryable ${m.errorClass} failure; next attempt is delayed.`,{stream:"system"}),{handled:!0,operation:this.controlPlane.getOperation(r.id),requeued:!0}}let T=m instanceof Error?m.message:String(m);return this.appendLog(r.id,T,{stream:"stderr"}),{handled:!0,operation:this.finish(r.id,"failed",{},T),terminalState:"failed"}}finally{clearTimeout(u),clearInterval(p),clearInterval(E)}}recoverExpired(){let e=this.controlPlane.database.query("SELECT o.id FROM operations o JOIN operation_jobs j ON j.operation_id=o.id WHERE o.state='running' AND (o.lease_expires_at IS NULL OR o.lease_expires_at<=?)").all(this.now()),t={requeued:0,failed:0,cancelled:0};for(let r of e){let n=this.controlPlane.getOperation(String(r.id)),o=this.getJob(n.id);if(this.release(n.id),n.cancelRequestedAt){this.finish(n.id,"cancelled",{recoveredAfterWorkerLoss:!0}),t.cancelled++;continue}if(o.resumePolicy==="requeue"&&n.attempt<o.maxAttempts)this.controlPlane.transitionOperation(n.id,{to:"queued",expectedVersion:n.version,error:"Worker lease expired; safely requeued from the last checkpoint."}),this.controlPlane.database.run("UPDATE operation_jobs SET available_at=?, blocked_reason='worker_restart', updated_at=? WHERE operation_id=?",[this.now(),this.now(),n.id]),this.appendLog(n.id,"Worker lease expired; operation requeued from its persisted checkpoint.",{stream:"system"}),t.requeued++;else this.finish(n.id,"failed",{recoverable:!0,lastCheckpoint:o.currentStep??null},"Worker lease expired; retry explicitly after reconciling provider state."),t.failed++}return t}clearCompleted(e={}){let t=this.now(),r=[t],n=e.projectId?"AND o.project_id=?":"";if(e.projectId)r.push(e.projectId);let o=e.before?"AND o.finished_at<=?":"";if(e.before)r.push(new Date(e.before).toISOString());let a=this.controlPlane.database.query(`SELECT o.id, o.project_id, o.correlation_id FROM operations o JOIN operation_jobs j ON j.operation_id=o.id WHERE o.state IN ('succeeded','failed','cancelled','timed_out') AND j.retention_until<=? ${n} ${o}`).all(...r);for(let l of a)this.controlPlane.appendEvent({projectId:J(l.project_id),actorId:e.actorId,correlationId:String(l.correlation_id),type:"queue.history.cleared",level:"warning",payload:{operationId:String(l.id),retentionCutoff:t}}),this.controlPlane.database.run("DELETE FROM operations WHERE id=?",[String(l.id)]);return a.length}}function sr(e,t,r){if(!Number.isFinite(e))return t;return Math.min(r,Math.max(1,Math.floor(e)))}class Bs{queue;handlers;parallelism;pollIntervalMs;onResult;onError;waits=new Map;nextWaitId=0;lanes=[];running=!1;unsubscribeAvailability;constructor(e,t,r={}){this.queue=e;this.handlers=t;this.parallelism=sr(r.parallelism,4,100),this.pollIntervalMs=sr(r.pollIntervalMs,5000,60000),this.onResult=r.onResult,this.onError=r.onError}get active(){return this.running}start(){if(this.running)return this;return this.running=!0,this.unsubscribeAvailability=this.queue.onAvailable(()=>this.wake()),this.lanes=Array.from({length:this.parallelism},(e,t)=>this.runLane(t)),this}stop(){this.running=!1,this.unsubscribeAvailability?.(),this.unsubscribeAvailability=void 0,this.wake()}wake(){for(let{resolve:e,timer:t}of this.waits.values()){if(t)clearTimeout(t);e()}this.waits.clear()}async settled(){await Promise.allSettled(this.lanes)}async drain(){let e=[];while(!0){let t=await Promise.all(Array.from({length:this.parallelism},()=>this.queue.runOne(this.handlers)));if(e.push(...t.filter((r)=>r.handled)),!t.some((r)=>r.handled))return e}}wait(e){return new Promise((t)=>{let r=++this.nextWaitId,n=e?setTimeout(()=>{this.waits.delete(r),t()},this.pollIntervalMs):void 0;n?.unref?.(),this.waits.set(r,{resolve:t,timer:n})})}async runLane(e){while(this.running){try{let t=await this.queue.runOne(this.handlers);if(!this.running)break;if(t.handled){this.onResult?.(t),this.wake();continue}}catch(t){this.onError?.(t)}await this.wait(e===0)}}}import{createHash as Kn}from"node:crypto";var lr=/^[a-z0-9](?:[a-z0-9_.-]{0,62})$/,$n=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,Qn=/(?:secret|token|password|passwd|private.?key|api.?key|credential)/i,Yn=new Set(["image","build","command","entrypoint","environment","ports","volumes","networks","depends_on","healthcheck","restart","deploy","labels"]),ar=new Map([["privileged","Privileged containers are blocked."],["network_mode","Host/custom network modes are blocked."],["pid","Host PID namespaces are blocked."],["ipc","Host IPC namespaces are blocked."],["devices","Device access is blocked."],["cap_add","Additional Linux capabilities require an external policy exception."],["security_opt","Custom security options require an external policy exception."]]);function U(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function pt(e){return Array.isArray(e)?e:e==null?[]:[e]}function Gn(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,63)||"compose-app"}function Te(e){if(Array.isArray(e))return e.map(String);if(typeof e==="string"&&e.trim())return["sh","-c",e];return}function ut(e,t){let r=String(e??""),n=/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/.exec(r);if(!n)return t;let o=Number(n[1]);return Math.max(0,Math.round(o*(n[2]==="ms"?0.001:n[2]==="m"?60:n[2]==="h"?3600:1)))}function dr(e){let t=/^(\d+(?:\.\d+)?)\s*(b|k|kb|kib|m|mb|mib|g|gb|gib)?$/i.exec(String(e??""));if(!t)return;let r=Number(t[1]),n=String(t[2]??"b").toLowerCase(),o=r*(n.startsWith("g")?1073741824:n.startsWith("m")?1048576:n.startsWith("k")?1024:1);return Math.max(1,Math.round(o/1024/1024))}function Wn(e){if(e==null)return"";return/^\$\{([A-Za-z_][A-Za-z0-9_]*)(?::[-?][^}]*)?\}$/.exec(String(e))?.[1]}function ur(e,t,r){let n={},o=Array.isArray(e)?e.map((a)=>{let[l,...u]=String(a).split("=");return[l,u.length?u.join("="):null]}):Object.entries(U(e));for(let[a,l]of o){let u=String(a);if(!$n.test(u)){r.push({severity:"error",path:`${t}.${u}`,code:"environment.name",message:"Environment variable names must use portable shell identifiers."});continue}let p=Wn(l);if(p!==void 0){n[u]={secretRef:p||u};continue}if(Qn.test(u)){r.push({severity:"error",path:`${t}.${u}`,code:"secret.literal",message:"Literal secret-like environment values are not stored.",alternative:`Use \${${u}} and supply ${u} through the secret store.`}),n[u]={secretRef:u};continue}n[u]=String(l??"")}return n}function Jn(e,t,r){let n=[];for(let[o,a]of pt(e).entries()){let l,u,p="tcp";if(typeof a==="number")l=a;else if(typeof a==="string"){let[E,g]=a.split("/");p=g==="udp"?"udp":"tcp";let m=E.split(":");l=Number(m.at(-1)),u=m.length>1?Number(m.at(-2)):void 0}else{let E=U(a);l=Number(E.target),u=E.published==null?void 0:Number(E.published),p=E.protocol==="udp"?"udp":"tcp"}if(!Number.isInteger(l)||l<1||l>65535||u!=null&&(!Number.isInteger(u)||u<1||u>65535))r.push({severity:"error",path:`${t}[${o}]`,code:"port.invalid",message:"Ports must be integers from 1 through 65535."});else n.push({target:l,...u?{published:u}:{},protocol:p})}return n}function Zn(e,t,r,n){let o=[];for(let[a,l]of pt(e).entries()){let u="",p="",E=!1,g="volume";if(typeof l==="string"){let m=l.split(":");u=m[0]??"",p=m[1]??"",E=m.slice(2).includes("ro"),g=u.startsWith("/")||u.startsWith(".")?"bind":"volume"}else{let m=U(l);u=String(m.source??""),p=String(m.target??""),E=m.read_only===!0,g=String(m.type??"volume")}if(g!=="volume"||u.startsWith("/")||u.startsWith(".")){n.push({severity:"error",path:`${r}[${a}]`,code:"volume.host_mount",message:"Host and bind mounts are blocked; use a named volume.",alternative:"Declare the volume at the top level and mount it by name."});continue}if(!lr.test(u)||!p.startsWith("/")){n.push({severity:"error",path:`${r}[${a}]`,code:"volume.invalid",message:"A named source and absolute container target are required."});continue}if(!t.has(u))n.push({severity:"warning",path:`${r}[${a}]`,code:"volume.implicit",message:`Named volume ${u} is implicit and will be declared on export.`});t.add(u),o.push({source:u,target:p,readOnly:E})}return o}function ei(e){return Array.isArray(e)?e.map((t)=>({service:String(t),condition:"service_started"})):Object.entries(U(e)).map(([t,r])=>({service:t,condition:["service_started","service_healthy","service_completed_successfully"].includes(String(U(r).condition))?String(U(r).condition):"service_started"}))}function cr(e){let t=U(e);if(!Object.keys(t).length||t.disable===!0)return;let r=Te(t.test);return r?{test:r,intervalSeconds:ut(t.interval,30),timeoutSeconds:ut(t.timeout,5),retries:Math.max(1,Number(t.retries)||3),...t.start_period?{startPeriodSeconds:ut(t.start_period,0)}:{}}:void 0}function ti(e,t,r){if(!e)return;let n=typeof e==="string"?{context:e}:U(e),o=String(n.context??"."),a=String(n.dockerfile??"Dockerfile");if(o.startsWith("/")||o.split("/").includes("..")||a.startsWith("/")||a.split("/").includes(".."))r.push({severity:"error",path:t,code:"build.traversal",message:"Build context and Dockerfile must stay inside the repository."});return{context:o,dockerfile:a,...n.target?{target:String(n.target)}:{},args:ur(n.args,`${t}.args`,r)}}function ri(e,t,r){let n=Array.isArray(e)?Object.fromEntries(e.map((a)=>String(a).split("=",2))):U(e),o=String(n["ts-cloud.domains"]??n["ts-cloud.domain"]??"").split(",").map((a)=>a.trim()).filter(Boolean);for(let a of o)if(!/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/i.test(a))r.push({severity:"error",path:t,code:"domain.invalid",message:`Invalid service domain ${a}.`});return o.filter((a)=>/\./.test(a))}function Ei(e,t){let r=[],n=new Set,o=new Set,a=(l)=>{if(o.has(l))return;if(n.has(l)){t.push({severity:"error",path:`services.${l}.depends_on`,code:"dependency.cycle",message:"Service dependencies contain a cycle."});return}n.add(l);for(let u of e[l]?.dependsOn??[])if(!e[u.service])t.push({severity:"error",path:`services.${l}.depends_on.${u.service}`,code:"dependency.missing",message:`Dependency ${u.service} does not exist.`});else a(u.service);n.delete(l),o.add(l),r.push(l)};return Object.keys(e).sort().forEach(a),r}function Cr(e,t){if(Buffer.byteLength(e)>524288)throw Error("Compose source exceeds the 512 KiB limit");let r;try{r=U(Bun.YAML.parse(e))}catch(T){throw Error(`Compose YAML could not be parsed: ${T instanceof Error?T.message:String(T)}`)}let n=[],o=U(r.services),a=Object.keys(o);if(!a.length)n.push({severity:"error",path:"services",code:"services.required",message:"At least one service is required."});if(a.length>64)n.push({severity:"error",path:"services",code:"services.limit",message:"A Compose application may contain at most 64 services."});let l=new Set(Object.keys(U(r.volumes))),u=new Set(Object.keys(U(r.networks))),p={};for(let T of a.sort()){let h=`services.${T}`,_=U(o[T]);if(!lr.test(T)){n.push({severity:"error",path:h,code:"service.name",message:"Service names must be portable lowercase identifiers."});continue}for(let[O,Ir]of ar)if(_[O]!=null&&_[O]!==!1&&(!Array.isArray(_[O])||_[O].length))n.push({severity:"error",path:`${h}.${O}`,code:`unsafe.${O}`,message:Ir});for(let O of Object.keys(_))if(!Yn.has(O)&&!ar.has(O))n.push({severity:"warning",path:`${h}.${O}`,code:"field.unsupported",message:`Compose field ${O} is not in the supported subset and will not be deployed.`});let N=_.image?String(_.image):void 0,y=ti(_.build,`${h}.build`,n);if(!N&&!y)n.push({severity:"error",path:h,code:"service.source",message:"Each service requires image or build."});if(N&&!N.includes("@sha256:")&&(!N.includes(":")||N.endsWith(":latest")))n.push({severity:"warning",path:`${h}.image`,code:"image.floating",message:`Image ${N} is not pinned to a digest or explicit tag.`});let L=pt(_.networks).map((O)=>typeof O==="string"?O:String(U(O).name??"")).filter(Boolean);L.forEach((O)=>u.add(O));let v=U(_.deploy),I=U(v.resources),A=U(I.limits),k=["no","always","on-failure","unless-stopped"].includes(String(_.restart))?String(_.restart):"unless-stopped";p[T]={name:T,...N?{image:N}:{},...y?{build:y}:{},...Te(_.command)?{command:Te(_.command)}:{},...Te(_.entrypoint)?{entrypoint:Te(_.entrypoint)}:{},environment:ur(_.environment,`${h}.environment`,n),ports:Jn(_.ports,`${h}.ports`,n),volumes:Zn(_.volumes,l,`${h}.volumes`,n),networks:L,dependsOn:ei(_.depends_on),...cr(_.healthcheck)?{healthCheck:cr(_.healthcheck)}:{},restart:k,...Number(A.cpus)>0?{cpu:Number(A.cpus)}:{},...dr(A.memory)?{memoryMb:dr(A.memory)}:{},replicas:Math.max(1,Math.min(100,Number(v.replicas)||1)),domains:ri(_.labels,`${h}.labels`,n)}}let E=Ei(p,n),g={apiVersion:"ts-cloud.dev/v1",kind:"ComposeApplication",metadata:{name:t.name.trim(),slug:Gn(t.slug??t.name),projectId:t.projectId,environmentId:t.environmentId},spec:{services:p,networks:[...u].sort(),volumes:[...l].sort(),dependencyOrder:E}},m=Dc(g);return{valid:!n.some((T)=>T.severity==="error"),manifest:g,diagnostics:n,redactedSource:m,sourceHash:Kn("sha256").update(e).digest("hex")}}function Dc(e){let t=Object.fromEntries(Object.entries(e.spec.services).map(([r,n])=>[r,{...n.image?{image:n.image}:{},...n.build?{build:{context:n.build.context,dockerfile:n.build.dockerfile,...n.build.target?{target:n.build.target}:{},...Object.keys(n.build.args).length?{args:Object.fromEntries(Object.entries(n.build.args).map(([o,a])=>[o,typeof a==="string"?a:`\${${a.secretRef}:?required secret ${a.secretRef}}`]))}:{}}}:{},...n.command?{command:n.command}:{},...n.entrypoint?{entrypoint:n.entrypoint}:{},...Object.keys(n.environment).length?{environment:Object.fromEntries(Object.entries(n.environment).map(([o,a])=>[o,typeof a==="string"?a:`\${${a.secretRef}:?required secret ${a.secretRef}}`]))}:{},...n.ports.length?{ports:n.ports.map((o)=>`${o.published?`${o.published}:`:""}${o.target}${o.protocol==="udp"?"/udp":""}`)}:{},...n.volumes.length?{volumes:n.volumes.map((o)=>`${o.source}:${o.target}${o.readOnly?":ro":""}`)}:{},...n.networks.length?{networks:n.networks}:{},...n.dependsOn.length?{depends_on:Object.fromEntries(n.dependsOn.map((o)=>[o.service,{condition:o.condition}]))}:{},...n.healthCheck?{healthcheck:{test:n.healthCheck.test,interval:`${n.healthCheck.intervalSeconds}s`,timeout:`${n.healthCheck.timeoutSeconds}s`,retries:n.healthCheck.retries,...n.healthCheck.startPeriodSeconds!=null?{start_period:`${n.healthCheck.startPeriodSeconds}s`}:{}}}:{},restart:n.restart,...n.cpu||n.memoryMb||n.replicas!==1?{deploy:{replicas:n.replicas,resources:{limits:{...n.cpu?{cpus:String(n.cpu)}:{},...n.memoryMb?{memory:`${n.memoryMb}M`}:{}}}}}:{},...n.domains.length?{labels:{"ts-cloud.domains":n.domains.join(",")}}:{}}]));return Bun.YAML.stringify({services:t,...e.spec.networks.length?{networks:Object.fromEntries(e.spec.networks.map((r)=>[r,{}]))}:{},...e.spec.volumes.length?{volumes:Object.fromEntries(e.spec.volumes.map((r)=>[r,{}]))}:{}})}function Pc(e,t){let r=[],n=(o,a,l)=>{if(JSON.stringify(a)===JSON.stringify(l))return;if(a&&l&&typeof a==="object"&&typeof l==="object"&&!Array.isArray(a)&&!Array.isArray(l)){for(let u of[...new Set([...Object.keys(a),...Object.keys(l)])].sort())n(o?`${o}.${u}`:u,a[u],l[u]);return}r.push({path:o,...a!==void 0?{before:a}:{},...l!==void 0?{after:l}:{}})};return n("",e,t),r}import{createHash as pr}from"node:crypto";var Ti="2026-07-21T00:00:00.000Z",mr=[{id:"bun-postgres-redis",name:"Bun + Postgres + Redis",description:"Web and worker services with durable Postgres and Redis dependencies.",category:"application",version:"1.0.0",sourceVersion:"oven/bun:1.2.21,postgres:17.5,redis:8.0.3",architecture:"web → Postgres + Redis; worker → Postgres + Redis",minimumResources:{cpu:2,memoryMb:3072},exposedServices:["web"],maintenanceNotes:"Back up the Postgres volume before major upgrades.",inputs:[{name:"domain",label:"Web domain",required:!0,secret:!1}],source:`services:
|
|
1558
1558
|
web:
|
|
1559
1559
|
image: oven/bun:1.2.21
|
|
1560
1560
|
command: [bun, run, start]
|
|
@@ -1610,8 +1610,8 @@ volumes:
|
|
|
1610
1610
|
volumes:
|
|
1611
1611
|
wordpress-data: {}
|
|
1612
1612
|
database-data: {}
|
|
1613
|
-
`}];function br(){return mr.map(({source:e,...t})=>({...t,source:`builtin:${t.id}`,lastVerifiedAt:_i,builtin:!0,checksum:pr("sha256").update(e).digest("hex"),exposedServices:[...t.exposedServices],inputs:t.inputs.map((r)=>({...r}))}))}function Qh(e,t){return br().find((r)=>r.id===e&&(!t||r.version===t))}function Dc(e,t,r,n){let o=mr.find((l)=>l.id===e&&(!n||l.version===n));if(!o)throw Error(`Compose template ${e}${n?`@${n}`:""} was not found`);let a=o.source;for(let l of o.inputs){let u=t[l.name]??("default"in l?l.default:void 0);if(l.required&&!u)throw Error(`Template input ${l.name} is required`);if(u&&!/^[A-Za-z0-9._:/@+-]{1,255}$/.test(u))throw Error(`Template input ${l.name} contains unsupported characters`);a=a.replaceAll(`{{${l.name}}}`,u??"")}return Cr(a,r)}function Iy(e,t){if(Buffer.byteLength(e)>1048576)throw Error("Compose catalog exceeds the 1 MiB limit");let r;try{r=JSON.parse(e)}catch{throw Error("Compose catalog must be valid JSON")}if(r.apiVersion!=="ts-cloud.dev/compose-catalog/v1"||!Array.isArray(r.templates))throw Error("Compose catalog must use ts-cloud.dev/compose-catalog/v1 and contain templates");let n=String(r.source??"").trim();if(!/^https:\/\//.test(n)&&!n.startsWith("file:"))throw Error("Compose catalog source must be HTTPS or an explicit file: source");let o=[],a=[];for(let[l,u]of r.templates.slice(0,100).entries()){let p=u&&typeof u==="object"&&!Array.isArray(u)?u:{},E=`templates[${l}]`,g=String(p.compose??""),m=pr("sha256").update(g).digest("hex");if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(String(p.id??""))||!/^\d+\.\d+\.\d+$/.test(String(p.version??""))){o.push({severity:"error",path:E,code:"template.identity",message:"Template id and semantic version are required."});continue}if(String(p.checksum??"")!==m){o.push({severity:"error",path:`${E}.checksum`,code:"template.checksum",message:"Template checksum does not match its Compose source."});continue}let T=Cr(g,{name:String(p.name??p.id),projectId:t.projectId,environmentId:t.environmentId});o.push(...T.diagnostics.map((h)=>({...h,path:`${E}.compose.${h.path}`})));let N={id:String(p.id),name:String(p.name??p.id),description:String(p.description??""),category:String(p.category??"custom"),version:String(p.version),source:n,sourceVersion:String(p.sourceVersion??p.version),architecture:String(p.architecture??Object.keys(T.manifest.spec.services).join(" + ")),minimumResources:{cpu:Math.max(0.1,Number(p.minimumResources?.cpu)||1),memoryMb:Math.max(128,Number(p.minimumResources?.memoryMb)||512)},exposedServices:Array.isArray(p.exposedServices)?p.exposedServices.map(String):[],maintenanceNotes:String(p.maintenanceNotes??""),lastVerifiedAt:String(p.lastVerifiedAt??""),inputs:[],checksum:m,builtin:!1};a.push({template:N,parsed:T})}return{valid:!o.some((l)=>l.severity==="error"),source:n,templates:a,diagnostics:o}}function Sy(e,t,r,n,o,a){let l=Qh(r,a);if(!l)throw Error(`Compose template ${r}@${a} was not found`);let u=Dc(r,n,o,a);return{template:l,parsed:u,templateChanges:Rc(t,u.manifest),userChanges:Rc(t,e)}}var xe=/^[a-z0-9][a-z0-9_.-]{0,62}$/;function k(e){return`'${e.replaceAll("'","'\\''")}'`}function Ds(e){return`${e.metadata.slug}-${e.metadata.environmentId.slice(0,8)}`.replace(/[^a-z0-9_-]/g,"-").slice(0,63)}function Cy(e,t,r={}){let n=Ds(e),o=`/opt/ts-cloud/compose/${n}`,a=`${o}/compose.yaml`,l=`docker compose --project-name ${k(n)} --file ${k(a)}`;if(r.service&&!xe.test(r.service))throw Error("Unsafe Compose service name");if(t==="deploy"||t==="redeploy"){let u=Buffer.from(wc(e)).toString("base64");return`install -d -m 0750 ${k(o)} && printf %s ${k(u)} | base64 --decode > ${k(a)} && chmod 0640 ${k(a)} && ${l} config --quiet && ${l} up --detach --remove-orphans --wait${t==="redeploy"?" --force-recreate":""}`}if(t==="start")return`${l} start${r.service?` ${k(r.service)}`:""}`;if(t==="stop")return`${l} stop${r.service?` ${k(r.service)}`:""}`;if(t==="status")return`${l} ps --format json`;return`${l} down --remove-orphans${r.removeVolumes?" --volumes":""}`}function by(e,t,r){if(!xe.test(t)||!Number.isInteger(r)||r<0||r>100)throw Error("Scale requires a safe service name and 0-100 replicas");let n=Ds(e);return`docker compose --project-name ${k(n)} --file ${k(`/opt/ts-cloud/compose/${n}/compose.yaml`)} up --detach --wait --scale ${k(`${t}=${r}`)}`}function Pc(e,t,r=200){if(!xe.test(t))throw Error("Unsafe Compose service name");let n=Ds(e);return`docker compose --project-name ${k(n)} --file ${k(`/opt/ts-cloud/compose/${n}/compose.yaml`)} logs --no-color --timestamps --tail ${Math.max(1,Math.min(2000,Math.floor(r)))} ${k(t)}`}function Nc(e,t,r=["sh"]){if(!xe.test(t)||!r.length||r.some((o)=>o.includes("\x00")||o.length>1024))throw Error("Unsafe Compose shell request");let n=Ds(e);return`docker compose --project-name ${k(n)} --file ${k(`/opt/ts-cloud/compose/${n}/compose.yaml`)} exec ${k(t)} ${r.map(k).join(" ")}`}import{mkdir as mt,readdir as vi,rm as Ii,stat as Si}from"node:fs/promises";import{basename as bi,resolve as gr,sep as Ri}from"node:path";var Et=/^[a-z0-9][a-z0-9_.-]{1,62}$/,hi=/^0?[0-7]{3}$/,Ni=["/","/boot","/dev","/etc","/proc","/root","/run","/sys","/var/run","/var/lib/docker","/var/lib/containers"],fi=["create","attach","detach","resize","snapshot","restore","delete","adopt","usage"],yi=(e)=>e&&typeof e==="object"&&!Array.isArray(e)?e:{};function qh(e){return Object.fromEntries(fi.map((t)=>[t,{supported:!1,reason:e}]))}function ks(e,t={}){let r=qh("This storage driver does not support the operation.");for(let n of e)r[n]={supported:!0};return{...r,...t}}function Vh(e){if(!e.startsWith("/")||e.includes("\x00")||e.split("/").includes(".."))throw Error("Mount target must be an absolute normalized path without traversal.");let t=e.replace(/\/+$/,"")||"/";if(Ni.some((r)=>t===r||t.startsWith(`${r}/`)))throw Error(`Mount target ${e} is a protected host or runtime path.`)}function jh(e){if(Vh(e.targetPath),e.uid!=null&&(!Number.isInteger(e.uid)||e.uid<0))throw Error("Mount UID must be a non-negative integer.");if(e.gid!=null&&(!Number.isInteger(e.gid)||e.gid<0))throw Error("Mount GID must be a non-negative integer.");if(e.mode&&!hi.test(e.mode))throw Error("Mount mode must be a three or four digit octal value.");if(e.propagation&&!["private","rprivate","shared","rshared","slave","rslave"].includes(e.propagation))throw Error("Unsupported mount propagation mode.")}class Bs{store;drivers;now;queue;constructor(e,t,r,n=()=>new Date){this.store=e;this.drivers=t;this.now=n;this.queue=r??new c(e.controlPlane)}driver(e,t){let r=this.drivers.find((n)=>n.provider===e&&n.type===t);if(!r)throw Error(`No ${e} ${t} volume driver is configured.`);return r}capability(e,t){let r=e.capabilities[t];if(!r?.supported)throw Error(r?.reason??`${t} is unsupported for this volume.`)}queueMutation(e,t,r,n,o){return this.queue.enqueue({projectId:e.projectId,environmentId:e.environmentId,resourceId:o??e.resourceId,actorId:n,kind:t,idempotencyKey:`${t}:${e.id}:v${e.version}:${JSON.stringify(r)}`,correlationId:`volume:${e.id}`,input:{volumeId:e.id,...r},lockKey:o?`resource:${o}`:`volume:${e.id}`,providerKey:e.provider,maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:365}).operation}create(e){if(!Et.test(e.name))throw Error("Volume names must be 2-63 lowercase letters, numbers, dots, dashes, or underscores.");if(e.capacityBytes!=null&&(!Number.isSafeInteger(e.capacityBytes)||e.capacityBytes<=0))throw Error("Volume capacity must be a positive byte count.");let t=this.store.controlPlane.getProject(e.projectId),r=e.environmentId?this.store.controlPlane.listEnvironments(e.projectId).find((E)=>E.id===e.environmentId):void 0,n=e.resourceId?this.store.controlPlane.getResource(e.resourceId):void 0;if(!t||t.organizationId!==e.organizationId)throw Error("Volume project does not belong to the organization.");if(e.environmentId&&!r)throw Error("Volume environment does not belong to the project.");if(n&&(n.projectId!==e.projectId||n.environmentId!==e.environmentId||n.kind!=="volume"))throw Error("Volume resource does not belong to the selected scope.");let o=n??this.store.controlPlane.createResource({projectId:e.projectId,environmentId:e.environmentId,kind:"volume",slug:e.name,name:e.name,provider:e.provider,desiredState:{type:e.type,capacityBytes:e.capacityBytes??null,filesystem:e.filesystem??null,encrypted:!!e.encrypted}}),a=this.driver(e.provider,e.type),l=a.capabilities(),u=this.store.create({organizationId:e.organizationId,projectId:e.projectId,environmentId:e.environmentId,resourceId:o.id,name:e.name,provider:e.provider,type:e.type,status:"pending",capacityBytes:e.capacityBytes,filesystem:e.filesystem,encrypted:!!e.encrypted,capabilities:l,desiredState:e.desiredState??{},observedState:{}}),p=this.queueMutation(u,"volume.create",{},e.actorId);return this.store.audit({organizationId:u.organizationId,projectId:u.projectId,environmentId:u.environmentId,actorId:e.actorId,type:"volume.create.queued",volumeId:u.id,payload:{name:u.name,type:u.type}}),{volume:u,operation:p}}attach(e,t){let r=this.store.get(e);if(!r)throw Error("Volume was not found.");this.capability(r,"attach"),jh(t);let n=this.store.controlPlane.getResource(t.resourceId);if(!n||n.projectId!==r.projectId||n.environmentId!==r.environmentId)throw Error("Cross-project or cross-environment volume attachments are forbidden.");let o=this.store.upsertAttachment({volumeId:e,resourceId:t.resourceId,targetPath:t.targetPath,readOnly:!!t.readOnly,uid:t.uid,gid:t.gid,mode:t.mode,propagation:t.propagation??"private",driverOptions:t.driverOptions??{},desiredState:"attached",observedState:"pending"}),a=this.queueMutation(r,"volume.attach",{attachmentId:o.id},t.actorId,t.resourceId);return this.store.updateAttachment(o.id,{operationId:a.id}),this.store.update(r.id,r.version,{status:"attaching"}),this.store.audit({organizationId:r.organizationId,projectId:r.projectId,environmentId:r.environmentId,actorId:t.actorId,type:"volume.attach.queued",volumeId:e,payload:{resourceId:t.resourceId,targetPath:t.targetPath}}),{volume:this.store.get(r.id),attachment:this.store.attachment(o.id),operation:a}}detach(e,t,r={}){let n=this.store.get(e),o=this.store.attachment(t);if(!n||!o||o.volumeId!==e)throw Error("Volume attachment was not found.");if(this.capability(n,"detach"),o.observedState==="attached"&&(!r.drained||!r.unmounted))throw Error("Detach requires completed workload drain and filesystem unmount checkpoints.");if(r.force&&r.confirmation!==`detach ${n.name}`)throw Error(`Force detach requires confirmation: detach ${n.name}`);let a=this.store.updateAttachment(t,{desiredState:"detached"}),l=this.queueMutation(n,"volume.detach",{attachmentId:t,force:!!r.force},r.actorId,o.resourceId);return this.store.updateAttachment(t,{operationId:l.id}),this.store.update(n.id,n.version,{status:"detaching"}),{volume:this.store.get(e),attachment:a,operation:l}}resize(e,t,r={}){let n=this.store.get(e);if(!n)throw Error("Volume was not found.");if(this.capability(n,"resize"),!Number.isSafeInteger(t)||t<=0)throw Error("Volume capacity must be a positive byte count.");if(n.capacityBytes!=null&&t<n.capacityBytes)throw Error("Volume shrinking is not supported because it can corrupt data.");let o=n.capabilities.resize;if(o.minimumBytes&&t<o.minimumBytes)throw Error(`Minimum supported capacity is ${o.minimumBytes} bytes.`);if(o.maximumBytes&&t>o.maximumBytes)throw Error(`Maximum supported capacity is ${o.maximumBytes} bytes.`);if(o.online===!1&&!r.drained)throw Error("This resize requires a completed workload drain checkpoint.");let a=this.store.update(e,n.version,{status:"resizing",desiredState:{...n.desiredState,capacityBytes:t}}),l=this.queueMutation(a,"volume.resize",{capacityBytes:t},r.actorId);return{volume:a,operation:l}}snapshot(e,t={}){let r=this.store.get(e);if(!r)throw Error("Volume was not found.");this.capability(r,"snapshot");let n=this.store.createSnapshot({volumeId:e,name:t.name??`${r.name}-${this.now().toISOString().replace(/[:.]/g,"-")}`,status:"pending",encrypted:r.encrypted,metadata:{}}),o=this.store.update(e,r.version,{status:"snapshotting"}),a=this.queueMutation(o,"volume.snapshot",{snapshotId:n.id},t.actorId);return{volume:o,snapshot:n,operation:a}}restore(e,t){let r=this.store.snapshot(e),n=r?this.store.get(r.volumeId):void 0;if(!r||!n||r.status!=="available")throw Error("An available volume snapshot is required for restore.");if(this.capability(n,"restore"),!Et.test(t.name))throw Error("Restored volume names must be 2-63 lowercase letters, numbers, dots, dashes, or underscores.");let o=this.store.controlPlane.createResource({projectId:n.projectId,environmentId:n.environmentId,kind:"volume",slug:t.name,name:t.name,provider:n.provider,desiredState:{restoreFromSnapshotId:r.id}}),a=this.store.create({organizationId:n.organizationId,projectId:n.projectId,environmentId:n.environmentId,resourceId:o.id,name:t.name,provider:n.provider,type:n.type,status:"pending",capacityBytes:r.sizeBytes??n.capacityBytes,filesystem:n.filesystem,encrypted:r.encrypted,capabilities:n.capabilities,desiredState:{restoreFromSnapshotId:r.id,sourceVolumeId:n.id},observedState:{}}),l=this.queueMutation(a,"volume.restore",{snapshotId:r.id,sourceVolumeId:n.id},t.actorId);return{volume:a,snapshot:r,operation:l}}delete(e,t){let r=this.store.get(e);if(!r)throw Error("Volume was not found.");this.capability(r,"delete");let n=this.store.attachments(e).filter((u)=>u.desiredState==="attached"||u.observedState==="attached");if(n.length)throw Error(`Detach ${n.length} active consumer(s) before deleting this volume.`);if(!t.recentAuthAt||this.now().getTime()-new Date(t.recentAuthAt).getTime()>900000)throw Error("Volume deletion requires authentication verified within the last 15 minutes.");if(t.confirmation!==r.name)throw Error(`Type ${r.name} to confirm permanent volume deletion.`);if(!(r.lastBackupAt&&this.now().getTime()-new Date(r.lastBackupAt).getTime()<=86400000)&&(!t.backupOverride||t.backupOverrideConfirmation!==`delete without backup ${r.name}`))throw Error(`A verified backup from the last 24 hours is required, or confirm: delete without backup ${r.name}`);let a=this.store.update(e,r.version,{status:"deleting"}),l=this.queueMutation(a,"volume.delete",{backupOverride:!!t.backupOverride},t.actorId);return{volume:a,operation:l}}async discover(e){let t=new Set;for(let r of this.drivers)for(let n of await r.discover(e.projectId,e.environmentId)){let o=this.store.list({projectId:e.projectId,environmentId:e.environmentId}).find((l)=>l.provider===r.provider&&l.providerId===n.providerId);if(o){t.add(o.id),this.store.update(o.id,o.version,{capacityBytes:n.capacityBytes,usedBytes:n.usedBytes,filesystem:n.filesystem,encrypted:n.encrypted??o.encrypted,observedState:n.raw??{},status:o.status==="orphaned"?"available":o.status,orphanedAt:void 0});continue}let a=this.store.create({organizationId:e.organizationId,projectId:e.projectId,environmentId:e.environmentId,name:`orphan-${n.providerId}`.toLowerCase().replace(/[^a-z0-9_.-]/g,"-").slice(0,63),provider:r.provider,providerId:n.providerId,type:r.type,status:"orphaned",capacityBytes:n.capacityBytes,usedBytes:n.usedBytes,filesystem:n.filesystem,encrypted:!!n.encrypted,capabilities:r.capabilities(),desiredState:{},observedState:n.raw??{},orphanedAt:this.now().toISOString()});t.add(a.id)}return this.store.list({projectId:e.projectId,environmentId:e.environmentId})}adopt(e,t){let r=this.store.get(e);if(!r||r.status!=="orphaned")throw Error("Only discovered orphan volumes can be adopted.");if(!Et.test(t.name))throw Error("Volume names must be 2-63 lowercase letters, numbers, dots, dashes, or underscores.");let n=this.store.update(e,r.version,{name:t.name,status:"available",adoptedAt:this.now().toISOString(),orphanedAt:void 0});return this.store.audit({organizationId:r.organizationId,projectId:r.projectId,environmentId:r.environmentId,actorId:t.actorId,type:"volume.adopted",volumeId:e,payload:{providerId:r.providerId??null}}),n}}function Li(e){let t=yi(e.input);if(typeof t.volumeId!=="string")throw Error("Queued volume operation is missing its volume identity.");return{volumeId:t.volumeId,sourceVolumeId:typeof t.sourceVolumeId==="string"?t.sourceVolumeId:void 0,attachmentId:typeof t.attachmentId==="string"?t.attachmentId:void 0,snapshotId:typeof t.snapshotId==="string"?t.snapshotId:void 0,capacityBytes:typeof t.capacityBytes==="number"?t.capacityBytes:void 0,force:t.force===!0}}function Bc(e,t){let r=(o)=>{let a=t.find((l)=>l.provider===o.provider&&l.type===o.type);if(!a)throw Error(`No ${o.provider} ${o.type} volume driver is configured.`);return a},n=async(o)=>{let a=Li(o.operation),l=e.get(a.volumeId);if(!l)throw Error("Queued volume was not found.");let u=r(l);o.checkpoint("preflight","Validating persistent volume identity and capabilities."),o.throwIfCancellationRequested();let p;if(o.operation.kind==="volume.create")p=await u.create(l),e.update(l.id,l.version,{providerId:p.providerId,capacityBytes:p.capacityBytes??l.capacityBytes,usedBytes:p.usedBytes,filesystem:p.filesystem??l.filesystem,encrypted:p.encrypted??l.encrypted,observedState:p.raw??{},status:"available"});else if(o.operation.kind==="volume.attach"){let E=a.attachmentId?e.attachment(a.attachmentId):void 0;if(!E)throw Error("Queued volume attachment was not found.");await u.attach(l,E),e.updateAttachment(E.id,{observedState:"attached",lastError:void 0}),e.update(l.id,l.version,{status:"attached"})}else if(o.operation.kind==="volume.detach"){let E=a.attachmentId?e.attachment(a.attachmentId):void 0;if(!E)throw Error("Queued volume attachment was not found.");await u.detach(l,E,{force:a.force}),e.updateAttachment(E.id,{observedState:"detached",lastError:void 0});let g=e.attachments(l.id).some((m)=>m.id!==E.id&&m.observedState==="attached");e.update(l.id,l.version,{status:g?"attached":"available"})}else if(o.operation.kind==="volume.resize"){if(!a.capacityBytes)throw Error("Queued volume resize is missing its capacity.");p=await u.resize(l,a.capacityBytes),e.update(l.id,l.version,{capacityBytes:p.capacityBytes??a.capacityBytes,usedBytes:p.usedBytes??l.usedBytes,observedState:p.raw??l.observedState,status:e.attachments(l.id).some((E)=>E.observedState==="attached")?"attached":"available"})}else if(o.operation.kind==="volume.snapshot"){let E=a.snapshotId?e.snapshot(a.snapshotId):void 0;if(!E)throw Error("Queued volume snapshot was not found.");let g=await u.snapshot(l,E);e.updateSnapshot(E.id,{...g,status:"available"}),e.update(l.id,l.version,{status:e.attachments(l.id).some((m)=>m.observedState==="attached")?"attached":"available",lastBackupAt:new Date().toISOString()})}else if(o.operation.kind==="volume.restore"){let E=a.snapshotId?e.snapshot(a.snapshotId):void 0,g=a.sourceVolumeId?e.get(a.sourceVolumeId):void 0;if(!E||!g)throw Error("Queued volume restore source was not found.");p=await u.restore(g,E,l),e.update(l.id,l.version,{providerId:p.providerId,capacityBytes:p.capacityBytes??l.capacityBytes,usedBytes:p.usedBytes,filesystem:p.filesystem??l.filesystem,encrypted:p.encrypted??l.encrypted,observedState:p.raw??{},status:"available"})}else if(o.operation.kind==="volume.delete")await u.delete(l),e.update(l.id,l.version,{status:"deleted",deletedAt:new Date().toISOString()});return o.checkpoint("finalize","Persisted observed volume state."),{volumeId:l.id,status:e.get(l.id)?.status??"deleted"}};return Object.fromEntries(["volume.create","volume.attach","volume.detach","volume.resize","volume.snapshot","volume.restore","volume.delete"].map((o)=>[o,n]))}var Ci=async(e)=>{let t=Bun.spawn(["docker",...e],{stdout:"pipe",stderr:"pipe"}),[r,n,o]=await Promise.all([t.exited,new Response(t.stdout).text(),new Response(t.stderr).text()]);return{code:r,stdout:n,stderr:o}},ee=/^[A-Za-z0-9][A-Za-z0-9_.-]{1,127}$/;class vr{command;provider="docker";type="docker";constructor(e=Ci){this.command=e}capabilities(){return ks(["create","attach","detach","delete","adopt","usage"],{resize:{supported:!1,reason:"Docker named volumes do not expose a portable capacity resize operation."},snapshot:{supported:!1,reason:"Attach a volume backup policy to create verified recovery points."},restore:{supported:!1,reason:"Restore this volume from its verified backup recovery point."}})}async run(e,t=!1){let r=await this.command(e);if(r.code!==0&&!t)throw Error(`Docker volume command failed: ${r.stderr.trim()||r.code}`);return r.stdout}async inspect(e){let t=await this.run(["volume","inspect",e],!0);if(!t.trim())return;let r;try{r=JSON.parse(t)[0]}catch{return}return{providerId:String(r.Name??e),raw:{driver:String(r.Driver??"local"),mountpoint:String(r.Mountpoint??""),labels:r.Labels??{}}}}async discover(e,t){let r=await this.run(["volume","ls","--format","{{.Name}}"]),n=[];for(let o of r.split(`
|
|
1613
|
+
`}];function Er(){return mr.map(({source:e,...t})=>({...t,source:`builtin:${t.id}`,lastVerifiedAt:Ti,builtin:!0,checksum:pr("sha256").update(e).digest("hex"),exposedServices:[...t.exposedServices],inputs:t.inputs.map((r)=>({...r}))}))}function Kh(e,t){return Er().find((r)=>r.id===e&&(!t||r.version===t))}function Nc(e,t,r,n){let o=mr.find((l)=>l.id===e&&(!n||l.version===n));if(!o)throw Error(`Compose template ${e}${n?`@${n}`:""} was not found`);let a=o.source;for(let l of o.inputs){let u=t[l.name]??("default"in l?l.default:void 0);if(l.required&&!u)throw Error(`Template input ${l.name} is required`);if(u&&!/^[A-Za-z0-9._:/@+-]{1,255}$/.test(u))throw Error(`Template input ${l.name} contains unsupported characters`);a=a.replaceAll(`{{${l.name}}}`,u??"")}return Cr(a,r)}function Ry(e,t){if(Buffer.byteLength(e)>1048576)throw Error("Compose catalog exceeds the 1 MiB limit");let r;try{r=JSON.parse(e)}catch{throw Error("Compose catalog must be valid JSON")}if(r.apiVersion!=="ts-cloud.dev/compose-catalog/v1"||!Array.isArray(r.templates))throw Error("Compose catalog must use ts-cloud.dev/compose-catalog/v1 and contain templates");let n=String(r.source??"").trim();if(!/^https:\/\//.test(n)&&!n.startsWith("file:"))throw Error("Compose catalog source must be HTTPS or an explicit file: source");let o=[],a=[];for(let[l,u]of r.templates.slice(0,100).entries()){let p=u&&typeof u==="object"&&!Array.isArray(u)?u:{},E=`templates[${l}]`,g=String(p.compose??""),m=pr("sha256").update(g).digest("hex");if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(String(p.id??""))||!/^\d+\.\d+\.\d+$/.test(String(p.version??""))){o.push({severity:"error",path:E,code:"template.identity",message:"Template id and semantic version are required."});continue}if(String(p.checksum??"")!==m){o.push({severity:"error",path:`${E}.checksum`,code:"template.checksum",message:"Template checksum does not match its Compose source."});continue}let T=Cr(g,{name:String(p.name??p.id),projectId:t.projectId,environmentId:t.environmentId});o.push(...T.diagnostics.map((_)=>({..._,path:`${E}.compose.${_.path}`})));let h={id:String(p.id),name:String(p.name??p.id),description:String(p.description??""),category:String(p.category??"custom"),version:String(p.version),source:n,sourceVersion:String(p.sourceVersion??p.version),architecture:String(p.architecture??Object.keys(T.manifest.spec.services).join(" + ")),minimumResources:{cpu:Math.max(0.1,Number(p.minimumResources?.cpu)||1),memoryMb:Math.max(128,Number(p.minimumResources?.memoryMb)||512)},exposedServices:Array.isArray(p.exposedServices)?p.exposedServices.map(String):[],maintenanceNotes:String(p.maintenanceNotes??""),lastVerifiedAt:String(p.lastVerifiedAt??""),inputs:[],checksum:m,builtin:!1};a.push({template:h,parsed:T})}return{valid:!o.some((l)=>l.severity==="error"),source:n,templates:a,diagnostics:o}}function Dy(e,t,r,n,o,a){let l=Kh(r,a);if(!l)throw Error(`Compose template ${r}@${a} was not found`);let u=Nc(r,n,o,a);return{template:l,parsed:u,templateChanges:Pc(t,u.manifest),userChanges:Pc(t,e)}}var xe=/^[a-z0-9][a-z0-9_.-]{0,62}$/;function D(e){return`'${e.replaceAll("'","'\\''")}'`}function Ns(e){return`${e.metadata.slug}-${e.metadata.environmentId.slice(0,8)}`.replace(/[^a-z0-9_-]/g,"-").slice(0,63)}function Py(e,t,r={}){let n=Ns(e),o=`/opt/ts-cloud/compose/${n}`,a=`${o}/compose.yaml`,l=`docker compose --project-name ${D(n)} --file ${D(a)}`;if(r.service&&!xe.test(r.service))throw Error("Unsafe Compose service name");if(t==="deploy"||t==="redeploy"){let u=Buffer.from(Dc(e)).toString("base64");return`install -d -m 0750 ${D(o)} && printf %s ${D(u)} | base64 --decode > ${D(a)} && chmod 0640 ${D(a)} && ${l} config --quiet && ${l} up --detach --remove-orphans --wait${t==="redeploy"?" --force-recreate":""}`}if(t==="start")return`${l} start${r.service?` ${D(r.service)}`:""}`;if(t==="stop")return`${l} stop${r.service?` ${D(r.service)}`:""}`;if(t==="status")return`${l} ps --format json`;return`${l} down --remove-orphans${r.removeVolumes?" --volumes":""}`}function Ny(e,t,r){if(!xe.test(t)||!Number.isInteger(r)||r<0||r>100)throw Error("Scale requires a safe service name and 0-100 replicas");let n=Ns(e);return`docker compose --project-name ${D(n)} --file ${D(`/opt/ts-cloud/compose/${n}/compose.yaml`)} up --detach --wait --scale ${D(`${t}=${r}`)}`}function kc(e,t,r=200){if(!xe.test(t))throw Error("Unsafe Compose service name");let n=Ns(e);return`docker compose --project-name ${D(n)} --file ${D(`/opt/ts-cloud/compose/${n}/compose.yaml`)} logs --no-color --timestamps --tail ${Math.max(1,Math.min(2000,Math.floor(r)))} ${D(t)}`}function Bc(e,t,r=["sh"]){if(!xe.test(t)||!r.length||r.some((o)=>o.includes("\x00")||o.length>1024))throw Error("Unsafe Compose shell request");let n=Ns(e);return`docker compose --project-name ${D(n)} --file ${D(`/opt/ts-cloud/compose/${n}/compose.yaml`)} exec ${D(t)} ${r.map(D).join(" ")}`}import{mkdir as mt,readdir as vi,rm as Ii,stat as Si}from"node:fs/promises";import{basename as bi,resolve as gr,sep as Ri}from"node:path";var Et=/^[a-z0-9][a-z0-9_.-]{1,62}$/,_i=/^0?[0-7]{3}$/,Ni=["/","/boot","/dev","/etc","/proc","/root","/run","/sys","/var/run","/var/lib/docker","/var/lib/containers"],fi=["create","attach","detach","resize","snapshot","restore","delete","adopt","usage"],yi=(e)=>e&&typeof e==="object"&&!Array.isArray(e)?e:{};function Xh(e){return Object.fromEntries(fi.map((t)=>[t,{supported:!1,reason:e}]))}function _s(e,t={}){let r=Xh("This storage driver does not support the operation.");for(let n of e)r[n]={supported:!0};return{...r,...t}}function Yh(e){if(!e.startsWith("/")||e.includes("\x00")||e.split("/").includes(".."))throw Error("Mount target must be an absolute normalized path without traversal.");let t=e.replace(/\/+$/,"")||"/";if(Ni.some((r)=>t===r||t.startsWith(`${r}/`)))throw Error(`Mount target ${e} is a protected host or runtime path.`)}function Zh(e){if(Yh(e.targetPath),e.uid!=null&&(!Number.isInteger(e.uid)||e.uid<0))throw Error("Mount UID must be a non-negative integer.");if(e.gid!=null&&(!Number.isInteger(e.gid)||e.gid<0))throw Error("Mount GID must be a non-negative integer.");if(e.mode&&!_i.test(e.mode))throw Error("Mount mode must be a three or four digit octal value.");if(e.propagation&&!["private","rprivate","shared","rshared","slave","rslave"].includes(e.propagation))throw Error("Unsupported mount propagation mode.")}class xs{store;drivers;now;queue;constructor(e,t,r,n=()=>new Date){this.store=e;this.drivers=t;this.now=n;this.queue=r??new c(e.controlPlane)}driver(e,t){let r=this.drivers.find((n)=>n.provider===e&&n.type===t);if(!r)throw Error(`No ${e} ${t} volume driver is configured.`);return r}capability(e,t){let r=e.capabilities[t];if(!r?.supported)throw Error(r?.reason??`${t} is unsupported for this volume.`)}queueMutation(e,t,r,n,o){return this.queue.enqueue({projectId:e.projectId,environmentId:e.environmentId,resourceId:o??e.resourceId,actorId:n,kind:t,idempotencyKey:`${t}:${e.id}:v${e.version}:${JSON.stringify(r)}`,correlationId:`volume:${e.id}`,input:{volumeId:e.id,...r},lockKey:o?`resource:${o}`:`volume:${e.id}`,providerKey:e.provider,maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:365}).operation}create(e){if(!Et.test(e.name))throw Error("Volume names must be 2-63 lowercase letters, numbers, dots, dashes, or underscores.");if(e.capacityBytes!=null&&(!Number.isSafeInteger(e.capacityBytes)||e.capacityBytes<=0))throw Error("Volume capacity must be a positive byte count.");let t=this.store.controlPlane.getProject(e.projectId),r=e.environmentId?this.store.controlPlane.listEnvironments(e.projectId).find((E)=>E.id===e.environmentId):void 0,n=e.resourceId?this.store.controlPlane.getResource(e.resourceId):void 0;if(!t||t.organizationId!==e.organizationId)throw Error("Volume project does not belong to the organization.");if(e.environmentId&&!r)throw Error("Volume environment does not belong to the project.");if(n&&(n.projectId!==e.projectId||n.environmentId!==e.environmentId||n.kind!=="volume"))throw Error("Volume resource does not belong to the selected scope.");let o=n??this.store.controlPlane.createResource({projectId:e.projectId,environmentId:e.environmentId,kind:"volume",slug:e.name,name:e.name,provider:e.provider,desiredState:{type:e.type,capacityBytes:e.capacityBytes??null,filesystem:e.filesystem??null,encrypted:!!e.encrypted}}),a=this.driver(e.provider,e.type),l=a.capabilities(),u=this.store.create({organizationId:e.organizationId,projectId:e.projectId,environmentId:e.environmentId,resourceId:o.id,name:e.name,provider:e.provider,type:e.type,status:"pending",capacityBytes:e.capacityBytes,filesystem:e.filesystem,encrypted:!!e.encrypted,capabilities:l,desiredState:e.desiredState??{},observedState:{}}),p=this.queueMutation(u,"volume.create",{},e.actorId);return this.store.audit({organizationId:u.organizationId,projectId:u.projectId,environmentId:u.environmentId,actorId:e.actorId,type:"volume.create.queued",volumeId:u.id,payload:{name:u.name,type:u.type}}),{volume:u,operation:p}}attach(e,t){let r=this.store.get(e);if(!r)throw Error("Volume was not found.");this.capability(r,"attach"),Zh(t);let n=this.store.controlPlane.getResource(t.resourceId);if(!n||n.projectId!==r.projectId||n.environmentId!==r.environmentId)throw Error("Cross-project or cross-environment volume attachments are forbidden.");let o=this.store.upsertAttachment({volumeId:e,resourceId:t.resourceId,targetPath:t.targetPath,readOnly:!!t.readOnly,uid:t.uid,gid:t.gid,mode:t.mode,propagation:t.propagation??"private",driverOptions:t.driverOptions??{},desiredState:"attached",observedState:"pending"}),a=this.queueMutation(r,"volume.attach",{attachmentId:o.id},t.actorId,t.resourceId);return this.store.updateAttachment(o.id,{operationId:a.id}),this.store.update(r.id,r.version,{status:"attaching"}),this.store.audit({organizationId:r.organizationId,projectId:r.projectId,environmentId:r.environmentId,actorId:t.actorId,type:"volume.attach.queued",volumeId:e,payload:{resourceId:t.resourceId,targetPath:t.targetPath}}),{volume:this.store.get(r.id),attachment:this.store.attachment(o.id),operation:a}}detach(e,t,r={}){let n=this.store.get(e),o=this.store.attachment(t);if(!n||!o||o.volumeId!==e)throw Error("Volume attachment was not found.");if(this.capability(n,"detach"),o.observedState==="attached"&&(!r.drained||!r.unmounted))throw Error("Detach requires completed workload drain and filesystem unmount checkpoints.");if(r.force&&r.confirmation!==`detach ${n.name}`)throw Error(`Force detach requires confirmation: detach ${n.name}`);let a=this.store.updateAttachment(t,{desiredState:"detached"}),l=this.queueMutation(n,"volume.detach",{attachmentId:t,force:!!r.force},r.actorId,o.resourceId);return this.store.updateAttachment(t,{operationId:l.id}),this.store.update(n.id,n.version,{status:"detaching"}),{volume:this.store.get(e),attachment:a,operation:l}}resize(e,t,r={}){let n=this.store.get(e);if(!n)throw Error("Volume was not found.");if(this.capability(n,"resize"),!Number.isSafeInteger(t)||t<=0)throw Error("Volume capacity must be a positive byte count.");if(n.capacityBytes!=null&&t<n.capacityBytes)throw Error("Volume shrinking is not supported because it can corrupt data.");let o=n.capabilities.resize;if(o.minimumBytes&&t<o.minimumBytes)throw Error(`Minimum supported capacity is ${o.minimumBytes} bytes.`);if(o.maximumBytes&&t>o.maximumBytes)throw Error(`Maximum supported capacity is ${o.maximumBytes} bytes.`);if(o.online===!1&&!r.drained)throw Error("This resize requires a completed workload drain checkpoint.");let a=this.store.update(e,n.version,{status:"resizing",desiredState:{...n.desiredState,capacityBytes:t}}),l=this.queueMutation(a,"volume.resize",{capacityBytes:t},r.actorId);return{volume:a,operation:l}}snapshot(e,t={}){let r=this.store.get(e);if(!r)throw Error("Volume was not found.");this.capability(r,"snapshot");let n=this.store.createSnapshot({volumeId:e,name:t.name??`${r.name}-${this.now().toISOString().replace(/[:.]/g,"-")}`,status:"pending",encrypted:r.encrypted,metadata:{}}),o=this.store.update(e,r.version,{status:"snapshotting"}),a=this.queueMutation(o,"volume.snapshot",{snapshotId:n.id},t.actorId);return{volume:o,snapshot:n,operation:a}}restore(e,t){let r=this.store.snapshot(e),n=r?this.store.get(r.volumeId):void 0;if(!r||!n||r.status!=="available")throw Error("An available volume snapshot is required for restore.");if(this.capability(n,"restore"),!Et.test(t.name))throw Error("Restored volume names must be 2-63 lowercase letters, numbers, dots, dashes, or underscores.");let o=this.store.controlPlane.createResource({projectId:n.projectId,environmentId:n.environmentId,kind:"volume",slug:t.name,name:t.name,provider:n.provider,desiredState:{restoreFromSnapshotId:r.id}}),a=this.store.create({organizationId:n.organizationId,projectId:n.projectId,environmentId:n.environmentId,resourceId:o.id,name:t.name,provider:n.provider,type:n.type,status:"pending",capacityBytes:r.sizeBytes??n.capacityBytes,filesystem:n.filesystem,encrypted:r.encrypted,capabilities:n.capabilities,desiredState:{restoreFromSnapshotId:r.id,sourceVolumeId:n.id},observedState:{}}),l=this.queueMutation(a,"volume.restore",{snapshotId:r.id,sourceVolumeId:n.id},t.actorId);return{volume:a,snapshot:r,operation:l}}delete(e,t){let r=this.store.get(e);if(!r)throw Error("Volume was not found.");this.capability(r,"delete");let n=this.store.attachments(e).filter((u)=>u.desiredState==="attached"||u.observedState==="attached");if(n.length)throw Error(`Detach ${n.length} active consumer(s) before deleting this volume.`);if(!t.recentAuthAt||this.now().getTime()-new Date(t.recentAuthAt).getTime()>900000)throw Error("Volume deletion requires authentication verified within the last 15 minutes.");if(t.confirmation!==r.name)throw Error(`Type ${r.name} to confirm permanent volume deletion.`);if(!(r.lastBackupAt&&this.now().getTime()-new Date(r.lastBackupAt).getTime()<=86400000)&&(!t.backupOverride||t.backupOverrideConfirmation!==`delete without backup ${r.name}`))throw Error(`A verified backup from the last 24 hours is required, or confirm: delete without backup ${r.name}`);let a=this.store.update(e,r.version,{status:"deleting"}),l=this.queueMutation(a,"volume.delete",{backupOverride:!!t.backupOverride},t.actorId);return{volume:a,operation:l}}async discover(e){let t=new Set;for(let r of this.drivers)for(let n of await r.discover(e.projectId,e.environmentId)){let o=this.store.list({projectId:e.projectId,environmentId:e.environmentId}).find((l)=>l.provider===r.provider&&l.providerId===n.providerId);if(o){t.add(o.id),this.store.update(o.id,o.version,{capacityBytes:n.capacityBytes,usedBytes:n.usedBytes,filesystem:n.filesystem,encrypted:n.encrypted??o.encrypted,observedState:n.raw??{},status:o.status==="orphaned"?"available":o.status,orphanedAt:void 0});continue}let a=this.store.create({organizationId:e.organizationId,projectId:e.projectId,environmentId:e.environmentId,name:`orphan-${n.providerId}`.toLowerCase().replace(/[^a-z0-9_.-]/g,"-").slice(0,63),provider:r.provider,providerId:n.providerId,type:r.type,status:"orphaned",capacityBytes:n.capacityBytes,usedBytes:n.usedBytes,filesystem:n.filesystem,encrypted:!!n.encrypted,capabilities:r.capabilities(),desiredState:{},observedState:n.raw??{},orphanedAt:this.now().toISOString()});t.add(a.id)}return this.store.list({projectId:e.projectId,environmentId:e.environmentId})}adopt(e,t){let r=this.store.get(e);if(!r||r.status!=="orphaned")throw Error("Only discovered orphan volumes can be adopted.");if(!Et.test(t.name))throw Error("Volume names must be 2-63 lowercase letters, numbers, dots, dashes, or underscores.");let n=this.store.update(e,r.version,{name:t.name,status:"available",adoptedAt:this.now().toISOString(),orphanedAt:void 0});return this.store.audit({organizationId:r.organizationId,projectId:r.projectId,environmentId:r.environmentId,actorId:t.actorId,type:"volume.adopted",volumeId:e,payload:{providerId:r.providerId??null}}),n}}function Li(e){let t=yi(e.input);if(typeof t.volumeId!=="string")throw Error("Queued volume operation is missing its volume identity.");return{volumeId:t.volumeId,sourceVolumeId:typeof t.sourceVolumeId==="string"?t.sourceVolumeId:void 0,attachmentId:typeof t.attachmentId==="string"?t.attachmentId:void 0,snapshotId:typeof t.snapshotId==="string"?t.snapshotId:void 0,capacityBytes:typeof t.capacityBytes==="number"?t.capacityBytes:void 0,force:t.force===!0}}function xc(e,t){let r=(o)=>{let a=t.find((l)=>l.provider===o.provider&&l.type===o.type);if(!a)throw Error(`No ${o.provider} ${o.type} volume driver is configured.`);return a},n=async(o)=>{let a=Li(o.operation),l=e.get(a.volumeId);if(!l)throw Error("Queued volume was not found.");let u=r(l);o.checkpoint("preflight","Validating persistent volume identity and capabilities."),o.throwIfCancellationRequested();let p;if(o.operation.kind==="volume.create")p=await u.create(l),e.update(l.id,l.version,{providerId:p.providerId,capacityBytes:p.capacityBytes??l.capacityBytes,usedBytes:p.usedBytes,filesystem:p.filesystem??l.filesystem,encrypted:p.encrypted??l.encrypted,observedState:p.raw??{},status:"available"});else if(o.operation.kind==="volume.attach"){let E=a.attachmentId?e.attachment(a.attachmentId):void 0;if(!E)throw Error("Queued volume attachment was not found.");await u.attach(l,E),e.updateAttachment(E.id,{observedState:"attached",lastError:void 0}),e.update(l.id,l.version,{status:"attached"})}else if(o.operation.kind==="volume.detach"){let E=a.attachmentId?e.attachment(a.attachmentId):void 0;if(!E)throw Error("Queued volume attachment was not found.");await u.detach(l,E,{force:a.force}),e.updateAttachment(E.id,{observedState:"detached",lastError:void 0});let g=e.attachments(l.id).some((m)=>m.id!==E.id&&m.observedState==="attached");e.update(l.id,l.version,{status:g?"attached":"available"})}else if(o.operation.kind==="volume.resize"){if(!a.capacityBytes)throw Error("Queued volume resize is missing its capacity.");p=await u.resize(l,a.capacityBytes),e.update(l.id,l.version,{capacityBytes:p.capacityBytes??a.capacityBytes,usedBytes:p.usedBytes??l.usedBytes,observedState:p.raw??l.observedState,status:e.attachments(l.id).some((E)=>E.observedState==="attached")?"attached":"available"})}else if(o.operation.kind==="volume.snapshot"){let E=a.snapshotId?e.snapshot(a.snapshotId):void 0;if(!E)throw Error("Queued volume snapshot was not found.");let g=await u.snapshot(l,E);e.updateSnapshot(E.id,{...g,status:"available"}),e.update(l.id,l.version,{status:e.attachments(l.id).some((m)=>m.observedState==="attached")?"attached":"available",lastBackupAt:new Date().toISOString()})}else if(o.operation.kind==="volume.restore"){let E=a.snapshotId?e.snapshot(a.snapshotId):void 0,g=a.sourceVolumeId?e.get(a.sourceVolumeId):void 0;if(!E||!g)throw Error("Queued volume restore source was not found.");p=await u.restore(g,E,l),e.update(l.id,l.version,{providerId:p.providerId,capacityBytes:p.capacityBytes??l.capacityBytes,usedBytes:p.usedBytes,filesystem:p.filesystem??l.filesystem,encrypted:p.encrypted??l.encrypted,observedState:p.raw??{},status:"available"})}else if(o.operation.kind==="volume.delete")await u.delete(l),e.update(l.id,l.version,{status:"deleted",deletedAt:new Date().toISOString()});return o.checkpoint("finalize","Persisted observed volume state."),{volumeId:l.id,status:e.get(l.id)?.status??"deleted"}};return Object.fromEntries(["volume.create","volume.attach","volume.detach","volume.resize","volume.snapshot","volume.restore","volume.delete"].map((o)=>[o,n]))}var Ci=async(e)=>{let t=Bun.spawn(["docker",...e],{stdout:"pipe",stderr:"pipe"}),[r,n,o]=await Promise.all([t.exited,new Response(t.stdout).text(),new Response(t.stderr).text()]);return{code:r,stdout:n,stderr:o}},ee=/^[A-Za-z0-9][A-Za-z0-9_.-]{1,127}$/;class vr{command;provider="docker";type="docker";constructor(e=Ci){this.command=e}capabilities(){return _s(["create","attach","detach","delete","adopt","usage"],{resize:{supported:!1,reason:"Docker named volumes do not expose a portable capacity resize operation."},snapshot:{supported:!1,reason:"Attach a volume backup policy to create verified recovery points."},restore:{supported:!1,reason:"Restore this volume from its verified backup recovery point."}})}async run(e,t=!1){let r=await this.command(e);if(r.code!==0&&!t)throw Error(`Docker volume command failed: ${r.stderr.trim()||r.code}`);return r.stdout}async inspect(e){let t=await this.run(["volume","inspect",e],!0);if(!t.trim())return;let r;try{r=JSON.parse(t)[0]}catch{return}return{providerId:String(r.Name??e),raw:{driver:String(r.Driver??"local"),mountpoint:String(r.Mountpoint??""),labels:r.Labels??{}}}}async discover(e,t){let r=await this.run(["volume","ls","--format","{{.Name}}"]),n=[];for(let o of r.split(`
|
|
1614
1614
|
`).map((a)=>a.trim()).filter(ee.test.bind(ee))){let a=await this.inspect(o);if(a)n.push(a)}return n}async create(e){let t=typeof e.desiredState.nativeName==="string"?e.desiredState.nativeName:e.name;if(!ee.test(t))throw Error("Docker volume name is invalid.");return await this.run(["volume","create","--label",`ts-cloud.volume=${e.id}`,"--label",`ts-cloud.project=${e.projectId}`,t]),await this.inspect(t)??{providerId:t}}async attach(e,t){}async detach(e,t){}async resize(){throw Error(this.capabilities().resize.reason)}async snapshot(){throw Error(this.capabilities().snapshot.reason)}async restore(e,t,r){throw Error(this.capabilities().restore.reason)}async delete(e){if(!e.providerId||!ee.test(e.providerId))throw Error("Docker volume provider identity is missing or invalid.");await this.run(["volume","rm",e.providerId])}async usage(e){let t=await this.run(["system","df","-v","--format","{{json .}}"],!0),r=t.split(`
|
|
1615
|
-
`).find((n)=>n.includes(`"Name":"${e.providerId}"`));if(!r)return{};try{let n=JSON.parse(r);return{usedBytes:typeof n.Size==="number"?n.Size:void 0}}catch{return{}}}}class xs{provider="server";type="server_path";root;constructor(e){this.root=gr(e)}capabilities(){return ks(["create","attach","detach","delete","adopt","usage"],{resize:{supported:!1,reason:"Server paths use the capacity of their containing filesystem."},snapshot:{supported:!1,reason:"Attach a filesystem backup policy for verified recovery points."},restore:{supported:!1,reason:"Restore a filesystem recovery point into a new managed path."}})}path(e){if(!ee.test(e))throw Error("Server path volume name is invalid.");let t=gr(this.root,e);if(!t.startsWith(`${this.root}${Ri}`)||bi(t)!==e)throw Error("Server path escaped the managed volume root.");return t}async discover(e,t){return await mt(this.root,{recursive:!0,mode:488}),(await vi(this.root,{withFileTypes:!0})).filter((n)=>n.isDirectory()&&ee.test(n.name)).map((n)=>({providerId:n.name,raw:{path:this.path(n.name)}}))}async create(e){let t=typeof e.desiredState.nativeName==="string"?e.desiredState.nativeName:e.name,r=this.path(t);return await mt(this.root,{recursive:!0,mode:488}),await mt(r,{recursive:!1,mode:488}),{providerId:t,filesystem:"host",raw:{path:r}}}async attach(e,t){}async detach(e,t){}async resize(){throw Error(this.capabilities().resize.reason)}async snapshot(){throw Error(this.capabilities().snapshot.reason)}async restore(e,t,r){throw Error(this.capabilities().restore.reason)}async delete(e){if(!e.providerId)throw Error("Server path provider identity is unavailable.");await Ii(this.path(e.providerId),{recursive:!0,force:!1})}async usage(e){if(!e.providerId)return{};return{usedBytes:(await Si(this.path(e.providerId))).size}}}class zh{provider;transport;type="ebs";constructor(e,t){this.provider=e;this.transport=t}capabilities(){return ks(["create","attach","detach","resize","snapshot","restore","delete","adopt","usage"],{resize:{supported:!0,online:!0,minimumBytes:1073741824}})}discover(e,t){return this.transport.list(e,t)}create(e){return this.transport.create({name:e.name,projectId:e.projectId,environmentId:e.environmentId,capacityBytes:e.capacityBytes,encrypted:e.encrypted,filesystem:e.filesystem})}resource(e,t){let r=e.resourceId===t.resourceId?e.observedState.resourceProviderId:void 0,n=typeof r==="string"?r:t.driverOptions.resourceProviderId;if(typeof n!=="string"||!n)throw Error("Cloud attachment requires a reviewed resourceProviderId driver option.");return n}attach(e,t){return this.transport.attach(e.providerId,this.resource(e,t),t.targetPath,t.readOnly)}detach(e,t,r){return this.transport.detach(e.providerId,this.resource(e,t),r.force)}resize(e,t){return this.transport.resize(e.providerId,t)}snapshot(e,t){return this.transport.snapshot(e.providerId,t.name)}restore(e,t,r){if(!t.providerId)throw Error("Cloud snapshot provider identity is unavailable.");return this.transport.restore(e.providerId,t.providerId,r.name)}delete(e){return this.transport.delete(e.providerId)}usage(e){return this.transport.usage(e.providerId)}}var F=(e)=>e==null?void 0:String(e),ge=(e,t)=>{try{return JSON.parse(String(e))}catch{return t}},gt=(e)=>Number(e)===1,te=(e)=>e().toISOString();function _r(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:F(e.environment_id),resourceId:F(e.resource_id),name:String(e.name),provider:String(e.provider),providerId:F(e.provider_id),type:String(e.type),status:String(e.status),capacityBytes:e.capacity_bytes==null?void 0:Number(e.capacity_bytes),usedBytes:e.used_bytes==null?void 0:Number(e.used_bytes),filesystem:F(e.filesystem),encrypted:gt(e.encrypted),capabilities:ge(e.capabilities,{}),desiredState:ge(e.desired_state,{}),observedState:ge(e.observed_state,{}),backupPolicyId:F(e.backup_policy_id),lastBackupAt:F(e.last_backup_at),orphanedAt:F(e.orphaned_at),adoptedAt:F(e.adopted_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at),deletedAt:F(e.deleted_at)}}function Tt(e){return{id:String(e.id),volumeId:String(e.volume_id),resourceId:String(e.resource_id),targetPath:String(e.target_path),readOnly:gt(e.read_only),uid:e.uid==null?void 0:Number(e.uid),gid:e.gid==null?void 0:Number(e.gid),mode:F(e.mode),propagation:String(e.propagation),driverOptions:ge(e.driver_options,{}),desiredState:String(e.desired_state),observedState:String(e.observed_state),operationId:F(e.operation_id),lastError:F(e.last_error),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function hr(e){return{id:String(e.id),volumeId:String(e.volume_id),recoveryPointId:F(e.recovery_point_id),providerId:F(e.provider_id),name:String(e.name),status:String(e.status),sizeBytes:e.size_bytes==null?void 0:Number(e.size_bytes),encrypted:gt(e.encrypted),checksum:F(e.checksum),metadata:ge(e.metadata,{}),createdAt:String(e.created_at),updatedAt:String(e.updated_at),deletedAt:F(e.deleted_at)}}class _t{controlPlane;now;id;constructor(e,t=()=>new Date,r=()=>crypto.randomUUID()){this.controlPlane=e;this.now=t;this.id=r}get(e){let t=this.controlPlane.database.query("SELECT * FROM persistent_volumes WHERE id=?").get(e);return t?_r(t):void 0}list(e){let t=["project_id=?"],r=[e.projectId];if(e.environmentId)t.push("environment_id=?"),r.push(e.environmentId);if(!e.includeDeleted)t.push("deleted_at IS NULL");return this.controlPlane.database.query(`SELECT * FROM persistent_volumes WHERE ${t.join(" AND ")} ORDER BY name`).all(...r).map(_r)}create(e){let t=te(this.now),r=e.id??this.id();return this.controlPlane.database.run("INSERT INTO persistent_volumes (id,organization_id,project_id,environment_id,resource_id,name,provider,provider_id,type,status,capacity_bytes,used_bytes,filesystem,encrypted,capabilities,desired_state,observed_state,backup_policy_id,last_backup_at,orphaned_at,adopted_at,created_at,updated_at,deleted_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[r,e.organizationId,e.projectId,e.environmentId??null,e.resourceId??null,e.name,e.provider,e.providerId??null,e.type,e.status,e.capacityBytes??null,e.usedBytes??null,e.filesystem??null,e.encrypted?1:0,JSON.stringify(e.capabilities),JSON.stringify(e.desiredState),JSON.stringify(e.observedState),e.backupPolicyId??null,e.lastBackupAt??null,e.orphanedAt??null,e.adoptedAt??null,t,t,e.deletedAt??null]),this.get(r)}update(e,t,r){let n=this.get(e);if(!n||n.version!==t)throw Error("Volume changed before this operation could be applied.");let o={...n,...r,updatedAt:te(this.now)};if(this.controlPlane.database.run("UPDATE persistent_volumes SET environment_id=?,resource_id=?,name=?,provider=?,provider_id=?,type=?,status=?,capacity_bytes=?,used_bytes=?,filesystem=?,encrypted=?,capabilities=?,desired_state=?,observed_state=?,backup_policy_id=?,last_backup_at=?,orphaned_at=?,adopted_at=?,deleted_at=?,version=version+1,updated_at=? WHERE id=? AND version=?",[o.environmentId??null,o.resourceId??null,o.name,o.provider,o.providerId??null,o.type,o.status,o.capacityBytes??null,o.usedBytes??null,o.filesystem??null,o.encrypted?1:0,JSON.stringify(o.capabilities),JSON.stringify(o.desiredState),JSON.stringify(o.observedState),o.backupPolicyId??null,o.lastBackupAt??null,o.orphanedAt??null,o.adoptedAt??null,o.deletedAt??null,o.updatedAt,e,t]).changes!==1)throw Error("Volume changed before this operation could be applied.");return this.get(e)}attachments(e){return this.controlPlane.database.query("SELECT * FROM volume_attachments WHERE volume_id=? ORDER BY target_path").all(e).map(Tt)}attachment(e){let t=this.controlPlane.database.query("SELECT * FROM volume_attachments WHERE id=?").get(e);return t?Tt(t):void 0}upsertAttachment(e){let t=this.controlPlane.database.query("SELECT * FROM volume_attachments WHERE volume_id=? AND resource_id=? AND target_path=?").get(e.volumeId,e.resourceId,e.targetPath),r=te(this.now);if(t){let o=Tt(t);return this.controlPlane.database.run("UPDATE volume_attachments SET read_only=?,uid=?,gid=?,mode=?,propagation=?,driver_options=?,desired_state=?,observed_state=?,operation_id=?,last_error=?,version=version+1,updated_at=? WHERE id=?",[e.readOnly?1:0,e.uid??null,e.gid??null,e.mode??null,e.propagation,JSON.stringify(e.driverOptions),e.desiredState,e.observedState,e.operationId??null,e.lastError??null,r,o.id]),this.attachment(o.id)}let n=e.id??this.id();return this.controlPlane.database.run("INSERT INTO volume_attachments (id,volume_id,resource_id,target_path,read_only,uid,gid,mode,propagation,driver_options,desired_state,observed_state,operation_id,last_error,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[n,e.volumeId,e.resourceId,e.targetPath,e.readOnly?1:0,e.uid??null,e.gid??null,e.mode??null,e.propagation,JSON.stringify(e.driverOptions),e.desiredState,e.observedState,e.operationId??null,e.lastError??null,r,r]),this.attachment(n)}updateAttachment(e,t){let r=this.attachment(e);if(!r)throw Error("Volume attachment was not found.");let n={...r,...t};return this.controlPlane.database.run("UPDATE volume_attachments SET desired_state=?,observed_state=?,operation_id=?,last_error=?,version=version+1,updated_at=? WHERE id=?",[n.desiredState,n.observedState,n.operationId??null,n.lastError??null,te(this.now),e]),this.attachment(e)}snapshots(e){return this.controlPlane.database.query("SELECT * FROM volume_snapshots WHERE volume_id=? AND deleted_at IS NULL ORDER BY created_at DESC").all(e).map(hr)}snapshot(e){let t=this.controlPlane.database.query("SELECT * FROM volume_snapshots WHERE id=?").get(e);return t?hr(t):void 0}createSnapshot(e){let t=e.id??this.id(),r=te(this.now);return this.controlPlane.database.run("INSERT INTO volume_snapshots (id,volume_id,recovery_point_id,provider_id,name,status,size_bytes,encrypted,checksum,metadata,created_at,updated_at,deleted_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.volumeId,e.recoveryPointId??null,e.providerId??null,e.name,e.status,e.sizeBytes??null,e.encrypted?1:0,e.checksum??null,JSON.stringify(e.metadata),r,r,e.deletedAt??null]),this.snapshot(t)}updateSnapshot(e,t){let r=this.snapshot(e);if(!r)throw Error("Volume snapshot was not found.");let n={...r,...t};return this.controlPlane.database.run("UPDATE volume_snapshots SET recovery_point_id=?,provider_id=?,name=?,status=?,size_bytes=?,encrypted=?,checksum=?,metadata=?,deleted_at=?,updated_at=? WHERE id=?",[n.recoveryPointId??null,n.providerId??null,n.name,n.status,n.sizeBytes??null,n.encrypted?1:0,n.checksum??null,JSON.stringify(n.metadata),n.deletedAt??null,te(this.now),e]),this.snapshot(e)}inventory(e,t){return this.list({projectId:e,environmentId:t}).map((r)=>{let n=this.attachments(r.id),o=this.snapshots(r.id),a=r.lastBackupAt?Date.now()-new Date(r.lastBackupAt).getTime():1/0;return{...r,attachments:n,snapshots:o,orphaned:r.status==="orphaned",usagePercent:r.capacityBytes&&r.usedBytes!=null?Math.round(r.usedBytes/r.capacityBytes*1000)/10:void 0,backupState:r.backupPolicyId?a<=86400000?"protected":"stale":"unprotected"}})}audit(e){this.controlPlane.appendEvent({organizationId:e.organizationId,projectId:e.projectId,resourceId:this.get(e.volumeId)?.resourceId,actorId:e.actorId,type:e.type,level:"warning",payload:{volumeId:e.volumeId,environmentId:e.environmentId??null,...e.payload}})}}function xc(e,t){let r=e.getProject(t.projectId);if(!r?.organizationId)return;let n=new _t(e),o=new vr,a=new Set(t.manifest.spec.volumes),l=new Set;for(let u of a){let p=`${t.slug}-${u}`.toLowerCase().replace(/[^a-z0-9_.-]/g,"-").slice(0,63),E=n.list({projectId:t.projectId,environmentId:t.environmentId,includeDeleted:!0}).find((N)=>N.name===p);if(E?.deletedAt)throw Error(`Compose volume ${p} was permanently deleted; rename it before redeploying.`);let g=E?.resourceId?e.getResource(E.resourceId):e.createResource({projectId:t.projectId,environmentId:t.environmentId,kind:"volume",slug:p,name:p,provider:"docker",providerId:p,desiredState:{composeApplicationId:t.id,composeVolume:u}}),m=E??n.create({organizationId:r.organizationId,projectId:t.projectId,environmentId:t.environmentId,resourceId:g?.id,name:p,provider:"docker",providerId:p,type:"docker",status:"available",encrypted:!1,capabilities:o.capabilities(),desiredState:{composeApplicationId:t.id,composeVolume:u,nativeName:p},observedState:{}});l.add(m.id);let T=new Map;for(let N of Object.values(t.manifest.spec.services))for(let h of N.volumes.filter((f)=>f.source===u)){let f=T.get(h.target)??[];f.push(N.name),T.set(h.target,f),n.upsertAttachment({volumeId:m.id,resourceId:t.resourceId,targetPath:h.target,readOnly:h.readOnly,propagation:"private",driverOptions:{composeServices:f},desiredState:"attached",observedState:"pending"})}}for(let u of n.list({projectId:t.projectId,environmentId:t.environmentId}).filter((p)=>p.desiredState.composeApplicationId===t.id&&!l.has(p.id)))for(let p of n.attachments(u.id))n.updateAttachment(p.id,{desiredState:"detached"})}function dp(e,t,r){let n=new _t(e);for(let o of n.list({projectId:t.projectId,environmentId:t.environmentId}).filter((a)=>a.desiredState.composeApplicationId===t.id)){for(let a of n.attachments(o.id))n.updateAttachment(a.id,{desiredState:"detached",observedState:"detached"});n.update(o.id,o.version,{status:r?"deleted":"available",deletedAt:r?new Date().toISOString():void 0})}}function re(e){return typeof e==="string"&&e?e:void 0}function ht(e,t){try{return JSON.parse(String(e))}catch{return t}}function je(e){return{id:String(e.id),resourceId:String(e.resource_id),projectId:String(e.project_id),environmentId:String(e.environment_id),name:String(e.name),slug:String(e.slug),status:String(e.status),sourceKind:String(e.source_kind),sourceHash:String(e.source_hash),redactedSource:String(e.redacted_source),manifest:ht(e.manifest,{}),diagnostics:ht(e.diagnostics,[]),templateId:re(e.template_id),templateVersion:re(e.template_version),latestOperationId:re(e.latest_operation_id),createdByActorId:re(e.created_by_actor_id),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at),deletedAt:re(e.deleted_at)}}function Ai(e){return{applicationId:String(e.application_id),serviceName:String(e.service_name),status:String(e.status),replicas:Number(e.replicas),healthyReplicas:Number(e.healthy_replicas),latestOperationId:re(e.latest_operation_id),observedState:ht(e.observed_state,{}),updatedAt:String(e.updated_at)}}class Ot{controlPlane;now;id;constructor(e,t={}){this.controlPlane=e;this.now=t.now??(()=>new Date),this.id=t.id??(()=>crypto.randomUUID())}persist(e,t){if(!e.valid)throw Error(`Compose definition contains ${e.diagnostics.filter((h)=>h.severity==="error").length} blocking diagnostic(s)`);let{projectId:r,environmentId:n,name:o,slug:a}=e.manifest.metadata;if(!this.controlPlane.listEnvironments(r).find((h)=>h.id===n))throw Error("Compose project and environment scope was not found");let u=this.getBySlug(r,n,a),p=this.now().toISOString(),E=JSON.stringify(e.manifest),g=JSON.stringify(s(e.diagnostics));if(u){if(u.status==="deleted")throw Error("A deleted Compose application cannot be overwritten; choose another slug");let h=this.controlPlane.getResource(u.resourceId);if(!h)throw Error("Compose application resource was not found");this.controlPlane.updateResource(h.id,h.version,{name:o,provider:h.provider,providerId:h.providerId,desiredState:e.manifest,discoveredState:h.discoveredState,metadata:{sourceKind:t.sourceKind,templateId:t.templateId??null,templateVersion:t.templateVersion??null,sourceHash:e.sourceHash}}),this.controlPlane.database.run("UPDATE compose_applications SET name=?, status='ready', source_kind=?, source_hash=?, redacted_source=?, manifest=?, diagnostics=?, template_id=?, template_version=?, version=version+1, updated_at=? WHERE id=?",[o,t.sourceKind,e.sourceHash,e.redactedSource,E,g,t.templateId??null,t.templateVersion??null,p,u.id]);let f=Object.keys(e.manifest.spec.services);if(f.length)this.controlPlane.database.run(`DELETE FROM compose_service_states WHERE application_id=? AND service_name NOT IN (${f.map(()=>"?").join(",")})`,[u.id,...f]);for(let v of Object.values(e.manifest.spec.services))this.controlPlane.database.run("INSERT INTO compose_service_states (application_id, service_name, status, replicas, healthy_replicas, observed_state, updated_at) VALUES (?, ?, 'pending', ?, 0, '{}', ?) ON CONFLICT(application_id, service_name) DO UPDATE SET replicas=excluded.replicas, updated_at=excluded.updated_at",[u.id,v.name,v.replicas,p]);this.controlPlane.appendEvent({projectId:r,resourceId:u.resourceId,actorId:t.createdByActorId,type:"compose.application.updated",payload:{applicationId:u.id,sourceHash:e.sourceHash,diagnosticCount:e.diagnostics.length,templateId:t.templateId??null,templateVersion:t.templateVersion??null}});let L=this.get(u.id);return xc(this.controlPlane,L),L}let m=this.controlPlane.createResource({projectId:r,environmentId:n,kind:"compose_application",slug:a,name:o,desiredState:e.manifest,metadata:{sourceKind:t.sourceKind,templateId:t.templateId??null,templateVersion:t.templateVersion??null,sourceHash:e.sourceHash}}),T=this.id();this.controlPlane.database.run("INSERT INTO compose_applications (id, resource_id, project_id, environment_id, name, slug, status, source_kind, source_hash, redacted_source, manifest, diagnostics, template_id, template_version, created_by_actor_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, 'ready', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[T,m.id,r,n,o,a,t.sourceKind,e.sourceHash,e.redactedSource,E,g,t.templateId??null,t.templateVersion??null,t.createdByActorId??null,p,p]);for(let h of Object.values(e.manifest.spec.services))this.controlPlane.database.run("INSERT INTO compose_service_states (application_id, service_name, status, replicas, healthy_replicas, observed_state, updated_at) VALUES (?, ?, 'pending', ?, 0, '{}', ?)",[T,h.name,h.replicas,p]);this.controlPlane.appendEvent({projectId:r,resourceId:m.id,actorId:t.createdByActorId,type:"compose.application.created",payload:{applicationId:T,sourceHash:e.sourceHash,serviceNames:Object.keys(e.manifest.spec.services),templateId:t.templateId??null}});let N=this.get(T);return xc(this.controlPlane,N),N}import(e,t){let r=Cr(e,t);return{application:this.persist(r,{sourceKind:"compose",createdByActorId:t.createdByActorId}),parsed:r}}fromTemplate(e,t,r){let n=Dc(e,t,r,r.version);return{application:this.persist(n,{sourceKind:"template",templateId:e,templateVersion:r.version??"1.0.0",createdByActorId:r.createdByActorId}),parsed:n}}preview(e,t){return Cr(e,t)}get(e){let t=this.controlPlane.database.query("SELECT * FROM compose_applications WHERE id=?").get(e);return t?je(t):void 0}getByResource(e){let t=this.controlPlane.database.query("SELECT * FROM compose_applications WHERE resource_id=?").get(e);return t?je(t):void 0}getBySlug(e,t,r){let n=this.controlPlane.database.query("SELECT * FROM compose_applications WHERE project_id=? AND environment_id=? AND slug=?").get(e,t,r);return n?je(n):void 0}list(e={}){return this.controlPlane.database.query("SELECT * FROM compose_applications ORDER BY updated_at DESC").all().map(je).filter((t)=>(!e.projectId||t.projectId===e.projectId)&&(!e.environmentId||t.environmentId===e.environmentId)&&(e.includeDeleted||t.status!=="deleted"))}services(e){return this.controlPlane.database.query("SELECT * FROM compose_service_states WHERE application_id=? ORDER BY service_name").all(e).map(Ai)}transition(e,t,r={}){let n=this.get(e);if(!n)throw Error(`Compose application ${e} was not found`);let o=this.now().toISOString(),a=t==="deleted"?o:null;this.controlPlane.database.run("UPDATE compose_applications SET status=?, latest_operation_id=COALESCE(?, latest_operation_id), version=version+1, updated_at=?, deleted_at=? WHERE id=?",[t,r.operationId??null,o,a,e]);for(let l of r.services??[])if(n.manifest.spec.services[l.name])this.controlPlane.database.run("INSERT INTO compose_service_states (application_id, service_name, status, replicas, healthy_replicas, latest_operation_id, observed_state, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(application_id, service_name) DO UPDATE SET status=excluded.status, replicas=excluded.replicas, healthy_replicas=excluded.healthy_replicas, latest_operation_id=excluded.latest_operation_id, observed_state=excluded.observed_state, updated_at=excluded.updated_at",[e,l.name,l.status,l.replicas??n.manifest.spec.services[l.name].replicas,l.healthyReplicas??0,r.operationId??null,JSON.stringify(s(l.observedState??{})),o]);return this.controlPlane.appendEvent({projectId:n.projectId,resourceId:n.resourceId,operationId:r.operationId,type:`compose.application.${t}`,level:t==="failed"||t==="degraded"?"error":"info",payload:{applicationId:e,error:r.error??null}}),this.get(e)}}class Tr{controlPlane;applications;queue;constructor(e){this.controlPlane=e;this.applications=new Ot(e),this.queue=new c(e)}enqueue(e,t,r={}){if(e.status==="deleted")throw Error("Deleted Compose applications cannot be operated");if(r.service&&!e.manifest.spec.services[r.service])throw Error(`Compose service ${r.service} was not found`);if(t==="delete"){let o=r.removeVolumes?`${e.slug} delete volumes`:e.slug;if(r.confirmation!==o)throw Error(`Type ${o} to confirm ${r.removeVolumes?"persistent data removal":"stack deletion"}`)}if(t==="scale"&&(!r.service||!Number.isInteger(r.replicas)||r.replicas<0||r.replicas>100))throw Error("Scale requires a service and 0-100 replicas");let n=this.queue.enqueue({projectId:e.projectId,environmentId:e.environmentId,resourceId:e.resourceId,actorId:r.actorId,kind:`compose.${t}`,idempotencyKey:`compose:${e.id}:${t}:${r.service??"stack"}:${r.replicas??""}:${e.version}`,correlationId:`compose:${e.id}`,input:{applicationId:e.id,service:r.service??null,replicas:r.replicas??null,removeVolumes:!!r.removeVolumes},lockKey:`compose:${e.id}`,providerKey:this.controlPlane.getResource(e.resourceId)?.provider??"default",buildSlot:t==="deploy"||t==="redeploy",maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;return this.applications.transition(e.id,t==="delete"?"deleting":t==="stop"?"stopped":t==="start"?"deploying":t==="scale"?e.status:"deploying",{operationId:n.id}),n}}import{createHash as Oi}from"node:crypto";var Ui=/^[a-f0-9]{40,64}$/i,Di=/^[A-Z][A-Z0-9_]{1,127}$/;function K(e){return typeof e==="string"&&e?e:void 0}function ne(e){try{return JSON.parse(String(e))}catch{return{}}}function wi(e){let t=ne(e);return Array.isArray(t)?t.map(String):[]}function Nt(e){return{id:String(e.id),projectId:String(e.project_id),resourceId:String(e.resource_id),baseEnvironmentId:String(e.base_environment_id),enabled:Number(e.enabled)===1,branchRule:K(e.branch_rule),domainPattern:String(e.domain_pattern),ttlHours:Number(e.ttl_hours),keepCount:Number(e.keep_count),publicAccess:Number(e.public_access)===1,authenticationRequired:Number(e.authentication_required)===1,allowForks:Number(e.allow_forks)===1,inheritedSecrets:wi(e.inherited_secrets),resourceOverrides:ne(e.resource_overrides),databaseStrategy:String(e.database_strategy),maxMonthlyCost:Number(e.max_monthly_cost),maxCpu:Number(e.max_cpu),maxMemoryMb:Number(e.max_memory_mb),cleanupOnClose:Number(e.cleanup_on_close)===1,version:Number(e.version),createdByActorId:K(e.created_by_actor_id),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function _e(e){return{id:String(e.id),definitionId:String(e.definition_id),projectId:String(e.project_id),resourceId:String(e.resource_id),baseEnvironmentId:String(e.base_environment_id),identityKey:String(e.identity_key),sourceProvider:K(e.source_provider),repository:K(e.repository),branch:String(e.branch),pullRequestNumber:e.pull_request_number==null?void 0:Number(e.pull_request_number),fork:Number(e.fork)===1,commitSha:String(e.commit_sha),name:String(e.name),stackName:String(e.stack_name),url:K(e.url),status:String(e.status),expiresAt:String(e.expires_at),latestOperationId:K(e.latest_operation_id),createdByActorId:K(e.created_by_actor_id),costEstimate:e.cost_estimate==null?void 0:Number(e.cost_estimate),desiredState:ne(e.desired_state),observedState:ne(e.observed_state),teardownError:K(e.teardown_error),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at),destroyedAt:K(e.destroyed_at)}}function fr(e){return{id:String(e.id),previewId:String(e.preview_id),provider:String(e.provider),providerResourceId:String(e.provider_resource_id),kind:String(e.kind),tags:ne(e.tags),observedState:ne(e.observed_state),discoveredAt:String(e.discovered_at),deletedAt:K(e.deleted_at)}}function Q(e,t,r,n){return Number.isFinite(e)?Math.min(n,Math.max(r,Math.floor(e))):t}function Me(e,t,r,n){return Number.isFinite(e)?Math.min(n,Math.max(r,e)):t}function ft(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,28)||"preview"}class Ue{controlPlane;now;id;constructor(e,t={}){this.controlPlane=e;this.now=t.now??(()=>new Date),this.id=t.id??(()=>crypto.randomUUID())}createDefinition(e){let t=this.controlPlane.getResource(e.resourceId),r=this.controlPlane.listEnvironments(e.projectId).find((E)=>E.id===e.baseEnvironmentId);if(!t||t.projectId!==e.projectId||t.environmentId!==r?.id)throw Error("Preview resource and base environment must belong to the same project scope");if(t.kind!=="application")throw Error("Preview environments currently support application resources only");if(!/^https:\/\//.test(e.domainPattern)||!e.domainPattern.includes("{name}"))throw Error("Preview domainPattern must be HTTPS and include {name}");let n=this.getDefinitionForResource(e.resourceId),o=e.publicAccess??n?.publicAccess??!1,a=e.authenticationRequired??n?.authenticationRequired??!0;if(o&&!a)throw Error("Public preview environments require an authentication policy");let l=[...new Set(e.inheritedSecrets??[])];if(l.some((E)=>!Di.test(E)))throw Error("Inherited preview secret names must use uppercase environment-variable identifiers");let u=this.now().toISOString();if(n)return this.controlPlane.database.run("UPDATE preview_definitions SET base_environment_id=?, enabled=1, branch_rule=?, domain_pattern=?, ttl_hours=?, keep_count=?, public_access=?, authentication_required=?, allow_forks=?, inherited_secrets=?, resource_overrides=?, database_strategy=?, max_monthly_cost=?, max_cpu=?, max_memory_mb=?, cleanup_on_close=?, version=version+1, updated_at=? WHERE id=?",[e.baseEnvironmentId,e.branchRule??null,e.domainPattern,Q(e.ttlHours,n.ttlHours,1,720),Q(e.keepCount,n.keepCount,1,100),o?1:0,a?1:0,e.allowForks??n.allowForks?1:0,JSON.stringify(e.inheritedSecrets===void 0?n.inheritedSecrets:l),JSON.stringify(s(e.resourceOverrides??n.resourceOverrides)),e.databaseStrategy??n.databaseStrategy,Me(e.maxMonthlyCost,n.maxMonthlyCost,0,1e4),Me(e.maxCpu,n.maxCpu,0.1,64),Q(e.maxMemoryMb,n.maxMemoryMb,128,131072),e.cleanupOnClose??n.cleanupOnClose?1:0,u,n.id]),this.controlPlane.appendEvent({projectId:e.projectId,resourceId:e.resourceId,actorId:e.createdByActorId,type:"preview.definition.updated",payload:{definitionId:n.id,baseEnvironmentId:e.baseEnvironmentId,version:n.version+1}}),this.getDefinition(n.id);let p=this.id();return this.controlPlane.database.run("INSERT INTO preview_definitions (id, project_id, resource_id, base_environment_id, enabled, branch_rule, domain_pattern, ttl_hours, keep_count, public_access, authentication_required, allow_forks, inherited_secrets, resource_overrides, database_strategy, max_monthly_cost, max_cpu, max_memory_mb, cleanup_on_close, created_by_actor_id, created_at, updated_at) VALUES (?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[p,e.projectId,e.resourceId,e.baseEnvironmentId,e.branchRule??null,e.domainPattern,Q(e.ttlHours,24,1,720),Q(e.keepCount,10,1,100),e.publicAccess?1:0,e.authenticationRequired===!1?0:1,e.allowForks?1:0,JSON.stringify(l),JSON.stringify(s(e.resourceOverrides??{})),e.databaseStrategy??"disabled",Me(e.maxMonthlyCost,25,0,1e4),Me(e.maxCpu,1,0.1,64),Q(e.maxMemoryMb,1024,128,131072),e.cleanupOnClose===!1?0:1,e.createdByActorId??null,u,u]),this.controlPlane.appendEvent({projectId:e.projectId,resourceId:e.resourceId,actorId:e.createdByActorId,type:"preview.definition.created",payload:{definitionId:p,baseEnvironmentId:e.baseEnvironmentId,ttlHours:Q(e.ttlHours,24,1,720),inheritedSecretNames:l}}),this.getDefinition(p)}getDefinition(e){let t=this.controlPlane.database.query("SELECT * FROM preview_definitions WHERE id=?").get(e);return t?Nt(t):void 0}getDefinitionForResource(e){let t=this.controlPlane.database.query("SELECT * FROM preview_definitions WHERE resource_id=?").get(e);return t?Nt(t):void 0}listDefinitions(e){return this.controlPlane.database.query("SELECT * FROM preview_definitions WHERE project_id=? ORDER BY updated_at DESC").all(e).map(Nt)}listInstances(e={}){return this.controlPlane.database.query("SELECT * FROM preview_instances ORDER BY created_at DESC").all().map(_e).filter((r)=>(!e.projectId||r.projectId===e.projectId)&&(!e.definitionId||r.definitionId===e.definitionId)&&(!e.status||r.status===e.status))}getInstance(e){let t=this.controlPlane.database.query("SELECT * FROM preview_instances WHERE id=?").get(e);return t?_e(t):void 0}findForPullRequest(e,t,r){let n=this.controlPlane.database.query("SELECT * FROM preview_instances WHERE definition_id=? AND identity_key=?").get(e,`pr:${t}:${r}`);return n?_e(n):void 0}findForBranch(e,t,r){let n=this.controlPlane.database.query("SELECT * FROM preview_instances WHERE definition_id=? AND identity_key=?").get(e,`branch:${t}:${r}`);return n?_e(n):void 0}upsert(e){let t=this.getDefinition(e.definitionId);if(!t?.enabled)throw Error("Preview environments are not enabled for this application");if(!Ui.test(e.commitSha))throw Error("Preview deployment requires an immutable 40-64 character commit SHA");if(e.fork&&!t.allowForks)throw Error("Untrusted fork previews are disabled");let r=e.pullRequestNumber?`pr:${e.repository??"unknown"}:${e.pullRequestNumber}`:`branch:${e.repository??"local"}:${e.branch}`,n=Oi("sha256").update(`${t.id}:${r}`).digest("hex").slice(0,8),a=`${(e.pullRequestNumber?`pr-${e.pullRequestNumber}`:ft(e.branch)).slice(0,28)}-${n}`,l=`preview-${a}`.slice(0,63),u=t.domainPattern.replaceAll("{name}",a).replaceAll("{project}",ft(t.projectId)).replaceAll("{branch}",ft(e.branch)).replaceAll("{pr}",String(e.pullRequestNumber??"branch")),p=e.now??this.now(),E=p.toISOString(),g=new Date(p.getTime()+t.ttlHours*60*60*1000).toISOString(),m=this.controlPlane.database.query("SELECT * FROM preview_instances WHERE definition_id=? AND identity_key=?").get(t.id,r);if(m){let h=_e(m),f=h.commitSha!==e.commitSha||h.status==="destroyed";if(f)this.controlPlane.database.run("UPDATE preview_instances SET commit_sha=?, branch=?, fork=?, status='queued', expires_at=?, url=?, teardown_error=NULL, destroyed_at=NULL, version=version+1, updated_at=? WHERE id=?",[e.commitSha,e.branch,e.fork?1:0,g,u,E,h.id]);return{preview:this.getInstance(h.id),created:!1,changed:f,inheritedSecrets:e.fork?[]:t.inheritedSecrets}}let T=this.id(),N=s({source:{provider:e.sourceProvider??null,repository:e.repository??null,branch:e.branch,commitSha:e.commitSha,pullRequestNumber:e.pullRequestNumber??null,fork:!!e.fork},policy:{databaseStrategy:t.databaseStrategy,resourceOverrides:t.resourceOverrides,maxMonthlyCost:t.maxMonthlyCost,maxCpu:t.maxCpu,maxMemoryMb:t.maxMemoryMb,publicAccess:t.publicAccess,authenticationRequired:t.authenticationRequired},inheritedSecretNames:e.fork?[]:t.inheritedSecrets});return this.controlPlane.database.run("INSERT INTO preview_instances (id, definition_id, project_id, resource_id, base_environment_id, identity_key, source_provider, repository, branch, pull_request_number, fork, commit_sha, name, stack_name, url, status, expires_at, created_by_actor_id, desired_state, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'queued', ?, ?, ?, ?, ?)",[T,t.id,t.projectId,t.resourceId,t.baseEnvironmentId,r,e.sourceProvider??null,e.repository??null,e.branch,e.pullRequestNumber??null,e.fork?1:0,e.commitSha,a,l,u,g,e.createdByActorId??null,JSON.stringify(N),E,E]),this.controlPlane.appendEvent({projectId:t.projectId,resourceId:t.resourceId,actorId:e.createdByActorId,type:"preview.created",payload:{previewId:T,identityKey:r,commitSha:e.commitSha,expiresAt:g,fork:!!e.fork}}),{preview:this.getInstance(T),created:!0,changed:!0,inheritedSecrets:e.fork?[]:t.inheritedSecrets}}transition(e,t,r={}){let n=this.getInstance(e);if(!n)throw Error(`Preview ${e} was not found`);let o=this.now().toISOString(),a=t==="destroyed"?o:null;return this.controlPlane.database.run("UPDATE preview_instances SET status=?, latest_operation_id=COALESCE(?, latest_operation_id), observed_state=?, teardown_error=?, cost_estimate=COALESCE(?, cost_estimate), destroyed_at=?, version=version+1, updated_at=? WHERE id=?",[t,r.operationId??null,JSON.stringify(s(r.observedState??n.observedState)),r.teardownError??null,r.costEstimate??null,a,o,e]),this.controlPlane.appendEvent({projectId:n.projectId,resourceId:n.resourceId,operationId:r.operationId,type:`preview.${t}`,level:t==="failed"||t==="cleanup_failed"?"error":"info",payload:{previewId:e,commitSha:n.commitSha,teardownError:r.teardownError??null}}),this.getInstance(e)}extend(e,t){let r=this.getInstance(e),n=r?this.getDefinition(r.definitionId):void 0;if(!r||!n)throw Error(`Preview ${e} was not found`);let o=this.now(),a=Q(t,n.ttlHours,1,720),l=new Date(Math.max(o.getTime(),new Date(r.expiresAt).getTime())+a*3600000).toISOString();return this.controlPlane.database.run("UPDATE preview_instances SET expires_at=?, version=version+1, updated_at=? WHERE id=?",[l,o.toISOString(),e]),this.getInstance(e)}expired(e=this.now()){return this.listInstances().filter((t)=>["queued","deploying","active","updating","failed","cleanup_failed"].includes(t.status)&&new Date(t.expiresAt)<=e)}recordResource(e){let t=this.getInstance(e.previewId);if(!t)throw Error(`Preview ${e.previewId} was not found`);let r={"ts-cloud:preview":t.id,"ts-cloud:project":t.projectId,"ts-cloud:expires-at":t.expiresAt};for(let[l,u]of Object.entries(r))if(e.tags[l]!==u)throw Error(`Preview resource is missing immutable tag ${l}`);let n=this.id(),o=this.now().toISOString();this.controlPlane.database.run("INSERT INTO preview_resources (id, preview_id, provider, provider_resource_id, kind, tags, observed_state, discovered_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(preview_id, provider, provider_resource_id) DO UPDATE SET kind=excluded.kind, tags=excluded.tags, observed_state=excluded.observed_state, deleted_at=NULL",[n,t.id,e.provider,e.providerResourceId,e.kind,JSON.stringify(e.tags),JSON.stringify(s(e.observedState??{})),o]);let a=this.controlPlane.database.query("SELECT * FROM preview_resources WHERE preview_id=? AND provider=? AND provider_resource_id=?").get(t.id,e.provider,e.providerResourceId);return fr(a)}listResources(e){return this.controlPlane.database.query("SELECT * FROM preview_resources WHERE preview_id=? ORDER BY kind, provider_resource_id").all(e).map(fr)}markResourcesDeleted(e){if(!this.getInstance(e))throw Error(`Preview ${e} was not found`);return this.controlPlane.database.run("UPDATE preview_resources SET deleted_at=? WHERE preview_id=? AND deleted_at IS NULL",[this.now().toISOString(),e]).changes}}class Er{controlPlane;previews;queue;constructor(e){this.controlPlane=e;this.previews=new Ue(e),this.queue=new c(e)}enqueueDeploy(e,t={}){let r=t.created?"preview.create":"preview.update",n=t.reason==="manual_rebuild"?`:${crypto.randomUUID()}`:"",o=this.queue.enqueue({projectId:e.projectId,environmentId:e.baseEnvironmentId,resourceId:e.resourceId,actorId:t.actorId,kind:r,correlationId:`preview:${e.id}`,idempotencyKey:`preview:${e.id}:${e.commitSha}${n}`,input:{previewId:e.id,reason:t.reason??(t.created?"create":"commit_update"),source:{repository:e.repository??null,branch:e.branch,commitSha:e.commitSha,pullRequestNumber:e.pullRequestNumber??null,fork:e.fork}},lockKey:`preview:${e.id}`,providerKey:"preview",buildSlot:!0,maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;return this.previews.transition(e.id,"queued",{operationId:o.id}),o}enqueueDestroy(e,t,r){if(e.status==="destroyed")throw Error("Preview is already destroyed");let n=this.queue.enqueue({projectId:e.projectId,environmentId:e.baseEnvironmentId,resourceId:e.resourceId,actorId:r,kind:"preview.destroy",correlationId:`preview:${e.id}`,idempotencyKey:`preview:${e.id}:destroy:${t}`,input:{previewId:e.id,reason:t},lockKey:`preview:${e.id}`,providerKey:"preview",maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;return this.previews.transition(e.id,"queued",{operationId:n.id}),n}cleanup(e={}){let t=e.now??new Date,r=new Map,n=this.previews.listInstances().filter((p)=>!["destroyed","destroying"].includes(p.status)),o=(p,E)=>{let g=r.get(p.id)??{preview:p,reasons:[]};if(!g.reasons.includes(E))g.reasons.push(E);r.set(p.id,g)};for(let p of n){if(new Date(p.expiresAt)<=t)o(p,"ttl_expired");if(e.maxAgeHours&&t.getTime()-new Date(p.createdAt).getTime()>=e.maxAgeHours*3600000)o(p,"max_age")}let a=new Map;for(let p of n)a.set(p.definitionId,[...a.get(p.definitionId)??[],p]);for(let[p,E]of a){let g=this.previews.getDefinition(p),m=e.keepCount??g?.keepCount;if(!m)continue;E.sort((T,N)=>N.createdAt.localeCompare(T.createdAt)).slice(m).forEach((T)=>o(T,"keep_count"))}let l=[...r.values()].sort((p,E)=>p.preview.createdAt.localeCompare(E.preview.createdAt)),u=e.dryRun?[]:l.map((p)=>this.enqueueDestroy(p.preview,p.reasons.sort().join("+"),e.actorId));if(l.length)this.controlPlane.appendEvent({actorId:e.actorId,type:e.dryRun?"preview.cleanup.planned":"preview.cleanup.queued",payload:{previewIds:l.map((p)=>p.preview.id),reasons:Object.fromEntries(l.map((p)=>[p.preview.id,p.reasons])),dryRun:!!e.dryRun}});return{candidates:l,operations:u,dryRun:!!e.dryRun}}reconcile(e){let t=[],r=[],n=[];for(let o of e){let a=o.tags["ts-cloud:preview"],l=o.tags["ts-cloud:project"],u=o.tags["ts-cloud:expires-at"];if(!a||!l||!u){n.push(o.providerResourceId);continue}let p=this.previews.getInstance(a);if(!p||p.projectId!==l||p.expiresAt!==u){r.push(o.providerResourceId);continue}if(this.previews.recordResource({...o,previewId:p.id}),o.estimatedMonthlyCost!==void 0)this.previews.transition(p.id,p.status,{costEstimate:o.estimatedMonthlyCost,observedState:{...p.observedState,lastReconciledAt:new Date().toISOString()}});t.push(o.providerResourceId)}if(r.length)this.controlPlane.appendEvent({type:"preview.reconciliation.leaks",level:"error",payload:{providerResourceIds:r}});return{matched:t,unknownPreviewResources:r,ignoredUntagged:n}}}var Hh=["deployment.create","deployment.rollback","application.create","deploy.source","deploy.preview","preview.create","preview.update","preview.destroy","compose.deploy","compose.redeploy","compose.start","compose.stop","compose.delete","compose.scale"];function ze(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function Gh(e,t){if(!t.projectId||!t.environmentId)throw Error(`Queued ${t.kind} operation is missing its project or environment scope`);let r=e.listEnvironments(t.projectId).find((l)=>l.id===t.environmentId);if(!r)throw Error(`Environment ${t.environmentId} was not found for queued ${t.kind} operation`);let n=t.resourceId?e.getResource(t.resourceId):void 0;if(t.resourceId&&(!n||n.projectId!==t.projectId||n.environmentId!==t.environmentId))throw Error(`Resource ${t.resourceId} was not found in the queued deployment scope`);let o=ze(t.input);if(t.kind.startsWith("compose.")){let l=typeof o.applicationId==="string"?o.applicationId:void 0,u=l?new Ot(e).get(l):t.resourceId?new Ot(e).getByResource(t.resourceId):void 0;if(!u||u.projectId!==t.projectId||u.environmentId!==t.environmentId||u.resourceId!==t.resourceId)throw Error("Queued Compose application does not match the operation scope");let p=t.kind.slice(8),E=["compose:apply",u.id,"--action",p,"--env",r.slug];if(typeof o.service==="string"&&o.service)E.push("--service",o.service);if(typeof o.replicas==="number")E.push("--replicas",String(o.replicas));if(o.removeVolumes===!0)E.push("--remove-volumes");return{id:`queue:${t.id}`,label:`${p[0].toUpperCase()}${p.slice(1)} Compose application`,description:`${p} ${u.name}.`,command:E,mutates:!0,target:{environment:r.slug,resource:n?.slug,composeId:u.id}}}if(t.kind.startsWith("preview.")){let l=typeof o.previewId==="string"?o.previewId:void 0,u=l?new Ue(e).getInstance(l):void 0;if(!u)throw Error(`Preview ${l??"(missing)"} was not found for queued ${t.kind}`);if(u.projectId!==t.projectId||u.resourceId!==t.resourceId)throw Error("Queued preview does not match the operation scope");if(t.kind==="preview.destroy")return{id:`queue:${t.id}`,label:"Destroy preview",description:`Destroy ${u.name}.`,command:["stack:delete",u.stackName,"--yes"],mutates:!0,target:{environment:r.slug,resource:n?.slug,previewId:u.id}};return{id:`queue:${t.id}`,label:t.kind==="preview.create"?"Create preview":"Update preview",description:`Deploy ${u.name} at ${u.commitSha}.`,command:["deploy","--stack",u.stackName,"--env",r.slug,"--yes","--skip-dns-verification",...n?["--site",n.slug]:[]],mutates:!0,target:{environment:r.slug,resource:n?.slug,previewId:u.id}}}if(t.kind==="deployment.rollback"){let l=["deploy:rollback"];if(n)l.push(n.slug);if(l.push("--env",r.slug),typeof o.revision==="string"&&o.revision)l.push("--to",o.revision);return{id:`queue:${t.id}`,label:"Rollback deployment",description:`Roll back ${n?.slug??r.slug}.`,command:l,mutates:!0,target:{environment:r.slug,resource:n?.slug}}}let a=["deploy","--env",r.slug,"--yes"];if(n)a.push("--site",n.slug);return{id:`queue:${t.id}`,label:t.kind==="deploy.preview"?"Deploy preview":"Deploy release",description:`Deploy ${n?.slug??r.slug}.`,command:a,mutates:!0,target:{environment:r.slug,resource:n?.slug}}}function ki(e){let t=e.stderr?.trim()||`Deployment process exited with code ${e.exitCode}`;if(/\b(?:429|rate.?limit|throttl)/i.test(t))return new X(t,"provider_throttled");if(/\b(?:502|503|504|temporar(?:y|ily)|unavailable|provider.?error)/i.test(t))return new X(t,"provider_unavailable");if(/\b(?:network|econn|enotfound|socket|timed?\s*out|fetch failed|dns)\b/i.test(t))return new X(t,"network");return Error(t)}function kc(e){let t=async(r)=>{r.checkpoint("prepare","Resolving the persisted deployment target.");let n=Gh(e.store,r.operation),o=n.target.previewId?new Ue(e.store):void 0,a=n.target.composeId?new Ot(e.store):void 0;if(o&&n.target.previewId)o.transition(n.target.previewId,r.operation.kind==="preview.destroy"?"destroying":r.operation.kind==="preview.update"?"updating":"deploying",{operationId:r.operation.id});if(a&&n.target.composeId)a.transition(n.target.composeId,r.operation.kind==="compose.delete"?"deleting":r.operation.kind==="compose.stop"?"stopped":"deploying",{operationId:r.operation.id});r.log(`Target: ${n.target.resource??"all resources"} in ${n.target.environment}.`,{stream:"system"}),r.throwIfCancellationRequested(),r.checkpoint("execute",`Running cloud ${n.command.join(" ")}.`);let l=await e.execute(n,r);if(!l.ok){if(o&&n.target.previewId)o.transition(n.target.previewId,r.operation.kind==="preview.destroy"?"cleanup_failed":"failed",{operationId:r.operation.id,teardownError:r.operation.kind==="preview.destroy"?l.stderr?.trim()||`Process exited with ${l.exitCode}`:void 0});if(a&&n.target.composeId)a.transition(n.target.composeId,r.operation.kind==="compose.delete"?"degraded":"failed",{operationId:r.operation.id,error:l.stderr?.trim()||`Process exited with ${l.exitCode}`});throw ki(l)}if(r.throwIfCancellationRequested(),o&&n.target.previewId){let u=o.getInstance(n.target.previewId);if(r.operation.kind==="preview.destroy")o.markResourcesDeleted(u.id),o.transition(u.id,"destroyed",{operationId:r.operation.id,observedState:{reconciledResourceIds:o.listResources(u.id).map((p)=>p.providerResourceId),exactCommitSha:u.commitSha}});else{let p=e.store.getResource(u.resourceId)?.provider??"default";o.recordResource({previewId:u.id,provider:p,providerResourceId:u.stackName,kind:"stack",tags:{"ts-cloud:preview":u.id,"ts-cloud:project":u.projectId,"ts-cloud:expires-at":u.expiresAt},observedState:{command:l.command??null,exactCommitSha:u.commitSha}}),o.transition(u.id,"active",{operationId:r.operation.id,observedState:{url:u.url??null,stackName:u.stackName,exactCommitSha:u.commitSha,providerStatus:"deployed"}})}}if(a&&n.target.composeId){let u=a.get(n.target.composeId),p=typeof ze(r.operation.input).service==="string"?String(ze(r.operation.input).service):void 0,E=r.operation.kind==="compose.delete"?"deleted":r.operation.kind==="compose.stop"?"stopped":"running",g=a.transition(u.id,E,{operationId:r.operation.id,services:Object.values(u.manifest.spec.services).filter((m)=>!p||m.name===p).map((m)=>({name:m.name,status:E==="stopped"||E==="deleted"?"stopped":"running",replicas:E==="deleted"?0:m.replicas,healthyReplicas:E==="running"?m.replicas:0,observedState:{command:l.command??null,healthGatePassed:E==="running"}}))});if(E==="deleted")dp(e.store,g,ze(r.operation.input).removeVolumes===!0)}return r.checkpoint("finalize","Deployment command completed; persisting the terminal result."),{command:l.command??`cloud ${n.command.join(" ")}`,exitCode:l.exitCode,environment:n.target.environment,resource:n.target.resource??null}};return Object.fromEntries(Hh.map((r)=>[r,t]))}class i extends Error{code;status;details;constructor(e,t,r,n){super(t);this.code=e;this.status=r;this.details=n}}function yt(e,t){if(e.organizationId!==t.organizationId)return!1;if(e.projectId&&e.projectId!==t.projectId)return!1;if(e.environmentId&&e.environmentId!==t.environmentId)return!1;if(e.resourceId&&e.resourceId!==t.resourceId)return!1;return!0}function mf(e,t,r){return Xi("sha256").update(`${e.toUpperCase()}
|
|
1615
|
+
`).find((n)=>n.includes(`"Name":"${e.providerId}"`));if(!r)return{};try{let n=JSON.parse(r);return{usedBytes:typeof n.Size==="number"?n.Size:void 0}}catch{return{}}}}class Os{provider="server";type="server_path";root;constructor(e){this.root=gr(e)}capabilities(){return _s(["create","attach","detach","delete","adopt","usage"],{resize:{supported:!1,reason:"Server paths use the capacity of their containing filesystem."},snapshot:{supported:!1,reason:"Attach a filesystem backup policy for verified recovery points."},restore:{supported:!1,reason:"Restore a filesystem recovery point into a new managed path."}})}path(e){if(!ee.test(e))throw Error("Server path volume name is invalid.");let t=gr(this.root,e);if(!t.startsWith(`${this.root}${Ri}`)||bi(t)!==e)throw Error("Server path escaped the managed volume root.");return t}async discover(e,t){return await mt(this.root,{recursive:!0,mode:488}),(await vi(this.root,{withFileTypes:!0})).filter((n)=>n.isDirectory()&&ee.test(n.name)).map((n)=>({providerId:n.name,raw:{path:this.path(n.name)}}))}async create(e){let t=typeof e.desiredState.nativeName==="string"?e.desiredState.nativeName:e.name,r=this.path(t);return await mt(this.root,{recursive:!0,mode:488}),await mt(r,{recursive:!1,mode:488}),{providerId:t,filesystem:"host",raw:{path:r}}}async attach(e,t){}async detach(e,t){}async resize(){throw Error(this.capabilities().resize.reason)}async snapshot(){throw Error(this.capabilities().snapshot.reason)}async restore(e,t,r){throw Error(this.capabilities().restore.reason)}async delete(e){if(!e.providerId)throw Error("Server path provider identity is unavailable.");await Ii(this.path(e.providerId),{recursive:!0,force:!1})}async usage(e){if(!e.providerId)return{};return{usedBytes:(await Si(this.path(e.providerId))).size}}}class ef{provider;transport;type="ebs";constructor(e,t){this.provider=e;this.transport=t}capabilities(){return _s(["create","attach","detach","resize","snapshot","restore","delete","adopt","usage"],{resize:{supported:!0,online:!0,minimumBytes:1073741824}})}discover(e,t){return this.transport.list(e,t)}create(e){return this.transport.create({name:e.name,projectId:e.projectId,environmentId:e.environmentId,capacityBytes:e.capacityBytes,encrypted:e.encrypted,filesystem:e.filesystem})}resource(e,t){let r=e.resourceId===t.resourceId?e.observedState.resourceProviderId:void 0,n=typeof r==="string"?r:t.driverOptions.resourceProviderId;if(typeof n!=="string"||!n)throw Error("Cloud attachment requires a reviewed resourceProviderId driver option.");return n}attach(e,t){return this.transport.attach(e.providerId,this.resource(e,t),t.targetPath,t.readOnly)}detach(e,t,r){return this.transport.detach(e.providerId,this.resource(e,t),r.force)}resize(e,t){return this.transport.resize(e.providerId,t)}snapshot(e,t){return this.transport.snapshot(e.providerId,t.name)}restore(e,t,r){if(!t.providerId)throw Error("Cloud snapshot provider identity is unavailable.");return this.transport.restore(e.providerId,t.providerId,r.name)}delete(e){return this.transport.delete(e.providerId)}usage(e){return this.transport.usage(e.providerId)}}var F=(e)=>e==null?void 0:String(e),ge=(e,t)=>{try{return JSON.parse(String(e))}catch{return t}},gt=(e)=>Number(e)===1,te=(e)=>e().toISOString();function hr(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:F(e.environment_id),resourceId:F(e.resource_id),name:String(e.name),provider:String(e.provider),providerId:F(e.provider_id),type:String(e.type),status:String(e.status),capacityBytes:e.capacity_bytes==null?void 0:Number(e.capacity_bytes),usedBytes:e.used_bytes==null?void 0:Number(e.used_bytes),filesystem:F(e.filesystem),encrypted:gt(e.encrypted),capabilities:ge(e.capabilities,{}),desiredState:ge(e.desired_state,{}),observedState:ge(e.observed_state,{}),backupPolicyId:F(e.backup_policy_id),lastBackupAt:F(e.last_backup_at),orphanedAt:F(e.orphaned_at),adoptedAt:F(e.adopted_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at),deletedAt:F(e.deleted_at)}}function Tt(e){return{id:String(e.id),volumeId:String(e.volume_id),resourceId:String(e.resource_id),targetPath:String(e.target_path),readOnly:gt(e.read_only),uid:e.uid==null?void 0:Number(e.uid),gid:e.gid==null?void 0:Number(e.gid),mode:F(e.mode),propagation:String(e.propagation),driverOptions:ge(e.driver_options,{}),desiredState:String(e.desired_state),observedState:String(e.observed_state),operationId:F(e.operation_id),lastError:F(e.last_error),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function fr(e){return{id:String(e.id),volumeId:String(e.volume_id),recoveryPointId:F(e.recovery_point_id),providerId:F(e.provider_id),name:String(e.name),status:String(e.status),sizeBytes:e.size_bytes==null?void 0:Number(e.size_bytes),encrypted:gt(e.encrypted),checksum:F(e.checksum),metadata:ge(e.metadata,{}),createdAt:String(e.created_at),updatedAt:String(e.updated_at),deletedAt:F(e.deleted_at)}}class xt{controlPlane;now;id;constructor(e,t=()=>new Date,r=()=>crypto.randomUUID()){this.controlPlane=e;this.now=t;this.id=r}get(e){let t=this.controlPlane.database.query("SELECT * FROM persistent_volumes WHERE id=?").get(e);return t?hr(t):void 0}list(e){let t=["project_id=?"],r=[e.projectId];if(e.environmentId)t.push("environment_id=?"),r.push(e.environmentId);if(!e.includeDeleted)t.push("deleted_at IS NULL");return this.controlPlane.database.query(`SELECT * FROM persistent_volumes WHERE ${t.join(" AND ")} ORDER BY name`).all(...r).map(hr)}create(e){let t=te(this.now),r=e.id??this.id();return this.controlPlane.database.run("INSERT INTO persistent_volumes (id,organization_id,project_id,environment_id,resource_id,name,provider,provider_id,type,status,capacity_bytes,used_bytes,filesystem,encrypted,capabilities,desired_state,observed_state,backup_policy_id,last_backup_at,orphaned_at,adopted_at,created_at,updated_at,deleted_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[r,e.organizationId,e.projectId,e.environmentId??null,e.resourceId??null,e.name,e.provider,e.providerId??null,e.type,e.status,e.capacityBytes??null,e.usedBytes??null,e.filesystem??null,e.encrypted?1:0,JSON.stringify(e.capabilities),JSON.stringify(e.desiredState),JSON.stringify(e.observedState),e.backupPolicyId??null,e.lastBackupAt??null,e.orphanedAt??null,e.adoptedAt??null,t,t,e.deletedAt??null]),this.get(r)}update(e,t,r){let n=this.get(e);if(!n||n.version!==t)throw Error("Volume changed before this operation could be applied.");let o={...n,...r,updatedAt:te(this.now)};if(this.controlPlane.database.run("UPDATE persistent_volumes SET environment_id=?,resource_id=?,name=?,provider=?,provider_id=?,type=?,status=?,capacity_bytes=?,used_bytes=?,filesystem=?,encrypted=?,capabilities=?,desired_state=?,observed_state=?,backup_policy_id=?,last_backup_at=?,orphaned_at=?,adopted_at=?,deleted_at=?,version=version+1,updated_at=? WHERE id=? AND version=?",[o.environmentId??null,o.resourceId??null,o.name,o.provider,o.providerId??null,o.type,o.status,o.capacityBytes??null,o.usedBytes??null,o.filesystem??null,o.encrypted?1:0,JSON.stringify(o.capabilities),JSON.stringify(o.desiredState),JSON.stringify(o.observedState),o.backupPolicyId??null,o.lastBackupAt??null,o.orphanedAt??null,o.adoptedAt??null,o.deletedAt??null,o.updatedAt,e,t]).changes!==1)throw Error("Volume changed before this operation could be applied.");return this.get(e)}attachments(e){return this.controlPlane.database.query("SELECT * FROM volume_attachments WHERE volume_id=? ORDER BY target_path").all(e).map(Tt)}attachment(e){let t=this.controlPlane.database.query("SELECT * FROM volume_attachments WHERE id=?").get(e);return t?Tt(t):void 0}upsertAttachment(e){let t=this.controlPlane.database.query("SELECT * FROM volume_attachments WHERE volume_id=? AND resource_id=? AND target_path=?").get(e.volumeId,e.resourceId,e.targetPath),r=te(this.now);if(t){let o=Tt(t);return this.controlPlane.database.run("UPDATE volume_attachments SET read_only=?,uid=?,gid=?,mode=?,propagation=?,driver_options=?,desired_state=?,observed_state=?,operation_id=?,last_error=?,version=version+1,updated_at=? WHERE id=?",[e.readOnly?1:0,e.uid??null,e.gid??null,e.mode??null,e.propagation,JSON.stringify(e.driverOptions),e.desiredState,e.observedState,e.operationId??null,e.lastError??null,r,o.id]),this.attachment(o.id)}let n=e.id??this.id();return this.controlPlane.database.run("INSERT INTO volume_attachments (id,volume_id,resource_id,target_path,read_only,uid,gid,mode,propagation,driver_options,desired_state,observed_state,operation_id,last_error,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[n,e.volumeId,e.resourceId,e.targetPath,e.readOnly?1:0,e.uid??null,e.gid??null,e.mode??null,e.propagation,JSON.stringify(e.driverOptions),e.desiredState,e.observedState,e.operationId??null,e.lastError??null,r,r]),this.attachment(n)}updateAttachment(e,t){let r=this.attachment(e);if(!r)throw Error("Volume attachment was not found.");let n={...r,...t};return this.controlPlane.database.run("UPDATE volume_attachments SET desired_state=?,observed_state=?,operation_id=?,last_error=?,version=version+1,updated_at=? WHERE id=?",[n.desiredState,n.observedState,n.operationId??null,n.lastError??null,te(this.now),e]),this.attachment(e)}snapshots(e){return this.controlPlane.database.query("SELECT * FROM volume_snapshots WHERE volume_id=? AND deleted_at IS NULL ORDER BY created_at DESC").all(e).map(fr)}snapshot(e){let t=this.controlPlane.database.query("SELECT * FROM volume_snapshots WHERE id=?").get(e);return t?fr(t):void 0}createSnapshot(e){let t=e.id??this.id(),r=te(this.now);return this.controlPlane.database.run("INSERT INTO volume_snapshots (id,volume_id,recovery_point_id,provider_id,name,status,size_bytes,encrypted,checksum,metadata,created_at,updated_at,deleted_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.volumeId,e.recoveryPointId??null,e.providerId??null,e.name,e.status,e.sizeBytes??null,e.encrypted?1:0,e.checksum??null,JSON.stringify(e.metadata),r,r,e.deletedAt??null]),this.snapshot(t)}updateSnapshot(e,t){let r=this.snapshot(e);if(!r)throw Error("Volume snapshot was not found.");let n={...r,...t};return this.controlPlane.database.run("UPDATE volume_snapshots SET recovery_point_id=?,provider_id=?,name=?,status=?,size_bytes=?,encrypted=?,checksum=?,metadata=?,deleted_at=?,updated_at=? WHERE id=?",[n.recoveryPointId??null,n.providerId??null,n.name,n.status,n.sizeBytes??null,n.encrypted?1:0,n.checksum??null,JSON.stringify(n.metadata),n.deletedAt??null,te(this.now),e]),this.snapshot(e)}inventory(e,t){return this.list({projectId:e,environmentId:t}).map((r)=>{let n=this.attachments(r.id),o=this.snapshots(r.id),a=r.lastBackupAt?Date.now()-new Date(r.lastBackupAt).getTime():1/0;return{...r,attachments:n,snapshots:o,orphaned:r.status==="orphaned",usagePercent:r.capacityBytes&&r.usedBytes!=null?Math.round(r.usedBytes/r.capacityBytes*1000)/10:void 0,backupState:r.backupPolicyId?a<=86400000?"protected":"stale":"unprotected"}})}audit(e){this.controlPlane.appendEvent({organizationId:e.organizationId,projectId:e.projectId,resourceId:this.get(e.volumeId)?.resourceId,actorId:e.actorId,type:e.type,level:"warning",payload:{volumeId:e.volumeId,environmentId:e.environmentId??null,...e.payload}})}}function Oc(e,t){let r=e.getProject(t.projectId);if(!r?.organizationId)return;let n=new xt(e),o=new vr,a=new Set(t.manifest.spec.volumes),l=new Set;for(let u of a){let p=`${t.slug}-${u}`.toLowerCase().replace(/[^a-z0-9_.-]/g,"-").slice(0,63),E=n.list({projectId:t.projectId,environmentId:t.environmentId,includeDeleted:!0}).find((h)=>h.name===p);if(E?.deletedAt)throw Error(`Compose volume ${p} was permanently deleted; rename it before redeploying.`);let g=E?.resourceId?e.getResource(E.resourceId):e.createResource({projectId:t.projectId,environmentId:t.environmentId,kind:"volume",slug:p,name:p,provider:"docker",providerId:p,desiredState:{composeApplicationId:t.id,composeVolume:u}}),m=E??n.create({organizationId:r.organizationId,projectId:t.projectId,environmentId:t.environmentId,resourceId:g?.id,name:p,provider:"docker",providerId:p,type:"docker",status:"available",encrypted:!1,capabilities:o.capabilities(),desiredState:{composeApplicationId:t.id,composeVolume:u,nativeName:p},observedState:{}});l.add(m.id);let T=new Map;for(let h of Object.values(t.manifest.spec.services))for(let _ of h.volumes.filter((N)=>N.source===u)){let N=T.get(_.target)??[];N.push(h.name),T.set(_.target,N),n.upsertAttachment({volumeId:m.id,resourceId:t.resourceId,targetPath:_.target,readOnly:_.readOnly,propagation:"private",driverOptions:{composeServices:N},desiredState:"attached",observedState:"pending"})}}for(let u of n.list({projectId:t.projectId,environmentId:t.environmentId}).filter((p)=>p.desiredState.composeApplicationId===t.id&&!l.has(p.id)))for(let p of n.attachments(u.id))n.updateAttachment(p.id,{desiredState:"detached"})}function fp(e,t,r){let n=new xt(e);for(let o of n.list({projectId:t.projectId,environmentId:t.environmentId}).filter((a)=>a.desiredState.composeApplicationId===t.id)){for(let a of n.attachments(o.id))n.updateAttachment(a.id,{desiredState:"detached",observedState:"detached"});n.update(o.id,o.version,{status:r?"deleted":"available",deletedAt:r?new Date().toISOString():void 0})}}function re(e){return typeof e==="string"&&e?e:void 0}function ht(e,t){try{return JSON.parse(String(e))}catch{return t}}function je(e){return{id:String(e.id),resourceId:String(e.resource_id),projectId:String(e.project_id),environmentId:String(e.environment_id),name:String(e.name),slug:String(e.slug),status:String(e.status),sourceKind:String(e.source_kind),sourceHash:String(e.source_hash),redactedSource:String(e.redacted_source),manifest:ht(e.manifest,{}),diagnostics:ht(e.diagnostics,[]),templateId:re(e.template_id),templateVersion:re(e.template_version),latestOperationId:re(e.latest_operation_id),createdByActorId:re(e.created_by_actor_id),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at),deletedAt:re(e.deleted_at)}}function Ai(e){return{applicationId:String(e.application_id),serviceName:String(e.service_name),status:String(e.status),replicas:Number(e.replicas),healthyReplicas:Number(e.healthy_replicas),latestOperationId:re(e.latest_operation_id),observedState:ht(e.observed_state,{}),updatedAt:String(e.updated_at)}}class Ot{controlPlane;now;id;constructor(e,t={}){this.controlPlane=e;this.now=t.now??(()=>new Date),this.id=t.id??(()=>crypto.randomUUID())}persist(e,t){if(!e.valid)throw Error(`Compose definition contains ${e.diagnostics.filter((_)=>_.severity==="error").length} blocking diagnostic(s)`);let{projectId:r,environmentId:n,name:o,slug:a}=e.manifest.metadata;if(!this.controlPlane.listEnvironments(r).find((_)=>_.id===n))throw Error("Compose project and environment scope was not found");let u=this.getBySlug(r,n,a),p=this.now().toISOString(),E=JSON.stringify(e.manifest),g=JSON.stringify(s(e.diagnostics));if(u){if(u.status==="deleted")throw Error("A deleted Compose application cannot be overwritten; choose another slug");let _=this.controlPlane.getResource(u.resourceId);if(!_)throw Error("Compose application resource was not found");this.controlPlane.updateResource(_.id,_.version,{name:o,provider:_.provider,providerId:_.providerId,desiredState:e.manifest,discoveredState:_.discoveredState,metadata:{sourceKind:t.sourceKind,templateId:t.templateId??null,templateVersion:t.templateVersion??null,sourceHash:e.sourceHash}}),this.controlPlane.database.run("UPDATE compose_applications SET name=?, status='ready', source_kind=?, source_hash=?, redacted_source=?, manifest=?, diagnostics=?, template_id=?, template_version=?, version=version+1, updated_at=? WHERE id=?",[o,t.sourceKind,e.sourceHash,e.redactedSource,E,g,t.templateId??null,t.templateVersion??null,p,u.id]);let N=Object.keys(e.manifest.spec.services);if(N.length)this.controlPlane.database.run(`DELETE FROM compose_service_states WHERE application_id=? AND service_name NOT IN (${N.map(()=>"?").join(",")})`,[u.id,...N]);for(let L of Object.values(e.manifest.spec.services))this.controlPlane.database.run("INSERT INTO compose_service_states (application_id, service_name, status, replicas, healthy_replicas, observed_state, updated_at) VALUES (?, ?, 'pending', ?, 0, '{}', ?) ON CONFLICT(application_id, service_name) DO UPDATE SET replicas=excluded.replicas, updated_at=excluded.updated_at",[u.id,L.name,L.replicas,p]);this.controlPlane.appendEvent({projectId:r,resourceId:u.resourceId,actorId:t.createdByActorId,type:"compose.application.updated",payload:{applicationId:u.id,sourceHash:e.sourceHash,diagnosticCount:e.diagnostics.length,templateId:t.templateId??null,templateVersion:t.templateVersion??null}});let y=this.get(u.id);return Oc(this.controlPlane,y),y}let m=this.controlPlane.createResource({projectId:r,environmentId:n,kind:"compose_application",slug:a,name:o,desiredState:e.manifest,metadata:{sourceKind:t.sourceKind,templateId:t.templateId??null,templateVersion:t.templateVersion??null,sourceHash:e.sourceHash}}),T=this.id();this.controlPlane.database.run("INSERT INTO compose_applications (id, resource_id, project_id, environment_id, name, slug, status, source_kind, source_hash, redacted_source, manifest, diagnostics, template_id, template_version, created_by_actor_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, 'ready', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[T,m.id,r,n,o,a,t.sourceKind,e.sourceHash,e.redactedSource,E,g,t.templateId??null,t.templateVersion??null,t.createdByActorId??null,p,p]);for(let _ of Object.values(e.manifest.spec.services))this.controlPlane.database.run("INSERT INTO compose_service_states (application_id, service_name, status, replicas, healthy_replicas, observed_state, updated_at) VALUES (?, ?, 'pending', ?, 0, '{}', ?)",[T,_.name,_.replicas,p]);this.controlPlane.appendEvent({projectId:r,resourceId:m.id,actorId:t.createdByActorId,type:"compose.application.created",payload:{applicationId:T,sourceHash:e.sourceHash,serviceNames:Object.keys(e.manifest.spec.services),templateId:t.templateId??null}});let h=this.get(T);return Oc(this.controlPlane,h),h}import(e,t){let r=Cr(e,t);return{application:this.persist(r,{sourceKind:"compose",createdByActorId:t.createdByActorId}),parsed:r}}fromTemplate(e,t,r){let n=Nc(e,t,r,r.version);return{application:this.persist(n,{sourceKind:"template",templateId:e,templateVersion:r.version??"1.0.0",createdByActorId:r.createdByActorId}),parsed:n}}preview(e,t){return Cr(e,t)}get(e){let t=this.controlPlane.database.query("SELECT * FROM compose_applications WHERE id=?").get(e);return t?je(t):void 0}getByResource(e){let t=this.controlPlane.database.query("SELECT * FROM compose_applications WHERE resource_id=?").get(e);return t?je(t):void 0}getBySlug(e,t,r){let n=this.controlPlane.database.query("SELECT * FROM compose_applications WHERE project_id=? AND environment_id=? AND slug=?").get(e,t,r);return n?je(n):void 0}list(e={}){return this.controlPlane.database.query("SELECT * FROM compose_applications ORDER BY updated_at DESC").all().map(je).filter((t)=>(!e.projectId||t.projectId===e.projectId)&&(!e.environmentId||t.environmentId===e.environmentId)&&(e.includeDeleted||t.status!=="deleted"))}services(e){return this.controlPlane.database.query("SELECT * FROM compose_service_states WHERE application_id=? ORDER BY service_name").all(e).map(Ai)}transition(e,t,r={}){let n=this.get(e);if(!n)throw Error(`Compose application ${e} was not found`);let o=this.now().toISOString(),a=t==="deleted"?o:null;this.controlPlane.database.run("UPDATE compose_applications SET status=?, latest_operation_id=COALESCE(?, latest_operation_id), version=version+1, updated_at=?, deleted_at=? WHERE id=?",[t,r.operationId??null,o,a,e]);for(let l of r.services??[])if(n.manifest.spec.services[l.name])this.controlPlane.database.run("INSERT INTO compose_service_states (application_id, service_name, status, replicas, healthy_replicas, latest_operation_id, observed_state, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(application_id, service_name) DO UPDATE SET status=excluded.status, replicas=excluded.replicas, healthy_replicas=excluded.healthy_replicas, latest_operation_id=excluded.latest_operation_id, observed_state=excluded.observed_state, updated_at=excluded.updated_at",[e,l.name,l.status,l.replicas??n.manifest.spec.services[l.name].replicas,l.healthyReplicas??0,r.operationId??null,JSON.stringify(s(l.observedState??{})),o]);return this.controlPlane.appendEvent({projectId:n.projectId,resourceId:n.resourceId,operationId:r.operationId,type:`compose.application.${t}`,level:t==="failed"||t==="degraded"?"error":"info",payload:{applicationId:e,error:r.error??null}}),this.get(e)}}class Tr{controlPlane;applications;queue;constructor(e){this.controlPlane=e;this.applications=new Ot(e),this.queue=new c(e)}enqueue(e,t,r={}){if(e.status==="deleted")throw Error("Deleted Compose applications cannot be operated");if(r.service&&!e.manifest.spec.services[r.service])throw Error(`Compose service ${r.service} was not found`);if(t==="delete"){let o=r.removeVolumes?`${e.slug} delete volumes`:e.slug;if(r.confirmation!==o)throw Error(`Type ${o} to confirm ${r.removeVolumes?"persistent data removal":"stack deletion"}`)}if(t==="scale"&&(!r.service||!Number.isInteger(r.replicas)||r.replicas<0||r.replicas>100))throw Error("Scale requires a service and 0-100 replicas");let n=this.queue.enqueue({projectId:e.projectId,environmentId:e.environmentId,resourceId:e.resourceId,actorId:r.actorId,kind:`compose.${t}`,idempotencyKey:`compose:${e.id}:${t}:${r.service??"stack"}:${r.replicas??""}:${e.version}`,correlationId:`compose:${e.id}`,input:{applicationId:e.id,service:r.service??null,replicas:r.replicas??null,removeVolumes:!!r.removeVolumes},lockKey:`compose:${e.id}`,providerKey:this.controlPlane.getResource(e.resourceId)?.provider??"default",buildSlot:t==="deploy"||t==="redeploy",maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;return this.applications.transition(e.id,t==="delete"?"deleting":t==="stop"?"stopped":t==="start"?"deploying":t==="scale"?e.status:"deploying",{operationId:n.id}),n}}import{createHash as Oi}from"node:crypto";var Ui=/^[a-f0-9]{40,64}$/i,Di=/^[A-Z][A-Z0-9_]{1,127}$/;function K(e){return typeof e==="string"&&e?e:void 0}function ne(e){try{return JSON.parse(String(e))}catch{return{}}}function wi(e){let t=ne(e);return Array.isArray(t)?t.map(String):[]}function Nt(e){return{id:String(e.id),projectId:String(e.project_id),resourceId:String(e.resource_id),baseEnvironmentId:String(e.base_environment_id),enabled:Number(e.enabled)===1,branchRule:K(e.branch_rule),domainPattern:String(e.domain_pattern),ttlHours:Number(e.ttl_hours),keepCount:Number(e.keep_count),publicAccess:Number(e.public_access)===1,authenticationRequired:Number(e.authentication_required)===1,allowForks:Number(e.allow_forks)===1,inheritedSecrets:wi(e.inherited_secrets),resourceOverrides:ne(e.resource_overrides),databaseStrategy:String(e.database_strategy),maxMonthlyCost:Number(e.max_monthly_cost),maxCpu:Number(e.max_cpu),maxMemoryMb:Number(e.max_memory_mb),cleanupOnClose:Number(e.cleanup_on_close)===1,version:Number(e.version),createdByActorId:K(e.created_by_actor_id),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function _e(e){return{id:String(e.id),definitionId:String(e.definition_id),projectId:String(e.project_id),resourceId:String(e.resource_id),baseEnvironmentId:String(e.base_environment_id),identityKey:String(e.identity_key),sourceProvider:K(e.source_provider),repository:K(e.repository),branch:String(e.branch),pullRequestNumber:e.pull_request_number==null?void 0:Number(e.pull_request_number),fork:Number(e.fork)===1,commitSha:String(e.commit_sha),name:String(e.name),stackName:String(e.stack_name),url:K(e.url),status:String(e.status),expiresAt:String(e.expires_at),latestOperationId:K(e.latest_operation_id),createdByActorId:K(e.created_by_actor_id),costEstimate:e.cost_estimate==null?void 0:Number(e.cost_estimate),desiredState:ne(e.desired_state),observedState:ne(e.observed_state),teardownError:K(e.teardown_error),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at),destroyedAt:K(e.destroyed_at)}}function yr(e){return{id:String(e.id),previewId:String(e.preview_id),provider:String(e.provider),providerResourceId:String(e.provider_resource_id),kind:String(e.kind),tags:ne(e.tags),observedState:ne(e.observed_state),discoveredAt:String(e.discovered_at),deletedAt:K(e.deleted_at)}}function Q(e,t,r,n){return Number.isFinite(e)?Math.min(n,Math.max(r,Math.floor(e))):t}function Me(e,t,r,n){return Number.isFinite(e)?Math.min(n,Math.max(r,e)):t}function ft(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,28)||"preview"}class Ue{controlPlane;now;id;constructor(e,t={}){this.controlPlane=e;this.now=t.now??(()=>new Date),this.id=t.id??(()=>crypto.randomUUID())}createDefinition(e){let t=this.controlPlane.getResource(e.resourceId),r=this.controlPlane.listEnvironments(e.projectId).find((E)=>E.id===e.baseEnvironmentId);if(!t||t.projectId!==e.projectId||t.environmentId!==r?.id)throw Error("Preview resource and base environment must belong to the same project scope");if(t.kind!=="application")throw Error("Preview environments currently support application resources only");if(!/^https:\/\//.test(e.domainPattern)||!e.domainPattern.includes("{name}"))throw Error("Preview domainPattern must be HTTPS and include {name}");let n=this.getDefinitionForResource(e.resourceId),o=e.publicAccess??n?.publicAccess??!1,a=e.authenticationRequired??n?.authenticationRequired??!0;if(o&&!a)throw Error("Public preview environments require an authentication policy");let l=[...new Set(e.inheritedSecrets??[])];if(l.some((E)=>!Di.test(E)))throw Error("Inherited preview secret names must use uppercase environment-variable identifiers");let u=this.now().toISOString();if(n)return this.controlPlane.database.run("UPDATE preview_definitions SET base_environment_id=?, enabled=1, branch_rule=?, domain_pattern=?, ttl_hours=?, keep_count=?, public_access=?, authentication_required=?, allow_forks=?, inherited_secrets=?, resource_overrides=?, database_strategy=?, max_monthly_cost=?, max_cpu=?, max_memory_mb=?, cleanup_on_close=?, version=version+1, updated_at=? WHERE id=?",[e.baseEnvironmentId,e.branchRule??null,e.domainPattern,Q(e.ttlHours,n.ttlHours,1,720),Q(e.keepCount,n.keepCount,1,100),o?1:0,a?1:0,e.allowForks??n.allowForks?1:0,JSON.stringify(e.inheritedSecrets===void 0?n.inheritedSecrets:l),JSON.stringify(s(e.resourceOverrides??n.resourceOverrides)),e.databaseStrategy??n.databaseStrategy,Me(e.maxMonthlyCost,n.maxMonthlyCost,0,1e4),Me(e.maxCpu,n.maxCpu,0.1,64),Q(e.maxMemoryMb,n.maxMemoryMb,128,131072),e.cleanupOnClose??n.cleanupOnClose?1:0,u,n.id]),this.controlPlane.appendEvent({projectId:e.projectId,resourceId:e.resourceId,actorId:e.createdByActorId,type:"preview.definition.updated",payload:{definitionId:n.id,baseEnvironmentId:e.baseEnvironmentId,version:n.version+1}}),this.getDefinition(n.id);let p=this.id();return this.controlPlane.database.run("INSERT INTO preview_definitions (id, project_id, resource_id, base_environment_id, enabled, branch_rule, domain_pattern, ttl_hours, keep_count, public_access, authentication_required, allow_forks, inherited_secrets, resource_overrides, database_strategy, max_monthly_cost, max_cpu, max_memory_mb, cleanup_on_close, created_by_actor_id, created_at, updated_at) VALUES (?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[p,e.projectId,e.resourceId,e.baseEnvironmentId,e.branchRule??null,e.domainPattern,Q(e.ttlHours,24,1,720),Q(e.keepCount,10,1,100),e.publicAccess?1:0,e.authenticationRequired===!1?0:1,e.allowForks?1:0,JSON.stringify(l),JSON.stringify(s(e.resourceOverrides??{})),e.databaseStrategy??"disabled",Me(e.maxMonthlyCost,25,0,1e4),Me(e.maxCpu,1,0.1,64),Q(e.maxMemoryMb,1024,128,131072),e.cleanupOnClose===!1?0:1,e.createdByActorId??null,u,u]),this.controlPlane.appendEvent({projectId:e.projectId,resourceId:e.resourceId,actorId:e.createdByActorId,type:"preview.definition.created",payload:{definitionId:p,baseEnvironmentId:e.baseEnvironmentId,ttlHours:Q(e.ttlHours,24,1,720),inheritedSecretNames:l}}),this.getDefinition(p)}getDefinition(e){let t=this.controlPlane.database.query("SELECT * FROM preview_definitions WHERE id=?").get(e);return t?Nt(t):void 0}getDefinitionForResource(e){let t=this.controlPlane.database.query("SELECT * FROM preview_definitions WHERE resource_id=?").get(e);return t?Nt(t):void 0}listDefinitions(e){return this.controlPlane.database.query("SELECT * FROM preview_definitions WHERE project_id=? ORDER BY updated_at DESC").all(e).map(Nt)}listInstances(e={}){return this.controlPlane.database.query("SELECT * FROM preview_instances ORDER BY created_at DESC").all().map(_e).filter((r)=>(!e.projectId||r.projectId===e.projectId)&&(!e.definitionId||r.definitionId===e.definitionId)&&(!e.status||r.status===e.status))}getInstance(e){let t=this.controlPlane.database.query("SELECT * FROM preview_instances WHERE id=?").get(e);return t?_e(t):void 0}findForPullRequest(e,t,r){let n=this.controlPlane.database.query("SELECT * FROM preview_instances WHERE definition_id=? AND identity_key=?").get(e,`pr:${t}:${r}`);return n?_e(n):void 0}findForBranch(e,t,r){let n=this.controlPlane.database.query("SELECT * FROM preview_instances WHERE definition_id=? AND identity_key=?").get(e,`branch:${t}:${r}`);return n?_e(n):void 0}upsert(e){let t=this.getDefinition(e.definitionId);if(!t?.enabled)throw Error("Preview environments are not enabled for this application");if(!Ui.test(e.commitSha))throw Error("Preview deployment requires an immutable 40-64 character commit SHA");if(e.fork&&!t.allowForks)throw Error("Untrusted fork previews are disabled");let r=e.pullRequestNumber?`pr:${e.repository??"unknown"}:${e.pullRequestNumber}`:`branch:${e.repository??"local"}:${e.branch}`,n=Oi("sha256").update(`${t.id}:${r}`).digest("hex").slice(0,8),a=`${(e.pullRequestNumber?`pr-${e.pullRequestNumber}`:ft(e.branch)).slice(0,28)}-${n}`,l=`preview-${a}`.slice(0,63),u=t.domainPattern.replaceAll("{name}",a).replaceAll("{project}",ft(t.projectId)).replaceAll("{branch}",ft(e.branch)).replaceAll("{pr}",String(e.pullRequestNumber??"branch")),p=e.now??this.now(),E=p.toISOString(),g=new Date(p.getTime()+t.ttlHours*60*60*1000).toISOString(),m=this.controlPlane.database.query("SELECT * FROM preview_instances WHERE definition_id=? AND identity_key=?").get(t.id,r);if(m){let _=_e(m),N=_.commitSha!==e.commitSha||_.status==="destroyed";if(N)this.controlPlane.database.run("UPDATE preview_instances SET commit_sha=?, branch=?, fork=?, status='queued', expires_at=?, url=?, teardown_error=NULL, destroyed_at=NULL, version=version+1, updated_at=? WHERE id=?",[e.commitSha,e.branch,e.fork?1:0,g,u,E,_.id]);return{preview:this.getInstance(_.id),created:!1,changed:N,inheritedSecrets:e.fork?[]:t.inheritedSecrets}}let T=this.id(),h=s({source:{provider:e.sourceProvider??null,repository:e.repository??null,branch:e.branch,commitSha:e.commitSha,pullRequestNumber:e.pullRequestNumber??null,fork:!!e.fork},policy:{databaseStrategy:t.databaseStrategy,resourceOverrides:t.resourceOverrides,maxMonthlyCost:t.maxMonthlyCost,maxCpu:t.maxCpu,maxMemoryMb:t.maxMemoryMb,publicAccess:t.publicAccess,authenticationRequired:t.authenticationRequired},inheritedSecretNames:e.fork?[]:t.inheritedSecrets});return this.controlPlane.database.run("INSERT INTO preview_instances (id, definition_id, project_id, resource_id, base_environment_id, identity_key, source_provider, repository, branch, pull_request_number, fork, commit_sha, name, stack_name, url, status, expires_at, created_by_actor_id, desired_state, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'queued', ?, ?, ?, ?, ?)",[T,t.id,t.projectId,t.resourceId,t.baseEnvironmentId,r,e.sourceProvider??null,e.repository??null,e.branch,e.pullRequestNumber??null,e.fork?1:0,e.commitSha,a,l,u,g,e.createdByActorId??null,JSON.stringify(h),E,E]),this.controlPlane.appendEvent({projectId:t.projectId,resourceId:t.resourceId,actorId:e.createdByActorId,type:"preview.created",payload:{previewId:T,identityKey:r,commitSha:e.commitSha,expiresAt:g,fork:!!e.fork}}),{preview:this.getInstance(T),created:!0,changed:!0,inheritedSecrets:e.fork?[]:t.inheritedSecrets}}transition(e,t,r={}){let n=this.getInstance(e);if(!n)throw Error(`Preview ${e} was not found`);let o=this.now().toISOString(),a=t==="destroyed"?o:null;return this.controlPlane.database.run("UPDATE preview_instances SET status=?, latest_operation_id=COALESCE(?, latest_operation_id), observed_state=?, teardown_error=?, cost_estimate=COALESCE(?, cost_estimate), destroyed_at=?, version=version+1, updated_at=? WHERE id=?",[t,r.operationId??null,JSON.stringify(s(r.observedState??n.observedState)),r.teardownError??null,r.costEstimate??null,a,o,e]),this.controlPlane.appendEvent({projectId:n.projectId,resourceId:n.resourceId,operationId:r.operationId,type:`preview.${t}`,level:t==="failed"||t==="cleanup_failed"?"error":"info",payload:{previewId:e,commitSha:n.commitSha,teardownError:r.teardownError??null}}),this.getInstance(e)}extend(e,t){let r=this.getInstance(e),n=r?this.getDefinition(r.definitionId):void 0;if(!r||!n)throw Error(`Preview ${e} was not found`);let o=this.now(),a=Q(t,n.ttlHours,1,720),l=new Date(Math.max(o.getTime(),new Date(r.expiresAt).getTime())+a*3600000).toISOString();return this.controlPlane.database.run("UPDATE preview_instances SET expires_at=?, version=version+1, updated_at=? WHERE id=?",[l,o.toISOString(),e]),this.getInstance(e)}expired(e=this.now()){return this.listInstances().filter((t)=>["queued","deploying","active","updating","failed","cleanup_failed"].includes(t.status)&&new Date(t.expiresAt)<=e)}recordResource(e){let t=this.getInstance(e.previewId);if(!t)throw Error(`Preview ${e.previewId} was not found`);let r={"ts-cloud:preview":t.id,"ts-cloud:project":t.projectId,"ts-cloud:expires-at":t.expiresAt};for(let[l,u]of Object.entries(r))if(e.tags[l]!==u)throw Error(`Preview resource is missing immutable tag ${l}`);let n=this.id(),o=this.now().toISOString();this.controlPlane.database.run("INSERT INTO preview_resources (id, preview_id, provider, provider_resource_id, kind, tags, observed_state, discovered_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(preview_id, provider, provider_resource_id) DO UPDATE SET kind=excluded.kind, tags=excluded.tags, observed_state=excluded.observed_state, deleted_at=NULL",[n,t.id,e.provider,e.providerResourceId,e.kind,JSON.stringify(e.tags),JSON.stringify(s(e.observedState??{})),o]);let a=this.controlPlane.database.query("SELECT * FROM preview_resources WHERE preview_id=? AND provider=? AND provider_resource_id=?").get(t.id,e.provider,e.providerResourceId);return yr(a)}listResources(e){return this.controlPlane.database.query("SELECT * FROM preview_resources WHERE preview_id=? ORDER BY kind, provider_resource_id").all(e).map(yr)}markResourcesDeleted(e){if(!this.getInstance(e))throw Error(`Preview ${e} was not found`);return this.controlPlane.database.run("UPDATE preview_resources SET deleted_at=? WHERE preview_id=? AND deleted_at IS NULL",[this.now().toISOString(),e]).changes}}class br{controlPlane;previews;queue;constructor(e){this.controlPlane=e;this.previews=new Ue(e),this.queue=new c(e)}enqueueDeploy(e,t={}){let r=t.created?"preview.create":"preview.update",n=t.reason==="manual_rebuild"?`:${crypto.randomUUID()}`:"",o=this.queue.enqueue({projectId:e.projectId,environmentId:e.baseEnvironmentId,resourceId:e.resourceId,actorId:t.actorId,kind:r,correlationId:`preview:${e.id}`,idempotencyKey:`preview:${e.id}:${e.commitSha}${n}`,input:{previewId:e.id,reason:t.reason??(t.created?"create":"commit_update"),source:{repository:e.repository??null,branch:e.branch,commitSha:e.commitSha,pullRequestNumber:e.pullRequestNumber??null,fork:e.fork}},lockKey:`preview:${e.id}`,providerKey:"preview",buildSlot:!0,maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;return this.previews.transition(e.id,"queued",{operationId:o.id}),o}enqueueDestroy(e,t,r){if(e.status==="destroyed")throw Error("Preview is already destroyed");let n=this.queue.enqueue({projectId:e.projectId,environmentId:e.baseEnvironmentId,resourceId:e.resourceId,actorId:r,kind:"preview.destroy",correlationId:`preview:${e.id}`,idempotencyKey:`preview:${e.id}:destroy:${t}`,input:{previewId:e.id,reason:t},lockKey:`preview:${e.id}`,providerKey:"preview",maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;return this.previews.transition(e.id,"queued",{operationId:n.id}),n}cleanup(e={}){let t=e.now??new Date,r=new Map,n=this.previews.listInstances().filter((p)=>!["destroyed","destroying"].includes(p.status)),o=(p,E)=>{let g=r.get(p.id)??{preview:p,reasons:[]};if(!g.reasons.includes(E))g.reasons.push(E);r.set(p.id,g)};for(let p of n){if(new Date(p.expiresAt)<=t)o(p,"ttl_expired");if(e.maxAgeHours&&t.getTime()-new Date(p.createdAt).getTime()>=e.maxAgeHours*3600000)o(p,"max_age")}let a=new Map;for(let p of n)a.set(p.definitionId,[...a.get(p.definitionId)??[],p]);for(let[p,E]of a){let g=this.previews.getDefinition(p),m=e.keepCount??g?.keepCount;if(!m)continue;E.sort((T,h)=>h.createdAt.localeCompare(T.createdAt)).slice(m).forEach((T)=>o(T,"keep_count"))}let l=[...r.values()].sort((p,E)=>p.preview.createdAt.localeCompare(E.preview.createdAt)),u=e.dryRun?[]:l.map((p)=>this.enqueueDestroy(p.preview,p.reasons.sort().join("+"),e.actorId));if(l.length)this.controlPlane.appendEvent({actorId:e.actorId,type:e.dryRun?"preview.cleanup.planned":"preview.cleanup.queued",payload:{previewIds:l.map((p)=>p.preview.id),reasons:Object.fromEntries(l.map((p)=>[p.preview.id,p.reasons])),dryRun:!!e.dryRun}});return{candidates:l,operations:u,dryRun:!!e.dryRun}}reconcile(e){let t=[],r=[],n=[];for(let o of e){let a=o.tags["ts-cloud:preview"],l=o.tags["ts-cloud:project"],u=o.tags["ts-cloud:expires-at"];if(!a||!l||!u){n.push(o.providerResourceId);continue}let p=this.previews.getInstance(a);if(!p||p.projectId!==l||p.expiresAt!==u){r.push(o.providerResourceId);continue}if(this.previews.recordResource({...o,previewId:p.id}),o.estimatedMonthlyCost!==void 0)this.previews.transition(p.id,p.status,{costEstimate:o.estimatedMonthlyCost,observedState:{...p.observedState,lastReconciledAt:new Date().toISOString()}});t.push(o.providerResourceId)}if(r.length)this.controlPlane.appendEvent({type:"preview.reconciliation.leaks",level:"error",payload:{providerResourceIds:r}});return{matched:t,unknownPreviewResources:r,ignoredUntagged:n}}}var Wh=["deployment.create","deployment.rollback","application.create","deploy.source","deploy.preview","preview.create","preview.update","preview.destroy","compose.deploy","compose.redeploy","compose.start","compose.stop","compose.delete","compose.scale"];function ze(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function Jh(e,t){if(!t.projectId||!t.environmentId)throw Error(`Queued ${t.kind} operation is missing its project or environment scope`);let r=e.listEnvironments(t.projectId).find((l)=>l.id===t.environmentId);if(!r)throw Error(`Environment ${t.environmentId} was not found for queued ${t.kind} operation`);let n=t.resourceId?e.getResource(t.resourceId):void 0;if(t.resourceId&&(!n||n.projectId!==t.projectId||n.environmentId!==t.environmentId))throw Error(`Resource ${t.resourceId} was not found in the queued deployment scope`);let o=ze(t.input);if(t.kind.startsWith("compose.")){let l=typeof o.applicationId==="string"?o.applicationId:void 0,u=l?new Ot(e).get(l):t.resourceId?new Ot(e).getByResource(t.resourceId):void 0;if(!u||u.projectId!==t.projectId||u.environmentId!==t.environmentId||u.resourceId!==t.resourceId)throw Error("Queued Compose application does not match the operation scope");let p=t.kind.slice(8),E=["compose:apply",u.id,"--action",p,"--env",r.slug];if(typeof o.service==="string"&&o.service)E.push("--service",o.service);if(typeof o.replicas==="number")E.push("--replicas",String(o.replicas));if(o.removeVolumes===!0)E.push("--remove-volumes");return{id:`queue:${t.id}`,label:`${p[0].toUpperCase()}${p.slice(1)} Compose application`,description:`${p} ${u.name}.`,command:E,mutates:!0,target:{environment:r.slug,resource:n?.slug,composeId:u.id}}}if(t.kind.startsWith("preview.")){let l=typeof o.previewId==="string"?o.previewId:void 0,u=l?new Ue(e).getInstance(l):void 0;if(!u)throw Error(`Preview ${l??"(missing)"} was not found for queued ${t.kind}`);if(u.projectId!==t.projectId||u.resourceId!==t.resourceId)throw Error("Queued preview does not match the operation scope");if(t.kind==="preview.destroy")return{id:`queue:${t.id}`,label:"Destroy preview",description:`Destroy ${u.name}.`,command:["stack:delete",u.stackName,"--yes"],mutates:!0,target:{environment:r.slug,resource:n?.slug,previewId:u.id}};return{id:`queue:${t.id}`,label:t.kind==="preview.create"?"Create preview":"Update preview",description:`Deploy ${u.name} at ${u.commitSha}.`,command:["deploy","--stack",u.stackName,"--env",r.slug,"--yes","--skip-dns-verification",...n?["--site",n.slug]:[]],mutates:!0,target:{environment:r.slug,resource:n?.slug,previewId:u.id}}}if(t.kind==="deployment.rollback"){let l=["deploy:rollback"];if(n)l.push(n.slug);if(l.push("--env",r.slug),typeof o.revision==="string"&&o.revision)l.push("--to",o.revision);return{id:`queue:${t.id}`,label:"Rollback deployment",description:`Roll back ${n?.slug??r.slug}.`,command:l,mutates:!0,target:{environment:r.slug,resource:n?.slug}}}let a=["deploy","--env",r.slug,"--yes"];if(n)a.push("--site",n.slug);return{id:`queue:${t.id}`,label:t.kind==="deploy.preview"?"Deploy preview":"Deploy release",description:`Deploy ${n?.slug??r.slug}.`,command:a,mutates:!0,target:{environment:r.slug,resource:n?.slug}}}function ki(e){let t=e.stderr?.trim()||`Deployment process exited with code ${e.exitCode}`;if(/\b(?:429|rate.?limit|throttl)/i.test(t))return new X(t,"provider_throttled");if(/\b(?:502|503|504|temporar(?:y|ily)|unavailable|provider.?error)/i.test(t))return new X(t,"provider_unavailable");if(/\b(?:network|econn|enotfound|socket|timed?\s*out|fetch failed|dns)\b/i.test(t))return new X(t,"network");return Error(t)}function _c(e){let t=async(r)=>{r.checkpoint("prepare","Resolving the persisted deployment target.");let n=Jh(e.store,r.operation),o=n.target.previewId?new Ue(e.store):void 0,a=n.target.composeId?new Ot(e.store):void 0;if(o&&n.target.previewId)o.transition(n.target.previewId,r.operation.kind==="preview.destroy"?"destroying":r.operation.kind==="preview.update"?"updating":"deploying",{operationId:r.operation.id});if(a&&n.target.composeId)a.transition(n.target.composeId,r.operation.kind==="compose.delete"?"deleting":r.operation.kind==="compose.stop"?"stopped":"deploying",{operationId:r.operation.id});r.log(`Target: ${n.target.resource??"all resources"} in ${n.target.environment}.`,{stream:"system"}),r.throwIfCancellationRequested(),r.checkpoint("execute",`Running cloud ${n.command.join(" ")}.`);let l=await e.execute(n,r);if(!l.ok){if(o&&n.target.previewId)o.transition(n.target.previewId,r.operation.kind==="preview.destroy"?"cleanup_failed":"failed",{operationId:r.operation.id,teardownError:r.operation.kind==="preview.destroy"?l.stderr?.trim()||`Process exited with ${l.exitCode}`:void 0});if(a&&n.target.composeId)a.transition(n.target.composeId,r.operation.kind==="compose.delete"?"degraded":"failed",{operationId:r.operation.id,error:l.stderr?.trim()||`Process exited with ${l.exitCode}`});throw ki(l)}if(r.throwIfCancellationRequested(),o&&n.target.previewId){let u=o.getInstance(n.target.previewId);if(r.operation.kind==="preview.destroy")o.markResourcesDeleted(u.id),o.transition(u.id,"destroyed",{operationId:r.operation.id,observedState:{reconciledResourceIds:o.listResources(u.id).map((p)=>p.providerResourceId),exactCommitSha:u.commitSha}});else{let p=e.store.getResource(u.resourceId)?.provider??"default";o.recordResource({previewId:u.id,provider:p,providerResourceId:u.stackName,kind:"stack",tags:{"ts-cloud:preview":u.id,"ts-cloud:project":u.projectId,"ts-cloud:expires-at":u.expiresAt},observedState:{command:l.command??null,exactCommitSha:u.commitSha}}),o.transition(u.id,"active",{operationId:r.operation.id,observedState:{url:u.url??null,stackName:u.stackName,exactCommitSha:u.commitSha,providerStatus:"deployed"}})}}if(a&&n.target.composeId){let u=a.get(n.target.composeId),p=typeof ze(r.operation.input).service==="string"?String(ze(r.operation.input).service):void 0,E=r.operation.kind==="compose.delete"?"deleted":r.operation.kind==="compose.stop"?"stopped":"running",g=a.transition(u.id,E,{operationId:r.operation.id,services:Object.values(u.manifest.spec.services).filter((m)=>!p||m.name===p).map((m)=>({name:m.name,status:E==="stopped"||E==="deleted"?"stopped":"running",replicas:E==="deleted"?0:m.replicas,healthyReplicas:E==="running"?m.replicas:0,observedState:{command:l.command??null,healthGatePassed:E==="running"}}))});if(E==="deleted")fp(e.store,g,ze(r.operation.input).removeVolumes===!0)}return r.checkpoint("finalize","Deployment command completed; persisting the terminal result."),{command:l.command??`cloud ${n.command.join(" ")}`,exitCode:l.exitCode,environment:n.target.environment,resource:n.target.resource??null}};return Object.fromEntries(Wh.map((r)=>[r,t]))}class i extends Error{code;status;details;constructor(e,t,r,n){super(t);this.code=e;this.status=r;this.details=n}}function yt(e,t){if(e.organizationId!==t.organizationId)return!1;if(e.projectId&&e.projectId!==t.projectId)return!1;if(e.environmentId&&e.environmentId!==t.environmentId)return!1;if(e.resourceId&&e.resourceId!==t.resourceId)return!1;return!0}function Cf(e,t,r){return Xi("sha256").update(`${e.toUpperCase()}
|
|
1616
1616
|
${t}
|
|
1617
|
-
${JSON.stringify(r)}`).digest("hex")}class mi{controlPlane;identities;queue;spendGate;constructor(e,t){this.controlPlane=e;this.identities=t;this.queue=new c(e),this.spendGate=new Pr(e)}target(e,t){let r=this.controlPlane.resolveAuthorizationTarget(e.serviceAccount.organizationId,t),n=this.controlPlane.resolveAuthorizationTarget(e.serviceAccount.organizationId,e.token.scope);if(!r||!n||!yt(n,r))throw new i("forbidden","The token does not grant access to this resource.",403);return r}authorize(e,t,r){if(!e.token.capabilities.includes(t))throw new i("forbidden",`The token is missing the ${t} capability.`,403);let n=this.controlPlane.resolveAuthorizationTarget(e.serviceAccount.organizationId,r),o=this.controlPlane.resolveAuthorizationTarget(e.serviceAccount.organizationId,e.token.scope),a=t==="project:read"&&!!n&&!!o&&yt(n,o);if(!n||!o||!yt(o,n)&&!a)throw new i("forbidden","The token does not grant access to this resource.",403);let l=a?o:n;if(!w({membership:e.membership,grants:this.controlPlane.listGrants(e.membership.id),capability:t,target:l}).allowed)throw new i("forbidden","The service account does not have access to this resource.",403);return n}listProjects(e){return this.controlPlane.listProjects().filter((t)=>t.organizationId===e.serviceAccount.organizationId).filter((t)=>{try{return this.authorize(e,"project:read",{type:"project",id:t.id}),!0}catch{return!1}}).map((t)=>({id:t.id,slug:t.slug,name:t.name,description:t.description,version:t.version,createdAt:t.createdAt,updatedAt:t.updatedAt}))}listEnvironments(e,t){let r=this.controlPlane.getProject(t);if(!r||r.organizationId!==e.serviceAccount.organizationId)throw new i("not_found","Project was not found.",404);return this.controlPlane.listEnvironments(t).filter((n)=>{try{return this.authorize(e,"project:read",{type:"environment",id:n.id}),!0}catch{return!1}}).map((n)=>({id:n.id,projectId:n.projectId,slug:n.slug,name:n.name,kind:n.kind,region:n.region,version:n.version,createdAt:n.createdAt,updatedAt:n.updatedAt}))}listServices(e,t,r){let n=new Set(this.listEnvironments(e,t).map((o)=>String(o.id)));if(r&&!n.has(r))throw new i("not_found","Environment was not found.",404);return this.controlPlane.listResources(t,r).filter((o)=>!o.environmentId||n.has(o.environmentId)).filter((o)=>{try{return this.authorize(e,"project:read",{type:"resource",id:o.id}),!0}catch{return!1}}).map((o)=>({id:o.id,projectId:o.projectId,environmentId:o.environmentId,kind:o.kind,slug:o.slug,name:o.name,provider:o.provider,providerId:o.providerId,metadata:s(o.metadata),version:o.version,createdAt:o.createdAt,updatedAt:o.updatedAt}))}listOperations(e,t){return this.controlPlane.listOperations({projectId:t,limit:500}).filter((n)=>{let o=n.resourceId?{type:"resource",id:n.resourceId}:n.environmentId?{type:"environment",id:n.environmentId}:n.projectId?{type:"project",id:n.projectId}:{type:"organization"};try{return this.authorize(e,"deployments:read",o),!0}catch{return!1}}).map((n)=>this.operation(n))}listEvents(e,t,r){if(t)this.authorize(e,"audit:read",{type:"project",id:t});else this.authorize(e,"audit:read",e.token.scope);return this.controlPlane.listEvents({organizationId:e.serviceAccount.organizationId,projectId:t,afterSequence:r,limit:500}).filter((n)=>{let o=n.resourceId?{type:"resource",id:n.resourceId}:n.projectId?{type:"project",id:n.projectId}:{type:"organization"};try{return this.target(e,o),!0}catch{return!1}}).map((n)=>({id:n.id,sequence:n.sequence,projectId:n.projectId,operationId:n.operationId,resourceId:n.resourceId,correlationId:n.correlationId,type:n.type,level:n.level,payload:s(n.payload),createdAt:n.createdAt}))}createDeployment(e,t,r){if(!this.controlPlane.listEnvironments(t.projectId).find((g)=>g.id===t.environmentId))throw new i("not_found","Environment was not found in this project.",404);let o=t.serviceId?{type:"resource",id:t.serviceId}:{type:"environment",id:t.environmentId};this.authorize(e,"deployments:create",o);let a=this.spendGate.check("deploy",{organizationId:e.serviceAccount.organizationId,projectId:t.projectId,environmentId:t.environmentId});if(!a.allowed)throw new i("spend_cap_exceeded",a.reason??"A spend cap is blocking deployments.",402,{action:a.action,budgetId:a.budgetId});let l=mf("POST","/api/v1/deployments",t),u=this.identities.getIdempotency(e.token.id,r);if(u){if(u.requestHash!==l)throw new i("idempotency_conflict","Idempotency-Key was already used for another request.",409);let g=u.operationId?this.controlPlane.getOperation(u.operationId):void 0;if(!g)throw new i("idempotency_unavailable","The original operation is no longer available.",409);return{operation:this.operation(g),replay:!0}}if(t.serviceId){let g=this.controlPlane.getResource(t.serviceId);if(!g||g.projectId!==t.projectId||g.environmentId!==t.environmentId)throw new i("not_found","Service was not found in this environment.",404)}let p=t.serviceId?this.controlPlane.getResource(t.serviceId):void 0,E=this.queue.enqueue({projectId:t.projectId,environmentId:t.environmentId,resourceId:t.serviceId,actorId:e.actor.id,kind:t.action==="rollback"?"deployment.rollback":"deployment.create",idempotencyKey:`api:${e.token.id}:${r}`,input:s({action:t.action??"deploy",revision:t.revision??null}),lockKey:t.serviceId?`resource:${t.serviceId}`:`environment:${t.environmentId}`,providerKey:p?.provider??"default",buildSlot:t.action!=="rollback",maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;return this.identities.saveIdempotency({tokenId:e.token.id,key:r,requestHash:l,operationId:E.id,responseStatus:202,responseBody:{operationId:E.id}}),{operation:this.operation(E),replay:!1}}operation(e){return{id:e.id,state:e.state,kind:e.kind,projectId:e.projectId,environmentId:e.environmentId,resourceId:e.resourceId,actorId:e.actorId,correlationId:e.correlationId,input:s(e.input),output:s(e.output),error:e.error,attempt:e.attempt,createdAt:e.createdAt,updatedAt:e.updatedAt,startedAt:e.startedAt,finishedAt:e.finishedAt}}}function qe(e){return e.serviceAccount.organizationId}function yr(e){if(e==null)return;if(e==="daily"||e==="weekly"||e==="monthly")return e;throw new i("validation_error","period must be daily, weekly, or monthly.",422)}function ie(e,t){if(e==null)return;let r=Number(e);if(!Number.isFinite(r)||r<0||!Number.isInteger(r))throw new i("validation_error",`${t} must be a non-negative integer.`,422);return r}function j(e,t,r,n,o){if(o)e.authorization.authorize(t,r,{type:"environment",id:o});else if(n)e.authorization.authorize(t,r,{type:"project",id:n});else e.authorization.authorize(t,r,{type:"organization"});return{organizationId:qe(t),projectId:n,environmentId:o}}async function Ks(e,t,r){let{method:n,url:o}=r,a=e.now?.()??new Date,l=o.searchParams.get("projectId")??void 0,u=o.searchParams.get("environmentId")??void 0;if(n==="GET"&&o.pathname==="/api/v1/usage"){let T=j(e,t,"billing:read",l,u);return e.service.usageReport({...T,period:yr(o.searchParams.get("period")),timezone:o.searchParams.get("timezone")??void 0,now:a})}if(n==="GET"&&o.pathname==="/api/v1/usage/rollups"){let T=j(e,t,"billing:read",l,u),N=o.searchParams.get("from"),h=o.searchParams.get("to");if(!N||!h)throw new i("validation_error","from and to are required.",422);if(Number.isNaN(Date.parse(N))||Number.isNaN(Date.parse(h)))throw new i("validation_error","from and to must be ISO-8601 timestamps.",422);let f=o.searchParams.getAll("meter");return{data:e.store.listRollups({...T,from:N,to:h,meters:f.length>0?f:void 0},ie(o.searchParams.get("limit"),"limit")??1000)}}if(n==="GET"&&o.pathname==="/api/v1/usage/focus"){let T=j(e,t,"billing:read",l,u),N=o.searchParams.get("from"),h=o.searchParams.get("to");if(!N||!h)throw new i("validation_error","from and to are required.",422);if(Number.isNaN(Date.parse(N))||Number.isNaN(Date.parse(h)))throw new i("validation_error","from and to must be ISO-8601 timestamps.",422);if(new Date(h).getTime()-new Date(N).getTime()>31622400000)throw new i("validation_error","The range must not exceed one year.",422);let f=o.searchParams.get("granularity")==="hourly"?"hourly":"daily",L=e.store.listRollups({...T,from:N,to:h},1e4),v=Wc(L,{billingPeriodStart:N,billingPeriodEnd:h,currency:e.store.priceBook.currency,granularity:f});return{contentType:"application/x-ndjson",body:qs(v),recordCount:v.length}}if(n==="GET"&&o.pathname==="/api/v1/spend/budgets"){let T=j(e,t,"billing:read",l,u);return{data:e.store.listBudgets({organizationId:T.organizationId,projectId:T.projectId})}}if(n==="POST"&&o.pathname==="/api/v1/spend/budgets"){let T=await r.body?.()??{},h={organizationId:j(e,t,"billing:manage",T.projectId,T.environmentId).organizationId,projectId:T.projectId,environmentId:T.environmentId,name:String(T.name??"").trim(),period:yr(T.period??"monthly")??"monthly",timezone:T.timezone,currency:T.currency,softLimitCents:ie(T.softLimitCents,"softLimitCents"),hardLimitCents:ie(T.hardLimitCents,"hardLimitCents"),thresholds:T.thresholds,meters:T.meters,graceSeconds:ie(T.graceSeconds,"graceSeconds"),hysteresisPercent:T.hysteresisPercent,dryRun:T.dryRun!==!1,enabled:T.enabled};try{return{data:e.store.createBudget(h)}}catch(f){throw new i("validation_error",f instanceof Error?f.message:String(f),422)}}let p=/^\/api\/v1\/spend\/budgets\/([^/]+)$/.exec(o.pathname);if(p&&(n==="PATCH"||n==="DELETE")){let T=e.store.getBudget(decodeURIComponent(p[1]));if(!T||T.organizationId!==qe(t))throw new i("not_found","Budget was not found.",404);if(j(e,t,"billing:manage",T.projectId,T.environmentId),n==="DELETE")return{data:{deleted:e.store.deleteBudget(T.id)}};let N=await r.body?.()??{};try{return{data:e.store.updateBudget(T.id,N,ie(N.expectedVersion,"expectedVersion"))}}catch(h){let f=h instanceof Error?h.message:String(h);throw new i(f.includes("concurrently")?"conflict":"validation_error",f,f.includes("concurrently")?409:422)}}if(n==="GET"&&o.pathname==="/api/v1/spend/anomalies"){let T=j(e,t,"billing:read",l,u);return{data:e.store.listAnomalies({organizationId:T.organizationId,projectId:T.projectId,since:o.searchParams.get("since")??void 0,unacknowledgedOnly:o.searchParams.get("unacknowledged")==="true",limit:ie(o.searchParams.get("limit"),"limit")})}}let E=/^\/api\/v1\/spend\/anomalies\/([^/]+)\/acknowledge$/.exec(o.pathname);if(E&&n==="POST"){let T=e.store.getAnomaly(decodeURIComponent(E[1]));if(!T||T.organizationId!==qe(t))throw new i("not_found","Anomaly was not found.",404);return j(e,t,"billing:manage",T.projectId,T.environmentId),{data:{acknowledged:e.store.acknowledgeAnomaly(T.id)}}}if(n==="GET"&&o.pathname==="/api/v1/spend/signals")return j(e,t,"billing:read",l,u),{data:Dr};if(o.pathname==="/api/v1/spend/anomaly-configs"){if(n==="GET"){let T=j(e,t,"billing:read",l,u);return{data:e.service.anomalyConfigs.list({organizationId:T.organizationId,projectId:T.projectId})}}if(n==="POST"){let T=await r.body?.()??{},N=j(e,t,"billing:manage",T.projectId,T.environmentId);try{return{data:e.service.anomalyConfigs.upsert({organizationId:N.organizationId,projectId:T.projectId,environmentId:T.environmentId,signal:String(T.signal??""),enabled:T.enabled,sensitivity:T.sensitivity,seasonLength:T.seasonLength==null?void 0:Number(T.seasonLength),minAbsoluteDelta:T.minAbsoluteDelta==null?void 0:Number(T.minAbsoluteDelta),detectDrops:T.detectDrops,severity:T.severity})}}catch(h){throw new i("validation_error",h instanceof Error?h.message:String(h),422)}}}let g=/^\/api\/v1\/spend\/anomaly-configs\/([^/]+)$/.exec(o.pathname);if(g&&n==="DELETE"){let T=e.service.anomalyConfigs.get(decodeURIComponent(g[1]));if(!T||T.organizationId!==qe(t))throw new i("not_found","Anomaly config was not found.",404);return j(e,t,"billing:manage",T.projectId,T.environmentId),{data:{deleted:e.service.anomalyConfigs.delete(T.id)}}}if(o.pathname==="/api/v1/spend/anomaly-silences"){if(n==="GET"){let T=j(e,t,"billing:read",l,u);return{data:e.service.anomalyConfigs.listSilences({organizationId:T.organizationId,projectId:T.projectId,includeExpired:o.searchParams.get("includeExpired")==="true"})}}if(n==="POST"){let T=await r.body?.()??{},N=j(e,t,"billing:manage",T.projectId);try{return{data:e.service.anomalyConfigs.silence({organizationId:N.organizationId,projectId:T.projectId,signal:T.signal,routePattern:T.routePattern,statusCode:T.statusCode==null?void 0:Number(T.statusCode),reason:String(T.reason??""),expiresAt:T.expiresAt})}}catch(h){throw new i("validation_error",h instanceof Error?h.message:String(h),422)}}}let m=/^\/api\/v1\/spend\/anomaly-silences\/([^/]+)$/.exec(o.pathname);if(m&&n==="DELETE")return j(e,t,"billing:manage",l),{data:{deleted:e.service.anomalyConfigs.removeSilence(decodeURIComponent(m[1]))}};if(n==="GET"&&o.pathname==="/api/v1/spend/enforcement"){let T=j(e,t,"billing:read",l,u);return{data:e.store.listEnforcements({organizationId:T.organizationId,activeOnly:o.searchParams.get("active")!=="false"})}}if(n==="GET"&&o.pathname==="/api/v1/spend/allowance"){let T=j(e,t,"billing:read",l,u),N=o.searchParams.get("operation")??"deploy";if(!["build","deploy","function_invoke","request"].includes(N))throw new i("validation_error","operation must be build, deploy, function_invoke, or request.",422);let f=e.store.listEnforcements({organizationId:T.organizationId,activeOnly:!0}).filter((S)=>(!S.projectId||S.projectId===T.projectId)&&(!S.environmentId||S.environmentId===T.environmentId)),L=jc(N,f),I=e.store.budgetsForScope(T.organizationId,T.projectId,T.environmentId).map((S)=>e.service.status(S,a));return{operation:N,allowed:L.allowed,blockedBy:L.blockedBy??null,reason:L.reason??null,budgets:I.map((S)=>({id:S.budget.id,name:S.budget.name,usedPercent:S.decision.usedPercent,projectedPercent:S.decision.projectedPercent,level:S.decision.level,timeToCap:S.timeToCap}))}}return}function Ws(){let e=[{name:"projectId",in:"query",schema:{type:"string"}},{name:"environmentId",in:"query",schema:{type:"string"}}];return{"/api/v1/usage":{get:{summary:"Current usage, cost, and every budget governing the scope.",parameters:[...e,{name:"period",in:"query",schema:{type:"string",enum:["daily","weekly","monthly"]}},{name:"timezone",in:"query",schema:{type:"string"}}],responses:{"200":{description:"Usage totals, per-meter breakdown, hourly series, and budget status."}}}},"/api/v1/usage/rollups":{get:{summary:"Itemized hourly usage rollups.",parameters:[...e,{name:"from",in:"query",required:!0,schema:{type:"string",format:"date-time"}},{name:"to",in:"query",required:!0,schema:{type:"string",format:"date-time"}},{name:"meter",in:"query",schema:{type:"array",items:{type:"string"}}},{name:"limit",in:"query",schema:{type:"integer"}}],responses:{"200":{description:"Hourly rollups, newest first."}}}},"/api/v1/usage/focus":{get:{summary:"Usage and cost in FOCUS v1.3 format, newline-delimited JSON.",parameters:[...e,{name:"from",in:"query",required:!0,schema:{type:"string",format:"date-time"}},{name:"to",in:"query",required:!0,schema:{type:"string",format:"date-time"}},{name:"granularity",in:"query",schema:{type:"string",enum:["daily","hourly"]}}],responses:{"200":{description:"FOCUS records, one JSON object per line."}}}},"/api/v1/spend/budgets":{get:{summary:"Budgets governing a scope.",parameters:e,responses:{"200":{description:"Budgets."}}},post:{summary:"Create a budget. Starts in dry run unless dryRun is explicitly false.",responses:{"201":{description:"The created budget."},"422":{description:"Validation error."}}}},"/api/v1/spend/budgets/{budgetId}":{patch:{summary:"Update a budget. Pass expectedVersion for optimistic concurrency.",responses:{"200":{description:"The updated budget."},"409":{description:"Version conflict."}}},delete:{summary:"Delete a budget.",responses:{"200":{description:"Deletion result."}}}},"/api/v1/spend/anomalies":{get:{summary:"Detected spend anomalies.",parameters:[...e,{name:"since",in:"query",schema:{type:"string",format:"date-time"}},{name:"unacknowledged",in:"query",schema:{type:"boolean"}}],responses:{"200":{description:"Anomalies, newest first."}}}},"/api/v1/spend/anomalies/{anomalyId}/acknowledge":{post:{summary:"Acknowledge an anomaly.",responses:{"200":{description:"Acknowledgement result."}}}},"/api/v1/spend/signals":{get:{summary:"Signals anomaly detection can run on, with their gap and sample rules.",responses:{"200":{description:"Signal catalog."}}}},"/api/v1/spend/anomaly-configs":{get:{summary:"Anomaly detection configuration.",parameters:e,responses:{"200":{description:"Configs."}}},post:{summary:"Create or update the config for a signal.",responses:{"200":{description:"The config."}}}},"/api/v1/spend/anomaly-configs/{configId}":{delete:{summary:"Delete an anomaly config, returning the signal to its default.",responses:{"200":{description:"Result."}}}},"/api/v1/spend/anomaly-silences":{get:{summary:"Active anomaly silences.",parameters:e,responses:{"200":{description:"Silences."}}},post:{summary:"Silence a signal, route, or status code. A reason is required.",responses:{"200":{description:"The silence."}}}},"/api/v1/spend/anomaly-silences/{silenceId}":{delete:{summary:"Remove a silence.",responses:{"200":{description:"Result."}}}},"/api/v1/spend/enforcement":{get:{summary:"Enforcement actions in force.",parameters:[...e,{name:"active",in:"query",schema:{type:"boolean"}}],responses:{"200":{description:"Enforcement records."}}}},"/api/v1/spend/allowance":{get:{summary:"Whether an operation is allowed under current spend enforcement.",parameters:[...e,{name:"operation",in:"query",schema:{type:"string",enum:["build","deploy","function_invoke","request"]}}],responses:{"200":{description:"Allowance verdict and the budgets behind it."}}}}}}export{Fe,bc,de,Bt,Ec,w,xt,at,vc,ws,Uh,cp,Tc,s,ri,Rs,Cr,wc,Rc,br,Qh,Dc,Iy,Sy,Ds,Cy,by,Pc,Nc,ni,Ps,X,c,Ns,Ue,Er,Hh,Gh,kc,_t,qh,ks,Vh,jh,Bs,Bc,vr,xs,zh,xc,dp,Ot,Tr,Kh,_s,Wh,R,Jh,_c,lp,Os,Xh,Yh,Zh,Oc,ii,Ls,Lc,Lt,ct,ef,wr,tf,$c,up,pp,$s,Mc,Fc,dt,gp,si,Uc,Ms,Rr,mp,oi,Qc,Hc,ai,hp,Gc,qc,Vc,jc,Fs,fp,Ap,rf,yp,zc,ci,Ip,Sp,Us,Dr,Qs,Hs,Gs,Kc,Cp,Wc,qs,nf,$t,sf,Jc,Pr,Xc,of,Yc,bp,di,Nr,Vs,li,Qe,af,Ep,vp,Mt,Zc,ed,td,ui,pi,gi,cf,df,lt,js,lf,kr,Tp,zs,uf,wp,Rp,Dp,pf,Pp,Np,gf,i,mf,mi,Ks,Ws};
|
|
1617
|
+
${JSON.stringify(r)}`).digest("hex")}class hi{controlPlane;identities;queue;spendGate;constructor(e,t){this.controlPlane=e;this.identities=t;this.queue=new c(e),this.spendGate=new Pr(e)}target(e,t){let r=this.controlPlane.resolveAuthorizationTarget(e.serviceAccount.organizationId,t),n=this.controlPlane.resolveAuthorizationTarget(e.serviceAccount.organizationId,e.token.scope);if(!r||!n||!yt(n,r))throw new i("forbidden","The token does not grant access to this resource.",403);return r}authorize(e,t,r){if(!e.token.capabilities.includes(t))throw new i("forbidden",`The token is missing the ${t} capability.`,403);let n=this.controlPlane.resolveAuthorizationTarget(e.serviceAccount.organizationId,r),o=this.controlPlane.resolveAuthorizationTarget(e.serviceAccount.organizationId,e.token.scope),a=t==="project:read"&&!!n&&!!o&&yt(n,o);if(!n||!o||!yt(o,n)&&!a)throw new i("forbidden","The token does not grant access to this resource.",403);let l=a?o:n;if(!w({membership:e.membership,grants:this.controlPlane.listGrants(e.membership.id),capability:t,target:l}).allowed)throw new i("forbidden","The service account does not have access to this resource.",403);return n}listProjects(e){return this.controlPlane.listProjects().filter((t)=>t.organizationId===e.serviceAccount.organizationId).filter((t)=>{try{return this.authorize(e,"project:read",{type:"project",id:t.id}),!0}catch{return!1}}).map((t)=>({id:t.id,slug:t.slug,name:t.name,description:t.description,version:t.version,createdAt:t.createdAt,updatedAt:t.updatedAt}))}listEnvironments(e,t){let r=this.controlPlane.getProject(t);if(!r||r.organizationId!==e.serviceAccount.organizationId)throw new i("not_found","Project was not found.",404);return this.controlPlane.listEnvironments(t).filter((n)=>{try{return this.authorize(e,"project:read",{type:"environment",id:n.id}),!0}catch{return!1}}).map((n)=>({id:n.id,projectId:n.projectId,slug:n.slug,name:n.name,kind:n.kind,region:n.region,version:n.version,createdAt:n.createdAt,updatedAt:n.updatedAt}))}listServices(e,t,r){let n=new Set(this.listEnvironments(e,t).map((o)=>String(o.id)));if(r&&!n.has(r))throw new i("not_found","Environment was not found.",404);return this.controlPlane.listResources(t,r).filter((o)=>!o.environmentId||n.has(o.environmentId)).filter((o)=>{try{return this.authorize(e,"project:read",{type:"resource",id:o.id}),!0}catch{return!1}}).map((o)=>({id:o.id,projectId:o.projectId,environmentId:o.environmentId,kind:o.kind,slug:o.slug,name:o.name,provider:o.provider,providerId:o.providerId,metadata:s(o.metadata),version:o.version,createdAt:o.createdAt,updatedAt:o.updatedAt}))}listOperations(e,t){return this.controlPlane.listOperations({projectId:t,limit:500}).filter((n)=>{let o=n.resourceId?{type:"resource",id:n.resourceId}:n.environmentId?{type:"environment",id:n.environmentId}:n.projectId?{type:"project",id:n.projectId}:{type:"organization"};try{return this.authorize(e,"deployments:read",o),!0}catch{return!1}}).map((n)=>this.operation(n))}listEvents(e,t,r){if(t)this.authorize(e,"audit:read",{type:"project",id:t});else this.authorize(e,"audit:read",e.token.scope);return this.controlPlane.listEvents({organizationId:e.serviceAccount.organizationId,projectId:t,afterSequence:r,limit:500}).filter((n)=>{let o=n.resourceId?{type:"resource",id:n.resourceId}:n.projectId?{type:"project",id:n.projectId}:{type:"organization"};try{return this.target(e,o),!0}catch{return!1}}).map((n)=>({id:n.id,sequence:n.sequence,projectId:n.projectId,operationId:n.operationId,resourceId:n.resourceId,correlationId:n.correlationId,type:n.type,level:n.level,payload:s(n.payload),createdAt:n.createdAt}))}createDeployment(e,t,r){if(!this.controlPlane.listEnvironments(t.projectId).find((g)=>g.id===t.environmentId))throw new i("not_found","Environment was not found in this project.",404);let o=t.serviceId?{type:"resource",id:t.serviceId}:{type:"environment",id:t.environmentId};this.authorize(e,"deployments:create",o);let a=this.spendGate.check("deploy",{organizationId:e.serviceAccount.organizationId,projectId:t.projectId,environmentId:t.environmentId});if(!a.allowed)throw new i("spend_cap_exceeded",a.reason??"A spend cap is blocking deployments.",402,{action:a.action,budgetId:a.budgetId});let l=Cf("POST","/api/v1/deployments",t),u=this.identities.getIdempotency(e.token.id,r);if(u){if(u.requestHash!==l)throw new i("idempotency_conflict","Idempotency-Key was already used for another request.",409);let g=u.operationId?this.controlPlane.getOperation(u.operationId):void 0;if(!g)throw new i("idempotency_unavailable","The original operation is no longer available.",409);return{operation:this.operation(g),replay:!0}}if(t.serviceId){let g=this.controlPlane.getResource(t.serviceId);if(!g||g.projectId!==t.projectId||g.environmentId!==t.environmentId)throw new i("not_found","Service was not found in this environment.",404)}let p=t.serviceId?this.controlPlane.getResource(t.serviceId):void 0,E=this.queue.enqueue({projectId:t.projectId,environmentId:t.environmentId,resourceId:t.serviceId,actorId:e.actor.id,kind:t.action==="rollback"?"deployment.rollback":"deployment.create",idempotencyKey:`api:${e.token.id}:${r}`,input:s({action:t.action??"deploy",revision:t.revision??null}),lockKey:t.serviceId?`resource:${t.serviceId}`:`environment:${t.environmentId}`,providerKey:p?.provider??"default",buildSlot:t.action!=="rollback",maxAttempts:3,retryClasses:["network","provider_throttled","provider_unavailable"],resumePolicy:"fail",cancellationMode:"provider_non_cancellable",retentionDays:90}).operation;return this.identities.saveIdempotency({tokenId:e.token.id,key:r,requestHash:l,operationId:E.id,responseStatus:202,responseBody:{operationId:E.id}}),{operation:this.operation(E),replay:!1}}operation(e){return{id:e.id,state:e.state,kind:e.kind,projectId:e.projectId,environmentId:e.environmentId,resourceId:e.resourceId,actorId:e.actorId,correlationId:e.correlationId,input:s(e.input),output:s(e.output),error:e.error,attempt:e.attempt,createdAt:e.createdAt,updatedAt:e.updatedAt,startedAt:e.startedAt,finishedAt:e.finishedAt}}}function qe(e){return e.serviceAccount.organizationId}function Lr(e){if(e==null)return;if(e==="daily"||e==="weekly"||e==="monthly")return e;throw new i("validation_error","period must be daily, weekly, or monthly.",422)}function ie(e,t){if(e==null)return;let r=Number(e);if(!Number.isFinite(r)||r<0||!Number.isInteger(r))throw new i("validation_error",`${t} must be a non-negative integer.`,422);return r}function j(e,t,r,n,o){if(o)e.authorization.authorize(t,r,{type:"environment",id:o});else if(n)e.authorization.authorize(t,r,{type:"project",id:n});else e.authorization.authorize(t,r,{type:"organization"});return{organizationId:qe(t),projectId:n,environmentId:o}}async function Js(e,t,r){let{method:n,url:o}=r,a=e.now?.()??new Date,l=o.searchParams.get("projectId")??void 0,u=o.searchParams.get("environmentId")??void 0;if(n==="GET"&&o.pathname==="/api/v1/usage"){let T=j(e,t,"billing:read",l,u);return e.service.usageReport({...T,period:Lr(o.searchParams.get("period")),timezone:o.searchParams.get("timezone")??void 0,now:a})}if(n==="GET"&&o.pathname==="/api/v1/usage/rollups"){let T=j(e,t,"billing:read",l,u),h=o.searchParams.get("from"),_=o.searchParams.get("to");if(!h||!_)throw new i("validation_error","from and to are required.",422);if(Number.isNaN(Date.parse(h))||Number.isNaN(Date.parse(_)))throw new i("validation_error","from and to must be ISO-8601 timestamps.",422);let N=o.searchParams.getAll("meter");return{data:e.store.listRollups({...T,from:h,to:_,meters:N.length>0?N:void 0},ie(o.searchParams.get("limit"),"limit")??1000)}}if(n==="GET"&&o.pathname==="/api/v1/usage/focus"){let T=j(e,t,"billing:read",l,u),h=o.searchParams.get("from"),_=o.searchParams.get("to");if(!h||!_)throw new i("validation_error","from and to are required.",422);if(Number.isNaN(Date.parse(h))||Number.isNaN(Date.parse(_)))throw new i("validation_error","from and to must be ISO-8601 timestamps.",422);if(new Date(_).getTime()-new Date(h).getTime()>31622400000)throw new i("validation_error","The range must not exceed one year.",422);let N=o.searchParams.get("granularity")==="hourly"?"hourly":"daily",y=e.store.listRollups({...T,from:h,to:_},1e4),L=Xc(y,{billingPeriodStart:h,billingPeriodEnd:_,currency:e.store.priceBook.currency,granularity:N});return{contentType:"application/x-ndjson",body:js(L),recordCount:L.length}}if(n==="GET"&&o.pathname==="/api/v1/spend/budgets"){let T=j(e,t,"billing:read",l,u);return{data:e.store.listBudgets({organizationId:T.organizationId,projectId:T.projectId})}}if(n==="POST"&&o.pathname==="/api/v1/spend/budgets"){let T=await r.body?.()??{},_={organizationId:j(e,t,"billing:manage",T.projectId,T.environmentId).organizationId,projectId:T.projectId,environmentId:T.environmentId,name:String(T.name??"").trim(),period:Lr(T.period??"monthly")??"monthly",timezone:T.timezone,currency:T.currency,softLimitCents:ie(T.softLimitCents,"softLimitCents"),hardLimitCents:ie(T.hardLimitCents,"hardLimitCents"),thresholds:T.thresholds,meters:T.meters,graceSeconds:ie(T.graceSeconds,"graceSeconds"),hysteresisPercent:T.hysteresisPercent,dryRun:T.dryRun!==!1,enabled:T.enabled};try{return{data:e.store.createBudget(_)}}catch(N){throw new i("validation_error",N instanceof Error?N.message:String(N),422)}}let p=/^\/api\/v1\/spend\/budgets\/([^/]+)$/.exec(o.pathname);if(p&&(n==="PATCH"||n==="DELETE")){let T=e.store.getBudget(decodeURIComponent(p[1]));if(!T||T.organizationId!==qe(t))throw new i("not_found","Budget was not found.",404);if(j(e,t,"billing:manage",T.projectId,T.environmentId),n==="DELETE")return{data:{deleted:e.store.deleteBudget(T.id)}};let h=await r.body?.()??{};try{return{data:e.store.updateBudget(T.id,h,ie(h.expectedVersion,"expectedVersion"))}}catch(_){let N=_ instanceof Error?_.message:String(_);throw new i(N.includes("concurrently")?"conflict":"validation_error",N,N.includes("concurrently")?409:422)}}if(n==="GET"&&o.pathname==="/api/v1/spend/anomalies"){let T=j(e,t,"billing:read",l,u);return{data:e.store.listAnomalies({organizationId:T.organizationId,projectId:T.projectId,since:o.searchParams.get("since")??void 0,unacknowledgedOnly:o.searchParams.get("unacknowledged")==="true",limit:ie(o.searchParams.get("limit"),"limit")})}}let E=/^\/api\/v1\/spend\/anomalies\/([^/]+)\/acknowledge$/.exec(o.pathname);if(E&&n==="POST"){let T=e.store.getAnomaly(decodeURIComponent(E[1]));if(!T||T.organizationId!==qe(t))throw new i("not_found","Anomaly was not found.",404);return j(e,t,"billing:manage",T.projectId,T.environmentId),{data:{acknowledged:e.store.acknowledgeAnomaly(T.id)}}}if(n==="GET"&&o.pathname==="/api/v1/spend/signals")return j(e,t,"billing:read",l,u),{data:Dr};if(o.pathname==="/api/v1/spend/anomaly-configs"){if(n==="GET"){let T=j(e,t,"billing:read",l,u);return{data:e.service.anomalyConfigs.list({organizationId:T.organizationId,projectId:T.projectId})}}if(n==="POST"){let T=await r.body?.()??{},h=j(e,t,"billing:manage",T.projectId,T.environmentId);try{return{data:e.service.anomalyConfigs.upsert({organizationId:h.organizationId,projectId:T.projectId,environmentId:T.environmentId,signal:String(T.signal??""),enabled:T.enabled,sensitivity:T.sensitivity,seasonLength:T.seasonLength==null?void 0:Number(T.seasonLength),minAbsoluteDelta:T.minAbsoluteDelta==null?void 0:Number(T.minAbsoluteDelta),detectDrops:T.detectDrops,severity:T.severity})}}catch(_){throw new i("validation_error",_ instanceof Error?_.message:String(_),422)}}}let g=/^\/api\/v1\/spend\/anomaly-configs\/([^/]+)$/.exec(o.pathname);if(g&&n==="DELETE"){let T=e.service.anomalyConfigs.get(decodeURIComponent(g[1]));if(!T||T.organizationId!==qe(t))throw new i("not_found","Anomaly config was not found.",404);return j(e,t,"billing:manage",T.projectId,T.environmentId),{data:{deleted:e.service.anomalyConfigs.delete(T.id)}}}if(o.pathname==="/api/v1/spend/anomaly-silences"){if(n==="GET"){let T=j(e,t,"billing:read",l,u);return{data:e.service.anomalyConfigs.listSilences({organizationId:T.organizationId,projectId:T.projectId,includeExpired:o.searchParams.get("includeExpired")==="true"})}}if(n==="POST"){let T=await r.body?.()??{},h=j(e,t,"billing:manage",T.projectId);try{return{data:e.service.anomalyConfigs.silence({organizationId:h.organizationId,projectId:T.projectId,signal:T.signal,routePattern:T.routePattern,statusCode:T.statusCode==null?void 0:Number(T.statusCode),reason:String(T.reason??""),expiresAt:T.expiresAt})}}catch(_){throw new i("validation_error",_ instanceof Error?_.message:String(_),422)}}}let m=/^\/api\/v1\/spend\/anomaly-silences\/([^/]+)$/.exec(o.pathname);if(m&&n==="DELETE")return j(e,t,"billing:manage",l),{data:{deleted:e.service.anomalyConfigs.removeSilence(decodeURIComponent(m[1]))}};if(n==="GET"&&o.pathname==="/api/v1/spend/enforcement"){let T=j(e,t,"billing:read",l,u);return{data:e.store.listEnforcements({organizationId:T.organizationId,activeOnly:o.searchParams.get("active")!=="false"})}}if(n==="GET"&&o.pathname==="/api/v1/spend/allowance"){let T=j(e,t,"billing:read",l,u),h=o.searchParams.get("operation")??"deploy";if(!["build","deploy","function_invoke","request"].includes(h))throw new i("validation_error","operation must be build, deploy, function_invoke, or request.",422);let N=e.store.listEnforcements({organizationId:T.organizationId,activeOnly:!0}).filter((I)=>(!I.projectId||I.projectId===T.projectId)&&(!I.environmentId||I.environmentId===T.environmentId)),y=Kc(h,N),v=e.store.budgetsForScope(T.organizationId,T.projectId,T.environmentId).map((I)=>e.service.status(I,a));return{operation:h,allowed:y.allowed,blockedBy:y.blockedBy??null,reason:y.reason??null,budgets:v.map((I)=>({id:I.budget.id,name:I.budget.name,usedPercent:I.decision.usedPercent,projectedPercent:I.decision.projectedPercent,level:I.decision.level,timeToCap:I.timeToCap}))}}return}function Xs(){let e=[{name:"projectId",in:"query",schema:{type:"string"}},{name:"environmentId",in:"query",schema:{type:"string"}}];return{"/api/v1/usage":{get:{summary:"Current usage, cost, and every budget governing the scope.",parameters:[...e,{name:"period",in:"query",schema:{type:"string",enum:["daily","weekly","monthly"]}},{name:"timezone",in:"query",schema:{type:"string"}}],responses:{"200":{description:"Usage totals, per-meter breakdown, hourly series, and budget status."}}}},"/api/v1/usage/rollups":{get:{summary:"Itemized hourly usage rollups.",parameters:[...e,{name:"from",in:"query",required:!0,schema:{type:"string",format:"date-time"}},{name:"to",in:"query",required:!0,schema:{type:"string",format:"date-time"}},{name:"meter",in:"query",schema:{type:"array",items:{type:"string"}}},{name:"limit",in:"query",schema:{type:"integer"}}],responses:{"200":{description:"Hourly rollups, newest first."}}}},"/api/v1/usage/focus":{get:{summary:"Usage and cost in FOCUS v1.3 format, newline-delimited JSON.",parameters:[...e,{name:"from",in:"query",required:!0,schema:{type:"string",format:"date-time"}},{name:"to",in:"query",required:!0,schema:{type:"string",format:"date-time"}},{name:"granularity",in:"query",schema:{type:"string",enum:["daily","hourly"]}}],responses:{"200":{description:"FOCUS records, one JSON object per line."}}}},"/api/v1/spend/budgets":{get:{summary:"Budgets governing a scope.",parameters:e,responses:{"200":{description:"Budgets."}}},post:{summary:"Create a budget. Starts in dry run unless dryRun is explicitly false.",responses:{"201":{description:"The created budget."},"422":{description:"Validation error."}}}},"/api/v1/spend/budgets/{budgetId}":{patch:{summary:"Update a budget. Pass expectedVersion for optimistic concurrency.",responses:{"200":{description:"The updated budget."},"409":{description:"Version conflict."}}},delete:{summary:"Delete a budget.",responses:{"200":{description:"Deletion result."}}}},"/api/v1/spend/anomalies":{get:{summary:"Detected spend anomalies.",parameters:[...e,{name:"since",in:"query",schema:{type:"string",format:"date-time"}},{name:"unacknowledged",in:"query",schema:{type:"boolean"}}],responses:{"200":{description:"Anomalies, newest first."}}}},"/api/v1/spend/anomalies/{anomalyId}/acknowledge":{post:{summary:"Acknowledge an anomaly.",responses:{"200":{description:"Acknowledgement result."}}}},"/api/v1/spend/signals":{get:{summary:"Signals anomaly detection can run on, with their gap and sample rules.",responses:{"200":{description:"Signal catalog."}}}},"/api/v1/spend/anomaly-configs":{get:{summary:"Anomaly detection configuration.",parameters:e,responses:{"200":{description:"Configs."}}},post:{summary:"Create or update the config for a signal.",responses:{"200":{description:"The config."}}}},"/api/v1/spend/anomaly-configs/{configId}":{delete:{summary:"Delete an anomaly config, returning the signal to its default.",responses:{"200":{description:"Result."}}}},"/api/v1/spend/anomaly-silences":{get:{summary:"Active anomaly silences.",parameters:e,responses:{"200":{description:"Silences."}}},post:{summary:"Silence a signal, route, or status code. A reason is required.",responses:{"200":{description:"The silence."}}}},"/api/v1/spend/anomaly-silences/{silenceId}":{delete:{summary:"Remove a silence.",responses:{"200":{description:"Result."}}}},"/api/v1/spend/enforcement":{get:{summary:"Enforcement actions in force.",parameters:[...e,{name:"active",in:"query",schema:{type:"boolean"}}],responses:{"200":{description:"Enforcement records."}}}},"/api/v1/spend/allowance":{get:{summary:"Whether an operation is allowed under current spend enforcement.",parameters:[...e,{name:"operation",in:"query",schema:{type:"string",enum:["build","deploy","function_invoke","request"]}}],responses:{"200":{description:"Allowance verdict and the budgets behind it."}}}}}}export{Fe,vc,de,Bt,Tc,w,_t,at,wc,Ds,zh,hp,Rc,s,ni,Ps,Cr,Dc,Pc,Er,Kh,Nc,Ry,Dy,Ns,Py,Ny,kc,Bc,ii,ks,X,c,Bs,Ue,br,Wh,Jh,_c,xt,Xh,_s,Yh,Zh,xs,xc,vr,Os,ef,Oc,fp,Ot,Tr,tf,Ls,rf,R,nf,Lc,Ap,$s,sf,of,af,$c,si,Ms,Mc,Lt,ct,cf,wr,df,Fc,yp,Ip,Fs,Uc,Qc,dt,Sp,oi,Hc,Us,Rr,Cp,ai,Gc,qc,ci,Ep,Vc,jc,zc,Kc,Qs,bp,vp,lf,Tp,Wc,di,wp,Rp,Hs,Dr,Gs,qs,Vs,Jc,Dp,Xc,js,uf,$t,pf,Yc,Pr,Zc,gf,ed,Pp,li,Nr,zs,ui,Qe,mf,Np,kp,Mt,td,rd,nd,pi,gi,mi,hf,ff,lt,Ks,Af,kr,Bp,Ws,yf,_p,xp,Op,If,Lp,$p,Sf,i,Cf,hi,Js,Xs};
|