gemi 0.190.0 → 0.192.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/Agent.d.ts +28 -1
- package/dist/ai/Agent.d.ts.map +1 -1
- package/dist/ai/AgentController.d.ts +143 -3
- package/dist/ai/AgentController.d.ts.map +1 -1
- package/dist/ai/client/index.d.ts +1 -1
- package/dist/ai/client/index.d.ts.map +1 -1
- package/dist/ai/client/index.js +59 -1
- package/dist/ai/client/index.js.map +1 -1
- package/dist/ai/index.d.ts +3 -3
- package/dist/ai/index.d.ts.map +1 -1
- package/dist/ai/index.js +91 -68
- package/dist/ai/index.js.map +5 -5
- package/dist/ai/jobs/AgentJob.d.ts +32 -0
- package/dist/ai/jobs/AgentJob.d.ts.map +1 -1
- package/dist/ai/jobs/index.d.ts +1 -1
- package/dist/ai/jobs/index.d.ts.map +1 -1
- package/dist/ai/store/DatabaseAgentStore.d.ts +66 -3
- package/dist/ai/store/DatabaseAgentStore.d.ts.map +1 -1
- package/dist/ai/store/MemoryAgentStore.d.ts +12 -0
- package/dist/ai/store/MemoryAgentStore.d.ts.map +1 -1
- package/dist/ai/types.d.ts +18 -0
- package/dist/ai/types.d.ts.map +1 -1
- package/dist/ai/useChat.d.ts +15 -0
- package/dist/ai/useChat.d.ts.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-6z3wv71t.js → chunk-0m1a636t.js} +2 -2
- package/dist/{chunk-6z3wv71t.js.map → chunk-0m1a636t.js.map} +1 -1
- package/dist/{chunk-00g20rfa.js → chunk-0mb77yd2.js} +2 -2
- package/dist/{chunk-00g20rfa.js.map → chunk-0mb77yd2.js.map} +1 -1
- package/dist/{chunk-qz6grt61.js → chunk-0p76bhy2.js} +2 -2
- package/dist/{chunk-qz6grt61.js.map → chunk-0p76bhy2.js.map} +1 -1
- package/dist/{chunk-zwj4w4zt.js → chunk-17mdszc3.js} +2 -2
- package/dist/{chunk-zwj4w4zt.js.map → chunk-17mdszc3.js.map} +1 -1
- package/dist/{chunk-yt5n62nj.js → chunk-199nvtrj.js} +2 -2
- package/dist/{chunk-yt5n62nj.js.map → chunk-199nvtrj.js.map} +1 -1
- package/dist/{chunk-w2z4jc4v.js → chunk-1mpwzjxa.js} +3 -3
- package/dist/{chunk-w2z4jc4v.js.map → chunk-1mpwzjxa.js.map} +1 -1
- package/dist/{chunk-dsgjdk94.js → chunk-24jgzc8y.js} +2 -2
- package/dist/{chunk-dsgjdk94.js.map → chunk-24jgzc8y.js.map} +1 -1
- package/dist/{chunk-fgk1e5xe.js → chunk-4s7st9y4.js} +3 -3
- package/dist/{chunk-fgk1e5xe.js.map → chunk-4s7st9y4.js.map} +1 -1
- package/dist/{chunk-epb0qfce.js → chunk-5zx4e2wa.js} +3 -3
- package/dist/{chunk-epb0qfce.js.map → chunk-5zx4e2wa.js.map} +1 -1
- package/dist/{chunk-s5z8qcdv.js → chunk-67ex6nem.js} +3 -3
- package/dist/{chunk-s5z8qcdv.js.map → chunk-67ex6nem.js.map} +1 -1
- package/dist/{chunk-790dx3s7.js → chunk-67zz58cw.js} +2 -2
- package/dist/{chunk-790dx3s7.js.map → chunk-67zz58cw.js.map} +1 -1
- package/dist/{chunk-kcg2znz2.js → chunk-6frbegay.js} +2 -2
- package/dist/{chunk-kcg2znz2.js.map → chunk-6frbegay.js.map} +1 -1
- package/dist/{chunk-0gvw46j0.js → chunk-6n44t4hn.js} +2 -2
- package/dist/{chunk-0gvw46j0.js.map → chunk-6n44t4hn.js.map} +1 -1
- package/dist/{chunk-baknm4tn.js → chunk-6rmz0mkm.js} +2 -2
- package/dist/{chunk-baknm4tn.js.map → chunk-6rmz0mkm.js.map} +1 -1
- package/dist/{chunk-k9f7gww2.js → chunk-6wsmdf51.js} +2 -2
- package/dist/{chunk-k9f7gww2.js.map → chunk-6wsmdf51.js.map} +1 -1
- package/dist/{chunk-2v7a5wv6.js → chunk-7k43y71n.js} +2 -2
- package/dist/{chunk-2v7a5wv6.js.map → chunk-7k43y71n.js.map} +1 -1
- package/dist/{chunk-er7xemh2.js → chunk-7ynahcy6.js} +2 -2
- package/dist/{chunk-er7xemh2.js.map → chunk-7ynahcy6.js.map} +1 -1
- package/dist/{chunk-7des5zys.js → chunk-7zpjdwfq.js} +3 -3
- package/dist/{chunk-7des5zys.js.map → chunk-7zpjdwfq.js.map} +1 -1
- package/dist/{chunk-yn2av14e.js → chunk-8em2ebj1.js} +2 -2
- package/dist/{chunk-yn2av14e.js.map → chunk-8em2ebj1.js.map} +1 -1
- package/dist/{chunk-nc37phkt.js → chunk-8pfy75y6.js} +3 -3
- package/dist/{chunk-nc37phkt.js.map → chunk-8pfy75y6.js.map} +1 -1
- package/dist/{chunk-8f8bp75w.js → chunk-8zeky0fj.js} +5 -5
- package/dist/{chunk-8f8bp75w.js.map → chunk-8zeky0fj.js.map} +3 -3
- package/dist/{chunk-khzss89b.js → chunk-9dfrsj4m.js} +2 -2
- package/dist/{chunk-khzss89b.js.map → chunk-9dfrsj4m.js.map} +1 -1
- package/dist/{chunk-fcj0e64h.js → chunk-9hmm8acy.js} +1 -1
- package/dist/{chunk-rp2h86ph.js → chunk-9m04tdzh.js} +1 -1
- package/dist/{chunk-71jcjnwk.js → chunk-bd14zwmj.js} +25 -21
- package/dist/{chunk-71jcjnwk.js.map → chunk-bd14zwmj.js.map} +4 -4
- package/dist/{chunk-g52hvs5q.js → chunk-bhfwp3gz.js} +2 -2
- package/dist/{chunk-g52hvs5q.js.map → chunk-bhfwp3gz.js.map} +1 -1
- package/dist/{chunk-2adfcfdw.js → chunk-bm7z4vj9.js} +2 -2
- package/dist/{chunk-2adfcfdw.js.map → chunk-bm7z4vj9.js.map} +1 -1
- package/dist/{chunk-e9nmsgnd.js → chunk-c36sbvnz.js} +2 -2
- package/dist/{chunk-e9nmsgnd.js.map → chunk-c36sbvnz.js.map} +1 -1
- package/dist/{chunk-x1ng1dnx.js → chunk-ccx7rt7y.js} +2 -2
- package/dist/{chunk-x1ng1dnx.js.map → chunk-ccx7rt7y.js.map} +1 -1
- package/dist/{chunk-xqzrd7st.js → chunk-ce73s4kh.js} +2 -2
- package/dist/{chunk-xqzrd7st.js.map → chunk-ce73s4kh.js.map} +1 -1
- package/dist/{chunk-3z55zyfe.js → chunk-cx3n8qyr.js} +2 -2
- package/dist/{chunk-3z55zyfe.js.map → chunk-cx3n8qyr.js.map} +1 -1
- package/dist/{chunk-xwa8vtg5.js → chunk-d0khszc9.js} +2 -2
- package/dist/{chunk-xwa8vtg5.js.map → chunk-d0khszc9.js.map} +1 -1
- package/dist/{chunk-frvca65w.js → chunk-efgemgbe.js} +2 -2
- package/dist/{chunk-frvca65w.js.map → chunk-efgemgbe.js.map} +1 -1
- package/dist/{chunk-6tsyk2mr.js → chunk-ejc0mbe3.js} +2 -2
- package/dist/{chunk-6tsyk2mr.js.map → chunk-ejc0mbe3.js.map} +1 -1
- package/dist/{chunk-hv6nbbty.js → chunk-etzd00a8.js} +2 -2
- package/dist/{chunk-hv6nbbty.js.map → chunk-etzd00a8.js.map} +1 -1
- package/dist/{chunk-6a3t825g.js → chunk-f02anz24.js} +2 -2
- package/dist/{chunk-6a3t825g.js.map → chunk-f02anz24.js.map} +1 -1
- package/dist/{chunk-qy678j5z.js → chunk-fbxnxze2.js} +1 -1
- package/dist/{chunk-j16ekp16.js → chunk-freerpzc.js} +1 -1
- package/dist/{chunk-h8knqrc5.js → chunk-fryj3asn.js} +2 -2
- package/dist/{chunk-h8knqrc5.js.map → chunk-fryj3asn.js.map} +1 -1
- package/dist/{chunk-vzzt4kpk.js → chunk-h688s2ba.js} +2 -2
- package/dist/{chunk-vzzt4kpk.js.map → chunk-h688s2ba.js.map} +1 -1
- package/dist/{chunk-bc1k2206.js → chunk-hwq0kk1d.js} +1 -1
- package/dist/{chunk-mvs6brkk.js → chunk-j34ektzj.js} +2 -2
- package/dist/{chunk-mvs6brkk.js.map → chunk-j34ektzj.js.map} +1 -1
- package/dist/{chunk-ds684s0w.js → chunk-jbee3n3p.js} +2 -2
- package/dist/{chunk-ds684s0w.js.map → chunk-jbee3n3p.js.map} +1 -1
- package/dist/{chunk-80kpxp4m.js → chunk-k1c0xd8r.js} +2 -2
- package/dist/{chunk-80kpxp4m.js.map → chunk-k1c0xd8r.js.map} +1 -1
- package/dist/{chunk-tmz3gf96.js → chunk-k8gn0q91.js} +1 -1
- package/dist/{chunk-8p7a2ctj.js → chunk-m3180wkp.js} +2 -2
- package/dist/{chunk-8p7a2ctj.js.map → chunk-m3180wkp.js.map} +1 -1
- package/dist/{chunk-s1wj0ff8.js → chunk-m37vvh99.js} +2 -2
- package/dist/{chunk-s1wj0ff8.js.map → chunk-m37vvh99.js.map} +1 -1
- package/dist/{chunk-mmzf9c2e.js → chunk-m4r8btey.js} +2 -2
- package/dist/{chunk-mmzf9c2e.js.map → chunk-m4r8btey.js.map} +1 -1
- package/dist/{chunk-8mgz2na4.js → chunk-mdrsec0r.js} +2 -2
- package/dist/{chunk-8mgz2na4.js.map → chunk-mdrsec0r.js.map} +1 -1
- package/dist/{chunk-nbhxm3sz.js → chunk-mx9zcq7w.js} +2 -2
- package/dist/{chunk-nbhxm3sz.js.map → chunk-mx9zcq7w.js.map} +1 -1
- package/dist/{chunk-t6ng9yxp.js → chunk-p00rd4ja.js} +2 -2
- package/dist/{chunk-t6ng9yxp.js.map → chunk-p00rd4ja.js.map} +1 -1
- package/dist/{chunk-rf4a3tnm.js → chunk-qfb6r3cq.js} +3 -3
- package/dist/{chunk-rf4a3tnm.js.map → chunk-qfb6r3cq.js.map} +1 -1
- package/dist/{chunk-352y2y3z.js → chunk-qg60pgve.js} +2 -2
- package/dist/{chunk-352y2y3z.js.map → chunk-qg60pgve.js.map} +1 -1
- package/dist/{chunk-2qqm3482.js → chunk-qnc840pb.js} +2 -2
- package/dist/{chunk-2qqm3482.js.map → chunk-qnc840pb.js.map} +1 -1
- package/dist/{chunk-mqvyhqa6.js → chunk-r7vnxqck.js} +2 -2
- package/dist/{chunk-mqvyhqa6.js.map → chunk-r7vnxqck.js.map} +1 -1
- package/dist/{chunk-bwmyd47e.js → chunk-rf9c6e49.js} +2 -2
- package/dist/{chunk-bwmyd47e.js.map → chunk-rf9c6e49.js.map} +1 -1
- package/dist/{chunk-1987f978.js → chunk-ryfty6mj.js} +3 -3
- package/dist/{chunk-1987f978.js.map → chunk-ryfty6mj.js.map} +1 -1
- package/dist/{chunk-6bhscseq.js → chunk-sqev442x.js} +4 -4
- package/dist/{chunk-6bhscseq.js.map → chunk-sqev442x.js.map} +1 -1
- package/dist/{chunk-npd1501w.js → chunk-t86nc1jd.js} +2 -2
- package/dist/{chunk-npd1501w.js.map → chunk-t86nc1jd.js.map} +1 -1
- package/dist/{chunk-qp1nzdjc.js → chunk-thq8tc9x.js} +3 -3
- package/dist/{chunk-qp1nzdjc.js.map → chunk-thq8tc9x.js.map} +1 -1
- package/dist/{chunk-cbw4676x.js → chunk-tngf3h1g.js} +2 -2
- package/dist/{chunk-cbw4676x.js.map → chunk-tngf3h1g.js.map} +1 -1
- package/dist/{chunk-n415vvxw.js → chunk-tt5qk0xt.js} +2 -2
- package/dist/{chunk-n415vvxw.js.map → chunk-tt5qk0xt.js.map} +1 -1
- package/dist/{chunk-b35mk5rd.js → chunk-tvsjq0my.js} +2 -2
- package/dist/{chunk-b35mk5rd.js.map → chunk-tvsjq0my.js.map} +1 -1
- package/dist/{chunk-2k948anx.js → chunk-vr48swd0.js} +2 -2
- package/dist/{chunk-2k948anx.js.map → chunk-vr48swd0.js.map} +1 -1
- package/dist/{chunk-sz0avnch.js → chunk-wa1xmvgr.js} +2 -2
- package/dist/{chunk-sz0avnch.js.map → chunk-wa1xmvgr.js.map} +1 -1
- package/dist/chunk-waq4kj7n.js +5 -0
- package/dist/{chunk-qv3y19h5.js.map → chunk-waq4kj7n.js.map} +1 -1
- package/dist/{chunk-8b897pc1.js → chunk-xsx69765.js} +2 -2
- package/dist/{chunk-8b897pc1.js.map → chunk-xsx69765.js.map} +1 -1
- package/dist/{chunk-eqnrk0p8.js → chunk-xwz5fmwy.js} +2 -2
- package/dist/{chunk-eqnrk0p8.js.map → chunk-xwz5fmwy.js.map} +1 -1
- package/dist/{chunk-ct2kqpv5.js → chunk-xzz6ps4z.js} +2 -2
- package/dist/{chunk-ct2kqpv5.js.map → chunk-xzz6ps4z.js.map} +1 -1
- package/dist/{chunk-s91xa67z.js → chunk-y67rmd3y.js} +2 -2
- package/dist/{chunk-s91xa67z.js.map → chunk-y67rmd3y.js.map} +1 -1
- package/dist/{chunk-1e7pnsx2.js → chunk-z1aeh05w.js} +3 -3
- package/dist/{chunk-1e7pnsx2.js.map → chunk-z1aeh05w.js.map} +1 -1
- package/dist/{chunk-070cacy8.js → chunk-z7mbhc68.js} +2 -2
- package/dist/{chunk-070cacy8.js.map → chunk-z7mbhc68.js.map} +1 -1
- package/dist/{chunk-pjjwbs2f.js → chunk-z8dxdqzm.js} +2 -2
- package/dist/{chunk-pjjwbs2f.js.map → chunk-z8dxdqzm.js.map} +1 -1
- package/dist/{chunk-9q5g3a9t.js → chunk-z9pq557m.js} +2 -2
- package/dist/{chunk-9q5g3a9t.js.map → chunk-z9pq557m.js.map} +1 -1
- package/dist/{chunk-dhwxcedm.js → chunk-zcrhagx5.js} +2 -2
- package/dist/{chunk-dhwxcedm.js.map → chunk-zcrhagx5.js.map} +1 -1
- package/dist/client/Head.d.ts +26 -1
- package/dist/client/Head.d.ts.map +1 -1
- package/dist/client/index.d.ts +1 -1
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +17 -2
- package/dist/client/index.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 +1 -1
- package/dist/foundation/index.js +2 -2
- package/dist/foundation/index.js.map +1 -1
- package/dist/http/ApiRouter.d.ts +1 -0
- package/dist/http/ApiRouter.d.ts.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 +2 -2
- package/dist/services/index.js.map +1 -1
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.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-qv3y19h5.js +0 -5
- /package/dist/{chunk-fcj0e64h.js.map → chunk-9hmm8acy.js.map} +0 -0
- /package/dist/{chunk-rp2h86ph.js.map → chunk-9m04tdzh.js.map} +0 -0
- /package/dist/{chunk-qy678j5z.js.map → chunk-fbxnxze2.js.map} +0 -0
- /package/dist/{chunk-j16ekp16.js.map → chunk-freerpzc.js.map} +0 -0
- /package/dist/{chunk-bc1k2206.js.map → chunk-hwq0kk1d.js.map} +0 -0
- /package/dist/{chunk-tmz3gf96.js.map → chunk-k8gn0q91.js.map} +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{th as WV}from"./chunk-yt5n62nj.js";import{Nh as JV}from"./chunk-eqnrk0p8.js";import{$h as J3,Bi as H6,Hi as M6,Oh as O3,Pi as R1,Sh as WB,Th as X9,Ti as uG,Uh as G9,Ui as jZ,Vh as S8,Vi as zZ,Wh as N8,Wi as qB,Yi as vB,Zh as _8,_h as I8,ai as W8,bi as o5,ci as R2,di as d,ji as C,ki as x5,li as o8,mi as HZ,ni as E8,oi as L6,qi as R$,ri as m,si as a4}from"./chunk-1987f978.js";import{$i as Z$,aj as K0,bj as W$,cj as B9}from"./chunk-8b897pc1.js";import{dj as ZZ,ej as t5,ij as s9,jj as Y8,kj as P}from"./chunk-bwmyd47e.js";import{nj as wG,qj as a3}from"./chunk-7des5zys.js";import{uj as zY,xj as SB}from"./chunk-epb0qfce.js";import{Pj as b$,Uj as J$}from"./chunk-2k948anx.js";import{gk as OG}from"./chunk-cbw4676x.js";import{hk as XZ,kk as CB}from"./chunk-khzss89b.js";import{lk as N1}from"./chunk-xqzrd7st.js";import{Ck as M2,mk as F6,nk as s0,ok as w1,pk as H2,qk as ZV,sk as sZ,tk as wB}from"./chunk-fgk1e5xe.js";import{Rk as f1}from"./chunk-yn2av14e.js";import{$k as c5,Wk as p5}from"./chunk-vzzt4kpk.js";import{gl as h5,ll as c}from"./chunk-x1ng1dnx.js";import{ml as Z3,pl as M}from"./chunk-nc37phkt.js";import{xl as q5}from"./chunk-0gvw46j0.js";import{yl as gB}from"./chunk-6a3t825g.js";import{Il as b5}from"./chunk-h8knqrc5.js";import{Jl as F8,Ll as YB}from"./chunk-s91xa67z.js";import{Ql as j8}from"./chunk-80kpxp4m.js";function z6($){return typeof $==="function"&&$.prototype!==void 0}var N2=Symbol.for("gemi.HttpResponse"),BV=new Set([301,302,303,307,308]);class F1{kind;body;status;headers;[N2]=!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 P2(J,"json"),new F1("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 F1.json({error:Z},{...J,status:$})}static redirect($,Z={}){let J=Z.status??303;if(!BV.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 F1("empty",void 0,J,Y)}static noContent($={}){return new F1("empty",null,204,new Headers($.headers))}static text($,Z={}){let J=Z.status??200;return P2(J,"text"),new F1("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 P2($,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 r1($){return typeof $==="object"&&$!==null&&$[N2]===!0}function VV($,Z,J={}){return F1.error($,Z,J)}function e0($){return typeof $==="string"?[$]:$}function X6($,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 FV($){return"total"in $&&"partial"in $&&"body"in $}function _2(){return new Response("Not found",{status:404,headers:{"X-Content-Type-Options":"nosniff"}})}function Q3($){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 UV($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(FV($))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 _2();let J=await UV($),{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 _2()}let{range:G}=Z;if(G){if(z<=0)return Q3(Math.max(z,0));if(!X){if(W instanceof Blob){let B=N8(G,z);if(!B)return Q3(z);W=W.slice(B.start,B.end+1),Y=B.start,j=B.end,X=!0}}}let Q=Boolean(G)&&X,V=Q?206:J.status,F=new Headers;if(F.set("Accept-Ranges","bytes"),F.set("Content-Type",J.type||"application/octet-stream"),F.set("X-Content-Type-Options","nosniff"),Q)F.set("Content-Range",_8(Y,j,z)),F.set("Content-Length",String(j-Y+1));else if(z>=0)F.set("Content-Length",String(z));if(J.name)F.set("Content-Disposition",X6(J.name,J.download));if(J.etag)F.set("ETag",J.etag);if(J.lastModified)F.set("Last-Modified",J.lastModified.toUTCString());for(let[B,U]of Object.entries(J.extraHeaders))F.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:V,headers:F})}return new Response(W,{status:V,headers:F})}class FZ extends K0{limit;constructor($){super("The request body is too large.",{status:413});this.limit=$}}var I2={b:1,k:1024,kb:1024,m:1048576,mb:1048576,g:1073741824,gb:1073741824};function V3($){if(typeof $==="number"){if(Number.isFinite($)&&$>=0)return Math.floor($);if($===1/0)return 1/0}else{let Z=$.trim().toLowerCase();if(Z==="none"||Z==="off")return 1/0;let J=/^(\d+(?:\.\d+)?)\s*([a-z]*)$/.exec(Z);if(J&&(J[2]===""||(J[2]in I2)))return Math.floor(Number(J[1])*(I2[J[2]]??1))}throw Error(`Invalid body limit ${JSON.stringify($)}. Use a byte count or a size such as "64kb", "1mb" or "none".`)}var B3=new WeakMap;function C2($){return B3.has($)}function A2($){return B3.get($)?.limit??null}function S2($){let Z=B3.get($);return Z?Z.read>Z.limit:!1}function OV($){let Z=$.headers.get("Content-Length");if(Z===null||!/^\s*\d+\s*$/.test(Z))return null;return Number(Z)}function A8($,Z){let J=OV($);if(J!==null&&J>Z)throw new FZ(Z)}function G6($,Z,J={}){let W=B3.get($);if(W)W.limit=Z;else{let Y={limit:Z,read:0,stream:void 0,used:!1};B3.set($,Y),LV($,Y)}if(J.checkDeclared!==!1)A8($,Z)}function DV($){return Reflect.get(Object.getPrototypeOf($),"body",$)??null}function C8($,Z){if(Z.stream!==void 0)return Z.stream;let J=DV($);if(!J)return Z.stream=null;let W;return Z.stream=new ReadableStream({async pull(Y){W??=J.getReader();let{done:j,value:z}=await W.read();if(j){Y.close();return}if(Z.read+=z.byteLength,Z.read>Z.limit){let X=new FZ(Z.limit);Y.error(X),W.cancel(X).catch(()=>{});return}Y.enqueue(z)},cancel(Y){return W?W.cancel(Y):J.cancel(Y)}},{highWaterMark:0}),Z.stream}async function VZ($,Z){if(A8($,Z.limit),Z.used||Z.stream?.locked)throw TypeError("Body already used");Z.used=!0;let J=C8($,Z);if(!J)return new Uint8Array(0);let W=J.getReader(),Y=[],j=0;for(;;){let{done:G,value:Q}=await W.read();if(G)break;Y.push(Q),j+=Q.byteLength}let z=new Uint8Array(j),X=0;for(let G of Y)z.set(G,X),X+=G.byteLength;return z}function x2($){return $.headers.get("Content-Type")??""}function LV($,Z){let J=(W,Y)=>Object.defineProperty($,W,{configurable:!0,...Y});J("body",{get:()=>C8($,Z)}),J("bodyUsed",{get:()=>Z.used||Boolean(Z.stream?.locked)||Reflect.get(Object.getPrototypeOf($),"bodyUsed",$)}),J("bytes",{value:()=>VZ($,Z)}),J("arrayBuffer",{value:async()=>{let W=await VZ($,Z);return W.buffer.slice(W.byteOffset,W.byteOffset+W.byteLength)}}),J("text",{value:async()=>new TextDecoder().decode(await VZ($,Z))}),J("json",{value:async()=>JSON.parse(new TextDecoder().decode(await VZ($,Z)))}),J("blob",{value:async()=>new Blob([await VZ($,Z)],{type:x2($)})}),J("formData",{value:async()=>new Response(await VZ($,Z),{headers:{"Content-Type":x2($)}}).formData()}),J("clone",{value:()=>{A8($,Z.limit);let W=C8($,Z),Y=null;if(W){let[j,z]=W.tee();Z.stream=j,Y=z}return new Request($.url,{method:$.method,headers:$.headers,body:Y,signal:$.signal,duplex:"half"})}})}function HV($){return z6($)}function E2($,Z){if($.length===0)return $();return $(Z??new C)}class o{method;handler;methodName;__internal_brand="RouteHandler";middlewares=[];constructor($,Z,J){this.method=$;this.handler=Z;this.methodName=J;this.handler=Z,this.methodName=J,this.method=$}get source(){if(!HV(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 E2(Z[this.methodName].bind(Z),$)}return E2(this.handler,$)}middleware($){return this.middlewares=e0($),this}}class k2{url;headers;__internal_brand="ProxyHandler";middlewares=[];constructor($,Z){this.url=$;this.headers=Z}middleware($){return this.middlewares=e0($),this}async run(){let $=new C,Z=$.headers.toJSON();for(let J of R2($.rawRequest))delete Z[J];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(J){if(S2($.rawRequest))throw new FZ(A2($.rawRequest));throw J}}}class w2{constructor(...$){return new o(...$)}}class f2 extends o{__internal_brand="StreamHandler";async run($){let Z=P.getStore(),J=Z?.req?.rawRequest,W=S8(J?.headers.get("Range"));if(Z)Z.rangeRequest=W;try{let Y=await super.run($);if(r1(Y))return Y;return await x8(Y,{range:W,method:J?.method})}catch(Y){if(Y instanceof E8)return Q3(Y.total);throw Y}finally{if(Z)Z.rangeRequest=null}}}class q2{constructor(...$){return new f2(...$)}}class v2{__internal_brand="ResourceRoutes";first;second;constructor($){this.first={get:new o("GET",$,"list"),post:new o("POST",$,"store")},this.second={get:new o("GET",$,"show"),put:new o("PUT",$,"update"),delete:new o("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 C0{static __brand="ApiRouter";routes={};middlewares=[];middleware($){}get($,Z){return new o("GET",$,Z)}post($,Z){return new o("POST",$,Z)}put($,Z){return new o("PUT",$,Z)}patch($,Z){return new o("PATCH",$,Z)}delete($,Z){return new o("DELETE",$,Z)}resource($){return new v2($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${b2($)}.`);return MV($)}voice($){if($.kind!=="agent-controller")throw TypeError(`this.voice() takes an AgentController class, and got ${b2($)}.`);return KV($)}file($,Z){return new w2("GET",$,Z)}stream($,Z){return new q2("GET",$,Z)}proxy($,Z={}){return new k2($,Z)}}function b2($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function MV($){let Z={stream:new o("POST",$,"stream"),attach:new o("POST",$,"attach"),stop:new o("POST",$,"stop"),upload:new o("POST",$,"upload")};return class extends C0{static __internal_brand="AgentRoute";static controller=$;static handlers=Z;routes={"/":Z.stream,"/attach":Z.attach,"/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);if(W.stop)Z.stop.middleware(W.stop);if(W.upload)Z.upload.middleware(W.upload);return this}}}function KV($){let Z={start:new o("POST",$,"voiceStart"),update:new o("PATCH",$,"voiceUpdate"),end:new o("DELETE",$,"voiceEnd")};return class extends C0{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 e1="access_token";function E$($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function Q6($,Z){let J=E$(Z);if(!J)return null;return(await $.getSession(J,Z.headers.get("User-Agent")))?.user??null}var TV=/^[A-Za-z0-9_-]+$/,PV=/^:[A-Za-z_][A-Za-z0-9_]*$/,g2=/^[A-Za-z0-9_-]{1,128}$/,NV=/^[A-Za-z0-9_.:-]+$/;class u extends Error{constructor($){super($);this.name="InvalidChannelError"}}function y2($){return typeof $==="object"&&$!==null&&typeof $.topic==="string"}function UZ($){if(typeof $!=="string"||$.length===0)throw new u("A channel pattern must be a non-empty string.");if($.length>255)throw new u(`The channel pattern "${$.slice(0,40)}\u2026" is longer than ${"255"} characters.`);let Z=$.split("."),J=new Set;for(let W of Z){if(PV.test(W)){let Y=W.slice(1);if(J.has(Y))throw new u(`The channel pattern "${$}" names the param "${Y}" twice.`);J.add(Y);continue}if(W.startsWith("__"))throw new u(`The channel "${$}" has the segment "${W}". Segments starting with "__" are reserved for gemi (driver control messages).`);if(!TV.test(W))throw new u(`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 F3($,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 u(`The channel "${$}" needs the param "${z}".`);let G=typeof X==="number"&&Number.isFinite(X)?String(X):X;if(typeof G!=="string"||!g2.test(G))throw new u(`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 u(`The channel "${$}" has no param "${j}".`);if(Y.length>255)throw new u(`The topic built from "${$}" is longer than 255 characters.`);return Y}function b8($){if(UZ($).some((J)=>J.startsWith(":")))throw new u(`"${$}" is a pattern, not a topic: pass its params, as in Broadcast.to("${$}", { ... }).`);return $}function m2($){if(typeof $!=="string"||$.length===0||$.length>64||!NV.test($))throw new u(`The event name "${String($).slice(0,40)}" must be 1 to 64 letters, digits, "_", "-", "." or ":".`);return $}function h2($,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(":")&&g2.test(W[j]))}var U0="user";function OZ($){let Z=typeof $==="object"&&$!==null?$.id:$;return F3(`${U0}.:id`,{id:Z})}class J0{req;static runsOnRefusal=!1;config={};constructor($){this.req=$}run(...$){return{}}static configure($){let Z=this;return class extends Z{config=$}}}class B6 extends J0{run($){let Z=$??this.config.limit;if(Z===void 0||Z==="")throw Error('`body-limit` needs a size, as in "body-limit:64kb".');return G6(this.req.rawRequest,V3(Z)),{}}}function _V($){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}var IV={"body-limit":B6};class $${config;static token="middleware";defaultBodyLimit;constructor($){this.config=$;this.defaultBodyLimit=$.bodyLimit===null||$.bodyLimit===void 0?null:V3($.bodyLimit)}get aliases(){return{...IV,...this.config.aliases}}applyDefaultBodyLimit($){if(this.defaultBodyLimit!==null&&!C2($))G6($,this.defaultBodyLimit,{checkDeclared:!1})}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 C,J=this.aliases,W=[];for(let[Y,j]of _V($).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:p2(z)})}}else if(z6(Y)){let z=new Y(Z);W.push({run:z.run.bind(z),runsOnRefusal:p2(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 xV(W.slice(j+1)),z}return Y})()}}function p2($){return $?.runsOnRefusal===!0}async function xV($){for(let Z of $){if(!Z.runsOnRefusal)continue;try{await Z.run()}catch(J){console.error(J)}}}class V6{visibility;authorizer;middlewares=[];constructor($,Z){this.visibility=$;this.authorizer=Z}middleware($){return this.middlewares=[...this.middlewares,...e0($)],this}events(...$){return this}}class l2{static __brand="ChannelRouter";channels={};public(){return new V6("public")}private($){return new V6("private",$)}async authorize($,Z,J={},W={}){try{EV(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(!i2(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=F3(Z,J??{})}catch(G){if(G instanceof u)return{ok:!1,code:"invalid_params"};throw G}let z=Object.fromEntries(Object.entries(J??{}).map(([G,Q])=>[G,String(Q)])),X=new C($,z,"api",Z);return P.exit(()=>F6.exit(()=>P.run(X,async()=>{let G=P.getStore();try{if(Y.middlewares.length>0)await M($$).runMiddleware(Y.middlewares);if(Z===U0){let Q=await c2(X);if(!Q)return{ok:!1,code:"denied"};if(j=OZ(Q),Y.visibility==="private"&&Y.authorizer){if(await d2(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 d2(Y.authorizer,X,z):await c2(X)!==null)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}catch(Q){if(SV(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 CV($,Z,J={},W={}){let Y=typeof $==="function"?new $:$;s2(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 i2($){let Z=$?.visibility;return typeof $==="object"&&$!==null&&Array.isArray($.middlewares)&&(Z==="public"||Z==="private")}async function c2($){if(!P.getStore().user&&E$($)===null)return null;try{return await q0.user()}catch(Z){if(Z?.name==="AuthenticationError")return null;throw Z}}function d2($,Z,J){if(AV($))return new $().authorize(Z,J);return $(Z,J)}function AV($){return typeof $==="function"&&typeof $.prototype?.authorize==="function"}function SV($){return $?.kind===Z$||J$($)||b$($)}var u2=new WeakSet;function EV($){if(u2.has($))return;s2($),u2.add($)}function s2($){let Z=Object.entries($.channels),J=[];for(let[W,Y]of Z){if(!i2(Y))throw new u(`The channel "${W}" is not declared with this.public() or this.private().`);let j=UZ(W);if(j[0].startsWith(":"))throw new u(`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 u(`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 u(`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(bV(J[W].segments,J[Y].segments))throw new u(`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 bV($,Z){if($.length!==Z.length)return!1;return $.every((J,W)=>J===Z[W]||J.startsWith(":")||Z[W].startsWith(":"))}class R8{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,J){this.as=$;this.input=Z;this.bind=J}}class U6{method;url;meta;__internal_brand="McpRoute";constructor($,Z,J){this.method=$;this.url=Z;this.meta=J}}class k8{tool;meta;__internal_brand="McpTool";constructor($,Z){this.tool=$;this.meta=Z}}function RV($){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 kV($,Z){let J=RV($);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 n2{static __brand="McpRouter";routes={};scopes;param($){return new R8($.as,$.input,$.bind)}fromTool($,Z={}){return new k8($,Z)}fromApiRoute($,Z,J){return new U6($,Z,J)}fromApiRouteFor($,Z,J){let{name:W,audiences:Y,description:j,params:z,files:X,...G}=J,Q=`McpRouter.fromApiRouteFor("${$}", "${Z}")`,V=Object.keys(Y??{});if(V.length===0)throw Error(`${Q}: declare at least one audience.`);let F={},B=new Map;for(let U of V){let{name:D,casing:O,description:L,params:H,files:T,...K}=Y[U],I=D??(O?kV(W,O):W);if(B.has(I))throw Error(`${Q}: the audiences "${B.get(I)}" and "${U}" are both named "${I}". Give one its own name or casing.`);B.set(I,U);let b=typeof L==="function"?j===void 0?void 0:L(j):L??j;if(typeof b!=="string")throw Error(`${Q}: the audience "${U}" has no description, and there is no shared one.`);let S={...G,...K,description:b};if(z||H)S.params={...z,...H};if(X||T)S.files={...X,...T};F[I]=new U6($,Z,S)}return F}}function O0($,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 w8 extends K0{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 E1{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 w8([O0($,Y)||"/",X.toString()].filter(Boolean).join("?"),z??(j?301:307))}static external($,Z=307){throw new w8($,Z)}}class o2{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 E1.to(J,{permanent:W,status:Y}),{}}middleware($){return this.middlewares=e0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function f8($,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",X6(Y,z));return new Response(W instanceof Blob?W.stream():W,{status:X,headers:Z})}class a2{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=e0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}function t2($,Z){if(r1($))throw Error(`The handler of view "${Z}" returned an HttpResponse. HttpResponse is for api routes; a view handler returns its props.`);return $}class r2{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=t2(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}middleware($){return this.middlewares=e0($),this}static($={}){return this.staticOptions={...$},this}feature($){return this.featureGates=[...this.featureGates,$],this}}class e2{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=t2(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=e0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class b1{middlewares=[];featureGates=[];routes={};view($,Z){return new r2($,Z)}file($){return new a2($)}redirect($){return new o2($)}layout($,Z,J){return new e2($,Z,J)}}function wV($){return $}function fV(){return{aliases:{},global:[],bodyLimit:null}}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 DZ($){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 qV($,Z=!0){let J=new URL($.rawRequest.url),W=J.pathname.replace(/\.(json|og)$/,""),[,Y,...j]=W.split("/");if(M(c).supportedLocales.includes(Y))W=`/${j.join("/")}`;return Z?`${W}${J.search}`:W}function vV($,Z){let J=(W)=>W.replace(/\/+$/,"")||"/";return J($)===J(Z)}function O6($,Z){let J=Z||M(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=qV($,!W);if(W||!vV(new URL(j,Y).pathname,Y.pathname))Y.searchParams.set(l0,j)}return W?Y.href:`${Y.pathname}${Y.search}`}class $9 extends J0{async run($){let Z=P.getStore(),J=Z.req;if(Z.user)return{};let W=await Q6(M(E),J);if(!W)throw new R$({redirectTo:O6(J,$)});return Z.setUser(W),{}}}var g8="gemi_same_site",v8="private, no-cache, no-store, max-age=0, must-revalidate";class D6 extends J0{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(g8))return{};if(E$(Z))return{};let Y=J.headers.get("Sec-Fetch-Site");if(Y&&Y!=="cross-site")return{};throw W.searchParams.set(g8,"1"),new Z9(`${W.pathname}${W.search}`)}}class Z9 extends K0{location;constructor($){super("Same-site bounce");this.location=$;this.name="SameSiteBounce";let Z=gV($),J={"Content-Type":"text/html; charset=utf-8","Cache-Control":v8,"Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex"};this.payload={api:{status:401,data:{},headers:{"Cache-Control":v8}},viewData:{status:200,data:{},headers:{"Cache-Control":v8},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 gV($){return $.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}class J9 extends J0{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 W9={"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 Y9 extends J0{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={...W9,...this.config.origins[Z]};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={...W9,...this.config.origins["*"]};delete J["Access-Control-Allow-Credentials"];for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}return{}}}var yV="Rate limit exceeded";class Y$ extends K0{result;retryAfter;constructor($,Z=yV){super(Z);this.result=$;this.retryAfter=$?.retryAfter;let J={"Content-Type":"application/json",...$?y8($):{}};this.payload={api:{status:429,data:{error:{...W$("rate_limit",Z,429),...$?{retryAfter:$.retryAfter}:{}}},headers:J},view:{error:{message:Z},status:429,headers:J}}}}function y8($){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 O1{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(j9("window",W),j9("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 Y$(W,typeof J==="function"?J(W):J);return W}}function j9($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}import{isIP as m8}from"net";function k$($){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 m8(j)===6?j:null}if(m8(Z))return Z;let J=/^(\d{1,3}(?:\.\d{1,3}){3}):\d{1,5}$/.exec(Z);return J&&m8(J[1])===4?J[1]:null}class Q9 extends J0{async run($,Z){let J=mV();if(!J)return{};let W=await J.consume(this.key(),{limit:z9($)??this.config.limit,window:z9(Z)??this.config.window});if(this.config.headers!==!1){let Y=this.req.ctx?.();if(Y)for(let[j,z]of Object.entries(y8(W)))Y.setHeaders(j,z)}if(!W.allowed)throw new Y$(W);return{}}key(){if(this.config.key)return this.config.key(this.req);let $=X9(this.req.rawRequest);if($)return`mcp:${$.via}:${$.id}:${this.req.routePath??"*"}`;return`${LZ(this.req)}:${this.req.routePath??"*"}`}}function mV(){try{let $=M();return $.bound(O1)?$.make(O1):null}catch{return null}}function LZ($){let Z=G9($.rawRequest);if(Z!==void 0)return Z;let J=$.headers.get("x-forwarded-for");if(J){let[W]=J.split(",");if(W?.trim())return k$(W)??W.trim()}return $.headers.get("x-real-ip")?.trim()||"unknown"}function z9($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}class V9 extends J0{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new h8;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new h8;return{}}}class h8 extends K0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:B9("csrf","Invalid CSRF token",403)}},view:{}}}class F9{policiesList={};constructor(){let $=this.register();for(let Z of $){let J=new Z;this.policiesList[Z.name]=J}}register(){return[]}}class U9{all($,Z){return!0}}class p8{options;param;refuse;answers=new WeakMap;constructor($){this.options=$;this.param=$.param,this.refuse=$.refuse??"not_found"}refusal(){return this.refuse==="forbidden"?new HZ: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 C,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 J0{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 HZ:$ instanceof L6}}function hV($){return new p8($)}async function K6($,Z,J=!1){if(!$.body)return new Uint8Array;let[W,Y]=await eV($.body),z=W.length>=2&&W[0]===31&&W[1]===139?Y.pipeThrough(new DecompressionStream("gzip")):Y;return rV(z,Z,J,$.url)}async function rV($,Z,J,W){let Y=$.getReader(),j=[],z=0;try{for(;;){let{done:Q,value:V}=await Y.read();if(Q)break;if(z+V.byteLength>Z){if(!J)throw new M6(W,Z);j.push(V.subarray(0,Z-z)),z=Z;break}j.push(V),z+=V.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 eV($){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 T6($){return new TextDecoder("utf-8").decode($)}var $F={"&":"&","<":"<",">":">",'"':""","'":"'"};function w$($){return $.replace(/[&<>"']/g,(Z)=>$F[Z])}var ZF={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function c8($){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 ZF[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 d8($){let Z=$.indexOf(":");return(Z===-1?$:$.slice(Z+1)).toLowerCase()}function O9($,Z){let J=$.length,W=0;while(W<J){if(Z.stopped?.())return;let Y=$.indexOf("<",W);if(Y===-1){Z.text(c8($.slice(W)));return}if(Y>W)Z.text(c8($.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(d8($.slice(Y+2,j).trim())),W=j+1}else{let j=JF($,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=d8(z.slice(0,G));if(Q){if(Z.open(Q,WF(z.slice(G)),X),X)Z.close(Q)}W=j+1}}}function JF($,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 WF($){let Z={},J=/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;for(let W of $.matchAll(J))Z[d8(W[1])]=c8(W[2]??W[3]??"");return Z}class z0 extends Error{url;status;constructor($,Z=null,J=null){super($);this.url=Z;this.status=J;this.name="SitemapError"}}var K9="http://www.sitemaps.org/schemas/sitemap/0.9",YF="http://www.w3.org/1999/xhtml",i8=`<?xml version="1.0" encoding="UTF-8"?>
|
|
2
|
+
import{th as WV}from"./chunk-199nvtrj.js";import{Nh as JV}from"./chunk-xwz5fmwy.js";import{$h as J3,Bi as H6,Hi as M6,Oh as O3,Pi as R1,Sh as WB,Th as X9,Ti as uG,Uh as G9,Ui as jZ,Vh as S8,Vi as zZ,Wh as N8,Xi as qB,Zh as _8,Zi as vB,_h as I8,ai as W8,bi as o5,ci as R2,di as d,ji as C,ki as x5,li as o8,mi as HZ,ni as E8,oi as L6,qi as R$,ri as m,si as a4}from"./chunk-ryfty6mj.js";import{aj as Z$,bj as K0,cj as W$,dj as B9}from"./chunk-xsx69765.js";import{ej as ZZ,fj as t5,jj as s9,kj as Y8,lj as P}from"./chunk-rf9c6e49.js";import{oj as wG,rj as a3}from"./chunk-7zpjdwfq.js";import{vj as zY,yj as SB}from"./chunk-5zx4e2wa.js";import{Qj as b$,Vj as J$}from"./chunk-vr48swd0.js";import{hk as OG}from"./chunk-tngf3h1g.js";import{ik as XZ,lk as CB}from"./chunk-9dfrsj4m.js";import{mk as N1}from"./chunk-ce73s4kh.js";import{Dk as M2,nk as F6,ok as s0,pk as w1,qk as H2,rk as ZV,tk as sZ,uk as wB}from"./chunk-4s7st9y4.js";import{Sk as f1}from"./chunk-8em2ebj1.js";import{Xk as p5,al as c5}from"./chunk-h688s2ba.js";import{hl as h5,ml as c}from"./chunk-ccx7rt7y.js";import{nl as Z3,ql as M}from"./chunk-8pfy75y6.js";import{yl as q5}from"./chunk-6n44t4hn.js";import{zl as gB}from"./chunk-f02anz24.js";import{Jl as b5}from"./chunk-fryj3asn.js";import{Kl as F8,Ml as YB}from"./chunk-y67rmd3y.js";import{Rl as j8}from"./chunk-k1c0xd8r.js";function z6($){return typeof $==="function"&&$.prototype!==void 0}var N2=Symbol.for("gemi.HttpResponse"),BV=new Set([301,302,303,307,308]);class F1{kind;body;status;headers;[N2]=!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 P2(J,"json"),new F1("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 F1.json({error:Z},{...J,status:$})}static redirect($,Z={}){let J=Z.status??303;if(!BV.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 F1("empty",void 0,J,Y)}static noContent($={}){return new F1("empty",null,204,new Headers($.headers))}static text($,Z={}){let J=Z.status??200;return P2(J,"text"),new F1("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 P2($,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 r1($){return typeof $==="object"&&$!==null&&$[N2]===!0}function VV($,Z,J={}){return F1.error($,Z,J)}function e0($){return typeof $==="string"?[$]:$}function X6($,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 FV($){return"total"in $&&"partial"in $&&"body"in $}function _2(){return new Response("Not found",{status:404,headers:{"X-Content-Type-Options":"nosniff"}})}function Q3($){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 UV($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(FV($))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 _2();let J=await UV($),{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 _2()}let{range:G}=Z;if(G){if(z<=0)return Q3(Math.max(z,0));if(!X){if(W instanceof Blob){let B=N8(G,z);if(!B)return Q3(z);W=W.slice(B.start,B.end+1),Y=B.start,j=B.end,X=!0}}}let Q=Boolean(G)&&X,V=Q?206:J.status,F=new Headers;if(F.set("Accept-Ranges","bytes"),F.set("Content-Type",J.type||"application/octet-stream"),F.set("X-Content-Type-Options","nosniff"),Q)F.set("Content-Range",_8(Y,j,z)),F.set("Content-Length",String(j-Y+1));else if(z>=0)F.set("Content-Length",String(z));if(J.name)F.set("Content-Disposition",X6(J.name,J.download));if(J.etag)F.set("ETag",J.etag);if(J.lastModified)F.set("Last-Modified",J.lastModified.toUTCString());for(let[B,U]of Object.entries(J.extraHeaders))F.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:V,headers:F})}return new Response(W,{status:V,headers:F})}class FZ extends K0{limit;constructor($){super("The request body is too large.",{status:413});this.limit=$}}var I2={b:1,k:1024,kb:1024,m:1048576,mb:1048576,g:1073741824,gb:1073741824};function V3($){if(typeof $==="number"){if(Number.isFinite($)&&$>=0)return Math.floor($);if($===1/0)return 1/0}else{let Z=$.trim().toLowerCase();if(Z==="none"||Z==="off")return 1/0;let J=/^(\d+(?:\.\d+)?)\s*([a-z]*)$/.exec(Z);if(J&&(J[2]===""||(J[2]in I2)))return Math.floor(Number(J[1])*(I2[J[2]]??1))}throw Error(`Invalid body limit ${JSON.stringify($)}. Use a byte count or a size such as "64kb", "1mb" or "none".`)}var B3=new WeakMap;function C2($){return B3.has($)}function A2($){return B3.get($)?.limit??null}function S2($){let Z=B3.get($);return Z?Z.read>Z.limit:!1}function OV($){let Z=$.headers.get("Content-Length");if(Z===null||!/^\s*\d+\s*$/.test(Z))return null;return Number(Z)}function A8($,Z){let J=OV($);if(J!==null&&J>Z)throw new FZ(Z)}function G6($,Z,J={}){let W=B3.get($);if(W)W.limit=Z;else{let Y={limit:Z,read:0,stream:void 0,used:!1};B3.set($,Y),LV($,Y)}if(J.checkDeclared!==!1)A8($,Z)}function DV($){return Reflect.get(Object.getPrototypeOf($),"body",$)??null}function C8($,Z){if(Z.stream!==void 0)return Z.stream;let J=DV($);if(!J)return Z.stream=null;let W;return Z.stream=new ReadableStream({async pull(Y){W??=J.getReader();let{done:j,value:z}=await W.read();if(j){Y.close();return}if(Z.read+=z.byteLength,Z.read>Z.limit){let X=new FZ(Z.limit);Y.error(X),W.cancel(X).catch(()=>{});return}Y.enqueue(z)},cancel(Y){return W?W.cancel(Y):J.cancel(Y)}},{highWaterMark:0}),Z.stream}async function VZ($,Z){if(A8($,Z.limit),Z.used||Z.stream?.locked)throw TypeError("Body already used");Z.used=!0;let J=C8($,Z);if(!J)return new Uint8Array(0);let W=J.getReader(),Y=[],j=0;for(;;){let{done:G,value:Q}=await W.read();if(G)break;Y.push(Q),j+=Q.byteLength}let z=new Uint8Array(j),X=0;for(let G of Y)z.set(G,X),X+=G.byteLength;return z}function x2($){return $.headers.get("Content-Type")??""}function LV($,Z){let J=(W,Y)=>Object.defineProperty($,W,{configurable:!0,...Y});J("body",{get:()=>C8($,Z)}),J("bodyUsed",{get:()=>Z.used||Boolean(Z.stream?.locked)||Reflect.get(Object.getPrototypeOf($),"bodyUsed",$)}),J("bytes",{value:()=>VZ($,Z)}),J("arrayBuffer",{value:async()=>{let W=await VZ($,Z);return W.buffer.slice(W.byteOffset,W.byteOffset+W.byteLength)}}),J("text",{value:async()=>new TextDecoder().decode(await VZ($,Z))}),J("json",{value:async()=>JSON.parse(new TextDecoder().decode(await VZ($,Z)))}),J("blob",{value:async()=>new Blob([await VZ($,Z)],{type:x2($)})}),J("formData",{value:async()=>new Response(await VZ($,Z),{headers:{"Content-Type":x2($)}}).formData()}),J("clone",{value:()=>{A8($,Z.limit);let W=C8($,Z),Y=null;if(W){let[j,z]=W.tee();Z.stream=j,Y=z}return new Request($.url,{method:$.method,headers:$.headers,body:Y,signal:$.signal,duplex:"half"})}})}function HV($){return z6($)}function E2($,Z){if($.length===0)return $();return $(Z??new C)}class s{method;handler;methodName;__internal_brand="RouteHandler";middlewares=[];constructor($,Z,J){this.method=$;this.handler=Z;this.methodName=J;this.handler=Z,this.methodName=J,this.method=$}get source(){if(!HV(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 E2(Z[this.methodName].bind(Z),$)}return E2(this.handler,$)}middleware($){return this.middlewares=e0($),this}}class k2{url;headers;__internal_brand="ProxyHandler";middlewares=[];constructor($,Z){this.url=$;this.headers=Z}middleware($){return this.middlewares=e0($),this}async run(){let $=new C,Z=$.headers.toJSON();for(let J of R2($.rawRequest))delete Z[J];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(J){if(S2($.rawRequest))throw new FZ(A2($.rawRequest));throw J}}}class w2{constructor(...$){return new s(...$)}}class f2 extends s{__internal_brand="StreamHandler";async run($){let Z=P.getStore(),J=Z?.req?.rawRequest,W=S8(J?.headers.get("Range"));if(Z)Z.rangeRequest=W;try{let Y=await super.run($);if(r1(Y))return Y;return await x8(Y,{range:W,method:J?.method})}catch(Y){if(Y instanceof E8)return Q3(Y.total);throw Y}finally{if(Z)Z.rangeRequest=null}}}class q2{constructor(...$){return new f2(...$)}}class v2{__internal_brand="ResourceRoutes";first;second;constructor($){this.first={get:new s("GET",$,"list"),post:new s("POST",$,"store")},this.second={get:new s("GET",$,"show"),put:new s("PUT",$,"update"),delete:new s("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 C0{static __brand="ApiRouter";routes={};middlewares=[];middleware($){}get($,Z){return new s("GET",$,Z)}post($,Z){return new s("POST",$,Z)}put($,Z){return new s("PUT",$,Z)}patch($,Z){return new s("PATCH",$,Z)}delete($,Z){return new s("DELETE",$,Z)}resource($){return new v2($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${b2($)}.`);return MV($)}voice($){if($.kind!=="agent-controller")throw TypeError(`this.voice() takes an AgentController class, and got ${b2($)}.`);return KV($)}file($,Z){return new w2("GET",$,Z)}stream($,Z){return new q2("GET",$,Z)}proxy($,Z={}){return new k2($,Z)}}function b2($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function MV($){let Z={stream:new s("POST",$,"stream"),attach:new s("POST",$,"attach"),watch:new s("POST",$,"watch"),stop:new s("POST",$,"stop"),upload:new s("POST",$,"upload")};return class extends C0{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 KV($){let Z={start:new s("POST",$,"voiceStart"),update:new s("PATCH",$,"voiceUpdate"),end:new s("DELETE",$,"voiceEnd")};return class extends C0{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 e1="access_token";function E$($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function Q6($,Z){let J=E$(Z);if(!J)return null;return(await $.getSession(J,Z.headers.get("User-Agent")))?.user??null}var TV=/^[A-Za-z0-9_-]+$/,PV=/^:[A-Za-z_][A-Za-z0-9_]*$/,g2=/^[A-Za-z0-9_-]{1,128}$/,NV=/^[A-Za-z0-9_.:-]+$/;class u extends Error{constructor($){super($);this.name="InvalidChannelError"}}function y2($){return typeof $==="object"&&$!==null&&typeof $.topic==="string"}function UZ($){if(typeof $!=="string"||$.length===0)throw new u("A channel pattern must be a non-empty string.");if($.length>255)throw new u(`The channel pattern "${$.slice(0,40)}\u2026" is longer than ${"255"} characters.`);let Z=$.split("."),J=new Set;for(let W of Z){if(PV.test(W)){let Y=W.slice(1);if(J.has(Y))throw new u(`The channel pattern "${$}" names the param "${Y}" twice.`);J.add(Y);continue}if(W.startsWith("__"))throw new u(`The channel "${$}" has the segment "${W}". Segments starting with "__" are reserved for gemi (driver control messages).`);if(!TV.test(W))throw new u(`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 F3($,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 u(`The channel "${$}" needs the param "${z}".`);let G=typeof X==="number"&&Number.isFinite(X)?String(X):X;if(typeof G!=="string"||!g2.test(G))throw new u(`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 u(`The channel "${$}" has no param "${j}".`);if(Y.length>255)throw new u(`The topic built from "${$}" is longer than 255 characters.`);return Y}function b8($){if(UZ($).some((J)=>J.startsWith(":")))throw new u(`"${$}" is a pattern, not a topic: pass its params, as in Broadcast.to("${$}", { ... }).`);return $}function m2($){if(typeof $!=="string"||$.length===0||$.length>64||!NV.test($))throw new u(`The event name "${String($).slice(0,40)}" must be 1 to 64 letters, digits, "_", "-", "." or ":".`);return $}function h2($,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(":")&&g2.test(W[j]))}var U0="user";function OZ($){let Z=typeof $==="object"&&$!==null?$.id:$;return F3(`${U0}.:id`,{id:Z})}class J0{req;static runsOnRefusal=!1;config={};constructor($){this.req=$}run(...$){return{}}static configure($){let Z=this;return class extends Z{config=$}}}class B6 extends J0{run($){let Z=$??this.config.limit;if(Z===void 0||Z==="")throw Error('`body-limit` needs a size, as in "body-limit:64kb".');return G6(this.req.rawRequest,V3(Z)),{}}}function _V($){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}var IV={"body-limit":B6};class $${config;static token="middleware";defaultBodyLimit;constructor($){this.config=$;this.defaultBodyLimit=$.bodyLimit===null||$.bodyLimit===void 0?null:V3($.bodyLimit)}get aliases(){return{...IV,...this.config.aliases}}applyDefaultBodyLimit($){if(this.defaultBodyLimit!==null&&!C2($))G6($,this.defaultBodyLimit,{checkDeclared:!1})}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 C,J=this.aliases,W=[];for(let[Y,j]of _V($).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:p2(z)})}}else if(z6(Y)){let z=new Y(Z);W.push({run:z.run.bind(z),runsOnRefusal:p2(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 xV(W.slice(j+1)),z}return Y})()}}function p2($){return $?.runsOnRefusal===!0}async function xV($){for(let Z of $){if(!Z.runsOnRefusal)continue;try{await Z.run()}catch(J){console.error(J)}}}class V6{visibility;authorizer;middlewares=[];constructor($,Z){this.visibility=$;this.authorizer=Z}middleware($){return this.middlewares=[...this.middlewares,...e0($)],this}events(...$){return this}}class l2{static __brand="ChannelRouter";channels={};public(){return new V6("public")}private($){return new V6("private",$)}async authorize($,Z,J={},W={}){try{EV(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(!i2(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=F3(Z,J??{})}catch(G){if(G instanceof u)return{ok:!1,code:"invalid_params"};throw G}let z=Object.fromEntries(Object.entries(J??{}).map(([G,Q])=>[G,String(Q)])),X=new C($,z,"api",Z);return P.exit(()=>F6.exit(()=>P.run(X,async()=>{let G=P.getStore();try{if(Y.middlewares.length>0)await M($$).runMiddleware(Y.middlewares);if(Z===U0){let Q=await c2(X);if(!Q)return{ok:!1,code:"denied"};if(j=OZ(Q),Y.visibility==="private"&&Y.authorizer){if(await d2(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 d2(Y.authorizer,X,z):await c2(X)!==null)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}catch(Q){if(SV(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 CV($,Z,J={},W={}){let Y=typeof $==="function"?new $:$;s2(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 i2($){let Z=$?.visibility;return typeof $==="object"&&$!==null&&Array.isArray($.middlewares)&&(Z==="public"||Z==="private")}async function c2($){if(!P.getStore().user&&E$($)===null)return null;try{return await q0.user()}catch(Z){if(Z?.name==="AuthenticationError")return null;throw Z}}function d2($,Z,J){if(AV($))return new $().authorize(Z,J);return $(Z,J)}function AV($){return typeof $==="function"&&typeof $.prototype?.authorize==="function"}function SV($){return $?.kind===Z$||J$($)||b$($)}var u2=new WeakSet;function EV($){if(u2.has($))return;s2($),u2.add($)}function s2($){let Z=Object.entries($.channels),J=[];for(let[W,Y]of Z){if(!i2(Y))throw new u(`The channel "${W}" is not declared with this.public() or this.private().`);let j=UZ(W);if(j[0].startsWith(":"))throw new u(`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 u(`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 u(`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(bV(J[W].segments,J[Y].segments))throw new u(`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 bV($,Z){if($.length!==Z.length)return!1;return $.every((J,W)=>J===Z[W]||J.startsWith(":")||Z[W].startsWith(":"))}class R8{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,J){this.as=$;this.input=Z;this.bind=J}}class U6{method;url;meta;__internal_brand="McpRoute";constructor($,Z,J){this.method=$;this.url=Z;this.meta=J}}class k8{tool;meta;__internal_brand="McpTool";constructor($,Z){this.tool=$;this.meta=Z}}function RV($){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 kV($,Z){let J=RV($);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 n2{static __brand="McpRouter";routes={};scopes;param($){return new R8($.as,$.input,$.bind)}fromTool($,Z={}){return new k8($,Z)}fromApiRoute($,Z,J){return new U6($,Z,J)}fromApiRouteFor($,Z,J){let{name:W,audiences:Y,description:j,params:z,files:X,...G}=J,Q=`McpRouter.fromApiRouteFor("${$}", "${Z}")`,V=Object.keys(Y??{});if(V.length===0)throw Error(`${Q}: declare at least one audience.`);let F={},B=new Map;for(let U of V){let{name:D,casing:O,description:L,params:H,files:T,...K}=Y[U],I=D??(O?kV(W,O):W);if(B.has(I))throw Error(`${Q}: the audiences "${B.get(I)}" and "${U}" are both named "${I}". Give one its own name or casing.`);B.set(I,U);let b=typeof L==="function"?j===void 0?void 0:L(j):L??j;if(typeof b!=="string")throw Error(`${Q}: the audience "${U}" has no description, and there is no shared one.`);let S={...G,...K,description:b};if(z||H)S.params={...z,...H};if(X||T)S.files={...X,...T};F[I]=new U6($,Z,S)}return F}}function O0($,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 w8 extends K0{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 E1{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 w8([O0($,Y)||"/",X.toString()].filter(Boolean).join("?"),z??(j?301:307))}static external($,Z=307){throw new w8($,Z)}}class o2{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 E1.to(J,{permanent:W,status:Y}),{}}middleware($){return this.middlewares=e0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function f8($,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",X6(Y,z));return new Response(W instanceof Blob?W.stream():W,{status:X,headers:Z})}class a2{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=e0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}function t2($,Z){if(r1($))throw Error(`The handler of view "${Z}" returned an HttpResponse. HttpResponse is for api routes; a view handler returns its props.`);return $}class r2{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=t2(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}middleware($){return this.middlewares=e0($),this}static($={}){return this.staticOptions={...$},this}feature($){return this.featureGates=[...this.featureGates,$],this}}class e2{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=t2(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=e0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class b1{middlewares=[];featureGates=[];routes={};view($,Z){return new r2($,Z)}file($){return new a2($)}redirect($){return new o2($)}layout($,Z,J){return new e2($,Z,J)}}function wV($){return $}function fV(){return{aliases:{},global:[],bodyLimit:null}}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 DZ($){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 qV($,Z=!0){let J=new URL($.rawRequest.url),W=J.pathname.replace(/\.(json|og)$/,""),[,Y,...j]=W.split("/");if(M(c).supportedLocales.includes(Y))W=`/${j.join("/")}`;return Z?`${W}${J.search}`:W}function vV($,Z){let J=(W)=>W.replace(/\/+$/,"")||"/";return J($)===J(Z)}function O6($,Z){let J=Z||M(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=qV($,!W);if(W||!vV(new URL(j,Y).pathname,Y.pathname))Y.searchParams.set(l0,j)}return W?Y.href:`${Y.pathname}${Y.search}`}class $9 extends J0{async run($){let Z=P.getStore(),J=Z.req;if(Z.user)return{};let W=await Q6(M(E),J);if(!W)throw new R$({redirectTo:O6(J,$)});return Z.setUser(W),{}}}var g8="gemi_same_site",v8="private, no-cache, no-store, max-age=0, must-revalidate";class D6 extends J0{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(g8))return{};if(E$(Z))return{};let Y=J.headers.get("Sec-Fetch-Site");if(Y&&Y!=="cross-site")return{};throw W.searchParams.set(g8,"1"),new Z9(`${W.pathname}${W.search}`)}}class Z9 extends K0{location;constructor($){super("Same-site bounce");this.location=$;this.name="SameSiteBounce";let Z=gV($),J={"Content-Type":"text/html; charset=utf-8","Cache-Control":v8,"Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex"};this.payload={api:{status:401,data:{},headers:{"Cache-Control":v8}},viewData:{status:200,data:{},headers:{"Cache-Control":v8},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 gV($){return $.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}class J9 extends J0{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 W9={"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 Y9 extends J0{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={...W9,...this.config.origins[Z]};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={...W9,...this.config.origins["*"]};delete J["Access-Control-Allow-Credentials"];for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}return{}}}var yV="Rate limit exceeded";class Y$ extends K0{result;retryAfter;constructor($,Z=yV){super(Z);this.result=$;this.retryAfter=$?.retryAfter;let J={"Content-Type":"application/json",...$?y8($):{}};this.payload={api:{status:429,data:{error:{...W$("rate_limit",Z,429),...$?{retryAfter:$.retryAfter}:{}}},headers:J},view:{error:{message:Z},status:429,headers:J}}}}function y8($){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 O1{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(j9("window",W),j9("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 Y$(W,typeof J==="function"?J(W):J);return W}}function j9($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}import{isIP as m8}from"net";function k$($){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 m8(j)===6?j:null}if(m8(Z))return Z;let J=/^(\d{1,3}(?:\.\d{1,3}){3}):\d{1,5}$/.exec(Z);return J&&m8(J[1])===4?J[1]:null}class Q9 extends J0{async run($,Z){let J=mV();if(!J)return{};let W=await J.consume(this.key(),{limit:z9($)??this.config.limit,window:z9(Z)??this.config.window});if(this.config.headers!==!1){let Y=this.req.ctx?.();if(Y)for(let[j,z]of Object.entries(y8(W)))Y.setHeaders(j,z)}if(!W.allowed)throw new Y$(W);return{}}key(){if(this.config.key)return this.config.key(this.req);let $=X9(this.req.rawRequest);if($)return`mcp:${$.via}:${$.id}:${this.req.routePath??"*"}`;return`${LZ(this.req)}:${this.req.routePath??"*"}`}}function mV(){try{let $=M();return $.bound(O1)?$.make(O1):null}catch{return null}}function LZ($){let Z=G9($.rawRequest);if(Z!==void 0)return Z;let J=$.headers.get("x-forwarded-for");if(J){let[W]=J.split(",");if(W?.trim())return k$(W)??W.trim()}return $.headers.get("x-real-ip")?.trim()||"unknown"}function z9($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}class V9 extends J0{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new h8;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new h8;return{}}}class h8 extends K0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:B9("csrf","Invalid CSRF token",403)}},view:{}}}class F9{policiesList={};constructor(){let $=this.register();for(let Z of $){let J=new Z;this.policiesList[Z.name]=J}}register(){return[]}}class U9{all($,Z){return!0}}class p8{options;param;refuse;answers=new WeakMap;constructor($){this.options=$;this.param=$.param,this.refuse=$.refuse??"not_found"}refusal(){return this.refuse==="forbidden"?new HZ: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 C,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 J0{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 HZ:$ instanceof L6}}function hV($){return new p8($)}async function K6($,Z,J=!1){if(!$.body)return new Uint8Array;let[W,Y]=await eV($.body),z=W.length>=2&&W[0]===31&&W[1]===139?Y.pipeThrough(new DecompressionStream("gzip")):Y;return rV(z,Z,J,$.url)}async function rV($,Z,J,W){let Y=$.getReader(),j=[],z=0;try{for(;;){let{done:Q,value:V}=await Y.read();if(Q)break;if(z+V.byteLength>Z){if(!J)throw new M6(W,Z);j.push(V.subarray(0,Z-z)),z=Z;break}j.push(V),z+=V.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 eV($){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 T6($){return new TextDecoder("utf-8").decode($)}var $F={"&":"&","<":"<",">":">",'"':""","'":"'"};function w$($){return $.replace(/[&<>"']/g,(Z)=>$F[Z])}var ZF={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function c8($){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 ZF[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 d8($){let Z=$.indexOf(":");return(Z===-1?$:$.slice(Z+1)).toLowerCase()}function O9($,Z){let J=$.length,W=0;while(W<J){if(Z.stopped?.())return;let Y=$.indexOf("<",W);if(Y===-1){Z.text(c8($.slice(W)));return}if(Y>W)Z.text(c8($.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(d8($.slice(Y+2,j).trim())),W=j+1}else{let j=JF($,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=d8(z.slice(0,G));if(Q){if(Z.open(Q,WF(z.slice(G)),X),X)Z.close(Q)}W=j+1}}}function JF($,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 WF($){let Z={},J=/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;for(let W of $.matchAll(J))Z[d8(W[1])]=c8(W[2]??W[3]??"");return Z}class z0 extends Error{url;status;constructor($,Z=null,J=null){super($);this.url=Z;this.status=J;this.name="SitemapError"}}var K9="http://www.sitemaps.org/schemas/sitemap/0.9",YF="http://www.w3.org/1999/xhtml",i8=`<?xml version="1.0" encoding="UTF-8"?>
|
|
3
3
|
`,D9=`<urlset xmlns="${K9}" xmlns:xhtml="${YF}">
|
|
4
4
|
`,L9=`</urlset>
|
|
5
5
|
`,f$=50000,U3=52428800,H9=2048,jF=new Set(["always","hourly","daily","weekly","monthly","yearly","never"]),zF=/^\d{4}(-\d{2}(-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2}))?)?)?$/,XF="application/xml; charset=utf-8",M9=new TextEncoder;function s8($,Z){let J;try{J=new URL($)}catch{throw new z0(`Sitemap: ${Z} "${$}" is not an absolute URL.`)}if(J.protocol!=="http:"&&J.protocol!=="https:")throw new z0(`Sitemap: ${Z} "${$}" is not an http(s) URL.`);let W=J.href;if(W.length>H9)throw new z0(`Sitemap: ${Z} is over ${H9} characters: "${W.slice(0,80)}\u2026".`);return W}function T9($,Z){if($ instanceof Date){if(Number.isNaN($.getTime()))throw new z0(`Sitemap: lastmod of ${Z} is an invalid Date.`);return $.toISOString()}if(!zF.test($))throw new z0(`Sitemap: lastmod "${$}" of ${Z} is not a W3C datetime (e.g. "2026-10-07" or "2026-10-07T12:00:00Z").`);return $}function GF($){let Z=s8($.loc,"loc"),J=`<url><loc>${w$(Z)}</loc>`;if($.lastmod!=null)J+=`<lastmod>${w$(T9($.lastmod,Z))}</lastmod>`;if($.changefreq!=null){if(!jF.has($.changefreq))throw new z0(`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 z0(`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 z0(`Sitemap: an alternate of ${Z} has no hrefLang.`);let j=s8(W.href,`alternate href of ${Z}`);J+=`<xhtml:link rel="alternate" hreflang="${w$(Y)}" href="${w$(j)}"/>`}return`${J}</url>
|
|
@@ -10,7 +10,7 @@ ${Z}</sitemapindex>
|
|
|
10
10
|
`)));return A9(G,{url:j.url})}function n8($){return $===void 0?[]:typeof $==="string"?[$]:$}function P6($,Z){if(/[\r\n]/.test(Z))throw TypeError(`Robots: the ${$} value ${JSON.stringify(Z)} has a line break in it.`);return`${$}: ${Z}
|
|
11
11
|
`}function S9($){let Z=[];for(let W of $.rules??[]){let Y=n8(W.userAgent);if(Y.length===0)throw TypeError("Robots: a rule needs at least one userAgent.");let j=Y.map((X)=>P6("User-agent",X)).join(""),z=[...n8(W.allow).map((X)=>["Allow",X]),...n8(W.disallow).map((X)=>["Disallow",X])];for(let[X,G]of z){if(!G.startsWith("/")&&!G.startsWith("*"))throw TypeError(`Robots: ${X} "${G}" must start with "/" or "*".`);j+=P6(X,G)}if(z.length===0)j+=`Disallow:
|
|
12
12
|
`;if(W.crawlDelay!==void 0){if(!Number.isFinite(W.crawlDelay)||W.crawlDelay<0)throw TypeError(`Robots: crawlDelay ${W.crawlDelay} is not a number of seconds.`);j+=P6("Crawl-delay",String(W.crawlDelay))}Z.push(j)}let J=($.sitemaps??[]).map((W)=>{let Y;try{Y=new URL(W)}catch{throw TypeError(`Robots: sitemap "${W}" is not an absolute URL.`)}return P6("Sitemap",Y.href)});if(J.length>0)Z.push(J.join(""));return Z.join(`
|
|
13
|
-
`)}function MF($,Z={}){let J=new Headers(Z.headers);if(!J.has("content-type"))J.set("content-type","text/plain; charset=utf-8");return new Response(S9($),{status:200,headers:J})}var E9={response:MF,text:S9,parse:A9,fetch:HF};import{createHmac as b9,randomBytes as KF}from"crypto";var a8="v2.";function t8($){return $.startsWith(a8)}function KZ(){let $=process.env.SECRET;if(!$)throw Error("Signing in needs a secret to mint session tokens with. Set SECRET in the environment.");return $}function R9($){let Z=KF(16).toString("hex"),J=b9("sha256",KZ()).update(`${$}:${Z}`).digest("hex");return`${a8}${J}`}function N6($,Z){let J=b9("sha256",KZ()).update(`legacy-session:${Z}:${$}`).digest("hex");return`${a8}${J}`}import{createHash as NF,createHmac as _F,randomInt as IF,timingSafeEqual as f9}from"crypto";function k9($,Z){return Math.floor($/Z)*Z}function TF($,Z){if(Z<=0)return 0;return Math.min(1,Math.max(0,(Z-$)/Z))}function r8($,Z,J,W){return Z*TF(J,W)+$}function PF($){let{current:Z,previous:J,elapsed:W,window:Y,limit:j,cost:z}=$,X=j-z;if(X<0)return Y;let G=Math.max(0,Y-W);if(J>0){let V=Y*(1-(X-Z)/J);if(V<=Y)return Math.max(0,Math.ceil(V-W))}if(Z<=X)return G;if(Z<=0)return G;let Q=Y*(1-X/Z);return G+Math.max(0,Math.ceil(Q))}function w9($){let{allowed:Z,current:J,previous:W,now:Y,elapsed:j,window:z,limit:X,cost:G}=$;if(Z){let V=r8(J,W,j,z);return{allowed:!0,limit:X,remaining:Math.max(0,Math.floor(X-V)),resetAt:Y-j+z,retryAfter:0}}let Q=PF({current:J,previous:W,elapsed:j,window:z,limit:X,cost:G});return{allowed:!1,limit:X,remaining:0,resetAt:Y+Q,retryAfter:Q}}class e8{}class $7 extends e8{buckets=new Map;maxKeys;constructor($={}){super();this.maxKeys=Math.max(1,$.maxKeys??1e5)}consume($){let{key:Z,limit:J,window:W}=$,Y=$.cost??1,j=Date.now(),z=k9(j,W),X=j-z,G=this.roll(Z,W,z);G.limit=J;let V=r8(G.current,G.previous,X,W)+Y<=J;if(V)G.current+=Y;if(this.buckets.delete(Z),this.buckets.set(Z,G),this.buckets.size>this.maxKeys)this.evict(j);return w9({allowed:V,current:G.current,previous:G.previous,now:j,elapsed:X,window:W,limit:J,cost:Y})}clear(){this.buckets.clear()}get size(){return this.buckets.size}roll($,Z,J){let W=this.buckets.get($);if(!W||W.window!==Z)return{window:Z,limit:0,windowStart:J,current:0,previous:0};if(W.windowStart===J)return W;if(W.windowStart+Z===J)return W.previous=W.current,W.current=0,W.windowStart=J,W;return W.previous=0,W.current=0,W.windowStart=J,W}evict($){for(let[W,Y]of this.buckets)if($-Y.windowStart>=Y.window*2)this.buckets.delete(W);let Z=this.maxKeys-Math.floor(this.maxKeys/10);if(this.buckets.size<=Z)return;let J=[...this.buckets].map(([W,Y],j)=>({key:W,order:j,spent:Y.limit>0?(Y.current+Y.previous)/Y.limit:0}));J.sort((W,Y)=>W.spent-Y.spent||W.order-Y.order);for(let{key:W}of J){if(this.buckets.size<=Z)break;this.buckets.delete(W)}}}var v9="h1.";function _6($,Z,J){let W=_F("sha256",KZ()).update(`gemi:one-time:${$}:${Z}:${J}`).digest("hex");return`${v9}${W}`}function TZ($,Z,J,W){let Y=typeof W==="string"?W:"",j=typeof J==="string"?J:"",z=j.startsWith(v9),X=_6($,Z,Y),G=Buffer.from(z?X:Y),Q=Buffer.from(j);if(G.length!==Q.length||Y===""||j==="")return f9(G,G),!1;return f9(G,Q)}function g9($){let Z="";for(let J=0;J<$;J++)Z+=String(IF(0,10));return Z}var y9=320;function q$($){if(typeof $!=="string")return null;let Z=$.trim();if(Z===""||Z.length>y9)return null;return Z.toLowerCase()}function I6($){if(typeof $!=="string")return null;let Z=$.trim();if(Z.length>y9)return null;let J=Z.toLowerCase();if(J.length<3||J.length>254||!/^[^\s@]+@[^\s@]+$/.test(J))return null;return J}var q9=null;function m9(){try{let $=M();if(typeof $?.bound==="function"&&$.bound(O1))return $.make(O1)}catch{}return q9??=new O1({driver:new $7,limit:1000,window:60}),q9}function Z7($){return $.length<=64?$:`sha256:${NF("sha256").update($).digest("hex")}`}function xF($){return $==="request"||$==="verify"||$==="link"?`auth:code-${$}`:`auth:${$}`}async function v$($,Z,J,W,Y,j){let z=m9(),X=[["perIp",`ip:${Z7(LZ(J))}`,W.perIp]];if(Z!==null)X.push(["perEmail",`email:${Z7(Z)}`,W.perEmail]);for(let[G,Q,V]of X){if(!V)continue;let F=Y?await Y({req:J,scope:$,limit:G}):void 0,B=xF($),U=F?`${B}:p:${Z7(String(F))}:${Q}`:`${B}:${Q}`,[D,O]=V,L=await z.consume(U,{limit:D,window:O});if(!L.allowed)throw await j?.(G),new Y$(L)}}async function h9($,Z,J,W=10){let Y=Math.max(86400,Math.ceil(W*60*(J+1)));return(await m9().consume(`auth:code-attempt:${$}:${Z}`,{limit:J,window:Y})).allowed}import{randomBytes as W7}from"crypto";class J7 extends C{schema={name:{string:"Invalid name",required:"Name is required","min:2":"Name must be at least 3 characters"},email:{string:"Invalid email",required:"Email is required",email:"Invalid email"},password:{"min:8":"Password must be at least 9 characters"}}}async function k1($,Z){if(typeof $==="function")return await $({req:Z})===!0;return Boolean($)}function Y7($){return $===!0||typeof $==="function"}function j7($={}){return{signIn:{perEmail:$.signIn?.perEmail??[10,900],perIp:$.signIn?.perIp??[50,900]},signUp:{perEmail:$.signUp?.perEmail??!1,perIp:$.signUp?.perIp??[10,3600]},forgot:{perEmail:$.forgot?.perEmail??[5,900],perIp:$.forgot?.perIp??[20,900]},reset:{perEmail:$.reset?.perEmail??!1,perIp:$.reset?.perIp??[20,900]}}}function D3($,Z,J,W=1/0){if(!Number.isInteger(Z)||Z<J||Z>W){let Y=W===1/0?`an integer of at least ${J}`:`an integer from ${J} to ${W}`;throw Error(`auth.emailCode.${$} must be ${Y}, got ${Z}`)}}function CF($={}){let Z=[["password",$?.password],["magicLink",$?.magicLink],["verifyEmail",$?.verifyEmail],["emailCode.enabled",$?.emailCode?.enabled]];for(let[J,W]of Z)if(W!==void 0&&typeof W!=="boolean"&&typeof W!=="function")throw Error(`auth.${J} must be true, false or a function of the request, got ${JSON.stringify(W)}`)}function z7($={}){let Z=$.length??6,J=$.expiresInMinutes??10,W=$.linkExpiresInMinutes??10080,Y=$.maxAttempts??5,j=$.activeCodes??1;return D3("length",Z,4,12),D3("expiresInMinutes",J,1),D3("linkExpiresInMinutes",W,1),D3("maxAttempts",Y,1),D3("activeCodes",j,1,5),{enabled:$.enabled??!1,createUser:$.createUser??!1,length:Z,expiresInMinutes:J,linkExpiresInMinutes:W,maxAttempts:Y,activeCodes:j,requestLimit:{perEmail:$.requestLimit?.perEmail??[5,900],perIp:$.requestLimit?.perIp??[20,900]},verifyLimit:{perEmail:$.verifyLimit?.perEmail??[10,900],perIp:$.verifyLimit?.perIp??[50,900]},uniformMagicLinkResponse:$.uniformMagicLinkResponse??!1,send:$.send??(({email:z,code:X})=>{if(Bun.env.NODE_ENV!=="production")console.info(`[gemi] email code for ${z}: ${X} (set auth.emailCode.send to deliver it)`)})}}async function AF($,Z){if(typeof Z!=="string"||Z==="")return!1;try{return await Bun.password.verify($,Z)}catch{return!1}}function p9($){if(!$)return null;if(typeof $.getRedirectUrl==="function")return{provider:$};let{provider:Z,feature:J,enabled:W}=$;return{provider:Z,...J!==void 0?{feature:J}:{},...W!==void 0?{enabled:W}:{}}}function c9($){for(let[Z,J]of Object.entries($??{})){if(typeof J?.getRedirectUrl==="function")continue;let W=J;if(typeof W?.provider?.getRedirectUrl!=="function")throw Error(`auth.oauthProviders.${Z} must be an OAuthProvider, or { provider, feature, enabled } with an OAuthProvider.`);if(W.enabled!==void 0&&typeof W.enabled!=="boolean"&&typeof W.enabled!=="function")throw Error(`auth.oauthProviders.${Z}.enabled must be true, false or a function of the request.`);if(W.feature!==void 0&&(typeof W.feature!=="string"||W.feature===""))throw Error(`auth.oauthProviders.${Z}.feature must be a feature key from app/features.`)}}function MP($){return $}function d9($={}){return CF($),{basePath:"/auth",verifyEmail:!0,password:!0,passwordLimits:j7($.passwordLimits),magicLink:!0,redirectPath:"/dashboard",signInPath:"/auth/sign-in",sessionExpiresInHours:24,sessionAbsoluteExpiresInHours:672,cookieDomain:null,migrateLegacySession:null,signUpRequest:J7,oauthProviders:{},oauthFailurePath:null,oauthCompleteProfilePath:null,connections:{},connectionStore:null,onConnected:()=>{},verifyPassword:AF,hashPassword:async(Z)=>await Bun.password.hash(Z),generateForgotPasswordToken:async()=>W7(32).toString("hex"),generateEmailVerificationToken:()=>{if($.verifyEmail===!1)return"";return W7(32).toString("hex")},generateMagicLinkToken:()=>W7(32).toString("hex"),extendSession:()=>({}),onUserCreated:async()=>{},onSignUp:()=>{},onSignIn:()=>{},onSignOut:()=>{},onForgotPassword:()=>{},onResetPassword:()=>{},onMagicLinkCreated:()=>{},emailCode:z7($.emailCode),generateCode:()=>{return},rateLimitKey:()=>{return},onAuthenticated:()=>{}}}var SF=new Set(["script","style","textarea","title","xmp","iframe","noembed","noframes","noscript"]),EF=new Set(["svg","math"]);function u9($){return $===32||$===9||$===10||$===12||$===13}function l9($){return $>=65&&$<=90||$>=97&&$<=122}function x6($){return $>=65&&$<=90?$+32:$}function i9(){let $="data",Z="",J=!1,W="",Y=0,j=0,z=!1,X=0,G=0,Q=()=>$==="data"&&X===0&&G===0,V=()=>{if(!J&&SF.has(Z)){$="rawText",W=`</${Z}`,Y=0,Z="";return}if($="data",Z==="template")if(J)X=Math.max(0,X-1);else X+=1;else if(EF.has(Z)){if(J)G=Math.max(0,G-1);else if(!z)G+=1}Z=""},F=(B)=>{switch($){case"data":if(B===60)$="tagOpen";return;case"tagOpen":if(B===33)$="bang",j=0;else if(B===47)$="endTagOpen";else if(l9(B))$="tagName",J=!1,z=!1,Z=String.fromCharCode(x6(B));else if(B===63)$="bogus";else if(B===60)$="tagOpen";else $="data";return;case"endTagOpen":if(l9(B))$="tagName",J=!0,z=!1,Z=String.fromCharCode(x6(B));else if(B===62)$="data";else $="bogus";return;case"tagName":if(u9(B)||B===47)$="inTag",z=B===47;else if(B===62)V();else Z+=String.fromCharCode(x6(B));return;case"inTag":if(B===62){V();return}if(z=B===47,B===34)$="attrDouble";else if(B===39)$="attrSingle";return;case"attrDouble":if(B===34)$="inTag";z=!1;return;case"attrSingle":if(B===39)$="inTag";z=!1;return;case"bang":if(B===45){if(j+=1,j===2)$="comment",j=0}else if(B===62)$="data";else $="bogus";return;case"bogus":if(B===62)$="data";return;case"comment":if(B===45)j=j<2?j+1:2;else if(B===62&&j>=2)$="data",j=0;else j=0;return;case"rawText":{if(Y<W.length){if(x6(B)===W.charCodeAt(Y))Y+=1;else Y=B===60?1:0;return}if(B===62)$="data",Z="";else if(u9(B)||B===47)$="inTag",Z="";else Y=B===60?1:0;return}}};return{scanToInsertionPoint(B){for(let U=0;U<B.length;U++){if(Q())return U;F(B[U])}return B.length},write(B){for(let U=0;U<B.length;U++)F(B[U])},isSafe:Q}}function i0($){let Z=JSON.stringify($);if(Z===void 0)return"undefined";return Z.replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function bF($){return`<script>(self.__GEMI_STREAM__=self.__GEMI_STREAM__||[]).push(${i0([$.path,$.variantKey,$.data])})</script>`}function RF($){return`<script>(self.__GEMI_DICT__=self.__GEMI_DICT__||[]).push(${i0([$.id,$.locale,$.strings])})</script>`}function X7($,Z,J={},W){let Y=new TextEncoder,j=[],z=!1,X=!1,G=()=>{if(X)return;X=!0,J.onClose?.()};Z.onSettle((D)=>{if(D.status!=="resolved")return;j.push(bF(D))}),W?.onUse((D)=>{j.push(RF(D))});let Q=$.getReader(),V=i9(),F=(D,O)=>{D.enqueue(O),J.onChunk?.(O)},B=(D)=>{while(j.length>0){let O=Y.encode(j.shift());V.write(O),F(D,O)}},U=(D,O)=>{if(j.length===0){V.write(O),F(D,O);return}let L=V.scanToInsertionPoint(O);if(L>0)F(D,O.subarray(0,L));if(V.isSafe())B(D);let H=O.subarray(L);if(H.length>0)V.write(H),F(D,H)};return new ReadableStream({async pull(D){let O;try{O=await Q.read()}catch(T){throw G(),T}let{done:L,value:H}=O;if(L){B(D),D.close(),G();return}if(!z){if(z=!0,V.write(H),F(D,H),J.onShell?.(),V.isSafe())B(D);return}U(D,H)},cancel(D){return G(),Q.cancel(D)}})}var kF=/bot|crawler|spider|crawling|slurp|bingpreview|mediapartners|headless|lighthouse|prerender|facebookexternalhit|whatsapp|telegram|discord|twitterbot|linkedinbot/i;function C6($){if(!$)return!1;return kF.test($)}async function n9($,Z=()=>{}){let J=P.getStore(),W=J?.req??null,Y=null;if(W?.rawRequest?.url)try{Y=new URL(W.rawRequest.url).pathname}catch{Y=null}return{user:J?.user??null,attributes:await wF($,Z),request:{path:Y,routePath:W?.routePath??null,locale:J?.locale??null},anonymousId:s9(),isBot:C6(W?.rawRequest?.headers?.get("user-agent")??null),now:new Date}}function o9($){return{user:$.user??null,attributes:$.attributes??{},request:{path:null,routePath:null,locale:null},anonymousId:$.subjectId??null,isBot:!1,now:new Date}}async function wF($,Z){if(!$.context)return{};try{let J=P.getStore();return await $.context(J?.req??null)??{}}catch(J){return Z(`The \`context\` hook in app/config/features.ts threw; evaluating with no attributes. ${J instanceof Error?J.message:String(J)}`),{}}}function a9($,Z){return`${$}:${Z}`}function G7($){let Z=new Bun.CryptoHasher("sha1").update($).digest("hex"),J=Number.parseInt(Z.slice(0,8),16);return Math.floor(J/4294967296*1e4)}function t9($,Z){if(Z>=100)return!0;if(Z<=0)return!1;return $<Math.round(Z*100)}function r9($,Z,J,W){if(W.unavailable)return{value:!1,reason:"unavailable"};if(W.active!==!0)return{value:!1,reason:"inactive"};if(Z.when){let j;try{j=Z.when(J)}catch(z){return W.warn?.(`The \`when\` for feature "${$}" threw; treating it as off. ${z instanceof Error?z.message:String(z)}`),{value:!1,reason:"error"}}if(typeof j==="boolean")return{value:j,reason:"attributed"}}if(Z.rollout===void 0)return{value:!0,reason:"on"};if(J.isBot)return{value:!1,reason:"bot"};let Y=qF($,Z,J,W.buckets);return t9(Y,Z.rollout)?{value:!0,reason:"rollout"}:{value:!1,reason:"excluded"}}function fF($){let Z=$.user?.publicId??$.user?.id;if(Z!==void 0&&Z!==null)return String(Z);return $.anonymousId??""}function qF($,Z,J,W){let Y=a9(Z.salt??$,fF(J));if(!W)return G7(Y);let j=W.get(Y);if(j!==void 0)return j;let z=G7(Y);return W.set(Y,z),z}class e9 extends Error{cause;kind="FeatureReloadFailed";constructor($){super(`Could not reload feature switches after a write, so the cached switches may still predate it: ${$ instanceof Error?$.message:String($)}`);this.cause=$}}class Q7{source;declared;ttlMs;warn;snapshot=null;inflight=null;lastFailureLoggedAt=0;generation=0;lastError=null;retryAfter=0;constructor($,Z,J,W=()=>{}){this.source=$;this.declared=Z;this.ttlMs=J;this.warn=W}async get(){let $=this.snapshot;if($&&Date.now()-$.loadedAt<this.ttlMs)return $;if($){if(Date.now()>=this.retryAfter)this.refresh().catch(()=>{});return $}return await this.refresh()}refresh(){return this.inflight??=this.load().finally(()=>{this.inflight=null}),this.inflight}async invalidate(){await this.inflight?.catch(()=>{});let $=this.generation,Z=await this.refresh();if(this.generation===$)throw new e9(this.lastError);return Z}peek(){return this.snapshot}async load(){try{let $=await this.source.load(),{active:Z,audit:J}=this.readRows($);return this.snapshot={active:Z,audit:J,loadedAt:Date.now(),unavailable:!1},this.generation++,this.lastError=null,this.retryAfter=0,this.snapshot}catch($){return this.handleFailure($)}}readRows($){let Z=new Map,J=new Map;for(let W of $??[]){let Y=typeof W?.key==="string"?W.key:null;if(!Y){this.warn("Ignoring a feature row with no `key`.");continue}if(!(Y in this.declared)){this.warn(`Feature row "${Y}" is not declared in app/features, so it is ignored. Delete the row, or declare the feature.`);continue}Z.set(Y,W.active===!0);let j=vF(W);if(j)J.set(Y,j)}return{active:Z,audit:J}}handleFailure($){let Z=$ instanceof Error?$.message:String($),J=Date.now();if(this.lastError=$,this.retryAfter=J+this.ttlMs,J-this.lastFailureLoggedAt>=this.ttlMs)this.lastFailureLoggedAt=J,this.warn(`Could not load feature switches: ${Z}`);if(this.snapshot)return this.snapshot;return this.snapshot={active:new Map,audit:new Map,loadedAt:J,unavailable:!0},this.snapshot}}function vF($){let Z={},J=$.updatedBy;if(typeof J==="string")Z.updatedBy=J;else if(J===null)Z.updatedBy=null;let W=$.updatedAt;if(W instanceof Date||typeof W==="string"||typeof W==="number"){let Y=W instanceof Date?W:new Date(W);if(!Number.isNaN(Y.getTime()))Z.updatedAt=Y}return"updatedBy"in Z||"updatedAt"in Z?Z:null}class gF{}class yF extends Error{modelName;kind="FeatureModelMissing";constructor($){super(`No "${$}" model is registered, so every feature stays off. Add the model to prisma/schema.prisma and export it from app/models \u2014 see docs/feature-flags.md.`);this.modelName=$}}class B7 extends Error{sourceName;kind="FeatureSourceReadOnly";constructor($){super(`The feature source (${$}) is read-only, so Features.set() cannot write to it. Change the switch where that source reads from, or give the source a write() method.`);this.sourceName=$}}class $Y extends Error{key;kind="UndeclaredFeature";constructor($){super(`"${$}" is not declared in app/features, so it cannot be switched. A row for it would be ignored \u2014 declare the feature first.`);this.key=$}}class ZY{manager;ctx;constructor($,Z){this.manager=$;this.ctx=Z}async enabled($){return(await this.explain($)).value}async explain($){return await this.manager.evaluateIn($,this.ctx,new Map)}async all(){return await this.manager.evaluateAllIn(this.ctx,new Map,{clientOnly:!1})}}class j${config;log;static token="features";store;declared;warnedAboutSize=!1;warnedAboutActor=!1;constructor($,Z=()=>{}){this.config=$;this.log=Z;this.declared=$.features??{},this.store=new Q7($.source,this.declared,Math.max(0,$.ttl)*1000,this.log)}declarations(){return this.declared}async list(){let{active:$,audit:Z,unavailable:J}=await this.switches();return{unavailable:J,features:Object.entries(this.declared).map(([W,Y])=>({key:W,describe:Y.describe,rollout:Y.rollout,targeted:Y.when!==void 0,serverOnly:Y.serverOnly,salt:Y.salt,active:$.get(W),...Z.get(W)}))}}async refresh(){if(!this.config.enabled)return;if(Object.keys(this.declared).length===0)return;await this.store.refresh()}async invalidate(){try{if(this.config.enabled&&Object.keys(this.declared).length>0)await this.store.invalidate()}finally{P.getStore()?.featureEvaluations?.clear()}}async set($,Z,J={}){if(typeof $!=="string"||!Object.hasOwn(this.declared,$))throw new $Y(String($));if(typeof Z!=="boolean")throw TypeError(`Features.set("${$}", \u2026) takes a boolean, not ${Z===null?"null":typeof Z}.`);let W=mF(J.actor),Y=this.config.source;if(typeof Y.write!=="function")throw new B7(Y.constructor?.name||"an anonymous source");let{actorRecorded:j}=await Y.write($,Z,{actor:W});if(W!==null&&!j&&!this.warnedAboutActor)this.warnedAboutActor=!0,this.log('Features.set() was given an actor, but the feature source has nowhere to record it. For the database source, add a nullable `updatedBy String?` column to the feature flag model to keep "last changed by".');await this.invalidate()}async enabled($){return(await this.explain($)).value}async explain($){let Z=await this.requestContext();return await this.evaluateIn($,Z,this.requestBuckets())}async all(){let $=await this.requestContext();return await this.evaluateAllIn($,this.requestBuckets(),{clientOnly:!1})}async forClient(){if(!this.config.enabled)return{};let $=await this.requestContext(),Z=await this.evaluateAllIn($,this.requestBuckets(),{clientOnly:!0});return this.warnIfOversized(Object.keys(Z).length),Z}for($){return new ZY(this,o9($))}async evaluateIn($,Z,J){let W=this.memoFor(Z),Y=W?.get($);if(Y)return Y;let j=this.declared[$];if(!j)return{value:!1,reason:"undeclared"};let{active:z,unavailable:X}=await this.switchFor($),G=r9($,j,Z,{active:z,unavailable:X,buckets:J,warn:this.log});return W?.set($,G),this.notify($,G,Z),G}async evaluateAllIn($,Z,J){let W={};for(let[Y,j]of Object.entries(this.declared)){if(J.clientOnly&&j.serverOnly)continue;W[Y]=(await this.evaluateIn(Y,$,Z)).value}return W}async switches(){if(!this.config.enabled||Object.keys(this.declared).length===0)return{active:new Map,audit:new Map,unavailable:!1};let $=await this.store.get();return{active:$.active,audit:$.audit,unavailable:$.unavailable}}async switchFor($){if(!this.config.enabled)return{active:!1,unavailable:!1};let Z=await this.store.get();return{active:Z.active.get($),unavailable:Z.unavailable}}async requestContext(){let $=P.getStore();if($?.featureContext)return $.featureContext;let Z=await n9(this.config,this.log);if($)$.featureContext=Z;return Z}memoFor($){let Z=P.getStore();if(!Z||Z.featureContext!==$)return null;return Z.featureEvaluations??=new Map,Z.featureEvaluations}requestBuckets(){let $=P.getStore();if(!$)return new Map;return $.featureBuckets??=new Map,$.featureBuckets}notify($,Z,J){if(!this.config.onEvaluate)return;try{this.config.onEvaluate($,Z,J)}catch(W){this.log(`The \`onEvaluate\` hook in app/config/features.ts threw for "${$}". ${W instanceof Error?W.message:String(W)}`)}}warnIfOversized($){if(this.warnedAboutSize||$<=this.config.maxClientFlags)return;this.warnedAboutSize=!0,this.log(`${$} client-visible features are embedded in every document. Mark the ones only the server reads with \`serverOnly: true\` to keep them out of the payload.`)}}function mF($){if($===void 0||$===null)return null;if(typeof $==="string"){if($.length>0)return $}else if(typeof $==="object"){let{publicId:Z,id:J}=$;if(typeof Z==="string"&&Z.length>0)return Z;if(typeof J==="string"&&J.length>0||typeof J==="number")return String(J)}throw TypeError("Features.set() was given an `actor` that identifies nobody. Pass a string, or a user with a `publicId` or an `id`.")}async function JY($){if($===void 0)return!0;return await M(j$).enabled($)}function WY(){try{return P.getStore()?.req??null}catch{return null}}async function PZ($,Z,J=WY()){if(typeof Z!=="string"||!Object.hasOwn($,Z))return null;let W=p9($[Z]);if(!W||!await JY(W.feature))return null;if(W.enabled!==void 0&&W.enabled!==!0){if(typeof W.enabled==="function"&&!J)return null;if(!await k1(W.enabled,J))return null}let Y=W.provider;if(typeof Y.isAvailable==="function"&&!await Y.isAvailable(J))return null;return Y}async function YY($,Z=WY()){let J=[];for(let W of Object.keys($))if(await PZ($,W,Z))J.push(W);return J}function V7($){if($&&typeof $==="object")delete $.password;return $}function hF(){return new Proxy({},{get:($,Z)=>zY(Z)})}var jY=new WeakMap;function XY($){if($&&typeof $==="object"){for(let Z of Object.values($))XY(Z);Object.freeze($)}return $}var pF={select:{id:!0,publicId:!0,email:!0,name:!0,locale:!0,globalRole:!0,accounts:{select:{id:!0,publicId:!0,organizationRole:!0,organization:!0}}}},cF=XY({token:!0,expiresAt:!0,absoluteExpiresAt:!0,updatedAt:!0,location:!0,userAgent:!0,user:pF});class F7{models;constructor($=hF()){this.models=$}run($){return this.models.User.asSystem($)}sessionSelect(){return cF}transaction($){return this.models.User.transaction($)}withLegacySessionLock($,Z){let J=this.models.User.$connection??w1(),W=M(f1).connection(J),Y=()=>this.transaction(async()=>{if(W.dialect==="postgres"){let X=`gemi:legacy-session:${$}`;await s0()`SELECT pg_advisory_xact_lock(hashtextextended(${X}, 0))`}return Z()});if(W.dialect!=="sqlite"||s0())return Y();let z=(jY.get(W)??Promise.resolve()).then(Y,Y);return jY.set(W,z.catch(()=>{})),z}async createUser($){let Z=await this.run(()=>this.models.User.create({data:$}));return V7(Z)}async updateUserPassword($){let Z=await this.run(()=>this.models.User.update({where:{id:$.id},data:{password:$.password}}));return V7(Z)}async findUserByEmailAddress($,Z){return await this.run(()=>this.models.User.findUnique({where:Z?{email:$,emailVerifiedAt:{not:null}}:{email:$}}))}async findUserByVerificationToken($){if(typeof $!=="string"||$==="")return null;return await this.run(()=>this.models.User.findFirst({where:{verificationToken:$}}))}async verifyUser($){return await this.run(()=>this.models.User.update({where:{email:$},data:{emailVerifiedAt:new Date}}))}async createSession($){return await this.run(()=>this.models.Session.create({data:$,include:{user:!0}}))}async createSessionV2($){return await this.run(()=>this.models.Session.create({data:$,select:this.sessionSelect()}))}async findSession($){if(!$.token)return null;return await this.run(()=>this.models.Session.findUnique({where:{token:$.token},select:this.sessionSelect()}))}async updateSession($){return await this.run(()=>this.models.Session.update({where:{token:$.token},data:{expiresAt:$.expiresAt},select:this.sessionSelect()}))}async deleteSession($){if(!$.token)return;await this.run(()=>this.models.Session.deleteMany({where:{token:$.token}}))}async claimLegacySession($){if(!$.token)return!1;let{count:Z}=await this.run(()=>this.models.Session.deleteMany({where:{token:$.token}}));return Z>0}async deleteAllUserSessions($){await this.run(()=>this.models.Session.deleteMany({where:{userId:$}}))}async createPasswordResetToken($){return await this.run(()=>this.models.PasswordResetToken.create({data:{token:$.token,user:{connect:{id:$.user.id}}}}))}async findPasswordResetToken($){if(typeof $.token!=="string"||$.token==="")return null;return await this.run(()=>this.models.PasswordResetToken.findUnique({where:{token:$.token},include:{user:!0}}))}async deletePasswordResetToken($){return await this.run(()=>this.models.PasswordResetToken.delete({where:{token:$.token}}))}async findInvitation($,Z){if(typeof $!=="string"||typeof Z!=="string")return null;return await this.run(()=>this.models.OrganizationInvitation.findFirst({where:{publicId:$,email:Z}}))}async deleteInvitationById($){await this.run(()=>this.models.OrganizationInvitation.delete({where:{publicId:$}}))}async createAccount($){return await this.run(()=>this.models.Account.create({data:{userId:$.userId,organizationId:$.organizationId,organizationRole:$.organizationRole}}))}async createMagicLinkToken($){return await this.run(()=>this.models.MagicLinkToken.create({data:{email:$.email,token:$.token,pin:$.pin}}))}async findUserMagicLinkToken($){let Z=(J)=>typeof J==="string"&&J!=="";if(!Z($.email))return null;if($.token!==void 0&&!Z($.token))return null;if($.token===void 0&&!Z($.pin))return null;return await this.run(()=>$.token?this.models.MagicLinkToken.findUnique({where:{token_email:{token:$.token,email:$.email}}}):this.models.MagicLinkToken.findUnique({where:{pin_email:{pin:$.pin,email:$.email}}}))}async findMagicLinkTokenByEmail($){return await this.run(()=>this.models.MagicLinkToken.findFirst({where:{email:$},orderBy:{id:"desc"}}))}async listMagicLinkTokensByEmail($,Z){return await this.run(()=>this.models.MagicLinkToken.findMany({where:{email:$},orderBy:{id:"desc"},take:Z}))}async deleteMagicLinkTokensExcept($,Z){await this.run(()=>this.models.MagicLinkToken.deleteMany({where:{email:$,id:{notIn:Z}}}))}async claimMagicLinkToken($){let{count:Z}=await this.run(()=>this.models.MagicLinkToken.deleteMany({where:{id:$}}));return Z===1}async deleteMagicLinkToken($){await this.run(()=>this.models.MagicLinkToken.deleteMany({where:{email:$}}))}async createSocialAccount($){return await this.run(()=>this.models.SocialAccount.create({data:$}))}async findUserBySocialAccount($,Z){if(!Z)return null;let J=await this.run(()=>this.models.SocialAccount.findFirst({where:{provider:$,providerId:Z},include:{user:!0}}));return J?V7(J.user):null}async findSocialAccounts($,Z){return await this.run(()=>this.models.SocialAccount.findMany({where:{userId:$,provider:Z},orderBy:{id:"asc"}}))}async claimSocialAccount($,Z){let{count:J}=await this.run(()=>this.models.SocialAccount.updateMany({where:{id:$.id,providerId:$.providerId},data:{providerId:Z}}));return J===1}}import{randomBytes as iD}from"crypto";function v0($,Z,J,W,Y){return $1(Z,_Y($,Z),J,W,Y)}function $1($,Z,J,W,Y,j){let z=H7(Z,J,W);if(Y&&Z!==z)throw RangeError(zX($,Z,J,W,j));return z}function _Y($,Z){let J=$[Z];if(J===void 0)throw TypeError(iJ(Z));return J}function L0($){return $!==null&&/object|function/.test(typeof $)}function m0($,Z=Map){let J=new Z;return(W,...Y)=>{if(J.has(W))return J.get(W);let j=$(W,...Y);return J.set(W,j),j}}function x7($){return h$({name:$},1)}function h$($,Z){return Y1((J)=>({value:J,configurable:1,writable:!Z}),$)}function IY($){return Y1((Z)=>({get:Z,configurable:1}),$)}function c6($){return{[Symbol.toStringTag]:{value:$,configurable:1}}}function SZ($,Z){let J={},W=$.length;for(let Y of Z)J[$[--W]]=Y;return J}function Y1($,Z,J){let W={};for(let Y in Z)W[Y]=$(Z[Y],Y,J);return W}function I3($,Z,J){let W={};for(let Y=0;Y<Z.length;Y++){let j=Z[Y];W[j]=$(j,Y,J)}return W}function dF($,Z,J){let W={};for(let Y=0;Y<$.length;Y++)W[Z[Y]]=J[$[Y]];return W}function p0($,Z){let J={};for(let W of $)J[W]=Z[W];return J}function C7($,Z){let J={};for(let W in Z)$.has(W)||(J[W]=Z[W]);return J}function A7($){$={...$};let Z=Object.keys($);for(let J of Z)$[J]===void 0&&delete $[J];return $}function xY($,Z){for(let J of Z)if(!(J in $))return 0;return 1}function CY($,Z,J){for(let W of $)if(Z[W]!==J[W])return 0;return 1}function AY($,Z,J){let W={...J};for(let Y=0;Y<Z;Y++)W[$[Y]]=0;return W}function f($,...Z){return(...J)=>$(...Z,...J)}function GY($){return $[0].toUpperCase()+$.substring(1)}function x3($){return $.slice().sort()}function w6($,Z){return String(Z).padStart($,"0")}function z$($,Z){return Math.sign($-Z)}function H7($,Z,J){return Math.min(Math.max($,Z),J)}function v1($,Z){return[Math.floor($/Z),H3($,Z)]}function H3($,Z){return($%Z+Z)%Z}function Q$($,Z){return[d6($,Z),S7($,Z)]}function d6($,Z){return Math.trunc($/Z)||0}function S7($,Z){return $%Z||0}function A6($){return Math.abs($%1)===0.5}function SY($,Z,J){let W=0,Y=0;for(let X=0;X<=Z;X++){let G=$[J[X]],Q=L1[X],V=l/Q,[F,B]=Q$(G,V);W+=B*Q,Y+=F}let[j,z]=Q$(W,l);return[Y+j,z]}function u6($,Z,J){let W={};for(let Y=Z;Y>=0;Y--){let j=L1[Y];W[J[Y]]=d6($,j),$=S7($,j)}return W}function EY($){return $===q?I4:[]}function bY($){return $===q?q3:[]}function RY($){return $===q?["year","day"]:[]}function kY($){if($!==void 0)return W0($)}function wY($){if($!==void 0)return j1($)}function E7($){if($!==void 0)return C3($)}function j1($){return vY(C3($))}function C3($){return qY(fU($))}function b7($){if($==null)throw TypeError("Cannot be null or undefined");return $}function fY($,Z){if(Z==null)throw RangeError(iJ($));return Z}function y1($){if(!L0($))throw TypeError(jX);return $}function l6($,Z,J=$){if(typeof Z!==$)throw TypeError(k3(J,Z));return Z}function qY($,Z="number"){if(!Number.isInteger($))throw RangeError(jU(Z,$));return $||0}function vY($,Z="number"){if($<=0)throw RangeError(zU(Z,$));return $}function R7($){if(typeof $=="symbol")throw TypeError(BU);return String($)}function f6($,Z){return L0($)?String($):W0($,Z)}function i6($){if(typeof $=="string")return BigInt($);if(typeof $!="bigint")throw TypeError(QU($));return $}function gY($,Z="number"){if(typeof $=="bigint")throw TypeError(GU(Z));if($=Number($),!Number.isFinite($))throw RangeError(XU(Z,$));return $}function A0($,Z){return Math.trunc(gY($,Z))||0}function yY($,Z){return qY(gY($,Z),Z)}function QY($,Z){return vY(A0($,Z),Z)}function k7($,Z){let[J,W]=Q$(Z,l),Y=$+J,j=Math.sign(Y);return j&&j===-Math.sign(W)&&(Y-=j,W+=j*l),[Y,W]}function _Z($,Z,J=1){return k7($[0]+Z[0]*J,$[1]+Z[1]*J)}function IZ($,Z){return k7($[0],$[1]+Z)}function n0($,Z){return _Z(Z,$,-1)}function E0($,Z){return z$($[0],Z[0])||z$($[1],Z[1])}function mY($,Z,J){return E0($,Z)===-1||E0($,J)===1}function s6($,Z=1){let J=BigInt(l/Z);return[Number($/J),Number($%J)*Z]}function xZ($,Z=1){let J=l/Z,[W,Y]=Q$($,J);return[W,Y*Z]}function hY($,Z=1){let[J,W]=$,Y=Math.floor(W/Z),j=l/Z;return BigInt(J)*BigInt(j)+BigInt(Y)}function o0($,Z=1,J){let[W,Y]=$,[j,z]=Q$(Y,Z);return W*(l/Z)+(j+(J?z/Z:0))}function w7($,Z,J=v1){let[W,Y]=$,[j,z]=J(Y,Z);return[W*(l/Z)+j,z]}function f7($,Z){let J=$.formatToParts(Z),W={};for(let Y of J)W[Y.type]=Y.value;return W}function q7($){return v0($,"isoYear",_3,N3,1),$.isoYear===_3?v0($,"isoMonth",4,12,1):$.isoYear===N3&&v0($,"isoMonth",1,9,1),$}function X$($){return m1({...$,...W1,isoHour:12}),$}function m1($){let Z=v0($,"isoYear",_3,N3,1),J=Z===_3?1:Z===N3?-1:0;return J&&a0(S0({...$,isoDay:$.isoDay+J,isoNanosecond:$.isoNanosecond-J})),$}function a0($){if(!$||mY($,pU,hU))throw RangeError(T4);return $}function B$($){return SY($,5,Q1)[1]}function n6($){let[Z,J]=v1($,l);return[u6(J,5,Q1),Z]}function pY($){return cY($)[0]}function cY($){return w7($,J1)}function b0($){return EZ($.isoYear,$.isoMonth,$.isoDay,$.isoHour,$.isoMinute,$.isoSecond,$.isoMillisecond)}function S0($){let Z=b0($);if(Z!==void 0){let[J,W]=Q$(Z,y0);return[J,W*H1+($.isoMicrosecond||0)*o$+($.isoNanosecond||0)]}}function v7($,Z){let[J,W]=n6(B$($)-Z);return a0(S0({...$,isoDay:$.isoDay+W,...J}))}function q6(...$){return EZ(...$)/HX}function EZ(...$){let[Z,J]=dY(...$),W=Z.valueOf();if(!isNaN(W))return W-J*y0}function dY($,Z=1,J=1,W=0,Y=0,j=0,z=0){let X=$===_3?1:$===N3?-1:0,G=new Date;return G.setUTCHours(W,Y,j,z),G.setUTCFullYear($,Z-1,J+X),[G,X]}function F$($,Z){let[J,W]=IZ($,Z);W<0&&(W+=l,J-=1);let[Y,j]=v1(W,H1),[z,X]=v1(j,o$);return o6(J*y0+Y,z,X)}function o6($,Z=0,J=0){let W=Math.ceil(Math.max(0,Math.abs($)-mU)/y0)*Math.sign($),Y=new Date($-W*y0);return SZ(C4,[Y.getUTCFullYear(),Y.getUTCMonth()+1,Y.getUTCDate()+W,Y.getUTCHours(),Y.getUTCMinutes(),Y.getUTCSeconds(),Y.getUTCMilliseconds(),Z,J])}function uY($){return[$.isoYear,$.isoMonth,$.isoDay]}function lY(){return q1}function g7($,Z){switch(Z){case 2:return y7($)?29:28;case 4:case 6:case 9:case 11:return 30}return 31}function iY($){return y7($)?366:365}function y7($){return $%4==0&&($%100!=0||$%400==0)}function sY($){let[Z,J]=dY($.isoYear,$.isoMonth,$.isoDay);return H3(Z.getUTCDay()-J,7)||7}function nY({isoYear:$}){return $<1?["bce",1-$]:["ce",$]}function uF($){let Z=b0($);if(Z<dU)return nY($);let J=f7(BW(CZ),Z),{era:W,eraYear:Y}=jz(J,CZ);return[W,Y]}function a6($){return p$($),t6($,1),$}function p$($){return oY($,1),$}function BY($){return CY(JW,$,oY($))}function oY($,Z){let{isoYear:J}=$,W=v0($,"isoMonth",1,lY(),Z);return{isoYear:J,isoMonth:W,isoDay:v0($,"isoDay",1,g7(J,W),Z)}}function t6($,Z){return SZ(Q1,[v0($,"isoHour",0,23,Z),v0($,"isoMinute",0,59,Z),v0($,"isoSecond",0,59,Z),v0($,"isoMillisecond",0,999,Z),v0($,"isoMicrosecond",0,999,Z),v0($,"isoNanosecond",0,999,Z)])}function y($){return $===void 0?0:fX(y1($))}function A3($,Z=0){$=z1($);let J=qX($),W=eU($,Z);return[fX($),W,J]}function m7($){return qX(z1($))}function aY($){return $=z1($),jW($,9,6,1)}function bZ($,Z,J,W=9,Y=0,j=4){Z=z1(Z);let z=jW(Z,W,Y),X=c7(Z),G=g3(Z,j),Q=v3(Z,W,Y,1);return z==null?z=Math.max(J,Q):$j(z,Q),X=d7(X,Q,1),$&&(G=((V)=>V<4?(V+2)%4:V)(G)),[z,Q,X,G]}function r6($,Z=6,J){let W=c7($=u7($,p6)),Y=g3($,7),j=v3($,Z);return j=fY(p6,j),W=d7(W,j,void 0,J),[j,W,Y]}function h7($){return zW(z1($))}function tY($,Z){return p7(z1($),Z)}function p7($,Z=4){let J=eY($);return[g3($,4),...rY(v3($,Z),J)]}function rY($,Z){return $!=null?[L1[$],$<4?9-3*$:-1]:[Z===void 0?1:10**(9-Z),Z]}function c7($){let Z=$[M3];return Z===void 0?1:A0(Z,M3)}function d7($,Z,J,W){let Y=W?l:L1[Z+1];if(Y){let j=L1[Z];if(Y%(($=$1(M3,$,1,Y/j-(W?0:1),1))*j))throw RangeError(k3(M3,$))}else $=$1(M3,$,1,J?1e9:1,1);return $}function eY($){let Z=$[L7];if(Z!==void 0){if(typeof Z!="number"){if(R7(Z)==="auto")return;throw RangeError(k3(L7,Z))}Z=$1(L7,Math.floor(Z),0,9,1)}return Z}function z1($){return $===void 0?{}:y1($)}function u7($,Z){return typeof $=="string"?{[Z]:$}:y1($)}function X0($){if($!==void 0){if(L0($))return Object.assign(Object.create(null),$);throw TypeError(jX)}}function e6($,Z){return $&&Object.assign(Object.create(null),$,{overflow:lU[Z]})}function l7($,Z,J=9,W=0,Y){let j=Z[$];if(j===void 0)return Y?W:void 0;if(j=R7(j),j==="auto")return Y?W:null;let z=P7[j];if(z===void 0&&(z=gU[j]),z===void 0)throw RangeError(QX($,j,P7));return $1($,z,W,J,1,f3),z}function c$($,Z,J,W=0){let Y=J[$];if(Y===void 0)return W;let j=R7(Y),z=Z[j];if(z===void 0)throw RangeError(QX($,j,Z));return z}function $j($,Z){if(Z>$)throw RangeError(EU)}function H0($){return{branding:S4,epochNanoseconds:$}}function N0($,Z,J){return{branding:d1,calendar:J,timeZone:Z,epochNanoseconds:$}}function G0($,Z=$.calendar){return{branding:t$,calendar:Z,...p0(bX,$)}}function Q0($,Z=$.calendar){return{branding:a$,calendar:Z,...p0(WW,$)}}function y$($,Z=$.calendar){return{branding:yZ,calendar:Z,...p0(WW,$)}}function v6($,Z=$.calendar){return{branding:mZ,calendar:Z,...p0(WW,$)}}function X1($){return{branding:A4,...p0(EX,$)}}function $0($){return{branding:E4,sign:U$($),...p0(eJ,$)}}function Zj($){return pY($.epochNanoseconds)}function $4($){return w7($.epochNanoseconds,H1)[0]}function Jj($){return hY($.epochNanoseconds,o$)}function Wj($){return hY($.epochNanoseconds)}function Yj($){return $.epochNanoseconds}function T0($){return typeof $=="string"?$:W0($.id)}function RZ($,Z){return $===Z||T0($)===T0(Z)}function jj($,Z,J,W,Y){let j=m$(W),[z,X]=((L,H)=>{let T=H((L=u7(L,I7))[kX]),K=rU(L);return K=fY(I7,K),[K,T]})(Y,$);if(T3(Math.max(z,j),X))return VY(W,z);if(!X)throw RangeError(P4);let[G,Q,V]=z4(Z,J,X),F=DJ(V),B=X4(V),U=LJ(V),D=B(Q,G,W),O=U(Q,G,D,z);return T3(z,X)?VY(O,z):((L,H,T,K,I,b,S)=>{let R=U$(L),[w,N]=i7(K,ZW(T,L),T,R,I,b,S),g=s7(H,w,N);return L[h[T]]+g*R})(O,F(D),z,Q,G,F,B)}function VY($,Z){return o0(D0($),L1[Z],1)}function i7($,Z,J,W,Y,j,z){let X=h[J],G={...Z,[X]:Z[X]+W},Q=z($,Y,Z),V=z($,Y,G);return[j(Q),j(V)]}function s7($,Z,J){let W=o0(n0(Z,J));if(!W)throw RangeError(w3);return o0(n0(Z,$))/W}function zj($,Z){let[J,W,Y]=r6(Z,5,1);return H0(J4($.epochNanoseconds,J,W,Y,1))}function Xj($,Z,J){let{epochNanoseconds:W,timeZone:Y,calendar:j}=Z,[z,X,G]=r6(J);if(z===0&&X===1)return Z;let Q=$(Y);if(z===6)W=((V,F,B,U)=>{let D=R0(B,F),[O,L]=V(D),H=B.epochNanoseconds,T=h0(F,O),K=h0(F,L);if(mY(H,T,K))throw RangeError(w3);return Lj(s7(H,T,K),U)?K:T})(Oj,Q,Z,G);else{let V=Q.getOffsetNanosecondsFor(W);W=u$(Q,Fj(F$(W,V),z,X,G),V,2,0,1)}return N0(W,Y,j)}function Gj($,Z){return G0(Fj($,...r6(Z)),$.calendar)}function Qj($,Z){let[J,W,Y]=r6(Z,5);var j;return X1((j=Y,n7($,S3(J,W),j)[0]))}function Bj($,Z){let J=$(Z.timeZone),W=R0(Z,J),[Y,j]=Oj(W),z=o0(n0(h0(J,Y),h0(J,j)),_4,1);if(z<=0)throw RangeError(w3);return z}function Vj($,Z){let{timeZone:J,calendar:W}=Z,Y=((j,z,X)=>h0(z,j(R0(X,z))))(Dj,$(J),Z);return N0(Y,J,W)}function Fj($,Z,J,W){return Uj($,S3(Z,J),W)}function Uj($,Z,J){let[W,Y]=n7($,Z,J);return m1({...l$($,Y),...W})}function n7($,Z,J){return n6(V$(B$($),Z,J))}function g6($){return V$($,N4,7)}function S3($,Z){return L1[$]*Z}function Oj($){let Z=Dj($);return[Z,l$(Z,1)]}function Dj($){return yU(6,$)}function lF($,Z,J){let W=Math.min(m$($),6);return wZ(W4(D0($,W),Z,J),W)}function Z4($,Z,J,W,Y,j,z,X,G,Q){if(W===0&&Y===1)return $;let V=T3(W,X)?G4(X)&&W<6&&J>=6?sF:iF:nF,[F,B,U]=V($,Z,J,W,Y,j,z,X,G,Q);return U&&W!==7&&(F=((D,O,L,H,T,K,I,b)=>{let S=U$(D);for(let R=H+1;R<=L;R++){if(R===7&&L!==7)continue;let w=ZW(R,D);w[h[R]]+=S;let N=o0(n0(I(b(T,K,w)),O));if(N&&Math.sign(N)!==S)break;D=w}return D})(F,B,J,Math.max(6,W),z,X,G,Q)),F}function J4($,Z,J,W,Y){if(Z===6){let j=((z)=>z[0]+z[1]/l)($);return[V$(j,J,W),0]}return W4($,S3(Z,J),W,Y)}function W4($,Z,J,W){let[Y,j]=$;W&&j<0&&(j+=l,Y-=1);let[z,X]=v1(V$(j,Z,J),l);return k7(Y+z,X)}function V$($,Z,J){return Lj($/Z,J)*Z}function Lj($,Z){return JO[Z]($)}function iF($,Z,J,W,Y,j){let z=U$($),X=D0($),G=J4(X,W,Y,j),Q=n0(X,G),V=Math.sign(G[0]-X[0])===z,F=wZ(G,Math.min(J,6));return[{...$,...F},_Z(Z,Q),V]}function sF($,Z,J,W,Y,j,z,X,G,Q){let V=U$($),F=o0(D0($,5)),B=S3(W,Y),U=V$(F,B,j),[D,O]=i7(z,{...$,...$W},6,V,X,G,Q),L=U-o0(n0(D,O)),H=0;L&&Math.sign(L)!==V?Z=IZ(D,U):(H+=V,U=V$(L,B,j),Z=IZ(O,U));let T=B4(U);return[{...$,...T,days:$.days+H},Z,Boolean(H)]}function nF($,Z,J,W,Y,j,z,X,G,Q){let V=U$($),F=h[W],B=ZW(W,$);W===7&&($={...$,weeks:$.weeks+Math.trunc($.days/7)});let U=d6($[F],Y)*Y;B[F]=U;let[D,O]=i7(z,B,W,Y*V,X,G,Q),L=U+s7(Z,D,O)*V*Y,H=V$(L,Y,j),T=Math.sign(H-L)===V;return B[F]=H,[B,T?O:D,T]}function o7($,Z,J,W){let[Y,j,z,X]=((Q)=>{let V=p7(Q=z1(Q));return[Q.timeZone,...V]})(W),G=Y!==void 0;return((Q,V,F,B,U,D)=>{F=W4(F,U,B,1);let O=V.getOffsetNanosecondsFor(F);return JJ(F$(F,O),D)+(Q?d$(g6(O)):"Z")})(G,Z(G?$(Y):r$),J.epochNanoseconds,j,z,X)}function a7($,Z,J){let[W,Y,j,z,X,G]=((Q)=>{Q=z1(Q);let V=zW(Q),F=eY(Q),B=ZO(Q),U=g3(Q,4),D=v3(Q,4);return[V,$O(Q),B,U,...rY(D,F)]})(J);return((Q,V,F,B,U,D,O,L,H,T)=>{B=W4(B,H,L,1);let K=Q(F).getOffsetNanosecondsFor(B);return JJ(F$(B,K),T)+d$(g6(K),O)+((I,b)=>b!==1?"["+(b===2?"!":"")+T0(I)+"]":"")(F,D)+WJ(V,U)})($,Z.calendar,Z.timeZone,Z.epochNanoseconds,W,Y,j,z,X,G)}function t7($,Z){let[J,W,Y,j]=((Q)=>(Q=z1(Q),[zW(Q),...p7(Q)]))(Z);return z=$.calendar,X=J,G=j,JJ(Uj($,Y,W),G)+WJ(z,X);var z,X,G}function r7($,Z){return J=$.calendar,W=$,Y=h7(Z),y6(W)+WJ(J,Y);var J,W,Y}function e7($,Z){return Hj($.calendar,Mj,$,h7(Z))}function $J($,Z){return Hj($.calendar,oF,$,h7(Z))}function ZJ($,Z){let[J,W,Y]=tY(Z);return j=Y,Kj(n7($,W,J)[0],j);var j}function Y4($,Z){let[J,W,Y]=tY(Z,3);return W>1&&($={...$,...lF($,W,J)}),((j,z)=>{let{sign:X}=j,G=X===-1?k0(j):j,{hours:Q,minutes:V}=G,[F,B]=w7(D0(G,3),J1,Q$);Aj(F);let U=YJ(B,z),D=z>=0||!X||U;return(X<0?"-":"")+"P"+FY({Y:g$(G.years),M:g$(G.months),W:g$(G.weeks),D:g$(G.days)})+(Q||V||F||D?"T"+FY({H:g$(Q),M:g$(V),S:g$(F,D)+U}):"")})($,Y)}function Hj($,Z,J,W){let Y=T0($),j=W>1||W===0&&Y!==q;return W===1?Y===q?Z(J):y6(J):j?y6(J)+Tj(Y,W===2):Z(J)}function FY($){let Z=[];for(let J in $){let W=$[J];W&&Z.push(W,J)}return Z.join("")}function JJ($,Z){return y6($)+"T"+Kj($,Z)}function y6($){return Mj($)+"-"+Z1($.isoDay)}function Mj($){let{isoYear:Z}=$;return(Z<0||Z>9999?Pj(Z)+w6(6,Math.abs(Z)):w6(4,Z))+"-"+Z1($.isoMonth)}function oF($){return Z1($.isoMonth)+"-"+Z1($.isoDay)}function Kj($,Z){let J=[Z1($.isoHour),Z1($.isoMinute)];return Z!==-1&&J.push(Z1($.isoSecond)+((W,Y,j,z)=>YJ(W*H1+Y*o$+j,z))($.isoMillisecond,$.isoMicrosecond,$.isoNanosecond,Z)),J.join(":")}function d$($,Z=0){if(Z===1)return"";let[J,W]=v1(Math.abs($),_4),[Y,j]=v1(W,N4),[z,X]=v1(j,J1);return Pj($)+Z1(J)+":"+Z1(Y)+(z||X?":"+Z1(z)+YJ(X):"")}function WJ($,Z){if(Z!==1){let J=T0($);if(Z>1||Z===0&&J!==q)return Tj(J,Z===2)}return""}function Tj($,Z){return"["+(Z?"!":"")+"u-ca="+$+"]"}function YJ($,Z){let J=w6(9,$);return J=Z===void 0?J.replace(jO,""):J.slice(0,Z),J?"."+J:""}function Pj($){return $<0?"-":"+"}function g$($,Z){return $||Z?$.toLocaleString("fullwide",{useGrouping:0}):""}function aF($,Z){let{epochNanoseconds:J}=$,W=(Z.getOffsetNanosecondsFor?Z:Z($.timeZone)).getOffsetNanosecondsFor(J),Y=F$(J,W);return{calendar:$.calendar,...Y,offsetNanoseconds:W}}function Nj($,Z){let J=R0(Z,$);return{calendar:Z.calendar,...p0(bX,J),offset:d$(J.offsetNanoseconds),timeZone:Z.timeZone}}function u$($,Z,J,W=0,Y=0,j,z){if(J!==void 0&&W===1&&(W===1||z))return v7(Z,J);let X=$.getPossibleInstantsFor(Z);if(J!==void 0&&W!==3){let G=((Q,V,F,B)=>{let U=S0(V);B&&(F=g6(F));for(let D of Q){let O=o0(n0(D,U));if(B&&(O=g6(O)),O===F)return D}})(X,Z,J,j);if(G!==void 0)return G;if(W===0)throw RangeError(_U)}return z?S0(Z):h0($,Z,Y,X)}function h0($,Z,J=0,W=$.getPossibleInstantsFor(Z)){if(W.length===1)return W[0];if(J===1)throw RangeError(IU);if(W.length)return W[J===3?1:0];let Y=S0(Z),j=((X,G)=>{let Q=X.getOffsetNanosecondsFor(IZ(G,-l));return zJ(X.getOffsetNanosecondsFor(IZ(G,l))-Q)})($,Y),z=j*(J===2?-1:1);return(W=$.getPossibleInstantsFor(F$(Y,z)))[J===2?0:W.length-1]}function jJ($){if(Math.abs($)>=l)throw RangeError(PU);return $}function zJ($){if($>l)throw RangeError(NU);return $}function XJ($,Z,J){return H0(a0(_Z(Z.epochNanoseconds,((W)=>{if(Sj(W))throw RangeError(AU);return D0(W,5)})($?k0(J):J))))}function GJ($,Z,J,W,Y,j=Object.create(null)){let z=Z(W.timeZone),X=$(W.calendar);return{...W,...UJ(z,X,W,J?k0(Y):Y,j)}}function QJ($,Z,J,W,Y=Object.create(null)){let{calendar:j}=J;return G0(OJ($(j),J,Z?k0(W):W,Y),j)}function BJ($,Z,J,W,Y){let{calendar:j}=J;return Q0(j4($(j),J,Z?k0(W):W,Y),j)}function VJ($,Z,J,W,Y=Object.create(null)){let j=J.calendar,z=$(j),X=K3(z,J);Z&&(W=Q4(W)),W.sign<0&&(X=z.dateAdd(X,{...P0,months:1}),X=l$(X,-1));let G=z.dateAdd(X,W,Y);return y$(K3(z,G),j)}function FJ($,Z,J){return X1(_j(Z,$?k0(J):J)[0])}function UJ($,Z,J,W,Y){let j=D0(W,5),z=J.epochNanoseconds;if(Sj(W)){let X=R0(J,$);z=_Z(h0($,{...j4(Z,X,{...W,...$W},Y),...p0(Q1,X)}),j)}else z=_Z(z,j),y(Y);return{epochNanoseconds:a0(z)}}function OJ($,Z,J,W){let[Y,j]=_j(Z,J);return m1({...j4($,Z,{...J,...$W,days:J.days+j},W),...Y})}function j4($,Z,J,W){if(J.years||J.months||J.weeks)return $.dateAdd(Z,J,W);y(W);let Y=J.days+D0(J,5)[0];return Y?X$(l$(Z,Y)):Z}function K3($,Z,J=1){return l$(Z,J-$.day(Z))}function _j($,Z){let[J,W]=D0(Z,5),[Y,j]=n6(B$($)+W);return[Y,J+j]}function l$($,Z){return Z?{...$,...o6(b0($)+Z*y0)}:$}function z4($,Z,J){let W=$(J.calendar);return G4(J)?[J,W,Z(J.timeZone)]:[{...J,...W1},W]}function DJ($){return $?Yj:S0}function X4($){return $?f(UJ,$):OJ}function LJ($){return $?f(rF,$):eF}function G4($){return $&&$.epochNanoseconds}function T3($,Z){return $<=6-(G4(Z)?1:0)}function HJ($,Z,J,W,Y,j,z){let X=$(z1(z).relativeTo),G=Math.max(m$(Y),m$(j));if(T3(G,X))return $0(kZ(((O,L,H,T)=>{let K=_Z(D0(O),D0(L),T?-1:1);if(!Number.isFinite(K[0]))throw RangeError(T4);return{...P0,...wZ(K,H)}})(Y,j,G,W)));if(!X)throw RangeError(P4);W&&(j=k0(j));let[Q,V,F]=z4(Z,J,X),B=X4(F),U=LJ(F),D=B(V,Q,Y);return $0(U(V,Q,B(V,D,j),G))}function Ij($,Z,J,W,Y){let j=m$(W),[z,X,G,Q,V]=((S,R,w)=>{S=u7(S,p6);let N=jW(S),g=w(S[kX]),_=c7(S),k=g3(S,7),M0=v3(S);if(N===void 0&&M0===void 0)throw RangeError(SU);return M0==null&&(M0=0),N==null&&(N=Math.max(M0,R)),$j(N,M0),_=d7(_,M0,1),[N,M0,_,k,g]})(Y,j,$),F=Math.max(j,z);if(!G4(V)&&F<=6)return $0(kZ(((S,R,w,N,g)=>{let _=J4(D0(S),w,N,g);return{...P0,...wZ(_,R)}})(W,z,X,G,Q)));if(!V)throw RangeError(P4);let[B,U,D]=z4(Z,J,V),O=DJ(D),L=X4(D),H=LJ(D),T=L(U,B,W),K=H(U,B,T,z),I=W.sign,b=U$(K);if(I&&b&&I!==b)throw RangeError(w3);return b&&(K=Z4(K,O(T),z,X,G,Q,U,B,O,L)),$0(K)}function xj($){return $.sign===-1?Q4($):$}function Q4($){return $0(k0($))}function k0($){let Z={};for(let J of h)Z[J]=-1*$[J]||0;return Z}function Cj($){return!$.sign}function U$($,Z=h){let J=0;for(let W of Z){let Y=Math.sign($[W]);if(Y){if(J&&J!==Y)throw RangeError(CU);J=Y}}return J}function kZ($){for(let Z of vU)$1(Z,$[Z],-KY,KY,1);return Aj(o0(D0($),J1)),$}function Aj($){if(!Number.isSafeInteger($))throw RangeError(xU)}function D0($,Z=6){return SY($,Z,h)}function wZ($,Z=6){let[J,W]=$,Y=u6(W,Z,h);if(Y[h[Z]]+=J*(l/L1[Z]),!Number.isFinite(Y[h[Z]]))throw RangeError(T4);return Y}function B4($,Z=5){return u6($,Z,h)}function Sj($){return Boolean(U$($,SX))}function m$($){let Z=9;for(;Z>0&&!$[h[Z]];Z--);return Z}function tF($,Z){return[$,Z]}function UY($){let Z=Math.floor($/R6)*R6;return[Z,Z+R6]}function Ej($){let Z=O$($=f6($));if(!Z)throw RangeError(g0($));let J;if(Z.m)J=0;else{if(!Z.offset)throw RangeError(g0($));J=fZ(Z.offset)}return Z.timeZone&&PJ(Z.timeZone,1),H0(v7(a6(Z),J))}function bj($){let Z=O$(W0($));if(!Z)throw RangeError(g0($));if(Z.timeZone)return mj(Z,Z.offset?fZ(Z.offset):void 0);if(Z.m)throw RangeError(g0($));return pj(Z)}function Rj($,Z){let J=O$(W0($));if(!J||!J.timeZone)throw RangeError(g0($));let{offset:W}=J,Y=W?fZ(W):void 0,[,j,z]=A3(Z);return mj(J,Y,j,z)}function fZ($){let Z=PJ($);if(Z===void 0)throw RangeError(g0($));return Z}function kj($){let Z=O$(W0($));if(!Z||Z.m)throw RangeError(g0($));return G0(hj(Z))}function V4($){let Z=O$(W0($));if(!Z||Z.m)throw RangeError(g0($));return Q0(Z.p?hj(Z):pj(Z))}function wj($,Z){let J=KJ(W0(Z));if(J)return MJ(J),y$(q7(p$(J)));let W=V4(Z);return y$(K3($(W.calendar),W))}function MJ($){if($.calendar!==q)throw RangeError(g1($.calendar))}function fj($,Z){let J=TJ(W0(Z));if(J)return MJ(J),v6(p$(J));let W=V4(Z),{calendar:Y}=W,j=$(Y),[z,X,G]=j.h(W),[Q,V]=j.I(z,X),[F,B]=j.N(Q,V,G);return v6(X$(j.P(F,B,G)),Y)}function qj($){let Z,J=((W)=>{let Y=BO.exec(W);return Y?(F4(Y[10]),uj(Y)):void 0})(W0($));if(!J){if(J=O$($),!J)throw RangeError(g0($));if(!J.p)throw RangeError(g0($));if(J.m)throw RangeError(g1("Z"));MJ(J)}if((Z=KJ($))&&BY(Z))throw RangeError(g0($));if((Z=TJ($))&&BY(Z))throw RangeError(g0($));return X1(t6(J,1))}function vj($){let Z=((J)=>{let W=UO.exec(J);return W?((Y)=>{function j(V,F,B){let U=0,D=0;if(B&&([U,G]=v1(G,L1[B])),V!==void 0){if(X)throw RangeError(g1(V));D=((O)=>{let L=parseInt(O);if(!Number.isFinite(L))throw RangeError(g1(O));return L})(V),z=1,F&&(G=NJ(F)*(L1[B]/J1),X=1)}return U+D}let z=0,X=0,G=0,Q={...SZ(h,[j(Y[2]),j(Y[3]),j(Y[4]),j(Y[5]),j(Y[6],Y[7],5),j(Y[8],Y[9],4),j(Y[10],Y[11],3)]),...u6(G,2,h)};if(!z)throw RangeError(XX(h));return _J(Y[1])<0&&(Q=k0(Q)),Q})(W):void 0})(W0($));if(!Z)throw RangeError(g0($));return $0(kZ(Z))}function gj($){let Z=O$($)||KJ($)||TJ($);return Z?Z.calendar:$}function yj($){let Z=O$($);return Z&&(Z.timeZone||Z.m&&r$||Z.offset)||$}function mj($,Z,J=0,W=0){let Y=U4($.timeZone),j=b4(Y);return N0(u$(j,a6($),Z,J,W,!j.v,$.m),Y,E3($.calendar))}function hj($){return cj(m1(a6($)))}function pj($){return cj(X$(p$($)))}function cj($){return{...$,calendar:E3($.calendar)}}function O$($){let Z=QO.exec($);return Z?((J)=>{let W=J[10],Y=(W||"").toUpperCase()==="Z";return{isoYear:dj(J),isoMonth:parseInt(J[4]),isoDay:parseInt(J[5]),...uj(J.slice(5)),...F4(J[16]),p:Boolean(J[6]),m:Y,offset:Y?void 0:W}})(Z):void 0}function KJ($){let Z=XO.exec($);return Z?((J)=>({isoYear:dj(J),isoMonth:parseInt(J[4]),isoDay:1,...F4(J[5])}))(Z):void 0}function TJ($){let Z=GO.exec($);return Z?((J)=>({isoYear:AZ,isoMonth:parseInt(J[1]),isoDay:parseInt(J[2]),...F4(J[3])}))(Z):void 0}function PJ($,Z){let J=VO.exec($);return J?((W,Y)=>{let j=W[4]||W[5];if(Y&&j)throw RangeError(g1(j));return jJ((NZ(W[2])*_4+NZ(W[3])*N4+NZ(W[4])*J1+NJ(W[5]||""))*_J(W[1]))})(J,Z):void 0}function dj($){let Z=_J($[1]),J=parseInt($[2]||$[3]);if(Z<0&&!J)throw RangeError(g1(-0));return Z*J}function uj($){let Z=NZ($[3]);return{...n6(NJ($[4]||""))[0],isoHour:NZ($[1]),isoMinute:NZ($[2]),isoSecond:Z===60?59:Z}}function F4($){let Z,J,W=[];if($.replace(FO,(Y,j,z)=>{let X=Boolean(j),[G,Q]=z.split("=").reverse();if(Q){if(Q==="u-ca")W.push(G),Z||(Z=X);else if(X||/[A-Z]/.test(Q))throw RangeError(g1(Y))}else{if(J)throw RangeError(g1(Y));J=G}return""}),W.length>1&&Z)throw RangeError(g1($));return{timeZone:J,calendar:W[0]||q}}function NJ($){return parseInt($.padEnd(9,"0"))}function qZ($){return new RegExp(`^${$}$`,"i")}function _J($){return $&&$!=="+"?-1:1}function NZ($){return $===void 0?0:parseInt($)}function lj($){return U4(W0($))}function U4($){let Z=IJ($);return typeof Z=="number"?d$(Z):Z?((J)=>{if(DO.test(J))throw RangeError(TU);return J.toLowerCase().split("/").map((W,Y)=>(W.length<=3||/\d/.test(W))&&!/etc|yap/.test(W)?W.toUpperCase():W.replace(/baja|dumont|[a-z]+/g,(j,z)=>j.length<=2&&!Y||j==="in"||j==="chat"?j.toUpperCase():j.length>2||!z?GY(j).replace(/island|noronha|murdo|rivadavia|urville/,GY):j)).join("/")})($):r$}function OY($){let Z=IJ($);return typeof Z=="number"?Z:Z?Z.resolvedOptions().timeZone:r$}function IJ($){let Z=PJ($=$.toUpperCase(),1);return Z!==void 0?Z:$!==r$?OO($):void 0}function xJ($,Z){return E0($.epochNanoseconds,Z.epochNanoseconds)}function CJ($,Z){return E0($.epochNanoseconds,Z.epochNanoseconds)}function ij($,Z,J,W,Y,j){let z=$(z1(j).relativeTo),X=Math.max(m$(W),m$(Y));if(CY(h,W,Y))return 0;if(T3(X,z))return E0(D0(W),D0(Y));if(!z)throw RangeError(P4);let[G,Q,V]=z4(Z,J,z),F=DJ(V),B=X4(V);return E0(F(B(Q,G,W)),F(B(Q,G,Y)))}function AJ($,Z){return i$($,Z)||O4($,Z)}function i$($,Z){return z$(b0($),b0(Z))}function O4($,Z){return z$(B$($),B$(Z))}function sj($,Z){return!xJ($,Z)}function nj($,Z){return!CJ($,Z)&&!!D4($.timeZone,Z.timeZone)&&RZ($.calendar,Z.calendar)}function oj($,Z){return!AJ($,Z)&&RZ($.calendar,Z.calendar)}function aj($,Z){return!i$($,Z)&&RZ($.calendar,Z.calendar)}function tj($,Z){return!i$($,Z)&&RZ($.calendar,Z.calendar)}function rj($,Z){return!i$($,Z)&&RZ($.calendar,Z.calendar)}function ej($,Z){return!O4($,Z)}function D4($,Z){if($===Z)return 1;let J=T0($),W=T0(Z);if(J===W)return 1;try{return OY(J)===OY(W)}catch(Y){}}function SJ($,Z,J,W){let Y=bZ($,X0(W),3,5),j=L4(Z.epochNanoseconds,J.epochNanoseconds,...Y);return $0($?k0(j):j)}function EJ($,Z,J,W,Y,j){let z=M4(W.calendar,Y.calendar),X=X0(j),[G,Q,V,F]=bZ(J,X,5),B=W.epochNanoseconds,U=Y.epochNanoseconds,D=E0(U,B),O;if(D)if(G<6)O=L4(B,U,G,Q,V,F);else{let L=Z(((T,K)=>{if(!D4(T,K))throw RangeError(UX);return T})(W.timeZone,Y.timeZone)),H=$(z);O=Zz(H,L,W,Y,D,G,X),O=Z4(O,U,G,Q,V,F,H,W,Yj,f(UJ,L))}else O=P0;return $0(J?k0(O):O)}function bJ($,Z,J,W,Y){let j=M4(J.calendar,W.calendar),z=X0(Y),[X,G,Q,V]=bZ(Z,z,6),F=S0(J),B=S0(W),U=E0(B,F),D;if(U)if(X<=6)D=L4(F,B,X,G,Q,V);else{let O=$(j);D=Jz(O,J,W,U,X,z),D=Z4(D,B,X,G,Q,V,O,J,S0,OJ)}else D=P0;return $0(Z?k0(D):D)}function RJ($,Z,J,W,Y){let j=M4(J.calendar,W.calendar),z=X0(Y);return $z(Z,()=>$(j),J,W,...bZ(Z,z,6,9,6),z)}function kJ($,Z,J,W,Y){let j=M4(J.calendar,W.calendar),z=X0(Y),X=bZ(Z,z,9,9,8),G=$(j);return $z(Z,()=>G,K3(G,J),K3(G,W),...X,z)}function $z($,Z,J,W,Y,j,z,X,G){let Q=S0(J),V=S0(W),F;if(E0(V,Q))if(Y===6)F=L4(Q,V,Y,j,z,X);else{let B=Z();F=B.dateUntil(J,W,Y,G),j===6&&z===1||(F=Z4(F,V,Y,j,z,X,B,J,S0,j4))}else F=P0;return $0($?k0(F):F)}function wJ($,Z,J,W){let Y=X0(W),[j,z,X,G]=bZ($,Y,5,5),Q=V$(fJ(Z,J),S3(z,X),G),V={...P0,...B4(Q,j)};return $0($?k0(V):V)}function rF($,Z,J,W,Y,j){let z=E0(W.epochNanoseconds,J.epochNanoseconds);return z?Y<6?Wz(J.epochNanoseconds,W.epochNanoseconds,Y):Zz(Z,$,J,W,z,Y,j):P0}function eF($,Z,J,W,Y){let j=S0(Z),z=S0(J),X=E0(z,j);return X?W<=6?Wz(j,z,W):Jz($,Z,J,X,W,Y):P0}function Zz($,Z,J,W,Y,j,z){let[X,G,Q]=((B,U,D,O)=>{function L(){return R={...l$(K,b++*-O),...T},w=h0(B,R),E0(I,w)===-O}let H=R0(U,B),T=p0(Q1,H),K=R0(D,B),I=D.epochNanoseconds,b=0,S=fJ(H,K),R,w;if(Math.sign(S)===-O&&b++,L()&&(O===-1||L()))throw RangeError(w3);let N=o0(n0(w,I));return[H,R,N]})(Z,J,W,Y);var V,F;return{...j===6?(V=X,F=G,{...P0,days:Yz(V,F)}):$.dateUntil(X,G,j,z),...B4(Q)}}function Jz($,Z,J,W,Y,j){let[z,X,G]=((Q,V,F)=>{let B=V,U=fJ(Q,V);return Math.sign(U)===-F&&(B=l$(V,-F),U+=l*F),[Q,B,U]})(Z,J,W);return{...$.dateUntil(z,X,Y,j),...B4(G)}}function L4($,Z,J,W,Y,j){return{...P0,...wZ(J4(n0($,Z),W,Y,j),J)}}function Wz($,Z,J){return{...P0,...wZ(n0($,Z),J)}}function Yz($,Z){return H4(b0($),b0(Z))}function H4($,Z){return Math.trunc((Z-$)/y0)}function fJ($,Z){return B$(Z)-B$($)}function M4($,Z){if(!RZ($,Z))throw RangeError(oJ);return $}function $U($){function Z(Y){return((j,z)=>({...jz(j,z),F:j.month,day:parseInt(j.day)}))(f7(J,Y),W)}let J=BW($),W=m6($);return{id:$,O:ZU(Z),B:JU(Z)}}function ZU($){return m0((Z)=>{let J=b0(Z);return $(J)},WeakMap)}function JU($){let Z=$(0).year-cU;return m0((J)=>{let W,Y=EZ(J-Z),j=[],z=[];do Y+=400*y0;while((W=$(Y)).year<=J);do Y+=(1-W.day)*y0,W.year===J&&(j.push(Y),z.push(W.F)),Y-=y0;while((W=$(Y)).year>=J);return{k:j.reverse(),C:LX(z.reverse())}})}function jz($,Z){let J,W,Y=zz($);if($.era){let j=xX[Z];j!==void 0&&(J=Z==="islamic"?"ah":$.era.normalize("NFD").toLowerCase().replace(/[^a-z0-9]/g,""),J==="bc"||J==="b"?J="bce":J!=="ad"&&J!=="a"||(J="ce"),W=Y,Y=Vz(W,j[J]||0))}return{era:J,eraYear:W,year:Y}}function zz($){return parseInt($.relatedYear||$.year)}function M7($){let{year:Z,F:J,day:W}=this.O($),{C:Y}=this.B(Z);return[Z,Y[J]+1,W]}function P3($,Z=1,J=1){return this.B($).k[Z-1]+(J-1)*y0}function S6($){let Z=LY(this,$),J=LY(this,$-1),W=Z.length;if(W>J.length){let Y=Fz(this);if(Y<0)return-Y;for(let j=0;j<W;j++)if(Z[j]!==J[j])return j+1}}function E6($){return H4(P3.call(this,$),P3.call(this,$+1))}function DY($,Z){let{k:J}=this.B($),W=Z+1,Y=J;return W>J.length&&(W=1,Y=this.B($+1).k),H4(J[Z-1],Y[W-1])}function b6($){return this.B($).k.length}function LY($,Z){return Object.keys($.B(Z).C)}function Xz($){return E3(W0($))}function E3($){if(($=$.toLowerCase())!==q&&$!==x4&&m6($)!==m6(BW($).resolvedOptions().calendar))throw RangeError(KU($));return $}function m6($){return $==="islamicc"&&($="islamic"),$.split("-")[0]}function Gz($){return this.R($)[0]}function Qz($){return this.R($)[1]}function qJ($){let[Z]=this.h($);return H4(this.q(Z),b0($))+1}function Bz($){let Z=HO.exec($);if(!Z)throw RangeError(HU($));return[parseInt(Z[1]),Boolean(Z[2])]}function h6($,Z,J){return $+(Z||J&&$>=J?1:0)}function K7($,Z){return $-(Z&&$>=Z?1:0)}function Vz($,Z){return(Z+$)*(Math.sign(Z)||1)||0}function T7($){return xX[Uz($)]}function Fz($){return wU[Uz($)]}function Uz($){return m6($.id||q)}function Oz($,Z,J,W){let Y=D$(J,W,G1,[],PX);if(Y.timeZone!==void 0){let j=J.dateFromFields(Y),z=s$(Y),X=$(Y.timeZone);return{epochNanoseconds:u$(Z(X),{...j,...z},Y.offset!==void 0?fZ(Y.offset):void 0),timeZone:X}}return{...J.dateFromFields(Y),...W1}}function Dz($,Z,J,W,Y,j){let z=D$(J,Y,G1,KX,PX),X=$(z.timeZone),[G,Q,V]=A3(j),F=J.dateFromFields(z,e6(j,G)),B=s$(z,G);return N0(u$(Z(X),{...F,...B},z.offset!==void 0?fZ(z.offset):void 0,Q,V),X,W)}function Lz($,Z,J){let W=D$($,Z,G1,[],c1),Y=y(J);return G0(m1({...$.dateFromFields(W,e6(J,Y)),...s$(W,Y)}))}function vJ($,Z,J,W=[]){let Y=D$($,Z,G1,W);return $.dateFromFields(Y,J)}function gJ($,Z,J,W){let Y=D$($,Z,rJ,W);return $.yearMonthFromFields(Y,J)}function yJ($,Z,J,W,Y=[]){let j=D$($,J,G1,Y);return Z&&j.month!==void 0&&j.monthCode===void 0&&j.year===void 0&&(j.year=AZ),$.monthDayFromFields(j,W)}function Hz($,Z){let J=y(Z);return X1(s$(D1($,N7,[],1),J))}function Mz($){let Z=D1($,eJ);return $0(kZ({...P0,...Z}))}function D$($,Z,J,W=[],Y=[]){return D1(Z,[...$.fields(J),...Y].sort(),W)}function D1($,Z,J,W=!J){let Y={},j,z=0;for(let X of Z){if(X===j)throw RangeError(VU(X));if(X==="constructor"||X==="__proto__")throw RangeError(sJ(X));let G=$[X];if(G!==void 0)z=1,TY[X]&&(G=TY[X](G,X)),Y[X]=G;else if(J){if(J.includes(X))throw TypeError(iJ(X));Y[X]=IX[X]}j=X}if(W&&!z)throw TypeError(XX(Z));return Y}function s$($,Z){return t6(PO({...IX,...$}),Z)}function Kz($,Z,J,W,Y,j){let z=X0(j),{calendar:X,timeZone:G}=J;return N0(((Q,V,F,B,U)=>{let D=b3(Q,F,B,G1,TX,MX),[O,L,H]=A3(U,2);return u$(V,{...Q.dateFromFields(D,e6(U,O)),...s$(D,O)},fZ(D.offset),L,H)})($(X),Z(G),W,Y,z),G,X)}function Tz($,Z,J,W,Y){let j=X0(Y);return G0(((z,X,G,Q)=>{let V=b3(z,X,G,G1,c1),F=y(Q);return m1({...z.dateFromFields(V,e6(Q,F)),...s$(V,F)})})($(Z.calendar),J,W,j))}function Pz($,Z,J,W,Y){let j=X0(Y);return((z,X,G,Q)=>{let V=b3(z,X,G,G1);return z.dateFromFields(V,Q)})($(Z.calendar),J,W,j)}function Nz($,Z,J,W,Y){let j=X0(Y);return y$(((z,X,G,Q)=>{let V=b3(z,X,G,rJ);return z.yearMonthFromFields(V,Q)})($(Z.calendar),J,W,j))}function _z($,Z,J,W,Y){let j=X0(Y);return((z,X,G,Q)=>{let V=b3(z,X,G,G1);return z.monthDayFromFields(V,Q)})($(Z.calendar),J,W,j)}function Iz($,Z,J){return X1(((W,Y,j)=>{let z=y(j);return s$({...p0(N7,W),...D1(Y,N7)},z)})($,Z,J))}function xz($,Z){return $0((J=$,W=Z,kZ({...J,...D1(W,eJ)})));var J,W}function b3($,Z,J,W,Y=[],j=[]){let z=[...$.fields(W),...Y].sort(),X=D1(Z,z,j),G=D1(J,z);return X=$.mergeFields(X,G),D1(X,z,[])}function mJ($,Z){let J=D$($,Z,_X);return $.monthDayFromFields(J)}function hJ($,Z,J){let W=D$($,Z,NX);return $.yearMonthFromFields(W,J)}function Cz($,Z,J,W,Y){Z=p0(J=$.fields(J),Z),W=D1(W,Y=$.fields(Y),[]);let j=$.mergeFields(Z,W);return j=D1(j,[...J,...Y].sort(),[]),$.dateFromFields(j)}function U7($,Z){let{era:J,eraYear:W,year:Y}=Z,j=T7($);if(J!==void 0||W!==void 0){if(J===void 0||W===void 0)throw TypeError(UU);if(!j)throw RangeError(FU);let z=j[J];if(z===void 0)throw RangeError(DU(J));let X=Vz(W,z);if(Y!==void 0&&Y!==X)throw RangeError(OU);Y=X}else if(Y===void 0)throw TypeError(LU(j));return Y}function O7($,Z,J,W){let{month:Y,monthCode:j}=Z;if(j!==void 0){let z=((X,G,Q,V)=>{let F=X.U(Q),[B,U]=Bz(G),D=h6(B,U,F);if(U){let O=Fz(X);if(O===void 0)throw RangeError(L3);if(O>0){if(D>O)throw RangeError(L3);if(F===void 0){if(V===1)throw RangeError(L3);D--}}else{if(D!==-O)throw RangeError(L3);if(F===void 0&&V===1)throw RangeError(L3)}}return D})($,j,J,W);if(Y!==void 0&&Y!==z)throw RangeError(VX);Y=z,W=1}else if(Y===void 0)throw TypeError(MU);return $1("month",Y,1,$.L(J),W)}function HY($,Z,J,W,Y){return v0(Z,"day",1,$.j(W,J),Y)}function D7($,Z,J,W){let Y=0,j=[];for(let z of J)Z[z]!==void 0?Y=1:j.push(z);if(Object.assign($,Z),Y)for(let z of W||j)delete $[z]}function Az($){return H0(a0(s6(i6($))))}function Sz($,Z,J,W,Y=q){return N0(a0(s6(i6(J))),Z(W),$(Y))}function Ez($,Z,J,W,Y=0,j=0,z=0,X=0,G=0,Q=0,V=q){return G0(m1(a6(Y1(A0,SZ(C4,[Z,J,W,Y,j,z,X,G,Q])))),$(V))}function bz($,Z,J,W,Y=q){return Q0(X$(p$(Y1(A0,{isoYear:Z,isoMonth:J,isoDay:W}))),$(Y))}function Rz($,Z,J,W=q,Y=1){let j=A0(Z),z=A0(J),X=$(W);return y$(q7(p$({isoYear:j,isoMonth:z,isoDay:A0(Y)})),X)}function kz($,Z,J,W=q,Y=AZ){let j=A0(Z),z=A0(J),X=$(W);return v6(X$(p$({isoYear:A0(Y),isoMonth:j,isoDay:z})),X)}function wz($=0,Z=0,J=0,W=0,Y=0,j=0){return X1(t6(Y1(A0,SZ(Q1,[$,Z,J,W,Y,j])),1))}function fz($=0,Z=0,J=0,W=0,Y=0,j=0,z=0,X=0,G=0,Q=0){return $0(kZ(Y1(yY,SZ(h,[$,Z,J,W,Y,j,z,X,G,Q]))))}function pJ($,Z,J=q){return N0($.epochNanoseconds,Z,J)}function qz($){return H0($.epochNanoseconds)}function cJ($,Z){return G0(R0(Z,$))}function dJ($,Z){return Q0(R0(Z,$))}function vz($,Z,J){return hJ($(Z.calendar),J)}function gz($,Z,J){return mJ($(Z.calendar),J)}function uJ($,Z){return X1(R0(Z,$))}function yz($,Z,J,W){let Y=((j,z,X,G)=>{let Q=m7(G);return h0(j(z),X,Q)})($,J,Z,W);return N0(a0(Y),J,Z.calendar)}function mz($,Z,J){let W=$(Z.calendar);return y$({...Z,...hJ(W,J)})}function hz($,Z,J){return mJ($(Z.calendar),J)}function pz($,Z,J,W,Y){let j=$(Y.timeZone),z=Y.plainTime,X=z!==void 0?Z(z):W1;return N0(h0(J(j),{...W,...X}),j,W.calendar)}function cz($,Z=W1){return G0(m1({...$,...Z}))}function dz($,Z,J){return hJ($(Z.calendar),J)}function uz($,Z,J){return mJ($(Z.calendar),J)}function lz($,Z,J,W){return((Y,j,z)=>Cz(Y,j,NX,y1(z),q3))($(Z.calendar),J,W)}function iz($,Z,J,W){return((Y,j,z)=>Cz(Y,j,_X,y1(z),I4))($(Z.calendar),J,W)}function sz($,Z,J,W,Y){let j=y1(Y),z=Z(j.plainDate),X=$(j.timeZone);return N0(h0(J(X),{...z,...W}),X,z.calendar)}function nz($,Z){return G0(m1({...$,...Z}))}function oz($){return H0(a0(xZ($,J1)))}function az($){return H0(a0(xZ($,H1)))}function tz($){return H0(a0(s6(i6($),o$)))}function rz($){return H0(a0(s6(i6($))))}function ez($,Z,J=W1){let W=Z.timeZone,Y=$(W),j={...R0(Z,Y),...J};return N0(u$(Y,j,j.offsetNanoseconds,2),W,Z.calendar)}function $X($,Z,J){let W=Z.timeZone,Y=$(W),j={...R0(Z,Y),...J},z=YX(Z.calendar,J.calendar);return N0(u$(Y,j,j.offsetNanoseconds,2),W,z)}function ZX($,Z=W1){return G0({...$,...Z})}function JX($,Z){return G0({...$,...Z},YX($.calendar,Z.calendar))}function K4($,Z){return{...$,calendar:Z}}function WX($,Z){return{...$,timeZone:Z}}function YX($,Z){if($===Z)return $;let J=T0($),W=T0(Z);if(J===W||J===q)return Z;if(W===q)return $;throw RangeError(oJ)}function WU($,Z){return(J)=>J===q?$:J===x4||J===CZ?Object.assign(Object.create($),{id:J}):Object.assign(Object.create(Z),LO(J))}function n$($,Z,J){let W=new Set(J);return(Y)=>(((j,z)=>{for(let X of z)if(X in j)return 1;return 0})(Y=C7(W,Y),$)||Object.assign(Y,Z),J&&(Y.timeZone=r$,["full","long"].includes(Y.timeStyle)&&(Y.timeStyle="medium")),Y)}function h1($,Z=lJ){let[J,,,W]=$;return(Y,j=gO,...z)=>{let X=Z(W&&W(...z),Y,j,J),G=X.resolvedOptions();return[X,...YU($,G,z)]}}function lJ($,Z,J,W){if(J=W(J),$){if(J.timeZone!==void 0)throw TypeError(bU);J.timeZone=$}return new L$(Z,J)}function YU($,Z,J){let[,W,Y]=$;return J.map((j)=>(j.calendar&&((z,X,G)=>{if((G||z!==q)&&z!==X)throw RangeError(oJ)})(T0(j.calendar),Z.calendar,Y),W(j,Z)))}function vZ($){let Z=R3();return F$(Z,$.getOffsetNanosecondsFor(Z))}function R3(){return xZ(Date.now(),H1)}function p1(){return NY||(NY=new L$().resolvedOptions().timeZone)}var jU=($,Z)=>`Non-integer ${$}: ${Z}`,zU=($,Z)=>`Non-positive ${$}: ${Z}`,XU=($,Z)=>`Non-finite ${$}: ${Z}`,GU=($)=>`Cannot convert bigint to ${$}`,QU=($)=>`Invalid bigint: ${$}`,BU="Cannot convert Symbol to string",jX="Invalid object",zX=($,Z,J,W,Y)=>Y?zX($,Y[Z],Y[J],Y[W]):k3($,Z)+`; must be between ${J}-${W}`,k3=($,Z)=>`Invalid ${$}: ${Z}`,iJ=($)=>`Missing ${$}`,sJ=($)=>`Invalid field ${$}`,VU=($)=>`Duplicate field ${$}`,XX=($)=>"No valid fields: "+$.join(),GX="Invalid bag",QX=($,Z,J)=>k3($,Z)+"; must be "+Object.keys(J).join(),BX="Cannot use valueOf",nJ="Invalid calling context",FU="Forbidden era/eraYear",UU="Mismatching era/eraYear",OU="Mismatching year/eraYear",DU=($)=>`Invalid era: ${$}`,LU=($)=>"Missing year"+($?"/era/eraYear":""),HU=($)=>`Invalid monthCode: ${$}`,VX="Mismatching month/monthCode",MU="Missing month/monthCode",MY="Cannot guess year",L3="Invalid leap month",FX="Invalid protocol",w3="Invalid protocol results",oJ="Mismatching Calendars",KU=($)=>`Invalid Calendar: ${$}`,UX="Mismatching TimeZones",TU="Forbidden ICU TimeZone",PU="Out-of-bounds offset",NU="Out-of-bounds TimeZone gap",_U="Invalid TimeZone offset",IU="Ambiguous offset",T4="Out-of-bounds date",xU="Out-of-bounds duration",CU="Cannot mix duration signs",P4="Missing relativeTo",AU="Cannot use large units",SU="Required smallestUnit or largestUnit",EU="smallestUnit > largestUnit",g0=($)=>`Cannot parse: ${$}`,g1=($)=>`Invalid substring: ${$}`,OX=($)=>`Cannot format ${$}`,DX="Mismatching types for formatting",bU="Cannot specify TimeZone",LX=f(I3,($,Z)=>Z),gZ=f(I3,($,Z,J)=>J),Z1=f(w6,2),P7={nanosecond:0,microsecond:1,millisecond:2,second:3,minute:4,hour:5,day:6,week:7,month:8,year:9},f3=Object.keys(P7),y0=86400000,HX=1000,o$=1000,H1=1e6,J1=1e9,N4=60000000000,_4=3600000000000,l=86400000000000,L1=[1,o$,H1,J1,N4,_4,l],c1=f3.slice(0,6),N7=x3(c1),MX=["offset"],KX=["timeZone"],TX=c1.concat(MX),PX=TX.concat(KX),_7=["era","eraYear"],RU=_7.concat(["year"]),I4=["year"],aJ=["monthCode"],tJ=["month"].concat(aJ),q3=["day"],rJ=tJ.concat(I4),NX=aJ.concat(I4),G1=q3.concat(rJ),kU=q3.concat(tJ),_X=q3.concat(aJ),IX=gZ(c1,0),q="iso8601",x4="gregory",CZ="japanese",xX={[x4]:{bce:-1,ce:0},[CZ]:{bce:-1,ce:0,meiji:1867,taisho:1911,showa:1925,heisei:1988,reiwa:2018},ethioaa:{era0:0},ethiopic:{era0:0,era1:5500},coptic:{era0:-1,era1:0},roc:{beforeroc:-1,minguo:0},buddhist:{be:0},islamic:{ah:0},indian:{saka:0},persian:{ap:0}},wU={chinese:13,dangi:13,hebrew:-6},W0=f(l6,"string"),CX=f(l6,"boolean"),fU=f(l6,"number"),AX=f(l6,"function"),h=f3.map(($)=>$+"s"),eJ=x3(h),qU=h.slice(0,6),SX=h.slice(6),vU=SX.slice(1),gU=LX(h),P0=gZ(h,0),$W=gZ(qU,0),ZW=f(AY,h),Q1=["isoNanosecond","isoMicrosecond","isoMillisecond","isoSecond","isoMinute","isoHour"],JW=["isoDay","isoMonth","isoYear"],C4=Q1.concat(JW),WW=x3(JW),EX=x3(Q1),bX=x3(C4),W1=gZ(EX,0),yU=f(AY,C4),L$=Intl.DateTimeFormat,RX="en-GB",YW=1e8,mU=YW*y0,hU=[YW,0],pU=[-YW,0],N3=275760,_3=-271821,cU=1970,AZ=1972,q1=12,dU=EZ(1868,9,8),uU=m0(uF,WeakMap),p6="smallestUnit",I7="unit",M3="roundingIncrement",L7="fractionalSecondDigits",kX="relativeTo",wX={constrain:0,reject:1},lU=Object.keys(wX),iU={compatible:0,reject:1,earlier:2,later:3},sU={reject:0,use:1,prefer:2,ignore:3},nU={auto:0,never:1,critical:2,always:3},oU={auto:0,never:1,critical:2},aU={auto:0,never:1},tU={floor:0,halfFloor:1,ceil:2,halfCeil:3,trunc:4,halfTrunc:5,expand:6,halfExpand:7,halfEven:8},v3=f(l7,p6),jW=f(l7,"largestUnit"),rU=f(l7,I7),fX=f(c$,"overflow",wX),qX=f(c$,"disambiguation",iU),eU=f(c$,"offset",sU),zW=f(c$,"calendarName",nU),$O=f(c$,"timeZoneName",oU),ZO=f(c$,"offset",aU),g3=f(c$,"roundingMode",tU),yZ="PlainYearMonth",mZ="PlainMonthDay",a$="PlainDate",t$="PlainDateTime",A4="PlainTime",d1="ZonedDateTime",S4="Instant",E4="Duration",JO=[Math.floor,($)=>A6($)?Math.floor($):Math.round($),Math.ceil,($)=>A6($)?Math.ceil($):Math.round($),Math.trunc,($)=>A6($)?Math.trunc($)||0:Math.round($),($)=>$<0?Math.floor($):Math.ceil($),($)=>Math.sign($)*Math.round(Math.abs($))||0,($)=>A6($)?($=Math.trunc($)||0)+$%2:Math.round($)],r$="UTC",R6=5184000,WO=q6(1847),YO=q6(new Date().getUTCFullYear()+10),jO=/0+$/,R0=m0(aF,WeakMap),KY=4294967295,b4=m0(($)=>{let Z=IJ($);return typeof Z=="object"?new gX(Z):new vX(Z||0)});class vX{constructor($){this.v=$}getOffsetNanosecondsFor(){return this.v}getPossibleInstantsFor($){return[v7($,this.v)]}l(){}}class gX{constructor($){this.$=((Z)=>{function J(G){let Q=H7(G,z,X),[V,F]=UY(Q),B=Y(V),U=Y(F);return B===U?B:W(j(V,F),B,U,G)}function W(G,Q,V,F){let B,U;for(;(F===void 0||(B=F<G[0]?Q:F>=G[1]?V:void 0)===void 0)&&(U=G[1]-G[0]);){let D=G[0]+Math.floor(U/2);Z(D)===V?G[1]=D:G[0]=D+1}return B}let Y=m0(Z),j=m0(tF),z=WO,X=YO;return{G(G){let Q=J(G-86400),V=J(G+86400),F=G-Q,B=G-V;if(Q===V)return[F];let U=J(F);return U===J(B)?[G-U]:Q>V?[F,B]:[]},V:J,l(G,Q){let V=H7(G,z,X),[F,B]=UY(V),U=R6*Q,D=Q<0?()=>B>z||(z=V,0):()=>F<X||(X=V,0);for(;D();){let O=Y(F),L=Y(B);if(O!==L){let H=j(F,B);W(H,O,L);let T=H[0];if((z$(T,G)||1)===Q)return T}F+=U,B+=U}}}})(((Z)=>(J)=>{let W=f7(Z,J*HX);return q6(zz(W),parseInt(W.month),parseInt(W.day),parseInt(W.hour),parseInt(W.minute),parseInt(W.second))-J})($))}getOffsetNanosecondsFor($){return this.$.V(pY($))*J1}getPossibleInstantsFor($){let[Z,J]=[q6((W=$).isoYear,W.isoMonth,W.isoDay,W.isoHour,W.isoMinute,W.isoSecond),W.isoMillisecond*H1+W.isoMicrosecond*o$+W.isoNanosecond];var W;return this.$.G(Z).map((Y)=>a0(IZ(xZ(Y,J1),J)))}l($,Z){let[J,W]=cY($),Y=this.$.l(J+(Z>0||W?1:0),Z);if(Y!==void 0)return xZ(Y,J1)}}var XW="([+\u2212-])",k6="(?:[.,](\\d{1,9}))?",yX=`(?:(?:${XW}(\\d{6}))|(\\d{4}))-?(\\d{2})`,GW="(\\d{2})(?::?(\\d{2})(?::?(\\d{2})"+k6+")?)?",QW=XW+GW,zO=yX+"-?(\\d{2})(?:[T ]"+GW+"(Z|"+QW+")?)?",mX="\\[(!?)([^\\]]*)\\]",R4=`((?:${mX}){0,9})`,XO=qZ(yX+R4),GO=qZ("(?:--)?(\\d{2})-?(\\d{2})"+R4),QO=qZ(zO+R4),BO=qZ("T?"+GW+"(?:"+QW+")?"+R4),VO=qZ(QW),FO=new RegExp(mX,"g"),UO=qZ(`${XW}?P(\\d+Y)?(\\d+M)?(\\d+W)?(\\d+D)?(?:T(?:(\\d+)${k6}H)?(?:(\\d+)${k6}M)?(?:(\\d+)${k6}S)?)?`),OO=m0(($)=>new L$(RX,{timeZone:$,era:"short",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"})),DO=/^(AC|AE|AG|AR|AS|BE|BS|CA|CN|CS|CT|EA|EC|IE|IS|JS|MI|NE|NS|PL|PN|PR|PS|SS|VS)T$/,LO=m0($U),BW=m0(($)=>new L$(RX,{calendar:$,timeZone:r$,era:"short",year:"numeric",month:"short",day:"numeric"})),HO=/^M(\d{2})(L?)$/,MO={era:f6,eraYear:A0,year:A0,month:QY,monthCode:f6,day:QY},KO=gZ(c1,A0),TO=gZ(h,yY),TY=Object.assign({},MO,KO,TO,{offset:f6}),PO=f(dF,c1,Q1),PY={dateAdd($,Z,J){let W=y(J),Y,{years:j,months:z,weeks:X,days:G}=Z;if(G+=D0(Z,5)[0],j||z)Y=((Q,V,F,B,U)=>{let[D,O,L]=Q.h(V);if(F){let[H,T]=Q.I(D,O);D+=F,O=h6(H,T,Q.U(D)),O=$1("month",O,1,Q.L(D),U)}return B&&([D,O]=Q._(D,O,B)),L=$1("day",L,1,Q.j(D,O),U),Q.q(D,O,L)})(this,$,j,z,W);else{if(!X&&!G)return $;Y=b0($)}return Y+=(7*X+G)*y0,X$(o6(Y))},dateUntil($,Z,J){if(J<=7){let G=0,Q=Yz({...$,...W1},{...Z,...W1});return J===7&&([G,Q]=Q$(Q,7)),{...P0,weeks:G,days:Q}}let W=this.h($),Y=this.h(Z),[j,z,X]=((G,Q,V,F,B,U,D)=>{let O=B-Q,L=U-V,H=D-F;if(O||L){let T=Math.sign(O||L),K=G.j(B,U),I=0;if(Math.sign(H)===-T){let b=K;[B,U]=G._(B,U,-T),O=B-Q,L=U-V,K=G.j(B,U),I=T<0?-b:K}if(H=D-Math.min(F,K)+I,O){let[b,S]=G.I(Q,V),[R,w]=G.I(B,U);if(L=R-b||Number(w)-Number(S),Math.sign(L)===-T){let N=T<0&&-G.L(B);O=(B-=T)-Q,L=U-h6(b,S,G.U(B))+(N||G.L(B))}}}return[O,L,H]})(this,...W,...Y);return J===8&&(z+=this.J(j,W[0]),j=0),{...P0,years:j,months:z,days:X}},dateFromFields($,Z){let J=y(Z),W=U7(this,$),Y=O7(this,$,W,J),j=HY(this,$,Y,W,J);return Q0(X$(this.P(W,Y,j)),this.id||q)},yearMonthFromFields($,Z){let J=y(Z),W=U7(this,$),Y=O7(this,$,W,J);return y$(q7(this.P(W,Y,1)),this.id||q)},monthDayFromFields($,Z){let J=y(Z),W=!this.id,{monthCode:Y,year:j,month:z}=$,X,G,Q,V,F;if(Y!==void 0){[X,G]=Bz(Y),F=_Y($,"day");let B=this.N(X,G,F);if(!B)throw RangeError(MY);if([Q,V]=B,z!==void 0&&z!==V)throw RangeError(VX);W&&(V=$1("month",V,1,q1,1),F=$1("day",F,1,g7(j!==void 0?j:Q,V),J))}else{Q=j===void 0&&W?AZ:U7(this,$),V=O7(this,$,Q,J),F=HY(this,$,V,Q,J);let B=this.U(Q);G=V===B,X=K7(V,B);let U=this.N(X,G,F);if(!U)throw RangeError(MY);[Q,V]=U}return v6(X$(this.P(Q,V,F)),this.id||q)},fields($){return T7(this)&&$.includes("year")?[...$,..._7]:$},mergeFields($,Z){let J=Object.assign(Object.create(null),$);return D7(J,Z,tJ),T7(this)&&(D7(J,Z,RU),this.id===CZ&&D7(J,Z,kU,_7)),J},inLeapYear($){let[Z]=this.h($);return this.K(Z)},monthsInYear($){let[Z]=this.h($);return this.L(Z)},daysInMonth($){let[Z,J]=this.h($);return this.j(Z,J)},daysInYear($){let[Z]=this.h($);return this.X(Z)},dayOfYear:qJ,era($){return this.ee($)[0]},eraYear($){return this.ee($)[1]},monthCode($){let[Z,J]=this.h($),[W,Y]=this.I(Z,J);return((j,z)=>"M"+Z1(j)+(z?"L":""))(W,Y)},dayOfWeek:sY,daysInWeek(){return 7}},NO={dayOfYear:qJ,h:uY,q:EZ},_O=Object.assign({},NO,{weekOfYear:Gz,yearOfWeek:Qz,R($){function Z(U){return(7-U<W?7:0)-U}function J(U){let D=iY(B+U),O=U||1,L=Z(H3(G+D*O,7));return V=(D+(L-Q)*O)/7}let W=this.id?1:4,Y=sY($),j=this.dayOfYear($),z=H3(Y-1,7),X=j-1,G=H3(z-X,7),Q=Z(G),V,F=Math.floor((X-Q)/7)+1,B=$.isoYear;return F?F>J(0)&&(F=1,B++):(F=J(-1),B--),[F,B,V]}}),IO={dayOfYear:qJ,h:M7,q:P3,weekOfYear:Gz,yearOfWeek:Qz,R(){return[]}},hZ=WU(Object.assign({},PY,_O,{h:uY,ee($){return this.id===x4?nY($):this.id===CZ?uU($):[]},I:($,Z)=>[Z,0],N($,Z){if(!Z)return[AZ,$]},K:y7,U(){},L:lY,J:($)=>$*q1,j:g7,X:iY,P:($,Z,J)=>({isoYear:$,isoMonth:Z,isoDay:J}),q:EZ,_:($,Z,J)=>($+=d6(J,q1),(Z+=S7(J,q1))<1?($--,Z+=q1):Z>q1&&($++,Z-=q1),[$,Z]),year($){return $.isoYear},month($){return $.isoMonth},day:($)=>$.isoDay}),Object.assign({},PY,IO,{h:M7,ee($){let Z=this.O($);return[Z.era,Z.eraYear]},I($,Z){let J=S6.call(this,$);return[K7(Z,J),J===Z]},N($,Z,J){let[W,Y,j]=M7.call(this,{isoYear:AZ,isoMonth:q1,isoDay:31}),z=S6.call(this,W),X=Y===z;(z$($,K7(Y,z))||z$(Number(Z),Number(X))||z$(J,j))===1&&W--;for(let G=0;G<100;G++){let Q=W-G,V=S6.call(this,Q),F=h6($,Z,V);if(Z===(F===V)&&J<=DY.call(this,Q,F))return[Q,F]}},K($){let Z=E6.call(this,$);return Z>E6.call(this,$-1)&&Z>E6.call(this,$+1)},U:S6,L:b6,J($,Z){let J=Z+$,W=Math.sign($),Y=W<0?-1:0,j=0;for(let z=Z;z!==J;z+=W)j+=b6.call(this,z+Y);return j},j:DY,X:E6,P($,Z,J){return o6(P3.call(this,$,Z,J))},q:P3,_($,Z,J){if(J){if(Z+=J,!Number.isSafeInteger(Z))throw RangeError(T4);if(J<0)for(;Z<1;)Z+=b6.call(this,--$);else{let W;for(;Z>(W=b6.call(this,$));)Z-=W,$++}}return[$,Z]},year($){return this.O($).year},month($){let{year:Z,F:J}=this.O($),{C:W}=this.B(Z);return W[J]+1},day($){return this.O($).day}})),G$="numeric",pZ=["timeZoneName"],hX={month:G$,day:G$},VW={year:G$,month:G$},FW=Object.assign({},VW,{day:G$}),UW={hour:G$,minute:G$,second:G$},OW=Object.assign({},FW,UW),xO=Object.assign({},OW,{timeZoneName:"short"}),CO=Object.keys(VW),AO=Object.keys(hX),SO=Object.keys(FW),EO=Object.keys(UW),DW=["dateStyle"],bO=CO.concat(DW),RO=AO.concat(DW),LW=SO.concat(DW,["weekday"]),y3=EO.concat(["dayPeriod","timeStyle"]),HW=LW.concat(y3),kO=HW.concat(pZ),wO=pZ.concat(y3),fO=pZ.concat(LW),qO=pZ.concat(["day","weekday"],y3),vO=pZ.concat(["year","weekday"],y3),gO={},MW=[n$(HW,OW),$4],pX=[n$(kO,xO),$4,0,($,Z)=>{let J=T0($.timeZone);if(Z&&T0(Z.timeZone)!==J)throw RangeError(UX);return J}],KW=[n$(HW,OW,pZ),b0],TW=[n$(LW,FW,wO),b0],PW=[n$(y3,UW,fO),($)=>B$($)/H1],NW=[n$(bO,VW,qO),b0,1],_W=[n$(RO,hX,vO),b0,1],NY;function T1($,Z,J,W,Y){function j(...G){if(!(this instanceof j))throw TypeError(nJ);lX(this,Z(...G))}function z(G,Q){return Object.defineProperties(function(...V){return G.call(this,X(this),...V)},x7(Q))}function X(G){let Q=x0(G);if(!Q||Q.branding!==$)throw TypeError(nJ);return Q}return Object.defineProperties(j.prototype,{...IY(Y1(z,J)),...h$(Y1(z,W)),...c6("Temporal."+$)}),Object.defineProperties(j,{...h$(Y),...x7($)}),[j,(G)=>{let Q=Object.create(j.prototype);return lX(Q,G),Q},X]}function nX($){return $=$.concat("id").sort(),(Z)=>{if(!xY(Z,$))throw TypeError(FX);return Z}}function lZ($){if(x0($)||$.calendar!==void 0||$.timeZone!==void 0)throw TypeError(GX);return $}function k4($,Z){let J={};for(let W in $)J[W]=({o:Y},j)=>{let z=x0(j)||{},{branding:X}=z,G=X===a$||Z.includes(X)?z:f0(j);return Y[W](G)};return J}function CW($){let Z={};for(let J in $)Z[J]=(W)=>{let{calendar:Y}=W;return(j=Y,typeof j=="string"?hZ(j):(z=j,Object.assign(Object.create(eO),{i:z})))[J](W);var j,z};return Z}function P$(){throw TypeError(BX)}function h3({calendar:$}){return typeof $=="string"?new qW($):$}function cX($,Z){if(Z=X0(Z),L0($)){let W=x0($);if(W&&W.branding===mZ)return y(Z),W;let Y=tX($);return yJ(m4(Y||q),!Y,$,Z)}let J=fj(hZ,$);return y(Z),J}function oX($,Z,J){return W=Z.call($,w0(H0(J))),jJ(C3(W));var W}function w4($,Z=ZG){let J=Object.keys(Z).sort(),W={};for(let Y of J)W[Y]=f(Z[Y],$,AX($[Y]));return W}function s($,Z){return typeof $=="string"?b4($):w4($,Z)}function V0($){return s($,xW)}function M1($){if(L0($)){let Z=x0($);if(Z)switch(Z.branding){case S4:return Z;case d1:return H0(Z.epochNanoseconds)}}return Ej($)}function dX($,Z,J){let W=Z.l(M1(J).epochNanoseconds,$);return W?w0(H0(W)):null}function a($){return L0($)?(x0($)||{}).timeZone||jD($):((Z)=>U4(yj(W0(Z))))($)}function H$($,Z){if(L0($)){let J=x0($)||{};switch(J.branding){case A4:return y(Z),J;case t$:return y(Z),X1(J);case d1:return y(Z),uJ(V0,J)}return Hz($,Z)}return y(Z),qj($)}function AW($){return $===void 0?void 0:H$($)}function cZ($,Z){if(Z=X0(Z),L0($)){let W=x0($);return W&&W.branding===yZ?(y(Z),W):gJ(g4(p3($)),$,Z)}let J=wj(hZ,$);return y(Z),J}function M$($,Z){if(Z=X0(Z),L0($)){let W=x0($)||{};switch(W.branding){case t$:return y(Z),W;case a$:return y(Z),G0({...W,...W1});case d1:return y(Z),cJ(V0,W)}return Lz(y4(p3($)),$,Z)}let J=kj($);return y(Z),J}function f0($,Z){if(Z=X0(Z),L0($)){let W=x0($)||{};switch(W.branding){case a$:return y(Z),W;case t$:return y(Z),Q0(W);case d1:return y(Z),dJ(V0,W)}return vJ(y4(p3($)),$,Z)}let J=V4($);return y(Z),J}function aX($,Z,J){return j1(Z.call($,j0(Q0(J,$))))}function P1($){return(Z)=>typeof Z=="string"?hZ(Z):((J,W)=>{let Y=Object.keys(W).sort(),j={};for(let z of Y)j[z]=f(W[z],J,J[z]);return j})(Z,$)}function Y0($){if(L0($)){let Z=x0($);return Z&&Z.branding===E4?Z:Mz($)}return vj($)}function m3($){if($!==void 0){if(L0($)){let Z=x0($)||{};switch(Z.branding){case d1:case a$:return Z;case t$:return Q0(Z)}let J=p3($);return{...Oz(a,s,y4(J),$),calendar:J}}return bj($)}}function p3($){return tX($)||q}function tX($){let{calendar:Z}=$;if(Z!==void 0)return I0(Z)}function I0($){return L0($)?(x0($)||{}).calendar||TD($):((Z)=>E3(gj(W0(Z))))($)}function dZ($,Z){if(Z=X0(Z),L0($)){let J=x0($);if(J&&J.branding===d1)return A3(Z),J;let W=p3($);return Dz(a,s,y4(W),W,$,Z)}return Rj($,Z)}function uX($){return Y1((Z)=>(J)=>Z(IW(J)),$)}function IW($){return R0($,V0)}function yO(){let $=L$.prototype,Z=Object.getOwnPropertyDescriptors($),J=Object.getOwnPropertyDescriptors(L$),W=function(Y,j={}){if(!(this instanceof W))return new W(Y,j);vW.set(this,((z,X={})=>{let G=new L$(z,X),Q=G.resolvedOptions(),V=Q.locale,F=p0(Object.keys(X),Q),B=m0(pO),U=(...D)=>{let O,L=D.map((H,T)=>{let K=x0(H),I=(K||{}).branding;if(T&&O&&O!==I)throw TypeError(DX);return O=I,K});return O?B(O)(V,F,...L):[G,...D]};return U.u=G,U})(Y,j))};for(let Y in Z){let j=Z[Y],z=Y.startsWith("format")&&mO(Y);typeof j.value=="function"?j.value=Y==="constructor"?W:z||hO(Y):z&&(j.get=function(){return z.bind(this)})}return J.prototype.value=Object.create($,Z),Object.defineProperties(W,J),W}function mO($){return function(...Z){let J=vW.get(this),[W,...Y]=J(...Z);return W[$](...Y)}}function hO($){return function(...Z){return vW.get(this).u[$](...Z)}}function pO($){let Z=cO[$];if(!Z)throw TypeError(OX($));return h1(Z,m0(lJ))}var cO={Instant:MW,PlainDateTime:KW,PlainDate:TW,PlainTime:PW,PlainYearMonth:NW,PlainMonthDay:_W},dO=h1(MW),uO=h1(pX),lO=h1(KW),iO=h1(TW),sO=h1(PW),nO=h1(NW),oO=h1(_W),SW={era:kY,eraYear:E7,year:C3,month:j1,daysInMonth:j1,daysInYear:j1,inLeapYear:CX,monthsInYear:j1},q4={monthCode:W0},EW={day:j1},rX={dayOfWeek:j1,dayOfYear:j1,weekOfYear:wY,yearOfWeek:E7,daysInWeek:j1},eX=Object.assign({},SW,q4,EW,rX),f4=new WeakMap,x0=f4.get.bind(f4),lX=f4.set.bind(f4),aO={...k4(SW,[yZ]),...k4(rX,[]),...k4(q4,[yZ,mZ]),...k4(EW,[mZ])},bW=CW(eX),tO=CW({...SW,...q4}),rO=CW({...q4,...EW}),c3={calendarId:($)=>T0($.calendar)},eO=Y1(($,Z)=>function(J){let{i:W}=this;return $(W[Z](j0(Q0(J,W))))},eX),$D=I3(($)=>(Z)=>Z[$],h.concat("sign")),RW=I3(($,Z)=>(J)=>J[Q1[Z]],c1),$G={epochSeconds:Zj,epochMilliseconds:$4,epochMicroseconds:Jj,epochNanoseconds:Wj},d3=f(C7,new Set(["branding"])),[ZD,uZ,JD]=T1(mZ,f(kz,I0),{...c3,...rO},{getISOFields:d3,getCalendar:h3,with($,Z,J){return uZ(_z(HD,$,this,lZ(Z),J))},equals:($,Z)=>rj($,cX(Z)),toPlainDate($,Z){return j0(iz(u3,$,this,Z))},toLocaleString($,Z,J){let[W,Y]=oO(Z,J,$);return W.format(Y)},toString:$J,toJSON:($)=>$J($),valueOf:P$},{from:($,Z)=>uZ(cX($,Z))}),ZG={getOffsetNanosecondsFor:oX,getPossibleInstantsFor($,Z,J){let W=[...Z.call($,_0(G0(J,q)))].map((j)=>YD(j).epochNanoseconds),Y=W.length;return Y>1&&(W.sort(E0),zJ(o0(n0(W[0],W[Y-1])))),W}},xW={getOffsetNanosecondsFor:oX},[WD,w0,YD]=T1(S4,Az,$G,{add:($,Z)=>w0(XJ(0,$,Y0(Z))),subtract:($,Z)=>w0(XJ(1,$,Y0(Z))),until:($,Z,J)=>n(SJ(0,$,M1(Z),J)),since:($,Z,J)=>n(SJ(1,$,M1(Z),J)),round:($,Z)=>w0(zj($,Z)),equals:($,Z)=>sj($,M1(Z)),toZonedDateTime($,Z){let J=y1(Z);return B0(pJ($,a(J.timeZone),I0(J.calendar)))},toZonedDateTimeISO:($,Z)=>B0(pJ($,a(Z))),toLocaleString($,Z,J){let[W,Y]=dO(Z,J,$);return W.format(Y)},toString:($,Z)=>o7(a,V0,$,Z),toJSON:($)=>o7(a,V0,$),valueOf:P$},{from:($)=>w0(M1($)),fromEpochSeconds:($)=>w0(oz($)),fromEpochMilliseconds:($)=>w0(az($)),fromEpochMicroseconds:($)=>w0(tz($)),fromEpochNanoseconds:($)=>w0(rz($)),compare:($,Z)=>xJ(M1($),M1(Z))}),[v4,tP]=T1("TimeZone",($)=>{let Z=lj($);return{branding:"TimeZone",id:Z,o:b4(Z)}},{id:($)=>$.id},{getPossibleInstantsFor:({o:$},Z)=>$.getPossibleInstantsFor(M$(Z)).map((J)=>w0(H0(J))),getOffsetNanosecondsFor:({o:$},Z)=>$.getOffsetNanosecondsFor(M1(Z).epochNanoseconds),getOffsetStringFor($,Z){let J=M1(Z).epochNanoseconds,W=w4(this,xW).getOffsetNanosecondsFor(J);return d$(W)},getPlainDateTimeFor($,Z,J=q){let W=M1(Z).epochNanoseconds,Y=w4(this,xW).getOffsetNanosecondsFor(W);return _0(G0(F$(W,Y),I0(J)))},getInstantFor($,Z,J){let W=M$(Z),Y=m7(J),j=w4(this);return w0(H0(h0(j,W,Y)))},getNextTransition:({o:$},Z)=>dX(1,$,Z),getPreviousTransition:({o:$},Z)=>dX(-1,$,Z),equals($,Z){return!!D4(this,a(Z))},toString:($)=>$.id,toJSON:($)=>$.id},{from($){let Z=a($);return typeof Z=="string"?new v4(Z):Z}}),jD=nX(Object.keys(ZG)),[zD,K$]=T1(A4,wz,RW,{getISOFields:d3,with($,Z,J){return K$(Iz(this,lZ(Z),J))},add:($,Z)=>K$(FJ(0,$,Y0(Z))),subtract:($,Z)=>K$(FJ(1,$,Y0(Z))),until:($,Z,J)=>n(wJ(0,$,H$(Z),J)),since:($,Z,J)=>n(wJ(1,$,H$(Z),J)),round:($,Z)=>K$(Qj($,Z)),equals:($,Z)=>ej($,H$(Z)),toZonedDateTime:($,Z)=>B0(sz(a,f0,s,$,Z)),toPlainDateTime:($,Z)=>_0(nz($,f0(Z))),toLocaleString($,Z,J){let[W,Y]=sO(Z,J,$);return W.format(Y)},toString:ZJ,toJSON:($)=>ZJ($),valueOf:P$},{from:($,Z)=>K$(H$($,Z)),compare:($,Z)=>O4(H$($),H$(Z))}),[XD,T$,GD]=T1(yZ,f(Rz,I0),{...c3,...tO},{getISOFields:d3,getCalendar:h3,with($,Z,J){return T$(Nz(LD,$,this,lZ(Z),J))},add:($,Z,J)=>T$(VJ(iX,0,$,Y0(Z),J)),subtract:($,Z,J)=>T$(VJ(iX,1,$,Y0(Z),J)),until:($,Z,J)=>n(kJ(sX,0,$,cZ(Z),J)),since:($,Z,J)=>n(kJ(sX,1,$,cZ(Z),J)),equals:($,Z)=>tj($,cZ(Z)),toPlainDate($,Z){return j0(lz(u3,$,this,Z))},toLocaleString($,Z,J){let[W,Y]=nO(Z,J,$);return W.format(Y)},toString:e7,toJSON:($)=>e7($),valueOf:P$},{from:($,Z)=>T$(cZ($,Z)),compare:($,Z)=>i$(cZ($),cZ(Z))}),[QD,_0]=T1(t$,f(Ez,I0),{...c3,...bW,...RW},{getISOFields:d3,getCalendar:h3,with($,Z,J){return _0(Tz(u3,$,this,lZ(Z),J))},withCalendar:($,Z)=>_0(K4($,I0(Z))),withPlainDate:($,Z)=>_0(JX($,f0(Z))),withPlainTime:($,Z)=>_0(ZX($,AW(Z))),add:($,Z,J)=>_0(QJ(e$,0,$,Y0(Z),J)),subtract:($,Z,J)=>_0(QJ(e$,1,$,Y0(Z),J)),until:($,Z,J)=>n(bJ(K1,0,$,M$(Z),J)),since:($,Z,J)=>n(bJ(K1,1,$,M$(Z),J)),round:($,Z)=>_0(Gj($,Z)),equals:($,Z)=>oj($,M$(Z)),toZonedDateTime:($,Z,J)=>B0(yz(s,$,a(Z),J)),toPlainDate:($)=>j0(Q0($)),toPlainTime:($)=>K$(X1($)),toPlainYearMonth($){return T$(mz(g4,$,this))},toPlainMonthDay($){return uZ(hz(m4,$,this))},toLocaleString($,Z,J){let[W,Y]=lO(Z,J,$);return W.format(Y)},toString:t7,toJSON:($)=>t7($),valueOf:P$},{from:($,Z)=>_0(M$($,Z)),compare:($,Z)=>AJ(M$($),M$(Z))}),[BD,j0,JG]=T1(a$,f(bz,I0),{...c3,...bW},{getISOFields:d3,getCalendar:h3,with($,Z,J){return j0(Pz(u3,$,this,lZ(Z),J))},withCalendar:($,Z)=>j0(K4($,I0(Z))),add:($,Z,J)=>j0(BJ(e$,0,$,Y0(Z),J)),subtract:($,Z,J)=>j0(BJ(e$,1,$,Y0(Z),J)),until:($,Z,J)=>n(RJ(K1,0,$,f0(Z),J)),since:($,Z,J)=>n(RJ(K1,1,$,f0(Z),J)),equals:($,Z)=>aj($,f0(Z)),toZonedDateTime($,Z){let J=!L0(Z)||Z instanceof v4?{timeZone:Z}:Z;return B0(pz(a,H$,s,$,J))},toPlainDateTime:($,Z)=>_0(cz($,AW(Z))),toPlainYearMonth($){return T$(dz(g4,$,this))},toPlainMonthDay($){return uZ(uz(m4,$,this))},toLocaleString($,Z,J){let[W,Y]=iO(Z,J,$);return W.format(Y)},toString:r7,toJSON:($)=>r7($),valueOf:P$},{from:($,Z)=>j0(f0($,Z)),compare:($,Z)=>i$(f0($),f0(Z))}),kW={fields($,Z,J){return[...Z.call($,J)]}},WG=Object.assign({dateFromFields($,Z,J,W){return JG(Z.call($,Object.assign(Object.create(null),J),W))}},kW),YG=Object.assign({yearMonthFromFields($,Z,J,W){return GD(Z.call($,Object.assign(Object.create(null),J),W))}},kW),jG=Object.assign({monthDayFromFields($,Z,J,W){return JD(Z.call($,Object.assign(Object.create(null),J),W))}},kW),wW={mergeFields($,Z,J,W){return y1(Z.call($,Object.assign(Object.create(null),J),Object.assign(Object.create(null),W)))}},VD=Object.assign({},WG,wW),FD=Object.assign({},YG,wW),UD=Object.assign({},jG,wW),fW={dateAdd($,Z,J,W,Y){return JG(Z.call($,j0(Q0(J,$)),n($0(W)),Y))}},zG=Object.assign({},fW,{dateUntil($,Z,J,W,Y,j){return KD(Z.call($,j0(Q0(J,$)),j0(Q0(W,$)),Object.assign(Object.create(null),j,{largestUnit:f3[Y]})))}}),OD=Object.assign({},fW,{day:aX}),DD=Object.assign({},zG,{day:aX}),g4=P1(YG),y4=P1(WG),m4=P1(jG),LD=P1(FD),u3=P1(VD),HD=P1(UD),e$=P1(fW),K1=P1(zG),iX=P1(OD),sX=P1(DD),[MD,n,KD]=T1(E4,fz,{...$D,blank:Cj},{with:($,Z)=>n(xz($,Z)),negated:($)=>n(Q4($)),abs:($)=>n(xj($)),add:($,Z,J)=>n(HJ(m3,K1,s,0,$,Y0(Z),J)),subtract:($,Z,J)=>n(HJ(m3,K1,s,1,$,Y0(Z),J)),round:($,Z)=>n(Ij(m3,K1,s,$,Z)),total:($,Z)=>jj(m3,K1,s,$,Z),toLocaleString($,Z,J){return Intl.DurationFormat?new Intl.DurationFormat(Z,J).format(this):Y4($)},toString:Y4,toJSON:($)=>Y4($),valueOf:P$},{from:($)=>n(Y0($)),compare:($,Z,J)=>ij(m3,e$,s,Y0($),Y0(Z),J)}),XG={toString:($)=>$.id,toJSON:($)=>$.id,...aO,dateAdd:({id:$,o:Z},J,W,Y)=>j0(Q0(Z.dateAdd(f0(J),Y0(W),Y),$)),dateUntil:({o:$},Z,J,W)=>n($0($.dateUntil(f0(Z),f0(J),aY(W)))),dateFromFields:({id:$,o:Z},J,W)=>j0(vJ(Z,J,W,RY($))),yearMonthFromFields:({id:$,o:Z},J,W)=>T$(gJ(Z,J,W,EY($))),monthDayFromFields:({id:$,o:Z},J,W)=>uZ(yJ(Z,0,J,W,bY($))),fields({o:$},Z){let J=new Set(G1),W=[];for(let Y of Z){if(W0(Y),!J.has(Y))throw RangeError(sJ(Y));J.delete(Y),W.push(Y)}return $.fields(W)},mergeFields:({o:$},Z,J)=>$.mergeFields(A7(b7(Z)),A7(b7(J)))},[qW]=T1("Calendar",($)=>{let Z=Xz($);return{branding:"Calendar",id:Z,o:hZ(Z)}},{id:($)=>$.id},XG,{from($){let Z=I0($);return typeof Z=="string"?new qW(Z):Z}}),TD=nX(Object.keys(XG).slice(4)),[PD,B0]=T1(d1,f(Sz,I0,a),{...$G,...c3,...uX(bW),...uX(RW),offset:($)=>d$(IW($).offsetNanoseconds),offsetNanoseconds:($)=>IW($).offsetNanoseconds,timeZoneId:($)=>T0($.timeZone),hoursInDay:($)=>Bj(s,$)},{getISOFields:($)=>Nj(V0,$),getCalendar:h3,getTimeZone:({timeZone:$})=>typeof $=="string"?new v4($):$,with($,Z,J){return B0(Kz(u3,s,$,this,lZ(Z),J))},withCalendar:($,Z)=>B0(K4($,I0(Z))),withTimeZone:($,Z)=>B0(WX($,a(Z))),withPlainDate:($,Z)=>B0($X(s,$,f0(Z))),withPlainTime:($,Z)=>B0(ez(s,$,AW(Z))),add:($,Z,J)=>B0(GJ(e$,s,0,$,Y0(Z),J)),subtract:($,Z,J)=>B0(GJ(e$,s,1,$,Y0(Z),J)),until:($,Z,J)=>n($0(EJ(K1,s,0,$,dZ(Z),J))),since:($,Z,J)=>n($0(EJ(K1,s,1,$,dZ(Z),J))),round:($,Z)=>B0(Xj(s,$,Z)),startOfDay:($)=>B0(Vj(s,$)),equals:($,Z)=>nj($,dZ(Z)),toInstant:($)=>w0(qz($)),toPlainDateTime:($)=>_0(cJ(V0,$)),toPlainDate:($)=>j0(dJ(V0,$)),toPlainTime:($)=>K$(uJ(V0,$)),toPlainYearMonth($){return T$(vz(g4,$,this))},toPlainMonthDay($){return uZ(gz(m4,$,this))},toLocaleString($,Z,J={}){let[W,Y]=uO(Z,J,$);return W.format(Y)},toString:($,Z)=>a7(V0,$,Z),toJSON:($)=>a7(V0,$),valueOf:P$},{from:($,Z)=>B0(dZ($,Z)),compare:($,Z)=>CJ(dZ($),dZ(Z))}),ND=Object.defineProperties({},{...c6("Temporal.Now"),...h$({timeZoneId:()=>p1(),instant:()=>w0(H0(R3())),zonedDateTime:($,Z=p1())=>B0(N0(R3(),a(Z),I0($))),zonedDateTimeISO:($=p1())=>B0(N0(R3(),a($),q)),plainDateTime:($,Z=p1())=>_0(G0(vZ(V0(a(Z))),I0($))),plainDateTimeISO:($=p1())=>_0(G0(vZ(V0(a($))),q)),plainDate:($,Z=p1())=>j0(Q0(vZ(V0(a(Z))),I0($))),plainDateISO:($=p1())=>j0(Q0(vZ(V0(a($))),q)),plainTimeISO:($=p1())=>K$(X1(vZ(V0(a($)))))})}),iZ=Object.defineProperties({},{...c6("Temporal"),...h$({PlainYearMonth:XD,PlainMonthDay:ZD,PlainDate:BD,PlainTime:zD,PlainDateTime:QD,ZonedDateTime:PD,Instant:WD,Calendar:qW,TimeZone:v4,Duration:MD,Now:ND})}),_D=yO(),vW=new WeakMap,ID=Object.defineProperties(Object.create(Intl),h$({DateTimeFormat:_D}));var h4="x-gemi-socket";var WN="gemi.v1",GG="/__gemi/socket",YN=/^[A-Za-z0-9_-]{1,32}$/,jN={Normal:1000,UnsupportedData:1003,PolicyViolation:1008,Restart:1012,TryAgainLater:1013,Revoked:4001};function QN($){return $}function QG(){return{driver:"memory",redis:{},maxEventBytes:16384,warnEventBytes:4096,path:GG,allowedOrigins:[],maxConnectionsPerProcess:1e4,maxConnectionsPerIp:100,maxConnectionsPerUser:50,maxChannelsPerSocket:50,maxInboundMessageBytes:16384,backpressureLimit:1048576,idleTimeout:120,heartbeatMs:25000,subscribeRate:{limit:300,windowMs:60000}}}import{hkdfSync as xD,randomBytes as CD}from"crypto";function AD($=process.env.SECRET){if(!$)return"gemi:bc:";return`gemi:bc:${Buffer.from(xD("sha256",$,"gemi","gemi.broadcast.prefix",4)).toString("hex")}:`}var SD="__control",gW=250,ED=1e4,bD=15000;class yW{config;prefix;controlChannel;instanceId=CD(9).toString("base64url");subscribeTimeoutMs;healthCheckMs;publisher=null;subscriber=null;ready=null;deliver=null;hooks;wanted=new Set;active=new Set;chains=new Map;connectedOnce=!1;reconnectAttempt=0;reconnectTimer=null;healthTimer=null;closed=!1;constructor($={}){this.config=$;this.prefix=$.prefix??AD(),this.controlChannel=this.prefix+SD,this.subscribeTimeoutMs=$.subscribeTimeoutMs??5000,this.healthCheckMs=$.healthCheckMs??30000}get connected(){return this.subscriber!==null&&this.ready===null}publish($,Z){return this.send(this.prefix+$,Z)}async revoke($){this.hooks?.onRevoke?.($);let Z={op:"revoke",from:this.instanceId,r:$};try{await this.send(this.controlChannel,JSON.stringify(Z))}catch(J){throw Error(`The broadcast revocation ${JSON.stringify($)} could not reach the other instances.`,{cause:J})}}async start($,Z){this.closed=!1,this.deliver=$,this.hooks=Z,this.connectSubscriber(),this.startHealthCheck();try{await this.whenReady()}catch{console.warn("[gemi] Broadcast: Redis is not reachable yet; sockets get events once it is.")}}topicAdded($){return this.wanted.add($),this.sync($,!0)}topicRemoved($){return this.wanted.delete($),this.sync($,!1)}async close(){if(this.closed=!0,this.deliver=null,this.hooks=void 0,this.reconnectTimer)clearTimeout(this.reconnectTimer);if(this.reconnectTimer=null,this.healthTimer)clearInterval(this.healthTimer);this.healthTimer=null;let $=[this.subscriber,this.publisher];this.subscriber=null,this.publisher=null,this.ready=null,this.wanted.clear(),this.active.clear(),this.chains.clear();for(let Z of $){if(!Z)continue;Z.onclose=null;try{Z.close()}catch{}}}async send($,Z){let J=this.publisherClient();try{await J.publish($,Z)}catch{if(this.closed)throw Error("The broadcast driver is closed.");this.dropPublisher(J),await this.publisherClient().publish($,Z)}}dropPublisher($){if(this.publisher!==$)return;this.publisher=null,$.onclose=null;try{$.close()}catch{}}publisherClient(){if(this.publisher)return this.publisher;let $=this.createClient("publisher");return $.onclose=()=>{if(this.publisher===$)this.publisher=null},this.publisher=$,$}createClient($){if(this.config.createClient)return this.config.createClient($);let Z=globalThis.Bun?.RedisClient;if(typeof Z!=="function")throw Error("The redis broadcast driver needs Bun's built-in Redis client. Run the app under Bun.");let J=$==="subscriber"?{...this.config.options,autoReconnect:!1}:{...this.config.options};return new Z(this.config.url,J)}connectSubscriber(){if(this.closed||this.ready)return;let $;try{$=this.createClient("subscriber")}catch(J){console.error("[gemi] Broadcast: the Redis subscriber could not be created.",J),this.scheduleReconnect();return}this.subscriber=$,this.active.clear(),$.onclose=()=>this.lost($);let Z=l3((async()=>{await $.connect(),await $.subscribe(this.controlChannel,this.onMessage);let J=[...this.wanted];if(await Promise.all(J.map((W)=>$.subscribe(this.prefix+W,this.onMessage))),this.subscriber!==$)throw Error("Replaced.");for(let W of J)this.active.add(W);return $})(),bD,"connect");this.ready=Z,Z.then(()=>{if(this.subscriber!==$)return;this.ready=null,this.reconnectAttempt=0;for(let J of this.active)if(!this.wanted.has(J))this.sync(J,!1).catch(()=>{});if(this.connectedOnce)this.hooks?.onGap?.();this.connectedOnce=!0},(J)=>{if(this.subscriber!==$||this.closed)return;console.warn(`[gemi] Broadcast: the Redis subscriber could not connect (${BG(J)}); retrying.`),this.drop($)})}lost($){if(this.subscriber!==$||this.closed)return;if(this.ready===null)console.warn("[gemi] Broadcast: the Redis subscriber connection dropped; reconnecting.");this.drop($)}drop($){if(this.subscriber!==$)return;this.subscriber=null,this.ready=null,this.active.clear(),$.onclose=null;try{$.close()}catch{}this.scheduleReconnect()}scheduleReconnect(){if(this.closed||this.reconnectTimer)return;let $=Math.min(ED,gW*2**this.reconnectAttempt);this.reconnectAttempt=Math.min(this.reconnectAttempt+1,16);let Z=Math.max(gW,Math.floor(Math.random()*$));this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connectSubscriber()},Z),this.reconnectTimer.unref?.()}startHealthCheck(){if(this.healthCheckMs<=0||this.healthTimer)return;this.healthTimer=setInterval(()=>{let $=this.subscriber;if(!$||this.ready)return;l3($.ping(),this.subscribeTimeoutMs,"ping").catch((Z)=>{if(this.subscriber!==$)return;console.warn(`[gemi] Broadcast: the Redis subscriber did not answer a ping (${BG(Z)}); reconnecting.`),this.drop($)})},this.healthCheckMs),this.healthTimer.unref?.()}async whenReady(){if(this.closed)throw Error("The broadcast driver is closed.");let $=Date.now()+this.subscribeTimeoutMs;for(;;){if(this.subscriber&&!this.ready)return this.subscriber;let Z=$-Date.now();if(Z<=0)throw Error("Redis did not answer in time.");let J=this.ready??RD(Math.min(Z,gW));await l3(J,Z,"subscribe").catch((W)=>{if(Date.now()>=$)throw W})}}sync($,Z){let W=(this.chains.get($)??Promise.resolve()).catch(()=>{}).then(()=>this.reconcile($,Z));this.chains.set($,W);let Y=()=>{if(this.chains.get($)===W)this.chains.delete($)};return W.then(Y,Y),W}async reconcile($,Z){if(!this.wanted.has($)){if(!this.active.has($)||!this.connected)return;let Y=this.subscriber;this.active.delete($);try{await l3(Y.unsubscribe(this.prefix+$),this.subscribeTimeoutMs,"unsubscribe")}catch(j){if(this.subscriber===Y)this.drop(Y);throw j}return}if(!Z)return;let W=await this.whenReady();if(!this.wanted.has($)||this.active.has($))return;try{await l3(W.subscribe(this.prefix+$,this.onMessage),this.subscribeTimeoutMs,"subscribe")}catch(Y){if(this.subscriber===W)this.drop(W);throw Y}if(this.subscriber===W)this.active.add($)}onMessage=($,Z)=>{if(Z===this.controlChannel){this.onControl($);return}if(!Z.startsWith(this.prefix))return;this.deliver?.(Z.slice(this.prefix.length),$)};onControl($){let Z;try{Z=JSON.parse($)}catch{return}if(Z?.op!=="revoke"||Z.from===this.instanceId)return;let J=Z.r;if(J&&typeof J.user==="string")this.hooks?.onRevoke?.({user:J.user});else if(J&&typeof J.topic==="string")this.hooks?.onRevoke?.({topic:J.topic})}}function l3($,Z,J){let W;return Promise.race([$,new Promise((Y,j)=>{W=setTimeout(()=>j(Error(`Redis ${J} timed out after ${Z} ms.`)),Z)})]).finally(()=>clearTimeout(W))}function RD($){return new Promise((Z)=>setTimeout(Z,$))}function BG($){return $ instanceof Error?$.message:String($)}import{createHmac as kD,hkdfSync as wD,randomBytes as VG}from"crypto";function FG($){return kD("sha256",fD()).update($).digest("base64url").slice(0,22)}var p4=null;function fD(){let $=process.env.SECRET||void 0;if(p4&&p4.secret===$)return p4.key;let Z=$?Buffer.from(wD("sha256",$,"gemi","gemi.broadcast.socket-tag",32)):VG(32);return p4={secret:$,key:Z},Z}function ON(){return VG(16).toString("base64url")}var qD=/^[A-Za-z0-9_-]{8,64}$/;function mW($){return typeof $==="string"&&qD.test($)}function UG($,Z,J,W){let Y={op:"ev",t:$,ev:Z};if(J!==void 0)Y.d=J;if(W)Y.x=W;return JSON.stringify(Y)}class DG extends Error{bytes;limit;constructor($,Z,J){super(`The broadcast "${J}" is ${$} bytes, over the limit of ${Z}. Send ids and a change hint, and let the client fetch the data over HTTP; or raise maxEventBytes in app/config/broadcast.ts.`);this.bytes=$;this.limit=Z;this.name="BroadcastPayloadTooLargeError"}}class c0{options;static token="broadcast";config;driver;warnedAboutSize=new Set;started=!1;hooks;channelRouter;constructor($={},Z={}){this.options=Z;this.config=N1(QG(),$),this.driver=yD(this.config,Z.application)}get channels(){if(this.channelRouter===void 0)this.channelRouter=this.options.channels?new this.options.channels:null;return this.channelRouter}to($,...Z){return new i3(this,c4($,Z[0]),null)}toUser($){return new i3(this,{topic:OZ($),pattern:U0},null)}toOthers($){return new LG(this,gD($))}broadcastEvent($){let Z=$.broadcastOn(),J=Array.isArray(Z)?Z:[Z],W=$.broadcastAs(),Y=$.broadcastWith(),j=J.map((z)=>this.prepare(c4(z,void 0),W,Y,null));for(let{sent:z,frame:X}of j)this.hand(z,X)}send($,Z,J,W){let{sent:Y,frame:j}=this.prepare($,Z,J,W);this.hand(Y,j)}prepare($,Z,J,W){m2(Z);let Y;try{Y=UG($.topic,Z,J,W?FG(W):null)}catch(z){throw TypeError(`The broadcast "${Z}" could not be encoded. Payloads must be JSON.`,{cause:z})}return this.checkSize(Z,Y),{sent:{topic:$.topic,...$.pattern?{pattern:$.pattern}:{},event:Z,data:JSON.parse(Y).d,...W?{except:W}:{}},frame:Y}}hand($,Z){sZ(()=>this.publish($,Z))}publish($,Z){let J=(W)=>console.error(`[gemi] The broadcast "${$.event}" on "${$.topic}" could not be published.`,W);try{let W=this.driver.publish($.topic,Z);if(W&&typeof W.catch==="function")W.catch(J)}catch(W){J(W)}}get isStarted(){return this.started}async start($,Z){if(this.started)throw Error("The broadcast driver was already started in this process.");this.started=!0,this.hooks=Z;try{await this.driver.start($,Z)}catch(J){throw this.started=!1,this.hooks=void 0,J}}topicAdded($){return this.driver.topicAdded?.($)}topicRemoved($){return this.driver.topicRemoved?.($)}async close(){this.started=!1,this.hooks=void 0,await this.driver.close()}revoke($){let Z=vD($);sZ(()=>this.sendRevocation(Z))}sendRevocation($){let Z=(J)=>console.error("[gemi] A broadcast revocation could not be sent.",J);try{if(typeof this.driver.revoke==="function"){let J=this.driver.revoke($);if(J&&typeof J.catch==="function")J.catch(Z);return}this.hooks?.onRevoke?.($)}catch(J){Z(J)}}checkSize($,Z){let J=Buffer.byteLength(Z,"utf8");if(J>this.config.maxEventBytes)throw new DG(J,this.config.maxEventBytes,$);let W=this.config.warnEventBytes;if(W!==!1&&J>W&&!this.warnedAboutSize.has($))this.warnedAboutSize.add($),console.warn(`[gemi] The broadcast "${$}" is ${J} bytes, over ${W}. Broadcasts are change hints: send ids and let the client fetch the data over HTTP. Warned once per event name.`)}}class i3{manager;target;except;constructor($,Z,J){this.manager=$;this.target=Z;this.except=J}emit($,...Z){this.manager.send(this.target,$,Z[0],this.except)}}class LG{manager;except;constructor($,Z){this.manager=$;this.except=Z}to($,...Z){return new i3(this.manager,c4($,Z[0]),this.except)}toUser($){return new i3(this.manager,{topic:OZ($),pattern:U0},this.except)}}function c4($,Z){if(y2($))return{topic:b8($.topic),...$.pattern?{pattern:$.pattern}:{}};if(Z!==void 0||$.includes(":"))return{topic:F3($,Z??{}),pattern:$};if($===U0)throw new u('"user" is not a topic: the "user" channel resolves to user.<id> per subscriber. Emit with Broadcast.toUser(user).');return{topic:b8($)}}function vD($){if($&&typeof $==="object"&&"user"in $)return{user:OZ($.user).slice(U0.length+1)};if($&&typeof $==="object"&&"channel"in $)return{topic:c4($.channel,$.params).topic};throw new u("Broadcast.revoke takes { user } or { channel }.")}function gD($){if($===null||$===void 0)return null;if(typeof $==="string")return mW($)?$:null;let J=($ instanceof Request?$.headers:("rawRequest"in $)?$.rawRequest.headers:$.headers)?.get(h4);return mW(J)?J:null}function yD($,Z){let J=$.driver;if(J===void 0||J==="memory")return new OG;if(J==="redis"){let W=Z?.config.get("redis",{})??{},Y=$.redis??{};return new yW({url:Y.url??W.url??process.env.REDIS_URL,options:Y.options??W.options,prefix:Y.prefix,subscribeTimeoutMs:Y.subscribeTimeoutMs,healthCheckMs:Y.healthCheckMs})}if(typeof J==="function"){if(!Z)throw Error("A broadcast driver factory needs the application to be called with.");return J(Z)}if(typeof J==="object"&&J!==null&&typeof J.publish==="function")return J;throw Error(`Unknown broadcast driver "${String(J)}" in app/config/broadcast.ts. Use "memory" or "redis", or pass a BroadcastDriver.`)}class hW extends Error{code;constructor($,Z=`OAuth callback failed: ${$}`){super(Z);this.name="OAuthCallbackError",this.code=$}}class mD{linkByEmail=!0;createUsers=!0;createUsersWithoutEmail=!1;clientFor($){return Promise.resolve(void 0)}async isAvailable($){return await this.clientFor($)!==null}async redirectUriFor($){return(await this.clientFor($))?.redirectUri}}import{createHash as pW,createHmac as hD,randomBytes as HG,timingSafeEqual as TG}from"crypto";var n3=600,d4="gemi_oauth",pD=`__Host-${d4}`;function nZ($,Z=d4){if(Z===d4)return $?pD:d4;return $?`__Host-${Z}`:Z}function s3($){return $.toString("base64url")}function PG($){return hD("sha256",KZ()).update(`gemi-oauth-state:${$}`).digest()}function MG($,Z){let J=pW("sha256").update($).digest(),W=pW("sha256").update(Z).digest();return TG(J,W)&&$.length===Z.length}function u4($,Z=Date.now(),J={}){let W=s3(HG(32)),Y=s3(HG(32)),j=cD(Y),z={provider:$,state:W,codeVerifier:Y,expiresAt:Z+n3*1000,...J.subject!==void 0?{subject:J.subject}:{},...J.returnTo!==void 0?{returnTo:J.returnTo}:{},...J.redirectUri!==void 0?{redirectUri:J.redirectUri}:{}};return{state:W,codeVerifier:Y,codeChallenge:j,cookieValue:dD(z)}}function cD($){return s3(pW("sha256").update($).digest())}function dD($){let Z=s3(Buffer.from(JSON.stringify($)));return`${Z}.${s3(PG(Z))}`}function uD($){if(typeof $!=="string"||$==="")return null;let Z=$.indexOf(".");if(Z<=0||Z!==$.lastIndexOf("."))return null;let J=$.slice(0,Z),W=Buffer.from($.slice(Z+1),"base64url"),Y=PG(J);if(W.length!==Y.length||!TG(W,Y))return null;try{let j=JSON.parse(Buffer.from(J,"base64url").toString("utf8"));if(typeof j?.provider!=="string"||typeof j?.state!=="string"||typeof j?.codeVerifier!=="string"||typeof j?.expiresAt!=="number"||j.subject!==void 0&&typeof j.subject!=="string"||j.returnTo!==void 0&&typeof j.returnTo!=="string"||j.redirectUri!==void 0&&typeof j.redirectUri!=="string")return null;return j}catch{return null}}var N$=new Map,KG=1e4;function lD($,Z,J){if(N$.size>=KG){for(let[W,Y]of N$)if(Y<=J)N$.delete(W);while(N$.size>=KG){let W=N$.keys().next().value;if(W===void 0)break;N$.delete(W)}}N$.set($,Z)}function l4($){let Z=$.now??Date.now();if(!$.cookieValue||!$.returnedState)return{ok:!1,reason:"missing_state"};let J=uD($.cookieValue);if(!J)return{ok:!1,reason:"invalid_state"};let W=MG(J.state,$.returnedState),Y=MG(J.provider,$.provider);if(!W||!Y)return{ok:!1,reason:"invalid_state"};if(J.expiresAt<=Z)return{ok:!1,reason:"expired_state"};if(N$.has(J.state))return{ok:!1,reason:"invalid_state"};return lD(J.state,J.expiresAt,Z),{ok:!0,payload:J}}var cW=new WeakMap;function sD($){let Z=cW.get($);if(!Z)Z=$(iD(32).toString("hex")),cW.set($,Z),Z.catch(()=>cW.delete($));return Z}async function i4($,Z,J){if(typeof J==="string"&&J!=="")return await $.verifyPassword(Z,J);try{await $.verifyPassword(Z,await sD($.hashPassword))}catch{}return!1}async function $Z($,Z){let J=Z.user??Z.session?.user;if(!J||!$.onAuthenticated)return;let{password:W,...Y}=J;await $.onAuthenticated({...Z,user:Y})}class uW extends Error{}function dW($){return typeof $==="string"&&$!==""?$:null}function NG($){return q$($)}var nD=256;function _G($){return typeof $==="string"&&$!==""&&$.length<=nD?$:null}function IG($){let{password:Z,code:J,...W}=$;return W}var n4="intended_url";function AG($){if($.cookies.get(n4))$.ctx().setCookie(n4,"",{maxAge:-1})}function xG($){let Z=$.cookies.get(n4);if(!Z)return null;AG($);try{return U1(decodeURIComponent(Z),"")||null}catch{return null}}class lW extends C{schema={email:{required:"Email is required",string:"Invalid email",email:"Invalid email"},password:{required:"Password is required"}}}class SG extends C{schema={email:{required:"Email is required",email:"Invalid email"}}}class EG extends C{schema={password:{required:"Password is required",password:"Invalid password"}}}function s4(){throw new K0("Not found",{status:404})}async function u1($,Z){if(!await k1(M(E).config[$],Z))s4()}async function o3($,Z,J,W){let{config:Y}=M(E),j={signIn:"sign-in",signUp:"sign-up",forgot:"forgot",reset:"reset"}[$];await v$(j,Z,J,Y.passwordLimits?.[$]??{},Y.rateLimitKey,W)}async function CG($,Z,J){let{config:W}=M(E);await o3("signIn",q$($),J,async(Y)=>{if(Y==="perEmail"&&typeof Z==="string")await i4(W,Z,null)})}async function oZ($){return await k1(M(E).config.verifyEmail,$)}class Z0 extends O3{async me(){let $=await q0.user();if(!$)throw new o8;return $}async verifyEmail($=new C){await u1("password",$);let Z=await $.input(),{userProvider:J}=M(E),W=dW(Z.get("token"));if(!W)return{email:null};let Y=await J.findUserByVerificationToken(W);if(!Y)return{email:null};return await J.verifyUser(Y.email),{email:Y.email}}async signInWithMagicLink($=new C){let Z=M(E),{userProvider:J}=Z;if(!await k1(Z.config.magicLink,$)&&!await k1(Z.config.emailCode.enabled,$))s4();let W=dW($.search.get("token")),Y=null;try{Y=q$(decodeURIComponent($.search.get("email")??""))}catch{}if(await v$("link",null,$,{perIp:Z.config.emailCode.verifyLimit.perIp},Z.config.rateLimitKey),!Y||!W||!await Z.verifyMagicLinkToken(Y,W))return{error:"Invalid token"};await J.verifyUser(Y);let j=await Z.createOrUpdateSession({email:Y});return $.ctx().setCookie("access_token",j.token,M(E).accessTokenCookieOptions($,j.expiresAt)),await Z.config.onSignIn(j,$.search.toJSON(),{req:$}),await $Z(Z.config,{session:j,isNewUser:!1,method:"magic-link",req:$}),{session:j}}async verifyPinRequest($){await u1("magicLink",$);let Z=M(E),J=await $.input(),{email:W,pin:Y}=J.toJSON(),j=q$(W),z=_G(Y);if(await v$("verify",j,$,Z.config.emailCode.verifyLimit,Z.config.rateLimitKey),!j||!z)throw new d({pin:["Invalid pin"]});let X=await Z.verifyOneTimeCode(j,z);if(X.status==="too_many_attempts")throw new d({pin:["Too many attempts"]});if(X.status!=="ok")throw new d({pin:["Invalid pin"]});return await Z.userProvider.verifyUser(j),j}async signInWithPinV2($=new C){let Z=M(E),J=await this.verifyPinRequest($),W=await Z.createOrUpdateSessionV2({email:J});return $.ctx().setCookie("access_token",W.token,M(E).accessTokenCookieOptions($,W.expiresAt)),await Z.config.onSignIn(W,$.search.toJSON(),{req:$}),await $Z(Z.config,{session:W,isNewUser:!1,method:"magic-link",req:$}),W}async signInWithPin($=new C){let Z=M(E),J=await this.verifyPinRequest($),W=await Z.createOrUpdateSession({email:J});return $.ctx().setCookie("access_token",W.token,M(E).accessTokenCookieOptions($,W.expiresAt)),await Z.config.onSignIn(W,$.search.toJSON(),{req:$}),await $Z(Z.config,{session:W,isNewUser:!1,method:"magic-link",req:$}),{session:W}}async signInV2($=new lW){await u1("password",$);let Z=await $.input(),{email:J,password:W}=Z.toJSON(),Y=J.toLowerCase().trim(),j=M(E);await CG(J,W,$);let z=await j.userProvider.findUserByEmailAddress(Y,await oZ($)),X=typeof W==="string"&&await i4(j.config,W,z?.password);if(!z||!X)throw new d({invalid_credentials:["Invalid credentials"]});let G=await j.createOrUpdateSessionV2({email:z.email,id:z.id});$.ctx().setCookie("access_token",G.token,M(E).accessTokenCookieOptions($,G.expiresAt)),await j.config.onSignIn(z,$.search.toJSON(),{req:$}),await $Z(j.config,{session:G,user:z,isNewUser:!1,method:"password",req:$});let{password:Q,...V}=z;return V}async signIn($=new lW){await u1("password",$);let Z=await $.input(),{email:J,password:W}=Z.toJSON(),Y=J.toLowerCase().trim(),j=M(E);await CG(J,W,$);let z=await j.userProvider.findUserByEmailAddress(Y,await oZ($)),X=typeof W==="string"&&await i4(j.config,W,z?.password);if(!z||!X)throw new d({invalid_credentials:["Invalid credentials"]});let G=await j.createOrUpdateSession({email:z.email,id:z.id});$.ctx().setCookie("access_token",G.token,M(E).accessTokenCookieOptions($,G.expiresAt)),await j.config.onSignIn(z,$.search.toJSON(),{req:$}),await $Z(j.config,{session:G,user:z,isNewUser:!1,method:"password",req:$});let{password:Q,...V}=z;return V}async signUp(){let $=M(E),{userProvider:Z,config:J}=$,W=new J.signUpRequest;await u1("password",W);let Y=await W.input(),{email:j,password:z,name:X,invitationId:G}=Y.toJSON(),Q={method:"password",input:IG(Y.toJSON()),req:W},V=NG(j);if(await o3("signUp",V,W),!V)throw new d({email:["Invalid email"]});if(z!=null&&typeof z!=="string")throw new d({password:["Invalid password"]});if(G!=null&&typeof G!=="string")throw new d({invitationId:["Invalid invitation"]});if(await Z.findUserByEmailAddress(V,!1))throw new d({email:["Email address already exists"]});let B=await J.hashPassword(z),U=M(c).detectLocale(W),D;if(G)D=await Z.findInvitation(G,V);let O,L="";if(D)O=await Z.transaction(async()=>{await Z.deleteInvitationById(G);let H=await Z.createUser({email:V,name:X,password:B,emailVerifiedAt:new Date,locale:U});return await Z.createAccount({organizationId:D.organizationId,userId:H.id,organizationRole:D.role}),await J.onUserCreated(H,Q),H});else{if(L=await J.generateEmailVerificationToken(V),typeof J.verifyEmail==="function"&&!await oZ(W))L="";O=await Z.transaction(async()=>{let H=await Z.createUser({email:V,name:X,password:B,verificationToken:L,locale:U});return await J.onUserCreated(H,Q),H})}return await J.onSignUp(O,L,W.search.toJSON(),{req:W}),O}async signOut($=new C){let Z=E$($),J=M(E),{config:W}=J,Y=await J.revokeSession(Z,$.headers.get("User-Agent"));if($.ctx().setCookie("access_token","",M(E).accessTokenCookieOptions($,new Date(0))),M(E).cookieDomain($))$.ctx().setCookie("access_token","",{...M(E).accessTokenCookieOptions($,new Date(0)),domain:void 0});if(Y?.user)oD(Y.user),Y.user.extension=await W.extendSession(Y.user),await W.onSignOut(Y.user,{req:$});return{}}async forgotPassword($=new SG){await u1("password",$);let Z=await $.input(),J=NG(Z.get("email"));if(await o3("forgot",J,$),!J)return{};let{userProvider:W,config:Y}=M(E),j=await W.findUserByEmailAddress(J,await oZ($));if(!j)return{};let z=await Y.generateForgotPasswordToken(j);return await W.createPasswordResetToken({user:j,token:z}),await Y.onForgotPassword(j,z,{req:$}),{}}async resetPassword($=new EG){await u1("password",$);let{userProvider:Z,config:J}=M(E),W=await $.input(),{password:Y,token:j}=W.toJSON(),z=dW(j);await o3("reset",null,$);let X=z?await Z.findPasswordResetToken({token:z}):null;if(!X)throw new d({token:["Invalid token"]});if(iZ.Instant.from(X.createdAt.toISOString()).add({hours:24}).until(iZ.Now.instant()).sign>=0)throw new d({token:["Token expired"]});await Z.deletePasswordResetToken({token:z});let Q=await Z.findUserByEmailAddress(X.user.email,await oZ($));if(!Q)throw new d({email:["User not found"]});let V=await J.hashPassword(Y);return await Z.updateUserPassword({id:Q.id,password:V}),await Z.deleteAllUserSessions(Q.id),await J.onResetPassword(Q,{req:$}),{}}async changePassword($=new C){await u1("password",$);let{userProvider:Z,config:J}=M(E),W=await q0.user(),Y=await $.input(),{oldPassword:j,newPassword:z}=Y.toJSON();if(await o3("signIn",q$(W?.email),$),typeof z!=="string")throw new d({newPassword:["Invalid password"]});let X=await Z.findUserByEmailAddress(W.email,await oZ($));if(!(typeof j==="string"&&await i4(J,j,X?.password)))throw new d({oldPassword:["Incorrect password"]});let Q=await J.hashPassword(z);return await Z.updateUserPassword({id:W.id,password:Q}),await Z.deleteAllUserSessions(W.id),{}}async oauthRedirect($=new C){let{provider:Z}=$.params,J=M(E).config.oauthProviders,W=Object.hasOwn(J,Z),Y=await PZ(J,Z,$);if(!Y){if(W)throw new K0("Not found",{status:404});throw Error(`Invalid provider: ${Z}`)}let j=DZ($.rawRequest),z=U1($.search.get(l0),"");if(z)$.ctx().setCookie(n4,encodeURIComponent(z),{httpOnly:!0,sameSite:"Lax",secure:j,maxAge:600});else AG($);let X=typeof Y.redirectUriFor==="function"?await Y.redirectUriFor($):void 0,{state:G,codeChallenge:Q,cookieValue:V}=u4(Z,Date.now(),X!==void 0?{redirectUri:X}:{});return $.ctx().setCookie(nZ(j),V,{httpOnly:!0,sameSite:"Lax",secure:j,maxAge:n3}),{destination:await Y.getRedirectUrl($,{state:G,codeChallenge:Q,codeChallengeMethod:"S256"})}}async oauthCallback($=new C){let{provider:Z}=$.params,J=M(E),{userProvider:W,config:Y}=J,j=Object.hasOwn(Y.oauthProviders,Z),z=await PZ(Y.oauthProviders,Z,$);if(j&&!z)throw new K0("Not found",{status:404});let X=DZ($.rawRequest),G=nZ(X),Q=$.cookies.get(G);if(Q!==void 0&&Q!==null)$.ctx().setCookie(G,"",{httpOnly:!0,sameSite:"Lax",secure:X,maxAge:-1});if(!z)return this.oauthFailure($,"unknown_provider");let V=$.search.get("error");if(V)return this.oauthFailure($,/^[a-z0-9_]{1,64}$/.test(V)?V:"provider_error");let F=l4({provider:Z,cookieValue:Q,returnedState:$.search.get("state")});if("reason"in F)return console.error(`Authentication error: OAuth callback refused (${F.reason})`),this.oauthFailure($,F.reason);if(F.payload.redirectUri!==void 0&&typeof z.redirectUriFor==="function"){let N=await z.redirectUriFor($);if(N!==void 0&&N!==F.payload.redirectUri)return console.error("Authentication error: OAuth callback refused (redirect_mismatch)"),this.oauthFailure($,"redirect_mismatch")}if(!$.search.get("code"))return this.oauthFailure($,"missing_code");let B;try{B=await z.onCallback($,{state:F.payload.state,codeVerifier:F.payload.codeVerifier})}catch(N){if(N instanceof hW)return this.oauthFailure($,N.code);return console.error("Authentication error: OAuth provider callback failed",N),this.oauthFailure($,"provider_error")}let{name:U,username:D,providerId:O,emailVerified:L}=B??{},H=typeof B?.email==="string"?B.email:void 0,T=H?I6(H):null,K=O?await W.findUserBySocialAccount(Z,O):null,I="signin",b=!K&&!T&&!H&&!!O&&z.createUsersWithoutEmail===!0;if(!K&&b){if(z.createUsers===!1)return console.error(`Authentication error: a ${Z} sign-in is not linked to a user, and ${Z} does not create users`),this.oauthFailure($,"signup_disabled");try{K=await this.createOAuthUserWithoutEmail({provider:Z,providerId:O,name:U,username:D,locale:M(c).detectLocale($),req:$}),I="signup"}catch(N){let g=await W.findUserBySocialAccount(Z,O);if(!g)throw N;K=g}}if(!K){if(!T)return console.error("Authentication error: No usable email returned from OAuth provider callback"),this.oauthFailure($,H?"invalid_email":O?"missing_email":"no_identity");if(L===!1)return console.error("Authentication error: OAuth provider returned an unverified email"),this.oauthFailure($,"email_not_verified");let N=M(c).detectLocale($);try{let g=await this.linkOAuthAccount({provider:Z,providerId:O,email:T,rawEmail:H,name:U,username:D,locale:N,req:$,linkExisting:z.linkByEmail!==!1,createUser:z.createUsers!==!1});if(g==="account_exists")return console.error(`Authentication error: a ${Z} sign-in matched an existing user by email, and ${Z} does not link by email`),this.oauthFailure($,"account_exists");if(g==="signup_disabled")return console.error(`Authentication error: a ${Z} sign-in is not linked to a user, and ${Z} does not create users`),this.oauthFailure($,"signup_disabled");if(g)K=g.user,I=g.action}catch(g){let _=O?await W.findUserBySocialAccount(Z,O):null;if(!_)throw g;K=_}if(!K)return this.oauthFailure($,"account_conflict")}let S=await J.createOrUpdateSessionV2({email:K.email,id:K.id});if($.ctx().setCookie("access_token",S.token,M(E).accessTokenCookieOptions($,S.expiresAt)),I==="signup")await Y.onSignUp(K,"",$.search.toJSON(),{req:$});else await Y.onSignIn(K,$.search.toJSON(),{req:$});await $Z(J.config,{session:S,user:K,isNewUser:I==="signup",method:"oauth",req:$});let R=xG($)??Y.redirectPath,w=Y.oauthCompleteProfilePath?U1(Y.oauthCompleteProfilePath,""):"";if(w&&!K.email){let N=new URL(w,"http://gemi.invalid");N.searchParams.set(l0,R),R=`${N.pathname}${N.search}${N.hash}`}return{session:S,redirectTo:R}}async createOAuthUserWithoutEmail($){let{userProvider:Z,config:J}=M(E);return await Z.transaction(async()=>{let W=await Z.createUser({email:null,name:$.name??$.username??"",locale:$.locale});return await Z.createSocialAccount({provider:$.provider,providerId:$.providerId,userId:W.id,username:$.username,expiresAt:new Date,accessToken:"",refreshToken:""}),await J.onUserCreated(W,{method:"oauth",input:{},req:$.req}),W})}oauthFailure($,Z){let J=xG($),W=M(E).config.oauthFailurePath;if(W){let Y=U1(W,"");if(Y){let j=new URL(Y,"http://gemi.invalid");if(j.searchParams.set("error",Z),J)j.searchParams.set(l0,J);E1.external(`${j.pathname}${j.search}${j.hash}`)}else console.error(`auth.oauthFailurePath must be a same-origin path, got ${JSON.stringify(W)}`)}return{session:null,error:Z,redirectTo:J}}async linkOAuthAccount($){let{provider:Z,providerId:J,email:W,rawEmail:Y,name:j,username:z,locale:X}=$,{userProvider:G,config:Q}=M(E),V=(D)=>({provider:Z,userId:D,email:W,username:z,providerId:J,expiresAt:new Date,accessToken:"",refreshToken:""}),F=await G.findUserByEmailAddress(W,!1),B=Y?.trim();if(!F&&B&&B!==W)F=await G.findUserByEmailAddress(B,!1);if(F){if($.linkExisting===!1)return"account_exists";if(!J)return{user:F,action:"signin"};let D=await G.findSocialAccounts(F.id,Z);if(D.some((L)=>L.providerId===J))return{user:F,action:"signin"};if(D.some((L)=>L.providerId))return console.error(`Authentication error: user ${F.id} is already linked to a different ${Z} account`),null;let O=D[0];if(O){if(!await G.claimSocialAccount(O,J))throw Error(`${Z} account link changed concurrently`)}else await G.createSocialAccount(V(F.id));return{user:F,action:"signin"}}if($.createUser===!1)return"signup_disabled";return{user:await G.transaction(async()=>{let D=await G.createUser({email:W,name:j,locale:X,emailVerifiedAt:new Date});if(J)await G.createSocialAccount(V(D.id));return await Q.onUserCreated(D,{method:"oauth",input:{},req:$.req}),D}),action:"signup"}}async createMagicLinkToken($=new C){await u1("magicLink",$);let Z=await $.input(),J=q$(Z.get("email")),W=M(E),{uniformMagicLinkResponse:Y,requestLimit:j}=W.config.emailCode;if(await v$("request",J,$,j,W.config.rateLimitKey),!J)return{email:null};let{user:z,pin:X,token:G}=await W.createMagicLinkToken(J);if(z)return await W.config.onMagicLinkCreated(z,{email:J,pin:X,token:G,req:$}),{email:J};return{email:Y?J:null}}async requestEmailCode($=new C){let Z=M(E),J=Z.config.emailCode;if(!await k1(J.enabled,$))s4();let W=await $.input(),Y=I6(W.get("email"));if(await v$("request",Y,$,J.requestLimit,Z.config.rateLimitKey),!Y)throw new d({email:["Invalid email"]});let j=await Z.userProvider.findUserByEmailAddress(Y,!1);if(j||J.createUser){let{pin:z,token:X}=await Z.issueOneTimeCode(Y,J.length);await J.send({email:Y,code:z,token:X,isNewUser:!j,req:$})}return{ok:!0}}async verifyEmailCode($=new C){let Z=M(E),{userProvider:J,config:W}=Z;if(!await k1(W.emailCode.enabled,$))s4();let Y=await $.input(),{email:j,code:z,name:X}=Y.toJSON(),G=I6(j),Q=_G(z);if(await v$("verify",G,$,W.emailCode.verifyLimit,W.rateLimitKey),!G||!Q)throw new d({code:["invalid_code"]});let V=await Z.verifyOneTimeCode(G,Q,{claim:!1});if(V.status==="too_many_attempts")throw new d({code:["too_many_attempts"]});if(V.status!=="ok")throw new d({code:["invalid_code"]});let F=V.row,B=await J.findUserByEmailAddress(G,!1),U=!1;if(B){if(!await Z.claimOneTimeCode(G,F.id))throw new d({code:["invalid_code"]});await J.verifyUser(G)}else if(W.emailCode.createUser){let O=M(c).detectLocale($);try{B=await J.transaction(async()=>{if(!await Z.claimOneTimeCode(G,F.id))throw new uW;let L=await J.createUser({email:G,name:typeof X==="string"?X.trim():"",emailVerifiedAt:new Date,locale:O});return await W.onUserCreated(L,{method:"email-code",input:IG(Y.toJSON()),req:$}),L}),U=!0}catch(L){if(L instanceof uW)throw new d({code:["invalid_code"]});throw L}}else throw await Z.claimOneTimeCode(G,F.id),new d({code:["invalid_code"]});let D=await Z.createOrUpdateSessionV2({email:G,id:B.id});return $.ctx().setCookie("access_token",D.token,M(E).accessTokenCookieOptions($,D.expiresAt)),await W.onSignIn(D,$.search.toJSON(),{req:$}),await $Z(Z.config,{session:D,isNewUser:U,method:"email-code",req:$}),{session:D,isNewUser:U}}}function oD($){try{let Z=$?.id;if(Z===void 0||Z===null)return;let J=M();if(typeof J?.bound!=="function"||!J.bound(c0))return;J.make(c0).revoke({user:{id:Z}})}catch(Z){console.error("[gemi] Revoking the signed-out user's sockets failed:",Z)}}var bG="gemi_oauth_connection";class o4 extends O3{async connect($=new C){let Z=String($.params.provider??""),W=M(a3).providers[Z],Y=await q0.user(),j=U1($.search.get(l0),"");if(!W)return this.finish(j,Z,"unknown_provider");let z=DZ($.rawRequest),{state:X,codeChallenge:G,cookieValue:Q}=u4(RG(Z),Date.now(),{subject:String(Y.id),...j?{returnTo:j}:{}});return $.ctx().setCookie(nZ(z,bG),Q,{httpOnly:!0,sameSite:"Lax",secure:z,maxAge:n3}),E1.external(W.authorizationUrl({state:X,codeChallenge:G,redirectUri:kG($,Z,W.config.redirectUri)})),{destination:"/"}}async callback($=new C){let Z=String($.params.provider??""),J=M(a3),W=await q0.user(),Y=DZ($.rawRequest),j=nZ(Y,bG),z=$.cookies.get(j);if(z!==void 0&&z!==null)$.ctx().setCookie(j,"",{httpOnly:!0,sameSite:"Lax",secure:Y,maxAge:-1});let X=l4({provider:RG(Z),cookieValue:z,returnedState:$.search.get("state")}),G="payload"in X?X.payload.returnTo??"":"",Q=J.providers[Z];if(!Q)return this.finish(G,Z,"unknown_provider");let V=$.search.get("error");if(V)return this.finish(G,Z,/^[a-z0-9_]{1,64}$/.test(V)?V:"provider_error");if("reason"in X)return console.error(`OAuth connection refused (${X.reason})`),this.finish(G,Z,X.reason);if(X.payload.subject!==String(W.id))return this.finish(G,Z,"user_mismatch");let F=$.search.get("code");if(!F)return this.finish(G,Z,"missing_code");try{let B=await Q.exchangeCode({code:F,codeVerifier:X.payload.codeVerifier,redirectUri:kG($,Z,Q.config.redirectUri)}),U=await J.save(W,Z,B);await M(E).config.onConnected({user:W,provider:Z,connection:U,profile:B.profile??null,req:$})}catch(B){if(B instanceof wG)return console.error(`OAuth connection to ${Z} failed: ${B.message}`),this.finish(G,Z,B.providerError??B.code);throw B}return this.finish(G,Z)}finish($,Z,J){let W=$||U1(M(E).config.redirectPath,"/"),Y=new URL(W,"http://gemi.invalid");if(Y.searchParams.set("connection",Z),J)Y.searchParams.set("connection_error",J);throw E1.external(`${Y.pathname}${Y.search}${Y.hash}`),Error("unreachable: Redirect.external throws")}}function RG($){return`connection:${$}`}function kG($,Z,J){if(J)return J;return`${ZZ()??new URL($.rawRequest.url).origin}/auth/connections/${encodeURIComponent(Z)}/callback`}function fG($){return $.magicLink!==!1||Y7($.emailCode?.enabled)}function qG($){return Object.keys($.oauthProviders??{}).length>0}function vG($={}){let Z=[];if(fG($))Z.push({view:"auth/MagicLinkSignIn",requiredBy:Y7($.emailCode?.enabled)&&$.magicLink===!1?"auth.emailCode.enabled":`auth.magicLink${$.magicLink===void 0?" (on by default; set `magicLink: false` to turn it off)":""}`});if(qG($)){let W=`auth.oauthProviders (${Object.keys($.oauthProviders??{}).join(", ")})`;Z.push({view:"_Redirect",requiredBy:W},{view:"auth/OauthCallback",requiredBy:W})}return Z}class gG extends b1{middlewares=["cache:private"];routes={"/:provider":this.redirect([o4,"connect"]).middleware(["auth"]),"/:provider/callback":this.redirect([o4,"callback"]).middleware([D6,"auth"])}}function yG($={}){let Z=fG($),J=qG($);class W extends b1{middlewares=["cache:private"];routes={"/:provider":this.view("_Redirect",[Z0,"oauthRedirect"]),"/:provider/callback":this.view("auth/OauthCallback",[Z0,"oauthCallback"])}}return class extends b1{middlewares=["cache:private"];routes={...Z?{"/sign-in/magic-link":this.view("auth/MagicLinkSignIn",[Z0,"signInWithMagicLink"])}:{},...J?{"/oauth":W}:{},"/connections":gG}}}class iW extends C0{middlewares=["cache:private"];routes={"/sign-in":this.post(Z0,"signIn"),"/sign-in-v2":this.post(Z0,"signInV2"),"/sign-up":this.post(Z0,"signUp"),"/sign-out":this.post(Z0,"signOut"),"/forgot-password":this.post(Z0,"forgotPassword"),"/reset-password":this.post(Z0,"resetPassword"),"/change-password":this.post(Z0,"changePassword"),"/verify-email":this.post(Z0,"verifyEmail"),"/me":this.get(Z0,"me").middleware(["auth"]),"/magic-link":this.post(Z0,"createMagicLinkToken"),"/sign-in-with-pin":this.post(Z0,"signInWithPin"),"/sign-in-with-pin-v2":this.post(Z0,"signInWithPinV2"),"/email-code":this.post(Z0,"requestEmailCode"),"/email-code/verify":this.post(Z0,"verifyEmailCode")}}class sW extends C0{middlewares=["cache:private,0,no-store"];routes={"/set-locale/:locale":this.get(async()=>{let Z=new C().params.locale;return await M(c).onLocaleChange(Z),{locale:Z}}),"/translations/:locale/:scope*":this.get(async()=>{let $=new C,Z=`/${$.params.scope??""}`,J=$.params.locale,W=M(c),Y=J??W.detectLocale($),j=W.getPageTranslations(Y,Z);return $.ctx().setCookie("i18n-locale",Y,{expires:new Date(Date.now()+31536000000)}),{[Y]:j}})}}class nW{}class oW extends nW{async resize($,Z){let{height:J,width:W,quality:Y,fit:j}=Z;return await(await a4("The Sharp image optimization driver"))($).resize(W>0?W:void 0,J>0?J:void 0,{fit:j}).webp({quality:Y>0?Y:80,force:!0}).toBuffer()}}function C_($){return $}function mG(){return{driver:new oW,allowedHosts:[],maxSize:10485760,timeout:1e4}}class F0 extends Error{status;constructor($,Z,J){super(Z,J);this.status=$;this.name="ImageSourceError"}}var aD=new Set([301,302,303,307,308]),tD="/api/__gemi__/services/image/";async function pG($,Z){let J=Z.maxRedirects??5,W=AbortSignal.timeout(Z.timeout),Y=Z.ownOrigins[0]??Z.localOrigin,j=hG($,Y);try{for(let z=0;;z++){let X=await rD(j,Z,W),G=X.headers.get("location");if(aD.has(X.status)&&G){if(await X.body?.cancel().catch(()=>{}),z>=J)throw new F0(502,"The image redirects too many times");j=hG(G,j.href);continue}if(!X.ok)throw await X.body?.cancel().catch(()=>{}),new F0(404,"Image not found");if(!X.headers.get("content-type")?.split(";")[0].trim().toLowerCase()?.startsWith("image/"))throw await X.body?.cancel().catch(()=>{}),new F0(415,"The source is not an image");return{bytes:Buffer.from(await X.arrayBuffer()),cacheControl:X.headers.get("cache-control")}}}catch(z){if(z instanceof TypeError&&z.message.startsWith("safeFetch:"))throw z;throw $L(z,W)}}function hG($,Z){let J;try{J=new URL($,Z)}catch{throw new F0(400,"The url parameter is not a URL")}if(J.protocol!=="http:"&&J.protocol!=="https:")throw new F0(400,"Only http(s) images can be resized");return J}async function rD($,Z,J){let W={method:"GET",redirect:"manual",signal:J,timeout:Z.timeout,maxSize:Z.maxSize,headers:{accept:"image/*"}},Y=$;if(Z.ownOrigins.includes($.origin)){if($.pathname.startsWith(tD))throw new F0(403,"This image source is not allowed");if(eD($.pathname))throw new F0(403,"This image source is not allowed");let j=new URL(Z.localOrigin).origin,z=new URL(`${$.pathname}${$.search}`,j);if(z.origin===j)return R1(z,{...W,allowPrivate:!0,ports:"any"});Y=z}if(Z.allowedHosts.length===0)throw new F0(403,"This image source is not allowed");return R1(Y,{...Z.external,...W,allow:Z.allowedHosts})}function eD($){let Z=$;for(let J=0;J<5;J++){if(/^[/\\][/\\]/.test(Z))return!0;let W;try{W=decodeURIComponent(Z)}catch{return!0}if(W===Z)return!1;Z=W}return!0}function $L($,Z){if($ instanceof F0)return $;if(Z.aborted)return new F0(504,"The image took too long to load",{cause:$});if($ instanceof H6)switch($.code){case"blocked-host":case"blocked-address":case"invalid-url":return new F0(403,"This image source is not allowed",{cause:$});case"too-large":return new F0(413,"The image is too large",{cause:$});case"timeout":return new F0(504,"The image took too long to load",{cause:$})}return new F0(502,"The image could not be loaded",{cause:$})}class aW extends C0{routes={"/resize":this.file(async()=>{let $=new C,Z=new URL($.rawRequest.url),J=Z.searchParams.get("url"),W=Number(Z.searchParams.get("w")),Y=Number(Z.searchParams.get("h")),j=Z.searchParams.get("fit")??"cover",z=Number(Z.searchParams.get("q"));if(!J)return cG(400,"url query parameter is required");let X=M(dG),G=[Z.origin,`${Z.protocol==="https:"?"http":"https"}://${Z.host}`],Q=ZZ();if(Q&&URL.canParse(Q))G.push(new URL(Q).origin);let V;try{V=await pG(J,{ownOrigins:G,localOrigin:`http://localhost:${process.env.PORT||5173}`,allowedHosts:X.allowedHosts,maxSize:X.maxSize,timeout:X.timeout})}catch(U){if(U instanceof F0)return cG(U.status,U.message);throw U}let F=await X.resize(V.bytes,{height:Y,width:W,fit:j,quality:z}),B=new Headers({"Content-Type":"image/webp","Content-Length":`${F.byteLength}`});if(V.cacheControl)B.set("Cache-Control",V.cacheControl);return new Response(new Uint8Array(F),{headers:B})})}}function cG($,Z){return Response.json({error:Z},{status:$})}class dG{static token="image";driver;allowedHosts;maxSize;timeout;constructor($={}){let Z=mG();this.driver=$.driver??Z.driver,this.allowedHosts=$.allowedHosts??Z.allowedHosts,this.maxSize=$.maxSize??Z.maxSize,this.timeout=$.timeout??Z.timeout}resize($,Z){return this.driver.resize($,Z)}}class tW extends C0{middlewares=["cache:private,0"];routes={"/live":this.get(async()=>{let $=Bun.file(M(uG).currentLogFilePath);return new Response(await $.text(),{headers:{"Content-Type":"text/plain"}})})}}function p_($){return $}function lG(){return{onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{}}}function iG(){return{partialRendering:!0,localeRouting:"prefix",theme:{},publicFiles:!0,assetRoutes:!1,onNotFound:()=>{},onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{},onStreamComplete:()=>{}}}function ZL($){return"run"in $}function JL($){return Object.hasOwn($,"get")||Object.hasOwn($,"post")||Object.hasOwn($,"put")||Object.hasOwn($,"patch")||Object.hasOwn($,"delete")}function WL($){return Object.hasOwn($,"first")&&Object.hasOwn($,"second")}function YL($){if("__brand"in $)return $.__brand==="ApiRouter";return!1}function jL($){if("__internal_brand"in $)return $.__internal_brand==="ProxyHandler";return!1}function sG($){if("__internal_brand"in $)return $.__internal_brand==="StreamHandler";return!1}function zL($){let Z=$.replace(/(?<!:\w*)\([\w-]+\)/g,"");if(Z===$)return $;let J=`/${Z}`.replace(/\/{2,}/g,"/");return J.length>1?J.replace(/\/$/,""):J}function rW($,Z="",J=[]){let W={};function Y(j,z,X,G,Q){let V=j==="/"?"":j,F=Z==="/"?"":Z,B=zL((`${F}${V}`===""?"/":`${F}${V}`).replaceAll("//","/"));if(!W[B])W[B]={};W[B][z.toUpperCase()]={exec:X,middleware:[...J,...G],...Q?{source:Q}:{}},W[B].OPTIONS={exec:()=>{let D=new C().ctx().headers;return new Response(null,{headers:D,status:204})},middleware:[]}}for(let[j,z]of Object.entries($)){if(jL(z)){let X=z;for(let G of["GET","POST","PUT","DELETE"])Y(j,G,X.run.bind(X),X.middlewares);continue}if(ZL(z)){let X=z,G=X.method,Q=X.middlewares,V=X.run.bind(X);if(Y(j,G,V,Q,X.source),sG(z))Y(j,"HEAD",V,Q,X.source)}if(JL(z))for(let[X,G]of Object.entries(z)){let Q=G,V=Q.middlewares,F=Q.run.bind(Q);if(Y(j,X,F,V,Q.source),X==="get"&&sG(Q))Y(j,"HEAD",F,V,Q.source)}if(YL(z)){let X=new z,G=rW(X.routes,`${Z}${j}`,[...J,...X.middlewares]);for(let[Q,V]of Object.entries(G)){let F=Q.replaceAll("//","/");W[F]={...W[F],...V}}}if(WL(z)){let{first:X,second:G}=z;for(let[Q,V]of Object.entries(X)){let F=V.middlewares,B=V.run.bind(V),[U,...D]=j.split("/").reverse();if(!U.startsWith(":"))throw Error("Resource route must end with a dynamic segment");Y(D.reverse().join("/"),Q,B,F,V.source)}for(let[Q,V]of Object.entries(G)){let F=V.middlewares,B=V.run.bind(V);Y(j,Q,B,F,V.source)}}}return Object.fromEntries(Object.entries(W).sort(([j],[z])=>{let X=j.split("/").length+j.split(":").length,G=z.split("/").length+z.split(":").length;return X-G}))}function t4($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function eW($,Z){if($==="/")return Z;if(Z==="/")return $;return`${$}${Z}`}function $5($){let Z=t4($);return Z.length>1?Z.replace(/\/$/,""):Z}function nG($,Z){return Z.map((J)=>({...J,path:$5(eW($,J.path))}))}function r4($){let Z={};for(let[J,W]of Object.entries($))if("run"in W){let Y=W;if("children"in Y){let j=new Y.children,z=r4(j.routes);for(let[X,{exec:G,middleware:Q,segments:V,features:F,static:B}]of Object.entries(z)){let U=eW(J,X),D=(O)=>Y.run.call(Y,O,J);Z[t4(U)]={exec:[D,...G],middleware:[...Y.middlewares,...Q],features:[...Y.featureGates,...F],viewPath:Y.viewPath,segments:[{path:$5(J),viewPath:Y.viewPath,...Y.alwaysRuns?{alwaysRun:!0}:{}},...nG(J,V)],...B?{static:B}:{}}}}else{let j=(z)=>Y.run.call(Y,z,J);Z[t4(J)]={exec:[j],middleware:Y.middlewares,features:Y.featureGates,viewPath:Y.viewPath,segments:[{path:$5(J),viewPath:Y.viewPath}],..."staticOptions"in Y&&Y.staticOptions?{static:Y.staticOptions}:{}}}}else{let Y=new W,j=r4(Y.routes);for(let[z,{exec:X,middleware:G,viewPath:Q,segments:V,features:F,static:B}]of Object.entries(j)){let U=eW(J,z);Z[t4(U)]={exec:X,middleware:[...Y.middlewares,...G],features:[...Y.featureGates,...F],viewPath:Q,segments:nG(J,V),...B?{static:B}:{}}}}return Object.fromEntries(Object.entries(Z).sort(([J],[W])=>{let Y=J.split("/").length+J.split(":").length,j=W.split("/").length+W.split(":").length;return Y-j}))}var Z5="theme";function oG($){return $==="light"||$==="dark"||$==="system"}function aG($){return`!function(o){try{var e=null,d=document.documentElement,c=d.classList,k=document.cookie.split(';'),i,j,v;
|
|
13
|
+
`)}function MF($,Z={}){let J=new Headers(Z.headers);if(!J.has("content-type"))J.set("content-type","text/plain; charset=utf-8");return new Response(S9($),{status:200,headers:J})}var E9={response:MF,text:S9,parse:A9,fetch:HF};import{createHmac as b9,randomBytes as KF}from"crypto";var a8="v2.";function t8($){return $.startsWith(a8)}function KZ(){let $=process.env.SECRET;if(!$)throw Error("Signing in needs a secret to mint session tokens with. Set SECRET in the environment.");return $}function R9($){let Z=KF(16).toString("hex"),J=b9("sha256",KZ()).update(`${$}:${Z}`).digest("hex");return`${a8}${J}`}function N6($,Z){let J=b9("sha256",KZ()).update(`legacy-session:${Z}:${$}`).digest("hex");return`${a8}${J}`}import{createHash as NF,createHmac as _F,randomInt as IF,timingSafeEqual as f9}from"crypto";function k9($,Z){return Math.floor($/Z)*Z}function TF($,Z){if(Z<=0)return 0;return Math.min(1,Math.max(0,(Z-$)/Z))}function r8($,Z,J,W){return Z*TF(J,W)+$}function PF($){let{current:Z,previous:J,elapsed:W,window:Y,limit:j,cost:z}=$,X=j-z;if(X<0)return Y;let G=Math.max(0,Y-W);if(J>0){let V=Y*(1-(X-Z)/J);if(V<=Y)return Math.max(0,Math.ceil(V-W))}if(Z<=X)return G;if(Z<=0)return G;let Q=Y*(1-X/Z);return G+Math.max(0,Math.ceil(Q))}function w9($){let{allowed:Z,current:J,previous:W,now:Y,elapsed:j,window:z,limit:X,cost:G}=$;if(Z){let V=r8(J,W,j,z);return{allowed:!0,limit:X,remaining:Math.max(0,Math.floor(X-V)),resetAt:Y-j+z,retryAfter:0}}let Q=PF({current:J,previous:W,elapsed:j,window:z,limit:X,cost:G});return{allowed:!1,limit:X,remaining:0,resetAt:Y+Q,retryAfter:Q}}class e8{}class $7 extends e8{buckets=new Map;maxKeys;constructor($={}){super();this.maxKeys=Math.max(1,$.maxKeys??1e5)}consume($){let{key:Z,limit:J,window:W}=$,Y=$.cost??1,j=Date.now(),z=k9(j,W),X=j-z,G=this.roll(Z,W,z);G.limit=J;let V=r8(G.current,G.previous,X,W)+Y<=J;if(V)G.current+=Y;if(this.buckets.delete(Z),this.buckets.set(Z,G),this.buckets.size>this.maxKeys)this.evict(j);return w9({allowed:V,current:G.current,previous:G.previous,now:j,elapsed:X,window:W,limit:J,cost:Y})}clear(){this.buckets.clear()}get size(){return this.buckets.size}roll($,Z,J){let W=this.buckets.get($);if(!W||W.window!==Z)return{window:Z,limit:0,windowStart:J,current:0,previous:0};if(W.windowStart===J)return W;if(W.windowStart+Z===J)return W.previous=W.current,W.current=0,W.windowStart=J,W;return W.previous=0,W.current=0,W.windowStart=J,W}evict($){for(let[W,Y]of this.buckets)if($-Y.windowStart>=Y.window*2)this.buckets.delete(W);let Z=this.maxKeys-Math.floor(this.maxKeys/10);if(this.buckets.size<=Z)return;let J=[...this.buckets].map(([W,Y],j)=>({key:W,order:j,spent:Y.limit>0?(Y.current+Y.previous)/Y.limit:0}));J.sort((W,Y)=>W.spent-Y.spent||W.order-Y.order);for(let{key:W}of J){if(this.buckets.size<=Z)break;this.buckets.delete(W)}}}var v9="h1.";function _6($,Z,J){let W=_F("sha256",KZ()).update(`gemi:one-time:${$}:${Z}:${J}`).digest("hex");return`${v9}${W}`}function TZ($,Z,J,W){let Y=typeof W==="string"?W:"",j=typeof J==="string"?J:"",z=j.startsWith(v9),X=_6($,Z,Y),G=Buffer.from(z?X:Y),Q=Buffer.from(j);if(G.length!==Q.length||Y===""||j==="")return f9(G,G),!1;return f9(G,Q)}function g9($){let Z="";for(let J=0;J<$;J++)Z+=String(IF(0,10));return Z}var y9=320;function q$($){if(typeof $!=="string")return null;let Z=$.trim();if(Z===""||Z.length>y9)return null;return Z.toLowerCase()}function I6($){if(typeof $!=="string")return null;let Z=$.trim();if(Z.length>y9)return null;let J=Z.toLowerCase();if(J.length<3||J.length>254||!/^[^\s@]+@[^\s@]+$/.test(J))return null;return J}var q9=null;function m9(){try{let $=M();if(typeof $?.bound==="function"&&$.bound(O1))return $.make(O1)}catch{}return q9??=new O1({driver:new $7,limit:1000,window:60}),q9}function Z7($){return $.length<=64?$:`sha256:${NF("sha256").update($).digest("hex")}`}function xF($){return $==="request"||$==="verify"||$==="link"?`auth:code-${$}`:`auth:${$}`}async function v$($,Z,J,W,Y,j){let z=m9(),X=[["perIp",`ip:${Z7(LZ(J))}`,W.perIp]];if(Z!==null)X.push(["perEmail",`email:${Z7(Z)}`,W.perEmail]);for(let[G,Q,V]of X){if(!V)continue;let F=Y?await Y({req:J,scope:$,limit:G}):void 0,B=xF($),U=F?`${B}:p:${Z7(String(F))}:${Q}`:`${B}:${Q}`,[D,O]=V,L=await z.consume(U,{limit:D,window:O});if(!L.allowed)throw await j?.(G),new Y$(L)}}async function h9($,Z,J,W=10){let Y=Math.max(86400,Math.ceil(W*60*(J+1)));return(await m9().consume(`auth:code-attempt:${$}:${Z}`,{limit:J,window:Y})).allowed}import{randomBytes as W7}from"crypto";class J7 extends C{schema={name:{string:"Invalid name",required:"Name is required","min:2":"Name must be at least 3 characters"},email:{string:"Invalid email",required:"Email is required",email:"Invalid email"},password:{"min:8":"Password must be at least 9 characters"}}}async function k1($,Z){if(typeof $==="function")return await $({req:Z})===!0;return Boolean($)}function Y7($){return $===!0||typeof $==="function"}function j7($={}){return{signIn:{perEmail:$.signIn?.perEmail??[10,900],perIp:$.signIn?.perIp??[50,900]},signUp:{perEmail:$.signUp?.perEmail??!1,perIp:$.signUp?.perIp??[10,3600]},forgot:{perEmail:$.forgot?.perEmail??[5,900],perIp:$.forgot?.perIp??[20,900]},reset:{perEmail:$.reset?.perEmail??!1,perIp:$.reset?.perIp??[20,900]}}}function D3($,Z,J,W=1/0){if(!Number.isInteger(Z)||Z<J||Z>W){let Y=W===1/0?`an integer of at least ${J}`:`an integer from ${J} to ${W}`;throw Error(`auth.emailCode.${$} must be ${Y}, got ${Z}`)}}function CF($={}){let Z=[["password",$?.password],["magicLink",$?.magicLink],["verifyEmail",$?.verifyEmail],["emailCode.enabled",$?.emailCode?.enabled]];for(let[J,W]of Z)if(W!==void 0&&typeof W!=="boolean"&&typeof W!=="function")throw Error(`auth.${J} must be true, false or a function of the request, got ${JSON.stringify(W)}`)}function z7($={}){let Z=$.length??6,J=$.expiresInMinutes??10,W=$.linkExpiresInMinutes??10080,Y=$.maxAttempts??5,j=$.activeCodes??1;return D3("length",Z,4,12),D3("expiresInMinutes",J,1),D3("linkExpiresInMinutes",W,1),D3("maxAttempts",Y,1),D3("activeCodes",j,1,5),{enabled:$.enabled??!1,createUser:$.createUser??!1,length:Z,expiresInMinutes:J,linkExpiresInMinutes:W,maxAttempts:Y,activeCodes:j,requestLimit:{perEmail:$.requestLimit?.perEmail??[5,900],perIp:$.requestLimit?.perIp??[20,900]},verifyLimit:{perEmail:$.verifyLimit?.perEmail??[10,900],perIp:$.verifyLimit?.perIp??[50,900]},uniformMagicLinkResponse:$.uniformMagicLinkResponse??!1,send:$.send??(({email:z,code:X})=>{if(Bun.env.NODE_ENV!=="production")console.info(`[gemi] email code for ${z}: ${X} (set auth.emailCode.send to deliver it)`)})}}async function AF($,Z){if(typeof Z!=="string"||Z==="")return!1;try{return await Bun.password.verify($,Z)}catch{return!1}}function p9($){if(!$)return null;if(typeof $.getRedirectUrl==="function")return{provider:$};let{provider:Z,feature:J,enabled:W}=$;return{provider:Z,...J!==void 0?{feature:J}:{},...W!==void 0?{enabled:W}:{}}}function c9($){for(let[Z,J]of Object.entries($??{})){if(typeof J?.getRedirectUrl==="function")continue;let W=J;if(typeof W?.provider?.getRedirectUrl!=="function")throw Error(`auth.oauthProviders.${Z} must be an OAuthProvider, or { provider, feature, enabled } with an OAuthProvider.`);if(W.enabled!==void 0&&typeof W.enabled!=="boolean"&&typeof W.enabled!=="function")throw Error(`auth.oauthProviders.${Z}.enabled must be true, false or a function of the request.`);if(W.feature!==void 0&&(typeof W.feature!=="string"||W.feature===""))throw Error(`auth.oauthProviders.${Z}.feature must be a feature key from app/features.`)}}function MP($){return $}function d9($={}){return CF($),{basePath:"/auth",verifyEmail:!0,password:!0,passwordLimits:j7($.passwordLimits),magicLink:!0,redirectPath:"/dashboard",signInPath:"/auth/sign-in",sessionExpiresInHours:24,sessionAbsoluteExpiresInHours:672,cookieDomain:null,migrateLegacySession:null,signUpRequest:J7,oauthProviders:{},oauthFailurePath:null,oauthCompleteProfilePath:null,connections:{},connectionStore:null,onConnected:()=>{},verifyPassword:AF,hashPassword:async(Z)=>await Bun.password.hash(Z),generateForgotPasswordToken:async()=>W7(32).toString("hex"),generateEmailVerificationToken:()=>{if($.verifyEmail===!1)return"";return W7(32).toString("hex")},generateMagicLinkToken:()=>W7(32).toString("hex"),extendSession:()=>({}),onUserCreated:async()=>{},onSignUp:()=>{},onSignIn:()=>{},onSignOut:()=>{},onForgotPassword:()=>{},onResetPassword:()=>{},onMagicLinkCreated:()=>{},emailCode:z7($.emailCode),generateCode:()=>{return},rateLimitKey:()=>{return},onAuthenticated:()=>{}}}var SF=new Set(["script","style","textarea","title","xmp","iframe","noembed","noframes","noscript"]),EF=new Set(["svg","math"]);function u9($){return $===32||$===9||$===10||$===12||$===13}function l9($){return $>=65&&$<=90||$>=97&&$<=122}function x6($){return $>=65&&$<=90?$+32:$}function i9(){let $="data",Z="",J=!1,W="",Y=0,j=0,z=!1,X=0,G=0,Q=()=>$==="data"&&X===0&&G===0,V=()=>{if(!J&&SF.has(Z)){$="rawText",W=`</${Z}`,Y=0,Z="";return}if($="data",Z==="template")if(J)X=Math.max(0,X-1);else X+=1;else if(EF.has(Z)){if(J)G=Math.max(0,G-1);else if(!z)G+=1}Z=""},F=(B)=>{switch($){case"data":if(B===60)$="tagOpen";return;case"tagOpen":if(B===33)$="bang",j=0;else if(B===47)$="endTagOpen";else if(l9(B))$="tagName",J=!1,z=!1,Z=String.fromCharCode(x6(B));else if(B===63)$="bogus";else if(B===60)$="tagOpen";else $="data";return;case"endTagOpen":if(l9(B))$="tagName",J=!0,z=!1,Z=String.fromCharCode(x6(B));else if(B===62)$="data";else $="bogus";return;case"tagName":if(u9(B)||B===47)$="inTag",z=B===47;else if(B===62)V();else Z+=String.fromCharCode(x6(B));return;case"inTag":if(B===62){V();return}if(z=B===47,B===34)$="attrDouble";else if(B===39)$="attrSingle";return;case"attrDouble":if(B===34)$="inTag";z=!1;return;case"attrSingle":if(B===39)$="inTag";z=!1;return;case"bang":if(B===45){if(j+=1,j===2)$="comment",j=0}else if(B===62)$="data";else $="bogus";return;case"bogus":if(B===62)$="data";return;case"comment":if(B===45)j=j<2?j+1:2;else if(B===62&&j>=2)$="data",j=0;else j=0;return;case"rawText":{if(Y<W.length){if(x6(B)===W.charCodeAt(Y))Y+=1;else Y=B===60?1:0;return}if(B===62)$="data",Z="";else if(u9(B)||B===47)$="inTag",Z="";else Y=B===60?1:0;return}}};return{scanToInsertionPoint(B){for(let U=0;U<B.length;U++){if(Q())return U;F(B[U])}return B.length},write(B){for(let U=0;U<B.length;U++)F(B[U])},isSafe:Q}}function i0($){let Z=JSON.stringify($);if(Z===void 0)return"undefined";return Z.replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function bF($){return`<script>(self.__GEMI_STREAM__=self.__GEMI_STREAM__||[]).push(${i0([$.path,$.variantKey,$.data])})</script>`}function RF($){return`<script>(self.__GEMI_DICT__=self.__GEMI_DICT__||[]).push(${i0([$.id,$.locale,$.strings])})</script>`}function X7($,Z,J={},W){let Y=new TextEncoder,j=[],z=!1,X=!1,G=()=>{if(X)return;X=!0,J.onClose?.()};Z.onSettle((D)=>{if(D.status!=="resolved")return;j.push(bF(D))}),W?.onUse((D)=>{j.push(RF(D))});let Q=$.getReader(),V=i9(),F=(D,O)=>{D.enqueue(O),J.onChunk?.(O)},B=(D)=>{while(j.length>0){let O=Y.encode(j.shift());V.write(O),F(D,O)}},U=(D,O)=>{if(j.length===0){V.write(O),F(D,O);return}let L=V.scanToInsertionPoint(O);if(L>0)F(D,O.subarray(0,L));if(V.isSafe())B(D);let H=O.subarray(L);if(H.length>0)V.write(H),F(D,H)};return new ReadableStream({async pull(D){let O;try{O=await Q.read()}catch(T){throw G(),T}let{done:L,value:H}=O;if(L){B(D),D.close(),G();return}if(!z){if(z=!0,V.write(H),F(D,H),J.onShell?.(),V.isSafe())B(D);return}U(D,H)},cancel(D){return G(),Q.cancel(D)}})}var kF=/bot|crawler|spider|crawling|slurp|bingpreview|mediapartners|headless|lighthouse|prerender|facebookexternalhit|whatsapp|telegram|discord|twitterbot|linkedinbot/i;function C6($){if(!$)return!1;return kF.test($)}async function n9($,Z=()=>{}){let J=P.getStore(),W=J?.req??null,Y=null;if(W?.rawRequest?.url)try{Y=new URL(W.rawRequest.url).pathname}catch{Y=null}return{user:J?.user??null,attributes:await wF($,Z),request:{path:Y,routePath:W?.routePath??null,locale:J?.locale??null},anonymousId:s9(),isBot:C6(W?.rawRequest?.headers?.get("user-agent")??null),now:new Date}}function o9($){return{user:$.user??null,attributes:$.attributes??{},request:{path:null,routePath:null,locale:null},anonymousId:$.subjectId??null,isBot:!1,now:new Date}}async function wF($,Z){if(!$.context)return{};try{let J=P.getStore();return await $.context(J?.req??null)??{}}catch(J){return Z(`The \`context\` hook in app/config/features.ts threw; evaluating with no attributes. ${J instanceof Error?J.message:String(J)}`),{}}}function a9($,Z){return`${$}:${Z}`}function G7($){let Z=new Bun.CryptoHasher("sha1").update($).digest("hex"),J=Number.parseInt(Z.slice(0,8),16);return Math.floor(J/4294967296*1e4)}function t9($,Z){if(Z>=100)return!0;if(Z<=0)return!1;return $<Math.round(Z*100)}function r9($,Z,J,W){if(W.unavailable)return{value:!1,reason:"unavailable"};if(W.active!==!0)return{value:!1,reason:"inactive"};if(Z.when){let j;try{j=Z.when(J)}catch(z){return W.warn?.(`The \`when\` for feature "${$}" threw; treating it as off. ${z instanceof Error?z.message:String(z)}`),{value:!1,reason:"error"}}if(typeof j==="boolean")return{value:j,reason:"attributed"}}if(Z.rollout===void 0)return{value:!0,reason:"on"};if(J.isBot)return{value:!1,reason:"bot"};let Y=qF($,Z,J,W.buckets);return t9(Y,Z.rollout)?{value:!0,reason:"rollout"}:{value:!1,reason:"excluded"}}function fF($){let Z=$.user?.publicId??$.user?.id;if(Z!==void 0&&Z!==null)return String(Z);return $.anonymousId??""}function qF($,Z,J,W){let Y=a9(Z.salt??$,fF(J));if(!W)return G7(Y);let j=W.get(Y);if(j!==void 0)return j;let z=G7(Y);return W.set(Y,z),z}class e9 extends Error{cause;kind="FeatureReloadFailed";constructor($){super(`Could not reload feature switches after a write, so the cached switches may still predate it: ${$ instanceof Error?$.message:String($)}`);this.cause=$}}class Q7{source;declared;ttlMs;warn;snapshot=null;inflight=null;lastFailureLoggedAt=0;generation=0;lastError=null;retryAfter=0;constructor($,Z,J,W=()=>{}){this.source=$;this.declared=Z;this.ttlMs=J;this.warn=W}async get(){let $=this.snapshot;if($&&Date.now()-$.loadedAt<this.ttlMs)return $;if($){if(Date.now()>=this.retryAfter)this.refresh().catch(()=>{});return $}return await this.refresh()}refresh(){return this.inflight??=this.load().finally(()=>{this.inflight=null}),this.inflight}async invalidate(){await this.inflight?.catch(()=>{});let $=this.generation,Z=await this.refresh();if(this.generation===$)throw new e9(this.lastError);return Z}peek(){return this.snapshot}async load(){try{let $=await this.source.load(),{active:Z,audit:J}=this.readRows($);return this.snapshot={active:Z,audit:J,loadedAt:Date.now(),unavailable:!1},this.generation++,this.lastError=null,this.retryAfter=0,this.snapshot}catch($){return this.handleFailure($)}}readRows($){let Z=new Map,J=new Map;for(let W of $??[]){let Y=typeof W?.key==="string"?W.key:null;if(!Y){this.warn("Ignoring a feature row with no `key`.");continue}if(!(Y in this.declared)){this.warn(`Feature row "${Y}" is not declared in app/features, so it is ignored. Delete the row, or declare the feature.`);continue}Z.set(Y,W.active===!0);let j=vF(W);if(j)J.set(Y,j)}return{active:Z,audit:J}}handleFailure($){let Z=$ instanceof Error?$.message:String($),J=Date.now();if(this.lastError=$,this.retryAfter=J+this.ttlMs,J-this.lastFailureLoggedAt>=this.ttlMs)this.lastFailureLoggedAt=J,this.warn(`Could not load feature switches: ${Z}`);if(this.snapshot)return this.snapshot;return this.snapshot={active:new Map,audit:new Map,loadedAt:J,unavailable:!0},this.snapshot}}function vF($){let Z={},J=$.updatedBy;if(typeof J==="string")Z.updatedBy=J;else if(J===null)Z.updatedBy=null;let W=$.updatedAt;if(W instanceof Date||typeof W==="string"||typeof W==="number"){let Y=W instanceof Date?W:new Date(W);if(!Number.isNaN(Y.getTime()))Z.updatedAt=Y}return"updatedBy"in Z||"updatedAt"in Z?Z:null}class gF{}class yF extends Error{modelName;kind="FeatureModelMissing";constructor($){super(`No "${$}" model is registered, so every feature stays off. Add the model to prisma/schema.prisma and export it from app/models \u2014 see docs/feature-flags.md.`);this.modelName=$}}class B7 extends Error{sourceName;kind="FeatureSourceReadOnly";constructor($){super(`The feature source (${$}) is read-only, so Features.set() cannot write to it. Change the switch where that source reads from, or give the source a write() method.`);this.sourceName=$}}class $Y extends Error{key;kind="UndeclaredFeature";constructor($){super(`"${$}" is not declared in app/features, so it cannot be switched. A row for it would be ignored \u2014 declare the feature first.`);this.key=$}}class ZY{manager;ctx;constructor($,Z){this.manager=$;this.ctx=Z}async enabled($){return(await this.explain($)).value}async explain($){return await this.manager.evaluateIn($,this.ctx,new Map)}async all(){return await this.manager.evaluateAllIn(this.ctx,new Map,{clientOnly:!1})}}class j${config;log;static token="features";store;declared;warnedAboutSize=!1;warnedAboutActor=!1;constructor($,Z=()=>{}){this.config=$;this.log=Z;this.declared=$.features??{},this.store=new Q7($.source,this.declared,Math.max(0,$.ttl)*1000,this.log)}declarations(){return this.declared}async list(){let{active:$,audit:Z,unavailable:J}=await this.switches();return{unavailable:J,features:Object.entries(this.declared).map(([W,Y])=>({key:W,describe:Y.describe,rollout:Y.rollout,targeted:Y.when!==void 0,serverOnly:Y.serverOnly,salt:Y.salt,active:$.get(W),...Z.get(W)}))}}async refresh(){if(!this.config.enabled)return;if(Object.keys(this.declared).length===0)return;await this.store.refresh()}async invalidate(){try{if(this.config.enabled&&Object.keys(this.declared).length>0)await this.store.invalidate()}finally{P.getStore()?.featureEvaluations?.clear()}}async set($,Z,J={}){if(typeof $!=="string"||!Object.hasOwn(this.declared,$))throw new $Y(String($));if(typeof Z!=="boolean")throw TypeError(`Features.set("${$}", \u2026) takes a boolean, not ${Z===null?"null":typeof Z}.`);let W=mF(J.actor),Y=this.config.source;if(typeof Y.write!=="function")throw new B7(Y.constructor?.name||"an anonymous source");let{actorRecorded:j}=await Y.write($,Z,{actor:W});if(W!==null&&!j&&!this.warnedAboutActor)this.warnedAboutActor=!0,this.log('Features.set() was given an actor, but the feature source has nowhere to record it. For the database source, add a nullable `updatedBy String?` column to the feature flag model to keep "last changed by".');await this.invalidate()}async enabled($){return(await this.explain($)).value}async explain($){let Z=await this.requestContext();return await this.evaluateIn($,Z,this.requestBuckets())}async all(){let $=await this.requestContext();return await this.evaluateAllIn($,this.requestBuckets(),{clientOnly:!1})}async forClient(){if(!this.config.enabled)return{};let $=await this.requestContext(),Z=await this.evaluateAllIn($,this.requestBuckets(),{clientOnly:!0});return this.warnIfOversized(Object.keys(Z).length),Z}for($){return new ZY(this,o9($))}async evaluateIn($,Z,J){let W=this.memoFor(Z),Y=W?.get($);if(Y)return Y;let j=this.declared[$];if(!j)return{value:!1,reason:"undeclared"};let{active:z,unavailable:X}=await this.switchFor($),G=r9($,j,Z,{active:z,unavailable:X,buckets:J,warn:this.log});return W?.set($,G),this.notify($,G,Z),G}async evaluateAllIn($,Z,J){let W={};for(let[Y,j]of Object.entries(this.declared)){if(J.clientOnly&&j.serverOnly)continue;W[Y]=(await this.evaluateIn(Y,$,Z)).value}return W}async switches(){if(!this.config.enabled||Object.keys(this.declared).length===0)return{active:new Map,audit:new Map,unavailable:!1};let $=await this.store.get();return{active:$.active,audit:$.audit,unavailable:$.unavailable}}async switchFor($){if(!this.config.enabled)return{active:!1,unavailable:!1};let Z=await this.store.get();return{active:Z.active.get($),unavailable:Z.unavailable}}async requestContext(){let $=P.getStore();if($?.featureContext)return $.featureContext;let Z=await n9(this.config,this.log);if($)$.featureContext=Z;return Z}memoFor($){let Z=P.getStore();if(!Z||Z.featureContext!==$)return null;return Z.featureEvaluations??=new Map,Z.featureEvaluations}requestBuckets(){let $=P.getStore();if(!$)return new Map;return $.featureBuckets??=new Map,$.featureBuckets}notify($,Z,J){if(!this.config.onEvaluate)return;try{this.config.onEvaluate($,Z,J)}catch(W){this.log(`The \`onEvaluate\` hook in app/config/features.ts threw for "${$}". ${W instanceof Error?W.message:String(W)}`)}}warnIfOversized($){if(this.warnedAboutSize||$<=this.config.maxClientFlags)return;this.warnedAboutSize=!0,this.log(`${$} client-visible features are embedded in every document. Mark the ones only the server reads with \`serverOnly: true\` to keep them out of the payload.`)}}function mF($){if($===void 0||$===null)return null;if(typeof $==="string"){if($.length>0)return $}else if(typeof $==="object"){let{publicId:Z,id:J}=$;if(typeof Z==="string"&&Z.length>0)return Z;if(typeof J==="string"&&J.length>0||typeof J==="number")return String(J)}throw TypeError("Features.set() was given an `actor` that identifies nobody. Pass a string, or a user with a `publicId` or an `id`.")}async function JY($){if($===void 0)return!0;return await M(j$).enabled($)}function WY(){try{return P.getStore()?.req??null}catch{return null}}async function PZ($,Z,J=WY()){if(typeof Z!=="string"||!Object.hasOwn($,Z))return null;let W=p9($[Z]);if(!W||!await JY(W.feature))return null;if(W.enabled!==void 0&&W.enabled!==!0){if(typeof W.enabled==="function"&&!J)return null;if(!await k1(W.enabled,J))return null}let Y=W.provider;if(typeof Y.isAvailable==="function"&&!await Y.isAvailable(J))return null;return Y}async function YY($,Z=WY()){let J=[];for(let W of Object.keys($))if(await PZ($,W,Z))J.push(W);return J}function V7($){if($&&typeof $==="object")delete $.password;return $}function hF(){return new Proxy({},{get:($,Z)=>zY(Z)})}var jY=new WeakMap;function XY($){if($&&typeof $==="object"){for(let Z of Object.values($))XY(Z);Object.freeze($)}return $}var pF={select:{id:!0,publicId:!0,email:!0,name:!0,locale:!0,globalRole:!0,accounts:{select:{id:!0,publicId:!0,organizationRole:!0,organization:!0}}}},cF=XY({token:!0,expiresAt:!0,absoluteExpiresAt:!0,updatedAt:!0,location:!0,userAgent:!0,user:pF});class F7{models;constructor($=hF()){this.models=$}run($){return this.models.User.asSystem($)}sessionSelect(){return cF}transaction($){return this.models.User.transaction($)}withLegacySessionLock($,Z){let J=this.models.User.$connection??w1(),W=M(f1).connection(J),Y=()=>this.transaction(async()=>{if(W.dialect==="postgres"){let X=`gemi:legacy-session:${$}`;await s0()`SELECT pg_advisory_xact_lock(hashtextextended(${X}, 0))`}return Z()});if(W.dialect!=="sqlite"||s0())return Y();let z=(jY.get(W)??Promise.resolve()).then(Y,Y);return jY.set(W,z.catch(()=>{})),z}async createUser($){let Z=await this.run(()=>this.models.User.create({data:$}));return V7(Z)}async updateUserPassword($){let Z=await this.run(()=>this.models.User.update({where:{id:$.id},data:{password:$.password}}));return V7(Z)}async findUserByEmailAddress($,Z){return await this.run(()=>this.models.User.findUnique({where:Z?{email:$,emailVerifiedAt:{not:null}}:{email:$}}))}async findUserByVerificationToken($){if(typeof $!=="string"||$==="")return null;return await this.run(()=>this.models.User.findFirst({where:{verificationToken:$}}))}async verifyUser($){return await this.run(()=>this.models.User.update({where:{email:$},data:{emailVerifiedAt:new Date}}))}async createSession($){return await this.run(()=>this.models.Session.create({data:$,include:{user:!0}}))}async createSessionV2($){return await this.run(()=>this.models.Session.create({data:$,select:this.sessionSelect()}))}async findSession($){if(!$.token)return null;return await this.run(()=>this.models.Session.findUnique({where:{token:$.token},select:this.sessionSelect()}))}async updateSession($){return await this.run(()=>this.models.Session.update({where:{token:$.token},data:{expiresAt:$.expiresAt},select:this.sessionSelect()}))}async deleteSession($){if(!$.token)return;await this.run(()=>this.models.Session.deleteMany({where:{token:$.token}}))}async claimLegacySession($){if(!$.token)return!1;let{count:Z}=await this.run(()=>this.models.Session.deleteMany({where:{token:$.token}}));return Z>0}async deleteAllUserSessions($){await this.run(()=>this.models.Session.deleteMany({where:{userId:$}}))}async createPasswordResetToken($){return await this.run(()=>this.models.PasswordResetToken.create({data:{token:$.token,user:{connect:{id:$.user.id}}}}))}async findPasswordResetToken($){if(typeof $.token!=="string"||$.token==="")return null;return await this.run(()=>this.models.PasswordResetToken.findUnique({where:{token:$.token},include:{user:!0}}))}async deletePasswordResetToken($){return await this.run(()=>this.models.PasswordResetToken.delete({where:{token:$.token}}))}async findInvitation($,Z){if(typeof $!=="string"||typeof Z!=="string")return null;return await this.run(()=>this.models.OrganizationInvitation.findFirst({where:{publicId:$,email:Z}}))}async deleteInvitationById($){await this.run(()=>this.models.OrganizationInvitation.delete({where:{publicId:$}}))}async createAccount($){return await this.run(()=>this.models.Account.create({data:{userId:$.userId,organizationId:$.organizationId,organizationRole:$.organizationRole}}))}async createMagicLinkToken($){return await this.run(()=>this.models.MagicLinkToken.create({data:{email:$.email,token:$.token,pin:$.pin}}))}async findUserMagicLinkToken($){let Z=(J)=>typeof J==="string"&&J!=="";if(!Z($.email))return null;if($.token!==void 0&&!Z($.token))return null;if($.token===void 0&&!Z($.pin))return null;return await this.run(()=>$.token?this.models.MagicLinkToken.findUnique({where:{token_email:{token:$.token,email:$.email}}}):this.models.MagicLinkToken.findUnique({where:{pin_email:{pin:$.pin,email:$.email}}}))}async findMagicLinkTokenByEmail($){return await this.run(()=>this.models.MagicLinkToken.findFirst({where:{email:$},orderBy:{id:"desc"}}))}async listMagicLinkTokensByEmail($,Z){return await this.run(()=>this.models.MagicLinkToken.findMany({where:{email:$},orderBy:{id:"desc"},take:Z}))}async deleteMagicLinkTokensExcept($,Z){await this.run(()=>this.models.MagicLinkToken.deleteMany({where:{email:$,id:{notIn:Z}}}))}async claimMagicLinkToken($){let{count:Z}=await this.run(()=>this.models.MagicLinkToken.deleteMany({where:{id:$}}));return Z===1}async deleteMagicLinkToken($){await this.run(()=>this.models.MagicLinkToken.deleteMany({where:{email:$}}))}async createSocialAccount($){return await this.run(()=>this.models.SocialAccount.create({data:$}))}async findUserBySocialAccount($,Z){if(!Z)return null;let J=await this.run(()=>this.models.SocialAccount.findFirst({where:{provider:$,providerId:Z},include:{user:!0}}));return J?V7(J.user):null}async findSocialAccounts($,Z){return await this.run(()=>this.models.SocialAccount.findMany({where:{userId:$,provider:Z},orderBy:{id:"asc"}}))}async claimSocialAccount($,Z){let{count:J}=await this.run(()=>this.models.SocialAccount.updateMany({where:{id:$.id,providerId:$.providerId},data:{providerId:Z}}));return J===1}}import{randomBytes as iD}from"crypto";function v0($,Z,J,W,Y){return $1(Z,_Y($,Z),J,W,Y)}function $1($,Z,J,W,Y,j){let z=H7(Z,J,W);if(Y&&Z!==z)throw RangeError(zX($,Z,J,W,j));return z}function _Y($,Z){let J=$[Z];if(J===void 0)throw TypeError(iJ(Z));return J}function L0($){return $!==null&&/object|function/.test(typeof $)}function m0($,Z=Map){let J=new Z;return(W,...Y)=>{if(J.has(W))return J.get(W);let j=$(W,...Y);return J.set(W,j),j}}function x7($){return h$({name:$},1)}function h$($,Z){return Y1((J)=>({value:J,configurable:1,writable:!Z}),$)}function IY($){return Y1((Z)=>({get:Z,configurable:1}),$)}function c6($){return{[Symbol.toStringTag]:{value:$,configurable:1}}}function SZ($,Z){let J={},W=$.length;for(let Y of Z)J[$[--W]]=Y;return J}function Y1($,Z,J){let W={};for(let Y in Z)W[Y]=$(Z[Y],Y,J);return W}function I3($,Z,J){let W={};for(let Y=0;Y<Z.length;Y++){let j=Z[Y];W[j]=$(j,Y,J)}return W}function dF($,Z,J){let W={};for(let Y=0;Y<$.length;Y++)W[Z[Y]]=J[$[Y]];return W}function p0($,Z){let J={};for(let W of $)J[W]=Z[W];return J}function C7($,Z){let J={};for(let W in Z)$.has(W)||(J[W]=Z[W]);return J}function A7($){$={...$};let Z=Object.keys($);for(let J of Z)$[J]===void 0&&delete $[J];return $}function xY($,Z){for(let J of Z)if(!(J in $))return 0;return 1}function CY($,Z,J){for(let W of $)if(Z[W]!==J[W])return 0;return 1}function AY($,Z,J){let W={...J};for(let Y=0;Y<Z;Y++)W[$[Y]]=0;return W}function f($,...Z){return(...J)=>$(...Z,...J)}function GY($){return $[0].toUpperCase()+$.substring(1)}function x3($){return $.slice().sort()}function w6($,Z){return String(Z).padStart($,"0")}function z$($,Z){return Math.sign($-Z)}function H7($,Z,J){return Math.min(Math.max($,Z),J)}function v1($,Z){return[Math.floor($/Z),H3($,Z)]}function H3($,Z){return($%Z+Z)%Z}function Q$($,Z){return[d6($,Z),S7($,Z)]}function d6($,Z){return Math.trunc($/Z)||0}function S7($,Z){return $%Z||0}function A6($){return Math.abs($%1)===0.5}function SY($,Z,J){let W=0,Y=0;for(let X=0;X<=Z;X++){let G=$[J[X]],Q=L1[X],V=l/Q,[F,B]=Q$(G,V);W+=B*Q,Y+=F}let[j,z]=Q$(W,l);return[Y+j,z]}function u6($,Z,J){let W={};for(let Y=Z;Y>=0;Y--){let j=L1[Y];W[J[Y]]=d6($,j),$=S7($,j)}return W}function EY($){return $===q?I4:[]}function bY($){return $===q?q3:[]}function RY($){return $===q?["year","day"]:[]}function kY($){if($!==void 0)return W0($)}function wY($){if($!==void 0)return j1($)}function E7($){if($!==void 0)return C3($)}function j1($){return vY(C3($))}function C3($){return qY(fU($))}function b7($){if($==null)throw TypeError("Cannot be null or undefined");return $}function fY($,Z){if(Z==null)throw RangeError(iJ($));return Z}function y1($){if(!L0($))throw TypeError(jX);return $}function l6($,Z,J=$){if(typeof Z!==$)throw TypeError(k3(J,Z));return Z}function qY($,Z="number"){if(!Number.isInteger($))throw RangeError(jU(Z,$));return $||0}function vY($,Z="number"){if($<=0)throw RangeError(zU(Z,$));return $}function R7($){if(typeof $=="symbol")throw TypeError(BU);return String($)}function f6($,Z){return L0($)?String($):W0($,Z)}function i6($){if(typeof $=="string")return BigInt($);if(typeof $!="bigint")throw TypeError(QU($));return $}function gY($,Z="number"){if(typeof $=="bigint")throw TypeError(GU(Z));if($=Number($),!Number.isFinite($))throw RangeError(XU(Z,$));return $}function A0($,Z){return Math.trunc(gY($,Z))||0}function yY($,Z){return qY(gY($,Z),Z)}function QY($,Z){return vY(A0($,Z),Z)}function k7($,Z){let[J,W]=Q$(Z,l),Y=$+J,j=Math.sign(Y);return j&&j===-Math.sign(W)&&(Y-=j,W+=j*l),[Y,W]}function _Z($,Z,J=1){return k7($[0]+Z[0]*J,$[1]+Z[1]*J)}function IZ($,Z){return k7($[0],$[1]+Z)}function n0($,Z){return _Z(Z,$,-1)}function E0($,Z){return z$($[0],Z[0])||z$($[1],Z[1])}function mY($,Z,J){return E0($,Z)===-1||E0($,J)===1}function s6($,Z=1){let J=BigInt(l/Z);return[Number($/J),Number($%J)*Z]}function xZ($,Z=1){let J=l/Z,[W,Y]=Q$($,J);return[W,Y*Z]}function hY($,Z=1){let[J,W]=$,Y=Math.floor(W/Z),j=l/Z;return BigInt(J)*BigInt(j)+BigInt(Y)}function o0($,Z=1,J){let[W,Y]=$,[j,z]=Q$(Y,Z);return W*(l/Z)+(j+(J?z/Z:0))}function w7($,Z,J=v1){let[W,Y]=$,[j,z]=J(Y,Z);return[W*(l/Z)+j,z]}function f7($,Z){let J=$.formatToParts(Z),W={};for(let Y of J)W[Y.type]=Y.value;return W}function q7($){return v0($,"isoYear",_3,N3,1),$.isoYear===_3?v0($,"isoMonth",4,12,1):$.isoYear===N3&&v0($,"isoMonth",1,9,1),$}function X$($){return m1({...$,...W1,isoHour:12}),$}function m1($){let Z=v0($,"isoYear",_3,N3,1),J=Z===_3?1:Z===N3?-1:0;return J&&a0(S0({...$,isoDay:$.isoDay+J,isoNanosecond:$.isoNanosecond-J})),$}function a0($){if(!$||mY($,pU,hU))throw RangeError(T4);return $}function B$($){return SY($,5,Q1)[1]}function n6($){let[Z,J]=v1($,l);return[u6(J,5,Q1),Z]}function pY($){return cY($)[0]}function cY($){return w7($,J1)}function b0($){return EZ($.isoYear,$.isoMonth,$.isoDay,$.isoHour,$.isoMinute,$.isoSecond,$.isoMillisecond)}function S0($){let Z=b0($);if(Z!==void 0){let[J,W]=Q$(Z,y0);return[J,W*H1+($.isoMicrosecond||0)*o$+($.isoNanosecond||0)]}}function v7($,Z){let[J,W]=n6(B$($)-Z);return a0(S0({...$,isoDay:$.isoDay+W,...J}))}function q6(...$){return EZ(...$)/HX}function EZ(...$){let[Z,J]=dY(...$),W=Z.valueOf();if(!isNaN(W))return W-J*y0}function dY($,Z=1,J=1,W=0,Y=0,j=0,z=0){let X=$===_3?1:$===N3?-1:0,G=new Date;return G.setUTCHours(W,Y,j,z),G.setUTCFullYear($,Z-1,J+X),[G,X]}function F$($,Z){let[J,W]=IZ($,Z);W<0&&(W+=l,J-=1);let[Y,j]=v1(W,H1),[z,X]=v1(j,o$);return o6(J*y0+Y,z,X)}function o6($,Z=0,J=0){let W=Math.ceil(Math.max(0,Math.abs($)-mU)/y0)*Math.sign($),Y=new Date($-W*y0);return SZ(C4,[Y.getUTCFullYear(),Y.getUTCMonth()+1,Y.getUTCDate()+W,Y.getUTCHours(),Y.getUTCMinutes(),Y.getUTCSeconds(),Y.getUTCMilliseconds(),Z,J])}function uY($){return[$.isoYear,$.isoMonth,$.isoDay]}function lY(){return q1}function g7($,Z){switch(Z){case 2:return y7($)?29:28;case 4:case 6:case 9:case 11:return 30}return 31}function iY($){return y7($)?366:365}function y7($){return $%4==0&&($%100!=0||$%400==0)}function sY($){let[Z,J]=dY($.isoYear,$.isoMonth,$.isoDay);return H3(Z.getUTCDay()-J,7)||7}function nY({isoYear:$}){return $<1?["bce",1-$]:["ce",$]}function uF($){let Z=b0($);if(Z<dU)return nY($);let J=f7(BW(CZ),Z),{era:W,eraYear:Y}=jz(J,CZ);return[W,Y]}function a6($){return p$($),t6($,1),$}function p$($){return oY($,1),$}function BY($){return CY(JW,$,oY($))}function oY($,Z){let{isoYear:J}=$,W=v0($,"isoMonth",1,lY(),Z);return{isoYear:J,isoMonth:W,isoDay:v0($,"isoDay",1,g7(J,W),Z)}}function t6($,Z){return SZ(Q1,[v0($,"isoHour",0,23,Z),v0($,"isoMinute",0,59,Z),v0($,"isoSecond",0,59,Z),v0($,"isoMillisecond",0,999,Z),v0($,"isoMicrosecond",0,999,Z),v0($,"isoNanosecond",0,999,Z)])}function y($){return $===void 0?0:fX(y1($))}function A3($,Z=0){$=z1($);let J=qX($),W=eU($,Z);return[fX($),W,J]}function m7($){return qX(z1($))}function aY($){return $=z1($),jW($,9,6,1)}function bZ($,Z,J,W=9,Y=0,j=4){Z=z1(Z);let z=jW(Z,W,Y),X=c7(Z),G=g3(Z,j),Q=v3(Z,W,Y,1);return z==null?z=Math.max(J,Q):$j(z,Q),X=d7(X,Q,1),$&&(G=((V)=>V<4?(V+2)%4:V)(G)),[z,Q,X,G]}function r6($,Z=6,J){let W=c7($=u7($,p6)),Y=g3($,7),j=v3($,Z);return j=fY(p6,j),W=d7(W,j,void 0,J),[j,W,Y]}function h7($){return zW(z1($))}function tY($,Z){return p7(z1($),Z)}function p7($,Z=4){let J=eY($);return[g3($,4),...rY(v3($,Z),J)]}function rY($,Z){return $!=null?[L1[$],$<4?9-3*$:-1]:[Z===void 0?1:10**(9-Z),Z]}function c7($){let Z=$[M3];return Z===void 0?1:A0(Z,M3)}function d7($,Z,J,W){let Y=W?l:L1[Z+1];if(Y){let j=L1[Z];if(Y%(($=$1(M3,$,1,Y/j-(W?0:1),1))*j))throw RangeError(k3(M3,$))}else $=$1(M3,$,1,J?1e9:1,1);return $}function eY($){let Z=$[L7];if(Z!==void 0){if(typeof Z!="number"){if(R7(Z)==="auto")return;throw RangeError(k3(L7,Z))}Z=$1(L7,Math.floor(Z),0,9,1)}return Z}function z1($){return $===void 0?{}:y1($)}function u7($,Z){return typeof $=="string"?{[Z]:$}:y1($)}function X0($){if($!==void 0){if(L0($))return Object.assign(Object.create(null),$);throw TypeError(jX)}}function e6($,Z){return $&&Object.assign(Object.create(null),$,{overflow:lU[Z]})}function l7($,Z,J=9,W=0,Y){let j=Z[$];if(j===void 0)return Y?W:void 0;if(j=R7(j),j==="auto")return Y?W:null;let z=P7[j];if(z===void 0&&(z=gU[j]),z===void 0)throw RangeError(QX($,j,P7));return $1($,z,W,J,1,f3),z}function c$($,Z,J,W=0){let Y=J[$];if(Y===void 0)return W;let j=R7(Y),z=Z[j];if(z===void 0)throw RangeError(QX($,j,Z));return z}function $j($,Z){if(Z>$)throw RangeError(EU)}function H0($){return{branding:S4,epochNanoseconds:$}}function N0($,Z,J){return{branding:d1,calendar:J,timeZone:Z,epochNanoseconds:$}}function G0($,Z=$.calendar){return{branding:t$,calendar:Z,...p0(bX,$)}}function Q0($,Z=$.calendar){return{branding:a$,calendar:Z,...p0(WW,$)}}function y$($,Z=$.calendar){return{branding:yZ,calendar:Z,...p0(WW,$)}}function v6($,Z=$.calendar){return{branding:mZ,calendar:Z,...p0(WW,$)}}function X1($){return{branding:A4,...p0(EX,$)}}function $0($){return{branding:E4,sign:U$($),...p0(eJ,$)}}function Zj($){return pY($.epochNanoseconds)}function $4($){return w7($.epochNanoseconds,H1)[0]}function Jj($){return hY($.epochNanoseconds,o$)}function Wj($){return hY($.epochNanoseconds)}function Yj($){return $.epochNanoseconds}function T0($){return typeof $=="string"?$:W0($.id)}function RZ($,Z){return $===Z||T0($)===T0(Z)}function jj($,Z,J,W,Y){let j=m$(W),[z,X]=((L,H)=>{let T=H((L=u7(L,I7))[kX]),K=rU(L);return K=fY(I7,K),[K,T]})(Y,$);if(T3(Math.max(z,j),X))return VY(W,z);if(!X)throw RangeError(P4);let[G,Q,V]=z4(Z,J,X),F=DJ(V),B=X4(V),U=LJ(V),D=B(Q,G,W),O=U(Q,G,D,z);return T3(z,X)?VY(O,z):((L,H,T,K,I,b,S)=>{let R=U$(L),[w,N]=i7(K,ZW(T,L),T,R,I,b,S),g=s7(H,w,N);return L[h[T]]+g*R})(O,F(D),z,Q,G,F,B)}function VY($,Z){return o0(D0($),L1[Z],1)}function i7($,Z,J,W,Y,j,z){let X=h[J],G={...Z,[X]:Z[X]+W},Q=z($,Y,Z),V=z($,Y,G);return[j(Q),j(V)]}function s7($,Z,J){let W=o0(n0(Z,J));if(!W)throw RangeError(w3);return o0(n0(Z,$))/W}function zj($,Z){let[J,W,Y]=r6(Z,5,1);return H0(J4($.epochNanoseconds,J,W,Y,1))}function Xj($,Z,J){let{epochNanoseconds:W,timeZone:Y,calendar:j}=Z,[z,X,G]=r6(J);if(z===0&&X===1)return Z;let Q=$(Y);if(z===6)W=((V,F,B,U)=>{let D=R0(B,F),[O,L]=V(D),H=B.epochNanoseconds,T=h0(F,O),K=h0(F,L);if(mY(H,T,K))throw RangeError(w3);return Lj(s7(H,T,K),U)?K:T})(Oj,Q,Z,G);else{let V=Q.getOffsetNanosecondsFor(W);W=u$(Q,Fj(F$(W,V),z,X,G),V,2,0,1)}return N0(W,Y,j)}function Gj($,Z){return G0(Fj($,...r6(Z)),$.calendar)}function Qj($,Z){let[J,W,Y]=r6(Z,5);var j;return X1((j=Y,n7($,S3(J,W),j)[0]))}function Bj($,Z){let J=$(Z.timeZone),W=R0(Z,J),[Y,j]=Oj(W),z=o0(n0(h0(J,Y),h0(J,j)),_4,1);if(z<=0)throw RangeError(w3);return z}function Vj($,Z){let{timeZone:J,calendar:W}=Z,Y=((j,z,X)=>h0(z,j(R0(X,z))))(Dj,$(J),Z);return N0(Y,J,W)}function Fj($,Z,J,W){return Uj($,S3(Z,J),W)}function Uj($,Z,J){let[W,Y]=n7($,Z,J);return m1({...l$($,Y),...W})}function n7($,Z,J){return n6(V$(B$($),Z,J))}function g6($){return V$($,N4,7)}function S3($,Z){return L1[$]*Z}function Oj($){let Z=Dj($);return[Z,l$(Z,1)]}function Dj($){return yU(6,$)}function lF($,Z,J){let W=Math.min(m$($),6);return wZ(W4(D0($,W),Z,J),W)}function Z4($,Z,J,W,Y,j,z,X,G,Q){if(W===0&&Y===1)return $;let V=T3(W,X)?G4(X)&&W<6&&J>=6?sF:iF:nF,[F,B,U]=V($,Z,J,W,Y,j,z,X,G,Q);return U&&W!==7&&(F=((D,O,L,H,T,K,I,b)=>{let S=U$(D);for(let R=H+1;R<=L;R++){if(R===7&&L!==7)continue;let w=ZW(R,D);w[h[R]]+=S;let N=o0(n0(I(b(T,K,w)),O));if(N&&Math.sign(N)!==S)break;D=w}return D})(F,B,J,Math.max(6,W),z,X,G,Q)),F}function J4($,Z,J,W,Y){if(Z===6){let j=((z)=>z[0]+z[1]/l)($);return[V$(j,J,W),0]}return W4($,S3(Z,J),W,Y)}function W4($,Z,J,W){let[Y,j]=$;W&&j<0&&(j+=l,Y-=1);let[z,X]=v1(V$(j,Z,J),l);return k7(Y+z,X)}function V$($,Z,J){return Lj($/Z,J)*Z}function Lj($,Z){return JO[Z]($)}function iF($,Z,J,W,Y,j){let z=U$($),X=D0($),G=J4(X,W,Y,j),Q=n0(X,G),V=Math.sign(G[0]-X[0])===z,F=wZ(G,Math.min(J,6));return[{...$,...F},_Z(Z,Q),V]}function sF($,Z,J,W,Y,j,z,X,G,Q){let V=U$($),F=o0(D0($,5)),B=S3(W,Y),U=V$(F,B,j),[D,O]=i7(z,{...$,...$W},6,V,X,G,Q),L=U-o0(n0(D,O)),H=0;L&&Math.sign(L)!==V?Z=IZ(D,U):(H+=V,U=V$(L,B,j),Z=IZ(O,U));let T=B4(U);return[{...$,...T,days:$.days+H},Z,Boolean(H)]}function nF($,Z,J,W,Y,j,z,X,G,Q){let V=U$($),F=h[W],B=ZW(W,$);W===7&&($={...$,weeks:$.weeks+Math.trunc($.days/7)});let U=d6($[F],Y)*Y;B[F]=U;let[D,O]=i7(z,B,W,Y*V,X,G,Q),L=U+s7(Z,D,O)*V*Y,H=V$(L,Y,j),T=Math.sign(H-L)===V;return B[F]=H,[B,T?O:D,T]}function o7($,Z,J,W){let[Y,j,z,X]=((Q)=>{let V=p7(Q=z1(Q));return[Q.timeZone,...V]})(W),G=Y!==void 0;return((Q,V,F,B,U,D)=>{F=W4(F,U,B,1);let O=V.getOffsetNanosecondsFor(F);return JJ(F$(F,O),D)+(Q?d$(g6(O)):"Z")})(G,Z(G?$(Y):r$),J.epochNanoseconds,j,z,X)}function a7($,Z,J){let[W,Y,j,z,X,G]=((Q)=>{Q=z1(Q);let V=zW(Q),F=eY(Q),B=ZO(Q),U=g3(Q,4),D=v3(Q,4);return[V,$O(Q),B,U,...rY(D,F)]})(J);return((Q,V,F,B,U,D,O,L,H,T)=>{B=W4(B,H,L,1);let K=Q(F).getOffsetNanosecondsFor(B);return JJ(F$(B,K),T)+d$(g6(K),O)+((I,b)=>b!==1?"["+(b===2?"!":"")+T0(I)+"]":"")(F,D)+WJ(V,U)})($,Z.calendar,Z.timeZone,Z.epochNanoseconds,W,Y,j,z,X,G)}function t7($,Z){let[J,W,Y,j]=((Q)=>(Q=z1(Q),[zW(Q),...p7(Q)]))(Z);return z=$.calendar,X=J,G=j,JJ(Uj($,Y,W),G)+WJ(z,X);var z,X,G}function r7($,Z){return J=$.calendar,W=$,Y=h7(Z),y6(W)+WJ(J,Y);var J,W,Y}function e7($,Z){return Hj($.calendar,Mj,$,h7(Z))}function $J($,Z){return Hj($.calendar,oF,$,h7(Z))}function ZJ($,Z){let[J,W,Y]=tY(Z);return j=Y,Kj(n7($,W,J)[0],j);var j}function Y4($,Z){let[J,W,Y]=tY(Z,3);return W>1&&($={...$,...lF($,W,J)}),((j,z)=>{let{sign:X}=j,G=X===-1?k0(j):j,{hours:Q,minutes:V}=G,[F,B]=w7(D0(G,3),J1,Q$);Aj(F);let U=YJ(B,z),D=z>=0||!X||U;return(X<0?"-":"")+"P"+FY({Y:g$(G.years),M:g$(G.months),W:g$(G.weeks),D:g$(G.days)})+(Q||V||F||D?"T"+FY({H:g$(Q),M:g$(V),S:g$(F,D)+U}):"")})($,Y)}function Hj($,Z,J,W){let Y=T0($),j=W>1||W===0&&Y!==q;return W===1?Y===q?Z(J):y6(J):j?y6(J)+Tj(Y,W===2):Z(J)}function FY($){let Z=[];for(let J in $){let W=$[J];W&&Z.push(W,J)}return Z.join("")}function JJ($,Z){return y6($)+"T"+Kj($,Z)}function y6($){return Mj($)+"-"+Z1($.isoDay)}function Mj($){let{isoYear:Z}=$;return(Z<0||Z>9999?Pj(Z)+w6(6,Math.abs(Z)):w6(4,Z))+"-"+Z1($.isoMonth)}function oF($){return Z1($.isoMonth)+"-"+Z1($.isoDay)}function Kj($,Z){let J=[Z1($.isoHour),Z1($.isoMinute)];return Z!==-1&&J.push(Z1($.isoSecond)+((W,Y,j,z)=>YJ(W*H1+Y*o$+j,z))($.isoMillisecond,$.isoMicrosecond,$.isoNanosecond,Z)),J.join(":")}function d$($,Z=0){if(Z===1)return"";let[J,W]=v1(Math.abs($),_4),[Y,j]=v1(W,N4),[z,X]=v1(j,J1);return Pj($)+Z1(J)+":"+Z1(Y)+(z||X?":"+Z1(z)+YJ(X):"")}function WJ($,Z){if(Z!==1){let J=T0($);if(Z>1||Z===0&&J!==q)return Tj(J,Z===2)}return""}function Tj($,Z){return"["+(Z?"!":"")+"u-ca="+$+"]"}function YJ($,Z){let J=w6(9,$);return J=Z===void 0?J.replace(jO,""):J.slice(0,Z),J?"."+J:""}function Pj($){return $<0?"-":"+"}function g$($,Z){return $||Z?$.toLocaleString("fullwide",{useGrouping:0}):""}function aF($,Z){let{epochNanoseconds:J}=$,W=(Z.getOffsetNanosecondsFor?Z:Z($.timeZone)).getOffsetNanosecondsFor(J),Y=F$(J,W);return{calendar:$.calendar,...Y,offsetNanoseconds:W}}function Nj($,Z){let J=R0(Z,$);return{calendar:Z.calendar,...p0(bX,J),offset:d$(J.offsetNanoseconds),timeZone:Z.timeZone}}function u$($,Z,J,W=0,Y=0,j,z){if(J!==void 0&&W===1&&(W===1||z))return v7(Z,J);let X=$.getPossibleInstantsFor(Z);if(J!==void 0&&W!==3){let G=((Q,V,F,B)=>{let U=S0(V);B&&(F=g6(F));for(let D of Q){let O=o0(n0(D,U));if(B&&(O=g6(O)),O===F)return D}})(X,Z,J,j);if(G!==void 0)return G;if(W===0)throw RangeError(_U)}return z?S0(Z):h0($,Z,Y,X)}function h0($,Z,J=0,W=$.getPossibleInstantsFor(Z)){if(W.length===1)return W[0];if(J===1)throw RangeError(IU);if(W.length)return W[J===3?1:0];let Y=S0(Z),j=((X,G)=>{let Q=X.getOffsetNanosecondsFor(IZ(G,-l));return zJ(X.getOffsetNanosecondsFor(IZ(G,l))-Q)})($,Y),z=j*(J===2?-1:1);return(W=$.getPossibleInstantsFor(F$(Y,z)))[J===2?0:W.length-1]}function jJ($){if(Math.abs($)>=l)throw RangeError(PU);return $}function zJ($){if($>l)throw RangeError(NU);return $}function XJ($,Z,J){return H0(a0(_Z(Z.epochNanoseconds,((W)=>{if(Sj(W))throw RangeError(AU);return D0(W,5)})($?k0(J):J))))}function GJ($,Z,J,W,Y,j=Object.create(null)){let z=Z(W.timeZone),X=$(W.calendar);return{...W,...UJ(z,X,W,J?k0(Y):Y,j)}}function QJ($,Z,J,W,Y=Object.create(null)){let{calendar:j}=J;return G0(OJ($(j),J,Z?k0(W):W,Y),j)}function BJ($,Z,J,W,Y){let{calendar:j}=J;return Q0(j4($(j),J,Z?k0(W):W,Y),j)}function VJ($,Z,J,W,Y=Object.create(null)){let j=J.calendar,z=$(j),X=K3(z,J);Z&&(W=Q4(W)),W.sign<0&&(X=z.dateAdd(X,{...P0,months:1}),X=l$(X,-1));let G=z.dateAdd(X,W,Y);return y$(K3(z,G),j)}function FJ($,Z,J){return X1(_j(Z,$?k0(J):J)[0])}function UJ($,Z,J,W,Y){let j=D0(W,5),z=J.epochNanoseconds;if(Sj(W)){let X=R0(J,$);z=_Z(h0($,{...j4(Z,X,{...W,...$W},Y),...p0(Q1,X)}),j)}else z=_Z(z,j),y(Y);return{epochNanoseconds:a0(z)}}function OJ($,Z,J,W){let[Y,j]=_j(Z,J);return m1({...j4($,Z,{...J,...$W,days:J.days+j},W),...Y})}function j4($,Z,J,W){if(J.years||J.months||J.weeks)return $.dateAdd(Z,J,W);y(W);let Y=J.days+D0(J,5)[0];return Y?X$(l$(Z,Y)):Z}function K3($,Z,J=1){return l$(Z,J-$.day(Z))}function _j($,Z){let[J,W]=D0(Z,5),[Y,j]=n6(B$($)+W);return[Y,J+j]}function l$($,Z){return Z?{...$,...o6(b0($)+Z*y0)}:$}function z4($,Z,J){let W=$(J.calendar);return G4(J)?[J,W,Z(J.timeZone)]:[{...J,...W1},W]}function DJ($){return $?Yj:S0}function X4($){return $?f(UJ,$):OJ}function LJ($){return $?f(rF,$):eF}function G4($){return $&&$.epochNanoseconds}function T3($,Z){return $<=6-(G4(Z)?1:0)}function HJ($,Z,J,W,Y,j,z){let X=$(z1(z).relativeTo),G=Math.max(m$(Y),m$(j));if(T3(G,X))return $0(kZ(((O,L,H,T)=>{let K=_Z(D0(O),D0(L),T?-1:1);if(!Number.isFinite(K[0]))throw RangeError(T4);return{...P0,...wZ(K,H)}})(Y,j,G,W)));if(!X)throw RangeError(P4);W&&(j=k0(j));let[Q,V,F]=z4(Z,J,X),B=X4(F),U=LJ(F),D=B(V,Q,Y);return $0(U(V,Q,B(V,D,j),G))}function Ij($,Z,J,W,Y){let j=m$(W),[z,X,G,Q,V]=((S,R,w)=>{S=u7(S,p6);let N=jW(S),g=w(S[kX]),_=c7(S),k=g3(S,7),M0=v3(S);if(N===void 0&&M0===void 0)throw RangeError(SU);return M0==null&&(M0=0),N==null&&(N=Math.max(M0,R)),$j(N,M0),_=d7(_,M0,1),[N,M0,_,k,g]})(Y,j,$),F=Math.max(j,z);if(!G4(V)&&F<=6)return $0(kZ(((S,R,w,N,g)=>{let _=J4(D0(S),w,N,g);return{...P0,...wZ(_,R)}})(W,z,X,G,Q)));if(!V)throw RangeError(P4);let[B,U,D]=z4(Z,J,V),O=DJ(D),L=X4(D),H=LJ(D),T=L(U,B,W),K=H(U,B,T,z),I=W.sign,b=U$(K);if(I&&b&&I!==b)throw RangeError(w3);return b&&(K=Z4(K,O(T),z,X,G,Q,U,B,O,L)),$0(K)}function xj($){return $.sign===-1?Q4($):$}function Q4($){return $0(k0($))}function k0($){let Z={};for(let J of h)Z[J]=-1*$[J]||0;return Z}function Cj($){return!$.sign}function U$($,Z=h){let J=0;for(let W of Z){let Y=Math.sign($[W]);if(Y){if(J&&J!==Y)throw RangeError(CU);J=Y}}return J}function kZ($){for(let Z of vU)$1(Z,$[Z],-KY,KY,1);return Aj(o0(D0($),J1)),$}function Aj($){if(!Number.isSafeInteger($))throw RangeError(xU)}function D0($,Z=6){return SY($,Z,h)}function wZ($,Z=6){let[J,W]=$,Y=u6(W,Z,h);if(Y[h[Z]]+=J*(l/L1[Z]),!Number.isFinite(Y[h[Z]]))throw RangeError(T4);return Y}function B4($,Z=5){return u6($,Z,h)}function Sj($){return Boolean(U$($,SX))}function m$($){let Z=9;for(;Z>0&&!$[h[Z]];Z--);return Z}function tF($,Z){return[$,Z]}function UY($){let Z=Math.floor($/R6)*R6;return[Z,Z+R6]}function Ej($){let Z=O$($=f6($));if(!Z)throw RangeError(g0($));let J;if(Z.m)J=0;else{if(!Z.offset)throw RangeError(g0($));J=fZ(Z.offset)}return Z.timeZone&&PJ(Z.timeZone,1),H0(v7(a6(Z),J))}function bj($){let Z=O$(W0($));if(!Z)throw RangeError(g0($));if(Z.timeZone)return mj(Z,Z.offset?fZ(Z.offset):void 0);if(Z.m)throw RangeError(g0($));return pj(Z)}function Rj($,Z){let J=O$(W0($));if(!J||!J.timeZone)throw RangeError(g0($));let{offset:W}=J,Y=W?fZ(W):void 0,[,j,z]=A3(Z);return mj(J,Y,j,z)}function fZ($){let Z=PJ($);if(Z===void 0)throw RangeError(g0($));return Z}function kj($){let Z=O$(W0($));if(!Z||Z.m)throw RangeError(g0($));return G0(hj(Z))}function V4($){let Z=O$(W0($));if(!Z||Z.m)throw RangeError(g0($));return Q0(Z.p?hj(Z):pj(Z))}function wj($,Z){let J=KJ(W0(Z));if(J)return MJ(J),y$(q7(p$(J)));let W=V4(Z);return y$(K3($(W.calendar),W))}function MJ($){if($.calendar!==q)throw RangeError(g1($.calendar))}function fj($,Z){let J=TJ(W0(Z));if(J)return MJ(J),v6(p$(J));let W=V4(Z),{calendar:Y}=W,j=$(Y),[z,X,G]=j.h(W),[Q,V]=j.I(z,X),[F,B]=j.N(Q,V,G);return v6(X$(j.P(F,B,G)),Y)}function qj($){let Z,J=((W)=>{let Y=BO.exec(W);return Y?(F4(Y[10]),uj(Y)):void 0})(W0($));if(!J){if(J=O$($),!J)throw RangeError(g0($));if(!J.p)throw RangeError(g0($));if(J.m)throw RangeError(g1("Z"));MJ(J)}if((Z=KJ($))&&BY(Z))throw RangeError(g0($));if((Z=TJ($))&&BY(Z))throw RangeError(g0($));return X1(t6(J,1))}function vj($){let Z=((J)=>{let W=UO.exec(J);return W?((Y)=>{function j(V,F,B){let U=0,D=0;if(B&&([U,G]=v1(G,L1[B])),V!==void 0){if(X)throw RangeError(g1(V));D=((O)=>{let L=parseInt(O);if(!Number.isFinite(L))throw RangeError(g1(O));return L})(V),z=1,F&&(G=NJ(F)*(L1[B]/J1),X=1)}return U+D}let z=0,X=0,G=0,Q={...SZ(h,[j(Y[2]),j(Y[3]),j(Y[4]),j(Y[5]),j(Y[6],Y[7],5),j(Y[8],Y[9],4),j(Y[10],Y[11],3)]),...u6(G,2,h)};if(!z)throw RangeError(XX(h));return _J(Y[1])<0&&(Q=k0(Q)),Q})(W):void 0})(W0($));if(!Z)throw RangeError(g0($));return $0(kZ(Z))}function gj($){let Z=O$($)||KJ($)||TJ($);return Z?Z.calendar:$}function yj($){let Z=O$($);return Z&&(Z.timeZone||Z.m&&r$||Z.offset)||$}function mj($,Z,J=0,W=0){let Y=U4($.timeZone),j=b4(Y);return N0(u$(j,a6($),Z,J,W,!j.v,$.m),Y,E3($.calendar))}function hj($){return cj(m1(a6($)))}function pj($){return cj(X$(p$($)))}function cj($){return{...$,calendar:E3($.calendar)}}function O$($){let Z=QO.exec($);return Z?((J)=>{let W=J[10],Y=(W||"").toUpperCase()==="Z";return{isoYear:dj(J),isoMonth:parseInt(J[4]),isoDay:parseInt(J[5]),...uj(J.slice(5)),...F4(J[16]),p:Boolean(J[6]),m:Y,offset:Y?void 0:W}})(Z):void 0}function KJ($){let Z=XO.exec($);return Z?((J)=>({isoYear:dj(J),isoMonth:parseInt(J[4]),isoDay:1,...F4(J[5])}))(Z):void 0}function TJ($){let Z=GO.exec($);return Z?((J)=>({isoYear:AZ,isoMonth:parseInt(J[1]),isoDay:parseInt(J[2]),...F4(J[3])}))(Z):void 0}function PJ($,Z){let J=VO.exec($);return J?((W,Y)=>{let j=W[4]||W[5];if(Y&&j)throw RangeError(g1(j));return jJ((NZ(W[2])*_4+NZ(W[3])*N4+NZ(W[4])*J1+NJ(W[5]||""))*_J(W[1]))})(J,Z):void 0}function dj($){let Z=_J($[1]),J=parseInt($[2]||$[3]);if(Z<0&&!J)throw RangeError(g1(-0));return Z*J}function uj($){let Z=NZ($[3]);return{...n6(NJ($[4]||""))[0],isoHour:NZ($[1]),isoMinute:NZ($[2]),isoSecond:Z===60?59:Z}}function F4($){let Z,J,W=[];if($.replace(FO,(Y,j,z)=>{let X=Boolean(j),[G,Q]=z.split("=").reverse();if(Q){if(Q==="u-ca")W.push(G),Z||(Z=X);else if(X||/[A-Z]/.test(Q))throw RangeError(g1(Y))}else{if(J)throw RangeError(g1(Y));J=G}return""}),W.length>1&&Z)throw RangeError(g1($));return{timeZone:J,calendar:W[0]||q}}function NJ($){return parseInt($.padEnd(9,"0"))}function qZ($){return new RegExp(`^${$}$`,"i")}function _J($){return $&&$!=="+"?-1:1}function NZ($){return $===void 0?0:parseInt($)}function lj($){return U4(W0($))}function U4($){let Z=IJ($);return typeof Z=="number"?d$(Z):Z?((J)=>{if(DO.test(J))throw RangeError(TU);return J.toLowerCase().split("/").map((W,Y)=>(W.length<=3||/\d/.test(W))&&!/etc|yap/.test(W)?W.toUpperCase():W.replace(/baja|dumont|[a-z]+/g,(j,z)=>j.length<=2&&!Y||j==="in"||j==="chat"?j.toUpperCase():j.length>2||!z?GY(j).replace(/island|noronha|murdo|rivadavia|urville/,GY):j)).join("/")})($):r$}function OY($){let Z=IJ($);return typeof Z=="number"?Z:Z?Z.resolvedOptions().timeZone:r$}function IJ($){let Z=PJ($=$.toUpperCase(),1);return Z!==void 0?Z:$!==r$?OO($):void 0}function xJ($,Z){return E0($.epochNanoseconds,Z.epochNanoseconds)}function CJ($,Z){return E0($.epochNanoseconds,Z.epochNanoseconds)}function ij($,Z,J,W,Y,j){let z=$(z1(j).relativeTo),X=Math.max(m$(W),m$(Y));if(CY(h,W,Y))return 0;if(T3(X,z))return E0(D0(W),D0(Y));if(!z)throw RangeError(P4);let[G,Q,V]=z4(Z,J,z),F=DJ(V),B=X4(V);return E0(F(B(Q,G,W)),F(B(Q,G,Y)))}function AJ($,Z){return i$($,Z)||O4($,Z)}function i$($,Z){return z$(b0($),b0(Z))}function O4($,Z){return z$(B$($),B$(Z))}function sj($,Z){return!xJ($,Z)}function nj($,Z){return!CJ($,Z)&&!!D4($.timeZone,Z.timeZone)&&RZ($.calendar,Z.calendar)}function oj($,Z){return!AJ($,Z)&&RZ($.calendar,Z.calendar)}function aj($,Z){return!i$($,Z)&&RZ($.calendar,Z.calendar)}function tj($,Z){return!i$($,Z)&&RZ($.calendar,Z.calendar)}function rj($,Z){return!i$($,Z)&&RZ($.calendar,Z.calendar)}function ej($,Z){return!O4($,Z)}function D4($,Z){if($===Z)return 1;let J=T0($),W=T0(Z);if(J===W)return 1;try{return OY(J)===OY(W)}catch(Y){}}function SJ($,Z,J,W){let Y=bZ($,X0(W),3,5),j=L4(Z.epochNanoseconds,J.epochNanoseconds,...Y);return $0($?k0(j):j)}function EJ($,Z,J,W,Y,j){let z=M4(W.calendar,Y.calendar),X=X0(j),[G,Q,V,F]=bZ(J,X,5),B=W.epochNanoseconds,U=Y.epochNanoseconds,D=E0(U,B),O;if(D)if(G<6)O=L4(B,U,G,Q,V,F);else{let L=Z(((T,K)=>{if(!D4(T,K))throw RangeError(UX);return T})(W.timeZone,Y.timeZone)),H=$(z);O=Zz(H,L,W,Y,D,G,X),O=Z4(O,U,G,Q,V,F,H,W,Yj,f(UJ,L))}else O=P0;return $0(J?k0(O):O)}function bJ($,Z,J,W,Y){let j=M4(J.calendar,W.calendar),z=X0(Y),[X,G,Q,V]=bZ(Z,z,6),F=S0(J),B=S0(W),U=E0(B,F),D;if(U)if(X<=6)D=L4(F,B,X,G,Q,V);else{let O=$(j);D=Jz(O,J,W,U,X,z),D=Z4(D,B,X,G,Q,V,O,J,S0,OJ)}else D=P0;return $0(Z?k0(D):D)}function RJ($,Z,J,W,Y){let j=M4(J.calendar,W.calendar),z=X0(Y);return $z(Z,()=>$(j),J,W,...bZ(Z,z,6,9,6),z)}function kJ($,Z,J,W,Y){let j=M4(J.calendar,W.calendar),z=X0(Y),X=bZ(Z,z,9,9,8),G=$(j);return $z(Z,()=>G,K3(G,J),K3(G,W),...X,z)}function $z($,Z,J,W,Y,j,z,X,G){let Q=S0(J),V=S0(W),F;if(E0(V,Q))if(Y===6)F=L4(Q,V,Y,j,z,X);else{let B=Z();F=B.dateUntil(J,W,Y,G),j===6&&z===1||(F=Z4(F,V,Y,j,z,X,B,J,S0,j4))}else F=P0;return $0($?k0(F):F)}function wJ($,Z,J,W){let Y=X0(W),[j,z,X,G]=bZ($,Y,5,5),Q=V$(fJ(Z,J),S3(z,X),G),V={...P0,...B4(Q,j)};return $0($?k0(V):V)}function rF($,Z,J,W,Y,j){let z=E0(W.epochNanoseconds,J.epochNanoseconds);return z?Y<6?Wz(J.epochNanoseconds,W.epochNanoseconds,Y):Zz(Z,$,J,W,z,Y,j):P0}function eF($,Z,J,W,Y){let j=S0(Z),z=S0(J),X=E0(z,j);return X?W<=6?Wz(j,z,W):Jz($,Z,J,X,W,Y):P0}function Zz($,Z,J,W,Y,j,z){let[X,G,Q]=((B,U,D,O)=>{function L(){return R={...l$(K,b++*-O),...T},w=h0(B,R),E0(I,w)===-O}let H=R0(U,B),T=p0(Q1,H),K=R0(D,B),I=D.epochNanoseconds,b=0,S=fJ(H,K),R,w;if(Math.sign(S)===-O&&b++,L()&&(O===-1||L()))throw RangeError(w3);let N=o0(n0(w,I));return[H,R,N]})(Z,J,W,Y);var V,F;return{...j===6?(V=X,F=G,{...P0,days:Yz(V,F)}):$.dateUntil(X,G,j,z),...B4(Q)}}function Jz($,Z,J,W,Y,j){let[z,X,G]=((Q,V,F)=>{let B=V,U=fJ(Q,V);return Math.sign(U)===-F&&(B=l$(V,-F),U+=l*F),[Q,B,U]})(Z,J,W);return{...$.dateUntil(z,X,Y,j),...B4(G)}}function L4($,Z,J,W,Y,j){return{...P0,...wZ(J4(n0($,Z),W,Y,j),J)}}function Wz($,Z,J){return{...P0,...wZ(n0($,Z),J)}}function Yz($,Z){return H4(b0($),b0(Z))}function H4($,Z){return Math.trunc((Z-$)/y0)}function fJ($,Z){return B$(Z)-B$($)}function M4($,Z){if(!RZ($,Z))throw RangeError(oJ);return $}function $U($){function Z(Y){return((j,z)=>({...jz(j,z),F:j.month,day:parseInt(j.day)}))(f7(J,Y),W)}let J=BW($),W=m6($);return{id:$,O:ZU(Z),B:JU(Z)}}function ZU($){return m0((Z)=>{let J=b0(Z);return $(J)},WeakMap)}function JU($){let Z=$(0).year-cU;return m0((J)=>{let W,Y=EZ(J-Z),j=[],z=[];do Y+=400*y0;while((W=$(Y)).year<=J);do Y+=(1-W.day)*y0,W.year===J&&(j.push(Y),z.push(W.F)),Y-=y0;while((W=$(Y)).year>=J);return{k:j.reverse(),C:LX(z.reverse())}})}function jz($,Z){let J,W,Y=zz($);if($.era){let j=xX[Z];j!==void 0&&(J=Z==="islamic"?"ah":$.era.normalize("NFD").toLowerCase().replace(/[^a-z0-9]/g,""),J==="bc"||J==="b"?J="bce":J!=="ad"&&J!=="a"||(J="ce"),W=Y,Y=Vz(W,j[J]||0))}return{era:J,eraYear:W,year:Y}}function zz($){return parseInt($.relatedYear||$.year)}function M7($){let{year:Z,F:J,day:W}=this.O($),{C:Y}=this.B(Z);return[Z,Y[J]+1,W]}function P3($,Z=1,J=1){return this.B($).k[Z-1]+(J-1)*y0}function S6($){let Z=LY(this,$),J=LY(this,$-1),W=Z.length;if(W>J.length){let Y=Fz(this);if(Y<0)return-Y;for(let j=0;j<W;j++)if(Z[j]!==J[j])return j+1}}function E6($){return H4(P3.call(this,$),P3.call(this,$+1))}function DY($,Z){let{k:J}=this.B($),W=Z+1,Y=J;return W>J.length&&(W=1,Y=this.B($+1).k),H4(J[Z-1],Y[W-1])}function b6($){return this.B($).k.length}function LY($,Z){return Object.keys($.B(Z).C)}function Xz($){return E3(W0($))}function E3($){if(($=$.toLowerCase())!==q&&$!==x4&&m6($)!==m6(BW($).resolvedOptions().calendar))throw RangeError(KU($));return $}function m6($){return $==="islamicc"&&($="islamic"),$.split("-")[0]}function Gz($){return this.R($)[0]}function Qz($){return this.R($)[1]}function qJ($){let[Z]=this.h($);return H4(this.q(Z),b0($))+1}function Bz($){let Z=HO.exec($);if(!Z)throw RangeError(HU($));return[parseInt(Z[1]),Boolean(Z[2])]}function h6($,Z,J){return $+(Z||J&&$>=J?1:0)}function K7($,Z){return $-(Z&&$>=Z?1:0)}function Vz($,Z){return(Z+$)*(Math.sign(Z)||1)||0}function T7($){return xX[Uz($)]}function Fz($){return wU[Uz($)]}function Uz($){return m6($.id||q)}function Oz($,Z,J,W){let Y=D$(J,W,G1,[],PX);if(Y.timeZone!==void 0){let j=J.dateFromFields(Y),z=s$(Y),X=$(Y.timeZone);return{epochNanoseconds:u$(Z(X),{...j,...z},Y.offset!==void 0?fZ(Y.offset):void 0),timeZone:X}}return{...J.dateFromFields(Y),...W1}}function Dz($,Z,J,W,Y,j){let z=D$(J,Y,G1,KX,PX),X=$(z.timeZone),[G,Q,V]=A3(j),F=J.dateFromFields(z,e6(j,G)),B=s$(z,G);return N0(u$(Z(X),{...F,...B},z.offset!==void 0?fZ(z.offset):void 0,Q,V),X,W)}function Lz($,Z,J){let W=D$($,Z,G1,[],c1),Y=y(J);return G0(m1({...$.dateFromFields(W,e6(J,Y)),...s$(W,Y)}))}function vJ($,Z,J,W=[]){let Y=D$($,Z,G1,W);return $.dateFromFields(Y,J)}function gJ($,Z,J,W){let Y=D$($,Z,rJ,W);return $.yearMonthFromFields(Y,J)}function yJ($,Z,J,W,Y=[]){let j=D$($,J,G1,Y);return Z&&j.month!==void 0&&j.monthCode===void 0&&j.year===void 0&&(j.year=AZ),$.monthDayFromFields(j,W)}function Hz($,Z){let J=y(Z);return X1(s$(D1($,N7,[],1),J))}function Mz($){let Z=D1($,eJ);return $0(kZ({...P0,...Z}))}function D$($,Z,J,W=[],Y=[]){return D1(Z,[...$.fields(J),...Y].sort(),W)}function D1($,Z,J,W=!J){let Y={},j,z=0;for(let X of Z){if(X===j)throw RangeError(VU(X));if(X==="constructor"||X==="__proto__")throw RangeError(sJ(X));let G=$[X];if(G!==void 0)z=1,TY[X]&&(G=TY[X](G,X)),Y[X]=G;else if(J){if(J.includes(X))throw TypeError(iJ(X));Y[X]=IX[X]}j=X}if(W&&!z)throw TypeError(XX(Z));return Y}function s$($,Z){return t6(PO({...IX,...$}),Z)}function Kz($,Z,J,W,Y,j){let z=X0(j),{calendar:X,timeZone:G}=J;return N0(((Q,V,F,B,U)=>{let D=b3(Q,F,B,G1,TX,MX),[O,L,H]=A3(U,2);return u$(V,{...Q.dateFromFields(D,e6(U,O)),...s$(D,O)},fZ(D.offset),L,H)})($(X),Z(G),W,Y,z),G,X)}function Tz($,Z,J,W,Y){let j=X0(Y);return G0(((z,X,G,Q)=>{let V=b3(z,X,G,G1,c1),F=y(Q);return m1({...z.dateFromFields(V,e6(Q,F)),...s$(V,F)})})($(Z.calendar),J,W,j))}function Pz($,Z,J,W,Y){let j=X0(Y);return((z,X,G,Q)=>{let V=b3(z,X,G,G1);return z.dateFromFields(V,Q)})($(Z.calendar),J,W,j)}function Nz($,Z,J,W,Y){let j=X0(Y);return y$(((z,X,G,Q)=>{let V=b3(z,X,G,rJ);return z.yearMonthFromFields(V,Q)})($(Z.calendar),J,W,j))}function _z($,Z,J,W,Y){let j=X0(Y);return((z,X,G,Q)=>{let V=b3(z,X,G,G1);return z.monthDayFromFields(V,Q)})($(Z.calendar),J,W,j)}function Iz($,Z,J){return X1(((W,Y,j)=>{let z=y(j);return s$({...p0(N7,W),...D1(Y,N7)},z)})($,Z,J))}function xz($,Z){return $0((J=$,W=Z,kZ({...J,...D1(W,eJ)})));var J,W}function b3($,Z,J,W,Y=[],j=[]){let z=[...$.fields(W),...Y].sort(),X=D1(Z,z,j),G=D1(J,z);return X=$.mergeFields(X,G),D1(X,z,[])}function mJ($,Z){let J=D$($,Z,_X);return $.monthDayFromFields(J)}function hJ($,Z,J){let W=D$($,Z,NX);return $.yearMonthFromFields(W,J)}function Cz($,Z,J,W,Y){Z=p0(J=$.fields(J),Z),W=D1(W,Y=$.fields(Y),[]);let j=$.mergeFields(Z,W);return j=D1(j,[...J,...Y].sort(),[]),$.dateFromFields(j)}function U7($,Z){let{era:J,eraYear:W,year:Y}=Z,j=T7($);if(J!==void 0||W!==void 0){if(J===void 0||W===void 0)throw TypeError(UU);if(!j)throw RangeError(FU);let z=j[J];if(z===void 0)throw RangeError(DU(J));let X=Vz(W,z);if(Y!==void 0&&Y!==X)throw RangeError(OU);Y=X}else if(Y===void 0)throw TypeError(LU(j));return Y}function O7($,Z,J,W){let{month:Y,monthCode:j}=Z;if(j!==void 0){let z=((X,G,Q,V)=>{let F=X.U(Q),[B,U]=Bz(G),D=h6(B,U,F);if(U){let O=Fz(X);if(O===void 0)throw RangeError(L3);if(O>0){if(D>O)throw RangeError(L3);if(F===void 0){if(V===1)throw RangeError(L3);D--}}else{if(D!==-O)throw RangeError(L3);if(F===void 0&&V===1)throw RangeError(L3)}}return D})($,j,J,W);if(Y!==void 0&&Y!==z)throw RangeError(VX);Y=z,W=1}else if(Y===void 0)throw TypeError(MU);return $1("month",Y,1,$.L(J),W)}function HY($,Z,J,W,Y){return v0(Z,"day",1,$.j(W,J),Y)}function D7($,Z,J,W){let Y=0,j=[];for(let z of J)Z[z]!==void 0?Y=1:j.push(z);if(Object.assign($,Z),Y)for(let z of W||j)delete $[z]}function Az($){return H0(a0(s6(i6($))))}function Sz($,Z,J,W,Y=q){return N0(a0(s6(i6(J))),Z(W),$(Y))}function Ez($,Z,J,W,Y=0,j=0,z=0,X=0,G=0,Q=0,V=q){return G0(m1(a6(Y1(A0,SZ(C4,[Z,J,W,Y,j,z,X,G,Q])))),$(V))}function bz($,Z,J,W,Y=q){return Q0(X$(p$(Y1(A0,{isoYear:Z,isoMonth:J,isoDay:W}))),$(Y))}function Rz($,Z,J,W=q,Y=1){let j=A0(Z),z=A0(J),X=$(W);return y$(q7(p$({isoYear:j,isoMonth:z,isoDay:A0(Y)})),X)}function kz($,Z,J,W=q,Y=AZ){let j=A0(Z),z=A0(J),X=$(W);return v6(X$(p$({isoYear:A0(Y),isoMonth:j,isoDay:z})),X)}function wz($=0,Z=0,J=0,W=0,Y=0,j=0){return X1(t6(Y1(A0,SZ(Q1,[$,Z,J,W,Y,j])),1))}function fz($=0,Z=0,J=0,W=0,Y=0,j=0,z=0,X=0,G=0,Q=0){return $0(kZ(Y1(yY,SZ(h,[$,Z,J,W,Y,j,z,X,G,Q]))))}function pJ($,Z,J=q){return N0($.epochNanoseconds,Z,J)}function qz($){return H0($.epochNanoseconds)}function cJ($,Z){return G0(R0(Z,$))}function dJ($,Z){return Q0(R0(Z,$))}function vz($,Z,J){return hJ($(Z.calendar),J)}function gz($,Z,J){return mJ($(Z.calendar),J)}function uJ($,Z){return X1(R0(Z,$))}function yz($,Z,J,W){let Y=((j,z,X,G)=>{let Q=m7(G);return h0(j(z),X,Q)})($,J,Z,W);return N0(a0(Y),J,Z.calendar)}function mz($,Z,J){let W=$(Z.calendar);return y$({...Z,...hJ(W,J)})}function hz($,Z,J){return mJ($(Z.calendar),J)}function pz($,Z,J,W,Y){let j=$(Y.timeZone),z=Y.plainTime,X=z!==void 0?Z(z):W1;return N0(h0(J(j),{...W,...X}),j,W.calendar)}function cz($,Z=W1){return G0(m1({...$,...Z}))}function dz($,Z,J){return hJ($(Z.calendar),J)}function uz($,Z,J){return mJ($(Z.calendar),J)}function lz($,Z,J,W){return((Y,j,z)=>Cz(Y,j,NX,y1(z),q3))($(Z.calendar),J,W)}function iz($,Z,J,W){return((Y,j,z)=>Cz(Y,j,_X,y1(z),I4))($(Z.calendar),J,W)}function sz($,Z,J,W,Y){let j=y1(Y),z=Z(j.plainDate),X=$(j.timeZone);return N0(h0(J(X),{...z,...W}),X,z.calendar)}function nz($,Z){return G0(m1({...$,...Z}))}function oz($){return H0(a0(xZ($,J1)))}function az($){return H0(a0(xZ($,H1)))}function tz($){return H0(a0(s6(i6($),o$)))}function rz($){return H0(a0(s6(i6($))))}function ez($,Z,J=W1){let W=Z.timeZone,Y=$(W),j={...R0(Z,Y),...J};return N0(u$(Y,j,j.offsetNanoseconds,2),W,Z.calendar)}function $X($,Z,J){let W=Z.timeZone,Y=$(W),j={...R0(Z,Y),...J},z=YX(Z.calendar,J.calendar);return N0(u$(Y,j,j.offsetNanoseconds,2),W,z)}function ZX($,Z=W1){return G0({...$,...Z})}function JX($,Z){return G0({...$,...Z},YX($.calendar,Z.calendar))}function K4($,Z){return{...$,calendar:Z}}function WX($,Z){return{...$,timeZone:Z}}function YX($,Z){if($===Z)return $;let J=T0($),W=T0(Z);if(J===W||J===q)return Z;if(W===q)return $;throw RangeError(oJ)}function WU($,Z){return(J)=>J===q?$:J===x4||J===CZ?Object.assign(Object.create($),{id:J}):Object.assign(Object.create(Z),LO(J))}function n$($,Z,J){let W=new Set(J);return(Y)=>(((j,z)=>{for(let X of z)if(X in j)return 1;return 0})(Y=C7(W,Y),$)||Object.assign(Y,Z),J&&(Y.timeZone=r$,["full","long"].includes(Y.timeStyle)&&(Y.timeStyle="medium")),Y)}function h1($,Z=lJ){let[J,,,W]=$;return(Y,j=gO,...z)=>{let X=Z(W&&W(...z),Y,j,J),G=X.resolvedOptions();return[X,...YU($,G,z)]}}function lJ($,Z,J,W){if(J=W(J),$){if(J.timeZone!==void 0)throw TypeError(bU);J.timeZone=$}return new L$(Z,J)}function YU($,Z,J){let[,W,Y]=$;return J.map((j)=>(j.calendar&&((z,X,G)=>{if((G||z!==q)&&z!==X)throw RangeError(oJ)})(T0(j.calendar),Z.calendar,Y),W(j,Z)))}function vZ($){let Z=R3();return F$(Z,$.getOffsetNanosecondsFor(Z))}function R3(){return xZ(Date.now(),H1)}function p1(){return NY||(NY=new L$().resolvedOptions().timeZone)}var jU=($,Z)=>`Non-integer ${$}: ${Z}`,zU=($,Z)=>`Non-positive ${$}: ${Z}`,XU=($,Z)=>`Non-finite ${$}: ${Z}`,GU=($)=>`Cannot convert bigint to ${$}`,QU=($)=>`Invalid bigint: ${$}`,BU="Cannot convert Symbol to string",jX="Invalid object",zX=($,Z,J,W,Y)=>Y?zX($,Y[Z],Y[J],Y[W]):k3($,Z)+`; must be between ${J}-${W}`,k3=($,Z)=>`Invalid ${$}: ${Z}`,iJ=($)=>`Missing ${$}`,sJ=($)=>`Invalid field ${$}`,VU=($)=>`Duplicate field ${$}`,XX=($)=>"No valid fields: "+$.join(),GX="Invalid bag",QX=($,Z,J)=>k3($,Z)+"; must be "+Object.keys(J).join(),BX="Cannot use valueOf",nJ="Invalid calling context",FU="Forbidden era/eraYear",UU="Mismatching era/eraYear",OU="Mismatching year/eraYear",DU=($)=>`Invalid era: ${$}`,LU=($)=>"Missing year"+($?"/era/eraYear":""),HU=($)=>`Invalid monthCode: ${$}`,VX="Mismatching month/monthCode",MU="Missing month/monthCode",MY="Cannot guess year",L3="Invalid leap month",FX="Invalid protocol",w3="Invalid protocol results",oJ="Mismatching Calendars",KU=($)=>`Invalid Calendar: ${$}`,UX="Mismatching TimeZones",TU="Forbidden ICU TimeZone",PU="Out-of-bounds offset",NU="Out-of-bounds TimeZone gap",_U="Invalid TimeZone offset",IU="Ambiguous offset",T4="Out-of-bounds date",xU="Out-of-bounds duration",CU="Cannot mix duration signs",P4="Missing relativeTo",AU="Cannot use large units",SU="Required smallestUnit or largestUnit",EU="smallestUnit > largestUnit",g0=($)=>`Cannot parse: ${$}`,g1=($)=>`Invalid substring: ${$}`,OX=($)=>`Cannot format ${$}`,DX="Mismatching types for formatting",bU="Cannot specify TimeZone",LX=f(I3,($,Z)=>Z),gZ=f(I3,($,Z,J)=>J),Z1=f(w6,2),P7={nanosecond:0,microsecond:1,millisecond:2,second:3,minute:4,hour:5,day:6,week:7,month:8,year:9},f3=Object.keys(P7),y0=86400000,HX=1000,o$=1000,H1=1e6,J1=1e9,N4=60000000000,_4=3600000000000,l=86400000000000,L1=[1,o$,H1,J1,N4,_4,l],c1=f3.slice(0,6),N7=x3(c1),MX=["offset"],KX=["timeZone"],TX=c1.concat(MX),PX=TX.concat(KX),_7=["era","eraYear"],RU=_7.concat(["year"]),I4=["year"],aJ=["monthCode"],tJ=["month"].concat(aJ),q3=["day"],rJ=tJ.concat(I4),NX=aJ.concat(I4),G1=q3.concat(rJ),kU=q3.concat(tJ),_X=q3.concat(aJ),IX=gZ(c1,0),q="iso8601",x4="gregory",CZ="japanese",xX={[x4]:{bce:-1,ce:0},[CZ]:{bce:-1,ce:0,meiji:1867,taisho:1911,showa:1925,heisei:1988,reiwa:2018},ethioaa:{era0:0},ethiopic:{era0:0,era1:5500},coptic:{era0:-1,era1:0},roc:{beforeroc:-1,minguo:0},buddhist:{be:0},islamic:{ah:0},indian:{saka:0},persian:{ap:0}},wU={chinese:13,dangi:13,hebrew:-6},W0=f(l6,"string"),CX=f(l6,"boolean"),fU=f(l6,"number"),AX=f(l6,"function"),h=f3.map(($)=>$+"s"),eJ=x3(h),qU=h.slice(0,6),SX=h.slice(6),vU=SX.slice(1),gU=LX(h),P0=gZ(h,0),$W=gZ(qU,0),ZW=f(AY,h),Q1=["isoNanosecond","isoMicrosecond","isoMillisecond","isoSecond","isoMinute","isoHour"],JW=["isoDay","isoMonth","isoYear"],C4=Q1.concat(JW),WW=x3(JW),EX=x3(Q1),bX=x3(C4),W1=gZ(EX,0),yU=f(AY,C4),L$=Intl.DateTimeFormat,RX="en-GB",YW=1e8,mU=YW*y0,hU=[YW,0],pU=[-YW,0],N3=275760,_3=-271821,cU=1970,AZ=1972,q1=12,dU=EZ(1868,9,8),uU=m0(uF,WeakMap),p6="smallestUnit",I7="unit",M3="roundingIncrement",L7="fractionalSecondDigits",kX="relativeTo",wX={constrain:0,reject:1},lU=Object.keys(wX),iU={compatible:0,reject:1,earlier:2,later:3},sU={reject:0,use:1,prefer:2,ignore:3},nU={auto:0,never:1,critical:2,always:3},oU={auto:0,never:1,critical:2},aU={auto:0,never:1},tU={floor:0,halfFloor:1,ceil:2,halfCeil:3,trunc:4,halfTrunc:5,expand:6,halfExpand:7,halfEven:8},v3=f(l7,p6),jW=f(l7,"largestUnit"),rU=f(l7,I7),fX=f(c$,"overflow",wX),qX=f(c$,"disambiguation",iU),eU=f(c$,"offset",sU),zW=f(c$,"calendarName",nU),$O=f(c$,"timeZoneName",oU),ZO=f(c$,"offset",aU),g3=f(c$,"roundingMode",tU),yZ="PlainYearMonth",mZ="PlainMonthDay",a$="PlainDate",t$="PlainDateTime",A4="PlainTime",d1="ZonedDateTime",S4="Instant",E4="Duration",JO=[Math.floor,($)=>A6($)?Math.floor($):Math.round($),Math.ceil,($)=>A6($)?Math.ceil($):Math.round($),Math.trunc,($)=>A6($)?Math.trunc($)||0:Math.round($),($)=>$<0?Math.floor($):Math.ceil($),($)=>Math.sign($)*Math.round(Math.abs($))||0,($)=>A6($)?($=Math.trunc($)||0)+$%2:Math.round($)],r$="UTC",R6=5184000,WO=q6(1847),YO=q6(new Date().getUTCFullYear()+10),jO=/0+$/,R0=m0(aF,WeakMap),KY=4294967295,b4=m0(($)=>{let Z=IJ($);return typeof Z=="object"?new gX(Z):new vX(Z||0)});class vX{constructor($){this.v=$}getOffsetNanosecondsFor(){return this.v}getPossibleInstantsFor($){return[v7($,this.v)]}l(){}}class gX{constructor($){this.$=((Z)=>{function J(G){let Q=H7(G,z,X),[V,F]=UY(Q),B=Y(V),U=Y(F);return B===U?B:W(j(V,F),B,U,G)}function W(G,Q,V,F){let B,U;for(;(F===void 0||(B=F<G[0]?Q:F>=G[1]?V:void 0)===void 0)&&(U=G[1]-G[0]);){let D=G[0]+Math.floor(U/2);Z(D)===V?G[1]=D:G[0]=D+1}return B}let Y=m0(Z),j=m0(tF),z=WO,X=YO;return{G(G){let Q=J(G-86400),V=J(G+86400),F=G-Q,B=G-V;if(Q===V)return[F];let U=J(F);return U===J(B)?[G-U]:Q>V?[F,B]:[]},V:J,l(G,Q){let V=H7(G,z,X),[F,B]=UY(V),U=R6*Q,D=Q<0?()=>B>z||(z=V,0):()=>F<X||(X=V,0);for(;D();){let O=Y(F),L=Y(B);if(O!==L){let H=j(F,B);W(H,O,L);let T=H[0];if((z$(T,G)||1)===Q)return T}F+=U,B+=U}}}})(((Z)=>(J)=>{let W=f7(Z,J*HX);return q6(zz(W),parseInt(W.month),parseInt(W.day),parseInt(W.hour),parseInt(W.minute),parseInt(W.second))-J})($))}getOffsetNanosecondsFor($){return this.$.V(pY($))*J1}getPossibleInstantsFor($){let[Z,J]=[q6((W=$).isoYear,W.isoMonth,W.isoDay,W.isoHour,W.isoMinute,W.isoSecond),W.isoMillisecond*H1+W.isoMicrosecond*o$+W.isoNanosecond];var W;return this.$.G(Z).map((Y)=>a0(IZ(xZ(Y,J1),J)))}l($,Z){let[J,W]=cY($),Y=this.$.l(J+(Z>0||W?1:0),Z);if(Y!==void 0)return xZ(Y,J1)}}var XW="([+\u2212-])",k6="(?:[.,](\\d{1,9}))?",yX=`(?:(?:${XW}(\\d{6}))|(\\d{4}))-?(\\d{2})`,GW="(\\d{2})(?::?(\\d{2})(?::?(\\d{2})"+k6+")?)?",QW=XW+GW,zO=yX+"-?(\\d{2})(?:[T ]"+GW+"(Z|"+QW+")?)?",mX="\\[(!?)([^\\]]*)\\]",R4=`((?:${mX}){0,9})`,XO=qZ(yX+R4),GO=qZ("(?:--)?(\\d{2})-?(\\d{2})"+R4),QO=qZ(zO+R4),BO=qZ("T?"+GW+"(?:"+QW+")?"+R4),VO=qZ(QW),FO=new RegExp(mX,"g"),UO=qZ(`${XW}?P(\\d+Y)?(\\d+M)?(\\d+W)?(\\d+D)?(?:T(?:(\\d+)${k6}H)?(?:(\\d+)${k6}M)?(?:(\\d+)${k6}S)?)?`),OO=m0(($)=>new L$(RX,{timeZone:$,era:"short",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"})),DO=/^(AC|AE|AG|AR|AS|BE|BS|CA|CN|CS|CT|EA|EC|IE|IS|JS|MI|NE|NS|PL|PN|PR|PS|SS|VS)T$/,LO=m0($U),BW=m0(($)=>new L$(RX,{calendar:$,timeZone:r$,era:"short",year:"numeric",month:"short",day:"numeric"})),HO=/^M(\d{2})(L?)$/,MO={era:f6,eraYear:A0,year:A0,month:QY,monthCode:f6,day:QY},KO=gZ(c1,A0),TO=gZ(h,yY),TY=Object.assign({},MO,KO,TO,{offset:f6}),PO=f(dF,c1,Q1),PY={dateAdd($,Z,J){let W=y(J),Y,{years:j,months:z,weeks:X,days:G}=Z;if(G+=D0(Z,5)[0],j||z)Y=((Q,V,F,B,U)=>{let[D,O,L]=Q.h(V);if(F){let[H,T]=Q.I(D,O);D+=F,O=h6(H,T,Q.U(D)),O=$1("month",O,1,Q.L(D),U)}return B&&([D,O]=Q._(D,O,B)),L=$1("day",L,1,Q.j(D,O),U),Q.q(D,O,L)})(this,$,j,z,W);else{if(!X&&!G)return $;Y=b0($)}return Y+=(7*X+G)*y0,X$(o6(Y))},dateUntil($,Z,J){if(J<=7){let G=0,Q=Yz({...$,...W1},{...Z,...W1});return J===7&&([G,Q]=Q$(Q,7)),{...P0,weeks:G,days:Q}}let W=this.h($),Y=this.h(Z),[j,z,X]=((G,Q,V,F,B,U,D)=>{let O=B-Q,L=U-V,H=D-F;if(O||L){let T=Math.sign(O||L),K=G.j(B,U),I=0;if(Math.sign(H)===-T){let b=K;[B,U]=G._(B,U,-T),O=B-Q,L=U-V,K=G.j(B,U),I=T<0?-b:K}if(H=D-Math.min(F,K)+I,O){let[b,S]=G.I(Q,V),[R,w]=G.I(B,U);if(L=R-b||Number(w)-Number(S),Math.sign(L)===-T){let N=T<0&&-G.L(B);O=(B-=T)-Q,L=U-h6(b,S,G.U(B))+(N||G.L(B))}}}return[O,L,H]})(this,...W,...Y);return J===8&&(z+=this.J(j,W[0]),j=0),{...P0,years:j,months:z,days:X}},dateFromFields($,Z){let J=y(Z),W=U7(this,$),Y=O7(this,$,W,J),j=HY(this,$,Y,W,J);return Q0(X$(this.P(W,Y,j)),this.id||q)},yearMonthFromFields($,Z){let J=y(Z),W=U7(this,$),Y=O7(this,$,W,J);return y$(q7(this.P(W,Y,1)),this.id||q)},monthDayFromFields($,Z){let J=y(Z),W=!this.id,{monthCode:Y,year:j,month:z}=$,X,G,Q,V,F;if(Y!==void 0){[X,G]=Bz(Y),F=_Y($,"day");let B=this.N(X,G,F);if(!B)throw RangeError(MY);if([Q,V]=B,z!==void 0&&z!==V)throw RangeError(VX);W&&(V=$1("month",V,1,q1,1),F=$1("day",F,1,g7(j!==void 0?j:Q,V),J))}else{Q=j===void 0&&W?AZ:U7(this,$),V=O7(this,$,Q,J),F=HY(this,$,V,Q,J);let B=this.U(Q);G=V===B,X=K7(V,B);let U=this.N(X,G,F);if(!U)throw RangeError(MY);[Q,V]=U}return v6(X$(this.P(Q,V,F)),this.id||q)},fields($){return T7(this)&&$.includes("year")?[...$,..._7]:$},mergeFields($,Z){let J=Object.assign(Object.create(null),$);return D7(J,Z,tJ),T7(this)&&(D7(J,Z,RU),this.id===CZ&&D7(J,Z,kU,_7)),J},inLeapYear($){let[Z]=this.h($);return this.K(Z)},monthsInYear($){let[Z]=this.h($);return this.L(Z)},daysInMonth($){let[Z,J]=this.h($);return this.j(Z,J)},daysInYear($){let[Z]=this.h($);return this.X(Z)},dayOfYear:qJ,era($){return this.ee($)[0]},eraYear($){return this.ee($)[1]},monthCode($){let[Z,J]=this.h($),[W,Y]=this.I(Z,J);return((j,z)=>"M"+Z1(j)+(z?"L":""))(W,Y)},dayOfWeek:sY,daysInWeek(){return 7}},NO={dayOfYear:qJ,h:uY,q:EZ},_O=Object.assign({},NO,{weekOfYear:Gz,yearOfWeek:Qz,R($){function Z(U){return(7-U<W?7:0)-U}function J(U){let D=iY(B+U),O=U||1,L=Z(H3(G+D*O,7));return V=(D+(L-Q)*O)/7}let W=this.id?1:4,Y=sY($),j=this.dayOfYear($),z=H3(Y-1,7),X=j-1,G=H3(z-X,7),Q=Z(G),V,F=Math.floor((X-Q)/7)+1,B=$.isoYear;return F?F>J(0)&&(F=1,B++):(F=J(-1),B--),[F,B,V]}}),IO={dayOfYear:qJ,h:M7,q:P3,weekOfYear:Gz,yearOfWeek:Qz,R(){return[]}},hZ=WU(Object.assign({},PY,_O,{h:uY,ee($){return this.id===x4?nY($):this.id===CZ?uU($):[]},I:($,Z)=>[Z,0],N($,Z){if(!Z)return[AZ,$]},K:y7,U(){},L:lY,J:($)=>$*q1,j:g7,X:iY,P:($,Z,J)=>({isoYear:$,isoMonth:Z,isoDay:J}),q:EZ,_:($,Z,J)=>($+=d6(J,q1),(Z+=S7(J,q1))<1?($--,Z+=q1):Z>q1&&($++,Z-=q1),[$,Z]),year($){return $.isoYear},month($){return $.isoMonth},day:($)=>$.isoDay}),Object.assign({},PY,IO,{h:M7,ee($){let Z=this.O($);return[Z.era,Z.eraYear]},I($,Z){let J=S6.call(this,$);return[K7(Z,J),J===Z]},N($,Z,J){let[W,Y,j]=M7.call(this,{isoYear:AZ,isoMonth:q1,isoDay:31}),z=S6.call(this,W),X=Y===z;(z$($,K7(Y,z))||z$(Number(Z),Number(X))||z$(J,j))===1&&W--;for(let G=0;G<100;G++){let Q=W-G,V=S6.call(this,Q),F=h6($,Z,V);if(Z===(F===V)&&J<=DY.call(this,Q,F))return[Q,F]}},K($){let Z=E6.call(this,$);return Z>E6.call(this,$-1)&&Z>E6.call(this,$+1)},U:S6,L:b6,J($,Z){let J=Z+$,W=Math.sign($),Y=W<0?-1:0,j=0;for(let z=Z;z!==J;z+=W)j+=b6.call(this,z+Y);return j},j:DY,X:E6,P($,Z,J){return o6(P3.call(this,$,Z,J))},q:P3,_($,Z,J){if(J){if(Z+=J,!Number.isSafeInteger(Z))throw RangeError(T4);if(J<0)for(;Z<1;)Z+=b6.call(this,--$);else{let W;for(;Z>(W=b6.call(this,$));)Z-=W,$++}}return[$,Z]},year($){return this.O($).year},month($){let{year:Z,F:J}=this.O($),{C:W}=this.B(Z);return W[J]+1},day($){return this.O($).day}})),G$="numeric",pZ=["timeZoneName"],hX={month:G$,day:G$},VW={year:G$,month:G$},FW=Object.assign({},VW,{day:G$}),UW={hour:G$,minute:G$,second:G$},OW=Object.assign({},FW,UW),xO=Object.assign({},OW,{timeZoneName:"short"}),CO=Object.keys(VW),AO=Object.keys(hX),SO=Object.keys(FW),EO=Object.keys(UW),DW=["dateStyle"],bO=CO.concat(DW),RO=AO.concat(DW),LW=SO.concat(DW,["weekday"]),y3=EO.concat(["dayPeriod","timeStyle"]),HW=LW.concat(y3),kO=HW.concat(pZ),wO=pZ.concat(y3),fO=pZ.concat(LW),qO=pZ.concat(["day","weekday"],y3),vO=pZ.concat(["year","weekday"],y3),gO={},MW=[n$(HW,OW),$4],pX=[n$(kO,xO),$4,0,($,Z)=>{let J=T0($.timeZone);if(Z&&T0(Z.timeZone)!==J)throw RangeError(UX);return J}],KW=[n$(HW,OW,pZ),b0],TW=[n$(LW,FW,wO),b0],PW=[n$(y3,UW,fO),($)=>B$($)/H1],NW=[n$(bO,VW,qO),b0,1],_W=[n$(RO,hX,vO),b0,1],NY;function T1($,Z,J,W,Y){function j(...G){if(!(this instanceof j))throw TypeError(nJ);lX(this,Z(...G))}function z(G,Q){return Object.defineProperties(function(...V){return G.call(this,X(this),...V)},x7(Q))}function X(G){let Q=x0(G);if(!Q||Q.branding!==$)throw TypeError(nJ);return Q}return Object.defineProperties(j.prototype,{...IY(Y1(z,J)),...h$(Y1(z,W)),...c6("Temporal."+$)}),Object.defineProperties(j,{...h$(Y),...x7($)}),[j,(G)=>{let Q=Object.create(j.prototype);return lX(Q,G),Q},X]}function nX($){return $=$.concat("id").sort(),(Z)=>{if(!xY(Z,$))throw TypeError(FX);return Z}}function lZ($){if(x0($)||$.calendar!==void 0||$.timeZone!==void 0)throw TypeError(GX);return $}function k4($,Z){let J={};for(let W in $)J[W]=({o:Y},j)=>{let z=x0(j)||{},{branding:X}=z,G=X===a$||Z.includes(X)?z:f0(j);return Y[W](G)};return J}function CW($){let Z={};for(let J in $)Z[J]=(W)=>{let{calendar:Y}=W;return(j=Y,typeof j=="string"?hZ(j):(z=j,Object.assign(Object.create(eO),{i:z})))[J](W);var j,z};return Z}function P$(){throw TypeError(BX)}function h3({calendar:$}){return typeof $=="string"?new qW($):$}function cX($,Z){if(Z=X0(Z),L0($)){let W=x0($);if(W&&W.branding===mZ)return y(Z),W;let Y=tX($);return yJ(m4(Y||q),!Y,$,Z)}let J=fj(hZ,$);return y(Z),J}function oX($,Z,J){return W=Z.call($,w0(H0(J))),jJ(C3(W));var W}function w4($,Z=ZG){let J=Object.keys(Z).sort(),W={};for(let Y of J)W[Y]=f(Z[Y],$,AX($[Y]));return W}function n($,Z){return typeof $=="string"?b4($):w4($,Z)}function V0($){return n($,xW)}function M1($){if(L0($)){let Z=x0($);if(Z)switch(Z.branding){case S4:return Z;case d1:return H0(Z.epochNanoseconds)}}return Ej($)}function dX($,Z,J){let W=Z.l(M1(J).epochNanoseconds,$);return W?w0(H0(W)):null}function a($){return L0($)?(x0($)||{}).timeZone||jD($):((Z)=>U4(yj(W0(Z))))($)}function H$($,Z){if(L0($)){let J=x0($)||{};switch(J.branding){case A4:return y(Z),J;case t$:return y(Z),X1(J);case d1:return y(Z),uJ(V0,J)}return Hz($,Z)}return y(Z),qj($)}function AW($){return $===void 0?void 0:H$($)}function cZ($,Z){if(Z=X0(Z),L0($)){let W=x0($);return W&&W.branding===yZ?(y(Z),W):gJ(g4(p3($)),$,Z)}let J=wj(hZ,$);return y(Z),J}function M$($,Z){if(Z=X0(Z),L0($)){let W=x0($)||{};switch(W.branding){case t$:return y(Z),W;case a$:return y(Z),G0({...W,...W1});case d1:return y(Z),cJ(V0,W)}return Lz(y4(p3($)),$,Z)}let J=kj($);return y(Z),J}function f0($,Z){if(Z=X0(Z),L0($)){let W=x0($)||{};switch(W.branding){case a$:return y(Z),W;case t$:return y(Z),Q0(W);case d1:return y(Z),dJ(V0,W)}return vJ(y4(p3($)),$,Z)}let J=V4($);return y(Z),J}function aX($,Z,J){return j1(Z.call($,j0(Q0(J,$))))}function P1($){return(Z)=>typeof Z=="string"?hZ(Z):((J,W)=>{let Y=Object.keys(W).sort(),j={};for(let z of Y)j[z]=f(W[z],J,J[z]);return j})(Z,$)}function Y0($){if(L0($)){let Z=x0($);return Z&&Z.branding===E4?Z:Mz($)}return vj($)}function m3($){if($!==void 0){if(L0($)){let Z=x0($)||{};switch(Z.branding){case d1:case a$:return Z;case t$:return Q0(Z)}let J=p3($);return{...Oz(a,n,y4(J),$),calendar:J}}return bj($)}}function p3($){return tX($)||q}function tX($){let{calendar:Z}=$;if(Z!==void 0)return I0(Z)}function I0($){return L0($)?(x0($)||{}).calendar||TD($):((Z)=>E3(gj(W0(Z))))($)}function dZ($,Z){if(Z=X0(Z),L0($)){let J=x0($);if(J&&J.branding===d1)return A3(Z),J;let W=p3($);return Dz(a,n,y4(W),W,$,Z)}return Rj($,Z)}function uX($){return Y1((Z)=>(J)=>Z(IW(J)),$)}function IW($){return R0($,V0)}function yO(){let $=L$.prototype,Z=Object.getOwnPropertyDescriptors($),J=Object.getOwnPropertyDescriptors(L$),W=function(Y,j={}){if(!(this instanceof W))return new W(Y,j);vW.set(this,((z,X={})=>{let G=new L$(z,X),Q=G.resolvedOptions(),V=Q.locale,F=p0(Object.keys(X),Q),B=m0(pO),U=(...D)=>{let O,L=D.map((H,T)=>{let K=x0(H),I=(K||{}).branding;if(T&&O&&O!==I)throw TypeError(DX);return O=I,K});return O?B(O)(V,F,...L):[G,...D]};return U.u=G,U})(Y,j))};for(let Y in Z){let j=Z[Y],z=Y.startsWith("format")&&mO(Y);typeof j.value=="function"?j.value=Y==="constructor"?W:z||hO(Y):z&&(j.get=function(){return z.bind(this)})}return J.prototype.value=Object.create($,Z),Object.defineProperties(W,J),W}function mO($){return function(...Z){let J=vW.get(this),[W,...Y]=J(...Z);return W[$](...Y)}}function hO($){return function(...Z){return vW.get(this).u[$](...Z)}}function pO($){let Z=cO[$];if(!Z)throw TypeError(OX($));return h1(Z,m0(lJ))}var cO={Instant:MW,PlainDateTime:KW,PlainDate:TW,PlainTime:PW,PlainYearMonth:NW,PlainMonthDay:_W},dO=h1(MW),uO=h1(pX),lO=h1(KW),iO=h1(TW),sO=h1(PW),nO=h1(NW),oO=h1(_W),SW={era:kY,eraYear:E7,year:C3,month:j1,daysInMonth:j1,daysInYear:j1,inLeapYear:CX,monthsInYear:j1},q4={monthCode:W0},EW={day:j1},rX={dayOfWeek:j1,dayOfYear:j1,weekOfYear:wY,yearOfWeek:E7,daysInWeek:j1},eX=Object.assign({},SW,q4,EW,rX),f4=new WeakMap,x0=f4.get.bind(f4),lX=f4.set.bind(f4),aO={...k4(SW,[yZ]),...k4(rX,[]),...k4(q4,[yZ,mZ]),...k4(EW,[mZ])},bW=CW(eX),tO=CW({...SW,...q4}),rO=CW({...q4,...EW}),c3={calendarId:($)=>T0($.calendar)},eO=Y1(($,Z)=>function(J){let{i:W}=this;return $(W[Z](j0(Q0(J,W))))},eX),$D=I3(($)=>(Z)=>Z[$],h.concat("sign")),RW=I3(($,Z)=>(J)=>J[Q1[Z]],c1),$G={epochSeconds:Zj,epochMilliseconds:$4,epochMicroseconds:Jj,epochNanoseconds:Wj},d3=f(C7,new Set(["branding"])),[ZD,uZ,JD]=T1(mZ,f(kz,I0),{...c3,...rO},{getISOFields:d3,getCalendar:h3,with($,Z,J){return uZ(_z(HD,$,this,lZ(Z),J))},equals:($,Z)=>rj($,cX(Z)),toPlainDate($,Z){return j0(iz(u3,$,this,Z))},toLocaleString($,Z,J){let[W,Y]=oO(Z,J,$);return W.format(Y)},toString:$J,toJSON:($)=>$J($),valueOf:P$},{from:($,Z)=>uZ(cX($,Z))}),ZG={getOffsetNanosecondsFor:oX,getPossibleInstantsFor($,Z,J){let W=[...Z.call($,_0(G0(J,q)))].map((j)=>YD(j).epochNanoseconds),Y=W.length;return Y>1&&(W.sort(E0),zJ(o0(n0(W[0],W[Y-1])))),W}},xW={getOffsetNanosecondsFor:oX},[WD,w0,YD]=T1(S4,Az,$G,{add:($,Z)=>w0(XJ(0,$,Y0(Z))),subtract:($,Z)=>w0(XJ(1,$,Y0(Z))),until:($,Z,J)=>o(SJ(0,$,M1(Z),J)),since:($,Z,J)=>o(SJ(1,$,M1(Z),J)),round:($,Z)=>w0(zj($,Z)),equals:($,Z)=>sj($,M1(Z)),toZonedDateTime($,Z){let J=y1(Z);return B0(pJ($,a(J.timeZone),I0(J.calendar)))},toZonedDateTimeISO:($,Z)=>B0(pJ($,a(Z))),toLocaleString($,Z,J){let[W,Y]=dO(Z,J,$);return W.format(Y)},toString:($,Z)=>o7(a,V0,$,Z),toJSON:($)=>o7(a,V0,$),valueOf:P$},{from:($)=>w0(M1($)),fromEpochSeconds:($)=>w0(oz($)),fromEpochMilliseconds:($)=>w0(az($)),fromEpochMicroseconds:($)=>w0(tz($)),fromEpochNanoseconds:($)=>w0(rz($)),compare:($,Z)=>xJ(M1($),M1(Z))}),[v4,tP]=T1("TimeZone",($)=>{let Z=lj($);return{branding:"TimeZone",id:Z,o:b4(Z)}},{id:($)=>$.id},{getPossibleInstantsFor:({o:$},Z)=>$.getPossibleInstantsFor(M$(Z)).map((J)=>w0(H0(J))),getOffsetNanosecondsFor:({o:$},Z)=>$.getOffsetNanosecondsFor(M1(Z).epochNanoseconds),getOffsetStringFor($,Z){let J=M1(Z).epochNanoseconds,W=w4(this,xW).getOffsetNanosecondsFor(J);return d$(W)},getPlainDateTimeFor($,Z,J=q){let W=M1(Z).epochNanoseconds,Y=w4(this,xW).getOffsetNanosecondsFor(W);return _0(G0(F$(W,Y),I0(J)))},getInstantFor($,Z,J){let W=M$(Z),Y=m7(J),j=w4(this);return w0(H0(h0(j,W,Y)))},getNextTransition:({o:$},Z)=>dX(1,$,Z),getPreviousTransition:({o:$},Z)=>dX(-1,$,Z),equals($,Z){return!!D4(this,a(Z))},toString:($)=>$.id,toJSON:($)=>$.id},{from($){let Z=a($);return typeof Z=="string"?new v4(Z):Z}}),jD=nX(Object.keys(ZG)),[zD,K$]=T1(A4,wz,RW,{getISOFields:d3,with($,Z,J){return K$(Iz(this,lZ(Z),J))},add:($,Z)=>K$(FJ(0,$,Y0(Z))),subtract:($,Z)=>K$(FJ(1,$,Y0(Z))),until:($,Z,J)=>o(wJ(0,$,H$(Z),J)),since:($,Z,J)=>o(wJ(1,$,H$(Z),J)),round:($,Z)=>K$(Qj($,Z)),equals:($,Z)=>ej($,H$(Z)),toZonedDateTime:($,Z)=>B0(sz(a,f0,n,$,Z)),toPlainDateTime:($,Z)=>_0(nz($,f0(Z))),toLocaleString($,Z,J){let[W,Y]=sO(Z,J,$);return W.format(Y)},toString:ZJ,toJSON:($)=>ZJ($),valueOf:P$},{from:($,Z)=>K$(H$($,Z)),compare:($,Z)=>O4(H$($),H$(Z))}),[XD,T$,GD]=T1(yZ,f(Rz,I0),{...c3,...tO},{getISOFields:d3,getCalendar:h3,with($,Z,J){return T$(Nz(LD,$,this,lZ(Z),J))},add:($,Z,J)=>T$(VJ(iX,0,$,Y0(Z),J)),subtract:($,Z,J)=>T$(VJ(iX,1,$,Y0(Z),J)),until:($,Z,J)=>o(kJ(sX,0,$,cZ(Z),J)),since:($,Z,J)=>o(kJ(sX,1,$,cZ(Z),J)),equals:($,Z)=>tj($,cZ(Z)),toPlainDate($,Z){return j0(lz(u3,$,this,Z))},toLocaleString($,Z,J){let[W,Y]=nO(Z,J,$);return W.format(Y)},toString:e7,toJSON:($)=>e7($),valueOf:P$},{from:($,Z)=>T$(cZ($,Z)),compare:($,Z)=>i$(cZ($),cZ(Z))}),[QD,_0]=T1(t$,f(Ez,I0),{...c3,...bW,...RW},{getISOFields:d3,getCalendar:h3,with($,Z,J){return _0(Tz(u3,$,this,lZ(Z),J))},withCalendar:($,Z)=>_0(K4($,I0(Z))),withPlainDate:($,Z)=>_0(JX($,f0(Z))),withPlainTime:($,Z)=>_0(ZX($,AW(Z))),add:($,Z,J)=>_0(QJ(e$,0,$,Y0(Z),J)),subtract:($,Z,J)=>_0(QJ(e$,1,$,Y0(Z),J)),until:($,Z,J)=>o(bJ(K1,0,$,M$(Z),J)),since:($,Z,J)=>o(bJ(K1,1,$,M$(Z),J)),round:($,Z)=>_0(Gj($,Z)),equals:($,Z)=>oj($,M$(Z)),toZonedDateTime:($,Z,J)=>B0(yz(n,$,a(Z),J)),toPlainDate:($)=>j0(Q0($)),toPlainTime:($)=>K$(X1($)),toPlainYearMonth($){return T$(mz(g4,$,this))},toPlainMonthDay($){return uZ(hz(m4,$,this))},toLocaleString($,Z,J){let[W,Y]=lO(Z,J,$);return W.format(Y)},toString:t7,toJSON:($)=>t7($),valueOf:P$},{from:($,Z)=>_0(M$($,Z)),compare:($,Z)=>AJ(M$($),M$(Z))}),[BD,j0,JG]=T1(a$,f(bz,I0),{...c3,...bW},{getISOFields:d3,getCalendar:h3,with($,Z,J){return j0(Pz(u3,$,this,lZ(Z),J))},withCalendar:($,Z)=>j0(K4($,I0(Z))),add:($,Z,J)=>j0(BJ(e$,0,$,Y0(Z),J)),subtract:($,Z,J)=>j0(BJ(e$,1,$,Y0(Z),J)),until:($,Z,J)=>o(RJ(K1,0,$,f0(Z),J)),since:($,Z,J)=>o(RJ(K1,1,$,f0(Z),J)),equals:($,Z)=>aj($,f0(Z)),toZonedDateTime($,Z){let J=!L0(Z)||Z instanceof v4?{timeZone:Z}:Z;return B0(pz(a,H$,n,$,J))},toPlainDateTime:($,Z)=>_0(cz($,AW(Z))),toPlainYearMonth($){return T$(dz(g4,$,this))},toPlainMonthDay($){return uZ(uz(m4,$,this))},toLocaleString($,Z,J){let[W,Y]=iO(Z,J,$);return W.format(Y)},toString:r7,toJSON:($)=>r7($),valueOf:P$},{from:($,Z)=>j0(f0($,Z)),compare:($,Z)=>i$(f0($),f0(Z))}),kW={fields($,Z,J){return[...Z.call($,J)]}},WG=Object.assign({dateFromFields($,Z,J,W){return JG(Z.call($,Object.assign(Object.create(null),J),W))}},kW),YG=Object.assign({yearMonthFromFields($,Z,J,W){return GD(Z.call($,Object.assign(Object.create(null),J),W))}},kW),jG=Object.assign({monthDayFromFields($,Z,J,W){return JD(Z.call($,Object.assign(Object.create(null),J),W))}},kW),wW={mergeFields($,Z,J,W){return y1(Z.call($,Object.assign(Object.create(null),J),Object.assign(Object.create(null),W)))}},VD=Object.assign({},WG,wW),FD=Object.assign({},YG,wW),UD=Object.assign({},jG,wW),fW={dateAdd($,Z,J,W,Y){return JG(Z.call($,j0(Q0(J,$)),o($0(W)),Y))}},zG=Object.assign({},fW,{dateUntil($,Z,J,W,Y,j){return KD(Z.call($,j0(Q0(J,$)),j0(Q0(W,$)),Object.assign(Object.create(null),j,{largestUnit:f3[Y]})))}}),OD=Object.assign({},fW,{day:aX}),DD=Object.assign({},zG,{day:aX}),g4=P1(YG),y4=P1(WG),m4=P1(jG),LD=P1(FD),u3=P1(VD),HD=P1(UD),e$=P1(fW),K1=P1(zG),iX=P1(OD),sX=P1(DD),[MD,o,KD]=T1(E4,fz,{...$D,blank:Cj},{with:($,Z)=>o(xz($,Z)),negated:($)=>o(Q4($)),abs:($)=>o(xj($)),add:($,Z,J)=>o(HJ(m3,K1,n,0,$,Y0(Z),J)),subtract:($,Z,J)=>o(HJ(m3,K1,n,1,$,Y0(Z),J)),round:($,Z)=>o(Ij(m3,K1,n,$,Z)),total:($,Z)=>jj(m3,K1,n,$,Z),toLocaleString($,Z,J){return Intl.DurationFormat?new Intl.DurationFormat(Z,J).format(this):Y4($)},toString:Y4,toJSON:($)=>Y4($),valueOf:P$},{from:($)=>o(Y0($)),compare:($,Z,J)=>ij(m3,e$,n,Y0($),Y0(Z),J)}),XG={toString:($)=>$.id,toJSON:($)=>$.id,...aO,dateAdd:({id:$,o:Z},J,W,Y)=>j0(Q0(Z.dateAdd(f0(J),Y0(W),Y),$)),dateUntil:({o:$},Z,J,W)=>o($0($.dateUntil(f0(Z),f0(J),aY(W)))),dateFromFields:({id:$,o:Z},J,W)=>j0(vJ(Z,J,W,RY($))),yearMonthFromFields:({id:$,o:Z},J,W)=>T$(gJ(Z,J,W,EY($))),monthDayFromFields:({id:$,o:Z},J,W)=>uZ(yJ(Z,0,J,W,bY($))),fields({o:$},Z){let J=new Set(G1),W=[];for(let Y of Z){if(W0(Y),!J.has(Y))throw RangeError(sJ(Y));J.delete(Y),W.push(Y)}return $.fields(W)},mergeFields:({o:$},Z,J)=>$.mergeFields(A7(b7(Z)),A7(b7(J)))},[qW]=T1("Calendar",($)=>{let Z=Xz($);return{branding:"Calendar",id:Z,o:hZ(Z)}},{id:($)=>$.id},XG,{from($){let Z=I0($);return typeof Z=="string"?new qW(Z):Z}}),TD=nX(Object.keys(XG).slice(4)),[PD,B0]=T1(d1,f(Sz,I0,a),{...$G,...c3,...uX(bW),...uX(RW),offset:($)=>d$(IW($).offsetNanoseconds),offsetNanoseconds:($)=>IW($).offsetNanoseconds,timeZoneId:($)=>T0($.timeZone),hoursInDay:($)=>Bj(n,$)},{getISOFields:($)=>Nj(V0,$),getCalendar:h3,getTimeZone:({timeZone:$})=>typeof $=="string"?new v4($):$,with($,Z,J){return B0(Kz(u3,n,$,this,lZ(Z),J))},withCalendar:($,Z)=>B0(K4($,I0(Z))),withTimeZone:($,Z)=>B0(WX($,a(Z))),withPlainDate:($,Z)=>B0($X(n,$,f0(Z))),withPlainTime:($,Z)=>B0(ez(n,$,AW(Z))),add:($,Z,J)=>B0(GJ(e$,n,0,$,Y0(Z),J)),subtract:($,Z,J)=>B0(GJ(e$,n,1,$,Y0(Z),J)),until:($,Z,J)=>o($0(EJ(K1,n,0,$,dZ(Z),J))),since:($,Z,J)=>o($0(EJ(K1,n,1,$,dZ(Z),J))),round:($,Z)=>B0(Xj(n,$,Z)),startOfDay:($)=>B0(Vj(n,$)),equals:($,Z)=>nj($,dZ(Z)),toInstant:($)=>w0(qz($)),toPlainDateTime:($)=>_0(cJ(V0,$)),toPlainDate:($)=>j0(dJ(V0,$)),toPlainTime:($)=>K$(uJ(V0,$)),toPlainYearMonth($){return T$(vz(g4,$,this))},toPlainMonthDay($){return uZ(gz(m4,$,this))},toLocaleString($,Z,J={}){let[W,Y]=uO(Z,J,$);return W.format(Y)},toString:($,Z)=>a7(V0,$,Z),toJSON:($)=>a7(V0,$),valueOf:P$},{from:($,Z)=>B0(dZ($,Z)),compare:($,Z)=>CJ(dZ($),dZ(Z))}),ND=Object.defineProperties({},{...c6("Temporal.Now"),...h$({timeZoneId:()=>p1(),instant:()=>w0(H0(R3())),zonedDateTime:($,Z=p1())=>B0(N0(R3(),a(Z),I0($))),zonedDateTimeISO:($=p1())=>B0(N0(R3(),a($),q)),plainDateTime:($,Z=p1())=>_0(G0(vZ(V0(a(Z))),I0($))),plainDateTimeISO:($=p1())=>_0(G0(vZ(V0(a($))),q)),plainDate:($,Z=p1())=>j0(Q0(vZ(V0(a(Z))),I0($))),plainDateISO:($=p1())=>j0(Q0(vZ(V0(a($))),q)),plainTimeISO:($=p1())=>K$(X1(vZ(V0(a($)))))})}),iZ=Object.defineProperties({},{...c6("Temporal"),...h$({PlainYearMonth:XD,PlainMonthDay:ZD,PlainDate:BD,PlainTime:zD,PlainDateTime:QD,ZonedDateTime:PD,Instant:WD,Calendar:qW,TimeZone:v4,Duration:MD,Now:ND})}),_D=yO(),vW=new WeakMap,ID=Object.defineProperties(Object.create(Intl),h$({DateTimeFormat:_D}));var h4="x-gemi-socket";var WN="gemi.v1",GG="/__gemi/socket",YN=/^[A-Za-z0-9_-]{1,32}$/,jN={Normal:1000,UnsupportedData:1003,PolicyViolation:1008,Restart:1012,TryAgainLater:1013,Revoked:4001};function QN($){return $}function QG(){return{driver:"memory",redis:{},maxEventBytes:16384,warnEventBytes:4096,path:GG,allowedOrigins:[],maxConnectionsPerProcess:1e4,maxConnectionsPerIp:100,maxConnectionsPerUser:50,maxChannelsPerSocket:50,maxInboundMessageBytes:16384,backpressureLimit:1048576,idleTimeout:120,heartbeatMs:25000,subscribeRate:{limit:300,windowMs:60000}}}import{hkdfSync as xD,randomBytes as CD}from"crypto";function AD($=process.env.SECRET){if(!$)return"gemi:bc:";return`gemi:bc:${Buffer.from(xD("sha256",$,"gemi","gemi.broadcast.prefix",4)).toString("hex")}:`}var SD="__control",gW=250,ED=1e4,bD=15000;class yW{config;prefix;controlChannel;instanceId=CD(9).toString("base64url");subscribeTimeoutMs;healthCheckMs;publisher=null;subscriber=null;ready=null;deliver=null;hooks;wanted=new Set;active=new Set;chains=new Map;connectedOnce=!1;reconnectAttempt=0;reconnectTimer=null;healthTimer=null;closed=!1;constructor($={}){this.config=$;this.prefix=$.prefix??AD(),this.controlChannel=this.prefix+SD,this.subscribeTimeoutMs=$.subscribeTimeoutMs??5000,this.healthCheckMs=$.healthCheckMs??30000}get connected(){return this.subscriber!==null&&this.ready===null}publish($,Z){return this.send(this.prefix+$,Z)}async revoke($){this.hooks?.onRevoke?.($);let Z={op:"revoke",from:this.instanceId,r:$};try{await this.send(this.controlChannel,JSON.stringify(Z))}catch(J){throw Error(`The broadcast revocation ${JSON.stringify($)} could not reach the other instances.`,{cause:J})}}async start($,Z){this.closed=!1,this.deliver=$,this.hooks=Z,this.connectSubscriber(),this.startHealthCheck();try{await this.whenReady()}catch{console.warn("[gemi] Broadcast: Redis is not reachable yet; sockets get events once it is.")}}topicAdded($){return this.wanted.add($),this.sync($,!0)}topicRemoved($){return this.wanted.delete($),this.sync($,!1)}async close(){if(this.closed=!0,this.deliver=null,this.hooks=void 0,this.reconnectTimer)clearTimeout(this.reconnectTimer);if(this.reconnectTimer=null,this.healthTimer)clearInterval(this.healthTimer);this.healthTimer=null;let $=[this.subscriber,this.publisher];this.subscriber=null,this.publisher=null,this.ready=null,this.wanted.clear(),this.active.clear(),this.chains.clear();for(let Z of $){if(!Z)continue;Z.onclose=null;try{Z.close()}catch{}}}async send($,Z){let J=this.publisherClient();try{await J.publish($,Z)}catch{if(this.closed)throw Error("The broadcast driver is closed.");this.dropPublisher(J),await this.publisherClient().publish($,Z)}}dropPublisher($){if(this.publisher!==$)return;this.publisher=null,$.onclose=null;try{$.close()}catch{}}publisherClient(){if(this.publisher)return this.publisher;let $=this.createClient("publisher");return $.onclose=()=>{if(this.publisher===$)this.publisher=null},this.publisher=$,$}createClient($){if(this.config.createClient)return this.config.createClient($);let Z=globalThis.Bun?.RedisClient;if(typeof Z!=="function")throw Error("The redis broadcast driver needs Bun's built-in Redis client. Run the app under Bun.");let J=$==="subscriber"?{...this.config.options,autoReconnect:!1}:{...this.config.options};return new Z(this.config.url,J)}connectSubscriber(){if(this.closed||this.ready)return;let $;try{$=this.createClient("subscriber")}catch(J){console.error("[gemi] Broadcast: the Redis subscriber could not be created.",J),this.scheduleReconnect();return}this.subscriber=$,this.active.clear(),$.onclose=()=>this.lost($);let Z=l3((async()=>{await $.connect(),await $.subscribe(this.controlChannel,this.onMessage);let J=[...this.wanted];if(await Promise.all(J.map((W)=>$.subscribe(this.prefix+W,this.onMessage))),this.subscriber!==$)throw Error("Replaced.");for(let W of J)this.active.add(W);return $})(),bD,"connect");this.ready=Z,Z.then(()=>{if(this.subscriber!==$)return;this.ready=null,this.reconnectAttempt=0;for(let J of this.active)if(!this.wanted.has(J))this.sync(J,!1).catch(()=>{});if(this.connectedOnce)this.hooks?.onGap?.();this.connectedOnce=!0},(J)=>{if(this.subscriber!==$||this.closed)return;console.warn(`[gemi] Broadcast: the Redis subscriber could not connect (${BG(J)}); retrying.`),this.drop($)})}lost($){if(this.subscriber!==$||this.closed)return;if(this.ready===null)console.warn("[gemi] Broadcast: the Redis subscriber connection dropped; reconnecting.");this.drop($)}drop($){if(this.subscriber!==$)return;this.subscriber=null,this.ready=null,this.active.clear(),$.onclose=null;try{$.close()}catch{}this.scheduleReconnect()}scheduleReconnect(){if(this.closed||this.reconnectTimer)return;let $=Math.min(ED,gW*2**this.reconnectAttempt);this.reconnectAttempt=Math.min(this.reconnectAttempt+1,16);let Z=Math.max(gW,Math.floor(Math.random()*$));this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connectSubscriber()},Z),this.reconnectTimer.unref?.()}startHealthCheck(){if(this.healthCheckMs<=0||this.healthTimer)return;this.healthTimer=setInterval(()=>{let $=this.subscriber;if(!$||this.ready)return;l3($.ping(),this.subscribeTimeoutMs,"ping").catch((Z)=>{if(this.subscriber!==$)return;console.warn(`[gemi] Broadcast: the Redis subscriber did not answer a ping (${BG(Z)}); reconnecting.`),this.drop($)})},this.healthCheckMs),this.healthTimer.unref?.()}async whenReady(){if(this.closed)throw Error("The broadcast driver is closed.");let $=Date.now()+this.subscribeTimeoutMs;for(;;){if(this.subscriber&&!this.ready)return this.subscriber;let Z=$-Date.now();if(Z<=0)throw Error("Redis did not answer in time.");let J=this.ready??RD(Math.min(Z,gW));await l3(J,Z,"subscribe").catch((W)=>{if(Date.now()>=$)throw W})}}sync($,Z){let W=(this.chains.get($)??Promise.resolve()).catch(()=>{}).then(()=>this.reconcile($,Z));this.chains.set($,W);let Y=()=>{if(this.chains.get($)===W)this.chains.delete($)};return W.then(Y,Y),W}async reconcile($,Z){if(!this.wanted.has($)){if(!this.active.has($)||!this.connected)return;let Y=this.subscriber;this.active.delete($);try{await l3(Y.unsubscribe(this.prefix+$),this.subscribeTimeoutMs,"unsubscribe")}catch(j){if(this.subscriber===Y)this.drop(Y);throw j}return}if(!Z)return;let W=await this.whenReady();if(!this.wanted.has($)||this.active.has($))return;try{await l3(W.subscribe(this.prefix+$,this.onMessage),this.subscribeTimeoutMs,"subscribe")}catch(Y){if(this.subscriber===W)this.drop(W);throw Y}if(this.subscriber===W)this.active.add($)}onMessage=($,Z)=>{if(Z===this.controlChannel){this.onControl($);return}if(!Z.startsWith(this.prefix))return;this.deliver?.(Z.slice(this.prefix.length),$)};onControl($){let Z;try{Z=JSON.parse($)}catch{return}if(Z?.op!=="revoke"||Z.from===this.instanceId)return;let J=Z.r;if(J&&typeof J.user==="string")this.hooks?.onRevoke?.({user:J.user});else if(J&&typeof J.topic==="string")this.hooks?.onRevoke?.({topic:J.topic})}}function l3($,Z,J){let W;return Promise.race([$,new Promise((Y,j)=>{W=setTimeout(()=>j(Error(`Redis ${J} timed out after ${Z} ms.`)),Z)})]).finally(()=>clearTimeout(W))}function RD($){return new Promise((Z)=>setTimeout(Z,$))}function BG($){return $ instanceof Error?$.message:String($)}import{createHmac as kD,hkdfSync as wD,randomBytes as VG}from"crypto";function FG($){return kD("sha256",fD()).update($).digest("base64url").slice(0,22)}var p4=null;function fD(){let $=process.env.SECRET||void 0;if(p4&&p4.secret===$)return p4.key;let Z=$?Buffer.from(wD("sha256",$,"gemi","gemi.broadcast.socket-tag",32)):VG(32);return p4={secret:$,key:Z},Z}function ON(){return VG(16).toString("base64url")}var qD=/^[A-Za-z0-9_-]{8,64}$/;function mW($){return typeof $==="string"&&qD.test($)}function UG($,Z,J,W){let Y={op:"ev",t:$,ev:Z};if(J!==void 0)Y.d=J;if(W)Y.x=W;return JSON.stringify(Y)}class DG extends Error{bytes;limit;constructor($,Z,J){super(`The broadcast "${J}" is ${$} bytes, over the limit of ${Z}. Send ids and a change hint, and let the client fetch the data over HTTP; or raise maxEventBytes in app/config/broadcast.ts.`);this.bytes=$;this.limit=Z;this.name="BroadcastPayloadTooLargeError"}}class c0{options;static token="broadcast";config;driver;warnedAboutSize=new Set;started=!1;hooks;channelRouter;constructor($={},Z={}){this.options=Z;this.config=N1(QG(),$),this.driver=yD(this.config,Z.application)}get channels(){if(this.channelRouter===void 0)this.channelRouter=this.options.channels?new this.options.channels:null;return this.channelRouter}to($,...Z){return new i3(this,c4($,Z[0]),null)}toUser($){return new i3(this,{topic:OZ($),pattern:U0},null)}toOthers($){return new LG(this,gD($))}broadcastEvent($){let Z=$.broadcastOn(),J=Array.isArray(Z)?Z:[Z],W=$.broadcastAs(),Y=$.broadcastWith(),j=J.map((z)=>this.prepare(c4(z,void 0),W,Y,null));for(let{sent:z,frame:X}of j)this.hand(z,X)}send($,Z,J,W){let{sent:Y,frame:j}=this.prepare($,Z,J,W);this.hand(Y,j)}prepare($,Z,J,W){m2(Z);let Y;try{Y=UG($.topic,Z,J,W?FG(W):null)}catch(z){throw TypeError(`The broadcast "${Z}" could not be encoded. Payloads must be JSON.`,{cause:z})}return this.checkSize(Z,Y),{sent:{topic:$.topic,...$.pattern?{pattern:$.pattern}:{},event:Z,data:JSON.parse(Y).d,...W?{except:W}:{}},frame:Y}}hand($,Z){sZ(()=>this.publish($,Z))}publish($,Z){let J=(W)=>console.error(`[gemi] The broadcast "${$.event}" on "${$.topic}" could not be published.`,W);try{let W=this.driver.publish($.topic,Z);if(W&&typeof W.catch==="function")W.catch(J)}catch(W){J(W)}}get isStarted(){return this.started}async start($,Z){if(this.started)throw Error("The broadcast driver was already started in this process.");this.started=!0,this.hooks=Z;try{await this.driver.start($,Z)}catch(J){throw this.started=!1,this.hooks=void 0,J}}topicAdded($){return this.driver.topicAdded?.($)}topicRemoved($){return this.driver.topicRemoved?.($)}async close(){this.started=!1,this.hooks=void 0,await this.driver.close()}revoke($){let Z=vD($);sZ(()=>this.sendRevocation(Z))}sendRevocation($){let Z=(J)=>console.error("[gemi] A broadcast revocation could not be sent.",J);try{if(typeof this.driver.revoke==="function"){let J=this.driver.revoke($);if(J&&typeof J.catch==="function")J.catch(Z);return}this.hooks?.onRevoke?.($)}catch(J){Z(J)}}checkSize($,Z){let J=Buffer.byteLength(Z,"utf8");if(J>this.config.maxEventBytes)throw new DG(J,this.config.maxEventBytes,$);let W=this.config.warnEventBytes;if(W!==!1&&J>W&&!this.warnedAboutSize.has($))this.warnedAboutSize.add($),console.warn(`[gemi] The broadcast "${$}" is ${J} bytes, over ${W}. Broadcasts are change hints: send ids and let the client fetch the data over HTTP. Warned once per event name.`)}}class i3{manager;target;except;constructor($,Z,J){this.manager=$;this.target=Z;this.except=J}emit($,...Z){this.manager.send(this.target,$,Z[0],this.except)}}class LG{manager;except;constructor($,Z){this.manager=$;this.except=Z}to($,...Z){return new i3(this.manager,c4($,Z[0]),this.except)}toUser($){return new i3(this.manager,{topic:OZ($),pattern:U0},this.except)}}function c4($,Z){if(y2($))return{topic:b8($.topic),...$.pattern?{pattern:$.pattern}:{}};if(Z!==void 0||$.includes(":"))return{topic:F3($,Z??{}),pattern:$};if($===U0)throw new u('"user" is not a topic: the "user" channel resolves to user.<id> per subscriber. Emit with Broadcast.toUser(user).');return{topic:b8($)}}function vD($){if($&&typeof $==="object"&&"user"in $)return{user:OZ($.user).slice(U0.length+1)};if($&&typeof $==="object"&&"channel"in $)return{topic:c4($.channel,$.params).topic};throw new u("Broadcast.revoke takes { user } or { channel }.")}function gD($){if($===null||$===void 0)return null;if(typeof $==="string")return mW($)?$:null;let J=($ instanceof Request?$.headers:("rawRequest"in $)?$.rawRequest.headers:$.headers)?.get(h4);return mW(J)?J:null}function yD($,Z){let J=$.driver;if(J===void 0||J==="memory")return new OG;if(J==="redis"){let W=Z?.config.get("redis",{})??{},Y=$.redis??{};return new yW({url:Y.url??W.url??process.env.REDIS_URL,options:Y.options??W.options,prefix:Y.prefix,subscribeTimeoutMs:Y.subscribeTimeoutMs,healthCheckMs:Y.healthCheckMs})}if(typeof J==="function"){if(!Z)throw Error("A broadcast driver factory needs the application to be called with.");return J(Z)}if(typeof J==="object"&&J!==null&&typeof J.publish==="function")return J;throw Error(`Unknown broadcast driver "${String(J)}" in app/config/broadcast.ts. Use "memory" or "redis", or pass a BroadcastDriver.`)}class hW extends Error{code;constructor($,Z=`OAuth callback failed: ${$}`){super(Z);this.name="OAuthCallbackError",this.code=$}}class mD{linkByEmail=!0;createUsers=!0;createUsersWithoutEmail=!1;clientFor($){return Promise.resolve(void 0)}async isAvailable($){return await this.clientFor($)!==null}async redirectUriFor($){return(await this.clientFor($))?.redirectUri}}import{createHash as pW,createHmac as hD,randomBytes as HG,timingSafeEqual as TG}from"crypto";var n3=600,d4="gemi_oauth",pD=`__Host-${d4}`;function nZ($,Z=d4){if(Z===d4)return $?pD:d4;return $?`__Host-${Z}`:Z}function s3($){return $.toString("base64url")}function PG($){return hD("sha256",KZ()).update(`gemi-oauth-state:${$}`).digest()}function MG($,Z){let J=pW("sha256").update($).digest(),W=pW("sha256").update(Z).digest();return TG(J,W)&&$.length===Z.length}function u4($,Z=Date.now(),J={}){let W=s3(HG(32)),Y=s3(HG(32)),j=cD(Y),z={provider:$,state:W,codeVerifier:Y,expiresAt:Z+n3*1000,...J.subject!==void 0?{subject:J.subject}:{},...J.returnTo!==void 0?{returnTo:J.returnTo}:{},...J.redirectUri!==void 0?{redirectUri:J.redirectUri}:{}};return{state:W,codeVerifier:Y,codeChallenge:j,cookieValue:dD(z)}}function cD($){return s3(pW("sha256").update($).digest())}function dD($){let Z=s3(Buffer.from(JSON.stringify($)));return`${Z}.${s3(PG(Z))}`}function uD($){if(typeof $!=="string"||$==="")return null;let Z=$.indexOf(".");if(Z<=0||Z!==$.lastIndexOf("."))return null;let J=$.slice(0,Z),W=Buffer.from($.slice(Z+1),"base64url"),Y=PG(J);if(W.length!==Y.length||!TG(W,Y))return null;try{let j=JSON.parse(Buffer.from(J,"base64url").toString("utf8"));if(typeof j?.provider!=="string"||typeof j?.state!=="string"||typeof j?.codeVerifier!=="string"||typeof j?.expiresAt!=="number"||j.subject!==void 0&&typeof j.subject!=="string"||j.returnTo!==void 0&&typeof j.returnTo!=="string"||j.redirectUri!==void 0&&typeof j.redirectUri!=="string")return null;return j}catch{return null}}var N$=new Map,KG=1e4;function lD($,Z,J){if(N$.size>=KG){for(let[W,Y]of N$)if(Y<=J)N$.delete(W);while(N$.size>=KG){let W=N$.keys().next().value;if(W===void 0)break;N$.delete(W)}}N$.set($,Z)}function l4($){let Z=$.now??Date.now();if(!$.cookieValue||!$.returnedState)return{ok:!1,reason:"missing_state"};let J=uD($.cookieValue);if(!J)return{ok:!1,reason:"invalid_state"};let W=MG(J.state,$.returnedState),Y=MG(J.provider,$.provider);if(!W||!Y)return{ok:!1,reason:"invalid_state"};if(J.expiresAt<=Z)return{ok:!1,reason:"expired_state"};if(N$.has(J.state))return{ok:!1,reason:"invalid_state"};return lD(J.state,J.expiresAt,Z),{ok:!0,payload:J}}var cW=new WeakMap;function sD($){let Z=cW.get($);if(!Z)Z=$(iD(32).toString("hex")),cW.set($,Z),Z.catch(()=>cW.delete($));return Z}async function i4($,Z,J){if(typeof J==="string"&&J!=="")return await $.verifyPassword(Z,J);try{await $.verifyPassword(Z,await sD($.hashPassword))}catch{}return!1}async function $Z($,Z){let J=Z.user??Z.session?.user;if(!J||!$.onAuthenticated)return;let{password:W,...Y}=J;await $.onAuthenticated({...Z,user:Y})}class uW extends Error{}function dW($){return typeof $==="string"&&$!==""?$:null}function NG($){return q$($)}var nD=256;function _G($){return typeof $==="string"&&$!==""&&$.length<=nD?$:null}function IG($){let{password:Z,code:J,...W}=$;return W}var n4="intended_url";function AG($){if($.cookies.get(n4))$.ctx().setCookie(n4,"",{maxAge:-1})}function xG($){let Z=$.cookies.get(n4);if(!Z)return null;AG($);try{return U1(decodeURIComponent(Z),"")||null}catch{return null}}class lW extends C{schema={email:{required:"Email is required",string:"Invalid email",email:"Invalid email"},password:{required:"Password is required"}}}class SG extends C{schema={email:{required:"Email is required",email:"Invalid email"}}}class EG extends C{schema={password:{required:"Password is required",password:"Invalid password"}}}function s4(){throw new K0("Not found",{status:404})}async function u1($,Z){if(!await k1(M(E).config[$],Z))s4()}async function o3($,Z,J,W){let{config:Y}=M(E),j={signIn:"sign-in",signUp:"sign-up",forgot:"forgot",reset:"reset"}[$];await v$(j,Z,J,Y.passwordLimits?.[$]??{},Y.rateLimitKey,W)}async function CG($,Z,J){let{config:W}=M(E);await o3("signIn",q$($),J,async(Y)=>{if(Y==="perEmail"&&typeof Z==="string")await i4(W,Z,null)})}async function oZ($){return await k1(M(E).config.verifyEmail,$)}class Z0 extends O3{async me(){let $=await q0.user();if(!$)throw new o8;return $}async verifyEmail($=new C){await u1("password",$);let Z=await $.input(),{userProvider:J}=M(E),W=dW(Z.get("token"));if(!W)return{email:null};let Y=await J.findUserByVerificationToken(W);if(!Y)return{email:null};return await J.verifyUser(Y.email),{email:Y.email}}async signInWithMagicLink($=new C){let Z=M(E),{userProvider:J}=Z;if(!await k1(Z.config.magicLink,$)&&!await k1(Z.config.emailCode.enabled,$))s4();let W=dW($.search.get("token")),Y=null;try{Y=q$(decodeURIComponent($.search.get("email")??""))}catch{}if(await v$("link",null,$,{perIp:Z.config.emailCode.verifyLimit.perIp},Z.config.rateLimitKey),!Y||!W||!await Z.verifyMagicLinkToken(Y,W))return{error:"Invalid token"};await J.verifyUser(Y);let j=await Z.createOrUpdateSession({email:Y});return $.ctx().setCookie("access_token",j.token,M(E).accessTokenCookieOptions($,j.expiresAt)),await Z.config.onSignIn(j,$.search.toJSON(),{req:$}),await $Z(Z.config,{session:j,isNewUser:!1,method:"magic-link",req:$}),{session:j}}async verifyPinRequest($){await u1("magicLink",$);let Z=M(E),J=await $.input(),{email:W,pin:Y}=J.toJSON(),j=q$(W),z=_G(Y);if(await v$("verify",j,$,Z.config.emailCode.verifyLimit,Z.config.rateLimitKey),!j||!z)throw new d({pin:["Invalid pin"]});let X=await Z.verifyOneTimeCode(j,z);if(X.status==="too_many_attempts")throw new d({pin:["Too many attempts"]});if(X.status!=="ok")throw new d({pin:["Invalid pin"]});return await Z.userProvider.verifyUser(j),j}async signInWithPinV2($=new C){let Z=M(E),J=await this.verifyPinRequest($),W=await Z.createOrUpdateSessionV2({email:J});return $.ctx().setCookie("access_token",W.token,M(E).accessTokenCookieOptions($,W.expiresAt)),await Z.config.onSignIn(W,$.search.toJSON(),{req:$}),await $Z(Z.config,{session:W,isNewUser:!1,method:"magic-link",req:$}),W}async signInWithPin($=new C){let Z=M(E),J=await this.verifyPinRequest($),W=await Z.createOrUpdateSession({email:J});return $.ctx().setCookie("access_token",W.token,M(E).accessTokenCookieOptions($,W.expiresAt)),await Z.config.onSignIn(W,$.search.toJSON(),{req:$}),await $Z(Z.config,{session:W,isNewUser:!1,method:"magic-link",req:$}),{session:W}}async signInV2($=new lW){await u1("password",$);let Z=await $.input(),{email:J,password:W}=Z.toJSON(),Y=J.toLowerCase().trim(),j=M(E);await CG(J,W,$);let z=await j.userProvider.findUserByEmailAddress(Y,await oZ($)),X=typeof W==="string"&&await i4(j.config,W,z?.password);if(!z||!X)throw new d({invalid_credentials:["Invalid credentials"]});let G=await j.createOrUpdateSessionV2({email:z.email,id:z.id});$.ctx().setCookie("access_token",G.token,M(E).accessTokenCookieOptions($,G.expiresAt)),await j.config.onSignIn(z,$.search.toJSON(),{req:$}),await $Z(j.config,{session:G,user:z,isNewUser:!1,method:"password",req:$});let{password:Q,...V}=z;return V}async signIn($=new lW){await u1("password",$);let Z=await $.input(),{email:J,password:W}=Z.toJSON(),Y=J.toLowerCase().trim(),j=M(E);await CG(J,W,$);let z=await j.userProvider.findUserByEmailAddress(Y,await oZ($)),X=typeof W==="string"&&await i4(j.config,W,z?.password);if(!z||!X)throw new d({invalid_credentials:["Invalid credentials"]});let G=await j.createOrUpdateSession({email:z.email,id:z.id});$.ctx().setCookie("access_token",G.token,M(E).accessTokenCookieOptions($,G.expiresAt)),await j.config.onSignIn(z,$.search.toJSON(),{req:$}),await $Z(j.config,{session:G,user:z,isNewUser:!1,method:"password",req:$});let{password:Q,...V}=z;return V}async signUp(){let $=M(E),{userProvider:Z,config:J}=$,W=new J.signUpRequest;await u1("password",W);let Y=await W.input(),{email:j,password:z,name:X,invitationId:G}=Y.toJSON(),Q={method:"password",input:IG(Y.toJSON()),req:W},V=NG(j);if(await o3("signUp",V,W),!V)throw new d({email:["Invalid email"]});if(z!=null&&typeof z!=="string")throw new d({password:["Invalid password"]});if(G!=null&&typeof G!=="string")throw new d({invitationId:["Invalid invitation"]});if(await Z.findUserByEmailAddress(V,!1))throw new d({email:["Email address already exists"]});let B=await J.hashPassword(z),U=M(c).detectLocale(W),D;if(G)D=await Z.findInvitation(G,V);let O,L="";if(D)O=await Z.transaction(async()=>{await Z.deleteInvitationById(G);let H=await Z.createUser({email:V,name:X,password:B,emailVerifiedAt:new Date,locale:U});return await Z.createAccount({organizationId:D.organizationId,userId:H.id,organizationRole:D.role}),await J.onUserCreated(H,Q),H});else{if(L=await J.generateEmailVerificationToken(V),typeof J.verifyEmail==="function"&&!await oZ(W))L="";O=await Z.transaction(async()=>{let H=await Z.createUser({email:V,name:X,password:B,verificationToken:L,locale:U});return await J.onUserCreated(H,Q),H})}return await J.onSignUp(O,L,W.search.toJSON(),{req:W}),O}async signOut($=new C){let Z=E$($),J=M(E),{config:W}=J,Y=await J.revokeSession(Z,$.headers.get("User-Agent"));if($.ctx().setCookie("access_token","",M(E).accessTokenCookieOptions($,new Date(0))),M(E).cookieDomain($))$.ctx().setCookie("access_token","",{...M(E).accessTokenCookieOptions($,new Date(0)),domain:void 0});if(Y?.user)oD(Y.user),Y.user.extension=await W.extendSession(Y.user),await W.onSignOut(Y.user,{req:$});return{}}async forgotPassword($=new SG){await u1("password",$);let Z=await $.input(),J=NG(Z.get("email"));if(await o3("forgot",J,$),!J)return{};let{userProvider:W,config:Y}=M(E),j=await W.findUserByEmailAddress(J,await oZ($));if(!j)return{};let z=await Y.generateForgotPasswordToken(j);return await W.createPasswordResetToken({user:j,token:z}),await Y.onForgotPassword(j,z,{req:$}),{}}async resetPassword($=new EG){await u1("password",$);let{userProvider:Z,config:J}=M(E),W=await $.input(),{password:Y,token:j}=W.toJSON(),z=dW(j);await o3("reset",null,$);let X=z?await Z.findPasswordResetToken({token:z}):null;if(!X)throw new d({token:["Invalid token"]});if(iZ.Instant.from(X.createdAt.toISOString()).add({hours:24}).until(iZ.Now.instant()).sign>=0)throw new d({token:["Token expired"]});await Z.deletePasswordResetToken({token:z});let Q=await Z.findUserByEmailAddress(X.user.email,await oZ($));if(!Q)throw new d({email:["User not found"]});let V=await J.hashPassword(Y);return await Z.updateUserPassword({id:Q.id,password:V}),await Z.deleteAllUserSessions(Q.id),await J.onResetPassword(Q,{req:$}),{}}async changePassword($=new C){await u1("password",$);let{userProvider:Z,config:J}=M(E),W=await q0.user(),Y=await $.input(),{oldPassword:j,newPassword:z}=Y.toJSON();if(await o3("signIn",q$(W?.email),$),typeof z!=="string")throw new d({newPassword:["Invalid password"]});let X=await Z.findUserByEmailAddress(W.email,await oZ($));if(!(typeof j==="string"&&await i4(J,j,X?.password)))throw new d({oldPassword:["Incorrect password"]});let Q=await J.hashPassword(z);return await Z.updateUserPassword({id:W.id,password:Q}),await Z.deleteAllUserSessions(W.id),{}}async oauthRedirect($=new C){let{provider:Z}=$.params,J=M(E).config.oauthProviders,W=Object.hasOwn(J,Z),Y=await PZ(J,Z,$);if(!Y){if(W)throw new K0("Not found",{status:404});throw Error(`Invalid provider: ${Z}`)}let j=DZ($.rawRequest),z=U1($.search.get(l0),"");if(z)$.ctx().setCookie(n4,encodeURIComponent(z),{httpOnly:!0,sameSite:"Lax",secure:j,maxAge:600});else AG($);let X=typeof Y.redirectUriFor==="function"?await Y.redirectUriFor($):void 0,{state:G,codeChallenge:Q,cookieValue:V}=u4(Z,Date.now(),X!==void 0?{redirectUri:X}:{});return $.ctx().setCookie(nZ(j),V,{httpOnly:!0,sameSite:"Lax",secure:j,maxAge:n3}),{destination:await Y.getRedirectUrl($,{state:G,codeChallenge:Q,codeChallengeMethod:"S256"})}}async oauthCallback($=new C){let{provider:Z}=$.params,J=M(E),{userProvider:W,config:Y}=J,j=Object.hasOwn(Y.oauthProviders,Z),z=await PZ(Y.oauthProviders,Z,$);if(j&&!z)throw new K0("Not found",{status:404});let X=DZ($.rawRequest),G=nZ(X),Q=$.cookies.get(G);if(Q!==void 0&&Q!==null)$.ctx().setCookie(G,"",{httpOnly:!0,sameSite:"Lax",secure:X,maxAge:-1});if(!z)return this.oauthFailure($,"unknown_provider");let V=$.search.get("error");if(V)return this.oauthFailure($,/^[a-z0-9_]{1,64}$/.test(V)?V:"provider_error");let F=l4({provider:Z,cookieValue:Q,returnedState:$.search.get("state")});if("reason"in F)return console.error(`Authentication error: OAuth callback refused (${F.reason})`),this.oauthFailure($,F.reason);if(F.payload.redirectUri!==void 0&&typeof z.redirectUriFor==="function"){let N=await z.redirectUriFor($);if(N!==void 0&&N!==F.payload.redirectUri)return console.error("Authentication error: OAuth callback refused (redirect_mismatch)"),this.oauthFailure($,"redirect_mismatch")}if(!$.search.get("code"))return this.oauthFailure($,"missing_code");let B;try{B=await z.onCallback($,{state:F.payload.state,codeVerifier:F.payload.codeVerifier})}catch(N){if(N instanceof hW)return this.oauthFailure($,N.code);return console.error("Authentication error: OAuth provider callback failed",N),this.oauthFailure($,"provider_error")}let{name:U,username:D,providerId:O,emailVerified:L}=B??{},H=typeof B?.email==="string"?B.email:void 0,T=H?I6(H):null,K=O?await W.findUserBySocialAccount(Z,O):null,I="signin",b=!K&&!T&&!H&&!!O&&z.createUsersWithoutEmail===!0;if(!K&&b){if(z.createUsers===!1)return console.error(`Authentication error: a ${Z} sign-in is not linked to a user, and ${Z} does not create users`),this.oauthFailure($,"signup_disabled");try{K=await this.createOAuthUserWithoutEmail({provider:Z,providerId:O,name:U,username:D,locale:M(c).detectLocale($),req:$}),I="signup"}catch(N){let g=await W.findUserBySocialAccount(Z,O);if(!g)throw N;K=g}}if(!K){if(!T)return console.error("Authentication error: No usable email returned from OAuth provider callback"),this.oauthFailure($,H?"invalid_email":O?"missing_email":"no_identity");if(L===!1)return console.error("Authentication error: OAuth provider returned an unverified email"),this.oauthFailure($,"email_not_verified");let N=M(c).detectLocale($);try{let g=await this.linkOAuthAccount({provider:Z,providerId:O,email:T,rawEmail:H,name:U,username:D,locale:N,req:$,linkExisting:z.linkByEmail!==!1,createUser:z.createUsers!==!1});if(g==="account_exists")return console.error(`Authentication error: a ${Z} sign-in matched an existing user by email, and ${Z} does not link by email`),this.oauthFailure($,"account_exists");if(g==="signup_disabled")return console.error(`Authentication error: a ${Z} sign-in is not linked to a user, and ${Z} does not create users`),this.oauthFailure($,"signup_disabled");if(g)K=g.user,I=g.action}catch(g){let _=O?await W.findUserBySocialAccount(Z,O):null;if(!_)throw g;K=_}if(!K)return this.oauthFailure($,"account_conflict")}let S=await J.createOrUpdateSessionV2({email:K.email,id:K.id});if($.ctx().setCookie("access_token",S.token,M(E).accessTokenCookieOptions($,S.expiresAt)),I==="signup")await Y.onSignUp(K,"",$.search.toJSON(),{req:$});else await Y.onSignIn(K,$.search.toJSON(),{req:$});await $Z(J.config,{session:S,user:K,isNewUser:I==="signup",method:"oauth",req:$});let R=xG($)??Y.redirectPath,w=Y.oauthCompleteProfilePath?U1(Y.oauthCompleteProfilePath,""):"";if(w&&!K.email){let N=new URL(w,"http://gemi.invalid");N.searchParams.set(l0,R),R=`${N.pathname}${N.search}${N.hash}`}return{session:S,redirectTo:R}}async createOAuthUserWithoutEmail($){let{userProvider:Z,config:J}=M(E);return await Z.transaction(async()=>{let W=await Z.createUser({email:null,name:$.name??$.username??"",locale:$.locale});return await Z.createSocialAccount({provider:$.provider,providerId:$.providerId,userId:W.id,username:$.username,expiresAt:new Date,accessToken:"",refreshToken:""}),await J.onUserCreated(W,{method:"oauth",input:{},req:$.req}),W})}oauthFailure($,Z){let J=xG($),W=M(E).config.oauthFailurePath;if(W){let Y=U1(W,"");if(Y){let j=new URL(Y,"http://gemi.invalid");if(j.searchParams.set("error",Z),J)j.searchParams.set(l0,J);E1.external(`${j.pathname}${j.search}${j.hash}`)}else console.error(`auth.oauthFailurePath must be a same-origin path, got ${JSON.stringify(W)}`)}return{session:null,error:Z,redirectTo:J}}async linkOAuthAccount($){let{provider:Z,providerId:J,email:W,rawEmail:Y,name:j,username:z,locale:X}=$,{userProvider:G,config:Q}=M(E),V=(D)=>({provider:Z,userId:D,email:W,username:z,providerId:J,expiresAt:new Date,accessToken:"",refreshToken:""}),F=await G.findUserByEmailAddress(W,!1),B=Y?.trim();if(!F&&B&&B!==W)F=await G.findUserByEmailAddress(B,!1);if(F){if($.linkExisting===!1)return"account_exists";if(!J)return{user:F,action:"signin"};let D=await G.findSocialAccounts(F.id,Z);if(D.some((L)=>L.providerId===J))return{user:F,action:"signin"};if(D.some((L)=>L.providerId))return console.error(`Authentication error: user ${F.id} is already linked to a different ${Z} account`),null;let O=D[0];if(O){if(!await G.claimSocialAccount(O,J))throw Error(`${Z} account link changed concurrently`)}else await G.createSocialAccount(V(F.id));return{user:F,action:"signin"}}if($.createUser===!1)return"signup_disabled";return{user:await G.transaction(async()=>{let D=await G.createUser({email:W,name:j,locale:X,emailVerifiedAt:new Date});if(J)await G.createSocialAccount(V(D.id));return await Q.onUserCreated(D,{method:"oauth",input:{},req:$.req}),D}),action:"signup"}}async createMagicLinkToken($=new C){await u1("magicLink",$);let Z=await $.input(),J=q$(Z.get("email")),W=M(E),{uniformMagicLinkResponse:Y,requestLimit:j}=W.config.emailCode;if(await v$("request",J,$,j,W.config.rateLimitKey),!J)return{email:null};let{user:z,pin:X,token:G}=await W.createMagicLinkToken(J);if(z)return await W.config.onMagicLinkCreated(z,{email:J,pin:X,token:G,req:$}),{email:J};return{email:Y?J:null}}async requestEmailCode($=new C){let Z=M(E),J=Z.config.emailCode;if(!await k1(J.enabled,$))s4();let W=await $.input(),Y=I6(W.get("email"));if(await v$("request",Y,$,J.requestLimit,Z.config.rateLimitKey),!Y)throw new d({email:["Invalid email"]});let j=await Z.userProvider.findUserByEmailAddress(Y,!1);if(j||J.createUser){let{pin:z,token:X}=await Z.issueOneTimeCode(Y,J.length);await J.send({email:Y,code:z,token:X,isNewUser:!j,req:$})}return{ok:!0}}async verifyEmailCode($=new C){let Z=M(E),{userProvider:J,config:W}=Z;if(!await k1(W.emailCode.enabled,$))s4();let Y=await $.input(),{email:j,code:z,name:X}=Y.toJSON(),G=I6(j),Q=_G(z);if(await v$("verify",G,$,W.emailCode.verifyLimit,W.rateLimitKey),!G||!Q)throw new d({code:["invalid_code"]});let V=await Z.verifyOneTimeCode(G,Q,{claim:!1});if(V.status==="too_many_attempts")throw new d({code:["too_many_attempts"]});if(V.status!=="ok")throw new d({code:["invalid_code"]});let F=V.row,B=await J.findUserByEmailAddress(G,!1),U=!1;if(B){if(!await Z.claimOneTimeCode(G,F.id))throw new d({code:["invalid_code"]});await J.verifyUser(G)}else if(W.emailCode.createUser){let O=M(c).detectLocale($);try{B=await J.transaction(async()=>{if(!await Z.claimOneTimeCode(G,F.id))throw new uW;let L=await J.createUser({email:G,name:typeof X==="string"?X.trim():"",emailVerifiedAt:new Date,locale:O});return await W.onUserCreated(L,{method:"email-code",input:IG(Y.toJSON()),req:$}),L}),U=!0}catch(L){if(L instanceof uW)throw new d({code:["invalid_code"]});throw L}}else throw await Z.claimOneTimeCode(G,F.id),new d({code:["invalid_code"]});let D=await Z.createOrUpdateSessionV2({email:G,id:B.id});return $.ctx().setCookie("access_token",D.token,M(E).accessTokenCookieOptions($,D.expiresAt)),await W.onSignIn(D,$.search.toJSON(),{req:$}),await $Z(Z.config,{session:D,isNewUser:U,method:"email-code",req:$}),{session:D,isNewUser:U}}}function oD($){try{let Z=$?.id;if(Z===void 0||Z===null)return;let J=M();if(typeof J?.bound!=="function"||!J.bound(c0))return;J.make(c0).revoke({user:{id:Z}})}catch(Z){console.error("[gemi] Revoking the signed-out user's sockets failed:",Z)}}var bG="gemi_oauth_connection";class o4 extends O3{async connect($=new C){let Z=String($.params.provider??""),W=M(a3).providers[Z],Y=await q0.user(),j=U1($.search.get(l0),"");if(!W)return this.finish(j,Z,"unknown_provider");let z=DZ($.rawRequest),{state:X,codeChallenge:G,cookieValue:Q}=u4(RG(Z),Date.now(),{subject:String(Y.id),...j?{returnTo:j}:{}});return $.ctx().setCookie(nZ(z,bG),Q,{httpOnly:!0,sameSite:"Lax",secure:z,maxAge:n3}),E1.external(W.authorizationUrl({state:X,codeChallenge:G,redirectUri:kG($,Z,W.config.redirectUri)})),{destination:"/"}}async callback($=new C){let Z=String($.params.provider??""),J=M(a3),W=await q0.user(),Y=DZ($.rawRequest),j=nZ(Y,bG),z=$.cookies.get(j);if(z!==void 0&&z!==null)$.ctx().setCookie(j,"",{httpOnly:!0,sameSite:"Lax",secure:Y,maxAge:-1});let X=l4({provider:RG(Z),cookieValue:z,returnedState:$.search.get("state")}),G="payload"in X?X.payload.returnTo??"":"",Q=J.providers[Z];if(!Q)return this.finish(G,Z,"unknown_provider");let V=$.search.get("error");if(V)return this.finish(G,Z,/^[a-z0-9_]{1,64}$/.test(V)?V:"provider_error");if("reason"in X)return console.error(`OAuth connection refused (${X.reason})`),this.finish(G,Z,X.reason);if(X.payload.subject!==String(W.id))return this.finish(G,Z,"user_mismatch");let F=$.search.get("code");if(!F)return this.finish(G,Z,"missing_code");try{let B=await Q.exchangeCode({code:F,codeVerifier:X.payload.codeVerifier,redirectUri:kG($,Z,Q.config.redirectUri)}),U=await J.save(W,Z,B);await M(E).config.onConnected({user:W,provider:Z,connection:U,profile:B.profile??null,req:$})}catch(B){if(B instanceof wG)return console.error(`OAuth connection to ${Z} failed: ${B.message}`),this.finish(G,Z,B.providerError??B.code);throw B}return this.finish(G,Z)}finish($,Z,J){let W=$||U1(M(E).config.redirectPath,"/"),Y=new URL(W,"http://gemi.invalid");if(Y.searchParams.set("connection",Z),J)Y.searchParams.set("connection_error",J);throw E1.external(`${Y.pathname}${Y.search}${Y.hash}`),Error("unreachable: Redirect.external throws")}}function RG($){return`connection:${$}`}function kG($,Z,J){if(J)return J;return`${ZZ()??new URL($.rawRequest.url).origin}/auth/connections/${encodeURIComponent(Z)}/callback`}function fG($){return $.magicLink!==!1||Y7($.emailCode?.enabled)}function qG($){return Object.keys($.oauthProviders??{}).length>0}function vG($={}){let Z=[];if(fG($))Z.push({view:"auth/MagicLinkSignIn",requiredBy:Y7($.emailCode?.enabled)&&$.magicLink===!1?"auth.emailCode.enabled":`auth.magicLink${$.magicLink===void 0?" (on by default; set `magicLink: false` to turn it off)":""}`});if(qG($)){let W=`auth.oauthProviders (${Object.keys($.oauthProviders??{}).join(", ")})`;Z.push({view:"_Redirect",requiredBy:W},{view:"auth/OauthCallback",requiredBy:W})}return Z}class gG extends b1{middlewares=["cache:private"];routes={"/:provider":this.redirect([o4,"connect"]).middleware(["auth"]),"/:provider/callback":this.redirect([o4,"callback"]).middleware([D6,"auth"])}}function yG($={}){let Z=fG($),J=qG($);class W extends b1{middlewares=["cache:private"];routes={"/:provider":this.view("_Redirect",[Z0,"oauthRedirect"]),"/:provider/callback":this.view("auth/OauthCallback",[Z0,"oauthCallback"])}}return class extends b1{middlewares=["cache:private"];routes={...Z?{"/sign-in/magic-link":this.view("auth/MagicLinkSignIn",[Z0,"signInWithMagicLink"])}:{},...J?{"/oauth":W}:{},"/connections":gG}}}class iW extends C0{middlewares=["cache:private"];routes={"/sign-in":this.post(Z0,"signIn"),"/sign-in-v2":this.post(Z0,"signInV2"),"/sign-up":this.post(Z0,"signUp"),"/sign-out":this.post(Z0,"signOut"),"/forgot-password":this.post(Z0,"forgotPassword"),"/reset-password":this.post(Z0,"resetPassword"),"/change-password":this.post(Z0,"changePassword"),"/verify-email":this.post(Z0,"verifyEmail"),"/me":this.get(Z0,"me").middleware(["auth"]),"/magic-link":this.post(Z0,"createMagicLinkToken"),"/sign-in-with-pin":this.post(Z0,"signInWithPin"),"/sign-in-with-pin-v2":this.post(Z0,"signInWithPinV2"),"/email-code":this.post(Z0,"requestEmailCode"),"/email-code/verify":this.post(Z0,"verifyEmailCode")}}class sW extends C0{middlewares=["cache:private,0,no-store"];routes={"/set-locale/:locale":this.get(async()=>{let Z=new C().params.locale;return await M(c).onLocaleChange(Z),{locale:Z}}),"/translations/:locale/:scope*":this.get(async()=>{let $=new C,Z=`/${$.params.scope??""}`,J=$.params.locale,W=M(c),Y=J??W.detectLocale($),j=W.getPageTranslations(Y,Z);return $.ctx().setCookie("i18n-locale",Y,{expires:new Date(Date.now()+31536000000)}),{[Y]:j}})}}class nW{}class oW extends nW{async resize($,Z){let{height:J,width:W,quality:Y,fit:j}=Z;return await(await a4("The Sharp image optimization driver"))($).resize(W>0?W:void 0,J>0?J:void 0,{fit:j}).webp({quality:Y>0?Y:80,force:!0}).toBuffer()}}function C_($){return $}function mG(){return{driver:new oW,allowedHosts:[],maxSize:10485760,timeout:1e4}}class F0 extends Error{status;constructor($,Z,J){super(Z,J);this.status=$;this.name="ImageSourceError"}}var aD=new Set([301,302,303,307,308]),tD="/api/__gemi__/services/image/";async function pG($,Z){let J=Z.maxRedirects??5,W=AbortSignal.timeout(Z.timeout),Y=Z.ownOrigins[0]??Z.localOrigin,j=hG($,Y);try{for(let z=0;;z++){let X=await rD(j,Z,W),G=X.headers.get("location");if(aD.has(X.status)&&G){if(await X.body?.cancel().catch(()=>{}),z>=J)throw new F0(502,"The image redirects too many times");j=hG(G,j.href);continue}if(!X.ok)throw await X.body?.cancel().catch(()=>{}),new F0(404,"Image not found");if(!X.headers.get("content-type")?.split(";")[0].trim().toLowerCase()?.startsWith("image/"))throw await X.body?.cancel().catch(()=>{}),new F0(415,"The source is not an image");return{bytes:Buffer.from(await X.arrayBuffer()),cacheControl:X.headers.get("cache-control")}}}catch(z){if(z instanceof TypeError&&z.message.startsWith("safeFetch:"))throw z;throw $L(z,W)}}function hG($,Z){let J;try{J=new URL($,Z)}catch{throw new F0(400,"The url parameter is not a URL")}if(J.protocol!=="http:"&&J.protocol!=="https:")throw new F0(400,"Only http(s) images can be resized");return J}async function rD($,Z,J){let W={method:"GET",redirect:"manual",signal:J,timeout:Z.timeout,maxSize:Z.maxSize,headers:{accept:"image/*"}},Y=$;if(Z.ownOrigins.includes($.origin)){if($.pathname.startsWith(tD))throw new F0(403,"This image source is not allowed");if(eD($.pathname))throw new F0(403,"This image source is not allowed");let j=new URL(Z.localOrigin).origin,z=new URL(`${$.pathname}${$.search}`,j);if(z.origin===j)return R1(z,{...W,allowPrivate:!0,ports:"any"});Y=z}if(Z.allowedHosts.length===0)throw new F0(403,"This image source is not allowed");return R1(Y,{...Z.external,...W,allow:Z.allowedHosts})}function eD($){let Z=$;for(let J=0;J<5;J++){if(/^[/\\][/\\]/.test(Z))return!0;let W;try{W=decodeURIComponent(Z)}catch{return!0}if(W===Z)return!1;Z=W}return!0}function $L($,Z){if($ instanceof F0)return $;if(Z.aborted)return new F0(504,"The image took too long to load",{cause:$});if($ instanceof H6)switch($.code){case"blocked-host":case"blocked-address":case"invalid-url":return new F0(403,"This image source is not allowed",{cause:$});case"too-large":return new F0(413,"The image is too large",{cause:$});case"timeout":return new F0(504,"The image took too long to load",{cause:$})}return new F0(502,"The image could not be loaded",{cause:$})}class aW extends C0{routes={"/resize":this.file(async()=>{let $=new C,Z=new URL($.rawRequest.url),J=Z.searchParams.get("url"),W=Number(Z.searchParams.get("w")),Y=Number(Z.searchParams.get("h")),j=Z.searchParams.get("fit")??"cover",z=Number(Z.searchParams.get("q"));if(!J)return cG(400,"url query parameter is required");let X=M(dG),G=[Z.origin,`${Z.protocol==="https:"?"http":"https"}://${Z.host}`],Q=ZZ();if(Q&&URL.canParse(Q))G.push(new URL(Q).origin);let V;try{V=await pG(J,{ownOrigins:G,localOrigin:`http://localhost:${process.env.PORT||5173}`,allowedHosts:X.allowedHosts,maxSize:X.maxSize,timeout:X.timeout})}catch(U){if(U instanceof F0)return cG(U.status,U.message);throw U}let F=await X.resize(V.bytes,{height:Y,width:W,fit:j,quality:z}),B=new Headers({"Content-Type":"image/webp","Content-Length":`${F.byteLength}`});if(V.cacheControl)B.set("Cache-Control",V.cacheControl);return new Response(new Uint8Array(F),{headers:B})})}}function cG($,Z){return Response.json({error:Z},{status:$})}class dG{static token="image";driver;allowedHosts;maxSize;timeout;constructor($={}){let Z=mG();this.driver=$.driver??Z.driver,this.allowedHosts=$.allowedHosts??Z.allowedHosts,this.maxSize=$.maxSize??Z.maxSize,this.timeout=$.timeout??Z.timeout}resize($,Z){return this.driver.resize($,Z)}}class tW extends C0{middlewares=["cache:private,0"];routes={"/live":this.get(async()=>{let $=Bun.file(M(uG).currentLogFilePath);return new Response(await $.text(),{headers:{"Content-Type":"text/plain"}})})}}function p_($){return $}function lG(){return{onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{}}}function iG(){return{partialRendering:!0,localeRouting:"prefix",theme:{},publicFiles:!0,assetRoutes:!1,onNotFound:()=>{},onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{},onStreamComplete:()=>{}}}function ZL($){return"run"in $}function JL($){return Object.hasOwn($,"get")||Object.hasOwn($,"post")||Object.hasOwn($,"put")||Object.hasOwn($,"patch")||Object.hasOwn($,"delete")}function WL($){return Object.hasOwn($,"first")&&Object.hasOwn($,"second")}function YL($){if("__brand"in $)return $.__brand==="ApiRouter";return!1}function jL($){if("__internal_brand"in $)return $.__internal_brand==="ProxyHandler";return!1}function sG($){if("__internal_brand"in $)return $.__internal_brand==="StreamHandler";return!1}function zL($){let Z=$.replace(/(?<!:\w*)\([\w-]+\)/g,"");if(Z===$)return $;let J=`/${Z}`.replace(/\/{2,}/g,"/");return J.length>1?J.replace(/\/$/,""):J}function rW($,Z="",J=[]){let W={};function Y(j,z,X,G,Q){let V=j==="/"?"":j,F=Z==="/"?"":Z,B=zL((`${F}${V}`===""?"/":`${F}${V}`).replaceAll("//","/"));if(!W[B])W[B]={};W[B][z.toUpperCase()]={exec:X,middleware:[...J,...G],...Q?{source:Q}:{}},W[B].OPTIONS={exec:()=>{let D=new C().ctx().headers;return new Response(null,{headers:D,status:204})},middleware:[]}}for(let[j,z]of Object.entries($)){if(jL(z)){let X=z;for(let G of["GET","POST","PUT","DELETE"])Y(j,G,X.run.bind(X),X.middlewares);continue}if(ZL(z)){let X=z,G=X.method,Q=X.middlewares,V=X.run.bind(X);if(Y(j,G,V,Q,X.source),sG(z))Y(j,"HEAD",V,Q,X.source)}if(JL(z))for(let[X,G]of Object.entries(z)){let Q=G,V=Q.middlewares,F=Q.run.bind(Q);if(Y(j,X,F,V,Q.source),X==="get"&&sG(Q))Y(j,"HEAD",F,V,Q.source)}if(YL(z)){let X=new z,G=rW(X.routes,`${Z}${j}`,[...J,...X.middlewares]);for(let[Q,V]of Object.entries(G)){let F=Q.replaceAll("//","/");W[F]={...W[F],...V}}}if(WL(z)){let{first:X,second:G}=z;for(let[Q,V]of Object.entries(X)){let F=V.middlewares,B=V.run.bind(V),[U,...D]=j.split("/").reverse();if(!U.startsWith(":"))throw Error("Resource route must end with a dynamic segment");Y(D.reverse().join("/"),Q,B,F,V.source)}for(let[Q,V]of Object.entries(G)){let F=V.middlewares,B=V.run.bind(V);Y(j,Q,B,F,V.source)}}}return Object.fromEntries(Object.entries(W).sort(([j],[z])=>{let X=j.split("/").length+j.split(":").length,G=z.split("/").length+z.split(":").length;return X-G}))}function t4($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function eW($,Z){if($==="/")return Z;if(Z==="/")return $;return`${$}${Z}`}function $5($){let Z=t4($);return Z.length>1?Z.replace(/\/$/,""):Z}function nG($,Z){return Z.map((J)=>({...J,path:$5(eW($,J.path))}))}function r4($){let Z={};for(let[J,W]of Object.entries($))if("run"in W){let Y=W;if("children"in Y){let j=new Y.children,z=r4(j.routes);for(let[X,{exec:G,middleware:Q,segments:V,features:F,static:B}]of Object.entries(z)){let U=eW(J,X),D=(O)=>Y.run.call(Y,O,J);Z[t4(U)]={exec:[D,...G],middleware:[...Y.middlewares,...Q],features:[...Y.featureGates,...F],viewPath:Y.viewPath,segments:[{path:$5(J),viewPath:Y.viewPath,...Y.alwaysRuns?{alwaysRun:!0}:{}},...nG(J,V)],...B?{static:B}:{}}}}else{let j=(z)=>Y.run.call(Y,z,J);Z[t4(J)]={exec:[j],middleware:Y.middlewares,features:Y.featureGates,viewPath:Y.viewPath,segments:[{path:$5(J),viewPath:Y.viewPath}],..."staticOptions"in Y&&Y.staticOptions?{static:Y.staticOptions}:{}}}}else{let Y=new W,j=r4(Y.routes);for(let[z,{exec:X,middleware:G,viewPath:Q,segments:V,features:F,static:B}]of Object.entries(j)){let U=eW(J,z);Z[t4(U)]={exec:X,middleware:[...Y.middlewares,...G],features:[...Y.featureGates,...F],viewPath:Q,segments:nG(J,V),...B?{static:B}:{}}}}return Object.fromEntries(Object.entries(Z).sort(([J],[W])=>{let Y=J.split("/").length+J.split(":").length,j=W.split("/").length+W.split(":").length;return Y-j}))}var Z5="theme";function oG($){return $==="light"||$==="dark"||$==="system"}function aG($){return`!function(o){try{var e=null,d=document.documentElement,c=d.classList,k=document.cookie.split(';'),i,j,v;
|
|
14
14
|
for(i=0;i<k.length;i++){j=k[i].indexOf('=');if(j>0&&k[i].slice(0,j).trim()===o.cookie){v=decodeURIComponent(k[i].slice(j+1).trim());break}}
|
|
15
15
|
if(v!=='light'&&v!=='dark'&&v!=='system'){try{v=localStorage.getItem('theme')}catch(x){}}
|
|
16
16
|
if(v==='light'||v==='dark'||v==='system')e=v;else e=o.default;
|
|
@@ -20,7 +20,7 @@ c.remove(e==='dark'?'light':'dark');c.add(e);d.style.colorScheme=e}catch(x){}}($
|
|
|
20
20
|
`)),Z.onSettle((V)=>{if(X||V.status!=="resolved")return;z.enqueue(Y.encode(`${JSON.stringify([V.path,V.variantKey,V.data])}
|
|
21
21
|
`))});let Q=setTimeout(()=>G(!0),J);Z.allSettled().then(()=>G(!1),()=>G(!1))},cancel(){j(!1)}})}import{Fragment as Hx,createContext as dL,createElement as Mx,lazy as Kx,use as Tx,useContext as Px}from"react";import{createContext as IL}from"react";var xL=IL(null);import{createContext as SL,useContext as lI}from"react";import{useContext as hI}from"react";import{createContext as CL}from"react";import{jsx as gI}from"react/jsx-runtime";var AL=CL({});var EL="gemi.islandI18n",bL=globalThis[Symbol.for(EL)]??=SL(null);import{createContext as fQ,useMemo as Gx,useRef as Qx}from"react";class P5{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 CQ($,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 AQ($){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 SQ="/auth/sign-in",RL=1000,kL=2,N5,_5=null,W3="idle",EQ=0,I5=[];function RQ($,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 wL($){let Z=$?.get?.(x5);if(typeof Z!=="string"||Z==="")return SQ;if(/^https?:\/\//i.test(Z))return Z;if(Z.startsWith("/")&&!Z.startsWith("//")&&!Z.includes("\\"))return Z;return SQ}function fL(){let $=_5?.current();if($)return $;if(typeof window>"u")return null;return{pathname:window.location.pathname,search:window.location.search}}var bQ=($)=>$.replace(/\/+$/,"")||"/";function qL($,Z){let J=q8($),W=new URL($,"http://gemi.invalid");if(!J&&bQ(W.pathname)===bQ(Z.pathname))return null;return W.searchParams.set(l0,J?Z.pathname:`${Z.pathname}${Z.search}`),J?W.href:`${W.pathname}${W.search}`}function vL($){if(!q8($)&&_5)_5.replace($);else window.location.replace($)}function kQ($){if(!N5||typeof window>"u")return;if(!RQ($.status,$.body))return;if($.path.split("?")[0]==="/auth/me")return;if(W3==="handled")return;if(W3==="idle"&&EQ>=kL)return;if($.refetch)I5.push($.refetch);if(W3==="checking")return;W3="checking",EQ++;let Z=$;setTimeout(()=>{gL(Z)},RL)}async function gL($){let Z=!1,J=$.headers?.get?.(x5)?$.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=RQ(X.status,G),Z&&!J)J=X.headers}catch{}let W=I5;if(I5=[],!Z){W3="idle";for(let X of W)try{X()}catch(G){console.error(G)}return}W3="handled";let Y=fL();if(!Y)return;let j=qL(wL(J),Y);if(!j)return;let z={source:$.source,path:$.path,error:$.error,signInUrl:j,redirect:()=>vL(j)};try{if(N5==="redirect")z.redirect();else N5?.(z)}catch(X){console.error(X)}}var C5=5000,yL=2147483647;class YZ{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;constructor($,Z){this.key=$,this.store=new P5(new Map),this.hydrate(Z)}hydrate($){let Z=this.store.getValue(),J=Date.now(),W=!1;for(let[Y,j]of Object.entries($??{})){if(j===void 0)continue;let z=Z.get(Y);if(z?.loading)continue;if(z?.hasData&&z.data===j)continue;this.fill(Z,Y,j,J),W=!0}if(W)this.store.next(Z)}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($)}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}),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.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.retryTimers.has($)||this.inflight.has($))return;let J=Math.min(Math.max(0,Z||0),yL),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)}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}));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 F=this.controllers.get($);if(!F)F=new Set,this.controllers.set($,F);F.add(j)}let z=()=>this.issued.get($)===Y,X=()=>(this.applied.get($)??0)>=Y,G=()=>{this.failures.set($,W?(this.failures.get($)??0)+1:1)},Q=this.store.getValue(),V=(F)=>{if(!z())return;G();let B=Q.get($);this.store.next(Q.set($,{loading:!1,data:B?.data,hasData:B?.hasData??!1,error:F,version:B?.version}))};try{let F=Q.get($);if(!Z)Q.set($,{loading:!0,data:F?.data,hasData:F?.hasData??!1,error:F?.error,version:F?.version});let B=null,U=null,D=[this.key,$].filter((O)=>O.length).join("?");try{U=await fetch(`/api${D}`,{cache:J&&!this.staleVariants.has($)?"default":"reload",signal:j?.signal});try{B=await AQ(U)}catch(O){if(U.ok)throw O;B=null}}catch(O){if(j?.signal.aborted){let L=Q.get($);if(z()&&L?.loading)this.store.next(Q.set($,{...L,loading:!1}));return}console.error(`Error fetching url /api${D}`,O),V(O);return}if(U.ok){if(X()){let L=Q.get($);if(z()&&L?.loading)this.store.next(Q.set($,{...L,loading:!1}));return}this.applied.set($,Y);let O=Q.get($);this.store.next(Q.set($,{loading:z()?!1:O?.loading??!1,data:B,hasData:!0,error:null,version:Date.now()})),this.staleVariants.delete($),this.lastFetchRecord.set($,Date.now()),this.failures.delete($)}else{let O=new t0(this.key,$,U.status,B,CQ(U.headers?.get?.("retry-after")));if(V(O),z())kQ({source:"query",path:this.key,status:U.status,body:B,headers:U.headers,error:O,refetch:()=>this.resolveVariant($,!0,!1)})}}finally{if(j){let F=this.controllers.get($);if(F?.delete(j),F?.size===0)this.controllers.delete($)}if(z())this.inflight.delete($);this.settle($)}}}import{jsx as hL}from"react/jsx-runtime";var Vx=fQ(null);var qQ=fQ({getResource:($,Z={})=>{return new YZ($,Z)},hydrate:()=>{},clearErrors:()=>{}});function mL(){let $=new Map;return{getResource(Z,J){let W=$.get(Z);if(!W)W=new YZ(Z,J??{}),$.set(Z,W);return W},hydrate(Z){if(!Z)return;for(let[J,W]of Object.entries(Z)){if(!W||typeof W!=="object")continue;let Y=$.get(J);if(Y)Y.hydrate(W);else $.set(J,new YZ(J,W))}},clearErrors(){for(let Z of $.values())Z.clearError()}}}var wQ="gemi.islandQueries";if(typeof window<"u"){let $=globalThis;if(!$[Symbol.for(wQ)]){let Z=mL(),J={seed:Z.hydrate,Provider:({children:W})=>hL(qQ.Provider,{value:Z,children:W})};$[Symbol.for(wQ)]=J}}import{createContext as pL}from"react";var cL=pL(null);function vQ($,Z={},J){let W=new Set,Y=new Map,j=J?{ensure(Q,V){let F=J.find(Q,V);if(!F||F.source!=="prefetch"||F.status==="rejected")return null;return z(F),F}}: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(V,F){let B=Q.get(V);if(!B){let U=new Map(J.entriesFor(V).filter((O)=>O.source==="prefetch"&&O.status==="resolved").map((O)=>[O.variantKey,O]));B=new YZ(V,U.size>0?Object.fromEntries(Array.from(U,([O,L])=>[O,L.data])):F??{});let D=B.peek.bind(B);B.peek=(O)=>{let L=U.get(O);if(L)z(L);return D(O)},Q.set(V,B)}return B},hydrate(){},clearErrors(){}}},islands:[],render:$,instances:new WeakMap,count:0,i18n:{},localeAware:Boolean(Z.currentLocale),i18nUsed:!1,dictionaries:[],sink:{use(Q,V,F){let B=`${Q} ${V}`;if(W.has(B))return;W.add(B),G.dictionaries.push([Q,V,F])},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 gQ($){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 yQ($){let Z;for(let J of $.queriesRead.values()){if(J.status!=="resolved")continue;Z??={},(Z[J.path]??={})[J.variantKey]=J.data}return Z}var e3="gemi-slot",mQ="data-slot",hQ="data-gemi-slot";var uL=Symbol.for("gemi.staticRender"),pQ=globalThis[uL]??=dL(null);import{createHash as iQ}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 lL}from"crypto";import{existsSync as dQ,readFileSync as iL}from"fs";import{join as R5}from"path";var uQ=".script",sL=[".ts",".js"],nL="document-scripts.json",lQ="data-gemi-script",oL=/^[A-Za-z0-9_-]+(\/[A-Za-z0-9_-]+)*$/;function aL($){if(typeof $!=="string"||!oL.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 tL($,Z){for(let J of sL){let W=R5($,"views",`${Z}${uQ}${J}`);if(dQ(W))return W}return null}async function cQ($){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 rL($){return`'sha256-${lL("sha256").update($).digest("base64")}'`}var S5,E5=new Map;function eL(){if(S5===void 0){let $=R5(b5(),"dist","server",nL);S5=dQ($)?JSON.parse(iL($,"utf8")):null}return S5??null}async function k5($){aL($);let Z=Bun.env.NODE_ENV==="production";if(Z){let j=eL()?.[$];if(j!==void 0)return j;let z=E5.get($);if(z)return z}let J=R5(b5(),"app"),W=tL(J,$);if(!W)throw Error(`The document script "${$}" was not found. It is a file at app/views/${$}${uQ}.ts (or .js).`);if(!Z)return cQ(W);let Y=cQ(W);return E5.set($,Y),Y.catch(()=>E5.delete($)),Y}async function wx($){return rL(await k5($))}var $H="gemi-islands",ZH="gemi-island-i18n",JH="gemi-island-queries",px=`'sha256-${iQ("sha256").update(q5).digest("base64")}'`;function w5($,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,"<"),cx=`'sha256-${iQ("sha256").update(A5).digest("base64")}'`,WH='await import("/refresh.js").catch(()=>{});await import("/@vite/client").catch(()=>{});',YH="gemi-static";function sQ($,Z,J,W,Y,j){let z=new Set,X=[];if(J)X=Z.islands.map((L)=>{let H=L.module?J(L.module):void 0;if(!H)return console.error(`[gemi] island ${L.module??"(unknown module)"}: no client build entry. Declare it as island(() => import("./Component")) so gemi's Vite plugin builds it.`),null;if(L.load==="eager"){for(let T of H.preload)z.add(T);if(L.preloadDynamic)for(let T of H.dynamicPreload??[])z.add(T)}return{s:H.src,e:L.export,l:L.load}});let G=X.some((L)=>L!==null),Q=j?`<script type="module" ${lQ}="${f5(j.name)}">${j.source}</script>`:"";if(!G&&!Y)return w5($,"</head>",Q,!1);let F=(Y?`<meta name="${YH}" content="${f5(Y.identity)}"${Y.prefetch==="none"?' data-prefetch="none"':""}/>`:"")+[...z].map((L)=>`<link rel="modulepreload" href="${f5(L)}"/>`).join("")+Q,B=Y?A5:q5,U=G?gQ(Z):void 0,D=G?yQ(Z):void 0,O=(G?`<script type="application/json" id="${$H}">${i0({i:X})}</script>`:"")+(U?`<script type="application/json" id="${ZH}">${i0(U)}</script>`:"")+(D?`<script type="application/json" id="${JH}">${i0(D)}</script>`:"")+`<script type="module">${W?WH+B:B}</script>`;return w5(w5($,"</head>",F,!1),"</body>",O,!0)}function jH($,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 nQ($){let Z=`<template ${hQ}="`;for(let J=$.lastIndexOf(Z);J!==-1;J=$.lastIndexOf(Z)){let W=jH($,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=`<${e3} ${mQ}="${j}" style="display:contents"></${e3}>`;$=$.split(G).join(`<${e3} style="display:contents">${X}</${e3}>`)}return $}function v5($){if(!$)return{locale:!0,session:!0,csrf:!0};return{locale:!1,session:$.session===!0,csrf:$.csrf===!0}}function tQ($,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 zH($){let Z=$.headers.get("Cache-Control")?.toLowerCase()??"";return/(^|[\s,])(public|s-maxage)\b/.test(Z)}var oQ=new Set,XH=new Set(["public","private","s-maxage","proxy-revalidate"]);function g5($,Z){let J=$.get("Cache-Control");if(!J||$.getSetCookie().length===0)return;if(!/(^|[\s,])(public|s-maxage)\b/i.test(J))return;let Y=["private",...J.split(",").map((j)=>j.trim()).filter((j)=>{let z=j.split("=")[0].trim().toLowerCase();return z!==""&&!XH.has(z)})].join(", ");if(Bun.env.NODE_ENV!=="production"&&!oQ.has(Z)){oQ.add(Z);let j=[...new Set($.getSetCookie().map((z)=>z.split("=")[0]))];console.warn(`[gemi] The view "${Z??""}" sets cookies (${j.join(", ")}) on a response with Cache-Control "${J}", so it was sent "${Y}" 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",Y)}var aQ=new Set;function rQ($,Z){if(!zH($)||$.headers.getSetCookie().length===0)return $;if(Bun.env.NODE_ENV!=="production"&&!aQ.has(Z))aQ.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 GH=async()=>(await import("./chunk-w2z4jc4v.js")).default,y5,$6=async(...$)=>{return y5??=import("react-dom/server.browser").catch((Z)=>{throw y5=void 0,Z}),(await y5).renderToReadableStream(...$)},$B=1e4,ZB="no-locale",QH="no-theme";async function BH($,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 d5="/assets";function VH($){return $===d5||$.startsWith(`${d5}/`)}function FH($){let Z=$.filter(VH);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 "${d5}" 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 UH($){let Z=M(B1).resolver;return{...$.domain,root:Z.root,origin:Z.publicOrigin($.rawRequest)}}function m5($){let{status:Z=400,error:J,body:W,...Y}=$;return new Response(W??J?.message,{...Y,status:Z})}function OH($){let{status:Z=400,data:J,directive:W,headers:Y}=$;return new Response(JSON.stringify({data:J,directive:W}),{headers:Y,status:Z})}class Z6{static token="router.view";flatViewRoutes={};routeManifest={};clientRouteManifest={};componentTree=[];flatComponentTree=[];requiredViews={};staticRoutes=[];root=null;shellReporter=_Q();preloadCache=new WeakMap;hooks;partialRendering;localeRouting;detectLocale;theme;defaultMeta;notFound;publicFiles;assetRoutes;translate;constructor($,Z={}){let J=iG();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.translate=$.translate,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":yG(Z)};if(this.requiredViews=Object.fromEntries(vG(Z).map(({view:Y,requiredBy:j})=>[Y,j])),this.flatViewRoutes=r4(W),!this.assetRoutes)FH(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=M(j$);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)=>{jZ.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 V of J?.[Q]??[])G.add(V);return[...G].map((Q)=>l1("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 V=c5(),F=new AbortController,B=setTimeout(()=>F.abort(),$B),U=(O)=>{if(Bun.env.NODE_ENV!=="production")console.error(O)},D=vQ(async(O,L)=>{let H=await $6(O,{signal:F.signal,identifierPrefix:L,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:U});return await H.allReady.catch(()=>{}),await new Response(H).text()},{currentLocale:j?.i18n?.currentLocale,defaultLocale:j?.i18n?.defaultLocale,timeZone:j?.i18n?.timeZone},z);try{let O,L=typeof W.script==="function"?await J(()=>W.script(Z)):W.script;if(L)O={name:L,source:await k5(L)};let H;if(W.navigation){let I=W.navigation===!0?{}:W.navigation,b=I.version?String(await J(()=>I.version(Z))):"";H={identity:[W.layout??"",$.buildId??"",O?.name??"",b].join("|"),prefetch:I.prefetch==="none"?"none":"intent"}}let T=await $6(l1(pQ.Provider,{value:D,children:l1(eQ,{children:[...Q,l1(this.root,{data:j,viewImportMap:$.viewImportMap,viewModules:$.viewModules,serverQueries:z,dictionarySink:V,rootLayout:G,key:"root"})]})}),{signal:F.signal,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:U});await T.allReady.catch(()=>{});let K=nQ(await new Response(T).text());return new Response(sQ(K,D,$.resolveIsland,Bun.env.NODE_ENV!=="production",H,O),{status:$.status,headers:X})}finally{clearTimeout(B),J(()=>this.completeStream(Z,z.summarize(F.signal.aborted)))}}async render($){let{req:Z,runInRequestScope:J,csrfTokenHMAC:W,currentPathName:Y,headers:j,i18n:z,params:X,pathname:G,serverQueries:Q,userAgent:V,noStream:F,noTheme:B,url:U,user:D,viewData:O,breadcrumbs:L,urlLocaleSegment:H,meta:T,isOgRequest:K,appId:I,features:b,staticView:S}=$,R=this.theme===!1||B||S?null:{cookie:this.theme.cookie??Z5,default:this.theme.default??null,value:DH(Z,this.theme.cookie??Z5)},w=H?PQ(G,[H]).pathname:G,N={kind:"view",data:{meta:T,pageData:{[w]:O},__csrf:W.toString("base64"),prefetchedData:{},i18n:z,auth:{user:D},routeManifest:this.clientRouteManifest,breadcrumbs:L,router:{urlLocaleSegment:H,pathname:Y,params:X,currentPath:G,searchParams:U.search,is404:!Y?!0:!1,domain:Z.domain?UH(Z):null},appId:I,features:b,theme:R,componentTree:[["404",[]],...this.componentTree],...this.staticRoutes.length>0?{staticRoutes:this.staticRoutes}:{}},head:{}},g=this.root,_=this.routeManifest[Y];return async(k)=>{let{bootstrapModules:M0=[],loaders:z3,getStyles:s1,viewImportMap:A1,cssManifest:i,ogMap:v,viewModules:t,clientEntry:S1,modulePreloadManifest:X3,assetBase:QZ,resolveIsland:r0,buildId:V1}=k,C$=S1?[]:M0,n1=(p)=>[p,`window.loaders=${z3}`,...S1?[`import(${JSON.stringify(S1.module)}).catch(function(e){setTimeout(function(){throw e})})`]:[]].join(";");if(K){let p=null,u0=null;for(let A of _??[])if(typeof v[A]==="function")u0=A,p=v[A];if(!p)return new Response("Not found",{status:404});let G3=Object.values(N.data.pageData)[0];try{await $6(l1(p,G3[u0]),{onError:()=>{}})}catch(A){let{fonts:e,...t1}=A.satoriOptions,Y6=await Promise.all(e.map((j6)=>{return BH(j6.name,j6.weight,j6.style).then((QV)=>({...j6,data:QV}))})),T2=new Headers(j);T2.set("Content-Type","image/png");let[jV,zV]=await Promise.all([GH(),a4("Rendering an OG image")]),XV=await jV(A.jsx,{...t1,fonts:Y6}),GV=await zV(Buffer.from(XV)).png({compressionLevel:0,effort:10}).toBuffer();return new Response(new Uint8Array(GV),{headers:T2})}return new Response("data")}if(S&&Y)return await this.renderStatic({req:Z,runInRequestScope:J,staticView:S,currentViews:_,data:N.data,serverQueries:Q,headers:j,getStyles:s1,viewImportMap:A1,viewModules:t,resolveIsland:r0,buildId:V1,status:200});if(S&&!Y&&this.notFound){let p=this.notFound.view;if(!A1[p])throw Error(`The not-found view "${p}" (route.view.notFound) was not found. It is a view path: a file at app/views/${p}.tsx.`);return await this.renderStatic({req:Z,runInRequestScope:J,staticView:S,currentViews:[p],data:N.data,serverQueries:Q,headers:j,getStyles:s1,viewImportMap:{...A1,"404":A1[p]},viewModules:t&&{...t,"404":t[p]},resolveIsland:r0,buildId:V1,status:$.refusedStatus??404})}if(N.data.cssManifest=i,N.data.modulePreloadManifest=X3??{},QZ&&QZ!=="/")N.data.assetBase=QZ;if(V1&&V1!=="dev")N.data.buildId=V1;let r=this.modulePreloadLinks({clientEntry:S1,modulePreloadManifest:X3,views:_??["404"],routeKey:Y??"404"}),P8=await s1(_??["404"]);N.data.prefetchedData=Q.snapshotResolved(),Q.markRenderStart();let A$=new AbortController,o1=setTimeout(()=>A$.abort(),$B),a1=C6(V)||F,BZ=Bun.env.NODE_ENV!=="production"&&!a1&&Y&&this.shellReporter.shouldObserve(Y)?IQ():null,S$=c5();try{let p=await $6(l1(eQ,{children:[...r,...P8,...R?[l1("script",{key:"theme-script",dangerouslySetInnerHTML:{__html:aG(i0({cookie:R.cookie,default:R.default}))}})]:[],l1(g,{data:N.data,viewImportMap:A1,viewModules:t,serverQueries:Q,dictionarySink:S$,key:"root"})]}),{bootstrapScriptContent:n1(`window.__GEMI_DATA__ = ${i0(N.data)}`),bootstrapModules:C$,signal:A$.signal,...a1?{progressiveChunkSize:Number.MAX_SAFE_INTEGER}:{},onError(u0){if(Bun.env.NODE_ENV!=="production")console.error(u0)}});if(p.allReady.catch(()=>{}).finally(()=>clearTimeout(o1)),a1)await p.allReady.catch(()=>{});return new Response(X7(p,Q,{onShell:a1?void 0:()=>Q.markShell(),onChunk:BZ?.onChunk,onClose:()=>J(()=>{if(this.completeStream(Z,Q.summarize(A$.signal.aborted)),BZ)this.shellReporter.report(Y,BZ.measure())})},S$),{status:!Y?$.refusedStatus??404:200,headers:j})}catch(p){if(clearTimeout(o1),Bun.env.NODE_ENV==="production")throw J(()=>this.completeStream(Z,Q.summarize(A$.signal.aborted))),p;let u0=await $6(l1("div"),{bootstrapScriptContent:n1(`window.error= ${i0(p.message)}; window.stack_trace=${i0(p.stack)};window.__GEMI_DATA__ = ${i0(N.data)}`),bootstrapModules:Bun.env.NODE_ENV==="development"?["/render-error.js",...C$]:C$});return new Response(X7(u0,Q,{onClose:()=>J(()=>this.completeStream(Z,Q.summarize(A$.signal.aborted)))}),{status:!Y?$.refusedStatus??404:200,headers:j})}}}viewRefusalStatus($,Z,J){if(b$(Z))return 404;if(Z?.kind===Z$){let W=Z.payload?.view?.status;return W===403||W===404?W:null}if(J$(Z)){if(!J.has(Z))this.hooks.onRequestFail($,Z);return console.error(Z),403}if(Z instanceof t0&&(Z.status===403||Z.status===404))return Z.status;return null}async handleViewRequest($,Z){let J=new URL($.url),W=J.pathname.endsWith(".json"),Y=J.pathname.endsWith(".og"),j=J.pathname.replace(".json","").replace(".og",""),[,z,...X]=j.split("/"),G=j,Q=null,V=null,F=M(c),B=t3(this.flatViewRoutes,j),U=F.isLocaleAware&&this.localeRouting==="prefix"&&!B?.route.middleware.includes(ZB);if(U&&F.supportedLocales.includes(z))G=`/${X.join("/")}`,Q=z,V=z;if(($.method==="GET"||$.method==="HEAD")&&!W&&!Y&&B===null&&J.pathname.endsWith("/")&&!J.pathname.startsWith("//")){let _=J.pathname.replace(/\/+$/,""),k=U&&F.supportedLocales.includes(_.slice(1));if(_&&!k)return new Response("",{status:301,headers:{Location:`${_}${J.search}`}})}if(U&&!Y&&V===null&&!(V===null&&B!==null)){let _=h5(z,F.supportedLocales,F.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 _=M(c).detectLocale(new C($,{},"view",G));if(V===null&&_!==F.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 O=[],L=[],H=null,T={},K=null,I=!1,b=!1,S=[],R,w=!1,N=!1;try{let _=t3(this.flatViewRoutes,G);if(V&&_?.route.middleware.includes(ZB))_=null;if(_){if(w=!0,H=_.routePath,T=_.params,O=_.route.exec,L=_.route.middleware,S=_.route.features,I=L.includes("no-stream"),b=L.includes(QH),R=_.route.static,N=_.route.segments.at(-1)?.viewPath==="FILE",W&&this.partialRendering){let k=$.headers.get(H5),M0=TQ({flatViewRoutes:this.flatViewRoutes,supportedLocales:M(c).supportedLocales,from:k,origin:J.origin,to:{segments:_.route.segments,params:T,search:J.search}});if(M0.startIndex>0)O=O.slice(M0.startIndex),K={from:k,carriedViews:M0.carriedViews}}}}catch(_){throw _}if(R&&W)return new Response("Not found",{status:404});let g=new C($,T,"view",H);return this.hooks.onRequestStart(g),await P.run(g,async()=>{let _=null,k=P.getStore(),M0=Z3.getStore(),z3=(v)=>Z3.run(M0,()=>P.runWith(k,v));k.serverQueries=new eZ(r3($));let s1=new Set;k.serverQueries.onQueryFail((v)=>{s1.add(v.error);try{z3(()=>Promise.resolve(this.hooks.onRequestFail(i,v.error)).catch(()=>{}))}catch{}});let A1=v5(N?{}:R??(H===null&&!W?this.notFound?.static:void 0));if(V){let v=V.replaceAll("/","");x$.setLocale(v,{cookie:A1.locale})}else if(F.isLocaleAware&&!U)k.setLocale(F.defaultLocale);else x$.setLocale(void 0,{cookie:A1.locale});let i=k.req;if(A1.session)Y8();try{let v=null;if(this.detectLocale&&!U&&M(c).isLocaleAware){let{supportedLocales:A,defaultLocale:e}=M(c),t1=await this.detectLocale(i,{supportedLocales:A,defaultLocale:e}),Y6=typeof t1==="string"?h5(t1,A,e):null;if(Y6)k.setLocale(Y6)}try{await M($$).runMiddleware(L)}catch(A){if(v=this.viewRefusalStatus(i,A,s1),v===null)throw A}if(v!==null||S.length>0&&!await this.passesFeatureGates(S))H=null,O=[],i.routePath="";let t=M(c),S1=t.isEnabled,X3=t.isLocaleAware,QZ=new C($,i.params),r0={defaultLocale:t.defaultLocale,timeZone:t.detectTimeZone(QZ)};if(X3){let A=null;if(V)A=V.replaceAll("/",""),k.setLocale(A);else if(!U)A=k.locale??t.defaultLocale;else A=t.detectLocale(QZ),k.setLocale(A);let e=S1?t.getPageTranslations(A,i.routePath):{};r0={...r0,supportedLocales:t.supportedLocales,currentLocale:A,dictionary:{[A]:e},defaultLocale:t.defaultLocale,...U?{}:{localeRouting:"off"}}}await p5(r0.currentLocale??"");let V1;try{V1=await Promise.all(O.map((A)=>A(i)))}catch(A){if(v=this.viewRefusalStatus(i,A,s1),v===null)throw A;H=null,O=[],i.routePath="",V1=[]}let C$=void 0;if(H===null){if(C$=await this.hooks.onNotFound(i,{status:v??404}),X3&&!U&&k.locale&&k.locale!==r0.currentLocale){let A=k.locale;r0={...r0,currentLocale:A,dictionary:{[A]:S1?t.getPageTranslations(A,i.routePath):{}}},await p5(A)}}if(this.defaultMeta&&!k.metadata.hasAllDefaultFields)k.metadata.applyDefaults(typeof this.defaultMeta==="function"?await this.defaultMeta(i):this.defaultMeta);if(this.translate!==void 0)k.metadata.applyTranslateDefault(this.translate);let{cookies:n1,headers:r}=k;if(v!==null)r.set("Cache-Control","no-store");_={data:V1,cookies:n1,headers:r,user:k.user,prefetchedData:k.serverQueries.snapshotResolved(),currentPathName:H,params:i.params,urlLocaleSegment:Q,meta:k.renderMeta(),appId:M(K5).id,features:await M(j$).forClient()};let{params:P8,user:A$}=_,o1={},a1={};for(let A of V1??[]){let[e,t1]=Object.entries(A)?.[0]??[];if(!e||!t1)continue;a1[`${e}:${H}`]=t1.breadcrumb,o1[e]=t1}let BZ=H===null&&this.notFound&&!W?this.notFound.static:void 0;if(BZ&&C$)o1["404"]=C$;let S$=o1.FILE;if(S$){try{await this.onRequestEnd(i,{mintSession:!1})}catch(e){jZ.error(e?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(e)})}let A;if(S$ instanceof Response)A=z8(S$,r,n1);else{for(let e of n1)r.append("Set-Cookie",e.toString());A=await f8(S$,r)}return rQ(A,H)}if(W){r.set("Content-Type","application/x-ndjson; charset=utf-8"),r.append("Vary",H5),n1.forEach((e)=>r.append("Set-Cookie",e.toString())),g5(r,H),await this.hooks.onRequestEnd(i);let A={meta:K&&!k.metadata.touched?null:_.meta,data:{[G]:o1},breadcrumbs:a1,prefetchedData:k.serverQueries.snapshotResolved(),i18n:r0,features:_.features,is404:!H,appId:_.appId,partial:K};return new Response(xQ(A,k.serverQueries,void 0,({aborted:e})=>z3(()=>this.completeStream(i,k.serverQueries.summarize(e)))),{headers:r})}r.set("Content-Type","text/html; charset=utf-8");let p=H?R:BZ,u0=Boolean(p),G3=v5(p);if(!I&&!u0)r.append("Vary","User-Agent");if(!u0||G3.session)Y8();for(let A of n1)r.append("Set-Cookie",A.toString());if(!u0||G3.csrf){let A=Bun.CSRF.generate(process.env.SECRET);r.append("Set-Cookie",`csrf_token=${A}; HttpOnly; Secure; SameSite=Strict; Expires=${new Date(Date.now()+86400000).toUTCString()}`)}try{await this.onRequestEnd(i,{mintSession:!u0||G3.session})}catch(A){jZ.error(A?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(A)})}if(u0&&(H||!w))tQ(r,p);return g5(r,H),await this.render({req:i,runInRequestScope:z3,csrfTokenHMAC:Buffer.from(""),currentPathName:H,headers:r,i18n:r0,params:P8,pathname:J.pathname,serverQueries:k.serverQueries,userAgent:$.headers.get("user-agent"),noStream:I,noTheme:b,url:J,user:A$,viewData:o1,breadcrumbs:a1,urlLocaleSegment:Q,meta:_.meta,appId:_.appId,features:_.features,isOgRequest:Y,staticView:p,refusedStatus:v??void 0})}catch(v){if(v.kind===Z$){let t=W?OH(v.payload.viewData??v.payload.api):m5(v.payload.view);for(let S1 of k.cookies)t.headers.append("Set-Cookie",S1.toString());return t}if(!s1.has(v))this.hooks.onRequestFail(i,v);if(J$(v))return console.error(v),W?$3():m5(T5());if(v instanceof t0&&v.status===403)return W?$3():m5(T5());throw v}},Z)}}function DH($,Z){let J=$.cookies?.get(Z);return oG(J)?J:null}function u5(){let $=JSON.stringify({error:W$("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 jB extends C0{routes={"/api-routes":this.get(()=>{let $=M(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 $=M(Z6).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 LH=new Set([e1,"cookie","content-type","content-length","transfer-encoding","connection","host","user-agent","forwarded"]),HH=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,MH=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/;function KH($,Z,J,W){for(let[Y,j]of Object.entries(J.headers??{})){if(j===void 0||j===null)continue;let z=Y.toLowerCase();if(LH.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===e1)throw Error(`dispatchAs: credentials may not set the "${e1}" cookie. The access token stays the initiator's.`);if(!HH.test(Y)||!MH.test(j))throw Error(`dispatchAs: "${Y}" is not a cookie a Cookie header can carry.`);Z.push(`${Y}=${j}`)}}function TH($,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 JB($){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 z8($,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 PH(){return Bun.env.NODE_ENV==="development"}class X8{static token="router.api";flatRoutes={};onRequestStart;onRequestEnd;onRequestFail;constructor($){let Z=lG();this.onRequestStart=$.onRequestStart??Z.onRequestStart,this.onRequestEnd=$.onRequestEnd??Z.onRequestEnd,this.onRequestFail=$.onRequestFail??Z.onRequestFail,this.flatRoutes=rW({"/":$.rootRouter,"/auth":iW,"/__gemi__/services/i18n":sW,"/__gemi__/services/image":aW,...PH()?{"/__gemi__/services/logs":tW,"/__gemi__/debug":jB}:{}})}getRouteHandlerAndParams($){let Z=new URL($.url),J=YB(Z.pathname),W={},Y;for(let[j]of Object.entries(this.flatRoutes))try{let z=new URLPattern({pathname:j});if(z.test({pathname:J})){Y=j,W=z.exec({pathname:J})?.pathname.groups;break}}catch(z){console.error(z)}return{params:W,path:Y}}async runRouteMiddleware($,Z){let W=this.flatRoutes[$][Z.rawRequest.method].middleware;try{await M($$).runMiddleware(W)}catch(Y){if(Y.kind===Z$)return JB(Y.payload.api);else{if(b$(Y))return u5();if(this.onRequestFail(Z,Y),console.error(Y),J$(Y))return $3();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===Z$)return JB(j.payload.api);if(b$(j))return u5();if(this.onRequestFail(J.req,j),console.error(j),J$(j))return $3();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){jZ.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||!Y[$.method])return new Response(JSON.stringify({error:W$("not_found","Not found",404)}),{status:404});let j=new C($,J,"api",W);if(!this.isFrameworkRoute(W))this.onRequestStart(j);return await P.run(j,async()=>{let z=P.getStore(),X=!1,G=async()=>{X=!0,await this.endRequest(z,j,W)};try{let Q=M(c);if(Q.isEnabled){let O=Q.detectLocale(j);z.setLocale(O)}z.setRequest(j),M($$).applyDefaultBodyLimit($);let V=await this.runRouteMiddleware(W,j);if(V instanceof Response){let O=z8(V,z.headers,z.cookies);return await G(),O}let F=await this.getRouteData(W),B=z.headers,U=z.cookies;if(F instanceof Response){let O=z8(F,B,U);if(this.isOpenEndedBody($,O)){let L=TH(O,()=>this.endRequest(z,j,W));return X=!0,L}return await G(),O}let D=(r1(F)?F:F1.json(F)).toResponse(B,U);return await G(),D}catch(Q){if(!X)try{await G()}catch(V){console.error(V)}throw Q}},Z)}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,V=[],F=G?null:$.cookies.get(e1);if(F)V.push(`${e1}=${F}`);if(Y?.credentials)KH(Q,V,Y.credentials,G!==void 0);if(V.length>0)Q.set("Cookie",V.join("; "));let B=G?null:$.headers.get(e1);if(B)Q.set(e1,B);let U=$.headers.get("User-Agent");if(U)Q.set("User-Agent",U);let D;if(W instanceof FormData)D=W;else if(W!==void 0)Q.set("Content-Type","application/json"),D=JSON.stringify(W);let O=new Request(z,{method:Z,headers:Q,body:D,...Y?.signal?{signal:Y.signal}:{}});if(WB(O,LZ($),G?.grant,Y?.progress),$.domain)J3(O,$.domain);let L=G?{user:G.user}:void 0;return P.exit(()=>F6.exit(()=>this.handleApiRequest(O,L)))}}import{timingSafeEqual as NH}from"crypto";var B8="",s5="*",_H=60000,IH=1e4,G8=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,Q8=16,l5=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,i5="x-forwarded-host";function XB($){return $.startsWith(":")}function J6($,Z){if($===null)return!1;let J=Buffer.from($,"utf8"),W=Buffer.from(Z,"utf8");return J.length===W.length&&NH(J,W)}function xH($){if(!$)return[];if($===!0)return[{header:i5,clientIpHeader:null,secret:null}];let Z=Array.isArray($)?$:[$],J=Array.isArray($)?null:i5;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 CH($){if(!$||$===!0)return;if(!Array.isArray($)){zB($,"route.domains.trustProxy",i5);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.`);zB(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 zB($,Z,J){let{hostHeader:W,clientIpHeader:Y,secret:j}=$;if(W!==void 0&&(typeof W!=="string"||!l5.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"||!l5.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"||!l5.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 I1($){if(!$)return null;try{return new URL(`http://${$.trim()}`).hostname.toLowerCase().replace(/\.$/,"")||null}catch{return null}}function AH($){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 SH($){let Z=I1($.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.`);CH($.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),XB(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 n5{root;devHosts;hostTrusts;fixed=new Map;param=null;custom;cacheTtlMs;cache=new Map;inFlight=new Map;askSecret;proxySecretHeaders;constructor($){SH($),this.root=I1($.root),this.devHosts=GB($.devHosts),this.hostTrusts=xH($.trustProxy);for(let Z of $.groups??[])if(XB(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??_H,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||J6($.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:k$(J)}applyClientIp($){let Z=this.trustedClientIp($);if(!Z)return;$.headers.set("x-forwarded-for",Z),$.headers.delete("x-real-ip")}hostOf($){return I1(this.forwardedHost($))??I1(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&&I1(Y)?AH(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:s5,params:{},custom:!0};return null}async allows($,Z){let J=I1($);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>=IH)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=I1($);if(Z)this.cache.delete(Z)}}}var EH={kind:"none"};function FA($){let Z=($??"").trim().toLowerCase();if(Z===""||Z==="false"||Z==="off"||Z==="0")return EH;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 UA($,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:k$(z))??Z}if(W)$.set("x-forwarded-for",W);else $.delete("x-forwarded-for")}var QB=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,BB=16;function OA($){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(!QB.test(Z))throw Error(`GEMI_CLIENT_IP_HEADER must be a single header name, e.g. "x-azure-clientip". Got ${JSON.stringify(Z)}.`);if(!QB.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<BB)throw Error(`GEMI_PROXY_SECRET must be at least ${BB} characters. A guessable one lets any client name its own address.`);return{header:Z.toLowerCase(),secretHeader:J.toLowerCase(),secret:W}}function VB($,Z){if(!J6($.get(Z.secretHeader),Z.secret))return null;let J=$.get(Z.header)?.split(",")[0];return J===void 0?null:k$(J)}var bH="/__gemi__/domains/ask";class B1{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 n5(J);let W=(Y)=>({api:Y.api?new X8({...Z.api,...Y.api}):$.api,view:Y.view?new Z6({...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(s5,W(J.custom.fallback));this.staticFilesVary=this.viewDispatchers().some((Y)=>Y.publicFiles!==$.view.publicFiles||Y.assetRoutes!==$.view.assetRoutes)}async staticFiles($){let Z=(this.staticFilesVary?await this.route($):null)?.view??this.dispatchers(null).view;return{publicFiles:Z.publicFiles,assetRoutes:Z.assetRoutes}}applyClientIp($){let Z=this.clientIpTrust;if(Z)o5($,Z.secretHeader);let J=this.resolver?.trustedClientIp($)??(Z?VB($.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)o5($,J);let Z=W8($)??await this.resolver.resolve($);if(!Z)return null;return J3($,Z),this.dispatchers(Z)}async ask($){if(!this.resolver?.askSecret||$.method!=="GET")return null;let Z=new URL($.url);if(Z.pathname!==bH)return null;if(!J6(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 Y3($){let Z=new Date($??0).getTime();return Number.isFinite(Z)?Z:0}var FB=600000;function UB($,Z){return[N6($,Z),N6($,Z-1)]}class E{static token="auth";config;provider;constructor($={},Z=new F7){c9($.oauthProviders),this.config={...N1(d9($),$),emailCode:z7($.emailCode),passwordLimits:j7($.passwordLimits)},this.provider=Z}async oauthProvider($){return await PZ(this.config.oauthProviders,$)}async oauthProviderNames(){return await YY(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=M().bound(B1)?M(B1).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"?M(B1).resolver?.root:I1(Z);if(!J)throw Error('`auth.cookieDomain` is "root", but `route.domains` is not configured.');let W=$.domain?.host??I1(new URL($.rawRequest.url).host);return W===J||W?.endsWith(`.${J}`)?J:void 0}async getSession($,Z){if(!$)return null;if(!t8($))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=Y3(J.expiresAt),j=Y3(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/FB),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=N6($,j),V=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:V,userAgent:Z,...this.freshLifetime(Y)}),!0}))z=Q}if(!z){for(let Q of UB($,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(t8($)||!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()/FB),W=UB($,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 C;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 C,J=$.id??(await this.userProvider.findUserByEmailAddress($.email,!1))?.id;if(!J)throw new R$;let W=Bun.env.NODE_ENV==="development"?"local":Z.headers.get("User-Agent"),Y=R9(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:g9(Z),G=_6("link",$,j),Q=_6("pin",$,X);if(J===1)await this.userProvider.deleteMagicLinkToken($);else{let V=Math.max(W,Y)*60000,B=(await this.userProvider.listMagicLinkTokensByEmail($,J-1)).filter((U)=>Y3(U.createdAt)+V>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)=>Y3(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 h9(Q.id,Y3(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(Y3(W.createdAt)+this.config.emailCode.linkExpiresInMinutes*60000<=Date.now())return!1;return await this.claimOneTimeCode($,W.id)}}class q0 extends m{static getFacadeAccessor(){return E}static async user(){let $=await q0.userOrNull();if($)return $;throw new R$({redirectTo:O6(P.getStore()?.req,this.getFacadeRoot().config.signInPath)})}static async userOrNull(){let $=P.getStore();if($?.user)return $.user;let Z=await Q6(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 HZ}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($)}}class V8{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 eZ(r3(J.req.rawRequest)),J.serverQueries.ensure($,Z,"prefetch")}static async instant($,...Z){let J=V8.ensure($,Z[0]);if(await J.promise,J.status==="rejected")throw J.error;return J.data}static prefetch($,...Z){V8.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 eZ(r3($.req.rawRequest)),$.serverQueries.muteDiscoveryHints()}}function RH($){return(Array.isArray($)?$:String($).split("/")).map((J)=>encodeURIComponent(String(J))).join("/")}function a5($,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==="*"?RH(z):encodeURIComponent(String(z))}`});return`${F8}${J==="/"?"":J}`||F8}var OB=new Map;function DB($,Z){let J=OB.get($);if(!J)J=new URLPattern({pathname:`${F8}${$==="/"?"":$}`}),OB.set($,J);let W;try{W=new URL(Z,"http://localhost").pathname}catch{return null}let Y=J.exec({pathname:W})?.pathname.groups;if(!Y)return null;let j={};for(let[z,X]of Object.entries(Y)){if(X===void 0)continue;try{j[z]=decodeURIComponent(X)}catch{return null}}return 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=kH(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 kH($){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 HB{static origin($){return t5($)}static absolute($,...Z){return`${ZZ()}${O0(String($),Z[0]??{})}`}static relative($,...Z){return O0(String($),Z[0]??{})}static forDomain($,Z,...J){let W=M(B1).resolver;if(!W)throw Error("`Url.forDomain` needs `route.domains` to be configured.");let Y=P.getStore()?.req?.rawRequest,j=Y?W.publicOrigin(Y):ZZ();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},$,O0(String(Z),J[0]??{}))}static api($,...Z){return a5(String($),Z[0]??{})}static apiAbsolute($,...Z){return`${t5()}${a5(String($),Z[0]??{})}`}static matchApi($,Z){return DB(String($),Z)}}class MB{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 wH={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 i1 extends m{static getFacadeAccessor(){return zZ}static get client(){return this.getFacadeRoot().client}static get($){return i1.client.get($)}static set($,Z){return i1.client.set($,Z)}static del(...$){return i1.client.del(...$)}static exists($){return i1.client.exists($)}static incr($){return i1.client.incr($)}static expire($,Z){return i1.client.expire($,Z)}static ttl($){return i1.client.ttl($)}}function VS($){return $}function KB(){return{store:"memory",ttl:null}}class r5{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 fH="500";class e5{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=`${qH(this.prefix)}*`,J="0";do{let W=await $.send("SCAN",[J,"MATCH",Z,"COUNT",fH]),[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 $=M(),Z=$.bound(zZ)?$.make(zZ).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 qH($){return $.replace(/[*?[\]\\^-]/g,(Z)=>`\\${Z}`)}var vH="k:",TB="tag:",gH="t:";class $2{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 Z2 extends $2{options;static token="cache";config;builtStore;inflight=new Map;constructor($={},Z={}){super();this.options=Z;if(this.config=N1(KB(),$),this.config.ttl!==null&&this.config.ttl!==void 0)XZ(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 NB(this,Z)}async flush(){await this.store.flush()}async storeKey($){return vH+_B($)}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=TB+Z,W=await this.store.get(J);if(W!==null)return W;let Y=PB();return await this.store.set(J,Y,null),Y}))}async flushTags($){await Promise.all($.map((Z)=>this.store.set(TB+Z,PB(),null)))}ttlMs($){let Z=$===void 0?this.config.ttl:$;return Z===null||Z===void 0?null:XZ(Z)}buildStore(){let{store:$}=this.config;if($===void 0||$==="memory")return new r5(this.config.memory);if($==="redis"){let Z=this.options.application;return new e5({...this.config.redis,client:Z?{send:(J,W)=>Z.make(zZ).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 NB extends $2{manager;tagNames;constructor($,Z){super();this.manager=$;this.tagNames=Z}async flush(){await this.manager.flushTags([...this.tagNames])}async storeKey($){_B($);let Z=await this.manager.tagVersions([...this.tagNames]);return`${gH}${Z.join(",")}:${$}`}}function _B($){if(typeof $!=="string"||$==="")throw TypeError(`A cache key is a non-empty string; got ${JSON.stringify($)}.`);return $}function PB(){let $=new Uint8Array(9);return crypto.getRandomValues($),Array.from($,(Z)=>Z.toString(16).padStart(2,"0")).join("")}class IB extends m{static getFacadeAccessor(){return Z2}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 xB extends m{static getFacadeAccessor(){return O1}static consume($,Z={}){return this.getFacadeRoot().consume($,Z)}static enforce($,Z={},J){return this.getFacadeRoot().enforce($,Z,J)}}class AB extends m{static getFacadeAccessor(){return CB}static run($,Z,J){return this.getFacadeRoot().run($,Z,J)}static acquire($,Z={}){return this.getFacadeRoot().acquire($,Z)}}class EB extends m{static getFacadeAccessor(){return SB}static encrypt($){return this.getFacadeRoot().encrypt($)}static decrypt($){return this.getFacadeRoot().decrypt($)}static needsReencryption($){return this.getFacadeRoot().needsReencryption($)}}class bB extends m{static getFacadeAccessor(){return a3}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()}}function mS($){return $}function RB(){return{driver:"memory",pollInterval:30000,maxSubscriptions:1e4,batchSize:100,keepaliveInterval:5000}}function U8($){let Z=new URLSearchParams;for(let[J,W]of $)Z.append(J,String(W));return Z.toString()}function J2($){let Z=new Map;if(!$)return Z;let J;try{J=new URLSearchParams($)}catch{return Z}for(let[W,Y]of J){let j=Number(Y);if(Y!==""&&Number.isSafeInteger(j)&&j>=0)Z.set(W,j)}return Z}var{SQL:yH}=globalThis.Bun;function mH(){return Bun.semver.satisfies(Bun.version,">=1.4.0")}var hH=async($)=>{let Z=new yH($,{max:1,idleTimeout:0,maxLifetime:0});return{listen:(J,W,Y)=>Z.listen(J,W,Y),close:()=>Z.close({timeout:1})}},pH=async($)=>{let Z;try{Z=(await import("./chunk-qy678j5z.js")).default}catch(W){throw Error("The change feed's database driver needs a Postgres client that can LISTEN: Bun 1.4 or later, or the `postgres` package (bun add postgres).",{cause:W})}let J=Z($,{max:1,idle_timeout:0,max_lifetime:null,fetch_types:!1,onnotice:()=>{}});return{listen:(W,Y,j)=>J.listen(W,Y,j),close:()=>J.end({timeout:1}).catch(()=>{})}},kB=($)=>mH()?hH($):pH($);var cH=/^[A-Za-z_][A-Za-z0-9_]*$/;class W2{headsTable;entriesTable;notifyChannel;sql;dialect;connection;url;retain;listener;sqliteTurn=Promise.resolve();constructor($,Z={}){if($.dialect!=="postgres"&&$.dialect!=="sqlite")throw Error(`The change feed's database driver supports Postgres and SQLite, not ${$.dialect}.`);let J=Z.headsTable??"gemi_change_heads",W=Z.entriesTable??"gemi_changes",Y=Z.notifyChannel??"gemi_changes";for(let z of[J,W,Y])if(!cH.test(z))throw Error(`"${z}" is not a plain identifier. Use letters, digits and underscores.`);let j=Z.retain??1000;if(!Number.isInteger(j)||j<1)throw Error(`The change feed's retain must be a whole number, 1 or more; got ${j}.`);this.headsTable=J,this.entriesTable=W,this.notifyChannel=Y,this.sql=$.sql,this.dialect=$.dialect,this.connection=$.name,this.url=$.url,this.retain=j,this.listener=Z.listener??kB}async createTable(){for(let $ of dH(this.headsTable,this.entriesTable))await this.sql.unsafe($)}joinsTransaction(){return this.transaction()!==void 0}publish($,Z){let J=this.transaction();if(!J){let Y=()=>this.sql.begin((z)=>this.append(z,$,Z));if(this.dialect!=="sqlite")return Y();let j=this.sqliteTurn.then(Y);return this.sqliteTurn=j.catch(()=>{}),j}let W=this.append(J,$,Z);return wB(W),W}async append($,Z,J){let W=$.unsafe(`"${this.headsTable}"`),Y=$.unsafe(`"${this.entriesTable}"`),[j]=await $`
|
|
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 rL($){return`'sha256-${lL("sha256").update($).digest("base64")}'`}var S5,E5=new Map;function eL(){if(S5===void 0){let $=R5(b5(),"dist","server",nL);S5=dQ($)?JSON.parse(iL($,"utf8")):null}return S5??null}async function k5($){aL($);let Z=Bun.env.NODE_ENV==="production";if(Z){let j=eL()?.[$];if(j!==void 0)return j;let z=E5.get($);if(z)return z}let J=R5(b5(),"app"),W=tL(J,$);if(!W)throw Error(`The document script "${$}" was not found. It is a file at app/views/${$}${uQ}.ts (or .js).`);if(!Z)return cQ(W);let Y=cQ(W);return E5.set($,Y),Y.catch(()=>E5.delete($)),Y}async function wx($){return rL(await k5($))}var $H="gemi-islands",ZH="gemi-island-i18n",JH="gemi-island-queries",px=`'sha256-${iQ("sha256").update(q5).digest("base64")}'`;function w5($,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,"<"),cx=`'sha256-${iQ("sha256").update(A5).digest("base64")}'`,WH='await import("/refresh.js").catch(()=>{});await import("/@vite/client").catch(()=>{});',YH="gemi-static";function sQ($,Z,J,W,Y,j){let z=new Set,X=[];if(J)X=Z.islands.map((L)=>{let H=L.module?J(L.module):void 0;if(!H)return console.error(`[gemi] island ${L.module??"(unknown module)"}: no client build entry. Declare it as island(() => import("./Component")) so gemi's Vite plugin builds it.`),null;if(L.load==="eager"){for(let T of H.preload)z.add(T);if(L.preloadDynamic)for(let T of H.dynamicPreload??[])z.add(T)}return{s:H.src,e:L.export,l:L.load}});let G=X.some((L)=>L!==null),Q=j?`<script type="module" ${lQ}="${f5(j.name)}">${j.source}</script>`:"";if(!G&&!Y)return w5($,"</head>",Q,!1);let F=(Y?`<meta name="${YH}" content="${f5(Y.identity)}"${Y.prefetch==="none"?' data-prefetch="none"':""}/>`:"")+[...z].map((L)=>`<link rel="modulepreload" href="${f5(L)}"/>`).join("")+Q,B=Y?A5:q5,U=G?gQ(Z):void 0,D=G?yQ(Z):void 0,O=(G?`<script type="application/json" id="${$H}">${i0({i:X})}</script>`:"")+(U?`<script type="application/json" id="${ZH}">${i0(U)}</script>`:"")+(D?`<script type="application/json" id="${JH}">${i0(D)}</script>`:"")+`<script type="module">${W?WH+B:B}</script>`;return w5(w5($,"</head>",F,!1),"</body>",O,!0)}function jH($,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 nQ($){let Z=`<template ${hQ}="`;for(let J=$.lastIndexOf(Z);J!==-1;J=$.lastIndexOf(Z)){let W=jH($,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=`<${e3} ${mQ}="${j}" style="display:contents"></${e3}>`;$=$.split(G).join(`<${e3} style="display:contents">${X}</${e3}>`)}return $}function v5($){if(!$)return{locale:!0,session:!0,csrf:!0};return{locale:!1,session:$.session===!0,csrf:$.csrf===!0}}function tQ($,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 zH($){let Z=$.headers.get("Cache-Control")?.toLowerCase()??"";return/(^|[\s,])(public|s-maxage)\b/.test(Z)}var oQ=new Set,XH=new Set(["public","private","s-maxage","proxy-revalidate"]);function g5($,Z){let J=$.get("Cache-Control");if(!J||$.getSetCookie().length===0)return;if(!/(^|[\s,])(public|s-maxage)\b/i.test(J))return;let Y=["private",...J.split(",").map((j)=>j.trim()).filter((j)=>{let z=j.split("=")[0].trim().toLowerCase();return z!==""&&!XH.has(z)})].join(", ");if(Bun.env.NODE_ENV!=="production"&&!oQ.has(Z)){oQ.add(Z);let j=[...new Set($.getSetCookie().map((z)=>z.split("=")[0]))];console.warn(`[gemi] The view "${Z??""}" sets cookies (${j.join(", ")}) on a response with Cache-Control "${J}", so it was sent "${Y}" 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",Y)}var aQ=new Set;function rQ($,Z){if(!zH($)||$.headers.getSetCookie().length===0)return $;if(Bun.env.NODE_ENV!=="production"&&!aQ.has(Z))aQ.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 GH=async()=>(await import("./chunk-1mpwzjxa.js")).default,y5,$6=async(...$)=>{return y5??=import("react-dom/server.browser").catch((Z)=>{throw y5=void 0,Z}),(await y5).renderToReadableStream(...$)},$B=1e4,ZB="no-locale",QH="no-theme";async function BH($,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 d5="/assets";function VH($){return $===d5||$.startsWith(`${d5}/`)}function FH($){let Z=$.filter(VH);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 "${d5}" 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 UH($){let Z=M(B1).resolver;return{...$.domain,root:Z.root,origin:Z.publicOrigin($.rawRequest)}}function m5($){let{status:Z=400,error:J,body:W,...Y}=$;return new Response(W??J?.message,{...Y,status:Z})}function OH($){let{status:Z=400,data:J,directive:W,headers:Y}=$;return new Response(JSON.stringify({data:J,directive:W}),{headers:Y,status:Z})}class Z6{static token="router.view";flatViewRoutes={};routeManifest={};clientRouteManifest={};componentTree=[];flatComponentTree=[];requiredViews={};staticRoutes=[];root=null;shellReporter=_Q();preloadCache=new WeakMap;hooks;partialRendering;localeRouting;detectLocale;theme;defaultMeta;notFound;publicFiles;assetRoutes;translate;constructor($,Z={}){let J=iG();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.translate=$.translate,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":yG(Z)};if(this.requiredViews=Object.fromEntries(vG(Z).map(({view:Y,requiredBy:j})=>[Y,j])),this.flatViewRoutes=r4(W),!this.assetRoutes)FH(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=M(j$);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)=>{jZ.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 V of J?.[Q]??[])G.add(V);return[...G].map((Q)=>l1("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 V=c5(),F=new AbortController,B=setTimeout(()=>F.abort(),$B),U=(O)=>{if(Bun.env.NODE_ENV!=="production")console.error(O)},D=vQ(async(O,L)=>{let H=await $6(O,{signal:F.signal,identifierPrefix:L,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:U});return await H.allReady.catch(()=>{}),await new Response(H).text()},{currentLocale:j?.i18n?.currentLocale,defaultLocale:j?.i18n?.defaultLocale,timeZone:j?.i18n?.timeZone},z);try{let O,L=typeof W.script==="function"?await J(()=>W.script(Z)):W.script;if(L)O={name:L,source:await k5(L)};let H;if(W.navigation){let I=W.navigation===!0?{}:W.navigation,b=I.version?String(await J(()=>I.version(Z))):"";H={identity:[W.layout??"",$.buildId??"",O?.name??"",b].join("|"),prefetch:I.prefetch==="none"?"none":"intent"}}let T=await $6(l1(pQ.Provider,{value:D,children:l1(eQ,{children:[...Q,l1(this.root,{data:j,viewImportMap:$.viewImportMap,viewModules:$.viewModules,serverQueries:z,dictionarySink:V,rootLayout:G,key:"root"})]})}),{signal:F.signal,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:U});await T.allReady.catch(()=>{});let K=nQ(await new Response(T).text());return new Response(sQ(K,D,$.resolveIsland,Bun.env.NODE_ENV!=="production",H,O),{status:$.status,headers:X})}finally{clearTimeout(B),J(()=>this.completeStream(Z,z.summarize(F.signal.aborted)))}}async render($){let{req:Z,runInRequestScope:J,csrfTokenHMAC:W,currentPathName:Y,headers:j,i18n:z,params:X,pathname:G,serverQueries:Q,userAgent:V,noStream:F,noTheme:B,url:U,user:D,viewData:O,breadcrumbs:L,urlLocaleSegment:H,meta:T,isOgRequest:K,appId:I,features:b,staticView:S}=$,R=this.theme===!1||B||S?null:{cookie:this.theme.cookie??Z5,default:this.theme.default??null,value:DH(Z,this.theme.cookie??Z5)},w=H?PQ(G,[H]).pathname:G,N={kind:"view",data:{meta:T,pageData:{[w]:O},__csrf:W.toString("base64"),prefetchedData:{},i18n:z,auth:{user:D},routeManifest:this.clientRouteManifest,breadcrumbs:L,router:{urlLocaleSegment:H,pathname:Y,params:X,currentPath:G,searchParams:U.search,is404:!Y?!0:!1,domain:Z.domain?UH(Z):null},appId:I,features:b,theme:R,componentTree:[["404",[]],...this.componentTree],...this.staticRoutes.length>0?{staticRoutes:this.staticRoutes}:{}},head:{}},g=this.root,_=this.routeManifest[Y];return async(k)=>{let{bootstrapModules:M0=[],loaders:z3,getStyles:s1,viewImportMap:A1,cssManifest:i,ogMap:v,viewModules:t,clientEntry:S1,modulePreloadManifest:X3,assetBase:QZ,resolveIsland:r0,buildId:V1}=k,C$=S1?[]:M0,n1=(p)=>[p,`window.loaders=${z3}`,...S1?[`import(${JSON.stringify(S1.module)}).catch(function(e){setTimeout(function(){throw e})})`]:[]].join(";");if(K){let p=null,u0=null;for(let A of _??[])if(typeof v[A]==="function")u0=A,p=v[A];if(!p)return new Response("Not found",{status:404});let G3=Object.values(N.data.pageData)[0];try{await $6(l1(p,G3[u0]),{onError:()=>{}})}catch(A){let{fonts:e,...t1}=A.satoriOptions,Y6=await Promise.all(e.map((j6)=>{return BH(j6.name,j6.weight,j6.style).then((QV)=>({...j6,data:QV}))})),T2=new Headers(j);T2.set("Content-Type","image/png");let[jV,zV]=await Promise.all([GH(),a4("Rendering an OG image")]),XV=await jV(A.jsx,{...t1,fonts:Y6}),GV=await zV(Buffer.from(XV)).png({compressionLevel:0,effort:10}).toBuffer();return new Response(new Uint8Array(GV),{headers:T2})}return new Response("data")}if(S&&Y)return await this.renderStatic({req:Z,runInRequestScope:J,staticView:S,currentViews:_,data:N.data,serverQueries:Q,headers:j,getStyles:s1,viewImportMap:A1,viewModules:t,resolveIsland:r0,buildId:V1,status:200});if(S&&!Y&&this.notFound){let p=this.notFound.view;if(!A1[p])throw Error(`The not-found view "${p}" (route.view.notFound) was not found. It is a view path: a file at app/views/${p}.tsx.`);return await this.renderStatic({req:Z,runInRequestScope:J,staticView:S,currentViews:[p],data:N.data,serverQueries:Q,headers:j,getStyles:s1,viewImportMap:{...A1,"404":A1[p]},viewModules:t&&{...t,"404":t[p]},resolveIsland:r0,buildId:V1,status:$.refusedStatus??404})}if(N.data.cssManifest=i,N.data.modulePreloadManifest=X3??{},QZ&&QZ!=="/")N.data.assetBase=QZ;if(V1&&V1!=="dev")N.data.buildId=V1;let r=this.modulePreloadLinks({clientEntry:S1,modulePreloadManifest:X3,views:_??["404"],routeKey:Y??"404"}),P8=await s1(_??["404"]);N.data.prefetchedData=Q.snapshotResolved(),Q.markRenderStart();let A$=new AbortController,o1=setTimeout(()=>A$.abort(),$B),a1=C6(V)||F,BZ=Bun.env.NODE_ENV!=="production"&&!a1&&Y&&this.shellReporter.shouldObserve(Y)?IQ():null,S$=c5();try{let p=await $6(l1(eQ,{children:[...r,...P8,...R?[l1("script",{key:"theme-script",dangerouslySetInnerHTML:{__html:aG(i0({cookie:R.cookie,default:R.default}))}})]:[],l1(g,{data:N.data,viewImportMap:A1,viewModules:t,serverQueries:Q,dictionarySink:S$,key:"root"})]}),{bootstrapScriptContent:n1(`window.__GEMI_DATA__ = ${i0(N.data)}`),bootstrapModules:C$,signal:A$.signal,...a1?{progressiveChunkSize:Number.MAX_SAFE_INTEGER}:{},onError(u0){if(Bun.env.NODE_ENV!=="production")console.error(u0)}});if(p.allReady.catch(()=>{}).finally(()=>clearTimeout(o1)),a1)await p.allReady.catch(()=>{});return new Response(X7(p,Q,{onShell:a1?void 0:()=>Q.markShell(),onChunk:BZ?.onChunk,onClose:()=>J(()=>{if(this.completeStream(Z,Q.summarize(A$.signal.aborted)),BZ)this.shellReporter.report(Y,BZ.measure())})},S$),{status:!Y?$.refusedStatus??404:200,headers:j})}catch(p){if(clearTimeout(o1),Bun.env.NODE_ENV==="production")throw J(()=>this.completeStream(Z,Q.summarize(A$.signal.aborted))),p;let u0=await $6(l1("div"),{bootstrapScriptContent:n1(`window.error= ${i0(p.message)}; window.stack_trace=${i0(p.stack)};window.__GEMI_DATA__ = ${i0(N.data)}`),bootstrapModules:Bun.env.NODE_ENV==="development"?["/render-error.js",...C$]:C$});return new Response(X7(u0,Q,{onClose:()=>J(()=>this.completeStream(Z,Q.summarize(A$.signal.aborted)))}),{status:!Y?$.refusedStatus??404:200,headers:j})}}}viewRefusalStatus($,Z,J){if(b$(Z))return 404;if(Z?.kind===Z$){let W=Z.payload?.view?.status;return W===403||W===404?W:null}if(J$(Z)){if(!J.has(Z))this.hooks.onRequestFail($,Z);return console.error(Z),403}if(Z instanceof t0&&(Z.status===403||Z.status===404))return Z.status;return null}async handleViewRequest($,Z){let J=new URL($.url),W=J.pathname.endsWith(".json"),Y=J.pathname.endsWith(".og"),j=J.pathname.replace(".json","").replace(".og",""),[,z,...X]=j.split("/"),G=j,Q=null,V=null,F=M(c),B=t3(this.flatViewRoutes,j),U=F.isLocaleAware&&this.localeRouting==="prefix"&&!B?.route.middleware.includes(ZB);if(U&&F.supportedLocales.includes(z))G=`/${X.join("/")}`,Q=z,V=z;if(($.method==="GET"||$.method==="HEAD")&&!W&&!Y&&B===null&&J.pathname.endsWith("/")&&!J.pathname.startsWith("//")){let _=J.pathname.replace(/\/+$/,""),k=U&&F.supportedLocales.includes(_.slice(1));if(_&&!k)return new Response("",{status:301,headers:{Location:`${_}${J.search}`}})}if(U&&!Y&&V===null&&!(V===null&&B!==null)){let _=h5(z,F.supportedLocales,F.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 _=M(c).detectLocale(new C($,{},"view",G));if(V===null&&_!==F.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 O=[],L=[],H=null,T={},K=null,I=!1,b=!1,S=[],R,w=!1,N=!1;try{let _=t3(this.flatViewRoutes,G);if(V&&_?.route.middleware.includes(ZB))_=null;if(_){if(w=!0,H=_.routePath,T=_.params,O=_.route.exec,L=_.route.middleware,S=_.route.features,I=L.includes("no-stream"),b=L.includes(QH),R=_.route.static,N=_.route.segments.at(-1)?.viewPath==="FILE",W&&this.partialRendering){let k=$.headers.get(H5),M0=TQ({flatViewRoutes:this.flatViewRoutes,supportedLocales:M(c).supportedLocales,from:k,origin:J.origin,to:{segments:_.route.segments,params:T,search:J.search}});if(M0.startIndex>0)O=O.slice(M0.startIndex),K={from:k,carriedViews:M0.carriedViews}}}}catch(_){throw _}if(R&&W)return new Response("Not found",{status:404});let g=new C($,T,"view",H);return this.hooks.onRequestStart(g),await P.run(g,async()=>{let _=null,k=P.getStore(),M0=Z3.getStore(),z3=(v)=>Z3.run(M0,()=>P.runWith(k,v));k.serverQueries=new eZ(r3($));let s1=new Set;k.serverQueries.onQueryFail((v)=>{s1.add(v.error);try{z3(()=>Promise.resolve(this.hooks.onRequestFail(i,v.error)).catch(()=>{}))}catch{}});let A1=v5(N?{}:R??(H===null&&!W?this.notFound?.static:void 0));if(V){let v=V.replaceAll("/","");x$.setLocale(v,{cookie:A1.locale})}else if(F.isLocaleAware&&!U)k.setLocale(F.defaultLocale);else x$.setLocale(void 0,{cookie:A1.locale});let i=k.req;if(A1.session)Y8();try{let v=null;if(this.detectLocale&&!U&&M(c).isLocaleAware){let{supportedLocales:A,defaultLocale:e}=M(c),t1=await this.detectLocale(i,{supportedLocales:A,defaultLocale:e}),Y6=typeof t1==="string"?h5(t1,A,e):null;if(Y6)k.setLocale(Y6)}try{await M($$).runMiddleware(L)}catch(A){if(v=this.viewRefusalStatus(i,A,s1),v===null)throw A}if(v!==null||S.length>0&&!await this.passesFeatureGates(S))H=null,O=[],i.routePath="";let t=M(c),S1=t.isEnabled,X3=t.isLocaleAware,QZ=new C($,i.params),r0={defaultLocale:t.defaultLocale,timeZone:t.detectTimeZone(QZ)};if(X3){let A=null;if(V)A=V.replaceAll("/",""),k.setLocale(A);else if(!U)A=k.locale??t.defaultLocale;else A=t.detectLocale(QZ),k.setLocale(A);let e=S1?t.getPageTranslations(A,i.routePath):{};r0={...r0,supportedLocales:t.supportedLocales,currentLocale:A,dictionary:{[A]:e},defaultLocale:t.defaultLocale,...U?{}:{localeRouting:"off"}}}await p5(r0.currentLocale??"");let V1;try{V1=await Promise.all(O.map((A)=>A(i)))}catch(A){if(v=this.viewRefusalStatus(i,A,s1),v===null)throw A;H=null,O=[],i.routePath="",V1=[]}let C$=void 0;if(H===null){if(C$=await this.hooks.onNotFound(i,{status:v??404}),X3&&!U&&k.locale&&k.locale!==r0.currentLocale){let A=k.locale;r0={...r0,currentLocale:A,dictionary:{[A]:S1?t.getPageTranslations(A,i.routePath):{}}},await p5(A)}}if(this.defaultMeta&&!k.metadata.hasAllDefaultFields)k.metadata.applyDefaults(typeof this.defaultMeta==="function"?await this.defaultMeta(i):this.defaultMeta);if(this.translate!==void 0)k.metadata.applyTranslateDefault(this.translate);let{cookies:n1,headers:r}=k;if(v!==null)r.set("Cache-Control","no-store");_={data:V1,cookies:n1,headers:r,user:k.user,prefetchedData:k.serverQueries.snapshotResolved(),currentPathName:H,params:i.params,urlLocaleSegment:Q,meta:k.renderMeta(),appId:M(K5).id,features:await M(j$).forClient()};let{params:P8,user:A$}=_,o1={},a1={};for(let A of V1??[]){let[e,t1]=Object.entries(A)?.[0]??[];if(!e||!t1)continue;a1[`${e}:${H}`]=t1.breadcrumb,o1[e]=t1}let BZ=H===null&&this.notFound&&!W?this.notFound.static:void 0;if(BZ&&C$)o1["404"]=C$;let S$=o1.FILE;if(S$){try{await this.onRequestEnd(i,{mintSession:!1})}catch(e){jZ.error(e?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(e)})}let A;if(S$ instanceof Response)A=z8(S$,r,n1);else{for(let e of n1)r.append("Set-Cookie",e.toString());A=await f8(S$,r)}return rQ(A,H)}if(W){r.set("Content-Type","application/x-ndjson; charset=utf-8"),r.append("Vary",H5),n1.forEach((e)=>r.append("Set-Cookie",e.toString())),g5(r,H),await this.hooks.onRequestEnd(i);let A={meta:K&&!k.metadata.touched?null:_.meta,data:{[G]:o1},breadcrumbs:a1,prefetchedData:k.serverQueries.snapshotResolved(),i18n:r0,features:_.features,is404:!H,appId:_.appId,partial:K};return new Response(xQ(A,k.serverQueries,void 0,({aborted:e})=>z3(()=>this.completeStream(i,k.serverQueries.summarize(e)))),{headers:r})}r.set("Content-Type","text/html; charset=utf-8");let p=H?R:BZ,u0=Boolean(p),G3=v5(p);if(!I&&!u0)r.append("Vary","User-Agent");if(!u0||G3.session)Y8();for(let A of n1)r.append("Set-Cookie",A.toString());if(!u0||G3.csrf){let A=Bun.CSRF.generate(process.env.SECRET);r.append("Set-Cookie",`csrf_token=${A}; HttpOnly; Secure; SameSite=Strict; Expires=${new Date(Date.now()+86400000).toUTCString()}`)}try{await this.onRequestEnd(i,{mintSession:!u0||G3.session})}catch(A){jZ.error(A?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(A)})}if(u0&&(H||!w))tQ(r,p);return g5(r,H),await this.render({req:i,runInRequestScope:z3,csrfTokenHMAC:Buffer.from(""),currentPathName:H,headers:r,i18n:r0,params:P8,pathname:J.pathname,serverQueries:k.serverQueries,userAgent:$.headers.get("user-agent"),noStream:I,noTheme:b,url:J,user:A$,viewData:o1,breadcrumbs:a1,urlLocaleSegment:Q,meta:_.meta,appId:_.appId,features:_.features,isOgRequest:Y,staticView:p,refusedStatus:v??void 0})}catch(v){if(v.kind===Z$){let t=W?OH(v.payload.viewData??v.payload.api):m5(v.payload.view);for(let S1 of k.cookies)t.headers.append("Set-Cookie",S1.toString());return t}if(!s1.has(v))this.hooks.onRequestFail(i,v);if(J$(v))return console.error(v),W?$3():m5(T5());if(v instanceof t0&&v.status===403)return W?$3():m5(T5());throw v}},Z)}}function DH($,Z){let J=$.cookies?.get(Z);return oG(J)?J:null}function u5(){let $=JSON.stringify({error:W$("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 jB extends C0{routes={"/api-routes":this.get(()=>{let $=M(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 $=M(Z6).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 LH=new Set([e1,"cookie","content-type","content-length","transfer-encoding","connection","host","user-agent","forwarded"]),HH=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,MH=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/;function KH($,Z,J,W){for(let[Y,j]of Object.entries(J.headers??{})){if(j===void 0||j===null)continue;let z=Y.toLowerCase();if(LH.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===e1)throw Error(`dispatchAs: credentials may not set the "${e1}" cookie. The access token stays the initiator's.`);if(!HH.test(Y)||!MH.test(j))throw Error(`dispatchAs: "${Y}" is not a cookie a Cookie header can carry.`);Z.push(`${Y}=${j}`)}}function TH($,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 JB($){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 z8($,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 PH(){return Bun.env.NODE_ENV==="development"}class X8{static token="router.api";flatRoutes={};onRequestStart;onRequestEnd;onRequestFail;constructor($){let Z=lG();this.onRequestStart=$.onRequestStart??Z.onRequestStart,this.onRequestEnd=$.onRequestEnd??Z.onRequestEnd,this.onRequestFail=$.onRequestFail??Z.onRequestFail,this.flatRoutes=rW({"/":$.rootRouter,"/auth":iW,"/__gemi__/services/i18n":sW,"/__gemi__/services/image":aW,...PH()?{"/__gemi__/services/logs":tW,"/__gemi__/debug":jB}:{}})}getRouteHandlerAndParams($){let Z=new URL($.url),J=YB(Z.pathname),W={},Y;for(let[j]of Object.entries(this.flatRoutes))try{let z=new URLPattern({pathname:j});if(z.test({pathname:J})){Y=j,W=z.exec({pathname:J})?.pathname.groups;break}}catch(z){console.error(z)}return{params:W,path:Y}}async runRouteMiddleware($,Z){let W=this.flatRoutes[$][Z.rawRequest.method].middleware;try{await M($$).runMiddleware(W)}catch(Y){if(Y.kind===Z$)return JB(Y.payload.api);else{if(b$(Y))return u5();if(this.onRequestFail(Z,Y),console.error(Y),J$(Y))return $3();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===Z$)return JB(j.payload.api);if(b$(j))return u5();if(this.onRequestFail(J.req,j),console.error(j),J$(j))return $3();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){jZ.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||!Y[$.method])return new Response(JSON.stringify({error:W$("not_found","Not found",404)}),{status:404});let j=new C($,J,"api",W);if(!this.isFrameworkRoute(W))this.onRequestStart(j);return await P.run(j,async()=>{let z=P.getStore(),X=!1,G=async()=>{X=!0,await this.endRequest(z,j,W)};try{let Q=M(c);if(Q.isEnabled){let O=Q.detectLocale(j);z.setLocale(O)}z.setRequest(j),M($$).applyDefaultBodyLimit($);let V=await this.runRouteMiddleware(W,j);if(V instanceof Response){let O=z8(V,z.headers,z.cookies);return await G(),O}let F=await this.getRouteData(W),B=z.headers,U=z.cookies;if(F instanceof Response){let O=z8(F,B,U);if(this.isOpenEndedBody($,O)){let L=TH(O,()=>this.endRequest(z,j,W));return X=!0,L}return await G(),O}let D=(r1(F)?F:F1.json(F)).toResponse(B,U);return await G(),D}catch(Q){if(!X)try{await G()}catch(V){console.error(V)}throw Q}},Z)}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,V=[],F=G?null:$.cookies.get(e1);if(F)V.push(`${e1}=${F}`);if(Y?.credentials)KH(Q,V,Y.credentials,G!==void 0);if(V.length>0)Q.set("Cookie",V.join("; "));let B=G?null:$.headers.get(e1);if(B)Q.set(e1,B);let U=$.headers.get("User-Agent");if(U)Q.set("User-Agent",U);let D;if(W instanceof FormData)D=W;else if(W!==void 0)Q.set("Content-Type","application/json"),D=JSON.stringify(W);let O=new Request(z,{method:Z,headers:Q,body:D,...Y?.signal?{signal:Y.signal}:{}});if(WB(O,LZ($),G?.grant,Y?.progress),$.domain)J3(O,$.domain);let L=G?{user:G.user}:void 0;return P.exit(()=>F6.exit(()=>this.handleApiRequest(O,L)))}}import{timingSafeEqual as NH}from"crypto";var B8="",s5="*",_H=60000,IH=1e4,G8=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,Q8=16,l5=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,i5="x-forwarded-host";function XB($){return $.startsWith(":")}function J6($,Z){if($===null)return!1;let J=Buffer.from($,"utf8"),W=Buffer.from(Z,"utf8");return J.length===W.length&&NH(J,W)}function xH($){if(!$)return[];if($===!0)return[{header:i5,clientIpHeader:null,secret:null}];let Z=Array.isArray($)?$:[$],J=Array.isArray($)?null:i5;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 CH($){if(!$||$===!0)return;if(!Array.isArray($)){zB($,"route.domains.trustProxy",i5);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.`);zB(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 zB($,Z,J){let{hostHeader:W,clientIpHeader:Y,secret:j}=$;if(W!==void 0&&(typeof W!=="string"||!l5.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"||!l5.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"||!l5.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 I1($){if(!$)return null;try{return new URL(`http://${$.trim()}`).hostname.toLowerCase().replace(/\.$/,"")||null}catch{return null}}function AH($){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 SH($){let Z=I1($.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.`);CH($.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),XB(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 n5{root;devHosts;hostTrusts;fixed=new Map;param=null;custom;cacheTtlMs;cache=new Map;inFlight=new Map;askSecret;proxySecretHeaders;constructor($){SH($),this.root=I1($.root),this.devHosts=GB($.devHosts),this.hostTrusts=xH($.trustProxy);for(let Z of $.groups??[])if(XB(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??_H,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||J6($.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:k$(J)}applyClientIp($){let Z=this.trustedClientIp($);if(!Z)return;$.headers.set("x-forwarded-for",Z),$.headers.delete("x-real-ip")}hostOf($){return I1(this.forwardedHost($))??I1(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&&I1(Y)?AH(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:s5,params:{},custom:!0};return null}async allows($,Z){let J=I1($);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>=IH)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=I1($);if(Z)this.cache.delete(Z)}}}var EH={kind:"none"};function FA($){let Z=($??"").trim().toLowerCase();if(Z===""||Z==="false"||Z==="off"||Z==="0")return EH;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 UA($,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:k$(z))??Z}if(W)$.set("x-forwarded-for",W);else $.delete("x-forwarded-for")}var QB=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,BB=16;function OA($){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(!QB.test(Z))throw Error(`GEMI_CLIENT_IP_HEADER must be a single header name, e.g. "x-azure-clientip". Got ${JSON.stringify(Z)}.`);if(!QB.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<BB)throw Error(`GEMI_PROXY_SECRET must be at least ${BB} characters. A guessable one lets any client name its own address.`);return{header:Z.toLowerCase(),secretHeader:J.toLowerCase(),secret:W}}function VB($,Z){if(!J6($.get(Z.secretHeader),Z.secret))return null;let J=$.get(Z.header)?.split(",")[0];return J===void 0?null:k$(J)}var bH="/__gemi__/domains/ask";class B1{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 n5(J);let W=(Y)=>({api:Y.api?new X8({...Z.api,...Y.api}):$.api,view:Y.view?new Z6({...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(s5,W(J.custom.fallback));this.staticFilesVary=this.viewDispatchers().some((Y)=>Y.publicFiles!==$.view.publicFiles||Y.assetRoutes!==$.view.assetRoutes)}async staticFiles($){let Z=(this.staticFilesVary?await this.route($):null)?.view??this.dispatchers(null).view;return{publicFiles:Z.publicFiles,assetRoutes:Z.assetRoutes}}applyClientIp($){let Z=this.clientIpTrust;if(Z)o5($,Z.secretHeader);let J=this.resolver?.trustedClientIp($)??(Z?VB($.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)o5($,J);let Z=W8($)??await this.resolver.resolve($);if(!Z)return null;return J3($,Z),this.dispatchers(Z)}async ask($){if(!this.resolver?.askSecret||$.method!=="GET")return null;let Z=new URL($.url);if(Z.pathname!==bH)return null;if(!J6(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 Y3($){let Z=new Date($??0).getTime();return Number.isFinite(Z)?Z:0}var FB=600000;function UB($,Z){return[N6($,Z),N6($,Z-1)]}class E{static token="auth";config;provider;constructor($={},Z=new F7){c9($.oauthProviders),this.config={...N1(d9($),$),emailCode:z7($.emailCode),passwordLimits:j7($.passwordLimits)},this.provider=Z}async oauthProvider($){return await PZ(this.config.oauthProviders,$)}async oauthProviderNames(){return await YY(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=M().bound(B1)?M(B1).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"?M(B1).resolver?.root:I1(Z);if(!J)throw Error('`auth.cookieDomain` is "root", but `route.domains` is not configured.');let W=$.domain?.host??I1(new URL($.rawRequest.url).host);return W===J||W?.endsWith(`.${J}`)?J:void 0}async getSession($,Z){if(!$)return null;if(!t8($))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=Y3(J.expiresAt),j=Y3(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/FB),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=N6($,j),V=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:V,userAgent:Z,...this.freshLifetime(Y)}),!0}))z=Q}if(!z){for(let Q of UB($,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(t8($)||!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()/FB),W=UB($,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 C;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 C,J=$.id??(await this.userProvider.findUserByEmailAddress($.email,!1))?.id;if(!J)throw new R$;let W=Bun.env.NODE_ENV==="development"?"local":Z.headers.get("User-Agent"),Y=R9(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:g9(Z),G=_6("link",$,j),Q=_6("pin",$,X);if(J===1)await this.userProvider.deleteMagicLinkToken($);else{let V=Math.max(W,Y)*60000,B=(await this.userProvider.listMagicLinkTokensByEmail($,J-1)).filter((U)=>Y3(U.createdAt)+V>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)=>Y3(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 h9(Q.id,Y3(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(Y3(W.createdAt)+this.config.emailCode.linkExpiresInMinutes*60000<=Date.now())return!1;return await this.claimOneTimeCode($,W.id)}}class q0 extends m{static getFacadeAccessor(){return E}static async user(){let $=await q0.userOrNull();if($)return $;throw new R$({redirectTo:O6(P.getStore()?.req,this.getFacadeRoot().config.signInPath)})}static async userOrNull(){let $=P.getStore();if($?.user)return $.user;let Z=await Q6(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 HZ}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($)}}class V8{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 eZ(r3(J.req.rawRequest)),J.serverQueries.ensure($,Z,"prefetch")}static async instant($,...Z){let J=V8.ensure($,Z[0]);if(await J.promise,J.status==="rejected")throw J.error;return J.data}static prefetch($,...Z){V8.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 eZ(r3($.req.rawRequest)),$.serverQueries.muteDiscoveryHints()}}function RH($){return(Array.isArray($)?$:String($).split("/")).map((J)=>encodeURIComponent(String(J))).join("/")}function a5($,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==="*"?RH(z):encodeURIComponent(String(z))}`});return`${F8}${J==="/"?"":J}`||F8}var OB=new Map;function DB($,Z){let J=OB.get($);if(!J)J=new URLPattern({pathname:`${F8}${$==="/"?"":$}`}),OB.set($,J);let W;try{W=new URL(Z,"http://localhost").pathname}catch{return null}let Y=J.exec({pathname:W})?.pathname.groups;if(!Y)return null;let j={};for(let[z,X]of Object.entries(Y)){if(X===void 0)continue;try{j[z]=decodeURIComponent(X)}catch{return null}}return 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=kH(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 kH($){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 HB{static origin($){return t5($)}static absolute($,...Z){return`${ZZ()}${O0(String($),Z[0]??{})}`}static relative($,...Z){return O0(String($),Z[0]??{})}static forDomain($,Z,...J){let W=M(B1).resolver;if(!W)throw Error("`Url.forDomain` needs `route.domains` to be configured.");let Y=P.getStore()?.req?.rawRequest,j=Y?W.publicOrigin(Y):ZZ();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},$,O0(String(Z),J[0]??{}))}static api($,...Z){return a5(String($),Z[0]??{})}static apiAbsolute($,...Z){return`${t5()}${a5(String($),Z[0]??{})}`}static matchApi($,Z){return DB(String($),Z)}}class MB{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 wH={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 i1 extends m{static getFacadeAccessor(){return zZ}static get client(){return this.getFacadeRoot().client}static get($){return i1.client.get($)}static set($,Z){return i1.client.set($,Z)}static del(...$){return i1.client.del(...$)}static exists($){return i1.client.exists($)}static incr($){return i1.client.incr($)}static expire($,Z){return i1.client.expire($,Z)}static ttl($){return i1.client.ttl($)}}function VS($){return $}function KB(){return{store:"memory",ttl:null}}class r5{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 fH="500";class e5{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=`${qH(this.prefix)}*`,J="0";do{let W=await $.send("SCAN",[J,"MATCH",Z,"COUNT",fH]),[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 $=M(),Z=$.bound(zZ)?$.make(zZ).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 qH($){return $.replace(/[*?[\]\\^-]/g,(Z)=>`\\${Z}`)}var vH="k:",TB="tag:",gH="t:";class $2{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 Z2 extends $2{options;static token="cache";config;builtStore;inflight=new Map;constructor($={},Z={}){super();this.options=Z;if(this.config=N1(KB(),$),this.config.ttl!==null&&this.config.ttl!==void 0)XZ(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 NB(this,Z)}async flush(){await this.store.flush()}async storeKey($){return vH+_B($)}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=TB+Z,W=await this.store.get(J);if(W!==null)return W;let Y=PB();return await this.store.set(J,Y,null),Y}))}async flushTags($){await Promise.all($.map((Z)=>this.store.set(TB+Z,PB(),null)))}ttlMs($){let Z=$===void 0?this.config.ttl:$;return Z===null||Z===void 0?null:XZ(Z)}buildStore(){let{store:$}=this.config;if($===void 0||$==="memory")return new r5(this.config.memory);if($==="redis"){let Z=this.options.application;return new e5({...this.config.redis,client:Z?{send:(J,W)=>Z.make(zZ).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 NB extends $2{manager;tagNames;constructor($,Z){super();this.manager=$;this.tagNames=Z}async flush(){await this.manager.flushTags([...this.tagNames])}async storeKey($){_B($);let Z=await this.manager.tagVersions([...this.tagNames]);return`${gH}${Z.join(",")}:${$}`}}function _B($){if(typeof $!=="string"||$==="")throw TypeError(`A cache key is a non-empty string; got ${JSON.stringify($)}.`);return $}function PB(){let $=new Uint8Array(9);return crypto.getRandomValues($),Array.from($,(Z)=>Z.toString(16).padStart(2,"0")).join("")}class IB extends m{static getFacadeAccessor(){return Z2}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 xB extends m{static getFacadeAccessor(){return O1}static consume($,Z={}){return this.getFacadeRoot().consume($,Z)}static enforce($,Z={},J){return this.getFacadeRoot().enforce($,Z,J)}}class AB extends m{static getFacadeAccessor(){return CB}static run($,Z,J){return this.getFacadeRoot().run($,Z,J)}static acquire($,Z={}){return this.getFacadeRoot().acquire($,Z)}}class EB extends m{static getFacadeAccessor(){return SB}static encrypt($){return this.getFacadeRoot().encrypt($)}static decrypt($){return this.getFacadeRoot().decrypt($)}static needsReencryption($){return this.getFacadeRoot().needsReencryption($)}}class bB extends m{static getFacadeAccessor(){return a3}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()}}function mS($){return $}function RB(){return{driver:"memory",pollInterval:30000,maxSubscriptions:1e4,batchSize:100,keepaliveInterval:5000}}function U8($){let Z=new URLSearchParams;for(let[J,W]of $)Z.append(J,String(W));return Z.toString()}function J2($){let Z=new Map;if(!$)return Z;let J;try{J=new URLSearchParams($)}catch{return Z}for(let[W,Y]of J){let j=Number(Y);if(Y!==""&&Number.isSafeInteger(j)&&j>=0)Z.set(W,j)}return Z}var{SQL:yH}=globalThis.Bun;function mH(){return Bun.semver.satisfies(Bun.version,">=1.4.0")}var hH=async($)=>{let Z=new yH($,{max:1,idleTimeout:0,maxLifetime:0});return{listen:(J,W,Y)=>Z.listen(J,W,Y),close:()=>Z.close({timeout:1})}},pH=async($)=>{let Z;try{Z=(await import("./chunk-fbxnxze2.js")).default}catch(W){throw Error("The change feed's database driver needs a Postgres client that can LISTEN: Bun 1.4 or later, or the `postgres` package (bun add postgres).",{cause:W})}let J=Z($,{max:1,idle_timeout:0,max_lifetime:null,fetch_types:!1,onnotice:()=>{}});return{listen:(W,Y,j)=>J.listen(W,Y,j),close:()=>J.end({timeout:1}).catch(()=>{})}},kB=($)=>mH()?hH($):pH($);var cH=/^[A-Za-z_][A-Za-z0-9_]*$/;class W2{headsTable;entriesTable;notifyChannel;sql;dialect;connection;url;retain;listener;sqliteTurn=Promise.resolve();constructor($,Z={}){if($.dialect!=="postgres"&&$.dialect!=="sqlite")throw Error(`The change feed's database driver supports Postgres and SQLite, not ${$.dialect}.`);let J=Z.headsTable??"gemi_change_heads",W=Z.entriesTable??"gemi_changes",Y=Z.notifyChannel??"gemi_changes";for(let z of[J,W,Y])if(!cH.test(z))throw Error(`"${z}" is not a plain identifier. Use letters, digits and underscores.`);let j=Z.retain??1000;if(!Number.isInteger(j)||j<1)throw Error(`The change feed's retain must be a whole number, 1 or more; got ${j}.`);this.headsTable=J,this.entriesTable=W,this.notifyChannel=Y,this.sql=$.sql,this.dialect=$.dialect,this.connection=$.name,this.url=$.url,this.retain=j,this.listener=Z.listener??kB}async createTable(){for(let $ of dH(this.headsTable,this.entriesTable))await this.sql.unsafe($)}joinsTransaction(){return this.transaction()!==void 0}publish($,Z){let J=this.transaction();if(!J){let Y=()=>this.sql.begin((z)=>this.append(z,$,Z));if(this.dialect!=="sqlite")return Y();let j=this.sqliteTurn.then(Y);return this.sqliteTurn=j.catch(()=>{}),j}let W=this.append(J,$,Z);return wB(W),W}async append($,Z,J){let W=$.unsafe(`"${this.headsTable}"`),Y=$.unsafe(`"${this.entriesTable}"`),[j]=await $`
|
|
24
24
|
INSERT INTO ${W} (channel, seq) VALUES (${Z}, 1)
|
|
25
25
|
ON CONFLICT (channel) DO UPDATE SET seq = ${W}.seq + 1
|
|
26
26
|
RETURNING seq
|
|
@@ -112,6 +112,6 @@ data: ${JSON.stringify(Z)}
|
|
|
112
112
|
"updated_at" BIGINT NOT NULL,
|
|
113
113
|
"finished_at" BIGINT,
|
|
114
114
|
"deadline_at" BIGINT${W}
|
|
115
|
-
)`,`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 nB=191,oB=30000;class M8 extends Error{id;constructor($){super(`No run has the id ${$}.`);this.id=$;this.name="RunNotFoundError"}}class K8 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 L2{options;static token="runs";store;config;ownFeed=null;constructor($={},Z={}){this.options=Z;this.config=N1(lB(),$),this.store=tH(this.config.store,Z.application)}get feed(){if(this.options.feed)return this.options.feed;if(this.options.application)return this.options.application.make(j3);return this.ownFeed??=new j3,this.ownFeed}channel($){return`gemi:run:${$}`}async create($){rB("kind",$.kind);let Z=$.id??`run_${crypto.randomUUID().replaceAll("-","")}`;rB("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:XZ($.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 aH(Z),this.change($,x1,{status:"running",progress:Z})}complete($,Z){return this.change($,x1,{status:"completed",result:Z===void 0?null:Z})}fail($,Z){return this.change($,x1,{status:"failed",error:tB(Z)})}cancel($,Z){return this.change($,x1,{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 M8($);if(C1(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 K8)&&!Y.signal.aborted)console.error(`[gemi] Run ${$} failed.`,G);X=await this.change($,x1,{status:"failed",error:G instanceof K8?tB(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()+XZ(Z.timeout),Y=this.feed.subscribe(this.channel($),{signal:J});try{await Y.ready();let j=await this.store.get($);if(!j)throw new M8($);let z=null;for(;;){if(C1(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 aB(z,Math.min(G,X??1/0,oB),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 M8($);if(yield W,C1(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,C1(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=XZ($);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||C1(Z.status))return null;let J=await this.untilDeadline(Z);if(J===null||J>0)return null;return this.change($,x1,{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(C1(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,aB(j,Math.min(z??1/0,oB))]);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 aB($,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 tB($){if(typeof $==="string")return{message:$};if($ instanceof K8)return{message:$.message,...$.code!==void 0?{code:$.code}:{},...$.data!==void 0?{data:$.data}:{}};if($ instanceof Error)return{message:$.message};return $}function rB($,Z){if(typeof Z!=="string"||Z===""||Z.length>nB)throw TypeError(`A run's ${$} is a string of 1 to ${nB} characters; got ${JSON.stringify(Z)}.`)}function aH($){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 tH($,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(f1).connection();return new D2(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 eB extends m{static getFacadeAccessor(){return L2}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 $V extends m{static getFacadeAccessor(){return j$}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 K2{value;constructor($){this.value=$}}var rH=/^[A-Za-z_][A-Za-z0-9_$]*$/;function eH($){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"||!rH.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??w1()}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 M2(J.sql,(W)=>H2(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=eH(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(s0()!==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 M2(z.sql,async(X)=>{for(let Q of Y)await X.unsafe(Q);let G=await H2(j,()=>W(X));throw new K2(G)},{slowTransactionThreshold:z.config.slowTransactionThreshold,connection:j})}catch(X){if(X instanceof K2)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-tmz3gf96.js");return Z(this.handle()??$.sql,$.dialect)}run($,Z){let J=this.connection(),{text:W,values:Y}=WV($,JV(J.dialect),Z);return(this.handle()??J.sql).unsafe(W,Y)}handle(){let $=s0();if($===void 0)return;return w1()===this.name?$:void 0}connection($=this.name){return ZV($),M(f1).connection($)}}var GZ=new T8;class YV extends m{static getFacadeAccessor(){return f1}static connection($){return new T8($)}static get sql(){return GZ.sql}static get dialect(){return GZ.dialect}static query($){return GZ.query($)}static execute($){return GZ.execute($)}static transaction($){return GZ.transaction($)}static readOnly($,Z){return GZ.readOnly($,Z)}static schema(){return GZ.schema()}static close(){return this.getFacadeRoot().close()}}export{F1 as oe,VV as pe,e0 as qe,Q3 as re,x8 as se,FZ as te,V3 as ue,C0 as ve,Q6 as we,a8 as xe,t8 as ye,R9 as ze,Y$ as Ae,O1 as Be,k$ as Ce,J0 as De,Q9 as Ee,LZ as Fe,k9 as Ge,w9 as He,e8 as Ie,$7 as Je,_6 as Ke,TZ as Le,CF as Me,MP as Ne,d9 as Oe,a9 as Pe,G7 as Qe,t9 as Re,r9 as Se,fF as Te,e9 as Ue,Q7 as Ve,gF as We,yF as Xe,B7 as Ye,$Y as Ze,ZY as _e,j$ as $e,JY as af,cF as bf,F7 as cf,g8 as df,D6 as ef,E1 as ff,f8 as gf,b1 as hf,x$ as if,V8 as jf,HB as kf,MB as lf,wH as mf,i1 as nf,VS as of,KB as pf,r5 as qf,e5 as rf,Z2 as sf,NB as tf,IB as uf,xB as vf,AB as wf,EB as xf,bB as yf,mS as zf,RB as Af,U8 as Bf,J2 as Cf,W2 as Df,Y2 as Ef,O8 as Ff,j3 as Gf,cB as Hf,dB as If,u as Jf,F3 as Kf,h4 as Lf,WN as Mf,YN as Nf,jN as Of,QN as Pf,QG as Qf,yW as Rf,FG as Sf,ON as Tf,DG as Uf,c0 as Vf,i3 as Wf,LG as Xf,uB as Yf,ME as Zf,B2 as _f,x1 as $f,C1 as ag,V2 as bg,D2 as cg,nH as dg,M8 as eg,K8 as fg,L2 as gg,eB as hg,$V as ig,T8 as jg,YV as kg,hW as lg,mD as mg,nW as ng,oW as og,C_ as pg,mG as qg,dG as rg,B6 as sg,$$ as tg,p_ as ug,lG as vg,iG as wg,K5 as xg,$3 as yg,T5 as zg,wx as Ag,px as Bg,cx as Cg,zH as Dg,g5 as Eg,d5 as Fg,VH as Gg,m5 as Hg,OH as Ig,Z6 as Jg,u5 as Kg,JB as Lg,z8 as Mg,X8 as Ng,FA as Og,UA as Pg,OA as Qg,B1 as Rg,E as Sg,q0 as Tg,V6 as Ug,l2 as Vg,CV as Wg,c2 as Xg,s2 as Yg,R8 as Zg,U6 as _g,k8 as $g,n2 as ah,wV as bh,fV as ch,$9 as dh,J9 as eh,Y9 as fh,V9 as gh,F9 as hh,U9 as ih,p8 as jh,hV as kh,z0 as lh,I9 as mh,MZ as nh,E9 as oh};
|
|
115
|
+
)`,`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 nB=191,oB=30000;class M8 extends Error{id;constructor($){super(`No run has the id ${$}.`);this.id=$;this.name="RunNotFoundError"}}class K8 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 L2{options;static token="runs";store;config;ownFeed=null;constructor($={},Z={}){this.options=Z;this.config=N1(lB(),$),this.store=tH(this.config.store,Z.application)}get feed(){if(this.options.feed)return this.options.feed;if(this.options.application)return this.options.application.make(j3);return this.ownFeed??=new j3,this.ownFeed}channel($){return`gemi:run:${$}`}async create($){rB("kind",$.kind);let Z=$.id??`run_${crypto.randomUUID().replaceAll("-","")}`;rB("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:XZ($.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 aH(Z),this.change($,x1,{status:"running",progress:Z})}complete($,Z){return this.change($,x1,{status:"completed",result:Z===void 0?null:Z})}fail($,Z){return this.change($,x1,{status:"failed",error:tB(Z)})}cancel($,Z){return this.change($,x1,{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 M8($);if(C1(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 K8)&&!Y.signal.aborted)console.error(`[gemi] Run ${$} failed.`,G);X=await this.change($,x1,{status:"failed",error:G instanceof K8?tB(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()+XZ(Z.timeout),Y=this.feed.subscribe(this.channel($),{signal:J});try{await Y.ready();let j=await this.store.get($);if(!j)throw new M8($);let z=null;for(;;){if(C1(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 aB(z,Math.min(G,X??1/0,oB),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 M8($);if(yield W,C1(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,C1(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=XZ($);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||C1(Z.status))return null;let J=await this.untilDeadline(Z);if(J===null||J>0)return null;return this.change($,x1,{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(C1(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,aB(j,Math.min(z??1/0,oB))]);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 aB($,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 tB($){if(typeof $==="string")return{message:$};if($ instanceof K8)return{message:$.message,...$.code!==void 0?{code:$.code}:{},...$.data!==void 0?{data:$.data}:{}};if($ instanceof Error)return{message:$.message};return $}function rB($,Z){if(typeof Z!=="string"||Z===""||Z.length>nB)throw TypeError(`A run's ${$} is a string of 1 to ${nB} characters; got ${JSON.stringify(Z)}.`)}function aH($){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 tH($,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(f1).connection();return new D2(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 eB extends m{static getFacadeAccessor(){return L2}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 $V extends m{static getFacadeAccessor(){return j$}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 K2{value;constructor($){this.value=$}}var rH=/^[A-Za-z_][A-Za-z0-9_$]*$/;function eH($){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"||!rH.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??w1()}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 M2(J.sql,(W)=>H2(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=eH(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(s0()!==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 M2(z.sql,async(X)=>{for(let Q of Y)await X.unsafe(Q);let G=await H2(j,()=>W(X));throw new K2(G)},{slowTransactionThreshold:z.config.slowTransactionThreshold,connection:j})}catch(X){if(X instanceof K2)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-k8gn0q91.js");return Z(this.handle()??$.sql,$.dialect)}run($,Z){let J=this.connection(),{text:W,values:Y}=WV($,JV(J.dialect),Z);return(this.handle()??J.sql).unsafe(W,Y)}handle(){let $=s0();if($===void 0)return;return w1()===this.name?$:void 0}connection($=this.name){return ZV($),M(f1).connection($)}}var GZ=new T8;class YV extends m{static getFacadeAccessor(){return f1}static connection($){return new T8($)}static get sql(){return GZ.sql}static get dialect(){return GZ.dialect}static query($){return GZ.query($)}static execute($){return GZ.execute($)}static transaction($){return GZ.transaction($)}static readOnly($,Z){return GZ.readOnly($,Z)}static schema(){return GZ.schema()}static close(){return this.getFacadeRoot().close()}}export{F1 as oe,VV as pe,e0 as qe,Q3 as re,x8 as se,FZ as te,V3 as ue,C0 as ve,Q6 as we,a8 as xe,t8 as ye,R9 as ze,Y$ as Ae,O1 as Be,k$ as Ce,J0 as De,Q9 as Ee,LZ as Fe,k9 as Ge,w9 as He,e8 as Ie,$7 as Je,_6 as Ke,TZ as Le,CF as Me,MP as Ne,d9 as Oe,a9 as Pe,G7 as Qe,t9 as Re,r9 as Se,fF as Te,e9 as Ue,Q7 as Ve,gF as We,yF as Xe,B7 as Ye,$Y as Ze,ZY as _e,j$ as $e,JY as af,cF as bf,F7 as cf,g8 as df,D6 as ef,E1 as ff,f8 as gf,b1 as hf,x$ as if,V8 as jf,HB as kf,MB as lf,wH as mf,i1 as nf,VS as of,KB as pf,r5 as qf,e5 as rf,Z2 as sf,NB as tf,IB as uf,xB as vf,AB as wf,EB as xf,bB as yf,mS as zf,RB as Af,U8 as Bf,J2 as Cf,W2 as Df,Y2 as Ef,O8 as Ff,j3 as Gf,cB as Hf,dB as If,u as Jf,F3 as Kf,h4 as Lf,WN as Mf,YN as Nf,jN as Of,QN as Pf,QG as Qf,yW as Rf,FG as Sf,ON as Tf,DG as Uf,c0 as Vf,i3 as Wf,LG as Xf,uB as Yf,ME as Zf,B2 as _f,x1 as $f,C1 as ag,V2 as bg,D2 as cg,nH as dg,M8 as eg,K8 as fg,L2 as gg,eB as hg,$V as ig,T8 as jg,YV as kg,hW as lg,mD as mg,nW as ng,oW as og,C_ as pg,mG as qg,dG as rg,B6 as sg,$$ as tg,p_ as ug,lG as vg,iG as wg,K5 as xg,$3 as yg,T5 as zg,wx as Ag,px as Bg,cx as Cg,zH as Dg,g5 as Eg,d5 as Fg,VH as Gg,m5 as Hg,OH as Ig,Z6 as Jg,u5 as Kg,JB as Lg,z8 as Mg,X8 as Ng,FA as Og,UA as Pg,OA as Qg,B1 as Rg,E as Sg,q0 as Tg,V6 as Ug,l2 as Vg,CV as Wg,c2 as Xg,s2 as Yg,R8 as Zg,U6 as _g,k8 as $g,n2 as ah,wV as bh,fV as ch,$9 as dh,J9 as eh,Y9 as fh,V9 as gh,F9 as hh,U9 as ih,p8 as jh,hV as kh,z0 as lh,I9 as mh,MZ as nh,E9 as oh};
|
|
116
116
|
|
|
117
|
-
//# debugId=
|
|
117
|
+
//# debugId=EE1EE98C33AAD21D64756E2164756E21
|