gemi 0.233.1 → 0.234.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/index.js +2 -2
- package/dist/ai/index.js.map +1 -1
- package/dist/ai/testing/index.js +2 -2
- package/dist/ai/testing/index.js.map +1 -1
- package/dist/app/index.js +1 -1
- package/dist/bun/plugin.js +1 -1
- package/dist/bun/preload.js +1 -1
- package/dist/chunk-0hy5dsbt.js +5 -0
- package/dist/{chunk-rqzpxeb5.js.map → chunk-0hy5dsbt.js.map} +1 -1
- package/dist/{chunk-e30saw5t.js → chunk-17bva6b1.js} +2 -2
- package/dist/{chunk-e30saw5t.js.map → chunk-17bva6b1.js.map} +1 -1
- package/dist/{chunk-6fpjc2eg.js → chunk-17ewxwga.js} +3 -3
- package/dist/{chunk-6fpjc2eg.js.map → chunk-17ewxwga.js.map} +1 -1
- package/dist/{chunk-5p0gbwq1.js → chunk-1mb7kaxs.js} +3 -3
- package/dist/{chunk-5p0gbwq1.js.map → chunk-1mb7kaxs.js.map} +1 -1
- package/dist/{chunk-mcgcgm6g.js → chunk-1w6ra6jc.js} +1 -1
- package/dist/{chunk-qqe19gtm.js → chunk-1xz206e1.js} +3 -3
- package/dist/{chunk-qqe19gtm.js.map → chunk-1xz206e1.js.map} +1 -1
- package/dist/{chunk-wgxkr2jx.js → chunk-28yb0q82.js} +2 -2
- package/dist/{chunk-wgxkr2jx.js.map → chunk-28yb0q82.js.map} +1 -1
- package/dist/{chunk-j5fh6pjs.js → chunk-2j45vbs2.js} +2 -2
- package/dist/{chunk-j5fh6pjs.js.map → chunk-2j45vbs2.js.map} +1 -1
- package/dist/{chunk-mgvrfhy8.js → chunk-2kzysesp.js} +3 -3
- package/dist/{chunk-mgvrfhy8.js.map → chunk-2kzysesp.js.map} +1 -1
- package/dist/{chunk-tegjs0gg.js → chunk-2ver7cdt.js} +1 -1
- package/dist/{chunk-kfcz4qa8.js → chunk-3y1h3ncf.js} +2 -2
- package/dist/{chunk-kfcz4qa8.js.map → chunk-3y1h3ncf.js.map} +1 -1
- package/dist/{chunk-xprhym1t.js → chunk-406ef17s.js} +2 -2
- package/dist/{chunk-xprhym1t.js.map → chunk-406ef17s.js.map} +1 -1
- package/dist/{chunk-j7swq19b.js → chunk-4mha212g.js} +1 -1
- package/dist/{chunk-vnpfdr52.js → chunk-4n3jva4e.js} +2 -2
- package/dist/{chunk-vnpfdr52.js.map → chunk-4n3jva4e.js.map} +1 -1
- package/dist/{chunk-jrvqya5h.js → chunk-4vn8gyzy.js} +2 -2
- package/dist/{chunk-jrvqya5h.js.map → chunk-4vn8gyzy.js.map} +1 -1
- package/dist/{chunk-c5kd7eac.js → chunk-5exrgw07.js} +3 -3
- package/dist/{chunk-c5kd7eac.js.map → chunk-5exrgw07.js.map} +1 -1
- package/dist/chunk-69xg5wgz.js +10 -0
- package/dist/{chunk-1eha67ey.js.map → chunk-69xg5wgz.js.map} +5 -4
- package/dist/{chunk-mg9j9r9f.js → chunk-6v1fbe70.js} +2 -2
- package/dist/{chunk-mg9j9r9f.js.map → chunk-6v1fbe70.js.map} +1 -1
- package/dist/{chunk-q78n7dvm.js → chunk-74dzzd64.js} +2 -2
- package/dist/{chunk-q78n7dvm.js.map → chunk-74dzzd64.js.map} +1 -1
- package/dist/{chunk-3v8b2kdr.js → chunk-7fbnw7e2.js} +1 -1
- package/dist/{chunk-znh1mbqs.js → chunk-8476xvk9.js} +2 -2
- package/dist/{chunk-znh1mbqs.js.map → chunk-8476xvk9.js.map} +1 -1
- package/dist/{chunk-65wnm25z.js → chunk-8gz07168.js} +4 -4
- package/dist/{chunk-65wnm25z.js.map → chunk-8gz07168.js.map} +1 -1
- package/dist/{chunk-8q1n4087.js → chunk-8jc8x9tc.js} +2 -2
- package/dist/{chunk-8q1n4087.js.map → chunk-8jc8x9tc.js.map} +1 -1
- package/dist/{chunk-kpmp5hmc.js → chunk-8mpptpn5.js} +3 -3
- package/dist/{chunk-kpmp5hmc.js.map → chunk-8mpptpn5.js.map} +1 -1
- package/dist/{chunk-5sgwnrr8.js → chunk-8n40a2sn.js} +2 -2
- package/dist/{chunk-5sgwnrr8.js.map → chunk-8n40a2sn.js.map} +1 -1
- package/dist/{chunk-wedj46ec.js → chunk-8yb9jrj5.js} +2 -2
- package/dist/{chunk-wedj46ec.js.map → chunk-8yb9jrj5.js.map} +1 -1
- package/dist/{chunk-7ka1abkd.js → chunk-9jt5qj1b.js} +2 -2
- package/dist/{chunk-7ka1abkd.js.map → chunk-9jt5qj1b.js.map} +1 -1
- package/dist/{chunk-7g3r55sj.js → chunk-9kt24ctk.js} +2 -2
- package/dist/{chunk-7g3r55sj.js.map → chunk-9kt24ctk.js.map} +1 -1
- package/dist/{chunk-gd4qydsx.js → chunk-9sbhqscs.js} +3 -3
- package/dist/{chunk-gd4qydsx.js.map → chunk-9sbhqscs.js.map} +1 -1
- package/dist/{chunk-efnerp0c.js → chunk-a119av2z.js} +2 -2
- package/dist/{chunk-efnerp0c.js.map → chunk-a119av2z.js.map} +1 -1
- package/dist/{chunk-g0t49jec.js → chunk-aj9atkwk.js} +1 -1
- package/dist/{chunk-8hr7z8cc.js → chunk-at82qczv.js} +3 -3
- package/dist/{chunk-8hr7z8cc.js.map → chunk-at82qczv.js.map} +1 -1
- package/dist/{chunk-xmrd9460.js → chunk-byv7b79h.js} +2 -2
- package/dist/{chunk-xmrd9460.js.map → chunk-byv7b79h.js.map} +1 -1
- package/dist/{chunk-3q0sbk92.js → chunk-ca5kp6cn.js} +2 -2
- package/dist/{chunk-3q0sbk92.js.map → chunk-ca5kp6cn.js.map} +1 -1
- package/dist/{chunk-hd9yny4q.js → chunk-cb7mgx75.js} +4 -4
- package/dist/{chunk-hd9yny4q.js.map → chunk-cb7mgx75.js.map} +1 -1
- package/dist/{chunk-7y2g8wbb.js → chunk-ehtj7zs2.js} +2 -2
- package/dist/{chunk-7y2g8wbb.js.map → chunk-ehtj7zs2.js.map} +1 -1
- package/dist/{chunk-69q9tk74.js → chunk-ezea9fpd.js} +2 -2
- package/dist/{chunk-69q9tk74.js.map → chunk-ezea9fpd.js.map} +1 -1
- package/dist/{chunk-kspqqyv1.js → chunk-fbk79z21.js} +2 -2
- package/dist/{chunk-kspqqyv1.js.map → chunk-fbk79z21.js.map} +1 -1
- package/dist/{chunk-vjqpcet2.js → chunk-fqndtpwm.js} +3 -3
- package/dist/{chunk-vjqpcet2.js.map → chunk-fqndtpwm.js.map} +1 -1
- package/dist/{chunk-qgka1mvf.js → chunk-fs94x6ef.js} +3 -3
- package/dist/{chunk-qgka1mvf.js.map → chunk-fs94x6ef.js.map} +1 -1
- package/dist/{chunk-a2y481gh.js → chunk-g7hz0dmk.js} +2 -2
- package/dist/{chunk-a2y481gh.js.map → chunk-g7hz0dmk.js.map} +1 -1
- package/dist/{chunk-1v1ek1ey.js → chunk-gt9ftnhn.js} +2 -2
- package/dist/{chunk-1v1ek1ey.js.map → chunk-gt9ftnhn.js.map} +1 -1
- package/dist/{chunk-x6fa13e1.js → chunk-gvr7cwxn.js} +3 -3
- package/dist/{chunk-x6fa13e1.js.map → chunk-gvr7cwxn.js.map} +1 -1
- package/dist/{chunk-vrtt8nvm.js → chunk-h0dch3vh.js} +2 -2
- package/dist/{chunk-vrtt8nvm.js.map → chunk-h0dch3vh.js.map} +1 -1
- package/dist/{chunk-jqqyj6cr.js → chunk-h1wmpa03.js} +2 -2
- package/dist/{chunk-jqqyj6cr.js.map → chunk-h1wmpa03.js.map} +1 -1
- package/dist/{chunk-agc0e46c.js → chunk-h5wjk91m.js} +2 -2
- package/dist/{chunk-agc0e46c.js.map → chunk-h5wjk91m.js.map} +1 -1
- package/dist/{chunk-x1p31k7q.js → chunk-hgwkxn0g.js} +2 -2
- package/dist/{chunk-x1p31k7q.js.map → chunk-hgwkxn0g.js.map} +1 -1
- package/dist/{chunk-bs8bq053.js → chunk-hprgj13q.js} +2 -2
- package/dist/{chunk-bs8bq053.js.map → chunk-hprgj13q.js.map} +1 -1
- package/dist/{chunk-9bjggtdt.js → chunk-jssjfvsz.js} +2 -2
- package/dist/{chunk-9bjggtdt.js.map → chunk-jssjfvsz.js.map} +1 -1
- package/dist/{chunk-ct8eh241.js → chunk-k2mpxwh2.js} +2 -2
- package/dist/{chunk-30jcs49q.js.map → chunk-k2mpxwh2.js.map} +1 -1
- package/dist/{chunk-x8by5j7p.js → chunk-ka8dzc6q.js} +2 -2
- package/dist/{chunk-x8by5j7p.js.map → chunk-ka8dzc6q.js.map} +1 -1
- package/dist/{chunk-0zf4dy4y.js → chunk-kak3vc71.js} +2 -2
- package/dist/{chunk-0zf4dy4y.js.map → chunk-kak3vc71.js.map} +1 -1
- package/dist/{chunk-g0mxdh2x.js → chunk-kvtvx64t.js} +2 -2
- package/dist/{chunk-g0mxdh2x.js.map → chunk-kvtvx64t.js.map} +1 -1
- package/dist/{chunk-6j439skq.js → chunk-m2f4n0mq.js} +2 -2
- package/dist/{chunk-6j439skq.js.map → chunk-m2f4n0mq.js.map} +1 -1
- package/dist/{chunk-0zakpsep.js → chunk-m3fbewhz.js} +3 -3
- package/dist/{chunk-0zakpsep.js.map → chunk-m3fbewhz.js.map} +1 -1
- package/dist/{chunk-ejvamy3q.js → chunk-n4kz9vft.js} +1 -1
- package/dist/{chunk-vsr08sbe.js → chunk-n84v63hn.js} +2 -2
- package/dist/{chunk-vsr08sbe.js.map → chunk-n84v63hn.js.map} +1 -1
- package/dist/{chunk-m4wagwhr.js → chunk-naj8bmj5.js} +2 -2
- package/dist/{chunk-m4wagwhr.js.map → chunk-naj8bmj5.js.map} +1 -1
- package/dist/{chunk-6xt7w9bb.js → chunk-np6vee9d.js} +3 -3
- package/dist/{chunk-6xt7w9bb.js.map → chunk-np6vee9d.js.map} +1 -1
- package/dist/{chunk-bm4hjbbk.js → chunk-pfkbhqp7.js} +2 -2
- package/dist/{chunk-bm4hjbbk.js.map → chunk-pfkbhqp7.js.map} +1 -1
- package/dist/{chunk-ngbrbeg2.js → chunk-px9h2qgv.js} +3 -3
- package/dist/{chunk-ngbrbeg2.js.map → chunk-px9h2qgv.js.map} +1 -1
- package/dist/{chunk-0dp6jvrg.js → chunk-qvn0w2rt.js} +2 -2
- package/dist/{chunk-0dp6jvrg.js.map → chunk-qvn0w2rt.js.map} +1 -1
- package/dist/{chunk-c3jg93sn.js → chunk-sh2bd09k.js} +2 -2
- package/dist/{chunk-c3jg93sn.js.map → chunk-sh2bd09k.js.map} +1 -1
- package/dist/{chunk-dqb257xv.js → chunk-sv2mv2q2.js} +2 -2
- package/dist/{chunk-dqb257xv.js.map → chunk-sv2mv2q2.js.map} +1 -1
- package/dist/{chunk-ph7cjs7e.js → chunk-t2p5n8fe.js} +2 -2
- package/dist/{chunk-ph7cjs7e.js.map → chunk-t2p5n8fe.js.map} +1 -1
- package/dist/{chunk-11yrxwkt.js → chunk-t60krz4g.js} +2 -2
- package/dist/{chunk-11yrxwkt.js.map → chunk-t60krz4g.js.map} +1 -1
- package/dist/{chunk-30zs008n.js → chunk-t6x1r5n6.js} +3 -3
- package/dist/{chunk-30zs008n.js.map → chunk-t6x1r5n6.js.map} +1 -1
- package/dist/{chunk-rgcdf5pb.js → chunk-t929a66m.js} +2 -2
- package/dist/{chunk-rgcdf5pb.js.map → chunk-t929a66m.js.map} +1 -1
- package/dist/{chunk-30jcs49q.js → chunk-ts75gcfd.js} +2 -2
- package/dist/{chunk-ct8eh241.js.map → chunk-ts75gcfd.js.map} +1 -1
- package/dist/{chunk-t17vf1ep.js → chunk-w225pkpp.js} +2 -2
- package/dist/{chunk-t17vf1ep.js.map → chunk-w225pkpp.js.map} +1 -1
- package/dist/{chunk-c71dr883.js → chunk-x185900b.js} +3 -3
- package/dist/{chunk-c71dr883.js.map → chunk-x185900b.js.map} +1 -1
- package/dist/{chunk-djhr379j.js → chunk-x2dmgge8.js} +2 -2
- package/dist/{chunk-djhr379j.js.map → chunk-x2dmgge8.js.map} +1 -1
- package/dist/{chunk-76sp9knq.js → chunk-x6a5qxpa.js} +2 -2
- package/dist/{chunk-76sp9knq.js.map → chunk-x6a5qxpa.js.map} +1 -1
- package/dist/{chunk-607nk925.js → chunk-xtpx3f5t.js} +3 -3
- package/dist/{chunk-607nk925.js.map → chunk-xtpx3f5t.js.map} +1 -1
- package/dist/{chunk-b9gwjs4r.js → chunk-y2vayxcd.js} +2 -2
- package/dist/{chunk-b9gwjs4r.js.map → chunk-y2vayxcd.js.map} +1 -1
- package/dist/{chunk-xd4kvswv.js → chunk-y56xd7sv.js} +2 -2
- package/dist/{chunk-xd4kvswv.js.map → chunk-y56xd7sv.js.map} +1 -1
- package/dist/{chunk-xkrfxcm7.js → chunk-yahabnz4.js} +3 -3
- package/dist/{chunk-xkrfxcm7.js.map → chunk-yahabnz4.js.map} +1 -1
- package/dist/{chunk-keqjdy8q.js → chunk-z3tk66vh.js} +2 -2
- package/dist/{chunk-keqjdy8q.js.map → chunk-z3tk66vh.js.map} +1 -1
- package/dist/{chunk-jkhtybga.js → chunk-zm6b938z.js} +3 -3
- package/dist/{chunk-jkhtybga.js.map → chunk-zm6b938z.js.map} +1 -1
- package/dist/{chunk-7vkqcrfn.js → chunk-zt4hybgg.js} +2 -2
- package/dist/{chunk-7vkqcrfn.js.map → chunk-zt4hybgg.js.map} +1 -1
- package/dist/config/index.js +1 -1
- package/dist/console/run.js +2 -2
- package/dist/console/run.js.map +1 -1
- package/dist/container/index.js +2 -2
- package/dist/container/index.js.map +1 -1
- package/dist/database/index.js +2 -2
- package/dist/database/index.js.map +1 -1
- package/dist/email/index.js +2 -2
- package/dist/email/index.js.map +1 -1
- package/dist/facades/index.js +2 -2
- package/dist/facades/index.js.map +1 -1
- package/dist/foundation/index.js +2 -2
- package/dist/foundation/index.js.map +1 -1
- package/dist/http/index.js +2 -2
- package/dist/http/index.js.map +1 -1
- package/dist/i18n/dictionaryRuntime.js +2 -2
- package/dist/i18n/dictionaryRuntime.js.map +1 -1
- package/dist/i18n/index.js +2 -2
- package/dist/i18n/index.js.map +1 -1
- package/dist/kernel/index.js +2 -2
- package/dist/kernel/index.js.map +1 -1
- package/dist/orm/index.js +2 -2
- package/dist/orm/index.js.map +1 -1
- package/dist/probe/index.js +2 -2
- package/dist/probe/index.js.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/services/index.js +9 -9
- package/dist/services/index.js.map +3 -4
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/services/rate-limiter/RateLimiterServiceProvider.d.ts +6 -0
- package/dist/services/rate-limiter/RateLimiterServiceProvider.d.ts.map +1 -1
- package/dist/services/rate-limiter/drivers/DatabaseRateLimiterDriver.d.ts +18 -0
- package/dist/services/rate-limiter/drivers/DatabaseRateLimiterDriver.d.ts.map +1 -1
- package/dist/stats/route-table.js +1 -1
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/dist/vitest/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-1eha67ey.js +0 -10
- package/dist/chunk-rqzpxeb5.js +0 -5
- /package/dist/{chunk-mcgcgm6g.js.map → chunk-1w6ra6jc.js.map} +0 -0
- /package/dist/{chunk-tegjs0gg.js.map → chunk-2ver7cdt.js.map} +0 -0
- /package/dist/{chunk-j7swq19b.js.map → chunk-4mha212g.js.map} +0 -0
- /package/dist/{chunk-3v8b2kdr.js.map → chunk-7fbnw7e2.js.map} +0 -0
- /package/dist/{chunk-g0t49jec.js.map → chunk-aj9atkwk.js.map} +0 -0
- /package/dist/{chunk-ejvamy3q.js.map → chunk-n4kz9vft.js.map} +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Wh as IF}from"./chunk-jkhtybga.js";import{oi as _F}from"./chunk-mgvrfhy8.js";import{Ai as _8,Bi as I8,Ci as SB,Di as c5,Fi as $3,Gi as W8,Hi as Z2,Ii as w2,Ji as d,Li as A8,Mi as k$,Ni as i2,Oi as q2,Pi as f2,Qi as z6,Ri as A,Si as I5,Ti as s8,Ui as LZ,Vi as S8,Wi as L6,Yi as q$,Zi as a4,gj as M6,mj as H6,pi as B3,ti as kB,ui as U9,uj as E1,vi as D9,wi as C8,xi as K8,yj as QZ}from"./chunk-vjqpcet2.js";import{Aj as o1,Bj as f0,Cj as t1,Dj as L9}from"./chunk-jqqyj6cr.js";import{Ij as h,Lj as JQ,Mj as GZ}from"./chunk-30zs008n.js";import{Nj as WZ,Oj as W2,Sj as jY,Tj as Y8,Uj as P}from"./chunk-m4wagwhr.js";import{Xj as lG,_j as i3}from"./chunk-6xt7w9bb.js";import{ck as HY,fk as WF}from"./chunk-c5kd7eac.js";import{Ck as a1,xk as w$}from"./chunk-9bjggtdt.js";import{Qk as CG}from"./chunk-efnerp0c.js";import{Rk as BZ,Uk as ZF,el as r3}from"./chunk-0zakpsep.js";import{gl as N$}from"./chunk-djhr379j.js";import{Al as NF,Bl as PF,Cl as KF,hl as Q6,il as Z$,jl as J$,kl as M8,ll as HF,ml as BJ,nl as m7,ol as TF,yl as H8}from"./chunk-qgka1mvf.js";import{Rl as W$}from"./chunk-znh1mbqs.js";import{$l as l5,Wl as u5}from"./chunk-g0mxdh2x.js";import{gm as d5,lm as u}from"./chunk-7ka1abkd.js";import{mm as eZ,pm as H}from"./chunk-6fpjc2eg.js";import{xm as v5}from"./chunk-1v1ek1ey.js";import{Mm as E5}from"./chunk-x8by5j7p.js";import{Nm as z8,Pm as wB}from"./chunk-kfcz4qa8.js";import{Um as s5}from"./chunk-30jcs49q.js";function W6($){return typeof $==="function"&&$.prototype!==void 0}var P2=Symbol.for("gemi.HttpResponse"),RF=new Set([301,302,303,307,308]);class V1{kind;body;status;headers;[P2]=!0;constructor($,Z,J,W){this.kind=$;this.body=Z;this.status=J;this.headers=W}static json($,Z={}){let J=Z.status??200;return N2(J,"json"),new V1("json",$,J,new Headers(Z.headers))}static error($,Z,J={}){if(!Number.isInteger($)||$<400||$>599)throw RangeError(`HttpResponse.error: status must be an integer from 400 to 599, got ${$}.`);return V1.json({error:Z},{...J,status:$})}static redirect($,Z={}){let J=Z.status??303;if(!RF.has(J))throw RangeError(`HttpResponse.redirect: status must be 301, 302, 303, 307 or 308, got ${J}.`);let W=String($);if(W==="")throw TypeError("HttpResponse.redirect: url is empty.");let Y=new Headers(Z.headers);return Y.set("Location",W),new V1("empty",void 0,J,Y)}static noContent($={}){return new V1("empty",null,204,new Headers($.headers))}static text($,Z={}){let J=Z.status??200;return N2(J,"text"),new V1("text",$,J,new Headers(Z.headers))}get ok(){return this.status>=200&&this.status<300}toResponse($,Z){let J=$,W=this.serialize(J);for(let Y of Z)J.append("Set-Cookie",Y);this.headers.forEach((Y,j)=>{if(j.toLowerCase()!=="set-cookie")J.set(j,Y)});for(let Y of this.headers.getSetCookie())J.append("Set-Cookie",Y);if(this.status>=400&&!this.headers.has("Cache-Control"))J.set("Cache-Control","no-store");return new Response(W,{status:this.status,headers:J})}serialize($){switch(this.kind){case"json":return $.set("Content-Type","application/json"),JSON.stringify(this.body)??null;case"text":return $.set("Content-Type","text/plain; charset=utf-8"),this.body;case"empty":return $.delete("Content-Type"),null}}}function N2($,Z){if(!Number.isInteger($)||$<200||$>599)throw RangeError(`HttpResponse.${Z}: status must be an integer from 200 to 599, got ${$}.`);if($===204||$===205||$===304)throw RangeError(`HttpResponse.${Z}: a ${$} response has no body.${$===204?" Use HttpResponse.noContent().":""}`)}function i1($){return typeof $==="object"&&$!==null&&$[P2]===!0}function kF($,Z,J={}){return V1.error($,Z,J)}function r0($){return typeof $==="string"?[$]:$}function Y6($,Z){let J=$.split(/[\\/]/).pop()??"",W=Z?"attachment":"inline",Y=J.replace(/["\\]/g,"").replace(/[^\x20-\x7e]/g,"_");return`${W}; filename="${Y}"; filename*=UTF-8''${encodeURIComponent(J)}`}function wF($){return"total"in $&&"partial"in $&&"body"in $}function K2(){return new Response("Not found",{status:404,headers:{"X-Content-Type-Options":"nosniff"}})}function z3($){return new Response(null,{status:416,headers:{"Accept-Ranges":"bytes","Content-Range":I8($),"Content-Length":"0","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}async function qF($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(wF($))return{body:$.body,start:$.start,end:$.end,total:$.total,partial:$.partial,type:$.type,name:$.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}};let Z=$.file,J=Z instanceof Blob?Z:null,W=$.total??J?.size??-1;return{body:Z,start:$.start??0,end:$.end??W-1,total:W,partial:$.partial??!1,type:$.type??J?.type??"",name:$.name??Z?.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}}}async function x8($,Z){if($ instanceof Response)return $;if(!$)return K2();let J=await qF($),{body:W,start:Y,end:j,total:z,partial:X}=J;if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return K2()}let{range:G}=Z;if(G){if(z<=0)return z3(Math.max(z,0));if(!X){if(W instanceof Blob){let B=K8(G,z);if(!B)return z3(z);W=W.slice(B.start,B.end+1),Y=B.start,j=B.end,X=!0}}}let Q=Boolean(G)&&X,F=Q?206:J.status,V=new Headers;if(V.set("Accept-Ranges","bytes"),V.set("Content-Type",J.type||"application/octet-stream"),V.set("X-Content-Type-Options","nosniff"),Q)V.set("Content-Range",_8(Y,j,z)),V.set("Content-Length",String(j-Y+1));else if(z>=0)V.set("Content-Length",String(z));if(J.name)V.set("Content-Disposition",Y6(J.name,J.download));if(J.etag)V.set("ETag",J.etag);if(J.lastModified)V.set("Last-Modified",J.lastModified.toUTCString());for(let[B,U]of Object.entries(J.extraHeaders))V.set(B,U);if((Z.method??"GET").toUpperCase()==="HEAD"){if(W&&"cancel"in W&&typeof W.cancel==="function")await W.cancel();return new Response(null,{status:F,headers:V})}return new Response(W,{status:F,headers:V})}var fF=["content-type"];var _2=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function vF($){try{let Z=new URL($);return Z.origin!=="null"&&Z.origin===$}catch{return!1}}function X3($,Z){let J=(Y)=>{throw Error(`CORS policy on ${Z}: ${Y}`)};if($===null||typeof $!=="object")J('expected an object such as { origins: "*" } or `false`.');let W=$.origins==="*"?"*":typeof $.origins==="string"?[$.origins]:$.origins;if(W!=="*"){if(!Array.isArray(W)||W.length===0)J('`origins` must be "*", an origin or a non-empty list of origins.');for(let Y of W){if(Y==="*")J('"*" goes on its own (`origins: "*"`), not in a list.');if(Y!=="null"&&!vF(Y))J(`"${Y}" is not an origin. Write scheme, host and port only, e.g. "https://shop.example".`)}}if($.credentials){if(W==="*")J("`credentials: true` needs a list of exact origins: browsers refuse credentials with `*`, and echoing any origin with credentials lets every site read the answer as the user.");if(W.includes("null"))J('`credentials: true` cannot admit "null": any site can send `Origin: null` (a sandboxed frame), so credentials for it are credentials for everyone. Authenticate such callers with a token instead.')}for(let Y of $.methods??[])if(!_2.test(Y))J(`"${Y}" is not a method.`);for(let Y of[...$.headers??[],...$.exposeHeaders??[]])if(!_2.test(Y))J(`"${Y}" is not a header name.`);if($.maxAge!==void 0&&!(Number.isInteger($.maxAge)&&$.maxAge>=0))J("`maxAge` must be a whole number of seconds.");return{...$,origins:W}}function x2($,Z){return $.origins==="*"||$.origins.includes(Z)}function gF($,Z){return $.credentials===!0&&$.origins!=="*"&&Z!=="null"}function C2($,Z,J){if($.set("Access-Control-Allow-Origin",Z.origins==="*"?"*":J),gF(Z,J))$.set("Access-Control-Allow-Credentials","true");else $.delete("Access-Control-Allow-Credentials")}function A2($,Z){let J=($.get("Vary")??"").split(",").map((Y)=>Y.trim()).filter(Boolean);if(J.includes("*"))return;let W=J.map((Y)=>Y.toLowerCase());for(let Y of Z)if(!W.includes(Y.toLowerCase()))J.push(Y);$.set("Vary",J.join(", "))}function I2($,Z,J){if(Z.origins!=="*")A2($,["Origin"]);if(!J||!x2(Z,J))return;if(C2($,Z,J),Z.exposeHeaders?.length)$.set("Access-Control-Expose-Headers",Z.exposeHeaders.join(", "))}function S2($,Z,J){let W=J.headers.get("Origin");try{return I2($.headers,Z,W),$}catch{let Y=new Headers($.headers);return I2(Y,Z,W),new Response($.body,{status:$.status,statusText:$.statusText,headers:Y})}}function b2($){return $.method==="OPTIONS"&&$.headers.has("Access-Control-Request-Method")}function E2($,Z){let J=new Headers,W=$.headers.get("Origin"),Y=$.headers.get("Access-Control-Request-Method").trim().toUpperCase(),j=Z[Y];if(A2(J,["Origin","Access-Control-Request-Method","Access-Control-Request-Headers"]),!j||!W||!x2(j,W))return new Response(null,{status:204,headers:J});let z=Object.keys(Z).filter((F)=>Z[F]===j),X=j.methods?j.methods.map((F)=>F.toUpperCase()).filter((F)=>z.includes(F)):z;if(!X.includes(Y))return new Response(null,{status:204,headers:J});let G=(j.headers??fF).map((F)=>F.toLowerCase());if(($.headers.get("Access-Control-Request-Headers")??"").split(",").map((F)=>F.trim().toLowerCase()).filter(Boolean).some((F)=>!G.includes(F)))return new Response(null,{status:204,headers:J});if(C2(J,j,W),J.set("Access-Control-Allow-Methods",X.join(", ")),G.length)J.set("Access-Control-Allow-Headers",G.join(", "));return J.set("Access-Control-Max-Age",String(j.maxAge??600)),new Response(null,{status:204,headers:J})}function yF($){return W6($)}function R2($,Z){if($.length===0)return $();return $(Z??new A)}class n{method;handler;methodName;__internal_brand="RouteHandler";middlewares=[];__internal_bodyLimitDefault;constructor($,Z,J){this.method=$;this.handler=Z;this.methodName=J;this.handler=Z,this.methodName=J,this.method=$}get source(){if(!yF(this.handler)||typeof this.methodName!=="string")return;return{controller:this.handler,methodName:this.methodName}}__internal_use(){return{run:this.run.bind(this),middlewares:this.middlewares}}run($){if(this.source){let Z=new this.source.controller;return R2(Z[this.methodName].bind(Z),$)}return R2(this.handler,$)}middleware($){return this.middlewares=r0($),this}corsPolicy;cors($){return this.corsPolicy=$===!1?!1:X3($,`a ${this.method} route`),this}}class v2{url;headers;__internal_brand="ProxyHandler";middlewares=[];constructor($,Z){this.url=$;this.headers=Z}middleware($){return this.middlewares=r0($),this}corsPolicy;cors($){return this.corsPolicy=$===!1?!1:X3($,"a proxy route"),this}async run(){let $=new A,Z=$.headers.toJSON();for(let J of w2($.rawRequest))delete Z[J];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(J){if(f2($.rawRequest))throw new A8(q2($.rawRequest));throw J}}}class g2{constructor(...$){return new n(...$)}}class y2 extends n{__internal_brand="StreamHandler";async run($){let Z=P.getStore(),J=Z?.req?.rawRequest,W=C8(J?.headers.get("Range"));if(Z)Z.rangeRequest=W;try{let Y=await super.run($);if(i1(Y))return Y;return await x8(Y,{range:W,method:J?.method})}catch(Y){if(Y instanceof S8)return z3(Y.total);throw Y}finally{if(Z)Z.rangeRequest=null}}}class m2{constructor(...$){return new y2(...$)}}class h2{__internal_brand="ResourceRoutes";first;second;constructor($){this.first={get:new n("GET",$,"list"),post:new n("POST",$,"store")},this.second={get:new n("GET",$,"show"),put:new n("PUT",$,"update"),delete:new n("DELETE",$,"delete")}}middleware($){if($.list)this.first.get.middleware($.list);if($.store)this.first.post.middleware($.store);if($.show)this.second.get.middleware($.show);if($.update)this.second.put.middleware($.update);if($.delete)this.second.delete.middleware($.delete);return this}}class x0{static __brand="ApiRouter";routes={};middlewares=[];cors;middleware($){}get($,Z){return new n("GET",$,Z)}post($,Z){return new n("POST",$,Z)}put($,Z){return new n("PUT",$,Z)}patch($,Z){return new n("PATCH",$,Z)}delete($,Z){return new n("DELETE",$,Z)}resource($){return new h2($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${k2($)}.`);return mF($)}voice($){if($.kind!=="agent-controller")throw TypeError(`this.voice() takes an AgentController class, and got ${k2($)}.`);return hF($)}file($,Z){return new g2("GET",$,Z)}stream($,Z){return new m2("GET",$,Z)}proxy($,Z={}){return new v2($,Z)}}function k2($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function mF($){let Z={stream:new n("POST",$,"stream"),attach:new n("POST",$,"attach"),watch:new n("POST",$,"watch"),stop:new n("POST",$,"stop"),upload:new n("POST",$,"upload")};return Z.stream.__internal_bodyLimitDefault="none",Z.upload.__internal_bodyLimitDefault="upload",class extends x0{static __internal_brand="AgentRoute";static controller=$;static handlers=Z;routes={"/":Z.stream,"/attach":Z.attach,"/watch":Z.watch,"/stop":Z.stop,"/files":Z.upload};static middleware(W){if(W.stream)Z.stream.middleware(W.stream);if(W.attach)Z.attach.middleware(W.attach),Z.watch.middleware(W.attach);if(W.stop)Z.stop.middleware(W.stop);if(W.upload)Z.upload.middleware(W.upload);return this}}}function hF($){let Z={start:new n("POST",$,"voiceStart"),update:new n("PATCH",$,"voiceUpdate"),end:new n("DELETE",$,"voiceEnd")};return class extends x0{static __internal_brand="VoiceRoute";static controller=$;static handlers=Z;routes={"/":Z.start,"/:sessionId":{patch:Z.update,delete:Z.end}};static middleware(W){if(W.start)Z.start.middleware(W.start);if(W.update)Z.update.middleware(W.update);if(W.end)Z.end.middleware(W.end);return this}}}var s1="access_token";function R$($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function j6($,Z){let J=R$(Z);if(!J)return null;return(await $.getSession(J,Z.headers.get("User-Agent")))?.user??null}var pF=/^[A-Za-z0-9_-]+$/,cF=/^:[A-Za-z_][A-Za-z0-9_]*$/,p2=/^[A-Za-z0-9_-]{1,128}$/,dF=/^[A-Za-z0-9_.:-]+$/;class i extends Error{constructor($){super($);this.name="InvalidChannelError"}}function c2($){return typeof $==="object"&&$!==null&&typeof $.topic==="string"}function UZ($){if(typeof $!=="string"||$.length===0)throw new i("A channel pattern must be a non-empty string.");if($.length>255)throw new i(`The channel pattern "${$.slice(0,40)}\u2026" is longer than ${"255"} characters.`);let Z=$.split("."),J=new Set;for(let W of Z){if(cF.test(W)){let Y=W.slice(1);if(J.has(Y))throw new i(`The channel pattern "${$}" names the param "${Y}" twice.`);J.add(Y);continue}if(W.startsWith("__"))throw new i(`The channel "${$}" has the segment "${W}". Segments starting with "__" are reserved for gemi (driver control messages).`);if(!pF.test(W))throw new i(`The channel pattern "${$}" has an invalid segment "${W}". Segments are separated by dots and are either letters, digits, "_" and "-", or a param such as ":siteId".`)}return Z}function G3($,Z={}){let J=UZ($),W=new Set,Y=J.map((j)=>{if(!j.startsWith(":"))return j;let z=j.slice(1);W.add(z);let X=Z[z];if(X===void 0||X===null)throw new i(`The channel "${$}" needs the param "${z}".`);let G=typeof X==="number"&&Number.isFinite(X)?String(X):X;if(typeof G!=="string"||!p2.test(G))throw new i(`The param "${z}" of the channel "${$}" must be 1 to 128 letters, digits, "_" or "-". Use a public id in a channel name.`);return G}).join(".");for(let j of Object.keys(Z))if(!W.has(j))throw new i(`The channel "${$}" has no param "${j}".`);if(Y.length>255)throw new i(`The topic built from "${$}" is longer than 255 characters.`);return Y}function b8($){if(UZ($).some((J)=>J.startsWith(":")))throw new i(`"${$}" is a pattern, not a topic: pass its params, as in Broadcast.to("${$}", { ... }).`);return $}function d2($){if(typeof $!=="string"||$.length===0||$.length>64||!dF.test($))throw new i(`The event name "${String($).slice(0,40)}" must be 1 to 64 letters, digits, "_", "-", "." or ":".`);return $}function u2($,Z){if($===Z)return!0;if($===U0)return Z.startsWith(`${U0}.`)&&Z.split(".").length===2;let J=$.split("."),W=Z.split(".");if(J.length!==W.length)return!1;return J.every((Y,j)=>Y===W[j]||Y.startsWith(":")&&p2.test(W[j]))}var U0="user";function DZ($){let Z=typeof $==="object"&&$!==null?$.id:$;return G3(`${U0}.:id`,{id:Z})}class Z0{req;static runsOnRefusal=!1;config={};constructor($){this.req=$}run(...$){return{}}static configure($){let Z=this;return class extends Z{config=$}}}class X6 extends Z0{run($){let Z=$??this.config.limit;if(Z===void 0||Z==="")throw Error('`body-limit` needs a size, as in "body-limit:64kb".');let J=Z==="upload"?this.config.uploadLimit??k$("50mb"):k$(Z);return z6(this.req.rawRequest,J),{}}}function uF($){let Z=new Map;for(let J of $)if(typeof J==="string"){let[W,Y=""]=J.split(":");if(W.startsWith("-")){if(Z.has(W.replace("-","")))Z.delete(W.replace("-",""))}else Z.set(W,Y.split(",").filter(Boolean))}else Z.set(J,[]);return Z}function lF($){return{"body-limit":X6.configure({uploadLimit:$})}}class n1{config;static token="middleware";defaultBodyLimit;uploadBodyLimit;builtinAliases;constructor($){this.config=$;let Z=$.bodyLimit===null||$.bodyLimit===void 0?null:k$($.bodyLimit);this.defaultBodyLimit=Z===1/0?null:Z,this.uploadBodyLimit=k$($.uploadBodyLimit??"50mb"),this.builtinAliases=lF(this.uploadBodyLimit)}get aliases(){return{...this.builtinAliases,...this.config.aliases}}applyDefaultBodyLimit($,Z){if(this.defaultBodyLimit===null||Z==="none"||i2($))return;let J=Z==="upload"?Math.max(this.defaultBodyLimit,this.uploadBodyLimit):this.defaultBodyLimit;z6($,J,{checkDeclared:!1,uploadLimit:this.uploadBodyLimit})}assertGlobalMiddleware(){for(let $ of this.config.global){if(typeof $!=="string")continue;let[Z]=$.split(":");if(Z.startsWith("-"))throw Error(`Global middleware "${$}" cancels an alias, but nothing is inherited into the global list. Remove it.`);if(!this.aliases[Z])throw Error(`Global middleware "${Z}" is not a registered alias. Add it to \`aliases\` in the middleware config, or list the class itself.`)}}runGlobalMiddleware(){return this.runMiddleware(this.config.global)}runMiddleware($){let Z=new A,J=this.aliases,W=[];for(let[Y,j]of uF($).entries())if(typeof Y==="string"){let z=J[Y];if(z){let X=new z(Z);W.push({run:()=>X.run.call(X,...j),runsOnRefusal:l2(z)})}}else if(W6(Y)){let z=new Y(Z);W.push({run:z.run.bind(z),runsOnRefusal:l2(Y)})}else W.push({run:Y,runsOnRefusal:!1});return(async()=>{let Y={};for(let j=0;j<W.length;j++)try{Y={...Y,...await W[j].run()}}catch(z){throw await iF(W.slice(j+1)),z}return Y})()}}function l2($){return $?.runsOnRefusal===!0}async function iF($){for(let Z of $){if(!Z.runsOnRefusal)continue;try{await Z.run()}catch(J){console.error(J)}}}class G6{visibility;authorizer;middlewares=[];constructor($,Z){this.visibility=$;this.authorizer=Z}middleware($){return this.middlewares=[...this.middlewares,...r0($)],this}events(...$){return this}}class a2{static __brand="ChannelRouter";channels={};public(){return new G6("public")}private($){return new G6("private",$)}async authorize($,Z,J={},W={}){try{aF(this)}catch(G){return console.error("[gemi] The channel router is invalid, so every subscription is refused.",G),{ok:!1,code:"error"}}let Y=Object.hasOwn(this.channels,Z)?this.channels[Z]:void 0;if(!t2(Y))return{ok:!1,code:"unknown_channel"};let j=null;try{if(Z===U0){if(Object.keys(J??{}).length>0)return{ok:!1,code:"invalid_params"}}else j=G3(Z,J??{})}catch(G){if(G instanceof i)return{ok:!1,code:"invalid_params"};throw G}let z=Object.fromEntries(Object.entries(J??{}).map(([G,Q])=>[G,String(Q)])),X=new A($,z,"api",Z);return P.exit(()=>Q6.exit(()=>P.run(X,async()=>{let G=P.getStore();try{if(Y.middlewares.length>0)await H(n1).runMiddleware(Y.middlewares);if(Z===U0){let Q=await s2(X);if(!Q)return{ok:!1,code:"denied"};if(j=DZ(Q),Y.visibility==="private"&&Y.authorizer){if(await n2(Y.authorizer,X,z)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}if(Y.visibility==="private"){if((Y.authorizer?await n2(Y.authorizer,X,z):await s2(X)!==null)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}catch(Q){if(oF(Q))return{ok:!1,code:"denied"};return console.error(`[gemi] Authorizing the channel "${Z}" threw, so the subscription was refused.`,Q),{ok:!1,code:"error"}}finally{G.destroy()}},W.carried)))}}async function sF($,Z,J={},W={}){let Y=typeof $==="function"?new $:$;r2(Y);let j=W.as,z,X=null;if(j instanceof Request)z=j;else if(j&&typeof j==="object"&&j.rawRequest instanceof Request)z=j.rawRequest;else z=new Request("http://localhost/__gemi/socket"),X=j?{user:j}:null;return(await Y.authorize(z,Z,J,{carried:X})).ok}function t2($){let Z=$?.visibility;return typeof $==="object"&&$!==null&&Array.isArray($.middlewares)&&(Z==="public"||Z==="private")}async function s2($){if(!P.getStore().user&&R$($)===null)return null;try{return await q0.user()}catch(Z){if(Z?.name==="AuthenticationError")return null;throw Z}}function n2($,Z,J){if(nF($))return new $().authorize(Z,J);return $(Z,J)}function nF($){return typeof $==="function"&&typeof $.prototype?.authorize==="function"}function oF($){return $?.kind===o1||a1($)||w$($)}var o2=new WeakSet;function aF($){if(o2.has($))return;r2($),o2.add($)}function r2($){let Z=Object.entries($.channels),J=[];for(let[W,Y]of Z){if(!t2(Y))throw new i(`The channel "${W}" is not declared with this.public() or this.private().`);let j=UZ(W);if(j[0].startsWith(":"))throw new i(`The channel pattern "${W}" starts with a param. Start it with a literal segment, such as "site.:siteId", so it cannot overlap another channel.`);if(W!==U0&&j.length===2&&j[0]===U0)throw new i(`The channel pattern "${W}" can build user.<id>, which belongs to the "user" channel (the signed-in user's own). Declare "user" and emit with Broadcast.toUser(user), or name this channel differently.`);if(W!==U0&&Y.visibility==="private"&&!Y.authorizer&&j.some((z)=>z.startsWith(":")))throw new i(`The private channel "${W}" has params but no authorization, so every signed-in user could join every one of them. Pass a callback or a policy that checks the params: this.private((req, params) => ...).`);J.push({pattern:W,segments:W===U0?[U0,":id"]:j})}for(let W=0;W<J.length;W++)for(let Y=W+1;Y<J.length;Y++)if(tF(J[W].segments,J[Y].segments))throw new i(`The channel patterns "${J[W].pattern}" and "${J[Y].pattern}" can build the same topic, so a subscriber could join one's topics through the other's authorization. Make them differ in a literal segment.`)}function tF($,Z){if($.length!==Z.length)return!1;return $.every((J,W)=>J===Z[W]||J.startsWith(":")||Z[W].startsWith(":"))}class E8{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,J){this.as=$;this.input=Z;this.bind=J}}class B6{method;url;meta;__internal_brand="McpRoute";constructor($,Z,J){this.method=$;this.url=Z;this.meta=J}}class R8{tool;meta;__internal_brand="McpTool";constructor($,Z){this.tool=$;this.meta=Z}}function rF($){let Z=[],J="";for(let W of $)if(W==="_"||W==="-"||W===" "){if(J)Z.push(J);J=""}else if(W===W.toLowerCase())J+=W;else{if(J)Z.push(J);J=W.toLowerCase()}if(J)Z.push(J);return Z}function eF($,Z){let J=rF($);if(Z==="snake")return J.join("_");if(Z==="kebab")return J.join("-");return J.map((W,Y)=>Y===0?W:W[0].toUpperCase()+W.slice(1)).join("")}class e2{static __brand="McpRouter";routes={};scopes;param($){return new E8($.as,$.input,$.bind)}fromTool($,Z={}){return new R8($,Z)}fromApiRoute($,Z,J){return new B6($,Z,J)}fromApiRouteFor($,Z,J){let{name:W,audiences:Y,description:j,params:z,files:X,...G}=J,Q=`McpRouter.fromApiRouteFor("${$}", "${Z}")`,F=Object.keys(Y??{});if(F.length===0)throw Error(`${Q}: declare at least one audience.`);let V={},B=new Map;for(let U of F){let{name:O,casing:D,description:L,params:M,files:T,...N}=Y[U],K=O??(D?eF(W,D):W);if(B.has(K))throw Error(`${Q}: the audiences "${B.get(K)}" and "${U}" are both named "${K}". Give one its own name or casing.`);B.set(K,U);let R=typeof L==="function"?j===void 0?void 0:L(j):L??j;if(typeof R!=="string")throw Error(`${Q}: the audience "${U}" has no description, and there is no shared one.`);let C={...G,...N,description:R};if(z||M)C.params={...z,...M};if(X||T)C.files={...X,...T};V[K]=new B6($,Z,C)}return V}}function D0($,Z){return $.replace(/:([^/]+[*?]?)/g,(J,W)=>{let Y=W.endsWith("?")||W.endsWith("*"),j=Y?W.slice(0,-1):W,z=Z[j];if(z===void 0){if(Y)return"";if(import.meta.env.DEV)throw Error(`Missing parameter: ${j}`);console.error(`Missing parameter: ${j} in URL: ${$}`)}return String(z)}).replace(/\/\//g,"/").replace(/\/$/,"")}class k8 extends f0{constructor($,Z=307){super("Redirect error");this.name="RedirectError",this.payload={api:{status:200,data:{},directive:{kind:"Redirect",path:$}},view:{status:Z,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:$}}}}}class S1{static to($,...Z){let[J={}]=Z,{search:W={},params:Y={},permanent:j,status:z}={params:{},status:307,permanent:!1,...J},X=new URLSearchParams(W).toString();throw new k8([D0($,Y)||"/",X.toString()].filter(Boolean).join("?"),z??(j?301:307))}static external($,Z=307){throw new k8($,Z)}}class $9{kind="redirect";viewPath="REDIRECT";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>({});else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(W)=>{return new Z()[J](W)}}}async run($,Z){let{destination:J,permanent:W=!1,status:Y=307}=await this.handler($);if(!J)throw Error(`Redirect destination is required see ${Z}`);return S1.to(J,{permanent:W,status:Y}),{}}middleware($){return this.middlewares=r0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function w8($,Z){if($ instanceof Response)return $;let J=$ instanceof Blob,W=J?$:$.file,Y=J?$.name:$.name??$.file?.name,j=(J?$.type:$.type??$.file?.type)||"",z=J?!1:$.download??!1,X=J?200:$.status??200;if(!J)for(let[G,Q]of Object.entries($.headers??{}))Z.set(G,Q);if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return new Response("Not found",{status:404})}if(Z.set("Content-Type",j||"application/octet-stream"),W instanceof Blob)Z.set("Content-Length",String(W.size));if(Y)Z.set("Content-Disposition",Y6(Y,z));return new Response(W instanceof Blob?W.stream():W,{status:X,headers:Z})}class Z9{kind="file";viewPath="FILE";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>null;else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(W)=>{return new Z()[J](W)}}}async run($,Z){let J=await this.handler($);if(!J)throw Error(`File route handler must return a file see ${Z}`);return{FILE:J}}middleware($){return this.middlewares=r0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}function J9($,Z){if(i1($))throw Error(`The handler of view "${Z}" returned an HttpResponse. HttpResponse is for api routes; a view handler returns its props.`);return $}class W9{viewPath;middlewares=[];featureGates=[];staticOptions=null;handler;constructor($,Z){this.viewPath=$;if(!Z)this.handler=()=>({});else if(typeof Z==="function")this.handler=Z;else{let[J,W]=Z;this.handler=(Y)=>{return new J()[W](Y)}}}async run($,Z){let J=J9(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}middleware($){return this.middlewares=r0($),this}static($={}){return this.staticOptions={...$},this}feature($){return this.featureGates=[...this.featureGates,$],this}}class Y9{viewPath;children;middlewares=[];featureGates=[];alwaysRuns=!1;handler=()=>({});constructor($,Z,J){this.viewPath=$;if(typeof Z==="function")this.handler=Z,this.children=class extends b1{routes=J??{}};else if(Array.isArray(Z)){let[W,Y]=Z;this.handler=(j)=>{return new W()[Y](j)},this.children=class extends b1{routes=J??{}}}else this.children=class extends b1{routes=Z},this.handler=()=>({})}async run($,Z){let J=J9(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}alwaysRun(){return this.alwaysRuns=!0,this}middleware($){return this.middlewares=r0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class b1{middlewares=[];featureGates=[];routes={};view($,Z){return new W9($,Z)}file($){return new Z9($)}redirect($){return new $9($)}layout($,Z,J){return new Y9($,Z,J)}}function $V($){return $}function ZV(){return{aliases:{},global:[],bodyLimit:"1mb",uploadBodyLimit:"50mb"}}var l0="redirect";function U1($,Z="/"){if(typeof $!=="string"||!$.startsWith("/"))return Z;if(/[\u0000-\u001f\u007f\\]/.test($)||$.startsWith("//"))return Z;try{let J=new URL($,"http://gemi.invalid");if(J.origin!=="http://gemi.invalid")return Z;let W=`${J.search}${J.hash}`.replaceAll("/","%2F"),Y=`${J.pathname}${W}`.replaceAll(":","%3A");return Y.startsWith("//")?Z:Y}catch{return Z}}function OZ($){let Z=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return Z?Z==="https":new URL($.url).protocol==="https:"}function q8($){return/^(https?:\/\/|\/\/)/i.test($??"")}function JV($,Z=!0){let J=new URL($.rawRequest.url),W=J.pathname.replace(/\.(json|og)$/,""),[,Y,...j]=W.split("/");if(H(u).supportedLocales.includes(Y))W=`/${j.join("/")}`;return Z?`${W}${J.search}`:W}function WV($,Z){let J=(W)=>W.replace(/\/+$/,"")||"/";return J($)===J(Z)}function F6($,Z){let J=Z||H(E).config.signInPath,W=/^[a-z][a-z\d+.-]*:/i.test(J);if(W?!/^https?:\/\//i.test(J):!J.startsWith("/"))throw Error(`\`auth.signInPath\` must be a path like "/auth/sign-in", or an http(s) URL for sign-in hosted elsewhere. Got "${J}". A route's own \`"auth:<path>"\` cannot carry a URL, because the alias parser splits it on the colon.`);let Y=new URL(J,"http://gemi.invalid");if($?.kind==="view"){let j=JV($,!W);if(W||!WV(new URL(j,Y).pathname,Y.pathname))Y.searchParams.set(l0,j)}return W?Y.href:`${Y.pathname}${Y.search}`}class j9 extends Z0{async run($){let Z=P.getStore(),J=Z.req;if(Z.user)return{};let W=await j6(H(E),J);if(!W)throw new q$({redirectTo:F6(J,$)});return Z.setUser(W),{}}}var v8="gemi_same_site",f8="private, no-cache, no-store, max-age=0, must-revalidate";class V6 extends Z0{run(){let $=P.getStore(),Z=$?.req;if(!Z||$.user)return{};let J=Z.rawRequest;if(Z.kind!=="view"||J.method!=="GET"&&J.method!=="HEAD")return{};let W=new URL(J.url);if(/\.(json|og)$/.test(W.pathname))return{};if(W.searchParams.has(v8))return{};if(R$(Z))return{};let Y=J.headers.get("Sec-Fetch-Site");if(Y&&Y!=="cross-site")return{};throw W.searchParams.set(v8,"1"),new z9(`${W.pathname}${W.search}`)}}class z9 extends f0{location;constructor($){super("Same-site bounce");this.location=$;this.name="SameSiteBounce";let Z=YV($),J={"Content-Type":"text/html; charset=utf-8","Cache-Control":f8,"Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex"};this.payload={api:{status:401,data:{},headers:{"Cache-Control":f8}},viewData:{status:200,data:{},headers:{"Cache-Control":f8},directive:{kind:"Redirect",path:$}},view:{status:200,headers:J,body:`<!doctype html><html><head><meta charset="utf-8"><meta name="robots" content="noindex"><meta name="referrer" content="no-referrer"><meta http-equiv="refresh" content="0;url=${Z}"><title>Redirecting</title></head><body><p><a href="${Z}">Continue</a></p></body></html>`}}}}function YV($){return $.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}class X9 extends Z0{async run(...$){let[Z="public",J="864000",...W]=$,Y=`${Z}, max-age=${J}${W.length>0?", ":""}${W.join(", ")}`;if($.length===0)Y="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="public")Y="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="private")Y="private, max-age=0, stale-while-revalidate=300, stale-if-error=600";if(this.req.rawRequest.method==="GET")this.req.ctx().setHeaders("Cache-Control",Y);return{}}}var G9={"Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Allow-Credentials":"true"};class Q9 extends Z0{static runsOnRefusal=!0;config={origins:{"":{"Access-Control-Allow-Methods":"GET, HEAD, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Allow-Credentials":"true"}}};run(){let $=this.req,Z=$.rawRequest.headers.get("Origin");if(Z&&this.config.origins[Z]){$.ctx().setHeaders("Access-Control-Allow-Origin",Z);let J={...G9,...this.config.origins[Z]};if(Z==="null")delete J["Access-Control-Allow-Credentials"];for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}else if(Z&&this.config.origins["*"]){$.ctx().setHeaders("Access-Control-Allow-Origin","*");let J={...G9,...this.config.origins["*"]};delete J["Access-Control-Allow-Credentials"];for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}return{}}}var jV="Rate limit exceeded";class r1 extends f0{result;retryAfter;constructor($,Z=jV){super(Z);this.result=$;this.retryAfter=$?.retryAfter;let J={"Content-Type":"application/json",...$?g8($):{}};this.payload={api:{status:429,data:{error:{...t1("rate_limit",Z,429),...$?{retryAfter:$.retryAfter}:{}}},headers:J},view:{error:{message:Z},status:429,headers:J}}}}function g8($){let Z={"X-RateLimit-Limit":String($.limit),"X-RateLimit-Remaining":String($.remaining),"X-RateLimit-Reset":String(Math.ceil($.resetAt/1000))};if(!$.allowed)Z["Retry-After"]=String(Math.max(1,Math.ceil($.retryAfter/1000)));return Z}class D1{config;static token="ratelimiter";constructor($){this.config=$}get driver(){return this.config.driver}async consume($,Z={}){let J=Z.limit??this.config.limit,W=Z.window??this.config.window,Y=Z.cost??1;if(B9("window",W),B9("limit",J),!Number.isFinite(Y)||Y<0)throw Error(`Rate limiter cost must be zero or greater, got ${Y}`);return await this.config.driver.consume({key:$,limit:J,window:W*1000,cost:Y})}async enforce($,Z={},J){let W=await this.consume($,Z);if(!W.allowed)throw new r1(W,typeof J==="function"?J(W):J);return W}}function B9($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}import{isIP as U6}from"net";function e1($){let Z=$.trim();if(Z==="")return null;if(Z.startsWith("[")){let W=Z.indexOf("]");if(W<0)return null;let Y=Z.slice(W+1);if(Y!==""&&!/^:\d{1,5}$/.test(Y))return null;let j=Z.slice(1,W);return U6(j)===6?j:null}if(U6(Z))return Z;let J=/^(\d{1,3}(?:\.\d{1,3}){3}):\d{1,5}$/.exec(Z);return J&&U6(J[1])===4?J[1]:null}function F9($,{ipv6Prefix:Z=64}={}){if(!Number.isInteger(Z)||Z<0||Z>128)throw RangeError(`ipv6Prefix must be a whole number from 0 to 128, not ${Z}.`);let J=e1($);if(J===null||U6(J)===4)return J??$;let W=zV(J);if(W===null)return $;if(W.slice(0,5).every((z)=>z===0)&&W[5]===65535)return`${W[6]>>8}.${W[6]&255}.${W[7]>>8}.${W[7]&255}`;let Y=W.map((z,X)=>{let G=Math.min(Math.max(Z-X*16,0),16);return z&(65535<<16-G&65535)}),j=XV(Y);return Z===128?j:`${j}/${Z}`}function zV($){let Z=$.split("%")[0].toLowerCase(),J=/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(Z);if(J){let[Q,F,V,B]=J.slice(1).map(Number);Z=`${Z.slice(0,J.index)}${(Q<<8|F).toString(16)}:${(V<<8|B).toString(16)}`}let[W,Y]=Z.split("::"),j=(Q)=>Q===""?[]:Q.split(":").map((F)=>parseInt(F,16)),z=j(W),X=Y===void 0?[]:j(Y),G=Y===void 0?z:[...z,...Array.from({length:8-z.length-X.length},()=>0),...X];return G.length===8&&G.every((Q)=>Q>=0&&Q<=65535)?G:null}function XV($){let Z=-1,J=0;for(let Y=0;Y<8;Y++){if($[Y]!==0)continue;let j=Y;while(j<8&&$[j]===0)j++;if(j-Y>J)Z=Y,J=j-Y;Y=j}let W=$.map((Y)=>Y.toString(16));if(J<2)return W.join(":");return`${W.slice(0,Z).join(":")}::${W.slice(Z+J).join(":")}`}class O9 extends Z0{async run($,Z){let J=GV();if(!J)return{};let W=await J.consume(this.key(),{limit:V9($)??this.config.limit,window:V9(Z)??this.config.window});if(this.config.headers!==!1){let Y=this.req.ctx?.();if(Y)for(let[j,z]of Object.entries(g8(W)))Y.setHeaders(j,z)}if(!W.allowed)throw new r1(W);return{}}key(){if(this.config.key)return this.config.key(this.req);let $=U9(this.req.rawRequest);if($)return`mcp:${$.via}:${$.id}:${this.req.routePath??"*"}`;return`${O6(this.req)}:${this.req.routePath??"*"}`}}function GV(){try{let $=H();return $.bound(D1)?$.make(D1):null}catch{return null}}function D6($){let Z=D9($.rawRequest);if(Z!==void 0)return Z;let J=$.headers.get("x-forwarded-for");if(J){let[W]=J.split(",");if(W?.trim())return e1(W)??W.trim()}return $.headers.get("x-real-ip")?.trim()||"unknown"}function O6($,Z){return F9(D6($),Z)}function V9($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}class M9 extends Z0{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new y8;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new y8;return{}}}class y8 extends f0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:L9("csrf","Invalid CSRF token",403)}},view:{}}}class H9{policiesList={};constructor(){let $=this.register();for(let Z of $){let J=new Z;this.policiesList[Z.name]=J}}register(){return[]}}class T9{all($,Z){return!0}}class m8{options;param;refuse;answers=new WeakMap;constructor($){this.options=$;this.param=$.param,this.refuse=$.refuse??"not_found"}refusal(){return this.refuse==="forbidden"?new LZ:new L6}authorize($,Z){if(typeof Z==="number"&&Number.isFinite(Z))Z=String(Z);if(typeof Z!=="string"||Z==="")return Promise.reject(this.refusal());let J=this.answers.get($.rawRequest);if(!J)J=new Map,this.answers.set($.rawRequest,J);let W=J.get(Z);if(!W)W=this.decide($,Z),J.set(Z,W);return W}async allows($,Z){try{return await this.authorize($,Z),!0}catch(J){if(this.isRefusal(J))return!1;throw J}}fromRoute($=new A,Z=this.param){if(Z===void 0)throw Error('This resource policy has no `param`. Give `defineResourcePolicy` one, or name it: `fromRoute(req, "pageId")`, or `alias:pageId` on the middleware.');return this.authorize($,$.params?.[Z])}get middleware(){if(!this.middlewareClass){let $=(Z,J)=>this.fromRoute(Z,J||void 0);this.middlewareClass=class extends Z0{async run(J){await $(this.req,J)}}}return this.middlewareClass}middlewareClass;forAgent($){return{authorize:async(Z,{threadId:J,body:W})=>{let Y;if(J!==void 0){if(Y=$.thread?await $.thread(J,Z):null,Y===null||Y===void 0)throw this.refusal()}if(W!==void 0){let j=await $.body(W,Z);if(await this.authorize(Z,j),J!==void 0&&String(Y)!==String(j))throw this.refusal();return}if(J!==void 0)await this.authorize(Z,Y)}}}async decide($,Z){let J=await this.options.load(Z,$);if(J===null||J===void 0||!await this.options.allow(J,$))throw this.refusal();return J}isRefusal($){return this.refuse==="forbidden"?$ instanceof LZ:$ instanceof L6}}function QV($){return new m8($)}async function T6($,Z,J=!1){if(!$.body)return new Uint8Array;let[W,Y]=await KV($.body),z=W.length>=2&&W[0]===31&&W[1]===139?Y.pipeThrough(new DecompressionStream("gzip")):Y;return PV(z,Z,J,$.url)}async function PV($,Z,J,W){let Y=$.getReader(),j=[],z=0;try{for(;;){let{done:Q,value:F}=await Y.read();if(Q)break;if(z+F.byteLength>Z){if(!J)throw new H6(W,Z);j.push(F.subarray(0,Z-z)),z=Z;break}j.push(F),z+=F.byteLength}}finally{Y.cancel().catch(()=>{})}let X=new Uint8Array(z),G=0;for(let Q of j)X.set(Q,G),G+=Q.byteLength;return X}async function KV($){let Z=$.getReader(),J=await Z.read(),W=J.done?new Uint8Array:J.value,Y=new ReadableStream({start(j){if(J.done)j.close();else j.enqueue(W)},async pull(j){let z=await Z.read();if(z.done)j.close();else j.enqueue(z.value)},cancel(j){return Z.cancel(j)}});return[W,Y]}function N6($){return new TextDecoder("utf-8").decode($)}var _V={"&":"&","<":"<",">":">",'"':""","'":"'"};function f$($){return $.replace(/[&<>"']/g,(Z)=>_V[Z])}var IV={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function h8($){if(!$.includes("&"))return $;return $.replace(/&(#x[0-9a-fA-F]{1,6}|#[0-9]{1,7}|[a-zA-Z]{2,4});/g,(Z,J)=>{if(J[0]!=="#")return IV[J]??Z;let W=J[1]==="x"?parseInt(J.slice(2),16):parseInt(J.slice(1),10);return W>0&&W<=1114111?String.fromCodePoint(W):Z})}function p8($){let Z=$.indexOf(":");return(Z===-1?$:$.slice(Z+1)).toLowerCase()}function N9($,Z){let J=$.length,W=0;while(W<J){if(Z.stopped?.())return;let Y=$.indexOf("<",W);if(Y===-1){Z.text(h8($.slice(W)));return}if(Y>W)Z.text(h8($.slice(W,Y)));if($.startsWith("<!--",Y)){let j=$.indexOf("-->",Y+4);if(j===-1)return;W=j+3}else if($.startsWith("<![CDATA[",Y)){let j=$.indexOf("]]>",Y+9);if(j===-1)return;Z.text($.slice(Y+9,j)),W=j+3}else if($.startsWith("<?",Y)){let j=$.indexOf("?>",Y+2);if(j===-1)return;W=j+2}else if($.startsWith("<!",Y)){let j=$.indexOf(">",Y+2);if(j===-1)return;let z=$.indexOf("[",Y+2);if(z!==-1&&z<j){let X=$.indexOf("]",z+1);if(X===-1)return;let G=$.indexOf(">",X+1);if(G===-1)return;W=G+1}else W=j+1}else if($[Y+1]==="/"){let j=$.indexOf(">",Y+2);if(j===-1)return;Z.close(p8($.slice(Y+2,j).trim())),W=j+1}else{let j=xV($,Y+1);if(j===-1)return;let z=$.slice(Y+1,j),X=z.endsWith("/");if(X)z=z.slice(0,-1);let G=z.search(/[\s]|$/),Q=p8(z.slice(0,G));if(Q){if(Z.open(Q,CV(z.slice(G)),X),X)Z.close(Q)}W=j+1}}}function xV($,Z){let J=null;for(let W=Z;W<$.length;W++){let Y=$[W];if(J){if(Y===J)J=null}else if(Y==='"'||Y==="'")J=Y;else if(Y===">")return W}return-1}function CV($){let Z={},J=/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;for(let W of $.matchAll(J))Z[p8(W[1])]=h8(W[2]??W[3]??"");return Z}class j0 extends Error{url;status;constructor($,Z=null,J=null){super($);this.url=Z;this.status=J;this.name="SitemapError"}}var x9="http://www.sitemaps.org/schemas/sitemap/0.9",AV="http://www.w3.org/1999/xhtml",u8=`<?xml version="1.0" encoding="UTF-8"?>
|
|
2
|
+
import{Xh as IF}from"./chunk-zm6b938z.js";import{pi as _F}from"./chunk-2kzysesp.js";import{Bi as _8,Ci as I8,Di as SB,Ei as c5,Gi as $3,Hi as W8,Ii as Z2,Ji as w2,Ki as d,Mi as A8,Ni as k$,Oi as i2,Pi as q2,Qi as f2,Ri as z6,Si as A,Ti as I5,Ui as s8,Vi as LZ,Wi as S8,Xi as L6,Zi as q$,_i as a4,hj as M6,nj as H6,qi as B3,ui as kB,vi as U9,vj as E1,wi as D9,xi as C8,yi as K8,zj as QZ}from"./chunk-fqndtpwm.js";import{Bj as o1,Cj as f0,Dj as t1,Ej as L9}from"./chunk-h1wmpa03.js";import{Jj as h,Mj as JQ,Nj as GZ}from"./chunk-t6x1r5n6.js";import{Oj as WZ,Pj as W2,Tj as jY,Uj as Y8,Vj as P}from"./chunk-naj8bmj5.js";import{$j as i3,Yj as lG}from"./chunk-np6vee9d.js";import{dk as HY,gk as WF}from"./chunk-5exrgw07.js";import{Dk as a1,yk as w$}from"./chunk-jssjfvsz.js";import{Rk as CG}from"./chunk-a119av2z.js";import{Sk as BZ,Vk as ZF,fl as r3}from"./chunk-m3fbewhz.js";import{hl as N$}from"./chunk-x2dmgge8.js";import{Bl as NF,Cl as PF,Dl as KF,il as Q6,jl as Z$,kl as J$,ll as M8,ml as HF,nl as BJ,ol as m7,pl as TF,zl as H8}from"./chunk-fs94x6ef.js";import{Sl as W$}from"./chunk-8476xvk9.js";import{Xl as u5,am as l5}from"./chunk-kvtvx64t.js";import{hm as d5,mm as u}from"./chunk-9jt5qj1b.js";import{nm as eZ,qm as H}from"./chunk-17ewxwga.js";import{ym as v5}from"./chunk-gt9ftnhn.js";import{Nm as E5}from"./chunk-ka8dzc6q.js";import{Om as z8,Qm as wB}from"./chunk-3y1h3ncf.js";import{Vm as s5}from"./chunk-ts75gcfd.js";function W6($){return typeof $==="function"&&$.prototype!==void 0}var P2=Symbol.for("gemi.HttpResponse"),RF=new Set([301,302,303,307,308]);class V1{kind;body;status;headers;[P2]=!0;constructor($,Z,J,W){this.kind=$;this.body=Z;this.status=J;this.headers=W}static json($,Z={}){let J=Z.status??200;return N2(J,"json"),new V1("json",$,J,new Headers(Z.headers))}static error($,Z,J={}){if(!Number.isInteger($)||$<400||$>599)throw RangeError(`HttpResponse.error: status must be an integer from 400 to 599, got ${$}.`);return V1.json({error:Z},{...J,status:$})}static redirect($,Z={}){let J=Z.status??303;if(!RF.has(J))throw RangeError(`HttpResponse.redirect: status must be 301, 302, 303, 307 or 308, got ${J}.`);let W=String($);if(W==="")throw TypeError("HttpResponse.redirect: url is empty.");let Y=new Headers(Z.headers);return Y.set("Location",W),new V1("empty",void 0,J,Y)}static noContent($={}){return new V1("empty",null,204,new Headers($.headers))}static text($,Z={}){let J=Z.status??200;return N2(J,"text"),new V1("text",$,J,new Headers(Z.headers))}get ok(){return this.status>=200&&this.status<300}toResponse($,Z){let J=$,W=this.serialize(J);for(let Y of Z)J.append("Set-Cookie",Y);this.headers.forEach((Y,j)=>{if(j.toLowerCase()!=="set-cookie")J.set(j,Y)});for(let Y of this.headers.getSetCookie())J.append("Set-Cookie",Y);if(this.status>=400&&!this.headers.has("Cache-Control"))J.set("Cache-Control","no-store");return new Response(W,{status:this.status,headers:J})}serialize($){switch(this.kind){case"json":return $.set("Content-Type","application/json"),JSON.stringify(this.body)??null;case"text":return $.set("Content-Type","text/plain; charset=utf-8"),this.body;case"empty":return $.delete("Content-Type"),null}}}function N2($,Z){if(!Number.isInteger($)||$<200||$>599)throw RangeError(`HttpResponse.${Z}: status must be an integer from 200 to 599, got ${$}.`);if($===204||$===205||$===304)throw RangeError(`HttpResponse.${Z}: a ${$} response has no body.${$===204?" Use HttpResponse.noContent().":""}`)}function i1($){return typeof $==="object"&&$!==null&&$[P2]===!0}function kF($,Z,J={}){return V1.error($,Z,J)}function r0($){return typeof $==="string"?[$]:$}function Y6($,Z){let J=$.split(/[\\/]/).pop()??"",W=Z?"attachment":"inline",Y=J.replace(/["\\]/g,"").replace(/[^\x20-\x7e]/g,"_");return`${W}; filename="${Y}"; filename*=UTF-8''${encodeURIComponent(J)}`}function wF($){return"total"in $&&"partial"in $&&"body"in $}function K2(){return new Response("Not found",{status:404,headers:{"X-Content-Type-Options":"nosniff"}})}function z3($){return new Response(null,{status:416,headers:{"Accept-Ranges":"bytes","Content-Range":I8($),"Content-Length":"0","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}async function qF($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(wF($))return{body:$.body,start:$.start,end:$.end,total:$.total,partial:$.partial,type:$.type,name:$.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}};let Z=$.file,J=Z instanceof Blob?Z:null,W=$.total??J?.size??-1;return{body:Z,start:$.start??0,end:$.end??W-1,total:W,partial:$.partial??!1,type:$.type??J?.type??"",name:$.name??Z?.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}}}async function x8($,Z){if($ instanceof Response)return $;if(!$)return K2();let J=await qF($),{body:W,start:Y,end:j,total:z,partial:X}=J;if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return K2()}let{range:G}=Z;if(G){if(z<=0)return z3(Math.max(z,0));if(!X){if(W instanceof Blob){let B=K8(G,z);if(!B)return z3(z);W=W.slice(B.start,B.end+1),Y=B.start,j=B.end,X=!0}}}let Q=Boolean(G)&&X,F=Q?206:J.status,V=new Headers;if(V.set("Accept-Ranges","bytes"),V.set("Content-Type",J.type||"application/octet-stream"),V.set("X-Content-Type-Options","nosniff"),Q)V.set("Content-Range",_8(Y,j,z)),V.set("Content-Length",String(j-Y+1));else if(z>=0)V.set("Content-Length",String(z));if(J.name)V.set("Content-Disposition",Y6(J.name,J.download));if(J.etag)V.set("ETag",J.etag);if(J.lastModified)V.set("Last-Modified",J.lastModified.toUTCString());for(let[B,U]of Object.entries(J.extraHeaders))V.set(B,U);if((Z.method??"GET").toUpperCase()==="HEAD"){if(W&&"cancel"in W&&typeof W.cancel==="function")await W.cancel();return new Response(null,{status:F,headers:V})}return new Response(W,{status:F,headers:V})}var fF=["content-type"];var _2=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function vF($){try{let Z=new URL($);return Z.origin!=="null"&&Z.origin===$}catch{return!1}}function X3($,Z){let J=(Y)=>{throw Error(`CORS policy on ${Z}: ${Y}`)};if($===null||typeof $!=="object")J('expected an object such as { origins: "*" } or `false`.');let W=$.origins==="*"?"*":typeof $.origins==="string"?[$.origins]:$.origins;if(W!=="*"){if(!Array.isArray(W)||W.length===0)J('`origins` must be "*", an origin or a non-empty list of origins.');for(let Y of W){if(Y==="*")J('"*" goes on its own (`origins: "*"`), not in a list.');if(Y!=="null"&&!vF(Y))J(`"${Y}" is not an origin. Write scheme, host and port only, e.g. "https://shop.example".`)}}if($.credentials){if(W==="*")J("`credentials: true` needs a list of exact origins: browsers refuse credentials with `*`, and echoing any origin with credentials lets every site read the answer as the user.");if(W.includes("null"))J('`credentials: true` cannot admit "null": any site can send `Origin: null` (a sandboxed frame), so credentials for it are credentials for everyone. Authenticate such callers with a token instead.')}for(let Y of $.methods??[])if(!_2.test(Y))J(`"${Y}" is not a method.`);for(let Y of[...$.headers??[],...$.exposeHeaders??[]])if(!_2.test(Y))J(`"${Y}" is not a header name.`);if($.maxAge!==void 0&&!(Number.isInteger($.maxAge)&&$.maxAge>=0))J("`maxAge` must be a whole number of seconds.");return{...$,origins:W}}function x2($,Z){return $.origins==="*"||$.origins.includes(Z)}function gF($,Z){return $.credentials===!0&&$.origins!=="*"&&Z!=="null"}function C2($,Z,J){if($.set("Access-Control-Allow-Origin",Z.origins==="*"?"*":J),gF(Z,J))$.set("Access-Control-Allow-Credentials","true");else $.delete("Access-Control-Allow-Credentials")}function A2($,Z){let J=($.get("Vary")??"").split(",").map((Y)=>Y.trim()).filter(Boolean);if(J.includes("*"))return;let W=J.map((Y)=>Y.toLowerCase());for(let Y of Z)if(!W.includes(Y.toLowerCase()))J.push(Y);$.set("Vary",J.join(", "))}function I2($,Z,J){if(Z.origins!=="*")A2($,["Origin"]);if(!J||!x2(Z,J))return;if(C2($,Z,J),Z.exposeHeaders?.length)$.set("Access-Control-Expose-Headers",Z.exposeHeaders.join(", "))}function S2($,Z,J){let W=J.headers.get("Origin");try{return I2($.headers,Z,W),$}catch{let Y=new Headers($.headers);return I2(Y,Z,W),new Response($.body,{status:$.status,statusText:$.statusText,headers:Y})}}function b2($){return $.method==="OPTIONS"&&$.headers.has("Access-Control-Request-Method")}function E2($,Z){let J=new Headers,W=$.headers.get("Origin"),Y=$.headers.get("Access-Control-Request-Method").trim().toUpperCase(),j=Z[Y];if(A2(J,["Origin","Access-Control-Request-Method","Access-Control-Request-Headers"]),!j||!W||!x2(j,W))return new Response(null,{status:204,headers:J});let z=Object.keys(Z).filter((F)=>Z[F]===j),X=j.methods?j.methods.map((F)=>F.toUpperCase()).filter((F)=>z.includes(F)):z;if(!X.includes(Y))return new Response(null,{status:204,headers:J});let G=(j.headers??fF).map((F)=>F.toLowerCase());if(($.headers.get("Access-Control-Request-Headers")??"").split(",").map((F)=>F.trim().toLowerCase()).filter(Boolean).some((F)=>!G.includes(F)))return new Response(null,{status:204,headers:J});if(C2(J,j,W),J.set("Access-Control-Allow-Methods",X.join(", ")),G.length)J.set("Access-Control-Allow-Headers",G.join(", "));return J.set("Access-Control-Max-Age",String(j.maxAge??600)),new Response(null,{status:204,headers:J})}function yF($){return W6($)}function R2($,Z){if($.length===0)return $();return $(Z??new A)}class n{method;handler;methodName;__internal_brand="RouteHandler";middlewares=[];__internal_bodyLimitDefault;constructor($,Z,J){this.method=$;this.handler=Z;this.methodName=J;this.handler=Z,this.methodName=J,this.method=$}get source(){if(!yF(this.handler)||typeof this.methodName!=="string")return;return{controller:this.handler,methodName:this.methodName}}__internal_use(){return{run:this.run.bind(this),middlewares:this.middlewares}}run($){if(this.source){let Z=new this.source.controller;return R2(Z[this.methodName].bind(Z),$)}return R2(this.handler,$)}middleware($){return this.middlewares=r0($),this}corsPolicy;cors($){return this.corsPolicy=$===!1?!1:X3($,`a ${this.method} route`),this}}class v2{url;headers;__internal_brand="ProxyHandler";middlewares=[];constructor($,Z){this.url=$;this.headers=Z}middleware($){return this.middlewares=r0($),this}corsPolicy;cors($){return this.corsPolicy=$===!1?!1:X3($,"a proxy route"),this}async run(){let $=new A,Z=$.headers.toJSON();for(let J of w2($.rawRequest))delete Z[J];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(J){if(f2($.rawRequest))throw new A8(q2($.rawRequest));throw J}}}class g2{constructor(...$){return new n(...$)}}class y2 extends n{__internal_brand="StreamHandler";async run($){let Z=P.getStore(),J=Z?.req?.rawRequest,W=C8(J?.headers.get("Range"));if(Z)Z.rangeRequest=W;try{let Y=await super.run($);if(i1(Y))return Y;return await x8(Y,{range:W,method:J?.method})}catch(Y){if(Y instanceof S8)return z3(Y.total);throw Y}finally{if(Z)Z.rangeRequest=null}}}class m2{constructor(...$){return new y2(...$)}}class h2{__internal_brand="ResourceRoutes";first;second;constructor($){this.first={get:new n("GET",$,"list"),post:new n("POST",$,"store")},this.second={get:new n("GET",$,"show"),put:new n("PUT",$,"update"),delete:new n("DELETE",$,"delete")}}middleware($){if($.list)this.first.get.middleware($.list);if($.store)this.first.post.middleware($.store);if($.show)this.second.get.middleware($.show);if($.update)this.second.put.middleware($.update);if($.delete)this.second.delete.middleware($.delete);return this}}class x0{static __brand="ApiRouter";routes={};middlewares=[];cors;middleware($){}get($,Z){return new n("GET",$,Z)}post($,Z){return new n("POST",$,Z)}put($,Z){return new n("PUT",$,Z)}patch($,Z){return new n("PATCH",$,Z)}delete($,Z){return new n("DELETE",$,Z)}resource($){return new h2($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${k2($)}.`);return mF($)}voice($){if($.kind!=="agent-controller")throw TypeError(`this.voice() takes an AgentController class, and got ${k2($)}.`);return hF($)}file($,Z){return new g2("GET",$,Z)}stream($,Z){return new m2("GET",$,Z)}proxy($,Z={}){return new v2($,Z)}}function k2($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function mF($){let Z={stream:new n("POST",$,"stream"),attach:new n("POST",$,"attach"),watch:new n("POST",$,"watch"),stop:new n("POST",$,"stop"),upload:new n("POST",$,"upload")};return Z.stream.__internal_bodyLimitDefault="none",Z.upload.__internal_bodyLimitDefault="upload",class extends x0{static __internal_brand="AgentRoute";static controller=$;static handlers=Z;routes={"/":Z.stream,"/attach":Z.attach,"/watch":Z.watch,"/stop":Z.stop,"/files":Z.upload};static middleware(W){if(W.stream)Z.stream.middleware(W.stream);if(W.attach)Z.attach.middleware(W.attach),Z.watch.middleware(W.attach);if(W.stop)Z.stop.middleware(W.stop);if(W.upload)Z.upload.middleware(W.upload);return this}}}function hF($){let Z={start:new n("POST",$,"voiceStart"),update:new n("PATCH",$,"voiceUpdate"),end:new n("DELETE",$,"voiceEnd")};return class extends x0{static __internal_brand="VoiceRoute";static controller=$;static handlers=Z;routes={"/":Z.start,"/:sessionId":{patch:Z.update,delete:Z.end}};static middleware(W){if(W.start)Z.start.middleware(W.start);if(W.update)Z.update.middleware(W.update);if(W.end)Z.end.middleware(W.end);return this}}}var s1="access_token";function R$($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function j6($,Z){let J=R$(Z);if(!J)return null;return(await $.getSession(J,Z.headers.get("User-Agent")))?.user??null}var pF=/^[A-Za-z0-9_-]+$/,cF=/^:[A-Za-z_][A-Za-z0-9_]*$/,p2=/^[A-Za-z0-9_-]{1,128}$/,dF=/^[A-Za-z0-9_.:-]+$/;class i extends Error{constructor($){super($);this.name="InvalidChannelError"}}function c2($){return typeof $==="object"&&$!==null&&typeof $.topic==="string"}function UZ($){if(typeof $!=="string"||$.length===0)throw new i("A channel pattern must be a non-empty string.");if($.length>255)throw new i(`The channel pattern "${$.slice(0,40)}\u2026" is longer than ${"255"} characters.`);let Z=$.split("."),J=new Set;for(let W of Z){if(cF.test(W)){let Y=W.slice(1);if(J.has(Y))throw new i(`The channel pattern "${$}" names the param "${Y}" twice.`);J.add(Y);continue}if(W.startsWith("__"))throw new i(`The channel "${$}" has the segment "${W}". Segments starting with "__" are reserved for gemi (driver control messages).`);if(!pF.test(W))throw new i(`The channel pattern "${$}" has an invalid segment "${W}". Segments are separated by dots and are either letters, digits, "_" and "-", or a param such as ":siteId".`)}return Z}function G3($,Z={}){let J=UZ($),W=new Set,Y=J.map((j)=>{if(!j.startsWith(":"))return j;let z=j.slice(1);W.add(z);let X=Z[z];if(X===void 0||X===null)throw new i(`The channel "${$}" needs the param "${z}".`);let G=typeof X==="number"&&Number.isFinite(X)?String(X):X;if(typeof G!=="string"||!p2.test(G))throw new i(`The param "${z}" of the channel "${$}" must be 1 to 128 letters, digits, "_" or "-". Use a public id in a channel name.`);return G}).join(".");for(let j of Object.keys(Z))if(!W.has(j))throw new i(`The channel "${$}" has no param "${j}".`);if(Y.length>255)throw new i(`The topic built from "${$}" is longer than 255 characters.`);return Y}function b8($){if(UZ($).some((J)=>J.startsWith(":")))throw new i(`"${$}" is a pattern, not a topic: pass its params, as in Broadcast.to("${$}", { ... }).`);return $}function d2($){if(typeof $!=="string"||$.length===0||$.length>64||!dF.test($))throw new i(`The event name "${String($).slice(0,40)}" must be 1 to 64 letters, digits, "_", "-", "." or ":".`);return $}function u2($,Z){if($===Z)return!0;if($===U0)return Z.startsWith(`${U0}.`)&&Z.split(".").length===2;let J=$.split("."),W=Z.split(".");if(J.length!==W.length)return!1;return J.every((Y,j)=>Y===W[j]||Y.startsWith(":")&&p2.test(W[j]))}var U0="user";function DZ($){let Z=typeof $==="object"&&$!==null?$.id:$;return G3(`${U0}.:id`,{id:Z})}class Z0{req;static runsOnRefusal=!1;config={};constructor($){this.req=$}run(...$){return{}}static configure($){let Z=this;return class extends Z{config=$}}}class X6 extends Z0{run($){let Z=$??this.config.limit;if(Z===void 0||Z==="")throw Error('`body-limit` needs a size, as in "body-limit:64kb".');let J=Z==="upload"?this.config.uploadLimit??k$("50mb"):k$(Z);return z6(this.req.rawRequest,J),{}}}function uF($){let Z=new Map;for(let J of $)if(typeof J==="string"){let[W,Y=""]=J.split(":");if(W.startsWith("-")){if(Z.has(W.replace("-","")))Z.delete(W.replace("-",""))}else Z.set(W,Y.split(",").filter(Boolean))}else Z.set(J,[]);return Z}function lF($){return{"body-limit":X6.configure({uploadLimit:$})}}class n1{config;static token="middleware";defaultBodyLimit;uploadBodyLimit;builtinAliases;constructor($){this.config=$;let Z=$.bodyLimit===null||$.bodyLimit===void 0?null:k$($.bodyLimit);this.defaultBodyLimit=Z===1/0?null:Z,this.uploadBodyLimit=k$($.uploadBodyLimit??"50mb"),this.builtinAliases=lF(this.uploadBodyLimit)}get aliases(){return{...this.builtinAliases,...this.config.aliases}}applyDefaultBodyLimit($,Z){if(this.defaultBodyLimit===null||Z==="none"||i2($))return;let J=Z==="upload"?Math.max(this.defaultBodyLimit,this.uploadBodyLimit):this.defaultBodyLimit;z6($,J,{checkDeclared:!1,uploadLimit:this.uploadBodyLimit})}assertGlobalMiddleware(){for(let $ of this.config.global){if(typeof $!=="string")continue;let[Z]=$.split(":");if(Z.startsWith("-"))throw Error(`Global middleware "${$}" cancels an alias, but nothing is inherited into the global list. Remove it.`);if(!this.aliases[Z])throw Error(`Global middleware "${Z}" is not a registered alias. Add it to \`aliases\` in the middleware config, or list the class itself.`)}}runGlobalMiddleware(){return this.runMiddleware(this.config.global)}runMiddleware($){let Z=new A,J=this.aliases,W=[];for(let[Y,j]of uF($).entries())if(typeof Y==="string"){let z=J[Y];if(z){let X=new z(Z);W.push({run:()=>X.run.call(X,...j),runsOnRefusal:l2(z)})}}else if(W6(Y)){let z=new Y(Z);W.push({run:z.run.bind(z),runsOnRefusal:l2(Y)})}else W.push({run:Y,runsOnRefusal:!1});return(async()=>{let Y={};for(let j=0;j<W.length;j++)try{Y={...Y,...await W[j].run()}}catch(z){throw await iF(W.slice(j+1)),z}return Y})()}}function l2($){return $?.runsOnRefusal===!0}async function iF($){for(let Z of $){if(!Z.runsOnRefusal)continue;try{await Z.run()}catch(J){console.error(J)}}}class G6{visibility;authorizer;middlewares=[];constructor($,Z){this.visibility=$;this.authorizer=Z}middleware($){return this.middlewares=[...this.middlewares,...r0($)],this}events(...$){return this}}class a2{static __brand="ChannelRouter";channels={};public(){return new G6("public")}private($){return new G6("private",$)}async authorize($,Z,J={},W={}){try{aF(this)}catch(G){return console.error("[gemi] The channel router is invalid, so every subscription is refused.",G),{ok:!1,code:"error"}}let Y=Object.hasOwn(this.channels,Z)?this.channels[Z]:void 0;if(!t2(Y))return{ok:!1,code:"unknown_channel"};let j=null;try{if(Z===U0){if(Object.keys(J??{}).length>0)return{ok:!1,code:"invalid_params"}}else j=G3(Z,J??{})}catch(G){if(G instanceof i)return{ok:!1,code:"invalid_params"};throw G}let z=Object.fromEntries(Object.entries(J??{}).map(([G,Q])=>[G,String(Q)])),X=new A($,z,"api",Z);return P.exit(()=>Q6.exit(()=>P.run(X,async()=>{let G=P.getStore();try{if(Y.middlewares.length>0)await H(n1).runMiddleware(Y.middlewares);if(Z===U0){let Q=await s2(X);if(!Q)return{ok:!1,code:"denied"};if(j=DZ(Q),Y.visibility==="private"&&Y.authorizer){if(await n2(Y.authorizer,X,z)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}if(Y.visibility==="private"){if((Y.authorizer?await n2(Y.authorizer,X,z):await s2(X)!==null)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}catch(Q){if(oF(Q))return{ok:!1,code:"denied"};return console.error(`[gemi] Authorizing the channel "${Z}" threw, so the subscription was refused.`,Q),{ok:!1,code:"error"}}finally{G.destroy()}},W.carried)))}}async function sF($,Z,J={},W={}){let Y=typeof $==="function"?new $:$;r2(Y);let j=W.as,z,X=null;if(j instanceof Request)z=j;else if(j&&typeof j==="object"&&j.rawRequest instanceof Request)z=j.rawRequest;else z=new Request("http://localhost/__gemi/socket"),X=j?{user:j}:null;return(await Y.authorize(z,Z,J,{carried:X})).ok}function t2($){let Z=$?.visibility;return typeof $==="object"&&$!==null&&Array.isArray($.middlewares)&&(Z==="public"||Z==="private")}async function s2($){if(!P.getStore().user&&R$($)===null)return null;try{return await q0.user()}catch(Z){if(Z?.name==="AuthenticationError")return null;throw Z}}function n2($,Z,J){if(nF($))return new $().authorize(Z,J);return $(Z,J)}function nF($){return typeof $==="function"&&typeof $.prototype?.authorize==="function"}function oF($){return $?.kind===o1||a1($)||w$($)}var o2=new WeakSet;function aF($){if(o2.has($))return;r2($),o2.add($)}function r2($){let Z=Object.entries($.channels),J=[];for(let[W,Y]of Z){if(!t2(Y))throw new i(`The channel "${W}" is not declared with this.public() or this.private().`);let j=UZ(W);if(j[0].startsWith(":"))throw new i(`The channel pattern "${W}" starts with a param. Start it with a literal segment, such as "site.:siteId", so it cannot overlap another channel.`);if(W!==U0&&j.length===2&&j[0]===U0)throw new i(`The channel pattern "${W}" can build user.<id>, which belongs to the "user" channel (the signed-in user's own). Declare "user" and emit with Broadcast.toUser(user), or name this channel differently.`);if(W!==U0&&Y.visibility==="private"&&!Y.authorizer&&j.some((z)=>z.startsWith(":")))throw new i(`The private channel "${W}" has params but no authorization, so every signed-in user could join every one of them. Pass a callback or a policy that checks the params: this.private((req, params) => ...).`);J.push({pattern:W,segments:W===U0?[U0,":id"]:j})}for(let W=0;W<J.length;W++)for(let Y=W+1;Y<J.length;Y++)if(tF(J[W].segments,J[Y].segments))throw new i(`The channel patterns "${J[W].pattern}" and "${J[Y].pattern}" can build the same topic, so a subscriber could join one's topics through the other's authorization. Make them differ in a literal segment.`)}function tF($,Z){if($.length!==Z.length)return!1;return $.every((J,W)=>J===Z[W]||J.startsWith(":")||Z[W].startsWith(":"))}class E8{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,J){this.as=$;this.input=Z;this.bind=J}}class B6{method;url;meta;__internal_brand="McpRoute";constructor($,Z,J){this.method=$;this.url=Z;this.meta=J}}class R8{tool;meta;__internal_brand="McpTool";constructor($,Z){this.tool=$;this.meta=Z}}function rF($){let Z=[],J="";for(let W of $)if(W==="_"||W==="-"||W===" "){if(J)Z.push(J);J=""}else if(W===W.toLowerCase())J+=W;else{if(J)Z.push(J);J=W.toLowerCase()}if(J)Z.push(J);return Z}function eF($,Z){let J=rF($);if(Z==="snake")return J.join("_");if(Z==="kebab")return J.join("-");return J.map((W,Y)=>Y===0?W:W[0].toUpperCase()+W.slice(1)).join("")}class e2{static __brand="McpRouter";routes={};scopes;param($){return new E8($.as,$.input,$.bind)}fromTool($,Z={}){return new R8($,Z)}fromApiRoute($,Z,J){return new B6($,Z,J)}fromApiRouteFor($,Z,J){let{name:W,audiences:Y,description:j,params:z,files:X,...G}=J,Q=`McpRouter.fromApiRouteFor("${$}", "${Z}")`,F=Object.keys(Y??{});if(F.length===0)throw Error(`${Q}: declare at least one audience.`);let V={},B=new Map;for(let U of F){let{name:O,casing:D,description:L,params:M,files:T,...N}=Y[U],K=O??(D?eF(W,D):W);if(B.has(K))throw Error(`${Q}: the audiences "${B.get(K)}" and "${U}" are both named "${K}". Give one its own name or casing.`);B.set(K,U);let R=typeof L==="function"?j===void 0?void 0:L(j):L??j;if(typeof R!=="string")throw Error(`${Q}: the audience "${U}" has no description, and there is no shared one.`);let C={...G,...N,description:R};if(z||M)C.params={...z,...M};if(X||T)C.files={...X,...T};V[K]=new B6($,Z,C)}return V}}function D0($,Z){return $.replace(/:([^/]+[*?]?)/g,(J,W)=>{let Y=W.endsWith("?")||W.endsWith("*"),j=Y?W.slice(0,-1):W,z=Z[j];if(z===void 0){if(Y)return"";if(import.meta.env.DEV)throw Error(`Missing parameter: ${j}`);console.error(`Missing parameter: ${j} in URL: ${$}`)}return String(z)}).replace(/\/\//g,"/").replace(/\/$/,"")}class k8 extends f0{constructor($,Z=307){super("Redirect error");this.name="RedirectError",this.payload={api:{status:200,data:{},directive:{kind:"Redirect",path:$}},view:{status:Z,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:$}}}}}class S1{static to($,...Z){let[J={}]=Z,{search:W={},params:Y={},permanent:j,status:z}={params:{},status:307,permanent:!1,...J},X=new URLSearchParams(W).toString();throw new k8([D0($,Y)||"/",X.toString()].filter(Boolean).join("?"),z??(j?301:307))}static external($,Z=307){throw new k8($,Z)}}class $9{kind="redirect";viewPath="REDIRECT";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>({});else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(W)=>{return new Z()[J](W)}}}async run($,Z){let{destination:J,permanent:W=!1,status:Y=307}=await this.handler($);if(!J)throw Error(`Redirect destination is required see ${Z}`);return S1.to(J,{permanent:W,status:Y}),{}}middleware($){return this.middlewares=r0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function w8($,Z){if($ instanceof Response)return $;let J=$ instanceof Blob,W=J?$:$.file,Y=J?$.name:$.name??$.file?.name,j=(J?$.type:$.type??$.file?.type)||"",z=J?!1:$.download??!1,X=J?200:$.status??200;if(!J)for(let[G,Q]of Object.entries($.headers??{}))Z.set(G,Q);if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return new Response("Not found",{status:404})}if(Z.set("Content-Type",j||"application/octet-stream"),W instanceof Blob)Z.set("Content-Length",String(W.size));if(Y)Z.set("Content-Disposition",Y6(Y,z));return new Response(W instanceof Blob?W.stream():W,{status:X,headers:Z})}class Z9{kind="file";viewPath="FILE";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>null;else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(W)=>{return new Z()[J](W)}}}async run($,Z){let J=await this.handler($);if(!J)throw Error(`File route handler must return a file see ${Z}`);return{FILE:J}}middleware($){return this.middlewares=r0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}function J9($,Z){if(i1($))throw Error(`The handler of view "${Z}" returned an HttpResponse. HttpResponse is for api routes; a view handler returns its props.`);return $}class W9{viewPath;middlewares=[];featureGates=[];staticOptions=null;handler;constructor($,Z){this.viewPath=$;if(!Z)this.handler=()=>({});else if(typeof Z==="function")this.handler=Z;else{let[J,W]=Z;this.handler=(Y)=>{return new J()[W](Y)}}}async run($,Z){let J=J9(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}middleware($){return this.middlewares=r0($),this}static($={}){return this.staticOptions={...$},this}feature($){return this.featureGates=[...this.featureGates,$],this}}class Y9{viewPath;children;middlewares=[];featureGates=[];alwaysRuns=!1;handler=()=>({});constructor($,Z,J){this.viewPath=$;if(typeof Z==="function")this.handler=Z,this.children=class extends b1{routes=J??{}};else if(Array.isArray(Z)){let[W,Y]=Z;this.handler=(j)=>{return new W()[Y](j)},this.children=class extends b1{routes=J??{}}}else this.children=class extends b1{routes=Z},this.handler=()=>({})}async run($,Z){let J=J9(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}alwaysRun(){return this.alwaysRuns=!0,this}middleware($){return this.middlewares=r0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class b1{middlewares=[];featureGates=[];routes={};view($,Z){return new W9($,Z)}file($){return new Z9($)}redirect($){return new $9($)}layout($,Z,J){return new Y9($,Z,J)}}function $V($){return $}function ZV(){return{aliases:{},global:[],bodyLimit:"1mb",uploadBodyLimit:"50mb"}}var l0="redirect";function U1($,Z="/"){if(typeof $!=="string"||!$.startsWith("/"))return Z;if(/[\u0000-\u001f\u007f\\]/.test($)||$.startsWith("//"))return Z;try{let J=new URL($,"http://gemi.invalid");if(J.origin!=="http://gemi.invalid")return Z;let W=`${J.search}${J.hash}`.replaceAll("/","%2F"),Y=`${J.pathname}${W}`.replaceAll(":","%3A");return Y.startsWith("//")?Z:Y}catch{return Z}}function OZ($){let Z=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return Z?Z==="https":new URL($.url).protocol==="https:"}function q8($){return/^(https?:\/\/|\/\/)/i.test($??"")}function JV($,Z=!0){let J=new URL($.rawRequest.url),W=J.pathname.replace(/\.(json|og)$/,""),[,Y,...j]=W.split("/");if(H(u).supportedLocales.includes(Y))W=`/${j.join("/")}`;return Z?`${W}${J.search}`:W}function WV($,Z){let J=(W)=>W.replace(/\/+$/,"")||"/";return J($)===J(Z)}function F6($,Z){let J=Z||H(E).config.signInPath,W=/^[a-z][a-z\d+.-]*:/i.test(J);if(W?!/^https?:\/\//i.test(J):!J.startsWith("/"))throw Error(`\`auth.signInPath\` must be a path like "/auth/sign-in", or an http(s) URL for sign-in hosted elsewhere. Got "${J}". A route's own \`"auth:<path>"\` cannot carry a URL, because the alias parser splits it on the colon.`);let Y=new URL(J,"http://gemi.invalid");if($?.kind==="view"){let j=JV($,!W);if(W||!WV(new URL(j,Y).pathname,Y.pathname))Y.searchParams.set(l0,j)}return W?Y.href:`${Y.pathname}${Y.search}`}class j9 extends Z0{async run($){let Z=P.getStore(),J=Z.req;if(Z.user)return{};let W=await j6(H(E),J);if(!W)throw new q$({redirectTo:F6(J,$)});return Z.setUser(W),{}}}var v8="gemi_same_site",f8="private, no-cache, no-store, max-age=0, must-revalidate";class V6 extends Z0{run(){let $=P.getStore(),Z=$?.req;if(!Z||$.user)return{};let J=Z.rawRequest;if(Z.kind!=="view"||J.method!=="GET"&&J.method!=="HEAD")return{};let W=new URL(J.url);if(/\.(json|og)$/.test(W.pathname))return{};if(W.searchParams.has(v8))return{};if(R$(Z))return{};let Y=J.headers.get("Sec-Fetch-Site");if(Y&&Y!=="cross-site")return{};throw W.searchParams.set(v8,"1"),new z9(`${W.pathname}${W.search}`)}}class z9 extends f0{location;constructor($){super("Same-site bounce");this.location=$;this.name="SameSiteBounce";let Z=YV($),J={"Content-Type":"text/html; charset=utf-8","Cache-Control":f8,"Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex"};this.payload={api:{status:401,data:{},headers:{"Cache-Control":f8}},viewData:{status:200,data:{},headers:{"Cache-Control":f8},directive:{kind:"Redirect",path:$}},view:{status:200,headers:J,body:`<!doctype html><html><head><meta charset="utf-8"><meta name="robots" content="noindex"><meta name="referrer" content="no-referrer"><meta http-equiv="refresh" content="0;url=${Z}"><title>Redirecting</title></head><body><p><a href="${Z}">Continue</a></p></body></html>`}}}}function YV($){return $.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}class X9 extends Z0{async run(...$){let[Z="public",J="864000",...W]=$,Y=`${Z}, max-age=${J}${W.length>0?", ":""}${W.join(", ")}`;if($.length===0)Y="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="public")Y="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="private")Y="private, max-age=0, stale-while-revalidate=300, stale-if-error=600";if(this.req.rawRequest.method==="GET")this.req.ctx().setHeaders("Cache-Control",Y);return{}}}var G9={"Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Allow-Credentials":"true"};class Q9 extends Z0{static runsOnRefusal=!0;config={origins:{"":{"Access-Control-Allow-Methods":"GET, HEAD, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Allow-Credentials":"true"}}};run(){let $=this.req,Z=$.rawRequest.headers.get("Origin");if(Z&&this.config.origins[Z]){$.ctx().setHeaders("Access-Control-Allow-Origin",Z);let J={...G9,...this.config.origins[Z]};if(Z==="null")delete J["Access-Control-Allow-Credentials"];for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}else if(Z&&this.config.origins["*"]){$.ctx().setHeaders("Access-Control-Allow-Origin","*");let J={...G9,...this.config.origins["*"]};delete J["Access-Control-Allow-Credentials"];for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}return{}}}var jV="Rate limit exceeded";class r1 extends f0{result;retryAfter;constructor($,Z=jV){super(Z);this.result=$;this.retryAfter=$?.retryAfter;let J={"Content-Type":"application/json",...$?g8($):{}};this.payload={api:{status:429,data:{error:{...t1("rate_limit",Z,429),...$?{retryAfter:$.retryAfter}:{}}},headers:J},view:{error:{message:Z},status:429,headers:J}}}}function g8($){let Z={"X-RateLimit-Limit":String($.limit),"X-RateLimit-Remaining":String($.remaining),"X-RateLimit-Reset":String(Math.ceil($.resetAt/1000))};if(!$.allowed)Z["Retry-After"]=String(Math.max(1,Math.ceil($.retryAfter/1000)));return Z}class D1{config;static token="ratelimiter";constructor($){this.config=$}get driver(){return this.config.driver}async consume($,Z={}){let J=Z.limit??this.config.limit,W=Z.window??this.config.window,Y=Z.cost??1;if(B9("window",W),B9("limit",J),!Number.isFinite(Y)||Y<0)throw Error(`Rate limiter cost must be zero or greater, got ${Y}`);return await this.config.driver.consume({key:$,limit:J,window:W*1000,cost:Y})}async enforce($,Z={},J){let W=await this.consume($,Z);if(!W.allowed)throw new r1(W,typeof J==="function"?J(W):J);return W}}function B9($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}import{isIP as U6}from"net";function e1($){let Z=$.trim();if(Z==="")return null;if(Z.startsWith("[")){let W=Z.indexOf("]");if(W<0)return null;let Y=Z.slice(W+1);if(Y!==""&&!/^:\d{1,5}$/.test(Y))return null;let j=Z.slice(1,W);return U6(j)===6?j:null}if(U6(Z))return Z;let J=/^(\d{1,3}(?:\.\d{1,3}){3}):\d{1,5}$/.exec(Z);return J&&U6(J[1])===4?J[1]:null}function F9($,{ipv6Prefix:Z=64}={}){if(!Number.isInteger(Z)||Z<0||Z>128)throw RangeError(`ipv6Prefix must be a whole number from 0 to 128, not ${Z}.`);let J=e1($);if(J===null||U6(J)===4)return J??$;let W=zV(J);if(W===null)return $;if(W.slice(0,5).every((z)=>z===0)&&W[5]===65535)return`${W[6]>>8}.${W[6]&255}.${W[7]>>8}.${W[7]&255}`;let Y=W.map((z,X)=>{let G=Math.min(Math.max(Z-X*16,0),16);return z&(65535<<16-G&65535)}),j=XV(Y);return Z===128?j:`${j}/${Z}`}function zV($){let Z=$.split("%")[0].toLowerCase(),J=/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(Z);if(J){let[Q,F,V,B]=J.slice(1).map(Number);Z=`${Z.slice(0,J.index)}${(Q<<8|F).toString(16)}:${(V<<8|B).toString(16)}`}let[W,Y]=Z.split("::"),j=(Q)=>Q===""?[]:Q.split(":").map((F)=>parseInt(F,16)),z=j(W),X=Y===void 0?[]:j(Y),G=Y===void 0?z:[...z,...Array.from({length:8-z.length-X.length},()=>0),...X];return G.length===8&&G.every((Q)=>Q>=0&&Q<=65535)?G:null}function XV($){let Z=-1,J=0;for(let Y=0;Y<8;Y++){if($[Y]!==0)continue;let j=Y;while(j<8&&$[j]===0)j++;if(j-Y>J)Z=Y,J=j-Y;Y=j}let W=$.map((Y)=>Y.toString(16));if(J<2)return W.join(":");return`${W.slice(0,Z).join(":")}::${W.slice(Z+J).join(":")}`}class O9 extends Z0{async run($,Z){let J=GV();if(!J)return{};let W=await J.consume(this.key(),{limit:V9($)??this.config.limit,window:V9(Z)??this.config.window});if(this.config.headers!==!1){let Y=this.req.ctx?.();if(Y)for(let[j,z]of Object.entries(g8(W)))Y.setHeaders(j,z)}if(!W.allowed)throw new r1(W);return{}}key(){if(this.config.key)return this.config.key(this.req);let $=U9(this.req.rawRequest);if($)return`mcp:${$.via}:${$.id}:${this.req.routePath??"*"}`;return`${O6(this.req)}:${this.req.routePath??"*"}`}}function GV(){try{let $=H();return $.bound(D1)?$.make(D1):null}catch{return null}}function D6($){let Z=D9($.rawRequest);if(Z!==void 0)return Z;let J=$.headers.get("x-forwarded-for");if(J){let[W]=J.split(",");if(W?.trim())return e1(W)??W.trim()}return $.headers.get("x-real-ip")?.trim()||"unknown"}function O6($,Z){return F9(D6($),Z)}function V9($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}class M9 extends Z0{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new y8;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new y8;return{}}}class y8 extends f0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:L9("csrf","Invalid CSRF token",403)}},view:{}}}class H9{policiesList={};constructor(){let $=this.register();for(let Z of $){let J=new Z;this.policiesList[Z.name]=J}}register(){return[]}}class T9{all($,Z){return!0}}class m8{options;param;refuse;answers=new WeakMap;constructor($){this.options=$;this.param=$.param,this.refuse=$.refuse??"not_found"}refusal(){return this.refuse==="forbidden"?new LZ:new L6}authorize($,Z){if(typeof Z==="number"&&Number.isFinite(Z))Z=String(Z);if(typeof Z!=="string"||Z==="")return Promise.reject(this.refusal());let J=this.answers.get($.rawRequest);if(!J)J=new Map,this.answers.set($.rawRequest,J);let W=J.get(Z);if(!W)W=this.decide($,Z),J.set(Z,W);return W}async allows($,Z){try{return await this.authorize($,Z),!0}catch(J){if(this.isRefusal(J))return!1;throw J}}fromRoute($=new A,Z=this.param){if(Z===void 0)throw Error('This resource policy has no `param`. Give `defineResourcePolicy` one, or name it: `fromRoute(req, "pageId")`, or `alias:pageId` on the middleware.');return this.authorize($,$.params?.[Z])}get middleware(){if(!this.middlewareClass){let $=(Z,J)=>this.fromRoute(Z,J||void 0);this.middlewareClass=class extends Z0{async run(J){await $(this.req,J)}}}return this.middlewareClass}middlewareClass;forAgent($){return{authorize:async(Z,{threadId:J,body:W})=>{let Y;if(J!==void 0){if(Y=$.thread?await $.thread(J,Z):null,Y===null||Y===void 0)throw this.refusal()}if(W!==void 0){let j=await $.body(W,Z);if(await this.authorize(Z,j),J!==void 0&&String(Y)!==String(j))throw this.refusal();return}if(J!==void 0)await this.authorize(Z,Y)}}}async decide($,Z){let J=await this.options.load(Z,$);if(J===null||J===void 0||!await this.options.allow(J,$))throw this.refusal();return J}isRefusal($){return this.refuse==="forbidden"?$ instanceof LZ:$ instanceof L6}}function QV($){return new m8($)}async function T6($,Z,J=!1){if(!$.body)return new Uint8Array;let[W,Y]=await KV($.body),z=W.length>=2&&W[0]===31&&W[1]===139?Y.pipeThrough(new DecompressionStream("gzip")):Y;return PV(z,Z,J,$.url)}async function PV($,Z,J,W){let Y=$.getReader(),j=[],z=0;try{for(;;){let{done:Q,value:F}=await Y.read();if(Q)break;if(z+F.byteLength>Z){if(!J)throw new H6(W,Z);j.push(F.subarray(0,Z-z)),z=Z;break}j.push(F),z+=F.byteLength}}finally{Y.cancel().catch(()=>{})}let X=new Uint8Array(z),G=0;for(let Q of j)X.set(Q,G),G+=Q.byteLength;return X}async function KV($){let Z=$.getReader(),J=await Z.read(),W=J.done?new Uint8Array:J.value,Y=new ReadableStream({start(j){if(J.done)j.close();else j.enqueue(W)},async pull(j){let z=await Z.read();if(z.done)j.close();else j.enqueue(z.value)},cancel(j){return Z.cancel(j)}});return[W,Y]}function N6($){return new TextDecoder("utf-8").decode($)}var _V={"&":"&","<":"<",">":">",'"':""","'":"'"};function f$($){return $.replace(/[&<>"']/g,(Z)=>_V[Z])}var IV={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function h8($){if(!$.includes("&"))return $;return $.replace(/&(#x[0-9a-fA-F]{1,6}|#[0-9]{1,7}|[a-zA-Z]{2,4});/g,(Z,J)=>{if(J[0]!=="#")return IV[J]??Z;let W=J[1]==="x"?parseInt(J.slice(2),16):parseInt(J.slice(1),10);return W>0&&W<=1114111?String.fromCodePoint(W):Z})}function p8($){let Z=$.indexOf(":");return(Z===-1?$:$.slice(Z+1)).toLowerCase()}function N9($,Z){let J=$.length,W=0;while(W<J){if(Z.stopped?.())return;let Y=$.indexOf("<",W);if(Y===-1){Z.text(h8($.slice(W)));return}if(Y>W)Z.text(h8($.slice(W,Y)));if($.startsWith("<!--",Y)){let j=$.indexOf("-->",Y+4);if(j===-1)return;W=j+3}else if($.startsWith("<![CDATA[",Y)){let j=$.indexOf("]]>",Y+9);if(j===-1)return;Z.text($.slice(Y+9,j)),W=j+3}else if($.startsWith("<?",Y)){let j=$.indexOf("?>",Y+2);if(j===-1)return;W=j+2}else if($.startsWith("<!",Y)){let j=$.indexOf(">",Y+2);if(j===-1)return;let z=$.indexOf("[",Y+2);if(z!==-1&&z<j){let X=$.indexOf("]",z+1);if(X===-1)return;let G=$.indexOf(">",X+1);if(G===-1)return;W=G+1}else W=j+1}else if($[Y+1]==="/"){let j=$.indexOf(">",Y+2);if(j===-1)return;Z.close(p8($.slice(Y+2,j).trim())),W=j+1}else{let j=xV($,Y+1);if(j===-1)return;let z=$.slice(Y+1,j),X=z.endsWith("/");if(X)z=z.slice(0,-1);let G=z.search(/[\s]|$/),Q=p8(z.slice(0,G));if(Q){if(Z.open(Q,CV(z.slice(G)),X),X)Z.close(Q)}W=j+1}}}function xV($,Z){let J=null;for(let W=Z;W<$.length;W++){let Y=$[W];if(J){if(Y===J)J=null}else if(Y==='"'||Y==="'")J=Y;else if(Y===">")return W}return-1}function CV($){let Z={},J=/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;for(let W of $.matchAll(J))Z[p8(W[1])]=h8(W[2]??W[3]??"");return Z}class j0 extends Error{url;status;constructor($,Z=null,J=null){super($);this.url=Z;this.status=J;this.name="SitemapError"}}var x9="http://www.sitemaps.org/schemas/sitemap/0.9",AV="http://www.w3.org/1999/xhtml",u8=`<?xml version="1.0" encoding="UTF-8"?>
|
|
3
3
|
`,P9=`<urlset xmlns="${x9}" xmlns:xhtml="${AV}">
|
|
4
4
|
`,K9=`</urlset>
|
|
5
5
|
`,v$=50000,Q3=52428800,_9=2048,SV=new Set(["always","hourly","daily","weekly","monthly","yearly","never"]),bV=/^\d{4}(-\d{2}(-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2}))?)?)?$/,EV="application/xml; charset=utf-8",I9=new TextEncoder;function l8($,Z){let J;try{J=new URL($)}catch{throw new j0(`Sitemap: ${Z} "${$}" is not an absolute URL.`)}if(J.protocol!=="http:"&&J.protocol!=="https:")throw new j0(`Sitemap: ${Z} "${$}" is not an http(s) URL.`);let W=J.href;if(W.length>_9)throw new j0(`Sitemap: ${Z} is over ${_9} characters: "${W.slice(0,80)}\u2026".`);return W}function C9($,Z){if($ instanceof Date){if(Number.isNaN($.getTime()))throw new j0(`Sitemap: lastmod of ${Z} is an invalid Date.`);return $.toISOString()}if(!bV.test($))throw new j0(`Sitemap: lastmod "${$}" of ${Z} is not a W3C datetime (e.g. "2026-10-07" or "2026-10-07T12:00:00Z").`);return $}function RV($){let Z=l8($.loc,"loc"),J=`<url><loc>${f$(Z)}</loc>`;if($.lastmod!=null)J+=`<lastmod>${f$(C9($.lastmod,Z))}</lastmod>`;if($.changefreq!=null){if(!SV.has($.changefreq))throw new j0(`Sitemap: changefreq "${$.changefreq}" of ${Z} is not one the protocol knows.`);J+=`<changefreq>${$.changefreq}</changefreq>`}if($.priority!=null){let W=$.priority;if(!Number.isFinite(W)||W<0||W>1)throw new j0(`Sitemap: priority ${W} of ${Z} is not between 0 and 1.`);J+=`<priority>${Number(W.toFixed(4))}</priority>`}for(let W of $.alternates??[]){let Y=W.hrefLang?.trim();if(!Y)throw new j0(`Sitemap: an alternate of ${Z} has no hrefLang.`);let j=l8(W.href,`alternate href of ${Z}`);J+=`<xhtml:link rel="alternate" hreflang="${f$(Y)}" href="${f$(j)}"/>`}return`${J}</url>
|
|
@@ -20,7 +20,7 @@ c.remove(e==='dark'?'light':'dark');c.add(e);d.style.colorScheme=e}catch(x){}}($
|
|
|
20
20
|
`)),Z.onSettle((F)=>{if(X||F.status!=="resolved")return;z.enqueue(Y.encode(`${JSON.stringify([F.path,F.variantKey,F.data])}
|
|
21
21
|
`))});let Q=setTimeout(()=>G(!0),J);Z.allSettled().then(()=>G(!1),()=>G(!1))},cancel(){j(!1)}})}import{Fragment as ax,createContext as LM,createElement as tx,lazy as rx,use as ex,useContext as $C}from"react";import{createContext as tL}from"react";var rL=tL(null);import{createContext as ZM,useContext as Kx}from"react";import{useContext as Mx}from"react";import{createContext as eL}from"react";import{jsx as Dx}from"react/jsx-runtime";var $M=eL({});var JM="gemi.islandI18n",WM=globalThis[Symbol.for(JM)]??=ZM(null);import{createContext as $B,useMemo as px,useRef as cx}from"react";class N5{subscribers=new Set;value;constructor($){this.value=$,this.subscribe=this.subscribe.bind(this),this.next=this.next.bind(this),this.getValue=this.getValue.bind(this)}subscribe($){return this.subscribers.add($),()=>{this.subscribers.delete($)}}next($){this.value=$,this.subscribers.forEach((Z)=>Z($))}getValue(){return this.value}}function uQ($,Z=Date.now()){if($==null)return;let J=$.trim();if(J==="")return;if(/^\d+$/.test(J))return Number(J)*1000;let W=Date.parse(J);if(Number.isNaN(W))return;return Math.max(0,W-Z)}function lQ($){if($.status===204||$.status===205)return Promise.resolve(null);let Z=$.headers?.get?.("Content-Type")??"";if(/^text\/plain\b/i.test(Z))return $.text();return $.json()}var iQ="/auth/sign-in",YM=1000,jM=2,P5,K5=null,J3="idle",sQ=0,_5=[];function oQ($,Z){if($!==401)return!1;let J=Z&&typeof Z==="object"?Z.error:void 0;if(typeof J==="string")return J==="Authentication error";return!!J&&typeof J==="object"&&J.kind==="authentication"}function zM($){let Z=$?.get?.(I5);if(typeof Z!=="string"||Z==="")return iQ;if(/^https?:\/\//i.test(Z))return Z;if(Z.startsWith("/")&&!Z.startsWith("//")&&!Z.includes("\\"))return Z;return iQ}function XM(){let $=K5?.current();if($)return $;if(typeof window>"u")return null;return{pathname:window.location.pathname,search:window.location.search}}var nQ=($)=>$.replace(/\/+$/,"")||"/";function GM($,Z){let J=q8($),W=new URL($,"http://gemi.invalid");if(!J&&nQ(W.pathname)===nQ(Z.pathname))return null;return W.searchParams.set(l0,J?Z.pathname:`${Z.pathname}${Z.search}`),J?W.href:`${W.pathname}${W.search}`}function QM($){if(!q8($)&&K5)K5.replace($);else window.location.replace($)}function aQ($){if(!P5||typeof window>"u")return;if(!oQ($.status,$.body))return;if($.path.split("?")[0]==="/auth/me")return;if(J3==="handled")return;if(J3==="idle"&&sQ>=jM)return;if($.refetch)_5.push($.refetch);if(J3==="checking")return;J3="checking",sQ++;let Z=$;setTimeout(()=>{BM(Z)},YM)}async function BM($){let Z=!1,J=$.headers?.get?.(I5)?$.headers:null;try{let X=await fetch("/api/auth/me",{cache:"no-store",headers:{Accept:"application/json"}}),G=null;try{G=await X.json()}catch{}if(Z=oQ(X.status,G),Z&&!J)J=X.headers}catch{}let W=_5;if(_5=[],!Z){J3="idle";for(let X of W)try{X()}catch(G){console.error(G)}return}J3="handled";let Y=XM();if(!Y)return;let j=GM(zM(J),Y);if(!j)return;let z={source:$.source,path:$.path,error:$.error,signInUrl:j,redirect:()=>QM(j)};try{if(P5==="redirect")z.redirect();else P5?.(z)}catch(X){console.error(X)}}class x5 extends Error{url;timeout;constructor($,Z){super(`Request to ${$} timed out after ${Z}ms`);this.url=$;this.timeout=Z;this.name="TimeoutError"}}function tQ($,Z){let J=!1,W=!1,Y,j=1/0,z=null,X=(G)=>{if(!$||W)return;if(typeof G!=="number"||!(G>0)||!Number.isFinite(G))return;let Q=Date.now();if(Q+G>=j)return;if(Y=G,j=Q+G,z!==null)clearTimeout(z);z=setTimeout(()=>{J=!0,$.abort()},G)};return X(Z),{timedOut:()=>J,timeout:()=>Y,tighten:X,clear:()=>{if(W=!0,z!==null)clearTimeout(z)}}}var C5=5000,FM=2147483647;class XZ{store;staleVariants=new Set;lastFetchRecord=new Map;key;inflight=new Set;pending=new Map;watchers=new Map;failures=new Map;retryTimers=new Map;seq=0;issued=new Map;applied=new Map;controllers=new Map;streamed=new Set;timeouts=new Map;renderTimeouts=new Map;renderTimeoutsClearing=!1;requestTimers=new Map;constructor($,Z){this.key=$,this.store=new N5(new Map),this.hydrate(Z)}hydrate($,Z=!1){let J=this.store.getValue(),W=Date.now(),Y=!1;for(let[j,z]of Object.entries($??{})){if(z===void 0)continue;let X=J.get(j);if(X?.loading)continue;if(X?.hasData&&X.data===z)continue;if(this.fill(J,j,z,W),Z)this.streamed.add(j);Y=!0}if(Y)this.store.next(J)}pendingFor($){let Z=this.pending.get($);if(!Z){let J;Z={promise:new Promise((Y)=>{J=Y}),resolve:J},this.pending.set($,Z)}return Z}settle($){let Z=this.pending.get($);if(Z)this.pending.delete($),Z.resolve()}isStale($,Z){if(this.staleVariants.has($))return!0;let J=Date.now();return J-(this.lastFetchRecord.get($)??J)>=Z}peek($){return this.store.getValue().get($)}peekForHydration($){return this.streamed.has($)?void 0:this.peek($)}setRequestTimeout($,Z){if(!rQ(Z))return;this.tightenInflight($,Z);let J=this.renderTimeouts.get($);if(J===void 0||Z<J)this.renderTimeouts.set($,Z);if(this.renderTimeoutsClearing)return;this.renderTimeoutsClearing=!0,Promise.resolve().then(()=>{this.renderTimeoutsClearing=!1,this.renderTimeouts.clear()})}holdRequestTimeout($,Z){if(!rQ(Z))return()=>{};this.tightenInflight($,Z);let J={},W=this.timeouts.get($);if(!W)W=new Map,this.timeouts.set($,W);return W.set(J,Z),()=>{let Y=this.timeouts.get($);if(!Y)return;if(Y.delete(J),Y.size===0)this.timeouts.delete($)}}tightenInflight($,Z){for(let J of this.requestTimers.get($)??[])J.tighten(Z)}requestTimeout($){let Z=this.renderTimeouts.get($);for(let J of this.timeouts.get($)?.values()??[])if(Z===void 0||J<Z)Z=J;return Z}isFetching($){return this.inflight.has($)}start($){if(typeof window>"u")return;if(this.store.getValue().has($))return;if(this.inflight.has($))return;this.resolveVariant($,!0)}read($,Z=C5){let J=this.peek($);if(J?.hasData){if(!this.inflight.has($)&&this.isStale($,Z))this.lastFetchRecord.set($,Date.now()),this.resolveVariant($,!0);return{state:J}}if(J?.error)return{state:J};if(typeof window>"u")return{state:J};let W=this.pendingFor($);if(!this.inflight.has($))this.resolveVariant($,!0);return{state:J,promise:W.promise}}getVariant($,Z=C5){let J=this.store.getValue();if(!J.has($)){if(!this.inflight.has($))this.resolveVariant($)}else{let W=J.get($);if(!W.loading&&!this.inflight.has($)){if(!W.hasData)return this.resolveVariant($),J.get($);if(this.isStale($,Z))return this.lastFetchRecord.set($,Date.now()),this.resolveVariant($,!0),J.get($)}}return J.get($)}revalidate($,Z=C5){if(typeof window>"u")return;if(this.inflight.has($))return;let J=this.peek($);if(J?.loading)return;if(J?.hasData){if(!this.isStale($,Z))return;this.lastFetchRecord.set($,Date.now())}this.resolveVariant($,!0)}clearError($){let Z=this.store.getValue(),J=!1;for(let[W,Y]of Z){if($!==void 0&&W!==$)continue;if(Y.error)Z.set(W,{...Y,error:null,reconnecting:!1}),J=!0}if(J)this.store.next(Z)}retain($){this.watchers.set($,(this.watchers.get($)??0)+1);let Z=!1;return()=>{if(Z)return;Z=!0;let J=(this.watchers.get($)??1)-1;if(J>0)this.watchers.set($,J);else this.watchers.delete($),this.cancelRetry($),this.setReconnecting($,!1),this.scheduleAbort($)}}scheduleAbort($){if(!this.controllers.has($))return;setTimeout(()=>{if(this.watchers.has($))return;this.abort($)},0)}abort($){let Z=this.controllers.get($);if(!Z)return;this.controllers.delete($);for(let J of Z)J.abort()}failureCount($){return this.failures.get($)??0}scheduleRetry($,Z){if(typeof window>"u")return;if(this.setReconnecting($,!0),this.retryTimers.has($)||this.inflight.has($))return;let J=Math.min(Math.max(0,Z||0),FM),W=setTimeout(()=>{if(this.retryTimers.delete($),!this.watchers.has($))return;if(this.inflight.has($))return;let Y=this.peek($);if(!Y?.error||Y.loading)return;this.resolveVariant($,Y.hasData,!0,!0)},J);this.retryTimers.set($,W)}giveUpRetry($){if(this.retryTimers.has($)||this.inflight.has($))return;this.setReconnecting($,!1)}setReconnecting($,Z){let J=this.store.getValue(),W=J.get($);if(!W||!!W.reconnecting===Z)return;this.store.next(J.set($,{...W,reconnecting:Z}))}cancelRetry($){let Z=this.retryTimers.get($);if(Z!==void 0)clearTimeout(Z),this.retryTimers.delete($)}retryNow($){if(typeof window>"u")return;if(this.inflight.has($))return;let Z=this.peek($);if(!Z?.error||Z.loading)return;this.resolveVariant($,!0)}variantKeys(){return[...this.store.getValue().keys()]}invalidate($,Z){this.dropHttpCache($);let J=this.store.getValue(),W=J.get($);if(Z&&W?.hasData)this.markApplied($),this.store.next(J.set($,{...W,data:Z(W.data),error:null,reconnecting:!1}));if(this.staleVariants.add($),this.watchers.has($))this.resolveVariant($,!1,!1)}dropHttpCache($){let Z=[typeof window<"u"&&window.location?.origin?window.location.origin:"",this.key,$].filter((J)=>J.length>0).join("?");try{if(caches)caches?.delete(Z)}catch{}}mutate($,Z=(J)=>J){this.dropHttpCache($);let J=this.store.getValue(),W=J.get($);if(!W||!W.hasData){this.resolveVariant($,!1,!1);return}let Y=Z(W.data);this.markApplied($),this.staleVariants.add($),this.store.next(J.set($,{loading:!1,data:Y,hasData:!0,error:null,version:W.version})),this.resolveVariant($,!1,!1)}fill($,Z,J,W){$.set(Z,{loading:!1,data:J,hasData:!0,error:null,version:W}),this.staleVariants.delete(Z),this.lastFetchRecord.set(Z,W),this.failures.delete(Z),this.cancelRetry(Z),this.settle(Z)}refetch($){this.resolveVariant($,!1,!1)}markApplied($){this.applied.set($,this.seq)}async resolveVariant($,Z=!1,J=!0,W=!1){if(typeof window>"u")return;this.cancelRetry($),this.inflight.add($);let Y=++this.seq;this.issued.set($,Y);let j=typeof AbortController>"u"?null:new AbortController;if(j){let U=this.controllers.get($);if(!U)U=new Set,this.controllers.set($,U);U.add(j)}let z=tQ(j,this.requestTimeout($)),X=this.requestTimers.get($);if(!X)X=new Set,this.requestTimers.set($,X);X.add(z);let G=()=>this.issued.get($)===Y,Q=()=>(this.applied.get($)??0)>=Y,F=()=>{this.failures.set($,W?(this.failures.get($)??0)+1:1)},V=this.store.getValue(),B=(U)=>{if(!G())return;F();let O=V.get($);this.store.next(V.set($,{loading:!1,data:O?.data,hasData:O?.hasData??!1,error:U,version:O?.version,reconnecting:O?.reconnecting}))};try{let U=V.get($);if(!Z)V.set($,{loading:!0,data:U?.data,hasData:U?.hasData??!1,error:U?.error,version:U?.version,reconnecting:U?.reconnecting});let O=null,D=null,L=[this.key,$].filter((M)=>M.length).join("?");try{D=await fetch(`/api${L}`,{cache:J&&!this.staleVariants.has($)?"default":"reload",signal:j?.signal});try{O=await lQ(D)}catch(M){if(D.ok||z.timedOut())throw M;O=null}}catch(M){if(z.timedOut()){B(new x5(`/api${L}`,z.timeout()));return}if(j?.signal.aborted){let T=V.get($);if(G()&&T?.loading)this.store.next(V.set($,{...T,loading:!1}));return}console.error(`Error fetching url /api${L}`,M),B(M);return}if(D.ok){if(Q()){let T=V.get($);if(G()&&T?.loading)this.store.next(V.set($,{...T,loading:!1}));return}this.applied.set($,Y);let M=V.get($);this.store.next(V.set($,{loading:G()?!1:M?.loading??!1,data:O,hasData:!0,error:null,version:Date.now()})),this.staleVariants.delete($),this.lastFetchRecord.set($,Date.now()),this.failures.delete($)}else{let M=new a0(this.key,$,D.status,O,uQ(D.headers?.get?.("retry-after")));if(B(M),G())aQ({source:"query",path:this.key,status:D.status,body:O,headers:D.headers,error:M,refetch:()=>this.resolveVariant($,!0,!1)})}}finally{z.clear();let U=this.requestTimers.get($);if(U?.delete(z),U?.size===0)this.requestTimers.delete($);if(j){let O=this.controllers.get($);if(O?.delete(j),O?.size===0)this.controllers.delete($)}if(G())this.inflight.delete($);this.settle($)}}}function rQ($){return typeof $==="number"&&$>0}import{jsx as UM}from"react/jsx-runtime";var ux=$B(null);var ZB=$B({getResource:($,Z={})=>{return new XZ($,Z)},hydrate:()=>{},allResources:()=>[],clearErrors:()=>{}});function VM(){let $=new Map;return{getResource(Z,J){let W=$.get(Z);if(!W)W=new XZ(Z,J??{}),$.set(Z,W);return W},hydrate(Z,J=!1){if(!Z)return;for(let[W,Y]of Object.entries(Z)){if(!Y||typeof Y!=="object")continue;let j=$.get(W);if(!j)j=new XZ(W,{}),$.set(W,j);j.hydrate(Y,J)}},allResources:()=>$.values(),clearErrors(){for(let Z of $.values())Z.clearError()}}}var eQ="gemi.islandQueries";if(typeof window<"u"){let $=globalThis;if(!$[Symbol.for(eQ)]){let Z=VM(),J={seed:Z.hydrate,Provider:({children:W})=>UM(ZB.Provider,{value:Z,children:W})};$[Symbol.for(eQ)]=J}}import{createContext as DM}from"react";var OM=DM(null);function JB($,Z={},J){let W=new Set,Y=new Map,j=J?{ensure(Q,F){let V=J.find(Q,F);if(!V||V.source!=="prefetch"||V.status==="rejected")return null;return z(V),V}}:null,z=(Q)=>Y.set(`${Q.path}?${Q.variantKey}`,Q),G={queries:j,queriesRead:Y,createQueryManager:()=>{if(!J)return null;let Q=new Map;return{getResource(F,V){let B=Q.get(F);if(!B){let U=new Map(J.entriesFor(F).filter((D)=>D.source==="prefetch"&&D.status==="resolved").map((D)=>[D.variantKey,D]));B=new XZ(F,U.size>0?Object.fromEntries(Array.from(U,([D,L])=>[D,L.data])):V??{});let O=B.peek.bind(B);B.peek=(D)=>{let L=U.get(D);if(L)z(L);return O(D)},Q.set(F,B)}return B},hydrate(){},allResources:()=>Q.values(),clearErrors(){}}},islands:[],render:$,instances:new WeakMap,count:0,i18n:{},localeAware:Boolean(Z.currentLocale),i18nUsed:!1,dictionaries:[],sink:{use(Q,F,V){let B=`${Q} ${F}`;if(W.has(B))return;W.add(B),G.dictionaries.push([Q,F,V])},onUse(){}}};for(let Q of["currentLocale","defaultLocale","timeZone"])Object.defineProperty(G.i18n,Q,{enumerable:!0,get(){return G.i18nUsed=!0,Z[Q]}});return G}function WB($){if(!$.i18nUsed&&!$.localeAware)return;let{currentLocale:Z,defaultLocale:J,timeZone:W}=$.i18n;return{...Z?{currentLocale:Z}:{},...J?{defaultLocale:J}:{},...W?{timeZone:W}:{},...$.dictionaries.length>0?{dictionaries:$.dictionaries}:{}}}function YB($){let Z;for(let J of $.queriesRead.values()){if(J.status!=="resolved")continue;Z??={},(Z[J.path]??={})[J.variantKey]=J.data}return Z}var n3="gemi-slot",jB="data-slot",zB="data-gemi-slot";var MM=Symbol.for("gemi.staticRender"),XB=globalThis[MM]??=LM(null);import{createHash as VB}from"crypto";var A5='var r=document,i=window,a=history;i.__gemi_nav?.d();var C=new AbortController,h=(t,e,n,s)=>t.addEventListener(e,n,{signal:C.signal,...s}),q=i.__gemi_nav={d:()=>C.abort()},y=(t,e)=>{if(!t.g)t.g=1,import(e.s).then((n)=>{if(t.isConnected)t.r=n.h(t,n.m[e.e])}).catch((n)=>console.error(n))},L=(t)=>{let e=t.getElementById("gemi-islands");return e?JSON.parse(e.textContent):{i:[]}},D=(t,e)=>{for(let n of t.querySelectorAll("gemi-island")){let s=e.i[n.dataset.island];if(!s||n.o)continue;if(s.l=="eager")y(n,s);else if(s.l=="idle"||!i.IntersectionObserver||!n.children.length)(i.requestIdleCallback||setTimeout)(()=>y(n,s));else{let l=new IntersectionObserver((m)=>{if(m.some((d)=>d.isIntersecting))l.disconnect(),y(n,s)});for(let m of n.children)l.observe(m)}}},R=\'meta[name="gemi-static"]\',A="style:not([data-gemi-fonts])",T=A+",link[rel=stylesheet]",K=`head>${A},body>${A},link[rel=stylesheet]`,I=\'meta[name]:not([name=viewport]),meta[property],link[rel~=canonical],link[rel~=alternate],link[rel~=icon],link[rel=preload][as=font],style[data-gemi-fonts],script[type="application/ld+json"]\',w=(t)=>t.querySelector(R)?.content,O=(t)=>[...t.querySelectorAll(K)].map((e)=>e.outerHTML).join(),c=(t)=>t.href.split("#")[0],N=O(r),p=r.createElement("div");p.setAttribute("aria-live","polite");p.style.cssText="position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap";r.body.append(p);var _=(t)=>{q.p={url:location.href,title:r.title,initial:t},r.dispatchEvent(new CustomEvent("gemi:page-load",{detail:q.p}))},f=new Map,k=(t)=>{let e=f.get(t);if(!e||Date.now()-e[0]>30000){let n=fetch(t,{headers:{accept:"text/html","x-gemi-navigate":"1"},signal:AbortSignal.timeout(1e4)}).then((s)=>{if(!s.ok||!/^text\\/html/.test(s.headers.get("content-type"))||new URL(s.url||t).origin!=location.origin)throw s;return s.text().then((l)=>[s.url||t,l])});e=[Date.now(),n],n.catch(()=>f.get(t)==e&&f.delete(t))}if(f.delete(t),f.set(t,e),f.size>10)f.delete(f.keys().next().value);return e[1]},M=(t)=>{let e=t.target.closest?.("a[href]"),n=e?.getAttribute("target");if(!e||n&&n!="_self"||e.hasAttribute("download")||/(^|\\s)external(\\s|$)/i.test(e.getAttribute("rel"))||e.closest("[data-gemi-reload]"))return;let s=new URL(e.getAttribute("href"),r.baseURI);if(s.origin==location.origin&&!(s.href.includes("#")&&c(s)==c(location)))return s},v={},U=()=>Math.random().toString(36).slice(2),E=()=>a.state?.g||a.replaceState({...a.state,g:U()},""),P=c(location),b=0,Y=(t)=>{if(!t.hasAttribute("tabindex"))t.setAttribute("tabindex","-1"),t.addEventListener("blur",()=>t.removeAttribute("tabindex"),{once:!0});t.focus({preventScroll:!0})},j=(t)=>{let e=r.body,n=t.body,s=L(t),l=r.documentElement;r.title=t.title;for(let o of["lang","dir"]){let u=t.documentElement.getAttribute(o);if(u==null)l.removeAttribute(o);else l.setAttribute(o,u)}for(let o of r.head.querySelectorAll(I))o.remove();let m=new Set([...r.querySelectorAll("link[rel=modulepreload]")].map((o)=>o.getAttribute("href")));r.head.append(...t.head.querySelectorAll(I),...[...t.head.querySelectorAll("link[rel=modulepreload]")].filter((o)=>!m.has(o.getAttribute("href"))));let d=new Map([...e.querySelectorAll("[data-gemi-persist]")].map((o)=>[o.dataset.gemiPersist,o])),g=[...n.querySelectorAll("[data-gemi-persist]")].map((o)=>[o,d.get(o.dataset.gemiPersist)]).filter((o)=>o[1]);for(let o of[...e.querySelectorAll("gemi-island")].reverse())if(o.o=1,!g.some((u)=>u[1].contains(o)))try{o.r?.unmount()}catch(u){console.error(u)}for(let[o,u]of g)o.replaceWith(u);for(let o of[...e.childNodes])if(!o.matches?.(T))o.remove();for(let o of[...n.children])if(o.matches(T))o.remove();for(let o of[...e.attributes])e.removeAttribute(o.name);for(let o of n.attributes)e.setAttribute(o.name,o.value);e.append(...n.childNodes,p),D(e,s)},H=async(t,e)=>{let n=++b,s=!e&&v[a.state?.g];a.scrollRestoration="manual";try{let[l,m]=await k(c(t));if(n!=b)return;let d=new DOMParser().parseFromString(m,"text/html");if(w(d)==null||w(d)!=w(r)||O(d)!=N)throw 0;if(e){let o=new URL(l);o.hash=t.hash,a.pushState({g:U()},"",o.href)}P=c(location),j(d);let g=e&&t.hash&&r.getElementById(decodeURIComponent(t.hash.slice(1)));if(g)g.scrollIntoView({behavior:"instant"});else i.scrollTo({left:s?.[0]||0,top:s?.[1]||0,behavior:"instant"});if(e)Y(g||r.querySelector("h1")||r.querySelector("main")||r.body);p.textContent=r.title,_(!1)}catch{if(n!=b)return;if(e)location.assign(t.href);else location.reload()}};h(r,"click",(t)=>{if(t.defaultPrevented||t.button||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey)return;let e=M(t);if(e&&r.dispatchEvent(new CustomEvent("gemi:before-navigate",{cancelable:!0,detail:{url:e.href}})))t.preventDefault(),E(),v[a.state.g]=[i.scrollX,i.scrollY],H(e,1)});h(i,"popstate",()=>{if(b++,c(location)==P){let t=v[a.state?.g];if(t)i.scrollTo({left:t[0],top:t[1],behavior:"instant"})}else if(a.state?.g)H(new URL(location.href),0);else location.reload()});h(i,"hashchange",E);h(i,"scroll",()=>a.state?.g&&(v[a.state.g]=[i.scrollX,i.scrollY]),{passive:!0});var S,x=(t)=>{if(r.querySelector(R)?.dataset.prefetch=="none"||navigator.connection?.saveData)return;let e=M(t);if(e&&c(e)!=c(location))k(c(e))};h(r,"pointerover",(t)=>{clearTimeout(S),S=setTimeout(()=>x(t),65)});h(r,"pointerout",()=>clearTimeout(S));h(r,"focusin",x);h(r,"touchstart",x,{passive:!0});E();D(r,L(r));_(!0);';import{createHash as HM}from"crypto";import{existsSync as QB,readFileSync as TM}from"fs";import{join as R5}from"path";var BB=".script",NM=[".ts",".js"],PM="document-scripts.json",FB="data-gemi-script",KM=/^[A-Za-z0-9_-]+(\/[A-Za-z0-9_-]+)*$/;function _M($){if(typeof $!=="string"||!KM.test($))throw Error(`A static view's \`script\` is a path under app/views without the ".script.ts" suffix, e.g. "site/clicks". Got ${JSON.stringify($)}.`)}function IM($,Z){for(let J of NM){let W=R5($,"views",`${Z}${BB}${J}`);if(QB(W))return W}return null}async function GB($){let Z=await Bun.build({entrypoints:[$],target:"browser",format:"iife",minify:!0,throw:!1});if(!Z.success||!Z.outputs[0]){let W=Z.logs.map((Y)=>String(Y)).join(`
|
|
22
22
|
`);throw Error(`The document script ${$} does not bundle.
|
|
23
|
-
${W}`)}let J=(await Z.outputs[0].text()).trim();if(/<\/script|<!--/i.test(J))throw Error(`The document script ${$} contains "</script" or "<!--", which would end the inline <script> it is put in. Write it "<\\/script" or build the string from parts.`);return J}function k5($){return`'sha256-${HM("sha256").update($).digest("base64")}'`}var S5,b5=new Map;function xM(){if(S5===void 0){let $=R5(E5(),"dist","server",PM);S5=QB($)?JSON.parse(TM($,"utf8")):null}return S5??null}async function w5($){_M($);let Z=Bun.env.NODE_ENV==="production";if(Z){let j=xM()?.[$];if(j!==void 0)return j;let z=b5.get($);if(z)return z}let J=R5(E5(),"app"),W=IM(J,$);if(!W)throw Error(`The document script "${$}" was not found. It is a file at app/views/${$}${BB}.ts (or .js).`);if(!Z)return GB(W);let Y=GB(W);return b5.set($,Y),Y.catch(()=>b5.delete($)),Y}async function VC($){return k5(await w5($))}var CM="gemi-islands",AM="gemi-island-i18n",SM="gemi-island-queries",NC=`'sha256-${VB("sha256").update(v5).digest("base64")}'`;function q5($,Z,J,W){if(!J)return $;let Y=W?$.lastIndexOf(Z):$.indexOf(Z);return Y===-1?$+J:$.slice(0,Y)+J+$.slice(Y)}var f5=($)=>$.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<"),PC=`'sha256-${VB("sha256").update(A5).digest("base64")}'`,bM='await import("/refresh.js").catch(()=>{});await import("/@vite/client").catch(()=>{});',EM="gemi-static";function UB($,Z,J,W,Y,j,z){let X=new Set,G=[];if(J)G=Z.islands.map((T)=>{let N=T.module?J(T.module):void 0;if(!N)return console.error(`[gemi] island ${T.module??"(unknown module)"}: no client build entry. Declare it as island(() => import("./Component")) so gemi's Vite plugin builds it.`),null;if(T.load==="eager"){for(let K of N.preload)X.add(K);if(T.preloadDynamic)for(let K of N.dynamicPreload??[])X.add(K)}return{s:N.src,e:T.export,l:T.load}});let Q=G.some((T)=>T!==null),F=j?`<script type="module" ${FB}="${f5(j.name)}">${j.source}</script>`:"";if(j)z?.push(j.source);if(!Q&&!Y)return q5($,"</head>",F,!1);let B=(Y?`<meta name="${EM}" content="${f5(Y.identity)}"${Y.prefetch==="none"?' data-prefetch="none"':""}/>`:"")+[...X].map((T)=>`<link rel="modulepreload" href="${f5(T)}"/>`).join("")+F,U=Y?A5:v5,O=W?bM+U:U;z?.push(O);let D=Q?WB(Z):void 0,L=Q?YB(Z):void 0,M=(Q?`<script type="application/json" id="${CM}">${i0({i:G})}</script>`:"")+(D?`<script type="application/json" id="${AM}">${i0(D)}</script>`:"")+(L?`<script type="application/json" id="${SM}">${i0(L)}</script>`:"")+`<script type="module">${O}</script>`;return q5(q5($,"</head>",B,!1),"</body>",M,!0)}function RM($,Z){let J=/<(\/?)template\b[^>]*>/gi;J.lastIndex=Z;let W=0;for(let Y=J.exec($);Y;Y=J.exec($))if(W+=Y[1]?-1:1,W===0)return J.lastIndex;return-1}function DB($){let Z=`<template ${zB}="`;for(let J=$.lastIndexOf(Z);J!==-1;J=$.lastIndexOf(Z)){let W=RM($,J);if(W===-1)break;let Y=J+Z.length,j=$.slice(Y,$.indexOf('"',Y)),z=$.indexOf(">",Y)+1,X=$.slice(z,W-11);$=$.slice(0,J)+$.slice(W);let G=`<${n3} ${jB}="${j}" style="display:contents"></${n3}>`;$=$.split(G).join(`<${n3} style="display:contents">${X}</${n3}>`)}return $}function g5($){if(!$)return{locale:!0,session:!0,csrf:!0};return{locale:!1,session:$.session===!0,csrf:$.csrf===!0}}function HB($,Z){if($.getSetCookie().length>0){if(Z.cacheControl&&Bun.env.NODE_ENV!=="production")console.warn(`[gemi] A static view with cacheControl "${Z.cacheControl}" set a cookie, so it was sent "private, no-store" instead. Static pages are cacheable only when nothing on them sets a cookie.`);$.set("Cache-Control","private, no-store");return}if(Z.cacheControl&&!$.has("Cache-Control"))$.set("Cache-Control",Z.cacheControl)}function kM($){let Z=$.headers.get("Cache-Control")?.toLowerCase()??"";return/(^|[\s,])(public|s-maxage)\b/.test(Z)}var OB=new Set,wM=new Set(["public","private","s-maxage","proxy-revalidate"]);function y5($,Z){let J=$.get("Cache-Control");if(!J||$.getSetCookie().length===0)return;if(!/(^|[\s,])(public|s-maxage)\b/i.test(J))return;let W=TB(J);if(Bun.env.NODE_ENV!=="production"&&!OB.has(Z)){OB.add(Z);let Y=[...new Set($.getSetCookie().map((j)=>j.split("=")[0]))];console.warn(`[gemi] The view "${Z??""}" sets cookies (${Y.join(", ")}) on a response with Cache-Control "${J}", so it was sent "${W}" instead: a shared cache would hand those cookies to every visitor. To let a CDN cache the page, make it a static view with .static({ cacheControl }).`)}$.set("Cache-Control",W)}function TB($){return["private",...$.split(",").map((J)=>J.trim()).filter((J)=>{let W=J.split("=")[0].trim().toLowerCase();return W!==""&&!wM.has(W)})].join(", ")}var LB=new Set;function NB($,Z,J){let W=$.get("Cache-Control");if(!W||!/(^|[\s,])(public|s-maxage)\b/i.test(W))return;let Y=TB(W);if(J&&Bun.env.NODE_ENV!=="production"&&!LB.has(Z))LB.add(Z),console.warn(`[gemi] The static view "${Z??""}" asked for a CSP nonce (cspNonce()) on a response with Cache-Control "${W}", so it was sent "${Y}" instead: a shared cache would hand the same nonce to every visitor. Allow a static page's scripts by hash instead (route.view.csp does).`);$.set("Cache-Control",Y)}var MB=new Set;function PB($,Z){if(!kM($)||$.headers.getSetCookie().length===0)return $;if(Bun.env.NODE_ENV!=="production"&&!MB.has(Z))MB.add(Z),console.warn(`[gemi] The file route "${Z??""}" set a cookie on a response with Cache-Control "${$.headers.get("Cache-Control")}", so the cookie was not sent: a shared cache would hand it to every visitor. Make the response private, or set the cookie elsewhere.`);try{return $.headers.delete("Set-Cookie"),$}catch{let J=new Headers($.headers);return J.delete("Set-Cookie"),new Response($.body,{status:$.status,statusText:$.statusText,headers:J})}}var qM="'strict-dynamic' 'self' https: 'unsafe-inline'",KB="Content-Security-Policy",_B="Content-Security-Policy-Report-Only";function fM($,Z={}){let J=[...$.nonce?[`'nonce-${$.nonce}'`]:[],...$.hashes??[]],W=[J.length>0?`script-src ${J.join(" ")} ${qM}`:"script-src 'none'","object-src 'none'","base-uri 'self'"];if(Z.reportUri)W.push(`report-uri ${Z.reportUri}`);return W.join("; ")}function m5($,Z,J){if(!Z)return;if($.has(KB)||$.has(_B))return;let W=Z===!0?{}:Z;$.set(W.reportOnly?_B:KB,fM({nonce:J.nonce,hashes:[...new Set(J.inlineScripts??[])].map(k5)},W))}var gM=async()=>(await import("./chunk-5p0gbwq1.js")).default,h5,o3=async(...$)=>{return h5??=import("react-dom/server.browser").catch((Z)=>{throw h5=void 0,Z}),(await h5).renderToReadableStream(...$)},xB=1e4,CB="no-locale",yM="no-theme";async function mM($,Z,J){let W=`${J==="italic"?"italic,":""}wght@${J==="italic"?"1,":""}${Z}`,z=(await(await fetch(`https://fonts.googleapis.com/css2?family=${$}:${W}&display=swap`,{headers:{"User-Agent":"Mozilla/5.0 Firefox/1.0"}})).text()).match(/url\(([^)]+)\)/)?.[1];return await fetch(z).then((X)=>X.arrayBuffer())}var i5="/assets";function hM($){return $===i5||$.startsWith(`${i5}/`)}function pM($){let Z=$.filter(hM);if(Z.length>0){let J=Z.length>1;throw Error(`View route path${J?"s":""} ${Z.map((W)=>`"${W}"`).join(", ")} use${J?"":"s"} the reserved "${i5}" prefix. The client build output is served from there before the router runs, so the route would never match. Mount it somewhere else, or set \`assetRoutes: true\` on these views' config (route.view or a route.domains group's view).`)}}function cM($){let Z=H(Q1).resolver;return{...$.domain,root:Z.root,origin:Z.publicOrigin($.rawRequest)}}function p5($){let{status:Z=400,error:J,body:W,...Y}=$;return new Response(W??J?.message,{...Y,status:Z})}function dM($){let{status:Z=400,data:J,directive:W,headers:Y}=$;return new Response(JSON.stringify({data:J,directive:W}),{headers:Y,status:Z})}class a3{static token="router.view";flatViewRoutes={};routeManifest={};clientRouteManifest={};componentTree=[];flatComponentTree=[];requiredViews={};staticRoutes=[];root=null;shellReporter=pQ();preloadCache=new WeakMap;hooks;partialRendering;localeRouting;detectLocale;theme;defaultMeta;notFound;publicFiles;assetRoutes;assetCors;translate;csp;constructor($,Z={}){let J=YQ();if(this.partialRendering=$.partialRendering??J.partialRendering,this.localeRouting=$.localeRouting??J.localeRouting,this.detectLocale=$.detectLocale,this.detectLocale&&this.localeRouting!=="off")throw Error('`view.detectLocale` needs `view.localeRouting: "off"`: on locale-routed views the URL, the `i18n-locale` cookie and `Accept-Language` decide the locale. A `route.domains` group that inherits it and keeps locale routing can set `detectLocale: undefined`.');this.theme=$.theme??J.theme,this.defaultMeta=$.meta,this.notFound=$.notFound,this.publicFiles=$.publicFiles??J.publicFiles,this.assetRoutes=$.assetRoutes??J.assetRoutes,this.assetCors=$.assetCors??J.assetCors,this.translate=$.translate,this.csp=$.csp,this.hooks={onNotFound:$.onNotFound??J.onNotFound,onRequestStart:$.onRequestStart??J.onRequestStart,onRequestEnd:$.onRequestEnd??J.onRequestEnd,onRequestFail:$.onRequestFail??J.onRequestFail,onStreamComplete:$.onStreamComplete??J.onStreamComplete};let W={"/":$.rootRouter,"/auth":aG(Z)};if(this.requiredViews=Object.fromEntries(nG(Z).map(({view:Y,requiredBy:j})=>[Y,j])),this.flatViewRoutes=e4(W),!this.assetRoutes)pM(Object.keys(this.flatViewRoutes));this.routeManifest=$8(W),this.clientRouteManifest=Object.fromEntries(Object.entries(this.routeManifest).filter(([,Y])=>Y.at(-1)!=="FILE")),this.componentTree=J8(W),this.flatComponentTree=M5(this.componentTree),this.staticRoutes=Object.entries(this.flatViewRoutes).filter(([,Y])=>Y.static).map(([Y])=>Y);for(let Y of this.staticRoutes){let j=this.flatViewRoutes[Y].static?.layout;if(j&&!this.flatComponentTree.includes(j))this.flatComponentTree.push(j)}if(this.notFound){for(let Y of[this.notFound.view,this.notFound.static?.layout])if(Y&&!this.flatComponentTree.includes(Y))this.flatComponentTree.push(Y)}this.root=$.root}async passesFeatureGates($){let Z=H($$);for(let J of $)if(!await Z.enabled(J))return!1;return!0}async onRequestEnd($,Z={}){if(Z.mintSession!==!1)Y8();return await this.hooks.onRequestEnd($)}completeStream($,Z){let J=(W)=>{GZ.error(W?.message??'Error in "onStreamComplete" event handler',{err:JSON.stringify(W)})};try{Promise.resolve(this.hooks.onStreamComplete($,Z)).catch(J)}catch(W){J(W)}}modulePreloadLinks($){let{clientEntry:Z,modulePreloadManifest:J,views:W,routeKey:Y}=$,j=()=>{let G=new Set(Z?.preload??[]);for(let Q of W)for(let F of J?.[Q]??[])G.add(F);return[...G].map((Q)=>c1("link",{key:`modulepreload:${Q}`,rel:"modulepreload",href:Q}))};if(!J)return j();let z=this.preloadCache.get(J);if(!z||z.clientEntry!==Z)z={clientEntry:Z,byRoute:new Map},this.preloadCache.set(J,z);let X=z.byRoute.get(Y);if(!X)X=j(),z.byRoute.set(Y,X);return X}async renderStatic($){let{req:Z,runInRequestScope:J,staticView:W,currentViews:Y,data:j,serverQueries:z,headers:X}=$,G;if(W.layout){if(G=$.viewImportMap[W.layout],!G)throw Error(`The static layout "${W.layout}" was not found. It is a view path: a file at app/views/${W.layout}.tsx whose default export renders the document.`)}let Q=await $.getStyles(Y,{static:!0,layout:W.layout});z.markRenderStart();let F=l5(),V=new AbortController,B=setTimeout(()=>V.abort(),xB),U=(D)=>{if(Bun.env.NODE_ENV!=="production")console.error(D)},O=JB(async(D,L)=>{let M=await o3(D,{signal:V.signal,identifierPrefix:L,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:U});return await M.allReady.catch(()=>{}),await new Response(M).text()},{currentLocale:j?.i18n?.currentLocale,defaultLocale:j?.i18n?.defaultLocale,timeZone:j?.i18n?.timeZone},z);try{let D,L=typeof W.script==="function"?await J(()=>W.script(Z)):W.script;if(L)D={name:L,source:await w5(L)};let M;if(W.navigation){let C=W.navigation===!0?{}:W.navigation,S=C.version?String(await J(()=>C.version(Z))):"";M={identity:[W.layout??"",$.buildId??"",D?.name??"",S].join("|"),prefetch:C.prefetch==="none"?"none":"intent"}}let T=await o3(c1(XB.Provider,{value:O,children:c1(IB,{children:[...Q,c1(this.root,{data:j,viewImportMap:$.viewImportMap,viewModules:$.viewModules,serverQueries:z,dictionarySink:F,rootLayout:G,key:"root"})]})}),{signal:V.signal,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:U});await T.allReady.catch(()=>{});let N=DB(await new Response(T).text()),K=[],R=UB(N,O,$.resolveIsland,Bun.env.NODE_ENV!=="production",M,D,K);return m5(X,this.csp,{nonce:c5(Z.rawRequest),inlineScripts:K}),new Response(R,{status:$.status,headers:X})}finally{clearTimeout(B),J(()=>this.completeStream(Z,z.summarize(V.signal.aborted)))}}async render($){let{req:Z,runInRequestScope:J,csrfTokenHMAC:W,currentPathName:Y,headers:j,i18n:z,params:X,pathname:G,serverQueries:Q,userAgent:F,noStream:V,noTheme:B,url:U,user:O,viewData:D,breadcrumbs:L,urlLocaleSegment:M,meta:T,isOgRequest:N,appId:K,features:R,staticView:C,cspNonce:S}=$,w=this.theme===!1||B||C?null:{cookie:this.theme.cookie??O5,default:this.theme.default??null,value:uM(Z,this.theme.cookie??O5)},x=M?mQ(G,[M]).pathname:G,q={kind:"view",data:{meta:T,pageData:{[x]:D},__csrf:W.toString("base64"),prefetchedData:{},i18n:z,auth:{user:O},routeManifest:this.clientRouteManifest,breadcrumbs:L,router:{urlLocaleSegment:M,pathname:Y,params:X,currentPath:G,searchParams:U.search,is404:!Y?!0:!1,domain:Z.domain?cM(Z):null},appId:K,features:R,theme:w,componentTree:[["404",[]],...this.componentTree],...this.staticRoutes.length>0?{staticRoutes:this.staticRoutes}:{}},head:{}},_=this.root,k=this.routeManifest[Y];return async(H0)=>{let{bootstrapModules:Y3=[],loaders:FZ,getStyles:C$,viewImportMap:c,cssManifest:g,ogMap:V0,viewModules:B1,clientEntry:A$,modulePreloadManifest:j3,assetBase:u0,resolveIsland:S$,buildId:C1}=H0,A1=A$?[]:Y3,l=(y)=>[y,`window.loaders=${FZ}`,...A$?[`import(${JSON.stringify(A$.module)}).catch(function(e){setTimeout(function(){throw e})})`]:[]].join(";");if(N){let y=null,F1=null;for(let b of k??[])if(typeof V0[b]==="function")F1=b,y=V0[b];if(!y)return new Response("Not found",{status:404});let $6=Object.values(q.data.pageData)[0];try{await o3(c1(y,$6[F1]),{onError:()=>{}})}catch(b){let{fonts:r,...l1}=b.satoriOptions,Z6=await Promise.all(r.map((J6)=>{return mM(J6.name,J6.weight,J6.style).then((EF)=>({...J6,data:EF}))})),T2=new Headers(j);T2.set("Content-Type","image/png");let[CF,AF]=await Promise.all([gM(),a4("Rendering an OG image")]),SF=await CF(b.jsx,{...l1,fonts:Z6}),bF=await AF(Buffer.from(SF)).png({compressionLevel:0,effort:10}).toBuffer();return new Response(new Uint8Array(bF),{headers:T2})}return new Response("data")}if(C&&Y)return await this.renderStatic({req:Z,runInRequestScope:J,staticView:C,currentViews:k,data:q.data,serverQueries:Q,headers:j,getStyles:C$,viewImportMap:c,viewModules:B1,resolveIsland:S$,buildId:C1,status:200});if(C&&!Y&&this.notFound){let y=this.notFound.view;if(!c[y])throw Error(`The not-found view "${y}" (route.view.notFound) was not found. It is a view path: a file at app/views/${y}.tsx.`);return await this.renderStatic({req:Z,runInRequestScope:J,staticView:C,currentViews:[y],data:q.data,serverQueries:Q,headers:j,getStyles:C$,viewImportMap:{...c,"404":c[y]},viewModules:B1&&{...B1,"404":B1[y]},resolveIsland:S$,buildId:C1,status:$.refusedStatus??404})}if(q.data.cssManifest=g,q.data.modulePreloadManifest=j3??{},u0&&u0!=="/")q.data.assetBase=u0;if(C1&&C1!=="dev")q.data.buildId=C1;let N8=AB(this.modulePreloadLinks({clientEntry:A$,modulePreloadManifest:j3,views:k??["404"],routeKey:Y??"404"}),S),P8=AB(await C$(k??["404"]),S);q.data.prefetchedData=Q.snapshotResolved(),Q.markRenderStart();let t0=new AbortController,VZ=setTimeout(()=>t0.abort(),xB),b$=C6(F)||V,u1=Bun.env.NODE_ENV!=="production"&&!b$&&Y&&this.shellReporter.shouldObserve(Y)?cQ():null,E$=l5();try{let y=await o3(c1(IB,{children:yQ(N8,[...P8,...w?[c1("script",{key:"theme-script",nonce:S,dangerouslySetInnerHTML:{__html:EQ(i0({cookie:w.cookie,default:w.default}))}})]:[]],c1(_,{data:q.data,viewImportMap:c,viewModules:B1,serverQueries:Q,dictionarySink:E$,cspNonce:S,key:"root"}))}),{bootstrapScriptContent:l(`window.__GEMI_DATA__ = ${i0(q.data)}`),bootstrapModules:A1,nonce:S,signal:t0.signal,...b$?{progressiveChunkSize:Number.MAX_SAFE_INTEGER}:{},onError(F1){if(Bun.env.NODE_ENV!=="production")console.error(F1)}});if(y.allReady.catch(()=>{}).finally(()=>clearTimeout(VZ)),b$)await y.allReady.catch(()=>{});return new Response(jJ(y,Q,{onShell:b$?void 0:()=>Q.markShell(),onChunk:u1?.onChunk,onClose:()=>J(()=>{if(this.completeStream(Z,Q.summarize(t0.signal.aborted)),u1)this.shellReporter.report(Y,u1.measure())})},E$,S),{status:!Y?$.refusedStatus??404:200,headers:j})}catch(y){if(clearTimeout(VZ),Bun.env.NODE_ENV==="production")throw J(()=>this.completeStream(Z,Q.summarize(t0.signal.aborted))),y;let F1=await o3(c1("div"),{bootstrapScriptContent:l(`window.error= ${i0(y.message)}; window.stack_trace=${i0(y.stack)};window.__GEMI_DATA__ = ${i0(q.data)}`),bootstrapModules:Bun.env.NODE_ENV==="development"?["/render-error.js",...A1]:A1,nonce:S});return new Response(jJ(F1,Q,{onClose:()=>J(()=>this.completeStream(Z,Q.summarize(t0.signal.aborted)))},void 0,S),{status:!Y?$.refusedStatus??404:200,headers:j})}}}viewRefusalStatus($,Z,J){if(w$(Z))return 404;if(Z?.kind===o1){let W=Z.payload?.view?.status;return W===403||W===404?W:null}if(a1(Z)){if(!J.has(Z))this.hooks.onRequestFail($,Z);return console.error(Z),403}if(Z instanceof a0&&(Z.status===403||Z.status===404))return Z.status;return null}async handleViewRequest($,Z){let J=new URL($.url),W=kQ(this.flatViewRoutes,J.pathname),Y=wQ(this.flatViewRoutes,J.pathname),j=W?J.pathname.slice(0,-5):Y?J.pathname.slice(0,-3):J.pathname,[,z,...X]=j.split("/"),G=j,Q=null,F=null,V=H(u),B=tZ(this.flatViewRoutes,j),U=V.isLocaleAware&&this.localeRouting==="prefix"&&!B?.route.middleware.includes(CB);if(U&&V.supportedLocales.includes(z))G=`/${X.join("/")}`,Q=z,F=z;if(($.method==="GET"||$.method==="HEAD")&&!W&&!Y&&B===null&&J.pathname.endsWith("/")&&!J.pathname.startsWith("//")){let _=J.pathname.replace(/\/+$/,""),k=U&&V.supportedLocales.includes(_.slice(1));if(_&&!k)return new Response("",{status:301,headers:{Location:`${_}${J.search}`}})}if(U&&!Y&&F===null&&!(F===null&&B!==null)){let _=d5(z,V.supportedLocales,V.defaultLocale);if(_){let k=X.length?`/${X.join("/")}`:"";return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${_}${k}${W?".json":""}${J.search}`}})}}if(U&&!Y){let _=H(u).detectLocale(new A($,{},"view",G));if(F===null&&_!==V.defaultLocale){let k=J.pathname==="/"?"":J.pathname;return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${_}${k}${J.search}`}})}}G=G.replace("//","/");let D=[],L=[],M=null,T={},N=null,K=!1,R=!1,C=[],S,w=!1,x=!1;try{let _=tZ(this.flatViewRoutes,G);if(F&&_?.route.middleware.includes(CB))_=null;if(_){if(w=!0,M=_.routePath,T=_.params,D=_.route.exec,L=_.route.middleware,C=_.route.features,K=L.includes("no-stream"),R=L.includes(yM),S=_.route.static,x=_.route.segments.at(-1)?.viewPath==="FILE",W&&this.partialRendering){let k=$.headers.get(L5),H0=fQ({flatViewRoutes:this.flatViewRoutes,supportedLocales:H(u).supportedLocales,from:k,origin:J.origin,to:{segments:_.route.segments,params:T,search:J.search}});if(H0.startIndex>0)D=D.slice(H0.startIndex),N={from:k,carriedViews:H0.carriedViews}}}}catch(_){throw _}if(S&&W)return new Response("Not found",{status:404});let q=new A($,T,"view",M);return this.hooks.onRequestStart(q),await P.run(q,async()=>{let _=null,k=P.getStore(),H0=eZ.getStore(),Y3=(g)=>eZ.run(H0,()=>P.runWith(k,g));k.serverQueries=new zZ(Z3($));let FZ=new Set;k.serverQueries.onQueryFail((g)=>{FZ.add(g.error);try{Y3(()=>Promise.resolve(this.hooks.onRequestFail(c,g.error)).catch(()=>{}))}catch{}});let C$=g5(x?{}:S??(M===null&&!W?this.notFound?.static:void 0));if(F){let g=F.replaceAll("/","");I$.setLocale(g,{cookie:C$.locale})}else if(V.isLocaleAware&&!U)k.setLocale(V.defaultLocale);else I$.setLocale(void 0,{cookie:C$.locale});let c=k.req;if(C$.session)Y8();try{let g=null;if(this.detectLocale&&!U&&H(u).isLocaleAware){let{supportedLocales:b,defaultLocale:r}=H(u),l1=await this.detectLocale(c,{supportedLocales:b,defaultLocale:r}),Z6=typeof l1==="string"?d5(l1,b,r):null;if(Z6)k.setLocale(Z6)}try{await H(n1).runMiddleware(L)}catch(b){if(g=this.viewRefusalStatus(c,b,FZ),g===null)throw b}if(g!==null||C.length>0&&!await this.passesFeatureGates(C))M=null,D=[],c.routePath="";let V0=H(u),B1=V0.isEnabled,A$=V0.isLocaleAware,j3=new A($,c.params),u0={defaultLocale:V0.defaultLocale,timeZone:V0.detectTimeZone(j3)};if(A$){let b=null;if(F)b=F.replaceAll("/",""),k.setLocale(b);else if(!U)b=k.locale??V0.defaultLocale;else b=V0.detectLocale(j3),k.setLocale(b);let r=B1?V0.getPageTranslations(b,c.routePath):{};u0={...u0,supportedLocales:V0.supportedLocales,currentLocale:b,dictionary:{[b]:r},defaultLocale:V0.defaultLocale,...U?{}:{localeRouting:"off"}}}await u5(u0.currentLocale??"");let S$;try{S$=await Promise.all(D.map((b)=>b(c)))}catch(b){if(g=this.viewRefusalStatus(c,b,FZ),g===null)throw b;M=null,D=[],c.routePath="",S$=[]}let C1=void 0;if(M===null){if(C1=await this.hooks.onNotFound(c,{status:g??404}),A$&&!U&&k.locale&&k.locale!==u0.currentLocale){let b=k.locale;u0={...u0,currentLocale:b,dictionary:{[b]:B1?V0.getPageTranslations(b,c.routePath):{}}},await u5(b)}}if(this.defaultMeta&&!k.metadata.hasAllDefaultFields)k.metadata.applyDefaults(typeof this.defaultMeta==="function"?await this.defaultMeta(c):this.defaultMeta);if(this.translate!==void 0)k.metadata.applyTranslateDefault(this.translate);let{cookies:A1,headers:l}=k;if(g!==null)l.set("Cache-Control","no-store");_={data:S$,cookies:A1,headers:l,user:k.user,prefetchedData:k.serverQueries.snapshotResolved(),currentPathName:M,params:c.params,urlLocaleSegment:Q,meta:k.renderMeta(),appId:H(H5).id,features:await H($$).forClient()};let{params:N8,user:P8}=_,t0={},VZ={};for(let b of S$??[]){let[r,l1]=Object.entries(b)?.[0]??[];if(!r||!l1)continue;VZ[`${r}:${M}`]=l1.breadcrumb,t0[r]=l1}let b$=M===null&&this.notFound&&!W?this.notFound.static:void 0;if(b$&&C1)t0["404"]=C1;let u1=t0.FILE;if(u1){try{await this.onRequestEnd(c,{mintSession:!1})}catch(r){GZ.error(r?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(r)})}let b;if(u1 instanceof Response)b=j8(u1,l,A1);else{for(let r of A1)l.append("Set-Cookie",r.toString());b=await w8(u1,l)}return PB(b,M)}if(W){l.set("Content-Type","application/x-ndjson; charset=utf-8"),l.append("Vary",L5),A1.forEach((r)=>l.append("Set-Cookie",r.toString())),y5(l,M),await this.hooks.onRequestEnd(c);let b={meta:N&&!k.metadata.touched?null:_.meta,data:{[G]:t0},breadcrumbs:VZ,prefetchedData:k.serverQueries.snapshotResolved(),i18n:u0,features:_.features,is404:!M,appId:_.appId,partial:N};return new Response(dQ(b,k.serverQueries,void 0,({aborted:r})=>Y3(()=>this.completeStream(c,k.serverQueries.summarize(r)))),{headers:l})}l.set("Content-Type","text/html; charset=utf-8");let E$=M?S:b$,y=Boolean(E$),F1=g5(E$);if(!K&&!y)l.append("Vary","User-Agent");if(!y||F1.session)Y8();for(let b of A1)l.append("Set-Cookie",b.toString());if(!y||F1.csrf){let b=Bun.CSRF.generate(process.env.SECRET);l.append("Set-Cookie",`csrf_token=${b}; HttpOnly; Secure; SameSite=Strict; Expires=${new Date(Date.now()+86400000).toUTCString()}`)}try{await this.onRequestEnd(c,{mintSession:!y||F1.session})}catch(b){GZ.error(b?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(b)})}if(y&&(M||!w))HB(l,E$);y5(l,M);let $6=y?void 0:SB($);if(!y)m5(l,this.csp,{nonce:$6});if(c5($))NB(l,M,y);return await this.render({req:c,runInRequestScope:Y3,csrfTokenHMAC:Buffer.from(""),currentPathName:M,headers:l,i18n:u0,params:N8,pathname:J.pathname,serverQueries:k.serverQueries,userAgent:$.headers.get("user-agent"),noStream:K,noTheme:R,url:J,user:P8,viewData:t0,breadcrumbs:VZ,urlLocaleSegment:Q,meta:_.meta,appId:_.appId,features:_.features,isOgRequest:Y,staticView:E$,refusedStatus:g??void 0,cspNonce:$6})}catch(g){if(g.kind===o1){let V0=W?dM(g.payload.viewData??g.payload.api):p5(g.payload.view);for(let B1 of k.cookies)V0.headers.append("Set-Cookie",B1.toString());return V0}if(!FZ.has(g))this.hooks.onRequestFail(c,g);if(a1(g))return console.error(g),W?rZ():p5(T5());if(g instanceof a0&&g.status===403)return W?rZ():p5(T5());throw g}},Z)}}function AB($,Z){return Z?$.map((J)=>vM(J,{nonce:Z})):$}function uM($,Z){let J=$.cookies?.get(Z);return bQ(J)?J:null}function lM($){return(Array.isArray($)?$:String($).split("/")).map((J)=>encodeURIComponent(String(J))).join("/")}function n5($,Z={}){let J=$.replace(/\/:(\w+)([*?]?)/g,(W,Y,j)=>{let z=Object.hasOwn(Z,Y)?Z[Y]:void 0;if(z===void 0||z===""){if(j)return"";throw Error(`\`${$}\` needs a value for :${Y}.`)}return`/${j==="*"?lM(z):encodeURIComponent(String(z))}`});return`${z8}${J==="/"?"":J}`||z8}var bB=new Map;function EB($,Z){let J=bB.get($);if(!J)J=new URLPattern({pathname:`${z8}${$==="/"?"":$}`}),bB.set($,J);let W;try{W=new URL(Z,"http://localhost").pathname}catch{return null}let Y=J.exec({pathname:W})?.pathname.groups;return Y?o5(Y):null}function o5($){let Z=[];try{for(let[J,W]of Object.entries($))if(W!==void 0)Z.push([J,decodeURIComponent(W)])}catch{return null}return Object.fromEntries(Z)}function a5(){let $=JSON.stringify({error:t1("not_found","Not found",404)});return new Response($,{status:404,headers:{"Content-Type":"application/json","Content-Length":String(Buffer.byteLength($)),"Cache-Control":"no-store"}})}class qB extends x0{routes={"/api-routes":this.get(()=>{let $=H(X8).flatRoutes,Z=[];for(let[J,W]of Object.entries($))for(let[Y,j]of Object.entries(W)){let{exec:z,middleware:X}=j;Z.push({path:J,method:Y,middleware:X})}return Z}),"/view-routes":this.get(()=>{let $=H(a3).flatViewRoutes,Z=[];for(let[J,{middleware:W,viewPath:Y}]of Object.entries($))Z.push({path:J,method:"GET",viewPath:Y,middleware:W});return Z})}}var iM=new Set([s1,"cookie","content-type","content-length","transfer-encoding","connection","host","user-agent","forwarded"]),sM=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,nM=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/;function oM($,Z,J,W){for(let[Y,j]of Object.entries(J.headers??{})){if(j===void 0||j===null)continue;let z=Y.toLowerCase();if(iM.has(z)||z.startsWith("x-forwarded-"))throw Error(`dispatchAs: credentials may not set the "${Y}" header. The access token stays the initiator's, and the request's framing is dispatchAs's own.`);if(W&&z==="authorization")throw Error(`dispatchAs: credentials may not set "Authorization" on a call dispatched as an identity. The caller's token is for the MCP endpoint and is never passed on.`);$.set(Y,j)}for(let[Y,j]of Object.entries(J.cookies??{})){if(j===void 0||j===null)continue;if(Y===s1)throw Error(`dispatchAs: credentials may not set the "${s1}" cookie. The access token stays the initiator's.`);if(!sM.test(Y)||!nM.test(j))throw Error(`dispatchAs: "${Y}" is not a cookie a Cookie header can carry.`);Z.push(`${Y}=${j}`)}}function aM($,Z){let J=$.body.getReader(),W=!1,Y=()=>{if(W)return;W=!0;try{Z()}catch(z){console.error(z)}},j=new ReadableStream({async pull(z){let X;try{X=await J.read()}catch(G){Y(),z.error(G);return}if(X.done){Y();try{z.close()}catch{}return}try{z.enqueue(X.value)}catch{}},async cancel(z){try{await J.cancel(z)}finally{Y()}}},{highWaterMark:0});return new Response(j,{status:$.status,statusText:$.statusText,headers:$.headers})}function RB($){let{status:Z=400,data:J,headers:W}=$,Y=new Headers({"Content-Type":"application/json",...W});if(!Y.has("Cache-Control"))Y.set("Cache-Control","no-store");return new Response(JSON.stringify(J),{status:Z,headers:Y})}function j8($,Z,J){let W=[];Z?.forEach((z,X)=>W.push([X,z]));let Y=[...typeof Z?.getSetCookie==="function"?Z.getSetCookie():[],...Array.from(J??[])];if(W.length===0&&Y.length===0)return $;let j=(z)=>{for(let[X,G]of W){if(X.toLowerCase()==="set-cookie")continue;if(!z.has(X))z.set(X,G)}for(let X of Y)z.append("Set-Cookie",X)};try{return j($.headers),$}catch{let z=new Headers($.headers);return j(z),new Response($.body,{status:$.status,statusText:$.statusText,headers:z})}}function tM(){return Bun.env.NODE_ENV==="development"}class X8{static token="router.api";flatRoutes={};onRequestStart;onRequestEnd;onRequestFail;constructor($){let Z=WQ();this.onRequestStart=$.onRequestStart??Z.onRequestStart,this.onRequestEnd=$.onRequestEnd??Z.onRequestEnd,this.onRequestFail=$.onRequestFail??Z.onRequestFail,this.flatRoutes=r7({"/":$.rootRouter,"/auth":i7,"/__gemi__/services/i18n":s7,"/__gemi__/services/image":a7,...tM()?{"/__gemi__/services/logs":t7,"/__gemi__/debug":qB}:{}})}getRouteHandlerAndParams($){let Z=new URL($.url),J=wB(Z.pathname),W={},Y;for(let[j]of Object.entries(this.flatRoutes))try{let X=new URLPattern({pathname:j}).exec({pathname:J});if(X){let G=o5(X.pathname.groups);if(!G)break;Y=j,W=G;break}}catch(z){console.error(z)}return{params:W,path:Y}}async runRouteMiddleware($,Z){let W=this.flatRoutes[$][Z.rawRequest.method].middleware;try{await H(n1).runMiddleware(W)}catch(Y){if(Y.kind===o1)return RB(Y.payload.api);else{if(w$(Y))return a5();if(this.onRequestFail(Z,Y),console.error(Y),a1(Y))return rZ();throw Y}}}async getRouteData($){let Z=this.flatRoutes[$],J=P.getStore(),W=Z[J.req.rawRequest.method].exec??(()=>Promise.resolve({})),Y={};try{Y=await W()}catch(j){if(j.kind===o1)return RB(j.payload.api);if(w$(j))return a5();if(this.onRequestFail(J.req,j),console.error(j),a1(j))return rZ();throw j}return Y}isFrameworkRoute($){return $.startsWith("/__gemi__")}async endRequest($,Z,J){let W=async()=>{try{if(!this.isFrameworkRoute(J))await this.onRequestEnd(Z)}catch(Y){GZ.error(Y?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(Y)})}finally{$.destroy()}};if(!$.hasPendingWork()){await W();return}$.whenIdle().then(W).catch((Y)=>{console.error(Y)})}isOpenEndedBody($,Z){return $.method!=="HEAD"&&!Z.headers.has("Content-Length")&&Z.body!==null}async handleApiRequest($,Z){let{params:J,path:W}=this.getRouteHandlerAndParams($),Y=this.flatRoutes[W];if(Y&&b2($)){let X={};for(let[G,Q]of Object.entries(Y))if(G!=="OPTIONS")X[G]=Q.cors;if(Object.values(X).some(Boolean))return E2($,X)}if(!Y||!Y[$.method])return new Response(JSON.stringify({error:t1("not_found","Not found",404)}),{status:404});let j=Y[$.method].cors,z=await this.dispatchRoute($,J,W,Z);return j?S2(z,j,$):z}async dispatchRoute($,Z,J,W){let Y=this.flatRoutes[J],j=new A($,Z,"api",J);if(!this.isFrameworkRoute(J))this.onRequestStart(j);return await P.run(j,async()=>{let z=P.getStore(),X=!1,G=async()=>{X=!0,await this.endRequest(z,j,J)};try{let Q=H(u);if(Q.isEnabled){let D=Q.detectLocale(j);z.setLocale(D)}z.setRequest(j),H(n1).applyDefaultBodyLimit($,Y[$.method].bodyLimitDefault);let F=await this.runRouteMiddleware(J,j);if(F instanceof Response){let D=j8(F,z.headers,z.cookies);return await G(),D}let V=await this.getRouteData(J),B=z.headers,U=z.cookies;if(V instanceof Response){let D=j8(V,B,U);if(this.isOpenEndedBody($,D)){let L=aM(D,()=>this.endRequest(z,j,J));return X=!0,L}return await G(),D}let O=(i1(V)?V:V1.json(V)).toResponse(B,U);return await G(),O}catch(Q){if(!X)try{await G()}catch(F){console.error(F)}throw Q}},W)}async dispatchAs($,Z,J,W,Y){let j=new URL($.rawRequest.url).origin,z=new URL(`${j}/api${J}`),X=`/api${J.split(/[?#]/)[0]}`;if(!J.startsWith("/")||z.origin!==j||z.pathname!==X||z.hash!==""||z.pathname.startsWith("/api/__gemi__")||z.pathname==="/api/auth"||z.pathname.startsWith("/api/auth/"))throw Error(`dispatchAs: "${J}" is not an app api path. Pass the route's own path, without "/api", with every param encoded.`);let G=Y?.identity;if(G!==void 0&&(typeof G!=="object"||!G?.user))throw Error("dispatchAs: identity needs the user to dispatch as.");let Q=new Headers,F=[],V=G?null:$.cookies.get(s1);if(V)F.push(`${s1}=${V}`);if(Y?.credentials)oM(Q,F,Y.credentials,G!==void 0);if(F.length>0)Q.set("Cookie",F.join("; "));let B=G?null:$.headers.get(s1);if(B)Q.set(s1,B);let U=$.headers.get("User-Agent");if(U)Q.set("User-Agent",U);let O;if(W instanceof FormData)O=W;else if(W!==void 0)Q.set("Content-Type","application/json"),O=JSON.stringify(W);let D=new Request(z,{method:Z,headers:Q,body:O,...Y?.signal?{signal:Y.signal}:{}});if(kB(D,D6($),G?.grant,Y?.progress),$.domain)$3(D,$.domain);let L=G?{user:G.user}:void 0;return P.exit(()=>Q6.exit(()=>this.handleApiRequest(D,L)))}}import{timingSafeEqual as rM}from"crypto";var B8="",e5="*",eM=60000,$H=1e4,G8=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,Q8=16,t5=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,r5="x-forwarded-host";function vB($){return $.startsWith(":")}function t3($,Z){if($===null)return!1;let J=Buffer.from($,"utf8"),W=Buffer.from(Z,"utf8");return J.length===W.length&&rM(J,W)}function ZH($){if(!$)return[];if($===!0)return[{header:r5,clientIpHeader:null,secret:null}];let Z=Array.isArray($)?$:[$],J=Array.isArray($)?null:r5;return Z.map((W)=>({header:W.hostHeader?.toLowerCase()??J,clientIpHeader:W.clientIpHeader?.toLowerCase()??null,secret:W.secret?{header:W.secret.header.toLowerCase(),value:W.secret.value}:null}))}function JH($){if(!$||$===!0)return;if(!Array.isArray($)){fB($,"route.domains.trustProxy",r5);return}if($.length===0)throw Error("`route.domains.trustProxy` is an empty list. List at least one proxy, or leave `trustProxy` out.");let Z=new Map;$.forEach((J,W)=>{let Y=`route.domains.trustProxy[${W}]`;if(typeof J!=="object"||J===null||Array.isArray(J))throw Error(`\`${Y}\` must be an object: { hostHeader?, clientIpHeader?, secret }. \`true\` is only accepted on its own.`);if(!J.secret)throw Error(`\`${Y}.secret\` is required: in a list, each proxy proves itself with a secret of its own.`);if(J.hostHeader===void 0&&J.clientIpHeader===void 0)throw Error(`\`${Y}\` names neither \`hostHeader\` nor \`clientIpHeader\`, so it would trust nothing.`);fB(J,Y,null);let j=Z.get(J.secret.value);if(j!==void 0)throw Error(`\`${Y}.secret.value\` is the same as \`route.domains.trustProxy[${j}].secret.value\`. Give each proxy a secret of its own.`);Z.set(J.secret.value,W)})}function fB($,Z,J){let{hostHeader:W,clientIpHeader:Y,secret:j}=$;if(W!==void 0&&(typeof W!=="string"||!t5.test(W)))throw Error(`\`${Z}.hostHeader\` must be a single header name, e.g. "x-forwarded-host". Got ${JSON.stringify(W)}.`);let z=(W??J)?.toLowerCase()??null;if(Y!==void 0){if(typeof Y!=="string"||!t5.test(Y))throw Error(`\`${Z}.clientIpHeader\` must be a single header name, e.g. "x-client-ip". Got ${JSON.stringify(Y)}.`);if(!j)throw Error(`\`${Z}.clientIpHeader\` needs \`secret\`: without proof the proxy sent it, any client that reaches the app directly picks its own address.`);if(Y.toLowerCase()===z)throw Error(`\`${Z}.clientIpHeader\` names the same header as \`hostHeader\`.`);if(typeof j.header==="string"&&Y.toLowerCase()===j.header.toLowerCase())throw Error(`\`${Z}.clientIpHeader\` names the same header as \`secret.header\`.`)}if(!j)return;if(typeof j.header!=="string"||!t5.test(j.header))throw Error(`\`${Z}.secret.header\` must be a header name. Got "${j.header}".`);if(j.header.toLowerCase()===z)throw Error(`\`${Z}.secret.header\` names the same header as \`hostHeader\`; the secret needs a header of its own.`);if(typeof j.value!=="string"||j.value.length<Q8)throw Error(`\`${Z}.secret.value\` must be at least ${Q8} characters. A guessable one lets any client name its own host.`)}function _1($){if(!$)return null;try{return new URL(`http://${$.trim()}`).hostname.toLowerCase().replace(/\.$/,"")||null}catch{return null}}function WH($){try{let Z=new URL(`http://${$.trim()}`),J=Z.hostname.toLowerCase().replace(/\.$/,"");return J?Z.port?`${J}:${Z.port}`:J:null}catch{return null}}function gB($){if($===void 0)return[];if($===!0)return!0;if(!Array.isArray($))throw Error(`\`route.domains.devHosts\` must be a list of hostnames (or \`true\`). Got ${JSON.stringify($)}.`);return $.map((Z,J)=>{let W=typeof Z==="string"?Z.trim().toLowerCase():"",Y=W.startsWith(".")?W.slice(1):W;if(!Y||!Y.split(".").every((j)=>G8.test(j)))throw Error(`\`route.domains.devHosts[${J}]\` must be a bare hostname, e.g. "app.acme.test", or ".acme.test" for the domain and its subdomains \u2014 no scheme, port, path or "*". Got ${JSON.stringify(Z)}.`);return W})}function YH($){let Z=_1($.root),J=$.root?.trim().toLowerCase().replace(/\.$/,"");if(!Z||Z!==J||!Z.split(".").every((j)=>G8.test(j)))throw Error(`\`route.domains.root\` must be a bare hostname, e.g. "example.com" \u2014 no scheme, port or path. Got "${$.root}".`);if($.custom&&($.custom.cacheTtlMs??0)<0)throw Error(`\`route.domains.custom.cacheTtlMs\` is ${$.custom.cacheTtlMs}; it cannot be negative. Use 0 to disable the cache.`);if($.ask&&$.ask.secret.length<Q8)throw Error(`\`route.domains.ask.secret\` must be at least ${Q8} characters. A guessable one is worse than leaving \`ask\` out.`);JH($.trustProxy),gB($.devHosts);let W=new Set,Y=null;for(let j of $.groups??[]){let{subdomain:z}=j;if(W.has(z))throw Error(`\`route.domains\` declares the subdomain "${z}" twice.`);if(W.add(z),vB(z)){if(!/^:[A-Za-z_][A-Za-z0-9_]*$/.test(z))throw Error(`"${z}" is not a valid param subdomain. It must be a single \`:name\` label.`);if(Y)throw Error(`\`route.domains\` declares two param subdomains, "${Y.subdomain}" and "${z}"; a host could match either.`);Y=j;continue}if(j.exists)throw Error(`The subdomain "${z}" is fixed, so \`exists\` has no param to check. It only applies to a \`:param\` subdomain.`);if(!z.split(".").every((X)=>G8.test(X)))throw Error(`"${z}" is not a valid subdomain.`)}if($.custom&&!W.has($.custom.group))throw Error(`\`route.domains.custom.group\` is "${$.custom.group}", but no group declares that subdomain.`);if($.ask&&Y&&!Y.exists)throw Error(`\`route.domains.ask\` is set, so "${Y.subdomain}" needs an \`exists\` to say which tenants are real. Without one every host under the root would be approved for a certificate.`)}class $2{root;devHosts;hostTrusts;fixed=new Map;param=null;custom;cacheTtlMs;cache=new Map;inFlight=new Map;askSecret;proxySecretHeaders;constructor($){YH($),this.root=_1($.root),this.devHosts=gB($.devHosts),this.hostTrusts=ZH($.trustProxy);for(let Z of $.groups??[])if(vB(Z.subdomain))this.param={...Z,name:Z.subdomain.slice(1)};else this.fixed.set(Z.subdomain.toLowerCase(),Z);this.custom=$.custom??null,this.cacheTtlMs=this.custom?.cacheTtlMs??eM,this.askSecret=$.ask?.secret??null,this.proxySecretHeaders=Array.from(new Set(this.hostTrusts.flatMap((Z)=>Z.secret?[Z.secret.header]:[])))}trustOf($){let Z=null;for(let J of this.hostTrusts)if((!J.secret||t3($.headers.get(J.secret.header),J.secret.value))&&!Z)Z=J;return Z}forwardedHost($){let Z=this.trustOf($)?.header;if(!Z)return null;return $.headers.get(Z)?.split(",")[0]?.trim()||null}trustedClientIp($){let Z=this.trustOf($);if(!Z?.clientIpHeader||!Z.secret)return null;let J=$.headers.get(Z.clientIpHeader)?.split(",")[0];return J===void 0?null:e1(J)}applyClientIp($){let Z=this.trustedClientIp($);if(!Z)return;$.headers.set("x-forwarded-for",Z),$.headers.delete("x-real-ip")}hostOf($){return _1(this.forwardedHost($))??_1(new URL($.url).host)}publicOrigin($){let Z=new URL($.url),J=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim(),W=J==="http"||J==="https"?J:Z.protocol.replace(/:$/,""),Y=this.forwardedHost($),j=Y&&_1(Y)?WH(Y):null;return`${W}://${j??Z.host}`}async resolve($){let Z=this.hostOf($);if(!Z)return null;let J=await this.match(Z,$);if(J)return J;if(this.custom?.fallback&&!this.isUnderRoot(Z))return{host:Z,group:e5,params:{},custom:!0};return null}async allows($,Z){let J=_1($);return J?await this.match(J,Z)!==null:!1}isUnderRoot($){return $===this.root||$.endsWith(`.${this.root}`)}async match($,Z){if($===this.root)return{host:$,group:B8,params:{},custom:!1};if($.endsWith(`.${this.root}`)){let W=$.slice(0,-(this.root.length+1)),Y=this.fixed.get(W);if(Y)return{host:$,group:Y.subdomain,params:{},custom:!1};if(this.param&&G8.test(W)){let j={[this.param.name]:W};if(this.param.exists&&!await this.param.exists(j,Z))return null;return{host:$,group:this.param.subdomain,params:j,custom:!1}}return null}if(!this.custom)return null;let J=await this.resolveCustom($);return J?{host:$,group:this.custom.group,params:J,custom:!0}:null}async resolveCustom($){let Z=Date.now(),J=this.cache.get($);if(J&&J.expiresAt>Z)return this.cache.delete($),this.cache.set($,J),J.value;let W=this.inFlight.get($);if(W)return W;let Y=(async()=>await this.custom.resolve($)??null)();this.inFlight.set($,Y);let j;try{j=await Y}finally{this.inFlight.delete($)}if(this.cacheTtlMs>0){if(this.cache.size>=$H)this.cache.delete(this.cache.keys().next().value);this.cache.delete($),this.cache.set($,{value:j,expiresAt:Date.now()+this.cacheTtlMs})}return j}forget($){if($===void 0)this.cache.clear();else{let Z=_1($);if(Z)this.cache.delete(Z)}}}var jH={kind:"none"};function ZS($){let Z=($??"").trim().toLowerCase();if(Z===""||Z==="false"||Z==="off"||Z==="0")return jH;if(Z==="true")return{kind:"all"};if(/^[1-9]\d*$/.test(Z))return{kind:"hops",hops:Number(Z)};throw Error(`GEMI_TRUST_PROXY must be "false", "true" or the number of proxies in front of the app (e.g. 1). Got ${JSON.stringify($)}.`)}function JS($,Z,J){if(J.kind==="all"){if(!$.get("x-forwarded-for")&&Z)$.set("x-forwarded-for",Z);return}$.delete("x-real-ip");let W=Z;if(J.kind==="hops"){let Y=($.get("x-forwarded-for")??"").split(",").map((X)=>X.trim()).filter(Boolean),j=Y.length-J.hops,z=j>=0?Y[j]:Y[0];W=(z===void 0?null:e1(z))??Z}if(W)$.set("x-forwarded-for",W);else $.delete("x-forwarded-for")}var yB=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,mB=16;function WS($){let Z=$.GEMI_CLIENT_IP_HEADER?.trim()??"",J=$.GEMI_PROXY_SECRET_HEADER?.trim()??"",W=$.GEMI_PROXY_SECRET??"";if(Z===""&&J===""&&W==="")return null;if(Z===""||J===""||W==="")throw Error("GEMI_CLIENT_IP_HEADER, GEMI_PROXY_SECRET_HEADER and GEMI_PROXY_SECRET go together: the client-IP header is only believed on a request that carries the proxy's secret. Set all three, or none.");if(!yB.test(Z))throw Error(`GEMI_CLIENT_IP_HEADER must be a single header name, e.g. "x-azure-clientip". Got ${JSON.stringify(Z)}.`);if(!yB.test(J))throw Error(`GEMI_PROXY_SECRET_HEADER must be a single header name, e.g. "x-azure-fdid". Got ${JSON.stringify(J)}.`);if(Z.toLowerCase()===J.toLowerCase())throw Error("GEMI_CLIENT_IP_HEADER and GEMI_PROXY_SECRET_HEADER name the same header.");if(W.length<mB)throw Error(`GEMI_PROXY_SECRET must be at least ${mB} characters. A guessable one lets any client name its own address.`);return{header:Z.toLowerCase(),secretHeader:J.toLowerCase(),secret:W}}function hB($,Z){if(!t3($.get(Z.secretHeader),Z.secret))return null;let J=$.get(Z.header)?.split(",")[0];return J===void 0?null:e1(J)}var zH="/__gemi__/domains/ask";class Q1{static token="router.domains";resolver;acceptsCustomDomains;clientIpTrust;groups=new Map;staticFilesVary=!1;constructor($,Z){this.groups.set(B8,$),this.clientIpTrust=Z.clientIpTrust??null;let{domains:J}=Z;if(this.acceptsCustomDomains=Boolean(J?.custom),!J){this.resolver=null;return}this.resolver=new $2(J);let W=(Y)=>({api:Y.api?new X8({...Z.api,...Y.api}):$.api,view:Y.view?new a3({...Z.view,...Y.view},Z.auth):$.view});for(let Y of J.groups??[])this.groups.set(Y.subdomain,W(Y));if(J.custom?.fallback)this.groups.set(e5,W(J.custom.fallback));this.staticFilesVary=this.viewDispatchers().some((Y)=>Y.publicFiles!==$.view.publicFiles||Y.assetRoutes!==$.view.assetRoutes||Y.assetCors!==$.view.assetCors)}async staticFiles($){let Z=(this.staticFilesVary?await this.route($):null)?.view??this.dispatchers(null).view;return{publicFiles:Z.publicFiles,assetRoutes:Z.assetRoutes,assetCors:Z.assetCors}}applyClientIp($){let Z=this.clientIpTrust;if(Z)Z2($,Z.secretHeader);let J=this.resolver?.trustedClientIp($)??(Z?hB($.headers,Z):null);if(!J)return;$.headers.set("x-forwarded-for",J),$.headers.delete("x-real-ip")}async route($){if(!this.resolver)return this.dispatchers(null);for(let J of this.resolver.proxySecretHeaders)Z2($,J);let Z=W8($)??await this.resolver.resolve($);if(!Z)return null;return $3($,Z),this.dispatchers(Z)}async ask($){if(!this.resolver?.askSecret||$.method!=="GET")return null;let Z=new URL($.url);if(Z.pathname!==zH)return null;if(!t3(Z.searchParams.get("secret"),this.resolver.askSecret))return null;let J=Z.searchParams.get("domain"),W=J?await this.resolver.allows(J,$):!1;return new Response(null,{status:W?200:404})}dispatchers($){return this.groups.get($?.group??B8)}viewDispatchers(){return Array.from(new Set(Array.from(this.groups.values(),($)=>$.view)))}viewGroups(){let $=new Set,Z=[];for(let[J,W]of this.groups){if($.has(W.view))continue;$.add(W.view),Z.push({group:J,view:W.view})}return Z}}function W3($){let Z=new Date($??0).getTime();return Number.isFinite(Z)?Z:0}var pB=600000;function cB($,Z){return[K6($,Z),K6($,Z-1)]}class E{static token="auth";config;provider;constructor($={},Z=new FJ){e9($.oauthProviders),this.config={...N$($Y($),$),emailCode:YJ($.emailCode),passwordLimits:WJ($.passwordLimits)},this.provider=Z}async oauthProvider($){return await NZ(this.config.oauthProviders,$)}async oauthProviderNames(){return await LY(this.config.oauthProviders)}get userProvider(){return this.provider}accessTokenCookieOptions($,Z){return{expires:Z,secure:this.publicOrigin($).startsWith("https://"),httpOnly:!0,domain:this.cookieDomain($)}}publicOrigin($){let Z=H().bound(Q1)?H(Q1).resolver:null;return Z?Z.publicOrigin($.rawRequest):new URL($.rawRequest.url).origin}cookieDomain($){let Z=this.config.cookieDomain;if(!Z)return;let J=Z==="root"?H(Q1).resolver?.root:_1(Z);if(!J)throw Error('`auth.cookieDomain` is "root", but `route.domains` is not configured.');let W=$.domain?.host??_1(new URL($.rawRequest.url).host);return W===J||W?.endsWith(`.${J}`)?J:void 0}async getSession($,Z){if(!$)return null;if(!o8($))return this.config.migrateLegacySession?this.convertLegacySession($,Z,this.config.migrateLegacySession):null;let J=await this.userProvider.findSession({token:$,userAgent:Z});if(!J?.user)return null;let W=Date.now(),Y=W3(J.expiresAt),j=W3(J.absoluteExpiresAt);if(Y<=W||j<=W)return await this.userProvider.deleteSession({token:$}),null;let X=await this.slideSession(J,W);return X.user.extension=await this.config.extendSession(X.user),X}async convertLegacySession($,Z,J){let W=P.getStore()?.req;if(!W)return null;let Y=Date.now(),j=Math.floor(Y/pB),z=null,X=await this.userProvider.findSession({token:$,userAgent:Z});if(X?.user){if(!await J(X,{token:$,req:W,userAgent:Z}))return null;let Q=K6($,j),F=X.user.id;if(await this.userProvider.withLegacySessionLock($,async()=>{if(!await this.userProvider.claimLegacySession({token:$}))return!1;return await this.userProvider.createSessionV2({token:Q,userId:F,userAgent:Z,...this.freshLifetime(Y)}),!0}))z=Q}if(!z){for(let Q of cB($,j))if((await this.userProvider.findSession({token:Q,userAgent:Z}))?.user){z=Q;break}}if(!z)return null;let G=await this.getSession(z,Z);if(G)W.ctx().setCookie("access_token",z,this.accessTokenCookieOptions(W,new Date(G.expiresAt)));return G}async revokeSession($,Z){if(!$)return await this.userProvider.deleteSession({token:$}),null;if(o8($)||!this.config.migrateLegacySession){let Y=await this.userProvider.findSession({token:$,userAgent:Z});return await this.userProvider.deleteSession({token:$}),Y}let J=Math.floor(Date.now()/pB),W=cB($,J);return this.userProvider.withLegacySessionLock($,async()=>{let Y=await this.userProvider.findSession({token:$,userAgent:Z});for(let j of W){if(Y?.user)break;Y=await this.userProvider.findSession({token:j,userAgent:Z})}await this.userProvider.deleteSession({token:$});for(let j of W)await this.userProvider.deleteSession({token:j});return Y})}requestCarryingCookie($){let Z=P.getStore()?.req;return Z?.cookies.get("access_token")===$?Z:null}async slideSession($,Z){let J=this.config.sessionExpiresInHours*3600000;if(new Date($.expiresAt).getTime()-Z>=J/2)return $;let W=new Date(Math.min(Z+J,new Date($.absoluteExpiresAt).getTime())),Y=await this.userProvider.updateSession({token:$.token,expiresAt:W}),j=this.requestCarryingCookie($.token);if(j)j.ctx().setCookie("access_token",$.token,this.accessTokenCookieOptions(j,W));if(!Y)return $;return{...$,expiresAt:Y.expiresAt??W}}freshLifetime($){return{expiresAt:new Date($+this.config.sessionExpiresInHours*3600000),absoluteExpiresAt:new Date($+this.config.sessionAbsoluteExpiresInHours*3600000)}}async generateMagicLink($){}async upsertSession($){await this.userProvider.findSession({token:"",userAgent:""})}async authenticate($){try{let Z=await this.userProvider.findUserByEmailAddress($,!1);if(!Z)throw Error(`User not found with email: ${$}`);let J=await this.createOrUpdateSession({email:$,id:Z.id}),W=new A;if(W.ctx().setCookie("access_token",J.token,this.accessTokenCookieOptions(W,J.expiresAt)),J?.user)J.user.extension=await this.config.extendSession(J.user);return J}catch(Z){console.log(Z)}}async createOrUpdateSessionV2($){let Z=await this.createOrUpdateSession($),J=null;if(Z?.user)J=await this.config.extendSession(Z.user),Z.user.extension=J;return Z}async createOrUpdateSession($){let Z=new A,J=$.id??(await this.userProvider.findUserByEmailAddress($.email,!1))?.id;if(!J)throw new q$;let W=Bun.env.NODE_ENV==="development"?"local":Z.headers.get("User-Agent"),Y=g9(J),j=await this.userProvider.createSessionV2({token:Y,userId:J,userAgent:W,...this.freshLifetime(Date.now())}),z=null;try{z=await this.userProvider.findSession({token:Y,userAgent:W??""})}catch(X){console.error("Reading the new session back failed:",X)}return z?.user?z:j}async createMagicLinkToken($){let Z=await this.userProvider.findUserByEmailAddress($,!1);if(Z){let{pin:J,token:W}=await this.issueOneTimeCode($,6);return{user:Z,email:$,pin:J,token:W}}return{}}async issueOneTimeCode($,Z){let{activeCodes:J,expiresInMinutes:W,linkExpiresInMinutes:Y}=this.config.emailCode,j=await this.config.generateMagicLinkToken($),z=await this.config.generateCode($),X=typeof z==="string"&&z!==""?z:d9(Z),G=_6("link",$,j),Q=_6("pin",$,X);if(J===1)await this.userProvider.deleteMagicLinkToken($);else{let F=Math.max(W,Y)*60000,B=(await this.userProvider.listMagicLinkTokensByEmail($,J-1)).filter((U)=>W3(U.createdAt)+F>Date.now()&&U.pin!==Q&&U.token!==G);await this.userProvider.deleteMagicLinkTokensExcept($,B.map((U)=>U.id))}return await this.userProvider.createMagicLinkToken({email:$,token:G,pin:Q}),{email:$,pin:X,token:j}}async oneTimeCodeRows($){let{activeCodes:Z}=this.config.emailCode;if(Z===1){let J=await this.userProvider.findMagicLinkTokenByEmail($);return J?[J]:[]}return await this.userProvider.listMagicLinkTokensByEmail($,Z)}async claimOneTimeCode($,Z){if(!await this.userProvider.claimMagicLinkToken(Z))return!1;if(this.config.emailCode.activeCodes>1)await this.userProvider.deleteMagicLinkToken($);return!0}async verifyOneTimeCode($,Z,J={}){let{expiresInMinutes:W,maxAttempts:Y}=this.config.emailCode,j=await this.oneTimeCodeRows($);if(j.length===0)return TZ("pin",$,null,Z),{status:"invalid"};let z=j.filter((Q)=>W3(Q.createdAt)+W*60000>Date.now());if(z.length===0)return TZ("pin",$,null,Z),{status:"expired"};let X=!0;for(let Q of z)if(!await i9(Q.id,W3(Q.createdAt),Y,W))X=!1;if(!X){if(this.config.emailCode.activeCodes===1)await this.userProvider.claimMagicLinkToken(z[0].id);else await this.userProvider.deleteMagicLinkToken($);return{status:"too_many_attempts"}}let G=null;for(let Q of z)if(TZ("pin",$,Q.pin,Z))G??=Q;if(!G)return{status:"invalid"};if(J.claim!==!1&&!await this.claimOneTimeCode($,G.id))return{status:"invalid"};return{status:"ok",row:G}}async verifyMagicLinkToken($,Z){let J=await this.oneTimeCodeRows($);if(J.length===0)return TZ("link",$,void 0,Z),!1;let W=null;for(let j of J)if(TZ("link",$,j.token,Z))W??=j;if(!W)return!1;if(W3(W.createdAt)+this.config.emailCode.linkExpiresInMinutes*60000<=Date.now())return!1;return await this.claimOneTimeCode($,W.id)}}class q0 extends h{static getFacadeAccessor(){return E}static async user(){let $=await q0.userOrNull();if($)return $;throw new q$({redirectTo:F6(P.getStore()?.req,this.getFacadeRoot().config.signInPath)})}static async userOrNull(){let $=P.getStore();if($?.user)return $.user;let Z=await j6(this.getFacadeRoot(),$?.req);if(Z)$?.setUser(Z);return Z}static intendedUrl($){let Z=P.getStore()?.req;return U1(Z?.search.get(l0),$??this.getFacadeRoot().config.redirectPath)}static async guard($){let Z=await q0.user();if(!await $(Z))throw new LZ}static async guardSafe($){let Z=await q0.user();try{return await $(Z)}catch(J){return!1}}static async authenticate($){return await this.getFacadeRoot().authenticate($)}static async oauthProviders(){return await this.getFacadeRoot().oauthProviderNames()}static async createMagicLink($){return await this.getFacadeRoot().createMagicLinkToken($)}}var J2="x-gemi-invalidate";function dB($){return encodeURIComponent(JSON.stringify([...new Set($)]))}function uB($){if(!$)return[];try{let Z=JSON.parse(decodeURIComponent($));return Array.isArray(Z)?Z.filter((J)=>typeof J==="string"):[]}catch{return[]}}class F8{static ensure($,Z={}){let J=P.getStore();if(J.req.kind==="api")throw Error("Query.prefetch() cannot be called from an API request");return J.serverQueries??=new zZ(Z3(J.req.rawRequest)),J.serverQueries.ensure($,Z,"prefetch")}static async instant($,...Z){let J=F8.ensure($,Z[0]);if(await J.promise,J.status==="rejected")throw J.error;return J.data}static prefetch($,...Z){F8.ensure($,Z[0])}static noPrefetch(){let $=P.getStore();if($.req.kind==="api")throw Error("Query.noPrefetch() cannot be called from an API request");$.serverQueries??=new zZ(Z3($.req.rawRequest)),$.serverQueries.muteDiscoveryHints()}static prefill($,Z,J){let W=P.getStore();if(W.req.kind==="api")throw Error("Query.prefill() cannot be called from an API request");W.serverQueries??=new zZ(Z3(W.req.rawRequest)),W.serverQueries.prefill($,Z,J)}static invalidate(...$){let Z=P.getStore(),J=uB(Z.headers.get(J2));Z.setHeaders(J2,dB([...J,...$]))}}function lB($,Z,J="/"){let W=new URL($.origin),Y=Z.host?Z.host:Z.subdomain?`${Z.subdomain}.${$.root}`:$.root,j=new URL(J.startsWith("/")?J:`/${J}`,W),z=XH(Y);if(!z)throw Error(`"${Y}" is not a hostname, so there is no URL for it. Give a bare host, optionally with a port \u2014 no scheme, path or credentials.`);if(j.hostname=z.hostname,z.port)j.port=z.port;return j.toString()}function XH($){try{let Z=new URL(`http://${$.trim()}`);return Z.host===$.trim().toLowerCase()&&Z.pathname==="/"?{hostname:Z.hostname,port:Z.port}:null}catch{return null}}class iB{static origin($){return W2($)}static absolute($,...Z){return`${WZ()}${D0(String($),Z[0]??{})}`}static relative($,...Z){return D0(String($),Z[0]??{})}static forDomain($,Z,...J){let W=H(Q1).resolver;if(!W)throw Error("`Url.forDomain` needs `route.domains` to be configured.");let Y=P.getStore()?.req?.rawRequest,j=Y?W.publicOrigin(Y):WZ();if(!j)throw Error("`Url.forDomain` outside a request needs `HOST_NAME` (or `APP_URL`) for the protocol.");return lB({root:W.root,origin:j},$,D0(String(Z),J[0]??{}))}static api($,...Z){return n5(String($),Z[0]??{})}static apiAbsolute($,...Z){return`${W2()}${n5(String($),Z[0]??{})}`}static matchApi($,Z){return EB(String($),Z)}}class sB{name="Meta";static description($){P.getStore().metadata.description($)}static title($){P.getStore().metadata.title($)}static openGraph($){P.getStore().metadata.openGraph($)}static htmlAttributes($){P.getStore().metadata.htmlAttributes($)}static canonical($){P.getStore().metadata.canonical($)}static alternates($){P.getStore().metadata.alternates($)}static tags($){P.getStore().metadata.tags($)}static robots($){P.getStore().metadata.robots($)}static translate($=!0){P.getStore().metadata.translate($)}static fonts($){P.getStore().metadata.fonts($)}}var GH={set($,Z,J){P.getStore().setCookie($,Z,J)},setIfAbsent($,Z,J){if(P.getStore().req.cookies.has($))return!1;return P.getStore().setCookie($,Z,J),!0},delete($,Z){P.getStore().deleteCookie($,Z)}};class d1 extends h{static getFacadeAccessor(){return QZ}static get client(){return this.getFacadeRoot().client}static get($){return d1.client.get($)}static set($,Z){return d1.client.set($,Z)}static del(...$){return d1.client.del(...$)}static exists($){return d1.client.exists($)}static incr($){return d1.client.incr($)}static expire($,Z){return d1.client.expire($,Z)}static ttl($){return d1.client.ttl($)}}function $b($){return $}function nB(){return{store:"memory",ttl:null}}class Y2{entries=new Map;maxEntries;now;constructor($={}){let Z=$.maxEntries??1e4;if(!Number.isInteger(Z)||Z<1)throw TypeError(`MemoryCacheStore maxEntries is a whole number of 1 or more; got ${Z}.`);this.maxEntries=Z,this.now=$.now??Date.now}get size(){return this.entries.size}async get($){let Z=this.live($);if(!Z)return null;return this.entries.delete($),this.entries.set($,Z),Z.value}async set($,Z,J){this.entries.delete($),this.entries.set($,{value:Z,expiresAt:J===null?null:this.now()+J});while(this.entries.size>this.maxEntries)this.entries.delete(this.entries.keys().next().value)}async delete($){let Z=this.live($)!==void 0;return this.entries.delete($),Z}async flush(){this.entries.clear()}live($){let Z=this.entries.get($);if(!Z)return;if(Z.expiresAt!==null&&Z.expiresAt<=this.now()){this.entries.delete($);return}return Z}}var QH="500";class j2{prefix;injectedClient;constructor($={}){this.injectedClient=$.client,this.prefix=$.prefix??"gemi:cache:"}async get($){let Z=await this.client.send("GET",[this.prefix+$]);return Z===null||Z===void 0?null:String(Z)}async set($,Z,J){let W=[this.prefix+$,Z];if(J!==null)W.push("PX",String(Math.max(1,Math.round(J))));await this.client.send("SET",W)}async delete($){return Number(await this.client.send("DEL",[this.prefix+$]))>0}async flush(){if(this.prefix==="")throw Error("RedisCacheStore refuses to flush with an empty prefix: that would delete every key in the database.");let $=this.client,Z=`${BH(this.prefix)}*`,J="0";do{let W=await $.send("SCAN",[J,"MATCH",Z,"COUNT",QH]),[Y,j]=Array.isArray(W)?W:["0",[]];if(J=String(Y),Array.isArray(j)&&j.length>0)await $.send("UNLINK",j.map(String))}while(J!=="0")}get client(){if(this.injectedClient)return this.injectedClient;let $=H(),Z=$.bound(QZ)?$.make(QZ).client:void 0;if(!Z)throw Error("RedisCacheStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisCacheStore({ client }).");return Z}}function BH($){return $.replace(/[*?[\]\\^-]/g,(Z)=>`\\${Z}`)}var FH="k:",oB="tag:",VH="t:";class z2{async get($){let Z=await this.manager.read(await this.storeKey($));return Z.found?Z.value:void 0}async has($){return(await this.manager.read(await this.storeKey($))).found}async set($,Z,J){await this.manager.write(await this.storeKey($),Z,J)}async delete($){return this.manager.store.delete(await this.storeKey($))}async pull($){let Z=await this.storeKey($),J=await this.manager.read(Z);if(!J.found)return;return await this.manager.store.delete(Z),J.value}async remember($,Z,J){let[W,Y]=typeof Z==="function"?[void 0,Z]:[Z,J];if(typeof Y!=="function")throw TypeError("Cache.remember needs a function that computes the value.");return this.manager.rememberAt(await this.storeKey($),W,Y)}}class X2 extends z2{options;static token="cache";config;builtStore;inflight=new Map;constructor($={},Z={}){super();this.options=Z;if(this.config=N$(nB(),$),this.config.ttl!==null&&this.config.ttl!==void 0)BZ(this.config.ttl)}get manager(){return this}get store(){return this.builtStore??=this.buildStore()}tags(...$){let Z=[...new Set($.flat())].sort();if(Z.length===0)throw TypeError("Cache.tags needs at least one tag.");for(let J of Z)if(typeof J!=="string"||J==="")throw TypeError(`A cache tag is a non-empty string; got ${JSON.stringify(J)}.`);return new tB(this,Z)}async flush(){await this.store.flush()}async storeKey($){return FH+rB($)}async read($){let Z=await this.store.get($);if(Z===null)return{found:!1};try{return{found:!0,value:JSON.parse(Z)}}catch{return{found:!1}}}async write($,Z,J){if(Z===void 0)throw TypeError("Cache.set cannot store undefined: get() returns undefined for a miss. Store null instead.");let W=this.ttlMs(J);if(W===0){await this.store.delete($);return}let Y=JSON.stringify(Z);if(Y===void 0)throw TypeError(`Cache.set cannot store a ${typeof Z}: it has no JSON form.`);await this.store.set($,Y,W)}async rememberAt($,Z,J){let W=await this.read($);if(W.found)return W.value;let Y=this.inflight.get($);if(Y)return Y;let j=(async()=>{try{let z=await J();if(z!==void 0)await this.write($,z,Z);return z}finally{this.inflight.delete($)}})();return this.inflight.set($,j),j}async tagVersions($){return Promise.all($.map(async(Z)=>{let J=oB+Z,W=await this.store.get(J);if(W!==null)return W;let Y=aB();return await this.store.set(J,Y,null),Y}))}async flushTags($){await Promise.all($.map((Z)=>this.store.set(oB+Z,aB(),null)))}ttlMs($){let Z=$===void 0?this.config.ttl:$;return Z===null||Z===void 0?null:BZ(Z)}buildStore(){let{store:$}=this.config;if($===void 0||$==="memory")return new Y2(this.config.memory);if($==="redis"){let Z=this.options.application;return new j2({...this.config.redis,client:Z?{send:(J,W)=>Z.make(QZ).client.send(J,W)}:void 0})}if(typeof $==="function"){let Z=this.options.application;if(!Z)throw Error("A cache store factory needs the application: build CacheManager with { application }.");return $(Z)}if($&&typeof $==="object")return $;throw Error(`Unknown cache store ${JSON.stringify($)} in app/config/cache.ts: use "memory", "redis", a CacheStore, or a function returning one.`)}}class tB extends z2{manager;tagNames;constructor($,Z){super();this.manager=$;this.tagNames=Z}async flush(){await this.manager.flushTags([...this.tagNames])}async storeKey($){rB($);let Z=await this.manager.tagVersions([...this.tagNames]);return`${VH}${Z.join(",")}:${$}`}}function rB($){if(typeof $!=="string"||$==="")throw TypeError(`A cache key is a non-empty string; got ${JSON.stringify($)}.`);return $}function aB(){let $=new Uint8Array(9);return crypto.getRandomValues($),Array.from($,(Z)=>Z.toString(16).padStart(2,"0")).join("")}class eB extends h{static getFacadeAccessor(){return X2}static get($){return this.getFacadeRoot().get($)}static has($){return this.getFacadeRoot().has($)}static set($,Z,J){return this.getFacadeRoot().set($,Z,J)}static delete($){return this.getFacadeRoot().delete($)}static pull($){return this.getFacadeRoot().pull($)}static remember($,Z,J){let W=this.getFacadeRoot();return typeof Z==="function"?W.remember($,Z):W.remember($,Z,J)}static tags(...$){return this.getFacadeRoot().tags(...$)}static flush(){return this.getFacadeRoot().flush()}}class $F extends h{static getFacadeAccessor(){return D1}static consume($,Z={}){return this.getFacadeRoot().consume($,Z)}static enforce($,Z={},J){return this.getFacadeRoot().enforce($,Z,J)}}class JF extends h{static getFacadeAccessor(){return ZF}static run($,Z,J){return this.getFacadeRoot().run($,Z,J)}static acquire($,Z={}){return this.getFacadeRoot().acquire($,Z)}}class YF extends h{static getFacadeAccessor(){return WF}static encrypt($){return this.getFacadeRoot().encrypt($)}static decrypt($){return this.getFacadeRoot().decrypt($)}static needsReencryption($){return this.getFacadeRoot().needsReencryption($)}}class jF extends h{static getFacadeAccessor(){return i3}static for($,Z,J){return this.getFacadeRoot().for($,Z,J)}static list($,Z){return this.getFacadeRoot().list($,Z)}static save($,Z,J){return this.getFacadeRoot().save($,Z,J)}static fake($={}){return this.getFacadeRoot().fake($)}static restore(){this.getFacadeRoot().restore()}}class zF extends h{static getFacadeAccessor(){return r3}static publish($,Z){return this.getFacadeRoot().publish($,Z)}static head($){return this.getFacadeRoot().head($)}static cursor($){return this.getFacadeRoot().cursor($)}static subscribe($,Z){return this.getFacadeRoot().subscribe($,Z)}static stream($,Z,J){return this.getFacadeRoot().stream($,Z,J)}}class e3 extends c0{application;previous;sent=[];revoked=[];static install($){let Z=$.bound(c0)?$.make(c0):void 0;if(Z instanceof e3)return Z;let J=new e3($,Z);return $.instance(c0,J),J}constructor($,Z){super({driver:"memory",maxEventBytes:Z?.config.maxEventBytes,warnEventBytes:Z?.config.warnEventBytes},{application:$});this.application=$;this.previous=Z;this.channelsFrom=Z}channelsFrom;get channels(){return this.channelsFrom?.channels??null}publish($){this.sent.push($)}sendRevocation($){this.revoked.push($)}restore(){if(this.previous){this.application.instance(c0,this.previous);return}this.application.forget(c0)}assertSent($,Z,J){if(this.matching($,Z,J).length>0)return;throw Error(`Expected ${G2($,Z,J)} to have been broadcast. ${this.summary()}`)}assertNotSent($,Z,J){let W=this.matching($,Z,J);if(W.length===0)return;throw Error(`Expected ${G2($,Z,J)} not to have been broadcast, but it was broadcast ${Q2(W.length)}: ${B2(W)}.`)}assertSentTimes($,Z,J,W){let Y=this.matching($,J,W);if(Y.length===Z)return;throw Error(`Expected ${G2($,J,W)} to have been broadcast ${Q2(Z)}, but it was broadcast ${Q2(Y.length)}. `+this.summary())}assertNothingSent(){if(this.sent.length===0)return;throw Error(`Expected nothing to have been broadcast, but ${this.sent.length} ${this.sent.length===1?"emit was":"emits were"}: ${B2(this.sent)}.`)}matching($,Z,J){return UZ($),this.sent.filter((W)=>(W.pattern===$||u2($,W.topic))&&(Z===void 0||W.event===Z)&&(J===void 0||J(W.data,W)))}summary(){if(this.sent.length===0)return"Nothing was broadcast.";return`Broadcast: ${B2(this.sent)}.`}}function G2($,Z,J){return`${Z?`"${Z}" on `:"an event on "}"${$}"`+(J?" matching the predicate":"")}function Q2($){return`${$} ${$===1?"time":"times"}`}function B2($){return $.map((Z)=>`${Z.topic} ${Z.event}(${UH(Z.data)})`).join(", ")}function UH($){if($===void 0)return"";try{return JSON.stringify($)??String($)}catch{return String($)}}class XF extends h{static getFacadeAccessor(){return c0}static to($,...Z){return this.getFacadeRoot().to($,...Z)}static toUser($){return this.getFacadeRoot().toUser($)}static toOthers($){return this.getFacadeRoot().toOthers($)}static revoke($){this.getFacadeRoot().revoke($)}static fake(){return e3.install(H())}}function mb($){return $}function GF(){return{store:"memory",sweepLimit:500}}var F2=["completed","failed","cancelled","timed_out"],I1=["pending","running"];function x1($){return F2.includes($)}class V2{runs=new Map;clock=0;get size(){return this.runs.size}async create($){if(this.runs.has($.id))throw Error(`A run with the id ${$.id} already exists.`);let Z=this.tick(),J={id:$.id,kind:$.kind,subject:$.subject,owner:$.owner,status:$.status,meta:structuredClone($.meta??null),progress:null,result:null,error:null,version:1,createdAt:Z,startedAt:$.status==="running"?Z:null,updatedAt:Z,finishedAt:null,deadlineAt:$.deadlineMs===null?null:Z+$.deadlineMs};return this.runs.set(J.id,J),structuredClone(J)}async get($){let Z=this.runs.get($);return Z?structuredClone(Z):null}async list($){let Z=[];for(let J of this.runs.values()){if($.kind!==void 0&&J.kind!==$.kind)continue;if($.subject!==void 0&&J.subject!==$.subject)continue;if($.owner!==void 0&&J.owner!==$.owner)continue;if($.statuses&&!$.statuses.includes(J.status))continue;Z.push(J)}return Z.reverse().sort((J,W)=>W.createdAt-J.createdAt),Z.slice(0,U2($.limit)).map((J)=>structuredClone(J))}async transition($,Z,J){let W=this.runs.get($);if(!W||!Z.includes(W.status))return null;let Y=structuredClone(J),j=this.tick();if(Y.status!==void 0){if(W.startedAt===null&&Y.status!=="pending")W.startedAt=j;if(x1(Y.status))W.finishedAt=j;W.status=Y.status}if("progress"in Y)W.progress=Y.progress??null;if("result"in Y)W.result=Y.result??null;if("error"in Y)W.error=Y.error??null;return W.version+=1,W.updatedAt=j,structuredClone(W)}async overdue($,Z){let J=[];for(let W of this.runs.values())if(I1.includes(W.status)&&W.deadlineAt!==null&&W.deadlineAt<=$)J.push(W);return J.sort((W,Y)=>W.deadlineAt-Y.deadlineAt),J.slice(0,Math.max(0,Z)).map((W)=>structuredClone(W))}async now(){return this.tick()}async prune($){let Z=this.tick()-$,J=0;for(let[W,Y]of this.runs)if(Y.finishedAt!==null&&Y.finishedAt<=Z)this.runs.delete(W),J++;return J}tick(){return this.clock=Math.max(this.clock,Date.now()),this.clock}}function U2($){if($===void 0)return 50;return Math.max(0,Math.floor($))}class L2{table;sql;dialect;connection;constructor($,Z={}){let J=Z.table??"gemi_runs";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(J))throw Error(`The runs table name "${J}" is not a plain identifier. Use letters, digits and underscores.`);this.table=J,this.sql=$.sql,this.dialect=$.dialect,this.connection=$.name}async createTable(){for(let $ of DH(this.dialect,this.table))await this.sql.unsafe($)}async create($){let Z=this.q(),J=this.clock(Z),W=$.deadlineMs===null?Z`NULL`:Z`${J} + ${this.ms(Z,$.deadlineMs)}`,Y=$.status==="running"?J:Z`NULL`;await Z`
|
|
23
|
+
${W}`)}let J=(await Z.outputs[0].text()).trim();if(/<\/script|<!--/i.test(J))throw Error(`The document script ${$} contains "</script" or "<!--", which would end the inline <script> it is put in. Write it "<\\/script" or build the string from parts.`);return J}function k5($){return`'sha256-${HM("sha256").update($).digest("base64")}'`}var S5,b5=new Map;function xM(){if(S5===void 0){let $=R5(E5(),"dist","server",PM);S5=QB($)?JSON.parse(TM($,"utf8")):null}return S5??null}async function w5($){_M($);let Z=Bun.env.NODE_ENV==="production";if(Z){let j=xM()?.[$];if(j!==void 0)return j;let z=b5.get($);if(z)return z}let J=R5(E5(),"app"),W=IM(J,$);if(!W)throw Error(`The document script "${$}" was not found. It is a file at app/views/${$}${BB}.ts (or .js).`);if(!Z)return GB(W);let Y=GB(W);return b5.set($,Y),Y.catch(()=>b5.delete($)),Y}async function VC($){return k5(await w5($))}var CM="gemi-islands",AM="gemi-island-i18n",SM="gemi-island-queries",NC=`'sha256-${VB("sha256").update(v5).digest("base64")}'`;function q5($,Z,J,W){if(!J)return $;let Y=W?$.lastIndexOf(Z):$.indexOf(Z);return Y===-1?$+J:$.slice(0,Y)+J+$.slice(Y)}var f5=($)=>$.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<"),PC=`'sha256-${VB("sha256").update(A5).digest("base64")}'`,bM='await import("/refresh.js").catch(()=>{});await import("/@vite/client").catch(()=>{});',EM="gemi-static";function UB($,Z,J,W,Y,j,z){let X=new Set,G=[];if(J)G=Z.islands.map((T)=>{let N=T.module?J(T.module):void 0;if(!N)return console.error(`[gemi] island ${T.module??"(unknown module)"}: no client build entry. Declare it as island(() => import("./Component")) so gemi's Vite plugin builds it.`),null;if(T.load==="eager"){for(let K of N.preload)X.add(K);if(T.preloadDynamic)for(let K of N.dynamicPreload??[])X.add(K)}return{s:N.src,e:T.export,l:T.load}});let Q=G.some((T)=>T!==null),F=j?`<script type="module" ${FB}="${f5(j.name)}">${j.source}</script>`:"";if(j)z?.push(j.source);if(!Q&&!Y)return q5($,"</head>",F,!1);let B=(Y?`<meta name="${EM}" content="${f5(Y.identity)}"${Y.prefetch==="none"?' data-prefetch="none"':""}/>`:"")+[...X].map((T)=>`<link rel="modulepreload" href="${f5(T)}"/>`).join("")+F,U=Y?A5:v5,O=W?bM+U:U;z?.push(O);let D=Q?WB(Z):void 0,L=Q?YB(Z):void 0,M=(Q?`<script type="application/json" id="${CM}">${i0({i:G})}</script>`:"")+(D?`<script type="application/json" id="${AM}">${i0(D)}</script>`:"")+(L?`<script type="application/json" id="${SM}">${i0(L)}</script>`:"")+`<script type="module">${O}</script>`;return q5(q5($,"</head>",B,!1),"</body>",M,!0)}function RM($,Z){let J=/<(\/?)template\b[^>]*>/gi;J.lastIndex=Z;let W=0;for(let Y=J.exec($);Y;Y=J.exec($))if(W+=Y[1]?-1:1,W===0)return J.lastIndex;return-1}function DB($){let Z=`<template ${zB}="`;for(let J=$.lastIndexOf(Z);J!==-1;J=$.lastIndexOf(Z)){let W=RM($,J);if(W===-1)break;let Y=J+Z.length,j=$.slice(Y,$.indexOf('"',Y)),z=$.indexOf(">",Y)+1,X=$.slice(z,W-11);$=$.slice(0,J)+$.slice(W);let G=`<${n3} ${jB}="${j}" style="display:contents"></${n3}>`;$=$.split(G).join(`<${n3} style="display:contents">${X}</${n3}>`)}return $}function g5($){if(!$)return{locale:!0,session:!0,csrf:!0};return{locale:!1,session:$.session===!0,csrf:$.csrf===!0}}function HB($,Z){if($.getSetCookie().length>0){if(Z.cacheControl&&Bun.env.NODE_ENV!=="production")console.warn(`[gemi] A static view with cacheControl "${Z.cacheControl}" set a cookie, so it was sent "private, no-store" instead. Static pages are cacheable only when nothing on them sets a cookie.`);$.set("Cache-Control","private, no-store");return}if(Z.cacheControl&&!$.has("Cache-Control"))$.set("Cache-Control",Z.cacheControl)}function kM($){let Z=$.headers.get("Cache-Control")?.toLowerCase()??"";return/(^|[\s,])(public|s-maxage)\b/.test(Z)}var OB=new Set,wM=new Set(["public","private","s-maxage","proxy-revalidate"]);function y5($,Z){let J=$.get("Cache-Control");if(!J||$.getSetCookie().length===0)return;if(!/(^|[\s,])(public|s-maxage)\b/i.test(J))return;let W=TB(J);if(Bun.env.NODE_ENV!=="production"&&!OB.has(Z)){OB.add(Z);let Y=[...new Set($.getSetCookie().map((j)=>j.split("=")[0]))];console.warn(`[gemi] The view "${Z??""}" sets cookies (${Y.join(", ")}) on a response with Cache-Control "${J}", so it was sent "${W}" instead: a shared cache would hand those cookies to every visitor. To let a CDN cache the page, make it a static view with .static({ cacheControl }).`)}$.set("Cache-Control",W)}function TB($){return["private",...$.split(",").map((J)=>J.trim()).filter((J)=>{let W=J.split("=")[0].trim().toLowerCase();return W!==""&&!wM.has(W)})].join(", ")}var LB=new Set;function NB($,Z,J){let W=$.get("Cache-Control");if(!W||!/(^|[\s,])(public|s-maxage)\b/i.test(W))return;let Y=TB(W);if(J&&Bun.env.NODE_ENV!=="production"&&!LB.has(Z))LB.add(Z),console.warn(`[gemi] The static view "${Z??""}" asked for a CSP nonce (cspNonce()) on a response with Cache-Control "${W}", so it was sent "${Y}" instead: a shared cache would hand the same nonce to every visitor. Allow a static page's scripts by hash instead (route.view.csp does).`);$.set("Cache-Control",Y)}var MB=new Set;function PB($,Z){if(!kM($)||$.headers.getSetCookie().length===0)return $;if(Bun.env.NODE_ENV!=="production"&&!MB.has(Z))MB.add(Z),console.warn(`[gemi] The file route "${Z??""}" set a cookie on a response with Cache-Control "${$.headers.get("Cache-Control")}", so the cookie was not sent: a shared cache would hand it to every visitor. Make the response private, or set the cookie elsewhere.`);try{return $.headers.delete("Set-Cookie"),$}catch{let J=new Headers($.headers);return J.delete("Set-Cookie"),new Response($.body,{status:$.status,statusText:$.statusText,headers:J})}}var qM="'strict-dynamic' 'self' https: 'unsafe-inline'",KB="Content-Security-Policy",_B="Content-Security-Policy-Report-Only";function fM($,Z={}){let J=[...$.nonce?[`'nonce-${$.nonce}'`]:[],...$.hashes??[]],W=[J.length>0?`script-src ${J.join(" ")} ${qM}`:"script-src 'none'","object-src 'none'","base-uri 'self'"];if(Z.reportUri)W.push(`report-uri ${Z.reportUri}`);return W.join("; ")}function m5($,Z,J){if(!Z)return;if($.has(KB)||$.has(_B))return;let W=Z===!0?{}:Z;$.set(W.reportOnly?_B:KB,fM({nonce:J.nonce,hashes:[...new Set(J.inlineScripts??[])].map(k5)},W))}var gM=async()=>(await import("./chunk-1mb7kaxs.js")).default,h5,o3=async(...$)=>{return h5??=import("react-dom/server.browser").catch((Z)=>{throw h5=void 0,Z}),(await h5).renderToReadableStream(...$)},xB=1e4,CB="no-locale",yM="no-theme";async function mM($,Z,J){let W=`${J==="italic"?"italic,":""}wght@${J==="italic"?"1,":""}${Z}`,z=(await(await fetch(`https://fonts.googleapis.com/css2?family=${$}:${W}&display=swap`,{headers:{"User-Agent":"Mozilla/5.0 Firefox/1.0"}})).text()).match(/url\(([^)]+)\)/)?.[1];return await fetch(z).then((X)=>X.arrayBuffer())}var i5="/assets";function hM($){return $===i5||$.startsWith(`${i5}/`)}function pM($){let Z=$.filter(hM);if(Z.length>0){let J=Z.length>1;throw Error(`View route path${J?"s":""} ${Z.map((W)=>`"${W}"`).join(", ")} use${J?"":"s"} the reserved "${i5}" prefix. The client build output is served from there before the router runs, so the route would never match. Mount it somewhere else, or set \`assetRoutes: true\` on these views' config (route.view or a route.domains group's view).`)}}function cM($){let Z=H(Q1).resolver;return{...$.domain,root:Z.root,origin:Z.publicOrigin($.rawRequest)}}function p5($){let{status:Z=400,error:J,body:W,...Y}=$;return new Response(W??J?.message,{...Y,status:Z})}function dM($){let{status:Z=400,data:J,directive:W,headers:Y}=$;return new Response(JSON.stringify({data:J,directive:W}),{headers:Y,status:Z})}class a3{static token="router.view";flatViewRoutes={};routeManifest={};clientRouteManifest={};componentTree=[];flatComponentTree=[];requiredViews={};staticRoutes=[];root=null;shellReporter=pQ();preloadCache=new WeakMap;hooks;partialRendering;localeRouting;detectLocale;theme;defaultMeta;notFound;publicFiles;assetRoutes;assetCors;translate;csp;constructor($,Z={}){let J=YQ();if(this.partialRendering=$.partialRendering??J.partialRendering,this.localeRouting=$.localeRouting??J.localeRouting,this.detectLocale=$.detectLocale,this.detectLocale&&this.localeRouting!=="off")throw Error('`view.detectLocale` needs `view.localeRouting: "off"`: on locale-routed views the URL, the `i18n-locale` cookie and `Accept-Language` decide the locale. A `route.domains` group that inherits it and keeps locale routing can set `detectLocale: undefined`.');this.theme=$.theme??J.theme,this.defaultMeta=$.meta,this.notFound=$.notFound,this.publicFiles=$.publicFiles??J.publicFiles,this.assetRoutes=$.assetRoutes??J.assetRoutes,this.assetCors=$.assetCors??J.assetCors,this.translate=$.translate,this.csp=$.csp,this.hooks={onNotFound:$.onNotFound??J.onNotFound,onRequestStart:$.onRequestStart??J.onRequestStart,onRequestEnd:$.onRequestEnd??J.onRequestEnd,onRequestFail:$.onRequestFail??J.onRequestFail,onStreamComplete:$.onStreamComplete??J.onStreamComplete};let W={"/":$.rootRouter,"/auth":aG(Z)};if(this.requiredViews=Object.fromEntries(nG(Z).map(({view:Y,requiredBy:j})=>[Y,j])),this.flatViewRoutes=e4(W),!this.assetRoutes)pM(Object.keys(this.flatViewRoutes));this.routeManifest=$8(W),this.clientRouteManifest=Object.fromEntries(Object.entries(this.routeManifest).filter(([,Y])=>Y.at(-1)!=="FILE")),this.componentTree=J8(W),this.flatComponentTree=M5(this.componentTree),this.staticRoutes=Object.entries(this.flatViewRoutes).filter(([,Y])=>Y.static).map(([Y])=>Y);for(let Y of this.staticRoutes){let j=this.flatViewRoutes[Y].static?.layout;if(j&&!this.flatComponentTree.includes(j))this.flatComponentTree.push(j)}if(this.notFound){for(let Y of[this.notFound.view,this.notFound.static?.layout])if(Y&&!this.flatComponentTree.includes(Y))this.flatComponentTree.push(Y)}this.root=$.root}async passesFeatureGates($){let Z=H($$);for(let J of $)if(!await Z.enabled(J))return!1;return!0}async onRequestEnd($,Z={}){if(Z.mintSession!==!1)Y8();return await this.hooks.onRequestEnd($)}completeStream($,Z){let J=(W)=>{GZ.error(W?.message??'Error in "onStreamComplete" event handler',{err:JSON.stringify(W)})};try{Promise.resolve(this.hooks.onStreamComplete($,Z)).catch(J)}catch(W){J(W)}}modulePreloadLinks($){let{clientEntry:Z,modulePreloadManifest:J,views:W,routeKey:Y}=$,j=()=>{let G=new Set(Z?.preload??[]);for(let Q of W)for(let F of J?.[Q]??[])G.add(F);return[...G].map((Q)=>c1("link",{key:`modulepreload:${Q}`,rel:"modulepreload",href:Q}))};if(!J)return j();let z=this.preloadCache.get(J);if(!z||z.clientEntry!==Z)z={clientEntry:Z,byRoute:new Map},this.preloadCache.set(J,z);let X=z.byRoute.get(Y);if(!X)X=j(),z.byRoute.set(Y,X);return X}async renderStatic($){let{req:Z,runInRequestScope:J,staticView:W,currentViews:Y,data:j,serverQueries:z,headers:X}=$,G;if(W.layout){if(G=$.viewImportMap[W.layout],!G)throw Error(`The static layout "${W.layout}" was not found. It is a view path: a file at app/views/${W.layout}.tsx whose default export renders the document.`)}let Q=await $.getStyles(Y,{static:!0,layout:W.layout});z.markRenderStart();let F=l5(),V=new AbortController,B=setTimeout(()=>V.abort(),xB),U=(D)=>{if(Bun.env.NODE_ENV!=="production")console.error(D)},O=JB(async(D,L)=>{let M=await o3(D,{signal:V.signal,identifierPrefix:L,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:U});return await M.allReady.catch(()=>{}),await new Response(M).text()},{currentLocale:j?.i18n?.currentLocale,defaultLocale:j?.i18n?.defaultLocale,timeZone:j?.i18n?.timeZone},z);try{let D,L=typeof W.script==="function"?await J(()=>W.script(Z)):W.script;if(L)D={name:L,source:await w5(L)};let M;if(W.navigation){let C=W.navigation===!0?{}:W.navigation,S=C.version?String(await J(()=>C.version(Z))):"";M={identity:[W.layout??"",$.buildId??"",D?.name??"",S].join("|"),prefetch:C.prefetch==="none"?"none":"intent"}}let T=await o3(c1(XB.Provider,{value:O,children:c1(IB,{children:[...Q,c1(this.root,{data:j,viewImportMap:$.viewImportMap,viewModules:$.viewModules,serverQueries:z,dictionarySink:F,rootLayout:G,key:"root"})]})}),{signal:V.signal,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:U});await T.allReady.catch(()=>{});let N=DB(await new Response(T).text()),K=[],R=UB(N,O,$.resolveIsland,Bun.env.NODE_ENV!=="production",M,D,K);return m5(X,this.csp,{nonce:c5(Z.rawRequest),inlineScripts:K}),new Response(R,{status:$.status,headers:X})}finally{clearTimeout(B),J(()=>this.completeStream(Z,z.summarize(V.signal.aborted)))}}async render($){let{req:Z,runInRequestScope:J,csrfTokenHMAC:W,currentPathName:Y,headers:j,i18n:z,params:X,pathname:G,serverQueries:Q,userAgent:F,noStream:V,noTheme:B,url:U,user:O,viewData:D,breadcrumbs:L,urlLocaleSegment:M,meta:T,isOgRequest:N,appId:K,features:R,staticView:C,cspNonce:S}=$,w=this.theme===!1||B||C?null:{cookie:this.theme.cookie??O5,default:this.theme.default??null,value:uM(Z,this.theme.cookie??O5)},x=M?mQ(G,[M]).pathname:G,q={kind:"view",data:{meta:T,pageData:{[x]:D},__csrf:W.toString("base64"),prefetchedData:{},i18n:z,auth:{user:O},routeManifest:this.clientRouteManifest,breadcrumbs:L,router:{urlLocaleSegment:M,pathname:Y,params:X,currentPath:G,searchParams:U.search,is404:!Y?!0:!1,domain:Z.domain?cM(Z):null},appId:K,features:R,theme:w,componentTree:[["404",[]],...this.componentTree],...this.staticRoutes.length>0?{staticRoutes:this.staticRoutes}:{}},head:{}},_=this.root,k=this.routeManifest[Y];return async(H0)=>{let{bootstrapModules:Y3=[],loaders:FZ,getStyles:C$,viewImportMap:c,cssManifest:g,ogMap:V0,viewModules:B1,clientEntry:A$,modulePreloadManifest:j3,assetBase:u0,resolveIsland:S$,buildId:C1}=H0,A1=A$?[]:Y3,l=(y)=>[y,`window.loaders=${FZ}`,...A$?[`import(${JSON.stringify(A$.module)}).catch(function(e){setTimeout(function(){throw e})})`]:[]].join(";");if(N){let y=null,F1=null;for(let b of k??[])if(typeof V0[b]==="function")F1=b,y=V0[b];if(!y)return new Response("Not found",{status:404});let $6=Object.values(q.data.pageData)[0];try{await o3(c1(y,$6[F1]),{onError:()=>{}})}catch(b){let{fonts:r,...l1}=b.satoriOptions,Z6=await Promise.all(r.map((J6)=>{return mM(J6.name,J6.weight,J6.style).then((EF)=>({...J6,data:EF}))})),T2=new Headers(j);T2.set("Content-Type","image/png");let[CF,AF]=await Promise.all([gM(),a4("Rendering an OG image")]),SF=await CF(b.jsx,{...l1,fonts:Z6}),bF=await AF(Buffer.from(SF)).png({compressionLevel:0,effort:10}).toBuffer();return new Response(new Uint8Array(bF),{headers:T2})}return new Response("data")}if(C&&Y)return await this.renderStatic({req:Z,runInRequestScope:J,staticView:C,currentViews:k,data:q.data,serverQueries:Q,headers:j,getStyles:C$,viewImportMap:c,viewModules:B1,resolveIsland:S$,buildId:C1,status:200});if(C&&!Y&&this.notFound){let y=this.notFound.view;if(!c[y])throw Error(`The not-found view "${y}" (route.view.notFound) was not found. It is a view path: a file at app/views/${y}.tsx.`);return await this.renderStatic({req:Z,runInRequestScope:J,staticView:C,currentViews:[y],data:q.data,serverQueries:Q,headers:j,getStyles:C$,viewImportMap:{...c,"404":c[y]},viewModules:B1&&{...B1,"404":B1[y]},resolveIsland:S$,buildId:C1,status:$.refusedStatus??404})}if(q.data.cssManifest=g,q.data.modulePreloadManifest=j3??{},u0&&u0!=="/")q.data.assetBase=u0;if(C1&&C1!=="dev")q.data.buildId=C1;let N8=AB(this.modulePreloadLinks({clientEntry:A$,modulePreloadManifest:j3,views:k??["404"],routeKey:Y??"404"}),S),P8=AB(await C$(k??["404"]),S);q.data.prefetchedData=Q.snapshotResolved(),Q.markRenderStart();let t0=new AbortController,VZ=setTimeout(()=>t0.abort(),xB),b$=C6(F)||V,u1=Bun.env.NODE_ENV!=="production"&&!b$&&Y&&this.shellReporter.shouldObserve(Y)?cQ():null,E$=l5();try{let y=await o3(c1(IB,{children:yQ(N8,[...P8,...w?[c1("script",{key:"theme-script",nonce:S,dangerouslySetInnerHTML:{__html:EQ(i0({cookie:w.cookie,default:w.default}))}})]:[]],c1(_,{data:q.data,viewImportMap:c,viewModules:B1,serverQueries:Q,dictionarySink:E$,cspNonce:S,key:"root"}))}),{bootstrapScriptContent:l(`window.__GEMI_DATA__ = ${i0(q.data)}`),bootstrapModules:A1,nonce:S,signal:t0.signal,...b$?{progressiveChunkSize:Number.MAX_SAFE_INTEGER}:{},onError(F1){if(Bun.env.NODE_ENV!=="production")console.error(F1)}});if(y.allReady.catch(()=>{}).finally(()=>clearTimeout(VZ)),b$)await y.allReady.catch(()=>{});return new Response(jJ(y,Q,{onShell:b$?void 0:()=>Q.markShell(),onChunk:u1?.onChunk,onClose:()=>J(()=>{if(this.completeStream(Z,Q.summarize(t0.signal.aborted)),u1)this.shellReporter.report(Y,u1.measure())})},E$,S),{status:!Y?$.refusedStatus??404:200,headers:j})}catch(y){if(clearTimeout(VZ),Bun.env.NODE_ENV==="production")throw J(()=>this.completeStream(Z,Q.summarize(t0.signal.aborted))),y;let F1=await o3(c1("div"),{bootstrapScriptContent:l(`window.error= ${i0(y.message)}; window.stack_trace=${i0(y.stack)};window.__GEMI_DATA__ = ${i0(q.data)}`),bootstrapModules:Bun.env.NODE_ENV==="development"?["/render-error.js",...A1]:A1,nonce:S});return new Response(jJ(F1,Q,{onClose:()=>J(()=>this.completeStream(Z,Q.summarize(t0.signal.aborted)))},void 0,S),{status:!Y?$.refusedStatus??404:200,headers:j})}}}viewRefusalStatus($,Z,J){if(w$(Z))return 404;if(Z?.kind===o1){let W=Z.payload?.view?.status;return W===403||W===404?W:null}if(a1(Z)){if(!J.has(Z))this.hooks.onRequestFail($,Z);return console.error(Z),403}if(Z instanceof a0&&(Z.status===403||Z.status===404))return Z.status;return null}async handleViewRequest($,Z){let J=new URL($.url),W=kQ(this.flatViewRoutes,J.pathname),Y=wQ(this.flatViewRoutes,J.pathname),j=W?J.pathname.slice(0,-5):Y?J.pathname.slice(0,-3):J.pathname,[,z,...X]=j.split("/"),G=j,Q=null,F=null,V=H(u),B=tZ(this.flatViewRoutes,j),U=V.isLocaleAware&&this.localeRouting==="prefix"&&!B?.route.middleware.includes(CB);if(U&&V.supportedLocales.includes(z))G=`/${X.join("/")}`,Q=z,F=z;if(($.method==="GET"||$.method==="HEAD")&&!W&&!Y&&B===null&&J.pathname.endsWith("/")&&!J.pathname.startsWith("//")){let _=J.pathname.replace(/\/+$/,""),k=U&&V.supportedLocales.includes(_.slice(1));if(_&&!k)return new Response("",{status:301,headers:{Location:`${_}${J.search}`}})}if(U&&!Y&&F===null&&!(F===null&&B!==null)){let _=d5(z,V.supportedLocales,V.defaultLocale);if(_){let k=X.length?`/${X.join("/")}`:"";return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${_}${k}${W?".json":""}${J.search}`}})}}if(U&&!Y){let _=H(u).detectLocale(new A($,{},"view",G));if(F===null&&_!==V.defaultLocale){let k=J.pathname==="/"?"":J.pathname;return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${_}${k}${J.search}`}})}}G=G.replace("//","/");let D=[],L=[],M=null,T={},N=null,K=!1,R=!1,C=[],S,w=!1,x=!1;try{let _=tZ(this.flatViewRoutes,G);if(F&&_?.route.middleware.includes(CB))_=null;if(_){if(w=!0,M=_.routePath,T=_.params,D=_.route.exec,L=_.route.middleware,C=_.route.features,K=L.includes("no-stream"),R=L.includes(yM),S=_.route.static,x=_.route.segments.at(-1)?.viewPath==="FILE",W&&this.partialRendering){let k=$.headers.get(L5),H0=fQ({flatViewRoutes:this.flatViewRoutes,supportedLocales:H(u).supportedLocales,from:k,origin:J.origin,to:{segments:_.route.segments,params:T,search:J.search}});if(H0.startIndex>0)D=D.slice(H0.startIndex),N={from:k,carriedViews:H0.carriedViews}}}}catch(_){throw _}if(S&&W)return new Response("Not found",{status:404});let q=new A($,T,"view",M);return this.hooks.onRequestStart(q),await P.run(q,async()=>{let _=null,k=P.getStore(),H0=eZ.getStore(),Y3=(g)=>eZ.run(H0,()=>P.runWith(k,g));k.serverQueries=new zZ(Z3($));let FZ=new Set;k.serverQueries.onQueryFail((g)=>{FZ.add(g.error);try{Y3(()=>Promise.resolve(this.hooks.onRequestFail(c,g.error)).catch(()=>{}))}catch{}});let C$=g5(x?{}:S??(M===null&&!W?this.notFound?.static:void 0));if(F){let g=F.replaceAll("/","");I$.setLocale(g,{cookie:C$.locale})}else if(V.isLocaleAware&&!U)k.setLocale(V.defaultLocale);else I$.setLocale(void 0,{cookie:C$.locale});let c=k.req;if(C$.session)Y8();try{let g=null;if(this.detectLocale&&!U&&H(u).isLocaleAware){let{supportedLocales:b,defaultLocale:r}=H(u),l1=await this.detectLocale(c,{supportedLocales:b,defaultLocale:r}),Z6=typeof l1==="string"?d5(l1,b,r):null;if(Z6)k.setLocale(Z6)}try{await H(n1).runMiddleware(L)}catch(b){if(g=this.viewRefusalStatus(c,b,FZ),g===null)throw b}if(g!==null||C.length>0&&!await this.passesFeatureGates(C))M=null,D=[],c.routePath="";let V0=H(u),B1=V0.isEnabled,A$=V0.isLocaleAware,j3=new A($,c.params),u0={defaultLocale:V0.defaultLocale,timeZone:V0.detectTimeZone(j3)};if(A$){let b=null;if(F)b=F.replaceAll("/",""),k.setLocale(b);else if(!U)b=k.locale??V0.defaultLocale;else b=V0.detectLocale(j3),k.setLocale(b);let r=B1?V0.getPageTranslations(b,c.routePath):{};u0={...u0,supportedLocales:V0.supportedLocales,currentLocale:b,dictionary:{[b]:r},defaultLocale:V0.defaultLocale,...U?{}:{localeRouting:"off"}}}await u5(u0.currentLocale??"");let S$;try{S$=await Promise.all(D.map((b)=>b(c)))}catch(b){if(g=this.viewRefusalStatus(c,b,FZ),g===null)throw b;M=null,D=[],c.routePath="",S$=[]}let C1=void 0;if(M===null){if(C1=await this.hooks.onNotFound(c,{status:g??404}),A$&&!U&&k.locale&&k.locale!==u0.currentLocale){let b=k.locale;u0={...u0,currentLocale:b,dictionary:{[b]:B1?V0.getPageTranslations(b,c.routePath):{}}},await u5(b)}}if(this.defaultMeta&&!k.metadata.hasAllDefaultFields)k.metadata.applyDefaults(typeof this.defaultMeta==="function"?await this.defaultMeta(c):this.defaultMeta);if(this.translate!==void 0)k.metadata.applyTranslateDefault(this.translate);let{cookies:A1,headers:l}=k;if(g!==null)l.set("Cache-Control","no-store");_={data:S$,cookies:A1,headers:l,user:k.user,prefetchedData:k.serverQueries.snapshotResolved(),currentPathName:M,params:c.params,urlLocaleSegment:Q,meta:k.renderMeta(),appId:H(H5).id,features:await H($$).forClient()};let{params:N8,user:P8}=_,t0={},VZ={};for(let b of S$??[]){let[r,l1]=Object.entries(b)?.[0]??[];if(!r||!l1)continue;VZ[`${r}:${M}`]=l1.breadcrumb,t0[r]=l1}let b$=M===null&&this.notFound&&!W?this.notFound.static:void 0;if(b$&&C1)t0["404"]=C1;let u1=t0.FILE;if(u1){try{await this.onRequestEnd(c,{mintSession:!1})}catch(r){GZ.error(r?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(r)})}let b;if(u1 instanceof Response)b=j8(u1,l,A1);else{for(let r of A1)l.append("Set-Cookie",r.toString());b=await w8(u1,l)}return PB(b,M)}if(W){l.set("Content-Type","application/x-ndjson; charset=utf-8"),l.append("Vary",L5),A1.forEach((r)=>l.append("Set-Cookie",r.toString())),y5(l,M),await this.hooks.onRequestEnd(c);let b={meta:N&&!k.metadata.touched?null:_.meta,data:{[G]:t0},breadcrumbs:VZ,prefetchedData:k.serverQueries.snapshotResolved(),i18n:u0,features:_.features,is404:!M,appId:_.appId,partial:N};return new Response(dQ(b,k.serverQueries,void 0,({aborted:r})=>Y3(()=>this.completeStream(c,k.serverQueries.summarize(r)))),{headers:l})}l.set("Content-Type","text/html; charset=utf-8");let E$=M?S:b$,y=Boolean(E$),F1=g5(E$);if(!K&&!y)l.append("Vary","User-Agent");if(!y||F1.session)Y8();for(let b of A1)l.append("Set-Cookie",b.toString());if(!y||F1.csrf){let b=Bun.CSRF.generate(process.env.SECRET);l.append("Set-Cookie",`csrf_token=${b}; HttpOnly; Secure; SameSite=Strict; Expires=${new Date(Date.now()+86400000).toUTCString()}`)}try{await this.onRequestEnd(c,{mintSession:!y||F1.session})}catch(b){GZ.error(b?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(b)})}if(y&&(M||!w))HB(l,E$);y5(l,M);let $6=y?void 0:SB($);if(!y)m5(l,this.csp,{nonce:$6});if(c5($))NB(l,M,y);return await this.render({req:c,runInRequestScope:Y3,csrfTokenHMAC:Buffer.from(""),currentPathName:M,headers:l,i18n:u0,params:N8,pathname:J.pathname,serverQueries:k.serverQueries,userAgent:$.headers.get("user-agent"),noStream:K,noTheme:R,url:J,user:P8,viewData:t0,breadcrumbs:VZ,urlLocaleSegment:Q,meta:_.meta,appId:_.appId,features:_.features,isOgRequest:Y,staticView:E$,refusedStatus:g??void 0,cspNonce:$6})}catch(g){if(g.kind===o1){let V0=W?dM(g.payload.viewData??g.payload.api):p5(g.payload.view);for(let B1 of k.cookies)V0.headers.append("Set-Cookie",B1.toString());return V0}if(!FZ.has(g))this.hooks.onRequestFail(c,g);if(a1(g))return console.error(g),W?rZ():p5(T5());if(g instanceof a0&&g.status===403)return W?rZ():p5(T5());throw g}},Z)}}function AB($,Z){return Z?$.map((J)=>vM(J,{nonce:Z})):$}function uM($,Z){let J=$.cookies?.get(Z);return bQ(J)?J:null}function lM($){return(Array.isArray($)?$:String($).split("/")).map((J)=>encodeURIComponent(String(J))).join("/")}function n5($,Z={}){let J=$.replace(/\/:(\w+)([*?]?)/g,(W,Y,j)=>{let z=Object.hasOwn(Z,Y)?Z[Y]:void 0;if(z===void 0||z===""){if(j)return"";throw Error(`\`${$}\` needs a value for :${Y}.`)}return`/${j==="*"?lM(z):encodeURIComponent(String(z))}`});return`${z8}${J==="/"?"":J}`||z8}var bB=new Map;function EB($,Z){let J=bB.get($);if(!J)J=new URLPattern({pathname:`${z8}${$==="/"?"":$}`}),bB.set($,J);let W;try{W=new URL(Z,"http://localhost").pathname}catch{return null}let Y=J.exec({pathname:W})?.pathname.groups;return Y?o5(Y):null}function o5($){let Z=[];try{for(let[J,W]of Object.entries($))if(W!==void 0)Z.push([J,decodeURIComponent(W)])}catch{return null}return Object.fromEntries(Z)}function a5(){let $=JSON.stringify({error:t1("not_found","Not found",404)});return new Response($,{status:404,headers:{"Content-Type":"application/json","Content-Length":String(Buffer.byteLength($)),"Cache-Control":"no-store"}})}class qB extends x0{routes={"/api-routes":this.get(()=>{let $=H(X8).flatRoutes,Z=[];for(let[J,W]of Object.entries($))for(let[Y,j]of Object.entries(W)){let{exec:z,middleware:X}=j;Z.push({path:J,method:Y,middleware:X})}return Z}),"/view-routes":this.get(()=>{let $=H(a3).flatViewRoutes,Z=[];for(let[J,{middleware:W,viewPath:Y}]of Object.entries($))Z.push({path:J,method:"GET",viewPath:Y,middleware:W});return Z})}}var iM=new Set([s1,"cookie","content-type","content-length","transfer-encoding","connection","host","user-agent","forwarded"]),sM=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,nM=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/;function oM($,Z,J,W){for(let[Y,j]of Object.entries(J.headers??{})){if(j===void 0||j===null)continue;let z=Y.toLowerCase();if(iM.has(z)||z.startsWith("x-forwarded-"))throw Error(`dispatchAs: credentials may not set the "${Y}" header. The access token stays the initiator's, and the request's framing is dispatchAs's own.`);if(W&&z==="authorization")throw Error(`dispatchAs: credentials may not set "Authorization" on a call dispatched as an identity. The caller's token is for the MCP endpoint and is never passed on.`);$.set(Y,j)}for(let[Y,j]of Object.entries(J.cookies??{})){if(j===void 0||j===null)continue;if(Y===s1)throw Error(`dispatchAs: credentials may not set the "${s1}" cookie. The access token stays the initiator's.`);if(!sM.test(Y)||!nM.test(j))throw Error(`dispatchAs: "${Y}" is not a cookie a Cookie header can carry.`);Z.push(`${Y}=${j}`)}}function aM($,Z){let J=$.body.getReader(),W=!1,Y=()=>{if(W)return;W=!0;try{Z()}catch(z){console.error(z)}},j=new ReadableStream({async pull(z){let X;try{X=await J.read()}catch(G){Y(),z.error(G);return}if(X.done){Y();try{z.close()}catch{}return}try{z.enqueue(X.value)}catch{}},async cancel(z){try{await J.cancel(z)}finally{Y()}}},{highWaterMark:0});return new Response(j,{status:$.status,statusText:$.statusText,headers:$.headers})}function RB($){let{status:Z=400,data:J,headers:W}=$,Y=new Headers({"Content-Type":"application/json",...W});if(!Y.has("Cache-Control"))Y.set("Cache-Control","no-store");return new Response(JSON.stringify(J),{status:Z,headers:Y})}function j8($,Z,J){let W=[];Z?.forEach((z,X)=>W.push([X,z]));let Y=[...typeof Z?.getSetCookie==="function"?Z.getSetCookie():[],...Array.from(J??[])];if(W.length===0&&Y.length===0)return $;let j=(z)=>{for(let[X,G]of W){if(X.toLowerCase()==="set-cookie")continue;if(!z.has(X))z.set(X,G)}for(let X of Y)z.append("Set-Cookie",X)};try{return j($.headers),$}catch{let z=new Headers($.headers);return j(z),new Response($.body,{status:$.status,statusText:$.statusText,headers:z})}}function tM(){return Bun.env.NODE_ENV==="development"}class X8{static token="router.api";flatRoutes={};onRequestStart;onRequestEnd;onRequestFail;constructor($){let Z=WQ();this.onRequestStart=$.onRequestStart??Z.onRequestStart,this.onRequestEnd=$.onRequestEnd??Z.onRequestEnd,this.onRequestFail=$.onRequestFail??Z.onRequestFail,this.flatRoutes=r7({"/":$.rootRouter,"/auth":i7,"/__gemi__/services/i18n":s7,"/__gemi__/services/image":a7,...tM()?{"/__gemi__/services/logs":t7,"/__gemi__/debug":qB}:{}})}getRouteHandlerAndParams($){let Z=new URL($.url),J=wB(Z.pathname),W={},Y;for(let[j]of Object.entries(this.flatRoutes))try{let X=new URLPattern({pathname:j}).exec({pathname:J});if(X){let G=o5(X.pathname.groups);if(!G)break;Y=j,W=G;break}}catch(z){console.error(z)}return{params:W,path:Y}}async runRouteMiddleware($,Z){let W=this.flatRoutes[$][Z.rawRequest.method].middleware;try{await H(n1).runMiddleware(W)}catch(Y){if(Y.kind===o1)return RB(Y.payload.api);else{if(w$(Y))return a5();if(this.onRequestFail(Z,Y),console.error(Y),a1(Y))return rZ();throw Y}}}async getRouteData($){let Z=this.flatRoutes[$],J=P.getStore(),W=Z[J.req.rawRequest.method].exec??(()=>Promise.resolve({})),Y={};try{Y=await W()}catch(j){if(j.kind===o1)return RB(j.payload.api);if(w$(j))return a5();if(this.onRequestFail(J.req,j),console.error(j),a1(j))return rZ();throw j}return Y}isFrameworkRoute($){return $.startsWith("/__gemi__")}async endRequest($,Z,J){let W=async()=>{try{if(!this.isFrameworkRoute(J))await this.onRequestEnd(Z)}catch(Y){GZ.error(Y?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(Y)})}finally{$.destroy()}};if(!$.hasPendingWork()){await W();return}$.whenIdle().then(W).catch((Y)=>{console.error(Y)})}isOpenEndedBody($,Z){return $.method!=="HEAD"&&!Z.headers.has("Content-Length")&&Z.body!==null}async handleApiRequest($,Z){let{params:J,path:W}=this.getRouteHandlerAndParams($),Y=this.flatRoutes[W];if(Y&&b2($)){let X={};for(let[G,Q]of Object.entries(Y))if(G!=="OPTIONS")X[G]=Q.cors;if(Object.values(X).some(Boolean))return E2($,X)}if(!Y||!Y[$.method])return new Response(JSON.stringify({error:t1("not_found","Not found",404)}),{status:404});let j=Y[$.method].cors,z=await this.dispatchRoute($,J,W,Z);return j?S2(z,j,$):z}async dispatchRoute($,Z,J,W){let Y=this.flatRoutes[J],j=new A($,Z,"api",J);if(!this.isFrameworkRoute(J))this.onRequestStart(j);return await P.run(j,async()=>{let z=P.getStore(),X=!1,G=async()=>{X=!0,await this.endRequest(z,j,J)};try{let Q=H(u);if(Q.isEnabled){let D=Q.detectLocale(j);z.setLocale(D)}z.setRequest(j),H(n1).applyDefaultBodyLimit($,Y[$.method].bodyLimitDefault);let F=await this.runRouteMiddleware(J,j);if(F instanceof Response){let D=j8(F,z.headers,z.cookies);return await G(),D}let V=await this.getRouteData(J),B=z.headers,U=z.cookies;if(V instanceof Response){let D=j8(V,B,U);if(this.isOpenEndedBody($,D)){let L=aM(D,()=>this.endRequest(z,j,J));return X=!0,L}return await G(),D}let O=(i1(V)?V:V1.json(V)).toResponse(B,U);return await G(),O}catch(Q){if(!X)try{await G()}catch(F){console.error(F)}throw Q}},W)}async dispatchAs($,Z,J,W,Y){let j=new URL($.rawRequest.url).origin,z=new URL(`${j}/api${J}`),X=`/api${J.split(/[?#]/)[0]}`;if(!J.startsWith("/")||z.origin!==j||z.pathname!==X||z.hash!==""||z.pathname.startsWith("/api/__gemi__")||z.pathname==="/api/auth"||z.pathname.startsWith("/api/auth/"))throw Error(`dispatchAs: "${J}" is not an app api path. Pass the route's own path, without "/api", with every param encoded.`);let G=Y?.identity;if(G!==void 0&&(typeof G!=="object"||!G?.user))throw Error("dispatchAs: identity needs the user to dispatch as.");let Q=new Headers,F=[],V=G?null:$.cookies.get(s1);if(V)F.push(`${s1}=${V}`);if(Y?.credentials)oM(Q,F,Y.credentials,G!==void 0);if(F.length>0)Q.set("Cookie",F.join("; "));let B=G?null:$.headers.get(s1);if(B)Q.set(s1,B);let U=$.headers.get("User-Agent");if(U)Q.set("User-Agent",U);let O;if(W instanceof FormData)O=W;else if(W!==void 0)Q.set("Content-Type","application/json"),O=JSON.stringify(W);let D=new Request(z,{method:Z,headers:Q,body:O,...Y?.signal?{signal:Y.signal}:{}});if(kB(D,D6($),G?.grant,Y?.progress),$.domain)$3(D,$.domain);let L=G?{user:G.user}:void 0;return P.exit(()=>Q6.exit(()=>this.handleApiRequest(D,L)))}}import{timingSafeEqual as rM}from"crypto";var B8="",e5="*",eM=60000,$H=1e4,G8=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,Q8=16,t5=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,r5="x-forwarded-host";function vB($){return $.startsWith(":")}function t3($,Z){if($===null)return!1;let J=Buffer.from($,"utf8"),W=Buffer.from(Z,"utf8");return J.length===W.length&&rM(J,W)}function ZH($){if(!$)return[];if($===!0)return[{header:r5,clientIpHeader:null,secret:null}];let Z=Array.isArray($)?$:[$],J=Array.isArray($)?null:r5;return Z.map((W)=>({header:W.hostHeader?.toLowerCase()??J,clientIpHeader:W.clientIpHeader?.toLowerCase()??null,secret:W.secret?{header:W.secret.header.toLowerCase(),value:W.secret.value}:null}))}function JH($){if(!$||$===!0)return;if(!Array.isArray($)){fB($,"route.domains.trustProxy",r5);return}if($.length===0)throw Error("`route.domains.trustProxy` is an empty list. List at least one proxy, or leave `trustProxy` out.");let Z=new Map;$.forEach((J,W)=>{let Y=`route.domains.trustProxy[${W}]`;if(typeof J!=="object"||J===null||Array.isArray(J))throw Error(`\`${Y}\` must be an object: { hostHeader?, clientIpHeader?, secret }. \`true\` is only accepted on its own.`);if(!J.secret)throw Error(`\`${Y}.secret\` is required: in a list, each proxy proves itself with a secret of its own.`);if(J.hostHeader===void 0&&J.clientIpHeader===void 0)throw Error(`\`${Y}\` names neither \`hostHeader\` nor \`clientIpHeader\`, so it would trust nothing.`);fB(J,Y,null);let j=Z.get(J.secret.value);if(j!==void 0)throw Error(`\`${Y}.secret.value\` is the same as \`route.domains.trustProxy[${j}].secret.value\`. Give each proxy a secret of its own.`);Z.set(J.secret.value,W)})}function fB($,Z,J){let{hostHeader:W,clientIpHeader:Y,secret:j}=$;if(W!==void 0&&(typeof W!=="string"||!t5.test(W)))throw Error(`\`${Z}.hostHeader\` must be a single header name, e.g. "x-forwarded-host". Got ${JSON.stringify(W)}.`);let z=(W??J)?.toLowerCase()??null;if(Y!==void 0){if(typeof Y!=="string"||!t5.test(Y))throw Error(`\`${Z}.clientIpHeader\` must be a single header name, e.g. "x-client-ip". Got ${JSON.stringify(Y)}.`);if(!j)throw Error(`\`${Z}.clientIpHeader\` needs \`secret\`: without proof the proxy sent it, any client that reaches the app directly picks its own address.`);if(Y.toLowerCase()===z)throw Error(`\`${Z}.clientIpHeader\` names the same header as \`hostHeader\`.`);if(typeof j.header==="string"&&Y.toLowerCase()===j.header.toLowerCase())throw Error(`\`${Z}.clientIpHeader\` names the same header as \`secret.header\`.`)}if(!j)return;if(typeof j.header!=="string"||!t5.test(j.header))throw Error(`\`${Z}.secret.header\` must be a header name. Got "${j.header}".`);if(j.header.toLowerCase()===z)throw Error(`\`${Z}.secret.header\` names the same header as \`hostHeader\`; the secret needs a header of its own.`);if(typeof j.value!=="string"||j.value.length<Q8)throw Error(`\`${Z}.secret.value\` must be at least ${Q8} characters. A guessable one lets any client name its own host.`)}function _1($){if(!$)return null;try{return new URL(`http://${$.trim()}`).hostname.toLowerCase().replace(/\.$/,"")||null}catch{return null}}function WH($){try{let Z=new URL(`http://${$.trim()}`),J=Z.hostname.toLowerCase().replace(/\.$/,"");return J?Z.port?`${J}:${Z.port}`:J:null}catch{return null}}function gB($){if($===void 0)return[];if($===!0)return!0;if(!Array.isArray($))throw Error(`\`route.domains.devHosts\` must be a list of hostnames (or \`true\`). Got ${JSON.stringify($)}.`);return $.map((Z,J)=>{let W=typeof Z==="string"?Z.trim().toLowerCase():"",Y=W.startsWith(".")?W.slice(1):W;if(!Y||!Y.split(".").every((j)=>G8.test(j)))throw Error(`\`route.domains.devHosts[${J}]\` must be a bare hostname, e.g. "app.acme.test", or ".acme.test" for the domain and its subdomains \u2014 no scheme, port, path or "*". Got ${JSON.stringify(Z)}.`);return W})}function YH($){let Z=_1($.root),J=$.root?.trim().toLowerCase().replace(/\.$/,"");if(!Z||Z!==J||!Z.split(".").every((j)=>G8.test(j)))throw Error(`\`route.domains.root\` must be a bare hostname, e.g. "example.com" \u2014 no scheme, port or path. Got "${$.root}".`);if($.custom&&($.custom.cacheTtlMs??0)<0)throw Error(`\`route.domains.custom.cacheTtlMs\` is ${$.custom.cacheTtlMs}; it cannot be negative. Use 0 to disable the cache.`);if($.ask&&$.ask.secret.length<Q8)throw Error(`\`route.domains.ask.secret\` must be at least ${Q8} characters. A guessable one is worse than leaving \`ask\` out.`);JH($.trustProxy),gB($.devHosts);let W=new Set,Y=null;for(let j of $.groups??[]){let{subdomain:z}=j;if(W.has(z))throw Error(`\`route.domains\` declares the subdomain "${z}" twice.`);if(W.add(z),vB(z)){if(!/^:[A-Za-z_][A-Za-z0-9_]*$/.test(z))throw Error(`"${z}" is not a valid param subdomain. It must be a single \`:name\` label.`);if(Y)throw Error(`\`route.domains\` declares two param subdomains, "${Y.subdomain}" and "${z}"; a host could match either.`);Y=j;continue}if(j.exists)throw Error(`The subdomain "${z}" is fixed, so \`exists\` has no param to check. It only applies to a \`:param\` subdomain.`);if(!z.split(".").every((X)=>G8.test(X)))throw Error(`"${z}" is not a valid subdomain.`)}if($.custom&&!W.has($.custom.group))throw Error(`\`route.domains.custom.group\` is "${$.custom.group}", but no group declares that subdomain.`);if($.ask&&Y&&!Y.exists)throw Error(`\`route.domains.ask\` is set, so "${Y.subdomain}" needs an \`exists\` to say which tenants are real. Without one every host under the root would be approved for a certificate.`)}class $2{root;devHosts;hostTrusts;fixed=new Map;param=null;custom;cacheTtlMs;cache=new Map;inFlight=new Map;askSecret;proxySecretHeaders;constructor($){YH($),this.root=_1($.root),this.devHosts=gB($.devHosts),this.hostTrusts=ZH($.trustProxy);for(let Z of $.groups??[])if(vB(Z.subdomain))this.param={...Z,name:Z.subdomain.slice(1)};else this.fixed.set(Z.subdomain.toLowerCase(),Z);this.custom=$.custom??null,this.cacheTtlMs=this.custom?.cacheTtlMs??eM,this.askSecret=$.ask?.secret??null,this.proxySecretHeaders=Array.from(new Set(this.hostTrusts.flatMap((Z)=>Z.secret?[Z.secret.header]:[])))}trustOf($){let Z=null;for(let J of this.hostTrusts)if((!J.secret||t3($.headers.get(J.secret.header),J.secret.value))&&!Z)Z=J;return Z}forwardedHost($){let Z=this.trustOf($)?.header;if(!Z)return null;return $.headers.get(Z)?.split(",")[0]?.trim()||null}trustedClientIp($){let Z=this.trustOf($);if(!Z?.clientIpHeader||!Z.secret)return null;let J=$.headers.get(Z.clientIpHeader)?.split(",")[0];return J===void 0?null:e1(J)}applyClientIp($){let Z=this.trustedClientIp($);if(!Z)return;$.headers.set("x-forwarded-for",Z),$.headers.delete("x-real-ip")}hostOf($){return _1(this.forwardedHost($))??_1(new URL($.url).host)}publicOrigin($){let Z=new URL($.url),J=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim(),W=J==="http"||J==="https"?J:Z.protocol.replace(/:$/,""),Y=this.forwardedHost($),j=Y&&_1(Y)?WH(Y):null;return`${W}://${j??Z.host}`}async resolve($){let Z=this.hostOf($);if(!Z)return null;let J=await this.match(Z,$);if(J)return J;if(this.custom?.fallback&&!this.isUnderRoot(Z))return{host:Z,group:e5,params:{},custom:!0};return null}async allows($,Z){let J=_1($);return J?await this.match(J,Z)!==null:!1}isUnderRoot($){return $===this.root||$.endsWith(`.${this.root}`)}async match($,Z){if($===this.root)return{host:$,group:B8,params:{},custom:!1};if($.endsWith(`.${this.root}`)){let W=$.slice(0,-(this.root.length+1)),Y=this.fixed.get(W);if(Y)return{host:$,group:Y.subdomain,params:{},custom:!1};if(this.param&&G8.test(W)){let j={[this.param.name]:W};if(this.param.exists&&!await this.param.exists(j,Z))return null;return{host:$,group:this.param.subdomain,params:j,custom:!1}}return null}if(!this.custom)return null;let J=await this.resolveCustom($);return J?{host:$,group:this.custom.group,params:J,custom:!0}:null}async resolveCustom($){let Z=Date.now(),J=this.cache.get($);if(J&&J.expiresAt>Z)return this.cache.delete($),this.cache.set($,J),J.value;let W=this.inFlight.get($);if(W)return W;let Y=(async()=>await this.custom.resolve($)??null)();this.inFlight.set($,Y);let j;try{j=await Y}finally{this.inFlight.delete($)}if(this.cacheTtlMs>0){if(this.cache.size>=$H)this.cache.delete(this.cache.keys().next().value);this.cache.delete($),this.cache.set($,{value:j,expiresAt:Date.now()+this.cacheTtlMs})}return j}forget($){if($===void 0)this.cache.clear();else{let Z=_1($);if(Z)this.cache.delete(Z)}}}var jH={kind:"none"};function ZS($){let Z=($??"").trim().toLowerCase();if(Z===""||Z==="false"||Z==="off"||Z==="0")return jH;if(Z==="true")return{kind:"all"};if(/^[1-9]\d*$/.test(Z))return{kind:"hops",hops:Number(Z)};throw Error(`GEMI_TRUST_PROXY must be "false", "true" or the number of proxies in front of the app (e.g. 1). Got ${JSON.stringify($)}.`)}function JS($,Z,J){if(J.kind==="all"){if(!$.get("x-forwarded-for")&&Z)$.set("x-forwarded-for",Z);return}$.delete("x-real-ip");let W=Z;if(J.kind==="hops"){let Y=($.get("x-forwarded-for")??"").split(",").map((X)=>X.trim()).filter(Boolean),j=Y.length-J.hops,z=j>=0?Y[j]:Y[0];W=(z===void 0?null:e1(z))??Z}if(W)$.set("x-forwarded-for",W);else $.delete("x-forwarded-for")}var yB=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,mB=16;function WS($){let Z=$.GEMI_CLIENT_IP_HEADER?.trim()??"",J=$.GEMI_PROXY_SECRET_HEADER?.trim()??"",W=$.GEMI_PROXY_SECRET??"";if(Z===""&&J===""&&W==="")return null;if(Z===""||J===""||W==="")throw Error("GEMI_CLIENT_IP_HEADER, GEMI_PROXY_SECRET_HEADER and GEMI_PROXY_SECRET go together: the client-IP header is only believed on a request that carries the proxy's secret. Set all three, or none.");if(!yB.test(Z))throw Error(`GEMI_CLIENT_IP_HEADER must be a single header name, e.g. "x-azure-clientip". Got ${JSON.stringify(Z)}.`);if(!yB.test(J))throw Error(`GEMI_PROXY_SECRET_HEADER must be a single header name, e.g. "x-azure-fdid". Got ${JSON.stringify(J)}.`);if(Z.toLowerCase()===J.toLowerCase())throw Error("GEMI_CLIENT_IP_HEADER and GEMI_PROXY_SECRET_HEADER name the same header.");if(W.length<mB)throw Error(`GEMI_PROXY_SECRET must be at least ${mB} characters. A guessable one lets any client name its own address.`);return{header:Z.toLowerCase(),secretHeader:J.toLowerCase(),secret:W}}function hB($,Z){if(!t3($.get(Z.secretHeader),Z.secret))return null;let J=$.get(Z.header)?.split(",")[0];return J===void 0?null:e1(J)}var zH="/__gemi__/domains/ask";class Q1{static token="router.domains";resolver;acceptsCustomDomains;clientIpTrust;groups=new Map;staticFilesVary=!1;constructor($,Z){this.groups.set(B8,$),this.clientIpTrust=Z.clientIpTrust??null;let{domains:J}=Z;if(this.acceptsCustomDomains=Boolean(J?.custom),!J){this.resolver=null;return}this.resolver=new $2(J);let W=(Y)=>({api:Y.api?new X8({...Z.api,...Y.api}):$.api,view:Y.view?new a3({...Z.view,...Y.view},Z.auth):$.view});for(let Y of J.groups??[])this.groups.set(Y.subdomain,W(Y));if(J.custom?.fallback)this.groups.set(e5,W(J.custom.fallback));this.staticFilesVary=this.viewDispatchers().some((Y)=>Y.publicFiles!==$.view.publicFiles||Y.assetRoutes!==$.view.assetRoutes||Y.assetCors!==$.view.assetCors)}async staticFiles($){let Z=(this.staticFilesVary?await this.route($):null)?.view??this.dispatchers(null).view;return{publicFiles:Z.publicFiles,assetRoutes:Z.assetRoutes,assetCors:Z.assetCors}}applyClientIp($){let Z=this.clientIpTrust;if(Z)Z2($,Z.secretHeader);let J=this.resolver?.trustedClientIp($)??(Z?hB($.headers,Z):null);if(!J)return;$.headers.set("x-forwarded-for",J),$.headers.delete("x-real-ip")}async route($){if(!this.resolver)return this.dispatchers(null);for(let J of this.resolver.proxySecretHeaders)Z2($,J);let Z=W8($)??await this.resolver.resolve($);if(!Z)return null;return $3($,Z),this.dispatchers(Z)}async ask($){if(!this.resolver?.askSecret||$.method!=="GET")return null;let Z=new URL($.url);if(Z.pathname!==zH)return null;if(!t3(Z.searchParams.get("secret"),this.resolver.askSecret))return null;let J=Z.searchParams.get("domain"),W=J?await this.resolver.allows(J,$):!1;return new Response(null,{status:W?200:404})}dispatchers($){return this.groups.get($?.group??B8)}viewDispatchers(){return Array.from(new Set(Array.from(this.groups.values(),($)=>$.view)))}viewGroups(){let $=new Set,Z=[];for(let[J,W]of this.groups){if($.has(W.view))continue;$.add(W.view),Z.push({group:J,view:W.view})}return Z}}function W3($){let Z=new Date($??0).getTime();return Number.isFinite(Z)?Z:0}var pB=600000;function cB($,Z){return[K6($,Z),K6($,Z-1)]}class E{static token="auth";config;provider;constructor($={},Z=new FJ){e9($.oauthProviders),this.config={...N$($Y($),$),emailCode:YJ($.emailCode),passwordLimits:WJ($.passwordLimits)},this.provider=Z}async oauthProvider($){return await NZ(this.config.oauthProviders,$)}async oauthProviderNames(){return await LY(this.config.oauthProviders)}get userProvider(){return this.provider}accessTokenCookieOptions($,Z){return{expires:Z,secure:this.publicOrigin($).startsWith("https://"),httpOnly:!0,domain:this.cookieDomain($)}}publicOrigin($){let Z=H().bound(Q1)?H(Q1).resolver:null;return Z?Z.publicOrigin($.rawRequest):new URL($.rawRequest.url).origin}cookieDomain($){let Z=this.config.cookieDomain;if(!Z)return;let J=Z==="root"?H(Q1).resolver?.root:_1(Z);if(!J)throw Error('`auth.cookieDomain` is "root", but `route.domains` is not configured.');let W=$.domain?.host??_1(new URL($.rawRequest.url).host);return W===J||W?.endsWith(`.${J}`)?J:void 0}async getSession($,Z){if(!$)return null;if(!o8($))return this.config.migrateLegacySession?this.convertLegacySession($,Z,this.config.migrateLegacySession):null;let J=await this.userProvider.findSession({token:$,userAgent:Z});if(!J?.user)return null;let W=Date.now(),Y=W3(J.expiresAt),j=W3(J.absoluteExpiresAt);if(Y<=W||j<=W)return await this.userProvider.deleteSession({token:$}),null;let X=await this.slideSession(J,W);return X.user.extension=await this.config.extendSession(X.user),X}async convertLegacySession($,Z,J){let W=P.getStore()?.req;if(!W)return null;let Y=Date.now(),j=Math.floor(Y/pB),z=null,X=await this.userProvider.findSession({token:$,userAgent:Z});if(X?.user){if(!await J(X,{token:$,req:W,userAgent:Z}))return null;let Q=K6($,j),F=X.user.id;if(await this.userProvider.withLegacySessionLock($,async()=>{if(!await this.userProvider.claimLegacySession({token:$}))return!1;return await this.userProvider.createSessionV2({token:Q,userId:F,userAgent:Z,...this.freshLifetime(Y)}),!0}))z=Q}if(!z){for(let Q of cB($,j))if((await this.userProvider.findSession({token:Q,userAgent:Z}))?.user){z=Q;break}}if(!z)return null;let G=await this.getSession(z,Z);if(G)W.ctx().setCookie("access_token",z,this.accessTokenCookieOptions(W,new Date(G.expiresAt)));return G}async revokeSession($,Z){if(!$)return await this.userProvider.deleteSession({token:$}),null;if(o8($)||!this.config.migrateLegacySession){let Y=await this.userProvider.findSession({token:$,userAgent:Z});return await this.userProvider.deleteSession({token:$}),Y}let J=Math.floor(Date.now()/pB),W=cB($,J);return this.userProvider.withLegacySessionLock($,async()=>{let Y=await this.userProvider.findSession({token:$,userAgent:Z});for(let j of W){if(Y?.user)break;Y=await this.userProvider.findSession({token:j,userAgent:Z})}await this.userProvider.deleteSession({token:$});for(let j of W)await this.userProvider.deleteSession({token:j});return Y})}requestCarryingCookie($){let Z=P.getStore()?.req;return Z?.cookies.get("access_token")===$?Z:null}async slideSession($,Z){let J=this.config.sessionExpiresInHours*3600000;if(new Date($.expiresAt).getTime()-Z>=J/2)return $;let W=new Date(Math.min(Z+J,new Date($.absoluteExpiresAt).getTime())),Y=await this.userProvider.updateSession({token:$.token,expiresAt:W}),j=this.requestCarryingCookie($.token);if(j)j.ctx().setCookie("access_token",$.token,this.accessTokenCookieOptions(j,W));if(!Y)return $;return{...$,expiresAt:Y.expiresAt??W}}freshLifetime($){return{expiresAt:new Date($+this.config.sessionExpiresInHours*3600000),absoluteExpiresAt:new Date($+this.config.sessionAbsoluteExpiresInHours*3600000)}}async generateMagicLink($){}async upsertSession($){await this.userProvider.findSession({token:"",userAgent:""})}async authenticate($){try{let Z=await this.userProvider.findUserByEmailAddress($,!1);if(!Z)throw Error(`User not found with email: ${$}`);let J=await this.createOrUpdateSession({email:$,id:Z.id}),W=new A;if(W.ctx().setCookie("access_token",J.token,this.accessTokenCookieOptions(W,J.expiresAt)),J?.user)J.user.extension=await this.config.extendSession(J.user);return J}catch(Z){console.log(Z)}}async createOrUpdateSessionV2($){let Z=await this.createOrUpdateSession($),J=null;if(Z?.user)J=await this.config.extendSession(Z.user),Z.user.extension=J;return Z}async createOrUpdateSession($){let Z=new A,J=$.id??(await this.userProvider.findUserByEmailAddress($.email,!1))?.id;if(!J)throw new q$;let W=Bun.env.NODE_ENV==="development"?"local":Z.headers.get("User-Agent"),Y=g9(J),j=await this.userProvider.createSessionV2({token:Y,userId:J,userAgent:W,...this.freshLifetime(Date.now())}),z=null;try{z=await this.userProvider.findSession({token:Y,userAgent:W??""})}catch(X){console.error("Reading the new session back failed:",X)}return z?.user?z:j}async createMagicLinkToken($){let Z=await this.userProvider.findUserByEmailAddress($,!1);if(Z){let{pin:J,token:W}=await this.issueOneTimeCode($,6);return{user:Z,email:$,pin:J,token:W}}return{}}async issueOneTimeCode($,Z){let{activeCodes:J,expiresInMinutes:W,linkExpiresInMinutes:Y}=this.config.emailCode,j=await this.config.generateMagicLinkToken($),z=await this.config.generateCode($),X=typeof z==="string"&&z!==""?z:d9(Z),G=_6("link",$,j),Q=_6("pin",$,X);if(J===1)await this.userProvider.deleteMagicLinkToken($);else{let F=Math.max(W,Y)*60000,B=(await this.userProvider.listMagicLinkTokensByEmail($,J-1)).filter((U)=>W3(U.createdAt)+F>Date.now()&&U.pin!==Q&&U.token!==G);await this.userProvider.deleteMagicLinkTokensExcept($,B.map((U)=>U.id))}return await this.userProvider.createMagicLinkToken({email:$,token:G,pin:Q}),{email:$,pin:X,token:j}}async oneTimeCodeRows($){let{activeCodes:Z}=this.config.emailCode;if(Z===1){let J=await this.userProvider.findMagicLinkTokenByEmail($);return J?[J]:[]}return await this.userProvider.listMagicLinkTokensByEmail($,Z)}async claimOneTimeCode($,Z){if(!await this.userProvider.claimMagicLinkToken(Z))return!1;if(this.config.emailCode.activeCodes>1)await this.userProvider.deleteMagicLinkToken($);return!0}async verifyOneTimeCode($,Z,J={}){let{expiresInMinutes:W,maxAttempts:Y}=this.config.emailCode,j=await this.oneTimeCodeRows($);if(j.length===0)return TZ("pin",$,null,Z),{status:"invalid"};let z=j.filter((Q)=>W3(Q.createdAt)+W*60000>Date.now());if(z.length===0)return TZ("pin",$,null,Z),{status:"expired"};let X=!0;for(let Q of z)if(!await i9(Q.id,W3(Q.createdAt),Y,W))X=!1;if(!X){if(this.config.emailCode.activeCodes===1)await this.userProvider.claimMagicLinkToken(z[0].id);else await this.userProvider.deleteMagicLinkToken($);return{status:"too_many_attempts"}}let G=null;for(let Q of z)if(TZ("pin",$,Q.pin,Z))G??=Q;if(!G)return{status:"invalid"};if(J.claim!==!1&&!await this.claimOneTimeCode($,G.id))return{status:"invalid"};return{status:"ok",row:G}}async verifyMagicLinkToken($,Z){let J=await this.oneTimeCodeRows($);if(J.length===0)return TZ("link",$,void 0,Z),!1;let W=null;for(let j of J)if(TZ("link",$,j.token,Z))W??=j;if(!W)return!1;if(W3(W.createdAt)+this.config.emailCode.linkExpiresInMinutes*60000<=Date.now())return!1;return await this.claimOneTimeCode($,W.id)}}class q0 extends h{static getFacadeAccessor(){return E}static async user(){let $=await q0.userOrNull();if($)return $;throw new q$({redirectTo:F6(P.getStore()?.req,this.getFacadeRoot().config.signInPath)})}static async userOrNull(){let $=P.getStore();if($?.user)return $.user;let Z=await j6(this.getFacadeRoot(),$?.req);if(Z)$?.setUser(Z);return Z}static intendedUrl($){let Z=P.getStore()?.req;return U1(Z?.search.get(l0),$??this.getFacadeRoot().config.redirectPath)}static async guard($){let Z=await q0.user();if(!await $(Z))throw new LZ}static async guardSafe($){let Z=await q0.user();try{return await $(Z)}catch(J){return!1}}static async authenticate($){return await this.getFacadeRoot().authenticate($)}static async oauthProviders(){return await this.getFacadeRoot().oauthProviderNames()}static async createMagicLink($){return await this.getFacadeRoot().createMagicLinkToken($)}}var J2="x-gemi-invalidate";function dB($){return encodeURIComponent(JSON.stringify([...new Set($)]))}function uB($){if(!$)return[];try{let Z=JSON.parse(decodeURIComponent($));return Array.isArray(Z)?Z.filter((J)=>typeof J==="string"):[]}catch{return[]}}class F8{static ensure($,Z={}){let J=P.getStore();if(J.req.kind==="api")throw Error("Query.prefetch() cannot be called from an API request");return J.serverQueries??=new zZ(Z3(J.req.rawRequest)),J.serverQueries.ensure($,Z,"prefetch")}static async instant($,...Z){let J=F8.ensure($,Z[0]);if(await J.promise,J.status==="rejected")throw J.error;return J.data}static prefetch($,...Z){F8.ensure($,Z[0])}static noPrefetch(){let $=P.getStore();if($.req.kind==="api")throw Error("Query.noPrefetch() cannot be called from an API request");$.serverQueries??=new zZ(Z3($.req.rawRequest)),$.serverQueries.muteDiscoveryHints()}static prefill($,Z,J){let W=P.getStore();if(W.req.kind==="api")throw Error("Query.prefill() cannot be called from an API request");W.serverQueries??=new zZ(Z3(W.req.rawRequest)),W.serverQueries.prefill($,Z,J)}static invalidate(...$){let Z=P.getStore(),J=uB(Z.headers.get(J2));Z.setHeaders(J2,dB([...J,...$]))}}function lB($,Z,J="/"){let W=new URL($.origin),Y=Z.host?Z.host:Z.subdomain?`${Z.subdomain}.${$.root}`:$.root,j=new URL(J.startsWith("/")?J:`/${J}`,W),z=XH(Y);if(!z)throw Error(`"${Y}" is not a hostname, so there is no URL for it. Give a bare host, optionally with a port \u2014 no scheme, path or credentials.`);if(j.hostname=z.hostname,z.port)j.port=z.port;return j.toString()}function XH($){try{let Z=new URL(`http://${$.trim()}`);return Z.host===$.trim().toLowerCase()&&Z.pathname==="/"?{hostname:Z.hostname,port:Z.port}:null}catch{return null}}class iB{static origin($){return W2($)}static absolute($,...Z){return`${WZ()}${D0(String($),Z[0]??{})}`}static relative($,...Z){return D0(String($),Z[0]??{})}static forDomain($,Z,...J){let W=H(Q1).resolver;if(!W)throw Error("`Url.forDomain` needs `route.domains` to be configured.");let Y=P.getStore()?.req?.rawRequest,j=Y?W.publicOrigin(Y):WZ();if(!j)throw Error("`Url.forDomain` outside a request needs `HOST_NAME` (or `APP_URL`) for the protocol.");return lB({root:W.root,origin:j},$,D0(String(Z),J[0]??{}))}static api($,...Z){return n5(String($),Z[0]??{})}static apiAbsolute($,...Z){return`${W2()}${n5(String($),Z[0]??{})}`}static matchApi($,Z){return EB(String($),Z)}}class sB{name="Meta";static description($){P.getStore().metadata.description($)}static title($){P.getStore().metadata.title($)}static openGraph($){P.getStore().metadata.openGraph($)}static htmlAttributes($){P.getStore().metadata.htmlAttributes($)}static canonical($){P.getStore().metadata.canonical($)}static alternates($){P.getStore().metadata.alternates($)}static tags($){P.getStore().metadata.tags($)}static robots($){P.getStore().metadata.robots($)}static translate($=!0){P.getStore().metadata.translate($)}static fonts($){P.getStore().metadata.fonts($)}}var GH={set($,Z,J){P.getStore().setCookie($,Z,J)},setIfAbsent($,Z,J){if(P.getStore().req.cookies.has($))return!1;return P.getStore().setCookie($,Z,J),!0},delete($,Z){P.getStore().deleteCookie($,Z)}};class d1 extends h{static getFacadeAccessor(){return QZ}static get client(){return this.getFacadeRoot().client}static get($){return d1.client.get($)}static set($,Z){return d1.client.set($,Z)}static del(...$){return d1.client.del(...$)}static exists($){return d1.client.exists($)}static incr($){return d1.client.incr($)}static expire($,Z){return d1.client.expire($,Z)}static ttl($){return d1.client.ttl($)}}function $b($){return $}function nB(){return{store:"memory",ttl:null}}class Y2{entries=new Map;maxEntries;now;constructor($={}){let Z=$.maxEntries??1e4;if(!Number.isInteger(Z)||Z<1)throw TypeError(`MemoryCacheStore maxEntries is a whole number of 1 or more; got ${Z}.`);this.maxEntries=Z,this.now=$.now??Date.now}get size(){return this.entries.size}async get($){let Z=this.live($);if(!Z)return null;return this.entries.delete($),this.entries.set($,Z),Z.value}async set($,Z,J){this.entries.delete($),this.entries.set($,{value:Z,expiresAt:J===null?null:this.now()+J});while(this.entries.size>this.maxEntries)this.entries.delete(this.entries.keys().next().value)}async delete($){let Z=this.live($)!==void 0;return this.entries.delete($),Z}async flush(){this.entries.clear()}live($){let Z=this.entries.get($);if(!Z)return;if(Z.expiresAt!==null&&Z.expiresAt<=this.now()){this.entries.delete($);return}return Z}}var QH="500";class j2{prefix;injectedClient;constructor($={}){this.injectedClient=$.client,this.prefix=$.prefix??"gemi:cache:"}async get($){let Z=await this.client.send("GET",[this.prefix+$]);return Z===null||Z===void 0?null:String(Z)}async set($,Z,J){let W=[this.prefix+$,Z];if(J!==null)W.push("PX",String(Math.max(1,Math.round(J))));await this.client.send("SET",W)}async delete($){return Number(await this.client.send("DEL",[this.prefix+$]))>0}async flush(){if(this.prefix==="")throw Error("RedisCacheStore refuses to flush with an empty prefix: that would delete every key in the database.");let $=this.client,Z=`${BH(this.prefix)}*`,J="0";do{let W=await $.send("SCAN",[J,"MATCH",Z,"COUNT",QH]),[Y,j]=Array.isArray(W)?W:["0",[]];if(J=String(Y),Array.isArray(j)&&j.length>0)await $.send("UNLINK",j.map(String))}while(J!=="0")}get client(){if(this.injectedClient)return this.injectedClient;let $=H(),Z=$.bound(QZ)?$.make(QZ).client:void 0;if(!Z)throw Error("RedisCacheStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisCacheStore({ client }).");return Z}}function BH($){return $.replace(/[*?[\]\\^-]/g,(Z)=>`\\${Z}`)}var FH="k:",oB="tag:",VH="t:";class z2{async get($){let Z=await this.manager.read(await this.storeKey($));return Z.found?Z.value:void 0}async has($){return(await this.manager.read(await this.storeKey($))).found}async set($,Z,J){await this.manager.write(await this.storeKey($),Z,J)}async delete($){return this.manager.store.delete(await this.storeKey($))}async pull($){let Z=await this.storeKey($),J=await this.manager.read(Z);if(!J.found)return;return await this.manager.store.delete(Z),J.value}async remember($,Z,J){let[W,Y]=typeof Z==="function"?[void 0,Z]:[Z,J];if(typeof Y!=="function")throw TypeError("Cache.remember needs a function that computes the value.");return this.manager.rememberAt(await this.storeKey($),W,Y)}}class X2 extends z2{options;static token="cache";config;builtStore;inflight=new Map;constructor($={},Z={}){super();this.options=Z;if(this.config=N$(nB(),$),this.config.ttl!==null&&this.config.ttl!==void 0)BZ(this.config.ttl)}get manager(){return this}get store(){return this.builtStore??=this.buildStore()}tags(...$){let Z=[...new Set($.flat())].sort();if(Z.length===0)throw TypeError("Cache.tags needs at least one tag.");for(let J of Z)if(typeof J!=="string"||J==="")throw TypeError(`A cache tag is a non-empty string; got ${JSON.stringify(J)}.`);return new tB(this,Z)}async flush(){await this.store.flush()}async storeKey($){return FH+rB($)}async read($){let Z=await this.store.get($);if(Z===null)return{found:!1};try{return{found:!0,value:JSON.parse(Z)}}catch{return{found:!1}}}async write($,Z,J){if(Z===void 0)throw TypeError("Cache.set cannot store undefined: get() returns undefined for a miss. Store null instead.");let W=this.ttlMs(J);if(W===0){await this.store.delete($);return}let Y=JSON.stringify(Z);if(Y===void 0)throw TypeError(`Cache.set cannot store a ${typeof Z}: it has no JSON form.`);await this.store.set($,Y,W)}async rememberAt($,Z,J){let W=await this.read($);if(W.found)return W.value;let Y=this.inflight.get($);if(Y)return Y;let j=(async()=>{try{let z=await J();if(z!==void 0)await this.write($,z,Z);return z}finally{this.inflight.delete($)}})();return this.inflight.set($,j),j}async tagVersions($){return Promise.all($.map(async(Z)=>{let J=oB+Z,W=await this.store.get(J);if(W!==null)return W;let Y=aB();return await this.store.set(J,Y,null),Y}))}async flushTags($){await Promise.all($.map((Z)=>this.store.set(oB+Z,aB(),null)))}ttlMs($){let Z=$===void 0?this.config.ttl:$;return Z===null||Z===void 0?null:BZ(Z)}buildStore(){let{store:$}=this.config;if($===void 0||$==="memory")return new Y2(this.config.memory);if($==="redis"){let Z=this.options.application;return new j2({...this.config.redis,client:Z?{send:(J,W)=>Z.make(QZ).client.send(J,W)}:void 0})}if(typeof $==="function"){let Z=this.options.application;if(!Z)throw Error("A cache store factory needs the application: build CacheManager with { application }.");return $(Z)}if($&&typeof $==="object")return $;throw Error(`Unknown cache store ${JSON.stringify($)} in app/config/cache.ts: use "memory", "redis", a CacheStore, or a function returning one.`)}}class tB extends z2{manager;tagNames;constructor($,Z){super();this.manager=$;this.tagNames=Z}async flush(){await this.manager.flushTags([...this.tagNames])}async storeKey($){rB($);let Z=await this.manager.tagVersions([...this.tagNames]);return`${VH}${Z.join(",")}:${$}`}}function rB($){if(typeof $!=="string"||$==="")throw TypeError(`A cache key is a non-empty string; got ${JSON.stringify($)}.`);return $}function aB(){let $=new Uint8Array(9);return crypto.getRandomValues($),Array.from($,(Z)=>Z.toString(16).padStart(2,"0")).join("")}class eB extends h{static getFacadeAccessor(){return X2}static get($){return this.getFacadeRoot().get($)}static has($){return this.getFacadeRoot().has($)}static set($,Z,J){return this.getFacadeRoot().set($,Z,J)}static delete($){return this.getFacadeRoot().delete($)}static pull($){return this.getFacadeRoot().pull($)}static remember($,Z,J){let W=this.getFacadeRoot();return typeof Z==="function"?W.remember($,Z):W.remember($,Z,J)}static tags(...$){return this.getFacadeRoot().tags(...$)}static flush(){return this.getFacadeRoot().flush()}}class $F extends h{static getFacadeAccessor(){return D1}static consume($,Z={}){return this.getFacadeRoot().consume($,Z)}static enforce($,Z={},J){return this.getFacadeRoot().enforce($,Z,J)}}class JF extends h{static getFacadeAccessor(){return ZF}static run($,Z,J){return this.getFacadeRoot().run($,Z,J)}static acquire($,Z={}){return this.getFacadeRoot().acquire($,Z)}}class YF extends h{static getFacadeAccessor(){return WF}static encrypt($){return this.getFacadeRoot().encrypt($)}static decrypt($){return this.getFacadeRoot().decrypt($)}static needsReencryption($){return this.getFacadeRoot().needsReencryption($)}}class jF extends h{static getFacadeAccessor(){return i3}static for($,Z,J){return this.getFacadeRoot().for($,Z,J)}static list($,Z){return this.getFacadeRoot().list($,Z)}static save($,Z,J){return this.getFacadeRoot().save($,Z,J)}static fake($={}){return this.getFacadeRoot().fake($)}static restore(){this.getFacadeRoot().restore()}}class zF extends h{static getFacadeAccessor(){return r3}static publish($,Z){return this.getFacadeRoot().publish($,Z)}static head($){return this.getFacadeRoot().head($)}static cursor($){return this.getFacadeRoot().cursor($)}static subscribe($,Z){return this.getFacadeRoot().subscribe($,Z)}static stream($,Z,J){return this.getFacadeRoot().stream($,Z,J)}}class e3 extends c0{application;previous;sent=[];revoked=[];static install($){let Z=$.bound(c0)?$.make(c0):void 0;if(Z instanceof e3)return Z;let J=new e3($,Z);return $.instance(c0,J),J}constructor($,Z){super({driver:"memory",maxEventBytes:Z?.config.maxEventBytes,warnEventBytes:Z?.config.warnEventBytes},{application:$});this.application=$;this.previous=Z;this.channelsFrom=Z}channelsFrom;get channels(){return this.channelsFrom?.channels??null}publish($){this.sent.push($)}sendRevocation($){this.revoked.push($)}restore(){if(this.previous){this.application.instance(c0,this.previous);return}this.application.forget(c0)}assertSent($,Z,J){if(this.matching($,Z,J).length>0)return;throw Error(`Expected ${G2($,Z,J)} to have been broadcast. ${this.summary()}`)}assertNotSent($,Z,J){let W=this.matching($,Z,J);if(W.length===0)return;throw Error(`Expected ${G2($,Z,J)} not to have been broadcast, but it was broadcast ${Q2(W.length)}: ${B2(W)}.`)}assertSentTimes($,Z,J,W){let Y=this.matching($,J,W);if(Y.length===Z)return;throw Error(`Expected ${G2($,J,W)} to have been broadcast ${Q2(Z)}, but it was broadcast ${Q2(Y.length)}. `+this.summary())}assertNothingSent(){if(this.sent.length===0)return;throw Error(`Expected nothing to have been broadcast, but ${this.sent.length} ${this.sent.length===1?"emit was":"emits were"}: ${B2(this.sent)}.`)}matching($,Z,J){return UZ($),this.sent.filter((W)=>(W.pattern===$||u2($,W.topic))&&(Z===void 0||W.event===Z)&&(J===void 0||J(W.data,W)))}summary(){if(this.sent.length===0)return"Nothing was broadcast.";return`Broadcast: ${B2(this.sent)}.`}}function G2($,Z,J){return`${Z?`"${Z}" on `:"an event on "}"${$}"`+(J?" matching the predicate":"")}function Q2($){return`${$} ${$===1?"time":"times"}`}function B2($){return $.map((Z)=>`${Z.topic} ${Z.event}(${UH(Z.data)})`).join(", ")}function UH($){if($===void 0)return"";try{return JSON.stringify($)??String($)}catch{return String($)}}class XF extends h{static getFacadeAccessor(){return c0}static to($,...Z){return this.getFacadeRoot().to($,...Z)}static toUser($){return this.getFacadeRoot().toUser($)}static toOthers($){return this.getFacadeRoot().toOthers($)}static revoke($){this.getFacadeRoot().revoke($)}static fake(){return e3.install(H())}}function mb($){return $}function GF(){return{store:"memory",sweepLimit:500}}var F2=["completed","failed","cancelled","timed_out"],I1=["pending","running"];function x1($){return F2.includes($)}class V2{runs=new Map;clock=0;get size(){return this.runs.size}async create($){if(this.runs.has($.id))throw Error(`A run with the id ${$.id} already exists.`);let Z=this.tick(),J={id:$.id,kind:$.kind,subject:$.subject,owner:$.owner,status:$.status,meta:structuredClone($.meta??null),progress:null,result:null,error:null,version:1,createdAt:Z,startedAt:$.status==="running"?Z:null,updatedAt:Z,finishedAt:null,deadlineAt:$.deadlineMs===null?null:Z+$.deadlineMs};return this.runs.set(J.id,J),structuredClone(J)}async get($){let Z=this.runs.get($);return Z?structuredClone(Z):null}async list($){let Z=[];for(let J of this.runs.values()){if($.kind!==void 0&&J.kind!==$.kind)continue;if($.subject!==void 0&&J.subject!==$.subject)continue;if($.owner!==void 0&&J.owner!==$.owner)continue;if($.statuses&&!$.statuses.includes(J.status))continue;Z.push(J)}return Z.reverse().sort((J,W)=>W.createdAt-J.createdAt),Z.slice(0,U2($.limit)).map((J)=>structuredClone(J))}async transition($,Z,J){let W=this.runs.get($);if(!W||!Z.includes(W.status))return null;let Y=structuredClone(J),j=this.tick();if(Y.status!==void 0){if(W.startedAt===null&&Y.status!=="pending")W.startedAt=j;if(x1(Y.status))W.finishedAt=j;W.status=Y.status}if("progress"in Y)W.progress=Y.progress??null;if("result"in Y)W.result=Y.result??null;if("error"in Y)W.error=Y.error??null;return W.version+=1,W.updatedAt=j,structuredClone(W)}async overdue($,Z){let J=[];for(let W of this.runs.values())if(I1.includes(W.status)&&W.deadlineAt!==null&&W.deadlineAt<=$)J.push(W);return J.sort((W,Y)=>W.deadlineAt-Y.deadlineAt),J.slice(0,Math.max(0,Z)).map((W)=>structuredClone(W))}async now(){return this.tick()}async prune($){let Z=this.tick()-$,J=0;for(let[W,Y]of this.runs)if(Y.finishedAt!==null&&Y.finishedAt<=Z)this.runs.delete(W),J++;return J}tick(){return this.clock=Math.max(this.clock,Date.now()),this.clock}}function U2($){if($===void 0)return 50;return Math.max(0,Math.floor($))}class L2{table;sql;dialect;connection;constructor($,Z={}){let J=Z.table??"gemi_runs";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(J))throw Error(`The runs table name "${J}" is not a plain identifier. Use letters, digits and underscores.`);this.table=J,this.sql=$.sql,this.dialect=$.dialect,this.connection=$.name}async createTable(){for(let $ of DH(this.dialect,this.table))await this.sql.unsafe($)}async create($){let Z=this.q(),J=this.clock(Z),W=$.deadlineMs===null?Z`NULL`:Z`${J} + ${this.ms(Z,$.deadlineMs)}`,Y=$.status==="running"?J:Z`NULL`;await Z`
|
|
24
24
|
INSERT INTO ${this.name(Z)}
|
|
25
25
|
(id, kind, subject, owner, status, meta, version,
|
|
26
26
|
created_at, started_at, updated_at, deadline_at)
|
|
@@ -83,6 +83,6 @@ ${W}`)}let J=(await Z.outputs[0].text()).trim();if(/<\/script|<!--/i.test(J))thr
|
|
|
83
83
|
"updated_at" BIGINT NOT NULL,
|
|
84
84
|
"finished_at" BIGINT,
|
|
85
85
|
"deadline_at" BIGINT${W}
|
|
86
|
-
)`,`CREATE INDEX IF NOT EXISTS "${Z}_subject_created_at_idx" ON "${Z}"("subject", "created_at")`,`CREATE INDEX IF NOT EXISTS "${Z}_status_deadline_at_idx" ON "${Z}"("status", "deadline_at")`]}var FF=191,VF=30000;class O8 extends Error{id;constructor($){super(`No run has the id ${$}.`);this.id=$;this.name="RunNotFoundError"}}class L8 extends Error{code;data;constructor($,Z={}){super($,Z.cause===void 0?void 0:{cause:Z.cause});this.name="RunFailure",this.code=Z.code,this.data=Z.data}}class M2{options;static token="runs";store;config;ownFeed=null;constructor($={},Z={}){this.options=Z;this.config=N$(GF(),$),this.store=MH(this.config.store,Z.application)}get feed(){if(this.options.feed)return this.options.feed;if(this.options.application)return this.options.application.make(r3);return this.ownFeed??=new r3,this.ownFeed}channel($){return`gemi:run:${$}`}async create($){OF("kind",$.kind);let Z=$.id??`run_${crypto.randomUUID().replaceAll("-","")}`;OF("id",Z);let J=await this.store.create({id:Z,kind:$.kind,subject:$.subject??null,owner:$.owner??null,meta:$.meta??null,status:$.start?"running":"pending",deadlineMs:$.deadline===void 0||$.deadline===null?null:BZ($.deadline)});return await this.publish(J),J}async get($){return await this.store.get($)}list($={}){return this.store.list($)}start($){return this.change($,["pending"],{status:"running"})}async progress($,Z){return LH(Z),this.change($,I1,{status:"running",progress:Z})}complete($,Z){return this.change($,I1,{status:"completed",result:Z===void 0?null:Z})}fail($,Z){return this.change($,I1,{status:"failed",error:DF(Z)})}cancel($,Z){return this.change($,I1,{status:"cancelled",error:{message:Z??"The run was cancelled.",code:"cancelled"}})}async execute($,Z){let J=this.feed.subscribe(this.channel($));try{await J.ready();let W=await this.start($)??await this.store.get($);if(!W)throw new O8($);if(x1(W.status))return W;let Y=new AbortController,j=this.watch($,W,J,Y),z={id:$,record:W,signal:Y.signal,progress:async(G)=>{if(Y.signal.aborted)return;await this.progress($,G)}},X;try{let G=await Z(z);X=await this.complete($,G)}catch(G){if(!(G instanceof L8)&&!Y.signal.aborted)console.error(`[gemi] Run ${$} failed.`,G);X=await this.change($,I1,{status:"failed",error:G instanceof L8?DF(G):{message:"The run failed.",code:"error"}})}finally{Y.abort(),J.close(),await j}return X??await this.store.get($)??W}finally{J.close()}}async wait($,Z={}){let{signal:J}=Z;J?.throwIfAborted();let W=Z.timeout===void 0?1/0:Date.now()+BZ(Z.timeout),Y=this.feed.subscribe(this.channel($),{signal:J});try{await Y.ready();let j=await this.store.get($);if(!j)throw new O8($);let z=null;for(;;){if(x1(j.status))return j;J?.throwIfAborted();let X=await this.untilDeadline(j);if(X!==null&&X<=0){j=await this.expire($)??await this.store.get($)??j;continue}let G=W-Date.now();if(G<=0)return j;if(z??=Y.isClosed?new Promise(()=>{}):Y.next(),await UF(z,Math.min(G,X??1/0,VF),J))z=null;j=await this.store.get($)??j}}finally{Y.close()}}async*subscribe($,Z={}){let J=this.feed.subscribe(this.channel($),{signal:Z.signal});try{await J.ready();let W=await this.store.get($);if(!W)throw new O8($);if(yield W,x1(W.status))return;for await(let Y of J){let j=OH(Y,$)??await this.store.get($);if(!j||j.version<=W.version)continue;if(W=j,yield W,x1(W.status))return}}finally{J.close()}}stream($,Z,J={}){return this.feed.stream($,this.channel(Z),J)}cursor($){return this.feed.cursor(this.channel($))}async sweep(){let $=await this.now(),Z=0;for(let J of await this.store.overdue($,this.config.sweepLimit))if(await this.expire(J.id))Z++;return Z}async prune($){let Z=BZ($);return await this.store.prune?.(Z)??0}async close(){await this.ownFeed?.close(),this.ownFeed=null}now(){return this.store.now?this.store.now():Promise.resolve(Date.now())}async untilDeadline($){if($.deadlineAt===null)return null;return $.deadlineAt-await this.now()}async expire($){let Z=await this.store.get($);if(!Z||x1(Z.status))return null;let J=await this.untilDeadline(Z);if(J===null||J>0)return null;return this.change($,I1,{status:"timed_out",error:{message:"The run passed its deadline.",code:"deadline"}})}async watch($,Z,J,W){let Y=new Promise((z)=>{if(W.signal.aborted)z("ended");W.signal.addEventListener("abort",()=>z("ended"),{once:!0})}),j=null;try{for(;;){if(W.signal.aborted)return;if(x1(Z.status)){W.abort();return}let z=await this.untilDeadline(Z);if(z!==null&&z<=0){Z=await this.expire($)??await this.store.get($)??Z;continue}j??=J.next();let X=await Promise.race([Y,UF(j,Math.min(z??1/0,VF))]);if(X==="ended")return;if(X)j=null;Z=await this.store.get($)??Z}}catch(z){console.error(`[gemi] Run ${$}: could not follow the run for a cancel.`,z)}}async change($,Z,J){let W=await this.store.transition($,Z,J);if(W)await this.publish(W);return W}async publish($){try{await this.feed.publish(this.channel($.id),$)}catch(Z){console.error(`[gemi] Run ${$.id}: could not publish its change.`,Z)}}}function UF($,Z,J){return new Promise((W,Y)=>{let j=Number.isFinite(Z)?setTimeout(()=>G(!1),Math.max(0,Z)):null,z=()=>{X(),Y(J.reason)},X=()=>{if(j)clearTimeout(j);J?.removeEventListener("abort",z)},G=(Q)=>{X(),W(Q)};J?.addEventListener("abort",z,{once:!0}),$.then(()=>G(!0),()=>G(!0))})}function OH($,Z){if($.type!=="change")return null;let J=$.data;if(!J||typeof J!=="object"||J.id!==Z||typeof J.version!=="number")return null;return J}function DF($){if(typeof $==="string")return{message:$};if($ instanceof L8)return{message:$.message,...$.code!==void 0?{code:$.code}:{},...$.data!==void 0?{data:$.data}:{}};if($ instanceof Error)return{message:$.message};return $}function OF($,Z){if(typeof Z!=="string"||Z===""||Z.length>FF)throw TypeError(`A run's ${$} is a string of 1 to ${FF} characters; got ${JSON.stringify(Z)}.`)}function LH($){let{fraction:Z}=$;if(Z!==void 0&&!(Number.isFinite(Z)&&Z>=0&&Z<=1))throw RangeError(`A run's progress fraction is between 0 and 1; got ${Z}.`)}function MH($,Z){if($==="memory")return new V2;if($==="database"||typeof $==="function"){if(!Z&&($==="database"||$.length>0))throw Error("The runs store needs the application it belongs to, and this RunManager was built without one. Pass { application }.");if($==="database"){let J=Z.make(W$).connection();return new L2(J)}return $(Z)}if(typeof $==="string")throw Error(`Unknown runs store "${$}". The runs slice's store is "memory", "database", a RunStore, or a function returning one.`);return $}class LF extends h{static getFacadeAccessor(){return M2}static create($){return this.getFacadeRoot().create($)}static get($){return this.getFacadeRoot().get($)}static list($){return this.getFacadeRoot().list($)}static start($){return this.getFacadeRoot().start($)}static progress($,Z){return this.getFacadeRoot().progress($,Z)}static complete($,Z){return this.getFacadeRoot().complete($,Z)}static fail($,Z){return this.getFacadeRoot().fail($,Z)}static cancel($,Z){return this.getFacadeRoot().cancel($,Z)}static execute($,Z){return this.getFacadeRoot().execute($,Z)}static wait($,Z){return this.getFacadeRoot().wait($,Z)}static subscribe($,Z){return this.getFacadeRoot().subscribe($,Z)}static stream($,Z,J){return this.getFacadeRoot().stream($,Z,J)}static cursor($){return this.getFacadeRoot().cursor($)}static channel($){return this.getFacadeRoot().channel($)}static sweep(){return this.getFacadeRoot().sweep()}static prune($){return this.getFacadeRoot().prune($)}}class MF extends h{static getFacadeAccessor(){return $$}static enabled($){return this.getFacadeRoot().enabled($)}static all(){return this.getFacadeRoot().forClient()}static explain($){return this.getFacadeRoot().explain($)}static for($){return this.getFacadeRoot().for($)}static list(){return this.getFacadeRoot().list()}static set($,Z,J){return this.getFacadeRoot().set($,Z,J)}static refresh(){return this.getFacadeRoot().refresh()}static invalidate(){return this.getFacadeRoot().invalidate()}}class H2{value;constructor($){this.value=$}}var HH=/^[A-Za-z_][A-Za-z0-9_$]*$/;function TH($){let Z=["SET TRANSACTION READ ONLY"],J=[["statementTimeoutMs","statement_timeout"],["lockTimeoutMs","lock_timeout"],["idleInTransactionTimeoutMs","idle_in_transaction_session_timeout"]];for(let[W,Y]of J){let j=$[W];if(j===void 0)continue;if(typeof j!=="number"||!Number.isInteger(j)||j<=0)throw TypeError(`DB.readOnly: ${W} must be a positive whole number of milliseconds, got ${String(j)}.`);Z.push(`SET LOCAL ${Y} = ${j}`)}if($.role!==void 0){if(typeof $.role!=="string"||!HH.test($.role))throw TypeError(`DB.readOnly: the role "${String($.role)}" is not a plain identifier. Use letters, digits, _ and $.`);Z.push(`SET LOCAL ROLE "${$.role}"`)}return Z}class T8{bound;constructor($){this.bound=$}get name(){return this.bound??J$()}get sql(){return this.connection().sql}get dialect(){return this.connection().dialect}async query($){return await this.run($,"query")}async execute($){let Z=await this.run($,"execute");return Number(Z?.count??0)}async transaction($){let Z=this.name,J=this.connection(Z);return H8(J.sql,(W)=>M8(Z,()=>$(W)),{slowTransactionThreshold:J.config.slowTransactionThreshold,connection:Z})}async readOnly($,Z){let J=typeof $==="function"?{}:$,W=typeof $==="function"?$:Z;if(typeof W!=="function")throw TypeError("DB.readOnly needs a callback: readOnly(options, async (tx) => ...).");let Y=TH(J??{}),j=this.name,z=this.connection(j);if(z.dialect!=="postgres")throw Error(`DB.readOnly is supported on Postgres only, and the "${j}" connection is ${z.dialect}.`);if(Z$()!==void 0)throw Error("DB.readOnly cannot run inside a transaction: SET TRANSACTION READ ONLY has to be the first statement of its own transaction. Call it outside the transaction.");try{await H8(z.sql,async(X)=>{for(let Q of Y)await X.unsafe(Q);await PF();let G=await M8(j,()=>W(X));throw new H2(G)},{slowTransactionThreshold:z.config.slowTransactionThreshold,connection:j,deferSettings:!0})}catch(X){if(X instanceof H2)return X.value;throw X}throw Error("DB.readOnly: the transaction committed, which it never should.")}async schema(){let $=this.connection(),{introspect:Z}=await import("./chunk-3v8b2kdr.js");return Z(this.handle()??$.sql,$.dialect)}async withSettings($,Z){let J=this.connection();if(J.dialect!=="postgres")throw Error(`DB.withSettings is supported on Postgres only, and the "${J.name}" connection is ${J.dialect}.`);return KF($,Z)}run($,Z){let J=this.connection(),{text:W,values:Y}=IF($,_F(J.dialect),Z),j=this.handle();if(j===void 0&&NF()){let z=this.name;return H8(J.sql,(X)=>M8(z,()=>X.unsafe(W,Y)),{slowTransactionThreshold:J.config.slowTransactionThreshold,connection:z})}if(j===void 0)return J.sql.unsafe(W,Y);return j.unsafe(W,Y).catch((z)=>{throw TF(j),z})}handle(){let $=Z$();if($===void 0)return;return J$()===this.name?$:void 0}connection($=this.name){return HF($),H(W$).connection($)}}var x$=new T8;class xF extends h{static getFacadeAccessor(){return W$}static connection($){return new T8($)}static get sql(){return x$.sql}static get dialect(){return x$.dialect}static query($){return x$.query($)}static execute($){return x$.execute($)}static transaction($){return x$.transaction($)}static withSettings($,Z){return x$.withSettings($,Z)}static readOnly($,Z){return x$.readOnly($,Z)}static schema(){return x$.schema()}static close(){return this.getFacadeRoot().close()}}export{V1 as Ve,kF as We,r0 as Xe,z3 as Ye,x8 as Ze,x0 as _e,j6 as $e,n8 as af,o8 as bf,g9 as cf,r1 as df,D1 as ef,e1 as ff,F9 as gf,Z0 as hf,O9 as if,D6 as jf,O6 as kf,y9 as lf,m9 as mf,t8 as nf,r8 as of,_6 as pf,TZ as qf,a9 as rf,rV as sf,t9 as tf,eV as uf,dP as vf,$Y as wf,GY as xf,zJ as yf,QY as zf,BY as Af,XU as Bf,FY as Cf,XJ as Df,BU as Ef,FU as Ff,GJ as Gf,VY as Hf,UY as If,$$ as Jf,DY as Kf,OU as Lf,FJ as Mf,v8 as Nf,V6 as Of,S1 as Pf,w8 as Qf,b1 as Rf,I$ as Sf,F8 as Tf,iB as Uf,sB as Vf,GH as Wf,d1 as Xf,$b as Yf,nB as Zf,Y2 as _f,j2 as $f,X2 as ag,tB as bg,eB as cg,$F as dg,JF as eg,YF as fg,jF as gg,zF as hg,i as ig,G3 as jg,h4 as kg,SK as lg,bK as mg,EK as ng,qK as og,PG as pg,g7 as qg,IG as rg,mK as sg,AG as tg,c0 as ug,c3 as vg,SG as wg,XF as xg,mb as yg,F2 as zg,I1 as Ag,x1 as Bg,V2 as Cg,L2 as Dg,DH as Eg,O8 as Fg,L8 as Gg,M2 as Hg,LF as Ig,MF as Jg,T8 as Kg,xF as Lg,h7 as Mg,VL as Ng,n7 as Og,o7 as Pg,r_ as Qg,tG as Rg,ZQ as Sg,X6 as Tg,n1 as Ug,UI as Vg,WQ as Wg,YQ as Xg,kQ as Yg,H5 as Zg,rZ as _g,T5 as $g,VC as ah,NC as bh,PC as ch,kM as dh,y5 as eh,fM as fh,i5 as gh,hM as hh,p5 as ih,dM as jh,a3 as kh,a5 as lh,RB as mh,j8 as nh,X8 as oh,ZS as ph,JS as qh,WS as rh,Q1 as sh,E as th,q0 as uh,G6 as vh,a2 as wh,sF as xh,s2 as yh,r2 as zh,E8 as Ah,B6 as Bh,R8 as Ch,e2 as Dh,$V as Eh,ZV as Fh,j9 as Gh,X9 as Hh,Q9 as Ih,M9 as Jh,H9 as Kh,T9 as Lh,m8 as Mh,QV as Nh,j0 as Oh,E9 as Ph,MZ as Qh,f9 as Rh};
|
|
86
|
+
)`,`CREATE INDEX IF NOT EXISTS "${Z}_subject_created_at_idx" ON "${Z}"("subject", "created_at")`,`CREATE INDEX IF NOT EXISTS "${Z}_status_deadline_at_idx" ON "${Z}"("status", "deadline_at")`]}var FF=191,VF=30000;class O8 extends Error{id;constructor($){super(`No run has the id ${$}.`);this.id=$;this.name="RunNotFoundError"}}class L8 extends Error{code;data;constructor($,Z={}){super($,Z.cause===void 0?void 0:{cause:Z.cause});this.name="RunFailure",this.code=Z.code,this.data=Z.data}}class M2{options;static token="runs";store;config;ownFeed=null;constructor($={},Z={}){this.options=Z;this.config=N$(GF(),$),this.store=MH(this.config.store,Z.application)}get feed(){if(this.options.feed)return this.options.feed;if(this.options.application)return this.options.application.make(r3);return this.ownFeed??=new r3,this.ownFeed}channel($){return`gemi:run:${$}`}async create($){OF("kind",$.kind);let Z=$.id??`run_${crypto.randomUUID().replaceAll("-","")}`;OF("id",Z);let J=await this.store.create({id:Z,kind:$.kind,subject:$.subject??null,owner:$.owner??null,meta:$.meta??null,status:$.start?"running":"pending",deadlineMs:$.deadline===void 0||$.deadline===null?null:BZ($.deadline)});return await this.publish(J),J}async get($){return await this.store.get($)}list($={}){return this.store.list($)}start($){return this.change($,["pending"],{status:"running"})}async progress($,Z){return LH(Z),this.change($,I1,{status:"running",progress:Z})}complete($,Z){return this.change($,I1,{status:"completed",result:Z===void 0?null:Z})}fail($,Z){return this.change($,I1,{status:"failed",error:DF(Z)})}cancel($,Z){return this.change($,I1,{status:"cancelled",error:{message:Z??"The run was cancelled.",code:"cancelled"}})}async execute($,Z){let J=this.feed.subscribe(this.channel($));try{await J.ready();let W=await this.start($)??await this.store.get($);if(!W)throw new O8($);if(x1(W.status))return W;let Y=new AbortController,j=this.watch($,W,J,Y),z={id:$,record:W,signal:Y.signal,progress:async(G)=>{if(Y.signal.aborted)return;await this.progress($,G)}},X;try{let G=await Z(z);X=await this.complete($,G)}catch(G){if(!(G instanceof L8)&&!Y.signal.aborted)console.error(`[gemi] Run ${$} failed.`,G);X=await this.change($,I1,{status:"failed",error:G instanceof L8?DF(G):{message:"The run failed.",code:"error"}})}finally{Y.abort(),J.close(),await j}return X??await this.store.get($)??W}finally{J.close()}}async wait($,Z={}){let{signal:J}=Z;J?.throwIfAborted();let W=Z.timeout===void 0?1/0:Date.now()+BZ(Z.timeout),Y=this.feed.subscribe(this.channel($),{signal:J});try{await Y.ready();let j=await this.store.get($);if(!j)throw new O8($);let z=null;for(;;){if(x1(j.status))return j;J?.throwIfAborted();let X=await this.untilDeadline(j);if(X!==null&&X<=0){j=await this.expire($)??await this.store.get($)??j;continue}let G=W-Date.now();if(G<=0)return j;if(z??=Y.isClosed?new Promise(()=>{}):Y.next(),await UF(z,Math.min(G,X??1/0,VF),J))z=null;j=await this.store.get($)??j}}finally{Y.close()}}async*subscribe($,Z={}){let J=this.feed.subscribe(this.channel($),{signal:Z.signal});try{await J.ready();let W=await this.store.get($);if(!W)throw new O8($);if(yield W,x1(W.status))return;for await(let Y of J){let j=OH(Y,$)??await this.store.get($);if(!j||j.version<=W.version)continue;if(W=j,yield W,x1(W.status))return}}finally{J.close()}}stream($,Z,J={}){return this.feed.stream($,this.channel(Z),J)}cursor($){return this.feed.cursor(this.channel($))}async sweep(){let $=await this.now(),Z=0;for(let J of await this.store.overdue($,this.config.sweepLimit))if(await this.expire(J.id))Z++;return Z}async prune($){let Z=BZ($);return await this.store.prune?.(Z)??0}async close(){await this.ownFeed?.close(),this.ownFeed=null}now(){return this.store.now?this.store.now():Promise.resolve(Date.now())}async untilDeadline($){if($.deadlineAt===null)return null;return $.deadlineAt-await this.now()}async expire($){let Z=await this.store.get($);if(!Z||x1(Z.status))return null;let J=await this.untilDeadline(Z);if(J===null||J>0)return null;return this.change($,I1,{status:"timed_out",error:{message:"The run passed its deadline.",code:"deadline"}})}async watch($,Z,J,W){let Y=new Promise((z)=>{if(W.signal.aborted)z("ended");W.signal.addEventListener("abort",()=>z("ended"),{once:!0})}),j=null;try{for(;;){if(W.signal.aborted)return;if(x1(Z.status)){W.abort();return}let z=await this.untilDeadline(Z);if(z!==null&&z<=0){Z=await this.expire($)??await this.store.get($)??Z;continue}j??=J.next();let X=await Promise.race([Y,UF(j,Math.min(z??1/0,VF))]);if(X==="ended")return;if(X)j=null;Z=await this.store.get($)??Z}}catch(z){console.error(`[gemi] Run ${$}: could not follow the run for a cancel.`,z)}}async change($,Z,J){let W=await this.store.transition($,Z,J);if(W)await this.publish(W);return W}async publish($){try{await this.feed.publish(this.channel($.id),$)}catch(Z){console.error(`[gemi] Run ${$.id}: could not publish its change.`,Z)}}}function UF($,Z,J){return new Promise((W,Y)=>{let j=Number.isFinite(Z)?setTimeout(()=>G(!1),Math.max(0,Z)):null,z=()=>{X(),Y(J.reason)},X=()=>{if(j)clearTimeout(j);J?.removeEventListener("abort",z)},G=(Q)=>{X(),W(Q)};J?.addEventListener("abort",z,{once:!0}),$.then(()=>G(!0),()=>G(!0))})}function OH($,Z){if($.type!=="change")return null;let J=$.data;if(!J||typeof J!=="object"||J.id!==Z||typeof J.version!=="number")return null;return J}function DF($){if(typeof $==="string")return{message:$};if($ instanceof L8)return{message:$.message,...$.code!==void 0?{code:$.code}:{},...$.data!==void 0?{data:$.data}:{}};if($ instanceof Error)return{message:$.message};return $}function OF($,Z){if(typeof Z!=="string"||Z===""||Z.length>FF)throw TypeError(`A run's ${$} is a string of 1 to ${FF} characters; got ${JSON.stringify(Z)}.`)}function LH($){let{fraction:Z}=$;if(Z!==void 0&&!(Number.isFinite(Z)&&Z>=0&&Z<=1))throw RangeError(`A run's progress fraction is between 0 and 1; got ${Z}.`)}function MH($,Z){if($==="memory")return new V2;if($==="database"||typeof $==="function"){if(!Z&&($==="database"||$.length>0))throw Error("The runs store needs the application it belongs to, and this RunManager was built without one. Pass { application }.");if($==="database"){let J=Z.make(W$).connection();return new L2(J)}return $(Z)}if(typeof $==="string")throw Error(`Unknown runs store "${$}". The runs slice's store is "memory", "database", a RunStore, or a function returning one.`);return $}class LF extends h{static getFacadeAccessor(){return M2}static create($){return this.getFacadeRoot().create($)}static get($){return this.getFacadeRoot().get($)}static list($){return this.getFacadeRoot().list($)}static start($){return this.getFacadeRoot().start($)}static progress($,Z){return this.getFacadeRoot().progress($,Z)}static complete($,Z){return this.getFacadeRoot().complete($,Z)}static fail($,Z){return this.getFacadeRoot().fail($,Z)}static cancel($,Z){return this.getFacadeRoot().cancel($,Z)}static execute($,Z){return this.getFacadeRoot().execute($,Z)}static wait($,Z){return this.getFacadeRoot().wait($,Z)}static subscribe($,Z){return this.getFacadeRoot().subscribe($,Z)}static stream($,Z,J){return this.getFacadeRoot().stream($,Z,J)}static cursor($){return this.getFacadeRoot().cursor($)}static channel($){return this.getFacadeRoot().channel($)}static sweep(){return this.getFacadeRoot().sweep()}static prune($){return this.getFacadeRoot().prune($)}}class MF extends h{static getFacadeAccessor(){return $$}static enabled($){return this.getFacadeRoot().enabled($)}static all(){return this.getFacadeRoot().forClient()}static explain($){return this.getFacadeRoot().explain($)}static for($){return this.getFacadeRoot().for($)}static list(){return this.getFacadeRoot().list()}static set($,Z,J){return this.getFacadeRoot().set($,Z,J)}static refresh(){return this.getFacadeRoot().refresh()}static invalidate(){return this.getFacadeRoot().invalidate()}}class H2{value;constructor($){this.value=$}}var HH=/^[A-Za-z_][A-Za-z0-9_$]*$/;function TH($){let Z=["SET TRANSACTION READ ONLY"],J=[["statementTimeoutMs","statement_timeout"],["lockTimeoutMs","lock_timeout"],["idleInTransactionTimeoutMs","idle_in_transaction_session_timeout"]];for(let[W,Y]of J){let j=$[W];if(j===void 0)continue;if(typeof j!=="number"||!Number.isInteger(j)||j<=0)throw TypeError(`DB.readOnly: ${W} must be a positive whole number of milliseconds, got ${String(j)}.`);Z.push(`SET LOCAL ${Y} = ${j}`)}if($.role!==void 0){if(typeof $.role!=="string"||!HH.test($.role))throw TypeError(`DB.readOnly: the role "${String($.role)}" is not a plain identifier. Use letters, digits, _ and $.`);Z.push(`SET LOCAL ROLE "${$.role}"`)}return Z}class T8{bound;constructor($){this.bound=$}get name(){return this.bound??J$()}get sql(){return this.connection().sql}get dialect(){return this.connection().dialect}async query($){return await this.run($,"query")}async execute($){let Z=await this.run($,"execute");return Number(Z?.count??0)}async transaction($){let Z=this.name,J=this.connection(Z);return H8(J.sql,(W)=>M8(Z,()=>$(W)),{slowTransactionThreshold:J.config.slowTransactionThreshold,connection:Z})}async readOnly($,Z){let J=typeof $==="function"?{}:$,W=typeof $==="function"?$:Z;if(typeof W!=="function")throw TypeError("DB.readOnly needs a callback: readOnly(options, async (tx) => ...).");let Y=TH(J??{}),j=this.name,z=this.connection(j);if(z.dialect!=="postgres")throw Error(`DB.readOnly is supported on Postgres only, and the "${j}" connection is ${z.dialect}.`);if(Z$()!==void 0)throw Error("DB.readOnly cannot run inside a transaction: SET TRANSACTION READ ONLY has to be the first statement of its own transaction. Call it outside the transaction.");try{await H8(z.sql,async(X)=>{for(let Q of Y)await X.unsafe(Q);await PF();let G=await M8(j,()=>W(X));throw new H2(G)},{slowTransactionThreshold:z.config.slowTransactionThreshold,connection:j,deferSettings:!0})}catch(X){if(X instanceof H2)return X.value;throw X}throw Error("DB.readOnly: the transaction committed, which it never should.")}async schema(){let $=this.connection(),{introspect:Z}=await import("./chunk-7fbnw7e2.js");return Z(this.handle()??$.sql,$.dialect)}async withSettings($,Z){let J=this.connection();if(J.dialect!=="postgres")throw Error(`DB.withSettings is supported on Postgres only, and the "${J.name}" connection is ${J.dialect}.`);return KF($,Z)}run($,Z){let J=this.connection(),{text:W,values:Y}=IF($,_F(J.dialect),Z),j=this.handle();if(j===void 0&&NF()){let z=this.name;return H8(J.sql,(X)=>M8(z,()=>X.unsafe(W,Y)),{slowTransactionThreshold:J.config.slowTransactionThreshold,connection:z})}if(j===void 0)return J.sql.unsafe(W,Y);return j.unsafe(W,Y).catch((z)=>{throw TF(j),z})}handle(){let $=Z$();if($===void 0)return;return J$()===this.name?$:void 0}connection($=this.name){return HF($),H(W$).connection($)}}var x$=new T8;class xF extends h{static getFacadeAccessor(){return W$}static connection($){return new T8($)}static get sql(){return x$.sql}static get dialect(){return x$.dialect}static query($){return x$.query($)}static execute($){return x$.execute($)}static transaction($){return x$.transaction($)}static withSettings($,Z){return x$.withSettings($,Z)}static readOnly($,Z){return x$.readOnly($,Z)}static schema(){return x$.schema()}static close(){return this.getFacadeRoot().close()}}export{V1 as We,kF as Xe,r0 as Ye,z3 as Ze,x8 as _e,x0 as $e,j6 as af,n8 as bf,o8 as cf,g9 as df,r1 as ef,D1 as ff,e1 as gf,F9 as hf,Z0 as if,O9 as jf,D6 as kf,O6 as lf,y9 as mf,m9 as nf,t8 as of,r8 as pf,_6 as qf,TZ as rf,a9 as sf,rV as tf,t9 as uf,eV as vf,dP as wf,$Y as xf,GY as yf,zJ as zf,QY as Af,BY as Bf,XU as Cf,FY as Df,XJ as Ef,BU as Ff,FU as Gf,GJ as Hf,VY as If,UY as Jf,$$ as Kf,DY as Lf,OU as Mf,FJ as Nf,v8 as Of,V6 as Pf,S1 as Qf,w8 as Rf,b1 as Sf,I$ as Tf,F8 as Uf,iB as Vf,sB as Wf,GH as Xf,d1 as Yf,$b as Zf,nB as _f,Y2 as $f,j2 as ag,X2 as bg,tB as cg,eB as dg,$F as eg,JF as fg,YF as gg,jF as hg,zF as ig,i as jg,G3 as kg,h4 as lg,SK as mg,bK as ng,EK as og,qK as pg,PG as qg,g7 as rg,IG as sg,mK as tg,AG as ug,c0 as vg,c3 as wg,SG as xg,XF as yg,mb as zg,F2 as Ag,I1 as Bg,x1 as Cg,V2 as Dg,L2 as Eg,DH as Fg,O8 as Gg,L8 as Hg,M2 as Ig,LF as Jg,MF as Kg,T8 as Lg,xF as Mg,h7 as Ng,VL as Og,n7 as Pg,o7 as Qg,r_ as Rg,tG as Sg,ZQ as Tg,X6 as Ug,n1 as Vg,UI as Wg,WQ as Xg,YQ as Yg,kQ as Zg,H5 as _g,rZ as $g,T5 as ah,VC as bh,NC as ch,PC as dh,kM as eh,y5 as fh,fM as gh,i5 as hh,hM as ih,p5 as jh,dM as kh,a3 as lh,a5 as mh,RB as nh,j8 as oh,X8 as ph,ZS as qh,JS as rh,WS as sh,Q1 as th,E as uh,q0 as vh,G6 as wh,a2 as xh,sF as yh,s2 as zh,r2 as Ah,E8 as Bh,B6 as Ch,R8 as Dh,e2 as Eh,$V as Fh,ZV as Gh,j9 as Hh,X9 as Ih,Q9 as Jh,M9 as Kh,H9 as Lh,T9 as Mh,m8 as Nh,QV as Oh,j0 as Ph,E9 as Qh,MZ as Rh,f9 as Sh};
|
|
87
87
|
|
|
88
|
-
//# debugId=
|
|
88
|
+
//# debugId=FD4AB2B0A62B3FEB64756E2164756E21
|