@stacksjs/ts-cloud 0.16.39 → 0.16.41
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/ec2-launch.test.d.ts +1 -0
- package/dist/aws/ec2.d.ts +47 -0
- package/dist/aws/index.js +1 -1
- package/dist/bin/chunk-040x6j9v.js +1 -0
- package/dist/bin/chunk-2b9e10db.js +1 -0
- package/dist/bin/chunk-2tvtr5fy.js +1 -0
- package/dist/bin/{chunk-r0yapyqc.js → chunk-35x7z78g.js} +1 -1
- package/dist/bin/chunk-45a8yv3j.js +6 -0
- package/dist/bin/{chunk-4bp4k1x2.js → chunk-4azcshw6.js} +2 -2
- package/dist/bin/{chunk-55cckkb2.js → chunk-4yym8xm4.js} +5 -5
- package/dist/bin/chunk-5dqnj5n9.js +1 -0
- package/dist/bin/chunk-5khcwxhn.js +1 -0
- package/dist/bin/{chunk-zmp0mksb.js → chunk-5nmt4s5w.js} +2 -2
- package/dist/bin/{chunk-8zn63v9h.js → chunk-5wx26yjy.js} +3 -3
- package/dist/bin/chunk-6kt12934.js +1 -0
- package/dist/bin/{chunk-0ynfqf9t.js → chunk-7593hjcq.js} +1 -1
- package/dist/bin/chunk-7nsjehvx.js +1 -0
- package/dist/bin/{chunk-wga7gj0h.js → chunk-7p2va3nj.js} +1 -1
- package/dist/bin/chunk-89hvgp5e.js +1 -0
- package/dist/bin/{chunk-hjq05rxh.js → chunk-8e4ck7cg.js} +5 -5
- package/dist/bin/{chunk-sqmays54.js → chunk-9eqpnanr.js} +1 -1
- package/dist/bin/{chunk-d8x60kvn.js → chunk-a06d7cyt.js} +2 -2
- package/dist/bin/chunk-aptdpa3m.js +1 -0
- package/dist/bin/chunk-bb08ms5q.js +1 -0
- package/dist/bin/chunk-c23r6gjb.js +1 -0
- package/dist/bin/chunk-cxcgqqdb.js +1 -0
- package/dist/bin/{chunk-q8hp4dfy.js → chunk-ddwp5np9.js} +94 -94
- package/dist/bin/{chunk-dmwfnbg0.js → chunk-dkf2kcsc.js} +6 -6
- package/dist/bin/{chunk-85k5gvnc.js → chunk-e8jwnsee.js} +3 -3
- package/dist/bin/{chunk-aykdp1wv.js → chunk-eaet154r.js} +2 -2
- package/dist/bin/chunk-ecd4swb7.js +2 -0
- package/dist/bin/{chunk-gc8p1tdr.js → chunk-f64jvh96.js} +2 -2
- package/dist/bin/{chunk-0c1fv0xt.js → chunk-f7jpzyhr.js} +5 -5
- package/dist/bin/{chunk-4h60xsat.js → chunk-f8689v5g.js} +3 -3
- package/dist/bin/chunk-fhq31xzt.js +1 -0
- package/dist/bin/{chunk-c7z8et78.js → chunk-fkzp9sg5.js} +1 -1
- package/dist/bin/chunk-gj26v5hg.js +1 -0
- package/dist/bin/{chunk-5wqjqh6c.js → chunk-gn03w47w.js} +23 -23
- package/dist/bin/{chunk-48nz63ab.js → chunk-grwth4nw.js} +3 -3
- package/dist/bin/chunk-jrztbsnb.js +1 -0
- package/dist/bin/chunk-jv9qp13h.js +1 -0
- package/dist/bin/{chunk-cqhtnsby.js → chunk-k0p394bn.js} +5 -5
- package/dist/bin/{chunk-mbr9j2fw.js → chunk-k343q24p.js} +6 -6
- package/dist/bin/chunk-k9ate69x.js +1 -0
- package/dist/bin/chunk-kbwm0sqv.js +2 -0
- package/dist/bin/chunk-ky4xdskt.js +1 -0
- package/dist/bin/chunk-kzgt05w5.js +1 -0
- package/dist/bin/{chunk-x0ywfbk5.js → chunk-kzpzkdpd.js} +1 -1
- package/dist/bin/chunk-m8p7mw67.js +1 -0
- package/dist/bin/chunk-mh3rgn0e.js +1 -0
- package/dist/bin/{chunk-07qwk0sj.js → chunk-n7yefy09.js} +5 -5
- package/dist/bin/{chunk-pyr0dc6j.js → chunk-ndf3t76p.js} +63 -63
- package/dist/bin/{chunk-7rpj0qhb.js → chunk-nj9x0tb8.js} +2 -2
- package/dist/bin/{chunk-tt3m3fda.js → chunk-nmqjmx30.js} +22 -22
- package/dist/bin/{chunk-e0kapeev.js → chunk-p8xy9qm7.js} +14 -14
- package/dist/bin/chunk-p9baztvr.js +1 -0
- package/dist/bin/chunk-pf9dbm3b.js +4 -0
- package/dist/bin/{chunk-qxg95ndf.js → chunk-q40k9jvk.js} +2 -2
- package/dist/bin/chunk-qgqgdkg0.js +1 -0
- package/dist/bin/chunk-s64d5nw2.js +1 -0
- package/dist/bin/chunk-s77kny9g.js +1 -0
- package/dist/bin/{chunk-ygsdntxq.js → chunk-x6w8jvs1.js} +5 -5
- package/dist/bin/{chunk-ehnevjt4.js → chunk-xe9p2q8f.js} +99 -99
- package/dist/bin/{chunk-6r5mehaj.js → chunk-xq7ngz6q.js} +4 -4
- package/dist/bin/{chunk-w6yx9bhb.js → chunk-zvbc92pc.js} +1 -1
- package/dist/bin/cli.js +173 -173
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/{chunk-yrcv3hrj.js → chunk-0evxayn1.js} +7 -7
- package/dist/chunk-1yhrkahz.js +1 -0
- package/dist/chunk-27y037yh.js +1 -0
- package/dist/chunk-2ns1w1fe.js +1 -0
- package/dist/chunk-2vrv31sk.js +37 -0
- package/dist/{chunk-n1r9313b.js → chunk-3s8dtcz8.js} +2 -2
- package/dist/chunk-3w7q4sjs.js +2 -0
- package/dist/{chunk-tbn385ak.js → chunk-5n1y5ehd.js} +94 -94
- package/dist/chunk-74yycwrd.js +1 -0
- package/dist/{chunk-t52wetq8.js → chunk-7eaech9q.js} +1 -1
- package/dist/{chunk-2n4ktft4.js → chunk-97gre81w.js} +1 -1
- package/dist/{chunk-zvyrpmvd.js → chunk-9e4afej1.js} +1 -1
- package/dist/{chunk-3cyszqzh.js → chunk-9mv07nz0.js} +2 -2
- package/dist/{chunk-kpjhfgbh.js → chunk-bfbahave.js} +4 -4
- package/dist/{chunk-xr7ew64s.js → chunk-bwtxb2hf.js} +3 -3
- package/dist/{chunk-dg834141.js → chunk-cgcthvq9.js} +5 -5
- package/dist/{chunk-ffjgw5m6.js → chunk-ckqjqw4w.js} +108 -108
- package/dist/chunk-e9z4gzmg.js +1 -0
- package/dist/chunk-fwcf0n8f.js +4 -0
- package/dist/{chunk-q08s698e.js → chunk-jaswfk6g.js} +71 -71
- package/dist/{chunk-ffba3270.js → chunk-jbtnyhrh.js} +2 -2
- package/dist/{chunk-gcqq9m4b.js → chunk-kexwq2h0.js} +4 -4
- package/dist/{chunk-p4rknh9f.js → chunk-mxprxjd4.js} +1 -1
- package/dist/{chunk-c45ay9fx.js → chunk-my61jkg1.js} +5 -5
- package/dist/{chunk-kkeb1dk1.js → chunk-qbbap3bt.js} +1 -1
- package/dist/{chunk-jsnhb1p4.js → chunk-qg03hfb6.js} +19 -19
- package/dist/{chunk-bx3jmgd0.js → chunk-r3m1fjd4.js} +2 -2
- package/dist/{chunk-nzmangkw.js → chunk-v6hysd5c.js} +5 -5
- package/dist/{chunk-kyn6a4zf.js → chunk-varjr6np.js} +1 -1
- package/dist/chunk-vd2jqt9w.js +1 -0
- package/dist/{chunk-n8g8t8hf.js → chunk-w78e5n94.js} +3 -3
- package/dist/{chunk-0rvnerbw.js → chunk-ype3pqh5.js} +5 -5
- package/dist/{chunk-qhtgfjhd.js → chunk-yt6m703r.js} +23 -23
- package/dist/deploy/index.js +1 -1
- package/dist/dns/index.js +1 -1
- package/dist/drivers/index.js +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +42 -42
- package/dist/operations/index.js +1 -1
- package/dist/protection/index.js +1 -1
- package/dist/r2/index.d.ts +8 -0
- package/dist/r2/provider.d.ts +303 -0
- package/dist/r2/provider.test.d.ts +1 -0
- package/dist/r2/reconcile.d.ts +98 -0
- package/dist/r2/reconcile.test.d.ts +1 -0
- package/dist/r2/test-fetch.d.ts +32 -0
- package/dist/spend/index.js +1 -1
- package/dist/ui/404.html +1 -1
- package/dist/ui/accept-invitation.html +1 -1
- package/dist/ui/access-denied.html +1 -1
- package/dist/ui/account/automation.html +6 -6
- package/dist/ui/account/security.html +2 -2
- package/dist/ui/applications/compose.html +6 -6
- package/dist/ui/applications/new.html +2 -2
- package/dist/ui/data/backups.html +6 -6
- package/dist/ui/data/services.html +6 -6
- package/dist/ui/data/volumes.html +6 -6
- package/dist/ui/index.html +6 -6
- package/dist/ui/infrastructure/topology.html +5 -5
- package/dist/ui/integrations.html +2 -2
- package/dist/ui/operations/alerts.html +6 -6
- package/dist/ui/operations/configuration.html +6 -6
- package/dist/ui/operations/jobs.html +6 -6
- 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 +6 -6
- package/dist/ui/operations/spend.html +6 -6
- package/dist/ui/operations/workloads.html +6 -6
- package/dist/ui/security.html +2 -2
- package/dist/ui/server/actions.html +6 -6
- package/dist/ui/server/activity.html +2 -2
- package/dist/ui/server/capacity.html +5 -5
- package/dist/ui/server/database.html +6 -6
- package/dist/ui/server/deployments.html +6 -6
- package/dist/ui/server/diagnostics.html +2 -2
- package/dist/ui/server/firewall.html +6 -6
- package/dist/ui/server/fleet.html +6 -6
- package/dist/ui/server/logs.html +6 -6
- package/dist/ui/server/metrics.html +6 -6
- 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 +2 -2
- package/dist/ui/serverless/cost.html +2 -2
- package/dist/ui/serverless/data.html +6 -6
- package/dist/ui/serverless/deployments.html +2 -2
- package/dist/ui/serverless/firewall.html +1 -1
- package/dist/ui/serverless/functions.html +6 -6
- package/dist/ui/serverless/logs.html +6 -6
- package/dist/ui/serverless/metrics.html +1 -1
- package/dist/ui/serverless/queues.html +6 -6
- package/dist/ui/serverless/secrets.html +6 -6
- package/dist/ui/serverless/traces.html +5 -5
- package/dist/ui/serverless.html +6 -6
- package/package.json +3 -3
- package/dist/bin/chunk-0c5vn8rp.js +0 -1
- package/dist/bin/chunk-1wf1s8db.js +0 -1
- package/dist/bin/chunk-4dtrry0t.js +0 -1
- package/dist/bin/chunk-6kcxf3b2.js +0 -1
- package/dist/bin/chunk-6ksbfg6t.js +0 -1
- package/dist/bin/chunk-7rkg1yph.js +0 -1
- package/dist/bin/chunk-989j6ezd.js +0 -1
- package/dist/bin/chunk-bgdvhp6m.js +0 -1
- package/dist/bin/chunk-cvc9bxd4.js +0 -2
- package/dist/bin/chunk-czzrfhn7.js +0 -1
- package/dist/bin/chunk-d5arnf2f.js +0 -1
- package/dist/bin/chunk-dnmb3sr0.js +0 -4
- package/dist/bin/chunk-e06m9m6z.js +0 -1
- package/dist/bin/chunk-e51ajfyr.js +0 -1
- package/dist/bin/chunk-e6mfcw0v.js +0 -6
- package/dist/bin/chunk-fh5bjm3d.js +0 -1
- package/dist/bin/chunk-fw6hbyeg.js +0 -1
- package/dist/bin/chunk-h7gfd2yq.js +0 -1
- package/dist/bin/chunk-jxnw879g.js +0 -1
- package/dist/bin/chunk-k3yq569a.js +0 -1
- package/dist/bin/chunk-nhrwct94.js +0 -1
- package/dist/bin/chunk-pa4fymr0.js +0 -1
- package/dist/bin/chunk-s9xven24.js +0 -1
- package/dist/bin/chunk-w8jfw39t.js +0 -2
- package/dist/bin/chunk-wgv9nv0z.js +0 -1
- package/dist/bin/chunk-y5980ycr.js +0 -1
- package/dist/bin/chunk-y5ez6ba7.js +0 -1
- package/dist/bin/chunk-ya71t2ed.js +0 -1
- package/dist/bin/chunk-zb1nh252.js +0 -1
- package/dist/chunk-1ty76ybd.js +0 -1
- package/dist/chunk-2mypcz4a.js +0 -1
- package/dist/chunk-5vk7nss8.js +0 -2
- package/dist/chunk-fe5sbczg.js +0 -1
- package/dist/chunk-gtc1gvfj.js +0 -1
- package/dist/chunk-j1aq97br.js +0 -4
- package/dist/chunk-j5t1amn0.js +0 -1
- package/dist/chunk-s20830hg.js +0 -1
- package/dist/chunk-v83qx041.js +0 -37
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{L,d}from"./chunk-tbn385ak.js";import{jr}from"./chunk-yrcv3hrj.js";var cA=["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"],ro={"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}},dA=["notify","block_builds","block_deployments","throttle_requests","suspend_functions","serve_static","suspend_project"],N={notify:0,block_builds:1,block_deployments:2,throttle_requests:3,suspend_functions:4,serve_static:5,suspend_project:6};var lA=1e6;function yr(e){if(e.tiers&&e.tiers.length>0)return e.tiers;return[{upToQuantity:null,microCentsPerUnit:e.microCentsPerUnit??0}]}function od(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 bp(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 no(e,t,r=0){let n=bp(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=yr(n),m=od(l+E,g)-od(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 uA(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=no(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 gA(e){return Math.round(e*100)/100}function pA(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 Q=(e)=>Math.round(e*1e6),q=(e)=>Math.round(e*1e6),ad={currency:"USD",entries:[{meter:"edge.requests",provider:"aws",microCentsPerUnit:q(0.00075)},{meter:"edge.egress_gb",provider:"aws",includedQuantity:100,tiers:[{upToQuantity:10240,microCentsPerUnit:Q(8.5)},{upToQuantity:51200,microCentsPerUnit:Q(8)},{upToQuantity:null,microCentsPerUnit:Q(6)}]},{meter:"function.invocations",provider:"aws",includedQuantity:1e6,microCentsPerUnit:q(0.002)},{meter:"function.gb_seconds",provider:"aws",includedQuantity:400000,microCentsPerUnit:q(0.00166667)},{meter:"storage.gb_hours",provider:"aws",microCentsPerUnit:q(0.010958904109589041)},{meter:"object.egress_gb",provider:"aws",includedQuantity:100,microCentsPerUnit:Q(9)},{meter:"object.requests",provider:"aws",microCentsPerUnit:q(0.000039999999999999996)},{meter:"database.gb_hours",provider:"aws",microCentsPerUnit:q(0.015753424657534248)},{meter:"compute.instance_hours",provider:"aws",microCentsPerUnit:q(4.16)},{meter:"edge.egress_gb",provider:"hetzner",includedQuantity:20480,microCentsPerUnit:Q(0.108)},{meter:"object.egress_gb",provider:"hetzner",includedQuantity:1024,microCentsPerUnit:Q(0.108)},{meter:"compute.instance_hours",provider:"hetzner",microCentsPerUnit:q(0.95)},{meter:"storage.gb_hours",provider:"hetzner",microCentsPerUnit:q(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:q(0.8)},{meter:"telemetry.ingest_gb",provider:"*",includedQuantity:5,microCentsPerUnit:Q(50)},{meter:"image.transformations",provider:"*",includedQuantity:5000,microCentsPerUnit:q(0.05)}]};var Nt=new Map;function yt(e){let t=Nt.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"}),Nt.set(e,t);return t}var vr={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6};function Ei(e){try{return yt(e),!0}catch{return!1}}function io(e,t){let r=yt(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:vr[n("weekday")]??0}}function cd(e,t){let r=io(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 qt(e,t,r,n,o=0){let a=Date.UTC(t,r-1,n,o),l=new Date(a-cd(new Date(a),e));return new Date(a-cd(l,e))}function Ir(e,t){return new Date(Date.UTC(e,t-1,1)).toLocaleString("en-US",{month:"long",year:"numeric",timeZone:"UTC"})}function ft(e,t,r=new Date){let n=Ei(t)?t:"UTC",o=io(r,n),a,l,u;if(e==="daily")a=qt(n,o.year,o.month,o.day),l=qt(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=qt(n,o.year,o.month,o.day-g),l=qt(n,o.year,o.month,o.day-g+7);let m=io(a,n);u=`week of ${m.year}-${String(m.month).padStart(2,"0")}-${String(m.day).padStart(2,"0")}`}else a=qt(n,o.year,o.month,1),l=qt(n,o.year,o.month+1,1),u=Ir(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 mA(e,t,r=new Date){let n=ft(e,t,r),o=new Date(new Date(n.start).getTime()-1),a=ft(e,t,o);return{...a,elapsedMs:a.totalMs}}function Fr(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 fA(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 Sr}from"node:crypto";var he=1073741824,dd=[{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 br(e,t){return e.match.endsWith("*")?t.startsWith(e.match.slice(0,-1)):e.match===t}function Cp(e,t=dd){return t.find((r)=>!r.match.endsWith("*")&&r.match===e)??t.find((r)=>br(r,e))}function Rr(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 Ep(e,t){return Sr("sha256").update([t,e.meter,e.organizationId,e.projectId??"",e.environmentId??"",e.resourceId??"",e.timestamp].join("\x00")).digest("hex").slice(0,32)}class so{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 Lt(e,t){let r=e[t];return typeof r==="string"&&r.length>0?r:void 0}function ld(e,t,r={}){let n=r.mappings??dd,o=r.counters,a=[];for(let l of t){let u=Cp(l.name,n);if(!u)continue;let p=Rr(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:Lt(l.attributes,"provider")??r.defaultProvider,region:l.region??Lt(l.attributes,"region"),meter:u.meter,quantity:p,timestamp:l.timestamp,attributes:{source:l.source,signal:l.name}};a.push({...E,key:Ep(E,l.id)})}return a}function ud(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 Yr}from"node:crypto";var Ge=40,Kc=[{version:1,name:"core_control_plane",sql:`
|
|
1
|
+
import{L,d}from"./chunk-5n1y5ehd.js";import{Wr}from"./chunk-0evxayn1.js";var lA=["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"],io={"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}},uA=["notify","block_builds","block_deployments","throttle_requests","suspend_functions","serve_static","suspend_project"],N={notify:0,block_builds:1,block_deployments:2,throttle_requests:3,suspend_functions:4,serve_static:5,suspend_project:6};var gA=1e6;function fr(e){if(e.tiers&&e.tiers.length>0)return e.tiers;return[{upToQuantity:null,microCentsPerUnit:e.microCentsPerUnit??0}]}function cd(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 Ep(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 so(e,t,r=0){let n=Ep(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=fr(n),m=cd(l+E,g)-cd(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 pA(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=so(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 mA(e){return Math.round(e*100)/100}function fA(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 Q=(e)=>Math.round(e*1e6),q=(e)=>Math.round(e*1e6),dd={currency:"USD",entries:[{meter:"edge.requests",provider:"aws",microCentsPerUnit:q(0.00075)},{meter:"edge.egress_gb",provider:"aws",includedQuantity:100,tiers:[{upToQuantity:10240,microCentsPerUnit:Q(8.5)},{upToQuantity:51200,microCentsPerUnit:Q(8)},{upToQuantity:null,microCentsPerUnit:Q(6)}]},{meter:"function.invocations",provider:"aws",includedQuantity:1e6,microCentsPerUnit:q(0.002)},{meter:"function.gb_seconds",provider:"aws",includedQuantity:400000,microCentsPerUnit:q(0.00166667)},{meter:"storage.gb_hours",provider:"aws",microCentsPerUnit:q(0.010958904109589041)},{meter:"object.egress_gb",provider:"aws",includedQuantity:100,microCentsPerUnit:Q(9)},{meter:"object.requests",provider:"aws",microCentsPerUnit:q(0.000039999999999999996)},{meter:"database.gb_hours",provider:"aws",microCentsPerUnit:q(0.015753424657534248)},{meter:"compute.instance_hours",provider:"aws",microCentsPerUnit:q(4.16)},{meter:"edge.egress_gb",provider:"hetzner",includedQuantity:20480,microCentsPerUnit:Q(0.108)},{meter:"object.egress_gb",provider:"hetzner",includedQuantity:1024,microCentsPerUnit:Q(0.108)},{meter:"compute.instance_hours",provider:"hetzner",microCentsPerUnit:q(0.95)},{meter:"storage.gb_hours",provider:"hetzner",microCentsPerUnit:q(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:q(0.8)},{meter:"telemetry.ingest_gb",provider:"*",includedQuantity:5,microCentsPerUnit:Q(50)},{meter:"image.transformations",provider:"*",includedQuantity:5000,microCentsPerUnit:q(0.05)}]};var Nt=new Map;function yt(e){let t=Nt.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"}),Nt.set(e,t);return t}var yr={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6};function wi(e){try{return yt(e),!0}catch{return!1}}function oo(e,t){let r=yt(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:yr[n("weekday")]??0}}function ld(e,t){let r=oo(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 Kt(e,t,r,n,o=0){let a=Date.UTC(t,r-1,n,o),l=new Date(a-ld(new Date(a),e));return new Date(a-ld(l,e))}function Lr(e,t){return new Date(Date.UTC(e,t-1,1)).toLocaleString("en-US",{month:"long",year:"numeric",timeZone:"UTC"})}function ft(e,t,r=new Date){let n=wi(t)?t:"UTC",o=oo(r,n),a,l,u;if(e==="daily")a=Kt(n,o.year,o.month,o.day),l=Kt(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=Kt(n,o.year,o.month,o.day-g),l=Kt(n,o.year,o.month,o.day-g+7);let m=oo(a,n);u=`week of ${m.year}-${String(m.month).padStart(2,"0")}-${String(m.day).padStart(2,"0")}`}else a=Kt(n,o.year,o.month,1),l=Kt(n,o.year,o.month+1,1),u=Lr(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 hA(e,t,r=new Date){let n=ft(e,t,r),o=new Date(new Date(n.start).getTime()-1),a=ft(e,t,o);return{...a,elapsedMs:a.totalMs}}function Hr(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 AA(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 vr}from"node:crypto";var he=1073741824,ud=[{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 Ir(e,t){return e.match.endsWith("*")?t.startsWith(e.match.slice(0,-1)):e.match===t}function vp(e,t=ud){return t.find((r)=>!r.match.endsWith("*")&&r.match===e)??t.find((r)=>Ir(r,e))}function Sr(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 Tp(e,t){return vr("sha256").update([t,e.meter,e.organizationId,e.projectId??"",e.environmentId??"",e.resourceId??"",e.timestamp].join("\x00")).digest("hex").slice(0,32)}class ao{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 Lt(e,t){let r=e[t];return typeof r==="string"&&r.length>0?r:void 0}function gd(e,t,r={}){let n=r.mappings??ud,o=r.counters,a=[];for(let l of t){let u=vp(l.name,n);if(!u)continue;let p=Sr(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:Lt(l.attributes,"provider")??r.defaultProvider,region:l.region??Lt(l.attributes,"region"),meter:u.meter,quantity:p,timestamp:l.timestamp,attributes:{source:l.source,signal:l.name}};a.push({...E,key:Tp(E,l.id)})}return a}function pd(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 Kr}from"node:crypto";var Ge=40,Jc=[{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,26 +1475,26 @@ import{L,d}from"./chunk-tbn385ak.js";import{jr}from"./chunk-yrcv3hrj.js";var cA=
|
|
|
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
|
|
1479
|
-
[output truncated]`}function fe(e){return{id:String(e.id),slug:String(e.slug),name:String(e.name),description:R(e.description),organizationId:R(e.organization_id),desiredConfigHash:R(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:R(e.region),desiredState:M(e.desired_state),discoveredState:M(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:R(e.environment_id),kind:String(e.kind),slug:String(e.slug),name:String(e.name),provider:R(e.provider),providerId:R(e.provider_id),desiredState:M(e.desired_state),discoveredState:M(e.discovered_state),metadata:M(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:R(e.external_id),displayName:String(e.display_name),metadata:M(e.metadata),disabledAt:R(e.disabled_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Y(e){return{id:String(e.id),projectId:R(e.project_id),environmentId:R(e.environment_id),resourceId:R(e.resource_id),actorId:R(e.actor_id),kind:String(e.kind),state:String(e.state),correlationId:String(e.correlation_id),idempotencyKey:R(e.idempotency_key),input:M(e.input),output:M(e.output),error:R(e.error),attempt:Number(e.attempt),priority:Number(e.priority),leaseOwner:R(e.lease_owner),leaseExpiresAt:R(e.lease_expires_at),cancelRequestedAt:R(e.cancel_requested_at),startedAt:R(e.started_at),finishedAt:R(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:R(e.organization_id),projectId:R(e.project_id),operationId:R(e.operation_id),resourceId:R(e.resource_id),actorId:R(e.actor_id),correlationId:String(e.correlation_id),type:String(e.type),level:String(e.level),payload:M(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:M(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 Qe(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:Qe(e),source:String(e.source??"manual"),status:String(e.status),sessionVersion:Number(e.session_version),lastActiveAt:R(e.last_active_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function se(e,t){let r=R(e.accepted_at),n=R(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:Qe(e),invitedByActorId:R(e.invited_by_actor_id),acceptedByActorId:R(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:Qe(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
|
|
1478
|
+
`}];import{createHash as Ne,randomBytes as Rr}from"node:crypto";import{chmodSync as He,existsSync as vt,mkdirSync as Cr,statSync as Ar}from"node:fs";import{dirname as It}from"node:path";import{Database as Or}from"bun:sqlite";var me=["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"],ze=["project:read","config:read","deployments:read","runtime:read","runtime:logs","data:read","backups:read","security:read","sources:read","applications:read","billing:read"],br={owner:new Set(me),admin:new Set(me.filter((e)=>e!=="users:transfer-ownership")),deployer:new Set([...ze,"deployments:create","deployments:cancel","deployments:rollback","sources:manage","applications:manage"]),operator:new Set([...ze,"runtime:restart","backups:create","security:manage","sources:manage","applications:manage"]),viewer:new Set(ze),auditor:new Set(["project:read","config:read","deployments:read","runtime:read","data:read","backups:read","audit:read","security:read","sources:read","applications:read"])};function Vt(e){return br[e]}function Xc(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 P(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&&Xc(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(!Xc(t.scope,n))return{allowed:!1,reason:"scope-mismatch"};if(Vt(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 qt(e){return me.filter((t)=>P({...e,capability:t}).allowed)}class mt extends Error{constructor(e,t,r){super(`${e} ${t} changed since version ${r}`);this.name="OptimisticConcurrencyError"}}class Yc extends Error{constructor(e,t){super(`Operation cannot transition from ${e} to ${t}`);this.name="InvalidOperationTransitionError"}}class Js extends Error{constructor(e,t){super(`Control-plane schema version ${e} is newer than supported version ${t}`);this.name="UnsupportedSchemaVersionError"}}function rA(){return L("control-plane.sqlite")}var bp=65536,Zc=16384,Dr=["succeeded","failed","cancelled","timed_out"],wr={queued:["running","cancelled","timed_out"],running:["queued","succeeded","failed","cancelled","timed_out"],succeeded:[],failed:["queued"],cancelled:["queued"],timed_out:["queued"]},kr=/(?:^|_)(?:authorization|cookie|credential|password|passwd|secret|token|api_?key|private_?key|access_?key)(?:$|_)/i,St=/(?:authorization|password|secret|token|api[_-]?key|private[_-]?key|access[_-]?key)\s*[=:]\s*[^\s,;]+/gi;function M(e){if(typeof e!=="string")return{};try{return JSON.parse(e)}catch{return{}}}function R(e){return typeof e==="string"?e:void 0}function $e(e,t){if(t&&kr.test(t))return"[REDACTED]";if(e===null||typeof e==="boolean"||typeof e==="number")return e;if(typeof e==="string")return e.replace(St,"[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=bp){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 C(e){return JSON.stringify(s(e))}function Be(e){if(!e)return;let t=e.replace(St,"[REDACTED]");return Buffer.byteLength(t)<=Zc?t:`${t.slice(0,Zc-24)}
|
|
1479
|
+
[output truncated]`}function fe(e){return{id:String(e.id),slug:String(e.slug),name:String(e.name),description:R(e.description),organizationId:R(e.organization_id),desiredConfigHash:R(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:R(e.region),desiredState:M(e.desired_state),discoveredState:M(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:R(e.environment_id),kind:String(e.kind),slug:String(e.slug),name:String(e.name),provider:R(e.provider),providerId:R(e.provider_id),desiredState:M(e.desired_state),discoveredState:M(e.discovered_state),metadata:M(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:R(e.external_id),displayName:String(e.display_name),metadata:M(e.metadata),disabledAt:R(e.disabled_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Y(e){return{id:String(e.id),projectId:R(e.project_id),environmentId:R(e.environment_id),resourceId:R(e.resource_id),actorId:R(e.actor_id),kind:String(e.kind),state:String(e.state),correlationId:String(e.correlation_id),idempotencyKey:R(e.idempotency_key),input:M(e.input),output:M(e.output),error:R(e.error),attempt:Number(e.attempt),priority:Number(e.priority),leaseOwner:R(e.lease_owner),leaseExpiresAt:R(e.lease_expires_at),cancelRequestedAt:R(e.cancel_requested_at),startedAt:R(e.started_at),finishedAt:R(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:R(e.organization_id),projectId:R(e.project_id),operationId:R(e.operation_id),resourceId:R(e.resource_id),actorId:R(e.actor_id),correlationId:String(e.correlation_id),type:String(e.type),level:String(e.level),payload:M(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:M(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 Qe(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:Qe(e),source:String(e.source??"manual"),status:String(e.status),sessionVersion:Number(e.session_version),lastActiveAt:R(e.last_active_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function se(e,t){let r=R(e.accepted_at),n=R(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:Qe(e),invitedByActorId:R(e.invited_by_actor_id),acceptedByActorId:R(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:Qe(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 Xr(e){return Array.from({length:e},()=>"?").join(", ")}function y(e,t,r){return e.run(t,r)}class vi{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){Cr(It(this.path),{recursive:!0,mode:448});try{He(It(this.path),448)}catch{}}if(this.database=new Or(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(!vt(e))continue;try{He(e,384)}catch{}}}backupTo(e){this.database.run("VACUUM INTO ?",[e]);try{He(e,384)}catch{}}migrate(){let e=this.database.query("PRAGMA user_version").get(),t=Number(e?.user_version??0);if(t>Ge)throw new Js(t,Ge);if(t===Ge)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 Jc){if(o.version<=t)continue;this.database.run(o.sql),y(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 y(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 mt("Project",e,t);if(y(this.database,`UPDATE projects SET name = ?, description = ?, organization_id = ?, desired_config_hash = ?, version = version + 1, updated_at = ?
|
|
1480
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 mt("Project",e,t);return this.getProject(e)}createEnvironment(e){let t=e.id??this.idFn(),r=this.now();return y(this.database,`INSERT INTO environments (id, project_id, slug, name, kind, region, desired_state, discovered_state, created_at, updated_at)
|
|
1481
1481
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[t,e.projectId,e.slug,e.name,e.kind,e.region??null,C(e.desiredState??{}),C(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 y(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
1482
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[t,e.projectId,e.environmentId??null,e.kind,e.slug,e.name,e.provider??null,e.providerId??null,C(e.desiredState??{}),C(e.discoveredState??{}),C(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 mt("Resource",e,t);if(y(this.database,`UPDATE resources SET name = ?, provider = ?, provider_id = ?, desired_state = ?, discovered_state = ?, metadata = ?,
|
|
1483
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,C(r.desiredState??n.desiredState),C(r.discoveredState??n.discoveredState),C(r.metadata??n.metadata),this.now(),e,t]).changes!==1)throw new mt("Resource",e,t);return this.getResource(e)}createActor(e){let t=e.id??this.idFn(),r=this.now();return y(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,C(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 y(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
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:R(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();y(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 y(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 y(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();y(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=
|
|
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(y(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
|
|
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 y(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 y(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();y(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=Rr(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 y(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(y(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 Vt(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)y(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(!me.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 y(this.database,`INSERT INTO authorization_grants (id, organization_id, membership_id, effect, capability, scope_type, scope_id, source, created_at, updated_at)
|
|
1488
1488
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[a,e.organizationId,e.membershipId,e.effect,e.capability,r.type,r.id??null,e.source??"manual",n,n]),y(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=y(this.database,"DELETE FROM authorization_grants WHERE id = ?",[e]).changes===1;if(n)y(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 Y(o)}let t=e.id??this.idFn(),r=e.correlationId??this.idFn(),n=this.now();try{return this.transaction(()=>(y(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,C(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 Y(a)}throw o}}getOperation(e){let t=this.database.query("SELECT * FROM operations WHERE id = ?").get(e);return t?Y(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(Y)}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 (${
|
|
1489
|
+
VALUES (?, ?, ?, ?, ?, ?, 'queued', ?, ?, ?, '{}', ?, ?, ?)`,[t,e.projectId??null,e.environmentId??null,e.resourceId??null,e.actorId??null,e.kind,r,e.idempotencyKey??null,C(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 Y(a)}throw o}}getOperation(e){let t=this.database.query("SELECT * FROM operations WHERE id = ?").get(e);return t?Y(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(Y)}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 (${Xr(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=Y(u);if(y(this.database,`UPDATE operations SET state = 'running', attempt = attempt + 1, lease_owner = ?, lease_expires_at = ?,
|
|
1490
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(y(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 mt("Operation",e,n);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 mt("Operation",e,n);if(!wr[r.state].includes(t.to))throw new Yc(r.state,t.to);let o=this.now(),a=Dr.includes(t.to),l=t.to==="queued";if(y(this.database,`UPDATE operations SET state = ?, output = ?, error = ?, lease_owner = ?, lease_expires_at = ?,
|
|
1492
1492
|
finished_at = ?, updated_at = ?, version = version + 1 WHERE id = ? AND version = ?`,[t.to,C(t.output??r.output),Be(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 mt("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:Be(t.error)??null}}),this.getOperation(e)})}requestCancellation(e){let t=this.now();y(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(Y),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?R(this.database.query("SELECT organization_id FROM projects WHERE id = ?").get(e.projectId)?.organization_id):void 0);return y(this.database,`INSERT INTO events (id, organization_id, project_id, operation_id, resource_id, actor_id, correlation_id, type, level, payload, created_at)
|
|
1493
1493
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[t,n??null,e.projectId??null,e.operationId??null,e.resourceId??null,e.actorId??null,r,e.type,e.level??"info",C(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){y(this.database,`INSERT INTO settings (key, value, updated_at) VALUES (?, ?, ?)
|
|
1494
1494
|
ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`,[e,C(t),this.now()])}getSetting(e){let t=this.database.query("SELECT value FROM settings WHERE key = ?").get(e);return t?M(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 y(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 y(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");y(this.database,"INSERT OR IGNORE INTO resource_tags (resource_id, tag_id, created_at) VALUES (?, ?, ?)",[e,t,this.now()])}removeTag(e,t){y(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
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=C(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 y(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 y(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 y(this.database,"DELETE FROM saved_filters WHERE actor_key = ? AND id = ?",[e,t]).changes===1}recordNavigation(e,t,r){let n=this.now();return y(this.database,`INSERT INTO navigation_items (actor_key, entity_type, entity_id, last_visited_at) VALUES (?, ?, ?, ?)
|
|
1496
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 y(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=y(this.database,"DELETE FROM events WHERE created_at < ?",[t]).changes,a=y(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:Ge,integrity:this.integrityCheck(),journalMode:String(t?.journal_mode??"unknown"),databaseBytes:this.path!==":memory:"&&vt(this.path)?
|
|
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=y(this.database,"DELETE FROM events WHERE created_at < ?",[t]).changes,a=y(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:Ge,integrity:this.integrityCheck(),journalMode:String(t?.journal_mode??"unknown"),databaseBytes:this.path!==":memory:"&&vt(this.path)?Ar(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)]=M(t.value);return{format:"ts-cloud-control-plane",schemaVersion:Ge,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(Y),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>Ge)throw new Js(e.schemaVersion,Ge);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??[])y(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)y(this.database,`INSERT INTO projects (id, slug, name, description, organization_id, desired_config_hash, version, created_at, updated_at)
|
|
1498
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)y(this.database,`INSERT INTO environments (id, project_id, slug, name, kind, region, desired_state, discovered_state, version, created_at, updated_at)
|
|
1499
1499
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n.id,n.projectId,n.slug,n.name,n.kind,n.region??null,C(n.desiredState),C(n.discoveredState),n.version,n.createdAt,n.updatedAt]);for(let n of e.resources)y(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
1500
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n.id,n.projectId,n.environmentId??null,n.kind,n.slug,n.name,n.provider??null,n.providerId??null,C(n.desiredState),C(n.discoveredState),C(n.metadata),n.version,n.createdAt,n.updatedAt]);for(let n of e.actors)y(this.database,`INSERT INTO actors (id, kind, external_id, display_name, metadata, disabled_at, version, created_at, updated_at)
|
|
@@ -1504,15 +1504,15 @@ import{L,d}from"./chunk-tbn385ak.js";import{jr}from"./chunk-yrcv3hrj.js";var cA=
|
|
|
1504
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)y(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
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,C(n.input),C(n.output),Be(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)y(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,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 qr=new Set(["domain","domains","hostname","hostnames","url","repository","repo","image","label","labels"]),Br=new Set(["sha","commit","commitsha","release","releaseid"]);function bt(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 Ye(e){return e.toLowerCase().trim().replace(/[^a-z0-9._:/@-]+/g," ")}function We(e,t,r){let n=Ye(e),o=Ye(t),a=Ye(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 Kr(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 Ws(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)??[],_=bt(m.desiredState,qr),f=[m.name,m.slug,m.kind,m.provider,m.providerId,T?.slug,..._,...h.map((I)=>I.name)].filter(Boolean).join(" "),v=Kr(m,T?.slug??n[0]?.slug??"");u.push({type:v.type,id:m.id,title:m.name,subtitle:[m.kind,..._.slice(0,2)].join(" · "),href:v.href,environment:T?.slug,provider:m.provider,tags:h,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,h=bt(m.input,Br),_=m.kind.includes("deploy"),f=h[0]??m.kind,v=[m.kind,m.id,m.correlationId,m.state,...h].join(" ");u.push({type:_?"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,v)})}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 de=(e)=>{if(typeof e!=="string")return{};try{return JSON.parse(e)}catch{return{}}},H=(e)=>typeof e==="string"&&e!==""?e:void 0,Ae=(e)=>Number(e)===1,Rt=(e)=>e==null?void 0:Number(e);function Ct(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:H(e.project_id),environmentId:H(e.environment_id),name:String(e.name),period:String(e.period),timezone:String(e.timezone),currency:String(e.currency),softLimitCents:Rt(e.soft_limit_cents),hardLimitCents:Rt(e.hard_limit_cents),thresholds:de(e.thresholds),meters:de(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:H(e.project_id),environmentId:H(e.environment_id),action:String(e.action),state:String(e.state),reason:String(e.reason),restore:de(e.restore),triggeredAtPercent:Number(e.triggered_at_percent),simulated:Ae(e.simulated),appliedAt:H(e.applied_at),releasedAt:H(e.released_at),error:H(e.error),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Ot(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:H(e.project_id),environmentId:H(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:de(e.evidence),acknowledgedAt:H(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 ht(e,t,r){return[e,t??"",r??""].join("/")}var vp=[{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 vi{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??ad}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(!Ei(r))throw Error(`Unknown timezone: ${r}`);let n=(e.thresholds??[...vp]).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?Ct(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(Ct)}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&&!Ei(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,Fr(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=no(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)
|
|
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 Pr=new Set(["domain","domains","hostname","hostnames","url","repository","repo","image","label","labels"]),xr=new Set(["sha","commit","commitsha","release","releaseid"]);function bt(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 Ye(e){return e.toLowerCase().trim().replace(/[^a-z0-9._:/@-]+/g," ")}function We(e,t,r){let n=Ye(e),o=Ye(t),a=Ye(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 Br(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 Xs(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)??[],_=bt(m.desiredState,Pr),f=[m.name,m.slug,m.kind,m.provider,m.providerId,T?.slug,..._,...h.map((I)=>I.name)].filter(Boolean).join(" "),v=Br(m,T?.slug??n[0]?.slug??"");u.push({type:v.type,id:m.id,title:m.name,subtitle:[m.kind,..._.slice(0,2)].join(" · "),href:v.href,environment:T?.slug,provider:m.provider,tags:h,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,h=bt(m.input,xr),_=m.kind.includes("deploy"),f=h[0]??m.kind,v=[m.kind,m.id,m.correlationId,m.state,...h].join(" ");u.push({type:_?"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,v)})}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 de=(e)=>{if(typeof e!=="string")return{};try{return JSON.parse(e)}catch{return{}}},H=(e)=>typeof e==="string"&&e!==""?e:void 0,Ae=(e)=>Number(e)===1,Rt=(e)=>e==null?void 0:Number(e);function Ct(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:H(e.project_id),environmentId:H(e.environment_id),name:String(e.name),period:String(e.period),timezone:String(e.timezone),currency:String(e.currency),softLimitCents:Rt(e.soft_limit_cents),hardLimitCents:Rt(e.hard_limit_cents),thresholds:de(e.thresholds),meters:de(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:H(e.project_id),environmentId:H(e.environment_id),action:String(e.action),state:String(e.state),reason:String(e.reason),restore:de(e.restore),triggeredAtPercent:Number(e.triggered_at_percent),simulated:Ae(e.simulated),appliedAt:H(e.applied_at),releasedAt:H(e.released_at),error:H(e.error),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Ot(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:H(e.project_id),environmentId:H(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:de(e.evidence),acknowledgedAt:H(e.acknowledged_at),createdAt:String(e.created_at)}}function Yr(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 ht(e,t,r){return[e,t??"",r??""].join("/")}var wp=[{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 Ri{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??dd}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(!wi(r))throw Error(`Unknown timezone: ${r}`);let n=(e.thresholds??[...wp]).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?Ct(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(Ct)}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&&!wi(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,Hr(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=so(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,
|
|
1511
1511
|
cost_cents = cost_cents + excluded.cost_cents,
|
|
1512
1512
|
sample_count = sample_count + 1,
|
|
1513
|
-
updated_at = excluded.updated_at`,[l.organizationId,E.projectId,E.environmentId,E.resourceId,E.provider,E.region,l.meter,
|
|
1513
|
+
updated_at = excluded.updated_at`,[l.organizationId,E.projectId,E.environmentId,E.resourceId,E.provider,E.region,l.meter,Hr(l.timestamp),l.quantity,m.costCents,n]),t.applied++,t.costCents+=m.costCents}})(e),t.unpricedMeters=[...r],t}deltaFallbackKey(e){return Kr("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=ft("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=ft(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:de(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,ht(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?Ot(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(Ot)}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 Ut(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=Ut(e),n=1-Math.exp(-3*r),o=Math.min(1,t/6);return Math.round(n*o*100)/100}function gd(e){let t=e.window,r=Ut(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 oo(e,t){if(t==null)return 0;if(t<=0)return e>0?1/0:0;return e/t*100}function Ur(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 Tp=0.35;function Ti(e){return e.hardLimitCents??e.softLimitCents}function en(e,t,r){if(r.some((l)=>l!=="notify"))return"hard_capped";let o=Ti(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)=>N[t]-N[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 pd(e){let{budget:t,window:r}=e,n=e.now??new Date,o=Ti(t),a=gd({window:r,actualCents:e.actualCents,series:e.series,limitCents:o}),l=oo(e.actualCents,o),u=oo(a.projectedCents,o),p=t.graceSeconds*1000,E=p===0||e.breachingSince!=null&&n.getTime()-new Date(e.breachingSince).getTime()>=p,g=a.confidence>=Tp,m=[],T=new Set;for(let I of[...t.thresholds].sort((S,b)=>S.atPercent-b.atPercent)){let S=I.onProjection===!0,b=S?u:l;if(!(b>=I.atPercent))continue;let O=I.actions.filter((k)=>k!=="notify");if(S&&!g&&O.length>0)continue;m.push({atPercent:I.atPercent,actions:I.actions,projected:S,observedPercent:b});for(let k of I.actions){if(k!=="notify"&&!E)continue;T.add(k)}}let h=Oe(T),_=100-t.hysteresisPercent,f=Oe((e.activeActions??[]).filter((I)=>{if(T.has(I))return!1;let S=t.thresholds.filter((O)=>O.actions.includes(I)).reduce((O,k)=>O==null?k.atPercent:Math.min(O,k.atPercent),void 0);if(S==null)return!0;return Math.max(l,g?u:0)<=S*(_/100)})),v=en(t,l,h);return{budgetId:t.id,level:v,window:r,projection:a,usedPercent:l,projectedPercent:u,breaches:m,actions:t.dryRun?h.filter((I)=>I==="notify"):h,releases:f,simulated:t.dryRun,reason:tn(v,t,l,a,m),evaluatedAt:n.toISOString()}}function md(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 wi={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."},wp=["throttle_requests","suspend_functions","serve_static","suspend_project"],rn=["production"];function Dt(e,t,r){let n=wp.includes(e),o=r.approvalRequiredFor??rn,a=r.environmentKind!=null&&o.includes(r.environmentKind),l=r.maxAutomaticAction!=null&&N[e]>N[r.maxAutomaticAction];return{action:e,description:wi[e],userVisible:n,requiresApproval:l||n&&a,reason:t}}function fd(e,t={}){let r=e.actions.map((o)=>Dt(o,e.reason,t)),n=[...e.releases].sort((o,a)=>N[a]-N[o]).map((o)=>Dt(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 hd(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 Ad(e){return e.filter((t)=>t.state==="active").map((t)=>t.action).sort((t,r)=>N[r]-N[t])[0]}function yd(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:wi[o]};return{allowed:!0}}function ao(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 Rp(e,t){if(e.length===0)return 0;let r=t??ao(e);return 1.4826*ao(e.map((n)=>Math.abs(n-r)))}function Dp(e,t){let r=ao(t),n=Rp(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 hA(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 Pp(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:f}=Dp(T,m),v=h>=0?"spike":"drop";if(v==="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:v,deltaPercent:_===0?T===0?0:1/0:(T-_)/_*100,severity:Math.abs(h)>=o?"critical":"warning",historySize:m.length,deviation:f})}return{anomalies:p,warmingUp:E===0,evaluated:E}}function Sd(e,t={}){if(e.length===0)return;let r=Pp(e,t),n=e[e.length-1].bucketStart;return r.anomalies.find((o)=>o.bucketStart===n)}function Ri(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 Np={low:6,medium:3.5,high:2.5},G=(e)=>typeof e==="string"&&e!==""?e:void 0;function Ze(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:G(e.project_id),environmentId:G(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:G(e.project_id),signal:G(e.signal),routePattern:G(e.route_pattern),statusCode:e.status_code==null?void 0:Number(e.status_code),reason:String(e.reason),actorId:G(e.actor_id),expiresAt:G(e.expires_at),createdAt:String(e.created_at)}}function kp(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 co{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=ht(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=Ri(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=[ht(e.organizationId,e.projectId,e.environmentId),ht(e.organizationId,e.projectId),ht(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:{...Ri(t),threshold:Np[a.sensitivity],seasonLength:a.seasonLength,minAbsoluteDelta:a.minAbsoluteDelta,detectDrops:a.detectDrops}}}return{options:Ri(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,ht(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(!kp(r.routePattern,t.route))return!1}return!0})}}var Qr=[{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 lo(e){return Qr.find((t)=>t.key===e)}var ce=3600000;function sn(e,t=960){let r=Math.floor(new Date(e.from).getTime()/ce)*ce,n=new Date(e.to).getTime(),o=[];for(let a=r;a<n&&o.length<t;a+=ce)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 uo{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(Yr)}budgetSpendCents(e,t=new Date){let r=ft(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:de(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,ht(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?Ot(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(Ot)}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 Ut(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=Ut(e),n=1-Math.exp(-3*r),o=Math.min(1,t/6);return Math.round(n*o*100)/100}function md(e){let t=e.window,r=Ut(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 co(e,t){if(t==null)return 0;if(t<=0)return e>0?1/0:0;return e/t*100}function Gr(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 Rp=0.35;function Di(e){return e.hardLimitCents??e.softLimitCents}function en(e,t,r){if(r.some((l)=>l!=="notify"))return"hard_capped";let o=Di(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)=>N[t]-N[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 fd(e){let{budget:t,window:r}=e,n=e.now??new Date,o=Di(t),a=md({window:r,actualCents:e.actualCents,series:e.series,limitCents:o}),l=co(e.actualCents,o),u=co(a.projectedCents,o),p=t.graceSeconds*1000,E=p===0||e.breachingSince!=null&&n.getTime()-new Date(e.breachingSince).getTime()>=p,g=a.confidence>=Rp,m=[],T=new Set;for(let I of[...t.thresholds].sort((S,b)=>S.atPercent-b.atPercent)){let S=I.onProjection===!0,b=S?u:l;if(!(b>=I.atPercent))continue;let O=I.actions.filter((k)=>k!=="notify");if(S&&!g&&O.length>0)continue;m.push({atPercent:I.atPercent,actions:I.actions,projected:S,observedPercent:b});for(let k of I.actions){if(k!=="notify"&&!E)continue;T.add(k)}}let h=Oe(T),_=100-t.hysteresisPercent,f=Oe((e.activeActions??[]).filter((I)=>{if(T.has(I))return!1;let S=t.thresholds.filter((O)=>O.actions.includes(I)).reduce((O,k)=>O==null?k.atPercent:Math.min(O,k.atPercent),void 0);if(S==null)return!0;return Math.max(l,g?u:0)<=S*(_/100)})),v=en(t,l,h);return{budgetId:t.id,level:v,window:r,projection:a,usedPercent:l,projectedPercent:u,breaches:m,actions:t.dryRun?h.filter((I)=>I==="notify"):h,releases:f,simulated:t.dryRun,reason:tn(v,t,l,a,m),evaluatedAt:n.toISOString()}}function hd(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 Pi={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."},Dp=["throttle_requests","suspend_functions","serve_static","suspend_project"],rn=["production"];function Dt(e,t,r){let n=Dp.includes(e),o=r.approvalRequiredFor??rn,a=r.environmentKind!=null&&o.includes(r.environmentKind),l=r.maxAutomaticAction!=null&&N[e]>N[r.maxAutomaticAction];return{action:e,description:Pi[e],userVisible:n,requiresApproval:l||n&&a,reason:t}}function Ad(e,t={}){let r=e.actions.map((o)=>Dt(o,e.reason,t)),n=[...e.releases].sort((o,a)=>N[a]-N[o]).map((o)=>Dt(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 yd(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 Sd(e){return e.filter((t)=>t.state==="active").map((t)=>t.action).sort((t,r)=>N[r]-N[t])[0]}function Id(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:Pi[o]};return{allowed:!0}}function lo(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 Pp(e,t){if(e.length===0)return 0;let r=t??lo(e);return 1.4826*lo(e.map((n)=>Math.abs(n-r)))}function Np(e,t){let r=lo(t),n=Pp(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 yA(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 kp(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:f}=Np(T,m),v=h>=0?"spike":"drop";if(v==="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:v,deltaPercent:_===0?T===0?0:1/0:(T-_)/_*100,severity:Math.abs(h)>=o?"critical":"warning",historySize:m.length,deviation:f})}return{anomalies:p,warmingUp:E===0,evaluated:E}}function bd(e,t={}){if(e.length===0)return;let r=kp(e,t),n=e[e.length-1].bucketStart;return r.anomalies.find((o)=>o.bucketStart===n)}function Ni(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 Bp={low:6,medium:3.5,high:2.5},G=(e)=>typeof e==="string"&&e!==""?e:void 0;function Ze(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:G(e.project_id),environmentId:G(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:G(e.project_id),signal:G(e.signal),routePattern:G(e.route_pattern),statusCode:e.status_code==null?void 0:Number(e.status_code),reason:String(e.reason),actorId:G(e.actor_id),expiresAt:G(e.expires_at),createdAt:String(e.created_at)}}function xp(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 uo{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=ht(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=Ni(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=[ht(e.organizationId,e.projectId,e.environmentId),ht(e.organizationId,e.projectId),ht(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:{...Ni(t),threshold:Bp[a.sensitivity],seasonLength:a.seasonLength,minAbsoluteDelta:a.minAbsoluteDelta,detectDrops:a.detectDrops}}}return{options:Ni(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,ht(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(!xp(r.routePattern,t.route))return!1}return!0})}}var Vr=[{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 go(e){return Vr.find((t)=>t.key===e)}var ce=3600000;function sn(e,t=960){let r=Math.floor(new Date(e.from).getTime()/ce)*ce,n=new Date(e.to).getTime(),o=[];for(let a=r;a<n&&o.length<t;a+=ce)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 po{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{L,d}from"./chunk-tbn385ak.js";import{jr}from"./chunk-yrcv3hrj.js";var cA=
|
|
|
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)*ce,{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)*ce,{value:Number(u.value),samples:Number(u.samples)});return et(e,r,l)}series(e,t,r){let n=go(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 mo(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 Cd(e){let t=mo(e),r=t.seasonLength*(t.minHistory+1);return Math.min(960,Math.max(336,r))}var Op="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 wt(e){return io[e]?.label??e}function kt(e){let t=io[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 Ed(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:Op,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:`${wt(a.meter)} on ${g}`,ProviderName:g,PublisherName:g,InvoiceIssuerName:g,ServiceName:wt(a.meter),ServiceCategory:an(String(a.meter)),SkuId:String(a.meter),PricingUnit:kt(String(a.meter)),PricingQuantity:l,ConsumedQuantity:l,ConsumedUnit:kt(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 fo(e){return e.map((t)=>JSON.stringify(t)).join(`
|
|
1539
1539
|
`)+(e.length>0?`
|
|
1540
|
-
`:"")}function*AA(e,t=500){for(let r=0;r<e.length;r+=t)yield po(e.slice(r,r+t))}class jt{store;counters=new so;breaching=new Map;anomalyConfigs;signals;constructor(e){this.store=e;this.anomalyConfigs=new co(e.controlPlane),this.signals=new uo(e.controlPlane,e)}ingestTelemetry(e,t,r){let n=ld(e,t,{counters:this.counters,defaultProvider:r});return this.store.ingestUsage(n)}ingestUsage(e,t=!0){return this.store.ingestUsage(t?ud(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=pd({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:Ur(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=md(n.map((l)=>l.decision));if(e.handlers){let l={environmentKind:e.environmentKind,...e.policy};for(let u of n){let p=fd(u.decision,l);if(p.apply.length===0&&p.release.length===0&&p.withheld.length===0)continue;o.push(await hd(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??Qr.map((p)=>p.key),l=[],u;for(let p of a){let E=r.seasonLength?Math.max(336,r.seasonLength*((r.minHistory??3)+1)):Id(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(!lo(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=Sd(l.points,{...go(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=ft(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=Ti(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:Ad(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:Fr(t)}}}function yA(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 Cd="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 Ue(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 Hr{controlPlane;options;constructor(e,t={}){this.controlPlane=e;this.options=t}read(){let e=this.controlPlane.getSetting(Cd);return Array.isArray(e)?e:[]}write(e){this.controlPlane.setSetting(Cd,e)}list(e){return this.read().filter((t)=>!e||pn(t,e)).sort((t,r)=>N[r.action]-N[t.action])}listUnder(e){return this.read().filter((t)=>En(t,e)).sort((t,r)=>N[r.action]-N[t.action])}open(e){let t=e.appliedAt??(this.options.now?.()??new Date).toISOString(),r=mn({...e,appliedAt:t}),n=this.read().filter((o)=>Ue(o)!==Ue(r));return n.push(r),this.write(n),r}close(e,t){let r=this.read(),n=r.filter((o)=>Ue(o)!==Ue({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} ${wi[n.action]}`}}return{allowed:!0}}strongest(e){return this.list(e).find((t)=>!t.simulated)?.action}}class Ed 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 SA(e,t,r){let n=e.check(t,r);if(!n.allowed)throw new Ed(t,n)}var Xt=["notify","block_builds","block_deployments"];function vd(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&&!Xt.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&&!Xt.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 xp{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 $t,randomBytes as _n}from"node:crypto";var F=(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,B=(e,t,r,n)=>{let o=Number(e);return Number.isFinite(o)?Math.min(n,Math.max(r,Math.floor(o))):t},Pt=(e)=>$t("sha256").update(e).digest("hex").slice(0,16);function xt(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:F(e.config),intervalSeconds:Number(e.interval_seconds),timeoutSeconds:Number(e.timeout_seconds),failureThreshold:Number(e.failure_threshold),recoveryThreshold:Number(e.recovery_threshold),regions:F(e.regions),enabled:nt(e.enabled),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Ft(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:F(e.timings),checkedAt:String(e.checked_at)}}function Mt(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:F(e.group_by),labels:F(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:F(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 Bt(e){return{id:String(e.id),organizationId:String(e.organization_id),name:String(e.name),kind:String(e.kind),config:F(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 Kt(e){return{id:String(e.id),organizationId:String(e.organization_id),name:String(e.name),priority:Number(e.priority),matcher:F(e.matcher),channelIds:F(e.channel_ids),quietHours:e.quiet_hours?F(e.quiet_hours):void 0,groupWaitSeconds:Number(e.group_wait_seconds),reminderSeconds:e.reminder_seconds==null?void 0:Number(e.reminder_seconds),escalation:F(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:F(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=$t("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),B(e.intervalSeconds,60,10,86400),B(e.timeoutSeconds,10,1,300),B(e.failureThreshold,3,1,100),B(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?xt(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(xt)}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]),Ft(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(Ft)}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,B(e.windowMs,300000,1e4,2678400000),B(e.consecutive,3,1,100),B(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?Mt(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(Mt)}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=F(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?Pt(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?Bt(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(Bt)}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),Pt(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,B(e.groupWaitSeconds,30,0,86400),e.reminderSeconds??null,JSON.stringify(e.escalation),e.template?.trim().slice(0,2000)??null,B(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?Kt(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(Kt)}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,B(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 Gr{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,v=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:v,severity:e.severity,title:e.name,evidence:g,failureCount:f,recoveryCount:0,occurrenceCount:1,firstSeenAt:E,lastSeenAt:E,firingAt:v==="firing"?E:void 0,updatedAt:E}}else if(u||p){let f=o.state==="resolved",v=(f?0:o.failureCount)+1,I=o.silencedUntil&&new Date(o.silencedUntil)>new Date(E),S=p?"pending":v>=e.consecutive?"firing":"pending";if((I||this.store.isSilenced(e,r.values,E))&&S==="firing")S="silenced";m={...o,state:S,severity:e.severity,title:e.name,evidence:g,failureCount:v,recoveryCount:0,occurrenceCount:o.occurrenceCount+1,firstSeenAt:f?E:o.firstSeenAt,lastSeenAt:E,firingAt:S==="firing"||S==="silenced"?o.firingAt??E:void 0,resolvedAt:void 0,updatedAt:E}}else{let f=o.recoveryCount+1,v=f>=e.recoveryConsecutive;m={...o,state:v?"resolved":o.state,evidence:g,failureCount:v?0:o.failureCount,recoveryCount:f,lastSeenAt:E,resolvedAt:v?E:o.resolvedAt,silencedUntil:v?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 Yt(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 mo(e,t){if(!e.quietHours)return!1;let r=In(t,e.quietHours.timezone),n=Yt(e.quietHours.start),o=Yt(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 Pi{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:mo(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*SA(e,t=500){for(let r=0;r<e.length;r+=t)yield fo(e.slice(r,r+t))}class Wt{store;counters=new ao;breaching=new Map;anomalyConfigs;signals;constructor(e){this.store=e;this.anomalyConfigs=new uo(e.controlPlane),this.signals=new po(e.controlPlane,e)}ingestTelemetry(e,t,r){let n=gd(e,t,{counters:this.counters,defaultProvider:r});return this.store.ingestUsage(n)}ingestUsage(e,t=!0){return this.store.ingestUsage(t?pd(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=fd({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:Gr(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=hd(n.map((l)=>l.decision));if(e.handlers){let l={environmentKind:e.environmentKind,...e.policy};for(let u of n){let p=Ad(u.decision,l);if(p.apply.length===0&&p.release.length===0&&p.withheld.length===0)continue;o.push(await yd(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??Vr.map((p)=>p.key),l=[],u;for(let p of a){let E=r.seasonLength?Math.max(336,r.seasonLength*((r.minHistory??3)+1)):Cd(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(!go(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=bd(l.points,{...mo(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=ft(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=Di(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:Sd(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:Hr(t)}}}function IA(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 vd="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 Ue(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 qr{controlPlane;options;constructor(e,t={}){this.controlPlane=e;this.options=t}read(){let e=this.controlPlane.getSetting(vd);return Array.isArray(e)?e:[]}write(e){this.controlPlane.setSetting(vd,e)}list(e){return this.read().filter((t)=>!e||pn(t,e)).sort((t,r)=>N[r.action]-N[t.action])}listUnder(e){return this.read().filter((t)=>En(t,e)).sort((t,r)=>N[r.action]-N[t.action])}open(e){let t=e.appliedAt??(this.options.now?.()??new Date).toISOString(),r=mn({...e,appliedAt:t}),n=this.read().filter((o)=>Ue(o)!==Ue(r));return n.push(r),this.write(n),r}close(e,t){let r=this.read(),n=r.filter((o)=>Ue(o)!==Ue({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} ${Pi[n.action]}`}}return{allowed:!0}}strongest(e){return this.list(e).find((t)=>!t.simulated)?.action}}class Td 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 bA(e,t,r){let n=e.check(t,r);if(!n.allowed)throw new Td(t,n)}var Xt=["notify","block_builds","block_deployments"];function wd(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&&!Xt.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&&!Xt.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 _p{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 $t,randomBytes as _n}from"node:crypto";var F=(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,B=(e,t,r,n)=>{let o=Number(e);return Number.isFinite(o)?Math.min(n,Math.max(r,Math.floor(o))):t},Pt=(e)=>$t("sha256").update(e).digest("hex").slice(0,16);function xt(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:F(e.config),intervalSeconds:Number(e.interval_seconds),timeoutSeconds:Number(e.timeout_seconds),failureThreshold:Number(e.failure_threshold),recoveryThreshold:Number(e.recovery_threshold),regions:F(e.regions),enabled:nt(e.enabled),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Ft(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:F(e.timings),checkedAt:String(e.checked_at)}}function Mt(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:F(e.group_by),labels:F(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:F(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 Ht(e){return{id:String(e.id),organizationId:String(e.organization_id),name:String(e.name),kind:String(e.kind),config:F(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 Bt(e){return{id:String(e.id),organizationId:String(e.organization_id),name:String(e.name),priority:Number(e.priority),matcher:F(e.matcher),channelIds:F(e.channel_ids),quietHours:e.quiet_hours?F(e.quiet_hours):void 0,groupWaitSeconds:Number(e.group_wait_seconds),reminderSeconds:e.reminder_seconds==null?void 0:Number(e.reminder_seconds),escalation:F(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:F(e.payload),createdAt:String(e.created_at),updatedAt:String(e.updated_at),deliveredAt:A(e.delivered_at)}}class ki{controlPlane;options;key;constructor(e,t){this.controlPlane=e;this.options=t;this.key=$t("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),B(e.intervalSeconds,60,10,86400),B(e.timeoutSeconds,10,1,300),B(e.failureThreshold,3,1,100),B(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?xt(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(xt)}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]),Ft(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(Ft)}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,B(e.windowMs,300000,1e4,2678400000),B(e.consecutive,3,1,100),B(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?Mt(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(Mt)}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=F(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?Pt(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?Ht(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(Ht)}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),Pt(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,B(e.groupWaitSeconds,30,0,86400),e.reminderSeconds??null,JSON.stringify(e.escalation),e.template?.trim().slice(0,2000)??null,B(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?Bt(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(Bt)}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,B(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 jr{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,v=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:v,severity:e.severity,title:e.name,evidence:g,failureCount:f,recoveryCount:0,occurrenceCount:1,firstSeenAt:E,lastSeenAt:E,firingAt:v==="firing"?E:void 0,updatedAt:E}}else if(u||p){let f=o.state==="resolved",v=(f?0:o.failureCount)+1,I=o.silencedUntil&&new Date(o.silencedUntil)>new Date(E),S=p?"pending":v>=e.consecutive?"firing":"pending";if((I||this.store.isSilenced(e,r.values,E))&&S==="firing")S="silenced";m={...o,state:S,severity:e.severity,title:e.name,evidence:g,failureCount:v,recoveryCount:0,occurrenceCount:o.occurrenceCount+1,firstSeenAt:f?E:o.firstSeenAt,lastSeenAt:E,firingAt:S==="firing"||S==="silenced"?o.firingAt??E:void 0,resolvedAt:void 0,updatedAt:E}}else{let f=o.recoveryCount+1,v=f>=e.recoveryConsecutive;m={...o,state:v?"resolved":o.state,evidence:g,failureCount:v?0:o.failureCount,recoveryCount:f,lastSeenAt:E,resolvedAt:v?E:o.resolvedAt,silencedUntil:v?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 Qt(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 ho(e,t){if(!e.quietHours)return!1;let r=In(t,e.quietHours.timezone),n=Qt(e.quietHours.start),o=Qt(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 Bi{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:ho(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"}),h=performance.now()-m,_=e.config.expectedBody?await T.text():"",f=e.config.expectedStatuses??[200,201,202,204],v=f.includes(T.status)&&(!e.config.expectedBody||_.includes(e.config.expectedBody));return{checkId:e.id,status:v?"healthy":"unhealthy",agent:n,region:this.options.region,statusCode:T.status,message:v?void 0:`Expected ${f.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 Gr(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 IA=Object.freeze({rawDays:30,downsampleAfterDays:7,downsampleBucketMs:3600000,maxRecords:1e6,samplingRate:1,collectLogs:!0,collectTraces:!0,collectRequestAnalytics:!0,estimatedStorageUsdPerGbMonth:0});function De(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 Op(e,t={...IA}){let r=e&&typeof e==="object"&&!Array.isArray(e)?e:{},n=De(r.rawDays,t.rawDays,1,3650),o=De(r.downsampleAfterDays,t.downsampleAfterDays,1,n);return{rawDays:n,downsampleAfterDays:o,downsampleBucketMs:De(r.downsampleBucketMs,t.downsampleBucketMs,60000,86400000),maxRecords:De(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 _p(e){return`telemetry.policy:${e}`}function zt(e,t){return Op(e.getSetting(_p(t)))}function Td(e,t,r){let n=Op(r,zt(e,t));return e.setSetting(_p(t),n),n}function wd(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 Rd(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 Ni(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 Rd(e,t);if(Array.isArray(e))return e.map((n)=>Ni(n,t));if(e&&typeof e==="object"){let n={};for(let[o,a]of Object.entries(e))n[o]=Ni(a,t,o);return n}return String(e??"")}function ki(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 le(e){return e==null?void 0:Number(e)}function xn(e){if(typeof e!=="string")return{};try{return JSON.parse(e)}catch{return{}}}function we(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:le(e.value),unit:X(e.unit),level:X(e.level),message:X(e.message),durationMs:le(e.duration_ms),statusCode:le(e.status_code),method:X(e.method),host:X(e.host),pathTemplate:X(e.path_template),bytesIn:le(e.bytes_in),bytesOut:le(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 J(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 ke(e){let t=J(e.from,"from"),r=J(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 Bi(e){return e?Buffer.from(JSON.stringify({timestamp:e.timestamp,id:e.id})).toString("base64url"):void 0}function bA(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 ue(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 bA(e,Number(t.slice(1)))}function CA(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 At{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=J(e.timestamp,"timestamp").toISOString(),r=e.observedAt?J(e.observedAt,"observedAt").toISOString():this.now().toISOString(),n=Ni(e.attributes??{},this.options.redaction),o=e.message?Rd(e.message,this.options.redaction).slice(0,32768):void 0,a=ki(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?we(t):void 0}query(e){let{from:t,to:r}=ke(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=(I,S)=>{if(S)o.push(`${I}=?`),a.push(S)},u=(I,S)=>{let b=[...new Set(S??[])].slice(0,100);if(b.length)o.push(`${I} IN (${b.map(()=>"?").join(",")})`),a.push(...b)};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(we),m=E.length>n,T=new Map;for(let I of g)T.set(I.source,[...T.get(I.source)??[],I]);let h=this.now().getTime(),_=[...T].map(([I,S])=>{let b=S.reduce((k,U)=>U.observedAt>k?U.observedAt:k,S[0].observedAt),O=h-new Date(b).getTime();return{source:I,latestAt:b,freshness:O<=120000?"live":O<=600000?"stale":"unavailable",count:S.length}}),f=Math.max(60000,(r.getTime()-t.getTime())/100),v=[...T].flatMap(([I,S])=>{let b=[...new Set(S.map((O)=>new Date(O.timestamp).getTime()))].sort((O,k)=>O-k);return b.slice(1).flatMap((O,k)=>O-b[k]>f?[{from:new Date(b[k]).toISOString(),to:new Date(O).toISOString(),source:I}]:[])});return{records:g,nextCursor:m?Bi(g.at(-1)):void 0,truncated:m,scannedRange:{from:t.toISOString(),to:r.toISOString()},sources:_,gaps:v}}tail(e,t){let{from:r,to:n}=ke(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(we);return{records:m,cursor:Bi(m.at(-1))??t,truncated:g.length>o}}series(e){let{from:t,to:r}=ke(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)??[],_=ue(h,e.aggregation);m.push({timestamp:new Date(T).toISOString(),label:CA(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,J(e.compareFrom,"compareFrom"),J(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(ke(n),n.projectId!==e)throw Error("Saved telemetry queries cannot cross project scope.");let a=this.now().toISOString(),l=JSON.stringify(Ni(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(we),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,_,f,v,I]=JSON.parse(E),S=g.flatMap((b)=>b.value==null?[]:[b.value]);this.append({projectId:m,environmentId:T||void 0,resourceId:h||void 0,kind:"metric",source:`${_}:rollup`,name:f,unit:v||void 0,timestamp:new Date(I).toISOString(),value:ue(S,"avg"),attributes:{downsampled:!0,count:S.length,min:ue(S,"min"),max:ue(S,"max"),p95:ue(S,"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():"",f=e.config.expectedStatuses??[200,201,202,204],v=f.includes(T.status)&&(!e.config.expectedBody||_.includes(e.config.expectedBody));return{checkId:e.id,status:v?"healthy":"unhealthy",agent:n,region:this.options.region,statusCode:T.status,message:v?void 0:`Expected ${f.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 jr(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 CA=Object.freeze({rawDays:30,downsampleAfterDays:7,downsampleBucketMs:3600000,maxRecords:1e6,samplingRate:1,collectLogs:!0,collectTraces:!0,collectRequestAnalytics:!0,estimatedStorageUsdPerGbMonth:0});function De(e,t,r,n){let o=Number(e);return Number.isFinite(o)?Math.min(n,Math.max(r,Math.floor(o))):t}function Yt(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 Lp(e,t={...CA}){let r=e&&typeof e==="object"&&!Array.isArray(e)?e:{},n=De(r.rawDays,t.rawDays,1,3650),o=De(r.downsampleAfterDays,t.downsampleAfterDays,1,n);return{rawDays:n,downsampleAfterDays:o,downsampleBucketMs:De(r.downsampleBucketMs,t.downsampleBucketMs,60000,86400000),maxRecords:De(r.maxRecords,t.maxRecords,1000,1e8),samplingRate:Yt(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:Yt(r.estimatedStorageUsdPerGbMonth,t.estimatedStorageUsdPerGbMonth,0,1e4)}}function $p(e){return`telemetry.policy:${e}`}function Jt(e,t){return Lp(e.getSetting($p(t)))}function Rd(e,t,r){let n=Lp(r,Jt(e,t));return e.setSetting($p(t),n),n}function Dd(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 Pd(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 xi(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 Pd(e,t);if(Array.isArray(e))return e.map((n)=>xi(n,t));if(e&&typeof e==="object"){let n={};for(let[o,a]of Object.entries(e))n[o]=xi(a,t,o);return n}return String(e??"")}function Oi(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 Gt=65536,Xn=2678400000,Pn=new Set(["metric","log","trace","request","event"]);function X(e){return typeof e==="string"?e:void 0}function le(e){return e==null?void 0:Number(e)}function xn(e){if(typeof e!=="string")return{};try{return JSON.parse(e)}catch{return{}}}function we(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:le(e.value),unit:X(e.unit),level:X(e.level),message:X(e.message),durationMs:le(e.duration_ms),statusCode:le(e.status_code),method:X(e.method),host:X(e.host),pathTemplate:X(e.path_template),bytesIn:le(e.bytes_in),bytesOut:le(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 J(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 ke(e){let t=J(e.from,"from"),r=J(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 _i(e){return e?Buffer.from(JSON.stringify({timestamp:e.timestamp,id:e.id})).toString("base64url"):void 0}function EA(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 ue(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 EA(e,Number(t.slice(1)))}function vA(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 At{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=J(e.timestamp,"timestamp").toISOString(),r=e.observedAt?J(e.observedAt,"observedAt").toISOString():this.now().toISOString(),n=xi(e.attributes??{},this.options.redaction),o=e.message?Pd(e.message,this.options.redaction).slice(0,32768):void 0,a=Oi(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>Gt)throw Error(`Telemetry records are limited to ${Gt} 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?we(t):void 0}query(e){let{from:t,to:r}=ke(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=(I,S)=>{if(S)o.push(`${I}=?`),a.push(S)},u=(I,S)=>{let b=[...new Set(S??[])].slice(0,100);if(b.length)o.push(`${I} IN (${b.map(()=>"?").join(",")})`),a.push(...b)};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(we),m=E.length>n,T=new Map;for(let I of g)T.set(I.source,[...T.get(I.source)??[],I]);let h=this.now().getTime(),_=[...T].map(([I,S])=>{let b=S.reduce((k,U)=>U.observedAt>k?U.observedAt:k,S[0].observedAt),O=h-new Date(b).getTime();return{source:I,latestAt:b,freshness:O<=120000?"live":O<=600000?"stale":"unavailable",count:S.length}}),f=Math.max(60000,(r.getTime()-t.getTime())/100),v=[...T].flatMap(([I,S])=>{let b=[...new Set(S.map((O)=>new Date(O.timestamp).getTime()))].sort((O,k)=>O-k);return b.slice(1).flatMap((O,k)=>O-b[k]>f?[{from:new Date(b[k]).toISOString(),to:new Date(O).toISOString(),source:I}]:[])});return{records:g,nextCursor:m?_i(g.at(-1)):void 0,truncated:m,scannedRange:{from:t.toISOString(),to:r.toISOString()},sources:_,gaps:v}}tail(e,t){let{from:r,to:n}=ke(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(we);return{records:m,cursor:_i(m.at(-1))??t,truncated:g.length>o}}series(e){let{from:t,to:r}=ke(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)??[],_=ue(h,e.aggregation);m.push({timestamp:new Date(T).toISOString(),label:vA(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,J(e.compareFrom,"compareFrom"),J(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(ke(n),n.projectId!==e)throw Error("Saved telemetry queries cannot cross project scope.");let a=this.now().toISOString(),l=JSON.stringify(xi(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(we),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,_,f,v,I]=JSON.parse(E),S=g.flatMap((b)=>b.value==null?[]:[b.value]);this.append({projectId:m,environmentId:T||void 0,resourceId:h||void 0,kind:"metric",source:`${_}:rollup`,name:f,unit:v||void 0,timestamp:new Date(I).toISOString(),value:ue(S,"avg"),attributes:{downsampled:!0,count:S.length,min:ue(S,"min"),max:ue(S,"max"),p95:ue(S,"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 fo(e,t,r,n=new Date){let o=new At(e.controlPlane,{now:()=>n}),a=new Gr(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 EA=["spend.enforced"];function jn(e){if(e.level==="hard_capped")return"critical";if(e.level==="soft_capped")return"warning";return"info"}function Vr(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 Lp(e,t,r){let n=Vr(t.projection.actualCents,e.currency),o=e.hardLimitCents??e.softLimitCents,a=o==null?"":` of ${Vr(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=Ur(t.projection.timeToExhaustionMs),p=u?` Projected to reach the limit in ${u}.`:` Projected ${Vr(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:Lp(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:Ur(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 ${Vr(e.expected,t)} for this hour (observed ${Vr(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 ho{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:mo(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 vA="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 Mp{options;gate;service;notifications;constructor(e){this.options=e;this.gate=new Hr(e.controlPlane,{now:e.now}),this.service=new jt(e.store),this.notifications=e.alerts?new ho(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=vd({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 Fp=60;function TA(e,t={}){let r=Math.max(10,t.intervalSeconds??Fp)*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 Up{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 Qp{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}'`);
|
|
1550
|
+
GROUP BY project_id, COALESCE(environment_id, ''), COALESCE(resource_id, ''), source`,r)})()}}function Ao(e,t,r,n=new Date){let o=new At(e.controlPlane,{now:()=>n}),a=new jr(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 TA=["spend.enforced"];function jn(e){if(e.level==="hard_capped")return"critical";if(e.level==="soft_capped")return"warning";return"info"}function zr(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 Mp(e,t,r){let n=zr(t.projection.actualCents,e.currency),o=e.hardLimitCents??e.softLimitCents,a=o==null?"":` of ${zr(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=Gr(t.projection.timeToExhaustionMs),p=u?` Projected to reach the limit in ${u}.`:` Projected ${zr(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:Mp(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:Gr(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 ${zr(e.expected,t)} for this hour (observed ${zr(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 yo{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:ho(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 wA="spend.loop.lease";function zn(){return`${typeof process>"u"?"unknown":String(process.pid)}:${crypto.randomUUID().slice(0,8)}`}class Fp{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 Up{options;gate;service;notifications;constructor(e){this.options=e;this.gate=new qr(e.controlPlane,{now:e.now}),this.service=new Wt(e.store),this.notifications=e.alerts?new yo(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: ${pe(u)}`)}let a=wd({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: ${pe(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: ${pe(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: ${pe(u)}`)}try{this.options.store.pruneUsage(this.options.retentionDays??400,r)}catch(u){n.push(`Usage pruning failed: ${pe(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 pe(e){return e instanceof Error?e.message:String(e)}var Qp=60;function RA(e,t={}){let r=Math.max(10,t.intervalSeconds??Qp)*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 Ee(e,t){if(t.code!==0)throw Error(`${e} failed (exit ${t.code}): ${t.stderr.trim().slice(0,400)}`)}class Hp{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 Gp{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}'`);Ee(`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}'`);Ee(`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}'`);Ee(`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:Wr(r.thresholds?.newConnectionsPerSecond??50,n),concurrentPerSource:Wr(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
|
-
TS_CLOUD_THROTTLE_EOF`);return
|
|
1553
|
+
TS_CLOUD_THROTTLE_EOF`);return Ee("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`);
|
|
1555
|
+
TS_CLOUD_THROTTLE_EOF`);Ee("restoring the firewall ruleset",a)}}function DA(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 Ci}from"node:crypto";class Ti extends Error{constructor(){super("Operation cancellation was requested")}}class Zs extends Error{timeoutSeconds;constructor(e){super(`Operation exceeded its ${e}s timeout`);this.timeoutSeconds=e}}class te extends Error{errorClass;constructor(e,t){super(e);this.errorClass=t}}var Xe={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 W(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:W(e.lock_key),providerKey:W(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:W(e.heartbeat_at),currentStep:W(e.current_step),blockedReason:W(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:W(e.step),message:String(e.message),redacted:Number(e.redacted)===1,truncated:Number(e.truncated)===1,createdAt:String(e.created_at)}}function z(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=z(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:z(t.limits?.project??r?.project,Xe.project,100),environment:z(t.limits?.environment??r?.environment,Xe.environment,100),provider:z(t.limits?.provider??r?.provider,Xe.provider,100),builds:z(t.limits?.builds??r?.builds,Xe.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=z(e.maxAttempts,1,20),a=z(e.timeoutSeconds,1800,86400),l=z(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:z(e.project,this.limits.project,100),environment:z(e.environment,this.limits.environment,100),provider:z(e.provider,this.limits.provider,100),builds:z(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 Xs(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 Ci)},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 Ci}};try{let m=await Promise.race([o(g),new Promise((_,f)=>a.signal.addEventListener("abort",()=>f(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 Xs)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 Ci||this.controlPlane.getOperation(r.id)?.cancelRequestedAt)return{handled:!0,operation:this.finish(r.id,"cancelled",{cooperativelyCancelled:!0}),terminalState:"cancelled"};if(m instanceof ee&&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 f=Math.min(60000,1000*2**Math.max(0,r.attempt-1)),v=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=?",[v,`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:W(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 Ys{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 dt(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 at(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 dt(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 dt(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:at(t.interval,30),timeoutSeconds:at(t.timeout,5),retries:Math.max(1,Number(t.retries)||3),...t.start_period?{startPeriodSeconds:at(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 ri(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 ni(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 Or(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 h=`services.${T}`,_=D(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[U,fr]of ar)if(_[U]!=null&&_[U]!==!1&&(!Array.isArray(_[U])||_[U].length))n.push({severity:"error",path:`${h}.${U}`,code:`unsafe.${U}`,message:fr});for(let U of Object.keys(_))if(!Yn.has(U)&&!ar.has(U))n.push({severity:"warning",path:`${h}.${U}`,code:"field.unsupported",message:`Compose field ${U} is not in the supported subset and will not be deployed.`});let f=_.image?String(_.image):void 0,v=ti(_.build,`${h}.build`,n);if(!f&&!v)n.push({severity:"error",path:h,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:`${h}.image`,code:"image.floating",message:`Image ${f} is not pinned to a digest or explicit tag.`});let I=dt(_.networks).map((U)=>typeof U==="string"?U:String(D(U).name??"")).filter(Boolean);I.forEach((U)=>u.add(U));let S=D(_.deploy),b=D(S.resources),O=D(b.limits),k=["no","always","on-failure","unless-stopped"].includes(String(_.restart))?String(_.restart):"unless-stopped";p[T]={name:T,...f?{image:f}:{},...v?{build:v}:{},...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:I,dependsOn:ei(_.depends_on),...cr(_.healthcheck)?{healthCheck:cr(_.healthcheck)}:{},restart:k,...Number(O.cpus)>0?{cpu:Number(O.cpus)}:{},...dr(O.memory)?{memoryMb:dr(O.memory)}:{},replicas:Math.max(1,Math.min(100,Number(S.replicas)||1)),domains:ri(_.labels,`${h}.labels`,n)}}let E=ni(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=Yc(g);return{valid:!n.some((T)=>T.severity==="error"),manifest:g,diagnostics:n,redactedSource:m,sourceHash:Kn("sha256").update(e).digest("hex")}}function Yc(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 Zc(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 ii="2026-07-21T00:00:00.000Z",Er=[{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 Zs(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 Ti)},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 Ti}};try{let m=await Promise.race([o(g),new Promise((_,f)=>a.signal.addEventListener("abort",()=>f(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 Zs)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 Ti||this.controlPlane.getOperation(r.id)?.cancelRequestedAt)return{handled:!0,operation:this.finish(r.id,"cancelled",{cooperativelyCancelled:!0}),terminalState:"cancelled"};if(m instanceof te&&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 f=Math.min(60000,1000*2**Math.max(0,r.attempt-1)),v=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=?",[v,`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:W(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 eo{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 dt(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 at(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 dt(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 dt(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:at(t.interval,30),timeoutSeconds:at(t.timeout,5),retries:Math.max(1,Number(t.retries)||3),...t.start_period?{startPeriodSeconds:at(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 ri(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 ni(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 $r(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 h=`services.${T}`,_=D(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[U,Nr]of ar)if(_[U]!=null&&_[U]!==!1&&(!Array.isArray(_[U])||_[U].length))n.push({severity:"error",path:`${h}.${U}`,code:`unsafe.${U}`,message:Nr});for(let U of Object.keys(_))if(!Yn.has(U)&&!ar.has(U))n.push({severity:"warning",path:`${h}.${U}`,code:"field.unsupported",message:`Compose field ${U} is not in the supported subset and will not be deployed.`});let f=_.image?String(_.image):void 0,v=ti(_.build,`${h}.build`,n);if(!f&&!v)n.push({severity:"error",path:h,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:`${h}.image`,code:"image.floating",message:`Image ${f} is not pinned to a digest or explicit tag.`});let I=dt(_.networks).map((U)=>typeof U==="string"?U:String(D(U).name??"")).filter(Boolean);I.forEach((U)=>u.add(U));let S=D(_.deploy),b=D(S.resources),O=D(b.limits),k=["no","always","on-failure","unless-stopped"].includes(String(_.restart))?String(_.restart):"unless-stopped";p[T]={name:T,...f?{image:f}:{},...v?{build:v}:{},...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:I,dependsOn:ei(_.depends_on),...cr(_.healthcheck)?{healthCheck:cr(_.healthcheck)}:{},restart:k,...Number(O.cpus)>0?{cpu:Number(O.cpus)}:{},...dr(O.memory)?{memoryMb:dr(O.memory)}:{},replicas:Math.max(1,Math.min(100,Number(S.replicas)||1)),domains:ri(_.labels,`${h}.labels`,n)}}let E=ni(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=ed(g);return{valid:!n.some((T)=>T.severity==="error"),manifest:g,diagnostics:n,redactedSource:m,sourceHash:Kn("sha256").update(e).digest("hex")}}function ed(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 td(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 ii="2026-07-21T00:00:00.000Z",Er=[{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 _r(){return Er.map(({source:e,...t})=>({...t,source:`builtin:${t.id}`,lastVerifiedAt:ii,builtin:!0,checksum:pr("sha256").update(e).digest("hex"),exposedServices:[...t.exposedServices],inputs:t.inputs.map((r)=>({...r}))}))}function tA(e,t){return _r().find((r)=>r.id===e&&(!t||r.version===t))}function ed(e,t,r,n){let o=Er.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 Or(a,r)}function nI(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=Or(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 iI(e,t,r,n,o,a){let l=tA(r,a);if(!l)throw Error(`Compose template ${r}@${a} was not found`);let u=ed(r,n,o,a);return{template:l,parsed:u,templateChanges:Zc(t,u.manifest),userChanges:Zc(t,e)}}var Pe=/^[a-z0-9][a-z0-9_.-]{0,62}$/;function w(e){return`'${e.replaceAll("'","'\\''")}'`}function Js(e){return`${e.metadata.slug}-${e.metadata.environmentId.slice(0,8)}`.replace(/[^a-z0-9_-]/g,"-").slice(0,63)}function sI(e,t,r={}){let n=Js(e),o=`/opt/ts-cloud/compose/${n}`,a=`${o}/compose.yaml`,l=`docker compose --project-name ${w(n)} --file ${w(a)}`;if(r.service&&!Pe.test(r.service))throw Error("Unsafe Compose service name");if(t==="deploy"||t==="redeploy"){let u=Buffer.from(Yc(e)).toString("base64");return`install -d -m 0750 ${w(o)} && printf %s ${w(u)} | base64 --decode > ${w(a)} && chmod 0640 ${w(a)} && ${l} config --quiet && ${l} up --detach --remove-orphans --wait${t==="redeploy"?" --force-recreate":""}`}if(t==="start")return`${l} start${r.service?` ${w(r.service)}`:""}`;if(t==="stop")return`${l} stop${r.service?` ${w(r.service)}`:""}`;if(t==="status")return`${l} ps --format json`;return`${l} down --remove-orphans${r.removeVolumes?" --volumes":""}`}function oI(e,t,r){if(!Pe.test(t)||!Number.isInteger(r)||r<0||r>100)throw Error("Scale requires a safe service name and 0-100 replicas");let n=Js(e);return`docker compose --project-name ${w(n)} --file ${w(`/opt/ts-cloud/compose/${n}/compose.yaml`)} up --detach --wait --scale ${w(`${t}=${r}`)}`}function td(e,t,r=200){if(!Pe.test(t))throw Error("Unsafe Compose service name");let n=Js(e);return`docker compose --project-name ${w(n)} --file ${w(`/opt/ts-cloud/compose/${n}/compose.yaml`)} logs --no-color --timestamps --tail ${Math.max(1,Math.min(2000,Math.floor(r)))} ${w(t)}`}function rd(e,t,r=["sh"]){if(!Pe.test(t)||!r.length||r.some((o)=>o.includes("\x00")||o.length>1024))throw Error("Unsafe Compose shell request");let n=Js(e);return`docker compose --project-name ${w(n)} --file ${w(`/opt/ts-cloud/compose/${n}/compose.yaml`)} exec ${w(t)} ${r.map(w).join(" ")}`}import{mkdir as lt,readdir as li,rm as ui,stat as pi}from"node:fs/promises";import{basename as mi,resolve as mr,sep as gi}from"node:path";var ct=/^[a-z0-9][a-z0-9_.-]{1,62}$/,oi=/^0?[0-7]{3}$/,si=["/","/boot","/dev","/etc","/proc","/root","/run","/sys","/var/run","/var/lib/docker","/var/lib/containers"],ai=["create","attach","detach","resize","snapshot","restore","delete","adopt","usage"],di=(e)=>e&&typeof e==="object"&&!Array.isArray(e)?e:{};function iA(e){return Object.fromEntries(ai.map((t)=>[t,{supported:!1,reason:e}]))}function Zs(e,t={}){let r=iA("This storage driver does not support the operation.");for(let n of e)r[n]={supported:!0};return{...r,...t}}function sA(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(si.some((r)=>t===r||t.startsWith(`${r}/`)))throw Error(`Mount target ${e} is a protected host or runtime path.`)}function oA(e){if(sA(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&&!oi.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 eo{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(!ct.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"),oA(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"),!ct.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(!ct.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 ci(e){let t=di(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 id(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=ci(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 _i=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}},Z=/^[A-Za-z0-9][A-Za-z0-9_.-]{1,127}$/;class $r{command;provider="docker";type="docker";constructor(e=_i){this.command=e}capabilities(){return Zs(["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 Mr(){return Er.map(({source:e,...t})=>({...t,source:`builtin:${t.id}`,lastVerifiedAt:ii,builtin:!0,checksum:pr("sha256").update(e).digest("hex"),exposedServices:[...t.exposedServices],inputs:t.inputs.map((r)=>({...r}))}))}function nA(e,t){return Mr().find((r)=>r.id===e&&(!t||r.version===t))}function rd(e,t,r,n){let o=Er.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 $r(a,r)}function sI(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=$r(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 oI(e,t,r,n,o,a){let l=nA(r,a);if(!l)throw Error(`Compose template ${r}@${a} was not found`);let u=rd(r,n,o,a);return{template:l,parsed:u,templateChanges:td(t,u.manifest),userChanges:td(t,e)}}var Pe=/^[a-z0-9][a-z0-9_.-]{0,62}$/;function w(e){return`'${e.replaceAll("'","'\\''")}'`}function Ys(e){return`${e.metadata.slug}-${e.metadata.environmentId.slice(0,8)}`.replace(/[^a-z0-9_-]/g,"-").slice(0,63)}function aI(e,t,r={}){let n=Ys(e),o=`/opt/ts-cloud/compose/${n}`,a=`${o}/compose.yaml`,l=`docker compose --project-name ${w(n)} --file ${w(a)}`;if(r.service&&!Pe.test(r.service))throw Error("Unsafe Compose service name");if(t==="deploy"||t==="redeploy"){let u=Buffer.from(ed(e)).toString("base64");return`install -d -m 0750 ${w(o)} && printf %s ${w(u)} | base64 --decode > ${w(a)} && chmod 0640 ${w(a)} && ${l} config --quiet && ${l} up --detach --remove-orphans --wait${t==="redeploy"?" --force-recreate":""}`}if(t==="start")return`${l} start${r.service?` ${w(r.service)}`:""}`;if(t==="stop")return`${l} stop${r.service?` ${w(r.service)}`:""}`;if(t==="status")return`${l} ps --format json`;return`${l} down --remove-orphans${r.removeVolumes?" --volumes":""}`}function cI(e,t,r){if(!Pe.test(t)||!Number.isInteger(r)||r<0||r>100)throw Error("Scale requires a safe service name and 0-100 replicas");let n=Ys(e);return`docker compose --project-name ${w(n)} --file ${w(`/opt/ts-cloud/compose/${n}/compose.yaml`)} up --detach --wait --scale ${w(`${t}=${r}`)}`}function nd(e,t,r=200){if(!Pe.test(t))throw Error("Unsafe Compose service name");let n=Ys(e);return`docker compose --project-name ${w(n)} --file ${w(`/opt/ts-cloud/compose/${n}/compose.yaml`)} logs --no-color --timestamps --tail ${Math.max(1,Math.min(2000,Math.floor(r)))} ${w(t)}`}function id(e,t,r=["sh"]){if(!Pe.test(t)||!r.length||r.some((o)=>o.includes("\x00")||o.length>1024))throw Error("Unsafe Compose shell request");let n=Ys(e);return`docker compose --project-name ${w(n)} --file ${w(`/opt/ts-cloud/compose/${n}/compose.yaml`)} exec ${w(t)} ${r.map(w).join(" ")}`}import{mkdir as lt,readdir as li,rm as ui,stat as pi}from"node:fs/promises";import{basename as Ei,resolve as mr,sep as mi}from"node:path";var ct=/^[a-z0-9][a-z0-9_.-]{1,62}$/,oi=/^0?[0-7]{3}$/,si=["/","/boot","/dev","/etc","/proc","/root","/run","/sys","/var/run","/var/lib/docker","/var/lib/containers"],ai=["create","attach","detach","resize","snapshot","restore","delete","adopt","usage"],di=(e)=>e&&typeof e==="object"&&!Array.isArray(e)?e:{};function oA(e){return Object.fromEntries(ai.map((t)=>[t,{supported:!1,reason:e}]))}function to(e,t={}){let r=oA("This storage driver does not support the operation.");for(let n of e)r[n]={supported:!0};return{...r,...t}}function aA(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(si.some((r)=>t===r||t.startsWith(`${r}/`)))throw Error(`Mount target ${e} is a protected host or runtime path.`)}function cA(e){if(aA(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&&!oi.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 ro{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(!ct.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"),cA(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"),!ct.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(!ct.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 ci(e){let t=di(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 od(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=ci(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 gi=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}},Z=/^[A-Za-z0-9][A-Za-z0-9_.-]{1,127}$/;class Ur{command;provider="docker";type="docker";constructor(e=gi){this.command=e}capabilities(){return to(["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(Z.test.bind(Z))){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(!Z.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||!Z.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 to{provider="server";type="server_path";root;constructor(e){this.root=mr(e)}capabilities(){return Zs(["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(!Z.test(e))throw Error("Server path volume name is invalid.");let t=mr(this.root,e);if(!t.startsWith(`${this.root}${gi}`)||mi(t)!==e)throw Error("Server path escaped the managed volume root.");return t}async discover(e,t){return await lt(this.root,{recursive:!0,mode:488}),(await li(this.root,{withFileTypes:!0})).filter((n)=>n.isDirectory()&&Z.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 lt(this.root,{recursive:!0,mode:488}),await lt(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 ui(this.path(e.providerId),{recursive:!0,force:!1})}async usage(e){if(!e.providerId)return{};return{usedBytes:(await pi(this.path(e.providerId))).size}}}class aA{provider;transport;type="ebs";constructor(e,t){this.provider=e;this.transport=t}capabilities(){return Zs(["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 j=(e)=>e==null?void 0:String(e),ge=(e,t)=>{try{return JSON.parse(String(e))}catch{return t}},pt=(e)=>Number(e)===1,te=(e)=>e().toISOString();function Tr(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:j(e.environment_id),resourceId:j(e.resource_id),name:String(e.name),provider:String(e.provider),providerId:j(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:j(e.filesystem),encrypted:pt(e.encrypted),capabilities:ge(e.capabilities,{}),desiredState:ge(e.desired_state,{}),observedState:ge(e.observed_state,{}),backupPolicyId:j(e.backup_policy_id),lastBackupAt:j(e.last_backup_at),orphanedAt:j(e.orphaned_at),adoptedAt:j(e.adopted_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at),deletedAt:j(e.deleted_at)}}function ut(e){return{id:String(e.id),volumeId:String(e.volume_id),resourceId:String(e.resource_id),targetPath:String(e.target_path),readOnly:pt(e.read_only),uid:e.uid==null?void 0:Number(e.uid),gid:e.gid==null?void 0:Number(e.gid),mode:j(e.mode),propagation:String(e.propagation),driverOptions:ge(e.driver_options,{}),desiredState:String(e.desired_state),observedState:String(e.observed_state),operationId:j(e.operation_id),lastError:j(e.last_error),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function gr(e){return{id:String(e.id),volumeId:String(e.volume_id),recoveryPointId:j(e.recovery_point_id),providerId:j(e.provider_id),name:String(e.name),status:String(e.status),sizeBytes:e.size_bytes==null?void 0:Number(e.size_bytes),encrypted:pt(e.encrypted),checksum:j(e.checksum),metadata:ge(e.metadata,{}),createdAt:String(e.created_at),updatedAt:String(e.updated_at),deletedAt:j(e.deleted_at)}}class Gt{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?Tr(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(Tr)}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(ut)}attachment(e){let t=this.controlPlane.database.query("SELECT * FROM volume_attachments WHERE id=?").get(e);return t?ut(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=ut(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(gr)}snapshot(e){let t=this.controlPlane.database.query("SELECT * FROM volume_snapshots WHERE id=?").get(e);return t?gr(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 sd(e,t){let r=e.getProject(t.projectId);if(!r?.organizationId)return;let n=new Gt(e),o=new $r,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((f)=>f.source===u)){let f=T.get(_.target)??[];f.push(h.name),T.set(_.target,f),n.upsertAttachment({volumeId:m.id,resourceId:t.resourceId,targetPath:_.target,readOnly:_.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 Ip(e,t,r){let n=new Gt(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 Et(e,t){try{return JSON.parse(String(e))}catch{return t}}function xe(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:Et(e.manifest,{}),diagnostics:Et(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 hi(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:Et(e.observed_state,{}),updatedAt:String(e.updated_at)}}class Vt{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 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 I 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,I.name,I.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 v=this.get(u.id);return sd(this.controlPlane,v),v}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 sd(this.controlPlane,h),h}import(e,t){let r=Or(e,t);return{application:this.persist(r,{sourceKind:"compose",createdByActorId:t.createdByActorId}),parsed:r}}fromTemplate(e,t,r){let n=ed(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 Or(e,t)}get(e){let t=this.controlPlane.database.query("SELECT * FROM compose_applications WHERE id=?").get(e);return t?xe(t):void 0}getByResource(e){let t=this.controlPlane.database.query("SELECT * FROM compose_applications WHERE resource_id=?").get(e);return t?xe(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?xe(n):void 0}list(e={}){return this.controlPlane.database.query("SELECT * FROM compose_applications ORDER BY updated_at DESC").all().map(xe).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(hi)}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 Mr{controlPlane;applications;queue;constructor(e){this.controlPlane=e;this.applications=new Vt(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 fi}from"node:crypto";var yi=/^[a-f0-9]{40,64}$/i,Li=/^[A-Z][A-Z0-9_]{1,127}$/;function V(e){return typeof e==="string"&&e?e:void 0}function ne(e){try{return JSON.parse(String(e))}catch{return{}}}function Ii(e){let t=ne(e);return Array.isArray(t)?t.map(String):[]}function Tt(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:V(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:Ii(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:V(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:V(e.source_provider),repository:V(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:V(e.url),status:String(e.status),expiresAt:String(e.expires_at),latestOperationId:V(e.latest_operation_id),createdByActorId:V(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:V(e.teardown_error),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at),destroyedAt:V(e.destroyed_at)}}function hr(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:V(e.deleted_at)}}function K(e,t,r,n){return Number.isFinite(e)?Math.min(n,Math.max(r,Math.floor(e))):t}function je(e,t,r,n){return Number.isFinite(e)?Math.min(n,Math.max(r,e)):t}function gt(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,28)||"preview"}class Ve{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)=>!Li.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,K(e.ttlHours,n.ttlHours,1,720),K(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,je(e.maxMonthlyCost,n.maxMonthlyCost,0,1e4),je(e.maxCpu,n.maxCpu,0.1,64),K(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,K(e.ttlHours,24,1,720),K(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",je(e.maxMonthlyCost,25,0,1e4),je(e.maxCpu,1,0.1,64),K(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:K(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?Tt(t):void 0}getDefinitionForResource(e){let t=this.controlPlane.database.query("SELECT * FROM preview_definitions WHERE resource_id=?").get(e);return t?Tt(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(Tt)}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(!yi.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=fi("sha256").update(`${t.id}:${r}`).digest("hex").slice(0,8),a=`${(e.pullRequestNumber?`pr-${e.pullRequestNumber}`:gt(e.branch)).slice(0,28)}-${n}`,l=`preview-${a}`.slice(0,63),u=t.domainPattern.replaceAll("{name}",a).replaceAll("{project}",gt(t.projectId)).replaceAll("{branch}",gt(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),f=_.commitSha!==e.commitSha||_.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,_.id]);return{preview:this.getInstance(_.id),created:!1,changed:f,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=K(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 hr(a)}listResources(e){return this.controlPlane.database.query("SELECT * FROM preview_resources WHERE preview_id=? ORDER BY kind, provider_resource_id").all(e).map(hr)}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 Lr{controlPlane;previews;queue;constructor(e){this.controlPlane=e;this.previews=new Ve(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 rA=["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 Fe(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function nA(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=Fe(t.input);if(t.kind.startsWith("compose.")){let l=typeof o.applicationId==="string"?o.applicationId:void 0,u=l?new Vt(e).get(l):t.resourceId?new Vt(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 Ve(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 Si(e){let t=e.stderr?.trim()||`Deployment process exited with code ${e.exitCode}`;if(/\b(?:429|rate.?limit|throttl)/i.test(t))return new ee(t,"provider_throttled");if(/\b(?:502|503|504|temporar(?:y|ily)|unavailable|provider.?error)/i.test(t))return new ee(t,"provider_unavailable");if(/\b(?:network|econn|enotfound|socket|timed?\s*out|fetch failed|dns)\b/i.test(t))return new ee(t,"network");return Error(t)}function nd(e){let t=async(r)=>{r.checkpoint("prepare","Resolving the persisted deployment target.");let n=nA(e.store,r.operation),o=n.target.previewId?new Ve(e.store):void 0,a=n.target.composeId?new Vt(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 Si(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 Fe(r.operation.input).service==="string"?String(Fe(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")Ip(e.store,g,Fe(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(rA.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 _t(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 RA(e,t,r){return Ai("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 no{provider="server";type="server_path";root;constructor(e){this.root=mr(e)}capabilities(){return to(["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(!Z.test(e))throw Error("Server path volume name is invalid.");let t=mr(this.root,e);if(!t.startsWith(`${this.root}${mi}`)||Ei(t)!==e)throw Error("Server path escaped the managed volume root.");return t}async discover(e,t){return await lt(this.root,{recursive:!0,mode:488}),(await li(this.root,{withFileTypes:!0})).filter((n)=>n.isDirectory()&&Z.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 lt(this.root,{recursive:!0,mode:488}),await lt(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 ui(this.path(e.providerId),{recursive:!0,force:!1})}async usage(e){if(!e.providerId)return{};return{usedBytes:(await pi(this.path(e.providerId))).size}}}class dA{provider;transport;type="ebs";constructor(e,t){this.provider=e;this.transport=t}capabilities(){return to(["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 j=(e)=>e==null?void 0:String(e),ge=(e,t)=>{try{return JSON.parse(String(e))}catch{return t}},pt=(e)=>Number(e)===1,ee=(e)=>e().toISOString();function Tr(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:j(e.environment_id),resourceId:j(e.resource_id),name:String(e.name),provider:String(e.provider),providerId:j(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:j(e.filesystem),encrypted:pt(e.encrypted),capabilities:ge(e.capabilities,{}),desiredState:ge(e.desired_state,{}),observedState:ge(e.observed_state,{}),backupPolicyId:j(e.backup_policy_id),lastBackupAt:j(e.last_backup_at),orphanedAt:j(e.orphaned_at),adoptedAt:j(e.adopted_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at),deletedAt:j(e.deleted_at)}}function ut(e){return{id:String(e.id),volumeId:String(e.volume_id),resourceId:String(e.resource_id),targetPath:String(e.target_path),readOnly:pt(e.read_only),uid:e.uid==null?void 0:Number(e.uid),gid:e.gid==null?void 0:Number(e.gid),mode:j(e.mode),propagation:String(e.propagation),driverOptions:ge(e.driver_options,{}),desiredState:String(e.desired_state),observedState:String(e.observed_state),operationId:j(e.operation_id),lastError:j(e.last_error),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function gr(e){return{id:String(e.id),volumeId:String(e.volume_id),recoveryPointId:j(e.recovery_point_id),providerId:j(e.provider_id),name:String(e.name),status:String(e.status),sizeBytes:e.size_bytes==null?void 0:Number(e.size_bytes),encrypted:pt(e.encrypted),checksum:j(e.checksum),metadata:ge(e.metadata,{}),createdAt:String(e.created_at),updatedAt:String(e.updated_at),deletedAt:j(e.deleted_at)}}class jt{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?Tr(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(Tr)}create(e){let t=ee(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:ee(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(ut)}attachment(e){let t=this.controlPlane.database.query("SELECT * FROM volume_attachments WHERE id=?").get(e);return t?ut(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=ee(this.now);if(t){let o=ut(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,ee(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(gr)}snapshot(e){let t=this.controlPlane.database.query("SELECT * FROM volume_snapshots WHERE id=?").get(e);return t?gr(t):void 0}createSnapshot(e){let t=e.id??this.id(),r=ee(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,ee(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 ad(e,t){let r=e.getProject(t.projectId);if(!r?.organizationId)return;let n=new jt(e),o=new Ur,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((f)=>f.source===u)){let f=T.get(_.target)??[];f.push(h.name),T.set(_.target,f),n.upsertAttachment({volumeId:m.id,resourceId:t.resourceId,targetPath:_.target,readOnly:_.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 Cp(e,t,r){let n=new jt(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 Et(e,t){try{return JSON.parse(String(e))}catch{return t}}function xe(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:Et(e.manifest,{}),diagnostics:Et(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 hi(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:Et(e.observed_state,{}),updatedAt:String(e.updated_at)}}class zt{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 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 I 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,I.name,I.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 v=this.get(u.id);return ad(this.controlPlane,v),v}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 ad(this.controlPlane,h),h}import(e,t){let r=$r(e,t);return{application:this.persist(r,{sourceKind:"compose",createdByActorId:t.createdByActorId}),parsed:r}}fromTemplate(e,t,r){let n=rd(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 $r(e,t)}get(e){let t=this.controlPlane.database.query("SELECT * FROM compose_applications WHERE id=?").get(e);return t?xe(t):void 0}getByResource(e){let t=this.controlPlane.database.query("SELECT * FROM compose_applications WHERE resource_id=?").get(e);return t?xe(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?xe(n):void 0}list(e={}){return this.controlPlane.database.query("SELECT * FROM compose_applications ORDER BY updated_at DESC").all().map(xe).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(hi)}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 Qr{controlPlane;applications;queue;constructor(e){this.controlPlane=e;this.applications=new zt(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 fi}from"node:crypto";var yi=/^[a-f0-9]{40,64}$/i,Ii=/^[A-Z][A-Z0-9_]{1,127}$/;function V(e){return typeof e==="string"&&e?e:void 0}function ne(e){try{return JSON.parse(String(e))}catch{return{}}}function Si(e){let t=ne(e);return Array.isArray(t)?t.map(String):[]}function Tt(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:V(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:Si(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:V(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:V(e.source_provider),repository:V(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:V(e.url),status:String(e.status),expiresAt:String(e.expires_at),latestOperationId:V(e.latest_operation_id),createdByActorId:V(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:V(e.teardown_error),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at),destroyedAt:V(e.destroyed_at)}}function _r(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:V(e.deleted_at)}}function K(e,t,r,n){return Number.isFinite(e)?Math.min(n,Math.max(r,Math.floor(e))):t}function je(e,t,r,n){return Number.isFinite(e)?Math.min(n,Math.max(r,e)):t}function gt(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,28)||"preview"}class Ve{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)=>!Ii.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,K(e.ttlHours,n.ttlHours,1,720),K(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,je(e.maxMonthlyCost,n.maxMonthlyCost,0,1e4),je(e.maxCpu,n.maxCpu,0.1,64),K(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,K(e.ttlHours,24,1,720),K(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",je(e.maxMonthlyCost,25,0,1e4),je(e.maxCpu,1,0.1,64),K(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:K(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?Tt(t):void 0}getDefinitionForResource(e){let t=this.controlPlane.database.query("SELECT * FROM preview_definitions WHERE resource_id=?").get(e);return t?Tt(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(Tt)}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(!yi.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=fi("sha256").update(`${t.id}:${r}`).digest("hex").slice(0,8),a=`${(e.pullRequestNumber?`pr-${e.pullRequestNumber}`:gt(e.branch)).slice(0,28)}-${n}`,l=`preview-${a}`.slice(0,63),u=t.domainPattern.replaceAll("{name}",a).replaceAll("{project}",gt(t.projectId)).replaceAll("{branch}",gt(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),f=_.commitSha!==e.commitSha||_.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,_.id]);return{preview:this.getInstance(_.id),created:!1,changed:f,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=K(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 _r(a)}listResources(e){return this.controlPlane.database.query("SELECT * FROM preview_resources WHERE preview_id=? ORDER BY kind, provider_resource_id").all(e).map(_r)}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 Fr{controlPlane;previews;queue;constructor(e){this.controlPlane=e;this.previews=new Ve(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 iA=["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 Fe(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function sA(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=Fe(t.input);if(t.kind.startsWith("compose.")){let l=typeof o.applicationId==="string"?o.applicationId:void 0,u=l?new zt(e).get(l):t.resourceId?new zt(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 Ve(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 bi(e){let t=e.stderr?.trim()||`Deployment process exited with code ${e.exitCode}`;if(/\b(?:429|rate.?limit|throttl)/i.test(t))return new te(t,"provider_throttled");if(/\b(?:502|503|504|temporar(?:y|ily)|unavailable|provider.?error)/i.test(t))return new te(t,"provider_unavailable");if(/\b(?:network|econn|enotfound|socket|timed?\s*out|fetch failed|dns)\b/i.test(t))return new te(t,"network");return Error(t)}function sd(e){let t=async(r)=>{r.checkpoint("prepare","Resolving the persisted deployment target.");let n=sA(e.store,r.operation),o=n.target.previewId?new Ve(e.store):void 0,a=n.target.composeId?new zt(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 bi(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 Fe(r.operation.input).service==="string"?String(Fe(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")Cp(e.store,g,Fe(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(iA.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 _t(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 PA(e,t,r){return Ci("sha256").update(`${e.toUpperCase()}
|
|
1616
1616
|
${t}
|
|
1617
|
-
${JSON.stringify(r)}`).digest("hex")}class xi{controlPlane;identities;queue;spendGate;constructor(e,t){this.controlPlane=e;this.identities=t;this.queue=new c(e),this.spendGate=new Hr(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||!_t(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&&_t(n,o);if(!n||!o||!_t(o,n)&&!a)throw new i("forbidden","The token does not grant access to this resource.",403);let l=a?o:n;if(!P({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=RA("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 Me(e){return e.serviceAccount.organizationId}function Nr(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 x(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:Me(t),projectId:n,environmentId:o}}async function Ao(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=x(e,t,"billing:read",l,u);return e.service.usageReport({...T,period:Nr(o.searchParams.get("period")),timezone:o.searchParams.get("timezone")??void 0,now:a})}if(n==="GET"&&o.pathname==="/api/v1/usage/rollups"){let T=x(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 f=o.searchParams.getAll("meter");return{data:e.store.listRollups({...T,from:h,to:_,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=x(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 f=o.searchParams.get("granularity")==="hourly"?"hourly":"daily",v=e.store.listRollups({...T,from:h,to:_},1e4),I=bd(v,{billingPeriodStart:h,billingPeriodEnd:_,currency:e.store.priceBook.currency,granularity:f});return{contentType:"application/x-ndjson",body:po(I),recordCount:I.length}}if(n==="GET"&&o.pathname==="/api/v1/spend/budgets"){let T=x(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:x(e,t,"billing:manage",T.projectId,T.environmentId).organizationId,projectId:T.projectId,environmentId:T.environmentId,name:String(T.name??"").trim(),period:Nr(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(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!==Me(t))throw new i("not_found","Budget was not found.",404);if(x(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 f=_ instanceof Error?_.message:String(_);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=x(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!==Me(t))throw new i("not_found","Anomaly was not found.",404);return x(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 x(e,t,"billing:read",l,u),{data:Qr};if(o.pathname==="/api/v1/spend/anomaly-configs"){if(n==="GET"){let T=x(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=x(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!==Me(t))throw new i("not_found","Anomaly config was not found.",404);return x(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=x(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=x(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 x(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=x(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=x(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 f=e.store.listEnforcements({organizationId:T.organizationId,activeOnly:!0}).filter((b)=>(!b.projectId||b.projectId===T.projectId)&&(!b.environmentId||b.environmentId===T.environmentId)),v=yd(h,f),S=e.store.budgetsForScope(T.organizationId,T.projectId,T.environmentId).map((b)=>e.service.status(b,a));return{operation:h,allowed:v.allowed,blockedBy:v.blockedBy??null,reason:v.reason??null,budgets:S.map((b)=>({id:b.budget.id,name:b.budget.name,usedPercent:b.decision.usedPercent,projectedPercent:b.decision.projectedPercent,level:b.decision.level,timeToCap:b.timeToCap}))}}return}function yo(){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{Ge,Kc,pe,Qt,Wc,P,Ht,mt,Jc,Ks,eA,Sp,Xc,s,bi,Ws,Or,Yc,Zc,_r,tA,ed,nI,iI,Js,sI,oI,td,rd,Ci,Xs,ee,c,Ys,Ve,Lr,rA,nA,nd,Gt,iA,Zs,sA,oA,eo,id,$r,to,aA,sd,Ip,Vt,Mr,cA,ro,dA,N,lA,od,bp,no,uA,gA,pA,ad,Ei,io,cd,qt,ft,mA,Fr,fA,dd,Cp,Ep,so,ld,ud,ht,vp,vi,gd,oo,Ur,Tp,Ti,pd,md,wi,wp,fd,hd,Ad,yd,ao,Rp,Dp,hA,Pp,Sd,Ri,Np,kp,co,Qr,lo,uo,go,Id,Bp,bd,po,AA,jt,yA,Cd,Hr,Ed,SA,vd,xp,Di,Gr,mo,Pi,qe,IA,Op,_p,zt,Td,wd,Rd,Ni,ki,Bi,bA,CA,At,fo,EA,Vr,Lp,ho,vA,$p,Mp,Fp,TA,Up,Qp,wA,i,RA,xi,Ao,yo};
|
|
1617
|
+
${JSON.stringify(r)}`).digest("hex")}class Li{controlPlane;identities;queue;spendGate;constructor(e,t){this.controlPlane=e;this.identities=t;this.queue=new c(e),this.spendGate=new qr(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||!_t(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&&_t(n,o);if(!n||!o||!_t(o,n)&&!a)throw new i("forbidden","The token does not grant access to this resource.",403);let l=a?o:n;if(!P({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=PA("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 Me(e){return e.serviceAccount.organizationId}function hr(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 x(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:Me(t),projectId:n,environmentId:o}}async function So(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=x(e,t,"billing:read",l,u);return e.service.usageReport({...T,period:hr(o.searchParams.get("period")),timezone:o.searchParams.get("timezone")??void 0,now:a})}if(n==="GET"&&o.pathname==="/api/v1/usage/rollups"){let T=x(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 f=o.searchParams.getAll("meter");return{data:e.store.listRollups({...T,from:h,to:_,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=x(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 f=o.searchParams.get("granularity")==="hourly"?"hourly":"daily",v=e.store.listRollups({...T,from:h,to:_},1e4),I=Ed(v,{billingPeriodStart:h,billingPeriodEnd:_,currency:e.store.priceBook.currency,granularity:f});return{contentType:"application/x-ndjson",body:fo(I),recordCount:I.length}}if(n==="GET"&&o.pathname==="/api/v1/spend/budgets"){let T=x(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:x(e,t,"billing:manage",T.projectId,T.environmentId).organizationId,projectId:T.projectId,environmentId:T.environmentId,name:String(T.name??"").trim(),period:hr(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(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!==Me(t))throw new i("not_found","Budget was not found.",404);if(x(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 f=_ instanceof Error?_.message:String(_);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=x(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!==Me(t))throw new i("not_found","Anomaly was not found.",404);return x(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 x(e,t,"billing:read",l,u),{data:Vr};if(o.pathname==="/api/v1/spend/anomaly-configs"){if(n==="GET"){let T=x(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=x(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!==Me(t))throw new i("not_found","Anomaly config was not found.",404);return x(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=x(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=x(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 x(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=x(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=x(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 f=e.store.listEnforcements({organizationId:T.organizationId,activeOnly:!0}).filter((b)=>(!b.projectId||b.projectId===T.projectId)&&(!b.environmentId||b.environmentId===T.environmentId)),v=Id(h,f),S=e.store.budgetsForScope(T.organizationId,T.projectId,T.environmentId).map((b)=>e.service.status(b,a));return{operation:h,allowed:v.allowed,blockedBy:v.blockedBy??null,reason:v.reason??null,budgets:S.map((b)=>({id:b.budget.id,name:b.budget.name,usedPercent:b.decision.usedPercent,projectedPercent:b.decision.projectedPercent,level:b.decision.level,timeToCap:b.timeToCap}))}}return}function Io(){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{Ge,Jc,me,Vt,Xc,P,qt,mt,Yc,Js,rA,bp,Zc,s,vi,Xs,$r,ed,td,Mr,nA,rd,sI,oI,Ys,aI,cI,nd,id,Ti,Zs,te,c,eo,Ve,Fr,iA,sA,sd,jt,oA,to,aA,cA,ro,od,Ur,no,dA,ad,Cp,zt,Qr,lA,io,uA,N,gA,cd,Ep,so,pA,mA,fA,dd,wi,oo,ld,Kt,ft,hA,Hr,AA,ud,vp,Tp,ao,gd,pd,ht,wp,Ri,md,co,Gr,Rp,Di,fd,hd,Pi,Dp,Ad,yd,Sd,Id,lo,Pp,Np,yA,kp,bd,Ni,Bp,xp,uo,Vr,go,po,mo,Cd,Op,Ed,fo,SA,Wt,IA,vd,qr,Td,bA,wd,_p,ki,jr,ho,Bi,qe,CA,Lp,$p,Jt,Rd,Dd,Pd,xi,Oi,_i,EA,vA,At,Ao,TA,zr,Mp,yo,wA,Fp,Up,Qp,RA,Hp,Gp,DA,i,PA,Li,So,Io};
|